mirror of
https://github.com/TheBozos/TMB_Recomp.git
synced 2026-12-05 19:35:03 -10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5864909a50 | ||
|
|
f7c06f2912 | ||
|
|
372a05850f | ||
|
|
4cdb0ec911 | ||
|
|
0ca92a14ad | ||
|
|
86179adf38 | ||
|
|
b066822107 | ||
|
|
57cf629e50 | ||
|
|
9217669e76 | ||
|
|
7aac19c03d | ||
|
|
435a0e092e | ||
|
|
8fcd3a5be8 | ||
|
|
5268eddd89 | ||
|
|
753c816cd8 | ||
|
|
15c439eb4f | ||
|
|
11694614a3 | ||
|
|
fa7fe981bc | ||
|
|
6da09e8712 | ||
|
|
0e66d19c58 | ||
|
|
1473dd3e0c | ||
|
|
ecb61b81f9 | ||
|
|
2e4f88fcab | ||
|
|
b98492db76 | ||
|
|
1754616537 | ||
|
|
fb17ea2508 | ||
|
|
c00c238331 | ||
|
|
14027a5026 | ||
|
|
2e37b81b0d | ||
|
|
13a63bcafd | ||
|
|
3f6623f47e | ||
|
|
f0806c5ef0 | ||
|
|
6db6a16b0d | ||
|
|
7ccc02b050 | ||
|
|
8d808aaf2a | ||
|
|
06d323c49d | ||
|
|
80ba27ab07 | ||
|
|
254f994459 | ||
|
|
f620ab163b | ||
|
|
ce069120c1 | ||
|
|
b84fefaf95 | ||
|
|
159d4a5de3 |
No files matched your search
@@ -13,6 +13,8 @@ jobs:
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.14'
|
||||
- name: The BozoEngine release cmake/bozo_engine.json pins (the RecompLauncher settings check reads it)
|
||||
run: cmake -P cmake/bozo_engine_fetch.cmake
|
||||
- name: Release, migration and timing checks
|
||||
run: python -m unittest discover -s tests -v
|
||||
- name: Python syntax
|
||||
|
||||
@@ -3,8 +3,10 @@
|
||||
#
|
||||
# git tag v0.1.0 && git push origin v0.1.0 (or Actions > Release > Run workflow, with the tag)
|
||||
#
|
||||
# On a version tag it makes the build kit from the pinned MSYS2 packages (tools/build_kit_packages.json), the release
|
||||
# zips TMB_Recomp-<version>-bozo.zip (folder TMB_Recomp_Bozo) and TMB_Recomp-<version>.zip (folder TMB_Recomp for
|
||||
# On a version tag the linux job makes TMB_Recomp-<version>-linux.tar.gz (folder TMB_Recomp_Bozo: the Linux launcher,
|
||||
# the code, the libraries' sources; make_release.py --linux) on the oldest supported Ubuntu, so the launcher runs on
|
||||
# older glibc. Then the build job makes the build kit from the pinned MSYS2 packages (tools/build_kit_packages.json), the
|
||||
# release zips TMB_Recomp-<version>-bozo.zip (folder TMB_Recomp_Bozo) and TMB_Recomp-<version>.zip (folder TMB_Recomp for
|
||||
# the previous updater). Both carry BozoEngine. It adds hashes and corresponding sources, checks without game data, and creates a DRAFT
|
||||
# GitHub release with CHANGELOG.md's section for the version as its body. Nothing is ever published by this workflow:
|
||||
# the owner runs docs/RELEASE_CHECKLIST.md on a clean PC, then publishes the draft by hand.
|
||||
@@ -46,8 +48,99 @@ concurrency:
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
linux:
|
||||
if: github.event_name != 'release'
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 60
|
||||
env:
|
||||
TAG: ${{ github.event_name == 'workflow_dispatch' && inputs.tag || (github.event_name == 'push' && github.ref_name || '') }}
|
||||
TEST_VERSION: ${{ inputs.version }}
|
||||
steps:
|
||||
- name: Version from the tag (or a test build's)
|
||||
run: |
|
||||
set -eu
|
||||
if [ -n "$TAG" ]; then
|
||||
echo "VERSION=${TAG#v}" >> "$GITHUB_ENV"
|
||||
echo "TEST_BUILD=" >> "$GITHUB_ENV"
|
||||
else
|
||||
echo "VERSION=${TEST_VERSION:-0.0.0-test.$GITHUB_RUN_NUMBER}" >> "$GITHUB_ENV"
|
||||
echo "TEST_BUILD=1" >> "$GITHUB_ENV"
|
||||
fi
|
||||
echo "WORK=$RUNNER_TEMP/tmb" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Check out the tag or the branch
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ env.TAG != '' && format('refs/tags/{0}', env.TAG) || '' }}
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
|
||||
- name: Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.14'
|
||||
|
||||
- name: The launcher's build tools and SDL3's video and audio development files
|
||||
run: |
|
||||
sudo apt-get update -q
|
||||
sudo apt-get install -y -q cmake ninja-build g++ pkg-config libx11-dev libxext-dev \
|
||||
libxrandr-dev libxcursor-dev libxi-dev libxss-dev libxtst-dev libxfixes-dev libxkbcommon-dev libwayland-dev \
|
||||
wayland-protocols libdecor-0-dev libegl-dev libgl-dev libgles-dev libpipewire-0.3-dev libpulse-dev \
|
||||
libasound2-dev libudev-dev libdbus-1-dev libibus-1.0-dev
|
||||
|
||||
- name: Cache the downloads (SDL3, ImGui, the font)
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ${{ runner.temp }}/tmb/downloads
|
||||
key: tmb-linux-downloads-${{ hashFiles('tools/make_build_kit.py', 'tools/make_release.py', 'cmake/bozo_engine.json') }}
|
||||
restore-keys: tmb-linux-downloads-
|
||||
|
||||
- name: Make the Linux release (.tar.gz, .sha256)
|
||||
run: |
|
||||
set -eu
|
||||
if [ -n "$TEST_BUILD" ]; then extra="--allow-missing-changelog"; else extra=""; fi
|
||||
python tools/make_release.py --linux --version "$VERSION" --out "$WORK/release" \
|
||||
--downloads "$WORK/downloads" $extra
|
||||
|
||||
- name: Smoke checks (no game data anywhere)
|
||||
run: |
|
||||
set -eu
|
||||
rel="$WORK/release"
|
||||
name="TMB_Recomp-$VERSION-linux.tar.gz"
|
||||
python tools/make_release.py --verify-zip "$rel/$name"
|
||||
(cd "$rel" && sha256sum -c "$name.sha256")
|
||||
t="$WORK/smoke/Jérôme Games"
|
||||
rm -rf "$t" && mkdir -p "$t/user"
|
||||
tar xzf "$rel/$name" -C "$t"
|
||||
app="$t/TMB_Recomp_Bozo"
|
||||
head -c 1048576 /dev/zero > "$t/not_a_disc.iso"
|
||||
if python3 -I -X utf8 "$app/source/tools/tmb_build.py" --check --disc "$t/not_a_disc.iso" > "$t/check.txt" 2>&1; then
|
||||
cat "$t/check.txt"; echo "::error::tmb_build --check accepted a file of zeros"; exit 1
|
||||
fi
|
||||
cat "$t/check.txt"
|
||||
grep -q "is not an ISO9660 disc image" "$t/check.txt"
|
||||
"$app/tmb-launcher" --version
|
||||
if ! PS2X_USER_DIR="$t/user" "$app/tmb-launcher" --self-check "$t/not_a_disc.iso" --report "$t/self-check.txt"; then
|
||||
cat "$t/self-check.txt"; echo "::error::the launcher's self-check failed"; exit 1
|
||||
fi
|
||||
cat "$t/self-check.txt"
|
||||
grep -q "^version $VERSION$" "$t/self-check.txt"
|
||||
readelf -d "$app/tmb-launcher" | grep NEEDED
|
||||
|
||||
- name: Keep the archive (the run's artifact; the build job attaches it to the draft)
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: TMB_Recomp-${{ env.VERSION }}-linux
|
||||
path: |
|
||||
${{ runner.temp }}/tmb/release/TMB_Recomp-${{ env.VERSION }}-linux.tar.gz
|
||||
${{ runner.temp }}/tmb/release/TMB_Recomp-${{ env.VERSION }}-linux.tar.gz.sha256
|
||||
if-no-files-found: error
|
||||
retention-days: 14
|
||||
compression-level: 0
|
||||
|
||||
build:
|
||||
if: github.event_name != 'release'
|
||||
needs: linux
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 150
|
||||
permissions:
|
||||
@@ -80,13 +173,15 @@ jobs:
|
||||
fi
|
||||
echo "WORK=$(cygpath -m "$RUNNER_TEMP")/tmb" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Check out the tag or the branch (and the BozoEngine submodule at its recorded commit)
|
||||
- name: Check out the tag or the branch
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ env.TAG != '' && format('refs/tags/{0}', env.TAG) || '' }}
|
||||
submodules: true
|
||||
persist-credentials: false
|
||||
|
||||
- name: The BozoEngine release cmake/bozo_engine.json pins (SHA-256 checked; the kit reads its library pins)
|
||||
run: cmake -P cmake/bozo_engine_fetch.cmake
|
||||
|
||||
- name: Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
@@ -138,6 +233,12 @@ jobs:
|
||||
python tools/make_build_kit.py --out "$WORK/kit" --msys "$MSYS2_ROOT" --downloads "$WORK/downloads" \
|
||||
--work "$WORK/kit-work" $steps --only manifest
|
||||
|
||||
- name: The Linux release (the linux job's), so the notes and the draft carry it
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: TMB_Recomp-${{ env.VERSION }}-linux
|
||||
path: ${{ runner.temp }}/tmb/release
|
||||
|
||||
- name: Make the release (zip, .sha256, sources zip, notes from CHANGELOG.md)
|
||||
env:
|
||||
MSYS2_ROOT: ${{ steps.msys2.outputs.msys2-location }}
|
||||
@@ -193,6 +294,8 @@ jobs:
|
||||
${{ runner.temp }}/tmb/release/TMB_Recomp-${{ env.VERSION }}.zip.sha256
|
||||
${{ runner.temp }}/tmb/release/TMB_Recomp-${{ env.VERSION }}-bozo-sources.zip
|
||||
${{ runner.temp }}/tmb/release/TMB_Recomp-${{ env.VERSION }}-bozo-sources.zip.sha256
|
||||
${{ runner.temp }}/tmb/release/TMB_Recomp-${{ env.VERSION }}-linux.tar.gz
|
||||
${{ runner.temp }}/tmb/release/TMB_Recomp-${{ env.VERSION }}-linux.tar.gz.sha256
|
||||
${{ runner.temp }}/tmb/release/RELEASE_NOTES.md
|
||||
if-no-files-found: error
|
||||
retention-days: 14
|
||||
|
||||
@@ -17,6 +17,10 @@ SLUS_*
|
||||
*.irx
|
||||
*.IMG
|
||||
|
||||
# The BozoEngine release cmake/bozo_engine.json pins (cmake/bozo_engine_fetch.cmake)
|
||||
/BozoEngine/
|
||||
/.BozoEngine-unpack/
|
||||
|
||||
# Local build trees
|
||||
build/
|
||||
out/
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
[submodule "BozoEngine"]
|
||||
path = BozoEngine
|
||||
url = https://github.com/TheBozos/BozoEngine.git
|
||||
-1
Submodule BozoEngine deleted from b29bc39114.
+69
-1
@@ -7,6 +7,70 @@ under "Unreleased" as they land, then move them under the new version's heading
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.8.1] - 2026-12-03
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Red flashes after retrying a lost level** (reported on Prison Passage in story mode). The level's reload left the
|
||||
loading bar's vblank callback running, and the native 2D drew the last load's full bar over the match's frames. It is
|
||||
now drawn only while the game shows it (as the game's own `informProgressBar` does too).
|
||||
- Linux: closing the game from the launcher sends it one stop signal, not one a frame (a second one could kill the game
|
||||
while it was closing).
|
||||
- The packages no longer carry Python's bytecode cache (`source/tools/__pycache__`), which held the build machine's
|
||||
paths.
|
||||
|
||||
### Added
|
||||
|
||||
- Testing switches: `TMB_KILL_PLAYER=<s>` (player 1's car takes a fatal hit every `<s>` seconds) and
|
||||
`TMB_PLAYER_LIVES=<n>` (player 1's story lives kept at most `n`), to reach a lost level and its retry in a script.
|
||||
|
||||
## [0.8.0] - 2026-12-02
|
||||
|
||||
### Added
|
||||
|
||||
- **A Linux download**, `TMB_Recomp-<version>-linux.tar.gz`: the same launcher for Linux (`tmb-launcher`), the code,
|
||||
the SDL3 and Dear ImGui sources and Real-ESRGAN's Linux build. It builds the game with your system's compiler, Python
|
||||
and FFmpeg; **Prepare the game** names the packages to install for your distribution when one is missing, the Update
|
||||
button installs the next Linux release, and **Make enhanced textures** works as on Windows (Vulkan needed). Saves
|
||||
and settings are in `~/.local/share/tmb_recomp`.
|
||||
- RecompLauncher can install and run the Linux download too (`recomplauncher.json`: `kit/python3`, the system's, for
|
||||
the setup step; `game/tmb` to play).
|
||||
|
||||
### Changed
|
||||
|
||||
- **BozoEngine 0.7.8** (from 0.6.0). The game's sine and cosine (the C runtime's `sinf` and `cosf` the reference
|
||||
build used) are computed the same way on every platform, bit for bit as on Windows, so the Linux build plays exactly
|
||||
as the Windows one: the same game state on every frame of the checked 1P and 4P routes, where it drifted after about
|
||||
90 seconds before. The snow's sway and the 2D rotations use them too. Windows plays as before (every checked frame
|
||||
identical).
|
||||
|
||||
## [0.7.3] - 2026-12-01
|
||||
|
||||
### Added
|
||||
|
||||
- **RecompLauncher support.** Releases carry a `recomplauncher.json`, so [RecompLauncher](https://recomplauncher.com)
|
||||
can install TMB_Recomp, check the disc against the USA dump, prepare the game with the release's own build, start
|
||||
it, show the video settings (display mode, widescreen, frame rate, render scale, anti-aliasing, texture smoothing)
|
||||
on the game's page and back up the memory cards. A game set up there keeps its saves, settings and logs in its
|
||||
`recompdata` folder.
|
||||
- Preparing again without a disc image uses the one the earlier preparation kept in the game folder, so an update can
|
||||
be built after the original image was deleted.
|
||||
|
||||
## [0.7.2] - 2026-11-30
|
||||
|
||||
### Changed
|
||||
|
||||
- **BozoEngine comes from its releases instead of a git submodule.** `cmake/bozo_engine.json` pins a release by
|
||||
version and SHA-256 (0.4.0, the same code as the commit pinned before), and configuring fetches it into
|
||||
`BozoEngine/` (`cmake/bozo_engine_fetch.cmake`, the scheme SoulCaliburIII_Recomp uses). A player's release still
|
||||
ships the engine's source in `source\BozoEngine` and builds offline; `release.ini` now stamps `engine_version`. To
|
||||
work on the engine and TMB together, point `BOZO_ENGINE_DIR` (or `tmb_build.py --engine`) at a BozoEngine checkout.
|
||||
- **BozoEngine 0.6.0** (from 0.4.0). In the window, the sound is held to the real time without clicks (engine PR #164),
|
||||
and a render scale over 1 averages the pixels under each window pixel instead of picking one (#168). The rest
|
||||
(SPU2 output interrupts, the movie library's work-area layout, the disc stream, ReferSemaStatus,
|
||||
sceSifGetOtherData and opt-in library answers for other ports) leaves TMB's runs unchanged: the 1P and 4P replay
|
||||
routes give the same record on every frame.
|
||||
|
||||
## [0.7.1] - 2026-11-30
|
||||
|
||||
### Fixed
|
||||
@@ -284,7 +348,11 @@ The first release. You build the game on your own PC from your own USA disc; not
|
||||
- Technical: built from TMB_Recomp's code and the PS2Recomp fork (`native/renderer`) with the build kit's GCC 16.2,
|
||||
FFmpeg 9.0.2 and Python 3.14; the default mode has no GS, VU or SPU2 emulation and no IOP hardware model.
|
||||
|
||||
[Unreleased]: https://github.com/TheBozos/TMB_Recomp/compare/v0.7.1...HEAD
|
||||
[Unreleased]: https://github.com/TheBozos/TMB_Recomp/compare/v0.8.1...HEAD
|
||||
[0.8.1]: https://github.com/TheBozos/TMB_Recomp/compare/v0.8.0...v0.8.1
|
||||
[0.8.0]: https://github.com/TheBozos/TMB_Recomp/compare/v0.7.3...v0.8.0
|
||||
[0.7.3]: https://github.com/TheBozos/TMB_Recomp/compare/v0.7.2...v0.7.3
|
||||
[0.7.2]: https://github.com/TheBozos/TMB_Recomp/compare/v0.7.1...v0.7.2
|
||||
[0.7.1]: https://github.com/TheBozos/TMB_Recomp/compare/v0.7.0...v0.7.1
|
||||
[0.7.0]: https://github.com/TheBozos/TMB_Recomp/compare/v0.6.0...v0.7.0
|
||||
[0.6.0]: https://github.com/TheBozos/TMB_Recomp/compare/v0.5.0...v0.6.0
|
||||
|
||||
@@ -23,7 +23,7 @@ SOFTWARE.
|
||||
---
|
||||
|
||||
This licence covers TMB_Recomp's own files. It does not cover:
|
||||
- BozoEngine/ (the recompiler and runtime, a separate MIT project): see BozoEngine/LICENSE.
|
||||
- BozoEngine/ (the recompiler and runtime, a separate MIT project, fetched from its releases): see BozoEngine/LICENSE.
|
||||
- Anything from Twisted Metal: Black. No game data, code or art is in this repository or its releases;
|
||||
players build the port from their own disc.
|
||||
- Third-party components with their own licences (SDL3, Dear ImGui, the Exo 2 font, and the build
|
||||
|
||||
@@ -24,7 +24,7 @@ PC services. BozoEngine replaces the PS2Recomp fork completely; the player build
|
||||
> |---|---|
|
||||
> | `SCUS_971.01` | `3ff17f4897552e355d0bb8c3abfa5125fe3ff2ef` |
|
||||
|
||||
## For players (Windows)
|
||||
## For players (Windows and Linux)
|
||||
|
||||
You build the game yourself, on your PC, from **your own disc**: nothing of the game is in the download.
|
||||
|
||||
@@ -50,6 +50,28 @@ remains available for comparison. The steps below describe the native packages.
|
||||
graphics driver is needed. The game then uses them; turn them off there or in F2 → Video → Texture pack. Nothing is
|
||||
downloaded or sent, and the result is yours alone: do not share it.
|
||||
|
||||
**RecompLauncher.** Releases carry a [`recomplauncher.json`](recomplauncher.json), so
|
||||
[RecompLauncher](https://recomplauncher.com) can install TMB_Recomp, check your disc, prepare the game with the same
|
||||
build, show the video settings on the game's page and back up the memory cards. A game set up there keeps its saves,
|
||||
settings and logs in its own `recompdata` folder, not in `%APPDATA%\TMB_Recomp`: copy `mc0` across to bring saves
|
||||
from TMB Launcher. Enhanced textures are made by TMB Launcher only.
|
||||
|
||||
**Linux.** Download `TMB_Recomp-<version>-linux.tar.gz` and check it (`sha256sum`). It holds the same launcher
|
||||
(`tmb-launcher`), our code, the SDL3 and Dear ImGui sources and Real-ESRGAN, but no compiler: the game is built with
|
||||
your system's. Install GCC, CMake, Ninja, pkg-config, Python 3 and the FFmpeg (`libavcodec`, `libavutil`), X11 or
|
||||
Wayland, OpenGL and audio development files; on Debian or Ubuntu:
|
||||
|
||||
```bash
|
||||
sudo apt install build-essential cmake ninja-build pkg-config python3 libavcodec-dev libavutil-dev libx11-dev \
|
||||
libxext-dev libxrandr-dev libxcursor-dev libxi-dev libxss-dev libxtst-dev libxfixes-dev libxkbcommon-dev \
|
||||
libwayland-dev libdecor-0-dev libegl-dev libgl-dev libpipewire-0.3-dev libpulse-dev libasound2-dev libudev-dev
|
||||
```
|
||||
|
||||
On Fedora, Arch or openSUSE, **Prepare the game** names the packages when one is missing. Then `tar xzf` it anywhere
|
||||
with about 10 GB free, run `TMB_Recomp_Bozo/tmb-launcher` and follow steps 4 to 7 above. The disc picker is your
|
||||
desktop's file dialog (xdg-desktop-portal) or zenity. Saves and settings are in `~/.local/share/tmb_recomp`; Update
|
||||
installs the next Linux release. Enhanced textures need a Vulkan driver, as on Windows.
|
||||
|
||||
Requires **Windows 10 version 1903 or newer / Windows 11, an AVX2 and FMA capable CPU, and OpenGL 3.3**.
|
||||
Original heat haze around fire and explosions is enabled by default. `BOZO_HEAT_HAZE=0` disables it for comparisons
|
||||
with the older PC port. Menus and movies use their native timing, independently of the presentation frame rate.
|
||||
@@ -121,7 +143,7 @@ those comparisons from actual native play. [docs/RECOMP_NOTES.md](docs/RECOMP_NO
|
||||
| Every Challenge arena rechecked on BozoEngine | 🔧 |
|
||||
| Every story level to the endings | 🔧 |
|
||||
| Fresh standard-user Windows installation and four physical controllers | 🔧 |
|
||||
| Linux player build validated on the new runtime | ⏳ |
|
||||
| Linux player build: the launcher builds from the disc, plays and updates (Ubuntu 24.04, X11, Mesa) | 🧪 |
|
||||
| Widescreen | ⏳ |
|
||||
|
||||
**Native port**: the shared goal of The Bozos' ports is to draw and play sound directly from the game's own data,
|
||||
@@ -184,7 +206,10 @@ Your USA disc
|
||||
|
||||
The executable retains its symbols, so this port does not need a Ghidra function-map pass.
|
||||
`runtime/tmb_overrides.cpp` contains game-specific bindings; `bozo/` contains the real-time host, headless host and
|
||||
checker. Generic recompiler/runtime work lives in the [BozoEngine](https://github.com/TheBozos/BozoEngine) submodule.
|
||||
checker. Generic recompiler/runtime work lives in [BozoEngine](https://github.com/TheBozos/BozoEngine): TMB builds on
|
||||
one of its releases, pinned by version and SHA-256 in `cmake/bozo_engine.json` and fetched into `BozoEngine/` when
|
||||
configuring (`cmake/bozo_engine_fetch.cmake`; a release's `source\BozoEngine` comes with it, so a player's build stays
|
||||
offline).
|
||||
Its [clean-room specifications and validation](https://github.com/TheBozos/BozoEngine/tree/main/docs) describe the engine.
|
||||
PS2Recomp remains credited in the project's history and available in the v0.3.2 release, but is no longer a dependency.
|
||||
|
||||
@@ -192,8 +217,8 @@ PS2Recomp remains credited in the project's history and available in the v0.3.2
|
||||
|
||||
The player package brings its own build tools. To build from the repository:
|
||||
|
||||
- Windows 10 version 1903 or newer / Windows 11; Windows is the validated player target. Linux portability is not yet
|
||||
validated for this migration.
|
||||
- Windows 10 version 1903 or newer / Windows 11, or a 64-bit Linux with X11 or Wayland (GCC 13 or newer).
|
||||
Windows is the most tested target.
|
||||
- An **AVX2 and FMA capable CPU**, OpenGL 3.3, about 10 GB free for preparation, and your own USA disc.
|
||||
- CMake 3.21+, Ninja, Python 3 and a C++20 compiler. The matching kit's GCC is the validated Windows configuration;
|
||||
MSVC is not supported for this port.
|
||||
@@ -205,10 +230,11 @@ The player package brings its own build tools. To build from the repository:
|
||||
|
||||
### One command, from your disc (Windows)
|
||||
|
||||
Clone the repository with its BozoEngine submodule, then use the same pipeline as the launcher:
|
||||
Clone the repository, then use the same pipeline as the launcher (it fetches the pinned BozoEngine release into
|
||||
`BozoEngine/` the first time; `cmake -P cmake/bozo_engine_fetch.cmake` does it alone):
|
||||
|
||||
```bat
|
||||
git clone --recurse-submodules https://github.com/TheBozos/TMB_Recomp.git
|
||||
git clone https://github.com/TheBozos/TMB_Recomp.git
|
||||
cd TMB_Recomp
|
||||
python tools\tmb_build.py --disc "D:\Discs\Twisted Metal - Black (USA).iso" --out D:\TMB-build --kit D:\tmb_kit_bozo\kit
|
||||
"D:\TMB-build\TMB\Play TMB.cmd"
|
||||
@@ -313,7 +339,8 @@ Follow [docs/RELEASE_CHECKLIST.md](docs/RELEASE_CHECKLIST.md) and include the co
|
||||
Releases are built by `.github/workflows/release.yml` when the owner asks. An ordinary push does not publish one.
|
||||
|
||||
1. Move `CHANGELOG.md`'s Unreleased entries into `## [<version>] - <date>`, update its links, and merge through a PR
|
||||
with green checks. Engine changes must already be public before updating the submodule pin.
|
||||
with green checks. Engine changes must already be in a BozoEngine release before the pin moves: set its version and its
|
||||
`.sha256` in `cmake/bozo_engine.json`.
|
||||
2. Tag that merged commit (`v<version>`) and push the tag, or run the workflow against the already pushed tag.
|
||||
3. The workflow checks the changelog, assembles the pinned kit, makes both player ZIPs and corresponding sources,
|
||||
verifies hashes/contents and runs the bundled-toolchain/launcher checks, then creates a **draft** release.
|
||||
@@ -350,7 +377,8 @@ cmake --build D:/TMB-dev -j 8
|
||||
D:/TMB-dev/tmb.exe --iso "D:/Discs/Twisted Metal - Black (USA).iso"
|
||||
```
|
||||
|
||||
`BOZO_ENGINE_DIR` selects another engine tree. `TMB_WINDOW=OFF` builds headless tools only.
|
||||
`BOZO_ENGINE_DIR` selects another engine tree (a BozoEngine checkout, to work on the engine and TMB together;
|
||||
`tools/tmb_build.py --engine <tree>` likewise); without it the pinned release is used. `TMB_WINDOW=OFF` builds headless tools only.
|
||||
`BOZO_BUILD_TOOLS=OFF` removes the optional zlib-dependent recording/checking tools from a player build.
|
||||
|
||||
### Windows
|
||||
@@ -507,7 +535,7 @@ captures, generated game code and disc data are local-only and never release con
|
||||
|
||||
| Path | Contents |
|
||||
|---|---|
|
||||
| `BozoEngine/` | the native recompiler/runtime submodule (MIT) |
|
||||
| `BozoEngine/` | the native recompiler/runtime (MIT): the release `cmake/bozo_engine.json` pins, fetched, not committed |
|
||||
| `bozo/` | TMB's windowed host, headless host and recorded-run checker |
|
||||
| `cmake/bozo.cmake` | the native game build and generated-code integration |
|
||||
| `recomp/` | game-specific recompiler declarations |
|
||||
|
||||
+7
-4
@@ -16,10 +16,13 @@
|
||||
# The generated code: bozo-recomp with the externals bozo-externals writes from the ELF (the stubs BozoEngine answers),
|
||||
# recomp/tmb_stubs.txt and TMB's override list (tools/tmb_overrides_list.py, from runtime/*.cpp).
|
||||
|
||||
# BozoEngine: the submodule (BozoEngine/, at the commit TMB pins) unless BOZO_ENGINE_DIR names another tree (development).
|
||||
set(BOZO_ENGINE_DIR "" CACHE PATH "BozoEngine's source tree (default: the BozoEngine submodule)")
|
||||
if(NOT BOZO_ENGINE_DIR AND EXISTS "${CMAKE_SOURCE_DIR}/BozoEngine/CMakeLists.txt")
|
||||
set(BOZO_ENGINE_DIR "${CMAKE_SOURCE_DIR}/BozoEngine" CACHE PATH "BozoEngine's source tree (default: the BozoEngine submodule)" FORCE)
|
||||
# BozoEngine: the release cmake/bozo_engine.json pins, fetched into BozoEngine/ (cmake/bozo_engine_fetch.cmake), unless
|
||||
# BOZO_ENGINE_DIR names another tree (development: a BozoEngine checkout).
|
||||
set(BOZO_ENGINE_DIR "" CACHE PATH "BozoEngine's source tree (default: the release cmake/bozo_engine.json pins, in BozoEngine/)")
|
||||
if(NOT BOZO_ENGINE_DIR OR BOZO_ENGINE_DIR STREQUAL "${CMAKE_SOURCE_DIR}/BozoEngine")
|
||||
include("${CMAKE_CURRENT_LIST_DIR}/bozo_engine_fetch.cmake")
|
||||
set(BOZO_ENGINE_DIR "${bozo_engine_tree}")
|
||||
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${CMAKE_CURRENT_LIST_DIR}/bozo_engine.json")
|
||||
endif()
|
||||
set(TMB_ELF "" CACHE FILEPATH "TMB's executable (SCUS_971.01), extracted from the disc")
|
||||
set(TMB_GEN_FILES 32 CACHE STRING "How many .cpp files the generated code is split into")
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"version": "0.7.8",
|
||||
"sha256": "a4c85d057b00bf8fe34a75cba88ef7e30213f4019b287053a88b5a6e7a1095f7"
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
# The BozoEngine release cmake/bozo_engine.json pins, in BozoEngine/ beside cmake/: the release's archive
|
||||
# (https://github.com/TheBozos/BozoEngine/releases), SHA-256 checked, unpacked, and its version and hash written to
|
||||
# BozoEngine/.release; nothing is downloaded while those match the pin (a release's source\BozoEngine comes with it, so
|
||||
# a player's build stays offline). Included by cmake/bozo.cmake and launcher/CMakeLists.txt when they are not given
|
||||
# another tree, run by tools/tmb_build.py in a git checkout and by tools/make_release.py, or on its own:
|
||||
# cmake [-DBOZO_ENGINE_DOWNLOADS=<dir>] -P cmake/bozo_engine_fetch.cmake
|
||||
# BOZO_ENGINE_DOWNLOADS is where the archive goes (default build/). The same scheme as SoulCaliburIII_Recomp's.
|
||||
cmake_minimum_required(VERSION 3.20)
|
||||
get_filename_component(bozo_engine_root "${CMAKE_CURRENT_LIST_DIR}/.." ABSOLUTE)
|
||||
file(READ "${CMAKE_CURRENT_LIST_DIR}/bozo_engine.json" bozo_engine_pin)
|
||||
string(JSON bozo_engine_version GET "${bozo_engine_pin}" version)
|
||||
string(JSON bozo_engine_sha256 GET "${bozo_engine_pin}" sha256)
|
||||
set(bozo_engine_tree "${bozo_engine_root}/BozoEngine")
|
||||
|
||||
set(bozo_engine_want "${bozo_engine_version} ${bozo_engine_sha256}")
|
||||
set(bozo_engine_have "")
|
||||
if(EXISTS "${bozo_engine_tree}/.release")
|
||||
file(READ "${bozo_engine_tree}/.release" bozo_engine_have)
|
||||
string(STRIP "${bozo_engine_have}" bozo_engine_have)
|
||||
elseif(EXISTS "${bozo_engine_tree}")
|
||||
file(GLOB bozo_engine_entries "${bozo_engine_tree}/*" "${bozo_engine_tree}/.*")
|
||||
if(bozo_engine_entries)
|
||||
message(FATAL_ERROR "BozoEngine: ${bozo_engine_tree} is not a pinned release (the old submodule's checkout?): "
|
||||
"move it away (to build on it there: -DBOZO_ENGINE_DIR=<its new place>, or "
|
||||
"tools/tmb_build.py --engine <its new place>)")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
if(NOT bozo_engine_have STREQUAL bozo_engine_want)
|
||||
if(NOT BOZO_ENGINE_DOWNLOADS)
|
||||
set(BOZO_ENGINE_DOWNLOADS "${bozo_engine_root}/build")
|
||||
endif()
|
||||
set(bozo_engine_name "BozoEngine-${bozo_engine_version}")
|
||||
set(bozo_engine_archive "${BOZO_ENGINE_DOWNLOADS}/${bozo_engine_name}.tar.gz")
|
||||
set(bozo_engine_url
|
||||
"https://github.com/TheBozos/BozoEngine/releases/download/v${bozo_engine_version}/${bozo_engine_name}.tar.gz")
|
||||
message(STATUS "BozoEngine ${bozo_engine_version}: ${bozo_engine_url}")
|
||||
file(DOWNLOAD "${bozo_engine_url}" "${bozo_engine_archive}" EXPECTED_HASH SHA256=${bozo_engine_sha256}
|
||||
TLS_VERIFY ON STATUS bozo_engine_status)
|
||||
list(GET bozo_engine_status 0 bozo_engine_code)
|
||||
if(bozo_engine_code)
|
||||
list(GET bozo_engine_status 1 bozo_engine_error)
|
||||
message(FATAL_ERROR "BozoEngine ${bozo_engine_version}: ${bozo_engine_error}")
|
||||
endif()
|
||||
set(bozo_engine_unpack "${bozo_engine_root}/.BozoEngine-unpack")
|
||||
file(REMOVE_RECURSE "${bozo_engine_tree}" "${bozo_engine_unpack}")
|
||||
file(ARCHIVE_EXTRACT INPUT "${bozo_engine_archive}" DESTINATION "${bozo_engine_unpack}")
|
||||
# Its files dated now: unpacked with the archive's own dates (the release's, older than objects built since), a
|
||||
# build made on the last release kept objects compiled against the old headers after a pin bump (Shinobido 0.7.0 ->
|
||||
# 0.7.3: two files built on the old renderer.h, objects and the HUD missing from the picture).
|
||||
file(GLOB_RECURSE bozo_engine_files LIST_DIRECTORIES false "${bozo_engine_unpack}/*")
|
||||
file(TOUCH_NOCREATE ${bozo_engine_files})
|
||||
file(WRITE "${bozo_engine_unpack}/${bozo_engine_name}/.release" "${bozo_engine_want}\n")
|
||||
file(RENAME "${bozo_engine_unpack}/${bozo_engine_name}" "${bozo_engine_tree}")
|
||||
file(REMOVE_RECURSE "${bozo_engine_unpack}")
|
||||
endif()
|
||||
+1
-1
@@ -250,7 +250,7 @@ no upload tag at the audited calls; game texture-manager bookkeeping and other p
|
||||
[`NATIVE_GRAPHICS_SERVICES.md`](NATIVE_GRAPHICS_SERVICES.md) records removal of the engine GS device/GIF
|
||||
reader state and TMB's old packet-based flare adapter, independent/combined tests and unsupported readback limits.
|
||||
|
||||
- One submodule: `BozoEngine`. No PS2Recomp gitlink, legacy CMake branch, import fallback, IOP recompilation or old runner scripts.
|
||||
- No submodule: BozoEngine is the release `cmake/bozo_engine.json` pins (fetched into `BozoEngine/`). No PS2Recomp gitlink, legacy CMake branch, import fallback, IOP recompilation or old runner scripts.
|
||||
- `tools/tmb_build.py`: verify → extract → configure → native tools → recompile → packs → compile → stage.
|
||||
- `scripts/build_runtime.sh` and the other retained shortcuts use that same pipeline.
|
||||
- Native frame pacing is unconditional. A legacy `TMB_NATIVE_FRAMES=0` environment setting cannot bypass it.
|
||||
|
||||
@@ -3,6 +3,72 @@
|
||||
Use a scratch `PS2X_USER_DIR` for every automated run. Keep game data and generated code out of Git and release ZIPs.
|
||||
Publication is separate from a successful build; this checklist records what was actually verified.
|
||||
|
||||
v0.8.0 was published on 2026-12-02 after tagged CI and the owner's release request. Its draft assets were checked
|
||||
locally before publication:
|
||||
- both player ZIPs pass the SHA-256 and package audits, carry an identical 8,028-file payload, and are stamped with
|
||||
the release commit and engine version `0.7.8`; the sources ZIP matches its hash; both carry the commit's
|
||||
`recomplauncher.json`;
|
||||
- the Linux archive (`TMB_Recomp-0.8.0-linux.tar.gz`, new) matches its hash and passes `verify_tar`. Its `source/`
|
||||
is the zips' but for line ends; `tmb-launcher`, `kit/python3` and Real-ESRGAN are executable;
|
||||
- the release's engine change (BozoEngine 0.7.8, #129) was checked before tagging: headless 1P (9,500 frames) and 4P
|
||||
(8,500 frames) Windows records are identical to engine 0.6.0's, and the Linux build's game state equals Windows' on
|
||||
every frame (the draw hash differs by GCC's fused multiply-adds only);
|
||||
- Windows: a fresh install in a path with spaces and accents was built offline from the disc with only the bundled
|
||||
kit, stopped and resumed, played and exited normally, with menu/movie timing passing; the v0.7.3 install was
|
||||
updated by its own updater, rebuilt and played; the v0.3.2 updater accepted the migration ZIP; player data was kept
|
||||
in both update cases; Enhanced textures made 2,190 replacements;
|
||||
- Linux (Docker, Ubuntu 24.04, Mesa llvmpipe, Xvfb): the archive unpacked into a path with spaces and accents passes
|
||||
the launcher's self-check; the launcher's self-test prepared the game from the disc (stopped and resumed) in 3:49
|
||||
and played 40 s, but reported a failure when closing it: the game was killed by a repeated close signal (exit 143),
|
||||
a self-test-only problem fixed after the release (#131, checked on this archive: exit 0). RecompLauncher's prepare
|
||||
through `kit/python3` built the game in 160 s ("Ready to play"), said "Already built" when run again, and its start
|
||||
played 600 frames with the cards in `recompdata`;
|
||||
- known leftover: `source/tools/__pycache__/tmb_build.cpython-314.pyc` is in every package, as in earlier releases
|
||||
(removed for the next one, #131).
|
||||
|
||||
v0.7.3 was published on 2026-12-01 after tagged CI and the owner's release request. Its draft assets were checked
|
||||
locally before publication:
|
||||
- both player ZIPs pass the SHA-256 and package audits, carry an identical 8,011-file payload, and are stamped with
|
||||
the release commit and engine version `0.6.0`; the sources ZIP matches its hash;
|
||||
- the release's change (RecompLauncher support, #125): both ZIPs carry the commit's `recomplauncher.json` at their
|
||||
top. On the `-bozo.zip`, unpacked into a path with accents, RecompLauncher's prepare and start (run as its
|
||||
`lib.rs` does, with DC's `rl_sim.py`) built the game in 158 s ending "Ready to play", said "Already built" when run
|
||||
again, played 600 frames hidden and muted at 59.7 frames/s with the cards and logs in `recompdata`, and prepared
|
||||
again from the kept `disc.iso` without the player's image;
|
||||
- a fresh install in a path with spaces and accents was built offline from the disc with only the bundled kit. The
|
||||
build was stopped and resumed, then the game played and exited normally, with menu/movie timing passing;
|
||||
- the v0.7.1 install was updated by its own updater, rebuilt and played; the v0.3.2 updater accepted the migration
|
||||
ZIP. Player data was kept in both update cases;
|
||||
- on the fresh install, the launcher's Enhanced textures made 2,181 replacements.
|
||||
|
||||
v0.7.2 was published on 2026-11-30 after tagged CI and the owner's release request. Its draft assets were checked
|
||||
locally before publication:
|
||||
- both player ZIPs pass the SHA-256 and package audits, carry an identical 8,009-file payload, and are stamped with
|
||||
the release commit and engine version `0.6.0`; the sources ZIP matches its hash and holds the pinned engine release
|
||||
(`source/BozoEngine/.release`);
|
||||
- the release's changes (engine fetched from a pinned BozoEngine release, #121; BozoEngine 0.6.0, #122) were checked
|
||||
before tagging: a clean checkout builds with no submodule, and headless 1P (9,500 frames) and 4P (8,500 frames)
|
||||
records match the previous engine on every field;
|
||||
- a fresh install in a path with spaces and accents was built offline from the disc with only the bundled kit. The
|
||||
build was stopped and resumed, then the game played and exited normally, with menu/movie timing passing;
|
||||
- the v0.7.1 install was updated by its own updater, rebuilt and played; the v0.3.2 updater accepted the migration
|
||||
ZIP. Player data was kept in both update cases;
|
||||
- on the fresh install, the launcher's Enhanced textures made 2,191 replacements.
|
||||
|
||||
v0.7.1 was published on 2026-11-30 after tagged CI and the owner's release request. Its draft assets were checked
|
||||
locally before publication:
|
||||
- both player ZIPs pass the SHA-256 and package audits, carry an identical 8,003-file payload, and are stamped with
|
||||
the release commit and engine `b29bc39`; the sources ZIP matches its hash;
|
||||
- the release's fix (source and kit file times settled before configuring, #118) was checked end to end: the v0.7.0
|
||||
player ZIP with every file dated 3 h ahead loops ninja ("still dirty after 100 tries") as shipped and passes
|
||||
Prepare's tools step with the fix;
|
||||
- a fresh install in a path with spaces and accents was built offline from the disc with only the bundled kit. The
|
||||
build was stopped and resumed, then the game played and exited normally, with menu/movie timing passing (a first
|
||||
run failed movie 2 at 28.3 pictures/s while another port's run shared the bench; the rerun passed);
|
||||
- the v0.7.0 install was updated by its own updater, rebuilt and played; the v0.3.2 updater accepted the migration
|
||||
ZIP. Player data was kept in both update cases;
|
||||
- on the fresh install, the launcher's Enhanced textures made 2,186 replacements.
|
||||
|
||||
v0.7.0 was published on 2026-11-27 after tagged CI and the owner's release request. Its draft assets were checked
|
||||
locally before publication:
|
||||
- both player ZIPs pass the SHA-256 and package audits, carry an identical 8,003-file payload, and are stamped with
|
||||
|
||||
+43
-28
@@ -4,31 +4,34 @@ project(TMB_Launcher LANGUAGES C CXX)
|
||||
# No C++ modules are used; keep GCC's module mapper out of relocatable kits with spaced/non-ASCII paths.
|
||||
set(CMAKE_CXX_SCAN_FOR_MODULES OFF)
|
||||
|
||||
# TMB Launcher.exe: what a player double-clicks. It checks their disc image, runs tools/tmb_build.py with the build kit
|
||||
# (kit\python), shows its progress, and starts the game. Its own small project (the game's CMake needs the disc): SDL3
|
||||
# and Dear ImGui at the releases BozoEngine pins (its runtime/CMakeLists.txt: the same archives and SHA-256), ImGui's own
|
||||
# SDL3 and OpenGL 3 backends, BozoEngine's PNG writer (the selftest's screenshots); built static, a GUI-subsystem exe
|
||||
# that needs no DLL. Windows only.
|
||||
# TMB Launcher.exe (tmb-launcher on Linux): what a player double-clicks. It checks their disc image, runs
|
||||
# tools/tmb_build.py with the build kit's Python (the system's python3 on Linux), shows its progress, and starts the
|
||||
# game. Its own small project (the game's CMake needs the disc): SDL3 and Dear ImGui at the releases BozoEngine pins
|
||||
# (its runtime/CMakeLists.txt: the same archives and SHA-256), ImGui's own SDL3 and OpenGL 3 backends, BozoEngine's PNG
|
||||
# writer (the selftest's screenshots). On Windows a static GUI-subsystem exe that needs no DLL; on Linux libstdc++ and
|
||||
# libgcc linked in, libcurl loaded when the update check runs.
|
||||
#
|
||||
# cmake -S launcher -B build/launcher -G Ninja -DCMAKE_BUILD_TYPE=Release
|
||||
# cmake --build build/launcher -> build/launcher/TMB Launcher.exe
|
||||
# cmake --build build/launcher -> build/launcher/TMB Launcher.exe, or build/launcher/tmb-launcher
|
||||
#
|
||||
# Offline (the build kit): -DFETCHCONTENT_SOURCE_DIR_SDL3=<kit>/deps/sdl3-src -DFETCHCONTENT_SOURCE_DIR_IMGUI=<kit>/deps/
|
||||
# imgui-src and -DLAUNCHER_FONT_DIR=<dir with Exo2[wght].ttf and OFL.txt>.
|
||||
|
||||
if(NOT WIN32)
|
||||
message(FATAL_ERROR "The launcher is Windows only (Linux players run tools/tmb_build.py).")
|
||||
endif()
|
||||
if(NOT CMAKE_BUILD_TYPE)
|
||||
set(CMAKE_BUILD_TYPE Release CACHE STRING "" FORCE)
|
||||
endif()
|
||||
set(CMAKE_CXX_STANDARD 20)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
|
||||
# BozoEngine's tree (the submodule beside launcher/): its PNG writer only.
|
||||
set(LAUNCHER_BOZO_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../BozoEngine" CACHE PATH "BozoEngine's source tree")
|
||||
# BozoEngine's tree (default: the release cmake/bozo_engine.json pins, in BozoEngine/ beside launcher/): its PNG writer
|
||||
# only.
|
||||
set(LAUNCHER_BOZO_DIR "" CACHE PATH "BozoEngine's source tree (default: the pinned release, in BozoEngine/)")
|
||||
if(NOT LAUNCHER_BOZO_DIR)
|
||||
include("${CMAKE_CURRENT_SOURCE_DIR}/../cmake/bozo_engine_fetch.cmake")
|
||||
set(LAUNCHER_BOZO_DIR "${bozo_engine_tree}")
|
||||
endif()
|
||||
if(NOT EXISTS "${LAUNCHER_BOZO_DIR}/runtime/app/png.cpp")
|
||||
message(FATAL_ERROR "No BozoEngine at ${LAUNCHER_BOZO_DIR} (git submodule update --init BozoEngine)")
|
||||
message(FATAL_ERROR "No BozoEngine at ${LAUNCHER_BOZO_DIR}")
|
||||
endif()
|
||||
|
||||
include(FetchContent)
|
||||
@@ -105,23 +108,35 @@ if(LAUNCHER_VERSION MATCHES "^v?([0-9]+)[.]([0-9]+)[.]([0-9]+)")
|
||||
endif()
|
||||
list(JOIN LAUNCHER_VERSION_NUMBERS "," LAUNCHER_FILEVERSION)
|
||||
|
||||
set(LAUNCHER_ICON "${_icon}")
|
||||
set(LAUNCHER_MANIFEST "${CMAKE_CURRENT_SOURCE_DIR}/launcher.manifest")
|
||||
set(LAUNCHER_EXO2 "${_font_dir}/exo2.ttf")
|
||||
set(LAUNCHER_OFL "${_font_dir}/OFL.txt")
|
||||
configure_file(launcher.rc.in "${CMAKE_BINARY_DIR}/launcher.rc" @ONLY)
|
||||
set_source_files_properties("${CMAKE_BINARY_DIR}/launcher.rc" PROPERTIES OBJECT_DEPENDS "${_icon};${LAUNCHER_EXO2};${LAUNCHER_MANIFEST}")
|
||||
enable_language(RC)
|
||||
set(LAUNCHER_SOURCES src/main.cpp src/ui.cpp src/window.cpp src/build_model.cpp src/config.cpp
|
||||
"${LAUNCHER_BOZO_DIR}/runtime/app/png.cpp")
|
||||
|
||||
add_executable(tmb_launcher WIN32
|
||||
src/main.cpp src/ui.cpp src/window.cpp src/build_model.cpp src/config.cpp src/platform_win.cpp
|
||||
"${LAUNCHER_BOZO_DIR}/runtime/app/png.cpp"
|
||||
"${CMAKE_BINARY_DIR}/launcher.rc")
|
||||
set_target_properties(tmb_launcher PROPERTIES OUTPUT_NAME "TMB Launcher")
|
||||
target_include_directories(tmb_launcher PRIVATE "${LAUNCHER_BOZO_DIR}/runtime/include")
|
||||
target_link_libraries(tmb_launcher PRIVATE launcher_imgui comdlg32 shell32 ole32 winhttp)
|
||||
target_compile_definitions(tmb_launcher PRIVATE TMB_VERSION="${LAUNCHER_VERSION}" TMB_COMMIT="${LAUNCHER_COMMIT}")
|
||||
if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
|
||||
# No DLL besides Windows' own: libstdc++, libgcc and winpthread linked in; no debug information.
|
||||
target_link_options(tmb_launcher PRIVATE -static -s)
|
||||
if(WIN32)
|
||||
set(LAUNCHER_ICON "${_icon}")
|
||||
set(LAUNCHER_MANIFEST "${CMAKE_CURRENT_SOURCE_DIR}/launcher.manifest")
|
||||
configure_file(launcher.rc.in "${CMAKE_BINARY_DIR}/launcher.rc" @ONLY)
|
||||
set_source_files_properties("${CMAKE_BINARY_DIR}/launcher.rc" PROPERTIES OBJECT_DEPENDS "${_icon};${LAUNCHER_EXO2};${LAUNCHER_MANIFEST}")
|
||||
enable_language(RC)
|
||||
|
||||
add_executable(tmb_launcher WIN32 ${LAUNCHER_SOURCES} src/platform_win.cpp "${CMAKE_BINARY_DIR}/launcher.rc")
|
||||
set_target_properties(tmb_launcher PROPERTIES OUTPUT_NAME "TMB Launcher")
|
||||
target_link_libraries(tmb_launcher PRIVATE launcher_imgui comdlg32 shell32 ole32 winhttp)
|
||||
if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
|
||||
# No DLL besides Windows' own: libstdc++, libgcc and winpthread linked in; no debug information.
|
||||
target_link_options(tmb_launcher PRIVATE -static -s)
|
||||
endif()
|
||||
else()
|
||||
# The font and its licence assembled into the executable (.incbin), read back by plat::resource.
|
||||
add_executable(tmb_launcher ${LAUNCHER_SOURCES} src/platform_linux.cpp)
|
||||
set_target_properties(tmb_launcher PROPERTIES OUTPUT_NAME "tmb-launcher")
|
||||
set_source_files_properties(src/platform_linux.cpp PROPERTIES
|
||||
COMPILE_DEFINITIONS "TMB_EXO2_FILE=\"${LAUNCHER_EXO2}\";TMB_OFL_FILE=\"${LAUNCHER_OFL}\""
|
||||
OBJECT_DEPENDS "${LAUNCHER_EXO2};${LAUNCHER_OFL}")
|
||||
find_package(Threads REQUIRED)
|
||||
target_link_libraries(tmb_launcher PRIVATE launcher_imgui Threads::Threads ${CMAKE_DL_LIBS})
|
||||
target_link_options(tmb_launcher PRIVATE -static-libstdc++ -static-libgcc -s)
|
||||
endif()
|
||||
target_include_directories(tmb_launcher PRIVATE "${LAUNCHER_BOZO_DIR}/runtime/include")
|
||||
target_compile_definitions(tmb_launcher PRIVATE TMB_VERSION="${LAUNCHER_VERSION}" TMB_COMMIT="${LAUNCHER_COMMIT}")
|
||||
+49
-13
@@ -4,13 +4,15 @@
|
||||
// SDL3 and OpenGL 3 backends; window.h).
|
||||
//
|
||||
// The release folder it expects (its own folder, or --release <dir>):
|
||||
// TMB Launcher.exe
|
||||
// TMB Launcher.exe (tmb-launcher on Linux)
|
||||
// source\ the TMB_Recomp code (tools\tmb_build.py, BozoEngine\...)
|
||||
// kit\ the build kit (kit\python\python.exe, the compiler...)
|
||||
// kit\ the build kit (kit\python\python.exe, the compiler...); on Linux only kit_manifest.json and deps\, the
|
||||
// system's python3 and compiler doing the rest
|
||||
// build\ tmb_build's work folder (made here)
|
||||
// game\ the game folder the build stages (made here): tmb.exe, SCUS_971.01, disc.iso, the packs
|
||||
// The player's settings: launcher.ini in the runner's user folder (%APPDATA%\TMB_Recomp, or PS2X_USER_DIR), next to
|
||||
// the game's video.ini, which the Settings tab writes in the runner's format.
|
||||
// game\ the game folder the build stages (made here): tmb.exe (tmb on Linux), SCUS_971.01, disc.iso, the packs
|
||||
// The player's settings: launcher.ini in the runner's user folder (%APPDATA%\TMB_Recomp,
|
||||
// ~/.local/share/tmb_recomp on Linux, or PS2X_USER_DIR), next to the game's video.ini, which the Settings tab
|
||||
// writes in the runner's format.
|
||||
//
|
||||
// --selftest <iso> --shots <dir>: the whole flow without a hand on it, a screenshot of each screen (see selftest()).
|
||||
|
||||
@@ -60,7 +62,13 @@ static const char *kReleasePagePrefix = "https://github.com/TheBozos/TMB_Recomp/
|
||||
// BozoEngine: the release's other zip, TMB_Recomp-<version>.zip, is the fork build's), the address made here from the
|
||||
// tag like the page's, never one read from the API's response.
|
||||
static const char *kReleaseDownloadPrefix = "https://github.com/TheBozos/TMB_Recomp/releases/download/";
|
||||
#ifdef _WIN32
|
||||
static std::string releaseZipName(const std::string &version) { return "TMB_Recomp-" + version + "-bozo.zip"; }
|
||||
static const wchar_t *kGameExeName = L"tmb.exe";
|
||||
#else
|
||||
static std::string releaseZipName(const std::string &version) { return "TMB_Recomp-" + version + "-linux.tar.gz"; }
|
||||
static const wchar_t *kGameExeName = L"tmb";
|
||||
#endif
|
||||
|
||||
// ---- language ----
|
||||
|
||||
@@ -353,6 +361,7 @@ struct App
|
||||
Phase phase = Phase::Welcome;
|
||||
Tab tab = Tab::Play;
|
||||
std::string missingPart; // Incomplete: what is not there
|
||||
bool missingPython = false; // Linux: no python3 on the PATH
|
||||
|
||||
// The disc check (tmb_build.py --check).
|
||||
plat::Process checker;
|
||||
@@ -435,12 +444,16 @@ struct App
|
||||
p.release = plat::str(r);
|
||||
p.source = plat::str(r / L"source");
|
||||
p.kit = plat::str(r / L"kit");
|
||||
#ifdef _WIN32
|
||||
p.python = plat::str(r / L"kit" / L"python" / L"python.exe");
|
||||
#else
|
||||
p.python = plat::findProgram("python3");
|
||||
#endif
|
||||
p.script = plat::str(r / L"source" / L"tools" / L"tmb_build.py");
|
||||
p.buildOut = plat::str(r / L"build");
|
||||
p.buildLogs = plat::str(r / L"build" / L"logs");
|
||||
p.game = plat::str(r / L"game");
|
||||
p.gameExe = plat::str(r / L"game" / L"tmb.exe");
|
||||
p.gameExe = plat::str(r / L"game" / kGameExeName);
|
||||
p.elf = plat::str(r / L"game" / L"SCUS_971.01");
|
||||
p.iso = plat::str(r / L"game" / L"disc.iso");
|
||||
p.releaseIni = plat::str(r / L"source" / L"release.ini");
|
||||
@@ -457,9 +470,18 @@ struct App
|
||||
video.load(p.videoIni);
|
||||
|
||||
if (!exists(p.script))
|
||||
missingPart = "source\\tools\\tmb_build.py";
|
||||
missingPart = plat::str(fs::path(L"source") / L"tools" / L"tmb_build.py");
|
||||
#ifdef _WIN32
|
||||
else if (!exists(p.python) || !exists(plat::str(r / L"kit" / L"kit_manifest.json")))
|
||||
missingPart = "kit\\";
|
||||
#else
|
||||
else if (!exists(plat::str(r / L"kit" / L"kit_manifest.json")))
|
||||
#endif
|
||||
missingPart = plat::str(fs::path(L"kit") / L"");
|
||||
else if (p.python.empty())
|
||||
{
|
||||
missingPart = "python3";
|
||||
missingPython = true;
|
||||
}
|
||||
phase = !missingPart.empty() ? Phase::Incomplete : cfg.disc.empty() ? Phase::Welcome : Phase::Ready;
|
||||
readStamps();
|
||||
cleanUpdateLeftovers();
|
||||
@@ -658,7 +680,12 @@ struct App
|
||||
std::string packDir() const { return plat::str(plat::path(p.user) / L"texture_pack"); }
|
||||
bool hasRealEsrgan() const
|
||||
{
|
||||
return exists(plat::str(plat::path(p.kit) / L"realesrgan" / L"realesrgan-ncnn-vulkan.exe")) &&
|
||||
#ifdef _WIN32
|
||||
const wchar_t *program = L"realesrgan-ncnn-vulkan.exe";
|
||||
#else
|
||||
const wchar_t *program = L"realesrgan-ncnn-vulkan";
|
||||
#endif
|
||||
return exists(plat::str(plat::path(p.kit) / L"realesrgan" / program)) &&
|
||||
exists(plat::str(plat::path(p.source) / L"tools" / L"tmb_texture_enhance.py"));
|
||||
}
|
||||
void countPack()
|
||||
@@ -1624,9 +1651,14 @@ static void drawIncomplete(App &app)
|
||||
{
|
||||
heading(L("Some files are missing", "Des fichiers manquent"), ui::color::early);
|
||||
gap(4);
|
||||
std::string text = std::string(L("The launcher did not find ", "Le lanceur ne trouve pas ")) + app.missingPart +
|
||||
L(" next to it. Unzip the whole download again, keeping its folders together.",
|
||||
" à côté de lui. Décompressez à nouveau tout le téléchargement, en gardant ses dossiers ensemble.");
|
||||
std::string text = app.missingPython
|
||||
? std::string(L("Python 3 is not installed. Install your distribution's python3 package, then start "
|
||||
"the launcher again.",
|
||||
"Python 3 n'est pas installé. Installez le paquet python3 de votre distribution, puis "
|
||||
"relancez le lanceur."))
|
||||
: std::string(L("The launcher did not find ", "Le lanceur ne trouve pas ")) + app.missingPart +
|
||||
L(" next to it. Unzip the whole download again, keeping its folders together.",
|
||||
" à côté de lui. Décompressez à nouveau tout le téléchargement, en gardant ses dossiers ensemble.");
|
||||
ui::textWrapped(text.c_str(), 19, ui::color::ink);
|
||||
ui::text(app.p.release.c_str(), 15, ui::color::inkFaint);
|
||||
}
|
||||
@@ -2178,7 +2210,7 @@ static int selfCheck(const std::string &release, const std::string &file, const
|
||||
}
|
||||
if (released && app.sourceVersion != kVersion)
|
||||
{
|
||||
say("FAIL source\\release.ini says " + app.sourceVersion + ", the launcher " + kVersion);
|
||||
say("FAIL " + plat::str(fs::path(L"source") / L"release.ini") + " says " + app.sourceVersion + ", the launcher " + kVersion);
|
||||
ok = false;
|
||||
}
|
||||
if (app.missingPart.empty())
|
||||
@@ -2316,7 +2348,11 @@ int main(int argc, char **argv)
|
||||
test.crashSeconds = crashSeconds;
|
||||
test.screensOnly = screensOnly;
|
||||
test.enhanceOnly = enhanceOnly;
|
||||
#ifdef _WIN32
|
||||
test.log = _wfopen((plat::path(test.shots) / L"selftest.log").c_str(), L"w");
|
||||
#else
|
||||
test.log = std::fopen((plat::path(test.shots) / "selftest.log").c_str(), "w");
|
||||
#endif
|
||||
test.t0 = plat::now();
|
||||
test.say("release %s, user folder %s", app.p.release, app.p.user);
|
||||
test.build();
|
||||
|
||||
+16
-11
@@ -1,7 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
// The launcher's operating-system layer (platform_win.cpp): everything that needs <windows.h>, kept out of the
|
||||
// ImGui and SDL translation units. Strings are UTF-8.
|
||||
// The launcher's operating-system layer (platform_win.cpp, platform_linux.cpp): everything that needs <windows.h> or
|
||||
// POSIX, kept out of the ImGui translation units. Strings are UTF-8.
|
||||
|
||||
#include <atomic>
|
||||
#include <cstddef>
|
||||
@@ -22,26 +22,30 @@ namespace plat
|
||||
std::string exeDirectory();
|
||||
// The command line's arguments (without the program), UTF-8.
|
||||
std::vector<std::string> arguments();
|
||||
// The runner's user folder: PS2X_USER_DIR, else %APPDATA%\TMB_Recomp (created).
|
||||
// The runner's user folder: PS2X_USER_DIR, else %APPDATA%\TMB_Recomp on Windows and
|
||||
// $XDG_DATA_HOME/tmb_recomp (~/.local/share/...) on Linux, as the game resolves it (created).
|
||||
std::string userDirectory();
|
||||
std::string getEnv(const char *name);
|
||||
void setEnv(const char *name, const std::string &value);
|
||||
// "fr" when Windows' display language is French, else "en".
|
||||
// "fr" when the system's display language is French, else "en".
|
||||
std::string systemLanguage();
|
||||
// A program's full path, searched on the PATH; "" when absent.
|
||||
std::string findProgram(const std::string &name);
|
||||
|
||||
// The native Open dialog for a disc image; "" when cancelled.
|
||||
// The native Open dialog for a disc image (on Linux the desktop portal or zenity); "" when cancelled.
|
||||
std::string pickDiscImage(void *ownerWindow, const std::string &title, const std::string &filterName,
|
||||
const std::string &allFilesName);
|
||||
// Opens a file, folder or URL as Explorer would.
|
||||
// Opens a file, folder or URL as Explorer (xdg-open) would.
|
||||
void open(const std::string &target);
|
||||
void showInFolder(const std::string &file);
|
||||
|
||||
// A resource of the launcher's exe (RCDATA), or nullptr.
|
||||
// A resource of the launcher's exe (RCDATA on Windows, embedded at build time on Linux), or nullptr.
|
||||
const void *resource(const char *name, size_t &size);
|
||||
|
||||
// A child process. With output: stdout and stderr through one pipe, read line by line by a thread; started with
|
||||
// CREATE_NO_WINDOW and in a job object, so kill() ends it and everything it started (and so does the launcher
|
||||
// exiting). Without output: a plain GUI process (the game), not tied to the launcher.
|
||||
// CREATE_NO_WINDOW and in a job object on Windows, in its own process group on Linux, so kill() ends it and
|
||||
// everything it started (and so does the launcher exiting). Without output: a plain GUI process (the game), not
|
||||
// tied to the launcher.
|
||||
class Process
|
||||
{
|
||||
public:
|
||||
@@ -60,7 +64,7 @@ namespace plat
|
||||
std::vector<std::string> takeLines();
|
||||
// Ends the process (and with output, its whole tree).
|
||||
void kill();
|
||||
// Asks the process's top-level windows to close (WM_CLOSE), as the window's X would.
|
||||
// Asks the process's top-level windows to close (WM_CLOSE; SIGTERM on Linux), as the window's X would.
|
||||
void requestClose();
|
||||
// Waits until its output pipe is drained (after it exited).
|
||||
void drain(int timeoutMs);
|
||||
@@ -76,7 +80,8 @@ namespace plat
|
||||
std::vector<std::pair<std::string, uint64_t>> listFiles(const std::string &folder, const std::string &suffix);
|
||||
uint64_t freeBytes(const std::string &folder);
|
||||
|
||||
// An HTTP(S) GET through WinHTTP (the system's proxy settings and certificate store; nothing else linked): the
|
||||
// An HTTP(S) GET through WinHTTP (the system's proxy settings and certificate store; nothing else linked), or the
|
||||
// system's libcurl on Linux (loaded when first used, so the launcher starts without it): the
|
||||
// body (at most maxBytes) and the status code. False with error set when the server could not be reached.
|
||||
// Blocking, with short timeouts: call it from a thread.
|
||||
bool httpGet(const std::string &url, const std::string &userAgent, std::string &body, long &status,
|
||||
|
||||
@@ -0,0 +1,795 @@
|
||||
// The launcher's Linux layer (platform.h).
|
||||
|
||||
#include "platform.h"
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <cerrno>
|
||||
#include <chrono>
|
||||
#include <climits>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <deque>
|
||||
#include <fstream>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
#include <type_traits>
|
||||
|
||||
#include <dlfcn.h>
|
||||
#include <fcntl.h>
|
||||
#include <poll.h>
|
||||
#include <signal.h>
|
||||
#include <sys/prctl.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/statvfs.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
|
||||
extern "C"
|
||||
{
|
||||
extern const unsigned char tmb_res_exo2[], tmb_res_exo2_end[];
|
||||
extern const unsigned char tmb_res_ofl[], tmb_res_ofl_end[];
|
||||
}
|
||||
|
||||
#define TMB_INCBIN(symbol, file) \
|
||||
asm(".section .rodata\n.global " #symbol "\n.balign 16\n" #symbol ":\n.incbin \"" file "\"\n.global " #symbol \
|
||||
"_end\n" #symbol "_end:\n.byte 0\n.previous\n")
|
||||
TMB_INCBIN(tmb_res_exo2, TMB_EXO2_FILE);
|
||||
TMB_INCBIN(tmb_res_ofl, TMB_OFL_FILE);
|
||||
|
||||
namespace plat
|
||||
{
|
||||
namespace
|
||||
{
|
||||
std::string readLink(const char *link)
|
||||
{
|
||||
std::string buffer(PATH_MAX, '\0');
|
||||
for (;;)
|
||||
{
|
||||
const ssize_t n = readlink(link, buffer.data(), buffer.size());
|
||||
if (n < 0)
|
||||
return {};
|
||||
if (static_cast<size_t>(n) < buffer.size())
|
||||
{
|
||||
buffer.resize(static_cast<size_t>(n));
|
||||
return buffer;
|
||||
}
|
||||
buffer.resize(buffer.size() * 2);
|
||||
}
|
||||
}
|
||||
|
||||
const std::string g_exePath = readLink("/proc/self/exe");
|
||||
|
||||
std::string localeLanguage()
|
||||
{
|
||||
for (const char *name : {"LC_ALL", "LC_MESSAGES", "LANG"})
|
||||
if (const char *v = std::getenv(name); v && *v)
|
||||
return std::string(v).substr(0, 2);
|
||||
return "en";
|
||||
}
|
||||
}
|
||||
|
||||
std::wstring widen(const std::string &utf8)
|
||||
{
|
||||
std::wstring out;
|
||||
for (size_t i = 0; i < utf8.size();)
|
||||
{
|
||||
const unsigned char c = static_cast<unsigned char>(utf8[i]);
|
||||
const int extra = c < 0x80 ? 0 : (c >> 5) == 6 ? 1 : (c >> 4) == 14 ? 2 : (c >> 3) == 30 ? 3 : -1;
|
||||
if (extra < 0 || i + extra >= utf8.size() + (extra == 0 ? 1 : 0))
|
||||
{
|
||||
out.push_back(0xFFFD);
|
||||
++i;
|
||||
continue;
|
||||
}
|
||||
char32_t code = extra == 0 ? c : c & (0x3F >> extra);
|
||||
bool valid = true;
|
||||
for (int k = 1; k <= extra; ++k)
|
||||
{
|
||||
const unsigned char d = static_cast<unsigned char>(utf8[i + k]);
|
||||
valid = valid && (d >> 6) == 2;
|
||||
code = (code << 6) | (d & 0x3F);
|
||||
}
|
||||
out.push_back(valid ? static_cast<wchar_t>(code) : 0xFFFD);
|
||||
i += valid ? extra + 1 : 1;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string narrow(const std::wstring &wide)
|
||||
{
|
||||
std::string out;
|
||||
for (const wchar_t w : wide)
|
||||
{
|
||||
const char32_t c = static_cast<char32_t>(w);
|
||||
if (c < 0x80)
|
||||
out.push_back(static_cast<char>(c));
|
||||
else if (c < 0x800)
|
||||
out += {static_cast<char>(0xC0 | (c >> 6)), static_cast<char>(0x80 | (c & 0x3F))};
|
||||
else if (c < 0x10000)
|
||||
out += {static_cast<char>(0xE0 | (c >> 12)), static_cast<char>(0x80 | ((c >> 6) & 0x3F)),
|
||||
static_cast<char>(0x80 | (c & 0x3F))};
|
||||
else
|
||||
out += {static_cast<char>(0xF0 | (c >> 18)), static_cast<char>(0x80 | ((c >> 12) & 0x3F)),
|
||||
static_cast<char>(0x80 | ((c >> 6) & 0x3F)), static_cast<char>(0x80 | (c & 0x3F))};
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::filesystem::path path(const std::string &utf8) { return std::filesystem::path(utf8); }
|
||||
std::string str(const std::filesystem::path &p) { return p.string(); }
|
||||
|
||||
std::string exeDirectory()
|
||||
{
|
||||
return g_exePath.empty() ? "." : std::filesystem::path(g_exePath).parent_path().string();
|
||||
}
|
||||
|
||||
std::vector<std::string> arguments()
|
||||
{
|
||||
std::vector<std::string> out;
|
||||
std::ifstream in("/proc/self/cmdline", std::ios::binary);
|
||||
std::string arg;
|
||||
bool first = true;
|
||||
while (std::getline(in, arg, '\0'))
|
||||
{
|
||||
if (!first)
|
||||
out.push_back(arg);
|
||||
first = false;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string getEnv(const char *name)
|
||||
{
|
||||
const char *v = std::getenv(name);
|
||||
return v ? v : "";
|
||||
}
|
||||
|
||||
void setEnv(const char *name, const std::string &value)
|
||||
{
|
||||
if (value.empty())
|
||||
unsetenv(name);
|
||||
else
|
||||
::setenv(name, value.c_str(), 1);
|
||||
}
|
||||
|
||||
std::string userDirectory()
|
||||
{
|
||||
std::filesystem::path dir;
|
||||
if (const std::string forced = getEnv("PS2X_USER_DIR"); !forced.empty())
|
||||
dir = forced;
|
||||
else if (const std::string data = getEnv("XDG_DATA_HOME"); !data.empty())
|
||||
dir = std::filesystem::path(data) / "tmb_recomp";
|
||||
else if (const std::string home = getEnv("HOME"); !home.empty())
|
||||
dir = std::filesystem::path(home) / ".local" / "share" / "tmb_recomp";
|
||||
else
|
||||
dir = std::filesystem::path(exeDirectory()) / "user";
|
||||
std::error_code ec;
|
||||
std::filesystem::create_directories(dir, ec);
|
||||
return std::filesystem::absolute(dir, ec).lexically_normal().string();
|
||||
}
|
||||
|
||||
std::string systemLanguage() { return localeLanguage() == "fr" ? "fr" : "en"; }
|
||||
|
||||
std::string systemGameLanguage()
|
||||
{
|
||||
const std::string l = localeLanguage();
|
||||
return l == "fr" || l == "de" || l == "es" || l == "it" ? l : "en";
|
||||
}
|
||||
|
||||
std::string findProgram(const std::string &name)
|
||||
{
|
||||
if (name.find('/') != std::string::npos)
|
||||
return access(name.c_str(), X_OK) == 0 ? name : std::string();
|
||||
const std::string pathVar = getEnv("PATH").empty() ? "/usr/local/bin:/usr/bin:/bin" : getEnv("PATH");
|
||||
size_t start = 0;
|
||||
for (;;)
|
||||
{
|
||||
const size_t end = pathVar.find(':', start);
|
||||
std::string dir = pathVar.substr(start, end == std::string::npos ? std::string::npos : end - start);
|
||||
if (!dir.empty())
|
||||
{
|
||||
const std::string candidate = dir + "/" + name;
|
||||
struct stat st{};
|
||||
if (stat(candidate.c_str(), &st) == 0 && S_ISREG(st.st_mode) && access(candidate.c_str(), X_OK) == 0)
|
||||
return candidate;
|
||||
}
|
||||
if (end == std::string::npos)
|
||||
return {};
|
||||
start = end + 1;
|
||||
}
|
||||
}
|
||||
|
||||
std::string pickDiscImage(void *ownerWindow, const std::string &title, const std::string &filterName,
|
||||
const std::string &allFilesName)
|
||||
{
|
||||
(void)title;
|
||||
struct Result
|
||||
{
|
||||
std::atomic<bool> done{false};
|
||||
std::string file, error;
|
||||
} result;
|
||||
const std::string discs = filterName + " (*.iso, *.bin, *.cue)";
|
||||
const SDL_DialogFileFilter filters[] = {{discs.c_str(), "iso;bin;cue;ISO;BIN;CUE"}, {allFilesName.c_str(), "*"}};
|
||||
SDL_ShowOpenFileDialog(
|
||||
[](void *user, const char *const *files, int)
|
||||
{
|
||||
auto *r = static_cast<Result *>(user);
|
||||
if (!files)
|
||||
r->error = SDL_GetError();
|
||||
else if (files[0])
|
||||
r->file = files[0];
|
||||
r->done = true;
|
||||
},
|
||||
&result, static_cast<SDL_Window *>(ownerWindow), filters, 2, nullptr, false);
|
||||
while (!result.done)
|
||||
{
|
||||
SDL_PumpEvents();
|
||||
SDL_Delay(20);
|
||||
}
|
||||
if (result.file.empty() && !result.error.empty())
|
||||
messageBox("TMB Launcher", "No file dialog could open (" + result.error +
|
||||
"). Install zenity or your desktop's xdg-desktop-portal, then try again.");
|
||||
return result.file;
|
||||
}
|
||||
|
||||
namespace
|
||||
{
|
||||
void spawnDetached(const std::vector<std::string> &argv)
|
||||
{
|
||||
std::vector<char *> args;
|
||||
for (const std::string &a : argv)
|
||||
args.push_back(const_cast<char *>(a.c_str()));
|
||||
args.push_back(nullptr);
|
||||
const pid_t pid = fork();
|
||||
if (pid == 0)
|
||||
{
|
||||
if (fork() == 0)
|
||||
{
|
||||
setsid();
|
||||
const int null = ::open("/dev/null", O_RDWR | O_CLOEXEC);
|
||||
if (null >= 0)
|
||||
{
|
||||
dup2(null, 0);
|
||||
dup2(null, 1);
|
||||
dup2(null, 2);
|
||||
}
|
||||
execvp(args[0], args.data());
|
||||
}
|
||||
_exit(0);
|
||||
}
|
||||
if (pid > 0)
|
||||
waitpid(pid, nullptr, 0);
|
||||
}
|
||||
}
|
||||
|
||||
void open(const std::string &target) { spawnDetached({"xdg-open", target}); }
|
||||
|
||||
void showInFolder(const std::string &file)
|
||||
{
|
||||
spawnDetached({"xdg-open", std::filesystem::path(file).parent_path().string()});
|
||||
}
|
||||
|
||||
const void *resource(const char *name, size_t &size)
|
||||
{
|
||||
size = 0;
|
||||
if (std::strcmp(name, "EXO2") == 0)
|
||||
{
|
||||
size = static_cast<size_t>(tmb_res_exo2_end - tmb_res_exo2);
|
||||
return tmb_res_exo2;
|
||||
}
|
||||
if (std::strcmp(name, "OFL") == 0)
|
||||
{
|
||||
size = static_cast<size_t>(tmb_res_ofl_end - tmb_res_ofl);
|
||||
return tmb_res_ofl;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
double now()
|
||||
{
|
||||
using namespace std::chrono;
|
||||
return duration<double>(steady_clock::now().time_since_epoch()).count();
|
||||
}
|
||||
|
||||
std::vector<std::pair<std::string, uint64_t>> listFiles(const std::string &folder, const std::string &suffix)
|
||||
{
|
||||
std::vector<std::pair<std::string, uint64_t>> out;
|
||||
std::error_code ec;
|
||||
for (const auto &entry : std::filesystem::directory_iterator(folder, ec))
|
||||
{
|
||||
const std::string name = entry.path().filename().string();
|
||||
if (!entry.is_regular_file(ec) || name.size() < suffix.size() ||
|
||||
name.compare(name.size() - suffix.size(), suffix.size(), suffix) != 0)
|
||||
continue;
|
||||
struct stat st{};
|
||||
if (stat(entry.path().c_str(), &st) != 0)
|
||||
continue;
|
||||
const uint64_t ticks = (static_cast<uint64_t>(st.st_mtim.tv_sec) + 11644473600ull) * 10000000ull +
|
||||
static_cast<uint64_t>(st.st_mtim.tv_nsec) / 100u;
|
||||
out.emplace_back(folder + "/" + name, ticks);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
uint64_t freeBytes(const std::string &folder)
|
||||
{
|
||||
struct statvfs st{};
|
||||
if (statvfs(folder.c_str(), &st) != 0)
|
||||
return 0;
|
||||
return static_cast<uint64_t>(st.f_bavail) * st.f_frsize;
|
||||
}
|
||||
|
||||
struct Process::Impl
|
||||
{
|
||||
pid_t pid = 0;
|
||||
bool group = false, reaped = false;
|
||||
bool closeAsked = false; // requestClose's SIGTERM: sent once
|
||||
int status = 0;
|
||||
int readFd = -1;
|
||||
std::thread reader;
|
||||
std::atomic<bool> stop{false};
|
||||
std::mutex mutex;
|
||||
std::deque<std::string> lines;
|
||||
std::atomic<bool> readerDone{true};
|
||||
|
||||
~Impl()
|
||||
{
|
||||
if (group && pid > 0 && !reap())
|
||||
{
|
||||
::kill(-pid, SIGKILL);
|
||||
waitpid(pid, &status, 0);
|
||||
reaped = true;
|
||||
}
|
||||
if (reader.joinable())
|
||||
{
|
||||
for (int i = 0; i < 200 && !readerDone; ++i)
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
||||
stop = true;
|
||||
reader.join();
|
||||
}
|
||||
if (readFd >= 0)
|
||||
close(readFd);
|
||||
}
|
||||
|
||||
bool reap()
|
||||
{
|
||||
if (reaped || pid <= 0)
|
||||
return reaped;
|
||||
const pid_t got = waitpid(pid, &status, WNOHANG);
|
||||
if (got == pid || (got < 0 && errno == ECHILD))
|
||||
reaped = true;
|
||||
return reaped;
|
||||
}
|
||||
|
||||
void readLoop()
|
||||
{
|
||||
std::string pending;
|
||||
char buffer[4096];
|
||||
while (!stop)
|
||||
{
|
||||
pollfd p{readFd, POLLIN, 0};
|
||||
const int ready = poll(&p, 1, 100);
|
||||
if (ready < 0 && errno == EINTR)
|
||||
continue;
|
||||
if (ready == 0)
|
||||
continue;
|
||||
if (ready < 0)
|
||||
break;
|
||||
const ssize_t got = read(readFd, buffer, sizeof(buffer));
|
||||
if (got < 0 && errno == EINTR)
|
||||
continue;
|
||||
if (got <= 0)
|
||||
break;
|
||||
pending.append(buffer, static_cast<size_t>(got));
|
||||
size_t at;
|
||||
while ((at = pending.find('\n')) != std::string::npos)
|
||||
{
|
||||
std::string line = pending.substr(0, at);
|
||||
if (!line.empty() && line.back() == '\r')
|
||||
line.pop_back();
|
||||
pending.erase(0, at + 1);
|
||||
std::lock_guard<std::mutex> lock(mutex);
|
||||
lines.push_back(std::move(line));
|
||||
}
|
||||
}
|
||||
if (!pending.empty())
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex);
|
||||
lines.push_back(pending);
|
||||
}
|
||||
readerDone = true;
|
||||
}
|
||||
};
|
||||
|
||||
Process::Process() : impl(std::make_unique<Impl>()) {}
|
||||
Process::~Process() = default;
|
||||
|
||||
bool Process::start(const std::string &exe, const std::vector<std::string> &args, const std::string &cwd,
|
||||
bool captureOutput, std::string &error)
|
||||
{
|
||||
impl = std::make_unique<Impl>();
|
||||
std::vector<std::string> argv{exe};
|
||||
argv.insert(argv.end(), args.begin(), args.end());
|
||||
std::vector<char *> cargv;
|
||||
for (std::string &a : argv)
|
||||
cargv.push_back(a.data());
|
||||
cargv.push_back(nullptr);
|
||||
|
||||
int out[2] = {-1, -1}, report[2] = {-1, -1};
|
||||
if ((captureOutput && pipe2(out, O_CLOEXEC) != 0) || pipe2(report, O_CLOEXEC) != 0)
|
||||
{
|
||||
error = std::strerror(errno);
|
||||
for (int fd : {out[0], out[1], report[0], report[1]})
|
||||
if (fd >= 0)
|
||||
close(fd);
|
||||
return false;
|
||||
}
|
||||
const pid_t parent = getpid();
|
||||
const pid_t pid = fork();
|
||||
if (pid < 0)
|
||||
{
|
||||
error = std::strerror(errno);
|
||||
for (int fd : {out[0], out[1], report[0], report[1]})
|
||||
if (fd >= 0)
|
||||
close(fd);
|
||||
return false;
|
||||
}
|
||||
if (pid == 0)
|
||||
{
|
||||
setsid();
|
||||
if (captureOutput)
|
||||
{
|
||||
prctl(PR_SET_PDEATHSIG, SIGKILL);
|
||||
if (getppid() != parent)
|
||||
_exit(127);
|
||||
}
|
||||
sigset_t none;
|
||||
sigemptyset(&none);
|
||||
sigprocmask(SIG_SETMASK, &none, nullptr);
|
||||
const int null = ::open("/dev/null", O_RDWR | O_CLOEXEC);
|
||||
if (null >= 0)
|
||||
{
|
||||
dup2(null, 0);
|
||||
if (!captureOutput)
|
||||
{
|
||||
dup2(null, 1);
|
||||
dup2(null, 2);
|
||||
}
|
||||
}
|
||||
if (captureOutput)
|
||||
{
|
||||
dup2(out[1], 1);
|
||||
dup2(out[1], 2);
|
||||
}
|
||||
if (!cwd.empty() && chdir(cwd.c_str()) != 0)
|
||||
{
|
||||
const int e = errno;
|
||||
(void)!write(report[1], &e, sizeof(e));
|
||||
_exit(127);
|
||||
}
|
||||
execvp(cargv[0], cargv.data());
|
||||
const int e = errno;
|
||||
(void)!write(report[1], &e, sizeof(e));
|
||||
_exit(127);
|
||||
}
|
||||
close(report[1]);
|
||||
if (captureOutput)
|
||||
close(out[1]);
|
||||
int childErrno = 0;
|
||||
ssize_t n;
|
||||
do
|
||||
n = read(report[0], &childErrno, sizeof(childErrno));
|
||||
while (n < 0 && errno == EINTR);
|
||||
close(report[0]);
|
||||
if (n == sizeof(childErrno))
|
||||
{
|
||||
waitpid(pid, nullptr, 0);
|
||||
if (captureOutput)
|
||||
close(out[0]);
|
||||
error = exe + ": " + std::strerror(childErrno);
|
||||
return false;
|
||||
}
|
||||
impl->pid = pid;
|
||||
impl->closeAsked = false;
|
||||
impl->group = captureOutput;
|
||||
if (captureOutput)
|
||||
{
|
||||
impl->readFd = out[0];
|
||||
impl->readerDone = false;
|
||||
impl->reader = std::thread([self = impl.get()] { self->readLoop(); });
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Process::running() { return impl->pid > 0 && !impl->reap(); }
|
||||
|
||||
long Process::exitCode()
|
||||
{
|
||||
if (impl->pid <= 0 || !impl->reap())
|
||||
return -1;
|
||||
if (WIFEXITED(impl->status))
|
||||
return WEXITSTATUS(impl->status);
|
||||
if (WIFSIGNALED(impl->status))
|
||||
return 128 + WTERMSIG(impl->status);
|
||||
return -1;
|
||||
}
|
||||
|
||||
uint32_t Process::pid() const { return static_cast<uint32_t>(impl->pid); }
|
||||
|
||||
std::vector<std::string> Process::takeLines()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(impl->mutex);
|
||||
std::vector<std::string> out(impl->lines.begin(), impl->lines.end());
|
||||
impl->lines.clear();
|
||||
return out;
|
||||
}
|
||||
|
||||
void Process::kill()
|
||||
{
|
||||
if (impl->pid <= 0)
|
||||
return;
|
||||
if (impl->group)
|
||||
::kill(-impl->pid, SIGKILL);
|
||||
else if (!impl->reap())
|
||||
::kill(impl->pid, SIGKILL);
|
||||
}
|
||||
|
||||
void Process::drain(int timeoutMs)
|
||||
{
|
||||
const double end = now() + timeoutMs / 1000.0;
|
||||
while (!impl->readerDone && now() < end)
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
||||
}
|
||||
|
||||
void Process::requestClose()
|
||||
{
|
||||
// Once: the game's SDL turns SIGTERM into a quit, then restores the default handlers as it shuts down, so a
|
||||
// second one (a caller asking every frame, as WM_CLOSE may be on Windows) would kill it mid-shutdown (exit 143).
|
||||
if (impl->pid > 0 && !impl->closeAsked && !impl->reap())
|
||||
{
|
||||
impl->closeAsked = true;
|
||||
::kill(impl->pid, SIGTERM);
|
||||
}
|
||||
}
|
||||
|
||||
namespace
|
||||
{
|
||||
using CURL = void;
|
||||
struct curl_slist;
|
||||
using curl_off_t = long long;
|
||||
constexpr int kOptUrl = 10002, kOptUserAgent = 10018, kOptHttpHeader = 10023, kOptWriteFunction = 20011,
|
||||
kOptWriteData = 10001, kOptFollow = 52, kOptMaxRedirs = 68, kOptConnectTimeoutMs = 156,
|
||||
kOptLowSpeedLimit = 19, kOptLowSpeedTime = 20, kOptNoSignal = 99, kOptProtocols = 181,
|
||||
kOptRedirProtocols = 182, kOptErrorBuffer = 10010, kOptXferInfoFunction = 20219,
|
||||
kOptXferInfoData = 10057, kOptNoProgress = 43;
|
||||
constexpr int kInfoResponseCode = 0x200000 + 2, kInfoContentLength = 0x600000 + 15;
|
||||
constexpr long kProtoHttp = 1, kProtoHttps = 2;
|
||||
constexpr int kCurlOk = 0, kErrorSize = 256;
|
||||
|
||||
struct Curl
|
||||
{
|
||||
bool loaded = false;
|
||||
int (*global_init)(long) = nullptr;
|
||||
CURL *(*easy_init)() = nullptr;
|
||||
int (*easy_setopt)(CURL *, int, ...) = nullptr;
|
||||
int (*easy_perform)(CURL *) = nullptr;
|
||||
int (*easy_getinfo)(CURL *, int, ...) = nullptr;
|
||||
void (*easy_cleanup)(CURL *) = nullptr;
|
||||
const char *(*easy_strerror)(int) = nullptr;
|
||||
curl_slist *(*slist_append)(curl_slist *, const char *) = nullptr;
|
||||
void (*slist_free_all)(curl_slist *) = nullptr;
|
||||
|
||||
Curl()
|
||||
{
|
||||
void *lib = nullptr;
|
||||
for (const char *name : {"libcurl.so.4", "libcurl-gnutls.so.4", "libcurl-nss.so.4", "libcurl.so"})
|
||||
if ((lib = dlopen(name, RTLD_NOW | RTLD_LOCAL)))
|
||||
break;
|
||||
if (!lib)
|
||||
return;
|
||||
auto get = [&](auto &fn, const char *name)
|
||||
{ fn = reinterpret_cast<std::remove_reference_t<decltype(fn)>>(dlsym(lib, name)); return fn != nullptr; };
|
||||
loaded = get(global_init, "curl_global_init") && get(easy_init, "curl_easy_init") &&
|
||||
get(easy_setopt, "curl_easy_setopt") && get(easy_perform, "curl_easy_perform") &&
|
||||
get(easy_getinfo, "curl_easy_getinfo") && get(easy_cleanup, "curl_easy_cleanup") &&
|
||||
get(easy_strerror, "curl_easy_strerror") && get(slist_append, "curl_slist_append") &&
|
||||
get(slist_free_all, "curl_slist_free_all");
|
||||
if (loaded)
|
||||
global_init(3);
|
||||
}
|
||||
};
|
||||
|
||||
Curl &curl()
|
||||
{
|
||||
static Curl c;
|
||||
return c;
|
||||
}
|
||||
|
||||
struct Transfer
|
||||
{
|
||||
CURL *handle = nullptr;
|
||||
long status = 0;
|
||||
uint64_t length = 0;
|
||||
bool sized = false, aborted = false;
|
||||
const std::function<bool(Transfer &, const char *, size_t)> *sink = nullptr;
|
||||
const std::atomic<bool> *cancel = nullptr;
|
||||
|
||||
void readHeaders()
|
||||
{
|
||||
if (sized)
|
||||
return;
|
||||
sized = true;
|
||||
curl().easy_getinfo(handle, kInfoResponseCode, &status);
|
||||
curl_off_t n = -1;
|
||||
if (curl().easy_getinfo(handle, kInfoContentLength, &n) == kCurlOk && n > 0)
|
||||
length = static_cast<uint64_t>(n);
|
||||
}
|
||||
};
|
||||
|
||||
size_t writeCallback(char *data, size_t size, size_t count, void *user)
|
||||
{
|
||||
auto *t = static_cast<Transfer *>(user);
|
||||
t->readHeaders();
|
||||
const size_t n = size * count;
|
||||
if (!(*t->sink)(*t, data, n))
|
||||
{
|
||||
t->aborted = true;
|
||||
return 0;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
int progressCallback(void *user, curl_off_t, curl_off_t, curl_off_t, curl_off_t)
|
||||
{
|
||||
auto *t = static_cast<Transfer *>(user);
|
||||
if (!t->cancel || !t->cancel->load())
|
||||
return 0;
|
||||
t->aborted = true;
|
||||
return 1;
|
||||
}
|
||||
|
||||
bool httpRequest(const std::string &url, const std::string &userAgent, const std::vector<std::string> &headers,
|
||||
int receiveMs, long &status, std::string &error,
|
||||
const std::function<bool(Transfer &, const char *, size_t)> &sink,
|
||||
const std::atomic<bool> *cancel = nullptr)
|
||||
{
|
||||
status = 0;
|
||||
Curl &c = curl();
|
||||
if (!c.loaded)
|
||||
{
|
||||
error = "libcurl is not installed";
|
||||
return false;
|
||||
}
|
||||
if (url.rfind("https://", 0) != 0 && url.rfind("http://", 0) != 0)
|
||||
{
|
||||
error = "bad URL";
|
||||
return false;
|
||||
}
|
||||
Transfer t;
|
||||
t.handle = c.easy_init();
|
||||
if (!t.handle)
|
||||
{
|
||||
error = "libcurl could not start";
|
||||
return false;
|
||||
}
|
||||
t.sink = &sink;
|
||||
t.cancel = cancel;
|
||||
curl_slist *list = nullptr;
|
||||
for (const std::string &h : headers)
|
||||
list = c.slist_append(list, h.c_str());
|
||||
char errorBuffer[kErrorSize] = {};
|
||||
const long https = url.rfind("https://", 0) == 0;
|
||||
c.easy_setopt(t.handle, kOptUrl, url.c_str());
|
||||
c.easy_setopt(t.handle, kOptUserAgent, userAgent.c_str());
|
||||
c.easy_setopt(t.handle, kOptHttpHeader, list);
|
||||
c.easy_setopt(t.handle, kOptFollow, 1L);
|
||||
c.easy_setopt(t.handle, kOptMaxRedirs, 10L);
|
||||
c.easy_setopt(t.handle, kOptProtocols, kProtoHttp | kProtoHttps);
|
||||
c.easy_setopt(t.handle, kOptRedirProtocols, https ? kProtoHttps : kProtoHttp | kProtoHttps);
|
||||
c.easy_setopt(t.handle, kOptConnectTimeoutMs, 5000L);
|
||||
c.easy_setopt(t.handle, kOptLowSpeedLimit, 1L);
|
||||
c.easy_setopt(t.handle, kOptLowSpeedTime, static_cast<long>((receiveMs + 999) / 1000));
|
||||
c.easy_setopt(t.handle, kOptNoSignal, 1L);
|
||||
c.easy_setopt(t.handle, kOptErrorBuffer, errorBuffer);
|
||||
c.easy_setopt(t.handle, kOptWriteFunction, &writeCallback);
|
||||
c.easy_setopt(t.handle, kOptWriteData, &t);
|
||||
if (cancel)
|
||||
{
|
||||
c.easy_setopt(t.handle, kOptXferInfoFunction, &progressCallback);
|
||||
c.easy_setopt(t.handle, kOptXferInfoData, &t);
|
||||
c.easy_setopt(t.handle, kOptNoProgress, 0L);
|
||||
}
|
||||
const int code = c.easy_perform(t.handle);
|
||||
t.readHeaders();
|
||||
status = t.status;
|
||||
c.easy_cleanup(t.handle);
|
||||
if (list)
|
||||
c.slist_free_all(list);
|
||||
if (t.aborted)
|
||||
return false;
|
||||
if (code != kCurlOk)
|
||||
{
|
||||
error = errorBuffer[0] ? errorBuffer : c.easy_strerror(code);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
bool httpGet(const std::string &url, const std::string &userAgent, std::string &body, long &status,
|
||||
std::string &error, size_t maxBytes)
|
||||
{
|
||||
body.clear();
|
||||
return httpRequest(url, userAgent, {"Accept: application/vnd.github+json", "X-GitHub-Api-Version: 2022-11-28"},
|
||||
8000, status, error, [&](Transfer &, const char *data, size_t n)
|
||||
{
|
||||
body.append(data, n);
|
||||
if (body.size() <= maxBytes)
|
||||
return true;
|
||||
error = "response too large";
|
||||
return false; });
|
||||
}
|
||||
|
||||
bool httpDownload(const std::string &url, const std::string &userAgent, const std::string &file, std::atomic<uint64_t> &done,
|
||||
std::atomic<uint64_t> &total, const std::atomic<bool> &cancel, std::string &error, uint64_t maxBytes)
|
||||
{
|
||||
done = 0;
|
||||
total = 0;
|
||||
std::FILE *out = std::fopen(file.c_str(), "wb");
|
||||
if (!out)
|
||||
{
|
||||
error = std::strerror(errno);
|
||||
return false;
|
||||
}
|
||||
long status = 0;
|
||||
bool ok = httpRequest(url, userAgent, {"Accept: application/octet-stream"}, 30000, status, error,
|
||||
[&](Transfer &t, const char *data, size_t n)
|
||||
{
|
||||
total = t.length;
|
||||
if (t.status != 200)
|
||||
return false;
|
||||
if (cancel.load())
|
||||
{
|
||||
error = "stopped";
|
||||
return false;
|
||||
}
|
||||
if (std::fwrite(data, 1, n, out) != n)
|
||||
{
|
||||
error = std::strerror(errno);
|
||||
return false;
|
||||
}
|
||||
done += n;
|
||||
if (done.load() <= maxBytes)
|
||||
return true;
|
||||
error = "download too large";
|
||||
return false; }, &cancel);
|
||||
if (!ok && error.empty() && cancel.load())
|
||||
error = "stopped";
|
||||
if (std::fclose(out) != 0 && ok)
|
||||
{
|
||||
ok = false;
|
||||
error = std::strerror(errno);
|
||||
}
|
||||
if (ok && status != 200)
|
||||
{
|
||||
ok = false;
|
||||
error = "HTTP " + std::to_string(status);
|
||||
}
|
||||
else if (!ok && error.empty())
|
||||
error = status != 200 ? "HTTP " + std::to_string(status) : "download failed";
|
||||
if (!ok)
|
||||
std::remove(file.c_str());
|
||||
return ok;
|
||||
}
|
||||
|
||||
std::string exePath() { return g_exePath; }
|
||||
|
||||
void messageBox(const std::string &title, const std::string &text)
|
||||
{
|
||||
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, title.c_str(), text.c_str(), nullptr);
|
||||
}
|
||||
}
|
||||
@@ -110,6 +110,23 @@ namespace plat
|
||||
return PRIMARYLANGID(GetUserDefaultUILanguage()) == LANG_FRENCH ? "fr" : "en";
|
||||
}
|
||||
|
||||
std::string findProgram(const std::string &name)
|
||||
{
|
||||
std::wstring buffer(MAX_PATH, L'\0');
|
||||
for (;;)
|
||||
{
|
||||
const DWORD n = SearchPathW(nullptr, widen(name).c_str(), L".exe", static_cast<DWORD>(buffer.size()), buffer.data(), nullptr);
|
||||
if (n == 0)
|
||||
return {};
|
||||
if (n < buffer.size())
|
||||
{
|
||||
buffer.resize(n);
|
||||
return narrow(buffer);
|
||||
}
|
||||
buffer.resize(n);
|
||||
}
|
||||
}
|
||||
|
||||
std::string pickDiscImage(void *ownerWindow, const std::string &title, const std::string &filterName,
|
||||
const std::string &allFilesName)
|
||||
{
|
||||
|
||||
+12
-1
@@ -41,10 +41,21 @@ namespace ui
|
||||
std::snprintf(cfg.Name, sizeof(cfg.Name), "Exo 2");
|
||||
fonts.text = io.Fonts->AddFontFromMemoryTTF(const_cast<void *>(exo), static_cast<int>(size), S(20), &cfg);
|
||||
}
|
||||
#ifdef _WIN32
|
||||
const std::string windir = plat::getEnv("WINDIR").empty() ? "C:\\Windows" : plat::getEnv("WINDIR");
|
||||
std::vector<std::string> monoFiles;
|
||||
for (const char *name : {"CascadiaMono.ttf", "CascadiaCode.ttf", "consola.ttf"})
|
||||
monoFiles.push_back(windir + "\\Fonts\\" + name);
|
||||
#else
|
||||
const std::vector<std::string> monoFiles = {
|
||||
"/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf", "/usr/share/fonts/TTF/DejaVuSansMono.ttf",
|
||||
"/usr/share/fonts/dejavu-sans-mono-fonts/DejaVuSansMono.ttf", "/usr/share/fonts/dejavu/DejaVuSansMono.ttf",
|
||||
"/usr/share/fonts/truetype/liberation/LiberationMono-Regular.ttf",
|
||||
"/usr/share/fonts/liberation-mono/LiberationMono-Regular.ttf", "/usr/share/fonts/TTF/LiberationMono-Regular.ttf",
|
||||
"/usr/share/fonts/noto/NotoSansMono-Regular.ttf", "/usr/share/fonts/truetype/noto/NotoSansMono-Regular.ttf"};
|
||||
#endif
|
||||
for (const std::string &file : monoFiles)
|
||||
{
|
||||
const std::string file = windir + "\\Fonts\\" + name;
|
||||
std::error_code ec;
|
||||
if (std::filesystem::exists(plat::path(file), ec))
|
||||
{
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
{
|
||||
"$schema": "https://recomplauncher.com/schema/recomplauncher.json",
|
||||
"format": 1,
|
||||
"name": "Twisted Metal: Black",
|
||||
"repo": "TheBozos/TMB_Recomp",
|
||||
"inputs": [
|
||||
{
|
||||
"id": "game",
|
||||
"label": "Your disc image of the USA release, serial SCUS-97101 (.iso, or .bin/.cue).",
|
||||
"formats": [{ "type": "file" }],
|
||||
"check": { "iso9660": "SCUS_971.01", "ids": ["SCUS-97101"] },
|
||||
"dumps": [{ "name": "USA", "size": 3799744512, "crc32": "347e93f9" }]
|
||||
}
|
||||
],
|
||||
"prepare": {
|
||||
"program": ["kit/python/python.exe", "kit/python3"],
|
||||
"args": ["-I", "-X", "utf8", "{install}/source/tools/tmb_build.py", "--disc={input:game}",
|
||||
"--out", "{install}/build", "--game", "{install}/game", "--progress-lines"],
|
||||
"label": "Building the game from your disc",
|
||||
"done": ["{install}/game/built_from.ini"],
|
||||
"keeps_copy": true
|
||||
},
|
||||
"start": {
|
||||
"program": ["game/tmb.exe", "game/tmb"],
|
||||
"args": ["--elf", "{install}/game/SCUS_971.01", "--iso", "{install}/game/disc.iso"],
|
||||
"env": { "PS2X_USER_DIR": "{data}" }
|
||||
},
|
||||
"folders": {
|
||||
"game": [{ "path": "{install}/game" }],
|
||||
"saves": [{ "path": "{data}/mc0" }],
|
||||
"logs": [{ "path": "{data}/logs" }]
|
||||
},
|
||||
"saves": ["{data}/mc0", "{data}/mc1"],
|
||||
"config": [{ "format": "ini", "file": [{ "path": "{data}/video.ini" }] }],
|
||||
"settings": [
|
||||
{
|
||||
"id": "mode", "label": "Display mode",
|
||||
"choices": [
|
||||
{ "label": "Windowed", "set": { "video/mode": "windowed" } },
|
||||
{ "label": "Borderless", "set": { "video/mode": "borderless" } },
|
||||
{ "label": "Full screen", "set": { "video/mode": "fullscreen" } }
|
||||
],
|
||||
"defaults": { "video/mode": "windowed" }
|
||||
},
|
||||
{
|
||||
"id": "widescreen", "label": "Widescreen",
|
||||
"help": "16:9 with more of the arena at the sides in one- and two-player matches; menus, movies and four-player matches stay 4:3.",
|
||||
"choices": [
|
||||
{ "label": "Off (4:3)", "set": { "video/widescreen": "off" } },
|
||||
{ "label": "On (16:9)", "set": { "video/widescreen": "on" } }
|
||||
],
|
||||
"defaults": { "video/widescreen": "off" }
|
||||
},
|
||||
{
|
||||
"id": "frame_rate", "label": "Frame rate",
|
||||
"help": "Above 60, frames between the game's are drawn in between; the game itself still runs at its own speed.",
|
||||
"choices": [
|
||||
{ "label": "60 (the game's)", "set": { "video/frame_rate": "game" } },
|
||||
{ "label": "Monitor's refresh", "set": { "video/frame_rate": "monitor" } },
|
||||
{ "label": "120", "set": { "video/frame_rate": "120" } },
|
||||
{ "label": "144", "set": { "video/frame_rate": "144" } },
|
||||
{ "label": "240", "set": { "video/frame_rate": "240" } }
|
||||
],
|
||||
"defaults": { "video/frame_rate": "game" }
|
||||
},
|
||||
{
|
||||
"id": "render_scale", "label": "Render scale",
|
||||
"help": "The 3D drawn at this many times the window's size.",
|
||||
"choices": [
|
||||
{ "label": "1x", "set": { "video/render_scale": "1" } },
|
||||
{ "label": "1.5x", "set": { "video/render_scale": "1.5" } },
|
||||
{ "label": "2x", "set": { "video/render_scale": "2" } },
|
||||
{ "label": "3x", "set": { "video/render_scale": "3" } },
|
||||
{ "label": "4x", "set": { "video/render_scale": "4" } }
|
||||
],
|
||||
"defaults": { "video/render_scale": "1" }
|
||||
},
|
||||
{
|
||||
"id": "anti_aliasing", "label": "Anti-aliasing",
|
||||
"help": "Smooths the edges of the 3D (MSAA).",
|
||||
"choices": [
|
||||
{ "label": "Off", "set": { "video/anti_aliasing": "off" } },
|
||||
{ "label": "2x", "set": { "video/anti_aliasing": "2x" } },
|
||||
{ "label": "4x", "set": { "video/anti_aliasing": "4x" } },
|
||||
{ "label": "8x", "set": { "video/anti_aliasing": "8x" } }
|
||||
],
|
||||
"defaults": { "video/anti_aliasing": "off" }
|
||||
},
|
||||
{
|
||||
"id": "texture_smoothing", "label": "Texture smoothing",
|
||||
"help": "Off samples textures as the PS2 does; the others stop distant textures shimmering.",
|
||||
"choices": [
|
||||
{ "label": "Off", "set": { "video/texture_smoothing": "off" } },
|
||||
{ "label": "Trilinear", "set": { "video/texture_smoothing": "trilinear" } },
|
||||
{ "label": "4x anisotropic", "set": { "video/texture_smoothing": "4x" } },
|
||||
{ "label": "8x anisotropic", "set": { "video/texture_smoothing": "8x" } },
|
||||
{ "label": "16x anisotropic", "set": { "video/texture_smoothing": "16x" } }
|
||||
],
|
||||
"defaults": { "video/texture_smoothing": "off" }
|
||||
},
|
||||
{
|
||||
"id": "pause_in_background", "label": "Pause in the background", "advanced": true,
|
||||
"help": "Holds the game while another window has the focus.",
|
||||
"choices": [
|
||||
{ "label": "Off", "set": { "video/pause_in_background": "off" } },
|
||||
{ "label": "On", "set": { "video/pause_in_background": "on" } }
|
||||
],
|
||||
"defaults": { "video/pause_in_background": "off" }
|
||||
},
|
||||
{
|
||||
"id": "fast_forward", "label": "Fast-forward speed", "advanced": true,
|
||||
"help": "The game's speed while fast forward is held (` on the keyboard, or the touchpad).",
|
||||
"choices": [
|
||||
{ "label": "2x", "set": { "video/fast_forward": "2x" } },
|
||||
{ "label": "3x", "set": { "video/fast_forward": "3x" } },
|
||||
{ "label": "5x", "set": { "video/fast_forward": "5x" } },
|
||||
{ "label": "10x", "set": { "video/fast_forward": "10x" } },
|
||||
{ "label": "Unlimited", "set": { "video/fast_forward": "unlimited" } }
|
||||
],
|
||||
"defaults": { "video/fast_forward": "3x" }
|
||||
}
|
||||
],
|
||||
"actions": [
|
||||
{ "id": "logs", "label": "Logs", "help": "The game's logs, for a bug report.", "open": "logs" }
|
||||
],
|
||||
"looks": { "graphics": "opengl" },
|
||||
"system": {
|
||||
"windows": { "version": "10", "graphics": { "opengl": "3.3" } },
|
||||
"linux": { "graphics": { "opengl": "3.3" } }
|
||||
}
|
||||
}
|
||||
+13
-4
@@ -11,6 +11,7 @@
|
||||
|
||||
#include "tmb_port.h"
|
||||
#include "bozo/render/renderer.h"
|
||||
#include "bozo/libs/crt_math.h"
|
||||
#include "bozo/render/texture.h"
|
||||
#include "bozo/render/movie.h"
|
||||
#include <mutex>
|
||||
@@ -571,11 +572,13 @@ namespace tmb::twod
|
||||
return a - kTwoPi * std::floor((a + kPi) / kTwoPi);
|
||||
}
|
||||
// mathfRotMatrixRPH(m, angles): the rotation of angles (x, y, z) (sines and cosines as the game combines them),
|
||||
// rows of three.
|
||||
// rows of three. The sines and cosines are the reference's C runtime's (crtSinf, crtCosf: the same bits on every
|
||||
// platform).
|
||||
void rotationRph(const float angles[3], float m[3][3])
|
||||
{
|
||||
const float sx = std::sin(angles[0]), cx = std::cos(angles[0]), sy = std::sin(angles[1]), cy = std::cos(angles[1]);
|
||||
const float sz = std::sin(angles[2]), cz = std::cos(angles[2]);
|
||||
const float sx = bozo::libs::crtSinf(angles[0]), cx = bozo::libs::crtCosf(angles[0]),
|
||||
sy = bozo::libs::crtSinf(angles[1]), cy = bozo::libs::crtCosf(angles[1]);
|
||||
const float sz = bozo::libs::crtSinf(angles[2]), cz = bozo::libs::crtCosf(angles[2]);
|
||||
m[0][0] = cy * cz + sy * sx * sz;
|
||||
m[0][1] = -cy * sz + sy * sx * cz;
|
||||
m[0][2] = -sy * cx;
|
||||
@@ -800,6 +803,9 @@ namespace tmb::twod
|
||||
informProgressBar__Ff_0x1fc8d0(rdram, ctx, runtime);
|
||||
if (!on())
|
||||
return;
|
||||
// Without a bar shown (gp - 0x3280 zero) the game's informProgressBar returns at once: nothing drawn either.
|
||||
if (word(rdram, gp + kGpBarShown) == 0u)
|
||||
return;
|
||||
noteGp(gp);
|
||||
g_barGp.store(gp, std::memory_order_relaxed);
|
||||
g_rdram.store(rdram, std::memory_order_relaxed);
|
||||
@@ -1043,7 +1049,10 @@ namespace tmb::twod
|
||||
}
|
||||
setWord(rdram, gp + kGpBarFlip, word(rdram, gp + kGpBarFlip) ^ 1u);
|
||||
setWord(rdram, gp + kGpBarProgress, std::min<uint32_t>(word(rdram, gp + kGpBarProgress) + 1u, 0x400u));
|
||||
loadingBar(rdram, gp);
|
||||
// Still called once a load in a match (a lost level's retry) has ended, with the bar hidden (gp - 0x3280
|
||||
// zero): drawn then, the bar covered the match's frames in red.
|
||||
if (word(rdram, gp + kGpBarShown) != 0u)
|
||||
loadingBar(rdram, gp);
|
||||
ctx->pc = getRegU32(ctx, 31); // jr $ra
|
||||
}
|
||||
}
|
||||
|
||||
@@ -350,6 +350,10 @@ namespace tmb::cheats
|
||||
std::fprintf(stderr, "[tmb:cheats] story starts at level %s\n", kLevelNames[start]);
|
||||
}
|
||||
s_lastLevel = static_cast<int32_t>(word(rdram, progress + kStoryLevel));
|
||||
// TMB_PLAYER_LIVES=<n> (testing, story's game over): player 1's lives (InitPlayerLives' + 0x2370) kept at most n.
|
||||
static const int s_lives = [] { const char *v = std::getenv("TMB_PLAYER_LIVES"); return v && *v ? std::atoi(v) : -1; }();
|
||||
if (s_lives >= 0 && static_cast<int32_t>(word(rdram, progress + 0x2370u)) > s_lives)
|
||||
setWord(rdram, progress + 0x2370u, static_cast<uint32_t>(s_lives));
|
||||
}
|
||||
static const bool s_on = std::getenv("TMB_LOG_PROGRESS") != nullptr;
|
||||
if (!s_on)
|
||||
|
||||
@@ -862,6 +862,44 @@ namespace
|
||||
const char *value = std::getenv("TMB_KILL_ENEMIES");
|
||||
return value && *value ? static_cast<uint32_t>(std::atof(value) * 50.0) : 0u;
|
||||
}();
|
||||
// TMB_KILL_PLAYER=<s> (testing, story's lost lives and game over): player 1's car takes the same hit every <s>
|
||||
// seconds.
|
||||
static const uint32_t s_playerInterval = []
|
||||
{
|
||||
const char *value = std::getenv("TMB_KILL_PLAYER");
|
||||
return value && *value ? static_cast<uint32_t>(std::atof(value) * 50.0) : 0u;
|
||||
}();
|
||||
static uint32_t s_playerUpdates = 0;
|
||||
if (s_playerInterval != 0u && g_theGame != 0u && ++s_playerUpdates % s_playerInterval == 0u)
|
||||
{
|
||||
float health = 0.0f;
|
||||
std::memcpy(&health, rdram + ((0x00257B50u + 1012u) & 0x1FFFFFFu), 4);
|
||||
if (health > 0.0f)
|
||||
{
|
||||
rdram[0x00257B50u + 0x475u] = 1u; // takes hits (0 in a story started past the first level)
|
||||
R5900Context call = *ctx;
|
||||
SET_GPR_U32(&call, 4, 0x00257B50u);
|
||||
SET_GPR_U32(&call, 5, 0x00257B50u);
|
||||
SET_GPR_U32(&call, 6, 10000u);
|
||||
// The attacker: the first opponent still alive (the player's own index, 0, does no damage).
|
||||
int32_t count = 0, attacker = 1;
|
||||
std::memcpy(&count, rdram + ((g_theGame + 0x001B3DB4u) & 0x1FFFFFFu), 4);
|
||||
for (int32_t index = 1; index < std::min(count, 64); ++index)
|
||||
{
|
||||
float other = 0.0f;
|
||||
std::memcpy(&other, rdram + ((g_theGame + static_cast<uint32_t>(index) * 0x2D00u + 1012u) & 0x1FFFFFFu), 4);
|
||||
if (other > 0.0f)
|
||||
{
|
||||
attacker = index;
|
||||
break;
|
||||
}
|
||||
}
|
||||
SET_GPR_U32(&call, 7, static_cast<uint32_t>(attacker));
|
||||
vehicleTakeHit__7VehicleP8_fvectorii_0x1ad208(rdram, &call, runtime);
|
||||
std::memcpy(&health, rdram + ((0x00257B50u + 1012u) & 0x1FFFFFFu), 4);
|
||||
std::fprintf(stderr, "[tmb:kill] player 1 hit by vehicle %d: health %.0f\n", attacker, health);
|
||||
}
|
||||
}
|
||||
static uint32_t s_updates = 0;
|
||||
if (s_interval == 0u || g_theGame == 0u || ++s_updates % s_interval != 0u)
|
||||
return;
|
||||
|
||||
@@ -49,6 +49,7 @@
|
||||
// compared with what runtime/tmb_native.cpp's translations draw from the same systems' packets.
|
||||
|
||||
#include "bozo/state.h"
|
||||
#include "bozo/libs/crt_math.h"
|
||||
#include "tmb_port.h"
|
||||
#include "bozo/render/renderer.h"
|
||||
#include "bozo/render/texture.h"
|
||||
@@ -1667,7 +1668,8 @@ namespace tmb::particles
|
||||
// sways: its homogeneous x (head and tail) plus 160 sin(a), a from the flake two before (the sine of one flake is
|
||||
// read in the next one's step, which moves the flake after it): a = (|f - 1/2| - 1/4) 2 pi, f = frac(W - VU 12.w),
|
||||
// W the flake's random number (VU1's, seeded from VU 21.x; the first flake's W is VU 15.z, the second's sway
|
||||
// sin(1) from the prologue). Dropped when a corner leaves the guard band (as the rain).
|
||||
// sin(1) from the prologue; the reference C runtime's sine, crtSinf, the same bits on every platform). Dropped when
|
||||
// a corner leaves the guard band (as the rain).
|
||||
void drawSnow(Batch &batch, const Precip &s, const ViewConstants &view)
|
||||
{
|
||||
const float(&c5)[4] = view.vu[5];
|
||||
@@ -1677,7 +1679,7 @@ namespace tmb::particles
|
||||
DropWalk walk(s);
|
||||
uint32_t random = vuRandNext(vuRandInit(s.mul[0])); // RINIT vf19x; the prologue's RNEXT
|
||||
float weight = s.step[2]; // the first flake's W: VU 15.z
|
||||
float sway = 0.0f, swayNext = 160.0f * std::sin(1.0f);
|
||||
float sway = 0.0f, swayNext = 160.0f * bozo::libs::crtSinf(1.0f);
|
||||
for (uint32_t n = 0; n < s.drops; ++n, walk.advance())
|
||||
{
|
||||
float h[4], t[4];
|
||||
@@ -1692,7 +1694,7 @@ namespace tmb::particles
|
||||
f += 1.0f;
|
||||
const float angle = (std::fabs(f) - 0.25f) * 6.28319f;
|
||||
sway = swayNext;
|
||||
swayNext = 160.0f * std::sin(angle);
|
||||
swayNext = 160.0f * bozo::libs::crtSinf(angle);
|
||||
random = vuRandNext(random);
|
||||
weight = vuRandFloat(random);
|
||||
if (h[3] == 0.0f || t[3] == 0.0f)
|
||||
|
||||
+228
-7
@@ -1,8 +1,8 @@
|
||||
"""Player-facing migration and timing regression checks; no game data required."""
|
||||
import configparser
|
||||
import contextlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import tempfile
|
||||
import io
|
||||
@@ -14,6 +14,7 @@ from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tools'))
|
||||
import apply_update
|
||||
import check_timing
|
||||
import make_release
|
||||
import tmb_build
|
||||
@@ -21,7 +22,7 @@ from unittest.mock import patch
|
||||
from types import SimpleNamespace
|
||||
|
||||
REQUIRED = (
|
||||
'TMB Launcher.exe', 'README.txt', 'CHANGELOG.md', 'LICENSES/TMB_Recomp/LICENSE',
|
||||
'TMB Launcher.exe', 'README.txt', 'CHANGELOG.md', 'recomplauncher.json', 'LICENSES/TMB_Recomp/LICENSE',
|
||||
'LICENSES/BozoEngine/LICENSE', 'source/release.ini', 'kit/kit_manifest.json',
|
||||
'kit/python/python.exe', 'source/tools/tmb_build.py', 'source/BozoEngine/CMakeLists.txt',
|
||||
'kit/deps/sdl3-src/CMakeLists.txt', 'kit/deps/imgui-src/imgui.cpp',
|
||||
@@ -221,11 +222,16 @@ class ReleaseTests(unittest.TestCase):
|
||||
self.assertEqual((root / 'CMakeLists.txt').stat().st_mtime_ns, now + 10**12)
|
||||
self.assertFalse((Path(folder) / tmb_build.SOURCE_TIMES).exists())
|
||||
|
||||
def test_only_native_engine_is_a_submodule(self):
|
||||
config = configparser.ConfigParser()
|
||||
config.read(ROOT / '.gitmodules')
|
||||
self.assertEqual(config.sections(), ['submodule "BozoEngine"'])
|
||||
self.assertEqual(config[config.sections()[0]]['path'], 'BozoEngine')
|
||||
def test_engine_is_a_pinned_release(self):
|
||||
# BozoEngine comes from its releases (cmake/bozo_engine.json, fetched by cmake/bozo_engine_fetch.cmake), no
|
||||
# longer from a submodule.
|
||||
self.assertFalse((ROOT / '.gitmodules').exists())
|
||||
pin = json.loads((ROOT / 'cmake/bozo_engine.json').read_text(encoding='utf-8'))
|
||||
self.assertRegex(pin['version'], r'^[0-9]+\.[0-9]+\.[0-9]+$')
|
||||
self.assertRegex(pin['sha256'], r'^[0-9a-f]{64}$')
|
||||
fetch = (ROOT / 'cmake/bozo_engine_fetch.cmake').read_text(encoding='utf-8')
|
||||
self.assertIn('EXPECTED_HASH SHA256=${bozo_engine_sha256}', fetch)
|
||||
self.assertIn('/BozoEngine/', (ROOT / '.gitignore').read_text(encoding='utf-8').splitlines())
|
||||
|
||||
def test_migration_zip_supports_the_existing_installation_layout(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
@@ -260,6 +266,106 @@ class ReleaseTests(unittest.TestCase):
|
||||
archive.writestr('TMB_Recomp_Bozo/source/hidden.dat', b'\x7fELF' + b'\0' * 100)
|
||||
self.assertTrue(any('an ELF file' in error for error in make_release.verify_zip(path)))
|
||||
|
||||
def test_no_bytecode_cache_in_a_release(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
stage = Path(folder) / 'stage'
|
||||
(stage / 'source/tools/__pycache__').mkdir(parents=True)
|
||||
(stage / 'source/tools/__pycache__/tmb_build.cpython-314.pyc').write_bytes(b'cache')
|
||||
(stage / 'source/tools/tmb_build.py').write_text('x')
|
||||
make_release.remove_bytecode_caches(str(stage))
|
||||
self.assertFalse((stage / 'source/tools/__pycache__').exists())
|
||||
self.assertTrue((stage / 'source/tools/tmb_build.py').exists())
|
||||
path = Path(folder) / 'cached.zip'
|
||||
with zipfile.ZipFile(path, 'w') as archive:
|
||||
for name in REQUIRED:
|
||||
archive.writestr('TMB_Recomp_Bozo/' + name, b'fixture')
|
||||
archive.writestr('TMB_Recomp_Bozo/source/tools/__pycache__/tmb_build.cpython-314.pyc', b'cache')
|
||||
self.assertTrue(any('bytecode cache' in p for p in make_release.verify_zip(str(path))))
|
||||
tar = self.linux_release(folder, [('source/tools/__pycache__/x.pyc', b'cache')])
|
||||
self.assertTrue(any('bytecode cache' in p for p in make_release.verify_tar(str(tar))))
|
||||
|
||||
def linux_release(self, folder, extra=()):
|
||||
stage = Path(folder) / 'stage'
|
||||
for name in make_release.LINUX_REQUIRED:
|
||||
file = stage / name
|
||||
file.parent.mkdir(parents=True, exist_ok=True)
|
||||
file.write_bytes(b'\x7fELF launcher' if name == 'tmb-launcher' else b'version = 0.1.1\n')
|
||||
(stage / 'tmb-launcher').chmod(0o755)
|
||||
for name, data in extra:
|
||||
(stage / name).parent.mkdir(parents=True, exist_ok=True)
|
||||
(stage / name).write_bytes(data)
|
||||
path = Path(folder) / 'TMB_Recomp-0.1.1-linux.tar.gz'
|
||||
make_release.tar_dir(str(stage), str(path), 'TMB_Recomp_Bozo', 1700000000)
|
||||
return path
|
||||
|
||||
def test_linux_release_has_one_folder_the_launcher_and_no_other_elf(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
good = self.linux_release(folder)
|
||||
self.assertEqual(make_release.verify_tar(str(good)), [])
|
||||
with tarfile.open(good) as tf:
|
||||
if sys.platform != 'win32':
|
||||
self.assertEqual(tf.getmember('TMB_Recomp_Bozo/tmb-launcher').mode, 0o755)
|
||||
self.assertEqual(tf.getmember('TMB_Recomp_Bozo/README.txt').mode, 0o644)
|
||||
bad = self.linux_release(folder, [('source/tool', b'\x7fELF other'), ('game/SCUS_971.01', b'x')])
|
||||
problems = make_release.verify_tar(str(bad))
|
||||
self.assertTrue(any('source/tool: an ELF file' in p for p in problems), problems)
|
||||
self.assertTrue(any('SCUS_971.01' in p for p in problems), problems)
|
||||
|
||||
def test_linux_release_is_reproducible(self):
|
||||
with tempfile.TemporaryDirectory() as a, tempfile.TemporaryDirectory() as b:
|
||||
self.assertEqual(self.linux_release(a).read_bytes(), self.linux_release(b).read_bytes())
|
||||
|
||||
def test_update_installs_a_linux_release_with_its_launcher_executable(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
path = self.linux_release(folder)
|
||||
make_release.write_sha256(str(path))
|
||||
install = Path(folder) / 'install'
|
||||
(install / 'game').mkdir(parents=True)
|
||||
(install / 'game/keep.txt').write_bytes(b'player')
|
||||
out = subprocess.run([sys.executable, '-I', str(ROOT / 'tools/apply_update.py'), '--zip', str(path),
|
||||
'--sha256', str(path) + '.sha256', '--version', '0.1.1', '--install', str(install),
|
||||
'--keep-zip'], stdout=subprocess.PIPE, universal_newlines=True)
|
||||
self.assertEqual(out.returncode, 0, out.stdout)
|
||||
self.assertIn('done 0.1.1', out.stdout)
|
||||
self.assertTrue(os.access(install / 'tmb-launcher', os.X_OK) or sys.platform == 'win32')
|
||||
self.assertEqual((install / 'game/keep.txt').read_bytes(), b'player')
|
||||
|
||||
def test_update_refuses_a_link_in_a_linux_release(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
path = Path(folder) / 'linked.tar.gz'
|
||||
with tarfile.open(path, 'w:gz') as tf:
|
||||
link = tarfile.TarInfo('TMB_Recomp_Bozo/source/escape')
|
||||
link.type, link.linkname = tarfile.SYMTYPE, '/etc'
|
||||
tf.addfile(link)
|
||||
with self.assertRaises(apply_update.UpdateError):
|
||||
apply_update.Archive(str(path))
|
||||
|
||||
|
||||
class LinuxBuildTests(unittest.TestCase):
|
||||
def test_missing_tools_are_named_with_the_distribution_command(self):
|
||||
with patch.object(tmb_build.shutil, 'which', lambda name, **_k: None if name == 'ninja' else '/usr/bin/' + name), \
|
||||
patch.object(tmb_build.subprocess, 'run', lambda cmd, **_k: SimpleNamespace(
|
||||
returncode=1 if cmd[-1] in ('libavutil', 'x11', 'wayland-client') else 0)):
|
||||
missing = tmb_build.linux_missing()
|
||||
self.assertEqual(missing, ['ninja', 'FFmpeg (libavutil)', 'X11 or Wayland (x11 or wayland-client)'])
|
||||
with patch.object(tmb_build, 'linux_family', lambda: 'fedora'):
|
||||
self.assertIn('sudo dnf install', tmb_build.linux_missing_message(missing))
|
||||
with patch.object(tmb_build, 'linux_family', lambda: None):
|
||||
self.assertIn('sudo apt install', tmb_build.linux_missing_message(missing))
|
||||
|
||||
def test_a_linux_kit_gives_the_libraries_sources_and_keeps_the_system_toolchain(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
kit = Path(folder) / 'kit'
|
||||
(kit / 'deps').mkdir(parents=True)
|
||||
(kit / 'kit_manifest.json').write_text('{"platform": "linux"}')
|
||||
args = SimpleNamespace(out=str(Path(folder) / 'out'), game=None, toolchain=None, fetch_cache=None,
|
||||
debug_info=None, kit=str(kit), no_kit=False)
|
||||
build = tmb_build.Build(args)
|
||||
self.assertEqual(build.kit, str(kit))
|
||||
self.assertIsNone(args.toolchain)
|
||||
self.assertIsNone(build.ffmpeg_root)
|
||||
self.assertEqual(args.fetch_cache, str(kit / 'deps'))
|
||||
|
||||
|
||||
class TimingTests(unittest.TestCase):
|
||||
LOG = '''[tmb:clock] frame 300: EE 5.000 s, PC 5.000 s, debt 0.0 ms; ticks 2880000 fields 300
|
||||
@@ -284,5 +390,120 @@ class TimingTests(unittest.TestCase):
|
||||
self.assertTrue(check_timing.check('')[0].startswith('FAIL:'))
|
||||
|
||||
|
||||
class RecompLauncherTests(unittest.TestCase):
|
||||
"""recomplauncher.json (RecompLauncher's manifest, recomplauncher.com/sdk) and what it runs."""
|
||||
|
||||
def manifest(self):
|
||||
return json.loads((ROOT / 'recomplauncher.json').read_text(encoding='utf-8'))
|
||||
|
||||
def test_progress_lines_follow_the_steps(self):
|
||||
self.assertEqual(tmb_build.progress_line(('PROGRESS', 'verify', '1/8', 'Checking the disc')),
|
||||
'progress 0.000 Checking the disc')
|
||||
before = sum(tmb_build.STEP_WEIGHTS[s] for s in tmb_build.STEPS[:tmb_build.STEPS.index('packs')])
|
||||
half = (before + tmb_build.STEP_WEIGHTS['packs'] / 2) / sum(tmb_build.STEP_WEIGHTS.values())
|
||||
self.assertEqual(tmb_build.progress_line(('PERCENT', 'packs', 50)),
|
||||
'progress %.3f %s (50%%)' % (half, tmb_build.STEP_TITLES['packs']))
|
||||
for other in (('SKIP', 'verify', '1/8'), ('DONE', 'stage', '8/8', 1.0), ('INFO', 'total', '1 s'),
|
||||
('ERROR', 'compile', 'x')):
|
||||
self.assertIsNone(tmb_build.progress_line(other))
|
||||
self.assertEqual(set(tmb_build.STEP_WEIGHTS), set(tmb_build.STEPS))
|
||||
# The launcher's own step weights (its progress bar), so both bars move alike.
|
||||
model = (ROOT / 'launcher' / 'src' / 'build_model.cpp').read_text(encoding='utf-8')
|
||||
self.assertEqual(dict((k, int(v)) for k, v in re.findall(r'\{"([a-z]+)", ([0-9]+)\}', model)),
|
||||
tmb_build.STEP_WEIGHTS)
|
||||
shares = []
|
||||
for step in tmb_build.STEPS:
|
||||
for parts in (('PROGRESS', step, '', ''), ('PERCENT', step, 37), ('PERCENT', step, 100)):
|
||||
shares.append(float(tmb_build.progress_line(parts).split()[1]))
|
||||
self.assertEqual(shares, sorted(shares))
|
||||
self.assertTrue(0 <= shares[0] and shares[-1] < 1)
|
||||
|
||||
def test_a_missing_disc_says_why_and_an_earlier_build_keeps_one(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
def run(*extra):
|
||||
return subprocess.run([sys.executable, '-I', '-X', 'utf8', str(ROOT / 'tools' / 'tmb_build.py'),
|
||||
'--out', str(Path(folder) / 'build'), '--game', str(Path(folder) / 'game')]
|
||||
+ list(extra), capture_output=True, text=True, encoding='utf-8')
|
||||
r = run('--progress-lines')
|
||||
self.assertEqual(r.returncode, 1)
|
||||
self.assertIn('ERROR verify no disc image given', r.stdout.strip().splitlines()[-1])
|
||||
# No --disc: the disc image an earlier build kept in the game folder (keeps_copy). Here it is not a disc.
|
||||
(Path(folder) / 'game').mkdir()
|
||||
(Path(folder) / 'game' / 'disc.iso').write_bytes(b'\0' * 65536)
|
||||
r = run('--check')
|
||||
self.assertEqual(r.returncode, 1)
|
||||
self.assertIn('ERROR verify disc.iso', r.stdout)
|
||||
|
||||
def test_manifest_runs_what_the_release_ships(self):
|
||||
m = self.manifest()
|
||||
self.assertEqual(m['format'], 1)
|
||||
self.assertEqual(m['repo'], 'TheBozos/TMB_Recomp')
|
||||
disc = m['inputs'][0]
|
||||
self.assertEqual(disc['id'], 'game')
|
||||
self.assertEqual(disc['check']['iso9660'], tmb_build.ELF_NAME)
|
||||
self.assertEqual(disc['check']['ids'], ['SCUS-97101'])
|
||||
# Redump's Twisted Metal: Black (USA), SCUS-97101 v1.00: its one dump, a DVD-5 (redump.org/disc/15035).
|
||||
self.assertEqual(disc['dumps'], [{'name': 'USA', 'size': 3799744512, 'crc32': '347e93f9'}])
|
||||
prepare, start = m['prepare'], m['start']
|
||||
# Windows: the kit's Python; Linux: kit/python3, the system's (the first that exists runs).
|
||||
self.assertEqual(prepare['program'], ['kit/python/python.exe', 'kit/python3'])
|
||||
self.assertIn('kit/python/python.exe', REQUIRED)
|
||||
self.assertIn('kit/python3', make_release.LINUX_REQUIRED)
|
||||
self.assertTrue(make_release.LINUX_PYTHON3.startswith('#!/bin/sh'))
|
||||
self.assertIn('{install}/source/tools/tmb_build.py', prepare['args'])
|
||||
self.assertIn('source/tools/tmb_build.py', REQUIRED)
|
||||
# The disc as one argument: RecompLauncher leaves it out when the player's copy is gone (keeps_copy).
|
||||
self.assertTrue(prepare['keeps_copy'])
|
||||
self.assertEqual([a for a in prepare['args'] if '{input:game}' in a], ['--disc={input:game}'])
|
||||
help_text = subprocess.run([sys.executable, '-I', str(ROOT / 'tools' / 'tmb_build.py'), '--help'],
|
||||
capture_output=True, text=True, check=True).stdout
|
||||
for flag in (a.split('=', 1)[0] for a in prepare['args'] if a.startswith('--')):
|
||||
self.assertIn(flag, help_text)
|
||||
self.assertIn('--progress-lines', prepare['args'])
|
||||
# The working folder is the program's (kit/python): every path RecompLauncher passes is {install}'s.
|
||||
for a in prepare['args']:
|
||||
if '/' in a:
|
||||
self.assertTrue(a.split('=', 1)[-1].startswith(('{install}/', '{input:')), a)
|
||||
self.assertEqual(prepare['done'], ['{install}/game/built_from.ini'])
|
||||
self.assertEqual(start['program'], ['game/' + tmb_build.GAME_EXE + '.exe', 'game/' + tmb_build.GAME_EXE])
|
||||
self.assertEqual(set(m['system']), {'windows', 'linux'})
|
||||
self.assertEqual(start['args'], ['--elf', '{install}/game/' + tmb_build.ELF_NAME, '--iso',
|
||||
'{install}/game/disc.iso'])
|
||||
# Everything the game writes (cards, settings, logs, save states) in RecompLauncher's {data}.
|
||||
self.assertEqual(start['env'], {'PS2X_USER_DIR': '{data}'})
|
||||
self.assertEqual(m['saves'], ['{data}/mc0', '{data}/mc1'])
|
||||
|
||||
def test_settings_are_keys_the_game_reads(self):
|
||||
m = self.manifest()
|
||||
self.assertEqual(m['config'], [{'format': 'ini', 'file': [{'path': '{data}/video.ini'}]}])
|
||||
source = ROOT / 'BozoEngine' / 'runtime' / 'app' / 'video_settings.cpp'
|
||||
if not source.is_file():
|
||||
self.skipTest('no BozoEngine tree (cmake -P cmake/bozo_engine_fetch.cmake)')
|
||||
written = set(re.findall(r'<< "([a-z_]+) = "', source.read_text(encoding='utf-8')))
|
||||
self.assertIn('widescreen', written)
|
||||
ids = [s['id'] for s in m['settings']]
|
||||
self.assertEqual(len(ids), len(set(ids)))
|
||||
for setting in m['settings']:
|
||||
keys = set(setting['defaults'])
|
||||
for choice in setting['choices']:
|
||||
self.assertEqual(set(choice['set']), keys, setting['id'])
|
||||
for key in keys:
|
||||
section, name = key.split('/')
|
||||
self.assertEqual(section, 'video')
|
||||
self.assertIn(name, written)
|
||||
values = [c['set'][k] for c in setting['choices'] for k in keys]
|
||||
self.assertEqual(len(values), len(set(values)), setting['id'])
|
||||
self.assertIn(setting['defaults'], [c['set'] for c in setting['choices']], setting['id'])
|
||||
|
||||
def test_release_zip_carries_the_manifest_at_its_top(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
path = Path(folder) / 'no_manifest.zip'
|
||||
with zipfile.ZipFile(path, 'w') as archive:
|
||||
for name in REQUIRED:
|
||||
if name != 'recomplauncher.json':
|
||||
archive.writestr('TMB_Recomp_Bozo/' + name, b'fixture')
|
||||
self.assertIn('TMB_Recomp_Bozo/recomplauncher.json is missing', make_release.verify_zip(path))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
+55
-18
@@ -3,6 +3,7 @@
|
||||
|
||||
python -I tools/apply_update.py --zip <TMB_Recomp-x.y.z-bozo.zip> --sha256 <its .sha256 file> --version x.y.z
|
||||
--install <the release folder> [--keep-zip]
|
||||
python3 -I tools/apply_update.py --zip <TMB_Recomp-x.y.z-linux.tar.gz> ... (the Linux release)
|
||||
|
||||
Checks the zip's SHA-256 against the release's .sha256, checks every name in it (one top folder TMB_Recomp_Bozo/, no
|
||||
absolute or parent paths, nothing under build/, game/ or update/, the launcher and source/release.ini of the version
|
||||
@@ -20,10 +21,11 @@ import hashlib
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tarfile
|
||||
import zipfile
|
||||
|
||||
TOP = 'TMB_Recomp_Bozo/' # the BozoEngine build's zip (tools/make_release.py's TOP)
|
||||
LAUNCHER = 'TMB Launcher.exe'
|
||||
LAUNCHERS = {'zip': 'TMB Launcher.exe', 'tar': 'tmb-launcher'}
|
||||
PROTECTED = ('build/', 'game/', 'update/') # the player's build and game, and this update's own folder
|
||||
|
||||
|
||||
@@ -56,11 +58,41 @@ def expected_sha256(path):
|
||||
return token[0].lower()
|
||||
|
||||
|
||||
def checked_names(zf, version):
|
||||
"""The zip's file entries as (entry, path under the top folder), after checking every name."""
|
||||
class Archive:
|
||||
"""A release's zip (Windows) or .tar.gz (Linux): its entries as (name, is_dir, size, mode), read the same way."""
|
||||
|
||||
def __init__(self, path):
|
||||
if tarfile.is_tarfile(path):
|
||||
self.kind, self.tf = 'tar', tarfile.open(path, 'r:*')
|
||||
self.members = {}
|
||||
for m in self.tf.getmembers():
|
||||
if not (m.isfile() or m.isdir()):
|
||||
raise UpdateError('unexpected entry in the archive: %r (a link or device)' % m.name)
|
||||
name = m.name + ('/' if m.isdir() and not m.name.endswith('/') else '')
|
||||
self.members[name] = m
|
||||
else:
|
||||
self.kind, self.zf = 'zip', zipfile.ZipFile(path)
|
||||
|
||||
def entries(self):
|
||||
if self.kind == 'tar':
|
||||
return [(n, m.isdir(), m.size, m.mode) for n, m in self.members.items()]
|
||||
return [(i.filename, i.filename.endswith('/'), i.file_size, None) for i in self.zf.infolist()]
|
||||
|
||||
def open(self, name):
|
||||
return self.tf.extractfile(self.members[name]) if self.kind == 'tar' else self.zf.open(name)
|
||||
|
||||
def read(self, name):
|
||||
with self.open(name) as f:
|
||||
return f.read()
|
||||
|
||||
def close(self):
|
||||
(self.tf if self.kind == 'tar' else self.zf).close()
|
||||
|
||||
|
||||
def checked_names(archive, version):
|
||||
"""The archive's file entries as (name, size, mode, path under the top folder), after checking every name."""
|
||||
files = []
|
||||
for info in zf.infolist():
|
||||
name = info.filename
|
||||
for name, is_dir, size, mode in archive.entries():
|
||||
if not name.startswith(TOP) or '\\' in name or ':' in name or name.startswith('/'):
|
||||
raise UpdateError('unexpected name in the zip: %r' % name)
|
||||
rel = name[len(TOP):]
|
||||
@@ -68,12 +100,12 @@ def checked_names(zf, version):
|
||||
raise UpdateError('unexpected name in the zip: %r' % name)
|
||||
if rel.startswith(PROTECTED) or rel.rstrip('/') in ('build', 'game', 'update'):
|
||||
raise UpdateError('the zip holds %r, a folder of the player\'s own' % name)
|
||||
if not name.endswith('/'):
|
||||
files.append((info, rel))
|
||||
rels = {rel for _info, rel in files}
|
||||
if LAUNCHER not in rels or 'source/release.ini' not in rels:
|
||||
if not is_dir:
|
||||
files.append((name, size, mode, rel))
|
||||
rels = {f[3] for f in files}
|
||||
if LAUNCHERS[archive.kind] not in rels or 'source/release.ini' not in rels:
|
||||
raise UpdateError('this is not a TMB_Recomp release (no launcher or source/release.ini)')
|
||||
stamp = zf.read(TOP + 'source/release.ini').decode('utf-8', 'replace')
|
||||
stamp = archive.read(TOP + 'source/release.ini').decode('utf-8', 'replace')
|
||||
found = ''
|
||||
for line in stamp.splitlines():
|
||||
key, _, value = line.partition('=')
|
||||
@@ -135,24 +167,29 @@ def main():
|
||||
|
||||
say('step extract')
|
||||
remove_tree(staging)
|
||||
with zipfile.ZipFile(args.zip) as zf:
|
||||
files = checked_names(zf, args.version)
|
||||
total = sum(info.file_size for info, _rel in files)
|
||||
archive = Archive(args.zip)
|
||||
try:
|
||||
files = checked_names(archive, args.version)
|
||||
total = sum(f[1] for f in files)
|
||||
if shutil.disk_usage(install).free < total + (256 << 20):
|
||||
raise UpdateError('not enough free space: %d MB needed' % ((total >> 20) + 256))
|
||||
done = 0
|
||||
for info, rel in files:
|
||||
for name, size, mode, rel in files:
|
||||
target = os.path.join(staging, *rel.split('/'))
|
||||
os.makedirs(os.path.dirname(target), exist_ok=True)
|
||||
with zf.open(info) as src, open(target, 'wb') as dst:
|
||||
with archive.open(name) as src, open(target, 'wb') as dst:
|
||||
shutil.copyfileobj(src, dst, 1 << 20)
|
||||
done += info.file_size
|
||||
if mode is not None:
|
||||
os.chmod(target, 0o755 if mode & 0o111 else 0o644)
|
||||
done += size
|
||||
say('progress', done, total)
|
||||
finally:
|
||||
archive.close()
|
||||
|
||||
# Everything is extracted and checked: only moves on the same disk from here.
|
||||
say('step install')
|
||||
old_files = []
|
||||
for n, (_info, rel) in enumerate(files):
|
||||
for n, (_name, _size, _mode, rel) in enumerate(files):
|
||||
replace(os.path.join(staging, *rel.split('/')), os.path.join(install, *rel.split('/')), old_files)
|
||||
if n % 200 == 0:
|
||||
say('progress', n, len(files))
|
||||
@@ -175,6 +212,6 @@ def main():
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except (UpdateError, OSError, zipfile.BadZipFile) as e:
|
||||
except (UpdateError, OSError, zipfile.BadZipFile, tarfile.TarError) as e:
|
||||
say('error', e)
|
||||
sys.exit(1)
|
||||
+24
-10
@@ -2,7 +2,7 @@
|
||||
"""make_build_kit: assembles the build kit tools/tmb_build.py uses on a PC with nothing installed (no MSYS2, git,
|
||||
network or Python): a compiler, CMake and Ninja, a minimal static FFmpeg, the libraries' sources (SDL3, Dear ImGui)
|
||||
and an embeddable Python. The game is built on BozoEngine, whose sources come with TMB_Recomp's (the BozoEngine
|
||||
submodule, in a release's source/BozoEngine): its recompiler is built on the player's PC with the rest. Run once on the
|
||||
release cmake/bozo_engine.json pins, in a release's source/BozoEngine): its recompiler is built on the player's PC with the rest. Run once on the
|
||||
developer's PC (MSYS2 UCRT64 installed, network for the downloads); the kit is build output, never committed.
|
||||
|
||||
python tools/make_build_kit.py --out D:/tmb_kit/kit [--downloads D:/tmb_kit/downloads] [--zip D:/tmb_kit/kit.zip]
|
||||
@@ -98,6 +98,15 @@ REALESRGAN = {
|
||||
'sha256': '6495f972a09ad7f64ccd953e79adba91a93d862edc7135e6d95210bbf4002a01'},
|
||||
],
|
||||
}
|
||||
# The same release's Linux build (--linux: the Linux release's kit). It loads the system's libvulkan and libgomp
|
||||
# (GCC's OpenMP runtime, there with the compiler the build needs), so nothing beside it is kept.
|
||||
REALESRGAN_LINUX = dict(REALESRGAN,
|
||||
url='https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/'
|
||||
'realesrgan-ncnn-vulkan-20220424-ubuntu.zip',
|
||||
sha256='e5aa6eb131234b87c0c51f82b89390f5e3e642b7b70f2b9bbe95b6a285a40c96',
|
||||
keep=['realesrgan-ncnn-vulkan', 'models/realesrgan-x4plus.bin',
|
||||
'models/realesrgan-x4plus.param'],
|
||||
license='MIT (realesrgan-ncnn-vulkan) and BSD-3-Clause (Real-ESRGAN, its model; ncnn)')
|
||||
# FetchContent sources: the release archives BozoEngine's CMake files pin (runtime/CMakeLists.txt: URL and URL_HASH),
|
||||
# unpacked as deps/<name>-src for tmb_build's FETCHCONTENT_SOURCE_DIR_<NAME>. 'top': the archive's top folder.
|
||||
DEPS = [
|
||||
@@ -632,26 +641,30 @@ class Kit:
|
||||
# -- realesrgan
|
||||
|
||||
def step_realesrgan(self):
|
||||
z = download(REALESRGAN, self.downloads)
|
||||
spec = REALESRGAN_LINUX if self.args.linux else REALESRGAN
|
||||
z = download(spec, self.downloads)
|
||||
dst = os.path.join(self.out, 'realesrgan')
|
||||
rmtree(dst)
|
||||
with zipfile.ZipFile(z) as zf:
|
||||
names = set(zf.namelist())
|
||||
for keep in REALESRGAN['keep']:
|
||||
for keep in spec['keep']:
|
||||
if keep not in names:
|
||||
raise KitError('%s: %s is not in the zip' % (os.path.basename(z), keep))
|
||||
target = os.path.join(dst, *keep.split('/'))
|
||||
os.makedirs(os.path.dirname(target), exist_ok=True)
|
||||
with zf.open(keep) as src, open(target, 'wb') as out:
|
||||
shutil.copyfileobj(src, out)
|
||||
if '.' not in os.path.basename(keep): # the Linux program
|
||||
os.chmod(target, 0o755)
|
||||
lic = self.licenses_dir('realesrgan')
|
||||
for spec in REALESRGAN['licenses']:
|
||||
shutil.copy2(download(spec, self.downloads), os.path.join(lic, spec['file']))
|
||||
with open(os.path.join(lic, 'vcomp140.txt'), 'w', encoding='utf-8', newline='\n') as f:
|
||||
f.write('vcomp140.dll is Microsoft\'s OpenMP runtime, part of the Visual C++ Redistributable, shipped in the '
|
||||
'Real-ESRGAN release zip next to the program that loads it.\n')
|
||||
self.part('realesrgan', {k: v for k, v in REALESRGAN.items() if k != 'licenses'})
|
||||
log(' realesrgan %s' % REALESRGAN['version'])
|
||||
for license_spec in spec['licenses']:
|
||||
shutil.copy2(download(license_spec, self.downloads), os.path.join(lic, license_spec['file']))
|
||||
if not self.args.linux:
|
||||
with open(os.path.join(lic, 'vcomp140.txt'), 'w', encoding='utf-8', newline='\n') as f:
|
||||
f.write('vcomp140.dll is Microsoft\'s OpenMP runtime, part of the Visual C++ Redistributable, shipped in '
|
||||
'the Real-ESRGAN release zip next to the program that loads it.\n')
|
||||
self.part('realesrgan', {k: v for k, v in spec.items() if k != 'licenses'})
|
||||
log(' realesrgan %s (%s)' % (spec['version'], 'Linux' if self.args.linux else 'Windows'))
|
||||
|
||||
# -- deps
|
||||
|
||||
@@ -1147,6 +1160,7 @@ def main():
|
||||
ap.add_argument('--only', choices=STEPS, action='append', help='run only these steps')
|
||||
ap.add_argument('--zip', help='also write the kit as this .zip')
|
||||
ap.add_argument('--jobs', type=int, default=os.cpu_count() or 4)
|
||||
ap.add_argument('--linux', action='store_true', help='the Linux release\'s parts (realesrgan: its Linux build)')
|
||||
ap.add_argument('--install-packages', action='store_true', help='only install the pinned MSYS2 packages '
|
||||
'(tools/build_kit_packages.json) into --msys with pacman -U, their files SHA-256 checked')
|
||||
ap.add_argument('--install-dry-run', action='store_true', help='with --install-packages: pacman --print only')
|
||||
|
||||
+427
-32
@@ -8,9 +8,10 @@ redistributes.
|
||||
python tools/make_release.py --out D:/tmb_release --publish --dry-run (the version from the commit's tag)
|
||||
|
||||
What it does, from <commit> (default HEAD; only committed files count, the working tree is never read):
|
||||
export git archive of the commit and of the BozoEngine submodule at the commit it records (without its
|
||||
reference/ records, which the build never reads) -> source\\ (no .git, no build/, nothing generated);
|
||||
source\\release.ini stamps the version and both commits. The tree is audited: no ELF, IRX, disc image,
|
||||
export git archive of the commit -> source\\ (no .git, no build/, nothing generated), and the BozoEngine
|
||||
release its cmake/bozo_engine.json pins -> source\\BozoEngine (cmake/bozo_engine_fetch.cmake: the
|
||||
release's archive, SHA-256 checked); source\\release.ini stamps the version, the commit and the
|
||||
engine's version. The tree is audited: no ELF, IRX, disc image,
|
||||
pack, generated code or disc file name may be in it.
|
||||
kit the build kit (--kit <dir>: an existing one, hard-linked into the release; else assembled by
|
||||
tools/make_build_kit.py, which needs MSYS2 and the network): a BozoEngine kit (kit_version 2: SDL3 and
|
||||
@@ -27,7 +28,8 @@ What it does, from <commit> (default HEAD; only committed files count, the worki
|
||||
changelog CHANGELOG.md's section for the version (## [x.y.z], Keep a Changelog), from the commit: the release
|
||||
refuses to be made without one (an empty one, or only "Unreleased", too) unless
|
||||
--allow-missing-changelog (test builds). CHANGELOG.md is shipped at the zip's top (the launcher's
|
||||
"What's new" reads it) and the section is the release notes' "What's new".
|
||||
"What's new" reads it) and the section is the release notes' "What's new". recomplauncher.json (the
|
||||
commit's) is shipped at the zip's top too, where RecompLauncher reads it.
|
||||
zip TMB_Recomp-<version>.zip (deflate, entries sorted, every timestamp the commit's), <zip>.sha256,
|
||||
RELEASE_NOTES.md (the changelog section, the hashes, the source offer: the GitHub release's body). The
|
||||
zip's names are audited again.
|
||||
@@ -43,6 +45,7 @@ What it does, from <commit> (default HEAD; only committed files count, the worki
|
||||
Standard library only (Python 3.8+; the kit's embeddable Python runs it too). Needs git; gh only for --publish.
|
||||
"""
|
||||
import argparse
|
||||
import gzip
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
@@ -60,14 +63,17 @@ import zipfile
|
||||
ROOT = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))
|
||||
REPO = 'TheBozos/TMB_Recomp'
|
||||
ENGINE_REPO = 'TheBozos/BozoEngine'
|
||||
ENGINE_DIR = 'BozoEngine' # the submodule
|
||||
# What BozoEngine's export leaves out (its reference records: hashes of recorded runs, never read by the build).
|
||||
ENGINE_SKIP = ('reference',)
|
||||
ENGINE_DIR = 'BozoEngine' # the release cmake/bozo_engine.json pins
|
||||
NAME = 'TMB_Recomp'
|
||||
# The BozoEngine build: its zips are <NAME>-<version>-bozo(.zip, -sources.zip) and the folder in them TOP, so they
|
||||
# sit beside the fork build's (<NAME>-<version>.zip, folder TMB_Recomp) on a release page and on a player's disk.
|
||||
FLAVOR = 'bozo'
|
||||
TOP = 'TMB_Recomp_Bozo'
|
||||
# The Linux release: <NAME>-<version>-linux.tar.gz, the same top folder, the launcher built for Linux.
|
||||
LINUX_SUFFIX = '-linux.tar.gz'
|
||||
LINUX_LAUNCHER = 'tmb-launcher'
|
||||
# RecompLauncher's manifest (recomplauncher.com/sdk): at the repo's top, shipped at the zip's top.
|
||||
RECOMPLAUNCHER_JSON = 'recomplauncher.json'
|
||||
VERSION_RE = re.compile(r'^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$')
|
||||
MSYS2_SOURCES = 'https://repo.msys2.org/mingw/sources/'
|
||||
# The launcher's font (launcher/CMakeLists.txt pins the same commit and hash).
|
||||
@@ -265,6 +271,15 @@ def parse_ini(path):
|
||||
return out
|
||||
|
||||
|
||||
def remove_bytecode_caches(folder):
|
||||
"""Python's bytecode caches (__pycache__/) a step left in the release folder (importing tmb_build from the
|
||||
exported source writes one): they hold the build machine's paths, and the player's Python makes its own."""
|
||||
for dirpath, dirnames, _files in os.walk(folder):
|
||||
if '__pycache__' in dirnames:
|
||||
rmtree(os.path.join(dirpath, '__pycache__'))
|
||||
dirnames.remove('__pycache__')
|
||||
|
||||
|
||||
def pe_imports_of(path, tools_dir):
|
||||
sys.path.insert(0, tools_dir)
|
||||
try:
|
||||
@@ -375,7 +390,7 @@ class Release:
|
||||
self.migration_zip = os.path.join(self.out, '%s-%s.zip' % (NAME, self.version))
|
||||
self.sources_zip = os.path.join(self.out, self.name + '-sources.zip')
|
||||
self.commit_date = int(git('show', '-s', '--format=%ct', self.commit))
|
||||
self.engine_commit = None
|
||||
self.engine_version = None
|
||||
self.manifest = None
|
||||
self.msys_sources = [] # (package base, version, licence, url, file, sha256)
|
||||
|
||||
@@ -396,21 +411,16 @@ class Release:
|
||||
rmtree(self.stage)
|
||||
os.makedirs(self.source)
|
||||
extract_tar_stream([find_git(), 'archive', '--format=tar', self.commit], self.source, ROOT)
|
||||
entry = git('ls-tree', self.commit, ENGINE_DIR).split()
|
||||
if len(entry) < 3 or entry[0] != '160000':
|
||||
raise ReleaseError('%s is not a submodule at %s' % (ENGINE_DIR, self.commit))
|
||||
self.engine_commit = entry[2]
|
||||
engine_repo = os.path.join(ROOT, ENGINE_DIR)
|
||||
try:
|
||||
git('cat-file', '-e', self.engine_commit + '^{commit}', cwd=engine_repo)
|
||||
except ReleaseError:
|
||||
raise ReleaseError('the submodule does not have %s: git submodule update --init %s'
|
||||
% (self.engine_commit, ENGINE_DIR))
|
||||
engine_dst = os.path.join(self.source, ENGINE_DIR)
|
||||
os.makedirs(engine_dst, exist_ok=True)
|
||||
extract_tar_stream([find_git(), 'archive', '--format=tar', self.engine_commit], engine_dst, engine_repo)
|
||||
for skip in ENGINE_SKIP:
|
||||
rmtree(os.path.join(engine_dst, skip))
|
||||
with open(os.path.join(self.source, 'cmake', 'bozo_engine.json'), encoding='utf-8') as f:
|
||||
self.engine_version = json.load(f)['version']
|
||||
cmake = shutil.which('cmake')
|
||||
if not cmake and os.path.isfile(os.path.join(self.args.msys, 'ucrt64', 'bin', 'cmake.exe')):
|
||||
cmake = os.path.join(self.args.msys, 'ucrt64', 'bin', 'cmake.exe')
|
||||
if not cmake:
|
||||
raise ReleaseError('no cmake on PATH: it fetches the BozoEngine release (cmake/bozo_engine_fetch.cmake)')
|
||||
os.makedirs(self.downloads, exist_ok=True)
|
||||
run([cmake, '-DBOZO_ENGINE_DOWNLOADS=' + self.downloads, '-P',
|
||||
os.path.join(self.source, 'cmake', 'bozo_engine_fetch.cmake')])
|
||||
# The list of the source's files: tmb_build removes the ones a newer release unzipped over this one no longer
|
||||
# has (CMake globs runtime/*.cpp: a deleted file left behind would still be compiled).
|
||||
files = sorted(os.path.relpath(os.path.join(d, n), self.source).replace('\\', '/')
|
||||
@@ -419,14 +429,14 @@ class Release:
|
||||
write_text(os.path.join(self.source, 'release_files.txt'), '\n'.join(sorted(set(files))) + '\n')
|
||||
write_text(os.path.join(self.source, 'release.ini'),
|
||||
'# The TMB_Recomp release this folder is (tools/make_release.py writes this file).\n'
|
||||
'version = %s\ncommit = %s\nengine = BozoEngine\nengine_commit = %s\ndate = %s\n'
|
||||
% (self.version, self.commit, self.engine_commit,
|
||||
'version = %s\ncommit = %s\nengine = BozoEngine\nengine_version = %s\ndate = %s\n'
|
||||
% (self.version, self.commit, self.engine_version,
|
||||
time.strftime('%Y-%m-%d', time.gmtime(self.commit_date))))
|
||||
problems = audit_tree(self.source, rel_prefix='source/')
|
||||
if problems:
|
||||
raise ReleaseError('the source export holds what looks like game data:\n ' + '\n '.join(problems[:20]))
|
||||
n = sum(len(f) for _d, _s, f in os.walk(self.source))
|
||||
log(' source: %s + BozoEngine %s, %d files, %.1f MB, audited' % (self.commit[:12], self.engine_commit[:12], n,
|
||||
log(' source: %s + BozoEngine %s, %d files, %.1f MB, audited' % (self.commit[:12], self.engine_version, n,
|
||||
dir_size(self.source) / 1e6))
|
||||
|
||||
# -- the kit
|
||||
@@ -639,7 +649,7 @@ class Release:
|
||||
'TMB_Recomp (source\\, this release\'s code; MIT, LICENSES\\TMB_Recomp)',
|
||||
' https://github.com/%s/tree/%s' % (REPO, self.commit),
|
||||
'BozoEngine, the recompiler and runtime the game is built on (source\\BozoEngine; MIT, LICENSES\\BozoEngine)',
|
||||
' https://github.com/%s/tree/%s' % (ENGINE_REPO, self.engine_commit),
|
||||
' https://github.com/%s/releases/tag/v%s' % (ENGINE_REPO, self.engine_version),
|
||||
' The whole source is in source\\ already, the launcher\'s too (source\\launcher).',
|
||||
'',
|
||||
'The build kit (kit\\) redistributes these programs and libraries unmodified. Their corresponding source:',
|
||||
@@ -775,6 +785,10 @@ class Release:
|
||||
at = at + 1 if at >= 0 else len(text)
|
||||
text = text[:at] + '## [%s] - test build\n\n%s\n\n' % (self.version, self.changelog_section) + text[at:]
|
||||
write_text(os.path.join(self.stage, 'CHANGELOG.md'), text, crlf=True)
|
||||
# RecompLauncher's manifest at the top, next to the launcher, where RecompLauncher reads it: the commit's.
|
||||
manifest = git('show', '%s:%s' % (self.commit, RECOMPLAUNCHER_JSON), binary=True)
|
||||
with open(os.path.join(self.stage, RECOMPLAUNCHER_JSON), 'wb') as f:
|
||||
f.write(manifest)
|
||||
|
||||
# -- the changelog
|
||||
|
||||
@@ -800,6 +814,7 @@ class Release:
|
||||
return '_A test build: no changelog entry for %s._' % self.version
|
||||
|
||||
def step_zip(self):
|
||||
remove_bytecode_caches(self.stage)
|
||||
problems = [p for p in audit_tree(self.stage, allow_pe=True)]
|
||||
if problems:
|
||||
raise ReleaseError('the release folder holds what looks like game data:\n ' + '\n '.join(problems[:20]))
|
||||
@@ -851,8 +866,13 @@ class Release:
|
||||
'Then **Rebuild now** when the launcher offers it. Saves and settings stay in `%APPDATA%\\TMB_Recomp`. '
|
||||
'Subsequent BozoEngine updates use `-bozo.zip` with either installation folder name.',
|
||||
'',
|
||||
]
|
||||
linux = self.linux_archive()
|
||||
if linux:
|
||||
lines += linux_download_lines(os.path.basename(linux), sha256_of_file_record(linux))
|
||||
lines += [
|
||||
'## Build information', '',
|
||||
'- Code: %s (`%s`), BozoEngine `%s`' % (REPO, self.commit, self.engine_commit),
|
||||
'- Code: %s (`%s`), BozoEngine %s' % (REPO, self.commit, self.engine_version),
|
||||
'- Build kit: GCC %s, CMake %s, Ninja %s (MSYS2 UCRT64), FFmpeg %s (LGPL, static), Python %s'
|
||||
% (self.pkg_version('gcc'), self.pkg_version('cmake'), self.pkg_version('ninja'),
|
||||
self.manifest['ffmpeg']['version'], self.manifest['python']['version']),
|
||||
@@ -865,6 +885,9 @@ class Release:
|
||||
sdig = f.read().split()[0]
|
||||
lines.append('- `%s-sources.zip`: %.1f MB, SHA-256 `%s`' % (self.name, os.path.getsize(self.sources_zip) / 1e6,
|
||||
sdig))
|
||||
if linux:
|
||||
lines.append('- `%s`: %.1f MB, SHA-256 `%s`' % (os.path.basename(linux), os.path.getsize(linux) / 1e6,
|
||||
sha256_of_file_record(linux)))
|
||||
lines += [
|
||||
'', '## Source code and licences', '',
|
||||
'The code is in the zip (`source\\`) and at the commit above: our own code and BozoEngine (the recompiler '
|
||||
@@ -882,6 +905,11 @@ class Release:
|
||||
write_text(os.path.join(self.out, 'RELEASE_NOTES.md'), '\n'.join(lines))
|
||||
log(' RELEASE_NOTES.md (the changelog section for %s, the hashes, the source offer)' % self.version)
|
||||
|
||||
def linux_archive(self):
|
||||
"""The Linux release a run with --linux left in --out (with its .sha256), else None."""
|
||||
path = os.path.join(self.out, linux_archive_name(self.version))
|
||||
return path if os.path.isfile(path) and os.path.isfile(path + '.sha256') else None
|
||||
|
||||
def pkg_version(self, name):
|
||||
info = self.manifest['toolchain']['msys2_packages'].get(name)
|
||||
return info['version'] if info else '?'
|
||||
@@ -892,6 +920,11 @@ class Release:
|
||||
assets += [self.sources_zip, self.sources_zip + '.sha256']
|
||||
else:
|
||||
log(' WARNING: no %s: the GPL source would not be attached' % os.path.basename(self.sources_zip))
|
||||
linux = self.linux_archive()
|
||||
if linux:
|
||||
assets += [linux, linux + '.sha256']
|
||||
else:
|
||||
log(' WARNING: no %s: the release would have no Linux download' % linux_archive_name(self.version))
|
||||
cmd = ['gh', 'release', 'create', 'v' + self.version, '--repo', REPO, '--draft', '--target', self.commit,
|
||||
'--title', '%s %s' % (NAME, self.version), '--notes-file', os.path.join(self.out, 'RELEASE_NOTES.md')]
|
||||
if '-' in self.version:
|
||||
@@ -930,6 +963,13 @@ class Release:
|
||||
problems = verify_zip(self.migration_zip, top=NAME)
|
||||
if problems or not sha256_matches(self.migration_zip):
|
||||
raise ReleaseError('migration zip audit or SHA-256 failed: %s' % problems)
|
||||
linux = self.linux_archive()
|
||||
if linux:
|
||||
problems = verify_tar(linux)
|
||||
if problems:
|
||||
raise ReleaseError('%s:\n %s' % (linux, '\n '.join(problems[:40])))
|
||||
if not sha256_matches(linux):
|
||||
raise ReleaseError('%s does not match its .sha256' % linux)
|
||||
self.publish()
|
||||
|
||||
def main(self):
|
||||
@@ -955,6 +995,229 @@ class Release:
|
||||
log('done in %.0f s: %s' % (time.time() - t0, self.zip))
|
||||
|
||||
|
||||
class LinuxRelease(Release):
|
||||
"""--linux: <name>-linux.tar.gz, the Linux player's download. The same source/ as the zip's, a kit/ with only
|
||||
the libraries' sources (deps/: SDL3, Dear ImGui; the compiler, Python and FFmpeg are the system's), the launcher
|
||||
built for Linux (tmb-launcher), the licences and a README. No GPL binary is redistributed: no sources zip."""
|
||||
|
||||
def __init__(self, args):
|
||||
super().__init__(args)
|
||||
self.archive = os.path.join(self.out, linux_archive_name(self.version))
|
||||
self.stage = os.path.join(self.out, self.name + '-linux')
|
||||
self.source = os.path.join(self.stage, 'source')
|
||||
self.kit = os.path.join(self.stage, 'kit')
|
||||
|
||||
def step_kit(self):
|
||||
rmtree(self.kit)
|
||||
if self.args.kit:
|
||||
src = os.path.join(os.path.abspath(self.args.kit), 'deps')
|
||||
if not os.path.isdir(src):
|
||||
raise ReleaseError('%s has no deps/ (--kit)' % self.args.kit)
|
||||
link_tree(src, os.path.join(self.kit, 'deps'))
|
||||
deps = realesrgan = {}
|
||||
else:
|
||||
work = os.path.join(self.work, 'kit-work')
|
||||
run(self.kit_tool() + ['--out', self.kit, '--only', 'deps', '--only', 'realesrgan', '--linux',
|
||||
'--downloads', self.downloads, '--work', work])
|
||||
with open(os.path.join(self.kit, '.parts', 'deps.json')) as f:
|
||||
deps = json.load(f)
|
||||
with open(os.path.join(self.kit, '.parts', 'realesrgan.json')) as f:
|
||||
realesrgan = json.load(f)
|
||||
rmtree(os.path.join(self.kit, '.parts'))
|
||||
for name in ('sdl3', 'imgui'):
|
||||
if not os.path.isdir(os.path.join(self.kit, 'deps', name + '-src')):
|
||||
raise ReleaseError('the Linux kit has no deps/%s-src' % name)
|
||||
# recomplauncher.json's prepare runs kit/python/python.exe on Windows and this on Linux: the system's python3.
|
||||
write_text(os.path.join(self.kit, 'python3'), LINUX_PYTHON3)
|
||||
os.chmod(os.path.join(self.kit, 'python3'), 0o755)
|
||||
self.manifest = {'kit': NAME + ' build kit', 'kit_version': self.kit_version(), 'engine': 'BozoEngine',
|
||||
'platform': 'linux', 'made_from': self.commit,
|
||||
'layout': {'deps': '<name>-src FetchContent sources: sdl3, imgui (the compiler, Python and '
|
||||
'FFmpeg are the system\'s)',
|
||||
'realesrgan': 'Real-ESRGAN ncnn-vulkan (Linux) and its realesrgan-x4plus model '
|
||||
'(the optional enhanced textures)',
|
||||
'licenses': 'license files per component'},
|
||||
'deps': deps, 'realesrgan': realesrgan}
|
||||
with open(os.path.join(self.kit, 'kit_manifest.json'), 'w') as f:
|
||||
json.dump(self.manifest, f, indent=1)
|
||||
log(' kit (Linux, libraries\' sources only): %.1f MB' % (dir_size(self.kit) / 1e6))
|
||||
|
||||
def kit_version(self):
|
||||
text = open(os.path.join(self.source, 'tools', 'make_build_kit.py'), encoding='utf-8').read()
|
||||
m = re.search(r'^KIT_VERSION = (\d+)', text, re.M)
|
||||
return int(m.group(1)) if m else None
|
||||
|
||||
def step_launcher(self):
|
||||
build = os.path.join(self.work, 'launcher-build')
|
||||
rmtree(build)
|
||||
deps = os.path.join(self.kit, 'deps')
|
||||
logf = os.path.join(self.work, 'launcher.log')
|
||||
cmake = shutil.which('cmake')
|
||||
if not cmake or not shutil.which('ninja'):
|
||||
raise ReleaseError('the Linux launcher needs cmake and ninja on the PATH')
|
||||
run([cmake, '-S', os.path.join(self.source, 'launcher'), '-B', build, '-G', 'Ninja',
|
||||
'-DCMAKE_BUILD_TYPE=Release', '-DFETCHCONTENT_FULLY_DISCONNECTED=ON',
|
||||
'-DFETCHCONTENT_SOURCE_DIR_SDL3=' + os.path.join(deps, 'sdl3-src'),
|
||||
'-DFETCHCONTENT_SOURCE_DIR_IMGUI=' + os.path.join(deps, 'imgui-src'),
|
||||
'-DLAUNCHER_FONT_DIR=' + self.font_dir(),
|
||||
'-DLAUNCHER_VERSION=' + self.version, '-DLAUNCHER_COMMIT=' + self.commit], logfile=logf)
|
||||
run([cmake, '--build', build, '-j', str(self.args.jobs)], logfile=logf)
|
||||
exe = os.path.join(build, LINUX_LAUNCHER)
|
||||
if not os.path.isfile(exe):
|
||||
raise ReleaseError('the launcher build made no %s' % exe)
|
||||
dest = os.path.join(self.stage, LINUX_LAUNCHER)
|
||||
strip = shutil.which('strip')
|
||||
if strip:
|
||||
run([strip, '-o', dest, exe], logfile=logf)
|
||||
else:
|
||||
shutil.copy2(exe, dest)
|
||||
os.chmod(dest, 0o755)
|
||||
libs = linked_libraries(dest)
|
||||
log(' %s: %.1f MB, needs %s' % (LINUX_LAUNCHER, os.path.getsize(dest) / 1e6, ', '.join(libs) or '?'))
|
||||
|
||||
def step_licenses(self):
|
||||
lic = os.path.join(self.stage, 'LICENSES')
|
||||
rmtree(lic)
|
||||
for name, src in (('TMB_Recomp', os.path.join(self.source, 'LICENSE')),
|
||||
('BozoEngine', os.path.join(self.source, ENGINE_DIR, 'LICENSE'))):
|
||||
if not os.path.isfile(src):
|
||||
raise ReleaseError('%s has no LICENSE at this commit (%s)' % (name, src))
|
||||
os.makedirs(os.path.join(lic, name))
|
||||
shutil.copy2(src, os.path.join(lic, name, 'LICENSE'))
|
||||
for name in sorted(os.listdir(os.path.join(self.kit, 'deps'))):
|
||||
src = os.path.join(self.kit, 'deps', name)
|
||||
files = [n for n in os.listdir(src) if re.match(r'(LICEN[CS]E|COPYING|NOTICE)', n, re.I)
|
||||
and os.path.isfile(os.path.join(src, n))]
|
||||
if files:
|
||||
d = os.path.join(lic, 'libraries', name[:-4] if name.endswith('-src') else name)
|
||||
os.makedirs(d, exist_ok=True)
|
||||
for n in files:
|
||||
shutil.copy2(os.path.join(src, n), d)
|
||||
esrgan = os.path.join(self.kit, 'licenses', 'realesrgan')
|
||||
if os.path.isdir(esrgan):
|
||||
shutil.copytree(esrgan, os.path.join(lic, 'realesrgan'))
|
||||
os.makedirs(os.path.join(lic, 'launcher-font-exo2'))
|
||||
shutil.copy2(os.path.join(self.font_dir(), 'OFL.txt'), os.path.join(lic, 'launcher-font-exo2', 'OFL.txt'))
|
||||
write_text(os.path.join(lic, 'README.txt'), LINUX_LICENSES_README.format(name=self.name))
|
||||
log(' LICENSES: %d files' % sum(len(f) for _d, _s, f in os.walk(lic)))
|
||||
|
||||
def step_readme(self):
|
||||
write_text(os.path.join(self.stage, 'README.txt'),
|
||||
LINUX_README.format(version=self.version, name=self.name, repo=REPO,
|
||||
archive=os.path.basename(self.archive)))
|
||||
text = self.changelog_text()
|
||||
if text is not None:
|
||||
text = text.replace('\r\n', '\n')
|
||||
if changelog_section(text, self.version) is None and self.args.allow_missing_changelog:
|
||||
at = text.find('\n## ')
|
||||
at = at + 1 if at >= 0 else len(text)
|
||||
text = text[:at] + '## [%s] - test build\n\n%s\n\n' % (self.version, self.changelog_section) + text[at:]
|
||||
write_text(os.path.join(self.stage, 'CHANGELOG.md'), text)
|
||||
manifest = git('show', '%s:%s' % (self.commit, RECOMPLAUNCHER_JSON), binary=True)
|
||||
with open(os.path.join(self.stage, RECOMPLAUNCHER_JSON), 'wb') as f:
|
||||
f.write(manifest)
|
||||
|
||||
def step_tar(self):
|
||||
remove_bytecode_caches(self.stage)
|
||||
problems = audit_tree(self.stage, allow_pe=True)
|
||||
problems = [p for p in problems if not p.startswith(tuple(n + ':' for n in LINUX_PROGRAMS))]
|
||||
if problems:
|
||||
raise ReleaseError('the release folder holds what looks like game data:\n ' + '\n '.join(problems[:20]))
|
||||
t = time.time()
|
||||
tar_dir(self.stage, self.archive, TOP, self.commit_date)
|
||||
problems = verify_tar(self.archive)
|
||||
if problems:
|
||||
raise ReleaseError('%s:\n %s' % (self.archive, '\n '.join(problems[:40])))
|
||||
digest = write_sha256(self.archive)
|
||||
with tarfile.open(self.archive) as tf:
|
||||
n = len(tf.getmembers())
|
||||
log(' %s: %d entries, %.1f MB (unpacked %.1f MB), %.0f s, SHA-256 %s'
|
||||
% (os.path.basename(self.archive), n, os.path.getsize(self.archive) / 1e6, dir_size(self.stage) / 1e6,
|
||||
time.time() - t, digest))
|
||||
|
||||
def main(self):
|
||||
os.makedirs(self.work, exist_ok=True)
|
||||
log('%s from %s' % (os.path.basename(self.archive), self.commit))
|
||||
self.changelog_section = self.changelog()
|
||||
t0 = time.time()
|
||||
for name, fn in (('export', self.step_export), ('kit', self.step_kit), ('launcher', self.step_launcher),
|
||||
('licenses', self.step_licenses), ('readme', self.step_readme), ('tar', self.step_tar)):
|
||||
log('[%s]' % name)
|
||||
t = time.time()
|
||||
fn()
|
||||
log(' %.1f s' % (time.time() - t))
|
||||
if not self.args.keep_work:
|
||||
rmtree(self.work)
|
||||
log('done in %.0f s: %s' % (time.time() - t0, self.archive))
|
||||
|
||||
|
||||
def linked_libraries(path):
|
||||
"""The shared libraries an ELF program needs (its DT_NEEDED entries, from readelf), or [] without readelf."""
|
||||
readelf = shutil.which('readelf')
|
||||
if not readelf:
|
||||
return []
|
||||
out = subprocess.run([readelf, '-d', path], stdout=subprocess.PIPE, universal_newlines=True).stdout
|
||||
return re.findall(r'\(NEEDED\)\s+Shared library: \[([^\]]+)\]', out)
|
||||
|
||||
|
||||
def tar_dir(folder, path, top, mtime):
|
||||
"""A reproducible .tar.gz of folder under top/: entries sorted, every time mtime, owner root, modes 755 / 644
|
||||
(755 for what is executable in folder), no link, gzip without a name or time."""
|
||||
entries = []
|
||||
for dirpath, dirnames, filenames in os.walk(folder):
|
||||
dirnames.sort()
|
||||
rel_dir = os.path.relpath(dirpath, folder).replace('\\', '/')
|
||||
rel_dir = '' if rel_dir == '.' else rel_dir
|
||||
entries.append((rel_dir, dirpath, True))
|
||||
for n in sorted(filenames):
|
||||
entries.append(((rel_dir + '/' if rel_dir else '') + n, os.path.join(dirpath, n), False))
|
||||
entries.sort(key=lambda e: e[0])
|
||||
with open(path, 'wb') as raw, gzip.GzipFile(filename='', mode='wb', fileobj=raw, mtime=0) as gz, \
|
||||
tarfile.open(fileobj=gz, mode='w', format=tarfile.PAX_FORMAT) as tf:
|
||||
for rel, full, is_dir in entries:
|
||||
if os.path.islink(full):
|
||||
raise ReleaseError('%s is a link: a release holds none' % full)
|
||||
info = tarfile.TarInfo(top + ('/' + rel if rel else ''))
|
||||
info.mtime, info.uid, info.gid, info.uname, info.gname = mtime, 0, 0, '', ''
|
||||
if is_dir:
|
||||
info.type, info.mode = tarfile.DIRTYPE, 0o755
|
||||
tf.addfile(info)
|
||||
else:
|
||||
info.size = os.path.getsize(full)
|
||||
info.mode = 0o755 if os.stat(full).st_mode & 0o111 else 0o644
|
||||
with open(full, 'rb') as f:
|
||||
tf.addfile(info, f)
|
||||
|
||||
|
||||
def linux_archive_name(version):
|
||||
return '%s-%s%s' % (NAME, version, LINUX_SUFFIX)
|
||||
|
||||
|
||||
def sha256_of_file_record(path):
|
||||
with open(path + '.sha256') as f:
|
||||
return f.read().split()[0]
|
||||
|
||||
|
||||
def linux_download_lines(archive, digest):
|
||||
return [
|
||||
'## Linux', '',
|
||||
'1. `%s` below. Check it: `sha256sum %s` must print' % (archive, archive), '',
|
||||
' ```', ' %s' % digest, ' ```', '',
|
||||
'2. Install what the build needs (GCC, CMake, Ninja, pkg-config, Python 3, the FFmpeg, X11/Wayland, OpenGL and '
|
||||
'audio development files). On Debian or Ubuntu:', '',
|
||||
' ```', ' %s' % LINUX_APT, ' ```', '',
|
||||
' The launcher names the packages for Fedora, Arch and openSUSE when one is missing.',
|
||||
'3. `tar xzf %s`, then run `%s/%s`, select your disc image, **Prepare the game**, **Play**.'
|
||||
% (archive, TOP, LINUX_LAUNCHER), '',
|
||||
'Saves and settings are in `~/.local/share/tmb_recomp`.', '']
|
||||
|
||||
|
||||
LINUX_APT = ('sudo apt install build-essential cmake ninja-build pkg-config python3 libavcodec-dev libavutil-dev '
|
||||
'libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev libxss-dev libxtst-dev libxfixes-dev '
|
||||
'libxkbcommon-dev libwayland-dev libdecor-0-dev libegl-dev libgl-dev libpipewire-0.3-dev libpulse-dev '
|
||||
'libasound2-dev libudev-dev')
|
||||
|
||||
|
||||
CHANGELOG_HEADING = re.compile(r'^##[ \t]+\[?([^\]\s]+)\]?(.*)$', re.M)
|
||||
|
||||
|
||||
@@ -994,13 +1257,15 @@ def verify_zip(path, top=TOP):
|
||||
continue
|
||||
if game_name(rel) or (rel.lower().endswith(GAME_EXTENSIONS) and not allowed_extension(rel)):
|
||||
problems.append('%s: named like a file of the game' % n)
|
||||
if rel.startswith('source/') and ('/__pycache__/' in rel or rel.endswith('.pyc')):
|
||||
problems.append('%s: a Python bytecode cache (it holds the build machine paths)' % n)
|
||||
with zf.open(info) as f:
|
||||
head = f.read(0x8006)
|
||||
if head[:4] == b'\x7fELF':
|
||||
problems.append('%s: an ELF file' % n)
|
||||
if len(head) >= 0x8006 and head[0x8001:0x8006] == b'CD001':
|
||||
problems.append('%s: an ISO9660 volume' % n)
|
||||
for need in ('TMB Launcher.exe', 'README.txt', 'CHANGELOG.md', 'LICENSES/TMB_Recomp/LICENSE',
|
||||
for need in ('TMB Launcher.exe', 'README.txt', 'CHANGELOG.md', RECOMPLAUNCHER_JSON, 'LICENSES/TMB_Recomp/LICENSE',
|
||||
'LICENSES/BozoEngine/LICENSE', 'source/release.ini', 'kit/kit_manifest.json',
|
||||
'kit/python/python.exe', 'source/tools/tmb_build.py', 'source/BozoEngine/CMakeLists.txt',
|
||||
'kit/deps/sdl3-src/CMakeLists.txt', 'kit/deps/imgui-src/imgui.cpp'):
|
||||
@@ -1009,6 +1274,61 @@ def verify_zip(path, top=TOP):
|
||||
return problems
|
||||
|
||||
|
||||
# kit/python3 (Linux): what recomplauncher.json's prepare runs after kit/python/python.exe, the system's python3.
|
||||
LINUX_PYTHON3 = '''#!/bin/sh
|
||||
# The system's Python 3, for recomplauncher.json's prepare (Windows: kit/python/python.exe).
|
||||
exec python3 "$@"
|
||||
'''
|
||||
|
||||
# The ELF programs a Linux release carries: its launcher and Real-ESRGAN (the enhanced textures).
|
||||
LINUX_PROGRAMS = (LINUX_LAUNCHER, 'kit/realesrgan/realesrgan-ncnn-vulkan')
|
||||
|
||||
LINUX_REQUIRED = (LINUX_LAUNCHER, 'README.txt', 'CHANGELOG.md', RECOMPLAUNCHER_JSON, 'kit/python3', 'LICENSES/TMB_Recomp/LICENSE',
|
||||
'LICENSES/BozoEngine/LICENSE', 'source/release.ini', 'kit/kit_manifest.json',
|
||||
'source/tools/tmb_build.py', 'source/BozoEngine/CMakeLists.txt', 'kit/deps/sdl3-src/CMakeLists.txt',
|
||||
'kit/deps/imgui-src/imgui.cpp')
|
||||
|
||||
|
||||
def verify_tar(path, top=TOP):
|
||||
"""The Linux release audited as verify_zip audits the zip: one top folder, only files and folders, no game file,
|
||||
no ELF but the launcher, the files a Linux release must have."""
|
||||
problems = []
|
||||
with tarfile.open(path) as tf:
|
||||
members = tf.getmembers()
|
||||
names = set()
|
||||
tops = set(m.name.split('/', 1)[0] for m in members)
|
||||
if tops != {top}:
|
||||
problems.append('the archive\'s top folders are %s, expected %s only' % (sorted(tops), top))
|
||||
for m in members:
|
||||
n = m.name
|
||||
rel = n.split('/', 1)[1] if '/' in n else ''
|
||||
names.add(rel)
|
||||
if not (m.isfile() or m.isdir()):
|
||||
problems.append('%s: not a file or a folder' % n)
|
||||
continue
|
||||
if n.startswith('/') or '..' in n.split('/'):
|
||||
problems.append('%s: an absolute or parent path' % n)
|
||||
if rel.lower().startswith('source/ps2recomp/'):
|
||||
problems.append('%s: PS2Recomp in a BozoEngine release' % n)
|
||||
if m.isdir():
|
||||
if rel and game_name(rel + '/'):
|
||||
problems.append('%s: a generated / game folder' % n)
|
||||
continue
|
||||
if game_name(rel) or (rel.lower().endswith(GAME_EXTENSIONS) and not allowed_extension(rel)):
|
||||
problems.append('%s: named like a file of the game' % n)
|
||||
if rel.startswith('source/') and ('/__pycache__/' in rel or rel.endswith('.pyc')):
|
||||
problems.append('%s: a Python bytecode cache (it holds the build machine paths)' % n)
|
||||
head = tf.extractfile(m).read(0x8006)
|
||||
if head[:4] == b'\x7fELF' and rel not in LINUX_PROGRAMS:
|
||||
problems.append('%s: an ELF file' % n)
|
||||
if len(head) >= 0x8006 and head[0x8001:0x8006] == b'CD001':
|
||||
problems.append('%s: an ISO9660 volume' % n)
|
||||
for need in LINUX_REQUIRED:
|
||||
if need not in names:
|
||||
problems.append('%s/%s is missing' % (top, need))
|
||||
return problems
|
||||
|
||||
|
||||
def link_tree_file(src, dst):
|
||||
try:
|
||||
os.link(src, dst)
|
||||
@@ -1161,6 +1481,79 @@ Un projet de fans non officiel, ni affilié ni approuvé par eux.
|
||||
Version {version}
|
||||
"""
|
||||
|
||||
LINUX_LICENSES_README = """{name} (Linux): licences
|
||||
|
||||
TMB_Recomp/LICENSE TMB_Recomp's own code in source/ (MIT)
|
||||
BozoEngine/LICENSE BozoEngine, the recompiler and runtime in source/BozoEngine (MIT)
|
||||
libraries/ the libraries compiled into the game and the launcher (SDL3, Dear ImGui), their sources in
|
||||
kit/deps
|
||||
realesrgan/ Real-ESRGAN ncnn-vulkan and its model in kit/realesrgan (MIT, BSD-3-Clause), the
|
||||
optional enhanced textures
|
||||
launcher-font-exo2/ the launcher's font, Exo 2 (SIL Open Font License 1.1)
|
||||
|
||||
No GPL program is redistributed: the compiler, Python and FFmpeg are your system's.
|
||||
Twisted Metal: Black is (c) Sony Interactive Entertainment. Nothing of the game is in this download.
|
||||
"""
|
||||
|
||||
LINUX_README = """Twisted Metal: Black - PC port ({name}, Linux)
|
||||
by The Bozos (boubou666 & Arzaroth)
|
||||
|
||||
What this is
|
||||
A native PC version of Twisted Metal: Black (PS2), built on your own PC from YOUR OWN disc.
|
||||
Nothing of the game is in this download: no game files, no code taken from the game.
|
||||
Requires a 64-bit Linux with X11 or Wayland, OpenGL 3.3, and an AVX2 and FMA capable CPU.
|
||||
You need a disc image of the USA release (SCUS-97101): a .iso, or a .bin with its .cue.
|
||||
The European disc and other games are refused with an explanation.
|
||||
|
||||
Before you start: check the download
|
||||
sha256sum {archive}
|
||||
The hash printed must be the same as on the release page (and in {archive}.sha256).
|
||||
|
||||
What the build needs
|
||||
GCC (C++20), CMake 3.21 or newer, Ninja, pkg-config, Python 3, and the development files of FFmpeg (libavcodec,
|
||||
libavutil), X11 or Wayland, OpenGL (EGL or GLX) and PipeWire, PulseAudio or ALSA. On Debian or Ubuntu:
|
||||
sudo apt install build-essential cmake ninja-build pkg-config python3 libavcodec-dev libavutil-dev \\
|
||||
libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev libxss-dev libxtst-dev libxfixes-dev \\
|
||||
libxkbcommon-dev libwayland-dev libdecor-0-dev libegl-dev libgl-dev libpipewire-0.3-dev libpulse-dev \\
|
||||
libasound2-dev libudev-dev
|
||||
On Fedora, Arch or openSUSE, "Prepare the game" names the packages to install when one is missing.
|
||||
The disc picker uses your desktop's file dialog (xdg-desktop-portal) or zenity.
|
||||
|
||||
Install
|
||||
1. tar xzf {archive} wherever you like, with about 10 GB free: that makes TMB_Recomp_Bozo/.
|
||||
Keep the folders together: tmb-launcher, source/ and kit/.
|
||||
2. Run TMB_Recomp_Bozo/tmb-launcher.
|
||||
3. Click "Select your disc image..." and pick your USA disc image.
|
||||
4. Click "Prepare the game". It takes a few minutes, once (converting the textures and models, then compiling).
|
||||
You can stop it; it continues later.
|
||||
5. Click "Play". In the game, F2 opens controls, video and cheats.
|
||||
6. Optional: Settings > "Make enhanced textures" upscales every arena's and car's textures with Real-ESRGAN (in
|
||||
kit/realesrgan), on your PC from your own disc: about 15 minutes with a recent graphics card, about 700 MB, and a
|
||||
Vulkan graphics driver is needed. Nothing is downloaded or sent, and the result is yours alone: do not share it.
|
||||
Without the launcher: python3 source/tools/tmb_build.py --disc <your image> --out build --game game, then
|
||||
game/play_tmb.sh.
|
||||
|
||||
Your saves and settings
|
||||
~/.local/share/tmb_recomp (the launcher's Maintenance tab opens it). They stay when you update.
|
||||
|
||||
Updates
|
||||
The launcher tells you when a new version is out, and its Update button installs it. Or extract the new archive
|
||||
where you extracted this one and click "Rebuild now": only what changed is built again. Your saves stay.
|
||||
|
||||
Uninstall
|
||||
Delete this folder, and ~/.local/share/tmb_recomp to remove your saves and settings too.
|
||||
|
||||
Help
|
||||
https://github.com/{repo}/issues
|
||||
When preparing fails, the launcher's "Copy details" button copies what we need to know.
|
||||
|
||||
Licences and source code: LICENSES/. Our code is MIT, and so is BozoEngine, the recompiler and runtime it is built on.
|
||||
Twisted Metal: Black (c) Sony Interactive Entertainment, developed by Incognito Entertainment.
|
||||
An unofficial fan project, not affiliated with or endorsed by them.
|
||||
|
||||
Version {version}
|
||||
"""
|
||||
|
||||
|
||||
def main():
|
||||
for stream in (sys.stdout, sys.stderr): # the changelog's text, whatever the console's code page (cp1252 on CI)
|
||||
@@ -1186,11 +1579,13 @@ def main():
|
||||
'CHANGELOG.md has no section for the version (never for a real release)')
|
||||
ap.add_argument('--check-changelog', action='store_true', help='only print CHANGELOG.md\'s section for the version '
|
||||
'(--version or the commit\'s tag) at the commit; exit 1 when it is missing')
|
||||
ap.add_argument('--verify-zip', metavar='ZIP', help='only audit a release zip (no game file, the expected files)')
|
||||
ap.add_argument('--verify-zip', metavar='ZIP', help='only audit a release zip or Linux .tar.gz (no game file, the '
|
||||
'expected files)')
|
||||
ap.add_argument('--linux', action='store_true', help='the Linux release (<name>-linux.tar.gz) instead of the zip')
|
||||
args = ap.parse_args()
|
||||
try:
|
||||
if args.verify_zip:
|
||||
problems = verify_zip(args.verify_zip)
|
||||
problems = (verify_tar if args.verify_zip.endswith('.tar.gz') else verify_zip)(args.verify_zip)
|
||||
if problems:
|
||||
raise ReleaseError('%s:\n %s' % (args.verify_zip, '\n '.join(problems[:40])))
|
||||
log('%s: no game file, the expected files present' % args.verify_zip)
|
||||
@@ -1218,7 +1613,7 @@ def main():
|
||||
if args.publish_only:
|
||||
Release(args).publish_made()
|
||||
return
|
||||
Release(args).main()
|
||||
(LinuxRelease if args.linux else Release)(args).main()
|
||||
except ReleaseError as e:
|
||||
sys.exit('make_release: %s' % e)
|
||||
|
||||
|
||||
+134
-11
@@ -1,8 +1,8 @@
|
||||
#!/usr/bin/env python3
|
||||
"""tmb_build: from the player's own Twisted Metal: Black disc (USA, SCUS-97101) to a game folder that runs, in one
|
||||
command. Nothing derived from the game is distributed: the disc's files, the generated code, the packs and the
|
||||
executable are all made here, on the player's PC. The game is built on BozoEngine (the BozoEngine submodule, at the
|
||||
commit this code pins; --engine <dir> for another tree).
|
||||
executable are all made here, on the player's PC. The game is built on BozoEngine (the release cmake/bozo_engine.json
|
||||
pins, in BozoEngine/: a release's source has it, a git checkout fetches it; --engine <dir> for another tree).
|
||||
|
||||
python tools/tmb_build.py --disc "Twisted Metal - Black (USA).iso" --out D:/TMB
|
||||
python tools/tmb_build.py --disc D:/TMB_Recomp/game_us --out D:/TMB (an extracted disc folder)
|
||||
@@ -22,7 +22,7 @@ again; within a step CMake and Ninja rebuild only what changed):
|
||||
packs the texture and mesh packs (tools/tmb_texture_pack.py, tools/tmb_mesh_pack.py on BozoEngine's
|
||||
tools/native_pack) -> <out>/build/packs
|
||||
compile the game (tmb: SDL3, OpenGL 3.3)
|
||||
stage <game>: tmb.exe, SCUS_971.01, the packs, disc.iso, "Play TMB.cmd"
|
||||
stage <game>: tmb.exe, SCUS_971.01, the packs, disc.iso, "Play TMB.cmd" (on Linux: tmb, play_tmb.sh)
|
||||
|
||||
The build kit (tools/make_build_kit.py): a folder with kit_manifest.json, the compiler (ucrt64/), a minimal static
|
||||
FFmpeg (ffmpeg/), the libraries' sources (deps/: SDL3, Dear ImGui) and an embeddable Python. Used when it sits in
|
||||
@@ -30,6 +30,9 @@ FFmpeg (ffmpeg/), the libraries' sources (deps/: SDL3, Dear ImGui) and an embedd
|
||||
nothing else is needed (no MSYS2, git, network or installed Python), and the game is the player's build: statically
|
||||
linked (no DLL), FFmpeg from the kit.
|
||||
kit/python/python.exe -I tools/tmb_build.py --disc "Twisted Metal - Black (USA).iso" --out D:/TMB
|
||||
The Linux release's kit has deps/ only: the compiler, Python and FFmpeg are the system's. On Linux the build first
|
||||
checks for GCC, CMake, Ninja, pkg-config and the FFmpeg, X11 or Wayland, OpenGL and audio development files, and names
|
||||
the packages to install (ERROR verify) when one is missing.
|
||||
|
||||
Without a kit: --toolchain <dir> (a folder whose bin/ has g++, cmake, ninja: an MSYS2 UCRT64 prefix such as
|
||||
C:/msys64/ucrt64), else the PATH, else C:/msys64/ucrt64; FFmpeg through pkg-config; SDL3 and ImGui downloaded by CMake
|
||||
@@ -106,19 +109,46 @@ class BuildError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
# --progress-lines: RecompLauncher's setup step (recomplauncher.json's prepare) reads "progress <0 to 1> <text>" lines.
|
||||
PROGRESS_LINES = False
|
||||
# Each step's share of the bar: its usual seconds on a first build (launcher/src/build_model.cpp's kSteps).
|
||||
STEP_WEIGHTS = {'verify': 1, 'extract': 2, 'configure': 60, 'tools': 7, 'recompile': 2, 'packs': 32, 'compile': 55,
|
||||
'stage': 1}
|
||||
|
||||
|
||||
def emit(*parts):
|
||||
print(' '.join(str(p) for p in parts), flush=True)
|
||||
if PROGRESS_LINES:
|
||||
line = progress_line(parts)
|
||||
if line:
|
||||
print(line, flush=True)
|
||||
|
||||
|
||||
def progress_line(parts):
|
||||
"""RecompLauncher's line for a PROGRESS (a step starts) or PERCENT (it moves on) line, else None: the share of the
|
||||
whole build done, and the step's title (recomplauncher.com/sdk, prepare)."""
|
||||
if len(parts) < 3 or parts[0] not in ('PROGRESS', 'PERCENT') or parts[1] not in STEP_WEIGHTS:
|
||||
return None
|
||||
step = parts[1]
|
||||
pct = int(parts[2]) if parts[0] == 'PERCENT' else 0
|
||||
before = sum(STEP_WEIGHTS[s] for s in STEPS[:STEPS.index(step)])
|
||||
done = (before + STEP_WEIGHTS[step] * min(max(pct, 0), 100) / 100) / sum(STEP_WEIGHTS.values())
|
||||
return 'progress %.3f %s%s' % (min(done, 0.999), STEP_TITLES[step], ' (%d%%)' % pct if parts[0] == 'PERCENT' else '')
|
||||
|
||||
|
||||
def load_engine(path=None):
|
||||
"""BozoEngine's tree (--engine, else the submodule) and its disc reader."""
|
||||
"""BozoEngine's tree (--engine, else the pinned release, fetched in a git checkout) and its disc reader."""
|
||||
global ENGINE, ps2_disc
|
||||
if path:
|
||||
ENGINE = os.path.abspath(path)
|
||||
tools = os.path.join(ENGINE, 'tools', 'native_pack')
|
||||
fetch = os.path.join(ROOT, 'cmake', 'bozo_engine_fetch.cmake')
|
||||
if not path and os.path.exists(os.path.join(ROOT, '.git')) and shutil.which('cmake'):
|
||||
# A checkout follows cmake/bozo_engine.json (nothing is downloaded while BozoEngine/.release matches it).
|
||||
subprocess.run([shutil.which('cmake'), '-P', fetch], check=False)
|
||||
if not os.path.isfile(os.path.join(tools, 'ps2_disc.py')):
|
||||
raise SystemExit('ERROR verify BozoEngine is missing (%s): the release is incomplete, or in a git checkout run '
|
||||
'"git submodule update --init BozoEngine"' % ENGINE)
|
||||
'"cmake -P cmake/bozo_engine_fetch.cmake"' % ENGINE)
|
||||
sys.path.insert(0, tools)
|
||||
import ps2_disc as module # noqa: E402
|
||||
ps2_disc = module
|
||||
@@ -262,10 +292,12 @@ class Build:
|
||||
self.kit = find_kit(args)
|
||||
self.ffmpeg_root = None
|
||||
if self.kit:
|
||||
# The kit's parts unless the command line names others.
|
||||
args.toolchain = args.toolchain or os.path.join(self.kit, 'ucrt64')
|
||||
# The kit's parts unless the command line names others. A Linux kit has deps/ only.
|
||||
if os.path.isdir(os.path.join(self.kit, 'ucrt64')):
|
||||
args.toolchain = args.toolchain or os.path.join(self.kit, 'ucrt64')
|
||||
args.fetch_cache = args.fetch_cache or os.path.join(self.kit, 'deps')
|
||||
self.ffmpeg_root = os.path.join(self.kit, 'ffmpeg')
|
||||
if os.path.isdir(os.path.join(self.kit, 'ffmpeg')):
|
||||
self.ffmpeg_root = os.path.join(self.kit, 'ffmpeg')
|
||||
if args.debug_info is None: # a player's build (the kit): no debug information
|
||||
args.debug_info = 'no' if self.kit else 'yes'
|
||||
|
||||
@@ -725,9 +757,15 @@ class Build:
|
||||
# -- driver
|
||||
|
||||
def main(self):
|
||||
if os.name != 'nt':
|
||||
missing = linux_missing(self.args.toolchain)
|
||||
if missing:
|
||||
emit('ERROR', 'verify', linux_missing_message(missing))
|
||||
return 1
|
||||
redo_from = STEPS.index(self.args.redo) if self.args.redo else len(STEPS)
|
||||
n = len(STEPS)
|
||||
dirty = False
|
||||
ran = False
|
||||
total_start = time.time()
|
||||
for i, step in enumerate(STEPS, 1):
|
||||
self.step = step
|
||||
@@ -740,7 +778,7 @@ class Build:
|
||||
emit('INFO', 'stopped', 'after ' + step)
|
||||
return 0
|
||||
continue
|
||||
dirty = True # every later step runs again (Ninja only redoes what changed)
|
||||
dirty = ran = True # every later step runs again (Ninja only redoes what changed)
|
||||
emit('PROGRESS', step, '%d/%d' % (i, n), STEP_TITLES[step])
|
||||
t = time.time()
|
||||
self.state[step] = {'done': False}
|
||||
@@ -769,6 +807,8 @@ class Build:
|
||||
launcher = os.path.join(self.game, 'Play TMB.cmd' if os.name == 'nt' else 'play_tmb.sh')
|
||||
emit('INFO', 'total', '%.1f s' % (time.time() - total_start))
|
||||
emit('RESULT', self.game, launcher)
|
||||
if PROGRESS_LINES:
|
||||
print('progress 1 %s' % ('Ready to play' if ran else 'Already built'), flush=True)
|
||||
return 0
|
||||
|
||||
|
||||
@@ -787,6 +827,74 @@ def find_kit(args):
|
||||
return None
|
||||
|
||||
|
||||
LINUX_TOOLS = ('gcc', 'g++', 'cmake', 'ninja', 'pkg-config')
|
||||
LINUX_MODULES = (('FFmpeg', ('libavcodec', 'libavutil')),
|
||||
('X11 or Wayland', ('x11|wayland-client',)),
|
||||
('OpenGL', ('gl|egl',)),
|
||||
('PipeWire, PulseAudio or ALSA', ('libpipewire-0.3|libpulse|alsa',)))
|
||||
LINUX_X11_EXTENSIONS = ('xext', 'xcursor', 'xi', 'xfixes', 'xrandr', 'xscrnsaver', 'xtst')
|
||||
LINUX_PACKAGES = {
|
||||
'debian': 'sudo apt install build-essential cmake ninja-build pkg-config python3 libavcodec-dev libavutil-dev '
|
||||
'libx11-dev libxext-dev libxrandr-dev libxcursor-dev '
|
||||
'libxi-dev libxss-dev libxtst-dev libxfixes-dev libxkbcommon-dev libwayland-dev libdecor-0-dev libegl-dev libgl-dev '
|
||||
'libpipewire-0.3-dev libpulse-dev libasound2-dev libudev-dev',
|
||||
'fedora': 'sudo dnf install gcc-c++ cmake ninja-build pkgconf python3 ffmpeg-free-devel libX11-devel libXext-devel '
|
||||
'libXrandr-devel libXcursor-devel libXi-devel libXScrnSaver-devel libXtst-devel libXfixes-devel libxkbcommon-devel wayland-devel '
|
||||
'libdecor-devel mesa-libEGL-devel mesa-libGL-devel pipewire-devel pulseaudio-libs-devel alsa-lib-devel '
|
||||
'systemd-devel',
|
||||
'arch': 'sudo pacman -S --needed base-devel cmake ninja pkgconf python ffmpeg libx11 libxext libxrandr libxcursor '
|
||||
'libxi libxss libxtst libxfixes libxkbcommon wayland libdecor mesa libpipewire libpulse alsa-lib',
|
||||
'suse': 'sudo zypper install gcc-c++ cmake ninja pkg-config python3 ffmpeg-7-libavcodec-devel '
|
||||
'ffmpeg-7-libavutil-devel '
|
||||
'libX11-devel libXext-devel libXrandr-devel libXcursor-devel libXi-devel libXss-devel libXtst-devel libXfixes-devel libxkbcommon-devel '
|
||||
'wayland-devel libdecor-devel Mesa-libEGL-devel Mesa-libGL-devel pipewire-devel libpulse-devel '
|
||||
'alsa-devel systemd-devel',
|
||||
}
|
||||
|
||||
|
||||
def linux_family():
|
||||
try:
|
||||
with open('/etc/os-release', encoding='utf-8') as f:
|
||||
fields = dict(l.rstrip('\n').split('=', 1) for l in f if '=' in l)
|
||||
except OSError:
|
||||
return None
|
||||
ids = ' '.join(fields.get(k, '').strip('"') for k in ('ID', 'ID_LIKE')).split()
|
||||
for family, names in (('debian', ('debian', 'ubuntu')), ('fedora', ('fedora', 'rhel', 'centos')),
|
||||
('arch', ('arch', 'archlinux')), ('suse', ('suse', 'opensuse'))):
|
||||
if any(i in names or i.startswith('opensuse') and family == 'suse' for i in ids):
|
||||
return family
|
||||
return None
|
||||
|
||||
|
||||
def linux_missing(toolchain=None):
|
||||
"""What the Linux build needs and this system lacks: tools on the PATH and pkg-config modules."""
|
||||
missing = []
|
||||
if not toolchain:
|
||||
missing += [t for t in LINUX_TOOLS if not shutil.which(t)]
|
||||
elif not shutil.which('pkg-config'):
|
||||
missing.append('pkg-config')
|
||||
if shutil.which('pkg-config'):
|
||||
for what, modules in LINUX_MODULES:
|
||||
lacking = [m for m in modules if not any(
|
||||
subprocess.run(['pkg-config', '--exists', alt]).returncode == 0 for alt in m.split('|'))]
|
||||
if lacking:
|
||||
missing.append('%s (%s)' % (what, ', '.join(m.replace('|', ' or ') for m in lacking)))
|
||||
if subprocess.run(['pkg-config', '--exists', 'x11']).returncode == 0:
|
||||
lacking = [m for m in LINUX_X11_EXTENSIONS if subprocess.run(['pkg-config', '--exists', m]).returncode != 0]
|
||||
if lacking:
|
||||
missing.append('X11 extensions (%s)' % ', '.join(lacking))
|
||||
return missing
|
||||
|
||||
|
||||
def linux_missing_message(missing):
|
||||
family = linux_family()
|
||||
install = LINUX_PACKAGES.get(family)
|
||||
return ('the build needs %s. %s' % (', '.join(missing),
|
||||
'Install them with: %s' % install if install else
|
||||
'Install your distribution\'s packages for them (GCC, CMake, Ninja, pkg-config, the FFmpeg, X11, Wayland, '
|
||||
'OpenGL and audio development files); on Debian or Ubuntu: %s' % LINUX_PACKAGES['debian']))
|
||||
|
||||
|
||||
STEP_TITLES = {
|
||||
'verify': 'Checking the disc',
|
||||
'extract': 'Reading the disc\'s files',
|
||||
@@ -826,12 +934,13 @@ def check_disc(path):
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description='Builds Twisted Metal: Black (USA) as a native PC game from your own disc.')
|
||||
ap.add_argument('--disc', required=True, help='the disc image (.iso, .bin, .cue) or an extracted disc folder')
|
||||
ap.add_argument('--disc', help='the disc image (.iso, .bin, .cue) or an extracted disc folder (default: the '
|
||||
'disc.iso an earlier build left in the game folder)')
|
||||
ap.add_argument('--out', default='tmb_build', help='the work folder; the game ends up in <out>/TMB')
|
||||
ap.add_argument('--game', help='the game folder to stage (default: <out>/TMB)')
|
||||
ap.add_argument('--check', action='store_true', help='only check the disc (no work folder): OK <message> or '
|
||||
'ERROR verify <message>')
|
||||
ap.add_argument('--engine', help='BozoEngine\'s source tree (default: the BozoEngine submodule)')
|
||||
ap.add_argument('--engine', help='BozoEngine\'s source tree (default: the release cmake/bozo_engine.json pins, in BozoEngine/)')
|
||||
ap.add_argument('--kit', help='the build kit folder (default: <TMB_Recomp>/kit or <its parent>/kit if present)')
|
||||
ap.add_argument('--no-kit', action='store_true', help='do not use a build kit even if one is found')
|
||||
ap.add_argument('--toolchain', help='compiler folder (with bin/g++, cmake, ninja), default: the kit, PATH, '
|
||||
@@ -844,7 +953,21 @@ def main():
|
||||
ap.add_argument('--jobs', type=int, default=os.cpu_count() or 4)
|
||||
ap.add_argument('--redo', choices=STEPS, help='run this step and the ones after it again')
|
||||
ap.add_argument('--stop-after', choices=STEPS, help='stop once this step is done')
|
||||
ap.add_argument('--progress-lines', action='store_true', help='also print "progress <0 to 1> <text>" lines, for '
|
||||
'RecompLauncher (recomplauncher.json)')
|
||||
args = ap.parse_args()
|
||||
global PROGRESS_LINES
|
||||
PROGRESS_LINES = args.progress_lines
|
||||
if not args.disc:
|
||||
# Built before: the game folder keeps the disc image (a link to the player's, or a copy), so an update builds
|
||||
# again without it (RecompLauncher's keeps_copy, after the player deleted their own).
|
||||
kept = os.path.join(os.path.abspath(args.game) if args.game else os.path.join(os.path.abspath(args.out), 'TMB'),
|
||||
'disc.iso')
|
||||
if not os.path.isfile(kept):
|
||||
emit('ERROR', 'verify', 'no disc image given (--disc) and none kept from an earlier build: pick your '
|
||||
'Twisted Metal: Black disc image (USA, SCUS-97101)')
|
||||
sys.exit(1)
|
||||
args.disc = kept
|
||||
load_engine(args.engine)
|
||||
if args.check:
|
||||
sys.exit(check_disc(args.disc))
|
||||
|
||||
@@ -77,7 +77,7 @@ import struct
|
||||
import sys
|
||||
import zlib
|
||||
|
||||
# native_pack: BozoEngine's tools/ (BOZO_ENGINE_TOOLS, or the BozoEngine submodule).
|
||||
# native_pack: BozoEngine's tools/ (BOZO_ENGINE_TOOLS, or the pinned release in BozoEngine/).
|
||||
_root = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')
|
||||
for _tools in (os.environ.get('BOZO_ENGINE_TOOLS', ''), os.path.join(_root, 'BozoEngine', 'tools')):
|
||||
if _tools and os.path.isdir(os.path.join(_tools, 'native_pack')):
|
||||
|
||||
@@ -25,7 +25,7 @@ import struct
|
||||
import sys
|
||||
import zlib
|
||||
|
||||
# native_pack: BozoEngine's tools/ (BOZO_ENGINE_TOOLS, or the BozoEngine submodule).
|
||||
# native_pack: BozoEngine's tools/ (BOZO_ENGINE_TOOLS, or the pinned release in BozoEngine/).
|
||||
_root = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')
|
||||
for _tools in (os.environ.get('BOZO_ENGINE_TOOLS', ''), os.path.join(_root, 'BozoEngine', 'tools')):
|
||||
if _tools and os.path.isdir(os.path.join(_tools, 'native_pack')):
|
||||
|
||||
Reference in new issue
Block a user