diff --git a/docs/xdxr.md b/docs/xdxr.md index 1a2d104a47..1b8a4cc274 100644 --- a/docs/xdxr.md +++ b/docs/xdxr.md @@ -112,6 +112,40 @@ type is one of two checks, and neither reads past the `InfoType` field: None of the 15 other DLLs in the package names the type or an offline builder. +## 4a. The runtime serves the DLL itself + +`runtime/shims/xbox_bvh_builder.cpp` serves the seven exports the executable imports with the layer's own XDXR +builder (`runtime/src/xdxr_build.*`), so the bundled DLL is not loaded and its 52 console programs are never created. +Their pipeline compile (31.2 s for one of them on an RTX 4080, 59.5 s for all 52 on an RX 9070 XT, #7231/#7049) runs +on the title's thread, longer than its ~30 s startup watchdog, so a cold first boot ends at the builder (boot stop 18). +`LEONIDA_BVH_BUILDER=console` turns the shim off. + +The executable's imports and call sites, measured statically on 1.0.2.1. The counts are `call [rip+disp32]` +through the import table. For `Batched2X`, IDA finds 8 direct calls: 4 in each of two sibling functions with no +static reference, reached through a table (#7516), so 2 of them are calls of another form. + +| Export | Call sites | The shim | +|---|---:|---| +| `XboxBvhBuilder(ID3D12Device11*, bool)` | 1 | keeps the device in a table keyed by `this`; writes nothing into the title's object | +| `~XboxBvhBuilder()` | 1 | releases that entry | +| `Set64BitMortonCodes(bool)` | 8 | recorded; the layer's builder has no such option | +| `GetRaytracingAccelerationStructurePrebuildInfo(INPUTS*, XDXR_STREAM_DESC*, PREBUILD_INFO*)` | 3 | the layer's sizes | +| `BuildRaytracingAccelerationStructureBatched2X(GCL6*, UINT, BATCHED_DESC2*)` | 6 (8) | one layer build per element (§1), with its postbuild descriptions | +| `CopyRaytracingAccelerationStructure(GCL4*, dest, source, mode)` | 2 | the layer's copy | +| `RehydrateRaytracingAccelerationStructureBatched2X(GCL8*, UINT, BUILD_DESC*, UINT64*)` | 4 | `E_NOTIMPL` for now | + +**Where it differs from the DLL:** +- **Stream records (§3):** they tune the console builder's heuristics, so they are ignored (logged once). The result + is still a valid BVH of the same geometry, in the node format the traversal shaders read. +- **Validation errors:** the DLL throws them as C++ exceptions. A shim must not throw into the title, so an element + the DLL would refuse is skipped with a log line. The offline-statistics postbuild type (`0x10`, §4) is one of + those. +- **Rehydration** is the next step: rebuild each structure on the GPU from the source geometry its description + carries ([bvh.md](bvh.md) §4a), in the leaf frame `compressionParams` gives. + +`xbox_bvh_builder_test` calls every export through the shim registry, the way the title's imports bind, and +`xdxr_bvh.py check-build` checks the BLAS, TLAS and compacted BLAS it builds (ctest `xbox_bvh_builder_check`). + ## 5. What is still open - The names of the stream record types and of their values. diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 2ab8c7bc84..642e9465a4 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -115,6 +115,7 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) shims/xgameruntime_gamesave.cpp shims/xgameruntime_store.cpp shims/xgameruntime_offline.cpp + shims/xbox_bvh_builder.cpp shims/library_loader.cpp shims/process.cpp ) @@ -1545,6 +1546,24 @@ if(TARGET Vulkan::Headers) set_tests_properties(d3d12_xdxr_rt_check PROPERTIES FIXTURES_REQUIRED d3d12_xdxr_cases SKIP_RETURN_CODE 77) endif() + # XboxBvhBuilder.dll served by the layer's builder (RT-5, boot stop 18): the seven exports the executable imports, + # through the shim registry as the title binds them; the structures are checked like d3d12_xdxr_rt's. + set(LEONIDA_XBOX_BVH_BUILDER_OUT "${CMAKE_CURRENT_BINARY_DIR}/xbox_bvh_builder_cases") + add_executable(xbox_bvh_builder_test test/xbox_bvh_builder_test.cpp shims/xbox_bvh_builder.cpp shims/registry.cpp) + target_link_libraries(xbox_bvh_builder_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(xbox_bvh_builder_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(xbox_bvh_builder_test PRIVATE /W4 /permissive- /utf-8) + target_link_options(xbox_bvh_builder_test PRIVATE /OPT:NOREF) + add_test(NAME xbox_bvh_builder COMMAND xbox_bvh_builder_test "${LEONIDA_XBOX_BVH_BUILDER_OUT}") + set_tests_properties(xbox_bvh_builder PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60 FIXTURES_SETUP xbox_bvh_builder_cases) + add_test(NAME xbox_bvh_builder_console COMMAND xbox_bvh_builder_test --console) + set_tests_properties(xbox_bvh_builder_console PROPERTIES ENVIRONMENT "LEONIDA_BVH_BUILDER=console") + if(Python3_FOUND) + add_test(NAME xbox_bvh_builder_check COMMAND "${Python3_EXECUTABLE}" -I + "${CMAKE_CURRENT_SOURCE_DIR}/../tools/xdxr_bvh.py" check-build "${LEONIDA_XBOX_BVH_BUILDER_OUT}" --rays 1000) + set_tests_properties(xbox_bvh_builder_check PROPERTIES FIXTURES_REQUIRED xbox_bvh_builder_cases SKIP_RETURN_CODE 77) + endif() + # GCL8's QueryInterface and its one method need an allocator and a list, not a Vulkan device. add_executable(d3d12_gcl8_test test/d3d12_gcl8_test.cpp) target_link_libraries(d3d12_gcl8_test PRIVATE gta6rt_d3d12_com) diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index e17a80353b..1357afe43f 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -1627,6 +1627,8 @@ unsigned detect_slot_count(ID3D12Device* real) { } // namespace +IUnknown* real_object_behind_proxy(const void* object) { return proxy_real_object(object); } + HRESULT create_device_proxy(ID3D12Device* real, REFIID riid, void** out) { if (!real) return E_POINTER; if (!out) return E_POINTER; diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index 0019ec5069..655ede97ec 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -89,6 +89,11 @@ unsigned device_proxy_slot_count(const void* device); // The PC device behind a proxy. Null when `device` is not a proxy. ID3D12Device* device_proxy_real_device(const void* device); +// The real object behind any of the child proxies (heap, queue, fence, allocator, and a kind added later, such as a +// console command-list proxy, which joins proxy_real_object), or null when `object` is none of them. For code outside +// this file that is handed a title's object, like the XboxBvhBuilder shim's command lists. +IUnknown* real_object_behind_proxy(const void* object); + // True for slots the proxy handles itself rather than forwarding verbatim: IUnknown (0-2), 8 and 75 (queue // proxies), 9 (allocator proxies), 14, 31/34/35/45/46/50 (proxies unwrapped), 32 and 36 (fence proxies), 48/73 and // 78/79/80 (the Xbox slots above, at their configured indices), 62, 67 and 76. Slot 10 is intentionally false: the diff --git a/runtime/shims/xbox_bvh_builder.cpp b/runtime/shims/xbox_bvh_builder.cpp new file mode 100644 index 0000000000..8c80419e2e --- /dev/null +++ b/runtime/shims/xbox_bvh_builder.cpp @@ -0,0 +1,285 @@ +// XboxBvhBuilder.dll served by the layer's own acceleration-structure builder (RT-5, boot stop 18). +// +// The package's XboxBvhBuilder.dll builds the game's ray-tracing structures with 52 console compute programs that +// its constructor creates as pipelines on the title's thread. Translated, they take 25-60 s to compile on a cold +// driver cache (31.2 s for one of them on an RTX 4080, 59.5 s for all 52 on an RX 9070 XT, measured in #7231 and +// #7049), longer than the title's startup watchdog (about 30 s), so a first boot ends at the builder. The layer +// already builds XDXR BVH4 structures itself (BuildRaytracingAccelerationStructure on the Vulkan device, D3D-178, +// src/xdxr_build.*), in the node format the game's translated traversal shaders read, and its one pipeline compiles +// in well under a second. So this file serves the DLL's exports with the layer's builder and the DLL is never +// loaded: the loader binds an import to a shim before a bundled module (pe_loader.cpp, Loader::resolve). +// +// The exports, as the executable imports them (7 of the DLL's 12, measured statically on 1.0.2.1: names and call +// counts only). Member functions: `this` comes first (rcx), then the arguments, as for a free function on x64. +// ??0 XboxBvhBuilder(ID3D12Device11*, bool) 1 call site +// ??1 ~XboxBvhBuilder() 1 +// Set64BitMortonCodes(bool) 8 +// GetRaytracingAccelerationStructurePrebuildInfo(const INPUTS*, const XDXR_STREAM_DESC*, PREBUILD_INFO*) 3 +// BuildRaytracingAccelerationStructureBatched2X(GCL6*, UINT, const BATCHED_DESC2*) 6 +// CopyRaytracingAccelerationStructure(GCL4*, UINT64 dest, UINT64 source, COPY_MODE) 2 +// RehydrateRaytracingAccelerationStructureBatched2X(GCL8*, UINT, const BUILD_DESC*, const UINT64*) -> HRESULT 4 +// The Xbox descriptions are the measured layouts of src/xdxr_descs.h (docs/xdxr.md). +// +// What differs from the console builder, on purpose: +// - No programs are created: the constructor only remembers the device. +// - The XDXR stream records (docs/xdxr.md §3) tune the console builder's own heuristics. The layer's builder has +// none of those settings, so a non-empty stream is logged once and otherwise ignored; the structure is still a +// valid BVH of the same geometry. Set64BitMortonCodes is recorded and ignored for the same reason. +// - The DLL throws its validation errors as C++ exceptions (docs/xdxr.md, "Errors are thrown, not returned"). A +// shim must not throw into the title, so an element the DLL would reject is logged and skipped instead. The one +// rule a correct title meets every time is kept: the offline-statistics postbuild type (0x10) is never written. +// - Rehydration is not implemented yet: RehydrateRaytracingAccelerationStructureBatched2X logs once and returns +// E_NOTIMPL. (Planned: rebuild each structure from the source geometry its description carries.) +// +// The builder object belongs to the title, which allocates it with a size this file doesn't know, so nothing is +// written into it: what the shim keeps (the device, the Morton option) lives in a table keyed by its address. +// +// LEONIDA_BVH_BUILDER=console turns the shim off, so the imports bind to the bundled DLL as before (for work on the +// console programs themselves, #5680 and #7318). The variable is read once, when the shim registers. +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "d3d12_xs_device.h" +#include "shims.h" +#include "../src/xdxr_descs.h" + +namespace { + +namespace xdxr = leonida::xdxr; + +struct BuilderState { + ID3D12Device5* device = nullptr; // a reference held for the builder's lifetime; null if it has no DXR methods + bool morton64 = false; +}; + +std::mutex g_mutex; +std::unordered_map g_builders; + +void log_once(std::atomic& flag, const char* text) { + if (!flag.exchange(true)) std::fprintf(stderr, "[rt] XboxBvhBuilder shim: %s\n", text); +} + +// The PC device behind what the title passed: the real device behind a d3d12_xs device proxy, or the pointer +// itself when it is already a device (a test, or a backend that hands out unwrapped devices). +ID3D12Device5* device5_of(void* device) { + if (!device) return nullptr; + IUnknown* base = rt::d3d12_xs::device_proxy_real_device(device); + if (!base) base = static_cast(device); + ID3D12Device5* out = nullptr; + if (FAILED(base->QueryInterface(IID_PPV_ARGS(&out)))) return nullptr; + return out; +} + +// The command list a title passes, as the backend's own list: a d3d12_xs proxy is unwrapped first, so the PC +// interfaces below are asked of the real list and never of a console-shaped proxy (whose vtable is not the PC one; +// docs/d3d12_command_objects.md §3.5a). Lists aren't wrapped on main yet; a console list proxy joins +// proxy_real_object, which real_object_behind_proxy follows. +IUnknown* real_list(void* list) { + if (!list) return nullptr; + IUnknown* real = rt::d3d12_xs::real_object_behind_proxy(list); + return real ? real : static_cast(list); +} + +ID3D12GraphicsCommandList4* list4_of(void* list) { + IUnknown* real = real_list(list); + if (!real) return nullptr; + ID3D12GraphicsCommandList4* out = nullptr; + if (FAILED(real->QueryInterface(IID_PPV_ARGS(&out)))) return nullptr; + return out; +} + +// ??0XboxBvhBuilder@@QEAA@PEAUID3D12Device11@@_N@Z: XboxBvhBuilder(ID3D12Device11* device, bool). +// Returns `this`, as an MSVC constructor does. The bool's meaning is not measured; it is not needed here. +void* builder_construct(void* self, void* device, bool) { + ID3D12Device5* device5 = device5_of(device); + if (!device5) { + static std::atomic s_logged{false}; + log_once(s_logged, "the device has no ID3D12Device5 (DXR) interface; builds will be skipped"); + } + std::lock_guard lock(g_mutex); + BuilderState& state = g_builders[self]; + if (state.device) state.device->Release(); // the same storage constructed twice without a destructor + state = BuilderState{device5, false}; + return self; +} + +// ??1XboxBvhBuilder@@QEAA@XZ: ~XboxBvhBuilder(). +void builder_destruct(void* self) { + std::lock_guard lock(g_mutex); + auto it = g_builders.find(self); + if (it == g_builders.end()) return; + if (it->second.device) it->second.device->Release(); + g_builders.erase(it); +} + +// ?Set64BitMortonCodes@XboxBvhBuilder@@QEAAX_N@Z: a console-builder option (64-bit Morton keys for its sort). +void builder_set_64bit_morton_codes(void* self, bool enable) { + std::lock_guard lock(g_mutex); + auto it = g_builders.find(self); + if (it != g_builders.end()) it->second.morton64 = enable; +} + +// The builder's device with a reference of the caller's own, taken under the lock, so a destructor on another +// thread can't release it during the call. The caller releases it. +ID3D12Device5* builder_device(void* self) { + std::lock_guard lock(g_mutex); + auto it = g_builders.find(self); + if (it == g_builders.end() || !it->second.device) return nullptr; + it->second.device->AddRef(); + return it->second.device; +} + +void note_stream(const xdxr::StreamDesc& stream) { + if (stream.size_in_bytes == 0 || !stream.stream) return; + static std::atomic s_logged{false}; + log_once(s_logged, "XDXR stream records (console builder settings) are ignored by the layer's builder"); +} + +// ?GetRaytracingAccelerationStructurePrebuildInfo@XboxBvhBuilder@@QEAAXPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_ +// STRUCTURE_INPUTS@@PEBUD3D12XBOX_XDXR_STREAM_DESC@@PEAUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO@@@Z +// The sizes the layer's own builder needs, which are the sizes the layer's build will use. +void builder_prebuild_info(void* self, const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS* inputs, + const xdxr::StreamDesc* stream, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO* info) { + if (!info) return; + *info = {}; + if (!inputs) return; + if (stream) note_stream(*stream); + ID3D12Device5* device = builder_device(self); + if (!device) { + static std::atomic s_logged{false}; + log_once(s_logged, "GetRaytracingAccelerationStructurePrebuildInfo on a builder without a DXR device; sizes are 0"); + return; + } + device->GetRaytracingAccelerationStructurePrebuildInfo(inputs, info); + device->Release(); +} + +// ?BuildRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList6@@IPEBUD3D12XBOX_ +// BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2@@@Z +// Each element is a public build description followed by its postbuild descriptions and a stream (xdxr_descs.h), so +// it is one BuildRaytracingAccelerationStructure on the list. +void builder_build_batched2x(void*, void* list, UINT count, const xdxr::BatchedDesc2* descs) { + static_assert(sizeof(D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC) == 0x30, "the BATCHED_DESC2 prefix"); + static_assert(sizeof(D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC) == sizeof(xdxr::PostbuildInfoDesc), + "postbuild descriptions are the public ones"); + if (count == 0) return; + if (!descs) return; + ID3D12GraphicsCommandList4* list4 = list4_of(list); + if (!list4) { + static std::atomic s_logged{false}; + log_once(s_logged, "BuildRaytracingAccelerationStructureBatched2X: the list has no ID3D12GraphicsCommandList4"); + return; + } + for (UINT i = 0; i < count; ++i) { + const xdxr::BatchedDesc2& element = descs[i]; + note_stream(element.stream); + D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC build; + std::memcpy(&build, &element, sizeof(build)); + // The postbuild descriptions, without the offline-statistics type the DLL refuses (docs/xdxr.md §4). + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC kept[16]; + UINT n_kept = 0; + bool skipped_statistics = false; + const auto* post = reinterpret_cast( + element.postbuild_info_descs); + for (UINT p = 0; post && p < element.num_postbuild_info_descs; ++p) { + if (static_cast(post[p].InfoType) == xdxr::kPostbuildInfoOfflineStatistics) { + skipped_statistics = true; + continue; + } + if (n_kept == 16) { + static std::atomic s_logged{false}; + log_once(s_logged, "more than 16 postbuild descriptions in one element; the rest are dropped"); + break; + } + kept[n_kept++] = post[p]; + } + if (skipped_statistics) { + // The DLL throws E_INVALIDARG for this element before any work; the shim skips it the same way. + static std::atomic s_logged{false}; + log_once(s_logged, "an element asked for offline statistics (0x10), which the DLL refuses; element skipped"); + continue; + } + list4->BuildRaytracingAccelerationStructure(&build, n_kept, n_kept ? kept : nullptr); + } + list4->Release(); +} + +// ?CopyRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@_K1W4D3D12_RAYTRACING_ +// ACCELERATION_STRUCTURE_COPY_MODE@@@Z +void builder_copy(void*, void* list, UINT64 dest, UINT64 source, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE mode) { + ID3D12GraphicsCommandList4* list4 = list4_of(list); + if (!list4) { + static std::atomic s_logged{false}; + log_once(s_logged, "CopyRaytracingAccelerationStructure: the list has no ID3D12GraphicsCommandList4"); + return; + } + list4->CopyRaytracingAccelerationStructure(dest, source, mode); + list4->Release(); +} + +// ?RehydrateRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAJPEAUID3D12GraphicsCommandList8@@IPEBUD3D12_ +// BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@PEB_K@Z -> HRESULT. Not implemented yet (see the header comment). +HRESULT builder_rehydrate_batched2x(void*, void*, UINT, const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC*, + const UINT64*) { + static std::atomic s_logged{false}; + log_once(s_logged, "RehydrateRaytracingAccelerationStructureBatched2X is not implemented yet; E_NOTIMPL"); + return E_NOTIMPL; +} + +constexpr const char kDll[] = "xboxbvhbuilder.dll"; + +const rt::shims::Entry kEntries[] = { + {kDll, "??0XboxBvhBuilder@@QEAA@PEAUID3D12Device11@@_N@Z", reinterpret_cast(&builder_construct)}, + {kDll, "??1XboxBvhBuilder@@QEAA@XZ", reinterpret_cast(&builder_destruct)}, + {kDll, "?Set64BitMortonCodes@XboxBvhBuilder@@QEAAX_N@Z", reinterpret_cast(&builder_set_64bit_morton_codes)}, + {kDll, + "?GetRaytracingAccelerationStructurePrebuildInfo@XboxBvhBuilder@@QEAAXPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_" + "STRUCTURE_INPUTS@@PEBUD3D12XBOX_XDXR_STREAM_DESC@@PEAUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO@@@Z", + reinterpret_cast(&builder_prebuild_info)}, + {kDll, + "?BuildRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList6@@IPEBUD3D12" + "XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2@@@Z", + reinterpret_cast(&builder_build_batched2x)}, + {kDll, + "?CopyRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@_K1W4D3D12_" + "RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE@@@Z", + reinterpret_cast(&builder_copy)}, + {kDll, + "?RehydrateRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAJPEAUID3D12GraphicsCommandList8@@IPEBU" + "D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@PEB_K@Z", + reinterpret_cast(&builder_rehydrate_batched2x)}, +}; + +bool shim_enabled() { + char value[16] = {}; + size_t length = 0; + if (getenv_s(&length, value, "LEONIDA_BVH_BUILDER") != 0 || length <= 1) return true; + return _stricmp(value, "console") != 0; +} + +// Registers the table unless LEONIDA_BVH_BUILDER=console asks for the bundled DLL. +struct Registration { + Registration() { + if (!shim_enabled()) return; + static rt::shims::Table table(kEntries, sizeof(kEntries) / sizeof(kEntries[0])); + } +} g_registration; + +} // namespace + +namespace rt::shims { +// For tests: the builders constructed and not destroyed. +size_t xbox_bvh_builder_live_count() { + std::lock_guard lock(g_mutex); + return g_builders.size(); +} +} // namespace rt::shims diff --git a/runtime/test/xbox_bvh_builder_test.cpp b/runtime/test/xbox_bvh_builder_test.cpp new file mode 100644 index 0000000000..3deb816b46 --- /dev/null +++ b/runtime/test/xbox_bvh_builder_test.cpp @@ -0,0 +1,430 @@ +// The XboxBvhBuilder.dll shim (shims/xbox_bvh_builder.cpp) on the standalone Vulkan device, called the way the +// title's imports bind: rt::shims::find("xboxbvhbuilder.dll", ), `this` first. A BLAS and a TLAS are +// built through BuildRaytracingAccelerationStructureBatched2X, the BLAS is compacted through +// CopyRaytracingAccelerationStructure, and the three are written to as .bin + .json for +// `python -I tools/xdxr_bvh.py check-build ` (ctest: xbox_bvh_builder + xbox_bvh_builder_check), which +// checks the records and traces rays against brute force. Also checked: the shim's prebuild sizes are the layer's, +// an element asking for offline statistics is skipped and leaves its destination untouched, a non-empty XDXR stream +// is accepted, rehydration answers E_NOTIMPL, and builders are released. +// +// xbox_bvh_builder_test the shim +// xbox_bvh_builder_test --console run with LEONIDA_BVH_BUILDER=console: nothing is registered +// +// Exit 77 without a Vulkan device. No game files. +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include "../shims/shims.h" +#include "../src/xdxr_descs.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rt::shims { +size_t xbox_bvh_builder_live_count(); +} + +namespace { + +namespace xdxr = leonida::xdxr; + +int g_checks = 0; +int g_failures = 0; + +void check(bool condition, const char* what) { + ++g_checks; + std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); + if (!condition) ++g_failures; +} + +template struct Ref { + T* p = nullptr; + ~Ref() { if (p) p->Release(); } + T* operator->() const { return p; } + T** put() { return &p; } +}; + +int fail(const char* what, HRESULT hr = S_OK) { + std::fprintf(stderr, "FAIL: %s (hr 0x%08lx)\n", what, static_cast(hr)); + return 1; +} + +HRESULT buffer(ID3D12Device* device, D3D12_HEAP_TYPE heap, UINT64 size, D3D12_RESOURCE_STATES state, + D3D12_RESOURCE_FLAGS flags, ID3D12Resource** out) { + D3D12_HEAP_PROPERTIES props{}; + props.Type = heap; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = size ? size : 1; + desc.Height = 1; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + desc.Flags = flags; + return device->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, IID_PPV_ARGS(out)); +} + +std::string num(double x) { + char s[64]; + std::snprintf(s, sizeof s, "%.9g", x); + return s; +} + +bool write_file(const std::string& path, const void* data, std::size_t bytes) { + std::ofstream f(path, std::ios::binary); + f.write(static_cast(data), std::streamsize(bytes)); + return bool(f); +} + +// The exports, as the executable imports them. +constexpr const char kDll[] = "xboxbvhbuilder.dll"; +constexpr const char kConstruct[] = "??0XboxBvhBuilder@@QEAA@PEAUID3D12Device11@@_N@Z"; +constexpr const char kDestruct[] = "??1XboxBvhBuilder@@QEAA@XZ"; +constexpr const char kMorton[] = "?Set64BitMortonCodes@XboxBvhBuilder@@QEAAX_N@Z"; +constexpr const char kPrebuild[] = + "?GetRaytracingAccelerationStructurePrebuildInfo@XboxBvhBuilder@@QEAAXPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_" + "STRUCTURE_INPUTS@@PEBUD3D12XBOX_XDXR_STREAM_DESC@@PEAUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO@@@Z"; +constexpr const char kBatched[] = + "?BuildRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList6@@IPEBUD3D12" + "XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2@@@Z"; +constexpr const char kCopy[] = + "?CopyRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@_K1W4D3D12_" + "RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE@@@Z"; +constexpr const char kRehydrate[] = + "?RehydrateRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAJPEAUID3D12GraphicsCommandList8@@IPEBU" + "D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@PEB_K@Z"; + +using Construct = void*(*)(void*, void*, bool); +using Destruct = void (*)(void*); +using Morton = void (*)(void*, bool); +using Prebuild = void (*)(void*, const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS*, const xdxr::StreamDesc*, + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO*); +using Batched = void (*)(void*, void*, UINT, const xdxr::BatchedDesc2*); +using Copy = void (*)(void*, void*, UINT64, UINT64, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE); +using Rehydrate = HRESULT (*)(void*, void*, UINT, const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC*, + const UINT64*); + +template F shim(const char* name) { return reinterpret_cast(rt::shims::find(kDll, name)); } + +} // namespace + +int main(int argc, char** argv) { + if (argc < 2) { + std::fprintf(stderr, "usage: xbox_bvh_builder_test | --console\n"); + return 2; + } + if (std::strcmp(argv[1], "--console") == 0) { + // LEONIDA_BVH_BUILDER=console: the imports must bind to the bundled DLL, so the shim registers nothing. + check(shim(kConstruct) == nullptr && shim(kBatched) == nullptr && + !rt::shims::owns_dll(kDll), + "LEONIDA_BVH_BUILDER=console registers none of the exports"); + std::printf("xbox_bvh_builder_test: %d of %d checks failed\n", g_failures, g_checks); + return g_failures ? 1 : 0; + } + const std::string dir = argv[1]; + std::error_code ec; + std::filesystem::create_directories(dir, ec); + for (const auto& entry : std::filesystem::directory_iterator(dir, ec)) { + const auto ext = entry.path().extension(); + if (ext == ".bin" || ext == ".json") std::filesystem::remove(entry.path(), ec); + } + + // ---- the seven exports are registered ---- + const auto construct = shim(kConstruct); + const auto destruct = shim(kDestruct); + const auto morton = shim(kMorton); + const auto prebuild = shim(kPrebuild); + const auto batched = shim(kBatched); + const auto copy = shim(kCopy); + const auto rehydrate = shim(kRehydrate); + check(construct && destruct && morton && prebuild && batched && copy && rehydrate && rt::shims::owns_dll(kDll), + "the seven exports the executable imports are served by the shim"); + if (!(construct && destruct && morton && prebuild && batched && copy && rehydrate)) return 1; + + char rt_as[8] = {}; + std::size_t rt_as_length = 0; + if (getenv_s(&rt_as_length, rt_as, "LEONIDA_RT_AS") == 0 && rt_as_length > 1 && std::strcmp(rt_as, "khr") == 0) { + std::puts("SKIP: LEONIDA_RT_AS=khr"); + return 77; + } + Ref device; + if (FAILED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(device.put())))) { + std::puts("SKIP: no Vulkan D3D12 device"); + return 77; + } + + // ---- the builder object: the title's storage, larger than anything the shim could write ---- + alignas(16) unsigned char builder[256]; + std::memset(builder, 0xab, sizeof builder); + check(construct(builder, device.p, true) == builder, "the constructor returns `this`"); + bool untouched = true; + for (unsigned char b : builder) untouched = untouched && b == 0xab; + check(untouched && rt::shims::xbox_bvh_builder_live_count() == 1, + "nothing is written into the title's builder object; its state is kept aside"); + morton(builder, true); + + // ---- geometry: a triangle soup ---- + std::mt19937 rng(23); + std::uniform_real_distribution spread(-4.0f, 4.0f), jitter(-0.6f, 0.6f); + const UINT tris = 400; + std::vector soup; + for (UINT t = 0; t < tris; ++t) { + const float c[3] = {spread(rng), spread(rng), spread(rng)}; + for (int k = 0; k < 9; ++k) soup.push_back(c[k % 3] + jitter(rng)); + } + const UINT64 soup_bytes = soup.size() * 4; + Ref upload; + HRESULT hr = buffer(device.p, D3D12_HEAP_TYPE_UPLOAD, 256 + soup_bytes + 3 * 64, D3D12_RESOURCE_STATE_GENERIC_READ, + D3D12_RESOURCE_FLAG_NONE, upload.put()); + if (FAILED(hr)) return fail("upload buffer", hr); + char* mapped = nullptr; + if (FAILED(upload->Map(0, nullptr, reinterpret_cast(&mapped)))) return fail("Map upload"); + std::memcpy(mapped, soup.data(), std::size_t(soup_bytes)); + const UINT64 soup_va = upload->GetGPUVirtualAddress(); + + D3D12_RAYTRACING_GEOMETRY_DESC geometry{}; + geometry.Type = D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES; + geometry.Flags = D3D12_RAYTRACING_GEOMETRY_FLAG_OPAQUE; + geometry.Triangles.VertexFormat = DXGI_FORMAT_R32G32B32_FLOAT; + geometry.Triangles.VertexCount = tris * 3; + geometry.Triangles.VertexBuffer = {soup_va, 12}; + D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS blas_inputs{}; + blas_inputs.Type = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL; + blas_inputs.Flags = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PREFER_FAST_TRACE | + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_ALLOW_COMPACTION; + blas_inputs.DescsLayout = D3D12_ELEMENTS_LAYOUT_ARRAY; + blas_inputs.NumDescs = 1; + blas_inputs.pGeometryDescs = &geometry; + + // ---- GetRaytracingAccelerationStructurePrebuildInfo: the layer's sizes, with or without a stream ---- + const xdxr::StreamRecord2 record{2, 0, -1.0f, 0.0f}; // a type-2 record with its defaults + const xdxr::StreamDesc stream{sizeof record, &record}; + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO blas_info{}, layer_info{}; + prebuild(builder, &blas_inputs, &stream, &blas_info); + device->GetRaytracingAccelerationStructurePrebuildInfo(&blas_inputs, &layer_info); + check(blas_info.ResultDataMaxSizeInBytes == layer_info.ResultDataMaxSizeInBytes && + blas_info.ScratchDataSizeInBytes == layer_info.ScratchDataSizeInBytes, + "the shim's prebuild sizes are the layer's own"); + if (!blas_info.ResultDataMaxSizeInBytes) { + std::puts("SKIP: the device does not build XDXR acceleration structures (no bufferDeviceAddress)"); + return 77; + } + // The title's device is a d3d12_xs device proxy (D3D12XboxCreateDevice): a builder constructed on one reaches the + // real device behind it. + { + Ref proxy; + alignas(16) unsigned char proxied[64]; + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO through_proxy{}; + device->AddRef(); // create_device_proxy takes one reference to the real device on success + const bool wrapped = SUCCEEDED(rt::d3d12_xs::create_device_proxy(device.p, IID_PPV_ARGS(proxy.put()))); + if (!wrapped) device->Release(); + const bool made = wrapped && rt::d3d12_xs::device_proxy_real_device(proxy.p) != nullptr; + if (made) { + construct(proxied, proxy.p, true); + prebuild(proxied, &blas_inputs, nullptr, &through_proxy); + destruct(proxied); + } + check(made && through_proxy.ResultDataMaxSizeInBytes == layer_info.ResultDataMaxSizeInBytes && + through_proxy.ScratchDataSizeInBytes == layer_info.ScratchDataSizeInBytes, + "a builder constructed on a d3d12_xs device proxy uses the real device behind it"); + } + D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS tlas_inputs{}; + tlas_inputs.Type = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL; + tlas_inputs.DescsLayout = D3D12_ELEMENTS_LAYOUT_ARRAY; + tlas_inputs.NumDescs = 2; + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO tlas_info{}; + prebuild(builder, &tlas_inputs, nullptr, &tlas_info); + if (!tlas_info.ResultDataMaxSizeInBytes) return fail("TLAS prebuild info is empty"); + + // ---- buffers ---- + const D3D12_RESOURCE_FLAGS uav = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + const D3D12_RESOURCE_STATES as_state = D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE; + Ref blas, refused, tlas, scratch, scratch2, info, blas_rb, refused_rb, tlas_rb, info_rb; + const UINT64 scratch_size = blas_info.ScratchDataSizeInBytes > tlas_info.ScratchDataSizeInBytes + ? blas_info.ScratchDataSizeInBytes : tlas_info.ScratchDataSizeInBytes; + if (FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, blas_info.ResultDataMaxSizeInBytes, as_state, uav, blas.put())) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, blas_info.ResultDataMaxSizeInBytes, as_state, uav, refused.put())) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, tlas_info.ResultDataMaxSizeInBytes, as_state, uav, tlas.put())) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, scratch_size, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, uav, scratch.put())) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, scratch_size, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, uav, scratch2.put())) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, 16, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, uav, info.put())) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_READBACK, blas_info.ResultDataMaxSizeInBytes, + D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE, blas_rb.put())) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_READBACK, blas_info.ResultDataMaxSizeInBytes, + D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE, refused_rb.put())) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_READBACK, tlas_info.ResultDataMaxSizeInBytes, + D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE, tlas_rb.put())) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_READBACK, 16, D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_FLAG_NONE, info_rb.put()))) + return fail("acceleration-structure buffers", hr); + + // ---- instances ---- + const float c = std::cos(0.9f), s = std::sin(0.9f); + const float xforms[2][12] = {{1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0}, {c, 0, s, 10, 0, 1, 0, -2, -s, 0, c, 1}}; + D3D12_RAYTRACING_INSTANCE_DESC instances[2]{}; + for (int i = 0; i < 2; ++i) { + std::memcpy(instances[i].Transform, xforms[i], sizeof xforms[i]); + instances[i].InstanceID = 40 + i; + instances[i].InstanceMask = 0xff; + instances[i].AccelerationStructure = blas->GetGPUVirtualAddress(); + } + const UINT64 instances_at = (soup_bytes + 255) / 256 * 256; + std::memcpy(mapped + instances_at, instances, sizeof instances); + upload->Unmap(0, nullptr); + tlas_inputs.InstanceDescs = upload->GetGPUVirtualAddress() + instances_at; + + D3D12_COMMAND_QUEUE_DESC qd{}; + qd.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; + Ref queue; + Ref allocator; + Ref list; + Ref fence; + if (FAILED(device->CreateCommandQueue(&qd, IID_PPV_ARGS(queue.put()))) || + FAILED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(allocator.put()))) || + FAILED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, IID_PPV_ARGS(list.put()))) || + FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(fence.put())))) + return fail("queue, allocator, list or fence"); + UINT64 fence_value = 0; + auto submit = [&]() { + if (FAILED(list->Close())) return false; + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + if (FAILED(queue->Signal(fence.p, ++fence_value))) return false; + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + const bool done = event && SUCCEEDED(fence->SetEventOnCompletion(fence_value, event)) && + WaitForSingleObject(event, 10000) == WAIT_OBJECT_0; + if (event) CloseHandle(event); + return done && SUCCEEDED(device->GetDeviceRemovedReason()); + }; + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + + // ---- BuildRaytracingAccelerationStructureBatched2X: the BLAS (with a stream and a COMPACTED_SIZE postbuild), + // and an element asking for offline statistics, which the DLL refuses and the shim skips ---- + const xdxr::PostbuildInfoDesc compacted_post{info->GetGPUVirtualAddress(), + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_COMPACTED_SIZE, 0}; + const xdxr::PostbuildInfoDesc statistics_post{info->GetGPUVirtualAddress() + 8, + xdxr::kPostbuildInfoOfflineStatistics, 0}; + xdxr::BatchedDesc2 elements[2]{}; + for (xdxr::BatchedDesc2& e : elements) { + std::memcpy(&e.inputs, &blas_inputs, sizeof e.inputs); + e.stream = stream; + } + elements[0].dest_acceleration_structure_data = blas->GetGPUVirtualAddress(); + elements[0].scratch_acceleration_structure_data = scratch->GetGPUVirtualAddress(); + elements[0].num_postbuild_info_descs = 1; + elements[0].postbuild_info_descs = &compacted_post; + elements[1].dest_acceleration_structure_data = refused->GetGPUVirtualAddress(); + elements[1].scratch_acceleration_structure_data = scratch2->GetGPUVirtualAddress(); + elements[1].num_postbuild_info_descs = 1; + elements[1].postbuild_info_descs = &statistics_post; + batched(builder, list.p, 2, elements); + list->ResourceBarrier(1, &barrier); + xdxr::BatchedDesc2 top{}; + top.dest_acceleration_structure_data = tlas->GetGPUVirtualAddress(); + std::memcpy(&top.inputs, &tlas_inputs, sizeof top.inputs); + top.scratch_acceleration_structure_data = scratch->GetGPUVirtualAddress(); + batched(builder, list.p, 1, &top); + batched(builder, list.p, 0, nullptr); // an empty batch does nothing + list->ResourceBarrier(1, &barrier); + list->CopyBufferRegion(blas_rb.p, 0, blas.p, 0, blas_info.ResultDataMaxSizeInBytes); + list->CopyBufferRegion(refused_rb.p, 0, refused.p, 0, blas_info.ResultDataMaxSizeInBytes); + list->CopyBufferRegion(tlas_rb.p, 0, tlas.p, 0, tlas_info.ResultDataMaxSizeInBytes); + list->CopyBufferRegion(info_rb.p, 0, info.p, 0, 16); + if (!submit()) return fail("the batched builds did not complete"); + + UINT64 post[2] = {}; + { + void* p = nullptr; + if (FAILED(info_rb->Map(0, nullptr, &p))) return fail("Map postbuild"); + std::memcpy(post, p, sizeof post); + info_rb->Unmap(0, nullptr); + } + check(post[0] && post[0] % 64 == 0 && post[0] <= blas_info.ResultDataMaxSizeInBytes, + "the BLAS element's COMPACTED_SIZE postbuild is written"); + check(post[1] == 0, "the offline-statistics element is skipped: its postbuild destination is untouched"); + { + void* p = nullptr; + std::uint32_t units = 0; + if (SUCCEEDED(refused_rb->Map(0, nullptr, &p))) { + std::memcpy(&units, static_cast(p) + 4, 4); + refused_rb->Unmap(0, nullptr); + } + check(units == 0, "and no structure was built into its destination"); + } + + // ---- CopyRaytracingAccelerationStructure COMPACT into a buffer of exactly COMPACTED_SIZE ---- + Ref compacted, compacted_rb; + if (FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, post[0], as_state, uav, compacted.put())) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_READBACK, post[0], D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_FLAG_NONE, compacted_rb.put()))) + return fail("compacted buffers", hr); + if (FAILED(allocator->Reset()) || FAILED(list->Reset(allocator.p, nullptr))) return fail("Reset for compaction"); + copy(builder, list.p, compacted->GetGPUVirtualAddress(), blas->GetGPUVirtualAddress(), + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT); + list->ResourceBarrier(1, &barrier); + list->CopyBufferRegion(compacted_rb.p, 0, compacted.p, 0, post[0]); + if (!submit()) return fail("the compaction did not complete"); + + // ---- RehydrateRaytracingAccelerationStructureBatched2X: not implemented yet ---- + D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC rehydrate_desc{}; + const UINT64 source = blas->GetGPUVirtualAddress(); + check(rehydrate(builder, list.p, 1, &rehydrate_desc, &source) == E_NOTIMPL, + "RehydrateRaytracingAccelerationStructureBatched2X answers E_NOTIMPL (stage 2)"); + + // ---- dump for xdxr_bvh.py check-build ---- + auto dump = [&](ID3D12Resource* rb, UINT64 size, const std::string& name, const std::string& json) { + void* p = nullptr; + if (FAILED(rb->Map(0, nullptr, &p))) return false; + std::uint32_t units = 0; + std::memcpy(&units, static_cast(p) + 4, 4); // header totalSizeIn64BNodes + const UINT64 used = (UINT64(units) + 1) * 64; // the field does not count the 64-byte header + const bool ok = units && used <= size && write_file(dir + "/" + name + ".bin", p, std::size_t(used)) && + write_file(dir + "/" + name + ".json", json.data(), json.size()); + rb->Unmap(0, nullptr); + return ok; + }; + std::string triangles = "["; + for (UINT t = 0; t < tris; ++t) { + triangles += t ? ",\n [" : "\n ["; + for (int k = 0; k < 3; ++k) + triangles += (k ? ", [" : "[") + num(soup[9 * t + 3 * k]) + ", " + num(soup[9 * t + 3 * k + 1]) + ", " + + num(soup[9 * t + 3 * k + 2]) + "]"; + triangles += ", 0, " + std::to_string(t) + "]"; + } + triangles += "]"; + check(dump(blas_rb.p, blas_info.ResultDataMaxSizeInBytes, "shim_blas", + "{\"kind\": \"blas\", \"address\": " + std::to_string(blas->GetGPUVirtualAddress()) + + ", \"triangles\": " + triangles + "}\n"), + "the BLAS built through the shim is written for check-build"); + std::string inst = "["; + for (int i = 0; i < 2; ++i) { + inst += i ? ", {\"transform\": [" : "{\"transform\": ["; + for (int k = 0; k < 12; ++k) inst += (k ? ", " : "") + num(xforms[i][k]); + inst += "], \"mask\": 255, \"blas\": 0}"; + } + inst += "]"; + check(dump(tlas_rb.p, tlas_info.ResultDataMaxSizeInBytes, "shim_tlas", + "{\"kind\": \"tlas\", \"address\": " + std::to_string(tlas->GetGPUVirtualAddress()) + + ", \"bias\": 0, \"blas\": [\"shim_blas\"], \"instances\": " + inst + "}\n"), + "the TLAS built through the shim is written for check-build"); + check(dump(compacted_rb.p, post[0], "shim_blas_compacted", + "{\"kind\": \"blas\", \"address\": " + std::to_string(compacted->GetGPUVirtualAddress()) + + ", \"triangles\": " + triangles + "}\n"), + "the BLAS compacted through the shim is written for check-build"); + + // ---- the destructor releases the builder ---- + destruct(builder); + destruct(builder); // a second destruction of the same storage is ignored + check(rt::shims::xbox_bvh_builder_live_count() == 0, "the destructor releases the builder's state"); + + std::printf("xbox_bvh_builder_test: %d of %d checks failed\n", g_failures, g_checks); + return g_failures ? 1 : 0; +} diff --git a/scripts/build_runtime.ps1 b/scripts/build_runtime.ps1 index 2fd5120cc4..ff9dbf5562 100644 --- a/scripts/build_runtime.ps1 +++ b/scripts/build_runtime.ps1 @@ -81,7 +81,7 @@ $build || exit /b 1 Write-Warning "CMake and Ninja weren't found (neither VS C++ CMake tools nor native PATH tools): building with cl.exe directly, without the GameInput shim (SDL3). Install CMake + Ninja or VS's CMake tools component to get it." $xtaskqueueDir = Join-Path $root "third_party\xtaskqueue" $xtaskqueueFiles = "Source\Task\TaskQueue.cpp", "Source\Task\AsyncLib.cpp", "Source\Task\ThreadPool_win32.cpp", "Source\Task\WaitTimer_win32.cpp" | ForEach-Object { "`"$xtaskqueueDir\$_`"" } - $files = "src\main.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\file_system.cpp", "shims\xmem.cpp", "shims\d3d12_xs.cpp", "shims\d3d12_xs_device.cpp", "shims\d3d12_xs_rootsig.cpp", "shims\xgameruntime.cpp", "shims\xgameruntime_user.cpp", "shims\xgameruntime_gamesave.cpp", "shims\xgameruntime_store.cpp", "shims\xgameruntime_offline.cpp", "shims\winhttp_offline.cpp", "shims\library_loader.cpp", "shims\process.cpp" | ForEach-Object { "`"$src\$_`"" } + $files = "src\main.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\file_system.cpp", "shims\xmem.cpp", "shims\d3d12_xs.cpp", "shims\d3d12_xs_device.cpp", "shims\d3d12_xs_rootsig.cpp", "shims\xgameruntime.cpp", "shims\xgameruntime_user.cpp", "shims\xgameruntime_gamesave.cpp", "shims\xgameruntime_store.cpp", "shims\xgameruntime_offline.cpp", "shims\xbox_bvh_builder.cpp", "shims\winhttp_offline.cpp", "shims\library_loader.cpp", "shims\process.cpp" | ForEach-Object { "`"$src\$_`"" } $includes = "/I `"$src\src`" /I `"$src\shims`" /I `"$src\shims\xtaskqueue`" /I `"$xtaskqueueDir\Include`" /I `"$xtaskqueueDir\Source\Task`" /I `"$xtaskqueueDir\Source\Common`"" $opt = if ($Debug) { "/Od /MDd" } else { "/O2 /MD" } $body = @"