8 changed files with 493 additions and 5 deletions

No files matched your search

+50 -1
View File
@@ -93,7 +93,56 @@ if(TMB_VU1_AOT_SOURCES)
target_sources(ps2EntryRunner PRIVATE $<TARGET_OBJECTS:tmb_vu1_aot>)
endif()
target_sources(ps2EntryRunner PRIVATE ${TMB_GENERATED_SOURCES} ${TMB_RUNTIME_SOURCES})
# The reference harness (docs/REFERENCE_HARNESS.md): the game's library and kernel stubs (the generated code's stub
# list, ps2_recompiled_stubs.h: name_0xaddress) whose calls PS2X_REFERENCE records, and the build's name (the two
# repositories' commits when configured), as a source in the build tree.
set(_tmb_stub_list "${TMB_GENERATED_DIR}/ps2_recompiled_stubs.h")
set(_tmb_call_names "")
set(_tmb_call_count 0)
if(EXISTS "${_tmb_stub_list}")
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${_tmb_stub_list}")
file(STRINGS "${_tmb_stub_list}" _tmb_stub_lines REGEX "^void [A-Za-z0-9_]+_0x[0-9a-fA-F]+\\(")
foreach(_tmb_line IN LISTS _tmb_stub_lines)
if(_tmb_line MATCHES "^void ([A-Za-z0-9_]+)_0x([0-9a-fA-F]+)\\(")
string(APPEND _tmb_call_names " {0x${CMAKE_MATCH_2}u, \"${CMAKE_MATCH_1}\"},\n")
math(EXPR _tmb_call_count "${_tmb_call_count} + 1")
endif()
endforeach()
endif()
if(_tmb_call_count EQUAL 0)
set(_tmb_call_names " {0u, \"\"},\n")
endif()
find_package(Git QUIET)
set(_tmb_commit "unknown")
set(_tmb_fork_commit "unknown")
if(GIT_FOUND)
execute_process(COMMAND "${GIT_EXECUTABLE}" rev-parse --short HEAD WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}"
OUTPUT_VARIABLE _tmb_commit OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET)
execute_process(COMMAND "${GIT_EXECUTABLE}" rev-parse --short HEAD WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}/PS2Recomp"
OUTPUT_VARIABLE _tmb_fork_commit OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET)
endif()
file(WRITE "${CMAKE_BINARY_DIR}/tmb_call_names.cpp.in"
"// Generated by CMakeLists.txt from ${_tmb_stub_list}: do not edit.
#include \"runtime/ps2_reference.h\"
#include <cstddef>
namespace tmb
{
extern const char *const kBuildName;
extern const ps2x::reference::CallName kCallNames[];
extern const size_t kCallNameCount;
const char *const kBuildName = \"TMB_Recomp ${_tmb_commit} fork ${_tmb_fork_commit}\";
const ps2x::reference::CallName kCallNames[] = {
${_tmb_call_names} };
const size_t kCallNameCount = ${_tmb_call_count};
}
")
configure_file("${CMAKE_BINARY_DIR}/tmb_call_names.cpp.in" "${CMAKE_BINARY_DIR}/tmb_call_names.cpp" COPYONLY)
set_source_files_properties("${CMAKE_BINARY_DIR}/tmb_call_names.cpp" PROPERTIES
SKIP_UNITY_BUILD_INCLUSION ON SKIP_PRECOMPILE_HEADERS ON)
message(STATUS "TMB_Recomp: ${_tmb_call_count} stub addresses for the reference records")
target_sources(ps2EntryRunner PRIVATE ${TMB_GENERATED_SOURCES} ${TMB_RUNTIME_SOURCES} "${CMAKE_BINARY_DIR}/tmb_call_names.cpp")
target_include_directories(ps2EntryRunner PRIVATE "${TMB_GENERATED_DIR}")
list(LENGTH TMB_GENERATED_SOURCES _tmb_count)
+121
View File
@@ -0,0 +1,121 @@
# The reference harness
Phase 0 of BozoEngine (its spec: `D:\BozoEngine\docs\specs\harness.md`): TMB on its current runtime (the PS2Recomp
fork) runs deterministically and records, per game frame, what the guest computed. Two runs with the same scripted
input write the same file; a later runtime must write the same records.
## Running
```sh
PS2X_DETERMINISTIC=1 PS2X_REFERENCE=run.ref PS2X_REFERENCE_FRAMES=9000 PS2X_USER_DIR=<empty folder> \
PS2X_PAD_SCRIPT="<frame:BUTTON/frames,...>" build/game_us/PS2Recomp/ps2xRuntime/ps2EntryRunner game_us/SCUS_971.01
tools/ref_compare.py a.ref b.ref
```
- `PS2X_DETERMINISTIC=1`: the deterministic mode (below). Off, every path is as before.
- `PS2X_REFERENCE=<file.ref>`: the recorder. Works in either mode (only deterministic runs compare equal).
- `PS2X_REFERENCE_FRAMES=<n>`: the process exits (0) once n frames are recorded.
- `PS2X_REFERENCE_CALLS=<n>` (default 120), `PS2X_REFERENCE_CALLS_FROM=<f>`: the full call lists of n frames from
frame f, as text, in `<file>.ref.calls`.
- `PS2X_REFERENCE_DUMP=<f>[-<g>][,...]`: RAM (32 MB) then scratchpad (16 KB) of those frames in `<file>.ref.ram.<f>`.
- `PS2X_REFERENCE_MASK=<address>:<bytes>[,...]`: RAM hashed as zeros there (listed in the header). None is needed for
TMB; `PS2X_REFERENCE_CHECK_HOST=1` scans RAM every 600 frames for words that look like host addresses (into the
host's copy of RAM or the scratchpad, or near the runtime's own data) and logs them.
- `PS2X_REFERENCE_RUN=<name>`: the run's name in the header (default: the file's stem).
- `PS2X_USER_DIR=<folder>`: a fresh folder per run, so the memory cards start pristine and the settings default.
Pad scripts in deterministic mode are keyed on game frames: `frame:BUTTON/frames` (held 30 frames when not given);
`PS2X_PAD2_SCRIPT` .. `PS2X_PAD4_SCRIPT` alike. `tools/ref_pad_script.py` converts a timed script: run it once with
`PS2X_DETERMINISTIC=1 PS2X_PAD_CLOCK=wall PS2X_PAD_LOG=1` (the pad on the wall clock, each change logged with its
frame; that run is not deterministic), then `--log <its log> --from-log` gives pad 1's presses at the frames they
landed, and `--log <log> "<timed script>"` maps any other timed script through the same anchors.
## What deterministic mode does
The run-to-run variation found in the code (`D:\BozoEngine\docs\notes\tmb-determinism.md`) and what each became:
| # | Source | Deterministic mode |
|---|---|---|
| 1 | The frame step from host time (`FramePacer::frameEnd`), the EE cycles charged at the frame end from it, TMB's field carry | `FramePacer` returns exactly one period of the cap (1/60 s); TMB charges exactly `294912000 / field rate` EE cycles less what the frame accounted (`nativeFrameEnd`), so one field per frame, no carry. The window is still held to 60 fps (pacing only) |
| 2 | `sceCdReadClock` from the host's date (TMB seeds its RNG from it) | 2001-06-18 12:00:00 (`ps2x::det::fixedDate`); OSD time zone UTC |
| 3 | The IOP on the host clock (`PS2X_IOP_WALLCLOCK`, which TMB sets), the IOP thread | Ignored: the IOP advances only by the EE cycles accounted, on the EE thread (`PS2X_IOP_THREAD` ignored) |
| 4 | The native mixer rendered on the audio device thread | Mixed on the IOP's clock: 768 IOP cycles per 48 kHz sample, brought up to the current IOP cycle before every libsd call and at the end of every IOP slice (`NativeMixer::advanceTo`), so envelopes, ended voices, input positions and the input's half interrupts change only at IOP points. The device only drains a 16384-sample queue (silence when dry, oldest dropped when full). The emulated SPU2 is never on the wall clock |
| 5 | Pad scripts in seconds; host keyboard / gamepads; players from plugged gamepads | Scripts in game frames (the frame count only moves at frame ends: latched per frame); no host input (`PS2X_PAD_NO_HOST` forced, `PS2X_PAD_INPUT` / `PS2X_PAD_RECORD` off); players 2-4 present only by their scripts; a pad port with no player behind it (port 2 while the multitap is on port 1) reads at rest instead of falling back to the host's keyboard and first gamepad (found by the first proof runs: its sticks read 0x7f or 0x80 with the window's focus) |
| 6 | EE wall-clock catch-up (`PS2X_EE_CATCHUP`, on by default) and host deadlines | Off; every scheduled event is due by its cycle alone; vblank holds ignored; an idle wait still sleeps (pacing) but always charges exactly the cycles to the next event; `waitHostDeadline` (other ports' frame waits) completes at the next dispatch point |
| 7 | Movies: picture clock from host time, host-deadline waits, decode time charged to the EE | Frame-clocked: pictures paced by the vblank count (which follows EE cycles), no host deadline, decode time not charged. A movie still plays whole (it ends no game frame, so the pad script's frame clock stands still through it) |
| 8 | Lens flare depth read back from the GPU into guest RAM; `inMatch` from a 100 ms host-time window | Flare samples all far (0); `inMatch` / the menus' window measured in game frames (frame count / 60), so a frame's kind follows the kinds of the frames before it |
| 9 | Memory card contents and dates; file dates | A fresh `PS2X_USER_DIR` per run (pristine card); every card and file date is the fixed date |
| 10 | Settings window actions (Cheats tab) | The tab shows nothing but a note; only the environment's cheats apply (from launch). `TMB_CHEATS_TOGGLE` off |
Beyond the list: the MPEG decode charge and `waitHostDeadline` (above), the OSD time zone, file `getstat` dates.
Left as they are (checked: no guest-visible effect, or not used by TMB's native port): the GS front end and VIF1
thread (absent in the native port), the CD read-ahead threads (the guest waits for them synchronously), the renderer's
present thread (reads published frames only), host-side statistics and traces.
## The record file
Little-endian, packed. Hashes: XXH64 (seed 0) for `ram`, `scratchpad`, `calls`, `draws`, `threads`; the sound is
FNV-1a 64. No hash ever takes a host pointer: textures are identified by their content.
Header (240 bytes, then `maskCount` pairs of u32 {address, bytes}):
| Offset | Type | Field |
|---|---|---|
| 0 | char[8] | magic `PS2XREF1` |
| 8 | u32 | version (1) |
| 12 | u32 | headerBytes (240 + 8 x maskCount: where the records start) |
| 16 | u32 | recordBytes (80) |
| 20 | u32 | hash (1: XXH64 seed 0, sound FNV-1a 64) |
| 24 | u32 | ramBytes (33554432) |
| 28 | u32 | scratchpadBytes (16384) |
| 32 | u64 | elfHash: XXH64 of the ELF file |
| 40 | u32 | flags: bit 0 deterministic mode |
| 44 | u32 | maskCount |
| 48 | char[64] | run name |
| 112 | char[64] | build ("TMB_Recomp <commit> fork <commit>", as configured) |
| 176 | char[64] | the ELF's file name |
Record (80 bytes), one per game frame. A game frame ends where the game hands its picture over
(`EeScheduler::presentGuestFrame`: TMB's `timer1Handler` / `sceGsSyncV`, menus and loading screens included; movies
end none). Frame 0 is everything up to the first one.
| Offset | Type | Field |
|---|---|---|
| 0 | u32 | frame |
| 4 | i32 | thread: the guest thread running at the frame end |
| 8 | u64 | ram: XXH64 of the 32 MB of EE RAM (masked ranges as zeros) at the frame end |
| 16 | u64 | scratchpad: XXH64 of the 16 KB scratchpad |
| 24 | u64 | calls: XXH64 of the frame's calls, each 7 u32 {id, a0, a1, a2, a3, v0, flags}, in call order |
| 32 | u64 | draws: the frame's published draw lists (below) |
| 40 | u64 | sound: FNV-1a 64 of the stereo int16 samples mixed during the frame (0 when none) |
| 48 | u64 | threads: XXH64 of i32 {running thread, then the ready threads in run order} |
| 56 | u64 | eeCycle: the EE cycle count at the frame end |
| 64 | u32 | callCount |
| 68 | u32 | drawBatches |
| 72 | u32 | drawVertices |
| 76 | u32 | soundSamples (800 a frame once the mix runs at one field per frame) |
Calls: the dispatcher's calls (JAL / JALR) to the game's library and kernel stubs, the 362 addresses of the generated
code's stub list (`ps2_recompiled_stubs.h`, compiled into `build/.../tmb_call_names.cpp` at configure time), and raw
`syscall`s. `id` is FNV-1a 32 of the stub's name with the top bit clear, or `0x80000000 | number` for a syscall;
`a0`-`a3` the argument registers' low words; `v0` the result's low word; `flags` 1 when the call blocked (its result
comes later), 2 when the frame ended inside it (`sceGsSyncV`, TMB's frame end). A tail jump compiled to a direct call
is not seen. The `.calls` side file lists them as text: name, id, a0-a3, result.
Draws: per published list (kind 1 the 3D frame at `Renderer::endFrame`, 2 the 2D overlay at `publishOverlay`, 3 a
movie picture at `setBackdrop`) h = XXH64(kind), then per batch h = XXH64(words, h) of 8 u64 {tex0, texa, region,
the flags packed (textured, blend << 8, alphaRef << 16, alphaTest << 24, depthTest << 25, depthWrite << 26, clampU
<< 27, clampV << 28, fog << 29, sampleTarget << 30, fromGsContext << 31, alphaBlend << 32, context << 40), fogColour,
texture identity (XXH64 of its RGBA texels seeded with XXH64 of {width, height}; 0 for none), vertex count, 0}, then
each GS write {address, value} of a GS-context batch, the matrix (16 floats), the clip (4 floats) and the vertices
(32 bytes each: x, y, z, u, v, rgba, fog, q). The frame's `draws` folds each list's h in order: d = XXH64({d, h}).
## Comparing
`tools/ref_compare.py a.ref b.ref [--ignore field,...]` prints both headers, then either `identical: N frames
compared` or the first frame where any field differs, every field that differs there with both values, and the first
frame each field differs at. With RAM dumps of that frame from both runs (`PS2X_REFERENCE_DUMP=<frame>`), the first
differing 32-byte block (address, both runs' bytes); with both runs' call lists of the first frame whose calls differ
(`PS2X_REFERENCE_CALLS_FROM=<frame> PS2X_REFERENCE_CALLS=1`), the two lists side by side from their first difference.
Exit status 0 when identical, 1 when not.
+8 -1
View File
@@ -28,6 +28,7 @@
#include "ps2_runtime.h"
#include "ps2_recompiled_functions.h"
#include "runtime/ps2_debug_ui.h"
#include "runtime/ps2_determinism.h"
#if defined(PS2X_ENABLE_DEBUG_UI)
#include "imgui.h"
#endif
@@ -242,6 +243,12 @@ namespace tmb::cheats
void drawTab()
{
// Deterministic mode: nothing the user does may change the run (only the environment's cheats, from launch).
if (ps2x::det::enabled())
{
ImGui::TextDisabled("Off in deterministic mode (PS2X_DETERMINISTIC=1): the environment's cheats only.");
return;
}
const uint8_t *rdram = g_rdram.load(std::memory_order_relaxed);
const uint32_t game = g_theGame.load(std::memory_order_relaxed);
const int players = rdram ? playerCount(rdram, game) : 0;
@@ -354,7 +361,7 @@ namespace tmb::cheats
const char *value = std::getenv("TMB_CHEATS_TOGGLE");
return value && *value ? std::atof(value) : 0.0;
}();
if (s_toggle > 0.0)
if (s_toggle > 0.0 && !ps2x::det::enabled())
{
const double now = std::chrono::duration<double>(std::chrono::steady_clock::now().time_since_epoch()).count();
static double s_next = now + s_toggle;
+11 -1
View File
@@ -25,6 +25,7 @@
#include "runtime/native/native_vu1_sandbox.h"
#include "runtime/ps2_memory.h"
#include "runtime/native/native_display.h"
#include "runtime/ps2_determinism.h"
#include "runtime/native/native_gs_hook.h"
#include "tmb_host.h"
#include "tmb_meshes.h"
@@ -198,9 +199,13 @@ namespace tmb::native
}
// A match is under way while its frames end (the end of real-time processing, onFrameEnd) less than 100 ms
// apart on the host's clock; the menus (the shell overlay's loop) end none.
// apart on the host's clock; the menus (the shell overlay's loop) end none. PS2X_DETERMINISTIC=1: the clock is
// the game frames ended (a sixtieth of a second each), so which frames count as a match's or a menu's is the
// kinds of the frames before, never the host's timing.
double hostSeconds()
{
if (ps2x::det::enabled())
return static_cast<double>(ps2x::det::frame()) / 60.0;
static const auto s_start = std::chrono::steady_clock::now();
return std::chrono::duration<double>(std::chrono::steady_clock::now() - s_start).count();
}
@@ -3401,6 +3406,9 @@ namespace tmb::native
}
if (!s_on || !enabled() || !inMatch())
return;
// Deterministic mode: every sample far (as the caller cleared them): the GPU's depth is host timing.
if (ps2x::det::enabled())
return;
ps2x::native::Renderer &renderer = ps2x::native::Renderer::instance();
renderer.wantDepth();
uint64_t bitbltbuf = 0, trxpos = 0, trxreg = 0;
@@ -3461,6 +3469,8 @@ namespace tmb::native
std::fill(z, z + 16, 0u);
if (!flareDepthNative())
return false;
if (ps2x::det::enabled()) // deterministic mode: all far (the GPU's depth is host timing)
return true;
ps2x::native::Renderer &renderer = ps2x::native::Renderer::instance();
renderer.wantDepth();
const ps2x::native::Screen view = screen();
+21 -1
View File
@@ -9,6 +9,8 @@
#include "runtime/gs/gs_draw_estimate.h"
#include "runtime/ps2_memory.h"
#include "runtime/native/native_display.h"
#include "runtime/ps2_determinism.h"
#include "runtime/ps2_reference.h"
#include "runtime/sampling_profiler_gate.h"
#include "tmb_host.h"
#include <string>
@@ -41,6 +43,11 @@ namespace tmb
{
extern std::atomic<bool> g_rainLiftOff; // runtime/vu1/tmb_vu1_rain.cpp
extern std::atomic<uint64_t> g_rainLiftedStrips;
// The build's name and the game's stub addresses for the reference records (tmb_call_names.cpp, which CMake
// generates in the build tree from the generated code's stub list).
extern const char *const kBuildName;
extern const ps2x::reference::CallName kCallNames[];
extern const size_t kCallNameCount;
}
namespace tmb::native
@@ -1125,7 +1132,10 @@ namespace
s_last = now;
}
EeScheduler &scheduler = runtime->eeScheduler();
const uint64_t real = static_cast<uint64_t>(step * static_cast<double>(EeScheduler::kEeClockHz));
// PS2X_DETERMINISTIC=1: exactly one field's EE cycles (the step is one field too).
const uint64_t real = ps2x::det::enabled()
? EeScheduler::kEeClockHz / static_cast<uint64_t>(fieldRate(rdram, gp))
: static_cast<uint64_t>(step * static_cast<double>(EeScheduler::kEeClockHz));
const uint64_t accounted = scheduler.currentCycle() - g_frameEndCycle;
for (uint64_t debt = real > accounted ? real - accounted : 0u; debt != 0u;)
{
@@ -1722,6 +1732,16 @@ namespace
g_traceIdle = true;
runtime.eeScheduler().setIdleObserver([](const EeScheduler::IdleRecord &record) { g_frameIdle.push_back(record); });
}
// PS2X_REFERENCE (the reference harness, docs/REFERENCE_HARNESS.md): the build, and the game's library and
// kernel stubs whose calls the records hash (their addresses from the generated stub list: tmb_call_names.cpp).
if (ps2x::reference::active())
{
ps2x::reference::setBuild(tmb::kBuildName);
ps2x::reference::setCallNames(tmb::kCallNames, tmb::kCallNameCount);
}
if (ps2x::det::enabled())
std::cout << "[tmb] deterministic mode (PS2X_DETERMINISTIC=1): a field per frame, fixed date, pad scripts in frames"
<< std::endl;
runtime.registerFunction(kVblankHandler, &vblankHandlerOverride);
runtime.registerFunction(kHier, &hierOverride);
tmb::native::install(); // TMB_NATIVE
+170
View File
@@ -0,0 +1,170 @@
#!/usr/bin/env python3
"""Compares two reference records (PS2X_REFERENCE=<file.ref>, docs/REFERENCE_HARNESS.md) frame by frame.
tools/ref_compare.py a.ref b.ref [--ignore eeCycle,...] [--lines 24]
Reports the frames compared and the first frame where a field differs (every field that differs there, and the first
frame each field differs at). For `ram`, when both runs dumped that frame (PS2X_REFERENCE_DUMP=<frame>: <file>.ram.<frame>),
the first differing 32-byte block (its address and both runs' bytes); for `calls`, when both have the frame's call list
(PS2X_REFERENCE_CALLS / _FROM: <file>.calls), the two lists side by side from their first difference.
Exit status 0: identical over the frames both have (and the same length); 1: they differ; 2: unreadable input.
"""
import argparse
import os
import struct
import sys
HEADER = struct.Struct('<8sIIIIIIQII64s64s64s')
RECORD = struct.Struct('<IiQQQQQQQIIII')
FIELDS = ('frame', 'thread', 'ram', 'scratchpad', 'calls', 'draws', 'sound', 'threads', 'eeCycle', 'callCount',
'drawBatches', 'drawVertices', 'soundSamples')
# The order fields are reported in (the guest's state first, then what it went through, then the counters).
COMPARED = ('ram', 'scratchpad', 'calls', 'callCount', 'draws', 'drawBatches', 'drawVertices', 'sound', 'soundSamples',
'threads', 'thread', 'eeCycle')
HEXED = {'ram', 'scratchpad', 'calls', 'draws', 'sound', 'threads'}
class Reference:
def __init__(self, path):
self.path = path
with open(path, 'rb') as f:
data = f.read()
if len(data) < HEADER.size:
raise ValueError(f'{path}: too short for a header')
(magic, version, header_bytes, record_bytes, hash_id, ram_bytes, sp_bytes, elf_hash, flags, mask_count, run,
build, elf) = HEADER.unpack_from(data, 0)
if magic != b'PS2XREF1':
raise ValueError(f'{path}: not a reference record (magic {magic!r})')
if record_bytes != RECORD.size:
raise ValueError(f'{path}: records of {record_bytes} bytes, this tool reads {RECORD.size}')
self.version, self.hash_id, self.elf_hash, self.flags = version, hash_id, elf_hash, flags
self.ram_bytes, self.sp_bytes = ram_bytes, sp_bytes
self.run, self.build, self.elf = (s.split(b'\0', 1)[0].decode(errors='replace') for s in (run, build, elf))
self.masks = [struct.unpack_from('<II', data, HEADER.size + 8 * i) for i in range(mask_count)]
body = data[header_bytes:]
count = len(body) // RECORD.size
self.records = [dict(zip(FIELDS, RECORD.unpack_from(body, i * RECORD.size))) for i in range(count)]
self.partial = len(body) % RECORD.size
def describe(self):
return (f'{self.path}: run "{self.run}", build "{self.build}", ELF {self.elf} {self.elf_hash:016x}, '
f'{"deterministic" if self.flags & 1 else "NOT deterministic"}, {len(self.records)} frames'
+ (f', {len(self.masks)} masked ranges' if self.masks else '')
+ (f' (+{self.partial} bytes of a cut record)' if self.partial else ''))
def value(field, v):
return f'{v:016x}' if field in HEXED else str(v)
def ram_block(a, b, frame):
"""The first differing 32-byte block of RAM (then the scratchpad) between the two runs' dumps of `frame`."""
pa, pb = f'{a.path}.ram.{frame}', f'{b.path}.ram.{frame}'
if not (os.path.exists(pa) and os.path.exists(pb)):
return f' (no RAM dumps of frame {frame}: run both again with PS2X_REFERENCE_DUMP={frame} for the first differing block)'
with open(pa, 'rb') as fa, open(pb, 'rb') as fb:
da, db = fa.read(), fb.read()
lines = []
for offset in range(0, min(len(da), len(db)), 32):
if da[offset:offset + 32] != db[offset:offset + 32]:
where = f'RAM {offset:08x}' if offset < a.ram_bytes else f'scratchpad {offset - a.ram_bytes:04x}'
lines.append(f' first differing 32-byte block: {where}')
lines.append(f' {a.run:>12}: {da[offset:offset + 32].hex(" ", 4)}')
lines.append(f' {b.run:>12}: {db[offset:offset + 32].hex(" ", 4)}')
differing = sum(1 for o in range(0, min(len(da), len(db)), 32) if da[o:o + 32] != db[o:o + 32])
lines.append(f' ({differing} blocks differ in all)')
return '\n'.join(lines)
return ' (the dumps are the same: the hash differs elsewhere, a masked range?)'
def call_list(path, frame):
"""The call list of `frame` from <file>.calls, or None."""
calls = path + '.calls'
if not os.path.exists(calls):
return None
found, lines = False, []
with open(calls, encoding='utf-8', errors='replace') as f:
for line in f:
if line.startswith('frame '):
if found:
break
found = int(line.split()[1]) == frame
continue
if found:
lines.append(line.rstrip('\n').strip())
return lines if found else None
def call_lists(a, b, frame, shown):
la, lb = call_list(a.path, frame), call_list(b.path, frame)
if la is None or lb is None:
return (f' (no call lists of frame {frame} in both: run both with PS2X_REFERENCE_CALLS_FROM={frame} '
f'PS2X_REFERENCE_CALLS=1 to see them)')
first = next((i for i in range(max(len(la), len(lb))) if i >= len(la) or i >= len(lb) or la[i] != lb[i]), None)
if first is None:
return ' (the lists read the same: the difference is in a value the text rounds?)'
width = max([len(x) for x in la[first:first + shown]] + [len(a.run), 10])
out = [f' calls from #{first} ({len(la)} / {len(lb)} calls):', f' {a.run:<{width}} | {b.run}']
for i in range(first, min(max(len(la), len(lb)), first + shown)):
left = la[i] if i < len(la) else ''
right = lb[i] if i < len(lb) else ''
out.append(f' {"*" if left != right else " "} {left:<{width}} | {right}')
return '\n'.join(out)
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('a')
parser.add_argument('b')
parser.add_argument('--ignore', default='', help='fields not compared, comma-separated (e.g. eeCycle)')
parser.add_argument('--lines', type=int, default=24, help='call list lines shown from the first difference')
args = parser.parse_args()
try:
a, b = Reference(args.a), Reference(args.b)
except (OSError, ValueError) as error:
print(error, file=sys.stderr)
return 2
print(a.describe())
print(b.describe())
if a.elf_hash != b.elf_hash:
print('warning: not the same ELF')
if a.masks != b.masks:
print('warning: not the same masked RAM ranges')
ignored = {f for f in args.ignore.split(',') if f}
unknown = ignored - set(COMPARED)
if unknown:
print(f'unknown fields: {", ".join(sorted(unknown))} (fields: {", ".join(COMPARED)})', file=sys.stderr)
return 2
fields = [f for f in COMPARED if f not in ignored]
frames = min(len(a.records), len(b.records))
first_by_field = {}
first = None
for i in range(frames):
ra, rb = a.records[i], b.records[i]
if ra['frame'] != i or rb['frame'] != i:
print(f'record {i}: frame numbers {ra["frame"]} / {rb["frame"]} (a record missing?)')
for f in fields:
if ra[f] != rb[f] and f not in first_by_field:
first_by_field[f] = i
if first is None and any(ra[f] != rb[f] for f in fields):
first = i
if first is None:
same = len(a.records) == len(b.records)
print(f'identical: {frames} frames compared ({", ".join(fields)})'
+ ('' if same else f'; lengths differ ({len(a.records)} / {len(b.records)} frames)'))
return 0 if same else 1
ra, rb = a.records[first], b.records[first]
print(f'first difference at frame {first} (of {frames} compared; the {first} before are identical):')
for f in fields:
if ra[f] != rb[f]:
print(f' {f:<13} {value(f, ra[f]):>16} {value(f, rb[f]):>16}')
print('first frame each field differs at: ' + ', '.join(f'{f} {n}' for f, n in sorted(first_by_field.items(), key=lambda x: x[1])))
if 'ram' in first_by_field and first_by_field['ram'] == first:
print(ram_block(a, b, first))
if 'calls' in first_by_field:
print(call_lists(a, b, first_by_field['calls'], args.lines))
return 1
if __name__ == '__main__':
sys.exit(main())
+111
View File
@@ -0,0 +1,111 @@
#!/usr/bin/env python3
"""A timed pad script (PS2X_PAD_SCRIPT, seconds) as a frame-keyed one for deterministic mode (PS2X_DETERMINISTIC=1:
"frame:BUTTON/frames"), docs/REFERENCE_HARNESS.md.
tools/ref_pad_script.py --log calibration.log "<seconds script>" (or --script-file f)
tools/ref_pad_script.py --log calibration.log --from-log
Calibration: run the timed script once in deterministic mode with the pad on the wall clock and its changes logged
(PS2X_DETERMINISTIC=1 PS2X_PAD_CLOCK=wall PS2X_PAD_LOG=1, stderr to calibration.log): each "[pad] frame N t=T" line
anchors second T to game frame N. A time between two anchors maps linearly between their frames, outside them at 60
frames a second from the nearest one; holds become frames at 60 a second (at least 1). --from-log: pad 1's script
rebuilt from the logged changes themselves (each press at the frame it began in the calibration run, held as long),
the closest to what the calibration run did. Without --log, seconds map to frames at 60 a second from frame 0
(`--offset` frames added): for scripts already written in game time, such as the driving part of a match counted
from its start.
"""
import argparse
import bisect
import re
import sys
BUTTONS = {0x0080: 'LEFT', 0x0040: 'DOWN', 0x0020: 'RIGHT', 0x0010: 'UP', 0x0008: 'START', 0x0004: 'R3', 0x0002: 'L3',
0x0001: 'SELECT', 0x8000: 'SQUARE', 0x4000: 'CROSS', 0x2000: 'CIRCLE', 0x1000: 'TRIANGLE', 0x0800: 'R1',
0x0400: 'L1', 0x0200: 'R2', 0x0100: 'L2'}
LOG_LINE = re.compile(r'\[pad\] frame (\d+) t=([0-9.]+): scripted ([0-9a-f]+)')
def anchors_from(log_path):
points = []
with open(log_path, encoding='utf-8', errors='replace') as f:
for line in f:
m = LOG_LINE.search(line)
if m:
points.append((float(m.group(2)), int(m.group(1))))
points.sort()
return points
def from_log(log_path):
"""Pad 1's presses as the calibration run logged them: frame pressed, button, frames held."""
presses, down, since = [], 0, {}
with open(log_path, encoding='utf-8', errors='replace') as f:
for line in f:
m = LOG_LINE.search(line)
if not m:
continue
frame, mask = int(m.group(1)), int(m.group(3), 16)
for bit, name in BUTTONS.items():
if mask & bit and not down & bit:
since[bit] = frame
elif down & bit and not mask & bit:
presses.append((since[bit], name, max(1, frame - since[bit])))
down = mask
for bit, name in BUTTONS.items():
if down & bit: # still held when the log ends: held to the end
presses.append((since[bit], name, 1000000))
presses.sort()
return ','.join(f'{f}:{b}/{h}' for f, b, h in presses)
def to_frame(seconds, anchors, offset):
if not anchors:
return offset + round(seconds * 60.0)
times = [t for t, _ in anchors]
i = bisect.bisect_right(times, seconds)
if i == 0:
t, f = anchors[0]
return max(0, f - round((t - seconds) * 60.0))
if i == len(anchors):
t, f = anchors[-1]
return f + round((seconds - t) * 60.0)
(t0, f0), (t1, f1) = anchors[i - 1], anchors[i]
if t1 == t0:
return f0
return round(f0 + (f1 - f0) * (seconds - t0) / (t1 - t0))
def convert(script, anchors, offset):
out = []
for entry in filter(None, (e.strip() for e in script.replace('\n', ',').split(','))):
when, _, press = entry.partition(':')
button, _, held = press.partition('/')
frames = max(1, round(float(held) * 60.0 / 1000.0)) if held else 30
out.append((to_frame(float(when), anchors, offset), button, frames))
out.sort()
return ','.join(f'{f}:{b}/{h}' for f, b, h in out)
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('script', nargs='?', default=None)
parser.add_argument('--script-file')
parser.add_argument('--log', help="a calibration run's log (PS2X_PAD_LOG=1 lines)")
parser.add_argument('--from-log', action='store_true', help="pad 1's script from the logged changes")
parser.add_argument('--offset', type=int, default=0, help='frames added (without --log)')
args = parser.parse_args()
if args.from_log:
if not args.log:
parser.error('--from-log needs --log')
print(from_log(args.log))
return 0
script = open(args.script_file).read() if args.script_file else args.script
if not script:
parser.error('no script')
anchors = anchors_from(args.log) if args.log else []
print(convert(script, anchors, args.offset))
return 0
if __name__ == '__main__':
sys.exit(main())