upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/src
diff options
context:
space:
mode:
authorAsh Hopkins <ashleighhopkins87@gmail.com>2026-11-22 14:21:37 +0000
committerAsh Hopkins <ashleighhopkins87@gmail.com>2026-11-22 14:21:37 +0000
commiteebf85b60f021ce567427ce766f4ec1c88b0f13a (patch)
treef8ee32c3f47c57a6beae5705b35c97cd69b44afe /runtime/src
parent19b261bb99735ceb33dd2daaefe31ac9ef9ed26a (diff)
parent003e78129303643a3fdc9e5f0e31a01b09759236 (diff)
Merge remote-tracking branch 'origin/main' into runtime-vulkan12-khr
# Conflicts: # runtime/shims/d3d12_vulkan_device.cpp # runtime/test/vk_test_device.h
Diffstat (limited to 'runtime/src')
-rw-r--r--runtime/src/resource_tiling.h25
-rw-r--r--runtime/src/retire_tickets.h7
-rw-r--r--runtime/src/shader_library.h11
-rw-r--r--runtime/src/subgroup_size.h152
-rw-r--r--runtime/src/vulkan13_features.h11
-rw-r--r--runtime/src/vulkan_backend.h28
-rw-r--r--runtime/src/vulkan_depth24.h13
-rw-r--r--runtime/src/vulkan_present.h26
-rw-r--r--runtime/src/vulkan_replay.h16
-rw-r--r--runtime/src/vulkan_scratch.h13
10 files changed, 267 insertions, 35 deletions
diff --git a/runtime/src/resource_tiling.h b/runtime/src/resource_tiling.h
index 6bd890ae8..a9d95ae9f 100644
--- a/runtime/src/resource_tiling.h
+++ b/runtime/src/resource_tiling.h
@@ -43,6 +43,7 @@ struct TilingDesc {
43 std::uint32_t mips = 1; 43 std::uint32_t mips = 1;
44 std::uint32_t element_bytes = 0; // bytes per texel, or per block of a block-compressed format 44 std::uint32_t element_bytes = 0; // bytes per texel, or per block of a block-compressed format
45 std::uint32_t block = 1; // texels per block side: 4 for BC1-7 45 std::uint32_t block = 1; // texels per block side: 4 for BC1-7
46 std::uint32_t samples = 1; // 1, or 4 for 2D single-mip MSAA
46}; 47};
47 48
48// D3D12_SUBRESOURCE_TILING: a packed mip has no tiles of its own and starts at packed_tile. 49// D3D12_SUBRESOURCE_TILING: a packed mip has no tiles of its own and starts at packed_tile.
@@ -63,9 +64,22 @@ struct ResourceTiling {
63 std::vector<SubresourceTiling> subresources; // mip + layer * mips 64 std::vector<SubresourceTiling> subresources; // mip + layer * mips
64}; 65};
65 66
66// The standard tile shape in elements (D3D12 "standard swizzle" tile shapes for 64 KiB tiles), or {} for an 67// The standard tile shape in elements (D3D12 "standard swizzle" tile shapes for 64 KiB tiles; 2D 4x MSAA scales the
67// element size that cannot be tiled (3- and 12-byte formats). 68// tile shape down by 4 samples per texel, measured on RTX 5070 Ti and WARP), or {} for an unsupported sample count or
68constexpr TileShape element_tile_shape(bool volume, std::uint32_t element_bytes) { 69// an element size that cannot be tiled (3- and 12-byte formats).
70constexpr TileShape element_tile_shape(bool volume, std::uint32_t element_bytes, std::uint32_t samples = 1) {
71 if (samples == 4) {
72 if (volume) return {};
73 switch (element_bytes) {
74 case 1: return {128, 128, 1};
75 case 2: return {128, 64, 1};
76 case 4: return {64, 64, 1};
77 case 8: return {64, 32, 1};
78 case 16: return {32, 32, 1};
79 default: return {};
80 }
81 }
82 if (samples != 1) return {};
69 switch (element_bytes) { 83 switch (element_bytes) {
70 case 1: return volume ? TileShape{64, 32, 32} : TileShape{256, 256, 1}; 84 case 1: return volume ? TileShape{64, 32, 32} : TileShape{256, 256, 1};
71 case 2: return volume ? TileShape{32, 32, 32} : TileShape{256, 128, 1}; 85 case 2: return volume ? TileShape{32, 32, 32} : TileShape{256, 128, 1};
@@ -103,7 +117,8 @@ inline bool resource_tiling(const TilingDesc& desc, ResourceTiling& out) {
103 return true; 117 return true;
104 } 118 }
105 const bool volume = desc.kind == TiledKind::texture3d; 119 const bool volume = desc.kind == TiledKind::texture3d;
106 const TileShape elements = element_tile_shape(volume, desc.element_bytes); 120 if (desc.samples != 1 && (desc.samples != 4 || volume || desc.mips != 1 || desc.block != 1)) return false;
121 const TileShape elements = element_tile_shape(volume, desc.element_bytes, desc.samples);
107 if (!elements.width || !desc.mips || !desc.block || !desc.width || !desc.height || !desc.depth_or_layers) 122 if (!elements.width || !desc.mips || !desc.block || !desc.width || !desc.height || !desc.depth_or_layers)
108 return false; 123 return false;
109 out.shape = {elements.width * desc.block, elements.height * desc.block, elements.depth}; 124 out.shape = {elements.width * desc.block, elements.height * desc.block, elements.depth};
@@ -124,7 +139,7 @@ inline bool resource_tiling(const TilingDesc& desc, ResourceTiling& out) {
124 ++out.standard_mips; 139 ++out.standard_mips;
125 } else { 140 } else {
126 slice[mip] = {0, 0, 0, packed_tile}; 141 slice[mip] = {0, 0, 0, packed_tile};
127 packed_bytes += up(w, desc.block) * up(h, desc.block) * d * desc.element_bytes; 142 packed_bytes += up(w, desc.block) * up(h, desc.block) * d * desc.element_bytes * desc.samples;
128 ++out.packed_mips; 143 ++out.packed_mips;
129 } 144 }
130 } 145 }
diff --git a/runtime/src/retire_tickets.h b/runtime/src/retire_tickets.h
index 17c3f589e..714cf40a4 100644
--- a/runtime/src/retire_tickets.h
+++ b/runtime/src/retire_tickets.h
@@ -7,7 +7,9 @@ namespace leonida {
7 7
8// Global submission tickets may finish out of order on independent Vulkan queues. Only the 8// Global submission tickets may finish out of order on independent Vulkan queues. Only the
9// contiguous completed prefix is safe for deferred resource destruction. The caller serializes 9// contiguous completed prefix is safe for deferred resource destruction. The caller serializes
10// record(), completed() and queue_idle() with the device submission mutex. 10// record(), completed() and queue_idle() with the device submission mutex. record() must
11// receive strictly increasing global ticket numbers; otherwise a duplicate or backward ticket
12// can make the completed prefix stall or move backward.
11template<class Semaphore> 13template<class Semaphore>
12class RetireTickets { 14class RetireTickets {
13public: 15public:
@@ -26,7 +28,8 @@ public:
26 return completed_; 28 return completed_;
27 } 29 }
28 30
29 // The owning queue has been waited idle and may now destroy its progress semaphore. 31 // Call only after the owning queue's wait-idle succeeded. Merely requesting idle does not
32 // prove its submissions completed and must not advance the retirement prefix.
30 void queue_idle(Semaphore semaphore) { 33 void queue_idle(Semaphore semaphore) {
31 for (Entry& entry : pending_) 34 for (Entry& entry : pending_)
32 if (entry.semaphore == semaphore) entry.idle = true; 35 if (entry.semaphore == semaphore) entry.idle = true;
diff --git a/runtime/src/shader_library.h b/runtime/src/shader_library.h
index 17705a5d1..0f31269a0 100644
--- a/runtime/src/shader_library.h
+++ b/runtime/src/shader_library.h
@@ -532,6 +532,13 @@ struct ShaderEntry {
532 std::array<std::uint32_t, 3> local_size{1, 1, 1}; 532 std::array<std::uint32_t, 3> local_size{1, 1, 1};
533 bool uses_code_base = false; 533 bool uses_code_base = false;
534 bool wave64 = false; 534 bool wave64 = false;
535 // The subgroup size the translator assumed (64 for a wave64 shader, 32 otherwise); 0 when the entry says null,
536 // as one translated with --wave64-emulate does, or has none.
537 std::uint32_t subgroup_size = 0;
538 // "workgroup" for a shader translated with --wave64-emulate: it uses no subgroup operation and is exact on any
539 // subgroup size. Empty for a native translation.
540 std::string wave64_exchange;
541 bool emulated() const { return !wave64_exchange.empty(); }
535 std::vector<SignatureElement> input_signature; // vertex shaders: what the input layout must feed 542 std::vector<SignatureElement> input_signature; // vertex shaders: what the input layout must feed
536 std::vector<std::uint32_t> outputs; // pixel shaders: the render-target locations written 543 std::vector<std::uint32_t> outputs; // pixel shaders: the render-target locations written
537}; 544};
@@ -613,6 +620,10 @@ private:
613 for (std::size_t i = 0; i < l->array.size() && i < 3; ++i) e.local_size[i] = u32(&l->array[i]); 620 for (std::size_t i = 0; i < l->array.size() && i < 3; ++i) e.local_size[i] = u32(&l->array[i]);
614 if (const Json* c = meta.find("uses_code_base"); c && c->kind == Json::Kind::boolean) e.uses_code_base = c->boolean; 621 if (const Json* c = meta.find("uses_code_base"); c && c->kind == Json::Kind::boolean) e.uses_code_base = c->boolean;
615 if (const Json* w = meta.find("wave64"); w && w->kind == Json::Kind::boolean) e.wave64 = w->boolean; 622 if (const Json* w = meta.find("wave64"); w && w->kind == Json::Kind::boolean) e.wave64 = w->boolean;
623 if (const Json* g = meta.find("subgroup_size"); g && g->kind == Json::Kind::number)
624 e.subgroup_size = u32(g);
625 if (const Json* x = meta.find("wave64_exchange"); x && x->kind == Json::Kind::string)
626 e.wave64_exchange = x->string;
616 if (const Json* s = meta.find("input_signature"); s && s->kind == Json::Kind::array) { 627 if (const Json* s = meta.find("input_signature"); s && s->kind == Json::Kind::array) {
617 for (const Json& item : s->array) { 628 for (const Json& item : s->array) {
618 SignatureElement element; 629 SignatureElement element;
diff --git a/runtime/src/subgroup_size.h b/runtime/src/subgroup_size.h
new file mode 100644
index 000000000..2df643fdf
--- /dev/null
+++ b/runtime/src/subgroup_size.h
@@ -0,0 +1,152 @@
1#pragma once
2
3// Subgroup size control for pipeline creation (docs/d3d12_vulkan.md, "Subgroup size"). A translated shader assumes
4// one subgroup size: 64 when the game's shader was wave64, 32 otherwise (spirv/index.json `subgroup_size`). A GPU
5// whose default differs runs it inexact (a wave64 shader reads lanes 32-63 of a 32-wide subgroup; a wave32 pixel
6// shader on a 64-wide default reads the other half's lanes), so each stage asks for the size it was translated for
7// where Vulkan allows (VK_EXT_subgroup_size_control, core in 1.3).
8//
9// The decision is a pure function of the shader's index entry and what the device offers, so it is tested without
10// a GPU (subgroup_size_test). It depends only on the Vulkan headers.
11
12#include "shader_library.h"
13
14#include <vulkan/vulkan_core.h>
15
16#include <cstdint>
17#include <string_view>
18
19namespace leonida {
20
21// What the device offers. `subgroup_size_control` and `compute_full_subgroups` say the feature is ENABLED on the
22// device (the validation layers reject the structure and the flag otherwise), not merely supported.
23struct SubgroupSizeCaps {
24 bool subgroup_size_control = false;
25 bool compute_full_subgroups = false;
26 std::uint32_t min_size = 0;
27 std::uint32_t max_size = 0;
28 std::uint32_t default_size = 0; // VkPhysicalDeviceSubgroupProperties::subgroupSize
29 std::uint32_t max_compute_workgroup_subgroups = 0;
30 VkShaderStageFlags required_stages = 0; // requiredSubgroupSizeStages
31};
32
33// Fills the limits of `caps` from vkGetPhysicalDeviceProperties2 and sets the two feature flags from what the
34// caller enables. Returns false when the device reports no subgroup size at all.
35template <class GetProperties2>
36bool query_subgroup_size_caps(GetProperties2 get_properties2, VkPhysicalDevice physical, bool enable_size_control,
37 bool enable_full_subgroups, SubgroupSizeCaps& caps) {
38 VkPhysicalDeviceSubgroupSizeControlProperties control{
39 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_PROPERTIES};
40 VkPhysicalDeviceSubgroupProperties subgroup{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES, &control};
41 VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &subgroup};
42 get_properties2(physical, &properties);
43 caps = {};
44 caps.default_size = subgroup.subgroupSize;
45 caps.min_size = control.minSubgroupSize;
46 caps.max_size = control.maxSubgroupSize;
47 caps.max_compute_workgroup_subgroups = control.maxComputeWorkgroupSubgroups;
48 caps.required_stages = control.requiredSubgroupSizeStages;
49 caps.subgroup_size_control = enable_size_control;
50 caps.compute_full_subgroups = enable_full_subgroups;
51 return caps.default_size != 0;
52}
53
54// The Vulkan stage of an index entry's `stage` ("cs", "ps", ...); 0 for one this layer has no pipeline for.
55inline VkShaderStageFlagBits subgroup_stage_bit(std::string_view stage) {
56 if (stage == "cs") return VK_SHADER_STAGE_COMPUTE_BIT;
57 if (stage == "ps") return VK_SHADER_STAGE_FRAGMENT_BIT;
58 if (stage == "vs") return VK_SHADER_STAGE_VERTEX_BIT;
59 if (stage == "gs") return VK_SHADER_STAGE_GEOMETRY_BIT;
60 if (stage == "ms") return VK_SHADER_STAGE_MESH_BIT_EXT;
61 return VkShaderStageFlagBits(0);
62}
63
64enum class SubgroupOutcome {
65 emulated, // --wave64-emulate: exact on any size, nothing is required
66 required, // the stage asks for `size`
67 device_fixed, // the device has one size and it is the wanted one: nothing to ask for
68 device_default, // cannot be required, but the default size is the wanted one: works, not guaranteed stable
69 unavailable, // the wanted size cannot be had: the shader runs at another size and may be inexact
70 unknown_stage, // no Vulkan stage for this entry
71 unknown_device, // the device sizes were not queried (all zero): nothing is asked for
72};
73
74struct SubgroupRequest {
75 SubgroupOutcome outcome = SubgroupOutcome::unknown_stage;
76 VkShaderStageFlagBits stage = VkShaderStageFlagBits(0);
77 std::uint32_t wanted = 0; // the size the translation assumed
78 std::uint32_t size = 0; // requiredSubgroupSize to chain; 0: chain nothing
79 VkPipelineShaderStageCreateFlags flags = 0; // REQUIRE_FULL_SUBGROUPS, compute only
80};
81
82inline bool subgroup_is_power_of_two(std::uint32_t v) { return v && !(v & (v - 1)); }
83
84// What to ask for one stage of a pipeline made from `entry`.
85// - Emulated (`wave64_exchange` present): nothing.
86// - Otherwise the wanted size is the entry's `subgroup_size`, or 64 for a wave64 entry without one and 32 for the
87// rest. VkPipelineShaderStageRequiredSubgroupSizeCreateInfo is chained when the subgroupSizeControl feature is
88// enabled, the stage is in requiredSubgroupSizeStages, the size is a power of two in [min, max] and, for
89// compute and mesh, the workgroup fits in size * maxComputeWorkgroupSubgroups
90// (VUID-VkPipelineShaderStageCreateInfo-pNext-02755 and -02756,
91// VUID-VkPipelineShaderStageRequiredSubgroupSizeCreateInfo-requiredSubgroupSize-02760..02762).
92// - A compute stage also gets VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT when computeFullSubgroups
93// is enabled and the local size X is a multiple of the size (VUID-VkPipelineShaderStageCreateInfo-flags-02785:
94// the flag needs the feature; -flags-08988: a compute, task or mesh stage; with a required size, -pNext-02757
95// wants X to be a multiple of it).
96// - A device whose one and only subgroup size (min == max) is the wanted one needs nothing (`device_fixed`).
97// - Where the size cannot be required (stage not listed, feature off) but the device default is the wanted size,
98// the shader works as it is (`device_default`): nothing guarantees it, a driver may change its default.
99// Otherwise the outcome is `unavailable`.
100inline SubgroupRequest decide_subgroup_size(const ShaderEntry& entry, const SubgroupSizeCaps& caps) {
101 SubgroupRequest r;
102 r.stage = subgroup_stage_bit(entry.stage);
103 if (!r.stage) return r;
104 if (entry.emulated()) {
105 r.outcome = SubgroupOutcome::emulated;
106 return r;
107 }
108 r.wanted = entry.subgroup_size ? entry.subgroup_size : (entry.wave64 ? 64 : 32);
109 if (!caps.default_size && !caps.max_size) {
110 r.outcome = SubgroupOutcome::unknown_device;
111 return r;
112 }
113
114 const bool compute_like = r.stage == VK_SHADER_STAGE_COMPUTE_BIT || r.stage == VK_SHADER_STAGE_MESH_BIT_EXT;
115 const std::uint64_t invocations =
116 std::uint64_t(entry.local_size[0]) * entry.local_size[1] * entry.local_size[2];
117 const bool fixed = caps.min_size && caps.min_size == caps.max_size && caps.min_size == r.wanted;
118 const bool requirable =
119 caps.subgroup_size_control && (caps.required_stages & r.stage) && subgroup_is_power_of_two(r.wanted) &&
120 r.wanted >= caps.min_size && r.wanted <= caps.max_size &&
121 (!compute_like || invocations <= std::uint64_t(r.wanted) * caps.max_compute_workgroup_subgroups);
122
123 if (fixed) {
124 r.outcome = SubgroupOutcome::device_fixed;
125 } else if (requirable) {
126 r.outcome = SubgroupOutcome::required;
127 r.size = r.wanted;
128 if (r.stage == VK_SHADER_STAGE_COMPUTE_BIT && caps.compute_full_subgroups &&
129 entry.local_size[0] % r.wanted == 0)
130 r.flags |= VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT;
131 } else if (caps.default_size == r.wanted) {
132 r.outcome = SubgroupOutcome::device_default;
133 } else {
134 r.outcome = SubgroupOutcome::unavailable;
135 }
136 return r;
137}
138
139// Puts a request into a stage create-info. `storage` holds the chained structure and must outlive the
140// vkCreate*Pipelines call. Chains in front of whatever pNext already holds.
141inline void apply_subgroup_request(const SubgroupRequest& request,
142 VkPipelineShaderStageRequiredSubgroupSizeCreateInfo& storage,
143 VkPipelineShaderStageCreateInfo& stage) {
144 stage.flags |= request.flags;
145 if (!request.size) return;
146 storage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO};
147 storage.requiredSubgroupSize = request.size;
148 storage.pNext = const_cast<void*>(stage.pNext);
149 stage.pNext = &storage;
150}
151
152} // namespace leonida
diff --git a/runtime/src/vulkan13_features.h b/runtime/src/vulkan13_features.h
index 111d81df3..2057d953b 100644
--- a/runtime/src/vulkan13_features.h
+++ b/runtime/src/vulkan13_features.h
@@ -31,6 +31,9 @@ public:
31 bool core = false; // a Vulkan 1.3 device: the features are core 31 bool core = false; // a Vulkan 1.3 device: the features are core
32 bool dynamic_rendering = false; // supported, as a core feature or through VK_KHR_dynamic_rendering 32 bool dynamic_rendering = false; // supported, as a core feature or through VK_KHR_dynamic_rendering
33 bool synchronization2 = false; // supported, as a core feature or through VK_KHR_synchronization2 33 bool synchronization2 = false; // supported, as a core feature or through VK_KHR_synchronization2
34 // Optional 1.3 core features, enabled where supported; on a 1.2 device they stay off (no required subgroup size).
35 bool subgroup_size_control = false;
36 bool compute_full_subgroups = false;
34 37
35 bool usable() const { return dynamic_rendering && synchronization2; } 38 bool usable() const { return dynamic_rendering && synchronization2; }
36 39
@@ -38,7 +41,7 @@ public:
38 void query(VkPhysicalDevice physical, std::uint32_t api_version, PFN_vkGetPhysicalDeviceFeatures2 features2, 41 void query(VkPhysicalDevice physical, std::uint32_t api_version, PFN_vkGetPhysicalDeviceFeatures2 features2,
39 PFN_vkEnumerateDeviceExtensionProperties enumerate_extensions) { 42 PFN_vkEnumerateDeviceExtensionProperties enumerate_extensions) {
40 core = api_version >= VK_API_VERSION_1_3; 43 core = api_version >= VK_API_VERSION_1_3;
41 dynamic_rendering = synchronization2 = false; 44 dynamic_rendering = synchronization2 = subgroup_size_control = compute_full_subgroups = false;
42 if (!features2) return; 45 if (!features2) return;
43 if (core) { 46 if (core) {
44 VkPhysicalDeviceVulkan13Features f13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES}; 47 VkPhysicalDeviceVulkan13Features f13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES};
@@ -46,6 +49,8 @@ public:
46 features2(physical, &query); 49 features2(physical, &query);
47 dynamic_rendering = f13.dynamicRendering == VK_TRUE; 50 dynamic_rendering = f13.dynamicRendering == VK_TRUE;
48 synchronization2 = f13.synchronization2 == VK_TRUE; 51 synchronization2 = f13.synchronization2 == VK_TRUE;
52 subgroup_size_control = f13.subgroupSizeControl == VK_TRUE;
53 compute_full_subgroups = f13.computeFullSubgroups == VK_TRUE;
49 return; 54 return;
50 } 55 }
51 if (api_version < VK_API_VERSION_1_2 || !enumerate_extensions) return; 56 if (api_version < VK_API_VERSION_1_2 || !enumerate_extensions) return;
@@ -73,6 +78,8 @@ public:
73 core = from.core; 78 core = from.core;
74 dynamic_rendering = from.dynamic_rendering; 79 dynamic_rendering = from.dynamic_rendering;
75 synchronization2 = from.synchronization2; 80 synchronization2 = from.synchronization2;
81 subgroup_size_control = from.subgroup_size_control;
82 compute_full_subgroups = from.compute_full_subgroups;
76 } 83 }
77 84
78 // The structs that enable both features, ahead of `chain`; returns their head for VkPhysicalDeviceVulkan12Features' 85 // The structs that enable both features, ahead of `chain`; returns their head for VkPhysicalDeviceVulkan12Features'
@@ -82,6 +89,8 @@ public:
82 enable13_.pNext = chain; 89 enable13_.pNext = chain;
83 enable13_.dynamicRendering = VK_TRUE; 90 enable13_.dynamicRendering = VK_TRUE;
84 enable13_.synchronization2 = VK_TRUE; 91 enable13_.synchronization2 = VK_TRUE;
92 enable13_.subgroupSizeControl = subgroup_size_control ? VK_TRUE : VK_FALSE;
93 enable13_.computeFullSubgroups = compute_full_subgroups ? VK_TRUE : VK_FALSE;
85 return &enable13_; 94 return &enable13_;
86 } 95 }
87 sync2_.pNext = chain; 96 sync2_.pNext = chain;
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h
index 95803fe34..2ddd8be74 100644
--- a/runtime/src/vulkan_backend.h
+++ b/runtime/src/vulkan_backend.h
@@ -847,7 +847,10 @@ public:
847 query_pools_[id] = pool; 847 query_pools_[id] = pool;
848 } 848 }
849 void remove_query_pool(QueryHeapId id) { 849 void remove_query_pool(QueryHeapId id) {
850 // Lock hierarchy: resource_mutex_ -> tracker_mutex_. Holding tracker_mutex_ before erasing keeps the
851 // QueryPool node alive until any in-flight execute() that unlocked resource_mutex_ finishes QueryReplay::commit().
850 std::unique_lock lock(resource_mutex_); 852 std::unique_lock lock(resource_mutex_);
853 std::lock_guard tlock(tracker_mutex_);
851 query_pools_.erase(id); 854 query_pools_.erase(id);
852 } 855 }
853 // The heap's d3d12_query_heap type, or ~0u for a heap that is not registered. 856 // The heap's d3d12_query_heap type, or ~0u for a heap that is not registered.
@@ -1026,6 +1029,7 @@ public:
1026 1029
1027 std::uint64_t completed_retire_ticket() { 1030 std::uint64_t completed_retire_ticket() {
1028 std::lock_guard lock(submit_mutex_); 1031 std::lock_guard lock(submit_mutex_);
1032 if (is_device_lost()) return 0;
1029 return retire_tickets_.completed([this](VkSemaphore semaphore, std::uint64_t value) { 1033 return retire_tickets_.completed([this](VkSemaphore semaphore, std::uint64_t value) {
1030 std::uint64_t done = 0; 1034 std::uint64_t done = 0;
1031 return vk.vkGetSemaphoreCounterValue(device_, semaphore, &done) == VK_SUCCESS && done >= value; 1035 return vk.vkGetSemaphoreCounterValue(device_, semaphore, &done) == VK_SUCCESS && done >= value;
@@ -1222,8 +1226,12 @@ public:
1222 if (queue_) { 1226 if (queue_) {
1223 std::lock_guard lock(context_.submit_mutex()); 1227 std::lock_guard lock(context_.submit_mutex());
1224 for (; open_labels_; --open_labels_) context_.labels_.queue_end(queue_); 1228 for (; open_labels_; --open_labels_) context_.labels_.queue_end(queue_);
1225 vk.vkQueueWaitIdle(queue_); 1229 const VkResult idle_result = vk.vkQueueWaitIdle(queue_);
1226 if (progress_) context_.retire_queue_idle_locked(progress_); 1230 if (idle_result == VK_SUCCESS) {
1231 if (progress_) context_.retire_queue_idle_locked(progress_);
1232 } else {
1233 context_.mark_device_lost();
1234 }
1227 } 1235 }
1228 if (progress_) { 1236 if (progress_) {
1229 std::lock_guard lock(context_.tracker_mutex_); 1237 std::lock_guard lock(context_.tracker_mutex_);
@@ -1344,6 +1352,7 @@ public:
1344 } 1352 }
1345 const auto resolve = [this](ResourceId id) { return context_.resolve(id); }; 1353 const auto resolve = [this](ResourceId id) { return context_.resolve(id); };
1346 std::uint32_t segments = 0, statistics_segments = 0; 1354 std::uint32_t segments = 0, statistics_segments = 0;
1355 bool has_queries = false;
1347 for (std::size_t i = 0; i < lists.size(); ++i) { 1356 for (std::size_t i = 0; i < lists.size(); ++i) {
1348 const auto result = prepare(*lists[i], resolve, replay, prepared[i]); 1357 const auto result = prepare(*lists[i], resolve, replay, prepared[i]);
1349 if (result != ReplayResult::success) return result; 1358 if (result != ReplayResult::success) return result;
@@ -1352,6 +1361,7 @@ public:
1352 return ReplayResult::unsupported; 1361 return ReplayResult::unsupported;
1353 segments += prepared[i].segment_count; 1362 segments += prepared[i].segment_count;
1354 statistics_segments += prepared[i].statistics_segment_count; 1363 statistics_segments += prepared[i].statistics_segment_count;
1364 has_queries = has_queries || !prepared[i].queries.empty();
1355 } 1365 }
1356 const auto segment_pool = [this](VkQueryType type, std::uint32_t count, 1366 const auto segment_pool = [this](VkQueryType type, std::uint32_t count,
1357 std::shared_ptr<OcclusionSegmentPool>& out) { 1367 std::shared_ptr<OcclusionSegmentPool>& out) {
@@ -1373,6 +1383,10 @@ public:
1373 if (statistics_segments && can_resolve_occlusion && 1383 if (statistics_segments && can_resolve_occlusion &&
1374 !segment_pool(VK_QUERY_TYPE_PIPELINE_STATISTICS, statistics_segments, statistics)) 1384 !segment_pool(VK_QUERY_TYPE_PIPELINE_STATISTICS, statistics_segments, statistics))
1375 return ReplayResult::unsupported; 1385 return ReplayResult::unsupported;
1386 // QueryReplay::plan() reads QueryPool::ended / occlusion and QueryReplay::commit() writes them after
1387 // resource_lock is unlocked. Hold tracker_mutex_ across plan -> emit -> submit -> commit so concurrent queues
1388 // see submission-order query state and remove_query_pool() waits until commit finishes.
1389 if (has_queries && !tracker_lock.owns_lock()) tracker_lock.lock();
1376 QueryReplay queries; 1390 QueryReplay queries;
1377 std::uint32_t base = 0, statistics_base = 0; 1391 std::uint32_t base = 0, statistics_base = 0;
1378 for (auto& list : prepared) { 1392 for (auto& list : prepared) {
@@ -1597,10 +1611,12 @@ private:
1597 return false; 1611 return false;
1598 } 1612 }
1599 const bool ok = (res == VK_SUCCESS); 1613 const bool ok = (res == VK_SUCCESS);
1600 waits_.clear(); 1614 if (ok) {
1601 wait_values_.clear(); 1615 waits_.clear();
1602 for (auto& slot : buffers_) 1616 wait_values_.clear();
1603 if (slot.buffer == command_buffer) slot.ticket = ticket; 1617 for (auto& slot : buffers_)
1618 if (slot.buffer == command_buffer) slot.ticket = ticket;
1619 }
1604 return ok; 1620 return ok;
1605 } 1621 }
1606 1622
diff --git a/runtime/src/vulkan_depth24.h b/runtime/src/vulkan_depth24.h
index 1bc9c8ba5..988b79d9f 100644
--- a/runtime/src/vulkan_depth24.h
+++ b/runtime/src/vulkan_depth24.h
@@ -143,11 +143,14 @@ public:
143 // Frees (or keeps for reuse) what finished submissions used. 143 // Frees (or keeps for reuse) what finished submissions used.
144 void collect() { 144 void collect() {
145 for (std::size_t i = 0; i < retired_.size();) { 145 for (std::size_t i = 0; i < retired_.size();) {
146 std::uint64_t done = 0; 146 if (retired_[i].ticket != 0) {
147 vk_.vkGetSemaphoreCounterValue(device_, retired_[i].timeline, &done); 147 std::uint64_t done = 0;
148 if (done < retired_[i].ticket) { 148 if (!retired_[i].timeline ||
149 ++i; 149 vk_.vkGetSemaphoreCounterValue(device_, retired_[i].timeline, &done) != VK_SUCCESS ||
150 continue; 150 done < retired_[i].ticket) {
151 ++i;
152 continue;
153 }
151 } 154 }
152 for (auto& chunk : retired_[i].chunks) { 155 for (auto& chunk : retired_[i].chunks) {
153 chunk.used = 0; 156 chunk.used = 0;
diff --git a/runtime/src/vulkan_present.h b/runtime/src/vulkan_present.h
index 5d59a301f..35f1cb556 100644
--- a/runtime/src/vulkan_present.h
+++ b/runtime/src/vulkan_present.h
@@ -75,9 +75,10 @@ class VulkanPresenter {
75public: 75public:
76 VulkanPresenter(VulkanContext& context, PFN_vkGetInstanceProcAddr get_instance, VkInstance instance, 76 VulkanPresenter(VulkanContext& context, PFN_vkGetInstanceProcAddr get_instance, VkInstance instance,
77 VkPhysicalDevice physical, VkQueue queue, std::uint32_t family, VkSurfaceKHR surface, 77 VkPhysicalDevice physical, VkQueue queue, std::uint32_t family, VkSurfaceKHR surface,
78 bool swapchain_maintenance1 = false) 78 bool swapchain_maintenance1 = false,
79 std::function<VkExtent2D()> extent_fn = nullptr)
79 : context_(context), instance_(instance), physical_(physical), queue_(queue), surface_(surface), 80 : context_(context), instance_(instance), physical_(physical), queue_(queue), surface_(surface),
80 maintenance1_(swapchain_maintenance1) { 81 maintenance1_(swapchain_maintenance1), extent_fn_(std::move(extent_fn)) {
81#define LEONIDA_INSTANCE_FN(name) name##_ = reinterpret_cast<PFN_##name>(get_instance(instance, #name)); 82#define LEONIDA_INSTANCE_FN(name) name##_ = reinterpret_cast<PFN_##name>(get_instance(instance, #name));
82 LEONIDA_INSTANCE_FN(vkGetPhysicalDeviceSurfaceSupportKHR) 83 LEONIDA_INSTANCE_FN(vkGetPhysicalDeviceSurfaceSupportKHR)
83 LEONIDA_INSTANCE_FN(vkGetPhysicalDeviceSurfaceCapabilitiesKHR) 84 LEONIDA_INSTANCE_FN(vkGetPhysicalDeviceSurfaceCapabilitiesKHR)
@@ -595,7 +596,21 @@ private:
595 tear_mode_ = VK_PRESENT_MODE_MAX_ENUM_KHR; 596 tear_mode_ = VK_PRESENT_MODE_MAX_ENUM_KHR;
596 VkSurfaceCapabilitiesKHR caps{}; 597 VkSurfaceCapabilitiesKHR caps{};
597 if (vkGetPhysicalDeviceSurfaceCapabilitiesKHR_(physical_, surface_, &caps) != VK_SUCCESS) return false; 598 if (vkGetPhysicalDeviceSurfaceCapabilitiesKHR_(physical_, surface_, &caps) != VK_SUCCESS) return false;
598 if (caps.currentExtent.width == 0 || caps.currentExtent.height == 0) { 599 VkExtent2D extent = caps.currentExtent;
600 // When the platform leaves the swapchain extent to the application (0xFFFFFFFF, as on Intel UHD / Win32 WSI),
601 // query the window client area or fall back to the last known extent, and clamp to the surface bounds (D3D-165).
602 if (extent.width == 0xFFFFFFFF || extent.height == 0xFFFFFFFF) {
603 if (extent_fn_) extent = extent_fn_();
604 // ponytail: if no window extent function was supplied, fall back to last extent_ or minImageExtent
605 if (extent.width == 0xFFFFFFFF || extent.height == 0xFFFFFFFF || (extent.width == 0 && extent.height == 0)) {
606 extent = extent_.width && extent_.height ? extent_ : caps.minImageExtent;
607 }
608 if (extent.width && extent.height) {
609 extent.width = std::clamp(extent.width, caps.minImageExtent.width, caps.maxImageExtent.width);
610 extent.height = std::clamp(extent.height, caps.minImageExtent.height, caps.maxImageExtent.height);
611 }
612 }
613 if (extent.width == 0 || extent.height == 0) {
599 release(swapchain_); 614 release(swapchain_);
600 swapchain_ = VK_NULL_HANDLE; 615 swapchain_ = VK_NULL_HANDLE;
601 vsync_ = vsync; 616 vsync_ = vsync;
@@ -659,7 +674,7 @@ private:
659 if (caps.maxImageCount) info.minImageCount = std::min(info.minImageCount, caps.maxImageCount); 674 if (caps.maxImageCount) info.minImageCount = std::min(info.minImageCount, caps.maxImageCount);
660 info.imageFormat = chosen.format; 675 info.imageFormat = chosen.format;
661 info.imageColorSpace = chosen.colorSpace; 676 info.imageColorSpace = chosen.colorSpace;
662 info.imageExtent = caps.currentExtent; 677 info.imageExtent = extent;
663 info.imageArrayLayers = 1; 678 info.imageArrayLayers = 1;
664 info.imageUsage = usage; 679 info.imageUsage = usage;
665 info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; 680 info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
@@ -713,7 +728,7 @@ private:
713 images_ = std::move(images); 728 images_ = std::move(images);
714 ready_ = std::move(ready); 729 ready_ = std::move(ready);
715 format_ = chosen.format; 730 format_ = chosen.format;
716 extent_ = caps.currentExtent; 731 extent_ = extent;
717 if (capture_) { 732 if (capture_) {
718 // A capture that cannot be made fails the recreation with the swapchain in place and stale_ still set. 733 // A capture that cannot be made fails the recreation with the swapchain in place and stale_ still set.
719 const bool four_bytes = format_ == VK_FORMAT_B8G8R8A8_UNORM || format_ == VK_FORMAT_R8G8B8A8_UNORM || 734 const bool four_bytes = format_ == VK_FORMAT_B8G8R8A8_UNORM || format_ == VK_FORMAT_R8G8B8A8_UNORM ||
@@ -812,6 +827,7 @@ private:
812 bool ok_ = false; 827 bool ok_ = false;
813 bool swapchain_srgb_ = false; // the swapchain format follows the source being presented (set once it exists) 828 bool swapchain_srgb_ = false; // the swapchain format follows the source being presented (set once it exists)
814 std::function<bool()> abort_; 829 std::function<bool()> abort_;
830 std::function<VkExtent2D()> extent_fn_;
815 std::map<VkFormat, VkFormatFeatureFlags> features_; 831 std::map<VkFormat, VkFormatFeatureFlags> features_;
816 bool warned_srgb_ = false; 832 bool warned_srgb_ = false;
817 bool capture_ = false; 833 bool capture_ = false;
diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h
index 89fe7381d..887c95b72 100644
--- a/runtime/src/vulkan_replay.h
+++ b/runtime/src/vulkan_replay.h
@@ -2007,8 +2007,15 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2007 // A depth plane footprint of a D24 texture stored as D32: words of 24-bit UNORM, floats in the image. 2007 // A depth plane footprint of a D24 texture stored as D32: words of 24-bit UNORM, floats in the image.
2008 const bool upload = texture_copy->src.footprint; 2008 const bool upload = texture_copy->src.footprint;
2009 const ResourceBinding& image = upload ? p.binding : p.source; 2009 const ResourceBinding& image = upload ? p.binding : p.source;
2010 if (result == ReplayResult::success && image.depth24_as_float && !p.buffer_image_copies.empty() && 2010 const bool depth24_footprint = result == ReplayResult::success && image.depth24_as_float &&
2011 p.buffer_image_copies[0].imageSubresource.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT) { 2011 !p.buffer_image_copies.empty() &&
2012 p.buffer_image_copies[0].imageSubresource.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT;
2013 const bool rgb96_footprint = result == ReplayResult::success && image.rgb96 &&
2014 !p.buffer_image_copies.empty();
2015 // These footprint conversions emit compute dispatches in emit(). Refuse them before allocating their
2016 // conversion scratch/descriptors because an active statistics query would include their CSInvocations.
2017 if (statistics_active && (depth24_footprint || rgb96_footprint)) return ReplayResult::unsupported;
2018 if (depth24_footprint) {
2012 const VkBufferImageCopy& region = p.buffer_image_copies[0]; 2019 const VkBufferImageCopy& region = p.buffer_image_copies[0];
2013 const ResourceBinding& buffer = upload ? p.source : p.binding; 2020 const ResourceBinding& buffer = upload ? p.source : p.binding;
2014 Depth24Job& job = p.depth24; 2021 Depth24Job& job = p.depth24;
@@ -2023,7 +2030,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2023 job.app_slice_words = job.app_row_words * (region.bufferImageHeight ? region.bufferImageHeight : job.height); 2030 job.app_slice_words = job.app_row_words * (region.bufferImageHeight ? region.bufferImageHeight : job.height);
2024 if (!vk.depth24_prepare || !vk.depth24_run || !vk.depth24_prepare(job, p.depth24_parts)) return ReplayResult::unsupported; 2031 if (!vk.depth24_prepare || !vk.depth24_run || !vk.depth24_prepare(job, p.depth24_parts)) return ReplayResult::unsupported;
2025 p.has_depth24 = true; 2032 p.has_depth24 = true;
2026 } else if (result == ReplayResult::success && image.rgb96 && !p.buffer_image_copies.empty()) { 2033 } else if (rgb96_footprint) {
2027 // A footprint of a 96-bit texture: 12-byte texels, 16 in the image. The same pass and scratch. 2034 // A footprint of a 96-bit texture: 12-byte texels, 16 in the image. The same pass and scratch.
2028 const VkBufferImageCopy& region = p.buffer_image_copies[0]; 2035 const VkBufferImageCopy& region = p.buffer_image_copies[0];
2029 const ResourceBinding& buffer = upload ? p.source : p.binding; 2036 const ResourceBinding& buffer = upload ? p.source : p.binding;
@@ -2041,9 +2048,6 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2041 if (!vk.depth24_prepare || !vk.depth24_run || !vk.depth24_prepare(job, p.depth24_parts)) return ReplayResult::unsupported; 2048 if (!vk.depth24_prepare || !vk.depth24_run || !vk.depth24_prepare(job, p.depth24_parts)) return ReplayResult::unsupported;
2042 p.has_depth24 = true; 2049 p.has_depth24 = true;
2043 } 2050 }
2044 // These footprint conversions emit compute dispatches in emit(). Until pipeline-statistics
2045 // segmentation can bracket arbitrary helper dispatches, don't let them inflate CSInvocations.
2046 if (p.has_depth24 && statistics_active) return ReplayResult::unsupported;
2047 } else { 2051 } else {
2048 result = detail::prepare_resource_copy(p); 2052 result = detail::prepare_resource_copy(p);
2049 } 2053 }
diff --git a/runtime/src/vulkan_scratch.h b/runtime/src/vulkan_scratch.h
index fe29d1a5c..4a8a59ddd 100644
--- a/runtime/src/vulkan_scratch.h
+++ b/runtime/src/vulkan_scratch.h
@@ -94,11 +94,14 @@ public:
94 // Keeps for reuse (or frees) the chunks of finished submissions. 94 // Keeps for reuse (or frees) the chunks of finished submissions.
95 void collect() { 95 void collect() {
96 for (std::size_t i = 0; i < retired_.size();) { 96 for (std::size_t i = 0; i < retired_.size();) {
97 std::uint64_t done = 0; 97 if (retired_[i].ticket != 0) {
98 if (retired_[i].timeline) vk_.vkGetSemaphoreCounterValue(device_, retired_[i].timeline, &done); 98 std::uint64_t done = 0;
99 if (done < retired_[i].ticket) { 99 if (!retired_[i].timeline ||
100 ++i; 100 vk_.vkGetSemaphoreCounterValue(device_, retired_[i].timeline, &done) != VK_SUCCESS ||
101 continue; 101 done < retired_[i].ticket) {
102 ++i;
103 continue;
104 }
102 } 105 }
103 for (auto& chunk : retired_[i].chunks) { 106 for (auto& chunk : retired_[i].chunks) {
104 chunk.used = 0; 107 chunk.used = 0;