diff --git a/docs/xdxr.md b/docs/xdxr.md index 1b8a4cc274..24e9429f0f 100644 --- a/docs/xdxr.md +++ b/docs/xdxr.md @@ -132,7 +132,7 @@ static reference, reached through a table (#7516), so 2 of them are calls of ano | `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 | +| `RehydrateRaytracingAccelerationStructureBatched2X(GCL8*, UINT, BUILD_DESC*, UINT64*)` | 4 | rebuilds each structure from source geometry; refuses source-only stream without geometry | **Where it differs from the DLL:** - **Stream records (§3):** they tune the console builder's heuristics, so they are ignored (logged once). The result @@ -140,8 +140,23 @@ static reference, reached through a table (#7516), so 2 of them are calls of ano - **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. +- **Rehydration (`RehydrateRaytracingAccelerationStructureBatched2X`):** Rebuilds each structure on the GPU from + the source geometry its description carries ([bvh.md](bvh.md) §4a). The leaf frame `compressionParams` gives is + **not applied yet**: the leaves are built from the geometry as the description has it. + What the 4th parameter (`const UINT64* source_data`, mangling `PEB_K`) conveys is a **hypothesis**: it points to + the array of source buffer addresses for offline dehydrated console streams (e.g. rehydration inputs). + When geometry is provided (`NumDescs > 0`), the shim issues `BuildRaytracingAccelerationStructure` to construct + traversable GPU BVH nodes. That is a fresh build: the title sets `SourceAccelerationStructureData` to the + dehydrated stream, so the shim clears it and the `PERFORM_UPDATE` flag (logged once), which would otherwise make + the layer refit from the stream's bytes. The title passes `ScratchAccelerationStructureData = 0` (measured on the retail + title), so the shim supplies scratch, or the layer would reject the build: one new buffer per call, in which each + element has its own 256-byte-aligned region sized via `GetRaytracingAccelerationStructurePrebuildInfo`. The + layer's XDXR builder leaves the dependency between builds to the caller's barrier and the title puts none between + the elements of a batch, so no two builds, in a batch, on one list or on lists recorded in parallel, share scratch + bytes. The layer's command list holds the buffer until it is Reset or released, and the layer destroys it after + the submission that used it has retired. When `source_data` is supplied without geometry, the shim logs once and + refuses with `E_NOTIMPL`: offline console dehydrated streams cannot be directly deserialized by PC Vulkan/D3D12 + drivers ([bvh.md](bvh.md) §4/§4a). Empty structures (`NumDescs == 0` without source) are logged and skipped. `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`). diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 5f22be917e..43f11cdd3e 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2457,7 +2457,8 @@ if(TARGET Vulkan::Headers) 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) + # LEONIDA_VULKAN_DEVICE: the shim hands its rehydration scratch to the layer's list, as in gta6rt. + target_compile_definitions(xbox_bvh_builder_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_VULKAN_DEVICE) 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}") diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 6dee464a8f..62b70d921a 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -222,8 +222,11 @@ class GraphicsCommandList final const leonida::CommandList& commands() const { return list_; } // The descriptor tables this recording binds (console VAs), for the scan before a submission. const std::vector>& tables() const { return tables_; } - // The pipeline states and root signatures the recording names (it holds a reference to each until Reset). + // The pipeline states and root signatures the recording names (it holds a reference to each until Reset), and + // the objects a shim handed it with hold_until_reset. const std::vector& pinned() const { return held_; } + // rt::d3d12::hold_until_reset: an object the recording uses that its caller does not keep (a shim's own scratch). + void hold_for_recording(IUnknown* object) { hold(object); } bool needs_all_sampled_views() const { if (directly_indexed_) return true; for (const auto& command : list_.commands()) { @@ -2178,7 +2181,8 @@ class CommandQueue final // What a held batch (queue_holds.h) keeps alive until it has run: the pipeline states and root signatures its // lists name, which the application may release and Reset away as soon as ExecuteCommandLists returns. Resources - // are not held (a D3D12 application keeps them until the fence it signals; the docs, section 4.4, list this). + // are not held (a D3D12 application keeps them until the fence it signals; the docs, section 4.4, list this), + // except a shim's own the recording uses (hold_until_reset), which are pinned with them. static std::shared_ptr pin_lists(const std::vector& lists) { auto objects = std::shared_ptr>(new std::vector, [](auto* held) { for (IUnknown* object : *held) object->Release(); @@ -2807,6 +2811,13 @@ bool front_back_stencil_ref(ID3D12GraphicsCommandList8* list, UINT& front, UINT& return true; } +bool hold_until_reset(ID3D12GraphicsCommandList* list, IUnknown* object) { + GraphicsCommandList* l = GraphicsCommandList::from(list); + if (!l || !object) return false; + l->hold_for_recording(object); + return true; +} + bool recorded_commands(ID3D12GraphicsCommandList* list, std::vector& commands) { const GraphicsCommandList* l = GraphicsCommandList::from(list); if (!l) return false; diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index 849791a262..cbc05a1a13 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -578,6 +578,14 @@ void set_global_realtime_privilege_override_for_test(int state); // not one of this module's command lists. bool front_back_stencil_ref(ID3D12GraphicsCommandList8* list, UINT& front, UINT& back); +// Makes `list` hold a reference to `object` until its next Reset or its release, as it holds the pipeline states it +// names: for an object only the recording uses, such as a shim's own scratch buffer. A list is Reset once it has +// been executed (or a held batch, src/queue_holds.h, keeps it pinned until it has run), and a resource released +// after its submission is destroyed through the device's deferred queue once that submission has retired, so the +// object outlives every GPU use the recording makes of it. False when `list` is not one of this module's command +// lists or `object` is null. +bool hold_until_reset(ID3D12GraphicsCommandList* list, IUnknown* object); + // A copy of the commands `list` has recorded so far, for tests of what a bundle puts into its parent. False when // `list` is not one of this module's command lists. bool recorded_commands(ID3D12GraphicsCommandList* list, std::vector& commands); diff --git a/runtime/shims/xbox_bvh_builder.cpp b/runtime/shims/xbox_bvh_builder.cpp index 8c80419e2e..ad6d6810ac 100644 --- a/runtime/shims/xbox_bvh_builder.cpp +++ b/runtime/shims/xbox_bvh_builder.cpp @@ -28,8 +28,13 @@ // - 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.) +// - Rehydration: RehydrateRaytracingAccelerationStructureBatched2X rebuilds each structure from the source +// geometry its description carries (BuildRaytracingAccelerationStructure) (docs/bvh.md §4a). The leaf frame +// compressionParams gives is not applied yet: the leaves are built from the geometry as the description has it. +// The GPU cannot read offline dehydrated console streams directly (docs/bvh.md §4/§4a), +// so source-only streams without geometry are refused with E_NOTIMPL. The title passes Scratch = 0, so the shim +// supplies scratch: one buffer per call, sized via GetRaytracingAccelerationStructurePrebuildInfo, in which each +// element has a region of its own (rehydrate_scratch). // // 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. @@ -47,7 +52,11 @@ #include #include #include +#include +#ifdef LEONIDA_VULKAN_DEVICE +#include "d3d12_com.h" // rt::d3d12::hold_until_reset +#endif #include "d3d12_xs_device.h" #include "shims.h" #include "../src/xdxr_descs.h" @@ -59,8 +68,18 @@ 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; + // Rehydration scratch made for a list that cannot hold it (not the layer's own, rehydrate_scratch): kept until the + // builder is destroyed, since the shim never learns when the GPU is done with it. + std::vector kept; }; +void release_state(BuilderState& state) { + for (ID3D12Resource* scratch : state.kept) scratch->Release(); + state.kept.clear(); + if (state.device) state.device->Release(); + state.device = nullptr; +} + std::mutex g_mutex; std::unordered_map g_builders; @@ -107,8 +126,8 @@ void* builder_construct(void* self, void* device, bool) { } 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}; + release_state(state); // the same storage constructed twice without a destructor + state = BuilderState{device5, false, {}}; return self; } @@ -117,7 +136,7 @@ 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(); + release_state(it->second); g_builders.erase(it); } @@ -138,6 +157,63 @@ ID3D12Device5* builder_device(void* self) { return it->second.device; } +// Scratch for one RehydrateRaytracingAccelerationStructureBatched2X call, where the title passes +// ScratchAccelerationStructureData = 0 (measured on the retail title): a new buffer of `bytes`, in which each element +// that needs scratch has a region of its own. It is never shared with another call: two calls on one list (the title +// puts no barrier between them for scratch it does not know of) or lists recorded on several threads never write the +// same bytes. The list holds the buffer until it is Reset or released (rt::d3d12::hold_until_reset), and the layer +// destroys it after the submission that used it has retired; a list that cannot hold it leaves it to the builder, +// which keeps it until its destruction. Returns the buffer's GPU address, 0 when it could not be made. +UINT64 rehydrate_scratch(void* self, ID3D12Device5* device, ID3D12GraphicsCommandList4* list, UINT64 bytes) { + if (!device || !bytes) return 0; + D3D12_HEAP_PROPERTIES heap_props{}; + heap_props.Type = D3D12_HEAP_TYPE_DEFAULT; + D3D12_RESOURCE_DESC res_desc{}; + res_desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + res_desc.Alignment = 0; + res_desc.Width = bytes; + res_desc.Height = 1; + res_desc.DepthOrArraySize = 1; + res_desc.MipLevels = 1; + res_desc.Format = DXGI_FORMAT_UNKNOWN; + res_desc.SampleDesc.Count = 1; + res_desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + res_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + + ID3D12Resource* res = nullptr; + HRESULT hr = device->CreateCommittedResource( + &heap_props, D3D12_HEAP_FLAG_NONE, &res_desc, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, + IID_PPV_ARGS(&res)); + if (FAILED(hr) || !res) return 0; + const UINT64 va = res->GetGPUVirtualAddress(); + bool held = false; +#ifdef LEONIDA_VULKAN_DEVICE + held = rt::d3d12::hold_until_reset(list, res); +#else + (void)list; +#endif + if (held) { + res->Release(); // the list's reference keeps it from here + return va; + } + static std::atomic s_logged{false}; + log_once(s_logged, "RehydrateRaytracingAccelerationStructureBatched2X: the list cannot hold its scratch; the " + "builder keeps it until it is destroyed"); + std::lock_guard lock(g_mutex); + auto it = g_builders.find(self); + if (it == g_builders.end()) { // destroyed during the call: nothing is recorded with this scratch + res->Release(); + return 0; + } + it->second.kept.push_back(res); + return va; +} + +bool has_geometry(const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS& inputs) { + return inputs.NumDescs > 0 && (inputs.pGeometryDescs || inputs.InstanceDescs); +} + void note_stream(const xdxr::StreamDesc& stream) { if (stream.size_in_bytes == 0 || !stream.stream) return; static std::atomic s_logged{false}; @@ -227,12 +303,102 @@ void builder_copy(void*, void* list, UINT64 dest, UINT64 source, D3D12_RAYTRACIN } // ?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; +// BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@PEB_K@Z -> HRESULT. +// Rebuilds each acceleration structure from geometry on the command list. +HRESULT builder_rehydrate_batched2x(void* self, void* list, UINT count, + const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC* descs, + const UINT64* source_data) { + if (count == 0) return S_OK; + if (!descs) return E_INVALIDARG; + if (!list) return E_INVALIDARG; + ID3D12GraphicsCommandList4* list4 = list4_of(list); + if (!list4) { + static std::atomic s_logged{false}; + log_once(s_logged, "RehydrateRaytracingAccelerationStructureBatched2X: the list has no ID3D12GraphicsCommandList4"); + return E_NOINTERFACE; + } + ID3D12Device5* device = builder_device(self); + // First pass: the descriptions as they are recorded, and for each element that builds without scratch of the + // title's a region of its own in one scratch buffer for the batch, at D3D12's acceleration-structure alignment + // (256 bytes, which the layer checks scratch addresses against). The XDXR recorder leaves the dependency between + // builds to the caller's barrier (src/xdxr_build.h, dispatch()) and the title puts none between the elements of + // a batch, so elements must not share scratch bytes. The first source-only element ends the batch (below). + constexpr UINT64 kAlign = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BYTE_ALIGNMENT; + constexpr UINT64 kNoRegion = ~0ull; + std::vector builds; + std::vector regions; + builds.reserve(count); + regions.reserve(count); + UINT64 scratch_bytes = 0; + bool source_only = false; + for (UINT i = 0; i < count; ++i) { + D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC build = descs[i]; + const UINT64 src = source_data ? source_data[i] : build.SourceAccelerationStructureData; + // A rehydrate is a fresh build from geometry. The title sets SourceAccelerationStructureData to the + // dehydrated stream (measured on the retail title), and the layer reads that address for an update + // (d3d12_com.cpp, BuildRaytracingAccelerationStructure), so with PERFORM_UPDATE kept it would refit from + // the stream's bytes. Both are cleared. + if (build.Inputs.Flags & D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PERFORM_UPDATE) { + static std::atomic s_update_logged{false}; + log_once(s_update_logged, + "RehydrateRaytracingAccelerationStructureBatched2X: an element asks for PERFORM_UPDATE; it is " + "built afresh from its geometry instead (the source is the dehydrated stream)"); + build.Inputs.Flags &= ~D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PERFORM_UPDATE; + } + build.SourceAccelerationStructureData = 0; + UINT64 region = kNoRegion; + if (has_geometry(build.Inputs)) { + if (!build.ScratchAccelerationStructureData && device) { + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO prebuild{}; + device->GetRaytracingAccelerationStructurePrebuildInfo(&build.Inputs, &prebuild); + const UINT64 size = prebuild.ScratchDataSizeInBytes ? prebuild.ScratchDataSizeInBytes : 1; + region = scratch_bytes; + scratch_bytes += (size + kAlign - 1) / kAlign * kAlign; + } + } else if (src) { + source_only = true; + break; + } + builds.push_back(build); + regions.push_back(region); + } + const UINT64 scratch = scratch_bytes ? rehydrate_scratch(self, device, list4, scratch_bytes) : 0; + + for (std::size_t i = 0; i < builds.size(); ++i) { + D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC& build = builds[i]; + if (has_geometry(build.Inputs)) { + // The title passes ScratchAccelerationStructureData = 0 (measured on the retail title). + // Supply a scratch region to prevent d3d12_com.cpp from poisoning the command list. + if (regions[i] != kNoRegion && scratch) build.ScratchAccelerationStructureData = scratch + regions[i]; + if (!build.ScratchAccelerationStructureData) { + static std::atomic s_scratch_logged{false}; + log_once(s_scratch_logged, + "RehydrateRaytracingAccelerationStructureBatched2X: ScratchAccelerationStructureData is 0 " + "and could not be allocated; skipping build to avoid command list rejection"); + continue; + } + list4->BuildRaytracingAccelerationStructure(&build, 0, nullptr); + } else { + static std::atomic s_empty_logged{false}; + log_once(s_empty_logged, + "RehydrateRaytracingAccelerationStructureBatched2X: element has NumDescs == 0 with no geometry; " + "skipping empty structure"); + } + } + if (source_only) { + // docs/bvh.md §4/§4a: the rehydrate source is a dehydrated console stream (element chunks, + // level table, box overrides), not a D3D12 serialized blob. On the XDXR path, a DESERIALIZE + // copy is replayed as a byte clone, so the destination would hold dehydrated bytes the GPU + // traversal shaders cannot read. Rehydration requires geometry reconstruction (docs/bvh.md §4a). + // Refusing source-only rehydration without geometry. + static std::atomic s_source_only_logged{false}; + log_once(s_source_only_logged, + "RehydrateRaytracingAccelerationStructureBatched2X: source-only dehydrated stream without " + "geometry cannot be deserialized as a D3D12 BLAS (docs/bvh.md §4/§4a); refusing element"); + } + if (device) device->Release(); + list4->Release(); + return source_only ? E_NOTIMPL : S_OK; } constexpr const char kDll[] = "xboxbvhbuilder.dll"; diff --git a/runtime/test/xbox_bvh_builder_test.cpp b/runtime/test/xbox_bvh_builder_test.cpp index 3deb816b46..8334143fd7 100644 --- a/runtime/test/xbox_bvh_builder_test.cpp +++ b/runtime/test/xbox_bvh_builder_test.cpp @@ -5,7 +5,9 @@ // `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. +// is accepted, rehydration rebuilds from geometry with S_OK (with the title's scratch, with none, and two elements of +// one batch without scratch, which the shim gives regions of their own; their structures go to check-build too) and +// refuses a source-only element, and builders are released. // // xbox_bvh_builder_test the shim // xbox_bvh_builder_test --console run with LEONIDA_BVH_BUILDER=console: nothing is registered @@ -373,11 +375,96 @@ int main(int argc, char** argv) { list->CopyBufferRegion(compacted_rb.p, 0, compacted.p, 0, post[0]); if (!submit()) return fail("the compaction did not complete"); - // ---- RehydrateRaytracingAccelerationStructureBatched2X: not implemented yet ---- + // ---- RehydrateRaytracingAccelerationStructureBatched2X: rebuilds from geometry ---- + Ref rehydrated_as, rehydrated_rb; + if (FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, blas_info.ResultDataMaxSizeInBytes, as_state, uav, + rehydrated_as.put())) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_READBACK, blas_info.ResultDataMaxSizeInBytes, + D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE, rehydrated_rb.put()))) + return fail("rehydrated buffers", hr); + if (FAILED(allocator->Reset()) || FAILED(list->Reset(allocator.p, nullptr))) return fail("Reset for rehydrate"); + D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC rehydrate_desc{}; + rehydrate_desc.DestAccelerationStructureData = rehydrated_as->GetGPUVirtualAddress(); + rehydrate_desc.Inputs = blas_inputs; + rehydrate_desc.ScratchAccelerationStructureData = scratch->GetGPUVirtualAddress(); const UINT64 source = blas->GetGPUVirtualAddress(); - check(rehydrate(builder, list.p, 1, &rehydrate_desc, &source) == E_NOTIMPL, - "RehydrateRaytracingAccelerationStructureBatched2X answers E_NOTIMPL (stage 2)"); + + check(rehydrate(builder, nullptr, 1, &rehydrate_desc, &source) == E_INVALIDARG, + "RehydrateRaytracingAccelerationStructureBatched2X rejects null list"); + check(rehydrate(builder, list.p, 1, nullptr, &source) == E_INVALIDARG, + "RehydrateRaytracingAccelerationStructureBatched2X rejects null descs"); + check(rehydrate(builder, list.p, 0, nullptr, nullptr) == S_OK, + "RehydrateRaytracingAccelerationStructureBatched2X with count 0 returns S_OK"); + + D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC source_only_desc{}; + source_only_desc.DestAccelerationStructureData = rehydrated_as->GetGPUVirtualAddress(); + check(rehydrate(builder, list.p, 1, &source_only_desc, &source) == E_NOTIMPL, + "RehydrateRaytracingAccelerationStructureBatched2X refuses source-only stream without geometry"); + + D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC empty_desc{}; + check(rehydrate(builder, list.p, 1, &empty_desc, nullptr) == S_OK, + "RehydrateRaytracingAccelerationStructureBatched2X logs and skips empty structure"); + + check(rehydrate(builder, list.p, 1, &rehydrate_desc, &source) == S_OK, + "RehydrateRaytracingAccelerationStructureBatched2X rebuilds BLAS and returns S_OK"); + + // The title passes ScratchAccelerationStructureData = 0: the shim supplies scratch. Each of these builds has a + // destination of its own, read back below, so a build the shim skipped fails its check. + Ref zero_scratch_as, zero_scratch_rb; + if (FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, blas_info.ResultDataMaxSizeInBytes, as_state, uav, + zero_scratch_as.put())) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_READBACK, blas_info.ResultDataMaxSizeInBytes, + D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE, zero_scratch_rb.put()))) + return fail("zero-scratch buffers", hr); + D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC zero_scratch_desc = rehydrate_desc; + zero_scratch_desc.DestAccelerationStructureData = zero_scratch_as->GetGPUVirtualAddress(); + zero_scratch_desc.ScratchAccelerationStructureData = 0; + check(rehydrate(builder, list.p, 1, &zero_scratch_desc, &source) == S_OK, + "RehydrateRaytracingAccelerationStructureBatched2X supplies scratch when ScratchAccelerationStructureData == 0"); + + // Two elements of one batch, both without scratch, and no barrier between them (the title puts none): each needs + // a scratch region of its own. The second element has half the triangles, and asks for PERFORM_UPDATE with a + // source, as the title's dehydrated stream would be: a rehydrate builds it afresh all the same. + const UINT pair_tris[2] = {tris, tris / 2}; + D3D12_RAYTRACING_GEOMETRY_DESC pair_geometry[2] = {geometry, geometry}; + pair_geometry[1].Triangles.VertexCount = pair_tris[1] * 3; + Ref pair_as[2], pair_rb[2]; + D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC pair_desc[2]{}; + for (int i = 0; i < 2; ++i) { + if (FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, blas_info.ResultDataMaxSizeInBytes, as_state, uav, + pair_as[i].put())) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_READBACK, blas_info.ResultDataMaxSizeInBytes, + D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE, pair_rb[i].put()))) + return fail("batch-of-two buffers", hr); + pair_desc[i].DestAccelerationStructureData = pair_as[i]->GetGPUVirtualAddress(); + pair_desc[i].Inputs = blas_inputs; + pair_desc[i].Inputs.pGeometryDescs = &pair_geometry[i]; + } + pair_desc[1].Inputs.Flags |= D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PERFORM_UPDATE; + pair_desc[1].SourceAccelerationStructureData = source; + check(rehydrate(builder, list.p, 2, pair_desc, nullptr) == S_OK, + "RehydrateRaytracingAccelerationStructureBatched2X builds a batch of two elements without scratch"); + + list->ResourceBarrier(1, &barrier); + list->CopyBufferRegion(rehydrated_rb.p, 0, rehydrated_as.p, 0, blas_info.ResultDataMaxSizeInBytes); + list->CopyBufferRegion(zero_scratch_rb.p, 0, zero_scratch_as.p, 0, blas_info.ResultDataMaxSizeInBytes); + for (int i = 0; i < 2; ++i) + list->CopyBufferRegion(pair_rb[i].p, 0, pair_as[i].p, 0, blas_info.ResultDataMaxSizeInBytes); + if (!submit()) return fail("the rehydrate build did not complete"); + auto header_units = [](ID3D12Resource* rb) { + void* p = nullptr; + std::uint32_t units = 0; + if (SUCCEEDED(rb->Map(0, nullptr, &p))) { + std::memcpy(&units, static_cast(p) + 4, 4); + rb->Unmap(0, nullptr); + } + return units; + }; + check(header_units(rehydrated_rb.p) > 0, "the rehydrated structure has non-zero totalSizeIn64BNodes header"); + check(header_units(zero_scratch_rb.p) > 0, "the structure rehydrated without the title's scratch was built"); + check(header_units(pair_rb[0].p) > 0 && header_units(pair_rb[1].p) > 0, + "both elements of the batch without scratch were built"); // ---- dump for xdxr_bvh.py check-build ---- auto dump = [&](ID3D12Resource* rb, UINT64 size, const std::string& name, const std::string& json) { @@ -391,15 +478,18 @@ int main(int argc, char** argv) { 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 += "]"; + auto triangle_list = [&](UINT count) { + std::string out = "["; + for (UINT t = 0; t < count; ++t) { + out += t ? ",\n [" : "\n ["; + for (int k = 0; k < 3; ++k) + out += (k ? ", [" : "[") + num(soup[9 * t + 3 * k]) + ", " + num(soup[9 * t + 3 * k + 1]) + ", " + + num(soup[9 * t + 3 * k + 2]) + "]"; + out += ", 0, " + std::to_string(t) + "]"; + } + return out + "]"; + }; + const std::string triangles = triangle_list(tris); check(dump(blas_rb.p, blas_info.ResultDataMaxSizeInBytes, "shim_blas", "{\"kind\": \"blas\", \"address\": " + std::to_string(blas->GetGPUVirtualAddress()) + ", \"triangles\": " + triangles + "}\n"), @@ -419,6 +509,18 @@ int main(int argc, char** argv) { "{\"kind\": \"blas\", \"address\": " + std::to_string(compacted->GetGPUVirtualAddress()) + ", \"triangles\": " + triangles + "}\n"), "the BLAS compacted through the shim is written for check-build"); + check(dump(zero_scratch_rb.p, blas_info.ResultDataMaxSizeInBytes, "shim_blas_rehydrated_zero_scratch", + "{\"kind\": \"blas\", \"address\": " + std::to_string(zero_scratch_as->GetGPUVirtualAddress()) + + ", \"triangles\": " + triangles + "}\n"), + "the BLAS rehydrated with the shim's scratch is written for check-build"); + for (int i = 0; i < 2; ++i) { + const std::string name = "shim_blas_rehydrated_batch" + std::to_string(i); + check(dump(pair_rb[i].p, blas_info.ResultDataMaxSizeInBytes, name, + "{\"kind\": \"blas\", \"address\": " + std::to_string(pair_as[i]->GetGPUVirtualAddress()) + + ", \"triangles\": " + triangle_list(pair_tris[i]) + "}\n"), + i ? "the batch's second element (its own scratch region) is written for check-build" + : "the batch's first element (its own scratch region) is written for check-build"); + } // ---- the destructor releases the builder ---- destruct(builder); diff --git a/tests/test_xbox_bvh_builder_rehydrate.py b/tests/test_xbox_bvh_builder_rehydrate.py new file mode 100644 index 0000000000..9f207b4bb4 --- /dev/null +++ b/tests/test_xbox_bvh_builder_rehydrate.py @@ -0,0 +1,88 @@ +"""Tests for RT-XDXR-BVH-REHYDRATE-BATCHED2X. + +Verifies that runtime/shims/xbox_bvh_builder.cpp implements +XboxBvhBuilder::RehydrateRaytracingAccelerationStructureBatched2X, +validates arguments (null list, null descs, count=0), rebuilds +structures from geometry via ID3D12GraphicsCommandList4, refuses +source-only dehydrated console streams without geometry (docs/bvh.md §4/§4a), +and registers the mangled export. +Synthetic test only; no retail game data or GPU required. +""" +import re +from pathlib import Path +import unittest + +ROOT = Path(__file__).resolve().parent.parent +XBOX_BVH_CPP = ROOT / "runtime" / "shims" / "xbox_bvh_builder.cpp" +XBOX_BVH_TEST_CPP = ROOT / "runtime" / "test" / "xbox_bvh_builder_test.cpp" + + +class XboxBvhBuilderRehydrateTest(unittest.TestCase): + def test_rehydrate_implementation_exists(self): + self.assertTrue(XBOX_BVH_CPP.is_file(), f"{XBOX_BVH_CPP} must exist") + content = XBOX_BVH_CPP.read_text(encoding="utf-8") + + # Function definition + m = re.search(r"HRESULT builder_rehydrate_batched2x\([^)]*\)\s*\{(.*?)\n\}", content, re.DOTALL) + self.assertIsNotNone(m, "builder_rehydrate_batched2x must be defined in xbox_bvh_builder.cpp") + body = m.group(1) + + # Must return S_OK on empty count + self.assertIn("if (count == 0) return S_OK;", body) + + # Must validate descs and list + self.assertIn("if (!descs) return E_INVALIDARG;", body) + self.assertIn("if (!list) return E_INVALIDARG;", body) + + # Must convert to list4 and call BuildRaytracingAccelerationStructure for geometry + self.assertIn("ID3D12GraphicsCommandList4* list4 = list4_of(list);", body) + self.assertIn("BuildRaytracingAccelerationStructure", body) + + # Must refuse source-only dehydrated streams without geometry (docs/bvh.md §4/§4a) + self.assertIn("E_NOTIMPL", body) + self.assertIn("docs/bvh.md", body) + + # Must release list4 and return S_OK on success + self.assertIn("list4->Release();", body) + self.assertIn("return S_OK;", body) + + def test_mangled_export_registered(self): + content = XBOX_BVH_CPP.read_text(encoding="utf-8") + # In C++, string literals split across lines are concatenated by the compiler. + compact = re.sub(r'"\s*\n\s*"', '', content) + symbol = "?RehydrateRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAJPEAUID3D12GraphicsCommandList8@@IPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@PEB_K@Z" + self.assertIn(symbol, compact, f"Symbol {symbol} must be registered in kEntries") + self.assertIn("&builder_rehydrate_batched2x", content) + + def test_test_harness_validates_rehydrate(self): + self.assertTrue(XBOX_BVH_TEST_CPP.is_file(), f"{XBOX_BVH_TEST_CPP} must exist") + test_content = XBOX_BVH_TEST_CPP.read_text(encoding="utf-8") + self.assertIn("rehydrate(builder, list.p, 1, &rehydrate_desc, &source) == S_OK", test_content) + self.assertIn("rehydrate(builder, nullptr, 1, &rehydrate_desc, &source) == E_INVALIDARG", test_content) + self.assertIn("rehydrate(builder, list.p, 0, nullptr, nullptr) == S_OK", test_content) + self.assertIn("rehydrate(builder, list.p, 1, &source_only_desc, &source) == E_NOTIMPL", test_content) + self.assertIn("rehydrate(builder, list.p, 1, &empty_desc, nullptr) == S_OK", test_content) + self.assertIn("rehydrate(builder, list.p, 1, &zero_scratch_desc, &source) == S_OK", test_content) + self.assertIn("rehydrate(builder, list.p, 2, pair_desc, nullptr) == S_OK", test_content) + # The zero-scratch build and both batch elements are read back and handed to check-build. + for name in ("shim_blas_rehydrated_zero_scratch", "shim_blas_rehydrated_batch"): + self.assertIn(name, test_content) + + def test_scratch_regions_and_fresh_build(self): + content = XBOX_BVH_CPP.read_text(encoding="utf-8") + m = re.search(r"HRESULT builder_rehydrate_batched2x\([^)]*\)\s*\{(.*?)\n\}", content, re.DOTALL) + self.assertIsNotNone(m) + body = m.group(1) + # One scratch buffer per call, a region per element at the D3D12 alignment. + self.assertIn("rehydrate_scratch(self, device, list4, scratch_bytes)", body) + self.assertIn("D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BYTE_ALIGNMENT", body) + # The list holds the scratch until it is Reset; no buffer is kept or regrown on the builder. + self.assertIn("rt::d3d12::hold_until_reset(list, res)", content) + self.assertNotIn("builder_ensure_scratch", content) + # A rehydrate is a fresh build: the update flag and the source are cleared. + self.assertIn("&= ~D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PERFORM_UPDATE", body) + self.assertIn("build.SourceAccelerationStructureData = 0;", body) + + +if __name__ == "__main__": + unittest.main()