From e925b634551ed96d1ed097dfe17d7dfca0cdbe4d Mon Sep 17 00:00:00 2001 From: Vadson159 Date: Mon, 23 Nov 2026 17:24:09 +0100 Subject: [PATCH 01/27] d3d12_xs: route command queue slot 35 to ExecuteCommandLists --- runtime/shims/d3d12_xs_device.cpp | 26 +++++++++++ runtime/shims/d3d12_xs_device.h | 14 ++++-- runtime/test/queue_proxy_test.cpp | 72 +++++++++++++++++++++++------ runtime/test/xs_proxy_mock_test.cpp | 37 ++++++++++++++- 4 files changed, 129 insertions(+), 20 deletions(-) diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index e17a80353b..daa2af795c 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -674,7 +674,11 @@ static_assert(kQueueSlots * sizeof(void*) <= 4096 && kFenceSlots * sizeof(void*) kAllocatorSlots * sizeof(void*) <= 4096, "a table must fit in the first page of its reservation"); +constexpr unsigned kQueueExecuteCommandLists = 10; // (UINT, ID3D12CommandList* const*) constexpr unsigned kQueueSignal = 14, kQueueWait = 15; // (ID3D12Fence*, UINT64) +constexpr unsigned kQueueExecuteCommandListsX = 35; // console ExecuteCommandLists(count, lists) variant +static_assert(kQueueExecuteCommandLists < kQueuePublicSlots && kQueueExecuteCommandListsX < kQueueSlots, + "queue execution slots must stay within their respective tables"); struct ChildProxy { void** vtable; // offset 0: the caller's ID3D12CommandQueue* / ID3D12Fence* points here @@ -715,6 +719,7 @@ const char* child_public_name(unsigned slot) { if (slot < 8) return object[slot]; if constexpr (K == ChildKind::queue) { if (slot < kQueuePublicSlots) return queue[slot - 8]; + if (slot == kQueueExecuteCommandListsX) return "ExecuteCommandListsX"; } else if constexpr (K == ChildKind::fence) { if (slot < kFence1PublicSlots) return fence[slot - 8]; } else { @@ -970,6 +975,15 @@ LONG CALLBACK table_overrun_handler(EXCEPTION_POINTERS* info) { return EXCEPTION_CONTINUE_SEARCH; // diagnostics only: the fault goes on to the title's handlers or the crash } +std::uint64_t queue_execute_command_lists(ChildProxy* self, std::uint64_t count_word, std::uint64_t lists_word) { + // Pass zero-extended UINT in 64-bit RDX so both 32-bit PC implementations and 64-bit mock thunks see clean count. + using ExecuteFn = void(WINAPI*)(void*, std::uint64_t, ID3D12CommandList* const*); + reinterpret_cast(self->real_vtable[kQueueExecuteCommandLists])( + self->real, static_cast(static_cast(count_word)), + reinterpret_cast(lists_word)); + return 0; +} + template std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, std::uint64_t a4, std::uint64_t a5, std::uint64_t a6, std::uint64_t a7, @@ -989,6 +1003,10 @@ std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_ reinterpret_cast(a2))); } else { note_child_slot(Slot); + if constexpr (K == ChildKind::queue && Slot == kQueueExecuteCommandListsX) { + d3d12_trace::record(child_trace_name(Slot)); + return queue_execute_command_lists(self, a1, a2); + } if (Slot >= self->slot_count) { bool expected = false; if (ChildStats::beyond_warned[Slot].compare_exchange_strong(expected, true, @@ -1004,6 +1022,9 @@ std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_ return hr_to_u64(E_NOTIMPL); } d3d12_trace::record(child_trace_name(Slot)); // "called": the real object's result is not inspected + if constexpr (K == ChildKind::queue && Slot == kQueueExecuteCommandLists) { + return queue_execute_command_lists(self, a1, a2); + } if constexpr (K == ChildKind::queue && (Slot == kQueueSignal || Slot == kQueueWait)) a1 = unwrap_object(a1); // The PC vtable entry with the real object as `this`; integer/pointer arguments, the hidden struct-return @@ -1742,6 +1763,11 @@ unsigned fence_proxy_slot_count(const void* fence) { unsigned queue_proxy_table_size() { return kQueueSlots; } unsigned fence_proxy_table_size() { return kFenceSlots; } + +bool queue_slot_overridden(unsigned slot) { + return slot <= 2 || slot == 7 || slot == kQueueSignal || slot == kQueueWait || + slot == kQueueExecuteCommandListsX; +} unsigned allocator_proxy_table_size() { return kAllocatorSlots; } unsigned allocator_proxy_slot_count(const void* allocator) { return is_allocator_proxy(allocator) ? static_cast(allocator)->slot_count : 0; diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index 0019ec5069..2bf25000ac 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -35,11 +35,12 @@ // // Command queues and fences (device slots 8, 75, 36, and 32 for a shared fence) come back wrapped in queue and fence // proxies of the same kind: the public chain (19 queue slots, 11 or 12 fence slots in SDK 10.0.26100) is forwarded -// in PC order, and a slot past it, up to the end of the proxy's table (128 queue, 64 fence slots), is logged with its -// first four argument words and refused with E_NOTIMPL. A slot past the table faults on the vtable read inside a -// reserved, never-committed region, and the fault is logged with the slot. That is where the console's queue methods -// (PresentX, SuspendX, ResumeX) will show up; their slots are not known and are not guessed, and that the console -// keeps the public slots is an assumption (docs/d3d12_command_objects.md §5.2). Heap, queue and fence proxies are +// in PC order. Queue slot 35 is the console ExecuteCommandLists(count, lists) variant and forwards to PC slot 10; +// every other slot past the public chain, up to the end of the proxy's table (128 queue, 64 fence slots), is logged +// with its first four argument words and refused with E_NOTIMPL. A slot past the table faults on the vtable read inside a +// reserved, never-committed region, and the fault is logged with the slot. PresentX, SuspendX and ResumeX slots past +// the public chain remain refused until measured and implemented, and that the console keeps the public slots is an +// assumption (docs/d3d12_command_objects.md §5.2). Heap, queue and fence proxies are // unwrapped wherever a device or queue method hands them to the real runtime: queue Signal/Wait (14/15), device // CreateSharedHandle (31), MakeResident/Evict (34/35), SetEventOnMultipleFenceCompletion (45), SetResidencyPriority // (46) and EnqueueMakeResident (50). Command lists are not wrapped, so ExecuteCommandLists passes them through and a @@ -107,6 +108,9 @@ unsigned queue_proxy_slot_count(const void* queue); unsigned fence_proxy_slot_count(const void* fence); unsigned queue_proxy_table_size(); unsigned fence_proxy_table_size(); +// True for queue slots handled by the proxy instead of forwarded verbatim past IUnknown: 0-2 (IUnknown), +// 7 (GetDevice), 14/15 (Signal/Wait unwrap fences), and 35 (Xbox ExecuteCommandLists variant -> PC slot 10). +bool queue_slot_overridden(unsigned slot); // Live references on a queue, fence or allocator proxy (0 for anything else). Test helper. unsigned long command_object_proxy_ref_count(const void* object); // Per-slot call counters and first-call flags, shared by all queue proxies and all fence proxies. diff --git a/runtime/test/queue_proxy_test.cpp b/runtime/test/queue_proxy_test.cpp index 3f46567f85..967313d53a 100644 --- a/runtime/test/queue_proxy_test.cpp +++ b/runtime/test/queue_proxy_test.cpp @@ -257,7 +257,9 @@ int check_slots(const Backend& b) { } } - // 10: ExecuteCommandLists passes the (real, not wrapped) command lists through. + // 10 and console slot 35: ExecuteCommandLists passes the (real, not wrapped) command lists through. + EXPECT(xs::queue_slot_overridden(35) && xs::queue_slot_overridden(14) && xs::queue_slot_overridden(15)); + EXPECT(!xs::queue_slot_overridden(10) && !xs::queue_slot_overridden(34)); { Ref allocator; EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, @@ -272,6 +274,11 @@ int check_slots(const Backend& b) { EXPECT(qhits(10) == before + 1); EXPECT(SUCCEEDED(queue->Signal(fence.p, 6))); if (wait_for(label, fence.p, 6)) return 1; + const std::uint64_t before35 = qhits(35); + EXPECT(raw_call(queue.p, 35, 1, reinterpret_cast(lists)) == 0); + EXPECT(qhits(35) == before35 + 1 && xs::queue_slot_first_call_seen(35)); + EXPECT(SUCCEEDED(queue->Signal(fence.p, 7))); + if (wait_for(label, fence.p, 7)) return 1; if (b.vulkan) { // The layer's own helpers find their queue behind the proxy. EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); @@ -293,17 +300,17 @@ int check_slots(const Backend& b) { // 14/15: Signal and Wait take fence proxies; the real queue gets the real fences. before = qhits(14); - EXPECT(SUCCEEDED(queue->Signal(fence.p, 7))); + EXPECT(SUCCEEDED(queue->Signal(fence.p, 8))); EXPECT(qhits(14) == before + 1); - if (wait_for(label, fence.p, 7)) return 1; + if (wait_for(label, fence.p, 8)) return 1; before = qhits(15); - EXPECT(SUCCEEDED(queue->Wait(fence.p, 8))); // the queue waits until the CPU signals 8 + EXPECT(SUCCEEDED(queue->Wait(fence.p, 9))); // the queue waits until the CPU signals 9 EXPECT(qhits(15) == before + 1); EXPECT(SUCCEEDED(queue->Signal(second.p, 1))); Sleep(50); EXPECT(second->GetCompletedValue() == 0); // still held by the Wait before = fhits(10); - EXPECT(SUCCEEDED(fence->Signal(8))); // fence 10, from the CPU + EXPECT(SUCCEEDED(fence->Signal(9))); // fence 10, from the CPU EXPECT(fhits(10) == before + 1); if (wait_for(label, second.p, 1)) return 1; @@ -359,12 +366,12 @@ int check_slots(const Backend& b) { EXPECT(fhits(7) == before + 1); } before = fhits(8); - EXPECT(fence->GetCompletedValue() == 8); + EXPECT(fence->GetCompletedValue() == 9); EXPECT(fhits(8) == before + 1); { Event done; before = fhits(9); - EXPECT(SUCCEEDED(fence->SetEventOnCompletion(8, done.h)) && done.set_within(5000)); + EXPECT(SUCCEEDED(fence->SetEventOnCompletion(9, done.h)) && done.set_within(5000)); EXPECT(fhits(9) == before + 1); } if (fence_slots == 12) { @@ -389,8 +396,9 @@ int check_slots(const Backend& b) { } } - // The refused tail: every slot from the end of the public chain to the end of the table. + // The refused tail: every unmodelled slot from the end of the public chain to the end of the table. for (unsigned slot = 19; slot < xs::queue_proxy_table_size(); ++slot) { + if (xs::queue_slot_overridden(slot)) continue; before = qhits(slot); EXPECT(as_hr(call_slot(queue.p, slot)) == E_NOTIMPL); EXPECT(qhits(slot) == before + 1 && xs::queue_slot_first_call_seen(slot)); @@ -1460,18 +1468,56 @@ int check_xbox_client(const Backend& b) { EXPECT(same); // the GPU really ran the list the queue proxy submitted } - // Device slot 50: EnqueueMakeResident with the objects and a fence proxy to signal. - EXPECT(SUCCEEDED(as_hr(raw(device, 50, D3D12_RESIDENCY_FLAG_NONE, 4, word(pageables), word(fence.p), 2)))); + // Second copy with fresh bytes, submitted through console ExecuteCommandLists slot 35. + { + std::uint8_t* bytes = nullptr; + EXPECT(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast(&bytes)))); + for (UINT64 i = 0; i < kBytes; ++i) bytes[i] = static_cast(i * 11 + 5); + upload->Unmap(0, nullptr); + } + EXPECT(SUCCEEDED(allocator->Reset())); + EXPECT(SUCCEEDED(list->Reset(allocator.p, nullptr))); + D3D12_RESOURCE_BARRIER to_dest{}; + to_dest.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + to_dest.Transition.pResource = gpu.p; + to_dest.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + to_dest.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_SOURCE; + to_dest.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_DEST; + list->ResourceBarrier(1, &to_dest); + list->CopyBufferRegion(gpu.p, 0, upload.p, 0, kBytes); + D3D12_RESOURCE_BARRIER to_source = to_dest; + to_source.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST; + to_source.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; + list->ResourceBarrier(1, &to_source); + list->CopyBufferRegion(readback.p, 0, gpu.p, 0, kBytes); + EXPECT(SUCCEEDED(list->Close())); + EXPECT(raw(queue.p, 35, 1, word(lists)) == 0); + EXPECT(SUCCEEDED(as_hr(raw(queue.p, 14, word(fence.p), 2)))); EXPECT(SUCCEEDED(as_hr(raw(fence.p, 9, 2, word(done.h)))) && done.set_within(5000)); + EXPECT(raw(fence.p, 8) >= 2); + { + std::uint8_t* bytes = nullptr; + const D3D12_RANGE read_range{0, kBytes}; + EXPECT(SUCCEEDED(readback->Map(0, &read_range, reinterpret_cast(&bytes)))); + bool same = true; + for (UINT64 i = 0; i < kBytes; ++i) same = same && bytes[i] == static_cast(i * 11 + 5); + const D3D12_RANGE nothing{0, 0}; + readback->Unmap(0, ¬hing); + EXPECT(same); // the GPU really ran the list submitted via queue slot 35 + } + + // Device slot 50: EnqueueMakeResident with the objects and a fence proxy to signal. + EXPECT(SUCCEEDED(as_hr(raw(device, 50, D3D12_RESIDENCY_FLAG_NONE, 4, word(pageables), word(fence.p), 3)))); + EXPECT(SUCCEEDED(as_hr(raw(fence.p, 9, 3, word(done.h)))) && done.set_within(5000)); // Queue slot 15 holds the queue until the CPU (fence slot 10) signals; device slot 45 then sees both fences. - EXPECT(SUCCEEDED(as_hr(raw(queue.p, 15, word(fence.p), 3)))); + EXPECT(SUCCEEDED(as_hr(raw(queue.p, 15, word(fence.p), 4)))); EXPECT(SUCCEEDED(as_hr(raw(queue.p, 14, word(second.p), 1)))); Sleep(50); EXPECT(raw(second.p, 8) == 0); - EXPECT(SUCCEEDED(as_hr(raw(fence.p, 10, 3)))); + EXPECT(SUCCEEDED(as_hr(raw(fence.p, 10, 4)))); ID3D12Fence* both[] = {fence.p, second.p}; - const UINT64 values[] = {3, 1}; + const UINT64 values[] = {4, 1}; EXPECT(SUCCEEDED(as_hr(raw(device, 45, word(both), word(values), 2, D3D12_MULTIPLE_FENCE_WAIT_FLAG_ALL, word(done.h)))) && done.set_within(5000)); diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index f0030116bd..c916402e42 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -767,6 +767,37 @@ int check_xbox_slots() { #endif } +// ---- 7b. Xbox queue ExecuteCommandLists variant (queue slot 35 -> PC slot 10) ---- + +int check_xbox_queue_slots() { + Mock* mock = nullptr; + void* device = make_device(mock, 9, true); + EXPECT(device); + void* queue = make_queue(device); + EXPECT(queue); + Mock* const queue_mock = reinterpret_cast(xs::queue_proxy_real_queue(queue)); + xs::reset_device_proxy_stats(); + + EXPECT(xs::queue_slot_overridden(35) && xs::queue_slot_overridden(14) && xs::queue_slot_overridden(15)); + EXPECT(!xs::queue_slot_overridden(10) && !xs::queue_slot_overridden(34) && !xs::queue_slot_overridden(36)); + + void* fake_lists[2] = {reinterpret_cast(0x12340000), reinterpret_cast(0x56780000)}; + EXPECT(raw(queue, 35, (0xdeadbeefull << 32) | 2ull, word(fake_lists)) == 0); + EXPECT(xs::queue_slot_hits(35) == 1 && xs::queue_slot_first_call_seen(35)); + EXPECT(xs::queue_slot_hits(10) == 0); + EXPECT(queue_mock->calls[35] == 0 && queue_mock->calls[10] == 1); + EXPECT(queue_mock->args[10][0] == 2 && queue_mock->args[10][1] == word(fake_lists)); + + EXPECT(raw(queue, 35, 0, 0) == 0); + EXPECT(xs::queue_slot_hits(35) == 2 && queue_mock->calls[35] == 0 && queue_mock->calls[10] == 2); + EXPECT(queue_mock->args[10][0] == 0 && queue_mock->args[10][1] == 0); + + EXPECT(release(queue) == 0 && release(device) == 0 && mock->refs == 0); + std::printf("%s: queue slot 35 routes ExecuteCommandLists(count, lists) to PC slot 10 with UINT count masking\n", + g_label); + return 0; +} + // ---- 8. Environment overrides for the Xbox device slots (one process each, read once) ---- int run_env_slots(bool valid) { @@ -835,8 +866,10 @@ int check_tail(bool want_guarded) { // Signal (14) still reaches the real queue, with the real fence. EXPECT(hr_of(raw(queue, 14, word(fence), 5)) == S_OK && queue_mock->calls[14] == 1 && queue_mock->args[14][0] == word(xs::fence_proxy_real_fence(fence)) && queue_mock->args[14][1] == 5); - for (unsigned slot = 19; slot < xs::queue_proxy_table_size(); ++slot) + for (unsigned slot = 19; slot < xs::queue_proxy_table_size(); ++slot) { + if (xs::queue_slot_overridden(slot)) continue; EXPECT(hr_of(raw(queue, slot)) == E_NOTIMPL && queue_mock->calls[slot] == 0); + } for (unsigned slot = 12; slot < xs::fence_proxy_table_size(); ++slot) EXPECT(hr_of(raw(fence, slot)) == E_NOTIMPL); EXPECT(xs::queue_table_overruns() == 0 && xs::fence_table_overruns() == 0); EXPECT(release(queue) == 0 && release(fence) == 0 && release(device) == 0 && mock->refs == 0); @@ -948,7 +981,7 @@ int main(int argc, char** argv) { } if (argc != 1) return 2; if (check_tail(true) || check_levels() || check_fence1() || check_create_failures() || check_open_shared() || - check_alloc_failures() || check_allocators() || check_xbox_slots()) + check_alloc_failures() || check_allocators() || check_xbox_slots() || check_xbox_queue_slots()) return 1; std::printf("xs_proxy_mock_test: PASS (%d allocations refused on purpose)\n", g_failed_news); return 0; From d3a1c290b5738694e4d3b78a66350e70e0eb5846 Mon Sep 17 00:00:00 2001 From: Daiko Date: Mon, 23 Nov 2026 17:39:20 +0100 Subject: [PATCH 02/27] d3d12: persist the pipeline cache across launches (D3D-704) PSOs a session built were compiled again by the next one. The layer already read the `pipelines` stage's pipeline_cache.bin beside gta6rt.exe (#367), but never wrote anything back. Now the runtime keeps its own cache in pipeline_cache.session.bin beside it: vkGetPipelineCacheData on device teardown, then vkMergePipelineCaches into the cache at the next launch. Vulkan takes one blob per create, so the offline seed and the session file are two caches merged together rather than one file. They are deliberately separate files, so a run can never replace the multi-GB corpus cache with the handful of pipelines it compiled. The write is capped at 256 MiB (LEONIDA_PIPELINE_CACHE_BYTES=, 0 turns it off): a cache seeded from the corpus comes back as the whole union, which is not worth rewriting at every exit; past the cap the previous session file is left alone. A foreign or truncated session file is ignored with one line, and so is a failed write (a read-only install directory). The header check moves to runtime/src/pipeline_cache_store.h, shared with the offline seed and tested without Vulkan (runtime/test/pipeline_cache_store_test.cpp: the limit parser and the 32-byte VkPipelineCacheHeaderVersionOne comparison). write_pipeline_cache_file moves from runtime/test to runtime/src so the runtime and vk_pipeline_check use the same staged write. Not run: this machine has neither MSVC nor the Windows SDK, so the shim itself is compiled by the Windows job. The portable test passes here (23/23 ctest on Linux). The end-to-end check needs a Vulkan GPU: run d3d12_vulkan_device_test twice and look for "wrote N bytes to pipeline_cache.session.bin", then "merged N bytes" on the second run. --- docs/d3d12_vulkan.md | 8 ++ runtime/CMakeLists.txt | 4 + runtime/shims/d3d12_vulkan_device.cpp | 130 ++++++++++++++++++-- runtime/{test => src}/pipeline_cache_file.h | 3 + runtime/src/pipeline_cache_store.h | 69 +++++++++++ runtime/src/vulkan_backend.h | 2 +- runtime/test/pipeline_cache_file_test.cpp | 2 +- runtime/test/pipeline_cache_store_test.cpp | 93 ++++++++++++++ runtime/test/vk_pipeline_check.cpp | 2 +- 9 files changed, 298 insertions(+), 15 deletions(-) rename runtime/{test => src}/pipeline_cache_file.h (90%) create mode 100644 runtime/src/pipeline_cache_store.h create mode 100644 runtime/test/pipeline_cache_store_test.cpp diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index a14d67bcc3..02846e4298 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2023,6 +2023,14 @@ Pipeline creation: and pipeline-cache UUID. When the file is absent or incompatible, the runtime starts with an empty cache. The offline checker matches the runtime's layout and subgroup request for compute shaders with no descriptor bindings and the standard 144-byte push-constant range. + The runtime also keeps what it compiled itself: `pipeline_cache.session.bin`, written from + `vkGetPipelineCacheData` on device teardown and merged into the cache at the next launch with + `vkMergePipelineCaches` (the offline seed and the session file cannot be passed together as one + `VkPipelineCacheCreateInfo`). The two files are separate so a run never replaces the multi-GB corpus cache with + the handful of pipelines it happened to compile. The session write is capped at 256 MiB + (`LEONIDA_PIPELINE_CACHE_BYTES=`, `0` turns it off): a cache seeded with the corpus file returns the whole + union, which is not worth rewriting at every exit. A session file from another device, driver or pipeline-cache + UUID is ignored with one line, and a write that fails (a read-only install directory) leaves the previous file. `GetCachedBlob` records the vendor, device, driver version, `pipelineCacheUUID` and a SHA-256 of the description without `Flags`, sealed by a checksum (`runtime/src/cached_pso.h`). The answers are the host's, measured on an RTX 3060 and WARP: the same description is accepted; another diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index b801320744..1afb3837bd 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -440,6 +440,10 @@ if(BUILD_TESTING) add_executable(pipeline_cache_file_test test/pipeline_cache_file_test.cpp) add_test(NAME pipeline_cache_file COMMAND pipeline_cache_file_test) + # D3D-704's session-cache limit and header check: pure stdlib, no Vulkan headers. + add_executable(pipeline_cache_store_test test/pipeline_cache_store_test.cpp) + add_test(NAME pipeline_cache_store COMMAND pipeline_cache_store_test) + add_executable(xdxr_build_output_test test/xdxr_build_output_test.cpp) add_test(NAME xdxr_build_output COMMAND xdxr_build_output_test) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index c7e3d99942..018c751364 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -23,6 +23,8 @@ #include "../src/vulkan_memory.h" #include "../src/resource_tiling.h" #include "../src/cached_pso.h" +#include "../src/pipeline_cache_file.h" +#include "../src/pipeline_cache_store.h" #include "../src/conservative_raster.h" #include "../src/resource_detile.h" #include "../src/shader_library.h" @@ -50,6 +52,7 @@ #include #include #include +#include #include #include #include @@ -66,6 +69,8 @@ constexpr UINT kDescriptorSize = descriptor_size; // for unbound vertex and index buffers to read (D3D12 reads zeros there). constexpr VkDeviceSize kArenaReserved = 64 * 1024; static_assert(sizeof(leonida::TargetView) <= kDescriptorSize); +// pipeline_cache_store.h reads this layout without vulkan.h (D3D-704); remember the two. +static_assert(sizeof(VkPipelineCacheHeaderVersionOne) == leonida::pipeline_cache_store::header_bytes); // The shader model and root signature version this layer can honour. Nothing in the runtime compiles DXIL: the // game's shaders arrive as SPIR-V from the offline translator, and the only DXIL path (the BVH builder) is lowered @@ -133,6 +138,25 @@ std::filesystem::path pipeline_cache_path() { return std::filesystem::path(path).parent_path() / L"pipeline_cache.bin"; } +// What the runtime itself compiled, kept next to the offline seed and never written over it (D3D-704). +std::filesystem::path pipeline_cache_session_path() { + std::filesystem::path path = pipeline_cache_path(); + if (!path.empty()) path.replace_filename(L"pipeline_cache.session.bin"); + return path; +} + +// LEONIDA_PIPELINE_CACHE_BYTES, in bytes; 0 turns the session file off. One line for a value that is not a number. +std::size_t pipeline_cache_save_limit() { + char text[32] = {}; + size_t length = 0; + const bool present = getenv_s(&length, text, "LEONIDA_PIPELINE_CACHE_BYTES") == 0 && length > 1; + const auto limit = leonida::pipeline_cache_store::parse_save_limit(present ? text : ""); + if (!limit.valid) + std::fprintf(stderr, "[rt] d3d12: LEONIDA_PIPELINE_CACHE_BYTES=%s is not a byte count; using %zu\n", text, + limit.bytes); + return limit.bytes; +} + // A corpus cache may be several GiB. Keep the read-only view alive through vkCreatePipelineCache // and deny writers while the view is in use. class PipelineCacheSeed { @@ -165,13 +189,7 @@ class PipelineCacheSeed { std::size_t size() const { return size_; } bool compatible(const leonida::cached_pso::Identity& identity) const { - static_assert(sizeof(VkPipelineCacheHeaderVersionOne) == 32); - VkPipelineCacheHeaderVersionOne header{}; - // The header is little-endian, like the host. The driver interprets the opaque payload. - std::memcpy(&header, data_, sizeof(header)); - return header.headerSize == sizeof(header) && header.headerVersion == VK_PIPELINE_CACHE_HEADER_VERSION_ONE && - header.vendorID == identity.vendor && header.deviceID == identity.device && - std::memcmp(header.pipelineCacheUUID, identity.cache_uuid, VK_UUID_SIZE) == 0; + return leonida::pipeline_cache_store::header_matches(data_, size_, identity); } private: @@ -199,6 +217,90 @@ VkPipelineCache create_seeded_pipeline_cache(PFN_vkCreatePipelineCache create_ca return cache; } +// D3D-704: merges what earlier launches compiled into the cache the pipelines are created against. The offline seed +// and the session file cannot be handed over as one VkPipelineCacheCreateInfo -- Vulkan reads a single blob -- so the +// session cache is created on its own and merged in. A missing, foreign or corrupt session file leaves the cache as +// it was, and so does a driver that does not expose vkMergePipelineCaches. +void merge_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, VkPipelineCache cache, + const leonida::cached_pso::Identity& identity) { + if (!cache || !vk.vkCreatePipelineCache || !vk.vkDestroyPipelineCache || !vk.vkMergePipelineCaches) return; + if (!pipeline_cache_save_limit()) return; // LEONIDA_PIPELINE_CACHE_BYTES=0 turns the session file off + const PipelineCacheSeed seed(pipeline_cache_session_path()); + if (!seed.data()) return; + if (!seed.compatible(identity)) { + std::fprintf(stderr, "[rt] d3d12: pipeline_cache.session.bin does not match this Vulkan device\n"); + return; + } + const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, nullptr, 0, seed.size(), + seed.data()}; + VkPipelineCache session = VK_NULL_HANDLE; + if (vk.vkCreatePipelineCache(device, &create, nullptr, &session) != VK_SUCCESS) { + std::fprintf(stderr, "[rt] d3d12: Vulkan declined pipeline_cache.session.bin\n"); + return; + } + const VkResult result = vk.vkMergePipelineCaches(device, cache, 1, &session); + vk.vkDestroyPipelineCache(device, session, nullptr); + if (result == VK_SUCCESS) + std::fprintf(stderr, "[rt] d3d12: merged %zu bytes from pipeline_cache.session.bin\n", seed.size()); + else + std::fprintf(stderr, "[rt] d3d12: vkMergePipelineCaches on pipeline_cache.session.bin returned %d; ignored\n", + static_cast(result)); +} + +// Writes what this device compiled for the next launch (D3D-704). Called once the device is idle, before the cache +// is destroyed. Past the cap nothing is written: the blob from an earlier, smaller session stays, which is better +// than replacing it with one the next launch would keep refusing to save. +void save_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, VkPipelineCache cache) { + if (!cache || !vk.vkGetPipelineCacheData) return; + const std::size_t limit = pipeline_cache_save_limit(); + if (!limit) return; // LEONIDA_PIPELINE_CACHE_BYTES=0 turns the session file off + const auto over_limit = [limit](std::size_t size) { + std::fprintf(stderr, + "[rt] d3d12: pipeline cache is %zu bytes, over the %zu-byte session limit " + "(LEONIDA_PIPELINE_CACHE_BYTES); pipeline_cache.session.bin left as it was\n", + size, limit); + }; + std::size_t size = 0; + if (vk.vkGetPipelineCacheData(device, cache, &size, nullptr) != VK_SUCCESS || + size <= sizeof(VkPipelineCacheHeaderVersionOne)) + return; + if (size > limit) { + over_limit(size); + return; + } + std::vector data; + try { + // Room to spare in case the driver counts the blob short between the query and the read. Nothing creates + // pipelines while the device is torn down, so this is a belt-and-braces margin, not a retry loop. + data.resize(size + (size >> 4)); + } catch (const std::bad_alloc&) { + std::fprintf(stderr, + "[rt] d3d12: no memory for the %zu-byte pipeline cache; pipeline_cache.session.bin not " + "written\n", + size); + return; + } + std::size_t written = data.size(); + const VkResult result = vk.vkGetPipelineCacheData(device, cache, &written, data.data()); + if (result != VK_SUCCESS || written < sizeof(VkPipelineCacheHeaderVersionOne) || written > data.size()) { + std::fprintf(stderr, + "[rt] d3d12: could not read the pipeline cache (%d); pipeline_cache.session.bin not written\n", + static_cast(result)); + return; + } + if (written > limit) { + over_limit(written); + return; + } + const std::filesystem::path path = pipeline_cache_session_path(); + if (path.empty()) return; + if (const std::error_code error = write_pipeline_cache_file(path, data.data(), written)) { + std::fprintf(stderr, "[rt] d3d12: pipeline_cache.session.bin not written: %s\n", error.message().c_str()); + return; + } + std::fprintf(stderr, "[rt] d3d12: wrote %zu bytes to pipeline_cache.session.bin\n", written); +} + // A shader whose subgroup size cannot be had runs at the device's: inexact if it crosses the halves of a wave64 (or, // for a wave32 shader on a 64-wide default, reads lanes that are not its own). Logged once per stage with the first // shader's name, then again at 10, 100, 1000... of that stage so a whole corpus stays readable. @@ -609,10 +711,12 @@ struct DeviceState { const auto& vk = context->vk; if (!vk.vkCreatePipelineCache || !vk.vkDestroyPipelineCache) return; pipeline_cache_handle = create_seeded_pipeline_cache(vk.vkCreatePipelineCache, info.device, pso_identity); - if (pipeline_cache_handle) return; - const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO}; - if (vk.vkCreatePipelineCache(info.device, &create, nullptr, &pipeline_cache_handle) != VK_SUCCESS) - pipeline_cache_handle = VK_NULL_HANDLE; + if (!pipeline_cache_handle) { + const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO}; + if (vk.vkCreatePipelineCache(info.device, &create, nullptr, &pipeline_cache_handle) != VK_SUCCESS) + pipeline_cache_handle = VK_NULL_HANDLE; + } + merge_session_pipeline_cache(vk, info.device, pipeline_cache_handle, pso_identity); }); // Without EXTERNALLY_SYNCHRONIZED_BIT the driver synchronizes concurrent pipeline creation using this cache. return pipeline_cache_handle; @@ -5208,8 +5312,10 @@ class Device final vk.vkDestroyBuffer(state_.info.device, state_.arena.buffer, nullptr); if (state_.arena.memory) vk.vkFreeMemory(state_.info.device, state_.arena.memory, nullptr); } - if (state_.pipeline_cache_handle) + if (state_.pipeline_cache_handle) { + save_session_pipeline_cache(state_.context->vk, state_.info.device, state_.pipeline_cache_handle); state_.context->vk.vkDestroyPipelineCache(state_.info.device, state_.pipeline_cache_handle, nullptr); + } state_.context.reset(); if (owned_.device) owned_.destroy_device(owned_.device, nullptr); if (owned_.instance) owned_.destroy_instance(owned_.instance, nullptr); diff --git a/runtime/test/pipeline_cache_file.h b/runtime/src/pipeline_cache_file.h similarity index 90% rename from runtime/test/pipeline_cache_file.h rename to runtime/src/pipeline_cache_file.h index 400138ef7d..95afbd10ad 100644 --- a/runtime/test/pipeline_cache_file.h +++ b/runtime/src/pipeline_cache_file.h @@ -1,4 +1,7 @@ // Publish a checkpoint only after every byte has reached a closed, same-directory staging file. +// +// Used by vk_pipeline_check (its corpus checkpoints) and by the runtime itself, which writes the session cache on +// device teardown (pipeline_cache_store.h). A reader of the old file keeps it open until its rename completes. #pragma once #include diff --git a/runtime/src/pipeline_cache_store.h b/runtime/src/pipeline_cache_store.h new file mode 100644 index 0000000000..6d519d99b1 --- /dev/null +++ b/runtime/src/pipeline_cache_store.h @@ -0,0 +1,69 @@ +// Persisting the runtime's VkPipelineCache across launches (D3D-704). +// +// Two files sit beside gta6rt.exe, and they are not interchangeable: +// +// pipeline_cache.bin the offline corpus seed the `pipelines` build stage writes (#367). Read only. +// pipeline_cache.session.bin what the runtime compiled last time. Written on device teardown. +// +// Keeping them apart means a run can never replace the multi-GB corpus cache with the handful of pipelines it +// happened to compile. On the next launch both are loaded and merged, so the offline entries and the previous +// session's entries are available together. +// +// This header is pure stdlib on purpose (it does not include vulkan.h): pipeline_cache_store_test builds on hosts +// where CMake has no Vulkan headers. The byte layout below is VkPipelineCacheHeaderVersionOne, whose 32 bytes are +// part of Vulkan's ABI, not something a driver chooses. +#pragma once + +#include +#include +#include +#include + +#include "cached_pso.h" + +namespace leonida::pipeline_cache_store { + +// A session cache normally holds what one boot compiled (a few MB to a few hundred MB). The cap is what keeps a +// cache seeded from the multi-GB corpus file -- whose data comes back as the whole union -- from being rewritten +// at every exit. Past it the previous session file is left alone; raise the limit with +// LEONIDA_PIPELINE_CACHE_BYTES when a session really compiles that much. +inline constexpr std::size_t default_save_limit = std::size_t{256} << 20; // 256 MiB + +struct SaveLimit { + std::size_t bytes = default_save_limit; + bool valid = true; // false when the text was not a byte count; bytes then stays at the default +}; + +// LEONIDA_PIPELINE_CACHE_BYTES: a decimal byte count, 0 turning the session file off entirely. Empty or absent +// means the default; stray text, a sign or an overflow is reported by the caller and the default is used. +inline SaveLimit parse_save_limit(const char* text) { + if (!text || !*text) return {}; + std::size_t value = 0; + for (const char* p = text; *p; ++p) { + if (*p < '0' || *p > '9') return {default_save_limit, false}; + const std::size_t digit = static_cast(*p - '0'); + if (value > (std::numeric_limits::max() - digit) / 10) return {default_save_limit, false}; + value = value * 10 + digit; + } + return {value, true}; +} + +inline constexpr std::size_t header_bytes = 32; +inline constexpr std::uint32_t header_version_one = 1; + +inline std::uint32_t read_u32(const std::uint8_t* p) { + return std::uint32_t(p[0]) | (std::uint32_t(p[1]) << 8) | (std::uint32_t(p[2]) << 16) | + (std::uint32_t(p[3]) << 24); +} + +// True when the blob's header names this physical device and pipeline-cache UUID, which is what a driver requires +// before it will read the opaque payload. The header is little-endian, like the host. +inline bool header_matches(const void* data, std::size_t size, const cached_pso::Identity& identity) { + if (!data || size < header_bytes) return false; + const auto* bytes = static_cast(data); + return read_u32(bytes) == header_bytes && read_u32(bytes + 4) == header_version_one && + read_u32(bytes + 8) == identity.vendor && read_u32(bytes + 12) == identity.device && + std::memcmp(bytes + 16, identity.cache_uuid, sizeof(identity.cache_uuid)) == 0; +} + +} // namespace leonida::pipeline_cache_store diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index e659a762dc..4303b55ef7 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -95,7 +95,7 @@ struct VulkanDeviceFunctions { X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \ X(vkCmdSetBlendConstants) X(vkCmdDraw) \ X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) X(vkGetImageSparseMemoryRequirements) \ - X(vkCreatePipelineCache) X(vkDestroyPipelineCache) \ + X(vkCreatePipelineCache) X(vkDestroyPipelineCache) X(vkGetPipelineCacheData) X(vkMergePipelineCaches) \ X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents) X(vkCmdDrawMeshTasksEXT) \ X(vkCreateRenderPass2) X(vkDestroyRenderPass) X(vkCreateFramebuffer) X(vkDestroyFramebuffer) \ X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass) diff --git a/runtime/test/pipeline_cache_file_test.cpp b/runtime/test/pipeline_cache_file_test.cpp index 73dad65de8..f24694a56d 100644 --- a/runtime/test/pipeline_cache_file_test.cpp +++ b/runtime/test/pipeline_cache_file_test.cpp @@ -1,5 +1,5 @@ // Exercise checkpoint replacement and real filesystem errors without a Vulkan device. -#include "pipeline_cache_file.h" +#include "../src/pipeline_cache_file.h" #include #include diff --git a/runtime/test/pipeline_cache_store_test.cpp b/runtime/test/pipeline_cache_store_test.cpp new file mode 100644 index 0000000000..dbf174768b --- /dev/null +++ b/runtime/test/pipeline_cache_store_test.cpp @@ -0,0 +1,93 @@ +// The two pure decisions behind D3D-704: how large a session cache may be (LEONIDA_PIPELINE_CACHE_BYTES) and +// whether a blob's VkPipelineCacheHeaderVersionOne names this device. No Vulkan, no GPU, no files. +#include "../src/pipeline_cache_store.h" + +#include +#include +#include +#include +#include + +#define CHECK(condition) do { \ + if (!(condition)) { \ + std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \ + return 1; \ + } \ +} while (0) + +namespace store = leonida::pipeline_cache_store; + +static void put32(std::uint8_t* p, std::uint32_t value) { + for (int i = 0; i < 4; ++i) p[i] = static_cast(value >> (8 * i)); +} + +static int test_limit() { + using store::default_save_limit; + // Absent, empty and the default knob. + CHECK(store::parse_save_limit(nullptr).bytes == default_save_limit); + CHECK(store::parse_save_limit(nullptr).valid); + CHECK(store::parse_save_limit("").bytes == default_save_limit); + // 0 is the documented "off", not a typo, and leading zeros are still a number. + CHECK(store::parse_save_limit("0").bytes == 0); + CHECK(store::parse_save_limit("0").valid); + CHECK(store::parse_save_limit("007").bytes == 7); + CHECK(store::parse_save_limit("1048576").bytes == 1048576); + const std::string largest = std::to_string(std::numeric_limits::max()); + CHECK(store::parse_save_limit(largest.c_str()).bytes == std::numeric_limits::max()); + // Anything that is not a plain byte count falls back to the default and says the value was rejected. + for (const char* text : {"-1", "+1", " 1", "1 ", "12x", "0x10", "1.5", "99999999999999999999999999"}) { + const auto limit = store::parse_save_limit(text); + CHECK(!limit.valid); + CHECK(limit.bytes == default_save_limit); + } + return 0; +} + +static int test_header() { + leonida::cached_pso::Identity identity; + identity.vendor = 0x1002; + identity.device = 0x73ff; + identity.driver = 0x02000d0b; + + std::uint8_t header[store::header_bytes] = {}; + put32(header, store::header_bytes); + put32(header + 4, store::header_version_one); + put32(header + 8, identity.vendor); + put32(header + 12, identity.device); + for (int i = 0; i < 16; ++i) header[16 + i] = identity.cache_uuid[i] = static_cast(i + 1); + CHECK(store::header_matches(header, sizeof(header), identity)); + // Extra payload past the header does not matter: the driver reads the header and then its own data. + std::uint8_t blob[store::header_bytes + 8] = {}; + std::memcpy(blob, header, sizeof(header)); + CHECK(store::header_matches(blob, sizeof(blob), identity)); + + // Too short and null are "no cache", never a read past the end. + CHECK(!store::header_matches(header, store::header_bytes - 1, identity)); + CHECK(!store::header_matches(nullptr, store::header_bytes, identity)); + + // The four fields a driver checks before trusting a blob from another device, driver or header version. + auto differs = [&](int offset, std::uint32_t value) { + std::uint8_t changed[store::header_bytes]; + std::memcpy(changed, header, sizeof(changed)); + put32(changed + offset, value); + return !store::header_matches(changed, sizeof(changed), identity); + }; + CHECK(differs(0, store::header_bytes + 4)); + CHECK(differs(4, store::header_version_one + 1)); + CHECK(differs(8, identity.vendor + 1)); + CHECK(differs(12, identity.device + 1)); + std::uint8_t uuid[store::header_bytes]; + std::memcpy(uuid, header, sizeof(uuid)); + uuid[16] ^= 0xff; + CHECK(!store::header_matches(uuid, sizeof(uuid), identity)); + // vendorID/deviceID are u32s little-endian; the same bytes read the other way name another device. + leonida::cached_pso::Identity swapped = identity; + swapped.vendor = 0x02100000; + CHECK(!store::header_matches(header, sizeof(header), swapped)); + return 0; +} + +int main() { + if (const int failed = test_limit()) return failed; + return test_header(); +} diff --git a/runtime/test/vk_pipeline_check.cpp b/runtime/test/vk_pipeline_check.cpp index 00b58901b4..12260b1bef 100644 --- a/runtime/test/vk_pipeline_check.cpp +++ b/runtime/test/vk_pipeline_check.cpp @@ -47,7 +47,7 @@ // pipelines stage's retry. #include "vulkan_loader.h" #include "vk_device_pick.h" -#include "pipeline_cache_file.h" +#include "../src/pipeline_cache_file.h" #include "pipeline_cache_snapshot.h" #include "large_module_gate.h" #include "pipeline_summary.h" From 86cd0c5f2a392f6637ff5724d2786b12084b28b7 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Mon, 23 Nov 2026 17:45:10 +0100 Subject: [PATCH 03/27] d3d12: draw the console's rectangle lists (17, PSO type 19) and quad lists (19) as triangles A rectangle list is three corners; the fourth is v2 + v3 - v1 for the position and every interpolant, after the vertex stage. A quad list is four vertices per quad. Vulkan has neither. A PSO with topology type 19 was refused (E_INVALIDARG) and the two list topologies drew as a plain triangle list. Rectangle list: the PSO becomes a triangle-list pipeline with a generated geometry stage (src/rect_list_geometry.h), built from the vertex shader's own SPIR-V outputs, that emits the strip v1 v2 v3 v4. Quad list: one triangle fan per quad (0 1 2, 0 2 3), drawn with the index values 4q..4q+3 so the translated vertex id (VertexIndex - BaseVertex) is right; non-indexed draws read a shared 0, 1, 2, ... buffer reserved in the arena. Facts from xvalkyrie (GPL-3.0, commit 53af7df77c10); no code copied. --- docs/d3d12_vulkan.md | 8 +- runtime/CMakeLists.txt | 9 + runtime/shims/d3d12_vulkan_device.cpp | 45 +++- runtime/src/rect_list_geometry.h | 214 ++++++++++++++++ runtime/src/vulkan_backend.h | 8 + runtime/src/vulkan_replay.h | 29 +++ runtime/test/d3d12_rect_list_test.cpp | 341 ++++++++++++++++++++++++++ 7 files changed, 649 insertions(+), 5 deletions(-) create mode 100644 runtime/src/rect_list_geometry.h create mode 100644 runtime/test/d3d12_rect_list_test.cpp diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 33b52d422f..76a8b16a7d 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -169,7 +169,7 @@ The command-list surface maps to the IR as follows: | `SetGraphicsRootSignature` / `SetComputeRootSignature` | state; select the pipeline layout and root map | | `Set*Root32BitConstant(s)` / `Set*Root*View` / `Set*RootDescriptorTable` | update root args; build the push-constant block at the draw/dispatch | | `SetDescriptorHeaps` | state; scan/populate the bindless arrays and hash table at execute | -| `IASetVertexBuffers` / `IASetIndexBuffer` / `IASetPrimitiveTopology` | state; bind arena buffer + offset, dynamic topology | +| `IASetVertexBuffers` / `IASetIndexBuffer` / `IASetPrimitiveTopology` | state; bind arena buffer + offset, dynamic topology. The console's rectangle list (17, PSO topology type 19) and quad list (19) are drawn as triangles, see *Console rectangle and quad lists* below | | `RSSetViewports` / `RSSetScissorRects` | state; dynamic viewport/scissor | | `OMSetRenderTargets` / `OMSetBlendFactor` / `OMSetStencilRef` | state; rendering scope and dynamic state | | `DrawInstanced` / `DrawIndexedInstanced` | command with a state snapshot | @@ -2080,6 +2080,12 @@ The trace will enumerate them. - **What it doesn't cover:** whether the console flattens a 3D `DispatchMesh` grid the same way. That is an open question in `docs/design.md`, "Mesh shaders"; the test shader reads the workgroup ID directly. +### Console rectangle and quad lists + +The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiveTopology(17)`, with a PSO whose topology type is 19) and quad list (`IASetPrimitiveTopology(19)`). The facts are from xvalkyrie (GPL-3.0, commit `53af7df77c10`; no code taken): a rectangle is three corners and the fourth is v2 + v3 - v1 for the position and every interpolant, after the vertex stage; a quad is four vertices. The layer draws both as triangles (`d3d12_rect_list_test`, RTX 4090: 4096 of 4096 pixels, the colour plane exact, quad list bit-exact). +- **Rectangle list**: PSO type 19 builds a triangle-list pipeline plus a generated geometry stage (`src/rect_list_geometry.h`, written from the vertex shader's own outputs) that takes the three corners and emits the strip v1 v2 v3 v4 (same winding). It has to be post-vertex-stage: the translated vertex shaders fetch by V# themselves, and the fourth corner is a function of what they write. A corner value with the same bits at all three corners (a flat attribute) is copied. Needs `geometryShader` (else `E_NOTIMPL`), no application GS, and a vertex shader with no ClipDistance, CullDistance, Layer or ViewportIndex output. +- **Quad list**: one four-vertex triangle fan per quad (the pattern 0 1 2, 0 2 3). The translated vertex id is `VertexIndex - BaseVertex`, so each fan reads the index values 4q..4q+3: from the application's index buffer when the draw is indexed, else from a shared 0, 1, 2, ... buffer in the arena's reserved pages (16384 quads per draw at most), with the draw's first vertex as the vertex offset. The PSO type is the ordinary triangle type. + ## 4. Object model mapping | D3D12 / Xbox object | Vulkan / layer object | Notes | diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 2ab8c7bc84..3be2911a9e 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2099,6 +2099,15 @@ if(TARGET Vulkan::Headers) add_test(NAME d3d12_translated_draw COMMAND d3d12_translated_draw_test) set_tests_properties(d3d12_translated_draw PROPERTIES SKIP_RETURN_CODE 77) + # The console's rectangle and quad lists (src/rect_list_geometry.h), through the same translated vs_m15 / ps_m15. + add_executable(d3d12_rect_list_test test/d3d12_rect_list_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_M15_FILES}) + target_link_libraries(d3d12_rect_list_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_rect_list_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_M15_DIR="${LEONIDA_M15_DIR}") + target_compile_options(d3d12_rect_list_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_rect_list COMMAND d3d12_rect_list_test) + set_tests_properties(d3d12_rect_list PROPERTIES SKIP_RETURN_CODE 77) + # vk_bindless_test (the bindless set and its table at the Vulkan level, no D3D12) takes the translated vs_ids, # ps_tex and ps_imgatomic; it was only run by scripts/run_gpu_tests.py and check.py until D3D-314 needed it. set(LEONIDA_BINDLESS_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/bindless_shaders) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index c7e3d99942..fbeccc3d34 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -18,6 +18,7 @@ #include "../src/arena_size.h" #include "../src/gfx10_descriptors.h" #include "../src/depth24_fragment.h" +#include "../src/rect_list_geometry.h" #include "../src/uav_clear.h" #include "../src/vulkan_bindless.h" #include "../src/vulkan_memory.h" @@ -64,7 +65,9 @@ namespace { constexpr UINT kDescriptorSize = descriptor_size; // The first 64 KiB of the GPU address arena are never handed out: VA 0 stays invalid, and the page is kept zero // for unbound vertex and index buffers to read (D3D12 reads zeros there). -constexpr VkDeviceSize kArenaReserved = 64 * 1024; +constexpr VkDeviceSize kZeroPage = 64 * 1024; // zeroed: what unbound vertex and index buffers read +constexpr std::uint32_t kQuadIndexCount = 64 * 1024; // 0, 1, 2, ... that non-indexed quad lists draw with (16384 quads) +constexpr VkDeviceSize kArenaReserved = kZeroPage + VkDeviceSize(kQuadIndexCount) * sizeof(std::uint32_t); static_assert(sizeof(leonida::TargetView) <= kDescriptorSize); // The shader model and root signature version this layer can honour. Nothing in the runtime compiles DXIL: the @@ -3189,6 +3192,14 @@ class PipelineState final log_once("geometry shaders need the Vulkan geometryShader feature; stage", 0); return E_NOTIMPL; } + // The console's rectangle topology type (19) draws as triangles through a generated geometry stage that adds + // each rectangle's fourth corner (src/rect_list_geometry.h); it needs the same device feature, and no GS of + // the application's own. + const bool rect_list = !mesh && desc.PrimitiveTopologyType == leonida::topology_type_rect_list; + if (rect_list && (geometry || !device_.info.features.geometryShader)) { + log_once("a rectangle-list pipeline needs the geometryShader feature and no geometry shader; stage", 0); + return geometry ? E_INVALIDARG : E_NOTIMPL; + } if (geometry && desc.PrimitiveTopologyType != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) { log_once("a translated geometry shader takes triangles; topology type", desc.PrimitiveTopologyType); return E_INVALIDARG; @@ -3378,6 +3389,26 @@ class PipelineState final subgroup_size_for(*stage.entry, required_sizes[stage_infos.size()], info); stage_infos.push_back(info); } + if (rect_list) { // the stage that adds each rectangle's fourth corner, from the vertex shader's outputs + std::string why; + const std::vector words = leonida::rect_list_geometry(vs_stage.words, why); + if (words.empty()) { + std::fprintf(stderr, "[rt] d3d12: %s cannot be drawn as a rectangle list: %s\n", + vs_stage.entry->name.c_str(), why.c_str()); + return E_NOTIMPL; + } + VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + module_info.codeSize = words.size() * 4; + module_info.pCode = words.data(); + VkShaderModule module = VK_NULL_HANDLE; + if (vk.vkCreateShaderModule(dev, &module_info, nullptr, &module) != VK_SUCCESS) return E_FAIL; + modules_.push_back(module); + VkPipelineShaderStageCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; + info.stage = VK_SHADER_STAGE_GEOMETRY_BIT; + info.module = module; + info.pName = "main"; + stage_infos.push_back(info); + } if (depth24_fragment && !ps_stage.entry) { // no pixel shader: a built-in one writes the depth const std::vector words = leonida::depth24_depth_only_fragment(depth24_bias); VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; @@ -3452,7 +3483,8 @@ class PipelineState final } } VkPipelineInputAssemblyStateCreateInfo assembly{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; - switch (mesh ? D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE : desc.PrimitiveTopologyType) { // mesh: not used + // Type 19 is the console's rectangles, drawn as triangle lists through the geometry stage added above. + switch (mesh || rect_list ? D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE : desc.PrimitiveTopologyType) { // mesh: not used case D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT: assembly.topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST; break; case D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE: assembly.topology = VK_PRIMITIVE_TOPOLOGY_LINE_LIST; break; case D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE: assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; break; @@ -5168,7 +5200,11 @@ class Device final return false; } arena.mapped = static_cast(mapped); - std::memset(arena.mapped, 0, kArenaReserved); // the zero page unbound vertex and index buffers read + std::memset(arena.mapped, 0, kZeroPage); // the zero page unbound vertex and index buffers read + { + auto* iota = reinterpret_cast(arena.mapped + kZeroPage); + for (std::uint32_t i = 0; i < kQuadIndexCount; ++i) iota[i] = i; + } VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; address.buffer = arena.buffer; arena.address = vk.vkGetBufferDeviceAddress(state_.info.device, &address); @@ -5179,7 +5215,8 @@ class Device final length = 0; arena.log = getenv_s(&length, log, "LEONIDA_ARENA_LOG") == 0 && length > 1 && log[0] != '0'; state_.context->set_heap_base(arena.address); - state_.context->set_zero_page(arena.buffer, 0, kArenaReserved); + state_.context->set_zero_page(arena.buffer, 0, kZeroPage); + state_.context->set_quad_indices(arena.buffer, kZeroPage, kQuadIndexCount); return true; } diff --git a/runtime/src/rect_list_geometry.h b/runtime/src/rect_list_geometry.h new file mode 100644 index 0000000000..ee7d69905c --- /dev/null +++ b/runtime/src/rect_list_geometry.h @@ -0,0 +1,214 @@ +#pragma once + +// Console rectangle lists on Vulkan, which has no such primitive. +// +// A rectangle is three corners (v1, v2, v3) and the hardware makes the fourth, v2 + v3 - v1, for the position and for +// every interpolant, after the vertex stage. A list topology of rectangles (D3D_PRIMITIVE_TOPOLOGY 17) and a pipeline +// whose topology type is 19 are console-only. The fact comes from xvalkyrie (GPL-3.0, commit 53af7df77c10, notes in +// its backlog); no code is taken from it. +// +// The fourth vertex depends on what the vertex stage wrote, not on what it read, so the expansion has to sit after +// the vertex stage: a pre-pass over the vertex buffers is wrong for any shader that is not linear in its inputs (and +// the translated vertex shaders fetch by V# themselves, so there is no vertex buffer to expand). The pipeline gets a +// small geometry stage instead, built here from the vertex shader's own SPIR-V: it takes the triangle (v1, v2, v3) +// the list draws, and emits the strip v1, v2, v3, v4, which is the two triangles (v1, v2, v3) and (v3, v2, v4) of the +// parallelogram with the same winding. Every Location output of the vertex stage is a vec4 float in the translator's +// output (rdna2spirv.py), and so is the stage's Position; the generated stage reads and writes exactly those. A value +// that is the same bit pattern at all three corners (a flat attribute, which may hold integer bits) is copied rather +// than computed, so it cannot turn into a NaN. +// +// Not covered, and refused with a reason: a vertex stage that writes ClipDistance, CullDistance, Layer or +// ViewportIndex, or a Location output that is not a vec4 float. +// +// Plain word editing, standard library only. + +#include +#include +#include +#include +#include +#include +#include + +namespace leonida { + +// D3D_PRIMITIVE_TOPOLOGY values and the PSO topology type of the console's rectangle and quad lists. +constexpr std::uint32_t topology_rect_list = 17; +constexpr std::uint32_t topology_quad_list = 19; +constexpr std::uint32_t topology_type_rect_list = 19; + +// The geometry stage for `vertex_words`' outputs; empty, with `why` set, when the vertex stage cannot be expanded. +inline std::vector rect_list_geometry(const std::vector& vertex_words, std::string& why) { + enum : std::uint32_t { + op_entry_point = 15, op_type_void = 19, op_type_bool = 20, op_type_int = 21, op_type_float = 22, + op_type_vector = 23, op_type_array = 28, op_type_pointer = 32, op_type_function = 33, op_constant = 43, + op_function = 54, op_function_end = 56, op_variable = 59, op_load = 61, op_store = 62, op_access_chain = 65, + op_decorate = 71, op_bitcast = 124, op_fadd = 129, op_fsub = 131, op_logical_and = 167, op_select = 169, + op_iequal = 170, op_emit_vertex = 218, op_end_primitive = 219, op_label = 248, op_return = 253, + op_capability = 17, op_memory_model = 14, op_execution_mode = 16, + deco_builtin = 11, deco_location = 30, builtin_position = 0, builtin_point_size = 1, + storage_input = 1, storage_output = 3 + }; + why.clear(); + if (vertex_words.size() < 6 || vertex_words[0] != 0x07230203u) { + why = "the vertex shader is not a SPIR-V module"; + return {}; + } + // What the vertex stage declares: types, Output variables, and the decorations that name them. + struct Type { std::uint32_t op = 0, component = 0, count = 0, width = 0; }; + std::map types; + std::map variable_type; // Output variable -> its pointer type + std::map location, builtin; // variable id -> value + std::set outputs; + for (std::size_t i = 5; i < vertex_words.size();) { + const std::uint32_t op = vertex_words[i] & 0xffffu, n = vertex_words[i] >> 16; + if (!n || i + n > vertex_words.size()) { + why = "the vertex shader's SPIR-V is cut short"; + return {}; + } + const std::uint32_t* w = &vertex_words[i]; + if (op == op_type_float && n >= 3) types[w[1]] = {op, 0, 0, w[2]}; + else if (op == op_type_vector && n >= 4) types[w[1]] = {op, w[2], w[3], 0}; + else if (op == op_type_pointer && n >= 4) types[w[1]] = {op, w[3], w[2], 0}; + else if (op == op_variable && n >= 4 && w[3] == storage_output) outputs.insert(w[2]), variable_type[w[2]] = w[1]; + else if (op == op_decorate && n >= 4 && w[2] == deco_location) location[w[1]] = w[3]; + else if (op == op_decorate && n >= 4 && w[2] == deco_builtin) builtin[w[1]] = w[3]; + i += n; + } + std::uint32_t position = 0; + std::vector params; // Location values, ascending + for (std::uint32_t id : outputs) { + const auto b = builtin.find(id); + if (b != builtin.end()) { + if (b->second == builtin_position) position = id; + else if (b->second != builtin_point_size) { + why = "the vertex shader writes ClipDistance, CullDistance, Layer or ViewportIndex"; + return {}; + } + continue; + } + const auto l = location.find(id); + if (l == location.end()) continue; + const Type& ptr = types[variable_type[id]]; + const Type& vec = types[ptr.component]; + const Type& scalar = types[vec.component]; + if (vec.op != op_type_vector || vec.count != 4 || scalar.op != op_type_float || scalar.width != 32) { + why = "a vertex output is not a vec4 float"; + return {}; + } + params.push_back(l->second); + } + if (!position) { + why = "the vertex shader writes no Position"; + return {}; + } + std::sort(params.begin(), params.end()); + params.erase(std::unique(params.begin(), params.end()), params.end()); + + // The module: a fixed prelude, then per variable ids, then the body. Ids count up from 1. + std::uint32_t next = 1; + const auto id = [&] { return next++; }; + std::vector head, annotations, globals, body; + const auto emit = [](std::vector& to, std::uint32_t op, std::initializer_list args) { + to.push_back((std::uint32_t(args.size()) + 1) << 16 | op); + to.insert(to.end(), args.begin(), args.end()); + }; + const std::uint32_t t_void = id(), t_fn = id(), t_uint = id(), t_float = id(), t_v4 = id(), t_bool = id(), + t_v4bool = id(), t_v4uint = id(), c3 = id(), t_arr = id(), t_pin_arr = id(), t_pin_v4 = id(), + t_pout_v4 = id(), c0 = id(), c1 = id(), c2 = id(); + emit(globals, op_type_void, {t_void}); + emit(globals, op_type_function, {t_fn, t_void}); + emit(globals, op_type_int, {t_uint, 32, 0}); + emit(globals, op_type_float, {t_float, 32}); + emit(globals, op_type_vector, {t_v4, t_float, 4}); + emit(globals, op_type_bool, {t_bool}); + emit(globals, op_type_vector, {t_v4bool, t_bool, 4}); + emit(globals, op_type_vector, {t_v4uint, t_uint, 4}); + emit(globals, op_constant, {t_uint, c3, 3}); + emit(globals, op_constant, {t_uint, c0, 0}); + emit(globals, op_constant, {t_uint, c1, 1}); + emit(globals, op_constant, {t_uint, c2, 2}); + emit(globals, op_type_array, {t_arr, t_v4, c3}); + emit(globals, op_type_pointer, {t_pin_arr, storage_input, t_arr}); + emit(globals, op_type_pointer, {t_pin_v4, storage_input, t_v4}); + emit(globals, op_type_pointer, {t_pout_v4, storage_output, t_v4}); + + struct Var { std::uint32_t in, out; bool is_position; }; + std::vector vars; + vars.push_back({id(), id(), true}); + for (std::size_t i = 0; i < params.size(); ++i) vars.push_back({id(), id(), false}); + std::vector io_vars; + emit(annotations, op_decorate, {vars[0].in, deco_builtin, builtin_position}); + emit(annotations, op_decorate, {vars[0].out, deco_builtin, builtin_position}); + for (std::size_t i = 0; i < params.size(); ++i) { + emit(annotations, op_decorate, {vars[i + 1].in, deco_location, params[i]}); + emit(annotations, op_decorate, {vars[i + 1].out, deco_location, params[i]}); + } + for (const Var& v : vars) { + emit(globals, op_variable, {t_pin_arr, v.in, storage_input}); + emit(globals, op_variable, {t_pout_v4, v.out, storage_output}); + io_vars.push_back(v.in); + io_vars.push_back(v.out); + } + + const std::uint32_t main_fn = id(), entry_label = id(); + emit(body, op_function, {t_void, main_fn, 0, t_fn}); + emit(body, op_label, {entry_label}); + // Per variable: the three corners, and the fourth. The fourth is v2 + v3 - v1, except where all three corners + // have the same bits (a flat value), where it is v1. + struct Corners { std::uint32_t v[4]; }; + std::vector corners; + const std::uint32_t cs[3] = {c0, c1, c2}; + for (const Var& v : vars) { + Corners c{}; + for (int k = 0; k < 3; ++k) { + const std::uint32_t ptr = id(); + c.v[k] = id(); + emit(body, op_access_chain, {t_pin_v4, ptr, v.in, cs[k]}); + emit(body, op_load, {t_v4, c.v[k], ptr}); + } + const std::uint32_t sum = id(), diff = id(); + emit(body, op_fadd, {t_v4, sum, c.v[1], c.v[2]}); + emit(body, op_fsub, {t_v4, diff, sum, c.v[0]}); + if (v.is_position) { + c.v[3] = diff; + } else { + const std::uint32_t b0 = id(), b1 = id(), b2 = id(), e1 = id(), e2 = id(), same = id(), pick = id(); + emit(body, op_bitcast, {t_v4uint, b0, c.v[0]}); + emit(body, op_bitcast, {t_v4uint, b1, c.v[1]}); + emit(body, op_bitcast, {t_v4uint, b2, c.v[2]}); + emit(body, op_iequal, {t_v4bool, e1, b1, b0}); + emit(body, op_iequal, {t_v4bool, e2, b2, b0}); + emit(body, op_logical_and, {t_v4bool, same, e1, e2}); + emit(body, op_select, {t_v4, pick, same, c.v[0], diff}); + c.v[3] = pick; + } + corners.push_back(c); + } + // The strip v1, v2, v3, v4. + for (int k = 0; k < 4; ++k) { + for (std::size_t i = 0; i < vars.size(); ++i) emit(body, op_store, {vars[i].out, corners[i].v[k]}); + emit(body, op_emit_vertex, {}); + } + emit(body, op_end_primitive, {}); + emit(body, op_return, {}); + emit(body, op_function_end, {}); + + std::vector out{0x07230203u, 0x00010000u, 0, next, 0}; + emit(out, op_capability, {19}); // Geometry + emit(out, op_memory_model, {0, 1}); // Logical, GLSL450 + std::vector entry{3, main_fn, 0x6e69616du, 0}; // Geometry, %main, "main" + entry.insert(entry.end(), io_vars.begin(), io_vars.end()); + out.push_back((std::uint32_t(entry.size()) + 1) << 16 | op_entry_point); + out.insert(out.end(), entry.begin(), entry.end()); + emit(out, op_execution_mode, {main_fn, 22}); // Triangles + emit(out, op_execution_mode, {main_fn, 0, 1}); // Invocations 1 + emit(out, op_execution_mode, {main_fn, 29}); // OutputTriangleStrip + emit(out, op_execution_mode, {main_fn, 26, 4}); // OutputVertices 4 + out.insert(out.end(), annotations.begin(), annotations.end()); + out.insert(out.end(), globals.begin(), globals.end()); + out.insert(out.end(), body.begin(), body.end()); + return out; +} + +} // namespace leonida diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index e659a762dc..b05f5fc1ad 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -1247,6 +1247,14 @@ class VulkanContext { replay_.zero_size = size; } + // 0, 1, 2, ... as 32-bit indices, for non-indexed quad lists (ReplayFunctions::quad_indices). + void set_quad_indices(VkBuffer buffer, VkDeviceSize offset, std::uint32_t count) { + std::unique_lock lock(resource_mutex_); + replay_.quad_indices = buffer; + replay_.quad_indices_offset = offset; + replay_.quad_index_count = count; + } + // Physical-device COLOR_ATTACHMENT format check for reinterpreted UAV clears. void set_color_attachment_format(std::function check) { std::unique_lock lock(resource_mutex_); diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 1e0e598c7f..d519fe822e 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -32,6 +32,7 @@ #include "command_list.h" #include "depth24.h" +#include "rect_list_geometry.h" #include "uav_clear.h" #include @@ -866,6 +867,10 @@ struct ReplayFunctions { VkBuffer zero_buffer = VK_NULL_HANDLE; VkDeviceSize zero_offset = 0; VkDeviceSize zero_size = 0; + // 0, 1, 2, ... as 32-bit indices: what a non-indexed quad list is drawn with (quad_index_count of them). + VkBuffer quad_indices = VK_NULL_HANDLE; + VkDeviceSize quad_indices_offset = 0; + std::uint32_t quad_index_count = 0; std::uint64_t heap_base = 0; // device address of the GPU address arena (push-constant dwords 32-33) // Resolves available binary-occlusion queries to 64-bit 0/1 values, outside conditional rendering. std::functionzero_step_slots & (1u << slot)) ? 0 : view.stride; } + // A non-indexed quad list is drawn from the shared 0, 1, 2, ... index buffer (emit). + if (!draw.indexed && !draw.mesh && draw.topology == topology_quad_list && !vk.quad_indices) + return ReplayResult::unresolved_resource; if (draw.indexed) { if (draw.index.format == 57) p.index_type = VK_INDEX_TYPE_UINT16; else if (draw.index.format == 42) p.index_type = VK_INDEX_TYPE_UINT32; @@ -2210,6 +2218,11 @@ inline VkPrimitiveTopology vulkan_topology(std::uint32_t topology) { case 11: return VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY; case 12: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY; case 13: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY; + // The console's lists (rect_list_geometry.h). A rectangle list is drawn as the triangle list of its three + // corners, the pipeline's geometry stage adds the fourth. A quad (v0 v1 v2 v3) is the fan (v0 v1 v2) (v0 v2 v3), + // which is the index pattern 0 1 2, 0 2 3; the draw below issues one fan per quad. + case topology_rect_list: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + case topology_quad_list: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN; default: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; } } @@ -4106,6 +4119,22 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c } if (draw->mesh) { vk.draw_mesh_tasks(command_buffer, draw->count, draw->instances, draw->first); + } else if (draw->topology == topology_quad_list) { + // One four-vertex fan per quad. The translated vertex shaders take their vertex id from the index + // value (VertexIndex - BaseVertex), so a fan must be drawn with the index values 4q..4q+3: an + // indexed draw reads them from the application's index buffer, a non-indexed one from the + // shared 0, 1, 2, ... buffer (quad_indices), with the draw's first vertex as the vertex offset, as + // VertexIndex is first + i for a plain draw. + const bool generated = !draw->indexed; // prepare() has checked that quad_indices is there + if (generated) + vk.bind_index_buffer(command_buffer, vk.quad_indices, vk.quad_indices_offset, VK_INDEX_TYPE_UINT32); + else + vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type); + const std::uint32_t quads = std::min(draw->count / 4, generated ? vk.quad_index_count / 4 : UINT32_MAX); + const std::int32_t vertex_offset = generated ? std::int32_t(draw->first) : draw->base_vertex; + for (std::uint32_t quad = 0; quad < quads; ++quad) + vk.draw_indexed(command_buffer, 4, draw->instances, (generated ? 0 : draw->first) + 4 * quad, + vertex_offset, draw->first_instance); } else if (draw->indexed) { vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type); vk.draw_indexed(command_buffer, draw->count, draw->instances, draw->first, draw->base_vertex, diff --git a/runtime/test/d3d12_rect_list_test.cpp b/runtime/test/d3d12_rect_list_test.cpp new file mode 100644 index 0000000000..05b90a81c8 --- /dev/null +++ b/runtime/test/d3d12_rect_list_test.cpp @@ -0,0 +1,341 @@ +// The console's rectangle and quad lists drawn through the D3D12-on-Vulkan layer (src/rect_list_geometry.h). +// +// Built like d3d12_translated_draw_test.cpp, from the same translated vs_m15 / ps_m15 (the VS fetches its vertices +// through a V#; the PS multiplies the colour by (0.5, 2, 1, 1) and adds the bias, 0 here), so the shaders are real +// translator output found by the SHA-256 of their FSSM programs. +// frame 1, rectangle list: PSO topology type 19, IASetPrimitiveTopology(17), DrawInstanced(3). The three corners +// v1 (-1, 1), v2 (1, 1), v3 (-1, -1) cover the top-left, top-right and bottom-left of the 64x64 target; the fourth +// corner, v2 + v3 - v1 = (1, -1) with colour c2 + c3 - c1, is made by the layer. Every pixel must carry the plane +// through the three corner colours; the bottom-right quadrant is only right when the fourth corner is. +// frame 2, quad list: PSO topology type TRIANGLE, IASetPrimitiveTopology(19), DrawInstanced(8): two quads (corners +// in order around the quad), the top-left and bottom-right quadrants, each one colour. These pixels are exact. +// Pixels are read back and compared; the other two quadrants of frame 2 stay the clear colour. LEONIDA_VK_VALIDATION=1 +// runs it under the validation layer. +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include "../src/gfx10_descriptors.h" +#include "../src/shader_library.h" + +#include +#include +#include +#include +#include +#include + +#ifndef LEONIDA_TEST_M15_DIR +#error "LEONIDA_TEST_M15_DIR must name the folder build.py wrote (spirv/index.json, fssm/*.fssm)" +#endif + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +using namespace d3d12test; +using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10: handle in RAX + +namespace { + +std::vector read_file(const std::filesystem::path& path) { + std::ifstream in(path, std::ios::binary); + return {std::istreambuf_iterator(in), std::istreambuf_iterator()}; +} + +struct Vertex { // 32 bytes, as vs_m15.asm reads it + float position[4]; + float color[4]; +}; + +using Pixel = std::array; +constexpr UINT target_extent = 64; +constexpr UINT pitch = target_extent * sizeof(Pixel); +constexpr D3D_PRIMITIVE_TOPOLOGY rect_list = D3D_PRIMITIVE_TOPOLOGY(17), quad_list = D3D_PRIMITIVE_TOPOLOGY(19); +const std::uint32_t rect_type_value = 19; // not an enumerator of D3D12_PRIMITIVE_TOPOLOGY_TYPE + +std::array make_vsharp(std::uint64_t base, std::uint32_t records) { + leonida::gfx10::Buffer buffer; + buffer.address = base; + buffer.stride = 32; + buffer.num_records = records; + buffer.format = 77; // GFX10_FORMAT_32_32_32_32_FLOAT + buffer.oob_select = leonida::gfx10::OobSelect::structured; + return leonida::gfx10::encode(buffer); +} + +Vertex vertex(float x, float y, const float* c) { return Vertex{{x, y, 0.0f, 1.0f}, {c[0], c[1], c[2], c[3]}}; } + +} // namespace + +int main() { + vktest::Device d; + const auto device_status = d.initialize(); + if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips + EXPECT(device_status == vktest::DeviceStatus::ready); + if (!d.enabled.geometryShader) { + std::printf("SKIP: no geometryShader on this GPU\n"); + return 77; + } + const std::filesystem::path root_dir = LEONIDA_TEST_M15_DIR; + const auto vs_program = read_file(root_dir / "fssm" / "vs_m15.fssm"); + const auto ps_program = read_file(root_dir / "fssm" / "ps_m15.fssm"); + EXPECT(vs_program.size() >= 4 && ps_program.size() == 0x110); + const auto vs_container = shader_container(vs_program), ps_container = shader_container(ps_program); + + // Frame 1: the rectangle's three corners. Vertices 0..2. Frame 2: two quads, vertices 3..10. + const float ca[4] = {0.0f, 0.0f, 0.0f, 1.0f}, cb[4] = {1.0f, 0.0f, 0.5f, 1.0f}, cc[4] = {0.0f, 0.5f, 1.0f, 1.0f}; + const float q1[4] = {0.25f, 0.5f, 0.75f, 1.0f}, q2[4] = {1.0f, 0.0f, 0.5f, 1.0f}; + const Vertex vertices[11] = {vertex(-1, 1, ca), vertex(1, 1, cb), vertex(-1, -1, cc), + vertex(-1, 1, q1), vertex(0, 1, q1), vertex(0, 0, q1), vertex(-1, 0, q1), + vertex(0, 0, q2), vertex(1, 0, q2), vertex(1, -1, q2), vertex(0, -1, q2)}; + static_assert(sizeof(Vertex) == 32 && sizeof(vertices) == 352); + + std::vector rect_pixels(target_extent * target_extent), quad_pixels(target_extent * target_extent); + { + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = d.instance_proc; + info.instance = d.instance; + info.physical = d.physical; + info.device = d.device; + info.queue = d.queue; + info.queue_family = d.family; + info.buffer_device_address = true; + info.features = d.enabled; // geometryShader: the rectangle stage needs it + info.shader_dir = (root_dir / "spirv").string(); + ID3D12Device* inner = nullptr; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); + Ref device; + EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), + reinterpret_cast(&device.p)))); + rt::d3d12::set_device_outer(inner, device.p); + + D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; + D3D12_ROOT_PARAMETER params[2] = {}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[0].DescriptorTable = {1, &range}; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[1].Constants = {0, 0, 4}; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; + root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + root_desc.Desc_1_0 = {2, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + const auto root_blob = serialize_root_signature(root_desc); + EXPECT(!root_blob.empty()); + Ref root; + EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p)))); + + D3D12_GRAPHICS_PIPELINE_STATE_DESC pso_desc{}; + pso_desc.pRootSignature = root.p; + pso_desc.VS = {vs_container.data(), vs_container.size()}; + pso_desc.PS = {ps_container.data(), ps_container.size()}; + pso_desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + pso_desc.SampleMask = 0xffffffff; + pso_desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + pso_desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + pso_desc.RasterizerState.DepthClipEnable = TRUE; + pso_desc.NumRenderTargets = 1; + pso_desc.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT; + pso_desc.SampleDesc.Count = 1; + Ref rect_pso, quad_pso; + std::memcpy(&pso_desc.PrimitiveTopologyType, &rect_type_value, sizeof(rect_type_value)); // 19: rectangles + EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&rect_pso.p)))); + pso_desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&quad_pso.p)))); + + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; + const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + Ref vertex_buffer, upload, readback, target; + const auto vb_desc = buffer_desc(sizeof(vertices)); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &vb_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&vertex_buffer.p)))); + const auto upload_desc = buffer_desc(1024); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &upload_desc, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + IID_PPV_ARGS(&upload.p)))); + const auto readback_desc = buffer_desc(pitch * target_extent); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.p)))); + D3D12_RESOURCE_DESC rt_desc{}; + rt_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + rt_desc.Width = rt_desc.Height = target_extent; + rt_desc.DepthOrArraySize = 1; + rt_desc.MipLevels = 1; + rt_desc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + rt_desc.SampleDesc.Count = 1; + rt_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &rt_desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&target.p)))); + std::uint8_t* up = nullptr; + EXPECT(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast(&up)))); + std::memcpy(up, vertices, sizeof(vertices)); + + // Two V#s over the one vertex buffer: slot 0 the rectangle's three corners, slot 1 the eight quad corners. + const D3D12_DESCRIPTOR_HEAP_DESC srv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + Ref srv_heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&srv_heap_desc, IID_PPV_ARGS(&srv_heap.p)))); + const std::uint64_t cpu = reinterpret_cast(slot(srv_heap.p, 9))(srv_heap.p); + const std::uint64_t gpu = reinterpret_cast(slot(srv_heap.p, 10))(srv_heap.p); + const UINT step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + EXPECT(cpu && gpu >= 0x10000 && gpu < (1ull << 32) && step >= 16); + const std::uint64_t buffer_va = vertex_buffer->GetGPUVirtualAddress(); + EXPECT(buffer_va >= 0x10000); + const std::array vsharps[2] = {make_vsharp(buffer_va, 3), + make_vsharp(buffer_va + 3 * sizeof(Vertex), 8)}; + for (unsigned i = 0; i < 2; ++i) + std::memcpy(reinterpret_cast(cpu + std::uint64_t(i) * step), vsharps[i].data(), 16); + + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + Ref rtv_heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&rtv_heap.p)))); + const D3D12_CPU_DESCRIPTOR_HANDLE rtv{ + SIZE_T(reinterpret_cast(slot(rtv_heap.p, 9))(rtv_heap.p))}; + device->CreateRenderTargetView(target.p, nullptr, rtv); + + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + Ref queue; + Ref allocator; + Ref list; + Ref fence; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, rect_pso.p, + IID_PPV_ARGS(&list.p)))); + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + + list->CopyBufferRegion(vertex_buffer.p, 0, upload.p, 0, sizeof(vertices)); + D3D12_RESOURCE_BARRIER barriers[2] = { + transition(vertex_buffer.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE), + transition(target.p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET)}; + list->ResourceBarrier(2, barriers); + + const auto render_frame = [&](UINT64 frame, ID3D12PipelineState* pso, D3D_PRIMITIVE_TOPOLOGY topology, + unsigned vsharp_slot, UINT vertex_count, std::vector& out) -> int { + if (frame > 1) { + EXPECT(SUCCEEDED(allocator->Reset())); + EXPECT(SUCCEEDED(list->Reset(allocator.p, pso))); + auto to_target = transition(target.p, D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_RENDER_TARGET); + list->ResourceBarrier(1, &to_target); + } else { + list->SetPipelineState(pso); + } + const FLOAT clear[4] = {0.5f, 0.125f, 0.25f, 0.5f}; + list->ClearRenderTargetView(rtv, clear, 0, nullptr); + list->SetGraphicsRootSignature(root.p); + ID3D12DescriptorHeap* heaps[] = {srv_heap.p}; + list->SetDescriptorHeaps(1, heaps); + list->IASetPrimitiveTopology(topology); + const D3D12_VIEWPORT viewport{0, 0, float(target_extent), float(target_extent), 0, 1}; + const D3D12_RECT scissor{0, 0, LONG(target_extent), LONG(target_extent)}; + list->RSSetViewports(1, &viewport); + list->RSSetScissorRects(1, &scissor); + list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); + const float constants[4] = {0, 0, 0, 0}; // no offset, no bias + list->SetGraphicsRootDescriptorTable(0, D3D12_GPU_DESCRIPTOR_HANDLE{gpu + std::uint64_t(vsharp_slot) * step}); + list->SetGraphicsRoot32BitConstants(1, 4, constants, 0); + list->DrawInstanced(vertex_count, 1, 0, 0); + D3D12_RESOURCE_BARRIER to_copy = transition(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &to_copy); + D3D12_TEXTURE_COPY_LOCATION dst{}; + dst.pResource = readback.p; + dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst.PlacedFootprint = {0, {DXGI_FORMAT_R32G32B32A32_FLOAT, target_extent, target_extent, 1, pitch}}; + D3D12_TEXTURE_COPY_LOCATION src{}; + src.pResource = target.p; + src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + EXPECT(list->Close() == S_OK); + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); + EXPECT(SUCCEEDED(queue->Signal(fence.p, frame))); + EXPECT(SUCCEEDED(fence->SetEventOnCompletion(frame, nullptr))); + void* mapped = nullptr; + EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); + std::memcpy(out.data(), mapped, out.size() * sizeof(Pixel)); + readback->Unmap(0, nullptr); + return 0; + }; + EXPECT(render_frame(1, rect_pso.p, rect_list, 0, 3, rect_pixels) == 0); + EXPECT(render_frame(2, quad_pso.p, quad_list, 1, 8, quad_pixels) == 0); + for (auto* r : {&vertex_buffer, &upload, &readback, &target}) r->reset(); + rect_pso.reset(); + quad_pso.reset(); + root.reset(); + srv_heap.reset(); + rtv_heap.reset(); + list.reset(); + allocator.reset(); + queue.reset(); + fence.reset(); + EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); + } + + // Rectangle: the plane through the three corner colours, at each pixel centre, through the PS's scale. + const float scale[4] = {0.5f, 2.0f, 1.0f, 1.0f}; + unsigned covered = 0, off = 0; + float worst = 0.0f; + for (UINT row = 0; row < target_extent; ++row) { + for (UINT col = 0; col < target_extent; ++col) { + const float u = (float(col) + 0.5f) / target_extent, v = (float(row) + 0.5f) / target_extent; + const Pixel& got = rect_pixels[row * target_extent + col]; + bool pixel_ok = true; + for (int c = 0; c < 4; ++c) { + const float want = (ca[c] + u * (cb[c] - ca[c]) + v * (cc[c] - ca[c])) * scale[c]; + const float error = std::fabs(got[c] - want); + worst = std::fmax(worst, error); + if (!(error <= 2e-5f)) pixel_ok = false; + } + covered += pixel_ok; + if (!pixel_ok && off++ < 8) + std::fprintf(stderr, "rect pixel (%u, %u): got %g,%g,%g,%g\n", col, row, got[0], got[1], got[2], got[3]); + } + } + // The four quadrant centres on their own, so a wrong fourth corner is named by quadrant. + const char* names[4] = {"top left", "top right", "bottom left", "bottom right"}; + for (int quadrant = 0; quadrant < 4; ++quadrant) { + const UINT col = (quadrant & 1 ? 48 : 16), row = (quadrant & 2 ? 48 : 16); + const Pixel& got = rect_pixels[row * target_extent + col]; + const float u = (float(col) + 0.5f) / target_extent, v = (float(row) + 0.5f) / target_extent; + for (int c = 0; c < 4; ++c) { + const float want = (ca[c] + u * (cb[c] - ca[c]) + v * (cc[c] - ca[c])) * scale[c]; + if (!(std::fabs(got[c] - want) <= 2e-5f)) { + std::fprintf(stderr, "rect %s quadrant: channel %d got %g want %g\n", names[quadrant], c, got[c], want); + return 1; + } + } + } + EXPECT(covered == target_extent * target_extent); + + // Quad list: whole-bit comparison; two quadrants one colour each, the rest the clear colour. + const Pixel clear_color = {0.5f, 0.125f, 0.25f, 0.5f}; + const Pixel top_left = {q1[0] * scale[0], q1[1] * scale[1], q1[2], q1[3]}; + const Pixel bottom_right = {q2[0] * scale[0], q2[1] * scale[1], q2[2], q2[3]}; + unsigned quad_wrong = 0; + for (UINT row = 0; row < target_extent; ++row) { + for (UINT col = 0; col < target_extent; ++col) { + const bool top = row < target_extent / 2, left = col < target_extent / 2; + const Pixel& want = top && left ? top_left : (!top && !left ? bottom_right : clear_color); + const Pixel& got = quad_pixels[row * target_extent + col]; + if (std::memcmp(&got, &want, sizeof(Pixel)) == 0) continue; + if (quad_wrong++ < 8) + std::fprintf(stderr, "quad pixel (%u, %u): got %g,%g,%g,%g want %g,%g,%g,%g\n", col, row, got[0], got[1], + got[2], got[3], want[0], want[1], want[2], want[3]); + } + } + EXPECT(!quad_wrong); + if (d.validation_errors()) { + std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); + return 1; + } + std::printf("rect list: %u of %u pixels on the colour plane (worst error %g), all four quadrants; quad list: " + "%u of %u pixels exact\n", + covered, target_extent * target_extent, double(worst), target_extent * target_extent - quad_wrong, + target_extent * target_extent); + return 0; +} From a6b31d51ac5d4ea43e965539fd1793f7d995d6db Mon Sep 17 00:00:00 2001 From: tedin7 Date: Mon, 23 Nov 2026 17:48:05 +0100 Subject: [PATCH 04/27] d3d12: rectangle list stage emits (v1 v2 v4) (v1 v4 v3) with capability Geometry, log cut-off quads (review fixes) --- docs/d3d12_vulkan.md | 2 +- runtime/src/rect_list_geometry.h | 57 ++++++++++++-------------------- runtime/src/vulkan_replay.h | 11 +++++- 3 files changed, 33 insertions(+), 37 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 76a8b16a7d..3233715169 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2084,7 +2084,7 @@ The trace will enumerate them. The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiveTopology(17)`, with a PSO whose topology type is 19) and quad list (`IASetPrimitiveTopology(19)`). The facts are from xvalkyrie (GPL-3.0, commit `53af7df77c10`; no code taken): a rectangle is three corners and the fourth is v2 + v3 - v1 for the position and every interpolant, after the vertex stage; a quad is four vertices. The layer draws both as triangles (`d3d12_rect_list_test`, RTX 4090: 4096 of 4096 pixels, the colour plane exact, quad list bit-exact). - **Rectangle list**: PSO type 19 builds a triangle-list pipeline plus a generated geometry stage (`src/rect_list_geometry.h`, written from the vertex shader's own outputs) that takes the three corners and emits the strip v1 v2 v3 v4 (same winding). It has to be post-vertex-stage: the translated vertex shaders fetch by V# themselves, and the fourth corner is a function of what they write. A corner value with the same bits at all three corners (a flat attribute) is copied. Needs `geometryShader` (else `E_NOTIMPL`), no application GS, and a vertex shader with no ClipDistance, CullDistance, Layer or ViewportIndex output. -- **Quad list**: one four-vertex triangle fan per quad (the pattern 0 1 2, 0 2 3). The translated vertex id is `VertexIndex - BaseVertex`, so each fan reads the index values 4q..4q+3: from the application's index buffer when the draw is indexed, else from a shared 0, 1, 2, ... buffer in the arena's reserved pages (16384 quads per draw at most), with the draw's first vertex as the vertex offset. The PSO type is the ordinary triangle type. +- **Quad list**: one four-vertex triangle fan per quad (the pattern 0 1 2, 0 2 3). The translated vertex id is `VertexIndex - BaseVertex`, so each fan reads the index values 4q..4q+3: from the application's index buffer when the draw is indexed, else from a shared 0, 1, 2, ... buffer in the arena's reserved pages (16384 quads per draw at most, more are cut off with a log line), with the draw's first vertex as the vertex offset. A quad's instances are drawn together, so several overlapping blended instances rasterize quad by quad rather than instance by instance. The PSO type is the ordinary triangle type. ## 4. Object model mapping diff --git a/runtime/src/rect_list_geometry.h b/runtime/src/rect_list_geometry.h index ee7d69905c..335e4db00e 100644 --- a/runtime/src/rect_list_geometry.h +++ b/runtime/src/rect_list_geometry.h @@ -11,11 +11,10 @@ // the vertex stage: a pre-pass over the vertex buffers is wrong for any shader that is not linear in its inputs (and // the translated vertex shaders fetch by V# themselves, so there is no vertex buffer to expand). The pipeline gets a // small geometry stage instead, built here from the vertex shader's own SPIR-V: it takes the triangle (v1, v2, v3) -// the list draws, and emits the strip v1, v2, v3, v4, which is the two triangles (v1, v2, v3) and (v3, v2, v4) of the -// parallelogram with the same winding. Every Location output of the vertex stage is a vec4 float in the translator's -// output (rdna2spirv.py), and so is the stage's Position; the generated stage reads and writes exactly those. A value -// that is the same bit pattern at all three corners (a flat attribute, which may hold integer bits) is copied rather -// than computed, so it cannot turn into a NaN. +// the list draws and emits the parallelogram as the two triangles (v1, v2, v4) and (v1, v4, v3), with the winding of +// (v1, v2, v3). Both start at v1, so a flat input (taken from a triangle's first vertex) is v1's over the whole +// rectangle. Every Location output of the vertex stage is a vec4 float in the translator's output (rdna2spirv.py), +// and so is the stage's Position; the generated stage reads and writes exactly those. // // Not covered, and refused with a reason: a vertex stage that writes ClipDistance, CullDistance, Layer or // ViewportIndex, or a Location output that is not a vec4 float. @@ -40,11 +39,10 @@ constexpr std::uint32_t topology_type_rect_list = 19; // The geometry stage for `vertex_words`' outputs; empty, with `why` set, when the vertex stage cannot be expanded. inline std::vector rect_list_geometry(const std::vector& vertex_words, std::string& why) { enum : std::uint32_t { - op_entry_point = 15, op_type_void = 19, op_type_bool = 20, op_type_int = 21, op_type_float = 22, + op_entry_point = 15, op_type_void = 19, op_type_int = 21, op_type_float = 22, op_type_vector = 23, op_type_array = 28, op_type_pointer = 32, op_type_function = 33, op_constant = 43, op_function = 54, op_function_end = 56, op_variable = 59, op_load = 61, op_store = 62, op_access_chain = 65, - op_decorate = 71, op_bitcast = 124, op_fadd = 129, op_fsub = 131, op_logical_and = 167, op_select = 169, - op_iequal = 170, op_emit_vertex = 218, op_end_primitive = 219, op_label = 248, op_return = 253, + op_decorate = 71, op_fadd = 129, op_fsub = 131, op_emit_vertex = 218, op_end_primitive = 219, op_label = 248, op_return = 253, op_capability = 17, op_memory_model = 14, op_execution_mode = 16, deco_builtin = 11, deco_location = 30, builtin_position = 0, builtin_point_size = 1, storage_input = 1, storage_output = 3 @@ -113,17 +111,14 @@ inline std::vector rect_list_geometry(const std::vector rect_list_geometry(const std::vector corners; const std::uint32_t cs[3] = {c0, c1, c2}; @@ -170,32 +164,25 @@ inline std::vector rect_list_geometry(const std::vector out{0x07230203u, 0x00010000u, 0, next, 0}; - emit(out, op_capability, {19}); // Geometry + emit(out, op_capability, {2}); // Geometry emit(out, op_memory_model, {0, 1}); // Logical, GLSL450 std::vector entry{3, main_fn, 0x6e69616du, 0}; // Geometry, %main, "main" entry.insert(entry.end(), io_vars.begin(), io_vars.end()); @@ -204,7 +191,7 @@ inline std::vector rect_list_geometry(const std::vector #include #include +#include #include #include #include @@ -4130,8 +4131,16 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c vk.bind_index_buffer(command_buffer, vk.quad_indices, vk.quad_indices_offset, VK_INDEX_TYPE_UINT32); else vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type); - const std::uint32_t quads = std::min(draw->count / 4, generated ? vk.quad_index_count / 4 : UINT32_MAX); + // The shared buffer holds quad_index_count / 4 quads: more are cut off here and said so. + const std::uint32_t wanted = draw->count / 4, room = generated ? vk.quad_index_count / 4 : UINT32_MAX; + const std::uint32_t quads = std::min(wanted, room); + if (quads < wanted) + std::fprintf(stderr, "[rt] d3d12: a non-indexed quad list of %u quads draws only the first %u\n", + wanted, quads); const std::int32_t vertex_offset = generated ? std::int32_t(draw->first) : draw->base_vertex; + // All the instances of a quad are drawn together (a split by instance would zero the translated + // instance id, InstanceIndex - BaseInstance), so with several instances the primitive order is quad + // by quad, not instance by instance: only overlapping blended instances can tell. for (std::uint32_t quad = 0; quad < quads; ++quad) vk.draw_indexed(command_buffer, 4, draw->instances, (generated ? 0 : draw->first) + 4 * quad, vertex_offset, draw->first_instance); From a3da5122fdb1d4d9db8c5c2cdb89e9f04f46671b Mon Sep 17 00:00:00 2001 From: P2GR <26923358+P2GR@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:59:05 +0100 Subject: [PATCH 05/27] d3d12: checkpoint slow compute pipeline compiles Depends on: #7384 AI-assisted: yes (Codex) --- docs/d3d12_vulkan.md | 3 +++ runtime/shims/d3d12_vulkan_device.cpp | 32 +++++++++++++++++++++------ 2 files changed, 28 insertions(+), 7 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 02846e4298..4bc67346ed 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2031,6 +2031,9 @@ Pipeline creation: (`LEONIDA_PIPELINE_CACHE_BYTES=`, `0` turns it off): a cache seeded with the corpus file returns the whole union, which is not worth rewriting at every exit. A session file from another device, driver or pipeline-cache UUID is ignored with one line, and a write that fails (a read-only install directory) leaves the previous file. + Set `LEONIDA_STARTUP_CACHE_CHECKPOINTS=1` to write the session file after a successful compute pipeline + compile that took at least 500 ms. A later launch can reuse the completed work if the process exits before device + teardown. The session file keeps the same size cap and atomic replacement. `GetCachedBlob` records the vendor, device, driver version, `pipelineCacheUUID` and a SHA-256 of the description without `Flags`, sealed by a checksum (`runtime/src/cached_pso.h`). The answers are the host's, measured on an RTX 3060 and WARP: the same description is accepted; another diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 018c751364..14d6085a6c 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -247,9 +247,15 @@ void merge_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDe static_cast(result)); } -// Writes what this device compiled for the next launch (D3D-704). Called once the device is idle, before the cache -// is destroyed. Past the cap nothing is written: the blob from an earlier, smaller session stays, which is better -// than replacing it with one the next launch would keep refusing to save. +bool startup_cache_checkpoints_enabled() { + static const bool enabled = [] { + wchar_t value[2]{}; + return GetEnvironmentVariableW(L"LEONIDA_STARTUP_CACHE_CHECKPOINTS", value, 2) == 1 && value[0] == L'1'; + }(); + return enabled; +} + +// Writes the session cache at a startup checkpoint or during device teardown. The size cap applies to either write. void save_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, VkPipelineCache cache) { if (!cache || !vk.vkGetPipelineCacheData) return; const std::size_t limit = pipeline_cache_save_limit(); @@ -270,8 +276,7 @@ void save_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDev } std::vector data; try { - // Room to spare in case the driver counts the blob short between the query and the read. Nothing creates - // pipelines while the device is torn down, so this is a belt-and-braces margin, not a retry loop. + // Leave room in case another thread grows the cache between the size query and the read. data.resize(size + (size >> 4)); } catch (const std::bad_alloc&) { std::fprintf(stderr, @@ -705,6 +710,7 @@ struct DeviceState { leonida::cached_pso::Identity pso_identity; // what GetCachedBlob records and CachedPSO is checked against std::once_flag pipeline_cache_once; VkPipelineCache pipeline_cache_handle = VK_NULL_HANDLE; + std::mutex startup_cache_checkpoint_mutex; VkPipelineCache pipeline_cache() { std::call_once(pipeline_cache_once, [this] { @@ -3903,9 +3909,21 @@ class PipelineState final VkPipelineShaderStageRequiredSubgroupSizeCreateInfo required_size{}; subgroup_size_for(*entry, required_size, pipeline_info.stage); pipeline_info.layout = pipeline_.layout; - if (vk.vkCreateComputePipelines(dev, device_.pipeline_cache(), 1, &pipeline_info, nullptr, &pipeline_.pipeline) != - VK_SUCCESS) + const VkPipelineCache cache = device_.pipeline_cache(); + const bool checkpoint = cache && startup_cache_checkpoints_enabled(); + const ULONGLONG started = checkpoint ? GetTickCount64() : 0; + if (vk.vkCreateComputePipelines(dev, cache, 1, &pipeline_info, nullptr, &pipeline_.pipeline) != VK_SUCCESS) return E_FAIL; + if (checkpoint && GetTickCount64() - started >= 500) { + const std::unique_lock lock(device_.startup_cache_checkpoint_mutex, std::try_to_lock); + if (lock.owns_lock()) { + try { + save_session_pipeline_cache(vk, dev, cache); + } catch (const std::exception& error) { + std::fprintf(stderr, "[rt] d3d12: pipeline cache checkpoint failed (%s)\n", error.what()); + } + } + } // The code base: shaders read constant tables embedded in their own program through s_getpc_b64. The // translator's code offsets are into the bytes the key hashes (the FSSM blob, or the kind-6 program). From 49410a52fc6684f09692d551815fd385c73be7fc Mon Sep 17 00:00:00 2001 From: thibaut Date: Mon, 23 Nov 2026 19:13:41 +0100 Subject: [PATCH 06/27] d3d12: a slot-133 buffer whose pages are not imported is a shadow at the title's VA When VK_EXT_external_memory_host refuses the title's pages (write-combined or uncached pages, pages not committed yet, no extension, or the driver's import budget: about 64 MiB on an RTX 3070 Ti), the fallback was an ordinary DEFAULT buffer with neither the title's VA nor its data, so the title's descriptors resolved to nothing (slot 70 wrote a null SRV) and UI draws sampled nothing. The fallback is now a host-visible buffer (VRAM through Resizable BAR where upload buffers use it) whose console VA is the title's address, filled from the title's pages at creation and again before every submission of command lists (VulkanContext::set_before_execute, called from VulkanQueue::execute_now). Only committed, readable pages are read; the rest is zero. GPU writes to the shadow are not copied back. The first per-submission copy of each buffer size is timed and logged. Write-combined pages are read with MOVNTDQA: memcpy read 64 MiB of them in 253 ms on a Core i9-13900K, MOVNTDQA in 13 to 17 ms. Tests: write-combined, uncached, 64 MiB write-combined and half-committed ranges in d3d12_existing_heap_test, two patterns over two submissions each, 0 validation errors on an RTX 4090. Co-Authored-By: Claude Opus 5.5 --- runtime/shims/d3d12_vulkan_device.cpp | 180 +++++++++++++++++++++- runtime/src/vulkan_backend.h | 7 + runtime/test/d3d12_existing_heap_test.cpp | 130 ++++++++++++---- 3 files changed, 281 insertions(+), 36 deletions(-) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 2a463e1f83..d34419a010 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -41,6 +41,7 @@ #include #include #include +#include #include #include #include @@ -54,6 +55,7 @@ #include #include #include +#include #include namespace rt::d3d12 { @@ -84,6 +86,53 @@ void log_once(const char* what, int value) { if (seen.insert({what, value}).second) std::fprintf(stderr, "[rt] d3d12: %s %d\n", what, value); } +// memcpy that a page fault ends instead of killing the process: the title may decommit a page between the +// VirtualQuery that saw it committed and the read. No C++ objects here: it is a __try frame. +// `streaming` reads with MOVNTDQA, for write-combined pages: ordinary loads from them are not cached, and memcpy +// read 64 MiB of them in 253 ms on a Core i9-13900K (253 MiB/s), MOVNTDQA in 13 to 17 ms (4 to 5 GiB/s). Paid at every submission. +bool copy_guarded(std::uint8_t* to, const std::uint8_t* from, std::size_t bytes, bool streaming) { + __try { + if (streaming) { + const std::size_t head = std::min(bytes, (0 - reinterpret_cast(from)) & 63); + std::memcpy(to, from, head); + to += head, from += head, bytes -= head; + for (; bytes >= 64; to += 64, from += 64, bytes -= 64) { + const auto* in = reinterpret_cast(from); + const __m128i a = _mm_stream_load_si128(in), b = _mm_stream_load_si128(in + 1); + const __m128i c = _mm_stream_load_si128(in + 2), d = _mm_stream_load_si128(in + 3); + auto* out = reinterpret_cast<__m128i*>(to); + _mm_storeu_si128(out, a), _mm_storeu_si128(out + 1, b); + _mm_storeu_si128(out + 2, c), _mm_storeu_si128(out + 3, d); + } + } + std::memcpy(to, from, bytes); + return true; + } __except (EXCEPTION_EXECUTE_HANDLER) { + return false; + } +} + +// Copies [from, from + bytes) of the title's address space to `to`, for a slot-133 shadow buffer. Only committed, +// readable pages are read (xmem commits on first touch, and a read of a reserved page faults); the rest is zero. +void copy_title_pages(std::uint8_t* to, const std::uint8_t* from, std::size_t bytes) { + constexpr DWORD readable = PAGE_READONLY | PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READ | + PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY; + for (std::size_t at = 0; at < bytes;) { + MEMORY_BASIC_INFORMATION region{}; + std::size_t run = bytes - at; + bool read = false; + if (VirtualQuery(from + at, ®ion, sizeof(region))) { + const auto end = reinterpret_cast(region.BaseAddress) + region.RegionSize; + run = std::min(run, end - reinterpret_cast(from + at)); + read = region.State == MEM_COMMIT && (region.Protect & readable) && + !(region.Protect & (PAGE_GUARD | PAGE_NOACCESS)); + } + if (!read || !copy_guarded(to + at, from + at, run, (region.Protect & PAGE_WRITECOMBINE) != 0)) + std::memset(to + at, 0, run); + at += run; + } +} + // Two test settings that make the standalone device look like a GPU with fewer Vulkan queues, so the path where D3D12 // queues share a VkQueue runs on any GPU; both together give the Intel UHD 770 on Windows and lavapipe (one family, // one queue). LEONIDA_VK_MAX_QUEUES_PER_FAMILY=N (1 to 16): at most N VkQueues per queue family (unset, or not a @@ -640,6 +689,45 @@ struct DeviceState { // VK_EXT_external_memory_host; null unless info.host_pointer_alignment is set and the entry point loaded. PFN_vkGetMemoryHostPointerPropertiesEXT get_host_pointer_properties = nullptr; + // The live shadow buffers of Xbox device slot 133 (Resource::create_shadow_buffer): title-placed buffers whose + // pages the driver would not import. Each is re-copied from the title's pages before every submission of + // command lists (VulkanContext::set_before_execute), since nothing says which pages the title wrote. The first + // per-submission copy of each buffer size is timed and logged, so the cost shows in a run's log. + struct Shadow { + const std::uint8_t* pages; // the title's + std::uint8_t* mapped; // the shadow's memory + std::size_t size; + }; + std::mutex shadow_mutex; // a leaf: nothing else is taken under it + std::vector shadows; + std::set shadow_sizes_logged; + + void add_shadow(const Shadow& shadow) { + std::lock_guard lock(shadow_mutex); + shadows.push_back(shadow); + } + void remove_shadow(const std::uint8_t* mapped) { + std::lock_guard lock(shadow_mutex); + std::erase_if(shadows, [mapped](const Shadow& s) { return s.mapped == mapped; }); + } + void refresh_shadows() { + std::lock_guard lock(shadow_mutex); + for (const Shadow& s : shadows) { + if (!shadow_sizes_logged.insert(s.size).second) { + copy_title_pages(s.mapped, s.pages, s.size); + continue; + } + const auto start = std::chrono::steady_clock::now(); + copy_title_pages(s.mapped, s.pages, s.size); + const double ms = + std::chrono::duration(std::chrono::steady_clock::now() - start).count(); + std::fprintf(stderr, "[rt] d3d12: slot-133 shadow buffer of %llu KiB: copied from the title's pages in " + "%.3f ms (%.0f MiB/s), paid at every submission\n", + static_cast(s.size / 1024), ms, + ms > 0 ? double(s.size) / (1024.0 * 1024.0) / (ms / 1000.0) : 0.0); + } + } + // WriteToSubresource/ReadFromSubresource without host image copy: one staging copy at a time, submitted to // the device's VkQueue and waited for. Created on first use. std::mutex staging_mutex; @@ -1726,6 +1814,8 @@ class Resource final } if (image_address_) device_.forget_image(image_address_); device_.context->remove_resource(id()); + // Before the memory goes to the deferred queue: no submission copies into it after this. + if (shadow_) device_.remove_shadow(shadow_); if (host_import_) { // VK_EXT_external_memory_host needs the caller's pages to stay valid for the imported memory's whole // lifetime, and a title may free them right after releasing the resource. So the memory is not left to @@ -2001,6 +2091,69 @@ class Resource final return S_OK; } + // The fallback of create_host_buffer, for pages the driver will not import: write-combined or uncached ones (in + // retail 74 MiB of the title's 182 MiB range), pages not committed yet, a device without + // VK_EXT_external_memory_host, or a driver past its import budget (an RTX 3070 Ti answers + // VK_ERROR_OUT_OF_DEVICE_MEMORY after about 64 MiB of imports). The buffer has its own host-visible memory, a + // shadow of the title's pages, but keeps the title's VA as its console VA, so the descriptors and views the title + // builds from that VA still find it (an ordinary buffer here had another VA and none of the data: slot 70 wrote + // a null SRV and the UI draws sampled nothing). It is filled from the pages now and again before every + // submission of command lists (DeviceState::refresh_shadows). + // One way only: what the GPU writes to the shadow is NOT copied back to the title's pages, and the next + // submission's copy overwrites it. A title that reads GPU output at `address` needs the import. + HRESULT create_shadow_buffer(void* address) { + auto& vk = device_.context->vk; + if (!address || !desc_.Width || desc_.Width > ~UINT64(0) - D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT) + return E_INVALIDARG; + const bool need_bda = device_.info.buffer_device_address || device_.arena.buffer != VK_NULL_HANDLE; + VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; + info.size = desc_.Width; + info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | + VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT | + VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | + VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT; + if (device_.info.conditional_rendering) info.usage |= VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT; + if (need_bda) info.usage |= VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + device_.share(info); + if (vk.vkCreateBuffer(device_.info.device, &info, nullptr, &buffer_) != VK_SUCCESS) return E_OUTOFMEMORY; + VkMemoryRequirements requirements{}; + vk.vkGetBufferMemoryRequirements(device_.info.device, buffer_, &requirements); + // As an upload buffer (D3D-96): the CPU writes it at every submission and the GPU reads it, so VRAM through + // Resizable BAR where there is one, system memory otherwise. + memory_ = device_.allocate(requirements, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, + device_.upload_in_vram ? VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT : 0, &memory_flags_, + need_bda); + void* shadow = nullptr; + if (!memory_ || vk.vkBindBufferMemory(device_.info.device, buffer_, memory_, 0) != VK_SUCCESS || + vk.vkMapMemory(device_.info.device, memory_, 0, VK_WHOLE_SIZE, 0, &shadow) != VK_SUCCESS) + return E_OUTOFMEMORY; + shadow_ = static_cast(shadow); + const auto* pages = static_cast(address); + copy_title_pages(shadow_, pages, std::size_t(desc_.Width)); + // Map() answers the title's own pages, as the imported buffer does: a write to the shadow's memory would be + // overwritten by the next copy. + mapped_ = address; + va_ = reinterpret_cast(address); + if (need_bda && vk.vkGetBufferDeviceAddress) { + VkBufferDeviceAddressInfo bda{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; + bda.buffer = buffer_; + buffer_va_ = vk.vkGetBufferDeviceAddress(device_.info.device, &bda); + gpu_va_ = buffer_va_; + } + device_.log_va("title-placed buffer (shadow)", va_, desc_.Width); + leonida::ResourceBinding binding{}; + binding.buffer = buffer_; + binding.size = desc_.Width; + // CPU-side reads take the shadow, not the title's pages: it is as fresh as what the GPU reads and every byte + // of it can be read, which the pages do not promise. Not host_readable: GPU writes are not handed back. + binding.host = shadow_; + binding.va = va_; + device_.context->add_resource(id(), binding); + device_.add_shadow({pages, shadow_, std::size_t(desc_.Width)}); + return S_OK; + } + HRESULT create_sparse_buffer() { constexpr std::uint64_t tile_bytes = leonida::tile_size_in_bytes; if (!desc_.Width || desc_.Width > UINT64_MAX - tile_bytes || @@ -2533,6 +2686,7 @@ class Resource final std::uint64_t buffer_va_ = 0; std::uint64_t gpu_va_ = 0; bool host_import_ = false; // memory_ is the caller's pages (create_host_buffer): freed at once, not deferred + std::uint8_t* shadow_ = nullptr; // create_shadow_buffer: memory_ mapped, in DeviceState::shadows bool reserved_ = false; bool sparse_image_ = false; bool placed_ = false; @@ -4985,6 +5139,7 @@ class Device final info.conditional_rendering, info.ray_tracing, info.xdxr_acceleration_structures && info.buffer_device_address); + state_.context->set_before_execute([this] { state_.refresh_shadows(); }); if (info.physical && state_.format_properties) { state_.context->set_color_attachment_format( [physical = info.physical, get_props = state_.format_properties](VkFormat format) { @@ -6996,13 +7151,26 @@ class Device final if (FAILED(hr)) { // The driver would not import these pages: RADV refuses a view of a pagefile-backed section, the form // xmem's physical pages take (found in review on an RX 9070 XT under Wine), and a device without - // VK_EXT_external_memory_host has no import at all. The boot goes on with an ordinary DEFAULT buffer - // of the same description, as #6915's stand-in did: the title gets a resource, but its writes at - // `address` do not reach it. + // VK_EXT_external_memory_host has no import at all; write-combined and uncommitted pages are not tried, + // and some drivers stop importing after a budget (create_shadow_buffer). The title then gets a shadow + // buffer at its VA, copied from its pages before every submission. + resource->Release(); + resource = new Resource(state_, desc, heap, D3D12_HEAP_FLAG_NONE); + resource->attach_device(identity()); + const HRESULT shadow = resource->create_shadow_buffer(address); + if (SUCCEEDED(shadow)) { + log_once("a title-placed buffer (device slot 133) could not import its pages, so it is a shadow " + "copied from them before every submission; HRESULT", + int(hr)); + return d3d12_trace::result(method, hand_out(resource, riid, out)); + } + // No memory for the shadow either: the boot goes on with an ordinary DEFAULT buffer of the same + // description, as #6915's stand-in did. The title gets a resource, but neither its VA nor its writes at + // `address` reach it. resource->Release(); - log_once("a title-placed buffer (device slot 133) could not import its pages, so it is an ordinary buffer " - "the title's writes do not reach; HRESULT", - int(hr)); + log_once("a title-placed buffer (device slot 133) could neither import its pages nor get a shadow, so it " + "is an ordinary buffer the title's writes do not reach; HRESULT", + int(shadow)); const D3D12_HEAP_PROPERTIES fallback{D3D12_HEAP_TYPE_DEFAULT}; return d3d12_trace::result(method, create_committed(&fallback, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, 0, nullptr, riid, out)); diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index e659a762dc..77e43b90cf 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -1362,6 +1362,11 @@ class VulkanContext { // and records what the set needs first. When it fails, nothing of that call is executed. void set_transfer_only_family(std::uint32_t family) { transfer_only_family_ = family; } + // `before` is called at the start of every submission of command lists (a held batch: when it is released), + // before any lock here is taken: the device re-copies its slot-133 shadow buffers from the title's pages there. + // Set once, before the first queue exists. + void set_before_execute(std::function before) { before_execute_ = std::move(before); } + void set_bindless_prepare(std::function prepare) { std::unique_lock lock(resource_mutex_); bindless_prepare_ = std::move(prepare); @@ -1666,6 +1671,7 @@ class VulkanContext { std::map, VkRenderPass> resolve_passes_; std::map, VkFramebuffer> resolve_framebuffers_; + std::function before_execute_; std::function bindless_prepare_; std::function bindless_current_; bool bindless_upload_pending_ = false; // tracker_mutex_ @@ -2154,6 +2160,7 @@ class VulkanQueue : private QueueHolds::Holder { ReplayResult execute_now(std::span lists) { if (context_.is_device_lost() || !wait_for_room()) return ReplayResult::unsupported; + if (context_.before_execute_) context_.before_execute_(); if (kind_ != QueueKind::direct) for (const auto* list : lists) for (const auto& command : list->commands()) diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index 04900226a1..94dc94cf17 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp @@ -226,15 +226,89 @@ int check_title_placed(ID3D12Device* device, const char* kind, void* pages, UINT Ref placed_texture; EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, texture, 0x6u, IID_PPV_ARGS(&placed_texture.p)), S_OK); EXPECT(placed_texture.p != nullptr && placed_texture->GetDesc().Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D); - // An address off the buffer alignment can't be bound inside the import: the ordinary-buffer fallback answers. + // An address off the buffer alignment can't be bound inside the import: a shadow buffer answers, at the same VA + // (a driver whose buffer alignment is 1 imports it; the VA is the address either way). Ref fallback; + desc.Width = size - 1; EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, bytes + 1, desc, 0xFFFFFFFFu, IID_PPV_ARGS(&fallback.p)), S_OK); - EXPECT(fallback->GetGPUVirtualAddress() != reinterpret_cast(bytes + 1)); + EXPECT(fallback->GetGPUVirtualAddress() == reinterpret_cast(bytes + 1)); std::printf("%s: %s, %llu bytes: GPU VA is the address, a GPU copy reads the CPU's writes\n", who, kind, static_cast(size)); return 0; } +std::uint8_t pattern_byte(UINT64 i, unsigned seed) { + return static_cast(i * 131u + (i >> 8) * 7u + seed); +} + +// The shadow fallback of slot 133: pages the driver does not import (write-combined, uncached, not all committed) +// still give a buffer whose GPU VA is the address. It is a copy of the pages, made again before every submission: +// a pattern written to the first `committed` bytes after the buffer exists is what a GPU copy in the next +// ExecuteCommandLists reads, and so is a second pattern in the submission after. Bytes past `committed` are not +// committed: they are never read, and the GPU sees zeros there. The same holds where the range was imported after +// all (a Wine that drops the cache modifier), so the caller need not know which path answered. +int check_title_placed_shadow(ID3D12Device* device, const char* kind, void* pages, UINT64 committed, UINT64 size) { + const char* who = "vulkan slot-133 shadow"; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = size; + desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + Ref buffer; + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, desc, 0xFFFFFFFFu, IID_PPV_ARGS(&buffer.p)), S_OK); + EXPECT(buffer->GetGPUVirtualAddress() == reinterpret_cast(pages)); + D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + Ref readback; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.p)))); + D3D12_COMMAND_QUEUE_DESC queue_desc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + Ref queue; + Ref allocator; + Ref list; + Ref fence; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, + IID_PPV_ARGS(&list.p)))); + EXPECT(SUCCEEDED(list->Close())); + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr); + EXPECT(done != nullptr); + auto* bytes = static_cast(pages); + UINT64 fence_value = 0; + for (const unsigned seed : {7u, 93u}) { + // Written after the buffer exists (and, the second time, after a submission read the first pattern). + for (UINT64 i = 0; i < committed; ++i) bytes[i] = pattern_byte(i, seed); + EXPECT(SUCCEEDED(allocator->Reset())); + EXPECT(SUCCEEDED(list->Reset(allocator.p, nullptr))); + list->CopyBufferRegion(readback.p, 0, buffer.p, 0, size); + EXPECT(SUCCEEDED(list->Close())); + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + EXPECT(SUCCEEDED(queue->Signal(fence.p, ++fence_value))); + EXPECT(SUCCEEDED(fence->SetEventOnCompletion(fence_value, done))); + EXPECT(WaitForSingleObject(done, 30000) == WAIT_OBJECT_0); + void* mapped = nullptr; + EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); + const auto* got = static_cast(mapped); + UINT64 wrong = size; + for (UINT64 i = 0; i < size && wrong == size; ++i) + if (got[i] != (i < committed ? pattern_byte(i, seed) : 0)) wrong = i; + readback->Unmap(0, nullptr); + if (wrong != size) + std::fprintf(stderr, "%s: %s: pattern %u: first wrong byte at %llu\n", who, kind, seed, + static_cast(wrong)); + EXPECT(wrong == size); + } + CloseHandle(done); + std::printf("%s: %s, %llu bytes (%llu committed): GPU VA is the address, each submission reads the pages' " + "latest bytes\n", + who, kind, static_cast(size), static_cast(committed)); + return 0; +} + int check_title_placed_all(ID3D12Device* device) { constexpr SIZE_T size = 4 * 0x10000; int failures = 0; @@ -252,47 +326,43 @@ int check_title_placed_all(ID3D12Device* device) { UnmapViewOfFile(view); CloseHandle(section); - // Cache-modified ranges are not imported (WC imports read wrong bytes on an RTX 5090 in review). Some Wine - // versions report a requested WC allocation as plain read-write memory; check the protection actually supplied. - // PAGE_NOCACHE also exercises the fallback on those hosts, rather than dropping the cache-protection check. + // Cache-modified ranges are not imported (WC imports read wrong bytes on an RTX 5090 in review): a shadow buffer + // answers at the same VA. Some Wine versions report a requested WC allocation as plain read-write memory; check + // the protection actually supplied. PAGE_NOCACHE also exercises the fallback on those hosts, rather than + // dropping the cache-protection check. const char* who = "vulkan slot-133 buffer"; - D3D12_RESOURCE_DESC desc{}; - desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - desc.Width = size; - desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1; - desc.SampleDesc.Count = 1; - desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; for (DWORD modifier : {DWORD(PAGE_WRITECOMBINE), DWORD(PAGE_NOCACHE)}) { void* pages = VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE | modifier); EXPECT(pages != nullptr); MEMORY_BASIC_INFORMATION region{}; EXPECT(VirtualQuery(pages, ®ion, sizeof(region)) == sizeof(region)); const bool cache_modified = (region.Protect & (PAGE_WRITECOMBINE | PAGE_NOCACHE)) != 0; - { - Ref buffer; - EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, desc, 0xFFFFFFFFu, IID_PPV_ARGS(&buffer.p)), S_OK); - if (cache_modified) { - EXPECT(buffer->GetGPUVirtualAddress() != reinterpret_cast(pages)); - } else { - EXPECT(region.Protect == PAGE_READWRITE); - EXPECT(buffer->GetGPUVirtualAddress() == reinterpret_cast(pages)); - } - } + if (!cache_modified) EXPECT(region.Protect == PAGE_READWRITE); + const int failed = check_title_placed_shadow(device, modifier == PAGE_WRITECOMBINE ? "write-combined range" + : "uncached range", + pages, size, size); std::printf("%s: cache modifier 0x%lx, reported protection 0x%lx: %s\n", who, modifier, region.Protect, - cache_modified ? "ordinary-buffer fallback verified" - : "modifier not reported; read-write import verified"); + failed ? "FAILED" + : cache_modified ? "shadow buffer verified" + : "modifier not reported; read-write import verified"); + failures += failed; VirtualFree(pages, 0, MEM_RELEASE); } - char* partial = static_cast(VirtualAlloc(nullptr, size, MEM_RESERVE, PAGE_READWRITE)); - EXPECT(partial != nullptr && VirtualAlloc(partial, size / 2, MEM_COMMIT, PAGE_READWRITE) == partial); { - // Pages not committed yet (xmem commits on first touch) are not imported either: the fallback answers. - Ref fallback; - EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, partial, desc, 0xFFFFFFFFu, IID_PPV_ARGS(&fallback.p)), S_OK); - EXPECT(fallback->GetGPUVirtualAddress() != reinterpret_cast(partial)); + // A larger write-combined range, so the per-submission copy the layer logs is measured on more than a few + // pages (retail places 182 MiB, 74 MiB of it write-combined). + constexpr SIZE_T large = 64u << 20; + void* pages = VirtualAlloc(nullptr, large, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE | PAGE_WRITECOMBINE); + EXPECT(pages != nullptr); + failures += check_title_placed_shadow(device, "64 MiB write-combined range", pages, large, large); + VirtualFree(pages, 0, MEM_RELEASE); } + char* partial = static_cast(VirtualAlloc(nullptr, size, MEM_RESERVE, PAGE_READWRITE)); + EXPECT(partial != nullptr && VirtualAlloc(partial, size / 2, MEM_COMMIT, PAGE_READWRITE) == partial); + // Pages not committed yet (xmem commits on first touch) are not imported either: the shadow copies the committed + // half and never reads the other, which a GPU copy sees as zeros. + failures += check_title_placed_shadow(device, "half-committed range", partial, size / 2, size); VirtualFree(partial, 0, MEM_RELEASE); - std::printf("%s: a partly committed range falls back to an ordinary buffer\n", who); return failures; } From 14dc9af525c5e54f9edbde43ccb2bbe499007852 Mon Sep 17 00:00:00 2001 From: Giovanni Lion Date: Tue, 24 Nov 2026 02:32:51 +0800 Subject: [PATCH 07/27] d3d12: enable SSE4.1 for Clang's slot-133 streaming copy Clang's baseline x64 target cannot inline _mm_stream_load_si128 into copy_guarded. Give only that function the target feature the existing intrinsic requires; keep the MSVC path and global build flags unchanged. Depends on: #8225. Claimed in #8186, comment7110252121. AI-assisted: yes (Codex). --- runtime/shims/d3d12_vulkan_device.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index d34419a010..0660b95130 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -90,6 +90,9 @@ void log_once(const char* what, int value) { // VirtualQuery that saw it committed and the read. No C++ objects here: it is a __try frame. // `streaming` reads with MOVNTDQA, for write-combined pages: ordinary loads from them are not cached, and memcpy // read 64 MiB of them in 253 ms on a Core i9-13900K (253 MiB/s), MOVNTDQA in 13 to 17 ms (4 to 5 GiB/s). Paid at every submission. +#if defined(__clang__) && defined(_M_X64) +__attribute__((target("sse4.1"))) +#endif bool copy_guarded(std::uint8_t* to, const std::uint8_t* from, std::size_t bytes, bool streaming) { __try { if (streaming) { From 8c5ce53d123c58f7b1219b4007489e44036b0afe Mon Sep 17 00:00:00 2001 From: Mumogg <104529023+Mumogg@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:35:55 -0600 Subject: [PATCH 08/27] local: wire #8591 into present_state_for --- runtime/shims/d3d12_xs_device.cpp | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 68f3700546..72b7a0692c 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -24,6 +24,7 @@ // 78 SetFrameIntervalX, 79 ScheduleFrameEventX and 80 WaitFrameEventX. The slots can be moved with LEONIDA_XS_*_SLOT // for a trace that disagrees. The frame-event calls answer from a per-device token counter: there is no vblank source // behind the device before a presenter exists, so WaitFrameEventX returns at once with a fresh non-zero token. +#include "title_window.h" #include "d3d12_xs_device.h" #include "d3d12_trace.h" #include "d3d12_xs_alloc_size.h" @@ -1337,7 +1338,15 @@ PresentState* present_state_for(DeviceProxy* device) { std::fprintf(stderr, "[rt] d3d12_xs: PresentX window failed (error %lu)\n", GetLastError()); return state; } - auto presenter = rt::d3d12::create_window_presenter(device->real, state->window); + // LOCAL (wiring of #8591): present into the title's own window when it has one; else show the fallback window. + HWND target = rt::d3d12::find_title_window(GetCurrentProcessId(), state->window); + if (target) { + std::fprintf(stderr, "[rt] d3d12_xs: PresentX uses the title's own window %p\n", static_cast(target)); + } else { + target = state->window; + ShowWindow(target, SW_SHOWNOACTIVATE); + } + auto presenter = rt::d3d12::create_window_presenter(device->real, target); if (!presenter) { std::fprintf(stderr, "[rt] d3d12_xs: no window presenter on this device; PresentX is a no-op\n"); return state; From ab1fbff95dbd8becb9866f2a26fafac80ed1f6a4 Mon Sep 17 00:00:00 2001 From: Etr0p <216035314+Etr0p@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:38:42 +0100 Subject: [PATCH 09/27] d3d12: shaders reach a title-placed buffer through the root views and buffer V#s the layer writes Xbox device slot 133 places a buffer at the title's own VA, about 1.5 TiB on Windows, while a translated shader computes heap_base + console VA with heap_base the arena's device address. A root view or V# naming that VA missed the buffer. The layer now translates an address inside a title-placed buffer where it writes it (root CBV/SRV/UAV, CBV and buffer SRV/UAV V#s): to the arena offset of the slot-133 shadow, which now lives in the GPU address arena when it fits, or to an import's device address minus heap_base. New tests: title_va_alias_test, d3d12_title_va_test. Co-Authored-By: Claude Opus 5.5 --- runtime/CMakeLists.txt | 11 + runtime/shims/d3d12_com.cpp | 5 + runtime/shims/d3d12_vulkan_device.cpp | 63 +++- runtime/src/title_va_alias.h | 89 ++++++ runtime/test/d3d12_title_va_test.cpp | 398 ++++++++++++++++++++++++++ runtime/test/glsl/cs_user_data.comp | 8 +- runtime/test/title_va_alias_test.cpp | 47 +++ 7 files changed, 618 insertions(+), 3 deletions(-) create mode 100644 runtime/src/title_va_alias.h create mode 100644 runtime/test/d3d12_title_va_test.cpp create mode 100644 runtime/test/title_va_alias_test.cpp diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 3d0bb02022..3fd8525d0d 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2438,6 +2438,14 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_compute_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_compute COMMAND d3d12_compute_test) set_tests_properties(d3d12_compute PROPERTIES SKIP_RETURN_CODE 77) + # A buffer at the title's own VA (device slot 133) read by the same shader through a root view and a V#. + add_executable(d3d12_title_va_test test/d3d12_title_va_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_TEST_CS}) + target_link_libraries(d3d12_title_va_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_title_va_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_CS_SPV="${LEONIDA_TEST_CS}") + target_compile_options(d3d12_title_va_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_title_va COMMAND d3d12_title_va_test) + set_tests_properties(d3d12_title_va PROPERTIES SKIP_RETURN_CODE 77) # Compute PSOs from FSPX programs (docs/fspx.md): an ACCC container at slot 62 and a bare kind-6 program. add_executable(d3d12_fspx_compute_test test/d3d12_fspx_compute_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_TEST_CS}) target_link_libraries(d3d12_fspx_compute_test PRIVATE gta6rt_d3d12_com) @@ -2997,6 +3005,9 @@ if(TARGET Vulkan::Headers) add_executable(arena_size_test test/arena_size_test.cpp) target_link_libraries(arena_size_test PRIVATE Vulkan::Headers) add_test(NAME arena_size COMMAND arena_size_test) + # Title-placed buffer VAs (device slot 133) and the console VA shaders reach them by (src/title_va_alias.h). + add_executable(title_va_alias_test test/title_va_alias_test.cpp) + add_test(NAME title_va_alias COMMAND title_va_alias_test) endif() else() include("${CMAKE_CURRENT_SOURCE_DIR}/cmake/vulkan_headers_missing.cmake") diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index e33769c580..2d7d6de713 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -6,6 +6,7 @@ #include "d3d12_trace.h" #include "d3d12_xs_device.h" #include "../src/gfx10_descriptors.h" +#include "../src/title_va_alias.h" #include #include @@ -1167,6 +1168,10 @@ class GraphicsCommandList final return; const RootArgumentLayout::Parameter* p = parameter(state, index, type); if (!p) return; + // A root view inside a buffer the title placed at its own VA (device slot 133) gets the console VA of the + // buffer's GPU copy, so the shader's heap_base + VA reaches it (src/title_va_alias.h). Descriptor tables are + // the layer's own heaps: never translated. + if (type == rt::rootsig::ParamType::Descriptor) va = leonida::title_va_aliases().shader_va(va); const std::uint32_t first = first_dword(state, *p); write(state, first, std::uint32_t(va)); // In the compute layout a descriptor table is one dword, the 32-bit VA of its first descriptor (the heaps diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 0660b95130..ff794dc05f 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -28,6 +28,7 @@ #include "../src/shader_library.h" #include "../src/spirv_f16_halves.h" #include "../src/spirv_stores.h" +#include "../src/title_va_alias.h" #include "../src/vulkan_present.h" #include "../src/vulkan_device_filter.h" #include "../src/vulkan13_features.h" @@ -86,6 +87,19 @@ void log_once(const char* what, int value) { if (seen.insert({what, value}).second) std::fprintf(stderr, "[rt] d3d12: %s %d\n", what, value); } +// The base address a V# gets for a buffer address: inside a buffer the title placed at its own VA (device slot +// 133), the console VA of the buffer's GPU copy (src/title_va_alias.h, docs/d3d12_vulkan.md section 3.3); anything +// else unchanged. A V# keeps 48 address bits. An arena copy always fits; an imported buffer's address is its device +// address minus heap_base, which wraps when the driver put it below the arena: logged, and written as before. +std::uint64_t vsharp_address(std::uint64_t va) { + const std::uint64_t to = leonida::title_va_aliases().shader_va(va); + if (to != va && (to >> 48)) + log_once("a V# names a title-placed buffer whose GPU copy lies below heap_base, out of a V#'s 48 bits; " + "address bits 48-63:", + int(to >> 48)); + return to; +} + // memcpy that a page fault ends instead of killing the process: the title may decommit a page between the // VirtualQuery that saw it committed and the read. No C++ objects here: it is a __try frame. // `streaming` reads with MOVNTDQA, for write-combined pages: ordinary loads from them are not cached, and memcpy @@ -1810,6 +1824,7 @@ class Resource final : device_(device), desc_(desc), heap_(heap), heap_flags_(heap_flags), placed_(true), va_(placed_va) {} ~Resource() override { + if (aliased_) leonida::title_va_aliases().remove(va_, title_alias_); if (accel_) { device_.context->unregister_acceleration_structure(gpu_va_); if (buffer_va_ && buffer_va_ != gpu_va_) device_.context->unregister_acceleration_structure(buffer_va_); @@ -2091,9 +2106,19 @@ class Resource final binding.host_readable = true; binding.va = va_; device_.context->add_resource(id(), binding); + // Shaders reach the imported pages by their device address (src/title_va_alias.h). + if (buffer_va_) alias_title_va(buffer_va_ - device_.arena.address); return S_OK; } + // Registers [va_, va_ + width) as reached by shaders at `shader_va` (src/title_va_alias.h): the root views and + // buffer V#s the layer writes for an address in it get the matching address of the buffer's GPU copy. + void alias_title_va(std::uint64_t shader_va) { + if (!leonida::title_va_aliases().add(va_, desc_.Width, shader_va)) return; + title_alias_ = shader_va; + aliased_ = true; + } + // The fallback of create_host_buffer, for pages the driver will not import: write-combined or uncached ones (in // retail 74 MiB of the title's 182 MiB range), pages not committed yet, a device without // VK_EXT_external_memory_host, or a driver past its import budget (an RTX 3070 Ti answers @@ -2108,6 +2133,35 @@ class Resource final auto& vk = device_.context->vk; if (!address || !desc_.Width || desc_.Width > ~UINT64(0) - D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT) return E_INVALIDARG; + const auto* pages = static_cast(address); + // The shadow is a range of the GPU address arena when it fits there (docs/d3d12_vulkan.md section 3.3). + // The title's VA is about 1.5 TiB on Windows, far past the arena, so a shader's heap_base + VA would miss + // any buffer of the layer's; the root views and V#s the layer writes for that VA name the arena offset + // instead (src/title_va_alias.h), a VA below 4 GiB that a root view and a V#'s 48 bits both hold. The arena + // is host-visible, so the per-submission copy writes it in place. + if (device_.arena.mapped && device_.arena_allocate(desc_.Width, D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT, + arena_offset_, DeviceState::arena_buffer)) { + in_arena_ = true; + shadow_ = device_.arena.mapped + arena_offset_; + copy_title_pages(shadow_, pages, std::size_t(desc_.Width)); + mapped_ = address; + va_ = reinterpret_cast(address); + buffer_va_ = gpu_va_ = device_.arena.address + arena_offset_; + device_.log_va("title-placed buffer (arena shadow)", va_, desc_.Width); + leonida::ResourceBinding binding{}; + binding.buffer = device_.arena.buffer; + binding.buffer_offset = arena_offset_; + binding.size = desc_.Width; + binding.host = shadow_; + binding.va = va_; + device_.context->add_resource(id(), binding); + device_.add_shadow({pages, shadow_, std::size_t(desc_.Width)}); + alias_title_va(arena_offset_); + return S_OK; + } + log_once("a title-placed shadow buffer does not fit the GPU address arena (raise LEONIDA_ARENA_MB), so it " + "has its own memory; size in KiB:", + int(desc_.Width / 1024)); const bool need_bda = device_.info.buffer_device_address || device_.arena.buffer != VK_NULL_HANDLE; VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; info.size = desc_.Width; @@ -2132,7 +2186,6 @@ class Resource final vk.vkMapMemory(device_.info.device, memory_, 0, VK_WHOLE_SIZE, 0, &shadow) != VK_SUCCESS) return E_OUTOFMEMORY; shadow_ = static_cast(shadow); - const auto* pages = static_cast(address); copy_title_pages(shadow_, pages, std::size_t(desc_.Width)); // Map() answers the title's own pages, as the imported buffer does: a write to the shadow's memory would be // overwritten by the next copy. @@ -2154,6 +2207,7 @@ class Resource final binding.va = va_; device_.context->add_resource(id(), binding); device_.add_shadow({pages, shadow_, std::size_t(desc_.Width)}); + if (buffer_va_) alias_title_va(buffer_va_ - device_.arena.address); return S_OK; } @@ -2690,6 +2744,8 @@ class Resource final std::uint64_t gpu_va_ = 0; bool host_import_ = false; // memory_ is the caller's pages (create_host_buffer): freed at once, not deferred std::uint8_t* shadow_ = nullptr; // create_shadow_buffer: memory_ mapped, in DeviceState::shadows + bool aliased_ = false; // va_ is in leonida::title_va_aliases(), reached at title_alias_ + std::uint64_t title_alias_ = 0; bool reserved_ = false; bool sparse_image_ = false; bool placed_ = false; @@ -6403,6 +6459,7 @@ class Device final buffer.num_records = desc->SizeInBytes; buffer.format = leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT); buffer.oob_select = leonida::gfx10::OobSelect::raw; + buffer.address = vsharp_address(buffer.address); const leonida::gfx10::BufferWords words = leonida::gfx10::encode(buffer); std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); } @@ -6494,6 +6551,7 @@ class Device final } buffer.oob_select = leonida::gfx10::OobSelect::structured; } + buffer.address = vsharp_address(buffer.address); const leonida::gfx10::BufferWords words = leonida::gfx10::encode(buffer); std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); return; @@ -6651,11 +6709,12 @@ class Device final buffer.swizzle = channels; buffer.oob_select = typed ? g::OobSelect::structured : structured ? g::OobSelect::structured_with_offset : g::OobSelect::raw; + buffer.address = vsharp_address(buffer.address); const g::BufferWords words = g::encode(buffer); std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); if (counter) { g::Buffer counter_buffer{}; - counter_buffer.address = counter_va + view.CounterOffsetInBytes; + counter_buffer.address = vsharp_address(counter_va + view.CounterOffsetInBytes); counter_buffer.num_records = 4; counter_buffer.oob_select = g::OobSelect::raw; const g::BufferWords counter_words = g::encode(counter_buffer); diff --git a/runtime/src/title_va_alias.h b/runtime/src/title_va_alias.h new file mode 100644 index 0000000000..66739f7c13 --- /dev/null +++ b/runtime/src/title_va_alias.h @@ -0,0 +1,89 @@ +#pragma once +// Title-chosen buffer VAs (Xbox device slot 133) and the console VA a translated shader reaches them by +// (docs/d3d12_vulkan.md section 3.3, "Title-placed buffers"). +// +// A translated shader computes heap_base + console_va, with heap_base the GPU address arena's device address. The +// layer chooses every console VA it hands out, so they all land in the arena, but slot 133 places a buffer at a VA +// the title chose: the CPU address of its own pages (about 1.5 TiB on Windows), far past the arena. A shader that +// adds heap_base to that VA reads nothing the layer made. So where the layer itself writes an address a shader will +// dereference (a root CBV/SRV/UAV, and the V# of a CBV or a buffer SRV/UAV), an address inside a title-placed +// buffer is replaced by the console VA of the buffer's GPU copy: its arena offset when the copy is an arena range +// (the slot-133 shadow), or its device address minus heap_base (mod 2^64) when it has its own memory (an imported +// buffer). Everything else is passed through unchanged. Addresses the title writes into memory itself (a V# it +// builds in its own constant data) are not seen by the layer and keep the title's VA. +// +// The table is process-wide, like the title's address space: a title VA names one buffer at a time. It depends only +// on the standard library, so it is tested without a GPU (title_va_alias_test). +#include +#include +#include +#include +#include +#include +#include + +namespace leonida { + +class TitleVaAliases { +public: + // [title_va, title_va + bytes) is reached as [shader_va, shader_va + bytes). A range that overlaps a live one + // replaces it (the title has placed a new buffer over pages it released). False for an empty or wrapping range. + bool add(std::uint64_t title_va, std::uint64_t bytes, std::uint64_t shader_va) { + if (!bytes || title_va > UINT64_MAX - bytes) return false; + std::unique_lock lock(mutex_); + erase_overlapping(title_va, title_va + bytes); + ranges_[title_va] = {title_va + bytes, shader_va}; + count_.store(ranges_.size(), std::memory_order_release); + return true; + } + + // Forgets the range that starts at title_va, if it still maps to shader_va (a newer buffer at the same VA keeps + // its own entry). + void remove(std::uint64_t title_va, std::uint64_t shader_va) { + std::unique_lock lock(mutex_); + const auto it = ranges_.find(title_va); + if (it != ranges_.end() && it->second.shader_va == shader_va) ranges_.erase(it); + count_.store(ranges_.size(), std::memory_order_release); + } + + // The address a shader must be given for `va`: translated inside a title-placed buffer, unchanged elsewhere. + std::uint64_t shader_va(std::uint64_t va) const { + if (!count_.load(std::memory_order_acquire)) return va; // the common case: no title-placed buffer + std::shared_lock lock(mutex_); + auto it = ranges_.upper_bound(va); + if (it == ranges_.begin()) return va; + --it; + if (va >= it->second.end) return va; + return it->second.shader_va + (va - it->first); + } + + std::size_t size() const { return count_.load(std::memory_order_acquire); } + +private: + struct Range { + std::uint64_t end; // exclusive + std::uint64_t shader_va; // what title_va becomes + }; + + void erase_overlapping(std::uint64_t begin, std::uint64_t end) { + auto it = ranges_.lower_bound(begin); + if (it != ranges_.begin()) { + auto previous = std::prev(it); + if (previous->second.end > begin) it = previous; + } + while (it != ranges_.end() && it->first < end) it = ranges_.erase(it); + } + + mutable std::shared_mutex mutex_; + std::map ranges_; // by title VA + std::atomic count_{0}; +}; + +// The process's table: the slot-133 buffers add and remove their ranges, the command lists and descriptor writers +// read it. +inline TitleVaAliases& title_va_aliases() { + static TitleVaAliases aliases; + return aliases; +} + +} // namespace leonida diff --git a/runtime/test/d3d12_title_va_test.cpp b/runtime/test/d3d12_title_va_test.cpp new file mode 100644 index 0000000000..73447964b5 --- /dev/null +++ b/runtime/test/d3d12_title_va_test.cpp @@ -0,0 +1,398 @@ +// A buffer the title places at its own VA (Xbox device slot 133, rt::d3d12::create_buffer_at_host_address) is read +// by a shader written to the translator's address contract (heap_base + console VA, docs/d3d12_vulkan.md section +// 3.3), through the two kinds of address the layer writes for it: +// - a root view (SetComputeRootUnorderedAccessView with the title's VA): read 256 bytes past its base and written +// at its base, then copied to a READBACK buffer; +// - a buffer V# (CreateShaderResourceView of the title's buffer), the way translated vertex shaders fetch their +// vertices: read and written to an arena buffer. +// The title's VA is a VirtualAlloc address, far past the 4 GiB arena. Both page kinds are covered: read-write pages +// (imported with VK_EXT_external_memory_host where the driver takes them) and write-combined pages (refused by the +// import, so a shadow copy in the arena, the retail case on an RTX 5070 Ti). The data is written after the buffer +// exists, so the shadow's copy before the submission is what the GPU reads. +// Negative controls: a second title buffer with other data must not be what the first one's V# reads; an address +// one byte past the title range, an arena buffer's VA, and the title's VA after the buffer is released are written +// to a V# unchanged. The shader is test/glsl/cs_user_data.comp. No game data. LEONIDA_VK_VALIDATION=1 for the +// Khronos validation layer. +#include "shader_fixture_path.h" +#include "test_temp_dir.h" +#include "vk_test_device.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include "../src/shader_library.h" +#include "../src/title_va_alias.h" + +#include +#include +#include +#include +#include + +#ifndef LEONIDA_TEST_CS_SPV +#error "LEONIDA_TEST_CS_SPV must name the compiled test shader" +#endif + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +namespace { + +using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10: handle in RAX +using XboxComputePipelineFn = HRESULT(WINAPI*)(void* device, const D3D12_COMPUTE_PIPELINE_STATE_DESC*, std::uint64_t, + std::uint64_t, const IID*, void**); +using SerializeFn = HRESULT(WINAPI*)(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC*, ID3DBlob**, ID3DBlob**); + +template +struct Ref { + T* p = nullptr; + ~Ref() { reset(); } + void reset() { + if (p) p->Release(); + p = nullptr; + } + T* operator->() const { return p; } +}; + +void* slot(void* object, unsigned index) { return (*reinterpret_cast(object))[index]; } + +void put32(std::vector& out, std::uint32_t v) { + for (int i = 0; i < 4; ++i) out.push_back(std::uint8_t(v >> (8 * i))); +} + +std::vector zlib_stored(const std::vector& data) { + std::vector out = {0x78, 0x01, 0x01}; + const auto length = std::uint16_t(data.size()); + out.insert(out.end(), {std::uint8_t(length), std::uint8_t(length >> 8), std::uint8_t(~length), + std::uint8_t(~length >> 8)}); + out.insert(out.end(), data.begin(), data.end()); + std::uint32_t a = 1, b = 0; + for (const std::uint8_t x : data) { + a = (a + x) % 65521; + b = (b + a) % 65521; + } + const std::uint32_t adler = (b << 16) | a; + out.insert(out.end(), {std::uint8_t(adler >> 24), std::uint8_t(adler >> 16), std::uint8_t(adler >> 8), + std::uint8_t(adler)}); + return out; +} + +// The game's shader container shape (DXBC > DXIL > XDAT 0x0D > XBCH > zlib > FSSM), as d3d12_compute_test builds it. +std::vector shader_container(const std::vector& fssm) { + const auto stream = zlib_stored(fssm); + std::vector xbch = {'X', 'B', 'C', 'H'}; + for (const std::uint32_t v : {1u, std::uint32_t(stream.size()), 0u, std::uint32_t(fssm.size()), 0u}) put32(xbch, v); + xbch.insert(xbch.end(), stream.begin(), stream.end()); + std::vector dxil(16, 0); + dxil.insert(dxil.end(), {'X', 'D', 'A', 'T'}); + put32(dxil, 1); + put32(dxil, 12); + put32(dxil, 0x0d); + put32(dxil, 16 + 12 + 12); + put32(dxil, std::uint32_t(xbch.size())); + dxil.insert(dxil.end(), xbch.begin(), xbch.end()); + std::vector out = {'D', 'X', 'B', 'C'}; + out.resize(28, 0); + put32(out, 1); + put32(out, 36); + out.insert(out.end(), {'D', 'X', 'I', 'L'}); + put32(out, std::uint32_t(dxil.size())); + out.insert(out.end(), dxil.begin(), dxil.end()); + return out; +} + +std::vector serialize(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC& desc) { + const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); + const auto fn = d3d12 ? reinterpret_cast( + reinterpret_cast(GetProcAddress(d3d12, "D3D12SerializeVersionedRootSignature"))) + : nullptr; + std::vector out; + ID3DBlob* blob = nullptr; + if (fn && SUCCEEDED(fn(&desc, &blob, nullptr)) && blob) { + const auto* p = static_cast(blob->GetBufferPointer()); + out.assign(p, p + blob->GetBufferSize()); + blob->Release(); + } + return out; +} + +D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes, D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) { + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = bytes; + desc.Height = 1; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + desc.Flags = flags; + return desc; +} + +// The 48-bit base address of the 16-byte GFX10 buffer V# at `cpu` (dword 0, and dword 1 bits 0-15). +std::uint64_t vsharp_base(std::uint64_t cpu) { + std::uint32_t w[2]; + std::memcpy(w, reinterpret_cast(cpu), sizeof(w)); + return std::uint64_t(w[0]) | (std::uint64_t(w[1] & 0xFFFFu) << 32); +} + +D3D12_SHADER_RESOURCE_VIEW_DESC raw_srv(UINT first_word, UINT words) { + D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; + desc.Format = DXGI_FORMAT_R32_TYPELESS; + desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + desc.Buffer.FirstElement = first_word; + desc.Buffer.NumElements = words; + desc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + return desc; +} + +constexpr UINT kElements = 64, kBytes = kElements * 4; +constexpr UINT64 kPages = 64 * 1024; +constexpr UINT kSrvWord = 256; // the V# reads title words 256..319 +constexpr UINT kRootAdd = 7; // root view mode: title word i = title word 64 + i + 7 + +struct Context { + ID3D12Device* inner = nullptr; // the Vulkan device (slot 133's backend takes it) + ID3D12Device* device = nullptr; // the Xbox-ABI proxy over it + ID3D12RootSignature* root = nullptr; + ID3D12PipelineState* pso = nullptr; + ID3D12CommandQueue* queue = nullptr; + ID3D12Fence* fence = nullptr; + UINT64 fence_value = 0; + std::uint64_t arena = 0; +}; + +// One kind of title pages: `protect` is PAGE_READWRITE, or with PAGE_WRITECOMBINE. +int check_kind(Context& c, const char* kind, DWORD protect, int& checks) { + void* pages = VirtualAlloc(nullptr, kPages, MEM_RESERVE | MEM_COMMIT, protect); + void* other_pages = VirtualAlloc(nullptr, kPages, MEM_RESERVE | MEM_COMMIT, protect); + EXPECT(pages && other_pages); + const auto title_va = reinterpret_cast(pages); + EXPECT(title_va >= c.arena); // outside the arena: heap_base + title_va names nothing of the layer's + const D3D12_RESOURCE_DESC desc = buffer_desc(kPages); + Ref title, other; + EXPECT(SUCCEEDED(rt::d3d12::create_buffer_at_host_address(c.inner, pages, desc, 0xFFFFFFFFu, + IID_PPV_ARGS(&title.p)))); + EXPECT(SUCCEEDED(rt::d3d12::create_buffer_at_host_address(c.inner, other_pages, desc, 0xFFFFFFFFu, + IID_PPV_ARGS(&other.p)))); + EXPECT(title->GetGPUVirtualAddress() == title_va); // the title keeps its own VA + const std::uint64_t shader_va = leonida::title_va_aliases().shader_va(title_va); + EXPECT(shader_va != title_va); + const bool arena_copy = shader_va < c.arena; + const bool vsharp_fits = (shader_va >> 48) == 0; + + // The data, written after the buffers exist. + auto* words = static_cast(pages); + auto* other_words = static_cast(other_pages); + for (UINT i = 0; i < kPages / 4; ++i) { + words[i] = 0xA0000000u + i * 3u; + other_words[i] = 0xB0000000u + i * 5u; + } + + // Descriptors: the title buffer's V# (and the other buffer's), and the negative controls. + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 8, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + Ref heap; + EXPECT(SUCCEEDED(c.device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p)))); + const std::uint64_t cpu = reinterpret_cast(slot(heap.p, 9))(heap.p); + const std::uint64_t gpu = reinterpret_cast(slot(heap.p, 10))(heap.p); + const UINT inc = c.device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + const D3D12_SHADER_RESOURCE_VIEW_DESC srv = raw_srv(kSrvWord, kElements); + c.device->CreateShaderResourceView(title.p, &srv, D3D12_CPU_DESCRIPTOR_HANDLE{cpu}); + c.device->CreateShaderResourceView(other.p, &srv, D3D12_CPU_DESCRIPTOR_HANDLE{cpu + inc}); + EXPECT(vsharp_base(cpu) == ((shader_va + kSrvWord * 4) & 0xFFFFFFFFFFFFull)); + // Negative controls, descriptor level: one byte past the title range is not translated. + const D3D12_CONSTANT_BUFFER_VIEW_DESC past{title_va + kPages, 256}; + c.device->CreateConstantBufferView(&past, D3D12_CPU_DESCRIPTOR_HANDLE{cpu + 2 * inc}); + EXPECT(vsharp_base(cpu + 2 * inc) == ((title_va + kPages) & 0xFFFFFFFFFFFFull)); + ++checks; + + // An arena buffer for the V# read's result, a READBACK buffer for both results. + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}, readback_heap{D3D12_HEAP_TYPE_READBACK}; + Ref out, readback; + const auto uav = buffer_desc(kBytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + EXPECT(SUCCEEDED(c.device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &uav, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, + IID_PPV_ARGS(&out.p)))); + const auto readback_desc = buffer_desc(3 * kBytes); + EXPECT(SUCCEEDED(c.device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.p)))); + // An arena buffer's V# keeps its VA: identity outside title-placed buffers. + const D3D12_CONSTANT_BUFFER_VIEW_DESC arena_cbv{out->GetGPUVirtualAddress(), 256}; + c.device->CreateConstantBufferView(&arena_cbv, D3D12_CPU_DESCRIPTOR_HANDLE{cpu + 3 * inc}); + EXPECT(vsharp_base(cpu + 3 * inc) == out->GetGPUVirtualAddress()); + + Ref allocator; + Ref list; + EXPECT(SUCCEEDED(c.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + EXPECT(SUCCEEDED(c.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, c.pso, + IID_PPV_ARGS(&list.p)))); + ID3D12DescriptorHeap* heaps[] = {heap.p}; + list->SetDescriptorHeaps(1, heaps); + list->SetComputeRootSignature(c.root); + // Through the V# (buffer SRV mode, s5 = 0xFFFFFFFF), into the arena buffer. Skipped when the buffer's copy is + // not within a V#'s 48 bits of heap_base (an import the driver put below the arena), which the layer logs. + if (vsharp_fits) { + list->SetComputeRoot32BitConstant(0, 0, 0); + list->SetComputeRoot32BitConstant(0, 0xFFFFFFFFu, 1); + list->SetComputeRootUnorderedAccessView(1, out->GetGPUVirtualAddress()); + list->SetComputeRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{gpu}); + list->Dispatch(1, 1, 1); + } + // Through the root view: the title's own VA, read at +256 bytes and written at +0. + list->SetComputeRoot32BitConstant(0, kRootAdd, 0); + list->SetComputeRoot32BitConstant(0, 0xFFFFFFFEu, 1); + list->SetComputeRootUnorderedAccessView(1, title_va); + list->Dispatch(1, 1, 1); + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + list->ResourceBarrier(1, &barrier); + D3D12_RESOURCE_BARRIER to_copy{}; + to_copy.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + to_copy.Transition.pResource = out.p; + to_copy.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + to_copy.Transition.StateBefore = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + to_copy.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; + list->ResourceBarrier(1, &to_copy); + list->CopyBufferRegion(readback.p, 0, out.p, 0, kBytes); + list->CopyBufferRegion(readback.p, kBytes, title.p, 0, kBytes); + EXPECT(list->Close() == S_OK); + ID3D12CommandList* lists[] = {list.p}; + c.queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(c.queue) == leonida::ReplayResult::success); + EXPECT(SUCCEEDED(c.queue->Signal(c.fence, ++c.fence_value))); + EXPECT(SUCCEEDED(c.fence->SetEventOnCompletion(c.fence_value, nullptr))); + + void* mapped = nullptr; + EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); + const auto* got = static_cast(mapped); + UINT srv_ok = 0, srv_other = 0, root_ok = 0; + for (UINT i = 0; i < kElements; ++i) { + if (got[i] == words[kSrvWord + i]) ++srv_ok; + if (got[i] == other_words[kSrvWord + i]) ++srv_other; + if (got[kElements + i] == words[64 + i] + kRootAdd) ++root_ok; + } + readback->Unmap(0, nullptr); + std::printf("%s pages: GPU copy %s (shader VA %s); V# read %s, %u/%u words matched, %u/%u read the other " + "buffer's (negative control); root view read+write %u/%u matched\n", + kind, arena_copy ? "in the arena" : "with its own device address", + arena_copy ? "an arena offset" : "device address - heap_base", + vsharp_fits ? "run" : "skipped (out of a V#'s 48 bits)", vsharp_fits ? srv_ok : 0, kElements, + vsharp_fits ? srv_other : 0, kElements, root_ok, kElements); + if (vsharp_fits) { + EXPECT(srv_ok == kElements); + EXPECT(srv_other == 0); + } + EXPECT(root_ok == kElements); + + // After release, the title's VA is no longer translated: a new view of it names the title's VA itself. + title.reset(); + const D3D12_CONSTANT_BUFFER_VIEW_DESC released{title_va, 256}; + c.device->CreateConstantBufferView(&released, D3D12_CPU_DESCRIPTOR_HANDLE{cpu + 4 * inc}); + EXPECT(vsharp_base(cpu + 4 * inc) == (title_va & 0xFFFFFFFFFFFFull)); + EXPECT(leonida::title_va_aliases().shader_va(title_va) == title_va); + checks += 2; + other.reset(); + heap.reset(); + VirtualFree(pages, 0, MEM_RELEASE); + VirtualFree(other_pages, 0, MEM_RELEASE); + return 0; +} + +} // namespace + +int main() { + vktest::Device d; + const auto device_status = d.initialize(); + if (device_status == vktest::DeviceStatus::unavailable) { + std::fprintf(stderr, "SKIP: no usable Vulkan 1.3 device\n"); + return 77; + } + EXPECT(device_status == vktest::DeviceStatus::ready); + + std::vector fssm = {'F', 'S', 'S', 'M'}; + put32(fssm, 6000); + for (std::uint32_t i = 0; i < 14; ++i) put32(fssm, 0xbf810000u + i); + const auto container = shader_container(fssm); + const testfiles::ScratchDir scratch("leonida_title_va_test"); + const auto& library = scratch.path(); + EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), library / "cs_user_data.spv")); + { + std::ofstream index(library / "index.json", std::ios::binary); + index << "{\"cs_user_data\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << leonida::sha256_hex(fssm) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"local_size\": [64, 1, 1], " + "\"uses_code_base\": true, \"wave64\": false}}"; + } + + int checks = 0; + { + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = d.instance_proc; + info.instance = d.instance; + info.physical = d.physical; + info.device = d.device; + info.queue = d.queue; + info.queue_family = d.family; + info.buffer_device_address = true; + info.subgroup = d.subgroup; + info.shader_dir = library.string(); + ID3D12Device* inner = nullptr; // owned by the proxy, as in d3d12_compute_test + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); + Ref device; + EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), + reinterpret_cast(&device.p)))); + rt::d3d12::set_device_outer(inner, device.p); + + // [0] two constants (s4, s5), [1] a root UAV (s6:s7), [2] a one-descriptor table (s8): the console compute + // layout cs_user_data.comp reads. + D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, 1, 0, 0}; + D3D12_ROOT_PARAMETER params[3] = {}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[0].Constants = {0, 0, 2}; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + params[1].Descriptor = {0, 0}; + params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[2].DescriptorTable = {1, &range}; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; + root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + root_desc.Desc_1_0 = {3, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + const auto root_blob = serialize(root_desc); + EXPECT(!root_blob.empty()); + Ref root; + EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p)))); + D3D12_COMPUTE_PIPELINE_STATE_DESC pso_desc{}; + pso_desc.pRootSignature = root.p; + pso_desc.CS = {container.data(), container.size()}; + const IID pso_iid = __uuidof(ID3D12PipelineState); + Ref pso; + EXPECT(SUCCEEDED(reinterpret_cast(slot(device.p, 62))( + device.p, &pso_desc, 0, 0, &pso_iid, reinterpret_cast(&pso.p)))); + + const D3D12_COMMAND_QUEUE_DESC queue_desc{}; + Ref queue; + Ref fence; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + + Context c; + c.inner = inner; + c.device = device.p; + c.root = root.p; + c.pso = pso.p; + c.queue = queue.p; + c.fence = fence.p; + c.arena = rt::d3d12::device_arena_size(device.p); + EXPECT(c.arena > 0); + if (check_kind(c, "read-write", PAGE_READWRITE, checks)) return 1; + if (check_kind(c, "write-combined", PAGE_READWRITE | PAGE_WRITECOMBINE, checks)) return 1; + } + if (d.validation_errors()) { + std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); + return 1; + } + std::printf("title-placed buffers: a translated shader reached both page kinds through a root view and a buffer " + "V#; %d descriptor-level negative controls held\n", + checks); + return 0; +} diff --git a/runtime/test/glsl/cs_user_data.comp b/runtime/test/glsl/cs_user_data.comp index b285c0f3f9..4e1dfc904e 100644 --- a/runtime/test/glsl/cs_user_data.comp +++ b/runtime/test/glsl/cs_user_data.comp @@ -37,8 +37,14 @@ Words at(uvec2 va) { void main() { const uint i = gl_GlobalInvocationID.x; - Words table = at(uvec2(pc.s[8], 0u)); Words result = at(uvec2(pc.s[6], pc.s[7])); + if (pc.s[5] == 0xFFFFFFFEu) { + // Root view read mode (d3d12_title_va_test): read through the root UAV itself, 256 bytes past its base, and + // write at the base, so the root view's address is both read and written. + result.w[i] = result.w[64u + i] + pc.s[4]; + return; + } + Words table = at(uvec2(pc.s[8], 0u)); if (pc.s[5] == 0u) { // CBV V# mode: table holds a 16-byte GFX10 raw buffer descriptor written by CreateConstantBufferView. const uint num_records = table.w[2]; diff --git a/runtime/test/title_va_alias_test.cpp b/runtime/test/title_va_alias_test.cpp new file mode 100644 index 0000000000..7a4a38b9a8 --- /dev/null +++ b/runtime/test/title_va_alias_test.cpp @@ -0,0 +1,47 @@ +// leonida::TitleVaAliases (src/title_va_alias.h): where an address inside a title-placed buffer (Xbox device slot +// 133) is translated to, and that everything else is left alone. No GPU. +#include "../src/title_va_alias.h" + +#include +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +int main() { + leonida::TitleVaAliases a; + constexpr std::uint64_t title = 0x18500000000ull; // the shape of a Windows VA past 1 TiB + constexpr std::uint64_t size = 0x10000; + constexpr std::uint64_t arena = 0x2340000; + // Empty: identity everywhere. + EXPECT(a.size() == 0 && a.shader_va(title) == title && a.shader_va(0) == 0); + EXPECT(!a.add(title, 0, arena)); // empty range + EXPECT(!a.add(UINT64_MAX - 4, 16, arena)); // wraps + EXPECT(a.add(title, size, arena) && a.size() == 1); + // Inside: the same offset in the copy, first and last byte included. + EXPECT(a.shader_va(title) == arena); + EXPECT(a.shader_va(title + 0x123) == arena + 0x123); + EXPECT(a.shader_va(title + size - 1) == arena + size - 1); + // Negative controls: one byte before, the end itself, and an arena VA are untouched. + EXPECT(a.shader_va(title - 1) == title - 1); + EXPECT(a.shader_va(title + size) == title + size); + EXPECT(a.shader_va(arena) == arena); + // A wrapping target (an import below heap_base) is kept as is: modular arithmetic. + constexpr std::uint64_t below = 0xFFFFFFFFFFF00000ull; + EXPECT(a.add(title + 0x100000, size, below) && a.shader_va(title + 0x100010) == below + 0x10); + // A new buffer over part of a live range replaces it; the old range's removal does not touch the new one. + EXPECT(a.add(title + 0x8000, size, 0x5000000)); + EXPECT(a.shader_va(title) == title); // the replaced range is gone entirely + EXPECT(a.shader_va(title + 0x8000) == 0x5000000); + a.remove(title, arena); // stale: nothing starts there any more + EXPECT(a.shader_va(title + 0x8000) == 0x5000000); + a.remove(title + 0x8000, 0x1234); // another target: kept + EXPECT(a.shader_va(title + 0x8000) == 0x5000000); + a.remove(title + 0x8000, 0x5000000); + EXPECT(a.shader_va(title + 0x8000) == title + 0x8000); + a.remove(title + 0x100000, below); + EXPECT(a.size() == 0 && a.shader_va(title + 0x100010) == title + 0x100010); + std::printf("title_va_alias: translation inside a title-placed range, identity outside it and after release\n"); + return 0; +} From 7a8ae20ca09c355852c55766eb9313f90f179e21 Mon Sep 17 00:00:00 2001 From: Etr0p <216035314+Etr0p@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:39:59 +0100 Subject: [PATCH 10/27] docs: section 3.3 says how shaders reach title-placed buffers Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_vulkan.md | 22 ++++++++++++++++++++++ runtime/shims/d3d12_vulkan_device.cpp | 5 +++-- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index aae8591bf4..272bc68579 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -1496,6 +1496,28 @@ Arena VAs (at most 4095 MiB, so 32-bit) pass. A VA biased from outside the arena VAs above are at or above 2^40 as unsigned values. That is one more reason for the rule above that every buffer a console client can address is an arena range, whichever heap it comes from. +**Title-placed buffers (device slot 133).** Here the title, not the layer, chooses the VA: `CreatePlacedResourceX` +puts a buffer at the CPU address of the title's own pages. On Windows that is a user-mode address around 1.5 TiB, +far past the arena (at most 4095 MiB, and descriptor tables must stay below 4 GiB), so `heap_base + title_va` +names nothing the layer made. The layer therefore translates the title's VA where it +writes an address itself: root CBV/SRV/UAV arguments (`SetGraphicsRoot*View`, `SetComputeRoot*View`) and the base +of the V# it writes for a CBV or a buffer SRV/UAV (counter included). An address inside a title-placed buffer +becomes the console VA of that buffer's GPU copy (`runtime/src/title_va_alias.h`); every other address is left +alone, and the range is forgotten when the buffer is released. +- When the pages can't be imported (write-combined or uncommitted pages, a missing extension, an import budget), + the copy is the per-submission shadow, and the shadow is an **arena range** when it fits. Its console VA is the + arena offset: below 4 GiB, so it holds in a root argument, in a V#'s 48 bits and in a 32-bit table pointer alike. + When the arena has no room, the shadow keeps its own memory and is biased like an upload buffer (logged once; + raise `LEONIDA_ARENA_MB`). +- When the pages are imported (`VK_EXT_external_memory_host`), the copy is the import and its console VA is its + device address minus `heap_base` (mod 2^64): exact for 64-bit root arguments, and for a V# only when the driver + put the import above the arena (otherwise logged once, as measured for upload buffers above). +- The title's own VA is still what `GetGPUVirtualAddress` answers and what vertex, index, copy and immediate-write + calls resolve through the buffer VA index, so nothing the title reads back changes. +- **Not covered:** a pointer or V# the title writes into memory itself (inside its constant data, say). The layer + never sees it, so it keeps the title's VA. Covering it needs the title's pages inside the GPU address space + (one of the options in #7218's design note) or the translator rewriting addresses. + Why not give each buffer its own BDA and set `heap_base = 0`? Because 25,865 of the 26,503 shaders (97.6%) truncate descriptor-table pointers to 32 bits, and host BDAs are not guaranteed to be below 4 GB. The arena keeps console VAs low and stable. diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index ff794dc05f..2fb79e587b 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -2010,8 +2010,9 @@ class Resource final // with VK_EXT_external_memory_host and the buffer bound to it at offset 0, so the CPU's writes there are the GPU's // reads with no copy. Its console VA is `address` itself, the VA the title chose, so vertex, index and immediate // writes the title names by that VA find this buffer (VulkanContext::buffer_at). A shader that adds heap_base to - // that VA does not reach it: the title's own V#s into these pages need the single address space of - // docs/d3d12_vulkan.md section 3.3, which this does not decide. The pages stay the caller's: nothing is zeroed. + // that VA would not reach it, so the root views and V#s the layer writes for it name its device address minus + // heap_base instead (alias_title_va, docs/d3d12_vulkan.md section 3.3 "Title-placed buffers"); V#s the title + // writes into memory itself keep its VA. The pages stay the caller's: nothing is zeroed. HRESULT create_host_buffer(void* address) { auto& vk = device_.context->vk; const VkDeviceSize alignment = device_.info.host_pointer_alignment; From d8ba5ff389ba41478bd2733237a359c6ce070a42 Mon Sep 17 00:00:00 2001 From: Mumogg <104529023+Mumogg@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:40:50 -0600 Subject: [PATCH 11/27] local: trace PresentX --- runtime/shims/d3d12_xs_device.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 72b7a0692c..446f94084a 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -1509,7 +1509,12 @@ std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_ } return hr_to_u64(S_OK); } - if (Slot == (newer ? 32u : 30u)) return queue_present_x(self, a1, a2, a3); // PresentX + if (Slot == (newer ? 32u : 30u)) { // PresentX + const std::uint64_t hr = queue_present_x(self, a1, a2, a3); + // LOCAL: one trace line per present, so a run's presents can be counted. + d3d12_trace::record("XboxID3D12CommandQueue::PresentX", static_cast(hr) < 0 ? "failed" : "ok"); + return hr; + } if (Slot >= self->slot_count || (newer && (Slot == 14 || Slot == 15))) { d3d12_trace::record(child_trace_name(Slot), "console-only"); return hr_to_u64(S_OK); // unmodelled console queue methods: frame pacing flows through them From 65668002e972259722f008617068dd8ee90c82ce Mon Sep 17 00:00:00 2001 From: Etr0p <216035314+Etr0p@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:47:45 +0100 Subject: [PATCH 12/27] d3d12: buffer addresses in the title's own memory reach a shader through an arena window A root view or buffer V# may name the title's own memory outside any slot-133 buffer (a per-frame constant ring, #8862 section 3.5). The layer now makes a 64 KiB-aligned window of those pages in the GPU address arena, copies it before every submission like a slot-133 shadow, and names that copy instead: for root views when set, for V#s the layer writes, and for buffer V#s the title writes into a bound CBV/SRV/UAV table itself, rewritten in place before each submission. Counters per kind, LEONIDA_TITLE_WINDOWS_MB caps the windows (64 MiB). Co-Authored-By: Claude Opus 5.5 --- runtime/shims/d3d12_com.cpp | 30 ++++- runtime/shims/d3d12_vulkan_device.cpp | 148 ++++++++++++++++++++-- runtime/src/title_va_alias.h | 124 ++++++++++++++++--- runtime/src/vulkan_backend.h | 6 + runtime/test/d3d12_title_va_test.cpp | 169 ++++++++++++++++++++++++-- runtime/test/glsl/cs_user_data.comp | 7 ++ runtime/test/title_va_alias_test.cpp | 13 ++ 7 files changed, 453 insertions(+), 44 deletions(-) diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 2d7d6de713..6e718cee72 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -199,6 +199,8 @@ 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). const std::vector& pinned() const { return held_; } UINT front_stencil_ref() const { return front_stencil_ref_; } @@ -235,6 +237,7 @@ class GraphicsCommandList final record_into(command_allocator); invalid_ = false; calls_.clear(); + tables_.clear(); release_held(); // what the old recording used: it was replayed at ExecuteCommandLists reset_state(state); // Reset returns every list state to its default if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) set_initial_pipeline(state); // reset_state holds it @@ -1168,10 +1171,13 @@ class GraphicsCommandList final return; const RootArgumentLayout::Parameter* p = parameter(state, index, type); if (!p) return; - // A root view inside a buffer the title placed at its own VA (device slot 133) gets the console VA of the - // buffer's GPU copy, so the shader's heap_base + VA reaches it (src/title_va_alias.h). Descriptor tables are - // the layer's own heaps: never translated. - if (type == rt::rootsig::ParamType::Descriptor) va = leonida::title_va_aliases().shader_va(va); + // A root view into the title's own memory (a slot-133 buffer, a constant ring) gets the console VA of a GPU + // copy of it, so the shader's heap_base + VA reaches it (src/title_va_alias.h). A descriptor table is in one + // of the layer's heaps: kept, and its buffer V#s are rewritten the same way before each submission. + if (type == rt::rootsig::ParamType::Descriptor) + va = leonida::title_va_aliases().resolve(va, kRootViewBytes, leonida::TitleVaAliases::root_view); + else if (va && (tables_.empty() || tables_.back() != va)) + tables_.push_back(va); const std::uint32_t first = first_dword(state, *p); write(state, first, std::uint32_t(va)); // In the compute layout a descriptor table is one dword, the 32-bit VA of its first descriptor (the heaps @@ -1196,6 +1202,9 @@ class GraphicsCommandList final std::uint32_t topology_ = 0; // D3D_PRIMITIVE_TOPOLOGY_UNDEFINED std::array vertex_buffers_{}; leonida::IndexBufferView index_{}; + std::vector tables_; // SetGraphicsRootDescriptorTable / SetComputeRootDescriptorTable VAs + // The span a root view may read: D3D12's largest constant buffer (4096 x 16 bytes). + static constexpr std::uint64_t kRootViewBytes = 65536; leonida::Viewport viewport_{}; leonida::Rect scissor_{}; std::array render_targets_{}; @@ -1310,13 +1319,16 @@ class GraphicsCommandList final void set_vertex_buffers(UINT start, UINT count, const D3D12_VERTEX_BUFFER_VIEW* views) { if (count) draw_views_stale_ = true; - for (UINT i = 0; i < count; ++i) + for (UINT i = 0; i < count; ++i) { + if (views) leonida::title_va_aliases().note(views[i].BufferLocation, leonida::TitleVaAliases::vertex_view); vertex_buffers_[start + i] = views ? leonida::VertexBufferView{views[i].BufferLocation, views[i].SizeInBytes, views[i].StrideInBytes} : leonida::VertexBufferView{}; + } } void set_index_buffer(const D3D12_INDEX_BUFFER_VIEW* view) { + if (view) leonida::title_va_aliases().note(view->BufferLocation, leonida::TitleVaAliases::index_view); index_ = view ? leonida::IndexBufferView{view->BufferLocation, view->SizeInBytes, u(view->Format)} : leonida::IndexBufferView{}; } @@ -1567,6 +1579,14 @@ class CommandQueue final recorded.push_back(&list->commands()); graphics.push_back(list); } + // Buffer V#s the title wrote into a bound table itself may name its own memory: rewritten to a GPU copy's + // console VA before the copies are refreshed for this submission (src/title_va_alias.h). + { + std::set scanned; + for (const GraphicsCommandList* list : graphics) + for (const std::uint64_t table : list->tables()) + if (scanned.insert(table).second) leonida::title_va_aliases().scan_table(table); + } last_result_ = queue_.execute(recorded, [&graphics] { return pin_lists(graphics); }); d3d12_trace::record(method, last_result_ == leonida::ReplayResult::success ? "ok" : "failed"); if (last_result_ != leonida::ReplayResult::success) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 2fb79e587b..fdf3cc2f0c 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -87,12 +87,13 @@ void log_once(const char* what, int value) { if (seen.insert({what, value}).second) std::fprintf(stderr, "[rt] d3d12: %s %d\n", what, value); } -// The base address a V# gets for a buffer address: inside a buffer the title placed at its own VA (device slot -// 133), the console VA of the buffer's GPU copy (src/title_va_alias.h, docs/d3d12_vulkan.md section 3.3); anything -// else unchanged. A V# keeps 48 address bits. An arena copy always fits; an imported buffer's address is its device +// The base address a V# gets for a buffer address: in the title's own memory (a slot-133 buffer, a constant ring), +// the console VA of a GPU copy of it (src/title_va_alias.h, docs/d3d12_vulkan.md section 3.3); anything else +// unchanged. A V# keeps 48 address bits. An arena copy always fits; an imported buffer's address is its device // address minus heap_base, which wraps when the driver put it below the arena: logged, and written as before. -std::uint64_t vsharp_address(std::uint64_t va) { - const std::uint64_t to = leonida::title_va_aliases().shader_va(va); +std::uint64_t vsharp_address(std::uint64_t va, std::uint64_t bytes, + leonida::TitleVaAliases::Kind kind = leonida::TitleVaAliases::created_view) { + const std::uint64_t to = leonida::title_va_aliases().resolve(va, bytes, kind); if (to != va && (to >> 48)) log_once("a V# names a title-placed buffer whose GPU copy lies below heap_base, out of a V#'s 48 bits; " "address bits 48-63:", @@ -745,6 +746,110 @@ struct DeviceState { } } + // Windows of the title's own memory in the GPU address arena (src/title_va_alias.h, docs/d3d12_vulkan.md + // section 3.3 "Title-chosen addresses"): a root view or buffer V# that names the title's memory outside any + // slot-133 buffer (a per-frame constant ring, #8862 section 3.5) gets a copy of the 64 KiB-aligned pages it + // covers, refreshed before every submission like a slot-133 shadow, and the address of that copy. Windows are + // kept until the device goes (the ring comes round to the same pages), up to LEONIDA_TITLE_WINDOWS_MB (64 MiB + // by default); past that, or with the arena full, the address is left as it was and counted. + struct TitleWindow { + std::uint64_t start; + std::uint64_t shader_va; + }; + static constexpr std::uint64_t kTitleWindowAlign = 65536; + static constexpr std::uint64_t kTitleWindowMax = 16ull << 20; // the most one address pulls in + std::mutex title_window_mutex; // taken before shadow_mutex, never under it + std::vector title_windows; + std::uint64_t title_window_bytes = 0; + std::uint64_t title_window_cap = 64ull << 20; + + // Called through title_va_aliases().resolve for an address with no copy yet. False: not the title's memory. + bool resolve_title_memory(std::uint64_t va, std::uint64_t bytes, std::uint64_t& out) { + out = va; + if (!arena.mapped || va < arena.size || !context) return false; + if (context->knows_buffer_va(va)) return false; // an upload or readback buffer's biased VA, say + MEMORY_BASIC_INFORMATION mbi{}; + if (!VirtualQuery(reinterpret_cast(static_cast(va)), &mbi, sizeof(mbi)) || + mbi.State != MEM_COMMIT || !mbi.Protect || (mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD))) + return false; + auto& aliases = leonida::title_va_aliases(); + std::lock_guard lock(title_window_mutex); + if (const std::uint64_t made = aliases.shader_va(va); made != va) { // another thread made it meanwhile + out = made; + return true; + } + std::uint64_t lo = 0, hi = UINT64_MAX; + aliases.gap(va, lo, hi); // never over a slot-133 buffer's range or another window + const std::uint64_t want = std::clamp(bytes, 1, kTitleWindowMax); + const std::uint64_t start = std::max(va & ~(kTitleWindowAlign - 1), lo); + std::uint64_t end = va > UINT64_MAX - want - kTitleWindowAlign ? UINT64_MAX + : (va + want + kTitleWindowAlign - 1) & + ~(kTitleWindowAlign - 1); + end = std::min(end, hi); + if (end <= va) return true; + const std::uint64_t size = end - start; + if (title_window_bytes + size > title_window_cap) { + log_once("title memory named by a shader address is past LEONIDA_TITLE_WINDOWS_MB, left untranslated; " + "MiB copied so far:", + int(title_window_bytes >> 20)); + return true; + } + VkDeviceSize offset = 0; + if (!arena_allocate(size, kTitleWindowAlign, offset, arena_buffer)) { + log_once("GPU address arena full (raise LEONIDA_ARENA_MB): title memory left untranslated; window KiB:", + int(std::min(size >> 10, INT_MAX))); + return true; + } + auto* mapped = arena.mapped + offset; + const auto* pages = reinterpret_cast(static_cast(start)); + copy_title_pages(mapped, pages, std::size_t(size)); + add_shadow({pages, mapped, std::size_t(size)}); + aliases.add(start, size, offset); + title_windows.push_back({start, offset}); + title_window_bytes += size; + if (title_windows.size() <= 4 || !(title_windows.size() & (title_windows.size() - 1))) + std::fprintf(stderr, "[rt] d3d12: a %llu KiB window of the title's memory, named by a shader address, is " + "copied into the GPU address arena before every submission (%zu windows, %llu KiB)\n", + static_cast(size >> 10), title_windows.size(), + static_cast(title_window_bytes >> 10)); + out = offset + (va - start); + return true; + } + + // The shader-visible CBV/SRV/UAV heaps (arena offset -> end), for the scan of bound tables before a submission. + std::mutex cbv_heap_mutex; + std::map cbv_heaps; + static constexpr VkDeviceSize kTableScanDescriptors = 1024; // per table and submission + + // The buffer V#s of the table at `table_va` whose base is in the title's own memory get the address of a copy, + // written in place: the title wrote them itself (or copied them), so no Create*View saw them. Images (T#s) and + // null slots are skipped; so is a V# already in the arena, so a rewritten one is left alone next time. + void scan_title_table(std::uint64_t table_va) { + VkDeviceSize end = 0; + { + std::lock_guard lock(cbv_heap_mutex); + auto it = cbv_heaps.upper_bound(table_va); + if (it == cbv_heaps.begin()) return; + --it; + if (table_va >= it->second) return; + end = std::min(it->second, table_va + kTableScanDescriptors * kDescriptorSize); + } + auto& aliases = leonida::title_va_aliases(); + for (VkDeviceSize at = table_va; at + 16 <= end; at += kDescriptorSize) { + auto* w = reinterpret_cast(arena.mapped + at); + const std::uint32_t w0 = w[0], w1 = w[1], w2 = w[2], w3 = w[3]; + if (!(w0 | w1 | w2 | w3) || (w3 >> 30)) continue; // null, or not a buffer V# (TYPE, dword 3 bits 30-31) + const std::uint64_t base = std::uint64_t(w0) | (std::uint64_t(w1 & 0xFFFFu) << 32); + if (base < arena.size) continue; + const std::uint32_t stride = (w1 >> 16) & 0x3FFFu; + const std::uint64_t to = + aliases.resolve(base, std::uint64_t(w2) * (stride ? stride : 1), leonida::TitleVaAliases::table_view); + if (to == base || (to >> 48)) continue; + w[0] = std::uint32_t(to); + w[1] = (w1 & 0xFFFF0000u) | std::uint32_t((to >> 32) & 0xFFFFu); + } + } + // WriteToSubresource/ReadFromSubresource without host image copy: one staging copy at a time, submitted to // the device's VkQueue and waited for. Created on first use. std::mutex staging_mutex; @@ -1767,6 +1872,10 @@ class DescriptorHeap final in_arena_ = true; cpu_ = device.arena.mapped + arena_offset_; std::memset(cpu_, 0, std::size_t(bytes)); + if (desc.Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) { + std::lock_guard lock(device.cbv_heap_mutex); + device.cbv_heaps[arena_offset_] = arena_offset_ + bytes; + } } else { storage_.reset(new std::byte[std::size_t(bytes)]()); cpu_ = reinterpret_cast(storage_.get()); @@ -1774,6 +1883,10 @@ class DescriptorHeap final } ~DescriptorHeap() override { + if (in_arena_ && desc_.Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) { + std::lock_guard lock(device_.cbv_heap_mutex); + device_.cbv_heaps.erase(arena_offset_); + } if (in_arena_) device_.arena_release(arena_offset_, VkDeviceSize(desc_.NumDescriptors) * kDescriptorSize, DeviceState::arena_descriptor_heap); } @@ -5200,6 +5313,14 @@ class Device final info.xdxr_acceleration_structures && info.buffer_device_address); state_.context->set_before_execute([this] { state_.refresh_shadows(); }); + if (const char* mb = std::getenv("LEONIDA_TITLE_WINDOWS_MB"); mb && *mb) + state_.title_window_cap = std::strtoull(mb, nullptr, 10) << 20; + leonida::title_va_aliases().set_hooks( + &state_, + [](void* device, std::uint64_t va, std::uint64_t bytes, std::uint64_t& out) { + return static_cast(device)->resolve_title_memory(va, bytes, out); + }, + [](void* device, std::uint64_t table) { static_cast(device)->scan_title_table(table); }); if (info.physical && state_.format_properties) { state_.context->set_color_attachment_format( [physical = info.physical, get_props = state_.format_properties](VkFormat format) { @@ -5544,6 +5665,13 @@ class Device final } ~Device() override { + leonida::title_va_aliases().clear_hooks(&state_); + { + std::lock_guard lock(state_.title_window_mutex); + for (const auto& window : state_.title_windows) + leonida::title_va_aliases().remove(window.start, window.shader_va); + state_.title_windows.clear(); + } if (state_.context) { { std::lock_guard lock(state_.context->submit_mutex()); @@ -6460,7 +6588,7 @@ class Device final buffer.num_records = desc->SizeInBytes; buffer.format = leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT); buffer.oob_select = leonida::gfx10::OobSelect::raw; - buffer.address = vsharp_address(buffer.address); + buffer.address = vsharp_address(buffer.address, desc->SizeInBytes); const leonida::gfx10::BufferWords words = leonida::gfx10::encode(buffer); std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); } @@ -6552,7 +6680,8 @@ class Device final } buffer.oob_select = leonida::gfx10::OobSelect::structured; } - buffer.address = vsharp_address(buffer.address); + buffer.address = vsharp_address( + buffer.address, std::uint64_t(buffer.num_records) * (buffer.stride ? buffer.stride : 1)); const leonida::gfx10::BufferWords words = leonida::gfx10::encode(buffer); std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); return; @@ -6710,12 +6839,13 @@ class Device final buffer.swizzle = channels; buffer.oob_select = typed ? g::OobSelect::structured : structured ? g::OobSelect::structured_with_offset : g::OobSelect::raw; - buffer.address = vsharp_address(buffer.address); + buffer.address = vsharp_address(buffer.address, + std::uint64_t(buffer.num_records) * (buffer.stride ? buffer.stride : 1)); const g::BufferWords words = g::encode(buffer); std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); if (counter) { g::Buffer counter_buffer{}; - counter_buffer.address = vsharp_address(counter_va + view.CounterOffsetInBytes); + counter_buffer.address = vsharp_address(counter_va + view.CounterOffsetInBytes, 4); counter_buffer.num_records = 4; counter_buffer.oob_select = g::OobSelect::raw; const g::BufferWords counter_words = g::encode(counter_buffer); diff --git a/runtime/src/title_va_alias.h b/runtime/src/title_va_alias.h index 66739f7c13..6f665f0ec2 100644 --- a/runtime/src/title_va_alias.h +++ b/runtime/src/title_va_alias.h @@ -1,19 +1,22 @@ #pragma once -// Title-chosen buffer VAs (Xbox device slot 133) and the console VA a translated shader reaches them by -// (docs/d3d12_vulkan.md section 3.3, "Title-placed buffers"). +// Buffer addresses in the title's own memory and the console VA a translated shader reaches them by +// (docs/d3d12_vulkan.md section 3.3, "Title-chosen addresses"). // // A translated shader computes heap_base + console_va, with heap_base the GPU address arena's device address. The -// layer chooses every console VA it hands out, so they all land in the arena, but slot 133 places a buffer at a VA -// the title chose: the CPU address of its own pages (about 1.5 TiB on Windows), far past the arena. A shader that -// adds heap_base to that VA reads nothing the layer made. So where the layer itself writes an address a shader will -// dereference (a root CBV/SRV/UAV, and the V# of a CBV or a buffer SRV/UAV), an address inside a title-placed -// buffer is replaced by the console VA of the buffer's GPU copy: its arena offset when the copy is an arena range -// (the slot-133 shadow), or its device address minus heap_base (mod 2^64) when it has its own memory (an imported -// buffer). Everything else is passed through unchanged. Addresses the title writes into memory itself (a V# it -// builds in its own constant data) are not seen by the layer and keep the title's VA. +// layer chooses every console VA it hands out, so they all land in the arena. The title does not always use them: +// - device slot 133 places a buffer at the CPU address of the title's own pages (about 1.5 TiB on Windows); +// - the title points V#s and root views at its own memory (a per-frame constant ring, #8862 section 3.5). +// Both are far past the arena, so heap_base + VA reads nothing the layer made. An address inside such a range is +// therefore replaced, wherever the layer can see it, by the console VA of a GPU copy of that range: its arena offset +// when the copy is an arena range (a slot-133 shadow, or a window of the title's pages copied before every +// submission), or its device address minus heap_base (mod 2^64) when it has its own memory (an imported slot-133 +// buffer). Addresses that are not in the title's memory are passed through unchanged. // -// The table is process-wide, like the title's address space: a title VA names one buffer at a time. It depends only -// on the standard library, so it is tested without a GPU (title_va_alias_test). +// The table is process-wide, like the title's address space. The device behind it registers two hooks: a resolver +// that makes a GPU copy for an address in the title's memory that has none yet, and a scanner that rewrites the +// buffer V#s of a bound descriptor table before a submission. Without hooks the table only translates what was +// added to it, so it is tested without a GPU (title_va_alias_test). +#include #include #include #include @@ -26,6 +29,16 @@ namespace leonida { class TitleVaAliases { public: + // Where the layer saw the address, for the counters. + enum Kind : unsigned { root_view, created_view, table_view, vertex_view, index_view, kind_count }; + static constexpr const char* kKindNames[kind_count] = {"root view", "created view", "table V#", "vertex view", + "index view"}; + + // An address in the title's memory: true, with `shader_va` what a shader must be given (the address itself when + // no copy could be made). False: not the title's memory (an arena VA, a buffer of the layer's). + using Resolver = bool (*)(void* context, std::uint64_t va, std::uint64_t bytes, std::uint64_t& shader_va); + using TableScanner = void (*)(void* context, std::uint64_t table_va); + // [title_va, title_va + bytes) is reached as [shader_va, shader_va + bytes). A range that overlaps a live one // replaces it (the title has placed a new buffer over pages it released). False for an empty or wrapping range. bool add(std::uint64_t title_va, std::uint64_t bytes, std::uint64_t shader_va) { @@ -37,7 +50,7 @@ class TitleVaAliases { return true; } - // Forgets the range that starts at title_va, if it still maps to shader_va (a newer buffer at the same VA keeps + // Forgets the range that starts at title_va, if it still maps to shader_va (a newer range at the same VA keeps // its own entry). void remove(std::uint64_t title_va, std::uint64_t shader_va) { std::unique_lock lock(mutex_); @@ -46,9 +59,10 @@ class TitleVaAliases { count_.store(ranges_.size(), std::memory_order_release); } - // The address a shader must be given for `va`: translated inside a title-placed buffer, unchanged elsewhere. + // The address a shader must be given for `va` from the ranges added so far: translated inside one, unchanged + // elsewhere. No copy is made here. std::uint64_t shader_va(std::uint64_t va) const { - if (!count_.load(std::memory_order_acquire)) return va; // the common case: no title-placed buffer + if (!count_.load(std::memory_order_acquire)) return va; // the common case: no title range at all std::shared_lock lock(mutex_); auto it = ranges_.upper_bound(va); if (it == ranges_.begin()) return va; @@ -57,12 +71,81 @@ class TitleVaAliases { return it->second.shader_va + (va - it->first); } + // The free span around `va` (not in any range): [lo, hi). A copy made for `va` must stay inside it, so it never + // replaces a range another buffer still uses. + void gap(std::uint64_t va, std::uint64_t& lo, std::uint64_t& hi) const { + std::shared_lock lock(mutex_); + lo = 0; + hi = UINT64_MAX; + auto it = ranges_.upper_bound(va); + if (it != ranges_.end()) hi = it->first; + if (it != ranges_.begin()) lo = std::prev(it)->second.end; + } + + // shader_va, and when `va` is in the title's memory with no copy yet, a copy made by the device's resolver. + // Counted by kind: translated, or in the title's memory and left as it was. + std::uint64_t resolve(std::uint64_t va, std::uint64_t bytes, Kind kind) { + if (!va) return va; + std::uint64_t to = shader_va(va); + if (to != va) { + translated_[kind].fetch_add(1, std::memory_order_relaxed); + return to; + } + Resolver resolver; + void* context; + { + std::lock_guard lock(hook_mutex_); + resolver = resolver_; + context = hook_context_; + } + if (!resolver || !resolver(context, va, bytes, to)) return va; + (to != va ? translated_ : untranslated_)[kind].fetch_add(1, std::memory_order_relaxed); + return to; + } + + // Counts an address that the layer resolves through its buffer index instead (vertex and index views): only + // whether it is in a title range. + void note(std::uint64_t va, Kind kind) { + if (va && shader_va(va) != va) untranslated_[kind].fetch_add(1, std::memory_order_relaxed); + } + + // Before a submission: the device rewrites the buffer V#s of the table at `table_va` (a console VA in one of its + // shader-visible CBV/SRV/UAV heaps). + void scan_table(std::uint64_t table_va) { + TableScanner scanner; + void* context; + { + std::lock_guard lock(hook_mutex_); + scanner = scanner_; + context = hook_context_; + } + if (scanner) scanner(context, table_va); + } + + // The first device to register keeps the hooks until it clears them. + void set_hooks(void* context, Resolver resolver, TableScanner scanner) { + std::lock_guard lock(hook_mutex_); + if (hook_context_) return; + hook_context_ = context; + resolver_ = resolver; + scanner_ = scanner; + } + void clear_hooks(void* context) { + std::lock_guard lock(hook_mutex_); + if (hook_context_ != context) return; + hook_context_ = nullptr; + resolver_ = nullptr; + scanner_ = nullptr; + } + std::size_t size() const { return count_.load(std::memory_order_acquire); } + std::uint64_t translated(Kind kind) const { return translated_[kind].load(std::memory_order_relaxed); } + std::uint64_t untranslated(Kind kind) const { return untranslated_[kind].load(std::memory_order_relaxed); } private: struct Range { std::uint64_t end; // exclusive - std::uint64_t shader_va; // what title_va becomes + std::uint64_t shader_va; // what the range's first byte becomes }; void erase_overlapping(std::uint64_t begin, std::uint64_t end) { @@ -77,10 +160,15 @@ class TitleVaAliases { mutable std::shared_mutex mutex_; std::map ranges_; // by title VA std::atomic count_{0}; + std::mutex hook_mutex_; + void* hook_context_ = nullptr; + Resolver resolver_ = nullptr; + TableScanner scanner_ = nullptr; + std::array, kind_count> translated_{}; + std::array, kind_count> untranslated_{}; }; -// The process's table: the slot-133 buffers add and remove their ranges, the command lists and descriptor writers -// read it. +// The process's table: the device's title ranges and hooks, read by the command lists and descriptor writers. inline TitleVaAliases& title_va_aliases() { static TitleVaAliases aliases; return aliases; diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index 77e43b90cf..23226d558b 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -1124,6 +1124,12 @@ class VulkanContext { std::unique_lock lock(resource_mutex_); set_resource_locked(id, binding); } + // Whether `va` is in a buffer this context knows by VA (the index buffer_at searches). + bool knows_buffer_va(std::uint64_t va) { + std::shared_lock lock(resource_mutex_); + BufferVaIndex::Hit hit{}; + return buffer_vas_.find(va, hit); + } void add_resource(ResourceId id, const ResourceBinding& binding, VkImageLayout current_layout) { std::unique_lock rlock(resource_mutex_); set_resource_locked(id, binding); diff --git a/runtime/test/d3d12_title_va_test.cpp b/runtime/test/d3d12_title_va_test.cpp index 73447964b5..d971c716e3 100644 --- a/runtime/test/d3d12_title_va_test.cpp +++ b/runtime/test/d3d12_title_va_test.cpp @@ -9,15 +9,18 @@ // (imported with VK_EXT_external_memory_host where the driver takes them) and write-combined pages (refused by the // import, so a shadow copy in the arena, the retail case on an RTX 5070 Ti). The data is written after the buffer // exists, so the shadow's copy before the submission is what the GPU reads. -// Negative controls: a second title buffer with other data must not be what the first one's V# reads; an address -// one byte past the title range, an arena buffer's VA, and the title's VA after the buffer is released are written -// to a V# unchanged. The shader is test/glsl/cs_user_data.comp. No game data. LEONIDA_VK_VALIDATION=1 for the +// Then the title's own memory outside any slot-133 buffer (a constant ring, #8862 section 3.5): a V# the CPU writes +// into a bound table itself, a created CBV and a root view. +// Negative controls: a second title buffer with other data must not be what the first one's V# reads; an arena +// buffer's V# keeps its VA; the title's range is forgotten when the buffer is released; a raw arena V# and a +// T#-shaped slot in a scanned table keep their bytes; a reserved, uncommitted address is left alone. The shader is test/glsl/cs_user_data.comp. No game data. LEONIDA_VK_VALIDATION=1 for the // Khronos validation layer. #include "shader_fixture_path.h" #include "test_temp_dir.h" #include "vk_test_device.h" #include "../shims/d3d12_com.h" #include "../shims/d3d12_xs_device.h" +#include "../src/gfx10_descriptors.h" #include "../src/shader_library.h" #include "../src/title_va_alias.h" @@ -201,11 +204,6 @@ int check_kind(Context& c, const char* kind, DWORD protect, int& checks) { c.device->CreateShaderResourceView(title.p, &srv, D3D12_CPU_DESCRIPTOR_HANDLE{cpu}); c.device->CreateShaderResourceView(other.p, &srv, D3D12_CPU_DESCRIPTOR_HANDLE{cpu + inc}); EXPECT(vsharp_base(cpu) == ((shader_va + kSrvWord * 4) & 0xFFFFFFFFFFFFull)); - // Negative controls, descriptor level: one byte past the title range is not translated. - const D3D12_CONSTANT_BUFFER_VIEW_DESC past{title_va + kPages, 256}; - c.device->CreateConstantBufferView(&past, D3D12_CPU_DESCRIPTOR_HANDLE{cpu + 2 * inc}); - EXPECT(vsharp_base(cpu + 2 * inc) == ((title_va + kPages) & 0xFFFFFFFFFFFFull)); - ++checks; // An arena buffer for the V# read's result, a READBACK buffer for both results. const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}, readback_heap{D3D12_HEAP_TYPE_READBACK}; @@ -286,11 +284,8 @@ int check_kind(Context& c, const char* kind, DWORD protect, int& checks) { } EXPECT(root_ok == kElements); - // After release, the title's VA is no longer translated: a new view of it names the title's VA itself. + // After release, the buffer's range is gone from the table: its old copy is not named any more. title.reset(); - const D3D12_CONSTANT_BUFFER_VIEW_DESC released{title_va, 256}; - c.device->CreateConstantBufferView(&released, D3D12_CPU_DESCRIPTOR_HANDLE{cpu + 4 * inc}); - EXPECT(vsharp_base(cpu + 4 * inc) == (title_va & 0xFFFFFFFFFFFFull)); EXPECT(leonida::title_va_aliases().shader_va(title_va) == title_va); checks += 2; other.reset(); @@ -300,6 +295,155 @@ int check_kind(Context& c, const char* kind, DWORD protect, int& checks) { return 0; } +// The title's own memory outside any slot-133 buffer: a VirtualAlloc range standing for its per-frame constant ring +// (#8862 section 3.5). Three ways a shader is given an address in it, each read back through an arena buffer: +// - a buffer V# the CPU writes into a shader-visible heap itself, as the title does (rewritten before the submission); +// - a V# made by CreateConstantBufferView (translated when written); +// - a root view (translated when set). +// Negative controls: a raw V# whose base is an arena buffer and a T#-shaped slot whose base is the ring keep their +// bytes; an address the ring does not hold is left alone. +int check_title_memory(Context& c, int& checks) { + constexpr UINT64 ring_bytes = 256 * 1024; + auto* ring = static_cast(VirtualAlloc(nullptr, ring_bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + EXPECT(ring); + const auto ring_va = reinterpret_cast(ring); + EXPECT(ring_va >= c.arena); + auto& aliases = leonida::title_va_aliases(); + const std::uint64_t table_before = aliases.translated(leonida::TitleVaAliases::table_view); + const std::uint64_t created_before = aliases.translated(leonida::TitleVaAliases::created_view); + const std::uint64_t root_before = aliases.translated(leonida::TitleVaAliases::root_view); + + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}, readback_heap{D3D12_HEAP_TYPE_READBACK}; + const auto uav = buffer_desc(kBytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + Ref out[3], readback; + for (auto& o : out) + EXPECT(SUCCEEDED(c.device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &uav, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, + IID_PPV_ARGS(&o.p)))); + const auto readback_desc = buffer_desc(3 * kBytes); + EXPECT(SUCCEEDED(c.device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.p)))); + + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 8, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + Ref heap; + EXPECT(SUCCEEDED(c.device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p)))); + const std::uint64_t cpu = reinterpret_cast(slot(heap.p, 9))(heap.p); + const std::uint64_t gpu = reinterpret_cast(slot(heap.p, 10))(heap.p); + const UINT inc = c.device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + const auto raw_vsharp = [](std::uint64_t address) { + leonida::gfx10::Buffer b{}; + b.address = address; + b.num_records = kBytes; + b.format = leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT); + b.oob_select = leonida::gfx10::OobSelect::raw; + return leonida::gfx10::encode(b); + }; + // Slot 0: a V# the CPU writes itself, its base in the ring. Slot 1: CreateConstantBufferView of the ring. + // Slot 2: a raw 64-bit VA (out[2]) for the root-view mode. Slots 3 and 4: the negative controls. + const auto v0 = raw_vsharp(ring_va + 0x1000); + std::memcpy(reinterpret_cast(cpu), v0.data(), sizeof(v0)); + const D3D12_CONSTANT_BUFFER_VIEW_DESC cbv{ring_va + 0x2000, 256}; + c.device->CreateConstantBufferView(&cbv, D3D12_CPU_DESCRIPTOR_HANDLE{cpu + inc}); + EXPECT(vsharp_base(cpu + inc) < c.arena); // translated when written + const std::uint64_t out2 = out[2]->GetGPUVirtualAddress(); + std::memcpy(reinterpret_cast(cpu + 2 * inc), &out2, sizeof(out2)); + const auto arena_vsharp = raw_vsharp(out[0]->GetGPUVirtualAddress()); + std::memcpy(reinterpret_cast(cpu + 3 * inc), arena_vsharp.data(), sizeof(arena_vsharp)); + auto image_like = raw_vsharp(ring_va + 0x4000); + image_like[3] |= 0x8u << 28; // TYPE: an image + std::memcpy(reinterpret_cast(cpu + 4 * inc), image_like.data(), sizeof(image_like)); + std::uint8_t before3[32], before4[32]; + std::memcpy(before3, reinterpret_cast(cpu + 3 * inc), 32); + std::memcpy(before4, reinterpret_cast(cpu + 4 * inc), 32); + + // The ring's data, written before the submission (after the descriptors, as a title fills its ring per frame). + for (UINT i = 0; i < ring_bytes / 4; ++i) ring[i] = 0xC0000000u + i * 7u; + + Ref allocator; + Ref list; + EXPECT(SUCCEEDED(c.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + EXPECT(SUCCEEDED(c.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, c.pso, + IID_PPV_ARGS(&list.p)))); + ID3D12DescriptorHeap* heaps[] = {heap.p}; + list->SetDescriptorHeaps(1, heaps); + list->SetComputeRootSignature(c.root); + // The CPU-written V# (buffer SRV mode). + list->SetComputeRoot32BitConstant(0, 0, 0); + list->SetComputeRoot32BitConstant(0, 0xFFFFFFFFu, 1); + list->SetComputeRootUnorderedAccessView(1, out[0]->GetGPUVirtualAddress()); + list->SetComputeRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{gpu}); + list->Dispatch(1, 1, 1); + // The created CBV (CBV mode). + list->SetComputeRoot32BitConstant(0, 0, 1); + list->SetComputeRootUnorderedAccessView(1, out[1]->GetGPUVirtualAddress()); + list->SetComputeRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{gpu + inc}); + list->Dispatch(1, 1, 1); + // A root view into the ring, read 256 bytes past its base, written through slot 2's raw VA. + list->SetComputeRoot32BitConstant(0, kRootAdd, 0); + list->SetComputeRoot32BitConstant(0, 0xFFFFFFFDu, 1); + list->SetComputeRootUnorderedAccessView(1, ring_va + 0x3000); + list->SetComputeRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{gpu + 2 * inc}); + list->Dispatch(1, 1, 1); + // The negative-control slots are bound too, so the scan reads them. + list->SetComputeRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{gpu + 3 * inc}); + list->SetComputeRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{gpu + 4 * inc}); + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + list->ResourceBarrier(1, &barrier); + for (UINT k = 0; k < 3; ++k) { + D3D12_RESOURCE_BARRIER to_copy{}; + to_copy.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + to_copy.Transition.pResource = out[k].p; + to_copy.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + to_copy.Transition.StateBefore = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + to_copy.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; + list->ResourceBarrier(1, &to_copy); + list->CopyBufferRegion(readback.p, k * kBytes, out[k].p, 0, kBytes); + } + EXPECT(list->Close() == S_OK); + ID3D12CommandList* lists[] = {list.p}; + c.queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(c.queue) == leonida::ReplayResult::success); + EXPECT(SUCCEEDED(c.queue->Signal(c.fence, ++c.fence_value))); + EXPECT(SUCCEEDED(c.fence->SetEventOnCompletion(c.fence_value, nullptr))); + + void* mapped = nullptr; + EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); + const auto* got = static_cast(mapped); + UINT raw_ok = 0, cbv_ok = 0, root_ok = 0; + for (UINT i = 0; i < kElements; ++i) { + if (got[i] == ring[0x1000 / 4 + i]) ++raw_ok; + if (got[kElements + i] == ring[0x2000 / 4 + i]) ++cbv_ok; + if (got[2 * kElements + i] == ring[0x3000 / 4 + 64 + i] + kRootAdd) ++root_ok; + } + readback->Unmap(0, nullptr); + const bool rewritten = vsharp_base(cpu) < c.arena; + const bool arena_kept = !std::memcmp(before3, reinterpret_cast(cpu + 3 * inc), 32); + const bool image_kept = !std::memcmp(before4, reinterpret_cast(cpu + 4 * inc), 32); + std::printf("title memory (a constant ring): CPU-written table V# %u/%u (rewritten before the submission: %s), " + "created CBV %u/%u, root view %u/%u; negative controls: arena V# kept %s, T#-shaped slot kept %s; " + "translated: %llu table V#, %llu created, %llu root\n", + raw_ok, kElements, rewritten ? "yes" : "no", cbv_ok, kElements, root_ok, kElements, + arena_kept ? "yes" : "no", image_kept ? "yes" : "no", + static_cast(aliases.translated(leonida::TitleVaAliases::table_view) - table_before), + static_cast(aliases.translated(leonida::TitleVaAliases::created_view) - + created_before), + static_cast(aliases.translated(leonida::TitleVaAliases::root_view) - root_before)); + EXPECT(raw_ok == kElements && cbv_ok == kElements && root_ok == kElements); + EXPECT(rewritten && arena_kept && image_kept); + // An address in no committed page is not title memory: left alone, nothing made for it. + void* gone = VirtualAlloc(nullptr, 65536, MEM_RESERVE, PAGE_READWRITE); + const auto gone_va = reinterpret_cast(gone); + const D3D12_CONSTANT_BUFFER_VIEW_DESC reserved_only{gone_va, 256}; + c.device->CreateConstantBufferView(&reserved_only, D3D12_CPU_DESCRIPTOR_HANDLE{cpu + 5 * inc}); + EXPECT(vsharp_base(cpu + 5 * inc) == (gone_va & 0xFFFFFFFFFFFFull)); + VirtualFree(gone, 0, MEM_RELEASE); + checks += 3; + return 0; +} + } // namespace int main() { @@ -386,6 +530,7 @@ int main() { EXPECT(c.arena > 0); if (check_kind(c, "read-write", PAGE_READWRITE, checks)) return 1; if (check_kind(c, "write-combined", PAGE_READWRITE | PAGE_WRITECOMBINE, checks)) return 1; + if (check_title_memory(c, checks)) return 1; } if (d.validation_errors()) { std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); diff --git a/runtime/test/glsl/cs_user_data.comp b/runtime/test/glsl/cs_user_data.comp index 4e1dfc904e..b8f2c12b90 100644 --- a/runtime/test/glsl/cs_user_data.comp +++ b/runtime/test/glsl/cs_user_data.comp @@ -45,6 +45,13 @@ void main() { return; } Words table = at(uvec2(pc.s[8], 0u)); + if (pc.s[5] == 0xFFFFFFFDu) { + // Root view read to a table pointer (d3d12_title_va_test): read through the root view, 256 bytes past its + // base, and write where the table entry's raw 64-bit VA points. + Words out = at(uvec2(table.w[0], table.w[1])); + out.w[i] = result.w[64u + i] + pc.s[4]; + return; + } if (pc.s[5] == 0u) { // CBV V# mode: table holds a 16-byte GFX10 raw buffer descriptor written by CreateConstantBufferView. const uint num_records = table.w[2]; diff --git a/runtime/test/title_va_alias_test.cpp b/runtime/test/title_va_alias_test.cpp index 7a4a38b9a8..e27faa8f60 100644 --- a/runtime/test/title_va_alias_test.cpp +++ b/runtime/test/title_va_alias_test.cpp @@ -27,6 +27,19 @@ int main() { EXPECT(a.shader_va(title - 1) == title - 1); EXPECT(a.shader_va(title + size) == title + size); EXPECT(a.shader_va(arena) == arena); + // The free span around an address: between the ranges, so a window made for it never covers one. + std::uint64_t lo = 1, hi = 1; + a.gap(title + size + 5, lo, hi); + EXPECT(lo == title + size && hi == UINT64_MAX); + a.gap(title - 5, lo, hi); + EXPECT(lo == 0 && hi == title); + // Without a device's resolver, resolve only translates what was added, and counts it. + EXPECT(a.resolve(title + 4, 4, leonida::TitleVaAliases::root_view) == arena + 4); + EXPECT(a.resolve(title - 4, 4, leonida::TitleVaAliases::root_view) == title - 4); + EXPECT(a.translated(leonida::TitleVaAliases::root_view) == 1); + a.note(title + 8, leonida::TitleVaAliases::vertex_view); + a.note(title - 8, leonida::TitleVaAliases::vertex_view); + EXPECT(a.untranslated(leonida::TitleVaAliases::vertex_view) == 1); // A wrapping target (an import below heap_base) is kept as is: modular arithmetic. constexpr std::uint64_t below = 0xFFFFFFFFFFF00000ull; EXPECT(a.add(title + 0x100000, size, below) && a.shader_va(title + 0x100010) == below + 0x10); From d2f328e560dcbbdbc0e34f5d26f5855c5ffd8209 Mon Sep 17 00:00:00 2001 From: Etr0p <216035314+Etr0p@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:51:08 +0100 Subject: [PATCH 13/27] d3d12: only the title's memory gets a copy; the table scan covers the declared slots and is timed The xmem shims record what they hand the title (XMemAlloc, XMemAllocDefault, XMemVirtualAlloc, the title's VirtualAlloc); an address outside those ranges is left as it was and counted. The submit-time scan reads only the CBV/SRV/UAV slots the bound table's root signature declares, and its cost is accumulated per ExecuteCommandLists. Section 3.3 describes the three places addresses are replaced and the two kinds of copy. Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_vulkan.md | 56 ++++++++++++++++---------- runtime/shims/d3d12_com.cpp | 24 +++++++---- runtime/shims/d3d12_com.h | 3 ++ runtime/shims/d3d12_vulkan_device.cpp | 39 +++++++++++++++--- runtime/shims/xmem.cpp | 36 ++++++++++++++--- runtime/src/title_va_alias.h | 58 ++++++++++++++++++++++++--- runtime/test/d3d12_title_va_test.cpp | 25 ++++++++---- runtime/test/title_va_alias_test.cpp | 8 ++++ 8 files changed, 198 insertions(+), 51 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 272bc68579..f108cc37d3 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -1496,27 +1496,41 @@ Arena VAs (at most 4095 MiB, so 32-bit) pass. A VA biased from outside the arena VAs above are at or above 2^40 as unsigned values. That is one more reason for the rule above that every buffer a console client can address is an arena range, whichever heap it comes from. -**Title-placed buffers (device slot 133).** Here the title, not the layer, chooses the VA: `CreatePlacedResourceX` -puts a buffer at the CPU address of the title's own pages. On Windows that is a user-mode address around 1.5 TiB, -far past the arena (at most 4095 MiB, and descriptor tables must stay below 4 GiB), so `heap_base + title_va` -names nothing the layer made. The layer therefore translates the title's VA where it -writes an address itself: root CBV/SRV/UAV arguments (`SetGraphicsRoot*View`, `SetComputeRoot*View`) and the base -of the V# it writes for a CBV or a buffer SRV/UAV (counter included). An address inside a title-placed buffer -becomes the console VA of that buffer's GPU copy (`runtime/src/title_va_alias.h`); every other address is left -alone, and the range is forgotten when the buffer is released. -- When the pages can't be imported (write-combined or uncommitted pages, a missing extension, an import budget), - the copy is the per-submission shadow, and the shadow is an **arena range** when it fits. Its console VA is the - arena offset: below 4 GiB, so it holds in a root argument, in a V#'s 48 bits and in a 32-bit table pointer alike. - When the arena has no room, the shadow keeps its own memory and is biased like an upload buffer (logged once; - raise `LEONIDA_ARENA_MB`). -- When the pages are imported (`VK_EXT_external_memory_host`), the copy is the import and its console VA is its - device address minus `heap_base` (mod 2^64): exact for 64-bit root arguments, and for a V# only when the driver - put the import above the arena (otherwise logged once, as measured for upload buffers above). -- The title's own VA is still what `GetGPUVirtualAddress` answers and what vertex, index, copy and immediate-write - calls resolve through the buffer VA index, so nothing the title reads back changes. -- **Not covered:** a pointer or V# the title writes into memory itself (inside its constant data, say). The layer - never sees it, so it keeps the title's VA. Covering it needs the title's pages inside the GPU address space - (one of the options in #7218's design note) or the translator rewriting addresses. +**Title-chosen addresses.** Two kinds of buffer address are the title's choice, not the layer's: +- device slot 133 (`CreatePlacedResourceX`) puts a buffer at the CPU address of the title's own pages; +- the title points root views and V#s at its own memory, for instance a per-frame constant ring (#8862, section + 3.5 of `docs/retail_boot_chain.md`). + +On Windows these are user-mode addresses around 1.5 TiB, far past the arena (at most 4095 MiB, and descriptor +tables must stay below 4 GiB), so `heap_base + VA` names nothing the layer made (the D3D-53 failure above). The layer +therefore replaces such an address, wherever it sees one, by the console VA of a GPU copy of that memory +(`runtime/src/title_va_alias.h`): + +| Where the address is | When it is replaced | +|---|---| +| Root CBV/SRV/UAV (`Set*Root*View`) | when the argument is set | +| CBV and buffer SRV/UAV V#s the layer writes (`Create*View`, slot 70, counter V#s included) | when the descriptor is written | +| Buffer V#s the title writes into a shader-visible CBV/SRV/UAV heap itself | before each `ExecuteCommandLists`, in place, for the tables the submitted lists bind and only the slots their root signatures declare | + +The copies: +- A **slot-133 buffer** whose pages cannot be imported is the per-submission shadow, and the shadow is an **arena + range** when it fits. Its console VA is its arena offset, which holds in a root argument, in a V#'s 48 bits and in + a 32-bit table pointer alike. Without room in the arena it keeps its own memory and is biased like an upload buffer + (logged once; raise `LEONIDA_ARENA_MB`). An **imported** slot-133 buffer is reached at its device address minus + `heap_base` (mod 2^64): exact for root arguments, and for a V# only when the driver put the import above the arena + (logged once otherwise). +- Any **other address in the title's memory** gets a window: the 64 KiB-aligned pages it covers, clipped to the + title's range, copied into the arena now and before every submission, through the same shadow refresh as slot 133 + (so dirty-page tracking for that refresh applies to both). Windows stay until the device goes, up to + `LEONIDA_TITLE_WINDOWS_MB` (64 MiB by default). +- **Only the title's memory** gets a copy: the blocks and ranges the xmem shims hand the title (`XMemAlloc`, + `XMemAllocDefault`, `XMemVirtualAlloc`, the title's `VirtualAlloc`). An address anywhere else, the runtime's or a + host DLL's memory included, is left as it was and counted, as is an arena VA or a buffer the layer made. + +The title's own VA is still what `GetGPUVirtualAddress` answers, and vertex, index, copy and immediate-write calls +still resolve it through the buffer VA index, which knows slot-133 buffers by that VA. The copies are one way: what +the GPU writes into a copy does not reach the title's pages. A pointer the title hides elsewhere (a raw VA inside its +constant data that a shader dereferences) is not seen by the layer and keeps the title's VA. Why not give each buffer its own BDA and set `heap_base = 0`? Because 25,865 of the 26,503 shaders (97.6%) truncate descriptor-table pointers to 32 bits, and host BDAs are not guaranteed to be below 4 GB. The arena keeps console VAs low and stable. diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 6e718cee72..1ad12e432f 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -12,8 +12,10 @@ #include #include #include +#include #include #include +#include #include #include #include @@ -200,7 +202,7 @@ 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_; } + const std::vector>& tables() const { return tables_; } // The pipeline states and root signatures the recording names (it holds a reference to each until Reset). const std::vector& pinned() const { return held_; } UINT front_stencil_ref() const { return front_stencil_ref_; } @@ -1176,8 +1178,8 @@ class GraphicsCommandList final // of the layer's heaps: kept, and its buffer V#s are rewritten the same way before each submission. if (type == rt::rootsig::ParamType::Descriptor) va = leonida::title_va_aliases().resolve(va, kRootViewBytes, leonida::TitleVaAliases::root_view); - else if (va && (tables_.empty() || tables_.back() != va)) - tables_.push_back(va); + else if (va && p->table_descriptors && (tables_.empty() || tables_.back().first != va)) + tables_.push_back({va, p->table_descriptors}); const std::uint32_t first = first_dword(state, *p); write(state, first, std::uint32_t(va)); // In the compute layout a descriptor table is one dword, the 32-bit VA of its first descriptor (the heaps @@ -1202,7 +1204,8 @@ class GraphicsCommandList final std::uint32_t topology_ = 0; // D3D_PRIMITIVE_TOPOLOGY_UNDEFINED std::array vertex_buffers_{}; leonida::IndexBufferView index_{}; - std::vector tables_; // SetGraphicsRootDescriptorTable / SetComputeRootDescriptorTable VAs + // SetGraphicsRootDescriptorTable / SetComputeRootDescriptorTable: VA, CBV/SRV/UAV slots the signature declares + std::vector> tables_; // The span a root view may read: D3D12's largest constant buffer (4096 x 16 bytes). static constexpr std::uint64_t kRootViewBytes = 65536; leonida::Viewport viewport_{}; @@ -1582,10 +1585,17 @@ class CommandQueue final // Buffer V#s the title wrote into a bound table itself may name its own memory: rewritten to a GPU copy's // console VA before the copies are refreshed for this submission (src/title_va_alias.h). { - std::set scanned; + std::map tables; // each table once, with the most slots it was bound with for (const GraphicsCommandList* list : graphics) - for (const std::uint64_t table : list->tables()) - if (scanned.insert(table).second) leonida::title_va_aliases().scan_table(table); + for (const auto& [table, descriptors] : list->tables()) + tables[table] = std::max(tables[table], descriptors); + if (!tables.empty()) { + const auto start = std::chrono::steady_clock::now(); + for (const auto& [table, descriptors] : tables) leonida::title_va_aliases().scan_table(table, descriptors); + leonida::title_va_aliases().note_scan(std::uint64_t( + std::chrono::duration_cast(std::chrono::steady_clock::now() - start) + .count())); + } } last_result_ = queue_.execute(recorded, [&graphics] { return pin_lists(graphics); }); d3d12_trace::record(method, last_result_ == leonida::ReplayResult::success ? "ok" : "failed"); diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index 14ead7b24f..d975b800a0 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -374,6 +374,9 @@ struct RootArgumentLayout { std::uint32_t user_offset; // graphics: first dword; unused for a parameter with no dwords std::uint32_t constant_count; // constants only std::uint32_t compute_offset = rt::rootsig::kNoSgpr; // compute: first user SGPR + // A table: the CBV/SRV/UAV slots its ranges declare (an unbounded range counts as 1024), for the scan of + // title-written V#s before a submission (src/title_va_alias.h). 0: a sampler table, or not a table. + std::uint32_t table_descriptors = 0; }; std::vector parameters; std::uint32_t flags = 0; // D3D12_ROOT_SIGNATURE_FLAGS from the serialized blob diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index fdf3cc2f0c..e431cf8cf2 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -101,6 +101,22 @@ std::uint64_t vsharp_address(std::uint64_t va, std::uint64_t bytes, return to; } +// The CBV/SRV/UAV slots a descriptor table declares: the end of its furthest range (D3D12 appends a range at +// D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND), an unbounded range counted as 1024. 0 for a sampler table or no table. +std::uint32_t table_view_descriptors(const rt::rootsig::RootParameter& param) { + if (param.type != rt::rootsig::ParamType::Table) return 0; + constexpr std::uint32_t kUnbounded = 1024; + std::uint64_t next = 0, end = 0; + for (const auto& range : param.ranges) { + const std::uint64_t start = range.offset_in_table == D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND ? next + : range.offset_in_table; + const std::uint64_t count = range.num_descriptors == UINT_MAX ? kUnbounded : range.num_descriptors; + next = start + count; + if (range.range_type != D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER) end = std::max(end, next); + } + return std::uint32_t(std::min(end, kUnbounded)); +} + // memcpy that a page fault ends instead of killing the process: the title may decommit a page between the // VirtualQuery that saw it committed and the read. No C++ objects here: it is a __try frame. // `streaming` reads with MOVNTDQA, for write-combined pages: ordinary loads from them are not cached, and memcpy @@ -768,11 +784,15 @@ struct DeviceState { out = va; if (!arena.mapped || va < arena.size || !context) return false; if (context->knows_buffer_va(va)) return false; // an upload or readback buffer's biased VA, say + auto& aliases = leonida::title_va_aliases(); + // Only the title's own memory gets a copy (xmem's ranges): an address anywhere else, the runtime's or a host + // DLL's memory included, is left as it was and counted. + std::uint64_t title_lo = 0, title_hi = 0; + if (!aliases.title_memory(va, title_lo, title_hi)) return true; MEMORY_BASIC_INFORMATION mbi{}; if (!VirtualQuery(reinterpret_cast(static_cast(va)), &mbi, sizeof(mbi)) || mbi.State != MEM_COMMIT || !mbi.Protect || (mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD))) - return false; - auto& aliases = leonida::title_va_aliases(); + return true; std::lock_guard lock(title_window_mutex); if (const std::uint64_t made = aliases.shader_va(va); made != va) { // another thread made it meanwhile out = made; @@ -780,6 +800,8 @@ struct DeviceState { } std::uint64_t lo = 0, hi = UINT64_MAX; aliases.gap(va, lo, hi); // never over a slot-133 buffer's range or another window + lo = std::max(lo, title_lo); // nor past the title's range + hi = std::min(hi, title_hi); const std::uint64_t want = std::clamp(bytes, 1, kTitleWindowMax); const std::uint64_t start = std::max(va & ~(kTitleWindowAlign - 1), lo); std::uint64_t end = va > UINT64_MAX - want - kTitleWindowAlign ? UINT64_MAX @@ -824,7 +846,7 @@ struct DeviceState { // The buffer V#s of the table at `table_va` whose base is in the title's own memory get the address of a copy, // written in place: the title wrote them itself (or copied them), so no Create*View saw them. Images (T#s) and // null slots are skipped; so is a V# already in the arena, so a rewritten one is left alone next time. - void scan_title_table(std::uint64_t table_va) { + void scan_title_table(std::uint64_t table_va, std::uint32_t descriptors) { VkDeviceSize end = 0; { std::lock_guard lock(cbv_heap_mutex); @@ -832,7 +854,9 @@ struct DeviceState { if (it == cbv_heaps.begin()) return; --it; if (table_va >= it->second) return; - end = std::min(it->second, table_va + kTableScanDescriptors * kDescriptorSize); + end = std::min( + it->second, table_va + VkDeviceSize(std::min(descriptors, kTableScanDescriptors)) * + kDescriptorSize); } auto& aliases = leonida::title_va_aliases(); for (VkDeviceSize at = table_va; at + 16 <= end; at += kDescriptorSize) { @@ -5320,7 +5344,9 @@ class Device final [](void* device, std::uint64_t va, std::uint64_t bytes, std::uint64_t& out) { return static_cast(device)->resolve_title_memory(va, bytes, out); }, - [](void* device, std::uint64_t table) { static_cast(device)->scan_title_table(table); }); + [](void* device, std::uint64_t table, std::uint32_t descriptors) { + static_cast(device)->scan_title_table(table, descriptors); + }); if (info.physical && state_.format_properties) { state_.context->set_color_attachment_format( [physical = info.physical, get_props = state_.format_properties](VkFormat format) { @@ -6241,7 +6267,8 @@ class Device final break; } layout.parameters.push_back({parsed.sig.params[i].type, first, parsed.sig.params[i].num_values, - compute.ok ? compute.first_sgpr[i] : rt::rootsig::kNoSgpr}); + compute.ok ? compute.first_sgpr[i] : rt::rootsig::kNoSgpr, + table_view_descriptors(parsed.sig.params[i])}); } register_static_samplers(parsed.sig); auto* signature = new RootSignature( diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp index 37f29459f1..cccb4002fc 100644 --- a/runtime/shims/xmem.cpp +++ b/runtime/shims/xmem.cpp @@ -35,6 +35,7 @@ #include "shims.h" #include "startup_trace.h" +#include "../src/title_va_alias.h" namespace { @@ -66,14 +67,27 @@ void note_attributes(const char* api, uint64_t attributes, size_t size, const vo void* allocate_block(size_t size) { return _aligned_malloc(size ? size : 1, kAlign); } +// Every block and range the title gets here is recorded as the title's memory (src/title_va_alias.h): a shader +// address into it can be given a GPU copy, and an address anywhere else cannot. +void* title_block(size_t size) { + void* p = allocate_block(size); + leonida::title_va_aliases().add_title_memory(reinterpret_cast(p), size ? size : 1); + return p; +} + +void free_title_block(void* p) { + if (p) leonida::title_va_aliases().remove_title_memory(reinterpret_cast(p)); + _aligned_free(p); +} + void* __stdcall XMemAlloc(size_t size, uint64_t attributes) { note_attributes("XMemAlloc", attributes, size, _ReturnAddress()); - return allocate_block(size); + return title_block(size); } void __stdcall XMemFree(void* p, uint64_t attributes) { note_attributes("XMemFree", attributes, kNoSize, _ReturnAddress()); - _aligned_free(p); + free_title_block(p); } // XMemAllocDefault / XMemFreeDefault: the GDK's own allocator behind XMemAlloc and XMemFree, which a title that hooks @@ -82,12 +96,12 @@ void __stdcall XMemFree(void* p, uint64_t attributes) { // released by either free. void* __stdcall XMemAllocDefault(size_t size, uint64_t attributes) { note_attributes("XMemAllocDefault", attributes, size, _ReturnAddress()); - return allocate_block(size); + return title_block(size); } void __stdcall XMemFreeDefault(void* p, uint64_t attributes) { note_attributes("XMemFreeDefault", attributes, kNoSize, _ReturnAddress()); - _aligned_free(p); + free_title_block(p); } // BOOL XMemIsToolsMemAvailable(void). The measured title calls it from one helper, which six out-of-memory paths reach @@ -320,8 +334,18 @@ PVOID reserve_placeholder(void* address, SIZE_T size, SIZE_T alignment) { // XMemMapPhysicalPages. The guest page size sets the alignment and rounding of the region; the host's own pages stay // 4 KiB (host large pages need SeLockMemoryPrivilege). A 2 MiB region the host places is reserved 2 MiB-aligned through // VirtualAlloc2. +void* xmem_virtual_alloc(void* address, SIZE_T size, DWORD allocation_type, ULONGLONG attributes, DWORD protect); + void* WINAPI XMemVirtualAlloc(void* address, SIZE_T size, DWORD allocation_type, ULONGLONG attributes, DWORD protect) { note_attributes("XMemVirtualAlloc", attributes, size, _ReturnAddress()); + void* result = xmem_virtual_alloc(address, size, allocation_type, attributes, protect); + // The title's memory (src/title_va_alias.h). Never forgotten: a released range is no longer committed, which + // the copy also checks. + if (result) leonida::title_va_aliases().add_title_memory(reinterpret_cast(result), size); + return result; +} + +void* xmem_virtual_alloc(void* address, SIZE_T size, DWORD allocation_type, ULONGLONG attributes, DWORD protect) { if (size == 0) { SetLastError(ERROR_INVALID_PARAMETER); return nullptr; @@ -689,7 +713,9 @@ constexpr DWORD kMemGraphics = 0x10000000; constexpr DWORD kMemTitle = 0x40000000; LPVOID WINAPI TitleVirtualAlloc(LPVOID address, SIZE_T size, DWORD allocation_type, DWORD protect) { - return VirtualAlloc(address, size, allocation_type & ~(kMemGraphics | kMemTitle), host_protect(protect)); + LPVOID result = VirtualAlloc(address, size, allocation_type & ~(kMemGraphics | kMemTitle), host_protect(protect)); + if (result) leonida::title_va_aliases().add_title_memory(reinterpret_cast(result), size); + return result; } } // namespace diff --git a/runtime/src/title_va_alias.h b/runtime/src/title_va_alias.h index 6f665f0ec2..1e907ea437 100644 --- a/runtime/src/title_va_alias.h +++ b/runtime/src/title_va_alias.h @@ -37,7 +37,7 @@ class TitleVaAliases { // An address in the title's memory: true, with `shader_va` what a shader must be given (the address itself when // no copy could be made). False: not the title's memory (an arena VA, a buffer of the layer's). using Resolver = bool (*)(void* context, std::uint64_t va, std::uint64_t bytes, std::uint64_t& shader_va); - using TableScanner = void (*)(void* context, std::uint64_t table_va); + using TableScanner = void (*)(void* context, std::uint64_t table_va, std::uint32_t descriptors); // [title_va, title_va + bytes) is reached as [shader_va, shader_va + bytes). A range that overlaps a live one // replaces it (the title has placed a new buffer over pages it released). False for an empty or wrapping range. @@ -109,9 +109,9 @@ class TitleVaAliases { if (va && shader_va(va) != va) untranslated_[kind].fetch_add(1, std::memory_order_relaxed); } - // Before a submission: the device rewrites the buffer V#s of the table at `table_va` (a console VA in one of its - // shader-visible CBV/SRV/UAV heaps). - void scan_table(std::uint64_t table_va) { + // Before a submission: the device rewrites the buffer V#s of the `descriptors` slots the root signature declares + // for the table at `table_va` (a console VA in one of its shader-visible CBV/SRV/UAV heaps). + void scan_table(std::uint64_t table_va, std::uint32_t descriptors) { TableScanner scanner; void* context; { @@ -119,7 +119,52 @@ class TitleVaAliases { scanner = scanner_; context = hook_context_; } - if (scanner) scanner(context, table_va); + if (scanner) scanner(context, table_va, descriptors); + } + + // The scan's cost, per ExecuteCommandLists that had tables to scan. + void note_scan(std::uint64_t nanoseconds) { + scans_.fetch_add(1, std::memory_order_relaxed); + scan_ns_.fetch_add(nanoseconds, std::memory_order_relaxed); + std::uint64_t seen = scan_max_ns_.load(std::memory_order_relaxed); + while (nanoseconds > seen && !scan_max_ns_.compare_exchange_weak(seen, nanoseconds)) { + } + } + std::uint64_t scans() const { return scans_.load(std::memory_order_relaxed); } + std::uint64_t scan_ns() const { return scan_ns_.load(std::memory_order_relaxed); } + std::uint64_t scan_max_ns() const { return scan_max_ns_.load(std::memory_order_relaxed); } + + // The title's own memory, as the xmem shims hand it out (XMemAlloc, XMemVirtualAlloc, the title's VirtualAlloc): + // only an address in one of these ranges gets a copy. A base anywhere else (the runtime's own heap, a host DLL) + // is left as it was and counted. + void add_title_memory(std::uint64_t base, std::uint64_t bytes) { + if (!base || !bytes || base > UINT64_MAX - bytes) return; + std::uint64_t begin = base, end = base + bytes; + std::unique_lock lock(memory_mutex_); + // A commit inside a reserved range, or two that overlap, are one range. + auto it = memory_.upper_bound(begin); + if (it != memory_.begin() && std::prev(it)->second > begin) --it; + while (it != memory_.end() && it->first < end) { + begin = std::min(begin, it->first); + end = std::max(end, it->second); + it = memory_.erase(it); + } + memory_[begin] = end; + } + void remove_title_memory(std::uint64_t base) { + std::unique_lock lock(memory_mutex_); + memory_.erase(base); + } + // The title range that holds `va`: [lo, hi). False when none does. + bool title_memory(std::uint64_t va, std::uint64_t& lo, std::uint64_t& hi) const { + std::shared_lock lock(memory_mutex_); + auto it = memory_.upper_bound(va); + if (it == memory_.begin()) return false; + --it; + if (va >= it->second) return false; + lo = it->first; + hi = it->second; + return true; } // The first device to register keeps the hooks until it clears them. @@ -166,6 +211,9 @@ class TitleVaAliases { TableScanner scanner_ = nullptr; std::array, kind_count> translated_{}; std::array, kind_count> untranslated_{}; + std::atomic scans_{0}, scan_ns_{0}, scan_max_ns_{0}; + mutable std::shared_mutex memory_mutex_; + std::map memory_; // the title's memory: base -> end }; // The process's table: the device's title ranges and hooks, read by the command lists and descriptor writers. diff --git a/runtime/test/d3d12_title_va_test.cpp b/runtime/test/d3d12_title_va_test.cpp index d971c716e3..7be1e880b4 100644 --- a/runtime/test/d3d12_title_va_test.cpp +++ b/runtime/test/d3d12_title_va_test.cpp @@ -301,7 +301,7 @@ int check_kind(Context& c, const char* kind, DWORD protect, int& checks) { // - a V# made by CreateConstantBufferView (translated when written); // - a root view (translated when set). // Negative controls: a raw V# whose base is an arena buffer and a T#-shaped slot whose base is the ring keep their -// bytes; an address the ring does not hold is left alone. +// bytes; committed memory that is not the title's, and a title range with no committed page, are left alone. int check_title_memory(Context& c, int& checks) { constexpr UINT64 ring_bytes = 256 * 1024; auto* ring = static_cast(VirtualAlloc(nullptr, ring_bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); @@ -309,6 +309,7 @@ int check_title_memory(Context& c, int& checks) { const auto ring_va = reinterpret_cast(ring); EXPECT(ring_va >= c.arena); auto& aliases = leonida::title_va_aliases(); + aliases.add_title_memory(ring_va, ring_bytes); // as the xmem shims record what they hand the title const std::uint64_t table_before = aliases.translated(leonida::TitleVaAliases::table_view); const std::uint64_t created_before = aliases.translated(leonida::TitleVaAliases::created_view); const std::uint64_t root_before = aliases.translated(leonida::TitleVaAliases::root_view); @@ -433,14 +434,24 @@ int check_title_memory(Context& c, int& checks) { static_cast(aliases.translated(leonida::TitleVaAliases::root_view) - root_before)); EXPECT(raw_ok == kElements && cbv_ok == kElements && root_ok == kElements); EXPECT(rewritten && arena_kept && image_kept); - // An address in no committed page is not title memory: left alone, nothing made for it. + // Left alone and counted: committed memory that is not the title's (the runtime's own, say), and a title range + // with no committed page. + const std::uint64_t untranslated_before = aliases.untranslated(leonida::TitleVaAliases::created_view); + void* host = VirtualAlloc(nullptr, 65536, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); void* gone = VirtualAlloc(nullptr, 65536, MEM_RESERVE, PAGE_READWRITE); - const auto gone_va = reinterpret_cast(gone); - const D3D12_CONSTANT_BUFFER_VIEW_DESC reserved_only{gone_va, 256}; - c.device->CreateConstantBufferView(&reserved_only, D3D12_CPU_DESCRIPTOR_HANDLE{cpu + 5 * inc}); - EXPECT(vsharp_base(cpu + 5 * inc) == (gone_va & 0xFFFFFFFFFFFFull)); + const auto host_va = reinterpret_cast(host), gone_va = reinterpret_cast(gone); + aliases.add_title_memory(gone_va, 65536); + const D3D12_CONSTANT_BUFFER_VIEW_DESC not_title{host_va, 256}, reserved_only{gone_va, 256}; + c.device->CreateConstantBufferView(¬_title, D3D12_CPU_DESCRIPTOR_HANDLE{cpu + 5 * inc}); + c.device->CreateConstantBufferView(&reserved_only, D3D12_CPU_DESCRIPTOR_HANDLE{cpu + 6 * inc}); + EXPECT(vsharp_base(cpu + 5 * inc) == (host_va & 0xFFFFFFFFFFFFull)); + EXPECT(vsharp_base(cpu + 6 * inc) == (gone_va & 0xFFFFFFFFFFFFull)); + EXPECT(aliases.untranslated(leonida::TitleVaAliases::created_view) - untranslated_before == 2); + aliases.remove_title_memory(gone_va); + aliases.remove_title_memory(ring_va); + VirtualFree(host, 0, MEM_RELEASE); VirtualFree(gone, 0, MEM_RELEASE); - checks += 3; + checks += 4; return 0; } diff --git a/runtime/test/title_va_alias_test.cpp b/runtime/test/title_va_alias_test.cpp index e27faa8f60..84758dbc97 100644 --- a/runtime/test/title_va_alias_test.cpp +++ b/runtime/test/title_va_alias_test.cpp @@ -40,6 +40,14 @@ int main() { a.note(title + 8, leonida::TitleVaAliases::vertex_view); a.note(title - 8, leonida::TitleVaAliases::vertex_view); EXPECT(a.untranslated(leonida::TitleVaAliases::vertex_view) == 1); + // The title's memory: a commit inside a reservation is one range; outside every range is not the title's. + std::uint64_t mlo = 0, mhi = 0; + a.add_title_memory(0x40000000, 0x100000); + a.add_title_memory(0x40010000, 0x1000); + EXPECT(a.title_memory(0x40080000, mlo, mhi) && mlo == 0x40000000 && mhi == 0x40100000); + EXPECT(!a.title_memory(0x40100000, mlo, mhi) && !a.title_memory(0x3FFFFFFF, mlo, mhi)); + a.remove_title_memory(0x40000000); + EXPECT(!a.title_memory(0x40080000, mlo, mhi)); // A wrapping target (an import below heap_base) is kept as is: modular arithmetic. constexpr std::uint64_t below = 0xFFFFFFFFFFF00000ull; EXPECT(a.add(title + 0x100000, size, below) && a.shader_va(title + 0x100010) == below + 0x10); From e997a1f28ff1e61d33d23b3946f53daae9e9e0ca Mon Sep 17 00:00:00 2001 From: Etr0p <216035314+Etr0p@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:59:03 +0100 Subject: [PATCH 14/27] test: cs_user_data's root-view-to-table mode names its pointer target, not the GLSL keyword out Co-Authored-By: Claude Opus 5.5 --- runtime/test/glsl/cs_user_data.comp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/runtime/test/glsl/cs_user_data.comp b/runtime/test/glsl/cs_user_data.comp index b8f2c12b90..07b4b7e4d4 100644 --- a/runtime/test/glsl/cs_user_data.comp +++ b/runtime/test/glsl/cs_user_data.comp @@ -48,8 +48,8 @@ void main() { if (pc.s[5] == 0xFFFFFFFDu) { // Root view read to a table pointer (d3d12_title_va_test): read through the root view, 256 bytes past its // base, and write where the table entry's raw 64-bit VA points. - Words out = at(uvec2(table.w[0], table.w[1])); - out.w[i] = result.w[64u + i] + pc.s[4]; + Words target = at(uvec2(table.w[0], table.w[1])); + target.w[i] = result.w[64u + i] + pc.s[4]; return; } if (pc.s[5] == 0u) { From 6d7842a55e34eef02150567e05a955b7c2c6a7fd Mon Sep 17 00:00:00 2001 From: Etr0p <216035314+Etr0p@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:59:21 +0100 Subject: [PATCH 15/27] d3d12: read LEONIDA_TITLE_WINDOWS_MB with getenv_s, as the file's other variables Co-Authored-By: Claude Opus 5.5 --- runtime/shims/d3d12_vulkan_device.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index e431cf8cf2..4596535527 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -5337,8 +5337,12 @@ class Device final info.xdxr_acceleration_structures && info.buffer_device_address); state_.context->set_before_execute([this] { state_.refresh_shadows(); }); - if (const char* mb = std::getenv("LEONIDA_TITLE_WINDOWS_MB"); mb && *mb) - state_.title_window_cap = std::strtoull(mb, nullptr, 10) << 20; + { + char text[16] = {}; + size_t length = 0; + if (getenv_s(&length, text, "LEONIDA_TITLE_WINDOWS_MB") == 0 && length > 1) + state_.title_window_cap = std::strtoull(text, nullptr, 10) << 20; + } leonida::title_va_aliases().set_hooks( &state_, [](void* device, std::uint64_t va, std::uint64_t bytes, std::uint64_t& out) { From f9db5e6bb3231c18c6b12d27b25f0ae18297966d Mon Sep 17 00:00:00 2001 From: Etr0p <216035314+Etr0p@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:05:45 +0100 Subject: [PATCH 16/27] d3d12: a bound table's slots the title wrote in its own heap backing are pulled in before the scan Co-Authored-By: Claude Opus 5.5 --- runtime/shims/d3d12_vulkan_device.cpp | 2 ++ runtime/src/title_va_alias.h | 25 +++++++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 4596535527..79d7d63fd1 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -859,6 +859,8 @@ struct DeviceState { kDescriptorSize); } auto& aliases = leonida::title_va_aliases(); + // Slots the title wrote in its own backing of this heap, if it gave the heap one. + aliases.pull_descriptors(arena.mapped + table_va, std::size_t(end - table_va)); for (VkDeviceSize at = table_va; at + 16 <= end; at += kDescriptorSize) { auto* w = reinterpret_cast(arena.mapped + at); const std::uint32_t w0 = w[0], w1 = w[1], w2 = w[2], w3 = w[3]; diff --git a/runtime/src/title_va_alias.h b/runtime/src/title_va_alias.h index 1e907ea437..987cf021be 100644 --- a/runtime/src/title_va_alias.h +++ b/runtime/src/title_va_alias.h @@ -167,6 +167,28 @@ class TitleVaAliases { return true; } + // A title that gives a descriptor heap its own backing memory (__XMemAllocationHooks__) writes descriptors there + // itself, while shaders read the layer's heap. The layer that keeps that mapping registers a source: before a + // bound table is scanned, it copies the slots the title wrote in its own memory over the layer's copy + // ([real, real + bytes) is the layer heap's CPU memory). Returns how many slots it copied. + using DescriptorSource = std::uint64_t (*)(void* context, std::uint8_t* real, std::size_t bytes); + void set_descriptor_source(void* context, DescriptorSource source) { + std::lock_guard lock(hook_mutex_); + source_context_ = context; + source_ = source; + } + void pull_descriptors(std::uint8_t* real, std::size_t bytes) { + DescriptorSource source; + void* context; + { + std::lock_guard lock(hook_mutex_); + source = source_; + context = source_context_; + } + if (source) pulled_.fetch_add(source(context, real, bytes), std::memory_order_relaxed); + } + std::uint64_t pulled() const { return pulled_.load(std::memory_order_relaxed); } + // The first device to register keeps the hooks until it clears them. void set_hooks(void* context, Resolver resolver, TableScanner scanner) { std::lock_guard lock(hook_mutex_); @@ -209,6 +231,9 @@ class TitleVaAliases { void* hook_context_ = nullptr; Resolver resolver_ = nullptr; TableScanner scanner_ = nullptr; + void* source_context_ = nullptr; + DescriptorSource source_ = nullptr; + std::atomic pulled_{0}; std::array, kind_count> translated_{}; std::array, kind_count> untranslated_{}; std::atomic scans_{0}, scan_ns_{0}, scan_max_ns_{0}; From dbab003b0e1ed5f6ab62b990971d60353857d138 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Mon, 23 Nov 2026 21:11:37 +0100 Subject: [PATCH 17/27] d3d12: quad lists draw as triangle-list indices (0 1 2) (0 2 3) so flat inputs use the first quad vertex, and the PSO topology type is read as raw bits Taken from the follow-up patch of @matheuskshn (930e78a2, tested by them on an RTX 4070 Ti: replay_quad_list_test fails the two non-indexed cases on a6b31d51 and passes with it). Re-run here: replay_quad_list_test and d3d12_rect_list_test exit 0 on the pod (Wine, RTX 4090). --- docs/d3d12_vulkan.md | 7 +- runtime/CMakeLists.txt | 6 ++ runtime/shims/d3d12_vulkan_device.cpp | 28 ++++--- runtime/src/rect_list_geometry.h | 2 + runtime/src/vulkan_backend.h | 2 +- runtime/src/vulkan_replay.h | 54 ++++++------ runtime/test/replay_quad_list_test.cpp | 110 +++++++++++++++++++++++++ 7 files changed, 168 insertions(+), 41 deletions(-) create mode 100644 runtime/test/replay_quad_list_test.cpp diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 3233715169..4f7e90553a 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2084,7 +2084,12 @@ The trace will enumerate them. The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiveTopology(17)`, with a PSO whose topology type is 19) and quad list (`IASetPrimitiveTopology(19)`). The facts are from xvalkyrie (GPL-3.0, commit `53af7df77c10`; no code taken): a rectangle is three corners and the fourth is v2 + v3 - v1 for the position and every interpolant, after the vertex stage; a quad is four vertices. The layer draws both as triangles (`d3d12_rect_list_test`, RTX 4090: 4096 of 4096 pixels, the colour plane exact, quad list bit-exact). - **Rectangle list**: PSO type 19 builds a triangle-list pipeline plus a generated geometry stage (`src/rect_list_geometry.h`, written from the vertex shader's own outputs) that takes the three corners and emits the strip v1 v2 v3 v4 (same winding). It has to be post-vertex-stage: the translated vertex shaders fetch by V# themselves, and the fourth corner is a function of what they write. A corner value with the same bits at all three corners (a flat attribute) is copied. Needs `geometryShader` (else `E_NOTIMPL`), no application GS, and a vertex shader with no ClipDistance, CullDistance, Layer or ViewportIndex output. -- **Quad list**: one four-vertex triangle fan per quad (the pattern 0 1 2, 0 2 3). The translated vertex id is `VertexIndex - BaseVertex`, so each fan reads the index values 4q..4q+3: from the application's index buffer when the draw is indexed, else from a shared 0, 1, 2, ... buffer in the arena's reserved pages (16384 quads per draw at most, more are cut off with a log line), with the draw's first vertex as the vertex offset. A quad's instances are drawn together, so several overlapping blended instances rasterize quad by quad rather than instance by instance. The PSO type is the ordinary triangle type. +- **Quad list**: a non-indexed draw uses a shared index buffer containing the triangle-list pattern + `0 1 2, 0 2 3` for each quad. Both triangles start at the first vertex for flat inputs. One draw preserves instance + order and supports up to 16384 quads. The draw's first vertex becomes the vertex offset. Indexed draws still + read the application's index buffer as one four-vertex fan per quad. Vulkan fans use a different provoking + vertex for flat inputs, and overlapping blended instances rasterize quad by quad in this path. The PSO type + is the ordinary triangle type. ## 4. Object model mapping diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 3be2911a9e..6b2db91ac7 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2864,6 +2864,12 @@ if(TARGET Vulkan::Headers) target_compile_definitions(replay_readback_stages_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) endif() add_test(NAME replay_readback_stages COMMAND replay_readback_stages_test) + add_executable(replay_quad_list_test test/replay_quad_list_test.cpp) + target_link_libraries(replay_quad_list_test PRIVATE Vulkan::Headers) + if(WIN32) + target_compile_definitions(replay_quad_list_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + endif() + add_test(NAME replay_quad_list COMMAND replay_quad_list_test) # emit of an enhanced texture barrier: no heap allocation for one layout piece, one barrier for each piece (no GPU). add_executable(replay_texture_barrier_test test/replay_texture_barrier_test.cpp) target_link_libraries(replay_texture_barrier_test PRIVATE Vulkan::Headers) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index fbeccc3d34..7bd9cef959 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -66,7 +66,8 @@ constexpr UINT kDescriptorSize = descriptor_size; // The first 64 KiB of the GPU address arena are never handed out: VA 0 stays invalid, and the page is kept zero // for unbound vertex and index buffers to read (D3D12 reads zeros there). constexpr VkDeviceSize kZeroPage = 64 * 1024; // zeroed: what unbound vertex and index buffers read -constexpr std::uint32_t kQuadIndexCount = 64 * 1024; // 0, 1, 2, ... that non-indexed quad lists draw with (16384 quads) +constexpr std::uint32_t kQuadIndicesPerQuad = leonida::quad_triangle_indices.size(); +constexpr std::uint32_t kQuadIndexCount = 16 * 1024 * kQuadIndicesPerQuad; constexpr VkDeviceSize kArenaReserved = kZeroPage + VkDeviceSize(kQuadIndexCount) * sizeof(std::uint32_t); static_assert(sizeof(leonida::TargetView) <= kDescriptorSize); @@ -2828,7 +2829,8 @@ leonida::cached_pso::Key pipeline_key(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& key.text(e.SemanticName).u32(e.SemanticIndex).u32(e.Format).u32(e.InputSlot).u32(e.AlignedByteOffset); key.u32(e.InputSlotClass).u32(e.InstanceDataStepRate); } - key.u32(desc.IBStripCutValue).u32(desc.PrimitiveTopologyType).u32(desc.NumRenderTargets); + key.u32(desc.IBStripCutValue).u32(std::bit_cast(desc.PrimitiveTopologyType)) + .u32(desc.NumRenderTargets); for (const DXGI_FORMAT format : desc.RTVFormats) key.u32(format); key.u32(desc.DSVFormat).u32(desc.SampleDesc.Count).u32(desc.SampleDesc.Quality).u32(desc.NodeMask); return leonida::sha256_hex(key.data()); @@ -3195,13 +3197,15 @@ class PipelineState final // The console's rectangle topology type (19) draws as triangles through a generated geometry stage that adds // each rectangle's fourth corner (src/rect_list_geometry.h); it needs the same device feature, and no GS of // the application's own. - const bool rect_list = !mesh && desc.PrimitiveTopologyType == leonida::topology_type_rect_list; + // Decode the ABI field as bits. The console's value is outside the PC enum's range. + const auto topology_type = std::bit_cast(desc.PrimitiveTopologyType); + const bool rect_list = !mesh && topology_type == leonida::topology_type_rect_list; if (rect_list && (geometry || !device_.info.features.geometryShader)) { log_once("a rectangle-list pipeline needs the geometryShader feature and no geometry shader; stage", 0); return geometry ? E_INVALIDARG : E_NOTIMPL; } - if (geometry && desc.PrimitiveTopologyType != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) { - log_once("a translated geometry shader takes triangles; topology type", desc.PrimitiveTopologyType); + if (geometry && topology_type != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) { + log_once("a translated geometry shader takes triangles; topology type", topology_type); return E_INVALIDARG; } const UINT samples = desc.SampleDesc.Count; @@ -3484,12 +3488,12 @@ class PipelineState final } VkPipelineInputAssemblyStateCreateInfo assembly{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; // Type 19 is the console's rectangles, drawn as triangle lists through the geometry stage added above. - switch (mesh || rect_list ? D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE : desc.PrimitiveTopologyType) { // mesh: not used + switch (mesh || rect_list ? D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE : topology_type) { // mesh: not used case D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT: assembly.topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST; break; case D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE: assembly.topology = VK_PRIMITIVE_TOPOLOGY_LINE_LIST; break; case D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE: assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; break; default: - log_once("primitive topology type not supported:", desc.PrimitiveTopologyType); + log_once("primitive topology type not supported:", topology_type); return E_INVALIDARG; } if (!mesh) { // a mesh PSO has no index buffer: its strip cut is ignored @@ -3511,7 +3515,7 @@ class PipelineState final return E_INVALIDARG; } if (r.FillMode != D3D12_FILL_MODE_SOLID || - desc.PrimitiveTopologyType != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) return E_INVALIDARG; + topology_type != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) return E_INVALIDARG; // Target-independent rasterization is a separate pipeline path; do not silently ignore its count. if (r.ForcedSampleCount) return E_NOTIMPL; } @@ -5201,9 +5205,11 @@ class Device final } arena.mapped = static_cast(mapped); std::memset(arena.mapped, 0, kZeroPage); // the zero page unbound vertex and index buffers read - { - auto* iota = reinterpret_cast(arena.mapped + kZeroPage); - for (std::uint32_t i = 0; i < kQuadIndexCount; ++i) iota[i] = i; + auto* indices = reinterpret_cast(arena.mapped + kZeroPage); + for (std::uint32_t i = 0; i < kQuadIndexCount; i += kQuadIndicesPerQuad) { + const std::uint32_t base = i / kQuadIndicesPerQuad * 4; + std::transform(leonida::quad_triangle_indices.begin(), leonida::quad_triangle_indices.end(), indices + i, + [base](std::uint32_t index) { return base + index; }); } VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; address.buffer = arena.buffer; diff --git a/runtime/src/rect_list_geometry.h b/runtime/src/rect_list_geometry.h index 335e4db00e..86826317c6 100644 --- a/runtime/src/rect_list_geometry.h +++ b/runtime/src/rect_list_geometry.h @@ -22,6 +22,7 @@ // Plain word editing, standard library only. #include +#include #include #include #include @@ -35,6 +36,7 @@ namespace leonida { constexpr std::uint32_t topology_rect_list = 17; constexpr std::uint32_t topology_quad_list = 19; constexpr std::uint32_t topology_type_rect_list = 19; +constexpr std::array quad_triangle_indices{0, 1, 2, 0, 2, 3}; // The geometry stage for `vertex_words`' outputs; empty, with `why` set, when the vertex stage cannot be expanded. inline std::vector rect_list_geometry(const std::vector& vertex_words, std::string& why) { diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index b05f5fc1ad..9dd83f20d8 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -1247,7 +1247,7 @@ class VulkanContext { replay_.zero_size = size; } - // 0, 1, 2, ... as 32-bit indices, for non-indexed quad lists (ReplayFunctions::quad_indices). + // Pre-expanded 32-bit triangle indices for non-indexed quad lists (ReplayFunctions::quad_indices). void set_quad_indices(VkBuffer buffer, VkDeviceSize offset, std::uint32_t count) { std::unique_lock lock(resource_mutex_); replay_.quad_indices = buffer; diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 5093fbd027..35ad689b23 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -868,7 +868,7 @@ struct ReplayFunctions { VkBuffer zero_buffer = VK_NULL_HANDLE; VkDeviceSize zero_offset = 0; VkDeviceSize zero_size = 0; - // 0, 1, 2, ... as 32-bit indices: what a non-indexed quad list is drawn with (quad_index_count of them). + // 32-bit triangle indices for non-indexed quad lists: 0, 1, 2, 0, 2, 3, then the same pattern for each quad. VkBuffer quad_indices = VK_NULL_HANDLE; VkDeviceSize quad_indices_offset = 0; std::uint32_t quad_index_count = 0; @@ -2182,7 +2182,7 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct p.vertex_sizes[slot] = size; p.vertex_strides[slot] = (pipeline->zero_step_slots & (1u << slot)) ? 0 : view.stride; } - // A non-indexed quad list is drawn from the shared 0, 1, 2, ... index buffer (emit). + // A non-indexed quad list is drawn from the shared triangle index buffer (emit). if (!draw.indexed && !draw.mesh && draw.topology == topology_quad_list && !vk.quad_indices) return ReplayResult::unresolved_resource; if (draw.indexed) { @@ -2219,9 +2219,8 @@ inline VkPrimitiveTopology vulkan_topology(std::uint32_t topology) { case 11: return VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY; case 12: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY; case 13: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY; - // The console's lists (rect_list_geometry.h). A rectangle list is drawn as the triangle list of its three - // corners, the pipeline's geometry stage adds the fourth. A quad (v0 v1 v2 v3) is the fan (v0 v1 v2) (v0 v2 v3), - // which is the index pattern 0 1 2, 0 2 3; the draw below issues one fan per quad. + // Rectangles draw as triangle lists through a geometry stage. Indexed quads draw as separate fans; + // emit() overrides non-indexed quads to a triangle list backed by the shared indices. case topology_rect_list: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; case topology_quad_list: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN; default: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; @@ -4103,7 +4102,8 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c // A mesh pipeline has no input assembly: its topology comes from the shader, and neither the topology // nor primitive restart is dynamic state there (VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-07065). if (!draw->mesh) { - const VkPrimitiveTopology topology = detail::vulkan_topology(draw->topology); + const VkPrimitiveTopology topology = draw->topology == topology_quad_list && !draw->indexed + ? VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST : detail::vulkan_topology(draw->topology); vk.set_primitive_topology(command_buffer, topology); const bool restart = draw->indexed && detail::strip_topology(topology) && ((graphics.strip_cut == 1 && d.index_type == VK_INDEX_TYPE_UINT16) || @@ -4121,29 +4121,27 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c if (draw->mesh) { vk.draw_mesh_tasks(command_buffer, draw->count, draw->instances, draw->first); } else if (draw->topology == topology_quad_list) { - // One four-vertex fan per quad. The translated vertex shaders take their vertex id from the index - // value (VertexIndex - BaseVertex), so a fan must be drawn with the index values 4q..4q+3: an - // indexed draw reads them from the application's index buffer, a non-indexed one from the - // shared 0, 1, 2, ... buffer (quad_indices), with the draw's first vertex as the vertex offset, as - // VertexIndex is first + i for a plain draw. - const bool generated = !draw->indexed; // prepare() has checked that quad_indices is there - if (generated) - vk.bind_index_buffer(command_buffer, vk.quad_indices, vk.quad_indices_offset, VK_INDEX_TYPE_UINT32); - else + if (draw->indexed) { + // Indexed quads still read their vertices from the application's index buffer, one fan per quad. vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type); - // The shared buffer holds quad_index_count / 4 quads: more are cut off here and said so. - const std::uint32_t wanted = draw->count / 4, room = generated ? vk.quad_index_count / 4 : UINT32_MAX; - const std::uint32_t quads = std::min(wanted, room); - if (quads < wanted) - std::fprintf(stderr, "[rt] d3d12: a non-indexed quad list of %u quads draws only the first %u\n", - wanted, quads); - const std::int32_t vertex_offset = generated ? std::int32_t(draw->first) : draw->base_vertex; - // All the instances of a quad are drawn together (a split by instance would zero the translated - // instance id, InstanceIndex - BaseInstance), so with several instances the primitive order is quad - // by quad, not instance by instance: only overlapping blended instances can tell. - for (std::uint32_t quad = 0; quad < quads; ++quad) - vk.draw_indexed(command_buffer, 4, draw->instances, (generated ? 0 : draw->first) + 4 * quad, - vertex_offset, draw->first_instance); + for (std::uint32_t quad = 0; quad < draw->count / 4; ++quad) + vk.draw_indexed(command_buffer, 4, draw->instances, draw->first + 4 * quad, + draw->base_vertex, draw->first_instance); + } else { + // Both triangles start at the quad's first vertex for flat inputs. One draw also preserves + // the original instance order, and VertexIndex - BaseVertex still gives 4q + k. + constexpr std::uint32_t indices_per_quad = quad_triangle_indices.size(); + const std::uint32_t wanted = draw->count / 4; + const std::uint32_t quads = std::min(wanted, vk.quad_index_count / indices_per_quad); + if (quads < wanted) + std::fprintf(stderr, "[rt] d3d12: a non-indexed quad list of %u quads draws only the first %u\n", + wanted, quads); + if (quads) { + vk.bind_index_buffer(command_buffer, vk.quad_indices, vk.quad_indices_offset, VK_INDEX_TYPE_UINT32); + vk.draw_indexed(command_buffer, quads * indices_per_quad, draw->instances, 0, + std::int32_t(draw->first), draw->first_instance); + } + } } else if (draw->indexed) { vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type); vk.draw_indexed(command_buffer, draw->count, draw->instances, draw->first, draw->base_vertex, diff --git a/runtime/test/replay_quad_list_test.cpp b/runtime/test/replay_quad_list_test.cpp new file mode 100644 index 0000000000..15b0c7e781 --- /dev/null +++ b/runtime/test/replay_quad_list_test.cpp @@ -0,0 +1,110 @@ +// Quad lists without an index buffer are one triangle-list draw. A switch back to Vulkan triangle fans +// changes the provoking vertex for flat attributes and the order of overlapping blended instances. +#include "../src/vulkan_replay.h" + +#include +#include +#include + +namespace { +using namespace leonida; + +struct DrawCall { + VkPrimitiveTopology topology; + VkBuffer buffer; + VkDeviceSize offset; + VkIndexType index_type; + std::uint32_t count, instances, first_index; + std::int32_t base_vertex; + std::uint32_t first_instance; + bool operator==(const DrawCall&) const = default; +}; + +DrawCall recorded{}; +std::vector calls; + +bool check(bool condition, const char* description) { + if (!condition) std::fprintf(stderr, "FAIL: %s\n", description); + return condition; +} +} + +int main() { + using namespace leonida; + ReplayFunctions vk{}; + vk.begin_rendering = +[](VkCommandBuffer, const VkRenderingInfo*) {}; + vk.end_rendering = +[](VkCommandBuffer) {}; + vk.bind_pipeline = +[](VkCommandBuffer, VkPipelineBindPoint, VkPipeline) {}; + vk.push_constants = +[](VkCommandBuffer, VkPipelineLayout, VkShaderStageFlags, std::uint32_t, + std::uint32_t, const void*) {}; + vk.set_viewport = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, const VkViewport*) {}; + vk.set_scissor = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, const VkRect2D*) {}; + vk.set_primitive_topology = +[](VkCommandBuffer, VkPrimitiveTopology topology) { recorded.topology = topology; }; + vk.set_primitive_restart_enable = +[](VkCommandBuffer, VkBool32) {}; + vk.set_stencil_reference = +[](VkCommandBuffer, VkStencilFaceFlags, std::uint32_t) {}; + vk.set_blend_constants = +[](VkCommandBuffer, const float*) {}; + vk.bind_index_buffer = +[](VkCommandBuffer, VkBuffer buffer, VkDeviceSize offset, VkIndexType type) { + recorded.buffer = buffer; + recorded.offset = offset; + recorded.index_type = type; + }; + vk.draw_indexed = +[](VkCommandBuffer, std::uint32_t count, std::uint32_t instances, std::uint32_t first, + std::int32_t base, std::uint32_t first_instance) { + recorded.count = count; + recorded.instances = instances; + recorded.first_index = first; + recorded.base_vertex = base; + recorded.first_instance = first_instance; + calls.push_back(recorded); + }; + + vk.quad_indices = reinterpret_cast(std::uintptr_t{1}); + vk.quad_indices_offset = 64; + vk.quad_index_count = 12; + const auto app_buffer = reinterpret_cast(std::uintptr_t{2}); + + GraphicsPipeline graphics{}; + const auto collect = [&](const Draw& draw) { + calls.clear(); + CommandList list; + if (!list.draw(draw) || !list.close()) return false; + PreparedList prepared; + prepared.list = &list; + prepared.commands.resize(1); + prepared.commands[0].draw = 0; + auto& entry = prepared.draws.emplace_back(); + entry.graphics = &graphics; + entry.index_buffer = app_buffer; + entry.index_offset = 32; + emit(prepared, VK_NULL_HANDLE, vk); + return true; + }; + + Draw draw{}; + draw.pipeline = 1; + draw.topology = topology_quad_list; + draw.count = 8; + draw.instances = 2; + draw.first = 13; + draw.first_instance = 7; + + const DrawCall triangles{VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, vk.quad_indices, 64, VK_INDEX_TYPE_UINT32, + 12, 2, 0, 13, 7}; + bool ok = check(collect(draw) && calls == std::vector{triangles}, + "non-indexed quads use one triangle-list draw and preserve draw bases"); + draw.count = 13; + ok &= check(collect(draw) && calls == std::vector{triangles}, + "a draw is limited to whole quads in the generated index buffer"); + draw.count = 3; + ok &= check(collect(draw) && calls.empty(), "an incomplete quad emits no draw"); + + draw.indexed = true; + draw.count = 8; + draw.first = 5; + draw.base_vertex = -2; + const DrawCall first_fan{VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN, app_buffer, 32, VK_INDEX_TYPE_UINT16, 4, 2, 5, -2, 7}; + const DrawCall second_fan{VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN, app_buffer, 32, VK_INDEX_TYPE_UINT16, 4, 2, 9, -2, 7}; + ok &= check(collect(draw) && calls == std::vector{first_fan, second_fan}, + "indexed quads use the application's index buffer and base vertex"); + return ok ? 0 : 1; +} From 6d1f046da6083c623bf78f2438f37c988df6b3f8 Mon Sep 17 00:00:00 2001 From: Etr0p <216035314+Etr0p@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:13:38 +0100 Subject: [PATCH 18/27] docs, comments: describe the title's VA by its range, not by a measured value Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_vulkan.md | 2 +- runtime/shims/d3d12_vulkan_device.cpp | 2 +- runtime/src/title_va_alias.h | 2 +- runtime/test/title_va_alias_test.cpp | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index f108cc37d3..9096e475cb 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -1501,7 +1501,7 @@ a console client can address is an arena range, whichever heap it comes from. - the title points root views and V#s at its own memory, for instance a per-frame constant ring (#8862, section 3.5 of `docs/retail_boot_chain.md`). -On Windows these are user-mode addresses around 1.5 TiB, far past the arena (at most 4095 MiB, and descriptor +On Windows these are user-mode addresses far above 4 GiB, past the arena (at most 4095 MiB, and descriptor tables must stay below 4 GiB), so `heap_base + VA` names nothing the layer made (the D3D-53 failure above). The layer therefore replaces such an address, wherever it sees one, by the console VA of a GPU copy of that memory (`runtime/src/title_va_alias.h`): diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 79d7d63fd1..6d94072525 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -2275,7 +2275,7 @@ class Resource final return E_INVALIDARG; const auto* pages = static_cast(address); // The shadow is a range of the GPU address arena when it fits there (docs/d3d12_vulkan.md section 3.3). - // The title's VA is about 1.5 TiB on Windows, far past the arena, so a shader's heap_base + VA would miss + // The title's VA is a user-mode Windows address far above 4 GiB, past the arena, so a shader's heap_base + VA would miss // any buffer of the layer's; the root views and V#s the layer writes for that VA name the arena offset // instead (src/title_va_alias.h), a VA below 4 GiB that a root view and a V#'s 48 bits both hold. The arena // is host-visible, so the per-submission copy writes it in place. diff --git a/runtime/src/title_va_alias.h b/runtime/src/title_va_alias.h index 987cf021be..829c1d8740 100644 --- a/runtime/src/title_va_alias.h +++ b/runtime/src/title_va_alias.h @@ -4,7 +4,7 @@ // // A translated shader computes heap_base + console_va, with heap_base the GPU address arena's device address. The // layer chooses every console VA it hands out, so they all land in the arena. The title does not always use them: -// - device slot 133 places a buffer at the CPU address of the title's own pages (about 1.5 TiB on Windows); +// - device slot 133 places a buffer at the CPU address of the title's own pages (a user-mode Windows address, far above 4 GiB); // - the title points V#s and root views at its own memory (a per-frame constant ring, #8862 section 3.5). // Both are far past the arena, so heap_base + VA reads nothing the layer made. An address inside such a range is // therefore replaced, wherever the layer can see it, by the console VA of a GPU copy of that range: its arena offset diff --git a/runtime/test/title_va_alias_test.cpp b/runtime/test/title_va_alias_test.cpp index 84758dbc97..133f7f2e54 100644 --- a/runtime/test/title_va_alias_test.cpp +++ b/runtime/test/title_va_alias_test.cpp @@ -11,7 +11,7 @@ int main() { leonida::TitleVaAliases a; - constexpr std::uint64_t title = 0x18500000000ull; // the shape of a Windows VA past 1 TiB + constexpr std::uint64_t title = 0x20000000000ull; // a synthetic user-mode VA far above 4 GiB constexpr std::uint64_t size = 0x10000; constexpr std::uint64_t arena = 0x2340000; // Empty: identity everywhere. From 81caaa165312c32d5cb9fe7afd4b36ed4f8b6c9a Mon Sep 17 00:00:00 2001 From: tedin7 Date: Mon, 23 Nov 2026 21:19:02 +0100 Subject: [PATCH 19/27] d3d12: rect_list_geometry records that packed f16 attributes cannot be told apart from float outputs on the vertex side (comment only) --- runtime/src/rect_list_geometry.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/runtime/src/rect_list_geometry.h b/runtime/src/rect_list_geometry.h index 86826317c6..15d7368d34 100644 --- a/runtime/src/rect_list_geometry.h +++ b/runtime/src/rect_list_geometry.h @@ -92,6 +92,10 @@ inline std::vector rect_list_geometry(const std::vector Date: Mon, 23 Nov 2026 15:20:43 -0600 Subject: [PATCH 20/27] local: diagnostics (draw/present/clear/rect state), rect experiments --- runtime/shims/d3d12_com.cpp | 12 +++ runtime/shims/d3d12_vulkan_device.cpp | 77 +++++++++++++++++ runtime/shims/d3d12_xs_device.cpp | 7 ++ runtime/shims/xbox_present.cpp | 10 +++ runtime/src/vulkan_backend.h | 6 ++ runtime/src/vulkan_replay.h | 120 ++++++++++++++++++-------- 6 files changed, 198 insertions(+), 34 deletions(-) diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index e1408d281c..ca28ac6da8 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -1,3 +1,4 @@ +#include #include "d3d12_com.h" #include "d3d12_stubs.h" // generated @@ -698,6 +699,17 @@ class GraphicsCommandList final d3d12_trace::record("ID3D12GraphicsCommandList::ClearRenderTargetView"); if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); if (!view.ptr || !color) return check(false); + // LOCAL DIAGNOSTIC: LEONIDA_DEBUG_CLEAR=1 clears to magenta; the first clears are logged. + static const bool magenta = [] { const char* v = std::getenv("LEONIDA_DEBUG_CLEAR"); return v && *v == '1'; }(); + const auto* target = reinterpret_cast(view.ptr); + static std::atomic shown{0}; + if (shown.fetch_add(1, std::memory_order_relaxed) < 6) + std::fprintf(stderr, "[rt] localdbg: clear resource=0x%llx colour=%g %g %g %g rects=%u\n", + static_cast(target->resource), color[0], color[1], color[2], color[3], count); + if (magenta) { + check(list_.clear_render_target(*target, {1.0f, 0.0f, 1.0f, 1.0f}, to_rects(count, rects))); + return; + } check(list_.clear_render_target(*reinterpret_cast(view.ptr), {color[0], color[1], color[2], color[3]}, to_rects(count, rects))); } diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 6c2e9d7bd8..95fb1187df 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -3745,6 +3745,16 @@ class PipelineState final : VK_CULL_MODE_NONE; // With the negative-height viewport, framebuffer winding matches D3D12's screen-space winding. raster.frontFace = r.FrontCounterClockwise ? VK_FRONT_FACE_COUNTER_CLOCKWISE : VK_FRONT_FACE_CLOCKWISE; + // LOCAL EXPERIMENT: LEONIDA_RECT_NOCULL=1 draws rectangle lists without face culling (hypothesis: the + // console's rectangle primitive has no facing, so the PSO's cull mode does not apply to it). + if (rect_list) { + static const bool no_cull = [] { const char* v = std::getenv("LEONIDA_RECT_NOCULL"); return v && *v == '1'; }(); + static std::atomic said{0}; + if (said.fetch_add(1) < 4) + std::fprintf(stderr, "[rt] localdbg: rect-list pipeline cull=%u frontCCW=%d depthClip=%d no_cull=%d\n", + unsigned(r.CullMode), int(r.FrontCounterClockwise), int(r.DepthClipEnable), int(no_cull)); + if (no_cull) raster.cullMode = VK_CULL_MODE_NONE; + } // The D24-as-D32 pixel stage applies the bias itself, in D24 units (depth24_fragment above): the // rasterizer's bias stays off and zero, so its clamp needs no depthBiasClamp feature either. raster.depthBiasEnable = !depth24_fragment && (r.DepthBias || r.SlopeScaledDepthBias != 0.0f); @@ -3785,6 +3795,25 @@ class PipelineState final blends[i].dstAlphaBlendFactor = blend_factor(b.DestBlendAlpha); blends[i].alphaBlendOp = blend_op(b.BlendOpAlpha); blends[i].colorWriteMask = b.RenderTargetWriteMask & 0xf; // R, G, B, A in both APIs + if (rect_list) { // LOCAL DIAGNOSTIC / EXPERIMENT (LEONIDA_RECT_FORCE=1: opaque, no depth or stencil test) + static const bool force = [] { const char* v = std::getenv("LEONIDA_RECT_FORCE"); return v && *v == '1'; }(); + static std::atomic said{0}; + if (said.fetch_add(1) < 6) + std::fprintf(stderr, "[rt] localdbg: rect pipeline rt%u/%u blend=%d src=%d dst=%d op=%d srcA=%d dstA=%d " + "mask=0x%x depth=%d write=%d func=%d stencil=%d samplemask=0x%x fmt=%d a2c=%d force=%d\n", + i, desc.NumRenderTargets, int(b.BlendEnable), int(b.SrcBlend), int(b.DestBlend), + int(b.BlendOp), int(b.SrcBlendAlpha), int(b.DestBlendAlpha), + unsigned(b.RenderTargetWriteMask), int(ds.DepthEnable), int(ds.DepthWriteMask), + int(ds.DepthFunc), int(ds.StencilEnable), unsigned(desc.SampleMask), + int(desc.RTVFormats[i]), int(desc.BlendState.AlphaToCoverageEnable), int(force)); + if (force) { + blends[i].blendEnable = VK_FALSE; + blends[i].colorWriteMask = 0xf; + depth.depthTestEnable = VK_FALSE; + depth.depthWriteEnable = VK_FALSE; + depth.stencilTestEnable = VK_FALSE; + } + } // B8G8R8X8 has no alpha, so blending reads destination alpha as 1 there (WARP and AMD's D3D12 driver), // where its BGRA8 Vulkan image would read the X byte. For colour SRC_ALPHA_SAT is min(As, 1 - Ad), so 0; // for alpha it is 1 in both APIs already. @@ -5461,6 +5490,54 @@ class Device final state_.context->set_heap_base(arena.address); state_.context->set_zero_page(arena.buffer, 0, kZeroPage); state_.context->set_quad_indices(arena.buffer, kZeroPage, kQuadIndexCount); + // LOCAL: vertex and index views that name the title's own CPU memory are copied into a ring carved from the + // arena at replay (not fence-tracked: the ring is large against a frame's few KiB of immediate geometry). + state_.context->set_title_memory( + [st = &state_](std::uint64_t va, std::uint64_t size, VkBuffer& buffer, VkDeviceSize& offset) { + static constexpr VkDeviceSize kRing = 16ull << 20; + static std::mutex mutex; + static VkDeviceSize ring_base = 0, ring_next = 0; + static bool tried = false, logged = false; + static std::atomic dbg{0}; + if (dbg.fetch_add(1) < 6) { + MEMORY_BASIC_INFORMATION q{}; + const SIZE_T got = VirtualQuery(reinterpret_cast(va), &q, sizeof(q)); + std::fprintf(stderr, "[rt] localdbg: title_memory va=0x%llx size=0x%llx query=%zu state=0x%lx " + "protect=0x%lx type=0x%lx region=0x%llx mapped=%d\n", + static_cast(va), static_cast(size), + static_cast(got), q.State, q.Protect, q.Type, + static_cast(q.RegionSize), st->arena.mapped != nullptr); + } + if (!va || !size || size > kRing / 4 || !st->arena.mapped) return false; + // The whole range must be committed, readable host memory. + for (std::uint64_t at = va; at < va + size;) { + MEMORY_BASIC_INFORMATION info{}; + if (!VirtualQuery(reinterpret_cast(at), &info, sizeof(info))) return false; + if (info.State != MEM_COMMIT || (info.Protect & (PAGE_NOACCESS | PAGE_GUARD)) || !info.Protect) + return false; + at = reinterpret_cast(info.BaseAddress) + info.RegionSize; + } + std::lock_guard lock(mutex); + if (!tried) { + tried = true; + if (!st->arena_allocate(kRing, 256, ring_base, DeviceState::arena_shader)) ring_base = 0; + } + if (!ring_base) return false; + const VkDeviceSize aligned = (size + 255) & ~VkDeviceSize(255); + if (ring_next + aligned > kRing) ring_next = 0; + std::memcpy(st->arena.mapped + ring_base + ring_next, reinterpret_cast(va), + std::size_t(size)); + buffer = st->arena.buffer; + offset = ring_base + ring_next; + ring_next += aligned; + if (!logged) { + logged = true; + std::fprintf(stderr, "[rt] d3d12: local: vertex/index views in title memory are copied into a " + "%llu MiB ring (first: %llu bytes)\n", + static_cast(kRing >> 20), static_cast(size)); + } + return true; + }); return true; } diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 446f94084a..a19157136a 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -1342,6 +1342,13 @@ PresentState* present_state_for(DeviceProxy* device) { HWND target = rt::d3d12::find_title_window(GetCurrentProcessId(), state->window); if (target) { std::fprintf(stderr, "[rt] d3d12_xs: PresentX uses the title's own window %p\n", static_cast(target)); + // LOCAL: LEONIDA_WINDOW=WxH resizes the title's window without waiting on its thread (SWP_ASYNCWINDOWPOS). + if (const char* size = std::getenv("LEONIDA_WINDOW")) { + int w = 0, h = 0; + if (std::sscanf(size, "%dx%d", &w, &h) == 2 && w > 0 && h > 0) + SetWindowPos(target, nullptr, 0, 0, w, h, + SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOMOVE | SWP_ASYNCWINDOWPOS); + } } else { target = state->window; ShowWindow(target, SW_SHOWNOACTIVATE); diff --git a/runtime/shims/xbox_present.cpp b/runtime/shims/xbox_present.cpp index 003b0d3fee..0b05ad4b9d 100644 --- a/runtime/shims/xbox_present.cpp +++ b/runtime/shims/xbox_present.cpp @@ -1,3 +1,4 @@ +#include #include "xbox_present.h" #include "../src/vulkan_present.h" @@ -128,6 +129,15 @@ HRESULT XboxPresentation::PresentX(UINT plane_count, const XboxPresentPlaneParam return result; } + { // LOCAL DIAGNOSTIC: what the first presents show + static std::atomic shown{0}; + if (shown.fetch_add(1, std::memory_order_relaxed) < 8) + for (UINT i = 0; i < plane_count; ++i) + std::fprintf(stderr, "[rt] localdbg: PresentX plane %u/%u resource=%p count=%u src=%p dest=%p cs=%d flags=0x%x\n", + i, plane_count, planes[i].ppResources ? static_cast(planes[i].ppResources[0]) : nullptr, + planes[i].ResourceCount, static_cast(planes[i].pSrcViewRects), + static_cast(planes[i].pDestPlacementBase), planes[i].ColorSpace, planes[i].Flags); + } // All planes carry the token of one frame. const std::uint64_t token = planes[0].Token; for (UINT i = 0; i < plane_count; ++i) { diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index 77c8827b08..0d4d84d6b3 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -1247,6 +1247,12 @@ class VulkanContext { replay_.zero_size = size; } + // LOCAL: the copy-in fallback for vertex and index views in title memory (ReplayFunctions::title_memory). + void set_title_memory(std::function copy) { + std::unique_lock lock(resource_mutex_); + replay_.title_memory = std::move(copy); + } + // Pre-expanded 32-bit triangle indices for non-indexed quad lists (ReplayFunctions::quad_indices). void set_quad_indices(VkBuffer buffer, VkDeviceSize offset, std::uint32_t count) { std::unique_lock lock(resource_mutex_); diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index af58efbbd3..0daaae4bad 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -1,3 +1,4 @@ +#include #pragma once #include "resource_tiling.h" @@ -808,6 +809,14 @@ enum class ReplayResult { invalid_draw, // DispatchMesh with a pipeline that has no mesh shader, or a vertex draw with one that has unsupported }; +// LOCAL DIAGNOSTIC: which check returned unresolved_resource (first 3 times per source line). +inline ReplayResult local_unresolved_at(int line) { + static std::atomic seen[8192]; + if (line >= 0 && line < 8192 && seen[line].fetch_add(1, std::memory_order_relaxed) < 3) + std::fprintf(stderr, "[rt] localdbg: unresolved_resource at vulkan_replay.h:%d\n", line); + return ReplayResult::unresolved_resource; +} + struct ReplayFunctions { // Set 0 for the pipelines that declare one (their own `bindless_set` is only the marker): the device's current @@ -868,6 +877,10 @@ struct ReplayFunctions { // cut to what the buffer holds from there: vertex and index views use what fits, WriteBufferImmediate needs all // of it. std::function buffer_at; + // LOCAL: a vertex or index view whose VA is the title's own CPU memory, not a registered buffer (on the console + // the GPU reads title memory directly). Copies [va, va + size) into a GPU-visible ring and names the copy; false + // when the range is not readable host memory. + std::function title_memory; // Host bytes for a whole console VA range; `not_cpu_written` when it names GPU-writable memory. For small // CPU-written inputs, such as the pointer list of an ARRAY_OF_POINTERS TLAS build. std::function host_at; @@ -2100,7 +2113,7 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct !vk.draw_indexed || !vk.bind_pipeline || !vk.push_constants) return ReplayResult::unsupported; const GraphicsPipeline* pipeline = vk.graphics_pipeline(draw.pipeline); - if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; + if (!pipeline || !pipeline->pipeline) return local_unresolved_at(__LINE__); if (pipeline->mesh != draw.mesh) return ReplayResult::invalid_draw; if (draw.mesh && !vk.draw_mesh_tasks) return ReplayResult::unsupported; if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; @@ -2121,7 +2134,7 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct const TargetView& target = draw.views->render_targets[slot]; if (!target.resource) continue; const ResourceBinding* binding = resolve(target.resource); - if (!binding) return ReplayResult::unresolved_resource; + if (!binding) return local_unresolved_at(__LINE__); auto& a = p.colors[slot]; a.binding = *binding; a.id = target.resource; @@ -2138,7 +2151,7 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct } if (draw.depth.resource && pipeline->depth_format != VK_FORMAT_UNDEFINED) { const ResourceBinding* binding = resolve(draw.depth.resource); - if (!binding) return ReplayResult::unresolved_resource; + if (!binding) return local_unresolved_at(__LINE__); auto& a = p.depth; a.binding = *binding; a.id = draw.depth.resource; @@ -2179,7 +2192,7 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct const bool bound = draw.views && slot < draw.views->vertex_buffers.size() && draw.views->vertex_buffers[slot].va; if (!bound) { - if (!vk.zero_buffer) return ReplayResult::unresolved_resource; + if (!vk.zero_buffer) return local_unresolved_at(__LINE__); p.vertex_buffers[slot] = vk.zero_buffer; p.vertex_offsets[slot] = vk.zero_offset; p.vertex_sizes[slot] = vk.zero_size; @@ -2188,26 +2201,65 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct } const VertexBufferView& view = draw.views->vertex_buffers[slot]; std::uint64_t size = view.size; - if (!vk.buffer_at(view.va, size, p.vertex_buffers[slot], p.vertex_offsets[slot])) - return ReplayResult::unresolved_resource; + if (!vk.buffer_at(view.va, size, p.vertex_buffers[slot], p.vertex_offsets[slot])) { + size = view.size; + if (!vk.title_memory || !vk.title_memory(view.va, size, p.vertex_buffers[slot], p.vertex_offsets[slot])) + return local_unresolved_at(__LINE__); + { // LOCAL DIAGNOSTIC: the first draws that read title memory + static std::atomic shown{0}; + if (shown.fetch_add(1, std::memory_order_relaxed) < 12) { + const float* f = reinterpret_cast(view.va); + std::fprintf(stderr, "[rt] localdbg: draw slot=%u topology=%u count=%u instances=%u first=%u stride=%u " + "bytes=%llu viewport=%.0f,%.0f %.0fx%.0f depth %.2f..%.2f\n", slot, draw.topology, + draw.count, draw.instances, draw.first, view.stride, + static_cast(view.size), draw.viewport.x, draw.viewport.y, + draw.viewport.width, draw.viewport.height, draw.viewport.min_depth, draw.viewport.max_depth); + for (std::uint32_t t = 0; draw.views && t < draw.views->render_target_count; ++t) + std::fprintf(stderr, "[rt] localdbg: target %u resource=0x%llx mip=%u pipeline=0x%llx depth=0x%llx " + "scissor=%d,%d..%d,%d\n", t, + static_cast(draw.views->render_targets[t].resource), + draw.views->render_targets[t].mip, static_cast(draw.pipeline), + static_cast(draw.depth.resource), draw.scissor.left, + draw.scissor.top, draw.scissor.right, draw.scissor.bottom); + std::fprintf(stderr, "[rt] localdbg: heap_base=0x%llx user_data:", static_cast(vk.heap_base)); + for (int w = 0; w < 16; ++w) std::fprintf(stderr, " %08x", draw.user_data[w]); + std::fprintf(stderr, "\n"); + for (int w = 0; w < 16; ++w) { // which root words name a registered buffer + std::uint64_t room = 1; VkBuffer bb = VK_NULL_HANDLE; VkDeviceSize bo = 0; + if (draw.user_data[w] && vk.buffer_at(draw.user_data[w], room, bb, bo)) + std::fprintf(stderr, "[rt] localdbg: user_data[%d] is a registered buffer VA\n", w); + } + const std::uint32_t words = view.stride / 4 ? view.stride / 4 : 1; + for (std::uint32_t v = 0; v < 4 && (draw.first + v + 1) * view.stride <= view.size; ++v) { + const float* q = f + (draw.first + v) * words; + std::fprintf(stderr, "[rt] localdbg: v%u = %g %g %g %g %g %g\n", v, q[0], q[1], + words > 2 ? q[2] : 0.f, words > 3 ? q[3] : 0.f, words > 4 ? q[4] : 0.f, + words > 5 ? q[5] : 0.f); + } + } + } + } p.vertex_sizes[slot] = size; p.vertex_strides[slot] = (pipeline->zero_step_slots & (1u << slot)) ? 0 : view.stride; } // A non-indexed quad list is drawn from the shared triangle index buffer (emit). if (!draw.indexed && !draw.mesh && draw.topology == topology_quad_list && !vk.quad_indices) - return ReplayResult::unresolved_resource; + return local_unresolved_at(__LINE__); if (draw.indexed) { if (draw.index.format == 57) p.index_type = VK_INDEX_TYPE_UINT16; else if (draw.index.format == 42) p.index_type = VK_INDEX_TYPE_UINT32; else if (draw.index.va) return ReplayResult::unsupported; if (!draw.index.va) { // no index buffer: every index reads 0 - if (!vk.zero_buffer) return ReplayResult::unresolved_resource; + if (!vk.zero_buffer) return local_unresolved_at(__LINE__); p.index_buffer = vk.zero_buffer; p.index_offset = vk.zero_offset; } else { std::uint64_t size = draw.index.size; - if (!vk.buffer_at(draw.index.va, size, p.index_buffer, p.index_offset)) - return ReplayResult::unresolved_resource; + if (!vk.buffer_at(draw.index.va, size, p.index_buffer, p.index_offset)) { + size = draw.index.size; + if (!vk.title_memory || !vk.title_memory(draw.index.va, size, p.index_buffer, p.index_offset)) + return local_unresolved_at(__LINE__); + } } } return ReplayResult::success; @@ -2626,7 +2678,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun }; if (const auto* transition = std::get_if(&command)) { - if (!bind(transition->resource)) return ReplayResult::unresolved_resource; + if (!bind(transition->resource)) return local_unresolved_at(__LINE__); if (p.binding.image == VK_NULL_HANDLE) { if (transition->subresource != 0 && transition->subresource != all_subresources) return ReplayResult::invalid_subresource; @@ -2636,14 +2688,14 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun } else if (std::holds_alternative(command) || std::holds_alternative(command)) { if (!vk.pipeline_barrier2) return ReplayResult::unsupported; if (const auto* buffer_barrier = std::get_if(&command)) - if (!bind(buffer_barrier->resource)) return ReplayResult::unresolved_resource; + if (!bind(buffer_barrier->resource)) return local_unresolved_at(__LINE__); } else if (const auto* texture = std::get_if(&command)) { if (!vk.pipeline_barrier2) return ReplayResult::unsupported; - if (!bind(texture->resource)) return ReplayResult::unresolved_resource; + if (!bind(texture->resource)) return local_unresolved_at(__LINE__); if (!p.binding.image || !barrier_range(p.binding, texture->range, p.range)) return ReplayResult::invalid_subresource; } else if (const auto* color_clear = std::get_if(&command)) { - if (!bind(color_clear->target.resource)) return ReplayResult::unresolved_resource; + if (!bind(color_clear->target.resource)) return local_unresolved_at(__LINE__); if (!p.binding.image || p.binding.aspects != VK_IMAGE_ASPECT_COLOR_BIT) return ReplayResult::invalid_clear; if (!detail::view_range(p.binding, color_clear->target, VK_IMAGE_ASPECT_COLOR_BIT, p.range)) return ReplayResult::invalid_subresource; @@ -2665,7 +2717,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun r != ReplayResult::success) return r; if (!p.skip && p.rects.empty() && !vk.clear_color_image) return ReplayResult::unsupported; } else if (const auto* depth_clear = std::get_if(&command)) { - if (!bind(depth_clear->target.resource)) return ReplayResult::unresolved_resource; + if (!bind(depth_clear->target.resource)) return local_unresolved_at(__LINE__); VkImageAspectFlags aspects = 0; if (depth_clear->flags & clear_depth) aspects |= VK_IMAGE_ASPECT_DEPTH_BIT; if (depth_clear->flags & clear_stencil) aspects |= VK_IMAGE_ASPECT_STENCIL_BIT; @@ -2685,7 +2737,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!p.skip && p.rects.empty() && !vk.clear_depth_stencil_image) return ReplayResult::unsupported; } else if (const auto* uav = std::get_if(&command)) { const UavView& view = uav->view; - if (!bind(view.resource)) return ReplayResult::unresolved_resource; + if (!bind(view.resource)) return local_unresolved_at(__LINE__); if (view.buffer) { if (!vk.fill_buffer || !vk.update_buffer || !vk.copy_buffer) return ReplayResult::unsupported; if (predicated) ++out.unpredicated_copies; // fills and copies are transfer commands @@ -2745,7 +2797,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (predicated && !std::holds_alternative(command)) ++out.unpredicated_copies; const auto [dst_id, src_id] = copy_ids(command); const ResourceBinding* source = resolve(src_id); - if (!bind(dst_id) || !source) return ReplayResult::unresolved_resource; + if (!bind(dst_id) || !source) return local_unresolved_at(__LINE__); p.source = *source; ReplayResult result = ReplayResult::success; if (const auto* buffer_copy = std::get_if(&command)) { @@ -2878,7 +2930,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!vk.resolve_image) return ReplayResult::unsupported; if (predicated) ++out.unpredicated_copies; // a transfer command, like the copies const ResourceBinding* source = resolve(resolve_command->src); - if (!bind(resolve_command->dst) || !source) return ReplayResult::unresolved_resource; + if (!bind(resolve_command->dst) || !source) return local_unresolved_at(__LINE__); p.source = *source; if (const auto result = detail::prepare_resolve(*resolve_command, p); result != ReplayResult::success) return result; @@ -2909,7 +2961,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun } } else if (const auto* discard = std::get_if(&command)) { // Buffers and partial (rectangle) discards keep their contents, which "undefined" allows. - if (!bind(discard->resource)) return ReplayResult::unresolved_resource; + if (!bind(discard->resource)) return local_unresolved_at(__LINE__); const std::uint64_t end = std::uint64_t(discard->first_subresource) + discard->count; if (!p.binding.image) { if (!discard->whole && end > 1) return ReplayResult::invalid_subresource; @@ -2929,7 +2981,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!vk.update_buffer || !vk.buffer_at) return ReplayResult::unsupported; std::uint64_t bytes = 4; if (!vk.buffer_at(write->address, bytes, p.write_buffer, p.write_offset) || bytes < 4) - return ReplayResult::unresolved_resource; + return local_unresolved_at(__LINE__); if (p.write_offset % 4) return ReplayResult::invalid_copy; // WriteBufferImmediate resolves by VA and may target a readback buffer in COPY_DEST. out.wrote_readback = true; @@ -2938,14 +2990,14 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!vk.copy_buffer) return ReplayResult::unsupported; if (predicated) ++out.unpredicated_copies; // a transfer command, like the copies const ResourceBinding* source = resolve(atomic->src); - if (!bind(atomic->dst) || !source) return ReplayResult::unresolved_resource; + if (!bind(atomic->dst) || !source) return local_unresolved_at(__LINE__); p.source = *source; if (!p.binding.buffer || !p.source.buffer || !detail::within(atomic->dst_offset, atomic->bytes, p.binding.size) || !detail::within(atomic->src_offset, atomic->bytes, p.source.size)) return ReplayResult::invalid_copy; for (const auto& d : atomic->dependencies) { const ResourceBinding* dependent = resolve(d.resource); - if (!dependent) return ReplayResult::unresolved_resource; + if (!dependent) return local_unresolved_at(__LINE__); if (!dependent->image) { const std::uint64_t end = d.end == UINT64_MAX ? dependent->size : d.end; if (d.subresource != 0 || d.begin >= end || end > dependent->size) @@ -2964,7 +3016,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!conditional) return ReplayResult::unsupported; // Without physical segments the capture dispatch would pollute CSInvocations. if (statistics_active && !statistics_helpers) return ReplayResult::unsupported; - if (!bind(predication->buffer)) return ReplayResult::unresolved_resource; + if (!bind(predication->buffer)) return local_unresolved_at(__LINE__); if (!p.binding.buffer || !detail::within(predication->offset, 8, p.binding.size) || predication->offset > UINT64_MAX - p.binding.buffer_offset) return ReplayResult::invalid_predication; @@ -2976,7 +3028,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun // not suppress them (emit_query suspends conditional rendering around ResolveQueryData). if (!queries) return ReplayResult::unsupported; QueryPool* heap = vk.query_pool(range.heap); - if (!heap) return ReplayResult::unresolved_resource; + if (!heap) return local_unresolved_at(__LINE__); if (!query_fits_heap(heap->heap_type, range.type)) return ReplayResult::invalid_query; if (range.first >= heap->count || range.count > heap->count - range.first) return ReplayResult::invalid_query; @@ -2999,7 +3051,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun } if (const auto* resolve_queries = std::get_if(&command)) { // The destination is a buffer, as D3D12 requires, large enough for every result. - if (!bind(resolve_queries->dst)) return ReplayResult::unresolved_resource; + if (!bind(resolve_queries->dst)) return local_unresolved_at(__LINE__); const std::uint64_t bytes = std::uint64_t(range.count) * query_result_size(range.type); if (!p.binding.buffer || p.binding.buffer_offset % 8 || !detail::within(resolve_queries->offset, bytes, p.binding.size) || @@ -3017,7 +3069,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun } out.queries.push_back({i, heap, statistics_active}); } else if (const auto* ind = std::get_if(&command)) { - if (!bind(ind->argument_buffer) || !p.binding.buffer) return ReplayResult::unresolved_resource; + if (!bind(ind->argument_buffer) || !p.binding.buffer) return local_unresolved_at(__LINE__); const VkDeviceSize record_size = detail::indirect_record_size(ind->kind); if (!record_size || ind->stride < record_size || ind->stride % sizeof(std::uint32_t)) return ReplayResult::invalid_indirect_arguments; @@ -3026,7 +3078,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun return ReplayResult::invalid_indirect_arguments; if (ind->count_buffer) { const ResourceBinding* cnt = resolve(ind->count_buffer); - if (!cnt || !cnt->buffer) return ReplayResult::unresolved_resource; + if (!cnt || !cnt->buffer) return local_unresolved_at(__LINE__); if (!detail::indirect_range(*cnt, ind->count_offset, sizeof(std::uint32_t))) return ReplayResult::invalid_indirect_arguments; p.source = *cnt; @@ -3052,7 +3104,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (ind->kind == IndirectKind::dispatch && ind->pipeline) { // the pipeline and root arguments it was recorded if (!vk.bind_pipeline || !vk.push_constants || !vk.compute_pipeline) return ReplayResult::unsupported; const ComputePipeline* pipeline = vk.compute_pipeline(ind->pipeline); - if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; + if (!pipeline || !pipeline->pipeline) return local_unresolved_at(__LINE__); if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; p.pipeline = *pipeline; } @@ -3064,10 +3116,10 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!vk.build_acceleration_structures || !vk.resolve_acceleration_structure) return ReplayResult::unsupported; p.accel_dst = vk.resolve_acceleration_structure(build->dst_va); - if (!p.accel_dst) return ReplayResult::unresolved_resource; + if (!p.accel_dst) return local_unresolved_at(__LINE__); if (build->update && build->src_va) { p.accel_src = vk.resolve_acceleration_structure(build->src_va); - if (!p.accel_src) return ReplayResult::unresolved_resource; + if (!p.accel_src) return local_unresolved_at(__LINE__); } if (build->is_tlas && build->instance_pointers && build->instance_count) { if (!vk.prepare_khr_instances || !vk.host_at || !vk.buffer_at) return ReplayResult::unsupported; @@ -3081,9 +3133,9 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun std::uint64_t room = ~std::uint64_t(0); VkBuffer buffer = VK_NULL_HANDLE; VkDeviceSize offset = 0; - if (!vk.buffer_at(copy->dst_va, room, buffer, offset)) return ReplayResult::unresolved_resource; + if (!vk.buffer_at(copy->dst_va, room, buffer, offset)) return local_unresolved_at(__LINE__); std::uint64_t source = ~std::uint64_t(0); - if (!vk.buffer_at(copy->src_va, source, buffer, offset)) return ReplayResult::unresolved_resource; + if (!vk.buffer_at(copy->src_va, source, buffer, offset)) return local_unresolved_at(__LINE__); p.xdxr_bytes = std::min(room, source); } else if (const auto* info = std::get_if(&command)) { // The KHR path never wrote postbuild values; it keeps skipping them rather than failing the list. @@ -3094,14 +3146,14 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun std::uint64_t room = 8 * info->sources.size(); VkBuffer buffer = VK_NULL_HANDLE; VkDeviceSize offset = 0; - if (!vk.buffer_at(info->dest_va, room, buffer, offset)) return ReplayResult::unresolved_resource; + if (!vk.buffer_at(info->dest_va, room, buffer, offset)) return local_unresolved_at(__LINE__); if (room < 8 * info->sources.size()) return ReplayResult::invalid_copy; } } else if (const auto* dispatch = std::get_if(&command)) { if (!vk.bind_pipeline || !vk.push_constants || !vk.dispatch || !vk.compute_pipeline) return ReplayResult::unsupported; const ComputePipeline* pipeline = vk.compute_pipeline(dispatch->pipeline); - if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; + if (!pipeline || !pipeline->pipeline) return local_unresolved_at(__LINE__); if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; p.pipeline = *pipeline; } else if (const auto* draw = std::get_if(&command)) { From c9ea50842077678228204a2be52314c4065f87d7 Mon Sep 17 00:00:00 2001 From: Mumogg <104529023+Mumogg@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:10:47 -0600 Subject: [PATCH 21/27] local: descriptor write-through and table mirror for title-backed heaps; diagnostics --- runtime/shims/d3d12_vulkan_device.cpp | 65 +++++++++++++++++- runtime/shims/d3d12_xs_device.cpp | 94 +++++++++++++++++++++++++++ runtime/src/vulkan_replay.h | 47 +++++++++++++- 3 files changed, 204 insertions(+), 2 deletions(-) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 4c4c5f60e1..0a75413d6c 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -4087,6 +4087,18 @@ class PipelineState final stage.words = std::move(patched); } } + { // LOCAL EXPERIMENT: LEONIDA_RECT_GREEN=1 gives rectangle-list pipelines a solid green pixel stage, to + // tell "no fragments" from "the pixel shader writes nothing". + static const bool green = [] { const char* v = std::getenv("LEONIDA_RECT_GREEN"); return v && *v == '1'; }(); + static const bool trivial_vs = [] { const char* v = std::getenv("LEONIDA_RECT_VS"); return v && *v == '1'; }(); + if (trivial_vs && rect_list && stage.bit == VK_SHADER_STAGE_VERTEX_BIT) + stage.words = {0x7230203,0x10500,0x70000,0x1d,0x0,0x20011,0x1,0x3000e,0x0,0x1,0x7000f,0x0,0x1,0x6e69616d,0x0,0x2,0x3,0x40047,0x2,0xb,0x2a,0x40047,0x3,0xb,0x0,0x20013,0x4,0x30021,0x5,0x4,0x30016,0x6,0x20,0x40015,0x7,0x20,0x1,0x40017,0x8,0x6,0x4,0x40020,0x9,0x1,0x7,0x40020,0xa,0x3,0x8,0x4003b,0x9,0x2,0x1,0x4003b,0xa,0x3,0x3,0x4002b,0x7,0xb,0x1,0x4002b,0x7,0xc,0x2,0x4002b,0x6,0xd,0x0,0x4002b,0x6,0xe,0x3f800000,0x4002b,0x6,0xf,0x40800000,0x4002b,0x6,0x10,0xbf800000,0x50036,0x4,0x1,0x0,0x5,0x200f8,0x11,0x4003d,0x7,0x12,0x2,0x500c7,0x7,0x13,0x12,0xb,0x500c3,0x7,0x14,0x12,0xb,0x500c7,0x7,0x15,0x14,0xb,0x4006f,0x6,0x16,0x13,0x4006f,0x6,0x17,0x15,0x50085,0x6,0x18,0x16,0xf,0x50085,0x6,0x19,0x17,0xf,0x50081,0x6,0x1a,0x18,0x10,0x50081,0x6,0x1b,0x19,0x10,0x70050,0x8,0x1c,0x1a,0x1b,0xd,0xe,0x3003e,0x3,0x1c,0x100fd,0x10038}; + static const bool passthrough_vs = [] { const char* v = std::getenv("LEONIDA_RECT_VS"); return v && *v == '2'; }(); + if (passthrough_vs && rect_list && stage.bit == VK_SHADER_STAGE_VERTEX_BIT) + stage.words = {0x7230203,0x10500,0x70000,0x11,0x0,0x20011,0x1,0x3000e,0x0,0x1,0x7000f,0x0,0x1,0x6e69616d,0x0,0x2,0x3,0x40047,0x2,0x1e,0x0,0x40047,0x3,0xb,0x0,0x20013,0x4,0x30021,0x5,0x4,0x30016,0x6,0x20,0x40017,0x7,0x6,0x4,0x40020,0x8,0x1,0x7,0x40020,0x9,0x3,0x7,0x4003b,0x8,0x2,0x1,0x4003b,0x9,0x3,0x3,0x4002b,0x6,0xa,0x0,0x4002b,0x6,0xb,0x3f800000,0x50036,0x4,0x1,0x0,0x5,0x200f8,0xc,0x4003d,0x7,0xd,0x2,0x50051,0x6,0xe,0xd,0x0,0x50051,0x6,0xf,0xd,0x1,0x70050,0x7,0x10,0xe,0xf,0xa,0xb,0x3003e,0x3,0x10,0x100fd,0x10038}; + if (green && rect_list && stage.bit == VK_SHADER_STAGE_FRAGMENT_BIT) + stage.words = {0x7230203,0x10500,0x70000,0xc,0x0,0x20011,0x1,0x3000e,0x0,0x1,0x6000f,0x4,0x1,0x6e69616d,0x0,0x2,0x30010,0x1,0x7,0x40047,0x2,0x1e,0x0,0x20013,0x3,0x30021,0x4,0x3,0x30016,0x5,0x20,0x40017,0x6,0x5,0x4,0x40020,0x7,0x3,0x6,0x4003b,0x7,0x2,0x3,0x4002b,0x5,0x8,0x0,0x4002b,0x5,0x9,0x3f800000,0x7002c,0x6,0xa,0x8,0x9,0x8,0x9,0x50036,0x3,0x1,0x0,0x4,0x200f8,0xb,0x3003e,0x2,0xa,0x100fd,0x10038}; + } VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; module_info.codeSize = stage.words.size() * 4; module_info.pCode = stage.words.data(); @@ -4100,7 +4112,9 @@ class PipelineState final subgroup_size_for(*stage.entry, required_sizes[stage_infos.size()], info); stage_infos.push_back(info); } - if (rect_list) { // the stage that adds each rectangle's fourth corner, from the vertex shader's outputs + // LOCAL EXPERIMENT: LEONIDA_RECT_NOGS=1 draws the rectangle list's three corners as a plain triangle. + static const bool local_no_gs = [] { const char* v = std::getenv("LEONIDA_RECT_NOGS"); return v && *v == '1'; }(); + if (rect_list && !local_no_gs) { // the stage that adds each rectangle's fourth corner, from the vertex shader's outputs std::string why; const std::vector words = leonida::rect_list_geometry(vs_stage.words, why); if (words.empty()) { @@ -4161,6 +4175,16 @@ class PipelineState final if (e.system_value == 0 && e.semantic_index == element.SemanticIndex && equal_semantic(e.semantic, element.SemanticName)) input = &e; + { // LOCAL DIAGNOSTIC: the input layout of the first graphics pipelines with one + static std::atomic said{0}; + const std::string& vsn = stages[0].entry->name; + if ((vsn.find("Blit") != std::string::npos || vsn.find("sga_dr") != std::string::npos) && said.fetch_add(1) < 24) + std::fprintf(stderr, "[rt] localdbg: input element %u/%u %s%u dxgi=%d slot=%u offset=%u -> %s (vs %s)\n", i, + desc.InputLayout.NumElements, element.SemanticName ? element.SemanticName : "?", + element.SemanticIndex, int(element.Format), element.InputSlot, offset, + input ? ("location " + std::to_string(input->register_index)).c_str() : "not read", + stages[0].entry->name.c_str()); + } if (!input) continue; // the shader does not read this element attributes.push_back({input->register_index, element.InputSlot, format, offset}); const bool instance = element.InputSlotClass == D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA; @@ -4183,6 +4207,13 @@ class PipelineState final instance ? VK_VERTEX_INPUT_RATE_INSTANCE : VK_VERTEX_INPUT_RATE_VERTEX}); } } + { // LOCAL DIAGNOSTIC + static std::atomic said2{0}; + const std::string& vsn = stages[0].entry->name; + if (!mesh && (vsn.find("Blit") != std::string::npos || vsn.find("sga_dr") != std::string::npos) && said2.fetch_add(1) < 8) + std::fprintf(stderr, "[rt] localdbg: %s input layout elements=%u attributes=%zu signature=%zu\n", vsn.c_str(), + desc.InputLayout.NumElements, attributes.size(), stages[0].entry->input_signature.size()); + } for (const auto& e : stages[0].entry->input_signature) { if (e.system_value) continue; const bool fed = std::any_of(attributes.begin(), attributes.end(), @@ -4286,6 +4317,12 @@ class PipelineState final if (rect_list) { // LOCAL DIAGNOSTIC / EXPERIMENT (LEONIDA_RECT_FORCE=1: opaque, no depth or stencil test) static const bool force = [] { const char* v = std::getenv("LEONIDA_RECT_FORCE"); return v && *v == '1'; }(); static std::atomic said{0}; + if (said.load() < 6) + for (const auto& st : stages) + if (st.entry) + std::fprintf(stderr, "[rt] localdbg: rect pipeline stage %s = %s wave64=%d emulated=%d push=%u\n", + st.entry->stage.c_str(), st.entry->name.c_str(), int(st.entry->wave64), + int(st.entry->emulated()), st.entry->push_constant_bytes); if (said.fetch_add(1) < 6) std::fprintf(stderr, "[rt] localdbg: rect pipeline rt%u/%u blend=%d src=%d dst=%d op=%d srcA=%d dstA=%d " "mask=0x%x depth=%d write=%d func=%d stencil=%d samplemask=0x%x fmt=%d a2c=%d force=%d\n", @@ -6000,6 +6037,9 @@ class Device final state_.context->set_heap_base(arena.address); state_.context->set_zero_page(arena.buffer, 0, kZeroPage); state_.context->set_quad_indices(arena.buffer, kZeroPage, kQuadIndexCount); + leonida::g_local_arena_mapped = arena.mapped; // LOCAL DIAGNOSTIC + std::fprintf(stderr, "[rt] localdbg: arena mapped at %p\n", static_cast(arena.mapped)); + leonida::g_local_arena_size = arena.size; // LOCAL: vertex and index views that name the title's own CPU memory are copied into a ring carved from the // arena at replay (not fence-tracked: the ring is large against a frame's few KiB of immediate geometry). state_.context->set_title_memory( @@ -6037,6 +6077,29 @@ class Device final if (ring_next + aligned > kRing) ring_next = 0; std::memcpy(st->arena.mapped + ring_base + ring_next, reinterpret_cast(va), std::size_t(size)); + { // LOCAL EXPERIMENT: LEONIDA_VTX_TEST=1 overwrites the copy with a screen-covering triangle (stride 24) + static const char mode = [] { const char* v = std::getenv("LEONIDA_VTX_TEST"); return v ? *v : '0'; }(); + const float second_y = reinterpret_cast(st->arena.mapped + ring_base + ring_next)[7]; + const bool test = mode == '1' || (mode == 'A' && second_y < 100.f) || (mode == 'B' && second_y >= 100.f); + if (test && size >= 72) { + const float tri[3][2] = {{-1.f, -1.f}, {3.f, -1.f}, {-1.f, 3.f}}; + for (int v = 0; v < 3; ++v) { + float* q = reinterpret_cast(st->arena.mapped + ring_base + ring_next + v * 24); + q[0] = tri[v][0]; q[1] = tri[v][1]; q[2] = 0.f; + } + } + static std::atomic said{0}; + if (said.load() < 6) { + const float* q = reinterpret_cast(st->arena.mapped + ring_base + ring_next); + std::fprintf(stderr, "[rt] localdbg: ring copy holds %g,%g | %g,%g | %g,%g (size %llu)\n", q[0], q[1], + q[6], q[7], q[12], q[13], static_cast(size)); + } + if (said.fetch_add(1) < 3) + std::fprintf(stderr, "[rt] localdbg: ring copy at arena offset 0x%llx (ring_base 0x%llx) arena size 0x%llx\n", + static_cast(ring_base + ring_next), + static_cast(ring_base), + static_cast(st->arena.size)); + } buffer = st->arena.buffer; offset = ring_base + ring_next; ring_next += aligned; diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 937390efae..2d00e00c9b 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -166,6 +166,9 @@ bool register_descriptor_range(const DeviceProxy* device, const HeapProxy* heap, return false; try { std::lock_guard lock(descriptor_range_mutex()); + std::fprintf(stderr, "[rt] localdbg: descriptor range custom=0x%llx..0x%llx real_cpu=0x%llx heap=%p\n", + static_cast(custom_start), static_cast(custom_start + byte_size), + static_cast(real_start), static_cast(heap)); descriptor_ranges().push_back({custom_start, custom_start + byte_size, real_start, device, heap}); g_custom_range_count.store(descriptor_ranges().size(), std::memory_order_release); return true; @@ -201,6 +204,59 @@ D3D12_CPU_DESCRIPTOR_HANDLE translate_cpu_handle(const DeviceProxy* device, D3D1 return handle; } +// LOCAL (title-backed descriptor heaps): the title copies descriptors between its heaps' backing memory itself, with +// no API call, so (1) every descriptor the layer writes for a title-backed slot is also stored at the title's address, +// and (2) when a table is bound, what the title wrote at that table's address is carried into the real heap. +// LEONIDA_DESC_MIRROR=0 turns both off. +constexpr SIZE_T kLocalDescriptorBytes = 32; +constexpr SIZE_T kLocalMirrorSlots = 64; + +bool local_desc_mirror() { + static const bool on = [] { const char* v = std::getenv("LEONIDA_DESC_MIRROR"); return !(v && *v == '0'); }(); + return on; +} + +void local_write_through(const DeviceProxy* device, D3D12_CPU_DESCRIPTOR_HANDLE custom, SIZE_T count) { + if (!local_desc_mirror() || !custom.ptr || !count) return; + const D3D12_CPU_DESCRIPTOR_HANDLE real = translate_cpu_handle(device, custom); + if (real.ptr == custom.ptr) return; + std::memcpy(reinterpret_cast(custom.ptr), reinterpret_cast(real.ptr), + count * kLocalDescriptorBytes); + static std::atomic said{false}; + if (!said.exchange(true)) + std::fprintf(stderr, "[rt] d3d12_xs: local: descriptors written for a title-backed heap are also stored at the " + "title's address\n"); +} + +D3D12_GPU_DESCRIPTOR_HANDLE local_real_gpu_start(const HeapProxy* heap); + +void local_mirror_table(const DeviceProxy* device, std::uint64_t gpu_handle) { + if (!local_desc_mirror() || !gpu_handle || g_custom_range_count.load(std::memory_order_acquire) == 0) return; + std::lock_guard lock(descriptor_range_mutex()); + for (const DescriptorRange& range : descriptor_ranges()) { + if ((device && range.device != device) || !range.heap) continue; + const std::uint64_t gpu_start = local_real_gpu_start(range.heap).ptr; + const std::uint64_t bytes = range.custom_end - range.custom_start; + if (!gpu_start || gpu_handle < gpu_start || gpu_handle >= gpu_start + bytes) continue; + const std::uint64_t offset = (gpu_handle - gpu_start) / kLocalDescriptorBytes * kLocalDescriptorBytes; + const std::uint64_t slots = (std::min)(kLocalMirrorSlots, (bytes - offset) / kLocalDescriptorBytes); + std::uint64_t copied = 0; + for (std::uint64_t i = 0; i < slots; ++i) { + const auto* from = reinterpret_cast(range.custom_start + offset + i * kLocalDescriptorBytes); + if (!(from[0] | from[1] | from[2] | from[3])) continue; // nothing the title wrote: keep the real slot + std::memcpy(reinterpret_cast(range.real_start + offset + i * kLocalDescriptorBytes), from, + kLocalDescriptorBytes); + ++copied; + } + static std::atomic said{0}; + if (said.fetch_add(1) < 4) + std::fprintf(stderr, "[rt] d3d12_xs: local: table at heap offset 0x%llx: %llu of %llu slots taken from the " + "title's backing memory\n", static_cast(offset), + static_cast(copied), static_cast(slots)); + return; + } +} + std::atomic g_hits[kMaxSlots]; std::atomic g_first[kMaxSlots]; std::atomic g_beyond_warned[kMaxSlots]; @@ -684,12 +740,31 @@ D3D12_CPU_DESCRIPTOR_HANDLE heap_get_cpu_handle(HeapProxy* self) { D3D12_GPU_DESCRIPTOR_HANDLE heap_get_gpu_handle(HeapProxy* self) { note_heap_slot(10); + { + static std::atomic said{0}; + if (said.fetch_add(1) < 8) std::fprintf(stderr, "[rt] localdbg: heap slot 10 (GPU handle) asked on heap %p\n", static_cast(self)); + } constexpr UINT64 kUnset = ~static_cast(0); D3D12_GPU_DESCRIPTOR_HANDLE handle{}; handle.ptr = kUnset; using Fn = D3D12_GPU_DESCRIPTOR_HANDLE(WINAPI*)(ID3D12DescriptorHeap*, D3D12_GPU_DESCRIPTOR_HANDLE*); const D3D12_GPU_DESCRIPTOR_HANDLE returned = reinterpret_cast(self->real_vtable[10])(self->real, &handle); + { + static std::atomic said{0}; + if (said.fetch_add(1) < 4) + std::fprintf(stderr, "[rt] localdbg: heap %p slot 10 answers GPU handle 0x%llx\n", static_cast(self), + static_cast(handle.ptr != kUnset ? handle.ptr : returned.ptr)); + } + return handle.ptr != kUnset ? handle : returned; +} + +D3D12_GPU_DESCRIPTOR_HANDLE local_real_gpu_start(const HeapProxy* heap) { + constexpr UINT64 kUnset = ~static_cast(0); + D3D12_GPU_DESCRIPTOR_HANDLE handle{}; + handle.ptr = kUnset; + using Fn = D3D12_GPU_DESCRIPTOR_HANDLE(WINAPI*)(ID3D12DescriptorHeap*, D3D12_GPU_DESCRIPTOR_HANDLE*); + const D3D12_GPU_DESCRIPTOR_HANDLE returned = reinterpret_cast(heap->real_vtable[10])(heap->real, &handle); return handle.ptr != kUnset ? handle : returned; } @@ -2050,6 +2125,8 @@ std::uint64_t WINAPI list_slot(ListProxy* self, std::uint64_t a1, std::uint64_t std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t); auto** const real_vtable = *reinterpret_cast(self->real); + // LOCAL: console SetComputeRootDescriptorTable (35) and SetGraphicsRootDescriptorTable (36) + if constexpr (Slot == 35 || Slot == 36) local_mirror_table(self->device, a2); if constexpr (pc == 10) { // Reset(allocator, pso) — console 10, and 139 as the retail title calls it: the title hands its // allocator proxy; the real list takes the real one (and a wrapped pipeline state, if that ever @@ -2673,19 +2750,32 @@ HRESULT proxy_create_descriptor_heap(DeviceProxy* self, const D3D12_DESCRIPTOR_H void proxy_create_cbv(DeviceProxy* self, const D3D12_CONSTANT_BUFFER_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE dest) { note_slot(17); + { // LOCAL DIAGNOSTIC + static std::atomic said{0}; + const int n = said.fetch_add(1); + if (n < 6 || (n > 3000 && n < 3008)) { + const D3D12_CPU_DESCRIPTOR_HANDLE t = translate_cpu_handle(self, dest); + std::fprintf(stderr, "[rt] localdbg: CreateCBV #%d dest=0x%llx -> 0x%llx location=0x%llx size=%u\n", n, + static_cast(dest.ptr), static_cast(t.ptr), + desc ? static_cast(desc->BufferLocation) : 0ull, desc ? desc->SizeInBytes : 0u); + } + } self->real->CreateConstantBufferView(desc, translate_cpu_handle(self, dest)); + local_write_through(self, dest, 1); } void proxy_create_srv(DeviceProxy* self, ID3D12Resource* resource, const D3D12_SHADER_RESOURCE_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE dest) { note_slot(18); self->real->CreateShaderResourceView(resource, desc, translate_cpu_handle(self, dest)); + local_write_through(self, dest, 1); } void proxy_create_uav(DeviceProxy* self, ID3D12Resource* resource, ID3D12Resource* counter, const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE dest) { note_slot(19); self->real->CreateUnorderedAccessView(resource, counter, desc, translate_cpu_handle(self, dest)); + local_write_through(self, dest, 1); } void proxy_create_rtv(DeviceProxy* self, ID3D12Resource* resource, const D3D12_RENDER_TARGET_VIEW_DESC* desc, @@ -2703,6 +2793,7 @@ void proxy_create_dsv(DeviceProxy* self, ID3D12Resource* resource, const D3D12_D void proxy_create_sampler(DeviceProxy* self, const D3D12_SAMPLER_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE dest) { note_slot(22); self->real->CreateSampler(desc, translate_cpu_handle(self, dest)); + local_write_through(self, dest, 1); } void proxy_copy_descriptors(DeviceProxy* self, UINT num_dest, const D3D12_CPU_DESCRIPTOR_HANDLE* dest_starts, @@ -2743,6 +2834,8 @@ void proxy_copy_descriptors(DeviceProxy* self, UINT num_dest, const D3D12_CPU_DE return; } self->real->CopyDescriptors(num_dest, dest_out, dest_sizes, num_src, src_out, src_sizes, type); + for (UINT i = 0; dest_starts && i < num_dest; ++i) + local_write_through(self, dest_starts[i], dest_sizes ? dest_sizes[i] : 1); } void proxy_copy_descriptors_simple(DeviceProxy* self, UINT num_descriptors, D3D12_CPU_DESCRIPTOR_HANDLE dest_start, @@ -2750,6 +2843,7 @@ void proxy_copy_descriptors_simple(DeviceProxy* self, UINT num_descriptors, D3D1 note_slot(24); self->real->CopyDescriptorsSimple(num_descriptors, translate_cpu_handle(self, dest_start), translate_cpu_handle(self, src_start), type); + local_write_through(self, dest_start, num_descriptors); } // The Xbox slot 62 takes two more words between the description and the IID: (desc, w2, w3, riid, out). Measured diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 0daaae4bad..c4dac14349 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -809,6 +809,10 @@ enum class ReplayResult { invalid_draw, // DispatchMesh with a pipeline that has no mesh shader, or a vertex draw with one that has unsupported }; +// LOCAL DIAGNOSTIC: the arena's host mapping and size, for dumps of what a shader would read. +inline std::uint8_t* g_local_arena_mapped = nullptr; +inline std::uint64_t g_local_arena_size = 0; + // LOCAL DIAGNOSTIC: which check returned unresolved_resource (first 3 times per source line). inline ReplayResult local_unresolved_at(int line) { static std::atomic seen[8192]; @@ -2207,7 +2211,8 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct return local_unresolved_at(__LINE__); { // LOCAL DIAGNOSTIC: the first draws that read title memory static std::atomic shown{0}; - if (shown.fetch_add(1, std::memory_order_relaxed) < 12) { + const int nth = shown.fetch_add(1, std::memory_order_relaxed); + if (nth < 12 || (nth % 20000) < 3) { const float* f = reinterpret_cast(view.va); std::fprintf(stderr, "[rt] localdbg: draw slot=%u topology=%u count=%u instances=%u first=%u stride=%u " "bytes=%llu viewport=%.0f,%.0f %.0fx%.0f depth %.2f..%.2f\n", slot, draw.topology, @@ -2229,6 +2234,46 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct if (draw.user_data[w] && vk.buffer_at(draw.user_data[w], room, bb, bo)) std::fprintf(stderr, "[rt] localdbg: user_data[%d] is a registered buffer VA\n", w); } + if (g_local_arena_mapped && draw.user_data[0] && draw.user_data[0] + 256ull <= g_local_arena_size) { + const std::uint32_t* t = reinterpret_cast(g_local_arena_mapped + draw.user_data[0]); + for (int e = 0; e < 4; ++e) { + std::fprintf(stderr, "[rt] localdbg: table[%d]:", e); + for (int w = 0; w < 8; ++w) std::fprintf(stderr, " %08x", t[e * 8 + w]); + std::fprintf(stderr, "\n"); + const std::uint64_t va = (std::uint64_t(t[e * 8 + 1] & 0xffff) << 32) | t[e * 8]; + if (va && va + 64 <= g_local_arena_size) { + const float* f2 = reinterpret_cast(g_local_arena_mapped + va); + std::fprintf(stderr, "[rt] localdbg: at va 0x%llx:", static_cast(va)); + for (int w = 0; w < 16; ++w) std::fprintf(stderr, " %g", f2[w]); + std::fprintf(stderr, "\n"); + } + } + } + { // the same table read from the title's memory, taking the high dword from the vertex view's VA + const std::uint64_t guess = (view.va & 0xffffffff00000000ull) | draw.user_data[0]; + std::fprintf(stderr, "[rt] localdbg: vertex va=0x%llx table guess=0x%llx delta=%lld\n", + static_cast(view.va), static_cast(guess), + static_cast(view.va - guess)); + std::uint64_t probe = 256; VkBuffer pb = VK_NULL_HANDLE; VkDeviceSize po = 0; + if (draw.user_data[0] && vk.title_memory && vk.title_memory(guess, probe, pb, po)) { + const std::uint32_t* t = reinterpret_cast(guess); + for (int e = 0; e < 3; ++e) { + std::fprintf(stderr, "[rt] localdbg: title table[%d]:", e); + for (int w = 0; w < 8; ++w) std::fprintf(stderr, " %08x", t[e * 8 + w]); + std::fprintf(stderr, "\n"); + } + } else { + std::fprintf(stderr, "[rt] localdbg: title table guess is not readable title memory\n"); + } + } + { // what sits just before the vertices in the title's ring + const std::uint32_t* t = reinterpret_cast(view.va - 0x60); + for (int e = 0; e < 3; ++e) { + std::fprintf(stderr, "[rt] localdbg: before vertices[-0x%x]:", 0x60 - e * 0x20); + for (int w = 0; w < 8; ++w) std::fprintf(stderr, " %08x", t[e * 8 + w]); + std::fprintf(stderr, "\n"); + } + } const std::uint32_t words = view.stride / 4 ? view.stride / 4 : 1; for (std::uint32_t v = 0; v < 4 && (draw.first + v + 1) * view.stride <= view.size; ++v) { const float* q = f + (draw.first + v) * words; From 0c7ec65c0e0d1890139eda86cc92fc4f0ed830e6 Mon Sep 17 00:00:00 2001 From: Mumogg <104529023+Mumogg@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:11:49 -0600 Subject: [PATCH 22/27] local: apply #9419 (present dump) as a patch --- runtime/CMakeLists.txt | 9 + runtime/src/present_dump.h | 256 ++++++++++++++++++++++++++ runtime/src/vulkan_present.h | 40 ++-- runtime/test/vk_present_dump_test.cpp | 113 ++++++++++++ 4 files changed, 407 insertions(+), 11 deletions(-) create mode 100644 runtime/src/present_dump.h create mode 100644 runtime/test/vk_present_dump_test.cpp diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index e24a5786c8..16aef2c294 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -1575,6 +1575,15 @@ if(TARGET Vulkan::Headers) endif() add_test(NAME vk_presenter_sync COMMAND vk_presenter_sync_test) set_tests_properties(vk_presenter_sync PROPERTIES SKIP_RETURN_CODE 77) + set(conformance_src ${CMAKE_CURRENT_SOURCE_DIR}/../tools/conformance/native/src) + add_executable(vk_present_dump_test test/vk_present_dump_test.cpp + ${conformance_src}/png_io.cpp ${conformance_src}/diagnostics.cpp) + target_link_libraries(vk_present_dump_test PRIVATE Vulkan::Headers user32 windowscodecs ole32) + target_compile_definitions(vk_present_dump_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + add_test(NAME vk_present_dump COMMAND vk_present_dump_test) + add_test(NAME vk_present_dump_default COMMAND vk_present_dump_test --default) + add_test(NAME vk_present_dump_invalid COMMAND vk_present_dump_test --invalid) + set_tests_properties(vk_present_dump vk_present_dump_default vk_present_dump_invalid PROPERTIES SKIP_RETURN_CODE 77) endif() if(NOT Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) find_program(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE glslangValidator HINTS "$ENV{VULKAN_SDK}/Bin" "$ENV{VULKAN_SDK}/bin") diff --git a/runtime/src/present_dump.h b/runtime/src/present_dump.h new file mode 100644 index 0000000000..2e594fcb50 --- /dev/null +++ b/runtime/src/present_dump.h @@ -0,0 +1,256 @@ +#pragma once + +// LEONIDA_PRESENT_DUMP: the final swapchain texels, encoded on a worker after their frame fence signals. +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace leonida::present_dump { + +inline unsigned texel_size(VkFormat format) { + switch (format) { + case VK_FORMAT_B8G8R8A8_UNORM: case VK_FORMAT_B8G8R8A8_SRGB: + case VK_FORMAT_R8G8B8A8_UNORM: case VK_FORMAT_R8G8B8A8_SRGB: + case VK_FORMAT_A2B10G10R10_UNORM_PACK32: case VK_FORMAT_A2R10G10B10_UNORM_PACK32: return 4; + case VK_FORMAT_R16G16B16A16_SFLOAT: return 8; + case VK_FORMAT_R32G32B32A32_SFLOAT: return 16; + default: return 0; + } +} + +inline std::uint8_t unorm8(float v) { + return v > 0 ? std::uint8_t(std::min(v, 1.0f) * 255 + 0.5f) : 0; +} + +inline std::uint8_t half_unorm8(std::uint16_t bits) { + const int exponent = bits >> 10; + const int fraction = bits & 1023; + if (bits >= 0x8000 || !exponent || (exponent == 31 && fraction)) return 0; + return unorm8(std::ldexp(float(1024 + fraction), exponent - 25)); +} + +inline void rgba_row(std::uint8_t* dst, const std::uint8_t* src, unsigned width, VkFormat format, bool pq) { + if (format == VK_FORMAT_R8G8B8A8_UNORM || format == VK_FORMAT_R8G8B8A8_SRGB) { + std::memcpy(dst, src, size_t(width) * 4); + return; + } + const unsigned stride = texel_size(format); + for (unsigned x = 0; x < width; ++x, src += stride, dst += 4) { + if (format == VK_FORMAT_B8G8R8A8_UNORM || format == VK_FORMAT_B8G8R8A8_SRGB) { + dst[0] = src[2]; dst[1] = src[1]; dst[2] = src[0]; dst[3] = src[3]; + } else if (format == VK_FORMAT_R16G16B16A16_SFLOAT) { + std::uint16_t v[4]; + std::memcpy(v, src, sizeof(v)); + std::transform(v, v + 4, dst, half_unorm8); + } else if (format == VK_FORMAT_R32G32B32A32_SFLOAT) { + float v[4]; + std::memcpy(v, src, sizeof(v)); + std::transform(v, v + 4, dst, unorm8); + } else { + // A cheap HDR10 preview: decode ST.2084 per component, clip at 203 nits and encode for SDR. + // Keep the source primaries. A 10-bit SDR swapchain just scales its code values to eight bits. + static const auto pq_to_sdr = [] { + std::array table{}; + for (unsigned i = 0; i < table.size(); ++i) { + const double p = std::pow(i / 1023.0, 1.0 / 78.84375); + const double linear = (10000.0 / 203.0) * + std::pow(std::max(0.0, p - 0.8359375) / (18.8515625 - 18.6875 * p), 1.0 / 0.1593017578125); + const double srgb = linear <= 0.0031308 ? 12.92 * linear : 1.055 * std::pow(linear, 1.0 / 2.4) - 0.055; + table[i] = unorm8(float(srgb)); + } + return table; + }(); + std::uint32_t packed; + std::memcpy(&packed, src, sizeof(packed)); + for (unsigned channel = 0; channel < 3; ++channel) { + const unsigned bits = (packed >> (10 * channel)) & 1023; + dst[channel] = pq ? pq_to_sdr[bits] : std::uint8_t((bits * 255 + 511) / 1023); + } + if (format == VK_FORMAT_A2R10G10B10_UNORM_PACK32) std::swap(dst[0], dst[2]); + dst[3] = std::uint8_t((packed >> 30) * 85); + } + } +} + +inline std::array big_endian(std::uint32_t n) { + return {std::uint8_t(n >> 24), std::uint8_t(n >> 16), std::uint8_t(n >> 8), std::uint8_t(n)}; +} + +inline bool chunk(std::FILE* file, const char (&type)[5], std::span data, + std::span prefix = {}) { + static constexpr auto crc_table = [] { + std::array table{}; + for (unsigned i = 0; i < table.size(); ++i) { + unsigned c = i; + for (int bit = 0; bit < 8; ++bit) c = (c >> 1) ^ ((c & 1) ? 0xedb88320u : 0); + table[i] = c; + } + return table; + }(); + std::uint32_t crc = ~0u; + const auto write = [&](std::span bytes) { + for (auto b : bytes) crc = crc_table[(crc ^ b) & 255] ^ (crc >> 8); + return bytes.empty() || std::fwrite(bytes.data(), 1, bytes.size(), file) == bytes.size(); + }; + return std::fwrite(big_endian(std::uint32_t(prefix.size() + data.size())).data(), 1, 4, file) == 4 && + write({reinterpret_cast(type), 4}) && write(prefix) && write(data) && + std::fwrite(big_endian(~crc).data(), 1, 4, file) == 4; +} + +inline bool write_png(std::FILE* file, VkExtent2D extent, VkFormat format, bool pq, const std::uint8_t* src) { + constexpr std::uint8_t signature[]{137, 80, 78, 71, 13, 10, 26, 10}; + std::array ihdr{}; + const auto w = big_endian(extent.width), h = big_endian(extent.height); + std::copy(w.begin(), w.end(), ihdr.begin()); + std::copy(h.begin(), h.end(), ihdr.begin() + 4); + ihdr[8] = 8; + ihdr[9] = 6; // 8-bit RGBA + constexpr std::uint8_t zlib_header[]{0x78, 0x01}; + if (std::fwrite(signature, 1, sizeof(signature), file) != sizeof(signature) || + !chunk(file, "IHDR", ihdr) || !chunk(file, "IDAT", zlib_header)) return false; + + // IDAT chunks concatenate to one zlib stream. Each scanline starts with PNG filter 0 and occupies + // one or more stored DEFLATE blocks (16-bit little-endian length and its ones' complement). + std::vector row(1 + size_t(extent.width) * 4); + std::uint32_t a = 1, b = 0; + for (unsigned y = 0; y < extent.height; ++y, src += size_t(extent.width) * texel_size(format)) { + rgba_row(row.data() + 1, src, extent.width, format, pq); + std::span rest(row); + while (!rest.empty()) { + auto block = rest.first(std::min(rest.size(), 65535)); + rest = rest.subspan(block.size()); + const auto len = std::uint16_t(block.size()); + const std::uint8_t header[]{std::uint8_t(y + 1 == extent.height && rest.empty()), + std::uint8_t(len), std::uint8_t(len >> 8), std::uint8_t(~len), std::uint8_t((len >> 8) ^ 255)}; + for (auto byte : block) { + a = (a + byte) % 65521; + b = (b + a) % 65521; + } + if (!chunk(file, "IDAT", block, header)) return false; + } + } + return chunk(file, "IDAT", big_endian((b << 16) | a)) && chunk(file, "IEND", {}); +} + +class PresentDump { +public: + PresentDump() { +#ifdef _WIN32 + wchar_t* env = nullptr; + size_t length = 0; + if (_wdupenv_s(&env, &length, L"LEONIDA_PRESENT_DUMP") != 0) { + bad_value(); + return; + } + const std::unique_ptr owned(env, &std::free); +#else + const auto* env = std::getenv("LEONIDA_PRESENT_DUMP"); +#endif + if (!env) return; + try { + auto value = std::filesystem::path(env).native(); + std::uint64_t interval = 60; + const auto comma = value.rfind(','); + if (comma != value.npos) { + const auto n = std::filesystem::path(value.substr(comma + 1)).string(); + const auto end = n.data() + n.size(); + const auto parsed = std::from_chars(n.data(), end, interval); + if (parsed.ec != std::errc{} || parsed.ptr != end || !interval) { + bad_value(); + return; + } + value.resize(comma); + } + if (value.empty()) { + bad_value(); + return; + } + dir_ = std::filesystem::absolute(value); + std::filesystem::create_directories(dir_); + interval_ = interval; + } catch (const std::exception&) { bad_value(); } + } + + bool enabled() const { return interval_ != 0; } + bool due(std::uint64_t frames_shown) const { + const auto n = interval_.load(); + return n && frames_shown % n == 0; + } + void disable(const char* why) { + if (interval_.exchange(0)) std::fprintf(stderr, "[rt] present: %s; LEONIDA_PRESENT_DUMP disabled\n", why); + } + void save(std::uint64_t frame, VkExtent2D extent, VkFormat format, bool pq, const std::uint8_t* src, size_t size) { + try { + // Bound memory to one outstanding write even at N=1. Teardown joins the final writer. + if (writer_.joinable()) writer_.join(); + if (!enabled()) return; + char name[48]; + std::snprintf(name, sizeof(name), "present_%06llu.png", static_cast(frame)); + writer_ = std::jthread([this, frame, extent, format, pq, path = dir_ / name, + bytes = std::vector(src, src + size)] { + try { + if (publish(path, extent, format, pq, bytes.data())) { + const auto utf8 = path.u8string(); + std::fprintf(stderr, "[rt] present: dumped frame %llu to %s\n", + static_cast(frame), reinterpret_cast(utf8.c_str())); + return; + } + } catch (const std::exception&) {} + disable("could not write the present dump"); + }); + } catch (const std::exception&) { disable("could not queue the present dump"); } + } + +private: + static void bad_value() { + static std::once_flag once; + std::call_once(once, [] { + std::fprintf(stderr, "[rt] present: invalid LEONIDA_PRESENT_DUMP (expected a writable dir[,N], N > 0); disabled\n"); + }); + } + static bool publish(const std::filesystem::path& path, VkExtent2D extent, VkFormat format, bool pq, + const std::uint8_t* src) { + // Never open an existing output for writing: it could be a link to a file outside the dump directory. + // Build a complete sibling exclusively, then replace the directory entry in a single rename. + auto tmp = path; + tmp += ".tmp"; +#ifdef _WIN32 + std::FILE* file = nullptr; + _wfopen_s(&file, tmp.c_str(), L"wbx"); +#else + auto* file = std::fopen(tmp.c_str(), "wbx"); +#endif + if (!file) return false; + bool ok = false; + try { ok = write_png(file, extent, format, pq, src); } catch (const std::exception&) {} + if (std::fclose(file) != 0) ok = false; + std::error_code ec; + if (ok) { + std::filesystem::rename(tmp, path, ec); + if (!ec) return true; + } + std::filesystem::remove(tmp, ec); + return false; + } + + std::filesystem::path dir_; + std::atomic interval_{0}; + std::jthread writer_; // joined before the state it uses is destroyed +}; + +} // namespace leonida::present_dump diff --git a/runtime/src/vulkan_present.h b/runtime/src/vulkan_present.h index 8644346c53..2ce6f457b2 100644 --- a/runtime/src/vulkan_present.h +++ b/runtime/src/vulkan_present.h @@ -27,6 +27,7 @@ #include "vulkan_backend.h" #include "vulkan_present_compose.h" +#include "present_dump.h" // Use the original EXT spellings. They are aliases of the promoted KHR types and are available in older headers. #if defined(VK_EXT_SWAPCHAIN_MAINTENANCE_1_EXTENSION_NAME) && defined(VK_EXT_SURFACE_MAINTENANCE_1_EXTENSION_NAME) @@ -583,7 +584,15 @@ class VulkanPresenter { // Only a present the engine took counts (SUBOPTIMAL is shown too). OUT_OF_DATE was not shown: the swapchain // is recreated next time, and the caller sees VK_SUCCESS, since its work was submitted. if (result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR) { - ++presented_; + const auto shown = ++presented_; + if (dump_.due(shown - 1)) { + // Presentation is already queued and the queue/tracker locks are released. A sampled frame + // may stall here for its transfer fence and a private CPU copy. PNG and disk I/O run on a worker. + if (vkWaitForFences_(device, 1, &frame.done, VK_TRUE, UINT64_MAX) == VK_SUCCESS) + dump_.save(shown, extent_, format_, dump_pq_, capture_ptr_, size_t(capture_size_)); + else + dump_.disable("present dump fence wait failed"); + } if (planes) ++composed_; if (tearing) { last_tore_ = true; @@ -915,7 +924,7 @@ class VulkanPresenter { const VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; VkImageLayout layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; VkAccessFlags access = VK_ACCESS_TRANSFER_WRITE_BIT; - if (capture_ && capture_buffer_) { + if (capture_buffer_ && (capture_ || dump_.due(presented_))) { // Two frames may be in flight and share `capture_buffer_`: serialize the prior frame's capture copy // before overwriting it, while moving this frame's swapchain image to TRANSFER_SRC. VkBufferMemoryBarrier capture_waw{VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER}; @@ -942,6 +951,10 @@ class VulkanPresenter { copy.imageExtent = {extent_.width, extent_.height, 1}; fn.copy_image_to_buffer(commands, images_[image], VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, capture_buffer_, 1, ©); + auto to_host = capture_waw; + to_host.dstAccessMask = VK_ACCESS_HOST_READ_BIT; + fn.pipeline_barrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, + 0, nullptr, 1, &to_host, 0, nullptr); layout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; access = VK_ACCESS_TRANSFER_READ_BIT; } @@ -954,7 +967,7 @@ class VulkanPresenter { release_capture(); auto& vk = context_.vk; const VkDevice device = context_.device(); - capture_size_ = VkDeviceSize(extent_.width) * extent_.height * 4; + capture_size_ = VkDeviceSize(extent_.width) * extent_.height * present_dump::texel_size(format_); VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; info.size = capture_size_; info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT; @@ -1039,7 +1052,9 @@ class VulkanPresenter { return true; } VkImageUsageFlags usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT; - if (capture_) usage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; + if (dump_.enabled() && !(caps.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_SRC_BIT)) + dump_.disable("surface does not support swapchain readback"); + if (capture_ || dump_.enabled()) usage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; if ((caps.supportedUsageFlags & usage) != usage) return false; // Not used by the presenter itself (it blits or copies into the images), but overlays that hook the swapchain // draw their own frame into its images through a framebuffer, which needs COLOR_ATTACHMENT: without it @@ -1183,13 +1198,14 @@ class VulkanPresenter { extent_ = extent; extent_packed_ = (std::uint64_t(extent.width) << 32) | extent.height; hdr_active_ = chose_hdr; - if (capture_) { - // A capture that cannot be made fails the recreation with the swapchain in place and stale_ still set. - const bool four_bytes = format_ == VK_FORMAT_B8G8R8A8_UNORM || format_ == VK_FORMAT_R8G8B8A8_UNORM || - format_ == VK_FORMAT_B8G8R8A8_SRGB || format_ == VK_FORMAT_R8G8B8A8_SRGB || - format_ == VK_FORMAT_A2B10G10R10_UNORM_PACK32 || - format_ == VK_FORMAT_A2R10G10B10_UNORM_PACK32; - if (!four_bytes || !make_capture_buffer()) return false; + dump_pq_ = chosen.colorSpace == VK_COLOR_SPACE_HDR10_ST2084_EXT; + if (capture_ || dump_.enabled()) { + const auto stride = present_dump::texel_size(format_); + if (capture_ && stride != 4) return false; // read_back() promises four bytes per texel + if (!stride || !make_capture_buffer()) { + dump_.disable("cannot read back this swapchain format or allocate its capture buffer"); + if (capture_) return false; + } } vsync_ = vsync; swapchain_srgb_ = srgb; @@ -1300,6 +1316,8 @@ class VulkanPresenter { std::map features_; bool warned_srgb_ = false; bool capture_ = false; + present_dump::PresentDump dump_; + bool dump_pq_ = false; VkBuffer capture_buffer_ = VK_NULL_HANDLE; VkDeviceMemory capture_memory_ = VK_NULL_HANDLE; VkDeviceSize capture_size_ = 0; diff --git a/runtime/test/vk_present_dump_test.cpp b/runtime/test/vk_present_dump_test.cpp new file mode 100644 index 0000000000..a4497166f9 --- /dev/null +++ b/runtime/test/vk_present_dump_test.cpp @@ -0,0 +1,113 @@ +// Present a small solid texture through the window blit and the PresentX plane composer. Only the composed +// image has a black lower half. Decode the PNGs independently with the conformance tool's WIC reader. +#define VK_USE_PLATFORM_WIN32_KHR +#include +#include + +#include "test_temp_dir.h" +#include "vk_test_device.h" +#include "../src/vulkan_present.h" +#include "../../tools/conformance/native/src/png_io.h" + +#include +#include +#include +#include +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +int main(int argc, char** argv) { + using namespace leonida; + namespace fs = std::filesystem; + vktest::Device d; + const auto status = d.initialize(true); + if (status == vktest::DeviceStatus::unavailable) return 77; + EXPECT(status == vktest::DeviceStatus::ready); + EXPECT(SUCCEEDED(CoInitializeEx(nullptr, COINIT_MULTITHREADED))); + testfiles::ScratchDir scratch("leonida_present_dump"); + const fs::path dir = scratch.path() / "frames"; + const std::string_view mode = argc == 2 ? argv[1] : ""; + EXPECT(mode.empty() || mode == "--default" || mode == "--invalid"); + const int interval = mode == "--default" ? 60 : 2; + const auto setting = dir.wstring() + (mode == "--default" ? L"" : mode == "--invalid" ? L",0" : L",2"); + EXPECT(_wputenv_s(L"LEONIDA_PRESENT_DUMP", setting.c_str()) == 0); + // An earlier dump might be a hard link outside the requested directory. Replacing it must leave that file intact. + const auto sentinel = scratch.path() / "outside"; + if (mode == "--default") { + EXPECT(fs::create_directory(dir)); + EXPECT(std::ofstream(sentinel).put('X')); + std::error_code ec; + fs::create_hard_link(sentinel, dir / "present_000001.png", ec); // optional on filesystems without links + } + + constexpr int width = 192, height = 100; + const HINSTANCE instance = GetModuleHandleW(nullptr); + HWND window = CreateWindowExW(0, L"STATIC", L"Leonida present dump test", WS_POPUP, 0, 0, width, height, + nullptr, nullptr, instance, nullptr); + EXPECT(window); + ShowWindow(window, SW_SHOWNOACTIVATE); + VulkanContext context(d.device_proc, d.device, true); + VulkanQueue queue(context, d.queue, d.family); + EXPECT(context.loaded() && queue.ok()); + ResourceBinding back{}; + back.format = VK_FORMAT_R8G8B8A8_UNORM; + back.width = back.height = 2; + back.aspects = VK_IMAGE_ASPECT_COLOR_BIT; + back.sampled = back.color_attachment = true; + back.image = d.image(back.format, 2, 2, 1, VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT); + EXPECT(back.image); + context.add_resource(1, back, VK_IMAGE_LAYOUT_UNDEFINED); + CommandList commands; + EXPECT(commands.transition({1, 0, d3d12_state::common, d3d12_state::render_target})); + EXPECT(commands.clear_render_target({1, 0, 0, 1}, {1.0f, 0.4f, 0.0f, 1.0f})); + EXPECT(commands.transition({1, 0, d3d12_state::render_target, d3d12_state::common})); + EXPECT(commands.close()); + const CommandList* list = &commands; + EXPECT(queue.execute({&list, 1}) == ReplayResult::success); + + VkWin32SurfaceCreateInfoKHR info{VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR}; + info.hinstance = instance; + info.hwnd = window; + VkSurfaceKHR surface{}; + EXPECT(d.instance_fn("vkCreateWin32SurfaceKHR")( + d.instance, &info, nullptr, &surface) == VK_SUCCESS); + { + VulkanPresenter presenter(context, d.instance_proc, d.instance, d.physical, d.queue, d.family, surface, + false, [] { return VkExtent2D{width, height}; }); + EXPECT(presenter.ok()); + EXPECT(presenter.present(1, true) == VK_SUCCESS); + for (int i = 1; i < interval; ++i) EXPECT(presenter.present_blank(true) == VK_SUCCESS); + PresentPlanes planes; + planes.plane[0].source = 1; + planes.plane[0].dest[3] = 0.5f; + EXPECT(presenter.present_planes(planes, true) == VK_SUCCESS); + EXPECT(presenter.presented() == unsigned(interval + 1) && presenter.composed_presents() == 1); + } + DestroyWindow(window); + EXPECT(d.validation_errors() == 0); + if (mode == "--invalid") { + EXPECT(!fs::exists(dir)); + CoUninitialize(); + return 0; + } + if (mode == "--default") EXPECT(fs::file_size(sentinel) == 1 && std::ifstream(sentinel).get() == 'X'); + for (bool composed : {false, true}) { + const auto* name = !composed ? "present_000001.png" : interval == 2 ? "present_000003.png" : "present_000061.png"; + PixelSurface png; + EXPECT(ReadPngFile(dir / name, png)); + EXPECT(png.width == width && png.height == height); + for (int y = 0; y < height; ++y) { + const bool black = composed && y >= height / 2; + const std::array expected = black ? std::array{0, 0, 0, 255} + : std::array{255, 102, 0, 255}; + for (int x = 0; x < width; ++x) + EXPECT(std::equal(expected.begin(), expected.end(), png.At(x, y))); + } + } + EXPECT(std::distance(fs::directory_iterator(dir), fs::directory_iterator{}) == 2); + CoUninitialize(); + return 0; +} From 3a4ffa45048d2f385a1083ff2c6f654b5f1eac27 Mon Sep 17 00:00:00 2001 From: Mumogg <104529023+Mumogg@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:21:40 -0600 Subject: [PATCH 23/27] local: graphics stage layout experiment (s8), CB diagnostics --- runtime/shims/d3d12_com.cpp | 3 ++- runtime/shims/d3d12_com.h | 10 ++++++++++ runtime/shims/d3d12_vulkan_device.cpp | 9 +++++++++ runtime/shims/d3d12_xs_device.cpp | 12 ++++++++++++ runtime/src/vulkan_replay.h | 7 +++++++ 5 files changed, 40 insertions(+), 1 deletion(-) diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index bf51da8e09..a497827445 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -1274,7 +1274,8 @@ class GraphicsCommandList final write(state, first, std::uint32_t(va)); // In the compute layout a descriptor table is one dword, the 32-bit VA of its first descriptor (the heaps // live below 4 GiB); a root view keeps both halves. The graphics layout gives every address two dwords. - if (!(is_compute(state) && type == rt::rootsig::ParamType::Table)) write(state, first + 1, std::uint32_t(va >> 32)); + if (!((is_compute(state) || local_graphics_stage_layout()) && type == rt::rootsig::ParamType::Table)) + write(state, first + 1, std::uint32_t(va >> 32)); } D3D12_COMMAND_LIST_TYPE type_; diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index b5e99ea6df..ae62e4b111 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -10,6 +10,8 @@ // - the CPU handle of an RTV or DSV points at a leonida::TargetView in the device's descriptor heap. #pragma once +#include + #include #include #include @@ -371,6 +373,14 @@ std::unique_ptr create_window_presenter(ID3D12Device* device, H // exist, because a mesh shader (s16) and a pixel shader (s8) share one push-constant block); // - compute: rt::rootsig::pack_stage(Stage::Compute), the measured console layout (from s4, one dword per table). // A layout that refuses the signature is marked unusable; binding the signature there invalidates the list. +// LOCAL EXPERIMENT: LEONIDA_GRAPHICS_STAGE_LAYOUT=1 lays graphics root arguments out as the console does for the +// vertex, pixel and geometry stages (rt::rootsig::pack_stage: from s8, a descriptor table in one dword) instead of +// from s0 with two dwords per address. +inline bool local_graphics_stage_layout() { + static const bool on = [] { const char* v = std::getenv("LEONIDA_GRAPHICS_STAGE_LAYOUT"); return v && *v == '1'; }(); + return on; +} + struct RootArgumentLayout { struct Parameter { rt::rootsig::ParamType type; diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 0a75413d6c..788434419a 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -6710,6 +6710,14 @@ class Device final layout.flags = parsed.sig.flags; layout.graphics_ok = packed.ok; layout.compute_ok = compute.ok; + const rt::rootsig::StagePackResult local_stage = rt::rootsig::pack_stage(parsed.sig, rt::rootsig::Stage::Vertex); + const bool local_stage_layout = local_graphics_stage_layout() && local_stage.ok; + if (local_graphics_stage_layout()) { + static std::atomic said{0}; + if (said.fetch_add(1) < 3) + std::fprintf(stderr, "[rt] d3d12: local: graphics root arguments in the console stage layout (from s%u): %s\n", + local_stage.base, local_stage.ok ? "ok" : local_stage.error.c_str()); + } for (std::size_t i = 0; i < parsed.sig.params.size(); ++i) { std::uint32_t first = UINT32_MAX; for (std::uint32_t d = 0; packed.ok && d < packed.dword_count; ++d) @@ -6717,6 +6725,7 @@ class Device final first = d; break; } + if (local_stage_layout) first = local_stage.first_sgpr[i]; layout.parameters.push_back({parsed.sig.params[i].type, first, parsed.sig.params[i].num_values, compute.ok ? compute.first_sgpr[i] : rt::rootsig::kNoSgpr, table_view_descriptors(parsed.sig.params[i])}); diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 2d00e00c9b..56b2863386 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -24,6 +24,7 @@ // 78 SetFrameIntervalX, 79 ScheduleFrameEventX and 80 WaitFrameEventX. The slots can be moved with LEONIDA_XS_*_SLOT // for a trace that disagrees. The frame-event calls answer from a per-device token counter: there is no vblank source // behind the device before a presenter exists, so WaitFrameEventX returns at once with a fresh non-zero token. +#include "../src/vulkan_replay.h" #include "title_window.h" #include "d3d12_xs_device.h" #include "d3d12_trace.h" @@ -2750,6 +2751,8 @@ HRESULT proxy_create_descriptor_heap(DeviceProxy* self, const D3D12_DESCRIPTOR_H void proxy_create_cbv(DeviceProxy* self, const D3D12_CONSTANT_BUFFER_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE dest) { note_slot(17); + if (desc && desc->SizeInBytes == 96 && desc->BufferLocation < 0x100000000ull) + leonida::g_local_last_cb96.store(desc->BufferLocation); { // LOCAL DIAGNOSTIC static std::atomic said{0}; const int n = said.fetch_add(1); @@ -2758,6 +2761,15 @@ void proxy_create_cbv(DeviceProxy* self, const D3D12_CONSTANT_BUFFER_VIEW_DESC* std::fprintf(stderr, "[rt] localdbg: CreateCBV #%d dest=0x%llx -> 0x%llx location=0x%llx size=%u\n", n, static_cast(dest.ptr), static_cast(t.ptr), desc ? static_cast(desc->BufferLocation) : 0ull, desc ? desc->SizeInBytes : 0u); + MEMORY_BASIC_INFORMATION q{}; + if (desc && desc->BufferLocation && desc->BufferLocation < 0x100000000ull && + VirtualQuery(reinterpret_cast(desc->BufferLocation), &q, sizeof(q)) && q.State == MEM_COMMIT && + !(q.Protect & (PAGE_NOACCESS | PAGE_GUARD))) { + const float* f = reinterpret_cast(desc->BufferLocation); + std::fprintf(stderr, "[rt] localdbg: constants now:"); + for (int w = 0; w < 24 && w * 4u < desc->SizeInBytes; ++w) std::fprintf(stderr, " %g", f[w]); + std::fprintf(stderr, "\n"); + } } } self->real->CreateConstantBufferView(desc, translate_cpu_handle(self, dest)); diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index c4dac14349..285159c602 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -812,6 +812,7 @@ enum class ReplayResult { // LOCAL DIAGNOSTIC: the arena's host mapping and size, for dumps of what a shader would read. inline std::uint8_t* g_local_arena_mapped = nullptr; inline std::uint64_t g_local_arena_size = 0; +inline std::atomic g_local_last_cb96{0}; // title address of the last 96-byte constant view created // LOCAL DIAGNOSTIC: which check returned unresolved_resource (first 3 times per source line). inline ReplayResult local_unresolved_at(int line) { @@ -2266,6 +2267,12 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct std::fprintf(stderr, "[rt] localdbg: title table guess is not readable title memory\n"); } } + if (const std::uint64_t cb = g_local_last_cb96.load()) { + const float* f3 = reinterpret_cast(cb); + std::fprintf(stderr, "[rt] localdbg: 96-byte constants in title memory at draw time:"); + for (int w = 0; w < 24; ++w) std::fprintf(stderr, " %g", f3[w]); + std::fprintf(stderr, "\n"); + } { // what sits just before the vertices in the title's ring const std::uint32_t* t = reinterpret_cast(view.va - 0x60); for (int e = 0; e < 3; ++e) { From 902d594127bd7355ebe9fb0aad84dcca5acd4dd7 Mon Sep 17 00:00:00 2001 From: Mumogg <104529023+Mumogg@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:00:51 -0600 Subject: [PATCH 24/27] local: slot 70 title views, rect fourth corner v1+v3-v2, diagnostics --- runtime/shims/d3d12_xs_device.cpp | 33 +++++++++++++++++++++++++++++++ runtime/src/rect_list_geometry.h | 18 ++++++++++++++--- runtime/src/vulkan_replay.h | 9 +++++---- 3 files changed, 53 insertions(+), 7 deletions(-) diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 56b2863386..99d70e4085 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -2533,6 +2533,18 @@ void proxy_create_srv_from_raw_x(DeviceProxy* self, std::uint64_t texture_words, note_slot(70); log_xbox_route_once(70, "CreateShaderResourceView from raw words", texture_words, view_desc, destination, 0, 0); if (!destination) return; + // LOCAL: whatever this call writes to the real slot is stored at the title's address too when it returns. + struct LocalWriteThrough { + DeviceProxy* self; + std::uint64_t custom; + ~LocalWriteThrough() { local_write_through(self, D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(custom)}, 1); } + } local_write_back{self, destination}; + { + static std::atomic calls{0}; + const int n = calls.fetch_add(1); + if (n < 4 || n % 5000 == 0) + std::fprintf(stderr, "[rt] localdbg: slot 70 call #%d dest=0x%llx\n", n, static_cast(destination)); + } // The console hands a CPU descriptor handle in the title's heap memory; #7021 translates it to the real heap's. destination = translate_cpu_handle(self, D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(destination)}).ptr; @@ -2547,7 +2559,28 @@ void proxy_create_srv_from_raw_x(DeviceProxy* self, std::uint64_t texture_words, ID3D12Resource* resource = self->resource_provider(self->real, shape.va, shape.resource.Width, &start, &size); if (!resource || shape.va < start || shape.va - start >= size) { if (resource) resource->Release(); + // LOCAL: a small raw view over the title's own memory becomes a raw buffer V# through the constant-view path, + // which resolves a title address to its GPU copy (#9137). LEONIDA_SLOT70_TITLE=0 keeps the null view. + static const bool title_views = [] { const char* v = std::getenv("LEONIDA_SLOT70_TITLE"); return !(v && *v == '0'); }(); + if (title_views && shape.va && shape.va < 0x100000000ull && shape.resource.Width && shape.resource.Width <= 65536) { + D3D12_CONSTANT_BUFFER_VIEW_DESC constants{}; + constants.BufferLocation = shape.va; + constants.SizeInBytes = static_cast(shape.resource.Width); + self->real->CreateConstantBufferView(&constants, D3D12_CPU_DESCRIPTOR_HANDLE{destination}); + static std::atomic said{false}; + if (!said.exchange(true)) + std::fprintf(stderr, "[rt] d3d12_xs: local: slot 70 view over title memory (%llu bytes) written as a raw " + "buffer V# on its GPU copy\n", static_cast(shape.resource.Width)); + return; + } log_slot70_null_once("no buffer holds the address", texture_words, view_desc); + { + static std::atomic nulls{0}; + const int n = nulls.fetch_add(1); + if (n < 3 || n % 5000 == 0) + std::fprintf(stderr, "[rt] localdbg: slot 70 null #%d: no buffer holds va=0x%llx width=%llu\n", n, + static_cast(shape.va), static_cast(shape.resource.Width)); + } write_null_srv(self, destination); return; } diff --git a/runtime/src/rect_list_geometry.h b/runtime/src/rect_list_geometry.h index 15d7368d34..1300c041ec 100644 --- a/runtime/src/rect_list_geometry.h +++ b/runtime/src/rect_list_geometry.h @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -168,15 +169,26 @@ inline std::vector rect_list_geometry(const std::vector(g_local_arena_mapped + draw.user_data[0]); + const std::uint32_t local_table = draw.user_data[0] ? draw.user_data[0] : draw.user_data[8]; + if (g_local_arena_mapped && local_table && local_table + 256ull <= g_local_arena_size) { + const std::uint32_t* t = reinterpret_cast(g_local_arena_mapped + local_table); for (int e = 0; e < 4; ++e) { std::fprintf(stderr, "[rt] localdbg: table[%d]:", e); for (int w = 0; w < 8; ++w) std::fprintf(stderr, " %08x", t[e * 8 + w]); std::fprintf(stderr, "\n"); const std::uint64_t va = (std::uint64_t(t[e * 8 + 1] & 0xffff) << 32) | t[e * 8]; - if (va && va + 64 <= g_local_arena_size) { + if (va && va + 128 <= g_local_arena_size) { const float* f2 = reinterpret_cast(g_local_arena_mapped + va); std::fprintf(stderr, "[rt] localdbg: at va 0x%llx:", static_cast(va)); - for (int w = 0; w < 16; ++w) std::fprintf(stderr, " %g", f2[w]); + for (int w = 0; w < 32; ++w) std::fprintf(stderr, " %g", f2[w]); std::fprintf(stderr, "\n"); } } From 74bf391fdae4e5d5c81314b8abe05412807d4f69 Mon Sep 17 00:00:00 2001 From: Mumogg <104529023+Mumogg@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:46:46 -0600 Subject: [PATCH 25/27] merge follow-up: the test tree builds again - xmem.cpp: rt::xmem::commit_physical_range and commit_physical_pages exist for the run-mapped xmem too (pages are committed when allocated, so they only check the range), and main.cpp registers the slot 133 hook as main does. - vk_test_device.h: VK_EXT_external_memory_host and host_pointer_alignment are back next to the A8 render target probe; d3d12_existing_heap_test and d3d12_xmem_placed_test use them. - xs_proxy_mock_test.cpp: the stack's version, which tests the proxy that is in the tree (the automatic merge left two list mocks in one switch). - d3d12_xs_device.cpp: no include of vulkan_replay.h, which the proxy tests without Vulkan headers could not compile, and the diagnostic that needed it is gone. Every target builds with clang-cl 22.1.8 + xwin. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01HxBQf4pXH8PWpC5oZsM4bt --- runtime/shims/d3d12_xs_device.cpp | 3 - runtime/shims/xmem.cpp | 31 ++++ runtime/src/main.cpp | 3 +- runtime/test/vk_test_device.h | 13 ++ runtime/test/xs_proxy_mock_test.cpp | 253 +--------------------------- 5 files changed, 47 insertions(+), 256 deletions(-) diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 7b0953382c..09d753a86a 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -24,7 +24,6 @@ // 78 SetFrameIntervalX, 79 ScheduleFrameEventX and 80 WaitFrameEventX. The slots can be moved with LEONIDA_XS_*_SLOT // for a trace that disagrees. The frame-event calls answer from a per-device token counter: there is no vblank source // behind the device before a presenter exists, so WaitFrameEventX returns at once with a fresh non-zero token. -#include "../src/vulkan_replay.h" #include "title_window.h" #include "d3d12_xs_device.h" #include "d3d12_trace.h" @@ -2784,8 +2783,6 @@ HRESULT proxy_create_descriptor_heap(DeviceProxy* self, const D3D12_DESCRIPTOR_H void proxy_create_cbv(DeviceProxy* self, const D3D12_CONSTANT_BUFFER_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE dest) { note_slot(17); - if (desc && desc->SizeInBytes == 96 && desc->BufferLocation < 0x100000000ull) - leonida::g_local_last_cb96.store(desc->BufferLocation); { // LOCAL DIAGNOSTIC static std::atomic said{0}; const int n = said.fetch_add(1); diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp index e5db2ce6d2..e8988c0461 100644 --- a/runtime/shims/xmem.cpp +++ b/runtime/shims/xmem.cpp @@ -37,6 +37,7 @@ #include "shims.h" #include "startup_trace.h" #include "../src/title_va_alias.h" +#include "xmem.h" namespace { @@ -801,6 +802,36 @@ LPVOID WINAPI TitleVirtualAlloc(LPVOID address, SIZE_T size, DWORD allocation_ty } // namespace +namespace rt::xmem { + +// main's xmem commits physical pages on first touch and exposes these two for code that must see them committed +// (slot 133's import, d3d12_xmem_placed_test). Here a physical page is committed when it is allocated, so there is +// nothing to do: the range only has to be mapped, readable memory, and the page array non-null. +bool commit_physical_range(const void* address, std::size_t size) { + if (size == 0) return true; + const auto* at = static_cast(address); + const auto* const end = at + size; + while (at < end) { + MEMORY_BASIC_INFORMATION info{}; + if (!VirtualQuery(at, &info, sizeof(info)) || info.State != MEM_COMMIT) { + SetLastError(ERROR_INVALID_ADDRESS); + return false; + } + at = static_cast(info.BaseAddress) + info.RegionSize; + } + return true; +} + +bool commit_physical_pages(const std::uint64_t* page_array, std::size_t count) { + if (count && !page_array) { + SetLastError(ERROR_INVALID_PARAMETER); + return false; + } + return true; +} + +} // namespace rt::xmem + #define TITLE_VIRTUAL_ALLOC(dll) {dll, "VirtualAlloc", reinterpret_cast(&TitleVirtualAlloc)} // The classic libraries and the memory api sets a title's imports name. diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp index 7d0dbfd88a..63bd016e8a 100644 --- a/runtime/src/main.cpp +++ b/runtime/src/main.cpp @@ -177,8 +177,7 @@ int wmain(int argc, wchar_t** argv) { } rt::d3d12_trace::set_enabled(trace_d3d12); // Slot 133 imports the title's pages; xmem commits them on first touch, so they are committed first. - // MERGE NOTE: main registers rt::xmem::commit_physical_range here for its commit-on-touch xmem. This branch keeps - // the run-mapped xmem (pages are committed when allocated), so there is nothing to commit before slot 133. + rt::d3d12_xs::set_placed_at_va_pages_hook(&rt::xmem::commit_physical_range); if (int trace_error = 0; !trace_file.empty() && !rt::startup_trace::open(trace_file.c_str(), &trace_error)) { std::fprintf(stderr, trace_error == EEXIST ? "error: the trace file already exists; --trace only creates a new file\n" : "error: cannot create the trace file\n"); diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h index 391ee5d097..0aca467878 100644 --- a/runtime/test/vk_test_device.h +++ b/runtime/test/vk_test_device.h @@ -109,6 +109,8 @@ class Device { // VK_KHR_maintenance5 enabled, where VK_FORMAT_A8_UNORM_KHR can be sampled and blended as a colour attachment, as // gta6rt enables it (VulkanDeviceInfo::a8_render_target). bool a8_render_target = false; + // VK_EXT_external_memory_host is enabled when non-zero: its minImportedHostPointerAlignment. + VkDeviceSize host_pointer_alignment = 0; // create(true) only: VK_KHR (else EXT) swapchain_maintenance1 and its feature enabled, with the surface half on the // instance, so a vsync swapchain can switch to IMMEDIATE or FIFO_RELAXED per present. bool swapchain_maintenance1 = false; @@ -500,6 +502,16 @@ class Device { host_copy.pNext = *v13_.next(); // after the conditional rendering features, if any *v13_.next() = &host_copy; } + // VK_EXT_external_memory_host where the device has it (OpenExistingHeapFromAddress). + for (const auto& extension : extensions) { + if (std::strcmp(extension.extensionName, VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME) != 0) continue; + VkPhysicalDeviceExternalMemoryHostPropertiesEXT host_memory{ + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_MEMORY_HOST_PROPERTIES_EXT}; + VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &host_memory}; + instance_fn("vkGetPhysicalDeviceProperties2")(physical, &properties); + host_pointer_alignment = host_memory.minImportedHostPointerAlignment; + } + #ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME VkPhysicalDeviceMaintenance5FeaturesKHR maintenance5{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_5_FEATURES_KHR}; @@ -592,6 +604,7 @@ class Device { #ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME if (a8_render_target) device_extensions.push_back(VK_KHR_MAINTENANCE_5_EXTENSION_NAME); #endif + if (host_pointer_alignment) device_extensions.push_back(VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME); const char* swapchain = "VK_KHR_swapchain"; if (presentation) device_extensions.push_back(swapchain); #if defined(VK_KHR_swapchain_maintenance1) diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index bd89438cfd..5592d5875f 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -90,7 +90,6 @@ struct Mock { Kind kind; long refs; int device_level; // device: highest ID3D12DeviceN it answers (0 = ID3D12Device only) - int list_level; // command_list: 0=base (60 slots), 7=GCL7 (81 slots), 8=GCL8 (82 slots) bool fence1; // fence: answers ID3D12Fence1; device: the fences it makes do bool allocator_tag; // allocator: answers kLeonidaCommandAllocatorTag; device: the allocators it makes do bool full_chain_lists; // device: CreateCommandList makes a full-chain list mock (Kind::list), else command_list @@ -205,21 +204,9 @@ bool mock_has(const Mock* m, REFIID iid) { case Kind::fence: return IsEqualIID(iid, __uuidof(ID3D12Fence)) || (m->fence1 && IsEqualIID(iid, __uuidof(ID3D12Fence1))); case Kind::resource: return IsEqualIID(iid, __uuidof(ID3D12Resource)); - case Kind::heap: return IsEqualIID(iid, __uuidof(ID3D12DescriptorHeap)); case Kind::command_list: - if (IsEqualIID(iid, __uuidof(ID3D12CommandList)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList))) return true; -#ifdef __ID3D12GraphicsCommandList7_INTERFACE_DEFINED__ - if (m->list_level >= 7 && (IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList7)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList6)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList5)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList4)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList3)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList2)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList1)))) - return true; -#endif - return false; + return IsEqualIID(iid, __uuidof(ID3D12CommandList)) || + IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList)); case Kind::allocator: return IsEqualIID(iid, __uuidof(ID3D12CommandAllocator)) || (m->allocator_tag && IsEqualIID(iid, xs::kLeonidaCommandAllocatorTag)); @@ -775,65 +762,6 @@ int check_levels() { mock->calls[68] == 0 && mock->calls[108] == 0); } - // 133 with a pages hook (set_placed_at_va_pages_hook): a buffer's range [va, va + width) is handed to it - // before the handler runs; a texture is not; a hook that fails still leaves the call to the handler. - { - static int order = 0; - static int hook_at = 0; - static int handler_at = 0; - static const void* hook_va = nullptr; - static std::size_t hook_bytes = 0; - static bool hook_result = true; - order = hook_at = handler_at = 0; - const xs::PlacedAtVaPagesHook hook = [](const void* va, std::size_t bytes) -> bool { - hook_at = ++order; - hook_va = va; - hook_bytes = bytes; - return hook_result; - }; - const xs::PlacedAtVaHandler handler = [](ID3D12Device*, void*, const D3D12_RESOURCE_DESC&, std::uint32_t, - REFIID, void** out) -> HRESULT { - handler_at = ++order; - *out = reinterpret_cast(0x1331); - return S_OK; - }; - xs::set_placed_at_va_handler(handler); - xs::set_placed_at_va_pages_hook(hook); - D3D12_RESOURCE_DESC xbox_desc{}; - xbox_desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - xbox_desc.Width = 0xadf0000; - xbox_desc.Height = xbox_desc.DepthOrArraySize = xbox_desc.MipLevels = 1; - xbox_desc.SampleDesc.Count = 1; - xbox_desc.Layout = static_cast(0x1); - const GUID resource_iid = __uuidof(ID3D12Resource); - void* placed = nullptr; - void* const va = reinterpret_cast(0x7f0000010000ull); - auto place = [&]() { - placed = nullptr; - return hr_of(raw(device, 133, word(va), word(&xbox_desc), 0xFFFFFFFFull, 0, word(&resource_iid), - word(&placed))); - }; - const HRESULT buffer_hr = place(); - EXPECT(buffer_hr == S_OK && placed == reinterpret_cast(0x1331)); - EXPECT(hook_at == 1 && handler_at == 2 && hook_va == va && hook_bytes == 0xadf0000); - - hook_result = false; - order = hook_at = handler_at = 0; - const HRESULT refused_hr = place(); - EXPECT(refused_hr == S_OK && hook_at == 1 && handler_at == 2); - hook_result = true; - - xbox_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; - xbox_desc.Width = 64; - xbox_desc.Height = 64; - order = hook_at = handler_at = 0; - const HRESULT texture_hr = place(); - EXPECT(texture_hr == S_OK && hook_at == 0 && handler_at == 1); - - xs::set_placed_at_va_pages_hook(nullptr); - xs::set_placed_at_va_handler(nullptr); - } - Mock* const queue_mock = reinterpret_cast(real_queue); Mock* const fence_mock = reinterpret_cast(real_fence); EXPECT(release(queue) == 0 && release(fence) == 0); @@ -2833,183 +2761,6 @@ static void no_dialogs() { SetErrorMode(GetErrorMode() | SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX); } -int check_console_command_list() { - // 1. Slot mapping checks - EXPECT(xs::console_to_pc_list_slot(14) == 14); // Dispatch - EXPECT(xs::console_to_pc_list_slot(26) == 26); // ResourceBarrier - EXPECT(xs::console_to_pc_list_slot(31) == 27); // ExecuteBundle - EXPECT(xs::console_to_pc_list_slot(32) == 28); // SetDescriptorHeaps - EXPECT(xs::console_to_pc_list_slot(33) == 29); // SetComputeRootSignature - EXPECT(xs::console_to_pc_list_slot(35) == 31); // SetComputeRootDescriptorTable - EXPECT(xs::console_to_pc_list_slot(60) == 58); // EndEvent - EXPECT(xs::console_to_pc_list_slot(61) == 59); // ExecuteIndirect - EXPECT(xs::console_to_pc_list_slot(85) == 16); // CopyTextureRegion - EXPECT(xs::console_to_pc_list_slot(146) == 80); // GCL7 Barrier - EXPECT(xs::console_to_pc_list_slot(148) == xs::kListNotForwarded); // AllocateUploadMemory - - Mock* mock_device = nullptr; - void* device = make_device(mock_device, 11, true); - EXPECT(device != nullptr); - - // 2. PC Slot 12 vs Xbox Slot 73 - // PC Slot 12 returns unwrapped list directly, so PC tests like tiny_frame can call slot 48 (ClearRenderTargetView) - void* pc_list = nullptr; - const IID list_iid = __uuidof(ID3D12GraphicsCommandList); - EXPECT(hr_of(raw(device, 12, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, 0, 0, word(&list_iid), word(&pc_list))) == S_OK); - EXPECT(pc_list != nullptr); - EXPECT(!xs::is_command_list_proxy(pc_list)); - Mock* real_pc_list = reinterpret_cast(pc_list); - EXPECT(real_pc_list->kind == Kind::command_list); - // In PC ABI, slot 48 is ClearRenderTargetView - raw(pc_list, 48, 0x1111, 0x2222, 0, 0); - EXPECT(real_pc_list->calls[48] == 1); - EXPECT(release(pc_list) == 0); - - // Xbox Slot 73 returns wrapped console command list proxy - void* allocator = nullptr; - const IID alloc_iid = __uuidof(ID3D12CommandAllocator); - EXPECT(hr_of(raw(device, 9, 0, word(&alloc_iid), word(&allocator))) == S_OK); - EXPECT(xs::is_allocator_proxy(allocator)); - Mock* real_allocator = reinterpret_cast(xs::allocator_proxy_real_allocator(allocator)); - - struct XboxCommandListDesc { - std::uint32_t type; - std::uint32_t node_mask; - std::uint64_t reserved[2]; - } desc{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, {0, 0}}; - - void* list_proxy = nullptr; - EXPECT(hr_of(raw(device, 73, word(&desc), word(allocator), 0, word(&list_iid), word(&list_proxy))) == S_OK); - EXPECT(xs::is_command_list_proxy(list_proxy)); - EXPECT(xs::command_list_proxy_table_size() == 160); - - // 3. Inline cursor pinning: +0x18, +0x28, +0x30 - const auto base = reinterpret_cast(list_proxy); - std::uint64_t c18 = 0, c28 = 0, c30 = 0; - std::memcpy(&c18, reinterpret_cast(base + 0x18), sizeof(c18)); - std::memcpy(&c28, reinterpret_cast(base + 0x28), sizeof(c28)); - std::memcpy(&c30, reinterpret_cast(base + 0x30), sizeof(c30)); - const std::uint64_t expected_limit = static_cast(base + 0x18 + 0x500); - EXPECT(c18 == expected_limit); - EXPECT(c28 == expected_limit); - EXPECT(c30 == expected_limit); - - // 4. Console slot routing on ListProxy - Mock* real_list = reinterpret_cast(xs::command_list_proxy_real_list(list_proxy)); - EXPECT(real_list != nullptr && real_list->kind == Kind::command_list); - - // Console slot 32 (SetDescriptorHeaps) -> PC slot 28 - // Pass descriptor heap proxy to ensure UnwrappedArray unwrap_object works - D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 16, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; - void* heap_proxy = nullptr; - const IID heap_iid = __uuidof(ID3D12DescriptorHeap); - EXPECT(hr_of(raw(device, 14, word(&heap_desc), word(&heap_iid), word(&heap_proxy))) == S_OK); - EXPECT(heap_proxy != nullptr && xs::is_heap_proxy(heap_proxy)); - ID3D12DescriptorHeap* real_heap = xs::heap_proxy_real_heap(heap_proxy); - void* heap_ptrs[2] = {heap_proxy, real_heap}; - raw(list_proxy, 32, 2, word(heap_ptrs), 0, 0); - EXPECT(real_list->calls[28] == 1); - EXPECT(real_list->args[28][0] == 2); - // The heap proxy should have been unwrapped in the array passed to PC slot 28: - EXPECT(real_list->array[28][0] == word(real_heap)); - EXPECT(real_list->array[28][1] == word(real_heap)); - EXPECT(xs::list_slot_hits(32) == 1); - EXPECT(xs::list_slot_first_call_seen(32)); - - // Console slot 33 (SetComputeRootSignature) -> PC slot 29 - raw(list_proxy, 33, 0x5555, 0, 0, 0); - EXPECT(real_list->calls[29] == 1); - EXPECT(real_list->args[29][0] == 0x5555); - EXPECT(xs::list_slot_hits(33) == 1); - EXPECT(xs::list_slot_first_call_seen(33)); - - // Console slot 60 (EndEvent) -> PC slot 58 - raw(list_proxy, 60, 0, 0, 0, 0); - EXPECT(real_list->calls[58] == 1); - - // Console slot 61 (ExecuteIndirect) -> PC slot 59 - raw(list_proxy, 61, 0x10, 0x20, 0x30, 0x40); - EXPECT(real_list->calls[59] == 1); - EXPECT(real_list->args[59][0] == 0x10); - - // Console slot 148 (AllocateUploadMemory stub) -> returns 0 without faulting - EXPECT(raw(list_proxy, 148, 2048, 512, 0, 0) == 0); - EXPECT(xs::list_slot_hits(148) == 1); - EXPECT(xs::list_slot_first_call_seen(148)); - - // Console slot 146 (Barrier) on base 60-slot list returns E_NOTIMPL (PC slot 80 >= 60) - EXPECT(hr_of(raw(list_proxy, 146, 0, 0, 0, 0)) == E_NOTIMPL); - - // Console slot 10 (Reset) unwraps allocator proxy and re-pins inline cursor - std::uint64_t zero = 0; - std::memcpy(reinterpret_cast(base + 0x18), &zero, sizeof(zero)); - EXPECT(hr_of(raw(list_proxy, 10, word(allocator), 0, 0, 0)) == S_OK); - EXPECT(real_list->calls[10] == 1); - EXPECT(real_list->args[10][0] == word(real_allocator)); - std::memcpy(&c18, reinterpret_cast(base + 0x18), sizeof(c18)); - EXPECT(c18 == expected_limit); - - // Console slot 7 (GetDevice) returns device proxy - void* list_dev = nullptr; - const IID dev_iid = __uuidof(ID3D12Device); - const auto dev_refs_before = xs::device_proxy_ref_count(device); - EXPECT(hr_of(raw(list_proxy, 7, word(&dev_iid), word(&list_dev))) == S_OK); - EXPECT(list_dev == device); - EXPECT(xs::device_proxy_ref_count(device) == dev_refs_before + 1); - EXPECT(release(list_dev) == dev_refs_before); - - // Console slot 0 (QueryInterface) - void* list_qi = nullptr; - EXPECT(hr_of(raw(list_proxy, 0, word(&list_iid), word(&list_qi))) == S_OK); - EXPECT(list_qi == list_proxy); - EXPECT(release(list_qi) == 1); - - // 5. Queue slot 10 (ExecuteCommandLists) unwraps ListProxy in array - void* queue = nullptr; - D3D12_COMMAND_QUEUE_DESC qdesc{}; - const IID queue_iid = __uuidof(ID3D12CommandQueue); - EXPECT(hr_of(raw(device, 8, word(&qdesc), word(&queue_iid), word(&queue))) == S_OK); - EXPECT(xs::is_queue_proxy(queue)); - Mock* real_queue = reinterpret_cast(xs::queue_proxy_real_queue(queue)); - - Mock* unwrapped_list = new_mock(Kind::command_list); - void* lists_to_exec[2] = {unwrapped_list, list_proxy}; - raw(queue, 10, 2, word(lists_to_exec), 0, 0); - EXPECT(real_queue->calls[10] == 1); - EXPECT(real_queue->args[10][0] == 2); - EXPECT(real_queue->array[10][0] == word(unwrapped_list)); - EXPECT(real_queue->array[10][1] == word(real_list)); - - // 6. Test with list_level = 7 (supporting ID3D12GraphicsCommandList7, 81 slots) - mock_device->list_level = 7; - void* list7_proxy = nullptr; - EXPECT(hr_of(raw(device, 73, word(&desc), word(allocator), 0, word(&list_iid), word(&list7_proxy))) == S_OK); - EXPECT(xs::is_command_list_proxy(list7_proxy)); - Mock* real_list7 = reinterpret_cast(xs::command_list_proxy_real_list(list7_proxy)); - EXPECT(real_list7 != nullptr); - // Console slot 146 -> PC slot 80 (since 80 < 81 slots) - raw(list7_proxy, 146, 0x9999, 0, 0, 0); - EXPECT(real_list7->calls[80] == 1); - EXPECT(real_list7->args[80][0] == 0x9999); - EXPECT(release(list7_proxy) == 0 && real_list7->refs == 0); - - // Clean up - EXPECT(release(list_proxy) == 0 && real_list->refs == 0); - EXPECT(release(heap_proxy) == 0); - EXPECT(release(allocator) == 0 && real_allocator->refs == 0); - EXPECT(release(queue) == 0 && real_queue->refs == 0); - EXPECT(release(device) == 0 && mock_device->refs == 0); - - // 7. Verify stats reset - EXPECT(xs::list_slot_hits(32) > 0); - xs::reset_device_proxy_stats(); - EXPECT(xs::list_slot_hits(32) == 0); - EXPECT(!xs::list_slot_first_call_seen(32)); - - std::printf("%s: console command list routing, cursor pinning, queue unwrapping, and slot mapping passed\n", g_label); - return 0; -} - int main(int argc, char** argv) { no_dialogs(); std::setvbuf(stdout, nullptr, _IONBF, 0); From 35a925252127b61bdca2796c5d47e5e86de6ea44 Mon Sep 17 00:00:00 2001 From: Mumogg <104529023+Mumogg@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:59:52 -0600 Subject: [PATCH 26/27] rect_list_geometry: the tested fourth-corner rule is the default again; v1 + v3 - v2 is opt-in (LEONIDA_RECT_FOURTH=v1v3) d3d12_rect_list passes again. The other rule stays behind the switch as an open question: it is the one that covers the target for the retail title's full-screen rectangle draws. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01HxBQf4pXH8PWpC5oZsM4bt --- runtime/src/rect_list_geometry.h | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/runtime/src/rect_list_geometry.h b/runtime/src/rect_list_geometry.h index 1300c041ec..0049394cf4 100644 --- a/runtime/src/rect_list_geometry.h +++ b/runtime/src/rect_list_geometry.h @@ -169,9 +169,10 @@ inline std::vector rect_list_geometry(const std::vector rect_list_geometry(const std::vector Date: Mon, 23 Nov 2026 21:31:53 -0600 Subject: [PATCH 27/27] runtime: remove the local diagnostics and experiments; descriptor copies check their memory - The "[rt] localdbg:" lines and the experiment switches are gone: LEONIDA_RECT_GREEN, LEONIDA_RECT_VS, LEONIDA_RECT_NOGS, LEONIDA_RECT_NOCULL, LEONIDA_RECT_FORCE, LEONIDA_VTX_TEST and LEONIDA_DEBUG_CLEAR, with the hard-coded test shader words. vulkan_replay.h returns unresolved_resource directly again. - The descriptor write-through and the table mirror for title-backed heaps only copy between committed memory they may read and write. A handle that is only a number (xs_proxy_mock's heaps) is left alone; the test crashed there before. - A slot 70 view over memory no buffer holds becomes a raw buffer view only when the title-memory registry (title_va_alias.h) holds the whole range, instead of any address below 4 GiB. xs_proxy_mock's null-view case passes again. Still switches: LEONIDA_GRAPHICS_STAGE_LAYOUT, LEONIDA_DESC_MIRROR, LEONIDA_SLOT70_TITLE, LEONIDA_RECT_FOURTH. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01HxBQf4pXH8PWpC5oZsM4bt --- runtime/shims/d3d12_com.cpp | 11 -- runtime/shims/d3d12_vulkan_device.cpp | 108 +----------------- runtime/shims/d3d12_xs_device.cpp | 77 +++++-------- runtime/shims/xbox_present.cpp | 9 -- runtime/src/vulkan_replay.h | 157 +++++--------------------- 5 files changed, 65 insertions(+), 297 deletions(-) diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 89b87e004a..a1aa3ccc55 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -705,17 +705,6 @@ class GraphicsCommandList final d3d12_trace::record("ID3D12GraphicsCommandList::ClearRenderTargetView"); if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); if (!view.ptr || !color) return check(false); - // LOCAL DIAGNOSTIC: LEONIDA_DEBUG_CLEAR=1 clears to magenta; the first clears are logged. - static const bool magenta = [] { const char* v = std::getenv("LEONIDA_DEBUG_CLEAR"); return v && *v == '1'; }(); - const auto* target = reinterpret_cast(view.ptr); - static std::atomic shown{0}; - if (shown.fetch_add(1, std::memory_order_relaxed) < 6) - std::fprintf(stderr, "[rt] localdbg: clear resource=0x%llx colour=%g %g %g %g rects=%u\n", - static_cast(target->resource), color[0], color[1], color[2], color[3], count); - if (magenta) { - check(list_.clear_render_target(*target, {1.0f, 0.0f, 1.0f, 1.0f}, to_rects(count, rects))); - return; - } check(list_.clear_render_target(*reinterpret_cast(view.ptr), {color[0], color[1], color[2], color[3]}, to_rects(count, rects))); } diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index d82ba6f5d5..1a9f1d6e48 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -4142,18 +4142,6 @@ class PipelineState final stage.words = std::move(patched); } } - { // LOCAL EXPERIMENT: LEONIDA_RECT_GREEN=1 gives rectangle-list pipelines a solid green pixel stage, to - // tell "no fragments" from "the pixel shader writes nothing". - static const bool green = [] { const char* v = std::getenv("LEONIDA_RECT_GREEN"); return v && *v == '1'; }(); - static const bool trivial_vs = [] { const char* v = std::getenv("LEONIDA_RECT_VS"); return v && *v == '1'; }(); - if (trivial_vs && rect_list && stage.bit == VK_SHADER_STAGE_VERTEX_BIT) - stage.words = {0x7230203,0x10500,0x70000,0x1d,0x0,0x20011,0x1,0x3000e,0x0,0x1,0x7000f,0x0,0x1,0x6e69616d,0x0,0x2,0x3,0x40047,0x2,0xb,0x2a,0x40047,0x3,0xb,0x0,0x20013,0x4,0x30021,0x5,0x4,0x30016,0x6,0x20,0x40015,0x7,0x20,0x1,0x40017,0x8,0x6,0x4,0x40020,0x9,0x1,0x7,0x40020,0xa,0x3,0x8,0x4003b,0x9,0x2,0x1,0x4003b,0xa,0x3,0x3,0x4002b,0x7,0xb,0x1,0x4002b,0x7,0xc,0x2,0x4002b,0x6,0xd,0x0,0x4002b,0x6,0xe,0x3f800000,0x4002b,0x6,0xf,0x40800000,0x4002b,0x6,0x10,0xbf800000,0x50036,0x4,0x1,0x0,0x5,0x200f8,0x11,0x4003d,0x7,0x12,0x2,0x500c7,0x7,0x13,0x12,0xb,0x500c3,0x7,0x14,0x12,0xb,0x500c7,0x7,0x15,0x14,0xb,0x4006f,0x6,0x16,0x13,0x4006f,0x6,0x17,0x15,0x50085,0x6,0x18,0x16,0xf,0x50085,0x6,0x19,0x17,0xf,0x50081,0x6,0x1a,0x18,0x10,0x50081,0x6,0x1b,0x19,0x10,0x70050,0x8,0x1c,0x1a,0x1b,0xd,0xe,0x3003e,0x3,0x1c,0x100fd,0x10038}; - static const bool passthrough_vs = [] { const char* v = std::getenv("LEONIDA_RECT_VS"); return v && *v == '2'; }(); - if (passthrough_vs && rect_list && stage.bit == VK_SHADER_STAGE_VERTEX_BIT) - stage.words = {0x7230203,0x10500,0x70000,0x11,0x0,0x20011,0x1,0x3000e,0x0,0x1,0x7000f,0x0,0x1,0x6e69616d,0x0,0x2,0x3,0x40047,0x2,0x1e,0x0,0x40047,0x3,0xb,0x0,0x20013,0x4,0x30021,0x5,0x4,0x30016,0x6,0x20,0x40017,0x7,0x6,0x4,0x40020,0x8,0x1,0x7,0x40020,0x9,0x3,0x7,0x4003b,0x8,0x2,0x1,0x4003b,0x9,0x3,0x3,0x4002b,0x6,0xa,0x0,0x4002b,0x6,0xb,0x3f800000,0x50036,0x4,0x1,0x0,0x5,0x200f8,0xc,0x4003d,0x7,0xd,0x2,0x50051,0x6,0xe,0xd,0x0,0x50051,0x6,0xf,0xd,0x1,0x70050,0x7,0x10,0xe,0xf,0xa,0xb,0x3003e,0x3,0x10,0x100fd,0x10038}; - if (green && rect_list && stage.bit == VK_SHADER_STAGE_FRAGMENT_BIT) - stage.words = {0x7230203,0x10500,0x70000,0xc,0x0,0x20011,0x1,0x3000e,0x0,0x1,0x6000f,0x4,0x1,0x6e69616d,0x0,0x2,0x30010,0x1,0x7,0x40047,0x2,0x1e,0x0,0x20013,0x3,0x30021,0x4,0x3,0x30016,0x5,0x20,0x40017,0x6,0x5,0x4,0x40020,0x7,0x3,0x6,0x4003b,0x7,0x2,0x3,0x4002b,0x5,0x8,0x0,0x4002b,0x5,0x9,0x3f800000,0x7002c,0x6,0xa,0x8,0x9,0x8,0x9,0x50036,0x3,0x1,0x0,0x4,0x200f8,0xb,0x3003e,0x2,0xa,0x100fd,0x10038}; - } VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; module_info.codeSize = stage.words.size() * 4; module_info.pCode = stage.words.data(); @@ -4167,9 +4155,7 @@ class PipelineState final subgroup_size_for(*stage.entry, required_sizes[stage_infos.size()], info); stage_infos.push_back(info); } - // LOCAL EXPERIMENT: LEONIDA_RECT_NOGS=1 draws the rectangle list's three corners as a plain triangle. - static const bool local_no_gs = [] { const char* v = std::getenv("LEONIDA_RECT_NOGS"); return v && *v == '1'; }(); - if (rect_list && !local_no_gs) { // the stage that adds each rectangle's fourth corner, from the vertex shader's outputs + if (rect_list) { // the stage that adds each rectangle's fourth corner, from the vertex shader's outputs std::string why; const std::vector words = leonida::rect_list_geometry(vs_stage.words, why); if (words.empty()) { @@ -4230,16 +4216,6 @@ class PipelineState final if (e.system_value == 0 && e.semantic_index == element.SemanticIndex && equal_semantic(e.semantic, element.SemanticName)) input = &e; - { // LOCAL DIAGNOSTIC: the input layout of the first graphics pipelines with one - static std::atomic said{0}; - const std::string& vsn = stages[0].entry->name; - if ((vsn.find("Blit") != std::string::npos || vsn.find("sga_dr") != std::string::npos) && said.fetch_add(1) < 24) - std::fprintf(stderr, "[rt] localdbg: input element %u/%u %s%u dxgi=%d slot=%u offset=%u -> %s (vs %s)\n", i, - desc.InputLayout.NumElements, element.SemanticName ? element.SemanticName : "?", - element.SemanticIndex, int(element.Format), element.InputSlot, offset, - input ? ("location " + std::to_string(input->register_index)).c_str() : "not read", - stages[0].entry->name.c_str()); - } if (!input) continue; // the shader does not read this element attributes.push_back({input->register_index, element.InputSlot, format, offset}); const bool instance = element.InputSlotClass == D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA; @@ -4262,13 +4238,6 @@ class PipelineState final instance ? VK_VERTEX_INPUT_RATE_INSTANCE : VK_VERTEX_INPUT_RATE_VERTEX}); } } - { // LOCAL DIAGNOSTIC - static std::atomic said2{0}; - const std::string& vsn = stages[0].entry->name; - if (!mesh && (vsn.find("Blit") != std::string::npos || vsn.find("sga_dr") != std::string::npos) && said2.fetch_add(1) < 8) - std::fprintf(stderr, "[rt] localdbg: %s input layout elements=%u attributes=%zu signature=%zu\n", vsn.c_str(), - desc.InputLayout.NumElements, attributes.size(), stages[0].entry->input_signature.size()); - } for (const auto& e : stages[0].entry->input_signature) { if (e.system_value) continue; const bool fed = std::any_of(attributes.begin(), attributes.end(), @@ -4319,16 +4288,6 @@ class PipelineState final : VK_CULL_MODE_NONE; // With the negative-height viewport, framebuffer winding matches D3D12's screen-space winding. raster.frontFace = r.FrontCounterClockwise ? VK_FRONT_FACE_COUNTER_CLOCKWISE : VK_FRONT_FACE_CLOCKWISE; - // LOCAL EXPERIMENT: LEONIDA_RECT_NOCULL=1 draws rectangle lists without face culling (hypothesis: the - // console's rectangle primitive has no facing, so the PSO's cull mode does not apply to it). - if (rect_list) { - static const bool no_cull = [] { const char* v = std::getenv("LEONIDA_RECT_NOCULL"); return v && *v == '1'; }(); - static std::atomic said{0}; - if (said.fetch_add(1) < 4) - std::fprintf(stderr, "[rt] localdbg: rect-list pipeline cull=%u frontCCW=%d depthClip=%d no_cull=%d\n", - unsigned(r.CullMode), int(r.FrontCounterClockwise), int(r.DepthClipEnable), int(no_cull)); - if (no_cull) raster.cullMode = VK_CULL_MODE_NONE; - } // The D24-as-D32 pixel stage applies the bias itself, in D24 units (depth24_fragment above): the // rasterizer's bias stays off and zero, so its clamp needs no depthBiasClamp feature either. raster.depthBiasEnable = !depth24_fragment && (r.DepthBias || r.SlopeScaledDepthBias != 0.0f); @@ -4369,31 +4328,6 @@ class PipelineState final blends[i].dstAlphaBlendFactor = blend_factor(b.DestBlendAlpha); blends[i].alphaBlendOp = blend_op(b.BlendOpAlpha); blends[i].colorWriteMask = b.RenderTargetWriteMask & 0xf; // R, G, B, A in both APIs - if (rect_list) { // LOCAL DIAGNOSTIC / EXPERIMENT (LEONIDA_RECT_FORCE=1: opaque, no depth or stencil test) - static const bool force = [] { const char* v = std::getenv("LEONIDA_RECT_FORCE"); return v && *v == '1'; }(); - static std::atomic said{0}; - if (said.load() < 6) - for (const auto& st : stages) - if (st.entry) - std::fprintf(stderr, "[rt] localdbg: rect pipeline stage %s = %s wave64=%d emulated=%d push=%u\n", - st.entry->stage.c_str(), st.entry->name.c_str(), int(st.entry->wave64), - int(st.entry->emulated()), st.entry->push_constant_bytes); - if (said.fetch_add(1) < 6) - std::fprintf(stderr, "[rt] localdbg: rect pipeline rt%u/%u blend=%d src=%d dst=%d op=%d srcA=%d dstA=%d " - "mask=0x%x depth=%d write=%d func=%d stencil=%d samplemask=0x%x fmt=%d a2c=%d force=%d\n", - i, desc.NumRenderTargets, int(b.BlendEnable), int(b.SrcBlend), int(b.DestBlend), - int(b.BlendOp), int(b.SrcBlendAlpha), int(b.DestBlendAlpha), - unsigned(b.RenderTargetWriteMask), int(ds.DepthEnable), int(ds.DepthWriteMask), - int(ds.DepthFunc), int(ds.StencilEnable), unsigned(desc.SampleMask), - int(desc.RTVFormats[i]), int(desc.BlendState.AlphaToCoverageEnable), int(force)); - if (force) { - blends[i].blendEnable = VK_FALSE; - blends[i].colorWriteMask = 0xf; - depth.depthTestEnable = VK_FALSE; - depth.depthWriteEnable = VK_FALSE; - depth.stencilTestEnable = VK_FALSE; - } - } // B8G8R8X8 has no alpha, so blending reads destination alpha as 1 there (WARP and AMD's D3D12 driver), // where its BGRA8 Vulkan image would read the X byte. For colour SRC_ALPHA_SAT is min(As, 1 - Ad), so 0; // for alpha it is 1 in both APIs already. @@ -6099,10 +6033,7 @@ class Device final state_.context->set_heap_base(arena.address); state_.context->set_zero_page(arena.buffer, 0, kZeroPage); state_.context->set_quad_indices(arena.buffer, kZeroPage, kQuadIndexCount); - leonida::g_local_arena_mapped = arena.mapped; // LOCAL DIAGNOSTIC - std::fprintf(stderr, "[rt] localdbg: arena mapped at %p\n", static_cast(arena.mapped)); - leonida::g_local_arena_size = arena.size; - // LOCAL: vertex and index views that name the title's own CPU memory are copied into a ring carved from the + // Vertex and index views that name the title's own CPU memory are copied into a ring carved from the // arena at replay (not fence-tracked: the ring is large against a frame's few KiB of immediate geometry). state_.context->set_title_memory( [st = &state_](std::uint64_t va, std::uint64_t size, VkBuffer& buffer, VkDeviceSize& offset) { @@ -6110,16 +6041,6 @@ class Device final static std::mutex mutex; static VkDeviceSize ring_base = 0, ring_next = 0; static bool tried = false, logged = false; - static std::atomic dbg{0}; - if (dbg.fetch_add(1) < 6) { - MEMORY_BASIC_INFORMATION q{}; - const SIZE_T got = VirtualQuery(reinterpret_cast(va), &q, sizeof(q)); - std::fprintf(stderr, "[rt] localdbg: title_memory va=0x%llx size=0x%llx query=%zu state=0x%lx " - "protect=0x%lx type=0x%lx region=0x%llx mapped=%d\n", - static_cast(va), static_cast(size), - static_cast(got), q.State, q.Protect, q.Type, - static_cast(q.RegionSize), st->arena.mapped != nullptr); - } if (!va || !size || size > kRing / 4 || !st->arena.mapped) return false; // The whole range must be committed, readable host memory. for (std::uint64_t at = va; at < va + size;) { @@ -6139,35 +6060,12 @@ class Device final if (ring_next + aligned > kRing) ring_next = 0; std::memcpy(st->arena.mapped + ring_base + ring_next, reinterpret_cast(va), std::size_t(size)); - { // LOCAL EXPERIMENT: LEONIDA_VTX_TEST=1 overwrites the copy with a screen-covering triangle (stride 24) - static const char mode = [] { const char* v = std::getenv("LEONIDA_VTX_TEST"); return v ? *v : '0'; }(); - const float second_y = reinterpret_cast(st->arena.mapped + ring_base + ring_next)[7]; - const bool test = mode == '1' || (mode == 'A' && second_y < 100.f) || (mode == 'B' && second_y >= 100.f); - if (test && size >= 72) { - const float tri[3][2] = {{-1.f, -1.f}, {3.f, -1.f}, {-1.f, 3.f}}; - for (int v = 0; v < 3; ++v) { - float* q = reinterpret_cast(st->arena.mapped + ring_base + ring_next + v * 24); - q[0] = tri[v][0]; q[1] = tri[v][1]; q[2] = 0.f; - } - } - static std::atomic said{0}; - if (said.load() < 6) { - const float* q = reinterpret_cast(st->arena.mapped + ring_base + ring_next); - std::fprintf(stderr, "[rt] localdbg: ring copy holds %g,%g | %g,%g | %g,%g (size %llu)\n", q[0], q[1], - q[6], q[7], q[12], q[13], static_cast(size)); - } - if (said.fetch_add(1) < 3) - std::fprintf(stderr, "[rt] localdbg: ring copy at arena offset 0x%llx (ring_base 0x%llx) arena size 0x%llx\n", - static_cast(ring_base + ring_next), - static_cast(ring_base), - static_cast(st->arena.size)); - } buffer = st->arena.buffer; offset = ring_base + ring_next; ring_next += aligned; if (!logged) { logged = true; - std::fprintf(stderr, "[rt] d3d12: local: vertex/index views in title memory are copied into a " + std::fprintf(stderr, "[rt] d3d12: vertex/index views in title memory are copied into a " "%llu MiB ring (first: %llu bytes)\n", static_cast(kRing >> 20), static_cast(size)); } diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 09d753a86a..9bfa5ea7f4 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -24,6 +24,7 @@ // 78 SetFrameIntervalX, 79 ScheduleFrameEventX and 80 WaitFrameEventX. The slots can be moved with LEONIDA_XS_*_SLOT // for a trace that disagrees. The frame-event calls answer from a per-device token counter: there is no vblank source // behind the device before a presenter exists, so WaitFrameEventX returns at once with a fresh non-zero token. +#include "../src/title_va_alias.h" #include "title_window.h" #include "d3d12_xs_device.h" #include "d3d12_trace.h" @@ -166,9 +167,6 @@ bool register_descriptor_range(const DeviceProxy* device, const HeapProxy* heap, return false; try { std::lock_guard lock(descriptor_range_mutex()); - std::fprintf(stderr, "[rt] localdbg: descriptor range custom=0x%llx..0x%llx real_cpu=0x%llx heap=%p\n", - static_cast(custom_start), static_cast(custom_start + byte_size), - static_cast(real_start), static_cast(heap)); descriptor_ranges().push_back({custom_start, custom_start + byte_size, real_start, device, heap}); g_custom_range_count.store(descriptor_ranges().size(), std::memory_order_release); return true; @@ -216,10 +214,33 @@ bool local_desc_mirror() { return on; } +// Whether [address, address + bytes) is committed memory that can be read (and, with `write`, written). A handle +// that is only a number (a mock's, or a range the title has released) is left alone instead of faulting. +bool local_accessible(std::uint64_t address, std::uint64_t bytes, bool write) { + const std::uint64_t end = address + bytes; + if (!address || end < address) return false; + while (address < end) { + MEMORY_BASIC_INFORMATION info{}; + if (!VirtualQuery(reinterpret_cast(address), &info, sizeof(info)) || info.State != MEM_COMMIT) + return false; + const DWORD protect = info.Protect & 0xff; + if (info.Protect & PAGE_GUARD) return false; + const bool writable = protect == PAGE_READWRITE || protect == PAGE_WRITECOPY || + protect == PAGE_EXECUTE_READWRITE || protect == PAGE_EXECUTE_WRITECOPY; + const bool readable = writable || protect == PAGE_READONLY || protect == PAGE_EXECUTE_READ; + if (write ? !writable : !readable) return false; + address = reinterpret_cast(info.BaseAddress) + info.RegionSize; + } + return true; +} + void local_write_through(const DeviceProxy* device, D3D12_CPU_DESCRIPTOR_HANDLE custom, SIZE_T count) { if (!local_desc_mirror() || !custom.ptr || !count) return; const D3D12_CPU_DESCRIPTOR_HANDLE real = translate_cpu_handle(device, custom); if (real.ptr == custom.ptr) return; + if (!local_accessible(real.ptr, count * kLocalDescriptorBytes, false) || + !local_accessible(custom.ptr, count * kLocalDescriptorBytes, true)) + return; std::memcpy(reinterpret_cast(custom.ptr), reinterpret_cast(real.ptr), count * kLocalDescriptorBytes); static std::atomic said{false}; @@ -240,6 +261,9 @@ void local_mirror_table(const DeviceProxy* device, std::uint64_t gpu_handle) { if (!gpu_start || gpu_handle < gpu_start || gpu_handle >= gpu_start + bytes) continue; const std::uint64_t offset = (gpu_handle - gpu_start) / kLocalDescriptorBytes * kLocalDescriptorBytes; const std::uint64_t slots = (std::min)(kLocalMirrorSlots, (bytes - offset) / kLocalDescriptorBytes); + if (!local_accessible(range.custom_start + offset, slots * kLocalDescriptorBytes, false) || + !local_accessible(range.real_start + offset, slots * kLocalDescriptorBytes, true)) + return; std::uint64_t copied = 0; for (std::uint64_t i = 0; i < slots; ++i) { const auto* from = reinterpret_cast(range.custom_start + offset + i * kLocalDescriptorBytes); @@ -740,22 +764,12 @@ D3D12_CPU_DESCRIPTOR_HANDLE heap_get_cpu_handle(HeapProxy* self) { D3D12_GPU_DESCRIPTOR_HANDLE heap_get_gpu_handle(HeapProxy* self) { note_heap_slot(10); - { - static std::atomic said{0}; - if (said.fetch_add(1) < 8) std::fprintf(stderr, "[rt] localdbg: heap slot 10 (GPU handle) asked on heap %p\n", static_cast(self)); - } constexpr UINT64 kUnset = ~static_cast(0); D3D12_GPU_DESCRIPTOR_HANDLE handle{}; handle.ptr = kUnset; using Fn = D3D12_GPU_DESCRIPTOR_HANDLE(WINAPI*)(ID3D12DescriptorHeap*, D3D12_GPU_DESCRIPTOR_HANDLE*); const D3D12_GPU_DESCRIPTOR_HANDLE returned = reinterpret_cast(self->real_vtable[10])(self->real, &handle); - { - static std::atomic said{0}; - if (said.fetch_add(1) < 4) - std::fprintf(stderr, "[rt] localdbg: heap %p slot 10 answers GPU handle 0x%llx\n", static_cast(self), - static_cast(handle.ptr != kUnset ? handle.ptr : returned.ptr)); - } return handle.ptr != kUnset ? handle : returned; } @@ -2538,12 +2552,6 @@ void proxy_create_srv_from_raw_x(DeviceProxy* self, std::uint64_t texture_words, std::uint64_t custom; ~LocalWriteThrough() { local_write_through(self, D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(custom)}, 1); } } local_write_back{self, destination}; - { - static std::atomic calls{0}; - const int n = calls.fetch_add(1); - if (n < 4 || n % 5000 == 0) - std::fprintf(stderr, "[rt] localdbg: slot 70 call #%d dest=0x%llx\n", n, static_cast(destination)); - } // The console hands a CPU descriptor handle in the title's heap memory; #7021 translates it to the real heap's. destination = translate_cpu_handle(self, D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(destination)}).ptr; @@ -2561,7 +2569,10 @@ void proxy_create_srv_from_raw_x(DeviceProxy* self, std::uint64_t texture_words, // LOCAL: a small raw view over the title's own memory becomes a raw buffer V# through the constant-view path, // which resolves a title address to its GPU copy (#9137). LEONIDA_SLOT70_TITLE=0 keeps the null view. static const bool title_views = [] { const char* v = std::getenv("LEONIDA_SLOT70_TITLE"); return !(v && *v == '0'); }(); - if (title_views && shape.va && shape.va < 0x100000000ull && shape.resource.Width && shape.resource.Width <= 65536) { + std::uint64_t title_lo = 0, title_hi = 0; + if (title_views && shape.resource.Width && shape.resource.Width <= 65536 && + leonida::title_va_aliases().title_memory(shape.va, title_lo, title_hi) && + shape.resource.Width <= title_hi - shape.va) { D3D12_CONSTANT_BUFFER_VIEW_DESC constants{}; constants.BufferLocation = shape.va; constants.SizeInBytes = static_cast(shape.resource.Width); @@ -2573,13 +2584,6 @@ void proxy_create_srv_from_raw_x(DeviceProxy* self, std::uint64_t texture_words, return; } log_slot70_null_once("no buffer holds the address", texture_words, view_desc); - { - static std::atomic nulls{0}; - const int n = nulls.fetch_add(1); - if (n < 3 || n % 5000 == 0) - std::fprintf(stderr, "[rt] localdbg: slot 70 null #%d: no buffer holds va=0x%llx width=%llu\n", n, - static_cast(shape.va), static_cast(shape.resource.Width)); - } write_null_srv(self, destination); return; } @@ -2783,25 +2787,6 @@ HRESULT proxy_create_descriptor_heap(DeviceProxy* self, const D3D12_DESCRIPTOR_H void proxy_create_cbv(DeviceProxy* self, const D3D12_CONSTANT_BUFFER_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE dest) { note_slot(17); - { // LOCAL DIAGNOSTIC - static std::atomic said{0}; - const int n = said.fetch_add(1); - if (n < 6 || (n > 3000 && n < 3008)) { - const D3D12_CPU_DESCRIPTOR_HANDLE t = translate_cpu_handle(self, dest); - std::fprintf(stderr, "[rt] localdbg: CreateCBV #%d dest=0x%llx -> 0x%llx location=0x%llx size=%u\n", n, - static_cast(dest.ptr), static_cast(t.ptr), - desc ? static_cast(desc->BufferLocation) : 0ull, desc ? desc->SizeInBytes : 0u); - MEMORY_BASIC_INFORMATION q{}; - if (desc && desc->BufferLocation && desc->BufferLocation < 0x100000000ull && - VirtualQuery(reinterpret_cast(desc->BufferLocation), &q, sizeof(q)) && q.State == MEM_COMMIT && - !(q.Protect & (PAGE_NOACCESS | PAGE_GUARD))) { - const float* f = reinterpret_cast(desc->BufferLocation); - std::fprintf(stderr, "[rt] localdbg: constants now:"); - for (int w = 0; w < 24 && w * 4u < desc->SizeInBytes; ++w) std::fprintf(stderr, " %g", f[w]); - std::fprintf(stderr, "\n"); - } - } - } self->real->CreateConstantBufferView(desc, translate_cpu_handle(self, dest)); local_write_through(self, dest, 1); } diff --git a/runtime/shims/xbox_present.cpp b/runtime/shims/xbox_present.cpp index 56299afe27..6fbed007d4 100644 --- a/runtime/shims/xbox_present.cpp +++ b/runtime/shims/xbox_present.cpp @@ -154,15 +154,6 @@ HRESULT XboxPresentation::present_x(UINT plane_count, const XboxPresentPlanePara return result; } - { // LOCAL DIAGNOSTIC: what the first presents show - static std::atomic shown{0}; - if (shown.fetch_add(1, std::memory_order_relaxed) < 8) - for (UINT i = 0; i < plane_count; ++i) - std::fprintf(stderr, "[rt] localdbg: PresentX plane %u/%u resource=%p count=%u src=%p dest=%p cs=%d flags=0x%x\n", - i, plane_count, planes[i].ppResources ? static_cast(planes[i].ppResources[0]) : nullptr, - planes[i].ResourceCount, static_cast(planes[i].pSrcViewRects), - static_cast(planes[i].pDestPlacementBase), planes[i].ColorSpace, planes[i].Flags); - } // All planes carry the token of one frame. const std::uint64_t token = planes[0].Token; for (UINT i = 0; i < plane_count; ++i) { diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index a531c9e72f..cdc6b5bfe8 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -809,20 +809,6 @@ enum class ReplayResult { invalid_draw, // DispatchMesh with a pipeline that has no mesh shader, or a vertex draw with one that has unsupported }; -// LOCAL DIAGNOSTIC: the arena's host mapping and size, for dumps of what a shader would read. -inline std::uint8_t* g_local_arena_mapped = nullptr; -inline std::uint64_t g_local_arena_size = 0; -inline std::atomic g_local_last_cb96{0}; // title address of the last 96-byte constant view created - -// LOCAL DIAGNOSTIC: which check returned unresolved_resource (first 3 times per source line). -inline ReplayResult local_unresolved_at(int line) { - static std::atomic seen[8192]; - if (line >= 0 && line < 8192 && seen[line].fetch_add(1, std::memory_order_relaxed) < 3) - std::fprintf(stderr, "[rt] localdbg: unresolved_resource at vulkan_replay.h:%d\n", line); - return ReplayResult::unresolved_resource; -} - - struct ReplayFunctions { // Set 0 for the pipelines that declare one (their own `bindless_set` is only the marker): the device's current // generation of it, which a flush may have replaced since the pipeline was made. Null: the pipeline's. @@ -882,7 +868,7 @@ struct ReplayFunctions { // cut to what the buffer holds from there: vertex and index views use what fits, WriteBufferImmediate needs all // of it. std::function buffer_at; - // LOCAL: a vertex or index view whose VA is the title's own CPU memory, not a registered buffer (on the console + // A vertex or index view whose VA is the title's own CPU memory, not a registered buffer (on the console // the GPU reads title memory directly). Copies [va, va + size) into a GPU-visible ring and names the copy; false // when the range is not readable host memory. std::function title_memory; @@ -2131,7 +2117,7 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct !vk.draw_indexed || !vk.bind_pipeline || !vk.push_constants) return ReplayResult::unsupported; const GraphicsPipeline* pipeline = vk.graphics_pipeline(draw.pipeline); - if (!pipeline || !pipeline->pipeline) return local_unresolved_at(__LINE__); + if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; if (pipeline->mesh != draw.mesh) return ReplayResult::invalid_draw; if (draw.mesh && !vk.draw_mesh_tasks) return ReplayResult::unsupported; if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; @@ -2152,7 +2138,7 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct const TargetView& target = draw.views->render_targets[slot]; if (!target.resource) continue; const ResourceBinding* binding = resolve(target.resource); - if (!binding) return local_unresolved_at(__LINE__); + if (!binding) return ReplayResult::unresolved_resource; auto& a = p.colors[slot]; a.binding = *binding; a.id = target.resource; @@ -2169,7 +2155,7 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct } if (draw.depth.resource && pipeline->depth_format != VK_FORMAT_UNDEFINED) { const ResourceBinding* binding = resolve(draw.depth.resource); - if (!binding) return local_unresolved_at(__LINE__); + if (!binding) return ReplayResult::unresolved_resource; auto& a = p.depth; a.binding = *binding; a.id = draw.depth.resource; @@ -2210,7 +2196,7 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct const bool bound = draw.views && slot < draw.views->vertex_buffers.size() && draw.views->vertex_buffers[slot].va; if (!bound) { - if (!vk.zero_buffer) return local_unresolved_at(__LINE__); + if (!vk.zero_buffer) return ReplayResult::unresolved_resource; p.vertex_buffers[slot] = vk.zero_buffer; p.vertex_offsets[slot] = vk.zero_offset; p.vertex_sizes[slot] = vk.zero_size; @@ -2222,101 +2208,20 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct if (!vk.buffer_at(view.va, size, p.vertex_buffers[slot], p.vertex_offsets[slot])) { size = view.size; if (!vk.title_memory || !vk.title_memory(view.va, size, p.vertex_buffers[slot], p.vertex_offsets[slot])) - return local_unresolved_at(__LINE__); - { // LOCAL DIAGNOSTIC: the first draws that read title memory - static std::atomic shown{0}; - const int nth = shown.fetch_add(1, std::memory_order_relaxed); - if (nth < 12 || (nth % 20000) < 3) { - const float* f = reinterpret_cast(view.va); - std::fprintf(stderr, "[rt] localdbg: draw slot=%u topology=%u count=%u instances=%u first=%u stride=%u " - "bytes=%llu viewport=%.0f,%.0f %.0fx%.0f depth %.2f..%.2f\n", slot, draw.topology, - draw.count, draw.instances, draw.first, view.stride, - static_cast(view.size), draw.viewport.x, draw.viewport.y, - draw.viewport.width, draw.viewport.height, draw.viewport.min_depth, draw.viewport.max_depth); - for (std::uint32_t t = 0; draw.views && t < draw.views->render_target_count; ++t) - std::fprintf(stderr, "[rt] localdbg: target %u resource=0x%llx mip=%u pipeline=0x%llx depth=0x%llx " - "scissor=%d,%d..%d,%d\n", t, - static_cast(draw.views->render_targets[t].resource), - draw.views->render_targets[t].mip, static_cast(draw.pipeline), - static_cast(draw.depth.resource), draw.scissor.left, - draw.scissor.top, draw.scissor.right, draw.scissor.bottom); - std::fprintf(stderr, "[rt] localdbg: heap_base=0x%llx user_data:", static_cast(vk.heap_base)); - for (int w = 0; w < 16; ++w) std::fprintf(stderr, " %08x", draw.user_data[w]); - std::fprintf(stderr, "\n"); - for (int w = 0; w < 16; ++w) { // which root words name a registered buffer - std::uint64_t room = 1; VkBuffer bb = VK_NULL_HANDLE; VkDeviceSize bo = 0; - if (draw.user_data[w] && vk.buffer_at(draw.user_data[w], room, bb, bo)) - std::fprintf(stderr, "[rt] localdbg: user_data[%d] is a registered buffer VA\n", w); - } - const std::uint32_t local_table = draw.user_data[0] ? draw.user_data[0] : draw.user_data[8]; - if (g_local_arena_mapped && local_table && local_table + 256ull <= g_local_arena_size) { - const std::uint32_t* t = reinterpret_cast(g_local_arena_mapped + local_table); - for (int e = 0; e < 4; ++e) { - std::fprintf(stderr, "[rt] localdbg: table[%d]:", e); - for (int w = 0; w < 8; ++w) std::fprintf(stderr, " %08x", t[e * 8 + w]); - std::fprintf(stderr, "\n"); - const std::uint64_t va = (std::uint64_t(t[e * 8 + 1] & 0xffff) << 32) | t[e * 8]; - if (va && va + 128 <= g_local_arena_size) { - const float* f2 = reinterpret_cast(g_local_arena_mapped + va); - std::fprintf(stderr, "[rt] localdbg: at va 0x%llx:", static_cast(va)); - for (int w = 0; w < 32; ++w) std::fprintf(stderr, " %g", f2[w]); - std::fprintf(stderr, "\n"); - } - } - } - { // the same table read from the title's memory, taking the high dword from the vertex view's VA - const std::uint64_t guess = (view.va & 0xffffffff00000000ull) | draw.user_data[0]; - std::fprintf(stderr, "[rt] localdbg: vertex va=0x%llx table guess=0x%llx delta=%lld\n", - static_cast(view.va), static_cast(guess), - static_cast(view.va - guess)); - std::uint64_t probe = 256; VkBuffer pb = VK_NULL_HANDLE; VkDeviceSize po = 0; - if (draw.user_data[0] && vk.title_memory && vk.title_memory(guess, probe, pb, po)) { - const std::uint32_t* t = reinterpret_cast(guess); - for (int e = 0; e < 3; ++e) { - std::fprintf(stderr, "[rt] localdbg: title table[%d]:", e); - for (int w = 0; w < 8; ++w) std::fprintf(stderr, " %08x", t[e * 8 + w]); - std::fprintf(stderr, "\n"); - } - } else { - std::fprintf(stderr, "[rt] localdbg: title table guess is not readable title memory\n"); - } - } - if (const std::uint64_t cb = g_local_last_cb96.load()) { - const float* f3 = reinterpret_cast(cb); - std::fprintf(stderr, "[rt] localdbg: 96-byte constants in title memory at draw time:"); - for (int w = 0; w < 24; ++w) std::fprintf(stderr, " %g", f3[w]); - std::fprintf(stderr, "\n"); - } - { // what sits just before the vertices in the title's ring - const std::uint32_t* t = reinterpret_cast(view.va - 0x60); - for (int e = 0; e < 3; ++e) { - std::fprintf(stderr, "[rt] localdbg: before vertices[-0x%x]:", 0x60 - e * 0x20); - for (int w = 0; w < 8; ++w) std::fprintf(stderr, " %08x", t[e * 8 + w]); - std::fprintf(stderr, "\n"); - } - } - const std::uint32_t words = view.stride / 4 ? view.stride / 4 : 1; - for (std::uint32_t v = 0; v < 4 && (draw.first + v + 1) * view.stride <= view.size; ++v) { - const float* q = f + (draw.first + v) * words; - std::fprintf(stderr, "[rt] localdbg: v%u = %g %g %g %g %g %g\n", v, q[0], q[1], - words > 2 ? q[2] : 0.f, words > 3 ? q[3] : 0.f, words > 4 ? q[4] : 0.f, - words > 5 ? q[5] : 0.f); - } - } - } + return ReplayResult::unresolved_resource; } p.vertex_sizes[slot] = size; p.vertex_strides[slot] = (pipeline->zero_step_slots & (1u << slot)) ? 0 : view.stride; } // A non-indexed quad list is drawn from the shared triangle index buffer (emit). if (!draw.indexed && !draw.mesh && draw.topology == topology_quad_list && !vk.quad_indices) - return local_unresolved_at(__LINE__); + return ReplayResult::unresolved_resource; if (draw.indexed) { if (draw.index.format == 57) p.index_type = VK_INDEX_TYPE_UINT16; else if (draw.index.format == 42) p.index_type = VK_INDEX_TYPE_UINT32; else if (draw.index.va) return ReplayResult::unsupported; if (!draw.index.va) { // no index buffer: every index reads 0 - if (!vk.zero_buffer) return local_unresolved_at(__LINE__); + if (!vk.zero_buffer) return ReplayResult::unresolved_resource; p.index_buffer = vk.zero_buffer; p.index_offset = vk.zero_offset; } else { @@ -2324,7 +2229,7 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct if (!vk.buffer_at(draw.index.va, size, p.index_buffer, p.index_offset)) { size = draw.index.size; if (!vk.title_memory || !vk.title_memory(draw.index.va, size, p.index_buffer, p.index_offset)) - return local_unresolved_at(__LINE__); + return ReplayResult::unresolved_resource; } } } @@ -2746,7 +2651,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun }; if (const auto* transition = std::get_if(&command)) { - if (!bind(transition->resource)) return local_unresolved_at(__LINE__); + if (!bind(transition->resource)) return ReplayResult::unresolved_resource; if (p.binding.image == VK_NULL_HANDLE) { if (transition->subresource != 0 && transition->subresource != all_subresources) return ReplayResult::invalid_subresource; @@ -2756,14 +2661,14 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun } else if (std::holds_alternative(command) || std::holds_alternative(command)) { if (!vk.pipeline_barrier2) return ReplayResult::unsupported; if (const auto* buffer_barrier = std::get_if(&command)) - if (!bind(buffer_barrier->resource)) return local_unresolved_at(__LINE__); + if (!bind(buffer_barrier->resource)) return ReplayResult::unresolved_resource; } else if (const auto* texture = std::get_if(&command)) { if (!vk.pipeline_barrier2) return ReplayResult::unsupported; - if (!bind(texture->resource)) return local_unresolved_at(__LINE__); + if (!bind(texture->resource)) return ReplayResult::unresolved_resource; if (!p.binding.image || !barrier_range(p.binding, texture->range, p.range)) return ReplayResult::invalid_subresource; } else if (const auto* color_clear = std::get_if(&command)) { - if (!bind(color_clear->target.resource)) return local_unresolved_at(__LINE__); + if (!bind(color_clear->target.resource)) return ReplayResult::unresolved_resource; if (!p.binding.image || p.binding.aspects != VK_IMAGE_ASPECT_COLOR_BIT) return ReplayResult::invalid_clear; if (!detail::view_range(p.binding, color_clear->target, VK_IMAGE_ASPECT_COLOR_BIT, p.range)) return ReplayResult::invalid_subresource; @@ -2785,7 +2690,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun r != ReplayResult::success) return r; if (!p.skip && p.rects.empty() && !vk.clear_color_image) return ReplayResult::unsupported; } else if (const auto* depth_clear = std::get_if(&command)) { - if (!bind(depth_clear->target.resource)) return local_unresolved_at(__LINE__); + if (!bind(depth_clear->target.resource)) return ReplayResult::unresolved_resource; VkImageAspectFlags aspects = 0; if (depth_clear->flags & clear_depth) aspects |= VK_IMAGE_ASPECT_DEPTH_BIT; if (depth_clear->flags & clear_stencil) aspects |= VK_IMAGE_ASPECT_STENCIL_BIT; @@ -2805,7 +2710,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!p.skip && p.rects.empty() && !vk.clear_depth_stencil_image) return ReplayResult::unsupported; } else if (const auto* uav = std::get_if(&command)) { const UavView& view = uav->view; - if (!bind(view.resource)) return local_unresolved_at(__LINE__); + if (!bind(view.resource)) return ReplayResult::unresolved_resource; if (view.buffer) { if (!vk.fill_buffer || !vk.update_buffer || !vk.copy_buffer) return ReplayResult::unsupported; if (predicated) ++out.unpredicated_copies; // fills and copies are transfer commands @@ -2865,7 +2770,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (predicated && !std::holds_alternative(command)) ++out.unpredicated_copies; const auto [dst_id, src_id] = copy_ids(command); const ResourceBinding* source = resolve(src_id); - if (!bind(dst_id) || !source) return local_unresolved_at(__LINE__); + if (!bind(dst_id) || !source) return ReplayResult::unresolved_resource; p.source = *source; ReplayResult result = ReplayResult::success; if (const auto* buffer_copy = std::get_if(&command)) { @@ -2998,7 +2903,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!vk.resolve_image) return ReplayResult::unsupported; if (predicated) ++out.unpredicated_copies; // a transfer command, like the copies const ResourceBinding* source = resolve(resolve_command->src); - if (!bind(resolve_command->dst) || !source) return local_unresolved_at(__LINE__); + if (!bind(resolve_command->dst) || !source) return ReplayResult::unresolved_resource; p.source = *source; if (const auto result = detail::prepare_resolve(*resolve_command, p); result != ReplayResult::success) return result; @@ -3029,7 +2934,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun } } else if (const auto* discard = std::get_if(&command)) { // Buffers and partial (rectangle) discards keep their contents, which "undefined" allows. - if (!bind(discard->resource)) return local_unresolved_at(__LINE__); + if (!bind(discard->resource)) return ReplayResult::unresolved_resource; const std::uint64_t end = std::uint64_t(discard->first_subresource) + discard->count; if (!p.binding.image) { if (!discard->whole && end > 1) return ReplayResult::invalid_subresource; @@ -3049,7 +2954,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!vk.update_buffer || !vk.buffer_at) return ReplayResult::unsupported; std::uint64_t bytes = 4; if (!vk.buffer_at(write->address, bytes, p.write_buffer, p.write_offset) || bytes < 4) - return local_unresolved_at(__LINE__); + return ReplayResult::unresolved_resource; if (p.write_offset % 4) return ReplayResult::invalid_copy; // WriteBufferImmediate resolves by VA and may target a readback buffer in COPY_DEST. out.wrote_readback = true; @@ -3058,14 +2963,14 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!vk.copy_buffer) return ReplayResult::unsupported; if (predicated) ++out.unpredicated_copies; // a transfer command, like the copies const ResourceBinding* source = resolve(atomic->src); - if (!bind(atomic->dst) || !source) return local_unresolved_at(__LINE__); + if (!bind(atomic->dst) || !source) return ReplayResult::unresolved_resource; p.source = *source; if (!p.binding.buffer || !p.source.buffer || !detail::within(atomic->dst_offset, atomic->bytes, p.binding.size) || !detail::within(atomic->src_offset, atomic->bytes, p.source.size)) return ReplayResult::invalid_copy; for (const auto& d : atomic->dependencies) { const ResourceBinding* dependent = resolve(d.resource); - if (!dependent) return local_unresolved_at(__LINE__); + if (!dependent) return ReplayResult::unresolved_resource; if (!dependent->image) { const std::uint64_t end = d.end == UINT64_MAX ? dependent->size : d.end; if (d.subresource != 0 || d.begin >= end || end > dependent->size) @@ -3084,7 +2989,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!conditional) return ReplayResult::unsupported; // Without physical segments the capture dispatch would pollute CSInvocations. if (statistics_active && !statistics_helpers) return ReplayResult::unsupported; - if (!bind(predication->buffer)) return local_unresolved_at(__LINE__); + if (!bind(predication->buffer)) return ReplayResult::unresolved_resource; if (!p.binding.buffer || !detail::within(predication->offset, 8, p.binding.size) || predication->offset > UINT64_MAX - p.binding.buffer_offset) return ReplayResult::invalid_predication; @@ -3096,7 +3001,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun // not suppress them (emit_query suspends conditional rendering around ResolveQueryData). if (!queries) return ReplayResult::unsupported; QueryPool* heap = vk.query_pool(range.heap); - if (!heap) return local_unresolved_at(__LINE__); + if (!heap) return ReplayResult::unresolved_resource; if (!query_fits_heap(heap->heap_type, range.type)) return ReplayResult::invalid_query; if (range.first >= heap->count || range.count > heap->count - range.first) return ReplayResult::invalid_query; @@ -3119,7 +3024,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun } if (const auto* resolve_queries = std::get_if(&command)) { // The destination is a buffer, as D3D12 requires, large enough for every result. - if (!bind(resolve_queries->dst)) return local_unresolved_at(__LINE__); + if (!bind(resolve_queries->dst)) return ReplayResult::unresolved_resource; const std::uint64_t bytes = std::uint64_t(range.count) * query_result_size(range.type); if (!p.binding.buffer || p.binding.buffer_offset % 8 || !detail::within(resolve_queries->offset, bytes, p.binding.size) || @@ -3137,7 +3042,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun } out.queries.push_back({i, heap, statistics_active}); } else if (const auto* ind = std::get_if(&command)) { - if (!bind(ind->argument_buffer) || !p.binding.buffer) return local_unresolved_at(__LINE__); + if (!bind(ind->argument_buffer) || !p.binding.buffer) return ReplayResult::unresolved_resource; const VkDeviceSize record_size = detail::indirect_record_size(ind->kind); if (!record_size || ind->stride < record_size || ind->stride % sizeof(std::uint32_t)) return ReplayResult::invalid_indirect_arguments; @@ -3151,7 +3056,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun return ReplayResult::invalid_indirect_arguments; if (ind->count_buffer) { const ResourceBinding* cnt = resolve(ind->count_buffer); - if (!cnt || !cnt->buffer) return local_unresolved_at(__LINE__); + if (!cnt || !cnt->buffer) return ReplayResult::unresolved_resource; if (!detail::indirect_range(*cnt, ind->count_offset, sizeof(std::uint32_t))) return ReplayResult::invalid_indirect_arguments; p.source = *cnt; @@ -3177,7 +3082,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (ind->kind == IndirectKind::dispatch && ind->pipeline) { // the pipeline and root arguments it was recorded if (!vk.bind_pipeline || !vk.push_constants || !vk.compute_pipeline) return ReplayResult::unsupported; const ComputePipeline* pipeline = vk.compute_pipeline(ind->pipeline); - if (!pipeline || !pipeline->pipeline) return local_unresolved_at(__LINE__); + if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; p.pipeline = *pipeline; } @@ -3189,10 +3094,10 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!vk.build_acceleration_structures || !vk.resolve_acceleration_structure) return ReplayResult::unsupported; p.accel_dst = vk.resolve_acceleration_structure(build->dst_va); - if (!p.accel_dst) return local_unresolved_at(__LINE__); + if (!p.accel_dst) return ReplayResult::unresolved_resource; if (build->update && build->src_va) { p.accel_src = vk.resolve_acceleration_structure(build->src_va); - if (!p.accel_src) return local_unresolved_at(__LINE__); + if (!p.accel_src) return ReplayResult::unresolved_resource; } if (build->is_tlas && build->instance_pointers && build->instance_count) { if (!vk.prepare_khr_instances || !vk.host_at || !vk.buffer_at) return ReplayResult::unsupported; @@ -3226,7 +3131,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun std::uint64_t room = 8 * info->sources.size(); VkBuffer buffer = VK_NULL_HANDLE; VkDeviceSize offset = 0; - if (!vk.buffer_at(info->dest_va, room, buffer, offset)) return local_unresolved_at(__LINE__); + if (!vk.buffer_at(info->dest_va, room, buffer, offset)) return ReplayResult::unresolved_resource; if (room < 8 * info->sources.size()) return ReplayResult::invalid_copy; } else if (info->type == 0 && vk.write_acceleration_structures_properties && vk.resolve_acceleration_structure && vk.reset_query_pool && vk.copy_query_pool_results && @@ -3265,7 +3170,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!vk.bind_pipeline || !vk.push_constants || !vk.dispatch || !vk.compute_pipeline) return ReplayResult::unsupported; const ComputePipeline* pipeline = vk.compute_pipeline(dispatch->pipeline); - if (!pipeline || !pipeline->pipeline) return local_unresolved_at(__LINE__); + if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; p.pipeline = *pipeline; } else if (const auto* draw = std::get_if(&command)) {