Lower vehicle and light directions and keep resumed particles native

Extend native XYZ direction math to audited vehicle collision-point, tire-height and light-node callers. Retain original ABI fallbacks outside those callers and add generated consumer comparisons.

Fix the native flare fallback exposed by a live 4P scheduler continuation: use durable backend/options selection and keep native depth available across host-time gaps. Add a regression that fails on the prior path without a live particleDraw call scope.

Validate ten native suites, twelve release-tool tests, full 9500/8500-frame baseline/default/strict comparisons and complete RAM snapshots, plus movie/loading/1P/4P window reruns and reviewed captures. Document the initial timing-sensitive stall and remaining acceptance limits.

Co-Authored-By: Codex <[email protected]>
This commit is contained in:
Thomas MartinandCodex committed 2026-11-07 03:25:21 +01:00
1 parent 582099259a
commit 889b086d47
10 files changed
+397 -10

No files matched your search

+6
View File
@@ -210,6 +210,12 @@ target_link_libraries(tmb-native-hud-tests PRIVATE tmb_runtime tmb_generated boz
if(MINGW)
target_link_options(tmb-native-hud-tests PRIVATE -static -Wl,--stack,268435456)
endif()
add_executable(tmb-native-particle-tests EXCLUDE_FROM_ALL tests/native_particle_tests.cpp)
target_include_directories(tmb-native-particle-tests PRIVATE "${CMAKE_SOURCE_DIR}/runtime" ${gen_dir})
target_link_libraries(tmb-native-particle-tests PRIVATE tmb_runtime tmb_generated bozo_host)
if(MINGW)
target_link_options(tmb-native-particle-tests PRIVATE -static -Wl,--stack,268435456)
endif()
add_executable(tmb-native-vehicle-tests EXCLUDE_FROM_ALL tests/native_vehicle_tests.cpp)
target_include_directories(tmb-native-vehicle-tests PRIVATE "${CMAKE_SOURCE_DIR}/runtime" ${gen_dir})
target_compile_options(tmb-native-vehicle-tests PRIVATE -ffp-contract=off -frounding-math)
+6
View File
@@ -38,6 +38,12 @@ inverse transforms and BSP plane distances, their original-caller tests and RAM
[`NATIVE_DIRECTIONS.md`](NATIVE_DIRECTIONS.md) adds three hot BSP collision direction callers to the
native record path, with generated-continuation tests, complete gameplay comparisons and stack-W audit.
[`NATIVE_DIRECTION_CONSUMERS.md`](NATIVE_DIRECTION_CONSUMERS.md) extends that scope to vehicle collision
points, tire-height corrections and light nodes, including the scalar clamps and normalization consumers.
[`NATIVE_PARTICLE_CONTINUATIONS.md`](NATIVE_PARTICLE_CONTINUATIONS.md) records the timing-sensitive
flare fallback found during that qualification and its native dispatch fix across scheduler resumes.
[`NATIVE_SCENE.md`](NATIVE_SCENE.md) covers the subsequent renderer hierarchy producer/consumer replacement:
native scene/frame/light records, zero VU0 program calls in both qualified routes, packet-buffer-only RAM
differences at the checked gameplay snapshot, and movie/loading/1P/4P validation. Other macro math and shader
+3
View File
@@ -76,3 +76,6 @@ restoration or broader memory-hash mask is introduced.
Full campaign, console visual parity, unaudited direction callers and complete VU removal remain
outside this bounded qualification. Further BSP inverse directions and other hot direction callers
still need their own consumer audit.
The subsequent [`NATIVE_DIRECTION_CONSUMERS.md`](NATIVE_DIRECTION_CONSUMERS.md) increment adds the
vehicle collision-point, tire-height and light-node direction callers with their generated consumers.
+80
View File
@@ -0,0 +1,80 @@
# Native vehicle and light directions
This increment extends the native `mathfMulTransVec` (`1da298`) path to four more audited return sites:
| Return | Caller | Immediate consumers |
| --- | --- | --- |
| `11708c` | `Vehicle::collisSetupHitPoints` | XYZ point addition, then original inverse/scalar point setup |
| `1880e0` | `Vehicle::suspCheckTireHeight` | Z displacement, scalar suspension clamps and tire-height write |
| `1d4284` | `hierLightNode` | XYZ view translation and scalar normalization |
| `1d42e8` | `hierLightNode` | Scalar XYZ dot product and light attenuation |
It reuses the native basis-times-XYZ calculation and destination-W contract documented in
[`NATIVE_DIRECTIONS.md`](NATIVE_DIRECTIONS.md). No VU registers, accumulator, flags or data memory are
read or maintained on these native leaf paths. Other return sites and the historical host retain the
original helper's complete ABI. BozoEngine remains at `4a8f70a`.
## Consumer audit
The collision-point loop writes the direction to the local vector at `sp+10`. `mathfAddVector` reads
only XYZ to produce the vehicle's world point. The loop then replaces the temporary XYZ before its
original inverse transform and final scalar addition. Direction W contributes to no numerical result
in these consumers; the original inverse still loads the complete vector into its compatibility state.
The method has no direct VU register/control/flag reads.
The tire-height loop transforms the local tire point into `sp+10` and reads only its Z at `sp+18`.
Generated scalar code computes and clamps the displacement before writing the tire height. Remaining
tire iterations reuse that vector, including null/flagged-tire branches. There are no calls after the
direction helper in that loop except later direction iterations, and no direct VU state reads.
The light-node position and direction vectors are at `sp+10` and `sp+30`. Their consumers are scalar
XYZ addition, normalization and dot product; light record indices/flags and attenuation are written
explicitly. Their W components are not copied into light parameters. The generated continuation
retains view lookup, normalization's small-vector branch, light-type branches, count/cursor updates
and the saved-register epilogue. `hierLightNode` has no direct VU state reads.
These are scoped helper replacements, not complete native collision, suspension or light builders.
The existing optional original check and caller-frequency trace remain available. No measured speedup
is claimed from counts alone.
## Validation
Local evidence is under `D:/BozoScratch/collision-directions`, against main `5820992` (PR #21).
No generated game code, disc data, captures or RAM dumps are committed.
- The existing math suite passes 1,048,576 helper numerical/ABI comparisons and 512 full flat-memory
comparisons. Its 262,144 direction cases now cover all eight audited return sites, with arbitrary
input bits, extreme exponents, four host FP modes, denormal controls, record overlap, RAM aliases,
low address bits and scratchpad. Native leaf VU state and complete host MXCSR remain untouched.
- Another 2,048 cases execute the actual generated vehicle/light continuations, including collision
point addition/inverse setup through the next loop boundary, remaining tire loops and clamps,
and both light continuations through their epilogue. They check the CPU state outside intentionally
retired VU effects, complete memory outside direction-output W, exact cycles/checkpoints and host
FP effects. Sixty-four cases compare the complete flat memory. Historical-host helper ABI checks
are exact at all four new sites. The previous 1,536 BSP continuation cases still pass.
- The scalar normalization can raise host exception flags. Each reference/native caller test starts
from the same complete MXCSR and compares the original continuation's complete outgoing effects;
only the native leaf promises to leave MXCSR unchanged.
- All ten native suites and 12 release-tool tests pass. Player, headless and checker builds pass.
- Default 1P completes 9,500 frames with 855,975 native directions, up from 533,524. The actual 4P
route completes 8,500 frames with 207,441, up from 8,363. This retires another 322,451 / 199,078
generated direction-helper executions in these routes. All four new sites run in both routes.
- Every baseline frame-record field matches in both default routes, including RAM, scratchpad,
draw/sound hashes and counts, library calls/counts, EE clocks and thread state. Default runs make
no original comparisons and no VU0 microprogram calls.
- Strict runs enable native math, hierarchy and projection original checks. All 855,975 / 207,441
direction XYZ comparisons pass; both complete recordings reproduce their default files byte-for-byte.
- Complete 32 MB snapshots at 1P frame 7000 and 4P frame 6000 match the baseline byte-for-byte.
No additional memory-hash mask, padding restoration or shadow VU state is introduced.
Live 4P qualification also exposed a timing-sensitive native-flare continuation issue. The subsequent
fix and its additional native-particle regression target are documented in
[`NATIVE_PARTICLE_CONTINUATIONS.md`](NATIVE_PARTICLE_CONTINUATIONS.md). Final results below use both changes.
Windowed final runs complete 4,201 movie/menu frames and 6,501 frames each for 1P and 4P. Direct final
captures show the decoded opening movie, loading screen, active rainy combat with targeting/HUD and
vehicle effects, and all four snow-arena views with driving/firing. The 4P run advances through the
previous stall point. Device logs report 17.8 / 46.2 / 30.9 ms of silence (movie / 1P / 4P) and some
dropped frames; deterministic sound remains exact. Flawless device audio or subjective listening
acceptance is not claimed. Full campaign, console visual parity and complete VU removal remain
outside the bounded qualification.
+48
View File
@@ -0,0 +1,48 @@
# Native particles across scheduler continuations
During qualification of the vehicle/light direction changes, the 4P window stopped advancing at
frame 4915. Its UI remained responsive because the game thread had raised an uncaught C++ exception
and was waiting for the crash dialog. The crash stack reached the guarded `sceGsExecStoreImage`
from a lens-flare helper dispatched directly by the scheduler. A fresh unchanged-main 4P window
completed 6,501 frames, so the live trigger is timing-sensitive.
The original particle wrapper set `g_flaresNative` around a C++ call into generated `particleDraw`.
A checkpoint can unwind that call before the lens helper runs. When the scheduler later enters the
helper directly, the scope flag has already been cleared; the old branch executes the generated
flare code and reaches the retired SDK readback. A flag tied to that C++ stack is not a durable
native-backend selection. Host-time freshness was also unsuitable for selecting native effects
and deciding whether native depth sampling was available after a long frame.
## Change
The normal native backend now selects the existing native flare test/render routines from its
backend and explicit particle options, independently of that transient call scope. Native particle
draw selection also survives a host-time gap. Native depth availability follows the enabled native
renderer and explicit depth option; it no longer expires when the last match frame is over 100 ms
old. Actual samples still come from the previous native renderer frame via `depthAt`; missing
coverage retains the existing far-depth behavior.
No SDK image descriptor is decoded, no fake image or completion interrupt is added, and the SDK
guard remains in place. Explicit legacy particle diagnostics retain their existing compatibility
selection. BozoEngine stays at `4a8f70a`; this change is owned by TMB.
## Regression evidence and validation
Local artifacts are under `D:/BozoScratch/collision-directions`. The initial failed window log,
scratch-user crash report, successful unchanged-main comparison, and `stall-runtime-evidence.json`
are retained there. REA observation `ev_fe6c8e868562f51268869b7c3a7baf210ff7b424a388ecfcdc58767f026c3e91`
records the waiting exception/dialog threads; `ev_9dffc412844e6e3efdc03fab1756e20be96683f4c5ad5e8242e036a0a737375b`
records the selected process image/base and thread context. Their provider reports no artifact
digest or OS/architecture identity, so executable attribution additionally uses the exact owned
process path, crash report module offsets and the built executable's local symbol table. Both
observations were ephemeral and detached; no live analysis session is retained.
`tmb-native-particle-tests` enters both native flare leaves without a live `particleDraw` scope or
any recent frame marker. The old code fails by entering generated/runtime-service code. The fixed
code passes eight test/render pairs across all four views, including visible and culled points,
projection records, missing-depth behavior, visibility, complete native CPU ABI (including VU and
clocks) and untouched legacy packet output. The leaf test does not claim GPU occlusion parity.
Final gameplay/movie/loading reruns and audio limits are recorded in
[`NATIVE_DIRECTION_CONSUMERS.md`](NATIVE_DIRECTION_CONSUMERS.md). This is bounded regression coverage;
full campaign, console visual parity and explicit legacy diagnostic modes are not qualified by it.
+3 -2
View File
@@ -167,7 +167,8 @@ namespace tmb::native
renderer.setPresentsAlone(true); // the native frame is the whole picture
}
// Lens-flare occlusion samples the previous native frame in a match. Disabling this selects the legacy
// Lens-flare occlusion samples the previous native frame. Availability does not expire on a host hitch.
// Disabling this selects the legacy
// particle diagnostic, whose unowned SDK readback is explicitly unsupported by the native engine.
bool flareDepthNative()
{
@@ -176,7 +177,7 @@ namespace tmb::native
const char *value = std::getenv("TMB_NATIVE_FLARE_DEPTH");
return !(value && *value == '0');
}();
return s_on && enabled() && inMatch();
return s_on && enabled();
}
// Native lens flares sample a 4 x 4 block at game screen coordinates from the last presented frame.
+3 -2
View File
@@ -9,8 +9,9 @@
namespace tmb::math
{
// Audited XYZ-only consumers: skid direction and hdBspNode's collision point/segment setup.
inline constexpr std::array<uint32_t, 4> directionReturns{0x168b30, 0x1cd618, 0x1cda54, 0x1cdabc};
// Audited XYZ-only consumers: skid, BSP collision setup, vehicle points/heights and light nodes.
inline constexpr std::array<uint32_t, 8> directionReturns{
0x168b30, 0x1cd618, 0x1cda54, 0x1cdabc, 0x11708c, 0x1880e0, 0x1d4284, 0x1d42e8};
struct alignas(16) Vector { std::array<uint32_t, 4> bits{}; };
struct Matrix { std::array<Vector, 4> column{}; };
+12 -3
View File
@@ -2314,6 +2314,14 @@ namespace tmb::particles
static_cast<unsigned long long>(st.unfinished));
}
bool nativeFlareContinuation(PS2Runtime *runtime)
{
// A checkpoint may unwind particleDraw's native scope before the flare leaf is dispatched.
// The native backend and explicit options remain valid across that scheduler continuation.
return bozo::port::nativeGraphics(runtime) && settings().on && settings().flares && !settings().check &&
!(settings().toggleFlares && toggledOff()) && tmb::native::flareDepthNative();
}
void lensTestOverride(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
if (g_flaresCheck)
@@ -2332,7 +2340,7 @@ namespace tmb::particles
compareFlares(0, mine, saveFlares(rdram, gp, view), mineResult, static_cast<int32_t>(getRegU32(ctx, 2)));
return;
}
if (!g_flaresNative)
if (!g_flaresNative && !nativeFlareContinuation(runtime))
{
ctx->pc = kLensTest;
gameLensTest(rdram, ctx, runtime);
@@ -2373,7 +2381,7 @@ namespace tmb::particles
}
return;
}
if (!g_flaresNative)
if (!g_flaresNative && !nativeFlareContinuation(runtime))
{
ctx->pc = kLensRender;
gameLensRender(rdram, ctx, runtime);
@@ -2406,7 +2414,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 || !tmb::native::effectsInStream() || u32(rdram, gp + static_cast<uint32_t>(kGpColours)) == 0u || toggledAll)
if (!settings().on || (!bozo::port::nativeGraphics(runtime) && !tmb::native::effectsInStream()) ||
u32(rdram, gp + static_cast<uint32_t>(kGpColours)) == 0u || toggledAll)
{
g_flaresNative = false;
ctx->pc = kParticleDraw;
+126 -3
View File
@@ -25,13 +25,14 @@ namespace
struct Services : bozo::RuntimeServices
{
unsigned yields = 0;
// Keep checkpoints enabled and stop just before the next unrelated result-buffer operation.
uint32_t stop = 0x1eeafc;
// Keep checkpoints enabled; stop at the chosen boundary or let a complete continuation return.
void yield(uint8_t *, R5900Context *ctx, Runtime *) override
{
require(++yields < 64, "caller did not reach segment end");
if (ctx->pc == 0x1eeafc) throw SegmentEnd{};
if (ctx->pc == stop) throw SegmentEnd{};
}
[[noreturn]] static void unexpected() { throw std::runtime_error("unexpected BSP caller service"); }
[[noreturn]] static void unexpected() { throw std::runtime_error("unexpected direction caller service"); }
void unknownTarget(uint8_t *, R5900Context *, Runtime *, uint32_t) override { unexpected(); }
void syscall(uint8_t *, R5900Context *, Runtime *, uint32_t) override { unexpected(); }
void breakpoint(uint8_t *, R5900Context *, Runtime *, uint32_t) override { unexpected(); }
@@ -152,4 +153,126 @@ void testDirectionCallers()
}
_mm_setcsr(saved);
std::printf("BSP direction callers: %u generated continuation cases, %u whole-memory checks; XYZ consumers, CPU/clock/checkpoints and FP control exact; historical helper ABI exact\n", cases, memoryCases);
// Vehicle point setup through its next loop boundary, complete remaining tire-height loops,
// and light-node continuations through their epilogue (including normalization and attenuation).
unsigned addedCases = 0, addedMemory = 0;
constexpr uint32_t callers[] = {0x11708c, 0x1880e0, 0x1d4284, 0x1d42e8};
for (unsigned mode = 0; mode < 4; ++mode) for (unsigned kind = 0; kind < 4; ++kind)
for (unsigned n = 0; n < 128; ++n)
{
for (unsigned i = 0; i < arenaBytes; i += 4)
{
const float f = float(int(bits() % 4097) - 2048) / 128.f;
std::memcpy(ram + 0x10000 + i, &f, 4);
}
const auto word = [&](uint32_t at, uint32_t value) { std::memcpy(ram + at, &value, 4); };
const auto wide = [&](uint32_t at, uint64_t value) { std::memcpy(ram + at, &value, 8); };
const uint32_t alias = n % 3 == 0 ? 0x80000000 : n % 3 == 1 ? 0x20000000 : 0;
const auto address = [&](uint32_t v) { return v | alias; };
constexpr uint32_t vehicle = 0x10000, node = 0x13000, gp = 0x40000, sp = 0x30000;
R5900Context initial;
for (unsigned i = 1; i < 32; ++i) for (auto &v : initial.r[i].uw) v = bits();
for (auto &v : initial.vu0_vf) for (auto &vbits : v.u) vbits = bits();
initial.vu0_vf[0] = {}; initial.vu0_vf[0].u[3] = 0x3f800000;
initial.vu0_status = bits(); initial.vu0_mac = bits(); initial.vi[5] = bits();
for (auto &v : initial.vu0_acc.u) v = bits();
setRegU32(&initial, 28, address(gp)); setRegU32(&initial, 29, address(sp));
const uint32_t caller = callers[kind];
setRegU32(&initial, 31, caller); initial.pc = 0x1da298; initial.cycleLimit = 0;
uint32_t output = sp + 0x10;
RecompiledFunction continuation;
if (kind == 0)
{
continuation = resume_0x115f30; services.stop = 0x116e78;
setRegU32(&initial, 16, address(vehicle)); setRegU32(&initial, 17, address(vehicle + 0x1a90));
setRegU32(&initial, 18, n % 3); setRegU32(&initial, 19, address(vehicle + 0x720));
setRegU32(&initial, 20, address(vehicle + 0x1ab0)); setRegU32(&initial, 21, address(vehicle + 0x7f0));
setRegU32(&initial, 22, address(vehicle + 0x1ac0)); setRegU32(&initial, 23, address(output));
setRegU32(&initial, 30, address(sp + 0x20));
word(sp + 0x34, address(vehicle + 0x1d0)); word(sp + 0x3c, address(output));
word(sp + 0x40, address(vehicle + 0xd0)); word(vehicle + 0x1b48, n & 1);
word(vehicle + 0x2018, address(0x17000));
setRegU32(&initial, 4, address(vehicle + 0xd0)); setRegU32(&initial, 5, address(vehicle + 0x1ab0));
}
else if (kind == 1)
{
continuation = resume_0x187db8; services.stop = 0xffffffff;
setRegU32(&initial, 16, address(vehicle + 0x1ab0)); setRegU32(&initial, 17, address(vehicle));
setRegU32(&initial, 18, address(vehicle + 0x1a90)); setRegU32(&initial, 19, n % 4);
setRegU32(&initial, 20, address(vehicle + 0x4e0)); setRegU32(&initial, 21, address(output));
initial.fu[21] = 0x3f000000; // positive and negative suspension clamp limits
word(vehicle + 0x378, 0x40000000); word(vehicle + 0x1790, n % 3);
for (unsigned j = 0; j < 4; ++j)
{
word(vehicle + 0x1a90 + j * 0xf0, address(0x18000 + j * 0x100));
word(vehicle + 0x1b48 + j * 0xf0, n % 5 == j ? 1 : 0);
}
wide(sp + 0x80, 0xbad0000);
setRegU32(&initial, 4, address(vehicle + 0x4e0)); setRegU32(&initial, 5, address(vehicle + 0x1ab0));
}
else
{
continuation = resume_0x1d4210; services.stop = 0xffffffff;
const uint64_t flags = n % 3 == 0 ? (1ull << 39) : n % 3 == 1 ? 0 : (1ull << 35);
wide(node, flags); wide(sp + 0x80, 0xbad0000);
word(gp - 0x358c, address(0x16000)); word(gp - 0x3588, n % 73);
word(gp - 0x4824, 0x358637bd); // normalization threshold
for (unsigned view = 0; view < 4; ++view) word(0x4dfcd0 + view * 16, address(0x15000 + view * 0x100));
setRegU32(&initial, 17, address(node)); setRegU32(&initial, 19, address(vehicle));
if (kind == 2)
{
setRegU32(&initial, 16, address(sp + 0x10)); setRegU32(&initial, 18, n % 4);
setRegU32(&initial, 5, address(sp));
// Exercise normalization's zero/short-vector branch as well as ordinary finite vectors.
if (n % 8 == 0) std::memset(ram + sp, 0, 12);
}
else
{
output = sp + 0x30;
setRegU32(&initial, 16, address(output)); setRegU32(&initial, 18, address(sp + 0x20));
setRegU32(&initial, 5, address(node + 0x20));
}
setRegU32(&initial, 4, address(vehicle));
}
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 auto run = [&](RecompiledFunction direction, R5900Context &ctx)
{
services.yields = 0; rt->functions.setOverride(0x1da298, direction);
direction(ram, &ctx, rt.get()); require(ctx.pc == caller, "new direction return");
try { continuation(ram, &ctx, rt.get()); }
catch (const SegmentEnd &) { require(kind == 0, "unexpected segment stop"); return; }
require(kind != 0 && ctx.pc == 0xbad0000, "new direction continuation did not finish");
};
_mm_setcsr(control); auto a = initial, b = initial; run(originalDirection, a);
const unsigned referenceYields = services.yields;
const auto preserveW = [&](uint32_t at) { std::memcpy(ram + at + 12, input.get() + at - 0x10000 + 12, 4); };
preserveW(output); if (kind == 2) preserveW(sp + 0x30);
std::memcpy(expected.get(), ram + 0x10000, arenaBytes);
if (n < 4) { std::memcpy(whole.get(), ram, bozo::kFlatBytes); ++addedMemory; }
const unsigned referenceControl = _mm_getcsr();
std::memcpy(ram + 0x10000, input.get(), arenaBytes);
_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) || 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,
referenceYields, services.yields);
throw std::runtime_error("vehicle/light direction consumer differs");
}
host.native = false; a = initial; b = initial; originalDirection(ram, &a, rt.get());
uint8_t originalOut[16]; std::memcpy(originalOut, ram + output, 16);
nativeDirection(ram, &b, rt.get()); host.native = true;
require(!std::memcmp(&a, &b, sizeof(a)) && !std::memcmp(originalOut, ram + output, 16), "new historical direction ABI");
++addedCases;
}
_mm_setcsr(saved);
std::printf("Vehicle/light directions: %u generated continuation cases, %u whole-memory checks; collision point/inverse consumers, tire loops/clamps and light normalization/attenuation CPU/memory/clock/FP exact outside direction W; historical ABI exact\n", addedCases, addedMemory);
}
+110
View File
@@ -0,0 +1,110 @@
// SPDX-License-Identifier: MIT
// A scheduler may enter a flare leaf after particleDraw's native C++ scope has unwound.
#include "tmb_port.h"
#include "tmb_host.h"
#include "bozo/libs/libraries.h"
#include <cstdio>
#include <cstring>
#include <memory>
#include <stdexcept>
namespace tmb::particles { void install(tmb::Registry &); }
namespace
{
void require(bool okay, const char *message) { if (!okay) throw std::runtime_error(message); }
struct Host : bozo::port::Host
{
bozo::libs::Libraries libs;
bozo::libs::Libraries &libraries() override { return libs; }
bool nativeGraphics() const override { return true; }
void frameEnd(Runtime *, R5900Context *) override { throw std::runtime_error("unexpected frame"); }
bool callLibrary(Runtime *, R5900Context *, uint32_t) override { throw std::runtime_error("unexpected library"); }
};
struct Services : bozo::RuntimeServices
{
[[noreturn]] static void unexpected() { throw std::runtime_error("native flare entered generated code or a runtime service"); }
void unknownTarget(uint8_t *, R5900Context *, Runtime *, uint32_t) override { unexpected(); }
void yield(uint8_t *, R5900Context *, Runtime *) override { unexpected(); }
void syscall(uint8_t *, R5900Context *, Runtime *, uint32_t) override { unexpected(); }
void breakpoint(uint8_t *, R5900Context *, Runtime *, uint32_t) override { unexpected(); }
void trap(uint8_t *, R5900Context *, Runtime *) override { unexpected(); }
void unimplemented(uint8_t *, R5900Context *, Runtime *, uint32_t) override { unexpected(); }
void eret(uint8_t *, R5900Context *, Runtime *) override { unexpected(); }
uint32_t cop0Read(R5900Context *, Runtime *, uint32_t) override { unexpected(); }
void cop0Write(R5900Context *, Runtime *, uint32_t, uint32_t) override { unexpected(); }
bool cop0Condition(R5900Context *, Runtime *) override { unexpected(); }
void vu0CallMicroprogram(uint8_t *, R5900Context *, Runtime *, uint32_t) override { unexpected(); }
uint32_t vu0ControlRead(R5900Context *, Runtime *, uint32_t) override { unexpected(); }
void vu0ControlWrite(R5900Context *, Runtime *, uint32_t, uint32_t) override { unexpected(); }
void ioRead(R5900Context *, Runtime *, uint32_t, uint32_t, uint64_t[2]) override { unexpected(); }
void ioWrite(R5900Context *, Runtime *, uint32_t, uint32_t, const uint64_t[2]) override { unexpected(); }
};
}
int main()
{
tmb::host::setEnvDefault("TMB_NATIVE", "1");
auto rt = std::make_unique<Runtime>(); Host host; Services services;
rt->port = &host; rt->services = &services;
tmb::Registry registry; tmb::particles::install(registry);
const auto test = registry.find(0x1dfe00), render = registry.find(0x1e01c8);
require(test && render, "flare overrides missing");
auto *ram = rt->memory.flat();
const auto word = [&](uint32_t at, uint32_t v) { std::memcpy(ram + at, &v, 4); };
const auto half = [&](uint32_t at, uint16_t v) { std::memcpy(ram + at, &v, 2); };
const auto value = [&](uint32_t at, float v) { std::memcpy(ram + at, &v, 4); };
const auto read = [&](uint32_t at) { uint32_t v; std::memcpy(&v, ram + at, 4); return v; };
unsigned cases = 0;
// No particleDraw call, recent frame marker, or live C++ native-flare scope exists in this process.
// The native backend must answer these valid leaf entries directly, just as after a scheduler resume.
for (unsigned view = 0; view < 4; ++view) for (unsigned visible = 0; visible < 2; ++visible)
{
constexpr uint32_t gp = 0x40000, list = 0x20000, viewport = 0x21000, chain = 0x22000;
std::memset(ram + list, 0, 0x1000); std::memset(ram + viewport, 0, 0x100);
std::memset(ram + chain, 0x5a, 256);
word(gp - 0x2f28 + (view & 1) * 4, 1); word(gp - 0x2f20 + (view & 1) * 4, list);
word(0x4dfcd0 + view * 16 + 4, viewport);
half(viewport + 4, 640); half(viewport + 6, 224);
word(viewport + 0x18, 2048); word(viewport + 0x1c, 2048);
std::memset(ram + 0x4a1240 + view * 0xf0, 0, 16);
const uint32_t matrix = 0x4e0230 + view * 64;
std::memset(ram + matrix, 0, 64);
for (unsigned row = 0; row < 4; ++row) value(matrix + row * 20, 1.f);
value(matrix + 12, 2048.f); value(matrix + 28, 2048.f); value(matrix + 44, 10.f);
value(list, visible ? 0.f : 10000.f); value(list + 8, 5.f);
word(list + 0x10, 0x80); value(list + 0x2c, 1.f);
std::memset(ram + gp - 0x34c0, 0, 8);
std::memset(ram + 0x7435c0, 0xa5, 64);
R5900Context ctx;
for (unsigned reg = 1; reg < 32; ++reg) for (auto &lane : ctx.r[reg].uw) lane = 0xa5c31987u ^ reg;
for (unsigned reg = 1; reg < 32; ++reg) for (auto &lane : ctx.vu0_vf[reg].u) lane = 0x7f812345u ^ reg;
ctx.vu0_acc.u[0] = 0xdeadbeef; ctx.vi[5] = 0x1234; ctx.vu0_status = 0xabcdef;
ctx.vu0_mac = 0xdead; ctx.vu0_clip_flags = 0xbeef; ctx.cycles = 123; ctx.checkpoints = 9;
setRegU32(&ctx, 4, view); setRegU32(&ctx, 28, gp); setRegU32(&ctx, 29, 0x30000);
setRegU32(&ctx, 31, 0xbad0000); ctx.pc = 0x1dfe00;
const auto before = ctx;
try { test(ram, &ctx, rt.get()); }
catch (const std::exception &e) { std::fprintf(stderr, "FAIL native resumed flare test: %s\n", e.what()); return 1; }
require(ctx.pc == 0xbad0000 && getRegU32(&ctx, 2) == visible, "resumed flare test result");
auto expected = before; setRegU32(&expected, 2, visible); expected.r[2].ud[1] = 0; expected.pc = 0xbad0000;
require(!std::memcmp(&expected, &ctx, sizeof(ctx)), "native flare test CPU ABI");
require(read(gp - 0x2f28 + (view & 1) * 4) == visible, "flare compaction count");
require(!std::memcmp(before.vu0_vf, ctx.vu0_vf, sizeof(ctx.vu0_vf)) && ctx.cycles == before.cycles &&
ctx.checkpoints == before.checkpoints, "native flare changed VU or clocks");
if (visible)
{
require(read(list) == 0x45000000 && read(list + 4) == 0x45000000 && read(list + 8) == 0x41700000 &&
read(list + 0x14) == 0x42c80000, "native flare projection record");
for (unsigned i = 0; i < 16; ++i) require(read(0x7435c0 + i * 4) == 0, "missing native depth must stay far");
}
setRegU32(&ctx, 4, chain); setRegU32(&ctx, 5, view); ctx.pc = 0x1e01c8;
expected = ctx; setRegU32(&expected, 2, chain); expected.r[2].ud[1] = 0; expected.pc = 0xbad0000;
try { render(ram, &ctx, rt.get()); }
catch (const std::exception &e) { std::fprintf(stderr, "FAIL native resumed flare render: %s\n", e.what()); return 2; }
require(ctx.pc == 0xbad0000 && getRegU32(&ctx, 2) == chain, "resumed flare render result");
require(!std::memcmp(&expected, &ctx, sizeof(ctx)), "native flare render CPU ABI");
if (visible) require(read(list + 0x2c) == 0x3f800000, "native flare visibility");
for (unsigned i = 0; i < 256; ++i) require(ram[chain + i] == 0x5a, "flare wrote a legacy output packet");
++cases;
}
std::printf("native particles: %u flare test/render continuations without a live particleDraw scope or frame marker; four views, culling/projection/depth/visibility, VU/clocks and untouched packet output pass\n", cases);
}