mirror of
https://github.com/TheBozos/TMB_Recomp.git
synced 2026-12-01 10:13:24 -10:00
Compare commits
29
Commits
No files matched your search
@@ -0,0 +1,22 @@
|
||||
name: CI
|
||||
on: [push, pull_request, workflow_dispatch]
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
release-tools:
|
||||
strategy:
|
||||
matrix:
|
||||
os: [windows-latest, ubuntu-latest]
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.14'
|
||||
- name: Release, migration and timing checks
|
||||
run: python -m unittest discover -s tests -v
|
||||
- name: Python syntax
|
||||
run: python -m compileall -q tools
|
||||
- name: Shell syntax
|
||||
shell: bash
|
||||
run: for file in scripts/*.sh; do bash -n "$file" || exit; done
|
||||
@@ -1,11 +1,17 @@
|
||||
# The release: built only when the owner asks for one, never on an ordinary push or a pull request.
|
||||
# The release of the BozoEngine build: built only when the owner asks for one, never on an ordinary push or a pull
|
||||
# request.
|
||||
#
|
||||
# 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
|
||||
# zip, its SHA-256 and the sources zip with tools/make_release.py, checks them without any 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.
|
||||
# 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.
|
||||
#
|
||||
# Run by hand without a tag (Actions > Release > Run workflow on a branch, or gh workflow run release.yml --ref
|
||||
# <branch>): a test build of that branch (version 0.0.0-test.<run number> unless given), the same kit, zip and checks,
|
||||
# no sources zip and no draft release; the zips are the run's artifacts.
|
||||
#
|
||||
# Every step is a thin call into tools/make_build_kit.py or tools/make_release.py, so the same commands run on a
|
||||
# developer's PC (README, "Making a release").
|
||||
@@ -20,8 +26,14 @@ on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: 'The version tag to release (already pushed), e.g. v0.1.0'
|
||||
required: true
|
||||
description: 'The version tag to release (already pushed), e.g. v0.1.0; empty: a test build of the branch'
|
||||
required: false
|
||||
default: ''
|
||||
type: string
|
||||
version:
|
||||
description: 'A test build only: its version (default 0.0.0-test.<run number>)'
|
||||
required: false
|
||||
default: ''
|
||||
type: string
|
||||
release:
|
||||
types: [published]
|
||||
@@ -41,25 +53,37 @@ jobs:
|
||||
permissions:
|
||||
contents: write # the draft release and its files
|
||||
env:
|
||||
TAG: ${{ github.event_name == 'workflow_dispatch' && inputs.tag || github.ref_name }}
|
||||
TAG: ${{ github.event_name == 'workflow_dispatch' && inputs.tag || (github.event_name == 'push' && github.ref_name || '') }}
|
||||
TEST_VERSION: ${{ inputs.version }}
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- name: Version from the tag
|
||||
- name: Version from the tag (or a test build's)
|
||||
run: |
|
||||
set -eu
|
||||
if ! printf '%s' "$TAG" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$'; then
|
||||
echo "::error::$TAG is not a version tag (vMAJOR.MINOR.PATCH or vMAJOR.MINOR.PATCH-pre)"
|
||||
exit 1
|
||||
if [ -n "$TAG" ]; then
|
||||
if ! printf '%s' "$TAG" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$'; then
|
||||
echo "::error::$TAG is not a version tag (vMAJOR.MINOR.PATCH or vMAJOR.MINOR.PATCH-pre)"
|
||||
exit 1
|
||||
fi
|
||||
echo "VERSION=${TAG#v}" >> "$GITHUB_ENV"
|
||||
echo "TEST_BUILD=" >> "$GITHUB_ENV"
|
||||
else
|
||||
v="${TEST_VERSION:-0.0.0-test.$GITHUB_RUN_NUMBER}"
|
||||
if ! printf '%s' "$v" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$'; then
|
||||
echo "::error::$v is not a version (MAJOR.MINOR.PATCH or MAJOR.MINOR.PATCH-pre)"
|
||||
exit 1
|
||||
fi
|
||||
echo "VERSION=$v" >> "$GITHUB_ENV"
|
||||
echo "TEST_BUILD=1" >> "$GITHUB_ENV"
|
||||
fi
|
||||
echo "VERSION=${TAG#v}" >> "$GITHUB_ENV"
|
||||
echo "WORK=$(cygpath -m "$RUNNER_TEMP")/tmb" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Check out the tag (and the PS2Recomp submodule at its recorded commit)
|
||||
- name: Check out the tag or the branch (and the BozoEngine submodule at its recorded commit)
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: refs/tags/${{ env.TAG }}
|
||||
ref: ${{ env.TAG != '' && format('refs/tags/{0}', env.TAG) || '' }}
|
||||
submodules: true
|
||||
persist-credentials: false
|
||||
|
||||
@@ -69,6 +93,7 @@ jobs:
|
||||
python-version: '3.14'
|
||||
|
||||
- name: The changelog has this version
|
||||
if: env.TEST_BUILD == ''
|
||||
run: python tools/make_release.py --check-changelog --version "$VERSION"
|
||||
|
||||
- name: MSYS2 (pacman, and sh for FFmpeg's configure; the toolchain itself comes from the pins)
|
||||
@@ -79,12 +104,12 @@ jobs:
|
||||
update: false
|
||||
install: diffutils
|
||||
|
||||
- name: Cache the downloads (pinned MSYS2 packages, FFmpeg, Python, MSYS2 sources, the font)
|
||||
- name: Cache the downloads (pinned MSYS2 packages, FFmpeg, Python, SDL3, ImGui, MSYS2 sources, the font)
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ${{ runner.temp }}/tmb/downloads
|
||||
key: tmb-downloads-${{ hashFiles('tools/build_kit_packages.json', 'tools/make_build_kit.py') }}
|
||||
restore-keys: tmb-downloads-
|
||||
key: tmb-bozo-downloads-${{ hashFiles('tools/build_kit_packages.json', 'tools/make_build_kit.py') }}
|
||||
restore-keys: tmb-bozo-downloads-
|
||||
|
||||
- name: Cache the kit's FFmpeg (by the pins and make_build_kit.py)
|
||||
id: ffmpeg
|
||||
@@ -95,14 +120,14 @@ jobs:
|
||||
${{ runner.temp }}/tmb/kit/sources
|
||||
${{ runner.temp }}/tmb/kit/licenses/ffmpeg
|
||||
${{ runner.temp }}/tmb/kit/.parts/ffmpeg.json
|
||||
key: tmb-ffmpeg-${{ hashFiles('tools/build_kit_packages.json', 'tools/make_build_kit.py') }}
|
||||
key: tmb-bozo-ffmpeg-${{ hashFiles('tools/build_kit_packages.json', 'tools/make_build_kit.py') }}
|
||||
|
||||
- name: Install the pinned MSYS2 packages (exact files, SHA-256 checked)
|
||||
env:
|
||||
MSYS2_ROOT: ${{ steps.msys2.outputs.msys2-location }}
|
||||
run: python tools/make_build_kit.py --install-packages --msys "$MSYS2_ROOT" --downloads "$WORK/downloads"
|
||||
|
||||
- name: Build kit
|
||||
- name: Build kit (toolchain, Python, SDL3 and ImGui sources, FFmpeg)
|
||||
env:
|
||||
MSYS2_ROOT: ${{ steps.msys2.outputs.msys2-location }}
|
||||
FFMPEG_CACHED: ${{ steps.ffmpeg.outputs.cache-hit }}
|
||||
@@ -111,28 +136,35 @@ jobs:
|
||||
steps="--only toolchain --only python --only deps"
|
||||
if [ "$FFMPEG_CACHED" != true ]; then steps="$steps --only ffmpeg"; fi
|
||||
python tools/make_build_kit.py --out "$WORK/kit" --msys "$MSYS2_ROOT" --downloads "$WORK/downloads" \
|
||||
--work "$WORK/kit-work" $steps --only tools --only manifest
|
||||
--work "$WORK/kit-work" $steps --only manifest
|
||||
|
||||
- name: Make the release (zip, .sha256, sources zip, notes from CHANGELOG.md)
|
||||
env:
|
||||
MSYS2_ROOT: ${{ steps.msys2.outputs.msys2-location }}
|
||||
run: |
|
||||
set -eu
|
||||
if [ -n "$TEST_BUILD" ]; then extra="--allow-missing-changelog"; else extra="--with-sources"; fi
|
||||
python tools/make_release.py --version "$VERSION" --kit "$WORK/kit" --msys "$MSYS2_ROOT" \
|
||||
--out "$WORK/release" --downloads "$WORK/downloads" --with-sources
|
||||
--out "$WORK/release" --downloads "$WORK/downloads" $extra
|
||||
|
||||
- name: Smoke checks (no game data anywhere)
|
||||
run: |
|
||||
set -eu
|
||||
rel="$WORK/release"
|
||||
name="TMB_Recomp-$VERSION"
|
||||
name="TMB_Recomp-$VERSION-bozo"
|
||||
# The zip: no game file, the files a release needs; the hashes.
|
||||
python tools/make_release.py --verify-zip "$rel/$name.zip"
|
||||
(cd "$rel" && sha256sum -c "$name.zip.sha256" && sha256sum -c "$name-sources.zip.sha256")
|
||||
(cd "$rel" && sha256sum -c "$name.zip.sha256")
|
||||
(cd "$rel" && sha256sum -c "TMB_Recomp-$VERSION.zip.sha256")
|
||||
python -c 'import sys; sys.path.insert(0, "tools"); from make_release import verify_zip; p = verify_zip(sys.argv[1], top="TMB_Recomp"); print(p); sys.exit(bool(p))' "$rel/TMB_Recomp-$VERSION.zip"
|
||||
if [ -z "$TEST_BUILD" ]; then (cd "$rel" && sha256sum -c "$name-sources.zip.sha256"); fi
|
||||
# Unzipped as a player would.
|
||||
t="$WORK/smoke"
|
||||
t="$WORK/smoke/Jérôme Games"
|
||||
rm -rf "$t" && mkdir -p "$t/user"
|
||||
python -I -c 'import sys, zipfile; zipfile.ZipFile(sys.argv[1]).extractall(sys.argv[2])' "$rel/$name.zip" "$t"
|
||||
app="$t/TMB_Recomp"
|
||||
app="$t/TMB_Recomp_Bozo"
|
||||
# A real static C++ link through an accented kit path, without any game data or installed developer tools.
|
||||
"$app/kit/python/python.exe" -I "$app/source/tools/check_toolchain.py" --toolchain "$app/kit/ucrt64" --out "$WORK/compiler-check"
|
||||
head -c 1048576 /dev/zero > "$t/not_a_disc.iso"
|
||||
# tmb_build with the kit's own Python refuses a file that is not a disc.
|
||||
if "$app/kit/python/python.exe" -I -X utf8 "$app/source/tools/tmb_build.py" --check \
|
||||
@@ -150,7 +182,24 @@ jobs:
|
||||
cat "$t/self-check.txt"
|
||||
grep -q "^version $VERSION$" "$t/self-check.txt"
|
||||
|
||||
- name: Draft GitHub release (never published here)
|
||||
- name: Keep the zips (the run's artifacts)
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: TMB_Recomp-${{ env.VERSION }}-bozo
|
||||
path: |
|
||||
${{ runner.temp }}/tmb/release/TMB_Recomp-${{ env.VERSION }}-bozo.zip
|
||||
${{ runner.temp }}/tmb/release/TMB_Recomp-${{ env.VERSION }}-bozo.zip.sha256
|
||||
${{ runner.temp }}/tmb/release/TMB_Recomp-${{ env.VERSION }}.zip
|
||||
${{ 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/RELEASE_NOTES.md
|
||||
if-no-files-found: error
|
||||
retention-days: 14
|
||||
compression-level: 0
|
||||
|
||||
- name: Draft GitHub release (never published here; tags only)
|
||||
if: env.TEST_BUILD == ''
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: python tools/make_release.py --version "$VERSION" --out "$WORK/release" --publish-only
|
||||
@@ -159,10 +208,14 @@ jobs:
|
||||
if: always()
|
||||
run: |
|
||||
{
|
||||
echo "## TMB_Recomp $VERSION"
|
||||
echo "## TMB_Recomp $VERSION (BozoEngine)"
|
||||
echo
|
||||
if [ -f "$WORK/release/RELEASE_NOTES.md" ]; then
|
||||
echo "A **draft** release was created if every step passed: run docs/RELEASE_CHECKLIST.md on a clean PC, then publish it."
|
||||
if [ -n "$TEST_BUILD" ]; then
|
||||
echo "A test build: the zip is this run's artifact; no release was made."
|
||||
else
|
||||
echo "A **draft** release was created if every step passed: run docs/RELEASE_CHECKLIST.md on a clean PC, then publish it."
|
||||
fi
|
||||
echo
|
||||
cat "$WORK/release/RELEASE_NOTES.md"
|
||||
else
|
||||
|
||||
+4
-1
@@ -17,7 +17,7 @@ SLUS_*
|
||||
*.irx
|
||||
*.IMG
|
||||
|
||||
# PS2Recomp is a git submodule; local build trees live here
|
||||
# Local build trees
|
||||
build/
|
||||
out/
|
||||
cmake-build-*/
|
||||
@@ -41,3 +41,6 @@ ps2_log.txt
|
||||
# Debug UI layout the runtime writes in the working directory
|
||||
imgui.ini
|
||||
__pycache__/
|
||||
|
||||
# Retired local checkout (not a dependency; preserves untracked local files during migration)
|
||||
/PS2Recomp/
|
||||
+3
-3
@@ -1,3 +1,3 @@
|
||||
[submodule "PS2Recomp"]
|
||||
path = PS2Recomp
|
||||
url = https://github.com/TheBozos/PS2Recomp.git
|
||||
[submodule "BozoEngine"]
|
||||
path = BozoEngine
|
||||
url = https://github.com/TheBozos/BozoEngine.git
|
||||
+3
-3
@@ -11,8 +11,8 @@
|
||||
"project": "TMB_Recomp",
|
||||
"status": "released",
|
||||
"targets": ["Windows"],
|
||||
"toolchain": "Ps2recomp",
|
||||
"approach": "Static recompilation with a PS2Recomp fork; native PC renderer, sound and timing, no GS, VU or SPU2 emulation in the default mode.",
|
||||
"toolchain": "BozoEngine",
|
||||
"approach": "Static recompilation with BozoEngine; native PC renderer, sound, input and timing, with no PS2Recomp dependency or IOP, GS, VIF or VU interpreter in the player build.",
|
||||
"started": "2026-10-22",
|
||||
"maintainers": [
|
||||
{ "name": "boubou666", "link": "https://github.com/boubou666" },
|
||||
@@ -27,5 +27,5 @@
|
||||
"Testing on high-refresh monitors (the experimental smoothed frame rate)",
|
||||
"Testing on Linux"
|
||||
],
|
||||
"notes": "Playable at 60 fps on Windows, built by the launcher from the player's own USA disc. Every Challenge arena played, split screen for 2 to 4 players, memory card saves, rebindable controls including keyboard and mouse, video settings and cheats. Next: story levels 2 to 8 checked to the end, widescreen."
|
||||
"notes": "Playable at a 60 Hz target on Windows, built by the launcher from the player's own USA disc. BozoEngine replaces the previous runtime; native 1P with bots, four-player split screen, level 20, card writes and restart/readback are validated. Rebindable controls, video settings, cheats and default-on heat haze. Next: full campaign endings, every arena rechecked on BozoEngine, physical-controller/clean-OS acceptance and widescreen."
|
||||
}
|
||||
Submodule
+1
Submodule BozoEngine added at 93619608b8.
+39
-1
@@ -7,6 +7,43 @@ under "Unreleased" as they land, then move them under the new version's heading
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.4.0] - 2026-11-06
|
||||
|
||||
### Changed
|
||||
|
||||
- **BozoEngine is now the only recompiler and runtime.** The PS2Recomp submodule, legacy build targets and IOP
|
||||
recompilation steps are removed. TMB and BozoEngine are MIT; release packages retain every third-party licence.
|
||||
- The launcher uses SDL3 and Dear ImGui; the game uses BozoEngine's native window, input, renderer, sound and movie
|
||||
services. Existing memory-card files and settings remain usable.
|
||||
- Two installation ZIPs contain the same BozoEngine build: `-bozo.zip` installs beside the previous port, while the
|
||||
ZIP without that suffix preserves the old launcher's in-place update path. Both use BozoEngine.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Original heat haze enabled by default** around fire and explosions. `BOZO_HEAT_HAZE=0` disables it for comparisons
|
||||
with the previous PC build.
|
||||
- Menu and movie pacing always uses the native clock. An old `TMB_NATIVE_FRAMES=0` setting can no longer select an
|
||||
unpaced path. Timing checks now measure menu ticks and movie picture cadence independently of the FPS counter.
|
||||
- Match-start sound and lens-flare presentation stalls are fixed in the pinned BozoEngine revision.
|
||||
- Building from folders with spaces and accents now keeps GCC's startup objects and static libraries on the
|
||||
safe path and disables unused C++ module scanning. In-place updates remove the retired runtime's source folder
|
||||
without following directory links. Launcher self-tests fail when preparing or starting the game fails.
|
||||
- Native Windows executables use UTF-8 file paths. A changed toolchain invalidates stale configure checks before
|
||||
retrying, and release source exports drain tar padding so they cannot hang waiting for `git archive`.
|
||||
|
||||
### Developer changes
|
||||
|
||||
- All build/run shortcuts use the disc-to-game BozoEngine pipeline. Release audits reject the retired runtime.
|
||||
- Added Windows/Linux CI and regression checks for timing, package contents and the migration ZIP layout.
|
||||
|
||||
### Known limits
|
||||
|
||||
- Only the USA disc is supported. Windows is the validated player target; the migrated Linux player build is not yet validated.
|
||||
- Full campaign endings, a fresh standard-user Windows installation and four physical controllers still need player/hardware acceptance.
|
||||
Widescreen is not implemented; presentation above 60 Hz remains experimental for effects that update at game rate.
|
||||
- Exact native sound-model/sample equality and the old test-only save-cheat replay remain reference-test limitations.
|
||||
Native story progression, card writes, restart/readback and actual four-player play pass; see `docs/HANDOFF.md` for the evidence.
|
||||
|
||||
## [0.3.2] - 2026-11-02
|
||||
|
||||
### Added
|
||||
@@ -123,7 +160,8 @@ 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.3.2...HEAD
|
||||
[Unreleased]: https://github.com/TheBozos/TMB_Recomp/compare/v0.4.0...HEAD
|
||||
[0.4.0]: https://github.com/TheBozos/TMB_Recomp/compare/v0.3.2...v0.4.0
|
||||
[0.3.2]: https://github.com/TheBozos/TMB_Recomp/compare/v0.3.1...v0.3.2
|
||||
[0.3.1]: https://github.com/TheBozos/TMB_Recomp/compare/v0.3.0...v0.3.1
|
||||
[0.3.0]: https://github.com/TheBozos/TMB_Recomp/compare/v0.2.0...v0.3.0
|
||||
|
||||
+4
-135
@@ -1,139 +1,8 @@
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(TMB_Recomp LANGUAGES C CXX)
|
||||
|
||||
# Twisted Metal: Black (USA, SCUS-97101) static recompilation on top of PS2Recomp.
|
||||
#
|
||||
# Build the tools first (scripts/build_tools.sh), generate code (scripts/recomp.sh),
|
||||
# then configure this project to get the `ps2EntryRunner` executable with the
|
||||
# recompiled game linked in.
|
||||
# The port uses no C++ modules. GCC's module mapper cannot represent canonical Windows kit paths with spaces.
|
||||
set(CMAKE_CXX_SCAN_FOR_MODULES OFF)
|
||||
|
||||
set(TMB_GENERATED_DIR "${CMAKE_SOURCE_DIR}/generated" CACHE PATH
|
||||
"Directory containing the output of ps2_recomp for the game ELF")
|
||||
|
||||
# Only the runtime is needed here; the recompiler/analyzer are built separately.
|
||||
set(PS2X_BUILD_RECOMP OFF CACHE BOOL "" FORCE)
|
||||
set(PS2X_BUILD_ANALYZER OFF CACHE BOOL "" FORCE)
|
||||
set(PS2X_BUILD_TEST OFF CACHE BOOL "" FORCE)
|
||||
set(PS2X_BUILD_STUDIO OFF CACHE BOOL "" FORCE)
|
||||
|
||||
# The runner as a PC game (the fork's ps2_app.h): its window title, the per-user folder (%APPDATA%\TMB_Recomp,
|
||||
# $XDG_DATA_HOME/tmb_recomp) for the memory cards, input.ini, video.ini, the log and crash reports, and with no argument
|
||||
# the game data in game/ next to the runner (or in the user folder). No console window (a GUI-subsystem runner: the
|
||||
# output goes to the log, and to the terminal it was started from).
|
||||
set(PS2X_APP_TITLE "Twisted Metal: Black" CACHE STRING "" FORCE)
|
||||
set(PS2X_APP_FOLDER "TMB_Recomp" CACHE STRING "" FORCE)
|
||||
set(PS2X_APP_XDG_FOLDER "tmb_recomp" CACHE STRING "" FORCE)
|
||||
set(PS2X_APP_BOOT_ELF "SCUS_971.01" CACHE STRING "" FORCE)
|
||||
set(PS2X_APP_DATA_FOLDER "game" CACHE STRING "" FORCE)
|
||||
set(PS2X_SHOW_WINDOWS_CONSOLE OFF CACHE BOOL "" FORCE)
|
||||
|
||||
add_subdirectory(PS2Recomp)
|
||||
|
||||
# The runner's icon and version information (runtime/app: a placeholder icon, no game art).
|
||||
if(WIN32)
|
||||
enable_language(RC)
|
||||
target_sources(ps2EntryRunner PRIVATE "${CMAKE_SOURCE_DIR}/runtime/app/tmb.rc")
|
||||
endif()
|
||||
|
||||
file(GLOB TMB_GENERATED_SOURCES CONFIGURE_DEPENDS "${TMB_GENERATED_DIR}/*.cpp")
|
||||
if(NOT TMB_GENERATED_SOURCES)
|
||||
message(FATAL_ERROR
|
||||
"No generated sources in ${TMB_GENERATED_DIR}. Run scripts/recomp.sh first.")
|
||||
endif()
|
||||
|
||||
# The runtime ships a placeholder register_functions.cpp that defines the same
|
||||
# function-table globals as the generated one; drop it from the runner.
|
||||
get_target_property(_runner_sources ps2EntryRunner SOURCES)
|
||||
list(FILTER _runner_sources EXCLUDE REGEX "src/runner/register_functions\\.cpp$")
|
||||
set_property(TARGET ps2EntryRunner PROPERTY SOURCES ${_runner_sources})
|
||||
|
||||
file(GLOB TMB_RUNTIME_SOURCES CONFIGURE_DEPENDS "${CMAKE_SOURCE_DIR}/runtime/*.cpp")
|
||||
# The native texture pack scripts/recomp.sh converts from the disc (runtime/tmb_textures.cpp loads it).
|
||||
target_compile_definitions(ps2EntryRunner PRIVATE TMB_TEXTURE_PACK="${TMB_GENERATED_DIR}/tmb_textures.pack")
|
||||
# The native mesh pack it converts from the disc's NGP files (tools/tmb_mesh_pack.py).
|
||||
target_compile_definitions(ps2EntryRunner PRIVATE TMB_MESH_PACK="${TMB_GENERATED_DIR}/tmb_meshes.pack")
|
||||
|
||||
# IOP modules recompiled to native C++ by the fork's tools/iop_recomp.py (989snd, libsd; PS2X_IOP_NATIVE=1 runs them;
|
||||
# scripts/iop_recomp.sh writes them, derived from the game's IRX files like the rest of generated/): their own object
|
||||
# library, outside the unity batches (each file's names are its own), without debug info.
|
||||
file(GLOB TMB_IOP_NATIVE_SOURCES CONFIGURE_DEPENDS "${TMB_GENERATED_DIR}/iop/*.cpp")
|
||||
if(TMB_IOP_NATIVE_SOURCES)
|
||||
add_library(tmb_iop_native OBJECT ${TMB_IOP_NATIVE_SOURCES})
|
||||
target_link_libraries(tmb_iop_native PRIVATE ps2x::iop)
|
||||
set_target_properties(tmb_iop_native PROPERTIES UNITY_BUILD OFF)
|
||||
if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
|
||||
target_compile_options(tmb_iop_native PRIVATE -O2 -g0)
|
||||
endif()
|
||||
target_sources(ps2EntryRunner PRIVATE $<TARGET_OBJECTS:tmb_iop_native>)
|
||||
endif()
|
||||
# The host OS layer includes <windows.h>, which clashes with raylib names: outside the unity batches and the PCH.
|
||||
set_source_files_properties("${CMAKE_SOURCE_DIR}/runtime/tmb_host.cpp" PROPERTIES
|
||||
SKIP_UNITY_BUILD_INCLUSION ON SKIP_PRECOMPILE_HEADERS ON)
|
||||
|
||||
# VU1 microcode compiled ahead of time by ps2_vu_aot (scripts/recomp.sh): an object library both executables
|
||||
# link, so it compiles once. -O3 unrolls the operand loops over each pair's constexpr decode; debug info is of no
|
||||
# use for it and triples its build time. Each file takes GCC several GB: at most 4 compile at once.
|
||||
file(GLOB TMB_VU1_AOT_SOURCES CONFIGURE_DEPENDS "${TMB_GENERATED_DIR}/vu1/*.cpp")
|
||||
if(TMB_VU1_AOT_SOURCES)
|
||||
set_property(GLOBAL APPEND PROPERTY JOB_POOLS tmb_vu1_aot=4)
|
||||
# With it, microcode loops lifted to native code by hand (runtime/vu1, VU1Interpreter::registerLiftedEntry).
|
||||
file(GLOB TMB_VU1_LIFTED_SOURCES CONFIGURE_DEPENDS "${CMAKE_SOURCE_DIR}/runtime/vu1/*.cpp")
|
||||
add_library(tmb_vu1_aot OBJECT ${TMB_VU1_AOT_SOURCES} ${TMB_VU1_LIFTED_SOURCES})
|
||||
target_link_libraries(tmb_vu1_aot PRIVATE ps2_runtime)
|
||||
set_target_properties(tmb_vu1_aot PROPERTIES UNITY_BUILD OFF JOB_POOL_COMPILE tmb_vu1_aot)
|
||||
# TMB_VU1_AOT_LINES=ON: line tables only (-g1), so a profile of the replay maps samples to the jit helpers.
|
||||
option(TMB_VU1_AOT_LINES "Line tables in the compiled VU1 microcode, for profiling" OFF)
|
||||
if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
|
||||
if(TMB_VU1_AOT_LINES)
|
||||
target_compile_options(tmb_vu1_aot PRIVATE -O3 -g1)
|
||||
else()
|
||||
target_compile_options(tmb_vu1_aot PRIVATE -O3 -g0)
|
||||
endif()
|
||||
endif()
|
||||
target_sources(ps2EntryRunner PRIVATE $<TARGET_OBJECTS:tmb_vu1_aot>)
|
||||
endif()
|
||||
|
||||
target_sources(ps2EntryRunner PRIVATE ${TMB_GENERATED_SOURCES} ${TMB_RUNTIME_SOURCES})
|
||||
target_include_directories(ps2EntryRunner PRIVATE "${TMB_GENERATED_DIR}")
|
||||
|
||||
list(LENGTH TMB_GENERATED_SOURCES _tmb_count)
|
||||
message(STATUS "TMB_Recomp: linking ${_tmb_count} generated source files from ${TMB_GENERATED_DIR}")
|
||||
|
||||
# The VU1 replay tool with the compiled microcode linked in: checks it against runs recorded with
|
||||
# PS2X_VU1_RECORD (build/game/tmb_vu1_replay <trace> [repeat]).
|
||||
if(TMB_VU1_AOT_SOURCES)
|
||||
add_executable(tmb_vu1_replay PS2Recomp/ps2xRuntime/tools/ps2_vu1_replay.cpp $<TARGET_OBJECTS:tmb_vu1_aot>)
|
||||
target_link_libraries(tmb_vu1_replay PRIVATE ps2_runtime)
|
||||
if(WIN32)
|
||||
# PS2X_PROFILE=<seconds>: the fork's sampling profiler, to see where the compiled microcode spends its time.
|
||||
target_sources(tmb_vu1_replay PRIVATE PS2Recomp/ps2xRuntime/src/profiling/sampling_profiler.cpp)
|
||||
target_link_libraries(tmb_vu1_replay PRIVATE raylib winmm) # raylib first: winmm has a PlaySound too
|
||||
endif()
|
||||
endif()
|
||||
|
||||
# Profile-guided optimization (GCC) of the runtime, the IOP and the compiled VU1 microcode, the code the frame time
|
||||
# goes to; the generated game code keeps its flags (it would all rebuild). scripts/pgo.sh: GENERATE, a training run
|
||||
# into the match, then USE. The profile is specific to this build tree and machine, never committed.
|
||||
set(TMB_PGO "OFF" CACHE STRING "Profile-guided optimization: OFF, GENERATE or USE (scripts/pgo.sh)")
|
||||
set_property(CACHE TMB_PGO PROPERTY STRINGS OFF GENERATE USE)
|
||||
set(TMB_PGO_DIR "${CMAKE_BINARY_DIR}/pgo-profile" CACHE PATH "Where TMB_PGO=GENERATE writes the profile USE reads")
|
||||
if(NOT TMB_PGO STREQUAL "OFF" AND CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
|
||||
if(TMB_PGO STREQUAL "GENERATE")
|
||||
set(_tmb_pgo_flags "-fprofile-generate=${TMB_PGO_DIR}" -fprofile-update=atomic)
|
||||
target_link_options(ps2EntryRunner PRIVATE "-fprofile-generate=${TMB_PGO_DIR}")
|
||||
target_sources(ps2EntryRunner PRIVATE "${CMAKE_SOURCE_DIR}/runtime/pgo/tmb_pgo_train.cpp")
|
||||
set_source_files_properties("${CMAKE_SOURCE_DIR}/runtime/pgo/tmb_pgo_train.cpp" PROPERTIES
|
||||
SKIP_UNITY_BUILD_INCLUSION ON SKIP_PRECOMPILE_HEADERS ON)
|
||||
else()
|
||||
set(_tmb_pgo_flags "-fprofile-use=${TMB_PGO_DIR}" -fprofile-partial-training -fprofile-correction -Wno-missing-profile)
|
||||
endif()
|
||||
foreach(_tmb_pgo_target ps2_runtime ps2_iop tmb_vu1_aot)
|
||||
if(TARGET ${_tmb_pgo_target})
|
||||
target_compile_options(${_tmb_pgo_target} PRIVATE ${_tmb_pgo_flags})
|
||||
endif()
|
||||
endforeach()
|
||||
if(TMB_PGO STREQUAL "GENERATE" AND TARGET tmb_vu1_replay)
|
||||
target_link_options(tmb_vu1_replay PRIVATE "-fprofile-generate=${TMB_PGO_DIR}")
|
||||
endif()
|
||||
message(STATUS "TMB_Recomp: profile-guided optimization ${TMB_PGO} (${TMB_PGO_DIR})")
|
||||
endif()
|
||||
# The port is built only on BozoEngine. The pre-migration build remains in the v0.3.2 tag.
|
||||
include(cmake/bozo.cmake)
|
||||
@@ -23,9 +23,8 @@ SOFTWARE.
|
||||
---
|
||||
|
||||
This licence covers TMB_Recomp's own files. It does not cover:
|
||||
- PS2Recomp/ (the runtime and recompiler, a separate project): GPL-3.0, see PS2Recomp/LICENSE.
|
||||
The game executable a player builds links that runtime, so that build is a GPL-3.0 combined work.
|
||||
- BozoEngine/ (the recompiler and runtime, a separate MIT project): 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 (raylib, Dear ImGui, the Exo 2 font, and the build
|
||||
- Third-party components with their own licences (SDL3, Dear ImGui, the Exo 2 font, and the build
|
||||
kit's GCC, binutils, CMake, Ninja, FFmpeg, Python); a release lists them in LICENSES\.
|
||||
-1
Submodule PS2Recomp deleted from 3eb40ffffd.
@@ -0,0 +1,154 @@
|
||||
// tmb-check: BozoEngine's call-log checker (bozo-run: BozoEngine's tools/run/README.md) with TMB's overrides running
|
||||
// natively (BozoEngine's kernel.md section 3b), each call checked against the reference's log:
|
||||
// tmb-check <log.clg> --pinned --ref <run.ref> [--iso <image>] [--pad-script <file>] [--overrides log] ...
|
||||
// The ELF defaults to the one this build was generated from.
|
||||
//
|
||||
// --window (builds with TMB_WINDOW): the same pinned run, its frames shown in a window as they are made (BozoEngine's
|
||||
// window, the renderer's present), to capture the pictures of chosen frames (milestone M5's pixel comparison):
|
||||
// tmb-check <log.clg> ... --window --capture-frames n,n,... [--capture-dir dir] [--width w --height h]
|
||||
// [--render-scale s] [--aspect a]
|
||||
// --capture-frames n: the picture once n frames have ended, i.e. the reference record n - 1's frame (frame_<n>.png). The
|
||||
// run is held at that frame's end until the window has read it back, so the picture is exactly that frame's. The window
|
||||
// is 640x448 at render scale 1 by default; --aspect is the picture's shape inside it (4:3 by default, letterboxed).
|
||||
#include "run_main.h"
|
||||
|
||||
#if TMB_CHECK_WINDOW
|
||||
#include "bozo/app/determinism.h"
|
||||
#include "bozo/app/window.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <mutex>
|
||||
#include <set>
|
||||
#include <sstream>
|
||||
#endif
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#ifndef BOZO_RUN_DEFAULT_ELF
|
||||
#define BOZO_RUN_DEFAULT_ELF ""
|
||||
#endif
|
||||
|
||||
#if TMB_CHECK_WINDOW
|
||||
namespace
|
||||
{
|
||||
// The run held at a capture frame's end until the window read that frame's picture back.
|
||||
struct CaptureGate
|
||||
{
|
||||
std::mutex mutex;
|
||||
std::condition_variable wake;
|
||||
std::set<uint64_t> frames;
|
||||
uint64_t captured = 0; // the last frame count the window captured at
|
||||
bool closing = false;
|
||||
};
|
||||
|
||||
CaptureGate &gate()
|
||||
{
|
||||
static CaptureGate s_gate;
|
||||
return s_gate;
|
||||
}
|
||||
|
||||
int runWindowed(const std::vector<char *> &args)
|
||||
{
|
||||
bozo::app::WindowOptions window;
|
||||
window.title = "Twisted Metal: Black (BozoEngine, pinned)";
|
||||
window.width = 640;
|
||||
window.height = 448;
|
||||
window.renderScale = 1.0f;
|
||||
window.aspect = 4.0f / 3.0f; // the picture's shape, letterboxed in the window (as the fork's window and tmb)
|
||||
window.panel = false;
|
||||
window.stats = false;
|
||||
static std::vector<char *> rest;
|
||||
for (size_t k = 0; k < args.size(); ++k)
|
||||
{
|
||||
const std::string a = args[k];
|
||||
auto value = [&]() -> std::string { return k + 1 < args.size() ? args[++k] : ""; };
|
||||
if (a == "--window")
|
||||
continue;
|
||||
if (a == "--capture-frames")
|
||||
{
|
||||
std::stringstream list(value());
|
||||
for (std::string item; std::getline(list, item, ',');)
|
||||
if (!item.empty())
|
||||
window.captureFrames.push_back(std::stoull(item));
|
||||
}
|
||||
else if (a == "--capture-dir")
|
||||
window.captureDir = value();
|
||||
else if (a == "--width")
|
||||
window.width = std::stoi(value());
|
||||
else if (a == "--height")
|
||||
window.height = std::stoi(value());
|
||||
else if (a == "--render-scale")
|
||||
window.renderScale = std::stof(value());
|
||||
else if (a == "--aspect")
|
||||
window.aspect = std::stof(value());
|
||||
else
|
||||
rest.push_back(args[k]);
|
||||
}
|
||||
|
||||
gate().frames.insert(window.captureFrames.begin(), window.captureFrames.end());
|
||||
bozo::run::setFrameHook([](uint64_t framesEnded) {
|
||||
CaptureGate &g = gate();
|
||||
std::unique_lock<std::mutex> lock(g.mutex);
|
||||
if (!g.frames.count(framesEnded))
|
||||
return;
|
||||
// Held until the window has shown and read back this frame (30 s at most: a closed window lets it go).
|
||||
if (!g.wake.wait_for(lock, std::chrono::seconds(30), [&] { return g.closing || g.captured >= framesEnded; }))
|
||||
std::fprintf(stderr, "tmb-check: no capture of frame %llu within 30 s\n", static_cast<unsigned long long>(framesEnded));
|
||||
});
|
||||
window.onCaptured = [](uint64_t frames) {
|
||||
CaptureGate &g = gate();
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(g.mutex);
|
||||
g.captured = std::max(g.captured, frames);
|
||||
}
|
||||
g.wake.notify_all();
|
||||
};
|
||||
|
||||
bozo::app::Game game;
|
||||
game.run = [] { return bozo::run::main(static_cast<int>(rest.size()), rest.data()); };
|
||||
game.stop = [] {
|
||||
CaptureGate &g = gate();
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(g.mutex);
|
||||
g.closing = true;
|
||||
}
|
||||
g.wake.notify_all();
|
||||
};
|
||||
game.framesEnded = [] { return bozo::det::frame(); };
|
||||
return bozo::app::runWindow(window, game, nullptr);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
std::vector<char *> args(argv, argv + argc);
|
||||
bool hasElf = false, windowed = false;
|
||||
for (int i = 1; i < argc; ++i)
|
||||
{
|
||||
hasElf = hasElf || std::strcmp(argv[i], "--elf") == 0;
|
||||
windowed = windowed || std::strcmp(argv[i], "--window") == 0;
|
||||
}
|
||||
static char elfFlag[] = "--elf";
|
||||
static std::string elf = BOZO_RUN_DEFAULT_ELF;
|
||||
if (!hasElf && !elf.empty() && argc >= 2)
|
||||
{
|
||||
args.push_back(elfFlag);
|
||||
args.push_back(elf.data());
|
||||
}
|
||||
if (windowed)
|
||||
{
|
||||
#if TMB_CHECK_WINDOW
|
||||
return runWindowed(args);
|
||||
#else
|
||||
std::fprintf(stderr, "tmb-check: --window needs a build with TMB_WINDOW\n");
|
||||
return 2;
|
||||
#endif
|
||||
}
|
||||
return bozo::run::main(static_cast<int>(args.size()), args.data());
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
// tmb-headless: Twisted Metal: Black on BozoEngine with no window (phase 4, milestone M0). Every library native, the
|
||||
// disc image read, BozoEngine's own timing (free mode), TMB's overrides native; the native renderer records its frames.
|
||||
//
|
||||
// tmb-headless [--frames n] [--elf SCUS_971.01] [--iso image] [--pad-script [n=]file]... [--card-dir dir]
|
||||
// [--out run.ref] [--report n] [--quiet] [--wav file [--wav-frames a-b]] [--no-sound]
|
||||
//
|
||||
// --pad-script n=file: player n's frame-keyed script (1 when omitted; players 2-4 are the multitap's slots, as the
|
||||
// reference's PS2X_PAD2_SCRIPT..PS2X_PAD4_SCRIPT).
|
||||
//
|
||||
// --wav: the sound the mixer made (48 kHz stereo, 16-bit), from game frame a to b (all of it by default); --no-sound:
|
||||
// the mixer is not brought up at the frames' ends (as before milestone M3).
|
||||
// Every --report frames (500 by default) and at the end: the frame, the EE clock, the function that waited for the
|
||||
// frame's end (the game's loop: uiTitle_Main__Fv at the title), the Shell (the menus' object, gp - 0x4148) and the
|
||||
// overrides that ran.
|
||||
#include "tmb_host.h"
|
||||
#include "tmb_port.h"
|
||||
|
||||
#include "bozo/app/determinism.h"
|
||||
#include "bozo/audio/wav.h"
|
||||
#include "bozo/ee/dispatcher.h"
|
||||
#include "bozo/host/free_host.h"
|
||||
#include "bozo/render/renderer.h"
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <map>
|
||||
#include <string>
|
||||
|
||||
#ifndef BOZO_RUN_DEFAULT_ELF
|
||||
#define BOZO_RUN_DEFAULT_ELF ""
|
||||
#endif
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
bozo::host::FreeOptions opt;
|
||||
opt.elf = BOZO_RUN_DEFAULT_ELF;
|
||||
uint64_t report = 500;
|
||||
std::string wavPath;
|
||||
uint64_t wavFrom = 0, wavTo = UINT64_MAX;
|
||||
for (int k = 1; k < argc; ++k)
|
||||
{
|
||||
const std::string a = argv[k];
|
||||
auto value = [&]() -> std::string { return k + 1 < argc ? argv[++k] : ""; };
|
||||
if (a == "--frames")
|
||||
opt.frames = static_cast<uint32_t>(std::stoul(value()));
|
||||
else if (a == "--elf")
|
||||
opt.elf = value();
|
||||
else if (a == "--iso")
|
||||
opt.iso = value();
|
||||
else if (a == "--pad-script")
|
||||
{
|
||||
std::string v = value();
|
||||
int player = 1;
|
||||
if (v.size() > 2 && v[1] == '=' && v[0] >= '1' && v[0] <= '4')
|
||||
{
|
||||
player = v[0] - '0';
|
||||
v = v.substr(2);
|
||||
}
|
||||
(player == 1 ? opt.padScript : opt.playerScripts[static_cast<size_t>(player - 2)]) = v;
|
||||
}
|
||||
else if (a == "--card-dir")
|
||||
opt.cardDir = value();
|
||||
else if (a == "--out")
|
||||
opt.out = value();
|
||||
else if (a == "--report")
|
||||
report = std::stoull(value());
|
||||
else if (a == "--quiet")
|
||||
opt.quiet = true;
|
||||
else if (a == "--print")
|
||||
opt.printGameOutput = true;
|
||||
else if (a == "--wav")
|
||||
wavPath = value();
|
||||
else if (a == "--wav-frames")
|
||||
{
|
||||
const std::string range = value();
|
||||
const size_t dash = range.find('-');
|
||||
wavFrom = std::stoull(range.substr(0, dash));
|
||||
if (dash != std::string::npos && dash + 1 < range.size())
|
||||
wavTo = std::stoull(range.substr(dash + 1));
|
||||
}
|
||||
else if (a == "--no-sound")
|
||||
opt.sound = false;
|
||||
else
|
||||
{
|
||||
std::fprintf(stderr, "usage: tmb-headless [--frames n] [--elf path] [--iso image] [--pad-script [n=]file]... [--card-dir dir] "
|
||||
"[--out run.ref] [--report n] [--print] [--quiet] [--wav file [--wav-frames a-b]] [--no-sound]\n");
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
if (opt.elf.empty())
|
||||
{
|
||||
std::fprintf(stderr, "tmb-headless: no ELF (--elf)\n");
|
||||
return 2;
|
||||
}
|
||||
tmb::host::setElfDirectory(std::filesystem::path(opt.elf).parent_path().string());
|
||||
if (opt.iso.empty())
|
||||
opt.iso = tmb::findDiscImage(std::filesystem::path(opt.elf).parent_path().string(), "SCUS_971.01");
|
||||
if (opt.iso.empty())
|
||||
{
|
||||
std::fprintf(stderr, "tmb-headless: no disc image (--iso, TMB_ISO, or an .iso beside the ELF)\n");
|
||||
return 2;
|
||||
}
|
||||
// Headless: no host clock reaches the game (determinism.h).
|
||||
bozo::det::setEnabled(true);
|
||||
|
||||
const bozo::port::Port *port = bozo::port::port();
|
||||
bozo::port::Registry registry;
|
||||
port->install(registry);
|
||||
const std::vector<uint32_t> missing = bozo::port::undeclared(registry, tmb_external_table, tmb_external_count);
|
||||
if (!missing.empty())
|
||||
{
|
||||
std::fprintf(stderr, "%zu registered overrides are not externals of the generated code (regenerate):", missing.size());
|
||||
for (uint32_t a : missing)
|
||||
std::fprintf(stderr, " 0x%x", a);
|
||||
std::fprintf(stderr, "\n");
|
||||
return 2;
|
||||
}
|
||||
|
||||
bozo::host::FreeHost host(opt);
|
||||
bozo::ee::Dispatcher d(host);
|
||||
d.setFunctions(tmb_function_table, tmb_function_count, tmb_resume_table, tmb_resume_count);
|
||||
std::string error;
|
||||
if (!host.setUp(d, tmb_external_table, tmb_external_count, ®istry, error))
|
||||
{
|
||||
std::fprintf(stderr, "tmb-headless: %s\n", error.c_str());
|
||||
return 2;
|
||||
}
|
||||
std::printf("tmb-headless: %s, %zu overrides, ELF %s, disc %s\n", port->title, registry.functions().size(), opt.elf.c_str(),
|
||||
opt.iso.c_str());
|
||||
|
||||
// What the game is doing at a frame's end.
|
||||
std::string waiter;
|
||||
uint32_t shell = 0;
|
||||
// The shell's screen: gp - 0x3d2c, which uiMain__Fv switches on through its table at 0x4eae90 (case 0, 0x18ee14,
|
||||
// calls uiTitle_Main__Fv), and the frame it last changed at; -1 outside the shell's loop.
|
||||
int32_t screen = -1;
|
||||
uint64_t screenSince = 0;
|
||||
std::map<int32_t, uint64_t> screens; // frames per screen
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
std::map<std::string, uint64_t> waiters; // the frames each loop function ended
|
||||
auto state = [&](uint64_t frame) {
|
||||
const double secs = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
|
||||
const bozo::render::Renderer &r = bozo::render::Renderer::instance();
|
||||
const auto published = r.published();
|
||||
const auto overlay = r.publishedOverlay();
|
||||
std::printf("frame %llu: EE cycle %llu (%llu vblanks), loop %s, Shell 0x%x, screen %d%s since frame %llu; renderer: 3D "
|
||||
"%zu batches, 2D %zu batches, movie picture %s; %.1f s\n",
|
||||
static_cast<unsigned long long>(frame), static_cast<unsigned long long>(d.now()),
|
||||
static_cast<unsigned long long>(d.kernel().vblankCount()), waiter.c_str(), shell, screen,
|
||||
screen == 0 ? " (uiTitle_Main__Fv)" : "", static_cast<unsigned long long>(screenSince),
|
||||
published ? published->batches.size() : 0u, overlay ? overlay->batches.size() : 0u,
|
||||
r.backdrop() ? "yes" : "no", secs);
|
||||
std::fflush(stdout);
|
||||
};
|
||||
host.onFrame = [&](uint64_t frame, const R5900Context *ctx) {
|
||||
if (ctx)
|
||||
{
|
||||
// The function that called the frame's end (timer1Handler's caller, or sceGsSyncV's): the game's loop.
|
||||
waiter = host.functionAt(ctx->r[31].uw[0]);
|
||||
const std::string fn = waiter.substr(0, waiter.find('+'));
|
||||
++waiters[fn];
|
||||
const uint32_t gp = ctx->r[28].uw[0];
|
||||
int32_t now = -1;
|
||||
if (gp)
|
||||
{
|
||||
std::memcpy(&shell, d.runtime().memory.ram() + ((gp - 0x4148u) & 0x1FFFFFCu), 4);
|
||||
if (fn == "uiMain__Fv")
|
||||
std::memcpy(&now, d.runtime().memory.ram() + ((gp - 0x3D2Cu) & 0x1FFFFFCu), 4);
|
||||
}
|
||||
if (now != screen)
|
||||
{
|
||||
screen = now;
|
||||
screenSince = frame;
|
||||
}
|
||||
++screens[now];
|
||||
}
|
||||
if (report && (frame + 1) % report == 0 && !opt.quiet)
|
||||
state(frame + 1);
|
||||
};
|
||||
bozo::audio::WavWriter wav;
|
||||
if (!wavPath.empty())
|
||||
{
|
||||
if (!wav.open(wavPath))
|
||||
{
|
||||
std::fprintf(stderr, "tmb-headless: cannot write %s\n", wavPath.c_str());
|
||||
return 2;
|
||||
}
|
||||
host.onAudio = [&](uint64_t frame, const int16_t *samples, size_t count) {
|
||||
if (frame >= wavFrom && frame <= wavTo)
|
||||
wav.write(samples, count);
|
||||
};
|
||||
}
|
||||
const uint64_t frames = host.run();
|
||||
if (wav.isOpen())
|
||||
{
|
||||
std::printf("wav: %s, %.1f s of sound\n", wavPath.c_str(), wav.frames() / 48000.0);
|
||||
wav.close();
|
||||
}
|
||||
state(frames);
|
||||
const bozo::host::FreeStats &s = host.stats();
|
||||
std::printf("end: %s; %llu frames; %llu library calls, %llu kernel calls, %llu override calls, %llu VU0 programs, %llu "
|
||||
"hardware accesses (%llu to registers the I/O model does not know)\n",
|
||||
host.endReason().empty() ? "every thread ended" : host.endReason().c_str(), static_cast<unsigned long long>(frames),
|
||||
static_cast<unsigned long long>(s.libraryCalls), static_cast<unsigned long long>(s.kernelCalls),
|
||||
static_cast<unsigned long long>(s.overrideCalls), static_cast<unsigned long long>(s.vu0Calls),
|
||||
static_cast<unsigned long long>(s.ioAccesses), static_cast<unsigned long long>(s.ioUnknown));
|
||||
std::printf("frame ends by loop function:");
|
||||
for (const auto &[fn, n] : waiters)
|
||||
std::printf(" %s %llu;", fn.c_str(), static_cast<unsigned long long>(n));
|
||||
std::printf("\nframes per shell screen (-1: outside the shell's loop):");
|
||||
for (const auto &[sc, n] : screens)
|
||||
std::printf(" %d: %llu;", sc, static_cast<unsigned long long>(n));
|
||||
std::printf("\noverride calls:");
|
||||
for (const auto &[a, n] : host.overrideCalls())
|
||||
std::printf(" 0x%x:%llu", a, static_cast<unsigned long long>(n));
|
||||
std::printf("\n");
|
||||
// The pads the game found and read: each socket's reads (port.slot), and whether the multitap was open.
|
||||
const bozo::libs::PadState &pads = host.libraries().pad;
|
||||
std::printf("pad reads (port.slot: reads; multitap %s):", pads.multitap ? "open" : "closed");
|
||||
for (int p = 0; p < 2; ++p)
|
||||
for (int sl = 0; sl < 4; ++sl)
|
||||
std::printf(" %d.%d: %llu;", p + 1, sl, static_cast<unsigned long long>(pads.socketReads[p][sl]));
|
||||
std::printf("\n");
|
||||
for (const auto &[name, n] : s.unanswered)
|
||||
std::printf("no native answer: %s (%llu)\n", name.c_str(), static_cast<unsigned long long>(n));
|
||||
return host.endReason().rfind("FAULT", 0) == 0 ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
// tmb: Twisted Metal: Black on BozoEngine in a window, in real time (phase 4, milestones M1 and M2). The free host as
|
||||
// tmb-headless runs it (every library native, the disc image read, TMB's overrides native), with the host's clock: the
|
||||
// game's frames held to the field rate (TMB's native frame end, bozo::app::FramePacer), each one presented in an SDL3
|
||||
// window through OpenGL 3.3 (bozo::app::runWindow). The players' pads: the keyboard, mouse and up to four gamepads
|
||||
// through input.ini's bindings (bozo::app::DevicePad; with the game's multitap, players 2-4 are its slots), or the
|
||||
// frame-keyed scripts given.
|
||||
//
|
||||
// tmb [--iso image] [--elf SCUS_971.01] [--card-dir dir] [--width w --height h] [--fullscreen] [--no-vsync]
|
||||
// [--render-scale s] [--capture-dir dir] [--capture-frames n,n,...] [--quit-after n] [--pad-script [n=]file]...
|
||||
// [--no-sound] [--audio-latency ms] [--audio-stats] [--wav file]
|
||||
//
|
||||
// The user folder (%APPDATA%\TMB_Recomp, as the fork's TMB; PS2X_USER_DIR overrides it) holds input.ini, the memory
|
||||
// cards (mc0, mc1; --card-dir overrides) and the logs (logs/TMB_Recomp.log). Without --elf the game data is looked for
|
||||
// as the fork's TMB did (<exe>/game/SCUS_971.01, then the same in the user folder).
|
||||
//
|
||||
// Milestone M4, as the fork's TMB: F2 the settings window (Controls: input.ini; Video: video.ini in the user folder,
|
||||
// --width / --height / --fullscreen (borderless) / --render-scale over it; Cheats: runtime/tmb_cheats.cpp), F3 the
|
||||
// frame rate counter (PS2X_SHOW_FPS=1 from the start), F8 a capture sequence (PS2X_CAPTURE_SEQUENCE presents,
|
||||
// PS2X_CAPTURE_SEQUENCE_AT seconds), F9 a burst of captures, ten a second; --capture-frames saves the game's picture at
|
||||
// the first present after each of those game frames. The captures go to --capture-dir, else PS2X_CAPTURE_WINDOW_DIR,
|
||||
// else <user folder>/captures. F11 / Alt+Enter: between the window and the last full-screen mode. --quit-after: close
|
||||
// after that many frames. PS2X_FRAME_STATS=1: the frames' work times every 2 s (the FramePacer).
|
||||
//
|
||||
// Sound (milestone M3): the mixer's samples, made on the EE clock at each frame's end, go to the default playback device
|
||||
// (bozo::app::AudioDevice: a queue of --audio-latency ms, 32 by default, plus the device's buffer). --audio-stats: the
|
||||
// queue, latency and underruns every 2 s. --wav (or PS2X_AUDIO_RECORD): what the mixer made, also to a WAV file.
|
||||
#include "tmb_host.h"
|
||||
#include "tmb_port.h"
|
||||
|
||||
#include "bozo/app/app.h"
|
||||
#include "bozo/app/audio_device.h"
|
||||
#include "bozo/app/determinism.h"
|
||||
#include "bozo/audio/wav.h"
|
||||
#include "bozo/app/device_pad.h"
|
||||
#include "bozo/app/input_bindings.h"
|
||||
#include "bozo/app/video_settings.h"
|
||||
#include "bozo/app/window.h"
|
||||
#include "bozo/ee/dispatcher.h"
|
||||
#include "bozo/host/free_host.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <filesystem>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
|
||||
#ifndef BOZO_RUN_DEFAULT_ELF
|
||||
#define BOZO_RUN_DEFAULT_ELF ""
|
||||
#endif
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
// The fork's TMB identity (its PS2X_APP_* CMake values): the same user folder, so the cards and input.ini carry over.
|
||||
bozo::app::Identity identity;
|
||||
identity.title = "Twisted Metal: Black";
|
||||
identity.folder = "TMB_Recomp";
|
||||
identity.xdgFolder = "tmb_recomp";
|
||||
identity.bootElf = "SCUS_971.01";
|
||||
identity.dataFolder = "game";
|
||||
bozo::app::setIdentity(identity);
|
||||
bozo::app::startLogging();
|
||||
bozo::app::installCrashHandler();
|
||||
|
||||
bozo::host::FreeOptions opt;
|
||||
opt.elf = BOZO_RUN_DEFAULT_ELF;
|
||||
opt.realTime = true;
|
||||
opt.quiet = true;
|
||||
bozo::app::WindowOptions window;
|
||||
window.title = "Twisted Metal: Black (BozoEngine)";
|
||||
bozo::app::AudioOptions audio;
|
||||
bool sound = true;
|
||||
std::string wavPath;
|
||||
if (const char *record = std::getenv("PS2X_AUDIO_RECORD"); record && *record)
|
||||
wavPath = record;
|
||||
// The command line's window options, over video.ini (applied once the user folder is known, below).
|
||||
int width = 0, height = 0;
|
||||
bool fullscreen = false;
|
||||
float renderScale = 0.0f;
|
||||
for (int k = 1; k < argc; ++k)
|
||||
{
|
||||
const std::string a = argv[k];
|
||||
auto value = [&]() -> std::string { return k + 1 < argc ? argv[++k] : ""; };
|
||||
if (a == "--elf")
|
||||
opt.elf = value();
|
||||
else if (a == "--iso")
|
||||
opt.iso = value();
|
||||
else if (a == "--card-dir")
|
||||
opt.cardDir = value();
|
||||
else if (a == "--pad-script")
|
||||
{
|
||||
// [n=]file: player n's script (1 when omitted; players 2-4: the multitap's slots)
|
||||
std::string v = value();
|
||||
int player = 1;
|
||||
if (v.size() > 2 && v[1] == '=' && v[0] >= '1' && v[0] <= '4')
|
||||
{
|
||||
player = v[0] - '0';
|
||||
v = v.substr(2);
|
||||
}
|
||||
(player == 1 ? opt.padScript : opt.playerScripts[static_cast<size_t>(player - 2)]) = v;
|
||||
}
|
||||
else if (a == "--width")
|
||||
width = std::stoi(value());
|
||||
else if (a == "--height")
|
||||
height = std::stoi(value());
|
||||
else if (a == "--fullscreen")
|
||||
fullscreen = true;
|
||||
else if (a == "--no-vsync")
|
||||
window.vsync = false;
|
||||
else if (a == "--render-scale")
|
||||
renderScale = std::stof(value());
|
||||
else if (a == "--capture-dir")
|
||||
window.captureDir = value();
|
||||
else if (a == "--capture-frames")
|
||||
{
|
||||
std::stringstream list(value());
|
||||
for (std::string item; std::getline(list, item, ',');)
|
||||
if (!item.empty())
|
||||
window.captureFrames.push_back(std::stoull(item));
|
||||
}
|
||||
else if (a == "--quit-after")
|
||||
window.quitAfterFrames = std::stoull(value());
|
||||
else if (a == "--print")
|
||||
opt.printGameOutput = true;
|
||||
else if (a == "--no-sound")
|
||||
sound = false;
|
||||
else if (a == "--audio-latency")
|
||||
audio.latencyMs = std::stod(value());
|
||||
else if (a == "--audio-stats")
|
||||
audio.stats = true;
|
||||
else if (a == "--wav")
|
||||
wavPath = value();
|
||||
else
|
||||
{
|
||||
std::fprintf(stderr, "usage: tmb [--iso image] [--elf path] [--card-dir dir] [--width w] [--height h] [--fullscreen] "
|
||||
"[--no-vsync] [--render-scale s] [--capture-dir dir] [--capture-frames n,n,...] [--quit-after n] "
|
||||
"[--pad-script [n=]file]... [--print] [--no-sound] [--audio-latency ms] [--audio-stats] [--wav file]\n");
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
// The window as the player set it (video.ini in the user folder, the fork's file; PS2X_WINDOW_SIZE / _MODE,
|
||||
// PS2X_RENDER_SCALE over it), then the command line over both.
|
||||
bozo::app::video::loadAtStartup(window.width, window.height);
|
||||
{
|
||||
bozo::app::video::Settings &v = bozo::app::video::edited();
|
||||
if (width > 0 && height > 0)
|
||||
v.width = width, v.height = height;
|
||||
if (fullscreen)
|
||||
v.mode = bozo::app::video::WindowMode::Borderless;
|
||||
if (renderScale > 0.0f)
|
||||
v.renderScale = renderScale;
|
||||
}
|
||||
window.videoSettings = true;
|
||||
std::error_code ec;
|
||||
if (opt.elf.empty() || !std::filesystem::is_regular_file(opt.elf, ec))
|
||||
{
|
||||
std::string searched;
|
||||
const std::filesystem::path found = bozo::app::findGameData(&searched);
|
||||
if (found.empty())
|
||||
{
|
||||
std::fprintf(stderr, "tmb: no ELF (--elf); looked for the game data at\n%s", searched.c_str());
|
||||
return 2;
|
||||
}
|
||||
opt.elf = found.string();
|
||||
}
|
||||
// The memory cards in the user folder (<user>/mc0, mc1: the fork's layout, its saves read as they are).
|
||||
if (opt.cardDir.empty() && !bozo::app::userDirectory().empty())
|
||||
opt.cardDir = bozo::app::userDirectory().string();
|
||||
tmb::host::setElfDirectory(std::filesystem::path(opt.elf).parent_path().string());
|
||||
if (opt.iso.empty())
|
||||
opt.iso = tmb::findDiscImage(std::filesystem::path(opt.elf).parent_path().string(), "SCUS_971.01");
|
||||
if (opt.iso.empty())
|
||||
{
|
||||
std::fprintf(stderr, "tmb: no disc image (--iso, TMB_ISO, or an .iso beside the ELF)\n");
|
||||
return 2;
|
||||
}
|
||||
// Real time: the host's clock reaches the game (frame steps, the EE charged the real time a frame took).
|
||||
bozo::det::setEnabled(false);
|
||||
|
||||
const bozo::port::Port *port = bozo::port::port();
|
||||
bozo::port::Registry registry;
|
||||
port->install(registry);
|
||||
const std::vector<uint32_t> missing = bozo::port::undeclared(registry, tmb_external_table, tmb_external_count);
|
||||
if (!missing.empty())
|
||||
{
|
||||
std::fprintf(stderr, "%zu registered overrides are not externals of the generated code (regenerate)\n", missing.size());
|
||||
return 2;
|
||||
}
|
||||
|
||||
bozo::host::FreeHost host(opt);
|
||||
bozo::ee::Dispatcher d(host);
|
||||
d.setFunctions(tmb_function_table, tmb_function_count, tmb_resume_table, tmb_resume_count);
|
||||
std::string error;
|
||||
if (!host.setUp(d, tmb_external_table, tmb_external_count, ®istry, error))
|
||||
{
|
||||
std::fprintf(stderr, "tmb: %s\n", error.c_str());
|
||||
return 2;
|
||||
}
|
||||
bozo::app::DevicePad pad;
|
||||
bool scripted = !opt.padScript.empty();
|
||||
for (const std::string &script : opt.playerScripts)
|
||||
scripted = scripted || !script.empty();
|
||||
if (!scripted)
|
||||
host.libraries().pad.input = &pad;
|
||||
const std::string pads = scripted ? std::string("the scripts") : "the PC's devices (" + bozo::app::input::configPath() + ")";
|
||||
std::fprintf(stderr, "tmb: user folder %s, memory cards in %s, pads from %s\n", bozo::app::userDirectory().string().c_str(),
|
||||
opt.cardDir.empty() ? "memory" : opt.cardDir.c_str(), pads.c_str());
|
||||
std::fprintf(stderr, "tmb: %s, %zu overrides, ELF %s, disc %s\n", port->title, registry.functions().size(), opt.elf.c_str(),
|
||||
opt.iso.c_str());
|
||||
|
||||
// The sound: what the mixer makes at each frame's end, to the device (and the WAV file).
|
||||
bozo::app::AudioDevice device(audio);
|
||||
bozo::audio::WavWriter wav;
|
||||
if (!wavPath.empty() && !wav.open(wavPath))
|
||||
std::fprintf(stderr, "tmb: cannot write %s\n", wavPath.c_str());
|
||||
if (sound)
|
||||
device.open();
|
||||
if (device.isOpen() || wav.isOpen())
|
||||
host.onAudio = [&](uint64_t, const int16_t *samples, size_t count) {
|
||||
device.push(samples, count);
|
||||
wav.write(samples, count);
|
||||
};
|
||||
|
||||
bozo::app::Game game;
|
||||
game.run = [&]
|
||||
{
|
||||
const uint64_t frames = host.run();
|
||||
if (device.isOpen())
|
||||
{
|
||||
const bozo::app::AudioDevice::Stats a = device.stats();
|
||||
std::fprintf(stderr, "tmb: sound: %.1f s pushed, %llu frames dropped, %llu underruns (%.1f ms of silence); queue %.1f ms "
|
||||
"(%.1f-%.1f) + device %.1f ms; ratio %.4f\n",
|
||||
a.pushed / 48000.0, static_cast<unsigned long long>(a.dropped), static_cast<unsigned long long>(a.underruns),
|
||||
a.missing / 48.0, a.queueMs, a.minQueueMs, a.maxQueueMs, a.deviceMs, a.ratio);
|
||||
device.close();
|
||||
}
|
||||
wav.close();
|
||||
std::fprintf(stderr, "tmb: the game ended after %llu frames: %s\n", static_cast<unsigned long long>(frames),
|
||||
host.endReason().empty() ? "every thread ended" : host.endReason().c_str());
|
||||
return host.endReason().rfind("FAULT", 0) == 0 ? 1 : 0;
|
||||
};
|
||||
game.stop = [&] { host.requestStop(); };
|
||||
game.framesEnded = [&] { return host.framesEnded(); };
|
||||
return bozo::app::runWindow(window, game, &pad);
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
# TMB on BozoEngine (phase 4, BozoEngine's docs/phase4-inventory.md): TMB's runtime/ built against BozoEngine instead
|
||||
# of the PS2Recomp fork. Milestone M0: headless; M1: the window (tmb), the packs built from the disc.
|
||||
#
|
||||
# cmake -S . -B build/bozo -G Ninja -DBOZO_ENGINE_DIR=<BozoEngine> -DTMB_ELF=<SCUS_971.01>
|
||||
# -DTMB_ISO=<the disc image> [-DBOZO_FFMPEG_ROOT=<kit>/ffmpeg] [-DTMB_WINDOW=OFF]
|
||||
#
|
||||
# Targets:
|
||||
# - tmb: the game in a window, in real time (SDL3, OpenGL 3.3: BozoEngine's bozo_app; TMB_WINDOW, on by default).
|
||||
# - tmb_packs: the texture and mesh packs (tools/tmb_texture_pack.py, tools/tmb_mesh_pack.py on BozoEngine's
|
||||
# tools/native_pack) from the disc image's files, into <build>/packs; the runtime's built-in pack paths point there.
|
||||
# - tmb-headless: the game on BozoEngine with no window (the free host: every library native, the disc image read,
|
||||
# BozoEngine's own timing); it reports the frames and the game's state.
|
||||
# - tmb-check: BozoEngine's call-log checker (bozo-run, tools/run/README.md) with TMB's overrides running natively:
|
||||
# tmb-check <log.clg> --pinned --ref <run.ref> ...
|
||||
#
|
||||
# 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)
|
||||
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")
|
||||
set(TMB_GEN_OPT "-O1" CACHE STRING "Optimisation of the generated code")
|
||||
if(WIN32)
|
||||
enable_language(RC)
|
||||
set_source_files_properties("${CMAKE_SOURCE_DIR}/runtime/app/utf8.rc" PROPERTIES
|
||||
OBJECT_DEPENDS "${CMAKE_SOURCE_DIR}/runtime/app/tmb.manifest")
|
||||
endif()
|
||||
function(tmb_native_manifest target)
|
||||
if(WIN32)
|
||||
target_sources(${target} PRIVATE "${CMAKE_SOURCE_DIR}/runtime/app/utf8.rc")
|
||||
endif()
|
||||
endfunction()
|
||||
set(TMB_ISO "" CACHE FILEPATH "TMB's disc image (the packs are built from its files)")
|
||||
set(TMB_DISC_DIR "" CACHE PATH "The packs' files already extracted from the disc (tools/tmb_build.py: <dir>/.extracted marks them done); else read from TMB_ISO here")
|
||||
option(TMB_WINDOW "Build tmb, the game in a window (BozoEngine's bozo_app: SDL3, OpenGL 3.3)" ON)
|
||||
if(NOT BOZO_ENGINE_DIR OR NOT EXISTS "${BOZO_ENGINE_DIR}/CMakeLists.txt")
|
||||
message(FATAL_ERROR "TMB: set BOZO_ENGINE_DIR to BozoEngine's source tree")
|
||||
endif()
|
||||
if(NOT TMB_ELF OR NOT EXISTS "${TMB_ELF}")
|
||||
message(FATAL_ERROR "TMB: set TMB_ELF to the game's executable (SCUS_971.01)")
|
||||
endif()
|
||||
set(CMAKE_CXX_STANDARD 20)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
if(NOT CMAKE_BUILD_TYPE)
|
||||
set(CMAKE_BUILD_TYPE Release)
|
||||
endif()
|
||||
|
||||
# BozoEngine's own TMB generation (its call-log checks) is not wanted here: TMB generates its own.
|
||||
set(BOZO_TMB_ELF "" CACHE FILEPATH "" FORCE)
|
||||
set(BOZO_APP ${TMB_WINDOW} CACHE BOOL "" FORCE)
|
||||
add_subdirectory("${BOZO_ENGINE_DIR}" bozo)
|
||||
|
||||
find_package(Python3 REQUIRED COMPONENTS Interpreter)
|
||||
|
||||
set(gen_dir "${CMAKE_BINARY_DIR}/tmb_gen")
|
||||
set(overrides_list "${gen_dir}/tmb_overrides.txt")
|
||||
set(externals "${gen_dir}/tmb_externals.txt")
|
||||
file(GLOB TMB_RUNTIME_SOURCES CONFIGURE_DEPENDS "${CMAKE_SOURCE_DIR}/runtime/*.cpp")
|
||||
|
||||
add_custom_command(
|
||||
OUTPUT ${overrides_list}
|
||||
COMMAND ${CMAKE_COMMAND} -E make_directory ${gen_dir}
|
||||
COMMAND Python3::Interpreter "${CMAKE_SOURCE_DIR}/tools/tmb_overrides_list.py" "${CMAKE_SOURCE_DIR}/runtime" ${overrides_list}
|
||||
DEPENDS "${CMAKE_SOURCE_DIR}/tools/tmb_overrides_list.py" ${TMB_RUNTIME_SOURCES}
|
||||
COMMENT "Listing TMB's overrides")
|
||||
add_custom_command(
|
||||
OUTPUT ${externals}
|
||||
COMMAND bozo-externals ${TMB_ELF} ${externals} --overrides ${overrides_list} --stubs "${CMAKE_SOURCE_DIR}/recomp/tmb_stubs.txt"
|
||||
DEPENDS bozo-externals ${overrides_list} "${CMAKE_SOURCE_DIR}/recomp/tmb_stubs.txt" ${TMB_ELF}
|
||||
COMMENT "Writing the externals list")
|
||||
|
||||
set(gen_files ${gen_dir}/tmb_functions.h ${gen_dir}/tmb_table.cpp)
|
||||
math(EXPR last "${TMB_GEN_FILES} - 1")
|
||||
foreach(i RANGE ${last})
|
||||
string(LENGTH "${i}" len)
|
||||
if(len EQUAL 1)
|
||||
set(n "00${i}")
|
||||
elseif(len EQUAL 2)
|
||||
set(n "0${i}")
|
||||
else()
|
||||
set(n "${i}")
|
||||
endif()
|
||||
list(APPEND gen_files ${gen_dir}/tmb_${n}.cpp)
|
||||
endforeach()
|
||||
add_custom_command(
|
||||
OUTPUT ${gen_files}
|
||||
COMMAND bozo-recomp ${TMB_ELF} ${gen_dir} --prefix tmb --files ${TMB_GEN_FILES} --no-comments --externals ${externals}
|
||||
DEPENDS bozo-recomp ${externals} ${TMB_ELF}
|
||||
COMMENT "Recompiling TMB")
|
||||
# The generated code alone (tools/tmb_build.py's recompile step, before the compile).
|
||||
add_custom_target(tmb_recompile DEPENDS ${gen_files})
|
||||
add_library(tmb_generated OBJECT ${gen_files})
|
||||
target_link_libraries(tmb_generated PUBLIC bozo_runtime_headers)
|
||||
target_include_directories(tmb_generated PUBLIC ${gen_dir})
|
||||
target_compile_options(tmb_generated PRIVATE ${TMB_GEN_OPT} -w)
|
||||
|
||||
# TMB's runtime: an object library (its port registration, BOZO_PORT, must be linked whatever references it).
|
||||
add_library(tmb_runtime OBJECT ${TMB_RUNTIME_SOURCES})
|
||||
target_include_directories(tmb_runtime PUBLIC "${CMAKE_SOURCE_DIR}/runtime" ${gen_dir})
|
||||
target_link_libraries(tmb_runtime PUBLIC bozo_port bozo_render bozo_libs bozo_runtime_core)
|
||||
# The Cheats tab of the settings window (F2): ImGui's core and the tab list (bozo_ui, no SDL3; BOZO_SETTINGS_UI), with
|
||||
# the window. The headless programs link it too and never draw it.
|
||||
if(TMB_WINDOW)
|
||||
target_link_libraries(tmb_runtime PUBLIC bozo_ui)
|
||||
endif()
|
||||
add_dependencies(tmb_runtime tmb_generated)
|
||||
target_compile_options(tmb_runtime PRIVATE -Wall -Wno-unused-function -Wno-unused-variable -Wno-unused-but-set-variable)
|
||||
# The draw lists as the reference build (the fork) computed them (the PS2XREF1 `draws` field): it compiled TMB's runtime
|
||||
# at -O2 (its RelWithDebInfo flags) and its native renderer library at -O3 (Release), both for AVX2 with FMA, and GCC
|
||||
# fuses a * b + c there (-ffp-contract=fast, its default outside ISO mode) where its inlining lets it. The matrices and
|
||||
# vertices TMB and the mesh submitter (BozoEngine's render/mesh_draw.cpp, moved from the fork) compute for the draws are
|
||||
# those fused results, so the same flags here give the same draws (match1p: every frame; -O3 for the runtime or no FMA:
|
||||
# the first difference within ten frames of the match's start). Nothing the game computes depends on them (the
|
||||
# generated code and BozoEngine's libraries keep their own flags). A CPU without FMA (before 2013's Haswell, 2011's
|
||||
# Bulldozer) cannot run it, as it could not run the fork's.
|
||||
set(TMB_RUNTIME_ARCH "-mavx2;-mfma" CACHE STRING "Instruction set flags of TMB's runtime and the renderer (the reference build's)")
|
||||
set(TMB_RUNTIME_OPT "-O2" CACHE STRING "Optimisation of TMB's runtime (the reference build's)")
|
||||
target_compile_options(tmb_runtime PRIVATE ${TMB_RUNTIME_ARCH} ${TMB_RUNTIME_OPT})
|
||||
target_compile_options(bozo_render PRIVATE ${TMB_RUNTIME_ARCH})
|
||||
# The packs: from the disc image's files (only those they read: .TEX, .RTX, .NGP, .PTR), into the build folder; with
|
||||
# TMB_DISC_DIR, from files already extracted there (tools/tmb_build.py). Both paths build the packs locally.
|
||||
if(TMB_ISO OR TMB_DISC_DIR)
|
||||
set(pack_dir "${CMAKE_BINARY_DIR}/packs")
|
||||
set(disc_dir "${CMAKE_BINARY_DIR}/disc")
|
||||
set(native_pack "${BOZO_ENGINE_DIR}/tools/native_pack")
|
||||
file(GLOB native_pack_sources CONFIGURE_DEPENDS "${native_pack}/*.py")
|
||||
if(TMB_DISC_DIR)
|
||||
set(disc_dir "${TMB_DISC_DIR}")
|
||||
else()
|
||||
add_custom_command(
|
||||
OUTPUT "${disc_dir}/.extracted"
|
||||
COMMAND Python3::Interpreter "${native_pack}/ps2_disc.py" extract "${TMB_ISO}" "${disc_dir}" --ext .TEX,.RTX,.NGP,.PTR
|
||||
COMMAND ${CMAKE_COMMAND} -E touch "${disc_dir}/.extracted"
|
||||
DEPENDS "${TMB_ISO}" "${native_pack}/ps2_disc.py"
|
||||
COMMENT "Reading the packs' files from the disc image")
|
||||
endif()
|
||||
add_custom_command(
|
||||
OUTPUT "${pack_dir}/tmb_textures.pack"
|
||||
COMMAND ${CMAKE_COMMAND} -E make_directory "${pack_dir}"
|
||||
COMMAND ${CMAKE_COMMAND} -E env "BOZO_ENGINE_TOOLS=${BOZO_ENGINE_DIR}/tools"
|
||||
"${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/tools/tmb_texture_pack.py" "${disc_dir}" "${TMB_ELF}" "${pack_dir}/tmb_textures.pack"
|
||||
DEPENDS "${disc_dir}/.extracted" "${CMAKE_SOURCE_DIR}/tools/tmb_texture_pack.py" ${native_pack_sources} "${TMB_ELF}"
|
||||
COMMENT "Building the texture pack")
|
||||
add_custom_command(
|
||||
OUTPUT "${pack_dir}/tmb_meshes.pack"
|
||||
COMMAND ${CMAKE_COMMAND} -E make_directory "${pack_dir}"
|
||||
COMMAND ${CMAKE_COMMAND} -E env "BOZO_ENGINE_TOOLS=${BOZO_ENGINE_DIR}/tools"
|
||||
"${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/tools/tmb_mesh_pack.py" "${disc_dir}" "${pack_dir}/tmb_meshes.pack"
|
||||
DEPENDS "${disc_dir}/.extracted" "${CMAKE_SOURCE_DIR}/tools/tmb_mesh_pack.py" ${native_pack_sources}
|
||||
COMMENT "Building the mesh pack")
|
||||
add_custom_target(tmb_packs ALL DEPENDS "${pack_dir}/tmb_textures.pack" "${pack_dir}/tmb_meshes.pack")
|
||||
add_dependencies(tmb_runtime tmb_packs)
|
||||
else()
|
||||
message(FATAL_ERROR "Set TMB_ISO or TMB_DISC_DIR to build the native texture and mesh packs")
|
||||
endif()
|
||||
target_compile_definitions(tmb_runtime PRIVATE TMB_TEXTURE_PACK="${pack_dir}/tmb_textures.pack"
|
||||
TMB_MESH_PACK="${pack_dir}/tmb_meshes.pack")
|
||||
|
||||
if(TARGET bozo_run)
|
||||
add_executable(tmb-check bozo/tmb_check.cpp)
|
||||
tmb_native_manifest(tmb-check)
|
||||
target_link_libraries(tmb-check PRIVATE tmb_runtime tmb_generated bozo_run)
|
||||
target_compile_definitions(tmb-check PRIVATE BOZO_RUN_DEFAULT_ELF="${TMB_ELF}")
|
||||
# --window: the pinned run shown in BozoEngine's window, its chosen frames captured (milestone M5's pictures).
|
||||
if(TMB_WINDOW)
|
||||
target_link_libraries(tmb-check PRIVATE bozo_app)
|
||||
target_compile_definitions(tmb-check PRIVATE TMB_CHECK_WINDOW=1)
|
||||
endif()
|
||||
if(MINGW)
|
||||
target_link_options(tmb-check PRIVATE -static -Wl,--stack,268435456)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
add_executable(tmb-headless bozo/tmb_headless.cpp)
|
||||
tmb_native_manifest(tmb-headless)
|
||||
target_link_libraries(tmb-headless PRIVATE tmb_runtime tmb_generated bozo_host)
|
||||
target_compile_definitions(tmb-headless PRIVATE BOZO_RUN_DEFAULT_ELF="${TMB_ELF}")
|
||||
if(MINGW)
|
||||
target_link_options(tmb-headless PRIVATE -static -Wl,--stack,268435456)
|
||||
endif()
|
||||
|
||||
if(TMB_WINDOW)
|
||||
add_executable(tmb bozo/tmb_window.cpp)
|
||||
tmb_native_manifest(tmb)
|
||||
target_link_libraries(tmb PRIVATE tmb_runtime tmb_generated bozo_host bozo_app)
|
||||
target_compile_definitions(tmb PRIVATE BOZO_RUN_DEFAULT_ELF="${TMB_ELF}")
|
||||
if(WIN32)
|
||||
enable_language(RC)
|
||||
target_sources(tmb PRIVATE "${CMAKE_SOURCE_DIR}/runtime/app/tmb.rc")
|
||||
# A player's build (tools/tmb_build.py): a GUI-subsystem exe, no console window; started from a terminal it
|
||||
# still prints there (bozo::app attaches to the parent's console).
|
||||
option(TMB_GUI_SUBSYSTEM "tmb.exe without a console window (the players' build)" OFF)
|
||||
if(TMB_GUI_SUBSYSTEM)
|
||||
set_target_properties(tmb PROPERTIES WIN32_EXECUTABLE ON)
|
||||
endif()
|
||||
endif()
|
||||
if(MINGW)
|
||||
target_link_options(tmb PRIVATE -static -Wl,--stack,268435456)
|
||||
endif()
|
||||
endif()
|
||||
+117
-71
@@ -1,86 +1,132 @@
|
||||
# Handoff (2026-11-01)
|
||||
# TMB on BozoEngine — 2026-11-05
|
||||
|
||||
Where the work stands and how to pick it up on another machine. Details and history are in `RECOMP_NOTES.md`.
|
||||
The goal is to remove the PS2Recomp fork from the project. This source tree now builds **only on BozoEngine**.
|
||||
The earlier v0.3.2 release remains in Git history and on GitHub for comparison; it is not a runtime dependency.
|
||||
|
||||
## Goal
|
||||
## Architecture and build
|
||||
|
||||
The game smooth (its own 60 fps, the USA release only: the European one is dropped) and fully playable as a true PC
|
||||
program: no PS2 hardware simulated where the PC can do the job itself. Locked runs on 2026-11-01: a 1P match
|
||||
57.7-60.4 fps, 4P split screen 55.8-60.4. Earlier:
|
||||
- One submodule: `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.
|
||||
- Heat haze defaults on, as requested. `BOZO_HEAT_HAZE=0` is the comparison switch.
|
||||
- Existing cards/settings keep their format and `%APPDATA%\TMB_Recomp` location. Agent runs must set a scratch `PS2X_USER_DIR`.
|
||||
|
||||
| Release | Path | fps mean | slowest tenth |
|
||||
|---|---|---|---|
|
||||
| USA (`SCUS-97101`, NTSC) | native (`scripts/run_native.sh`, 2x resolution) | 58.9 | 58.5 |
|
||||
## Validation recorded in this continuation
|
||||
|
||||
Windows, Ryzen 7 7800X3D, RTX 5070 Ti; scripted play through the menus into the first arena (`tools/play_script.py`).
|
||||
- Engine: all 5 local CTest checks pass, including the corrected FMAC overflow case and its new boundary cases.
|
||||
- Whole-function replay: **9,232/9,232 samples, 1,518/1,518 functions**, bit-exact.
|
||||
- Real-time menu/movie diagnostic: EE/PC **1.0001**, **576,005 ticks/s**, **59.97 fields/s**; movies **29.93–30.00 pictures/s**.
|
||||
The owner also said the freshly launched build no longer felt too fast. This measurement used the handoff build's existing clock fixes;
|
||||
the continuation adds a regression guard and removes the unpaced legacy frame switch.
|
||||
- Native story run without a call log: **26,000 frames**, stage progression, card files written, no fault.
|
||||
- Boot pinned: **MATCH**, 3,000/3,000 state frames; draws 2,999/3,000 (the established last-record exception).
|
||||
- 1P pinned: **MATCH**, 16,000/16,000 state frames; draws 15,999/16,000 (the same last-record exception).
|
||||
- Stage 6 pinned: the old frame-7105 interrupt mismatch is resolved. **11,000/11,000 state and draw frames match with recorded IOP-time sound replies**.
|
||||
Two events retain an ancestor pc in the reference; the checker accepts these only with an active inner call, matching function/caller,
|
||||
and an **exact cycle and checkpoint count**, and reports them separately. It does not shift their timing.
|
||||
- Release-tool regressions: 12 tests pass, including accelerated menus/movies, migration layout, retired source cleanup,
|
||||
junction boundaries, configure retry and archive-pipe completion. No game data is needed by those tests.
|
||||
- Engine and TMB Windows/Linux CI pass. The native package workflow's test run
|
||||
[42121468079](https://github.com/TheBozos/TMB_Recomp/actions/runs/42121468079) also passed, including its bundled-toolchain smoke check.
|
||||
|
||||
## Setting up a new machine
|
||||
### Packaged Windows build and updates
|
||||
|
||||
1. Install the requirements in the README (CMake, Ninja, GCC 13+, FFmpeg dev libs, X11/Wayland + OpenGL headers,
|
||||
bsdtar, an AVX2 CPU). The native port draws with OpenGL 3.3. A Vulkan driver is only needed for the PS2 path's
|
||||
paraLLEl-GS (`scripts/run.sh`), fetched by CMake with its shaders precompiled.
|
||||
2. `git clone --recurse-submodules https://github.com/TheBozos/TMB_Recomp.git`. `PS2Recomp` is the fork
|
||||
`TheBozos/PS2Recomp`; TMB pins a commit of its `native/renderer` branch (the native work, merged into `main` as it
|
||||
settles).
|
||||
3. The game data is not in the repository (never commit it). Put your own ISO at the repo root, then follow "Build and
|
||||
run" in the README: `extract_iso.sh`, `build_tools.sh`, `recomp.sh`, `build_runtime.sh`, optionally
|
||||
`iop_recomp.sh` (`game_us/`, `generated_us/`, `build/game_us`).
|
||||
4. On Windows: MSYS2 UCRT64 with its GCC, as in the README's Windows section; `scripts/stage_dlls.sh` after a build
|
||||
to start the runner outside the MSYS2 shell. No `perf`: use the fork's sampling profiler (`PS2X_PROFILE=<s>`).
|
||||
5. The first build compiles about 3500 generated files. A change to `ps2_runtime.h`, `ps2_memory.h` or
|
||||
`gs_frontend.h` rebuilds all of them.
|
||||
- Candidate `0.4.0-test.20261105.3`, code `b9c42cb`, engine `9361960`: both player ZIPs pass the archive audit and SHA-256 checks.
|
||||
All **7,750 files** have identical contents between the two installation layouts. The corresponding-source ZIP's hash passes too.
|
||||
- Built and played from `D:\BozoScratch\finish\Jérôme Jeux\TMB_Recomp_Bozo`, using only the bundled kit.
|
||||
The final packaged launcher stopped the build at 40%, resumed it, staged the native executable and launched it.
|
||||
The complete preparation took 126 seconds on this development PC; this is not a clean-OS performance promise.
|
||||
- The launcher self-test completed normal Play/shutdown (exit 0), English/French settings screenshots,
|
||||
and an intentional child crash with a usable report. Failure paths now fail the self-test instead of returning a false success.
|
||||
- Final packaged menu/movie log: **1.0000** EE/PC, **575,964 ticks/s**, **59.97 fields/s**, movies **29.94–30.00 pictures/s**.
|
||||
`tools/check_timing.py` passes with `TMB_NATIVE_FRAMES=0`. The fresh 2,400-frame accent-path run also passes.
|
||||
- The **actual v0.3.2 updater** installed the unsuffixed migration ZIP. The subsequent new build removed the retired
|
||||
`source/PS2Recomp` marker, preserved player-data sentinels, rebuilt, and started BozoEngine.
|
||||
The new updater separately installed its `-bozo.zip` payload into an old-named `TMB_Recomp` folder and preserved its settings marker.
|
||||
- These are test candidates, not a published release. No new tag has been pushed.
|
||||
|
||||
## Current state
|
||||
### Final gameplay and profiling checks (2026-11-06)
|
||||
|
||||
- **Playable.** Boot, movies (the USA release's story cinematics too), menus, loading, matches (driving, weapons, AI,
|
||||
sound, HUD, split screen), deaths, respawns, game over, saving and loading. Story mode: level 1 of 8 checked.
|
||||
- **The native path** (`TMB_NATIVE=1`, `scripts/run_native.sh`):
|
||||
- frames on the PC's clock (`timer1HandlerNative`, the fork's `FramePacer`; `TMB_NATIVE_FRAMES=0` for the vblanks);
|
||||
- 3D from an offline mesh pack at the game's per-object hook, in the game's order, clipped to its own clip volume
|
||||
(`runtime/tmb_meshes.cpp`); effects from the particle lists (`runtime/tmb_particles.cpp`); 2D builders rewritten
|
||||
(`runtime/tmb_2d.cpp`); textures from an offline pack (`runtime/tmb_textures.cpp`); VU0 programs in C++
|
||||
(`runtime/tmb_vu0.cpp`); no VU1 or VU0 interpreter;
|
||||
- no GS front end: no GS object, memory or thread; the DMA kicks to GIF / VIF0 / VIF1 complete unread; the native
|
||||
renderer presents the frame at 2x (`PS2X_GS_SCALE`);
|
||||
- sound: the recompiled 989snd's libsd calls on the fork's native mixer, the SPU2 absent (`TMB_NATIVE_AUDIO=0`
|
||||
brings it back);
|
||||
- the IOP: no hardware model and no interpreted instruction (`[iop:hw]`); its kernel services answered natively.
|
||||
- the settings window (F2): controls, video (resolution, windowed / fullscreen / borderless, render scale), cheats;
|
||||
the window shows each game frame once (no periodic stutter).
|
||||
- **Controls.** Rebindable to keys, controllers and the mouse: F2 in the game, saved to `input.ini`.
|
||||
- **Known gaps.** Not checked yet: every arena and story level to the endings. Widescreen and frame rates above the
|
||||
PS2's are not started (the game's update steps in whole fields).
|
||||
All runs use isolated user folders, the USA disc, engine `9361960` and the packaged build's game code.
|
||||
These figures measure **game-thread work**, not the interval between displayed pictures:
|
||||
|
||||
## Measuring
|
||||
| Scene | Measured frames | Mean work | Mean p95 | Maximum work | Over 16.7 ms |
|
||||
|---|---:|---:|---:|---:|---:|
|
||||
| 1P, bots active, after 125 s | 4,458 | 3.77 ms | 4.57 ms | 8.2 ms | 0 |
|
||||
| Actual four-player split-screen, after 100 s | 3,136 | 4.51 ms | 5.40 ms | 12.5 ms | 0 |
|
||||
| Effects-heavy story level 20, after 125 s | 4,098 | 2.72 ms | 3.54 ms | 11.2 ms | 0 |
|
||||
|
||||
- **Check runs.** A pad script reaching the match about 150 s in: `PS2X_PAD_SCRIPT="$(tools/play_script.py 230)"`,
|
||||
with `TMB_TRACE_FRAMES=1` (frame split and CPU per host thread every 100 frames; under native frames also the game's
|
||||
fields per real second, 60 when it runs at its own speed). `PS2X_CAPTURE_DIR` saves the presented picture
|
||||
every few seconds, `PS2X_CAPTURE_WINDOW_DIR` the window as shown, `PS2X_WINDOW_SIZE=1280x960` a bigger window.
|
||||
- **Timeline.** `TMB_TRACE_TIMELINE=<file>`, then `tools/timeline.py <file> [frame] [count]`.
|
||||
- **What is still read or emulated.** `TMB_TRACE_PACKETS=1`: per 250 frames, packets read, chains walked, VU0
|
||||
interpreter runs (all 0 by default); `[audio] native mixer` lines every 10 s with the SPU2 counters (all 0).
|
||||
- **Live diagnosis.** `TMB_LIVE_TOGGLES=<file>` (words read every 60 frames: nodepth, nofog, flat, noguard, dump...)
|
||||
and F9 bursts of window captures: let the owner drive to a spot scripts can't reach.
|
||||
- **Comparison modes.** `TMB_NATIVE_VIF=1` (+ `TMB_NATIVE_MESHES_CHECK=1`), `TMB_NATIVE_MESHES=0 TMB_NATIVE_CHECK=<n>`
|
||||
(VU1's own output beside the translation), `PS2X_VU0_HLE_CHECK=1`, `PS2X_AUDIO_RECORD=<wav>` on either sound path.
|
||||
- **Shared machine.** Only timed runs go through the bench lock (`tools/bench_lock.sh`); builds and visual checks run
|
||||
freely. Discard the first run after a build on Windows (Defender scans the new files).
|
||||
- 1P and level 20 each completed 12,000 frames; four-player completed 9,000. Gameplay intervals hold about 60
|
||||
updates/presents per second. Whole-run averages including loading are 59.7–59.9 updates/s. Occasional presentation
|
||||
intervals over 20 ms still occur; do not describe this as zero hitches on all hardware.
|
||||
- Repeated the handoff's exact 7,500-frame four-pad command, including captures at 6,000 and 7,000. Its old script
|
||||
actually stays on opponent selection in this real-time build. The previous 42-present/s dip did not recur on that
|
||||
same screen: frames 7,000–7,300 remained at 60 presents/s.
|
||||
- For the real split-screen run, omitted player 1's initial `1292:CROSS/18` from the local `p1_frames.txt` input;
|
||||
the native build has already reached the main menu there, so that old intro-skip press selects ONE PLAYER.
|
||||
Kept all other four-pad events unchanged. Captures at 6,000 and 8,000 show all four views, driving and firing.
|
||||
AI suppression was off; the four-human deathmatch itself has four human vehicles. Bot coverage comes from 1P.
|
||||
- One further historical 1P timing pair (125–195 s) measured 3.77 ms native versus 5.49 ms on the previous runtime,
|
||||
with no game-work frames over budget in either. This is a limited local comparison, not a cross-hardware speedup claim.
|
||||
- Completed the previously unwritten raw-profile output and fixed `hitch.py`'s imported `__file__` namespace in the local
|
||||
profiling tools. A 20-second sample contains 20,475 raw thread samples. Its game-thread pacer segmentation labels
|
||||
100 of 1,129 segments over 16.7 ms, but work samples are similar in the two groups (2.1 versus 1.8 per segment).
|
||||
The largest gaps line up with the profiler's 0.5-second thread enumeration; they cannot be counted as actual missed
|
||||
game frames. The game's own statistics in that interval show 4.51 ms mean, 8.9 ms maximum, zero over budget.
|
||||
Mesh submission and VU work remain the main CPU buckets. Mixer worker/COP2 inlining/GL batching remain optional
|
||||
optimization opportunities; none was introduced without a demonstrated frame-budget problem.
|
||||
- Restarted for 6,000 headless frames with a copy of the card written by the native story run. It reached gameplay
|
||||
without a fault; the four existing card files remain intact. This is restart/readback coverage, not a full-campaign-ending claim.
|
||||
- The new updater also passed in the accented `TMB_Recomp_Bozo` layout, **running from its own bundled Python**.
|
||||
It safely set aside loaded Python DLLs, installed the payload, preserved the player-data marker, and the updated Python starts.
|
||||
|
||||
## Next steps
|
||||
The source migration and README review are merged through [PR #3](https://github.com/TheBozos/TMB_Recomp/pull/3).
|
||||
The retired fork checkout, Git metadata and both linked worktrees are preserved independently at
|
||||
`D:\TMB_Retired\2026-11-05`; they are no longer an active submodule or local submodule configuration.
|
||||
|
||||
1. Story levels 2-8 to the endings, fixing what shows up (the owner's reports first); every Challenge arena is checked
|
||||
(the Cheats tab's Unlock everything, `TMB_UNLOCK_ALL=1`, opens the locked ones).
|
||||
2. Widescreen; frame rates above the PS2's (interpolating between game updates).
|
||||
3. Later, a bigger project: the PS2-shaped software layer the recompiled code still runs in (guest threads, DMA kicks,
|
||||
the IOP modules' RPC) replaced by the game's systems as PC code.
|
||||
## Limits of the old reference comparisons
|
||||
|
||||
## Working conventions
|
||||
- Native 989SND uses its own timing. Default pinned story/4P/stage runs can differ on opaque play handles or the instant a sound ends.
|
||||
Recorded sound replies let the remaining native game state/draws be checked. Those replies are a checker option and never used by the player build.
|
||||
- The old pinned `save` recording still differs inside the test-only kill-enemies cheat's copied-context guest call at frame 5458.
|
||||
The native campaign run does proceed through the kills, stage transitions and real card writes. Do not describe the old pinned save recording as MATCH.
|
||||
- Audio sample hashes are diagnostic, not an enforced equality claim; the existing handoff documents the few-sample timing differences.
|
||||
- A fresh standard-user Windows OS, SmartScreen/Mark of the Web, physical high-DPI displays and additional human/controller acceptance need real hardware testing.
|
||||
|
||||
- Commit as `Thomas Martin <[email protected]>`, never a personal e-mail. End commits with
|
||||
the `Co-Authored-By` line used in the history.
|
||||
- Fixes to the runtime, IOP or recompiler go into the fork `TheBozos/PS2Recomp`, not into workarounds here. Push the
|
||||
fork first, then bump the submodule here.
|
||||
- Run the fork tests before pushing (`ps2x_tests`, 610+ cases), and a TMB check run on the USA release.
|
||||
- Push with Git for Windows (`/c/Program Files/Git/cmd/git.exe`): MSYS2's git hangs without credentials.
|
||||
- Never edit a script a running or queued job will execute; clear a stale bench lock entry if a job dies holding it.
|
||||
## Packaging and updates
|
||||
|
||||
Both player ZIPs carry **the same BozoEngine build**:
|
||||
|
||||
| File | Root folder | Purpose |
|
||||
|---|---|---|
|
||||
| `TMB_Recomp-<version>-bozo.zip` | `TMB_Recomp_Bozo/` | Separate/new installation |
|
||||
| `TMB_Recomp-<version>.zip` | `TMB_Recomp/` | Existing launcher's in-place Update |
|
||||
|
||||
The older ZIP name does not retain the older engine. The existing updater can install the migration ZIP;
|
||||
the new launcher subsequently uses `-bozo.zip` updates regardless of its installation folder name.
|
||||
The corresponding-source ZIP and every SHA-256 accompany a published release.
|
||||
|
||||
Requirements: Windows 10 version 1903 or newer / Windows 11, **AVX2 + FMA**, OpenGL 3.3, about 10 GB free. Only the USA disc is supported.
|
||||
Follow [RELEASE_CHECKLIST.md](RELEASE_CHECKLIST.md). Do not publish a release tag merely because a test artifact builds.
|
||||
|
||||
## Working rules
|
||||
|
||||
- README follows the shared The Bozos project format: preserve its banner/badges, disc notice/hash, status screenshots,
|
||||
milestone/native-layer tables, goal, architecture, requirements, build/run, controls/cheats, disc facts, layout and credits.
|
||||
Updating stale facts is not permission to replace that presentation with a shorter standalone README.
|
||||
- Clean-room rules in `BozoEngine/docs/PLAN.md` still apply: do not read the old fork, its generated code or emulator source when writing engine code.
|
||||
- Push engine changes before the TMB pin; use reviewed branches/PRs and green CI. End commits with a `Co-Authored-By` line.
|
||||
- Do not modify game/disc files or commit derived content. Never modify the owner's real user folder during agent runs.
|
||||
- Keep scratch/builds on D:. Never edit a script while a job runs it, send input to other windows, or kill another project's processes.
|
||||
- The shared benchmark mechanism is for timing runs only; builds and functional checks do not take it. Do not announce its state.
|
||||
|
||||
## Local evidence
|
||||
|
||||
Continuation scratch: `D:\BozoScratch\finish`. Source worktrees: `D:\TMB_bozo` and `D:\BozoEngine`.
|
||||
Logs include `diag.log`, `ctest-final.log`, `replay/report.txt`, `pin-boot.log`, `pin-match1p.log`, `pin-stage6.log`,
|
||||
`save-free.log` and the deliberately retained failing `save-fixes.log` comparison.
|
||||
Final evidence: `final-launcher-shots/selftest.log`, `final-launcher-user/logs/TMB_Recomp.1.log`, `migration3.log`,
|
||||
`native-update3.log`, `future-update3.log`, `scene-1p.log`, `four-player.log`, `scene-stage.log`, `hitch-report.txt`,
|
||||
`scene-hitch.samples` (original), `scene-hitch-symbols.samples` (same samples with the Unicode module path resolved
|
||||
through a hard link to the same executable), and `save-readback.log`.
|
||||
+37
-87
@@ -1,97 +1,47 @@
|
||||
# Release checklist: a clean Windows PC before each release
|
||||
# Release checklist: BozoEngine-only TMB
|
||||
|
||||
Take the draft the release workflow made from the version tag (README, "Making a release"; or `tools/make_release.py`
|
||||
by hand), then check the zip on a Windows 10 or 11 PC that has never seen
|
||||
the project: a fresh VM or a spare PC, nothing installed (no MSYS2, git, Python, Visual C++ redistributables), a
|
||||
standard user account, Defender on. Tick each line, write what differed in "Notes", and keep the filled copy with the
|
||||
release (or in the release's issue).
|
||||
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.
|
||||
|
||||
Release: `TMB_Recomp-<version>.zip`, SHA-256 `<from the .sha256>`, commit `<commit>`.
|
||||
## Source and CI
|
||||
|
||||
## Download and unzip
|
||||
- [x] TMB's only runtime submodule is `BozoEngine`, pinned to a public, reviewed commit.
|
||||
- [x] No PS2Recomp gitlink, CMake target, Python import fallback, IOP recompiler or legacy runner script remains.
|
||||
- [x] Engine Windows/Linux CI and TMB release-tool Windows/Linux CI pass.
|
||||
- [x] Local engine instruction/runtime/library/audio tests and whole-function replay pass.
|
||||
- [x] Pinned boot and 1P match agree on RAM, scratchpad, calls, threads and draws (the established final-frame exception is recorded).
|
||||
- [x] Stage 6 passes its previous interrupt point. Report native sound-model differences separately from runs using recorded IOP-time replies.
|
||||
- [ ] Full native story completion. Card writes and a 6,000-frame restart/readback pass; the 26,000-frame story progression does not cover the campaign ending.
|
||||
|
||||
- [ ] The release page's SHA-256 equals `Get-FileHash .\TMB_Recomp-<version>.zip` (and `certutil -hashfile <zip>
|
||||
SHA256`).
|
||||
- [ ] Unzip with Explorer's "Extract all" (the zip carries the Mark of the Web from the browser).
|
||||
- [ ] SmartScreen: double-click `TMB Launcher.exe`: "Windows protected your PC", **More info**, **Run anyway**; it starts.
|
||||
(Once per exe; the downloaded zip's files carry the mark, the game built on the PC does not.)
|
||||
- [ ] Defender: no detection while unzipping, at the launcher's start, during the build (it scans the compiler's
|
||||
output; note how much it slows the compile: Task Manager, "Antimalware Service Executable"), at Play.
|
||||
- [ ] A path with spaces and non-ASCII characters: `C:\Users\Jérôme\Jeux\TMB_Recomp-<version>\` (a user name with an
|
||||
accent puts the user folder `%APPDATA%\TMB_Recomp` under it too).
|
||||
- [ ] Not in `C:\Program Files`: unzip there, start the launcher: preparing fails to write (the README says not to);
|
||||
note the message the player gets.
|
||||
## Timing and rendering
|
||||
|
||||
## The disc
|
||||
- [x] Menus: timer ticks and fields advance at their real-time rates, independently of presentation FPS.
|
||||
- [x] Movies: measure decoded picture cadence and run `tools/check_timing.py` on the log.
|
||||
- [ ] Human watch/listen acceptance of a full intro and story movie.
|
||||
- [x] Native clock pacing stays active even with an old `TMB_NATIVE_FRAMES=0` environment setting.
|
||||
- [x] Heat haze defaults on; `BOZO_HEAT_HAZE=0` restores the earlier port's rendering for comparisons.
|
||||
- [x] 1P with bots, actual four-player selection/split-screen, and the effects-heavy stage hold the 60 Hz target; timing logs are retained.
|
||||
- [x] Recheck the previous four-player present dip around frames 7000–7300 with captures at 6000 and 7000 (same opponent-selection screen, 60 presents/s).
|
||||
- [ ] F2 Controls/Video/Cheats, mouse/keyboard launcher navigation and fullscreen switching remain usable.
|
||||
|
||||
- [ ] The USA ISO on another drive than the release (or on a USB disk): accepted; `game\disc.iso` is a copy (3.8 GB
|
||||
more on the release's drive; the launcher asks for about 10 GB free), not a hard link.
|
||||
- [ ] The USA ISO on the same drive: `game\disc.iso` a hard link (no extra space).
|
||||
- [ ] A `.bin` + `.cue` (MODE2/2352): accepted, converted to `game\disc.iso` (a copy).
|
||||
- [ ] The European disc: refused, "This is the European disc. Only the USA disc (SCUS-97101) is supported."
|
||||
- [ ] Another PS2 game, a non-disc file: refused with a plain message.
|
||||
## Packages
|
||||
|
||||
## Preparing
|
||||
- [x] `TMB_Recomp-<version>-bozo.zip` contains one `TMB_Recomp_Bozo/` folder.
|
||||
- [x] `TMB_Recomp-<version>.zip` contains the identical BozoEngine payload under `TMB_Recomp/` for the old launcher's Update path.
|
||||
- [x] Both player ZIPs pass the package audit and their SHA-256 checks. Neither contains PS2Recomp or game-derived files.
|
||||
- [ ] The corresponding-source ZIP and licences accompany a published release.
|
||||
- [x] README and release notes state Windows 10/11, AVX2 + FMA, OpenGL 3.3 and approximately 10 GB free.
|
||||
- [x] Extract the player ZIP, then build from the player's USA disc with only its bundled kit, offline.
|
||||
- [x] Test a path with spaces/non-ASCII, cancellation/resume, Play, and restart.
|
||||
- [ ] Human F2 controls/video/cheats and fullscreen switching on the final package.
|
||||
- [x] Test the migration ZIP through the previous updater; source files removed by this release disappear, saves/settings survive, rebuild starts the BozoEngine executable.
|
||||
- [x] Test future updates of both folder layouts with the BozoEngine updater, including replacement of its own bundled Python DLLs.
|
||||
|
||||
- [ ] No internet (cable out / VM network off) from the launcher's start to Play: the build needs nothing from the
|
||||
network; the update check stays silent.
|
||||
- [ ] Timing on a 4-core / 8 GB PC (and on the 8-core reference): each step's time from `build\logs` or the launcher,
|
||||
the total "Prepared in". The PC stays usable meanwhile.
|
||||
- [ ] Stop at the compile, close the launcher (it asks first), start it again: "Continue preparing" resumes; "Prepared
|
||||
in" is the sum of both runs.
|
||||
- [ ] Free space: the launcher warns under 10 GB.
|
||||
## Clean-PC and player acceptance
|
||||
|
||||
## Playing
|
||||
- [ ] On a fresh standard-user Windows installation: SmartScreen/Mark of the Web, Defender, no MSYS2/Python/git/VC++ redist installed.
|
||||
- [ ] 150%/200% display scaling and controller interaction checked on real hardware.
|
||||
- [ ] Existing saves read correctly; movies, menus and matches feel right to the owner.
|
||||
- [ ] Record any remaining limitations explicitly in release notes before publication.
|
||||
|
||||
- [ ] Play: the boot movies, the main menu, a match; the launcher hides and comes back when the game closes.
|
||||
- [ ] F2 settings in the game; Settings' window mode / size in the launcher used at the next start.
|
||||
- [ ] A crash (`PS2X_TEST_CRASH=25`, or `--selftest ... --crash-seconds 25`): the launcher offers the crash report.
|
||||
- [ ] High DPI: Windows' scaling at 150 % and 200 % (Settings, Display): the launcher readable, nothing clipped on
|
||||
each tab; the game's window and F2 panel usable.
|
||||
|
||||
## Updating and removing
|
||||
|
||||
- [ ] With an older release published: "Version X is available" on the Play tab, "Open the release page" opens it.
|
||||
- [ ] Settings, "Check for updates at start: off": no request at start (a proxy log, or offline: nothing changes).
|
||||
- [ ] With an older release installed: **Update** on the Play tab downloads, installs and restarts the launcher on the
|
||||
new version (Maintenance shows it); no `update\` folder or `*.tmb-old` file is left after the next start.
|
||||
- [ ] Unzip the new release over the old one: the Play tab says the new version is installed and offers **Rebuild
|
||||
now**; after it, the notice is gone, the memory cards (`%APPDATA%\TMB_Recomp\mc0`, `mc1`) and settings are
|
||||
unchanged, the game plays.
|
||||
- [ ] Uninstall: delete the release folder, then `%APPDATA%\TMB_Recomp`: nothing else was written (no registry, no
|
||||
Start menu entry, no other folder: check `%LOCALAPPDATA%`, `%TEMP%`; `%ProgramData%\TMB_Recomp\paths` empty or
|
||||
absent: the junctions of a non-ASCII path are removed after each build).
|
||||
|
||||
## Before publishing
|
||||
|
||||
- [ ] `CHANGELOG.md`'s section for the version says what changed, for players; the draft's body is that section
|
||||
(plus the hashes and the source offer). The launcher's "What's new" (footer) shows the same section.
|
||||
- [ ] The draft has the zip, its `.sha256`, the sources zip and its `.sha256` (the GPL / LGPL corresponding source of
|
||||
the kit's MSYS2 binaries); the workflow's smoke checks passed (its summary).
|
||||
- [ ] Published by the owner on GitHub (the workflow only ever makes a draft).
|
||||
|
||||
## Results on the development PC
|
||||
|
||||
2026-11-01, Windows 10 Home 22H2 (16 threads, 1920 x 1080 at 100 %), not a clean PC: what could be checked here.
|
||||
Release `TMB_Recomp-0.1.0-test.zip` (commit ac63080, fork 1466e9d, SHA-256
|
||||
`8fc2cb3713f171d9493646587c83c21944221868d5e719da0410bfa0aaaeb214`), then `0.1.1-test` (commit 29179f4) over it.
|
||||
|
||||
| Check | Result |
|
||||
|---|---|
|
||||
| SHA-256 | `Get-FileHash` equals the `.sha256` file |
|
||||
| Unzip | PowerShell's `Expand-Archive` (no Mark of the Web: SmartScreen not exercised) into `D:\tmb_rel_test\Jérôme Jeux\` (spaces and accents), 96 s |
|
||||
| Non-ASCII path with spaces | **Failed three times, fixed**: ps2_recomp could not open the ELF (UTF-8 manifest, fork), windres's preprocessor (a space in the path: bare `gcc`), ld (junctions with plain names). Then: built and played from there |
|
||||
| European disc | Refused: "This is the European disc. Only the USA disc (SCUS-97101) is supported." (launcher screenshot; `tmb_build --check` exit 1) |
|
||||
| `.bin` + `.cue` | A MODE2/2352 image made from the ISO (4.36 GB) in `D:\tmb_rel_test\bin cue Jérôme\`: `--check` OK; extract 30.9 s, `disc.iso` a copy (1 link) byte-identical to the ISO. The copy path is the one an ISO on another drive takes; no second drive here (C: has 12 GB free) |
|
||||
| ISO on the same drive | `game\disc.iso` a hard link |
|
||||
| Preparing, Stop / resume | From an empty folder 186.6 s (extract 3.4, recompile 5.2, packs 33.4, iop 2.8, configure 5.3, compile 20 + 114.4 after a stop at 40 %, stage 0.2); "Prepared in 3:07", the sum of both runs |
|
||||
| 4-core / 8 GB | Not available here (16 threads) |
|
||||
| No internet | Not unplugged. The update check pointed at a closed port: silent, no notice; the real API (no release published yet, 404): silent. The build's network use is none by construction (FetchContent fully disconnected, the kit's sources) |
|
||||
| Defender | On, no detection while unzipping, building or playing; scan time not measured |
|
||||
| Play | Boot movies and the main menu (window captures), `GS scale 1` from video.ini, closed with code 0, the launcher back |
|
||||
| Crash report | `PS2X_TEST_CRASH=25`: exit 0xC0000005, the report offered |
|
||||
| High DPI | No 150 % / 200 % display here: `--ui-scale 1.5` and `2`. The layout did not fit a 1920 x 1080 screen at 150 % (1680 x 1140): the scale is now lowered to fit (1.32), every tab readable, nothing clipped; the Maintenance rows were made fixed-height (six rows overflowed the card at 1x). A real high-DPI monitor is still to check |
|
||||
| Update notice | A local server answering as the API with `v0.2.0`: "Version 0.2.0 is available", the link `.../releases/tag/v0.2.0`, "update available" in the footer and Maintenance |
|
||||
| Rebuild after an update | 0.1.1-test unzipped over 0.1.0-test (`-Force`): "Version 0.1.1-test is installed", Rebuild now; 31.8 s (recompile, packs, iop, configure again; nothing to compile); `built_from.ini` updated; the memory card file and video.ini byte-identical before and after; played again |
|
||||
| Uninstall | Not run here; the launcher writes only the release folder and the user folder (and, for a non-ASCII path, junctions under `%ProgramData%\TMB_Recomp\paths` removed after each build) |
|
||||
| Program Files | Not run (needs administrator rights to unzip there) |
|
||||
The development PC can verify an isolated source/build-kit flow, but cannot prove the fresh-OS, SmartScreen or real high-DPI checks by itself.
|
||||
+51
-30
@@ -1,16 +1,20 @@
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
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 runner's CMake needs the generated
|
||||
# code): raylib, Dear ImGui and rlImGui at the tags the fork's ps2xRuntime pins, built static, a GUI-subsystem exe that
|
||||
# needs no DLL. Windows only.
|
||||
# (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.
|
||||
#
|
||||
# cmake -S launcher -B build/launcher -G Ninja -DCMAKE_BUILD_TYPE=Release
|
||||
# cmake --build build/launcher -> build/launcher/TMB Launcher.exe
|
||||
#
|
||||
# Offline (the build kit): -DFETCHCONTENT_SOURCE_DIR_RAYLIB=<kit>/deps/raylib-src (IMGUI, RLIMGUI likewise) and
|
||||
# -DLAUNCHER_FONT_DIR=<dir with Exo2[wght].ttf and OFL.txt>.
|
||||
# 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).")
|
||||
@@ -21,33 +25,47 @@ 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")
|
||||
if(NOT EXISTS "${LAUNCHER_BOZO_DIR}/runtime/app/png.cpp")
|
||||
message(FATAL_ERROR "No BozoEngine at ${LAUNCHER_BOZO_DIR} (git submodule update --init BozoEngine)")
|
||||
endif()
|
||||
|
||||
include(FetchContent)
|
||||
if(POLICY CMP0169)
|
||||
cmake_policy(SET CMP0169 OLD) # FetchContent_Populate, as the fork uses it
|
||||
endif()
|
||||
set(BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
|
||||
set(BUILD_GAMES OFF CACHE BOOL "" FORCE)
|
||||
FetchContent_Declare(raylib GIT_REPOSITORY "https://github.com/raysan5/raylib.git" GIT_TAG "5.5" GIT_SHALLOW TRUE)
|
||||
FetchContent_MakeAvailable(raylib)
|
||||
FetchContent_Declare(imgui GIT_REPOSITORY https://github.com/ocornut/imgui.git GIT_TAG "v1.92.7-docking" GIT_SHALLOW TRUE)
|
||||
FetchContent_Declare(rlImGui GIT_REPOSITORY https://github.com/raylib-extras/rlImGui.git GIT_TAG "Raylib_5_5" GIT_SHALLOW TRUE)
|
||||
FetchContent_GetProperties(imgui)
|
||||
if(NOT imgui_POPULATED)
|
||||
FetchContent_Populate(imgui)
|
||||
endif()
|
||||
FetchContent_GetProperties(rlImGui)
|
||||
if(NOT rlimgui_POPULATED)
|
||||
FetchContent_Populate(rlImGui)
|
||||
endif()
|
||||
# SDL3, static, without audio, camera, GPU or renderer (the launcher starts only the video subsystem: mouse and
|
||||
# keyboard, OpenGL).
|
||||
set(SDL_SHARED OFF CACHE BOOL "" FORCE)
|
||||
set(SDL_STATIC ON CACHE BOOL "" FORCE)
|
||||
set(SDL_TEST_LIBRARY OFF CACHE BOOL "" FORCE)
|
||||
set(SDL_TESTS OFF CACHE BOOL "" FORCE)
|
||||
set(SDL_EXAMPLES OFF CACHE BOOL "" FORCE)
|
||||
set(SDL_INSTALL OFF CACHE BOOL "" FORCE)
|
||||
set(SDL_AUDIO OFF CACHE BOOL "" FORCE)
|
||||
set(SDL_CAMERA OFF CACHE BOOL "" FORCE)
|
||||
set(SDL_GPU OFF CACHE BOOL "" FORCE)
|
||||
set(SDL_RENDER OFF CACHE BOOL "" FORCE)
|
||||
set(SDL_VULKAN OFF CACHE BOOL "" FORCE)
|
||||
FetchContent_Declare(SDL3
|
||||
URL https://github.com/libsdl-org/SDL/releases/download/release-3.4.20/SDL3-3.4.20.tar.gz
|
||||
URL_HASH SHA256=f3bb06f55bed9557227a700af2ea62e49497ebdf58037732a731a5fb3ef8581f
|
||||
DOWNLOAD_EXTRACT_TIMESTAMP ON)
|
||||
FetchContent_MakeAvailable(SDL3)
|
||||
FetchContent_Declare(imgui
|
||||
URL https://github.com/ocornut/imgui/archive/b1bcb12a624af7509894c8e77dd47416997777fa.tar.gz
|
||||
URL_HASH SHA256=123926eb22d4990dea06bec0739d92f7790c8ee505b3d903fe2de7e5940f2c27
|
||||
DOWNLOAD_EXTRACT_TIMESTAMP ON)
|
||||
FetchContent_MakeAvailable(imgui) # no CMakeLists.txt of its own: only fetched
|
||||
|
||||
add_library(launcher_imgui STATIC
|
||||
"${imgui_SOURCE_DIR}/imgui.cpp" "${imgui_SOURCE_DIR}/imgui_draw.cpp"
|
||||
"${imgui_SOURCE_DIR}/imgui_tables.cpp" "${imgui_SOURCE_DIR}/imgui_widgets.cpp"
|
||||
"${rlimgui_SOURCE_DIR}/rlImGui.cpp")
|
||||
target_include_directories(launcher_imgui PUBLIC "${imgui_SOURCE_DIR}" "${rlimgui_SOURCE_DIR}")
|
||||
# No Font Awesome merged into the fonts, no demo window.
|
||||
target_compile_definitions(launcher_imgui PUBLIC NO_FONT_AWESOME IMGUI_DISABLE_DEMO_WINDOWS IMGUI_DISABLE_DEBUG_TOOLS)
|
||||
target_link_libraries(launcher_imgui PUBLIC raylib)
|
||||
"${imgui_SOURCE_DIR}/backends/imgui_impl_sdl3.cpp" "${imgui_SOURCE_DIR}/backends/imgui_impl_opengl3.cpp")
|
||||
target_include_directories(launcher_imgui PUBLIC "${imgui_SOURCE_DIR}" "${imgui_SOURCE_DIR}/backends")
|
||||
# No demo window, no debug tools.
|
||||
target_compile_definitions(launcher_imgui PUBLIC IMGUI_DISABLE_DEMO_WINDOWS IMGUI_DISABLE_DEBUG_TOOLS
|
||||
IMGUI_DISABLE_OBSOLETE_FUNCTIONS)
|
||||
target_link_libraries(launcher_imgui PUBLIC SDL3::SDL3-static)
|
||||
target_compile_options(launcher_imgui PRIVATE -w)
|
||||
|
||||
# The type: Exo 2 (SIL Open Font License 1.1) from google/fonts at a pinned commit, embedded as a resource with its
|
||||
# licence. Downloaded at configure time (never committed) unless LAUNCHER_FONT_DIR has the two files.
|
||||
@@ -88,17 +106,20 @@ 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}")
|
||||
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
|
||||
src/main.cpp src/ui.cpp src/build_model.cpp src/config.cpp src/platform_win.cpp
|
||||
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_link_libraries(tmb_launcher PRIVATE launcher_imgui raylib comdlg32 shell32 ole32 winhttp)
|
||||
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.
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
|
||||
<assemblyIdentity type="win32" name="TheBozos.TMBLauncher" version="1.0.0.0" processorArchitecture="amd64"/>
|
||||
<application xmlns="urn:schemas-microsoft-com:asm.v3">
|
||||
<windowsSettings>
|
||||
<activeCodePage xmlns="http://schemas.microsoft.com/SMI/2019/WindowsSettings">UTF-8</activeCodePage>
|
||||
<longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware>
|
||||
</windowsSettings>
|
||||
</application>
|
||||
</assembly>
|
||||
@@ -3,6 +3,7 @@
|
||||
#include <winver.h>
|
||||
|
||||
GLFW_ICON ICON "@LAUNCHER_ICON@"
|
||||
1 24 "@LAUNCHER_MANIFEST@"
|
||||
EXO2 RCDATA "@LAUNCHER_EXO2@"
|
||||
OFL RCDATA "@LAUNCHER_OFL@"
|
||||
|
||||
|
||||
@@ -6,16 +6,16 @@
|
||||
|
||||
namespace
|
||||
{
|
||||
// tools/tmb_build.py's STEPS, with their usual seconds on a player's build with the kit (8 cores, SSD): the
|
||||
// compile is most of it.
|
||||
// tools/tmb_build.py's STEPS (the build on BozoEngine), with their usual seconds on a player's build with the kit
|
||||
// (16 threads, SSD; a first build): SDL3's configure checks and the compile are most of it.
|
||||
struct StepInfo
|
||||
{
|
||||
const char *id;
|
||||
double weight;
|
||||
};
|
||||
const StepInfo kSteps[] = {
|
||||
{"verify", 1}, {"extract", 12}, {"tools", 1}, {"recompile", 4}, {"packs", 24},
|
||||
{"iop", 3}, {"configure", 7}, {"compile", 150}, {"stage", 2},
|
||||
{"verify", 1}, {"extract", 2}, {"configure", 60}, {"tools", 7},
|
||||
{"recompile", 2}, {"packs", 32}, {"compile", 55}, {"stage", 1},
|
||||
};
|
||||
|
||||
int indexOf(const std::vector<BuildStep> &steps, const std::string &id)
|
||||
|
||||
+61
-69
@@ -1,13 +1,14 @@
|
||||
// TMB Launcher: what a player double-clicks. Their disc image is checked, the game is built from it on their PC
|
||||
// (tools/tmb_build.py run by the build kit's Python, in the background), then started. The look is the team's:
|
||||
// RecompWatcher's PS2 BIOS blue, boot towers and glass (ui.cpp).
|
||||
// RecompWatcher's PS2 BIOS blue, boot towers and glass (ui.cpp), drawn with Dear ImGui in an SDL3 window (ImGui's own
|
||||
// SDL3 and OpenGL 3 backends; window.h).
|
||||
//
|
||||
// The release folder it expects (its own folder, or --release <dir>):
|
||||
// TMB Launcher.exe
|
||||
// source\ the TMB_Recomp code (tools\tmb_build.py, PS2Recomp...)
|
||||
// source\ the TMB_Recomp code (tools\tmb_build.py, BozoEngine\...)
|
||||
// kit\ the build kit (kit\python\python.exe, the compiler...)
|
||||
// build\ tmb_build's work folder (made here)
|
||||
// game\ the game folder the build stages (made here): ps2EntryRunner.exe, disc\, disc.iso, the packs
|
||||
// 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.
|
||||
//
|
||||
@@ -18,10 +19,8 @@
|
||||
#include "platform.h"
|
||||
#include "ui.h"
|
||||
|
||||
#include "raylib.h"
|
||||
#include "rlgl.h"
|
||||
#include "window.h"
|
||||
#include "imgui.h"
|
||||
#include "rlImGui.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
@@ -57,9 +56,11 @@ static const char *kCommit = TMB_COMMIT;
|
||||
// The update check: GitHub's latest release of the main repository (drafts and pre-releases are never "latest").
|
||||
static const char *kLatestReleaseApi = "https://api.github.com/repos/TheBozos/TMB_Recomp/releases/latest";
|
||||
static const char *kReleasePagePrefix = "https://github.com/TheBozos/TMB_Recomp/releases/tag/";
|
||||
// A release's files (the Update button): <prefix><tag>/TMB_Recomp-<version>.zip and its .sha256, the address made
|
||||
// here from the tag like the page's, never one read from the API's response.
|
||||
// A release's files (the Update button): <prefix><tag>/TMB_Recomp-<version>-bozo.zip and its .sha256 (the build on
|
||||
// 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/";
|
||||
static std::string releaseZipName(const std::string &version) { return "TMB_Recomp-" + version + "-bozo.zip"; }
|
||||
|
||||
// ---- language ----
|
||||
|
||||
@@ -71,15 +72,13 @@ static const char *stepTitle(const std::string &id)
|
||||
if (id == "verify")
|
||||
return L("Checking the disc", "Vérification du disque");
|
||||
if (id == "extract")
|
||||
return L("Copying the disc's files", "Copie des fichiers du disque");
|
||||
return L("Reading the disc's files", "Lecture des fichiers du disque");
|
||||
if (id == "tools")
|
||||
return L("Preparing the recompiler", "Préparation du recompilateur");
|
||||
if (id == "recompile")
|
||||
return L("Recompiling the game's code", "Recompilation du code du jeu");
|
||||
if (id == "packs")
|
||||
return L("Converting textures and models", "Conversion des textures et modèles");
|
||||
if (id == "iop")
|
||||
return L("Recompiling sound and controllers", "Recompilation du son et des manettes");
|
||||
if (id == "configure")
|
||||
return L("Configuring the build", "Configuration de la compilation");
|
||||
if (id == "compile")
|
||||
@@ -341,7 +340,7 @@ enum class Phase
|
||||
|
||||
struct Paths
|
||||
{
|
||||
std::string release, source, kit, python, script, buildOut, buildLogs, game, gameExe, elf;
|
||||
std::string release, source, kit, python, script, buildOut, buildLogs, game, gameExe, elf, iso;
|
||||
std::string releaseIni, builtFrom; // the source's release stamp, and the one of the code the game was built from
|
||||
std::string user, launcherIni, videoIni, logs, crashes;
|
||||
};
|
||||
@@ -432,8 +431,9 @@ struct App
|
||||
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"ps2EntryRunner.exe");
|
||||
p.elf = plat::str(r / L"game" / L"disc" / L"SCUS_971.01");
|
||||
p.gameExe = plat::str(r / L"game" / L"tmb.exe");
|
||||
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");
|
||||
p.builtFrom = plat::str(r / L"game" / L"built_from.ini");
|
||||
p.user = plat::userDirectory();
|
||||
@@ -512,7 +512,7 @@ struct App
|
||||
updateStep = UpdateStep::Downloading;
|
||||
if (downloader.joinable())
|
||||
downloader.join();
|
||||
const std::string name = "TMB_Recomp-" + version + ".zip";
|
||||
const std::string name = releaseZipName(version);
|
||||
const std::string url = downloadPrefix + tag + "/" + name;
|
||||
const std::string zip = plat::str(plat::path(updateDir()) / plat::path(name));
|
||||
downloader = std::thread([this, url, zip]
|
||||
@@ -554,7 +554,7 @@ struct App
|
||||
updateError = std::string(L("The download failed: ", "Le téléchargement a échoué : ")) + error + ".";
|
||||
return;
|
||||
}
|
||||
const std::string zip = plat::str(plat::path(updateDir()) / plat::path("TMB_Recomp-" + updateVersion + ".zip"));
|
||||
const std::string zip = plat::str(plat::path(updateDir()) / plat::path(releaseZipName(updateVersion)));
|
||||
const std::vector<std::string> args = {"-I", "-X", "utf8", plat::str(plat::path(p.source) / L"tools" / L"apply_update.py"),
|
||||
"--zip", zip, "--sha256", zip + ".sha256", "--version", updateVersion,
|
||||
"--install", p.release};
|
||||
@@ -648,7 +648,7 @@ struct App
|
||||
|
||||
void pickDisc()
|
||||
{
|
||||
const std::string file = plat::pickDiscImage(GetWindowHandle(), L("Select your Twisted Metal: Black disc image",
|
||||
const std::string file = plat::pickDiscImage(win::nativeHandle(), L("Select your Twisted Metal: Black disc image",
|
||||
"Choisir l'image disque de Twisted Metal: Black"),
|
||||
L("Disc images", "Images disque"), L("All files", "Tous les fichiers"));
|
||||
if (!file.empty())
|
||||
@@ -853,14 +853,14 @@ struct App
|
||||
launchError.clear();
|
||||
notice.clear();
|
||||
std::string error;
|
||||
// Nothing to set: the runner's defaults are the native port, and it finds the packs and disc.iso beside it.
|
||||
if (!game.start(p.gameExe, {p.elf}, p.game, false, error))
|
||||
// The game on BozoEngine: its ELF and disc image beside it (the packs too, found beside the ELF).
|
||||
if (!game.start(p.gameExe, {"--elf", p.elf, "--iso", p.iso}, p.game, false, error))
|
||||
{
|
||||
launchError = error;
|
||||
return;
|
||||
}
|
||||
gameRunning = true;
|
||||
SetWindowState(FLAG_WINDOW_HIDDEN);
|
||||
win::hide();
|
||||
hidden = true;
|
||||
}
|
||||
|
||||
@@ -878,9 +878,8 @@ struct App
|
||||
crashReport = f.first;
|
||||
}
|
||||
gameProblem = crashReport.empty() && gameExit != 0;
|
||||
ClearWindowState(FLAG_WINDOW_HIDDEN);
|
||||
win::show();
|
||||
hidden = false;
|
||||
SetWindowFocused();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1147,7 +1146,7 @@ static void drawReady(App &app, float inner)
|
||||
"et environ 10 Go d'espace libre."),
|
||||
19, ui::color::ink, 0.92f);
|
||||
const double freeGb = plat::freeBytes(app.p.release) / 1073741824.0;
|
||||
if (freeGb > 0 && freeGb < 10)
|
||||
if (freeGb > 0 && freeGb < 5)
|
||||
{
|
||||
char buf[160];
|
||||
std::snprintf(buf, sizeof(buf), L("Only %.1f GB free on this drive.", "Seulement %.1f Go libres sur ce disque."), freeGb);
|
||||
@@ -1303,8 +1302,7 @@ static void drawSettings(App &app, float inner)
|
||||
}
|
||||
gap(6);
|
||||
ui::text(L("Resolution", "Résolution"), 17, ui::color::inkFaint);
|
||||
const int monitor = GetCurrentMonitor();
|
||||
const auto sizes = offeredResolutions(GetMonitorWidth(monitor), GetMonitorHeight(monitor));
|
||||
const auto sizes = offeredResolutions(win::monitorWidth(), win::monitorHeight());
|
||||
auto label = [&](int w, int h)
|
||||
{
|
||||
char buf[96];
|
||||
@@ -1457,7 +1455,7 @@ static void drawIncomplete(App &app)
|
||||
|
||||
static void drawFrame(App &app)
|
||||
{
|
||||
const float W = static_cast<float>(GetScreenWidth()), H = static_cast<float>(GetScreenHeight());
|
||||
const float W = static_cast<float>(win::width()), H = static_cast<float>(win::height());
|
||||
ImGui::SetNextWindowPos(ImVec2(0, 0));
|
||||
ImGui::SetNextWindowSize(ImVec2(W, H));
|
||||
ImGui::Begin("##root", nullptr,
|
||||
@@ -1617,6 +1615,7 @@ struct Selftest
|
||||
{
|
||||
std::string iso, shots, wrong;
|
||||
bool errorDemo = false, cancel = false, screensOnly = false;
|
||||
bool failed = false;
|
||||
double playSeconds = 40, crashSeconds = 0;
|
||||
std::FILE *log = nullptr;
|
||||
|
||||
@@ -1806,6 +1805,12 @@ struct Selftest
|
||||
say("build ended after %s s: %s", std::to_string(plat::now() - buildStart),
|
||||
app.phase == Phase::Ready ? "ready" : "failed: " + app.model.errorMessage);
|
||||
say("notice: %s (launcher.ini last_build_seconds %s)", app.notice, std::to_string(app.cfg.lastBuildSeconds));
|
||||
if (!errorDemo && (app.phase != Phase::Ready || !app.built()))
|
||||
{
|
||||
say("FAIL build did not produce a playable game");
|
||||
failed = true;
|
||||
app.quit = true;
|
||||
}
|
||||
return true;
|
||||
}});
|
||||
steps.push_back(shot("09-built", 1.0));
|
||||
@@ -1836,6 +1841,12 @@ struct Selftest
|
||||
captureInto("play");
|
||||
app.play();
|
||||
say("game started (pid %s)", std::to_string(app.game.pid()));
|
||||
if (!errorDemo && !app.gameRunning)
|
||||
{
|
||||
say("FAIL game did not start");
|
||||
failed = true;
|
||||
app.quit = true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (app.gameRunning && t >= playSeconds && t < playSeconds + 0.1)
|
||||
@@ -1850,6 +1861,8 @@ struct Selftest
|
||||
if (app.gameRunning)
|
||||
return false;
|
||||
say("game exited, code %s, crash report: %s", std::to_string(app.gameExit), app.crashReport.empty() ? "none" : app.crashReport);
|
||||
if (!errorDemo && app.gameExit != 0)
|
||||
failed = true;
|
||||
return true;
|
||||
}});
|
||||
steps.push_back(shot("15-after-play", 1.5));
|
||||
@@ -1866,6 +1879,12 @@ struct Selftest
|
||||
plat::setEnv("PS2X_TEST_CRASH", "");
|
||||
plat::setEnv("PS2X_NO_DIALOGS", "");
|
||||
say("game started to crash (pid %s)", std::to_string(app.game.pid()));
|
||||
if (!errorDemo && !app.gameRunning)
|
||||
{
|
||||
failed = true;
|
||||
app.quit = true;
|
||||
say("FAIL crash-test game did not start");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (app.gameRunning && t > crashSeconds + 90)
|
||||
@@ -1873,6 +1892,8 @@ struct Selftest
|
||||
if (app.gameRunning)
|
||||
return false;
|
||||
say("game exited, code %s, crash report: %s", std::to_string(app.gameExit), app.crashReport.empty() ? "none" : app.crashReport);
|
||||
if (!errorDemo && (app.gameExit == 0 || app.crashReport.empty()))
|
||||
failed = true;
|
||||
return true;
|
||||
}});
|
||||
steps.push_back(shot("16-crash", 1.5));
|
||||
@@ -2033,7 +2054,7 @@ int main(int argc, char **argv)
|
||||
uiScale = static_cast<float>(std::atof(next().c_str()));
|
||||
else if (a == "--update-url") // a test: another address answering as GitHub's latest-release API
|
||||
updateUrl = next();
|
||||
else if (a == "--download-prefix") // a test: another address serving <tag>/TMB_Recomp-<version>.zip
|
||||
else if (a == "--download-prefix") // a test: another address serving <tag>/TMB_Recomp-<version>-bozo.zip
|
||||
downloadPrefix = next();
|
||||
else if (a == "--update-now") // a test: presses Update once the check finds a newer release
|
||||
updateNow = true;
|
||||
@@ -2052,32 +2073,15 @@ int main(int argc, char **argv)
|
||||
App app;
|
||||
app.init(release);
|
||||
|
||||
SetConfigFlags(FLAG_WINDOW_RESIZABLE | FLAG_MSAA_4X_HINT | FLAG_VSYNC_HINT);
|
||||
SetTraceLogLevel(LOG_WARNING);
|
||||
InitWindow(1120, 760, "TMB Launcher");
|
||||
std::string error;
|
||||
if (!win::open("TMB Launcher", 1120, 760, uiScale, error))
|
||||
{
|
||||
const Vector2 dpi = GetWindowScaleDPI();
|
||||
ui::scale = std::clamp(uiScale > 0 ? uiScale : dpi.x, 1.0f, 3.0f);
|
||||
if (ui::scale > 1.0f)
|
||||
{
|
||||
// The layout is made for 1120 x 760 at 1x: at Windows' 150 % on a 1920 x 1080 screen (1680 x 1140) it would
|
||||
// not fit, so the scale is lowered until the window does (1.32 there; text still half as large again).
|
||||
const int m = GetCurrentMonitor();
|
||||
const float fit = std::min((GetMonitorWidth(m) - 40) / 1120.0f, (GetMonitorHeight(m) - 80) / 760.0f);
|
||||
if (fit > 0.5f)
|
||||
ui::scale = std::max(1.0f, std::min(ui::scale, fit));
|
||||
const int w = static_cast<int>(1120 * ui::scale), h = static_cast<int>(760 * ui::scale);
|
||||
SetWindowSize(std::min(w, GetMonitorWidth(m) - 40), std::min(h, GetMonitorHeight(m) - 80));
|
||||
SetWindowPosition((GetMonitorWidth(m) - GetScreenWidth()) / 2, (GetMonitorHeight(m) - GetScreenHeight()) / 2);
|
||||
}
|
||||
plat::messageBox("TMB Launcher", error);
|
||||
return 1;
|
||||
}
|
||||
SetWindowMinSize(static_cast<int>(980 * ui::scale), static_cast<int>(700 * ui::scale));
|
||||
SetExitKey(KEY_NULL);
|
||||
SetTargetFPS(60);
|
||||
rlImGuiBeginInitImGui();
|
||||
win::setMinimumSize(static_cast<int>(980 * ui::scale), static_cast<int>(700 * ui::scale));
|
||||
ImGui::StyleColorsDark();
|
||||
ui::setup();
|
||||
rlImGuiEndInitImGui();
|
||||
|
||||
// The update check at start (setting "update_check"): not for a development launcher, unless pointed somewhere.
|
||||
if (!updateUrl.empty())
|
||||
@@ -2110,7 +2114,7 @@ int main(int argc, char **argv)
|
||||
const double t0 = plat::now();
|
||||
while (!app.quit)
|
||||
{
|
||||
if (WindowShouldClose())
|
||||
if (win::pollEvents()) // the window's close button (or Alt+F4)
|
||||
{
|
||||
if (app.building)
|
||||
app.wantQuit = true;
|
||||
@@ -2135,31 +2139,19 @@ int main(int argc, char **argv)
|
||||
test.tick(app);
|
||||
if (app.hidden)
|
||||
{
|
||||
PollInputEvents();
|
||||
WaitTime(0.1);
|
||||
win::idle(0.1);
|
||||
continue;
|
||||
}
|
||||
BeginDrawing();
|
||||
ClearBackground(Color{1, 3, 10, 255});
|
||||
win::beginFrame();
|
||||
ui::drawBackground(app.time, app.cfg.motion);
|
||||
rlImGuiBegin();
|
||||
drawFrame(app);
|
||||
rlImGuiEnd();
|
||||
if (!app.pendingShot.empty())
|
||||
{
|
||||
rlDrawRenderBatchActive();
|
||||
Image img = LoadImageFromScreen();
|
||||
ExportImage(img, app.pendingShot.c_str());
|
||||
UnloadImage(img);
|
||||
app.pendingShot.clear();
|
||||
}
|
||||
EndDrawing();
|
||||
win::endFrame(app.pendingShot); // the selftest's screenshot of this frame, when asked
|
||||
app.pendingShot.clear();
|
||||
}
|
||||
app.cancelBuild();
|
||||
rlImGuiShutdown();
|
||||
ui::releaseBackground();
|
||||
CloseWindow();
|
||||
win::close();
|
||||
if (test.log)
|
||||
std::fclose(test.log);
|
||||
return 0;
|
||||
const bool incomplete = !selftestIso.empty() && test.index < test.steps.size();
|
||||
return test.failed || incomplete ? 1 : 0;
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
// The launcher's operating-system layer (platform_win.cpp): everything that needs <windows.h>, kept out of the
|
||||
// raylib / ImGui translation units (their names clash: CloseWindow, DrawText, Rectangle...). Strings are UTF-8.
|
||||
// ImGui and SDL translation units. Strings are UTF-8.
|
||||
|
||||
#include <atomic>
|
||||
#include <cstddef>
|
||||
@@ -91,4 +91,7 @@ namespace plat
|
||||
|
||||
// This program's own file (the launcher's exe, to start it again after an update).
|
||||
std::string exePath();
|
||||
|
||||
// A message box (the window could not open).
|
||||
void messageBox(const std::string &title, const std::string &text);
|
||||
}
|
||||
@@ -610,4 +610,9 @@ namespace plat
|
||||
buffer.resize(buffer.size() * 2);
|
||||
}
|
||||
}
|
||||
|
||||
void messageBox(const std::string &title, const std::string &text)
|
||||
{
|
||||
MessageBoxW(nullptr, widen(text).c_str(), widen(title).c_str(), MB_OK | MB_ICONERROR);
|
||||
}
|
||||
}
|
||||
+49
-48
@@ -1,7 +1,7 @@
|
||||
#include "ui.h"
|
||||
#include "platform.h"
|
||||
#include "window.h"
|
||||
|
||||
#include "raylib.h"
|
||||
#include "imgui_internal.h"
|
||||
|
||||
#include <algorithm>
|
||||
@@ -114,57 +114,60 @@ namespace ui
|
||||
|
||||
namespace
|
||||
{
|
||||
Texture2D g_gradient{};
|
||||
bool g_hasGradient = false;
|
||||
|
||||
float smoothstep(float a, float b, float x)
|
||||
{
|
||||
const float t = std::clamp((x - a) / (b - a), 0.0f, 1.0f);
|
||||
return t * t * (3 - 2 * t);
|
||||
}
|
||||
|
||||
void makeGradient()
|
||||
// icon.svg's radialGradient (#14328f at the bottom centre, 0.55 #050b26, 1 #01030a) stretched to the window,
|
||||
// with global.css's vignette baked in: the colour at (u, v) in 0..1.
|
||||
ImU32 gradientAt(float u, float v)
|
||||
{
|
||||
// icon.svg's radialGradient (#14328f at the bottom centre, 0.55 #050b26, 1 #01030a) stretched to the
|
||||
// window, with global.css's vignette baked in.
|
||||
const int w = 384, h = 240;
|
||||
Image img = GenImageColor(w, h, BLACK);
|
||||
auto *px = static_cast<Color *>(img.data);
|
||||
auto lerp = [](float a, float b, float t) { return a + (b - a) * t; };
|
||||
const float s0[3] = {0x14, 0x32, 0x8f}, s1[3] = {0x05, 0x0b, 0x26}, s2[3] = {0x01, 0x03, 0x0a};
|
||||
for (int y = 0; y < h; ++y)
|
||||
for (int x = 0; x < w; ++x)
|
||||
{
|
||||
const float u = (x + 0.5f) / w, v = (y + 0.5f) / h;
|
||||
const float d = std::sqrt(((u - 0.5f) / 0.62f) * ((u - 0.5f) / 0.62f) + ((v - 1.02f) / 1.05f) * ((v - 1.02f) / 1.05f));
|
||||
float rgb[3];
|
||||
for (int k = 0; k < 3; ++k)
|
||||
rgb[k] = d < 0.55f ? lerp(s0[k], s1[k], d / 0.55f) : lerp(s1[k], s2[k], std::min(1.0f, (d - 0.55f) / 0.45f));
|
||||
const float e = std::sqrt((u - 0.5f) * (u - 0.5f) * 4 + (v - 0.5f) * (v - 0.5f) * 4) / 1.414f;
|
||||
const float vignette = 1.0f - 0.65f * smoothstep(0.45f, 1.0f, e);
|
||||
px[y * w + x] = Color{static_cast<unsigned char>(rgb[0] * vignette), static_cast<unsigned char>(rgb[1] * vignette),
|
||||
static_cast<unsigned char>(rgb[2] * vignette), 255};
|
||||
}
|
||||
g_gradient = LoadTextureFromImage(img);
|
||||
SetTextureFilter(g_gradient, TEXTURE_FILTER_BILINEAR);
|
||||
UnloadImage(img);
|
||||
g_hasGradient = true;
|
||||
const float d = std::sqrt(((u - 0.5f) / 0.62f) * ((u - 0.5f) / 0.62f) + ((v - 1.02f) / 1.05f) * ((v - 1.02f) / 1.05f));
|
||||
float rgb[3];
|
||||
for (int k = 0; k < 3; ++k)
|
||||
rgb[k] = d < 0.55f ? lerp(s0[k], s1[k], d / 0.55f) : lerp(s1[k], s2[k], std::min(1.0f, (d - 0.55f) / 0.45f));
|
||||
const float e = std::sqrt((u - 0.5f) * (u - 0.5f) * 4 + (v - 0.5f) * (v - 0.5f) * 4) / 1.414f;
|
||||
const float vignette = 1.0f - 0.65f * smoothstep(0.45f, 1.0f, e);
|
||||
return IM_COL32(static_cast<int>(rgb[0] * vignette), static_cast<int>(rgb[1] * vignette),
|
||||
static_cast<int>(rgb[2] * vignette), 255);
|
||||
}
|
||||
|
||||
Color col(unsigned rgb, float alpha)
|
||||
// The gradient as a mesh of coloured quads (the GPU interpolates between the vertices: no texture), 48 x 30
|
||||
// cells as raylib's 384 x 240 texture was bilinearly stretched.
|
||||
void drawGradient(ImDrawList *dl, float W, float H)
|
||||
{
|
||||
return Color{static_cast<unsigned char>((rgb >> 16) & 255), static_cast<unsigned char>((rgb >> 8) & 255),
|
||||
static_cast<unsigned char>(rgb & 255), static_cast<unsigned char>(std::clamp(alpha, 0.0f, 1.0f) * 255)};
|
||||
constexpr int cols = 48, rows = 30;
|
||||
static std::vector<ImU32> colours;
|
||||
if (colours.empty())
|
||||
for (int y = 0; y <= rows; ++y)
|
||||
for (int x = 0; x <= cols; ++x)
|
||||
colours.push_back(gradientAt(static_cast<float>(x) / cols, static_cast<float>(y) / rows));
|
||||
const ImVec2 uv = ImGui::GetFontTexUvWhitePixel();
|
||||
dl->PrimReserve(cols * rows * 6, (cols + 1) * (rows + 1));
|
||||
const ImDrawIdx base = static_cast<ImDrawIdx>(dl->_VtxCurrentIdx);
|
||||
for (int y = 0; y <= rows; ++y)
|
||||
for (int x = 0; x <= cols; ++x)
|
||||
dl->PrimWriteVtx(ImVec2(W * x / cols, H * y / rows), uv, colours[static_cast<size_t>(y * (cols + 1) + x)]);
|
||||
for (int y = 0; y < rows; ++y)
|
||||
for (int x = 0; x < cols; ++x)
|
||||
{
|
||||
const ImDrawIdx a = static_cast<ImDrawIdx>(base + y * (cols + 1) + x), b = static_cast<ImDrawIdx>(a + 1),
|
||||
c = static_cast<ImDrawIdx>(a + cols + 1), d = static_cast<ImDrawIdx>(c + 1);
|
||||
dl->PrimWriteIdx(a), dl->PrimWriteIdx(b), dl->PrimWriteIdx(d);
|
||||
dl->PrimWriteIdx(a), dl->PrimWriteIdx(d), dl->PrimWriteIdx(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void drawBackground(double time, bool motion)
|
||||
{
|
||||
if (!g_hasGradient)
|
||||
makeGradient();
|
||||
const float W = static_cast<float>(GetScreenWidth()), H = static_cast<float>(GetScreenHeight());
|
||||
DrawTexturePro(g_gradient, Rectangle{0, 0, static_cast<float>(g_gradient.width), static_cast<float>(g_gradient.height)},
|
||||
Rectangle{0, 0, W, H}, Vector2{0, 0}, 0, WHITE);
|
||||
ImDrawList *dl = ImGui::GetBackgroundDrawList();
|
||||
const float W = static_cast<float>(win::width()), H = static_cast<float>(win::height());
|
||||
drawGradient(dl, W, H);
|
||||
|
||||
// The boot towers: faint glowing columns rising from the bottom, as on the PS2's boot screen.
|
||||
const double t = motion ? time : 0.0;
|
||||
@@ -183,25 +186,23 @@ namespace ui
|
||||
for (int g = 3; g >= 1; --g)
|
||||
{
|
||||
const float pad = S(5.0f * g * g * 0.7f);
|
||||
DrawRectangleRounded(Rectangle{x - w / 2 - pad, top - pad, w + 2 * pad, hgt + pad}, 0.3f, 6,
|
||||
col(0x4f74ff, 0.03f * breathe / g));
|
||||
const ImVec2 a(x - w / 2 - pad, top - pad), b(x + w / 2 + pad, top + hgt);
|
||||
// raylib's DrawRectangleRounded roundness 0.3: 30 % of the shorter side's half.
|
||||
dl->AddRectFilled(a, b, rgba(0x4f74ff, 0.03f * breathe / g), 0.3f * 0.5f * std::min(b.x - a.x, b.y - a.y));
|
||||
}
|
||||
DrawRectangleGradientV(static_cast<int>(x - w / 2), static_cast<int>(top), static_cast<int>(w), static_cast<int>(hgt),
|
||||
col(0x6f8dff, 0.26f * breathe), col(0x14328f, 0.06f * breathe));
|
||||
DrawRectangle(static_cast<int>(x - w / 2), static_cast<int>(top), static_cast<int>(w), static_cast<int>(S(2)),
|
||||
col(0xc9dbff, 0.35f * breathe));
|
||||
const float left = std::floor(x - w / 2), right = left + std::floor(w);
|
||||
dl->AddRectFilledMultiColor(ImVec2(left, std::floor(top)), ImVec2(right, std::floor(top) + std::floor(hgt)),
|
||||
rgba(0x6f8dff, 0.26f * breathe), rgba(0x6f8dff, 0.26f * breathe),
|
||||
rgba(0x14328f, 0.06f * breathe), rgba(0x14328f, 0.06f * breathe));
|
||||
dl->AddRectFilled(ImVec2(left, std::floor(top)), ImVec2(right, std::floor(top) + std::floor(S(2))),
|
||||
rgba(0xc9dbff, 0.35f * breathe));
|
||||
}
|
||||
// Scanlines (global.css's .vignette: 1 px of white at 1.8 % every 3 px).
|
||||
for (int y = 0; y < static_cast<int>(H); y += 3)
|
||||
DrawRectangle(0, y, static_cast<int>(W), 1, Color{255, 255, 255, 5});
|
||||
dl->AddRectFilled(ImVec2(0, static_cast<float>(y)), ImVec2(W, static_cast<float>(y + 1)), IM_COL32(255, 255, 255, 5));
|
||||
}
|
||||
|
||||
void releaseBackground()
|
||||
{
|
||||
if (g_hasGradient)
|
||||
UnloadTexture(g_gradient);
|
||||
g_hasGradient = false;
|
||||
}
|
||||
void releaseBackground() {}
|
||||
|
||||
// ---- text ----
|
||||
|
||||
|
||||
+5
-5
@@ -1,7 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
// The launcher's look: RecompWatcher's identity (its src/styles/global.css tokens and public/icon.svg) on raylib and
|
||||
// Dear ImGui. The PS2 BIOS's radial blue behind faint glowing "boot towers", glass cards, Exo 2.
|
||||
// The launcher's look: RecompWatcher's identity (its src/styles/global.css tokens and public/icon.svg) on Dear
|
||||
// ImGui, in an SDL3 window (window.h). The PS2 BIOS's radial blue behind faint glowing "boot towers", glass cards, Exo 2.
|
||||
|
||||
#include "imgui.h"
|
||||
|
||||
@@ -28,11 +28,11 @@ namespace ui
|
||||
ImFont *mono = nullptr; // Cascadia Mono or Consolas (logs), else Exo 2
|
||||
};
|
||||
extern Fonts fonts;
|
||||
// After rlImGuiBeginInitImGui: Exo 2 from the exe's resources, the monospace font from Windows, the style.
|
||||
// After win::open: Exo 2 from the exe's resources, the monospace font from Windows, the style.
|
||||
void setup();
|
||||
|
||||
// The background, drawn with raylib before ImGui: the radial gradient, the boot towers (animated unless
|
||||
// motion is off), a vignette and faint scanlines.
|
||||
// The background, on ImGui's background draw list (after win::beginFrame): the radial gradient, the boot towers
|
||||
// (animated unless motion is off), a vignette and faint scanlines.
|
||||
void drawBackground(double time, bool motion);
|
||||
void releaseBackground();
|
||||
|
||||
|
||||
@@ -0,0 +1,276 @@
|
||||
// The launcher's window (window.h): SDL3, an OpenGL 3.3 core context, Dear ImGui's SDL3 and OpenGL 3 backends.
|
||||
// The few GL calls of its own (clear, viewport, the screenshot's read-back) are loaded through SDL, so nothing links
|
||||
// opengl32 directly; the screenshot is written by BozoEngine's dependency-free PNG writer (bozo/app/png.h).
|
||||
|
||||
#include "window.h"
|
||||
#include "platform.h"
|
||||
#include "ui.h"
|
||||
|
||||
#include "bozo/app/png.h"
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include "imgui.h"
|
||||
#include "imgui_impl_opengl3.h"
|
||||
#include "imgui_impl_sdl3.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
#ifdef _WIN32
|
||||
#define GLAPI_CALL __stdcall // opengl32's convention (the same as the default on x64)
|
||||
#else
|
||||
#define GLAPI_CALL
|
||||
#endif
|
||||
|
||||
namespace win
|
||||
{
|
||||
namespace
|
||||
{
|
||||
SDL_Window *g_window = nullptr;
|
||||
SDL_GLContext g_context = nullptr;
|
||||
bool g_vsync = false;
|
||||
uint64_t g_lastFrame = 0;
|
||||
|
||||
// GL 1.1 entry points (the types spelt out: no GL header needed).
|
||||
using GlClearColor = void(GLAPI_CALL *)(float, float, float, float);
|
||||
using GlClear = void(GLAPI_CALL *)(unsigned);
|
||||
using GlViewport = void(GLAPI_CALL *)(int, int, int, int);
|
||||
using GlReadPixels = void(GLAPI_CALL *)(int, int, int, int, unsigned, unsigned, void *);
|
||||
using GlPixelStorei = void(GLAPI_CALL *)(unsigned, int);
|
||||
using GlReadBuffer = void(GLAPI_CALL *)(unsigned);
|
||||
GlClearColor glClearColor_ = nullptr;
|
||||
GlClear glClear_ = nullptr;
|
||||
GlViewport glViewport_ = nullptr;
|
||||
GlReadPixels glReadPixels_ = nullptr;
|
||||
GlPixelStorei glPixelStorei_ = nullptr;
|
||||
GlReadBuffer glReadBuffer_ = nullptr;
|
||||
constexpr unsigned kColorBufferBit = 0x4000, kRgba = 0x1908, kUnsignedByte = 0x1401, kPackAlignment = 0x0D05,
|
||||
kBack = 0x0405;
|
||||
|
||||
template <typename T>
|
||||
T proc(const char *name)
|
||||
{
|
||||
return reinterpret_cast<T>(SDL_GL_GetProcAddress(name));
|
||||
}
|
||||
|
||||
SDL_DisplayID display()
|
||||
{
|
||||
SDL_DisplayID d = g_window ? SDL_GetDisplayForWindow(g_window) : 0;
|
||||
return d ? d : SDL_GetPrimaryDisplay();
|
||||
}
|
||||
|
||||
void screenshot(const std::string &path)
|
||||
{
|
||||
const int w = width(), h = height();
|
||||
if (w <= 0 || h <= 0 || !glReadPixels_)
|
||||
return;
|
||||
std::vector<uint8_t> pixels(static_cast<size_t>(w) * h * 4), rows(pixels.size());
|
||||
if (glReadBuffer_)
|
||||
glReadBuffer_(kBack);
|
||||
glPixelStorei_(kPackAlignment, 1);
|
||||
glReadPixels_(0, 0, w, h, kRgba, kUnsignedByte, pixels.data());
|
||||
const size_t stride = static_cast<size_t>(w) * 4;
|
||||
for (int y = 0; y < h; ++y) // GL's rows are bottom-up
|
||||
std::copy_n(pixels.data() + static_cast<size_t>(h - 1 - y) * stride, stride, rows.data() + y * stride);
|
||||
bozo::app::writePng(path, rows.data(), static_cast<uint32_t>(w), static_cast<uint32_t>(h));
|
||||
}
|
||||
}
|
||||
|
||||
bool open(const char *title, int w, int h, float uiScale, std::string &error)
|
||||
{
|
||||
// No gamepad, no sound: the launcher is driven by mouse and keyboard.
|
||||
SDL_SetHint(SDL_HINT_VIDEO_ALLOW_SCREENSAVER, "1");
|
||||
if (!SDL_Init(SDL_INIT_VIDEO))
|
||||
{
|
||||
error = std::string("SDL could not start: ") + SDL_GetError();
|
||||
return false;
|
||||
}
|
||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
|
||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
|
||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
|
||||
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
|
||||
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); // the boot towers' rounded glow, as raylib's MSAA 4x hint
|
||||
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);
|
||||
// The layout is made for w x h at 1x: at a larger display scale the window grows with it, the scale lowered
|
||||
// until the window fits (Windows' 150 % on a 1920 x 1080 screen: 1.32; text still half as large again).
|
||||
const SDL_DisplayID d = SDL_GetPrimaryDisplay();
|
||||
float scale = uiScale > 0 ? uiScale : SDL_GetDisplayContentScale(d);
|
||||
scale = std::clamp(scale > 0 ? scale : 1.0f, 1.0f, 3.0f);
|
||||
const SDL_DisplayMode *mode = SDL_GetDesktopDisplayMode(d);
|
||||
if (mode && scale > 1.0f)
|
||||
{
|
||||
const float fit = std::min((mode->w - 40) / static_cast<float>(w), (mode->h - 80) / static_cast<float>(h));
|
||||
if (fit > 0.5f)
|
||||
scale = std::max(1.0f, std::min(scale, fit));
|
||||
}
|
||||
ui::scale = scale;
|
||||
int ww = static_cast<int>(w * scale), wh = static_cast<int>(h * scale);
|
||||
if (mode)
|
||||
ww = std::min(ww, mode->w - 40), wh = std::min(wh, mode->h - 80);
|
||||
g_window = SDL_CreateWindow(title, ww, wh, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN);
|
||||
if (!g_window)
|
||||
{
|
||||
// No multisampling on this GPU / driver: without it.
|
||||
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0);
|
||||
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0);
|
||||
g_window = SDL_CreateWindow(title, ww, wh, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN);
|
||||
}
|
||||
if (!g_window)
|
||||
{
|
||||
error = std::string("the window could not be opened: ") + SDL_GetError();
|
||||
return false;
|
||||
}
|
||||
g_context = SDL_GL_CreateContext(g_window);
|
||||
if (!g_context)
|
||||
{
|
||||
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0);
|
||||
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0);
|
||||
SDL_DestroyWindow(g_window);
|
||||
g_window = SDL_CreateWindow(title, ww, wh, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN);
|
||||
g_context = g_window ? SDL_GL_CreateContext(g_window) : nullptr;
|
||||
}
|
||||
if (!g_context || !SDL_GL_MakeCurrent(g_window, g_context))
|
||||
{
|
||||
error = std::string("OpenGL 3.3 is not available (update the graphics driver): ") + SDL_GetError();
|
||||
return false;
|
||||
}
|
||||
g_vsync = SDL_GL_SetSwapInterval(1);
|
||||
glClearColor_ = proc<GlClearColor>("glClearColor");
|
||||
glClear_ = proc<GlClear>("glClear");
|
||||
glViewport_ = proc<GlViewport>("glViewport");
|
||||
glReadPixels_ = proc<GlReadPixels>("glReadPixels");
|
||||
glPixelStorei_ = proc<GlPixelStorei>("glPixelStorei");
|
||||
glReadBuffer_ = proc<GlReadBuffer>("glReadBuffer");
|
||||
SDL_SetWindowPosition(g_window, SDL_WINDOWPOS_CENTERED_DISPLAY(d), SDL_WINDOWPOS_CENTERED_DISPLAY(d));
|
||||
SDL_ShowWindow(g_window);
|
||||
|
||||
IMGUI_CHECKVERSION();
|
||||
ImGui::CreateContext();
|
||||
if (!ImGui_ImplSDL3_InitForOpenGL(g_window, g_context) || !ImGui_ImplOpenGL3_Init("#version 330"))
|
||||
{
|
||||
error = "ImGui's SDL3 / OpenGL 3 backends could not start";
|
||||
return false;
|
||||
}
|
||||
g_lastFrame = SDL_GetTicksNS();
|
||||
return true;
|
||||
}
|
||||
|
||||
void setMinimumSize(int w, int h)
|
||||
{
|
||||
if (g_window)
|
||||
SDL_SetWindowMinimumSize(g_window, w, h);
|
||||
}
|
||||
|
||||
void close()
|
||||
{
|
||||
if (ImGui::GetCurrentContext())
|
||||
{
|
||||
ImGui_ImplOpenGL3_Shutdown();
|
||||
ImGui_ImplSDL3_Shutdown();
|
||||
ImGui::DestroyContext();
|
||||
}
|
||||
if (g_context)
|
||||
SDL_GL_DestroyContext(g_context);
|
||||
if (g_window)
|
||||
SDL_DestroyWindow(g_window);
|
||||
g_context = nullptr;
|
||||
g_window = nullptr;
|
||||
SDL_Quit();
|
||||
}
|
||||
|
||||
bool pollEvents()
|
||||
{
|
||||
bool closeAsked = false;
|
||||
SDL_Event e;
|
||||
while (SDL_PollEvent(&e))
|
||||
{
|
||||
ImGui_ImplSDL3_ProcessEvent(&e);
|
||||
if (e.type == SDL_EVENT_QUIT ||
|
||||
(e.type == SDL_EVENT_WINDOW_CLOSE_REQUESTED && e.window.windowID == SDL_GetWindowID(g_window)))
|
||||
closeAsked = true;
|
||||
}
|
||||
return closeAsked;
|
||||
}
|
||||
|
||||
void idle(double seconds)
|
||||
{
|
||||
SDL_WaitEventTimeout(nullptr, static_cast<int32_t>(seconds * 1000));
|
||||
}
|
||||
|
||||
void beginFrame()
|
||||
{
|
||||
ImGui_ImplOpenGL3_NewFrame();
|
||||
ImGui_ImplSDL3_NewFrame();
|
||||
ImGui::NewFrame();
|
||||
}
|
||||
|
||||
void endFrame(const std::string &shot)
|
||||
{
|
||||
ImGui::Render();
|
||||
const int w = width(), h = height();
|
||||
glViewport_(0, 0, w, h);
|
||||
glClearColor_(1 / 255.0f, 3 / 255.0f, 10 / 255.0f, 1.0f); // global.css's --bg
|
||||
glClear_(kColorBufferBit);
|
||||
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
|
||||
if (!shot.empty())
|
||||
screenshot(shot);
|
||||
SDL_GL_SwapWindow(g_window);
|
||||
// 60 frames a second at most (as raylib's SetTargetFPS(60)): vsync on most PCs, else a wait.
|
||||
const uint64_t frameNs = 1000000000ull / 60, now = SDL_GetTicksNS();
|
||||
if (now - g_lastFrame < frameNs)
|
||||
SDL_DelayPrecise(frameNs - (now - g_lastFrame));
|
||||
g_lastFrame = SDL_GetTicksNS();
|
||||
}
|
||||
|
||||
int width()
|
||||
{
|
||||
int w = 0, h = 0;
|
||||
if (g_window)
|
||||
SDL_GetWindowSizeInPixels(g_window, &w, &h);
|
||||
return w;
|
||||
}
|
||||
|
||||
int height()
|
||||
{
|
||||
int w = 0, h = 0;
|
||||
if (g_window)
|
||||
SDL_GetWindowSizeInPixels(g_window, &w, &h);
|
||||
return h;
|
||||
}
|
||||
|
||||
int monitorWidth()
|
||||
{
|
||||
const SDL_DisplayMode *mode = SDL_GetDesktopDisplayMode(display());
|
||||
return mode ? mode->w : 1920;
|
||||
}
|
||||
|
||||
int monitorHeight()
|
||||
{
|
||||
const SDL_DisplayMode *mode = SDL_GetDesktopDisplayMode(display());
|
||||
return mode ? mode->h : 1080;
|
||||
}
|
||||
|
||||
void *nativeHandle()
|
||||
{
|
||||
if (!g_window)
|
||||
return nullptr;
|
||||
return SDL_GetPointerProperty(SDL_GetWindowProperties(g_window), SDL_PROP_WINDOW_WIN32_HWND_POINTER, nullptr);
|
||||
}
|
||||
|
||||
void hide()
|
||||
{
|
||||
if (g_window)
|
||||
SDL_HideWindow(g_window);
|
||||
}
|
||||
|
||||
void show()
|
||||
{
|
||||
if (!g_window)
|
||||
return;
|
||||
SDL_ShowWindow(g_window);
|
||||
SDL_RaiseWindow(g_window);
|
||||
g_lastFrame = SDL_GetTicksNS();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
#pragma once
|
||||
|
||||
// The launcher's window: SDL3 with an OpenGL 3.3 context, Dear ImGui through its own SDL3 and OpenGL 3 backends
|
||||
// (window.cpp). Mouse and keyboard only (no gamepad: SDL's gamepad subsystem is never started).
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace win
|
||||
{
|
||||
// Opens the window at width x height before the DPI scale, sets ui::scale (the display's content scale, or
|
||||
// uiScale when > 0; lowered until the window fits the screen) and the ImGui context with its backends.
|
||||
bool open(const char *title, int width, int height, float uiScale, std::string &error);
|
||||
void setMinimumSize(int width, int height);
|
||||
void close();
|
||||
|
||||
// The events since the last call, handed to ImGui; true when the window was asked to close.
|
||||
bool pollEvents();
|
||||
// While the window is hidden (the game runs): events only, then a pause.
|
||||
void idle(double seconds);
|
||||
|
||||
void beginFrame();
|
||||
// Draws the frame and presents it; with screenshot set, the frame is also written to that PNG first.
|
||||
void endFrame(const std::string &screenshot);
|
||||
|
||||
int width(); // the window's drawable size in pixels
|
||||
int height();
|
||||
int monitorWidth(); // the desktop mode of the display the window is on
|
||||
int monitorHeight();
|
||||
void *nativeHandle(); // the HWND (the Open dialog's owner)
|
||||
void hide();
|
||||
void show(); // shown again, raised and focused
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
{
|
||||
"comment": "The IOP modules TMB (USA, SCUS-97101) loads, in load order, at the base the runtime's IOP gives each (ps2xIOP IopModuleLoader: after the heap blocks the earlier start routines allocate). tools/tmb_build.py loads them offline at these bases (PS2Recomp/tools/irx_load.py) for tools/iop_recomp.py; a module's native code only activates at its base. hash: FNV-1a 64 of the disc's file. If the runtime's IOP allocation changes, scripts/iop_recomp.sh (the boot-and-dump path) prints the new bases.",
|
||||
"modules": [
|
||||
{
|
||||
"file": "MOD/SIO2MAN.IRX",
|
||||
"name": "SIO2MAN.IRX;1",
|
||||
"base": "0x10000",
|
||||
"size": "0xf00",
|
||||
"hash": "9000d253313b2eb6"
|
||||
},
|
||||
{
|
||||
"file": "MOD/MTAPMAN.IRX",
|
||||
"name": "MTAPMAN.IRX;1",
|
||||
"base": "0x13000",
|
||||
"size": "0x2100",
|
||||
"hash": "ce456ed631c4059f"
|
||||
},
|
||||
{
|
||||
"file": "MOD/MCMAN.IRX",
|
||||
"name": "MCMAN.IRX;1",
|
||||
"base": "0x1ab00",
|
||||
"size": "0x23a00",
|
||||
"hash": "5a6ef913b4cd3817"
|
||||
},
|
||||
{
|
||||
"file": "MOD/MCSERV.IRX",
|
||||
"name": "MCSERV.IRX;1",
|
||||
"base": "0x3e600",
|
||||
"size": "0x3600",
|
||||
"hash": "c791896027b9204d"
|
||||
},
|
||||
{
|
||||
"file": "MOD/PADMAN.IRX",
|
||||
"name": "PADMAN.IRX;1",
|
||||
"base": "0x42d00",
|
||||
"size": "0x9a00",
|
||||
"hash": "97f0888eece460ab"
|
||||
},
|
||||
{
|
||||
"file": "MOD/LIBSD.IRX",
|
||||
"name": "LIBSD.IRX;1",
|
||||
"base": "0x4d800",
|
||||
"size": "0x4900",
|
||||
"hash": "3bb566539f62cc63"
|
||||
},
|
||||
{
|
||||
"file": "MOD/989SND.IRX",
|
||||
"name": "989SND.IRX;1",
|
||||
"base": "0x52200",
|
||||
"size": "0x1c000",
|
||||
"hash": "b67e0634cd7f602c"
|
||||
},
|
||||
{
|
||||
"file": "MOD/USBD.IRX",
|
||||
"name": "USBD.IRX;1",
|
||||
"base": "0x6f300",
|
||||
"size": "0x5900",
|
||||
"hash": "0d1e13b7c104b003"
|
||||
},
|
||||
{
|
||||
"file": "MOD/LGDEV.IRX",
|
||||
"name": "LGDEV.IRX;1",
|
||||
"base": "0x74d00",
|
||||
"size": "0xa900",
|
||||
"hash": "537482c6870f2c39"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
# Hand-written recompiler settings, shared by both regions: by symbol name, so tools/tmb_manual_toml.py writes them into
|
||||
# each region's config (recomp/tmb_scus97101.toml, recomp/tmb_sces50360.toml) with that executable's addresses. The
|
||||
# rest of each config is ps2_analyzer's output (scripts/analyze.sh).
|
||||
|
||||
# Logitech steering wheel support (LGDEV.IRX). USBD.IRX and LGDEV.IRX fail to start in the IOP emulator (no USB host
|
||||
# controller), so RPC server 0x046d never appears and lgDevInit spins forever on sceSifBindRpc. Disable the whole
|
||||
# Logitech path until the IOP side exists.
|
||||
[[stub]]
|
||||
handler = "ret0"
|
||||
symbols = [
|
||||
"lgDevInit",
|
||||
"inputLgUpdate__Fv",
|
||||
"inputSetLgSpringOffset__Fii",
|
||||
"inputSetLgSpringEffect__Fiiiii",
|
||||
"inputSetLgCollisionEffect__Fiiii",
|
||||
"inputSetLgSmallActuatorEffect__Fiii",
|
||||
"inputSetLgLargeActuatorEffect__Fiiiiii",
|
||||
"inputStartLgEffect__FiPi",
|
||||
"inputSetLgTurningFriction__Fif",
|
||||
]
|
||||
|
||||
# Movie player (Sony ezmpeg sample: videoDec/viBuf/audioDec). The runtime's libmpeg HLE decodes video straight from
|
||||
# sceMpegDemuxPss* with FFmpeg. videoCallback copies the same M2V packets into the game's IPU ring (viBuf), which only
|
||||
# the IPU drains, through mpegNodata -> viBufAddDMA -> DMA ch4, a libmpeg callback the HLE never calls. The ring fills
|
||||
# and videoDecFlush spins forever at the end of the first movie (COPYRTE.PSS). The copy is useless with the HLE: accept
|
||||
# the packet and drop it.
|
||||
[[stub]]
|
||||
handler = "ret1"
|
||||
symbols = ["videoCallback__FP7sceMpegP16sceMpegCbDataStrPv"]
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,12 @@
|
||||
# Functions of TMB's executable the BozoEngine build answers as stubs beyond the libraries BozoEngine implements
|
||||
# (bozo-externals --stubs): the Logitech wheel's library, answered by runtime/tmb_overrides.cpp (returnZero), as the
|
||||
# PS2Recomp build's TOML stubs did.
|
||||
lgDevInit
|
||||
inputLgUpdate__Fv
|
||||
inputSetLgSpringOffset__Fii
|
||||
inputSetLgSpringEffect__Fiiiii
|
||||
inputSetLgCollisionEffect__Fiiii
|
||||
inputSetLgSmallActuatorEffect__Fiii
|
||||
inputSetLgLargeActuatorEffect__Fiiiiii
|
||||
inputStartLgEffect__FiPi
|
||||
inputSetLgTurningFriction__Fif
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
|
||||
<assemblyIdentity type="win32" name="TheBozos.TMB" version="1.0.0.0" processorArchitecture="amd64"/>
|
||||
<application xmlns="urn:schemas-microsoft-com:asm.v3">
|
||||
<windowsSettings>
|
||||
<activeCodePage xmlns="http://schemas.microsoft.com/SMI/2019/WindowsSettings">UTF-8</activeCodePage>
|
||||
<longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware>
|
||||
</windowsSettings>
|
||||
</application>
|
||||
</assembly>
|
||||
+2
-2
@@ -16,8 +16,8 @@ BEGIN
|
||||
BEGIN
|
||||
VALUE "FileDescription", "Twisted Metal: Black"
|
||||
VALUE "ProductName", "Twisted Metal: Black (TMB_Recomp, a native PC port)"
|
||||
VALUE "InternalName", "ps2EntryRunner"
|
||||
VALUE "OriginalFilename", "ps2EntryRunner.exe"
|
||||
VALUE "InternalName", "tmb"
|
||||
VALUE "OriginalFilename", "tmb.exe"
|
||||
VALUE "FileVersion", "1.0.0.0"
|
||||
VALUE "ProductVersion", "1.0.0.0"
|
||||
END
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
// Native Windows argv/file paths use UTF-8, including installation folders with accents.
|
||||
1 24 "tmb.manifest"
|
||||
@@ -1,33 +0,0 @@
|
||||
// Built only into a TMB_PGO=GENERATE runner (scripts/pgo.sh). The instrumented runtime writes its profile when the
|
||||
// process exits normally, which a run stopped from outside never does: TMB_PGO_SECONDS=<s> writes it after that many
|
||||
// seconds of play and exits.
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <thread>
|
||||
|
||||
extern "C" void __gcov_dump(void);
|
||||
|
||||
namespace
|
||||
{
|
||||
struct PgoTraining
|
||||
{
|
||||
PgoTraining()
|
||||
{
|
||||
const char *value = std::getenv("TMB_PGO_SECONDS");
|
||||
const double seconds = value ? std::atof(value) : 0.0;
|
||||
if (seconds <= 0.0)
|
||||
return;
|
||||
std::thread([seconds]()
|
||||
{
|
||||
std::this_thread::sleep_for(std::chrono::duration<double>(seconds));
|
||||
__gcov_dump();
|
||||
std::fprintf(stderr, "[tmb:pgo] profile written after %.0f s\n", seconds);
|
||||
std::fflush(stderr);
|
||||
std::_Exit(0); })
|
||||
.detach();
|
||||
}
|
||||
};
|
||||
|
||||
const PgoTraining g_pgoTraining;
|
||||
}
|
||||
+40
-42
@@ -9,13 +9,10 @@
|
||||
// font's packet, which fontDmaFontData sends to the GS. Here the same sprite is drawn natively, and fontDmaFontData
|
||||
// only resets what it would after sending (the font's texture from the texture pack: no upload).
|
||||
|
||||
#include "game_overrides.h"
|
||||
#include "ps2_runtime.h"
|
||||
#include "ps2_recompiled_functions.h"
|
||||
#include "runtime/native/native_renderer.h"
|
||||
#include "runtime/native/native_texture_cache.h"
|
||||
#include "runtime/ps2_store_patch.h"
|
||||
#include "runtime/native/native_movie.h"
|
||||
#include "tmb_port.h"
|
||||
#include "bozo/render/renderer.h"
|
||||
#include "bozo/render/texture.h"
|
||||
#include "bozo/render/movie.h"
|
||||
#include <mutex>
|
||||
|
||||
#include <cstdio>
|
||||
@@ -35,7 +32,7 @@ namespace tmb::native
|
||||
|
||||
namespace tmb::textures
|
||||
{
|
||||
std::shared_ptr<const ps2x::native::TextureCache::Texture> font();
|
||||
std::shared_ptr<const bozo::render::Texture> font();
|
||||
}
|
||||
|
||||
namespace tmb::native
|
||||
@@ -51,10 +48,10 @@ namespace tmb::twod
|
||||
{
|
||||
// The movie pictures (sceMpegGetPicture, below), shared by loadImage and the loading bar.
|
||||
std::mutex g_movieMutex;
|
||||
std::shared_ptr<const ps2x::native::TextureCache::Texture> g_moviePicture; // under g_movieMutex
|
||||
std::shared_ptr<const bozo::render::Texture> g_moviePicture; // under g_movieMutex
|
||||
// The picture loadImage last put in the display buffers (under g_movieMutex): the one shown through the display's
|
||||
// circuit 2 (ps2x::native::setDisplayPicture).
|
||||
std::shared_ptr<const ps2x::native::TextureCache::Texture> g_menuPicture;
|
||||
// circuit 2 (bozo::render::setDisplayPicture).
|
||||
std::shared_ptr<const bozo::render::Texture> g_menuPicture;
|
||||
std::atomic<bool> g_imageReplaced{false}; // loadImage drew a picture instead of transferring it (this vblank)
|
||||
|
||||
constexpr uint32_t kFontBuildPrim = 0x001C4918u;
|
||||
@@ -131,7 +128,7 @@ namespace tmb::twod
|
||||
std::memcpy(&rgba, rdram + record + 0x18u, 4);
|
||||
|
||||
// The sprite as two triangles: positions in GS pixels (12.4 / 16), texture coordinates over the 128 x 128 font.
|
||||
ps2x::native::Vertex corners[4];
|
||||
bozo::render::Vertex corners[4];
|
||||
const float xs[2] = {x0 / 16.0f, x1 / 16.0f}, ys[2] = {y0 / 16.0f, y1 / 16.0f};
|
||||
const float us[2] = {u0 / 16.0f / 128.0f, u1 / 16.0f / 128.0f}, vs[2] = {v0 / 16.0f / 128.0f, v1 / 16.0f / 128.0f};
|
||||
for (int i = 0; i < 4; ++i)
|
||||
@@ -143,12 +140,12 @@ namespace tmb::twod
|
||||
corners[i].rgba = rgba;
|
||||
corners[i].fog = 1.0f;
|
||||
}
|
||||
const ps2x::native::Vertex triangles[6] = {corners[0], corners[1], corners[2], corners[1], corners[3], corners[2]};
|
||||
const bozo::render::Vertex triangles[6] = {corners[0], corners[1], corners[2], corners[1], corners[3], corners[2]};
|
||||
// fontInitPacket's state: ALPHA (Cs - Cd) As + Cd, TEST alpha greater than 8, TEX1 bilinear.
|
||||
ps2x::native::Material material;
|
||||
bozo::render::Material material;
|
||||
material.textured = true;
|
||||
material.tex0 = 0xf0f7f0f7u; // the font's own GPU copy
|
||||
material.blend = ps2x::native::Material::Blend::Alpha;
|
||||
material.blend = bozo::render::Material::Blend::Alpha;
|
||||
material.alphaTest = true;
|
||||
material.alphaRef = 8;
|
||||
material.clampU = material.clampV = true;
|
||||
@@ -160,7 +157,7 @@ namespace tmb::twod
|
||||
if (s_log && s_logged < 6000u && !s_seen[place] && (s_seen[place] = true) && ++s_logged)
|
||||
std::fprintf(stderr, "[tmb:2d] glyph %c: (%.1f %.1f)-(%.1f %.1f) uv (%.3f %.3f)-(%.3f %.3f) rgba %08x view %u centre %d %d size %dx%d\n",
|
||||
static_cast<char>(c), xs[0], ys[0], xs[1], ys[1], us[0], vs[0], us[1], vs[1], rgba, view, centreX, centreY, viewW, viewH);
|
||||
ps2x::native::Renderer::instance().drawOverlay(material, triangles, 6u, tmb::textures::font());
|
||||
bozo::render::Renderer::instance().drawOverlay(material, triangles, 6u, tmb::textures::font());
|
||||
|
||||
// What fontBuildPrim leaves: its sprites' tag started (mode 2, where it would be), the cursor advanced, the
|
||||
// glyph counted.
|
||||
@@ -256,17 +253,17 @@ namespace tmb::twod
|
||||
|
||||
// The HUD's primitives on the overlay: GS pixel coordinates, colours as the GS has them (0x80 is 1.0); ABE: the
|
||||
// packet's ALPHA_1 (Cs - Cd) As + Cd, else opaque.
|
||||
void hudTriangles(const ps2x::native::Vertex *v, uint32_t count, bool blend)
|
||||
void hudTriangles(const bozo::render::Vertex *v, uint32_t count, bool blend)
|
||||
{
|
||||
ps2x::native::Material material;
|
||||
bozo::render::Material material;
|
||||
material.textured = false;
|
||||
material.blend = blend ? ps2x::native::Material::Blend::Alpha : ps2x::native::Material::Blend::Opaque;
|
||||
ps2x::native::Renderer::instance().drawOverlay(material, v, count, nullptr);
|
||||
material.blend = blend ? bozo::render::Material::Blend::Alpha : bozo::render::Material::Blend::Opaque;
|
||||
bozo::render::Renderer::instance().drawOverlay(material, v, count, nullptr);
|
||||
}
|
||||
uint32_t rgba(uint32_t r, uint32_t g, uint32_t b, uint32_t a) { return (r & 0xffu) | ((g & 0xffu) << 8) | ((b & 0xffu) << 16) | ((a & 0xffu) << 24); }
|
||||
ps2x::native::Vertex vertex(float x, float y, uint32_t colour)
|
||||
bozo::render::Vertex vertex(float x, float y, uint32_t colour)
|
||||
{
|
||||
ps2x::native::Vertex v;
|
||||
bozo::render::Vertex v;
|
||||
v.x = x;
|
||||
v.y = y;
|
||||
v.rgba = colour;
|
||||
@@ -277,7 +274,7 @@ namespace tmb::twod
|
||||
void hudSprite(float x0, float y0, float x1, float y1, uint32_t colour, bool blend)
|
||||
{
|
||||
const float l = std::min(x0, x1), r = std::max(x0, x1), t = std::min(y0, y1), b = std::max(y0, y1);
|
||||
const ps2x::native::Vertex v[6] = {vertex(l, t, colour), vertex(r, t, colour), vertex(l, b, colour),
|
||||
const bozo::render::Vertex v[6] = {vertex(l, t, colour), vertex(r, t, colour), vertex(l, b, colour),
|
||||
vertex(r, t, colour), vertex(r, b, colour), vertex(l, b, colour)};
|
||||
hudTriangles(v, 6u, blend);
|
||||
}
|
||||
@@ -288,7 +285,7 @@ namespace tmb::twod
|
||||
if (!(length > 0.0f))
|
||||
return;
|
||||
const float nx = -dy / length * 0.5f, ny = dx / length * 0.5f;
|
||||
const ps2x::native::Vertex v[6] = {vertex(x0 + nx, y0 + ny, colour), vertex(x1 + nx, y1 + ny, colour), vertex(x0 - nx, y0 - ny, colour),
|
||||
const bozo::render::Vertex v[6] = {vertex(x0 + nx, y0 + ny, colour), vertex(x1 + nx, y1 + ny, colour), vertex(x0 - nx, y0 - ny, colour),
|
||||
vertex(x1 + nx, y1 + ny, colour), vertex(x1 - nx, y1 - ny, colour), vertex(x0 - nx, y0 - ny, colour)};
|
||||
hudTriangles(v, 6u, blend);
|
||||
}
|
||||
@@ -461,7 +458,7 @@ namespace tmb::twod
|
||||
dbl(rdram, kAlphaConstants + 16u)) + 0x1e);
|
||||
}
|
||||
colour = (colour & 0xffffffu) | (std::min<uint32_t>(alpha, 0xffu) << 24);
|
||||
const ps2x::native::Vertex v[3] = {vertex(sx - 12.0f, sy - 6.0f, colour), vertex(sx, sy, colour), vertex(sx + 12.0f, sy - 6.0f, colour)};
|
||||
const bozo::render::Vertex v[3] = {vertex(sx - 12.0f, sy - 6.0f, colour), vertex(sx, sy, colour), vertex(sx + 12.0f, sy - 6.0f, colour)};
|
||||
hudTriangles(v, 3u, true);
|
||||
}
|
||||
}
|
||||
@@ -754,12 +751,12 @@ namespace tmb::twod
|
||||
static_cast<float>(bottom), rgba(0x4c, 0x1a, 0x0d, 0x80), false);
|
||||
const uint32_t def = word(rdram, kViews + 4u);
|
||||
const float width = half(rdram, def + 8u), height = half(rdram, def + 0xau);
|
||||
ps2x::native::Screen screen;
|
||||
bozo::render::Screen screen;
|
||||
screen.width = width > 0.0f ? width : 640.0f;
|
||||
screen.height = height > 0.0f ? height : 448.0f;
|
||||
screen.originX = 2048.0f - screen.width * 0.5f;
|
||||
screen.originY = 2048.0f - screen.height * 0.5f;
|
||||
ps2x::native::Renderer::instance().publishOverlay(screen);
|
||||
bozo::render::Renderer::instance().publishOverlay(screen);
|
||||
}
|
||||
|
||||
// buildProgressBar(progress): the bar at min(progress, 1024) / 1024, drawn instead of sent.
|
||||
@@ -777,7 +774,7 @@ namespace tmb::twod
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(g_movieMutex);
|
||||
g_menuPicture.reset();
|
||||
ps2x::native::clearDisplayPicture();
|
||||
bozo::render::clearDisplayPicture();
|
||||
}
|
||||
setWord(rdram, gp + kGpBarProgress, std::min<uint32_t>(getRegU32(ctx, 4), 0x400u));
|
||||
loadingBar(rdram, gp);
|
||||
@@ -827,6 +824,7 @@ namespace tmb::twod
|
||||
const float left = static_cast<float>(v.cx - (v.w >> 1)), top = static_cast<float>(v.cy - (v.h >> 1));
|
||||
hudSprite(left, top, left + static_cast<float>(v.w), top + static_cast<float>(v.h), rgba(0, 0, 0x0a, 0x21), true);
|
||||
}
|
||||
// bozo:store kDialogKick (the generated code sets ctx->pc before that store: tools/tmb_overrides_list.py)
|
||||
bool dialogKick(uint32_t pc, uint32_t address, uint32_t)
|
||||
{
|
||||
return pc == kDialogKick && address == 0x1000a000u && on();
|
||||
@@ -843,14 +841,14 @@ namespace tmb::twod
|
||||
void moviePicture(uint32_t, uint32_t width, uint32_t height, const uint8_t *rgba)
|
||||
{
|
||||
static uint64_t s_version = 0;
|
||||
ps2x::native::TextureCache::Texture picture;
|
||||
bozo::render::Texture picture;
|
||||
picture.width = width;
|
||||
picture.height = height;
|
||||
picture.key = 0x4d4f5649u; // one picture at a time: its GPU copy replaced
|
||||
picture.version = ++s_version;
|
||||
picture.rgba.resize(static_cast<size_t>(width) * height);
|
||||
std::memcpy(picture.rgba.data(), rgba, picture.rgba.size() * 4u);
|
||||
auto shared = std::make_shared<const ps2x::native::TextureCache::Texture>(std::move(picture));
|
||||
auto shared = std::make_shared<const bozo::render::Texture>(std::move(picture));
|
||||
std::lock_guard<std::mutex> lock(g_movieMutex);
|
||||
g_moviePicture = std::move(shared);
|
||||
}
|
||||
@@ -860,7 +858,7 @@ namespace tmb::twod
|
||||
// are drawn over it with alpha 0 where it shows (PMODE merges the circuits by the frame's alpha), and it stays
|
||||
// there after the clip ends (blitLastMovieFrame) until a load starts. A movie on its own (no menu frames) is
|
||||
// also shown under the overlay.
|
||||
void showOnCircuit2(const ps2x::native::TextureCache::Texture &picture)
|
||||
void showOnCircuit2(const bozo::render::Texture &picture)
|
||||
{
|
||||
constexpr uint32_t kFrameWidth = 640u, kFrameHeight = 448u;
|
||||
auto frame = std::make_shared<std::vector<uint32_t>>(static_cast<size_t>(kFrameWidth) * kFrameHeight, 0x80000000u);
|
||||
@@ -869,12 +867,12 @@ namespace tmb::twod
|
||||
for (uint32_t y = 0; y < height; ++y)
|
||||
for (uint32_t x = 0; x < width; ++x)
|
||||
(*frame)[(y0 + y) * kFrameWidth + x0 + x] = (picture.rgba[y * picture.width + x] & 0x00ffffffu) | 0x80000000u;
|
||||
ps2x::native::setDisplayPicture(std::move(frame), kFrameWidth, kFrameHeight);
|
||||
bozo::render::setDisplayPicture(std::move(frame), kFrameWidth, kFrameHeight);
|
||||
}
|
||||
|
||||
void loadImageOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
|
||||
{
|
||||
std::shared_ptr<const ps2x::native::TextureCache::Texture> picture;
|
||||
std::shared_ptr<const bozo::render::Texture> picture;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(g_movieMutex);
|
||||
picture = g_moviePicture;
|
||||
@@ -890,14 +888,14 @@ namespace tmb::twod
|
||||
return;
|
||||
}
|
||||
constexpr float kFrameHeight = 448.0f;
|
||||
ps2x::native::Screen screen;
|
||||
bozo::render::Screen screen;
|
||||
screen.originX = 2048.0f - 320.0f;
|
||||
screen.originY = 2048.0f - kFrameHeight * 0.5f;
|
||||
screen.width = 640.0f;
|
||||
screen.height = kFrameHeight;
|
||||
const float width = static_cast<float>(picture->width), height = static_cast<float>(picture->height);
|
||||
if (!tmb::native::menusDrawn())
|
||||
ps2x::native::Renderer::instance().setBackdrop(std::move(picture), screen, screen.originX + (640.0f - width) * 0.5f,
|
||||
bozo::render::Renderer::instance().setBackdrop(std::move(picture), screen, screen.originX + (640.0f - width) * 0.5f,
|
||||
screen.originY + (kFrameHeight - height) * 0.5f, width, height);
|
||||
g_imageReplaced.store(true, std::memory_order_relaxed);
|
||||
const uint32_t held = getRegU32(ctx, 28) + static_cast<uint32_t>(kImageHeld);
|
||||
@@ -987,7 +985,7 @@ namespace tmb::twod
|
||||
const uint8_t *rdram = g_rdram.load(std::memory_order_relaxed);
|
||||
if (!rdram)
|
||||
{
|
||||
ps2x::native::Renderer::instance().publishOverlay();
|
||||
bozo::render::Renderer::instance().publishOverlay();
|
||||
return;
|
||||
}
|
||||
// The whole display: every view the game shows (viewGetNumViews), e.g. a rear view over the main one.
|
||||
@@ -1005,18 +1003,18 @@ namespace tmb::twod
|
||||
}
|
||||
if (!(right > left && bottom > top))
|
||||
{
|
||||
ps2x::native::Renderer::instance().publishOverlay();
|
||||
bozo::render::Renderer::instance().publishOverlay();
|
||||
return;
|
||||
}
|
||||
ps2x::native::Screen screen;
|
||||
bozo::render::Screen screen;
|
||||
screen.originX = left;
|
||||
screen.originY = top;
|
||||
screen.width = right - left;
|
||||
screen.height = bottom - top;
|
||||
ps2x::native::Renderer::instance().publishOverlay(screen);
|
||||
bozo::render::Renderer::instance().publishOverlay(screen);
|
||||
}
|
||||
|
||||
void install(PS2Runtime &runtime)
|
||||
void install(tmb::Registry &runtime)
|
||||
{
|
||||
runtime.registerFunction(kFontBuildPrim, &fontBuildPrimOverride);
|
||||
runtime.registerFunction(kFontDmaFontData, &fontDmaFontDataOverride);
|
||||
@@ -1034,11 +1032,11 @@ namespace tmb::twod
|
||||
runtime.registerFunction(kInformProgressBar, &informProgressBarOverride);
|
||||
runtime.registerFunction(kBarVSync, &barVSyncOverride);
|
||||
runtime.registerFunction(kFinishShellLoop, &finishShellLoopOverride);
|
||||
ps2x::setStorePatch(&dialogKick);
|
||||
bozo::port::setStorePatch(&dialogKick);
|
||||
runtime.registerFunction(kLoadImage, &loadImageOverride);
|
||||
runtime.registerFunction(kVblankHandler, &vblankHandlerOverride);
|
||||
if (on())
|
||||
ps2x::native::setMoviePictureHook(&moviePicture);
|
||||
bozo::render::setMoviePictureHook(&moviePicture);
|
||||
runtime.registerFunction(kOverheat, &overheatOverride);
|
||||
}
|
||||
}
|
||||
+461
-462
@@ -1,462 +1,461 @@
|
||||
// Cheats, switched while playing from the Cheats tab of the settings window (F2), per human player; the environment
|
||||
// gives their values at launch (TMB_UNLOCK_ALL, TMB_NO_AI, TMB_PLAYER_GOD, TMB_INFINITE_AMMO, TMB_INFINITE_ENERGY,
|
||||
// TMB_ENEMY_HEALTH_CAP; TMB_PLAYER_HEALTH_CAP is the testing opposite, a cap on the player's health).
|
||||
//
|
||||
// What the game keeps, from its own code:
|
||||
// - TheGame (`this` of TheGame::Update): its vehicles at TheGame + i * 0x2D00, their count at + 0x1B3DB4
|
||||
// (TheGame::GetVehicleFromName); the human players' vehicles as pointers at + 0x1B28B0, their count at + 0x1B3DB8
|
||||
// (TheGame::gameCheckPlayerHealth, 0x133360, which walks them).
|
||||
// - A vehicle's health: float at + 0x3F4, its maximum at + 0x3F0 (gameCheckPlayerHealth's health fraction, the HUD's
|
||||
// health bars). Who drives it: + 0x580, 1 a player (vehicleUpdate calls playerUpdateInputs), 2 the computer
|
||||
// (aiUpdateInputs, 0x1014A0).
|
||||
// - Weapons: the count of pickup weapon i (1 to 8; slot 1 is the car's special, which Launcher::FireSpecial spends)
|
||||
// at + 0x22C4 + 4 * i, the weapon selected at + 0x2140; the machine gun (slot 0) has no count. Every shot,
|
||||
// detonation and special spends through TheGame::DecrementWeaponCount (0x1515A8, called by FireCurrentWeapon,
|
||||
// FireSpecial, UpdateSpecial, UpdateLauncher, UpdateEnvWeapon, UpdateZoomies, UpdateWeaponToggle, KillWeapon),
|
||||
// which goes on to Weapons::DecrementWeaponCount (0x1BA050: count - 1, then the next weapon with ammo when it
|
||||
// reaches 0).
|
||||
// - Energy (the freeze / mines / shield moves of the stick combos): int at + 0x2214 of + 0x2218 (the HUD's energy
|
||||
// bar, Hud::build4PEnergyBar).
|
||||
// - Progress: the Shell (at 0x40BCC0, the pointer at gp - 0x4148) keeps what is locked as words at Shell + 0x18000 +
|
||||
// offset, 1 locked and 0 open; Shell::Shell (0x15F270) sets a fresh save's (what loadGlobalData then overwrites
|
||||
// from the card's globalFile): the vehicles at + 0x218C + 4 * car (16; uiCarSel and uiAiSel play the locked sound
|
||||
// on a 1; 9-12, 14 and 15 locked at first), the levels at + 0x21CC + 4 * level (21; uiLvlSel, the same; Shell::
|
||||
// EvaluateEnduranceStatus clears 2 Freeway, 15 and 18 when their endurance kills are reached), and per character its
|
||||
// movies, three arrays of 14 at + 0x2220, + 0x2258, + 0x2290 (uiMovies; 2 for a movie the character does not have).
|
||||
|
||||
#include "game_overrides.h"
|
||||
#include "ps2_runtime.h"
|
||||
#include "ps2_recompiled_functions.h"
|
||||
#include "runtime/ps2_debug_ui.h"
|
||||
#if defined(PS2X_ENABLE_DEBUG_UI)
|
||||
#include "imgui.h"
|
||||
#endif
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace tmb::cheats
|
||||
{
|
||||
namespace
|
||||
{
|
||||
constexpr uint32_t kAiUpdateInputs = 0x001014A0u;
|
||||
constexpr uint32_t kAiUpdateFrozenInput = 0x001017E8u;
|
||||
constexpr uint32_t kDecrementWeaponCount = 0x001515A8u;
|
||||
constexpr uint32_t kVehicles = 0x00000000u, kVehicleStride = 0x2D00u, kVehicleCount = 0x001B3DB4u;
|
||||
constexpr uint32_t kPlayers = 0x001B28B0u, kPlayerCount = 0x001B3DB8u;
|
||||
constexpr uint32_t kHealth = 0x3F4u, kHealthMax = 0x3F0u, kDriver = 0x580u;
|
||||
constexpr uint32_t kWeaponCounts = 0x22C4u, kEnergy = 0x2214u, kEnergyMax = 0x2218u;
|
||||
constexpr int kMaxPlayers = 4;
|
||||
constexpr uint32_t kGpShell = 0x4148u, kShellProgress = 0x18000u;
|
||||
// The shell screens that read the locks, and the lock arrays (offset, count) from Shell + 0x18000.
|
||||
constexpr uint32_t kUiLvlSel = 0x001976B0u, kUiCarSel = 0x001963B0u, kUiAiSel = 0x001986A8u, kUiMovies = 0x00190760u;
|
||||
constexpr struct
|
||||
{
|
||||
uint32_t offset, count;
|
||||
} kLocks[] = {{0x218Cu, 16u}, {0x21CCu, 21u}, {0x2220u, 14u}, {0x2258u, 14u}, {0x2290u, 14u}};
|
||||
|
||||
// One bit per player (bit 0: player 1).
|
||||
std::atomic<uint32_t> g_infiniteHealth{0}, g_infiniteAmmo{0}, g_infiniteEnergy{0};
|
||||
std::atomic<bool> g_noAi{false};
|
||||
std::atomic<bool> g_unlockAll{false};
|
||||
// Story: start at a level (-1: off). The story's state is the level being played, Shell + 0x18000 + 0x2354 (the
|
||||
// index of the game's level table: GetLevelName, LoadLevelDB), the one last won at + 0x2358, the mode at
|
||||
// + 0x235C (1: one-player story); a new story sets the level to 1, the Junkyard, and each level won sets the
|
||||
// next (EvaluateOnePlayerStoryStatus).
|
||||
std::atomic<int> g_storyStart{-1};
|
||||
constexpr uint32_t kStoryLevel = 0x2354u, kStoryLastWon = 0x2358u, kGameMode = 0x235Cu;
|
||||
constexpr int kLevelCount = 21;
|
||||
// The levels by the level table's index (its names at 0x426070, 16 bytes each), with the card the story shows
|
||||
// when it starts there (the stage, of 8). Two stages have two arenas (the story picks one); ASYLUM and ROOFTOP2
|
||||
// show no card (reached from inside another level); the others are arenas the story does not use.
|
||||
constexpr const char *kLevelNames[kLevelCount] = {
|
||||
"Stage 2: Midtown Suburbs (SUBURB)", "Stage 1: Junkyard (JUNKYARD)", "Stage 2: Midtown Expressway 104 (FREEWAY)",
|
||||
"Stage 5: Prison Passage to Blackfield Asylum (PRISON)", "Stage 7: Abandoned Skyscrapers (ROOFTOP)",
|
||||
"Stage 3: Downtown Business District (CITY)", "Stage 3: Black Vista Highway (LOOP)", "Arena DEATH1", "Arena DEATH2",
|
||||
"Arena DEATH3", "Arena DEATH4", "Arena DEATH5", "Arena DEATH6", "Rooftops, second part (ROOFTOP2)",
|
||||
"Stage 4: Minion's Stadium (STADIUM)", "Arena SHIP", "Blackfield Asylum (ASYLUM)", "Arena MINICITY", "Arena MINIBURB",
|
||||
"Arena JUNK2", "Stage 8: Warhawk's Rooftop (ROOFBOSS)"};
|
||||
// The picker's order: the story's, then the rest.
|
||||
constexpr int kLevelOrder[kLevelCount] = {1, 0, 2, 5, 6, 14, 3, 16, 4, 13, 20, 7, 8, 9, 10, 11, 12, 15, 17, 18, 19};
|
||||
std::vector<uint32_t> g_unlocked; // the lock words Unlock everything opened (put back when it goes off)
|
||||
std::atomic<float> g_enemyCap{-1.0f}; // weak enemies: every computer vehicle's health held at most this; < 0 off
|
||||
std::atomic<float> g_playerCap{-1.0f}; // TMB_PLAYER_HEALTH_CAP (testing)
|
||||
std::atomic<uint32_t> g_theGame{0};
|
||||
std::atomic<const uint8_t *> g_rdram{nullptr}; // for the tab (onFrame's)
|
||||
const std::chrono::steady_clock::time_point g_start = std::chrono::steady_clock::now(); // the log's times
|
||||
std::atomic<uint32_t> g_decrements{0}, g_decrementsSkipped{0}; // TMB_CHEATS_LOG: weapon spends since the last line
|
||||
|
||||
uint32_t word(const uint8_t *rdram, uint32_t address)
|
||||
{
|
||||
uint32_t value = 0;
|
||||
std::memcpy(&value, rdram + (address & 0x1FFFFFFu), 4);
|
||||
return value;
|
||||
}
|
||||
float flt(const uint8_t *rdram, uint32_t address)
|
||||
{
|
||||
float value = 0.0f;
|
||||
std::memcpy(&value, rdram + (address & 0x1FFFFFFu), 4);
|
||||
return value;
|
||||
}
|
||||
void setWord(uint8_t *rdram, uint32_t address, uint32_t value) { std::memcpy(rdram + (address & 0x1FFFFFFu), &value, 4); }
|
||||
void setFlt(uint8_t *rdram, uint32_t address, float value) { std::memcpy(rdram + (address & 0x1FFFFFFu), &value, 4); }
|
||||
|
||||
int playerCount(const uint8_t *rdram, uint32_t game)
|
||||
{
|
||||
return game == 0u ? 0 : std::clamp(static_cast<int32_t>(word(rdram, game + kPlayerCount)), 0, kMaxPlayers);
|
||||
}
|
||||
uint32_t playerVehicle(const uint8_t *rdram, uint32_t game, int player)
|
||||
{
|
||||
return word(rdram, game + kPlayers + static_cast<uint32_t>(player) * 4u);
|
||||
}
|
||||
// The players whose bit is set in `mask` that own `vehicle`.
|
||||
bool forPlayer(const uint8_t *rdram, uint32_t vehicle, uint32_t mask)
|
||||
{
|
||||
const uint32_t game = g_theGame.load(std::memory_order_relaxed);
|
||||
if (mask == 0u || vehicle == 0u)
|
||||
return false;
|
||||
for (int player = 0; player < playerCount(rdram, game); ++player)
|
||||
if ((mask >> player & 1u) && playerVehicle(rdram, game, player) == vehicle)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
// The players a variable names: digits 1 to 4 (TMB_INFINITE_AMMO=12: players 1 and 2), any other value but 0
|
||||
// every player.
|
||||
uint32_t envMask(const char *name)
|
||||
{
|
||||
const char *value = std::getenv(name);
|
||||
if (!value || !*value || std::string(value) == "0")
|
||||
return 0u;
|
||||
uint32_t mask = 0u;
|
||||
for (const char *c = value; *c; ++c)
|
||||
{
|
||||
if (*c < '1' || *c > '0' + kMaxPlayers)
|
||||
return (1u << kMaxPlayers) - 1u;
|
||||
mask |= 1u << (*c - '1');
|
||||
}
|
||||
return mask;
|
||||
}
|
||||
float envFloat(const char *name)
|
||||
{
|
||||
const char *value = std::getenv(name);
|
||||
return value && *value ? static_cast<float>(std::atof(value)) : -1.0f;
|
||||
}
|
||||
|
||||
// No AI: Vehicle::aiUpdateInputs (each computer vehicle's pad, every frame) runs the game's own
|
||||
// aiUpdateFrozenInput instead (no throttle, no steering, no firing).
|
||||
void aiUpdateInputsOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
|
||||
{
|
||||
if (g_noAi.load(std::memory_order_relaxed))
|
||||
{
|
||||
ctx->pc = kAiUpdateFrozenInput;
|
||||
aiUpdateFrozenInput__7Vehicle_0x1017e8(rdram, ctx, runtime);
|
||||
return;
|
||||
}
|
||||
aiUpdateInputs__7Vehicle_0x1014a0(rdram, ctx, runtime);
|
||||
}
|
||||
|
||||
// Infinite ammo: TheGame::DecrementWeaponCount(game, vehicle, weapon) returns at once for a player who has it,
|
||||
// so nothing the car fires or detonates is counted (and the selected weapon stays).
|
||||
void decrementWeaponCountOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
|
||||
{
|
||||
g_decrements.fetch_add(1, std::memory_order_relaxed);
|
||||
static const bool s_log = std::getenv("TMB_CHEATS_LOG") != nullptr;
|
||||
if (s_log && word(rdram, getRegU32(ctx, 5) + kDriver) == 1u)
|
||||
std::fprintf(stderr, "[tmb:cheats] %.1f s: player car %x spends weapon %u (count %d)%s\n",
|
||||
std::chrono::duration<double>(std::chrono::steady_clock::now() - g_start).count(), getRegU32(ctx, 5), getRegU32(ctx, 6),
|
||||
static_cast<int32_t>(word(rdram, getRegU32(ctx, 5) + kWeaponCounts + getRegU32(ctx, 6) * 4u)),
|
||||
forPlayer(rdram, getRegU32(ctx, 5), g_infiniteAmmo.load(std::memory_order_relaxed)) ? ", not counted" : "");
|
||||
if (forPlayer(rdram, getRegU32(ctx, 5), g_infiniteAmmo.load(std::memory_order_relaxed)))
|
||||
{
|
||||
g_decrementsSkipped.fetch_add(1, std::memory_order_relaxed);
|
||||
ctx->pc = getRegU32(ctx, 31); // jr $ra
|
||||
return;
|
||||
}
|
||||
DecrementWeaponCount__7TheGameP7Vehiclei_0x1515a8(rdram, ctx, runtime);
|
||||
}
|
||||
|
||||
// Unlock everything: every lock word still 1 opened; off, the ones it opened closed again (the game's own unlocks
|
||||
// since then stay, the card is written only when the player saves).
|
||||
void applyUnlocks(uint8_t *rdram, uint32_t gp)
|
||||
{
|
||||
const uint32_t shell = word(rdram, gp - kGpShell);
|
||||
if (shell == 0u)
|
||||
return;
|
||||
const uint32_t progress = shell + kShellProgress;
|
||||
if (g_unlockAll.load(std::memory_order_relaxed))
|
||||
{
|
||||
for (const auto &locks : kLocks)
|
||||
for (uint32_t i = 0; i < locks.count; ++i)
|
||||
{
|
||||
const uint32_t address = progress + locks.offset + i * 4u;
|
||||
if (word(rdram, address) == 1u)
|
||||
{
|
||||
setWord(rdram, address, 0u);
|
||||
g_unlocked.push_back(address);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (!g_unlocked.empty())
|
||||
{
|
||||
for (const uint32_t address : g_unlocked)
|
||||
if (word(rdram, address) == 0u)
|
||||
setWord(rdram, address, 1u);
|
||||
g_unlocked.clear();
|
||||
}
|
||||
}
|
||||
template <void (*Screen)(uint8_t *, R5900Context *, PS2Runtime *)>
|
||||
void shellScreenOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
|
||||
{
|
||||
applyUnlocks(rdram, getRegU32(ctx, 28));
|
||||
Screen(rdram, ctx, runtime);
|
||||
}
|
||||
|
||||
#if defined(PS2X_ENABLE_DEBUG_UI)
|
||||
void perPlayer(const char *label, std::atomic<uint32_t> &flags, int players)
|
||||
{
|
||||
ImGui::PushID(label);
|
||||
uint32_t mask = flags.load(std::memory_order_relaxed);
|
||||
// On for every player of the match (every player when there is none yet).
|
||||
const uint32_t present = players > 0 ? (1u << players) - 1u : (1u << kMaxPlayers) - 1u;
|
||||
bool all = (mask & present) == present;
|
||||
if (ImGui::Checkbox(label, &all))
|
||||
mask = all ? (1u << kMaxPlayers) - 1u : 0u;
|
||||
for (int player = 0; player < std::max(players, 1); ++player)
|
||||
{
|
||||
ImGui::SameLine(player == 0 ? 220.0f : 0.0f);
|
||||
bool on = mask >> player & 1u;
|
||||
char name[8];
|
||||
std::snprintf(name, sizeof(name), "P%d", player + 1);
|
||||
if (ImGui::Checkbox(name, &on))
|
||||
mask = on ? mask | 1u << player : mask & ~(1u << player);
|
||||
}
|
||||
flags.store(mask, std::memory_order_relaxed);
|
||||
ImGui::PopID();
|
||||
}
|
||||
|
||||
void drawTab()
|
||||
{
|
||||
const uint8_t *rdram = g_rdram.load(std::memory_order_relaxed);
|
||||
const uint32_t game = g_theGame.load(std::memory_order_relaxed);
|
||||
const int players = rdram ? playerCount(rdram, game) : 0;
|
||||
ImGui::TextDisabled(players ? "In a match: %d player(s). Changes apply at once." : "They act in a match.", players);
|
||||
|
||||
bool unlock = g_unlockAll.load(std::memory_order_relaxed);
|
||||
if (ImGui::Checkbox("Unlock everything (levels, vehicles, movies)", &unlock))
|
||||
g_unlockAll.store(unlock, std::memory_order_relaxed);
|
||||
ImGui::TextDisabled("Opened in the menus; saving the game while it is on keeps them on the card.");
|
||||
|
||||
int start = g_storyStart.load(std::memory_order_relaxed);
|
||||
ImGui::SetNextItemWidth(420.0f);
|
||||
if (ImGui::BeginCombo("Story: start at", start < 0 ? "the first level (as the game)" : kLevelNames[start]))
|
||||
{
|
||||
if (ImGui::Selectable("the first level (as the game)", start < 0))
|
||||
start = -1;
|
||||
for (const int i : kLevelOrder)
|
||||
if (ImGui::Selectable(kLevelNames[i], start == i))
|
||||
start = i;
|
||||
ImGui::EndCombo();
|
||||
}
|
||||
g_storyStart.store(start, std::memory_order_relaxed);
|
||||
ImGui::TextDisabled("For testing: a new story begins at this level, then goes on as the game chains them.");
|
||||
|
||||
ImGui::SeparatorText("Players");
|
||||
perPlayer("Infinite health", g_infiniteHealth, players);
|
||||
perPlayer("Infinite ammo", g_infiniteAmmo, players);
|
||||
perPlayer("Infinite energy", g_infiniteEnergy, players);
|
||||
ImGui::TextDisabled("Health and energy held at their maximum; weapons and specials not spent.");
|
||||
|
||||
ImGui::SeparatorText("Opponents");
|
||||
bool noAi = g_noAi.load(std::memory_order_relaxed);
|
||||
if (ImGui::Checkbox("No AI (the computer's cars do nothing)", &noAi))
|
||||
g_noAi.store(noAi, std::memory_order_relaxed);
|
||||
float cap = g_enemyCap.load(std::memory_order_relaxed);
|
||||
bool weak = cap >= 0.0f;
|
||||
if (ImGui::Checkbox("Weak enemies", &weak))
|
||||
cap = weak ? 10.0f : -1.0f;
|
||||
if (weak)
|
||||
{
|
||||
ImGui::SameLine();
|
||||
ImGui::SetNextItemWidth(200.0f);
|
||||
ImGui::SliderFloat("health at most", &cap, 1.0f, 300.0f, "%.0f", ImGuiSliderFlags_Logarithmic);
|
||||
}
|
||||
g_enemyCap.store(cap, std::memory_order_relaxed);
|
||||
if (rdram && players)
|
||||
{
|
||||
const uint32_t car = playerVehicle(rdram, game, 0);
|
||||
ImGui::TextDisabled("Player 1: health %.0f of %.0f, energy %d of %d", flt(rdram, car + kHealth), flt(rdram, car + kHealthMax),
|
||||
static_cast<int32_t>(word(rdram, car + kEnergy)), static_cast<int32_t>(word(rdram, car + kEnergyMax)));
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
void setTheGame(uint32_t game) { g_theGame.store(game, std::memory_order_relaxed); }
|
||||
|
||||
// Once a frame (timerEndOfRealTimeProcessing, the frame's processing done).
|
||||
// TMB_LOG_PROGRESS=1 (finding the story's state): each word of Shell + 0x18000 + 0x2180 to + 0x2500 that changes,
|
||||
// with the time, from every frame end (the menus' too).
|
||||
void logProgress(uint8_t *rdram, uint32_t gp)
|
||||
{
|
||||
const uint32_t shell = word(rdram, gp - kGpShell);
|
||||
if (shell == 0u)
|
||||
return;
|
||||
// Story: start at a level. When a new story sets its first level (the Junkyard, nothing won yet), that level
|
||||
// is replaced, before the game loads it (it does once the character is chosen); the game's own chain goes on
|
||||
// from there.
|
||||
{
|
||||
const uint32_t progress = shell + kShellProgress;
|
||||
const int level = static_cast<int32_t>(word(rdram, progress + kStoryLevel));
|
||||
static int s_lastLevel = -2;
|
||||
const int start = g_storyStart.load(std::memory_order_relaxed);
|
||||
if (start >= 0 && level == 1 && s_lastLevel != 1 && word(rdram, progress + kGameMode) == 1u &&
|
||||
word(rdram, progress + kStoryLastWon) == 0u && start != 1)
|
||||
{
|
||||
setWord(rdram, progress + kStoryLevel, static_cast<uint32_t>(start));
|
||||
std::fprintf(stderr, "[tmb:cheats] story starts at level %s\n", kLevelNames[start]);
|
||||
}
|
||||
s_lastLevel = static_cast<int32_t>(word(rdram, progress + kStoryLevel));
|
||||
}
|
||||
static const bool s_on = std::getenv("TMB_LOG_PROGRESS") != nullptr;
|
||||
if (!s_on)
|
||||
return;
|
||||
static uint32_t s_last[0xE0] = {};
|
||||
static bool s_seen = false;
|
||||
static const auto s_start = std::chrono::steady_clock::now();
|
||||
const double t = std::chrono::duration<double>(std::chrono::steady_clock::now() - s_start).count();
|
||||
for (uint32_t i = 0; i < 0xE0u; ++i)
|
||||
{
|
||||
const uint32_t value = word(rdram, shell + kShellProgress + 0x2180u + i * 4u);
|
||||
if (s_seen && value != s_last[i])
|
||||
std::fprintf(stderr, "[tmb:progress] t=%.1f +0x%x: %d -> %d\n", t, 0x2180u + i * 4u, static_cast<int32_t>(s_last[i]),
|
||||
static_cast<int32_t>(value));
|
||||
s_last[i] = value;
|
||||
}
|
||||
s_seen = true;
|
||||
}
|
||||
|
||||
void onFrame(uint8_t *rdram)
|
||||
{
|
||||
g_rdram.store(rdram, std::memory_order_relaxed);
|
||||
const uint32_t game = g_theGame.load(std::memory_order_relaxed);
|
||||
if (game == 0u)
|
||||
return;
|
||||
// TMB_CHEATS_TOGGLE=<s> (testing): every cheat switched on and off every <s> seconds of match frames, as the
|
||||
// tab would (checks that each acts while playing, not only from launch).
|
||||
static const double s_toggle = []
|
||||
{
|
||||
const char *value = std::getenv("TMB_CHEATS_TOGGLE");
|
||||
return value && *value ? std::atof(value) : 0.0;
|
||||
}();
|
||||
if (s_toggle > 0.0)
|
||||
{
|
||||
const double now = std::chrono::duration<double>(std::chrono::steady_clock::now().time_since_epoch()).count();
|
||||
static double s_next = now + s_toggle;
|
||||
static bool s_on = false;
|
||||
if (now >= s_next)
|
||||
{
|
||||
s_next = now + s_toggle;
|
||||
s_on = !s_on;
|
||||
const uint32_t all = s_on ? (1u << kMaxPlayers) - 1u : 0u;
|
||||
g_infiniteHealth.store(all);
|
||||
g_infiniteAmmo.store(all);
|
||||
g_infiniteEnergy.store(all);
|
||||
g_noAi.store(s_on);
|
||||
g_enemyCap.store(s_on ? 10.0f : -1.0f);
|
||||
std::fprintf(stderr, "[tmb:cheats] all cheats %s\n", s_on ? "on" : "off");
|
||||
}
|
||||
}
|
||||
const uint32_t health = g_infiniteHealth.load(std::memory_order_relaxed), energy = g_infiniteEnergy.load(std::memory_order_relaxed);
|
||||
const float playerCap = g_playerCap.load(std::memory_order_relaxed);
|
||||
const int players = playerCount(rdram, game);
|
||||
for (int player = 0; player < players; ++player)
|
||||
{
|
||||
const uint32_t car = playerVehicle(rdram, game, player);
|
||||
if (car == 0u)
|
||||
continue;
|
||||
const float most = flt(rdram, car + kHealthMax), now = flt(rdram, car + kHealth);
|
||||
// Topped up while alive (a car already dead is left to respawn).
|
||||
if ((health >> player & 1u) && most > 0.0f && now > 0.0f && now < most)
|
||||
setFlt(rdram, car + kHealth, most);
|
||||
if (energy >> player & 1u)
|
||||
setWord(rdram, car + kEnergy, word(rdram, car + kEnergyMax));
|
||||
if (player == 0 && playerCap >= 0.0f)
|
||||
{
|
||||
static uint32_t s_frames = 0;
|
||||
if (++s_frames % 250u == 0u)
|
||||
std::fprintf(stderr, "[tmb:health] %.1f of %.1f\n", now, most);
|
||||
if (now > playerCap)
|
||||
setFlt(rdram, car + kHealth, playerCap);
|
||||
}
|
||||
}
|
||||
const float enemyCap = g_enemyCap.load(std::memory_order_relaxed);
|
||||
if (enemyCap >= 0.0f)
|
||||
{
|
||||
const int32_t count = std::min(static_cast<int32_t>(word(rdram, game + kVehicleCount)), 64);
|
||||
static uint32_t s_enemyFrames = 0;
|
||||
const bool log = ++s_enemyFrames % 500u == 0u;
|
||||
std::string line;
|
||||
for (int32_t index = 0; index < count; ++index)
|
||||
{
|
||||
const uint32_t vehicle = game + kVehicles + static_cast<uint32_t>(index) * kVehicleStride;
|
||||
const float now = flt(rdram, vehicle + kHealth);
|
||||
if (log)
|
||||
{
|
||||
char text[48];
|
||||
std::snprintf(text, sizeof(text), " %x:%.0f", vehicle, now);
|
||||
line += text;
|
||||
}
|
||||
if (word(rdram, vehicle + kDriver) != 1u && now > enemyCap)
|
||||
setFlt(rdram, vehicle + kHealth, enemyCap);
|
||||
}
|
||||
if (log)
|
||||
std::fprintf(stderr, "[tmb:enemies] TheGame %x, %d vehicles:%s\n", game, count, line.c_str());
|
||||
}
|
||||
// TMB_CHEATS_LOG=1: every 250 frames, each player's health, energy and weapon counts (scripted checks).
|
||||
static const bool s_log = std::getenv("TMB_CHEATS_LOG") != nullptr;
|
||||
static uint32_t s_logFrames = 0;
|
||||
if (s_log && ++s_logFrames % 250u == 0u)
|
||||
{
|
||||
std::fprintf(stderr, "[tmb:cheats] weapon spends %u (%u not counted: infinite ammo)\n", g_decrements.exchange(0),
|
||||
g_decrementsSkipped.exchange(0));
|
||||
for (int player = 0; player < players; ++player)
|
||||
{
|
||||
const uint32_t car = playerVehicle(rdram, game, player);
|
||||
std::string counts;
|
||||
for (uint32_t slot = 1; slot <= 8; ++slot)
|
||||
counts += " " + std::to_string(static_cast<int32_t>(word(rdram, car + kWeaponCounts + slot * 4u)));
|
||||
std::fprintf(stderr, "[tmb:cheats] P%d car %x: health %.0f/%.0f, energy %d/%d, weapon %d, counts%s\n", player + 1, car,
|
||||
flt(rdram, car + kHealth), flt(rdram, car + kHealthMax), static_cast<int32_t>(word(rdram, car + kEnergy)),
|
||||
static_cast<int32_t>(word(rdram, car + kEnergyMax)), static_cast<int32_t>(word(rdram, car + 0x2140u)), counts.c_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void install(PS2Runtime &runtime)
|
||||
{
|
||||
g_noAi.store(std::getenv("TMB_NO_AI") && *std::getenv("TMB_NO_AI") == '1');
|
||||
g_unlockAll.store(std::getenv("TMB_UNLOCK_ALL") && *std::getenv("TMB_UNLOCK_ALL") == '1');
|
||||
if (const char *level = std::getenv("TMB_STORY_LEVEL"); level && *level)
|
||||
g_storyStart.store(std::clamp(std::atoi(level), -1, kLevelCount - 1));
|
||||
g_infiniteHealth.store(envMask("TMB_PLAYER_GOD"));
|
||||
g_infiniteAmmo.store(envMask("TMB_INFINITE_AMMO"));
|
||||
g_infiniteEnergy.store(envMask("TMB_INFINITE_ENERGY"));
|
||||
g_enemyCap.store(envFloat("TMB_ENEMY_HEALTH_CAP"));
|
||||
g_playerCap.store(envFloat("TMB_PLAYER_HEALTH_CAP"));
|
||||
runtime.registerFunction(kAiUpdateInputs, &aiUpdateInputsOverride);
|
||||
runtime.registerFunction(kDecrementWeaponCount, &decrementWeaponCountOverride);
|
||||
runtime.registerFunction(kUiLvlSel, &shellScreenOverride<&uiLvlSel__Fv_0x1976b0>);
|
||||
runtime.registerFunction(kUiCarSel, &shellScreenOverride<&uiCarSel__Fv_0x1963b0>);
|
||||
runtime.registerFunction(kUiAiSel, &shellScreenOverride<&uiAiSel__Fv_0x1986a8>);
|
||||
runtime.registerFunction(kUiMovies, &shellScreenOverride<&uiMovies__Fv_0x190760>);
|
||||
#if defined(PS2X_ENABLE_DEBUG_UI)
|
||||
ps2x::debugui::registerTab("Cheats", &drawTab);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
// Cheats, switched while playing from the Cheats tab of the settings window (F2), per human player; the environment
|
||||
// gives their values at launch (TMB_UNLOCK_ALL, TMB_NO_AI, TMB_PLAYER_GOD, TMB_INFINITE_AMMO, TMB_INFINITE_ENERGY,
|
||||
// TMB_ENEMY_HEALTH_CAP; TMB_PLAYER_HEALTH_CAP is the testing opposite, a cap on the player's health).
|
||||
//
|
||||
// What the game keeps, from its own code:
|
||||
// - TheGame (`this` of TheGame::Update): its vehicles at TheGame + i * 0x2D00, their count at + 0x1B3DB4
|
||||
// (TheGame::GetVehicleFromName); the human players' vehicles as pointers at + 0x1B28B0, their count at + 0x1B3DB8
|
||||
// (TheGame::gameCheckPlayerHealth, 0x133360, which walks them).
|
||||
// - A vehicle's health: float at + 0x3F4, its maximum at + 0x3F0 (gameCheckPlayerHealth's health fraction, the HUD's
|
||||
// health bars). Who drives it: + 0x580, 1 a player (vehicleUpdate calls playerUpdateInputs), 2 the computer
|
||||
// (aiUpdateInputs, 0x1014A0).
|
||||
// - Weapons: the count of pickup weapon i (1 to 8; slot 1 is the car's special, which Launcher::FireSpecial spends)
|
||||
// at + 0x22C4 + 4 * i, the weapon selected at + 0x2140; the machine gun (slot 0) has no count. Every shot,
|
||||
// detonation and special spends through TheGame::DecrementWeaponCount (0x1515A8, called by FireCurrentWeapon,
|
||||
// FireSpecial, UpdateSpecial, UpdateLauncher, UpdateEnvWeapon, UpdateZoomies, UpdateWeaponToggle, KillWeapon),
|
||||
// which goes on to Weapons::DecrementWeaponCount (0x1BA050: count - 1, then the next weapon with ammo when it
|
||||
// reaches 0).
|
||||
// - Energy (the freeze / mines / shield moves of the stick combos): int at + 0x2214 of + 0x2218 (the HUD's energy
|
||||
// bar, Hud::build4PEnergyBar).
|
||||
// - Progress: the Shell (at 0x40BCC0, the pointer at gp - 0x4148) keeps what is locked as words at Shell + 0x18000 +
|
||||
// offset, 1 locked and 0 open; Shell::Shell (0x15F270) sets a fresh save's (what loadGlobalData then overwrites
|
||||
// from the card's globalFile): the vehicles at + 0x218C + 4 * car (16; uiCarSel and uiAiSel play the locked sound
|
||||
// on a 1; 9-12, 14 and 15 locked at first), the levels at + 0x21CC + 4 * level (21; uiLvlSel, the same; Shell::
|
||||
// EvaluateEnduranceStatus clears 2 Freeway, 15 and 18 when their endurance kills are reached), and per character its
|
||||
// movies, three arrays of 14 at + 0x2220, + 0x2258, + 0x2290 (uiMovies; 2 for a movie the character does not have).
|
||||
|
||||
#include "tmb_port.h"
|
||||
#include "bozo/app/determinism.h"
|
||||
#if defined(BOZO_SETTINGS_UI)
|
||||
#include "bozo/app/settings_tabs.h"
|
||||
#include "imgui.h"
|
||||
#endif
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace tmb::cheats
|
||||
{
|
||||
namespace
|
||||
{
|
||||
constexpr uint32_t kAiUpdateInputs = 0x001014A0u;
|
||||
constexpr uint32_t kAiUpdateFrozenInput = 0x001017E8u;
|
||||
constexpr uint32_t kDecrementWeaponCount = 0x001515A8u;
|
||||
constexpr uint32_t kVehicles = 0x00000000u, kVehicleStride = 0x2D00u, kVehicleCount = 0x001B3DB4u;
|
||||
constexpr uint32_t kPlayers = 0x001B28B0u, kPlayerCount = 0x001B3DB8u;
|
||||
constexpr uint32_t kHealth = 0x3F4u, kHealthMax = 0x3F0u, kDriver = 0x580u;
|
||||
constexpr uint32_t kWeaponCounts = 0x22C4u, kEnergy = 0x2214u, kEnergyMax = 0x2218u;
|
||||
constexpr int kMaxPlayers = 4;
|
||||
constexpr uint32_t kGpShell = 0x4148u, kShellProgress = 0x18000u;
|
||||
// The shell screens that read the locks, and the lock arrays (offset, count) from Shell + 0x18000.
|
||||
constexpr uint32_t kUiLvlSel = 0x001976B0u, kUiCarSel = 0x001963B0u, kUiAiSel = 0x001986A8u, kUiMovies = 0x00190760u;
|
||||
constexpr struct
|
||||
{
|
||||
uint32_t offset, count;
|
||||
} kLocks[] = {{0x218Cu, 16u}, {0x21CCu, 21u}, {0x2220u, 14u}, {0x2258u, 14u}, {0x2290u, 14u}};
|
||||
|
||||
// One bit per player (bit 0: player 1).
|
||||
std::atomic<uint32_t> g_infiniteHealth{0}, g_infiniteAmmo{0}, g_infiniteEnergy{0};
|
||||
std::atomic<bool> g_noAi{false};
|
||||
std::atomic<bool> g_unlockAll{false};
|
||||
// Story: start at a level (-1: off). The story's state is the level being played, Shell + 0x18000 + 0x2354 (the
|
||||
// index of the game's level table: GetLevelName, LoadLevelDB), the one last won at + 0x2358, the mode at
|
||||
// + 0x235C (1: one-player story); a new story sets the level to 1, the Junkyard, and each level won sets the
|
||||
// next (EvaluateOnePlayerStoryStatus).
|
||||
std::atomic<int> g_storyStart{-1};
|
||||
constexpr uint32_t kStoryLevel = 0x2354u, kStoryLastWon = 0x2358u, kGameMode = 0x235Cu;
|
||||
constexpr int kLevelCount = 21;
|
||||
// The levels by the level table's index (its names at 0x426070, 16 bytes each), with the card the story shows
|
||||
// when it starts there (the stage, of 8). Two stages have two arenas (the story picks one); ASYLUM and ROOFTOP2
|
||||
// show no card (reached from inside another level); the others are arenas the story does not use.
|
||||
constexpr const char *kLevelNames[kLevelCount] = {
|
||||
"Stage 2: Midtown Suburbs (SUBURB)", "Stage 1: Junkyard (JUNKYARD)", "Stage 2: Midtown Expressway 104 (FREEWAY)",
|
||||
"Stage 5: Prison Passage to Blackfield Asylum (PRISON)", "Stage 7: Abandoned Skyscrapers (ROOFTOP)",
|
||||
"Stage 3: Downtown Business District (CITY)", "Stage 3: Black Vista Highway (LOOP)", "Arena DEATH1", "Arena DEATH2",
|
||||
"Arena DEATH3", "Arena DEATH4", "Arena DEATH5", "Arena DEATH6", "Rooftops, second part (ROOFTOP2)",
|
||||
"Stage 4: Minion's Stadium (STADIUM)", "Arena SHIP", "Blackfield Asylum (ASYLUM)", "Arena MINICITY", "Arena MINIBURB",
|
||||
"Arena JUNK2", "Stage 8: Warhawk's Rooftop (ROOFBOSS)"};
|
||||
// The picker's order: the story's, then the rest.
|
||||
constexpr int kLevelOrder[kLevelCount] = {1, 0, 2, 5, 6, 14, 3, 16, 4, 13, 20, 7, 8, 9, 10, 11, 12, 15, 17, 18, 19};
|
||||
std::vector<uint32_t> g_unlocked; // the lock words Unlock everything opened (put back when it goes off)
|
||||
std::atomic<float> g_enemyCap{-1.0f}; // weak enemies: every computer vehicle's health held at most this; < 0 off
|
||||
std::atomic<float> g_playerCap{-1.0f}; // TMB_PLAYER_HEALTH_CAP (testing)
|
||||
std::atomic<uint32_t> g_theGame{0};
|
||||
std::atomic<const uint8_t *> g_rdram{nullptr}; // for the tab (onFrame's)
|
||||
const std::chrono::steady_clock::time_point g_start = std::chrono::steady_clock::now(); // the log's times
|
||||
std::atomic<uint32_t> g_decrements{0}, g_decrementsSkipped{0}; // TMB_CHEATS_LOG: weapon spends since the last line
|
||||
|
||||
uint32_t word(const uint8_t *rdram, uint32_t address)
|
||||
{
|
||||
uint32_t value = 0;
|
||||
std::memcpy(&value, rdram + (address & 0x1FFFFFFu), 4);
|
||||
return value;
|
||||
}
|
||||
float flt(const uint8_t *rdram, uint32_t address)
|
||||
{
|
||||
float value = 0.0f;
|
||||
std::memcpy(&value, rdram + (address & 0x1FFFFFFu), 4);
|
||||
return value;
|
||||
}
|
||||
void setWord(uint8_t *rdram, uint32_t address, uint32_t value) { std::memcpy(rdram + (address & 0x1FFFFFFu), &value, 4); }
|
||||
void setFlt(uint8_t *rdram, uint32_t address, float value) { std::memcpy(rdram + (address & 0x1FFFFFFu), &value, 4); }
|
||||
|
||||
int playerCount(const uint8_t *rdram, uint32_t game)
|
||||
{
|
||||
return game == 0u ? 0 : std::clamp(static_cast<int32_t>(word(rdram, game + kPlayerCount)), 0, kMaxPlayers);
|
||||
}
|
||||
uint32_t playerVehicle(const uint8_t *rdram, uint32_t game, int player)
|
||||
{
|
||||
return word(rdram, game + kPlayers + static_cast<uint32_t>(player) * 4u);
|
||||
}
|
||||
// The players whose bit is set in `mask` that own `vehicle`.
|
||||
bool forPlayer(const uint8_t *rdram, uint32_t vehicle, uint32_t mask)
|
||||
{
|
||||
const uint32_t game = g_theGame.load(std::memory_order_relaxed);
|
||||
if (mask == 0u || vehicle == 0u)
|
||||
return false;
|
||||
for (int player = 0; player < playerCount(rdram, game); ++player)
|
||||
if ((mask >> player & 1u) && playerVehicle(rdram, game, player) == vehicle)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
// The players a variable names: digits 1 to 4 (TMB_INFINITE_AMMO=12: players 1 and 2), any other value but 0
|
||||
// every player.
|
||||
uint32_t envMask(const char *name)
|
||||
{
|
||||
const char *value = std::getenv(name);
|
||||
if (!value || !*value || std::string(value) == "0")
|
||||
return 0u;
|
||||
uint32_t mask = 0u;
|
||||
for (const char *c = value; *c; ++c)
|
||||
{
|
||||
if (*c < '1' || *c > '0' + kMaxPlayers)
|
||||
return (1u << kMaxPlayers) - 1u;
|
||||
mask |= 1u << (*c - '1');
|
||||
}
|
||||
return mask;
|
||||
}
|
||||
float envFloat(const char *name)
|
||||
{
|
||||
const char *value = std::getenv(name);
|
||||
return value && *value ? static_cast<float>(std::atof(value)) : -1.0f;
|
||||
}
|
||||
|
||||
// No AI: Vehicle::aiUpdateInputs (each computer vehicle's pad, every frame) runs the game's own
|
||||
// aiUpdateFrozenInput instead (no throttle, no steering, no firing).
|
||||
void aiUpdateInputsOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
|
||||
{
|
||||
if (g_noAi.load(std::memory_order_relaxed))
|
||||
{
|
||||
ctx->pc = kAiUpdateFrozenInput;
|
||||
aiUpdateFrozenInput__7Vehicle_0x1017e8(rdram, ctx, runtime);
|
||||
return;
|
||||
}
|
||||
aiUpdateInputs__7Vehicle_0x1014a0(rdram, ctx, runtime);
|
||||
}
|
||||
|
||||
// Infinite ammo: TheGame::DecrementWeaponCount(game, vehicle, weapon) returns at once for a player who has it,
|
||||
// so nothing the car fires or detonates is counted (and the selected weapon stays).
|
||||
void decrementWeaponCountOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
|
||||
{
|
||||
g_decrements.fetch_add(1, std::memory_order_relaxed);
|
||||
static const bool s_log = std::getenv("TMB_CHEATS_LOG") != nullptr;
|
||||
if (s_log && word(rdram, getRegU32(ctx, 5) + kDriver) == 1u)
|
||||
std::fprintf(stderr, "[tmb:cheats] %.1f s: player car %x spends weapon %u (count %d)%s\n",
|
||||
std::chrono::duration<double>(std::chrono::steady_clock::now() - g_start).count(), getRegU32(ctx, 5), getRegU32(ctx, 6),
|
||||
static_cast<int32_t>(word(rdram, getRegU32(ctx, 5) + kWeaponCounts + getRegU32(ctx, 6) * 4u)),
|
||||
forPlayer(rdram, getRegU32(ctx, 5), g_infiniteAmmo.load(std::memory_order_relaxed)) ? ", not counted" : "");
|
||||
if (forPlayer(rdram, getRegU32(ctx, 5), g_infiniteAmmo.load(std::memory_order_relaxed)))
|
||||
{
|
||||
g_decrementsSkipped.fetch_add(1, std::memory_order_relaxed);
|
||||
ctx->pc = getRegU32(ctx, 31); // jr $ra
|
||||
return;
|
||||
}
|
||||
DecrementWeaponCount__7TheGameP7Vehiclei_0x1515a8(rdram, ctx, runtime);
|
||||
}
|
||||
|
||||
// Unlock everything: every lock word still 1 opened; off, the ones it opened closed again (the game's own unlocks
|
||||
// since then stay, the card is written only when the player saves).
|
||||
void applyUnlocks(uint8_t *rdram, uint32_t gp)
|
||||
{
|
||||
const uint32_t shell = word(rdram, gp - kGpShell);
|
||||
if (shell == 0u)
|
||||
return;
|
||||
const uint32_t progress = shell + kShellProgress;
|
||||
if (g_unlockAll.load(std::memory_order_relaxed))
|
||||
{
|
||||
for (const auto &locks : kLocks)
|
||||
for (uint32_t i = 0; i < locks.count; ++i)
|
||||
{
|
||||
const uint32_t address = progress + locks.offset + i * 4u;
|
||||
if (word(rdram, address) == 1u)
|
||||
{
|
||||
setWord(rdram, address, 0u);
|
||||
g_unlocked.push_back(address);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (!g_unlocked.empty())
|
||||
{
|
||||
for (const uint32_t address : g_unlocked)
|
||||
if (word(rdram, address) == 0u)
|
||||
setWord(rdram, address, 1u);
|
||||
g_unlocked.clear();
|
||||
}
|
||||
}
|
||||
template <void (*Screen)(uint8_t *, R5900Context *, PS2Runtime *)>
|
||||
void shellScreenOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
|
||||
{
|
||||
applyUnlocks(rdram, getRegU32(ctx, 28));
|
||||
Screen(rdram, ctx, runtime);
|
||||
}
|
||||
|
||||
#if defined(BOZO_SETTINGS_UI)
|
||||
void perPlayer(const char *label, std::atomic<uint32_t> &flags, int players)
|
||||
{
|
||||
ImGui::PushID(label);
|
||||
uint32_t mask = flags.load(std::memory_order_relaxed);
|
||||
// On for every player of the match (every player when there is none yet).
|
||||
const uint32_t present = players > 0 ? (1u << players) - 1u : (1u << kMaxPlayers) - 1u;
|
||||
bool all = (mask & present) == present;
|
||||
if (ImGui::Checkbox(label, &all))
|
||||
mask = all ? (1u << kMaxPlayers) - 1u : 0u;
|
||||
for (int player = 0; player < std::max(players, 1); ++player)
|
||||
{
|
||||
ImGui::SameLine(player == 0 ? 220.0f : 0.0f);
|
||||
bool on = mask >> player & 1u;
|
||||
char name[8];
|
||||
std::snprintf(name, sizeof(name), "P%d", player + 1);
|
||||
if (ImGui::Checkbox(name, &on))
|
||||
mask = on ? mask | 1u << player : mask & ~(1u << player);
|
||||
}
|
||||
flags.store(mask, std::memory_order_relaxed);
|
||||
ImGui::PopID();
|
||||
}
|
||||
|
||||
void drawTab()
|
||||
{
|
||||
const uint8_t *rdram = g_rdram.load(std::memory_order_relaxed);
|
||||
const uint32_t game = g_theGame.load(std::memory_order_relaxed);
|
||||
const int players = rdram ? playerCount(rdram, game) : 0;
|
||||
ImGui::TextDisabled(players ? "In a match: %d player(s). Changes apply at once." : "They act in a match.", players);
|
||||
|
||||
bool unlock = g_unlockAll.load(std::memory_order_relaxed);
|
||||
if (ImGui::Checkbox("Unlock everything (levels, vehicles, movies)", &unlock))
|
||||
g_unlockAll.store(unlock, std::memory_order_relaxed);
|
||||
ImGui::TextDisabled("Opened in the menus; saving the game while it is on keeps them on the card.");
|
||||
|
||||
int start = g_storyStart.load(std::memory_order_relaxed);
|
||||
ImGui::SetNextItemWidth(420.0f);
|
||||
if (ImGui::BeginCombo("Story: start at", start < 0 ? "the first level (as the game)" : kLevelNames[start]))
|
||||
{
|
||||
if (ImGui::Selectable("the first level (as the game)", start < 0))
|
||||
start = -1;
|
||||
for (const int i : kLevelOrder)
|
||||
if (ImGui::Selectable(kLevelNames[i], start == i))
|
||||
start = i;
|
||||
ImGui::EndCombo();
|
||||
}
|
||||
g_storyStart.store(start, std::memory_order_relaxed);
|
||||
ImGui::TextDisabled("For testing: a new story begins at this level, then goes on as the game chains them.");
|
||||
|
||||
ImGui::SeparatorText("Players");
|
||||
perPlayer("Infinite health", g_infiniteHealth, players);
|
||||
perPlayer("Infinite ammo", g_infiniteAmmo, players);
|
||||
perPlayer("Infinite energy", g_infiniteEnergy, players);
|
||||
ImGui::TextDisabled("Health and energy held at their maximum; weapons and specials not spent.");
|
||||
|
||||
ImGui::SeparatorText("Opponents");
|
||||
bool noAi = g_noAi.load(std::memory_order_relaxed);
|
||||
if (ImGui::Checkbox("No AI (the computer's cars do nothing)", &noAi))
|
||||
g_noAi.store(noAi, std::memory_order_relaxed);
|
||||
float cap = g_enemyCap.load(std::memory_order_relaxed);
|
||||
bool weak = cap >= 0.0f;
|
||||
if (ImGui::Checkbox("Weak enemies", &weak))
|
||||
cap = weak ? 10.0f : -1.0f;
|
||||
if (weak)
|
||||
{
|
||||
ImGui::SameLine();
|
||||
ImGui::SetNextItemWidth(200.0f);
|
||||
ImGui::SliderFloat("health at most", &cap, 1.0f, 300.0f, "%.0f", ImGuiSliderFlags_Logarithmic);
|
||||
}
|
||||
g_enemyCap.store(cap, std::memory_order_relaxed);
|
||||
if (rdram && players)
|
||||
{
|
||||
const uint32_t car = playerVehicle(rdram, game, 0);
|
||||
ImGui::TextDisabled("Player 1: health %.0f of %.0f, energy %d of %d", flt(rdram, car + kHealth), flt(rdram, car + kHealthMax),
|
||||
static_cast<int32_t>(word(rdram, car + kEnergy)), static_cast<int32_t>(word(rdram, car + kEnergyMax)));
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
void setTheGame(uint32_t game) { g_theGame.store(game, std::memory_order_relaxed); }
|
||||
|
||||
// Once a frame (timerEndOfRealTimeProcessing, the frame's processing done).
|
||||
// TMB_LOG_PROGRESS=1 (finding the story's state): each word of Shell + 0x18000 + 0x2180 to + 0x2500 that changes,
|
||||
// with the time, from every frame end (the menus' too).
|
||||
void logProgress(uint8_t *rdram, uint32_t gp)
|
||||
{
|
||||
const uint32_t shell = word(rdram, gp - kGpShell);
|
||||
if (shell == 0u)
|
||||
return;
|
||||
// Story: start at a level. When a new story sets its first level (the Junkyard, nothing won yet), that level
|
||||
// is replaced, before the game loads it (it does once the character is chosen); the game's own chain goes on
|
||||
// from there.
|
||||
{
|
||||
const uint32_t progress = shell + kShellProgress;
|
||||
const int level = static_cast<int32_t>(word(rdram, progress + kStoryLevel));
|
||||
static int s_lastLevel = -2;
|
||||
const int start = g_storyStart.load(std::memory_order_relaxed);
|
||||
if (start >= 0 && level == 1 && s_lastLevel != 1 && word(rdram, progress + kGameMode) == 1u &&
|
||||
word(rdram, progress + kStoryLastWon) == 0u && start != 1)
|
||||
{
|
||||
setWord(rdram, progress + kStoryLevel, static_cast<uint32_t>(start));
|
||||
std::fprintf(stderr, "[tmb:cheats] story starts at level %s\n", kLevelNames[start]);
|
||||
}
|
||||
s_lastLevel = static_cast<int32_t>(word(rdram, progress + kStoryLevel));
|
||||
}
|
||||
static const bool s_on = std::getenv("TMB_LOG_PROGRESS") != nullptr;
|
||||
if (!s_on)
|
||||
return;
|
||||
static uint32_t s_last[0xE0] = {};
|
||||
static bool s_seen = false;
|
||||
static const auto s_start = std::chrono::steady_clock::now();
|
||||
const double t = std::chrono::duration<double>(std::chrono::steady_clock::now() - s_start).count();
|
||||
for (uint32_t i = 0; i < 0xE0u; ++i)
|
||||
{
|
||||
const uint32_t value = word(rdram, shell + kShellProgress + 0x2180u + i * 4u);
|
||||
if (s_seen && value != s_last[i])
|
||||
std::fprintf(stderr, "[tmb:progress] t=%.1f +0x%x: %d -> %d\n", t, 0x2180u + i * 4u, static_cast<int32_t>(s_last[i]),
|
||||
static_cast<int32_t>(value));
|
||||
s_last[i] = value;
|
||||
}
|
||||
s_seen = true;
|
||||
}
|
||||
|
||||
void onFrame(uint8_t *rdram)
|
||||
{
|
||||
g_rdram.store(rdram, std::memory_order_relaxed);
|
||||
const uint32_t game = g_theGame.load(std::memory_order_relaxed);
|
||||
if (game == 0u)
|
||||
return;
|
||||
// TMB_CHEATS_TOGGLE=<s> (testing): every cheat switched on and off every <s> seconds of match frames, as the
|
||||
// tab would (checks that each acts while playing, not only from launch).
|
||||
static const double s_toggle = []
|
||||
{
|
||||
const char *value = std::getenv("TMB_CHEATS_TOGGLE");
|
||||
return value && *value ? std::atof(value) : 0.0;
|
||||
}();
|
||||
if (s_toggle > 0.0 && !bozo::det::enabled()) // deterministic mode: nothing the user does may change the run
|
||||
{
|
||||
const double now = std::chrono::duration<double>(std::chrono::steady_clock::now().time_since_epoch()).count();
|
||||
static double s_next = now + s_toggle;
|
||||
static bool s_on = false;
|
||||
if (now >= s_next)
|
||||
{
|
||||
s_next = now + s_toggle;
|
||||
s_on = !s_on;
|
||||
const uint32_t all = s_on ? (1u << kMaxPlayers) - 1u : 0u;
|
||||
g_infiniteHealth.store(all);
|
||||
g_infiniteAmmo.store(all);
|
||||
g_infiniteEnergy.store(all);
|
||||
g_noAi.store(s_on);
|
||||
g_enemyCap.store(s_on ? 10.0f : -1.0f);
|
||||
std::fprintf(stderr, "[tmb:cheats] all cheats %s\n", s_on ? "on" : "off");
|
||||
}
|
||||
}
|
||||
const uint32_t health = g_infiniteHealth.load(std::memory_order_relaxed), energy = g_infiniteEnergy.load(std::memory_order_relaxed);
|
||||
const float playerCap = g_playerCap.load(std::memory_order_relaxed);
|
||||
const int players = playerCount(rdram, game);
|
||||
for (int player = 0; player < players; ++player)
|
||||
{
|
||||
const uint32_t car = playerVehicle(rdram, game, player);
|
||||
if (car == 0u)
|
||||
continue;
|
||||
const float most = flt(rdram, car + kHealthMax), now = flt(rdram, car + kHealth);
|
||||
// Topped up while alive (a car already dead is left to respawn).
|
||||
if ((health >> player & 1u) && most > 0.0f && now > 0.0f && now < most)
|
||||
setFlt(rdram, car + kHealth, most);
|
||||
if (energy >> player & 1u)
|
||||
setWord(rdram, car + kEnergy, word(rdram, car + kEnergyMax));
|
||||
if (player == 0 && playerCap >= 0.0f)
|
||||
{
|
||||
static uint32_t s_frames = 0;
|
||||
if (++s_frames % 250u == 0u)
|
||||
std::fprintf(stderr, "[tmb:health] %.1f of %.1f\n", now, most);
|
||||
if (now > playerCap)
|
||||
setFlt(rdram, car + kHealth, playerCap);
|
||||
}
|
||||
}
|
||||
const float enemyCap = g_enemyCap.load(std::memory_order_relaxed);
|
||||
if (enemyCap >= 0.0f)
|
||||
{
|
||||
const int32_t count = std::min(static_cast<int32_t>(word(rdram, game + kVehicleCount)), 64);
|
||||
static uint32_t s_enemyFrames = 0;
|
||||
const bool log = ++s_enemyFrames % 500u == 0u;
|
||||
std::string line;
|
||||
for (int32_t index = 0; index < count; ++index)
|
||||
{
|
||||
const uint32_t vehicle = game + kVehicles + static_cast<uint32_t>(index) * kVehicleStride;
|
||||
const float now = flt(rdram, vehicle + kHealth);
|
||||
if (log)
|
||||
{
|
||||
char text[48];
|
||||
std::snprintf(text, sizeof(text), " %x:%.0f", vehicle, now);
|
||||
line += text;
|
||||
}
|
||||
if (word(rdram, vehicle + kDriver) != 1u && now > enemyCap)
|
||||
setFlt(rdram, vehicle + kHealth, enemyCap);
|
||||
}
|
||||
if (log)
|
||||
std::fprintf(stderr, "[tmb:enemies] TheGame %x, %d vehicles:%s\n", game, count, line.c_str());
|
||||
}
|
||||
// TMB_CHEATS_LOG=1: every 250 frames, each player's health, energy and weapon counts (scripted checks).
|
||||
static const bool s_log = std::getenv("TMB_CHEATS_LOG") != nullptr;
|
||||
static uint32_t s_logFrames = 0;
|
||||
if (s_log && ++s_logFrames % 250u == 0u)
|
||||
{
|
||||
std::fprintf(stderr, "[tmb:cheats] weapon spends %u (%u not counted: infinite ammo)\n", g_decrements.exchange(0),
|
||||
g_decrementsSkipped.exchange(0));
|
||||
for (int player = 0; player < players; ++player)
|
||||
{
|
||||
const uint32_t car = playerVehicle(rdram, game, player);
|
||||
std::string counts;
|
||||
for (uint32_t slot = 1; slot <= 8; ++slot)
|
||||
counts += " " + std::to_string(static_cast<int32_t>(word(rdram, car + kWeaponCounts + slot * 4u)));
|
||||
std::fprintf(stderr, "[tmb:cheats] P%d car %x: health %.0f/%.0f, energy %d/%d, weapon %d, counts%s\n", player + 1, car,
|
||||
flt(rdram, car + kHealth), flt(rdram, car + kHealthMax), static_cast<int32_t>(word(rdram, car + kEnergy)),
|
||||
static_cast<int32_t>(word(rdram, car + kEnergyMax)), static_cast<int32_t>(word(rdram, car + 0x2140u)), counts.c_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void install(tmb::Registry &runtime)
|
||||
{
|
||||
g_noAi.store(std::getenv("TMB_NO_AI") && *std::getenv("TMB_NO_AI") == '1');
|
||||
g_unlockAll.store(std::getenv("TMB_UNLOCK_ALL") && *std::getenv("TMB_UNLOCK_ALL") == '1');
|
||||
if (const char *level = std::getenv("TMB_STORY_LEVEL"); level && *level)
|
||||
g_storyStart.store(std::clamp(std::atoi(level), -1, kLevelCount - 1));
|
||||
g_infiniteHealth.store(envMask("TMB_PLAYER_GOD"));
|
||||
g_infiniteAmmo.store(envMask("TMB_INFINITE_AMMO"));
|
||||
g_infiniteEnergy.store(envMask("TMB_INFINITE_ENERGY"));
|
||||
g_enemyCap.store(envFloat("TMB_ENEMY_HEALTH_CAP"));
|
||||
g_playerCap.store(envFloat("TMB_PLAYER_HEALTH_CAP"));
|
||||
runtime.registerFunction(kAiUpdateInputs, &aiUpdateInputsOverride);
|
||||
runtime.registerFunction(kDecrementWeaponCount, &decrementWeaponCountOverride);
|
||||
runtime.registerFunction(kUiLvlSel, &shellScreenOverride<&uiLvlSel__Fv_0x1976b0>);
|
||||
runtime.registerFunction(kUiCarSel, &shellScreenOverride<&uiCarSel__Fv_0x1963b0>);
|
||||
runtime.registerFunction(kUiAiSel, &shellScreenOverride<&uiAiSel__Fv_0x1986a8>);
|
||||
runtime.registerFunction(kUiMovies, &shellScreenOverride<&uiMovies__Fv_0x190760>);
|
||||
#if defined(BOZO_SETTINGS_UI)
|
||||
bozo::app::ui::registerTab("Cheats", &drawTab);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
#include "tmb_host.h"
|
||||
|
||||
#include <cstdlib>
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
|
||||
#if defined(_WIN32)
|
||||
#ifndef NOMINMAX
|
||||
@@ -190,4 +192,26 @@ namespace tmb::host
|
||||
setenv(name, value, 0);
|
||||
}
|
||||
#endif
|
||||
|
||||
namespace
|
||||
{
|
||||
std::string g_elfDirectory;
|
||||
}
|
||||
|
||||
std::string executableDirectory()
|
||||
{
|
||||
#if defined(_WIN32)
|
||||
wchar_t path[MAX_PATH];
|
||||
const DWORD n = GetModuleFileNameW(nullptr, path, MAX_PATH);
|
||||
if (n == 0 || n >= MAX_PATH)
|
||||
return {};
|
||||
return std::filesystem::path(std::wstring(path, n)).parent_path().string();
|
||||
#else
|
||||
std::error_code ec;
|
||||
return std::filesystem::read_symlink("/proc/self/exe", ec).parent_path().string();
|
||||
#endif
|
||||
}
|
||||
|
||||
std::string elfDirectory() { return g_elfDirectory; }
|
||||
void setElfDirectory(const std::string &folder) { g_elfDirectory = folder; }
|
||||
}
|
||||
+7
-2
@@ -1,5 +1,4 @@
|
||||
// Host OS services the TMB overrides need (thread CPU times, environment), for Linux and Windows. Compiled
|
||||
// outside the unity build: <windows.h> clashes with raylib names.
|
||||
// Host OS services the TMB overrides need (thread CPU times, environment, folders), for Linux and Windows.
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
@@ -26,4 +25,10 @@ namespace tmb::host
|
||||
|
||||
// setenv(name, value, 0): sets the variable unless it is already set.
|
||||
void setEnvDefault(const char *name, const char *value);
|
||||
|
||||
// The folder this executable is in, and the game's ELF's (set by the executable's main: the packs may sit beside
|
||||
// either).
|
||||
std::string executableDirectory();
|
||||
std::string elfDirectory();
|
||||
void setElfDirectory(const std::string &folder);
|
||||
}
|
||||
+49
-52
@@ -56,17 +56,14 @@
|
||||
// order and the adapter reports, per object, the stream's order and GS state against them ([tmb:order]), besides its
|
||||
// VU 0-21, matrix and strips against its own translation.
|
||||
|
||||
#include "game_overrides.h"
|
||||
#include "ps2_runtime.h"
|
||||
#include "ps2_recompiled_functions.h"
|
||||
#include "tmb_port.h"
|
||||
#include "tmb_host.h"
|
||||
#include "tmb_meshes.h"
|
||||
#include "tmb_vu1_shading.h"
|
||||
#include "runtime/native/native_mesh_draw.h"
|
||||
#include "runtime/native/native_mesh_pack.h"
|
||||
#include "runtime/native/native_renderer.h"
|
||||
#include "runtime/native/native_texture_cache.h"
|
||||
#include "runtime/ps2_memory.h"
|
||||
#include "ps2_app.h"
|
||||
#include "bozo/render/mesh_draw.h"
|
||||
#include "bozo/render/mesh_pack.h"
|
||||
#include "bozo/render/renderer.h"
|
||||
#include "bozo/render/texture.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
@@ -89,8 +86,8 @@
|
||||
|
||||
namespace tmb::textures
|
||||
{
|
||||
std::shared_ptr<const ps2x::native::TextureCache::Texture> lookupId(uint32_t id, uint64_t tex0, uint64_t texa);
|
||||
std::shared_ptr<const ps2x::native::TextureCache::Texture> lookup(uint64_t tex0, uint64_t texa);
|
||||
std::shared_ptr<const bozo::render::Texture> lookupId(uint32_t id, uint64_t tex0, uint64_t texa);
|
||||
std::shared_ptr<const bozo::render::Texture> lookup(uint64_t tex0, uint64_t texa);
|
||||
uint32_t idAtTbp(uint32_t tbp);
|
||||
std::string nameAt(uint32_t address);
|
||||
}
|
||||
@@ -143,13 +140,13 @@ namespace tmb::meshes
|
||||
// pool it uses); the sections the morph deltas (kAux), where each pool's positions are in the image (kSources),
|
||||
// the environment map's parameter batches (kParams) and a skinned object's bones and weights (kSkin); the
|
||||
// file's register blocks the hier traversal's GS context blocks (ALPHA_1, TEST_1, ZBUF_1 writes).
|
||||
using ps2x::native::packs::MeshFile;
|
||||
using ps2x::native::packs::MeshObject;
|
||||
using ps2x::native::packs::MeshSection;
|
||||
constexpr uint32_t kAux = ps2x::native::packs::fourcc("AUX ");
|
||||
constexpr uint32_t kSources = ps2x::native::packs::fourcc("SRCS");
|
||||
constexpr uint32_t kParams = ps2x::native::packs::fourcc("PRMS");
|
||||
constexpr uint32_t kSkin = ps2x::native::packs::fourcc("SKIN");
|
||||
using bozo::render::packs::MeshFile;
|
||||
using bozo::render::packs::MeshObject;
|
||||
using bozo::render::packs::MeshSection;
|
||||
constexpr uint32_t kAux = bozo::render::packs::fourcc("AUX ");
|
||||
constexpr uint32_t kSources = bozo::render::packs::fourcc("SRCS");
|
||||
constexpr uint32_t kParams = bozo::render::packs::fourcc("PRMS");
|
||||
constexpr uint32_t kSkin = bozo::render::packs::fourcc("SKIN");
|
||||
constexpr uint32_t kAttributeSize = 40u;
|
||||
uint32_t poolFrom(const MeshObject &o)
|
||||
{
|
||||
@@ -165,9 +162,9 @@ namespace tmb::meshes
|
||||
return v;
|
||||
}
|
||||
|
||||
ps2x::native::packs::MeshPack &pack()
|
||||
bozo::render::packs::MeshPack &pack()
|
||||
{
|
||||
static ps2x::native::packs::MeshPack s_pack;
|
||||
static bozo::render::packs::MeshPack s_pack;
|
||||
static bool s_loaded = false;
|
||||
if (s_loaded)
|
||||
return s_pack;
|
||||
@@ -180,7 +177,7 @@ namespace tmb::meshes
|
||||
std::fprintf(stderr, "[tmb:mesh] no mesh pack at %s (tools/tmb_mesh_pack.py): objects stay on the stream path\n", path);
|
||||
else
|
||||
std::fprintf(stderr, "[tmb:mesh] %s: %s (%s: run tools/tmb_mesh_pack.py again)\n", path, s_pack.error().c_str(),
|
||||
ps2x::native::packs::MeshPack::kMagic);
|
||||
bozo::render::packs::MeshPack::kMagic);
|
||||
return s_pack;
|
||||
}
|
||||
std::fprintf(stderr, "[tmb:mesh] mesh pack %s: %zu files, %zu objects\n", path, s_pack.files().size(), s_pack.objectCount());
|
||||
@@ -189,13 +186,13 @@ namespace tmb::meshes
|
||||
|
||||
// ---- the NGP files as the game loaded them ----
|
||||
|
||||
ps2x::native::packs::LoadedImages g_loaded;
|
||||
bozo::render::packs::LoadedImages g_loaded;
|
||||
|
||||
void noteNgp(uint8_t *rdram, R5900Context *ctx, bool only)
|
||||
{
|
||||
const uint32_t base = getRegU32(ctx, 4), size = getRegU32(ctx, 5);
|
||||
const std::string name = tmb::textures::nameAt(base);
|
||||
const ps2x::native::packs::LoadedImages::Bound bound = g_loaded.bind(pack(), rdram, name, base, size, only);
|
||||
const bozo::render::packs::LoadedImages::Bound bound = g_loaded.bind(pack(), rdram, name, base, size, only);
|
||||
if (bound.named && !bound.image.file)
|
||||
std::fprintf(stderr, "[tmb:mesh] %s at %#x: %u bytes (crc %#x), the pack's is %u bytes (crc %#x): not used\n", name.c_str(), base, size,
|
||||
bound.crc, bound.named->size, bound.named->crc);
|
||||
@@ -286,7 +283,7 @@ namespace tmb::meshes
|
||||
contextsDiffering = 0, skid = 0;
|
||||
} g_stats;
|
||||
|
||||
void vf(const R5900Context *ctx, int reg, float out[4]) { _mm_storeu_ps(out, ctx->vu0_vf[reg]); }
|
||||
void vf(const R5900Context *ctx, int reg, float out[4]) { std::memcpy(out, ctx->vu0_vf[reg].f, 16); }
|
||||
|
||||
// ---- the game's order ----
|
||||
//
|
||||
@@ -309,7 +306,7 @@ namespace tmb::meshes
|
||||
uint64_t g_listDrops = 0, g_submitted[2] = {}, g_built[2] = {}, g_kicks[2] = {};
|
||||
// The vertex arrays of the objects drawn last, kept (cleared) for the next objects' batches: each one grew from
|
||||
// nothing every frame, a few hundred objects' worth of allocations and copies (the game thread only).
|
||||
std::vector<std::vector<ps2x::native::Vertex>> g_vertexPool;
|
||||
std::vector<std::vector<bozo::render::Vertex>> g_vertexPool;
|
||||
|
||||
void recycleVertices(Drawn &drawn)
|
||||
{
|
||||
@@ -321,16 +318,16 @@ namespace tmb::meshes
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<ps2x::native::Vertex> pooledVertices()
|
||||
std::vector<bozo::render::Vertex> pooledVertices()
|
||||
{
|
||||
if (g_vertexPool.empty())
|
||||
return {};
|
||||
std::vector<ps2x::native::Vertex> vertices = std::move(g_vertexPool.back());
|
||||
std::vector<bozo::render::Vertex> vertices = std::move(g_vertexPool.back());
|
||||
g_vertexPool.pop_back();
|
||||
return vertices;
|
||||
}
|
||||
|
||||
struct ViewList : ps2x::native::MeshViewList<Drawn>
|
||||
struct ViewList : bozo::render::MeshViewList<Drawn>
|
||||
{
|
||||
// Built by hier2p: sent only by hier2pFlushDma. On the frame a split screen ends hier2p builds its view once
|
||||
// more and nothing sends it (the game drops the chain), so it is dropped too rather than drawn in the next view.
|
||||
@@ -353,8 +350,8 @@ namespace tmb::meshes
|
||||
// The GS registers the hier objects' draws depend on, as their context and register blocks leave them in the
|
||||
// order the objects are sent (they persist from one object to the next, as in the GS): the submitter's
|
||||
// (runtime/native/native_mesh_draw.h), which follows them, makes each batch's material and clips its triangles.
|
||||
using GsState = ps2x::native::MeshGsState;
|
||||
ps2x::native::MeshSubmitter g_submitter;
|
||||
using GsState = bozo::render::MeshGsState;
|
||||
bozo::render::MeshSubmitter g_submitter;
|
||||
|
||||
// A batch's material as the GS state has it (TMB_NATIVE_MESHES_CHECK compares it with the stream's).
|
||||
struct Mat
|
||||
@@ -395,7 +392,7 @@ namespace tmb::meshes
|
||||
// TMB_LIVE_TOGGLES=<file> (a diagnostic): words read from the file every 60 frames, while the game runs:
|
||||
// nodepth (the hier objects drawn without the depth test), nofog, noclip (no view clip), flat (each object
|
||||
// untextured in a colour of its own), opaque, noatest, notex, noguard (no clip volume), dump.
|
||||
ps2x::native::MeshLiveToggles &g_live = g_submitter.live;
|
||||
bozo::render::MeshLiveToggles &g_live = g_submitter.live;
|
||||
void readLiveToggles()
|
||||
{
|
||||
static const char *s_path = std::getenv("TMB_LIVE_TOGGLES");
|
||||
@@ -405,10 +402,10 @@ namespace tmb::meshes
|
||||
}
|
||||
|
||||
// TMB_NATIVE_MESHES_CHECK=1: what the submitter applies, per marked object, recorded for compareOrders.
|
||||
struct CheckObserver : ps2x::native::MeshSubmitter::Observer
|
||||
struct CheckObserver : bozo::render::MeshSubmitter::Observer
|
||||
{
|
||||
CheckRecord *record = nullptr;
|
||||
void draw(const ps2x::native::MeshDraw &d) override
|
||||
void draw(const bozo::render::MeshDraw &d) override
|
||||
{
|
||||
const Drawn &drawn = static_cast<const Drawn &>(d);
|
||||
record = nullptr;
|
||||
@@ -467,7 +464,7 @@ namespace tmb::meshes
|
||||
{
|
||||
const MeshFile *file = nullptr;
|
||||
uint32_t base = 0;
|
||||
g_loaded.forEach([&](const ps2x::native::packs::LoadedImages::Image &l)
|
||||
g_loaded.forEach([&](const bozo::render::packs::LoadedImages::Image &l)
|
||||
{
|
||||
if (at >= l.base && at < l.base + l.size)
|
||||
{
|
||||
@@ -488,7 +485,7 @@ namespace tmb::meshes
|
||||
++g_stats.contextsDefault;
|
||||
return readContext(ee, at, out);
|
||||
}
|
||||
const ps2x::native::packs::RegisterBlock *block = file->block(at - base);
|
||||
const bozo::render::packs::RegisterBlock *block = file->block(at - base);
|
||||
if (!block)
|
||||
{
|
||||
++g_stats.contextsMissing;
|
||||
@@ -666,8 +663,8 @@ namespace tmb::meshes
|
||||
bool textured = false;
|
||||
uint32_t texnum = ~0u;
|
||||
Batch *batch = nullptr;
|
||||
static thread_local std::vector<ps2x::native::Vertex> s_strip; // kept from call to call (its capacity)
|
||||
std::vector<ps2x::native::Vertex> &strip = s_strip;
|
||||
static thread_local std::vector<bozo::render::Vertex> s_strip; // kept from call to call (its capacity)
|
||||
std::vector<bozo::render::Vertex> &strip = s_strip;
|
||||
strip.clear();
|
||||
static const bool s_check = std::getenv("TMB_NATIVE_MESHES_CHECK") != nullptr;
|
||||
for (uint32_t si = 0; si < strips; ++si)
|
||||
@@ -743,7 +740,7 @@ namespace tmb::meshes
|
||||
{
|
||||
// One sprite (one point, one colour, four corners' texture coordinates) or one ribbon segment (two
|
||||
// points, four colours and texture coordinates): the converter checked the shapes.
|
||||
std::vector<ps2x::native::Vertex> &triangles = batch->vertices;
|
||||
std::vector<bozo::render::Vertex> &triangles = batch->vertices;
|
||||
const size_t from = triangles.size();
|
||||
const auto vertexAt = [&](uint32_t v) { return vertices + v * 16u; };
|
||||
const auto pointOf = [&](uint32_t v, float out4[4])
|
||||
@@ -769,7 +766,7 @@ namespace tmb::meshes
|
||||
st[v][0] = pair[0];
|
||||
st[v][1] = pair[1];
|
||||
}
|
||||
ps2x::native::Vertex quad[4];
|
||||
bozo::render::Vertex quad[4];
|
||||
static const int kOrder[6] = {0, 1, 2, 1, 2, 3};
|
||||
if (tmb::vu1::spriteQuad(g_vu, m, point, rgba, st, quad))
|
||||
for (int i : kOrder)
|
||||
@@ -805,7 +802,7 @@ namespace tmb::meshes
|
||||
words[2] = words[3] = 0x1000u;
|
||||
}
|
||||
};
|
||||
tmb::vu1::ribbonStrip<ps2x::native::Vertex>(g_vu, m, read, triangles);
|
||||
tmb::vu1::ribbonStrip<bozo::render::Vertex>(g_vu, m, read, triangles);
|
||||
}
|
||||
if (s_check)
|
||||
out.checkStrips.emplace_back(triangles.begin() + static_cast<std::ptrdiff_t>(from), triangles.end());
|
||||
@@ -821,7 +818,7 @@ namespace tmb::meshes
|
||||
const uint8_t *vx = vertices + v * 16u;
|
||||
uint16_t index;
|
||||
std::memcpy(&index, vx, 2);
|
||||
ps2x::native::Vertex outV;
|
||||
bozo::render::Vertex outV;
|
||||
if (index >= positionCount)
|
||||
{
|
||||
outV.rgba = 0xdeadu;
|
||||
@@ -856,7 +853,7 @@ namespace tmb::meshes
|
||||
const uint8_t *vx = vertices + v * 16u;
|
||||
uint16_t index;
|
||||
std::memcpy(&index, vx, 2);
|
||||
ps2x::native::Vertex outV;
|
||||
bozo::render::Vertex outV;
|
||||
if (index >= positionCount)
|
||||
{
|
||||
outV.rgba = 0xdeadu;
|
||||
@@ -896,7 +893,7 @@ namespace tmb::meshes
|
||||
const uint8_t *vx = vertices + v * 16u;
|
||||
uint16_t index;
|
||||
std::memcpy(&index, vx, 2);
|
||||
ps2x::native::Vertex outV;
|
||||
bozo::render::Vertex outV;
|
||||
if (index >= positionCount)
|
||||
{
|
||||
outV.rgba = 0xdeadu; // a break: no triangle uses it
|
||||
@@ -1049,7 +1046,7 @@ namespace tmb::meshes
|
||||
{
|
||||
if (active() && hookOrder())
|
||||
{
|
||||
const Ee ee{rdram, runtime->memory().getScratchpad()};
|
||||
const Ee ee{rdram, bozo::port::scratchpad(runtime)};
|
||||
skidSnapshot(ee, getRegU32(ctx, 4));
|
||||
}
|
||||
draw__9SkidMarks_0x169490(rdram, ctx, runtime);
|
||||
@@ -1088,7 +1085,7 @@ namespace tmb::meshes
|
||||
return;
|
||||
++g_stats.calls;
|
||||
g_rdramForDump = rdram;
|
||||
const Ee ee{rdram, runtime->memory().getScratchpad()};
|
||||
const Ee ee{rdram, bozo::port::scratchpad(runtime)};
|
||||
const uint32_t fp = ee.u16(obj + 0xcu); // lh $fp, 0xC($s5): the flags' bits 32-47
|
||||
// TMB_NATIVE_MESHES_DUMP: the objects of the kinds other than the rigid strips, once each (a skinned one with
|
||||
// its per-instance chain and bones), for the offline comparison with the dump.
|
||||
@@ -1263,7 +1260,7 @@ namespace tmb::meshes
|
||||
// submitDrawn takes. Drawn here as the others.
|
||||
++g_stats.extra;
|
||||
}
|
||||
ps2x::native::packs::LoadedImages::Image file;
|
||||
bozo::render::packs::LoadedImages::Image file;
|
||||
const bool inFile = g_loaded.find(obj, file);
|
||||
// The skid marks' object (skidBuffer, which SkidMarks::draw fills): drawn from the marks themselves.
|
||||
const bool skid = obj == kSkidBuffer && g_skid.valid && !resume;
|
||||
@@ -1481,7 +1478,7 @@ namespace tmb::meshes
|
||||
g_previous.valid = false;
|
||||
if (static const bool s_dumpLog = std::getenv("TMB_NATIVE_MESHES_DUMP") != nullptr; s_dumpLog)
|
||||
{
|
||||
const Ee ee{rdram, runtime->memory().getScratchpad()};
|
||||
const Ee ee{rdram, bozo::port::scratchpad(runtime)};
|
||||
const uint32_t obj = getRegU32(ctx, 6), inst = ee.u32(0x70000020u);
|
||||
static std::unordered_map<uint32_t, bool> s_seen;
|
||||
if (!s_seen[obj])
|
||||
@@ -1511,7 +1508,7 @@ namespace tmb::meshes
|
||||
vf(ctx, 30, depth);
|
||||
int32_t bucket = 1;
|
||||
if (depth[0] > 8.0f)
|
||||
bucket = FPU_CVT_W_S((depth[0] > 1024.0f ? 1016.0f : depth[0]) * 0.125f) + 1;
|
||||
bucket = tmb::cvtWS((depth[0] > 1024.0f ? 1016.0f : depth[0]) * 0.125f) + 1;
|
||||
list.link(std::clamp(bucket, 0, 128));
|
||||
}
|
||||
}
|
||||
@@ -1529,7 +1526,7 @@ namespace tmb::meshes
|
||||
}
|
||||
tmb::native::applyViewClip();
|
||||
if (g_live.noClip)
|
||||
ps2x::native::Renderer::instance().clearClip();
|
||||
bozo::render::Renderer::instance().clearClip();
|
||||
g_submitIndex = 0;
|
||||
const int which = g_inHier2pFlush ? 1 : 0; // hier__Fi's, hier2p's
|
||||
++g_kicks[which];
|
||||
@@ -1581,7 +1578,7 @@ namespace tmb::meshes
|
||||
hierCacheForAsm_0x2020e4(rdram, ctx, runtime);
|
||||
if (!active())
|
||||
return;
|
||||
const Ee ee{rdram, runtime->memory().getScratchpad()};
|
||||
const Ee ee{rdram, bozo::port::scratchpad(runtime)};
|
||||
for (uint32_t q = 0; q < 3u; ++q)
|
||||
std::memcpy(g_lastLights[q], ee.at(kConstVu5 + 16u + q * 16u), 16);
|
||||
g_previous.valid = false;
|
||||
@@ -1605,7 +1602,7 @@ namespace tmb::meshes
|
||||
return builtIn;
|
||||
// A copy of the runner with its data (the pack beside the game's files, or beside the runner).
|
||||
const std::filesystem::path name = std::filesystem::path(builtIn).filename();
|
||||
for (const std::filesystem::path &dir : {PS2Runtime::getIoPaths().elfDirectory, ps2x::app::executableDirectory()})
|
||||
for (const std::filesystem::path &dir : {std::filesystem::path(tmb::host::elfDirectory()), std::filesystem::path(tmb::host::executableDirectory())})
|
||||
if (!dir.empty() && std::filesystem::exists(dir / name, ec))
|
||||
return (dir / name).string();
|
||||
return builtIn;
|
||||
@@ -1810,7 +1807,7 @@ namespace tmb::meshes
|
||||
}
|
||||
}
|
||||
|
||||
void install(PS2Runtime &runtime)
|
||||
void install(tmb::Registry &runtime)
|
||||
{
|
||||
if (!active())
|
||||
return;
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
// adapter (runtime/tmb_native.cpp) at their place in the frame.
|
||||
#pragma once
|
||||
|
||||
#include "ps2_runtime.h"
|
||||
#include "runtime/native/native_mesh_draw.h"
|
||||
#include "runtime/native/native_renderer.h"
|
||||
#include "runtime/native/native_texture_cache.h"
|
||||
#include "tmb_port.h"
|
||||
#include "bozo/render/mesh_draw.h"
|
||||
#include "bozo/render/renderer.h"
|
||||
#include "bozo/render/texture.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
@@ -17,11 +17,11 @@ namespace tmb::meshes
|
||||
// One batch of an object (the fork's, runtime/native/native_mesh_draw.h): its material as the strip program keeps
|
||||
// it (the GS state around it, ALPHA_1, TEST_1, ZBUF_1, FOGCOL, is the adapter's at the object's place) and its
|
||||
// triangles in the object's space.
|
||||
using Batch = ps2x::native::MeshBatch;
|
||||
using Batch = bozo::render::MeshBatch;
|
||||
|
||||
// One object drawn from the pack, waiting for its place in the stream: the fork's MeshDraw (matrix, clip volume,
|
||||
// batches, context block, key) and what TMB's checks and the stream path add.
|
||||
struct Drawn : ps2x::native::MeshDraw
|
||||
struct Drawn : bozo::render::MeshDraw
|
||||
{
|
||||
uint32_t setupPc = 0;
|
||||
uint32_t resumes = 0; // a resume (setupPc 0xc78): the setup it goes on with, which the stream's must be
|
||||
@@ -31,7 +31,7 @@ namespace tmb::meshes
|
||||
bool alphaList = false; // sent through the depth-sorted alpha list (pktLinkAlphaObjAsm), after the view's opaque ones
|
||||
// TMB_NATIVE_MESHES_CHECK: each strip's vertices before triangles (sprites and ribbons: its triangles; the
|
||||
// adapter compares its own translation).
|
||||
std::vector<std::vector<ps2x::native::Vertex>> checkStrips;
|
||||
std::vector<std::vector<bozo::render::Vertex>> checkStrips;
|
||||
};
|
||||
|
||||
// Where a pack is (the mesh pack, the texture pack): the environment's <envName>, else the path built in when it
|
||||
@@ -54,5 +54,5 @@ namespace tmb::meshes
|
||||
void flushUnsent();
|
||||
// A published frame's end.
|
||||
void endFrame();
|
||||
void install(PS2Runtime &runtime);
|
||||
void install(tmb::Registry &runtime);
|
||||
}
|
||||
+76
-3315
File diff suppressed because it is too large.
Load diff
+168
-769
File diff suppressed because it is too large.
Load diff
+37
-26
@@ -48,12 +48,9 @@
|
||||
// TMB_NATIVE_PARTICLES_CHECK=1 (a diagnostic): nothing drawn here; types 1, 4, 6 (not on a sphere), 7 and 8 computed and
|
||||
// compared with what runtime/tmb_native.cpp's translations draw from the same systems' packets.
|
||||
|
||||
#include "game_overrides.h"
|
||||
#include "ps2_runtime.h"
|
||||
#include "ps2_recompiled_functions.h"
|
||||
#include "ps2_runtime_macros.h"
|
||||
#include "runtime/native/native_renderer.h"
|
||||
#include "runtime/native/native_texture_cache.h"
|
||||
#include "tmb_port.h"
|
||||
#include "bozo/render/renderer.h"
|
||||
#include "bozo/render/texture.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
@@ -78,16 +75,16 @@ namespace tmb::native
|
||||
|
||||
namespace tmb::textures
|
||||
{
|
||||
std::shared_ptr<const ps2x::native::TextureCache::Texture> lookupId(uint32_t id, uint64_t tex0, uint64_t texa);
|
||||
std::shared_ptr<const bozo::render::Texture> lookupId(uint32_t id, uint64_t tex0, uint64_t texa);
|
||||
}
|
||||
|
||||
namespace tmb::particles
|
||||
{
|
||||
namespace
|
||||
{
|
||||
using ps2x::native::Material;
|
||||
using ps2x::native::Vertex;
|
||||
using TexturePtr = std::shared_ptr<const ps2x::native::TextureCache::Texture>;
|
||||
using bozo::render::Material;
|
||||
using bozo::render::Vertex;
|
||||
using TexturePtr = std::shared_ptr<const bozo::render::Texture>;
|
||||
|
||||
constexpr bool kRegionSupported = true;
|
||||
constexpr float kScreenTop = 2048.0f - 112.0f; // the field's top line (640 x 224)
|
||||
@@ -116,7 +113,14 @@ namespace tmb::particles
|
||||
kGpRainStep = -0x474c, kGpRainMul = -0x4740;
|
||||
constexpr int32_t kGpKite = -0x47d0; // kitePacketInit's three constants (alpha factor, origin y, factor step)
|
||||
constexpr int32_t kGpSprine = -0x47c4; // sprinePacketInit's
|
||||
void gameParticleDraw(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) { particleDraw__Fi_0x1e9540(rdram, ctx, runtime); }
|
||||
// From its start, or (ctx->pc inside it: the chain loop or its tail) from there, through its resume entry.
|
||||
void gameParticleDraw(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
|
||||
{
|
||||
if (ctx->pc != kParticleDraw)
|
||||
resume_0x1e9540(rdram, ctx, runtime);
|
||||
else
|
||||
particleDraw__Fi_0x1e9540(rdram, ctx, runtime);
|
||||
}
|
||||
void gameTexSpriteBuild(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
|
||||
{
|
||||
texSpritePacketBuild__FP13_ParticleType_0x1e12d8(rdram, ctx, runtime);
|
||||
@@ -275,10 +279,11 @@ namespace tmb::particles
|
||||
void putF(uint8_t *rdram, uint32_t address, float value) { std::memcpy(rdram + (address & 0x1fffffcu), &value, 4); }
|
||||
void put8(uint8_t *rdram, uint32_t address, uint8_t value) { rdram[address & 0x1ffffffu] = value; }
|
||||
|
||||
uint64_t reg64(const R5900Context *ctx, int reg) { return reg == 0 ? 0u : static_cast<uint64_t>(_mm_cvtsi128_si64(ctx->r[reg])); }
|
||||
uint64_t reg64(const R5900Context *ctx, int reg) { return reg == 0 ? 0u : ctx->r[reg].ud[0]; }
|
||||
void setReg(R5900Context *ctx, int reg, uint32_t value)
|
||||
{
|
||||
ctx->r[reg] = _mm_set_epi64x(0, static_cast<int64_t>(static_cast<int32_t>(value)));
|
||||
ctx->r[reg].sd[0] = static_cast<int64_t>(static_cast<int32_t>(value));
|
||||
ctx->r[reg].ud[1] = 0;
|
||||
}
|
||||
|
||||
bool typeNative(uint32_t type) { return type < 32u && ((settings().types >> type) & 1u) != 0u; }
|
||||
@@ -383,7 +388,7 @@ namespace tmb::particles
|
||||
// its place in the system's arrays (0 when the window is not interpolating: nothing kept).
|
||||
uint64_t particleId(uint32_t ps, uint32_t index)
|
||||
{
|
||||
if (!ps2x::native::Renderer::instance().interpolating())
|
||||
if (!bozo::render::Renderer::instance().interpolating())
|
||||
return 0u;
|
||||
return ((static_cast<uint64_t>(g_view) + 1u) << 52) ^ (static_cast<uint64_t>(ps) << 16) ^ (index + 1u);
|
||||
}
|
||||
@@ -397,11 +402,11 @@ namespace tmb::particles
|
||||
else if (batch.open && !batch.triangles.empty() && !batch.ids.empty())
|
||||
{
|
||||
batch.ids.resize(batch.triangles.size() / 3u, 0u);
|
||||
ps2x::native::Renderer::instance().drawTracked(batch.material, batch.triangles.data(),
|
||||
bozo::render::Renderer::instance().drawTracked(batch.material, batch.triangles.data(),
|
||||
static_cast<uint32_t>(batch.triangles.size()), batch.texture, batch.ids.data());
|
||||
}
|
||||
else if (batch.open && !batch.triangles.empty())
|
||||
ps2x::native::Renderer::instance().draw(batch.material, kScreenSpace, batch.triangles.data(),
|
||||
bozo::render::Renderer::instance().draw(batch.material, kScreenSpace, batch.triangles.data(),
|
||||
static_cast<uint32_t>(batch.triangles.size()), batch.texture);
|
||||
batch.triangles.clear();
|
||||
batch.ids.clear();
|
||||
@@ -1848,12 +1853,18 @@ namespace tmb::particles
|
||||
// The game's float arithmetic for the flares' (the checks compare them bit for bit): the FPU's (add.s ...
|
||||
// truncated, a zero divisor giving the largest float) and VU0's (macro mode: the host's rounding), each
|
||||
// operation on its own (no fused multiply-add).
|
||||
float fpuAdd(float a, float b) { return ps2_fadd(a, b); }
|
||||
float fpuSub(float a, float b) { return ps2_fsub(a, b); }
|
||||
float fpuMul(float a, float b) { return ps2_fmul(a, b); }
|
||||
float fpuDiv(float a, float b) { return ps2_fdiv(a, b); }
|
||||
float vuAdd(float a, float b) { return _mm_cvtss_f32(ps2_vadd(_mm_set_ss(a), _mm_set_ss(b))); }
|
||||
float vuMul(float a, float b) { return _mm_cvtss_f32(ps2_vmul(_mm_set_ss(a), _mm_set_ss(b))); }
|
||||
// (BozoEngine's PS2 float arithmetic: bozo/ops_fpu.h, the FPU's; bozo/ops_vu0.h, VU0's.)
|
||||
float fpuOp(uint32_t (*op)(uint32_t, uint32_t, uint32_t &), float a, float b)
|
||||
{
|
||||
uint32_t flags = 0;
|
||||
return ps2Float(op(ps2Bits(a), ps2Bits(b), flags));
|
||||
}
|
||||
float fpuAdd(float a, float b) { return fpuOp(&bozo::ps2f::add, a, b); }
|
||||
float fpuSub(float a, float b) { return fpuOp(&bozo::ps2f::sub, a, b); }
|
||||
float fpuMul(float a, float b) { return fpuOp(&bozo::ps2f::mul, a, b); }
|
||||
float fpuDiv(float a, float b) { return fpuOp(&bozo::ps2f::div, a, b); }
|
||||
float vuAdd(float a, float b) { return fpuOp(&bozo::vu0::addf, a, b); }
|
||||
float vuMul(float a, float b) { return fpuOp(&bozo::vu0::mulf, a, b); }
|
||||
|
||||
// particleLensFlareTestZbuffer(view): each light through mathfTransform3dTo2d (its position plus the view's
|
||||
// viewGetWeTrans, times viewGetWorldToScreenMat's rows, over w); the ones inside the view (viewGetCenter -+
|
||||
@@ -2375,7 +2386,7 @@ namespace tmb::particles
|
||||
if (count > 0)
|
||||
{
|
||||
lensFlareVisibility(rdram, list, count, view);
|
||||
ps2x::native::Renderer &renderer = ps2x::native::Renderer::instance();
|
||||
bozo::render::Renderer &renderer = bozo::render::Renderer::instance();
|
||||
renderer.beginGroup(tmb::native::nextStreamGroup());
|
||||
renderer.setKey(0);
|
||||
drawLensFlares(rdram, list, count, view);
|
||||
@@ -2468,7 +2479,7 @@ namespace tmb::particles
|
||||
for (int k = 0; k < 4; ++k)
|
||||
constants.vu[j][k] = f32(rdram, kEffectsVu + 16u * j + 4u * k);
|
||||
constants.fog = fogColour(rdram);
|
||||
ps2x::native::Renderer &renderer = ps2x::native::Renderer::instance();
|
||||
bozo::render::Renderer &renderer = bozo::render::Renderer::instance();
|
||||
bool drewNative = false;
|
||||
std::vector<Sorted> left;
|
||||
left.reserve(sorted.size());
|
||||
@@ -2595,13 +2606,13 @@ namespace tmb::particles
|
||||
|
||||
bool checking() { return settings().on && settings().check; }
|
||||
|
||||
void compare(uint32_t pc, const ps2x::native::Vertex *vertices, size_t count)
|
||||
void compare(uint32_t pc, const bozo::render::Vertex *vertices, size_t count)
|
||||
{
|
||||
if (checking())
|
||||
compareCaptured(pc, vertices, count);
|
||||
}
|
||||
|
||||
void install(PS2Runtime &runtime)
|
||||
void install(tmb::Registry &runtime)
|
||||
{
|
||||
if (!settings().on || !tmb::native::enabled())
|
||||
return;
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
// TMB's runtime on BozoEngine (phase 4): what every runtime file includes. The context helpers (getRegU32,
|
||||
// setReturnS32, SET_GPR_U32...), the generated functions by name (tmb_functions.h, made by bozo-recomp from the ELF
|
||||
// with TMB's externals), and the port API (bozo/port.h: registration, the kernel, the EE clock, the frame end).
|
||||
//
|
||||
// The names the fork gave these keep working where it was cheap: an override's third argument is still spelled
|
||||
// PS2Runtime (BozoEngine's opaque Runtime), and the install functions take the registry as `runtime`, so their
|
||||
// runtime.registerFunction(...) lines are unchanged.
|
||||
#pragma once
|
||||
|
||||
#include "bozo/context.h"
|
||||
#include "bozo/port.h"
|
||||
#include "bozo/recomp.h"
|
||||
#include "tmb_functions.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
|
||||
using PS2Runtime = Runtime;
|
||||
|
||||
namespace tmb
|
||||
{
|
||||
using Registry = bozo::port::Registry;
|
||||
|
||||
// The disc image that boots this executable: TMB_ISO, else an .iso found walking up from the folder given (the
|
||||
// ELF's or the executable's) whose SYSTEM.CNF names `elfName` (runtime/tmb_overrides.cpp).
|
||||
std::string findDiscImage(const std::string &fromFolder, const std::string &elfName);
|
||||
|
||||
// CVT.W.S as the R5900 makes it: toward zero, saturating at the int32 range (the fork's FPU_CVT_W_S).
|
||||
inline int32_t cvtWS(float v)
|
||||
{
|
||||
if (v >= 2147483648.0f)
|
||||
return INT32_MAX;
|
||||
if (v <= -2147483648.0f)
|
||||
return INT32_MIN;
|
||||
return static_cast<int32_t>(v);
|
||||
}
|
||||
}
|
||||
|
||||
// FPU helpers the particles use (the fork's ps2_runtime_macros.h names), on BozoEngine's PS2 float semantics.
|
||||
inline float ps2Float(uint32_t bits)
|
||||
{
|
||||
float f;
|
||||
__builtin_memcpy(&f, &bits, 4);
|
||||
return f;
|
||||
}
|
||||
inline uint32_t ps2Bits(float f)
|
||||
{
|
||||
uint32_t b;
|
||||
__builtin_memcpy(&b, &f, 4);
|
||||
return b;
|
||||
}
|
||||
+16
-18
@@ -16,11 +16,9 @@
|
||||
// The pack's container, its loader and the decoders (PSM, CSM1 palettes, TEXA alpha) are the fork's
|
||||
// (runtime/native/native_texture_pack.h, tools/native_pack/texture.py); what is TMB's here is the key scheme above.
|
||||
|
||||
#include "game_overrides.h"
|
||||
#include "ps2_runtime.h"
|
||||
#include "ps2_recompiled_functions.h"
|
||||
#include "runtime/native/native_texture_cache.h"
|
||||
#include "runtime/native/native_texture_pack.h"
|
||||
#include "tmb_port.h"
|
||||
#include "bozo/render/texture.h"
|
||||
#include "bozo/render/texture_pack.h"
|
||||
#include "tmb_meshes.h"
|
||||
|
||||
#include <algorithm>
|
||||
@@ -42,7 +40,7 @@ namespace tmb::textures
|
||||
{
|
||||
namespace
|
||||
{
|
||||
using Texture = ps2x::native::TextureCache::Texture;
|
||||
using Texture = bozo::render::Texture;
|
||||
|
||||
constexpr uint32_t kTexInfo = 0x004D1930u; // texInfo[1000], 16 bytes each
|
||||
constexpr uint32_t kFileReadf = 0x001C21D0u;
|
||||
@@ -59,9 +57,9 @@ namespace tmb::textures
|
||||
constexpr uint32_t kResLoadReturn = 0x001F8AB4u; // texmLoadResTexture's call of sceGsSetDefLoadImage
|
||||
constexpr uint32_t kFontInit = 0x001C3E48u;
|
||||
|
||||
using ps2x::native::packs::psmIndexed;
|
||||
using ps2x::native::packs::psmIsH;
|
||||
using Record = ps2x::native::packs::TextureRecord;
|
||||
using bozo::render::packs::psmIndexed;
|
||||
using bozo::render::packs::psmIsH;
|
||||
using Record = bozo::render::packs::TextureRecord;
|
||||
bool isH(uint32_t psm) { return psmIsH(psm); }
|
||||
bool indexed(uint32_t psm) { return psmIndexed(psm); }
|
||||
|
||||
@@ -69,7 +67,7 @@ namespace tmb::textures
|
||||
{
|
||||
std::mutex mutex;
|
||||
bool loaded = false;
|
||||
ps2x::native::packs::TexturePack pack; // file name -> its records in order
|
||||
bozo::render::packs::TexturePack pack; // file name -> its records in order
|
||||
std::unordered_map<uint32_t, std::string> nameAt; // destination -> the disc file read there
|
||||
std::vector<std::string> texFiles, resFiles; // the level's, in the game's order
|
||||
uint32_t texOrdinal = 0, resOrdinal = 0;
|
||||
@@ -303,7 +301,7 @@ namespace tmb::textures
|
||||
mismatch("resident record", n, r, psm, width, height);
|
||||
}
|
||||
}
|
||||
sceGsSetDefLoadImage_0x203f30(rdram, ctx, runtime);
|
||||
bozo::port::callLibrary(runtime, ctx, kSceGsSetDefLoadImage); // the library (BozoEngine's), not the game's copy
|
||||
}
|
||||
|
||||
void fontInitOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
|
||||
@@ -317,10 +315,10 @@ namespace tmb::textures
|
||||
fontInit__F10_vramAddrs_0x1c3e48(rdram, ctx, runtime);
|
||||
}
|
||||
|
||||
// A record's entry as RGBA with the GS's alpha (0x80 is 1.0), as ps2x::native::TextureCache gives it.
|
||||
// A record's entry as RGBA with the GS's alpha (0x80 is 1.0), as bozo::render::TextureCache gives it.
|
||||
uint32_t colour(const Record &r, uint32_t index, uint64_t texa)
|
||||
{
|
||||
return ps2x::native::packs::recordColour(r, index, texa);
|
||||
return bozo::render::packs::recordColour(r, index, texa);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -406,7 +404,7 @@ namespace tmb::textures
|
||||
for (uint32_t i = 0; i < 16u && !paletteFound; ++i)
|
||||
{
|
||||
uint32_t px = 0, py = 0;
|
||||
ps2x::native::csm1Position(ps2x::native::packs::psmEightBit(psm) ? i : (csa * 16u + i) & 0xffu, px, py);
|
||||
bozo::render::csm1Position(bozo::render::packs::psmEightBit(psm) ? i : (csa * 16u + i) & 0xffu, px, py);
|
||||
paletteFound = paletteEntry(px, py, ignored);
|
||||
}
|
||||
if (const auto it = s.byBlock.find(cbp); it != s.byBlock.end())
|
||||
@@ -433,7 +431,7 @@ namespace tmb::textures
|
||||
|
||||
uint32_t colours[256] = {};
|
||||
if (indexed(psm))
|
||||
ps2x::native::packs::csm1Palette(psm, csa,
|
||||
bozo::render::packs::csm1Palette(psm, csa,
|
||||
[&](uint32_t px, uint32_t py, uint32_t &out)
|
||||
{
|
||||
if (palette && palette == fontPalette)
|
||||
@@ -449,7 +447,7 @@ namespace tmb::textures
|
||||
Texture texture;
|
||||
texture.key = key;
|
||||
texture.version = ++s.decodes;
|
||||
ps2x::native::packs::decodeRecord(texture, width, height, psm, *texels, colours, texa);
|
||||
bozo::render::packs::decodeRecord(texture, width, height, psm, *texels, colours, texa);
|
||||
// A texture with no texel showing: reported once (a palette or texels taken from the wrong record).
|
||||
if (std::all_of(texture.rgba.begin(), texture.rgba.end(), [](uint32_t c) { return (c >> 24) == 0u; }))
|
||||
{
|
||||
@@ -521,14 +519,14 @@ namespace tmb::textures
|
||||
for (size_t i = 0; i < texture.rgba.size(); ++i)
|
||||
{
|
||||
uint32_t px = 0, py = 0;
|
||||
ps2x::native::csm1Position(texels.texels[i] & 0xfu, px, py);
|
||||
bozo::render::csm1Position(texels.texels[i] & 0xfu, px, py);
|
||||
texture.rgba[i] = px < palette.width && py < palette.height ? colour(palette, py * palette.width + px, 0u) : 0u;
|
||||
}
|
||||
s_font = std::make_shared<const Texture>(std::move(texture));
|
||||
return s_font;
|
||||
}
|
||||
|
||||
void install(PS2Runtime &runtime)
|
||||
void install(tmb::Registry &runtime)
|
||||
{
|
||||
runtime.registerFunction(kFileReadf, &fileReadfOverride);
|
||||
runtime.registerFunction(kZipInflateAll, &zipInflateAllOverride);
|
||||
|
||||
-1069
File diff suppressed because it is too large.
Load diff
@@ -1,443 +0,0 @@
|
||||
// The rain (VU1 microprogram at pc 0x1d40, compiled fragment 39b4d182198a494a), lifted: its per-drop loop
|
||||
// (pcs 0x1d80-0x1ed0) as native code, RECOMP_NOTES "Lifting the rain".
|
||||
//
|
||||
// One pass of the loop draws one drop P as a line, 5 qwords at vi6: 0 the texture-ish vector C (xyz), 1 and 3 the
|
||||
// colour (alpha computed / the tail's), 2 and 4 the two screen positions (FTOI4). A is P by this frame's
|
||||
// view-projection (vf1-vf4), B by last frame's (vf11-vf14), C by vf21-vf24; each is divided by its w (DIV, MULq).
|
||||
// The drop is culled (vi6 stays, vi10 counts it out of the GIF tag) when one of its screen positions is outside
|
||||
// the CLIP test the FCAND mask keeps, or its alpha (255 - 3.1875 * B.w, as a 0x4b0000xx float) is below vf25.w.
|
||||
// The positions come from a chain: G (vf5) and H (vf16) wrap into the 80-unit box (FMAND on the SUBs' sign
|
||||
// flags), the next P is H, the next H is G, the next G is vf10 * vf10.w + G * vf19.
|
||||
//
|
||||
// The entry runs every pass but the last with the same PS2 operations (vuAdd4, products, the ±FLT_MAX clamp of the
|
||||
// compiled fast path, the DIV and FTOI rules), four drops at a time where they do not depend on each other, then
|
||||
// leaves the last pass to the compiled block. A pass takes 35 cycles plus one per wrap (the IBEQs skip a pair when
|
||||
// the sign flag is clear; measured on 1.3M passes of the compiled code).
|
||||
#include "runtime/ps2_vu1_lifted.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
#include <vector>
|
||||
|
||||
namespace tmb
|
||||
{
|
||||
// TMB_RAIN_LIFT_AB (tmb_overrides.cpp): the compiled loop instead, and the strips run natively.
|
||||
std::atomic<bool> g_rainLiftOff{false};
|
||||
std::atomic<uint64_t> g_rainLiftedStrips{0};
|
||||
}
|
||||
|
||||
namespace
|
||||
{
|
||||
using Vu = VU1Interpreter;
|
||||
namespace vu = ps2_vu1_detail;
|
||||
|
||||
constexpr uint32_t kLoopPair = 0x1d80u / 8u;
|
||||
Vu::CompiledEntry g_compiledLoop = nullptr; // the compiled block the entry stands in for
|
||||
|
||||
// ---- PS2 operations, lane by lane (each lane its own value) ----
|
||||
inline __m128 clamp(__m128 value)
|
||||
{
|
||||
const __m128 maximum = _mm_set1_ps(std::numeric_limits<float>::max());
|
||||
return _mm_max_ps(_mm_min_ps(value, maximum), _mm_xor_ps(maximum, _mm_set1_ps(-0.0f)));
|
||||
}
|
||||
inline __m128 mul(__m128 a, __m128 b) { return clamp(_mm_mul_ps(a, b)); }
|
||||
inline __m128 madd(__m128 acc, __m128 a, __m128 b) { return clamp(vu::vuAdd4(acc, _mm_mul_ps(a, b))); }
|
||||
inline __m128 add(__m128 a, __m128 b) { return clamp(vu::vuAdd4(a, b)); }
|
||||
inline __m128 sub(__m128 a, __m128 b) { return clamp(vu::vuAdd4(a, vu::negate4(b))); }
|
||||
template <int kLane>
|
||||
inline __m128 spread(__m128 value) { return _mm_shuffle_ps(value, value, _MM_SHUFFLE(kLane, kLane, kLane, kLane)); }
|
||||
inline __m128 lane(const float *vector, int index) { return _mm_set1_ps(vector[index]); }
|
||||
|
||||
// normalizeOperand / normalizeResult: denormals to a zero of their sign, magnitudes at most FLT_MAX's.
|
||||
inline __m128 normalize(__m128 value)
|
||||
{
|
||||
const __m128i bits = _mm_castps_si128(value);
|
||||
const __m128i magnitudeMask = _mm_set1_epi32(0x7FFFFFFF);
|
||||
const __m128i magnitude = _mm_and_si128(bits, magnitudeMask);
|
||||
const __m128i normal = _mm_cmpgt_epi32(magnitude, _mm_set1_epi32(0x007FFFFF));
|
||||
const __m128i kept = _mm_and_si128(_mm_min_epi32(magnitude, _mm_set1_epi32(0x7F7FFFFF)), normal);
|
||||
return _mm_castsi128_ps(_mm_or_si128(_mm_andnot_si128(magnitudeMask, bits), kept));
|
||||
}
|
||||
// DIV Q, vf0w, w (Vu1Jit::div): 1 / w, ±FLT_MAX and the D status bit for a zero w. divideByZero: lane mask.
|
||||
inline __m128 reciprocal(__m128 w, uint32_t ÷ByZero)
|
||||
{
|
||||
const __m128 den = normalize(w);
|
||||
const __m128 zero = _mm_cmpeq_ps(den, _mm_setzero_ps());
|
||||
divideByZero |= static_cast<uint32_t>(_mm_movemask_ps(zero));
|
||||
const __m128 saturated = _mm_or_ps(_mm_and_ps(den, _mm_set1_ps(-0.0f)), _mm_set1_ps(std::numeric_limits<float>::max()));
|
||||
return normalize(_mm_blendv_ps(_mm_div_ps(_mm_set1_ps(1.0f), den), saturated, zero));
|
||||
}
|
||||
// FTOI4 (vuFloatToInt with 16): truncated, INT_MAX above the range, INT_MIN below.
|
||||
inline __m128i ftoi4(__m128 value)
|
||||
{
|
||||
const __m128 scaled = _mm_mul_ps(value, _mm_set1_ps(16.0f));
|
||||
const __m128i truncated = _mm_cvttps_epi32(scaled);
|
||||
const __m128 above = _mm_cmpge_ps(scaled, _mm_set1_ps(2147483648.0f));
|
||||
return _mm_castps_si128(_mm_blendv_ps(_mm_castsi128_ps(truncated), _mm_castsi128_ps(_mm_set1_epi32(0x7FFFFFFF)), above));
|
||||
}
|
||||
// CLIP's six flags of each lane's (x, y, z) against limit (the bits of |w|, Vu1Jit::clip).
|
||||
inline __m128i clipFlags(__m128 x, __m128 y, __m128 z, __m128i limit)
|
||||
{
|
||||
const __m128i signBit = _mm_set1_epi32(static_cast<int>(0x80000000u));
|
||||
__m128i flags = _mm_setzero_si128();
|
||||
int bit = 1;
|
||||
for (__m128 component : {x, y, z})
|
||||
{
|
||||
const __m128i bits = _mm_castps_si128(component);
|
||||
flags = _mm_or_si128(flags, _mm_and_si128(_mm_cmpgt_epi32(bits, limit), _mm_set1_epi32(bit)));
|
||||
flags = _mm_or_si128(flags, _mm_and_si128(_mm_cmpgt_epi32(_mm_xor_si128(bits, signBit), limit), _mm_set1_epi32(bit << 1)));
|
||||
bit <<= 2;
|
||||
}
|
||||
return flags;
|
||||
}
|
||||
// A live FMAC's flags (Vu1Jit::fmacRelaxed): zero, sign, overflow lane masks of a result (before the clamp).
|
||||
struct LaneFlags
|
||||
{
|
||||
uint32_t zero, sign, overflow;
|
||||
};
|
||||
inline LaneFlags laneFlags(__m128 result, uint32_t active)
|
||||
{
|
||||
const __m128 clamped = clamp(result);
|
||||
return {static_cast<uint32_t>(_mm_movemask_ps(_mm_cmpeq_ps(clamped, _mm_setzero_ps()))) & active,
|
||||
static_cast<uint32_t>(_mm_movemask_ps(clamped)) & active,
|
||||
static_cast<uint32_t>(_mm_movemask_ps(_mm_cmpneq_ps(clamped, result))) & active};
|
||||
}
|
||||
inline uint32_t statusBits(const LaneFlags &flags)
|
||||
{
|
||||
return (flags.zero ? 0x1u : 0u) | (flags.sign ? 0x2u : 0u) | (flags.overflow ? 0x8u : 0u);
|
||||
}
|
||||
|
||||
// ---- The loop's constants (registers it reads and never writes) ----
|
||||
struct Constants
|
||||
{
|
||||
__m128 a[4], b[4], c[4]; // A: vf1-vf4, B: vf11-vf14, C: vf21-vf24 (rows, as the products use them)
|
||||
__m128 step; // vf10.w, spread
|
||||
__m128 chainAcc; // MULAw.xyz ACC, vf10, vf10w (pc 0x1e80)
|
||||
__m128 chainScale; // vf19 (MADD.xyz vf5, vf5, vf19)
|
||||
__m128 boxLow, boxHigh; // vf26, vf25
|
||||
__m128 offset; // vf28 (ADD.xyz before each CLIP)
|
||||
__m128i clipLimit; // vf19.w's |bits| (or the largest denormal for a zero w)
|
||||
__m128 alphaBase; // MULA.w ACC, vf0, vf17: vf17.w
|
||||
__m128 alphaScale; // vf18.w
|
||||
__m128 alphaFloor; // vf25.w
|
||||
__m128 tailColor; // vf15 with w from ADDx.w vf15, vf25, vf0x
|
||||
};
|
||||
|
||||
// AoS transforms (one position, lanes xyzw), for the values handed to the last pass.
|
||||
inline __m128 transformA(const Constants &k, __m128 p)
|
||||
{
|
||||
__m128 acc = mul(k.a[3], _mm_set1_ps(1.0f));
|
||||
acc = madd(acc, k.a[0], spread<0>(p));
|
||||
acc = madd(acc, k.a[1], spread<1>(p));
|
||||
return madd(acc, k.a[2], spread<2>(p));
|
||||
}
|
||||
// MAC bits of a result's lane masks (lane 0 = x is bit 3, w bit 0; sign 4-7, overflow 12-15) and its Z/S/O.
|
||||
inline uint32_t macBits(const LaneFlags &flags)
|
||||
{
|
||||
static constexpr uint8_t kReverse4[16] = {0x0, 0x8, 0x4, 0xC, 0x2, 0xA, 0x6, 0xE,
|
||||
0x1, 0x9, 0x5, 0xD, 0x3, 0xB, 0x7, 0xF};
|
||||
return kReverse4[flags.zero] | (kReverse4[flags.sign] << 4) | (kReverse4[flags.overflow] << 12);
|
||||
}
|
||||
inline uint32_t macStatus(uint32_t mac)
|
||||
{
|
||||
return ((mac & 0xFu) ? 0x1u : 0u) | ((mac & 0xF0u) ? 0x2u : 0u) | ((mac & 0xF000u) ? 0x8u : 0u);
|
||||
}
|
||||
// ACC after MULAx, MADDAy, MADDAz (pcs 0x1eb0-0x1ed0), with the MADDAz's MAC flags.
|
||||
inline __m128 partialB(const Constants &k, __m128 p, uint32_t &mac)
|
||||
{
|
||||
__m128 acc = mul(k.b[0], spread<0>(p));
|
||||
acc = madd(acc, k.b[1], spread<1>(p));
|
||||
const __m128 raw = vu::vuAdd4(acc, _mm_mul_ps(k.b[2], spread<2>(p)));
|
||||
mac = macBits(laneFlags(raw, 0xFu));
|
||||
return clamp(raw);
|
||||
}
|
||||
|
||||
// Per drop, structure of arrays (index: pass). Scratch kept between runs (VU1 runs on one thread).
|
||||
struct Drops
|
||||
{
|
||||
std::vector<float> px, py, pz;
|
||||
std::vector<float> a[4], b[4], c[4];
|
||||
// The flags of MADDAz ACC, vf13, vf6z (pc 0x1ed0) computing this drop's B, which the pass before writes
|
||||
// when it keeps its drop: MAC, and the status bits (Z, S, O).
|
||||
std::vector<uint32_t> bMac, bStatus;
|
||||
void resize(size_t count)
|
||||
{
|
||||
const size_t padded = (count + 3u) & ~size_t{3};
|
||||
for (auto *v : {&px, &py, &pz})
|
||||
v->assign(padded, 0.0f);
|
||||
for (auto *set : {&a, &b, &c})
|
||||
for (auto &v : *set)
|
||||
v.assign(padded, 0.0f);
|
||||
bMac.assign(padded, 0u);
|
||||
bStatus.assign(padded, 0u);
|
||||
}
|
||||
};
|
||||
Drops g_drops;
|
||||
|
||||
// Output of one drop, before packing.
|
||||
struct DropOut
|
||||
{
|
||||
alignas(16) int32_t posA[4];
|
||||
alignas(16) int32_t posB[4];
|
||||
alignas(16) float c[4];
|
||||
float alpha;
|
||||
bool culled;
|
||||
};
|
||||
std::vector<DropOut> g_out;
|
||||
|
||||
Vu::StepResult rainLoop(Vu &vu, const Vu::RunContext &context)
|
||||
{
|
||||
VU1State &s = Vu1Lifted::state(vu);
|
||||
const int32_t passes = static_cast<int16_t>(s.vi[4]); // the loop runs until vi4, decremented first, is 0
|
||||
if (passes < 2 || passes > 4096 || !Vu1Lifted::canRunAhead(vu, context, 41ull * passes) ||
|
||||
tmb::g_rainLiftOff.load(std::memory_order_relaxed))
|
||||
return g_compiledLoop(vu, context);
|
||||
tmb::g_rainLiftedStrips.fetch_add(1u, std::memory_order_relaxed);
|
||||
Vu1Lifted::landQueued(vu);
|
||||
const int32_t native = passes - 1;
|
||||
|
||||
Constants k;
|
||||
for (int c = 0; c < 4; ++c)
|
||||
{
|
||||
k.a[c] = _mm_loadu_ps(s.vf[1 + c]);
|
||||
k.b[c] = _mm_loadu_ps(s.vf[11 + c]);
|
||||
k.c[c] = _mm_loadu_ps(s.vf[21 + c]);
|
||||
}
|
||||
const __m128 vf10 = _mm_loadu_ps(s.vf[10]);
|
||||
k.step = spread<3>(vf10);
|
||||
k.chainAcc = mul(vf10, k.step);
|
||||
k.chainScale = _mm_loadu_ps(s.vf[19]);
|
||||
k.boxLow = _mm_loadu_ps(s.vf[26]);
|
||||
k.boxHigh = _mm_loadu_ps(s.vf[25]);
|
||||
k.offset = _mm_loadu_ps(s.vf[28]);
|
||||
uint32_t wBits = 0;
|
||||
std::memcpy(&wBits, &s.vf[19][3], 4);
|
||||
k.clipLimit = _mm_set1_epi32((wBits & 0x7F800000u) != 0u ? static_cast<int32_t>(wBits & 0x7FFFFFFFu) : 0x007FFFFF);
|
||||
k.alphaBase = mul(_mm_set1_ps(1.0f), lane(s.vf[17], 3));
|
||||
k.alphaScale = lane(s.vf[18], 3);
|
||||
k.alphaFloor = lane(s.vf[25], 3);
|
||||
const __m128 vf15 = _mm_loadu_ps(s.vf[15]);
|
||||
k.tailColor = _mm_blend_ps(vf15, add(spread<3>(k.boxHigh), _mm_setzero_ps()), 0x8);
|
||||
|
||||
// Phase 1, sequential: the positions, the wraps (cycles), the SUBs' flags (sticky status bits).
|
||||
Drops &d = g_drops;
|
||||
d.resize(static_cast<size_t>(native));
|
||||
__m128 g = _mm_loadu_ps(s.vf[5]);
|
||||
__m128 h = _mm_loadu_ps(s.vf[16]);
|
||||
__m128 p = _mm_loadu_ps(s.vf[6]);
|
||||
uint64_t cycles = 0;
|
||||
uint32_t sticky = 0;
|
||||
for (int32_t pass = 0; pass < native; ++pass)
|
||||
{
|
||||
alignas(16) float position[4];
|
||||
_mm_store_ps(position, p);
|
||||
d.px[pass] = position[0];
|
||||
d.py[pass] = position[1];
|
||||
d.pz[pass] = position[2];
|
||||
const __m128 low = vu::vuAdd4(h, vu::negate4(k.boxLow)); // SUB.xyz vf0, vf16, vf26
|
||||
const __m128 high = vu::vuAdd4(k.boxHigh, vu::negate4(g)); // SUB.xyz vf0, vf25, vf5
|
||||
const LaneFlags lowFlags = laneFlags(low, 0x7u), highFlags = laneFlags(high, 0x7u);
|
||||
sticky |= statusBits(lowFlags) | statusBits(highFlags);
|
||||
cycles += 35u + static_cast<uint32_t>(__builtin_popcount(lowFlags.sign) + __builtin_popcount(highFlags.sign));
|
||||
h = _mm_blendv_ps(h, add(h, k.step), _mm_castsi128_ps(_mm_cmplt_epi32(_mm_setzero_si128(),
|
||||
_mm_and_si128(_mm_set1_epi32(static_cast<int>(lowFlags.sign)), _mm_setr_epi32(1, 2, 4, 8)))));
|
||||
g = _mm_blendv_ps(g, sub(g, k.step), _mm_castsi128_ps(_mm_cmplt_epi32(_mm_setzero_si128(),
|
||||
_mm_and_si128(_mm_set1_epi32(static_cast<int>(highFlags.sign)), _mm_setr_epi32(1, 2, 4, 8)))));
|
||||
p = h; // MOVE.xyzw vf6, vf16
|
||||
h = g; // MOVE.xyzw vf16, vf5
|
||||
g = _mm_blend_ps(g, madd(k.chainAcc, g, k.chainScale), 0x7); // MADD.xyz vf5, vf5, vf19
|
||||
}
|
||||
|
||||
// Phase 2, four drops at a time: the three transforms.
|
||||
const __m128 one = _mm_set1_ps(1.0f);
|
||||
alignas(16) float ma[4][4], mb[4][4], mc[4][4]; // [row][component]
|
||||
for (int r = 0; r < 4; ++r)
|
||||
{
|
||||
_mm_store_ps(ma[r], k.a[r]);
|
||||
_mm_store_ps(mb[r], k.b[r]);
|
||||
_mm_store_ps(mc[r], k.c[r]);
|
||||
}
|
||||
for (int32_t first = 0; first < native; first += 4)
|
||||
{
|
||||
const __m128 x = _mm_load_ps(&d.px[first]), y = _mm_load_ps(&d.py[first]), z = _mm_load_ps(&d.pz[first]);
|
||||
uint32_t mac[4] = {};
|
||||
for (int c = 0; c < 4; ++c)
|
||||
{
|
||||
__m128 acc = mul(_mm_set1_ps(ma[3][c]), one);
|
||||
acc = madd(acc, _mm_set1_ps(ma[0][c]), x);
|
||||
acc = madd(acc, _mm_set1_ps(ma[1][c]), y);
|
||||
_mm_store_ps(&d.a[c][first], madd(acc, _mm_set1_ps(ma[2][c]), z));
|
||||
acc = mul(_mm_set1_ps(mb[0][c]), x);
|
||||
acc = madd(acc, _mm_set1_ps(mb[1][c]), y);
|
||||
const __m128 raw = vu::vuAdd4(acc, _mm_mul_ps(_mm_set1_ps(mb[2][c]), z));
|
||||
const LaneFlags flags = laneFlags(raw, 0xFu); // lanes: drops; component c is MAC bit 3 - c
|
||||
const uint32_t bit = 1u << (3 - c);
|
||||
for (int i = 0; i < 4; ++i)
|
||||
mac[i] |= (((flags.zero >> i) & 1u) ? bit : 0u) | (((flags.sign >> i) & 1u) ? bit << 4 : 0u) |
|
||||
(((flags.overflow >> i) & 1u) ? bit << 12 : 0u);
|
||||
_mm_store_ps(&d.b[c][first], madd(clamp(raw), _mm_set1_ps(mb[3][c]), one));
|
||||
acc = mul(_mm_set1_ps(mc[0][c]), x);
|
||||
acc = madd(acc, _mm_set1_ps(mc[1][c]), y);
|
||||
acc = madd(acc, _mm_set1_ps(mc[2][c]), z);
|
||||
_mm_store_ps(&d.c[c][first], madd(acc, _mm_set1_ps(mc[3][c]), one));
|
||||
}
|
||||
for (int i = 0; i < 4; ++i)
|
||||
{
|
||||
d.bMac[first + i] = mac[i];
|
||||
d.bStatus[first + i] = macStatus(mac[i]);
|
||||
}
|
||||
}
|
||||
// The first drop's A and partial B come from the pairs before the entry (vf7, ACC).
|
||||
{
|
||||
const __m128 b0 = madd(_mm_loadu_ps(s.acc), k.b[3], one);
|
||||
alignas(16) float b0v[4];
|
||||
_mm_store_ps(b0v, b0);
|
||||
for (int c = 0; c < 4; ++c)
|
||||
{
|
||||
d.a[c][0] = s.vf[7][c];
|
||||
d.b[c][0] = b0v[c];
|
||||
}
|
||||
}
|
||||
|
||||
// Phase 3, four drops at a time: divisions, screen positions, alpha, clipping, culling.
|
||||
g_out.resize(static_cast<size_t>(native) + 3u);
|
||||
uint32_t divideByZero = 0;
|
||||
uint32_t lastMac = 0, lastStatus = 0, lastDivZero = 0;
|
||||
uint32_t clip = s.clip;
|
||||
for (int32_t first = 0; first < native; first += 4)
|
||||
{
|
||||
const int32_t count = std::min<int32_t>(4, native - first);
|
||||
const uint32_t active = (1u << count) - 1u;
|
||||
uint32_t zeroA = 0, zeroB = 0, zeroC = 0;
|
||||
const __m128 aw = _mm_load_ps(&d.a[3][first]);
|
||||
const __m128 qa = reciprocal(aw, zeroA);
|
||||
const __m128 ax = mul(_mm_load_ps(&d.a[0][first]), qa), ay = mul(_mm_load_ps(&d.a[1][first]), qa),
|
||||
az = mul(_mm_load_ps(&d.a[2][first]), qa);
|
||||
const __m128 bw = _mm_load_ps(&d.b[3][first]);
|
||||
const __m128 qb = reciprocal(bw, zeroB);
|
||||
const __m128 alpha = clamp(vu::vuAdd4(k.alphaBase, vu::negate4(_mm_mul_ps(bw, k.alphaScale))));
|
||||
__m128 cw = _mm_load_ps(&d.c[3][first]);
|
||||
{ // MAXx.w vf9, vf9, vf0x: the larger by sign-magnitude key, +0 on ties
|
||||
const __m128i bits = _mm_castps_si128(cw);
|
||||
const __m128i sign = _mm_srai_epi32(bits, 31);
|
||||
const __m128i key = _mm_sub_epi32(_mm_xor_si128(_mm_and_si128(bits, _mm_set1_epi32(0x7FFFFFFF)), sign), sign);
|
||||
cw = _mm_and_ps(cw, _mm_castsi128_ps(_mm_cmpgt_epi32(key, _mm_setzero_si128())));
|
||||
}
|
||||
const __m128 qc = reciprocal(cw, zeroC);
|
||||
const __m128 bx = mul(_mm_load_ps(&d.b[0][first]), qb), by = mul(_mm_load_ps(&d.b[1][first]), qb),
|
||||
bz = mul(_mm_load_ps(&d.b[2][first]), qb);
|
||||
const __m128 cx = mul(_mm_load_ps(&d.c[0][first]), qc), cy = mul(_mm_load_ps(&d.c[1][first]), qc);
|
||||
const __m128 cz = _mm_load_ps(&d.c[2][first]);
|
||||
const __m128i clipA = clipFlags(add(ax, spread<0>(k.offset)), add(ay, spread<1>(k.offset)),
|
||||
add(az, spread<2>(k.offset)), k.clipLimit);
|
||||
const __m128i clipB = clipFlags(add(bx, spread<0>(k.offset)), add(by, spread<1>(k.offset)),
|
||||
add(bz, spread<2>(k.offset)), k.clipLimit);
|
||||
const __m128 fade = vu::vuAdd4(alpha, vu::negate4(k.alphaFloor)); // SUB.w vf0, vf15, vf25
|
||||
const LaneFlags fadeFlags = laneFlags(fade, active);
|
||||
sticky |= statusBits(fadeFlags);
|
||||
divideByZero |= (zeroA | zeroB | zeroC) & active;
|
||||
|
||||
const __m128i ia[3] = {ftoi4(ax), ftoi4(ay), ftoi4(az)};
|
||||
const __m128i ib[3] = {ftoi4(bx), ftoi4(by), ftoi4(bz)};
|
||||
alignas(16) int32_t pa[3][4], pb[3][4], ca[4], cb[4];
|
||||
alignas(16) float c[3][4], al[4], fd[4];
|
||||
for (int i = 0; i < 3; ++i)
|
||||
{
|
||||
_mm_store_si128(reinterpret_cast<__m128i *>(pa[i]), ia[i]);
|
||||
_mm_store_si128(reinterpret_cast<__m128i *>(pb[i]), ib[i]);
|
||||
}
|
||||
_mm_store_ps(c[0], cx);
|
||||
_mm_store_ps(c[1], cy);
|
||||
_mm_store_ps(c[2], cz);
|
||||
_mm_store_ps(al, alpha);
|
||||
_mm_store_ps(fd, clamp(fade));
|
||||
_mm_store_si128(reinterpret_cast<__m128i *>(ca), clipA);
|
||||
_mm_store_si128(reinterpret_cast<__m128i *>(cb), clipB);
|
||||
for (int32_t i = 0; i < count; ++i)
|
||||
{
|
||||
DropOut &out = g_out[static_cast<size_t>(first + i)];
|
||||
for (int j = 0; j < 3; ++j)
|
||||
{
|
||||
out.posA[j] = pa[j][i];
|
||||
out.posB[j] = pb[j][i];
|
||||
out.c[j] = c[j][i];
|
||||
}
|
||||
out.posA[3] = out.posB[3] = 0; // MFIR.w vf7/vf8, vi0
|
||||
out.alpha = al[i];
|
||||
clip = ((((clip << 6) | static_cast<uint32_t>(ca[i])) << 6) | static_cast<uint32_t>(cb[i])) & 0xFFFFFFu;
|
||||
const bool faint = ((fadeFlags.sign >> i) & 1u) != 0u;
|
||||
out.culled = (clip & 0xBEFu) != 0u || faint;
|
||||
const bool zero = ((fadeFlags.zero >> i) & 1u) != 0u, over = ((fadeFlags.overflow >> i) & 1u) != 0u;
|
||||
lastMac = (zero ? 0x1u : 0u) | (faint ? 0x10u : 0u) | (over ? 0x1000u : 0u);
|
||||
lastStatus = (zero ? 0x1u : 0u) | (faint ? 0x2u : 0u) | (over ? 0x8u : 0u);
|
||||
// Kept: the MADDAz starting the next drop's B writes flags (live on that path only), after these.
|
||||
const size_t next = static_cast<size_t>(first + i + 1);
|
||||
if (!out.culled && next < static_cast<size_t>(native)) // the last pass's: at the handoff
|
||||
{
|
||||
lastMac = d.bMac[next];
|
||||
lastStatus = d.bStatus[next];
|
||||
sticky |= lastStatus;
|
||||
}
|
||||
lastDivZero = ((zeroC >> i) & 1u) != 0u ? 0x20u : 0u; // the pass's last DIV is C's
|
||||
}
|
||||
}
|
||||
|
||||
// Phase 4: the kept drops into VU memory, as the loop's stores leave it (a culled drop's 5 qwords are all
|
||||
// written again by the next pass, at the same vi6).
|
||||
int32_t vi6 = s.vi[6], vi10 = s.vi[10];
|
||||
const auto storeAt = [&](int32_t qword, __m128 value, int mask)
|
||||
{
|
||||
uint32_t address = static_cast<uint32_t>(qword) * 16u;
|
||||
address &= context.dataSize - 1u;
|
||||
if (address + 16u > context.dataSize)
|
||||
return;
|
||||
float *target = reinterpret_cast<float *>(context.vuData + address);
|
||||
const __m128 old = _mm_loadu_ps(target);
|
||||
_mm_storeu_ps(target, mask == 0xF ? value : _mm_blend_ps(old, value, mask));
|
||||
};
|
||||
for (int32_t pass = 0; pass < native; ++pass)
|
||||
{
|
||||
const DropOut &out = g_out[static_cast<size_t>(pass)];
|
||||
if (out.culled)
|
||||
{
|
||||
vi10 = static_cast<int16_t>(vi10 - 1);
|
||||
continue;
|
||||
}
|
||||
const __m128 tail = pass == 0 ? vf15 : k.tailColor;
|
||||
storeAt(vi6 + 3, tail, 0xF);
|
||||
storeAt(vi6 + 1, _mm_blend_ps(vf15, _mm_set1_ps(out.alpha), 0x8), 0xF);
|
||||
storeAt(vi6 + 2, _mm_castsi128_ps(_mm_load_si128(reinterpret_cast<const __m128i *>(out.posA))), 0xF);
|
||||
storeAt(vi6 + 4, _mm_castsi128_ps(_mm_load_si128(reinterpret_cast<const __m128i *>(out.posB))), 0xF);
|
||||
storeAt(vi6 + 0, _mm_load_ps(out.c), 0x7);
|
||||
vi6 = static_cast<int16_t>(vi6 + 5);
|
||||
}
|
||||
|
||||
// Hand the last pass to the compiled block: the state the passes leave.
|
||||
_mm_storeu_ps(s.vf[5], g);
|
||||
_mm_storeu_ps(s.vf[16], h);
|
||||
_mm_storeu_ps(s.vf[6], p);
|
||||
_mm_storeu_ps(s.vf[7], transformA(k, p));
|
||||
uint32_t handoffMac = 0;
|
||||
_mm_storeu_ps(s.acc, partialB(k, p, handoffMac));
|
||||
if (!g_out[static_cast<size_t>(native - 1)].culled)
|
||||
{
|
||||
lastMac = handoffMac;
|
||||
lastStatus = macStatus(handoffMac);
|
||||
sticky |= lastStatus;
|
||||
}
|
||||
_mm_storeu_ps(s.vf[15], k.tailColor);
|
||||
s.vi[4] = static_cast<int16_t>(s.vi[4] - native);
|
||||
s.vi[6] = vi6;
|
||||
s.vi[10] = vi10;
|
||||
Vu1Lifted::setClip(vu, clip);
|
||||
s.mac = lastMac;
|
||||
uint32_t divSticky = divideByZero ? 0x20u : 0u;
|
||||
s.status = (s.status & 0xFC0u) | lastStatus | lastDivZero | ((sticky | divSticky) << 6);
|
||||
Vu1Lifted::advanceTo(vu, Vu1Lifted::cycle(vu) + cycles);
|
||||
return g_compiledLoop(vu, context);
|
||||
}
|
||||
|
||||
const bool g_registered = (Vu::registerLiftedEntry({0u, 1284u, 0x39b4d182198a494aull, kLoopPair, &rainLoop, &g_compiledLoop}), true);
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Regenerates the region's recompiler config (recomp/tmb_scus97101.toml) from its ELF with
|
||||
# ps2_analyzer, then adds the hand-written part shared by both regions (recomp/tmb_manual.toml, by symbol name).
|
||||
# WARNING: this overwrites hand edits in the TOML outside the shared part; diff before committing.
|
||||
source "$(dirname "$0")/common.sh"
|
||||
[ -f "$ELF" ] || { echo "missing $ELF, run scripts/extract_iso.sh first"; exit 1; }
|
||||
cd "$ROOT"
|
||||
"$TOOLS_BUILD/ps2xAnalyzer/ps2_analyzer" "${ELF#$ROOT/}" "${CONFIG#$ROOT/}"
|
||||
sed -i "s|^output = .*|output = \"${GENERATED#$ROOT/}/\"|" "$CONFIG"
|
||||
python tools/tmb_manual_toml.py "$ELF" recomp/tmb_manual.toml "$CONFIG"
|
||||
@@ -1,11 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# scripts/bots.sh <name> [secs]: menus into the first match, the player idle at the start, every vehicle's position
|
||||
# traced to build/pos_<name>.txt, then tools/falls.py counts the vehicles falling under the arena. Extra env (e.g.
|
||||
# TMB_SUBSTEPS=1) passes through.
|
||||
source "$(dirname "$0")/common.sh"
|
||||
name=$1; secs=${2:-600}
|
||||
cd "$GAME_DIR" || exit 1
|
||||
S="25:CROSS/300"; for t in $(seq 60 6 140); do S="$S,$t:CROSS/250"; done
|
||||
PS2X_PAD_SCRIPT="$S" TMB_TRACE_POS="$ROOT/build/pos_$name.txt" timeout "$secs" "$GAME_BUILD/PS2Recomp/ps2xRuntime/ps2EntryRunner" \
|
||||
"$ELF" > "$ROOT/build/run_$name.log" 2>&1 || true
|
||||
python3 "$ROOT/tools/falls.py" "$ROOT/build/pos_$name.txt"
|
||||
@@ -1,11 +1,4 @@
|
||||
#!/usr/bin/env bash
|
||||
# Builds ps2EntryRunner with the region's generated code linked in -> build/game_us (or build/game for PAL)/PS2Recomp/
|
||||
# ps2xRuntime/ps2EntryRunner
|
||||
# Usage: scripts/build_runtime.sh [Release|RelWithDebInfo|Debug]
|
||||
# Build and stage the native game from your own USA disc. TMB_DISC / TMB_KIT / TMB_BUILD_DIR override paths.
|
||||
source "$(dirname "$0")/common.sh"
|
||||
BUILD_TYPE="${1:-RelWithDebInfo}"
|
||||
[ -f "$GENERATED/register_functions.cpp" ] || { echo "no generated code, run scripts/recomp.sh first"; exit 1; }
|
||||
cmake -S "$ROOT" -B "$GAME_BUILD" -G Ninja -DCMAKE_BUILD_TYPE="$BUILD_TYPE" -DTMB_GENERATED_DIR="$GENERATED"
|
||||
cmake --build "$GAME_BUILD" --target ps2EntryRunner -j "$JOBS"
|
||||
# Windows (MSYS2): the DLLs next to the runner, so it starts outside the MSYS2 shell too.
|
||||
case "$(uname -s)" in MINGW* | MSYS*) "$ROOT/scripts/stage_dlls.sh" ;; esac
|
||||
build_game "$@"
|
||||
@@ -1,6 +1,4 @@
|
||||
#!/usr/bin/env bash
|
||||
# Builds ps2_recomp, ps2_analyzer and ps2_vu_aot from the PS2Recomp submodule into build/tools.
|
||||
# Prepare the disc and build BozoEngine's recompiler and externals writer.
|
||||
source "$(dirname "$0")/common.sh"
|
||||
cmake -S "$ROOT/PS2Recomp" -B "$TOOLS_BUILD" -G Ninja -DCMAKE_BUILD_TYPE=Release \
|
||||
-DPS2X_BUILD_RUNTIME=OFF -DPS2X_BUILD_STUDIO=OFF -DPS2X_BUILD_TEST=OFF
|
||||
cmake --build "$TOOLS_BUILD" --target ps2_recomp ps2_analyzer ps2_vu_aot -j "$JOBS"
|
||||
build_game --stop-after tools "$@"
|
||||
+8
-12
@@ -1,15 +1,11 @@
|
||||
# Sourced by the other scripts. Resolves the repo root and tool paths.
|
||||
# Shared paths for the native BozoEngine build.
|
||||
set -euo pipefail
|
||||
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
export PATH="$HOME/.local/share/mise/shims:$PATH"
|
||||
|
||||
# The USA release (SCUS-97101, NTSC): its disc folder, recompiler config, generated code and build. (The European
|
||||
# release is dropped; the runtime's hooks are the USA executable's addresses.)
|
||||
TMB_REGION=us
|
||||
GAME_DIR="$ROOT/game_us"
|
||||
ELF="$GAME_DIR/SCUS_971.01"
|
||||
CONFIG="$ROOT/recomp/tmb_scus97101.toml"
|
||||
GENERATED="$ROOT/generated_us"
|
||||
GAME_BUILD="$ROOT/build/game_us"
|
||||
TOOLS_BUILD="$ROOT/build/tools"
|
||||
TMB_BUILD_DIR="${TMB_BUILD_DIR:-$ROOT/build/native}"
|
||||
TMB_DISC="${TMB_DISC:-$ROOT/Twisted Metal - Black (USA).iso}"
|
||||
JOBS="${JOBS:-$(nproc)}"
|
||||
build_game() {
|
||||
local kit=()
|
||||
[ -z "${TMB_KIT:-}" ] || kit=(--kit "$TMB_KIT")
|
||||
python "$ROOT/tools/tmb_build.py" --disc "$TMB_DISC" --out "$TMB_BUILD_DIR" --jobs "$JOBS" "${kit[@]}" "$@"
|
||||
}
|
||||
@@ -1,11 +1,5 @@
|
||||
#!/usr/bin/env bash
|
||||
# Usage: scripts/extract_iso.sh <path-to-the-disc.iso|.bin|.cue>
|
||||
# Extracts the disc into game_us/ (USA, SCUS-97101) with PS2Recomp/tools/ps2_disc.py (no bsdtar); the runtime mounts
|
||||
# cdrom0: on the ELF's directory. tools/tmb_build.py does this and every other step in one command.
|
||||
# Usage: scripts/extract_iso.sh [disc.iso|disc.bin|disc.cue]
|
||||
source "$(dirname "$0")/common.sh"
|
||||
ISO="${1:-}"
|
||||
[ -f "$ISO" ] || { echo "usage: $0 <iso>"; exit 1; }
|
||||
mkdir -p "$GAME_DIR"
|
||||
python "$ROOT/PS2Recomp/tools/ps2_disc.py" extract "$ISO" "$GAME_DIR"
|
||||
[ -f "$ELF" ] || { echo "ELF not found after extraction: $ELF (is this the $TMB_REGION disc?)"; exit 1; }
|
||||
echo "Extracted to $GAME_DIR"
|
||||
if [ "$#" -gt 0 ]; then TMB_DISC="$1"; shift; fi
|
||||
build_game --stop-after extract "$@"
|
||||
@@ -1,40 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Recompiles every IOP module TMB loads (989SND, LIBSD, PADMAN, SIO2MAN, MTAPMAN, MCMAN, MCSERV, USBD, LGDEV) to native
|
||||
# C++ in the region's generated folder, iop/ (run with PS2X_IOP_NATIVE=1). The recompiler works from each module as the
|
||||
# IOP loads it (relocated at its base): PS2Recomp/tools/irx_load.py loads the disc's MOD/*.IRX offline at the bases
|
||||
# recomp/tmb_iop_modules.json records (the ones the runtime's IOP gives them), the same bytes PS2X_IOP_DUMP_MODULES
|
||||
# writes, then the fork's tools/iop_recomp.py runs on them. Like the rest of the generated code, the output is derived
|
||||
# from the game: never committed.
|
||||
# scripts/iop_recomp.sh offline, from game_us/MOD
|
||||
# scripts/iop_recomp.sh --boot [seconds, default 40]
|
||||
# the old way: boots the game with PS2X_IOP_DUMP_MODULES and recompiles the dumps; prints each module's base,
|
||||
# to update recomp/tmb_iop_modules.json when the runtime's IOP allocation changes
|
||||
source "$(dirname "$0")/common.sh"
|
||||
cd "$ROOT"
|
||||
DUMPS="build/iopmods-$TMB_REGION"
|
||||
rm -rf "$DUMPS" && mkdir -p "$DUMPS" "$GENERATED/iop"
|
||||
if [ "${1:-}" = "--boot" ]; then
|
||||
SECONDS_TO_BOOT=${2:-40}
|
||||
EXE="$GAME_BUILD/PS2Recomp/ps2xRuntime/ps2EntryRunner"
|
||||
[ -x "$EXE" ] || EXE="$EXE.exe"
|
||||
PS2X_IOP_DUMP_MODULES="$ROOT/$DUMPS" timeout "$SECONDS_TO_BOOT" "$EXE" "$ELF" > "build/iop_dump-$TMB_REGION.log" 2>&1 || true
|
||||
ls "$DUMPS" | grep -qi '^989SND.IRX.*\.json$' || { echo "no dump of 989SND (see build/iop_dump-$TMB_REGION.log)"; exit 1; }
|
||||
python -c 'import json, sys
|
||||
for p in sorted(sys.argv[1:], key=lambda p: json.load(open(p))["base"]):
|
||||
d = json.load(open(p)); print("%-14s base %#x size %#x hash %s" % (d["name"], d["base"], d["size"], d["hash"]))' "$DUMPS"/*.json
|
||||
else
|
||||
python - "$GAME_DIR" "$DUMPS" <<'EOF' || exit 1
|
||||
import json, os, sys
|
||||
sys.path.insert(0, 'PS2Recomp/tools')
|
||||
import irx_load
|
||||
game, dumps = sys.argv[1], sys.argv[2]
|
||||
for m in json.load(open('recomp/tmb_iop_modules.json'))['modules']:
|
||||
irx = os.path.join(game, m['file'])
|
||||
if '%016x' % irx_load.fnv1a64(open(irx, 'rb').read()) != m['hash']:
|
||||
sys.exit('%s is not the USA disc\'s' % irx)
|
||||
irx_load.write_dump(irx, int(m['base'], 16), m['name'], dumps)
|
||||
EOF
|
||||
fi
|
||||
for json in "$DUMPS"/*.json; do
|
||||
python PS2Recomp/tools/iop_recomp.py "$json" --out "$GENERATED/iop" || exit 1
|
||||
done
|
||||
@@ -1,24 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Profile-guided build of the runner (GCC). After scripts/build_runtime.sh: rebuilds the runtime, the IOP and the
|
||||
# compiled VU1 microcode instrumented, plays into the first match with scripted menu presses for TMB_PGO_SECONDS
|
||||
# (default 200) while they record a profile, then rebuilds them with it. Experimental: the VU1 microcode replay is
|
||||
# ~12% faster, frame times in the game showed no measurable gain so far (RECOMP_NOTES).
|
||||
# scripts/build_runtime.sh afterwards keeps the profile (TMB_PGO stays USE); -DTMB_PGO=OFF goes back to a plain build.
|
||||
source "$(dirname "$0")/common.sh"
|
||||
BIN="$GAME_BUILD/PS2Recomp/ps2xRuntime/ps2EntryRunner"
|
||||
TRAIN_SECONDS="${TMB_PGO_SECONDS:-200}"
|
||||
|
||||
rm -rf "$GAME_BUILD/pgo-profile"
|
||||
cmake -S "$ROOT" -B "$GAME_BUILD" -DTMB_PGO=GENERATE
|
||||
cmake --build "$GAME_BUILD" --target ps2EntryRunner -j "$JOBS"
|
||||
|
||||
# Language, then the title, ONE PLAYER, the vehicle and the level: the match starts about 150 s in.
|
||||
S="25:CROSS/300"
|
||||
for t in $(seq 60 6 140); do S="$S,$t:CROSS/250"; done
|
||||
echo "Training for ${TRAIN_SECONDS} s (the game window opens)"
|
||||
TMB_PGO_SECONDS="$TRAIN_SECONDS" PS2X_PAD_SCRIPT="$S" "$BIN" "$ELF" > "$GAME_BUILD/pgo-training.log" 2>&1 || true
|
||||
[ -d "$GAME_BUILD/pgo-profile" ] || { echo "no profile was written (see $GAME_BUILD/pgo-training.log)"; exit 1; }
|
||||
|
||||
cmake -S "$ROOT" -B "$GAME_BUILD" -DTMB_PGO=USE
|
||||
cmake --build "$GAME_BUILD" --target ps2EntryRunner -j "$JOBS"
|
||||
echo "Profile-guided runner built: $BIN"
|
||||
+2
-31
@@ -1,33 +1,4 @@
|
||||
#!/usr/bin/env bash
|
||||
# Runs ps2_recomp with the committed config and ps2_vu_aot on the ELF's VU1 microcode; output lands in generated_us/
|
||||
# (VU1 microcode in its vu1/).
|
||||
# Output goes through build/recomp-staging first and only files whose content changed are
|
||||
# copied over, so ninja rebuilds just the affected unity batches instead of the whole game.
|
||||
# Recompile the USA executable with BozoEngine (no IOP or VU recompiler).
|
||||
source "$(dirname "$0")/common.sh"
|
||||
[ -f "$ELF" ] || { echo "missing $ELF, run scripts/extract_iso.sh first"; exit 1; }
|
||||
[ -x "$TOOLS_BUILD/ps2xRecomp/ps2_recomp" ] && [ -x "$TOOLS_BUILD/ps2xRecomp/ps2_vu_aot" ] || "$ROOT/scripts/build_tools.sh"
|
||||
cd "$ROOT"
|
||||
|
||||
STAGING="$ROOT/build/recomp-staging-$TMB_REGION"
|
||||
rm -rf "$STAGING"
|
||||
mkdir -p "$STAGING" "$GENERATED"
|
||||
sed "s|^output = .*|output = \"build/recomp-staging-$TMB_REGION/\"|" "$CONFIG" > "$ROOT/build/recomp-staging-$TMB_REGION.toml"
|
||||
"$TOOLS_BUILD/ps2xRecomp/ps2_recomp" "build/recomp-staging-$TMB_REGION.toml"
|
||||
# VU1 microcode on the fast path (PCSX2-like floats and block timing; RECOMP_NOTES "Fast VU1 path"): 41-43 against
|
||||
# 45 fps in play, same pictures. TMB_VU1_EXACT=1 generates the exact model instead (tmb_vu1_replay checks).
|
||||
if [ -n "${TMB_VU1_EXACT:-}" ]; then
|
||||
"$TOOLS_BUILD/ps2xRecomp/ps2_vu_aot" "$ELF" "$STAGING/vu1"
|
||||
else
|
||||
PS2X_VU_AOT_FAST=1 "$TOOLS_BUILD/ps2xRecomp/ps2_vu_aot" "$ELF" "$STAGING/vu1"
|
||||
fi
|
||||
|
||||
# The textures as a native pack (tools/tmb_texture_pack.py): converted once from the disc's files, nothing read from
|
||||
# the game's texture records while it runs.
|
||||
python tools/tmb_texture_pack.py "$GAME_DIR" "$ELF" "$STAGING/tmb_textures.pack"
|
||||
# The 3D models as a native pack (tools/tmb_mesh_pack.py): the NGP files' prebuilt VIF packets converted once from the
|
||||
# disc, nothing read from them while the game runs.
|
||||
python tools/tmb_mesh_pack.py "$GAME_DIR" "$STAGING/tmb_meshes.pack"
|
||||
|
||||
# -c compares content, not mtimes; --delete drops functions that are no longer generated.
|
||||
changed=$(rsync -rc --delete --out-format='%n' "$STAGING/" "$GENERATED/" | grep -vc '/$' || true)
|
||||
echo "Generated $(ls "$GENERATED" | wc -l) files in $GENERATED ($changed changed)"
|
||||
build_game --stop-after recompile "$@"
|
||||
@@ -1,29 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# The fork's port regression run for TMB: scripts/regress.sh <build-dir> <out-dir>
|
||||
# Boot movies, menus, Challenge mode into a Skyscrapers match, driving and firing for about 3 minutes (380 s in all),
|
||||
# under the box's bench lock (PS2Recomp/tools/bench_lock.sh). Writes <out-dir>/run.log, summary.txt (tools/regress_summary.py)
|
||||
# and last_frame.png. Exits 0 when the run itself completed; pass or fail is in the summary.
|
||||
# REGRESS_SECONDS run length (default 380)
|
||||
# REGRESS_ARENA RIGHT presses after Suburbs in the arena list (default 4, Skyscrapers)
|
||||
source "$(dirname "$0")/common.sh"
|
||||
BUILD="$(cd "${1:?usage: regress.sh <build-dir> <out-dir>}" && pwd)"
|
||||
OUT="${2:?usage: regress.sh <build-dir> <out-dir>}"
|
||||
END="${REGRESS_SECONDS:-380}"
|
||||
BIN="$BUILD/PS2Recomp/ps2xRuntime/ps2EntryRunner"
|
||||
[ -x "$BIN" ] || [ -x "$BIN.exe" ] || { echo "missing $BIN"; exit 1; }
|
||||
rm -rf "$OUT"; mkdir -p "$OUT"
|
||||
OUT="$(cd "$OUT" && pwd)"
|
||||
PS2RECOMP="$(git -C "$ROOT/PS2Recomp" rev-parse --short=8 HEAD)"
|
||||
|
||||
source "$ROOT/PS2Recomp/tools/bench_lock.sh"
|
||||
trap bench_lock_release EXIT
|
||||
bench_lock_take tmb-recomp $((END / 60 + 2)) "TMB regression run, PS2Recomp $PS2RECOMP"
|
||||
START=$(date +%s)
|
||||
code=0
|
||||
PS2X_CAPTURE_DIR="$OUT" PS2X_CAPTURE_INTERVAL=4 TMB_TRACE_FRAMES=1 \
|
||||
PS2X_PAD_SCRIPT="$(python3 "$ROOT/tools/arena_script.py" "${REGRESS_ARENA:-4}" "$END")" \
|
||||
timeout "$END" "$BIN" "$ELF" > "$OUT/run.log" 2>&1 || code=$?
|
||||
DURATION=$(($(date +%s) - START))
|
||||
bench_lock_release
|
||||
trap - EXIT
|
||||
python3 "$ROOT/tools/regress_summary.py" "$OUT" "$code" "$DURATION" "$PS2RECOMP"
|
||||
+2
-7
@@ -1,8 +1,3 @@
|
||||
#!/usr/bin/env bash
|
||||
# Launches the recompiled game on the PS2 path (VU1 and the GS simulated), for comparison: the runner's default is
|
||||
# the native port (scripts/run_native.sh), TMB_NATIVE=0 turns it off. Extra args are passed to ps2EntryRunner.
|
||||
source "$(dirname "$0")/common.sh"
|
||||
BIN="$GAME_BUILD/PS2Recomp/ps2xRuntime/ps2EntryRunner"
|
||||
[ -x "$BIN" ] || { echo "missing $BIN, run scripts/build_runtime.sh first"; exit 1; }
|
||||
export TMB_NATIVE="${TMB_NATIVE:-0}"
|
||||
exec "$BIN" "$ELF" "$@"
|
||||
# BozoEngine is the only runtime.
|
||||
exec "$(dirname "$0")/run_native.sh" "$@"
|
||||
+5
-14
@@ -1,17 +1,8 @@
|
||||
#!/usr/bin/env bash
|
||||
# Launches the game as a native PC port: the 3D drawn by the native renderer from the game's own data (TMB_NATIVE),
|
||||
# the sound driver's IOP modules as recompiled code (PS2X_IOP_NATIVE, when scripts/iop_recomp.sh has generated them)
|
||||
# and the sound and IOP on the PC's clock. Extra args are passed to ps2EntryRunner.
|
||||
# Launch the staged BozoEngine game; extra arguments go to tmb.
|
||||
source "$(dirname "$0")/common.sh"
|
||||
BIN="$GAME_BUILD/PS2Recomp/ps2xRuntime/ps2EntryRunner"
|
||||
[ -x "$BIN" ] || { echo "missing $BIN, run scripts/build_runtime.sh first"; exit 1; }
|
||||
# (All of these are the runner's defaults now, a double-click starts the same game; set here for the record. The frame
|
||||
# rate counter, off for players, is on for us.)
|
||||
export TMB_NATIVE=1 PS2X_SPU2_WALLCLOCK=1 PS2X_IOP_WALLCLOCK=1 PS2X_GS_RENDERER="${PS2X_GS_RENDERER:-native}"
|
||||
BIN="$TMB_BUILD_DIR/TMB/tmb"
|
||||
[ ! -f "$BIN.exe" ] || BIN="$BIN.exe"
|
||||
[ -f "$BIN" ] || { echo "Missing $BIN; run scripts/build_runtime.sh first"; exit 1; }
|
||||
export PS2X_SHOW_FPS="${PS2X_SHOW_FPS:-1}"
|
||||
if compgen -G "$GENERATED/iop/*.cpp" > /dev/null; then
|
||||
export PS2X_IOP_NATIVE=1
|
||||
else
|
||||
echo "no ${GENERATED#$ROOT/}/iop/: the sound modules run interpreted (scripts/iop_recomp.sh recompiles them)"
|
||||
fi
|
||||
exec "$BIN" "$ELF" "$@"
|
||||
exec "$BIN" --elf "$TMB_BUILD_DIR/TMB/SCUS_971.01" --iso "$TMB_BUILD_DIR/TMB/disc.iso" "$@"
|
||||
@@ -1,18 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Windows (MSYS2 UCRT64): copies the DLLs ps2EntryRunner.exe needs (GCC runtime, FFmpeg and their dependencies)
|
||||
# from the MSYS2 prefix next to it, so it also runs outside the MSYS2 shell (Explorer, PowerShell).
|
||||
source "$(dirname "$0")/common.sh"
|
||||
BIN_DIR="$GAME_BUILD/PS2Recomp/ps2xRuntime"
|
||||
EXE="$BIN_DIR/ps2EntryRunner.exe"
|
||||
[ -f "$EXE" ] || { echo "missing $EXE, run scripts/build_runtime.sh first"; exit 1; }
|
||||
PREFIX="${MINGW_PREFIX:-/ucrt64}"
|
||||
# ldd lists every DLL the loader resolves; keep the ones from the MSYS2 prefix (not Windows' own). DLLs staged by
|
||||
# an earlier run resolve next to the exe instead: they are refreshed from the prefix too.
|
||||
count=0
|
||||
for name in $(ldd "$EXE" | awk '$3 ~ /\.dll$/ {print $1}' | sort -u); do
|
||||
if [ -f "$PREFIX/bin/$name" ]; then
|
||||
cp -u "$PREFIX/bin/$name" "$BIN_DIR/"
|
||||
count=$((count + 1))
|
||||
fi
|
||||
done
|
||||
echo "$count DLLs from $PREFIX/bin staged in $BIN_DIR"
|
||||
@@ -0,0 +1,190 @@
|
||||
"""Player-facing migration and timing regression checks; no game data required."""
|
||||
import configparser
|
||||
import sys
|
||||
import tempfile
|
||||
import io
|
||||
import subprocess
|
||||
import tarfile
|
||||
import unittest
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tools'))
|
||||
import check_timing
|
||||
import make_release
|
||||
import tmb_build
|
||||
from unittest.mock import patch
|
||||
from types import SimpleNamespace
|
||||
|
||||
REQUIRED = (
|
||||
'TMB Launcher.exe', 'README.txt', 'CHANGELOG.md', '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',
|
||||
)
|
||||
|
||||
|
||||
class ReleaseTests(unittest.TestCase):
|
||||
def test_retry_drops_failed_feature_checks_after_toolchain_relocation_changes(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
root = Path(folder)
|
||||
cache = root / 'CMakeCache.txt'
|
||||
cache.write_text('CMAKE_HOME_DIRECTORY:INTERNAL=' + tmb_build.ROOT +
|
||||
'\nBOZO_ENGINE_DIR:PATH=engine\nHAVE_XINPUT_H:INTERNAL=\n', encoding='utf-8')
|
||||
(root / 'CMakeFiles').mkdir()
|
||||
(root / 'CMakeFiles/old-check').write_bytes(b'failed check')
|
||||
stamp = root / '.tmb-toolchain-key'
|
||||
stamp.write_text('before relocation fix', encoding='utf-8')
|
||||
build = tmb_build.Build.__new__(tmb_build.Build)
|
||||
build.cmake_build = folder
|
||||
build.disc_dir = folder
|
||||
build.args = SimpleNamespace(build_type='Release', debug_info='no')
|
||||
build.ffmpeg_root = folder
|
||||
build.toolchain_key = lambda: 'relocated compiler'
|
||||
build.tool = lambda name: name
|
||||
build.elf = lambda: str(root / 'own-elf')
|
||||
build.fetch_args = lambda: []
|
||||
def configure(_command):
|
||||
self.assertFalse(cache.exists())
|
||||
self.assertFalse((root / 'CMakeFiles').exists())
|
||||
build.run = configure
|
||||
build.step_configure()
|
||||
self.assertEqual(stamp.read_text(encoding='utf-8').strip(), 'relocated compiler')
|
||||
|
||||
def test_source_export_drains_archive_padding_before_waiting(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
base = Path(folder)
|
||||
archive = base / 'source.tar'
|
||||
content = b'native source archive\n'
|
||||
with tarfile.open(archive, 'w') as tar:
|
||||
entry = tarfile.TarInfo('source.txt')
|
||||
entry.size = len(content)
|
||||
tar.addfile(entry, io.BytesIO(content))
|
||||
producer = base / 'producer.py'
|
||||
producer.write_text('import sys\nfrom pathlib import Path\n'
|
||||
'sys.stdout.buffer.write(Path(sys.argv[1]).read_bytes())\n'
|
||||
'sys.stdout.buffer.write(bytes(1048576))\n', encoding='utf-8')
|
||||
command = [sys.executable, str(producer), str(archive)]
|
||||
code = ('import sys; sys.path.insert(0, %r); import make_release; '
|
||||
'make_release.extract_tar_stream(%r, %r, %r)' %
|
||||
(str(ROOT / 'tools'), command, str(base / 'out'), folder))
|
||||
subprocess.run([sys.executable, '-c', code], check=True, timeout=15)
|
||||
self.assertEqual((base / 'out/source.txt').read_bytes(), content)
|
||||
|
||||
def test_source_cleanup_cannot_escape_the_installation(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
root = Path(folder) / 'source'
|
||||
root.mkdir()
|
||||
outside = Path(folder) / 'outside'
|
||||
outside.mkdir()
|
||||
(outside / 'keep.txt').write_bytes(b'outside source')
|
||||
(root / 'release_files.txt').write_text('../outside/keep.txt\n', encoding='utf-8')
|
||||
with patch.object(tmb_build, 'ROOT', str(root)), self.assertRaises(tmb_build.BuildError):
|
||||
tmb_build.remove_stale_sources()
|
||||
self.assertEqual((outside / 'keep.txt').read_bytes(), b'outside source')
|
||||
|
||||
def test_update_removes_the_retired_source_component_and_keeps_player_data(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
root = Path(folder) / 'source'
|
||||
root.mkdir()
|
||||
(root / 'release_files.txt').write_text('tools/kept.py\n', encoding='utf-8')
|
||||
for name in ('tools/kept.py', 'tools/removed.py', 'PS2Recomp/runtime.cpp', 'PS2Recomp/__pycache__/old.pyc',
|
||||
'custom/untouched.txt', 'game/save.dat'):
|
||||
file = root / name
|
||||
file.parent.mkdir(parents=True, exist_ok=True)
|
||||
file.write_bytes(b'preserve or retire by ownership')
|
||||
with patch.object(tmb_build, 'ROOT', str(root)):
|
||||
tmb_build.remove_stale_sources()
|
||||
self.assertFalse((root / 'PS2Recomp').exists())
|
||||
self.assertFalse((root / 'tools/removed.py').exists())
|
||||
for name in ('tools/kept.py', 'custom/untouched.txt', 'game/save.dat'):
|
||||
self.assertEqual((root/name).read_bytes(), b'preserve or retire by ownership')
|
||||
|
||||
def test_update_never_follows_a_source_directory_link(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
root = Path(folder) / 'source'
|
||||
external = Path(folder) / 'external'
|
||||
root.mkdir()
|
||||
external.mkdir()
|
||||
(root / 'tools').mkdir()
|
||||
(root / 'release_files.txt').write_text('tools/kept.py\n', encoding='utf-8')
|
||||
(external / 'keep.txt').write_bytes(b'outside source')
|
||||
if sys.platform == 'win32':
|
||||
import _winapi
|
||||
_winapi.CreateJunction(str(external), str(root / 'PS2Recomp'))
|
||||
_winapi.CreateJunction(str(external), str(root / 'tools/linked'))
|
||||
else:
|
||||
(root / 'PS2Recomp').symlink_to(external, target_is_directory=True)
|
||||
(root / 'tools/linked').symlink_to(external, target_is_directory=True)
|
||||
with patch.object(tmb_build, 'ROOT', str(root)):
|
||||
tmb_build.remove_stale_sources()
|
||||
self.assertEqual((external / 'keep.txt').read_bytes(), b'outside source')
|
||||
self.assertFalse((root / 'PS2Recomp').exists())
|
||||
self.assertTrue((root / 'tools/linked').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_migration_zip_supports_the_existing_installation_layout(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
stage = Path(folder) / 'stage'
|
||||
for name in REQUIRED:
|
||||
file = stage / name
|
||||
file.parent.mkdir(parents=True, exist_ok=True)
|
||||
file.write_bytes(b'native test fixture\n')
|
||||
release = make_release.Release.__new__(make_release.Release)
|
||||
release.stage = str(stage)
|
||||
release.migration_zip = str(Path(folder) / 'TMB_Recomp-0.4.0.zip')
|
||||
release.zip_time = lambda: (2026, 11, 5, 12, 0, 0)
|
||||
release.step_migration_zip()
|
||||
self.assertTrue(make_release.sha256_matches(release.migration_zip))
|
||||
self.assertEqual(make_release.verify_zip(release.migration_zip, top='TMB_Recomp'), [])
|
||||
self.assertTrue(make_release.verify_zip(release.migration_zip))
|
||||
with zipfile.ZipFile(release.migration_zip) as archive:
|
||||
self.assertEqual({n.split('/')[0] for n in archive.namelist()}, {'TMB_Recomp'})
|
||||
for name in REQUIRED:
|
||||
self.assertEqual(archive.read('TMB_Recomp/' + name), (stage / name).read_bytes())
|
||||
with zipfile.ZipFile(release.migration_zip, 'a') as archive:
|
||||
archive.writestr('TMB_Recomp/source/PS2Recomp/runtime.cpp', b'retired runtime')
|
||||
self.assertTrue(any('retired runtime' in error for error in
|
||||
make_release.verify_zip(release.migration_zip, top='TMB_Recomp')))
|
||||
|
||||
def test_release_rejects_game_executables(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
path = Path(folder) / 'bad.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/hidden.dat', b'\x7fELF' + b'\0' * 100)
|
||||
self.assertTrue(any('an ELF file' in error for error in make_release.verify_zip(path)))
|
||||
|
||||
|
||||
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
|
||||
[tmb:clock] frame 600: EE 10.000 s, PC 10.000 s, debt 0.0 ms; ticks 5760000 fields 600
|
||||
[mpeg:clock] picture 0 at 0.000 s
|
||||
[mpeg:clock] picture 30 at 1.001 s
|
||||
[mpeg:clock] picture 60 at 2.002 s
|
||||
'''
|
||||
|
||||
def test_normal_game_speed(self):
|
||||
self.assertTrue(all(line.startswith('PASS:') for line in check_timing.check(self.LOG)))
|
||||
|
||||
def test_fast_menus_fail_even_if_the_picture_rate_is_normal(self):
|
||||
log = self.LOG.replace('ticks 5760000 fields 600', 'ticks 8640000 fields 900')
|
||||
self.assertTrue(any(line.startswith('FAIL: menu') for line in check_timing.check(log)))
|
||||
|
||||
def test_double_speed_movies_fail_independently(self):
|
||||
log = self.LOG.replace('at 2.002 s', 'at 1.5015 s')
|
||||
self.assertTrue(any(line.startswith('FAIL: movie') for line in check_timing.check(log)))
|
||||
|
||||
def test_missing_measurements_are_not_a_pass(self):
|
||||
self.assertTrue(check_timing.check('')[0].startswith('FAIL:'))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -1,10 +1,10 @@
|
||||
#!/usr/bin/env python3
|
||||
"""apply_update: installs a downloaded release over this one, for the launcher's Update button.
|
||||
|
||||
python -I tools/apply_update.py --zip <TMB_Recomp-x.y.z.zip> --sha256 <its .sha256 file> --version x.y.z
|
||||
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]
|
||||
|
||||
Checks the zip's SHA-256 against the release's .sha256, checks every name in it (one top folder TMB_Recomp/, no
|
||||
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
|
||||
asked for), extracts it whole to <install>/update/staging, and only then moves its files over the release folder.
|
||||
A file in use (the launcher that started this, the kit's Python running it) is renamed to <name>.tmb-old first, as
|
||||
@@ -22,7 +22,7 @@ import shutil
|
||||
import sys
|
||||
import zipfile
|
||||
|
||||
TOP = 'TMB_Recomp/'
|
||||
TOP = 'TMB_Recomp_Bozo/' # the BozoEngine build's zip (tools/make_release.py's TOP)
|
||||
LAUNCHER = 'TMB Launcher.exe'
|
||||
PROTECTED = ('build/', 'game/', 'update/') # the player's build and game, and this update's own folder
|
||||
|
||||
|
||||
+21
-6
@@ -1,15 +1,21 @@
|
||||
#!/usr/bin/env python3
|
||||
"""A PS2X_PAD_SCRIPT for one Challenge-mode match: ONE PLAYER, Challenge, the first vehicle, the arena `rights` RIGHT
|
||||
"""A frame-keyed BozoEngine pad script for one Challenge match: ONE PLAYER, Challenge, first vehicle, `rights` RIGHT
|
||||
presses after Suburbs (0 Suburbs, 1 Junkyard, 4 Skyscrapers, 5 Downtown, 6 Highway Loop, 7 Snowy Roads, 8 Drive-In;
|
||||
2 Freeway is locked and 3 Prison Passage can't be picked in Challenge), two opponents, then driving and firing as
|
||||
tools/play_script.py from 205 s (the match starts about 200 s in) until `end` seconds.
|
||||
|
||||
PS2X_PAD_SCRIPT="$(tools/arena_script.py 4 380)" timeout 380 build/game_us/PS2Recomp/ps2xRuntime/ps2EntryRunner game_us/SCUS_971.01
|
||||
python tools/arena_script.py 4 380 --out arena.txt
|
||||
bash scripts/run_native.sh --pad-script arena.txt
|
||||
"""
|
||||
import sys
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
|
||||
rights = int(sys.argv[1]) if len(sys.argv) > 1 else 4
|
||||
end = float(sys.argv[2]) if len(sys.argv) > 2 else 380
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('rights', nargs='?', type=int, default=4)
|
||||
parser.add_argument('end', nargs='?', type=float, default=380)
|
||||
parser.add_argument('--out', type=Path)
|
||||
args = parser.parse_args()
|
||||
rights, end = args.rights, args.end
|
||||
entries = ['25:CROSS/300', '62:CROSS/250', '72:DOWN/200', '80:CROSS/250', '92:CROSS/250']
|
||||
t = 112
|
||||
for _ in range(rights):
|
||||
@@ -31,4 +37,13 @@ for period, button, ms in ((0.6, 'R1', 150), (1.7, 'L1', 150), (2.9, 'CIRCLE', 1
|
||||
while t < end:
|
||||
entries.append(f'{t:.1f}:{button}/{ms}')
|
||||
t += period
|
||||
print(','.join(entries))
|
||||
frames = []
|
||||
for entry in entries:
|
||||
seconds, press = entry.split(':')
|
||||
button, milliseconds = press.split('/')
|
||||
frames.append(f'{round(float(seconds) * 60)}:{button}/{max(1, round(float(milliseconds) * .06))}')
|
||||
text = ','.join(frames) + '\n'
|
||||
if args.out:
|
||||
args.out.write_text(text, encoding='utf-8')
|
||||
else:
|
||||
print(text, end='')
|
||||
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check a real-time run's menu timers and movie cadence, independently of its FPS counter.
|
||||
|
||||
Run with TMB_TRACE_CLOCK=1 BOZO_TIMING_LOG=1 for at least 40 seconds, then:
|
||||
python tools/check_timing.py run.log
|
||||
The first second of each movie is excluded (decoder and disc startup). A sustained
|
||||
speed error over five percent fails; missing observations fail instead of passing silently.
|
||||
"""
|
||||
import argparse
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
CLOCK = re.compile(r'\[tmb:clock\] frame (\d+): EE ([\d.]+) s, PC ([\d.]+) s,.*ticks (\d+) fields (\d+)')
|
||||
MOVIE = re.compile(r'\[mpeg:clock\] picture (\d+) at ([\d.]+) s')
|
||||
|
||||
|
||||
def check(text):
|
||||
clocks = [tuple(map(float, m.groups())) for m in CLOCK.finditer(text)]
|
||||
results = []
|
||||
if len(clocks) < 2:
|
||||
return ['FAIL: need at least two clock observations (TMB_TRACE_CLOCK=1)']
|
||||
first, last = clocks[0], clocks[-1]
|
||||
seconds = last[2] - first[2]
|
||||
if seconds <= 0:
|
||||
return ['FAIL: clock observations have no elapsed real time']
|
||||
for label, actual, expected in (
|
||||
('game clock', (last[1] - first[1]) / seconds, 1),
|
||||
('menu ticks/s', (last[3] - first[3]) / seconds, 576000),
|
||||
('menu fields/s', (last[4] - first[4]) / seconds, 60),
|
||||
):
|
||||
ok = abs(actual / expected - 1) <= .05
|
||||
results.append(f'{"PASS" if ok else "FAIL"}: {label}: {actual:.4f} (expected {expected})')
|
||||
movies = []
|
||||
for match in MOVIE.finditer(text):
|
||||
frame, time = int(match[1]), float(match[2])
|
||||
if frame == 0 or not movies:
|
||||
movies.append([])
|
||||
if frame >= 30:
|
||||
movies[-1].append((frame, time))
|
||||
observed = 0
|
||||
for i, movie in enumerate(movies, 1):
|
||||
if len(movie) < 2:
|
||||
continue
|
||||
span = movie[-1][1] - movie[0][1]
|
||||
fps = (movie[-1][0] - movie[0][0]) / span if span > 0 else float('inf')
|
||||
ok = abs(fps / (30000 / 1001) - 1) <= .05
|
||||
results.append(f'{"PASS" if ok else "FAIL"}: movie {i}: {fps:.4f} pictures/s (expected 29.97)')
|
||||
observed += 1
|
||||
if not observed:
|
||||
results.append('FAIL: need movie observations (BOZO_TIMING_LOG=1)')
|
||||
return results
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('log', type=Path)
|
||||
args = parser.parse_args()
|
||||
results = check(args.log.read_text(encoding='utf-8', errors='replace'))
|
||||
print('\n'.join(results))
|
||||
return int(any(line.startswith('FAIL:') for line in results))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,50 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compile, statically link and run a C++ probe with only the bundled Windows toolchain.
|
||||
|
||||
The release workflow extracts the kit under a path with spaces and accents. No game data is needed.
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
from make_release import clean_env
|
||||
from tmb_build import configure_gcc_paths, is_ascii, make_alias, remove_alias
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--toolchain', required=True, type=Path)
|
||||
parser.add_argument('--out', required=True, type=Path)
|
||||
args = parser.parse_args()
|
||||
args.out.mkdir(parents=True, exist_ok=True)
|
||||
alias = None
|
||||
prefix = args.toolchain.resolve()
|
||||
try:
|
||||
if os.name == 'nt' and not is_ascii(str(prefix)):
|
||||
alias = make_alias(str(prefix), 'compiler-check')
|
||||
prefix = Path(alias)
|
||||
env = clean_env([str(prefix / 'bin')])
|
||||
configure_gcc_paths(env, str(prefix / 'bin'))
|
||||
source = args.out / 'native-toolchain.cpp'
|
||||
exe = args.out / 'native-toolchain.exe'
|
||||
source.write_text('#include <iostream>\n#include <vector>\n'
|
||||
'int main(){std::vector<int> v{1,2,3}; std::cout << "native toolchain " << v.size() << "\\n";}\n')
|
||||
result = subprocess.run([str(prefix / 'bin/g++.exe'), '-std=c++20', '-static', str(source), '-o', str(exe)],
|
||||
env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, errors='replace')
|
||||
(args.out / 'compiler.log').write_text(result.stdout, encoding='utf-8')
|
||||
if result.returncode:
|
||||
print(result.stdout)
|
||||
return result.returncode
|
||||
output = subprocess.check_output([str(exe)], env=env, text=True).strip()
|
||||
print(output)
|
||||
return int(output != 'native toolchain 3')
|
||||
finally:
|
||||
if alias:
|
||||
remove_alias(alias)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
+82
-104
@@ -1,8 +1,9 @@
|
||||
#!/usr/bin/env python3
|
||||
"""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, the prebuilt
|
||||
recompilers and an embeddable Python. Run once on the developer's PC (MSYS2 UCRT64 installed, network for the
|
||||
downloads); the kit is build output, never committed.
|
||||
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
|
||||
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]
|
||||
|
||||
@@ -13,16 +14,17 @@ The kit (tmb_build uses it when it sits in <TMB_Recomp>/kit or next to the TMB_R
|
||||
libraries, old / Store / API-set import libraries, the CMake GUI and tests), plus the DLLs the kept
|
||||
programs load. The folder keeps MSYS2's name: GCC finds its sysroot as <bin>/../../ucrt64.
|
||||
ffmpeg/ FFmpeg (official release tarball, pinned, SHA-256 checked) configured LGPL-only with nothing but the
|
||||
MPEG-2 video decoder, the MPEG video parser, avcodec, swscale and avutil, built static with the kit's
|
||||
compiler (configure in MSYS2's sh; the objects through Ninja, the list read from FFmpeg's Makefiles)
|
||||
deps/ <name>-src: the FetchContent sources at the tags the CMake files pin (git, without .git)
|
||||
tools/ ps2_recomp.exe and ps2_vu_aot.exe built with the kit, statically linked
|
||||
MPEG-2 video decoder, the MPEG video parser, avcodec and avutil (BozoEngine's libmpeg uses no swscale),
|
||||
built static with the kit's compiler (configure in MSYS2's sh; the objects through Ninja, the list read
|
||||
from FFmpeg's Makefiles)
|
||||
deps/ <name>-src: the FetchContent sources BozoEngine's CMake files pin (the same release archives, the same
|
||||
SHA-256), unpacked: sdl3-src (SDL 3.4.20) and imgui-src (Dear ImGui v1.92.7-docking, b1bcb12a)
|
||||
python/ the Windows embeddable Python (python.org, pinned, SHA-256 checked)
|
||||
sources/ the FFmpeg tarball the kit's FFmpeg is built from (LGPL: its corresponding source)
|
||||
licenses/ each package's license files
|
||||
licenses/ each package's license files (licenses/deps/<name>: SDL3's zlib licence, ImGui's MIT)
|
||||
kit_manifest.json versions, sources, hashes, licenses, sizes
|
||||
|
||||
Steps (--only <step> runs one): toolchain, python, deps, ffmpeg, tools, manifest; then --zip.
|
||||
Steps (--only <step> runs one): toolchain, python, deps, ffmpeg, manifest; then --zip.
|
||||
|
||||
The toolchain's MSYS2 packages are pinned in tools/build_kit_packages.json (committed): the packages the kit is made of
|
||||
and every package they depend on, each with its exact version, its file on repo.msys2.org and that file's SHA-256. The
|
||||
@@ -53,7 +55,7 @@ ROOT = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)),
|
||||
sys.path.insert(0, os.path.join(ROOT, 'tools'))
|
||||
from tmb_build import pe_imports, cmake_rc_flags # noqa: E402
|
||||
|
||||
KIT_VERSION = 1
|
||||
KIT_VERSION = 2 # 2: BozoEngine (SDL3 and ImGui sources, no prebuilt recompilers, no swscale)
|
||||
|
||||
# ---- pinned downloads (official upstream; a mirror of ours only as a fallback, held to the same SHA-256) ----
|
||||
FFMPEG = {
|
||||
@@ -73,32 +75,25 @@ PYTHON = {
|
||||
'sha256': '90905e64a840557d8c1bc4f5b74db3d7ee85e3ffb217611cac1c7813acea4159',
|
||||
'license': 'PSF-2.0',
|
||||
}
|
||||
# FetchContent sources: (name as tmb_build's --fetch-cache wants it, repository, tag, the CMake file pinning it)
|
||||
# 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 = [
|
||||
('raylib', 'https://github.com/raysan5/raylib.git', '5.5', 'PS2Recomp/ps2xRuntime/CMakeLists.txt', 'Zlib'),
|
||||
('imgui', 'https://github.com/ocornut/imgui.git', 'v1.92.7-docking', 'PS2Recomp/ps2xRuntime/CMakeLists.txt', 'MIT'),
|
||||
('rlimgui', 'https://github.com/raylib-extras/rlImGui.git', 'Raylib_5_5', 'PS2Recomp/ps2xRuntime/CMakeLists.txt',
|
||||
'Zlib'),
|
||||
('elfio', 'https://github.com/serge1/ELFIO.git', 'Release_3.12', 'PS2Recomp/ps2xRecomp/CMakeLists.txt', 'MIT'),
|
||||
('toml11', 'https://github.com/ToruNiina/toml11.git', 'v4.4.0', 'PS2Recomp/ps2xRecomp/CMakeLists.txt', 'MIT'),
|
||||
('fmt', 'https://github.com/fmtlib/fmt.git', '12.1.0', 'PS2Recomp/ps2xRecomp/CMakeLists.txt', 'MIT'),
|
||||
('libdwarf', 'https://github.com/davea42/libdwarf-code.git', 'v2.2.0', 'PS2Recomp/ps2xRecomp/CMakeLists.txt',
|
||||
'LGPL-2.1 (libdwarf)'),
|
||||
('rabbitizer', 'https://github.com/Decompollaborate/rabbitizer.git', '1.14.3',
|
||||
'PS2Recomp/ps2xRecomp/CMakeLists.txt', 'MIT'),
|
||||
{'name': 'sdl3', 'version': '3.4.20', 'top': 'SDL3-3.4.20',
|
||||
'url': 'https://github.com/libsdl-org/SDL/releases/download/release-3.4.20/SDL3-3.4.20.tar.gz',
|
||||
'sha256': 'f3bb06f55bed9557227a700af2ea62e49497ebdf58037732a731a5fb3ef8581f',
|
||||
'cmake_file': 'BozoEngine/runtime/CMakeLists.txt', 'license': 'Zlib', 'license_files': ['LICENSE.txt']},
|
||||
{'name': 'imgui', 'version': 'v1.92.7-docking (b1bcb12a624af7509894c8e77dd47416997777fa)',
|
||||
'top': 'imgui-b1bcb12a624af7509894c8e77dd47416997777fa',
|
||||
'url': 'https://github.com/ocornut/imgui/archive/b1bcb12a624af7509894c8e77dd47416997777fa.tar.gz',
|
||||
'sha256': '123926eb22d4990dea06bec0739d92f7790c8ee505b3d903fe2de7e5940f2c27',
|
||||
'cmake_file': 'BozoEngine/runtime/CMakeLists.txt', 'license': 'MIT', 'license_files': ['LICENSE.txt']},
|
||||
]
|
||||
|
||||
# What the build never reads in those sources (raylib's examples are only added with BUILD_EXAMPLES; rlImGui and imgui
|
||||
# are compiled from their top-level files; rlImGui's premake binaries are executables nothing runs; ELFIO's examples and
|
||||
# tests are only added when it is the top-level project, libdwarf's test/ with DO_TESTING: their sample ELF files would
|
||||
# also be the only ELF files in a release, which tools/make_release.py refuses).
|
||||
# What the build never reads in those sources (SDL3's tests and examples are only added with SDL_TESTS /
|
||||
# SDL_EXAMPLES, which BozoEngine turns off; the IDE projects; ImGui is compiled from its top-level files and backends/).
|
||||
DEP_PRUNE = {
|
||||
'elfio': ['tests', 'examples', 'doc'],
|
||||
'libdwarf': ['test'],
|
||||
'raylib': ['examples', 'projects'],
|
||||
'imgui': ['examples', 'docs'],
|
||||
'rlimgui': ['examples', 'resources', 'premake5', 'premake5.exe', 'premake5.osx', 'premake5.lua',
|
||||
'raylib_premake5.lua', 'premake-VisualStudio.bat', 'premake-mingw.bat'],
|
||||
'sdl3': ['test', 'examples', 'docs', 'Xcode', 'VisualC', 'VisualC-GDK', 'android-project'],
|
||||
'imgui': ['examples', 'docs', 'misc/fonts'],
|
||||
}
|
||||
|
||||
# ---- the toolchain ----
|
||||
@@ -613,39 +608,55 @@ class Kit:
|
||||
|
||||
# -- deps
|
||||
|
||||
def git(self):
|
||||
for c in (shutil.which('git'), r'C:\Program Files\Git\cmd\git.exe'):
|
||||
if c and os.path.isfile(c):
|
||||
return c
|
||||
raise KitError('git is needed to fetch the libraries\' sources')
|
||||
|
||||
def step_deps(self):
|
||||
git = self.git()
|
||||
"""The pinned archives (SHA-256 checked, the same BozoEngine's CMake files pin), unpacked as deps/<name>-src
|
||||
with what the build never reads left out; their licences in licenses/deps/<name>."""
|
||||
dst_root = os.path.join(self.out, 'deps')
|
||||
os.makedirs(dst_root, exist_ok=True)
|
||||
for old in os.listdir(dst_root): # a kit of the fork's build (raylib, rlimgui, the recompilers' libraries)
|
||||
if old.endswith('-src') and old[:-4] not in [d['name'] for d in DEPS]:
|
||||
rmtree(os.path.join(dst_root, old))
|
||||
info = {}
|
||||
for name, repo, tag, cmake_file, lic in DEPS:
|
||||
with open(os.path.join(ROOT, cmake_file), encoding='utf-8') as f:
|
||||
for dep in DEPS:
|
||||
name = dep['name']
|
||||
with open(os.path.join(ROOT, dep['cmake_file']), encoding='utf-8') as f:
|
||||
text = f.read()
|
||||
if not re.search(r'GIT_REPOSITORY\s+"?%s"?\s+GIT_TAG\s+"?%s"?' % (re.escape(repo), re.escape(tag)), text):
|
||||
raise KitError('%s no longer pins %s at %s: update DEPS' % (cmake_file, repo, tag))
|
||||
if dep['url'] not in text or ('SHA256=' + dep['sha256']) not in text:
|
||||
raise KitError('%s no longer pins %s (SHA-256 %s): update DEPS' % (dep['cmake_file'], dep['url'],
|
||||
dep['sha256']))
|
||||
archive = download(dep, self.downloads)
|
||||
dst = os.path.join(dst_root, name + '-src')
|
||||
rmtree(dst)
|
||||
run([git, '-c', 'advice.detachedHead=false', 'clone', '--quiet', '--depth', '1', '--branch', tag,
|
||||
repo, dst])
|
||||
commit = run([git, '-C', dst, 'rev-parse', 'HEAD']).strip()
|
||||
rmtree(os.path.join(dst, '.git'))
|
||||
tmp = os.path.join(self.work, 'deps-' + name)
|
||||
rmtree(tmp)
|
||||
os.makedirs(tmp)
|
||||
with tarfile.open(archive) as tf:
|
||||
for m in tf.getmembers():
|
||||
parts = m.name.split('/')
|
||||
if m.name.startswith('/') or '..' in parts or not (m.isfile() or m.isdir()):
|
||||
if m.issym() or m.islnk():
|
||||
continue # no links in a kit (none of these archives needs one)
|
||||
raise KitError('%s: unexpected entry %s' % (archive, m.name))
|
||||
tf.extractall(tmp, **({'filter': 'data'} if hasattr(tarfile, 'data_filter') else {}))
|
||||
top = os.path.join(tmp, dep['top'])
|
||||
if not os.path.isdir(top):
|
||||
raise KitError('%s has no %s/' % (archive, dep['top']))
|
||||
shutil.move(top, dst)
|
||||
rmtree(tmp)
|
||||
for rel in DEP_PRUNE.get(name, []):
|
||||
p = os.path.join(dst, rel)
|
||||
p = os.path.join(dst, *rel.split('/'))
|
||||
if os.path.isdir(p):
|
||||
rmtree(p)
|
||||
elif os.path.isfile(p):
|
||||
os.remove(p)
|
||||
lic = self.licenses_dir(os.path.join('deps', name))
|
||||
for n in dep['license_files']:
|
||||
shutil.copy2(os.path.join(dst, n), lic)
|
||||
size, nfiles = dir_size(dst)
|
||||
info[name] = {'repository': repo, 'tag': tag, 'commit': commit, 'license': lic,
|
||||
'left_out': DEP_PRUNE.get(name, []),
|
||||
'bytes': size, 'files': nfiles}
|
||||
log(' %s %s %s (%.1f MB)' % (name, tag, commit[:12], size / 1e6))
|
||||
info[name] = {'version': dep['version'], 'url': dep['url'], 'sha256': dep['sha256'],
|
||||
'pinned_by': dep['cmake_file'], 'license': dep['license'],
|
||||
'left_out': DEP_PRUNE.get(name, []), 'bytes': size, 'files': nfiles}
|
||||
log(' %s %s (%.1f MB)' % (name, dep['version'], size / 1e6))
|
||||
self.part('deps', info)
|
||||
|
||||
# -- ffmpeg
|
||||
@@ -707,66 +718,26 @@ class Kit:
|
||||
log(' ffmpeg %s: %s, %.1f MB' % (FFMPEG['version'], ', '.join('%s %d objects' % (lib, len(libs[lib]['objs']))
|
||||
for lib in FFMPEG_LIBS), size / 1e6))
|
||||
|
||||
# -- tools
|
||||
|
||||
def step_tools(self):
|
||||
build = os.path.join(self.work, 'tools-build')
|
||||
rmtree(build)
|
||||
env = clean_env([self.bin])
|
||||
b = lambda n: os.path.join(self.bin, n + '.exe').replace('\\', '/') # noqa: E731
|
||||
deps = os.path.join(self.out, 'deps')
|
||||
fetch = ['-DFETCHCONTENT_SOURCE_DIR_%s=%s' % (n.upper(), os.path.join(deps, n + '-src').replace('\\', '/'))
|
||||
for n, *_ in DEPS if os.path.isdir(os.path.join(deps, n + '-src'))]
|
||||
fetch.append('-DFETCHCONTENT_FULLY_DISCONNECTED=ON')
|
||||
logf = os.path.join(self.work, 'tools.log')
|
||||
if os.path.exists(logf):
|
||||
os.remove(logf)
|
||||
run([b('cmake'), '-S', os.path.join(ROOT, 'PS2Recomp'), '-B', build, '-G', 'Ninja',
|
||||
'-DCMAKE_BUILD_TYPE=Release', '-DPS2X_BUILD_RUNTIME=OFF', '-DPS2X_BUILD_STUDIO=OFF',
|
||||
'-DPS2X_BUILD_TEST=OFF', '-DPS2X_BUILD_ANALYZER=OFF',
|
||||
'-DCMAKE_C_COMPILER=' + b('gcc'), '-DCMAKE_CXX_COMPILER=' + b('g++'), '-DCMAKE_MAKE_PROGRAM=' + b('ninja'),
|
||||
'-DCMAKE_EXE_LINKER_FLAGS=-static'] + cmake_rc_flags() + fetch, env=env, logfile=logf)
|
||||
run([b('cmake'), '--build', build, '--target', 'ps2_recomp', 'ps2_vu_aot', '-j', str(self.args.jobs)],
|
||||
env=env, logfile=logf)
|
||||
dst = os.path.join(self.out, 'tools')
|
||||
rmtree(dst)
|
||||
os.makedirs(dst)
|
||||
info = {}
|
||||
for t in ('ps2_recomp', 'ps2_vu_aot'):
|
||||
exe = os.path.join(build, 'ps2xRecomp', t + '.exe')
|
||||
run([b('strip'), '--strip-debug', exe], env=env)
|
||||
shutil.copy2(exe, dst)
|
||||
imports = pe_imports(exe)
|
||||
local = [n for n in imports if os.path.isfile(os.path.join(self.bin, n))]
|
||||
if local:
|
||||
raise KitError('%s still loads %s' % (t, ', '.join(local)))
|
||||
info[t] = {'bytes': os.path.getsize(exe), 'sha256': sha256_file(exe), 'imports': sorted(imports)}
|
||||
log(' %s: %.1f MB, imports %s' % (t, info[t]['bytes'] / 1e6, ', '.join(sorted(imports))))
|
||||
info['fork_commit'] = release_stamp().get('fork_commit') or \
|
||||
run([self.git(), '-C', os.path.join(ROOT, 'PS2Recomp'), 'rev-parse', 'HEAD']).strip()
|
||||
self.part('tools', info)
|
||||
|
||||
# -- manifest
|
||||
|
||||
def step_manifest(self):
|
||||
parts = {n: self.part(n) for n in ('toolchain', 'python', 'deps', 'ffmpeg', 'tools')}
|
||||
parts = {n: self.part(n) for n in ('toolchain', 'python', 'deps', 'ffmpeg')}
|
||||
sizes = {}
|
||||
for d in ('ucrt64', 'ffmpeg', 'deps', 'tools', 'python', 'sources', 'licenses'):
|
||||
for d in ('ucrt64', 'ffmpeg', 'deps', 'python', 'sources', 'licenses'):
|
||||
sizes[d] = dir_size(os.path.join(self.out, d))[0]
|
||||
manifest = {
|
||||
'kit': 'TMB_Recomp build kit', 'kit_version': KIT_VERSION,
|
||||
'kit': 'TMB_Recomp build kit', 'kit_version': KIT_VERSION, 'engine': 'BozoEngine',
|
||||
'made': time.strftime('%Y-%m-%d %H:%M:%S'), 'made_from': self.tmb_commit(),
|
||||
'layout': {
|
||||
'ucrt64': 'the toolchain: GCC, binutils, mingw-w64, winpthreads, CMake, Ninja (MSYS2 UCRT64 '
|
||||
'packages, pruned)',
|
||||
'ffmpeg': 'static FFmpeg: avcodec (mpeg2video decoder, mpegvideo parser), swscale, avutil',
|
||||
'deps': '<name>-src FetchContent sources',
|
||||
'tools': 'ps2_recomp.exe, ps2_vu_aot.exe (static)',
|
||||
'ffmpeg': 'static FFmpeg: avcodec (mpeg2video decoder, mpegvideo parser), avutil',
|
||||
'deps': '<name>-src FetchContent sources: sdl3 (SDL 3.4.20), imgui (Dear ImGui b1bcb12a)',
|
||||
'python': 'Windows embeddable Python',
|
||||
'sources': 'FFmpeg source tarball',
|
||||
'licenses': 'license files per component'},
|
||||
'toolchain': parts['toolchain'], 'ffmpeg': parts['ffmpeg'], 'python': parts['python'],
|
||||
'deps': parts['deps'], 'tools': parts['tools'], 'bytes': sizes, 'total_bytes': sum(sizes.values()),
|
||||
'deps': parts['deps'], 'bytes': sizes, 'total_bytes': sum(sizes.values()),
|
||||
'licenses': {
|
||||
'gcc': 'GPL-3.0-or-later; the runtime libraries it links into a program (libgcc, libstdc++, '
|
||||
'libatomic) under the GCC Runtime Library Exception 3.1: the built game carries no GPL '
|
||||
@@ -778,7 +749,7 @@ class Kit:
|
||||
'ffmpeg': 'LGPL-2.1-or-later, configured without --enable-gpl / --enable-version3 / '
|
||||
'--enable-nonfree; its source in sources/',
|
||||
'python': 'PSF-2.0',
|
||||
'deps': {n: lic for n, _r, _t, _c, lic in DEPS},
|
||||
'deps': {d['name']: d['license'] for d in DEPS},
|
||||
'gpl_source_note': 'GCC, binutils and the other MSYS2 binaries are redistributed unmodified: their '
|
||||
'corresponding sources are the MSYS2 source packages of the versions listed in '
|
||||
'toolchain.msys2_packages (repo.msys2.org/mingw/sources); a public kit must ship or '
|
||||
@@ -789,6 +760,13 @@ class Kit:
|
||||
log(' kit: %.1f MB (%s)' % (sum(sizes.values()) / 1e6,
|
||||
', '.join('%s %.1f' % (k, v / 1e6) for k, v in sizes.items())))
|
||||
|
||||
@staticmethod
|
||||
def git():
|
||||
for c in (shutil.which('git'), r'C:\Program Files\Git\cmd\git.exe'):
|
||||
if c and os.path.isfile(c):
|
||||
return c
|
||||
raise KitError('git is needed to read the commit the kit is made from')
|
||||
|
||||
def tmb_commit(self):
|
||||
if release_stamp().get('commit'):
|
||||
return release_stamp()['commit']
|
||||
@@ -813,15 +791,15 @@ class Kit:
|
||||
|
||||
# ---- FFmpeg: configure flags, the Makefiles read, the Ninja file ----
|
||||
|
||||
FFMPEG_LIBS = ['avcodec', 'swscale', 'avutil'] # link order
|
||||
FFMPEG_LIBS = ['avcodec', 'avutil'] # link order (BozoEngine's libmpeg: no swscale)
|
||||
FFMPEG_CONFIGURE = [
|
||||
'--prefix=/kit/ffmpeg', '--arch=x86_64', '--target-os=mingw32',
|
||||
'--cc=gcc', '--cxx=g++', '--ar=ar', '--nm=nm', '--ranlib=ranlib', '--strip=strip', '--windres=windres',
|
||||
'--pkg-config=false',
|
||||
'--enable-static', '--disable-shared', '--disable-programs', '--disable-doc', '--disable-debug',
|
||||
'--disable-everything', '--disable-autodetect', '--disable-network',
|
||||
'--disable-avdevice', '--disable-avformat', '--disable-avfilter', '--disable-swresample',
|
||||
'--enable-avcodec', '--enable-swscale', '--enable-avutil',
|
||||
'--disable-avdevice', '--disable-avformat', '--disable-avfilter', '--disable-swresample', '--disable-swscale',
|
||||
'--enable-avcodec', '--enable-avutil',
|
||||
'--enable-decoder=mpeg2video', '--enable-parser=mpegvideo',
|
||||
'--enable-w32threads', '--disable-x86asm',
|
||||
]
|
||||
@@ -1107,7 +1085,7 @@ def write_pc(path, lib, version, mk):
|
||||
% (lib, lib, version, lib, private))
|
||||
|
||||
|
||||
STEPS = ['toolchain', 'python', 'deps', 'ffmpeg', 'tools', 'manifest']
|
||||
STEPS = ['toolchain', 'python', 'deps', 'ffmpeg', 'manifest']
|
||||
|
||||
|
||||
def main():
|
||||
@@ -1115,7 +1093,7 @@ def main():
|
||||
ap.add_argument('--out', help='the kit folder to write (outside the repository, or under build/)')
|
||||
ap.add_argument('--msys', default='C:/msys64', help='the MSYS2 installation the toolchain comes from')
|
||||
ap.add_argument('--downloads', help='where the FFmpeg and Python downloads are kept (default: next to --out)')
|
||||
ap.add_argument('--work', help='scratch folder for the FFmpeg and tools builds (default: next to --out)')
|
||||
ap.add_argument('--work', help='scratch folder for the FFmpeg build and the archives (default: next to --out)')
|
||||
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)
|
||||
|
||||
+145
-98
@@ -1,24 +1,27 @@
|
||||
#!/usr/bin/env python3
|
||||
"""make_release: the player's download, from a commit of this repository: TMB_Recomp-<version>.zip with the launcher,
|
||||
the code and the build kit, its SHA-256, the licences and the corresponding sources of what the kit redistributes.
|
||||
"""make_release: the player's download, from a commit of this repository: TMB_Recomp-<version>-bozo.zip (the game
|
||||
built on BozoEngine; its folder TMB_Recomp_Bozo, so it can sit beside the fork build's TMB_Recomp-<version>.zip) with the
|
||||
launcher, the code and the build kit, its SHA-256, the licences and the corresponding sources of what the kit
|
||||
redistributes.
|
||||
|
||||
python tools/make_release.py --version 0.1.0 --kit D:/tmb_kit/kit --out D:/tmb_release [--with-sources]
|
||||
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 PS2Recomp submodule at the commit it records -> 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, pack, generated code or disc file name may be in it.
|
||||
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,
|
||||
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). Its prebuilt recompilers must be the fork's at
|
||||
this commit (kit_manifest.json tools.fork_commit): when they are not, make_build_kit --only tools
|
||||
--only manifest rebuilds them in the release's copy (the original kit is left as it was). The pins of
|
||||
FFmpeg, Python and the FetchContent sources are checked against the exported make_build_kit.py.
|
||||
tools/make_build_kit.py, which needs MSYS2 and the network): a BozoEngine kit (kit_version 2: SDL3 and
|
||||
ImGui sources, no prebuilt recompilers). The pins of FFmpeg, Python, the library archives and the MSYS2
|
||||
packages are checked against the exported make_build_kit.py.
|
||||
launcher launcher/ configured and built with the kit's toolchain alone (PATH = the kit and Windows), offline (the
|
||||
kit's raylib, imgui, rlImGui; the Exo 2 font from --font-dir or downloaded and SHA-256 checked), with
|
||||
LAUNCHER_VERSION / LAUNCHER_COMMIT: the footer, the update check, the exe's version information.
|
||||
kit's SDL3 and ImGui, BozoEngine's PNG writer; the Exo 2 font from --font-dir or downloaded and SHA-256
|
||||
checked), with LAUNCHER_VERSION / LAUNCHER_COMMIT: the footer, the update check, the exe's version
|
||||
information.
|
||||
licences LICENSES\\: each component's licence files (TMB_Recomp's own code: MIT, the repository's LICENSE;
|
||||
PS2Recomp: GPL-3.0; the kit's components, the launcher's libraries and font) and SOURCES.txt: every MSYS2
|
||||
BozoEngine: MIT; the kit's components, the libraries and the launcher's font) and SOURCES.txt: every MSYS2
|
||||
package the kit holds files of, with its version and its source package on repo.msys2.org, FFmpeg's
|
||||
tarball, the libraries' repositories and commits.
|
||||
changelog CHANGELOG.md's section for the version (## [x.y.z], Keep a Changelog), from the commit: the release
|
||||
@@ -56,8 +59,15 @@ import zipfile
|
||||
|
||||
ROOT = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))
|
||||
REPO = 'TheBozos/TMB_Recomp'
|
||||
FORK_REPO = 'TheBozos/PS2Recomp'
|
||||
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',)
|
||||
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'
|
||||
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).
|
||||
@@ -183,23 +193,31 @@ def link_tree(src, dst, skip=(), copy=()):
|
||||
def extract_tar_stream(cmd, dst, cwd):
|
||||
"""A `git archive` (tar on stdout) unpacked into dst; links and absolute or parent paths refused."""
|
||||
p = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
with tarfile.open(fileobj=p.stdout, mode='r|') as tf:
|
||||
for m in tf:
|
||||
name = m.name
|
||||
if name.startswith('/') or '..' in name.split('/') or m.issym() or m.islnk():
|
||||
raise ReleaseError('unexpected entry in the archive: %s' % name)
|
||||
target = os.path.join(dst, *name.split('/'))
|
||||
if m.isdir():
|
||||
os.makedirs(target, exist_ok=True)
|
||||
elif m.isfile():
|
||||
os.makedirs(os.path.dirname(target), exist_ok=True)
|
||||
with tf.extractfile(m) as src, open(target, 'wb') as out:
|
||||
shutil.copyfileobj(src, out)
|
||||
if m.mode & 0o111:
|
||||
os.chmod(target, 0o755)
|
||||
os.utime(target, (m.mtime, m.mtime))
|
||||
err = p.stderr.read().decode('utf-8', 'replace')
|
||||
if p.wait() != 0:
|
||||
try:
|
||||
with tarfile.open(fileobj=p.stdout, mode='r|') as tf:
|
||||
for m in tf:
|
||||
name = m.name
|
||||
if name.startswith('/') or '..' in name.split('/') or m.issym() or m.islnk():
|
||||
raise ReleaseError('unexpected entry in the archive: %s' % name)
|
||||
target = os.path.join(dst, *name.split('/'))
|
||||
if m.isdir():
|
||||
os.makedirs(target, exist_ok=True)
|
||||
elif m.isfile():
|
||||
os.makedirs(os.path.dirname(target), exist_ok=True)
|
||||
with tf.extractfile(m) as src, open(target, 'wb') as out:
|
||||
shutil.copyfileobj(src, out)
|
||||
if m.mode & 0o111:
|
||||
os.chmod(target, 0o755)
|
||||
os.utime(target, (m.mtime, m.mtime))
|
||||
except BaseException:
|
||||
p.kill()
|
||||
p.communicate()
|
||||
raise
|
||||
# Tar readers stop at the end marker before all record padding has necessarily left stdout. Drain stdout and
|
||||
# stderr together: waiting on stderr alone can deadlock git archive on Windows' small pipe buffer.
|
||||
_padding, err = p.communicate()
|
||||
err = err.decode('utf-8', 'replace')
|
||||
if p.returncode != 0:
|
||||
raise ReleaseError('%s: %s' % (' '.join(cmd[1:4]), err.strip()))
|
||||
|
||||
|
||||
@@ -346,16 +364,17 @@ class Release:
|
||||
self.version = args.version or self.tag_version()
|
||||
if not VERSION_RE.match(self.version):
|
||||
raise ReleaseError('version %r: expected MAJOR.MINOR.PATCH[-prerelease]' % self.version)
|
||||
self.name = '%s-%s' % (NAME, self.version)
|
||||
self.name = '%s-%s-%s' % (NAME, self.version, FLAVOR)
|
||||
self.downloads = os.path.abspath(args.downloads or os.path.join(self.out, 'downloads'))
|
||||
self.work = os.path.join(self.out, 'work', self.version)
|
||||
self.stage = os.path.join(self.out, self.name)
|
||||
self.source = os.path.join(self.stage, 'source')
|
||||
self.kit = os.path.join(self.stage, 'kit')
|
||||
self.zip = os.path.join(self.out, self.name + '.zip')
|
||||
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.fork_commit = None
|
||||
self.engine_commit = None
|
||||
self.manifest = None
|
||||
self.msys_sources = [] # (package base, version, licence, url, file, sha256)
|
||||
|
||||
@@ -376,18 +395,21 @@ 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, 'PS2Recomp').split()
|
||||
entry = git('ls-tree', self.commit, ENGINE_DIR).split()
|
||||
if len(entry) < 3 or entry[0] != '160000':
|
||||
raise ReleaseError('PS2Recomp is not a submodule at %s' % self.commit)
|
||||
self.fork_commit = entry[2]
|
||||
fork_repo = os.path.join(ROOT, 'PS2Recomp')
|
||||
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.fork_commit + '^{commit}', cwd=fork_repo)
|
||||
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 PS2Recomp' % self.fork_commit)
|
||||
fork_dst = os.path.join(self.source, 'PS2Recomp')
|
||||
os.makedirs(fork_dst, exist_ok=True)
|
||||
extract_tar_stream([find_git(), 'archive', '--format=tar', self.fork_commit], fork_dst, fork_repo)
|
||||
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))
|
||||
# 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('\\', '/')
|
||||
@@ -396,14 +418,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\nfork_commit = %s\ndate = %s\n'
|
||||
% (self.version, self.commit, self.fork_commit,
|
||||
'version = %s\ncommit = %s\nengine = BozoEngine\nengine_commit = %s\ndate = %s\n'
|
||||
% (self.version, self.commit, self.engine_commit,
|
||||
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 + PS2Recomp %s, %d files, %.1f MB, audited' % (self.commit[:12], self.fork_commit[:12], n,
|
||||
log(' source: %s + BozoEngine %s, %d files, %.1f MB, audited' % (self.commit[:12], self.engine_commit[:12], n,
|
||||
dir_size(self.source) / 1e6))
|
||||
|
||||
# -- the kit
|
||||
@@ -427,22 +449,14 @@ class Release:
|
||||
'--work', os.path.join(self.work, 'kit-work'), '--jobs', str(self.args.jobs)])
|
||||
with open(os.path.join(self.kit, 'kit_manifest.json')) as f:
|
||||
self.manifest = json.load(f)
|
||||
if self.manifest.get('engine') != 'BozoEngine':
|
||||
raise ReleaseError('%s is a kit of the fork\'s build (kit_version %s): make a BozoEngine kit '
|
||||
'(tools/make_build_kit.py at this commit)' % (self.args.kit or self.kit,
|
||||
self.manifest.get('kit_version')))
|
||||
self.check_kit_pins()
|
||||
if self.manifest['tools'].get('fork_commit') != self.fork_commit:
|
||||
log(' the kit\'s recompilers are the fork\'s %s, this release\'s is %s: rebuilding them'
|
||||
% (str(self.manifest['tools'].get('fork_commit'))[:12], self.fork_commit[:12]))
|
||||
if not os.path.isdir(os.path.join(self.kit, '.parts')):
|
||||
raise ReleaseError('the kit has no .parts/ (make_build_kit\'s step records): it cannot be updated')
|
||||
run(self.kit_tool() + ['--out', self.kit, '--msys', self.args.msys, '--work',
|
||||
os.path.join(self.work, 'kit-work'), '--only', 'tools', '--only', 'manifest',
|
||||
'--jobs', str(self.args.jobs)], logfile=os.path.join(self.work, 'kit.log'))
|
||||
with open(os.path.join(self.kit, 'kit_manifest.json')) as f:
|
||||
self.manifest = json.load(f)
|
||||
if self.manifest['tools'].get('fork_commit') != self.fork_commit:
|
||||
raise ReleaseError('the rebuilt kit still records fork %s' % self.manifest['tools'].get('fork_commit'))
|
||||
self.prune_kit_deps()
|
||||
rmtree(os.path.join(self.kit, '.parts'))
|
||||
log(' kit: %.1f MB, tools from the fork\'s %s' % (dir_size(self.kit) / 1e6, self.fork_commit[:12]))
|
||||
log(' kit: %.1f MB' % (dir_size(self.kit) / 1e6))
|
||||
|
||||
def prune_kit_deps(self):
|
||||
"""What this commit's make_build_kit.py leaves out of the libraries' sources (DEP_PRUNE), out of the release's
|
||||
@@ -477,8 +491,8 @@ class Release:
|
||||
if not pinned or pinned.group(1) != ver:
|
||||
wrong.append('%s %s (pinned %s)' % (what.lower(), ver, pinned.group(1) if pinned else '?'))
|
||||
for name, info in m['deps'].items():
|
||||
if not re.search(r"\('%s', '[^']+', '%s'" % (re.escape(name), re.escape(info['tag'])), text):
|
||||
wrong.append('%s %s' % (name, info['tag']))
|
||||
if not re.search(r"'name': '%s',[^}]*'sha256': '%s'" % (re.escape(name), re.escape(info['sha256'])), text):
|
||||
wrong.append('%s %s' % (name, info['version']))
|
||||
# The toolchain's MSYS2 packages: the versions tools/build_kit_packages.json pins at this commit.
|
||||
pins_path = os.path.join(self.source, 'tools', 'build_kit_packages.json')
|
||||
if os.path.isfile(pins_path):
|
||||
@@ -514,9 +528,8 @@ class Release:
|
||||
'-DCMAKE_BUILD_TYPE=Release', '-DCMAKE_C_COMPILER=' + b('gcc'), '-DCMAKE_CXX_COMPILER=' + b('g++'),
|
||||
'-DCMAKE_RC_COMPILER=' + b('windres'), '-DCMAKE_MAKE_PROGRAM=' + b('ninja'),
|
||||
'-DFETCHCONTENT_FULLY_DISCONNECTED=ON',
|
||||
'-DFETCHCONTENT_SOURCE_DIR_RAYLIB=' + os.path.join(deps, 'raylib-src').replace('\\', '/'),
|
||||
'-DFETCHCONTENT_SOURCE_DIR_SDL3=' + os.path.join(deps, 'sdl3-src').replace('\\', '/'),
|
||||
'-DFETCHCONTENT_SOURCE_DIR_IMGUI=' + os.path.join(deps, 'imgui-src').replace('\\', '/'),
|
||||
'-DFETCHCONTENT_SOURCE_DIR_RLIMGUI=' + os.path.join(deps, 'rlimgui-src').replace('\\', '/'),
|
||||
'-DLAUNCHER_FONT_DIR=' + self.font_dir().replace('\\', '/'),
|
||||
'-DLAUNCHER_VERSION=' + self.version, '-DLAUNCHER_COMMIT=' + self.commit] + self.rc_flags(),
|
||||
env=env, logfile=logf)
|
||||
@@ -550,10 +563,10 @@ class Release:
|
||||
def step_licenses(self):
|
||||
lic = os.path.join(self.stage, 'LICENSES')
|
||||
rmtree(lic)
|
||||
# The code: TMB_Recomp's own files are MIT (the repository's LICENSE); PS2Recomp, the runtime and recompiler
|
||||
# in source\PS2Recomp, is GPL-3.0 (the game a player builds links it: a GPL-3.0 combined work).
|
||||
# The code: TMB_Recomp's own files are MIT (the repository's LICENSE); BozoEngine, the recompiler and runtime
|
||||
# in source\BozoEngine, is MIT too.
|
||||
for name, src in (('TMB_Recomp', os.path.join(self.source, 'LICENSE')),
|
||||
('PS2Recomp', os.path.join(self.source, 'PS2Recomp', '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))
|
||||
@@ -624,9 +637,8 @@ class Release:
|
||||
'',
|
||||
'TMB_Recomp (source\\, this release\'s code; MIT, LICENSES\\TMB_Recomp)',
|
||||
' https://github.com/%s/tree/%s' % (REPO, self.commit),
|
||||
'PS2Recomp, the runtime and recompiler (source\\PS2Recomp; GPL-3.0, LICENSES\\PS2Recomp): the game you',
|
||||
'build links its runtime, so that game is a GPL-3.0 combined work.',
|
||||
' PS2Recomp fork: https://github.com/%s/tree/%s' % (FORK_REPO, self.fork_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),
|
||||
' 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:',
|
||||
@@ -660,8 +672,8 @@ class Release:
|
||||
'4. Libraries built from source on your PC (kit\\deps, the sources themselves):',
|
||||
]
|
||||
for name, info in sorted(m['deps'].items()):
|
||||
lines.append(' %-12s %-18s %s commit %s (%s)' % (name, info['tag'], info['repository'], info['commit'],
|
||||
info['license']))
|
||||
lines.append(' %-6s %s (%s)' % (name, info['version'], info['license']))
|
||||
lines.append(' %s SHA-256 %s' % (info['url'], info['sha256']))
|
||||
lines += [
|
||||
'',
|
||||
'Written offer: for at least three years from the date of this release, the authors (The Bozos,',
|
||||
@@ -754,7 +766,14 @@ class Release:
|
||||
# The changelog at the top, for players (Notepad) and the launcher's "What's new": the commit's, CRLF.
|
||||
text = self.changelog_text()
|
||||
if text is not None:
|
||||
write_text(os.path.join(self.stage, 'CHANGELOG.md'), text.replace('\r\n', '\n'), crlf=True)
|
||||
text = text.replace('\r\n', '\n')
|
||||
if changelog_section(text, self.version) is None and self.args.allow_missing_changelog:
|
||||
# A test build (--allow-missing-changelog): a section of its own, so "What's new" and the launcher's
|
||||
# self-check find one for this version.
|
||||
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, crlf=True)
|
||||
|
||||
# -- the changelog
|
||||
|
||||
@@ -784,9 +803,9 @@ class Release:
|
||||
if problems:
|
||||
raise ReleaseError('the release folder holds what looks like game data:\n ' + '\n '.join(problems[:20]))
|
||||
t = time.time()
|
||||
# The folder in the zip is TMB_Recomp, not TMB_Recomp-<version>: a new release unzipped where the last one
|
||||
# was replaces it (and keeps build\ and game\, so Rebuild only does what changed).
|
||||
zip_dir(self.stage, self.zip, NAME, self.zip_time())
|
||||
# The folder in the zip is TMB_Recomp_Bozo, not TMB_Recomp-<version>-bozo: a new release unzipped where the
|
||||
# last one was replaces it (and keeps build\ and game\, so Rebuild only does what changed).
|
||||
zip_dir(self.stage, self.zip, TOP, self.zip_time())
|
||||
# The names once more, as the zip has them.
|
||||
with zipfile.ZipFile(self.zip) as zf:
|
||||
names = zf.namelist()
|
||||
@@ -799,6 +818,15 @@ class Release:
|
||||
% (os.path.basename(self.zip), len(names), os.path.getsize(self.zip) / 1e6, dir_size(self.stage) / 1e6,
|
||||
time.time() - t, self.zip_sha256))
|
||||
|
||||
def step_migration_zip(self):
|
||||
"""The same BozoEngine-only install under the old folder/asset name, for existing launchers' Update."""
|
||||
zip_dir(self.stage, self.migration_zip, NAME, self.zip_time())
|
||||
problems = verify_zip(self.migration_zip, top=NAME)
|
||||
if problems:
|
||||
raise ReleaseError('invalid migration zip:\n ' + '\n '.join(problems[:20]))
|
||||
self.migration_sha256 = write_sha256(self.migration_zip)
|
||||
log(' %s: SHA-256 %s' % (os.path.basename(self.migration_zip), self.migration_sha256))
|
||||
|
||||
def step_notes(self):
|
||||
sources = os.path.isfile(self.sources_zip + '.sha256')
|
||||
lines = [
|
||||
@@ -810,20 +838,26 @@ class Release:
|
||||
'1. `%s.zip` below. Check its SHA-256 before running anything:' % self.name,
|
||||
' `Get-FileHash .\\%s.zip` (PowerShell) must print' % self.name, '',
|
||||
' ```', ' %s' % self.zip_sha256.upper(), ' ```', '',
|
||||
'Requires Windows 10 version 1903 or newer (or Windows 11), an AVX2 and FMA capable CPU, and OpenGL 3.3.', '',
|
||||
'2. Unzip it anywhere you like except Program Files, with about 10 GB free, and double-click '
|
||||
'**TMB Launcher.exe**. It is not signed: on *Windows protected your PC*, click **More info**, then '
|
||||
'**Run anyway**.',
|
||||
'3. Select your USA disc image (SCUS-97101), **Prepare the game** (a few minutes, once), **Play**.', '',
|
||||
'Updating from an earlier release: unzip this one where you unzipped it (the zip holds a `TMB_Recomp` '
|
||||
'folder; replace the files), then **Rebuild now** when the launcher offers it: only what changed is built '
|
||||
'again. Saves and settings are in `%APPDATA%\\TMB_Recomp` and stay.',
|
||||
'For a new/separate installation, use `%s.zip` (`%s/`). ' % (self.name, TOP) +
|
||||
'For an existing v0.3.2 installation, use the launcher\'s **Update**, or extract `%s` over its ' %
|
||||
os.path.basename(self.migration_zip) +
|
||||
'`TMB_Recomp/` installation. Both ZIPs contain the same BozoEngine payload; neither retains the old runtime.',
|
||||
'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.',
|
||||
'',
|
||||
'## Build information', '',
|
||||
'- Code: %s (`%s`), PS2Recomp fork `%s`' % (REPO, self.commit, self.fork_commit),
|
||||
'- Code: %s (`%s`), BozoEngine `%s`' % (REPO, self.commit, self.engine_commit),
|
||||
'- 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']),
|
||||
'- `%s.zip`: %.1f MB, SHA-256 `%s`' % (self.name, os.path.getsize(self.zip) / 1e6, self.zip_sha256),
|
||||
'- `%s`: the same BozoEngine build in `TMB_Recomp/`, for the previous launcher\'s in-place update; '
|
||||
'SHA-256 `%s`' % (os.path.basename(self.migration_zip), self.migration_sha256),
|
||||
]
|
||||
if sources:
|
||||
with open(self.sources_zip + '.sha256') as f:
|
||||
@@ -832,9 +866,8 @@ class Release:
|
||||
sdig))
|
||||
lines += [
|
||||
'', '## Source code and licences', '',
|
||||
'The code is in the zip (`source\\`) and at the commit above: our own code under the MIT licence, '
|
||||
'PS2Recomp (the runtime and recompiler it is built on) under GPL-3.0, which makes the game you build a '
|
||||
'GPL-3.0 combined work. The build kit redistributes unmodified '
|
||||
'The code is in the zip (`source\\`) and at the commit above: our own code and BozoEngine (the recompiler '
|
||||
'and runtime it is built on) under the MIT licence. The build kit redistributes unmodified '
|
||||
'GPL / LGPL programs (GCC, binutils, mingw-w64, the DLLs CMake loads) and FFmpeg (LGPL-2.1+): '
|
||||
'`LICENSES\\` in the zip has their licences, and `LICENSES\\SOURCES.txt` lists each package with its exact '
|
||||
'source on repo.msys2.org.' +
|
||||
@@ -853,7 +886,7 @@ class Release:
|
||||
return info['version'] if info else '?'
|
||||
|
||||
def publish(self):
|
||||
assets = [self.zip, self.zip + '.sha256']
|
||||
assets = [self.zip, self.zip + '.sha256', self.migration_zip, self.migration_zip + '.sha256']
|
||||
if os.path.isfile(self.sources_zip):
|
||||
assets += [self.sources_zip, self.sources_zip + '.sha256']
|
||||
else:
|
||||
@@ -893,6 +926,9 @@ class Release:
|
||||
raise ReleaseError('%s:\n %s' % (self.zip, '\n '.join(problems[:40])))
|
||||
if not sha256_matches(self.zip):
|
||||
raise ReleaseError('%s does not match its .sha256' % self.zip)
|
||||
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)
|
||||
self.publish()
|
||||
|
||||
def main(self):
|
||||
@@ -904,7 +940,7 @@ class Release:
|
||||
('licenses', self.step_licenses), ('readme', self.step_readme)]
|
||||
if self.args.with_sources:
|
||||
steps.append(('sources', self.step_sources))
|
||||
steps += [('zip', self.step_zip), ('notes', self.step_notes)]
|
||||
steps += [('zip', self.step_zip), ('migration zip', self.step_migration_zip), ('notes', self.step_notes)]
|
||||
if self.args.publish:
|
||||
steps.append(('publish', self.publish))
|
||||
t0 = time.time()
|
||||
@@ -937,18 +973,20 @@ def changelog_section(text, version):
|
||||
return None
|
||||
|
||||
|
||||
def verify_zip(path):
|
||||
def verify_zip(path, top=TOP):
|
||||
"""The zip audited as the release folder is (--verify-zip): names of the game's files or the build's folders, ELF
|
||||
and ISO9660 contents, the top folder, the files a release must have. Problems as a list of strings."""
|
||||
problems = []
|
||||
with zipfile.ZipFile(path) as zf:
|
||||
names = zf.namelist()
|
||||
tops = set(n.split('/', 1)[0] for n in names)
|
||||
if tops != {NAME}:
|
||||
problems.append('the zip\'s top folders are %s, expected %s only' % (sorted(tops), NAME))
|
||||
if tops != {top}:
|
||||
problems.append('the zip\'s top folders are %s, expected %s only' % (sorted(tops), top))
|
||||
for info in zf.infolist():
|
||||
n = info.filename
|
||||
rel = n.split('/', 1)[1] if '/' in n else n
|
||||
if rel.replace('\\', '/').lower().startswith('source/ps2recomp/'):
|
||||
problems.append('%s: retired runtime in a BozoEngine-only release' % n)
|
||||
if n.endswith('/'):
|
||||
if game_name(rel):
|
||||
problems.append('%s: a generated / game folder' % n)
|
||||
@@ -962,10 +1000,11 @@ def verify_zip(path):
|
||||
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',
|
||||
'LICENSES/PS2Recomp/LICENSE', 'source/release.ini', 'kit/kit_manifest.json',
|
||||
'kit/python/python.exe', 'source/tools/tmb_build.py'):
|
||||
if '%s/%s' % (NAME, need) not in names:
|
||||
problems.append('%s/%s is missing' % (NAME, need))
|
||||
'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'):
|
||||
if '%s/%s' % (top, need) not in names:
|
||||
problems.append('%s/%s is missing' % (top, need))
|
||||
return problems
|
||||
|
||||
|
||||
@@ -1007,12 +1046,10 @@ def licence_files_in_source_package(path):
|
||||
LICENSES_README = """{name}: licences
|
||||
|
||||
TMB_Recomp\\LICENSE TMB_Recomp's own code in source\\ (MIT)
|
||||
PS2Recomp\\LICENSE PS2Recomp, the runtime and recompiler in source\\PS2Recomp (GPL-3.0); the game
|
||||
you build links its runtime, so that game is a GPL-3.0 combined work
|
||||
BozoEngine\\LICENSE BozoEngine, the recompiler and runtime in source\\BozoEngine (MIT)
|
||||
kit\\ the build kit's components: toolchain\\<MSYS2 package> (GCC, binutils, mingw-w64,
|
||||
winpthreads, CMake, Ninja and the DLLs they load), ffmpeg\\, python\\
|
||||
libraries\\ the libraries compiled into the game and the launcher (raylib, Dear ImGui, rlImGui,
|
||||
ELFIO, toml11, fmt, libdwarf, rabbitizer)
|
||||
libraries\\ the libraries compiled into the game and the launcher (SDL3, Dear ImGui)
|
||||
launcher-font-exo2\\ the launcher's font, Exo 2 (SIL Open Font License 1.1)
|
||||
SOURCES.txt where the source of every component is, with the exact MSYS2 source packages
|
||||
|
||||
@@ -1027,6 +1064,7 @@ 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 Windows 10 version 1903 or newer (or Windows 11), an AVX2 and FMA capable CPU, and OpenGL 3.3.
|
||||
You need a disc image of the USA release (SCUS-97101): a .iso, or a .bin with its .cue.
|
||||
The European disc is not supported.
|
||||
|
||||
@@ -1037,7 +1075,7 @@ Before you start: check the download
|
||||
|
||||
Install
|
||||
1. Unzip the whole zip anywhere you like, with about 10 GB free, for example into D:\\Games: that makes
|
||||
D:\\Games\\TMB_Recomp. Not in "Program Files" (the launcher writes the game next to itself).
|
||||
D:\\Games\\TMB_Recomp_Bozo (TMB_Recomp for the migration ZIP). Not in "Program Files" (the launcher writes the game next to itself).
|
||||
Keep the folders together: TMB Launcher.exe, source\\ and kit\\.
|
||||
2. Double-click "TMB Launcher.exe". It is not signed, so Windows may show
|
||||
"Windows protected your PC": click "More info", then "Run anyway".
|
||||
@@ -1045,6 +1083,10 @@ Install
|
||||
4. Click "Prepare the game". It takes a few minutes, once. You can stop it; it continues later.
|
||||
5. Click "Play". In the game, F2 opens the settings (controls, video, cheats).
|
||||
|
||||
Game speed and effects
|
||||
The game updates at 60 Hz; movies keep their original cadence. Heat haze around fire and explosions is on
|
||||
by default. Set BOZO_HEAT_HAZE=0 before launching to disable it for comparisons with the older PC build.
|
||||
|
||||
Your saves and settings
|
||||
%APPDATA%\\TMB_Recomp (the launcher's Maintenance tab opens it). They stay when you update.
|
||||
|
||||
@@ -1061,8 +1103,8 @@ 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\\ (SOURCES.txt says where every source is). Our code is MIT; PS2Recomp,
|
||||
the runtime it is built on, is GPL-3.0, and so is the game you build with it.
|
||||
Licences and source code: LICENSES\\ (SOURCES.txt says where every source is). 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.
|
||||
|
||||
@@ -1071,6 +1113,7 @@ An unofficial fan project, not affiliated with or endorsed by them.
|
||||
De quoi s'agit-il
|
||||
Une version PC native de Twisted Metal: Black (PS2), construite sur votre PC à partir de VOTRE PROPRE disque.
|
||||
Rien du jeu n'est dans ce téléchargement : aucun fichier du jeu, aucun code issu du jeu.
|
||||
Nécessite Windows 10 version 1903 ou ultérieure (ou Windows 11), un processeur compatible AVX2 et FMA, et OpenGL 3.3.
|
||||
Il vous faut une image disque de la version américaine (SCUS-97101) : un .iso, ou un .bin avec son .cue.
|
||||
Le disque européen n'est pas pris en charge.
|
||||
|
||||
@@ -1081,7 +1124,7 @@ Avant de commencer : vérifiez le téléchargement
|
||||
|
||||
Installation
|
||||
1. Décompressez tout le zip où vous voulez, avec environ 10 Go libres, par exemple dans D:\\Jeux : cela donne
|
||||
D:\\Jeux\\TMB_Recomp. Pas dans « Program Files » (le lanceur écrit le jeu à côté de lui).
|
||||
D:\\Jeux\\TMB_Recomp_Bozo (TMB_Recomp pour le ZIP de migration). Pas dans « Program Files » (le lanceur écrit le jeu à côté de lui).
|
||||
Gardez les dossiers ensemble : TMB Launcher.exe, source\\ et kit\\.
|
||||
2. Double-cliquez sur « TMB Launcher.exe ». Il n'est pas signé : si Windows affiche
|
||||
« Windows a protégé votre ordinateur », cliquez sur « Informations complémentaires », puis « Exécuter quand même ».
|
||||
@@ -1089,6 +1132,10 @@ Installation
|
||||
4. Cliquez sur « Préparer le jeu ». Cela prend quelques minutes, une seule fois. Vous pouvez l'arrêter ; la suite reprendra.
|
||||
5. Cliquez sur « Jouer ». En jeu, F2 ouvre les réglages (commandes, vidéo, astuces).
|
||||
|
||||
Vitesse et effets
|
||||
Le jeu tourne à 60 Hz ; les vidéos conservent leur cadence d'origine. La distorsion de chaleur autour des
|
||||
flammes et explosions est activée par défaut. Définissez BOZO_HEAT_HAZE=0 avant de lancer le jeu pour la désactiver.
|
||||
|
||||
Vos sauvegardes et réglages
|
||||
%APPDATA%\\TMB_Recomp (l'onglet Maintenance du lanceur l'ouvre). Ils restent lors d'une mise à jour.
|
||||
|
||||
@@ -1106,7 +1153,7 @@ Aide
|
||||
Si la préparation échoue, le bouton « Copier les détails » du lanceur copie ce dont nous avons besoin.
|
||||
|
||||
Licences et code source : LICENSES\\ (SOURCES.txt indique où se trouve chaque source). Notre code est sous
|
||||
licence MIT ; PS2Recomp, le moteur sur lequel il repose, est sous GPL-3.0, tout comme le jeu que vous construisez.
|
||||
licence MIT, tout comme BozoEngine, le recompilateur et le moteur sur lesquels il repose.
|
||||
Twisted Metal: Black (c) Sony Interactive Entertainment, développé par Incognito Entertainment.
|
||||
Un projet de fans non officiel, ni affilié ni approuvé par eux.
|
||||
|
||||
|
||||
+21
-7
@@ -1,15 +1,20 @@
|
||||
#!/usr/bin/env python3
|
||||
"""A PS2X_PAD_SCRIPT that plays: the menu presses into the first match (it starts about 150 s in), then accelerating,
|
||||
"""A frame-keyed BozoEngine pad script: menu presses into the first match (about 150 s in), then accelerating,
|
||||
steering both ways, firing (R1, L1, CIRCLE), switching weapons and braking until `end` seconds.
|
||||
|
||||
PS2X_PAD_SCRIPT="$(tools/play_script.py 600)" timeout 600 build/game_us/PS2Recomp/ps2xRuntime/ps2EntryRunner game_us/SCUS_971.01
|
||||
python tools/play_script.py 600 --out controls.txt
|
||||
bash scripts/run_native.sh --pad-script controls.txt
|
||||
|
||||
A car standing still sends few sound commands; this one made the 989snd freeze (fixed in the fork, RECOMP_NOTES
|
||||
"Freeze while playing") happen within 5 minutes.
|
||||
Times are authored in seconds, then converted to the game's native 60 Hz frame clock.
|
||||
"""
|
||||
import sys
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
|
||||
end = float(sys.argv[1]) if len(sys.argv) > 1 else 600
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('end', nargs='?', type=float, default=600)
|
||||
parser.add_argument('--out', type=Path)
|
||||
args = parser.parse_args()
|
||||
end = args.end
|
||||
entries = ['25:CROSS/300'] + [f'{t}:CROSS/250' for t in range(60, 141, 6)]
|
||||
t = 152.0
|
||||
while t < end:
|
||||
@@ -26,4 +31,13 @@ for period, button, ms in ((0.6, 'R1', 150), (1.7, 'L1', 150), (2.9, 'CIRCLE', 1
|
||||
while t < end:
|
||||
entries.append(f'{t:.1f}:{button}/{ms}')
|
||||
t += period
|
||||
print(','.join(entries))
|
||||
frames = []
|
||||
for entry in entries:
|
||||
seconds, press = entry.split(':')
|
||||
button, milliseconds = press.split('/')
|
||||
frames.append(f'{round(float(seconds) * 60)}:{button}/{max(1, round(float(milliseconds) * .06))}')
|
||||
text = ','.join(frames) + '\n'
|
||||
if args.out:
|
||||
args.out.write_text(text, encoding='utf-8')
|
||||
else:
|
||||
print(text, end='')
|
||||
+268
-270
@@ -1,43 +1,43 @@
|
||||
#!/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.
|
||||
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).
|
||||
|
||||
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)
|
||||
|
||||
Steps (each skipped when an earlier run finished it with the same inputs; --redo <step> runs it and the ones after
|
||||
again):
|
||||
again; within a step CMake and Ninja rebuild only what changed):
|
||||
verify the disc image or folder: ISO9660 (.iso, .bin/.cue), SYSTEM.CNF's boot file, SCUS_971.01's SHA-1
|
||||
extract the disc's files into <out>/TMB/disc (the runtime's cdrom0:), no outside tool (PS2Recomp/tools/ps2_disc.py),
|
||||
and the image itself as <out>/TMB/disc.iso (the game reads raw sectors too): a hard link to the .iso on
|
||||
the same drive, else a copy (a .bin / .cue converted)
|
||||
tools ps2_recomp and ps2_vu_aot: --tools <dir> (prebuilt), or built from PS2Recomp with the toolchain
|
||||
recompile ps2_recomp (recomp/tmb_scus97101.toml) and ps2_vu_aot (VU1 microcode) -> <out>/generated
|
||||
packs the texture and mesh packs (tools/tmb_texture_pack.py, tools/tmb_mesh_pack.py) -> <out>/generated
|
||||
iop the IOP modules loaded offline from the disc at their bases (recomp/tmb_iop_modules.json,
|
||||
PS2Recomp/tools/irx_load.py) and recompiled (PS2Recomp/tools/iop_recomp.py) -> <out>/generated/iop
|
||||
configure cmake (Ninja) of the runner with the generated code
|
||||
compile the runner (ps2EntryRunner)
|
||||
stage <out>/TMB: the executable, the DLLs it loads from the toolchain, the packs, "Play TMB.cmd"
|
||||
extract the files the build reads into <out>/disc: SCUS_971.01 and the packs' files (.TEX, .RTX, .NGP, .PTR), no
|
||||
outside tool (BozoEngine's tools/native_pack/ps2_disc.py); and the image itself as <game>/disc.iso (the
|
||||
game reads the disc from it): a hard link to the .iso on the same drive, else a copy (a .bin / .cue
|
||||
converted)
|
||||
configure cmake (Ninja) of TMB on BozoEngine (cmake/bozo.cmake): SDL3 and Dear ImGui from the kit's
|
||||
deps/, FFmpeg from the kit's ffmpeg/
|
||||
tools BozoEngine's recompiler and externals writer (bozo-recomp, bozo-externals), built from its sources
|
||||
recompile the externals list (the ELF's library symbols, TMB's overrides, recomp/tmb_stubs.txt) and bozo-recomp
|
||||
-> <out>/build/tmb_gen
|
||||
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"
|
||||
|
||||
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/), the prebuilt recompilers (tools/) and an embeddable Python. Used
|
||||
when it sits in <TMB_Recomp>/kit or next to the TMB_Recomp folder (<parent>/kit), or with --kit <dir> (--no-kit: not
|
||||
used). With it nothing else is needed (no MSYS2, git, network or installed Python), and the runner is the player's
|
||||
build: FFmpeg from the kit (no pkg-config, no FFmpeg DLLs: the game folder gets the exe and the three GCC runtime
|
||||
DLLs), paraLLEl-GS left out (PS2X_ENABLE_PARALLEL_GS=OFF, a GS-emulation diagnostic the native port never uses).
|
||||
FFmpeg (ffmpeg/), the libraries' sources (deps/: SDL3, Dear ImGui) and an embeddable Python. Used when it sits in
|
||||
<TMB_Recomp>/kit or next to the TMB_Recomp folder (<parent>/kit), or with --kit <dir> (--no-kit: not used). With it
|
||||
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
|
||||
|
||||
Without a kit: --toolchain <dir> (a folder whose bin/ has g++, cmake, ninja, pkg-config: an MSYS2 UCRT64 prefix such
|
||||
as C:/msys64/ucrt64), else the PATH, else C:/msys64/ucrt64; FFmpeg through pkg-config; FetchContent's sources from the
|
||||
network (git) unless --fetch-cache <dir> holds <name>-src folders. --toolchain, --tools and --fetch-cache also
|
||||
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
|
||||
(pinned URLs and SHA-256) unless --fetch-cache <dir> holds sdl3-src and imgui-src. --toolchain and --fetch-cache also
|
||||
override the kit's.
|
||||
|
||||
A player's build (the default with the kit, --debug-info no): the runner without debug information, the same code as
|
||||
RelWithDebInfo (its -O2 flags without -g; GCC's -g never changes the code), stripped again when staged: 45 MB instead
|
||||
of 613. --game <dir> stages the game somewhere else than <out>/TMB (the launcher: <release>/game). --check only checks
|
||||
the disc (no work folder): OK <message>, or ERROR verify <message> and exit code 1.
|
||||
--game <dir> stages the game somewhere else than <out>/TMB (the launcher: <release>/game). --check only checks the disc
|
||||
(no work folder): OK <message>, or ERROR verify <message> and exit code 1.
|
||||
Every successful run writes <game>/built_from.ini: the release stamp (<TMB_Recomp>/release.ini, from
|
||||
tools/make_release.py) of the code the game was built from; the launcher offers Rebuild when the source's differs.
|
||||
|
||||
@@ -52,7 +52,7 @@ Output for a launcher, one line each on stdout (everything else goes to <out>/lo
|
||||
Standard library only (Python 3.8+): runs on a bundled Windows embeddable Python.
|
||||
"""
|
||||
import argparse
|
||||
import filecmp
|
||||
import glob
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
@@ -64,9 +64,24 @@ import sys
|
||||
import time
|
||||
|
||||
ROOT = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))
|
||||
sys.path.insert(0, os.path.join(ROOT, 'PS2Recomp', 'tools'))
|
||||
import ps2_disc # noqa: E402
|
||||
import irx_load # noqa: E402
|
||||
|
||||
|
||||
def configure_gcc_paths(env, compiler_bin):
|
||||
"""Keep MinGW's linker paths on the ASCII alias, even if GCC resolves its executable's junction.
|
||||
|
||||
GCC_EXEC_PREFIX also selects startup objects; LIBRARY_PATH selects the native static libraries.
|
||||
See https://gcc.gnu.org/onlinedocs/gcc/Environment-Variables.html .
|
||||
"""
|
||||
prefix = os.path.dirname(os.path.abspath(compiler_bin))
|
||||
gcc = os.path.join(prefix, 'lib', 'gcc')
|
||||
versions = sorted(p for p in glob.glob(os.path.join(gcc, '*', '*')) if os.path.isdir(p))
|
||||
if os.name != 'nt' or not versions:
|
||||
return
|
||||
env['GCC_EXEC_PREFIX'] = gcc.replace('\\', '/') + '/'
|
||||
libraries = versions + [os.path.join(prefix, 'x86_64-w64-mingw32', 'lib'), os.path.join(prefix, 'lib')]
|
||||
env['LIBRARY_PATH'] = os.pathsep.join(p.replace('\\', '/') for p in libraries if os.path.isdir(p))
|
||||
ENGINE = os.path.join(ROOT, 'BozoEngine') # --engine replaces it
|
||||
ps2_disc = None # BozoEngine's tools/native_pack/ps2_disc.py, imported by load_engine()
|
||||
|
||||
ELF_NAME = 'SCUS_971.01'
|
||||
ELF_SHA1 = '3ff17f4897552e355d0bb8c3abfa5125fe3ff2ef'
|
||||
@@ -74,11 +89,12 @@ OTHER_RELEASES = {
|
||||
'SCES_503.60': 'the European release (SCES-50360)',
|
||||
'SCUS_971.01': 'the USA release',
|
||||
}
|
||||
STEPS = ['verify', 'extract', 'tools', 'recompile', 'packs', 'iop', 'configure', 'compile', 'stage']
|
||||
FETCH_NAMES = ['raylib', 'imgui', 'rlimgui', 'parallel_gs', 'granite',
|
||||
'elfio', 'toml11', 'fmt', 'libdwarf', 'rabbitizer', 'nlohmann_json']
|
||||
LAUNCH_ENV = [('TMB_NATIVE', '1'), ('PS2X_SPU2_WALLCLOCK', '1'), ('PS2X_IOP_WALLCLOCK', '1'),
|
||||
('PS2X_GS_RENDERER', 'native'), ('PS2X_IOP_NATIVE', '1')]
|
||||
# The disc's files the packs read (cmake/bozo.cmake's own extraction takes the same).
|
||||
PACK_EXTS = ('.TEX', '.RTX', '.NGP', '.PTR')
|
||||
STEPS = ['verify', 'extract', 'configure', 'tools', 'recompile', 'packs', 'compile', 'stage']
|
||||
# FetchContent sources (BozoEngine's runtime/CMakeLists.txt): <name>-src in the kit's deps/.
|
||||
FETCH_NAMES = ['sdl3', 'imgui']
|
||||
GAME_EXE = 'tmb'
|
||||
EXE = '.exe' if os.name == 'nt' else ''
|
||||
KIT_MANIFEST = 'kit_manifest.json'
|
||||
|
||||
@@ -91,6 +107,20 @@ def emit(*parts):
|
||||
print(' '.join(str(p) for p in parts), flush=True)
|
||||
|
||||
|
||||
def load_engine(path=None):
|
||||
"""BozoEngine's tree (--engine, else the submodule) and its disc reader."""
|
||||
global ENGINE, ps2_disc
|
||||
if path:
|
||||
ENGINE = os.path.abspath(path)
|
||||
tools = os.path.join(ENGINE, 'tools', 'native_pack')
|
||||
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)
|
||||
sys.path.insert(0, tools)
|
||||
import ps2_disc as module # noqa: E402
|
||||
ps2_disc = module
|
||||
|
||||
|
||||
def sha1_file(path):
|
||||
h = hashlib.sha1()
|
||||
with open(path, 'rb') as f:
|
||||
@@ -125,36 +155,12 @@ def tree_stamp(folder, exts=None):
|
||||
return fingerprint(out)
|
||||
|
||||
|
||||
def sync_tree(src, dst):
|
||||
"""Copies src over dst comparing contents (like rsync -c --delete): unchanged files keep their mtime, so ninja
|
||||
only rebuilds what changed. Returns the number of files written."""
|
||||
changed = 0
|
||||
wanted = set()
|
||||
for dirpath, _dirs, files in os.walk(src):
|
||||
rel = os.path.relpath(dirpath, src)
|
||||
out_dir = os.path.normpath(os.path.join(dst, rel))
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
wanted.add(os.path.normcase(out_dir))
|
||||
for name in files:
|
||||
s, d = os.path.join(dirpath, name), os.path.join(out_dir, name)
|
||||
wanted.add(os.path.normcase(d))
|
||||
if os.path.exists(d) and filecmp.cmp(s, d, shallow=False):
|
||||
continue
|
||||
shutil.copyfile(s, d)
|
||||
changed += 1
|
||||
for dirpath, dirs, files in os.walk(dst, topdown=False):
|
||||
for name in files:
|
||||
p = os.path.join(dirpath, name)
|
||||
if os.path.normcase(p) not in wanted:
|
||||
os.remove(p)
|
||||
if os.path.normcase(os.path.normpath(dirpath)) not in wanted and not os.listdir(dirpath):
|
||||
os.rmdir(dirpath)
|
||||
return changed
|
||||
SOURCE_EXTS = ('.cpp', '.h', '.hpp', '.inl', '.c', '.txt', '.cmake', '.rc', '.ico', '.manifest', '.py')
|
||||
|
||||
|
||||
# ---- PE imports (the DLLs the runner needs, found in the toolchain's bin) ----
|
||||
# ---- PE imports (the DLLs the game needs, found in the toolchain's bin) ----
|
||||
|
||||
# windres (the runner's icon, version and UTF-8 manifest resources) runs its preprocessor through popen, that is
|
||||
# windres (the game's icon, version and UTF-8 manifest resources) runs its preprocessor through popen, that is
|
||||
# cmd /c: by default as "<its own folder>\gcc" -E ... "<the .rc>". With a space in the toolchain's path (C:\Users\Jean
|
||||
# Dupont\..., D:\Games\TMB Recomp\kit) and a second quoted argument, cmd strips the outer quotes and runs
|
||||
# "D:\Games\TMB" ("preprocessing failed"). The bare name, found on the PATH tmb_build puts the toolchain first on, has no
|
||||
@@ -234,8 +240,7 @@ class Build:
|
||||
self.args = args
|
||||
self.out = os.path.abspath(args.out)
|
||||
self.game = os.path.abspath(args.game) if args.game else os.path.join(self.out, 'TMB')
|
||||
self.disc_dir = os.path.join(self.game, 'disc')
|
||||
self.gen = os.path.join(self.out, 'generated')
|
||||
self.disc_dir = os.path.join(self.out, 'disc')
|
||||
self.cmake_build = os.path.join(self.out, 'build')
|
||||
self.logs = os.path.join(self.out, 'logs')
|
||||
self.state_path = os.path.join(self.out, 'tmb_build_state.json')
|
||||
@@ -245,6 +250,9 @@ class Build:
|
||||
self.state = json.load(f)
|
||||
except (OSError, ValueError):
|
||||
self.state = {}
|
||||
if self.state.get('engine') != 'bozo':
|
||||
# A work folder of the fork's build (generated/, its CMake cache): its step records mean nothing here.
|
||||
self.state = {'engine': 'bozo'}
|
||||
self.toolchain_bin = None
|
||||
self.env = dict(os.environ)
|
||||
self.step = None
|
||||
@@ -253,10 +261,9 @@ class Build:
|
||||
if self.kit:
|
||||
# The kit's parts unless the command line names others.
|
||||
args.toolchain = args.toolchain or os.path.join(self.kit, 'ucrt64')
|
||||
args.tools = args.tools or os.path.join(self.kit, 'tools')
|
||||
args.fetch_cache = args.fetch_cache or os.path.join(self.kit, 'deps')
|
||||
self.ffmpeg_root = os.path.join(self.kit, 'ffmpeg')
|
||||
if args.debug_info is None: # a player's build (the kit): no debug information, a 613 MB runner otherwise
|
||||
if args.debug_info is None: # a player's build (the kit): no debug information
|
||||
args.debug_info = 'no' if self.kit else 'yes'
|
||||
|
||||
def save_state(self):
|
||||
@@ -297,8 +304,9 @@ class Build:
|
||||
raise BuildError('%s failed (exit %d); the full output is in %s'
|
||||
% (os.path.basename(cmd[0]), code, self.log_path()))
|
||||
|
||||
def py(self, script, *argv, **kw):
|
||||
self.run([sys.executable, '-I', script] + list(argv), **kw)
|
||||
def cmake_build_targets(self, *targets, percent=None):
|
||||
self.run([self.tool('cmake'), '--build', self.cmake_build, '--target'] + list(targets) +
|
||||
['-j', str(self.args.jobs)], percent=percent)
|
||||
|
||||
# -- inputs
|
||||
|
||||
@@ -325,49 +333,58 @@ class Build:
|
||||
'and ninja in its bin folder (an MSYS2 UCRT64 prefix: C:/msys64/ucrt64)'
|
||||
% (', '.join(cands) or 'PATH'))
|
||||
self.env['PATH'] = self.toolchain_bin + os.pathsep + self.env.get('PATH', '')
|
||||
configure_gcc_paths(self.env, self.toolchain_bin)
|
||||
return self.toolchain_bin
|
||||
|
||||
def tool(self, name):
|
||||
return os.path.join(self.find_toolchain(), name + EXE)
|
||||
|
||||
def toolchain_key(self):
|
||||
self.find_toolchain()
|
||||
return fingerprint(file_stamp(self.tool('gcc')), self.env.get('GCC_EXEC_PREFIX', ''),
|
||||
self.env.get('LIBRARY_PATH', ''))
|
||||
|
||||
def disc_input(self):
|
||||
src = os.path.abspath(self.args.disc)
|
||||
if not os.path.exists(src):
|
||||
raise BuildError('%s does not exist' % src)
|
||||
return src
|
||||
|
||||
def elf(self):
|
||||
return os.path.join(self.disc_dir, ELF_NAME)
|
||||
|
||||
# -- steps
|
||||
|
||||
def key(self, step):
|
||||
"""What a step's result depends on (its inputs and the earlier steps' keys)."""
|
||||
a = self.args
|
||||
prev = lambda s: self.state.get(s, {}).get('key') # noqa: E731
|
||||
if step == 'verify':
|
||||
return fingerprint(file_stamp(self.disc_input()))
|
||||
if step == 'extract':
|
||||
return fingerprint(self.state.get('verify', {}).get('key'))
|
||||
if step == 'tools':
|
||||
return fingerprint(os.path.abspath(a.tools) if a.tools else tree_stamp(
|
||||
os.path.join(ROOT, 'PS2Recomp'), ('.cpp', '.h', '.hpp', '.txt', '.cmake')))
|
||||
if step == 'recompile':
|
||||
return fingerprint(self.state.get('extract', {}).get('key'), self.state.get('tools', {}).get('key'),
|
||||
file_stamp(os.path.join(ROOT, 'recomp', 'tmb_scus97101.toml')))
|
||||
if step == 'packs':
|
||||
return fingerprint(self.state.get('extract', {}).get('key'),
|
||||
[file_stamp(os.path.join(ROOT, 'tools', t)) for t in ('tmb_texture_pack.py', 'tmb_mesh_pack.py')],
|
||||
tree_stamp(os.path.join(ROOT, 'PS2Recomp', 'tools', 'native_pack'), ('.py',)))
|
||||
if step == 'iop':
|
||||
return fingerprint(self.state.get('extract', {}).get('key'),
|
||||
file_stamp(os.path.join(ROOT, 'recomp', 'tmb_iop_modules.json')),
|
||||
[file_stamp(os.path.join(ROOT, 'PS2Recomp', 'tools', t)) for t in ('irx_load.py', 'iop_recomp.py')])
|
||||
return fingerprint(prev('verify'), PACK_EXTS, self.game)
|
||||
if step == 'configure':
|
||||
return fingerprint(self.find_toolchain(), a.build_type, a.debug_info, a.fetch_cache, self.ffmpeg_root,
|
||||
cmake_rc_flags(), [self.state.get(s, {}).get('key') for s in ('recompile', 'packs', 'iop')])
|
||||
self.toolchain_key(), cmake_rc_flags(), ROOT, ENGINE, sys.executable, prev('extract'),
|
||||
[file_stamp(os.path.join(ROOT, p)) for p in ('CMakeLists.txt', 'cmake/bozo.cmake')])
|
||||
if step == 'tools':
|
||||
return fingerprint(prev('configure'), tree_stamp(os.path.join(ENGINE, 'recompiler'), SOURCE_EXTS),
|
||||
tree_stamp(os.path.join(ENGINE, 'tools', 'externals'), SOURCE_EXTS))
|
||||
if step == 'recompile':
|
||||
return fingerprint(prev('tools'), tree_stamp(os.path.join(ROOT, 'runtime'), ('.cpp',)),
|
||||
file_stamp(os.path.join(ROOT, 'recomp', 'tmb_stubs.txt')),
|
||||
file_stamp(os.path.join(ROOT, 'tools', 'tmb_overrides_list.py')))
|
||||
if step == 'packs':
|
||||
return fingerprint(prev('configure'),
|
||||
[file_stamp(os.path.join(ROOT, 'tools', t)) for t in ('tmb_texture_pack.py', 'tmb_mesh_pack.py')],
|
||||
tree_stamp(os.path.join(ENGINE, 'tools', 'native_pack'), ('.py',)))
|
||||
if step == 'compile':
|
||||
return fingerprint(self.state.get('configure', {}).get('key'),
|
||||
tree_stamp(os.path.join(ROOT, 'runtime')),
|
||||
tree_stamp(os.path.join(ROOT, 'PS2Recomp'), ('.cpp', '.h', '.hpp', '.inl', '.txt', '.cmake')))
|
||||
return fingerprint(prev('recompile'), prev('packs'),
|
||||
tree_stamp(os.path.join(ROOT, 'runtime'), SOURCE_EXTS),
|
||||
tree_stamp(os.path.join(ROOT, 'bozo'), SOURCE_EXTS),
|
||||
tree_stamp(os.path.join(ENGINE, 'runtime'), SOURCE_EXTS))
|
||||
if step == 'stage':
|
||||
return fingerprint(self.state.get('compile', {}).get('key'), self.game)
|
||||
return fingerprint(prev('compile'), self.game)
|
||||
raise AssertionError(step)
|
||||
|
||||
def step_verify(self):
|
||||
@@ -414,12 +431,18 @@ class Build:
|
||||
if os.path.isdir(src):
|
||||
image = self.find_folder_image(src)
|
||||
if not image:
|
||||
raise BuildError('the game reads the disc image itself as well as its files: no .iso of the USA disc '
|
||||
'in %s or the folders above it. Pass the .iso (--disc <image>) instead.' % src)
|
||||
raise BuildError('the game reads the disc image itself: no .iso of the USA disc in %s or the folders '
|
||||
'above it. Pass the .iso (--disc <image>) instead.' % src)
|
||||
os.makedirs(self.game, exist_ok=True)
|
||||
marker = os.path.join(self.disc_dir, '.extracted')
|
||||
if os.path.exists(marker):
|
||||
os.remove(marker)
|
||||
self.extract_files(src)
|
||||
if sha1_file(os.path.join(self.disc_dir, ELF_NAME)) != ELF_SHA1:
|
||||
if sha1_file(self.elf()) != ELF_SHA1:
|
||||
raise BuildError("the extracted %s differs from the disc's (disk error?)" % ELF_NAME)
|
||||
# The packs' inputs are ready (cmake/bozo.cmake's TMB_DISC_DIR: the packs depend on this file).
|
||||
with open(marker, 'w') as f:
|
||||
f.write('extracted by tools/tmb_build.py\n')
|
||||
self.place_image(image)
|
||||
|
||||
def find_folder_image(self, folder):
|
||||
@@ -446,10 +469,9 @@ class Build:
|
||||
return None
|
||||
|
||||
def place_image(self, src):
|
||||
"""The game also reads raw sectors (sceCdRead by LBN: the volume descriptor, the directories, then its data
|
||||
files), which the extracted files cannot serve: the runtime reads them from a 2048-byte-sector image of the
|
||||
disc, <game>/disc.iso (TMB_ISO; the runtime also finds it walking up from the ELF's folder). A hard link to the
|
||||
player's .iso when it is on the same drive, else a copy; a .bin / .cue is converted."""
|
||||
"""The game reads the disc from a 2048-byte-sector image of it, <game>/disc.iso (tmb.exe --iso; it also finds
|
||||
it walking up from the ELF's folder). A hard link to the player's .iso when it is on the same drive, else a
|
||||
copy; a .bin / .cue is converted."""
|
||||
dest = os.path.join(self.game, 'disc.iso')
|
||||
disc = ps2_disc.Disc(src)
|
||||
try:
|
||||
@@ -466,9 +488,9 @@ class Build:
|
||||
except OSError:
|
||||
pass
|
||||
free = shutil.disk_usage(self.game).free
|
||||
if free < total * 2048 + (6 << 30):
|
||||
if free < total * 2048 + (2 << 30):
|
||||
raise BuildError('not enough free space on %s for the disc image: %.1f GB free, about %.1f GB needed'
|
||||
% (self.game, free / 2**30, (total * 2048 + (6 << 30)) / 2**30))
|
||||
% (self.game, free / 2**30, (total * 2048 + (2 << 30)) / 2**30))
|
||||
tmp = dest + '.part'
|
||||
with open(tmp, 'wb') as f:
|
||||
lba = 0
|
||||
@@ -481,17 +503,21 @@ class Build:
|
||||
finally:
|
||||
disc.close()
|
||||
|
||||
@staticmethod
|
||||
def wanted(rel):
|
||||
rel = rel.replace('\\', '/')
|
||||
return rel.upper() == ELF_NAME or rel.upper().endswith(PACK_EXTS)
|
||||
|
||||
def extract_files(self, src):
|
||||
"""Only what the build reads: the ELF and the packs' files (resumable: finished files stay)."""
|
||||
os.makedirs(self.disc_dir, exist_ok=True)
|
||||
if os.path.isdir(src):
|
||||
if os.path.normcase(os.path.abspath(src)) == os.path.normcase(self.disc_dir):
|
||||
return
|
||||
files = []
|
||||
for dirpath, _dirs, names in os.walk(src):
|
||||
for n in names:
|
||||
if n.lower() in ('input.ini', 'video.ini'):
|
||||
continue
|
||||
files.append(os.path.relpath(os.path.join(dirpath, n), src))
|
||||
rel = os.path.relpath(os.path.join(dirpath, n), src)
|
||||
if self.wanted(rel):
|
||||
files.append(rel)
|
||||
total = sum(os.path.getsize(os.path.join(src, f)) for f in files) or 1
|
||||
done, last = 0, -1
|
||||
for rel in files:
|
||||
@@ -513,19 +539,17 @@ class Build:
|
||||
return
|
||||
disc = ps2_disc.Disc(src)
|
||||
try:
|
||||
files = [e for e in disc.entries() if not e.is_dir]
|
||||
files = [e for e in disc.entries() if not e.is_dir and self.wanted(e.path)]
|
||||
total = sum(e.size for e in files) or 1
|
||||
free = shutil.disk_usage(self.out).free
|
||||
if free < total + (6 << 30):
|
||||
if free < total + (3 << 30):
|
||||
raise BuildError('not enough free space on %s: %.1f GB free, about %.1f GB needed (the disc\'s files '
|
||||
'and the build)' % (self.out, free / 2**30, (total + (6 << 30)) / 2**30))
|
||||
'and the build)' % (self.out, free / 2**30, (total + (3 << 30)) / 2**30))
|
||||
done, last = 0, -1
|
||||
for e in disc.entries():
|
||||
for e in files:
|
||||
dest = os.path.join(self.disc_dir, e.path)
|
||||
if e.is_dir:
|
||||
os.makedirs(dest, exist_ok=True)
|
||||
continue
|
||||
if not (os.path.exists(dest) and os.path.getsize(dest) == e.size): # resumes: finished files stay
|
||||
os.makedirs(os.path.dirname(dest), exist_ok=True)
|
||||
if not (os.path.exists(dest) and os.path.getsize(dest) == e.size):
|
||||
tmp = dest + '.part'
|
||||
with open(tmp, 'wb') as f:
|
||||
for chunk in disc.image.read_extent(e.lba, e.size):
|
||||
@@ -540,161 +564,91 @@ class Build:
|
||||
emit('PERCENT', 'extract', pct)
|
||||
finally:
|
||||
disc.close()
|
||||
|
||||
def tools_dir(self):
|
||||
if self.args.tools:
|
||||
return os.path.abspath(self.args.tools)
|
||||
return os.path.join(self.out, 'tools-build', 'ps2xRecomp')
|
||||
|
||||
def step_tools(self):
|
||||
if self.args.tools:
|
||||
for t in ('ps2_recomp', 'ps2_vu_aot'):
|
||||
if not os.path.isfile(os.path.join(self.tools_dir(), t + EXE)):
|
||||
raise BuildError('%s%s is not in %s (--tools)' % (t, EXE, self.tools_dir()))
|
||||
return
|
||||
build = os.path.join(self.out, 'tools-build')
|
||||
self.run([self.tool('cmake'), '-S', os.path.join(ROOT, 'PS2Recomp'), '-B', build, '-G', 'Ninja',
|
||||
'-DCMAKE_BUILD_TYPE=Release', '-DPS2X_BUILD_RUNTIME=OFF', '-DPS2X_BUILD_STUDIO=OFF',
|
||||
'-DPS2X_BUILD_TEST=OFF', '-DPS2X_BUILD_ANALYZER=OFF',
|
||||
'-DCMAKE_C_COMPILER=' + self.tool('gcc'), '-DCMAKE_CXX_COMPILER=' + self.tool('g++'),
|
||||
'-DCMAKE_MAKE_PROGRAM=' + self.tool('ninja')] + cmake_rc_flags() + self.fetch_args())
|
||||
self.run([self.tool('cmake'), '--build', build, '--target', 'ps2_recomp', 'ps2_vu_aot', '-j', str(self.args.jobs)],
|
||||
percent=ninja_percent, append=True)
|
||||
|
||||
def step_recompile(self):
|
||||
staging = os.path.join(self.out, 'recomp-staging')
|
||||
shutil.rmtree(staging, ignore_errors=True)
|
||||
os.makedirs(staging)
|
||||
with open(os.path.join(ROOT, 'recomp', 'tmb_scus97101.toml'), encoding='utf-8') as f:
|
||||
toml = f.read()
|
||||
fwd = lambda p: p.replace('\\', '/') # noqa: E731
|
||||
toml = re.sub(r'(?m)^input = .*$', 'input = "%s"' % fwd(os.path.join(self.disc_dir, ELF_NAME)), toml)
|
||||
toml = re.sub(r'(?m)^output = .*$', 'output = "%s/"' % fwd(staging), toml)
|
||||
cfg = os.path.join(self.out, 'tmb_scus97101.toml')
|
||||
with open(cfg, 'w', encoding='utf-8', newline='\n') as f:
|
||||
f.write(toml)
|
||||
self.run([os.path.join(self.tools_dir(), 'ps2_recomp' + EXE), cfg], cwd=ROOT)
|
||||
env = dict(self.env, PS2X_VU_AOT_FAST='1')
|
||||
self.run([os.path.join(self.tools_dir(), 'ps2_vu_aot' + EXE), os.path.join(self.disc_dir, ELF_NAME),
|
||||
os.path.join(staging, 'vu1')], env=env, append=True)
|
||||
# Keep what the other steps write in generated/ (the packs, iop/), refresh the rest by content.
|
||||
for keep in ('tmb_textures.pack', 'tmb_meshes.pack', 'iop'):
|
||||
p = os.path.join(self.gen, keep)
|
||||
if os.path.exists(p):
|
||||
d = os.path.join(staging, keep)
|
||||
if os.path.isdir(p):
|
||||
shutil.copytree(p, d)
|
||||
else:
|
||||
shutil.copyfile(p, d)
|
||||
os.makedirs(self.gen, exist_ok=True)
|
||||
changed = sync_tree(staging, self.gen)
|
||||
shutil.rmtree(staging, ignore_errors=True)
|
||||
emit('INFO', 'recompile', '%d files written' % changed)
|
||||
|
||||
def step_packs(self):
|
||||
elf = os.path.join(self.disc_dir, ELF_NAME)
|
||||
os.makedirs(self.gen, exist_ok=True)
|
||||
for i, (script, argv, name) in enumerate((
|
||||
('tmb_texture_pack.py', [self.disc_dir, elf], 'tmb_textures.pack'),
|
||||
('tmb_mesh_pack.py', [self.disc_dir], 'tmb_meshes.pack'))):
|
||||
tmp = os.path.join(self.gen, name + '.tmp')
|
||||
self.py(os.path.join(ROOT, 'tools', script), *(argv + [tmp]), append=i > 0)
|
||||
os.replace(tmp, os.path.join(self.gen, name))
|
||||
emit('PERCENT', 'packs', 50 * (i + 1))
|
||||
|
||||
def step_iop(self):
|
||||
with open(os.path.join(ROOT, 'recomp', 'tmb_iop_modules.json')) as f:
|
||||
table = json.load(f)['modules']
|
||||
dumps = os.path.join(self.out, 'iopmods')
|
||||
shutil.rmtree(dumps, ignore_errors=True)
|
||||
out = os.path.join(self.gen, 'iop')
|
||||
staging = os.path.join(self.out, 'iop-staging')
|
||||
shutil.rmtree(staging, ignore_errors=True)
|
||||
os.makedirs(staging)
|
||||
with open(self.log_path(), 'w') as log:
|
||||
for m in table:
|
||||
irx = os.path.join(self.disc_dir, *m['file'].split('/'))
|
||||
with open(irx, 'rb') as f:
|
||||
data = f.read()
|
||||
h = '%016x' % irx_load.fnv1a64(data)
|
||||
if h != m['hash']:
|
||||
raise BuildError('%s differs from the USA disc\'s (hash %s, expected %s)' % (m['file'], h, m['hash']))
|
||||
j = irx_load.write_dump(irx, int(m['base'], 16), m['name'], dumps)
|
||||
with open(j) as f:
|
||||
loaded = json.load(f)
|
||||
if loaded['size'] != int(m['size'], 16):
|
||||
raise BuildError('%s loaded as %#x bytes, expected %s' % (m['file'], loaded['size'], m['size']))
|
||||
log.write('%s -> %s\n' % (irx, j))
|
||||
for i, m in enumerate(table):
|
||||
j = os.path.join(dumps, '%s_%06x.json' % (m['name'], int(m['base'], 16)))
|
||||
self.py(os.path.join(ROOT, 'PS2Recomp', 'tools', 'iop_recomp.py'), j, '--out', staging, append=True)
|
||||
emit('PERCENT', 'iop', (i + 1) * 100 // len(table))
|
||||
os.makedirs(out, exist_ok=True)
|
||||
sync_tree(staging, out)
|
||||
shutil.rmtree(staging, ignore_errors=True)
|
||||
emit('INFO', 'extract', '%d files, %.0f MB' % (len(files), total / 1e6))
|
||||
|
||||
def fetch_args(self):
|
||||
if not self.args.fetch_cache:
|
||||
if not shutil.which('git', path=self.env.get('PATH')):
|
||||
raise BuildError('git is needed to download the libraries the build uses (raylib, imgui, ...), or '
|
||||
'pass --fetch-cache <dir> with their sources')
|
||||
return []
|
||||
return [] # CMake downloads the pinned archives (SHA-256 checked)
|
||||
cache = os.path.abspath(self.args.fetch_cache)
|
||||
out = ['-DFETCHCONTENT_FULLY_DISCONNECTED=ON'] if self.kit else [] # never the network
|
||||
for n in FETCH_NAMES:
|
||||
d = os.path.join(cache, n + '-src')
|
||||
if os.path.isdir(d):
|
||||
out.append('-DFETCHCONTENT_SOURCE_DIR_%s=%s' % (n.upper(), d.replace('\\', '/')))
|
||||
elif self.kit:
|
||||
raise BuildError('the build kit has no deps/%s-src: the kit is incomplete or of an older release' % n)
|
||||
return out
|
||||
|
||||
def step_configure(self):
|
||||
# A build folder configured from another path (the release folder moved or renamed, or reached once through
|
||||
# the non-ASCII aliases and once not): CMake refuses its cache or fetches again; start that folder afresh.
|
||||
# the non-ASCII aliases and once not), or a fork build's: CMake refuses its cache; start that folder afresh.
|
||||
cache = os.path.join(self.cmake_build, 'CMakeCache.txt')
|
||||
stamp = os.path.join(self.cmake_build, '.tmb-toolchain-key')
|
||||
toolchain_key = self.toolchain_key()
|
||||
try:
|
||||
with open(stamp, encoding='utf-8') as f:
|
||||
previous_toolchain = f.read().strip()
|
||||
except OSError:
|
||||
previous_toolchain = ''
|
||||
if os.path.isfile(cache):
|
||||
with open(cache, encoding='utf-8', errors='replace') as f:
|
||||
m = re.search(r'^CMAKE_HOME_DIRECTORY:INTERNAL=(.*)$', f.read(), re.M)
|
||||
if m and os.path.normcase(os.path.normpath(m.group(1))) != os.path.normcase(os.path.normpath(ROOT)):
|
||||
emit('INFO', 'configure', 'the build folder was configured from %s: configured again' % m.group(1))
|
||||
text = f.read()
|
||||
m = re.search(r'^CMAKE_HOME_DIRECTORY:INTERNAL=(.*)$', text, re.M)
|
||||
moved = m and os.path.normcase(os.path.normpath(m.group(1))) != os.path.normcase(os.path.normpath(ROOT))
|
||||
if moved or previous_toolchain != toolchain_key or not re.search(r'^BOZO_ENGINE_DIR:PATH=', text, re.M):
|
||||
emit('INFO', 'configure', 'the build folder was configured %s: configured again'
|
||||
% ('from %s' % m.group(1) if moved else 'with another toolchain configuration'))
|
||||
os.remove(cache)
|
||||
shutil.rmtree(os.path.join(self.cmake_build, 'CMakeFiles'), ignore_errors=True)
|
||||
fwd = lambda p: p.replace('\\', '/') # noqa: E731
|
||||
cmd = [self.tool('cmake'), '-S', ROOT, '-B', self.cmake_build, '-G', 'Ninja',
|
||||
'-DCMAKE_BUILD_TYPE=' + self.args.build_type,
|
||||
'-DTMB_GENERATED_DIR=' + self.gen.replace('\\', '/'),
|
||||
'-DBOZO_ENGINE_DIR=' + fwd(ENGINE),
|
||||
'-DTMB_ELF=' + fwd(self.elf()), '-DTMB_DISC_DIR=' + fwd(self.disc_dir),
|
||||
'-DBOZO_BUILD_TOOLS=OFF', '-DBUILD_TESTING=OFF', '-DTMB_GUI_SUBSYSTEM=ON',
|
||||
'-DPython3_EXECUTABLE=' + fwd(sys.executable),
|
||||
'-DCMAKE_C_COMPILER=' + self.tool('gcc'), '-DCMAKE_CXX_COMPILER=' + self.tool('g++'),
|
||||
'-DCMAKE_MAKE_PROGRAM=' + self.tool('ninja')] + cmake_rc_flags()
|
||||
if self.args.debug_info == 'no':
|
||||
# The configuration's own flags without -g: the same code (GCC's -g never changes it), the same -O2 and
|
||||
# GUI subsystem as RelWithDebInfo; Release would be -O3, which the generated code is too large for.
|
||||
flags = {'Release': '-O3 -DNDEBUG', 'RelWithDebInfo': '-O2 -DNDEBUG', 'Debug': '-O0'}[self.args.build_type]
|
||||
if self.args.debug_info == 'no' and self.args.build_type != 'Release':
|
||||
# The configuration's own flags without -g: the same code (GCC's -g never changes it).
|
||||
flags = {'RelWithDebInfo': '-O2 -DNDEBUG', 'Debug': '-O0'}[self.args.build_type]
|
||||
cmd += ['-DCMAKE_%s_FLAGS_%s=%s' % (lang, self.args.build_type.upper(), flags) for lang in ('C', 'CXX')]
|
||||
if self.ffmpeg_root:
|
||||
cmd += ['-DPS2X_FFMPEG_ROOT=' + self.ffmpeg_root.replace('\\', '/'), '-DPS2X_ENABLE_PARALLEL_GS=OFF']
|
||||
cmd.append('-DBOZO_FFMPEG_ROOT=' + fwd(self.ffmpeg_root))
|
||||
else:
|
||||
pkg = os.path.join(self.find_toolchain(), 'pkg-config' + EXE)
|
||||
if os.path.isfile(pkg):
|
||||
cmd.append('-DPKG_CONFIG_EXECUTABLE=' + pkg)
|
||||
self.run(cmd + self.fetch_args())
|
||||
with open(stamp, 'w', encoding='utf-8') as f:
|
||||
f.write(toolchain_key + '\n')
|
||||
|
||||
def runner_path(self):
|
||||
return os.path.join(self.cmake_build, 'PS2Recomp', 'ps2xRuntime', 'ps2EntryRunner' + EXE)
|
||||
def step_tools(self):
|
||||
self.cmake_build_targets('bozo-recomp', 'bozo-externals', percent=ninja_percent)
|
||||
|
||||
def step_recompile(self):
|
||||
self.cmake_build_targets('tmb_recompile', percent=ninja_percent)
|
||||
|
||||
def step_packs(self):
|
||||
self.cmake_build_targets('tmb_packs', percent=ninja_percent)
|
||||
|
||||
def step_compile(self):
|
||||
self.run([self.tool('cmake'), '--build', self.cmake_build, '--target', 'ps2EntryRunner',
|
||||
'-j', str(self.args.jobs)], percent=ninja_percent)
|
||||
self.cmake_build_targets(GAME_EXE, percent=ninja_percent)
|
||||
|
||||
def exe_path(self):
|
||||
return os.path.join(self.cmake_build, GAME_EXE + EXE)
|
||||
|
||||
def step_stage(self):
|
||||
exe = self.runner_path()
|
||||
exe = self.exe_path()
|
||||
if not os.path.isfile(exe):
|
||||
raise BuildError('no runner at %s' % exe)
|
||||
raise BuildError('no game at %s' % exe)
|
||||
os.makedirs(self.game, exist_ok=True)
|
||||
staged = [exe]
|
||||
dest = os.path.join(self.game, os.path.basename(exe))
|
||||
strip = os.path.join(self.find_toolchain(), 'strip' + EXE)
|
||||
if os.path.exists(dest):
|
||||
os.remove(dest)
|
||||
if self.args.debug_info == 'no' and os.path.isfile(strip):
|
||||
# What debug information is left (the libraries' own -g, if any) out of the player's copy.
|
||||
if os.path.exists(dest):
|
||||
os.remove(dest)
|
||||
self.run([strip, '--strip-debug', '-o', dest, exe])
|
||||
shutil.copystat(exe, dest)
|
||||
else:
|
||||
@@ -703,30 +657,33 @@ class Build:
|
||||
for dll in runtime_dlls(exe, [os.path.dirname(exe), self.find_toolchain()]):
|
||||
shutil.copy2(dll, os.path.join(self.game, os.path.basename(dll)))
|
||||
staged.append(dll)
|
||||
shutil.copy2(self.elf(), os.path.join(self.game, ELF_NAME))
|
||||
for name in ('tmb_textures.pack', 'tmb_meshes.pack'):
|
||||
shutil.copy2(os.path.join(self.gen, name), os.path.join(self.game, name))
|
||||
shutil.copy2(os.path.join(self.cmake_build, 'packs', name), os.path.join(self.game, name))
|
||||
# A fork build's game folder (ps2EntryRunner.exe and its DLLs): nothing of it is used any more.
|
||||
for old in ('ps2EntryRunner.exe', 'libstdc++-6.dll', 'libgcc_s_seh-1.dll', 'libwinpthread-1.dll'):
|
||||
p = os.path.join(self.game, old)
|
||||
if os.path.isfile(p) and p not in staged:
|
||||
os.remove(p)
|
||||
name = os.path.basename(exe)
|
||||
if os.name == 'nt':
|
||||
lines = ['@echo off', 'rem Made by tools/tmb_build.py: Twisted Metal: Black, native PC port.',
|
||||
'cd /d "%~dp0"']
|
||||
lines += ['set %s=%s' % kv for kv in LAUNCH_ENV]
|
||||
lines += ['set TMB_TEXTURE_PACK=%~dp0tmb_textures.pack', 'set TMB_MESH_PACK=%~dp0tmb_meshes.pack',
|
||||
'set TMB_ISO=%~dp0disc.iso',
|
||||
'start "" "%%~dp0%s" "%%~dp0disc\\%s" %%*' % (os.path.basename(exe), ELF_NAME), '']
|
||||
lines = ['@echo off', 'rem Made by tools/tmb_build.py: Twisted Metal: Black, native PC port (BozoEngine).',
|
||||
'cd /d "%~dp0"',
|
||||
'start "" "%%~dp0%s" --elf "%%~dp0%s" --iso "%%~dp0disc.iso" %%*' % (name, ELF_NAME), '']
|
||||
with open(os.path.join(self.game, 'Play TMB.cmd'), 'w', newline='\r\n') as f:
|
||||
f.write('\n'.join(lines))
|
||||
else:
|
||||
sh = os.path.join(self.game, 'play_tmb.sh')
|
||||
with open(sh, 'w', newline='\n') as f:
|
||||
f.write('#!/bin/sh\ncd "$(dirname "$0")"\n' + ''.join('export %s=%s\n' % kv for kv in LAUNCH_ENV) +
|
||||
'export TMB_TEXTURE_PACK="$PWD/tmb_textures.pack" TMB_MESH_PACK="$PWD/tmb_meshes.pack" TMB_ISO="$PWD/disc.iso"\n'
|
||||
'exec ./%s disc/%s "$@"\n' % (os.path.basename(exe), ELF_NAME))
|
||||
f.write('#!/bin/sh\ncd "$(dirname "$0")"\nexec ./%s --elf "$PWD/%s" --iso "$PWD/disc.iso" "$@"\n'
|
||||
% (name, ELF_NAME))
|
||||
os.chmod(sh, 0o755)
|
||||
with open(os.path.join(self.game, 'tmb_build.json'), 'w') as f:
|
||||
json.dump({'built': time.strftime('%Y-%m-%d %H:%M:%S'), 'elf_sha1': ELF_SHA1,
|
||||
'build_type': self.args.build_type, 'debug_info': self.args.debug_info, 'toolchain': self.find_toolchain(), 'kit': self.kit,
|
||||
'files': [os.path.basename(p) for p in staged],
|
||||
'env': dict(LAUNCH_ENV)}, f, indent=1)
|
||||
emit('INFO', 'stage', '%d DLLs staged' % (len(staged) - 1))
|
||||
json.dump({'built': time.strftime('%Y-%m-%d %H:%M:%S'), 'engine': 'BozoEngine', 'elf_sha1': ELF_SHA1,
|
||||
'build_type': self.args.build_type, 'debug_info': self.args.debug_info,
|
||||
'toolchain': self.find_toolchain(), 'kit': self.kit, 'exe': name,
|
||||
'files': [os.path.basename(p) for p in staged]}, f, indent=1)
|
||||
emit('INFO', 'stage', '%s, %.1f MB, %d DLLs staged' % (name, os.path.getsize(dest) / 1e6, len(staged) - 1))
|
||||
|
||||
def write_built_from(self):
|
||||
"""<game>/built_from.ini: the release stamp (<TMB_Recomp>/release.ini, written by tools/make_release.py) of the
|
||||
@@ -767,7 +724,7 @@ class Build:
|
||||
emit('INFO', 'stopped', 'after ' + step)
|
||||
return 0
|
||||
continue
|
||||
dirty = True # every later step runs again
|
||||
dirty = 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}
|
||||
@@ -816,12 +773,11 @@ def find_kit(args):
|
||||
|
||||
STEP_TITLES = {
|
||||
'verify': 'Checking the disc',
|
||||
'extract': 'Copying the disc\'s files',
|
||||
'extract': 'Reading the disc\'s files',
|
||||
'configure': 'Configuring the build',
|
||||
'tools': 'Preparing the recompiler',
|
||||
'recompile': 'Recompiling the game\'s code',
|
||||
'packs': 'Converting textures and models',
|
||||
'iop': 'Recompiling the sound and controller modules',
|
||||
'configure': 'Configuring the build',
|
||||
'compile': 'Compiling (this takes a while)',
|
||||
'stage': 'Assembling the game folder',
|
||||
}
|
||||
@@ -859,19 +815,21 @@ def main():
|
||||
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('--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, '
|
||||
'C:/msys64/ucrt64')
|
||||
ap.add_argument('--tools', help='folder with prebuilt ps2_recomp and ps2_vu_aot (default: built here)')
|
||||
ap.add_argument('--fetch-cache', help='folder with the FetchContent sources (<name>-src) instead of git')
|
||||
ap.add_argument('--build-type', default='RelWithDebInfo', choices=['Release', 'RelWithDebInfo', 'Debug'])
|
||||
ap.add_argument('--debug-info', choices=['yes', 'no'], help='debug information in the runner (default: no with '
|
||||
ap.add_argument('--fetch-cache', help='folder with the FetchContent sources (sdl3-src, imgui-src) instead of the '
|
||||
'download')
|
||||
ap.add_argument('--build-type', default='Release', choices=['Release', 'RelWithDebInfo', 'Debug'])
|
||||
ap.add_argument('--debug-info', choices=['yes', 'no'], help='debug information in the game (default: no with '
|
||||
'the build kit, a player build; yes without it)')
|
||||
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')
|
||||
args = ap.parse_args()
|
||||
load_engine(args.engine)
|
||||
if args.check:
|
||||
sys.exit(check_disc(args.disc))
|
||||
os.makedirs(os.path.abspath(args.out), exist_ok=True)
|
||||
@@ -884,29 +842,48 @@ def main():
|
||||
|
||||
def remove_stale_sources():
|
||||
"""A release's source folder lists its files (release_files.txt, tools/make_release.py). A newer release unzipped
|
||||
over an older one leaves the files it no longer has; CMake globs some folders (runtime/*.cpp, the fork's sources),
|
||||
so they are removed here: regular files under the source folder only, never through a link, never Python's caches;
|
||||
then the folders left empty."""
|
||||
over an older one leaves the files it no longer has; CMake globs some folders (runtime/*.cpp, BozoEngine's
|
||||
sources), so they are removed here: regular files under the source folder only, never through a link, never
|
||||
Python's caches; then the folders left empty."""
|
||||
listing = os.path.join(ROOT, 'release_files.txt')
|
||||
if not os.path.isfile(listing):
|
||||
return
|
||||
with open(listing, encoding='utf-8') as f:
|
||||
keep = set(l.strip() for l in f if l.strip())
|
||||
removed = 0
|
||||
# Only the folders a release ships (never a kit, a work folder or anything else put inside the source folder).
|
||||
tops = sorted(set(rel.split('/', 1)[0] for rel in keep if '/' in rel))
|
||||
for dirpath, dirs, names in (w for t in tops for w in os.walk(os.path.join(ROOT, t), topdown=False)):
|
||||
dirs[:] = [d for d in dirs if d != '__pycache__']
|
||||
if '__pycache__' in dirpath.replace('\\', '/').split('/'):
|
||||
# PS2Recomp was a managed source component in previous releases. It is absent from the new manifest, so deriving
|
||||
# traversal roots solely from that manifest would leave the entire retired runtime behind after an update.
|
||||
retired = {'PS2Recomp'}
|
||||
tops = sorted(set(rel.split('/', 1)[0] for rel in keep if '/' in rel) | retired)
|
||||
linked = lambda p: os.path.islink(p) or (hasattr(os.path, 'isjunction') and os.path.isjunction(p))
|
||||
for top in tops:
|
||||
if top in ('', '.', '..') or os.path.isabs(top) or '\\' in top or ':' in top:
|
||||
raise BuildError('invalid source manifest directory: %r' % top)
|
||||
base = os.path.abspath(os.path.join(ROOT, top))
|
||||
if os.path.normcase(os.path.commonpath([os.path.abspath(ROOT), base])) != os.path.normcase(os.path.abspath(ROOT)):
|
||||
raise BuildError('source cleanup escaped its root: %s' % base)
|
||||
if linked(base):
|
||||
if top in retired:
|
||||
if os.path.islink(base):
|
||||
os.unlink(base)
|
||||
else:
|
||||
os.rmdir(base) # the retired junction only, never its target
|
||||
continue
|
||||
for n in names:
|
||||
p = os.path.join(dirpath, n)
|
||||
rel = os.path.relpath(p, ROOT).replace('\\', '/')
|
||||
if rel not in keep and not os.path.islink(p) and os.path.isfile(p):
|
||||
os.remove(p)
|
||||
removed += 1
|
||||
if dirpath != ROOT and not os.listdir(dirpath) and not os.path.islink(dirpath):
|
||||
os.rmdir(dirpath)
|
||||
visited = []
|
||||
# Prune links before descending. A bottom-up walk cannot prevent traversal of a Windows junction.
|
||||
for dirpath, dirs, names in os.walk(base, topdown=True, followlinks=False):
|
||||
visited.append(dirpath)
|
||||
dirs[:] = [d for d in dirs if (d != '__pycache__' or top in retired) and
|
||||
not linked(os.path.join(dirpath, d))]
|
||||
for n in names:
|
||||
p = os.path.join(dirpath, n)
|
||||
rel = os.path.relpath(p, ROOT).replace('\\', '/')
|
||||
if rel not in keep and not linked(p) and os.path.isfile(p):
|
||||
os.remove(p)
|
||||
removed += 1
|
||||
for dirpath in reversed(visited):
|
||||
if not os.listdir(dirpath):
|
||||
os.rmdir(dirpath)
|
||||
if removed:
|
||||
emit('INFO', 'update', '%d files of an earlier release removed from %s' % (removed, ROOT))
|
||||
|
||||
@@ -915,11 +892,11 @@ def remove_stale_sources():
|
||||
#
|
||||
# MSYS2's binutils open files in the ANSI code page: ld cannot open an object or library whose path, read from the
|
||||
# response file CMake writes in UTF-8, has a non-ASCII character (C:\Users\Jérôme\..., D:\Jeux\Été\...): "cannot find
|
||||
# ...obj". GCC itself and the fork's tools (UTF-8 manifests) cope; ld does not, and it is not ours to rebuild. So when
|
||||
# the code, the work folder, the game folder or the kit has such a path, tmb_build runs itself again through
|
||||
# directory junctions with plain names (%ProgramData%\TMB_Recomp\paths\<hash>-<name>, the same each time so CMake's
|
||||
# cache stays valid) and removes the junctions afterwards (only the links: os.rmdir on a junction never touches its
|
||||
# target). A junction needs no administrator rights; the disc image is read by Python only and keeps its path.
|
||||
# ...obj". GCC itself copes; ld does not, and it is not ours to rebuild. So when the code, the work folder, the game
|
||||
# folder or the kit has such a path, tmb_build runs itself again through directory junctions with plain names
|
||||
# (%ProgramData%\TMB_Recomp\paths\<hash>-<name>, the same each time so CMake's cache stays valid) and removes the
|
||||
# junctions afterwards (only the links: os.rmdir on a junction never touches its target). A junction needs no
|
||||
# administrator rights; the disc image is read by Python only and keeps its path.
|
||||
|
||||
ALIAS_ENV = 'TMB_BUILD_ALIASED'
|
||||
|
||||
@@ -936,7 +913,8 @@ def needs_ascii_aliases(args):
|
||||
if os.name != 'nt' or os.environ.get(ALIAS_ENV):
|
||||
return False
|
||||
kit = find_kit(args)
|
||||
paths = [ROOT, os.path.abspath(args.out), os.path.abspath(args.game) if args.game else '', kit or '']
|
||||
paths = [ROOT, ENGINE, os.path.abspath(args.out), os.path.abspath(args.game) if args.game else '', kit or '',
|
||||
os.path.abspath(args.toolchain) if args.toolchain else '']
|
||||
return not all(is_ascii(p) for p in paths)
|
||||
|
||||
|
||||
@@ -982,10 +960,18 @@ def run_through_aliases(args):
|
||||
rest = sys.argv[1:]
|
||||
# The same command line, the folders replaced by their aliases.
|
||||
replace = {'--out': out, '--game': game}
|
||||
if args.toolchain:
|
||||
t = make_alias(args.toolchain, 'toolchain')
|
||||
links.append(t)
|
||||
replace['--toolchain'] = t
|
||||
if kit:
|
||||
k = make_alias(kit, 'kit')
|
||||
links.append(k)
|
||||
replace['--kit'] = k
|
||||
if args.engine:
|
||||
e = make_alias(ENGINE, 'engine')
|
||||
links.append(e)
|
||||
replace['--engine'] = e
|
||||
new = []
|
||||
i = 0
|
||||
while i < len(rest):
|
||||
@@ -1003,7 +989,19 @@ def run_through_aliases(args):
|
||||
env = dict(os.environ)
|
||||
env[ALIAS_ENV] = '1'
|
||||
sys.stdout.flush()
|
||||
return subprocess.call(argv + new, env=env)
|
||||
# The links disappear at exit. Protocol paths shown to the launcher/CLI must point at the real folders.
|
||||
display = [(root, ROOT), (out, os.path.abspath(args.out))]
|
||||
if game:
|
||||
display.append((game, os.path.abspath(args.game)))
|
||||
if kit:
|
||||
display.append((replace['--kit'], kit))
|
||||
proc = subprocess.Popen(argv + new, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
||||
text=True, encoding='utf-8', errors='replace')
|
||||
for line in proc.stdout:
|
||||
for alias, real in display:
|
||||
line = line.replace(alias, real).replace(alias.replace('\\', '/'), real.replace('\\', '/'))
|
||||
print(line, end='', flush=True)
|
||||
return proc.wait()
|
||||
except OSError as e:
|
||||
emit('ERROR', 'verify', 'could not make plain-named links to the folders (%s): move the game\'s folder to a '
|
||||
'path with plain letters, such as C:\\Games\\TMB_Recomp' % e)
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Writes the hand-written recompiler settings shared by both regions (recomp/tmb_manual.toml, by symbol name) into a
|
||||
region's config, with its executable's addresses: the manual block at the top of its stub list, replacing the one
|
||||
there (between '# --- Manual' and '# --- Analyzer output below').
|
||||
|
||||
tools/tmb_manual_toml.py <ELF> recomp/tmb_manual.toml <region config>
|
||||
"""
|
||||
import os, sys, tomllib
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
import tmb_elf
|
||||
|
||||
BEGIN = ' # --- Manual (recomp/tmb_manual.toml, tools/tmb_manual_toml.py)'
|
||||
END = ' # --- Analyzer output below'
|
||||
|
||||
|
||||
def main():
|
||||
elf, manual_path, config_path = sys.argv[1:4]
|
||||
table = tmb_elf.by_name(tmb_elf.symbols(elf))
|
||||
manual = tomllib.load(open(manual_path, 'rb'))
|
||||
lines = [BEGIN]
|
||||
for stub in manual.get('stub', []):
|
||||
for name in stub['symbols']:
|
||||
s = table.get(name)
|
||||
if s is None:
|
||||
sys.exit(f'tmb_manual_toml: no {name} in {elf}')
|
||||
lines.append(f' "{stub["handler"]}@{s.address:#010X}", # {name}'.replace('0X', '0x', 1))
|
||||
lines.append(END)
|
||||
|
||||
text = open(config_path, encoding='utf-8').read().split('\n')
|
||||
start = text.index('stubs = [') + 1
|
||||
# Drop the block a previous run wrote (or the hand-written one before this tool), up to the analyzer's part.
|
||||
end = start
|
||||
while end < len(text) and text[end].strip().startswith(('#', '"ret')) and text[end] != END:
|
||||
end += 1
|
||||
if end < len(text) and text[end] == END:
|
||||
end += 1
|
||||
text[start:end] = lines
|
||||
open(config_path, 'w', encoding='utf-8', newline='\n').write('\n'.join(text))
|
||||
print(f'tmb_manual_toml: {len(lines) - 2} manual stubs written into {config_path}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -46,8 +46,8 @@ What it reads:
|
||||
packet comes in sections, each closed by STCYCL 4,4 and NOPs to the quadword (the chain sends the bones again
|
||||
before each); the next starts with its pool's S-32 @180. A bone offset is 4 quadwords per bone: bone = offset / 4.
|
||||
|
||||
The pack is the fork's generic mesh pack (PS2Recomp/tools/native_pack/mesh.py, PS2XMSH1; the runtime's loader is
|
||||
ps2x::native::packs::MeshPack, PS2Recomp/docs/native_packs.md): one file per NGP file (its name upper case, no
|
||||
The pack is BozoEngine's generic mesh pack (BozoEngine tools/native_pack/mesh.py, PS2XMSH1; the runtime's loader is
|
||||
bozo::render::packs::MeshPack, bozo/render/mesh_pack.h): one file per NGP file (its name upper case, no
|
||||
directory, e.g. "JUNKYARD.NGP"; the image's size and CRC32 inflated), one object per hierobject keyed by its offset
|
||||
(obj - 0x980000 in the image). What TMB puts in it:
|
||||
kind: 0 rigid, 1 pool-less, 2 sprite, 3 ribbon, 4 skinned.
|
||||
@@ -77,7 +77,12 @@ import struct
|
||||
import sys
|
||||
import zlib
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'PS2Recomp', 'tools'))
|
||||
# native_pack: BozoEngine's tools/ (BOZO_ENGINE_TOOLS, or the BozoEngine submodule).
|
||||
_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')):
|
||||
sys.path.insert(0, _tools)
|
||||
break
|
||||
from native_pack import mesh as native_mesh # noqa: E402
|
||||
from native_pack.ps2 import UNPACK_FORMATS, u16, u32, vif_codes, dma_chain, chain_stream, image_offset # noqa: E402,F401
|
||||
from native_pack.ps2 import find_gs_register_blocks # noqa: E402
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
"""TMB's override list for BozoEngine's bozo-externals (phase 4): every address runtime/*.cpp registers
|
||||
(runtime.registerFunction(<address>, ...)), whatever environment toggle guards it, and every store the store patch
|
||||
tells apart (a "// bozo:store <constant>" line next to it).
|
||||
|
||||
python tools/tmb_overrides_list.py <runtime folder> <out.txt>
|
||||
|
||||
The generated code must route every one of them to the runtime: BozoEngine checks at startup that each registered
|
||||
override is an external of the generated code (bozo::port::undeclared) and refuses to run otherwise.
|
||||
"""
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
CONST = re.compile(r'\b(k[A-Z0-9]\w*)\s*=\s*(0x[0-9A-Fa-f]+)u?\b')
|
||||
ARRAY = re.compile(r'\b(k[A-Z0-9]\w*)\[\]\s*=\s*\{([^}]*)\}')
|
||||
LOOP = re.compile(r'for\s*\(\s*uint32_t\s+(\w+)\s*:\s*(k\w+)\s*\)')
|
||||
REGISTER = re.compile(r'registerFunction\(\s*([^,]+?)\s*,')
|
||||
STORE = re.compile(r'//\s*bozo:store\s+(k\w+)')
|
||||
|
||||
|
||||
def main():
|
||||
folder, out = Path(sys.argv[1]), Path(sys.argv[2])
|
||||
files = sorted(folder.glob('*.cpp'))
|
||||
constants, perFile = {}, {}
|
||||
for f in files:
|
||||
text = f.read_text(encoding='utf-8')
|
||||
local = {}
|
||||
for name, value in CONST.findall(text):
|
||||
local[name] = int(value, 16)
|
||||
constants.setdefault(name, int(value, 16))
|
||||
perFile[f] = local
|
||||
overrides, stores, errors = {}, {}, []
|
||||
|
||||
def resolve(f, expr):
|
||||
expr = expr.strip()
|
||||
if re.fullmatch(r'0x[0-9A-Fa-f]+u?', expr):
|
||||
return int(expr.rstrip('u'), 16)
|
||||
if expr in perFile[f]:
|
||||
return perFile[f][expr]
|
||||
if expr in constants:
|
||||
return constants[expr]
|
||||
errors.append(f'{f.name}: cannot resolve {expr}')
|
||||
return None
|
||||
|
||||
for f in files:
|
||||
text = f.read_text(encoding='utf-8')
|
||||
arrays = {n: [int(v, 16) for v in re.findall(r'0x[0-9A-Fa-f]+', body)] for n, body in ARRAY.findall(text)}
|
||||
loops = {var: arrays.get(arr) for var, arr in LOOP.findall(text)}
|
||||
for expr in REGISTER.findall(text):
|
||||
if loops.get(expr.strip()):
|
||||
for a in loops[expr.strip()]:
|
||||
overrides.setdefault(a, f'{f.name}: {expr} (a loop)')
|
||||
continue
|
||||
a = resolve(f, expr)
|
||||
if a is not None:
|
||||
overrides.setdefault(a, f'{f.name}: {expr}')
|
||||
for name in STORE.findall(text):
|
||||
a = resolve(f, name)
|
||||
if a is not None:
|
||||
stores[a] = f'{f.name}: {name}'
|
||||
if errors:
|
||||
sys.exit('\n'.join(errors))
|
||||
lines = ['# TMB\'s overrides and patched stores (tools/tmb_overrides_list.py from runtime/*.cpp). Do not edit.']
|
||||
lines += [f'override 0x{a:x} # {where}' for a, where in sorted(overrides.items())]
|
||||
lines += [f'store 0x{a:x} # {where}' for a, where in sorted(stores.items())]
|
||||
text = '\n'.join(lines) + '\n'
|
||||
if not out.exists() or out.read_text(encoding='utf-8') != text:
|
||||
out.write_text(text, encoding='utf-8', newline='\n')
|
||||
print(f'tmb_overrides_list: {len(overrides)} overrides, {len(stores)} patched stores -> {out}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -15,8 +15,8 @@ What it reads:
|
||||
the T8H / T4HL / T4HH textures (pixels at +0x80) and the palettes (entries at +0x10).
|
||||
- the font (fontDmaFontData's sources in the ELF: a 128 x 128 T4 raster, a 16-entry CT32 palette).
|
||||
|
||||
The pack is the fork's generic texture pack (PS2Recomp/tools/native_pack/texture.py, PS2XTEX1; the runtime's loader
|
||||
and decoders are ps2x::native::packs, PS2Recomp/docs/native_packs.md): per file its name (upper case, no directory)
|
||||
The pack is BozoEngine's generic texture pack (BozoEngine tools/native_pack/texture.py, PS2XTEX1; the runtime's loader
|
||||
and decoders are bozo::render::packs, bozo/render/texture_pack.h): per file its name (upper case, no directory)
|
||||
and its records in the order the game sets them up (the runtime's key scheme counts them so), each psm, width, height
|
||||
and its texels unpacked; the font as the file "FONT" (its raster, then its palette).
|
||||
"""
|
||||
@@ -25,7 +25,12 @@ import struct
|
||||
import sys
|
||||
import zlib
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'PS2Recomp', 'tools'))
|
||||
# native_pack: BozoEngine's tools/ (BOZO_ENGINE_TOOLS, or the BozoEngine submodule).
|
||||
_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')):
|
||||
sys.path.insert(0, _tools)
|
||||
break
|
||||
from native_pack import texture as native_texture # noqa: E402
|
||||
from native_pack.texture import bits, unpack_texels # noqa: E402,F401
|
||||
from native_pack.ps2 import u32, elf_bytes # noqa: E402
|
||||
|
||||
Reference in new issue
Block a user