diff options
| author | romainveurrier <romain.veurrier@gmail.com> | 2026-11-22 14:04:34 +0100 |
|---|---|---|
| committer | romainveurrier <romain.veurrier@gmail.com> | 2026-11-22 14:04:34 +0100 |
| commit | 1c58d6cfbc63ef3eb41d332c8aa443bb65ac4b4d (patch) | |
| tree | ad1aafa19ed74e0b550af8081fd7024b32596c83 | |
| parent | 51a028115446da42565fa75d4657e82c214afc2d (diff) | |
D3D12: BuildRaytracingAccelerationStructure writes XDXR BVH4 records
The game's translated RT shaders read the console's XDXR records, which a
VkAccelerationStructureKHR is not (docs/d3d12_vulkan.md 4.8). The standalone
Vulkan device now builds them with src/xdxr_build.h, unless LEONIDA_RT_AS=khr
keeps #743's KHR builds (the proposal in the maintainer decisions of #1548).
- VulkanDeviceInfo::xdxr_acceleration_structures; the standalone device sets
it with bufferDeviceAddress and then leaves the KHR extensions off, so
acceleration-structure buffers keep their console VAs.
- VulkanContext owns an XdxrBuilder; replay checks the inputs while the list
is prepared (R32G32B32/R32G32 vertices, none/R16/R32 indices, addresses,
counts) and records the build with heap_base added to every VA and as the
bias for instance BLAS addresses.
- GetRaytracingAccelerationStructurePrebuildInfo answers from XdxrLayout,
exactly; an update rebuilds, so it needs the same scratch.
- The geometry's vertex format is mapped per DXGI format (an unknown one is
refused instead of read as R32G32B32), and its D3D12 flags reach the build.
- test/d3d12_xdxr_rt_test.cpp: a two-geometry BLAS (a soup; an R16-indexed
grid with stride 16 and a transform) and a TLAS of three instances through
the D3D12 API; ctest d3d12_xdxr_rt + d3d12_xdxr_rt_check.
- tools/xdxr_bvh.py: check-build compares TLAS hits by (geometry, primitive),
and skips (77) when the build step wrote no cases.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
| -rw-r--r-- | docs/bvh.md | 4 | ||||
| -rw-r--r-- | docs/d3d12_vulkan.md | 9 | ||||
| -rw-r--r-- | runtime/CMakeLists.txt | 19 | ||||
| -rw-r--r-- | runtime/shims/d3d12_com.cpp | 15 | ||||
| -rw-r--r-- | runtime/shims/d3d12_com.h | 5 | ||||
| -rw-r--r-- | runtime/shims/d3d12_vulkan_device.cpp | 42 | ||||
| -rw-r--r-- | runtime/src/command_list.h | 1 | ||||
| -rw-r--r-- | runtime/src/vulkan_backend.h | 68 | ||||
| -rw-r--r-- | runtime/src/vulkan_replay.h | 24 | ||||
| -rw-r--r-- | runtime/test/d3d12_xdxr_rt_test.cpp | 306 | ||||
| -rw-r--r-- | tools/xdxr_bvh.py | 14 |
11 files changed, 487 insertions, 20 deletions
diff --git a/docs/bvh.md b/docs/bvh.md index 77834afd8..23e046221 100644 --- a/docs/bvh.md +++ b/docs/bvh.md | |||
| @@ -352,6 +352,10 @@ no BLAS and one with a singular transform. An instance record holds its BLAS add | |||
| 352 | so BLAS addresses must be below 2^40, as console GPU addresses are. Where device addresses are wider (llvmpipe's are | 352 | so BLAS addresses must be below 2^40, as console GPU addresses are. Where device addresses are wider (llvmpipe's are |
| 353 | host pointers), the builder takes a bias that is added to the addresses read from instance descs. | 353 | host pointers), the builder takes a bias that is added to the addresses read from instance descs. |
| 354 | 354 | ||
| 355 | The Vulkan layer uses it for `BuildRaytracingAccelerationStructure` unless `LEONIDA_RT_AS=khr` | ||
| 356 | (`docs/d3d12_vulkan.md` §4.8); `d3d12_xdxr_rt_test <dir>` builds a BLAS and a TLAS through the D3D12 API and writes | ||
| 357 | them the same way. | ||
| 358 | |||
| 355 | `vk_xdxr_build_test <dir>` builds nine synthetic cases on the GPU and writes each structure with a description of its | 359 | `vk_xdxr_build_test <dir>` builds nine synthetic cases on the GPU and writes each structure with a description of its |
| 356 | scene. `xdxr_bvh.py check-build <dir>` validates them and traces rays against brute force. `ctest` runs both as | 360 | scene. `xdxr_bvh.py check-build <dir>` validates them and traces rays against brute force. `ctest` runs both as |
| 357 | `xdxr_build` and `xdxr_build_check`. | 361 | `xdxr_build` and `xdxr_build_check`. |
diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 77fdf89bb..c12c93ab6 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md | |||
| @@ -1987,8 +1987,13 @@ Vulkan AS would be invisible to them. Two paths: | |||
| 1987 | and make `GetRaytracingAccelerationStructurePrebuildInfo` return sizes for that layout. | 1987 | and make `GetRaytracingAccelerationStructurePrebuildInfo` return sizes for that layout. |
| 1988 | The layout is the XDXR BVH4 runtime form ([bvh.md](bvh.md) §3.1). `tools/xdxr_bvh.py` encodes it on the | 1988 | The layout is the XDXR BVH4 runtime form ([bvh.md](bvh.md) §3.1). `tools/xdxr_bvh.py` encodes it on the |
| 1989 | CPU, with a reference traversal and a validator ([bvh.md](bvh.md) §7a). `runtime/src/xdxr_build.h` builds it on | 1989 | CPU, with a reference traversal and a validator ([bvh.md](bvh.md) §7a). `runtime/src/xdxr_build.h` builds it on |
| 1990 | the GPU and is checked against that reference. It is not yet wired to `BuildRaytracingAccelerationStructure`, which | 1990 | the GPU and is checked against that reference. The standalone device uses it for `BuildRaytracingAccelerationStructure` |
| 1991 | today builds a `VkAccelerationStructureKHR` (#743) that the game's shaders can't read. | 1991 | and answers `GetRaytracingAccelerationStructurePrebuildInfo` from its layout, exactly. Acceleration-structure |
| 1992 | buffers then keep their console VAs, the addresses the records name each other by. `LEONIDA_RT_AS=khr` keeps | ||
| 1993 | #743's `VkAccelerationStructureKHR` builds (for `RayQueryKHR`), which the game's shaders can't read. Updates rebuild | ||
| 1994 | the structure; compaction, copies, serialization and the Xbox batched/streaming builds are not implemented. The | ||
| 1995 | reported `RaytracingTier` is unchanged (`NOT_SUPPORTED`). Checked by `runtime/test/d3d12_xdxr_rt_test.cpp` through | ||
| 1996 | the D3D12 API. | ||
| 1992 | 1997 | ||
| 1993 | **Open:** which path the game uses. Resolve by logging the first call to the standard AS methods and by tracing the | 1998 | **Open:** which path the game uses. Resolve by logging the first call to the standard AS methods and by tracing the |
| 1994 | builder's command-list usage. If XDXR batched/streaming builds are used, their structs and compression formats need | 1999 | builder's command-list usage. If XDXR batched/streaming builds are used, their structs and compression formats need |
diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 1444bc355..5d1fa9a8d 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt | |||
| @@ -663,7 +663,7 @@ if(TARGET Vulkan::Headers) | |||
| 663 | if(Python3_FOUND) | 663 | if(Python3_FOUND) |
| 664 | add_test(NAME xdxr_build_check COMMAND "${Python3_EXECUTABLE}" -I | 664 | add_test(NAME xdxr_build_check COMMAND "${Python3_EXECUTABLE}" -I |
| 665 | "${CMAKE_CURRENT_SOURCE_DIR}/../tools/xdxr_bvh.py" check-build "${LEONIDA_XDXR_OUT}" --rays 1000) | 665 | "${CMAKE_CURRENT_SOURCE_DIR}/../tools/xdxr_bvh.py" check-build "${LEONIDA_XDXR_OUT}" --rays 1000) |
| 666 | set_tests_properties(xdxr_build_check PROPERTIES FIXTURES_REQUIRED xdxr_build_cases) | 666 | set_tests_properties(xdxr_build_check PROPERTIES FIXTURES_REQUIRED xdxr_build_cases SKIP_RETURN_CODE 77) |
| 667 | endif() | 667 | endif() |
| 668 | endif() | 668 | endif() |
| 669 | if(NOT Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) | 669 | if(NOT Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) |
| @@ -785,6 +785,23 @@ if(TARGET Vulkan::Headers) | |||
| 785 | add_test(NAME d3d12_queue_wait COMMAND d3d12_queue_wait_test) | 785 | add_test(NAME d3d12_queue_wait COMMAND d3d12_queue_wait_test) |
| 786 | set_tests_properties(d3d12_queue_wait PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 20) | 786 | set_tests_properties(d3d12_queue_wait PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 20) |
| 787 | 787 | ||
| 788 | # XDXR acceleration structures through BuildRaytracingAccelerationStructure (docs/d3d12_vulkan.md 4.8): the | ||
| 789 | # device builds them, tools/xdxr_bvh.py checks them. | ||
| 790 | add_executable(d3d12_xdxr_rt_test test/d3d12_xdxr_rt_test.cpp) | ||
| 791 | target_link_libraries(d3d12_xdxr_rt_test PRIVATE gta6rt_d3d12_com) | ||
| 792 | target_compile_definitions(d3d12_xdxr_rt_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) | ||
| 793 | target_compile_options(d3d12_xdxr_rt_test PRIVATE /W4 /permissive- /utf-8) | ||
| 794 | set(LEONIDA_D3D12_XDXR_OUT "${CMAKE_CURRENT_BINARY_DIR}/d3d12_xdxr_cases") | ||
| 795 | file(MAKE_DIRECTORY "${LEONIDA_D3D12_XDXR_OUT}") | ||
| 796 | add_test(NAME d3d12_xdxr_rt COMMAND d3d12_xdxr_rt_test "${LEONIDA_D3D12_XDXR_OUT}") | ||
| 797 | set_tests_properties(d3d12_xdxr_rt PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60 FIXTURES_SETUP d3d12_xdxr_cases) | ||
| 798 | find_package(Python3 COMPONENTS Interpreter QUIET) | ||
| 799 | if(Python3_FOUND) | ||
| 800 | add_test(NAME d3d12_xdxr_rt_check COMMAND "${Python3_EXECUTABLE}" -I | ||
| 801 | "${CMAKE_CURRENT_SOURCE_DIR}/../tools/xdxr_bvh.py" check-build "${LEONIDA_D3D12_XDXR_OUT}" --rays 1000) | ||
| 802 | set_tests_properties(d3d12_xdxr_rt_check PROPERTIES FIXTURES_REQUIRED d3d12_xdxr_cases SKIP_RETURN_CODE 77) | ||
| 803 | endif() | ||
| 804 | |||
| 788 | # GCL8's QueryInterface and its one method need an allocator and a list, not a Vulkan device. | 805 | # GCL8's QueryInterface and its one method need an allocator and a list, not a Vulkan device. |
| 789 | add_executable(d3d12_gcl8_test test/d3d12_gcl8_test.cpp) | 806 | add_executable(d3d12_gcl8_test test/d3d12_gcl8_test.cpp) |
| 790 | target_link_libraries(d3d12_gcl8_test PRIVATE gta6rt_d3d12_com) | 807 | target_link_libraries(d3d12_gcl8_test PRIVATE gta6rt_d3d12_com) |
diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 44740dd98..418053333 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp | |||
| @@ -603,9 +603,17 @@ public: | |||
| 603 | t.vertex_va = gd->Triangles.VertexBuffer.StartAddress; | 603 | t.vertex_va = gd->Triangles.VertexBuffer.StartAddress; |
| 604 | t.vertex_count = gd->Triangles.VertexCount; | 604 | t.vertex_count = gd->Triangles.VertexCount; |
| 605 | t.vertex_stride = static_cast<std::uint32_t>(gd->Triangles.VertexBuffer.StrideInBytes); | 605 | t.vertex_stride = static_cast<std::uint32_t>(gd->Triangles.VertexBuffer.StrideInBytes); |
| 606 | t.vertex_format = (gd->Triangles.VertexFormat == DXGI_FORMAT_R32G32_FLOAT) | 606 | // The vertex formats D3D12 allows for BLAS builds; any other stays VK_FORMAT_UNDEFINED and the |
| 607 | ? VK_FORMAT_R32G32_SFLOAT | 607 | // build is refused at replay instead of reading the wrong layout. |
| 608 | : VK_FORMAT_R32G32B32_SFLOAT; | 608 | switch (gd->Triangles.VertexFormat) { |
| 609 | case DXGI_FORMAT_R32G32B32_FLOAT: t.vertex_format = VK_FORMAT_R32G32B32_SFLOAT; break; | ||
| 610 | case DXGI_FORMAT_R32G32_FLOAT: t.vertex_format = VK_FORMAT_R32G32_SFLOAT; break; | ||
| 611 | case DXGI_FORMAT_R16G16B16A16_FLOAT: t.vertex_format = VK_FORMAT_R16G16B16A16_SFLOAT; break; | ||
| 612 | case DXGI_FORMAT_R16G16_FLOAT: t.vertex_format = VK_FORMAT_R16G16_SFLOAT; break; | ||
| 613 | case DXGI_FORMAT_R16G16B16A16_SNORM: t.vertex_format = VK_FORMAT_R16G16B16A16_SNORM; break; | ||
| 614 | case DXGI_FORMAT_R16G16_SNORM: t.vertex_format = VK_FORMAT_R16G16_SNORM; break; | ||
| 615 | default: t.vertex_format = VK_FORMAT_UNDEFINED; break; | ||
| 616 | } | ||
| 609 | t.index_va = gd->Triangles.IndexBuffer; | 617 | t.index_va = gd->Triangles.IndexBuffer; |
| 610 | t.index_count = gd->Triangles.IndexCount; | 618 | t.index_count = gd->Triangles.IndexCount; |
| 611 | if (gd->Triangles.IndexFormat == DXGI_FORMAT_R16_UINT) | 619 | if (gd->Triangles.IndexFormat == DXGI_FORMAT_R16_UINT) |
| @@ -614,6 +622,7 @@ public: | |||
| 614 | t.index_type = 2; | 622 | t.index_type = 2; |
| 615 | t.transform_va = gd->Triangles.Transform3x4; | 623 | t.transform_va = gd->Triangles.Transform3x4; |
| 616 | t.opaque = (gd->Flags & D3D12_RAYTRACING_GEOMETRY_FLAG_OPAQUE) != 0; | 624 | t.opaque = (gd->Flags & D3D12_RAYTRACING_GEOMETRY_FLAG_OPAQUE) != 0; |
| 625 | t.flags = static_cast<std::uint32_t>(gd->Flags); | ||
| 617 | cmd.triangles.push_back(t); | 626 | cmd.triangles.push_back(t); |
| 618 | } | 627 | } |
| 619 | } | 628 | } |
diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index 48ba11bc2..3908e83d2 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h | |||
| @@ -119,6 +119,11 @@ struct VulkanDeviceInfo { | |||
| 119 | // Optional VK_KHR_acceleration_structure + VK_KHR_deferred_host_operations + VK_KHR_ray_query are enabled: | 119 | // Optional VK_KHR_acceleration_structure + VK_KHR_deferred_host_operations + VK_KHR_ray_query are enabled: |
| 120 | // GetRaytracingAccelerationStructurePrebuildInfo and BuildRaytracingAccelerationStructure (BLAS + TLAS) work. | 120 | // GetRaytracingAccelerationStructurePrebuildInfo and BuildRaytracingAccelerationStructure (BLAS + TLAS) work. |
| 121 | bool ray_tracing = false; | 121 | bool ray_tracing = false; |
| 122 | // BuildRaytracingAccelerationStructure writes the console's XDXR BVH4 records into the destination buffer | ||
| 123 | // (src/xdxr_build.h), the layout the game's translated traversal shaders read, instead of building a | ||
| 124 | // VkAccelerationStructureKHR; needs buffer_device_address and the GPU address arena. The standalone device sets it | ||
| 125 | // unless LEONIDA_RT_AS=khr (docs/d3d12_vulkan.md 4.8); with it set, ray_tracing is not enabled. | ||
| 126 | bool xdxr_acceleration_structures = false; | ||
| 122 | // The core features enabled on `device`. Graphics PSOs that need independentBlend, fillModeNonSolid, | 127 | // The core features enabled on `device`. Graphics PSOs that need independentBlend, fillModeNonSolid, |
| 123 | // depthBiasClamp or dualSrcBlend are refused unless it is set here. | 128 | // depthBiasClamp or dualSrcBlend are refused unless it is set here. |
| 124 | VkPhysicalDeviceFeatures features{}; | 129 | VkPhysicalDeviceFeatures features{}; |
diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index d98e3d1dc..cb7fbe685 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp | |||
| @@ -2664,7 +2664,9 @@ public: | |||
| 2664 | 2664 | ||
| 2665 | state_.context = std::make_unique<leonida::VulkanContext>(get_device, info.device, | 2665 | state_.context = std::make_unique<leonida::VulkanContext>(get_device, info.device, |
| 2666 | info.separate_depth_stencil_layouts, | 2666 | info.separate_depth_stencil_layouts, |
| 2667 | info.conditional_rendering, info.ray_tracing); | 2667 | info.conditional_rendering, info.ray_tracing, |
| 2668 | info.xdxr_acceleration_structures && | ||
| 2669 | info.buffer_device_address); | ||
| 2668 | if (info.buffer_device_address && state_.context->loaded() && !create_arena()) | 2670 | if (info.buffer_device_address && state_.context->loaded() && !create_arena()) |
| 2669 | std::fprintf(stderr, "[rt] d3d12: the GPU address arena could not be created\n"); | 2671 | std::fprintf(stderr, "[rt] d3d12: the GPU address arena could not be created\n"); |
| 2670 | if (info.conditional_rendering) { | 2672 | if (info.conditional_rendering) { |
| @@ -3150,6 +3152,34 @@ public: | |||
| 3150 | if (!out) return; | 3152 | if (!out) return; |
| 3151 | *out = {}; | 3153 | *out = {}; |
| 3152 | auto& vk = state_.context->vk; | 3154 | auto& vk = state_.context->vk; |
| 3155 | if (desc && state_.context->xdxr_acceleration_structures()) { | ||
| 3156 | // XDXR records: the layout depends only on the triangle or instance count (xdxr_build.h), so the sizes | ||
| 3157 | // are exact. An update rebuilds the structure, so it needs the same scratch. | ||
| 3158 | leonida::BuildAccelerationStructure build{}; | ||
| 3159 | build.is_tlas = desc->Type == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL; | ||
| 3160 | if (build.is_tlas) { | ||
| 3161 | build.instance_count = desc->NumDescs; | ||
| 3162 | } else { | ||
| 3163 | for (UINT i = 0; i < desc->NumDescs; ++i) { | ||
| 3164 | const D3D12_RAYTRACING_GEOMETRY_DESC* gd = | ||
| 3165 | (desc->DescsLayout == D3D12_ELEMENTS_LAYOUT_ARRAY_OF_POINTERS) | ||
| 3166 | ? (desc->ppGeometryDescs ? desc->ppGeometryDescs[i] : nullptr) | ||
| 3167 | : (desc->pGeometryDescs ? &desc->pGeometryDescs[i] : nullptr); | ||
| 3168 | if (!gd || gd->Type != D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES) continue; | ||
| 3169 | leonida::RtTriangleGeometry t{}; | ||
| 3170 | t.vertex_count = gd->Triangles.VertexCount; | ||
| 3171 | t.index_count = gd->Triangles.IndexCount; | ||
| 3172 | t.index_type = gd->Triangles.IndexFormat == DXGI_FORMAT_UNKNOWN ? 0u : 1u; | ||
| 3173 | build.triangles.push_back(t); | ||
| 3174 | } | ||
| 3175 | } | ||
| 3176 | leonida::XdxrLayout layout; | ||
| 3177 | if (!layout.compute(leonida::VulkanContext::xdxr_elements(build), build.is_tlas)) return; | ||
| 3178 | out->ResultDataMaxSizeInBytes = layout.size; | ||
| 3179 | out->ScratchDataSizeInBytes = layout.scratch; | ||
| 3180 | out->UpdateScratchDataSizeInBytes = layout.scratch; | ||
| 3181 | return; | ||
| 3182 | } | ||
| 3153 | if (!desc || !state_.info.ray_tracing || !vk.vkGetAccelerationStructureBuildSizesKHR) return; | 3183 | if (!desc || !state_.info.ray_tracing || !vk.vkGetAccelerationStructureBuildSizesKHR) return; |
| 3154 | 3184 | ||
| 3155 | const bool is_tlas = (desc->Type == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL); | 3185 | const bool is_tlas = (desc->Type == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL); |
| @@ -5413,6 +5443,16 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) { | |||
| 5413 | vkGetPhysicalDeviceFeatures2(info.physical, &features); | 5443 | vkGetPhysicalDeviceFeatures2(info.physical, &features); |
| 5414 | info.ray_tracing = as_features.accelerationStructure == VK_TRUE && rq_features.rayQuery == VK_TRUE; | 5444 | info.ray_tracing = as_features.accelerationStructure == VK_TRUE && rq_features.rayQuery == VK_TRUE; |
| 5415 | } | 5445 | } |
| 5446 | // The game's translated RT shaders read XDXR BVH4 records, which a VkAccelerationStructureKHR is not | ||
| 5447 | // (docs/d3d12_vulkan.md 4.8): build those, unless LEONIDA_RT_AS=khr asks for #743's KHR builds instead. | ||
| 5448 | char rt_as[8] = {}; | ||
| 5449 | std::size_t rt_as_length = 0; | ||
| 5450 | const bool khr = getenv_s(&rt_as_length, rt_as, "LEONIDA_RT_AS") == 0 && rt_as_length > 1 && | ||
| 5451 | std::strcmp(rt_as, "khr") == 0; | ||
| 5452 | if (!khr && chosen12.bufferDeviceAddress) { | ||
| 5453 | info.xdxr_acceleration_structures = true; | ||
| 5454 | info.ray_tracing = false; // no KHR extensions: AS resources keep their console VAs | ||
| 5455 | } | ||
| 5416 | if (!info.conditional_rendering) | 5456 | if (!info.conditional_rendering) |
| 5417 | std::fprintf(stderr, "[rt] d3d12: the GPU has no VK_EXT_conditional_rendering: SetPredication is unsupported\n"); | 5457 | std::fprintf(stderr, "[rt] d3d12: the GPU has no VK_EXT_conditional_rendering: SetPredication is unsupported\n"); |
| 5418 | } | 5458 | } |
diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h index 5891e7533..3830608a2 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h | |||
| @@ -578,6 +578,7 @@ struct RtTriangleGeometry { | |||
| 578 | std::uint32_t index_type = 0; // 0=NONE, 1=UINT16, 2=UINT32 | 578 | std::uint32_t index_type = 0; // 0=NONE, 1=UINT16, 2=UINT32 |
| 579 | std::uint64_t transform_va = 0; | 579 | std::uint64_t transform_va = 0; |
| 580 | bool opaque = true; | 580 | bool opaque = true; |
| 581 | std::uint32_t flags = 0; // D3D12_RAYTRACING_GEOMETRY_FLAGS (bit 0 opaque, bit 1 no duplicate any-hit) | ||
| 581 | }; | 582 | }; |
| 582 | 583 | ||
| 583 | // BLAS or TLAS build command (VK_KHR_acceleration_structure). | 584 | // BLAS or TLAS build command (VK_KHR_acceleration_structure). |
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index 7006911c2..90adb7577 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h | |||
| @@ -14,6 +14,7 @@ | |||
| 14 | #include "vulkan_depth24.h" | 14 | #include "vulkan_depth24.h" |
| 15 | #include "vulkan_scratch.h" | 15 | #include "vulkan_scratch.h" |
| 16 | #include "vulkan_replay.h" | 16 | #include "vulkan_replay.h" |
| 17 | #include "xdxr_build.h" | ||
| 17 | 18 | ||
| 18 | #include <algorithm> | 19 | #include <algorithm> |
| 19 | #include <atomic> | 20 | #include <atomic> |
| @@ -646,8 +647,9 @@ class VulkanContext { | |||
| 646 | public: | 647 | public: |
| 647 | // conditional_rendering: VK_EXT_conditional_rendering is enabled on `device` (SetPredication). | 648 | // conditional_rendering: VK_EXT_conditional_rendering is enabled on `device` (SetPredication). |
| 648 | // ray_tracing: VK_KHR_acceleration_structure + VK_KHR_ray_query are enabled on `device`. | 649 | // ray_tracing: VK_KHR_acceleration_structure + VK_KHR_ray_query are enabled on `device`. |
| 650 | // xdxr: acceleration-structure builds write XDXR BVH4 records (xdxr_build.h) instead; needs bufferDeviceAddress. | ||
| 649 | VulkanContext(PFN_vkGetDeviceProcAddr get, VkDevice device, bool separate_depth_stencil_layouts, | 651 | VulkanContext(PFN_vkGetDeviceProcAddr get, VkDevice device, bool separate_depth_stencil_layouts, |
| 650 | bool conditional_rendering = false, bool ray_tracing = false) | 652 | bool conditional_rendering = false, bool ray_tracing = false, bool xdxr = false) |
| 651 | : device_(device), tracker_(separate_depth_stencil_layouts), ray_tracing_(ray_tracing) { | 653 | : device_(device), tracker_(separate_depth_stencil_layouts), ray_tracing_(ray_tracing) { |
| 652 | loaded_ = vk.load(get, device); | 654 | loaded_ = vk.load(get, device); |
| 653 | replay_.pipeline_barrier = vk.vkCmdPipelineBarrier; | 655 | replay_.pipeline_barrier = vk.vkCmdPipelineBarrier; |
| @@ -711,7 +713,34 @@ public: | |||
| 711 | } | 713 | } |
| 712 | return false; | 714 | return false; |
| 713 | }; | 715 | }; |
| 714 | if (ray_tracing_ && vk.vkCmdBuildAccelerationStructuresKHR) { | 716 | if (xdxr && loaded_) { |
| 717 | xdxr_ = std::make_unique<XdxrBuilder>(get, device); | ||
| 718 | if (xdxr_->loaded()) { | ||
| 719 | replay_.xdxr_check = [](const BuildAccelerationStructure& b) { | ||
| 720 | XdxrLayout layout; | ||
| 721 | return xdxr_inputs(b, nullptr, 0) && layout.compute(xdxr_elements(b), b.is_tlas) && b.dst_va && | ||
| 722 | b.scratch_va && (!b.is_tlas || !b.instance_count || b.instances_va); | ||
| 723 | }; | ||
| 724 | replay_.xdxr_record = [this](VkCommandBuffer cb, const BuildAccelerationStructure& b) { | ||
| 725 | // Every address is a console VA in the GPU address arena: the device address is heap_base + VA, | ||
| 726 | // and the BLAS addresses in instance descs get the same bias. | ||
| 727 | const std::uint64_t base = replay_.heap_base; | ||
| 728 | XdxrLayout layout; | ||
| 729 | layout.compute(xdxr_elements(b), b.is_tlas); | ||
| 730 | if (b.is_tlas) { | ||
| 731 | xdxr_->record_tlas(cb, layout, b.instances_va ? base + b.instances_va : 0, base + b.dst_va, | ||
| 732 | base + b.scratch_va, base); | ||
| 733 | } else { | ||
| 734 | std::vector<XdxrTriangles> geometries; | ||
| 735 | xdxr_inputs(b, &geometries, base); | ||
| 736 | xdxr_->record_blas(cb, layout, geometries, base + b.dst_va, base + b.scratch_va); | ||
| 737 | } | ||
| 738 | }; | ||
| 739 | } else { | ||
| 740 | xdxr_.reset(); | ||
| 741 | } | ||
| 742 | } | ||
| 743 | if (!xdxr_ && ray_tracing_ && vk.vkCmdBuildAccelerationStructuresKHR) { | ||
| 715 | replay_.build_acceleration_structures = vk.vkCmdBuildAccelerationStructuresKHR; | 744 | replay_.build_acceleration_structures = vk.vkCmdBuildAccelerationStructuresKHR; |
| 716 | replay_.resolve_acceleration_structure = [this](std::uint64_t va) { | 745 | replay_.resolve_acceleration_structure = [this](std::uint64_t va) { |
| 717 | const auto it = acceleration_structures_.find(va); | 746 | const auto it = acceleration_structures_.find(va); |
| @@ -883,6 +912,40 @@ public: | |||
| 883 | } | 912 | } |
| 884 | 913 | ||
| 885 | bool ray_tracing_supported() const { return ray_tracing_ && vk.vkCmdBuildAccelerationStructuresKHR != nullptr; } | 914 | bool ray_tracing_supported() const { return ray_tracing_ && vk.vkCmdBuildAccelerationStructuresKHR != nullptr; } |
| 915 | bool xdxr_acceleration_structures() const { return xdxr_ != nullptr; } | ||
| 916 | |||
| 917 | // Triangles (BLAS) or instances (TLAS) a build has: what XdxrLayout is computed from, for the build and for | ||
| 918 | // GetRaytracingAccelerationStructurePrebuildInfo. | ||
| 919 | static std::uint32_t xdxr_elements(const BuildAccelerationStructure& b) { | ||
| 920 | if (b.is_tlas) return b.instance_count; | ||
| 921 | std::uint64_t n = 0; | ||
| 922 | for (const auto& t : b.triangles) n += (t.index_type ? t.index_count : t.vertex_count) / 3; | ||
| 923 | return n > 0xffffffffu ? 0xffffffffu : std::uint32_t(n); | ||
| 924 | } | ||
| 925 | // The geometries as the builder reads them, with `base` added to their VAs; false for an input it cannot read | ||
| 926 | // (a vertex format other than R32G32B32_FLOAT or R32G32_FLOAT, an index type other than none/R16/R32). | ||
| 927 | static bool xdxr_inputs(const BuildAccelerationStructure& b, std::vector<XdxrTriangles>* out, std::uint64_t base) { | ||
| 928 | if (b.is_tlas) return true; | ||
| 929 | for (const auto& t : b.triangles) { | ||
| 930 | if (t.vertex_format != VK_FORMAT_R32G32B32_SFLOAT && t.vertex_format != VK_FORMAT_R32G32_SFLOAT) return false; | ||
| 931 | if (t.index_type > 2) return false; | ||
| 932 | const std::uint32_t count = (t.index_type ? t.index_count : t.vertex_count) / 3; | ||
| 933 | if (count && !t.vertex_va) return false; | ||
| 934 | if (count && t.index_type && !t.index_va) return false; | ||
| 935 | if (!out) continue; | ||
| 936 | XdxrTriangles g; | ||
| 937 | g.vertices = t.vertex_va ? base + t.vertex_va : 0; | ||
| 938 | g.vertex_stride = t.vertex_stride; | ||
| 939 | g.xy_only = t.vertex_format == VK_FORMAT_R32G32_SFLOAT; | ||
| 940 | g.indices = t.index_type && t.index_va ? base + t.index_va : 0; | ||
| 941 | g.index_type = t.index_type; | ||
| 942 | g.triangle_count = count; | ||
| 943 | g.transform = t.transform_va ? base + t.transform_va : 0; | ||
| 944 | g.flags = t.flags | (t.opaque ? 1u : 0u); | ||
| 945 | out->push_back(g); | ||
| 946 | } | ||
| 947 | return true; | ||
| 948 | } | ||
| 886 | 949 | ||
| 887 | void register_acceleration_structure(std::uint64_t va, VkAccelerationStructureKHR as) { | 950 | void register_acceleration_structure(std::uint64_t va, VkAccelerationStructureKHR as) { |
| 888 | if (!va || !as) return; | 951 | if (!va || !as) return; |
| @@ -1031,6 +1094,7 @@ private: | |||
| 1031 | VkDevice device_; | 1094 | VkDevice device_; |
| 1032 | bool loaded_ = false; | 1095 | bool loaded_ = false; |
| 1033 | bool ray_tracing_ = false; | 1096 | bool ray_tracing_ = false; |
| 1097 | std::unique_ptr<XdxrBuilder> xdxr_; // set: acceleration structures are XDXR BVH4 records | ||
| 1034 | std::atomic<bool> device_lost_{false}; | 1098 | std::atomic<bool> device_lost_{false}; |
| 1035 | alignas(64) std::shared_mutex resource_mutex_; // shared for prepare lookups, unique for add/remove | 1099 | alignas(64) std::shared_mutex resource_mutex_; // shared for prepare lookups, unique for add/remove |
| 1036 | alignas(64) std::mutex tracker_mutex_; | 1100 | alignas(64) std::mutex tracker_mutex_; |
diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index ca27b1063..fb2e9334b 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h | |||
| @@ -779,6 +779,10 @@ struct ReplayFunctions { | |||
| 779 | PFN_vkCmdDispatchIndirect dispatch_indirect = nullptr; | 779 | PFN_vkCmdDispatchIndirect dispatch_indirect = nullptr; |
| 780 | // Optional VK_KHR_acceleration_structure: BuildRaytracingAccelerationStructure. | 780 | // Optional VK_KHR_acceleration_structure: BuildRaytracingAccelerationStructure. |
| 781 | PFN_vkCmdBuildAccelerationStructuresKHR build_acceleration_structures = nullptr; | 781 | PFN_vkCmdBuildAccelerationStructuresKHR build_acceleration_structures = nullptr; |
| 782 | // XDXR BVH4 builds (xdxr_build.h), used instead of the KHR ones when set: `xdxr_check` refuses inputs the builder | ||
| 783 | // cannot read while the list is prepared, `xdxr_record` records the build. | ||
| 784 | std::function<bool(const BuildAccelerationStructure&)> xdxr_check; | ||
| 785 | std::function<void(VkCommandBuffer, const BuildAccelerationStructure&)> xdxr_record; | ||
| 782 | std::function<VkAccelerationStructureKHR(std::uint64_t)> resolve_acceleration_structure; | 786 | std::function<VkAccelerationStructureKHR(std::uint64_t)> resolve_acceleration_structure; |
| 783 | // Preparation only allocates a slot; capture records the GPU snapshot at the SetPredication command. | 787 | // Preparation only allocates a slot; capture records the GPU snapshot at the SetPredication command. |
| 784 | std::function<bool(VkBuffer, VkDeviceSize, PredicateCapture&)> prepare_predicate; | 788 | std::function<bool(VkBuffer, VkDeviceSize, PredicateCapture&)> prepare_predicate; |
| @@ -2203,13 +2207,17 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 2203 | return ReplayResult::unsupported; | 2207 | return ReplayResult::unsupported; |
| 2204 | } | 2208 | } |
| 2205 | } else if (const auto* build = std::get_if<BuildAccelerationStructure>(&command)) { | 2209 | } else if (const auto* build = std::get_if<BuildAccelerationStructure>(&command)) { |
| 2206 | if (!vk.build_acceleration_structures || !vk.resolve_acceleration_structure) | 2210 | if (vk.xdxr_check) { |
| 2207 | return ReplayResult::unsupported; | 2211 | if (!vk.xdxr_check(*build)) return ReplayResult::unsupported; |
| 2208 | p.accel_dst = vk.resolve_acceleration_structure(build->dst_va); | 2212 | } else { |
| 2209 | if (!p.accel_dst) return ReplayResult::unresolved_resource; | 2213 | if (!vk.build_acceleration_structures || !vk.resolve_acceleration_structure) |
| 2210 | if (build->update && build->src_va) { | 2214 | return ReplayResult::unsupported; |
| 2211 | p.accel_src = vk.resolve_acceleration_structure(build->src_va); | 2215 | p.accel_dst = vk.resolve_acceleration_structure(build->dst_va); |
| 2212 | if (!p.accel_src) return ReplayResult::unresolved_resource; | 2216 | if (!p.accel_dst) return ReplayResult::unresolved_resource; |
| 2217 | if (build->update && build->src_va) { | ||
| 2218 | p.accel_src = vk.resolve_acceleration_structure(build->src_va); | ||
| 2219 | if (!p.accel_src) return ReplayResult::unresolved_resource; | ||
| 2220 | } | ||
| 2213 | } | 2221 | } |
| 2214 | } else if (const auto* dispatch = std::get_if<Dispatch>(&command)) { | 2222 | } else if (const auto* dispatch = std::get_if<Dispatch>(&command)) { |
| 2215 | if (!vk.bind_pipeline || !vk.push_constants || !vk.dispatch || !vk.compute_pipeline) | 2223 | if (!vk.bind_pipeline || !vk.push_constants || !vk.dispatch || !vk.compute_pipeline) |
| @@ -2924,6 +2932,8 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 2924 | } | 2932 | } |
| 2925 | } | 2933 | } |
| 2926 | } | 2934 | } |
| 2935 | } else if (const auto* build = std::get_if<BuildAccelerationStructure>(&command); build && vk.xdxr_record) { | ||
| 2936 | vk.xdxr_record(command_buffer, *build); | ||
| 2927 | } else if (const auto* build = std::get_if<BuildAccelerationStructure>(&command)) { | 2937 | } else if (const auto* build = std::get_if<BuildAccelerationStructure>(&command)) { |
| 2928 | // The build's addresses are console VAs into the GPU address arena (heap_base is its device address). | 2938 | // The build's addresses are console VAs into the GPU address arena (heap_base is its device address). |
| 2929 | // A null VA (no index buffer, no transform) stays null: heap_base + 0 would name the arena's zero page. | 2939 | // A null VA (no index buffer, no transform) stays null: heap_base + 0 would name the arena's zero page. |
diff --git a/runtime/test/d3d12_xdxr_rt_test.cpp b/runtime/test/d3d12_xdxr_rt_test.cpp new file mode 100644 index 000000000..9499dbe0d --- /dev/null +++ b/runtime/test/d3d12_xdxr_rt_test.cpp | |||
| @@ -0,0 +1,306 @@ | |||
| 1 | // BuildRaytracingAccelerationStructure on the standalone Vulkan device writes XDXR BVH4 records (docs/d3d12_vulkan.md | ||
| 2 | // 4.8, src/xdxr_build.h), the layout the game's translated traversal shaders read. A BLAS of two geometries (an | ||
| 3 | // unindexed triangle soup, and an R16-indexed grid with a 16-byte stride and a 3x4 transform) and a TLAS of three | ||
| 4 | // instances are built through the D3D12 API, sized by GetRaytracingAccelerationStructurePrebuildInfo, copied to | ||
| 5 | // readback buffers and written to <out dir> as <case>.bin + <case>.json at their console GPU virtual addresses. | ||
| 6 | // `python -I tools/xdxr_bvh.py check-build <out dir>` validates them and traces rays against brute force (ctest: | ||
| 7 | // d3d12_xdxr_rt + d3d12_xdxr_rt_check). Exit 77 without a Vulkan device, or with LEONIDA_RT_AS=khr. No game files. | ||
| 8 | #include "../shims/d3d12_com.h" | ||
| 9 | |||
| 10 | #include <cmath> | ||
| 11 | #include <cstdint> | ||
| 12 | #include <cstdio> | ||
| 13 | #include <cstring> | ||
| 14 | #include <filesystem> | ||
| 15 | #include <fstream> | ||
| 16 | #include <random> | ||
| 17 | #include <string> | ||
| 18 | #include <vector> | ||
| 19 | |||
| 20 | namespace { | ||
| 21 | |||
| 22 | template<class T> struct Ref { | ||
| 23 | T* p = nullptr; | ||
| 24 | ~Ref() { if (p) p->Release(); } | ||
| 25 | T* operator->() const { return p; } | ||
| 26 | T** put() { return &p; } | ||
| 27 | }; | ||
| 28 | |||
| 29 | int fail(const char* what, HRESULT hr = S_OK) { | ||
| 30 | std::fprintf(stderr, "FAIL: %s (hr 0x%08lx)\n", what, static_cast<unsigned long>(hr)); | ||
| 31 | return 1; | ||
| 32 | } | ||
| 33 | |||
| 34 | HRESULT buffer(ID3D12Device* device, D3D12_HEAP_TYPE heap, UINT64 size, D3D12_RESOURCE_STATES state, | ||
| 35 | D3D12_RESOURCE_FLAGS flags, ID3D12Resource** out) { | ||
| 36 | D3D12_HEAP_PROPERTIES props{}; | ||
| 37 | props.Type = heap; | ||
| 38 | D3D12_RESOURCE_DESC desc{}; | ||
| 39 | desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; | ||
| 40 | desc.Width = size ? size : 1; | ||
| 41 | desc.Height = 1; | ||
| 42 | desc.DepthOrArraySize = 1; | ||
| 43 | desc.MipLevels = 1; | ||
| 44 | desc.SampleDesc.Count = 1; | ||
| 45 | desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; | ||
| 46 | desc.Flags = flags; | ||
| 47 | return device->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, IID_PPV_ARGS(out)); | ||
| 48 | } | ||
| 49 | |||
| 50 | std::string num(double x) { | ||
| 51 | char s[64]; | ||
| 52 | std::snprintf(s, sizeof s, "%.9g", x); | ||
| 53 | return s; | ||
| 54 | } | ||
| 55 | |||
| 56 | bool write_file(const std::string& path, const void* data, std::size_t bytes) { | ||
| 57 | std::ofstream f(path, std::ios::binary); | ||
| 58 | f.write(static_cast<const char*>(data), std::streamsize(bytes)); | ||
| 59 | return bool(f); | ||
| 60 | } | ||
| 61 | |||
| 62 | } // namespace | ||
| 63 | |||
| 64 | int main(int argc, char** argv) { | ||
| 65 | if (argc < 2) { | ||
| 66 | std::fprintf(stderr, "usage: d3d12_xdxr_rt_test <out dir>\n"); | ||
| 67 | return 2; | ||
| 68 | } | ||
| 69 | const std::string dir = argv[1]; | ||
| 70 | std::error_code ec; | ||
| 71 | for (const auto& entry : std::filesystem::directory_iterator(dir, ec)) { | ||
| 72 | const auto ext = entry.path().extension(); | ||
| 73 | if (ext == ".bin" || ext == ".json") std::filesystem::remove(entry.path(), ec); | ||
| 74 | } | ||
| 75 | |||
| 76 | // LEONIDA_RT_AS=khr builds #743's VkAccelerationStructureKHR instead, whose bytes are the driver's own. | ||
| 77 | char rt_as[8] = {}; | ||
| 78 | std::size_t rt_as_length = 0; | ||
| 79 | if (getenv_s(&rt_as_length, rt_as, "LEONIDA_RT_AS") == 0 && rt_as_length > 1 && std::strcmp(rt_as, "khr") == 0) { | ||
| 80 | std::puts("SKIP: LEONIDA_RT_AS=khr"); | ||
| 81 | return 77; | ||
| 82 | } | ||
| 83 | Ref<ID3D12Device5> device; | ||
| 84 | if (FAILED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(device.put())))) { | ||
| 85 | std::puts("SKIP: no Vulkan D3D12 device"); | ||
| 86 | return 77; | ||
| 87 | } | ||
| 88 | |||
| 89 | // ---- geometry: a triangle soup, and an R16-indexed grid (stride 16) with a transform ---- | ||
| 90 | std::mt19937 rng(11); | ||
| 91 | std::uniform_real_distribution<float> spread(-4.0f, 4.0f), jitter(-0.6f, 0.6f); | ||
| 92 | const UINT soup_tris = 300; | ||
| 93 | std::vector<float> soup; | ||
| 94 | for (UINT t = 0; t < soup_tris; ++t) { | ||
| 95 | const float c[3] = {spread(rng), spread(rng), spread(rng)}; | ||
| 96 | for (int k = 0; k < 9; ++k) soup.push_back(c[k % 3] + jitter(rng)); | ||
| 97 | } | ||
| 98 | const UINT n = 8; | ||
| 99 | std::vector<float> grid; | ||
| 100 | for (UINT j = 0; j <= n; ++j) | ||
| 101 | for (UINT i = 0; i <= n; ++i) { | ||
| 102 | grid.push_back(float(i) - n * 0.5f); | ||
| 103 | grid.push_back(float(j) - n * 0.5f); | ||
| 104 | grid.push_back(0.25f * float((i * 7 + j * 3) % 5)); | ||
| 105 | grid.push_back(9.0f); // padding: the stride is 16 | ||
| 106 | } | ||
| 107 | std::vector<std::uint16_t> indices; | ||
| 108 | for (UINT j = 0; j < n; ++j) | ||
| 109 | for (UINT i = 0; i < n; ++i) { | ||
| 110 | const std::uint16_t a = std::uint16_t(j * (n + 1) + i); | ||
| 111 | const std::uint16_t q[6] = {a, std::uint16_t(a + 1), std::uint16_t(a + n + 2), a, std::uint16_t(a + n + 2), | ||
| 112 | std::uint16_t(a + n + 1)}; | ||
| 113 | indices.insert(indices.end(), q, q + 6); | ||
| 114 | } | ||
| 115 | const float transform[12] = {0, 2, 0, 1, 0, 0, 1, -2, 2, 0, 0, 3}; // exact in float | ||
| 116 | |||
| 117 | const UINT64 soup_bytes = soup.size() * 4, grid_bytes = grid.size() * 4, index_bytes = indices.size() * 2; | ||
| 118 | const UINT64 upload_size = 256 + soup_bytes + grid_bytes + index_bytes + 64 + 3 * 64; | ||
| 119 | Ref<ID3D12Resource> upload; | ||
| 120 | HRESULT hr = buffer(device.p, D3D12_HEAP_TYPE_UPLOAD, upload_size, D3D12_RESOURCE_STATE_GENERIC_READ, | ||
| 121 | D3D12_RESOURCE_FLAG_NONE, upload.put()); | ||
| 122 | if (FAILED(hr)) return fail("upload buffer", hr); | ||
| 123 | char* mapped = nullptr; | ||
| 124 | if (FAILED(upload->Map(0, nullptr, reinterpret_cast<void**>(&mapped)))) return fail("Map upload"); | ||
| 125 | UINT64 at = 0; | ||
| 126 | auto place = [&](const void* data, UINT64 bytes, UINT64 align) { | ||
| 127 | at = (at + align - 1) / align * align; | ||
| 128 | std::memcpy(mapped + at, data, std::size_t(bytes)); | ||
| 129 | const UINT64 va = upload->GetGPUVirtualAddress() + at; | ||
| 130 | at += bytes; | ||
| 131 | return va; | ||
| 132 | }; | ||
| 133 | const UINT64 soup_va = place(soup.data(), soup_bytes, 16); | ||
| 134 | const UINT64 grid_va = place(grid.data(), grid_bytes, 16); | ||
| 135 | const UINT64 index_va = place(indices.data(), index_bytes, 16); | ||
| 136 | const UINT64 transform_va = place(transform, sizeof transform, 16); | ||
| 137 | |||
| 138 | D3D12_RAYTRACING_GEOMETRY_DESC geometries[2]{}; | ||
| 139 | geometries[0].Type = D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES; | ||
| 140 | geometries[0].Flags = D3D12_RAYTRACING_GEOMETRY_FLAG_OPAQUE; | ||
| 141 | geometries[0].Triangles.VertexFormat = DXGI_FORMAT_R32G32B32_FLOAT; | ||
| 142 | geometries[0].Triangles.VertexCount = soup_tris * 3; | ||
| 143 | geometries[0].Triangles.VertexBuffer = {soup_va, 12}; | ||
| 144 | geometries[1].Type = D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES; | ||
| 145 | geometries[1].Flags = D3D12_RAYTRACING_GEOMETRY_FLAG_OPAQUE; | ||
| 146 | geometries[1].Triangles.VertexFormat = DXGI_FORMAT_R32G32B32_FLOAT; | ||
| 147 | geometries[1].Triangles.VertexCount = (n + 1) * (n + 1); | ||
| 148 | geometries[1].Triangles.VertexBuffer = {grid_va, 16}; | ||
| 149 | geometries[1].Triangles.IndexFormat = DXGI_FORMAT_R16_UINT; | ||
| 150 | geometries[1].Triangles.IndexCount = UINT(indices.size()); | ||
| 151 | geometries[1].Triangles.IndexBuffer = index_va; | ||
| 152 | geometries[1].Triangles.Transform3x4 = transform_va; | ||
| 153 | |||
| 154 | D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS blas_inputs{}; | ||
| 155 | blas_inputs.Type = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL; | ||
| 156 | blas_inputs.DescsLayout = D3D12_ELEMENTS_LAYOUT_ARRAY; | ||
| 157 | blas_inputs.NumDescs = 2; | ||
| 158 | blas_inputs.pGeometryDescs = geometries; | ||
| 159 | D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO blas_info{}; | ||
| 160 | device->GetRaytracingAccelerationStructurePrebuildInfo(&blas_inputs, &blas_info); | ||
| 161 | if (!blas_info.ResultDataMaxSizeInBytes) { | ||
| 162 | std::puts("SKIP: the device does not build XDXR acceleration structures (no bufferDeviceAddress)"); | ||
| 163 | return 77; | ||
| 164 | } | ||
| 165 | |||
| 166 | D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS tlas_inputs{}; | ||
| 167 | tlas_inputs.Type = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL; | ||
| 168 | tlas_inputs.DescsLayout = D3D12_ELEMENTS_LAYOUT_ARRAY; | ||
| 169 | tlas_inputs.NumDescs = 3; | ||
| 170 | D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO tlas_info{}; | ||
| 171 | device->GetRaytracingAccelerationStructurePrebuildInfo(&tlas_inputs, &tlas_info); | ||
| 172 | if (!tlas_info.ResultDataMaxSizeInBytes) return fail("TLAS prebuild info is empty"); | ||
| 173 | |||
| 174 | const D3D12_RESOURCE_FLAGS uav = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; | ||
| 175 | const D3D12_RESOURCE_STATES as_state = D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE; | ||
| 176 | Ref<ID3D12Resource> blas, tlas, scratch, blas_rb, tlas_rb; | ||
| 177 | const UINT64 scratch_size = blas_info.ScratchDataSizeInBytes > tlas_info.ScratchDataSizeInBytes | ||
| 178 | ? blas_info.ScratchDataSizeInBytes : tlas_info.ScratchDataSizeInBytes; | ||
| 179 | if (FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, blas_info.ResultDataMaxSizeInBytes, as_state, uav, blas.put())) || | ||
| 180 | FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, tlas_info.ResultDataMaxSizeInBytes, as_state, uav, tlas.put())) || | ||
| 181 | FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, scratch_size, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, uav, | ||
| 182 | scratch.put())) || | ||
| 183 | FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_READBACK, blas_info.ResultDataMaxSizeInBytes, | ||
| 184 | D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE, blas_rb.put())) || | ||
| 185 | FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_READBACK, tlas_info.ResultDataMaxSizeInBytes, | ||
| 186 | D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE, tlas_rb.put()))) | ||
| 187 | return fail("acceleration-structure buffers", hr); | ||
| 188 | if (blas->GetGPUVirtualAddress() % 256 || tlas->GetGPUVirtualAddress() % 256) | ||
| 189 | return fail("acceleration structures must be 256-byte aligned"); | ||
| 190 | |||
| 191 | // ---- instances: identity, rotated + translated, and masked out ---- | ||
| 192 | const float c = std::cos(0.7f), s = std::sin(0.7f); | ||
| 193 | const float xforms[3][12] = {{1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0}, | ||
| 194 | {c, -s, 0, 9, s, c, 0, -1, 0, 0, 1, 0.5f}, | ||
| 195 | {2, 0, 0, -9, 0, 0.5f, 0, 2, 0, 0, 1.5f, 1}}; | ||
| 196 | const UINT masks[3] = {0xff, 0x01, 0x00}; | ||
| 197 | D3D12_RAYTRACING_INSTANCE_DESC instances[3]{}; | ||
| 198 | for (int i = 0; i < 3; ++i) { | ||
| 199 | std::memcpy(instances[i].Transform, xforms[i], sizeof xforms[i]); | ||
| 200 | instances[i].InstanceID = 20 + i; | ||
| 201 | instances[i].InstanceMask = masks[i]; | ||
| 202 | instances[i].AccelerationStructure = blas->GetGPUVirtualAddress(); | ||
| 203 | } | ||
| 204 | const UINT64 instances_va = place(instances, sizeof instances, 16); | ||
| 205 | upload->Unmap(0, nullptr); | ||
| 206 | tlas_inputs.InstanceDescs = instances_va; | ||
| 207 | |||
| 208 | // ---- record: BLAS, barrier, TLAS, barrier, copies to readback ---- | ||
| 209 | D3D12_COMMAND_QUEUE_DESC qd{}; | ||
| 210 | qd.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; | ||
| 211 | Ref<ID3D12CommandQueue> queue; | ||
| 212 | Ref<ID3D12CommandAllocator> allocator; | ||
| 213 | Ref<ID3D12GraphicsCommandList4> list; | ||
| 214 | Ref<ID3D12Fence> fence; | ||
| 215 | if (FAILED(device->CreateCommandQueue(&qd, IID_PPV_ARGS(queue.put()))) || | ||
| 216 | FAILED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(allocator.put()))) || | ||
| 217 | FAILED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, | ||
| 218 | IID_PPV_ARGS(list.put()))) || | ||
| 219 | FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(fence.put())))) | ||
| 220 | return fail("queue, allocator, list or fence"); | ||
| 221 | D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC build{}; | ||
| 222 | build.Inputs = blas_inputs; | ||
| 223 | build.DestAccelerationStructureData = blas->GetGPUVirtualAddress(); | ||
| 224 | build.ScratchAccelerationStructureData = scratch->GetGPUVirtualAddress(); | ||
| 225 | list->BuildRaytracingAccelerationStructure(&build, 0, nullptr); | ||
| 226 | D3D12_RESOURCE_BARRIER barrier{}; | ||
| 227 | barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; | ||
| 228 | barrier.UAV.pResource = nullptr; // every UAV: the BLAS and the scratch | ||
| 229 | list->ResourceBarrier(1, &barrier); | ||
| 230 | build.Inputs = tlas_inputs; | ||
| 231 | build.DestAccelerationStructureData = tlas->GetGPUVirtualAddress(); | ||
| 232 | list->BuildRaytracingAccelerationStructure(&build, 0, nullptr); | ||
| 233 | list->ResourceBarrier(1, &barrier); | ||
| 234 | // The layer keeps buffers in one memory, so a copy out of an acceleration structure reads its bytes as they are | ||
| 235 | // (D3D12 itself only allows CopyRaytracingAccelerationStructure; this is a test of the layer's records). | ||
| 236 | list->CopyBufferRegion(blas_rb.p, 0, blas.p, 0, blas_info.ResultDataMaxSizeInBytes); | ||
| 237 | list->CopyBufferRegion(tlas_rb.p, 0, tlas.p, 0, tlas_info.ResultDataMaxSizeInBytes); | ||
| 238 | if (FAILED(hr = list->Close())) return fail("Close", hr); | ||
| 239 | ID3D12CommandList* lists[] = {list.p}; | ||
| 240 | queue->ExecuteCommandLists(1, lists); | ||
| 241 | if (FAILED(queue->Signal(fence.p, 1))) return fail("Signal"); | ||
| 242 | HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); | ||
| 243 | const bool done = event && SUCCEEDED(fence->SetEventOnCompletion(1, event)) && | ||
| 244 | WaitForSingleObject(event, 10000) == WAIT_OBJECT_0; | ||
| 245 | if (event) CloseHandle(event); | ||
| 246 | if (!done) return fail("the builds did not complete"); | ||
| 247 | if (FAILED(device->GetDeviceRemovedReason())) return fail("device removed", device->GetDeviceRemovedReason()); | ||
| 248 | |||
| 249 | // ---- dump ---- | ||
| 250 | auto dump = [&](ID3D12Resource* rb, UINT64 size, const std::string& name, const std::string& json) { | ||
| 251 | void* p = nullptr; | ||
| 252 | if (FAILED(rb->Map(0, nullptr, &p))) return false; | ||
| 253 | std::uint32_t units = 0; | ||
| 254 | std::memcpy(&units, static_cast<char*>(p) + 4, 4); // header totalSizeIn64BNodes | ||
| 255 | const UINT64 used = UINT64(units) * 64; | ||
| 256 | const bool ok = used && used <= size && write_file(dir + "/" + name + ".bin", p, std::size_t(used)) && | ||
| 257 | write_file(dir + "/" + name + ".json", json.data(), json.size()); | ||
| 258 | rb->Unmap(0, nullptr); | ||
| 259 | return ok; | ||
| 260 | }; | ||
| 261 | std::string tris = "["; | ||
| 262 | bool first = true; | ||
| 263 | auto add_tri = [&](const float v[3][3], int geometry, UINT primitive) { | ||
| 264 | tris += first ? "\n [" : ",\n ["; | ||
| 265 | first = false; | ||
| 266 | for (int k = 0; k < 3; ++k) | ||
| 267 | tris += (k ? ", [" : "[") + num(v[k][0]) + ", " + num(v[k][1]) + ", " + num(v[k][2]) + "]"; | ||
| 268 | tris += ", " + std::to_string(geometry) + ", " + std::to_string(primitive) + "]"; | ||
| 269 | }; | ||
| 270 | for (UINT t = 0; t < soup_tris; ++t) { | ||
| 271 | float v[3][3]; | ||
| 272 | for (int k = 0; k < 9; ++k) v[k / 3][k % 3] = soup[9 * t + k]; | ||
| 273 | add_tri(v, 0, t); | ||
| 274 | } | ||
| 275 | for (UINT t = 0; t < indices.size() / 3; ++t) { | ||
| 276 | float v[3][3]; | ||
| 277 | for (int k = 0; k < 3; ++k) { | ||
| 278 | const float* p = &grid[4 * indices[3 * t + k]]; | ||
| 279 | for (int r = 0; r < 3; ++r) | ||
| 280 | v[k][r] = transform[4 * r] * p[0] + transform[4 * r + 1] * p[1] + transform[4 * r + 2] * p[2] + | ||
| 281 | transform[4 * r + 3]; | ||
| 282 | } | ||
| 283 | add_tri(v, 1, t); | ||
| 284 | } | ||
| 285 | tris += "]"; | ||
| 286 | if (!dump(blas_rb.p, blas_info.ResultDataMaxSizeInBytes, "d3d12_blas", | ||
| 287 | "{\"kind\": \"blas\", \"address\": " + std::to_string(blas->GetGPUVirtualAddress()) + | ||
| 288 | ", \"triangles\": " + tris + "}\n")) | ||
| 289 | return fail("BLAS readback"); | ||
| 290 | std::string inst = "["; | ||
| 291 | for (int i = 0; i < 3; ++i) { | ||
| 292 | inst += i ? ", {\"transform\": [" : "{\"transform\": ["; | ||
| 293 | for (int k = 0; k < 12; ++k) inst += (k ? ", " : "") + num(xforms[i][k]); | ||
| 294 | inst += "], \"mask\": " + std::to_string(masks[i]) + ", \"blas\": 0}"; | ||
| 295 | } | ||
| 296 | inst += "]"; | ||
| 297 | if (!dump(tlas_rb.p, tlas_info.ResultDataMaxSizeInBytes, "d3d12_tlas", | ||
| 298 | "{\"kind\": \"tlas\", \"address\": " + std::to_string(tlas->GetGPUVirtualAddress()) + | ||
| 299 | ", \"bias\": 0, \"blas\": [\"d3d12_blas\"], \"instances\": " + inst + "}\n")) | ||
| 300 | return fail("TLAS readback"); | ||
| 301 | std::printf("d3d12_xdxr_rt: BLAS %llu bytes (prebuild %llu), TLAS (prebuild %llu), written to %s\n", | ||
| 302 | static_cast<unsigned long long>(blas_info.ResultDataMaxSizeInBytes), | ||
| 303 | static_cast<unsigned long long>(blas_info.ResultDataMaxSizeInBytes), | ||
| 304 | static_cast<unsigned long long>(tlas_info.ResultDataMaxSizeInBytes), dir.c_str()); | ||
| 305 | return 0; | ||
| 306 | } | ||
diff --git a/tools/xdxr_bvh.py b/tools/xdxr_bvh.py index fb4df317a..edcc79a8b 100644 --- a/tools/xdxr_bvh.py +++ b/tools/xdxr_bvh.py | |||
| @@ -753,12 +753,13 @@ def check_build(directory, rays=300, seed=1): | |||
| 753 | ids = [(t[3], t[4]) for t in tris] | 753 | ids = [(t[3], t[4]) for t in tris] |
| 754 | else: | 754 | else: |
| 755 | blas = [cases[b][0] for b in desc["blas"]] | 755 | blas = [cases[b][0] for b in desc["blas"]] |
| 756 | scene, ids = [], None | 756 | scene, ids, inst_ids = [], None, [] |
| 757 | for inst in desc["instances"]: | 757 | for inst in desc["instances"]: |
| 758 | m = inst["transform"] | 758 | m = inst["transform"] |
| 759 | rows = [m[0:4], m[4:8], m[8:12]] | 759 | rows = [m[0:4], m[4:8], m[8:12]] |
| 760 | tris = [t[:3] for t in blas[inst["blas"]]["triangles"]] if inst["blas"] >= 0 else [] | 760 | src = blas[inst["blas"]]["triangles"] if inst["blas"] >= 0 else [] |
| 761 | scene.append((rows, inst["mask"], tris)) | 761 | scene.append((rows, inst["mask"], [t[:3] for t in src])) |
| 762 | inst_ids.append([(t[3], t[4]) for t in src]) # list position -> (geometry, primitive) | ||
| 762 | bad = hits = 0 | 763 | bad = hits = 0 |
| 763 | case_rays = min(rays, desc.get("rays", rays)) # a large case may ask for fewer (brute force is slow) | 764 | case_rays = min(rays, desc.get("rays", rays)) # a large case may ask for fewer (brute force is slow) |
| 764 | for _ in range(case_rays): | 765 | for _ in range(case_rays): |
| @@ -778,7 +779,8 @@ def check_build(directory, rays=300, seed=1): | |||
| 778 | same = same and math.isclose(got["t"], want["t"], rel_tol=1e-6, abs_tol=1e-9) | 779 | same = same and math.isclose(got["t"], want["t"], rel_tol=1e-6, abs_tol=1e-9) |
| 779 | else: | 780 | else: |
| 780 | # the instance's world-to-object matrix is a float32 inverse; allow for its rounding in t | 781 | # the instance's world-to-object matrix is a float32 inverse; allow for its rounding in t |
| 781 | same = (got["instance"], got["primitive"]) == (want["instance"], want["primitive"]) | 782 | want_id = inst_ids[want["instance"]][want["primitive"]] |
| 783 | same = (got["instance"], (got["geometry"], got["primitive"])) == (want["instance"], want_id) | ||
| 782 | same = same and math.isclose(got["t"], want["t"], rel_tol=1e-4) | 784 | same = same and math.isclose(got["t"], want["t"], rel_tol=1e-4) |
| 783 | bad += not same | 785 | bad += not same |
| 784 | print(f"{n}: {len(data)} bytes, {len(errs)} validation errors, {bad}/{case_rays} rays differ ({hits} hits)") | 786 | print(f"{n}: {len(data)} bytes, {len(errs)} validation errors, {bad}/{case_rays} rays differ ({hits} hits)") |
| @@ -856,6 +858,10 @@ def main(argv=None): | |||
| 856 | if a.cmd == "check-build": | 858 | if a.cmd == "check-build": |
| 857 | if a.rays < 1: | 859 | if a.rays < 1: |
| 858 | ap.error("--rays must be at least 1") | 860 | ap.error("--rays must be at least 1") |
| 861 | import glob | ||
| 862 | if not glob.glob(f"{a.dir}/*.json"): | ||
| 863 | print(f"no cases in {a.dir}: skipped (the build step skipped or did not run)") | ||
| 864 | return 77 # ctest SKIP_RETURN_CODE | ||
| 859 | problems = check_build(a.dir, a.rays) | 865 | problems = check_build(a.dir, a.rays) |
| 860 | for e in problems: | 866 | for e in problems: |
| 861 | print(e) | 867 | print(e) |