Compare commits
No files matched your search
@@ -181,4 +181,4 @@ jobs:
|
||||
if: env.WATCHER_TOKEN != ''
|
||||
env:
|
||||
GH_TOKEN: ${{ env.WATCHER_TOKEN }}
|
||||
run: gh api repos/boubou666/RecompWatcher/dispatches -f event_type=project-updated
|
||||
run: gh api repos/TheBozos/RecompWatcher/dispatches -f event_type=project-updated
|
||||
@@ -1,3 +1,3 @@
|
||||
[submodule "PS2Recomp"]
|
||||
path = PS2Recomp
|
||||
url = https://github.com/boubou666/PS2Recomp.git
|
||||
url = https://github.com/TheBozos/PS2Recomp.git
|
||||
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"$schema": "https://recomp.fyi/schema/v1.json",
|
||||
"game": "Twisted Metal: Black",
|
||||
"wikidata": "Q2978434",
|
||||
"system": "PS2",
|
||||
"type": "recomp",
|
||||
"original": {
|
||||
"region": "USA",
|
||||
"serial": "SCUS-97101"
|
||||
},
|
||||
"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.",
|
||||
"started": "2026-10-22",
|
||||
"maintainers": [
|
||||
{ "name": "boubou666", "link": "https://github.com/boubou666" },
|
||||
{ "name": "Arzaroth", "link": "https://github.com/Arzaroth" }
|
||||
],
|
||||
"links": [
|
||||
{ "label": "Releases", "url": "https://github.com/TheBozos/TMB_Recomp/releases" },
|
||||
{ "label": "RecompWatcher (The Bozos' projects)", "url": "https://thebozos.github.io/RecompWatcher/" }
|
||||
],
|
||||
"help": [
|
||||
"Playtesting story levels 2 to 8 to the endings",
|
||||
"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."
|
||||
}
|
||||
@@ -7,6 +7,91 @@ under "Unreleased" as they land, then move them under the new version's heading
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.3.2] - 2026-11-02
|
||||
|
||||
### Added
|
||||
|
||||
- **Story: start at** (F2, Cheats): a new story can begin at any of its stages, Midtown Suburbs to Warhawk's Rooftop,
|
||||
instead of the Junkyard, then goes on from there as usual. Handy to try the later stages without playing through.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Black Vista Highway** (story stage 3) had no road: most of the level's ground and walls were not drawn. Some
|
||||
pieces of three Challenge arenas (DEATH1, DEATH2, DEATH5) were missing for the same reason. "Rebuild now" after
|
||||
updating fixes them.
|
||||
- **Movie sound volume**: the movies' sound now plays at the volume the game sets for it (it used a default
|
||||
volume before; a fix from the Valkyrie Profile 2 port, which shares the sound code).
|
||||
|
||||
### Known limits
|
||||
|
||||
- Story stages past the first are reachable and load correctly, but most have not been played to the end yet.
|
||||
- No widescreen yet.
|
||||
- Only the USA disc (SCUS-97101) is supported.
|
||||
- The launcher and the game are not signed: Windows SmartScreen asks for "More info", then "Run anyway".
|
||||
|
||||
## [0.3.1] - 2026-11-02
|
||||
|
||||
### Changed
|
||||
|
||||
- **Faster**: the game now needs about a third less processor time per frame than in 0.3.0 (in our tests a busy
|
||||
match went from about 7.5 to 5 milliseconds of work per frame, out of the 16.7 a frame lasts at 60 frames per
|
||||
second). Older or slower PCs that dropped below 60 in big fights or in split screen should hold it much better.
|
||||
Nothing changes in how the game looks or plays.
|
||||
|
||||
### Known limits
|
||||
|
||||
- Story levels 2 to 8 are not checked to the end yet.
|
||||
- No widescreen yet.
|
||||
- Only the USA disc (SCUS-97101) is supported.
|
||||
- The launcher and the game are not signed: Windows SmartScreen asks for "More info", then "Run anyway".
|
||||
|
||||
## [0.3.0] - 2026-11-02
|
||||
|
||||
### Added
|
||||
|
||||
- **The launcher updates the game itself**: when a new version is out, "Update" on the Play tab downloads it, checks
|
||||
it, installs it over this one and restarts the launcher; then "Rebuild now" prepares the game again (only what
|
||||
changed). Your saves and settings stay. Unzipping a new release by hand still works too.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Smoother frame times**: the game does less work each frame (about 2 ms less per frame in our tests), so slower PCs
|
||||
drop fewer frames in busy fights. The lens flares no longer read the whole picture back from the graphics card
|
||||
each frame.
|
||||
|
||||
### Known limits
|
||||
|
||||
- Players on 0.1.0 or 0.2.0 update to this version by hand one last time (unzip it over the old one, then Rebuild);
|
||||
from 0.3.0 on, the launcher's Update button does it.
|
||||
- Story levels 2 to 8 are not checked to the end yet.
|
||||
- No widescreen yet.
|
||||
- Only the USA disc (SCUS-97101) is supported.
|
||||
- The launcher and the game are not signed: Windows SmartScreen asks for "More info", then "Run anyway".
|
||||
|
||||
## [0.2.0] - 2026-11-02
|
||||
|
||||
### Added
|
||||
|
||||
- **Smoother picture on high-refresh monitors, experimental** (F2, Video, "Frame rate": "Match the monitor"): on a 120, 144, 165
|
||||
or 240 Hz monitor the window shows that many frames a second, the ones between the game's 60 drawn in between (the
|
||||
cars, the camera, the scenery and the smoke and sparks move smoothly; the HUD stays as the game draws it). The game
|
||||
itself still runs at 60, as it always did, and this costs one game frame (about 17 ms) more input lag. Off by
|
||||
default: "60 (the game's)" stays exactly as before. Experimental: a few effects (rain, snow, lens flares, some
|
||||
trails) still move at 60 against the smoother rest.
|
||||
|
||||
### Changed
|
||||
|
||||
- **New icon** for the launcher and the game window: The Bozos' clown, with its head on fire.
|
||||
- The project moved to The Bozos' GitHub organisation (github.com/TheBozos/TMB_Recomp). The launcher's update check
|
||||
and links follow; the 0.1.0 launcher still finds new releases through GitHub's redirect.
|
||||
|
||||
### Known limits
|
||||
|
||||
- Story levels 2 to 8 are not checked to the end yet.
|
||||
- No widescreen yet.
|
||||
- Only the USA disc (SCUS-97101) is supported.
|
||||
- The launcher and the game are not signed: Windows SmartScreen asks for "More info", then "Run anyway".
|
||||
|
||||
## [0.1.0] - 2026-11-01
|
||||
|
||||
The first release. You build the game on your own PC from your own USA disc; nothing of the game is in the download.
|
||||
@@ -31,12 +116,16 @@ The first release. You build the game on your own PC from your own USA disc; not
|
||||
### Known limits
|
||||
|
||||
- Story mode: level 1 of 8 checked to the end; levels 2 to 8 and the endings are not fully checked yet. Please report
|
||||
what you find on the [issues page](https://github.com/boubou666/TMB_Recomp/issues).
|
||||
what you find on the [issues page](https://github.com/TheBozos/TMB_Recomp/issues).
|
||||
- No widescreen yet, and no frame rate above the game's own 60.
|
||||
- Only the USA disc (SCUS-97101) is supported; the European disc is not.
|
||||
- The launcher and the game are not signed: Windows SmartScreen asks for "More info", then "Run anyway".
|
||||
- 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/boubou666/TMB_Recomp/compare/v0.1.0...HEAD
|
||||
[0.1.0]: https://github.com/boubou666/TMB_Recomp/releases/tag/v0.1.0
|
||||
[Unreleased]: https://github.com/TheBozos/TMB_Recomp/compare/v0.3.2...HEAD
|
||||
[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
|
||||
[0.2.0]: https://github.com/TheBozos/TMB_Recomp/compare/v0.1.0...v0.2.0
|
||||
[0.1.0]: https://github.com/TheBozos/TMB_Recomp/releases/tag/v0.1.0
|
||||
@@ -93,7 +93,56 @@ if(TMB_VU1_AOT_SOURCES)
|
||||
target_sources(ps2EntryRunner PRIVATE $<TARGET_OBJECTS:tmb_vu1_aot>)
|
||||
endif()
|
||||
|
||||
target_sources(ps2EntryRunner PRIVATE ${TMB_GENERATED_SOURCES} ${TMB_RUNTIME_SOURCES})
|
||||
# The reference harness (docs/REFERENCE_HARNESS.md): the game's library and kernel stubs (the generated code's stub
|
||||
# list, ps2_recompiled_stubs.h: name_0xaddress) whose calls PS2X_REFERENCE records, and the build's name (the two
|
||||
# repositories' commits when configured), as a source in the build tree.
|
||||
set(_tmb_stub_list "${TMB_GENERATED_DIR}/ps2_recompiled_stubs.h")
|
||||
set(_tmb_call_names "")
|
||||
set(_tmb_call_count 0)
|
||||
if(EXISTS "${_tmb_stub_list}")
|
||||
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${_tmb_stub_list}")
|
||||
file(STRINGS "${_tmb_stub_list}" _tmb_stub_lines REGEX "^void [A-Za-z0-9_]+_0x[0-9a-fA-F]+\\(")
|
||||
foreach(_tmb_line IN LISTS _tmb_stub_lines)
|
||||
if(_tmb_line MATCHES "^void ([A-Za-z0-9_]+)_0x([0-9a-fA-F]+)\\(")
|
||||
string(APPEND _tmb_call_names " {0x${CMAKE_MATCH_2}u, \"${CMAKE_MATCH_1}\"},\n")
|
||||
math(EXPR _tmb_call_count "${_tmb_call_count} + 1")
|
||||
endif()
|
||||
endforeach()
|
||||
endif()
|
||||
if(_tmb_call_count EQUAL 0)
|
||||
set(_tmb_call_names " {0u, \"\"},\n")
|
||||
endif()
|
||||
find_package(Git QUIET)
|
||||
set(_tmb_commit "unknown")
|
||||
set(_tmb_fork_commit "unknown")
|
||||
if(GIT_FOUND)
|
||||
execute_process(COMMAND "${GIT_EXECUTABLE}" rev-parse --short HEAD WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}"
|
||||
OUTPUT_VARIABLE _tmb_commit OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET)
|
||||
execute_process(COMMAND "${GIT_EXECUTABLE}" rev-parse --short HEAD WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}/PS2Recomp"
|
||||
OUTPUT_VARIABLE _tmb_fork_commit OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET)
|
||||
endif()
|
||||
file(WRITE "${CMAKE_BINARY_DIR}/tmb_call_names.cpp.in"
|
||||
"// Generated by CMakeLists.txt from ${_tmb_stub_list}: do not edit.
|
||||
#include \"runtime/ps2_reference.h\"
|
||||
#include <cstddef>
|
||||
|
||||
namespace tmb
|
||||
{
|
||||
extern const char *const kBuildName;
|
||||
extern const ps2x::reference::CallName kCallNames[];
|
||||
extern const size_t kCallNameCount;
|
||||
const char *const kBuildName = \"TMB_Recomp ${_tmb_commit} fork ${_tmb_fork_commit}\";
|
||||
const ps2x::reference::CallName kCallNames[] = {
|
||||
${_tmb_call_names} };
|
||||
const size_t kCallNameCount = ${_tmb_call_count};
|
||||
}
|
||||
")
|
||||
configure_file("${CMAKE_BINARY_DIR}/tmb_call_names.cpp.in" "${CMAKE_BINARY_DIR}/tmb_call_names.cpp" COPYONLY)
|
||||
set_source_files_properties("${CMAKE_BINARY_DIR}/tmb_call_names.cpp" PROPERTIES
|
||||
SKIP_UNITY_BUILD_INCLUSION ON SKIP_PRECOMPILE_HEADERS ON)
|
||||
message(STATUS "TMB_Recomp: ${_tmb_call_count} stub addresses for the reference records")
|
||||
|
||||
target_sources(ps2EntryRunner PRIVATE ${TMB_GENERATED_SOURCES} ${TMB_RUNTIME_SOURCES} "${CMAKE_BINARY_DIR}/tmb_call_names.cpp")
|
||||
target_include_directories(ps2EntryRunner PRIVATE "${TMB_GENERATED_DIR}")
|
||||
|
||||
list(LENGTH TMB_GENERATED_SOURCES _tmb_count)
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
<div align="center">
|
||||
|
||||
<img src="docs/branding/tmb_banner.png" alt="Twisted Metal: Black, native PC port by The Bozos" width="100%">
|
||||
|
||||
# TMB_Recomp
|
||||
|
||||
**A native Linux and Windows port of *Twisted Metal: Black* (USA `SCUS-97101`): the whole game recompiled to C++ and run on the PC itself.**<br>
|
||||
@@ -30,7 +32,7 @@ display mode) comes from native code on the PC's clock.
|
||||
|
||||
You build the game yourself, on your PC, from **your own disc**: nothing of the game is in the download.
|
||||
|
||||
1. Download the release zip from the [Releases](https://github.com/boubou666/TMB_Recomp/releases) page. Each release
|
||||
1. Download the release zip from the [Releases](https://github.com/TheBozos/TMB_Recomp/releases) page. Each release
|
||||
publishes the zip's SHA-256: check it before running anything
|
||||
(`Get-FileHash .\TMB_Recomp-<version>.zip` in PowerShell, or `certutil -hashfile <zip> SHA256`).
|
||||
2. Unzip it anywhere with about 10 GB free (into `D:\Games`, say: the zip holds a `TMB_Recomp` folder), but not in
|
||||
@@ -46,10 +48,12 @@ You build the game yourself, on your PC, from **your own disc**: nothing of the
|
||||
logs are in `%APPDATA%\TMB_Recomp` (the launcher's Maintenance tab opens it).
|
||||
|
||||
The launcher says when a newer release is out (it asks GitHub for the latest version number at start; Settings
|
||||
turns that off; nothing is downloaded by itself). After an update, unzip the new release where the old one was (replacing the files): the
|
||||
launcher sees the code changed since the game was built and offers **Rebuild now** (also Rebuild in the Maintenance
|
||||
turns that off; nothing is downloaded by itself). Its **Update** button downloads the new release's zip, checks it against the
|
||||
release's SHA-256, installs it over this one and restarts (`tools/apply_update.py`); unzipping the new release where the old
|
||||
one was (replacing the files) does the same by hand. The launcher then sees the code changed since the game was built and offers **Rebuild now** (also Rebuild in the Maintenance
|
||||
tab); only what changed is built again, the files the new release no longer has are removed, and the saves stay. To uninstall, delete the folder (and `%APPDATA%\TMB_Recomp` for the saves
|
||||
and settings). Linux players build with `tools/tmb_build.py` (below).
|
||||
and settings). Releases are Windows only for now; on Linux the port builds from source (below), but has not been
|
||||
tested there since the native work of November 2026.
|
||||
|
||||
## Status
|
||||
|
||||
@@ -57,9 +61,9 @@ Picking the work up elsewhere: [`docs/HANDOFF.md`](docs/HANDOFF.md) (state, how
|
||||
|
||||
**Playable, at full speed, as a native port, at NTSC's 60 frames per second.** The game boots, runs its own IOP modules,
|
||||
plays the movies with their sound, goes through the menus and level loading, and plays matches
|
||||
and story levels: driving, weapons, bots, HUD, music and effects, deaths, respawns, saving and loading. With the native
|
||||
path (`scripts/run_native.sh`, at twice the PS2's resolution) a match holds 57.7 to 60.4 fps (4 players split screen:
|
||||
55.8 to 60.4) on a Ryzen 7 7800X3D with an RTX 5070 Ti. Still being checked: every arena and story level to the endings, and some effects against the PS2 picture
|
||||
and story levels: driving, weapons, bots, HUD, music and effects, deaths, respawns, saving and loading. Natively (the default,
|
||||
at twice the PS2's resolution) a match holds 57.7 to 60.4 fps (4 players split screen:
|
||||
55.8 to 60.4) on a Ryzen 7 7800X3D with an RTX 5070 Ti. Every Challenge arena has been played; still being checked: story levels 2 to 8 to the endings, and some effects against the PS2 picture
|
||||
(issues found while playing are fixed as they come: [docs/RECOMP_NOTES.md](docs/RECOMP_NOTES.md)).
|
||||
|
||||
<p align="center">
|
||||
@@ -68,7 +72,7 @@ path (`scripts/run_native.sh`, at twice the PS2's resolution) a match holds 57.7
|
||||
<img src="docs/screenshots/intro_movie.jpg" width="49%" alt="The intro movie">
|
||||
<img src="docs/screenshots/story_menu.jpg" width="49%" alt="The game-mode menu">
|
||||
</p>
|
||||
<p align="center"><sub>The USA release on the native path (<code>scripts/run_native.sh</code>), drawn at twice the PS2's resolution.</sub>
|
||||
<p align="center"><sub>The USA release, native (the default), drawn at twice the PS2's resolution.</sub>
|
||||
</p>
|
||||
|
||||
| Milestone | |
|
||||
@@ -80,7 +84,7 @@ path (`scripts/run_native.sh`, at twice the PS2's resolution) a match holds 57.7
|
||||
| Controller input; every button and stick direction rebindable to keys, controllers and the mouse (F2, `input.ini`) | ✅ |
|
||||
| Movies (PSS, MPEG-2 decoded with FFmpeg) | ✅ |
|
||||
| Title screen and main menu | ✅ |
|
||||
| Memory card: save, load, overwrite (`mc0`, `mc1` in the disc folder) | ✅ |
|
||||
| Memory card: save, load, overwrite (`mc0`, `mc1` in `%APPDATA%\TMB_Recomp`) | ✅ |
|
||||
| Story mode: level 1 of 8 cleared (Junkyard, Midtown Suburbs), progress saved and loaded | ✅ |
|
||||
| Menus, level select, level loading | ✅ |
|
||||
| First match: HUD, cars, textured 3D, bots | ✅ |
|
||||
@@ -94,7 +98,8 @@ path (`scripts/run_native.sh`, at twice the PS2's resolution) a match holds 57.7
|
||||
| No GS emulation: no GS front end, no GS memory, no GS packet read; the native renderer draws and presents the frame (`runtime/native/native_display.h` for the display's field and mode) | ✅ |
|
||||
| Multi-player split screen, 2 to 4 players (a multitap on port 0: players 1-4 on their own controllers; `PS2X_PAD2_SCRIPT` to `PS2X_PAD4_SCRIPT` for scripted players) | ✅ |
|
||||
| Every Challenge arena played (all of them; the ones a fresh save keeps locked through the Cheats tab's Unlock everything) | ✅ |
|
||||
| Settings window (F2): controls, video (resolution, windowed / fullscreen / borderless, render scale) and cheats, all switched while playing | ✅ |
|
||||
| Settings window (F2): controls, video (resolution, windowed / fullscreen / borderless, render scale, frame rate) and cheats, all switched while playing | ✅ |
|
||||
| Frame rates above 60 for high-refresh monitors (the Video tab's frame rate: the frames between the game's 60 drawn interpolated, one game frame of latency; experimental: rain, snow, lens flares and some trails still move at 60) | 🧪 |
|
||||
| Every story level to the endings (level 1 of 8 checked) | 🔧 |
|
||||
| Higher internal resolution (2x by default; the Video tab's render scale, `PS2X_RENDER_SCALE`) | ✅ |
|
||||
| Widescreen, frame rates above the PS2's | ⏳ |
|
||||
@@ -109,7 +114,7 @@ state machine and no copy of GS memory in between.
|
||||
| No IOP hardware: no SIO2, no IOP interrupt controller, DMA or timer registers modelled; the modules reach the IOP through their imports only (`[iop:hw] hardware absent`) | ✅ |
|
||||
| Sound and IOP on the PC's clock (`PS2X_SPU2_WALLCLOCK=1`, `PS2X_IOP_WALLCLOCK=1`) | ✅ |
|
||||
| No SPU2 emulation: 989SND's libsd calls played by the fork's native mixer (`PS2X_NATIVE_AUDIO=1`), the SPU2 absent | ✅ |
|
||||
| No paraLLEl-GS: OpenGL on the GPU (the GS native back end) | ✅ |
|
||||
| No paraLLEl-GS and no GS back end: the native renderer draws with OpenGL on the GPU | ✅ |
|
||||
| Frame loop on the PC's clock (`FramePacer`; `TMB_NATIVE_FRAMES=0`: the vblanks) | ✅ |
|
||||
| Every VU1 program translated to C++ (3D, skinning, effects), no VU interpreter and no sandbox | ✅ |
|
||||
| Every VU0 program translated to C++ (the scene traversal's, bit-exact with VU0, and the 2D engine's), no VIF0 packet read, no VU0 interpreter (`runtime/tmb_vu0.cpp`) | ✅ |
|
||||
@@ -117,7 +122,7 @@ state machine and no copy of GS memory in between.
|
||||
| Font, HUD, loading bar, overlays' darkening and movies drawn natively from the game's variables (no GIF packet built or read) | ✅ |
|
||||
| 3D meshes from an offline native pack (`tools/tmb_mesh_pack.py`, through the fork's generic pack writer and runtime: `PS2Recomp/docs/native_packs.md`) drawn at the game's per-object hook from its own state, in the game's own order, clipped to its microprograms' clip volume; no VIF stream read | ✅ |
|
||||
| Effects (particles, lens flares, rain...) drawn from the game's particle lists (`runtime/tmb_particles.cpp`); no VIF stream read | ✅ |
|
||||
| IOP kernel layer (interrupts, timers, SIF) under the recompiled IOP modules: still the fork's model | 🔧 |
|
||||
| IOP kernel layer (threads, semaphores, interrupts, timers, SIF RPC, cdvdman) answered natively at its API, under the recompiled modules (the software layer, not hardware) | ✅ |
|
||||
| No GS front end, no copy of GS memory, no VIF stream read: the native renderer draws and presents the whole frame (`TMB_GS_FRONTEND=1` and the diagnostic switches bring the GS front end back, headless) | ✅ |
|
||||
|
||||
✅ works · 🔧 in progress · ⏳ not reached yet
|
||||
@@ -138,7 +143,7 @@ program piece by piece. Each piece below replaces a part of the PS2 that was sim
|
||||
| Part of the game | On the PS2 | In the port |
|
||||
|---|---|---|
|
||||
| Frame timing | the vblank interrupt; the game counts the fields a frame took from a hardware timer | each frame paced on the PC's clock (the fork's `FramePacer`) and shown as soon as it ends, its fields counted from the real time it took (`TMB_NATIVE_FRAMES=0`: the vblanks) |
|
||||
| Game code (EE, MIPS R5900) | the EE CPU | 3,572 functions recompiled to C++ (`generated/`), with the ELF's own symbols |
|
||||
| Game code (EE, MIPS R5900) | the EE CPU | 3,572 functions recompiled to C++ (`generated_us/`), with the ELF's own symbols |
|
||||
| IOP modules (989SND, LIBSD, PADMAN, SIO2MAN, MTAPMAN, MCMAN, MCSERV, USBD, LGDEV) | R3000A code on the IOP | all recompiled to C++ by the fork's `tools/iop_recomp.py` (`scripts/iop_recomp.sh`), switch cases and frameless leaf functions included; none left interpreted (`[iop:hw]`: interpreted instructions 0) |
|
||||
| IOP hardware (interrupt controller, DMA channels, root counters, SIO2, CDVD and SIF registers) | devices behind the IOP's registers | none: the IOP kernel (threads, semaphores, events, intrman, timrman, vblank), SIF (sifman, sifcmd, RPC) and cdvdman are answered natively at their API; pad and memory card are the EE's libpad / libmc HLE; the registers a module's start code still touches (LIBSD's bus setup, USBD's probe, SIO2MAN's first write: about 1000 accesses at boot, none after) are plain storage without effect (`PS2X_IOP_HARDWARE=0`, TMB's default; `TMB_IOP_HARDWARE=1` brings the models back) |
|
||||
| Sound mixing (SPU2) | the SPU2 chip, at the IOP's pace | no SPU2: libsd's exports (the recompiled 989SND's calls: voices, banks, effects, the movie stream) taken over by the fork's native mixer (`ps2xIOP/src/native_audio`, `PS2X_NATIVE_AUDIO=1`, TMB's default): 48 voices playing the game's ADPCM banks from a native sound memory, ADSR, reverb and the looping sound data input (movie audio), mixed at 48 kHz when the PC's audio device asks; the SPU2 emulation is absent (no sound RAM, no registers, no DMA, never scheduled; `TMB_NATIVE_AUDIO=0` brings it back) |
|
||||
@@ -151,10 +156,10 @@ program piece by piece. Each piece below replaces a part of the PS2 that was sim
|
||||
| Display (vblank, CSR.FIELD, display mode) | GS CRTC | native: the field from the EE scheduler's vblank count, the mode from `sceGsResetGraph` / `SetGsCrt`, `GsPutIMR` kept for `GsGetIMR` (no GS interrupt exists) |
|
||||
|
||||
```
|
||||
disc files (game_us/, game/) ──► ps2_analyzer ──► recomp/tmb_scus97101.toml, tmb_sces50360.toml (+ recomp/tmb_manual.toml)
|
||||
disc files (game_us/) ──► ps2_analyzer ──► recomp/tmb_scus97101.toml (+ recomp/tmb_manual.toml)
|
||||
│
|
||||
ps2_recomp + the ELF's own symbol table ──► C++ (one file per function, generated/)
|
||||
989SND, LIBSD as the IOP loads them ──► iop_recomp.py ──► C++ (generated/iop/)
|
||||
ps2_recomp + the ELF's own symbol table ──► C++ (one file per function, generated_us/)
|
||||
the disc's IOP modules, loaded offline ──► iop_recomp.py ──► C++ (generated_us/iop/)
|
||||
│
|
||||
CMakeLists.txt ──► PS2Recomp runtime + generated code + runtime/ (TMB's overrides, native adapter)
|
||||
│
|
||||
@@ -176,17 +181,20 @@ disc files (game_us/, game/) ──► ps2_analyzer ──► recomp/tmb_scus971
|
||||
texture cache, GIF translation; `docs/native.md`), shared with the other ports.
|
||||
- `runtime/tmb_overrides.cpp` holds the other game-specific bindings.
|
||||
|
||||
The PS2Recomp fork lives in `PS2Recomp/` (git submodule, [boubou666/PS2Recomp](https://github.com/boubou666/PS2Recomp)),
|
||||
The PS2Recomp fork lives in `PS2Recomp/` (git submodule, [TheBozos/PS2Recomp](https://github.com/TheBozos/PS2Recomp)),
|
||||
shared with the other recompilations built on it (*Valkyrie Profile 2*, *Drakengard*, *The Lord of the Rings: The Third
|
||||
Age*, *Jade Cocoon 2*, *Soulcalibur III* and others). Fixes made for this port land there.
|
||||
|
||||
## Requirements
|
||||
|
||||
- Linux (developed on Arch) or Windows 10/11 with [MSYS2](https://www.msys2.org/) (UCRT64, see below)
|
||||
Players need none of this: the release's launcher and build kit bring everything ("For players" above). To build
|
||||
from the repository:
|
||||
|
||||
- Windows 10/11 with [MSYS2](https://www.msys2.org/) (UCRT64, see below), or Linux (developed on Arch at first; not
|
||||
tested since November 2026)
|
||||
- CMake 3.21+, Ninja, GCC 13+ or Clang with C++20
|
||||
- FFmpeg development libraries (`libavcodec`, `libavutil`, `libswscale`) and `pkg-config` (or a static FFmpeg folder: `PS2X_FFMPEG_ROOT`)
|
||||
- X11/Wayland and OpenGL development headers (raylib is fetched and built by the fork)
|
||||
- `bsdtar` (libarchive) to extract the disc
|
||||
- A CPU with AVX2 (the runtime is built for `x86-64-v3`)
|
||||
- Your own copy of `SCUS-97101` (check the hash above)
|
||||
|
||||
@@ -280,16 +288,22 @@ rem -DLAUNCHER_FONT_DIR=<folder with Exo2[wght].ttf and O
|
||||
(disc, language, background motion, build state) sits next to it. English and French.
|
||||
- The look is the team's, from RecompWatcher: the PS2 BIOS's radial blue, glowing boot towers (motion can be turned
|
||||
off), glass cards, Exo 2 (SIL OFL 1.1, google/fonts at a pinned commit, embedded with its licence; downloaded at
|
||||
configure time, never committed). The icon is drawn at build time by `launcher/tools/make_icon.cpp`. No game art.
|
||||
configure time, never committed). The icon is TMB's variant of The Bozos' logo, the clown with its head on fire (`launcher/tmb.ico`; the game's window uses the same, `runtime/app/tmb.ico`; drawn by `docs/branding/make_logo.py`). No game art.
|
||||
- Updates: at start (Settings: "Check for updates at start") and from Maintenance's "Check for updates", one HTTPS
|
||||
GET of `api.github.com/repos/boubou666/TMB_Recomp/releases/latest` through WinHTTP; a newer `tag_name` shows
|
||||
"Version X is available" with a link to its release page (built from the tag). Offline or no release: silent. When
|
||||
GET of `api.github.com/repos/TheBozos/TMB_Recomp/releases/latest` through WinHTTP; a newer `tag_name` shows
|
||||
"Version X is available" with a link to its release page (built from the tag). Offline or no release: silent. Update
|
||||
downloads `releases/download/<tag>/TMB_Recomp-<version>.zip` and its `.sha256` (addresses built from the tag, not read
|
||||
from the API's answer) into `update\`, then runs `source\tools\apply_update.py` with the kit's Python: it checks the
|
||||
SHA-256 and every name in the zip (one `TMB_Recomp\` folder, no `..`, nothing under `build\` or `game\`, the version
|
||||
asked for), unpacks it whole to `update\staging`, then moves the files over the release; a file in use (the launcher
|
||||
itself) is renamed `*.tmb-old` first and deleted at the next start. The launcher then starts its new exe. When
|
||||
`source\release.ini`'s commit differs from the one in `game\built_from.ini` (written by tmb_build), the Play tab
|
||||
offers "Rebuild now".
|
||||
- `--selftest <iso> --shots <dir> [--wrong <image>] [--error-demo] [--cancel] [--play-seconds s] [--crash-seconds s]`:
|
||||
the whole flow unattended, a screenshot of each screen and `selftest.log` (with `PS2X_USER_DIR` set, the real user
|
||||
folder is untouched). `--screens`: the tabs' screenshots only; `--ui-scale <x>`: another DPI scale; `--update-url
|
||||
<url>`: the update check asks another address (a test server).
|
||||
<url>`: the update check asks another address (a test server); `--download-prefix <url>` downloads the release from
|
||||
there, `--update-now` presses Update once a newer release is found.
|
||||
|
||||
### The release (maintainers)
|
||||
|
||||
@@ -356,7 +370,7 @@ python tools\make_release.py --version 0.1.0 --kit D:\tmb_kit\kit --out D:\tmb_r
|
||||
### Step by step (development)
|
||||
|
||||
```bash
|
||||
git clone --recurse-submodules https://github.com/boubou666/TMB_Recomp.git
|
||||
git clone --recurse-submodules https://github.com/TheBozos/TMB_Recomp.git
|
||||
cd TMB_Recomp
|
||||
scripts/extract_iso.sh "/path/to/Twisted Metal - Black (USA).iso" # disc files -> game_us/
|
||||
scripts/build_tools.sh # ps2_recomp, ps2_analyzer, ps2_vu_aot -> build/tools
|
||||
@@ -374,7 +388,7 @@ The same scripts run in an MSYS2 **UCRT64** shell, with MSYS2's GCC (MSVC is not
|
||||
|
||||
```bash
|
||||
pacman -S --needed mingw-w64-ucrt-x86_64-{gcc,cmake,ninja,pkgconf,ffmpeg,python} git rsync
|
||||
git clone --recurse-submodules https://github.com/boubou666/TMB_Recomp.git
|
||||
git clone --recurse-submodules https://github.com/TheBozos/TMB_Recomp.git
|
||||
```
|
||||
|
||||
Then follow the steps above. `scripts/stage_dlls.sh` copies the DLLs the runner needs next to
|
||||
@@ -406,7 +420,7 @@ the sound and the IOP on the PC's clock) is the runner's default, and the variab
|
||||
- **Game data.** With no argument the runner looks for `game/SCUS_971.01` next to it, then in the user folder; `game/`
|
||||
holds the disc's files and the disc image (`.iso`, for the raw sector reads: the sound banks). With neither, a message
|
||||
box says the data was not found (run the launcher, or see this README) and where it looked.
|
||||
- **Window.** Titled *Twisted Metal: Black*, with an icon (a placeholder, `runtime/app/tmb.ico`; no game art). No
|
||||
- **Window.** Titled *Twisted Metal: Black*, with TMB's flaming-clown icon (`runtime/app/tmb.ico`; no game art). No
|
||||
console window on Windows: the runner is a GUI-subsystem program. Started from a terminal (MSYS2, cmd, PowerShell) or
|
||||
with its output redirected, it prints there as before.
|
||||
- **User folder.** `%APPDATA%\TMB_Recomp` on Windows, `$XDG_DATA_HOME/tmb_recomp` (`~/.local/share/tmb_recomp`) on
|
||||
@@ -442,7 +456,7 @@ key positions):
|
||||
| Key | What it does |
|
||||
|---|---|
|
||||
| F1 | Runtime debugger |
|
||||
| F2 | Settings. Controls: rebind every PS2 button and stick direction, per player, to keys, controller buttons, sticks and triggers, mouse buttons, the wheel or mouse movement (sensitivity, invert Y, cursor capture). Saved to `input.ini` in the user folder (`%APPDATA%\TMB_Recomp\input.ini`; `PS2X_INPUT_CONFIG=<file>` for another place). Video: the resolution (common 4:3 and 16:9 sizes up to the monitor's, and the monitor's own), windowed, fullscreen (the monitor switched to that resolution) or borderless window (the monitor's size), and the render scale (the 3D at 50 % to 200 % of the window's resolution; 200 % is supersampled); Apply changes them at once, Apply and save writes `video.ini` next to `input.ini` (`PS2X_VIDEO_CONFIG=<file>` for another place), read when the window opens. The picture stays 4:3, centred with bars, whatever the window's shape. |
|
||||
| F2 | Settings. Controls: rebind every PS2 button and stick direction, per player, to keys, controller buttons, sticks and triggers, mouse buttons, the wheel or mouse movement (sensitivity, invert Y, cursor capture). Saved to `input.ini` in the user folder (`%APPDATA%\TMB_Recomp\input.ini`; `PS2X_INPUT_CONFIG=<file>` for another place). Video: the resolution (common 4:3 and 16:9 sizes up to the monitor's, and the monitor's own), windowed, fullscreen (the monitor switched to that resolution) or borderless window (the monitor's size), the render scale (the 3D at 50 % to 200 % of the window's resolution; 200 % is supersampled) and the frame rate (60, the game's, by default; "Match the monitor": the monitor's refresh with vsync, every frame between the game's two latest drawn interpolated, its objects, camera and particles moved between them, the HUD as the game drew it last; smoother on a 120 / 144 / 165 / 240 Hz monitor for one game frame, 17 ms, more input lag; the game itself still runs at 60); Apply changes them at once, Apply and save writes `video.ini` next to `input.ini` (`PS2X_VIDEO_CONFIG=<file>` for another place), read when the window opens. The picture stays 4:3, centred with bars, whatever the window's shape. |
|
||||
| F11, Alt+Enter | Between the window and full screen (the last full-screen mode chosen, borderless by default) |
|
||||
|
||||
### Cheats
|
||||
@@ -453,6 +467,7 @@ screen); the variables give their state at launch (`runtime/tmb_cheats.cpp`).
|
||||
| Cheat | | Variable |
|
||||
|---|---|---|
|
||||
| Unlock everything | every level (Freeway, Prison Passage, Skyscrapers, Minion's Stadium...), every vehicle (Yellow Jacket, Axel, Warthog, Manslaughter, Minion...) and every movie, opened in the menus; switched off, put back; saving while it is on keeps them on the card | `TMB_UNLOCK_ALL=1` |
|
||||
| Story: start at | a new story begins at the chosen level instead of the Junkyard (every stage: Midtown Suburbs or Expressway 104, Downtown or Black Vista Highway, Minion's Stadium, Prison Passage, Blackfield Asylum, Abandoned Skyscrapers, Warhawk's Rooftop; and the other arenas), then goes on as the game chains them; for testing the later stages without playing through | `TMB_STORY_LEVEL=<level number>` (the game's level table: 1 Junkyard, 0 Suburbs, 2 Expressway, 5 Downtown, 6 Black Vista, 14 Stadium, 3 Prison, 16 Asylum, 4 Skyscrapers, 13 their second part, 20 Warhawk's Rooftop) |
|
||||
| Infinite health | per player: the car's health held at its maximum (the game's own, as its health bar shows it) | `TMB_PLAYER_GOD=<players>` |
|
||||
| Infinite ammo | per player: pickup weapons and the special are not spent (the HUD's counts stay) | `TMB_INFINITE_AMMO=<players>` |
|
||||
| Infinite energy | per player: the energy bar (freeze, mines, shield...) held full | `TMB_INFINITE_ENERGY=<players>` |
|
||||
@@ -481,14 +496,16 @@ screen); the variables give their state at launch (`runtime/tmb_cheats.cpp`).
|
||||
| `TMB_NATIVE_FRAMES=0` | Frames on the emulated vblanks instead of the PC clock |
|
||||
| `PS2X_GS_SCALE=<n>` | With `TMB_NATIVE=1`: the GS renderer's internal resolution, n times the PS2's each way (1 to 4; default: video.ini's `gs_scale`, 1). Only the GS front end diagnostic draws with it |
|
||||
| `PS2X_WINDOW_SIZE=<w>x<h>`, `PS2X_WINDOW_MODE=windowed\|fullscreen\|borderless`, `PS2X_RENDER_SCALE=<x>` | The window's size, mode and render scale when it opens, over `video.ini` (F2, Video) |
|
||||
| `PS2X_FRAME_RATE=game\|monitor\|<n>` | The frame rate, over `video.ini`'s `frame_rate` (F2, Video): `game` the game's 60, each frame shown once (the default); `monitor` the monitor's refresh with vsync, the frames between the game's interpolated; `<n>` n a second without vsync, interpolated (to measure: e.g. 144 on a 60 Hz monitor) |
|
||||
| `TMB_NATIVE_VU1=1` | VU1 runs the translated programs too (the GS frame then has everything, to compare) |
|
||||
| `TMB_NATIVE_VU1_PCS=<pc,...>` | Diagnostic: leave those setups on VU1 (a `PS2X_VU1_RECORD` reference for a translation) |
|
||||
| `TMB_NATIVE_CHECK=<n>` | Diagnostic: run VU1's own program beside each translation (an interpreter, off in play) and log where they differ |
|
||||
| `PS2X_PRESENT_STATS=1` | Every 600 presents: the game frames not shown and the waits that timed out (the window shows each frame the game publishes once, on the game's clock: no periodic stutter) |
|
||||
| `PS2X_PRESENT_STATS=1` | Every 600 presents: the game frames not shown and the waits that timed out (the window shows each frame the game publishes once, on the game's clock: no periodic stutter). Above 60 (`PS2X_FRAME_RATE`): every 2 s the presents and game frames a second, the share of objects and particle triangles drawn interpolated, teleports, spins and camera cuts drawn as the newer frame, held presents, the longest still picture and gap between presents, `present()`'s time |
|
||||
| `PS2X_CAPTURE_SEQUENCE=<n>`, `PS2X_CAPTURE_SEQUENCE_AT=<s>[,<s>...]`, F8 | n consecutive presents of the window as `seq<k>_<i>.png` (in `PS2X_CAPTURE_WINDOW_DIR` or `PS2X_CAPTURE_SEQUENCE_DIR`) with `seq<k>.txt` (each one's time and the game frames it was drawn between), at those seconds and on F8; the moving objects' screen positions over the same presents in the log (`[interp-trace]`) |
|
||||
| `TMB_LIVE_TOGGLES=<file>` | Diagnostic: words read from the file every 60 frames while the game runs, for the 3D at the hooks: `nodepth`, `nofog`, `noclip`, `flat` (each object in a colour of its own), `opaque`, `noatest`, `notex`, `noguard` (no clip volume), `dump` (one frame's objects, materials and triangles to the log) |
|
||||
| F9 (with `PS2X_CAPTURE_WINDOW_DIR`) | Start / stop a burst of window captures, ten a second (`burst_<ms>.png`) |
|
||||
| `PS2X_NATIVE_VIEW=only` | Show the native frame alone, without the GS one under it |
|
||||
| `PS2X_NATIVE_INTERPOLATE=1`, `PS2X_PRESENT_FPS=<n>` | Draw frames between the game's 50 (objects interpolated), presented at up to n per second |
|
||||
| `PS2X_NATIVE_INTERPOLATE=1`, `PS2X_PRESENT_FPS=<n>` | The older switch for `PS2X_FRAME_RATE=monitor` (with `PS2X_PRESENT_FPS`: `PS2X_FRAME_RATE=<n>`); `PS2X_INTERP_LOG=1` logs the objects drawn as the newer frame (teleports, spins), `PS2X_INTERP_CHECK=1` checks the camera and object matrices against their product |
|
||||
| `PS2X_IOP_NATIVE=1` | Run the recompiled sound driver (`scripts/iop_recomp.sh` generates it) |
|
||||
| `PS2X_SPU2_WALLCLOCK=1`, `PS2X_IOP_WALLCLOCK=1` | Mix the sound when the audio device asks, and run the IOP on the PC's clock |
|
||||
| `TMB_NATIVE_AUDIO=0` | The emulated SPU2 under the recompiled libsd instead of the native mixer (`PS2X_NATIVE_AUDIO=1`, set by default with `TMB_NATIVE=1`: libsd's exports taken over, the SPU2 absent). With native audio, `[audio] native mixer:` every 10 s says what it played and what reached the SPU2 emulation (`SPU2 absent: register accesses 0, ...`; `PS2X_NATIVE_AUDIO_STATS=0` silences it, `PS2X_NATIVE_AUDIO_LOG=1` logs the first libsd calls) |
|
||||
@@ -547,9 +564,11 @@ screen); the variables give their state at launch (`runtime/tmb_cheats.cpp`).
|
||||
| `recomp/` | Recompiler config (analyzer output plus manual additions) |
|
||||
| `runtime/` | Game override module (game-specific bindings) |
|
||||
| `scripts/` | Extract, build tools, analyze, recomp, build runner, run |
|
||||
| `tools/` | `tmb_build.py` (disc to game folder), `make_build_kit.py` (the build kit), analysis helpers (`iso_lbn.py`: disc file of a sector; `gs_fb_decode.py`: framebuffer out of a VRAM dump; `irx_disasm.py`: IOP module code) |
|
||||
| `tools/` | `tmb_build.py` (disc to game folder), `make_build_kit.py` (the build kit; `build_kit_packages.json` pins its MSYS2 packages), `make_release.py` (the release zip), analysis helpers (`iso_lbn.py`: disc file of a sector; `gs_fb_decode.py`: framebuffer out of a VRAM dump; `irx_disasm.py`: IOP module code) |
|
||||
| `launcher/` | `TMB Launcher.exe`: checks the player's disc, builds the game with the kit, starts it (raylib, Dear ImGui) |
|
||||
| `docs/` | Bring-up notes |
|
||||
| `docs/` | Bring-up notes (`RECOMP_NOTES.md`), `HANDOFF.md`, `RELEASE_CHECKLIST.md` |
|
||||
| `.github/workflows/` | `release.yml`: the release, built only on a version tag ("Making a release") |
|
||||
| `CHANGELOG.md`, `LICENSE` | What each release changes; TMB_Recomp's own code under the MIT licence (PS2Recomp stays GPL-3.0) |
|
||||
| `PS2Recomp/` | PS2Recomp fork (submodule) |
|
||||
|
||||
Everything derived from the game (`game_us/`, `game/`, `generated_us/`, `generated/`, `build/`, disc images, captures) is git-ignored. Never commit or
|
||||
@@ -557,6 +576,7 @@ redistribute it.
|
||||
|
||||
## Credits
|
||||
|
||||
- [PS2Recomp](https://github.com/ran-j/PS2Recomp) by ran-j and contributors (GPL), the recompiler and runtime this port is built on.
|
||||
- The *Valkyrie Profile 2: Silmeria* and *Drakengard* recompilations, developed on the same PS2Recomp fork; runtime fixes are shared.
|
||||
- **The Bozos**: boubou666 and Arzaroth, who make this port and the PS2Recomp fork it runs on ([RecompWatcher](https://thebozos.github.io/RecompWatcher/) shows our projects).
|
||||
- [PS2Recomp](https://github.com/ran-j/PS2Recomp) by ran-j and contributors (GPL-3.0), the recompiler and runtime this port is built on.
|
||||
- The other recompilations on the same fork (*Valkyrie Profile 2: Silmeria*, *Dark Cloud*, *Soulcalibur III*, *Drakengard*, *The Lord of the Rings: The Third Age*, *Jade Cocoon 2* and others): runtime fixes are shared, and DC_Recomp's native sound mixer plays TMB's sound.
|
||||
- *Twisted Metal: Black* © Sony Interactive Entertainment, developed by Incognito Entertainment. This is an unofficial fan project, not affiliated with or endorsed by them.
|
||||
@@ -19,8 +19,8 @@ Windows, Ryzen 7 7800X3D, RTX 5070 Ti; scripted play through the menus into the
|
||||
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/boubou666/TMB_Recomp.git`. `PS2Recomp` is the fork
|
||||
`boubou666/PS2Recomp`; TMB pins a commit of its `native/renderer` branch (the native work, merged into `main` as it
|
||||
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
|
||||
@@ -79,7 +79,7 @@ Windows, Ryzen 7 7800X3D, RTX 5070 Ti; scripted play through the menus into the
|
||||
|
||||
- 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 `boubou666/PS2Recomp`, not into workarounds here. Push the
|
||||
- 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.
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
## Layout
|
||||
- `game/` – full disc contents (ELF `SCES_503.60`, `MOD/*.IRX`, `IOPRP213.IMG`, data folders). The runtime uses the
|
||||
ELF's folder as `cdrom0:`.
|
||||
- `PS2Recomp/` – submodule, fork https://github.com/boubou666/PS2Recomp branch `main`, shared with VP2S and Drakengard.
|
||||
- `PS2Recomp/` – submodule, fork https://github.com/TheBozos/PS2Recomp branch `main`, shared with VP2S and Drakengard.
|
||||
- `recomp/tmb_sces50360.toml` – **current config**: `ps2_analyzer` output (352 SDK stubs bound by address, 326
|
||||
entry points, 1 jump table at `0x4ee6a0`), output redirected to `generated/`.
|
||||
- `runtime/tmb_overrides.cpp` – game override module, matched on ELF name `SCES_503.60` + entry `0x100008`.
|
||||
@@ -1611,7 +1611,7 @@ folder) and `game\` (the staged game).
|
||||
--good / --wip / --early for states, the focus colour for keyboard navigation (Tab, arrows, Enter; Esc goes back to
|
||||
Play). Mouse and keyboard only. Wordmark "The Bozos" (`TEAM_NAME` in `launcher/src/main.cpp`), "by boubou666 &
|
||||
Arzaroth" under it, the title in large type with "PC port — your own disc required", a link to
|
||||
https://boubou666.github.io/RecompWatcher/ (no custom domain in the site: GitHub Pages' repository path). Exo 2
|
||||
https://thebozos.github.io/RecompWatcher/ (no custom domain in the site: GitHub Pages' repository path). Exo 2
|
||||
from google/fonts at 1796e344 (`ofl/exo2/Exo2[wght].ttf`, SHA-256 205a4486..., SIL OFL 1.1, no reserved font name),
|
||||
downloaded and checked at configure time (or `LAUNCHER_FONT_DIR`), embedded as RCDATA with OFL.txt; stb_truetype
|
||||
draws the variable font's default instance (weight 400), headings get a faux bold and the glow. Logs in Cascadia
|
||||
@@ -1696,7 +1696,7 @@ clean PC).
|
||||
must be pushed first and the owner publishes the draft.
|
||||
- **Launcher: version and updates.** The footer shows `TMB_Recomp <version> · <commit>`; the exe's version resource
|
||||
too. At start (launcher.ini `update_check`, a Settings toggle; not in a "dev" build) and from Maintenance's "Check for
|
||||
updates": one GET of `https://api.github.com/repos/boubou666/TMB_Recomp/releases/latest` through WinHTTP (the
|
||||
updates": one GET of `https://api.github.com/repos/TheBozos/TMB_Recomp/releases/latest` through WinHTTP (the
|
||||
system's proxy and certificates, 5 s timeouts) in a thread. A newer `tag_name` (semantic versions, 1.0.0-rc <
|
||||
1.0.0) shows "Version X is available" on the Play tab with "Open the release page"; the link is built from the tag
|
||||
(only `[A-Za-z0-9._+-]`), never taken from the response; nothing is downloaded. Offline, no release yet (404), a
|
||||
@@ -1800,3 +1800,79 @@ push or pull request), and every release has a changelog.
|
||||
zip with `game/SCUS_971.01` (ELF) and an ISO9660 image: refused with each reason; `--publish-only --dry-run` printed
|
||||
the gh command; 0.1.1-test without `--allow-missing-changelog`: refused before the export; a tampered pin
|
||||
(version, hash) refused.
|
||||
|
||||
## Frame rates above 60: frames drawn between the game's (2026-11-02)
|
||||
|
||||
The game's logic stays at 60 Hz (TheGame::Update once per NTSC field: physics counts in fields, see "falls"). For
|
||||
120 / 144 / 165 / 240 Hz monitors the window can run on its own clock and draw, at each present, the game's two latest
|
||||
frames blended by where that clock lies between them: one game frame (about 17 ms) of extra latency. Off by default:
|
||||
"60 (the game's)" keeps the present loop as it was (it follows each published frame once, `followFrames`, no vsync).
|
||||
|
||||
- **The option**: F2, Video, "Frame rate": "60 (the game's)" or "Match the monitor (<n> Hz), smoothed" (vsync on,
|
||||
`glfwSwapInterval(1)` through raylib's `FLAG_VSYNC_HINT`, only in that mode; if presents run over 1.5 times the
|
||||
monitor's refresh for 2 s, vsync is taken as not honoured and the window's own timer at the refresh takes over).
|
||||
`video.ini` `frame_rate = game | monitor | <n>`, `PS2X_FRAME_RATE` over it; `<n>` is a set rate without vsync (for
|
||||
measuring on a 60 Hz monitor). `PS2X_NATIVE_INTERPOLATE=1` (`PS2X_PRESENT_FPS=<n>`) is the older name for it.
|
||||
Applies at once (`ps2_video::apply` -> `Renderer::setFrameRate`). Interpolation needs the native renderer's own
|
||||
frame (`presentsAlone`, no stream draws); otherwise frames show as they come.
|
||||
- **The clock** (`Renderer::endFrame`, `pickInterpolated`): each published frame gets a place on a smoothed clock
|
||||
(the publishing interval averaged, each frame's time pulled 10% toward its real publishing time, so frames published
|
||||
a few ms early or late are still evenly spaced; restarted after a pause over 250 ms or a hitch over 4 intervals: no
|
||||
blending across a load). The window draws the time `now - (interval + recent lateness + 2 ms)`: the pair of frames
|
||||
around it from the last six, and how far between. Past the newest frame it holds the newest (counted as a held
|
||||
present).
|
||||
- **Objects** (`setKey(key, base)`, `setParts(camera, object)`): TMB's mesh hook keys an object by its file and
|
||||
offset, its instance (s7) and its count among the frame's alike ones; the base is the key without that count. Its
|
||||
matrix is given as camera (VU 9-12, the view's projection, z row scaled by the object's depth factor) times object
|
||||
(VU 0-3: object to camera, the camera's turn included); `PS2X_INTERP_CHECK=1` checks the product against the matrix
|
||||
(1.4 M batches, worst relative error 2e-7). Between two frames: the camera part linearly, the object's rotation by
|
||||
slerp with its column scales and translation linearly (no shrinking on a fast turn); an object turning over 90
|
||||
degrees a frame (a spinning wheel: the shortest arc would turn it backwards) keeps the newer turn with its place
|
||||
interpolated; a teleport (a camera-space step over half its distance) and objects without a match (spawned) are
|
||||
drawn as the newer frame has them; objects gone from the newer frame are not drawn.
|
||||
- **Matching** (`matchFrames`, once per pair of frames, not per present): an object alone of its kind in its view (a
|
||||
split screen's view: its clip) is matched to its previous self. The count among alike objects (the same scenery
|
||||
model placed many times, cars' parts without an instance) changes whenever one of them is culled, so matching by
|
||||
key slid barrels and posts toward their neighbours: alike objects are matched to the nearest of the previous
|
||||
frame's, either where it was or moved by the camera's move (estimated per view from the unique objects: D = A' A^-1
|
||||
of the one most others agree with), whichever tells them apart better; when the second nearest is within twice the
|
||||
nearest's distance (a row of alike objects passing about one spacing a frame) it is drawn as the newer frame has it
|
||||
(1 to 2 objects a frame in a 4-player match). A view where 60% of the matched objects teleported or moved over 7.5%
|
||||
of the width is a camera cut: drawn as the newer frame.
|
||||
- **Particles and sprites** (`drawTracked`): screen-space triangles with an id each; a triangle with the same id in
|
||||
the previous frame has its corners blended (a centroid move over 30% of the width: not). TMB's particles (sprites,
|
||||
textured sprites, lines) are (view, system, index) per quad; the mesh pack's sprites and ribbons (key, batch,
|
||||
triangle). Not tracked: sprines, stripes, arcs, kites, rain and snow, the lens flares (drawn as the newer frame).
|
||||
- **HUD, menus' 2D, movies**: unchanged (the overlay is the latest the game published; movies are backdrops).
|
||||
- **Cost**: a frame is uploaded once (its tracked triangles again when blended); per present the matrices of the
|
||||
keyed objects are blended on the CPU (the matching is per frame pair).
|
||||
|
||||
Measured on this PC (1P Junkyard Challenge match, `arena.sh`'s script; 4P split screen, `main4p.sh`'s with player 1
|
||||
driving; 640 x 448 window unless said), `PS2X_PRESENT_STATS=1`:
|
||||
|
||||
| Run | Presents / s | Game frames / s | Objects interpolated | present() |
|
||||
|---|---|---|---|---|
|
||||
| Default (60, follow frames), final build | 60 | 59.4 | - | 0-1 of 600 frames not shown in a match (25-50 around a 24-picture capture, which stops the loop to write PNGs) |
|
||||
| `PS2X_FRAME_RATE=144`, 1P | 141-144 | 59.0-59.5 | 96-100% of keyed batches, particles' triangles 85-99% | 1.2-3.5 ms average, 7 ms max |
|
||||
| `PS2X_FRAME_RATE=144`, 4P | 141-143 | 59.0-59.5 | 98% | 2.6-3.2 ms average |
|
||||
| `monitor` (60 Hz here: vsync) | 60.0-60.8 | 59.5 | 98-99% | (includes the vsync wait) |
|
||||
| `PS2X_FRAME_RATE=1000`, 1P | 400-650 | 59.0-59.5 | 97-99% | 1.4-2.4 ms: the whole loop 1.5-2.5 ms a present |
|
||||
| `PS2X_FRAME_RATE=1000`, 1P, 1920 x 1080 | 190-270 | 59.4-59.9 | 96-99% | 3.4-5.2 ms average: 3.7-5.2 ms a present |
|
||||
| `PS2X_FRAME_RATE=144`, 1P, 1920 x 1080 | 142-143 (130 in one 2 s window) | 58.9-59.4 | 97-99% | 3.7-5.0 ms average, 7.7 max |
|
||||
|
||||
Held presents (the clock past the newest frame) 0-2 per 2 s in a match; longest still picture 0 ms in a match (50-80 ms
|
||||
in the menus, where the game's own frames come unevenly); longest gap between presents 7.6-8 ms at 144 (35-50 ms once
|
||||
every few seconds: the window captures). The game's 60 does not drop with 600 presents a second.
|
||||
|
||||
Smoothness (`PS2X_CAPTURE_SEQUENCE=24`, the `[interp-trace]` positions of the five objects that moved most, followed
|
||||
from frame to frame through their match; `trace_stats.py` in the session's scratchpad): at 144 the presents are
|
||||
7.0 ms apart (6.9-7.6), alpha steps by 0.42 each present, the traced objects move monotonically (no direction
|
||||
reversal), the step from one present to the next varies by 1-6% from its neighbours' (unevenness 0.01-0.06; a
|
||||
60 Hz present moves the same object 2.4 times as far per picture). The 4P row of alike objects passing a spacing a
|
||||
frame showed the one artifact found (the nearest match is the wrong one: the row ran backwards between frames) until
|
||||
the ambiguity rule.
|
||||
|
||||
Known artifacts: the objects drawn as the newer frame (teleports, ambiguous alike ones, cuts) and the untracked effects
|
||||
(sprines, stripes, arcs, kites, rain and snow, lens flares) move at 60 against the rest; the HUD is 60 Hz; anything
|
||||
the game moves without a key (rain, the screen-space programs of the VIF path) is 60 Hz; a camera cut detected late
|
||||
(fewer than 60% of the objects moved) blends one frame across it.
|
||||
@@ -0,0 +1,121 @@
|
||||
# The reference harness
|
||||
|
||||
Phase 0 of BozoEngine (its spec: `D:\BozoEngine\docs\specs\harness.md`): TMB on its current runtime (the PS2Recomp
|
||||
fork) runs deterministically and records, per game frame, what the guest computed. Two runs with the same scripted
|
||||
input write the same file; a later runtime must write the same records.
|
||||
|
||||
## Running
|
||||
|
||||
```sh
|
||||
PS2X_DETERMINISTIC=1 PS2X_REFERENCE=run.ref PS2X_REFERENCE_FRAMES=9000 PS2X_USER_DIR=<empty folder> \
|
||||
PS2X_PAD_SCRIPT="<frame:BUTTON/frames,...>" build/game_us/PS2Recomp/ps2xRuntime/ps2EntryRunner game_us/SCUS_971.01
|
||||
tools/ref_compare.py a.ref b.ref
|
||||
```
|
||||
|
||||
- `PS2X_DETERMINISTIC=1`: the deterministic mode (below). Off, every path is as before.
|
||||
- `PS2X_REFERENCE=<file.ref>`: the recorder. Works in either mode (only deterministic runs compare equal).
|
||||
- `PS2X_REFERENCE_FRAMES=<n>`: the process exits (0) once n frames are recorded.
|
||||
- `PS2X_REFERENCE_CALLS=<n>` (default 120), `PS2X_REFERENCE_CALLS_FROM=<f>`: the full call lists of n frames from
|
||||
frame f, as text, in `<file>.ref.calls`.
|
||||
- `PS2X_REFERENCE_DUMP=<f>[-<g>][,...]`: RAM (32 MB) then scratchpad (16 KB) of those frames in `<file>.ref.ram.<f>`.
|
||||
- `PS2X_REFERENCE_MASK=<address>:<bytes>[,...]`: RAM hashed as zeros there (listed in the header). None is needed for
|
||||
TMB; `PS2X_REFERENCE_CHECK_HOST=1` scans RAM every 600 frames for words that look like host addresses (into the
|
||||
host's copy of RAM or the scratchpad, or near the runtime's own data) and logs them.
|
||||
- `PS2X_REFERENCE_RUN=<name>`: the run's name in the header (default: the file's stem).
|
||||
- `PS2X_USER_DIR=<folder>`: a fresh folder per run, so the memory cards start pristine and the settings default.
|
||||
|
||||
Pad scripts in deterministic mode are keyed on game frames: `frame:BUTTON/frames` (held 30 frames when not given);
|
||||
`PS2X_PAD2_SCRIPT` .. `PS2X_PAD4_SCRIPT` alike. `tools/ref_pad_script.py` converts a timed script: run it once with
|
||||
`PS2X_DETERMINISTIC=1 PS2X_PAD_CLOCK=wall PS2X_PAD_LOG=1` (the pad on the wall clock, each change logged with its
|
||||
frame; that run is not deterministic), then `--log <its log> --from-log` gives pad 1's presses at the frames they
|
||||
landed, and `--log <log> "<timed script>"` maps any other timed script through the same anchors.
|
||||
|
||||
## What deterministic mode does
|
||||
|
||||
The run-to-run variation found in the code (`D:\BozoEngine\docs\notes\tmb-determinism.md`) and what each became:
|
||||
|
||||
| # | Source | Deterministic mode |
|
||||
|---|---|---|
|
||||
| 1 | The frame step from host time (`FramePacer::frameEnd`), the EE cycles charged at the frame end from it, TMB's field carry | `FramePacer` returns exactly one period of the cap (1/60 s); TMB charges exactly `294912000 / field rate` EE cycles less what the frame accounted (`nativeFrameEnd`), so one field per frame, no carry. The window is still held to 60 fps (pacing only) |
|
||||
| 2 | `sceCdReadClock` from the host's date (TMB seeds its RNG from it) | 2001-06-18 12:00:00 (`ps2x::det::fixedDate`); OSD time zone UTC |
|
||||
| 3 | The IOP on the host clock (`PS2X_IOP_WALLCLOCK`, which TMB sets), the IOP thread | Ignored: the IOP advances only by the EE cycles accounted, on the EE thread (`PS2X_IOP_THREAD` ignored) |
|
||||
| 4 | The native mixer rendered on the audio device thread | Mixed on the IOP's clock: 768 IOP cycles per 48 kHz sample, brought up to the current IOP cycle before every libsd call and at the end of every IOP slice (`NativeMixer::advanceTo`), so envelopes, ended voices, input positions and the input's half interrupts change only at IOP points. The device only drains a 16384-sample queue (silence when dry, oldest dropped when full). The emulated SPU2 is never on the wall clock |
|
||||
| 5 | Pad scripts in seconds; host keyboard / gamepads; players from plugged gamepads | Scripts in game frames (the frame count only moves at frame ends: latched per frame); no host input (`PS2X_PAD_NO_HOST` forced, `PS2X_PAD_INPUT` / `PS2X_PAD_RECORD` off); players 2-4 present only by their scripts; a pad port with no player behind it (port 2 while the multitap is on port 1) reads at rest instead of falling back to the host's keyboard and first gamepad (found by the first proof runs: its sticks read 0x7f or 0x80 with the window's focus) |
|
||||
| 6 | EE wall-clock catch-up (`PS2X_EE_CATCHUP`, on by default) and host deadlines | Off; every scheduled event is due by its cycle alone; vblank holds ignored; an idle wait still sleeps (pacing) but always charges exactly the cycles to the next event; `waitHostDeadline` (other ports' frame waits) completes at the next dispatch point |
|
||||
| 7 | Movies: picture clock from host time, host-deadline waits, decode time charged to the EE | Frame-clocked: pictures paced by the vblank count (which follows EE cycles), no host deadline, decode time not charged. A movie still plays whole (it ends no game frame, so the pad script's frame clock stands still through it) |
|
||||
| 8 | Lens flare depth read back from the GPU into guest RAM; `inMatch` from a 100 ms host-time window | Flare samples all far (0); `inMatch` / the menus' window measured in game frames (frame count / 60), so a frame's kind follows the kinds of the frames before it |
|
||||
| 9 | Memory card contents and dates; file dates | A fresh `PS2X_USER_DIR` per run (pristine card); every card and file date is the fixed date |
|
||||
| 10 | Settings window actions (Cheats tab) | The tab shows nothing but a note; only the environment's cheats apply (from launch). `TMB_CHEATS_TOGGLE` off |
|
||||
|
||||
Beyond the list: the MPEG decode charge and `waitHostDeadline` (above), the OSD time zone, file `getstat` dates.
|
||||
|
||||
Left as they are (checked: no guest-visible effect, or not used by TMB's native port): the GS front end and VIF1
|
||||
thread (absent in the native port), the CD read-ahead threads (the guest waits for them synchronously), the renderer's
|
||||
present thread (reads published frames only), host-side statistics and traces.
|
||||
|
||||
## The record file
|
||||
|
||||
Little-endian, packed. Hashes: XXH64 (seed 0) for `ram`, `scratchpad`, `calls`, `draws`, `threads`; the sound is
|
||||
FNV-1a 64. No hash ever takes a host pointer: textures are identified by their content.
|
||||
|
||||
Header (240 bytes, then `maskCount` pairs of u32 {address, bytes}):
|
||||
|
||||
| Offset | Type | Field |
|
||||
|---|---|---|
|
||||
| 0 | char[8] | magic `PS2XREF1` |
|
||||
| 8 | u32 | version (1) |
|
||||
| 12 | u32 | headerBytes (240 + 8 x maskCount: where the records start) |
|
||||
| 16 | u32 | recordBytes (80) |
|
||||
| 20 | u32 | hash (1: XXH64 seed 0, sound FNV-1a 64) |
|
||||
| 24 | u32 | ramBytes (33554432) |
|
||||
| 28 | u32 | scratchpadBytes (16384) |
|
||||
| 32 | u64 | elfHash: XXH64 of the ELF file |
|
||||
| 40 | u32 | flags: bit 0 deterministic mode |
|
||||
| 44 | u32 | maskCount |
|
||||
| 48 | char[64] | run name |
|
||||
| 112 | char[64] | build ("TMB_Recomp <commit> fork <commit>", as configured) |
|
||||
| 176 | char[64] | the ELF's file name |
|
||||
|
||||
Record (80 bytes), one per game frame. A game frame ends where the game hands its picture over
|
||||
(`EeScheduler::presentGuestFrame`: TMB's `timer1Handler` / `sceGsSyncV`, menus and loading screens included; movies
|
||||
end none). Frame 0 is everything up to the first one.
|
||||
|
||||
| Offset | Type | Field |
|
||||
|---|---|---|
|
||||
| 0 | u32 | frame |
|
||||
| 4 | i32 | thread: the guest thread running at the frame end |
|
||||
| 8 | u64 | ram: XXH64 of the 32 MB of EE RAM (masked ranges as zeros) at the frame end |
|
||||
| 16 | u64 | scratchpad: XXH64 of the 16 KB scratchpad |
|
||||
| 24 | u64 | calls: XXH64 of the frame's calls, each 7 u32 {id, a0, a1, a2, a3, v0, flags}, in call order |
|
||||
| 32 | u64 | draws: the frame's published draw lists (below) |
|
||||
| 40 | u64 | sound: FNV-1a 64 of the stereo int16 samples mixed during the frame (0 when none) |
|
||||
| 48 | u64 | threads: XXH64 of i32 {running thread, then the ready threads in run order} |
|
||||
| 56 | u64 | eeCycle: the EE cycle count at the frame end |
|
||||
| 64 | u32 | callCount |
|
||||
| 68 | u32 | drawBatches |
|
||||
| 72 | u32 | drawVertices |
|
||||
| 76 | u32 | soundSamples (800 a frame once the mix runs at one field per frame) |
|
||||
|
||||
Calls: the dispatcher's calls (JAL / JALR) to the game's library and kernel stubs, the 362 addresses of the generated
|
||||
code's stub list (`ps2_recompiled_stubs.h`, compiled into `build/.../tmb_call_names.cpp` at configure time), and raw
|
||||
`syscall`s. `id` is FNV-1a 32 of the stub's name with the top bit clear, or `0x80000000 | number` for a syscall;
|
||||
`a0`-`a3` the argument registers' low words; `v0` the result's low word; `flags` 1 when the call blocked (its result
|
||||
comes later), 2 when the frame ended inside it (`sceGsSyncV`, TMB's frame end). A tail jump compiled to a direct call
|
||||
is not seen. The `.calls` side file lists them as text: name, id, a0-a3, result.
|
||||
|
||||
Draws: per published list (kind 1 the 3D frame at `Renderer::endFrame`, 2 the 2D overlay at `publishOverlay`, 3 a
|
||||
movie picture at `setBackdrop`) h = XXH64(kind), then per batch h = XXH64(words, h) of 8 u64 {tex0, texa, region,
|
||||
the flags packed (textured, blend << 8, alphaRef << 16, alphaTest << 24, depthTest << 25, depthWrite << 26, clampU
|
||||
<< 27, clampV << 28, fog << 29, sampleTarget << 30, fromGsContext << 31, alphaBlend << 32, context << 40), fogColour,
|
||||
texture identity (XXH64 of its RGBA texels seeded with XXH64 of {width, height}; 0 for none), vertex count, 0}, then
|
||||
each GS write {address, value} of a GS-context batch, the matrix (16 floats), the clip (4 floats) and the vertices
|
||||
(32 bytes each: x, y, z, u, v, rgba, fog, q). The frame's `draws` folds each list's h in order: d = XXH64({d, h}).
|
||||
|
||||
## Comparing
|
||||
|
||||
`tools/ref_compare.py a.ref b.ref [--ignore field,...]` prints both headers, then either `identical: N frames
|
||||
compared` or the first frame where any field differs, every field that differs there with both values, and the first
|
||||
frame each field differs at. With RAM dumps of that frame from both runs (`PS2X_REFERENCE_DUMP=<frame>`), the first
|
||||
differing 32-byte block (address, both runs' bytes); with both runs' call lists of the first frame whose calls differ
|
||||
(`PS2X_REFERENCE_CALLS_FROM=<frame> PS2X_REFERENCE_CALLS=1`), the two lists side by side from their first difference.
|
||||
Exit status 0 when identical, 1 when not.
|
||||
@@ -53,6 +53,8 @@ Release: `TMB_Recomp-<version>.zip`, SHA-256 `<from the .sha256>`, commit `<comm
|
||||
|
||||
- [ ] 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.
|
||||
|
||||
|
After Width: | Height: | Size: 507 KiB |
|
After Width: | Height: | Size: 360 KiB |
|
After Width: | Height: | Size: 49 KiB |
|
After Width: | Height: | Size: 340 KiB |
@@ -0,0 +1,284 @@
|
||||
"""The Bozos' logo (python make_logo.py) and Twisted Metal: Black's variant (python make_logo.py tmb): a clown face drawn from retro console shapes (cross and triangle eyes, a round red nose, square teeth),
|
||||
on the PS2 BIOS blue with boot towers, in RecompWatcher's colours. Writes PNGs: the icon, the wordmark, a banner."""
|
||||
import math
|
||||
import os
|
||||
import sys
|
||||
from PIL import Image, ImageDraw, ImageFilter, ImageFont
|
||||
|
||||
OUT = os.path.dirname(os.path.abspath(__file__))
|
||||
FONT = r'D:\tmb_kit\downloads\exo2-1796e344\Exo2[wght].ttf'
|
||||
SS = 4 # supersampling
|
||||
|
||||
INK = (232, 239, 255)
|
||||
DIM = (154, 172, 207)
|
||||
CROSS = (126, 166, 255)
|
||||
CIRCLE = (255, 107, 122)
|
||||
TRIANGLE = (79, 224, 163)
|
||||
SQUARE = (255, 143, 216)
|
||||
ACCENT = (183, 155, 255)
|
||||
|
||||
|
||||
def font(size, weight):
|
||||
f = ImageFont.truetype(FONT, size)
|
||||
try:
|
||||
f.set_variation_by_axes([weight])
|
||||
except Exception:
|
||||
pass
|
||||
return f
|
||||
|
||||
|
||||
def radial(w, h, cx, cy, r, stops):
|
||||
"""A radial gradient: stops = [(t, (r,g,b)), ...], t from the centre (0) to r (1)."""
|
||||
img = Image.new('RGB', (w, h))
|
||||
px = img.load()
|
||||
for y in range(h):
|
||||
for x in range(w):
|
||||
t = min(math.hypot(x - cx, y - cy) / r, 1.0)
|
||||
for i in range(len(stops) - 1):
|
||||
t0, c0 = stops[i]
|
||||
t1, c1 = stops[i + 1]
|
||||
if t <= t1:
|
||||
k = (t - t0) / (t1 - t0) if t1 > t0 else 0
|
||||
px[x, y] = tuple(int(c0[j] + (c1[j] - c0[j]) * k) for j in range(3))
|
||||
break
|
||||
return img
|
||||
|
||||
|
||||
def background(w, h):
|
||||
small = radial(w // 8, h // 8, w // 16, h // 8 * 0.92, max(w, h) // 8 * 0.95,
|
||||
[(0, (20, 50, 143)), (0.55, (5, 11, 38)), (1, (1, 3, 10))])
|
||||
return small.resize((w, h), Image.BICUBIC)
|
||||
|
||||
|
||||
def towers(size, w, h, base, count, seed=7, dim=1.0):
|
||||
"""The PS2 boot screen's towers: glowing translucent bars rising from the bottom."""
|
||||
layer = Image.new('RGBA', (w, h), (0, 0, 0, 0))
|
||||
d = ImageDraw.Draw(layer)
|
||||
rnd = seed
|
||||
bw = w / (count * 1.6)
|
||||
for i in range(count):
|
||||
rnd = (rnd * 1103515245 + 12345) & 0x7fffffff
|
||||
frac = 0.25 + (rnd % 1000) / 1000 * 0.75
|
||||
x = (i + 0.3) * w / count
|
||||
top = base - frac * size
|
||||
alpha = int((40 + (rnd >> 10) % 60) * dim)
|
||||
d.rectangle([x, top, x + bw, h], fill=(111, 141, 255, alpha))
|
||||
d.rectangle([x, top, x + bw, top + bw * 0.25], fill=(201, 219, 255, int(alpha + 60 * dim)))
|
||||
glow = layer.filter(ImageFilter.GaussianBlur(w / 120))
|
||||
return Image.alpha_composite(glow, layer)
|
||||
|
||||
|
||||
def glow_shape(canvas, draw_fn, blur, strength=1.0):
|
||||
"""Draws a shape twice: blurred (its glow) and sharp."""
|
||||
g = Image.new('RGBA', canvas.size, (0, 0, 0, 0))
|
||||
draw_fn(ImageDraw.Draw(g))
|
||||
# Blurred with premultiplied alpha, so the glow keeps the shape's colour (no dark fringe on a light background).
|
||||
pre = Image.new('RGBA', g.size)
|
||||
r_, g_, b_, a_ = g.split()
|
||||
from PIL import ImageChops
|
||||
pre = Image.merge('RGBA', [ImageChops.multiply(c, a_) for c in (r_, g_, b_)] + [a_]).filter(ImageFilter.GaussianBlur(blur))
|
||||
pr, pg, pb, pa = pre.split()
|
||||
import numpy as _np
|
||||
arr = _np.asarray(pre).astype(_np.float32)
|
||||
alpha = arr[..., 3:4]
|
||||
rgb = _np.where(alpha > 0, arr[..., :3] * 255.0 / _np.maximum(alpha, 1), 0)
|
||||
halo = Image.fromarray(_np.concatenate([_np.clip(rgb, 0, 255), alpha], axis=2).astype(_np.uint8), 'RGBA')
|
||||
if strength != 1.0:
|
||||
a = halo.getchannel('A').point(lambda v: min(255, int(v * strength)))
|
||||
halo.putalpha(a)
|
||||
canvas.alpha_composite(halo)
|
||||
canvas.alpha_composite(g)
|
||||
|
||||
|
||||
def clown(canvas, cx, cy, r, fire=False):
|
||||
"""The clown face, centred at (cx, cy), radius r (in canvas pixels). fire: flames for hair and no hat (Twisted Metal:
|
||||
Black's variant)."""
|
||||
lw = max(2, int(r * 0.075))
|
||||
if fire:
|
||||
fire_hair(canvas, cx, cy, r)
|
||||
# Hair puffs: two clouds of circles, in the cross and square colours.
|
||||
def puffs(d):
|
||||
for side, col in ((-1, CROSS), (1, SQUARE)):
|
||||
for k, (dx, dy, rr) in enumerate([(1.02, -0.28, 0.36), (1.18, 0.08, 0.34), (0.98, 0.38, 0.30), (0.78, -0.62, 0.28)]):
|
||||
x = cx + side * dx * r
|
||||
y = cy + dy * r
|
||||
d.ellipse([x - rr * r, y - rr * r, x + rr * r, y + rr * r], fill=col + (255,))
|
||||
if not fire:
|
||||
glow_shape(canvas, puffs, r * 0.12, 0.8)
|
||||
# Head.
|
||||
def head(d):
|
||||
d.ellipse([cx - r, cy - r, cx + r, cy + r], fill=INK + (255,))
|
||||
glow_shape(canvas, head, r * 0.08, 0.6)
|
||||
d = ImageDraw.Draw(canvas)
|
||||
# Small cone hat in the accent violet, a pompom on top.
|
||||
hx, hy = cx, cy - r * 0.86
|
||||
if fire:
|
||||
hx = None
|
||||
if hx is not None:
|
||||
d.polygon([(hx - r * 0.34, hy + r * 0.1), (hx + r * 0.34, hy + r * 0.1), (hx + r * 0.05, hy - r * 0.78)], fill=ACCENT + (255,))
|
||||
if hx is not None:
|
||||
d.line([(hx - r * 0.34, hy + r * 0.1), (hx + r * 0.34, hy + r * 0.1)], fill=(120, 90, 210, 255), width=lw)
|
||||
if hx is not None:
|
||||
d.ellipse([hx + r * 0.05 - r * 0.13, hy - r * 0.78 - r * 0.13, hx + r * 0.05 + r * 0.13, hy - r * 0.78 + r * 0.13], fill=TRIANGLE + (255,))
|
||||
# Eyes: a cross (left) and a triangle (right).
|
||||
ex, ey, es = r * 0.40, cy - r * 0.27, r * 0.16
|
||||
lx = cx - ex
|
||||
d.line([(lx - es, ey - es), (lx + es, ey + es)], fill=CROSS + (255,), width=int(lw * 1.5))
|
||||
d.line([(lx - es, ey + es), (lx + es, ey - es)], fill=CROSS + (255,), width=int(lw * 1.5))
|
||||
rx = cx + ex
|
||||
tri = [(rx, ey - es * 1.15), (rx + es * 1.2, ey + es * 0.9), (rx - es * 1.2, ey + es * 0.9)]
|
||||
d.polygon(tri, fill=TRIANGLE + (255,))
|
||||
k = 0.42 # the inner cut-out: a smaller triangle with the same centre
|
||||
gx, gy = rx, (tri[0][1] + tri[1][1] + tri[2][1]) / 3
|
||||
d.polygon([(gx + (x - gx) * k, gy + (y - gy) * k) for x, y in tri], fill=INK + (255,))
|
||||
# Mouth: a wide grin with square teeth.
|
||||
mw, mt, mb = r * 0.6, cy + r * 0.33, cy + r * 0.68
|
||||
d.chord([cx - mw, mt - (mb - mt), cx + mw, mb], 0, 180, fill=(40, 22, 60, 255))
|
||||
teeth = 4
|
||||
tw = mw * 2 / (teeth + 1.6)
|
||||
for i in range(teeth):
|
||||
x0 = cx - mw + tw * 0.8 + i * tw
|
||||
d.rectangle([x0 + tw * 0.08, mt + r * 0.01, x0 + tw * 0.92, mt + r * 0.13], fill=INK + (255,))
|
||||
d.arc([cx - mw, mt - (mb - mt), cx + mw, mb], 0, 180, fill=(40, 22, 60, 255), width=lw)
|
||||
# Cheeks.
|
||||
for side in (-1, 1):
|
||||
x, y, rr = cx + side * r * 0.66, cy + r * 0.24, r * 0.12
|
||||
d.ellipse([x - rr, y - rr, x + rr, y + rr], fill=SQUARE + (110,))
|
||||
# The nose: the red circle, glowing.
|
||||
def nose(dd):
|
||||
nr = r * 0.19
|
||||
dd.ellipse([cx - nr, cy + r * 0.04 - nr, cx + nr, cy + r * 0.04 + nr], fill=CIRCLE + (255,))
|
||||
glow_shape(canvas, nose, r * 0.1, 1.4)
|
||||
dd = ImageDraw.Draw(canvas)
|
||||
nr = r * 0.19
|
||||
dd.ellipse([cx - nr * 0.55, cy + r * 0.04 - nr * 0.62, cx - nr * 0.15, cy + r * 0.04 - nr * 0.22], fill=(255, 220, 225, 200))
|
||||
|
||||
|
||||
def scanlines(img, step):
|
||||
over = Image.new('RGBA', img.size, (0, 0, 0, 0))
|
||||
d = ImageDraw.Draw(over)
|
||||
for y in range(0, img.size[1], step):
|
||||
d.line([(0, y), (img.size[0], y)], fill=(0, 0, 0, 28))
|
||||
return Image.alpha_composite(img, over)
|
||||
|
||||
|
||||
def gradient_text(size, text, fnt, c0, c1, tracking):
|
||||
"""The text with a horizontal gradient and letter spacing, on a transparent layer."""
|
||||
w, h = size
|
||||
mask = Image.new('L', (w, h), 0)
|
||||
d = ImageDraw.Draw(mask)
|
||||
widths = [d.textlength(ch, font=fnt) for ch in text]
|
||||
total = sum(widths) + tracking * (len(text) - 1)
|
||||
asc, desc = fnt.getmetrics()
|
||||
x = (w - total) / 2
|
||||
y = (h - (asc + desc)) / 2
|
||||
for ch, cw in zip(text, widths):
|
||||
d.text((x, y), ch, font=fnt, fill=255)
|
||||
x += cw + tracking
|
||||
grad = Image.new('RGBA', (w, h))
|
||||
gp = ImageDraw.Draw(grad)
|
||||
for xx in range(w):
|
||||
k = xx / max(1, w - 1)
|
||||
gp.line([(xx, 0), (xx, h)], fill=tuple(int(c0[j] + (c1[j] - c0[j]) * k) for j in range(3)) + (255,))
|
||||
grad.putalpha(mask)
|
||||
return grad, mask
|
||||
|
||||
|
||||
def icon(px):
|
||||
W = px * SS
|
||||
bg = background(W, W).convert('RGBA')
|
||||
bg.alpha_composite(towers(W * 0.45, W, W, W * 1.02, 9))
|
||||
clown(bg, W / 2, W * 0.53, W * 0.26)
|
||||
bg = scanlines(bg, SS * 3)
|
||||
# Rounded square.
|
||||
mask = Image.new('L', (W, W), 0)
|
||||
ImageDraw.Draw(mask).rounded_rectangle([0, 0, W - 1, W - 1], radius=W * 0.18, fill=255)
|
||||
bg.putalpha(mask)
|
||||
return bg.resize((px, px), Image.LANCZOS)
|
||||
|
||||
|
||||
def wordmark(w, h, transparent, title='THE BOZOS', subtitle='PS2 RECOMPILATION · BOUBOU666 & ARZAROTH', fire=False, title_size=0.33):
|
||||
W, H = w * SS, h * SS
|
||||
img = Image.new('RGBA', (W, H), (0, 0, 0, 0)) if transparent else background(W, H).convert('RGBA')
|
||||
if not transparent:
|
||||
img.alpha_composite(towers(H * 0.55, W, H, H * 1.04, 16, seed=11, dim=0.55))
|
||||
cr = H * 0.25
|
||||
clown(img, H * 0.62, H * (0.62 if fire else 0.58), cr * (0.92 if fire else 1.0), fire=fire)
|
||||
ox, oy = int(H * 1.1), int(H * 0.10)
|
||||
tw, th = int(W - ox), int(H * 0.55)
|
||||
# The title as large as title_size allows, smaller when it would not fit the space right of the clown.
|
||||
size = int(H * title_size)
|
||||
while True:
|
||||
fnt = font(size, 800)
|
||||
probe = ImageDraw.Draw(Image.new('L', (1, 1)))
|
||||
tracking = size * 0.075
|
||||
width = sum(probe.textlength(ch, font=fnt) for ch in title) + tracking * (len(title) - 1)
|
||||
if width <= tw * 0.92 or size <= 8:
|
||||
break
|
||||
size = int(size * 0.95)
|
||||
text, tmask = gradient_text((tw, th), title, fnt, CROSS, ACCENT, tracking)
|
||||
# The glow from the letters' shape alone (a blurred mask in the accent colour), so no box shows around them.
|
||||
glow = Image.new('RGBA', (tw, th), ACCENT + (0,))
|
||||
glow.putalpha(tmask.filter(ImageFilter.GaussianBlur(H * 0.03)).point(lambda v: int(v * 0.7)))
|
||||
img.alpha_composite(glow, (ox, oy))
|
||||
img.alpha_composite(text, (ox, oy))
|
||||
sub = font(int(H * 0.085), 500)
|
||||
d = ImageDraw.Draw(img)
|
||||
line = subtitle
|
||||
lw = d.textlength(line, font=sub)
|
||||
bottom = tmask.getbbox()[3] if tmask.getbbox() else th
|
||||
d.text((ox + (tw - lw) / 2, oy + bottom + H * 0.07), line, font=sub, fill=DIM + (255,))
|
||||
if not transparent:
|
||||
img = scanlines(img, SS * 3)
|
||||
return img.resize((w, h), Image.LANCZOS)
|
||||
|
||||
|
||||
# ---- per-game variants: the Bozos clown plus a landmark of the game (generic shapes only, no game art) ----
|
||||
|
||||
def fire_hair(canvas, cx, cy, r):
|
||||
"""Flames standing up from the top half of the head, in three layers (outer red to inner yellow), glowing."""
|
||||
layer = Image.new('RGBA', canvas.size, (0, 0, 0, 0))
|
||||
d = ImageDraw.Draw(layer)
|
||||
tongues = [(-1.05, 0.55), (-0.85, 0.95), (-0.55, 1.25), (-0.2, 1.45), (0.2, 1.38), (0.55, 1.2), (0.85, 0.92), (1.05, 0.5)]
|
||||
for k, col in enumerate([(230, 60, 50), (255, 140, 60), (255, 210, 120)]):
|
||||
s = 1.0 - k * 0.24
|
||||
for i, (dx, hgt) in enumerate(tongues):
|
||||
ang = math.atan2(-1.0, dx * 0.9)
|
||||
bx = cx + dx * r * 0.92
|
||||
by = cy - math.sqrt(max(0.0, 1 - min(1.0, abs(dx)) ** 2)) * r * 0.55
|
||||
tip_x = bx + dx * r * 0.35 * s + (0.08 * r if i % 2 else -0.08 * r) * s
|
||||
tip_y = by - hgt * r * s
|
||||
w = r * 0.32 * s
|
||||
d.polygon([(bx - w, by + r * 0.25), (bx - w * 0.6, by - hgt * r * 0.45 * s), (tip_x, tip_y),
|
||||
(bx + w * 0.6, by - hgt * r * 0.4 * s), (bx + w, by + r * 0.25)], fill=col + (255,))
|
||||
glow = layer.filter(ImageFilter.GaussianBlur(r * 0.14))
|
||||
canvas.alpha_composite(glow)
|
||||
canvas.alpha_composite(layer)
|
||||
|
||||
|
||||
def icon_tmb(px):
|
||||
"""Twisted Metal: Black: the Bozos clown with its head on fire (car combat), on the team's PS2 blue."""
|
||||
W = px * SS
|
||||
bg = background(W, W).convert('RGBA')
|
||||
bg.alpha_composite(towers(W * 0.4, W, W, W * 1.02, 9))
|
||||
clown(bg, W / 2, W * 0.6, W * 0.25, fire=True)
|
||||
bg = scanlines(bg, SS * 3)
|
||||
mask = Image.new('L', (W, W), 0)
|
||||
ImageDraw.Draw(mask).rounded_rectangle([0, 0, W - 1, W - 1], radius=W * 0.18, fill=255)
|
||||
bg.putalpha(mask)
|
||||
return bg.resize((px, px), Image.LANCZOS)
|
||||
|
||||
|
||||
if __name__ == '__main__' and len(sys.argv) > 1 and sys.argv[1] == 'tmb':
|
||||
# Twisted Metal: Black's launcher logo: the team clown with its head on fire.
|
||||
icon_tmb(1024).save(os.path.join(OUT, 'tmb_icon_1024.png'))
|
||||
icon_tmb(256).save(os.path.join(OUT, 'tmb_icon_256.png'))
|
||||
wordmark(2000, 600, False, title='TWISTED METAL: BLACK', subtitle='NATIVE PC PORT · THE BOZOS', fire=True,
|
||||
title_size=0.3).save(os.path.join(OUT, 'tmb_banner.png'))
|
||||
print('tmb done')
|
||||
elif __name__ == '__main__':
|
||||
icon(1024).save(os.path.join(OUT, 'bozos_icon_1024.png'))
|
||||
icon(256).save(os.path.join(OUT, 'bozos_icon_256.png'))
|
||||
wordmark(2000, 600, False).save(os.path.join(OUT, 'bozos_banner.png'))
|
||||
wordmark(2000, 600, True).save(os.path.join(OUT, 'bozos_wordmark_transparent.png'))
|
||||
print('done')
|
||||
|
After Width: | Height: | Size: 463 KiB |
|
After Width: | Height: | Size: 369 KiB |
|
After Width: | Height: | Size: 52 KiB |
@@ -70,11 +70,9 @@ endif()
|
||||
# windres does not like brackets in names.
|
||||
configure_file("${_font_dir}/Exo2[wght].ttf" "${_font_dir}/exo2.ttf" COPYONLY)
|
||||
|
||||
# The icon, drawn by a small program at build time (launcher/tools/make_icon.cpp): no image committed.
|
||||
add_executable(launcher_make_icon tools/make_icon.cpp)
|
||||
set(_icon "${CMAKE_BINARY_DIR}/launcher.ico")
|
||||
add_custom_command(OUTPUT "${_icon}" COMMAND launcher_make_icon "${_icon}" DEPENDS launcher_make_icon VERBATIM)
|
||||
add_custom_target(launcher_icon DEPENDS "${_icon}")
|
||||
# The icon: Twisted Metal: Black's variant of The Bozos' logo, the clown with its head on fire
|
||||
# (docs/branding/tmb_icon_1024.png, drawn by `python docs/branding/make_logo.py tmb`), as a multi-size .ico (16 to 256 px).
|
||||
set(_icon "${CMAKE_CURRENT_SOURCE_DIR}/tmb.ico")
|
||||
|
||||
# The release's version and source commit (tools/make_release.py passes them): shown in the footer, compared with
|
||||
# GitHub's latest release by the update check, in the exe's version information. "dev" builds skip the check at start.
|
||||
@@ -99,7 +97,6 @@ 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
|
||||
"${CMAKE_BINARY_DIR}/launcher.rc")
|
||||
add_dependencies(tmb_launcher launcher_icon)
|
||||
set_target_properties(tmb_launcher PROPERTIES OUTPUT_NAME "TMB Launcher")
|
||||
target_link_libraries(tmb_launcher PRIVATE launcher_imgui raylib comdlg32 shell32 ole32 winhttp)
|
||||
target_compile_definitions(tmb_launcher PRIVATE TMB_VERSION="${LAUNCHER_VERSION}" TMB_COMMIT="${LAUNCHER_COMMIT}")
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// TMB Launcher's resources: its icon (drawn by tools/make_icon.cpp at build time; GLFW_ICON is the name GLFW gives the
|
||||
// TMB Launcher's resources: its icon (TMB's variant of The Bozos' logo, launcher/tmb.ico; GLFW_ICON is the name GLFW gives the
|
||||
// window's class, so the window and the taskbar show it too), the Exo 2 font and its licence, and version information.
|
||||
#include <winver.h>
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
#include "rlImGui.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
@@ -43,7 +44,7 @@ using ui::S;
|
||||
// The team's wordmark and the credits under it.
|
||||
#define TEAM_NAME "The Bozos"
|
||||
#define TEAM_CREDITS "by boubou666 & Arzaroth"
|
||||
static const char *kSiteUrl = "https://boubou666.github.io/RecompWatcher/";
|
||||
static const char *kSiteUrl = "https://thebozos.github.io/RecompWatcher/";
|
||||
// The release's version and source commit (CMake's LAUNCHER_VERSION / LAUNCHER_COMMIT, from tools/make_release.py).
|
||||
#ifndef TMB_VERSION
|
||||
#define TMB_VERSION "dev"
|
||||
@@ -54,8 +55,11 @@ static const char *kSiteUrl = "https://boubou666.github.io/RecompWatcher/";
|
||||
static const char *kVersion = TMB_VERSION;
|
||||
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/boubou666/TMB_Recomp/releases/latest";
|
||||
static const char *kReleasePagePrefix = "https://github.com/boubou666/TMB_Recomp/releases/tag/";
|
||||
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.
|
||||
static const char *kReleaseDownloadPrefix = "https://github.com/TheBozos/TMB_Recomp/releases/download/";
|
||||
|
||||
// ---- language ----
|
||||
|
||||
@@ -171,7 +175,7 @@ struct UpdateCheck
|
||||
};
|
||||
std::mutex mutex;
|
||||
State state = State::Idle;
|
||||
std::string version, page, error;
|
||||
std::string version, page, error, tag;
|
||||
bool manual = false; // the button: say the outcome, even "you have the latest"
|
||||
std::thread worker;
|
||||
|
||||
@@ -203,13 +207,17 @@ struct UpdateCheck
|
||||
return;
|
||||
}
|
||||
version = tag[0] == 'v' || tag[0] == 'V' ? tag.substr(1) : tag;
|
||||
this->tag = tag;
|
||||
page = kReleasePagePrefix + tag;
|
||||
state = newerVersion(tag, kVersion) ? State::Available : State::Latest; });
|
||||
}
|
||||
|
||||
State get(std::string *v = nullptr, std::string *p = nullptr, std::string *e = nullptr, bool *byHand = nullptr)
|
||||
State get(std::string *v = nullptr, std::string *p = nullptr, std::string *e = nullptr, bool *byHand = nullptr,
|
||||
std::string *t = nullptr)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex);
|
||||
if (t)
|
||||
*t = tag;
|
||||
if (v)
|
||||
*v = version;
|
||||
if (p)
|
||||
@@ -371,6 +379,36 @@ struct App
|
||||
// The update check, and the code the game was built from (an update unzipped over the release: Rebuild).
|
||||
UpdateCheck updates;
|
||||
std::string updateUrl = kLatestReleaseApi;
|
||||
|
||||
// Installing an update (the Update button): the release's zip and .sha256 downloaded into the update folder (a
|
||||
// thread), then source/tools/apply_update.py (the kit's Python) checks and installs them, and the launcher starts
|
||||
// its new self.
|
||||
enum class UpdateStep
|
||||
{
|
||||
Idle,
|
||||
Downloading,
|
||||
Installing,
|
||||
Restarting,
|
||||
Failed
|
||||
};
|
||||
UpdateStep updateStep = UpdateStep::Idle;
|
||||
std::string updateVersion, updateError, updatePhase; // updatePhase: apply_update's step (verify, extract...)
|
||||
std::string downloadPrefix = kReleaseDownloadPrefix;
|
||||
std::vector<std::string> restartArgs; // this launcher's arguments, given to the new one
|
||||
std::atomic<uint64_t> updateDone{0}, updateTotal{0};
|
||||
std::atomic<bool> updateCancel{false}, downloadFinished{false};
|
||||
std::mutex downloadMutex;
|
||||
bool downloadOk = false;
|
||||
std::string downloadError;
|
||||
std::thread downloader;
|
||||
plat::Process installer;
|
||||
|
||||
~App()
|
||||
{
|
||||
updateCancel = true; // a download stops at its next block
|
||||
if (downloader.joinable())
|
||||
downloader.join();
|
||||
}
|
||||
std::string sourceCommit, sourceVersion, builtCommit;
|
||||
bool runCounted = false; // this build run's time is already in cfg.pendingSeconds
|
||||
// "What's new": CHANGELOG.md's section for the installed version (the release's top folder, else source\).
|
||||
@@ -415,6 +453,171 @@ struct App
|
||||
missingPart = "kit\\";
|
||||
phase = !missingPart.empty() ? Phase::Incomplete : cfg.disc.empty() ? Phase::Welcome : Phase::Ready;
|
||||
readStamps();
|
||||
cleanUpdateLeftovers();
|
||||
}
|
||||
|
||||
// -- updates
|
||||
|
||||
std::string updateDir() const { return plat::str(plat::path(p.release) / L"update"); }
|
||||
|
||||
// An update's leftovers: the files apply_update.py set aside because they were in use (this launcher's old exe,
|
||||
// the kit's Python), listed in update/old_files.txt; deleted now, or at a later start if still in use.
|
||||
void cleanUpdateLeftovers()
|
||||
{
|
||||
const fs::path list = plat::path(updateDir()) / L"old_files.txt";
|
||||
std::error_code ec;
|
||||
if (!fs::exists(list, ec))
|
||||
return;
|
||||
std::ifstream in(list);
|
||||
std::string line, kept;
|
||||
while (std::getline(in, line))
|
||||
{
|
||||
if (!line.empty() && line.back() == '\r')
|
||||
line.pop_back();
|
||||
// Only what it set aside in this release folder.
|
||||
if (line.rfind(p.release, 0) != 0 || line.find(".tmb-old") == std::string::npos)
|
||||
continue;
|
||||
const fs::path file = plat::path(line);
|
||||
if (!fs::remove(file, ec) && fs::exists(file, ec))
|
||||
kept += line + "\n";
|
||||
}
|
||||
in.close();
|
||||
if (kept.empty())
|
||||
{
|
||||
fs::remove(list, ec);
|
||||
fs::remove(plat::path(updateDir()), ec); // only when empty (a stopped download's files stay)
|
||||
}
|
||||
else if (std::ofstream out{list, std::ios::trunc})
|
||||
out << kept;
|
||||
}
|
||||
|
||||
bool updating() const
|
||||
{
|
||||
return updateStep == UpdateStep::Downloading || updateStep == UpdateStep::Installing || updateStep == UpdateStep::Restarting;
|
||||
}
|
||||
|
||||
void startUpdate(const std::string &tag, const std::string &version)
|
||||
{
|
||||
if (updating() || building || gameRunning || checking || tag.empty() || version.empty())
|
||||
return;
|
||||
std::error_code ec;
|
||||
fs::create_directories(plat::path(updateDir()), ec);
|
||||
updateVersion = version;
|
||||
updateError.clear();
|
||||
updatePhase.clear();
|
||||
updateCancel = false;
|
||||
downloadFinished = false;
|
||||
updateDone = 0;
|
||||
updateTotal = 0;
|
||||
updateStep = UpdateStep::Downloading;
|
||||
if (downloader.joinable())
|
||||
downloader.join();
|
||||
const std::string name = "TMB_Recomp-" + version + ".zip";
|
||||
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]
|
||||
{
|
||||
const std::string agent = std::string("TMB-Launcher/") + kVersion;
|
||||
std::atomic<uint64_t> shaDone{0}, shaTotal{0};
|
||||
std::string error;
|
||||
const bool ok = plat::httpDownload(url + ".sha256", agent, zip + ".sha256", shaDone, shaTotal, updateCancel, error, 4096) &&
|
||||
plat::httpDownload(url, agent, zip, updateDone, updateTotal, updateCancel, error);
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(downloadMutex);
|
||||
downloadOk = ok;
|
||||
downloadError = error;
|
||||
}
|
||||
downloadFinished = true; });
|
||||
}
|
||||
|
||||
void cancelUpdate()
|
||||
{
|
||||
if (updateStep == UpdateStep::Downloading)
|
||||
updateCancel = true;
|
||||
}
|
||||
|
||||
void pollUpdate()
|
||||
{
|
||||
if (updateStep == UpdateStep::Downloading && downloadFinished)
|
||||
{
|
||||
downloader.join();
|
||||
bool ok;
|
||||
std::string error;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(downloadMutex);
|
||||
ok = downloadOk;
|
||||
error = downloadError;
|
||||
}
|
||||
if (!ok)
|
||||
{
|
||||
updateStep = updateCancel ? UpdateStep::Idle : UpdateStep::Failed;
|
||||
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::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};
|
||||
updateDone = 0;
|
||||
updateTotal = 0;
|
||||
std::string startError;
|
||||
if (!installer.start(p.python, args, p.release, true, startError))
|
||||
{
|
||||
updateStep = UpdateStep::Failed;
|
||||
updateError = std::string(L("The update could not start: ", "La mise à jour n'a pas pu démarrer : ")) + startError;
|
||||
return;
|
||||
}
|
||||
updateStep = UpdateStep::Installing;
|
||||
return;
|
||||
}
|
||||
if (updateStep != UpdateStep::Installing)
|
||||
return;
|
||||
auto feed = [&](const std::string &line)
|
||||
{
|
||||
unsigned long long a = 0, b = 0;
|
||||
if (line.rfind("step ", 0) == 0)
|
||||
{
|
||||
updatePhase = line.substr(5);
|
||||
updateDone = 0;
|
||||
updateTotal = 0;
|
||||
}
|
||||
else if (line.rfind("progress ", 0) == 0 && std::sscanf(line.c_str() + 9, "%llu %llu", &a, &b) == 2)
|
||||
{
|
||||
updateDone = a;
|
||||
updateTotal = b;
|
||||
}
|
||||
else if (line.rfind("error ", 0) == 0)
|
||||
updateError = line.substr(6);
|
||||
else if (line.rfind("done ", 0) == 0)
|
||||
updatePhase = "done";
|
||||
};
|
||||
for (const std::string &line : installer.takeLines())
|
||||
feed(line);
|
||||
if (installer.running())
|
||||
return;
|
||||
installer.drain(2000);
|
||||
for (const std::string &line : installer.takeLines())
|
||||
feed(line);
|
||||
if (installer.exitCode() != 0 || updatePhase != "done")
|
||||
{
|
||||
updateStep = UpdateStep::Failed;
|
||||
if (updateError.empty())
|
||||
updateError = std::string(L("The update stopped (exit code ", "La mise à jour s'est arrêtée (code ")) +
|
||||
std::to_string(installer.exitCode()) + ").";
|
||||
return;
|
||||
}
|
||||
// Installed: the new launcher (now at this exe's path) takes over, and offers Rebuild.
|
||||
plat::Process next;
|
||||
std::string startError;
|
||||
if (next.start(plat::exePath(), restartArgs, p.release, false, startError))
|
||||
{
|
||||
updateStep = UpdateStep::Restarting;
|
||||
quit = true;
|
||||
return;
|
||||
}
|
||||
updateStep = UpdateStep::Failed;
|
||||
updateError = std::string(L("Version ", "La version ")) + updateVersion +
|
||||
L(" is installed: start the launcher again. ", " est installée : relancez le lanceur. ") + startError;
|
||||
}
|
||||
|
||||
// The source's commit (source\release.ini, else the launcher's own) and the one the game was built from.
|
||||
@@ -1005,16 +1208,50 @@ static void drawReady(App &app, float inner)
|
||||
// One note at a time (both do not fit the card at the window's smallest size): Rebuild first; the footer and
|
||||
// Maintenance still say a newer release is out.
|
||||
const bool rebuildShown = built && !app.cfg.buildPending && app.codeChanged() && !app.building;
|
||||
if (!rebuildShown && app.updates.get(&newVersion, &page) == UpdateCheck::State::Available &&
|
||||
newVersion != app.sourceVersion)
|
||||
std::string newTag;
|
||||
if (app.updating())
|
||||
{
|
||||
// Downloading, then apply_update.py's steps, each with its bar.
|
||||
gap(12);
|
||||
const std::string what = std::string(L("Updating to version ", "Mise à jour vers la version ")) + app.updateVersion + "\xE2\x80\xA6";
|
||||
const uint64_t done = app.updateDone, total = app.updateTotal;
|
||||
char detail[160];
|
||||
if (app.updateStep == App::UpdateStep::Downloading)
|
||||
std::snprintf(detail, sizeof(detail), L("Downloading: %.0f of %.0f MB.", "Téléchargement : %.0f sur %.0f Mo."), done / 1e6, total / 1e6);
|
||||
else
|
||||
std::snprintf(detail, sizeof(detail), "%s",
|
||||
app.updatePhase == "verify" ? L("Checking the download.", "Vérification du téléchargement.")
|
||||
: app.updatePhase == "extract" ? L("Unpacking.", "Décompression.")
|
||||
: app.updatePhase == "install" ? L("Installing.", "Installation.")
|
||||
: L("Finishing.", "Finalisation."));
|
||||
noteBox(what.c_str(), detail, ui::color::wip, inner);
|
||||
gap(6);
|
||||
ui::progressBar(total ? static_cast<float>(static_cast<double>(done) / static_cast<double>(total)) : 0.0f, ImVec2(inner, S(18)), app.time);
|
||||
if (app.updateStep == App::UpdateStep::Downloading)
|
||||
{
|
||||
gap(6);
|
||||
if (ui::button(L("Stop", "Arrêter"), ImVec2(0, S(48))))
|
||||
app.cancelUpdate();
|
||||
}
|
||||
}
|
||||
else if (!rebuildShown && app.updates.get(&newVersion, &page, nullptr, nullptr, &newTag) == UpdateCheck::State::Available &&
|
||||
newVersion != app.sourceVersion)
|
||||
{
|
||||
gap(12);
|
||||
const bool failed = app.updateStep == App::UpdateStep::Failed;
|
||||
std::string what = std::string(L("Version ", "La version ")) + newVersion + L(" is available.", " est disponible.");
|
||||
noteBox(what.c_str(),
|
||||
L("Download it from the release page and unzip it where you unzipped this one (replace the files), then Rebuild.",
|
||||
"Téléchargez-la depuis la page de la version et décompressez-la au même endroit que celle-ci (remplacez les fichiers), puis Reconstruire."),
|
||||
ui::color::cross, inner);
|
||||
failed ? app.updateError
|
||||
: std::string(L("Update downloads and installs it here, then the launcher restarts and Rebuild prepares the game again "
|
||||
"(only what changed). Your saves and settings stay.",
|
||||
"Mettre à jour la télécharge et l'installe ici, puis le lanceur redémarre et Reconstruire prépare "
|
||||
"à nouveau le jeu (seulement ce qui a changé). Vos sauvegardes et réglages restent.")),
|
||||
failed ? ui::color::early : ui::color::cross, inner);
|
||||
gap(6);
|
||||
if (ui::button(failed ? L("Try again", "Réessayer") : L("Update", "Mettre à jour"), ImVec2(0, S(48)), ui::Kind::Primary,
|
||||
!app.building && !app.gameRunning))
|
||||
app.startUpdate(newTag, newVersion);
|
||||
ImGui::SameLine(0, S(12));
|
||||
if (ui::button(L("Open the release page", "Ouvrir la page de la version"), ImVec2(0, S(48))))
|
||||
plat::open(page);
|
||||
}
|
||||
@@ -1765,8 +2002,8 @@ int main(int argc, char **argv)
|
||||
bool errorDemo = false, cancel = false, screensOnly = false;
|
||||
double playSeconds = 40, crashSeconds = 0;
|
||||
float uiScale = 0;
|
||||
std::string updateUrl, selfCheckFile, reportPath;
|
||||
bool versionOnly = false;
|
||||
std::string updateUrl, selfCheckFile, reportPath, downloadPrefix;
|
||||
bool versionOnly = false, updateNow = false;
|
||||
(void)argc;
|
||||
(void)argv;
|
||||
const std::vector<std::string> args = plat::arguments(); // UTF-8, from the wide command line
|
||||
@@ -1796,6 +2033,10 @@ 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
|
||||
downloadPrefix = next();
|
||||
else if (a == "--update-now") // a test: presses Update once the check finds a newer release
|
||||
updateNow = true;
|
||||
else if (a == "--self-check") // no window: the release folder and the disc check on a file (see selfCheck)
|
||||
selfCheckFile = next();
|
||||
else if (a == "--report")
|
||||
@@ -1841,6 +2082,9 @@ int main(int argc, char **argv)
|
||||
// The update check at start (setting "update_check"): not for a development launcher, unless pointed somewhere.
|
||||
if (!updateUrl.empty())
|
||||
app.updateUrl = updateUrl;
|
||||
if (!downloadPrefix.empty())
|
||||
app.downloadPrefix = downloadPrefix;
|
||||
app.restartArgs = args;
|
||||
if (app.cfg.updateCheck && (std::strcmp(kVersion, "dev") != 0 || !updateUrl.empty()))
|
||||
app.updates.start(app.updateUrl, false);
|
||||
|
||||
@@ -1870,12 +2114,22 @@ int main(int argc, char **argv)
|
||||
{
|
||||
if (app.building)
|
||||
app.wantQuit = true;
|
||||
else
|
||||
else if (app.updateStep != App::UpdateStep::Installing) // installing: not stopped half way
|
||||
break;
|
||||
}
|
||||
app.time = plat::now() - t0;
|
||||
app.pollCheck();
|
||||
app.pollBuild();
|
||||
app.pollUpdate();
|
||||
if (updateNow && app.updateStep == App::UpdateStep::Idle)
|
||||
{
|
||||
std::string version, tag;
|
||||
if (app.updates.get(&version, nullptr, nullptr, nullptr, &tag) == UpdateCheck::State::Available)
|
||||
{
|
||||
updateNow = false;
|
||||
app.startUpdate(tag, version);
|
||||
}
|
||||
}
|
||||
app.pollGame();
|
||||
if (!selftestIso.empty())
|
||||
test.tick(app);
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
// 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.
|
||||
|
||||
#include <atomic>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
@@ -80,4 +81,14 @@ namespace plat
|
||||
// Blocking, with short timeouts: call it from a thread.
|
||||
bool httpGet(const std::string &url, const std::string &userAgent, std::string &body, long &status,
|
||||
std::string &error, size_t maxBytes = 1 << 20);
|
||||
|
||||
// The same GET streamed into a file (a release's zip, through GitHub's redirect to its storage): bytes written so
|
||||
// far and the size the server announced (0 when it did not) into done and total, stopped when cancel turns true.
|
||||
// False with error set on a failure, a status other than 200 or a stop; the file is then removed.
|
||||
bool httpDownload(const std::string &url, const std::string &userAgent, const std::string &file, std::atomic<uint64_t> &done,
|
||||
std::atomic<uint64_t> &total, const std::atomic<bool> &cancel, std::string &error,
|
||||
uint64_t maxBytes = uint64_t(1) << 31);
|
||||
|
||||
// This program's own file (the launcher's exe, to start it again after an update).
|
||||
std::string exePath();
|
||||
}
|
||||
@@ -16,6 +16,7 @@
|
||||
#include <chrono>
|
||||
#include <cstdlib>
|
||||
#include <deque>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
|
||||
namespace plat
|
||||
@@ -423,95 +424,190 @@ namespace plat
|
||||
reinterpret_cast<LPARAM>(&ctx));
|
||||
}
|
||||
|
||||
bool httpGet(const std::string &url, const std::string &userAgent, std::string &body, long &status,
|
||||
std::string &error, size_t maxBytes)
|
||||
namespace
|
||||
{
|
||||
body.clear();
|
||||
status = 0;
|
||||
std::wstring wurl = widen(url);
|
||||
URL_COMPONENTS parts{};
|
||||
parts.dwStructSize = sizeof(parts);
|
||||
wchar_t host[256] = {}, pathBuf[2048] = {};
|
||||
parts.lpszHostName = host;
|
||||
parts.dwHostNameLength = 256;
|
||||
parts.lpszUrlPath = pathBuf;
|
||||
parts.dwUrlPathLength = 2048;
|
||||
if (!WinHttpCrackUrl(wurl.c_str(), 0, 0, &parts) ||
|
||||
(parts.nScheme != INTERNET_SCHEME_HTTPS && parts.nScheme != INTERNET_SCHEME_HTTP))
|
||||
{
|
||||
error = "bad URL";
|
||||
return false;
|
||||
}
|
||||
struct Handle
|
||||
struct Internet
|
||||
{
|
||||
HINTERNET h = nullptr;
|
||||
~Handle()
|
||||
~Internet()
|
||||
{
|
||||
if (h)
|
||||
WinHttpCloseHandle(h);
|
||||
}
|
||||
} session, connection, request;
|
||||
// WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY (Windows 8.1+): the proxy Windows itself uses.
|
||||
session.h = WinHttpOpen(widen(userAgent).c_str(), 4 /* WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY */,
|
||||
WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
|
||||
if (!session.h)
|
||||
session.h = WinHttpOpen(widen(userAgent).c_str(), WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME,
|
||||
WINHTTP_NO_PROXY_BYPASS, 0);
|
||||
if (!session.h)
|
||||
};
|
||||
|
||||
// A GET whose body goes to sink (false from it stops the read): the shared part of httpGet and httpDownload.
|
||||
// receiveMs: the longest wait for data (a large download through a slow line needs more than a version check).
|
||||
bool httpRequest(const std::string &url, const std::string &userAgent, const wchar_t *headers, int receiveMs,
|
||||
long &status, uint64_t &contentLength, std::string &error,
|
||||
const std::function<bool(const char *, size_t)> &sink)
|
||||
{
|
||||
status = 0;
|
||||
contentLength = 0;
|
||||
std::wstring wurl = widen(url);
|
||||
URL_COMPONENTS parts{};
|
||||
parts.dwStructSize = sizeof(parts);
|
||||
wchar_t host[256] = {}, pathBuf[2048] = {};
|
||||
parts.lpszHostName = host;
|
||||
parts.dwHostNameLength = 256;
|
||||
parts.lpszUrlPath = pathBuf;
|
||||
parts.dwUrlPathLength = 2048;
|
||||
if (!WinHttpCrackUrl(wurl.c_str(), 0, 0, &parts) ||
|
||||
(parts.nScheme != INTERNET_SCHEME_HTTPS && parts.nScheme != INTERNET_SCHEME_HTTP))
|
||||
{
|
||||
error = "bad URL";
|
||||
return false;
|
||||
}
|
||||
Internet session, connection, request;
|
||||
// WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY (Windows 8.1+): the proxy Windows itself uses.
|
||||
session.h = WinHttpOpen(widen(userAgent).c_str(), 4 /* WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY */,
|
||||
WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
|
||||
if (!session.h)
|
||||
session.h = WinHttpOpen(widen(userAgent).c_str(), WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME,
|
||||
WINHTTP_NO_PROXY_BYPASS, 0);
|
||||
if (!session.h)
|
||||
{
|
||||
error = lastError();
|
||||
return false;
|
||||
}
|
||||
WinHttpSetTimeouts(session.h, 5000, 5000, 5000, receiveMs);
|
||||
connection.h = WinHttpConnect(session.h, host, parts.nPort, 0);
|
||||
if (!connection.h)
|
||||
{
|
||||
error = lastError();
|
||||
return false;
|
||||
}
|
||||
request.h = WinHttpOpenRequest(connection.h, L"GET", pathBuf, nullptr, WINHTTP_NO_REFERER,
|
||||
WINHTTP_DEFAULT_ACCEPT_TYPES,
|
||||
parts.nScheme == INTERNET_SCHEME_HTTPS ? WINHTTP_FLAG_SECURE : 0);
|
||||
if (!request.h)
|
||||
{
|
||||
error = lastError();
|
||||
return false;
|
||||
}
|
||||
// Redirects are followed (GitHub sends a release's files from its storage), never from HTTPS to HTTP.
|
||||
if (!WinHttpSendRequest(request.h, headers, static_cast<DWORD>(-1L), WINHTTP_NO_REQUEST_DATA, 0, 0, 0) ||
|
||||
!WinHttpReceiveResponse(request.h, nullptr))
|
||||
{
|
||||
error = lastError();
|
||||
return false;
|
||||
}
|
||||
DWORD code = 0, size = sizeof(code);
|
||||
WinHttpQueryHeaders(request.h, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX,
|
||||
&code, &size, WINHTTP_NO_HEADER_INDEX);
|
||||
status = static_cast<long>(code);
|
||||
wchar_t length[32] = {};
|
||||
DWORD lengthSize = sizeof(length);
|
||||
if (WinHttpQueryHeaders(request.h, WINHTTP_QUERY_CONTENT_LENGTH, WINHTTP_HEADER_NAME_BY_INDEX, length, &lengthSize,
|
||||
WINHTTP_NO_HEADER_INDEX))
|
||||
contentLength = std::wcstoull(length, nullptr, 10);
|
||||
std::string chunk;
|
||||
for (;;)
|
||||
{
|
||||
DWORD available = 0;
|
||||
if (!WinHttpQueryDataAvailable(request.h, &available))
|
||||
{
|
||||
error = lastError();
|
||||
return false;
|
||||
}
|
||||
if (available == 0)
|
||||
break;
|
||||
chunk.resize(available);
|
||||
DWORD read = 0;
|
||||
if (!WinHttpReadData(request.h, chunk.data(), available, &read))
|
||||
{
|
||||
error = lastError();
|
||||
return false;
|
||||
}
|
||||
if (!sink(chunk.data(), read))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
bool httpGet(const std::string &url, const std::string &userAgent, std::string &body, long &status,
|
||||
std::string &error, size_t maxBytes)
|
||||
{
|
||||
body.clear();
|
||||
uint64_t length = 0;
|
||||
return httpRequest(url, userAgent, L"Accept: application/vnd.github+json\r\nX-GitHub-Api-Version: 2022-11-28\r\n", 8000,
|
||||
status, length, error, [&](const char *data, size_t n)
|
||||
{
|
||||
body.append(data, n);
|
||||
if (body.size() <= maxBytes)
|
||||
return true;
|
||||
error = "response too large";
|
||||
return false; });
|
||||
}
|
||||
|
||||
bool httpDownload(const std::string &url, const std::string &userAgent, const std::string &file, std::atomic<uint64_t> &done,
|
||||
std::atomic<uint64_t> &total, const std::atomic<bool> &cancel, std::string &error, uint64_t maxBytes)
|
||||
{
|
||||
done = 0;
|
||||
total = 0;
|
||||
HANDLE out = CreateFileW(widen(file).c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
if (out == INVALID_HANDLE_VALUE)
|
||||
{
|
||||
error = lastError();
|
||||
return false;
|
||||
}
|
||||
WinHttpSetTimeouts(session.h, 5000, 5000, 5000, 8000);
|
||||
connection.h = WinHttpConnect(session.h, host, parts.nPort, 0);
|
||||
if (!connection.h)
|
||||
long status = 0;
|
||||
uint64_t length = 0;
|
||||
bool sized = false;
|
||||
bool ok = httpRequest(url, userAgent, L"Accept: application/octet-stream\r\n", 30000, status, length, error,
|
||||
[&](const char *data, size_t n)
|
||||
{
|
||||
if (!sized)
|
||||
{
|
||||
sized = true;
|
||||
total = length;
|
||||
}
|
||||
if (status != 200)
|
||||
return false; // an error page: not written
|
||||
if (cancel.load())
|
||||
{
|
||||
error = "stopped";
|
||||
return false;
|
||||
}
|
||||
DWORD written = 0;
|
||||
if (!WriteFile(out, data, static_cast<DWORD>(n), &written, nullptr) || written != n)
|
||||
{
|
||||
error = lastError();
|
||||
return false;
|
||||
}
|
||||
done += n;
|
||||
if (done.load() <= maxBytes)
|
||||
return true;
|
||||
error = "download too large";
|
||||
return false; });
|
||||
CloseHandle(out);
|
||||
if (ok && status != 200)
|
||||
{
|
||||
error = lastError();
|
||||
return false;
|
||||
ok = false;
|
||||
error = "HTTP " + std::to_string(status);
|
||||
}
|
||||
request.h = WinHttpOpenRequest(connection.h, L"GET", pathBuf, nullptr, WINHTTP_NO_REFERER,
|
||||
WINHTTP_DEFAULT_ACCEPT_TYPES,
|
||||
parts.nScheme == INTERNET_SCHEME_HTTPS ? WINHTTP_FLAG_SECURE : 0);
|
||||
if (!request.h)
|
||||
{
|
||||
error = lastError();
|
||||
return false;
|
||||
}
|
||||
const wchar_t *headers = L"Accept: application/vnd.github+json\r\nX-GitHub-Api-Version: 2022-11-28\r\n";
|
||||
if (!WinHttpSendRequest(request.h, headers, static_cast<DWORD>(-1L), WINHTTP_NO_REQUEST_DATA, 0, 0, 0) ||
|
||||
!WinHttpReceiveResponse(request.h, nullptr))
|
||||
{
|
||||
error = lastError();
|
||||
return false;
|
||||
}
|
||||
DWORD code = 0, size = sizeof(code);
|
||||
WinHttpQueryHeaders(request.h, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX,
|
||||
&code, &size, WINHTTP_NO_HEADER_INDEX);
|
||||
status = static_cast<long>(code);
|
||||
else if (!ok && error.empty())
|
||||
error = status != 200 ? "HTTP " + std::to_string(status) : "download failed";
|
||||
if (!ok)
|
||||
DeleteFileW(widen(file).c_str());
|
||||
return ok;
|
||||
}
|
||||
|
||||
std::string exePath()
|
||||
{
|
||||
std::wstring buffer(MAX_PATH, L'\0');
|
||||
for (;;)
|
||||
{
|
||||
DWORD available = 0;
|
||||
if (!WinHttpQueryDataAvailable(request.h, &available))
|
||||
const DWORD n = GetModuleFileNameW(nullptr, buffer.data(), static_cast<DWORD>(buffer.size()));
|
||||
if (n == 0)
|
||||
return {};
|
||||
if (n < buffer.size())
|
||||
{
|
||||
error = lastError();
|
||||
return false;
|
||||
}
|
||||
if (available == 0)
|
||||
break;
|
||||
std::string chunk(available, '\0');
|
||||
DWORD read = 0;
|
||||
if (!WinHttpReadData(request.h, chunk.data(), available, &read))
|
||||
{
|
||||
error = lastError();
|
||||
return false;
|
||||
}
|
||||
body.append(chunk.data(), read);
|
||||
if (body.size() > maxBytes)
|
||||
{
|
||||
error = "response too large";
|
||||
return false;
|
||||
buffer.resize(n);
|
||||
return narrow(buffer);
|
||||
}
|
||||
buffer.resize(buffer.size() * 2);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 82 KiB |
@@ -1,178 +0,0 @@
|
||||
// Draws the launcher's icon and writes it as a .ico (256, 64, 48, 32, 24, 16 pixels, 32-bit): the build makes it, so no
|
||||
// image is committed. The style of RecompWatcher's icon.svg: the PS2 BIOS's radial blue (#14328f at the bottom centre,
|
||||
// #050b26, #01030a) and its glowing "boot towers", in a rounded square. No game art.
|
||||
//
|
||||
// make_icon <out.ico>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <vector>
|
||||
|
||||
namespace
|
||||
{
|
||||
struct Rgb
|
||||
{
|
||||
float r, g, b;
|
||||
};
|
||||
|
||||
Rgb hex(uint32_t v) { return {((v >> 16) & 255) / 255.0f, ((v >> 8) & 255) / 255.0f, (v & 255) / 255.0f}; }
|
||||
Rgb mix(Rgb a, Rgb b, float t) { return {a.r + (b.r - a.r) * t, a.g + (b.g - a.g) * t, a.b + (b.b - a.b) * t}; }
|
||||
|
||||
// The background: radialGradient cx 50% cy 85% r 80%, stops 0 #14328f, 0.55 #050b26, 1 #01030a.
|
||||
Rgb background(float u, float v)
|
||||
{
|
||||
const float d = std::sqrt((u - 0.5f) * (u - 0.5f) + (v - 0.85f) * (v - 0.85f)) / 0.8f;
|
||||
if (d < 0.55f)
|
||||
return mix(hex(0x14328f), hex(0x050b26), d / 0.55f);
|
||||
return mix(hex(0x050b26), hex(0x01030a), std::min(1.0f, (d - 0.55f) / 0.45f));
|
||||
}
|
||||
|
||||
struct Tower
|
||||
{
|
||||
float x, w, h;
|
||||
};
|
||||
// Five towers rising from the bottom, the middle one tallest.
|
||||
const Tower kTowers[] = {{0.17f, 0.11f, 0.36f}, {0.335f, 0.11f, 0.54f}, {0.5f, 0.12f, 0.72f}, {0.665f, 0.11f, 0.5f},
|
||||
{0.83f, 0.11f, 0.32f}};
|
||||
|
||||
// One sample (u, v in 0..1, v down): colour and coverage of the rounded square.
|
||||
void sample(float u, float v, float &r, float &g, float &b, float &a)
|
||||
{
|
||||
// The rounded square (corner radius 0.2).
|
||||
const float rad = 0.2f;
|
||||
const float cx = std::clamp(u, rad, 1 - rad), cy = std::clamp(v, rad, 1 - rad);
|
||||
if ((u - cx) * (u - cx) + (v - cy) * (v - cy) > rad * rad)
|
||||
{
|
||||
r = g = b = a = 0;
|
||||
return;
|
||||
}
|
||||
Rgb c = background(u, v);
|
||||
// The towers' glow: a halo around each, then the tower itself (light at the top, deep blue at the foot).
|
||||
float glow = 0;
|
||||
for (const Tower &t : kTowers)
|
||||
{
|
||||
const float top = 1.0f - t.h;
|
||||
const float dx = std::max(0.0f, std::fabs(u - t.x) - t.w / 2), dy = std::max(0.0f, top - v);
|
||||
const float d = std::sqrt(dx * dx + dy * dy);
|
||||
glow += 0.55f * std::exp(-d / 0.035f);
|
||||
if (dx == 0 && dy == 0)
|
||||
{
|
||||
const float k = (v - top) / t.h; // 0 at the top
|
||||
Rgb tower = mix(hex(0xc9dbff), hex(0x3a58d6), std::min(1.0f, k * 1.6f));
|
||||
tower = mix(tower, hex(0x0d1c66), std::max(0.0f, k - 0.6f) * 1.5f);
|
||||
// The cap: a bright line at the top.
|
||||
if (v - top < 0.025f)
|
||||
tower = mix(tower, hex(0xeef4ff), 0.7f);
|
||||
c = mix(c, tower, 0.92f);
|
||||
glow = 0;
|
||||
break;
|
||||
}
|
||||
}
|
||||
const Rgb halo = hex(0x6f8dff);
|
||||
glow = std::min(glow, 0.8f);
|
||||
c = {c.r + halo.r * glow * 0.5f, c.g + halo.g * glow * 0.5f, c.b + halo.b * glow * 0.5f};
|
||||
r = std::min(1.0f, c.r);
|
||||
g = std::min(1.0f, c.g);
|
||||
b = std::min(1.0f, c.b);
|
||||
a = 1;
|
||||
}
|
||||
|
||||
// BGRA rows top-down, 4x4 supersampled.
|
||||
std::vector<uint8_t> render(int size)
|
||||
{
|
||||
std::vector<uint8_t> out(size * size * 4);
|
||||
const int ss = 4;
|
||||
for (int y = 0; y < size; ++y)
|
||||
for (int x = 0; x < size; ++x)
|
||||
{
|
||||
float R = 0, G = 0, B = 0, A = 0;
|
||||
for (int sy = 0; sy < ss; ++sy)
|
||||
for (int sx = 0; sx < ss; ++sx)
|
||||
{
|
||||
float r, g, b, a;
|
||||
sample((x + (sx + 0.5f) / ss) / size, (y + (sy + 0.5f) / ss) / size, r, g, b, a);
|
||||
R += r * a;
|
||||
G += g * a;
|
||||
B += b * a;
|
||||
A += a;
|
||||
}
|
||||
uint8_t *p = &out[(y * size + x) * 4];
|
||||
const float n = ss * ss;
|
||||
const float alpha = A / n;
|
||||
p[0] = static_cast<uint8_t>(std::lround(A > 0 ? B / A * 255 : 0));
|
||||
p[1] = static_cast<uint8_t>(std::lround(A > 0 ? G / A * 255 : 0));
|
||||
p[2] = static_cast<uint8_t>(std::lround(A > 0 ? R / A * 255 : 0));
|
||||
p[3] = static_cast<uint8_t>(std::lround(alpha * 255));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
void put16(std::vector<uint8_t> &v, uint32_t x) { v.insert(v.end(), {uint8_t(x), uint8_t(x >> 8)}); }
|
||||
void put32(std::vector<uint8_t> &v, uint32_t x)
|
||||
{
|
||||
v.insert(v.end(), {uint8_t(x), uint8_t(x >> 8), uint8_t(x >> 16), uint8_t(x >> 24)});
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
if (argc != 2)
|
||||
{
|
||||
std::fprintf(stderr, "usage: make_icon <out.ico>\n");
|
||||
return 2;
|
||||
}
|
||||
const int sizes[] = {256, 64, 48, 32, 24, 16};
|
||||
std::vector<std::vector<uint8_t>> images;
|
||||
for (int s : sizes)
|
||||
{
|
||||
// A BMP without its file header: BITMAPINFOHEADER (height doubled: the XOR image and the AND mask), the
|
||||
// pixels bottom-up, then the AND mask (all zero: the alpha channel decides).
|
||||
const std::vector<uint8_t> px = render(s);
|
||||
std::vector<uint8_t> img;
|
||||
put32(img, 40);
|
||||
put32(img, s);
|
||||
put32(img, s * 2);
|
||||
put16(img, 1);
|
||||
put16(img, 32);
|
||||
put32(img, 0);
|
||||
put32(img, s * s * 4);
|
||||
put32(img, 0);
|
||||
put32(img, 0);
|
||||
put32(img, 0);
|
||||
put32(img, 0);
|
||||
for (int y = s - 1; y >= 0; --y)
|
||||
img.insert(img.end(), px.begin() + y * s * 4, px.begin() + (y + 1) * s * 4);
|
||||
const int maskRow = ((s + 31) / 32) * 4;
|
||||
img.insert(img.end(), static_cast<size_t>(maskRow * s), 0);
|
||||
images.push_back(std::move(img));
|
||||
}
|
||||
std::vector<uint8_t> ico;
|
||||
put16(ico, 0);
|
||||
put16(ico, 1);
|
||||
put16(ico, static_cast<uint32_t>(images.size()));
|
||||
uint32_t offset = 6 + 16 * static_cast<uint32_t>(images.size());
|
||||
for (size_t i = 0; i < images.size(); ++i)
|
||||
{
|
||||
ico.push_back(static_cast<uint8_t>(sizes[i] >= 256 ? 0 : sizes[i]));
|
||||
ico.push_back(static_cast<uint8_t>(sizes[i] >= 256 ? 0 : sizes[i]));
|
||||
ico.push_back(0);
|
||||
ico.push_back(0);
|
||||
put16(ico, 1);
|
||||
put16(ico, 32);
|
||||
put32(ico, static_cast<uint32_t>(images[i].size()));
|
||||
put32(ico, offset);
|
||||
offset += static_cast<uint32_t>(images[i].size());
|
||||
}
|
||||
for (const auto &img : images)
|
||||
ico.insert(ico.end(), img.begin(), img.end());
|
||||
FILE *f = std::fopen(argv[1], "wb");
|
||||
if (!f || std::fwrite(ico.data(), 1, ico.size(), f) != ico.size())
|
||||
{
|
||||
std::fprintf(stderr, "make_icon: cannot write %s\n", argv[1]);
|
||||
return 1;
|
||||
}
|
||||
std::fclose(f);
|
||||
return 0;
|
||||
}
|
||||
|
Before Width: | Height: | Size: 28 KiB After Width: | Height: | Size: 82 KiB |
@@ -1,4 +1,4 @@
|
||||
// The runner's resources on Windows: its icon (a placeholder, no game art; GLFW_ICON is the name GLFW gives the
|
||||
// The runner's resources on Windows: its icon (TMB's variant of The Bozos' logo, the clown with its head on fire; no game art; GLFW_ICON is the name GLFW gives the
|
||||
// window's class, so the window and the taskbar show it too) and its version information.
|
||||
#include <winver.h>
|
||||
|
||||
|
||||
@@ -28,6 +28,7 @@
|
||||
#include "ps2_runtime.h"
|
||||
#include "ps2_recompiled_functions.h"
|
||||
#include "runtime/ps2_debug_ui.h"
|
||||
#include "runtime/ps2_determinism.h"
|
||||
#if defined(PS2X_ENABLE_DEBUG_UI)
|
||||
#include "imgui.h"
|
||||
#endif
|
||||
@@ -64,6 +65,25 @@ namespace tmb::cheats
|
||||
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)
|
||||
@@ -223,6 +243,12 @@ namespace tmb::cheats
|
||||
|
||||
void drawTab()
|
||||
{
|
||||
// Deterministic mode: nothing the user does may change the run (only the environment's cheats, from launch).
|
||||
if (ps2x::det::enabled())
|
||||
{
|
||||
ImGui::TextDisabled("Off in deterministic mode (PS2X_DETERMINISTIC=1): the environment's cheats only.");
|
||||
return;
|
||||
}
|
||||
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;
|
||||
@@ -233,6 +259,20 @@ namespace tmb::cheats
|
||||
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);
|
||||
@@ -267,6 +307,47 @@ namespace tmb::cheats
|
||||
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);
|
||||
@@ -280,7 +361,7 @@ namespace tmb::cheats
|
||||
const char *value = std::getenv("TMB_CHEATS_TOGGLE");
|
||||
return value && *value ? std::atof(value) : 0.0;
|
||||
}();
|
||||
if (s_toggle > 0.0)
|
||||
if (s_toggle > 0.0 && !ps2x::det::enabled())
|
||||
{
|
||||
const double now = std::chrono::duration<double>(std::chrono::steady_clock::now().time_since_epoch()).count();
|
||||
static double s_next = now + s_toggle;
|
||||
@@ -368,6 +449,8 @@ namespace tmb::cheats
|
||||
{
|
||||
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"));
|
||||
|
||||
@@ -267,6 +267,7 @@ namespace tmb::meshes
|
||||
bool valid = false;
|
||||
uint32_t file = 0, offset = 0, poolFrom = 0, pc = 0;
|
||||
float screen[16] = {}, clip[16] = {};
|
||||
float object[16] = {}; // its object-to-camera matrix (VU 0-3), for interpolation's parts
|
||||
uint32_t pointLights[11][4] = {};
|
||||
} g_previous;
|
||||
|
||||
@@ -306,6 +307,29 @@ namespace tmb::meshes
|
||||
bool g_inHier2pFlush = false;
|
||||
uint64_t g_unsentFlushes = 0; // views submitted at the frame's end (not kicked by hier__Fi)
|
||||
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;
|
||||
|
||||
void recycleVertices(Drawn &drawn)
|
||||
{
|
||||
for (auto &batch : drawn.batches)
|
||||
if (batch.vertices.capacity() != 0u && g_vertexPool.size() < 8192u)
|
||||
{
|
||||
batch.vertices.clear();
|
||||
g_vertexPool.push_back(std::move(batch.vertices));
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<ps2x::native::Vertex> pooledVertices()
|
||||
{
|
||||
if (g_vertexPool.empty())
|
||||
return {};
|
||||
std::vector<ps2x::native::Vertex> vertices = std::move(g_vertexPool.back());
|
||||
g_vertexPool.pop_back();
|
||||
return vertices;
|
||||
}
|
||||
|
||||
struct ViewList : ps2x::native::MeshViewList<Drawn>
|
||||
{
|
||||
// Built by hier2p: sent only by hier2pFlushDma. On the frame a split screen ends hier2p builds its view once
|
||||
@@ -313,6 +337,11 @@ namespace tmb::meshes
|
||||
bool hier2p = false;
|
||||
void clear()
|
||||
{
|
||||
for (Drawn &drawn : opaque)
|
||||
recycleVertices(drawn);
|
||||
for (std::vector<Drawn> &bucket : buckets)
|
||||
for (Drawn &drawn : bucket)
|
||||
recycleVertices(drawn);
|
||||
MeshViewList<Drawn>::clear();
|
||||
hier2p = false;
|
||||
}
|
||||
@@ -637,7 +666,9 @@ namespace tmb::meshes
|
||||
bool textured = false;
|
||||
uint32_t texnum = ~0u;
|
||||
Batch *batch = nullptr;
|
||||
std::vector<ps2x::native::Vertex> strip;
|
||||
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;
|
||||
strip.clear();
|
||||
static const bool s_check = std::getenv("TMB_NATIVE_MESHES_CHECK") != nullptr;
|
||||
for (uint32_t si = 0; si < strips; ++si)
|
||||
{
|
||||
@@ -690,6 +721,7 @@ namespace tmb::meshes
|
||||
{
|
||||
out.batches.emplace_back(std::move(writes));
|
||||
batch = &out.batches.back();
|
||||
batch->vertices = pooledVertices();
|
||||
batch->tex0 = tex0;
|
||||
batch->textured = textured;
|
||||
batch->blended = blended;
|
||||
@@ -1254,6 +1286,15 @@ namespace tmb::meshes
|
||||
if (!it)
|
||||
{
|
||||
++g_stats.noObject;
|
||||
// TMB_NATIVE_MESHES_LOG_MISSING=1: the first objects of a loaded file the pack does not have.
|
||||
static const bool s_logMissing = std::getenv("TMB_NATIVE_MESHES_LOG_MISSING") != nullptr;
|
||||
static std::unordered_map<uint32_t, bool> s_seen;
|
||||
if (s_logMissing && !s_seen[obj] && s_seen.size() < 40u)
|
||||
{
|
||||
s_seen[obj] = true;
|
||||
std::fprintf(stderr, "[tmb:mesh] object %#x (%s + %#x, setup %#x, flags %#x, %s): not in the pack\n", obj,
|
||||
file.file->name.c_str(), offset, pc, fp, opaque ? "opaque" : "alpha");
|
||||
}
|
||||
stateOnly(ee, extra, opaque);
|
||||
return;
|
||||
}
|
||||
@@ -1318,14 +1359,18 @@ namespace tmb::meshes
|
||||
drawn.offset = offset;
|
||||
// The setup's matrix: this object's, or (a resume) the one before it, which 0xc78 keeps (it runs 0x1700's
|
||||
// setup again, which makes it anew).
|
||||
float screen[16], clip[16];
|
||||
float screen[16], clip[16], object[16];
|
||||
if (resume && drawPc != 0x1700u)
|
||||
{
|
||||
std::memcpy(screen, previous.screen, sizeof(screen));
|
||||
std::memcpy(clip, previous.clip, sizeof(clip));
|
||||
std::memcpy(object, previous.object, sizeof(object));
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int j = 0; j < 4; ++j)
|
||||
for (int i = 0; i < 4; ++i)
|
||||
object[j * 4 + i] = g_vu.f(j, i);
|
||||
tmb::vu1::objectToScreen(g_vu, screen, false);
|
||||
for (int j = 0; j < 4; ++j)
|
||||
for (int k = 0; k < 4; ++k)
|
||||
@@ -1335,6 +1380,18 @@ namespace tmb::meshes
|
||||
buildStrips(ee, obj, fileBase, *it, drawPc, drawn, screen, it->kind == 4u ? bones : 0u);
|
||||
std::memcpy(drawn.clip, clip, sizeof(clip));
|
||||
drawn.hasClip = !drawn.screenSpace && it->kind != 4u; // (the skinned programs: not modelled)
|
||||
// For interpolation (Renderer::setParts): the matrix as camera (VU 9-12, the view's projection, its z row
|
||||
// scaled by the object's depth factor as buildStrips scales the matrix's) times the object (VU 0-3: object to
|
||||
// camera, the camera's turn included), interpolated apart so a turning object or camera keeps its shape.
|
||||
if (!drawn.screenSpace)
|
||||
{
|
||||
const bool depthScaled = drawPc != 0x0070u;
|
||||
for (int i = 0; i < 4; ++i)
|
||||
for (int k = 0; k < 4; ++k)
|
||||
drawn.partCamera[i * 4 + k] = g_vu.f(9 + i, k) * (k == 2 && depthScaled ? g_vu.f(4, 2) : 1.0f);
|
||||
std::memcpy(drawn.partObject, object, sizeof(object));
|
||||
drawn.hasParts = true;
|
||||
}
|
||||
g_stats.skid += skid ? 1u : 0u;
|
||||
if (opaque)
|
||||
{
|
||||
@@ -1345,11 +1402,30 @@ namespace tmb::meshes
|
||||
g_previous.pc = drawPc;
|
||||
std::memcpy(g_previous.screen, screen, sizeof(screen));
|
||||
std::memcpy(g_previous.clip, clip, sizeof(clip));
|
||||
std::memcpy(g_previous.object, object, sizeof(object));
|
||||
std::memcpy(g_previous.pointLights, &g_vu.words[165u * 4u], sizeof(g_previous.pointLights));
|
||||
}
|
||||
const uint64_t hash = (static_cast<uint64_t>(fileIndex) << 32 | offset) * 0x9e3779b97f4a7c15ull;
|
||||
// Its key for interpolation (Renderer::setKey): the object (file, offset) and its instance (two cars of one model
|
||||
// apart), with how many had both before it this frame (a model placed several times, the views of a split
|
||||
// screen); the renderer matches alike ones by where they are (the key's base), since that count changes as they
|
||||
// are culled.
|
||||
const uint64_t hash = ((static_cast<uint64_t>(fileIndex) << 32 | offset) * 0x9e3779b97f4a7c15ull) ^ (static_cast<uint64_t>(inst) * 0xc4ceb9fe1a85ec53ull);
|
||||
const uint32_t occurrence = g_keysThisFrame[hash]++;
|
||||
drawn.key = (hash ^ (static_cast<uint64_t>(occurrence) * 0xc2b2ae3d27d4eb4full)) | 1u;
|
||||
drawn.keyBase = hash | 1u; // alike objects (the same model without an instance of its own): matched by place
|
||||
// PS2X_INTERP_LOG=1: each key the first time it is made (what the renderer's jump lines name).
|
||||
static const bool s_logKeys = std::getenv("PS2X_INTERP_LOG") != nullptr;
|
||||
if (s_logKeys)
|
||||
{
|
||||
static std::unordered_map<uint64_t, bool> s_seen;
|
||||
if (!s_seen[drawn.key] && s_seen.size() < 20000u)
|
||||
{
|
||||
s_seen[drawn.key] = true;
|
||||
std::fprintf(stderr, "[interp-key] %016llx obj %#x file %u offset %#x inst %#x occurrence %u setup %#x%s\n",
|
||||
static_cast<unsigned long long>(drawn.key), obj, fileIndex, offset, inst, occurrence, drawPc,
|
||||
opaque ? "" : " alpha");
|
||||
}
|
||||
}
|
||||
for (uint32_t q = 0; q < 22u; ++q)
|
||||
for (int k = 0; k < 4; ++k)
|
||||
drawn.check[q][k] = g_vu.w(q, k);
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
#include "runtime/native/native_vu1_sandbox.h"
|
||||
#include "runtime/ps2_memory.h"
|
||||
#include "runtime/native/native_display.h"
|
||||
#include "runtime/ps2_determinism.h"
|
||||
#include "runtime/native/native_gs_hook.h"
|
||||
#include "tmb_host.h"
|
||||
#include "tmb_meshes.h"
|
||||
@@ -198,9 +199,13 @@ namespace tmb::native
|
||||
}
|
||||
|
||||
// A match is under way while its frames end (the end of real-time processing, onFrameEnd) less than 100 ms
|
||||
// apart on the host's clock; the menus (the shell overlay's loop) end none.
|
||||
// apart on the host's clock; the menus (the shell overlay's loop) end none. PS2X_DETERMINISTIC=1: the clock is
|
||||
// the game frames ended (a sixtieth of a second each), so which frames count as a match's or a menu's is the
|
||||
// kinds of the frames before, never the host's timing.
|
||||
double hostSeconds()
|
||||
{
|
||||
if (ps2x::det::enabled())
|
||||
return static_cast<double>(ps2x::det::frame()) / 60.0;
|
||||
static const auto s_start = std::chrono::steady_clock::now();
|
||||
return std::chrono::duration<double>(std::chrono::steady_clock::now() - s_start).count();
|
||||
}
|
||||
@@ -3401,6 +3406,9 @@ namespace tmb::native
|
||||
}
|
||||
if (!s_on || !enabled() || !inMatch())
|
||||
return;
|
||||
// Deterministic mode: every sample far (as the caller cleared them): the GPU's depth is host timing.
|
||||
if (ps2x::det::enabled())
|
||||
return;
|
||||
ps2x::native::Renderer &renderer = ps2x::native::Renderer::instance();
|
||||
renderer.wantDepth();
|
||||
uint64_t bitbltbuf = 0, trxpos = 0, trxreg = 0;
|
||||
@@ -3461,17 +3469,38 @@ namespace tmb::native
|
||||
std::fill(z, z + 16, 0u);
|
||||
if (!flareDepthNative())
|
||||
return false;
|
||||
if (ps2x::det::enabled()) // deterministic mode: all far (the GPU's depth is host timing)
|
||||
return true;
|
||||
ps2x::native::Renderer &renderer = ps2x::native::Renderer::instance();
|
||||
renderer.wantDepth();
|
||||
const ps2x::native::Screen view = screen();
|
||||
uint32_t found = 0;
|
||||
for (uint32_t y = 0; y < 4u; ++y)
|
||||
for (uint32_t x = 0; x < 4u; ++x)
|
||||
{
|
||||
uint32_t sample = 0;
|
||||
if (renderer.depthAt(view.originX + static_cast<float>((x0 + x) & 0x7ffu) + 0.5f,
|
||||
view.originY + static_cast<float>((y0 + y) & 0x7ffu) + 0.5f, sample))
|
||||
{
|
||||
z[y * 4u + x] = std::min<uint32_t>(sample, 0xffffffu);
|
||||
++found;
|
||||
}
|
||||
}
|
||||
// TMB_NATIVE_LOG_FLARES=1: every 300 blocks, how many of their samples the native depth had (not read yet: far).
|
||||
static const bool s_log = std::getenv("TMB_NATIVE_LOG_FLARES") != nullptr;
|
||||
static uint32_t s_blocks = 0, s_found = 0, s_near = 0;
|
||||
if (s_log)
|
||||
{
|
||||
s_found += found;
|
||||
for (uint32_t i = 0; i < 16u; ++i)
|
||||
s_near += z[i] != 0u && z[i] < 0xffffffu ? 1u : 0u;
|
||||
if (++s_blocks % 300u == 0u)
|
||||
{
|
||||
std::fprintf(stderr, "[tmb:native] flare depth: %u blocks, %u of %u samples read, %u in front of the far plane\n", 300u,
|
||||
s_found, 300u * 16u, s_near);
|
||||
s_found = s_near = 0;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
#include "runtime/gs/gs_draw_estimate.h"
|
||||
#include "runtime/ps2_memory.h"
|
||||
#include "runtime/native/native_display.h"
|
||||
#include "runtime/ps2_determinism.h"
|
||||
#include "runtime/ps2_reference.h"
|
||||
#include "runtime/sampling_profiler_gate.h"
|
||||
#include "tmb_host.h"
|
||||
#include <string>
|
||||
@@ -41,6 +43,11 @@ namespace tmb
|
||||
{
|
||||
extern std::atomic<bool> g_rainLiftOff; // runtime/vu1/tmb_vu1_rain.cpp
|
||||
extern std::atomic<uint64_t> g_rainLiftedStrips;
|
||||
// The build's name and the game's stub addresses for the reference records (tmb_call_names.cpp, which CMake
|
||||
// generates in the build tree from the generated code's stub list).
|
||||
extern const char *const kBuildName;
|
||||
extern const ps2x::reference::CallName kCallNames[];
|
||||
extern const size_t kCallNameCount;
|
||||
}
|
||||
|
||||
namespace tmb::native
|
||||
@@ -75,6 +82,7 @@ namespace tmb::cheats
|
||||
void install(PS2Runtime &runtime);
|
||||
void setTheGame(uint32_t game);
|
||||
void onFrame(uint8_t *rdram);
|
||||
void logProgress(uint8_t *rdram, uint32_t gp);
|
||||
}
|
||||
|
||||
namespace tmb::meshes
|
||||
@@ -1104,6 +1112,7 @@ namespace
|
||||
tmb::native::onMenuFrameEnd(); // TMB_NATIVE: publishes a menu frame's native draws (not in a match)
|
||||
const double step = pacer.frameEnd();
|
||||
g_lastFrameEndSeconds.store(hitchClock(), std::memory_order_relaxed);
|
||||
tmb::cheats::logProgress(rdram, gp); // TMB_LOG_PROGRESS
|
||||
// The fps overlay in the menus (a match's frames are counted at timerEndOfRealTimeProcessing).
|
||||
if (hitchClock() - g_lastMatchFrameNoted.load(std::memory_order_relaxed) > 0.5)
|
||||
runtime->noteGameFrame();
|
||||
@@ -1123,7 +1132,10 @@ namespace
|
||||
s_last = now;
|
||||
}
|
||||
EeScheduler &scheduler = runtime->eeScheduler();
|
||||
const uint64_t real = static_cast<uint64_t>(step * static_cast<double>(EeScheduler::kEeClockHz));
|
||||
// PS2X_DETERMINISTIC=1: exactly one field's EE cycles (the step is one field too).
|
||||
const uint64_t real = ps2x::det::enabled()
|
||||
? EeScheduler::kEeClockHz / static_cast<uint64_t>(fieldRate(rdram, gp))
|
||||
: static_cast<uint64_t>(step * static_cast<double>(EeScheduler::kEeClockHz));
|
||||
const uint64_t accounted = scheduler.currentCycle() - g_frameEndCycle;
|
||||
for (uint64_t debt = real > accounted ? real - accounted : 0u; debt != 0u;)
|
||||
{
|
||||
@@ -1720,6 +1732,16 @@ namespace
|
||||
g_traceIdle = true;
|
||||
runtime.eeScheduler().setIdleObserver([](const EeScheduler::IdleRecord &record) { g_frameIdle.push_back(record); });
|
||||
}
|
||||
// PS2X_REFERENCE (the reference harness, docs/REFERENCE_HARNESS.md): the build, and the game's library and
|
||||
// kernel stubs whose calls the records hash (their addresses from the generated stub list: tmb_call_names.cpp).
|
||||
if (ps2x::reference::active())
|
||||
{
|
||||
ps2x::reference::setBuild(tmb::kBuildName);
|
||||
ps2x::reference::setCallNames(tmb::kCallNames, tmb::kCallNameCount);
|
||||
}
|
||||
if (ps2x::det::enabled())
|
||||
std::cout << "[tmb] deterministic mode (PS2X_DETERMINISTIC=1): a field per frame, fixed date, pad scripts in frames"
|
||||
<< std::endl;
|
||||
runtime.registerFunction(kVblankHandler, &vblankHandlerOverride);
|
||||
runtime.registerFunction(kHier, &hierOverride);
|
||||
tmb::native::install(); // TMB_NATIVE
|
||||
|
||||
@@ -370,18 +370,41 @@ namespace tmb::particles
|
||||
TexturePtr texture;
|
||||
std::vector<Vertex> triangles;
|
||||
bool open = false;
|
||||
// Interpolation (Renderer::drawTracked): the particle the next quads are (particleId; 0: none), and an id per
|
||||
// triangle so far (0 for the triangles of no particle).
|
||||
uint64_t id = 0;
|
||||
std::vector<uint64_t> ids;
|
||||
};
|
||||
|
||||
// The view particleDraw draws (a split screen's), for the particles' ids.
|
||||
uint32_t g_view = 0;
|
||||
|
||||
// A particle's identity from one frame to the next, for frames drawn between the game's: its view, its system and
|
||||
// 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())
|
||||
return 0u;
|
||||
return ((static_cast<uint64_t>(g_view) + 1u) << 52) ^ (static_cast<uint64_t>(ps) << 16) ^ (index + 1u);
|
||||
}
|
||||
|
||||
std::vector<Vertex> *g_capture = nullptr; // TMB_NATIVE_PARTICLES_CHECK: the draws go here instead
|
||||
|
||||
void flush(Batch &batch)
|
||||
{
|
||||
if (g_capture)
|
||||
g_capture->insert(g_capture->end(), batch.triangles.begin(), batch.triangles.end());
|
||||
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(),
|
||||
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(),
|
||||
static_cast<uint32_t>(batch.triangles.size()), batch.texture);
|
||||
batch.triangles.clear();
|
||||
batch.ids.clear();
|
||||
batch.open = false;
|
||||
}
|
||||
|
||||
@@ -404,6 +427,13 @@ namespace tmb::particles
|
||||
|
||||
void pushQuad(Batch &batch, const Vertex corner[4])
|
||||
{
|
||||
if (batch.id != 0u) // its two triangles' ids (the triangles before it without: 0)
|
||||
{
|
||||
batch.ids.resize(batch.triangles.size() / 3u, 0u);
|
||||
const uint64_t h = batch.id * 0x9e3779b97f4a7c15ull;
|
||||
batch.ids.push_back(h | 1u);
|
||||
batch.ids.push_back((h ^ 0x5555555555555554ull) | 1u);
|
||||
}
|
||||
const int order[6] = {0, 1, 2, 1, 2, 3}; // as the adapter splits a sprite
|
||||
for (int i : order)
|
||||
batch.triangles.push_back(corner[i]);
|
||||
@@ -547,6 +577,7 @@ namespace tmb::particles
|
||||
corner[i].rgba = rgba;
|
||||
corner[i].fog = std::floor(fog) / 255.0f;
|
||||
}
|
||||
batch.id = particleId(ps, index);
|
||||
pushQuad(batch, corner);
|
||||
++g_stats.nativeSprites;
|
||||
}
|
||||
@@ -619,6 +650,7 @@ namespace tmb::particles
|
||||
corner[i].rgba = rgba;
|
||||
corner[i].fog = std::floor(std::max(fog, 0.0f)) / 255.0f;
|
||||
}
|
||||
batch.id = particleId(ps, index);
|
||||
pushQuad(batch, corner);
|
||||
++g_stats.nativeSprites;
|
||||
}
|
||||
@@ -700,6 +732,7 @@ namespace tmb::particles
|
||||
corner[i].z = (i < 2 ? a[2] * qa : b[2] * qb) * 16.0f;
|
||||
corner[i].rgba = i < 2 ? nearColour : farColour;
|
||||
}
|
||||
batch.id = particleId(ps, k);
|
||||
pushQuad(batch, corner);
|
||||
++g_stats.nativeSprites;
|
||||
}
|
||||
@@ -2360,6 +2393,7 @@ namespace tmb::particles
|
||||
void particleDrawOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
|
||||
{
|
||||
const uint32_t view = getRegU32(ctx, 4), gp = getRegU32(ctx, 28);
|
||||
g_view = view;
|
||||
const bool toggledAll = toggledOff() && !settings().toggleFlares;
|
||||
if (!settings().on || !tmb::native::effectsInStream() || u32(rdram, gp + static_cast<uint32_t>(kGpColours)) == 0u || toggledAll)
|
||||
{
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env bash
|
||||
# Regenerates the region's recompiler config (recomp/tmb_scus97101.toml or recomp/tmb_sces50360.toml) from its ELF with
|
||||
# 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"
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
#!/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
|
||||
--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
|
||||
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
|
||||
Windows lets a running program's file be renamed but not replaced; those are listed in update/old_files.txt for the
|
||||
launcher to delete at its next start. The player's own folders (build/, game/) and saves (%APPDATA%) are never
|
||||
touched; tmb_build removes the source files a release no longer has (source/release_files.txt).
|
||||
|
||||
Prints one line per event for the launcher: "step <verify|extract|install|clean>", "progress <done> <total>" (bytes),
|
||||
"done <version>", or "error <message>" (exit code 1).
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import zipfile
|
||||
|
||||
TOP = 'TMB_Recomp/'
|
||||
LAUNCHER = 'TMB Launcher.exe'
|
||||
PROTECTED = ('build/', 'game/', 'update/') # the player's build and game, and this update's own folder
|
||||
|
||||
|
||||
class UpdateError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def say(*parts):
|
||||
print(*parts, flush=True)
|
||||
|
||||
|
||||
def sha256_of(path):
|
||||
h = hashlib.sha256()
|
||||
total = os.path.getsize(path)
|
||||
done = 0
|
||||
with open(path, 'rb') as f:
|
||||
for block in iter(lambda: f.read(1 << 20), b''):
|
||||
h.update(block)
|
||||
done += len(block)
|
||||
if done % (16 << 20) < (1 << 20):
|
||||
say('progress', done, total)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def expected_sha256(path):
|
||||
with open(path, 'r', encoding='utf-8', errors='replace') as f:
|
||||
token = f.read().split()
|
||||
if not token or len(token[0]) != 64 or any(c not in '0123456789abcdefABCDEF' for c in token[0]):
|
||||
raise UpdateError('the .sha256 file does not hold a SHA-256')
|
||||
return token[0].lower()
|
||||
|
||||
|
||||
def checked_names(zf, version):
|
||||
"""The zip's file entries as (entry, path under the top folder), after checking every name."""
|
||||
files = []
|
||||
for info in zf.infolist():
|
||||
name = info.filename
|
||||
if not name.startswith(TOP) or '\\' in name or ':' in name or name.startswith('/'):
|
||||
raise UpdateError('unexpected name in the zip: %r' % name)
|
||||
rel = name[len(TOP):]
|
||||
if any(part in ('..', '.') for part in rel.split('/')):
|
||||
raise UpdateError('unexpected name in the zip: %r' % name)
|
||||
if rel.startswith(PROTECTED) or rel.rstrip('/') in ('build', 'game', 'update'):
|
||||
raise UpdateError('the zip holds %r, a folder of the player\'s own' % name)
|
||||
if not name.endswith('/'):
|
||||
files.append((info, rel))
|
||||
rels = {rel for _info, rel in files}
|
||||
if LAUNCHER not in rels or 'source/release.ini' not in rels:
|
||||
raise UpdateError('this is not a TMB_Recomp release (no launcher or source/release.ini)')
|
||||
stamp = zf.read(TOP + 'source/release.ini').decode('utf-8', 'replace')
|
||||
found = ''
|
||||
for line in stamp.splitlines():
|
||||
key, _, value = line.partition('=')
|
||||
if key.strip() == 'version':
|
||||
found = value.strip()
|
||||
if found != version:
|
||||
raise UpdateError('the zip is version %r, not %r' % (found, version))
|
||||
return files
|
||||
|
||||
|
||||
def remove_tree(path):
|
||||
def onerror(func, p, _exc):
|
||||
os.chmod(p, 0o666)
|
||||
func(p)
|
||||
if os.path.isdir(path):
|
||||
shutil.rmtree(path, onerror=onerror)
|
||||
|
||||
|
||||
def replace(src, dst, old_files):
|
||||
"""Moves src over dst; a dst in use is renamed aside first (<dst>.tmb-old, or .tmb-old2... if that one is too)."""
|
||||
os.makedirs(os.path.dirname(dst), exist_ok=True)
|
||||
try:
|
||||
os.replace(src, dst)
|
||||
return
|
||||
except PermissionError:
|
||||
pass
|
||||
for n in range(1, 100):
|
||||
aside = dst + ('.tmb-old' if n == 1 else '.tmb-old%d' % n)
|
||||
try:
|
||||
if os.path.exists(aside):
|
||||
os.remove(aside)
|
||||
os.rename(dst, aside)
|
||||
break
|
||||
except OSError:
|
||||
continue
|
||||
else:
|
||||
raise UpdateError('%s is in use and could not be set aside' % dst)
|
||||
old_files.append(aside)
|
||||
os.replace(src, dst)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument('--zip', required=True)
|
||||
ap.add_argument('--sha256', required=True)
|
||||
ap.add_argument('--version', required=True)
|
||||
ap.add_argument('--install', required=True)
|
||||
ap.add_argument('--keep-zip', action='store_true')
|
||||
args = ap.parse_args()
|
||||
install = os.path.abspath(args.install)
|
||||
work = os.path.join(install, 'update')
|
||||
staging = os.path.join(work, 'staging')
|
||||
|
||||
say('step verify')
|
||||
want = expected_sha256(args.sha256)
|
||||
got = sha256_of(args.zip)
|
||||
if got != want:
|
||||
raise UpdateError('the download is damaged (SHA-256 %s, expected %s): try again' % (got, want))
|
||||
|
||||
say('step extract')
|
||||
remove_tree(staging)
|
||||
with zipfile.ZipFile(args.zip) as zf:
|
||||
files = checked_names(zf, args.version)
|
||||
total = sum(info.file_size for info, _rel in files)
|
||||
if shutil.disk_usage(install).free < total + (256 << 20):
|
||||
raise UpdateError('not enough free space: %d MB needed' % ((total >> 20) + 256))
|
||||
done = 0
|
||||
for info, rel in files:
|
||||
target = os.path.join(staging, *rel.split('/'))
|
||||
os.makedirs(os.path.dirname(target), exist_ok=True)
|
||||
with zf.open(info) as src, open(target, 'wb') as dst:
|
||||
shutil.copyfileobj(src, dst, 1 << 20)
|
||||
done += info.file_size
|
||||
say('progress', done, total)
|
||||
|
||||
# Everything is extracted and checked: only moves on the same disk from here.
|
||||
say('step install')
|
||||
old_files = []
|
||||
for n, (_info, rel) in enumerate(files):
|
||||
replace(os.path.join(staging, *rel.split('/')), os.path.join(install, *rel.split('/')), old_files)
|
||||
if n % 200 == 0:
|
||||
say('progress', n, len(files))
|
||||
say('progress', len(files), len(files))
|
||||
if old_files:
|
||||
with open(os.path.join(work, 'old_files.txt'), 'a', encoding='utf-8') as f:
|
||||
f.write(''.join(path + '\n' for path in old_files))
|
||||
|
||||
say('step clean')
|
||||
remove_tree(staging)
|
||||
if not args.keep_zip:
|
||||
for path in (args.zip, args.sha256):
|
||||
try:
|
||||
os.remove(path)
|
||||
except OSError:
|
||||
pass
|
||||
say('done', args.version)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except (UpdateError, OSError, zipfile.BadZipFile) as e:
|
||||
say('error', e)
|
||||
sys.exit(1)
|
||||
@@ -4,7 +4,7 @@ presses after Suburbs (0 Suburbs, 1 Junkyard, 4 Skyscrapers, 5 Downtown, 6 Highw
|
||||
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/PS2Recomp/ps2xRuntime/ps2EntryRunner game/SCES_503.60
|
||||
PS2X_PAD_SCRIPT="$(tools/arena_script.py 4 380)" timeout 380 build/game_us/PS2Recomp/ps2xRuntime/ps2EntryRunner game_us/SCUS_971.01
|
||||
"""
|
||||
import sys
|
||||
|
||||
|
||||
@@ -45,6 +45,7 @@ import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import zipfile
|
||||
|
||||
@@ -54,10 +55,13 @@ from tmb_build import pe_imports, cmake_rc_flags # noqa: E402
|
||||
|
||||
KIT_VERSION = 1
|
||||
|
||||
# ---- pinned downloads (official upstream only) ----
|
||||
# ---- pinned downloads (official upstream; a mirror of ours only as a fallback, held to the same SHA-256) ----
|
||||
FFMPEG = {
|
||||
'version': '9.0.2',
|
||||
'url': 'https://ffmpeg.org/releases/ffmpeg-9.0.2.tar.xz',
|
||||
# Tried only when the upstream address fails: the same file on our build-deps pre-release (ffmpeg.org dropped
|
||||
# the release runner's connections), held to the same SHA-256.
|
||||
'mirrors': ['https://github.com/TheBozos/TMB_Recomp/releases/download/build-deps/ffmpeg-9.0.2.tar.xz'],
|
||||
'sha256': '8c3850283eb25fa026482078a04051e0be17347b09ef81a0849bec15a96e002e',
|
||||
# ffmpeg-9.0.2.tar.xz.asc checked once with gpg against https://ffmpeg.org/ffmpeg-devel.asc:
|
||||
'signing_key': 'FCF986EA15E6E293A5644F10B4322F04D67658D8 (FFmpeg release signing key)',
|
||||
@@ -243,10 +247,30 @@ def download(spec, downloads):
|
||||
os.makedirs(downloads, exist_ok=True)
|
||||
path = os.path.join(downloads, spec['url'].rsplit('/', 1)[1])
|
||||
if not (os.path.isfile(path) and sha256_file(path) == spec['sha256']):
|
||||
log(' downloading %s' % spec['url'])
|
||||
# A few tries, further apart each time: an upstream site sometimes drops or times out a CI runner's connection
|
||||
# (GitHub's release runs start with an empty download cache: a tag's run cannot read another tag's cache).
|
||||
# Then the spec's mirrors, if any; a file from any of them must have the pinned SHA-256.
|
||||
tmp = path + '.part'
|
||||
with urllib.request.urlopen(spec['url']) as r, open(tmp, 'wb') as f:
|
||||
shutil.copyfileobj(r, f, 1 << 20)
|
||||
tries = [(spec['url'], wait) for wait in (0, 20, 60, 120)]
|
||||
tries += [(mirror, wait) for mirror in spec.get('mirrors', ()) for wait in (0, 20, 60)]
|
||||
error = None
|
||||
for url, wait in tries:
|
||||
if wait:
|
||||
log(' %s failed (%s): again in %d s' % (url, error, wait))
|
||||
time.sleep(wait)
|
||||
log(' downloading %s' % url)
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=120) as r, open(tmp, 'wb') as f:
|
||||
shutil.copyfileobj(r, f, 1 << 20)
|
||||
except (urllib.error.URLError, OSError) as e:
|
||||
error = e
|
||||
continue
|
||||
digest = sha256_file(tmp)
|
||||
if digest == spec['sha256']:
|
||||
break
|
||||
error = 'SHA-256 %s, expected %s' % (digest, spec['sha256'])
|
||||
else:
|
||||
raise KitError('%s: could not download (%s)' % (spec['url'], error))
|
||||
os.replace(tmp, path)
|
||||
digest = sha256_file(path)
|
||||
if digest != spec['sha256']:
|
||||
|
||||
@@ -55,8 +55,8 @@ import urllib.request
|
||||
import zipfile
|
||||
|
||||
ROOT = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))
|
||||
REPO = 'boubou666/TMB_Recomp'
|
||||
FORK_REPO = 'boubou666/PS2Recomp'
|
||||
REPO = 'TheBozos/TMB_Recomp'
|
||||
FORK_REPO = 'TheBozos/PS2Recomp'
|
||||
NAME = 'TMB_Recomp'
|
||||
VERSION_RE = re.compile(r'^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$')
|
||||
MSYS2_SOURCES = 'https://repo.msys2.org/mingw/sources/'
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"""A PS2X_PAD_SCRIPT that plays: the menu presses into the first match (it starts 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/PS2Recomp/ps2xRuntime/ps2EntryRunner game/SCES_503.60
|
||||
PS2X_PAD_SCRIPT="$(tools/play_script.py 600)" timeout 600 build/game_us/PS2Recomp/ps2xRuntime/ps2EntryRunner game_us/SCUS_971.01
|
||||
|
||||
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.
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compares two reference records (PS2X_REFERENCE=<file.ref>, docs/REFERENCE_HARNESS.md) frame by frame.
|
||||
|
||||
tools/ref_compare.py a.ref b.ref [--ignore eeCycle,...] [--lines 24]
|
||||
|
||||
Reports the frames compared and the first frame where a field differs (every field that differs there, and the first
|
||||
frame each field differs at). For `ram`, when both runs dumped that frame (PS2X_REFERENCE_DUMP=<frame>: <file>.ram.<frame>),
|
||||
the first differing 32-byte block (its address and both runs' bytes); for `calls`, when both have the frame's call list
|
||||
(PS2X_REFERENCE_CALLS / _FROM: <file>.calls), the two lists side by side from their first difference.
|
||||
Exit status 0: identical over the frames both have (and the same length); 1: they differ; 2: unreadable input.
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import struct
|
||||
import sys
|
||||
|
||||
HEADER = struct.Struct('<8sIIIIIIQII64s64s64s')
|
||||
RECORD = struct.Struct('<IiQQQQQQQIIII')
|
||||
FIELDS = ('frame', 'thread', 'ram', 'scratchpad', 'calls', 'draws', 'sound', 'threads', 'eeCycle', 'callCount',
|
||||
'drawBatches', 'drawVertices', 'soundSamples')
|
||||
# The order fields are reported in (the guest's state first, then what it went through, then the counters).
|
||||
COMPARED = ('ram', 'scratchpad', 'calls', 'callCount', 'draws', 'drawBatches', 'drawVertices', 'sound', 'soundSamples',
|
||||
'threads', 'thread', 'eeCycle')
|
||||
HEXED = {'ram', 'scratchpad', 'calls', 'draws', 'sound', 'threads'}
|
||||
|
||||
|
||||
class Reference:
|
||||
def __init__(self, path):
|
||||
self.path = path
|
||||
with open(path, 'rb') as f:
|
||||
data = f.read()
|
||||
if len(data) < HEADER.size:
|
||||
raise ValueError(f'{path}: too short for a header')
|
||||
(magic, version, header_bytes, record_bytes, hash_id, ram_bytes, sp_bytes, elf_hash, flags, mask_count, run,
|
||||
build, elf) = HEADER.unpack_from(data, 0)
|
||||
if magic != b'PS2XREF1':
|
||||
raise ValueError(f'{path}: not a reference record (magic {magic!r})')
|
||||
if record_bytes != RECORD.size:
|
||||
raise ValueError(f'{path}: records of {record_bytes} bytes, this tool reads {RECORD.size}')
|
||||
self.version, self.hash_id, self.elf_hash, self.flags = version, hash_id, elf_hash, flags
|
||||
self.ram_bytes, self.sp_bytes = ram_bytes, sp_bytes
|
||||
self.run, self.build, self.elf = (s.split(b'\0', 1)[0].decode(errors='replace') for s in (run, build, elf))
|
||||
self.masks = [struct.unpack_from('<II', data, HEADER.size + 8 * i) for i in range(mask_count)]
|
||||
body = data[header_bytes:]
|
||||
count = len(body) // RECORD.size
|
||||
self.records = [dict(zip(FIELDS, RECORD.unpack_from(body, i * RECORD.size))) for i in range(count)]
|
||||
self.partial = len(body) % RECORD.size
|
||||
|
||||
def describe(self):
|
||||
return (f'{self.path}: run "{self.run}", build "{self.build}", ELF {self.elf} {self.elf_hash:016x}, '
|
||||
f'{"deterministic" if self.flags & 1 else "NOT deterministic"}, {len(self.records)} frames'
|
||||
+ (f', {len(self.masks)} masked ranges' if self.masks else '')
|
||||
+ (f' (+{self.partial} bytes of a cut record)' if self.partial else ''))
|
||||
|
||||
|
||||
def value(field, v):
|
||||
return f'{v:016x}' if field in HEXED else str(v)
|
||||
|
||||
|
||||
def ram_block(a, b, frame):
|
||||
"""The first differing 32-byte block of RAM (then the scratchpad) between the two runs' dumps of `frame`."""
|
||||
pa, pb = f'{a.path}.ram.{frame}', f'{b.path}.ram.{frame}'
|
||||
if not (os.path.exists(pa) and os.path.exists(pb)):
|
||||
return f' (no RAM dumps of frame {frame}: run both again with PS2X_REFERENCE_DUMP={frame} for the first differing block)'
|
||||
with open(pa, 'rb') as fa, open(pb, 'rb') as fb:
|
||||
da, db = fa.read(), fb.read()
|
||||
lines = []
|
||||
for offset in range(0, min(len(da), len(db)), 32):
|
||||
if da[offset:offset + 32] != db[offset:offset + 32]:
|
||||
where = f'RAM {offset:08x}' if offset < a.ram_bytes else f'scratchpad {offset - a.ram_bytes:04x}'
|
||||
lines.append(f' first differing 32-byte block: {where}')
|
||||
lines.append(f' {a.run:>12}: {da[offset:offset + 32].hex(" ", 4)}')
|
||||
lines.append(f' {b.run:>12}: {db[offset:offset + 32].hex(" ", 4)}')
|
||||
differing = sum(1 for o in range(0, min(len(da), len(db)), 32) if da[o:o + 32] != db[o:o + 32])
|
||||
lines.append(f' ({differing} blocks differ in all)')
|
||||
return '\n'.join(lines)
|
||||
return ' (the dumps are the same: the hash differs elsewhere, a masked range?)'
|
||||
|
||||
|
||||
def call_list(path, frame):
|
||||
"""The call list of `frame` from <file>.calls, or None."""
|
||||
calls = path + '.calls'
|
||||
if not os.path.exists(calls):
|
||||
return None
|
||||
found, lines = False, []
|
||||
with open(calls, encoding='utf-8', errors='replace') as f:
|
||||
for line in f:
|
||||
if line.startswith('frame '):
|
||||
if found:
|
||||
break
|
||||
found = int(line.split()[1]) == frame
|
||||
continue
|
||||
if found:
|
||||
lines.append(line.rstrip('\n').strip())
|
||||
return lines if found else None
|
||||
|
||||
|
||||
def call_lists(a, b, frame, shown):
|
||||
la, lb = call_list(a.path, frame), call_list(b.path, frame)
|
||||
if la is None or lb is None:
|
||||
return (f' (no call lists of frame {frame} in both: run both with PS2X_REFERENCE_CALLS_FROM={frame} '
|
||||
f'PS2X_REFERENCE_CALLS=1 to see them)')
|
||||
first = next((i for i in range(max(len(la), len(lb))) if i >= len(la) or i >= len(lb) or la[i] != lb[i]), None)
|
||||
if first is None:
|
||||
return ' (the lists read the same: the difference is in a value the text rounds?)'
|
||||
width = max([len(x) for x in la[first:first + shown]] + [len(a.run), 10])
|
||||
out = [f' calls from #{first} ({len(la)} / {len(lb)} calls):', f' {a.run:<{width}} | {b.run}']
|
||||
for i in range(first, min(max(len(la), len(lb)), first + shown)):
|
||||
left = la[i] if i < len(la) else ''
|
||||
right = lb[i] if i < len(lb) else ''
|
||||
out.append(f' {"*" if left != right else " "} {left:<{width}} | {right}')
|
||||
return '\n'.join(out)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument('a')
|
||||
parser.add_argument('b')
|
||||
parser.add_argument('--ignore', default='', help='fields not compared, comma-separated (e.g. eeCycle)')
|
||||
parser.add_argument('--lines', type=int, default=24, help='call list lines shown from the first difference')
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
a, b = Reference(args.a), Reference(args.b)
|
||||
except (OSError, ValueError) as error:
|
||||
print(error, file=sys.stderr)
|
||||
return 2
|
||||
print(a.describe())
|
||||
print(b.describe())
|
||||
if a.elf_hash != b.elf_hash:
|
||||
print('warning: not the same ELF')
|
||||
if a.masks != b.masks:
|
||||
print('warning: not the same masked RAM ranges')
|
||||
ignored = {f for f in args.ignore.split(',') if f}
|
||||
unknown = ignored - set(COMPARED)
|
||||
if unknown:
|
||||
print(f'unknown fields: {", ".join(sorted(unknown))} (fields: {", ".join(COMPARED)})', file=sys.stderr)
|
||||
return 2
|
||||
fields = [f for f in COMPARED if f not in ignored]
|
||||
frames = min(len(a.records), len(b.records))
|
||||
first_by_field = {}
|
||||
first = None
|
||||
for i in range(frames):
|
||||
ra, rb = a.records[i], b.records[i]
|
||||
if ra['frame'] != i or rb['frame'] != i:
|
||||
print(f'record {i}: frame numbers {ra["frame"]} / {rb["frame"]} (a record missing?)')
|
||||
for f in fields:
|
||||
if ra[f] != rb[f] and f not in first_by_field:
|
||||
first_by_field[f] = i
|
||||
if first is None and any(ra[f] != rb[f] for f in fields):
|
||||
first = i
|
||||
if first is None:
|
||||
same = len(a.records) == len(b.records)
|
||||
print(f'identical: {frames} frames compared ({", ".join(fields)})'
|
||||
+ ('' if same else f'; lengths differ ({len(a.records)} / {len(b.records)} frames)'))
|
||||
return 0 if same else 1
|
||||
ra, rb = a.records[first], b.records[first]
|
||||
print(f'first difference at frame {first} (of {frames} compared; the {first} before are identical):')
|
||||
for f in fields:
|
||||
if ra[f] != rb[f]:
|
||||
print(f' {f:<13} {value(f, ra[f]):>16} {value(f, rb[f]):>16}')
|
||||
print('first frame each field differs at: ' + ', '.join(f'{f} {n}' for f, n in sorted(first_by_field.items(), key=lambda x: x[1])))
|
||||
if 'ram' in first_by_field and first_by_field['ram'] == first:
|
||||
print(ram_block(a, b, first))
|
||||
if 'calls' in first_by_field:
|
||||
print(call_lists(a, b, first_by_field['calls'], args.lines))
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,111 @@
|
||||
#!/usr/bin/env python3
|
||||
"""A timed pad script (PS2X_PAD_SCRIPT, seconds) as a frame-keyed one for deterministic mode (PS2X_DETERMINISTIC=1:
|
||||
"frame:BUTTON/frames"), docs/REFERENCE_HARNESS.md.
|
||||
|
||||
tools/ref_pad_script.py --log calibration.log "<seconds script>" (or --script-file f)
|
||||
tools/ref_pad_script.py --log calibration.log --from-log
|
||||
|
||||
Calibration: run the timed script once in deterministic mode with the pad on the wall clock and its changes logged
|
||||
(PS2X_DETERMINISTIC=1 PS2X_PAD_CLOCK=wall PS2X_PAD_LOG=1, stderr to calibration.log): each "[pad] frame N t=T" line
|
||||
anchors second T to game frame N. A time between two anchors maps linearly between their frames, outside them at 60
|
||||
frames a second from the nearest one; holds become frames at 60 a second (at least 1). --from-log: pad 1's script
|
||||
rebuilt from the logged changes themselves (each press at the frame it began in the calibration run, held as long),
|
||||
the closest to what the calibration run did. Without --log, seconds map to frames at 60 a second from frame 0
|
||||
(`--offset` frames added): for scripts already written in game time, such as the driving part of a match counted
|
||||
from its start.
|
||||
"""
|
||||
import argparse
|
||||
import bisect
|
||||
import re
|
||||
import sys
|
||||
|
||||
BUTTONS = {0x0080: 'LEFT', 0x0040: 'DOWN', 0x0020: 'RIGHT', 0x0010: 'UP', 0x0008: 'START', 0x0004: 'R3', 0x0002: 'L3',
|
||||
0x0001: 'SELECT', 0x8000: 'SQUARE', 0x4000: 'CROSS', 0x2000: 'CIRCLE', 0x1000: 'TRIANGLE', 0x0800: 'R1',
|
||||
0x0400: 'L1', 0x0200: 'R2', 0x0100: 'L2'}
|
||||
LOG_LINE = re.compile(r'\[pad\] frame (\d+) t=([0-9.]+): scripted ([0-9a-f]+)')
|
||||
|
||||
|
||||
def anchors_from(log_path):
|
||||
points = []
|
||||
with open(log_path, encoding='utf-8', errors='replace') as f:
|
||||
for line in f:
|
||||
m = LOG_LINE.search(line)
|
||||
if m:
|
||||
points.append((float(m.group(2)), int(m.group(1))))
|
||||
points.sort()
|
||||
return points
|
||||
|
||||
|
||||
def from_log(log_path):
|
||||
"""Pad 1's presses as the calibration run logged them: frame pressed, button, frames held."""
|
||||
presses, down, since = [], 0, {}
|
||||
with open(log_path, encoding='utf-8', errors='replace') as f:
|
||||
for line in f:
|
||||
m = LOG_LINE.search(line)
|
||||
if not m:
|
||||
continue
|
||||
frame, mask = int(m.group(1)), int(m.group(3), 16)
|
||||
for bit, name in BUTTONS.items():
|
||||
if mask & bit and not down & bit:
|
||||
since[bit] = frame
|
||||
elif down & bit and not mask & bit:
|
||||
presses.append((since[bit], name, max(1, frame - since[bit])))
|
||||
down = mask
|
||||
for bit, name in BUTTONS.items():
|
||||
if down & bit: # still held when the log ends: held to the end
|
||||
presses.append((since[bit], name, 1000000))
|
||||
presses.sort()
|
||||
return ','.join(f'{f}:{b}/{h}' for f, b, h in presses)
|
||||
|
||||
|
||||
def to_frame(seconds, anchors, offset):
|
||||
if not anchors:
|
||||
return offset + round(seconds * 60.0)
|
||||
times = [t for t, _ in anchors]
|
||||
i = bisect.bisect_right(times, seconds)
|
||||
if i == 0:
|
||||
t, f = anchors[0]
|
||||
return max(0, f - round((t - seconds) * 60.0))
|
||||
if i == len(anchors):
|
||||
t, f = anchors[-1]
|
||||
return f + round((seconds - t) * 60.0)
|
||||
(t0, f0), (t1, f1) = anchors[i - 1], anchors[i]
|
||||
if t1 == t0:
|
||||
return f0
|
||||
return round(f0 + (f1 - f0) * (seconds - t0) / (t1 - t0))
|
||||
|
||||
|
||||
def convert(script, anchors, offset):
|
||||
out = []
|
||||
for entry in filter(None, (e.strip() for e in script.replace('\n', ',').split(','))):
|
||||
when, _, press = entry.partition(':')
|
||||
button, _, held = press.partition('/')
|
||||
frames = max(1, round(float(held) * 60.0 / 1000.0)) if held else 30
|
||||
out.append((to_frame(float(when), anchors, offset), button, frames))
|
||||
out.sort()
|
||||
return ','.join(f'{f}:{b}/{h}' for f, b, h in out)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument('script', nargs='?', default=None)
|
||||
parser.add_argument('--script-file')
|
||||
parser.add_argument('--log', help="a calibration run's log (PS2X_PAD_LOG=1 lines)")
|
||||
parser.add_argument('--from-log', action='store_true', help="pad 1's script from the logged changes")
|
||||
parser.add_argument('--offset', type=int, default=0, help='frames added (without --log)')
|
||||
args = parser.parse_args()
|
||||
if args.from_log:
|
||||
if not args.log:
|
||||
parser.error('--from-log needs --log')
|
||||
print(from_log(args.log))
|
||||
return 0
|
||||
script = open(args.script_file).read() if args.script_file else args.script
|
||||
if not script:
|
||||
parser.error('no script')
|
||||
anchors = anchors_from(args.log) if args.log else []
|
||||
print(convert(script, anchors, args.offset))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -11,7 +11,8 @@ What it reads:
|
||||
- the NGP files (LVL/*.NGP, SHELL/*.NGP: a zip entry, "IE" instead of "PK", raw deflate after the local header;
|
||||
ACAR/PCAR car files: raw). Each is a memory image linked at EE 0x980000: a pointer is (value - 0x980000) in the file.
|
||||
The .PTR file next to it lists the pointer words (its first count, then their byte offsets); a hierobject is a node
|
||||
of type 0 (word 0 bits 0-5) whose +4 (a listed pointer) is its own prebuilt packet, at obj + 0x70 + 0x30 * ntex.
|
||||
of type 0 (word 0 bits 0-5) whose +4 (a listed pointer) is its own prebuilt packet, at obj + 0x70 + 0x30 * ntex
|
||||
or a little after it, zeros between (LOOP pads some packets to an alignment).
|
||||
- the hierobject: +8 u64 flags (VU1 program choice), +0x10 bounding sphere, +0x50 u16[5] texture numbers (the file's
|
||||
own, before the game adds the file's texture base), +0x5a ntex, +0x64 skeleton (0 = rigid).
|
||||
- its packet: DMA tags (REF: data elsewhere in the file, next tag after it; CNT / RET: data after the tag, RET ends;
|
||||
@@ -104,18 +105,27 @@ def load_pointers(path):
|
||||
|
||||
|
||||
def find_objects(image, pointers):
|
||||
"""Every hierobject: a type 0 node whose listed +4 pointer is its own packet."""
|
||||
"""Every hierobject: a type 0 node whose listed +4 pointer is its own packet: right after its texture blocks, or up
|
||||
to 0x100 bytes later with only zeros between (an aligned packet: LOOP's)."""
|
||||
found = []
|
||||
for slot in pointers:
|
||||
obj = slot - 4
|
||||
if obj < 0 or obj + 0x70 > len(image) or u32(image, obj) & 0x3f:
|
||||
continue
|
||||
ntex = u16(image, obj + 0x5a)
|
||||
if ntex <= 5 and u32(image, obj + 4) - LINK == obj + 0x70 + 0x30 * ntex:
|
||||
if ntex > 5:
|
||||
continue
|
||||
after, packet = obj + 0x70 + 0x30 * ntex, u32(image, obj + 4) - LINK
|
||||
if packet == after or (after < packet < after + 0x100 and packet % 16 == 0 and not any(image[after:packet])):
|
||||
found.append(obj)
|
||||
return sorted(set(found))
|
||||
|
||||
|
||||
def packet_start(image, obj):
|
||||
"""Where an object's packet is: its +4 pointer (find_objects checked it)."""
|
||||
return u32(image, obj + 4) - LINK
|
||||
|
||||
|
||||
def packet_segments(image, start):
|
||||
"""The DMA chain from start: [(VIF bytes, their offset in the image)] (the tag's two VIF codes first)."""
|
||||
return dma_chain(image, start, LINK)
|
||||
@@ -129,7 +139,7 @@ def packet_stream(image, obj):
|
||||
|
||||
def packet_stream_mapped(image, obj):
|
||||
"""The same, with where each piece of it is in the image: (stream, [(stream offset, image offset, length)])."""
|
||||
return chain_stream(image, obj + 0x70 + 0x30 * u16(image, obj + 0x5a), LINK)
|
||||
return chain_stream(image, packet_start(image, obj), LINK)
|
||||
|
||||
|
||||
class Strip:
|
||||
|
||||