upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime/shims/d3d12_com.cpp
diff options
context:
space:
mode:
authoraslan2142 <jan.trencansky@protonmail.com>2026-11-25 02:37:19 +0100
committerGitHub <noreply@github.com>2026-11-25 02:37:19 +0100
commit18a22c1aefa227fd2eda047bab3385147d569f9d (patch)
tree74ad707a670f980da61b5b9e0bc9241dfd6ef181 /runtime/shims/d3d12_com.cpp
parent5a5df8e0b6bff458814c934e18f4216e69c40d36 (diff)
parent71a783e56fb6eb591849b5c9fb6618ed3af3f595 (diff)
Merge pull request #984 from Moriz82/integration/proton-story-load
[integration] Linux/Proton and native Windows: boot through the story load (RT-PROTON-STORY-LOAD)
Diffstat (limited to 'runtime/shims/d3d12_com.cpp')
-rw-r--r--runtime/shims/d3d12_com.cpp396
1 files changed, 362 insertions, 34 deletions
diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp
index 3adb31549..f84465564 100644
--- a/runtime/shims/d3d12_com.cpp
+++ b/runtime/shims/d3d12_com.cpp
@@ -6,20 +6,27 @@
6#include "d3d12_trace.h" 6#include "d3d12_trace.h"
7#include "d3d12_xs_device.h" 7#include "d3d12_xs_device.h"
8#include "../src/gfx10_descriptors.h" 8#include "../src/gfx10_descriptors.h"
9#include "../src/title_va_alias.h"
10#include "../src/fsdraw_probe.h" // LOCAL DIAGNOSTIC
11#include "../src/local_diagnostics.h"
9 12
10#include <algorithm> 13#include <algorithm>
11#include <array> 14#include <array>
12#include <atomic> 15#include <atomic>
13#include <bit> 16#include <bit>
17#include <chrono>
14#include <condition_variable> 18#include <condition_variable>
15#include <functional> 19#include <functional>
20#include <map>
16#include <memory> 21#include <memory>
17#include <optional> 22#include <optional>
18#include <cstdio> 23#include <cstdio>
19#include <cstring> 24#include <cstring>
20#include <mutex> 25#include <mutex>
21#include <set> 26#include <set>
27#include <source_location>
22#include <string> 28#include <string>
29#include <string_view>
23#include <thread> 30#include <thread>
24#include <utility> 31#include <utility>
25#include <vector> 32#include <vector>
@@ -198,6 +205,8 @@ public:
198 } 205 }
199 206
200 const leonida::CommandList& commands() const { return list_; } 207 const leonida::CommandList& commands() const { return list_; }
208 // The descriptor tables this recording binds (console VAs), for the scan before a submission.
209 const std::vector<std::pair<std::uint64_t, std::uint32_t>>& tables() const { return tables_; }
201 // The pipeline states and root signatures the recording names (it holds a reference to each until Reset). 210 // The pipeline states and root signatures the recording names (it holds a reference to each until Reset).
202 const std::vector<IUnknown*>& pinned() const { return held_; } 211 const std::vector<IUnknown*>& pinned() const { return held_; }
203 UINT front_stencil_ref() const { return front_stencil_ref_; } 212 UINT front_stencil_ref() const { return front_stencil_ref_; }
@@ -234,6 +243,7 @@ public:
234 record_into(command_allocator); 243 record_into(command_allocator);
235 invalid_ = false; 244 invalid_ = false;
236 calls_.clear(); 245 calls_.clear();
246 tables_.clear();
237 release_held(); // what the old recording used: it was replayed at ExecuteCommandLists 247 release_held(); // what the old recording used: it was replayed at ExecuteCommandLists
238 reset_state(state); // Reset returns every list state to its default 248 reset_state(state); // Reset returns every list state to its default
239 if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) set_initial_pipeline(state); // reset_state holds it 249 if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) set_initial_pipeline(state); // reset_state holds it
@@ -509,7 +519,7 @@ public:
509 if (x > 65535 || y > 65535 || z > 65535 || std::uint64_t(x) * y * z > (1u << 22)) return check(false); 519 if (x > 65535 || y > 65535 || z > 65535 || std::uint64_t(x) * y * z > (1u << 22)) return check(false);
510 if (!graphics_pipeline_ || !graphics_.layout) return check(false); 520 if (!graphics_pipeline_ || !graphics_.layout) return check(false);
511 if (!any_nonempty_viewport()) return; // as record_draw: nothing is rasterized 521 if (!any_nonempty_viewport()) return; // as record_draw: nothing is rasterized
512 leonida::Draw draw{graphics_pipeline_, graphics_.data, draw_views(), depth_, {}, 0, viewport_, 522 leonida::Draw draw{graphics_pipeline_, graphics_user_data(), draw_views(), depth_, {}, 0, viewport_,
513 scissor_, blend_factor_, front_stencil_ref_, back_stencil_ref_, false, x, y, z, 0, 0}; 523 scissor_, blend_factor_, front_stencil_ref_, back_stencil_ref_, false, x, y, z, 0, 0};
514 draw.mesh = true; 524 draw.mesh = true;
515 draw.viewports = draw_viewports(); 525 draw.viewports = draw_viewports();
@@ -549,29 +559,49 @@ public:
549 switch (group[g].Type) { 559 switch (group[g].Type) {
550 case D3D12_BARRIER_TYPE_GLOBAL: { 560 case D3D12_BARRIER_TYPE_GLOBAL: {
551 const auto& b = group[g].pGlobalBarriers[i]; 561 const auto& b = group[g].pGlobalBarriers[i];
552 check(list_.barrier(leonida::GlobalBarrier{u(b.SyncBefore), u(b.SyncAfter), u(b.AccessBefore), 562 if (!list_.barrier(leonida::GlobalBarrier{u(b.SyncBefore), u(b.SyncAfter), u(b.AccessBefore),
553 u(b.AccessAfter)})); 563 u(b.AccessAfter)}) &&
564 reject())
565 std::fprintf(stderr, "[rt] d3d12: global barrier sync 0x%x->0x%x access 0x%x->0x%x\n",
566 u(b.SyncBefore), u(b.SyncAfter), u(b.AccessBefore), u(b.AccessAfter));
554 break; 567 break;
555 } 568 }
556 case D3D12_BARRIER_TYPE_BUFFER: { 569 case D3D12_BARRIER_TYPE_BUFFER: {
557 const auto& b = group[g].pBufferBarriers[i]; 570 const auto& b = group[g].pBufferBarriers[i];
558 check(list_.barrier(leonida::BufferBarrier{u(b.SyncBefore), u(b.SyncAfter), u(b.AccessBefore), 571 if (!list_.barrier(leonida::BufferBarrier{u(b.SyncBefore), u(b.SyncAfter), u(b.AccessBefore),
559 u(b.AccessAfter), resource_id(b.pResource)})); 572 u(b.AccessAfter), resource_id(b.pResource)}) &&
573 reject()) {
574 std::fprintf(stderr, "[rt] d3d12: buffer barrier sync 0x%x->0x%x access 0x%x->0x%x offset "
575 "0x%llx size 0x%llx\n",
576 u(b.SyncBefore), u(b.SyncAfter), u(b.AccessBefore), u(b.AccessAfter),
577 static_cast<unsigned long long>(b.Offset), static_cast<unsigned long long>(b.Size));
578 describe_barrier_resource(b.pResource);
579 }
560 break; 580 break;
561 } 581 }
562 case D3D12_BARRIER_TYPE_TEXTURE: { 582 case D3D12_BARRIER_TYPE_TEXTURE: {
563 const auto& b = group[g].pTextureBarriers[i]; 583 const auto& b = group[g].pTextureBarriers[i];
564 const auto& r = b.Subresources; 584 const auto& r = b.Subresources;
565 check(list_.barrier(leonida::TextureBarrier{ 585 if (!list_.barrier(leonida::TextureBarrier{
566 u(b.SyncBefore), u(b.SyncAfter), u(b.AccessBefore), u(b.AccessAfter), u(b.LayoutBefore), 586 u(b.SyncBefore), u(b.SyncAfter), u(b.AccessBefore), u(b.AccessAfter), u(b.LayoutBefore),
567 u(b.LayoutAfter), resource_id(b.pResource), 587 u(b.LayoutAfter), resource_id(b.pResource),
568 {r.IndexOrFirstMipLevel, r.NumMipLevels, r.FirstArraySlice, r.NumArraySlices, r.FirstPlane, 588 {r.IndexOrFirstMipLevel, r.NumMipLevels, r.FirstArraySlice, r.NumArraySlices,
569 r.NumPlanes}, 589 r.FirstPlane, r.NumPlanes},
570 u(b.Flags)})); 590 u(b.Flags)}) &&
591 reject()) {
592 std::fprintf(stderr,
593 "[rt] d3d12: texture barrier sync 0x%x->0x%x access 0x%x->0x%x layout %u->%u "
594 "mips %u+%u layers %u+%u planes %u+%u flags 0x%x\n",
595 u(b.SyncBefore), u(b.SyncAfter), u(b.AccessBefore), u(b.AccessAfter),
596 u(b.LayoutBefore), u(b.LayoutAfter), r.IndexOrFirstMipLevel, r.NumMipLevels,
597 r.FirstArraySlice, r.NumArraySlices, r.FirstPlane, r.NumPlanes, u(b.Flags));
598 describe_barrier_resource(b.pResource);
599 }
571 break; 600 break;
572 } 601 }
573 default: 602 default:
574 check(false); 603 if (reject())
604 std::fprintf(stderr, "[rt] d3d12: barrier group type %d\n", int(group[g].Type));
575 } 605 }
576 } 606 }
577 } 607 }
@@ -639,7 +669,24 @@ public:
639 if (!dst || !src) return check(false); 669 if (!dst || !src) return check(false);
640 leonida::CopyTexture copy{location(*dst), x, y, z, location(*src), box != nullptr, {}}; 670 leonida::CopyTexture copy{location(*dst), x, y, z, location(*src), box != nullptr, {}};
641 if (box) copy.box = {box->left, box->top, box->front, box->right, box->bottom, box->back}; 671 if (box) copy.box = {box->left, box->top, box->front, box->right, box->bottom, box->back};
642 check(list_.copy_texture(copy)); 672 if (!list_.copy_texture(copy) && reject()) {
673 for (const auto* l : {dst, src}) {
674 const char* side = l == dst ? "dst" : "src";
675 if (l->Type != D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT) {
676 std::fprintf(stderr, "[rt] d3d12: %s type %d resource %p subresource %u\n", side, int(l->Type),
677 static_cast<void*>(l->pResource), l->SubresourceIndex);
678 continue;
679 }
680 const auto& f = l->PlacedFootprint;
681 std::fprintf(stderr, "[rt] d3d12: %s footprint resource %p offset 0x%llx format %d %ux%ux%u pitch %u\n",
682 side, static_cast<void*>(l->pResource), static_cast<unsigned long long>(f.Offset),
683 int(f.Footprint.Format), f.Footprint.Width, f.Footprint.Height, f.Footprint.Depth,
684 f.Footprint.RowPitch);
685 }
686 if (box)
687 std::fprintf(stderr, "[rt] d3d12: at %u,%u,%u box %u,%u,%u-%u,%u,%u\n", x, y, z, box->left, box->top,
688 box->front, box->right, box->bottom, box->back);
689 }
643 } 690 }
644 691
645 void STDMETHODCALLTYPE CopyResource(ID3D12Resource* dst, ID3D12Resource* src) override { 692 void STDMETHODCALLTYPE CopyResource(ID3D12Resource* dst, ID3D12Resource* src) override {
@@ -721,6 +768,18 @@ public:
721 d3d12_trace::record("ID3D12GraphicsCommandList::ClearRenderTargetView"); 768 d3d12_trace::record("ID3D12GraphicsCommandList::ClearRenderTargetView");
722 if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); 769 if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false);
723 if (!view.ptr || !color) return check(false); 770 if (!view.ptr || !color) return check(false);
771 // LOCAL DIAGNOSTIC: what the title clears, and with which colour
772 if (leonida::local_diagnostics()) {
773 static std::atomic<std::uint64_t> clears{0};
774 const std::uint64_t n = ++clears;
775 if (n <= 6 || n % 600 == 0) {
776 const auto& t = *reinterpret_cast<const leonida::TargetView*>(view.ptr);
777 std::fprintf(stderr, "[rt] present-probe: ClearRenderTargetView #%llu resource 0x%llx mip %u layers %u+%u "
778 "colour %.3f %.3f %.3f %.3f rects %u\n",
779 static_cast<unsigned long long>(n), static_cast<unsigned long long>(t.resource), t.mip,
780 t.first_layer, t.layer_count, color[0], color[1], color[2], color[3], count);
781 }
782 }
724 check(list_.clear_render_target(*reinterpret_cast<const leonida::TargetView*>(view.ptr), 783 check(list_.clear_render_target(*reinterpret_cast<const leonida::TargetView*>(view.ptr),
725 {color[0], color[1], color[2], color[3]}, to_rects(count, rects))); 784 {color[0], color[1], color[2], color[3]}, to_rects(count, rects)));
726 } 785 }
@@ -898,7 +957,7 @@ public:
898 if (kind == leonida::IndirectKind::dispatch && max_command_count) { // the pipeline and root arguments a Dispatch would record 957 if (kind == leonida::IndirectKind::dispatch && max_command_count) { // the pipeline and root arguments a Dispatch would record
899 if (!compute_pipeline_ || !compute_.layout) return check(false); 958 if (!compute_pipeline_ || !compute_.layout) return check(false);
900 cmd.pipeline = compute_pipeline_; 959 cmd.pipeline = compute_pipeline_;
901 cmd.user_data = compute_.data; 960 cmd.user_data = compute_user_data();
902 } 961 }
903 check(list_.execute_indirect(cmd)); 962 check(list_.execute_indirect(cmd));
904 } 963 }
@@ -1056,8 +1115,35 @@ private:
1056 return out; 1115 return out;
1057 } 1116 }
1058 1117
1059 void check(bool ok) { 1118 // Records an invalid call: Close then returns E_INVALIDARG and ExecuteCommandLists refuses the list. The first
1060 if (!ok) invalid_ = true; 1119 // rejection at each call site is logged with the method and line, so a failed Close names its cause; reject()
1120 // returns true for that first one, when a caller may print the arguments too.
1121 bool reject(std::source_location where = std::source_location::current()) {
1122 invalid_ = true;
1123 static std::array<std::atomic<bool>, 4096> seen{};
1124 const std::uint_least32_t line = where.line();
1125 if (line < seen.size() && seen[line].exchange(true, std::memory_order_relaxed)) return false;
1126 std::string_view method = where.function_name();
1127 if (const auto at = method.find("GraphicsCommandList::"); at != std::string_view::npos)
1128 method.remove_prefix(at);
1129 if (const auto paren = method.find('('); paren != std::string_view::npos) method = method.substr(0, paren);
1130 std::fprintf(stderr, "[rt] d3d12: %.*s rejected a call (d3d12_com.cpp:%u): the list's Close returns "
1131 "E_INVALIDARG and ExecuteCommandLists refuses it\n",
1132 int(method.size()), method.data(), unsigned(line));
1133 return true;
1134 }
1135 void check(bool ok, std::source_location where = std::source_location::current()) {
1136 if (!ok) reject(where);
1137 }
1138 static void describe_barrier_resource(ID3D12Resource* resource) {
1139 if (!resource) return void(std::fprintf(stderr, "[rt] d3d12: resource null\n"));
1140 const D3D12_RESOURCE_DESC desc = resource->GetDesc();
1141 std::fprintf(stderr,
1142 "[rt] d3d12: resource %p dimension %d format %d %llux%ux%u mips %u samples %u layout %d "
1143 "flags 0x%x\n",
1144 static_cast<void*>(resource), int(desc.Dimension), int(desc.Format),
1145 static_cast<unsigned long long>(desc.Width), desc.Height, desc.DepthOrArraySize, desc.MipLevels,
1146 desc.SampleDesc.Count, int(desc.Layout), unsigned(desc.Flags));
1061 } 1147 }
1062 1148
1063 void stop_recording() { 1149 void stop_recording() {
@@ -1280,11 +1366,23 @@ private:
1280 return; 1366 return;
1281 const RootArgumentLayout::Parameter* p = parameter(state, index, type); 1367 const RootArgumentLayout::Parameter* p = parameter(state, index, type);
1282 if (!p) return; 1368 if (!p) return;
1369 // A root view into the title's own memory (a slot-133 buffer, a constant ring) gets the console VA of a GPU
1370 // copy of it, so the shader's heap_base + VA reaches it (src/title_va_alias.h). A descriptor table is in one
1371 // of the layer's heaps: kept, and its buffer V#s are rewritten the same way before each submission.
1372 // A table in a console descriptor heap is read from the heap's arena copy (console_descriptor_table_va).
1373 if (type == rt::rootsig::ParamType::Descriptor)
1374 va = leonida::title_va_aliases().resolve(va, kRootViewBytes, leonida::TitleVaAliases::root_view);
1375 else
1376 va = console_descriptor_table_va(va);
1377 if (type != rt::rootsig::ParamType::Descriptor && va && p->table_descriptors &&
1378 (tables_.empty() || tables_.back().first != va))
1379 tables_.push_back({va, p->table_descriptors});
1283 const std::uint32_t first = first_dword(state, *p); 1380 const std::uint32_t first = first_dword(state, *p);
1284 write(state, first, std::uint32_t(va)); 1381 write(state, first, std::uint32_t(va));
1285 // In the compute layout a descriptor table is one dword, the 32-bit VA of its first descriptor (the heaps 1382 // In the console layouts a descriptor table is one dword, the 32-bit VA of its first descriptor (the heaps
1286 // live below 4 GiB); a root view keeps both halves. The graphics layout gives every address two dwords. 1383 // live below 4 GiB); a root view keeps both halves. pack()'s graphics layout gives every address two dwords.
1287 if (!(is_compute(state) && type == rt::rootsig::ParamType::Table)) write(state, first + 1, std::uint32_t(va >> 32)); 1384 const bool console = is_compute(state) || state.layout->graphics_console;
1385 if (!(console && type == rt::rootsig::ParamType::Table)) write(state, first + 1, std::uint32_t(va >> 32));
1288 } 1386 }
1289 1387
1290 D3D12_COMMAND_LIST_TYPE type_; 1388 D3D12_COMMAND_LIST_TYPE type_;
@@ -1296,6 +1394,7 @@ private:
1296 RootState compute_; 1394 RootState compute_;
1297 RootState graphics_; 1395 RootState graphics_;
1298 std::uintptr_t compute_pipeline_ = 0; 1396 std::uintptr_t compute_pipeline_ = 0;
1397 bool unregistered_pipeline_ = false; // the bound PSO has no pipeline here (a stub): see set_pipeline
1299 std::uintptr_t graphics_pipeline_ = 0; 1398 std::uintptr_t graphics_pipeline_ = 0;
1300 ID3D12DescriptorHeap* cbv_srv_uav_heap_ = nullptr; 1399 ID3D12DescriptorHeap* cbv_srv_uav_heap_ = nullptr;
1301 ID3D12DescriptorHeap* sampler_heap_ = nullptr; 1400 ID3D12DescriptorHeap* sampler_heap_ = nullptr;
@@ -1304,6 +1403,10 @@ private:
1304 std::uint32_t topology_ = 0; // D3D_PRIMITIVE_TOPOLOGY_UNDEFINED 1403 std::uint32_t topology_ = 0; // D3D_PRIMITIVE_TOPOLOGY_UNDEFINED
1305 std::array<leonida::VertexBufferView, D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT> vertex_buffers_{}; 1404 std::array<leonida::VertexBufferView, D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT> vertex_buffers_{};
1306 leonida::IndexBufferView index_{}; 1405 leonida::IndexBufferView index_{};
1406 // SetGraphicsRootDescriptorTable / SetComputeRootDescriptorTable: VA, CBV/SRV/UAV slots the signature declares
1407 std::vector<std::pair<std::uint64_t, std::uint32_t>> tables_;
1408 // The span a root view may read: D3D12's largest constant buffer (4096 x 16 bytes).
1409 static constexpr std::uint64_t kRootViewBytes = 65536;
1307 leonida::Viewport viewport_{}; 1410 leonida::Viewport viewport_{};
1308 leonida::Rect scissor_{}; 1411 leonida::Rect scissor_{};
1309 std::array<leonida::Viewport, D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE> viewports_{}; 1412 std::array<leonida::Viewport, D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE> viewports_{};
@@ -1367,7 +1470,11 @@ private:
1367 hold(state); 1470 hold(state);
1368 compute_pipeline_ = compute_pipeline_id(state); 1471 compute_pipeline_ = compute_pipeline_id(state);
1369 graphics_pipeline_ = graphics_pipeline_id(state); 1472 graphics_pipeline_ = graphics_pipeline_id(state);
1370 if (state && !compute_pipeline_ && !graphics_pipeline_) 1473 // A pipeline this device never registered: a LEONIDA_STUB_PIPELINES stub (its translated shader is missing),
1474 // or one from another device. Its draws resolve to nothing in replay; its dispatches are no-ops too
1475 // (record_dispatch), so the list still closes.
1476 unregistered_pipeline_ = state && !compute_pipeline_ && !graphics_pipeline_;
1477 if (unregistered_pipeline_)
1371 stub("ID3D12GraphicsCommandList::SetPipelineState(pipeline from another device)"); 1478 stub("ID3D12GraphicsCommandList::SetPipelineState(pipeline from another device)");
1372 } 1479 }
1373 1480
@@ -1391,13 +1498,13 @@ private:
1391 if (!cbv_srv_uav_heap_) 1498 if (!cbv_srv_uav_heap_)
1392 note_once("draw/dispatch uses CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED with no CBV/SRV/UAV heap bound"); 1499 note_once("draw/dispatch uses CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED with no CBV/SRV/UAV heap bound");
1393 else 1500 else
1394 note_once("CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED heap base tracked on list (SGPR slot open, section 3.4)"); 1501 note_once("CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED heap base tracked on list");
1395 } 1502 }
1396 if (layout->flags & D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED) { 1503 if (layout->flags & D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED) {
1397 if (!sampler_heap_) 1504 if (!sampler_heap_)
1398 note_once("draw/dispatch uses SAMPLER_HEAP_DIRECTLY_INDEXED with no sampler heap bound"); 1505 note_once("draw/dispatch uses SAMPLER_HEAP_DIRECTLY_INDEXED with no sampler heap bound");
1399 else 1506 else
1400 note_once("SAMPLER_HEAP_DIRECTLY_INDEXED heap base tracked on list (SGPR slot open, section 3.4)"); 1507 note_once("SAMPLER_HEAP_DIRECTLY_INDEXED heap base tracked on list");
1401 } 1508 }
1402 } 1509 }
1403 1510
@@ -1430,21 +1537,114 @@ private:
1430 1537
1431 void set_vertex_buffers(UINT start, UINT count, const D3D12_VERTEX_BUFFER_VIEW* views) { 1538 void set_vertex_buffers(UINT start, UINT count, const D3D12_VERTEX_BUFFER_VIEW* views) {
1432 if (count) draw_views_stale_ = true; 1539 if (count) draw_views_stale_ = true;
1433 for (UINT i = 0; i < count; ++i) 1540 for (UINT i = 0; i < count; ++i) {
1541 if (views) leonida::title_va_aliases().note(views[i].BufferLocation, leonida::TitleVaAliases::vertex_view);
1542 if (views) leonida::title_va_aliases().want_buffer(views[i].BufferLocation, views[i].SizeInBytes);
1434 vertex_buffers_[start + i] = views ? leonida::VertexBufferView{views[i].BufferLocation, views[i].SizeInBytes, 1543 vertex_buffers_[start + i] = views ? leonida::VertexBufferView{views[i].BufferLocation, views[i].SizeInBytes,
1435 views[i].StrideInBytes} 1544 views[i].StrideInBytes}
1436 : leonida::VertexBufferView{}; 1545 : leonida::VertexBufferView{};
1546 }
1437 } 1547 }
1438 1548
1439 void set_index_buffer(const D3D12_INDEX_BUFFER_VIEW* view) { 1549 void set_index_buffer(const D3D12_INDEX_BUFFER_VIEW* view) {
1550 if (view) leonida::title_va_aliases().note(view->BufferLocation, leonida::TitleVaAliases::index_view);
1551 if (view) leonida::title_va_aliases().want_buffer(view->BufferLocation, view->SizeInBytes);
1440 index_ = view ? leonida::IndexBufferView{view->BufferLocation, view->SizeInBytes, u(view->Format)} 1552 index_ = view ? leonida::IndexBufferView{view->BufferLocation, view->SizeInBytes, u(view->Format)}
1441 : leonida::IndexBufferView{}; 1553 : leonida::IndexBufferView{};
1442 } 1554 }
1443 1555
1556 // The compiled console ABI appends directly indexed heaps after the explicit root arguments: the resource heap's
1557 // 32-bit shader VA, then the sampler heap's, each only when the signature has its flag. `slot` is the first
1558 // dword after the arguments (RootArgumentLayout::*_arguments_end). The heaps are snapshotted for each command,
1559 // so rebinding a heap cannot change a recorded draw or dispatch.
1560 std::array<std::uint32_t, rt::rootsig::kMaxUserSgprs> with_direct_heaps(const RootState& state,
1561 std::uint32_t slot) const {
1562 auto data = state.data;
1563 const auto flags = state.layout->flags;
1564 if ((flags & D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED) && slot < data.size())
1565 data[slot++] = static_cast<std::uint32_t>(cbv_srv_uav_base_);
1566 if ((flags & D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED) && slot < data.size())
1567 data[slot] = static_cast<std::uint32_t>(sampler_base_);
1568 return data;
1569 }
1570
1571 static bool direct_heaps_enabled(const char* variable) {
1572 const char* v = std::getenv(variable);
1573 return !(v && std::string_view(v) == "0");
1574 }
1575
1576 std::array<std::uint32_t, rt::rootsig::kMaxUserSgprs> compute_user_data() const {
1577 static const bool enabled = direct_heaps_enabled("LEONIDA_COMPUTE_DIRECT_HEAPS");
1578 if (!enabled) return compute_.data;
1579 return with_direct_heaps(compute_, compute_.layout->compute_arguments_end);
1580 }
1581
1582 // Graphics: vertex, pixel and geometry shaders share one user-data block and the s8 layout, so the heaps after
1583 // the explicit arguments serve every one of those stages (a pixel shader of a signature whose arguments end at
1584 // s11 reads the resource heap from s11). A mesh shader reads its arguments from s16, which is not modelled
1585 // (RootArgumentLayout, D3D-448): its pixel shader gets the heaps, the mesh stage does not.
1586 // LEONIDA_GRAPHICS_DIRECT_HEAPS=0 restores the previous arguments.
1587 std::array<std::uint32_t, rt::rootsig::kMaxUserSgprs> graphics_user_data() const {
1588 constexpr UINT direct = D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED |
1589 D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED;
1590 const RootArgumentLayout& layout = *graphics_.layout;
1591 if (!(layout.flags & direct)) return graphics_.data;
1592 static const bool enabled = direct_heaps_enabled("LEONIDA_GRAPHICS_DIRECT_HEAPS");
1593 if (!enabled) {
1594 note_once("graphics direct heaps: off (LEONIDA_GRAPHICS_DIRECT_HEAPS=0), draws keep the explicit "
1595 "arguments only");
1596 return graphics_.data;
1597 }
1598 const std::uint32_t end = layout.graphics_arguments_end;
1599 if (end >= rt::rootsig::kMaxUserSgprs) {
1600 note_once(layout.graphics_console
1601 ? "graphics direct heaps: not supplied, the explicit arguments fill s8..s31"
1602 : "graphics direct heaps: not supplied, the signature keeps the s0 graphics layout");
1603 return graphics_.data;
1604 }
1605 static std::atomic<bool> logged{false};
1606 if (!logged.exchange(true, std::memory_order_relaxed)) {
1607 const bool resource = layout.flags & D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED;
1608 const bool sampler = layout.flags & D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED;
1609 char resource_at[48] = "none", sampler_at[48] = "none";
1610 if (resource)
1611 std::snprintf(resource_at, sizeof resource_at, "0x%llx at s%u",
1612 static_cast<unsigned long long>(std::uint32_t(cbv_srv_uav_base_)), end);
1613 if (sampler && end + (resource ? 1u : 0u) < rt::rootsig::kMaxUserSgprs)
1614 std::snprintf(sampler_at, sizeof sampler_at, "0x%llx at s%u",
1615 static_cast<unsigned long long>(std::uint32_t(sampler_base_)),
1616 end + (resource ? 1u : 0u));
1617 std::fprintf(stderr,
1618 "[rt] d3d12: graphics direct heaps: resource heap %s, sampler heap %s, after %u dwords of "
1619 "explicit arguments from s8 (first draw; LEONIDA_GRAPHICS_DIRECT_HEAPS=0 restores the "
1620 "old arguments)\n",
1621 resource_at, sampler_at, end - 8);
1622 }
1623 return with_direct_heaps(graphics_, end);
1624 }
1625
1444 void record_dispatch(UINT x, UINT y, UINT z) { 1626 void record_dispatch(UINT x, UINT y, UINT z) {
1445 if (!compute_pipeline_ || !compute_.layout) return check(false); 1627 if (!compute_pipeline_ && unregistered_pipeline_) return; // a stub pipeline's dispatch: nothing to run
1628 if (!compute_pipeline_) return check(false); // separate lines: the rejection log names which
1629 if (!compute_.layout) return check(false);
1630 static const bool probe = std::getenv("LEONIDA_COMPUTE_INPUTS") != nullptr;
1631 if (probe) {
1632 static std::mutex mutex;
1633 static std::set<std::tuple<std::uintptr_t, const RootArgumentLayout*, UINT64>> seen;
1634 std::lock_guard lock(mutex);
1635 if (seen.emplace(compute_pipeline_, compute_.layout, cbv_srv_uav_base_).second) {
1636 std::fprintf(stderr, "[rt] compute-layout: pso=%p flags=%x bound-heap=0x%llx shader-heap=0x%llx",
1637 reinterpret_cast<void*>(compute_pipeline_), compute_.layout->flags,
1638 (unsigned long long)cbv_srv_uav_base_,
1639 (unsigned long long)console_descriptor_table_va(cbv_srv_uav_base_));
1640 for (const auto& p : compute_.layout->parameters)
1641 std::fprintf(stderr, " (s%u type=%u const=%u slots=%u)", p.compute_offset,
1642 unsigned(p.type), p.constant_count, p.table_descriptors);
1643 std::fputc('\n', stderr);
1644 }
1645 }
1446 note_direct_heap_indexing(compute_.layout); 1646 note_direct_heap_indexing(compute_.layout);
1447 check(list_.dispatch({compute_pipeline_, compute_.data, x, y, z})); 1647 check(list_.dispatch({compute_pipeline_, compute_user_data(), x, y, z}));
1448 } 1648 }
1449 1649
1450 // The views block a draw records. Rebuilt only when the render targets or the bound vertex buffers change. 1650 // The views block a draw records. Rebuilt only when the render targets or the bound vertex buffers change.
@@ -1486,8 +1686,88 @@ private:
1486 note_direct_heap_indexing(graphics_.layout); 1686 note_direct_heap_indexing(graphics_.layout);
1487 // No viewport (never set, or unbound with RSSetViewports(0)) or every bound viewport empty: D3D12 rasterizes 1687 // No viewport (never set, or unbound with RSSetViewports(0)) or every bound viewport empty: D3D12 rasterizes
1488 // nothing, and Vulkan forbids a 0x0 viewport, so the draw is not recorded. 1688 // nothing, and Vulkan forbids a 0x0 viewport, so the draw is not recorded.
1689 // LOCAL DIAGNOSTIC: the state each draw is recorded with
1690 if (leonida::local_diagnostics()) {
1691 static std::atomic<std::uint64_t> draws{0}, skipped{0};
1692 const bool skip = !any_nonempty_viewport();
1693 const std::uint64_t n = ++draws, k = skip ? ++skipped : skipped.load();
1694 if (n <= 8 || n % 1200 == 0)
1695 std::fprintf(stderr, "[rt] present-probe: draw #%llu (%s; %llu skipped so far) pso %p rts %u rt0 0x%llx "
1696 "mip %u viewport %.0fx%.0f at %.0f,%.0f scissor %d,%d-%d,%d count %u x%u\n",
1697 static_cast<unsigned long long>(n), skip ? "SKIPPED: no viewport" : "recorded",
1698 static_cast<unsigned long long>(k), reinterpret_cast<const void*>(graphics_pipeline_),
1699 render_target_count_, static_cast<unsigned long long>(render_targets_[0].resource),
1700 render_targets_[0].mip, viewport_.width, viewport_.height, viewport_.x, viewport_.y,
1701 scissor_.left, scissor_.top, scissor_.right, scissor_.bottom, count, instances);
1702 // LOCAL DIAGNOSTIC (fsdraw): the first draw of each pipeline, and one frame's draws every ~300 frames,
1703 // with the pipeline's description, the root data and what the bound descriptor tables hold.
1704 static std::mutex seen_mutex;
1705 static std::set<std::uintptr_t> seen;
1706 bool first_seen;
1707 {
1708 std::lock_guard lock(seen_mutex);
1709 first_seen = seen.insert(graphics_pipeline_).second;
1710 }
1711 const bool fullscreen = render_target_count_ >= 1 && count == 3 && viewport_.width >= 1000;
1712 if (fullscreen) leonida::fsdraw::note_target(render_targets_[0].resource);
1713 if (first_seen || (n - 1) % 600 < 2 || (n > 2 && n < 9)) {
1714 std::fprintf(stderr, "[rt] fsdraw: draw #%llu pso %p%s rt0 0x%llx rts %u depth 0x%llx count %u x%u: %s\n",
1715 static_cast<unsigned long long>(n), reinterpret_cast<const void*>(graphics_pipeline_),
1716 first_seen ? " (first use)" : "", static_cast<unsigned long long>(render_targets_[0].resource),
1717 render_target_count_, static_cast<unsigned long long>(depth_.resource), count, instances,
1718 leonida::fsdraw::pipeline(graphics_pipeline_).c_str());
1719 std::fprintf(stderr, "[rt] fsdraw: draw #%llu layout %p user data [%s] cbv heap %p base 0x%llx sampler "
1720 "base 0x%llx tables %zu\n",
1721 static_cast<unsigned long long>(n), static_cast<const void*>(graphics_.layout),
1722 leonida::fsdraw::hex_words(graphics_.data.data(), graphics_.data.size()).c_str(),
1723 static_cast<const void*>(cbv_srv_uav_heap_),
1724 static_cast<unsigned long long>(cbv_srv_uav_base_),
1725 static_cast<unsigned long long>(sampler_base_), tables_.size());
1726 for (std::size_t slot = 0; slot < 2; ++slot) { // the vertex buffers the blit's VS reads
1727 const auto& vb = vertex_buffers_[slot];
1728 if (!vb.va) continue;
1729 std::uint32_t words[12]{};
1730 bool read = false;
1731 MEMORY_BASIC_INFORMATION mbi{};
1732 if (vb.va < leonida::fsdraw::arena_size()) {
1733 read = leonida::fsdraw::arena_words(vb.va, words, 12);
1734 } else if (VirtualQuery(reinterpret_cast<const void*>(static_cast<std::uintptr_t>(vb.va)), &mbi, sizeof mbi) &&
1735 mbi.State == MEM_COMMIT && !(mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD)) && mbi.Protect) {
1736 std::memcpy(words, reinterpret_cast<const void*>(static_cast<std::uintptr_t>(vb.va)), sizeof words);
1737 read = true;
1738 }
1739 std::fprintf(stderr, "[rt] fsdraw: draw #%llu vb%zu va 0x%llx size %u stride %u: %s [%s]\n",
1740 static_cast<unsigned long long>(n), slot, static_cast<unsigned long long>(vb.va),
1741 unsigned(vb.size), unsigned(vb.stride), read ? "read" : "unreadable",
1742 read ? leonida::fsdraw::hex_words(words, 12).c_str() : "");
1743 }
1744 D3D12_DESCRIPTOR_HEAP_DESC heap_desc{};
1745 std::uintptr_t heap_cpu = 0;
1746 if (cbv_srv_uav_heap_) {
1747 heap_desc = cbv_srv_uav_heap_->GetDesc();
1748 heap_cpu = cbv_srv_uav_heap_->GetCPUDescriptorHandleForHeapStart().ptr;
1749 }
1750 char tag[48];
1751 std::snprintf(tag, sizeof tag, "draw #%llu", static_cast<unsigned long long>(n));
1752 for (const auto& [shader_va, slots] : tables_) {
1753 const std::uint64_t va = leonida::fsdraw::table_origin(shader_va);
1754 const std::uint64_t end = cbv_srv_uav_base_ + std::uint64_t(heap_desc.NumDescriptors) * 32;
1755 const bool in_heap = heap_cpu && va >= cbv_srv_uav_base_ && va + 32 <= end;
1756 const auto* cpu = in_heap ? reinterpret_cast<const std::uint8_t*>(heap_cpu + (va - cbv_srv_uav_base_))
1757 : nullptr;
1758 const bool console = heap_cpu == std::uintptr_t(cbv_srv_uav_base_);
1759 if (shader_va != va)
1760 std::fprintf(stderr, "[rt] fsdraw: %s table title va 0x%llx is shader va 0x%llx\n", tag,
1761 static_cast<unsigned long long>(va), static_cast<unsigned long long>(shader_va));
1762 leonida::fsdraw::describe_table(tag, shader_va, slots, cpu,
1763 !in_heap ? "none (not in the bound CBV/SRV/UAV heap)"
1764 : console ? "console (CPU address = GPU VA, title memory)"
1765 : "layer heap (arena)");
1766 }
1767 }
1768 }
1489 if (!any_nonempty_viewport()) return; 1769 if (!any_nonempty_viewport()) return;
1490 leonida::Draw draw{graphics_pipeline_, graphics_.data, draw_views(), depth_, index_, topology_, viewport_, 1770 leonida::Draw draw{graphics_pipeline_, graphics_user_data(), draw_views(), depth_, index_, topology_, viewport_,
1491 scissor_, blend_factor_, front_stencil_ref_, back_stencil_ref_, indexed, count, instances, 1771 scissor_, blend_factor_, front_stencil_ref_, back_stencil_ref_, indexed, count, instances,
1492 first, base_vertex, first_instance}; 1772 first, base_vertex, first_instance};
1493 draw.viewports = draw_viewports(); 1773 draw.viewports = draw_viewports();
@@ -1542,12 +1822,14 @@ public:
1542 context_.enqueue_fence_callback(semaphore, queued, [context, semaphore, queued, value, held = held_] { 1822 context_.enqueue_fence_callback(semaphore, queued, [context, semaphore, queued, value, held = held_] {
1543 std::uint64_t now = 0; 1823 std::uint64_t now = 0;
1544 bool signaled = false; 1824 bool signaled = false;
1545 if (context->vk.vkGetSemaphoreCounterValue(context->device(), semaphore, &now) == VK_SUCCESS && 1825 if (context->observe_result(context->vk.vkGetSemaphoreCounterValue(context->device(), semaphore, &now),
1826 "vkGetSemaphoreCounterValue (fence callback)") == VK_SUCCESS &&
1546 now >= queued && now < value) { 1827 now >= queued && now < value) {
1547 VkSemaphoreSignalInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO}; 1828 VkSemaphoreSignalInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO};
1548 info.semaphore = semaphore; 1829 info.semaphore = semaphore;
1549 info.value = value; 1830 info.value = value;
1550 signaled = context->vk.vkSignalSemaphore(context->device(), &info) == VK_SUCCESS; 1831 signaled = context->observe_result(context->vk.vkSignalSemaphore(context->device(), &info),
1832 "vkSignalSemaphore (fence callback)") == VK_SUCCESS;
1551 } 1833 }
1552 held->fetch_sub(1); 1834 held->fetch_sub(1);
1553 if (signaled) { 1835 if (signaled) {
@@ -1717,6 +1999,47 @@ public:
1717 recorded.push_back(&list->commands()); 1999 recorded.push_back(&list->commands());
1718 graphics.push_back(list); 2000 graphics.push_back(list);
1719 } 2001 }
2002 // Buffer V#s the title wrote into a bound table itself may name its own memory: rewritten to a GPU copy's
2003 // console VA before the copies are refreshed for this submission (src/title_va_alias.h).
2004 {
2005 std::map<std::uint64_t, std::uint32_t> tables; // each table once, with the most slots it was bound with
2006 for (const GraphicsCommandList* list : graphics)
2007 for (const auto& [table, descriptors] : list->tables())
2008 tables[table] = std::max(tables[table], descriptors);
2009 // LOCAL DIAGNOSTIC (fsdraw): poke experiment, LEONIDA_FSDRAW_POKE_CB=1
2010 if (leonida::fsdraw::poke_enabled()) {
2011 for (const auto& [table, descriptors] : tables) {
2012 const std::uint64_t origin = leonida::fsdraw::table_origin(table);
2013 if (origin != table)
2014 leonida::fsdraw::poke_cb(
2015 reinterpret_cast<const std::uint8_t*>(static_cast<std::uintptr_t>(origin)));
2016 }
2017 }
2018 // LOCAL DIAGNOSTIC (fsdraw): what the bound tables hold when the lists are submitted
2019 if (leonida::local_diagnostics()) {
2020 static std::atomic<std::uint64_t> submits{0};
2021 const std::uint64_t n = tables.empty() ? 0 : ++submits;
2022 if (n && (n <= 6 || n % 300 == 0)) {
2023 char tag[48];
2024 std::snprintf(tag, sizeof tag, "submit #%llu", static_cast<unsigned long long>(n));
2025 for (const auto& [table, descriptors] : tables) {
2026 const std::uint64_t origin = leonida::fsdraw::table_origin(table);
2027 const bool title = origin != table;
2028 leonida::fsdraw::describe_table(
2029 tag, table, descriptors,
2030 title ? reinterpret_cast<const std::uint8_t*>(static_cast<std::uintptr_t>(origin)) : nullptr,
2031 title ? "title memory (CPU bytes read at the title VA the table was set with)" : "arena or unknown");
2032 }
2033 }
2034 }
2035 if (!tables.empty()) {
2036 const auto start = std::chrono::steady_clock::now();
2037 for (const auto& [table, descriptors] : tables) leonida::title_va_aliases().scan_table(table, descriptors);
2038 leonida::title_va_aliases().note_scan(std::uint64_t(
2039 std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now() - start)
2040 .count()));
2041 }
2042 }
1720 last_result_ = queue_.execute(recorded, [&graphics] { return pin_lists(graphics); }); 2043 last_result_ = queue_.execute(recorded, [&graphics] { return pin_lists(graphics); });
1721 d3d12_trace::record(method, last_result_ == leonida::ReplayResult::success ? "ok" : "failed"); 2044 d3d12_trace::record(method, last_result_ == leonida::ReplayResult::success ? "ok" : "failed");
1722 if (last_result_ != leonida::ReplayResult::success) 2045 if (last_result_ != leonida::ReplayResult::success)
@@ -1869,16 +2192,20 @@ private:
1869 LARGE_INTEGER before{}, after{}; 2192 LARGE_INTEGER before{}, after{};
1870 { 2193 {
1871 std::lock_guard submit_lock(context_.submit_mutex()); 2194 std::lock_guard submit_lock(context_.submit_mutex());
1872 if (vk.vkQueueWaitIdle(vk_queue_) != VK_SUCCESS) return E_FAIL; 2195 if (context_.observe_result(vk.vkQueueWaitIdle(vk_queue_), "vkQueueWaitIdle (calibration)") != VK_SUCCESS)
2196 return E_FAIL;
1873 QueryPerformanceCounter(&before); 2197 QueryPerformanceCounter(&before);
1874 if (vk.vkQueueSubmit(vk_queue_, 1, &submit, VK_NULL_HANDLE) != VK_SUCCESS || 2198 if (context_.observe_result(vk.vkQueueSubmit(vk_queue_, 1, &submit, VK_NULL_HANDLE),
1875 vk.vkQueueWaitIdle(vk_queue_) != VK_SUCCESS) 2199 "vkQueueSubmit (calibration)") != VK_SUCCESS ||
2200 context_.observe_result(vk.vkQueueWaitIdle(vk_queue_), "vkQueueWaitIdle (calibration)") != VK_SUCCESS)
1876 return E_FAIL; 2201 return E_FAIL;
1877 QueryPerformanceCounter(&after); 2202 QueryPerformanceCounter(&after);
1878 } 2203 }
1879 std::uint64_t stamp = 0; 2204 std::uint64_t stamp = 0;
1880 if (stamp_.get_query_pool_results(context_.device(), stamp_.queries, 0, 1, sizeof(stamp), &stamp, 2205 if (context_.observe_result(stamp_.get_query_pool_results(context_.device(), stamp_.queries, 0, 1,
1881 sizeof(stamp), VK_QUERY_RESULT_64_BIT) != VK_SUCCESS) 2206 sizeof(stamp), &stamp, sizeof(stamp),
2207 VK_QUERY_RESULT_64_BIT),
2208 "vkGetQueryPoolResults (calibration)") != VK_SUCCESS)
1882 return E_FAIL; 2209 return E_FAIL;
1883 if (clock_.timestamp_valid_bits < 64) stamp &= (std::uint64_t(1) << clock_.timestamp_valid_bits) - 1; 2210 if (clock_.timestamp_valid_bits < 64) stamp &= (std::uint64_t(1) << clock_.timestamp_valid_bits) - 1;
1884 gpu = stamp; 2211 gpu = stamp;
@@ -2098,7 +2425,8 @@ HRESULT set_event_on_multiple_fence_completion(leonida::VulkanContext& context,
2098 wait.semaphoreCount = count; 2425 wait.semaphoreCount = count;
2099 wait.pSemaphores = semaphores.data(); 2426 wait.pSemaphores = semaphores.data();
2100 wait.pValues = values; 2427 wait.pValues = values;
2101 const VkResult result = context.vk.vkWaitSemaphores(context.device(), &wait, UINT64_MAX); 2428 const VkResult result = context.observe_result(
2429 context.vk.vkWaitSemaphores(context.device(), &wait, UINT64_MAX), "vkWaitSemaphores (multiple fences)");
2102 // Unlike a single fence's blocking SetEventOnCompletion, this path invokes Vulkan directly. 2430 // Unlike a single fence's blocking SetEventOnCompletion, this path invokes Vulkan directly.
2103 // A lost device must wake its other registered fence waiters and reject later submissions. 2431 // A lost device must wake its other registered fence waiters and reject later submissions.
2104 if (result == VK_ERROR_DEVICE_LOST) { 2432 if (result == VK_ERROR_DEVICE_LOST) {