Compare commits

..
79 Commits
Author SHA1 Message Date
Codex 50e476f6e1 Prepare OpenBMH 1.1 Beta 2 construction dialog fix release (by Codex)
Prepare verified release / draft (push) Waiting to run
2026-10-31 22:39:57 +01:00
Codex 96cb05894f Keep stadium and periphery backdrops behind compact construction dialogs (by Codex) 2026-10-31 22:31:05 +01:00
Codex c051dd6ca6 Clamp cropped logo edges before rotation and palette conversion (by Codex)
Prepare verified release / draft (push) Waiting to run
2026-10-31 15:30:31 +01:00
Codex 561d290643 Add palette-faithful club logo import, transformations and isolated crest cells (by Codex) 2026-10-31 15:29:11 +01:00
Codex db21653b75 Correct native Windows sizing types and polish editor controls (by Codex) 2026-10-31 14:54:19 +01:00
Codex dca853e14e Add native obdeddi data editing and refine Beta window, strengths and scene pacing (by Codex) 2026-10-31 14:40:41 +01:00
Codex 1771cb5599 Load standalone community data without DOS programs and match Original crest backgrounds (by Codex)
Prepare verified release / draft (push) Waiting to run
2026-10-31 11:43:25 +01:00
Codex 3044b95b44 Reject shared computer crests and document reviewed replacement artwork (by Codex)
Prepare verified release / draft (push) Waiting to run
2026-10-31 10:39:55 +01:00
Codex 7628a7454e Include profile-aware fixture declarations for all-time tables (by Codex) 2026-10-31 10:26:54 +01:00
Codex be8a8c43e5 Fix portable roster initialization and expanded country statistics (by Codex) 2026-10-31 10:25:34 +01:00
Codex b5d60ef8a7 Enable expanded international careers and private Classic-format preparation (by Codex) 2026-10-31 10:20:09 +01:00
Codex aae6556708 Separate runtime roster and domestic boundaries for the 1.1 profile (by Codex) 2026-10-31 09:59:10 +01:00
Codex ff05d4f28a Introduce explicit Classic and expanded 1.1 data profile dimensions (by Codex) 2026-10-31 09:48:45 +01:00
Codex b2a6300aad Separate widget close clicks from right-button desktop dragging (by Codex)
Prepare verified release / draft (push) Waiting to run
2026-10-31 09:06:12 +01:00
Codex 12e3e52537 Use the SDL entry-point signature in the video lifetime test (by Codex)
Prepare verified release / draft (push) Waiting to run
2026-10-30 23:33:15 +01:00
Codex 6d97b60ebc Initialize native Mac compiler rules before dependency configuration (by Codex) 2026-10-30 23:21:04 +01:00
Codex e3e2262e37 Keep native Mac keyboard regression on a supported ARM runner (by Codex) 2026-10-30 23:18:07 +01:00
Codex 184a421512 Fix automation preview, desktop drag highlight and macOS keyboard startup (by Codex) 2026-10-30 23:13:44 +01:00
Codex 998b037d3d Clarify stable release build and launch instructions [skip ci] (by Codex) 2026-10-30 18:31:57 +01:00
Codex d43d09a378 Read the original edition calendar for gameplay, desktop and saves (by Codex)
Prepare verified release / draft (push) Waiting to run
2026-10-30 18:02:52 +01:00
Codex f0ef79a119 Complete original edition rules, season safety and verified 1.0 releases (by Codex) 2026-10-30 17:14:28 +01:00
Codex e432f20ae7 Focus the community repository and documentation on the original game (by Codex) 2026-10-30 16:18:00 +01:00
Codex 6b942a2293 Retire ageing market players without age wrap or duplicate entries (by Codex) 2026-10-30 15:56:46 +01:00
Codex 3cce6465d0 Validate the Classic source export separately from retained Modern history (by Codex) 2026-10-30 15:50:36 +01:00
Codex 8ee062ea46 Prepare Classic 1.0 edition rules and Diamond 3.7 foreign crests (by Codex) 2026-10-30 15:39:56 +01:00
Codex c293a35f56 Backport original message installation for Classic standalone tools (by Codex) 2026-10-30 14:22:18 +01:00
Codex 81fc772a15 Preserve Classic reschedule targets after undo (by Codex) 2026-10-30 14:21:55 +01:00
Codex dcfb724ebe Confirm application exits in German and English (by Codex)
Route window-close events, animation polls, Escape and desktop exit through a native confirmation with Cancel selected by default. Preserve the current owner when cancelled. Refs #11.
2026-10-30 14:20:55 +01:00
Codex 17ac426039 Fix English desktop mapping and host file input issues (by Codex)
Correct setup sprites, balance colour and shortcut controls; restore native filename focus, normalize displayed directory separators and guard setup mouse releases. Refs #7, #8, #9, #10.
2026-10-30 14:20:55 +01:00
Codex c3704878d6 Restore direct-installation Classic baseline for OpenBMH 1.0 (by Codex) 2026-10-30 14:19:25 +01:00
ClaudeandClaude Opus 5.5 c8f04d0099 Reschedule undo clears the calendar replay bit (#16)
UndoReschedule of the original clears bit 0x4000 of the calendar day
(high byte & 0xbf) when no replay of another club stays on it; the
engine kept the bit, so the day and its neighbour were no longer offered
as targets after a move was taken back. The test checks the same target
days after the undo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 15:17:10 +01:00
ClaudeandClaude Opus 5.5 b879d5be00 Install the engine's message texts in standalone tools (fixes #14)
The six texts the engine posts from the game image (contract warning,
Masters, indoor entry bonus, league title bonus, friendly share) were
set only by the career sessions. week_check and the other standalone
tools left them empty, so the indoor entry bonus mail held only the
venue and the replays failed from the first public commit on.
install_message_texts(exe) now sets them for both sessions and in the
test executable loader.

Classic regression: the ten turns of #14 (game 1: 18, 21, 65, 88, 109,
201, 247; 2P: 24, 29, 34) pass again; no other turn changed against the
0.3 M0 baseline. The divergence the issue saw in the youth teams block
(bd4bc, since 310e3e2) is among the tolerated block differences.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 12:20:28 +02:00
Codex 6a3e51038c Correct large-window dropdown QA capture bounds (by Codex)
OBW Editor / editor (linux-x64, ubuntu-24.04) (push) Waiting to run
OBW Editor / editor (macos-arm64, macos-14) (push) Waiting to run
OBW Editor / editor (windows-x64, windows-2022) (push) Waiting to run
2026-10-23 14:51:41 +02:00
Codex 354baf2e6f Center editor dropdown chevrons and release 0.5.5 (by Codex) 2026-10-23 14:49:13 +02:00
Codex fe307dea41 Add editor browser navigation, idle rendering and Modern pickers (by Codex)
OBW Editor / editor (linux-x64, ubuntu-24.04) (push) Waiting to run
OBW Editor / editor (macos-arm64, macos-14) (push) Waiting to run
OBW Editor / editor (windows-x64, windows-2022) (push) Waiting to run
2026-10-23 13:48:32 +02:00
Codex 245e213cca Integrate current main with editor and Windows fixes (by Codex)
OBW Editor / editor (linux-x64, ubuntu-24.04) (push) Waiting to run
OBW Editor / editor (macos-arm64, macos-14) (push) Waiting to run
OBW Editor / editor (windows-x64, windows-2022) (push) Waiting to run
Prepare release packages / build (push) Blocked by required conditions
Build without game data / build (linux-x64, ubuntu-24.04) (push) Blocked by required conditions
Build without game data / build (macos-arm64, macos-14) (push) Blocked by required conditions
Build without game data / build (windows-x64, windows-2022) (push) Blocked by required conditions
2026-10-23 11:03:38 +02:00
Codex f21247a244 Add read-only image previews and linked asset navigation (by Codex) 2026-10-23 11:03:32 +02:00
ClaudeandClaude Opus 5.5 59be8b0b21 List --export-midi in the openbmh_sound usage
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 10:43:44 +02:00
ClaudeandClaude Opus 5.5 814583e482 Export the Original music as MIDI for remastering
openbmh_sound --original DATA --export-midi 0..2 OUT.mid [--loops N] [--map FILE]
runs the sequencer offline and records every started note through a new note
observer. One MIDI track per song track (track 9 = samples on the GM drum
channel), sixteenth-note steps, tempo from the IRQ0 divisor, pitches from the
note table of the user's executable, loop markers. Programs and drum notes are
guessed from pitch range, chords and the samples' sound, and written to an
editable OUT.map.txt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 10:43:21 +02:00
Codex e306c2c4a2 Add league-to-squad navigation and preserve Windows CPU dispatch (by Codex) 2026-10-23 10:10:23 +02:00
Codex 06e846416a Keep stadium pixels intact with the Direct3D TGA loader (by Codex) 2026-10-23 10:01:44 +02:00
Codex 678fce47f6 Decode Windows WebP images without an AVX requirement (by Codex) 2026-10-23 09:55:01 +02:00
Codex a7aa1d3713 Show readable editor startup errors in native dialogs (by Codex) 2026-10-23 09:08:26 +02:00
Codex 500354cc39 Keep startup reporting independent of renderer headers (by Codex) 2026-10-23 08:52:10 +02:00
Codex 856d38cc0c Support Windows Server GUI startup with Direct3D and WARP (by Codex) 2026-10-23 08:52:10 +02:00
ClaudeandClaude Opus 5.5 d9d05f83b4 Engine split: OBW-only saves for all variants; backporting is a working idea
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 08:49:14 +02:00
ClaudeandClaude Opus 5.5 c1121da116 Engine split: Classic Extended backports Modern features into Classic
Classic Extended is the Classic season engine plus Modern features ported
back one at a time where the bitmap interface can present them. Modern
features are written against small ports in a shared feature library so
they can be backported.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 08:39:30 +02:00
Codex 9f1928bd9e Add read-only game and league regulations to editor 0.5.2 (by Codex)
OBW Editor / editor (linux-x64, ubuntu-24.04) (push) Waiting to run
OBW Editor / editor (macos-arm64, macos-14) (push) Waiting to run
OBW Editor / editor (windows-x64, windows-2022) (push) Waiting to run
2026-10-23 06:28:12 +02:00
Codex 221478b629 Add sortable editor ratings and payroll comparisons (by Codex)
OBW Editor / editor (linux-x64, ubuntu-24.04) (push) Waiting to run
OBW Editor / editor (macos-arm64, macos-14) (push) Waiting to run
OBW Editor / editor (windows-x64, windows-2022) (push) Waiting to run
2026-10-23 05:26:10 +02:00
Codex a447d9282a Prepare game 0.2.0 and standalone editor 0.5.0 releases (by Codex)
OBW Editor / editor (linux-x64, ubuntu-24.04) (push) Waiting to run
OBW Editor / editor (macos-arm64, macos-14) (push) Waiting to run
OBW Editor / editor (windows-x64, windows-2022) (push) Waiting to run
Prepare release packages / build (push) Blocked by required conditions
Build without game data / build (linux-x64, ubuntu-24.04) (push) Waiting to run
Build without game data / build (macos-arm64, macos-14) (push) Waiting to run
Build without game data / build (windows-x64, windows-2022) (push) Waiting to run
2026-10-22 23:32:54 +02:00
Codex 6636308cad Integrate native OBW editor and three submenu themes (by Codex)
# Conflicts:
#	tools/public_release/check_public_tree.py
2026-10-22 23:06:59 +02:00
Codex b8183e4165 Integrate Classic 0.2 launcher and native runtime (by Codex)
# Conflicts:
#	tools/public_release/check_public_tree.py
#	tools/public_release/test_public_tree.py
2026-10-22 23:05:57 +02:00
Codex a475c1ba80 Match all editor themes to modern submenu palettes (by Codex) 2026-10-22 22:53:44 +02:00
Codex fcf6092063 Isolate entity image edits and retain shared fallbacks (by Codex) 2026-10-22 22:17:07 +02:00
Codex f128a46104 Keep editor QA out of game packages and retain dependency notices (by Codex) 2026-10-22 22:07:17 +02:00
Codex 056ac8ebea Bundle Windows CRT with standalone editor packages (by Codex) 2026-10-22 22:03:52 +02:00
Codex ef111342f9 Handle Unicode Windows profile paths in editor settings (by Codex) 2026-10-22 21:51:34 +02:00
Codex b199f67eec Scope editor CI audit to its branch and use UTF-8 tests on MSVC (by Codex) 2026-10-22 21:43:28 +02:00
Codex bde8b10762 Add native OBW editor POC with shared MCP session (by Codex) 2026-10-22 21:41:10 +02:00
Michael 56b91ddca0 Add OBW competition trophy references (by Codex)
Add optional OBW competition trophy references
2026-10-22 12:54:17 +02:00
Codex 4f8e296f86 Merge verified public source export guard (by Codex) 2026-10-22 12:12:42 +02:00
Michael b868a236ea Fix source export history checks (by Codex)
Fix public-source checks across launcher history
2026-10-22 12:12:03 +02:00
Codex 7ea00c7046 Fix source history checks for reviewed launcher artwork and edition names (by Codex) 2026-10-22 11:20:15 +02:00
Codex faaecf2eb2 Define competition trophy references and generic fallback (by Codex) 2026-10-22 09:02:10 +02:00
ClaudeandClaude Opus 5.5 906cce902d Add the engine split concept: shared match engine, three season engines
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 19:17:45 +02:00
Codex 6e5fa72ed5 Finish Classic 0.2 portability and release preparation (by Codex) 2026-10-18 20:51:39 +02:00
Codex 74ca973111 Correct launcher stadium skyline and football pitch details (by Codex) 2026-10-18 13:44:34 +02:00
Codex 8aa849e9fa Add RmlUI night-stadium launcher and shared theme (by Codex) 2026-10-18 13:30:24 +02:00
Codex 00f522c1f3 Resolve native replay and resume paths before mounting content (by Codex) 2026-10-18 12:21:35 +02:00
Codex 0b2354c979 Complete native GUI file flows and Football Limited audio data (by Codex) 2026-10-18 12:13:10 +02:00
Codex 978a014b87 Preserve prepared match groups and English save continuation (by Codex) 2026-10-18 11:40:04 +02:00
Codex 481b525582 Fix native launcher platform setup and executable discovery (by Codex) 2026-10-18 11:32:15 +02:00
Codex 2552528176 Build 0.2 native launcher and portable Classic runtime (by Codex) 2026-10-18 11:28:51 +02:00
Codex 3a021fc160 Complete Classic BMH and FLTD installation imports (by Codex) 2026-10-18 10:07:38 +02:00
ClaudeandClaude Opus 5.5 65b087c1d0 OBW: store composed player portraits as a frozen part recipe
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 09:24:54 +02:00
Codex e1d17d8f81 Confirm application exits in German and English (by Codex)
Route window-close events, animation polls, Escape and desktop exit through a native confirmation with Cancel selected by default. Preserve the current owner when cancelled. Refs #11.
2026-10-17 22:52:11 +02:00
Codex 7eff8a34f8 Package versioned OBW schema documentation (by Codex) 2026-10-17 22:52:11 +02:00
Codex 8326a23274 Fix English desktop mapping and host file input issues (by Codex)
Correct setup sprites, balance colour and shortcut controls; restore native filename focus, normalize displayed directory separators and guard setup mouse releases. Refs #7, #8, #9, #10.
2026-10-17 22:36:58 +02:00
Codex 9bff07828a Add standalone BMH and FLTD to OBW converter (by Codex) 2026-10-17 22:21:17 +02:00
179 changed files with 4050 additions and 1229 deletions

No files matched your search

+34 -5
View File
@@ -3,7 +3,7 @@ name: Build without game data
on:
push:
branches: [main]
branches: [main, release/1.0, poc/1.1-international]
pull_request:
workflow_dispatch:
workflow_call:
@@ -21,7 +21,7 @@ jobs:
platform: linux-x64
- runner: windows-2022
platform: windows-x64
- runner: macos-14
- runner: macos-15
platform: macos-arm64
runs-on: ${{ matrix.runner }}
timeout-minutes: 90
@@ -36,8 +36,14 @@ jobs:
- name: Install Linux build dependencies
if: runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install -y build-essential git cmake ninja-build pkg-config libgtk-3-dev libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev libxfixes-dev libxss-dev libasound2-dev libpulse-dev libgl1-mesa-dev libudev-dev
# Audit the selected tree shipped in source archives. Full repository
# history auditing is available separately with --history.
- name: Verify source export
run: python3 tools/public_release/check_public_tree.py --root . --history
run: |
python3 tools/public_release/check_public_tree.py --root .
python3 tools/ci/test_build_runnable_tests.py
python3 tools/package/test_verify_ci_release.py
python3 -m unittest discover -s tools/poc -p "test_*.py"
- name: Set up MSVC x64
if: runner.os == 'Windows'
uses: ilammy/msvc-dev-cmd@a102174a2b586eec2ea151a69e6fd14404a8ce7c # v1.13.0
@@ -62,12 +68,35 @@ jobs:
run: |
test "$(uname -m)" = arm64
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_OSX_ARCHITECTURES=arm64 -DCMAKE_OSX_DEPLOYMENT_TARGET=11.0 -DBMH_DATA= -DCMAKE_EXPORT_COMPILE_COMMANDS=ON
- name: Build every target
run: cmake --build build --config Release --parallel 2
- name: Build products and every runnable test
run: python3 tools/ci/build_runnable_tests.py --build build --config Release --parallel 2
- name: Run synthetic tests and report data tests as skipped
run: ctest --test-dir build -C Release --output-on-failure --output-junit test-results.xml
- name: Verify product versions
shell: python
run: |
import pathlib, subprocess, sys
build = pathlib.Path('build').resolve()
version = (build / 'product-version.txt').read_text().strip()
suffix = '.exe' if sys.platform == 'win32' else ''
cli = subprocess.run([str(build / ('openbmh_cli' + suffix)), '--version'], check=True, capture_output=True, text=True)
assert cli.stdout.strip() == 'OpenBMH console ' + version
subprocess.run([str(build / ('OpenBMH' + suffix)), '--version'], check=True)
- name: Package products and licenses
run: python3 tools/package/make_package.py --build build --out dist --platform ${{ matrix.platform }}
- name: Package native Windows editor
if: runner.os == 'Windows'
shell: pwsh
run: |
$game = (Get-ChildItem dist/OpenBMH-*-windows-x64.zip | Select-Object -First 1).FullName
python3 tools/package/make_editor_package.py --build build --game $game --out editor-dist
- name: Upload native editor
if: runner.os == 'Windows'
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
with:
name: obdeddi-windows-x64
path: editor-dist/*.zip
if-no-files-found: error
- name: Package corresponding source and pinned dependencies
if: runner.os == 'Linux'
run: python3 tools/package/make_source_package.py --source . --build build --out source-dist
+36 -11
View File
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: GPL-3.0-only
name: Prepare release packages
name: Prepare verified release
on:
push:
@@ -7,34 +7,59 @@ on:
permissions:
contents: read
actions: read
jobs:
build:
uses: ./.github/workflows/ci.yml
draft:
needs: build
runs-on: ubuntu-24.04
permissions:
contents: write
actions: read
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
fetch-depth: 0
- name: Locate successful CI for this exact revision
id: ci
env:
GH_TOKEN: ${{ github.token }}
EXPECTED_SHA: ${{ github.sha }}
run: |
gh api "repos/$GITHUB_REPOSITORY/actions/workflows/ci.yml/runs?status=success&event=push&per_page=100" > ci-runs.json
python3 - <<'PY'
import json, os
runs = json.load(open('ci-runs.json'))['workflow_runs']
matches = [r for r in runs if r['head_sha'] == os.environ['EXPECTED_SHA'] and
r['conclusion'] == 'success' and r['event'] == 'push' and
r['head_repository']['full_name'].lower() == os.environ['GITHUB_REPOSITORY'].lower()]
if not matches:
raise SystemExit('Run the full CI successfully for this revision before tagging a release')
with open(os.environ['GITHUB_OUTPUT'], 'a') as output:
output.write('run_id=' + str(matches[0]['id']) + '\n')
PY
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
with:
github-token: ${{ github.token }}
run-id: ${{ steps.ci.outputs.run_id }}
pattern: OpenBMH-*
path: dist
merge-multiple: true
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
with:
github-token: ${{ github.token }}
run-id: ${{ steps.ci.outputs.run_id }}
pattern: tests-*
path: test-reports
- name: Verify archives, corresponding source and platform reports
env:
RELEASE_TAG: ${{ github.ref_name }}
CI_RUN: ${{ steps.ci.outputs.run_id }}
run: |
python3 tools/package/verify_ci_release.py --dist dist --reports test-reports --tag "$RELEASE_TAG" --source-sha "$GITHUB_SHA" --ci-run "$CI_RUN" --repository "$GITHUB_REPOSITORY"
- name: Create draft for review
env:
GH_TOKEN: ${{ github.token }}
RELEASE_TAG: ${{ github.ref_name }}
run: |
for package in dist/*.zip; do
case "$(basename "$package")" in
OpenBMH-${RELEASE_TAG#v}-*.zip) ;;
*) echo "Release tag and package version differ" >&2; exit 1 ;;
esac
done
gh release create "$RELEASE_TAG" dist/*.zip --draft --verify-tag --title "OpenBMH $RELEASE_TAG" --notes-file docs/release/0.1/RELEASE_NOTES.md
gh release create "$RELEASE_TAG" dist/*.zip dist/SHA256SUMS dist/QA-REPORT.json --draft --verify-tag --title "OpenBMH $RELEASE_TAG" --notes-file docs/release/1.0/RELEASE_NOTES.md
+111 -4
View File
@@ -1,8 +1,19 @@
# 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 1.1.0 LANGUAGES CXX C)
if(APPLE)
# Enable native languages before dependencies/subdirectories inherit rules.
enable_language(OBJC OBJCXX)
endif()
set(OPENBMH_PRERELEASE "beta.2" CACHE STRING "Prerelease identifier; empty for final release")
set(OPENBMH_PRODUCT_VERSION "${PROJECT_VERSION}")
if(OPENBMH_PRERELEASE)
string(APPEND OPENBMH_PRODUCT_VERSION "-${OPENBMH_PRERELEASE}")
endif()
file(GENERATE OUTPUT "${CMAKE_BINARY_DIR}/product-version.txt" CONTENT "${OPENBMH_PRODUCT_VERSION}\n")
# the one place of the version: --version of both programs and the window title (src/version.hpp)
add_compile_definitions(OPENBMH_VERSION="${PROJECT_VERSION}")
file(GENERATE OUTPUT "${CMAKE_BINARY_DIR}/generated/openbmh_build_version.hpp"
CONTENT "// SPDX-License-Identifier: GPL-3.0-only\n#pragma once\n#define OPENBMH_VERSION \"${OPENBMH_PRODUCT_VERSION}\"\n")
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
@@ -196,19 +207,21 @@ 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/resource_bundle.cpp
src/formats/palette.cpp
src/formats/vga.cpp
src/formats/font.cpp
src/formats/textd.cpp
src/formats/fbm.cpp
src/formats/le.cpp
src/formats/rule_base.cpp
src/formats/data_profile.cpp
src/formats/m3d.cpp
src/formats/savestate.cpp
src/game/schedule.cpp
src/game/league_pairings.cpp
src/game/source_tip.cpp
src/game/table_forecast.cpp
src/game/profile_runtime.cpp
src/game/state.cpp
src/game/rating.cpp
src/game/match.cpp
@@ -239,6 +252,7 @@ add_library(bmhcore STATIC
src/game/weekly.cpp
src/game/messages.cpp
src/game/table.cpp
src/game/calendar.cpp
src/game/week.cpp
src/game/lineup.cpp
src/game/national.cpp
@@ -292,6 +306,7 @@ FetchContent_MakeAvailable(miniz lzma_sdk nfd)
add_library(bmh_miniz STATIC ${miniz_SOURCE_DIR}/miniz.c)
target_include_directories(bmh_miniz PUBLIC ${miniz_SOURCE_DIR})
target_link_libraries(bmhcore PRIVATE bmh_miniz)
set(BMH_LZMA_C ${lzma_sdk_SOURCE_DIR}/C)
add_library(bmh_7z STATIC
${BMH_LZMA_C}/7zAlloc.c ${BMH_LZMA_C}/7zArcIn.c ${BMH_LZMA_C}/7zBuf.c ${BMH_LZMA_C}/7zCrc.c
@@ -441,7 +456,8 @@ add_executable(openbmh_play
target_link_libraries(openbmh_play PRIVATE bmhui 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)
target_include_directories(openbmh_play PRIVATE "${CMAKE_BINARY_DIR}/generated")
if(MSVC)
target_compile_options(openbmh_play PRIVATE /utf-8)
# App sources also compile in headless tests/helpers without target /utf-8.
@@ -621,6 +637,7 @@ add_executable(openbmh_cli
src/cli/seat_hub.cpp
src/cli/json.cpp
${BMH_APP_SESSION_SOURCE})
target_include_directories(openbmh_cli PRIVATE "${CMAKE_BINARY_DIR}/generated")
target_link_libraries(openbmh_cli PRIVATE bmhui bmhlaunch)
if(WIN32)
target_link_libraries(openbmh_cli PRIVATE ws2_32) # --listen (Winsock)
@@ -1069,6 +1086,25 @@ if(MSVC)
endif()
add_test(NAME launch_unit_tests COMMAND launch_unit_tests)
add_executable(fltd_translation_unit_tests tests/fltd_translation_unit_tests.cpp)
target_link_libraries(fltd_translation_unit_tests PRIVATE bmhlaunch)
add_test(NAME fltd_translation_unit_tests COMMAND fltd_translation_unit_tests)
add_executable(host_path_display_unit_tests tests/host_path_display_unit_tests.cpp)
target_include_directories(host_path_display_unit_tests PRIVATE src)
if(MSVC)
target_compile_options(host_path_display_unit_tests PRIVATE /utf-8)
endif()
add_test(NAME host_path_display_unit_tests COMMAND host_path_display_unit_tests)
add_executable(quit_confirmation_unit_tests tests/quit_confirmation_unit_tests.cpp)
target_include_directories(quit_confirmation_unit_tests PRIVATE src)
target_link_libraries(quit_confirmation_unit_tests PRIVATE ${BMH_SDL_TARGET})
if(MSVC)
target_compile_options(quit_confirmation_unit_tests PRIVATE /utf-8)
endif()
add_test(NAME quit_confirmation_unit_tests COMMAND quit_confirmation_unit_tests)
add_executable(fixture_table_tests tests/fixture_table_tests.cpp)
target_link_libraries(fixture_table_tests PRIVATE bmhcore)
add_test(NAME fixture_table_unit_tests COMMAND fixture_table_tests)
@@ -1087,3 +1123,74 @@ foreach(dependency IN ITEMS SDL2 miniz lzma_sdk nfd)
string(JSON package_dependencies SET "${package_dependencies}" "${dependency}" "\"${dependency_path}\"")
endforeach()
file(GENERATE OUTPUT "${CMAKE_BINARY_DIR}/package-dependencies.json" CONTENT "${package_dependencies}\n")
add_executable(classic_rules_unit_tests tests/classic_rules_unit_tests.cpp)
target_link_libraries(classic_rules_unit_tests PRIVATE bmhcore)
add_test(NAME classic_rules_unit_tests COMMAND classic_rules_unit_tests)
add_executable(season_player_reset_tests tests/season_player_reset_tests.cpp)
target_link_libraries(season_player_reset_tests PRIVATE bmhcore)
add_test(NAME season_player_reset_tests COMMAND season_player_reset_tests)
set_tests_properties(season_player_reset_tests PROPERTIES TIMEOUT 10)
add_executable(lineup_foreign_limit_tests tests/lineup_foreign_limit_tests.cpp)
target_link_libraries(lineup_foreign_limit_tests PRIVATE bmhcore)
add_test(NAME lineup_foreign_limit_tests COMMAND lineup_foreign_limit_tests)
add_executable(calendar_epoch_tests tests/calendar_epoch_tests.cpp)
target_link_libraries(calendar_epoch_tests PRIVATE bmhui)
add_test(NAME calendar_epoch_tests COMMAND calendar_epoch_tests)
add_executable(video_session_tests tests/video_session_tests.cpp)
target_include_directories(video_session_tests PRIVATE src)
target_link_libraries(video_session_tests PRIVATE ${BMH_SDL_TARGET})
add_test(NAME video_session_tests COMMAND video_session_tests)
if(APPLE)
add_executable(mac_video_picker_tests tests/mac_video_picker_tests.mm)
set_target_properties(mac_video_picker_tests PROPERTIES OBJCXX_STANDARD 20 OBJCXX_STANDARD_REQUIRED YES)
target_include_directories(mac_video_picker_tests PRIVATE src)
target_link_libraries(mac_video_picker_tests PRIVATE ${BMH_SDL_TARGET} nfd::nfd "-framework Cocoa")
add_test(NAME mac_video_picker_tests COMMAND mac_video_picker_tests)
endif()
add_executable(desktop_feedback_tests tests/desktop_feedback_tests.cpp)
target_link_libraries(desktop_feedback_tests PRIVATE bmhui)
bmh_add_data_test(NAME desktop_feedback_tests COMMAND desktop_feedback_tests "${BMH_DATA}")
add_executable(data_profile_tests tests/data_profile_tests.cpp)
target_link_libraries(data_profile_tests PRIVATE bmhcore)
add_test(NAME data_profile_tests COMMAND data_profile_tests)
# Offline private package preparation; never installs Original data.
add_executable(export_community_runtime tools/poc/export_runtime.cpp)
target_link_libraries(export_community_runtime PRIVATE bmhcore)
add_executable(resource_bundle_tests tests/resource_bundle_tests.cpp)
target_link_libraries(resource_bundle_tests PRIVATE bmhcore bmh_miniz)
add_test(NAME resource_bundle_tests COMMAND resource_bundle_tests)
# Small native OBD editor. Its model is tested on every platform; UI is Win32 only.
add_library(obdeddi_hash STATIC ${BMH_LZMA_C}/Sha256.c ${BMH_LZMA_C}/Sha256Opt.c)
target_include_directories(obdeddi_hash PUBLIC ${BMH_LZMA_C})
target_link_libraries(obdeddi_hash PRIVATE bmh_7z)
add_library(obdeddi_model STATIC src/obdeddi/document.cpp src/cli/json.cpp)
target_include_directories(obdeddi_model PUBLIC src)
target_link_libraries(obdeddi_model PUBLIC bmhcore PRIVATE bmh_miniz obdeddi_hash)
if(WIN32)
add_executable(obdeddi WIN32 src/obdeddi/main_win32.cpp src/obdeddi/logo_win32.cpp src/obdeddi/logo_transform_win32.cpp)
target_link_libraries(obdeddi PRIVATE obdeddi_model comctl32 comdlg32 user32 gdi32 shell32 gdiplus)
if(MSVC)
target_compile_options(obdeddi PRIVATE /utf-8)
target_compile_options(obdeddi_model PRIVATE /utf-8)
endif()
install(TARGETS obdeddi RUNTIME DESTINATION . COMPONENT Editor)
endif()
add_executable(obdeddi_tests tests/obdeddi_tests.cpp)
target_link_libraries(obdeddi_tests PRIVATE obdeddi_model bmh_miniz)
add_test(NAME obdeddi_tests COMMAND obdeddi_tests)
if(WIN32)
add_executable(obdeddi_logo_tests tests/obdeddi_logo_tests.cpp src/obdeddi/logo_transform_win32.cpp)
target_include_directories(obdeddi_logo_tests PRIVATE src)
target_link_libraries(obdeddi_logo_tests PRIVATE gdiplus)
add_test(NAME obdeddi_logo_tests COMMAND obdeddi_logo_tests)
endif()
+16 -14
View File
@@ -1,10 +1,10 @@
# OpenBMH
A modern and faithful open source rebuild of the *Bundesliga Manager Hattrick* engine.
This is the **1.1 community development branch**. A prepared community package starts directly from `COMMUNITY.OBD`, without BMH.exe or a DOS installation. Original loose Classic installations remain supported. The stable 1.0 line stays on main. See [standalone community data](docs/poc-1.1/STANDALONE.md).
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.
A faithful, standalone community reconstruction of *Bundesliga Manager Hattrick*, using the player's original installation and SDL2 interface.
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.
OpenBMH 1.0 builds on v0.1.2 with reviewed bug fixes and starts directly with the original game data. Original game files, graphics, audio and manuals are not distributed. German CD-compatible BMH and verified Diamond editions are the primary release targets. Football Limited remains experimental; the older floppy executable is not supported.
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.
@@ -14,26 +14,28 @@ Check the [releases page](https://github.com/Weyoune/openbmh/releases) for avail
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.
3. Start `OpenBMH` (`OpenBMH.exe` on Windows). Select the game directory or executable when prompted. A ZIP or 7z containing one game installation can also be selected.
From a terminal:
From a terminal in the extracted package on Linux or macOS:
```sh
openbmh_play --data "path/to/game" --save-directory "path/to/saves"
openbmh_cli --console --data "path/to/game" --saves "path/to/saves"
./OpenBMH --data "path/to/game" --save-directory "path/to/saves"
./openbmh_cli --console --data "path/to/game" --saves "path/to/saves"
```
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).
In Windows PowerShell, use `.\OpenBMH.exe` and `.\openbmh_cli.exe` instead.
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 [release notes](docs/release/1.0/RELEASE_NOTES.md).
## Features and direction
The graphical client and console share career management, matches, transfers, contracts, finances, training, stadium management and save handling. The console supports command batches, structured views and multiple manager clients. Audio is decoded from the user's installation where supported.
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.
OpenBMH focuses on original-game compatibility, stability and community contributions. See the [contribution guide](CONTRIBUTING.md) and [maintenance roadmap](docs/ROADMAP.md).
## 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 build OpenBMH 1.0. 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:
@@ -50,7 +52,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 --data "path/to/game" --save-directory "path/to/saves"
```
### Linux
@@ -62,7 +64,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 --data "path/to/game" --save-directory "path/to/saves"
```
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.
@@ -77,7 +79,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 --data "path/to/game" --save-directory "path/to/saves"
```
On Intel Macs omit the arm64 setting or select `x86_64`. These commands build terminal executables; they do not create a signed application bundle.
@@ -103,6 +105,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.
Every published binary release identifies its matching source tag and provides a corresponding source archive. 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).
+13 -2
View File
@@ -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` (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
@@ -45,8 +45,19 @@ Use native toolchain/dependency architectures consistently. A terminal executabl
## Run with your data
```sh
build/openbmh_play --data "path/to/game" --save-directory "path/to/saves"
build/OpenBMH --data "path/to/game" --save-directory "path/to/saves"
build/openbmh_cli --console --data "path/to/game" --saves "path/to/saves" --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.
## Build the data-free CI subset
`cmake --build build` compiles every development helper and test. With no private integration data configured, CI builds both products and every executable actually referenced by CTest instead:
```sh
python3 tools/ci/build_runnable_tests.py --build build --config Release --parallel 2
ctest --test-dir build -C Release --output-on-failure
```
Tests whose inputs are unavailable still report a skip through the normal optional-data helper; they are not counted as passes. Supplying integration data during configuration causes their real programs to enter this build subset automatically. Source-export and build-discovery checks run separately in CI.
+1 -1
View File
@@ -1,6 +1,6 @@
# Text, encoding and editions
The installation supplies game text and names. The command vocabulary stays stable across editions; it is not translated into the selected game's display language. German and English installation data can have different text, league contents, executable layouts and currency presentation. English support remains experimental as described in the [release notes](../release/0.1/RELEASE_NOTES.md).
The installation supplies game text and names. The command vocabulary stays stable across editions; it is not translated into the selected game's display language. German and English installation data can have different text, league contents, executable layouts and currency presentation. English support remains experimental as described in the [release notes](../release/1.0/RELEASE_NOTES.md).
Legacy bytes are decoded at the display boundary. Client-facing text is intended to be UTF-8, while save and database offsets refer to legacy byte pools. Avoid using a displayed name as a persistent identifier: names may be edited, ambiguous or rendered differently. Prefer the ID domain required by the current command.
+27 -21
View File
@@ -2,7 +2,7 @@
OpenBMH aims to preserve the familiar game while handling malformed input and unsafe edge cases explicitly. A reconstruction can remain faithful without reproducing a crash or pretending to implement an unknown path.
- Content such as names, text, graphics and edition-specific tables is loaded from the user's installation. OpenBMH's shared rule base supplies simulation values; selecting another data edition does not select a separate engine.
- Content such as names, text, graphics and edition-specific tables is loaded from the user's installation. The loaded program retains its own rule-table values; loading no longer applies the former shared replacement profile.
- Safety checks reject transactions that would exhaust required return capacity, use stale identities or lose a valid state. Unsupported operations report their limitation rather than inventing an outcome.
- Calendar progression handles boundary days and seasonal transitions without relying on unsafe fixed-day assumptions.
- Saves are written from the committed session state. Saving does not deliberately replay unrelated game actions.
@@ -12,26 +12,32 @@ Intentional changes in code should use the marker `OpenBMH deviates from the ori
The [generated differences catalogue](DIFFERENCES.md) lists these markers with links to their source files.
## Environment and presentation in 0.1.2
## Application exit confirmation
The desktop environment provides three youth teams and three staff
budgets, each set to zero through six stars. Youth budgets are monthly, can be
changed throughout the season, and contribute to the finance preview, balance
plan and booked expenses. Youth tables develop on first-division matchdays;
promotion, relegation and age-group handover occur at the season change.
The two previously hidden youth groups are available across data editions.
Staff prices and the shared academy player-generation strength bands stay in
effect. Recruitment needs an active middle youth budget and an oldest youth team
within 25 strength points of the senior squad (the full-build mode bypasses the
strength gate). This deliberately
combines the six-budget environment with OpenBMH's existing player-generation rules.
Closing the window, exiting with Escape or confirming the desktop's exit control
opens a native confirmation dialog. BMH data uses German text and Football
Limited data uses English. Enter, Escape and closing the confirmation cancel the
exit; only the explicit Quit/Beenden button permits normal shutdown. Cancelling
keeps the current dialog or match owner alive without a turn or implicit save.
An unavailable native message box also cancels the request. This applies to
voluntary application exits, including quit events received during animations;
normal completed-career handling remains separate.
Old saved academy lump sums remain payable once and retain their paid status.
They are not multiplied into twelve monthly payments. Editing that tile replaces
the old amount with the selected monthly budget. There is no new save field.
## Original edition rules in 1.0
Live match minutes use the loaded original delay setting (A9), including zero,
instead of an added fixed pause. A9 and the existing scene delays can be adjusted
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.
Loaded executable images retain their own rule tables. Career strength ranges are read from all nine pairs of the supplied original table.
The six-budget monthly environment implementation has been checked against the provided CD and Diamond 3.6/3.7 program code. Its budget increments are read from that program's own table. Capability recognition uses verified code fingerprints, never directory names. Unrecognized environment implementations cannot be edited or simulated through a guessed model; they require separate compatibility verification. Older Diamond academy patches are not silently treated as the monthly model. The old floppy executable remains unsupported, and Football Limited remains experimental.
Release acceptance of individual editions is recorded separately from their recognition. Source compatibility and automated tests do not establish full original-game or platform validation.
## Diamond 3.7 foreign crests
The supplied edition controls whether foreign league clubs use individual
original crests or the original neutral crest. OpenBMH recognizes the verified
Diamond 3.7 drawing gate and uses its database/save selectors and W atlases.
Older drawing gates retain their own behaviour; no external crest pack is needed.
The automatic lineup installs the supplied foreign-player rule switch alongside the career tables. Where enabled, it restores the original three/two-player limit, reserve swaps with board-coordinate preservation and the short-lineup outcome when domestic reserves are unavailable. This does not consume additional random draws.
New careers correct the original all-zero EM qualification placeholders to the original national-team placeholders. Supplied nonzero seeds and restored savegame state are not rewritten by this initialization.
+5 -6
View File
@@ -6,20 +6,19 @@ 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/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.
- [src/formats/rule_base.hpp](../src/formats/rule_base.hpp): normalizes live-scene options, league strength ranges, option defaults, stadium prices and capacities, betting limits, and the foreign-player limit.
- [src/app/quit_confirmation.hpp](../src/app/quit_confirmation.hpp): confirms application exit with a localized native dialog, with cancellation selected by default.
- [src/game/career.cpp](../src/game/career.cpp): skips reserved calendar positions when assigning a joining manager to a club.
- [src/game/career.hpp](../src/game/career.hpp): uses the supported player-generation ranges and excludes reserved calendar positions when assigning managers.
- [src/game/desk_actions.cpp](../src/game/desk_actions.cpp): uses the supported transfer-fee arithmetic and designated set-piece fields.
- [src/game/desk_actions.hpp](../src/game/desk_actions.hpp): supports designated set-piece records and the supported transfer-editor rules.
- [src/game/environment.hpp](../src/game/environment.hpp): uses six monthly environment budgets across data editions while retaining the shared staff prices and academy player-generation strength bands.
- [src/game/highscore.cpp](../src/game/highscore.cpp): reads the supported edition-specific high-score format from the loaded image.
- [src/game/lineup.cpp](../src/game/lineup.cpp): disables the foreign-player limit in the supported rule profile.
- [src/game/lineup.hpp](../src/game/lineup.hpp): disables the foreign-player limit and supports owner-bound designated set-piece selection.
- [src/game/lineup.hpp](../src/game/lineup.hpp): supports owner-bound designated set-piece selection.
- [src/game/match.hpp](../src/game/match.hpp): uses the enhanced injury selection and suspension rules.
- [src/game/match_engine.cpp](../src/game/match_engine.cpp): supports designated set-piece takers, the enhanced injury tables, and the extended suspension fields.
- [src/game/season.cpp](../src/game/season.cpp): retains the enhanced academy player-generation strength bands with monthly youth budgets.
- [src/game/season.cpp](../src/game/season.cpp): age/retire each player once, even when a temporary offer row references his club slot or regeneration moves him to a later free-agent slot.
- [src/game/season.cpp](../src/game/season.cpp): includes transfer-market players in retirement so the five-bit age cannot wrap to 16.
- [src/game/season.cpp](../src/game/season.cpp): initializes the empty EM qualifier seeds with national teams, preventing club zero from entering the EM.
- [src/game/season.hpp](../src/game/season.hpp): retains the enhanced academy player-generation strength bands with monthly youth budgets.
- [src/game/state.hpp](../src/game/state.hpp): retains designated set-piece selections in the supported manager-record extension.
- [src/game/week.cpp](../src/game/week.cpp): uses the enhanced training rules: focus strength is at least five below its target, and completed skills rotate to another focus.
+12 -21
View File
@@ -1,29 +1,20 @@
# Roadmap
# Community maintenance roadmap
OpenBMH combines a playable reconstruction with a foundation for extension. These milestones describe direction and dependencies, not promised dates.
OpenBMH reconstructs the original Bundesliga Manager Hattrick experience using the player's own game data. Development priorities are compatibility, reliability and accessible community maintenance.
## 0.1: a usable engine
## 1.0 acceptance
Career management, matches, finances, transfers, original-style SDL2 screens, audio and a console share the same session logic. German game data is the primary target; Football Limited support is experimental. Compatibility and remaining limitations are documented in the [release notes](release/0.1/RELEASE_NOTES.md).
- Validate German CD-compatible BMH and supported Diamond installations, including career setup, management, matches and season transitions.
- Preserve original data and save layouts; document intentional bug corrections.
- Check Windows x64, macOS ARM64 and Linux x64 builds and publish matching source archives, licenses and checksums.
- Keep release limitations and reproducible defects visible in the issue tracker.
## 0.15: broader English compatibility
## Continued maintenance
Complete edition-specific loading, presentation, competitions and sound support. Imported content determines names, text, clubs and league organisation; a shared engine rule base defines the simulation.
Prioritize reproducible gameplay, save, rendering, input and platform bugs. Keep improvements focused and cover unsafe state transitions with regression tests. Contributions should preserve the familiar interface and the supplied edition's content and competition structure.
## 0.2: open data and typed state
Football Limited remains experimental. Improvements require independent checks of its original loading, presentation, competitions, audio and save compatibility; German acceptance does not establish English acceptance.
Introduce a documented import format and a native save format, retaining supported legacy import where practical. The format concept is [OBW](formats/OBW.md). Replace fixed-layout state gradually with typed clubs, players, contracts and competitions. Keep each intermediate stage usable and cover transitions with tests.
The SDL2 graphical client and console share the game/session layer. Community clients and automation should use the documented [console interface](CONSOLE_CLIENTS.md) and retain its ownership and revision checks.
## 0.3: configurable rules
Expose rule values and balance choices as configuration, with reproducible simulations to assess changes. Improve tactical automation, transfer decisions and scoring distributions through documented changes rather than hidden edition-specific branches.
## 0.4: adaptable interfaces and competitions
Add a scalable interface (RmlUi) through the shared application/protocol boundary. Make league sizes and competition structures data-driven. Define content-pack formats for independently licensed artwork, names and other resources; do not distribute third-party material without permission.
## 0.5: independently distributable content
Provide original or freely licensed graphics, sound and generated football worlds so that OpenBMH can be played without proprietary game data. Support editors, new competitions and multiplayer clients built on the same engine interfaces.
The typed model and open format are prerequisites for flexible competitions, configurable rules and new content. See [architecture](architecture.md) for the current boundaries and [compatibility decisions](COMPATIBILITY.md) for intentional departures.
See [architecture](architecture.md), [compatibility decisions](COMPATIBILITY.md) and [contributing](../CONTRIBUTING.md) before changing shared behaviour. No proprietary game content belongs in public code, tests or releases.
+10
View File
@@ -1991,3 +1991,13 @@ declarations change. Game text, resort, image and audio fallbacks belong outside
| `EnglishSixTeamFixtureTable` | `0x6eed4` | English image adapter |
| `EnglishTwelveTeamFixtureTable` | `0x6f0bc` | English image adapter |
| `EnglishTwentyTeamFixtureTable` | `0x6ee40` | English image adapter |
## Verified edition-dependent parameters
| Field | Address | Use |
|---|---|---|
| `CalendarDateSetup` | `0x21270` | Verified date setup: weekday byte at +4, initial year dword at +13. Original CD uses 1995/Saturday; checked Diamond editions use 2026/Wednesday. |
| `ForeignBadgeGateInstruction` | `0x10070` | Verified original drawing gate; operand at +3 selects neutral foreign crests or individual W-sheet selectors. |
| `EnvironmentBudgetSteps` | `0xa50ff` | Six budget increments in the verified monthly environment implementation. |
Calendar presentation, engine weekday processing and save-list headers share the supplied installation's epoch. The original four-year date arithmetic is preserved; this reader does not substitute a different calendar system or rewrite the installation. Unknown date setup instructions and invalid values are rejected.
-475
View File
@@ -1,475 +0,0 @@
# OBW: OpenBMH world, save and pack format (concept, format version 1.0)
Status: **concept** for roadmap 0.2 (open data and typed state) with preparation for 0.4 (scalable interface, content packs). Nothing here is implemented yet; the legacy formats in this directory remain authoritative for the current engine.
## 1. Goals and non-goals
Goals:
- One documented, versioned format for a game world (start database), a running career (save) and content packs.
- A typed model of nations, clubs, players, staff, contracts, finances and competitions that no longer depends on the memory image of a particular executable.
- Data-driven competitions: up to **32 leagues** (national and foreign leagues together), real-world European club cups (league phase plus knockout), and national-team competitions including qualification and a Nations-League-style tiered competition.
- Import from the supported German editions and from Football Limited (FLTD), both for a new career and for an existing `.FBM` save.
- Preparation for a high-resolution interface built with RmlUi: logical asset keys, high-resolution crests and icons, player photos, further languages and modern font formats.
- Forward compatibility: readers of the same major version accept files written by later minor versions.
Non-goals of version 1.0:
- The match engine and its parameters (reserved namespace `x-matchengine`, see §3.3).
- Network play, an editor application and a binary encoding (reserved, see §2.4).
- Layout or screen data. Interfaces are themes (§9.6), not part of a world.
## 2. Container and files
### 2.1 Container
Every OBW file is a ZIP archive (deflate or stored) containing UTF-8 JSON documents. The project already links miniz (`bmh_miniz`) and has a JSON reader/writer (`src/cli/json.cpp`), so the format needs no new dependency. JSON keeps worlds diffable and editable by hand or by script.
| Extension | `kind` | Contents |
|---|---|---|
| `.obw` | `world` | Start database: everything needed to begin a career |
| `.obs` | `save` | A world plus the running state of a career |
| `.obp` | `pack` | Overlays and assets for worlds (names, crests, photos, texts) |
| `.obt` | `theme` | Interface theme for the RmlUi client (§9.6) |
An unpacked directory with the same layout is accepted wherever an archive is, which keeps development and version control simple.
### 2.2 Layout
```
manifest.json required, §3
world/nations.json nations and their national teams
world/clubs.json clubs (teams of type "club")
world/players.json players
world/staff.json managers, coaches, other staff
world/stadiums.json stadiums
world/contracts.json player and staff contracts
world/finance.json club finances, sponsors, advertising, loans, shares
world/competitions.json competition definitions, §6
world/calendar.json season calendar, §7
world/rules.json rule values (training camps, interest rates, ...)
state/... save only, §5.9
locale/<lang>/*.po texts, §9.3
assets/... packs and themes only, §9
x-<name>/... extensions, §3.3
```
Every table file is an object `{"schema": "<table>@<major>.<minor>", "items": [...]}`. Tables with many rows (results, history, mail) may instead be stored as JSON Lines (`*.jsonl`, one item per line, first line the header object without `items`).
### 2.3 Encoding rules
- Text is UTF-8. Legacy single-byte text is converted on import (`iso646de_to_utf8`).
- Money is an integer in the smallest unit of the world currency (`manifest.currency`, e.g. `{"code": "DEM", "minor_units": 0}`); no floating point for money.
- Dates are ISO 8601 calendar dates (`"1995-07-01"`), in-game time is a date plus an optional `"minute"`.
- Percentages and ratings are integers on the scale declared by their attribute set (§5.3).
- Optional fields may be omitted; the schema gives their default.
### 2.4 Reserved
A compact binary encoding of large `state/` tables is reserved for a later minor version as an alternative representation of the same schema (`"encoding": "cbor"` in the table header). Readers of 1.0 reject unknown encodings with a clear error.
## 3. Versioning and migration
### 3.1 Manifest
```json
{
"format": "openbmh-world",
"format_version": "1.0",
"kind": "world",
"min_reader": "1.0",
"generator": "OpenBMH 0.2.0",
"created": "2026-10-17",
"title": {"default": "Season 1995/96"},
"provenance": "import:bmh-de",
"content_license": "local-import-only",
"currency": {"code": "DEM", "minor_units": 0},
"start_date": "1995-07-01",
"languages": ["de"],
"limits": {"leagues": 32},
"requires": [],
"extensions": []
}
```
- `format_version` is `major.minor`. A **minor** step only adds optional fields, tables, enum values that have a documented fallback, or new stage types guarded by `requires`. A **major** step may rename, remove or re-interpret fields.
- `min_reader` is the lowest reader version that can use the file correctly (a writer raises it when it uses a minor feature without a safe fallback).
- `requires` lists features without which the file cannot be played, e.g. `["stage:swiss"]`; a reader that lacks one refuses the file instead of guessing.
- `provenance` records where the content came from: `native`, `import:bmh-de`, `import:bmh-de-classic`, `import:fltd`, or `pack:<id>`. `content_license` is free text or an SPDX identifier; `local-import-only` marks data converted from a user's own installation (§8.4).
### 3.2 Reading and migration
- Readers ignore unknown fields and tables, keep them in memory and write them back unchanged (round trip), so a newer minor version survives an older tool.
- Missing optional fields take the schema default.
- Older major versions are upgraded on load through a chain of migrations (`migrate_1_to_2`, `migrate_2_to_3`, ...). Writers always write the newest version; a migrated save is written under a new name unless the player confirms the upgrade.
- Each table carries its own `schema` version, so a table can advance a minor step independently; the manifest version is the highest of them.
### 3.3 Extensions
Fields and directories whose name starts with `x-` belong to extensions (`x-matchengine`, `x-realnames`, `x-editor`). The core never interprets them, preserves them on round trip and lists active ones in `manifest.extensions` with a version, e.g. `{"id": "x-matchengine", "version": "1.0"}`.
### 3.4 Schemas
Each format version is published as JSON Schema (draft 2020-12) under `docs/formats/obw/schema/<major>.<minor>/`, one file per table. The schemas are the machine-readable specification and the basis of the validator (§10).
## 4. Identifiers and names
- Every entity has a stable string id `<type>:<key>`, e.g. `nation:de`, `club:0042`, `player:01873`, `comp:de-1`, `stadium:0042`. Keys are opaque: they never encode a real name, so a world and a pack can be published independently.
- Ids are unique within a world and never reused within a save. The engine assigns runtime indices; files never store them.
- Nation keys use ISO 3166-1 alpha-2 where one exists, otherwise a documented private key (`nation:x-eng` for England, `nation:x-sco`, ...).
- Every displayed name is a localized string: `{"default": "...", "en": "...", "short": {"default": "..."}}`. `default` is required; a language entry overrides it; `short` and `abbr` are optional display variants for narrow layouts.
- Packs overlay names, crests and photos by id (§9.5), never by position.
## 5. Entities
Field lists name the type and whether the field is required (R) or optional (O, with default). Only the main fields are listed; the schema is authoritative.
### 5.1 Nation (`world/nations.json`)
| Field | Type | | Meaning |
|---|---|---|---|
| `id` | string | R | `nation:<key>` |
| `name` | localized | R | |
| `confederation` | string | R | `uefa`, `conmebol`, `caf`, `afc`, `concacaf`, `ofc`, `other` |
| `coefficient` | integer | O 0 | Club-competition ranking points (§6.6) |
| `strength` | integer | O 0 | Rating of the national team when no squad is simulated |
| `national_team` | string | O | Team id of type `national` (§5.2) |
| `playable` | bool | O false | Whether its leagues are simulated in full |
### 5.2 Team (`world/clubs.json`)
Clubs and national teams share one entity type, distinguished by `type`.
| Field | Type | | Meaning |
|---|---|---|---|
| `id` | string | R | `club:<key>` or `nt:<nation key>` |
| `type` | enum | R | `club`, `national`, `amateur` (newcomer pool), `foreign` (strength only) |
| `name` | localized | R | |
| `nation` | string | R | |
| `stadium` | string | O | |
| `colors` | array | O | 1 to 3 `#rrggbb` values, used for generated crests and kits |
| `reputation`, `fans`, `strength` | integer | O | Club values on the attribute scale of the world |
| `founded` | integer | O | Year |
| `crest` | string | O | Asset key, default `asset:club/<key>/crest` (§9.1) |
| `x-*` | any | O | Extensions |
Teams without a squad (`foreign`, or `national` in a world that does not simulate national squads) carry `strength` instead of players.
### 5.3 Player (`world/players.json`)
| Field | Type | | Meaning |
|---|---|---|---|
| `id` | string | R | |
| `name` | object | R | `{"first": "...", "last": "...", "known_as": "..."}`, each a plain string; `known_as` optional |
| `born` | date | R | Age is derived from the in-game date |
| `nationalities` | array | R | Nation ids, first entry is the sporting nationality (national-team eligibility) |
| `positions` | array | R | `gk`, `def`, `mid`, `fwd` in the classic set; finer positions in later attribute sets |
| `foot` | enum | O | `left`, `right`, `both` |
| `attribute_set` | string | O world default | e.g. `bmh-classic@1` |
| `attributes` | object | R | Values named by the attribute set, e.g. `{"strength": 7, "technique": 5, "condition": 9, "form": 6}` |
| `character` | object | O | Traits the attribute set defines |
| `team` | string | O | Current team id; absent for free agents |
| `squad_number` | integer | O | |
| `status` | object | O | Injury, suspension and card counters per competition (save only) |
| `photo` | string | O | Default `asset:player/<key>/photo` |
An attribute set is declared once in `world/rules.json` with its fields, scales and meaning, so a later, finer model can sit next to the classic one without breaking the format:
```json
{"id": "bmh-classic@1", "fields": {
"strength": {"min": 1, "max": 10},
"technique": {"min": 1, "max": 10},
"condition": {"min": 0, "max": 100},
"form": {"min": 1, "max": 10}}}
```
The exact list and scales of `bmh-classic@1` are fixed when the importer is written, from the fields the current engine uses (`Player` in `src/game/state.hpp`).
### 5.4 Staff and managers (`world/staff.json`)
Managers (human or computer), coaches and other employees: `id`, `name`, `born`, `nation`, `role` (`manager`, `coach`, `physio`, ...), `team`, `attributes`. In a save, `state/managers.json` adds the human manager profile: options, ratings, history, automation settings.
### 5.5 Contracts (`world/contracts.json`)
`id`, `person` (player or staff id), `team`, `start`, `end`, `salary` (money per season), `bonuses` (signing, per goal, ...), `release_clause` (O), `options` (O). One active contract per person and team; the history is kept in the save.
### 5.6 Stadiums (`world/stadiums.json`)
`id`, `name`, `capacity` split by area (`standing`, `seated`, `boxes`), `facilities` (floodlights, heating, scoreboard, ... as named levels), `pitch`, `owner` (team id or `null`).
### 5.7 Finance (`world/finance.json`)
Per team: balance, ticket prices, sponsors (shirt, boards, with duration and value), advertising, loans (amount, rate, due date), shares and other income or cost sources the engine models today. Rate tables such as the credit table live in `world/rules.json`.
### 5.8 Rules (`world/rules.json`)
Named rule values that are content of the world rather than of the engine: training-camp resorts (price, quality grades), credit-rate tables, attribute sets, points for a win, squad limits. Today these values are read from the executable of the selected edition; in OBW they are ordinary data (and the starting point of the configurable rules of roadmap 0.3).
### 5.9 Save state (`state/`, saves only)
| File | Contents |
|---|---|
| `state/career.json` | Current date, season, phase, active human managers, settings |
| `state/rng.json` | State of the random generator(s) (`docs/RNG.md`), so a load continues deterministically |
| `state/tables.json` | Standings per competition stage and group |
| `state/results.jsonl` | Every played or scheduled match: competition, stage, round, home, away, result, after extra time / penalties |
| `state/squads.json` | Lineups, formations, tactics per team |
| `state/history.jsonl` | Season history: champions, cup winners, top scorers, records |
| `state/mail.jsonl` | Messages and news |
| `state/market.json` | Transfer list, open bids, loan offers |
| `state/x-legacy.json` | Unmapped legacy values carried over by the importer (§8.3) |
## 6. Competitions
### 6.1 Model
A competition is an ordered list of **stages**. Each stage takes teams from **slots** (§6.4), plays a format and hands teams on (to the next stage, to another competition, or to a final ranking).
```json
{
"id": "comp:de-2",
"name": {"default": "2. Liga"},
"type": "league",
"nation": "nation:de",
"tier": 2,
"season_cycle": 1,
"stages": [{
"id": "regular",
"format": "league",
"teams": 18,
"legs": 2,
"points": {"win": 3, "draw": 1, "loss": 0},
"tiebreakers": ["points", "goal_difference", "goals_for", "head_to_head", "draw_lots"],
"matchdays": "calendar:league-weekends"
}],
"movement": [
{"ranks": [1, 2], "to": "comp:de-1"},
{"ranks": [3], "to": "comp:de-1/playoff", "role": "challenger"},
{"ranks": [16, 18], "to": "comp:de-3"}
]
}
```
`type` is `league` (counts towards the league limit), `cup` (national cup), `club_international`, `national_team`, `friendly` or `indoor`.
### 6.2 Stage formats
| Format | Purpose | Main parameters |
|---|---|---|
| `league` | Round robin | `teams`, `legs` (1, 2, n), `points`, `tiebreakers`, fixture generator |
| `groups` | Several round robins | `groups`, `teams_per_group`, `legs`, seeding `pots`, draw constraints (e.g. no two teams of one nation) |
| `swiss` | League phase with a fixed number of games against drawn opponents | `teams` (e.g. 36), `matches` (e.g. 8), `pots`, `home_away_balance`, one common table |
| `knockout` | Ties | `legs` (1 or 2), `seeded`, `draw` (`open`, `seeded`, `bracket`), `extra_time`, `penalties`, `away_goals` (on/off), `neutral_venue`, `replay` (FA-Cup style) |
| `playoff` | Ties between teams of different competitions (relegation, qualification) | as `knockout` plus the roles of the participants |
| `final` | Single match or final tournament | `venue`, `teams` |
Common stage parameters: `extra_time` (minutes), `penalties`, `suspensions` (cards that lead to a ban, counted per competition or per stage), `substitutions`, `squad_registration` (size, home-grown quota), `prize_money` per round and result, `tv_money`, `gate_split`. New formats are added through a minor version with an entry in `manifest.requires`.
### 6.3 Fixture generation
A `league` or `groups` stage names a generator: `"generator": "round-robin"` (circle method, home/away balanced) works for every size. The legacy round tables of the original game remain available as `"generator": "legacy:<teams>"` for imported worlds, so imported careers keep their familiar order; they come from the user's installation, not from the format.
### 6.4 Slots and qualification
Participants are declared, not hard-coded:
```json
"slots": [
{"from": "comp:de-1", "ranks": [1, 4], "stage": "league-phase"},
{"from": "comp:de-cup", "winner": true, "to": "comp:uel", "stage": "league-phase",
"fallback": {"from": "comp:de-1", "next_unqualified": true}},
{"from": "coefficient", "nation_rank": [1, 4], "places": 4},
{"holder": "comp:ucl", "stage": "league-phase"}
]
```
A slot source is: a rank range of a stage, the winner/runner-up of a competition, the holder of a title, the next team not yet qualified (substitution rules), a coefficient ranking, or an explicit list. The engine resolves all slots at season end in the order given by `world/calendar.json`.
### 6.5 League pyramid
`movement` on a league connects tiers: promotion, relegation and playoffs between two leagues, several parallel lower leagues feeding one league (the two regional third divisions of the German editions), and a refill pool for the lowest tier (`"refill": {"from": "pool:amateur", "count": 2}`). This replaces the fixed per-edition tables in `src/game/schedule.hpp` (`kLeagueRelegation`, `kLeagueEurope`, `kGroupBelow`, `kNewcomerFirst`).
### 6.6 Coefficients
`world/rules.json` may define coefficient rankings (club and nation) with the points per result and per round reached and the number of seasons summed. They drive seeding pots and the number of European places per nation. A world may instead fix places per nation (`"places": {"nation:de": {"ucl": 4, "uel": 2}}`), which is how imported legacy worlds start.
### 6.7 Templates
The project ships competition templates under `docs/formats/obw/templates/`. They contain structure only, with neutral names:
- **Club competitions:** a champions cup with a 36-team league phase, a knockout playoff for places 9 to 24, round of 16 to final; a second and a third club cup in the same shape; a super cup; the knockout-only cups of the original game.
- **National teams:** a world cup with continental qualification groups and playoffs, a continental championship with qualification, and a **tiered nations league**. The nations league has leagues A to D with groups of three or four, promotion and relegation between tiers, a final tournament for the group winners of A, and playoffs that can feed continental-championship places.
- **National cups and side competitions:** knockout national cups (with or without replays and a qualifying round), an indoor tournament, friendlies.
### 6.8 National teams
A world that simulates national teams gives each `national` team a call-up rule: squad size, eligibility through `nationalities[0]`, selection by attribute set (best `n` by position) or by a human manager. International windows in the calendar (§7) suspend club play when the world asks for it (`"club_break": true`). Worlds without national squads use `strength` and simulate only results.
## 7. Calendar
`world/calendar.json` describes a season as dated events, independent of the executable's day table:
```json
{
"season_start": "07-01",
"season_length_days": 365,
"windows": [
{"id": "summer-transfer", "type": "transfer", "from": "07-01", "to": "08-31"},
{"id": "intl-sep", "type": "international", "from": "09-02", "to": "09-10", "club_break": true}
],
"series": [
{"id": "league-weekends", "weekday": "sat", "from": "08-08", "to": "05-20", "skip": ["winter-break", "intl-*"]},
{"id": "ucl-league-phase", "weekdays": ["tue", "wed"], "dates": ["09-16", "09-30"]}
],
"events": [
{"date": "06-30", "action": "season_end"},
{"date": "01-05", "action": "training_camp_window"}
]
}
```
Dates are month-day within the season; the engine maps them to concrete days each year, including leap years and seasons whose first day falls on a different weekday (the cases fixed in the current calendar code). Stages refer to a series by id. Imported worlds receive a calendar generated from the edition's day table, so the familiar rhythm stays.
## 8. Import from BMH and Football Limited
### 8.1 Sources
The importer (planned module `src/import/`) reuses the existing loaders:
| Source | Loader | Result |
|---|---|---|
| Master database `M3D.MAN` / `M3E.MAN` | `src/formats/m3d.cpp` | Clubs, players, staff, stadiums |
| Executable tables (league sizes, ladders, calendar, fixture tables, rule values) | `src/formats/le.cpp`, `src/launch/fltd.cpp`, `src/game/schedule.hpp` installers | Competitions, calendar, rules |
| Text database `TEXTD.BLK` / `TEXTE.BLK` | `src/formats/textd.cpp` | Local language layer `de-original` / `en-original` |
| Save `*.FBM` | `src/formats/fbm.cpp`, `savestate.cpp` | `state/` of a save |
| Crests and pictures `*.VGA`, `WAPPEN.LBM` | `src/formats/vga.cpp` | Low-resolution fallback assets, local only |
Edition detection is the one the launcher already performs (`src/launch/game_data.cpp`).
### 8.2 Mapping per edition
Every edition has a mapping table in the importer (to be published with it as `docs/formats/obw/import.md`):
| Legacy league | German editions | Football Limited | OBW |
|---|---|---|---|
| 0 | 1st division, 18 teams | 1st division, 20 teams | `comp:<n>-1`, tier 1 |
| 1 | 2nd division, 18 | 2nd division, 20 | tier 2 |
| 2, 3 | Two parallel third divisions A and B, 18 each, one promotion group | 3rd and 4th division, 20 each | tier 3 (two leagues) / tiers 3 and 4 |
| 4 | Fourth tier, 18 | Fifth league, 10 teams, not played | tier 4 / tier 5 with `"played": false` |
| 5-8 | Four foreign leagues of 12 | Same four foreign leagues of 12 | `comp:<nation>-1` each, `nation.playable = true` |
| Newcomer pool | 30 amateur clubs | 12 further named clubs | `pool:amateur` |
Cups, European cups, the indoor tournament, the English FA Cup with its qualifying stage and the League Cup become competitions with the same rules the engine applies today. Relegation places, European places and promotion groups are taken from the installed tables (`kLeagueRelegation`, `kLeagueEurope`, `kGroupBelow`), not re-typed by hand.
### 8.3 Fidelity
- A new career imported from an installation must produce the same first season in the engine as the legacy start (same fixtures, same participants), verified by the regression runs.
- A converted `.FBM` must continue with the same results as the legacy save for a fixed number of turns.
- Values the typed model does not yet understand go to `state/x-legacy.json` with their legacy name, so nothing is lost while the model grows area by area.
### 8.4 Rights
Imported content stays on the player's machine. The importer marks it `"provenance": "import:..."` and `"content_license": "local-import-only"`; tools refuse to bundle such a world into a distributable pack. Only worlds and packs with their own licence may be shared.
## 9. Assets, languages, fonts and the RmlUi interface
### 9.1 Asset keys
Data never refers to file paths. It uses logical keys:
| Key | Meaning |
|---|---|
| `asset:club/<key>/crest` | Club crest |
| `asset:club/<key>/kit/home` | Kit |
| `asset:player/<key>/photo` | Player photo |
| `asset:staff/<key>/photo` | Staff photo |
| `asset:comp/<key>/logo`, `asset:comp/<key>/trophy` | Competition logo and trophy |
| `asset:nation/<key>/flag` | Flag |
| `asset:stadium/<key>/image` | Stadium picture |
| `asset:icon/<name>` | Interface icon |
### 9.2 Resolution and image formats
A resolver looks a key up in the active packs by priority (§9.5), then in the world, then falls back: original low-resolution graphics of the installation where one exists, a crest generated from `colors`, a silhouette for photos, a neutral icon.
- **Crests, logos, flags, icons:** SVG preferred (scales to every resolution). Otherwise PNG with alpha in size steps 64, 128, 256 and 512 px (`crest@128.png`). The resolver picks the smallest step not below the requested size.
- **Photos:** PNG, JPEG or WebP, aspect 3:4, reference size 300×400 px, larger allowed. Faces centred; the interface crops, it never stretches.
- **Pictures** (stadiums, backgrounds): PNG, JPEG or WebP, 16:9 reference 1920×1080.
Asset metadata sits next to the files in `assets/index.json`: key, files per size, author, source and licence (required).
### 9.3 Languages
- Interface texts use gettext `.po` files under `locale/<lang>/openbmh.po` (`msgctxt` for context, plural forms, mature translator tools such as Poedit and Weblate). Message ids are stable English keys.
- Data names are localized strings inside the tables (§4); packs can add languages to them.
- The original text databases are imported into a local layer `de-original` or `en-original`, which the classic interface uses. New interfaces use the project's own texts.
- A fallback chain is configured by the player, e.g. `["en-GB", "en", "de"]`.
- Text is shaped as Unicode (RmlUi supports it); no single-byte substitutions outside the legacy layer.
### 9.4 Fonts
- TrueType and OpenType (`.ttf`, `.otf`); RmlUi renders them through FreeType. Variable fonts are allowed.
- A theme declares font families with weights, a fallback chain covering the languages it claims, and the licence of every font file (for example SIL OFL).
- The original bitmap fonts stay for the classic interface only.
### 9.5 Content packs (`.obp`)
```json
{
"format": "openbmh-world",
"format_version": "1.0",
"kind": "pack",
"id": "pack:example-crests",
"title": {"default": "Example crests"},
"targets": [{"world_provenance": "import:bmh-de"}],
"priority": 100,
"content_license": "CC-BY-4.0",
"overlays": ["names", "assets", "locale"]
}
```
- A pack contains `overlay/<table>.json` files with partial entities by id (only the fields it changes), `assets/` and `locale/`.
- Several packs stack; the higher `priority` wins per field and per asset key. A pack may not add or remove entities in 1.0 (that is a world, not a pack), which keeps saves valid when a pack is removed.
- `targets` restricts a pack to worlds by provenance or world id.
- The project distributes only the format, tools and its own or freely licensed material. Packs with real names, crests or photos are made and shared by their authors under their own responsibility. The team's internal real-name pack uses this format and stays private.
### 9.6 RmlUi themes (`.obt`)
- A theme contains `.rml` documents, `.rcss` style sheets, fonts, icons and its `locale/` texts, plus a manifest naming the client version it targets.
- Interfaces bind to a **view model**, not to the world files. The client exposes data models (RmlUi data bindings) built from the application/protocol layer (`docs/protocol.md`), with ids and asset keys as values. RmlUi loads images through a file interface that resolves `asset:` keys (§9.2).
- Neither worlds nor packs contain layout, so a theme works with every world, and the classic 320×200 interface keeps working next to it.
## 10. Validation and limits
The validator (planned `openbmh_cli --validate <file>`) checks, in this order:
1. Container, manifest, `format_version`, `min_reader`, `requires`.
2. Every table against its JSON Schema.
3. References: every id used exists and has the right type; no id is defined twice.
4. Competition logic: slot counts match stage sizes; movements between tiers are balanced; every stage can be scheduled in the calendar; fixture generators exist for the sizes.
5. Engine limits declared in `manifest.limits` and enforced by the engine of a version. For 1.0:
| Limit | Value |
|---|---|
| Competitions of type `league` (national and foreign) | **32** |
| Teams per league | 4 to 24 |
| Squad size per team | engine maximum of the attribute set |
| Groups per stage | 16 |
The format itself has no fixed limits; a later engine raises them by changing `limits` and its own checks, without a format change.
Errors name the file, the JSON path and the rule (`clubs.json: items[41].stadium: unknown id stadium:0999`).
## 11. Implementation steps
| Step | Roadmap | Content |
|---|---|---|
| 1 | 0.2 | Schemas 1.0, reader/writer, validator, round-trip tests with synthetic worlds |
| 2 | 0.2 | Importer for German editions and FLTD into `.obw`; adapter OBW → current `GameState`; regression: same first seasons |
| 3 | 0.2 | `.FBM` → `.obs` conversion and native OBW saves; area by area the engine reads typed data instead of the memory image (clubs, players, contracts, finances, then competitions) |
| 4 | 0.3 | `rules.json` drives the rule values; balance changes as data |
| 5 | 0.4 | Generic competition engine (stage formats, slots, pyramid, variable league sizes up to the limits); templates for the real-world club cups and national-team competitions |
| 6 | 0.4 | Asset resolver, packs, `.po` languages, RmlUi client with themes |
| 7 | 0.5 | Own worlds that need no original data |
Each step keeps the game playable and the regression runs green; the legacy formats stay readable as import sources.
-1
View File
@@ -19,7 +19,6 @@ Unless a page says otherwise, integer fields are little endian. Legacy strings u
| Audio containers | `S/2000` through `S/2003` | [SOUND](SOUND.md) | `src/audio/container.cpp`, `original.cpp` |
| Executable data | German LE and English X-32 images | [LE](LE.md), [executable layout](EXECUTABLE_LAYOUT.md) | `src/formats/le.cpp`, `src/launch/fltd.cpp` |
| IFF crest template | `WAPPEN.LBM` | [WAPPEN](WAPPEN.md) | Not loaded by OpenBMH |
| OpenBMH world, save and pack (concept) | `*.obw`, `*.obs`, `*.obp`, `*.obt` | [OBW](OBW.md) | Planned for 0.2 |
German and English editions can share a physical format while differing in text, league contents, executable layout and currency. Select the edition through the supplied installation; do not rename files or patch a save header to simulate another version. Original English V2.20 save import is a separate compatibility limitation from English installation support.
+28
View File
@@ -0,0 +1,28 @@
# obdeddi 0.1.0
A small native Windows data editor for the standalone OpenBMH 1.1 COMMUNITY.OBD format. It uses Win32/common controls, not SDL, RmlUI or a browser. The model and archive-writing tests build on all supported platforms; the graphical editor is Windows x64 only.
## Use
Extract the separate editor package and start `obdeddi.exe`. Open a COMMUNITY.OBD with the Open button or Ctrl+O. A file path may also be passed on the command line. Search and sortable virtual lists cover players and clubs; the club filter applies to players. Artwork is decoded only on demand in the separate club-logo dialog.
Player fields include names, position, nationality, age, form/technique/condition, bonus and the seven Classic skills. Displayed strength is derived, not a second independent field. Club fields include names, the stored short-name span and existing kit selectors. League sizes and record counts stay fixed. Country rows and rules are not editable. Club logos can be imported from PNG/JPEG/BMP, cropped by source-pixel coordinates, freely rotated and mirrored. The before/after preview uses the actual 38×38 Original palette and bright background; shared crest cells are cloned into a free cell. Other artwork is not editable. League players can move between squads or swap places; temporary/reserve-table players cannot be reassigned as if they were ordinary roster members.
Classic new-career generation is deliberately retained: many stored player values are randomized/recalculated when a career starts. Editing the database does not modify an existing saved game. This limitation is visible in the player form.
Apply commits the current form to the in-memory document. Changing selection also validates the draft form. Ctrl+S writes the document to its original OBD after verification and backup. Closing or opening another file asks about unsaved changes.
## Save safety
- ZIP/resource limits and supplied hashes are checked on open. Original database order, IDs, unknown player bits and non-database resource bytes are preserved.
- The M3D writer validates a decode/encode roundtrip. Unsupported characters and full 16-bit string pools are rejected rather than silently replaced.
- Save serializes a temporary sibling archive and reopens it for validation. A cooperating editor lock prevents overlapping saves.
- The complete prior archive is copied to `backups/` and read back for verification. External modifications are checked before the transaction and again before replacement.
- Only then does the OS atomically replace the original. A failed backup, validation or replacement leaves the original intact; a temporary file is cleaned up. Successful saves update resource hashes and append an editor-history record.
- Saving an unchanged document is a no-op. Backups are independent OBD bytes and can be copied back while the application is closed.
## Performance and delivery
Owner-data lists request only visible cell text. Search is debounced, forms update on selection/change, and the native message loop does not render continuously while idle. Assets are retained as bytes for integrity and save roundtrips, without image/font/audio decoding.
The editor has its own ZIP/release. It is not inserted into the small Windows community game package. Corresponding full sources are offered separately. OpenBMH 1.1 Beta keeps a fixed `OpenBMH 1.1` window caption, fits 18/20-team strengths views above the controls and uses a 25% longer default scene-frame delay (at least 16 ms). Explicit frame-delay overrides remain available; simulation clocks and random streams are not changed.
+64
View File
@@ -0,0 +1,64 @@
# Classic-plus-1 profile
This opt-in experimental profile keeps the Classic competition types and indexed artwork formats. It is not a DOS patch. The original executable is read only; verified dimension data and the expanded calendar are prepared in memory. Unmarked installations retain Classic dimensions and save identity.
## Discovery and dimensions
`OBMHPROF.INI` contains exactly:
```ini
[OpenBMH]
profile=classic-plus-1
```
Unknown keys/profiles are rejected. The German executable and calendar are required.
| Table | Classic | Classic-plus-1 |
| --- | ---: | ---: |
| League sizes, German divisions | 18/18/18/18/18 | 18/18/18/18/18 |
| Spain/England/France/Italy | 12/12/12/12 | 18/20/18/18 |
| League clubs | 138 | 164 |
| Cup-only clubs | 30 | 30 |
| League and cup records | 168 | 194 |
| Other foreign clubs | 189 | 189 |
| National teams | 62 | 62 |
| All club/country entries | 419 | 445 |
| Players | 2,574 | 3,334 |
| Clubs with 24 roster slots | 90 | 164 |
| First market slot | 2,928 | 3,936 |
| First national roster slot | 3,072 | 4,080 |
| First extra-player slot | 3,096 | 4,104 |
| Total runtime slots | 3,150 | 4,158 |
Player identifiers still use twelve bits, with 4,095 reserved for empty. **An absolute roster slot is not a player identifier**: extended auxiliary slots exceed 4,095 and must not be masked. Club identifiers fit existing packed club fields and crest selectors fit nine bits.
## Master database and artwork
The M3D table order and encoding remain unchanged. Kit selectors scale with all club/country entries; short-name offsets and auxiliary words scale with league-plus-cup entries. The squad master has four fewer rows than runtime, because temporary transfer rows are inserted during career initialization. String pools retain unsigned 16-bit offsets. Imported names use ISO 646-DE, with explicit transliteration of unsupported letters.
The preparation script keeps original player words and original IDs, appends supplemental players and records the source-to-runtime club mapping. Existing twelve-club foreign cores are retained; additional clubs are ranked by donor mean player strength. Missing-person data are not silently fetched or invented. Every supplied provenance/fictional-field note is retained in the private import report.
Crests are fitted into 38-by-38 cells of 304-by-38 VGA sheets, using the supplied VGA palette. No PNG/SVG decoder is needed at runtime. Transparency is index zero for these generated crest cells. Existing protected crest cells remain intact. Repeated Original placeholder images are rejected rather than counted as real club crests. Missing crests use explicitly fictional vector monograms, and dark monochrome logos can use a light contrast variant; both are recorded per club. Asset source and rights notes remain separate from the application's GPL license.
The offline preparation utility accepts local paths:
```sh
python3 -m venv asset-tools
asset-tools/bin/pip install Pillow CairoSVG
asset-tools/bin/python tools/poc/prepare_international.py \
--source /path/to/supplied/german-game \
--supplement /path/to/supplied/season.obw \
--output /path/to/new/private-data
```
The destination must not exist. Inputs are never overwritten. Original content and private import reports must stay outside public source trees, issues and CI artifacts.
## Save and memory boundaries
Classic containers retain `V2.24`. Extended containers use `O1.1`, checked against the selected installation before state decoding. The table sequence remains familiar, with count-derived sizes for club records, manager/opponent histories, crests, kits and short-name offsets. Extended typed tables must not grow into adjacent globals in the guest-memory compatibility representation.
The result store already reserves nine leagues with 38 rounds and ten matches per round. Expanded scheduling uses each league's own fixture size. The shared foreign calendar supplies 38 dates; each league stops at its own 34 or 38 rounds. Domestic/cup/national flags are preserved. Dates are an experimental calendar policy, not a claim about real-world fixtures.
## Distribution
Public artifacts contain the implementation, build information and corresponding sources. The community data ZIP is prepared privately and separately; existing content provenance and rights are unchanged. The stable 1.0 release line is not replaced by this POC.
+21
View File
@@ -0,0 +1,21 @@
# Standalone community data
The 1.1 community edition can start from `COMMUNITY.OBD` without an installed DOS game. The stable main line and loose Classic installation support remain separate.
`COMMUNITY.OBD` is a compressed read-only resource bundle. It contains the master database, text, palette, formations, desktop layout, fonts, indexed pictures/crests and audio containers required by OpenBMH. These are game content, not application code. Saves, highscores and user layouts remain normal writable files outside the bundle.
The bundle's `RUNTIME.DAT` uses the `OBMHDAT1` schema: data-segment base/length, calendar epoch, resolved badge/environment policies, data-segment bytes and explicitly named auxiliary labels. The exporter discards the DOS header, DOS/4GW loader and machine-code objects. Calendar and verified edition policies are values, rather than retained code fingerprints. This is not a renamed or embedded BMH executable.
The Classic address-view adapter still supplies the existing engine/UI table readers. It reads resource entries directly from the compressed bundle, without unpacking original executables or a cached DOS installation. Bundle paths are case-insensitive and reject duplicate/path-traversal entries; compressed/uncompressed limits bound allocations. Original loose installations retain their loading path.
Offline preparation from privately supplied resources:
```sh
cmake --build build --target export_community_runtime
python3 tools/poc/bundle_community.py --source /path/to/prepared-data \
--exporter /path/to/build/export_community_runtime --out /path/to/new/community-data
```
Only required resource types are included. DOS programs, installers, editor executables, original saves, backup directories, manuals and unused picture formats are excluded. Import provenance stays in `IMPORT-REPORT.json`; `PACKAGE.json` records the hashes of the bundled resources. A bundled `OBMHPROF.INI` selects the expanded league profile, so no additional loose Original files are needed.
Generated foreign crests now use the supplied Original domestic crest background texture. Transparent edges are composited onto that bright texture before palette reduction; actual black logo details remain black. The previous black rectangles and the light-on-dark monochrome workaround are removed.
+22
View File
@@ -0,0 +1,22 @@
# International-league POC
Working branch: `poc/1.1-international`, based on `v1.0.2`. Stable main remains separate.
Implemented:
- Explicit `OBMHPROF.INI` metadata; unmarked installations retain Classic dimensions.
- Five German divisions unchanged; international sizes 18/20/18/18, 164 league clubs.
- Twenty starting players and 24 slots per league club; 4,158 runtime roster/auxiliary slots.
- Profile-aware master-database and executable-data views, preserving executable bytes on disk.
- Count-derived club records, opponent histories, kit/short-name and fair-play tables.
- Per-league fixtures and 38 foreign calendar dates, with smaller leagues stopping at 34 rounds.
- Extended save identity `O1.1`; Classic retains `V2.24` and its existing dimensions.
- Offline private data preparation, provenance, crest fitting and Original-format VGA output.
Local integration evidence so far: the expanded career completed 180 turns with seed 1 (three season ends), and another 180 with seed 11 (two season ends). No simulator invariant violations or contract-policy errors were reported. These are automated manager-policy runs, not claims of complete human gameplay QA or validation of all editions/platforms.
The prepared private dataset has 445 club/country entries, 3,334 players and 263 individual foreign club crests. Original German rosters and all 2,574 Original player word records are preserved by assertions during preparation. The visual review identified 175 usable supplied foreign crests and 88 missing/shared Original placeholders. Those 88 now have explicit fictional club-specific monograms instead of the computer symbol; the updated crest preparation uses the bright Original background texture and preserves black logo details. Donor fields retain their real/fictional provenance. No original game content is committed here.
Validation: 37 configured synthetic tests executed successfully, with 158 external-input tests explicitly skipped; four offline preparation tests passed. Extended save/reload and both cross-profile rejection paths passed. Two separate season-end snapshots each contain every fixture in all nine leagues. A Classic 80-turn run produces a byte-identical save to stable 1.0.2. Screenshots and saves are archived privately. Native platform CI also builds and tests Windows x64, macOS ARM64 and Linux x64; release QA receipts identify the exact successful revision. See [FORMAT.md](FORMAT.md) for dimensions, preparation and distribution boundaries. A development commit is not a completed release claim.
The next community package uses a data-only `COMMUNITY.OBD` bundle and no DOS executables. See [STANDALONE.md](STANDALONE.md). The Windows community ZIP omits source archives and loose PNG/JPEG studies; corresponding sources remain available separately.
-44
View File
@@ -1,44 +0,0 @@
OpenBMH v0.1.0
===============
OpenBMH ist eine eigenstaendige Neuumsetzung der Engine von Bundesliga Manager
Hattrick und der englischen Fassung Football Limited. Die englische Unterstuetzung
ist experimentell. Originale Spielinhalte sind nicht enthalten; du benoetigst eine
eigene unterstuetzte Installation. Originale V2.20-Spielstaende der englischen
Fassung sind nicht mit dem unterstuetzten Speicherlayout austauschbar.
Start
-----
Paket in einen eigenen Ordner oder neben die Installation entpacken.
openbmh_play starten (unter Windows openbmh_play.exe). Der Dateidialog nimmt einen
Spielordner, die Programmdatei oder ZIP/7z mit einer einzelnen Installation an.
Aus einem Terminal:
openbmh_play --data "path/to/game" --save-directory "path/to/saves"
openbmh_cli --console --data "path/to/game" --saves "path/to/saves"
Unter Windows den Programmnamen um .exe ergaenzen. Ein beschreibbarer separater
Spielstandordner wird empfohlen. Vorhandene Spielstaende vorher sichern.
Tonoptionen: --mute, --no-music, --volume 0.5. --version zeigt die Programmversion.
In der Konsole zeigt ListOptions die aktuellen Befehle; eine eigene Zeile go.
fuehrt den eingegebenen Block aus. Help beschreibt die Parameter.
Dokumentation und Rueckmeldungen
-------------------------------
README.md enthaelt die Bauanleitungen fuer Windows, Linux und macOS.
Die Releasehinweise beschreiben den Umfang und die bekannten Grenzen.
Linux benoetigt je nach Paket Systembibliotheken, insbesondere GTK3 fuer den
Standard-Dateidialog. Plattform-Bauhinweise sind kein Nachweis eines nativen Tests.
Fehler mit Programmversion, Spielfassung und kurzen eigenen Schritten melden.
Keine Originaldateien, Spielbilder, Aufnahmen, Textlisten oder Spielstaende in
oeffentliche Issues hochladen.
Lizenz
------
Eigener OpenBMH-Code und Dokumentation: GNU GPL Version 3 ausschliesslich
(GPL-3.0-only). LICENSE enthaelt den vollstaendigen Text. Drittanbieter behalten
ihre Lizenzen; siehe THIRD_PARTY_NOTICES.md und docs/licenses/.
Diese Lizenzen gelten nicht fuer die separat benoetigten Originalinhalte.
OpenBMH ist ein unabhaengiges Projekt ohne Verbindung oder Billigung durch die
urspruenglichen Rechteinhaber, DFL oder Bundesliga.
-60
View File
@@ -1,60 +0,0 @@
# OpenBMH v0.1.2
OpenBMH reconstructs the Bundesliga Manager Hattrick engine in C++20. The graphical client uses SDL2; the console provides command batches and local manager-client transports over the same career session. This release needs a supported game installation supplied by the player. No original executable, artwork, music, text database, manual or saved game is included.
## Changes in 0.1.2
- The environment menu shows all six original artwork panels: three youth teams,
assistant coach, doctor and physio. Youth panels include their league and rank.
- All six monthly budgets can be set directly to zero through six stars. Youth
development, season promotion/relegation, finance previews and monthly accounts
share those values. Existing academy lump-sum saves retain their paid status.
- Match-minute pacing follows the loaded original delay setting; A9 in Settings
allows faster or slower progression. No fixed 250-ms pause is added. Retrace
animations use the original reference rate on different host monitors.
- External test fixtures are now recognised correctly by CMake instead of being
reported as unavailable despite configured paths.
See [compatibility decisions](../../COMPATIBILITY.md) for youth recruitment and
legacy contract handling. The previous UI corrections remain included.
## Changes in 0.1.1
- Live lineup navigation preserves the saved pitch view and allows repeated switches between the team list and pitch. Right-click can leave the dialog even when the pointer moves between press and release ([#1](https://github.com/Weyoune/openbmh/issues/1)).
- The instruction panel restores original control symbols, substitute information, red coverage on player hover and pitch-position hints ([#2](https://github.com/Weyoune/openbmh/issues/2)).
- Right-click cancels load/save dialogs, including settings and desktop-layout files ([#3](https://github.com/Weyoune/openbmh/issues/3)).
- Save filenames accept typing immediately, replace a selected existing name and support Ctrl+A/Cmd+A. This also applies to desktop layouts saved as MEN files ([#4](https://github.com/Weyoune/openbmh/issues/4)).
These corrections passed targeted UI/controller checks and Linux SDL input replays, including normal and Reality matches, substitutions, file writing and a fresh-process reload. Physical macOS window verification remains human QA. Use packages from 0.1.1 or later to test these fixes; older 0.1.0 builds do not include them.
## Scope
The engine includes career management, leagues and cups, transfers and contracts, finances, training and camps, stadium management, live match interventions, audio playback and normal saves. Supported actions remain subject to mode, manager and phase restrictions; an unimplemented path reports an explicit error rather than an invented result. The project aims for recognisable behaviour and plausible results, not a promise that every original version produces identical events.
German game editions are the primary compatibility target. **Football Limited support is experimental.** English installation loading and edition-specific text/layout data are supported paths, while original V2.20 save import, English audio and remaining competition/interface differences have limitations. A known limitation can reject an English save made after the first calendar
advance: the saved turn cursor may no longer match the active calendar. Initial
save/reload works; a complete English career is not yet verified. Check current
issues before relying on a particular English workflow.
## Compatibility decisions
OpenBMH uses shared rule values across supported German editions, with installation-specific content read from the selected data. It includes safety handling around invalid input, calendar boundaries, capacity checks and suspended operations. See [compatibility decisions](../../COMPATIBILITY.md) and [architecture](../../architecture.md). This is an independent reconstruction, not an official update to the original game.
## Running
Extract the package to a separate directory or alongside your installation. `openbmh_play` can select a game directory, executable or a ZIP/7z containing one supported installation. Use an explicit writable save directory when the original directory is read-only, and keep backups.
```sh
openbmh_play --data "path/to/game" --save-directory "path/to/saves"
openbmh_cli --console --data "path/to/game" --saves "path/to/saves"
```
Version 0.1 ships binary packages for Windows x64, macOS on Apple silicon (arm64, macOS 11 or later) and Linux x64. The Linux package passes the automated build and tests but has not yet been played natively; reports are welcome. The macOS package is not signed or notarized, so Gatekeeper asks for confirmation on first start: open it once via right-click → Open, or allow it under System Settings → Privacy & Security. Packages and their native platform results are listed with the release assets. The [build instructions](../../BUILDING.md) cover Windows, Linux and macOS source builds; an instruction is not a claim of native acceptance. Linux's default file dialog backend requires GTK3 system libraries. A macOS terminal executable is distinct from a signed application bundle.
## License
The matching application source tag is [v0.1.2](https://github.com/Weyoune/openbmh/tree/v0.1.2). Source/build and relinking materials for linked components must also accompany or be offered with binary releases under their licenses.
OpenBMH-owned code and documentation use GPL-3.0-only. Third-party components retain their licenses; the full texts accompany the package. Read [LICENSE](../../../LICENSE) and [THIRD_PARTY_NOTICES](../../../THIRD_PARTY_NOTICES.md). These licenses do not grant rights to original game content.
For reports, include the OpenBMH version, data edition, independently written steps and the observed result. Do not upload original files, game screenshots, recordings, text collections or saved games to public issues.
+43
View File
@@ -0,0 +1,43 @@
# Classic 1.0 backport audit
Baseline: v0.1.2. The release branch keeps the existing public history; the baseline restoration is an ordinary commit, not a force reset of main.
| Later change | Decision |
|---|---|
| 8326a23: host filenames/path display, setup input guards | Included; direct-installation code, uses direct original-installation data |
| e1d17d8: explicit quit confirmation | Included; cancellation preserves current owner/state |
| c8f04d0: reschedule undo replay bit | Included; restores original target-day availability |
| b879d5b: standalone original message texts | Included as a focused adaptation; reads the original message table |
Version 1.0 no longer rewrites loaded rule tables to a shared profile. Original strength ranges and environment price steps are installed from the supplied edition. Environment implementations outside verified program fingerprints remain unverified, never silently enabled by a directory name.
This is an implementation audit, not a completed release acceptance report. Original-data, GUI, save compatibility and platform results must be recorded before the final tag.
## Diamond 3.7 foreign crests
The drawing policy is installed from the verified gate in the supplied executable.
Diamond 3.7 uses individual original W-sheet cells for the 48 foreign league clubs.
Earlier verified editions retain their neutral foreign-club crest. Database and
savegame selectors remain authoritative, including after club movement; no
high-resolution replacement pack or changed competition structure is required.
Unknown drawing gates retain the conservative legacy policy. National teams,
non-rostered clubs and missing-club tokens retain their existing treatment.
Private data verification decoded all 48 Diamond 3.7 selections and checked their
38-pixel cells against atlas bounds. This is an asset-path/contact-sheet check,
not a claim of completed interactive GUI acceptance.
## Author-supplied defect reference
The Diamond author supplied a private reference catalogue covering 33 original
bug corrections. The supplied original executable hash and all 1,084 documented
byte changes were independently checked against local original/Diamond files.
The archive and disassembly remain outside this public repository. Binary patch
caves are evidence of the old defect, not an implementation requirement.
Initial source review finds corrected camp field packing and separated card
save-back contexts already present. Their dedicated regression acceptance is
still pending. Transfer-market retirement is now corrected and covered by a
synthetic season-boundary regression test, including relocation uniqueness and
unchanged club-player random draws. The complete 33-item review is tracked privately; none of
the unreviewed entries is claimed complete.
+22
View File
@@ -0,0 +1,22 @@
OpenBMH 1.0
Eigenstaendige Community-Umsetzung von Bundesliga Manager Hattrick mit der
Original-Oberflaeche. Originaldateien werden nicht mitgeliefert.
Das Paket vollstaendig entpacken und OpenBMH starten (Windows: OpenBMH.exe).
Die eigene Spielinstallation oder deren ausfuehrbare Datei auswaehlen.
Ein gesondertes, beschreibbares Verzeichnis fuer Spielstaende wird empfohlen.
Beispiel:
OpenBMH --data "path/to/game" --save-directory "path/to/saves"
Deutsche CD-kompatible Versionen und gepruefte Diamond-Ausgaben sind die
primaeren Ziele. Football Limited ist experimentell; die alte Disketten-EXE
wird nicht unterstuetzt. Bestehende Spielstaende vorher sichern.
Quellen, Plattformhinweise und bekannte Einschraenkungen stehen in README.md
und docs/release/1.0/RELEASE_NOTES.md. Reproduzierbare Fehler bitte ueber den
Issue-Tracker des Repositorys melden; keine Originaldateien hochladen.
Eigener Programmcode: GPL-3.0-only. Lizenzen und Hinweise fuer eingebundene
Komponenten stehen in LICENSE und THIRD_PARTY_NOTICES.md.
+37
View File
@@ -0,0 +1,37 @@
# OpenBMH 1.0.2
A left click on an open desktop widget's upper-left close button now hides that widget through the normal validated layout transaction. The close button no longer starts a drag or shows the moving outline. Moving an element with the right mouse button remains available.
The close action consumes its matching mouse release even if the engine has already removed the widget, preventing an accidental click on an icon underneath. The automation and macOS keyboard fixes from 1.0.1 remain unchanged.
---
# OpenBMH 1.0.1
The automatic-lineup monitor now draws the selected formation from the actual manager formation table. Outdoor, indoor and custom formation slots retain their original coordinates and palette. Dragging a desktop element shows the original yellow outline, which disappears when the drag ends.
SDL video initialization now precedes the initial native file picker. On macOS this lets SDL establish the Cocoa application and keyboard activation policy before the picker creates or modifies NSApp. It addresses keyboard input missing throughout the game, including entering the manager name. A native macOS regression checks the activation policy after the picker initialization/shutdown lifecycle.
Native interactive Mac keyboard acceptance remains human QA; automated checks do not represent physical typing on a user's Mac.
---
# OpenBMH 1.0.0
Classic direct-installation runtime restored from v0.1.2. The game executable is OpenBMH / OpenBMH.exe; openbmh_cli remains available.
Reviewed backports include host filename/path handling, explicit quit confirmation, original message text installation in standalone tools, and clearing the calendar replay flag after undoing a reschedule. German CD-compatible BMH and verified Diamond editions are the release targets. Football Limited remains experimental; the old floppy executable is unsupported.
This community release focuses on the original game. See VALIDATION.md for the scope and limits of its checks. Build/test reports do not establish complete bit-for-bit parity with every original edition.
Diamond 3.7 foreign league crests use the supplied edition's original drawing gate, database selectors and W sheets. Older editions retain their original neutral foreign-club crest.
Transfer-market players now enter the season-boundary retirement process, preventing the five-bit age from wrapping from 47 to 16. Relocated free agents no longer leave a duplicate in their old market slot. Young club players retain their existing random-draw count.
The automatic lineup reads the original foreign-player limit switch: enabled editions enforce three foreign starters in domestic clubs and two in the foreign leagues, with original reserve replacement and partial-lineup handling. Editions that disable this rule retain unrestricted selection. New careers also initialize the original empty EM qualification placeholders with national-team IDs; existing nonzero seeds and loaded savegames are preserved.
Known limits: Football Limited remains experimental, the floppy executable is unsupported, and intentional implementation differences remain listed in docs/DIFFERENCES.md. The supplied original-defect catalogue is an ongoing compatibility reference, not a claim that all its entries have received independent runtime acceptance.
The season reset processes each player only once, including temporary offer references to an active club player. This prevents double ageing and regeneration of a still-owned player into a second club. The correction is covered by a synthetic cached-offer regression and long runs through eleven to twelve season-end desks.
The start year and weekday are read from the supplied edition for the desktop, engine and save-list headers. Original CD therefore starts in 1995 on Saturday; checked Diamond editions retain 2026 on Wednesday. The original date arithmetic remains intact.
+45
View File
@@ -0,0 +1,45 @@
# OpenBMH 1.0 validation
Scope: recorded automated/original-data checks. Exact final source revision and native platform build records accompany the published release.
- Linux x64 Release build: all targets compiled.
- Local Linux CTest: 35 passed, 157 skipped, zero failures (192 registered tests). Skips require separately configured original-data or save fixtures; they are not acceptance passes.
- Synthetic tests cover unchanged executable image loading, nine original strength ranges, atomic rejection of malformed ranges, unsupported environment guards, and legacy/extended/truncated crest gates.
- Public source scan: zero findings; generated differences catalogue matches source markers.
- Version output: both GUI and console identify 1.0.0-rc.1.
- Private crest probe: all 48 foreign league clubs in Diamond 3.7 resolve to original 38 × 38 W cells within atlas bounds. A native-size contact sheet was inspected; older Diamond data retain the neutral-crest gate.
- Author defect reference: original hash and all 1,084 listed original/changed bytes checked. All 33 defects are tracked privately; source inspection is not regression acceptance.
Still required: dedicated original-game/GUI/save roundtrips, completing the original-defect audit, per-edition gameplay review, Windows/macOS native checks and release-package acceptance. No final 1.0 tag is justified by these checks alone.
Source archives contain the audited current tree. The optional full-history audit is a separate check; published Git history has not been rewritten.
## Follow-up original-data checks
Twenty-six additional private-data checks passed across BMH CD and Diamond 3.6/3.7: exact loaded fixture tables, manager selection, standard dialogs, training camps, tactics, banking, settings and player cards. The Diamond 3.6 two-manager fixture also passed the human-buyer transfer and rescheduling suites. A currency-format fixture had assumed the Diamond resort price for all German editions; its fixed-price check now uses an explicit synthetic price, and the CD test passes without changing game data or product prices. These are automated render/interaction and engine checks, not a claim of complete interactive playthroughs.
The market-player retirement regression failed before the correction with an age wrap from 47 to 16 and passed afterward. It checks market boundaries, unique relocation, unaffected extra slots, new-career setup and unchanged random draw counts for a young club player.
## Additional edition rules
Targeted synthetic tests pass for the enabled/disabled foreign-player switch, domestic and foreign clubs, human assistant board and card-row movement, reserve shortages and switching back to an unrestricted edition. Separate season-boundary tests pass for zero EM placeholders becoming national teams and existing nonzero seeds remaining unchanged. Final full-build/platform acceptance for these additions is recorded with the release artifacts.
Long-run diagnostics with seed 4711 and the existing explicit contract-renewal policy reached 120 turns and two season-end desks in each of the three German data editions. Diamond 3.6/3.7 returned success. Original CD exceeded the simulator's statistical high-score threshold (two ordinary results above twelve goals); it is recorded as a QA finding, not hidden or counted as a successful simulation. The earlier no-presenter runs stopped at a contract expiry; enabling the existing opt-in presenter resolved that harness limitation without changing gameplay code.
## Extended season regression
After the final lineup, qualification and once-per-player season-reset corrections, each German edition completed 600 turns using seed 4711. Original CD reached twelve season-end desks; Diamond 3.6 and 3.7 reached eleven each. With the existing explicit contract-renewal and advertising policies enabled, all three simulator runs returned success, with no duplicate club players or other invariant failures. With contract renewals alone, all three still completed 600 turns without duplicate club players; only the test policy's excessive-debt warning remained. The latter is not presented as a successful financial strategy.
The duplicate-player defect was reproduced and captured before correction: a temporary offer referenced a player already owned by a club, then the extended market-retirement pass regenerated that player a second time. Frozen private before/after saves and a cached-reference regression support the correction. Save-envelope diagnostics use a separate RNG and do not consume either gameplay stream.
Calendar epoch regression covers the original CD and Diamond parameters, engine weekdays, desktop dates, save-header dates, year rollover and atomic rejection of invalid/unknown setup instructions. The original and checked Diamond date routines differ only in their weekday/year operands. After installing the original CD calendar parameters, the 600-turn run with contract and advertising policies completed eleven season-end desks without invariant failures.
## 1.0.1 desktop and macOS regressions
The desktop feedback test checks selected saved formations against their original table, compares changed miniature pixels, and checks the original yellow outline during a drag and its removal afterward. Private CD and Diamond render captures use the original assets. The SDL lifetime test checks initialization before the picker scope, normal destruction and failed initialization cleanup.
A macOS-only native Cocoa test initializes SDL before the native picker lifecycle, checks regular activation, creates a keyboard-focused window and verifies that a Cocoa key event produces both SDL key and text events. This automated native event test supplements human keyboard QA; it is not a claim of physical typing on the user's machine.
## 1.0.2 close-button regression
The desktop feedback test checks that the left corner requests removal instead of entering drag mode, that the remaining layout chain is intact, and that the release after acknowledgement does not activate an underlying icon. A subsequent independent click remains usable. Right-button movement and its temporary yellow outline remain covered. The user confirmed the 1.0.1 automation and Mac keyboard corrections.
+9
View File
@@ -0,0 +1,9 @@
# OpenBMH 1.1 Beta 2
Bei Rückfragen zum Bau von Stadionplätzen und Peripherie bleibt die aktuelle Stadionansicht jetzt sichtbar. Das gilt auch für gedrückte Schaltflächen und nachfolgende Zahlungs-, Zuschuss- und Entschädigungshinweise. Der zuvor schwarze Hintergrund ist behoben.
Die Änderung betrifft die Darstellung; Baupreise, Bauzeiten und Spielstände bleiben unverändert. Bestehende 1.1-Daten und Spielstände können weiterverwendet werden. Bei einem bestehenden Community-Paket die Programmdateien aktualisieren und die eigene `COMMUNITY.OBD` sowie Spielstände behalten.
Downloads für Windows x64, macOS ARM64 und Linux x64 sowie ein passendes Source-Archiv. Originale Spieldaten sind nicht enthalten. Der Dateneditor `obdeddi` bleibt ein separater Download. Die stabile Classic-Linie 1.0 bleibt unabhängig; 1.2 wird weiterhin separat entwickelt und ist kein Bestandteil dieses Releases.
Der Fix wurde unter Linux mit Original-Assets, Pixelvergleichen und Bauablauf-Tests geprüft. Native Plattform-Builds und synthetische Tests sind über `QA-REPORT.json` und `SHA256SUMS` dokumentiert. Eine vollständige menschliche Spielprüfung auf allen Plattformen wird damit nicht behauptet.
+43 -36
View File
@@ -1,5 +1,8 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/badge_policy.hpp"
#include "game/calendar.hpp"
#include "formats/executable_layout.hpp"
#include "formats/data_profile.hpp"
#include "app/career_session.hpp"
#include <stdexcept>
@@ -69,7 +72,7 @@ int national_opportunities_rank(const GameState& game,int team,std::array<uint8_
ranks.fill(1);
const int rounds=game.league_rounds.empty()?0:int8_t(game.league_rounds.at(0));
if(rounds<2||rounds>=league_matchdays(0))return 0;
return team>=138?9:0;
return team>=runtime_dimensions.league_teams?9:0;
}
uint8_t source_runtime_byte(const GameState& state,const std::map<uint32_t,uint8_t>& runtime,
@@ -539,16 +542,20 @@ static void install_league_sizes(const LeImage& exe) {
kNewcomerFirst = exe.u16(::bmh::layout::CareerSession_DispatchLineup_RuntimeField);
kNewcomerCount = exe.u16(::bmh::layout::CareerSession_InstallLeagueSizes_RuntimeField6);
// EXE strings the engine posts (messages.hpp)
kContractEndsSoonText = exe.cstring(kEnglishCompetitions ? ::bmh::layout::EnglishContractExpiryWarningText : ::bmh::layout::ContractExpiryWarningText);
kMastersQualificationText = kEnglishCompetitions ? "Masters entry confirmed. Your participation bonus has been credited." : exe.cstring(::bmh::layout::MastersQualificationText);
kMastersWinnerText = kEnglishCompetitions ? "Masters title won. Your prize money has been credited." : exe.cstring(::bmh::layout::MastersWinnerText);
kIndoorInvitationText = kEnglishCompetitions ? "Indoor event entry bonus credited for " : exe.cstring(::bmh::layout::IndoorInvitationText);
kChampionshipBonusText = kEnglishCompetitions ? "League title bonus credited." : exe.cstring(::bmh::layout::ChampionshipBonusText);
kFriendlyPayerPrefixText = kEnglishCompetitions ? "Your share: " : exe.cstring(::bmh::layout::NationalFriendlyPayerPrefixText);
install_message_texts(exe);
install_career_rules(exe);
install_environment_rules(exe);
install_original_badge_policy(exe);
install_calendar_rules(exe);
}
static std::filesystem::path install_session_profile(const std::filesystem::path& data) {
install_runtime_profile(load_data_profile(data));
return data;
}
CareerSession::CareerSession(const std::filesystem::path& data, uint32_t watcom_seed)
: data_directory_(data), exe_(load_le(data / "BMH.exe")),
: data_directory_(install_session_profile(data)), exe_(load_le(data / "BMH.exe")),
db_(load_database(data / "M3D.MAN")),
texts_(load_textd(data / "TEXTD.BLK")),
rand_(watcom_seed) {
@@ -575,7 +582,7 @@ CareerSession::CareerSession(const std::filesystem::path& data, uint32_t watcom_
CareerSession::CareerSession(const std::filesystem::path& data, uint32_t watcom_seed,
const std::filesystem::path& save_path)
: data_directory_(data), exe_(load_le(data / "BMH.exe")), db_(load_database(data / "M3D.MAN")),
: data_directory_(install_session_profile(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_);
turn_driver_.alternate_match_event_roll = exe_.u8(::bmh::layout::AlternateEventRoll) != 0;
@@ -585,8 +592,8 @@ 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();
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)};
if (!file.checksum_ok || file.version != (runtime_dimensions.expanded ? "O1.1" : "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), db_.counts.league_teams, db_.counts.cup_teams};
const SaveState save(file.stream, counts);
g_ = GameState::from_save(save, counts);
// CompetitionPointers2, after DeskDate2: these are process statics, not FBM fields.
@@ -1277,7 +1284,7 @@ std::optional<ui::StrengthsIdentity> CareerSession::begin_friendly_opponent_tabl
uint64_t revision,std::string& error) {
error.clear();
const auto request=strengths_open_request(revision);
if(!request||request->identity.runtime_club>=168||request->identity.source_param2||
if(!request||request->identity.runtime_club>=runtime_dimensions.record_teams||request->identity.source_param2||
league_family_owner_||strengths_owner_||league_pairings_draft_) {
error="friendly table: unavailable club entry";return {};
}
@@ -1325,7 +1332,7 @@ std::optional<int> CareerSession::resolve_friendly_table_opponent(
if(visible.runtime_team_id!=request.runtime_team||visible.club_identity_key!=request.expected_club_identity||
visible.runtime_team_id<0||size_t(visible.runtime_team_id)>=g_.club_ids.size()||
visible.club_identity_key!=int(g_.club_ids[size_t(visible.runtime_team_id)])||
normal.rank!=row+1||normal.runtime_team_id<0||normal.runtime_team_id>=168||
normal.rank!=row+1||normal.runtime_team_id<0||normal.runtime_team_id>=runtime_dimensions.record_teams||
size_t(normal.runtime_team_id)>=g_.club_ids.size()||
normal.club_identity_key!=int(g_.club_ids[size_t(normal.runtime_team_id)])) {
error="friendly table: opponent row identity changed";return {};
@@ -1782,13 +1789,13 @@ std::optional<CareerSession::LiveOverviewProjection> CareerSession::open_running
// CupGroupOverviewEffects resolves this exact active descriptor through FindCup(selector, ordinal).
const int competition_id = int16_t(g_.memory.u16(cup_entry_address(entry_index)+0x18));
int stable_team = request.runtime_team;
if (stable_team > 0x164) {
if (stable_team > (kNoTeam - 1)) {
const size_t backup = 4 * 0xb0c + 0x290;
if (request.manager_slot != 0 || backup + 2 > g_.manager_records.size())
throw FormatError("live overview: unsupported national cup owner");
stable_team = int(uint16_t(g_.manager_records[backup] | uint16_t(g_.manager_records[backup+1])<<8));
}
if (stable_team < 0 || stable_team >= 138 || size_t(stable_team) >= g_.club_ids.size())
if (stable_team < 0 || stable_team >= runtime_dimensions.league_teams || size_t(stable_team) >= g_.club_ids.size())
throw FormatError("live overview: missing stable cup owner identity");
ui::OtherGamesIdentity identity;
identity.manager_slot=request.manager_slot; identity.runtime_team=request.runtime_team;
@@ -2258,7 +2265,7 @@ std::optional<ui::StrengthsIdentity> CareerSession::dispatch_family_table_team_i
if(poach_selection && *poach_selection) {
const auto chosen=club_player_detail_context(next,**poach_selection);
if(chosen.selection.runtime_team!=selected_team || chosen.source_slot<0 ||
chosen.source_slot>=0xb70 || chosen.human_loan)
chosen.source_slot>=runtime_dimensions.pool_first || chosen.human_loan)
throw FormatError("poach: card returned a different ordinary squad player");
refreshed.expected_family_word=next.memory.u16(family_word_at);
// A successful param1=1 selection leaves50775 here. Its common
@@ -2574,12 +2581,12 @@ std::optional<ui::TopScorersState> CareerSession::open_top_scorers(
throw FormatError("top scorers: unsupported national-coach owner");
stable_team = int(uint16_t(g_.manager_records[backup] |
uint16_t(g_.manager_records[backup + 1]) << 8));
} else if (team < 0 || team >= 138) {
} else if (team < 0 || team >= runtime_dimensions.league_teams) {
throw FormatError("top scorers: manager team is outside Source league scope");
}
if (stable_team < 0 || stable_team >= 138 || size_t(stable_team) >= g_.club_ids.size())
if (stable_team < 0 || stable_team >= runtime_dimensions.league_teams || size_t(stable_team) >= g_.club_ids.size())
throw FormatError("top scorers: missing stable club identity");
const int league = team > 0x164 ? 0 : team_league(team);
const int league = team > (kNoTeam - 1) ? 0 : team_league(team);
if (league < 0 || league > 8)
throw FormatError("top scorers: manager has no supported Source league");
@@ -2644,7 +2651,7 @@ std::optional<CareerSession::TopScorersDispatch> CareerSession::dispatch_top_sco
(backup + 2 <= g_.manager_records.size() ?
int(uint16_t(g_.manager_records[backup] |
uint16_t(g_.manager_records[backup + 1]) << 8)) : -1) : identity.runtime_team;
if (identity_team < 0 || identity_team >= 138 ||
if (identity_team < 0 || identity_team >= runtime_dimensions.league_teams ||
size_t(identity_team) >= g_.club_ids.size() ||
int(g_.club_ids[size_t(identity_team)]) != identity.club_identity)
throw FormatError("top scorers: stable club identity changed");
@@ -2747,9 +2754,9 @@ std::optional<ui::OpportunitiesState> CareerSession::open_opportunities(
const int manager=request.manager_slot,team=g_.manager_teams[size_t(manager)];
const int league=national_source_case?0:team_league(team);
if(national_source_case) {
if(team!=0x165||league!=0)throw FormatError("opportunities: invalid national menu-6 owner");
if(team!=kNoTeam||league!=0)throw FormatError("opportunities: invalid national menu-6 owner");
if(stable_identity<0)throw FormatError("opportunities: missing national Desk identity");
} else if(team<0||team>=138||size_t(team)>=g_.club_ids.size()||league<0||league>=9)
} else if(team<0||team>=runtime_dimensions.league_teams||size_t(team)>=g_.club_ids.size()||league<0||league>=9)
throw FormatError("opportunities: unsupported team/league");
if(underlay.width!=320||underlay.height!=240)throw FormatError("opportunities: expected captured 320x240 desktop");
const uint32_t choice_at=::bmh::layout::CareerSession_FormatError_ExecutableField+uint32_t(manager)*2;
@@ -2786,7 +2793,7 @@ std::optional<CareerSession::OpportunitiesDispatch> CareerSession::dispatch_oppo
uint32_t(g_.date)!=current.identity.day_counter||
size_t(current.identity.runtime_team)>=g_.club_ids.size()||
(!national_source_case&&int(g_.club_ids[size_t(current.identity.runtime_team)])!=current.identity.stable_club_identity)||
(national_source_case&&(current.identity.runtime_team!=0x165||
(national_source_case&&(current.identity.runtime_team!=kNoTeam||
current.identity.stable_club_identity<0)))
throw FormatError("opportunities: desk owner changed");
OpportunitiesDispatch result;result.page=current;
@@ -2866,14 +2873,14 @@ std::optional<ui::OtherGamesState> CareerSession::open_other_games(
uint16_t(next.manager_records[record + 0x291]) << 8) != uint16_t(team))
throw FormatError("other games: manager record does not own the active team");
int stable_team = team;
if (team > 0x164) {
if (team > (kNoTeam - 1)) {
const size_t backup = 4 * 0xb0c + 0x290;
if (manager != 0 || backup + 2 > next.manager_records.size())
throw FormatError("other games: unsupported national-coach owner");
stable_team = int(uint16_t(next.manager_records[backup] |
uint16_t(next.manager_records[backup + 1]) << 8));
}
if (stable_team < 0 || stable_team >= 138 || size_t(stable_team) >= next.club_ids.size())
if (stable_team < 0 || stable_team >= runtime_dimensions.league_teams || size_t(stable_team) >= next.club_ids.size())
throw FormatError("other games: missing stable manager club identity");
const uint8_t source_view = next.memory.u8(::bmh::layout::CareerSession_DispatchOtherGames_RuntimeField + uint32_t(manager));
@@ -2964,13 +2971,13 @@ std::optional<CareerSession::OtherGamesDispatch> CareerSession::dispatch_other_g
uint16_t(id.runtime_team))
throw FormatError("other games: manager record changed");
int stable_team = id.runtime_team;
if (id.runtime_team > 0x164) {
if (id.runtime_team > (kNoTeam - 1)) {
const size_t backup = 4 * 0xb0c + 0x290;
if (id.manager_slot != 0 || backup + 2 > g_.manager_records.size())
throw FormatError("other games: unsupported national owner");
stable_team = int(uint16_t(g_.manager_records[backup] | uint16_t(g_.manager_records[backup + 1]) << 8));
}
if (stable_team < 0 || stable_team >= 138 || size_t(stable_team) >= g_.club_ids.size() ||
if (stable_team < 0 || stable_team >= runtime_dimensions.league_teams || size_t(stable_team) >= g_.club_ids.size() ||
int(g_.club_ids[size_t(stable_team)]) != id.club_identity)
throw FormatError("other games: stable club identity changed");
if (request.action == ui::OtherGamesAction::team_info) {
@@ -3019,10 +3026,10 @@ std::optional<CareerSession::OtherGamesDispatch> CareerSession::dispatch_other_g
uint16_t(next.manager_records[active_record+0x290]|
uint16_t(next.manager_records[active_record+0x291])<<8)!=uint16_t(id.runtime_team))
throw FormatError("other games: TeamInfo changed the active manager record");
const int retained_team=id.runtime_team>0x164
const int retained_team=id.runtime_team>(kNoTeam - 1)
? int(uint16_t(next.manager_records[4*0xb0c+0x290]|
uint16_t(next.manager_records[4*0xb0c+0x291])<<8)) : id.runtime_team;
if(retained_team<0||retained_team>=138||size_t(retained_team)>=next.club_ids.size()||
if(retained_team<0||retained_team>=runtime_dimensions.league_teams||size_t(retained_team)>=next.club_ids.size()||
int(next.club_ids[size_t(retained_team)])!=id.club_identity)
throw FormatError("other games: TeamInfo changed the stable desk club identity");
@@ -3336,7 +3343,7 @@ std::optional<CareerSession::BalanceDispatch> CareerSession::dispatch_balance_pl
notice.manager_name.assign(reinterpret_cast<const char*>(next.state.manager_records.data()+name_at),name_end-name_at);
notice.portrait=next.state.manager_records[record+0x221];
const int club=next.state.manager_teams[size_t(manager)];
notice.badge_fallback=club==0x0fff||(club>89&&club<138)||(club>167&&club<357);
notice.badge_fallback=original_badge_fallback(club,&exe_);
if(!notice.badge_fallback&&club>=0&&size_t(club)*2+2<=next.state.club_heap_78.size())
notice.badge_sprite=(int(next.state.club_heap_78[size_t(club)*2])|
int(next.state.club_heap_78[size_t(club)*2+1])<<8)&0x1ff;
@@ -3575,7 +3582,7 @@ std::optional<CareerSession::TransferOfferEditorDispatch> CareerSession::open_tr
!g_.memory.has(::bmh::layout::ActiveManager) || g_.memory.u8(::bmh::layout::ActiveManager) != request.manager_slot ||
request.runtime_club != g_.manager_teams[size_t(request.manager_slot)] ||
request.bid.manager != request.manager_slot || request.bid.list_entry < 0 || request.bid.list_entry >= 40 ||
request.bid.source_slot != 2928 + request.bid.list_entry || request.selected_players.size() > 1) {
request.bid.source_slot != runtime_dimensions.pool_first + request.bid.list_entry || request.selected_players.size() > 1) {
error = "transfer offer: stale, nested or unsupported marked opening";
return std::nullopt;
}
@@ -3637,7 +3644,7 @@ std::optional<CareerSession::PoachDispatch> CareerSession::open_poach(
result.start = start_poach(next_state, manager_slot, squad_slot, next_rand);
if (result.start.status == PoachStatus::ready) {
const int row = 0x28 + result.start.offer_row;
const TransferOfferEditorRequest input{manager_slot, g_.manager_teams[size_t(manager_slot)], row, 2928 + row,
const TransferOfferEditorRequest input{manager_slot, g_.manager_teams[size_t(manager_slot)], row, runtime_dimensions.pool_first + row,
result.start.player, next_state.memory.u16(::bmh::layout::EditorList + uint32_t(row) * 0x58 + 8), 0, false, true};
auto owner = open_transfer_offer_editor_source(next_state, input, next_game, next_rand);
if (!owner.supported) { error = owner.reason; return std::nullopt; }
@@ -3760,7 +3767,7 @@ bool CareerSession::dispatch_poach_ui(const ui::TransferMarketRequest& request,
throw FormatError("poach: selection is not an ordinary squad row");
const auto player=club_player_detail_context(next,*selection);
slot=player.source_slot;
if(slot<0 || slot>=0xb70 || slot_team(slot)!=selection->runtime_team ||
if(slot<0 || slot>=runtime_dimensions.pool_first || slot_team(slot)!=selection->runtime_team ||
(next.squad_slots.at(size_t(slot))&0xfff)!=selection->player_id)
throw FormatError("poach: stale player selection");
}
@@ -3925,7 +3932,7 @@ std::optional<CareerSession::TransferMarketPreviewDispatch> CareerSession::previ
if (request.preview_snapshot_index != -1 || request.squad_row != -1 || request.bid.manager != request.manager_slot ||
request.bid.list_entry < 0 || request.bid.list_entry >= 40 ||
request.bid.source_slot != request.preview_source_slot ||
request.preview_source_slot != 0xb70 + request.bid.list_entry ||
request.preview_source_slot != runtime_dimensions.pool_first + request.bid.list_entry ||
request.bid.player != request.expected_player) {
error = "transfer market: mismatched preview listing identity";
return std::nullopt;
@@ -7202,7 +7209,7 @@ ui::PreparationState CareerSession::preparation_projection(const GameState& stat
uint16_t(state.manager_records.at(size_t(stadium.manager_slot) * 0xb0c + 0x2ad)) << 8;
const int source_team = int16_t(uint16_t(state.manager_records.at(size_t(stadium.manager_slot) * 0xb0c + 0x290)) |
uint16_t(state.manager_records.at(size_t(stadium.manager_slot) * 0xb0c + 0x291)) << 8);
const int source_league = source_team > 0x164 ? 0 : team_league(source_team);
const int source_league = source_team > (kNoTeam - 1) ? 0 : team_league(source_team);
if (source_league < 0 || size_t(source_league) >= state.league_rounds.size())
throw FormatError("stadium source league is outside the live league table");
stadium.live_league_round = state.league_rounds.at(size_t(source_league));
@@ -7946,7 +7953,7 @@ bool CareerSession::dispatch_stadium(const ui::StadiumRequest& supplied_request,
}
if (request.manager_slot != active || active < 0 || active > 3 ||
size_t(active) >= g_.manager_teams.size() || request.runtime_club != g_.manager_teams[size_t(active)] ||
request.runtime_club < 0 || request.runtime_club >= 357 ||
request.runtime_club < 0 || request.runtime_club >= kNoTeam ||
size_t(request.runtime_club) >= g_.club_ids.size() ||
request.stable_club_identity != std::optional<int>(int(g_.club_ids[size_t(request.runtime_club)])) ||
request.revision != revision || revision == UINT64_MAX || !g_.memory.has(::bmh::layout::GameMode)) {
+16 -15
View File
@@ -1,4 +1,5 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/badge_policy.hpp"
#include "formats/executable_layout.hpp"
#include "app/controller.hpp"
#include "app/window_actions.hpp"
@@ -56,7 +57,7 @@ ui::NationalFriendlyIdentity national_friendly_identity(const GameState& game,in
out.manager_name.push_back(char(game.manager_records[record+0xa8+i]));
out.portrait=game.manager_records[record+0x221];
out.manager_slot=manager;
out.badge_fallback=team==0x0fff||(team>89&&team<138)||(team>167&&team<357);
out.badge_fallback=original_badge_fallback(team);
if(!out.badge_fallback&&team>=0&&size_t(team)*2+1<game.club_heap_78.size())
out.badge_sprite=int(game.club_heap_78[size_t(team)*2]|
uint16_t(game.club_heap_78[size_t(team)*2+1])<<8)&0x1ff;
@@ -144,12 +145,12 @@ void serve_friendly_action(ui::StartupFlow& flow, CareerSession& session,
const auto& national=*request.national_booking;
const auto expected=FriendlyActions::national_owner(request);
if(request.kind!=ui::FriendlyRequestKind::book||!request.quote_id||
request.runtime_team!=0x165||request.opponent<0x166||request.opponent>0x1a2||
request.runtime_team!=kNoTeam||request.opponent<(kNoTeam + 1)||request.opponent>(kNoTeam + 61)||
request.season_day<0||request.season_day>365||request.planner_count<0||
request.planner_count>253||request.revision!=revision||
national.owner!=expected||national.quote.owner!=expected||
national.season_day!=request.season_day||national.quote.terms.manager!=manager||
national.quote.terms.manager_team!=0x165||national.quote.terms.opponent!=request.opponent||
national.quote.terms.manager_team!=kNoTeam||national.quote.terms.opponent!=request.opponent||
national.quote.terms.planner_count!=request.planner_count||
national.quote.terms.home_team!=request.home_team||national.quote.terms.away_team!=request.away_team||
national.quote.terms.payer_manager!=request.payer_manager||
@@ -231,7 +232,7 @@ void serve_friendly_action(ui::StartupFlow& flow, CareerSession& session,
if (request.kind != ui::FriendlyRequestKind::book || request.quote_id == 0 ||
request.season_day < 0 || request.season_day > 365 || request.opponent < 0 ||
request.opponent >= 168 || request.cost < 0 || request.planner_count > 253) {
request.opponent >= runtime_dimensions.record_teams || request.cost < 0 || request.planner_count > 253) {
flow.reject_friendly_action("Die Angaben zum Spieltermin sind ungültig.");
return;
}
@@ -256,13 +257,13 @@ bool valid_national_friendly_family(const ui::StartupFlow& flow,const GameState&
const auto* origin=flow.national_friendly_desk_owner();
const auto* menu=flow.statistics_menu();
const auto* desk=flow.desktop();
if(!owner||!origin||!menu||!desk||owner->desk_menu!=6||owner->runtime_team!=0x165||
if(!owner||!origin||!menu||!desk||owner->desk_menu!=6||owner->runtime_team!=kNoTeam||
owner->manager<0||owner->revision!=revision||origin->kind!=ui::DeskRequestKind::open_menu||
origin->menu_kind!=6||origin->manager_slot!=owner->manager||origin->revision!=revision||
desk->state().revision!=revision||desk->state().manager_slot!=owner->manager||
menu->state().owner.kind!=ui::DeskRequestKind::open_menu||menu->state().owner.menu_kind!=23||
menu->state().owner.manager_slot!=owner->manager||menu->state().owner.revision!=revision||
size_t(owner->manager)>=game.manager_teams.size()||game.manager_teams[size_t(owner->manager)]!=0x165||
size_t(owner->manager)>=game.manager_teams.size()||game.manager_teams[size_t(owner->manager)]!=kNoTeam||
!game.memory.has(::bmh::layout::ActiveManager)||int(game.memory.u8(::bmh::layout::ActiveManager))!=owner->manager)return false;
return true;
}
@@ -277,17 +278,17 @@ void serve_national_friendly_selection(ui::StartupFlow& flow,CareerSession& sess
const auto& game=session.state();
const auto& desk=flow.desktop()->state();
const int manager=owner->manager;
if(owner->desk_menu!=6||owner->runtime_team!=0x165||owner->revision!=revision||
if(owner->desk_menu!=6||owner->runtime_team!=kNoTeam||owner->revision!=revision||
desk_request->kind!=ui::DeskRequestKind::open_menu||desk_request->menu_kind!=6||
desk_request->revision!=revision||desk_request->manager_slot!=manager||
desk.revision!=revision||desk.manager_slot!=manager||manager<0||
size_t(manager)>=game.manager_teams.size()||game.manager_teams[size_t(manager)]!=0x165||
int(game.memory.u8(::bmh::layout::ActiveManager))!=manager||selected_team<0x166||selected_team>0x1a2) {
size_t(manager)>=game.manager_teams.size()||game.manager_teams[size_t(manager)]!=kNoTeam||
int(game.memory.u8(::bmh::layout::ActiveManager))!=manager||selected_team<(kNoTeam + 1)||selected_team>(kNoTeam + 61)) {
flow.close_national_friendly_picker();
return;
}
if(!presenter) { flow.close_national_friendly_picker(); return; }
ui::NationalFriendlyUi dialog_flow(*owner,national_friendly_identity(game,manager,0x165));
ui::NationalFriendlyUi dialog_flow(*owner,national_friendly_identity(game,manager,kNoTeam));
auto venue=dialog_flow.select_opponent(game,selected_team);
if(venue.kind!=ui::NationalFriendlyUiActionKind::show_question||!venue.question) {
flow.close_national_friendly_picker();return;
@@ -320,7 +321,7 @@ void serve_national_friendly_selection(ui::StartupFlow& flow,CareerSession& sess
}
ui::FriendlyQuoteProjection projection;
projection.request_id=quote_request.engine_owner->request_id;
projection.revision=revision;projection.manager_slot=manager;projection.runtime_team=0x165;
projection.revision=revision;projection.manager_slot=manager;projection.runtime_team=kNoTeam;
projection.opponent=selected_team;projection.opponent_manager=quote.terms.opponent_manager;
projection.payer_manager=quote.terms.payer_manager;projection.home_team=quote.terms.home_team;
projection.away_team=quote.terms.away_team;projection.cost=quote.terms.cost;
@@ -335,7 +336,7 @@ void serve_national_friendly_selection(ui::StartupFlow& flow,CareerSession& sess
projection.dates.push_back({day,mark});
}
ui::FriendlyMatchState calendar;
calendar.revision=revision;calendar.manager_slot=manager;calendar.runtime_team=0x165;
calendar.revision=revision;calendar.manager_slot=manager;calendar.runtime_team=kNoTeam;
calendar.current_day=game.season_day();calendar.planner_count=quote.terms.planner_count;
calendar.season_start_counter=game.season_start;calendar.mode_three=desk.options.mode==3;
calendar.national_team=true;calendar.manager_name=ui::original_to_utf8(desk.manager_name);
@@ -956,7 +957,7 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu
const int team=game.manager_teams[size_t(manager)];
if(team!=kNoTeam&&(team<0||size_t(team)>=game.team_flags.size()))
throw FormatError("fair play: active manager has no Source roster");
const int league=team>0x164?0:team_league(team);
const int league=team>(kNoTeam - 1)?0:team_league(team);
page=ui::fair_play_state_from_game(game,league,underlay,manager);
} else {
page.kind=ui::DeskRecordKind::highscore;
@@ -2109,11 +2110,11 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu
const auto& desk = flow.desktop()->state();
const int manager=request.manager_slot;
if(manager>=0&&size_t(manager)<game.manager_teams.size()&&
game.manager_teams[size_t(manager)]==0x165) {
game.manager_teams[size_t(manager)]==kNoTeam) {
const auto projection=ui::world_cup_statistics_from_game(game,
load_le(ui::asset_path(data,"BMH.exe")),
ui::WorldCupStatisticsOwner::friendly_match_nation_picker);
flow.show_national_friendly_picker(projection,request,0x165);
flow.show_national_friendly_picker(projection,request,kNoTeam);
return {};
}
LeagueFamilyActions(*session).apply(revision, [&] {
+162 -109
View File
@@ -1,5 +1,9 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/badge_policy.hpp"
#include "formats/executable_layout.hpp"
#include "app/scene_timing.hpp"
#include "formats/data_profile.hpp"
#include "game/profile_runtime.hpp"
#include "ui/live_timing.hpp"
// openbmh_play - the UI of src/ui connected to the engine: options, manager dialogs, a new
// career initialised by the engine (app/career_session.hpp) and its desk.
@@ -10,6 +14,7 @@
#include <SDL.h>
#include <algorithm>
#include <array>
#include <chrono>
#include <cstdio>
#include <cstdlib>
@@ -24,10 +29,12 @@
#include <vector>
#include "app/controller.hpp"
#include "app/quit_confirmation.hpp"
#include "launch/archive.hpp"
#include "launch/file_dialog.hpp"
#include "launch/game_data.hpp"
#include "version.hpp"
#include "app/video_session.hpp"
#include "app/live_matchday_events.hpp"
#include "audio/playback.hpp"
#include "app/audio.hpp"
@@ -74,6 +81,18 @@ static void show_start_error(const std::string& text) {
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "OpenBMH", text.c_str(), nullptr);
}
// Reattach the native editor when an in-game filename field takes focus. Cocoa
// owns a field-editor responder in addition to SDL's TEXTINPUT enable flag.
static void focus_filename_input(SDL_Renderer* renderer) {
int left, top, right, bottom;
SDL_RenderLogicalToWindow(renderer, 106, 209, &left, &top);
SDL_RenderLogicalToWindow(renderer, 262, 219, &right, &bottom);
const SDL_Rect field{left, top, std::max(1, right - left), std::max(1, bottom - top)};
SDL_StopTextInput();
SDL_SetTextInputRect(&field);
SDL_StartTextInput();
}
#ifdef _WIN32
// The game is a Windows GUI program (no console window on double-click). Started from a
// console, it writes --version, --help and start errors there (kernel32 AttachConsole).
@@ -129,13 +148,16 @@ 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>] "
std::printf("usage: OpenBMH [<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");
return 0;
} else if (args[i].rfind("--", 0) != 0 && data.empty()) {
data = launch::path_from_utf8(args[i]);
}
}
std::optional<app::VideoSession> video;
try { video.emplace(); }
catch (const std::exception& error) { show_start_error(error.what()); 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
@@ -175,11 +197,11 @@ int main(int argc, char** argv) {
}
if (save_directory.empty()) save_directory = data;
try {
install_runtime_profile(load_data_profile(data));
const Palette palette = load_palette(ui::asset_path(data, "M3PC.COL"));
ui::StartupFlow flow(data, save_directory);
std::unique_ptr<app::CareerSession> session;
uint64_t revision = 0;
if (SDL_Init(SDL_INIT_VIDEO) != 0) throw FormatError(SDL_GetError());
openbmh::audio::Playback playback;
std::string audio_error;
playback.initialize(audio_error); // Audio is optional; the game continues without a device.
@@ -187,8 +209,7 @@ int main(int argc, char** argv) {
playback.set_volume(volume);
std::optional<uint64_t> audio_session;
SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "0");
const std::string window_title = std::string("OpenBMH ") + bmh::kOpenBmhVersion +
(english_game ? " - Football Limited (experimental)" : "");
const std::string window_title = "OpenBMH 1.1";
SDL_Window* window = SDL_CreateWindow(window_title.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 960, 720, SDL_WINDOW_RESIZABLE);
if (!window) throw FormatError(SDL_GetError());
SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_PRESENTVSYNC);
@@ -206,6 +227,8 @@ int main(int argc, char** argv) {
ui::SportschauTeamInfo sportschau_team_info(data);
ui::CompetitionWinnerScreen competition_winner(data);
const auto season_exe = load_le(ui::asset_path(data, "BMH.exe"));
english_game = english_game || season_exe.u8(layout::LeagueSizes) == 20;
app::QuitConfirmation quit_confirmation(window, english_game);
try {
if (!playback.initialize_original(app::original_audio_assets(data, season_exe), audio_error))
std::fprintf(stderr, "audio: %s\n", audio_error.c_str());
@@ -308,7 +331,7 @@ int main(int argc, char** argv) {
std::optional<Image> season_backdrop;
auto present_season = [&](const Image& image, const char* title,
const Palette* palette_override = nullptr) {
SDL_SetWindowTitle(window, title);
SDL_SetWindowTitle(window, "OpenBMH 1.1");
season_backdrop = image;
const Palette& frame_palette = palette_override ? *palette_override : palette;
const Image painted = process_timer_image(image);
@@ -345,7 +368,7 @@ int main(int argc, char** argv) {
if (screen.close_requested()) return renewed_expired_player ? 1 : 0;
SDL_Event event;
bool changed = false;
while (SDL_PollEvent(&event)) {
while (quit_confirmation.poll(&event)) {
if (event.type == SDL_QUIT) {
running = false;
staged = before;
@@ -447,7 +470,7 @@ int main(int argc, char** argv) {
SDL_FlushEvents(SDL_MOUSEMOTION, SDL_MOUSEBUTTONUP);
while (running) {
SDL_Event event;
while (SDL_PollEvent(&event)) {
while (quit_confirmation.poll(&event)) {
if (event.type == SDL_QUIT) { running = false; return; }
if (event.type == SDL_MOUSEBUTTONDOWN &&
(event.button.button == SDL_BUTTON_LEFT || event.button.button == SDL_BUTTON_RIGHT)) return;
@@ -461,7 +484,7 @@ int main(int argc, char** argv) {
SDL_FlushEvents(SDL_MOUSEMOTION, SDL_MOUSEBUTTONUP);
while (running) {
SDL_Event event;
while (SDL_PollEvent(&event)) {
while (quit_confirmation.poll(&event)) {
if (event.type == SDL_QUIT) { running = false; return; }
if (event.type == SDL_MOUSEBUTTONDOWN &&
(event.button.button == SDL_BUTTON_LEFT || event.button.button == SDL_BUTTON_RIGHT)) return;
@@ -474,7 +497,7 @@ int main(int argc, char** argv) {
SDL_Delay(20); // Source timer unit used by the traced intro path.
SDL_PumpEvents();
SDL_Event close;
while (SDL_PeepEvents(&close, 1, SDL_GETEVENT, SDL_QUIT, SDL_QUIT) > 0)
while (quit_confirmation.peep(&close, 1, SDL_GETEVENT, SDL_QUIT, SDL_QUIT) > 0)
running = false; // platform close is the only intro-loop escape
}
};
@@ -488,7 +511,7 @@ int main(int argc, char** argv) {
while (running && SDL_GetPerformanceCounter() - started < ticks_per_wait) {
SDL_PumpEvents();
SDL_Event close;
while (SDL_PeepEvents(&close, 1, SDL_GETEVENT, SDL_QUIT, SDL_QUIT) > 0)
while (quit_confirmation.peep(&close, 1, SDL_GETEVENT, SDL_QUIT, SDL_QUIT) > 0)
running = false; // platform close is the only animation-loop escape
if (running) SDL_Delay(1);
}
@@ -538,7 +561,7 @@ int main(int argc, char** argv) {
bool skipped = false;
while (running && !skipped && SDL_GetTicks() - start < duration) {
SDL_Event input;
while (SDL_PollEvent(&input)) {
while (quit_confirmation.poll(&input)) {
if (input.type == SDL_QUIT) running = false;
if (input.type == SDL_MOUSEBUTTONDOWN && input.button.button == SDL_BUTTON_LEFT)
skipped = true;
@@ -561,21 +584,21 @@ int main(int argc, char** argv) {
bool skip = false;
SDL_Event input;
if (step.minute_wait) {
while (SDL_PollEvent(&input)) {
while (quit_confirmation.poll(&input)) {
if (input.type == SDL_QUIT) running = false;
if (input.type == SDL_MOUSEBUTTONDOWN && input.button.button == SDL_BUTTON_LEFT)
skip = true;
}
} else {
SDL_PumpEvents();
while (SDL_PeepEvents(&input, 1, SDL_GETEVENT, SDL_QUIT, SDL_QUIT) > 0) running = false;
while (quit_confirmation.peep(&input, 1, SDL_GETEVENT, SDL_QUIT, SDL_QUIT) > 0) running = false;
}
if (!running) return true;
const std::string title = "OpenBMH - sportschau_replay_" + std::to_string(fixture.group) +
"_" + std::to_string(fixture.fixture) + "_" + std::to_string(sportschau_step_index++);
present_season(sportschau_replay_screen->render_report(step), title.c_str());
const int raw = state.memory.has(::bmh::layout::Main_FormatError_RuntimeField4) ? state.memory.u8(::bmh::layout::Main_FormatError_RuntimeField4) : 0;
if (step.minute_wait) source_tick_wait(unsigned(raw < 6 ? raw / 2 : raw));
if (step.minute_wait) source_tick_wait(unsigned((app::scene_frame_delay((raw < 6 ? raw / 2 : raw)*20)+19)/20));
if (step.chance_wait) source_tick_wait(50);
return skip;
};
@@ -596,7 +619,7 @@ int main(int argc, char** argv) {
const auto delay = [&](int row) {
const uint32_t address = ::bmh::layout::Main_FormatError_ExecutableFieldUnsigned + uint32_t(row * 9);
const int raw = state.memory.has(address) ? state.memory.u8(address) : 0;
source_tick_wait(unsigned(raw < 6 ? raw / 2 : raw));
source_tick_wait(unsigned((app::scene_frame_delay((raw < 6 ? raw / 2 : raw)*20)+19)/20));
};
present_season(backdrop, ("OpenBMH - sportschau_scene_header_" + id).c_str(), &colors);
delay(12); // AdvanceStep(12), header preview in ShotAnimation
@@ -607,7 +630,7 @@ int main(int argc, char** argv) {
std::to_string(i)).c_str(), &colors);
const unsigned retraces = i == 0 ? 40u :
(state.memory.has(::bmh::layout::Main_FormatError_RuntimeField2) ? state.memory.u8(::bmh::layout::Main_FormatError_RuntimeField2) : 0u);
wait_source_retraces(retraces); // FirstThen: first40, then F8
SDL_Delay(Uint32(live_frame_ms_explicit?live_frame_ms:app::scene_frame_delay(int(retraces)*1000/70))); // FirstThen: first40, then F8
}
}
const auto frames = live_screen.render_shot(frame, scene.shot, &backdrop);
@@ -615,7 +638,7 @@ int main(int argc, char** argv) {
present_season(frames[i], ("OpenBMH - sportschau_shot_" + id + "_" +
std::to_string(i)).c_str(), &colors);
const int speed = state.memory.has(::bmh::layout::Main_FormatError_RuntimeField) ? int(int8_t(state.memory.u8(::bmh::layout::Main_FormatError_RuntimeField))) : 0;
wait_source_retraces(unsigned(std::max(0, speed)));
SDL_Delay(Uint32(live_frame_ms_explicit?live_frame_ms:app::scene_frame_delay(std::max(0,speed)*1000/70)));
}
source_tick_wait(10); // LiveMatchdayFrame's final ten ticks
if (!running) return;
@@ -668,8 +691,7 @@ int main(int argc, char** argv) {
view.manager_name += char(state.manager_records[base + 0xa8 + i]);
view.body = event.text;
view.portrait = state.manager_records[base + 0x221];
view.badge_fallback = event.team == 0x0fff || (event.team > 89 && event.team < 138) ||
(event.team > 167 && event.team < 357);
view.badge_fallback = original_badge_fallback(event.team);
view.badge_sprite = view.badge_fallback ? 0 : le16(state.club_heap_78, size_t(event.team) * 2) & 0x1ff;
ui::GameEndTaxDialog screen(data, std::move(view), game_end_options(state),
event.kind == SeasonTaxEventKind::outcome ? season_backdrop : std::optional<Image>{});
@@ -683,7 +705,7 @@ int main(int argc, char** argv) {
auto pressed = ui::GameEndTaxDialog::Button::none;
while (running) {
SDL_Event input;
while (SDL_PollEvent(&input)) {
while (quit_confirmation.poll(&input)) {
if (input.type == SDL_QUIT) { running = false; return false; }
if (input.type == SDL_MOUSEBUTTONDOWN) {
if (event.kind != SeasonTaxEventKind::question &&
@@ -722,7 +744,7 @@ int main(int argc, char** argv) {
const auto started = SDL_GetTicks();
while (running && Uint32(SDL_GetTicks() - started) < animation.wait_milliseconds()) {
SDL_Event input;
while (SDL_PollEvent(&input)) if (input.type == SDL_QUIT) running = false;
while (quit_confirmation.poll(&input)) if (input.type == SDL_QUIT) running = false;
// Source param4=0: clicks/keys cannot change this script or RNG.
SDL_Delay(10);
}
@@ -739,7 +761,7 @@ int main(int argc, char** argv) {
// events for the next Original input boundary; only handle SDL exit.
SDL_PumpEvents();
SDL_Event quit;
if (SDL_PeepEvents(&quit, 1, SDL_GETEVENT, SDL_QUIT, SDL_QUIT) > 0) running = false;
if (quit_confirmation.peep(&quit, 1, SDL_GETEVENT, SDL_QUIT, SDL_QUIT) > 0) running = false;
if (running) SDL_Delay(10);
}
};
@@ -794,7 +816,7 @@ int main(int argc, char** argv) {
if (timed && Uint32(SDL_GetTicks() - started) >= 70 * 3 * 20)
return complete(PendingOfferAnswer::yes);
SDL_Event input;
while (SDL_PollEvent(&input)) {
while (quit_confirmation.poll(&input)) {
if (input.type == SDL_QUIT) { running = false; return PendingOfferAnswer::unsupported; }
const bool question_deadline = question && poll_process_timer(true,true);
if (question_deadline && pressed == ui::GameEndTaxDialog::Button::none)
@@ -864,7 +886,7 @@ int main(int argc, char** argv) {
SDL_FlushEvents(SDL_MOUSEMOTION, SDL_MOUSEBUTTONUP); // DecodeTaxAnimationScript/SDLFlushEvents redraw boundary
while (running) {
SDL_Event input;
while (SDL_PollEvent(&input)) {
while (quit_confirmation.poll(&input)) {
if (input.type == SDL_QUIT) { running = false; return PendingOfferTransferChoice{}; }
std::optional<int> bid;
if (input.type == SDL_MOUSEBUTTONDOWN &&
@@ -893,7 +915,7 @@ int main(int argc, char** argv) {
bool acknowledged=false;
while(running && !acknowledged) {
SDL_Event event;
while(SDL_PollEvent(&event)) {
while(quit_confirmation.poll(&event)) {
if(event.type==SDL_QUIT){running=false;break;}
if(event.type==SDL_MOUSEBUTTONDOWN &&
(event.button.button==SDL_BUTTON_LEFT || event.button.button==SDL_BUTTON_RIGHT)) {
@@ -926,7 +948,7 @@ int main(int argc, char** argv) {
int manager, int source_slot, int list_entry,
const HumanBuyerSaleHooks& sale_hooks) -> int {
if (!running || manager < 0 || manager >= 4 || list_entry < 40 || list_entry >= 44 ||
source_slot != 2928 + list_entry || !staged.memory.has(::bmh::layout::EditorList + uint32_t(list_entry) * 0x58 + 0x57))
source_slot != runtime_dimensions.pool_first + list_entry || !staged.memory.has(::bmh::layout::EditorList + uint32_t(list_entry) * 0x58 + 0x57))
return -1;
const uint32_t row = ::bmh::layout::EditorList + uint32_t(list_entry) * 0x58;
const int player = staged.squad_slots.at(size_t(source_slot)) & 0x0fff;
@@ -956,7 +978,7 @@ int main(int argc, char** argv) {
draw();
while (running) {
SDL_Event event;
while (SDL_PollEvent(&event)) {
while (quit_confirmation.poll(&event)) {
if (event.type == SDL_QUIT) { running = false; return -1; }
ui::OutgoingTransferRequest action;
if (event.type == SDL_MOUSEMOTION) continue;
@@ -1073,7 +1095,7 @@ int main(int argc, char** argv) {
while (running) {
if (deadline_expired()) return true; //ClubInfoFromGame event8 returns to its owning caller.
SDL_Event input;
while (SDL_PollEvent(&input)) {
while (quit_confirmation.poll(&input)) {
if (input.type == SDL_QUIT) { running = false; return false; }
if (deadline_expired()) return true;
ui::ClubInfoRequest request;
@@ -1174,7 +1196,7 @@ int main(int argc, char** argv) {
SDL_PumpEvents();
while (running && (SDL_GetMouseState(nullptr, nullptr) & SDL_BUTTON_LMASK)) {
SDL_Event input;
while (SDL_PollEvent(&input))
while (quit_confirmation.poll(&input))
if (input.type == SDL_QUIT) { running = false; return; }
SDL_PumpEvents();
if (running) SDL_Delay(10);
@@ -1242,7 +1264,7 @@ int main(int argc, char** argv) {
while (running) {
if (const auto complete = expire_card()) return *complete;
SDL_Event input;
while (SDL_PollEvent(&input)) {
while (quit_confirmation.poll(&input)) {
if (input.type == SDL_QUIT) { running = false; return std::nullopt; }
if (const auto complete = expire_card()) return *complete;
bool changed = false;
@@ -1304,7 +1326,7 @@ int main(int argc, char** argv) {
while (running) {
if (deadline_expired()) return; //LeagueCalculations frees its child before4f548 polls again.
SDL_Event input;
while (SDL_PollEvent(&input)) {
while (quit_confirmation.poll(&input)) {
if (input.type == SDL_QUIT) { running = false; return; }
if (deadline_expired()) return;
if (input.type == SDL_MOUSEBUTTONDOWN && input.button.button == SDL_BUTTON_RIGHT)
@@ -1339,7 +1361,7 @@ int main(int argc, char** argv) {
auto page=staged.current_league_table_dispatch(error);
if(!page)throw FormatError(error);
const auto present=[&](const Image& frame,const std::string& title) {
SDL_SetWindowTitle(window,title.c_str());season_backdrop=frame;
SDL_SetWindowTitle(window, "OpenBMH 1.1");season_backdrop=frame;
const auto painted=process_timer_image(frame);
for(size_t i=0;i<pixels.size();++i)pixels[i]=palette.argb[painted.pixels[i]];
if(SDL_UpdateTexture(texture,nullptr,pixels.data(),320*4)!=0 ||
@@ -1388,7 +1410,7 @@ int main(int argc, char** argv) {
while(running&&!outcome) {
if(expire_range())break;
SDL_Event input;
while(SDL_PollEvent(&input)) {
while(quit_confirmation.poll(&input)) {
if(input.type==SDL_QUIT){running=false;break;}
if(expire_range())break;
bool changed=false;
@@ -1444,7 +1466,7 @@ int main(int argc, char** argv) {
while(running) {
if(deadline_expired())return std::nullopt;
SDL_Event input;
while(SDL_PollEvent(&input)) {
while(quit_confirmation.poll(&input)) {
if(input.type==SDL_QUIT){running=false;break;}
if(deadline_expired())return std::nullopt;
bool changed=false;
@@ -1538,7 +1560,7 @@ int main(int argc, char** argv) {
// Source ignores the first OriginalMouseSound poll's gameplay result, then
// presents the starting scene before its ten option-delay polls.
SDL_Event initial;
if (SDL_PollEvent(&initial) && initial.type == SDL_QUIT) { running = false; return; }
if (quit_confirmation.poll(&initial) && initial.type == SDL_QUIT) { running = false; return; }
show_draw();
while (running && screen.advance_step()) {
if (screen.present_needed()) show_draw();
@@ -1546,7 +1568,7 @@ int main(int argc, char** argv) {
if (!running) return;
if (screen.input_poll_needed()) {
SDL_Event input;
while (SDL_PollEvent(&input)) {
while (quit_confirmation.poll(&input)) {
if (input.type == SDL_QUIT) { running = false; return; }
if (input.type == SDL_MOUSEBUTTONDOWN &&
(input.button.button == SDL_BUTTON_LEFT || input.button.button == SDL_BUTTON_RIGHT)) {
@@ -1581,7 +1603,7 @@ int main(int argc, char** argv) {
SDL_FlushEvents(SDL_MOUSEMOTION, SDL_MOUSEBUTTONUP);
while (running) {
SDL_Event input;
while (SDL_PollEvent(&input)) {
while (quit_confirmation.poll(&input)) {
if (input.type == SDL_QUIT) { running = false; return; }
if (input.type != SDL_MOUSEBUTTONDOWN) continue;
if (input.button.button == SDL_BUTTON_RIGHT) return;
@@ -1618,7 +1640,7 @@ int main(int argc, char** argv) {
while (running && screen.phase() == ui::AlternateScorePhase::Calculator) {
SDL_Event event;
bool changed = false;
while (SDL_PollEvent(&event)) {
while (quit_confirmation.poll(&event)) {
if (event.type == SDL_QUIT) { running = false; return; }
if (event.type == SDL_MOUSEBUTTONDOWN && event.button.button == SDL_BUTTON_RIGHT) {
right_cancel = true;
@@ -1683,6 +1705,11 @@ int main(int argc, char** argv) {
std::optional<Uint64> timed_notice_presented_at;
std::optional<Uint8> timed_notice_release;
auto handle = [&](const ui::FlowResult& r) {
if (r.request == ui::FlowRequest::end_session && !quit_confirmation.confirm()) {
flow.reject_desk_action(english_game ? "Quit cancelled." : "Beenden abgebrochen.");
dirty = true;
return;
}
if (const auto* desk = flow.desktop())
for (const auto id : desk->take_sound_ids()) app::original_audio_command(playback, id);
if (r.request == ui::FlowRequest::kickoff || r.request == ui::FlowRequest::end_session) {
@@ -1723,7 +1750,7 @@ int main(int argc, char** argv) {
"OpenBMH - live_substitution_notice") == PendingOfferAnswer::unsupported)
throw FormatError("live substitution notice presenter stopped");
SDL_FlushEvents(SDL_MOUSEMOTION, SDL_MOUSEBUTTONUP);
SDL_SetWindowTitle(window, parent_title);
SDL_SetWindowTitle(window, "OpenBMH 1.1");
};
bool completed = false;
const int selected_manager = selected_team >= 0 ? state.manager_of(selected_team) : -1;
@@ -1753,7 +1780,7 @@ int main(int argc, char** argv) {
return (screen.extras().native_display_word & 8)
? "OpenBMH - live_pitch" : "OpenBMH - live_lineup";
};
SDL_SetWindowTitle(window, live_title());
SDL_SetWindowTitle(window, "OpenBMH 1.1");
bool closed = false;
const auto apply_live_pitch = [&](const ui::PitchRequest& action) {
if (action.kind == ui::PitchRequestKind::none) return;
@@ -1792,7 +1819,7 @@ int main(int argc, char** argv) {
? "Der Spielerwechsel ist nicht freigegeben." : result.error);
}
}
SDL_SetWindowTitle(window, live_title());
SDL_SetWindowTitle(window, "OpenBMH 1.1");
};
bool left_held = false, left_release_consumed = false, right_held = false;
while (running && !closed) {
@@ -1805,7 +1832,7 @@ int main(int argc, char** argv) {
SDL_RenderPresent(renderer);
SDL_Event modal;
bool redrawn = false;
while (SDL_PollEvent(&modal)) {
while (quit_confirmation.poll(&modal)) {
if (modal.type == SDL_QUIT) { running = false; closed = true; break; }
if (modal.type == SDL_KEYDOWN && modal.key.keysym.sym == SDLK_ESCAPE) {
screen.key("ESC"); closed = true; break;
@@ -1856,7 +1883,7 @@ int main(int argc, char** argv) {
scope_finished = true;
completed = true;
}
SDL_SetWindowTitle(window, "OpenBMH - live_matchday");
SDL_SetWindowTitle(window, "OpenBMH 1.1");
} catch (const std::exception& e) {
if (scope_started && !scope_finished)
dispatch_scope(app::LiveInterventionBoundary::abort, 2,
@@ -1940,7 +1967,7 @@ int main(int argc, char** argv) {
const Image image = table_screen ? table_screen->render()
: pairings_screen ? pairings_screen->render()
: strengths_screen ? strengths_screen->render() : cup_screen->render();
SDL_SetWindowTitle(window, overview_title().c_str());
SDL_SetWindowTitle(window, "OpenBMH 1.1");
for (size_t i = 0; i < pixels.size(); ++i)
pixels[i] = palette.argb[image.pixels[i]];
SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4);
@@ -1962,7 +1989,7 @@ int main(int argc, char** argv) {
std::optional<ui::TableRangeDialogOutcome> outcome;
const auto show_dialog = [&] {
const Image image = dialog.render();
SDL_SetWindowTitle(window, "OpenBMH - live_table_range");
SDL_SetWindowTitle(window, "OpenBMH 1.1");
for (size_t i = 0; i < pixels.size(); ++i)
pixels[i] = palette.argb[image.pixels[i]];
SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4);
@@ -1975,7 +2002,7 @@ int main(int argc, char** argv) {
show_dialog();
while (running && !outcome) {
SDL_Event input;
while (SDL_PollEvent(&input)) {
while (quit_confirmation.poll(&input)) {
if (input.type == SDL_QUIT) { running = false; break; }
bool changed = false;
if (input.type == SDL_TEXTINPUT) {
@@ -2075,7 +2102,7 @@ int main(int argc, char** argv) {
while (running && !closed) {
SDL_Event input;
bool redrawn = false;
while (SDL_PollEvent(&input)) {
while (quit_confirmation.poll(&input)) {
if (input.type == SDL_QUIT) { running = false; break; }
if (input.type == SDL_MOUSEMOTION) {
const bool changed = table_screen ? table_screen->move(input.motion.x, input.motion.y)
@@ -2143,7 +2170,7 @@ int main(int argc, char** argv) {
if (!live_skipped) {
const auto frame = ui::live_matchday_frame(minute, groups, state);
if (!frame.matches.empty()) {
SDL_SetWindowTitle(window, "OpenBMH - live_matchday");
SDL_SetWindowTitle(window, "OpenBMH 1.1");
const Image live_image = live_screen.render(frame);
for (size_t i = 0; i < pixels.size(); ++i) pixels[i] = palette.argb[live_image.pixels[i]];
SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4);
@@ -2164,7 +2191,7 @@ int main(int argc, char** argv) {
ui::IncomingTransferScreen offer_screen(data,
ui::incoming_transfer_decision_from_game(state, view),
state.memory.u8(::bmh::layout::TextGradientDisabled) == 0);
SDL_SetWindowTitle(window, "OpenBMH - incoming_transfer");
SDL_SetWindowTitle(window, "OpenBMH 1.1");
const Uint32 notice_started = SDL_GetTicks();
bool offer_dirty = true;
// Keep the original synchronous decision stack suspended here.
@@ -2185,7 +2212,7 @@ int main(int argc, char** argv) {
offer_dirty = false;
}
SDL_Event event;
while (SDL_PollEvent(&event)) {
while (quit_confirmation.poll(&event)) {
if (event.type == SDL_QUIT) { running = false; return -1; }
std::optional<int> answer;
if (event.type == SDL_MOUSEBUTTONUP &&
@@ -2233,7 +2260,7 @@ int main(int argc, char** argv) {
decision_screen.begin_outcome(decision.offers.offer_count,
decision.accepted ? decision.selected_bid_index : -1, state.memory.u8(::bmh::layout::OutcomeDelayDisabled));
}
SDL_SetWindowTitle(window, confirmation ? "OpenBMH - transfer_confirmation" : "OpenBMH - transfer_evaluation");
SDL_SetWindowTitle(window, "OpenBMH 1.1");
const Uint32 started = SDL_GetTicks();
uint64_t rendered_phase = UINT64_MAX;
// The observer only presents the engine's settled decision. Keep
@@ -2254,7 +2281,7 @@ int main(int argc, char** argv) {
rendered_phase = phase;
}
SDL_Event event;
while (SDL_PollEvent(&event)) {
while (quit_confirmation.poll(&event)) {
if (event.type == SDL_QUIT) { running = false; return; }
if (event.type == SDL_MOUSEBUTTONUP &&
(event.button.button == SDL_BUTTON_LEFT || event.button.button == SDL_BUTTON_RIGHT))
@@ -2272,7 +2299,7 @@ int main(int argc, char** argv) {
// Other season animations remain separate implementation work.
for (auto view : ui::season_entrants_from_game(state, season_exe, season_texts)) {
ui::SeasonEntrantsScreen entrants_screen(data, std::move(view));
SDL_SetWindowTitle(window, "OpenBMH - season_entrants");
SDL_SetWindowTitle(window, "OpenBMH 1.1");
const Image image = entrants_screen.render();
for (size_t i = 0; i < pixels.size(); ++i) pixels[i] = palette.argb[image.pixels[i]];
SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4);
@@ -2282,7 +2309,7 @@ int main(int argc, char** argv) {
bool dismissed = false;
while (running && !dismissed) {
SDL_Event event;
while (SDL_PollEvent(&event)) {
while (quit_confirmation.poll(&event)) {
if (event.type == SDL_QUIT) { running = false; return; }
if (event.type == SDL_MOUSEBUTTONUP &&
(event.button.button == SDL_BUTTON_LEFT || event.button.button == SDL_BUTTON_RIGHT)) {
@@ -2314,11 +2341,13 @@ int main(int argc, char** argv) {
// after the tip question has returned, before the outer ACK.
const Image backdrop = flow.stadium()->construction_notice_backdrop();
auto view = ui::construction_notice_dialog(staged, season_exe, notice);
std::optional<ui::GameEndRenderOptions> effective_options;
const auto& stadium_owner = flow.stadium()->state();
std::optional<ui::GameEndRenderOptions> effective_options =
ui::GameEndRenderOptions{stadium_owner.plain_background, stadium_owner.gradient_text, true};
if (flow.stadium()->state().block_expansion || flow.stadium()->state().quoted_object) {
const auto& owner = flow.stadium()->state();
view.compact_dialog_frame = owner.compact_dialog_frame;
effective_options = ui::GameEndRenderOptions{owner.plain_background, owner.gradient_text};
effective_options = ui::GameEndRenderOptions{owner.plain_background, owner.gradient_text, true};
}
const char* title = notice.kind == ConstructionNoticeKind::InsufficientFunds
? "OpenBMH - stadium_funds_notice" : "OpenBMH - stadium_sponsor_notice";
@@ -2332,7 +2361,7 @@ int main(int argc, char** argv) {
view.compact_dialog_frame = owner.compact_dialog_frame;
if (present_pending_dialog(staged, view, backdrop,
"OpenBMH - stadium_ticket_compensation_notice",
ui::GameEndRenderOptions{owner.plain_background, owner.gradient_text}) == PendingOfferAnswer::unsupported)
ui::GameEndRenderOptions{owner.plain_background, owner.gradient_text, true}) == PendingOfferAnswer::unsupported)
throw std::runtime_error("compensation notice presenter stopped");
}, sportschau_presenter,
[&](const GameState& staged, const AdvertisingRenewal& renewal, const Image& backdrop)
@@ -2396,7 +2425,7 @@ int main(int argc, char** argv) {
// SDLFlushEvents3 is a timed Source notice. Do not let its release
// event become another click in the resumed parent screen.
SDL_FlushEvents(SDL_MOUSEMOTION, SDL_MOUSEBUTTONUP);
SDL_SetWindowTitle(window, parent_title);
SDL_SetWindowTitle(window, "OpenBMH 1.1");
};
const auto open_live_tactics = [&](int side, int y) {
const auto frame = ui::live_matchday_frame(minute, groups, state);
@@ -2422,7 +2451,7 @@ int main(int argc, char** argv) {
tactics_game.memory.set8(::bmh::layout::ActiveManager, uint8_t(selected_manager));
ui::TacticsScreen screen(data,
ui::tactics_from_game(tactics_game, season_exe, live_revision));
SDL_SetWindowTitle(window, "OpenBMH - live_tactics");
SDL_SetWindowTitle(window, "OpenBMH 1.1");
bool closed = false;
std::optional<SDL_MouseButtonEvent> tactics_down;
bool source_completed = false;
@@ -2436,7 +2465,7 @@ int main(int argc, char** argv) {
SDL_RenderPresent(renderer);
SDL_Event modal;
bool redrawn = false;
while (SDL_PollEvent(&modal)) {
while (quit_confirmation.poll(&modal)) {
if (modal.type == SDL_QUIT) { running = false; closed = true; break; }
if (modal.type == SDL_MOUSEBUTTONDOWN &&
(modal.button.button == SDL_BUTTON_LEFT || modal.button.button == SDL_BUTTON_RIGHT))
@@ -2476,7 +2505,7 @@ int main(int argc, char** argv) {
selected_manager, selected_team, scope_error);
scope_active = false;
}
SDL_SetWindowTitle(window, "OpenBMH - live_matchday");
SDL_SetWindowTitle(window, "OpenBMH 1.1");
} catch (const std::exception& e) {
if (scope_active)
dispatch_scope(app::LiveInterventionBoundary::abort, 8,
@@ -2495,13 +2524,13 @@ int main(int argc, char** argv) {
SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4);
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, nullptr, nullptr);
SDL_SetWindowTitle(window, "OpenBMH - live_paused");
SDL_SetWindowTitle(window, "OpenBMH 1.1");
SDL_RenderPresent(renderer);
bool resumed = false;
while (running && !resumed) {
SDL_Event paused_event;
while (SDL_PollEvent(&paused_event)) {
while (quit_confirmation.poll(&paused_event)) {
if (paused_event.type == SDL_QUIT) {
quit = true;
live_skipped = true;
@@ -2514,12 +2543,12 @@ int main(int argc, char** argv) {
}
if (!resumed && running) SDL_Delay(8);
}
if (running) SDL_SetWindowTitle(window, "OpenBMH - live_matchday");
if (running) SDL_SetWindowTitle(window, "OpenBMH 1.1");
};
const auto restore_live_frame = [&] {
if (!running) return;
const Image image = live_screen.render(ui::live_matchday_frame(minute, groups, state));
SDL_SetWindowTitle(window, "OpenBMH - live_matchday");
SDL_SetWindowTitle(window, "OpenBMH 1.1");
for (size_t i = 0; i < pixels.size(); ++i)
pixels[i] = palette.argb[image.pixels[i]];
SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4);
@@ -2584,7 +2613,7 @@ int main(int argc, char** argv) {
std::unique_ptr<ui::SettingsReadmeScreen> readme;
const auto render_settings = [&] {
const Image image = readme ? readme->render() : screen.render();
SDL_SetWindowTitle(window, readme ? "OpenBMH - settings_readme" : "OpenBMH - live_settings");
SDL_SetWindowTitle(window, "OpenBMH 1.1");
for (size_t i = 0; i < pixels.size(); ++i)
pixels[i] = palette.argb[image.pixels[i]];
SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4);
@@ -2605,7 +2634,7 @@ int main(int argc, char** argv) {
ui::SaveLoadFileKind::settings, menu_request.origin_item_id);
const auto render_file = [&] {
const Image image = file_screen.render();
SDL_SetWindowTitle(window, "OpenBMH - live_settings_file");
SDL_SetWindowTitle(window, "OpenBMH 1.1");
for (size_t i = 0; i < pixels.size(); ++i)
pixels[i] = palette.argb[image.pixels[i]];
SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4);
@@ -2614,11 +2643,12 @@ int main(int argc, char** argv) {
SDL_RenderPresent(renderer);
};
render_file();
focus_filename_input(renderer);
bool finished = false;
while (running && !finished) {
SDL_Event file_input;
bool file_changed = false;
while (SDL_PollEvent(&file_input)) {
while (quit_confirmation.poll(&file_input)) {
if (file_input.type == SDL_QUIT) { running = false; break; }
if (file_input.type == SDL_MOUSEBUTTONUP &&
(file_input.button.button == SDL_BUTTON_LEFT ||
@@ -2678,7 +2708,7 @@ int main(int argc, char** argv) {
while (running && !closed) {
SDL_Event input;
bool changed = false;
while (SDL_PollEvent(&input)) {
while (quit_confirmation.poll(&input)) {
if (input.type == SDL_QUIT) { running = false; break; }
if (readme) {
if (input.type == SDL_MOUSEBUTTONDOWN &&
@@ -2750,7 +2780,7 @@ int main(int argc, char** argv) {
screen.consume_release();
settings_down.reset();
SDL_FlushEvents(SDL_MOUSEMOTION, SDL_MOUSEBUTTONUP);
SDL_SetWindowTitle(window, "OpenBMH - live_settings");
SDL_SetWindowTitle(window, "OpenBMH 1.1");
} else {
screen.reject(error.empty() ? "Diese Einstellung wurde nicht übernommen." : error);
std::fprintf(stderr, "live settings: %s\n", error.c_str());
@@ -2792,7 +2822,7 @@ int main(int argc, char** argv) {
const bool source_phase_start = minute == 1 ||
(state.indoor ? minute == 21 : (minute == 46 || minute == 91 || minute == 106));
SDL_Event event;
while (SDL_PollEvent(&event)) {
while (quit_confirmation.poll(&event)) {
if (event.type == SDL_QUIT) { quit = true; live_skipped = true; }
else if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE)
live_skipped = true;
@@ -2905,7 +2935,7 @@ int main(int argc, char** argv) {
const std::string title = "OpenBMH - live_ball_" + std::to_string(event.minute) + "_" +
std::to_string(event.group) + "_" + std::to_string(event.match) + "_" +
std::to_string(event.displacement) + "_" + std::to_string(index);
SDL_SetWindowTitle(window, title.c_str());
SDL_SetWindowTitle(window, "OpenBMH 1.1");
const auto* chance = live_chance_context &&
live_chance_context->minute == event.minute &&
live_chance_context->group == event.group &&
@@ -2913,20 +2943,20 @@ int main(int argc, char** argv) {
present(live_screen.render_ball(frame, event.displacement, index, chance));
SDL_PumpEvents();
SDL_Event quit_event;
if (SDL_PeepEvents(&quit_event, 1, SDL_GETEVENT, SDL_QUIT, SDL_QUIT) > 0) {
if (quit_confirmation.peep(&quit_event, 1, SDL_GETEVENT, SDL_QUIT, SDL_QUIT) > 0) {
running = false;
break;
}
// AdvanceStep(5) reads a252c; DecodeTaxAnimationScript2 uses 20ms ticks.
// Retain key/mouse events for the live-minute input boundary.
const int delay = live_frame_ms_explicit ? live_frame_ms :
source_delay(5);
app::scene_frame_delay(source_delay(5));
if (delay > 0) SDL_Delay(Uint32(delay));
}
if (running) {
const int final_delay = live_frame_ms_explicit ? live_frame_ms : source_delay(6);
const int final_delay = live_frame_ms_explicit ? live_frame_ms : app::scene_frame_delay(source_delay(6));
if (final_delay > 0) SDL_Delay(Uint32(final_delay));
SDL_SetWindowTitle(window, "OpenBMH - live_matchday");
SDL_SetWindowTitle(window, "OpenBMH 1.1");
present(live_screen.render(frame));
}
}, [&](const LiveChanceEvent& event, const std::vector<MatchGroup>& groups,
@@ -2941,7 +2971,7 @@ int main(int argc, char** argv) {
std::to_string(event.minute) + "_" + std::to_string(event.group) + "_" +
std::to_string(event.match) + "_" + std::to_string(event.side) + "_" +
std::to_string(event.kind) + "_" + std::to_string(int(event.goal));
SDL_SetWindowTitle(window, title.c_str());
SDL_SetWindowTitle(window, "OpenBMH 1.1");
const Image image = live_screen.render_chance(frame, chance);
for (size_t i = 0; i < pixels.size(); ++i) pixels[i] = palette.argb[image.pixels[i]];
SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4);
@@ -2950,7 +2980,7 @@ int main(int argc, char** argv) {
SDL_RenderPresent(renderer);
SDL_PumpEvents();
SDL_Event quit_event;
if (SDL_PeepEvents(&quit_event, 1, SDL_GETEVENT, SDL_QUIT, SDL_QUIT) > 0) {
if (quit_confirmation.peep(&quit_event, 1, SDL_GETEVENT, SDL_QUIT, SDL_QUIT) > 0) {
running = false;
live_chance_context.reset();
return;
@@ -2959,7 +2989,7 @@ int main(int argc, char** argv) {
const uint32_t address = ::bmh::layout::Main_FormatError_ExecutableFieldUnsigned + uint32_t(pause * 9);
const int saved = state.memory.has(address) ? state.memory.u8(address) : 0;
const int delay = live_frame_ms_explicit ? live_frame_ms :
(saved < 6 ? saved / 2 : saved) * 20;
app::scene_frame_delay((saved < 6 ? saved / 2 : saved) * 20);
if (delay > 0) SDL_Delay(Uint32(delay));
if (event.stage == LiveChanceStage::result) live_chance_context.reset();
}, [&](const LiveShotEvent& event, const std::vector<MatchGroup>& groups,
@@ -2974,7 +3004,7 @@ int main(int argc, char** argv) {
std::to_string(event.acting_side) + "_" + std::to_string(int(event.miss));
for (size_t index = 0; index < frames.size() && running; ++index) {
const std::string title = "OpenBMH - live_shot_" + identity + "_" + std::to_string(index);
SDL_SetWindowTitle(window, title.c_str());
SDL_SetWindowTitle(window, "OpenBMH 1.1");
for (size_t i = 0; i < pixels.size(); ++i) pixels[i] = shot_colors.argb[frames[index].pixels[i]];
SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4);
SDL_RenderClear(renderer);
@@ -2982,14 +3012,14 @@ int main(int argc, char** argv) {
SDL_RenderPresent(renderer);
SDL_PumpEvents();
SDL_Event input;
if (SDL_PeepEvents(&input, 1, SDL_GETEVENT, SDL_QUIT, SDL_QUIT) > 0) {
if (quit_confirmation.peep(&input, 1, SDL_GETEVENT, SDL_QUIT, SDL_QUIT) > 0) {
running = false;
return;
}
// Source waits Main_FormatError_RuntimeField vertical retraces after each frame (70 Hz).
const int retraces = state.memory.has(::bmh::layout::Main_FormatError_RuntimeField) ?
std::max(0, int(int8_t(state.memory.u8(::bmh::layout::Main_FormatError_RuntimeField)))) : 0;
const int delay = live_frame_ms_explicit ? live_frame_ms : retraces * 1000 / 70;
const int delay = live_frame_ms_explicit ? live_frame_ms : app::scene_frame_delay(retraces * 1000 / 70);
if (delay > 0) SDL_Delay(Uint32(delay));
}
if (!running) return;
@@ -2999,12 +3029,12 @@ int main(int argc, char** argv) {
if (state.memory.has(::bmh::layout::Main_FormatError_RuntimeField5) && state.memory.u8(::bmh::layout::Main_FormatError_RuntimeField5) == 0) {
// SDLFlushEvents2 accepts a fresh left/right press, not a keyboard skip.
const std::string title = "OpenBMH - live_shot_wait_" + identity;
SDL_SetWindowTitle(window, title.c_str());
SDL_SetWindowTitle(window, "OpenBMH 1.1");
SDL_FlushEvents(SDL_MOUSEBUTTONDOWN, SDL_MOUSEBUTTONUP);
SDL_Event input;
bool acknowledged = false;
while (running && !acknowledged) {
while (SDL_PollEvent(&input)) {
while (quit_confirmation.poll(&input)) {
if (input.type == SDL_QUIT) { running = false; break; }
if (input.type == SDL_MOUSEBUTTONDOWN &&
(input.button.button == SDL_BUTTON_LEFT || input.button.button == SDL_BUTTON_RIGHT)) {
@@ -3017,7 +3047,7 @@ int main(int argc, char** argv) {
} else {
// AdvanceStep(15): the ordinary saved pause instead of a click.
const int saved = state.memory.has(::bmh::layout::Main_FormatError_RuntimeField7) ? state.memory.u8(::bmh::layout::Main_FormatError_RuntimeField7) : 0;
const int delay = live_frame_ms_explicit ? live_frame_ms : (saved < 6 ? saved / 2 : saved) * 20;
const int delay = live_frame_ms_explicit ? live_frame_ms : app::scene_frame_delay((saved < 6 ? saved / 2 : saved) * 20);
if (delay > 0) SDL_Delay(Uint32(delay));
}
}, [&](const LiveSetPieceEvent& event, const std::vector<MatchGroup>& groups,
@@ -3034,16 +3064,16 @@ int main(int argc, char** argv) {
std::to_string(event.group)+"_"+std::to_string(event.match)+"_"+
std::to_string(event.source_side)+"_"+std::to_string(event.kind)+"_"+
std::to_string(index)+"_"+std::to_string(images.size());
SDL_SetWindowTitle(window,title.c_str());
SDL_SetWindowTitle(window, "OpenBMH 1.1");
for (size_t i=0;i<pixels.size();++i) pixels[i]=colors.argb[images[index].pixels[i]];
SDL_UpdateTexture(texture,nullptr,pixels.data(),320*4);
SDL_RenderClear(renderer);SDL_RenderCopy(renderer,texture,nullptr,nullptr);SDL_RenderPresent(renderer);
SDL_PumpEvents();SDL_Event input;
if (SDL_PeepEvents(&input,1,SDL_GETEVENT,SDL_QUIT,SDL_QUIT)>0) { running=false;return; }
if (quit_confirmation.peep(&input,1,SDL_GETEVENT,SDL_QUIT,SDL_QUIT)>0) { running=false;return; }
// FirstThen holds the first frame for 40 retraces; later frames
// use saved Main_FormatError_RuntimeField2. Keyboard/mouse input remains for the minute hook.
const int retraces=index==0?40:(state.memory.has(::bmh::layout::Main_FormatError_RuntimeField2)?state.memory.u8(::bmh::layout::Main_FormatError_RuntimeField2):0);
const int delay=live_frame_ms_explicit?live_frame_ms:retraces*1000/70;
const int delay=live_frame_ms_explicit?live_frame_ms:app::scene_frame_delay(retraces*1000/70);
if (delay>0) SDL_Delay(Uint32(delay));
}
if (running && !live_frame_ms_explicit) SDL_Delay(200); // LiveMatchdayFrame
@@ -3061,18 +3091,18 @@ int main(int argc, char** argv) {
SDL_UpdateTexture(texture,nullptr,pixels.data(),320*4);
SDL_RenderClear(renderer);SDL_RenderCopy(renderer,texture,nullptr,nullptr);SDL_RenderPresent(renderer);
};
SDL_SetWindowTitle(window,title.c_str());present(live_screen.render_booking(frame,booking));
SDL_SetWindowTitle(window, "OpenBMH 1.1");present(live_screen.render_booking(frame,booking));
if (event.kind != 2 && app::match_sound_enabled(state))
app::original_audio_command(playback, 17); // EventImpl/SDLPumpEvents, no injury whistle.
SDL_PumpEvents();SDL_Event input;
if (SDL_PeepEvents(&input,1,SDL_GETEVENT,SDL_QUIT,SDL_QUIT)>0) { running=false;return; }
if (quit_confirmation.peep(&input,1,SDL_GETEVENT,SDL_QUIT,SDL_QUIT)>0) { running=false;return; }
const int pause=event.kind==0?3:4;
const uint32_t address=::bmh::layout::Main_FormatError_ExecutableFieldUnsigned+uint32_t(pause*9);
const int saved=state.memory.has(address)?state.memory.u8(address):0;
const int delay=live_frame_ms_explicit?live_frame_ms:(saved<6?saved/2:saved)*20;
const int delay=live_frame_ms_explicit?live_frame_ms:app::scene_frame_delay((saved<6?saved/2:saved)*20);
if (delay>0) SDL_Delay(Uint32(delay));
// EventImpl clears the box after its pause; no Source click wait here.
SDL_SetWindowTitle(window,"OpenBMH - live_matchday");present(live_screen.render(frame));
SDL_SetWindowTitle(window, "OpenBMH 1.1");present(live_screen.render(frame));
}, [&](const LiveShootoutEvent& event, const std::vector<MatchGroup>& groups,
const GameState& state) {
if (!running || live_skipped) return;
@@ -3083,30 +3113,30 @@ int main(int argc, char** argv) {
std::to_string(event.group)+"_"+std::to_string(event.match)+"_"+
std::to_string(event.side)+"_"+std::to_string(event.round)+"_"+
std::to_string(event.of)+"_"+std::to_string(event.player);
SDL_SetWindowTitle(window,title.c_str());
SDL_SetWindowTitle(window, "OpenBMH 1.1");
const auto image=live_screen.render_shootout(frame,projection);
for (size_t i=0;i<pixels.size();++i) pixels[i]=palette.argb[image.pixels[i]];
SDL_UpdateTexture(texture,nullptr,pixels.data(),320*4);
SDL_RenderClear(renderer);SDL_RenderCopy(renderer,texture,nullptr,nullptr);SDL_RenderPresent(renderer);
SDL_PumpEvents();SDL_Event input;
if (SDL_PeepEvents(&input,1,SDL_GETEVENT,SDL_QUIT,SDL_QUIT)>0) { running=false;return; }
if (quit_confirmation.peep(&input,1,SDL_GETEVENT,SDL_QUIT,SDL_QUIT)>0) { running=false;return; }
const int repeats=event.stage==LiveShootoutStage::preview?4:2;
const int saved=state.memory.has(::bmh::layout::Main_FormatError_RuntimeField6)?state.memory.u8(::bmh::layout::Main_FormatError_RuntimeField6):0;
const int delay=live_frame_ms_explicit?live_frame_ms:(saved<6?saved/2:saved)*20;
const int delay=live_frame_ms_explicit?live_frame_ms:app::scene_frame_delay((saved<6?saved/2:saved)*20);
for (int i=0;i<repeats && running;++i) if (delay>0) SDL_Delay(Uint32(delay));
}, [&](const LiveRealityEvent& event, const std::vector<MatchGroup>& groups,
const GameState& state) -> bool {
if (!running || live_skipped) return false;
const auto frame = ui::live_matchday_frame(event.minute,groups,state);
const auto present = [&](const Image& image,const Palette& colors,const std::string& title) {
SDL_SetWindowTitle(window,title.c_str());
SDL_SetWindowTitle(window, "OpenBMH 1.1");
for (size_t i=0;i<pixels.size();++i) pixels[i]=colors.argb[image.pixels[i]];
SDL_UpdateTexture(texture,nullptr,pixels.data(),320*4);
SDL_RenderClear(renderer);SDL_RenderCopy(renderer,texture,nullptr,nullptr);SDL_RenderPresent(renderer);
};
const auto delay = [&](uint32_t address) {
const int saved=state.memory.has(address)?state.memory.u8(address):0;
const int ms=live_frame_ms_explicit?live_frame_ms:(saved<6?saved/2:saved)*20;
const int ms=live_frame_ms_explicit?live_frame_ms:app::scene_frame_delay((saved<6?saved/2:saved)*20);
if (ms>0) SDL_Delay(Uint32(ms));
};
const std::string identity=std::to_string(event.minute)+"_"+std::to_string(event.group)+"_"+
@@ -3126,7 +3156,7 @@ int main(int argc, char** argv) {
}
if (event.stage==LiveRealityStage::settling) {
reality_field.reset();
const int ms=live_frame_ms_explicit?live_frame_ms:200; // DecodeTaxAnimationScript2(10)
const int ms=live_frame_ms_explicit?live_frame_ms:app::scene_frame_delay(200); // DecodeTaxAnimationScript2(10)
if (ms>0) SDL_Delay(Uint32(ms));
return false;
}
@@ -3153,16 +3183,16 @@ int main(int argc, char** argv) {
present(reality_surface,reality_colors,"OpenBMH - live_reality_report_"+round_identity);
}
SDL_PumpEvents();SDL_Event input;
if (SDL_PeepEvents(&input,1,SDL_GETEVENT,SDL_QUIT,SDL_QUIT)>0) {running=false;return true;}
if (quit_confirmation.peep(&input,1,SDL_GETEVENT,SDL_QUIT,SDL_QUIT)>0) {running=false;return true;}
// Consume only the Source exit for this scene. Other input remains
// queued for the existing live-minute/manager intervention boundary.
if (SDL_PeepEvents(&input,1,SDL_PEEKEVENT,SDL_KEYDOWN,SDL_KEYDOWN)>0 &&
if (quit_confirmation.peep(&input,1,SDL_PEEKEVENT,SDL_KEYDOWN,SDL_KEYDOWN)>0 &&
input.key.keysym.sym==SDLK_ESCAPE) {
SDL_PeepEvents(&input,1,SDL_GETEVENT,SDL_KEYDOWN,SDL_KEYDOWN);return true;
quit_confirmation.peep(&input,1,SDL_GETEVENT,SDL_KEYDOWN,SDL_KEYDOWN);return true;
}
if (SDL_PeepEvents(&input,1,SDL_PEEKEVENT,SDL_MOUSEBUTTONDOWN,SDL_MOUSEBUTTONDOWN)>0 &&
if (quit_confirmation.peep(&input,1,SDL_PEEKEVENT,SDL_MOUSEBUTTONDOWN,SDL_MOUSEBUTTONDOWN)>0 &&
input.button.button==SDL_BUTTON_RIGHT) {
SDL_PeepEvents(&input,1,SDL_GETEVENT,SDL_MOUSEBUTTONDOWN,SDL_MOUSEBUTTONDOWN);return true;
quit_confirmation.peep(&input,1,SDL_GETEVENT,SDL_MOUSEBUTTONDOWN,SDL_MOUSEBUTTONDOWN);return true;
}
return false;
}, [&](const PhaseResultRequest& request, const std::vector<MatchGroup>& groups,
@@ -3201,7 +3231,7 @@ int main(int argc, char** argv) {
}
}
if(!flow.timed_notice_open())timed_notice_presented_at.reset();
SDL_SetWindowTitle(window, ("OpenBMH - " + flow.screen_name()).c_str());
SDL_SetWindowTitle(window, "OpenBMH 1.1");
};
const auto present_formation_save_feedback = [&] {
for (bool restored : {false, true}) {
@@ -3575,18 +3605,42 @@ int main(int argc, char** argv) {
}
};
SDL_StartTextInput();
bool filename_input_active = false;
std::array<bool, 2> setup_button_down{};
while (running) {
const bool filename_open = flow.screen_name() == "save_load";
if (filename_open && !filename_input_active) focus_filename_input(renderer);
filename_input_active = filename_open;
if(timed_notice_presented_at && flow.timed_notice_open() &&
SDL_GetTicks64()-*timed_notice_presented_at>=70*3*20)
handle(flow.expire_timed_notice());
service_process_timer();
if (!running) break;
SDL_Event e;
while (SDL_PollEvent(&e)) {
while (quit_confirmation.poll(&e)) {
if (e.type == SDL_QUIT) {
running = false;
break;
}
if (e.type == SDL_WINDOWEVENT) {
if (e.window.event == SDL_WINDOWEVENT_FOCUS_LOST) setup_button_down.fill(false);
if (e.window.event == SDL_WINDOWEVENT_FOCUS_GAINED) {
if (flow.screen_name() == "save_load") focus_filename_input(renderer);
else SDL_StartTextInput();
}
}
// A native picker/window activation can leave an unmatched UP.
// Only a press which began on setup may toggle its options.
if ((e.type == SDL_MOUSEBUTTONDOWN || e.type == SDL_MOUSEBUTTONUP) &&
(e.button.button == SDL_BUTTON_LEFT || e.button.button == SDL_BUTTON_RIGHT)) {
const size_t button = e.button.button == SDL_BUTTON_LEFT ? 0 : 1;
if (e.type == SDL_MOUSEBUTTONDOWN) setup_button_down[button] = flow.screen_name() == "setup";
else {
const bool owned = setup_button_down[button];
setup_button_down[button] = false;
if (flow.screen_name() == "setup" && !owned) continue;
}
}
if(e.type==SDL_MOUSEBUTTONUP&&timed_notice_release&&e.button.button==*timed_notice_release) {
timed_notice_release.reset();continue;
}
@@ -3642,7 +3696,8 @@ int main(int argc, char** argv) {
continue;
}
if (e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_ESCAPE &&
!flow.in_preparation_menu() && !flow.in_results_view() && !flow.in_readonly_view())
!flow.in_preparation_menu() && !flow.in_results_view() && !flow.in_readonly_view() &&
quit_confirmation.confirm())
running = false;
if (e.type == SDL_MOUSEBUTTONDOWN && e.button.button == SDL_BUTTON_LEFT)
press = Press{e.button.x, e.button.y, SDL_GetTicks(), flow.screen_name(),
@@ -3678,7 +3733,7 @@ int main(int argc, char** argv) {
} else if (flow.desktop() && flow.desktop()->socket_confirmation_armed()) {
// SDLSetWindowTitle paints its pressed socket sprite before
// DeskDate waits for the physical release.
SDL_SetWindowTitle(window, "OpenBMH - desktop");
SDL_SetWindowTitle(window, "OpenBMH 1.1");
const auto image=process_timer_image(flow.render());
for(size_t i=0;i<pixels.size();++i)pixels[i]=palette.argb[image.pixels[i]];
SDL_UpdateTexture(texture,nullptr,pixels.data(),320*4);
@@ -3856,11 +3911,9 @@ int main(int argc, char** argv) {
SDL_DestroyWindow(window);
mouse_sound.detach(); // Remove event producers before closing the audio device.
playback.shutdown();
SDL_Quit();
return 0;
} catch (const std::exception& e) {
std::fprintf(stderr, "error: %s\n", e.what());
SDL_Quit();
return 1;
}
}
+63
View File
@@ -0,0 +1,63 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <SDL.h>
#include <functional>
#include <utility>
namespace bmh::app {
// OpenBMH deviates from the original: confirms application exit with a localized native dialog, with cancellation selected by default.
// All event retrieval remains on the UI thread. An event filter/watch could run
// on SDL's event thread and must not own a native modal dialog.
class QuitConfirmation {
public:
using Presenter = std::function<int(const SDL_MessageBoxData*, int*)>;
QuitConfirmation(SDL_Window* window, bool english, Presenter presenter = SDL_ShowMessageBox)
: window_(window), english_(english), presenter_(std::move(presenter)) {}
bool confirm() {
if (confirmed_) return true;
const SDL_MessageBoxButtonData buttons[] = {
{SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT | SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT,
0, english_ ? "Cancel" : "Abbrechen"},
{0, 1, english_ ? "Quit" : "Beenden"}
};
const SDL_MessageBoxData dialog{SDL_MESSAGEBOX_WARNING, window_,
english_ ? "Quit OpenBMH?" : "OpenBMH beenden?",
english_ ? "Do you really want to quit OpenBMH?\nUnsaved changes will be lost." :
"OpenBMH wirklich beenden?\nNicht gespeicherte Änderungen gehen verloren.",
2, buttons, nullptr};
int selected = 0;
if (presenter_(&dialog, &selected) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Cannot show quit confirmation: %s", SDL_GetError());
return false; // A failed dialog must not silently discard the session.
}
confirmed_ = selected == 1;
return confirmed_;
}
int poll(SDL_Event* event) {
if (!event) return SDL_PollEvent(nullptr);
while (SDL_PollEvent(event)) {
if (event->type != SDL_QUIT || confirm()) return 1;
}
return 0;
}
int peep(SDL_Event* events, int count, SDL_eventaction action, Uint32 first, Uint32 last) {
const int received = SDL_PeepEvents(events, count, action, first, last);
if (received <= 0 || !events || action != SDL_GETEVENT) return received;
int kept = 0;
for (int i = 0; i < received; ++i)
if (events[i].type != SDL_QUIT || confirm()) events[kept++] = events[i];
return kept;
}
private:
SDL_Window* window_;
bool english_, confirmed_ = false;
Presenter presenter_;
};
} // namespace bmh::app
+7
View File
@@ -0,0 +1,7 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <algorithm>
namespace bmh::app {
// Presentation only: 25% more time per scene frame, without gameplay/RNG changes.
constexpr int scene_frame_delay(int milliseconds) { return std::max(16,(milliseconds*5+3)/4); }
}
+22
View File
@@ -0,0 +1,22 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <SDL.h>
#include <stdexcept>
#include <string>
namespace bmh::app {
// Establish SDL's native application before any file picker can create NSApp.
// Cocoa otherwise retains the picker's non-keyboard activation policy.
class VideoSession {
public:
VideoSession() {
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
const std::string error = SDL_GetError();
SDL_Quit();
throw std::runtime_error(error);
}
}
~VideoSession() { SDL_Quit(); }
VideoSession(const VideoSession&) = delete;
VideoSession& operator=(const VideoSession&) = delete;
};
}
+1 -1
View File
@@ -420,7 +420,7 @@ void Console::register_transfer_commands() {
Arg a;
a.text = number;
const auto id = to_int(a);
if (!id || *id < 0 || *id >= 138) fail("E_BAD_ARGUMENT", "club is club:<n> (ListPoachClubs)");
if (!id || *id < 0 || *id >= runtime_dimensions.league_teams) fail("E_BAD_ARGUMENT", "club is club:<n> (ListPoachClubs)");
return int(*id);
};
Param club = detail::text("club");
+40
View File
@@ -0,0 +1,40 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "formats/executable_layout.hpp"
#include "formats/le.hpp"
namespace bmh {
// Installed alongside the loaded edition's other runtime tables. Club selectors
// remain database/savegame data; this only reproduces the original drawing gate.
inline int original_foreign_badge_end = 138;
inline bool expanded_badges = false;
inline int original_badge_gate(const LeImage& exe) {
if(const auto* policy=exe.runtime_policy())return int(policy->badge_end);
constexpr auto instruction = layout::ForeignBadgeGateInstruction;
if (exe.contains(instruction) && exe.contains(instruction + 6) &&
exe.u8(instruction) == 0x66 && exe.u8(instruction + 1) == 0x81 &&
exe.u8(instruction + 2) == 0xfb && exe.u8(instruction + 5) == 0x7c &&
exe.u8(instruction + 6) == 7) {
const int end = exe.u16(instruction + 3);
if (end == 90 || end == 138) return end;
}
// Never invent individual foreign crests for an unverified drawing routine.
return 138;
}
inline void install_original_badge_policy(const LeImage& exe) {
original_foreign_badge_end = original_badge_gate(exe);
expanded_badges = exe.expanded_profile();
}
inline bool original_badge_fallback(int token, const LeImage* exe = nullptr) {
const int team = token & 0xfff;
if (exe ? exe->expanded_profile() : expanded_badges) return team == 0xfff;
const int end = exe ? original_badge_gate(*exe) : original_foreign_badge_end;
return team == 0xfff || (team >= 90 && team < end) || (team >= 168 && team < 357);
}
} // namespace bmh
+3
View File
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/binary.hpp"
#include "formats/resource_bundle.hpp"
#include <fstream>
#include <iterator>
@@ -7,6 +8,8 @@
namespace bmh {
Bytes read_file(const std::filesystem::path& path) {
if (!std::filesystem::exists(path))
if (auto bytes=bundled_resource(path)) return std::move(*bytes);
std::ifstream in(path, std::ios::binary);
if (!in) throw FormatError("cannot open " + path.string());
return Bytes(std::istreambuf_iterator<char>(in), {});
+45
View File
@@ -0,0 +1,45 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/data_profile.hpp"
#include "formats/resource_bundle.hpp"
#include <fstream>
#include <numeric>
#include <set>
#include <sstream>
namespace bmh {
DataProfile DataProfile::international_11() {
DataProfile p;
p.id="classic-plus-1";
p.leagues={18,18,18,18,18,18,20,18,18};
p.counts={445,3334,194,4104,164,30};
p.big_squad_teams=164;
p.national_first=383;
return p;
}
void DataProfile::validate() const {
const auto total=std::accumulate(leagues.begin(),leagues.end(),uint32_t(0));
if(total!=counts.league_teams || big_squad_teams>total || counts.n42!=total+counts.cup_teams ||
counts.n66!=extra_slots_first() || counts.clubs!=national_first+62 ||
national_first!=total+counts.cup_teams+189 || counts.clubs>512 || counts.players>=4095 || total_slots()>65535)
throw FormatError("profile: inconsistent counts or packed identifier overflow");
for(auto size:leagues)if(size!=12 && size!=18 && size!=20)throw FormatError("profile: unsupported league size");
}
DataProfile load_data_profile(const std::filesystem::path& directory) {
const auto file=directory/"OBMHPROF.INI";
if(!resource_exists(file))return {};
return decode_data_profile(read_file(file));
}
DataProfile decode_data_profile(const Bytes& raw) {
std::istringstream input(std::string(raw.begin(),raw.end()));
std::string line,id;bool section=false,seen=false;
while(std::getline(input,line)) {
if(!line.empty()&&line.back()=='\r')line.pop_back();
const auto first=line.find_first_not_of(" \t");if(first==std::string::npos||line[first]==';'||line[first]=='#')continue;
const auto last=line.find_last_not_of(" \t");line=line.substr(first,last-first+1);
if(line=="[OpenBMH]"){if(section)throw FormatError("profile: duplicate section");section=true;continue;}
if(!section||line.rfind("profile=",0)!=0||seen)throw FormatError("profile: unknown or duplicate metadata key");
id=line.substr(8);seen=true;
}
if(id!="classic-plus-1")throw FormatError("profile: unsupported data profile");
auto p=DataProfile::international_11();p.validate();return p;
}
}
+25
View File
@@ -0,0 +1,25 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <array>
#include <filesystem>
#include <string>
#include "formats/m3d.hpp"
namespace bmh {
// Installation metadata; original files retain their implicit Classic profile.
struct DataProfile {
std::string id = "classic";
std::array<uint8_t,9> leagues{18,18,18,18,18,12,12,12,12};
DbCounts counts{};
uint32_t big_squad_teams = 90;
uint32_t national_first = 357;
uint32_t pool_first() const { return big_squad_teams*24+(counts.league_teams-big_squad_teams)*16; }
uint32_t national_slots_first() const { return pool_first()+144; }
uint32_t extra_slots_first() const { return national_slots_first()+24; }
uint32_t total_slots() const { return extra_slots_first()+54; }
bool extended() const { return id != "classic"; }
void validate() const;
static DataProfile international_11();
};
DataProfile decode_data_profile(const Bytes&);
DataProfile load_data_profile(const std::filesystem::path& directory);
}
+23 -2
View File
@@ -764,7 +764,7 @@ inline constexpr auto EnglishLayoutTranslation156 = 0x6e08c;
inline constexpr auto EnglishLayoutTranslation157 = 0x6e094;
inline constexpr auto EnglishLayoutTranslation158 = 0x6e0b8;
inline constexpr auto EnglishLayoutTranslation159 = 0x6e0bb;
inline constexpr auto EnglishLayoutTranslation16 = 0x6be4f;
inline constexpr auto EnglishLayoutTranslation16 = 0x6be50;
inline constexpr auto EnglishLayoutTranslation160 = 0x6e0d8;
inline constexpr auto EnglishLayoutTranslation161 = 0x6e110;
inline constexpr auto EnglishLayoutTranslation162 = 0x6e11c;
@@ -986,7 +986,7 @@ inline constexpr auto EnglishLayoutTranslation7 = 0x6be0c;
inline constexpr auto EnglishLayoutTranslation70 = 0x6d270;
inline constexpr auto EnglishLayoutTranslation71 = 0x6d272;
inline constexpr auto EnglishLayoutTranslation72 = 0x6d274;
inline constexpr auto EnglishLayoutTranslation73 = 0x6d29c;
inline constexpr auto EnglishLayoutTranslation73 = 0x6d29d;
inline constexpr auto EnglishLayoutTranslation74 = 0x6d3b4;
inline constexpr auto EnglishLayoutTranslation75 = 0x6d404;
inline constexpr auto EnglishLayoutTranslation76 = 0x6d408;
@@ -1412,7 +1412,13 @@ inline constexpr auto NationalFriendlyPayerPrefixText = 0xa000f;
inline constexpr auto NextDeskManager = 0xbd6cc;
inline constexpr auto NoClubText = 0xaec74;
inline constexpr auto NoPlayerText = 0xaec78;
// Legacy symbol name: this is the league+cup team count, NOT a squad slot offset.
inline constexpr auto NoTeamSquadStart = 0xa2c38;
inline constexpr auto ProfileSmallSquadClubs = 0xa2c32;
inline constexpr auto ProfilePoolFirst = 0xa2c56;
inline constexpr auto ProfileFreeFirst = 0xa2c5a;
inline constexpr auto ProfileForeignFreeFirst = 0xa2c5e;
inline constexpr auto ProfileNationalSlotsFirst = 0xa2c62;
inline constexpr auto OfferSlots = 0xbb844;
inline constexpr auto Opportunities_FormatError_RuntimeField = 0xa3a6e;
inline constexpr auto Opportunities_FormatError_RuntimeField2 = 0xa3a80;
@@ -1972,4 +1978,19 @@ inline constexpr auto EnglishFourTeamFixtureTable = 0x6eea0;
inline constexpr auto EnglishSixTeamFixtureTable = 0x6eed4;
inline constexpr auto EnglishTwelveTeamFixtureTable = 0x6f0bc;
inline constexpr auto EnglishTwentyTeamFixtureTable = 0x6ee40;
inline constexpr auto EnglishDesktopBinSourceX = 0x6e180;
inline constexpr auto EnglishDesktopBinSourceY = 0x6e182;
inline constexpr auto EnglishDesktopSocketSourceX = 0x6e184;
} // namespace bmh::layout
namespace bmh::layout {
inline constexpr auto EnvironmentBudgetSteps = 0xa50ff;
inline constexpr auto EnvironmentVerifiedCodeBegin = 0x6c000;
inline constexpr auto EnvironmentVerifiedCodeEnd = 0x6cb40;
inline constexpr auto EnvironmentVerifiedHookBegin = 0x7af65;
inline constexpr auto EnvironmentVerifiedHookEnd = 0x7b020;
}
namespace bmh::layout { inline constexpr auto ForeignBadgeGateInstruction = 0x10070; }
namespace bmh::layout { inline constexpr auto CalendarDateSetup = 0x21270; }
+97 -5
View File
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/le.hpp"
#include "formats/rule_base.hpp"
#include "formats/data_profile.hpp"
#include "formats/executable_layout.hpp"
#include <algorithm>
#include <fstream>
@@ -17,6 +18,10 @@ struct Object {
} // namespace
std::string LeImage::cstring(uint32_t address) const {
if (runtime_policy_) {
const auto label=runtime_policy_->labels.find(address);
if(label!=runtime_policy_->labels.end())return label->second;
}
std::string s;
while (contains(address) && u8(address) != 0) s.push_back(char(u8(address++)));
return s;
@@ -36,15 +41,103 @@ void save_image(const LeImage& image, const std::filesystem::path& path) {
if (!file) throw FormatError("cannot write the OpenBMH image");
}
void save_runtime_image(const LeImage& image, const RuntimePolicy& policy, const std::filesystem::path& path) {
constexpr uint32_t start=layout::GermanDataSegmentBegin;
if(!image.contains(start) || policy.year<1600 || policy.year>9999 || policy.weekday>6 ||
(policy.badge_end!=90 && policy.badge_end!=138) || policy.environment_verified>1 || policy.labels.size()>16)
throw FormatError("runtime data: unsupported source policies");
const uint32_t size=image.base()+image.size()-start;
if(size>1024*1024)throw FormatError("runtime data: data segment too large");
Bytes out{'O','B','M','H','D','A','T','1'};
const auto put=[&](uint32_t value){for(int b=0;b<4;++b)out.push_back(uint8_t(value>>(8*b)));};
for(uint32_t value:{start,size,policy.year,policy.weekday,policy.badge_end,policy.environment_verified,uint32_t(policy.labels.size())})put(value);
out.insert(out.end(),image.data(start),image.data(start)+size);
for(const auto& [address,text]:policy.labels) {
if(text.size()>1024)throw FormatError("runtime data: label too long");
put(address);put(uint32_t(text.size()));out.insert(out.end(),text.begin(),text.end());
}
std::ofstream file(path,std::ios::binary|std::ios::trunc);file.write(reinterpret_cast<const char*>(out.data()),std::streamsize(out.size()));
if(!file)throw FormatError("cannot write runtime data");
}
LeImage load_le(const std::filesystem::path& path) {
const auto profile = load_data_profile(path.parent_path());
const auto apply_profile = [&](LeImage img) {
if (!profile.extended()) return img;
const auto put = [&](uint32_t address, uint32_t value, int width) {
if (!img.contains(address) || !img.contains(address + uint32_t(width - 1)))
throw FormatError("profile: executable lacks verified data dimensions");
for (int b = 0; b < width; ++b) img.bytes_.at(address - img.base_ + uint32_t(b)) = uint8_t(value >> (8 * b));
};
if (img.u8(layout::LeagueSizes) != 18)
throw FormatError("profile: classic-plus-1 requires a German installation");
put(layout::CareerSession_DataDirectory_RuntimeField, profile.counts.clubs, 4);
put(layout::CareerSession_DataDirectory_RuntimeField3, profile.counts.players, 4);
put(layout::CareerSession_DataDirectory_RuntimeField2, profile.counts.n42, 4);
put(layout::CareerSession_DataDirectory_RuntimeField4, profile.counts.n66, 4);
put(layout::CareerSession_DispatchLineup_RuntimeField, profile.counts.league_teams, 2);
put(layout::TeamsWithSquads, profile.big_squad_teams, 2);
put(layout::NoTeamSquadStart, profile.counts.n42, 2);
put(layout::ProfileSmallSquadClubs, profile.counts.league_teams - profile.big_squad_teams, 2);
put(layout::ClubPlayerDetail_ClubPlayerDetailRedraw_RuntimeField, profile.counts.players, 4);
put(layout::ProfilePoolFirst, profile.pool_first(), 4);
put(layout::ProfileFreeFirst, profile.pool_first() + 44, 4);
put(layout::ProfileForeignFreeFirst, profile.pool_first() + 124, 4);
put(layout::ProfileNationalSlotsFirst, profile.national_slots_first(), 4);
for (size_t league = 0; league < profile.leagues.size(); ++league)
put(layout::LeagueSizes + uint32_t(league), profile.leagues[league], 1);
std::vector<int> foreign_days;
for (int day = 0; day < 365; ++day) {
const auto at = layout::CompetitionCalendar + uint32_t(day * 2);
const uint16_t flags = img.u16(at);
if ((flags & 0x4001) == 1 && day + 1 < 365) foreign_days.push_back(day + 1);
put(at, flags & ~0x10u, 2);
}
if (foreign_days.size() != 34) throw FormatError("profile: unsupported domestic calendar");
for (int target : {60, 110, 250, 290}) {
int chosen = -1;
for (int delta = 0; delta < 7 && chosen < 0; ++delta) {
const int day = target + delta;
if (img.u16(layout::CompetitionCalendar + uint32_t(day * 2)) == 0 &&
std::find(foreign_days.begin(), foreign_days.end(), day) == foreign_days.end()) chosen = day;
}
if (chosen < 0) throw FormatError("profile: no calendar space for extra English fixtures");
foreign_days.push_back(chosen);
}
for (int day : foreign_days) {
const auto at = layout::CompetitionCalendar + uint32_t(day * 2);
put(at, img.u16(at) | 0x10, 2);
}
img.expanded_profile_ = true;
return img;
};
const Bytes raw = read_file(path);
if(raw.size()>=8 && std::string(raw.begin(),raw.begin()+8)=="OBMHDAT1") {
if(raw.size()<36)throw FormatError("runtime data: truncated header");
const uint32_t base=le32(raw,8),size=le32(raw,12),labels=le32(raw,32);
RuntimePolicy policy{le32(raw,16),le32(raw,20),le32(raw,24),le32(raw,28),{}};
if(base!=layout::GermanDataSegmentBegin || size>1024*1024 || size_t(size)+36>raw.size() || labels>16 ||
policy.year<1600 || policy.year>9999 || policy.weekday>6 || (policy.badge_end!=90 && policy.badge_end!=138) || policy.environment_verified>1)
throw FormatError("runtime data: invalid dimensions or policies");
auto image=LeImage::from_bytes(base,Bytes(raw.begin()+36,raw.begin()+36+size));
size_t at=36+size;
for(uint32_t i=0;i<labels;++i) {
if(at+8>raw.size())throw FormatError("runtime data: truncated label");
const auto address=le32(raw,at),length=le32(raw,at+4);at+=8;
if(length>1024 || at+length>raw.size() || !policy.labels.emplace(address,std::string(raw.begin()+at,raw.begin()+at+length)).second)
throw FormatError("runtime data: invalid label");
at+=length;
}
if(at!=raw.size())throw FormatError("runtime data: trailing bytes");
image.runtime_policy_=std::move(policy);
return apply_profile(std::move(image));
}
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; };
const uint32_t base = word(sizeof kImageMagic), size = word(sizeof kImageMagic + 4);
if (raw.size() != sizeof kImageMagic + 8 + size_t(size)) throw FormatError("OpenBMH image: wrong size");
LeImage img = LeImage::from_bytes(base, Bytes(raw.begin() + sizeof kImageMagic + 8, raw.end()));
apply_rule_base(img);
return img;
return apply_profile(std::move(img));
}
auto u8 = [&](size_t o) -> uint32_t {
if (o >= raw.size()) throw FormatError("LE: read beyond the file");
@@ -133,8 +226,7 @@ LeImage load_le(const std::filesystem::path& path) {
}
}
}
apply_rule_base(img);
return img;
return apply_profile(std::move(img));
}
} // namespace bmh
+15 -4
View File
@@ -11,11 +11,18 @@
#include <cstdint>
#include <filesystem>
#include <string>
#include <map>
#include <optional>
#include "formats/binary.hpp"
namespace bmh {
// Resolved edition policies, not copied machine instructions.
struct RuntimePolicy {
uint32_t year=0, weekday=0, badge_end=0, environment_verified=0;
std::map<uint32_t,std::string> labels;
};
class LeImage {
public:
uint32_t base() const { return base_; }
@@ -29,7 +36,7 @@ public:
// 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).
// Overwrites bytes inside a prepared image for verified address translation.
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];
}
@@ -43,22 +50,26 @@ public:
return img;
}
const Bytes& bytes() const { return bytes_; }
bool expanded_profile() const { return expanded_profile_; }
const RuntimePolicy* runtime_policy() const { return runtime_policy_ ? &*runtime_policy_ : nullptr; }
friend LeImage load_le(const std::filesystem::path& path);
private:
std::optional<RuntimePolicy> runtime_policy_;
bool expanded_profile_ = false;
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.
// Loads the original executable image without changing edition-specific rule tables.
// Throws FormatError for files that are not LE executables or use external fixups.
// A German BMH.EXE is loaded with the OpenBMH rule base applied (formats/rule_base.hpp):
// every edition plays by the supported rule profile rule values.
LeImage load_le(const std::filesystem::path& path);
// The OpenBMH image format: "OPENBMH-IMAGE" NUL, u32 base, u32 size, the bytes. load_le()
// reads it as well, so a translated image can stand in for BMH.exe in a data directory.
void save_image(const LeImage& image, const std::filesystem::path& path);
// Exports only the data segment and resolved policy values, never DOS/LE/code objects.
void save_runtime_image(const LeImage&, const RuntimePolicy&, const std::filesystem::path&);
} // namespace bmh
+25 -4
View File
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/m3d.hpp"
#include "formats/data_profile.hpp"
#include <cstring>
@@ -34,13 +35,20 @@ std::string pool_string(const Bytes& pool, size_t offset) {
} // namespace
Database load_database(const std::filesystem::path& path) {
return load_database(path, load_data_profile(path.parent_path()).counts);
}
Database load_database(const std::filesystem::path& path, const DbCounts& c) {
Bytes d = read_file(path);
return decode_database(read_file(path),c);
}
Database decode_database(const Bytes& d,const DbCounts& c) {
Reader r{d};
Bytes lens = r.take(8);
size_t len_clubs = le16(lens, 0), len_players = le16(lens, 2), len_refs = le16(lens, 4), len_stadiums = le16(lens, 6);
Database db;
Database db; db.counts=c;
db.raw_player_bonus_values = r.take(c.n66 + 0x32);
Bytes club_pool = r.take(len_clubs);
Bytes player_pool = r.take(len_players);
@@ -57,8 +65,8 @@ Database load_database(const std::filesystem::path& path, const DbCounts& c) {
db.raw_foreign_club_strength = r.take(0xFB);
db.raw_league_auxiliary_bytes = r.take(0xBD);
db.raw_referee_properties = r.take(0x32);
db.raw_club_kit_selectors = r.take(0x1A3);
db.raw_club_short_name_offsets = r.take(0xA8);
db.raw_club_kit_selectors = r.take(c.clubs);
db.raw_club_short_name_offsets = r.take(c.n42);
db.squad_list = r.take((c.n66 - 4) * 2 + 0x6C);
Bytes w35c = r.take(c.players * 4), w368 = r.take(c.players * 4), w364 = r.take(c.players * 4);
if (r.pos != d.size()) throw FormatError("M3D: trailing data, table sizes do not match");
@@ -69,4 +77,17 @@ Database load_database(const std::filesystem::path& path, const DbCounts& c) {
return db;
}
Bytes encode_database(const Database& db) {
Bytes out;
const auto put=[&](uint32_t value,int width){for(int i=0;i<width;++i)out.push_back(uint8_t(value>>(8*i)));};
const auto append=[&](const Bytes& bytes){out.insert(out.end(),bytes.begin(),bytes.end());};
for(const auto& pool:db.pools){if(pool.size()>65535)throw FormatError("M3D: string pool exceeds 16-bit offsets");put(uint32_t(pool.size()),2);}
append(db.raw_player_bonus_values);for(const auto& pool:db.pools)append(pool);
for(const auto* bytes:{&db.raw_club_name_offsets,&db.raw_player_name_offsets,&db.raw_database_metadata,&db.raw_club_auxiliary_words,
&db.raw_club_badge_selectors,&db.raw_foreign_club_strength,&db.raw_league_auxiliary_bytes,&db.raw_referee_properties,&db.raw_club_kit_selectors,&db.raw_club_short_name_offsets,&db.squad_list})append(*bytes);
for(int word=0;word<3;++word)for(const auto& player:db.players)put(word==0?player.w35c:word==1?player.w368:player.w364,4);
(void)decode_database(out,db.counts);
return out;
}
} // namespace bmh
+7 -1
View File
@@ -16,6 +16,8 @@ struct DbCounts {
uint32_t players = 2574;
uint32_t n42 = 168;
uint32_t n66 = 3096;
uint32_t league_teams = 138;
uint32_t cup_teams = 30;
};
// A player as stored in the three parallel u32 tables of the database/savegame
@@ -61,6 +63,7 @@ struct Player {
};
struct Database {
DbCounts counts{};
std::vector<std::string> club_names;
std::vector<std::string> referees;
std::vector<std::string> stadiums;
@@ -73,6 +76,9 @@ struct Database {
Bytes raw_player_bonus_values, raw_database_metadata, raw_club_auxiliary_words, raw_club_badge_selectors, raw_foreign_club_strength, raw_league_auxiliary_bytes, raw_referee_properties, raw_club_kit_selectors, raw_club_short_name_offsets;
};
Database load_database(const std::filesystem::path& path, const DbCounts& counts = {});
Database load_database(const std::filesystem::path& path, const DbCounts& counts);
Database load_database(const std::filesystem::path& path);
Database decode_database(const Bytes&, const DbCounts&);
Bytes encode_database(const Database&);
} // namespace bmh
+92
View File
@@ -0,0 +1,92 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/resource_bundle.hpp"
#include "miniz.h"
#include <algorithm>
#include <cctype>
#include <fstream>
#include <iterator>
#include <map>
#include <memory>
#include <mutex>
namespace bmh {
namespace {
std::string folded(std::string name) {
std::transform(name.begin(),name.end(),name.begin(),[](unsigned char ch){return char(std::toupper(ch));});
return name;
}
struct Bundle {
Bytes file;
mz_zip_archive zip{};
std::map<std::string,mz_uint> entries;
explicit Bundle(const std::filesystem::path& path) {
const auto size=std::filesystem::file_size(path);
if(size>64*1024*1024)throw FormatError("community bundle exceeds size limit");
std::ifstream input(path,std::ios::binary);
file.assign(std::istreambuf_iterator<char>(input),{});
if(!input.is_open() || file.size()!=size || !mz_zip_reader_init_mem(&zip,file.data(),file.size(),0))
throw FormatError("cannot read community bundle");
try {
uint64_t total=0;
const auto count=mz_zip_reader_get_num_files(&zip);
if(count>4096)throw FormatError("community bundle has too many entries");
for(mz_uint i=0;i<count;++i) {
mz_zip_archive_file_stat st{};
if(!mz_zip_reader_file_stat(&zip,i,&st))throw FormatError("invalid community directory");
if(st.m_is_directory)continue;
const std::string name=st.m_filename;
const std::filesystem::path relative(name);
if(name.empty()||name.find('\\')!=std::string::npos||name.find(':')!=std::string::npos||relative.is_absolute())
throw FormatError("unsafe community resource name");
for(const auto& part:relative)if(part==".."||part==".")throw FormatError("unsafe community resource path");
total+=st.m_uncomp_size;
if(st.m_uncomp_size>32*1024*1024 || total>128*1024*1024 ||
!entries.emplace(folded(name),i).second)throw FormatError("ambiguous or oversized community resources");
}
}catch(...){mz_zip_reader_end(&zip);throw;}
}
~Bundle(){mz_zip_reader_end(&zip);}
};
std::mutex bundle_mutex;
struct Cached { std::filesystem::file_time_type modified; uintmax_t size; std::shared_ptr<Bundle> bundle; };
std::map<std::filesystem::path,Cached> cache;
std::pair<std::shared_ptr<Bundle>,std::string> locate(const std::filesystem::path& requested) {
auto path=std::filesystem::absolute(requested).lexically_normal();
auto root=path.parent_path();
for(int depth=0;depth<4 && !root.empty();++depth) {
const auto archive=root/kCommunityBundle;
std::error_code ec;
if(std::filesystem::is_regular_file(archive,ec)) {
const auto modified=std::filesystem::last_write_time(archive);
const auto size=std::filesystem::file_size(archive);
auto found=cache.find(archive);
if(found==cache.end()||found->second.modified!=modified||found->second.size!=size) {
auto bundle=std::make_shared<Bundle>(archive);
if(cache.size()>=4)cache.clear();
found=cache.insert_or_assign(archive,Cached{modified,size,std::move(bundle)}).first;
}
auto name=folded(path.lexically_relative(root).generic_string());
// Compatibility address-view API; the archive contains no EXE image.
if(name=="BMH.EXE")name="RUNTIME.DAT";
return {found->second.bundle,std::move(name)};
}
const auto parent=root.parent_path();if(parent==root)break;root=parent;
}
return {};
}
}
std::optional<Bytes> bundled_resource(const std::filesystem::path& path) {
std::lock_guard lock(bundle_mutex);
auto [bundle,name]=locate(path);if(!bundle)return std::nullopt;
const auto found=bundle->entries.find(name);if(found==bundle->entries.end())return std::nullopt;
mz_zip_archive_file_stat st{};mz_zip_reader_file_stat(&bundle->zip,found->second,&st);
Bytes result(size_t(st.m_uncomp_size));
if(!mz_zip_reader_extract_to_mem(&bundle->zip,found->second,result.data(),result.size(),0))
throw FormatError("damaged community resource: "+name);
return result;
}
bool resource_exists(const std::filesystem::path& path) {
std::error_code ec;if(std::filesystem::is_regular_file(path,ec))return true;
std::lock_guard lock(bundle_mutex);auto [bundle,name]=locate(path);
return bundle && bundle->entries.count(name)!=0;
}
}
+10
View File
@@ -0,0 +1,10 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "formats/binary.hpp"
#include <optional>
namespace bmh {
inline constexpr const char* kCommunityBundle = "COMMUNITY.OBD";
// Read-only package lookup. Loose user saves always remain outside the bundle.
std::optional<Bytes> bundled_resource(const std::filesystem::path& path);
bool resource_exists(const std::filesystem::path& path);
}
-44
View File
@@ -1,44 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "formats/rule_base.hpp"
#include <cstdint>
#include <vector>
namespace bmh {
namespace {
struct RuleBytes {
uint32_t address;
std::vector<uint8_t> bytes;
};
// OpenBMH deviates from the original: normalizes live-scene defaults, league strength ranges, option defaults, stadium prices and capacities, betting limits, and the foreign-player limit across supported editions.
// Every byte here differs in at least one German edition from supported rule profile 2026-27 and is read by
// the engine as a rule (runtime verification exe_diff over the ten editions, minus texts, calendar,
// season values and screen positions).
const std::vector<RuleBytes> kRuleBase = {
{::bmh::layout::LiveSceneOptions, {0x01, 0x01, 0x01, 0x01, 0x01, 0x01}}, // live scene options (CareerSession_DispatchLiveTactic_RuntimeField2, RerateTeam)
// (The training camp resorts DeskActions_ConfigureTrainingCampData_RuntimeField.. - qualities and prices - are content, not rules:
// every edition, the English one too, keeps its own resorts;
{::bmh::layout::LeagueStrengthRanges, {0x47, 0x5d, 0x31, 0x47, 0x1c, 0x31, 0x1c, 0x31, 0x0a, 0x1c}}, // league strength ranges (LeagueStrengthRanges)
{::bmh::layout::AdditionalLeagueStrengthRanges, {0x5f, 0x5a, 0x5f, 0x4b, 0x5f}}, // league strength ranges
{::bmh::layout::FinalLeagueStrengthMaximum, {0x5f}}, // league strength ranges
{::bmh::layout::RuleOptionDefaults, {0x02, 0x02, 0x02, 0x02, 0x03, 0x02, 0x03, 0x02, 0x02, 0x02, 0x02, 0x03, 0x04, 0x02, 0x03, 0x02, 0x03, 0x06, 0x08, 0x06, 0x08, 0x0a, 0x0c, 0x10, 0x14, 0x18, 0x1c, 0x1e}}, // option defaults (ClubPlayerDetail_ClubPlayerDetailFromGame_RuntimeField4...)
{::bmh::layout::StadiumPriceTable, {0xa0, 0x25, 0x26, 0x00, 0xa0, 0xf0, 0x19, 0x00, 0xc0, 0x91, 0x21, 0x00, 0x40, 0x42, 0x0f, 0x00, 0xe0, 0xc8, 0x10, 0x00, 0x60, 0xe3, 0x16, 0x00, 0xc0, 0x45, 0x04, 0x00, 0xc0, 0x45, 0x04, 0x00, 0xc0, 0x45, 0x04, 0x00, 0xc0, 0x45, 0x04, 0x00, 0x30, 0x57, 0x05, 0x00, 0x30, 0x57, 0x05, 0x00, 0x30, 0x57, 0x05, 0x00, 0x30, 0x57, 0x05, 0x00, 0xa0, 0xbb, 0x0d, 0x00, 0xb0, 0x71, 0x0b, 0x00, 0x40, 0x77, 0x1b, 0x00, 0xc0, 0x91, 0x21, 0x00, 0x30, 0x57, 0x05, 0x00, 0xc0, 0x27, 0x09, 0x00, 0x70, 0x64, 0x08, 0x00, 0x40, 0x42, 0x0f, 0x00, 0xe0, 0x93, 0x04, 0x00, 0xd8, 0xb8, 0x05, 0x00, 0xe0, 0x93, 0x04, 0x00, 0x30, 0x57, 0x05, 0x00, 0xe0, 0x93, 0x04, 0x00, 0xd8, 0xb8, 0x05, 0x00, 0xe0, 0x93, 0x04, 0x00, 0x30, 0x57, 0x05, 0x00, 0xd0, 0x07, 0xb8, 0x0b, 0xb8, 0x0b, 0x40, 0x1f, 0xa0, 0x0f, 0xb8, 0x0b}}, // stadium prices (CareerSession_DispatchStadium_RuntimeField)
{::bmh::layout::AdditionalStadiumPrices, {0x88, 0x13, 0xc0, 0x12, 0x60, 0x09, 0x40, 0x1f}}, // stadium prices (CareerSession_DispatchStadium_RuntimeField)
{::bmh::layout::StadiumBlockCapacities, {0x12, 0x08, 0x0e, 0x08, 0x12, 0x08, 0x0e}}, // stadium block places (CareerSession_Invalid_RuntimeField)
{::bmh::layout::ComputerBettingLimits, {0x33, 0x20, 0x50, 0x74}}, // computer tip gaps (CareerSession_DispatchLeagueTableControl_RuntimeField)
{::bmh::layout::ForeignPlayerLimitEnabled, {0x00}}, // substitution rule switch (ForeignPlayerLimitEnabled)
};
} // namespace
void apply_rule_base(LeImage& exe) {
// only the German data object has these addresses
if (exe.base() != 0x10000 || !exe.contains(::bmh::layout::GermanDataSegmentBegin) || !exe.contains(::bmh::layout::GermanDataCompatibilityEnd)) return;
for (const RuleBytes& r : kRuleBase) exe.patch(r.address, r.bytes.data(), r.bytes.size());
}
} // namespace bmh
-17
View File
@@ -1,17 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// One engine uses a shared rule profile across supported editions.
// OpenBMH deviates from the original: normalizes live-scene options, league
// strength ranges, option defaults, stadium prices and capacities, betting limits,
// and the foreign-player limit. Texts, currency, calendar, league structure, screen
// positions, season values, and edition-specific resort content stay loaded from data.
#include "formats/le.hpp"
namespace bmh {
// Applies the shared rule profile to compatible German executable images.
// Images without the matching data segment are left unchanged.
void apply_rule_base(LeImage& exe);
} // namespace bmh
+8 -8
View File
@@ -31,7 +31,7 @@ constexpr BlockDef kBlocks[] = {
{::bmh::layout::Cup_AdvanceCup_RuntimeField3, false, 1, Count::None, 0, false}, {::bmh::layout::LiveMatchday_FormatError_RuntimeField14, false, 6, Count::None, 0, false},
{::bmh::layout::ManagerRecords, false, 0x373c, Count::None, 0, false}, // 5 manager records of 0xB0C bytes
{::bmh::layout::Loans, false, 0x1e0, Count::None, 0, false},
{::bmh::layout::ManagerMatchHistory, false, 0x20d0, Count::None, 0, false}, // form history: 5 managers x 168 teams x 10
{::bmh::layout::ManagerMatchHistory, false, 0, Count::N42, 50, false}, // form history: 5 managers x 168 teams x 10
{::bmh::layout::MatchdayGroupDescriptors, false, 0x4e0, Count::None, 0, false}, {::bmh::layout::ManagerAutomation, false, 0x14, Count::None, 0, false},
{::bmh::layout::Desktops, false, 0x10e0, Count::None, 0, false}, // desktop layouts (.MEN), 5 x 0x360
{::bmh::layout::CareerSession_DispatchToto_RuntimeField, false, 1, Count::None, 0, false}, {::bmh::layout::Cup_AdvanceCup_RuntimeField4, false, 1, Count::None, 0, false},
@@ -43,7 +43,7 @@ constexpr BlockDef kBlocks[] = {
{::bmh::layout::Placements, false, 0x50, Count::None, 0, false}, {::bmh::layout::ActiveSelectors, false, 8, Count::None, 0, false},
{::bmh::layout::Career_CareerAddManager_RuntimeField2, false, 0x90, Count::None, 0, false}, {::bmh::layout::DeskActions_SubmitPoolsCoupon_RuntimeField, false, 0x2c, Count::None, 0, false},
{::bmh::layout::NextDeskManager, false, 8, Count::None, 0, false}, {::bmh::layout::Savestate_Layout_ExecutableField8, false, 10, Count::None, 0, false},
{::bmh::layout::DeskPosition, false, 1, Count::None, 0, false}, {::bmh::layout::DeskRecords_Teams_RuntimeField, false, 0x114, Count::None, 0, false},
{::bmh::layout::DeskPosition, false, 1, Count::None, 0, false}, {::bmh::layout::DeskRecords_Teams_RuntimeField, false, 0, Count::Teams, 2, false},
{::bmh::layout::CareerSession_FormatError_RuntimeField7, false, 2, Count::None, 0, false}, {::bmh::layout::Cup_AdvanceCup_RuntimeField6, false, 6, Count::None, 0, false},
{::bmh::layout::CurrentMatchday, false, 4, Count::None, 0, false}, // seed of the game RNG (GameRandom)
{::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField3, false, 1, Count::None, 0, false}, {::bmh::layout::CoachActive, false, 1, Count::None, 0, false},
@@ -51,12 +51,12 @@ constexpr BlockDef kBlocks[] = {
{::bmh::layout::CareerDuration, false, 1, Count::None, 0, false}, {::bmh::layout::GameMode, false, 1, Count::None, 0, false},
{::bmh::layout::CompetitionSelection, false, 4, Count::None, 0, false}, {::bmh::layout::ManagerCount, false, 1, Count::None, 0, false}, // number of managers
{::bmh::layout::SavedCompetition, false, 4, Count::None, 0, false}, {::bmh::layout::Difficulty, false, 1, Count::None, 0, false},
{::bmh::layout::StockExchange, false, 0x450, Count::None, 0, false}, {::bmh::layout::FundBlock, false, 0xa8, Count::None, 0, false},
{::bmh::layout::StockExchange, false, 0x450, Count::None, 0, false}, {::bmh::layout::FundBlock, false, 0, Count::N42, 1, false},
{::bmh::layout::Coupon, false, 100, Count::None, 0, false}, {::bmh::layout::Savestate_Layout_ExecutableField2, false, 3, Count::None, 0, false},
{::bmh::layout::Savestate_Layout_ExecutableField, false, 1, Count::None, 0, false}, {::bmh::layout::AdGroupId, false, 1, Count::None, 0, false},
{::bmh::layout::OfferSlots, false, 0x10, Count::None, 0, false}, {::bmh::layout::ForeignClubStrength, false, 0xfb, Count::None, 0, false},
{::bmh::layout::Career_Put_ExecutableField3, false, 0xbd, Count::None, 0, false}, {::bmh::layout::ClubShortNameOffsets, false, 0xa8, Count::None, 0, false},
{::bmh::layout::ClubKitSelectors, false, 0x1a3, Count::None, 0, false}, {::bmh::layout::Savestate_Layout_ExecutableField7, false, 0x18, Count::None, 0, false},
{::bmh::layout::Career_Put_ExecutableField3, false, 0xbd, Count::None, 0, false}, {::bmh::layout::ClubShortNameOffsets, false, 0, Count::N42, 1, false},
{::bmh::layout::ClubKitSelectors, false, 0, Count::Clubs, 1, false}, {::bmh::layout::Savestate_Layout_ExecutableField7, false, 0x18, Count::None, 0, false},
{::bmh::layout::ClubInfo_FormatError_RuntimeField, false, 0x420, Count::None, 0, false}, {::bmh::layout::Career_CareerManagersEnd_RuntimeField, false, 0x18, Count::None, 0, false},
{::bmh::layout::ClubInfo_FormatError_RuntimeField2, false, 0xc, Count::None, 0, false}, {::bmh::layout::DeskActions_Unsupported_RuntimeField, false, 4, Count::None, 0, false},
{::bmh::layout::Career_RemoveJoinLoans_RuntimeField, false, 800, Count::None, 0, false}, {::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField, false, 200, Count::None, 0, false},
@@ -98,7 +98,7 @@ constexpr BlockDef kBlocks[] = {
{::bmh::layout::Career_EuropeanClub_ExecutableField, false, 1, Count::None, 0, false}, {::bmh::layout::Career_EuropeanClub_ExecutableField2, false, 1, Count::None, 0, false},
{::bmh::layout::Career_EuropeanClub_ExecutableField3, false, 1, Count::None, 0, false}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField24, false, 0x28, Count::None, 0, false},
{::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField29, false, 0x14, Count::None, 0, false}, {::bmh::layout::ClubSeasonRecords, false, 4, Count::None, 0, false},
{::bmh::layout::ClubSeasonRecords, true, 0x3090, Count::None, 0, true}, // club records (168 x 74), only if pointer != 0
{::bmh::layout::ClubSeasonRecords, true, 0, Count::N42, 74, true}, // club records (168 x 74), only if pointer != 0
};
} // namespace
@@ -106,7 +106,7 @@ constexpr BlockDef kBlocks[] = {
SaveState::SaveState(const Bytes& stream, const DbCounts& c) : stream_(stream) {
// Teams in league play and cup-only teams are not part of DbCounts yet;
// these are the V2.24 values (CareerSession_DispatchLineup_RuntimeField, CareerSession_InstallLeagueSizes_RuntimeField6).
constexpr uint32_t kTeams = 138, kCupTeams = 30;
const uint32_t kTeams = c.league_teams, kCupTeams = c.cup_teams;
size_t pos = 0;
uint32_t last_pointer = 0;
for (const BlockDef& d : kBlocks) {
@@ -177,7 +177,7 @@ const SaveBlock& SaveState::block(uint32_t address) const {
namespace bmh {
std::vector<SaveBlock> save_layout(const DbCounts& c, bool club_records) {
constexpr uint32_t kTeams = 138, kCupTeams = 30;
const uint32_t kTeams = c.league_teams, kCupTeams = c.cup_teams;
std::vector<SaveBlock> out;
size_t pos = 0;
for (const BlockDef& d : kBlocks) {
+1 -1
View File
@@ -261,7 +261,7 @@ int32_t stadium_required_attendance(const GameState& source, int manager) {
if (manager < 0 || manager > 4) throw FormatError("stadium attendance: invalid manager");
GameState g = source;
const int team = g.manager_teams.at(size_t(manager));
const int league = team > 0x164 ? 0 : team_league(team);
const int league = team > (kNoTeam - 1) ? 0 : team_league(team);
if (league < 0 || league >= kLeagueCount)
throw FormatError("stadium attendance: manager has no Source league");
const int home_games = league_matchdays(league) / 2;
+24
View File
@@ -0,0 +1,24 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "game/calendar.hpp"
#include "formats/executable_layout.hpp"
#include "formats/le.hpp"
namespace bmh {
namespace { CalendarEpoch installed_epoch{2026, 2}; }
CalendarEpoch calendar_epoch_from_executable(const LeImage& exe) {
if(const auto* policy=exe.runtime_policy())return {int(policy->year),int(policy->weekday)};
constexpr auto setup = layout::CalendarDateSetup;
constexpr uint8_t weekday_prefix[] = {0xc6,0x44,0x24,0x04};
constexpr uint8_t month_and_year_prefix[] = {0xc6,0x44,0x24,0x0c,0x07,0xc7,0x04,0x24};
if (!exe.contains(setup) || !exe.contains(setup + 16))
throw FormatError("calendar: missing original date setup");
for (uint32_t i=0;i<sizeof weekday_prefix;++i)
if(exe.u8(setup+i)!=weekday_prefix[i])throw FormatError("calendar: unverified weekday setup");
for (uint32_t i=0;i<sizeof month_and_year_prefix;++i)
if(exe.u8(setup+5+i)!=month_and_year_prefix[i])throw FormatError("calendar: unverified year setup");
const auto year=exe.u32(setup+13);const int weekday=exe.u8(setup+4);
if(year<1600||year>9999||weekday>6)throw FormatError("calendar: invalid original epoch");
return {int(year),weekday};
}
void install_calendar_rules(const LeImage& exe) { installed_epoch=calendar_epoch_from_executable(exe); }
CalendarEpoch calendar_epoch() { return installed_epoch; }
}
+11
View File
@@ -0,0 +1,11 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
namespace bmh {
class LeImage;
struct CalendarEpoch { int year; int weekday; };
// Read verified original date-setup operands; unknown routines are rejected.
CalendarEpoch calendar_epoch_from_executable(const LeImage& exe);
void install_calendar_rules(const LeImage& exe);
// Isolated authored states default to the established synthetic calendar.
CalendarEpoch calendar_epoch();
}
+39 -20
View File
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "game/career.hpp"
#include "game/lineup.hpp"
#include <algorithm>
@@ -11,20 +12,38 @@ namespace bmh {
namespace {
constexpr size_t kPoolSlots = 2928; // CareerRuntimeField: the clubs' squads end here
constexpr size_t kTailFrom = 2928 + 40;
constexpr size_t kTailTo = 2972; // CareerRuntimeField2
constexpr size_t kExtraSlots = 3096; // CareerSession_DataDirectory_RuntimeField4: 54 extra players from here
constexpr size_t kSquadSlots = 3096 + 54;
constexpr int kLeagueTeams = 138; // CareerSession_DispatchLineup_RuntimeField
const int& kPoolSlots = runtime_dimensions.pool_first; // CareerRuntimeField: the clubs' squads end here
const int& kTailFrom = runtime_dimensions.market_special_first;
const int& kTailTo = runtime_dimensions.free_first; // CareerRuntimeField2
const int& kExtraSlots = runtime_dimensions.extra_slots_first; // CareerSession_DataDirectory_RuntimeField4: 54 extra players from here
const int& kSquadSlots = runtime_dimensions.total_slots;
const int& kLeagueTeams = runtime_dimensions.league_teams; // CareerSession_DispatchLineup_RuntimeField
// LeagueSizes: clubs per league; LeagueStrengthRanges: (minimum, maximum) strength per league.
// (the clubs per league are kLeagueSizes, schedule.hpp)
constexpr int kLeagueStrength[9][2] = {{71, 93}, {49, 71}, {28, 49}, {28, 49}, {10, 28},
int kLeagueStrength[9][2] = {{71, 93}, {49, 71}, {28, 49}, {28, 49}, {10, 28},
{85, 95}, {90, 95}, {75, 95}, {80, 95}};
} // namespace
std::pair<int,int> career_strength_range(int league) {
if (league<0 || league>=9) throw FormatError("career: invalid league range");
return {kLeagueStrength[league][0],kLeagueStrength[league][1]};
}
void install_career_rules(const LeImage& exe) {
int next[9][2]{};
for (int league = 0; league < 9; ++league) {
for (int bound = 0; bound < 2; ++bound)
next[league][bound] = exe.u8(layout::LeagueStrengthRanges + uint32_t(league * 2 + bound));
if (next[league][0] > next[league][1] || next[league][1] > 99)
throw FormatError("career: unsupported original league strength range");
}
install_lineup_rules(exe);
for (int league = 0; league < 9; ++league)
for (int bound = 0; bound < 2; ++bound) kLeagueStrength[league][bound] = next[league][bound];
}
void generate_player(GameState& g, int id, int level_flags, GameRandom& game, WatcomRandom& rand) {
Player& p = g.players.at(size_t(id));
const bool keep_age = (level_flags & 0x1000) != 0, exact = (level_flags & 0x2000) != 0;
@@ -82,7 +101,7 @@ void startup_players(GameState& g, GameRandom& game, WatcomRandom& rand) {
namespace bmh {
GameState startup_state(const LeImage& exe, const Database& db, const Bytes& m3_men, const Bytes& m3_dat) {
const DbCounts counts;
const DbCounts counts=db.counts;
const std::vector<SaveBlock> layout = save_layout(counts, true);
Bytes stream;
for (const SaveBlock& b : layout) {
@@ -135,7 +154,7 @@ GameState startup_state(const LeImage& exe, const Database& db, const Bytes& m3_
if (b.heap) {
for (size_t i = 0; i < db.players.size() && 4 * i + 3 < data.size(); i++) {
uint32_t w = b.address == ::bmh::layout::PlayerConditionTechniqueForm ? db.players[i].w35c : b.address == ::bmh::layout::PlayerSkillWords ? db.players[i].w368 : db.players[i].w364;
if (b.address == ::bmh::layout::PlayerSkillWords && i + 32 >= db.players.size())
if (b.address == ::bmh::layout::PlayerSkillWords && !runtime_dimensions.expanded && i + 32 >= db.players.size())
w = (w & 0x07ffffffu) | uint32_t(exe.u8(::bmh::layout::Career_BuildStadium_RuntimeField4 - uint32_t(db.players.size() - i))) << 27;
for (int k = 0; k < 4; k++) data[4 * i + size_t(k)] = uint8_t(w >> (8 * k));
}
@@ -194,14 +213,14 @@ void new_career_markets_and_moods(GameState& g, GameRandom& game, WatcomRandom&
}
bool new_career_players(GameState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report) {
for (size_t slot = 0; slot < 2928; slot++) {
for (size_t slot = 0; slot < runtime_dimensions.pool_first; slot++) {
const int id = g.squad_slots.at(slot) & 0x0fff;
if (id == 0x0fff) continue;
Player& p = g.players.at(size_t(id));
p.w364 |= uint32_t(rand.range(4, 0x10)) << 21;
p.w368 = (p.w368 & 0xffffc000u) + uint32_t(rand.range(0, 0x3fff));
}
for (int slot = 3096; slot < 3096 + 0x36; slot++)
for (int slot = runtime_dimensions.extra_slots_first; slot < runtime_dimensions.extra_slots_first + 0x36; slot++)
if (!release_player(g, slot, game, rand, report)) return false;
return !report.unsupported;
}
@@ -239,7 +258,7 @@ bool human_club(const GameState& g, int team) {
const int managers = g.memory.u8(::bmh::layout::ManagerCount);
for (int m = 0; m < managers; m++)
if (team_of(g, m) == uint16_t(team)) return true;
return team_of(g, 0) == 0x165 && team_of(g, 4) == uint16_t(team);
return team_of(g, 0) == kNoTeam && team_of(g, 4) == uint16_t(team);
}
// OpenBMH deviates from the original: skips reserved calendar positions when assigning a joining manager to a club.
@@ -412,17 +431,17 @@ bool career_add_manager(GameState& g, const LeImage& exe, int m, const CareerMan
if (!g.memory.has(::bmh::layout::ManagerCount) || m < 0 || m >= 4 ||
g.memory.u8(::bmh::layout::ManagerCount) > 4 || m >= g.memory.u8(::bmh::layout::ManagerCount) ||
size_t(m) >= g.manager_teams.size() || g.manager_records.size() < 5 * kRecord ||
choice.team < 0 || choice.team >= 168 || size_t(choice.team) >= g.club_ids.size() ||
choice.team < 0 || choice.team >= runtime_dimensions.record_teams || size_t(choice.team) >= g.club_ids.size() ||
choice.league < 0 || choice.league > 4 || choice.strength < 0 || choice.strength > 2 ||
choice.portrait < 0 || choice.portrait > 11 || choice.name.size() > 24 ||
g.tactics.size() < size_t(m + 1) * 0x840 ||
g.manager_ratings.size() < size_t(m + 1) * 0x3c ||
g.manager_results.size() < g.manager_teams.size() * 0x690 ||
g.squad_slots.size() < kSquadSlots || g.club_ids.size() < 168 ||
g.team_morale.size() < 168 || g.team_flags.size() < 168 ||
g.club_heap_bc.size() < 168 * 2 || g.club_heap_78.size() < 168 * 2 ||
g.club_heap_b8.size() < 168 || g.position_history.size() < 138 * 0x1a ||
(!g.club_table.empty() && g.club_table.size() < 168 * 0x4a) ||
g.manager_results.size() < g.manager_teams.size() * (runtime_dimensions.record_teams * 10) ||
g.squad_slots.size() < kSquadSlots || g.club_ids.size() < runtime_dimensions.record_teams ||
g.team_morale.size() < runtime_dimensions.record_teams || g.team_flags.size() < runtime_dimensions.record_teams ||
g.club_heap_bc.size() < runtime_dimensions.record_teams * 2 || g.club_heap_78.size() < runtime_dimensions.record_teams * 2 ||
g.club_heap_b8.size() < runtime_dimensions.record_teams || g.position_history.size() < runtime_dimensions.league_teams * 0x1a ||
(!g.club_table.empty() && g.club_table.size() < runtime_dimensions.record_teams * 0x4a) ||
g.player_bonus.size() < g.players.size() || g.player_cards.size() < g.players.size() ||
!exe.contains(::bmh::layout::Career_CareerAddManager_ExecutableField) || !exe.contains(::bmh::layout::Career_BuildStadium_RuntimeField3 + 0x15 * 5) ||
!exe.contains(::bmh::layout::Career_BuildStadium_RuntimeField + 4 * 0x17 + 0x15)) {
@@ -535,7 +554,7 @@ bool career_add_manager(GameState& g, const LeImage& exe, int m, const CareerMan
new_board_entry(g, m, int(i), int(slot), rand);
g.tactics.at(size_t(m) * 0x840 + i * 0x58 + 0xd) = 100;
}
for (size_t i = 0; i < 0x690; i++) g.manager_results.at(size_t(m) * 0x690 + i) = 0xff;
for (size_t i = 0; i < (runtime_dimensions.record_teams * 10); i++) g.manager_results.at(size_t(m) * (runtime_dimensions.record_teams * 10) + i) = 0xff;
const uint8_t level = mem.u8(::bmh::layout::Difficulty);
const uint32_t money = level == 0 ? 50000000u : 4000000u - level * 200000u;
put32(r, rec + 0x314, money);
+4
View File
@@ -24,6 +24,10 @@
namespace bmh {
// Install the nine strength ranges from the loaded edition, never a shared replacement.
void install_career_rules(const LeImage&);
std::pair<int,int> career_strength_range(int league);
// OpenBMH deviates from the original: uses the supported player-generation ranges and excludes reserved calendar positions when assigning managers.
// GeneratePlayer with the supported rule profile patch GeneratePlayer2: new values for player `id` around
// `level` (low 12 bits of `level_flags`; 0x1000 = leave the age at 0, 0x2000 = exactly
+1 -1
View File
@@ -4,7 +4,7 @@
#include <stdexcept>
namespace bmh {
ClubInfoEntry prepare_club_info_entry(GameState& g, int team) {
if (team < 0 || (team >= 138 && team != kNoTeam))
if (team < 0 || (team >= runtime_dimensions.league_teams && team != kNoTeam))
throw std::invalid_argument("club info: team has no squad");
const SquadRange range = squad_range(team);
if (range.first > g.squad_slots.size() || range.count > g.squad_slots.size() - range.first)
+4 -4
View File
@@ -31,9 +31,9 @@ int source_manager(const GameState& g, int club) {
int club_of_slot(int slot) {
if (slot < 0) return -1;
if (slot < 90 * 24) return slot / 24;
if (slot < 90 * 24 + 48 * 16) return (slot - 90 * 8) / 16;
if (slot >= 3072 && slot < 3096) return kNoTeam;
if (slot < runtime_dimensions.big_squad_teams * 24) return slot / 24;
if (slot < runtime_dimensions.pool_first) return (slot - runtime_dimensions.big_squad_teams * 8) / 16;
if (slot >= runtime_dimensions.national_slots_first && slot < runtime_dimensions.extra_slots_first) return kNoTeam;
return -1;
}
@@ -72,7 +72,7 @@ ClubPlayerDetailContext club_player_detail_context(const GameState& g, const Clu
out.primary_club = -1;
} else {
if (s.rendered_row < 0 || s.rendered_row >= 24 || s.runtime_team < 0 ||
(s.runtime_team >= 138 && s.runtime_team != kNoTeam))
(s.runtime_team >= runtime_dimensions.league_teams && s.runtime_team != kNoTeam))
throw std::invalid_argument("player detail: invalid runtime club");
const auto range = squad_range(s.runtime_team);
if (range.first + range.count > g.squad_slots.size()) throw std::invalid_argument("player detail: truncated squad");
+1 -1
View File
@@ -53,7 +53,7 @@ struct ClubPlayerDetailContext {
// OpenTransferEditor passes actual slots CareerRuntimeField + entry (0..39) for ordinary
// transfer-market pool cards. It never turns the entry into a squad row.
constexpr int kClubPlayerDetailMarketPoolFirst = 0xb70;
inline const int& kClubPlayerDetailMarketPoolFirst = runtime_dimensions.pool_first;
constexpr int kClubPlayerDetailMarketPoolCount = 40;
// Resolves runtime club, explicit row and Source loan/national ownership without
+1 -1
View File
@@ -482,7 +482,7 @@ void order_national_cup_ties(GameState& g, int teams, int offset) {
for (int i = 0; i < teams; i += 2) {
if (lower <= team(i + 1) && team(i) < lower)
swap16(mem, list + uint32_t(i) * 2, list + uint32_t(i + 1) * 2);
auto league = [](int t) { return t > 0x164 ? 0 : team_league(t); };
auto league = [](int t) { return t > (kNoTeam - 1) ? 0 : team_league(t); };
const int la = league(team(i)), lb = league(team(i + 1));
weights.push_back(uint8_t(kWeight[la < 10 ? la : 9] + kWeight[lb < 10 ? lb : 9]));
}
+12 -12
View File
@@ -69,7 +69,7 @@ FriendlyBookingQuote make_friendly_quote(const GameState& g, int manager, int op
return out;
}
const int own_team = g.manager_teams[size_t(manager)];
if (own_team < 0 || own_team >= 168 || opponent < 0 || opponent >= 168 || opponent == own_team) {
if (own_team < 0 || own_team >= runtime_dimensions.record_teams || opponent < 0 || opponent >= runtime_dimensions.record_teams || opponent == own_team) {
out.status = FriendlyQuoteStatus::invalid_opponent;
return out;
}
@@ -122,7 +122,7 @@ NationalFriendlyQuote make_national_friendly_quote(const GameState& g,
return out;
}
// Page 4 cannot return Germany (0); the engine boundary repeats that gate.
if (opponent <= kNoTeam || opponent > 0x1a2 || opponent == kNoTeam) {
if (opponent <= kNoTeam || opponent > (kNoTeam + 61) || opponent == kNoTeam) {
out.terms.status = FriendlyQuoteStatus::invalid_opponent;
return out;
}
@@ -624,7 +624,7 @@ TransferActionResult submit_transfer_bid_impl(GameState& g, const TransferBidReq
const bool source_direct_candidate = source_hooks && seller_manager < 0 &&
fee_pct >= 110 && salary_pct >= g.memory.u8(entry + 0x55);
if (source_direct_candidate) {
if (request.list_entry >= 40 || seller < 0 || (seller >= 0x8a && seller != 0x0fff) || seller == buyer ||
if (request.list_entry >= 40 || seller < 0 || (seller >= runtime_dimensions.league_teams && seller != 0x0fff) || seller == buyer ||
request.manager < 0 || size_t(request.manager) >= g.manager_teams.size() ||
!g.memory.has(::bmh::layout::ActiveManager) || g.memory.u8(::bmh::layout::ActiveManager) != request.manager ||
source_hooks->direct_mode != HumanBuyerSaleDirectMode::ordinary_ai_purchase ||
@@ -790,7 +790,7 @@ TransferActionResult submit_transfer_bid_source_impl(GameState& g, const Transfe
// ordinary settlement already removes players using that actual range.
// Higher club IDs have no ordinary squad; do not invent their settlement
// or let ReleasePlayer reach its missing-player/internal-error21 boundary.
if (seller != 0x0fff && seller >= 138) {
if (seller != 0x0fff && seller >= runtime_dimensions.league_teams) {
report.fail(kOrdinarySellerBoundary);
out.status = TransferActionStatus::unsupported;
out.player = player; out.list_entry = request.list_entry;
@@ -1009,7 +1009,7 @@ TransferActionResult submit_transfer_bid_source_impl(GameState& g, const Transfe
std::optional<TransferMarketSnapshotPreview> transfer_market_snapshot_preview(
const GameState& g,int manager,int runtime_club,int index) {
if(manager<0||manager>=4||size_t(manager)>=g.manager_teams.size()||
g.manager_teams[size_t(manager)]!=runtime_club||runtime_club<0||runtime_club>=138||index<0||index>=12)
g.manager_teams[size_t(manager)]!=runtime_club||runtime_club<0||runtime_club>=runtime_dimensions.league_teams||index<0||index>=12)
return std::nullopt;
const auto owner=squad_range(runtime_club);
int count=0,ordinal=-1;
@@ -1036,7 +1036,7 @@ std::optional<TransferMarketSnapshotPreview> transfer_market_snapshot_preview(
// Require exactly one genuine ledger and its authenticated owner.
if(borrower!=-1||int(loan>>12&0x3ff)!=runtime_club)return std::nullopt;
borrower=int(loan>>22&0x3ff);
if(borrower<0||borrower>=138||borrower==runtime_club)return std::nullopt;
if(borrower<0||borrower>=runtime_dimensions.league_teams||borrower==runtime_club)return std::nullopt;
}
if(borrower<0)return std::nullopt;
const auto range=squad_range(borrower);
@@ -1072,9 +1072,9 @@ TransferMarketPreviewResult quote_transfer_market_preview_source(
return unsupported("market preview: stale Source player/slot");
if(request.purchase) {
if(request.snapshot_index!=-1)return unsupported("market preview: snapshot is not a purchase row");
if(request.source_slot<2928||request.source_slot>=2928+40)
if(request.source_slot<runtime_dimensions.pool_first||request.source_slot>=runtime_dimensions.pool_first+40)
return unsupported("market preview: purchase is not an ordinary market row");
const uint32_t seller_at=::bmh::layout::EditorList+uint32_t(request.source_slot-2928)*0x58+8;
const uint32_t seller_at=::bmh::layout::EditorList+uint32_t(request.source_slot-runtime_dimensions.pool_first)*0x58+8;
if(!g.memory.has(seller_at)||!g.memory.has(seller_at+1))
return unsupported("market preview: missing Source seller word");
const uint16_t raw=g.memory.u16(seller_at);
@@ -1091,7 +1091,7 @@ TransferMarketPreviewResult quote_transfer_market_preview_source(
// with the unchanged42307 formula; do not synthesize a Native slot.
} else {
if(request.snapshot_index!=-1)return unsupported("market preview: invalid snapshot index");
if(request.seller!=request.runtime_club||request.runtime_club>=138)
if(request.seller!=request.runtime_club||request.runtime_club>=runtime_dimensions.league_teams)
return unsupported("market preview: outgoing club is not an ordinary owned squad");
const auto range=squad_range(request.runtime_club);
if(range.count==0||range.first+range.count>g.squad_slots.size()||
@@ -1133,7 +1133,7 @@ int editor_slot(const GameState& g,const TransferOfferEditorRequest& r) {
std::string editor_identity(const GameState& g,const TransferOfferEditorRequest& r) {
if(r.manager<0||r.manager>=4||size_t(r.manager)>=g.manager_teams.size()||
!g.memory.has(::bmh::layout::ActiveManager)||g.memory.u8(::bmh::layout::ActiveManager)!=r.manager||
g.manager_teams[size_t(r.manager)]!=r.runtime_club||r.runtime_club<0||r.runtime_club>=138)
g.manager_teams[size_t(r.manager)]!=r.runtime_club||r.runtime_club<0||r.runtime_club>=runtime_dimensions.league_teams)
return "OpenTransferEditor: stale ordinary manager/team";
const size_t record=size_t(r.manager)*kRecordSize;
if(record+kRecordSize>g.manager_records.size()||
@@ -1143,7 +1143,7 @@ std::string editor_identity(const GameState& g,const TransferOfferEditorRequest&
const bool ordinary_entry = r.list_entry >= 0 && r.list_entry < 40 && !r.poach && !r.loan_return_entry;
const bool poach_entry = r.list_entry >= 40 && r.list_entry < 44 && r.poach && !r.loan_return_entry;
const bool return_entry = r.list_entry >= 40 && r.list_entry < 44 && r.loan_return_entry && !r.poach;
if((!ordinary_entry&&!poach_entry&&!return_entry)||r.source_slot!=2928+r.list_entry||
if((!ordinary_entry&&!poach_entry&&!return_entry)||r.source_slot!=runtime_dimensions.pool_first+r.list_entry||
size_t(r.source_slot)>=g.squad_slots.size()||r.expected_player<0||r.expected_player>=0x0fff||
size_t(r.expected_player)>=g.players.size()||
int(g.squad_slots[size_t(r.source_slot)]&0x0fff)!=r.expected_player)
@@ -1159,7 +1159,7 @@ std::string editor_identity(const GameState& g,const TransferOfferEditorRequest&
const int seller=int(r.expected_seller_word&0x7fff);
if(r.expected_seller_word==0xffff||seller==r.runtime_club)
return "OpenTransferEditor: targeted/invalid seller is outside ordinary editor";
if(seller!=0x0fff&&seller>=138)return kOrdinarySellerBoundary;
if(seller!=0x0fff&&seller>=runtime_dimensions.league_teams)return kOrdinarySellerBoundary;
// OpenTransferEditor: the original refuses a loan from a free agent (seller 0x0fff) with the message
// DeskActionsRuntimeField6 (SDLFlushEvents3) - a rule of the game, not a gap: the code names it
if(r.loan&&r.expected_seller_word==0x0fff)return "free_agent_loan_refused";
+21
View File
@@ -3,9 +3,12 @@
#include "game/environment.hpp"
#include <algorithm>
#include <cstdlib>
#include <utility>
namespace bmh {
namespace {
bool supported_environment = true; // Synthetic state tests explicitly use the verified monthly model.
uint32_t youth_at(int manager) { return layout::EnvironmentYouthTeams + uint32_t(manager) * 0x24; }
uint32_t spending_at(int manager, int item) {
return layout::Spending + uint32_t(manager) * 0x24 + uint32_t(item) * 4;
@@ -29,6 +32,22 @@ uint32_t academy_paid(const GameState& g, int manager) {
uint32_t(g.manager_records.at(at + 2)) << 16 | uint32_t(g.manager_records.at(at + 3)) << 24;
}
}
void install_environment_rules(const LeImage& exe) {
for (size_t i=0;i<kEnvironmentStep.size();++i) {
const uint32_t at=layout::EnvironmentBudgetSteps+uint32_t(i);
if (!exe.contains(at) || exe.u8(at)==0) { supported_environment=false; return; }
kEnvironmentStep[i]=int32_t(exe.u8(at))*1000;
}
if(const auto* policy=exe.runtime_policy()) { supported_environment=policy->environment_verified!=0;return; }
uint64_t fingerprint = 14695981039346656037ull;
for (const auto [first,last] : {std::pair{layout::EnvironmentVerifiedCodeBegin,layout::EnvironmentVerifiedCodeEnd},std::pair{layout::EnvironmentVerifiedHookBegin,layout::EnvironmentVerifiedHookEnd}}) {
if (!exe.contains(first) || !exe.contains(last-1)) { supported_environment=false; return; }
for (uint32_t at=first;at<last;++at) fingerprint=(fingerprint ^ exe.u8(at))*1099511628211ull;
}
// Fingerprints identify verified behaviour, not filenames, dates or artwork.
supported_environment = fingerprint==0xc2488a656f340e99ull || fingerprint==0x19adba7ef3eda507ull;
}
bool environment_rules_supported() { return supported_environment; }
int32_t environment_monthly_cost(const GameState& g, int manager, int item) {
const auto value = g.memory.u32(spending_at(manager, item));
if (item == kYouthAcademy && legacy_academy(g, manager) && academy_paid(g, manager) >= value) return 0;
@@ -39,6 +58,7 @@ bool environment_academy_active(const GameState& g, int manager) {
return value != 0 && (!legacy_academy(g, manager) || academy_paid(g, manager) >= value);
}
EnvironmentState environment_state(const GameState& g, int manager) {
if (!supported_environment) throw FormatError("environment: this original program variant is not verified");
validate_manager(g, manager);
EnvironmentState result;
for (int i = 0; i < kEnvironmentItems; ++i) {
@@ -56,6 +76,7 @@ EnvironmentState environment_state(const GameState& g, int manager) {
}
EnvironmentResult set_environment(GameState& g, int manager, int item, int level, std::string* message) {
if (message) message->clear();
if (!supported_environment) return EnvironmentResult::invalid;
if (manager < 0 || size_t(manager) >= g.manager_teams.size() || item < 0 || item >= kEnvironmentItems ||
level < 0 || level > 6 || !g.memory.has(spending_at(manager, item) + 3))
return EnvironmentResult::invalid;
+6 -2
View File
@@ -4,14 +4,18 @@
#include <cstdint>
#include <string>
#include "game/random.hpp"
#include "formats/le.hpp"
#include "game/state.hpp"
namespace bmh {
// Verified original-program capability; unknown environment variants are not guessed.
void install_environment_rules(const LeImage&);
bool environment_rules_supported();
constexpr int kEnvironmentItems = 6;
enum EnvironmentItem : int { kYouthYoungest = 0, kYouthAcademy = 1, kYouthOldest = 2,
kCoTrainer = 3, kDoctor = 4, kPhysio = 5 };
// OpenBMH deviates from the original: uses six monthly environment budgets across data editions while retaining the shared staff prices and academy player-generation strength bands.
inline constexpr std::array<int32_t, kEnvironmentItems> kEnvironmentStep = {2000, 4000, 5000, 5000, 5000, 5000};
// Monthly environment model verified in the supported CD and Diamond 3.6/3.7 programs.
inline std::array<int32_t, kEnvironmentItems> kEnvironmentStep = {2000, 4000, 5000, 5000, 5000, 5000};
struct EnvironmentState {
std::array<int32_t, kEnvironmentItems> monthly{};
std::array<int, kEnvironmentItems> level{};
+5 -5
View File
@@ -108,7 +108,7 @@ void validate(const GameState& g,const LeaguePairingsOwner& o) {
require(o.supported&&!o.closed&&o.manager>=0&&o.manager<4&&
size_t(o.manager)<g.manager_teams.size()&&g.memory.has(::bmh::layout::ActiveManager)&&
g.memory.u8(::bmh::layout::ActiveManager)==o.manager&&g.manager_teams[size_t(o.manager)]==o.runtime_club&&
(national||(o.runtime_club>=0&&o.runtime_club<138))&&
(national||(o.runtime_club>=0&&o.runtime_club<runtime_dimensions.league_teams))&&
size_t(o.runtime_club)<g.club_ids.size()&&
g.club_ids[size_t(o.runtime_club)]==o.club_identity,
"pairings: stale or unsupported manager identity");
@@ -124,12 +124,12 @@ void validate(const GameState& g,const LeaguePairingsOwner& o) {
(g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(o.manager))&0x0f)==8)&&
g.memory.has(::bmh::layout::LeagueTableDisplayModes+uint32_t(o.manager)*2+1),
"pairings: missing preferences or unsupported saved list mode");
require(g.results.size()>=kResultsSize&&g.club_ids.size()>=138&&g.league_rounds.size()>=9&&
require(g.results.size()>=kResultsSize&&g.club_ids.size()>=runtime_dimensions.league_teams&&g.league_rounds.size()>=9&&
g.memory.has(::bmh::layout::Postponed+0xef)&&g.memory.has(::bmh::layout::CompetitionCalendar+365*2+1),
"pairings: incomplete Native schedule");
const auto selection_valid=[&](int team,int identity) {
return team<0 ? team>=-2&&identity==-1 :
team<138&&team_league(team)==o.league&&g.club_ids.at(size_t(team))==identity;
team<runtime_dimensions.league_teams&&team_league(team)==o.league&&g.club_ids.at(size_t(team))==identity;
};
require(selection_valid(o.search_first,o.search_first_identity)&&
selection_valid(o.search_second,o.search_second_identity)&&
@@ -181,7 +181,7 @@ void validate(const GameState& g,const LeaguePairingsOwner& o) {
o.filter_offset>=0&&o.filter_offset%10==0&&o.filter_team>=-2,
"pairings: invalid Source club-filter mode");
if(o.filter_team>=0) {
require(o.filter_team<138&&team_league(o.filter_team)==o.league&&
require(o.filter_team<runtime_dimensions.league_teams&&team_league(o.filter_team)==o.league&&
g.club_ids.at(size_t(o.filter_team))==o.filter_identity&&
(o.filter_offset==0||o.filter_offset<filtered_fixture_count(o.league,o.filter_team)),
"pairings: stale or out-of-range filtered club");
@@ -315,7 +315,7 @@ LeaguePairingsOwner open_league_pairings_source(GameState& g,int manager,const L
require(manager>=0&&manager<4&&size_t(manager)<g.manager_teams.size(),"pairings: unsupported manager");
LeaguePairingsOwner out;out.manager=manager;out.runtime_club=g.manager_teams[size_t(manager)];
const bool national=out.runtime_club==kNoTeam;
require((national||(out.runtime_club>=0&&out.runtime_club<138))&&
require((national||(out.runtime_club>=0&&out.runtime_club<runtime_dimensions.league_teams))&&
size_t(out.runtime_club)<g.club_ids.size(),"pairings: unsupported or unowned manager");
out.club_identity=g.club_ids[size_t(out.runtime_club)];
// TeamLeague2 maps the Original national runtime team 0x165 to league 0.
+58 -6
View File
@@ -1,6 +1,9 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "game/lineup.hpp"
#include "formats/le.hpp"
#include "game/match.hpp"
#include "game/weekly.hpp"
#include <cstdlib>
#include <stdexcept>
@@ -10,6 +13,7 @@
namespace bmh {
namespace {
bool original_foreign_limit_enabled = false;
// Position type by formation depth x (table at layout field).
constexpr int8_t kTypeByDepth[24] = {0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 0, 1, 2, 2};
@@ -33,7 +37,7 @@ uint8_t formation_byte(const GameState& g, size_t index) {
}
bool pitch_context_valid(const GameState& g, int manager, int team) {
if (manager < 0 || manager > 3 || team < 0 || team >= 138 || g.lineups_frozen ||
if (manager < 0 || manager > 3 || team < 0 || team >= runtime_dimensions.league_teams || g.lineups_frozen ||
!g.memory.has(::bmh::layout::ActiveManager) || !g.memory.has(::bmh::layout::GameMode) ||
g.memory.u8(::bmh::layout::ActiveManager) != manager || g.memory.u8(::bmh::layout::GameMode) < 1 || g.memory.u8(::bmh::layout::GameMode) > 3 ||
size_t(manager) >= g.manager_teams.size() || g.manager_teams[size_t(manager)] != team ||
@@ -317,8 +321,12 @@ bool save_pitch_formation_source(GameState& g, int manager_slot, int runtime_clu
}
}
void install_lineup_rules(const LeImage& exe) {
original_foreign_limit_enabled = exe.u8(layout::ForeignPlayerLimitEnabled) != 0;
}
static void auto_lineup_impl(GameState& g, int team, int mode, int manager) {
if (team >= 138 && team != kNoTeam) return; // teams without squads
if (team >= runtime_dimensions.league_teams && team != kNoTeam) return; // teams without squads
if (g.lineups_frozen) return; // LineupRuntimeField (the season change)
const bool improve_from_reserves = (mode & 0x80) != 0;
mode &= 0x7F;
@@ -574,8 +582,52 @@ static void auto_lineup_impl(GameState& g, int team, int mode, int manager) {
break;
}
}
// OpenBMH deviates from the original: disables the foreign-player limit in the supported rule profile.
// (foreign-player limit ForeignPlayerLimitEnabled is off in the supported rule profile)
if (original_foreign_limit_enabled) {
const int country = team_region(team) & 0xff;
const int allowed = 3 - int(country != 0);
std::vector<int> foreign_rows, foreign_roles;
for (int row = 0; row < 11; ++row) {
const int id = g.squad_slots.at(range.first + row) & 0x0fff;
if (id != 0x0fff && nationality(g, id) != country) {
foreign_rows.push_back(row);
foreign_roles.push_back(g.players.at(id).position());
}
}
int tolerance = 0;
for (int attempt = 0; foreign_rows.size() > size_t(allowed) && attempt < 200; ++attempt) {
++tolerance;
if (tolerance > 100) {
// No suitable domestic reserve: retain the original short-lineup
// outcome rather than fielding more foreign players than allowed.
g.squad_slots.at(range.first + foreign_rows.back()) &= 0x1fff;
foreign_rows.pop_back(); foreign_roles.pop_back();
continue;
}
for (int row = 11; row < players && value[row] != kUnavailable; ++row) {
const int id = g.squad_slots.at(range.first + row) & 0x0fff;
if (id == 0x0fff || nationality(g, id) != country) continue;
const int role = g.players.at(id).position();
const int replaced_role = foreign_roles.back();
if ((role == 0 && replaced_role != 0 && tolerance <= 7) ||
std::abs(role - replaced_role) >= tolerance) continue;
const int field = foreign_rows.back();
foreign_rows.pop_back(); foreign_roles.pop_back();
auto& incoming = g.squad_slots.at(range.first + row);
auto& outgoing = g.squad_slots.at(range.first + field);
incoming = uint16_t((incoming & 0x1fff) | 0x8000);
outgoing = uint16_t((outgoing & 0x1fff) | (row < 17 ? 0x4000 : 0));
std::swap(incoming, outgoing);
std::swap(value[row], value[field]);
if (manager >= 0) {
std::swap_ranges(board(row), board(row) + 0x58, board(field));
std::swap(board(row)[0x41], board(field)[0x41]);
std::swap(board(row)[0x42], board(field)[0x42]);
}
tolerance = 0;
if (foreign_rows.size() <= size_t(allowed)) break;
}
}
}
// After a full line-up every player in the eleven or on the bench notes his squad slot
// (relative to the squad start) in bits 0-4 of his card word (*PlayerCards).
if (!first_eleven_only && !g.player_cards.empty())
@@ -594,7 +646,7 @@ void auto_lineup(GameState& g, int team, int mode) {
void auto_lineup_parked_club_source(GameState& g, int team, int mode) {
constexpr size_t record = 4*0xb0c+0x290;
if (team<0 || team>=138 || g.manager_teams.size()!=1 || g.manager_teams[0]!=kNoTeam ||
if (team<0 || team>=runtime_dimensions.league_teams || g.manager_teams.size()!=1 || g.manager_teams[0]!=kNoTeam ||
!g.memory.has(::bmh::layout::CoachActive) || g.memory.u8(::bmh::layout::CoachActive)==0 ||
!g.memory.has(::bmh::layout::ManagerCount) || g.memory.u8(::bmh::layout::ManagerCount)!=1 ||
!g.memory.has(::bmh::layout::OriginalManagerCount) || g.memory.u8(::bmh::layout::OriginalManagerCount)<1 || g.memory.u8(::bmh::layout::OriginalManagerCount)>4 ||
@@ -630,7 +682,7 @@ void quicksort_by_key(int16_t* items, uint32_t* keys, int count, bool ascending)
}
bool substitute(GameState& g, int team, int off, int mode, WatcomRandom& rand) {
if (!(team < 138 || team == kNoTeam)) return false;
if (!(team < runtime_dimensions.league_teams || team == kNoTeam)) return false;
const int manager = g.manager_of(team);
int used = g.team_flags.at(team) >> 5 & 7; // substitutions so far
if (mode == 10) {
+7 -3
View File
@@ -1,6 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// OpenBMH deviates from the original: disables the foreign-player limit and supports owner-bound designated set-piece selection.
// OpenBMH deviates from the original: supports owner-bound designated set-piece selection.
// Automatic line-up of computer teams, port of Int2.
//
// The squad of a team is a run of squad slots (squad_range). The first 11 slots are the
@@ -21,7 +21,7 @@
// The chosen player is swapped into slot p and flagged 0x8000 (slots 0-10) or 0x4000.
//
// Ported: assistant training-camp familiarity penalty and detailed position scoring at
// difficulty >= 6. The foreign-player limit (ForeignPlayerLimitEnabled) is off in supported rule profile.
// difficulty >= 6. The supplied edition controls the original foreign-player limit.
#include <cstdint>
#include <array>
@@ -30,6 +30,10 @@
#include "game/state.hpp"
namespace bmh {
class LeImage;
// Install the supplied edition's original automatic-lineup rule switch.
void install_lineup_rules(const LeImage& exe);
// Games: in-place quicksort (Hoare partition, middle element as pivot) of `keys`
// descending (ascending if `ascending`), comparing as unsigned 32-bit, moving `items`
@@ -93,7 +97,7 @@ bool save_pitch_formation_source(GameState& g, int manager_slot, int runtime_clu
int formation, uint8_t expected_weights,
const std::array<uint8_t, 22>& formation_positions);
// OpenBMH deviates from the original: disables the foreign-player limit and supports owner-bound designated set-piece selection.
// OpenBMH deviates from the original: supports owner-bound designated set-piece selection.
// supported rule profile NormalizePitchSetPieceSource/NormalizePitchSetPieceSource3/NormalizePitchSetPieceSource2/NormalizePitchSetPieceSource4: deterministic, owner-bound
// set-piece presentation state. Stored takers are player_id+1; zero is AUTO.
bool normalize_pitch_set_piece_source(GameState& g, int manager_slot, int runtime_club);
+1 -1
View File
@@ -103,7 +103,7 @@ void rate_side(GameState& g, const MatchSetup& m, int side, int previous6, Watco
}
}
if (side == 0) {
int league = team > 0x164 ? 0 : team_league(team); // TeamLeague2
int league = team > (kNoTeam - 1) ? 0 : team_league(team); // TeamLeague2
int base = kLeagueCrowd[league < 10 ? league : 9] * 1000;
if (unsigned(rand.range(base + 3000, base + 6000)) < unsigned(m.spectators)) {
// a human manager's side with record +0x289 set suffers more from a full house
+7 -7
View File
@@ -78,7 +78,7 @@ MinuteReport MatchEngine::minute(int minute, int last_minute, int stoppage) {
// Human teams use the places on their tactics board, also for the player's value.
int MatchEngine::pick_player(int team, int mode, int exclude, MinuteReport& report, int preset) {
mode &= 0x7F; // 0x80 = reuse the squad of the previous call, same team here
if (team >= 138 && team != kNoTeam) return 0xFFF; // clubs without squad: nobody, no draws
if (team >= runtime_dimensions.league_teams && team != kNoTeam) return 0xFFF; // clubs without squad: nobody, no draws
SquadRange range = squad_range(team);
if (range.count == 0) return 0xFFF;
RatingContext ctx{state.chance_rain, state.chance_temperature};
@@ -522,8 +522,8 @@ ForcedMatchEvent MatchEngine::event_impl(MatchGroup& g, int m, int s, int minute
// Small-squad teams (id >= 90) only half of the time; teams without squads never. The
// national team (0x165, squad nominated on the national team days) only while manager
// slot 0 holds it (CupDraw_FormatError_RuntimeField2 == 0x165: a Bundestrainer's match).
if (!(team < 90 || rand.range(0, 1) == 0)) return result;
if (!(team < 138 || team == kNoTeam)) return result;
if (!(team < runtime_dimensions.big_squad_teams || rand.range(0, 1) == 0)) return result;
if (!(team < runtime_dimensions.league_teams || team == kNoTeam)) return result;
if (team == kNoTeam && (state.manager_teams.empty() || state.manager_teams[0] != kNoTeam)) return result;
const int manager = state.manager_of(team); // FindManagerForClub, local_6c
const bool human = manager >= 0;
@@ -944,7 +944,7 @@ void MatchEngine::side(MatchGroup& g, int m, int& s, int minute, int& own_att, i
}
// Goalkeeper of the opponent: the player in squad slot 0 if the formation puts it in goal.
if (!reality_played && (opp_team < 168 || opp_team == kNoTeam)) {
if (!reality_played && (opp_team < runtime_dimensions.record_teams || opp_team == kNoTeam)) {
int x = 0, y = 0;
state.formation_position(opp_team, 0, x, y);
if (x == 0 && y == 4) keeper = state.squad_slots.at(squad_range(opp_team).first) & 0x0FFF;
@@ -979,7 +979,7 @@ void MatchEngine::side(MatchGroup& g, int m, int& s, int minute, int& own_att, i
deflected = game.range(0, 5) == 0;
}
if (kind == 0) {
if (team >= 168 && team != kNoTeam) {
if (team >= runtime_dimensions.record_teams && team != kNoTeam) {
// clubs without squad: the attack rating (TeamRating, profile 3), drawn
RatingContext drawn;
drawn.rand = &rand;
@@ -989,7 +989,7 @@ void MatchEngine::side(MatchGroup& g, int m, int& s, int minute, int& own_att, i
}
}
if (keeper == 0xFFF) {
if (opp_team >= 168 && opp_team != kNoTeam) {
if (opp_team >= runtime_dimensions.record_teams && opp_team != kNoTeam) {
// clubs without squad: the goalkeeping rating (profile 0), drawn
RatingContext drawn;
drawn.rand = &rand;
@@ -1196,7 +1196,7 @@ void MatchEngine::penalty_shootout(MatchGroup& g, int m, MinuteReport& report) {
const int side = order[k];
const int team = pair[side];
int player = 0xFFF;
if (team < 138 || team == kNoTeam) {
if (team < runtime_dimensions.league_teams || team == kNoTeam) {
// a player who has not taken a penalty yet (after 100 tries the list restarts)
int tries = 0;
bool fresh;
+9 -8
View File
@@ -46,7 +46,7 @@ int competition_class(int type) { return type >= 0 && type < 24 ? kCompetitionCl
// TeamLeague2: league (0-8) of a club id, 9 for clubs outside the leagues.
int league_of(int team) {
if (team > 0x164) return 0;
if (team > (kNoTeam - 1)) return 0;
int end = 0;
for (int l = 0; l < 9; l++) {
end += kLeagueSizes[l];
@@ -129,10 +129,10 @@ SportschauFixtureView sportschau_fixture_view(const GameState& state, const Matc
if (team >= 0 && size_t(team) * 2 + 1 < state.club_heap_78.size())
badge_word = uint16_t(state.club_heap_78[size_t(team) * 2] |
uint16_t(state.club_heap_78[size_t(team) * 2 + 1]) << 8);
if (team >= 0 && team < 0xa8) {
if (team >= 0 && team < runtime_dimensions.record_teams) {
requires_font_fit = true;
if (state.memory.has(::bmh::layout::ClubShortNameOffsets + uint32_t(team))) {
const uint8_t source = state.memory.u8(::bmh::layout::ClubShortNameOffsets + uint32_t(team));
const uint8_t source = state.club_short_offset(team);
const size_t offset = source >> 4;
const size_t length = (source & 0x0f) + 1;
if (offset <= full.size()) {
@@ -302,7 +302,7 @@ void update_club_table(GameState& g, int home, int away, int hg, int ag) {
auto add16 = [&](size_t o, int v) { wr16(g.club_table, o, uint16_t(rd16(g.club_table, o) + v)); };
// Only the first league and the regional leagues keep points in this table (the
// condition tests the home club only).
const bool league = home < kLeagueSizes[0] || (home >= 90 && home < 138);
const bool league = home < kLeagueSizes[0] || (home >= 90 && home < runtime_dimensions.league_teams);
const int win_points = kThreePoints[league_of(home)] ? 3 : 2;
if (league) {
add16(H + 0x20, hg);
@@ -404,7 +404,7 @@ void develop_players(GameState& g, const MatchGroup& grp, int m, GameRandom& gam
const int type = grp.desc.at(0);
for (int side = 0; side < 2; side++) {
const int team = grp.fixtures.at(m * 2 + side);
if (!(team < 168 || team == kNoTeam)) continue;
if (!(team < runtime_dimensions.record_teams || team == kNoTeam)) continue;
const uint8_t cls = (type == 0xb && team == kNoTeam) ? 3 : uint8_t(competition_class(type));
const int manager = g.manager_of(team);
const SquadRange range = squad_range(team);
@@ -586,7 +586,7 @@ bool league_screen_shown(const std::vector<uint8_t>& buttons, int param_1, int p
int table_position(const GameState& g, int team) {
if (team >= 138) return 2;
if (team >= runtime_dimensions.league_teams) return 2;
int league = league_of(team);
int rounds = league < int(g.league_rounds.size()) ? g.league_rounds[league] : 0;
if (rounds == 0) return -1;
@@ -667,8 +667,8 @@ void manager_match_record(GameState& g, const MatchGroup& grp, int m, int home_g
rating = std::clamp(int16_t(rating), int16_t(0), int16_t(200));
rate_manager(g, int(k), rating, 0);
}
if (opp < 0xa8) {
size_t at = k * 0x690 + size_t(opp) * 10 + (side == 1 ? 5 : 0);
if (opp < runtime_dimensions.record_teams) {
size_t at = k * (runtime_dimensions.record_teams * 10) + size_t(opp) * 10 + (side == 1 ? 5 : 0);
std::copy_backward(g.manager_results.begin() + at, g.manager_results.begin() + at + 4,
g.manager_results.begin() + at + 5);
g.manager_results.at(at) = uint8_t(own + (against << 4));
@@ -717,6 +717,7 @@ void advance_league_rounds(GameState& g, uint32_t competitions, WatcomRandom& ra
const int end = bit < 4 ? bit + 1 : 8;
for (int c = bit; c < end; c++) {
for (int league = kFirst[c]; league < kFirst[c] + kCount[c]; league++) {
if (runtime_dimensions.expanded && g.league_rounds.at(size_t(league)) >= 2 * (kLeagueSizes[league] - 1)) continue;
if (league == 0) {
for (size_t m = 0; m < g.manager_teams.size(); m++) {
advance_youth_teams(g, int(m), rand);
+7 -6
View File
@@ -35,9 +35,9 @@ constexpr uint8_t kCompetitionClass[24] = {0, 1, 2, 2, 2, 3, 3, 3, 3, 255, 0, 25
// Crowd interest per descriptor type (MatchdaySetupRuntimeField).
constexpr uint8_t kTypeInterest[24] = {5, 5, 10, 15, 12, 10, 5, 10, 5, 10, 5, 31, 10, 10, 10, 0, 0, 1, 0, 0, 0, 12, 0, 0};
// Number of clubs taking part in league play (CareerSession_DispatchLineup_RuntimeField).
constexpr int kLeagueClubCount = 0x8a;
const int& kLeagueClubCount = runtime_dimensions.league_teams;
// Squad slots checked by the driver (CareerRuntimeField).
constexpr size_t kSquadSlotCount = 0xb70;
const int& kSquadSlotCount = runtime_dimensions.pool_first;
// The attendance tables MatchdaySetup_Attendance_ExecutableField .. MatchdaySetupRuntimeField2 as one block, because the original
// indexes them with league classes 0-7 although they only have four entries: classes 4-7
@@ -76,7 +76,7 @@ void wr16(Bytes& b, size_t o, uint16_t v) { b.at(o) = uint8_t(v), b.at(o + 1) =
// TeamLeague2: league of a club, 0 for the special ids above 0x164, 9 outside the leagues.
int league_of(int team) {
if (team > 0x164) return 0;
if (team > (kNoTeam - 1)) return 0;
return team_league(team);
}
@@ -376,7 +376,7 @@ void indoor_tournament_draw(GameState& g, GameRandom& game, WatcomRandom& rand)
indoor_tournament_reset(g);
uint8_t attempts = 0;
const int guest = rand.range(0, 1);
if (guest != 0) mem.set16(kTeams, uint16_t(rand.range(90, 137)));
if (guest != 0) mem.set16(kTeams, uint16_t(rand.range(runtime_dimensions.domestic_teams, runtime_dimensions.league_teams - 1)));
int count = guest != 0;
int n = rand.range(5, 7);
uint8_t lo = 0, hi = uint8_t(kLeagueSizes[0]);
@@ -431,7 +431,7 @@ void indoor_tournament_draw(GameState& g, GameRandom& game, WatcomRandom& rand)
int sum = 0; // IndoorTournamentReset
for (uint32_t k = 0; k < 8; k++) {
const int t = mem.u16(kTeams + k * 2);
const int league = t > 0x164 ? 0 : team_league(t); // TeamLeague2
const int league = t > (kNoTeam - 1) ? 0 : team_league(t); // TeamLeague2
if (league < 2) sum += (0x26 - table_position(g, t)) - kLeagueSizes[0] * league;
else if (league < 5) sum += 1;
else sum += 0x19;
@@ -563,6 +563,7 @@ std::vector<MatchGroup> setup_matchday(GameState& g, uint32_t competitions, cons
for (int k = from; k < to; k++) {
// FixturesFromGenerateFixtures(k)
for (int league = kGroupLeague[k]; league < kGroupLeague[k] + kGroupLeagues[k]; league++) {
if (runtime_dimensions.expanded && g.league_rounds.at(size_t(league)) >= 2 * (kLeagueSizes[league] - 1)) continue;
turn_step = "setup: winter postponements";
winter_postponements(g, ctx.season_day, league, game, rand);
const int round = g.league_rounds.at(size_t(league));
@@ -886,7 +887,7 @@ bool select_live_match(GameState& g, int home, int away) {
// record +0x8ac / 16 + 40.
void man_marking(GameState& g, int own_manager, int own, int other_manager, int other, int chance, int rate,
WatcomRandom& rand) {
constexpr int kLeagueTeams = 138; // CareerSession_DispatchLineup_RuntimeField
const int kLeagueTeams = runtime_dimensions.league_teams; // CareerSession_DispatchLineup_RuntimeField
if (g.indoor || own >= kLeagueTeams || other >= kLeagueTeams || (own_manager < 0 && other_manager < 0)) return;
if (other_manager >= 0)
for (size_t s = 0; s < 24; s++) {
+10 -1
View File
@@ -20,6 +20,7 @@
#include <vector>
#include "formats/savestate.hpp"
#include "formats/executable_layout.hpp"
namespace bmh {
@@ -34,7 +35,15 @@ public:
explicit StaticMemory(const SaveState& save) {
for (const SaveBlock& b : save.blocks())
if (!b.heap && b.size != 0 && !blocks_.count(b.address))
blocks_[b.address].assign(save.stream().begin() + b.offset, save.stream().begin() + b.offset + b.size);
{
// Expanded tails live in typed GameState vectors. Keep guest
// memory at Original extents to avoid aliasing adjacent globals.
size_t size = b.size;
if (b.address == layout::ClubKitSelectors) size = std::min(size, size_t(419));
if (b.address == layout::ClubShortNameOffsets) size = std::min(size, size_t(168));
if (b.address == layout::ManagerMatchHistory) size = std::min(size, size_t(8400));
blocks_[b.address].assign(save.stream().begin() + b.offset, save.stream().begin() + b.offset + size);
}
}
// A global the savegame does not store (e.g. a work list the original rebuilds before
+10
View File
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "game/messages.hpp"
#include "game/schedule.hpp"
#include <algorithm>
#include <cstdio>
@@ -150,4 +151,13 @@ std::string format_number(const GameState& g, int32_t value, int flags) {
std::string format_amount(const GameState& g, int32_t value) { return format_number(g, value, 0x101); }
void install_message_texts(const LeImage& exe) {
kContractEndsSoonText = exe.cstring(kEnglishCompetitions ? ::bmh::layout::EnglishContractExpiryWarningText : ::bmh::layout::ContractExpiryWarningText);
kMastersQualificationText = kEnglishCompetitions ? "Masters entry confirmed. Your participation bonus has been credited." : exe.cstring(::bmh::layout::MastersQualificationText);
kMastersWinnerText = kEnglishCompetitions ? "Masters title won. Your prize money has been credited." : exe.cstring(::bmh::layout::MastersWinnerText);
kIndoorInvitationText = kEnglishCompetitions ? "Indoor event entry bonus credited for " : exe.cstring(::bmh::layout::IndoorInvitationText);
kChampionshipBonusText = kEnglishCompetitions ? "League title bonus credited." : exe.cstring(::bmh::layout::ChampionshipBonusText);
kFriendlyPayerPrefixText = kEnglishCompetitions ? "Your share: " : exe.cstring(::bmh::layout::NationalFriendlyPayerPrefixText);
}
} // namespace bmh
+6
View File
@@ -16,6 +16,7 @@
#include <string>
#include <vector>
#include "formats/le.hpp"
#include "game/state.hpp"
namespace bmh {
@@ -59,6 +60,11 @@ inline std::string kIndoorInvitationText;
inline std::string kChampionshipBonusText;
inline std::string kFriendlyPayerPrefixText;
// Installs the six texts above from the game image (the English game uses its own wording).
// Both career sessions call it at start; standalone engine tools (week_check, the season sims)
// must call it too, or these messages lose their text (#14: the indoor entry bonus mail).
void install_message_texts(const LeImage& exe);
// FormatNumber(buf, value, 0x101, ""): an amount of money as the messages show it: the
// value converted with CurrencyMultiplier / CurrencyDivisor, digits grouped by dots, then " EU".
std::string format_amount(const GameState& g, int32_t value);
+11 -11
View File
@@ -30,12 +30,12 @@ constexpr size_t kBoard = 0x840; // tactics board of a manager
constexpr size_t kBoardSlot = 0x58;
constexpr uint32_t kTransferList = ::bmh::layout::EditorList;
constexpr uint32_t kListEntry = 0x58;
constexpr int kPoolFirst = 0xb70; // CareerRuntimeField: the transfer list (40 slots + 4)
constexpr int kFreeAgents = 0xb9c; // CareerRuntimeField2: free agents (80 slots)
constexpr int kForeignAgents = 0xbec; // MonthRuntimeField: foreign free agents (20 slots)
constexpr int kPoolEnd = 0xc00; // LargeSquadClubCount
constexpr int kBigSquadClubs = 90; // TeamsWithSquads
constexpr int kLeagueClubs = 0x8a; // CareerSession_DispatchLineup_RuntimeField
const int& kPoolFirst = runtime_dimensions.pool_first; // CareerRuntimeField: the transfer list (40 slots + 4)
const int& kFreeAgents = runtime_dimensions.free_first; // CareerRuntimeField2: free agents (80 slots)
const int& kForeignAgents = runtime_dimensions.foreign_free_first; // MonthRuntimeField: foreign free agents (20 slots)
const int& kPoolEnd = runtime_dimensions.national_slots_first; // LargeSquadClubCount
const int& kBigSquadClubs = runtime_dimensions.big_squad_teams; // TeamsWithSquads
const int& kLeagueClubs = runtime_dimensions.league_teams; // CareerSession_DispatchLineup_RuntimeField
// MonthRuntimeField2: development steps by strength / 10; the ten bytes after it (PlayerCard_PlayerCardMarketValue_RuntimeField)
// are the extra value above 500 points.
@@ -162,8 +162,8 @@ bool in_pseudo_squad(const GameState& g, int slot) {
void list_club_player(GameState& g, int first, int last, WatcomRandom& rand, MinuteReport& report) {
const int8_t* wanted = first < kBigSquadClubs ? kWantedBig : kWantedSmall; // Attempt
for (;;) {
int16_t teams[138];
uint32_t keys[138];
std::vector<int16_t> teams(size_t(kLeagueClubs), 0);
std::vector<uint32_t> keys(size_t(kLeagueClubs), 0);
int n = 0; // local_14
g.list_toggle = g.list_toggle + 1 == 2 ? 0 : g.list_toggle + 1;
int best_line = 0; // local_1c, keeps its value between the clubs
@@ -207,10 +207,10 @@ void list_club_player(GameState& g, int first, int last, WatcomRandom& rand, Min
n++;
}
}
int pick = 0x8a; // sVar11
int pick = runtime_dimensions.league_teams; // sVar11
int slot = -1; // unaff_EDI: the slot tried last
if (n != 0) {
quicksort_by_key(teams, keys, n);
quicksort_by_key(teams.data(), keys.data(), n);
for (pick = 0; pick < n; pick++) {
const int team = teams[pick];
const SquadRange range = squad_range(team);
@@ -229,7 +229,7 @@ void list_club_player(GameState& g, int first, int last, WatcomRandom& rand, Min
}
// (when no club had a fitting player the slot tried last is listed all the same)
}
if (pick < 0x8a) {
if (pick < runtime_dimensions.league_teams) {
list_player(g, slot, rand, report);
return;
}
+1 -1
View File
@@ -19,7 +19,7 @@ constexpr size_t kBoard = 0x840; // one manager's tactics board (24 x 0
constexpr size_t kBoardSlot = 0x58;
constexpr uint32_t kDesktops = ::bmh::layout::Desktops; // desktop layouts, 0x360 per manager slot
constexpr size_t kDesktop = 0x360;
constexpr size_t kPoolSlots = 0xb70; // CareerRuntimeField: the clubs' squads end here
const int& kPoolSlots = runtime_dimensions.pool_first; // CareerRuntimeField: the clubs' squads end here
constexpr uint8_t kNominated[4] = {3, 5, 7, 5}; // NationalRuntimeField: keepers, defence, midfield, attack
// the manager's team (record +0x290) as the port caches it
+3 -3
View File
@@ -156,13 +156,13 @@ OtherGamesClubMetadata source_metadata(const GameState& game, int team) {
uint16_t(game.manager_records[kNationalOriginalClub + 1]) << 8));
manager_owned = original_club == team;
}
if (team >= 168 && !manager_owned) {
const size_t at = size_t(team - 168);
if (team >= runtime_dimensions.record_teams && !manager_owned) {
const size_t at = size_t(team - runtime_dimensions.record_teams);
if (at >= game.foreign_strength.size()) invalid("missing Source foreign-strength byte");
out.foreign_strength = game.foreign_strength[at];
return out;
}
if (team >= 168 && team != kNoTeam)
if (team >= runtime_dimensions.record_teams && team != kNoTeam)
invalid("manager-controlled foreign-club row needs live TeamRating W-generator context");
constexpr std::array<uint16_t, 5> kFlags{0x0f1, 0x0f2, 0x0f4, 0x0f8, 0x0ff};
for (size_t i = 0; i < kFlags.size(); ++i)
+2 -2
View File
@@ -16,9 +16,9 @@ constexpr size_t kRecordSize = 0xb0c;
constexpr size_t kAttempts = 0x8b6; // five player ids, 0xffff free
constexpr uint32_t kTransferList = ::bmh::layout::EditorList; // 44 rows of 0x58 bytes
constexpr uint32_t kListRow = 0x58;
constexpr size_t kPoolFirst = 0xb70; // CareerRuntimeField: squad slot of list row 0
const int& kPoolFirst = runtime_dimensions.pool_first; // CareerRuntimeField: squad slot of list row 0
constexpr uint32_t kOfferSlots = ::bmh::layout::OfferSlots; // OfferSlots: 4 words, -1 free
constexpr int kBigSquadClubs = 90; // TeamsWithSquads
const int& kBigSquadClubs = runtime_dimensions.big_squad_teams; // TeamsWithSquads
// Attempt: how many players of each position a club wants (MonthRuntimeField4 / MonthRuntimeField5)
constexpr int8_t kWantedBig[4] = {2, 6, 7, 5}, kWantedSmall[4] = {2, 4, 5, 4};
+1 -1
View File
@@ -21,7 +21,7 @@ constexpr size_t kBoardSlot = 0x58; // one slot of the board
// Static league tables of V2.24 (not part of the savegame):
// (European places per league, CareerSession_InstallLeagueSizes_RuntimeField, are kLeagueEurope of the loaded game; league 0 uses 4)
// (the relegation places per league, CareerSession_InstallLeagueSizes_RuntimeField2, are kLeagueRelegation of the loaded game)
constexpr int kLeagueTeams = 138; // CareerSession_DispatchLineup_RuntimeField: clubs in the league system
const int& kLeagueTeams = runtime_dimensions.league_teams; // CareerSession_DispatchLineup_RuntimeField: clubs in the league system
// Text of a pointer variable of the text table TextPointerTable.
} // namespace
+23
View File
@@ -0,0 +1,23 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "game/profile_runtime.hpp"
#include "formats/data_profile.hpp"
namespace bmh {
void install_runtime_profile(const DataProfile& profile) {
profile.validate();
RuntimeDimensions next;
next.league_teams=int(profile.counts.league_teams);
next.cup_teams=int(profile.counts.cup_teams);
next.big_squad_teams=int(profile.big_squad_teams);
next.record_teams=int(profile.counts.n42);
next.national_first=int(profile.national_first);
next.pool_first=int(profile.pool_first());
next.market_special_first=next.pool_first+40;
next.free_first=next.pool_first+44;
next.foreign_free_first=next.pool_first+124;
next.national_slots_first=int(profile.national_slots_first());
next.extra_slots_first=int(profile.extra_slots_first());
next.total_slots=int(profile.total_slots());
next.expanded=profile.extended();
runtime_dimensions=next;
}
}
+17
View File
@@ -0,0 +1,17 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
namespace bmh {
struct DataProfile;
// Explicitly distinct concepts: German clubs, league clubs and large rosters.
// One installation is active per process, like the existing fixture/rule tables.
struct RuntimeDimensions {
int domestic_teams=90, league_teams=138, cup_teams=30, big_squad_teams=90;
int record_teams=168;
int national_first=357, pool_first=2928, market_special_first=2968;
int free_first=2972, foreign_free_first=3052, national_slots_first=3072;
int extra_slots_first=3096, total_slots=3150;
bool expanded=false;
};
inline RuntimeDimensions runtime_dimensions{};
void install_runtime_profile(const DataProfile& profile);
}
+2 -2
View File
@@ -121,7 +121,7 @@ int human_correction(GameState& g, RatingContext& ctx, int manager, int rank, in
} // namespace
int team_rating(GameState& g, int team, const RatingProfile& profile, RatingContext& ctx, int* keeper) {
if (team >= 168 && team != kNoTeam) {
if (team >= runtime_dimensions.record_teams && team != kNoTeam) {
// Clubs without squad: per group a random value around the level of the club
// (ForeignClubStrength bits 5-7 -> RatingRuntimeField2), +2 if the group's strength bit is set
// (bit 3, 3, 2, 1 for goal, defence, midfield, attack: RatingRuntimeField3) and a style
@@ -130,7 +130,7 @@ int team_rating(GameState& g, int team, const RatingProfile& profile, RatingCont
static const uint8_t kStrongBit[4] = {3, 3, 2, 1};
static const int8_t kStyle[8] = {0, 6, 0, -6, 0, -6, 0, 6};
if (!ctx.rand) throw std::invalid_argument("team_rating: a team without squad needs the Watcom generator");
const uint8_t s = g.foreign_strength.at(size_t(team - 168));
const uint8_t s = g.foreign_strength.at(size_t(team - runtime_dimensions.record_teams));
int16_t total = 0;
for (int i = 0; i < 4; i++) {
const int level = kLevel[s >> 5];
+8 -1
View File
@@ -228,15 +228,22 @@ bool undo_reschedule(GameState& g, int manager, int day) {
if (std::none_of(moved.begin(), moved.end(), [&](const LeagueMatchRef& m) { return m.day == day; })) return false;
const int team = manager_team(g, manager);
// UndoReschedule(day, 1, team): every replay of the club on that day, whatever its league
int kept = 0; // local_18: the replays of other clubs that stay on the day
for (int e = 0; e < kPostponedEntries; e++) {
const uint32_t at = kPostponed + uint32_t(e) * 6;
if (g.memory.u16(at) != uint16_t(day)) continue;
const int league = g.memory.u8(at + 3), round = g.memory.u8(at + 2), m = g.memory.u8(at + 4);
const Fixture f = round_fixtures(league, round).at(size_t(m));
if (f.home != team && f.away != team) continue;
if (f.home != team && f.away != team) { ++kept; continue; }
g.results.at(result_at(league, round, m)) = kNotPlayed;
g.memory.set16(at, 0);
}
// with no replay left the day loses its replay bit 0x4000 again (calendar high byte & 0xbf),
// so it can be a target once more
if (kept == 0) {
const uint32_t high = kCalendar + uint32_t(day) * 2 + 1;
g.memory.set8(high, uint8_t(g.memory.u8(high) & 0xbf));
}
return true;
}
+2 -2
View File
@@ -15,8 +15,8 @@
// matchday the 0xCE turns into 0xCD (matchday_setup) and the match is played on the
// new day like a winter postponement.
// 4. A click on the new day of a moved match takes the move back (UndoReschedule(day, 1,
// team)): the entry is freed and the result byte is 0xCC again. The calendar keeps bit
// 0x4000, as in the original.
// team)): the entry is freed and the result byte is 0xCC again. When no replay of another
// club stays on that day, the day loses bit 0x4000 again and can be a target once more.
//
// Everything here works on the saved GameState only: no random numbers are drawn, so a
// rescheduled career stays deterministic.
+12 -5
View File
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "game/save.hpp"
#include "game/calendar.hpp"
#include <cstdio>
#include <cstring>
@@ -25,7 +26,7 @@ void put32(Bytes& d, size_t at, uint32_t x) {
for (int i = 0; i < 4 && at + size_t(i) < d.size(); i++) d[at + size_t(i)] = uint8_t(x >> (8 * i));
}
// DeskDate2(date, buffer, 0): "TT.MM.JJJJ" of a day counter (day 0 = 1 July 2026; a
// DeskDate2(date, buffer, 0): "TT.MM.JJJJ" of a day counter (day 0 = 1 July of the supplied edition; a
// four-year leap cycle that starts with the third year).
std::string date_text(uint32_t counter) {
static const int kDays[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
@@ -45,7 +46,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, calendar_epoch().year + years);
return buf;
}
@@ -58,7 +59,7 @@ Bytes save_stream(const GameState& live) {
const GameState& g = coach ? swapped : live;
const bool records = g.memory.has(::bmh::layout::ClubSeasonRecords) && g.memory.u32(::bmh::layout::ClubSeasonRecords) != 0;
Bytes stream;
for (const SaveBlock& b : save_layout(DbCounts{}, records)) {
for (const SaveBlock& b : save_layout(g.counts, records)) {
Bytes d(b.size, 0);
if (b.heap) {
switch (b.address) {
@@ -93,6 +94,12 @@ Bytes save_stream(const GameState& live) {
// the blocks GameState keeps in typed fields
switch (b.address) {
case ::bmh::layout::ManagerRecords: put(d, g.manager_records); break;
case ::bmh::layout::ClubKitSelectors:
if (g.counts.league_teams == 164) put(d, g.club_kits);
break;
case ::bmh::layout::ClubShortNameOffsets:
if (g.counts.league_teams == 164) put(d, g.club_short_offsets);
break;
case ::bmh::layout::ManagerMatchHistory: put(d, g.manager_results); break;
case ::bmh::layout::ManagerRatings: put(d, g.manager_ratings); break;
case ::bmh::layout::LeagueResults: put(d, g.results); break;
@@ -139,7 +146,7 @@ Bytes save_header(const GameState& g) {
for (int m = 0; m < managers && m < 4; m++) {
const size_t rec = size_t(m) * 0xb0c;
const int team = int16_t(g.manager_records.at(rec + 0x290) | g.manager_records.at(rec + 0x291) << 8);
const bool national = team == 0x165;
const bool national = team == kNoTeam;
const size_t at = size_t(m) * 0x28;
list[at] = national ? 0x1e : g.manager_records.at(rec + 0x210); // (0x1e: high byte of the loop word)
list[at + 1] = national ? 1 : 0;
@@ -155,7 +162,7 @@ Savegame make_savegame(const GameState& g, WatcomRandom& rand) {
Savegame s;
s.plain_header = save_header(g);
s.id1 = 0;
s.version = "V2.24";
s.version = g.counts.league_teams == 164 ? "O1.1" : "V2.24";
const uint32_t hi = uint32_t(rand.range(0, 0x8fff)), lo = uint32_t(rand.range(0, 0x8fff));
s.id2 = lo + hi * 0x10000 + 1;
s.key = uint8_t(rand.range(0, 0xff) + 'n');
+5 -4
View File
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "game/schedule.hpp"
#include "game/profile_runtime.hpp"
#include "formats/executable_layout.hpp"
#include "formats/le.hpp"
@@ -123,16 +124,16 @@ std::vector<Fixture> generate_fixtures(int teams, int matchday, int rounds, int
return out;
}
int league_table_teams(int league) { return league < 5 ? kLeagueSizes[0] : kLeagueSizes[5]; }
int league_table_teams(int league) { return runtime_dimensions.expanded ? kLeagueSizes[league] : (league < 5 ? kLeagueSizes[0] : kLeagueSizes[5]); }
void set_league_sizes(const uint8_t (&sizes)[kLeagueCount]) {
int total = 0;
for (int l = 0; l < kLeagueCount; l++) total += sizes[l];
const auto has_table = [](int teams) { return teams == 20 || teams == 18 || teams == 16 || teams == 12; };
if (total != 138 || !has_table(sizes[0]) || !has_table(sizes[5]))
throw std::invalid_argument("league sizes do not describe 138 league teams with fixture tables");
if (total != runtime_dimensions.league_teams || !has_table(sizes[0]) || !has_table(sizes[5]))
throw std::invalid_argument("league sizes do not match the installed profile and fixture tables");
for (int l = 0; l < kLeagueCount; l++)
if (sizes[l] < 2 || sizes[l] > (l < 5 ? sizes[0] : sizes[5]))
if (sizes[l] < 2 || (!runtime_dimensions.expanded && sizes[l] > (l < 5 ? sizes[0] : sizes[5])) || (runtime_dimensions.expanded && !has_table(sizes[l])))
throw std::invalid_argument("a league is larger than its fixture table");
for (int l = 0; l < kLeagueCount; l++) kLeagueSizes[l] = sizes[l];
}
+58 -28
View File
@@ -28,7 +28,7 @@ namespace {
constexpr uint32_t kTransferList = ::bmh::layout::EditorList; // 44 entries of 0x58 bytes
constexpr uint32_t kListEntry = 0x58;
constexpr size_t kPoolSlots = 0xb70; // CareerRuntimeField
const int& kPoolSlots = runtime_dimensions.pool_first; // CareerRuntimeField
constexpr uint32_t kOffers = ::bmh::layout::OfferSlots; // OfferSlots: 4 offers, -1 = free
constexpr size_t kBoard = 0x840; // tactics board of a manager
constexpr size_t kBoardSlot = 0x58;
@@ -173,7 +173,7 @@ void club_balance(GameState& g, int team, WatcomRandom& rand) {
namespace {
// TeamLeague2: the league of a club; ids above 0x164 (national teams) count as league 0
int club_league(int team) { return team > 0x164 ? 0 : team_league(team); }
int club_league(int team) { return team > (kNoTeam - 1) ? 0 : team_league(team); }
// The European entrants (Career_CompetitionPointersEnglish_ExecutableField25 UEFA Cup, Career_CompetitionPointersEnglish_RuntimeField14 Champions League,
// Career_CompetitionPointersEnglish_ExecutableField19 Cup Winners' Cup) and their counts (Career_EuropeanClub_ExecutableField / Career_EuropeanClub_ExecutableField2 / Career_EuropeanClub_ExecutableField3).
@@ -279,9 +279,9 @@ void observe_initial_international_groups(GameState& g, WatcomRandom& rand, int
for(int position:{fixture.home,fixture.away}) {
const int team=mem.u16(teams+uint32_t(position)*2);
const bool manager_national=mem.has(::bmh::layout::CupDraw_FormatError_RuntimeField2)&&mem.has(::bmh::layout::CupDraw_FormatError_RuntimeField3)&&
mem.u16(::bmh::layout::CupDraw_FormatError_RuntimeField2)==0x165&&mem.u16(::bmh::layout::CupDraw_FormatError_RuntimeField3)==team;
mem.u16(::bmh::layout::CupDraw_FormatError_RuntimeField2)==kNoTeam&&mem.u16(::bmh::layout::CupDraw_FormatError_RuntimeField3)==team;
const bool human_owned=g.manager_of(team)>=0||manager_national;
if(team<168||team==kNoTeam||!human_owned)continue;
if(team<runtime_dimensions.record_teams||team==kNoTeam||!human_owned)continue;
SeasonCupDrawEvent::GroupAverageSnapshot snapshot;
snapshot.runtime_id=uint16_t(team);
snapshot.values={team_average(g,team,0x0f1,&rand).value,
@@ -320,7 +320,7 @@ void european_setup(GameState& g, GameRandom& game, WatcomRandom& rand, const Se
constexpr uint32_t kField0 = ::bmh::layout::Field0;
if (!mem.has(kField0)) mem.add_block(kField0, 0x30);
const int s = g.season % 4;
const int base = 0xbd + 0x8a + 0x1e; // ClubPlayerDetail_ClubPlayerDetailFromGame_RuntimeField3 + CareerSession_DispatchLineup_RuntimeField + CareerSession_InstallLeagueSizes_RuntimeField6
const int base = 0xbd + runtime_dimensions.league_teams + 0x1e; // ClubPlayerDetail_ClubPlayerDetailFromGame_RuntimeField3 + CareerSession_DispatchLineup_RuntimeField + CareerSession_InstallLeagueSizes_RuntimeField6
int n = 1;
std::vector<uint16_t> last;
if (s % 2 == 0) {
@@ -390,7 +390,7 @@ void european_setup(GameState& g, GameRandom& game, WatcomRandom& rand, const Se
void european_fields(GameState& g, GameRandom& game, WatcomRandom& rand) {
StaticMemory& mem = g.memory;
Entrants en{mem};
const int pool = 0x8a + 0x1e; // CareerSession_DispatchLineup_RuntimeField + CareerSession_InstallLeagueSizes_RuntimeField6: the first foreign club
const int pool = runtime_dimensions.league_teams + 0x1e; // CareerSession_DispatchLineup_RuntimeField + CareerSession_InstallLeagueSizes_RuntimeField6: the first foreign club
auto pick = [&](int from) {
int t;
do t = rand.range(from, from + 6); while (en.find(t) != 0);
@@ -759,7 +759,7 @@ void season_accounts(GameState& g, int m, GameRandom& game, WatcomRandom& rand,
// swaps twice for them (no change), once otherwise.
void change_places(GameState& g, int a, int b) {
StaticMemory& mem = g.memory;
if (a >= 0x8a + 0x1e || b >= 0x8a + 0x1e) return;
if (a >= runtime_dimensions.league_teams + 0x1e || b >= runtime_dimensions.league_teams + 0x1e) return;
auto swap_bytes = [](std::vector<uint8_t>& v, size_t x, size_t y, size_t n) {
for (size_t i = 0; i < n; i++)
if (x + i < v.size() && y + i < v.size()) std::swap(v[x + i], v[y + i]);
@@ -776,7 +776,7 @@ void change_places(GameState& g, int a, int b) {
else if (v == uint16_t(b)) mem.set16(at + uint32_t(i) * 2, uint16_t(a));
}
};
const bool league_clubs = a < 0x8a && b < 0x8a;
const bool league_clubs = a < runtime_dimensions.league_teams && b < runtime_dimensions.league_teams;
if (league_clubs)
for (uint32_t k = 0; k < 200; k++) { // loans: seller and buyer
const uint32_t e = mem.u32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + k * 4);
@@ -786,21 +786,28 @@ void change_places(GameState& g, int a, int b) {
buyer = buyer == a ? b : buyer == b ? a : buyer;
mem.set32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + k * 4, (e & 0xfff) | uint32_t(seller) << 12 | uint32_t(buyer) << 22);
}
if (!g.club_table.empty() && a < 0xa8 && b < 0xa8) swap_bytes(g.club_table, size_t(a) * 0x4a, size_t(b) * 0x4a, 0x4a);
if (!g.club_table.empty() && a < runtime_dimensions.record_teams && b < runtime_dimensions.record_teams) swap_bytes(g.club_table, size_t(a) * 0x4a, size_t(b) * 0x4a, 0x4a);
std::swap(g.club_ids.at(size_t(a)), g.club_ids.at(size_t(b)));
swap_bytes(g.club_heap_bc, size_t(a) * 2, size_t(b) * 2, 2);
std::swap(g.team_morale.at(size_t(a)), g.team_morale.at(size_t(b)));
swap_mem8(::bmh::layout::ClubShortNameOffsets);
swap_mem8(::bmh::layout::ClubKitSelectors);
if (runtime_dimensions.expanded) {
std::swap(g.club_short_offsets.at(size_t(a)), g.club_short_offsets.at(size_t(b)));
std::swap(g.club_kits.at(size_t(a)), g.club_kits.at(size_t(b)));
} else {
swap_mem8(::bmh::layout::ClubShortNameOffsets);
swap_mem8(::bmh::layout::ClubKitSelectors);
}
swap_bytes(g.club_heap_78, size_t(a) * 2, size_t(b) * 2, 2);
std::swap(g.team_flags.at(size_t(a)), g.team_flags.at(size_t(b)));
if (league_clubs) {
swap_bytes(g.club_heap_b8, size_t(a) * 2, size_t(b) * 2, 2);
if (runtime_dimensions.expanded) std::swap(g.club_heap_b8.at(size_t(a)), g.club_heap_b8.at(size_t(b)));
else swap_bytes(g.club_heap_b8, size_t(a) * 2, size_t(b) * 2, 2);
swap_bytes(g.position_history, size_t(a) * 0x1a, size_t(b) * 0x1a, 0x1a);
const SquadRange ra = squad_range(a), rb = squad_range(b);
for (size_t i = 0; i < ra.count; i++) std::swap(g.squad_slots.at(ra.first + i), g.squad_slots.at(rb.first + i));
}
swap_bytes(g.club_heap_b8, size_t(a) * 2, size_t(b) * 2, 2);
if (runtime_dimensions.expanded) std::swap(g.club_heap_b8.at(size_t(a)), g.club_heap_b8.at(size_t(b)));
else swap_bytes(g.club_heap_b8, size_t(a) * 2, size_t(b) * 2, 2);
replace(::bmh::layout::Titles, 0x1c2); // title holders
replace(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField28, 2);
if (!mem.has(::bmh::layout::CareerSession_FormatError_RuntimeField6) || mem.u8(::bmh::layout::CareerSession_FormatError_RuntimeField6) == 0) {
@@ -830,7 +837,7 @@ void change_places(GameState& g, int a, int b) {
const uint16_t w = v == uint16_t(a) ? uint16_t(b) : v == uint16_t(b) ? uint16_t(a) : v;
g.manager_records.at(at) = uint8_t(w), g.manager_records.at(at + 1) = uint8_t(w >> 8);
}
swap_bytes(g.manager_results, size_t(a) * 10 + m * 0x690, size_t(b) * 10 + m * 0x690, 10);
swap_bytes(g.manager_results, size_t(a) * 10 + m * (runtime_dimensions.record_teams * 10), size_t(b) * 10 + m * (runtime_dimensions.record_teams * 10), 10);
}
}
@@ -1080,7 +1087,7 @@ bool release_player(GameState& g, int slot, GameRandom& game, WatcomRandom& rand
}
const int team = slot_team(slot);
const bool foreign = nationality(g, player) != 0;
const int start = foreign ? 0xbec : 0xb9c, count = foreign ? 0x14 : 0x50; // FirstFreeSlotSquad
const int start = foreign ? runtime_dimensions.foreign_free_first : runtime_dimensions.free_first, count = foreign ? 0x14 : 0x50; // FirstFreeSlotSquad
int free = -1;
for (int s = start; s < start + count && free < 0; s++)
if (g.squad_slots.at(size_t(s)) == 0x0FFF) free = s;
@@ -1104,8 +1111,6 @@ bool release_player(GameState& g, int slot, GameRandom& game, WatcomRandom& rand
return true;
}
namespace {
// CareerSeasonSetup3: the players' new season. Records and boards of the managers restart
// (with new advertising offers, TransferListCountdown2); then every squad and pool slot: players
// out for their career recover now and then with a human club's good doctor, else leave;
@@ -1169,10 +1174,16 @@ void season_players(GameState& g, GameRandom& game, WatcomRandom& rand, MinuteRe
uint8_t count = 0xff; // local_20
int8_t owner = -1; // local_24: the club's human manager
size_t board_first = 0; // local_3c
for (int s = 0; s < 0xc00 && !report.unsupported; s++) {
std::vector<bool> processed(g.players.size(), false);
for (int s = 0; s < runtime_dimensions.national_slots_first && !report.unsupported; s++) {
for (;;) {
const int player = g.squad_slots.at(size_t(s)) & 0xFFF;
if (player == 0xFFF) break;
// OpenBMH deviates from the original: age/retire each player
// once, even when a temporary offer row references his club
// slot or regeneration moves him to a later free-agent slot.
if (processed.at(size_t(player))) break;
processed.at(size_t(player)) = true;
const int team = slot_team(s);
if (team != int(last_team)) { // (-1 for the pool never equals 0xFFFF)
count = 0xff;
@@ -1182,7 +1193,7 @@ void season_players(GameState& g, GameRandom& game, WatcomRandom& rand, MinuteRe
}
Player& p = g.players.at(size_t(player));
bool leaves = false;
if (s < 0xb70 && (p.w35c >> 27) == 0x1f) {
if (s < runtime_dimensions.pool_first && (p.w35c >> 27) == 0x1f) {
// out for his career
bool gone = true;
if (owner != -1) {
@@ -1234,7 +1245,9 @@ void season_players(GameState& g, GameRandom& game, WatcomRandom& rand, MinuteRe
// a year older
p.w368 &= 0xf8003fffu;
int age = int16_t(((p.w364 >> 21) & 0x1f) + 1);
if (s < 0xb70 && rand.range(0x10, 0x16) < age && owner == -1) {
// OpenBMH deviates from the original: includes transfer-market
// players in retirement so the five-bit age cannot wrap to 16.
if (rand.range(0x10, 0x16) < age && owner == -1) {
if (count != 0xff) count = uint8_t(squad_count(g, team, 2) + loans[team]);
if (count > 0xd) {
count--;
@@ -1252,16 +1265,22 @@ void season_players(GameState& g, GameRandom& game, WatcomRandom& rand, MinuteRe
if (std::getenv("BMH_TRACE"))
std::printf(" [release slot %d player %d team %d age %u count %u]\n", s, player, team, (p.w364 >> 21) & 0x1f, count);
if (!release_player(g, s, game, rand, report)) return;
// Club releases compact their squad in remove_from_seller. Pool
// releases have no club: retire this source entry explicitly after
// the regenerated player has been placed in the free-agent pool.
if (team < 0) g.squad_slots.at(size_t(s)) = 0x0fff;
}
}
g.lineups_frozen = false;
}
for (size_t l = 0; l < g.league_rounds.size() && l < 9; l++) g.league_rounds[l] = 0;
fill8(::bmh::layout::DeskRecords_Teams_RuntimeField, 0x114, 0);
for (size_t i = 0; i < size_t(0x8a) * 0x1a && i < g.position_history.size(); i++) g.position_history[i] = 0;
fill8(::bmh::layout::DeskRecords_Teams_RuntimeField, uint32_t(g.counts.league_teams * 2), 0);
for (size_t i = 0; i < size_t(runtime_dimensions.league_teams) * 0x1a && i < g.position_history.size(); i++) g.position_history[i] = 0;
std::fill(g.results.begin(), g.results.end(), uint8_t(0xcc));
}
namespace {
// The end of the CareerSession_RuntimeError_RuntimeField4 branch of DailyInterest: histories beyond 50 seasons shift
// (SeasonEndSteps), the managers' season record starts (ManagerOf(m, 0, -2)), the
// limited game length counts down (CareerDuration), the days pass (DayStepRest) up to the
@@ -1637,25 +1656,36 @@ SeasonTransitionOutcome season_transition(GameState& g, GameRandom& game, Watcom
namespace bmh {
void initialize_european_qualification_seed(GameState& g) {
constexpr uint32_t entry = layout::CupTable + 14 * 0x28;
if (g.memory.u16(entry + 0x22) == 0 && g.memory.u16(entry + 0x24) == 0) {
// OpenBMH deviates from the original: initializes the empty EM qualifier
// seeds with national teams, preventing club zero from entering the EM.
g.memory.set16(entry + 0x22, kNoTeam);
g.memory.set16(entry + 0x24, (kNoTeam + 1));
}
}
bool career_season_setup(GameState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report,
const std::function<void(const char*)>& pause,
const SeasonCupDrawHook& cup_draw) {
StaticMemory& mem = g.memory;
g.team_morale.at(0x165) |= 0x80;
for (int team = 0; team < 0x8a; team++) {
g.team_morale.at(kNoTeam) |= 0x80;
for (int team = 0; team < runtime_dimensions.league_teams; team++) {
club_balance(g, team, rand);
auto_lineup(g, team, g.manager_of(team) >= 0 ? 0xe4 : 100); // (byte 100 - 0x80 for humans)
}
// the title holders of the cup entries (+0x22): none yet, the placeholder clubs
const uint16_t first_small = 90; // TeamsWithSquads
const uint16_t foreign = 189 + 138 + 30; // ClubPlayerDetail_ClubPlayerDetailFromGame_RuntimeField3 + CareerSession_DispatchLineup_RuntimeField + CareerSession_InstallLeagueSizes_RuntimeField6 (0x165)
const uint16_t first_small = uint16_t(league_first_team(5)); // TeamsWithSquads
const uint16_t foreign = 189 + runtime_dimensions.league_teams + 30; // ClubPlayerDetail_ClubPlayerDetailFromGame_RuntimeField3 + CareerSession_DispatchLineup_RuntimeField + CareerSession_InstallLeagueSizes_RuntimeField6 (0x165)
mem.set16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField2, foreign);
mem.set16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField6, uint16_t(first_small + 7));
mem.set16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField, 7);
if (kEnglishCompetitions) mem.set16(::bmh::layout::CupTable + 28 * 0x28 + 0x22, 7); // (EN: the FA Cup proper, SeasonRuntimeField8)
mem.set16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField5, uint16_t(first_small + 0x1f));
mem.set16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField4, uint16_t(first_small + 0x13));
mem.set16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField5, uint16_t(league_first_team(7) + 7));
mem.set16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField4, uint16_t(league_first_team(6) + 7));
mem.set16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField3, uint16_t(foreign + 1));
initialize_european_qualification_seed(g);
mem.set16(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField28, 0);
mem.set16(::bmh::layout::Cup_AdvanceCup_RuntimeField6, 0);
mem.set16(::bmh::layout::Cup_AdvanceCup_RuntimeField5, 7);
+8
View File
@@ -187,6 +187,14 @@ void cup_group_overview_effects(GameState& g, int group_index);
// LeagueName: the name of a league below 5 (with its letter, e.g. for the third divisions).
std::string league_name(const GameState& g, int league);
// New careers: fill the original uninitialized EM qualification placeholders;
// preserve any nonzero seeds supplied by the installation.
void initialize_european_qualification_seed(GameState& g);
// Season boundary: reset manager boards, age/retire players and clear seasonal
// histories. Kept separate from cup draws, accounts and calendar advancement.
void season_players(GameState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report);
// MonthChange(absolute squad slot): the player leaves his club for the free agents with new
// values (W and game draws) and an age W(4, 15); his club closes the gap (ReleasePlayer,
// with a human club its tactics board as well). False if the source ownership/state
+2 -2
View File
@@ -25,7 +25,7 @@ std::optional<MatchdayIntroView> matchday_intro_view(const GameState& state,
if (league >= 9) throw FormatError("matchday intro: invalid Source league");
// LeagueName with TeamStatistics_SourceLeagueName_RuntimeField=1 includes the secondary-league prefix.
name = league < 5 ? league_name(state, int(league)) :
message_text(state, ::bmh::layout::SportschauAwards_MatchdayIntroView_TextPointer) + state.club_name(0x165 + int(league) - 4);
message_text(state, ::bmh::layout::SportschauAwards_MatchdayIntroView_TextPointer) + state.club_name(kNoTeam + int(league) - 4);
} else {
if (type > 14) throw FormatError("matchday intro: invalid Source competition type");
name = message_text(state, ::bmh::layout::DeskState_FormatError_ExecutableField3 + uint32_t(type) * 4);
@@ -43,7 +43,7 @@ std::string sportschau_competition_title(const GameState& state, const MatchGrou
if (id > 20) index = state.memory.u8(id + 0x18) + 9;
else if (index >= 9) index = std::min(index + 12, 19);
if (index < 5) return league_name(state, index);
if (index < 9) return state.club_name(0x165 + index - 4);
if (index < 9) return state.club_name(kNoTeam + index - 4);
return message_text(state, ::bmh::layout::CupDraw_FormatError_ExecutableField6 + uint32_t(index - 9) * 4);
}
+15 -6
View File
@@ -11,9 +11,9 @@ namespace bmh {
namespace {
// Squad table layout constants of V2.24 (TeamsWithSquads, LargeSquadClubCount, NoTeamSquadStart).
constexpr int kBigSquadTeams = 90;
constexpr size_t kNoTeamSquadStart = 3072;
constexpr int kTeamsWithSquads = 168;
const int& kBigSquadTeams = runtime_dimensions.big_squad_teams;
const int& kNoTeamSquadStart = runtime_dimensions.national_slots_first;
const int& kTeamsWithSquads = runtime_dimensions.record_teams;
// C-style signed division by 8 as compiled by Watcom (rounds toward zero).
int div8(int x) { return x / 8; }
@@ -21,7 +21,7 @@ int div8(int x) { return x / 8; }
} // namespace
GameState GameState::from_save(const SaveState& save, const DbCounts& c) {
GameState g;
GameState g; g.counts=c;
const SaveBlock& squads = save.block(::bmh::layout::SquadSlots);
for (size_t i = 0; i + 1 < squads.size; i += 2)
g.squad_slots.push_back(uint16_t(save.data(::bmh::layout::SquadSlots)[i] | save.data(::bmh::layout::SquadSlots)[i + 1] << 8));
@@ -90,6 +90,8 @@ GameState GameState::from_save(const SaveState& save, const DbCounts& c) {
auto bytes = [&](uint32_t address) {
return std::vector<uint8_t>(save.data(address), save.data(address) + save.block(address).size);
};
g.club_kits = bytes(layout::ClubKitSelectors);
g.club_short_offsets = bytes(layout::ClubShortNameOffsets);
g.manager_results = bytes(::bmh::layout::ManagerMatchHistory);
g.manager_ratings = bytes(::bmh::layout::ManagerRatings);
g.position_history = bytes(::bmh::layout::LeagueRankHistory);
@@ -113,6 +115,13 @@ GameState GameState::from_save(const SaveState& save, const DbCounts& c) {
return g;
}
uint8_t GameState::club_kit(int team) const {
return counts.league_teams == 164 ? club_kits.at(size_t(team)) : memory.u8(layout::ClubKitSelectors + uint32_t(team));
}
uint8_t GameState::club_short_offset(int team) const {
return counts.league_teams == 164 ? club_short_offsets.at(size_t(team)) : memory.u8(layout::ClubShortNameOffsets + uint32_t(team));
}
int GameState::manager_of(int team) const {
for (size_t m = 0; m < manager_teams.size(); m++)
if (manager_teams[m] == team) return int(m);
@@ -156,9 +165,9 @@ void GameState::formation_position(int team, int slot, int& x, int& y) const {
}
SquadRange squad_range(int team) {
if (team == kNoTeam) return {kNoTeamSquadStart, 24};
if (team == kNoTeam) return {size_t(kNoTeamSquadStart), 24};
if (team < kBigSquadTeams) return {size_t(team) * 24, 24};
if (team < 138) return {size_t(team) * 16 + kBigSquadTeams * 8, 16};
if (team < runtime_dimensions.league_teams) return {size_t(team) * 16 + kBigSquadTeams * 8, 16};
return {0, 0};
}
+6 -1
View File
@@ -16,6 +16,7 @@
#include "formats/savestate.hpp"
#include "formats/textd.hpp"
#include "game/memory.hpp"
#include "game/profile_runtime.hpp"
#include "game/random.hpp"
#include "game/reality_motion.hpp"
@@ -26,7 +27,7 @@ struct TransferDecisionEvent;
struct HumanBuyerSaleHooks;
// Special team id used by the original for "no club" / the player pool (0x165).
constexpr int kNoTeam = 0x165;
inline const int& kNoTeam = runtime_dimensions.national_first;
// Squad slot values (u16 in table *SquadSlots):
// bits 0-11 player id, 0xFFF = empty slot
@@ -36,6 +37,10 @@ constexpr uint16_t kEmptySlot = 0x0FFF;
constexpr uint16_t kSlotInLineup = 0x8000;
struct GameState {
DbCounts counts{};
std::vector<uint8_t> club_kits, club_short_offsets;
uint8_t club_kit(int team) const;
uint8_t club_short_offset(int team) const;
std::vector<uint16_t> squad_slots; // *SquadSlots, all squads back to back (see squad_range)
std::vector<Player> players; // *PlayerConditionTechniqueForm / *PlayerSkillWords / *PlayerIdentityWords, names not filled
std::vector<uint8_t> team_morale; // *TeamMorale, per team: bits 0-5 morale / 2, bits 6-7 flags
+2 -2
View File
@@ -70,13 +70,13 @@ TopScorersProjection top_scorers_from_game(const GameState& g, int manager_slot,
invalid("manager has no supported domestic league");
// TeamLeague2 deliberately maps team IDs above 0x164 (including the
// national team 0x165) to league zero; ordinary cup-only teams map to 9.
const int league = manager_team > 0x164 ? 0 : team_league(manager_team);
const int league = manager_team > (kNoTeam - 1) ? 0 : team_league(manager_team);
if (league < 0 || league >= kLeagueCount)
invalid("manager team is outside Source's nine domestic leagues");
const int first_team = league_first_team(league);
const int team_count = kLeagueSizes[league];
if (first_team < 0 || first_team + team_count > 138 ||
if (first_team < 0 || first_team + team_count > runtime_dimensions.league_teams ||
g.club_ids.size() < size_t(first_team + team_count) || g.club_names.empty())
invalid("incomplete domestic club table");
+2 -3
View File
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "game/week.hpp"
#include "game/calendar.hpp"
#include "game/matchday.hpp"
#include "game/lineup.hpp"
@@ -93,9 +94,7 @@ int attribute(Player& p, int area, bool write, int delta, int max) {
} // namespace
int weekday_code(uint32_t date) {
int c = int(date % 7) + 2;
if (c > 6) c = int(date % 7) - 5;
return c;
return int((date % 7 + uint32_t(calendar_epoch().weekday)) % 7);
}
void familiarity_decay(GameState& g, GameRandom& game, WatcomRandom& rand) {
+13 -12
View File
@@ -32,8 +32,8 @@ constexpr size_t kBoard = 0x840; // tactics board of a manager
constexpr size_t kBoardSlot = 0x58;
constexpr uint32_t kTransferList = ::bmh::layout::EditorList; // 44 entries of 0x58 bytes, one per pool slot
constexpr uint32_t kListEntry = 0x58;
constexpr size_t kPoolSlots = 0xb70; // CareerRuntimeField: first squad slot of the transfer pool
constexpr int kLeagueClubs = 0x8a; // CareerSession_DispatchLineup_RuntimeField
const int& kPoolSlots = runtime_dimensions.pool_first; // CareerRuntimeField: first squad slot of the transfer pool
const int& kLeagueClubs = runtime_dimensions.league_teams; // CareerSession_DispatchLineup_RuntimeField
constexpr int kBigSquadClubs = 90; // TeamsWithSquads
// Offers and incidents (Bool): 1 in WeeklyRuntimeField[kind] is only possible while the
@@ -125,7 +125,7 @@ bool source_pending_owner_valid(const GameState& g,const SourcePendingOwner& own
int((word>>10)&0x0fff)==int(g.squad_slots[slot]&0x0fff);
}
int league_of(int team) { return team > 0x164 ? 0 : team_league(team); } // TeamLeague2
int league_of(int team) { return team > (kNoTeam - 1) ? 0 : team_league(team); } // TeamLeague2
} // namespace
@@ -154,8 +154,9 @@ int squad_count(const GameState& g, int team, int flags) {
// SlotTeam: club of an absolute squad slot (-1 for the pool).
int slot_team(int slot) {
if (slot < kBigSquadClubs * 24) return slot / 24;
if (slot < int(kPoolSlots)) return (slot - kBigSquadClubs * 24) / 16 + kBigSquadClubs;
const int large=runtime_dimensions.big_squad_teams;
if (slot < large * 24) return slot / 24;
if (slot < int(kPoolSlots)) return (slot - large * 24) / 16 + large;
return -1;
}
@@ -605,7 +606,7 @@ void transfer_bid(GameState& g, int slot, uint32_t list, bool high, int months,
const int r = rand.range(int16_t(need) + 3, int16_t(need) + 0xd);
if (int16_t(diff) < r) score += int(int16_t(need + 0xe - diff)) * 16 + 100;
else score -= int16_t(diff) * 8;
const int8_t* wanted = team < kBigSquadClubs ? kWantedBig : kWantedSmall;
const int8_t* wanted = team < runtime_dimensions.big_squad_teams ? kWantedBig : kWantedSmall;
int16_t d = int16_t(wanted[position] - int8_t(count[position]));
if (d < 0) {
score += int(d) << 8;
@@ -958,7 +959,7 @@ static bool remove_from_seller_impl(GameState& g, int seller, int player, Minute
bool native_takeover) {
player &= 0xFFF;
if (seller == 0xFFF || seller == 0xFFFF) {
for (size_t s = kPoolSlots; s < 3072; s++) // CareerRuntimeField .. LargeSquadClubCount
for (size_t s = kPoolSlots; s < runtime_dimensions.national_slots_first; s++) // CareerRuntimeField .. LargeSquadClubCount
if ((g.squad_slots[s] & 0xFFF) == player) g.squad_slots[s] = 0xFFF;
return true;
}
@@ -969,7 +970,7 @@ static bool remove_from_seller_impl(GameState& g, int seller, int player, Minute
report.fail("transfer: the player is not in the seller's squad (internal error 0x21)");
return false;
}
for (size_t s = kPoolSlots; s < 2972; s++) // CareerRuntimeField .. CareerRuntimeField2
for (size_t s = kPoolSlots; s < runtime_dimensions.free_first; s++) // CareerRuntimeField .. CareerRuntimeField2
if ((g.squad_slots[s] & 0xFFF) == player) g.squad_slots[s] = 0xFFF;
for (size_t s = at; s + 1 < range.first + range.count; s++) g.squad_slots[s] = g.squad_slots[s + 1];
g.squad_slots[range.first + range.count - 1] = 0xFFF;
@@ -2150,7 +2151,7 @@ HumanBuyerSaleResult settle_human_buyer_sale(GameState& g, const HumanBuyerSaleR
if (free_agent) {
// ReleasePlayer's canonical 0FFF seller scans the entire free-player pool,
// not a fictitious seller squad. FFFF is not an alias for this seller.
if (g.squad_slots.size() < 3072)
if (g.squad_slots.size() < runtime_dimensions.national_slots_first)
return fail("ReleasePlayer: free-agent pool is outside native squad storage");
} else {
const auto seller_range = squad_range(seller);
@@ -2524,7 +2525,7 @@ PendingOfferResult process_natural_pending_offers_after_desk(GameState& g,
};
if (record_team(0)!=kNoTeam) return false;
const int club=record_team(4*kRecord);
if (club<0 || club>=138) return false;
if (club<0 || club>=runtime_dimensions.league_teams) return false;
const auto squad=squad_range(club);
if (squad.first+squad.count>g.squad_slots.size()) return false;
for (size_t i=squad.first;i<squad.first+squad.count;++i)
@@ -2538,7 +2539,7 @@ PendingOfferResult process_natural_pending_offers_after_desk(GameState& g,
if(offer==0xffffffffu || int(offer&31)!=manager)continue;
const int team=native_team;
const bool national_owner = takeover && team == kNoTeam;
if (team<0 || (team>=138 && !national_owner))
if (team<0 || (team>=runtime_dimensions.league_teams && !national_owner))
return fail("AdvanceTurn: national or unknown owner is unsupported for normal-club offers");
// AdvanceTurn scans raw offer words until the first owned player resolves in
// an ordinary squad. A missing earlier player requires PresentLoanReturn's error
@@ -2661,7 +2662,7 @@ void transfer_list_countdown(GameState& g, GameRandom& game, WatcomRandom& rand,
// FindManagerForClub also recognizes the coach's temporarily saved
// club as owner 4 while manager 0 runs the national team.
return g.manager_of(club) >= 0 || (!g.manager_teams.empty() &&
g.manager_teams[0] == 0x165 && mem.has(::bmh::layout::DeskActions_NationalOpponentManager_RuntimeField) &&
g.manager_teams[0] == kNoTeam && mem.has(::bmh::layout::DeskActions_NationalOpponentManager_RuntimeField) &&
int(mem.u16(::bmh::layout::CupDraw_FormatError_RuntimeField3)) == club);
};
bool human_involved = human_participant(seller);
+1 -1
View File
@@ -14,7 +14,7 @@ std::optional<std::filesystem::path> choose_game_file(const std::string& title)
NFD::Guard guard;
NFD::UniquePathU8 path;
// one filter with all accepted kinds; the check after the choice decides
const nfdu8filteritem_t filters[] = {{"BMH game (ZIP, 7z, BMH.EXE, FLTD.EXE)", "zip,7z,exe"}};
const nfdu8filteritem_t filters[] = {{"BMH game (ZIP, 7z, BMH.EXE, FLTD.EXE)", "zip,7z,exe,obd"}};
const nfdresult_t result = NFD::OpenDialog(path, filters, 1);
if (result == NFD_CANCEL) return std::nullopt;
if (result != NFD_OKAY) throw std::runtime_error(std::string("no file dialog: ") + NFD::GetError());
-2
View File
@@ -11,7 +11,6 @@
#include <vector>
#include "formats/binary.hpp"
#include "formats/rule_base.hpp"
#include "launch/archive.hpp"
#include "launch/game_data.hpp"
@@ -120,7 +119,6 @@ LeImage translate_fltd(const fs::path& fltd_exe) {
}
}
LeImage out = LeImage::from_bytes(kDeBase, std::move(image));
apply_rule_base(out);
return out;
}
+3
View File
@@ -96,6 +96,9 @@
{::bmh::layout::TeamStatistics_Render_ExecutableField, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation72, {}},
{::bmh::layout::DeskDrawers_Curve_ExecutableField, 24, Kind::copy, ::bmh::layout::EnglishLayoutTranslation160, {}},
{::bmh::layout::DeskState_FormatError_RuntimeField, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation161, {}},
{::bmh::layout::Desktop_Render_RuntimeField, 2, Kind::copy, ::bmh::layout::EnglishDesktopBinSourceX, {}},
{::bmh::layout::Desktop_Render_RuntimeField2, 2, Kind::copy, ::bmh::layout::EnglishDesktopBinSourceY, {}},
{::bmh::layout::Desktop_Render_RuntimeField3, 2, Kind::copy, ::bmh::layout::EnglishDesktopSocketSourceX, {}},
{::bmh::layout::Tactics_DrawSetting_RuntimeField, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation224, {}},
{::bmh::layout::Tactics_DrawSetting_RuntimeField2, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation225, {}},
{::bmh::layout::Tactics_DrawSetting_RuntimeField3, 7, Kind::copy, ::bmh::layout::EnglishLayoutTranslation226, {}},
+14 -6
View File
@@ -11,6 +11,8 @@
#include <system_error>
#include "formats/binary.hpp"
#include "formats/resource_bundle.hpp"
#include "formats/data_profile.hpp"
#include "formats/le.hpp"
#include "formats/m3d.hpp"
#include "formats/textd.hpp"
@@ -52,6 +54,7 @@ struct Family {
const char* database;
};
constexpr Family kFamilies[] = {
{GameFamily::german, "COMMUNITY.OBD", 0, "TEXTD.BLK", "M3D.MAN"},
{GameFamily::german, "BMH.EXE", 602527, "TEXTD.BLK", "M3D.MAN"},
{GameFamily::english, "FLTD.EXE", 507925, "TEXTE.BLK", "M3E.MAN"},
{GameFamily::disk1994, "M3.EXE", 0, "", "M3PC.MAN"},
@@ -82,7 +85,7 @@ void require(GameCheck& c, const fs::path& dir, const std::string& name, uint64_
return;
}
std::error_code ec;
const uint64_t actual = fs::file_size(*p, ec);
const uint64_t actual = fs::exists(*p,ec) ? fs::file_size(*p, ec) : read_file(*p).size();
if (ec || actual == 0) c.problems.push_back(shown + " is empty or unreadable");
else if (size != 0 && actual != size)
c.problems.push_back(shown + " has " + std::to_string(actual) + " bytes instead of " + std::to_string(size));
@@ -90,7 +93,9 @@ void require(GameCheck& c, const fs::path& dir, const std::string& name, uint64_
// The shared picture/font/sound files of the sub directories KB, W, F and S.
void require_media(GameCheck& c) {
const bool bundled=fs::is_regular_file(c.directory/kCommunityBundle);
const auto sub = [&](const char* name) -> std::optional<fs::path> {
if(bundled)return c.directory/name;
auto p = find_file(c.directory, name);
if (!p || !fs::is_directory(*p)) {
c.problems.push_back(std::string("the directory ") + name + " is missing");
@@ -142,14 +147,15 @@ std::string text_title(const std::string& raw) {
void check_german(GameCheck& c) {
// (a translated English game has BMH.exe in the OpenBMH image format, launch/fltd.hpp)
const bool bundled=fs::is_regular_file(c.directory/kCommunityBundle);
bool image = false;
if (const auto exe = find_file(c.directory, "BMH.EXE")) {
if (const auto exe = find_file(c.directory, "BMH.EXE"); exe && !bundled) {
std::ifstream in(*exe, std::ios::binary);
char head[13] = {};
in.read(head, sizeof head);
image = std::string(head, sizeof head) == "OPENBMH-IMAGE";
}
require(c, c.directory, "BMH.EXE", image ? 0 : 602527, "BMH.EXE");
require(c, c.directory, "BMH.EXE", (image || bundled) ? 0 : 602527, bundled ? "RUNTIME.DAT" : "BMH.EXE");
require(c, c.directory, "TEXTD.BLK", 0, "TEXTD.BLK");
require(c, c.directory, "M3D.MAN", 0, "M3D.MAN");
for (const Required& r : kCommon) require(c, c.directory, r.name, r.size, r.name);
@@ -158,7 +164,8 @@ void check_german(GameCheck& c) {
// the files must also load: the engine reads tables from the EXE, the texts and the
// database of clubs and players
try {
load_le(*find_file(c.directory, "BMH.EXE"));
const auto runtime=load_le(*find_file(c.directory, "BMH.EXE"));
if(bundled && (!runtime.runtime_policy() || !runtime.expanded_profile()))throw FormatError("unsupported standalone runtime/profile");
} catch (const std::exception& e) {
c.problems.push_back(std::string("BMH.EXE cannot be read: ") + e.what());
}
@@ -212,7 +219,7 @@ bool is_game_file(const std::string& relative) {
const size_t dot = base.find_last_of('.');
if (dot == std::string::npos) return false;
const std::string ext = base.substr(dot + 1);
for (const char* e : {"EXE", "BLK", "MAN", "DAT", "MEN", "COL", "VGA", "FNT", "LBM", "EIN", "CFG", "FBM", "WAP"})
for (const char* e : {"EXE", "BLK", "MAN", "DAT", "MEN", "COL", "VGA", "FNT", "LBM", "EIN", "CFG", "FBM", "WAP", "OBD"})
if (ext == e) return true;
return false;
}
@@ -315,6 +322,7 @@ ResolvedGame resolve_game_unchecked(const fs::path& input, const fs::path& cache
std::optional<fs::path> find_file(const fs::path& directory, const std::string& name) {
std::error_code ec;
const fs::path exact = directory / path_from_utf8(name);
if(resource_exists(exact))return exact;
if (fs::exists(exact, ec)) return exact;
const std::string wanted = upper(name);
for (const auto& e : fs::directory_iterator(directory, ec))
@@ -379,7 +387,7 @@ ResolvedGame resolve_game(const fs::path& input, const fs::path& cache) {
const fs::path marker = prepared / ".openbmh-english";
// the version of the translation (launch/fltd.cpp, fltd_map.inc): a cache built
// by another version is built again
constexpr const char* kTranslation = "english translation 12"; // 12: contract warning ContractExpiryWarningText; 11: statistics windows, graph labels/count classes, streaks and national-badge banks
constexpr const char* kTranslation = "english translation 13"; // 13: setup toggle rows, positive balance colour and desktop bar controls
std::string built;
{
std::ifstream in(marker);
+176
View File
@@ -0,0 +1,176 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "obdeddi/document.hpp"
#include "cli/json.hpp"
#include "formats/palette.hpp"
#include "miniz.h"
#include "Sha256.h"
#include <algorithm>
#include <chrono>
#include <fstream>
#include <iomanip>
#include <sstream>
#ifdef _WIN32
#define NOMINMAX
#include <windows.h>
#else
#include <fcntl.h>
#include <sys/file.h>
#include <unistd.h>
#endif
namespace bmh::obdeddi {
namespace {
using Entries=std::map<std::string,Bytes>;
std::string upper(std::string s){for(char&c:s)if(c>='a'&&c<='z')c=char(c-'a'+'A');return s;}
std::string key(const Entries& entries,std::string name){for(const auto&[k,v]:entries)if(upper(k)==upper(name))return k;throw FormatError("Fehlende OBD-Ressource: "+name);}
Entries unpack(const Bytes& bytes) {
mz_zip_archive zip{};
if(bytes.size()>64*1024*1024 || !mz_zip_reader_init_mem(&zip,bytes.data(),bytes.size(),0))throw FormatError("OBD-Archiv ist ungueltig oder zu gross.");
Entries result;std::vector<std::string> names;uint64_t total=0;
try {
const auto count=mz_zip_reader_get_num_files(&zip);if(count>4096)throw FormatError("Zu viele OBD-Eintraege.");
for(mz_uint i=0;i<count;++i){mz_zip_archive_file_stat st{};if(!mz_zip_reader_file_stat(&zip,i,&st))throw FormatError("OBD-Verzeichnis beschaedigt.");if(st.m_is_directory)continue;
std::string name=st.m_filename;const std::filesystem::path path(name);
if(path.is_absolute()||name.find('\\')!=std::string::npos||name.find(':')!=std::string::npos)throw FormatError("Ungueltiger Ressourcenpfad.");
for(const auto&part:path)if(part==".."||part==".")throw FormatError("Ungueltiger Ressourcenpfad.");
if(std::find(names.begin(),names.end(),upper(name))!=names.end())throw FormatError("Doppelte OBD-Ressource.");names.push_back(upper(name));
total+=st.m_uncomp_size;if(st.m_uncomp_size>32*1024*1024||total>128*1024*1024)throw FormatError("OBD-Ressourcen zu gross.");
Bytes data(size_t(st.m_uncomp_size));if(!mz_zip_reader_extract_to_mem(&zip,i,data.data(),data.size(),0))throw FormatError("OBD-Pruefsumme fehlerhaft.");result.emplace(name,std::move(data));
}
}catch(...){mz_zip_reader_end(&zip);throw;}
mz_zip_reader_end(&zip);return result;
}
Bytes pack(const Entries& entries){
mz_zip_archive zip{};if(!mz_zip_writer_init_heap(&zip,0,0))throw FormatError("Archiv kann nicht erstellt werden.");
void*data=nullptr;size_t size=0;
try{for(const auto&[name,value]:entries)if(!mz_zip_writer_add_mem(&zip,name.c_str(),value.data(),value.size(),MZ_BEST_COMPRESSION))throw FormatError("Ressource kann nicht gespeichert werden.");
if(!mz_zip_writer_finalize_heap_archive(&zip,&data,&size))throw FormatError("Archivabschluss fehlgeschlagen.");
}catch(...){mz_zip_writer_end(&zip);throw;}
Bytes result(static_cast<uint8_t*>(data),static_cast<uint8_t*>(data)+size);mz_free(data);mz_zip_writer_end(&zip);return result;
}
void write(const std::filesystem::path& path,const Bytes& bytes){std::ofstream f(path,std::ios::binary|std::ios::trunc);f.write(reinterpret_cast<const char*>(bytes.data()),std::streamsize(bytes.size()));if(!f)throw FormatError("Datei kann nicht geschrieben werden.");f.close();if(!f)throw FormatError("Dateiabschluss fehlgeschlagen.");}
void word(Bytes& data,size_t pos,uint16_t value){data.at(pos)=uint8_t(value);data.at(pos+1)=uint8_t(value>>8);}
void rename(Bytes& pool,Bytes& offsets,size_t index,const std::string& name){
if(name.empty()||name.size()>255||std::any_of(name.begin(),name.end(),[](unsigned char c){return c<32||c>=127;}))throw FormatError("Name muss 1 bis 255 darstellbare Original-Zeichen enthalten.");
const size_t at=le16(offsets,index*2);std::string old;for(size_t i=at;i<pool.size()&&pool[i];++i)old+=char(pool[i]);if(old==name)return;
if(pool.size()+name.size()+1>65535)throw FormatError("Namenspool ist voll.");
word(offsets,index*2,uint16_t(pool.size()));pool.insert(pool.end(),name.begin(),name.end());pool.push_back(0);
}
struct Lock {
#ifdef _WIN32
HANDLE handle=INVALID_HANDLE_VALUE;
explicit Lock(std::filesystem::path path){path+=".obdeddi.lock";handle=CreateFileW(path.c_str(),GENERIC_READ|GENERIC_WRITE,0,nullptr,OPEN_ALWAYS,FILE_ATTRIBUTE_TEMPORARY|FILE_FLAG_DELETE_ON_CLOSE,nullptr);if(handle==INVALID_HANDLE_VALUE)throw FormatError("Datei ist gesperrt oder nicht beschreibbar.");}
~Lock(){CloseHandle(handle);}
#else
int fd=-1;std::filesystem::path path;
explicit Lock(std::filesystem::path p):path(std::move(p)){path+=".obdeddi.lock";fd=open(path.c_str(),O_CREAT|O_RDWR,0600);if(fd<0)throw FormatError("Datei ist nicht beschreibbar.");if(flock(fd,LOCK_EX|LOCK_NB)){close(fd);fd=-1;throw FormatError("Datei ist gesperrt.");}}
~Lock(){if(fd>=0){unlink(path.c_str());close(fd);}}
#endif
};
}
std::string sha256(const Bytes& bytes){CSha256 state;Sha256_Init(&state);Sha256_Update(&state,bytes.data(),bytes.size());Byte digest[SHA256_DIGEST_SIZE];Sha256_Final(&state,digest);std::ostringstream text;for(auto b:digest)text<<std::hex<<std::setw(2)<<std::setfill('0')<<unsigned(b);return text.str();}
Document::Document(const std::filesystem::path& path):path_(std::filesystem::absolute(path)),original_(read_file(path)),entries_(unpack(original_)){
profile_=decode_data_profile(entries_.at(key(entries_,"OBMHPROF.INI")));profile_.validate();
const auto&raw=entries_.at(key(entries_,"PACKAGE.JSON"));const auto manifest=cli::parse_json(std::string(raw.begin(),raw.end()));
if(!manifest.object())throw FormatError("Ungueltiges OBD-Manifest.");
const auto it=manifest.object()->find("files");if(it==manifest.object()->end()||!it->second.object())throw FormatError("OBD-Pruefsummen fehlen.");
for(const auto&[name,hash]:*it->second.object())if(!hash.string()||sha256(entries_.at(key(entries_,name)))!=*hash.string())throw FormatError("OBD-Ressource wurde extern veraendert: "+name);
const auto& runtime=entries_.at(key(entries_,"RUNTIME.DAT"));if(runtime.size()<36 || std::string(runtime.begin(),runtime.begin()+8)!="OBMHDAT1")throw FormatError("Kein unterstuetztes eigenstaendiges OBD-Datenpaket.");
db_=decode_database(entries_.at(key(entries_,"M3D.MAN")),profile_.counts);refresh_owners();
}
void Document::refresh_owners(){owners_.assign(db_.players.size(),-1);for(uint32_t team=0;team<profile_.counts.league_teams;++team)for(uint32_t row=0;row<24;++row){int id=le16(db_.squad_list,(team*24+row)*2)&4095;if(id!=4095){if(size_t(id)>=owners_.size()||owners_[size_t(id)]!=-1)throw FormatError("Ungueltige oder doppelte Kaderzuordnung.");owners_[size_t(id)]=int(team);}}}
int Document::club_of(size_t id)const{return owners_.at(id);}
PlayerValues Document::player(size_t id)const{const auto&p=db_.players.at(id);PlayerValues v;v.name=p.name;v.position=p.position();v.nation=p.nationality()+((db_.raw_player_bonus_values.at(id)&128)?32:0);v.age=p.age();v.form=p.form();v.technique=p.technique();v.condition=p.condition();v.bonus=db_.raw_player_bonus_values.at(id)&127;for(int i=0;i<7;++i)v.skills[i]=p.skill(Player::Skill(i));return v;}
void Document::set_player(size_t id,const PlayerValues& v){
if(v.position<0||v.position>3||v.nation<0||v.nation>=62||v.age<16||v.age>47||v.form<0||v.form>99||v.technique<0||v.technique>99||v.condition<0||v.condition>99||v.bonus<0||v.bonus>127)throw FormatError("Spielerwert ausserhalb des Original-Bereichs.");
for(auto skill:v.skills)if(skill<0||skill>3)throw FormatError("Faehigkeiten liegen zwischen 0 und 3.");
auto next=db_;auto&p=next.players.at(id);rename(next.pools[1],next.raw_player_name_offsets,id,v.name);p.name=v.name;
p.w35c=(p.w35c&~0x1fffffu)|uint32_t(v.form)|uint32_t(v.technique)<<7|uint32_t(v.condition)<<14;
p.w364=(p.w364&~(3u|(31u<<21)))|uint32_t(v.position)|uint32_t(v.age-16)<<21;
uint32_t skills=0;for(int i=0;i<7;++i)skills|=uint32_t(v.skills[i])<<(i*2);
p.w368=(p.w368&0x07ffc000u)|skills|uint32_t(v.nation&31)<<27;
next.raw_player_bonus_values.at(id)=uint8_t(v.bonus|((v.nation>>5)<<7));
if(encode_database(next)!=encode_database(db_)){db_=std::move(next);dirty_=true;changes_.push_back("player:"+std::to_string(id));}
}
void Document::set_club(size_t id,std::string name,int kit,int start,int length){
if(kit<0||kit>255||start<0||start>15||length<1||length>16||size_t(start+length)>name.size())throw FormatError("Ungueltige Farbe oder Kurznamens-Auswahl.");
auto next=db_;rename(next.pools[0],next.raw_club_name_offsets,id,name);next.club_names.at(id)=std::move(name);next.raw_club_kit_selectors.at(id)=uint8_t(kit);
if(id<next.counts.n42)next.raw_club_short_name_offsets.at(id)=uint8_t((start<<4)|(length-1));
if(encode_database(next)!=encode_database(db_)){db_=std::move(next);dirty_=true;changes_.push_back("club:"+std::to_string(id));}
}
void Document::move_player(size_t id,int destination,int swap){
const int source=club_of(id);if(source<0||destination<0||destination>=int(profile_.counts.league_teams)||source==destination)throw FormatError("Kaderwechsel nur zwischen zwei Ligavereinen moeglich.");
auto find=[&](int team,int pid){for(int row=0;row<24;++row)if((le16(db_.squad_list,size_t(team*24+row)*2)&4095)==pid)return team*24+row;return -1;};
int from=find(source,int(id)),to=find(destination,swap<0?4095:swap);
if(to<0)throw FormatError("Zielkader ist voll; Tauschpartner auswaehlen.");
if(swap>=0 && (size_t(swap)>=owners_.size()||club_of(size_t(swap))!=destination))throw FormatError("Ungueltiger Tauschpartner.");
if(swap<0 && std::count(owners_.begin(),owners_.end(),source)<=11)throw FormatError("Der Quellverein braucht mindestens elf Spieler.");
auto slots=db_.squad_list;
if(swap>=0){const auto a=le16(slots,size_t(from)*2),b=le16(slots,size_t(to)*2);word(slots,size_t(from)*2,uint16_t((a&0xf000)|(b&4095)));word(slots,size_t(to)*2,uint16_t((b&0xf000)|(a&4095)));}
else{word(slots,size_t(to)*2,le16(slots,size_t(from)*2));word(slots,size_t(from)*2,4095);for(int team:{source,destination}){std::vector<uint16_t> list;for(int row=0;row<24;++row){auto v=le16(slots,size_t(team*24+row)*2);if((v&4095)!=4095)list.push_back(v);}for(int row=0;row<24;++row)word(slots,size_t(team*24+row)*2,row<int(list.size())?uint16_t((list[size_t(row)]&0x7fff)|(row<11?0x8000:0)):4095);}}
db_.squad_list=std::move(slots);refresh_owners();dirty_=true;changes_.push_back("roster:player:"+std::to_string(id)+":"+std::to_string(source)+">"+std::to_string(destination));
}
std::array<uint32_t,256> Document::palette() const {
const auto& data=entries_.at(key(entries_,"M3PC.COL"));if(data.size()!=768)throw FormatError("Ungueltige Palette.");
std::array<uint32_t,256> colors{};for(size_t i=0;i<256;++i)colors[i]=0xff000000u|uint32_t(vga_dac_rgb8(data[i*3]))<<16|uint32_t(vga_dac_rgb8(data[i*3+1]))<<8|vga_dac_rgb8(data[i*3+2]);return colors;
}
Image Document::logo_sheet(int page) const {
const auto name="W/"+std::to_string(page)+".VGA";
const auto changed=changed_assets_.find(name);if(changed!=changed_assets_.end())return decode_vga(changed->second);
return decode_vga(entries_.at(key(entries_,name)));
}
std::array<uint32_t,1444> Document::logo(size_t club) const {
if(club>=profile_.national_first)throw FormatError("Kein Vereinslogo.");
const int cell=le16(db_.raw_club_badge_selectors,club*2)&511;const auto sheet=logo_sheet(cell/8);if(sheet.width!=304||sheet.height!=38)throw FormatError("Ungueltiger Wappenbogen.");
const auto colors=palette();std::array<uint32_t,1444> out{};for(int y=0;y<38;++y)for(int x=0;x<38;++x)out[size_t(y*38+x)]=colors[sheet.pixels[size_t(y*304+(cell%8)*38+x)]];return out;
}
Image Document::convert_logo(const std::array<uint32_t,1444>& rgba) const {
const auto colors=palette();Image image(38,38,94);std::map<int,Image> sheets;
for(int y=0;y<38;++y)for(int x=0;x<38;++x){int votes[4]{};for(int club=0;club<90;++club){int cell=le16(db_.raw_club_badge_selectors,size_t(club)*2)&511;auto it=sheets.find(cell/8);if(it==sheets.end())it=sheets.emplace(cell/8,logo_sheet(cell/8)).first;if(it->second.width!=304||it->second.height!=38)throw FormatError("Ungueltiger Wappenbogen.");auto value=it->second.pixels[size_t(y*304+(cell%8)*38+x)];if(value>=92&&value<=95)++votes[value-92];}
const int background=92+int(std::max_element(votes,votes+4)-votes);auto c=rgba[size_t(y*38+x)];int alpha=int(c>>24);int red=(int(c>>16&255)*alpha+int(colors[size_t(background)]>>16&255)*(255-alpha)+127)/255;int green=(int(c>>8&255)*alpha+int(colors[size_t(background)]>>8&255)*(255-alpha)+127)/255;int blue=(int(c&255)*alpha+int(colors[size_t(background)]&255)*(255-alpha)+127)/255;
int best=0,distance=2147483647;for(int i=0;i<256;++i){int dr=int(colors[size_t(i)]>>16&255)-red,dg=int(colors[size_t(i)]>>8&255)-green,db=int(colors[size_t(i)]&255)-blue;int d=dr*dr+dg*dg+db*db;if(d<distance){best=i;distance=d;}}image.at(x,y)=uint8_t(best);
}return image;
}
std::array<uint32_t,1444> Document::preview_logo(const std::array<uint32_t,1444>& rgba) const {auto image=convert_logo(rgba);auto colors=palette();std::array<uint32_t,1444> out{};for(size_t i=0;i<1444;++i)out[i]=colors[image.pixels[i]];return out;}
void Document::set_logo(size_t club,const std::array<uint32_t,1444>& rgba){
if(club>=profile_.national_first)throw FormatError("Kein Vereinslogo.");
auto selectors=db_.raw_club_badge_selectors;const auto old=le16(selectors,club*2);int cell=old&511;int references=0;bool used[512]{};
for(size_t i=0;i<db_.counts.clubs;++i){int c=le16(selectors,i*2)&511;used[c]=true;references+=c==cell;}
if(references>1){auto free=std::find(used,used+512,false);if(free==used+512)throw FormatError("Keine freie Wappenzelle vorhanden.");cell=int(free-used);}
Image sheet;try{sheet=logo_sheet(cell/8);}catch(const std::out_of_range&){sheet=Image(304,38,94);}catch(const FormatError&){if(entries_.count("W/"+std::to_string(cell/8)+".VGA"))throw;sheet=Image(304,38,94);}
if(sheet.width!=304||sheet.height!=38)throw FormatError("Ungueltiger Wappenbogen.");auto image=convert_logo(rgba);
for(int y=0;y<38;++y)for(int x=0;x<38;++x)sheet.at((cell%8)*38+x,y)=image.at(x,y);
Bytes encoded;const auto put=[&](uint32_t v,int count){for(int i=0;i<count;++i)encoded.push_back(uint8_t(v>>(8*i)));};Bytes payload;
for(size_t i=0;i<sheet.pixels.size();i+=128){auto count=std::min(size_t(128),sheet.pixels.size()-i);payload.push_back(uint8_t(count-1));payload.insert(payload.end(),sheet.pixels.begin()+i,sheet.pixels.begin()+i+count);}payload.push_back(0);put(304,2);put(38,2);put(uint32_t(payload.size()),4);encoded.insert(encoded.end(),payload.begin(),payload.end());
const auto name="W/"+std::to_string(cell/8)+".VGA";changed_assets_[name]=std::move(encoded);word(db_.raw_club_badge_selectors,club*2,uint16_t((old&~511)|cell));dirty_=true;changes_.push_back("logo:club:"+std::to_string(club));
}
std::filesystem::path Document::save(){
if(!dirty_)return {};
Lock lock(path_);if(read_file(path_)!=original_)throw FormatError("OBD wurde seit dem Oeffnen extern geaendert. Bitte neu oeffnen.");
const auto master=encode_database(db_);
if(changed_assets_.empty()&&master==entries_.at(key(entries_,"M3D.MAN"))){dirty_=false;changes_.clear();return {};}
auto changed=entries_;changed[key(changed,"M3D.MAN")]=master;for(const auto&[name,data]:changed_assets_){auto found=std::find_if(changed.begin(),changed.end(),[&](const auto& item){return upper(item.first)==upper(name);});if(found==changed.end())changed[name]=data;else found->second=data;}
auto&manifestBytes=changed.at(key(changed,"PACKAGE.JSON"));auto manifest=cli::parse_json(std::string(manifestBytes.begin(),manifestBytes.end()));cli::Json::Object hashes;
for(const auto&[name,bytes]:changed)if(upper(name)!="PACKAGE.JSON")hashes.emplace(name,sha256(bytes));
(*manifest.object())["files"]=std::move(hashes);
const auto token=std::to_string(std::chrono::system_clock::now().time_since_epoch().count());
cli::Json::Array records;for(const auto& change:changes_)records.emplace_back(change);
auto& history=(*manifest.object())["editor_history"];
if(!history.array())history=cli::Json::Array{};
std::get<cli::Json::Array>(history.value).emplace_back(cli::Json::Object{{"editor","obdeddi"},{"timestamp_epoch_ticks",token},{"source_sha256",sha256(original_)},{"changes",std::move(records)}});
const auto text=cli::dump_json(manifest);manifestBytes=Bytes(text.begin(),text.end());
const auto output=pack(changed);auto temp=path_;temp+=".tmp-"+token;
std::filesystem::path backup;
try{
write(temp,output);Document verified(temp);if(encode_database(verified.database())!=encode_database(db_))throw FormatError("Pruefung des neuen Archivs fehlgeschlagen.");
const auto backups=path_.parent_path()/"backups";std::filesystem::create_directories(backups);auto backupName=path_.filename();backupName+="."+token+".bak";backup=backups/backupName;
std::filesystem::copy_file(path_,backup);if(read_file(backup)!=original_)throw FormatError("Backup-Pruefung fehlgeschlagen.");
if(read_file(path_)!=original_)throw FormatError("OBD wurde waehrend des Speicherns extern geaendert.");
#ifdef _WIN32
if(!ReplaceFileW(path_.c_str(),temp.c_str(),nullptr,0,nullptr,nullptr))throw FormatError("OBD konnte nicht atomar ersetzt werden. Original und Backup bleiben erhalten.");
#else
std::filesystem::rename(temp,path_);
#endif
}catch(...){std::error_code ec;std::filesystem::remove(temp,ec);throw;}
entries_=std::move(changed);original_=output;dirty_=false;changes_.clear();changed_assets_.clear();return backup;
}
}
+47
View File
@@ -0,0 +1,47 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "formats/m3d.hpp"
#include "formats/data_profile.hpp"
#include <map>
#include <array>
#include "formats/vga.hpp"
namespace bmh::obdeddi {
struct PlayerValues {
std::string name;
int position=0,nation=0,age=16,form=0,technique=0,condition=0,bonus=0;
int skills[7]{};
};
class Document {
public:
explicit Document(const std::filesystem::path&);
const Database& database() const {return db_;}
const DataProfile& profile() const{return profile_;}
const std::filesystem::path& path() const{return path_;}
bool dirty() const{return dirty_;}
PlayerValues player(size_t) const;
int club_of(size_t player) const;
void set_player(size_t,const PlayerValues&);
void set_club(size_t,std::string name,int kit,int short_start,int short_length);
std::array<uint32_t,1444> logo(size_t club) const;
std::array<uint32_t,1444> preview_logo(const std::array<uint32_t,1444>& rgba) const;
void set_logo(size_t club,const std::array<uint32_t,1444>& rgba);
void move_player(size_t player,int club,int swap_player=-1);
// Returns the verified backup path, or an empty path for a no-op.
std::filesystem::path save();
private:
std::filesystem::path path_;
Bytes original_;
std::map<std::string,Bytes> entries_;
Database db_;
DataProfile profile_;
bool dirty_=false;
std::vector<int> owners_;
std::vector<std::string> changes_;
std::map<std::string,Bytes> changed_assets_;
Image logo_sheet(int page) const;
Image convert_logo(const std::array<uint32_t,1444>&) const;
std::array<uint32_t,256> palette() const;
void refresh_owners();
};
std::string sha256(const Bytes&);
}
+17
View File
@@ -0,0 +1,17 @@
// SPDX-License-Identifier: GPL-3.0-only
#define NOMINMAX
#include "obdeddi/logo_transform_win32.hpp"
#include <algorithm>
#include <cmath>
#include <stdexcept>
#include <memory>
namespace bmh::obdeddi {
std::array<uint32_t,1444> transform_logo(Gdiplus::Bitmap& source,int x,int y,int width,int height,float angle,bool mirror_x,bool mirror_y){
if(x<0||y<0||width<=0||height<=0||int64_t(x)+width>source.GetWidth()||int64_t(y)+height>source.GetHeight()||!std::isfinite(angle)||std::abs(angle)>360)throw std::runtime_error("invalid logo transform");
std::unique_ptr<Gdiplus::Bitmap> cropped(source.Clone(Gdiplus::Rect(x,y,width,height),PixelFormat32bppARGB));if(!cropped||cropped->GetLastStatus()!=Gdiplus::Ok)throw std::runtime_error("logo crop failed");
Gdiplus::ImageAttributes edges;edges.SetWrapMode(Gdiplus::WrapModeTileFlipXY);
Gdiplus::Bitmap target(38,38,PixelFormat32bppARGB);
{Gdiplus::Graphics g(&target);g.Clear(Gdiplus::Color(0,0,0,0));g.SetInterpolationMode(Gdiplus::InterpolationModeHighQualityBicubic);g.SetPixelOffsetMode(Gdiplus::PixelOffsetModeHighQuality);float radians=angle*3.14159265358979323846f/180,w=float(width),h=float(height);float extent=std::max(std::abs(std::cos(radians))*w+std::abs(std::sin(radians))*h,std::abs(std::sin(radians))*w+std::abs(std::cos(radians))*h);float scale=36/extent;g.TranslateTransform(19,19);g.RotateTransform(angle);g.ScaleTransform(mirror_x?-1.f:1.f,mirror_y?-1.f:1.f);if(g.DrawImage(cropped.get(),Gdiplus::RectF(-w*scale/2,-h*scale/2,w*scale,h*scale),0.f,0.f,w,h,Gdiplus::UnitPixel,&edges)!=Gdiplus::Ok)throw std::runtime_error("logo render failed");g.Flush(Gdiplus::FlushIntentionSync);}
std::array<uint32_t,1444> rgba{};for(int py=0;py<38;++py)for(int px=0;px<38;++px){Gdiplus::Color color;if(target.GetPixel(px,py,&color)!=Gdiplus::Ok)throw std::runtime_error("logo pixel read failed");rgba[size_t(py*38+px)]=color.GetValue();}return rgba;
}
}
+9
View File
@@ -0,0 +1,9 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <windows.h>
#include <gdiplus.h>
#include <array>
#include <cstdint>
namespace bmh::obdeddi {
std::array<uint32_t,1444> transform_logo(Gdiplus::Bitmap&,int x,int y,int width,int height,float angle,bool mirror_x,bool mirror_y);
}
+48
View File
@@ -0,0 +1,48 @@
// SPDX-License-Identifier: GPL-3.0-only
#define UNICODE
#define _UNICODE
#define NOMINMAX
#include <windows.h>
#include <commdlg.h>
#include <gdiplus.h>
#include "obdeddi/logo_win32.hpp"
#include "obdeddi/logo_transform_win32.hpp"
#include <algorithm>
#include <cmath>
#include <memory>
#include <string>
namespace bmh::obdeddi {
namespace {
struct Dialog {
HWND window=nullptr,owner=nullptr,edits[5]{},after=nullptr,apply=nullptr;HFONT font=nullptr;
Document* document=nullptr;size_t club=0;int dpi=96;bool done=false,accepted=false,mirrorX=false,mirrorY=false;
ULONG_PTR token=0;std::unique_ptr<Gdiplus::Bitmap> source;std::array<uint32_t,1444> before{},preview{},rgba{};
int px(int n)const{return MulDiv(n,dpi,96);}
HWND child(const wchar_t* cls,const wchar_t* text,DWORD style,int id,int x,int y,int w,int h){auto c=CreateWindowExW(cls==std::wstring(L"EDIT")?WS_EX_CLIENTEDGE:0,cls,text,WS_CHILD|WS_VISIBLE|style,px(x),px(y),px(w),px(h),window,reinterpret_cast<HMENU>(INT_PTR(id)),GetModuleHandleW(nullptr),nullptr);SendMessageW(c,WM_SETFONT,reinterpret_cast<WPARAM>(font),TRUE);return c;}
std::wstring value(int n){wchar_t text[64]{};GetWindowTextW(edits[n],text,64);return text;}
void set(int n,int v){SetWindowTextW(edits[n],std::to_wstring(v).c_str());}
void whole(){if(!source)return;set(0,0);set(1,0);set(2,int(source->GetWidth()));set(3,int(source->GetHeight()));}
void update(){if(!source)return;try{int crop[4];for(int i=0;i<4;++i){auto s=value(i);size_t used=0;crop[i]=std::stoi(s,&used);if(used!=s.size())throw std::runtime_error("number");}auto angleText=value(4);std::replace(angleText.begin(),angleText.end(),L',',L'.');size_t used=0;float angle=std::stof(angleText,&used);if(used!=angleText.size()||!std::isfinite(angle)||angle < -360||angle>360)throw std::runtime_error("angle");
if(crop[0]<0||crop[1]<0||crop[2]<=0||crop[3]<=0||int64_t(crop[0])+crop[2]>source->GetWidth()||int64_t(crop[1])+crop[3]>source->GetHeight())throw std::runtime_error("crop");
rgba=transform_logo(*source,crop[0],crop[1],crop[2],crop[3],angle,mirrorX,mirrorY);preview=document->preview_logo(rgba);InvalidateRect(after,nullptr,TRUE);EnableWindow(apply,TRUE);
}catch(...){EnableWindow(apply,FALSE);MessageBoxW(window,L"Bitte einen gültigen Ausschnitt innerhalb des Bildes und einen Winkel zwischen -360 und 360 eingeben.",L"Vereinslogo",MB_OK|MB_ICONWARNING);}}
void import(){wchar_t path[32768]{};OPENFILENAMEW f{sizeof(f)};f.hwndOwner=window;f.lpstrFilter=L"Bilder (PNG, JPEG, BMP)\0*.png;*.jpg;*.jpeg;*.bmp\0\0";f.lpstrFile=path;f.nMaxFile=32768;f.Flags=OFN_FILEMUSTEXIST|OFN_PATHMUSTEXIST|OFN_NOCHANGEDIR;if(!GetOpenFileNameW(&f))return;auto image=std::unique_ptr<Gdiplus::Bitmap>(Gdiplus::Bitmap::FromFile(path,FALSE));if(!image||image->GetLastStatus()!=Gdiplus::Ok||image->GetWidth()==0||image->GetHeight()==0||image->GetWidth()>16384||image->GetHeight()>16384||uint64_t(image->GetWidth())*image->GetHeight()>64000000){MessageBoxW(window,L"Das Bild konnte nicht geladen werden oder ist zu groß.",L"Vereinslogo",MB_OK|MB_ICONERROR);return;}source=std::move(image);mirrorX=mirrorY=false;set(4,0);whole();update();}
};
void draw(DRAWITEMSTRUCT* item,const std::array<uint32_t,1444>& pixels){FillRect(item->hDC,&item->rcItem,GetSysColorBrush(COLOR_WINDOW));BITMAPINFO info{};info.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);info.bmiHeader.biWidth=38;info.bmiHeader.biHeight=-38;info.bmiHeader.biPlanes=1;info.bmiHeader.biBitCount=32;info.bmiHeader.biCompression=BI_RGB;int size=std::min(int(item->rcItem.right-item->rcItem.left),int(item->rcItem.bottom-item->rcItem.top));int x=item->rcItem.left+(int(item->rcItem.right-item->rcItem.left)-size)/2,y=item->rcItem.top+(int(item->rcItem.bottom-item->rcItem.top)-size)/2;SetStretchBltMode(item->hDC,COLORONCOLOR);StretchDIBits(item->hDC,x,y,size,size,0,0,38,38,pixels.data(),&info,DIB_RGB_COLORS,SRCCOPY);}
LRESULT CALLBACK proc(HWND window,UINT message,WPARAM w,LPARAM l){auto* d=reinterpret_cast<Dialog*>(GetWindowLongPtrW(window,GWLP_USERDATA));if(message==WM_NCCREATE){d=static_cast<Dialog*>(reinterpret_cast<CREATESTRUCTW*>(l)->lpCreateParams);SetWindowLongPtrW(window,GWLP_USERDATA,reinterpret_cast<LONG_PTR>(d));d->window=window;}
if(!d)return DefWindowProcW(window,message,w,l);
if(message==WM_DRAWITEM){auto item=reinterpret_cast<DRAWITEMSTRUCT*>(l);draw(item,item->CtlID==51?d->before:d->preview);return TRUE;}
if(message==WM_COMMAND){switch(LOWORD(w)){case 10:d->import();break;case 11:d->whole();d->update();break;case 12:d->mirrorX=!d->mirrorX;d->update();break;case 13:d->mirrorY=!d->mirrorY;d->update();break;case 14:d->update();break;case IDOK:if(d->source){d->update();if(IsWindowEnabled(d->apply)){try{d->document->set_logo(d->club,d->rgba);d->accepted=true;SendMessageW(window,WM_CLOSE,0,0);}catch(const std::exception&){MessageBoxW(window,L"Das Logo konnte nicht übernommen werden. Bitte die Wappenzuordnung prüfen.",L"Vereinslogo",MB_OK|MB_ICONERROR);}}}break;case IDCANCEL:SendMessageW(window,WM_CLOSE,0,0);break;}return 0;}
if(message==WM_CLOSE){DestroyWindow(window);return 0;}if(message==WM_DESTROY){d->done=true;return 0;}return DefWindowProcW(window,message,w,l);}
}
bool edit_logo(HWND owner,Document& document,size_t club){Dialog d;d.owner=owner;d.document=&document;d.club=club;d.before=document.logo(club);d.preview=d.before;HDC dc=GetDC(owner);d.dpi=GetDeviceCaps(dc,LOGPIXELSX);ReleaseDC(owner,dc);Gdiplus::GdiplusStartupInput startup;if(Gdiplus::GdiplusStartup(&d.token,&startup,nullptr)!=Gdiplus::Ok)throw FormatError("Bildimport kann nicht gestartet werden.");
d.font=CreateFontW(-d.px(14),0,0,0,FW_NORMAL,FALSE,FALSE,FALSE,DEFAULT_CHARSET,OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS,CLEARTYPE_QUALITY,DEFAULT_PITCH,L"Segoe UI");WNDCLASSW wc{};wc.lpfnWndProc=proc;wc.hInstance=GetModuleHandleW(nullptr);wc.hCursor=LoadCursor(nullptr,IDC_ARROW);wc.hbrBackground=GetSysColorBrush(COLOR_BTNFACE);wc.lpszClassName=L"obdeddi.logo";RegisterClassW(&wc);
CreateWindowExW(WS_EX_DLGMODALFRAME|WS_EX_CONTROLPARENT,L"obdeddi.logo",L"Vereinslogo",WS_CAPTION|WS_SYSMENU,CW_USEDEFAULT,CW_USEDEFAULT,d.px(560),d.px(580),owner,nullptr,wc.hInstance,&d);
d.child(L"STATIC",L"Bisher",0,0,18,12,230,24);d.child(L"STATIC",L"Vorschau im Originalformat",0,0,286,12,250,24);d.child(L"STATIC",L"",SS_OWNERDRAW|WS_BORDER,51,28,42,190,190);d.after=d.child(L"STATIC",L"",SS_OWNERDRAW|WS_BORDER,52,310,42,190,190);
d.child(L"BUTTON",L"Bild importieren…",WS_TABSTOP,10,18,247,220,28);d.child(L"BUTTON",L"Ganzes Bild",WS_TABSTOP,11,286,247,250,28);
const wchar_t* labels[]={L"Links",L"Oben",L"Breite",L"Höhe"};for(int i=0;i<4;++i){d.child(L"STATIC",labels[i],0,0,18+i*130,290,120,22);d.edits[i]=d.child(L"EDIT",L"0",WS_TABSTOP|ES_AUTOHSCROLL,30+i,18+i*130,315,118,24);}
d.child(L"STATIC",L"Drehung (Grad)",0,0,18,359,120,22);d.edits[4]=d.child(L"EDIT",L"0",WS_TABSTOP|ES_AUTOHSCROLL,34,150,353,86,24);d.child(L"BUTTON",L"Horizontal spiegeln",WS_TABSTOP,12,260,350,276,28);d.child(L"BUTTON",L"Vertikal spiegeln",WS_TABSTOP,13,260,386,276,28);d.child(L"BUTTON",L"Vorschau aktualisieren",WS_TABSTOP,14,18,395,220,28);
d.child(L"STATIC",L"38 × 38 Pixel, Originalpalette, heller Original-Hintergrund. Speichern erfolgt anschließend im Hauptfenster mit Backup.",0,0,18,433,518,38);d.apply=d.child(L"BUTTON",L"Übernehmen",WS_TABSTOP|BS_DEFPUSHBUTTON,IDOK,260,478,132,28);d.child(L"BUTTON",L"Abbrechen",WS_TABSTOP,IDCANCEL,402,478,134,28);EnableWindow(d.apply,FALSE);
EnableWindow(owner,FALSE);ShowWindow(d.window,SW_SHOW);UpdateWindow(d.window);MSG m{};while(!d.done&&GetMessageW(&m,nullptr,0,0)>0){if(!IsDialogMessageW(d.window,&m)){TranslateMessage(&m);DispatchMessageW(&m);}}EnableWindow(owner,TRUE);SetActiveWindow(owner);d.source.reset();DeleteObject(d.font);Gdiplus::GdiplusShutdown(d.token);return d.accepted;
}
}
+5
View File
@@ -0,0 +1,5 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <windows.h>
#include "obdeddi/document.hpp"
namespace bmh::obdeddi { bool edit_logo(HWND owner,Document&,size_t club); }
+97
View File
@@ -0,0 +1,97 @@
// SPDX-License-Identifier: GPL-3.0-only
#define UNICODE
#define _UNICODE
#define NOMINMAX
#include <windows.h>
#include <commctrl.h>
#include <commdlg.h>
#include <shellapi.h>
#include "obdeddi/document.hpp"
#include "obdeddi/logo_win32.hpp"
#include <algorithm>
#include <cwctype>
#include <memory>
#include <numeric>
#include <string>
#include <vector>
#ifdef _MSC_VER
#pragma comment(linker, "/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
#endif
using bmh::obdeddi::Document;
namespace {
HWND window,list,tab,search,filter,panel,status,saveButton,target,swapBox;
HFONT font;int dpi=96,mode=0,selected=-1,sortColumn=0,scrollPos=0;
bool ascending=true,updating=false,formDirty=false;
std::unique_ptr<Document> document;
std::vector<int> visible;std::vector<HWND> fields;std::wstring displayText;
constexpr int Open=100,Save=101,Search=102,Filter=103,Apply=104,Target=105,Swap=106,Move=107,Tabs=108,Logo=109;
int px(int n){return MulDiv(n,dpi,96);}
std::wstring wide(const std::string& text){int n=MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,text.data(),int(text.size()),nullptr,0);std::wstring out(size_t(n),L' ');if(n)MultiByteToWideChar(CP_UTF8,0,text.data(),int(text.size()),out.data(),n);return out;}
std::wstring original(const std::string& text){return wide(bmh::iso646de_to_utf8(text.c_str()));}
std::wstring text(HWND h){int n=GetWindowTextLengthW(h);std::wstring out(size_t(n)+1,L'\0');GetWindowTextW(h,out.data(),n+1);out.resize(size_t(n));return out;}
std::string encode(std::wstring value){std::string out;for(auto c:value){switch(c){case L'Ä':out+='[';break;case L'Ö':out+='\\';break;case L'Ü':out+=']';break;case L'ä':out+='{';break;case L'ö':out+='|';break;case L'ü':out+='}';break;case L'ß':out+='~';break;default:if(c<32||c>=127)throw std::runtime_error("Name enthaelt nicht darstellbare Original-Zeichen.");out+=char(c);}}return out;}
void error(const std::exception& e){MessageBoxW(window,wide(e.what()).c_str(),L"obdeddi",MB_OK|MB_ICONERROR);}
HWND control(const wchar_t* cls,const wchar_t* caption,DWORD style,int id,int x,int y,int w,int h,HWND parent){HWND c=CreateWindowExW(cls==std::wstring(L"EDIT")?WS_EX_CLIENTEDGE:0,cls,caption,WS_CHILD|WS_VISIBLE|style,px(x),px(y),px(w),px(h),parent,reinterpret_cast<HMENU>(INT_PTR(id)),GetModuleHandleW(nullptr),nullptr);SendMessageW(c,WM_SETFONT,reinterpret_cast<WPARAM>(font),TRUE);return c;}
int combo(HWND h){return int(SendMessageW(h,CB_GETCURSEL,0,0));}
void add(HWND h,const std::wstring& s){SendMessageW(h,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(s.c_str()));}
int number(HWND h){try{auto value=text(h);size_t used=0;int n=std::stoi(value,&used);if(used!=value.size())throw std::invalid_argument("number");return n;}catch(...){throw std::runtime_error("Bitte eine ganze Zahl im angegebenen Bereich eingeben.");}}
void caption(){SetWindowTextW(window,document&&document->dirty()?L"obdeddi *":L"obdeddi");EnableWindow(saveButton,document!=nullptr);}
void setStatus(const std::wstring& value){SetWindowTextW(status,value.c_str());}
std::wstring clubName(int id){return id<0?L"Pool / Reserve":original(document->database().club_names.at(size_t(id)));}
int league(int team){int first=0;for(int l=0;l<9;++l){first+=document->profile().leagues[size_t(l)];if(team<first)return l;}return 9;}
const wchar_t* leagueName(int id){static const wchar_t* names[]={L"Bundesliga",L"2. Bundesliga",L"Regionalliga A",L"Regionalliga B",L"Oberliga",L"Spanien",L"England",L"Frankreich",L"Italien",L"Pokal / International"};return names[id];}
std::wstring cell(int id,int column){const auto& db=document->database();if(mode==0){const auto&p=db.players.at(size_t(id));switch(column){case 0:return original(p.name);case 1:return clubName(document->club_of(size_t(id)));case 2:{static const wchar_t* positions[]={L"Tor",L"Abwehr",L"Mittelfeld",L"Sturm"};return positions[p.position()];}case 3:return std::to_wstring(p.age());default:return std::to_wstring(p.strength());}}switch(column){case 0:return original(db.club_names.at(size_t(id)));case 1:return leagueName(league(id));case 2:{int count=0;for(size_t p=0;p<db.players.size();++p)count+=document->club_of(p)==id;return std::to_wstring(count);}default:return std::to_wstring(id);}}
void buildForm();void rebuild();bool apply();
void setSwapOptions(){if(!document||!target||!swapBox)return;SendMessageW(swapBox,CB_RESETCONTENT,0,0);add(swapBox,L"Nur verschieben");SendMessageW(swapBox,CB_SETITEMDATA,0,-1);int dest=combo(target);for(size_t i=0;i<document->database().players.size();++i)if(document->club_of(i)==dest){int row=int(SendMessageW(swapBox,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(original(document->database().players[i].name).c_str())));SendMessageW(swapBox,CB_SETITEMDATA,WPARAM(row),LPARAM(i));}SendMessageW(swapBox,CB_SETCURSEL,0,0);}
void formField(const wchar_t* label,int row,const std::wstring& value,bool dropdown=false){control(L"STATIC",label,0,0,8,12+row*27,125,23,panel);HWND h=control(dropdown?L"COMBOBOX":L"EDIT",dropdown?L"":value.c_str(),dropdown?(CBS_DROPDOWNLIST|WS_VSCROLL|WS_TABSTOP):(ES_AUTOHSCROLL|WS_TABSTOP),200+row,138,8+row*27,228,dropdown?240:24,panel);fields.push_back(h);}
void buildForm(){updating=true;formDirty=false;selected=selected<0?-1:selected;fields.clear();target=swapBox=nullptr;HWND child=GetWindow(panel,GW_CHILD);while(child){HWND next=GetWindow(child,GW_HWNDNEXT);DestroyWindow(child);child=next;}scrollPos=0;SetScrollPos(panel,SB_VERT,0,TRUE);
if(!document||selected<0){updating=false;return;}
const auto& db=document->database();
if(mode==0){auto p=document->player(size_t(selected));formField(L"Name",0,original(p.name));formField(L"Position",1,L"",true);for(auto s:{L"Tor",L"Abwehr",L"Mittelfeld",L"Sturm"})add(fields[1],s);SendMessageW(fields[1],CB_SETCURSEL,p.position,0);
formField(L"Nationalität",2,L"",true);for(int n=0;n<62;++n)add(fields[2],original(db.club_names.at(document->profile().national_first+uint32_t(n))));SendMessageW(fields[2],CB_SETCURSEL,p.nation,0);
const wchar_t* labels[]={L"Alter (16–47)",L"Form (0–99)",L"Technik (0–99)",L"Kondition (0–99)",L"Bonus (0–127)",L"Teamplay (0–3)",L"Tempo (0–3)",L"Schuss (0–3)",L"Passspiel (0–3)",L"Zweikampf (0–3)",L"Freistoß (0–3)",L"Ecke (0–3)"};int values[]={p.age,p.form,p.technique,p.condition,p.bonus,p.skills[0],p.skills[1],p.skills[2],p.skills[3],p.skills[4],p.skills[5],p.skills[6]};for(int n=0;n<12;++n)formField(labels[n],n+3,std::to_wstring(values[n]));
control(L"STATIC",(L"Berechnete Stärke: "+std::to_wstring(db.players[size_t(selected)].strength())).c_str(),0,0,8,420,350,24,panel);
control(L"BUTTON",L"Werte übernehmen",WS_TABSTOP,Apply,8,451,358,28,panel);
control(L"STATIC",L"Classic-Eigenheit: Beim Karrierestart werden viele Spielerwerte neu erzeugt. Keine Änderung bestehender Spielstände.",0,0,8,490,358,55,panel);
control(L"STATIC",L"Zielverein",0,0,8,555,115,24,panel);target=control(L"COMBOBOX",L"",CBS_DROPDOWNLIST|WS_VSCROLL|WS_TABSTOP,Target,138,550,228,240,panel);for(int t=0;t<int(document->profile().counts.league_teams);++t)add(target,clubName(t));SendMessageW(target,CB_SETCURSEL,0,0);
control(L"STATIC",L"Tauschpartner",0,0,8,588,125,24,panel);swapBox=control(L"COMBOBOX",L"",CBS_DROPDOWNLIST|WS_VSCROLL|WS_TABSTOP,Swap,138,584,228,240,panel);setSwapOptions();control(L"BUTTON",L"Kaderwechsel",WS_TABSTOP,Move,8,621,358,28,panel);bool assigned=document->club_of(size_t(selected))>=0;EnableWindow(target,assigned);EnableWindow(swapBox,assigned);EnableWindow(GetDlgItem(panel,Move),assigned);
}else{auto id=size_t(selected);formField(L"Vereinsname",0,original(db.club_names[id]));formField(L"Trikot-Farbset",1,L"",true);for(int i=0;i<256;++i){if(std::find(db.raw_club_kit_selectors.begin(),db.raw_club_kit_selectors.end(),uint8_t(i))==db.raw_club_kit_selectors.end())continue;int row=int(SendMessageW(fields[1],CB_ADDSTRING,0,reinterpret_cast<LPARAM>((L"Farbset "+std::to_wstring(i)).c_str())));SendMessageW(fields[1],CB_SETITEMDATA,WPARAM(row),i);if(db.raw_club_kit_selectors[id]==i)SendMessageW(fields[1],CB_SETCURSEL,WPARAM(row),0);}
auto span=id<db.raw_club_short_name_offsets.size()?db.raw_club_short_name_offsets[id]:uint8_t(0);formField(L"Beginn (0–15)",2,std::to_wstring(span>>4));formField(L"Länge (1–16)",3,std::to_wstring((span&15)+1));if(id>=db.raw_club_short_name_offsets.size()){EnableWindow(fields[2],FALSE);EnableWindow(fields[3],FALSE);}
control(L"STATIC",L"Liga und Datensatzanzahlen bleiben fest. Wappen und andere Weitere Assets bleiben unverändert.",0,0,8,130,358,60,panel);control(L"BUTTON",L"Werte übernehmen",WS_TABSTOP,Apply,8,205,358,28,panel);control(L"BUTTON",L"Vereinslogo bearbeiten…",WS_TABSTOP,Logo,8,250,358,28,panel);
}
RECT r;GetClientRect(panel,&r);SCROLLINFO si{sizeof(si),SIF_RANGE|SIF_PAGE|SIF_POS,0,px(mode==0?670:250),UINT(r.bottom),0,0};SetScrollInfo(panel,SB_VERT,&si,TRUE);updating=false;
}
bool apply(){if(updating||!formDirty||!document||selected<0)return true;try{if(mode==0){auto p=document->player(size_t(selected));p.name=encode(text(fields[0]));p.position=combo(fields[1]);p.nation=combo(fields[2]);p.age=number(fields[3]);p.form=number(fields[4]);p.technique=number(fields[5]);p.condition=number(fields[6]);p.bonus=number(fields[7]);for(int i=0;i<7;++i)p.skills[i]=number(fields[size_t(i+8)]);document->set_player(size_t(selected),p);}else{int kit=int(SendMessageW(fields[1],CB_GETITEMDATA,WPARAM(combo(fields[1])),0));document->set_club(size_t(selected),encode(text(fields[0])),kit,number(fields[2]),number(fields[3]));}formDirty=false;caption();InvalidateRect(list,nullptr,FALSE);return true;}catch(const std::exception&e){error(e);return false;}}
void rebuild(){if(!document)return;updating=true;visible.clear();auto query=text(search);std::transform(query.begin(),query.end(),query.begin(),[](wchar_t c){return wchar_t(std::towlower(c));});int chosen=combo(filter);
const int total=mode==0?int(document->database().players.size()):int(document->profile().national_first);
for(int id=0;id<total;++id){if(mode==0&&chosen>0){int owner=document->club_of(size_t(id));if(chosen==1?owner!=-1:owner!=chosen-2)continue;}auto name=cell(id,0);std::transform(name.begin(),name.end(),name.begin(),[](wchar_t c){return wchar_t(std::towlower(c));});if(name.find(query)!=std::wstring::npos)visible.push_back(id);}
std::stable_sort(visible.begin(),visible.end(),[](int a,int b){int compare=0;if(mode==0&&sortColumn>=3){int x=sortColumn==3?document->database().players[size_t(a)].age():document->database().players[size_t(a)].strength(),y=sortColumn==3?document->database().players[size_t(b)].age():document->database().players[size_t(b)].strength();compare=(x>y)-(x<y);}else if(mode==1&&sortColumn>=2){int x=std::stoi(cell(a,sortColumn)),y=std::stoi(cell(b,sortColumn));compare=(x>y)-(x<y);}else compare=CompareStringOrdinal(cell(a,sortColumn).c_str(),-1,cell(b,sortColumn).c_str(),-1,TRUE)-CSTR_EQUAL;return ascending?compare<0:compare>0;});
ListView_SetItemCountEx(list,int(visible.size()),LVSICF_NOSCROLL);ListView_SetItemState(list,-1,0,LVIS_SELECTED|LVIS_FOCUSED);auto found=std::find(visible.begin(),visible.end(),selected);if(found==visible.end())selected=visible.empty()?-1:visible.front();int row=selected<0?-1:int(std::find(visible.begin(),visible.end(),selected)-visible.begin());if(row>=0)ListView_SetItemState(list,row,LVIS_SELECTED|LVIS_FOCUSED,LVIS_SELECTED|LVIS_FOCUSED);updating=false;buildForm();setStatus(std::to_wstring(visible.size())+L" Einträge · "+document->path().wstring());
}
void columns(){while(ListView_DeleteColumn(list,0)){};const wchar_t* player[]={L"Spieler",L"Verein",L"Position",L"Alter",L"Stärke"};const wchar_t* clubs[]={L"Verein",L"Liga",L"Kader",L"ID"};for(int i=0;i<(mode==0?5:4);++i){LVCOLUMNW c{};c.mask=LVCF_TEXT|LVCF_WIDTH|LVCF_FMT;c.pszText=const_cast<wchar_t*>(mode==0?player[i]:clubs[i]);c.cx=px(i==0?210:i==1?180:70);c.fmt=i>=3?LVCFMT_RIGHT:LVCFMT_LEFT;ListView_InsertColumn(list,i,&c);}}
bool save(){if(!apply())return false;if(!document)return true;try{SetCursor(LoadCursor(nullptr,IDC_WAIT));auto backup=document->save();setStatus(backup.empty()?L"Keine Änderungen.":L"Gespeichert. Backup: "+backup.wstring());caption();SetCursor(LoadCursor(nullptr,IDC_ARROW));return true;}catch(const std::exception&e){SetCursor(LoadCursor(nullptr,IDC_ARROW));error(e);return false;}}
bool mayClose(){if(!apply())return false;if(!document||!document->dirty())return true;int choice=MessageBoxW(window,L"Änderungen an der OBD speichern?",L"obdeddi",MB_YESNOCANCEL|MB_ICONQUESTION);return choice==IDNO||(choice==IDYES&&save());}
void load(const std::filesystem::path& path){try{auto next=std::make_unique<Document>(path);document=std::move(next);selected=-1;updating=true;SendMessageW(filter,CB_RESETCONTENT,0,0);add(filter,L"Alle Vereine");add(filter,L"Pool / Reserve");for(int t=0;t<int(document->profile().counts.league_teams);++t)add(filter,clubName(t));SendMessageW(filter,CB_SETCURSEL,0,0);updating=false;rebuild();caption();}catch(const std::exception&e){error(e);}}
void open(){if(!mayClose())return;wchar_t path[32768]{};OPENFILENAMEW ofn{sizeof(ofn)};ofn.hwndOwner=window;ofn.lpstrFilter=L"OpenBMH-Daten (*.obd)\0*.obd\0Alle Dateien\0*.*\0";ofn.lpstrFile=path;ofn.nMaxFile=32768;ofn.Flags=OFN_FILEMUSTEXIST|OFN_PATHMUSTEXIST|OFN_NOCHANGEDIR;if(GetOpenFileNameW(&ofn))load(path);}
LRESULT CALLBACK formProc(HWND h,UINT m,WPARAM w,LPARAM l){if(m==WM_SIZE){SCROLLINFO si{sizeof(si),SIF_PAGE};si.nPage=UINT(HIWORD(l));SetScrollInfo(h,SB_VERT,&si,TRUE);int next=GetScrollPos(h,SB_VERT);ScrollWindowEx(h,0,scrollPos-next,nullptr,nullptr,nullptr,nullptr,SW_SCROLLCHILDREN|SW_INVALIDATE|SW_ERASE);scrollPos=next;return 0;}if(m==WM_COMMAND)return SendMessageW(window,m,w,l);if(m==WM_VSCROLL||m==WM_MOUSEWHEEL){SCROLLINFO si{sizeof(si),SIF_ALL};GetScrollInfo(h,SB_VERT,&si);int next=scrollPos;if(m==WM_MOUSEWHEEL)next-=GET_WHEEL_DELTA_WPARAM(w)/WHEEL_DELTA*px(60);else switch(LOWORD(w)){case SB_LINEUP:next-=px(27);break;case SB_LINEDOWN:next+=px(27);break;case SB_PAGEUP:next-=int(si.nPage);break;case SB_PAGEDOWN:next+=int(si.nPage);break;case SB_THUMBTRACK:next=si.nTrackPos;break;};next=std::clamp(next,0,std::max(0,si.nMax-int(si.nPage)+1));ScrollWindowEx(h,0,scrollPos-next,nullptr,nullptr,nullptr,nullptr,SW_SCROLLCHILDREN|SW_INVALIDATE|SW_ERASE);scrollPos=next;SetScrollPos(h,SB_VERT,next,TRUE);return 0;}return DefWindowProcW(h,m,w,l);}
LRESULT CALLBACK proc(HWND h,UINT m,WPARAM w,LPARAM l){switch(m){case WM_SIZE:{RECT r;GetClientRect(h,&r);int right=std::max(px(420),int(r.right)-px(400));MoveWindow(list,px(12),px(92),right-px(24),r.bottom-px(132),TRUE);MoveWindow(panel,right,px(92),r.right-right-px(12),r.bottom-px(132),TRUE);MoveWindow(status,px(12),r.bottom-px(30),r.right-px(24),px(24),TRUE);return 0;}
case WM_GETMINMAXINFO:{auto p=reinterpret_cast<MINMAXINFO*>(l);p->ptMinTrackSize={px(940),px(630)};return 0;}
case WM_COMMAND:{int id=LOWORD(w),code=HIWORD(w);if(updating)return 0;if(id==Open){open();return 0;}if(id==Save){save();return 0;}if(id==Apply){if(apply())buildForm();return 0;}if(id==Search&&code==EN_CHANGE){SetTimer(h,1,180,nullptr);return 0;}if(id==Filter&&code==CBN_SELCHANGE){if(apply())rebuild();return 0;}if(id==Target&&code==CBN_SELCHANGE){setSwapOptions();return 0;}if(id==Logo){if(!apply())return 0;try{if(document&&selected>=0&&bmh::obdeddi::edit_logo(window,*document,size_t(selected)))caption();}catch(const std::exception&e){error(e);}return 0;}if(id==Move){if(!apply())return 0;try{int partner=int(SendMessageW(swapBox,CB_GETITEMDATA,WPARAM(combo(swapBox)),0));document->move_player(size_t(selected),combo(target),partner);caption();rebuild();}catch(const std::exception&e){error(e);}return 0;}if(id>=200&&id<220&&(code==EN_CHANGE||code==CBN_SELCHANGE))formDirty=true;return 0;}
case WM_TIMER:KillTimer(h,1);if(apply())rebuild();return 0;
case WM_NOTIFY:{auto hdr=reinterpret_cast<NMHDR*>(l);if(hdr->hwndFrom==tab&&hdr->code==TCN_SELCHANGING)return apply()?FALSE:TRUE;if(hdr->hwndFrom==tab&&hdr->code==TCN_SELCHANGE){mode=TabCtrl_GetCurSel(tab);selected=-1;sortColumn=0;ascending=true;EnableWindow(filter,mode==0);columns();rebuild();return 0;}if(hdr->hwndFrom!=list)return 0;
if(hdr->code==LVN_GETDISPINFOW){auto info=reinterpret_cast<NMLVDISPINFOW*>(l);if(info->item.iItem>=0&&size_t(info->item.iItem)<visible.size()){displayText=cell(visible[size_t(info->item.iItem)],info->item.iSubItem);info->item.pszText=displayText.data();}return 0;}
if(hdr->code==LVN_ITEMCHANGING&&!updating){auto n=reinterpret_cast<NMLISTVIEW*>(l);if((n->uOldState&LVIS_SELECTED)&&!(n->uNewState&LVIS_SELECTED)&&!apply())return TRUE;}
if(hdr->code==LVN_ITEMCHANGED&&!updating){auto n=reinterpret_cast<NMLISTVIEW*>(l);if((n->uNewState&LVIS_SELECTED)&&n->iItem>=0&&size_t(n->iItem)<visible.size()){selected=visible[size_t(n->iItem)];buildForm();}return 0;}
if(hdr->code==LVN_COLUMNCLICK){if(!apply())return 0;auto n=reinterpret_cast<NMLISTVIEW*>(l);ascending=sortColumn==n->iSubItem?!ascending:true;sortColumn=n->iSubItem;rebuild();return 0;}return 0;}
case WM_CLOSE:if(mayClose())DestroyWindow(h);return 0;case WM_DESTROY:PostQuitMessage(0);return 0;}
return DefWindowProcW(h,m,w,l);}
}
int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,PWSTR,int show){SetProcessDPIAware();HDC dc=GetDC(nullptr);dpi=GetDeviceCaps(dc,LOGPIXELSX);ReleaseDC(nullptr,dc);font=CreateFontW(-px(14),0,0,0,FW_NORMAL,FALSE,FALSE,FALSE,DEFAULT_CHARSET,OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS,CLEARTYPE_QUALITY,DEFAULT_PITCH,L"Segoe UI");INITCOMMONCONTROLSEX init{sizeof(init),ICC_LISTVIEW_CLASSES|ICC_TAB_CLASSES};InitCommonControlsEx(&init);
WNDCLASSW wc{};wc.lpfnWndProc=proc;wc.hInstance=instance;wc.hCursor=LoadCursor(nullptr,IDC_ARROW);wc.hbrBackground=reinterpret_cast<HBRUSH>(COLOR_BTNFACE+1);wc.lpszClassName=L"obdeddi.window";RegisterClassW(&wc);wc.lpfnWndProc=formProc;wc.lpszClassName=L"obdeddi.form";wc.hbrBackground=reinterpret_cast<HBRUSH>(COLOR_WINDOW+1);RegisterClassW(&wc);
window=CreateWindowExW(0,L"obdeddi.window",L"obdeddi",WS_OVERLAPPEDWINDOW|WS_CLIPCHILDREN,CW_USEDEFAULT,CW_USEDEFAULT,px(1180),px(800),nullptr,nullptr,instance,nullptr);
control(L"BUTTON",L"Öffnen…",WS_TABSTOP,Open,12,12,94,28,window);saveButton=control(L"BUTTON",L"Speichern",WS_TABSTOP,Save,114,12,94,28,window);search=control(L"EDIT",L"",ES_AUTOHSCROLL|WS_TABSTOP,Search,228,14,265,25,window);SendMessageW(search,EM_SETCUEBANNER,TRUE,reinterpret_cast<LPARAM>(L"Suchen …"));filter=control(L"COMBOBOX",L"",CBS_DROPDOWNLIST|WS_VSCROLL|WS_TABSTOP,Filter,510,12,350,300,window);
tab=control(WC_TABCONTROLW,L"",WS_TABSTOP,Tabs,12,54,300,30,window);for(int i=0;i<2;++i){TCITEMW item{};item.mask=TCIF_TEXT;item.pszText=const_cast<wchar_t*>(i==0?L"Spieler":L"Vereine");TabCtrl_InsertItem(tab,i,&item);}
list=control(WC_LISTVIEWW,L"",LVS_REPORT|LVS_OWNERDATA|LVS_SINGLESEL|LVS_SHOWSELALWAYS|WS_TABSTOP,120,12,92,650,600,window);ListView_SetExtendedListViewStyle(list,LVS_EX_FULLROWSELECT|LVS_EX_DOUBLEBUFFER|LVS_EX_LABELTIP);
panel=control(L"obdeddi.form",L"",WS_VSCROLL|WS_CLIPCHILDREN,0,780,92,380,600,window);SetWindowLongPtrW(panel,GWL_EXSTYLE,GetWindowLongPtrW(panel,GWL_EXSTYLE)|WS_EX_CONTROLPARENT);status=control(L"STATIC",L"Eine COMMUNITY.OBD öffnen. Weitere Assets bleiben unverändert.",SS_LEFT,0,12,720,1100,24,window);columns();caption();ShowWindow(window,show);SendMessageW(window,WM_SIZE,0,0);UpdateWindow(window);
int argumentCount=0;auto arguments=CommandLineToArgvW(GetCommandLineW(),&argumentCount);if(arguments&&argumentCount>1)load(arguments[1]);if(arguments)LocalFree(arguments);
ACCEL keys[]={{FVIRTKEY|FCONTROL,'O',Open},{FVIRTKEY|FCONTROL,'S',Save}};HACCEL accel=CreateAcceleratorTableW(keys,2);MSG message{};while(GetMessageW(&message,nullptr,0,0)>0){if(!TranslateAcceleratorW(window,accel,&message)&&!IsDialogMessageW(window,&message)){TranslateMessage(&message);DispatchMessageW(&message);}}DestroyAcceleratorTable(accel);DeleteObject(font);return int(message.wParam);}
+10 -4
View File
@@ -1,8 +1,10 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "game/state.hpp"
#include "formats/executable_layout.hpp"
#include "alltime_table.hpp"
#include <algorithm>
#include "game/table.hpp"
#include "game/schedule.hpp"
#include "ui/manager.hpp"
#include "ui/setup.hpp"
namespace bmh::ui { namespace {
@@ -25,11 +27,15 @@ void button(Image&out,const Image&a,const SpriteFont&spr,const LeImage&exe,int x
}
AllTimeTableState alltime_table_from_game(const GameState&g,const LeImage&exe,DeskRequest owner,const Image&underlay,int nation,bool relative){
if(nation<0||nation>4)throw FormatError("alltime: nation outside 0..4");if(underlay.width!=320||underlay.height!=240)throw FormatError("alltime: parent underlay must be 320x240");AllTimeTableState s;s.owner=owner;s.underlay=underlay;s.nation=nation;s.relative=relative;s.mask=uint8_t((1U<<nation)|(relative?0x20:0));
if(g.club_table.size()<168*0x4a)return s;s.has_data=true;s.records.resize(168);
for(int t=0;t<168;++t){size_t b=size_t(t)*0x4a+0x1e;auto u=[&](int o){return uint16_t(g.club_table[b+size_t(o)]|uint16_t(g.club_table[b+size_t(o+1)])<<8);};auto&r=s.records[size_t(t)];r.points=u(0);r.goals_for=u(2);r.goals_against=u(4);r.wins=u(6);r.draws=u(8);r.losses=u(10);if(t<int(g.club_ids.size()))s.club_names[size_t(t)]=g.club_name(t);s.club_name_colors[size_t(t)]=team_color(g,t);}
for(int n=0;n<5;++n)if(0x165+n<int(g.club_ids.size()))s.nation_names[size_t(n)]=g.club_name(0x165+n);
if(g.club_table.size()<runtime_dimensions.record_teams*0x4a)return s;s.has_data=true;s.records.resize(runtime_dimensions.record_teams);
for(int t=0;t<runtime_dimensions.record_teams;++t){size_t b=size_t(t)*0x4a+0x1e;auto u=[&](int o){return uint16_t(g.club_table[b+size_t(o)]|uint16_t(g.club_table[b+size_t(o+1)])<<8);};auto&r=s.records[size_t(t)];r.points=u(0);r.goals_for=u(2);r.goals_against=u(4);r.wins=u(6);r.draws=u(8);r.losses=u(10);if(t<int(g.club_ids.size()))s.club_names[size_t(t)]=g.club_name(t);s.club_name_colors[size_t(t)]=team_color(g,t);}
for(int n=0;n<5;++n)if(kNoTeam+n<int(g.club_ids.size()))s.nation_names[size_t(n)]=g.club_name(kNoTeam+n);
const uint32_t start=kFirst+uint32_t(nation)*8;const int league=exe.u8(kLeague+uint32_t(nation));const uint32_t full=uint32_t(league_matchdays(league));
for(int part=0;part<2;++part){int first=exe.u16(start+uint32_t(part)*4),end=exe.u16(::bmh::layout::AlltimeTable_AlltimeTableFromGame_RuntimeField+uint32_t(nation)*8+uint32_t(part)*4);for(int team=first;team<end;++team){if(team<0||team>=168)continue;const auto&r=s.records[size_t(team)];int played=int(r.wins)+r.draws+r.losses;if(!played)continue;uint32_t p=r.points,gf=r.goals_for,ga=r.goals_against;if(relative){p=p*full*10U/uint32_t(played);gf=gf*full*10U/uint32_t(played);ga=ga*full*10U/uint32_t(played);}AllTimeRow row;row.team=team;row.played=played;row.points=p;row.goals_for=gf;row.goals_against=ga;row.points_key=p*0x10001U+0x7d000000U;row.goal_key=gf*0x10001U-ga*0x10000U+0x7d000000U;s.rows.push_back(row);}}
for(int part=0;part<2;++part){int first=exe.u16(start+uint32_t(part)*4),end=exe.u16(::bmh::layout::AlltimeTable_AlltimeTableFromGame_RuntimeField+uint32_t(nation)*8+uint32_t(part)*4);if (runtime_dimensions.expanded) {
if (nation == 0) { first = part == 0 ? 0 : runtime_dimensions.league_teams; end = part == 0 ? runtime_dimensions.domestic_teams : runtime_dimensions.record_teams; }
else { const int selected = nation + 4; first = league_first_team(selected); end = part == 0 ? first + kLeagueSizes[selected] : first; }
}
for(int team=first;team<end;++team){if(team<0||team>=runtime_dimensions.record_teams)continue;const auto&r=s.records[size_t(team)];int played=int(r.wins)+r.draws+r.losses;if(!played)continue;uint32_t p=r.points,gf=r.goals_for,ga=r.goals_against;if(relative){p=p*full*10U/uint32_t(played);gf=gf*full*10U/uint32_t(played);ga=ga*full*10U/uint32_t(played);}AllTimeRow row;row.team=team;row.played=played;row.points=p;row.goals_for=gf;row.goals_against=ga;row.points_key=p*0x10001U+0x7d000000U;row.goal_key=gf*0x10001U-ga*0x10000U+0x7d000000U;s.rows.push_back(row);}}
std::stable_sort(s.rows.begin(),s.rows.end(),[](const auto&a,const auto&b){if(a.points_key!=b.points_key)return a.points_key>b.points_key;return a.goal_key>b.goal_key;});if(s.rows.size()>24)s.rows.resize(24);return s;
}
AllTimeTableScreen::AllTimeTableScreen(const std::filesystem::path&data,AllTimeTableState s):state_(std::move(s)),data_(data),exe_(load_le(asset_path(data,"BMH.exe"))),font_(load_font(asset_path(data/"F","BMH3.FNT"))),header_(load_font(asset_path(data/"F","BMH2.FNT"))),sprite_(data),window_(load_vga(asset_path(data/"KB","56.VGA"))),buttons_(load_vga(asset_path(data/"KB","0.VGA"))),texts_(load_textd(asset_path(data,"TEXTD.BLK"))){if(state_.underlay.width!=320||state_.underlay.height!=240)throw FormatError("alltime: invalid parent frame");}
+2 -2
View File
@@ -22,8 +22,8 @@ struct AllTimeTableState {
Image underlay;
std::vector<AllTimeRecord> records;
std::array<std::string,5> nation_names{};
std::array<std::string,168> club_names{};
std::array<uint8_t,168> club_name_colors{};
std::vector<std::string> club_names = std::vector<std::string>(size_t(runtime_dimensions.record_teams));
std::vector<uint8_t> club_name_colors = std::vector<uint8_t>(size_t(runtime_dimensions.record_teams));
std::vector<AllTimeRow> rows;
int nation=0;
uint8_t mask=1;
+1 -1
View File
@@ -47,7 +47,7 @@ int32_t source_asset_mask_1e(const GameState& game, int manager) {
}
int source_manager_league(const GameState& game, const LeImage& exe, int manager) {
const int team = game.manager_teams.at(size_t(manager));
if (team > 0x164) return 0; // TeamLeague2 special-team early return.
if (team > (kNoTeam - 1)) return 0; // TeamLeague2 special-team early return.
int cumulative = 0;
for (int league = 0; league < 9; ++league) {
cumulative += exe.u8(::bmh::layout::LeagueSizes + uint32_t(league));
Loaded 100 of 179 files, more files were not shown because too many files have changed in this diff. Show more