52 Commits
Author SHA1 Message Date
Thomas MartinandClaude Opus 5.5 fb17ea2508 Engine fetch: the unpacked release's files dated now
cmake/bozo_engine_fetch.cmake unpacked the pinned BozoEngine release with the
archive's own file dates, older than objects already built. After a pin bump
Ninja then kept port objects compiled against the previous release's headers
(found in Shinobido_WOTN_Recomp, 0.7.0 -> 0.7.3: shino_gs_state.cpp and
shino_render.cpp stayed on the old renderer.h, the picture lost its objects and
HUD while the game state was identical). Every unpacked file is now touched.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-01 12:31:23 +01:00
boubou666 c00c238331 Merge pull request #127 from TheBozos/claude/checklist-0.7.3
Release checklist: v0.7.3
2026-12-01 01:56:22 +01:00
Thomas MartinandClaude Opus 5.5 14027a5026 Release checklist: v0.7.3
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-01 01:55:27 +01:00
boubou666 2e37b81b0d Merge pull request #126 from TheBozos/claude/release-0.7.3
Changelog: 0.7.3
2026-12-01 01:21:18 +01:00
Thomas MartinandClaude Opus 5.5 13a63bcafd Changelog: 0.7.3
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-01 01:20:28 +01:00
boubou666 3f6623f47e Merge pull request #125 from TheBozos/claude/recomplauncher
Support RecompLauncher: ship recomplauncher.json
2026-12-01 01:19:01 +01:00
Thomas MartinandClaude Opus 5.5 f0806c5ef0 Support RecompLauncher: ship recomplauncher.json
Releases carry RecompLauncher's manifest at the zip's top: the USA disc
check (Redump's dump), prepare with the release's own build (--progress-lines,
--disc optional for keeps_copy), start with PS2X_USER_DIR in {data}, the
video settings and the memory cards. As in DC_Recomp#67.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-01 01:12:45 +01:00
boubou666 6db6a16b0d Merge pull request #124 from TheBozos/claude/checklist-0.7.2
Release checklist: v0.7.2
2026-11-30 22:37:16 +01:00
Thomas MartinandClaude Opus 5.5 7ccc02b050 Release checklist: v0.7.2
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 22:36:22 +01:00
boubou666 8d808aaf2a Merge pull request #123 from TheBozos/claude/release-0.7.2
Changelog: 0.7.2
2026-11-30 19:49:04 +01:00
Thomas MartinandClaude Opus 5.5 06d323c49d Changelog: 0.7.2
BozoEngine from its releases (#121) and BozoEngine 0.6.0 (#122).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 19:48:14 +01:00
boubou666 80ba27ab07 Merge pull request #122 from TheBozos/claude/engine-0.6.0
BozoEngine 0.6.0
2026-11-30 19:33:44 +01:00
Thomas MartinandClaude Opus 5.5 254f994459 BozoEngine 0.6.0
The pin moves from 0.4.0 to 0.6.0: Amplitude's sound held to the host's time without clicks (#164), the render scale
over 1 averaged (#168), SPU2 output IRQs (#165), the movie library's work-area entries (#161), the disc stream (#167),
ReferSemaStatus (#166), sceSifGetOtherData (#170) and other ports' opt-in answers (#150, #160, #169).

Checked against v0.7.1 (0.4.0), same kit: the 1P route (9,500 frames, with sound) and the 4P route (8,500) give
identical records on every field and frame, and the 1P WAV is byte-identical; the 11 native test suites pass; a hidden
window run of the 1P route at render scale 2 plays through with fewer dropped sound frames (1,463 vs 3,238) and
underruns (9 vs 11).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 19:32:31 +01:00
boubou666 f620ab163b Merge pull request #121 from TheBozos/claude/engine-release-pin
Build on BozoEngine's releases instead of the submodule
2026-11-30 19:11:13 +01:00
Thomas MartinandClaude Opus 5.5 ce069120c1 Build on BozoEngine's releases instead of the submodule
cmake/bozo_engine.json pins a BozoEngine release by version and SHA-256 (0.4.0, the same source as the b29bc39
submodule pin minus reference/), and cmake/bozo_engine_fetch.cmake downloads, checks and unpacks it into
BozoEngine/ (ignored) when its .release stamp does not match: the scheme SoulCaliburIII_Recomp uses. cmake/bozo.cmake
and launcher/CMakeLists.txt include it unless given another tree; tmb_build runs it in a git checkout; make_release
fetches it into the release's source/BozoEngine, so a player's build stays offline, and release.ini stamps
engine_version. The release workflow fetches it after checkout (the kit reads the engine's library pins). The
submodule and .gitmodules are removed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 19:00:25 +01:00
boubou666 b84fefaf95 Merge pull request #120 from TheBozos/claude/release-0.7.1-checklist
Release checklist: v0.7.1's checks
2026-11-30 18:33:02 +01:00
Thomas MartinandClaude Opus 5.5 159d4a5de3 Release checklist: v0.7.1's checks
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 18:32:06 +01:00
boubou666 979544ce35 Merge pull request #119 from TheBozos/claude/release-0.7.1
Changelog: 0.7.1
2026-11-30 17:48:08 +01:00
Thomas MartinandClaude Opus 5.5 7f3a59ce5b Changelog: 0.7.1
The release zip file-time fix (#118). Adds the missing 0.7.0 and 0.7.1 compare links.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 17:47:02 +01:00
boubou666 d1e53a845c Merge pull request #118 from TheBozos/claude/settle-source-times
tmb_build: settle source and kit times before configuring
2026-11-30 17:45:53 +01:00
Thomas MartinandClaude Opus 5.5 8dbb7b0c23 tmb_build: settle source and kit times before configuring
A release zip dates every file at its commit's time, which an unzip reads as local time: west of UTC the files are
in the future and ninja loops ("manifest 'build.ninja' still dirty after 100 tries"), and an update unzipped over a
newer build can leave a changed file uncompiled. Ported from DC_Recomp's settle_source_times (DC_Recomp#60, 0.5.2):
the kit's future times are clamped to now, and the release source and kit/deps keep a size+time+SHA-1 record in
<out>/source_times.json so changed or new files are dated now and unchanged ones keep their time. A git checkout is
left alone. With the tests from DC's suite.

Checked end to end: the v0.7.0 player zip dated +3 h loops as shipped and passes Prepare's tools step fixed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 17:21:09 +01:00
boubou666 09e8c8b45f Merge pull request #117 from TheBozos/claude/release-0.7.0-checklist
Release checklist: v0.7.0's checks
2026-11-27 10:47:10 +01:00
Thomas MartinandClaude Opus 5.5 6e27203fcc Release checklist: v0.7.0's checks
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 10:46:18 +01:00
boubou666 894a16a651 Merge pull request #116 from TheBozos/claude/release-0.7.0
Changelog: 0.7.0
2026-11-27 10:22:16 +01:00
Thomas MartinandClaude Opus 5.5 9cea4513b1 Changelog: 0.7.0
Save states (#106), PC SETTINGS in the Options screen and the pause menu,
QUIT GAME, widescreen with its HUD and dialogs, and the quit-music fix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 10:10:25 +01:00
boubou666 38ff9f8ea3 Merge pull request #115 from TheBozos/claude/engine-snd-unload
Quitting a match no longer leaves its music over the menus
2026-11-27 02:56:35 +01:00
Thomas MartinandClaude Opus 5.5 d003ced242 Quitting a match no longer leaves its music over the menus (BozoEngine b29bc39)
BozoEngine at master b29bc39: #159, the 989SND driver stops a bank's
sounds still playing when the game unloads it (quitting a match from the
pause unloads the level's banks without a StopAllSounds, and the match's
music, played from its bank, went on over the menus), with the other
ports' merges since e2dff55 (#155-#158).

Checked: a headless quit from the pause, sound recorded: after the quit
the mean level goes from 4207 (match music over the menu's) to 2136 (the
menu's own); the 11 native suites pass; the 1P and 4P replays match main on
every recorded field, RAM image and sound; the pinned boot and match1p
checks match.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 02:55:32 +01:00
boubou666 6043791a00 Merge pull request #114 from TheBozos/claude/widescreen-hud
Widescreen: dialogs centred at 4:3, HUD at the 16:9 edges
2026-11-27 02:17:44 +01:00
Thomas MartinandClaude Opus 5.5 dbb8c73b23 Widescreen: the HUD at the 16:9 edges
The match HUD's two clusters are hier meshes on coordinate systems the game
hangs in front of the camera each frame (Hud::updateHUDPosition 0x13CC90:
the view's matrix, its translation plus the cluster's camera-space offset,
Hud + 0x810 the radar's, + 0x820 the weapon's; x right, y the depth). Seen
through the same focal length they kept their 4:3 places. With the views
wide, each cluster's x goes out by the width gained on its side,
(w - 640) / 2 * y / D (D the views' focal length, viewFovH), for the call,
and is put back after it, so a narrowed view finds the game's values. The
radar's centre and blips follow (computed in the same call); the markers
and bars over the cars are the world's.

The game reaches Hud::updateHUDPosition and Hud::Update by a jump from
TheGame::HudUpdateHUDPosition (0x15BD20) and TheGame::HudUpdate
(0x15BD40), so those are the ones overridden (a jump does not reach an
override). The HUD text Hud::Update draws from a 640 layout through
fontSpritePrintXY / CenteredXY (the ammo count and KILLS on the right,
DEMO in the middle) goes with its cluster: x past 400 by the width gained,
past 240 by half of it.

Checked: the 11 native suites pass; the 1P and 4P replays match main on
every recorded field, RAM image and sound; the pinned boot and match1p
checks match. Hidden window runs with widescreen on: the radar, name and
health at the top left, the weapon panel, its ammo count, energy and lives
at the bottom right, in the single view and the rear-view layout; the
markers over the cars on them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 02:16:41 +01:00
Thomas MartinandClaude Opus 5.5 de1f627801 Widescreen: the dialogs over a match shown 4:3 and centred
The dialogs over a match (displayDialog 0x163500: the pause, the results,
won and lost) lay their text and darkening out for a 640-wide view (centred
at x 320 from the view's left edge, the darkening band 640 wide). With one
player the pause kept the match's widened view, so its menu sat left of
centre in a 16:9 picture.

displayDialog's override now narrows every widened viewport back to 640 and
rebuilds the views (viewTweakSetFov) before the game's dialog; the picture
is 4:3 while it shows, and the match's next frame end widens the views
again. Every widened viewport is remembered, not only those shown: the
pause's full-screen view (viewport 0x4DEF80) is handed out again by
viewCreate while still 853 wide from earlier in the match.

Checked in hidden window runs with widescreen on: the 1P pause menu and its
PC SETTINGS pages centred at 4:3, the match back at 16:9 after Start.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 01:40:04 +01:00
boubou666 ad371920d7 Merge pull request #113 from TheBozos/claude/pause-pc-settings
PC SETTINGS in the pause menu
2026-11-27 01:16:49 +01:00
Thomas MartinandClaude Opus 5.5 5531425daf PC SETTINGS in the pause menu
The in-match pause (displayDialog types 0 and 16, its page
pauseLevelOverlay 0x166960 in the dialog's own loop) gets a PC SETTINGS line
under RESUME, QUIT, SET VIBRATION and ADJUST REAR VIEW (under SET
VIBRATION with several players), opening the same pages (Video, Cheats,
Save states, QUIT GAME) drawn in the pause's style:
- getCurrentMenuSelection (0x167AF8), for the pause's call (return
  0x166AE4): the count one more, so the cursor reaches the new line (the
  wrap uses the count itself).
- checkInputForPauseExit (0x167670, return 0x166D64): Cross on that line
  opens the pages and the pause stays (returns 0), instead of the game's
  hidden TWEAK action at that index closing it.
- pauseLevelOverlay: after the game's menu, the line through setMenuFont
  (highlighted as the game's lines) and fontSpritePrintCenteredXY; while
  the pages are open, the pages instead (returns 0, the dialog goes on).
  Their input is the pausing player's pad (inputGetPlayerPad of
  gPlayerThatPaused, inputGetInput in uiGetInput's order), their sounds the
  pause's (playRTShellSound 0x2A / 0x2B / 0x2C), their fonts the pause's
  (setTitleFont; setMenuFont's sizes 0x12 / 0x10 and colours). A new pause
  starts on the game's menu.
- tmb_2d.cpp: displayDialog's darkening is left out under the pages.

runPage serves both: the Options screen's input (uiGetInput's flags),
sounds and sub-pixel fonts, or the pause's.

Checked: the 11 native suites pass; the 1P and 4P replays match main
89d5306 on every recorded field, RAM image and sound; the pinned boot and
match1p checks match. A hidden window run in a 1P match: paused, Up onto
PC SETTINGS, Cross to the pages, Video and Cheats pages, Triangle back to
the pause menu, Start resumed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 01:12:43 +01:00
boubou666 56e2f2e932 Merge pull request #112 from TheBozos/claude/quit-and-widescreen
Widescreen in 1P/2P matches, and QUIT GAME in PC SETTINGS
2026-11-27 00:50:46 +01:00
Thomas MartinandClaude Opus 5.5 3b05396300 Widescreen in 1P/2P matches, and QUIT GAME in PC SETTINGS
Widescreen (runtime/tmb_widescreen.cpp; off by default: Video's
Widescreen in F2 or PC SETTINGS, video.ini `widescreen`, PS2X_WIDESCREEN):
at each match frame's end, when every view is the screen's full width (one
player, or two one above the other), each view's width goes from 640 to
853 about the same centre and the game's own viewTweakSetFov (0x1FDEA0)
rebuilds its frustum planes and projection from it, on a copy of the
context. The game then culls, projects and clips a scene 4/3 as wide with
the same focal length: more at the sides, nothing stretched. The 3D screen
(tmb_native.cpp) and the 2D overlay follow the views' width, so the HUD
keeps its shape; the window shows 16:9 (BozoEngine's setPictureAspect)
while a view is wide. The menus, the pause dialog and the next level make
their views again at 640 (viewCreate), so they stay 4:3; three- and
four-player splits stay 4:3; the loading bar and movie pictures are drawn
centred.

QUIT GAME at the bottom of PC SETTINGS' first page: Cross shows "PRESS X
AGAIN", a second Cross ends the game (the host's stop; the window closes),
Back or a move disarms it.

BozoEngine at master e2dff55 (#154: video::Settings::widescreen,
offerWidescreen, setPictureAspect; #153 libmpeg's demux in runs).

Checked: the 11 native suites pass; the 1P (9,500) and 4P (8,500) replays
match main 89d5306 on every recorded field, RAM image and sound; the
pinned boot and match1p checks match. Hidden window runs with widescreen
on: 1P matches at 16:9 (cars, rain and target markers to the edges, the
radar round), the menus 4:3, a 4P split 4:3, the pause screen as without
it; QUIT GAME ended the game at the second Cross.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 00:36:29 +01:00
boubou666 2a7eff7a3a Merge pull request #111 from TheBozos/claude/pc-settings-menu
PC SETTINGS in the game's Options screen: video, cheats and save states with the pad
2026-11-26 21:24:04 +01:00
Thomas MartinandClaude Opus 5.5 de7bfb32aa PC SETTINGS in the game's Options screen: video, cheats and save states with the pad
A ninth line under the game's Options (after SAVE SETTINGS TO MEMORY CARD)
opens pages drawn with the game's own font and steered with the pad:
- Video: display mode, resolution, render scale, frame rate, anti-aliasing,
  texture smoothing, upscaling and its filter, texture pack, pause in
  background, fast forward; APPLY AND SAVE posts them to the window and
  writes video.ini (bozo::app::video::post).
- Cheats: unlock everything, infinite health / ammo / energy (off, player 1,
  all players), no AI, weak enemies; at once (tmb::cheats::values /
  setValues, the F2 tab's switches).
- Save states: the slot, LOAD, SAVE (the host's requests, the slot's
  picture through BozoEngine's captureStatePicture, as F5 / F7).
Triangle or Circle goes back; the controls stay in F2.

runtime/tmb_menu.cpp, from the game's code (uiOptions 0x1911F0):
- uiGetInput's override (for the Options page's call, 0x19128C) lets the
  cursor (options_main_line) reach 8: every other use of the cursor is a
  compare, so 8 selects none of the game's lines. Cross there opens the
  pages instead of the game's accept-and-leave.
- uiOptions' override draws the line after the game's page and, while the
  pages are open, draws them instead (the 3D shell stays the game's, its
  sliders hidden by blankSliders as the controls page does).
- The game's font, sound and input functions run on a copy of the context
  (BozoEngine kernel.md section 3b): guest code there never leaves the
  override. Calling them on the thread's context let fontSpritePrint leave
  at a checkpoint and return later into uiMain on the pages' stack.
- Only where the graphics are native (every free run); a save state's load
  closes the pages.

BozoEngine at master 5d34d41 (#151's captureStatePicture, with the other
ports' merges since f93b5af).

Checked: the 11 native suites pass; the 1P (9,500) and 4P (8,500) replays
match main 89d5306 on every recorded field, RAM image and sound, before and
after the engine move; the pinned boot and match1p checks match (match1p
16000/16000 frames). Hidden window runs: the line, Up from DIFFICULTY onto
it and Down off it, each page, render scale applied and saved, slot 0
saved (state and picture) and loaded, and 8,100 frames on the Video page
without a fault.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 21:22:56 +01:00
boubou666 89d530697c Merge pull request #110 from TheBozos/claude/no-lives-left-wording
Wording: the "No lives left" screen, not an attract demo; BozoEngine at f93b5af
2026-11-24 11:31:46 +01:00
Thomas MartinandClaude Opus 5.5 28159632e2 BozoEngine at master f93b5af (#137 merged: the readbacks' wording)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 11:24:43 +01:00
Thomas MartinandClaude Opus 5.5 c821465d6a Wording: the checker's flares note names the "No lives left" screen, not an attract demo
Frames 13736 on in match1p are the game-over screen after the 1P match
(tmb-check's hidden captures at 13740 and 15900). Comment only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 11:21:39 +01:00
boubou666 a0d9386896 Merge pull request #109 from TheBozos/claude/match1p-check
Pinned match1p passes again: the checker's particles by game frame
2026-11-24 11:16:52 +01:00
Thomas MartinandClaude Opus 5.5 0aedf924ed BozoEngine at master 822e8ef (#136 merged; same tree as 0b961a4)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 11:15:21 +01:00
Thomas MartinandClaude Opus 5.5 e1797b1315 Pinned match1p passes again: the checker's particles by game frame
tmb-check's particleDraw chose TMB's path or the game's by host time
(effectsInStream: a match or menu frame within 0.1 s), and the lens flares'
native path no longer needed a match (889b086). The reference (TMB a7869c0,
paced at 60 fps) drew all 13,716 particleDraws itself from frame 5593 and
left the flares to the game from 13736, six frames after the last match
frame (13729), with the attract demo's GS readbacks. So the check stopped at
5593, 13731 or 13737 by the host's speed, and at 13736 on the readback.

Without native graphics (only the checker; every free run has them) the
same choices by game frame: particles within 6 frames of a match or menu
frame's end, flares natively within 6 of a match frame's (checkedEffects,
checkedFlares). Free runs are unchanged. BozoEngine at 0b961a4 answers the
readback as the reference's stub in its log host.

match1p --pinned: 16000/16000 frames, 74,615,923 records, 0 divergences;
draws 15999/16000 (the log's last frame, as before).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 11:04:14 +01:00
boubou666 ccd52e8401 Merge pull request #108 from TheBozos/claude/pinned-boot-hidden
Pinned boot check passes again (BozoEngine 5b830b6); hidden pinned captures
2026-11-24 00:21:57 +01:00
Thomas MartinandClaude Opus 5.5 ae2ac42953 BozoEngine at master 5b830b6: the pinned boot check passes again
BozoEngine #132: sceGsResetGraph's display mode kept in the library. tmb-check on boot.clg diverged at frame 4
(sceGsSetDefDispEnv read the mode back from scratchpad 0x100, which the game reuses); it now matches all 3000 frames
and 4,650,558 records, and runs hidden with its captures (tmb-check --window --hidden). The game's display
environments now hold the reference's SMODE2 / DISPLAY; sound, calls, draws and threads unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 00:20:49 +01:00
boubou666 153336ae0c Merge pull request #107 from TheBozos/claude/hidden-window-captures
Hidden, muted test runs on BozoEngine master; native suites on the engine's float shortcuts
2026-11-23 23:15:18 +01:00
Thomas MartinandClaude Opus 5.5 b1aa812ed7 BozoEngine at master e15775a (#131 merged; same tree as 7521b3e)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 23:13:46 +01:00
Thomas MartinandClaude Opus 5.5 cd5262a7a0 Hidden test runs: tmb-check --window --hidden; the native suites on engine master's float shortcuts
- BozoEngine at claude/ps2f-mul-min-normal (7521b3e, BozoEngine #131 on master 3222624): hidden windows, and the
  fix for products that rounded up to the smallest normals in ps2f's and VU0's host shortcuts.
- tmb-check --window --hidden: the pinned pixel captures without showing the window (the offscreen picture).
- README: --hidden, --capture-scene; --no-sound keeps --wav.
- Native suites (tests/host_control.h): engine master's ps2f and VU0 shortcuts use the host's arithmetic, exact only
  when the host rounds to nearest (the game's word) and leaving SSE's sticky status flags. The original now runs at
  the caller's word rounding to nearest, native code still at the varied caller word (generated callers on both sides
  at nearest), and the control word is compared without the status flags.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 23:02:21 +01:00
Thomas MartinandClaude Opus 5.5 4eddae4fa3 WIP: hidden-window test runs (--hidden, --capture-scene) on BozoEngine master 3222624
Not qualified yet: the bumped engine's 1P/4P headless replays and a 4P save-state
round trip match; the hidden window routes ran (the 4P one paced slowly, to recheck).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 20:26:03 +01:00
boubou666 fb17656603 Merge pull request #106 from TheBozos/claude/save-states
Save states: F5/F7 slots, --save-state / --load-state, 989SND saved
2026-11-18 19:59:32 +01:00
Thomas MartinandClaude Opus 5.5 a67b0cd9fe Save states: TMB's section, command-line options and window slots
TMB adds its own part to BozoEngine's save states (runtime/tmb_state.cpp):
- the overrides' frame pacing (the parity written to the game's memory, the
  field carry and clock debt) and movie sound queue;
- the native hierarchy's retained scene records;
- the NGP files the game bound, saved as bound, and the DMA marks' counter;
- what the game told the texture hooks once (files read per address, the
  level's lists, VRAM placements), with pack records as (file, index);
- the particles' stripe and arc records, and the cheats' opened lock words.

Decoded textures, the skid marks' object and the 2D pictures are dropped on a
load.

Options: --save-state FILE --save-state-at N, --load-state FILE
[--load-state-at N], and tmb-headless --dump-ram FILE. In the window: F5 save,
F7 load, F6 / Shift+F6 slots, and the F2 Save states tab.

BozoEngine moves to the save-state work with the 989SND driver saved
(unloaded banks kept: their headers were read after being freed).

Checked headless, for a menu state and 1P/4P match states loaded in a new
process and mid-run: the end-of-route EE RAM and the sound after the save are
identical to the run that never stopped. The default 1P/4P replays match the
previous build on every recorded field.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 19:58:16 +01:00
boubou666 a58a702260 Merge pull request #105 from TheBozos/claude/release-0.6.0-checklist
Record the 0.6.0 release verification in the checklist
2026-11-11 13:22:25 +01:00
Thomas MartinandClaude Opus 5.5 8d971a3f3d Record the 0.6.0 release verification in the checklist
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 13:21:06 +01:00
47 changed files with 6777 additions and 4315 deletions

No files matched your search

+2
View File
@@ -13,6 +13,8 @@ jobs:
- uses: actions/setup-python@v5
with:
python-version: '3.14'
- name: The BozoEngine release cmake/bozo_engine.json pins (the RecompLauncher settings check reads it)
run: cmake -P cmake/bozo_engine_fetch.cmake
- name: Release, migration and timing checks
run: python -m unittest discover -s tests -v
- name: Python syntax
+4 -2
View File
@@ -80,13 +80,15 @@ jobs:
fi
echo "WORK=$(cygpath -m "$RUNNER_TEMP")/tmb" >> "$GITHUB_ENV"
- name: Check out the tag or the branch (and the BozoEngine submodule at its recorded commit)
- name: Check out the tag or the branch
uses: actions/checkout@v4
with:
ref: ${{ env.TAG != '' && format('refs/tags/{0}', env.TAG) || '' }}
submodules: true
persist-credentials: false
- name: The BozoEngine release cmake/bozo_engine.json pins (SHA-256 checked; the kit reads its library pins)
run: cmake -P cmake/bozo_engine_fetch.cmake
- name: Python
uses: actions/setup-python@v5
with:
+4
View File
@@ -17,6 +17,10 @@ SLUS_*
*.irx
*.IMG
# The BozoEngine release cmake/bozo_engine.json pins (cmake/bozo_engine_fetch.cmake)
/BozoEngine/
/.BozoEngine-unpack/
# Local build trees
build/
out/
-3
View File
@@ -1,3 +0,0 @@
[submodule "BozoEngine"]
path = BozoEngine
url = https://github.com/TheBozos/BozoEngine.git
Submodule BozoEngine deleted from a36a4d23f2.
+74 -1
View File
@@ -7,6 +7,75 @@ under "Unreleased" as they land, then move them under the new version's heading
## [Unreleased]
## [0.7.3] - 2026-12-01
### Added
- **RecompLauncher support.** Releases carry a `recomplauncher.json`, so [RecompLauncher](https://recomplauncher.com)
can install TMB_Recomp, check the disc against the USA dump, prepare the game with the release's own build, start
it, show the video settings (display mode, widescreen, frame rate, render scale, anti-aliasing, texture smoothing)
on the game's page and back up the memory cards. A game set up there keeps its saves, settings and logs in its
`recompdata` folder.
- Preparing again without a disc image uses the one the earlier preparation kept in the game folder, so an update can
be built after the original image was deleted.
## [0.7.2] - 2026-11-30
### Changed
- **BozoEngine comes from its releases instead of a git submodule.** `cmake/bozo_engine.json` pins a release by
version and SHA-256 (0.4.0, the same code as the commit pinned before), and configuring fetches it into
`BozoEngine/` (`cmake/bozo_engine_fetch.cmake`, the scheme SoulCaliburIII_Recomp uses). A player's release still
ships the engine's source in `source\BozoEngine` and builds offline; `release.ini` now stamps `engine_version`. To
work on the engine and TMB together, point `BOZO_ENGINE_DIR` (or `tmb_build.py --engine`) at a BozoEngine checkout.
- **BozoEngine 0.6.0** (from 0.4.0). In the window, the sound is held to the real time without clicks (engine PR #164),
and a render scale over 1 averages the pixels under each window pixel instead of picking one (#168). The rest
(SPU2 output interrupts, the movie library's work-area layout, the disc stream, ReferSemaStatus,
sceSifGetOtherData and opt-in library answers for other ports) leaves TMB's runs unchanged: the 1P and 4P replay
routes give the same record on every frame.
## [0.7.1] - 2026-11-30
### Fixed
- **A release unzipped by hand no longer trips the build on its file times.** The zip dates every file at its
commit's time, which an unzip reads as local time: west of UTC, within hours of a release, the files were in the
future and Prepare stopped with ninja's "manifest 'build.ninja' still dirty after 100 tries"; and an update unzipped
over a game built after its commit could leave a changed file uncompiled. `tools/tmb_build.py` now settles the times
before configuring: nothing in the source or the kit stays in the future, and with a record of each source and kit
dependency file (`<work folder>/source_times.json`) a changed or new file is dated now and an unchanged one keeps its
old time. A git checkout is left alone; the launcher's Update was not affected.
## [0.7.0] - 2026-11-27
### Added
- **Save states.** F5 saves and F7 loads the current slot, F6 / Shift+F6 pick the slot (0 to 9), and F2 has a
**Save states** tab listing them with a picture of each. They go to `states/slot<n>.state` in the user folder (about
40 MB each). A state loads only into the build that wrote it, and a save waits while a movie plays. For scripted
runs: `--save-state FILE --save-state-at N` and `--load-state FILE`.
- **PC SETTINGS in the game's own Options screen.** A ninth line under SAVE SETTINGS TO MEMORY CARD opens pages
drawn in the game's font and steered with the pad: **Video** (display mode, resolution, render scale, frame rate,
anti-aliasing, texture smoothing, upscaling and its filter, texture pack, pause in background, fast forward; APPLY
AND SAVE writes `video.ini`), **Cheats** (unlock everything, infinite health / ammo / energy, no AI, weak enemies;
at once) and **Save states** (the slot, LOAD, SAVE, as F5 / F7). Triangle or Circle goes back. The controls stay in
F2.
- **PC SETTINGS in the pause menu** too: a fifth line under RESUME, QUIT, SET VIBRATION and ADJUST REAR VIEW (a
fourth with several players) opens the same pages in the pause menu's style, on the pausing player's pad.
- **QUIT GAME** at the bottom of PC SETTINGS: Cross, then Cross again, ends the game and closes the window.
- **Widescreen (16:9)**, off by default: in F2's Video tab, PC SETTINGS → Video, or `widescreen = on` in `video.ini`
(`PS2X_WIDESCREEN=1`). In one-player and two-player matches the game draws a 16:9 picture: it shows more at the
sides (its own views made wider, culling and all), nothing is stretched, and the HUD keeps its shape. The menus,
movies and loading screens stay 4:3, centred, and three- and four-player split screens stay 4:3. The pause menu and
the other dialogs over a match (results, won, lost) are shown 4:3 and centred. The HUD goes to the 16:9 edges: the
radar, name and health to the left, the weapons, energy and lives to the right; the markers over the cars stay
on them.
### Fixed
- Quitting a match from the pause menu no longer leaves the match's music playing over the menus (BozoEngine's
989SND driver now stops a bank's sounds when the game unloads it).
## [0.6.0] - 2026-11-11
### Added
@@ -242,7 +311,11 @@ The first release. You build the game on your own PC from your own USA disc; not
- Technical: built from TMB_Recomp's code and the PS2Recomp fork (`native/renderer`) with the build kit's GCC 16.2,
FFmpeg 9.0.2 and Python 3.14; the default mode has no GS, VU or SPU2 emulation and no IOP hardware model.
[Unreleased]: https://github.com/TheBozos/TMB_Recomp/compare/v0.6.0...HEAD
[Unreleased]: https://github.com/TheBozos/TMB_Recomp/compare/v0.7.3...HEAD
[0.7.3]: https://github.com/TheBozos/TMB_Recomp/compare/v0.7.2...v0.7.3
[0.7.2]: https://github.com/TheBozos/TMB_Recomp/compare/v0.7.1...v0.7.2
[0.7.1]: https://github.com/TheBozos/TMB_Recomp/compare/v0.7.0...v0.7.1
[0.7.0]: https://github.com/TheBozos/TMB_Recomp/compare/v0.6.0...v0.7.0
[0.6.0]: https://github.com/TheBozos/TMB_Recomp/compare/v0.5.0...v0.6.0
[0.5.0]: https://github.com/TheBozos/TMB_Recomp/compare/v0.4.0...v0.5.0
[0.4.0]: https://github.com/TheBozos/TMB_Recomp/compare/v0.3.2...v0.4.0
+1 -1
View File
@@ -23,7 +23,7 @@ SOFTWARE.
---
This licence covers TMB_Recomp's own files. It does not cover:
- BozoEngine/ (the recompiler and runtime, a separate MIT project): see BozoEngine/LICENSE.
- BozoEngine/ (the recompiler and runtime, a separate MIT project, fetched from its releases): see BozoEngine/LICENSE.
- Anything from Twisted Metal: Black. No game data, code or art is in this repository or its releases;
players build the port from their own disc.
- Third-party components with their own licences (SDL3, Dear ImGui, the Exo 2 font, and the build
+36 -8
View File
@@ -50,6 +50,12 @@ remains available for comparison. The steps below describe the native packages.
graphics driver is needed. The game then uses them; turn them off there or in F2 → Video → Texture pack. Nothing is
downloaded or sent, and the result is yours alone: do not share it.
**RecompLauncher.** Releases carry a [`recomplauncher.json`](recomplauncher.json), so
[RecompLauncher](https://recomplauncher.com) can install TMB_Recomp, check your disc, prepare the game with the same
build, show the video settings on the game's page and back up the memory cards. A game set up there keeps its saves,
settings and logs in its own `recompdata` folder, not in `%APPDATA%\TMB_Recomp`: copy `mc0` across to bring saves
from TMB Launcher. Enhanced textures are made by TMB Launcher only.
Requires **Windows 10 version 1903 or newer / Windows 11, an AVX2 and FMA capable CPU, and OpenGL 3.3**.
Original heat haze around fire and explosions is enabled by default. `BOZO_HEAT_HAZE=0` disables it for comparisons
with the older PC port. Menus and movies use their native timing, independently of the presentation frame rate.
@@ -113,6 +119,9 @@ those comparisons from actual native play. [docs/RECOMP_NOTES.md](docs/RECOMP_NO
| Original heat haze enabled by default | ✅ |
| Multi-player split-screen, 2 to 4 players; frame-keyed scripts for unattended checks | ✅ |
| Settings (F2): controls, video, cheats; windowed / fullscreen / borderless | ✅ |
| PC SETTINGS in the game's Options screen and pause menu: video, cheats and save states with the pad | ✅ |
| Widescreen 16:9 in one- and two-player matches (more at the sides, HUD unstretched; menus stay 4:3) | ✅ |
| Save states (F5 save, F7 load, ten slots; `--save-state` / `--load-state` for scripted runs) | ✅ |
| Higher internal resolution (2× by default; Video's render scale) | ✅ |
| Interpolated presentation above 60 Hz; rain, snow, flares and some trails still update at game rate | 🧪 |
| Every Challenge arena rechecked on BozoEngine | 🔧 |
@@ -181,7 +190,10 @@ Your USA disc
The executable retains its symbols, so this port does not need a Ghidra function-map pass.
`runtime/tmb_overrides.cpp` contains game-specific bindings; `bozo/` contains the real-time host, headless host and
checker. Generic recompiler/runtime work lives in the [BozoEngine](https://github.com/TheBozos/BozoEngine) submodule.
checker. Generic recompiler/runtime work lives in [BozoEngine](https://github.com/TheBozos/BozoEngine): TMB builds on
one of its releases, pinned by version and SHA-256 in `cmake/bozo_engine.json` and fetched into `BozoEngine/` when
configuring (`cmake/bozo_engine_fetch.cmake`; a release's `source\BozoEngine` comes with it, so a player's build stays
offline).
Its [clean-room specifications and validation](https://github.com/TheBozos/BozoEngine/tree/main/docs) describe the engine.
PS2Recomp remains credited in the project's history and available in the v0.3.2 release, but is no longer a dependency.
@@ -202,10 +214,11 @@ The player package brings its own build tools. To build from the repository:
### One command, from your disc (Windows)
Clone the repository with its BozoEngine submodule, then use the same pipeline as the launcher:
Clone the repository, then use the same pipeline as the launcher (it fetches the pinned BozoEngine release into
`BozoEngine/` the first time; `cmake -P cmake/bozo_engine_fetch.cmake` does it alone):
```bat
git clone --recurse-submodules https://github.com/TheBozos/TMB_Recomp.git
git clone https://github.com/TheBozos/TMB_Recomp.git
cd TMB_Recomp
python tools\tmb_build.py --disc "D:\Discs\Twisted Metal - Black (USA).iso" --out D:\TMB-build --kit D:\tmb_kit_bozo\kit
"D:\TMB-build\TMB\Play TMB.cmd"
@@ -310,7 +323,8 @@ Follow [docs/RELEASE_CHECKLIST.md](docs/RELEASE_CHECKLIST.md) and include the co
Releases are built by `.github/workflows/release.yml` when the owner asks. An ordinary push does not publish one.
1. Move `CHANGELOG.md`'s Unreleased entries into `## [<version>] - <date>`, update its links, and merge through a PR
with green checks. Engine changes must already be public before updating the submodule pin.
with green checks. Engine changes must already be in a BozoEngine release before the pin moves: set its version and its
`.sha256` in `cmake/bozo_engine.json`.
2. Tag that merged commit (`v<version>`) and push the tag, or run the workflow against the already pushed tag.
3. The workflow checks the changelog, assembles the pinned kit, makes both player ZIPs and corresponding sources,
verifies hashes/contents and runs the bundled-toolchain/launcher checks, then creates a **draft** release.
@@ -347,7 +361,8 @@ cmake --build D:/TMB-dev -j 8
D:/TMB-dev/tmb.exe --iso "D:/Discs/Twisted Metal - Black (USA).iso"
```
`BOZO_ENGINE_DIR` selects another engine tree. `TMB_WINDOW=OFF` builds headless tools only.
`BOZO_ENGINE_DIR` selects another engine tree (a BozoEngine checkout, to work on the engine and TMB together;
`tools/tmb_build.py --engine <tree>` likewise); without it the pinned release is used. `TMB_WINDOW=OFF` builds headless tools only.
`BOZO_BUILD_TOOLS=OFF` removes the optional zlib-dependent recording/checking tools from a player build.
### Windows
@@ -400,12 +415,23 @@ use physical US positions:
| Key | What it does |
|---|---|
| F2 | Settings: Controls (per-player buttons, sticks, triggers, mouse and sensitivity), Video (resolution, window mode, render scale, presentation frame rate and texture upscaling), Cheats. Controls save to `input.ini`; video saves to `video.ini`. |
| F2 | Settings: Controls (per-player buttons, sticks, triggers, mouse and sensitivity), Video (resolution, window mode, render scale, presentation frame rate, texture upscaling and widescreen), Cheats. Controls save to `input.ini`; video saves to `video.ini`. |
| F3 | Toggle the frame-rate counter. |
| F5 / F7 | Save / load a save state in the current slot (`states/slot<n>.state` in the user folder). A state loads only into the build that wrote it; a save waits while a movie plays. |
| F6, Shift+F6 | Next / previous save-state slot (0-9); F2 → Save states lists them. |
| F11, Alt+Enter | Switch between the window and the last fullscreen mode. |
| F8 | Capture consecutive presents (the sequence settings below). |
| F9 | Start/stop a capture burst, ten captures per second. |
In the game, **Options → PC SETTINGS** (the last line, under the memory card lines), and **PC SETTINGS** in the pause
menu during a match, have the same Video, Cheats and Save states with the pad: Up / Down to choose, Left / Right to change, Cross to open or act (Video's APPLY AND SAVE,
Save states' LOAD and SAVE), Triangle or Circle to go back. The controls are rebound in F2. **QUIT GAME** at the
bottom of PC SETTINGS closes the game (press Cross twice).
**Widescreen** (Video: Widescreen, off by default; `widescreen = on` in `video.ini`, `PS2X_WIDESCREEN=1`): one- and
two-player matches are drawn 16:9, showing more at the sides with nothing stretched, the HUD at the screen's edges. Menus, movies, loading screens
and three- or four-player split screens stay 4:3.
The picture stays 4:3 inside the window. Video can present at game rate, a fixed higher rate, or the monitor's rate
with interpolation; the game itself keeps its 60 Hz timing. Interpolation adds about one game frame of latency and
remains experimental for effects that only update at game rate.
@@ -446,13 +472,15 @@ screen); the variables give their state at launch (`runtime/tmb_cheats.cpp`).
| `--pad-script [n=]<file>` | Frame-keyed scripted input for player n (1–4); repeat for multiple players |
| `--quit-after <frames>` | End an unattended windowed run |
| `--capture-dir <dir> --capture-frames n,n` | Capture chosen game frames |
| `--hidden` | Test run that never shows the window: captures read the game's offscreen picture (add `--no-sound` so nothing plays; `--wav` still records) |
| `--capture-scene` | Captures read the game's picture without overlays, in a shown window |
| `PS2X_CAPTURE_WINDOW_DIR=<dir>` | F8/F9 capture destination |
| `PS2X_CAPTURE_SEQUENCE=<n>`, `PS2X_CAPTURE_SEQUENCE_AT=<s>[,<s>...]` | Consecutive presents at F8 or the chosen times, with interpolation timing metadata |
| `PS2X_CAPTURE_BURST_AT=<s>[,<s>...]` | Start/stop an F9-style burst at the chosen times |
| `PS2X_CAPTURE_DIR=<dir>`, `PS2X_CAPTURE_INTERVAL=<s>` | Periodic picture captures |
| `--audio-stats`, `--audio-latency <ms>` | Audio queue/underrun diagnostics and queue target |
| `--wav <file>`, `PS2X_AUDIO_RECORD=<file>` | Record the native mixer output |
| `--no-sound` | Disable device playback for a diagnostic run |
| `--no-sound` | Disable device playback (test runs; `--wav` still records) |
| `PS2X_SETTINGS_OPEN=Controls\|Video\|Cheats` | Open F2 directly on a tab for UI tests |
| `PS2X_LOG_FILE=<file>\|0`, `PS2X_NO_DIALOGS=1`, `PS2X_TEST_CRASH=<s>` | Another log/none, suppress unattended dialogs, or intentionally test crash handling |
| `TMB_CHEATS_LOG=1`, `TMB_CHEATS_TOGGLE=<s>` | Cheat diagnostics and periodic switching for tests |
@@ -491,7 +519,7 @@ captures, generated game code and disc data are local-only and never release con
| Path | Contents |
|---|---|
| `BozoEngine/` | the native recompiler/runtime submodule (MIT) |
| `BozoEngine/` | the native recompiler/runtime (MIT): the release `cmake/bozo_engine.json` pins, fetched, not committed |
| `bozo/` | TMB's windowed host, headless host and recorded-run checker |
| `cmake/bozo.cmake` | the native game build and generated-code integration |
| `recomp/` | game-specific recompiler declarations |
+4 -1
View File
@@ -6,10 +6,11 @@
// --window (builds with TMB_WINDOW): the same pinned run, its frames shown in a window as they are made (BozoEngine's
// window, the renderer's present), to capture the pictures of chosen frames (milestone M5's pixel comparison):
// tmb-check <log.clg> ... --window --capture-frames n,n,... [--capture-dir dir] [--width w --height h]
// [--render-scale s] [--aspect a]
// [--render-scale s] [--aspect a] [--hidden]
// --capture-frames n: the picture once n frames have ended, i.e. the reference record n - 1's frame (frame_<n>.png). The
// run is held at that frame's end until the window has read it back, so the picture is exactly that frame's. The window
// is 640x448 at render scale 1 by default; --aspect is the picture's shape inside it (4:3 by default, letterboxed).
// --hidden: the window is never shown, and the captures read the game's offscreen picture (the same pixels).
#include "run_main.h"
#if TMB_CHECK_WINDOW
@@ -86,6 +87,8 @@ namespace
window.renderScale = std::stof(value());
else if (a == "--aspect")
window.aspect = std::stof(value());
else if (a == "--hidden")
window.hidden = true;
else
rest.push_back(args[k]);
}
+26 -2
View File
@@ -3,17 +3,21 @@
//
// tmb-headless [--frames n] [--elf SCUS_971.01] [--iso image] [--pad-script [n=]file]... [--card-dir dir]
// [--out run.ref] [--report n] [--quiet] [--wav file [--wav-frames a-b]] [--no-sound]
// [--save-state file --save-state-at n] [--load-state file [--load-state-at n]] [--dump-ram file]
//
// --pad-script n=file: player n's frame-keyed script (1 when omitted; players 2-4 are the multitap's slots, as the
// reference's PS2X_PAD2_SCRIPT..PS2X_PAD4_SCRIPT).
//
// --wav: the sound the mixer made (48 kHz stereo, 16-bit), from game frame a to b (all of it by default); --no-sound:
// the mixer is not brought up at the frames' ends (as before milestone M3).
// --save-state / --load-state: BozoEngine's save states (BozoEngine/docs/save-states.md): the whole run written when n
// frames have ended, or loaded before the first frame (or when n frames have ended). --dump-ram: EE RAM at the run's end.
// Every --report frames (500 by default) and at the end: the frame, the EE clock, the function that waited for the
// frame's end (the game's loop: uiTitle_Main__Fv at the title), the Shell (the menus' object, gp - 0x4148) and the
// overrides that ran.
#include "tmb_host.h"
#include "tmb_port.h"
#include "tmb_state.h"
#include "bozo/app/determinism.h"
#include "bozo/audio/wav.h"
@@ -39,7 +43,7 @@ int main(int argc, char **argv)
bozo::host::FreeOptions opt;
opt.elf = BOZO_RUN_DEFAULT_ELF;
uint64_t report = 500;
std::string wavPath;
std::string wavPath, dumpRam;
uint64_t wavFrom = 0, wavTo = UINT64_MAX;
for (int k = 1; k < argc; ++k)
{
@@ -84,10 +88,21 @@ int main(int argc, char **argv)
}
else if (a == "--no-sound")
opt.sound = false;
else if (a == "--save-state")
opt.saveState = value();
else if (a == "--save-state-at")
opt.saveStateFrame = static_cast<uint32_t>(std::stoull(value()));
else if (a == "--load-state")
opt.loadState = value();
else if (a == "--load-state-at")
opt.loadStateFrame = static_cast<uint32_t>(std::stoull(value()));
else if (a == "--dump-ram")
dumpRam = value();
else
{
std::fprintf(stderr, "usage: tmb-headless [--frames n] [--elf path] [--iso image] [--pad-script [n=]file]... [--card-dir dir] "
"[--out run.ref] [--report n] [--print] [--quiet] [--wav file [--wav-frames a-b]] [--no-sound]\n");
"[--out run.ref] [--report n] [--print] [--quiet] [--wav file [--wav-frames a-b]] [--no-sound] "
"[--save-state file --save-state-at n] [--load-state file [--load-state-at n]] [--dump-ram file]\n");
return 2;
}
}
@@ -120,9 +135,12 @@ int main(int argc, char **argv)
return 2;
}
opt.gameTag = "SCUS-97101";
bozo::host::FreeHost host(opt);
host.onStateMessage = [](bool, const std::string &message) { std::printf("[state] %s\n", message.c_str()); };
bozo::ee::Dispatcher d(host);
tmb::scene::Binding scene(&d.runtime());
tmb::addStateSection(host, &d.runtime());
d.setFunctions(tmb_function_table, tmb_function_count, tmb_resume_table, tmb_resume_count);
std::string error;
if (!host.setUp(d, tmb_external_table, tmb_external_count, &registry, error))
@@ -196,6 +214,12 @@ int main(int argc, char **argv)
};
}
const uint64_t frames = host.run();
if (!dumpRam.empty())
if (FILE *f = std::fopen(dumpRam.c_str(), "wb"))
{
std::fwrite(d.runtime().memory.ram(), 1, 0x2000000u, f);
std::fclose(f);
}
if (wav.isOpen())
{
std::printf("wav: %s, %.1f s of sound\n", wavPath.c_str(), wav.frames() / 48000.0);
+300 -244
View File
@@ -1,246 +1,302 @@
// tmb: Twisted Metal: Black on BozoEngine in a window, in real time (phase 4, milestones M1 and M2). The free host as
// tmb-headless runs it (every library native, the disc image read, TMB's overrides native), with the host's clock: the
// game's frames held to the field rate (TMB's native frame end, bozo::app::FramePacer), each one presented in an SDL3
// window through OpenGL 3.3 (bozo::app::runWindow). The players' pads: the keyboard, mouse and up to four gamepads
// through input.ini's bindings (bozo::app::DevicePad; with the game's multitap, players 2-4 are its slots), or the
// frame-keyed scripts given.
//
// tmb [--iso image] [--elf SCUS_971.01] [--card-dir dir] [--width w --height h] [--fullscreen] [--no-vsync]
// [--render-scale s] [--capture-dir dir] [--capture-frames n,n,...] [--quit-after n] [--pad-script [n=]file]...
// [--no-sound] [--audio-latency ms] [--audio-stats] [--wav file]
//
// The user folder (%APPDATA%\TMB_Recomp, as the fork's TMB; PS2X_USER_DIR overrides it) holds input.ini, the memory
// cards (mc0, mc1; --card-dir overrides) and the logs (logs/TMB_Recomp.log). Without --elf the game data is looked for
// as the fork's TMB did (<exe>/game/SCUS_971.01, then the same in the user folder).
//
// Milestone M4, as the fork's TMB: F2 the settings window (Controls: input.ini; Video: video.ini in the user folder,
// --width / --height / --fullscreen (borderless) / --render-scale over it; Cheats: runtime/tmb_cheats.cpp), F3 the
// frame rate counter (PS2X_SHOW_FPS=1 from the start), F8 a capture sequence (PS2X_CAPTURE_SEQUENCE presents,
// PS2X_CAPTURE_SEQUENCE_AT seconds), F9 a burst of captures, ten a second; --capture-frames saves the game's picture at
// the first present after each of those game frames. The captures go to --capture-dir, else PS2X_CAPTURE_WINDOW_DIR,
// else <user folder>/captures. F11 / Alt+Enter: between the window and the last full-screen mode. --quit-after: close
// after that many frames. PS2X_FRAME_STATS=1: the frames' work times every 2 s (the FramePacer).
//
// Sound (milestone M3): the mixer's samples, made on the EE clock at each frame's end, go to the default playback device
// (bozo::app::AudioDevice: a queue of --audio-latency ms, 32 by default, plus the device's buffer). --audio-stats: the
// queue, latency and underruns every 2 s. --wav (or PS2X_AUDIO_RECORD): what the mixer made, also to a WAV file.
#include "tmb_host.h"
#include "tmb_port.h"
#include "bozo/app/app.h"
#include "bozo/app/audio_device.h"
#include "bozo/app/determinism.h"
#include "bozo/audio/wav.h"
#include "bozo/app/device_pad.h"
#include "bozo/app/input_bindings.h"
#include "bozo/app/video_settings.h"
#include "bozo/app/window.h"
#include "bozo/ee/dispatcher.h"
#include "bozo/host/free_host.h"
// tmb: Twisted Metal: Black on BozoEngine in a window, in real time (phase 4, milestones M1 and M2). The free host as
// tmb-headless runs it (every library native, the disc image read, TMB's overrides native), with the host's clock: the
// game's frames held to the field rate (TMB's native frame end, bozo::app::FramePacer), each one presented in an SDL3
// window through OpenGL 3.3 (bozo::app::runWindow). The players' pads: the keyboard, mouse and up to four gamepads
// through input.ini's bindings (bozo::app::DevicePad; with the game's multitap, players 2-4 are its slots), or the
// frame-keyed scripts given.
//
// tmb [--iso image] [--elf SCUS_971.01] [--card-dir dir] [--width w --height h] [--fullscreen] [--no-vsync]
// [--render-scale s] [--capture-dir dir] [--capture-frames n,n,...] [--quit-after n] [--pad-script [n=]file]...
// [--no-sound] [--audio-latency ms] [--audio-stats] [--wav file] [--hidden] [--capture-scene]
// [--save-state file --save-state-at n] [--load-state file [--load-state-at n]]
//
// --hidden: a test run that shows nothing (the window is never shown; --capture-frames reads the game's offscreen
// picture). --capture-scene: captures read that picture (no overlays) in a shown window too.
//
// The user folder (%APPDATA%\TMB_Recomp, as the fork's TMB; PS2X_USER_DIR overrides it) holds input.ini, the memory
// cards (mc0, mc1; --card-dir overrides) and the logs (logs/TMB_Recomp.log). Without --elf the game data is looked for
// as the fork's TMB did (<exe>/game/SCUS_971.01, then the same in the user folder).
//
// Milestone M4, as the fork's TMB: F2 the settings window (Controls: input.ini; Video: video.ini in the user folder,
// --width / --height / --fullscreen (borderless) / --render-scale over it; Cheats: runtime/tmb_cheats.cpp; Video,
// Cheats and Save states also in the game's Options screen, PC SETTINGS: runtime/tmb_menu.cpp), F3 the
// frame rate counter (PS2X_SHOW_FPS=1 from the start), F8 a capture sequence (PS2X_CAPTURE_SEQUENCE presents,
// PS2X_CAPTURE_SEQUENCE_AT seconds), F9 a burst of captures, ten a second; --capture-frames saves the game's picture at
// the first present after each of those game frames. The captures go to --capture-dir, else PS2X_CAPTURE_WINDOW_DIR,
// else <user folder>/captures. F11 / Alt+Enter: between the window and the last full-screen mode. --quit-after: close
// after that many frames. PS2X_FRAME_STATS=1: the frames' work times every 2 s (the FramePacer).
//
// Sound (milestone M3): the mixer's samples, made on the EE clock at each frame's end, go to the default playback device
// (bozo::app::AudioDevice: a queue of --audio-latency ms, 32 by default, plus the device's buffer). --audio-stats: the
// queue, latency and underruns every 2 s. --wav (or PS2X_AUDIO_RECORD): what the mixer made, also to a WAV file.
#include "tmb_state.h"
#include "tmb_host.h"
#include "tmb_menu.h"
#include "tmb_port.h"
#include "bozo/app/app.h"
#include "bozo/app/audio_device.h"
#include "bozo/app/determinism.h"
#include "bozo/audio/wav.h"
#include "bozo/app/device_pad.h"
#include "bozo/app/input_bindings.h"
#include "bozo/app/panel.h"
#include "bozo/app/video_settings.h"
#include "bozo/app/window.h"
#include "bozo/ee/dispatcher.h"
#include "bozo/host/free_host.h"
#include "tmb_scene.h"
#include <cstdio>
#include <cstdlib>
#include <filesystem>
#include <sstream>
#include <string>
#ifndef BOZO_RUN_DEFAULT_ELF
#define BOZO_RUN_DEFAULT_ELF ""
#endif
int main(int argc, char **argv)
{
// The fork's TMB identity (its PS2X_APP_* CMake values): the same user folder, so the cards and input.ini carry over.
bozo::app::Identity identity;
identity.title = "Twisted Metal: Black";
identity.folder = "TMB_Recomp";
identity.xdgFolder = "tmb_recomp";
identity.bootElf = "SCUS_971.01";
identity.dataFolder = "game";
bozo::app::setIdentity(identity);
bozo::app::startLogging();
bozo::app::installCrashHandler();
bozo::host::FreeOptions opt;
opt.elf = BOZO_RUN_DEFAULT_ELF;
opt.realTime = true;
opt.quiet = true;
bozo::app::WindowOptions window;
window.title = "Twisted Metal: Black (BozoEngine)";
bozo::app::AudioOptions audio;
bool sound = true;
std::string wavPath;
if (const char *record = std::getenv("PS2X_AUDIO_RECORD"); record && *record)
wavPath = record;
// The command line's window options, over video.ini (applied once the user folder is known, below).
int width = 0, height = 0;
bool fullscreen = false;
float renderScale = 0.0f;
for (int k = 1; k < argc; ++k)
{
const std::string a = argv[k];
auto value = [&]() -> std::string { return k + 1 < argc ? argv[++k] : ""; };
if (a == "--elf")
opt.elf = value();
else if (a == "--iso")
opt.iso = value();
else if (a == "--card-dir")
opt.cardDir = value();
else if (a == "--pad-script")
{
// [n=]file: player n's script (1 when omitted; players 2-4: the multitap's slots)
std::string v = value();
int player = 1;
if (v.size() > 2 && v[1] == '=' && v[0] >= '1' && v[0] <= '4')
{
player = v[0] - '0';
v = v.substr(2);
}
(player == 1 ? opt.padScript : opt.playerScripts[static_cast<size_t>(player - 2)]) = v;
}
else if (a == "--width")
width = std::stoi(value());
else if (a == "--height")
height = std::stoi(value());
else if (a == "--fullscreen")
fullscreen = true;
else if (a == "--no-vsync")
window.vsync = false;
else if (a == "--render-scale")
renderScale = std::stof(value());
else if (a == "--capture-dir")
window.captureDir = value();
else if (a == "--capture-frames")
{
std::stringstream list(value());
for (std::string item; std::getline(list, item, ',');)
if (!item.empty())
window.captureFrames.push_back(std::stoull(item));
}
else if (a == "--quit-after")
window.quitAfterFrames = std::stoull(value());
else if (a == "--print")
opt.printGameOutput = true;
else if (a == "--no-sound")
sound = false;
else if (a == "--audio-latency")
audio.latencyMs = std::stod(value());
else if (a == "--audio-stats")
audio.stats = true;
else if (a == "--wav")
wavPath = value();
else
{
std::fprintf(stderr, "usage: tmb [--iso image] [--elf path] [--card-dir dir] [--width w] [--height h] [--fullscreen] "
"[--no-vsync] [--render-scale s] [--capture-dir dir] [--capture-frames n,n,...] [--quit-after n] "
"[--pad-script [n=]file]... [--print] [--no-sound] [--audio-latency ms] [--audio-stats] [--wav file]\n");
return 2;
}
}
// The window as the player set it (video.ini in the user folder, the fork's file; PS2X_WINDOW_SIZE / _MODE,
// PS2X_RENDER_SCALE over it), then the command line over both.
bozo::app::video::loadAtStartup(window.width, window.height);
{
bozo::app::video::Settings &v = bozo::app::video::edited();
if (width > 0 && height > 0)
v.width = width, v.height = height;
if (fullscreen)
v.mode = bozo::app::video::WindowMode::Borderless;
if (renderScale > 0.0f)
v.renderScale = renderScale;
}
window.videoSettings = true;
std::error_code ec;
if (opt.elf.empty() || !std::filesystem::is_regular_file(opt.elf, ec))
{
std::string searched;
const std::filesystem::path found = bozo::app::findGameData(&searched);
if (found.empty())
{
std::fprintf(stderr, "tmb: no ELF (--elf); looked for the game data at\n%s", searched.c_str());
return 2;
}
opt.elf = found.string();
}
// The memory cards in the user folder (<user>/mc0, mc1: the fork's layout, its saves read as they are).
if (opt.cardDir.empty() && !bozo::app::userDirectory().empty())
opt.cardDir = bozo::app::userDirectory().string();
tmb::host::setElfDirectory(std::filesystem::path(opt.elf).parent_path().string());
if (opt.iso.empty())
opt.iso = tmb::findDiscImage(std::filesystem::path(opt.elf).parent_path().string(), "SCUS_971.01");
if (opt.iso.empty())
{
std::fprintf(stderr, "tmb: no disc image (--iso, TMB_ISO, or an .iso beside the ELF)\n");
return 2;
}
// Real time: the host's clock reaches the game (frame steps, the EE charged the real time a frame took).
bozo::det::setEnabled(false);
const bozo::port::Port *port = bozo::port::port();
bozo::port::Registry registry;
port->install(registry);
const std::vector<uint32_t> missing = bozo::port::undeclared(registry, tmb_external_table, tmb_external_count);
if (!missing.empty())
{
std::fprintf(stderr, "%zu registered overrides are not externals of the generated code (regenerate)\n", missing.size());
return 2;
}
bozo::host::FreeHost host(opt);
bozo::ee::Dispatcher d(host);
d.setFunctions(tmb_function_table, tmb_function_count, tmb_resume_table, tmb_resume_count);
std::string error;
if (!host.setUp(d, tmb_external_table, tmb_external_count, &registry, error))
{
std::fprintf(stderr, "tmb: %s\n", error.c_str());
return 2;
}
bozo::app::DevicePad pad;
bool scripted = !opt.padScript.empty();
for (const std::string &script : opt.playerScripts)
scripted = scripted || !script.empty();
if (!scripted)
host.libraries().pad.input = &pad;
const std::string pads = scripted ? std::string("the scripts") : "the PC's devices (" + bozo::app::input::configPath() + ")";
std::fprintf(stderr, "tmb: user folder %s, memory cards in %s, pads from %s\n", bozo::app::userDirectory().string().c_str(),
opt.cardDir.empty() ? "memory" : opt.cardDir.c_str(), pads.c_str());
std::fprintf(stderr, "tmb: %s, %zu overrides, ELF %s, disc %s\n", port->title, registry.functions().size(), opt.elf.c_str(),
opt.iso.c_str());
// The sound: what the mixer makes at each frame's end, to the device (and the WAV file).
bozo::app::AudioDevice device(audio);
bozo::audio::WavWriter wav;
if (!wavPath.empty() && !wav.open(wavPath))
std::fprintf(stderr, "tmb: cannot write %s\n", wavPath.c_str());
if (sound)
device.open();
if (device.isOpen() || wav.isOpen())
host.onAudio = [&](uint64_t, const int16_t *samples, size_t count) {
device.push(samples, count);
wav.write(samples, count);
};
bozo::app::Game game;
game.run = [&]
{
#include <cstdio>
#include <cstdlib>
#include <filesystem>
#include <sstream>
#include <string>
#ifndef BOZO_RUN_DEFAULT_ELF
#define BOZO_RUN_DEFAULT_ELF ""
#endif
int main(int argc, char **argv)
{
// The fork's TMB identity (its PS2X_APP_* CMake values): the same user folder, so the cards and input.ini carry over.
bozo::app::Identity identity;
identity.title = "Twisted Metal: Black";
identity.folder = "TMB_Recomp";
identity.xdgFolder = "tmb_recomp";
identity.bootElf = "SCUS_971.01";
identity.dataFolder = "game";
bozo::app::setIdentity(identity);
bozo::app::startLogging();
bozo::app::installCrashHandler();
bozo::host::FreeOptions opt;
opt.elf = BOZO_RUN_DEFAULT_ELF;
opt.realTime = true;
opt.quiet = true;
bozo::app::WindowOptions window;
window.title = "Twisted Metal: Black (BozoEngine)";
bozo::app::AudioOptions audio;
bool sound = true;
std::string wavPath;
if (const char *record = std::getenv("PS2X_AUDIO_RECORD"); record && *record)
wavPath = record;
// The command line's window options, over video.ini (applied once the user folder is known, below).
int width = 0, height = 0;
bool fullscreen = false;
float renderScale = 0.0f;
for (int k = 1; k < argc; ++k)
{
const std::string a = argv[k];
auto value = [&]() -> std::string { return k + 1 < argc ? argv[++k] : ""; };
if (a == "--elf")
opt.elf = value();
else if (a == "--iso")
opt.iso = value();
else if (a == "--card-dir")
opt.cardDir = value();
else if (a == "--pad-script")
{
// [n=]file: player n's script (1 when omitted; players 2-4: the multitap's slots)
std::string v = value();
int player = 1;
if (v.size() > 2 && v[1] == '=' && v[0] >= '1' && v[0] <= '4')
{
player = v[0] - '0';
v = v.substr(2);
}
(player == 1 ? opt.padScript : opt.playerScripts[static_cast<size_t>(player - 2)]) = v;
}
else if (a == "--width")
width = std::stoi(value());
else if (a == "--height")
height = std::stoi(value());
else if (a == "--fullscreen")
fullscreen = true;
else if (a == "--no-vsync")
window.vsync = false;
else if (a == "--render-scale")
renderScale = std::stof(value());
else if (a == "--capture-dir")
window.captureDir = value();
else if (a == "--capture-frames")
{
std::stringstream list(value());
for (std::string item; std::getline(list, item, ',');)
if (!item.empty())
window.captureFrames.push_back(std::stoull(item));
}
else if (a == "--hidden")
window.hidden = true; // a test run that shows nothing: captures read the game's offscreen picture
else if (a == "--capture-scene")
window.captureScene = true; // captures read the game's picture (no overlays) even in a shown window
else if (a == "--quit-after")
window.quitAfterFrames = std::stoull(value());
else if (a == "--print")
opt.printGameOutput = true;
else if (a == "--no-sound")
sound = false;
else if (a == "--audio-latency")
audio.latencyMs = std::stod(value());
else if (a == "--audio-stats")
audio.stats = true;
else if (a == "--wav")
wavPath = value();
else if (a == "--save-state")
opt.saveState = value();
else if (a == "--save-state-at")
opt.saveStateFrame = static_cast<uint32_t>(std::stoull(value()));
else if (a == "--load-state")
opt.loadState = value();
else if (a == "--load-state-at")
opt.loadStateFrame = static_cast<uint32_t>(std::stoull(value()));
else
{
std::fprintf(stderr, "usage: tmb [--iso image] [--elf path] [--card-dir dir] [--width w] [--height h] [--fullscreen] "
"[--no-vsync] [--render-scale s] [--capture-dir dir] [--capture-frames n,n,...] [--quit-after n] [--hidden] [--capture-scene] "
"[--pad-script [n=]file]... [--print] [--no-sound] [--audio-latency ms] [--audio-stats] [--wav file] "
"[--save-state file --save-state-at n] [--load-state file [--load-state-at n]]\n");
return 2;
}
}
// The window as the player set it (video.ini in the user folder, the fork's file; PS2X_WINDOW_SIZE / _MODE,
// PS2X_RENDER_SCALE over it), then the command line over both.
bozo::app::video::loadAtStartup(window.width, window.height);
{
bozo::app::video::Settings &v = bozo::app::video::edited();
if (width > 0 && height > 0)
v.width = width, v.height = height;
if (fullscreen)
v.mode = bozo::app::video::WindowMode::Borderless;
if (renderScale > 0.0f)
v.renderScale = renderScale;
}
window.videoSettings = true;
std::error_code ec;
if (opt.elf.empty() || !std::filesystem::is_regular_file(opt.elf, ec))
{
std::string searched;
const std::filesystem::path found = bozo::app::findGameData(&searched);
if (found.empty())
{
std::fprintf(stderr, "tmb: no ELF (--elf); looked for the game data at\n%s", searched.c_str());
return 2;
}
opt.elf = found.string();
}
// The memory cards in the user folder (<user>/mc0, mc1: the fork's layout, its saves read as they are).
if (opt.cardDir.empty() && !bozo::app::userDirectory().empty())
opt.cardDir = bozo::app::userDirectory().string();
tmb::host::setElfDirectory(std::filesystem::path(opt.elf).parent_path().string());
if (opt.iso.empty())
opt.iso = tmb::findDiscImage(std::filesystem::path(opt.elf).parent_path().string(), "SCUS_971.01");
if (opt.iso.empty())
{
std::fprintf(stderr, "tmb: no disc image (--iso, TMB_ISO, or an .iso beside the ELF)\n");
return 2;
}
// Real time: the host's clock reaches the game (frame steps, the EE charged the real time a frame took).
bozo::det::setEnabled(false);
const bozo::port::Port *port = bozo::port::port();
bozo::port::Registry registry;
port->install(registry);
const std::vector<uint32_t> missing = bozo::port::undeclared(registry, tmb_external_table, tmb_external_count);
if (!missing.empty())
{
std::fprintf(stderr, "%zu registered overrides are not externals of the generated code (regenerate)\n", missing.size());
return 2;
}
opt.gameTag = "SCUS-97101";
bozo::host::FreeHost host(opt);
bozo::ee::Dispatcher d(host);
// Save states (BozoEngine/docs/save-states.md): TMB's section, F5 save, F7 load, F6 / Shift+F6 the slot, the F2 tab.
tmb::addStateSection(host, &d.runtime());
host.onStateMessage = [](bool, const std::string &message)
{
std::fprintf(stderr, "[state] %s\n", message.c_str());
bozo::app::notify(message);
};
d.setFunctions(tmb_function_table, tmb_function_count, tmb_resume_table, tmb_resume_count);
std::string error;
if (!host.setUp(d, tmb_external_table, tmb_external_count, &registry, error))
{
std::fprintf(stderr, "tmb: %s\n", error.c_str());
return 2;
}
bozo::app::DevicePad pad;
bool scripted = !opt.padScript.empty();
for (const std::string &script : opt.playerScripts)
scripted = scripted || !script.empty();
if (!scripted)
host.libraries().pad.input = &pad;
const std::string pads = scripted ? std::string("the scripts") : "the PC's devices (" + bozo::app::input::configPath() + ")";
std::fprintf(stderr, "tmb: user folder %s, memory cards in %s, pads from %s\n", bozo::app::userDirectory().string().c_str(),
opt.cardDir.empty() ? "memory" : opt.cardDir.c_str(), pads.c_str());
std::fprintf(stderr, "tmb: %s, %zu overrides, ELF %s, disc %s\n", port->title, registry.functions().size(), opt.elf.c_str(),
opt.iso.c_str());
// The sound: what the mixer makes at each frame's end, to the device (and the WAV file).
bozo::app::AudioDevice device(audio);
bozo::audio::WavWriter wav;
if (!wavPath.empty() && !wav.open(wavPath))
std::fprintf(stderr, "tmb: cannot write %s\n", wavPath.c_str());
if (sound)
device.open();
if (device.isOpen() || wav.isOpen())
host.onAudio = [&](uint64_t, const int16_t *samples, size_t count) {
device.push(samples, count);
wav.write(samples, count);
};
bozo::app::Game game;
game.run = [&]
{
tmb::scene::Binding scene(&d.runtime());
const uint64_t frames = host.run();
if (device.isOpen())
{
const bozo::app::AudioDevice::Stats a = device.stats();
std::fprintf(stderr, "tmb: sound: %.1f s pushed, %llu frames dropped, %llu underruns (%.1f ms of silence); queue %.1f ms "
"(%.1f-%.1f) + device %.1f ms; ratio %.4f\n",
a.pushed / 48000.0, static_cast<unsigned long long>(a.dropped), static_cast<unsigned long long>(a.underruns),
a.missing / 48.0, a.queueMs, a.minQueueMs, a.maxQueueMs, a.deviceMs, a.ratio);
device.close();
}
wav.close();
std::fprintf(stderr, "tmb: the game ended after %llu frames: %s\n", static_cast<unsigned long long>(frames),
host.endReason().empty() ? "every thread ended" : host.endReason().c_str());
return host.endReason().rfind("FAULT", 0) == 0 ? 1 : 0;
};
game.stop = [&] { host.requestStop(); };
game.framesEnded = [&] { return host.framesEnded(); };
return bozo::app::runWindow(window, game, &pad);
}
const uint64_t frames = host.run();
if (device.isOpen())
{
const bozo::app::AudioDevice::Stats a = device.stats();
std::fprintf(stderr, "tmb: sound: %.1f s pushed, %llu frames dropped, %llu underruns (%.1f ms of silence); queue %.1f ms "
"(%.1f-%.1f) + device %.1f ms; ratio %.4f\n",
a.pushed / 48000.0, static_cast<unsigned long long>(a.dropped), static_cast<unsigned long long>(a.underruns),
a.missing / 48.0, a.queueMs, a.minQueueMs, a.maxQueueMs, a.deviceMs, a.ratio);
device.close();
}
wav.close();
std::fprintf(stderr, "tmb: the game ended after %llu frames: %s\n", static_cast<unsigned long long>(frames),
host.endReason().empty() ? "every thread ended" : host.endReason().c_str());
return host.endReason().rfind("FAULT", 0) == 0 ? 1 : 0;
};
game.stop = [&] { host.requestStop(); };
game.framesEnded = [&] { return host.framesEnded(); };
game.saveState = [&](int slot) { host.requestSave(bozo::app::stateSlotPath(slot)); };
game.loadState = [&](int slot) { host.requestLoad(bozo::app::stateSlotPath(slot)); };
// PC SETTINGS in the game's Options screen (runtime/tmb_menu.cpp): the window's video settings and save states.
tmb::menu::Hooks menuHooks;
menuHooks.videoShared = [] { return bozo::app::video::shared(); };
menuHooks.videoApply = [](const bozo::app::video::Settings &s) { bozo::app::video::post(s, true); };
menuHooks.texturePackFolder = [](const std::string &s) { return bozo::app::video::texturePackFolder(s); };
menuHooks.stateSlot = [] { return bozo::app::stateSlot(); };
menuHooks.setStateSlot = [](int slot) { bozo::app::setStateSlot(slot); };
menuHooks.slotSummary = [](int slot) { return bozo::app::stateSlotSummary(slot); };
menuHooks.saveState = [&](int slot)
{
host.requestSave(bozo::app::stateSlotPath(slot));
bozo::app::captureStatePicture(slot); // the slot's picture, as F5 takes it
return true;
};
menuHooks.loadState = [&](int slot)
{
host.requestLoad(bozo::app::stateSlotPath(slot));
return true;
};
menuHooks.quit = [&] { host.requestStop(); };
menuHooks.widescreen = [] { return bozo::app::video::shared().applied.widescreen; };
menuHooks.setPictureAspect = [](float aspect) { bozo::app::setPictureAspect(aspect); };
bozo::app::video::offerWidescreen(true); // runtime/tmb_widescreen.cpp
tmb::menu::setHooks(std::move(menuHooks));
return bozo::app::runWindow(window, game, &pad);
}
+7 -4
View File
@@ -16,10 +16,13 @@
# The generated code: bozo-recomp with the externals bozo-externals writes from the ELF (the stubs BozoEngine answers),
# recomp/tmb_stubs.txt and TMB's override list (tools/tmb_overrides_list.py, from runtime/*.cpp).
# BozoEngine: the submodule (BozoEngine/, at the commit TMB pins) unless BOZO_ENGINE_DIR names another tree (development).
set(BOZO_ENGINE_DIR "" CACHE PATH "BozoEngine's source tree (default: the BozoEngine submodule)")
if(NOT BOZO_ENGINE_DIR AND EXISTS "${CMAKE_SOURCE_DIR}/BozoEngine/CMakeLists.txt")
set(BOZO_ENGINE_DIR "${CMAKE_SOURCE_DIR}/BozoEngine" CACHE PATH "BozoEngine's source tree (default: the BozoEngine submodule)" FORCE)
# BozoEngine: the release cmake/bozo_engine.json pins, fetched into BozoEngine/ (cmake/bozo_engine_fetch.cmake), unless
# BOZO_ENGINE_DIR names another tree (development: a BozoEngine checkout).
set(BOZO_ENGINE_DIR "" CACHE PATH "BozoEngine's source tree (default: the release cmake/bozo_engine.json pins, in BozoEngine/)")
if(NOT BOZO_ENGINE_DIR OR BOZO_ENGINE_DIR STREQUAL "${CMAKE_SOURCE_DIR}/BozoEngine")
include("${CMAKE_CURRENT_LIST_DIR}/bozo_engine_fetch.cmake")
set(BOZO_ENGINE_DIR "${bozo_engine_tree}")
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${CMAKE_CURRENT_LIST_DIR}/bozo_engine.json")
endif()
set(TMB_ELF "" CACHE FILEPATH "TMB's executable (SCUS_971.01), extracted from the disc")
set(TMB_GEN_FILES 32 CACHE STRING "How many .cpp files the generated code is split into")
+4
View File
@@ -0,0 +1,4 @@
{
"version": "0.6.0",
"sha256": "d29bae3852abea4a6eee7b091141e637cd2db417383b476ac9778f3f3ff60957"
}
+56
View File
@@ -0,0 +1,56 @@
# The BozoEngine release cmake/bozo_engine.json pins, in BozoEngine/ beside cmake/: the release's archive
# (https://github.com/TheBozos/BozoEngine/releases), SHA-256 checked, unpacked, and its version and hash written to
# BozoEngine/.release; nothing is downloaded while those match the pin (a release's source\BozoEngine comes with it, so
# a player's build stays offline). Included by cmake/bozo.cmake and launcher/CMakeLists.txt when they are not given
# another tree, run by tools/tmb_build.py in a git checkout and by tools/make_release.py, or on its own:
# cmake [-DBOZO_ENGINE_DOWNLOADS=<dir>] -P cmake/bozo_engine_fetch.cmake
# BOZO_ENGINE_DOWNLOADS is where the archive goes (default build/). The same scheme as SoulCaliburIII_Recomp's.
cmake_minimum_required(VERSION 3.20)
get_filename_component(bozo_engine_root "${CMAKE_CURRENT_LIST_DIR}/.." ABSOLUTE)
file(READ "${CMAKE_CURRENT_LIST_DIR}/bozo_engine.json" bozo_engine_pin)
string(JSON bozo_engine_version GET "${bozo_engine_pin}" version)
string(JSON bozo_engine_sha256 GET "${bozo_engine_pin}" sha256)
set(bozo_engine_tree "${bozo_engine_root}/BozoEngine")
set(bozo_engine_want "${bozo_engine_version} ${bozo_engine_sha256}")
set(bozo_engine_have "")
if(EXISTS "${bozo_engine_tree}/.release")
file(READ "${bozo_engine_tree}/.release" bozo_engine_have)
string(STRIP "${bozo_engine_have}" bozo_engine_have)
elseif(EXISTS "${bozo_engine_tree}")
file(GLOB bozo_engine_entries "${bozo_engine_tree}/*" "${bozo_engine_tree}/.*")
if(bozo_engine_entries)
message(FATAL_ERROR "BozoEngine: ${bozo_engine_tree} is not a pinned release (the old submodule's checkout?): "
"move it away (to build on it there: -DBOZO_ENGINE_DIR=<its new place>, or "
"tools/tmb_build.py --engine <its new place>)")
endif()
endif()
if(NOT bozo_engine_have STREQUAL bozo_engine_want)
if(NOT BOZO_ENGINE_DOWNLOADS)
set(BOZO_ENGINE_DOWNLOADS "${bozo_engine_root}/build")
endif()
set(bozo_engine_name "BozoEngine-${bozo_engine_version}")
set(bozo_engine_archive "${BOZO_ENGINE_DOWNLOADS}/${bozo_engine_name}.tar.gz")
set(bozo_engine_url
"https://github.com/TheBozos/BozoEngine/releases/download/v${bozo_engine_version}/${bozo_engine_name}.tar.gz")
message(STATUS "BozoEngine ${bozo_engine_version}: ${bozo_engine_url}")
file(DOWNLOAD "${bozo_engine_url}" "${bozo_engine_archive}" EXPECTED_HASH SHA256=${bozo_engine_sha256}
TLS_VERIFY ON STATUS bozo_engine_status)
list(GET bozo_engine_status 0 bozo_engine_code)
if(bozo_engine_code)
list(GET bozo_engine_status 1 bozo_engine_error)
message(FATAL_ERROR "BozoEngine ${bozo_engine_version}: ${bozo_engine_error}")
endif()
set(bozo_engine_unpack "${bozo_engine_root}/.BozoEngine-unpack")
file(REMOVE_RECURSE "${bozo_engine_tree}" "${bozo_engine_unpack}")
file(ARCHIVE_EXTRACT INPUT "${bozo_engine_archive}" DESTINATION "${bozo_engine_unpack}")
# Its files dated now: unpacked with the archive's own dates (the release's, older than objects built since), a
# build made on the last release kept objects compiled against the old headers after a pin bump (Shinobido 0.7.0 ->
# 0.7.3: two files built on the old renderer.h, objects and the HUD missing from the picture).
file(GLOB_RECURSE bozo_engine_files LIST_DIRECTORIES false "${bozo_engine_unpack}/*")
file(TOUCH_NOCREATE ${bozo_engine_files})
file(WRITE "${bozo_engine_unpack}/${bozo_engine_name}/.release" "${bozo_engine_want}\n")
file(RENAME "${bozo_engine_unpack}/${bozo_engine_name}" "${bozo_engine_tree}")
file(REMOVE_RECURSE "${bozo_engine_unpack}")
endif()
+2 -1
View File
@@ -15,6 +15,7 @@ The earlier v0.3.2 release remains in Git history and on GitHub for comparison;
## Architecture and build
[`SAVE_STATES.md`](SAVE_STATES.md) adds save states (F5/F7/F6, `--save-state` / `--load-state`), with the 989SND driver saved in BozoEngine.
[`NATIVE_PERSISTENT_FORWARD.md`](NATIVE_PERSISTENT_FORWARD.md) adds the last three forwards: 269/269 forward returns are native.
[`NATIVE_BLOW_DEBRIS_FORWARD.md`](NATIVE_BLOW_DEBRIS_FORWARD.md) adds the BlowDebris forwards (one dead-W-slot RAM hash difference, proven).
[`NATIVE_HUD_LASER_FORWARD.md`](NATIVE_HUD_LASER_FORWARD.md) adds the HUD laser forwards.
@@ -249,7 +250,7 @@ no upload tag at the audited calls; game texture-manager bookkeeping and other p
[`NATIVE_GRAPHICS_SERVICES.md`](NATIVE_GRAPHICS_SERVICES.md) records removal of the engine GS device/GIF
reader state and TMB's old packet-based flare adapter, independent/combined tests and unsupported readback limits.
- One submodule: `BozoEngine`. No PS2Recomp gitlink, legacy CMake branch, import fallback, IOP recompilation or old runner scripts.
- No submodule: BozoEngine is the release `cmake/bozo_engine.json` pins (fetched into `BozoEngine/`). No PS2Recomp gitlink, legacy CMake branch, import fallback, IOP recompilation or old runner scripts.
- `tools/tmb_build.py`: verify → extract → configure → native tools → recompile → packs → compile → stage.
- `scripts/build_runtime.sh` and the other retained shortcuts use that same pipeline.
- Native frame pacing is unconditional. A legacy `TMB_NATIVE_FRAMES=0` environment setting cannot bypass it.
+68
View File
@@ -3,6 +3,74 @@
Use a scratch `PS2X_USER_DIR` for every automated run. Keep game data and generated code out of Git and release ZIPs.
Publication is separate from a successful build; this checklist records what was actually verified.
v0.7.3 was published on 2026-12-01 after tagged CI and the owner's release request. Its draft assets were checked
locally before publication:
- both player ZIPs pass the SHA-256 and package audits, carry an identical 8,011-file payload, and are stamped with
the release commit and engine version `0.6.0`; the sources ZIP matches its hash;
- the release's change (RecompLauncher support, #125): both ZIPs carry the commit's `recomplauncher.json` at their
top. On the `-bozo.zip`, unpacked into a path with accents, RecompLauncher's prepare and start (run as its
`lib.rs` does, with DC's `rl_sim.py`) built the game in 158 s ending "Ready to play", said "Already built" when run
again, played 600 frames hidden and muted at 59.7 frames/s with the cards and logs in `recompdata`, and prepared
again from the kept `disc.iso` without the player's image;
- a fresh install in a path with spaces and accents was built offline from the disc with only the bundled kit. The
build was stopped and resumed, then the game played and exited normally, with menu/movie timing passing;
- the v0.7.1 install was updated by its own updater, rebuilt and played; the v0.3.2 updater accepted the migration
ZIP. Player data was kept in both update cases;
- on the fresh install, the launcher's Enhanced textures made 2,181 replacements.
v0.7.2 was published on 2026-11-30 after tagged CI and the owner's release request. Its draft assets were checked
locally before publication:
- both player ZIPs pass the SHA-256 and package audits, carry an identical 8,009-file payload, and are stamped with
the release commit and engine version `0.6.0`; the sources ZIP matches its hash and holds the pinned engine release
(`source/BozoEngine/.release`);
- the release's changes (engine fetched from a pinned BozoEngine release, #121; BozoEngine 0.6.0, #122) were checked
before tagging: a clean checkout builds with no submodule, and headless 1P (9,500 frames) and 4P (8,500 frames)
records match the previous engine on every field;
- a fresh install in a path with spaces and accents was built offline from the disc with only the bundled kit. The
build was stopped and resumed, then the game played and exited normally, with menu/movie timing passing;
- the v0.7.1 install was updated by its own updater, rebuilt and played; the v0.3.2 updater accepted the migration
ZIP. Player data was kept in both update cases;
- on the fresh install, the launcher's Enhanced textures made 2,191 replacements.
v0.7.1 was published on 2026-11-30 after tagged CI and the owner's release request. Its draft assets were checked
locally before publication:
- both player ZIPs pass the SHA-256 and package audits, carry an identical 8,003-file payload, and are stamped with
the release commit and engine `b29bc39`; the sources ZIP matches its hash;
- the release's fix (source and kit file times settled before configuring, #118) was checked end to end: the v0.7.0
player ZIP with every file dated 3 h ahead loops ninja ("still dirty after 100 tries") as shipped and passes
Prepare's tools step with the fix;
- a fresh install in a path with spaces and accents was built offline from the disc with only the bundled kit. The
build was stopped and resumed, then the game played and exited normally, with menu/movie timing passing (a first
run failed movie 2 at 28.3 pictures/s while another port's run shared the bench; the rerun passed);
- the v0.7.0 install was updated by its own updater, rebuilt and played; the v0.3.2 updater accepted the migration
ZIP. Player data was kept in both update cases;
- on the fresh install, the launcher's Enhanced textures made 2,186 replacements.
v0.7.0 was published on 2026-11-27 after tagged CI and the owner's release request. Its draft assets were checked
locally before publication:
- both player ZIPs pass the SHA-256 and package audits, carry an identical 8,003-file payload, and are stamped with
the release commit and engine `b29bc39`; the sources ZIP matches its hash;
- a fresh install in a path with spaces and accents was built offline from the disc with only the bundled kit. The
build was stopped and resumed, then the game played and exited normally, with menu/movie timing passing;
- the v0.6.0 install was updated by its own updater, rebuilt and played; the v0.3.2 updater accepted the migration
ZIP. Player data was kept in both update cases;
- on the fresh install, the launcher's Enhanced textures made 2,191 replacements;
- the release's new features (PC SETTINGS in the Options screen and the pause menu, QUIT GAME, widescreen, its HUD
and dialogs, the quit-music fix) were played by the owner on the development PC before the tag.
v0.6.0 was published on 2026-11-11 after tagged CI and the owner's release request. Its draft assets were checked
locally before publication:
- both player ZIPs pass the SHA-256 and package audits, carry an identical 7,974-file payload, and are stamped with
the release commit and engine `a36a4d2`. Real-ESRGAN, its licences and the enhanced-texture tools are in the kit;
- a fresh install in a path with spaces and accents was built offline from the disc with only the bundled kit. The
build was stopped and resumed, then the game played and exited normally, with menu/movie timing passing;
- on that install, the launcher's Enhanced textures dumped and upscaled 2,181 replacements in 4 min 18 s. An earlier
draft failed here because the dump listed some textures more than once; it was rebuilt with the fix (#104);
- the v0.5.0 install was updated by its own updater, rebuilt and played; the v0.3.2 updater accepted the migration
ZIP. Player data was kept in both update cases;
- with the bench lock, the pack at 4x held 59.1 to 59.5 minimum and 59.9 average game fps in 1P, three story arenas
and 4P, the same as with it off (one RTX 5070 Ti).
v0.5.0 was published on 2026-11-09 after tagged CI and the owner's release request. Its draft assets were checked
locally before publication:
- both player ZIPs pass the SHA-256 and package audits, carry an identical 7,889-file payload, and are stamped with
+70
View File
@@ -0,0 +1,70 @@
# Save states
TMB uses BozoEngine's save states (`BozoEngine/docs/save-states.md`). A state holds the whole run at a frame's end.
It can be loaded back in the same process or in a new one, and the run then goes on exactly as the saved run did.
## Using them
- **Window:**
- F5 saves in the current slot and F7 loads it.
- F6 and Shift+F6 change the slot (0-9). F2 → Save states lists the slots.
- The files are `states/slot<n>.state` in the user folder, about 40 MB each.
- **Command line** (`tmb` and `tmb-headless`):
- `--save-state FILE --save-state-at N` writes a state when N frames have ended.
- `--load-state FILE [--load-state-at N]` loads one before the first frame, or when N frames have ended.
- Frame numbers stay absolute after a load: `--frames`, `--quit-after` and `--capture-frames` still count from the
start of the run.
- `tmb-headless --dump-ram FILE` writes EE RAM at the run's end.
- **Limits:**
- A state loads only into the build that wrote it. Make the states again after a change to a section's layout.
- A save waits while a movie plays, and says why.
- Recorded runs (`--out`) do not follow a load.
For checks, keep a few named states, for example the title, a 1P match or a 4P match. Note the frame and pad script
that made each one, then start runs from them instead of replaying the scripts from boot.
## What is saved
The engine saves the runtime, its libraries and the host:
- EE memory, threads, the kernel, timers, pads, cards, CD and MPEG;
- the 989SND sound driver: banks, handles, its IOP memory, mixer, libsd and 989SND's own model.
Two engine changes came with this:
- **989SND unloaded banks:** the engine used to destroy a bank's header while busy voices still read its program
records, a use-after-free. Unloaded banks are now kept, as 989SND's IOP memory is.
- **`LoadedImages::images` / `restore`:** these let a port save the mesh files it bound.
TMB adds its own section, `tmb` (`runtime/tmb_state.cpp`):
| Part | Saved | Why |
| --- | --- | --- |
| Overrides | Frame pacing parity, frame-end cycle, field carry, clock debt; the movie sound's queue | The parity is written to the game's memory; the pacing carries over between frames |
| Native hierarchy | `tmb::scene::Scene` whole: frames, lights, renderer parameters | The records the game's VU programs kept between draws |
| Meshes | The NGP files the game bound (base, size, pack file), the DMA marks' counter | Told once when the game loads a level. The images change in memory afterwards, so they cannot be bound again |
| Textures | Disc file per address, the level's file lists and set-up order, the records placed in VRAM, TBP → texture id | Told once at load time; records saved as (file, index) |
| Particles | Stripe scroll, arc VU records, texture choices, per system | Kept between frames |
| Cheats | The lock words Unlock everything opened | Put back when it goes off |
On a load, the decoded textures, the skid marks' object and the 2D menu and movie pictures are dropped. They are
caches of the old run's memory.
## How it was checked
Headless runs are deterministic. Each check saves at frame N on the 1P or 4P route (A), then:
- loads that state in a new process (B);
- loads it in the middle of a run, at a later frame (C).
All three run to the route's end.
| Route | Saved at | End-of-route EE RAM (B, C against A) | Sound after the save |
| --- | --- | --- | --- |
| 1P, menus | 3,000 | identical | byte-identical |
| 1P, match | 7,000 | identical | byte-identical |
| 4P, match | 7,000 | identical | byte-identical |
The native renderer's batch counts and EE cycles after the load match the run that never stopped.
The default replays still match the build without save states on every recorded field. That covers 1P 9,500 frames
and 4P 8,500 frames, including RAM, sound and the sampled RAM images.
A window run that loaded a match state showed the same scene, HUD and sound as the run that saved it.
+8 -3
View File
@@ -25,10 +25,15 @@ endif()
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# BozoEngine's tree (the submodule beside launcher/): its PNG writer only.
set(LAUNCHER_BOZO_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../BozoEngine" CACHE PATH "BozoEngine's source tree")
# BozoEngine's tree (default: the release cmake/bozo_engine.json pins, in BozoEngine/ beside launcher/): its PNG writer
# only.
set(LAUNCHER_BOZO_DIR "" CACHE PATH "BozoEngine's source tree (default: the pinned release, in BozoEngine/)")
if(NOT LAUNCHER_BOZO_DIR)
include("${CMAKE_CURRENT_SOURCE_DIR}/../cmake/bozo_engine_fetch.cmake")
set(LAUNCHER_BOZO_DIR "${bozo_engine_tree}")
endif()
if(NOT EXISTS "${LAUNCHER_BOZO_DIR}/runtime/app/png.cpp")
message(FATAL_ERROR "No BozoEngine at ${LAUNCHER_BOZO_DIR} (git submodule update --init BozoEngine)")
message(FATAL_ERROR "No BozoEngine at ${LAUNCHER_BOZO_DIR}")
endif()
include(FetchContent)
+128
View File
@@ -0,0 +1,128 @@
{
"$schema": "https://recomplauncher.com/schema/recomplauncher.json",
"format": 1,
"name": "Twisted Metal: Black",
"repo": "TheBozos/TMB_Recomp",
"inputs": [
{
"id": "game",
"label": "Your disc image of the USA release, serial SCUS-97101 (.iso, or .bin/.cue).",
"formats": [{ "type": "file" }],
"check": { "iso9660": "SCUS_971.01", "ids": ["SCUS-97101"] },
"dumps": [{ "name": "USA", "size": 3799744512, "crc32": "347e93f9" }]
}
],
"prepare": {
"program": ["kit/python/python.exe"],
"args": ["-I", "-X", "utf8", "{install}/source/tools/tmb_build.py", "--disc={input:game}",
"--out", "{install}/build", "--game", "{install}/game", "--progress-lines"],
"label": "Building the game from your disc",
"done": ["{install}/game/built_from.ini"],
"keeps_copy": true
},
"start": {
"program": ["game/tmb.exe"],
"args": ["--elf", "{install}/game/SCUS_971.01", "--iso", "{install}/game/disc.iso"],
"env": { "PS2X_USER_DIR": "{data}" }
},
"folders": {
"game": [{ "path": "{install}/game" }],
"saves": [{ "path": "{data}/mc0" }],
"logs": [{ "path": "{data}/logs" }]
},
"saves": ["{data}/mc0", "{data}/mc1"],
"config": [{ "format": "ini", "file": [{ "path": "{data}/video.ini" }] }],
"settings": [
{
"id": "mode", "label": "Display mode",
"choices": [
{ "label": "Windowed", "set": { "video/mode": "windowed" } },
{ "label": "Borderless", "set": { "video/mode": "borderless" } },
{ "label": "Full screen", "set": { "video/mode": "fullscreen" } }
],
"defaults": { "video/mode": "windowed" }
},
{
"id": "widescreen", "label": "Widescreen",
"help": "16:9 with more of the arena at the sides in one- and two-player matches; menus, movies and four-player matches stay 4:3.",
"choices": [
{ "label": "Off (4:3)", "set": { "video/widescreen": "off" } },
{ "label": "On (16:9)", "set": { "video/widescreen": "on" } }
],
"defaults": { "video/widescreen": "off" }
},
{
"id": "frame_rate", "label": "Frame rate",
"help": "Above 60, frames between the game's are drawn in between; the game itself still runs at its own speed.",
"choices": [
{ "label": "60 (the game's)", "set": { "video/frame_rate": "game" } },
{ "label": "Monitor's refresh", "set": { "video/frame_rate": "monitor" } },
{ "label": "120", "set": { "video/frame_rate": "120" } },
{ "label": "144", "set": { "video/frame_rate": "144" } },
{ "label": "240", "set": { "video/frame_rate": "240" } }
],
"defaults": { "video/frame_rate": "game" }
},
{
"id": "render_scale", "label": "Render scale",
"help": "The 3D drawn at this many times the window's size.",
"choices": [
{ "label": "1x", "set": { "video/render_scale": "1" } },
{ "label": "1.5x", "set": { "video/render_scale": "1.5" } },
{ "label": "2x", "set": { "video/render_scale": "2" } },
{ "label": "3x", "set": { "video/render_scale": "3" } },
{ "label": "4x", "set": { "video/render_scale": "4" } }
],
"defaults": { "video/render_scale": "1" }
},
{
"id": "anti_aliasing", "label": "Anti-aliasing",
"help": "Smooths the edges of the 3D (MSAA).",
"choices": [
{ "label": "Off", "set": { "video/anti_aliasing": "off" } },
{ "label": "2x", "set": { "video/anti_aliasing": "2x" } },
{ "label": "4x", "set": { "video/anti_aliasing": "4x" } },
{ "label": "8x", "set": { "video/anti_aliasing": "8x" } }
],
"defaults": { "video/anti_aliasing": "off" }
},
{
"id": "texture_smoothing", "label": "Texture smoothing",
"help": "Off samples textures as the PS2 does; the others stop distant textures shimmering.",
"choices": [
{ "label": "Off", "set": { "video/texture_smoothing": "off" } },
{ "label": "Trilinear", "set": { "video/texture_smoothing": "trilinear" } },
{ "label": "4x anisotropic", "set": { "video/texture_smoothing": "4x" } },
{ "label": "8x anisotropic", "set": { "video/texture_smoothing": "8x" } },
{ "label": "16x anisotropic", "set": { "video/texture_smoothing": "16x" } }
],
"defaults": { "video/texture_smoothing": "off" }
},
{
"id": "pause_in_background", "label": "Pause in the background", "advanced": true,
"help": "Holds the game while another window has the focus.",
"choices": [
{ "label": "Off", "set": { "video/pause_in_background": "off" } },
{ "label": "On", "set": { "video/pause_in_background": "on" } }
],
"defaults": { "video/pause_in_background": "off" }
},
{
"id": "fast_forward", "label": "Fast-forward speed", "advanced": true,
"help": "The game's speed while fast forward is held (` on the keyboard, or the touchpad).",
"choices": [
{ "label": "2x", "set": { "video/fast_forward": "2x" } },
{ "label": "3x", "set": { "video/fast_forward": "3x" } },
{ "label": "5x", "set": { "video/fast_forward": "5x" } },
{ "label": "10x", "set": { "video/fast_forward": "10x" } },
{ "label": "Unlimited", "set": { "video/fast_forward": "unlimited" } }
],
"defaults": { "video/fast_forward": "3x" }
}
],
"actions": [
{ "id": "logs", "label": "Logs", "help": "The game's logs, for a bug report.", "open": "logs" }
],
"looks": { "graphics": "opengl" },
"system": { "windows": { "version": "10", "graphics": { "opengl": "3.3" } } }
}
+1137 -1120
View File
File diff suppressed because it is too large. Load diff
+492 -461
View File
@@ -1,461 +1,492 @@
// Cheats, switched while playing from the Cheats tab of the settings window (F2), per human player; the environment
// gives their values at launch (TMB_UNLOCK_ALL, TMB_NO_AI, TMB_PLAYER_GOD, TMB_INFINITE_AMMO, TMB_INFINITE_ENERGY,
// TMB_ENEMY_HEALTH_CAP; TMB_PLAYER_HEALTH_CAP is the testing opposite, a cap on the player's health).
//
// What the game keeps, from its own code:
// - TheGame (`this` of TheGame::Update): its vehicles at TheGame + i * 0x2D00, their count at + 0x1B3DB4
// (TheGame::GetVehicleFromName); the human players' vehicles as pointers at + 0x1B28B0, their count at + 0x1B3DB8
// (TheGame::gameCheckPlayerHealth, 0x133360, which walks them).
// - A vehicle's health: float at + 0x3F4, its maximum at + 0x3F0 (gameCheckPlayerHealth's health fraction, the HUD's
// health bars). Who drives it: + 0x580, 1 a player (vehicleUpdate calls playerUpdateInputs), 2 the computer
// (aiUpdateInputs, 0x1014A0).
// - Weapons: the count of pickup weapon i (1 to 8; slot 1 is the car's special, which Launcher::FireSpecial spends)
// at + 0x22C4 + 4 * i, the weapon selected at + 0x2140; the machine gun (slot 0) has no count. Every shot,
// detonation and special spends through TheGame::DecrementWeaponCount (0x1515A8, called by FireCurrentWeapon,
// FireSpecial, UpdateSpecial, UpdateLauncher, UpdateEnvWeapon, UpdateZoomies, UpdateWeaponToggle, KillWeapon),
// which goes on to Weapons::DecrementWeaponCount (0x1BA050: count - 1, then the next weapon with ammo when it
// reaches 0).
// - Energy (the freeze / mines / shield moves of the stick combos): int at + 0x2214 of + 0x2218 (the HUD's energy
// bar, Hud::build4PEnergyBar).
// - Progress: the Shell (at 0x40BCC0, the pointer at gp - 0x4148) keeps what is locked as words at Shell + 0x18000 +
// offset, 1 locked and 0 open; Shell::Shell (0x15F270) sets a fresh save's (what loadGlobalData then overwrites
// from the card's globalFile): the vehicles at + 0x218C + 4 * car (16; uiCarSel and uiAiSel play the locked sound
// on a 1; 9-12, 14 and 15 locked at first), the levels at + 0x21CC + 4 * level (21; uiLvlSel, the same; Shell::
// EvaluateEnduranceStatus clears 2 Freeway, 15 and 18 when their endurance kills are reached), and per character its
// movies, three arrays of 14 at + 0x2220, + 0x2258, + 0x2290 (uiMovies; 2 for a movie the character does not have).
#include "tmb_port.h"
#include "bozo/app/determinism.h"
#if defined(BOZO_SETTINGS_UI)
#include "bozo/app/settings_tabs.h"
#include "imgui.h"
#endif
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
namespace tmb::cheats
{
namespace
{
constexpr uint32_t kAiUpdateInputs = 0x001014A0u;
constexpr uint32_t kAiUpdateFrozenInput = 0x001017E8u;
constexpr uint32_t kDecrementWeaponCount = 0x001515A8u;
constexpr uint32_t kVehicles = 0x00000000u, kVehicleStride = 0x2D00u, kVehicleCount = 0x001B3DB4u;
constexpr uint32_t kPlayers = 0x001B28B0u, kPlayerCount = 0x001B3DB8u;
constexpr uint32_t kHealth = 0x3F4u, kHealthMax = 0x3F0u, kDriver = 0x580u;
constexpr uint32_t kWeaponCounts = 0x22C4u, kEnergy = 0x2214u, kEnergyMax = 0x2218u;
constexpr int kMaxPlayers = 4;
constexpr uint32_t kGpShell = 0x4148u, kShellProgress = 0x18000u;
// The shell screens that read the locks, and the lock arrays (offset, count) from Shell + 0x18000.
constexpr uint32_t kUiLvlSel = 0x001976B0u, kUiCarSel = 0x001963B0u, kUiAiSel = 0x001986A8u, kUiMovies = 0x00190760u;
constexpr struct
{
uint32_t offset, count;
} kLocks[] = {{0x218Cu, 16u}, {0x21CCu, 21u}, {0x2220u, 14u}, {0x2258u, 14u}, {0x2290u, 14u}};
// One bit per player (bit 0: player 1).
std::atomic<uint32_t> g_infiniteHealth{0}, g_infiniteAmmo{0}, g_infiniteEnergy{0};
std::atomic<bool> g_noAi{false};
std::atomic<bool> g_unlockAll{false};
// Story: start at a level (-1: off). The story's state is the level being played, Shell + 0x18000 + 0x2354 (the
// index of the game's level table: GetLevelName, LoadLevelDB), the one last won at + 0x2358, the mode at
// + 0x235C (1: one-player story); a new story sets the level to 1, the Junkyard, and each level won sets the
// next (EvaluateOnePlayerStoryStatus).
std::atomic<int> g_storyStart{-1};
constexpr uint32_t kStoryLevel = 0x2354u, kStoryLastWon = 0x2358u, kGameMode = 0x235Cu;
constexpr int kLevelCount = 21;
// The levels by the level table's index (its names at 0x426070, 16 bytes each), with the card the story shows
// when it starts there (the stage, of 8). Two stages have two arenas (the story picks one); ASYLUM and ROOFTOP2
// show no card (reached from inside another level); the others are arenas the story does not use.
constexpr const char *kLevelNames[kLevelCount] = {
"Stage 2: Midtown Suburbs (SUBURB)", "Stage 1: Junkyard (JUNKYARD)", "Stage 2: Midtown Expressway 104 (FREEWAY)",
"Stage 5: Prison Passage to Blackfield Asylum (PRISON)", "Stage 7: Abandoned Skyscrapers (ROOFTOP)",
"Stage 3: Downtown Business District (CITY)", "Stage 3: Black Vista Highway (LOOP)", "Arena DEATH1", "Arena DEATH2",
"Arena DEATH3", "Arena DEATH4", "Arena DEATH5", "Arena DEATH6", "Rooftops, second part (ROOFTOP2)",
"Stage 4: Minion's Stadium (STADIUM)", "Arena SHIP", "Blackfield Asylum (ASYLUM)", "Arena MINICITY", "Arena MINIBURB",
"Arena JUNK2", "Stage 8: Warhawk's Rooftop (ROOFBOSS)"};
// The picker's order: the story's, then the rest.
constexpr int kLevelOrder[kLevelCount] = {1, 0, 2, 5, 6, 14, 3, 16, 4, 13, 20, 7, 8, 9, 10, 11, 12, 15, 17, 18, 19};
std::vector<uint32_t> g_unlocked; // the lock words Unlock everything opened (put back when it goes off)
std::atomic<float> g_enemyCap{-1.0f}; // weak enemies: every computer vehicle's health held at most this; < 0 off
std::atomic<float> g_playerCap{-1.0f}; // TMB_PLAYER_HEALTH_CAP (testing)
std::atomic<uint32_t> g_theGame{0};
std::atomic<const uint8_t *> g_rdram{nullptr}; // for the tab (onFrame's)
const std::chrono::steady_clock::time_point g_start = std::chrono::steady_clock::now(); // the log's times
std::atomic<uint32_t> g_decrements{0}, g_decrementsSkipped{0}; // TMB_CHEATS_LOG: weapon spends since the last line
uint32_t word(const uint8_t *rdram, uint32_t address)
{
uint32_t value = 0;
std::memcpy(&value, rdram + (address & 0x1FFFFFFu), 4);
return value;
}
float flt(const uint8_t *rdram, uint32_t address)
{
float value = 0.0f;
std::memcpy(&value, rdram + (address & 0x1FFFFFFu), 4);
return value;
}
void setWord(uint8_t *rdram, uint32_t address, uint32_t value) { std::memcpy(rdram + (address & 0x1FFFFFFu), &value, 4); }
void setFlt(uint8_t *rdram, uint32_t address, float value) { std::memcpy(rdram + (address & 0x1FFFFFFu), &value, 4); }
int playerCount(const uint8_t *rdram, uint32_t game)
{
return game == 0u ? 0 : std::clamp(static_cast<int32_t>(word(rdram, game + kPlayerCount)), 0, kMaxPlayers);
}
uint32_t playerVehicle(const uint8_t *rdram, uint32_t game, int player)
{
return word(rdram, game + kPlayers + static_cast<uint32_t>(player) * 4u);
}
// The players whose bit is set in `mask` that own `vehicle`.
bool forPlayer(const uint8_t *rdram, uint32_t vehicle, uint32_t mask)
{
const uint32_t game = g_theGame.load(std::memory_order_relaxed);
if (mask == 0u || vehicle == 0u)
return false;
for (int player = 0; player < playerCount(rdram, game); ++player)
if ((mask >> player & 1u) && playerVehicle(rdram, game, player) == vehicle)
return true;
return false;
}
// The players a variable names: digits 1 to 4 (TMB_INFINITE_AMMO=12: players 1 and 2), any other value but 0
// every player.
uint32_t envMask(const char *name)
{
const char *value = std::getenv(name);
if (!value || !*value || std::string(value) == "0")
return 0u;
uint32_t mask = 0u;
for (const char *c = value; *c; ++c)
{
if (*c < '1' || *c > '0' + kMaxPlayers)
return (1u << kMaxPlayers) - 1u;
mask |= 1u << (*c - '1');
}
return mask;
}
float envFloat(const char *name)
{
const char *value = std::getenv(name);
return value && *value ? static_cast<float>(std::atof(value)) : -1.0f;
}
// No AI: Vehicle::aiUpdateInputs (each computer vehicle's pad, every frame) runs the game's own
// aiUpdateFrozenInput instead (no throttle, no steering, no firing).
void aiUpdateInputsOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
if (g_noAi.load(std::memory_order_relaxed))
{
ctx->pc = kAiUpdateFrozenInput;
aiUpdateFrozenInput__7Vehicle_0x1017e8(rdram, ctx, runtime);
return;
}
aiUpdateInputs__7Vehicle_0x1014a0(rdram, ctx, runtime);
}
// Infinite ammo: TheGame::DecrementWeaponCount(game, vehicle, weapon) returns at once for a player who has it,
// so nothing the car fires or detonates is counted (and the selected weapon stays).
void decrementWeaponCountOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
g_decrements.fetch_add(1, std::memory_order_relaxed);
static const bool s_log = std::getenv("TMB_CHEATS_LOG") != nullptr;
if (s_log && word(rdram, getRegU32(ctx, 5) + kDriver) == 1u)
std::fprintf(stderr, "[tmb:cheats] %.1f s: player car %x spends weapon %u (count %d)%s\n",
std::chrono::duration<double>(std::chrono::steady_clock::now() - g_start).count(), getRegU32(ctx, 5), getRegU32(ctx, 6),
static_cast<int32_t>(word(rdram, getRegU32(ctx, 5) + kWeaponCounts + getRegU32(ctx, 6) * 4u)),
forPlayer(rdram, getRegU32(ctx, 5), g_infiniteAmmo.load(std::memory_order_relaxed)) ? ", not counted" : "");
if (forPlayer(rdram, getRegU32(ctx, 5), g_infiniteAmmo.load(std::memory_order_relaxed)))
{
g_decrementsSkipped.fetch_add(1, std::memory_order_relaxed);
ctx->pc = getRegU32(ctx, 31); // jr $ra
return;
}
DecrementWeaponCount__7TheGameP7Vehiclei_0x1515a8(rdram, ctx, runtime);
}
// Unlock everything: every lock word still 1 opened; off, the ones it opened closed again (the game's own unlocks
// since then stay, the card is written only when the player saves).
void applyUnlocks(uint8_t *rdram, uint32_t gp)
{
const uint32_t shell = word(rdram, gp - kGpShell);
if (shell == 0u)
return;
const uint32_t progress = shell + kShellProgress;
if (g_unlockAll.load(std::memory_order_relaxed))
{
for (const auto &locks : kLocks)
for (uint32_t i = 0; i < locks.count; ++i)
{
const uint32_t address = progress + locks.offset + i * 4u;
if (word(rdram, address) == 1u)
{
setWord(rdram, address, 0u);
g_unlocked.push_back(address);
}
}
}
else if (!g_unlocked.empty())
{
for (const uint32_t address : g_unlocked)
if (word(rdram, address) == 0u)
setWord(rdram, address, 1u);
g_unlocked.clear();
}
}
template <void (*Screen)(uint8_t *, R5900Context *, PS2Runtime *)>
void shellScreenOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
applyUnlocks(rdram, getRegU32(ctx, 28));
Screen(rdram, ctx, runtime);
}
#if defined(BOZO_SETTINGS_UI)
void perPlayer(const char *label, std::atomic<uint32_t> &flags, int players)
{
ImGui::PushID(label);
uint32_t mask = flags.load(std::memory_order_relaxed);
// On for every player of the match (every player when there is none yet).
const uint32_t present = players > 0 ? (1u << players) - 1u : (1u << kMaxPlayers) - 1u;
bool all = (mask & present) == present;
if (ImGui::Checkbox(label, &all))
mask = all ? (1u << kMaxPlayers) - 1u : 0u;
for (int player = 0; player < std::max(players, 1); ++player)
{
ImGui::SameLine(player == 0 ? 220.0f : 0.0f);
bool on = mask >> player & 1u;
char name[8];
std::snprintf(name, sizeof(name), "P%d", player + 1);
if (ImGui::Checkbox(name, &on))
mask = on ? mask | 1u << player : mask & ~(1u << player);
}
flags.store(mask, std::memory_order_relaxed);
ImGui::PopID();
}
void drawTab()
{
const uint8_t *rdram = g_rdram.load(std::memory_order_relaxed);
const uint32_t game = g_theGame.load(std::memory_order_relaxed);
const int players = rdram ? playerCount(rdram, game) : 0;
ImGui::TextDisabled(players ? "In a match: %d player(s). Changes apply at once." : "They act in a match.", players);
bool unlock = g_unlockAll.load(std::memory_order_relaxed);
if (ImGui::Checkbox("Unlock everything (levels, vehicles, movies)", &unlock))
g_unlockAll.store(unlock, std::memory_order_relaxed);
ImGui::TextDisabled("Opened in the menus; saving the game while it is on keeps them on the card.");
int start = g_storyStart.load(std::memory_order_relaxed);
ImGui::SetNextItemWidth(420.0f);
if (ImGui::BeginCombo("Story: start at", start < 0 ? "the first level (as the game)" : kLevelNames[start]))
{
if (ImGui::Selectable("the first level (as the game)", start < 0))
start = -1;
for (const int i : kLevelOrder)
if (ImGui::Selectable(kLevelNames[i], start == i))
start = i;
ImGui::EndCombo();
}
g_storyStart.store(start, std::memory_order_relaxed);
ImGui::TextDisabled("For testing: a new story begins at this level, then goes on as the game chains them.");
ImGui::SeparatorText("Players");
perPlayer("Infinite health", g_infiniteHealth, players);
perPlayer("Infinite ammo", g_infiniteAmmo, players);
perPlayer("Infinite energy", g_infiniteEnergy, players);
ImGui::TextDisabled("Health and energy held at their maximum; weapons and specials not spent.");
ImGui::SeparatorText("Opponents");
bool noAi = g_noAi.load(std::memory_order_relaxed);
if (ImGui::Checkbox("No AI (the computer's cars do nothing)", &noAi))
g_noAi.store(noAi, std::memory_order_relaxed);
float cap = g_enemyCap.load(std::memory_order_relaxed);
bool weak = cap >= 0.0f;
if (ImGui::Checkbox("Weak enemies", &weak))
cap = weak ? 10.0f : -1.0f;
if (weak)
{
ImGui::SameLine();
ImGui::SetNextItemWidth(200.0f);
ImGui::SliderFloat("health at most", &cap, 1.0f, 300.0f, "%.0f", ImGuiSliderFlags_Logarithmic);
}
g_enemyCap.store(cap, std::memory_order_relaxed);
if (rdram && players)
{
const uint32_t car = playerVehicle(rdram, game, 0);
ImGui::TextDisabled("Player 1: health %.0f of %.0f, energy %d of %d", flt(rdram, car + kHealth), flt(rdram, car + kHealthMax),
static_cast<int32_t>(word(rdram, car + kEnergy)), static_cast<int32_t>(word(rdram, car + kEnergyMax)));
}
}
#endif
}
void setTheGame(uint32_t game) { g_theGame.store(game, std::memory_order_relaxed); }
// Once a frame (timerEndOfRealTimeProcessing, the frame's processing done).
// TMB_LOG_PROGRESS=1 (finding the story's state): each word of Shell + 0x18000 + 0x2180 to + 0x2500 that changes,
// with the time, from every frame end (the menus' too).
void logProgress(uint8_t *rdram, uint32_t gp)
{
const uint32_t shell = word(rdram, gp - kGpShell);
if (shell == 0u)
return;
// Story: start at a level. When a new story sets its first level (the Junkyard, nothing won yet), that level
// is replaced, before the game loads it (it does once the character is chosen); the game's own chain goes on
// from there.
{
const uint32_t progress = shell + kShellProgress;
const int level = static_cast<int32_t>(word(rdram, progress + kStoryLevel));
static int s_lastLevel = -2;
const int start = g_storyStart.load(std::memory_order_relaxed);
if (start >= 0 && level == 1 && s_lastLevel != 1 && word(rdram, progress + kGameMode) == 1u &&
word(rdram, progress + kStoryLastWon) == 0u && start != 1)
{
setWord(rdram, progress + kStoryLevel, static_cast<uint32_t>(start));
std::fprintf(stderr, "[tmb:cheats] story starts at level %s\n", kLevelNames[start]);
}
s_lastLevel = static_cast<int32_t>(word(rdram, progress + kStoryLevel));
}
static const bool s_on = std::getenv("TMB_LOG_PROGRESS") != nullptr;
if (!s_on)
return;
static uint32_t s_last[0xE0] = {};
static bool s_seen = false;
static const auto s_start = std::chrono::steady_clock::now();
const double t = std::chrono::duration<double>(std::chrono::steady_clock::now() - s_start).count();
for (uint32_t i = 0; i < 0xE0u; ++i)
{
const uint32_t value = word(rdram, shell + kShellProgress + 0x2180u + i * 4u);
if (s_seen && value != s_last[i])
std::fprintf(stderr, "[tmb:progress] t=%.1f +0x%x: %d -> %d\n", t, 0x2180u + i * 4u, static_cast<int32_t>(s_last[i]),
static_cast<int32_t>(value));
s_last[i] = value;
}
s_seen = true;
}
void onFrame(uint8_t *rdram)
{
g_rdram.store(rdram, std::memory_order_relaxed);
const uint32_t game = g_theGame.load(std::memory_order_relaxed);
if (game == 0u)
return;
// TMB_CHEATS_TOGGLE=<s> (testing): every cheat switched on and off every <s> seconds of match frames, as the
// tab would (checks that each acts while playing, not only from launch).
static const double s_toggle = []
{
const char *value = std::getenv("TMB_CHEATS_TOGGLE");
return value && *value ? std::atof(value) : 0.0;
}();
if (s_toggle > 0.0 && !bozo::det::enabled()) // deterministic mode: nothing the user does may change the run
{
const double now = std::chrono::duration<double>(std::chrono::steady_clock::now().time_since_epoch()).count();
static double s_next = now + s_toggle;
static bool s_on = false;
if (now >= s_next)
{
s_next = now + s_toggle;
s_on = !s_on;
const uint32_t all = s_on ? (1u << kMaxPlayers) - 1u : 0u;
g_infiniteHealth.store(all);
g_infiniteAmmo.store(all);
g_infiniteEnergy.store(all);
g_noAi.store(s_on);
g_enemyCap.store(s_on ? 10.0f : -1.0f);
std::fprintf(stderr, "[tmb:cheats] all cheats %s\n", s_on ? "on" : "off");
}
}
const uint32_t health = g_infiniteHealth.load(std::memory_order_relaxed), energy = g_infiniteEnergy.load(std::memory_order_relaxed);
const float playerCap = g_playerCap.load(std::memory_order_relaxed);
const int players = playerCount(rdram, game);
for (int player = 0; player < players; ++player)
{
const uint32_t car = playerVehicle(rdram, game, player);
if (car == 0u)
continue;
const float most = flt(rdram, car + kHealthMax), now = flt(rdram, car + kHealth);
// Topped up while alive (a car already dead is left to respawn).
if ((health >> player & 1u) && most > 0.0f && now > 0.0f && now < most)
setFlt(rdram, car + kHealth, most);
if (energy >> player & 1u)
setWord(rdram, car + kEnergy, word(rdram, car + kEnergyMax));
if (player == 0 && playerCap >= 0.0f)
{
static uint32_t s_frames = 0;
if (++s_frames % 250u == 0u)
std::fprintf(stderr, "[tmb:health] %.1f of %.1f\n", now, most);
if (now > playerCap)
setFlt(rdram, car + kHealth, playerCap);
}
}
const float enemyCap = g_enemyCap.load(std::memory_order_relaxed);
if (enemyCap >= 0.0f)
{
const int32_t count = std::min(static_cast<int32_t>(word(rdram, game + kVehicleCount)), 64);
static uint32_t s_enemyFrames = 0;
const bool log = ++s_enemyFrames % 500u == 0u;
std::string line;
for (int32_t index = 0; index < count; ++index)
{
const uint32_t vehicle = game + kVehicles + static_cast<uint32_t>(index) * kVehicleStride;
const float now = flt(rdram, vehicle + kHealth);
if (log)
{
char text[48];
std::snprintf(text, sizeof(text), " %x:%.0f", vehicle, now);
line += text;
}
if (word(rdram, vehicle + kDriver) != 1u && now > enemyCap)
setFlt(rdram, vehicle + kHealth, enemyCap);
}
if (log)
std::fprintf(stderr, "[tmb:enemies] TheGame %x, %d vehicles:%s\n", game, count, line.c_str());
}
// TMB_CHEATS_LOG=1: every 250 frames, each player's health, energy and weapon counts (scripted checks).
static const bool s_log = std::getenv("TMB_CHEATS_LOG") != nullptr;
static uint32_t s_logFrames = 0;
if (s_log && ++s_logFrames % 250u == 0u)
{
std::fprintf(stderr, "[tmb:cheats] weapon spends %u (%u not counted: infinite ammo)\n", g_decrements.exchange(0),
g_decrementsSkipped.exchange(0));
for (int player = 0; player < players; ++player)
{
const uint32_t car = playerVehicle(rdram, game, player);
std::string counts;
for (uint32_t slot = 1; slot <= 8; ++slot)
counts += " " + std::to_string(static_cast<int32_t>(word(rdram, car + kWeaponCounts + slot * 4u)));
std::fprintf(stderr, "[tmb:cheats] P%d car %x: health %.0f/%.0f, energy %d/%d, weapon %d, counts%s\n", player + 1, car,
flt(rdram, car + kHealth), flt(rdram, car + kHealthMax), static_cast<int32_t>(word(rdram, car + kEnergy)),
static_cast<int32_t>(word(rdram, car + kEnergyMax)), static_cast<int32_t>(word(rdram, car + 0x2140u)), counts.c_str());
}
}
}
void install(tmb::Registry &runtime)
{
g_noAi.store(std::getenv("TMB_NO_AI") && *std::getenv("TMB_NO_AI") == '1');
g_unlockAll.store(std::getenv("TMB_UNLOCK_ALL") && *std::getenv("TMB_UNLOCK_ALL") == '1');
if (const char *level = std::getenv("TMB_STORY_LEVEL"); level && *level)
g_storyStart.store(std::clamp(std::atoi(level), -1, kLevelCount - 1));
g_infiniteHealth.store(envMask("TMB_PLAYER_GOD"));
g_infiniteAmmo.store(envMask("TMB_INFINITE_AMMO"));
g_infiniteEnergy.store(envMask("TMB_INFINITE_ENERGY"));
g_enemyCap.store(envFloat("TMB_ENEMY_HEALTH_CAP"));
g_playerCap.store(envFloat("TMB_PLAYER_HEALTH_CAP"));
runtime.registerFunction(kAiUpdateInputs, &aiUpdateInputsOverride);
runtime.registerFunction(kDecrementWeaponCount, &decrementWeaponCountOverride);
runtime.registerFunction(kUiLvlSel, &shellScreenOverride<&uiLvlSel__Fv_0x1976b0>);
runtime.registerFunction(kUiCarSel, &shellScreenOverride<&uiCarSel__Fv_0x1963b0>);
runtime.registerFunction(kUiAiSel, &shellScreenOverride<&uiAiSel__Fv_0x1986a8>);
runtime.registerFunction(kUiMovies, &shellScreenOverride<&uiMovies__Fv_0x190760>);
#if defined(BOZO_SETTINGS_UI)
bozo::app::ui::registerTab("Cheats", &drawTab);
#endif
}
}
// Cheats, switched while playing from the Cheats tab of the settings window (F2), per human player; the environment
// gives their values at launch (TMB_UNLOCK_ALL, TMB_NO_AI, TMB_PLAYER_GOD, TMB_INFINITE_AMMO, TMB_INFINITE_ENERGY,
// TMB_ENEMY_HEALTH_CAP; TMB_PLAYER_HEALTH_CAP is the testing opposite, a cap on the player's health).
//
// What the game keeps, from its own code:
// - TheGame (`this` of TheGame::Update): its vehicles at TheGame + i * 0x2D00, their count at + 0x1B3DB4
// (TheGame::GetVehicleFromName); the human players' vehicles as pointers at + 0x1B28B0, their count at + 0x1B3DB8
// (TheGame::gameCheckPlayerHealth, 0x133360, which walks them).
// - A vehicle's health: float at + 0x3F4, its maximum at + 0x3F0 (gameCheckPlayerHealth's health fraction, the HUD's
// health bars). Who drives it: + 0x580, 1 a player (vehicleUpdate calls playerUpdateInputs), 2 the computer
// (aiUpdateInputs, 0x1014A0).
// - Weapons: the count of pickup weapon i (1 to 8; slot 1 is the car's special, which Launcher::FireSpecial spends)
// at + 0x22C4 + 4 * i, the weapon selected at + 0x2140; the machine gun (slot 0) has no count. Every shot,
// detonation and special spends through TheGame::DecrementWeaponCount (0x1515A8, called by FireCurrentWeapon,
// FireSpecial, UpdateSpecial, UpdateLauncher, UpdateEnvWeapon, UpdateZoomies, UpdateWeaponToggle, KillWeapon),
// which goes on to Weapons::DecrementWeaponCount (0x1BA050: count - 1, then the next weapon with ammo when it
// reaches 0).
// - Energy (the freeze / mines / shield moves of the stick combos): int at + 0x2214 of + 0x2218 (the HUD's energy
// bar, Hud::build4PEnergyBar).
// - Progress: the Shell (at 0x40BCC0, the pointer at gp - 0x4148) keeps what is locked as words at Shell + 0x18000 +
// offset, 1 locked and 0 open; Shell::Shell (0x15F270) sets a fresh save's (what loadGlobalData then overwrites
// from the card's globalFile): the vehicles at + 0x218C + 4 * car (16; uiCarSel and uiAiSel play the locked sound
// on a 1; 9-12, 14 and 15 locked at first), the levels at + 0x21CC + 4 * level (21; uiLvlSel, the same; Shell::
// EvaluateEnduranceStatus clears 2 Freeway, 15 and 18 when their endurance kills are reached), and per character its
// movies, three arrays of 14 at + 0x2220, + 0x2258, + 0x2290 (uiMovies; 2 for a movie the character does not have).
#include "bozo/state.h"
#include "tmb_port.h"
#include "bozo/app/determinism.h"
#if defined(BOZO_SETTINGS_UI)
#include "bozo/app/settings_tabs.h"
#include "imgui.h"
#endif
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
namespace tmb::cheats
{
namespace
{
constexpr uint32_t kAiUpdateInputs = 0x001014A0u;
constexpr uint32_t kAiUpdateFrozenInput = 0x001017E8u;
constexpr uint32_t kDecrementWeaponCount = 0x001515A8u;
constexpr uint32_t kVehicles = 0x00000000u, kVehicleStride = 0x2D00u, kVehicleCount = 0x001B3DB4u;
constexpr uint32_t kPlayers = 0x001B28B0u, kPlayerCount = 0x001B3DB8u;
constexpr uint32_t kHealth = 0x3F4u, kHealthMax = 0x3F0u, kDriver = 0x580u;
constexpr uint32_t kWeaponCounts = 0x22C4u, kEnergy = 0x2214u, kEnergyMax = 0x2218u;
constexpr int kMaxPlayers = 4;
constexpr uint32_t kGpShell = 0x4148u, kShellProgress = 0x18000u;
// The shell screens that read the locks, and the lock arrays (offset, count) from Shell + 0x18000.
constexpr uint32_t kUiLvlSel = 0x001976B0u, kUiCarSel = 0x001963B0u, kUiAiSel = 0x001986A8u, kUiMovies = 0x00190760u;
constexpr struct
{
uint32_t offset, count;
} kLocks[] = {{0x218Cu, 16u}, {0x21CCu, 21u}, {0x2220u, 14u}, {0x2258u, 14u}, {0x2290u, 14u}};
// One bit per player (bit 0: player 1).
std::atomic<uint32_t> g_infiniteHealth{0}, g_infiniteAmmo{0}, g_infiniteEnergy{0};
std::atomic<bool> g_noAi{false};
std::atomic<bool> g_unlockAll{false};
// Story: start at a level (-1: off). The story's state is the level being played, Shell + 0x18000 + 0x2354 (the
// index of the game's level table: GetLevelName, LoadLevelDB), the one last won at + 0x2358, the mode at
// + 0x235C (1: one-player story); a new story sets the level to 1, the Junkyard, and each level won sets the
// next (EvaluateOnePlayerStoryStatus).
std::atomic<int> g_storyStart{-1};
constexpr uint32_t kStoryLevel = 0x2354u, kStoryLastWon = 0x2358u, kGameMode = 0x235Cu;
constexpr int kLevelCount = 21;
// The levels by the level table's index (its names at 0x426070, 16 bytes each), with the card the story shows
// when it starts there (the stage, of 8). Two stages have two arenas (the story picks one); ASYLUM and ROOFTOP2
// show no card (reached from inside another level); the others are arenas the story does not use.
constexpr const char *kLevelNames[kLevelCount] = {
"Stage 2: Midtown Suburbs (SUBURB)", "Stage 1: Junkyard (JUNKYARD)", "Stage 2: Midtown Expressway 104 (FREEWAY)",
"Stage 5: Prison Passage to Blackfield Asylum (PRISON)", "Stage 7: Abandoned Skyscrapers (ROOFTOP)",
"Stage 3: Downtown Business District (CITY)", "Stage 3: Black Vista Highway (LOOP)", "Arena DEATH1", "Arena DEATH2",
"Arena DEATH3", "Arena DEATH4", "Arena DEATH5", "Arena DEATH6", "Rooftops, second part (ROOFTOP2)",
"Stage 4: Minion's Stadium (STADIUM)", "Arena SHIP", "Blackfield Asylum (ASYLUM)", "Arena MINICITY", "Arena MINIBURB",
"Arena JUNK2", "Stage 8: Warhawk's Rooftop (ROOFBOSS)"};
// The picker's order: the story's, then the rest.
constexpr int kLevelOrder[kLevelCount] = {1, 0, 2, 5, 6, 14, 3, 16, 4, 13, 20, 7, 8, 9, 10, 11, 12, 15, 17, 18, 19};
std::vector<uint32_t> g_unlocked; // the lock words Unlock everything opened (put back when it goes off)
std::atomic<float> g_enemyCap{-1.0f}; // weak enemies: every computer vehicle's health held at most this; < 0 off
std::atomic<float> g_playerCap{-1.0f}; // TMB_PLAYER_HEALTH_CAP (testing)
std::atomic<uint32_t> g_theGame{0};
std::atomic<const uint8_t *> g_rdram{nullptr}; // for the tab (onFrame's)
const std::chrono::steady_clock::time_point g_start = std::chrono::steady_clock::now(); // the log's times
std::atomic<uint32_t> g_decrements{0}, g_decrementsSkipped{0}; // TMB_CHEATS_LOG: weapon spends since the last line
uint32_t word(const uint8_t *rdram, uint32_t address)
{
uint32_t value = 0;
std::memcpy(&value, rdram + (address & 0x1FFFFFFu), 4);
return value;
}
float flt(const uint8_t *rdram, uint32_t address)
{
float value = 0.0f;
std::memcpy(&value, rdram + (address & 0x1FFFFFFu), 4);
return value;
}
void setWord(uint8_t *rdram, uint32_t address, uint32_t value) { std::memcpy(rdram + (address & 0x1FFFFFFu), &value, 4); }
void setFlt(uint8_t *rdram, uint32_t address, float value) { std::memcpy(rdram + (address & 0x1FFFFFFu), &value, 4); }
int playerCount(const uint8_t *rdram, uint32_t game)
{
return game == 0u ? 0 : std::clamp(static_cast<int32_t>(word(rdram, game + kPlayerCount)), 0, kMaxPlayers);
}
uint32_t playerVehicle(const uint8_t *rdram, uint32_t game, int player)
{
return word(rdram, game + kPlayers + static_cast<uint32_t>(player) * 4u);
}
// The players whose bit is set in `mask` that own `vehicle`.
bool forPlayer(const uint8_t *rdram, uint32_t vehicle, uint32_t mask)
{
const uint32_t game = g_theGame.load(std::memory_order_relaxed);
if (mask == 0u || vehicle == 0u)
return false;
for (int player = 0; player < playerCount(rdram, game); ++player)
if ((mask >> player & 1u) && playerVehicle(rdram, game, player) == vehicle)
return true;
return false;
}
// The players a variable names: digits 1 to 4 (TMB_INFINITE_AMMO=12: players 1 and 2), any other value but 0
// every player.
uint32_t envMask(const char *name)
{
const char *value = std::getenv(name);
if (!value || !*value || std::string(value) == "0")
return 0u;
uint32_t mask = 0u;
for (const char *c = value; *c; ++c)
{
if (*c < '1' || *c > '0' + kMaxPlayers)
return (1u << kMaxPlayers) - 1u;
mask |= 1u << (*c - '1');
}
return mask;
}
float envFloat(const char *name)
{
const char *value = std::getenv(name);
return value && *value ? static_cast<float>(std::atof(value)) : -1.0f;
}
// No AI: Vehicle::aiUpdateInputs (each computer vehicle's pad, every frame) runs the game's own
// aiUpdateFrozenInput instead (no throttle, no steering, no firing).
void aiUpdateInputsOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
if (g_noAi.load(std::memory_order_relaxed))
{
ctx->pc = kAiUpdateFrozenInput;
aiUpdateFrozenInput__7Vehicle_0x1017e8(rdram, ctx, runtime);
return;
}
aiUpdateInputs__7Vehicle_0x1014a0(rdram, ctx, runtime);
}
// Infinite ammo: TheGame::DecrementWeaponCount(game, vehicle, weapon) returns at once for a player who has it,
// so nothing the car fires or detonates is counted (and the selected weapon stays).
void decrementWeaponCountOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
g_decrements.fetch_add(1, std::memory_order_relaxed);
static const bool s_log = std::getenv("TMB_CHEATS_LOG") != nullptr;
if (s_log && word(rdram, getRegU32(ctx, 5) + kDriver) == 1u)
std::fprintf(stderr, "[tmb:cheats] %.1f s: player car %x spends weapon %u (count %d)%s\n",
std::chrono::duration<double>(std::chrono::steady_clock::now() - g_start).count(), getRegU32(ctx, 5), getRegU32(ctx, 6),
static_cast<int32_t>(word(rdram, getRegU32(ctx, 5) + kWeaponCounts + getRegU32(ctx, 6) * 4u)),
forPlayer(rdram, getRegU32(ctx, 5), g_infiniteAmmo.load(std::memory_order_relaxed)) ? ", not counted" : "");
if (forPlayer(rdram, getRegU32(ctx, 5), g_infiniteAmmo.load(std::memory_order_relaxed)))
{
g_decrementsSkipped.fetch_add(1, std::memory_order_relaxed);
ctx->pc = getRegU32(ctx, 31); // jr $ra
return;
}
DecrementWeaponCount__7TheGameP7Vehiclei_0x1515a8(rdram, ctx, runtime);
}
// Unlock everything: every lock word still 1 opened; off, the ones it opened closed again (the game's own unlocks
// since then stay, the card is written only when the player saves).
void applyUnlocks(uint8_t *rdram, uint32_t gp)
{
const uint32_t shell = word(rdram, gp - kGpShell);
if (shell == 0u)
return;
const uint32_t progress = shell + kShellProgress;
if (g_unlockAll.load(std::memory_order_relaxed))
{
for (const auto &locks : kLocks)
for (uint32_t i = 0; i < locks.count; ++i)
{
const uint32_t address = progress + locks.offset + i * 4u;
if (word(rdram, address) == 1u)
{
setWord(rdram, address, 0u);
g_unlocked.push_back(address);
}
}
}
else if (!g_unlocked.empty())
{
for (const uint32_t address : g_unlocked)
if (word(rdram, address) == 0u)
setWord(rdram, address, 1u);
g_unlocked.clear();
}
}
template <void (*Screen)(uint8_t *, R5900Context *, PS2Runtime *)>
void shellScreenOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
applyUnlocks(rdram, getRegU32(ctx, 28));
Screen(rdram, ctx, runtime);
}
#if defined(BOZO_SETTINGS_UI)
void perPlayer(const char *label, std::atomic<uint32_t> &flags, int players)
{
ImGui::PushID(label);
uint32_t mask = flags.load(std::memory_order_relaxed);
// On for every player of the match (every player when there is none yet).
const uint32_t present = players > 0 ? (1u << players) - 1u : (1u << kMaxPlayers) - 1u;
bool all = (mask & present) == present;
if (ImGui::Checkbox(label, &all))
mask = all ? (1u << kMaxPlayers) - 1u : 0u;
for (int player = 0; player < std::max(players, 1); ++player)
{
ImGui::SameLine(player == 0 ? 220.0f : 0.0f);
bool on = mask >> player & 1u;
char name[8];
std::snprintf(name, sizeof(name), "P%d", player + 1);
if (ImGui::Checkbox(name, &on))
mask = on ? mask | 1u << player : mask & ~(1u << player);
}
flags.store(mask, std::memory_order_relaxed);
ImGui::PopID();
}
void drawTab()
{
const uint8_t *rdram = g_rdram.load(std::memory_order_relaxed);
const uint32_t game = g_theGame.load(std::memory_order_relaxed);
const int players = rdram ? playerCount(rdram, game) : 0;
ImGui::TextDisabled(players ? "In a match: %d player(s). Changes apply at once." : "They act in a match.", players);
bool unlock = g_unlockAll.load(std::memory_order_relaxed);
if (ImGui::Checkbox("Unlock everything (levels, vehicles, movies)", &unlock))
g_unlockAll.store(unlock, std::memory_order_relaxed);
ImGui::TextDisabled("Opened in the menus; saving the game while it is on keeps them on the card.");
int start = g_storyStart.load(std::memory_order_relaxed);
ImGui::SetNextItemWidth(420.0f);
if (ImGui::BeginCombo("Story: start at", start < 0 ? "the first level (as the game)" : kLevelNames[start]))
{
if (ImGui::Selectable("the first level (as the game)", start < 0))
start = -1;
for (const int i : kLevelOrder)
if (ImGui::Selectable(kLevelNames[i], start == i))
start = i;
ImGui::EndCombo();
}
g_storyStart.store(start, std::memory_order_relaxed);
ImGui::TextDisabled("For testing: a new story begins at this level, then goes on as the game chains them.");
ImGui::SeparatorText("Players");
perPlayer("Infinite health", g_infiniteHealth, players);
perPlayer("Infinite ammo", g_infiniteAmmo, players);
perPlayer("Infinite energy", g_infiniteEnergy, players);
ImGui::TextDisabled("Health and energy held at their maximum; weapons and specials not spent.");
ImGui::SeparatorText("Opponents");
bool noAi = g_noAi.load(std::memory_order_relaxed);
if (ImGui::Checkbox("No AI (the computer's cars do nothing)", &noAi))
g_noAi.store(noAi, std::memory_order_relaxed);
float cap = g_enemyCap.load(std::memory_order_relaxed);
bool weak = cap >= 0.0f;
if (ImGui::Checkbox("Weak enemies", &weak))
cap = weak ? 10.0f : -1.0f;
if (weak)
{
ImGui::SameLine();
ImGui::SetNextItemWidth(200.0f);
ImGui::SliderFloat("health at most", &cap, 1.0f, 300.0f, "%.0f", ImGuiSliderFlags_Logarithmic);
}
g_enemyCap.store(cap, std::memory_order_relaxed);
if (rdram && players)
{
const uint32_t car = playerVehicle(rdram, game, 0);
ImGui::TextDisabled("Player 1: health %.0f of %.0f, energy %d of %d", flt(rdram, car + kHealth), flt(rdram, car + kHealthMax),
static_cast<int32_t>(word(rdram, car + kEnergy)), static_cast<int32_t>(word(rdram, car + kEnergyMax)));
}
}
#endif
}
void setTheGame(uint32_t game) { g_theGame.store(game, std::memory_order_relaxed); }
// The Cheats tab's switches, for the game's own Options screen (runtime/tmb_menu.cpp): read, and set at once.
struct Values
{
bool unlockAll = false, noAi = false;
uint32_t health = 0u, ammo = 0u, energy = 0u; // one bit per player
float enemyCap = -1.0f; // weak enemies: < 0 off
};
Values values()
{
Values v;
v.unlockAll = g_unlockAll.load(std::memory_order_relaxed);
v.noAi = g_noAi.load(std::memory_order_relaxed);
v.health = g_infiniteHealth.load(std::memory_order_relaxed);
v.ammo = g_infiniteAmmo.load(std::memory_order_relaxed);
v.energy = g_infiniteEnergy.load(std::memory_order_relaxed);
v.enemyCap = g_enemyCap.load(std::memory_order_relaxed);
return v;
}
void setValues(const Values &v)
{
g_unlockAll.store(v.unlockAll, std::memory_order_relaxed);
g_noAi.store(v.noAi, std::memory_order_relaxed);
g_infiniteHealth.store(v.health, std::memory_order_relaxed);
g_infiniteAmmo.store(v.ammo, std::memory_order_relaxed);
g_infiniteEnergy.store(v.energy, std::memory_order_relaxed);
g_enemyCap.store(v.enemyCap, std::memory_order_relaxed);
}
// Once a frame (timerEndOfRealTimeProcessing, the frame's processing done).
// TMB_LOG_PROGRESS=1 (finding the story's state): each word of Shell + 0x18000 + 0x2180 to + 0x2500 that changes,
// with the time, from every frame end (the menus' too).
void logProgress(uint8_t *rdram, uint32_t gp)
{
const uint32_t shell = word(rdram, gp - kGpShell);
if (shell == 0u)
return;
// Story: start at a level. When a new story sets its first level (the Junkyard, nothing won yet), that level
// is replaced, before the game loads it (it does once the character is chosen); the game's own chain goes on
// from there.
{
const uint32_t progress = shell + kShellProgress;
const int level = static_cast<int32_t>(word(rdram, progress + kStoryLevel));
static int s_lastLevel = -2;
const int start = g_storyStart.load(std::memory_order_relaxed);
if (start >= 0 && level == 1 && s_lastLevel != 1 && word(rdram, progress + kGameMode) == 1u &&
word(rdram, progress + kStoryLastWon) == 0u && start != 1)
{
setWord(rdram, progress + kStoryLevel, static_cast<uint32_t>(start));
std::fprintf(stderr, "[tmb:cheats] story starts at level %s\n", kLevelNames[start]);
}
s_lastLevel = static_cast<int32_t>(word(rdram, progress + kStoryLevel));
}
static const bool s_on = std::getenv("TMB_LOG_PROGRESS") != nullptr;
if (!s_on)
return;
static uint32_t s_last[0xE0] = {};
static bool s_seen = false;
static const auto s_start = std::chrono::steady_clock::now();
const double t = std::chrono::duration<double>(std::chrono::steady_clock::now() - s_start).count();
for (uint32_t i = 0; i < 0xE0u; ++i)
{
const uint32_t value = word(rdram, shell + kShellProgress + 0x2180u + i * 4u);
if (s_seen && value != s_last[i])
std::fprintf(stderr, "[tmb:progress] t=%.1f +0x%x: %d -> %d\n", t, 0x2180u + i * 4u, static_cast<int32_t>(s_last[i]),
static_cast<int32_t>(value));
s_last[i] = value;
}
s_seen = true;
}
void onFrame(uint8_t *rdram)
{
g_rdram.store(rdram, std::memory_order_relaxed);
const uint32_t game = g_theGame.load(std::memory_order_relaxed);
if (game == 0u)
return;
// TMB_CHEATS_TOGGLE=<s> (testing): every cheat switched on and off every <s> seconds of match frames, as the
// tab would (checks that each acts while playing, not only from launch).
static const double s_toggle = []
{
const char *value = std::getenv("TMB_CHEATS_TOGGLE");
return value && *value ? std::atof(value) : 0.0;
}();
if (s_toggle > 0.0 && !bozo::det::enabled()) // deterministic mode: nothing the user does may change the run
{
const double now = std::chrono::duration<double>(std::chrono::steady_clock::now().time_since_epoch()).count();
static double s_next = now + s_toggle;
static bool s_on = false;
if (now >= s_next)
{
s_next = now + s_toggle;
s_on = !s_on;
const uint32_t all = s_on ? (1u << kMaxPlayers) - 1u : 0u;
g_infiniteHealth.store(all);
g_infiniteAmmo.store(all);
g_infiniteEnergy.store(all);
g_noAi.store(s_on);
g_enemyCap.store(s_on ? 10.0f : -1.0f);
std::fprintf(stderr, "[tmb:cheats] all cheats %s\n", s_on ? "on" : "off");
}
}
const uint32_t health = g_infiniteHealth.load(std::memory_order_relaxed), energy = g_infiniteEnergy.load(std::memory_order_relaxed);
const float playerCap = g_playerCap.load(std::memory_order_relaxed);
const int players = playerCount(rdram, game);
for (int player = 0; player < players; ++player)
{
const uint32_t car = playerVehicle(rdram, game, player);
if (car == 0u)
continue;
const float most = flt(rdram, car + kHealthMax), now = flt(rdram, car + kHealth);
// Topped up while alive (a car already dead is left to respawn).
if ((health >> player & 1u) && most > 0.0f && now > 0.0f && now < most)
setFlt(rdram, car + kHealth, most);
if (energy >> player & 1u)
setWord(rdram, car + kEnergy, word(rdram, car + kEnergyMax));
if (player == 0 && playerCap >= 0.0f)
{
static uint32_t s_frames = 0;
if (++s_frames % 250u == 0u)
std::fprintf(stderr, "[tmb:health] %.1f of %.1f\n", now, most);
if (now > playerCap)
setFlt(rdram, car + kHealth, playerCap);
}
}
const float enemyCap = g_enemyCap.load(std::memory_order_relaxed);
if (enemyCap >= 0.0f)
{
const int32_t count = std::min(static_cast<int32_t>(word(rdram, game + kVehicleCount)), 64);
static uint32_t s_enemyFrames = 0;
const bool log = ++s_enemyFrames % 500u == 0u;
std::string line;
for (int32_t index = 0; index < count; ++index)
{
const uint32_t vehicle = game + kVehicles + static_cast<uint32_t>(index) * kVehicleStride;
const float now = flt(rdram, vehicle + kHealth);
if (log)
{
char text[48];
std::snprintf(text, sizeof(text), " %x:%.0f", vehicle, now);
line += text;
}
if (word(rdram, vehicle + kDriver) != 1u && now > enemyCap)
setFlt(rdram, vehicle + kHealth, enemyCap);
}
if (log)
std::fprintf(stderr, "[tmb:enemies] TheGame %x, %d vehicles:%s\n", game, count, line.c_str());
}
// TMB_CHEATS_LOG=1: every 250 frames, each player's health, energy and weapon counts (scripted checks).
static const bool s_log = std::getenv("TMB_CHEATS_LOG") != nullptr;
static uint32_t s_logFrames = 0;
if (s_log && ++s_logFrames % 250u == 0u)
{
std::fprintf(stderr, "[tmb:cheats] weapon spends %u (%u not counted: infinite ammo)\n", g_decrements.exchange(0),
g_decrementsSkipped.exchange(0));
for (int player = 0; player < players; ++player)
{
const uint32_t car = playerVehicle(rdram, game, player);
std::string counts;
for (uint32_t slot = 1; slot <= 8; ++slot)
counts += " " + std::to_string(static_cast<int32_t>(word(rdram, car + kWeaponCounts + slot * 4u)));
std::fprintf(stderr, "[tmb:cheats] P%d car %x: health %.0f/%.0f, energy %d/%d, weapon %d, counts%s\n", player + 1, car,
flt(rdram, car + kHealth), flt(rdram, car + kHealthMax), static_cast<int32_t>(word(rdram, car + kEnergy)),
static_cast<int32_t>(word(rdram, car + kEnergyMax)), static_cast<int32_t>(word(rdram, car + 0x2140u)), counts.c_str());
}
}
}
void install(tmb::Registry &runtime)
{
g_noAi.store(std::getenv("TMB_NO_AI") && *std::getenv("TMB_NO_AI") == '1');
g_unlockAll.store(std::getenv("TMB_UNLOCK_ALL") && *std::getenv("TMB_UNLOCK_ALL") == '1');
if (const char *level = std::getenv("TMB_STORY_LEVEL"); level && *level)
g_storyStart.store(std::clamp(std::atoi(level), -1, kLevelCount - 1));
g_infiniteHealth.store(envMask("TMB_PLAYER_GOD"));
g_infiniteAmmo.store(envMask("TMB_INFINITE_AMMO"));
g_infiniteEnergy.store(envMask("TMB_INFINITE_ENERGY"));
g_enemyCap.store(envFloat("TMB_ENEMY_HEALTH_CAP"));
g_playerCap.store(envFloat("TMB_PLAYER_HEALTH_CAP"));
runtime.registerFunction(kAiUpdateInputs, &aiUpdateInputsOverride);
runtime.registerFunction(kDecrementWeaponCount, &decrementWeaponCountOverride);
runtime.registerFunction(kUiLvlSel, &shellScreenOverride<&uiLvlSel__Fv_0x1976b0>);
runtime.registerFunction(kUiCarSel, &shellScreenOverride<&uiCarSel__Fv_0x1963b0>);
runtime.registerFunction(kUiAiSel, &shellScreenOverride<&uiAiSel__Fv_0x1986a8>);
runtime.registerFunction(kUiMovies, &shellScreenOverride<&uiMovies__Fv_0x190760>);
#if defined(BOZO_SETTINGS_UI)
bozo::app::ui::registerTab("Cheats", &drawTab);
#endif
}
// Save states (tmb_state.cpp): the lock words Unlock everything opened (put back when it goes off).
void state(bozo::state::Archive &a) { bozo::state::io(a, g_unlocked); }
}
+900
View File
@@ -0,0 +1,900 @@
// PC SETTINGS in the game's own Options screen (a ninth line under the game's eight) and in its pause menu (a line under
// its own, below), and behind it pages drawn with the
// game's font and steered with the pad, for what the settings window (F2) offers besides the controls: Video (the
// window's settings, applied and saved to video.ini; widescreen: runtime/tmb_widescreen.cpp), Cheats
// (runtime/tmb_cheats.cpp's switches, at once) and Save states (the slot, load, save), and QUIT GAME (a second Cross
// ends the game). The controls stay in F2.
//
// The Options screen (uiOptions, 0x1911F0, screen 10 of uiMain's table; one call a frame), from its code:
// - Its cursor is options_main_line (0x4FB2F4), 0 to 7 (DIFFICULTY ... SAVE SETTINGS TO MEMORY CARD); options_subScreen
// (0x4FB2F0) is 0 on that page (1 the controls, 2 the brightness). Up and Down wrap the cursor (0x1915AC, 0x1915E8:
// 0 - 1 gives 7, 7 + 1 gives 0) from the button flags uiGetInput (0x199880, called at 0x191284) sets that frame, one
// press one flag (up 0x4FB368, down 0x4FB36C, left 0x4FB360, right 0x4FB364, square 0x4FB370, triangle 0x4FB374,
// circle 0x4FB378, cross 0x4FB37C). Every other use of the cursor compares it with a line, so 8 matches none: no line
// is highlighted and no line's handler runs. The game puts it back to 0 when the screen ends (0x191338).
// - Cross on a line without a handler of its own accepts the settings and leaves (0x1923D4); Triangle restores them and
// leaves, Square sets the defaults.
// - The lines: x 0x320, y 0x550 + 0x210 a line in 12.4 sub-pixels from the view's corner, through fontSetColor,
// fontSetCharSizesInSubPixels, fontSetCursorAtSubPixel and fontSpritePrint on font 0; the selected line in
// (0x60, 0x4C, 0x36) at sizes (307, 332, -48, 48), the others in (0x30, 0x26, 0x1C) at (288, 312, -48, 48); the title
// centred at (0x1400, 0x100) in (0x29, 0x1E, 0x0E). The sounds: playShellSFXSound(shell + 0x1A144, n), 0 down, 1 up,
// 2 accept, 3 back, 5 a value changed.
//
// Here: uiGetInput's override, when the Options page called it, lets the cursor reach 8 (Down on 7, Up on 0) and takes
// Cross on 8; uiOptions' override draws the line after the game's page, and while the pages are open draws them
// instead of the game's (the 3D shell behind them stays the game's; its sliders hidden by the game's blankSliders, as
// its controls page does). The pages read the pad through the game's uiGetInput and draw through the game's font
// functions, so they look and answer as the game's, on a copy of the context (Guest, below). Its legend (X apply all,
// Triangle cancel, Square default) stays the game's: Cross acts, Triangle backs out. The lines' text uses the font's
// glyphs (capitals, digits, space, ( ) and -; no apostrophe). A save state's load closes the pages (stateLoaded).
//
// Only where the game's graphics are native (every free run): the reference checker runs the game's own code.
#include "tmb_port.h"
#include "tmb_menu.h"
#include <algorithm>
#include <chrono>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <initializer_list>
#include <mutex>
#include <string>
#include <vector>
namespace tmb::cheats
{
struct Values
{
bool unlockAll = false, noAi = false;
uint32_t health = 0u, ammo = 0u, energy = 0u;
float enemyCap = -1.0f;
};
Values values();
void setValues(const Values &v);
}
namespace tmb::menu
{
namespace
{
constexpr uint32_t kUiOptions = 0x001911F0u, kUiGetInput = 0x00199880u, kOptionsInputReturn = 0x0019128Cu;
constexpr uint32_t kFontSetColor = 0x001C4258u, kFontSetSizes = 0x001C4700u, kFontSetCursor = 0x001C47B8u,
kFontPrint = 0x001C47D8u, kFontPrintCentered = 0x001C4568u, kPlaySound = 0x00179720u,
kBlankSliders = 0x0019DE38u;
// The pause menu (pauseLevelOverlay 0x166960, in displayDialog's own loop; types 0 and 16 the pause).
constexpr uint32_t kPauseOverlay = 0x00166960u, kMenuSelection = 0x00167AF8u, kPauseExit = 0x00167670u,
kPauseSelectionReturn = 0x00166AE4u, kPauseExitReturn = 0x00166D64u, kPauseReturn0 = 0x001637E4u,
kPauseReturn16 = 0x001637F4u;
constexpr uint32_t kSetMenuFont = 0x00167810u, kSetTitleFont = 0x00167AC8u, kFontSetSize = 0x001C4330u,
kFontPrintXY = 0x001C44A8u, kFontPrintCenteredXY = 0x001C44D8u, kPlayRtSound = 0x00179768u,
kInputGetInput = 0x001D8770u, kInputGetPlayerPad = 0x001D8658u;
constexpr uint32_t kCurrentMenuSelection = 0x004FAD30u, kPlayerThatPaused = 0x004FAE64u;
constexpr uint32_t kScreen = 0x004FB144u, kTransitioning = 0x004FB1ACu, kSubScreen = 0x004FB2F0u, kLine = 0x004FB2F4u;
constexpr uint32_t kShellPointer = 0x004FAD28u, kShellSound = 0x1A144u;
constexpr uint32_t kLeft = 0x004FB360u, kRight = 0x004FB364u, kUp = 0x004FB368u, kDown = 0x004FB36Cu,
kTriangle = 0x004FB374u, kCircle = 0x004FB378u, kCross = 0x004FB37Cu;
// The flags a leaving page sets (still_processing_triangle, _x, _x_main_options, _x_controls, _x_brightness).
constexpr uint32_t kBusy[] = {0x004FB2FCu, 0x004FB300u, 0x004FB304u, 0x004FB308u, 0x004FB30Cu};
constexpr uint32_t kOptionsScreen = 10u, kLastLine = 7u, kPcLine = 8u;
constexpr int32_t kLineX = 0x320, kPcLineY = 0x17C0;
constexpr int kSoundDown = 0, kSoundUp = 1, kSoundAccept = 2, kSoundBack = 3, kSoundValue = 5;
std::mutex g_hooksMutex;
Hooks g_hooks; // under g_hooksMutex
Hooks hooks()
{
std::lock_guard lock(g_hooksMutex);
return g_hooks;
}
uint32_t word(const uint8_t *rdram, uint32_t address)
{
uint32_t value;
std::memcpy(&value, rdram + (address & 0x1FFFFFCu), 4);
return value;
}
void setWord(uint8_t *rdram, uint32_t address, uint32_t value) { std::memcpy(rdram + (address & 0x1FFFFFCu), &value, 4); }
// The game's functions called from an override, with their arguments in a0..a3, t0, on a copy of the thread's
// context (BozoEngine kernel.md section 3b, "Guest code on an override's own context"): guest code there never
// leaves the override (an event due waits for the thread's own code), so the override's own code after each
// call runs on the game's state as that call left it, and the thread's registers are never touched. The copy's
// stack starts 0x200 bytes below the thread's (the callees' frames go below that); the strings printed go in
// the free space between the two.
struct Guest
{
uint8_t *rdram;
PS2Runtime *rt;
R5900Context copy;
uint32_t text = 0u;
bool pause = false; // the pause menu's pages: its pad, sounds and fonts (pixels, not sub-pixels)
Guest(uint8_t *memory, const R5900Context *ctx, PS2Runtime *runtime) : rdram(memory), rt(runtime), copy(*ctx)
{
const uint32_t frame = (getRegU32(ctx, 29) - 0x200u) & ~0xFu;
SET_GPR_U32(&copy, 29, frame);
copy.leaving = 0;
text = (frame + 0x20u) & 0x1FFFFFFu;
}
void call(void (*fn)(uint8_t *, R5900Context *, Runtime *), uint32_t address, std::initializer_list<uint32_t> args)
{
static constexpr int kArgs[] = {4, 5, 6, 7, 8};
int i = 0;
for (const uint32_t a : args)
SET_GPR_U32(&copy, kArgs[i++], a);
copy.pc = address;
fn(rdram, &copy, rt);
}
uint32_t result() const { return getRegU32(&copy, 2); }
uint32_t string(const std::string &s)
{
const size_t n = std::min<size_t>(s.size(), 255u);
std::memcpy(rdram + text, s.data(), n);
rdram[text + n] = 0;
return text;
}
void sound(int which)
{
if (pause)
{
// The pause's own sounds (getCurrentMenuSelection, checkInputForPauseExit): 0x2C down, 0x2B up,
// 0x2A accept.
const uint32_t code = which == kSoundDown || which == kSoundValue ? 0x2Cu : which == kSoundAccept ? 0x2Au : 0x2Bu;
call(&playRTShellSound__Fi_0x179768, kPlayRtSound, {code});
return;
}
const uint32_t shell = word(rdram, kShellPointer);
if (shell != 0u)
call(&playShellSFXSound__10ShellSoundi_0x179720, kPlaySound, {shell + kShellSound, static_cast<uint32_t>(which)});
}
void color(uint32_t r, uint32_t g, uint32_t b) { call(&fontSetColor__Fiiii_0x1c4258, kFontSetColor, {0u, r, g, b}); }
// The game's two sizes (the selected line 1.6 times the font's 12 x 13, the others 1.5), times `scale`:
// fontSetCharSizesInSubPixels(font, width, height, -48, 48), as uiOptions sets them.
void sizes(bool large, float scale = 1.0f)
{
const float k = (large ? 1.6f : 1.5f) * scale;
call(&fontSetCharSizesInSubPixels__Fiiiii_0x1c4700, kFontSetSizes,
{0u, static_cast<uint32_t>(std::lround(12.0f * k * 16.0f)), static_cast<uint32_t>(std::lround(13.0f * k * 16.0f)),
static_cast<uint32_t>(-48), 48u});
}
void print(int32_t x, int32_t y, const std::string &s)
{
call(&fontSetCursorAtSubPixel__Fiii_0x1c47b8, kFontSetCursor, {0u, static_cast<uint32_t>(x), static_cast<uint32_t>(y)});
call(&fontSpritePrint__FiPc_0x1c47d8, kFontPrint, {0u, string(s)});
}
// Centred on x, as the game centres its values: the cursor set, then fontSpritePrintCentered.
void printCentered(int32_t x, int32_t y, const std::string &s)
{
call(&fontSetCursorAtSubPixel__Fiii_0x1c47b8, kFontSetCursor, {0u, static_cast<uint32_t>(x), static_cast<uint32_t>(y)});
call(&fontSpritePrintCentered__FiPc_0x1c4568, kFontPrintCentered, {0u, string(s)});
}
void title(const std::string &s)
{
color(0x29u, 0x1Eu, 0x0Eu);
sizes(true);
call(&fontSetCursorAtSubPixel__Fiii_0x1c47b8, kFontSetCursor, {0u, 0x1400u, 0x100u});
call(&fontSpritePrintCentered__FiPc_0x1c4568, kFontPrintCentered, {0u, string(s)});
}
};
void setSizes(Guest &g, bool large, float scale) { g.sizes(large, scale); }
bool active(PS2Runtime *rt) { return bozo::port::nativeGraphics(rt); }
bool optionsPageIdle(const uint8_t *rdram)
{
if (word(rdram, kScreen) != kOptionsScreen || word(rdram, kSubScreen) != 0u || word(rdram, kTransitioning) != 0u)
return false;
for (const uint32_t flag : kBusy)
if (word(rdram, flag) != 0u)
return false;
return true;
}
// ---- The pages ----
enum class Page
{
Closed,
Top,
Video,
Cheats,
States
};
struct Row
{
std::string label;
std::string value; // "" a line Cross acts on
bool info = false; // a line the cursor skips
};
struct Menu
{
Page page = Page::Closed;
int line = 0;
Page lastTop = Page::Video;
bozo::app::video::Settings video; // the Video page's edits (Apply and save sends them)
std::vector<std::pair<int, int>> resolutions;
int monitorRefresh = 0;
std::string status; // a line under the page: what Cross did
bool quitArmed = false; // QUIT GAME pressed once: a second Cross quits
bool inPause = false; // opened from the pause menu (its style and pad), not the Options screen
} g_menu;
std::string upper(std::string s)
{
for (char &c : s)
c = static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
return s;
}
template <typename T> int indexOf(const std::vector<T> &list, const T &value, int fallback = 0)
{
for (size_t i = 0; i < list.size(); ++i)
if (list[i] == value)
return static_cast<int>(i);
return fallback;
}
template <typename T> T step(const std::vector<T> &list, const T &value, int delta)
{
const int n = static_cast<int>(list.size());
const int i = indexOf(list, value, delta > 0 ? -1 : 0);
return list[static_cast<size_t>(((i + delta) % n + n) % n)];
}
// Video.
const std::vector<int> kModes = {0, 1, 2};
const std::vector<float> kScales = {0.5f, 0.75f, 1.0f, 1.5f, 2.0f};
const std::vector<int> kUpscales = {1, 2, 4};
const std::vector<int> kSmoothings = {0, 1, 2, 4, 8, 16};
const std::vector<int> kAntiAliasings = {0, 2, 4, 8};
const std::vector<int> kFastForwards = {200, 300, 400, 0};
std::string modeText(bozo::app::video::WindowMode m)
{
switch (m)
{
case bozo::app::video::WindowMode::Fullscreen: return "FULLSCREEN";
case bozo::app::video::WindowMode::Borderless: return "BORDERLESS";
default: return "WINDOWED";
}
}
std::string scaleText(float s)
{
char text[16];
std::snprintf(text, sizeof(text), "%d", static_cast<int>(std::lround(s * 100.0f)));
return std::string(text) + " PERCENT";
}
std::string timesText(int n) { return std::to_string(n) + "X"; }
std::string onOff(bool on) { return on ? "ON" : "OFF"; }
bool packOn(const std::string &pack) { return pack != "off" && pack != "0"; }
std::vector<int> frameRates(const Menu &m)
{
std::vector<int> rates = {0, -1};
if (m.video.frameRate > 0)
rates.push_back(m.video.frameRate);
return rates;
}
std::string frameRateText(int rate, int refresh)
{
if (rate == 0)
return "60 (GAME)";
if (rate < 0)
return refresh > 0 ? "MONITOR (" + std::to_string(refresh) + ")" : "MONITOR";
return std::to_string(rate);
}
enum VideoLine
{
VMode,
VResolution,
VScale,
VFrameRate,
VAntiAliasing,
VSmoothing,
VUpscale,
VFilter,
VPack,
VWide,
VPause,
VFast,
VApply,
VCount
};
std::vector<Row> videoRows(const Menu &m, const Hooks &h)
{
const auto &v = m.video;
std::vector<Row> rows(VCount);
rows[VMode] = {"DISPLAY", modeText(v.mode)};
rows[VResolution] = {"RESOLUTION", std::to_string(v.width) + " X " + std::to_string(v.height)};
rows[VScale] = {"RENDER SCALE", scaleText(v.renderScale)};
rows[VFrameRate] = {"FRAME RATE", frameRateText(v.frameRate, m.monitorRefresh)};
rows[VAntiAliasing] = {"ANTIALIASING", v.antiAliasing ? timesText(v.antiAliasing) : "OFF"};
rows[VSmoothing] = {"TEXTURE SMOOTHING", v.textureSmoothing == 0 ? "OFF" : v.textureSmoothing == 1 ? "TRILINEAR"
: timesText(v.textureSmoothing)};
rows[VUpscale] = {"TEXTURE UPSCALING", v.textureUpscale.factor > 1 ? timesText(v.textureUpscale.factor) : "OFF"};
rows[VFilter] = {"UPSCALING FILTER", v.textureUpscale.filter == bozo::render::UpscaleFilter::Smooth ? "SMOOTH" : "EDGE"};
const bool pack = h.texturePackFolder && !h.texturePackFolder(packOn(v.texturePack) ? v.texturePack : "").empty();
rows[VPack] = {"TEXTURE PACK", pack ? onOff(packOn(v.texturePack)) : "NONE"};
rows[VWide] = {"WIDESCREEN", onOff(v.widescreen)};
rows[VPause] = {"PAUSE IN BACKGROUND", onOff(v.pauseInBackground)};
rows[VFast] = {"FAST FORWARD", v.fastForward == 0 ? "UNLIMITED" : timesText(v.fastForward / 100)};
rows[VApply] = {"APPLY AND SAVE", ""};
return rows;
}
bool videoChange(Menu &m, int line, int delta)
{
auto &v = m.video;
switch (line)
{
case VMode:
v.mode = static_cast<bozo::app::video::WindowMode>(step(kModes, static_cast<int>(v.mode), delta));
return true;
case VResolution:
{
if (m.resolutions.empty())
return false;
const auto next = step(m.resolutions, std::make_pair(v.width, v.height), delta);
v.width = next.first, v.height = next.second;
return true;
}
case VScale:
{
int i = 2;
for (size_t k = 0; k < kScales.size(); ++k)
if (std::fabs(v.renderScale - kScales[k]) < 0.01f)
i = static_cast<int>(k);
const int n = static_cast<int>(kScales.size());
v.renderScale = kScales[static_cast<size_t>(((i + delta) % n + n) % n)];
return true;
}
case VFrameRate: v.frameRate = step(frameRates(m), v.frameRate, delta); return true;
case VAntiAliasing: v.antiAliasing = step(kAntiAliasings, v.antiAliasing, delta); return true;
case VSmoothing: v.textureSmoothing = step(kSmoothings, v.textureSmoothing, delta); return true;
case VUpscale:
v.textureUpscale.factor = static_cast<uint8_t>(step(kUpscales, static_cast<int>(v.textureUpscale.factor), delta));
return true;
case VFilter:
v.textureUpscale.filter = v.textureUpscale.filter == bozo::render::UpscaleFilter::Smooth ? bozo::render::UpscaleFilter::Edge
: bozo::render::UpscaleFilter::Smooth;
return true;
case VPack:
{
static std::string s_lastOn; // the folder a set texture_pack named, given back when turned on again
if (packOn(v.texturePack) && !v.texturePack.empty())
s_lastOn = v.texturePack;
const Hooks h = hooks();
if (!h.texturePackFolder || h.texturePackFolder(packOn(v.texturePack) ? v.texturePack : s_lastOn).empty())
return false;
v.texturePack = packOn(v.texturePack) ? "off" : s_lastOn;
return true;
}
case VWide: v.widescreen = !v.widescreen; return true;
case VPause: v.pauseInBackground = !v.pauseInBackground; return true;
case VFast: v.fastForward = step(kFastForwards, v.fastForward, delta); return true;
default: return false;
}
}
// Cheats.
enum CheatLine
{
CUnlock,
CHealth,
CAmmo,
CEnergy,
CNoAi,
CWeak,
CCount
};
const std::vector<uint32_t> kMasks = {0u, 1u, 0xFu};
const std::vector<float> kCaps = {-1.0f, 10.0f, 25.0f, 50.0f, 100.0f};
std::string maskText(uint32_t mask)
{
if (mask == 0u)
return "OFF";
if (mask == 1u)
return "PLAYER 1";
if ((mask & 0xFu) == 0xFu)
return "ALL PLAYERS";
std::string players = "PLAYERS";
for (int p = 0; p < 4; ++p)
if (mask >> p & 1u)
players += " " + std::to_string(p + 1);
return players;
}
std::vector<Row> cheatRows()
{
const cheats::Values c = cheats::values();
std::vector<Row> rows(CCount);
rows[CUnlock] = {"UNLOCK EVERYTHING", onOff(c.unlockAll)};
rows[CHealth] = {"INFINITE HEALTH", maskText(c.health)};
rows[CAmmo] = {"INFINITE AMMO", maskText(c.ammo)};
rows[CEnergy] = {"INFINITE ENERGY", maskText(c.energy)};
rows[CNoAi] = {"NO AI", onOff(c.noAi)};
rows[CWeak] = {"WEAK ENEMIES", c.enemyCap < 0.0f ? "OFF" : "HEALTH " + std::to_string(static_cast<int>(std::lround(c.enemyCap)))};
return rows;
}
bool cheatChange(int line, int delta)
{
cheats::Values c = cheats::values();
const auto mask = [&](uint32_t &m) { m = step(kMasks, m, delta); };
switch (line)
{
case CUnlock: c.unlockAll = !c.unlockAll; break;
case CHealth: mask(c.health); break;
case CAmmo: mask(c.ammo); break;
case CEnergy: mask(c.energy); break;
case CNoAi: c.noAi = !c.noAi; break;
case CWeak:
{
int i = c.enemyCap < 0.0f ? 0 : 1;
for (size_t k = 1; k < kCaps.size(); ++k)
if (std::fabs(c.enemyCap - kCaps[k]) < 0.5f)
i = static_cast<int>(k);
const int n = static_cast<int>(kCaps.size());
c.enemyCap = kCaps[static_cast<size_t>(((i + delta) % n + n) % n)];
break;
}
default: return false;
}
cheats::setValues(c);
return true;
}
// Save states.
enum StateLine
{
SSlot,
SSummary,
SLoad,
SSave,
SCount
};
std::vector<Row> stateRows(const Hooks &h)
{
const int slot = h.stateSlot ? h.stateSlot() : 0;
std::string summary = h.slotSummary ? upper(h.slotSummary(slot)) : "";
if (const size_t colon = summary.find(": "); colon != std::string::npos)
summary = summary.substr(colon + 2);
std::vector<Row> rows(SCount);
rows[SSlot] = {"SLOT", std::to_string(slot)};
rows[SSummary] = {" " + summary, "", true};
rows[SLoad] = {"LOAD", ""};
rows[SSave] = {"SAVE", ""};
return rows;
}
// The top page: the pages this program can offer.
std::vector<Page> topPages(const Hooks &h)
{
std::vector<Page> pages;
if (h.videoShared && h.videoApply && h.videoShared().open)
pages.push_back(Page::Video);
pages.push_back(Page::Cheats);
if (h.stateSlot && h.saveState && h.loadState)
pages.push_back(Page::States);
return pages;
}
const char *pageName(Page p)
{
switch (p)
{
case Page::Video: return "VIDEO";
case Page::Cheats: return "CHEATS";
case Page::States: return "SAVE STATES";
default: return "";
}
}
std::vector<Row> rowsOf(const Menu &m, const Hooks &h)
{
switch (m.page)
{
case Page::Top:
{
std::vector<Row> rows;
for (const Page p : topPages(h))
rows.push_back({pageName(p), ""});
if (h.quit)
rows.push_back({m.quitArmed ? "QUIT GAME: PRESS X AGAIN" : "QUIT GAME", ""});
return rows;
}
case Page::Video: return videoRows(m, h);
case Page::Cheats: return cheatRows();
case Page::States: return stateRows(h);
default: return {};
}
}
int nextLine(const std::vector<Row> &rows, int line, int delta)
{
const int n = static_cast<int>(rows.size());
for (int k = 0; k < n; ++k)
{
line = ((line + delta) % n + n) % n;
if (!rows[static_cast<size_t>(line)].info)
return line;
}
return line;
}
void open(Menu &m, Page page, const Hooks &h)
{
m.page = page;
m.line = 0;
m.status.clear();
m.quitArmed = false;
if (page == Page::Video && h.videoShared)
{
const bozo::app::video::Shared s = h.videoShared();
m.video = s.applied;
m.resolutions = s.resolutions;
m.monitorRefresh = s.monitorRefresh;
}
}
// The pages in the pause's own style: its fonts (setTitleFont's title; the selected line at size 0x12 in
// (0x78, 0x6E, 0x00), the others at 0x10 in (0x46, 0x46, 0x46), as setMenuFont), in pixels of the paused view.
void drawPause(Guest &g, const Menu &m, const std::vector<Row> &rows)
{
g.call(&setTitleFont__Fv_0x167ac8, kSetTitleFont, {});
g.call(&fontSpritePrintCenteredXY__FiiiPc_0x1c44d8, kFontPrintCenteredXY,
{0u, 0x140u, 0x12u, g.string(m.page == Page::Top ? "PC SETTINGS" : pageName(m.page))});
const int32_t top = m.page == Page::Top ? 0x40 : 0x26, spacing = 0xB;
for (size_t i = 0; i < rows.size(); ++i)
{
const Row &r = rows[i];
const bool selected = static_cast<int>(i) == m.line && !r.info;
const uint32_t y = static_cast<uint32_t>(top + static_cast<int32_t>(i) * spacing);
g.call(&fontSetSize__Fii_0x1c4330, kFontSetSize, {0u, selected ? 0x12u : 0x10u});
if (selected)
g.color(0x78u, 0x6Eu, 0x00u);
else
g.color(0x46u, 0x46u, 0x46u);
if (m.page == Page::Top)
g.call(&fontSpritePrintCenteredXY__FiiiPc_0x1c44d8, kFontPrintCenteredXY, {0u, 0x140u, y, g.string(r.label)});
else
{
g.call(&fontSpritePrintXY__FiiiPc_0x1c44a8, kFontPrintXY, {0u, 0x3Cu, y, g.string(r.label)});
if (!r.value.empty())
g.call(&fontSpritePrintCenteredXY__FiiiPc_0x1c44d8, kFontPrintCenteredXY,
{0u, 0x1C0u, y, g.string(selected ? "\\ " + r.value + " ]" : r.value)});
}
}
if (!m.status.empty())
{
g.call(&fontSetSize__Fii_0x1c4330, kFontSetSize, {0u, 0x10u});
g.color(0x78u, 0x6Eu, 0x00u);
g.call(&fontSpritePrintCenteredXY__FiiiPc_0x1c44d8, kFontPrintCenteredXY,
{0u, 0x140u, static_cast<uint32_t>(top + static_cast<int32_t>(rows.size()) * spacing + 4), g.string(m.status)});
}
}
// A frame of the open pages: the pad's presses (uiGetInput's flags), then the page drawn.
void runPage(Guest &g)
{
Menu &m = g_menu;
const Hooks h = hooks();
// This frame's press: the Options page's from uiGetInput's flags; the pause's from the pausing player's pad
// (inputGetInput, one press a frame in uiGetInput's order), as the pause reads it.
uint32_t press = 0u;
if (g.pause)
{
g.call(&inputGetPlayerPad__Fi_0x1d8658, kInputGetPlayerPad, {word(g.rdram, kPlayerThatPaused)});
const uint32_t pad = g.result();
static constexpr std::pair<uint32_t, uint32_t> kMasks[] = {{0x40u, kDown}, {0x10u, kUp}, {0x4000u, kCross}, {0x80u, kLeft},
{0x20u, kRight}, {0x1000u, kTriangle}, {0x2000u, kCircle}};
for (const auto &[mask, flag] : kMasks)
{
g.call(&inputGetInput__Fii_0x1d8770, kInputGetInput, {mask, pad});
if (g.result() != 0u)
{
press = flag;
break;
}
}
}
else
g.call(&uiGetInput__Fv_0x199880, kUiGetInput, {});
const auto pressed = [&](uint32_t flag) { return g.pause ? press == flag : word(g.rdram, flag) != 0u; };
std::vector<Row> rows = rowsOf(m, h);
if (m.page != Page::Closed && rows.empty())
m.page = Page::Top, rows = rowsOf(m, h);
m.line = std::clamp(m.line, 0, std::max(0, static_cast<int>(rows.size()) - 1));
if (pressed(kTriangle) || pressed(kCircle))
{
if (m.quitArmed)
{
m.quitArmed = false; // Back only disarms QUIT GAME
g.sound(kSoundBack);
rows = rowsOf(m, h);
goto draw;
}
g.sound(kSoundBack);
if (m.page == Page::Top)
{
m.page = Page::Closed;
return; // the game's page again from the next frame, its cursor on PC SETTINGS
}
const Page from = m.page;
open(m, Page::Top, h);
const std::vector<Page> pages = topPages(h);
m.line = std::max(0, indexOf(pages, from));
rows = rowsOf(m, h);
}
else if (pressed(kUp) || pressed(kDown))
{
m.line = nextLine(rows, m.line, pressed(kUp) ? -1 : 1);
m.quitArmed = false;
g.sound(pressed(kUp) ? kSoundUp : kSoundDown);
m.status.clear();
}
else if (pressed(kLeft) || pressed(kRight))
{
const int delta = pressed(kLeft) ? -1 : 1;
bool changed = false;
if (m.page == Page::Video)
changed = videoChange(m, m.line, delta);
else if (m.page == Page::Cheats)
changed = cheatChange(m.line, delta);
else if (m.page == Page::States && m.line == SSlot && h.stateSlot && h.setStateSlot)
{
h.setStateSlot(h.stateSlot() + delta);
changed = true;
}
if (changed)
{
g.sound(kSoundValue);
m.status.clear();
rows = rowsOf(m, h);
}
}
else if (pressed(kCross))
{
if (m.page == Page::Top)
{
const std::vector<Page> pages = topPages(h);
if (m.line < static_cast<int>(pages.size()))
{
g.sound(kSoundAccept);
open(m, pages[static_cast<size_t>(m.line)], h);
rows = rowsOf(m, h);
}
else if (h.quit && m.line == static_cast<int>(pages.size()))
{
// QUIT GAME: a second Cross ends the game (the window closes, as closing it does).
g.sound(kSoundAccept);
if (m.quitArmed)
h.quit();
m.quitArmed = !m.quitArmed;
rows = rowsOf(m, h);
}
}
else if (m.page == Page::Video && m.line == VApply && h.videoApply)
{
h.videoApply(m.video);
g.sound(kSoundAccept);
m.status = "APPLIED AND SAVED";
}
else if (m.page == Page::States && (m.line == SLoad || m.line == SSave) && h.stateSlot)
{
const int slot = h.stateSlot();
const bool empty = h.slotSummary && upper(h.slotSummary(slot)).find("EMPTY") != std::string::npos;
if (m.line == SLoad && empty)
{
g.sound(kSoundBack);
m.status = "SLOT " + std::to_string(slot) + " IS EMPTY";
}
else
{
const bool ok = m.line == SLoad ? (h.loadState && h.loadState(slot)) : (h.saveState && h.saveState(slot));
g.sound(ok ? kSoundAccept : kSoundBack);
m.status = !ok ? "NOT AVAILABLE" : m.line == SLoad ? "LOADING SLOT " + std::to_string(slot) : "SAVING IN SLOT " + std::to_string(slot);
}
}
}
draw:
if (g.pause)
{
drawPause(g, m, rows);
return;
}
// The page's sliders hidden, as the game's controls page hides them (uiOptions shows them again on its page).
g.call(&blankSliders__Fi_0x19de38, kBlankSliders, {0u});
// Drawn: the title, then each line (the selected one larger and brighter, as the game's), its value to the right.
g.title(m.page == Page::Top ? "PC SETTINGS" : pageName(m.page));
const bool wide = m.page == Page::Top;
const int32_t top = wide ? 0x550 : 0x4A0, spacing = wide ? 0x210 : 0x1A0;
const float scale = wide ? 1.0f : 0.8f;
for (size_t i = 0; i < rows.size(); ++i)
{
const Row &r = rows[i];
const bool selected = static_cast<int>(i) == m.line && !r.info;
const int32_t y = top + static_cast<int32_t>(i) * spacing;
if (selected)
g.color(0x60u, 0x4Cu, 0x36u);
else
g.color(0x30u, 0x26u, 0x1Cu);
setSizes(g, selected, scale);
g.print(kLineX, y, r.label);
if (!r.value.empty())
g.printCentered(0x1D00, y, selected ? "\\ " + r.value + " ]" : r.value);
}
if (!m.status.empty())
{
g.color(0x60u, 0x4Cu, 0x36u);
setSizes(g, false, scale);
g.printCentered(0x1400, top + static_cast<int32_t>(rows.size()) * spacing + spacing / 2, m.status);
}
}
// ---- The overrides ----
// uiGetInput: the game's, then, for the Options page's call, the cursor let onto line 8 and Cross taken there.
void uiGetInputOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
const uint32_t ra = getRegU32(ctx, 31);
uiGetInput__Fv_0x199880(rdram, ctx, runtime);
// A call that left (an event due) goes on from the dispatcher: its flags are not all set yet.
if (ctx->leaving || ra != kOptionsInputReturn || !active(runtime) || !optionsPageIdle(rdram))
return;
const uint32_t line = word(rdram, kLine);
int sound = -1;
if (line == kLastLine && word(rdram, kDown))
{
setWord(rdram, kDown, 0u); // the game would wrap to 0
setWord(rdram, kLine, kPcLine);
sound = kSoundDown;
}
else if (line == 0u && word(rdram, kUp))
setWord(rdram, kLine, kPcLine + 1u); // the game's Up then gives 8
else if (line == kPcLine)
{
if (word(rdram, kDown))
setWord(rdram, kLine, kLastLine); // the game's Down then wraps to 0
else if (word(rdram, kCross))
{
setWord(rdram, kCross, 0u); // not the game's accept-and-leave
sound = kSoundAccept;
open(g_menu, Page::Top, hooks());
g_menu.inPause = false;
}
setWord(rdram, kLeft, 0u);
setWord(rdram, kRight, 0u);
}
if (sound >= 0)
{
Guest g(rdram, ctx, runtime);
g.sound(sound);
}
}
// uiOptions: the game's page and the PC SETTINGS line under it, or, while they are open, the PC pages instead.
void uiOptionsOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
if (g_menu.page != Page::Closed && (g_menu.inPause || !active(runtime) || !optionsPageIdle(rdram)))
g_menu.page = Page::Closed;
const bool pages = g_menu.page != Page::Closed;
if (!pages)
uiOptions__Fv_0x1911f0(rdram, ctx, runtime); // returns with pc its return address (or where it left)
if (active(runtime) && optionsPageIdle(rdram))
{
Guest g(rdram, ctx, runtime);
if (pages)
runPage(g);
else
{
const bool selected = word(rdram, kLine) == kPcLine;
if (selected)
g.color(0x60u, 0x4Cu, 0x36u);
else
g.color(0x30u, 0x26u, 0x1Cu);
setSizes(g, selected, 1.0f);
g.print(kLineX, kPcLineY, "PC SETTINGS");
}
}
if (pages)
ctx->pc = getRegU32(ctx, 31); // jr $ra: the game's page not run
}
// ---- The pause menu (displayDialog's pauseLevelOverlay, types 0 and 16) ----
// getCurrentMenuSelection(count, pad) moves the cursor (gCurrentMenuSelection) on the pausing player's pad,
// wrapping at `count` (4 in one player: RESUME, QUIT, SET VIBRATION, ADJUST REAR VIEW; 3 with more players);
// checkInputForPauseExit returns 2 for Cross; at index `count` the game keeps a hidden TWEAK action, which Cross
// there would run. So: for the pause's call (return 0x166AE4) the count is one more (PC SETTINGS at `count`),
// Cross there (return 0x166D64) opens the pages instead, and pauseLevelOverlay draws the line after its menu,
// or, while the pages are open, the pages instead (displayDialog's loop goes on: 3D, font flush, frame).
uint32_t g_pauseCount = 0u;
bool g_pauseMenuShown = false; // the overlay drew its menu this frame (not the QUIT confirmation or the save)
std::chrono::steady_clock::time_point g_lastPause{};
void menuSelectionOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
if (getRegU32(ctx, 31) == kPauseSelectionReturn && active(runtime))
{
g_pauseCount = getRegU32(ctx, 4);
g_pauseMenuShown = true;
SET_GPR_U32(ctx, 4, g_pauseCount + 1u);
}
getCurrentMenuSelection__Fii_0x167af8(rdram, ctx, runtime);
}
void pauseExitOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
const uint32_t ra = getRegU32(ctx, 31);
checkInputForPauseExit__Fi_0x167670(rdram, ctx, runtime);
if (ctx->leaving || ra != kPauseExitReturn || !active(runtime) || !g_pauseMenuShown)
return;
if (getRegU32(ctx, 2) == 2u && word(rdram, kCurrentMenuSelection) == g_pauseCount)
{
SET_GPR_U32(ctx, 2, 0u); // the pause stays (not TWEAK)
open(g_menu, Page::Top, hooks());
g_menu.inPause = true;
}
}
void pauseOverlayOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
const uint32_t ra = getRegU32(ctx, 31);
const bool pause = (ra == kPauseReturn0 || ra == kPauseReturn16) && active(runtime);
if (pause)
{
// A new pause (the overlay not called for a while) starts on the game's menu.
const auto now = std::chrono::steady_clock::now();
if (now - g_lastPause > std::chrono::milliseconds(500) && g_menu.inPause)
g_menu.page = Page::Closed;
g_lastPause = now;
if (g_menu.inPause && g_menu.page != Page::Closed)
{
Guest g(rdram, ctx, runtime);
g.pause = true;
runPage(g);
SET_GPR_U32(ctx, 2, 0u); // the dialog stays
ctx->pc = ra;
return;
}
}
g_pauseMenuShown = false;
pauseLevelOverlay__Fv_0x166960(rdram, ctx, runtime);
if (!pause || ctx->leaving || !g_pauseMenuShown)
return;
Guest g(rdram, ctx, runtime);
g.pause = true;
g.call(&setMenuFont__Fi_0x167810, kSetMenuFont, {g_pauseCount}); // highlighted as the game's lines
g.call(&fontSpritePrintCenteredXY__FiiiPc_0x1c44d8, kFontPrintCenteredXY,
{0u, 0x140u, 0x61u + 0xBu * g_pauseCount, g.string("PC SETTINGS")});
}
}
Hooks currentHooks() { return hooks(); }
bool pausePagesOpen() { return g_menu.inPause && g_menu.page != Page::Closed; }
void setHooks(Hooks h)
{
std::lock_guard lock(g_hooksMutex);
g_hooks = std::move(h);
}
void stateLoaded() { g_menu.page = Page::Closed; }
void install(tmb::Registry &runtime)
{
runtime.registerFunction(kUiGetInput, &uiGetInputOverride);
runtime.registerFunction(kUiOptions, &uiOptionsOverride);
runtime.registerFunction(kMenuSelection, &menuSelectionOverride);
runtime.registerFunction(kPauseExit, &pauseExitOverride);
runtime.registerFunction(kPauseOverlay, &pauseOverlayOverride);
}
}
+40
View File
@@ -0,0 +1,40 @@
// PC SETTINGS in the game's own Options screen (runtime/tmb_menu.cpp): what the settings window (F2) offers besides the
// controls (video, cheats, save states), on pages drawn with the game's font and steered with the pad. The window's
// parts (its video settings and save states) come from the window program through these hooks; without them (the
// headless program) those pages are not offered.
#pragma once
#include "bozo/app/video_settings.h"
#include <functional>
#include <string>
namespace tmb::menu
{
struct Hooks
{
// Video: what is applied now (with the sizes to offer), and a change applied and saved to video.ini.
std::function<bozo::app::video::Shared()> videoShared;
std::function<void(const bozo::app::video::Settings &)> videoApply;
// The texture pack's folder a texture_pack setting names ("" none).
std::function<std::string(const std::string &)> texturePackFolder;
// Save states: the slot F5 / F7 use, its summary ("Slot 3: saved ..." or "Slot 3: empty"), save and load.
std::function<int()> stateSlot;
std::function<void(int)> setStateSlot;
std::function<std::string(int)> slotSummary;
std::function<bool(int)> saveState, loadState;
// Ends the game (the window closes): QUIT GAME, confirmed by a second Cross.
std::function<void()> quit;
// Widescreen (runtime/tmb_widescreen.cpp): the setting applied now, and the window's picture shape (0 the
// default 4:3, 16:9 while a view is wide).
std::function<bool()> widescreen;
std::function<void(float)> setPictureAspect;
};
void setHooks(Hooks hooks);
Hooks currentHooks();
// The pages are open over the pause menu (tmb_2d.cpp: displayDialog's darkening left out under them).
bool pausePagesOpen();
// A save state was loaded: the pages close (what they showed is gone).
void stateLoaded();
}
+1808 -1777
View File
File diff suppressed because it is too large. Load diff
+30 -4
View File
@@ -22,6 +22,11 @@
#include <cstdlib>
#include <cstring>
namespace tmb::widescreen
{
float screenWidth();
}
namespace tmb::twod
{
void publish();
@@ -45,6 +50,13 @@ namespace tmb::native
}
double g_lastMatchFrame = -1.0, g_lastMenuFrame = -1.0;
bool inMatch() { return g_lastMatchFrame >= 0.0 && hostSeconds() - g_lastMatchFrame < 0.1; }
// The same by game frame, not host time, for the reference checker (checkedEffects): the frames (bozo::det) at
// the last match frame's end and the last menu frame's (counted outside a match only, as g_lastMenuFrame).
int64_t g_checkMatchEnd = -1, g_checkMenuEnd = -1;
// 0.1 s as the reference ran (60 frames a second): match1p's last match frame ends at 13729 and its flares stay
// native to 13735 (6 frames on), the game's from 13736.
bool checkRecent(int64_t at) { return at >= 0 && static_cast<int64_t>(bozo::det::frame()) - at <= 6; }
bool checkInMatch() { return checkRecent(g_checkMatchEnd); }
// The menus natively too (TMB_NATIVE_MENUS=0: not drawn). Their frames end at sceGsSyncV (onMenuFrameEnd).
bool menusNative()
@@ -105,6 +117,9 @@ namespace tmb::native
// A match draws fields (the frame's every other line), the shell's menus whole frames.
const float lines = menusNative() ? 2.0f : 1.0f;
screen.originY = 2048.0f - 112.0f * lines; // NTSC: a 640 x 224 field
// Widescreen: the views 853 wide about the same centre (runtime/tmb_widescreen.cpp).
screen.width = tmb::widescreen::screenWidth();
screen.originX = 2048.0f - screen.width * 0.5f;
screen.height = 224.0f * lines;
// GS Z is z / w itself (the microprograms write FTOI4 of z / w into XYZF2's 24-bit Z, that word over 16).
screen.gsZScale = 1.0f;
@@ -139,10 +154,16 @@ namespace tmb::native
return on;
}
// For the particles drawn natively (runtime/tmb_particles.cpp): whether the effects are drawn natively now (a match
// or a native menu), and the group the next natively drawn program gets.
bool effectsInStream() { return enabled() && (inMatch() || menusNative()); }
// For the particles in the reference checker (tmb-check: no native graphics). Not the match and menu flags' host
// time, which made the check stop at match1p frame 5593 or 13737 by the host's speed: the reference's choices (TMB
// a7869c0, which recorded it), by game frame. The particles natively within 0.1 s of a match or menu frame's end (its
// effectsInStream); the lens flares natively only within 0.1 s of a match frame's (its flareDepthNative needed
// inMatch: the "No lives left" screen's frames after the match end as menu frames, their flares the game's, with its
// GS readback).
bool checkedEffects() { return enabled() && (checkInMatch() || checkRecent(g_checkMenuEnd)); }
bool checkedFlares() { return enabled() && checkInMatch(); }
// For the particles drawn natively: the group the next natively drawn program gets.
uint64_t nextStreamGroup() { return g_group + 1u; }
// For the movie pictures (runtime/tmb_2d.cpp): whether the shell's menus are drawn natively now.
@@ -208,6 +229,7 @@ namespace tmb::native
{
if (!enabled())
return;
g_checkMatchEnd = static_cast<int64_t>(bozo::det::frame());
g_lastMatchFrame = hostSeconds();
publish();
}
@@ -216,7 +238,11 @@ namespace tmb::native
// of it (empty with TMB_NATIVE_MENUS=0, so the last match frame does not stay over a menu).
void onMenuFrameEnd()
{
if (!enabled() || inMatch())
if (!enabled())
return;
if (!checkInMatch())
g_checkMenuEnd = static_cast<int64_t>(bozo::det::frame());
if (inMatch())
return;
g_lastMenuFrame = hostSeconds();
publish();
+27
View File
@@ -2,6 +2,7 @@
// BozoEngine (bozo/port.h). The fork's scheduler experiments, GS lag, VIF1 thread and IOP defaults stayed behind with
// the emulation (BozoEngine's phase4-inventory.md section 3).
#include "bozo/state.h"
#include "tmb_port.h"
#include "bozo/app/determinism.h"
@@ -55,6 +56,17 @@ namespace tmb::cheats
void logProgress(uint8_t *rdram, uint32_t gp);
}
namespace tmb::menu
{
void install(tmb::Registry &runtime);
}
namespace tmb::widescreen
{
void update(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime, bool match);
void install(tmb::Registry &runtime);
}
namespace tmb::meshes
{
void install(tmb::Registry &runtime);
@@ -495,6 +507,7 @@ namespace
g_lastMatchFrameNoted.store(hitchClock(), std::memory_order_relaxed);
tmb::cheats::onFrame(rdram); // the Cheats tab (runtime/tmb_cheats.cpp)
const uint32_t gp = getRegU32(ctx, 28);
tmb::widescreen::update(rdram, ctx, runtime, true); // widescreen: the match's views (runtime/tmb_widescreen.cpp)
tmb::native::onFrameEnd(); // TMB_NATIVE: publish the frame's native draws
timerEndOfRealTimeProcessing__Fv_0x1f67f0(rdram, ctx, runtime);
int32_t *frameTicks = reinterpret_cast<int32_t *>(rdram + ((gp + kFrameTicksGpOffset) & 0x1FFFFFFu));
@@ -544,6 +557,7 @@ namespace
{
g_pacer.setCap(static_cast<uint32_t>(fieldRate(rdram, gp)));
g_pacer.setPaced(bozo::port::realTime(runtime)); // a headless or checked run is not held to real time
tmb::widescreen::update(rdram, ctx, runtime, false); // the window's picture shape as the views are now
tmb::native::onMenuFrameEnd(); // TMB_NATIVE: publishes a menu frame's native draws (not in a match)
const double step = g_pacer.frameEnd();
tmb::cheats::logProgress(rdram, gp); // TMB_LOG_PROGRESS
@@ -1138,6 +1152,8 @@ namespace
runtime.registerFunction(kMtapPortClose, &mtapPortClose);
runtime.registerFunction(kMtapGetConnection, &mtapGetConnection);
tmb::cheats::install(runtime); // TMB_NO_AI, infinite health / ammo / energy, weak enemies (runtime/tmb_cheats.cpp)
tmb::menu::install(runtime); // PC SETTINGS in the game's Options screen (runtime/tmb_menu.cpp)
tmb::widescreen::install(runtime); // the dialogs over a widescreen match back at 640 (runtime/tmb_widescreen.cpp)
if (const char *fx = std::getenv("TMB_FX_TEST"); fx && *fx)
{
g_fxTest.period = std::max(0.5, std::atof(fx));
@@ -1179,4 +1195,15 @@ namespace tmb
}
}
namespace tmb
{
// Save states (tmb_state.cpp): the overrides' own state (the frame pacing's parity, carry and clock debt, the
// movie sound's queue).
void overridesState(bozo::state::Archive &a)
{
bozo::state::fields(a, g_syncVParity, g_frameEndCycle, g_fieldCarry, g_clockDebt, g_theGame, g_moviePcm, g_pcmCalls,
g_sendCalls);
}
}
BOZO_PORT("Twisted Metal - Black (USA)", "SCUS_971.01", kTmbPalEntry, &applyTmb)
+52 -3
View File
@@ -48,6 +48,7 @@
// TMB_NATIVE_PARTICLES_CHECK=1 (a diagnostic): nothing drawn here; types 1, 4, 6 (not on a sphere), 7 and 8 computed and
// compared with what runtime/tmb_native.cpp's translations draw from the same systems' packets.
#include "bozo/state.h"
#include "tmb_port.h"
#include "bozo/render/renderer.h"
#include "bozo/render/texture.h"
@@ -67,7 +68,8 @@
namespace tmb::native
{
bool enabled();
bool effectsInStream();
bool checkedEffects();
bool checkedFlares();
uint64_t nextStreamGroup();
bool flareDepthNative();
bool flareDepthBlock(uint32_t x0, uint32_t y0, uint32_t z[16]);
@@ -2414,7 +2416,8 @@ namespace tmb::particles
const uint32_t view = getRegU32(ctx, 4), gp = getRegU32(ctx, 28);
g_view = view;
const bool toggledAll = toggledOff() && !settings().toggleFlares;
if (!settings().on || (!bozo::port::nativeGraphics(runtime) && !tmb::native::effectsInStream()) ||
// Without native graphics (only the reference checker, tmb-check) as the reference chose (checkedEffects).
if (!settings().on || (!bozo::port::nativeGraphics(runtime) && !tmb::native::checkedEffects()) ||
u32(rdram, gp + static_cast<uint32_t>(kGpColours)) == 0u || toggledAll)
{
g_flaresNative = false;
@@ -2423,8 +2426,9 @@ namespace tmb::particles
return;
}
// The lens flares here too unless left to the game (the check, TMB_NATIVE_PARTICLES_FLARES=0, the flares' toggle
// period, the native depth off: their GS readback then).
// period, the native depth off: their GS readback then; in the reference checker outside a match, checkedFlares).
const bool flaresNative = settings().flares && !settings().check && !(settings().toggleFlares && toggledOff()) &&
(bozo::port::nativeGraphics(runtime) || tmb::native::checkedFlares()) &&
tmb::native::flareDepthNative();
// The frustum (viewGetWH, viewGetFov): the half extents' slopes and the sphere test's factors.
@@ -2637,4 +2641,49 @@ namespace tmb::particles
runtime.registerFunction(kLensRender, &lensRenderOverride);
std::fprintf(stderr, "[tmb:particles] native particles on (types mask %#x)\n", settings().types);
}
// Save states (tmb_state.cpp): the stripes' scroll, the arcs' VU records and the texture choices, per system.
void state(bozo::state::Archive &a)
{
uint64_t n = bozo::state::count(a, g_stripes.size());
if (!a.loading())
for (auto &[ps, st] : g_stripes)
{
uint32_t key = ps;
bozo::state::io(a, key);
bozo::state::pod(a, st);
}
else
{
g_stripes.clear();
for (uint64_t i = 0; i < n; ++i)
{
uint32_t key = 0;
StripeState st;
bozo::state::io(a, key);
bozo::state::pod(a, st);
g_stripes[key] = st;
}
}
n = bozo::state::count(a, g_arcs.size());
if (!a.loading())
for (auto &[ps, st] : g_arcs)
{
uint32_t key = ps;
bozo::state::io(a, key);
bozo::state::pod(a, st);
}
else
{
g_arcs.clear();
for (uint64_t i = 0; i < n; ++i)
{
uint32_t key = 0;
ArcState st;
bozo::state::io(a, key);
bozo::state::pod(a, st);
g_arcs[key] = st;
}
}
bozo::state::io(a, g_texIndex);
}
}
+53
View File
@@ -0,0 +1,53 @@
// Save states: TMB's section (tmb_state.h). The engine saves the runtime, its libraries (989SND included) and the host;
// this adds what TMB keeps itself: what the game told its hooks once, the native renderer's retained records, and the
// overrides' own counters. Caches decoded from guest memory are dropped on a load.
#include "tmb_state.h"
#include "tmb_scene.h"
#include "bozo/host/free_host.h"
#include "bozo/state.h"
#include <string>
#include <type_traits>
namespace tmb
{
void overridesState(bozo::state::Archive &a); // tmb_overrides.cpp
namespace meshes { void state(bozo::state::Archive &); }
namespace textures { void state(bozo::state::Archive &); }
namespace particles { void state(bozo::state::Archive &); }
namespace cheats { void state(bozo::state::Archive &); }
namespace twod { void stateLoaded(); }
namespace menu { void stateLoaded(); }
void addStateSection(bozo::host::FreeHost &host, Runtime *runtime)
{
host.stateSections()->add({"tmb",
[runtime](bozo::state::Archive &a) {
overridesState(a);
// The native hierarchy's retained records (the frames, lights, renderer
// parameters the game's VU programs kept between draws).
static_assert(std::is_trivially_copyable_v<scene::Scene>);
a.begin("scene");
bozo::state::pod(a, scene::get(runtime));
a.end();
a.begin("meshes");
meshes::state(a);
a.end();
a.begin("textures");
textures::state(a);
a.end();
a.begin("particles");
particles::state(a);
a.end();
cheats::state(a);
if (a.loading())
{
twod::stateLoaded();
menu::stateLoaded();
}
},
[] { return std::string(); }});
}
}
+16
View File
@@ -0,0 +1,16 @@
// Save states: TMB's own part of BozoEngine's save states (BozoEngine/docs/save-states.md).
#pragma once
#include "bozo/runtime.h"
namespace bozo::host
{
class FreeHost;
}
namespace tmb
{
// Adds the "tmb" section to the host's save states: what TMB's overrides and native code keep about the game.
// On a load, the caches decoded from the old run's guest memory are dropped.
void addStateSection(bozo::host::FreeHost &host, Runtime *runtime);
}
+703 -586
View File
File diff suppressed because it is too large. Load diff
+254
View File
@@ -0,0 +1,254 @@
// Widescreen (the Video settings' widescreen, video.ini): in a match whose views are each the screen's full width (one
// player, or two players one above the other), the game is made to draw a 16:9 picture. Each view's width goes from
// 640 to 853 pixels about the same centre, then the game's own viewTweakSetFov (0x1FDEA0: viewSetFov for every view,
// with its horizontal FOV and the view's definition) rebuilds the frustum planes it culls with and the projection it
// clips with from that width. The game then projects, culls and clips a scene 4/3 as wide with the same focal length:
// more at the sides, nothing stretched. The 3D screen (tmb_native.cpp) and the 2D overlay (the views' union,
// tmb_2d.cpp) follow the views' width; the HUD, drawn about the screen's centre in its 640 pixels, stays in the middle;
// the window shows a 16:9 picture (bozo::app::setPictureAspect, through the menu's hooks) while a view is wide.
//
// The views, from the game's code: viewNumViews (0x4FBC44) views, each a 16-byte record at 0x4DFCD0 whose word +4 is
// its viewport (viewGetWH: width u16 +4, height +6; viewSetFov's planes and projection from them). viewCreate makes
// them again at each screen's start (the menus get theirs back at 640), so only a match frame's end widens them, and
// one ends them narrow again when widescreen is switched off or the layout is split in four.
//
// The dialogs over a match (displayDialog 0x163500: the pause, the results, won and lost) lay their text and darkening
// out for a 640-wide view (centred at x 320 from the view's left edge, the band 640 wide), and with one player the
// pause keeps the match's view: so the views go back to 640 before the dialog starts (its picture 4:3, centred), and the
// match's next frame end widens them again.
//
// The HUD (a match's, one or two players over and under): its two clusters are hier meshes on coordinate systems the
// game hangs in front of the camera each frame (Hud::updateHUDPosition 0x13CC90: the view's matrix, its translation
// plus the cluster's camera-space offset, Hud + 0x810 the radar's, + 0x820 the weapon's, x right, y the depth). Seen
// through the same focal length D (viewport + 0) they keep their 4:3 places; for the 16:9 picture each goes out by
// the width gained on its side, (w - 640) / 2 pixels, that is x - / + that * y / D for the call (the offsets put back
// after it, so a narrowed view finds them as the game set them). The radar's centre and its blips follow (computed in
// the same call); the markers and bars over the cars are the world's. (The game reaches both Hud functions by a jump
// from TheGame's HudUpdateHUDPosition 0x15BD20 and HudUpdate 0x15BD40, which are the ones overridden.) The HUD's text
// drawn from a 640 layout (Hud::Update 0x13D908: the ammo count and KILLS on the right, DEMO in the middle) goes with its cluster: x past 400
// by the width gained, x past 240 by half of it, from the view's left edge (fontBuildPrim's).
//
// Off (the default) or in the headless program (no hooks), nothing changes: replays and the reference check are the
// game's own picture.
#include "tmb_port.h"
#include "tmb_menu.h"
#include <algorithm>
#include <atomic>
#include <vector>
#include <cstring>
namespace tmb::widescreen
{
namespace
{
constexpr uint32_t kViews = 0x004DFCD0u, kNumViews = 0x004FBC44u, kViewTweakSetFov = 0x001FDEA0u,
kDisplayDialog = 0x00163500u, kHudPositionCall = 0x0015BD20u, kHudUpdateCall = 0x0015BD40u,
kFontPrintXY = 0x001C44A8u, kFontPrintCenteredXY = 0x001C44D8u;
constexpr uint32_t kViewFovH = 0x004FBC04u, kHuds = 0x001ABE50u, kHudStride = 0xA00u, kRadarOffset = 0x810u,
kWeaponOffset = 0x820u;
constexpr uint16_t kNarrow = 640, kWide = 853; // 640 * 4 / 3
constexpr float kWideAspect = 16.0f / 9.0f;
std::atomic<bool> g_wide{false};
// Every viewport widened (the views' records point at a few fixed ones, which viewCreate hands out again: the
// pause's full-screen view may be one widened earlier in the match and not shown since), narrowed together.
std::vector<uint32_t> g_widened;
float g_aspectSet = -1.0f;
uint32_t word(const uint8_t *rdram, uint32_t address)
{
uint32_t value;
std::memcpy(&value, rdram + (address & 0x1FFFFFCu), 4);
return value;
}
uint16_t half(const uint8_t *rdram, uint32_t address)
{
uint16_t value;
std::memcpy(&value, rdram + (address & 0x1FFFFFEu), 2);
return value;
}
void setHalf(uint8_t *rdram, uint32_t address, uint16_t value) { std::memcpy(rdram + (address & 0x1FFFFFEu), &value, 2); }
float flt(const uint8_t *rdram, uint32_t address)
{
float value;
std::memcpy(&value, rdram + (address & 0x1FFFFFCu), 4);
return value;
}
void setFlt(uint8_t *rdram, uint32_t address, float value) { std::memcpy(rdram + (address & 0x1FFFFFCu), &value, 4); }
// The view's viewport (0 none).
uint32_t viewport(const uint8_t *rdram, uint32_t view)
{
const uint32_t v = word(rdram, kViews + view * 16u + 4u);
return v >= 0x100000u && v < 0x2000000u ? v : 0u;
}
}
namespace
{
// The game's own rebuild of every view's frustum and projection, on a copy of the context (guest code there
// never leaves the override: BozoEngine kernel.md section 3b), its stack below the thread's.
void rebuildViews(uint8_t *rdram, const R5900Context *ctx, PS2Runtime *runtime)
{
R5900Context copy = *ctx;
SET_GPR_U32(&copy, 29, (getRegU32(ctx, 29) - 0x200u) & ~0xFu);
copy.leaving = 0;
copy.pc = kViewTweakSetFov;
viewTweakSetFov__Fv_0x1fdea0(rdram, &copy, runtime);
}
}
namespace
{
// Every widened viewport back at 640; whether one was.
bool narrowAll(uint8_t *rdram)
{
bool changed = false;
for (const uint32_t vp : g_widened)
if (half(rdram, vp + 4u) == kWide)
setHalf(rdram, vp + 4u, kNarrow), changed = true;
g_widened.clear();
return changed;
}
}
bool wide() { return g_wide.load(std::memory_order_relaxed); }
float screenWidth() { return wide() ? kNarrow * 4.0f / 3.0f : static_cast<float>(kNarrow); }
// At a frame's end: in a match (`match`), the views widened or narrowed as the setting and the layout want; at
// every frame end, whether a view is wide now and the window's picture shaped to it.
void update(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime, bool match)
{
if (!bozo::port::nativeGraphics(runtime))
return;
const tmb::menu::Hooks h = tmb::menu::currentHooks();
if (!h.setPictureAspect)
return; // the headless program: no window, no widescreen
const uint32_t count = std::min<uint32_t>(word(rdram, kNumViews), 4u);
if (match)
{
bool fullWidth = count > 0u;
for (uint32_t i = 0; i < count; ++i)
{
const uint32_t vp = viewport(rdram, i);
const uint16_t w = vp ? half(rdram, vp + 4u) : 0;
fullWidth = fullWidth && (w == kNarrow || w == kWide);
}
const bool want = fullWidth && h.widescreen && h.widescreen();
bool changed = false;
for (uint32_t i = 0; i < count; ++i)
if (const uint32_t vp = viewport(rdram, i))
{
const uint16_t w = half(rdram, vp + 4u);
if (want && w == kNarrow)
{
setHalf(rdram, vp + 4u, kWide), changed = true;
if (std::find(g_widened.begin(), g_widened.end(), vp) == g_widened.end())
g_widened.push_back(vp);
}
}
if (!want)
changed = narrowAll(rdram) || changed;
if (changed)
rebuildViews(rdram, ctx, runtime);
}
bool anyWide = false;
for (uint32_t i = 0; i < count; ++i)
if (const uint32_t vp = viewport(rdram, i))
anyWide = anyWide || half(rdram, vp + 4u) == kWide;
g_wide.store(anyWide, std::memory_order_relaxed);
const float aspect = anyWide ? kWideAspect : 0.0f;
if (aspect != g_aspectSet)
{
g_aspectSet = aspect;
h.setPictureAspect(aspect);
}
}
namespace
{
// displayDialog(type): the views narrow again first (above), then the game's dialog.
void displayDialogOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
if (bozo::port::nativeGraphics(runtime))
{
if (narrowAll(rdram))
{
rebuildViews(rdram, ctx, runtime);
g_wide.store(false, std::memory_order_relaxed);
const tmb::menu::Hooks h = tmb::menu::currentHooks();
if (h.setPictureAspect)
h.setPictureAspect(0.0f), g_aspectSet = 0.0f;
}
}
displayDialog__F13_shellOverlay_0x163500(rdram, ctx, runtime);
}
}
namespace
{
// TheGame::HudUpdateHUDPosition(this, i) (0x15BD20, which jumps on to Hud::updateHUDPosition of the Hud at
// TheGame + 0x1ABE50 + i * 0xA00): the clusters' offsets out by the width gained, for the call (above).
void updateHudPositionOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
// The focal length every view is given (viewTweakSetFov's viewFovH), while the match's views are wide.
const uint32_t hud = getRegU32(ctx, 4) + kHuds + getRegU32(ctx, 5) * kHudStride;
const float d = flt(rdram, kViewFovH);
if (!bozo::port::nativeGraphics(runtime) || !wide() || !(d > 1.0f))
{
HudUpdateHUDPosition__7TheGamei_0x15bd20(rdram, ctx, runtime);
return;
}
const float gained = (kWide - kNarrow) * 0.5f;
const float radar = flt(rdram, hud + kRadarOffset), weapon = flt(rdram, hud + kWeaponOffset);
setFlt(rdram, hud + kRadarOffset, radar - gained * flt(rdram, hud + kRadarOffset + 4u) / d);
setFlt(rdram, hud + kWeaponOffset, weapon + gained * flt(rdram, hud + kWeaponOffset + 4u) / d);
// On a copy of the context: the call ends here (it never leaves), so the offsets go back after all of it.
R5900Context copy = *ctx;
copy.leaving = 0;
HudUpdateHUDPosition__7TheGamei_0x15bd20(rdram, &copy, runtime);
setFlt(rdram, hud + kRadarOffset, radar);
setFlt(rdram, hud + kWeaponOffset, weapon);
ctx->pc = getRegU32(ctx, 31);
}
bool g_inHudUpdate = false;
void hudUpdateOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
g_inHudUpdate = true;
HudUpdate__7TheGamei_0x15bd40(rdram, ctx, runtime); // on to Hud::Update
g_inHudUpdate = false;
}
// fontSpritePrintXY / CenteredXY (font, x, y, text) from Hud::Update: x from its 640 layout, moved with its cluster.
void shiftHudText(R5900Context *ctx)
{
if (!g_inHudUpdate || !wide())
return;
const int32_t x = static_cast<int32_t>(getRegU32(ctx, 5));
const int32_t gained = kWide - kNarrow;
SET_GPR_U32(ctx, 5, static_cast<uint32_t>(x > 400 ? x + gained : x > 240 ? x + gained / 2 : x));
}
void fontPrintXYOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
shiftHudText(ctx);
fontSpritePrintXY__FiiiPc_0x1c44a8(rdram, ctx, runtime);
}
void fontPrintCenteredXYOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
shiftHudText(ctx);
fontSpritePrintCenteredXY__FiiiPc_0x1c44d8(rdram, ctx, runtime);
}
}
void install(tmb::Registry &runtime)
{
runtime.registerFunction(kDisplayDialog, &displayDialogOverride);
runtime.registerFunction(kHudPositionCall, &updateHudPositionOverride);
runtime.registerFunction(kHudUpdateCall, &hudUpdateOverride);
runtime.registerFunction(kFontPrintXY, &fontPrintXYOverride);
runtime.registerFunction(kFontPrintCenteredXY, &fontPrintCenteredXYOverride);
}
}
+16
View File
@@ -0,0 +1,16 @@
// The host's floating-point control word (MXCSR) in the native tests.
//
// BozoEngine's ps2f takes the host's own float add / mul where it gives the PS2's bits (operands and result normal,
// rounded to nearest: BozoEngine e1518bf). So the game's original code is exact only when the host rounds to nearest,
// as the game runs, and it leaves the sticky status flags set as SSE does. The tests run the original at the caller's
// word rounding to nearest (its flush-to-zero and denormals-are-zero kept, which both sides follow), the native code at
// the caller's varied word, and compare the control word without the six status flags (nothing reads them).
#pragma once
namespace tmb::test
{
// The word the original runs at: the caller's, rounding to nearest, the status flags clear.
inline unsigned referenceControl(unsigned control) { return control & ~0x603fu; }
// The control part equal: rounding, flush to zero, denormals-are-zero, the masks (not the status flags).
inline bool sameControl(unsigned a, unsigned b) { return ((a ^ b) & ~0x3fu) == 0; }
}
+8 -6
View File
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: MIT
// Compare actual generated original blocks against the production instruction dispatcher, including ordered aliases.
#include "host_control.h"
#include "tmb_contact_math.h"
#include "tmb_native_math.h"
#include "tmb_contact_original.h"
@@ -201,7 +202,7 @@ namespace
if (kind == 6 && ctx.pc == 0xbad0000) return;
throw std::runtime_error("contact continuation did not reach query boundary");
};
const auto control = ((saved | 0x1f80u) & ~0xe040u) | (mode << 13u) | (n & 1 ? 0x8040u : 0u);
const auto control = tmb::test::referenceControl(((saved | 0x1f80u) & ~0xe040u) | (mode << 13u) | (n & 1 ? 0x8040u : 0u)); // generated code on both sides: the game's rounding
auto a = initial, b = initial;
_mm_setcsr(control); run(false, a); const auto refControl = _mm_getcsr(); const auto refYields = services.yields;
for (unsigned i = 0; i < outputs; ++i) std::memcpy(ram + output[i] + 12, payload(output[i]) + 12, 4);
@@ -215,10 +216,10 @@ namespace
const bool untouched = !std::memcmp(reinterpret_cast<uint8_t *>(&initial) + vuAt, reinterpret_cast<uint8_t *>(&b) + vuAt, vuBytes);
std::memset(reinterpret_cast<uint8_t *>(&a) + vuAt, 0, vuBytes);
std::memset(reinterpret_cast<uint8_t *>(&b) + vuAt, 0, vuBytes);
if (std::memcmp(&a, &b, sizeof(a)) || !untouched || after != refControl || refYields != services.yields ||
if (std::memcmp(&a, &b, sizeof(a)) || !untouched || !tmb::test::sameControl(after, refControl) || refYields != services.yields ||
std::memcmp(expectedAll.get(), ram + base, bytes) || std::memcmp(expectedAll.get() + bytes, ram + globals, globalBytes) ||
(n < 4 && std::memcmp(whole.get(), ram, bozo::kFlatBytes)))
{ std::fprintf(stderr, "FAIL contact continuation %u case %u mode %u CPU%d VU%d FP%d data%d globals%d\n",kind,n,mode,std::memcmp(&a,&b,sizeof(a)),untouched,after==refControl,std::memcmp(expectedAll.get(),ram+base,bytes),std::memcmp(expectedAll.get()+bytes,ram+globals,globalBytes)); throw std::runtime_error("contact continuation differs"); }
{ std::fprintf(stderr, "FAIL contact continuation %u case %u mode %u CPU%d VU%d FP%d data%d globals%d\n",kind,n,mode,std::memcmp(&a,&b,sizeof(a)),untouched,tmb::test::sameControl(after, refControl),std::memcmp(expectedAll.get(),ram+base,bytes),std::memcmp(expectedAll.get()+bytes,ram+globals,globalBytes)); throw std::runtime_error("contact continuation differs"); }
++cases;
}
host.enabled = true; rt.services = nullptr;
@@ -279,11 +280,12 @@ int main()
if (site.translation) setRegU32(&initial, site.translation, (translation | alias) + ((n >> 8u) & 15u));
R5900Context original = initial, native = initial;
const unsigned control = ((savedControl | 0x1f80u) & ~0xe040u) | (mode << 13u) | (n & 1u ? 0x8040u : 0u);
_mm_setcsr(control);
_mm_setcsr(tmb::test::referenceControl(control));
originalBlock(index, ram, original, rt.get());
std::memcpy(expected.data(), arena, arenaBytes);
if (n < 8) { std::memcpy(whole.get(), ram, bozo::kFlatBytes); ++wholeCases; }
std::memcpy(arena, input.data(), arenaBytes);
_mm_setcsr(control);
for (uint32_t pc = site.first; pc <= site.last; pc += 4)
{
if (!handler(ram, &native, rt.get(), pc)) return 2;
@@ -292,10 +294,10 @@ int main()
const unsigned after = _mm_getcsr();
_mm_setcsr(savedControl);
if (std::memcmp(arena, expected.data(), arenaBytes) || std::memcmp(&native, &initial, sizeof(initial)) ||
after != control || (n < 8 && std::memcmp(whole.get(), ram, bozo::kFlatBytes)))
!tmb::test::sameControl(after, control) || (n < 8 && std::memcmp(whole.get(), ram, bozo::kFlatBytes)))
{
std::fprintf(stderr, "FAIL contact block %u case %u mode %u: memory %d CPU/VU %d host %d\n", index, n, mode,
std::memcmp(arena, expected.data(), arenaBytes), std::memcmp(&native, &initial, sizeof(initial)), after == control);
std::memcmp(arena, expected.data(), arenaBytes), std::memcmp(&native, &initial, sizeof(initial)), tmb::test::sameControl(after, control));
return 4;
}
host.enabled = false;
+8 -7
View File
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: MIT
// Run the generated BSP collision setup through its real XYZ consumers. No copied game code is committed.
#include "host_control.h"
#include "tmb_port.h"
#include "tmb_native_math.h"
#include "bozo/libs/libraries.h"
@@ -123,7 +124,7 @@ void testDirectionCallers()
const float radius = 6.5f; std::memcpy(&initial.fu[20], &radius, 4);
std::memcpy(input.get(), ram + 0x10000, arenaBytes);
std::memcpy(input.get() + arenaBytes, ram + globals, globalBytes);
const unsigned control = ((saved | 0x1f80) & ~0xe040u) | (mode << 13) | (n & 1 ? 0x8040 : 0);
const unsigned control = tmb::test::referenceControl(((saved | 0x1f80) & ~0xe040u) | (mode << 13) | (n & 1 ? 0x8040 : 0)); // generated code on both sides: the game's rounding
const auto run = [&](RecompiledFunction direction, R5900Context &ctx)
{
services.yields = 0; rt->functions.setOverride(0x1da298, direction);
@@ -145,7 +146,7 @@ void testDirectionCallers()
std::memcpy(ram + 0x10000, input.get(), arenaBytes);
std::memcpy(ram + globals, input.get() + arenaBytes, globalBytes);
run(nativeDirection, b); const unsigned after = _mm_getcsr(); _mm_setcsr(saved);
if (!cpuEqual(a, b) || !vuUntouched(initial, b) || after != control || referenceYields != services.yields ||
if (!cpuEqual(a, b) || !vuUntouched(initial, b) || !tmb::test::sameControl(after, control) || referenceYields != services.yields ||
std::memcmp(expected.get(), ram + 0x10000, arenaBytes) ||
std::memcmp(expected.get() + arenaBytes, ram + globals, globalBytes) ||
(n < 4 && std::memcmp(whole.get(), ram, bozo::kFlatBytes)))
@@ -248,7 +249,7 @@ void testDirectionCallers()
setRegU32(&initial, 6, address(output)); word(output + 12, bits());
// Both light directions may execute in one continuation; both opaque W words must stay untouched.
std::memcpy(input.get(), ram + 0x10000, arenaBytes);
const unsigned control = ((saved | 0x1f80) & ~0xe040u) | (mode << 13) | (n & 1 ? 0x8040 : 0);
const unsigned control = tmb::test::referenceControl(((saved | 0x1f80) & ~0xe040u) | (mode << 13) | (n & 1 ? 0x8040 : 0)); // generated code on both sides: the game's rounding
const auto run = [&](RecompiledFunction direction, R5900Context &ctx)
{
services.yields = 0; rt->functions.setOverride(0x1da298, direction);
@@ -269,12 +270,12 @@ void testDirectionCallers()
_mm_setcsr(control); run(nativeDirection, b);
const unsigned after = _mm_getcsr(); _mm_setcsr(saved);
// Original scalar normalization can raise host exception flags; compare its complete FP effects too.
if (!cpuEqual(a, b) || !vuUntouched(initial, b) || after != referenceControl || referenceYields != services.yields ||
if (!cpuEqual(a, b) || !vuUntouched(initial, b) || !tmb::test::sameControl(after, referenceControl) || referenceYields != services.yields ||
std::memcmp(expected.get(), ram + 0x10000, arenaBytes) ||
(n < 4 && std::memcmp(whole.get(), ram, bozo::kFlatBytes)))
{
std::fprintf(stderr, "FAIL vehicle/light caller %x case %u mode %u CPU%d data%d FP%d yields %u/%u\n",
caller, n, mode, cpuEqual(a, b), std::memcmp(expected.get(), ram + 0x10000, arenaBytes), after == referenceControl,
caller, n, mode, cpuEqual(a, b), std::memcmp(expected.get(), ram + 0x10000, arenaBytes), tmb::test::sameControl(after, referenceControl),
referenceYields, services.yields);
throw std::runtime_error("vehicle/light direction consumer differs");
}
@@ -307,7 +308,7 @@ void testDirectionCallers()
const uint32_t alias = n % 3 == 0 ? 0x80000000 : n % 3 == 1 ? 0x20000000 : 0;
setRegU32(&initial, 4, vehicle | alias); setRegU32(&initial, 5, n % 4);
setRegU32(&initial, 29, sp | alias); initial.pc = 0x118178; initial.cycleLimit = 0;
const unsigned control = ((saved | 0x1f80) & ~0xe040u) | (mode << 13) | (n & 1 ? 0x8040 : 0);
const unsigned control = tmb::test::referenceControl(((saved | 0x1f80) & ~0xe040u) | (mode << 13) | (n & 1 ? 0x8040 : 0)); // generated code on both sides: the game's rounding
const auto run = [&](R5900Context &ctx)
{
services.yields = 0;
@@ -324,7 +325,7 @@ void testDirectionCallers()
const uint32_t poisonedW = bits(); std::memcpy(ram + result + 12, &poisonedW, 4);
_mm_setcsr(control); run(b); const auto after = _mm_getcsr(); _mm_setcsr(saved);
std::memcpy(ram + result + 12, input.get() + result - 0x10000 + 12, 4);
require(!std::memcmp(&a, &b, sizeof(a)) && after == referenceControl && services.yields == referenceYields &&
require(!std::memcmp(&a, &b, sizeof(a)) && tmb::test::sameControl(after, referenceControl) && services.yields == referenceYields &&
!std::memcmp(expected.get(), ram + 0x10000, arenaBytes) &&
(n >= 4 || !std::memcmp(whole.get(), ram, bozo::kFlatBytes)), "contact position W affected XYZ consumer");
++contactCases;
+4 -3
View File
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: MIT
// Real hierarchy helper consumers compiled from the local game ELF; no copied game implementation.
#include "host_control.h"
#include "tmb_port.h"
#include "tmb_native_math.h"
#include "tmb_hierarchy_math.h"
@@ -2826,7 +2827,7 @@ void testHierarchyHelperCallers()
require(ctx.pc==0xbad0000,"peel-out coordinate-system consumer returned early");
}
};
const unsigned control = ((saved | 0x1f80u) & ~0xe040u) | (mode << 13u) | (n & 1 ? 0x8040u : 0u);
const unsigned control = tmb::test::referenceControl(((saved | 0x1f80u) & ~0xe040u) | (mode << 13u) | (n & 1 ? 0x8040u : 0u)); // generated code on both sides: the game's rounding
auto a = initial, b = initial; _mm_setcsr(control);
try { run(false, a); }
catch (...) { std::fprintf(stderr, "hierarchy original kind %u case %u\n", kind, n); throw; }
@@ -3467,10 +3468,10 @@ void testHierarchyHelperCallers()
// Full rear-view entries retain the original rotation producer's identity-helper VU writes.
const auto &expectedVu=kind == 148 && sawDirectionEntry ? directionEntry : kind==195 && sawForceInverseEntry ? forceInverseEntry : initial;
if(kind==195 && sawForceInverseEntry) require(vuUntouched(forceReferenceEntry,forceInverseEntry),"force-field original producer effects differ");
if (!cpuEqual(a,b) || !(kind>=236 ? weaponVuRetired(initial,a,b) : vuUntouched(expectedVu,b)) || after != refControl || services.yields != refYields || services.randomCalls != refRandomCalls ||
if (!cpuEqual(a,b) || !(kind>=236 ? weaponVuRetired(initial,a,b) : vuUntouched(expectedVu,b)) || !tmb::test::sameControl(after, refControl) || services.yields != refYields || services.randomCalls != refRandomCalls ||
services.weatherPoints != refWeatherPoints || services.weatherIdentities != refWeatherIdentities || services.spatialCalls != refSpatialCalls || auditedInverseCalls != refAuditedInverseCalls || services.aiActions != refAiActions || services.vehicleLightActions != refVehicleLightActions || services.finalActions != refFinalActions || services.rigidActions != refRigidActions || rigidDirectionCalls != refRigidDirections || driverDirectionCalls != refDriverDirections || services.driverActions != refDriverActions || services.driverQueryEndpoints != refDriverEndpoints || services.collisionActions != refCollisionActions || services.collisionVelocities != refCollisionVelocities || collisionDirectionCalls != refCollisionDirections || attachmentDirectionCalls != refAttachmentDirections || services.attachmentActions != refAttachmentActions || minionDirectionCalls != refMinionDirections || services.minionActions != refMinionActions || services.minionPoints != refMinionPoints || weaponDirectionCalls != refWeaponDirections || services.weaponInputs != refWeaponInputs || services.weaponBases != refWeaponBases || services.weaponOutputs != refWeaponOutputs || services.weaponTargets != refWeaponTargets || !dataEqual() ||
(wholeCase && std::memcmp(whole.get(),ram,bozo::kFlatBytes)))
{ std::fprintf(stderr,"FAIL hierarchy %x case %u mode %u CPU%d VU%d FP%d data%d\n",callers[kind],n,mode,cpuEqual(a,b),vuUntouched(initial,b),after==refControl,dataEqual()); throw std::runtime_error("hierarchy consumer differs"); }
{ std::fprintf(stderr,"FAIL hierarchy %x case %u mode %u CPU%d VU%d FP%d data%d\n",callers[kind],n,mode,cpuEqual(a,b),vuUntouched(initial,b),tmb::test::sameControl(after, refControl),dataEqual()); throw std::runtime_error("hierarchy consumer differs"); }
++cases;
}
require(aiShotPublications[0] && aiShotPublications[1],"AI fixtures did not publish front/rear attack states");
+11 -7
View File
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: MIT
// Differential checks against complete generated helpers, including the original VCALLMS library path.
#include "host_control.h"
#include "tmb_port.h"
#include "tmb_hierarchy_math.h"
#include "bozo/ee/dispatcher.h"
@@ -107,7 +108,7 @@ int main()
d.updateLimit(&initial); // the dispatcher supplies this scheduler cache before executing a helper
R5900Context original=initial,native=initial;
const unsigned control = ((saved|0x1f80u)&~0xe040u)|(mode<<13)|(n&1 ? 0x8040u : 0);
_mm_setcsr(control);
_mm_setcsr(tmb::test::referenceControl(control));
if (kind == 2) bspPlaneTest2Vec__FP6_planeP8_fvectorT1T1_0x201660(ram,&original,&rt);
else if (kind) mathfMulVec__FPA3_fP8_fvectorT1_0x1da1e8(ram,&original,&rt);
else hdHatSphereTestAsm__FP8_fvectorfT0T0_0x1cf7c0(ram,&original,&rt);
@@ -119,10 +120,11 @@ int main()
if (n<32) { std::memcpy(full.get(),ram,bozo::kFlatBytes); ++memoryCases; }
std::memcpy(arena,input.data(),input.size());
const auto before=host.microCalls;
_mm_setcsr(control);
(kind == 2 ? plane : kind ? inverse : sphere)(ram,&native,&rt);
nativeMicros += host.microCalls-before;
const unsigned after=_mm_getcsr(); _mm_setcsr(saved);
if (!compareCpu(original,native,initial) || std::memcmp(arena,expected.data(),input.size()) || after!=control ||
if (!compareCpu(original,native,initial) || std::memcmp(arena,expected.data(),input.size()) || !tmb::test::sameControl(after,control) ||
(n<32 && std::memcmp(full.get(),ram,bozo::kFlatBytes)))
{
if(!kind) {
@@ -130,7 +132,7 @@ int main()
for(unsigned v:{14u,15u,17u,18u,20u,21u,22u,23u,24u,27u})std::fprintf(stderr,"vf%u %08x %08x %08x %08x\n",v,original.vu0_vf[v].u[0],original.vu0_vf[v].u[1],original.vu0_vf[v].u[2],original.vu0_vf[v].u[3]);
}
std::fprintf(stderr,"FAIL kind %u mode %u case %u: CPU %d data %d host %d return %x/%x\n",kind,mode,n,
compareCpu(original,native,initial),std::memcmp(arena,expected.data(),input.size()),after==control,
compareCpu(original,native,initial),std::memcmp(arena,expected.data(),input.size()),tmb::test::sameControl(after,control),
getRegU32(&native,2),getRegU32(&original,2));
for (size_t i=0;i<sizeof(native);++i) if ((i<vuAt || i>=vuAt+vuBytes) && ((uint8_t *)&original)[i]!=((uint8_t *)&native)[i])
std::fprintf(stderr,"CPU byte %zu original %02x native %02x\n",i,((uint8_t *)&original)[i],((uint8_t *)&native)[i]);
@@ -155,11 +157,12 @@ int main()
setRegU32(&initial,28,0x14854);setRegU32(&initial,31,0xbad0000);d.updateLimit(&initial);
auto original=initial,native=initial;
const unsigned control=((saved|0x1f80u)&~0xe040u)|(mode<<13)|(n&1 ? 0x8040u : 0);
_mm_setcsr(control);
_mm_setcsr(tmb::test::referenceControl(control));
hdHatSphereTestAsm__FP8_fvectorfT0T0_0x1cf7c0(ram,&original,&rt);
_mm_setcsr(control);
const auto before=host.microCalls;sphere(ram,&native,&rt);
const auto after=_mm_getcsr();_mm_setcsr(saved);
if (!compareCpu(original,native,initial) || after!=control || host.microCalls!=before) {
if (!compareCpu(original,native,initial) || !tmb::test::sameControl(after,control) || host.microCalls!=before) {
std::fprintf(stderr,"FAIL sphere edge %u mode %u return %x/%x\n",n,mode,getRegU32(&native,2),getRegU32(&original,2));return 5;
}
++edges;
@@ -196,7 +199,7 @@ int main()
for(auto &v:initial.vu0_vf)for(auto &b:v.u)b=randomBits();initial.vu0_vf[0]={};initial.vu0_vf[0].u[3]=0x3f800000;
d.updateLimit(&initial);auto original=initial,native=initial;
const unsigned control=((saved|0x1f80u)&~0xe040u)|(mode<<13)|(n&1 ? 0x8040u : 0);
_mm_setcsr(control);
_mm_setcsr(tmb::test::referenceControl(control));
rt.functions.setOverride(0x201660,&referencePlane);
try { bspVecTestIn__FP8_hierbspP8_fvectorT1_0x201318(ram,&original,&rt); }
catch(const bozo::ee::StopGuest &) { if(original.pc!=0xbad0000)throw; } // recursive root return to dispatcher
@@ -204,10 +207,11 @@ int main()
if(n<8)std::memcpy(full.get(),ram,bozo::kFlatBytes);
std::memcpy(ram+0x10000,callerInput.get(),callerBytes);
rt.functions.setOverride(0x201660,plane);
_mm_setcsr(tmb::test::referenceControl(control)); // the generated caller runs on both sides: the game's rounding
try { bspVecTestIn__FP8_hierbspP8_fvectorT1_0x201318(ram,&native,&rt); }
catch(const bozo::ee::StopGuest &) { if(native.pc!=0xbad0000)throw; }
const unsigned after=_mm_getcsr();_mm_setcsr(saved);
if(!compareCpu(original,native,initial)||std::memcmp(callerExpected.get(),ram+0x10000,callerBytes)||after!=control||
if(!compareCpu(original,native,initial)||std::memcmp(callerExpected.get(),ram+0x10000,callerBytes)||!tmb::test::sameControl(after,tmb::test::referenceControl(control))||
(n<8&&std::memcmp(full.get(),ram,bozo::kFlatBytes))||native.pc!=0xbad0000) {
std::fprintf(stderr,"FAIL complete BSP caller %u mode %u CPU %d data %d pc %x\n",n,mode,compareCpu(original,native,initial),std::memcmp(callerExpected.get(),ram+0x10000,callerBytes),native.pc);return 6;
}
+5 -3
View File
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: MIT
// Compare actual generated original blocks against the production instruction dispatcher, including ordered aliases.
#include "host_control.h"
#include "tmb_hud_math.h"
#include "tmb_native_math.h"
#include "tmb_hud_original.h"
@@ -92,11 +93,12 @@ int main()
if (site.translation) setRegU32(&initial, site.translation, (translation | alias) + ((n >> 8u) & 15u));
R5900Context original = initial, native = initial;
const unsigned control = ((savedControl | 0x1f80u) & ~0xe040u) | (mode << 13u) | (n & 1u ? 0x8040u : 0u);
_mm_setcsr(control);
_mm_setcsr(tmb::test::referenceControl(control));
originalBlock(index, ram, original, rt.get());
std::memcpy(expected.data(), arena, arenaBytes);
if (n < 8) { std::memcpy(whole.get(), ram, bozo::kFlatBytes); ++wholeCases; }
std::memcpy(arena, input.data(), arenaBytes);
_mm_setcsr(control);
for (uint32_t pc = site.first; pc <= site.last; pc += 4)
{
if (!handler(ram, &native, rt.get(), pc)) return 2;
@@ -105,10 +107,10 @@ int main()
const unsigned after = _mm_getcsr();
_mm_setcsr(savedControl);
if (std::memcmp(arena, expected.data(), arenaBytes) || std::memcmp(&native, &initial, sizeof(initial)) ||
after != control || (n < 8 && std::memcmp(whole.get(), ram, bozo::kFlatBytes)))
!tmb::test::sameControl(after, control) || (n < 8 && std::memcmp(whole.get(), ram, bozo::kFlatBytes)))
{
std::fprintf(stderr, "FAIL HUD block %u case %u mode %u: memory %d CPU/VU %d host %d\n", index, n, mode,
std::memcmp(arena, expected.data(), arenaBytes), std::memcmp(&native, &initial, sizeof(initial)), after == control);
std::memcmp(arena, expected.data(), arenaBytes), std::memcmp(&native, &initial, sizeof(initial)), tmb::test::sameControl(after, control));
return 4;
}
host.enabled = false;
+5 -3
View File
@@ -1,4 +1,5 @@
// Exact, independent-original comparisons: record values, overlapping memory, the complete CPU ABI and untouched VU state.
#include "host_control.h"
#include "tmb_port.h"
#include "tmb_native_math.h"
#include "bozo/libs/libraries.h"
@@ -99,7 +100,7 @@ int main()
R5900Context original = initial, native = initial;
// Deliberately vary caller rounding and denormal settings. Native code must restore the whole word.
const unsigned control = ((savedControl | 0x1f80u) & ~0xe040u) | (mode << 13u) | (n & 1u ? 0x8040u : 0u);
_mm_setcsr(control);
_mm_setcsr(tmb::test::referenceControl(control));
helper.original(rt->memory.flat(), &original, rt.get());
if (helper.direction) // direction outputs are XYZ; the native record contract retains destination W
std::memcpy(arena + (output - physicalBase) + 12, input.data() + (output - physicalBase) + 12, 4);
@@ -110,6 +111,7 @@ int main()
++fullMemoryCases;
}
std::memcpy(arena, input.data(), input.size());
_mm_setcsr(control);
registry.find(helper.address)(rt->memory.flat(), &native, rt.get());
const unsigned after = _mm_getcsr();
_mm_setcsr(savedControl);
@@ -119,11 +121,11 @@ int main()
std::memset(reinterpret_cast<uint8_t *>(&original) + vuAt, 0, vuBytes);
std::memset(reinterpret_cast<uint8_t *>(&native) + vuAt, 0, vuBytes);
if (std::memcmp(arena, expected.data(), expected.size()) || std::memcmp(&original, &native, sizeof(native)) ||
!untouched || after != control || (n < 32 && std::memcmp(rt->memory.flat(), wholeRam.get(), bozo::kFlatBytes)))
!untouched || !tmb::test::sameControl(after, control) || (n < 32 && std::memcmp(rt->memory.flat(), wholeRam.get(), bozo::kFlatBytes)))
{
std::fprintf(stderr, "FAIL %s case %u host mode %u: data %d, CPU %d, untouched VU %d, host control %d\n",
helper.name, n, mode, std::memcmp(arena, expected.data(), expected.size()),
std::memcmp(&original, &native, sizeof(native)), untouched, after == control);
std::memcmp(&original, &native, sizeof(native)), untouched, tmb::test::sameControl(after, control));
for (size_t i = 0; i < arenaBytes; i += 4)
if (std::memcmp(arena + i, expected.data() + i, 4))
{
+7 -6
View File
@@ -1,4 +1,5 @@
// SPDX-License-Identifier: MIT
#include "host_control.h"
#include "tmb_port.h"
#include "tmb_projection_math.h"
#include "tmb_vehicle_math.h"
@@ -78,17 +79,17 @@ int main()
setRegU32(&initial,31,caller); initial.pc=kind==2?0x1db0f0:0x1da238;
if(kind==2)setRegU32(&initial,4,(output+(n&15))|alias);
const unsigned control=((saved|0x1f80)&~0xe040u)|(mode<<13)|(n&1?0x8040:0);
_mm_setcsr(control); auto original=initial,native=initial;
_mm_setcsr(tmb::test::referenceControl(control)); auto original=initial,native=initial;
const auto fn=kind==2?mathfUnitMatrixAsm__FPA3_f_0x1db0f0:mathfMulVec4x4__FPA3_fP8_fvectorT1_0x1da238;
fn(ram,&original,&rt); std::memcpy(expected,ram+flat,512);
if(n<16){std::memcpy(full.get(),ram,bozo::kFlatBytes);++memoryCases;}
std::memcpy(ram+flat,input,512); (kind==2?identity:point)(ram,&native,&rt);
std::memcpy(ram+flat,input,512); _mm_setcsr(control); (kind==2?identity:point)(ram,&native,&rt);
const unsigned after=_mm_getcsr(); _mm_setcsr(saved);
if(std::memcmp(expected,ram+flat,512)||!cpu(original,native,initial)||after!=control||
if(std::memcmp(expected,ram+flat,512)||!cpu(original,native,initial)||!tmb::test::sameControl(after, control)||
(n<16&&std::memcmp(full.get(),ram,bozo::kFlatBytes)))
{
std::fprintf(stderr,"FAIL projection kind%u case%u mode%u data%d CPU%d FP%d\n",kind,n,mode,
std::memcmp(expected,ram+flat,512),cpu(original,native,initial),after==control);return 1;
std::memcmp(expected,ram+flat,512),cpu(original,native,initial),tmb::test::sameControl(after, control));return 1;
}
++cases;
}
@@ -136,7 +137,7 @@ int main()
const uint64_t ret=0xbad0000;std::memcpy(ram+0x30000+0x120,&ret,8);
}
d.updateLimit(&initial); std::memcpy(arenaInput.get(),ram+0x10000,0x40000);
const unsigned control=((saved|0x1f80)&~0xe040u)|(mode<<13)|(n&1?0x8040:0);
const unsigned control=tmb::test::referenceControl(((saved|0x1f80)&~0xe040u)|(mode<<13)|(n&1?0x8040:0)); // generated code on both sides: the game's rounding
_mm_setcsr(control); auto a=initial,b=initial;
rt.functions.setOverride(0x1da238,mathfMulVec4x4__FPA3_fP8_fvectorT1_0x1da238);
rt.functions.setOverride(0x1db0f0,mathfUnitMatrixAsm__FPA3_f_0x1db0f0);
@@ -146,7 +147,7 @@ int main()
rt.functions.setOverride(0x1da238,point);rt.functions.setOverride(0x1db0f0,identity);
try{caller(ram,&b,&rt);}catch(const bozo::ee::StopGuest&){require(b.pc==0xbad0000,"native caller stopped early");}
const unsigned after=_mm_getcsr();_mm_setcsr(saved);
if(!cpu(a,b,initial)||std::memcmp(arenaExpected.get(),ram+0x10000,0x40000)||after!=control||
if(!cpu(a,b,initial)||std::memcmp(arenaExpected.get(),ram+0x10000,0x40000)||!tmb::test::sameControl(after, control)||
(n<8&&std::memcmp(full.get(),ram,bozo::kFlatBytes)))
{std::fprintf(stderr,"FAIL caller kind%u case%u mode%u CPU%d\n",kind,n,mode,cpu(a,b,initial));return 2;}
++callers;
+7 -6
View File
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: MIT
// Actual sphere/LOD decisions and hierarchy-helper consumers, compiled from the local game ELF.
#include "host_control.h"
#include "tmb_port.h"
#include "tmb_native_math.h"
#include "tmb_hierarchy_math.h"
@@ -145,7 +146,7 @@ void testSphereLodCallers()
std::memset(ram + 0x13000, 0, 12); word(0x14000, 0x40400000); word(0x14004, 0x40800000); word(0x14008, 0);
}
snapshot(input.get()); auto a = initial, b = initial;
const unsigned control = ((saved | 0x1f80u) & ~0xe040u) | (mode << 13u) | (n & 1 ? 0x8040u : 0u);
const unsigned control = tmb::test::referenceControl(((saved | 0x1f80u) & ~0xe040u) | (mode << 13u) | (n & 1 ? 0x8040u : 0u)); // generated code on both sides: the game's rounding
host.enabled = false; services.yields = 0; services.stop = 0xffffffff;
_mm_setcsr(control);
try { function(ram, &a, rt.get()); }
@@ -156,9 +157,9 @@ void testSphereLodCallers()
snapshot(expected.get()); if (n < 4) { std::memcpy(whole.get(), ram, bozo::kFlatBytes); ++memoryCases; }
restore(); host.enabled = true; services.yields = 0;
_mm_setcsr(control); function(ram, &b, rt.get()); const auto after = _mm_getcsr(); _mm_setcsr(saved);
if (!cpuEqual(a, b) || !vuUntouched(initial, b) || after != refControl || services.yields != refYields || !dataEqual() ||
if (!cpuEqual(a, b) || !vuUntouched(initial, b) || !tmb::test::sameControl(after, refControl) || services.yields != refYields || !dataEqual() ||
(n < 4 && std::memcmp(whole.get(), ram, bozo::kFlatBytes)))
{ std::fprintf(stderr, "FAIL sphere/LOD kind %u case %u mode %u CPU%d VU%d FP%d data%d\n", kind,n,mode,cpuEqual(a,b),vuUntouched(initial,b),after==refControl,dataEqual()); throw std::runtime_error("sphere/LOD caller differs"); }
{ std::fprintf(stderr, "FAIL sphere/LOD kind %u case %u mode %u CPU%d VU%d FP%d data%d\n", kind,n,mode,cpuEqual(a,b),vuUntouched(initial,b),tmb::test::sameControl(after, refControl),dataEqual()); throw std::runtime_error("sphere/LOD caller differs"); }
require(b.pc == 0xbad0000 && getRegU32(&b, 29) == address(sp), "sphere/LOD return ABI"); ++cases;
}
std::printf("sphere/LOD: %u complete generated callers, %u whole-memory checks; complete CPU/clock/FP/selection exact outside retired VU/local W; native VU untouched\n", cases, memoryCases);
@@ -221,16 +222,16 @@ void testSphereLodCallers()
throw std::runtime_error("hierarchy helper continuation did not reach its query boundary");
};
auto a = initial, b = initial;
const auto control = ((saved | 0x1f80u) & ~0xe040u) | (mode << 13u) | (n & 1 ? 0x8040u : 0u);
const auto control = tmb::test::referenceControl(((saved | 0x1f80u) & ~0xe040u) | (mode << 13u) | (n & 1 ? 0x8040u : 0u)); // generated code on both sides: the game's rounding
_mm_setcsr(control);
try { run(false, a); }
catch (...) { std::fprintf(stderr, "hierarchy original kind %u case %u\n", kind, n); throw; }
const auto refControl = _mm_getcsr(); const auto refYields = services.yields;
snapshot(expected.get()); if (n < 4) { std::memcpy(whole.get(), ram, bozo::kFlatBytes); ++helperMemory; }
restore(); _mm_setcsr(control); run(true, b); const auto after = _mm_getcsr(); _mm_setcsr(saved);
if (!cpuEqual(a,b) || !vuUntouched(initial,b) || after != refControl || services.yields != refYields || !dataEqual() ||
if (!cpuEqual(a,b) || !vuUntouched(initial,b) || !tmb::test::sameControl(after, refControl) || services.yields != refYields || !dataEqual() ||
(n < 4 && std::memcmp(whole.get(),ram,bozo::kFlatBytes)))
{ std::fprintf(stderr,"FAIL hierarchy helper %x case %u mode %u CPU%d VU%d FP%d data%d\n",caller,n,mode,cpuEqual(a,b),vuUntouched(initial,b),after==refControl,dataEqual()); throw std::runtime_error("hierarchy helper consumer differs"); }
{ std::fprintf(stderr,"FAIL hierarchy helper %x case %u mode %u CPU%d VU%d FP%d data%d\n",caller,n,mode,cpuEqual(a,b),vuUntouched(initial,b),tmb::test::sameControl(after, refControl),dataEqual()); throw std::runtime_error("hierarchy helper consumer differs"); }
++helperCases;
}
_mm_setcsr(saved);
+8 -6
View File
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: MIT
// Compare actual generated original blocks against the production instruction dispatcher, including ordered aliases.
#include "host_control.h"
#include "tmb_vehicle_math.h"
#include "tmb_native_math.h"
#include "tmb_vehicle_original.h"
@@ -100,11 +101,12 @@ int main()
if (site.translation) setRegU32(&initial, site.translation, (translation | alias) + ((n >> 8u) & 15u));
R5900Context original = initial, native = initial;
const unsigned control = ((savedControl | 0x1f80u) & ~0xe040u) | (mode << 13u) | (n & 1u ? 0x8040u : 0u);
_mm_setcsr(control);
_mm_setcsr(tmb::test::referenceControl(control));
originalBlock(index, ram, original, rt.get());
std::memcpy(expected.data(), arena, arenaBytes);
if (n < 8) { std::memcpy(whole.get(), ram, bozo::kFlatBytes); ++wholeCases; }
std::memcpy(arena, input.data(), arenaBytes);
_mm_setcsr(control);
for (uint32_t pc = site.first; pc <= site.last; pc += 4)
{
if (!handler(ram, &native, rt.get(), pc)) return 2;
@@ -113,10 +115,10 @@ int main()
const unsigned after = _mm_getcsr();
_mm_setcsr(savedControl);
if (std::memcmp(arena, expected.data(), arenaBytes) || std::memcmp(&native, &initial, sizeof(initial)) ||
after != control || (n < 8 && std::memcmp(whole.get(), ram, bozo::kFlatBytes)))
!tmb::test::sameControl(after, control) || (n < 8 && std::memcmp(whole.get(), ram, bozo::kFlatBytes)))
{
std::fprintf(stderr, "FAIL vehicle block %u case %u mode %u: memory %d CPU/VU %d host %d\n", index, n, mode,
std::memcmp(arena, expected.data(), arenaBytes), std::memcmp(&native, &initial, sizeof(initial)), after == control);
std::memcmp(arena, expected.data(), arenaBytes), std::memcmp(&native, &initial, sizeof(initial)), tmb::test::sameControl(after, control));
return 4;
}
host.enabled = false;
@@ -177,7 +179,7 @@ int main()
for (auto &v : initial.vu0_vf) for (auto &bits : v.u) bits = randomBits();
initial.vu0_vf[0] = Vu0Vector{}; initial.vu0_vf[0].u[3] = 0x3f800000;
R5900Context original = initial, native = initial;
const unsigned control = ((savedControl | 0x1f80u) & ~0xe040u) | (mode << 13u) | (n & 1u ? 0x8040u : 0u);
const unsigned control = tmb::test::referenceControl(((savedControl | 0x1f80u) & ~0xe040u) | (mode << 13u) | (n & 1u ? 0x8040u : 0u)); // generated code on both sides: the game's rounding
_mm_setcsr(control);
host.enabled = false;
vehicleSetCsMat__7Vehicle_0x1ab250(ram, &original, rt.get());
@@ -195,10 +197,10 @@ int main()
std::memset(reinterpret_cast<uint8_t *>(&native) + vuAt, 0, vuBytes);
std::memset(reinterpret_cast<uint8_t *>(&original) + vuAt, 0, vuBytes);
if (std::memcmp(ram + vehicle, callerExpected.get(), callerBytes) || std::memcmp(&original, &native, sizeof(native)) ||
!untouched || after != control || (n < 4 && std::memcmp(ram, whole.get(), bozo::kFlatBytes)))
!untouched || !tmb::test::sameControl(after, control) || (n < 4 && std::memcmp(ram, whole.get(), bozo::kFlatBytes)))
{
std::fprintf(stderr, "FAIL complete vehicleSetCsMat case %u mode %u: memory %d CPU %d VU %d host %d\n", n, mode,
std::memcmp(ram + vehicle, callerExpected.get(), callerBytes), std::memcmp(&original, &native, sizeof(native)), untouched, after == control);
std::memcmp(ram + vehicle, callerExpected.get(), callerBytes), std::memcmp(&original, &native, sizeof(native)), untouched, tmb::test::sameControl(after, control));
return 8;
}
if (native.cycles != 16 || native.checkpoints != 2 || native.pc != 0xbad0000) return 9;
+221 -7
View File
@@ -1,5 +1,8 @@
"""Player-facing migration and timing regression checks; no game data required."""
import configparser
import contextlib
import json
import os
import re
import sys
import tempfile
import io
@@ -18,7 +21,7 @@ from unittest.mock import patch
from types import SimpleNamespace
REQUIRED = (
'TMB Launcher.exe', 'README.txt', 'CHANGELOG.md', 'LICENSES/TMB_Recomp/LICENSE',
'TMB Launcher.exe', 'README.txt', 'CHANGELOG.md', 'recomplauncher.json', 'LICENSES/TMB_Recomp/LICENSE',
'LICENSES/BozoEngine/LICENSE', 'source/release.ini', 'kit/kit_manifest.json',
'kit/python/python.exe', 'source/tools/tmb_build.py', 'source/BozoEngine/CMakeLists.txt',
'kit/deps/sdl3-src/CMakeLists.txt', 'kit/deps/imgui-src/imgui.cpp',
@@ -123,11 +126,111 @@ class ReleaseTests(unittest.TestCase):
self.assertFalse((root / 'PS2Recomp').exists())
self.assertTrue((root / 'tools/linked').exists())
def test_only_native_engine_is_a_submodule(self):
config = configparser.ConfigParser()
config.read(ROOT / '.gitmodules')
self.assertEqual(config.sections(), ['submodule "BozoEngine"'])
self.assertEqual(config[config.sections()[0]]['path'], 'BozoEngine')
@staticmethod
def release_source(folder, files):
"""A release's source folder: the files, dated as an unzip of the release zip dates them, and its listing."""
root = Path(folder) / 'source'
for name, data in files.items():
(root / name).parent.mkdir(parents=True, exist_ok=True)
(root / name).write_bytes(data)
(root / 'release_files.txt').write_text(''.join(n + '\n' for n in sorted(files)) + 'release_files.txt\n',
encoding='utf-8')
return root
@staticmethod
def date(root, ns):
for p in root.rglob('*'):
if p.is_file():
os.utime(p, ns=(ns, ns))
def settle(self, root, out, now, kit=None):
with patch.object(tmb_build, 'ROOT', str(root)), contextlib.redirect_stdout(io.StringIO()):
tmb_build.settle_source_times(str(out), kit, now_ns=now)
def test_source_dated_in_the_future_is_dated_now(self):
# Issue 60: the zip's commit time, read as local time west of UTC, is hours ahead; ninja then never settles.
now = 1_800_000_000 * 10**9
with tempfile.TemporaryDirectory() as folder:
root = self.release_source(folder, {'CMakeLists.txt': b'project', 'runtime/a.cpp': b'a'})
kit = Path(folder) / 'kit'
(kit / 'deps/sdl3-src').mkdir(parents=True)
(kit / 'deps/sdl3-src/CMakeLists.txt').write_bytes(b'sdl')
module = kit / 'ucrt64/share/cmake/Modules/FindPython.cmake' # build.ninja's input too
module.parent.mkdir(parents=True)
module.write_bytes(b'module')
self.date(root, now + 3 * 3600 * 10**9)
self.date(kit, now + 3 * 3600 * 10**9)
out = Path(folder) / 'build'
out.mkdir()
self.settle(root, out, now, str(kit))
for p in (root / 'CMakeLists.txt', root / 'runtime/a.cpp', kit / 'deps/sdl3-src/CMakeLists.txt', module):
self.assertEqual(p.stat().st_mtime_ns, now)
record = json.loads((out / tmb_build.SOURCE_TIMES).read_text(encoding='utf-8'))
self.assertIn('source/runtime/a.cpp', record)
self.assertIn('deps/sdl3-src/CMakeLists.txt', record)
def test_first_build_keeps_past_times(self):
now = 1_800_000_000 * 10**9
with tempfile.TemporaryDirectory() as folder:
root = self.release_source(folder, {'runtime/a.cpp': b'a'})
self.date(root, now - 10**12)
out = Path(folder) / 'build'
out.mkdir()
self.settle(root, out, now)
self.assertEqual((root / 'runtime/a.cpp').stat().st_mtime_ns, now - 10**12)
def test_update_dates_changed_files_now_and_restores_unchanged_ones(self):
# An update unzipped over a game built after the update's commit: its files are older than the build's.
built, commit, now = 1_800_000_000 * 10**9, 1_799_990_000 * 10**9, 1_800_100_000 * 10**9
with tempfile.TemporaryDirectory() as folder:
root = self.release_source(folder, {'runtime/same.cpp': b'same', 'runtime/fixed.cpp': b'old'})
self.date(root, built - 10**12)
out = Path(folder) / 'build'
out.mkdir()
self.settle(root, out, built)
(root / 'runtime/fixed.cpp').write_bytes(b'new')
(root / 'runtime/added.cpp').write_bytes(b'added')
with open(root / 'release_files.txt', 'a', encoding='utf-8') as f:
f.write('runtime/added.cpp\n')
self.date(root, commit)
self.settle(root, out, now)
self.assertEqual((root / 'runtime/same.cpp').stat().st_mtime_ns, built - 10**12)
self.assertEqual((root / 'runtime/fixed.cpp').stat().st_mtime_ns, now)
self.assertEqual((root / 'runtime/added.cpp').stat().st_mtime_ns, now)
def test_update_without_a_record_over_a_build_rebuilds_everything(self):
# 0.5.1 and earlier wrote no record: an update over their build cannot tell what changed.
commit, now = 1_799_990_000 * 10**9, 1_800_100_000 * 10**9
with tempfile.TemporaryDirectory() as folder:
root = self.release_source(folder, {'runtime/a.cpp': b'a'})
self.date(root, commit)
out = Path(folder) / 'build'
(out / 'build').mkdir(parents=True)
(out / 'build/build.ninja').write_bytes(b'')
self.settle(root, out, now)
self.assertEqual((root / 'runtime/a.cpp').stat().st_mtime_ns, now)
def test_checkout_is_left_alone(self):
now = 1_800_000_000 * 10**9
with tempfile.TemporaryDirectory() as folder:
root = Path(folder) / 'source'
root.mkdir()
(root / 'CMakeLists.txt').write_bytes(b'project')
os.utime(root / 'CMakeLists.txt', ns=(now + 10**12, now + 10**12))
self.settle(root, Path(folder), now)
self.assertEqual((root / 'CMakeLists.txt').stat().st_mtime_ns, now + 10**12)
self.assertFalse((Path(folder) / tmb_build.SOURCE_TIMES).exists())
def test_engine_is_a_pinned_release(self):
# BozoEngine comes from its releases (cmake/bozo_engine.json, fetched by cmake/bozo_engine_fetch.cmake), no
# longer from a submodule.
self.assertFalse((ROOT / '.gitmodules').exists())
pin = json.loads((ROOT / 'cmake/bozo_engine.json').read_text(encoding='utf-8'))
self.assertRegex(pin['version'], r'^[0-9]+\.[0-9]+\.[0-9]+$')
self.assertRegex(pin['sha256'], r'^[0-9a-f]{64}$')
fetch = (ROOT / 'cmake/bozo_engine_fetch.cmake').read_text(encoding='utf-8')
self.assertIn('EXPECTED_HASH SHA256=${bozo_engine_sha256}', fetch)
self.assertIn('/BozoEngine/', (ROOT / '.gitignore').read_text(encoding='utf-8').splitlines())
def test_migration_zip_supports_the_existing_installation_layout(self):
with tempfile.TemporaryDirectory() as folder:
@@ -186,5 +289,116 @@ class TimingTests(unittest.TestCase):
self.assertTrue(check_timing.check('')[0].startswith('FAIL:'))
class RecompLauncherTests(unittest.TestCase):
"""recomplauncher.json (RecompLauncher's manifest, recomplauncher.com/sdk) and what it runs."""
def manifest(self):
return json.loads((ROOT / 'recomplauncher.json').read_text(encoding='utf-8'))
def test_progress_lines_follow_the_steps(self):
self.assertEqual(tmb_build.progress_line(('PROGRESS', 'verify', '1/8', 'Checking the disc')),
'progress 0.000 Checking the disc')
before = sum(tmb_build.STEP_WEIGHTS[s] for s in tmb_build.STEPS[:tmb_build.STEPS.index('packs')])
half = (before + tmb_build.STEP_WEIGHTS['packs'] / 2) / sum(tmb_build.STEP_WEIGHTS.values())
self.assertEqual(tmb_build.progress_line(('PERCENT', 'packs', 50)),
'progress %.3f %s (50%%)' % (half, tmb_build.STEP_TITLES['packs']))
for other in (('SKIP', 'verify', '1/8'), ('DONE', 'stage', '8/8', 1.0), ('INFO', 'total', '1 s'),
('ERROR', 'compile', 'x')):
self.assertIsNone(tmb_build.progress_line(other))
self.assertEqual(set(tmb_build.STEP_WEIGHTS), set(tmb_build.STEPS))
# The launcher's own step weights (its progress bar), so both bars move alike.
model = (ROOT / 'launcher' / 'src' / 'build_model.cpp').read_text(encoding='utf-8')
self.assertEqual(dict((k, int(v)) for k, v in re.findall(r'\{"([a-z]+)", ([0-9]+)\}', model)),
tmb_build.STEP_WEIGHTS)
shares = []
for step in tmb_build.STEPS:
for parts in (('PROGRESS', step, '', ''), ('PERCENT', step, 37), ('PERCENT', step, 100)):
shares.append(float(tmb_build.progress_line(parts).split()[1]))
self.assertEqual(shares, sorted(shares))
self.assertTrue(0 <= shares[0] and shares[-1] < 1)
def test_a_missing_disc_says_why_and_an_earlier_build_keeps_one(self):
with tempfile.TemporaryDirectory() as folder:
def run(*extra):
return subprocess.run([sys.executable, '-I', '-X', 'utf8', str(ROOT / 'tools' / 'tmb_build.py'),
'--out', str(Path(folder) / 'build'), '--game', str(Path(folder) / 'game')]
+ list(extra), capture_output=True, text=True, encoding='utf-8')
r = run('--progress-lines')
self.assertEqual(r.returncode, 1)
self.assertIn('ERROR verify no disc image given', r.stdout.strip().splitlines()[-1])
# No --disc: the disc image an earlier build kept in the game folder (keeps_copy). Here it is not a disc.
(Path(folder) / 'game').mkdir()
(Path(folder) / 'game' / 'disc.iso').write_bytes(b'\0' * 65536)
r = run('--check')
self.assertEqual(r.returncode, 1)
self.assertIn('ERROR verify disc.iso', r.stdout)
def test_manifest_runs_what_the_release_ships(self):
m = self.manifest()
self.assertEqual(m['format'], 1)
self.assertEqual(m['repo'], 'TheBozos/TMB_Recomp')
disc = m['inputs'][0]
self.assertEqual(disc['id'], 'game')
self.assertEqual(disc['check']['iso9660'], tmb_build.ELF_NAME)
self.assertEqual(disc['check']['ids'], ['SCUS-97101'])
# Redump's Twisted Metal: Black (USA), SCUS-97101 v1.00: its one dump, a DVD-5 (redump.org/disc/15035).
self.assertEqual(disc['dumps'], [{'name': 'USA', 'size': 3799744512, 'crc32': '347e93f9'}])
prepare, start = m['prepare'], m['start']
self.assertEqual(prepare['program'], ['kit/python/python.exe'])
self.assertIn('kit/python/python.exe', REQUIRED)
self.assertIn('{install}/source/tools/tmb_build.py', prepare['args'])
self.assertIn('source/tools/tmb_build.py', REQUIRED)
# The disc as one argument: RecompLauncher leaves it out when the player's copy is gone (keeps_copy).
self.assertTrue(prepare['keeps_copy'])
self.assertEqual([a for a in prepare['args'] if '{input:game}' in a], ['--disc={input:game}'])
help_text = subprocess.run([sys.executable, '-I', str(ROOT / 'tools' / 'tmb_build.py'), '--help'],
capture_output=True, text=True, check=True).stdout
for flag in (a.split('=', 1)[0] for a in prepare['args'] if a.startswith('--')):
self.assertIn(flag, help_text)
self.assertIn('--progress-lines', prepare['args'])
# The working folder is the program's (kit/python): every path RecompLauncher passes is {install}'s.
for a in prepare['args']:
if '/' in a:
self.assertTrue(a.split('=', 1)[-1].startswith(('{install}/', '{input:')), a)
self.assertEqual(prepare['done'], ['{install}/game/built_from.ini'])
self.assertEqual(start['program'], ['game/' + tmb_build.GAME_EXE + '.exe'])
self.assertEqual(start['args'], ['--elf', '{install}/game/' + tmb_build.ELF_NAME, '--iso',
'{install}/game/disc.iso'])
# Everything the game writes (cards, settings, logs, save states) in RecompLauncher's {data}.
self.assertEqual(start['env'], {'PS2X_USER_DIR': '{data}'})
self.assertEqual(m['saves'], ['{data}/mc0', '{data}/mc1'])
def test_settings_are_keys_the_game_reads(self):
m = self.manifest()
self.assertEqual(m['config'], [{'format': 'ini', 'file': [{'path': '{data}/video.ini'}]}])
source = ROOT / 'BozoEngine' / 'runtime' / 'app' / 'video_settings.cpp'
if not source.is_file():
self.skipTest('no BozoEngine tree (cmake -P cmake/bozo_engine_fetch.cmake)')
written = set(re.findall(r'<< "([a-z_]+) = "', source.read_text(encoding='utf-8')))
self.assertIn('widescreen', written)
ids = [s['id'] for s in m['settings']]
self.assertEqual(len(ids), len(set(ids)))
for setting in m['settings']:
keys = set(setting['defaults'])
for choice in setting['choices']:
self.assertEqual(set(choice['set']), keys, setting['id'])
for key in keys:
section, name = key.split('/')
self.assertEqual(section, 'video')
self.assertIn(name, written)
values = [c['set'][k] for c in setting['choices'] for k in keys]
self.assertEqual(len(values), len(set(values)), setting['id'])
self.assertIn(setting['defaults'], [c['set'] for c in setting['choices']], setting['id'])
def test_release_zip_carries_the_manifest_at_its_top(self):
with tempfile.TemporaryDirectory() as folder:
path = Path(folder) / 'no_manifest.zip'
with zipfile.ZipFile(path, 'w') as archive:
for name in REQUIRED:
if name != 'recomplauncher.json':
archive.writestr('TMB_Recomp_Bozo/' + name, b'fixture')
self.assertIn('TMB_Recomp_Bozo/recomplauncher.json is missing', make_release.verify_zip(path))
if __name__ == '__main__':
unittest.main()
+1 -1
View File
@@ -2,7 +2,7 @@
"""make_build_kit: assembles the build kit tools/tmb_build.py uses on a PC with nothing installed (no MSYS2, git,
network or Python): a compiler, CMake and Ninja, a minimal static FFmpeg, the libraries' sources (SDL3, Dear ImGui)
and an embeddable Python. The game is built on BozoEngine, whose sources come with TMB_Recomp's (the BozoEngine
submodule, in a release's source/BozoEngine): its recompiler is built on the player's PC with the rest. Run once on the
release cmake/bozo_engine.json pins, in a release's source/BozoEngine): its recompiler is built on the player's PC with the rest. Run once on the
developer's PC (MSYS2 UCRT64 installed, network for the downloads); the kit is build output, never committed.
python tools/make_build_kit.py --out D:/tmb_kit/kit [--downloads D:/tmb_kit/downloads] [--zip D:/tmb_kit/kit.zip]
+30 -29
View File
@@ -8,9 +8,10 @@ redistributes.
python tools/make_release.py --out D:/tmb_release --publish --dry-run (the version from the commit's tag)
What it does, from <commit> (default HEAD; only committed files count, the working tree is never read):
export git archive of the commit and of the BozoEngine submodule at the commit it records (without its
reference/ records, which the build never reads) -> source\\ (no .git, no build/, nothing generated);
source\\release.ini stamps the version and both commits. The tree is audited: no ELF, IRX, disc image,
export git archive of the commit -> source\\ (no .git, no build/, nothing generated), and the BozoEngine
release its cmake/bozo_engine.json pins -> source\\BozoEngine (cmake/bozo_engine_fetch.cmake: the
release's archive, SHA-256 checked); source\\release.ini stamps the version, the commit and the
engine's version. The tree is audited: no ELF, IRX, disc image,
pack, generated code or disc file name may be in it.
kit the build kit (--kit <dir>: an existing one, hard-linked into the release; else assembled by
tools/make_build_kit.py, which needs MSYS2 and the network): a BozoEngine kit (kit_version 2: SDL3 and
@@ -27,7 +28,8 @@ What it does, from <commit> (default HEAD; only committed files count, the worki
changelog CHANGELOG.md's section for the version (## [x.y.z], Keep a Changelog), from the commit: the release
refuses to be made without one (an empty one, or only "Unreleased", too) unless
--allow-missing-changelog (test builds). CHANGELOG.md is shipped at the zip's top (the launcher's
"What's new" reads it) and the section is the release notes' "What's new".
"What's new" reads it) and the section is the release notes' "What's new". recomplauncher.json (the
commit's) is shipped at the zip's top too, where RecompLauncher reads it.
zip TMB_Recomp-<version>.zip (deflate, entries sorted, every timestamp the commit's), <zip>.sha256,
RELEASE_NOTES.md (the changelog section, the hashes, the source offer: the GitHub release's body). The
zip's names are audited again.
@@ -60,14 +62,14 @@ import zipfile
ROOT = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))
REPO = 'TheBozos/TMB_Recomp'
ENGINE_REPO = 'TheBozos/BozoEngine'
ENGINE_DIR = 'BozoEngine' # the submodule
# What BozoEngine's export leaves out (its reference records: hashes of recorded runs, never read by the build).
ENGINE_SKIP = ('reference',)
ENGINE_DIR = 'BozoEngine' # the release cmake/bozo_engine.json pins
NAME = 'TMB_Recomp'
# The BozoEngine build: its zips are <NAME>-<version>-bozo(.zip, -sources.zip) and the folder in them TOP, so they
# sit beside the fork build's (<NAME>-<version>.zip, folder TMB_Recomp) on a release page and on a player's disk.
FLAVOR = 'bozo'
TOP = 'TMB_Recomp_Bozo'
# RecompLauncher's manifest (recomplauncher.com/sdk): at the repo's top, shipped at the zip's top.
RECOMPLAUNCHER_JSON = 'recomplauncher.json'
VERSION_RE = re.compile(r'^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$')
MSYS2_SOURCES = 'https://repo.msys2.org/mingw/sources/'
# The launcher's font (launcher/CMakeLists.txt pins the same commit and hash).
@@ -375,7 +377,7 @@ class Release:
self.migration_zip = os.path.join(self.out, '%s-%s.zip' % (NAME, self.version))
self.sources_zip = os.path.join(self.out, self.name + '-sources.zip')
self.commit_date = int(git('show', '-s', '--format=%ct', self.commit))
self.engine_commit = None
self.engine_version = None
self.manifest = None
self.msys_sources = [] # (package base, version, licence, url, file, sha256)
@@ -396,21 +398,16 @@ class Release:
rmtree(self.stage)
os.makedirs(self.source)
extract_tar_stream([find_git(), 'archive', '--format=tar', self.commit], self.source, ROOT)
entry = git('ls-tree', self.commit, ENGINE_DIR).split()
if len(entry) < 3 or entry[0] != '160000':
raise ReleaseError('%s is not a submodule at %s' % (ENGINE_DIR, self.commit))
self.engine_commit = entry[2]
engine_repo = os.path.join(ROOT, ENGINE_DIR)
try:
git('cat-file', '-e', self.engine_commit + '^{commit}', cwd=engine_repo)
except ReleaseError:
raise ReleaseError('the submodule does not have %s: git submodule update --init %s'
% (self.engine_commit, ENGINE_DIR))
engine_dst = os.path.join(self.source, ENGINE_DIR)
os.makedirs(engine_dst, exist_ok=True)
extract_tar_stream([find_git(), 'archive', '--format=tar', self.engine_commit], engine_dst, engine_repo)
for skip in ENGINE_SKIP:
rmtree(os.path.join(engine_dst, skip))
with open(os.path.join(self.source, 'cmake', 'bozo_engine.json'), encoding='utf-8') as f:
self.engine_version = json.load(f)['version']
cmake = shutil.which('cmake')
if not cmake and os.path.isfile(os.path.join(self.args.msys, 'ucrt64', 'bin', 'cmake.exe')):
cmake = os.path.join(self.args.msys, 'ucrt64', 'bin', 'cmake.exe')
if not cmake:
raise ReleaseError('no cmake on PATH: it fetches the BozoEngine release (cmake/bozo_engine_fetch.cmake)')
os.makedirs(self.downloads, exist_ok=True)
run([cmake, '-DBOZO_ENGINE_DOWNLOADS=' + self.downloads, '-P',
os.path.join(self.source, 'cmake', 'bozo_engine_fetch.cmake')])
# The list of the source's files: tmb_build removes the ones a newer release unzipped over this one no longer
# has (CMake globs runtime/*.cpp: a deleted file left behind would still be compiled).
files = sorted(os.path.relpath(os.path.join(d, n), self.source).replace('\\', '/')
@@ -419,14 +416,14 @@ class Release:
write_text(os.path.join(self.source, 'release_files.txt'), '\n'.join(sorted(set(files))) + '\n')
write_text(os.path.join(self.source, 'release.ini'),
'# The TMB_Recomp release this folder is (tools/make_release.py writes this file).\n'
'version = %s\ncommit = %s\nengine = BozoEngine\nengine_commit = %s\ndate = %s\n'
% (self.version, self.commit, self.engine_commit,
'version = %s\ncommit = %s\nengine = BozoEngine\nengine_version = %s\ndate = %s\n'
% (self.version, self.commit, self.engine_version,
time.strftime('%Y-%m-%d', time.gmtime(self.commit_date))))
problems = audit_tree(self.source, rel_prefix='source/')
if problems:
raise ReleaseError('the source export holds what looks like game data:\n ' + '\n '.join(problems[:20]))
n = sum(len(f) for _d, _s, f in os.walk(self.source))
log(' source: %s + BozoEngine %s, %d files, %.1f MB, audited' % (self.commit[:12], self.engine_commit[:12], n,
log(' source: %s + BozoEngine %s, %d files, %.1f MB, audited' % (self.commit[:12], self.engine_version, n,
dir_size(self.source) / 1e6))
# -- the kit
@@ -639,7 +636,7 @@ class Release:
'TMB_Recomp (source\\, this release\'s code; MIT, LICENSES\\TMB_Recomp)',
' https://github.com/%s/tree/%s' % (REPO, self.commit),
'BozoEngine, the recompiler and runtime the game is built on (source\\BozoEngine; MIT, LICENSES\\BozoEngine)',
' https://github.com/%s/tree/%s' % (ENGINE_REPO, self.engine_commit),
' https://github.com/%s/releases/tag/v%s' % (ENGINE_REPO, self.engine_version),
' The whole source is in source\\ already, the launcher\'s too (source\\launcher).',
'',
'The build kit (kit\\) redistributes these programs and libraries unmodified. Their corresponding source:',
@@ -775,6 +772,10 @@ class Release:
at = at + 1 if at >= 0 else len(text)
text = text[:at] + '## [%s] - test build\n\n%s\n\n' % (self.version, self.changelog_section) + text[at:]
write_text(os.path.join(self.stage, 'CHANGELOG.md'), text, crlf=True)
# RecompLauncher's manifest at the top, next to the launcher, where RecompLauncher reads it: the commit's.
manifest = git('show', '%s:%s' % (self.commit, RECOMPLAUNCHER_JSON), binary=True)
with open(os.path.join(self.stage, RECOMPLAUNCHER_JSON), 'wb') as f:
f.write(manifest)
# -- the changelog
@@ -852,7 +853,7 @@ class Release:
'Subsequent BozoEngine updates use `-bozo.zip` with either installation folder name.',
'',
'## Build information', '',
'- Code: %s (`%s`), BozoEngine `%s`' % (REPO, self.commit, self.engine_commit),
'- Code: %s (`%s`), BozoEngine %s' % (REPO, self.commit, self.engine_version),
'- Build kit: GCC %s, CMake %s, Ninja %s (MSYS2 UCRT64), FFmpeg %s (LGPL, static), Python %s'
% (self.pkg_version('gcc'), self.pkg_version('cmake'), self.pkg_version('ninja'),
self.manifest['ffmpeg']['version'], self.manifest['python']['version']),
@@ -1000,7 +1001,7 @@ def verify_zip(path, top=TOP):
problems.append('%s: an ELF file' % n)
if len(head) >= 0x8006 and head[0x8001:0x8006] == b'CD001':
problems.append('%s: an ISO9660 volume' % n)
for need in ('TMB Launcher.exe', 'README.txt', 'CHANGELOG.md', 'LICENSES/TMB_Recomp/LICENSE',
for need in ('TMB Launcher.exe', 'README.txt', 'CHANGELOG.md', RECOMPLAUNCHER_JSON, 'LICENSES/TMB_Recomp/LICENSE',
'LICENSES/BozoEngine/LICENSE', 'source/release.ini', 'kit/kit_manifest.json',
'kit/python/python.exe', 'source/tools/tmb_build.py', 'source/BozoEngine/CMakeLists.txt',
'kit/deps/sdl3-src/CMakeLists.txt', 'kit/deps/imgui-src/imgui.cpp'):
+138 -7
View File
@@ -1,8 +1,8 @@
#!/usr/bin/env python3
"""tmb_build: from the player's own Twisted Metal: Black disc (USA, SCUS-97101) to a game folder that runs, in one
command. Nothing derived from the game is distributed: the disc's files, the generated code, the packs and the
executable are all made here, on the player's PC. The game is built on BozoEngine (the BozoEngine submodule, at the
commit this code pins; --engine <dir> for another tree).
executable are all made here, on the player's PC. The game is built on BozoEngine (the release cmake/bozo_engine.json
pins, in BozoEngine/: a release's source has it, a git checkout fetches it; --engine <dir> for another tree).
python tools/tmb_build.py --disc "Twisted Metal - Black (USA).iso" --out D:/TMB
python tools/tmb_build.py --disc D:/TMB_Recomp/game_us --out D:/TMB (an extracted disc folder)
@@ -106,19 +106,46 @@ class BuildError(Exception):
pass
# --progress-lines: RecompLauncher's setup step (recomplauncher.json's prepare) reads "progress <0 to 1> <text>" lines.
PROGRESS_LINES = False
# Each step's share of the bar: its usual seconds on a first build (launcher/src/build_model.cpp's kSteps).
STEP_WEIGHTS = {'verify': 1, 'extract': 2, 'configure': 60, 'tools': 7, 'recompile': 2, 'packs': 32, 'compile': 55,
'stage': 1}
def emit(*parts):
print(' '.join(str(p) for p in parts), flush=True)
if PROGRESS_LINES:
line = progress_line(parts)
if line:
print(line, flush=True)
def progress_line(parts):
"""RecompLauncher's line for a PROGRESS (a step starts) or PERCENT (it moves on) line, else None: the share of the
whole build done, and the step's title (recomplauncher.com/sdk, prepare)."""
if len(parts) < 3 or parts[0] not in ('PROGRESS', 'PERCENT') or parts[1] not in STEP_WEIGHTS:
return None
step = parts[1]
pct = int(parts[2]) if parts[0] == 'PERCENT' else 0
before = sum(STEP_WEIGHTS[s] for s in STEPS[:STEPS.index(step)])
done = (before + STEP_WEIGHTS[step] * min(max(pct, 0), 100) / 100) / sum(STEP_WEIGHTS.values())
return 'progress %.3f %s%s' % (min(done, 0.999), STEP_TITLES[step], ' (%d%%)' % pct if parts[0] == 'PERCENT' else '')
def load_engine(path=None):
"""BozoEngine's tree (--engine, else the submodule) and its disc reader."""
"""BozoEngine's tree (--engine, else the pinned release, fetched in a git checkout) and its disc reader."""
global ENGINE, ps2_disc
if path:
ENGINE = os.path.abspath(path)
tools = os.path.join(ENGINE, 'tools', 'native_pack')
fetch = os.path.join(ROOT, 'cmake', 'bozo_engine_fetch.cmake')
if not path and os.path.exists(os.path.join(ROOT, '.git')) and shutil.which('cmake'):
# A checkout follows cmake/bozo_engine.json (nothing is downloaded while BozoEngine/.release matches it).
subprocess.run([shutil.which('cmake'), '-P', fetch], check=False)
if not os.path.isfile(os.path.join(tools, 'ps2_disc.py')):
raise SystemExit('ERROR verify BozoEngine is missing (%s): the release is incomplete, or in a git checkout run '
'"git submodule update --init BozoEngine"' % ENGINE)
'"cmake -P cmake/bozo_engine_fetch.cmake"' % ENGINE)
sys.path.insert(0, tools)
import ps2_disc as module # noqa: E402
ps2_disc = module
@@ -728,6 +755,7 @@ class Build:
redo_from = STEPS.index(self.args.redo) if self.args.redo else len(STEPS)
n = len(STEPS)
dirty = False
ran = False
total_start = time.time()
for i, step in enumerate(STEPS, 1):
self.step = step
@@ -740,7 +768,7 @@ class Build:
emit('INFO', 'stopped', 'after ' + step)
return 0
continue
dirty = True # every later step runs again (Ninja only redoes what changed)
dirty = ran = True # every later step runs again (Ninja only redoes what changed)
emit('PROGRESS', step, '%d/%d' % (i, n), STEP_TITLES[step])
t = time.time()
self.state[step] = {'done': False}
@@ -769,6 +797,8 @@ class Build:
launcher = os.path.join(self.game, 'Play TMB.cmd' if os.name == 'nt' else 'play_tmb.sh')
emit('INFO', 'total', '%.1f s' % (time.time() - total_start))
emit('RESULT', self.game, launcher)
if PROGRESS_LINES:
print('progress 1 %s' % ('Ready to play' if ran else 'Already built'), flush=True)
return 0
@@ -826,12 +856,13 @@ def check_disc(path):
def main():
ap = argparse.ArgumentParser(description='Builds Twisted Metal: Black (USA) as a native PC game from your own disc.')
ap.add_argument('--disc', required=True, help='the disc image (.iso, .bin, .cue) or an extracted disc folder')
ap.add_argument('--disc', help='the disc image (.iso, .bin, .cue) or an extracted disc folder (default: the '
'disc.iso an earlier build left in the game folder)')
ap.add_argument('--out', default='tmb_build', help='the work folder; the game ends up in <out>/TMB')
ap.add_argument('--game', help='the game folder to stage (default: <out>/TMB)')
ap.add_argument('--check', action='store_true', help='only check the disc (no work folder): OK <message> or '
'ERROR verify <message>')
ap.add_argument('--engine', help='BozoEngine\'s source tree (default: the BozoEngine submodule)')
ap.add_argument('--engine', help='BozoEngine\'s source tree (default: the release cmake/bozo_engine.json pins, in BozoEngine/)')
ap.add_argument('--kit', help='the build kit folder (default: <TMB_Recomp>/kit or <its parent>/kit if present)')
ap.add_argument('--no-kit', action='store_true', help='do not use a build kit even if one is found')
ap.add_argument('--toolchain', help='compiler folder (with bin/g++, cmake, ninja), default: the kit, PATH, '
@@ -844,13 +875,28 @@ def main():
ap.add_argument('--jobs', type=int, default=os.cpu_count() or 4)
ap.add_argument('--redo', choices=STEPS, help='run this step and the ones after it again')
ap.add_argument('--stop-after', choices=STEPS, help='stop once this step is done')
ap.add_argument('--progress-lines', action='store_true', help='also print "progress <0 to 1> <text>" lines, for '
'RecompLauncher (recomplauncher.json)')
args = ap.parse_args()
global PROGRESS_LINES
PROGRESS_LINES = args.progress_lines
if not args.disc:
# Built before: the game folder keeps the disc image (a link to the player's, or a copy), so an update builds
# again without it (RecompLauncher's keeps_copy, after the player deleted their own).
kept = os.path.join(os.path.abspath(args.game) if args.game else os.path.join(os.path.abspath(args.out), 'TMB'),
'disc.iso')
if not os.path.isfile(kept):
emit('ERROR', 'verify', 'no disc image given (--disc) and none kept from an earlier build: pick your '
'Twisted Metal: Black disc image (USA, SCUS-97101)')
sys.exit(1)
args.disc = kept
load_engine(args.engine)
if args.check:
sys.exit(check_disc(args.disc))
os.makedirs(os.path.abspath(args.out), exist_ok=True)
if not os.environ.get(ALIAS_ENV):
remove_stale_sources()
settle_source_times(os.path.abspath(args.out), find_kit(args))
if needs_ascii_aliases(args):
sys.exit(run_through_aliases(args))
sys.exit(Build(args).main())
@@ -904,6 +950,91 @@ def remove_stale_sources():
emit('INFO', 'update', '%d files of an earlier release removed from %s' % (removed, ROOT))
SOURCE_TIMES = 'source_times.json'
def settle_source_times(out, kit, now_ns=None):
"""A release zip dates every file at its commit's time (tools/make_release.py), which an unzip takes as local
time. Two failures follow for ninja, which only compares times:
- dated in the future (unzipped west of UTC within hours of the commit): build.ninja, regenerated, stays older
than CMakeLists.txt forever ("manifest 'build.ninja' still dirty after 100 tries");
- dated before the player's last build (an update unzipped over a game built after the commit): a changed file
looks older than its object and is not compiled again.
So the release's source files (release_files.txt) and the kit's FetchContent sources (deps/) are re-dated here,
from <out>/source_times.json (each file's size, time and SHA-1 as the last run left them): a file whose content changed,
or new to this release, is dated now; one unchanged gets its time back; nothing stays in the future. Without that
record and with a build folder from before, every file is dated now: everything is built again, once. The rest of
the kit (the toolchain: CMake's own modules are build.ninja's inputs too, the compiler's headers every object's)
only comes back from the future. A git checkout (no release_files.txt) is left alone: git dates the files it
writes now."""
listing = os.path.join(ROOT, 'release_files.txt')
if not os.path.isfile(listing):
return
now = now_ns if now_ns is not None else time.time_ns()
future = 0
if kit and os.path.isdir(kit):
for dirpath, _dirs, names in os.walk(kit):
for n in names:
p = os.path.join(dirpath, n)
try:
if os.stat(p).st_mtime_ns > now:
os.utime(p, ns=(now, now))
future += 1
except OSError:
pass
files = []
with open(listing, encoding='utf-8') as f:
files += [('source/' + l.strip(), os.path.join(ROOT, *l.strip().split('/'))) for l in f if l.strip()]
deps = os.path.join(kit, 'deps') if kit else None
if deps and os.path.isdir(deps):
for dirpath, dirs, names in os.walk(deps):
dirs.sort()
for n in sorted(names):
p = os.path.join(dirpath, n)
files.append(('deps/' + os.path.relpath(p, deps).replace('\\', '/'), p))
record_path = os.path.join(out, SOURCE_TIMES)
try:
with open(record_path, encoding='utf-8') as f:
old = json.load(f)
if not isinstance(old, dict):
old = None
except (OSError, ValueError):
old = None
built_before = os.path.isfile(os.path.join(out, 'build', 'build.ninja'))
record, changed = {}, 0
for key, path in files:
try:
st = os.stat(path)
except OSError:
continue
mtime = st.st_mtime_ns
rec = old.get(key) if old else None
if rec and rec[0] == st.st_size and rec[1] == mtime:
digest, target = rec[2], mtime # untouched since the last build
else:
digest = sha1_file(path)
if rec and rec[2] == digest:
target = rec[1] # the same content: its time at the last build
elif rec or old is not None or built_before:
target = now # changed, new to this release, or unknown with a build from before
changed += 1
else:
target = mtime # a first build: nothing to be older than
if target > now:
target = now
future += 1
if target != mtime:
os.utime(path, ns=(target, target))
record[key] = [st.st_size, target, digest]
tmp = record_path + '.tmp'
with open(tmp, 'w', encoding='utf-8') as f:
json.dump(record, f, separators=(',', ':'))
os.replace(tmp, record_path)
if changed or future:
emit('INFO', 'update', '%d source files dated now (%d changed or new, %d were dated in the future)'
% (changed + future, changed, future))
# ---- folders whose path is not ASCII (Windows) ----
#
# MSYS2's binutils open files in the ANSI code page: ld cannot open an object or library whose path, read from the
+1 -1
View File
@@ -77,7 +77,7 @@ import struct
import sys
import zlib
# native_pack: BozoEngine's tools/ (BOZO_ENGINE_TOOLS, or the BozoEngine submodule).
# native_pack: BozoEngine's tools/ (BOZO_ENGINE_TOOLS, or the pinned release in BozoEngine/).
_root = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')
for _tools in (os.environ.get('BOZO_ENGINE_TOOLS', ''), os.path.join(_root, 'BozoEngine', 'tools')):
if _tools and os.path.isdir(os.path.join(_tools, 'native_pack')):
+1 -1
View File
@@ -25,7 +25,7 @@ import struct
import sys
import zlib
# native_pack: BozoEngine's tools/ (BOZO_ENGINE_TOOLS, or the BozoEngine submodule).
# native_pack: BozoEngine's tools/ (BOZO_ENGINE_TOOLS, or the pinned release in BozoEngine/).
_root = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')
for _tools in (os.environ.get('BOZO_ENGINE_TOOLS', ''), os.path.join(_root, 'BozoEngine', 'tools')):
if _tools and os.path.isdir(os.path.join(_tools, 'native_pack')):