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:
authorRain156 <77776581+Rain156@users.noreply.github.com>2026-11-24 21:26:25 +0800
committerRain156 <77776581+Rain156@users.noreply.github.com>2026-11-24 21:26:25 +0800
commitaa8be9aef20291e6faf6ed986d2b6691aad96abf (patch)
tree80e0224b761256cd2375d069089f1eb6413dcd7a /runtime/src
parentbe767b6889cb373cc695b67367644ea4370f8e9c (diff)
parentdb19bbd3455a757c3fe986c6e6db36998f275150 (diff)
Integrate the offline first-run UI runtime with current main and the published renderer fixes
Use the tagged pipeline variants and indexed quad expansion from #722 and #682 with the shared shader cache. Retain title-backed index uploads, cross-queue scratch sharing, amd64 console return conventions and the PC/console caller discriminator. The local shader build indexes native containers and includes the executable's embedded stages.
Diffstat (limited to 'runtime/src')
-rw-r--r--runtime/src/command_list.h9
-rw-r--r--runtime/src/depth24_fragment.h18
-rw-r--r--runtime/src/frame_pacer.h23
-rw-r--r--runtime/src/gfx10_descriptors.h24
-rw-r--r--runtime/src/gpu_label_memory.h77
-rw-r--r--runtime/src/main.cpp70
-rw-r--r--runtime/src/native_pso.h332
-rw-r--r--runtime/src/pe_loader.cpp450
-rw-r--r--runtime/src/pe_loader.h14
-rw-r--r--runtime/src/pipeline_cache_file.h67
-rw-r--r--runtime/src/pipeline_cache_store.h69
-rw-r--r--runtime/src/present_dump.h256
-rw-r--r--runtime/src/queue_families.h10
-rw-r--r--runtime/src/rgba4_fragment.h81
-rw-r--r--runtime/src/shader_library.h20
-rw-r--r--runtime/src/title_va_alias.h232
-rw-r--r--runtime/src/tls_host.cpp13
-rw-r--r--runtime/src/vulkan13_features.h6
-rw-r--r--runtime/src/vulkan_backend.h116
-rw-r--r--runtime/src/vulkan_bindless.h81
-rw-r--r--runtime/src/vulkan_gpu_labels.h156
-rw-r--r--runtime/src/vulkan_graphics_shader_modules.h61
-rw-r--r--runtime/src/vulkan_present.h40
-rw-r--r--runtime/src/vulkan_replay.h370
-rw-r--r--runtime/src/vulkan_scratch.h9
25 files changed, 2435 insertions, 169 deletions
diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h
index 595110f36..3e89e1cff 100644
--- a/runtime/src/command_list.h
+++ b/runtime/src/command_list.h
@@ -1,4 +1,5 @@
1#pragma once 1#pragma once
2#include "gpu_label_memory.h"
2 3
3// The command-list IR (docs/d3d12_vulkan.md section 3.2): what a D3D12 command list records, kept until 4// The command-list IR (docs/d3d12_vulkan.md section 3.2): what a D3D12 command list records, kept until
4// ExecuteCommandLists replays it on Vulkan (vulkan_replay.h). This slice covers legacy and enhanced barriers and 5// ExecuteCommandLists replays it on Vulkan (vulkan_replay.h). This slice covers legacy and enhanced barriers and
@@ -517,6 +518,7 @@ struct UavView {
517 std::uint32_t mip; // texture 518 std::uint32_t mip; // texture
518 std::uint32_t first_layer; 519 std::uint32_t first_layer;
519 std::uint32_t layer_count; 520 std::uint32_t layer_count;
521 bool exact_clear_format = false; // newly exposed 1D/3D UAVs: do not clear via a different backing format
520}; 522};
521 523
522// ClearUnorderedAccessViewUint / ...Float; the resource must be in unordered_access state at execution. values are 524// ClearUnorderedAccessViewUint / ...Float; the resource must be in unordered_access state at execution. values are
@@ -657,7 +659,7 @@ struct AccelerationStructurePostbuild {
657using Command = std::variant<TransitionBarrier, UavBarrier, AliasingBarrier, GlobalBarrier, BufferBarrier, 659using Command = std::variant<TransitionBarrier, UavBarrier, AliasingBarrier, GlobalBarrier, BufferBarrier,
658 TextureBarrier, ClearRenderTarget, ClearDepthStencil, CopyBuffer, CopyTexture, 660 TextureBarrier, ClearRenderTarget, ClearDepthStencil, CopyBuffer, CopyTexture,
659 CopyResource, ResolveSubresource, Predication, ClearUnorderedAccess, DiscardResource, 661 CopyResource, ResolveSubresource, Predication, ClearUnorderedAccess, DiscardResource,
660 WriteImmediate, AtomicCopyBuffer, BeginQuery, EndQuery, ResolveQueries, DebugMarker, 662 WriteImmediate, label::Write, AtomicCopyBuffer, BeginQuery, EndQuery, ResolveQueries, DebugMarker,
661 ExecuteIndirect, BuildAccelerationStructure, Dispatch, Draw, CopyAccelerationStructure, 663 ExecuteIndirect, BuildAccelerationStructure, Dispatch, Draw, CopyAccelerationStructure,
662 AccelerationStructurePostbuild>; 664 AccelerationStructurePostbuild>;
663 665
@@ -786,6 +788,11 @@ public:
786 } 788 }
787 789
788 // WriteBufferImmediate: D3D12 requires a 4-byte aligned, non-null address and one of the three modes. 790 // WriteBufferImmediate: D3D12 requires a 4-byte aligned, non-null address and one of the three modes.
791 bool write_gpu_label(const label::Write& write) {
792 if(write.target.owner.expired() || write.clock>2) return false;
793 return append(write);
794 }
795
789 bool write_immediate(const WriteImmediate& write) { 796 bool write_immediate(const WriteImmediate& write) {
790 if (!write.address || write.address % 4 || write.mode > write_immediate_mode::marker_out) return false; 797 if (!write.address || write.address % 4 || write.mode > write_immediate_mode::marker_out) return false;
791 return append(write); 798 return append(write);
diff --git a/runtime/src/depth24_fragment.h b/runtime/src/depth24_fragment.h
index 10f0dada8..d32f975b2 100644
--- a/runtime/src/depth24_fragment.h
+++ b/runtime/src/depth24_fragment.h
@@ -37,12 +37,13 @@ struct Depth24Bias {
37 int constant = 0; // D3D12_RASTERIZER_DESC::DepthBias 37 int constant = 0; // D3D12_RASTERIZER_DESC::DepthBias
38 float slope = 0.0f; // SlopeScaledDepthBias 38 float slope = 0.0f; // SlopeScaledDepthBias
39 float clamp = 0.0f; // DepthBiasClamp: > 0 caps the bias, < 0 floors it, 0 leaves it 39 float clamp = 0.0f; // DepthBiasClamp: > 0 caps the bias, < 0 floors it, 0 leaves it
40 float levels = 16777215.0f;
40 bool any() const { return constant != 0 || slope != 0.0f; } 41 bool any() const { return constant != 0 || slope != 0.0f; }
41}; 42};
42 43
43// D3D's constant term in float: (float)DepthBias * r, with r the float nearest 1 / (2^24 - 1). 44// D3D's constant term in float: (float)DepthBias * r, with r the float nearest 1 / (2^24 - 1).
44inline float depth24_bias_constant(int bias) { 45inline float depth24_bias_constant(int bias, float levels=16777215.0f) {
45 return float(bias) * float(1.0 / 16777215.0); 46 return float(bias) * float(1.0 / double(levels));
46} 47}
47 48
48namespace spirv24 { 49namespace spirv24 {
@@ -141,7 +142,7 @@ private:
141// The edit, on a parsed module. Globals are collected first and spliced in at their section's end. 142// The edit, on a parsed module. Globals are collected first and spliced in at their section's end.
142class Patch { 143class Patch {
143public: 144public:
144 Patch(Module& m, std::uint32_t entry) : m_(m), entry_(entry) { 145 Patch(Module& m, std::uint32_t entry, float levels) : m_(m), entry_(entry), levels_(levels) {
145 // Copies: apply() moves the module's instructions while the code at returns still looks types up. 146 // Copies: apply() moves the module's instructions while the code at returns still looks types up.
146 for (const Inst& i : m.insts()) { 147 for (const Inst& i : m.insts()) {
147 if (opcode(i) == op_function) break; 148 if (opcode(i) == op_function) break;
@@ -185,7 +186,7 @@ public:
185 void prime_quantise() { 186 void prime_quantise() {
186 t_bool(); 187 t_bool();
187 glsl(); 188 glsl();
188 for (float f : {16777215.0f, 0.0f}) f32(f); 189 for (float f : {levels_, 0.0f}) f32(f);
189 for (std::uint32_t u : {0x3f800000u, 0xffffffu, 0x7f800000u, 0u, 23u, 1u, 80u}) u32(u); 190 for (std::uint32_t u : {0x3f800000u, 0xffffffu, 0x7f800000u, 0u, 23u, 1u, 80u}) u32(u);
190 } 191 }
191 std::uint32_t f32(float f) { return constant(t_float(), bits(f)); } 192 std::uint32_t f32(float f) { return constant(t_float(), bits(f)); }
@@ -248,11 +249,11 @@ public:
248 std::uint32_t quantise(std::vector<Inst>& code, std::uint32_t z) { 249 std::uint32_t quantise(std::vector<Inst>& code, std::uint32_t z) {
249 const std::uint32_t tf = t_float(), tu = t_uint(), tb = t_bool(); 250 const std::uint32_t tf = t_float(), tu = t_uint(), tb = t_bool();
250 const std::uint32_t b = emit(code, op_bitcast, tu, {z}); 251 const std::uint32_t b = emit(code, op_bitcast, tu, {z});
251 const std::uint32_t product = emit(code, op_f_mul, tf, {z, f32(16777215.0f)}); 252 const std::uint32_t product = emit(code, op_f_mul, tf, {z, f32(levels_)});
252 const std::uint32_t rounded = ext(code, tf, glsl_round_even, {product}); 253 const std::uint32_t rounded = ext(code, tf, glsl_round_even, {product});
253 // Clamped before the conversion so an out-of-range float never reaches OpConvertFToU (undefined there). 254 // Clamped before the conversion so an out-of-range float never reaches OpConvertFToU (undefined there).
254 const std::uint32_t safe = ext(code, tf, glsl_fmin, {ext(code, tf, glsl_fmax, {rounded, f32(0.0f)}), 255 const std::uint32_t safe = ext(code, tf, glsl_fmin, {ext(code, tf, glsl_fmax, {rounded, f32(0.0f)}),
255 f32(16777215.0f)}); 256 f32(levels_)});
256 const std::uint32_t code_mid = emit(code, op_convert_f_to_u, tu, {safe}); 257 const std::uint32_t code_mid = emit(code, op_convert_f_to_u, tu, {safe});
257 const std::uint32_t at_least_one = emit(code, op_u_greater_than_equal, tb, {b, u32(0x3f800000u)}); 258 const std::uint32_t at_least_one = emit(code, op_u_greater_than_equal, tb, {b, u32(0x3f800000u)});
258 const std::uint32_t code_hi = emit(code, op_select, tu, {at_least_one, u32(0xffffffu), code_mid}); 259 const std::uint32_t code_hi = emit(code, op_select, tu, {at_least_one, u32(0xffffffu), code_mid});
@@ -327,6 +328,7 @@ public:
327 } 328 }
328 329
329private: 330private:
331 float levels_;
330 Module& m_; 332 Module& m_;
331 std::uint32_t entry_; 333 std::uint32_t entry_;
332 std::vector<Inst> existing_; 334 std::vector<Inst> existing_;
@@ -369,7 +371,7 @@ inline std::vector<std::uint32_t> depth24_patch_fragment(const std::vector<std::
369 if (opcode(i) == op_function) break; 371 if (opcode(i) == op_function) break;
370 } 372 }
371 373
372 Patch p(m, entry); 374 Patch p(m, entry, bias.levels);
373 const std::uint32_t tf = p.t_float(); 375 const std::uint32_t tf = p.t_float();
374 p.prime_quantise(); 376 p.prime_quantise();
375 std::uint32_t frag_depth = p.builtin_variable(builtin_frag_depth); 377 std::uint32_t frag_depth = p.builtin_variable(builtin_frag_depth);
@@ -396,7 +398,7 @@ inline std::vector<std::uint32_t> depth24_patch_fragment(const std::vector<std::
396 const std::uint32_t dy = p.ext(entry_code, tf, glsl_fabs, {p.emit(entry_code, op_dpdy, tf, {z})}); 398 const std::uint32_t dy = p.ext(entry_code, tf, glsl_fabs, {p.emit(entry_code, op_dpdy, tf, {z})});
397 const std::uint32_t max_slope = p.ext(entry_code, tf, glsl_fmax, {dx, dy}); 399 const std::uint32_t max_slope = p.ext(entry_code, tf, glsl_fmax, {dx, dy});
398 std::uint32_t amount = p.emit(entry_code, op_f_mul, tf, {p.f32(bias.slope), max_slope}); 400 std::uint32_t amount = p.emit(entry_code, op_f_mul, tf, {p.f32(bias.slope), max_slope});
399 amount = p.emit(entry_code, op_f_add, tf, {amount, p.f32(depth24_bias_constant(bias.constant))}); 401 amount = p.emit(entry_code, op_f_add, tf, {amount, p.f32(depth24_bias_constant(bias.constant,bias.levels))});
400 if (bias.clamp > 0.0f) amount = p.ext(entry_code, tf, glsl_fmin, {amount, p.f32(bias.clamp)}); 402 if (bias.clamp > 0.0f) amount = p.ext(entry_code, tf, glsl_fmin, {amount, p.f32(bias.clamp)});
401 if (bias.clamp < 0.0f) amount = p.ext(entry_code, tf, glsl_fmax, {amount, p.f32(bias.clamp)}); 403 if (bias.clamp < 0.0f) amount = p.ext(entry_code, tf, glsl_fmax, {amount, p.f32(bias.clamp)});
402 z = p.emit(entry_code, op_f_add, tf, {z, amount}); 404 z = p.emit(entry_code, op_f_add, tf, {z, amount});
diff --git a/runtime/src/frame_pacer.h b/runtime/src/frame_pacer.h
index 5de8e9b79..6e14c60d5 100644
--- a/runtime/src/frame_pacer.h
+++ b/runtime/src/frame_pacer.h
@@ -106,6 +106,8 @@ private:
106 106
107// Provisional definitions of ours: the real constants and layouts of the console API are unmeasured. 107// Provisional definitions of ours: the real constants and layouts of the console API are unmeasured.
108inline constexpr std::uint32_t frame_event_origin = 0; 108inline constexpr std::uint32_t frame_event_origin = 0;
109// WaitFrameEventX flag 2 with timeout 0 is the retail title's poll for the current token, which it asserts succeeds.
110inline constexpr std::uint32_t wait_flag_current_token = 0x2;
109// Statistics types (bit mask). Interval and render entries are never produced here. 111// Statistics types (bit mask). Interval and render entries are never produced here.
110inline constexpr std::uint32_t stat_frame_interval = 0x01; 112inline constexpr std::uint32_t stat_frame_interval = 0x01;
111inline constexpr std::uint32_t stat_frame_event = 0x02; 113inline constexpr std::uint32_t stat_frame_event = 0x02;
@@ -216,9 +218,9 @@ public:
216 // alone then. invalid_state when nothing is registered, the pacer is suspended, or one of those happens while waiting. 218 // alone then. invalid_state when nothing is registered, the pacer is suspended, or one of those happens while waiting.
217 std::int32_t wait_frame_event(std::uint32_t event, std::uint32_t timeout_ms, std::uint32_t flags, 219 std::int32_t wait_frame_event(std::uint32_t event, std::uint32_t timeout_ms, std::uint32_t flags,
218 std::uint64_t* token) { 220 std::uint64_t* token) {
219 (void)flags;
220 if (event != frame_event_origin || !token) return pacer_hr::invalid_arg; 221 if (event != frame_event_origin || !token) return pacer_hr::invalid_arg;
221 std::unique_lock lock(mutex_); 222 std::unique_lock lock(mutex_);
223 if (flags & wait_flag_current_token) return current_token_locked(token);
222 ++waiters_; 224 ++waiters_;
223 const std::int32_t result = wait_locked(lock, timeout_ms, token); 225 const std::int32_t result = wait_locked(lock, timeout_ms, token);
224 if (--waiters_ == 0) cv_.notify_all(); 226 if (--waiters_ == 0) cv_.notify_all();
@@ -412,6 +414,25 @@ private:
412 } 414 }
413 } 415 }
414 416
417 // Never blocks: a fresh token for the newest passed origin, with no wait for the next origin or the latency.
418 std::int32_t current_token_locked(std::uint64_t* token) {
419 if (shutdown_ || suspended_) return pacer_hr::invalid_state;
420 *token = tokens_->issue();
421 if (!interval_set_ || !armed_) return pacer_hr::ok;
422 const std::uint64_t now = clock_.now_us();
423 retire_locked(now);
424 const std::uint64_t first = epoch_us_ + offset_us_;
425 const std::int64_t newest = now >= first ? std::int64_t((now - first) / period_us_) : 0;
426 last_origin_ = std::max(last_origin_, newest);
427 Record record;
428 record.token = *token;
429 record.origin_us = first + std::uint64_t(last_origin_) * period_us_;
430 record.due_us = record.origin_us - offset_us_ + period_us_;
431 records_.push_back(record);
432 if (records_.size() > 64) records_.pop_front();
433 return pacer_hr::ok;
434 }
435
415 std::int32_t wait_locked(std::unique_lock<std::mutex>& lock, std::uint32_t timeout_ms, std::uint64_t* token) { 436 std::int32_t wait_locked(std::unique_lock<std::mutex>& lock, std::uint32_t timeout_ms, std::uint64_t* token) {
416 const std::uint64_t start = clock_.now_us(); 437 const std::uint64_t start = clock_.now_us();
417 const std::uint64_t give_up = timeout_ms == infinite_timeout_ms ? no_deadline 438 const std::uint64_t give_up = timeout_ms == infinite_timeout_ms ? no_deadline
diff --git a/runtime/src/gfx10_descriptors.h b/runtime/src/gfx10_descriptors.h
index b225cddef..85ea2edfc 100644
--- a/runtime/src/gfx10_descriptors.h
+++ b/runtime/src/gfx10_descriptors.h
@@ -146,6 +146,26 @@ inline ImageWords encode(const Image& image) {
146// TYPE names an image, so these eight dwords are a T# and not a V# followed by something else. 146// TYPE names an image, so these eight dwords are a T# and not a V# followed by something else.
147inline constexpr bool is_image(const ImageWords& words) { return detail::get(words[3], 28, 4) >= 8; } 147inline constexpr bool is_image(const ImageWords& words) { return detail::get(words[3], 28, 4) >= 8; }
148 148
149// Synthetic volume UAV metadata distinguishes the storage view from SRVs of the same mip, and distinct W
150// ranges from one another. Sampled fetches use it because Vulkan only applies slicing to storage views.
151// WORD4[31] is reserved on GFX10/GFX103; hardware uses WORD7 for metadata addresses. DEPTH and BASE_ARRAY
152// stay unchanged. D3D12 depth is at most 2048, so count - 1 and offset fit 11 bits.
153inline constexpr std::uint32_t volume_uav_flag = 0x80000000;
154inline constexpr std::uint32_t volume_uav_tag = 0xD7800000;
155inline constexpr std::uint32_t volume_uav_tag_mask = 0xff800000;
156// RGB9E5 emulation uses R32_UINT storage, not the logical float format in T# word 1. The same tag marks packed
157// 1D-family UAVs (without a W range). No ordinary SRV or raw hardware T# has this synthetic metadata.
158inline constexpr std::uint32_t packed_uav_flag = 0x00400000;
159inline constexpr std::uint32_t volume_uav_word(std::uint32_t offset, std::uint32_t count) {
160 return volume_uav_tag | ((count - 1) << 11) | offset;
161}
162inline constexpr bool partial_volume_uav(const ImageWords& words, const Image& image) {
163 const auto mip_depth = image.depth >> image.first_mip;
164 return image.type == ImageType::image_3d && (words[4] & volume_uav_flag) &&
165 (words[7] & volume_uav_tag_mask) == volume_uav_tag &&
166 (words[7] & ~packed_uav_flag) != volume_uav_word(0, mip_depth ? mip_depth : 1u);
167}
168
149inline constexpr float image_min_lod(const ImageWords& words) { 169inline constexpr float image_min_lod(const ImageWords& words) {
150 return float(detail::get(words[1], 8, 12)) / 256.0f; 170 return float(detail::get(words[1], 8, 12)) / 256.0f;
151} 171}
@@ -218,6 +238,7 @@ struct FormatRow {
218}; 238};
219 239
220inline constexpr Swizzle channels_r{select_x, select_zero, select_zero, select_one}; 240inline constexpr Swizzle channels_r{select_x, select_zero, select_zero, select_one};
241inline constexpr Swizzle channels_a{select_zero, select_zero, select_zero, select_x};
221inline constexpr Swizzle channels_rg{select_x, select_y, select_zero, select_one}; 242inline constexpr Swizzle channels_rg{select_x, select_y, select_zero, select_one};
222inline constexpr Swizzle channels_rgb{select_x, select_y, select_z, select_one}; 243inline constexpr Swizzle channels_rgb{select_x, select_y, select_z, select_one};
223inline constexpr Swizzle channels_rgba = identity_swizzle; 244inline constexpr Swizzle channels_rgba = identity_swizzle;
@@ -227,6 +248,9 @@ inline constexpr Swizzle channels_abgr{select_w, select_z, select_y, select_x};
227 248
228inline constexpr FormatRow format_table[] = { 249inline constexpr FormatRow format_table[] = {
229 {1, VK_FORMAT_R8_UNORM, channels_r}, // GFX10_FORMAT_8_UNORM 250 {1, VK_FORMAT_R8_UNORM, channels_r}, // GFX10_FORMAT_8_UNORM
251#ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME
252 {1, VK_FORMAT_A8_UNORM_KHR, channels_a}, // GFX10_FORMAT_8_UNORM (an A8 render target)
253#endif
230 {2, VK_FORMAT_R8_SNORM, channels_r}, // GFX10_FORMAT_8_SNORM 254 {2, VK_FORMAT_R8_SNORM, channels_r}, // GFX10_FORMAT_8_SNORM
231 {3, VK_FORMAT_R8_USCALED, channels_r}, // GFX10_FORMAT_8_USCALED 255 {3, VK_FORMAT_R8_USCALED, channels_r}, // GFX10_FORMAT_8_USCALED
232 {4, VK_FORMAT_R8_SSCALED, channels_r}, // GFX10_FORMAT_8_SSCALED 256 {4, VK_FORMAT_R8_SSCALED, channels_r}, // GFX10_FORMAT_8_SSCALED
diff --git a/runtime/src/gpu_label_memory.h b/runtime/src/gpu_label_memory.h
new file mode 100644
index 000000000..890aadf7e
--- /dev/null
+++ b/runtime/src/gpu_label_memory.h
@@ -0,0 +1,77 @@
1#pragma once
2#include <cstdint>
3#include <map>
4#include <memory>
5#include <mutex>
6#include <limits>
7
8namespace leonida::label {
9struct Region {
10 std::uintptr_t begin, end, allocation_base;
11 bool heap;
12 std::uint64_t generation=1;
13};
14struct Target {
15 std::weak_ptr<const Region> owner;
16 std::uintptr_t address = 0;
17 unsigned bytes = 0;
18 std::uint64_t generation=0;
19};
20struct Write {
21 Target target;
22 std::uint64_t value{};
23 unsigned clock{}; // 0: supplied value; 1: GPU timestamp; 2: system timestamp
24};
25class Memory {
26 std::mutex mutex_;
27 std::map<std::uintptr_t,std::shared_ptr<Region>> regions_;
28public:
29 void track(std::uintptr_t base,std::uintptr_t bytes,std::uintptr_t allocation_base,bool heap) {
30 if (!base || !bytes || !allocation_base || bytes>std::numeric_limits<std::uintptr_t>::max()-base) return;
31 const auto end=base+bytes;
32 std::lock_guard lock(mutex_);
33 auto previous=regions_.upper_bound(base);
34 if (!heap && previous!=regions_.begin()) {
35 --previous;
36 const auto& r=*previous->second;
37 if (!r.heap && r.allocation_base==allocation_base && base>=r.begin && end<=r.end) return;
38 }
39 regions_[base]=std::make_shared<Region>(Region{base,end,allocation_base,heap});
40 }
41 void release_heap(std::uintptr_t base) {
42 std::lock_guard lock(mutex_);regions_.erase(base);
43 }
44 template<class Release> bool release_pages(std::uintptr_t base,std::uintptr_t bytes,bool entire,Release&& release) {
45 std::lock_guard lock(mutex_);
46 if(!release()) return false;
47 for(auto i=regions_.begin();i!=regions_.end();) {
48 const auto& r=*i->second;
49 if(r.heap || (entire ? r.allocation_base!=base :
50 (!bytes ? r.allocation_base!=base : (base>=r.end || (base<r.begin && r.begin-base>=bytes))))) { ++i; continue; }
51 if(entire || i->second->generation==std::numeric_limits<std::uint64_t>::max()) i=regions_.erase(i);
52 else { ++i->second->generation; ++i; }
53 }
54 return true;
55 }
56 Target capture(std::uintptr_t address,unsigned bytes) {
57 if((bytes!=4 && bytes!=8) || (address&(bytes-1)))return {};
58 std::lock_guard lock(mutex_);
59 auto it=regions_.upper_bound(address);
60 while(it!=regions_.begin()) {
61 --it;const auto& r=*it->second;
62 if(address<r.end && r.end-address>=bytes) return {it->second,address,bytes,r.generation};
63 }
64 return {};
65 }
66 template<class Store> bool publish(const Target& target,Store&& store) {
67 std::lock_guard lock(mutex_);
68 const auto region=target.owner.lock();
69 if(!region || target.generation!=region->generation || (target.bytes!=4 && target.bytes!=8) || (target.address&(target.bytes-1)) ||
70 target.address<region->begin || target.address>=region->end || region->end-target.address<target.bytes) return false;
71 const auto it=regions_.find(region->begin);
72 if(it==regions_.end() || it->second!=region) return false;
73 return store(target.address,target.bytes,region->allocation_base);
74 }
75};
76inline Memory& memory(){static Memory m;return m;}
77} // namespace leonida::label
diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp
index 098a8ee40..8ea202fa0 100644
--- a/runtime/src/main.cpp
+++ b/runtime/src/main.cpp
@@ -52,10 +52,50 @@ const char* binding_name(rt::Binding b) {
52 } 52 }
53} 53}
54 54
55// Module TLS index 0 for the game's executable (rt::reserve_tls_index0), from the CRT's initializer table: .CRT$XCT
56// runs after the C runtime is set up and before every C++ dynamic initializer of gta6rt (.CRT$XCU), so before any of
57// gta6rt's code can have started a thread. The frames above it (wmainCRTStartup, __scrt_common_main_seh, _initterm)
58// hold no TLS slot address. The result is read again where an image is run.
59void __cdecl reserve_tls_index0_at_start() { rt::reserve_tls_index0(); }
60#pragma section(".CRT$XCT", read)
61extern "C" __declspec(allocate(".CRT$XCT")) void(__cdecl* const gta6rt_reserve_tls_index0)() =
62 reserve_tls_index0_at_start;
63#pragma comment(linker, "/INCLUDE:gta6rt_reserve_tls_index0")
64
65// Select the settings used to display the offline first-run UI. Keep explicit caller settings.
66bool configure_first_run_ui(const std::filesystem::path& package, std::filesystem::path& overlay) {
67 const auto set_default = [](const wchar_t* name, const wchar_t* value) {
68 return GetEnvironmentVariableW(name, nullptr, 0) != 0 || _wputenv_s(name, value) == 0;
69 };
70 const struct { const wchar_t* name; const wchar_t* value; } settings[] = {
71 {L"LEONIDA_D3D12", L"vulkan"}, {L"LEONIDA_ARENA_MB", L"2048"},
72 {L"LEONIDA_GRAPHICS_STAGE_LAYOUT", L"1"}, {L"LEONIDA_PIPELINE_COMPILE", L"on-demand"},
73 {L"LEONIDA_GPU_LABELS", L"1"}, {L"LEONIDA_FRAME_PACING", L"1"},
74 {L"LEONIDA_LOCAL_SPEECH", L"1"}, {L"LEONIDA_KEYBOARD_PAD", L"always"},
75 };
76 for (const auto& setting : settings) {
77 if (!set_default(setting.name, setting.value)) return false;
78 }
79 std::wstring executable(32768, L'\0');
80 const DWORD length = GetModuleFileNameW(nullptr, executable.data(), static_cast<DWORD>(executable.size()));
81 if (!length || length >= executable.size()) return false;
82 executable.resize(length);
83 const auto state = std::filesystem::path(executable).parent_path() / L"first-run-ui";
84 if (overlay.empty()) overlay = state / L"overlay";
85 if (!GetEnvironmentVariableW(L"LEONIDA_XMEM_BACKING_DIR", nullptr, 0)) {
86 std::error_code error;
87 const auto backing = state / L"xmem";
88 std::filesystem::create_directories(backing, error);
89 if (error || !set_default(L"LEONIDA_XMEM_BACKING_DIR", backing.c_str())) return false;
90 }
91 return SetCurrentDirectoryW(package.c_str()) != FALSE;
92}
93
55int usage() { 94int usage() {
56 std::fprintf(stderr, 95 std::fprintf(stderr,
57 "usage: gta6rt --dry-run <image> [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace FILE]\n" 96 "usage: gta6rt --dry-run <image> [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace FILE]\n"
58 " gta6rt --init <image> [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace-d3d12] [--trace FILE]\n" 97 " gta6rt --init <image> [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace-d3d12] [--trace FILE]\n"
98 " gta6rt --first-run-ui <exe> [--game-dir DIR] [--overlay DIR] [--trace FILE]\n"
59 " gta6rt --run <exe> [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace-d3d12] [--trace FILE] [-- game arguments...]\n"); 99 " gta6rt --run <exe> [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace-d3d12] [--trace FILE] [-- game arguments...]\n");
60 return 2; 100 return 2;
61} 101}
@@ -67,7 +107,7 @@ int wmain(int argc, wchar_t** argv) {
67 uint32_t archetype_lookup_rva = 0; // --archetype-lookup RVA[,ARG]: the game's archetype lookup by hash 107 uint32_t archetype_lookup_rva = 0; // --archetype-lookup RVA[,ARG]: the game's archetype lookup by hash
68 int archetype_lookup_arg = 0; 108 int archetype_lookup_arg = 0;
69 uint32_t view_mode_getter_rva = 0; // --view-mode-getter RVA: the game's view mode of a camera context 109 uint32_t view_mode_getter_rva = 0; // --view-mode-getter RVA: the game's view mode of a camera context
70 bool dry_run = false, init = false, run = false, trace_d3d12 = false; 110 bool dry_run = false, init = false, run = false, trace_d3d12 = false, first_run_ui = false;
71 std::vector<std::wstring> game_args; // wide: path::string() throws on a character the code page lacks (RT-84) 111 std::vector<std::wstring> game_args; // wide: path::string() throws on a character the code page lacks (RT-84)
72 std::wstring trace_file; 112 std::wstring trace_file;
73 for (int i = 1; i < argc; ++i) { 113 for (int i = 1; i < argc; ++i) {
@@ -78,6 +118,7 @@ int wmain(int argc, wchar_t** argv) {
78 } 118 }
79 if (a == L"--dry-run") dry_run = true; 119 if (a == L"--dry-run") dry_run = true;
80 else if (a == L"--init") init = true; 120 else if (a == L"--init") init = true;
121 else if (a == L"--first-run-ui") first_run_ui = true;
81 else if (a == L"--run") run = true; 122 else if (a == L"--run") run = true;
82 else if (a == L"--trace-d3d12") trace_d3d12 = true; 123 else if (a == L"--trace-d3d12") trace_d3d12 = true;
83 else if (a == L"--trace" && i + 1 < argc) trace_file = argv[++i]; 124 else if (a == L"--trace" && i + 1 < argc) trace_file = argv[++i];
@@ -104,7 +145,8 @@ int wmain(int argc, wchar_t** argv) {
104 } 145 }
105 if (image.empty()) return usage(); 146 if (image.empty()) return usage();
106 // Exactly one mode: --dry-run --run would otherwise initialise the modules and call the entry point. 147 // Exactly one mode: --dry-run --run would otherwise initialise the modules and call the entry point.
107 if (dry_run + init + run != 1) return usage(); 148 if (dry_run + init + run + first_run_ui != 1) return usage();
149 run = run || first_run_ui;
108 // The game runs AVX code from its TLS callbacks on; without AVX that is a bare 0xC000001D (src/host_cpu.h). 150 // The game runs AVX code from its TLS callbacks on; without AVX that is a bare 0xC000001D (src/host_cpu.h).
109 if ((init || run) && !rt::host_cpu::check_skipped()) 151 if ((init || run) && !rt::host_cpu::check_skipped())
110 if (const auto missing = rt::host_cpu::missing_host_features(); !missing.empty()) { 152 if (const auto missing = rt::host_cpu::missing_host_features(); !missing.empty()) {
@@ -119,6 +161,11 @@ int wmain(int argc, wchar_t** argv) {
119 std::filesystem::path a = std::filesystem::absolute(p, ec); 161 std::filesystem::path a = std::filesystem::absolute(p, ec);
120 return ec ? p : a; 162 return ec ? p : a;
121 }; 163 };
164 if (first_run_ui) {
165 image = absolute_or_same(image);
166 if (!mods_dir.empty()) mods_dir = absolute_or_same(mods_dir);
167 if (!trace_file.empty()) trace_file = absolute_or_same(trace_file).wstring();
168 }
122 game_dir = game_dir.empty() ? absolute_or_same(image).parent_path() : absolute_or_same(game_dir); 169 game_dir = game_dir.empty() ? absolute_or_same(image).parent_path() : absolute_or_same(game_dir);
123 if (!overlay_dir.empty()) overlay_dir = absolute_or_same(overlay_dir); 170 if (!overlay_dir.empty()) overlay_dir = absolute_or_same(overlay_dir);
124 // LEONIDA_SHADERS too: the D3D12 device reads it at the title's first pipeline state, after it may have moved. 171 // LEONIDA_SHADERS too: the D3D12 device reads it at the title's first pipeline state, after it may have moved.
@@ -135,6 +182,10 @@ int wmain(int argc, wchar_t** argv) {
135 if (!rt::base_reservation::inherited()) 182 if (!rt::base_reservation::inherited())
136 if (const auto range = rt::base_reservation::needed(image)) return rt::base_reservation::relaunch(*range); 183 if (const auto range = rt::base_reservation::needed(image)) return rt::base_reservation::relaunch(*range);
137 // GAME: paths read under --game-dir; whatever a title writes lands in the overlay, never in the package. 184 // GAME: paths read under --game-dir; whatever a title writes lands in the overlay, never in the package.
185 if (first_run_ui && !configure_first_run_ui(game_dir, overlay_dir)) {
186 std::fprintf(stderr, "cannot initialize the first-run UI paths or graphics settings\n");
187 return 1;
188 }
138 if (overlay_dir.empty()) overlay_dir = game_dir / "overlay"; 189 if (overlay_dir.empty()) overlay_dir = game_dir / "overlay";
139 rt::fs::configure(game_dir, overlay_dir); 190 rt::fs::configure(game_dir, overlay_dir);
140 // Mods (docs/modding.md): <folder of gta6rt.exe>\mods unless --mods names another. Loaded and reported here; 191 // Mods (docs/modding.md): <folder of gta6rt.exe>\mods unless --mods names another. Loaded and reported here;
@@ -168,6 +219,7 @@ int wmain(int argc, wchar_t** argv) {
168 rt::d3d12_trace::set_enabled(trace_d3d12); 219 rt::d3d12_trace::set_enabled(trace_d3d12);
169 // Slot 133 imports the title's pages; xmem commits them on first touch, so they are committed first. 220 // Slot 133 imports the title's pages; xmem commits them on first touch, so they are committed first.
170 rt::d3d12_xs::set_placed_at_va_pages_hook(&rt::xmem::commit_physical_range); 221 rt::d3d12_xs::set_placed_at_va_pages_hook(&rt::xmem::commit_physical_range);
222 rt::d3d12_xs::set_texture_page_provider(&rt::xmem::pin_mapped_data);
171 if (int trace_error = 0; !trace_file.empty() && !rt::startup_trace::open(trace_file.c_str(), &trace_error)) { 223 if (int trace_error = 0; !trace_file.empty() && !rt::startup_trace::open(trace_file.c_str(), &trace_error)) {
172 std::fprintf(stderr, trace_error == EEXIST ? "error: the trace file already exists; --trace only creates a new file\n" 224 std::fprintf(stderr, trace_error == EEXIST ? "error: the trace file already exists; --trace only creates a new file\n"
173 : "error: cannot create the trace file\n"); 225 : "error: cannot create the trace file\n");
@@ -186,6 +238,20 @@ int wmain(int argc, wchar_t** argv) {
186 try { 238 try {
187 rt::Loader loader(game_dir); 239 rt::Loader loader(game_dir);
188 rt::Module& main_module = loader.load(image); // maps, binds and installs TLS; runs no image code 240 rt::Module& main_module = loader.load(image); // maps, binds and installs TLS; runs no image code
241 // An executable with TLS that did not get index 0: its /GA code would read and write the TLS in slot 0, which
242 // is gta6rt's own (or another executable's), so no code of it may run.
243 const auto* main_nt = reinterpret_cast<const IMAGE_NT_HEADERS64*>(
244 main_module.base + reinterpret_cast<const IMAGE_DOS_HEADER*>(main_module.base)->e_lfanew);
245 const bool main_is_exe = (main_nt->FileHeader.Characteristics & IMAGE_FILE_DLL) == 0;
246 if ((init || run) && main_is_exe && main_module.tls_slot != rt::kNoTlsIndex && main_module.tls_index != 0) {
247 std::string why;
248 if (rt::reserve_tls_index0(&why)) why = "another mapped executable holds it";
249 std::fprintf(stderr,
250 "error: %s cannot have module TLS index 0 (%s); code built with /GA would read and write "
251 "another module's TLS through slot 0, so it is not run\n",
252 main_module.name.c_str(), why.c_str());
253 return 1;
254 }
189 // The mods' archetype swaps (docs/modding.md): hooked here, before any image code runs, when the lookup's RVA 255 // The mods' archetype swaps (docs/modding.md): hooked here, before any image code runs, when the lookup's RVA
190 // for this executable is given. The count of redirected calls shows whether the RVA is the real lookup. 256 // for this executable is given. The count of redirected calls shows whether the RVA is the real lookup.
191 if (view_mode_getter_rva) { 257 if (view_mode_getter_rva) {
diff --git a/runtime/src/native_pso.h b/runtime/src/native_pso.h
new file mode 100644
index 000000000..88a260ca8
--- /dev/null
+++ b/runtime/src/native_pso.h
@@ -0,0 +1,332 @@
1#pragma once
2
3// The description Xbox device slot 57 receives (native graphics pipelines) and how its stages find the game's own
4// shader containers. Standard library only, so the parsing is tested on every platform.
5//
6// Layout measured by LooperSalty on 1.0.2.1 and implemented by enx in 5c175db90: 0x108 bytes, the root
7// signature at +0x00, pairs at +0x08 and +0x18, then seven blocks {code, size, records, size} at +0x28 + k * 0x20.
8// Measured by KkelebekK: pair 0 is state blob A (380-388 bytes: blend, raster,
9// depth, not decoded), pair 1 is state blob B (80-188 bytes: formats and input layout, decode_state_b), and each
10// stage's records blob carries the source container's HASH digest after its 0x43 word (docs/fspx.md, kind 7).
11// The block index is not trusted as the stage: the stage comes from the translator's index entry of the container.
12
13#include <array>
14#include <cstddef>
15#include <cstdint>
16#include <cstring>
17#include <map>
18#include <optional>
19#include <span>
20#include <set>
21#include <string>
22#include <string_view>
23#include <utility>
24#include <vector>
25
26namespace leonida::native_pso {
27
28struct Pair {
29 const void* data;
30 std::uint64_t size;
31};
32
33struct StageBlock {
34 Pair code; // +0x00: the stage's native program
35 Pair records; // +0x10: kind-7 style records holding the container's HASH digest
36};
37
38inline constexpr std::size_t kStageBlocks = 7;
39
40struct GraphicsDesc {
41 const void* root_signature; // +0x00
42 Pair state_a; // +0x08
43 Pair state_b; // +0x18
44 StageBlock stages[kStageBlocks]; // +0x28
45};
46
47static_assert(sizeof(Pair) == 0x10 && sizeof(StageBlock) == 0x20, "pairs are {pointer, u64 size}");
48static_assert(offsetof(GraphicsDesc, state_a) == 0x08 && offsetof(GraphicsDesc, state_b) == 0x18);
49static_assert(offsetof(GraphicsDesc, stages) == 0x28 && sizeof(GraphicsDesc) == 0x108,
50 "the slot-57 description has a 0x108-byte prefix");
51
52// Far above the largest blob measured (a few KiB), and small enough for 32-bit offsets inside one.
53inline constexpr std::uint64_t kPairLimit = 16u << 20;
54
55// The size, not the pointer, determines whether a pair is absent.
56enum class PairState { absent, present, malformed };
57
58// A table entry with size 0 is absent whatever its pointer (the title passes base + offset, measured on 1.0.2.1).
59inline PairState pair_state(const Pair& p) {
60 if (!p.size) return PairState::absent;
61 if (!p.data || p.size > kPairLimit) return PairState::malformed;
62 return PairState::present;
63}
64
65inline std::span<const std::uint8_t> bytes(const Pair& p) {
66 if (pair_state(p) != PairState::present) return {};
67 return {static_cast<const std::uint8_t*>(p.data), static_cast<std::size_t>(p.size)};
68}
69
70inline std::uint32_t read_u32(std::span<const std::uint8_t> b, std::size_t at) {
71 std::uint32_t v = 0;
72 if (at + 4 <= b.size()) std::memcpy(&v, b.data() + at, 4);
73 return v;
74}
75
76struct InputElement {
77 std::string name;
78 std::uint32_t semantic_index = 0;
79 std::uint32_t format = 0;
80 std::uint32_t input_slot = 0;
81 std::uint32_t aligned_byte_offset = 0;
82 std::uint32_t classification = 0;
83 std::uint32_t step_rate = 0;
84};
85
86// State blob B. The u32 field widths after each name are a hypothesis that fits the
87// measured sizes: 0x50 bytes with no element, and 188 bytes with POSITION, COLOR and TEXCOORD.
88struct FixedState {
89 std::array<std::uint8_t, 8> rtv_formats{}; // +0x10, DXGI_FORMAT values
90 std::uint32_t sample_mask = 0; // +0x1c
91 std::uint8_t dsv_format = 0; // +0x24
92 std::uint8_t rt_count = 0; // +0x25
93 std::uint8_t topology_type = 0; // +0x26, low nibble
94 std::uint8_t sample_count = 1; // +0x28
95 std::vector<InputElement> elements; // count at +0x4c, packed from +0x50
96};
97
98inline constexpr std::size_t kStateBHeader = 0x50;
99inline constexpr std::uint32_t kMaxInputElements = 32; // D3D12_IA_VERTEX_INPUT_STRUCTURE_ELEMENT_COUNT
100inline constexpr std::uint32_t kMaxSemanticName = 256;
101
102// Empty for a blob that is too short, names more than 8 targets, a topology type past PATCH (4), or an element
103// list that runs past the blob or has a malformed name. Bytes after the last element are allowed.
104inline std::optional<FixedState> decode_state_b(std::span<const std::uint8_t> b, const char** why = nullptr) {
105 const auto fail = [&](const char* reason) {
106 if (why) *why = reason;
107 return std::nullopt;
108 };
109 if (b.size() < kStateBHeader) return fail("blob B shorter than its header");
110 FixedState s;
111 std::memcpy(s.rtv_formats.data(), b.data() + 0x10, 8);
112 s.sample_mask = read_u32(b, 0x1c);
113 s.dsv_format = b[0x24];
114 s.rt_count = b[0x25];
115 s.topology_type = b[0x26] & 0x0f;
116 s.sample_count = b[0x28] ? b[0x28] : 1;
117 if (s.rt_count > 8) return fail("blob B render target count over 8");
118 if (s.topology_type > 4) return fail("blob B topology type over 4");
119 const std::uint32_t count = read_u32(b, 0x4c);
120 if (count > kMaxInputElements) return fail("blob B input element count over 32");
121 std::size_t at = kStateBHeader;
122 for (std::uint32_t i = 0; i < count; ++i) {
123 if (at + 4 > b.size()) return fail("blob B input element past the end");
124 const std::uint32_t length = read_u32(b, at);
125 at += 4;
126 if (length < 2 || length > kMaxSemanticName || at + length + 24 > b.size())
127 return fail("blob B semantic name length out of range");
128 const auto* name = reinterpret_cast<const char*>(b.data() + at);
129 if (name[length - 1] != '\0' || std::memchr(name, '\0', length - 1))
130 return fail("blob B semantic name not one NUL-terminated string");
131 InputElement e;
132 e.name.assign(name, length - 1);
133 at += length;
134 e.semantic_index = read_u32(b, at);
135 e.format = read_u32(b, at + 4);
136 e.input_slot = read_u32(b, at + 8);
137 e.aligned_byte_offset = read_u32(b, at + 12);
138 e.classification = read_u32(b, at + 16);
139 e.step_rate = read_u32(b, at + 20);
140 at += 24;
141 s.elements.push_back(std::move(e));
142 }
143 return s;
144}
145
146using Digest = std::array<std::uint8_t, 16>;
147
148// Every 16 bytes that follow a 4-aligned 0x43 word, without duplicates. A register number can also read 0x43, so
149// all candidates are returned and the map decides which one names a container.
150inline std::vector<Digest> record_digests(std::span<const std::uint8_t> records) {
151 std::vector<Digest> out;
152 std::set<Digest> seen;
153 for (std::size_t at = 0; at + 4 + 16 <= records.size(); at += 4) {
154 if (read_u32(records, at) != 0x43) continue;
155 Digest d;
156 std::memcpy(d.data(), records.data() + at + 4, 16);
157 if (seen.insert(d).second) out.push_back(d);
158 }
159 return out;
160}
161
162inline std::string hex(const Digest& d) {
163 static constexpr char kHex[] = "0123456789abcdef";
164 std::string s;
165 for (const std::uint8_t b : d) {
166 s += kHex[b >> 4];
167 s += kHex[b & 15];
168 }
169 return s;
170}
171
172inline std::optional<Digest> parse_digest(std::string_view text) {
173 if (text.size() != 32) return std::nullopt;
174 Digest d{};
175 for (std::size_t i = 0; i < 32; ++i) {
176 const char c = text[i];
177 int v = c >= '0' && c <= '9' ? c - '0' : c >= 'a' && c <= 'f' ? c - 'a' + 10 : -1;
178 if (v < 0) return std::nullopt;
179 d[i / 2] = static_cast<std::uint8_t>(d[i / 2] << 4 | v);
180 }
181 return d;
182}
183
184struct ShaderRef {
185 Digest digest;
186 std::string stage; // the translator's stage: "vs", "ps", "gs", "ms", "cs"
187 std::string path; // the container, relative to the map file's folder, '/' separated
188};
189
190// native_hashes.txt, written by tools/native_pso_hashes.py next to the translator's index.json: a first line
191// "# native_pso_hashes 1", then one "<32 hex digest>\t<stage>\t<relative container path>" line per digest.
192class HashMap {
193public:
194 static constexpr std::string_view kHeader = "# native_pso_hashes 1";
195
196 bool parse(std::string_view text, std::string* error = nullptr) {
197 const auto fail = [&](std::string why) {
198 if (error) *error = std::move(why);
199 map_.clear();
200 return false;
201 };
202 map_.clear();
203 std::size_t line_no = 0;
204 bool header = false;
205 while (!text.empty()) {
206 const std::size_t end = text.find('\n');
207 std::string_view line = text.substr(0, end);
208 text = end == std::string_view::npos ? std::string_view{} : text.substr(end + 1);
209 ++line_no;
210 if (!line.empty() && line.back() == '\r') line.remove_suffix(1);
211 if (line_no == 1) {
212 if (line != kHeader) return fail("native_hashes.txt: unknown header");
213 header = true;
214 continue;
215 }
216 if (line.empty() || line.front() == '#') continue;
217 const std::size_t t1 = line.find('\t');
218 const std::size_t t2 = t1 == std::string_view::npos ? t1 : line.find('\t', t1 + 1);
219 if (t2 == std::string_view::npos || t2 + 1 >= line.size())
220 return fail("native_hashes.txt line " + std::to_string(line_no) + ": expected three fields");
221 const auto digest = parse_digest(line.substr(0, t1));
222 const std::string_view stage = line.substr(t1 + 1, t2 - t1 - 1);
223 if (!digest || stage.empty())
224 return fail("native_hashes.txt line " + std::to_string(line_no) + ": bad digest or stage");
225 const std::string_view path = line.substr(t2 + 1);
226 const auto [it, inserted] = map_.try_emplace(*digest, ShaderRef{*digest, std::string(stage), std::string(path)});
227 if (!inserted && (it->second.stage != stage || it->second.path != path))
228 return fail("native_hashes.txt line " + std::to_string(line_no) + ": conflicting digest");
229 }
230 if (!header) return fail("native_hashes.txt is empty");
231 return true;
232 }
233
234 const ShaderRef* find(const Digest& d) const {
235 const auto it = map_.find(d);
236 return it == map_.end() ? nullptr : &it->second;
237 }
238
239 std::size_t size() const { return map_.size(); }
240
241private:
242 std::map<Digest, ShaderRef> map_;
243};
244
245struct PlannedStage {
246 std::size_t block = 0;
247 const ShaderRef* shader = nullptr;
248};
249
250enum class PlanStatus {
251 ok,
252 malformed, // a pair is malformed or blob B does not decode
253 missing, // a stage has no records, or its digest names no translated container
254 ambiguous, // a stage's records name two different containers
255 unsupported, // a stage kind this path does not build (hs, ds, cs), two of one kind, or no VS/MS
256};
257
258struct Plan {
259 PlanStatus status = PlanStatus::malformed;
260 FixedState state;
261 std::vector<PlannedStage> stages; // in block order
262 std::size_t failed_block = 0; // for missing/ambiguous/unsupported/malformed blocks
263 const char* reason = ""; // why a description is malformed
264 bool mesh = false; // an MS stage: the pipeline goes through a pipeline state stream
265
266 const ShaderRef* stage(std::string_view name) const {
267 for (const PlannedStage& s : stages)
268 if (s.shader->stage == name) return s.shader;
269 return nullptr;
270 }
271};
272
273inline Plan plan(const GraphicsDesc& desc, const HashMap& map) {
274 Plan p;
275 if (pair_state(desc.state_a) == PairState::malformed) {
276 p.reason = "blob A pair malformed";
277 return p;
278 }
279 if (pair_state(desc.state_b) != PairState::present) {
280 p.reason = "blob B pair absent or malformed";
281 return p;
282 }
283 auto state = decode_state_b(bytes(desc.state_b), &p.reason);
284 if (!state) return p;
285 p.state = std::move(*state);
286 for (std::size_t k = 0; k < kStageBlocks; ++k) {
287 const StageBlock& block = desc.stages[k];
288 const PairState code = pair_state(block.code), records = pair_state(block.records);
289 p.failed_block = k;
290 if (code == PairState::malformed || records == PairState::malformed) {
291 p.reason = "a stage pair malformed";
292 return p;
293 }
294 if (code == PairState::absent && records == PairState::absent) continue;
295 if (records != PairState::present) { // code without records: nothing names its container
296 p.status = PlanStatus::missing;
297 return p;
298 }
299 const ShaderRef* found = nullptr;
300 for (const Digest& d : record_digests(bytes(block.records))) {
301 const ShaderRef* ref = map.find(d);
302 if (!ref) continue;
303 if (found && found != ref) {
304 p.status = PlanStatus::ambiguous;
305 p.failed_block = k;
306 return p;
307 }
308 found = ref;
309 }
310 p.failed_block = k;
311 if (!found) {
312 p.status = PlanStatus::missing;
313 return p;
314 }
315 const std::string& s = found->stage;
316 if (!(s == "vs" || s == "ps" || s == "gs" || s == "ms") || p.stage(s)) {
317 p.status = PlanStatus::unsupported;
318 return p;
319 }
320 p.stages.push_back({k, found});
321 }
322 const bool vs = p.stage("vs"), ms = p.stage("ms");
323 if (vs == ms || (ms && p.stage("gs"))) {
324 p.status = PlanStatus::unsupported;
325 return p;
326 }
327 p.mesh = ms;
328 p.status = PlanStatus::ok;
329 return p;
330}
331
332} // namespace leonida::native_pso
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp
index cc4ae88aa..57822d1ec 100644
--- a/runtime/src/pe_loader.cpp
+++ b/runtime/src/pe_loader.cpp
@@ -126,8 +126,29 @@ IMAGE_TLS_DIRECTORY64* tls_directory(Module& m) {
126// reuses that index for the mapped image. When more than one manually mapped module uses static TLS at once, the loader 126// reuses that index for the mapped image. When more than one manually mapped module uses static TLS at once, the loader
127// clones gta6rt_tls_host.dll to a per-process temporary path on demand and loads it, so the OS assigns an independent 127// clones gta6rt_tls_host.dll to a per-process temporary path on demand and loads it, so the OS assigns an independent
128// module TLS index for each simultaneous module (up to kMaxMappedTlsModules). 128// module TLS index for each simultaneous module (up to kMaxMappedTlsModules).
129//
130// A mapped executable is different: MSVC code built with /GA (an EXE-only optimisation) skips _tls_index and reads
131// TEB->ThreadLocalStoragePointer[0] directly (mov rax, gs:[58h]; mov rax, [rax]), because Windows always gives the
132// process executable module TLS index 0. Measured with a `thread_local int v = 42;` EXE built /O2 /GA /MD: natively
133// tls_index=0 value=42; mapped with a helper index (6) the code still read slot 0 and printed value=0. Index 0
134// belongs to the runtime's own EXE (gta6rt.exe: a 1398-byte template when measured, no TLS callbacks; so does each
135// test EXE that links this file), and every TLS read in its disassembly goes through _tls_index (the only direct
136// gs:[58h] read is module_tls_slots below, which wants the array itself). reserve_tls_index0 therefore moves the owner
137// off index 0, once, at process start: it loads the home clone (make_home_clone_image), whose TLS template is a copy of
138// the owner's, and on the calling thread swaps slots 0 and home and writes home into the owner's _tls_index. From then on every thread the OS
139// starts has a fresh copy of the owner's template at home, which is where the owner looks, from its first instruction:
140// nothing has to run on a new thread first. Slot 0 holds a block nobody reads, which the mapped executable's copy
141// replaces (kMainImageSlot) exactly as a DLL's copy replaces a helper's, and the OS frees both slots at thread exit.
142// It has to happen before any other thread has run the owner's code: MSVC keeps &ThreadLocalStoragePointer[_tls_index]
143// across calls (zlib_inflate in shader_library.h saves it at [rbp-80h] across memset, push_back and inflate_codes, then
144// reads _Init_thread_epoch through it), so a running thread cannot be moved safely, wherever it is stopped. Such a
145// thread's TLS would also stay where it was, at index 0.
129constexpr DWORD kMaxModuleTlsSlots = 64; 146constexpr DWORD kMaxModuleTlsSlots = 64;
130constexpr size_t kMaxMappedTlsModules = 16; 147constexpr size_t kMaxMappedTlsModules = 16;
148// The slot for a mapped executable, which reads module TLS index 0 (see above). Only one at a time; a second
149// executable mapped while one is live gets an ordinary helper slot. kTlsSlotCount sizes the per-slot tables.
150constexpr size_t kMainImageSlot = kMaxMappedTlsModules;
151constexpr size_t kTlsSlotCount = kMaxMappedTlsModules + 1;
131void** module_tls_slots() { return reinterpret_cast<void**>(__readgsqword(0x58)); } 152void** module_tls_slots() { return reinterpret_cast<void**>(__readgsqword(0x58)); }
132 153
133void __cdecl on_host_thread_event(DWORD reason); 154void __cdecl on_host_thread_event(DWORD reason);
@@ -135,6 +156,7 @@ void __cdecl on_host_thread_event(DWORD reason);
135struct TlsHostModule { 156struct TlsHostModule {
136 HMODULE module = nullptr; 157 HMODULE module = nullptr;
137 DWORD index = TLS_OUT_OF_INDEXES; 158 DWORD index = TLS_OUT_OF_INDEXES;
159 bool hooked = false; // its DllMain reports thread events to on_host_thread_event
138}; 160};
139 161
140std::filesystem::path tls_host_base_path() { 162std::filesystem::path tls_host_base_path() {
@@ -167,20 +189,39 @@ struct TlsCloneRecord {
167 189
168std::mutex g_tls_alloc_mutex; 190std::mutex g_tls_alloc_mutex;
169std::array<TlsHostModule, kMaxMappedTlsModules> g_tls_hosts{}; 191std::array<TlsHostModule, kMaxMappedTlsModules> g_tls_hosts{};
170std::array<std::atomic<Module*>, kMaxMappedTlsModules> g_tls_slot_owners{}; 192std::array<std::atomic<Module*>, kTlsSlotCount> g_tls_slot_owners{};
171std::array<std::atomic<uint64_t>, kMaxMappedTlsModules> g_tls_slot_generations{}; 193std::array<std::atomic<uint64_t>, kTlsSlotCount> g_tls_slot_generations{};
172std::atomic<uint64_t> g_next_tls_generation{1}; 194std::atomic<uint64_t> g_next_tls_generation{1};
173std::vector<TlsCloneRecord> g_tls_clones; 195// Allocated with the first clone and never destroyed: cleanup_tls_clones_at_exit runs from the atexit table, and a
196// static vector's destructor (registered when its dynamic initializer ran) could run before it. Under
197// g_tls_alloc_mutex, as are its records.
198std::vector<TlsCloneRecord>* g_tls_clones = nullptr;
199
200// The move of module TLS index 0 (see kMainImageSlot): done at most once, by reserve_tls_index0 under
201// g_tls_alloc_mutex. `why` is the reason it was not done, for the executable that then maps with a helper index.
202// Constant-initialized only (no std::string): gta6rt reserves from a CRT initializer that runs before the dynamic
203// initializers of this file, which would otherwise reset what it wrote.
204struct Index0Move {
205 bool moved = false;
206 bool traced = false; // the startup trace opens after the move; the first executable map reports it
207 TlsHostModule home; // the clone whose index holds the owner's TLS from now on; never freed
208 char owner[260] = {}; // UTF-8 file name of the image that held index 0
209 char why[160] = "reserve_tls_index0 was not called at process start";
210};
211Index0Move g_index0;
174 212
175// Frees every TLS helper clone this process loaded and deletes its files. load() registers the wrapper with atexit; 213// Frees every TLS helper clone recorded for a mapped DLL's slot and deletes its files. ensure_tls_host registers the
176// the --run path in main() must also call this directly before ExitProcess, which skips the atexit table. Call it 214// wrapper with atexit when it records the first clone; the --run path in main() must also call this directly before
177// only when no mapped code can run again: it unmaps the helper images. 215// ExitProcess, which skips the atexit table. Call it only when no mapped code can run again: it unmaps the helper
216// images. The home clone is not recorded (reserve_index0): it stays loaded, so its file outlives the process and the
217// next run's sweep deletes it.
178void cleanup_tls_clones_internal() { 218void cleanup_tls_clones_internal() {
179 for (const auto& rec : g_tls_clones) { 219 if (!g_tls_clones) return;
220 for (const auto& rec : *g_tls_clones) {
180 if (rec.module) FreeLibrary(rec.module); 221 if (rec.module) FreeLibrary(rec.module);
181 if (!rec.path.empty()) DeleteFileW(rec.path.c_str()); 222 if (!rec.path.empty()) DeleteFileW(rec.path.c_str());
182 } 223 }
183 g_tls_clones.clear(); 224 g_tls_clones->clear();
184} 225}
185 226
186void cleanup_tls_clones_at_exit() { cleanup_tls_clones_internal(); } 227void cleanup_tls_clones_at_exit() { cleanup_tls_clones_internal(); }
@@ -204,10 +245,14 @@ DWORD clone_owner_pid(const wchar_t* name) {
204bool process_alive(DWORD pid) { 245bool process_alive(DWORD pid) {
205 // PROCESS_QUERY_LIMITED_INFORMATION needs no handle rights a normal process could deny; a failure means the 246 // PROCESS_QUERY_LIMITED_INFORMATION needs no handle rights a normal process could deny; a failure means the
206 // process is gone. A still-mapped or still-open file is caught by the checks below even for a misjudged PID. 247 // process is gone. A still-mapped or still-open file is caught by the checks below even for a misjudged PID.
248 // OpenProcess also succeeds on a process that has ended while another process still holds a handle to it (a
249 // parent waiting on its exit code, as CMake's execute_process does), so the exit code decides.
207 HANDLE p = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid); 250 HANDLE p = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
208 if (!p) return false; 251 if (!p) return false;
252 DWORD code = 0;
253 const bool alive = !GetExitCodeProcess(p, &code) || code == STILL_ACTIVE;
209 CloseHandle(p); 254 CloseHandle(p);
210 return true; 255 return alive;
211} 256}
212 257
213// Deletes clones left behind by processes that have exited. Deletion is scoped to files whose owner is gone: a 258// Deletes clones left behind by processes that have exited. Deletion is scoped to files whose owner is gone: a
@@ -262,45 +307,66 @@ TlsHostModule load_tls_host_image(const std::filesystem::path& path, bool hook_t
262 if (hook_thread_events) { 307 if (hook_thread_events) {
263 // Only the primary helper reports thread attach/detach events; on_host_thread_event iterates all active slots. 308 // Only the primary helper reports thread attach/detach events; on_host_thread_event iterates all active slots.
264 using SetThreadEvent = void(__cdecl*)(void(__cdecl*)(DWORD)); 309 using SetThreadEvent = void(__cdecl*)(void(__cdecl*)(DWORD));
265 if (auto set = reinterpret_cast<SetThreadEvent>(GetProcAddress(host.module, "gta6rt_tls_host_set_thread_event"))) 310 auto set = reinterpret_cast<SetThreadEvent>(GetProcAddress(host.module, "gta6rt_tls_host_set_thread_event"));
311 if (set) {
266 set(&on_host_thread_event); 312 set(&on_host_thread_event);
313 host.hooked = true;
314 }
267 } 315 }
268 return host; 316 return host;
269} 317}
270 318
271// Must be called with g_tls_alloc_mutex held and WITHOUT g_tls_lock held (LoadLibraryExW takes the Windows loader lock). 319// The primary helper: slot 0's index, and the only helper whose DllMain reports thread events (on_host_thread_event
272TlsHostModule ensure_tls_host(size_t slot) { 320// covers every slot). Must be called with g_tls_alloc_mutex held and WITHOUT g_tls_lock held (LoadLibraryExW takes the
273 if (slot >= kMaxMappedTlsModules) return {}; 321// Windows loader lock).
274 if (g_tls_hosts[slot].index != TLS_OUT_OF_INDEXES) return g_tls_hosts[slot]; 322// A helper without the thread-event export is refused: no thread started later would get its copies.
275 323bool ensure_primary_tls_host() {
324 if (g_tls_hosts[0].index != TLS_OUT_OF_INDEXES) return true;
276 const std::filesystem::path primary = tls_host_base_path(); 325 const std::filesystem::path primary = tls_host_base_path();
277 if (primary.empty()) return {}; 326 if (primary.empty()) return false;
278 327 TlsHostModule host = load_tls_host_image(primary, true);
279 if (slot == 0) { 328 if (host.index != TLS_OUT_OF_INDEXES && !host.hooked) {
280 g_tls_hosts[0] = load_tls_host_image(primary, true); 329 FreeLibrary(host.module);
281 return g_tls_hosts[0]; 330 return false;
282 }
283
284 // Ensure slot 0 is loaded first so thread attach/detach events are hooked.
285 if (g_tls_hosts[0].index == TLS_OUT_OF_INDEXES) {
286 g_tls_hosts[0] = load_tls_host_image(primary, true);
287 if (g_tls_hosts[0].index == TLS_OUT_OF_INDEXES) return {};
288 } 331 }
332 g_tls_hosts[0] = host;
333 return host.index != TLS_OUT_OF_INDEXES;
334}
289 335
336// Copies gta6rt_tls_host.dll (or writes `image`, a changed copy of it) to "leonida_tls_host_<pid>_<tag>.dll" in the
337// clone directory and loads it, so the OS gives the copy an index of its own. On failure the file is gone again and
338// the result has no index. The caller records the clone (g_tls_clones) if it is to be freed at exit. Same locking rule
339// as ensure_primary_tls_host.
340TlsHostModule load_tls_host_clone(const std::wstring& tag, std::filesystem::path& clone_path,
341 const std::vector<uint8_t>* image = nullptr) {
342 const std::filesystem::path primary = tls_host_base_path();
343 if (primary.empty()) return {};
290 // Clone gta6rt_tls_host.dll to a distinct path using CopyFileW (Wine 9 lacks CopyFile2 used by std::filesystem). 344 // Clone gta6rt_tls_host.dll to a distinct path using CopyFileW (Wine 9 lacks CopyFile2 used by std::filesystem).
291 const std::filesystem::path dir = tls_host_clone_dir(); 345 const std::filesystem::path dir = tls_host_clone_dir();
292 static bool swept = false; 346 static bool swept = false;
293 if (!swept) { 347 if (!swept) {
294 swept = true; 348 swept = true;
295 sweep_stale_tls_clones(dir); 349 sweep_stale_tls_clones(dir);
296 std::atexit(&cleanup_tls_clones_at_exit);
297 } 350 }
298 const std::wstring name = 351 const std::wstring name = L"leonida_tls_host_" + std::to_wstring(GetCurrentProcessId()) + L"_" + tag + L".dll";
299 L"leonida_tls_host_" + std::to_wstring(GetCurrentProcessId()) + L"_" + std::to_wstring(slot) + L".dll"; 352 clone_path = dir / name;
300 const std::filesystem::path clone_path = dir / name;
301 // The staging name must not match the sweep pattern, which only covers final clone names ending in .dll. 353 // The staging name must not match the sweep pattern, which only covers final clone names ending in .dll.
302 const std::filesystem::path staging = clone_path.wstring() + L".new"; 354 const std::filesystem::path staging = clone_path.wstring() + L".new";
303 if (!CopyFileW(primary.c_str(), staging.c_str(), FALSE)) return {}; 355 if (image) {
356 HANDLE out =
357 CreateFileW(staging.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
358 if (out == INVALID_HANDLE_VALUE) return {};
359 DWORD written = 0;
360 const bool ok = WriteFile(out, image->data(), static_cast<DWORD>(image->size()), &written, nullptr) &&
361 written == image->size();
362 CloseHandle(out);
363 if (!ok) {
364 DeleteFileW(staging.c_str());
365 return {};
366 }
367 } else if (!CopyFileW(primary.c_str(), staging.c_str(), FALSE)) {
368 return {};
369 }
304 370
305 // Open the guard before the clone exists under its final name and hold it across LoadLibraryExW: the rename 371 // Open the guard before the clone exists under its final name and hold it across LoadLibraryExW: the rename
306 // below needs DELETE access, which the handle's FILE_SHARE_DELETE grants, and no purge can remove the clone 372 // below needs DELETE access, which the handle's FILE_SHARE_DELETE grants, and no purge can remove the clone
@@ -320,18 +386,34 @@ TlsHostModule ensure_tls_host(size_t slot) {
320 TlsHostModule loaded = load_tls_host_image(clone_path, false); 386 TlsHostModule loaded = load_tls_host_image(clone_path, false);
321 CloseHandle(guard); 387 CloseHandle(guard);
322 388
323 if (loaded.index == TLS_OUT_OF_INDEXES) { 389 if (loaded.index == TLS_OUT_OF_INDEXES) DeleteFileW(clone_path.c_str());
390 return loaded;
391}
392
393// Must be called with g_tls_alloc_mutex held and WITHOUT g_tls_lock held (LoadLibraryExW takes the Windows loader lock).
394TlsHostModule ensure_tls_host(size_t slot) {
395 if (slot >= kMaxMappedTlsModules) return {};
396 if (g_tls_hosts[slot].index != TLS_OUT_OF_INDEXES) return g_tls_hosts[slot];
397 // Slot 0 is the primary helper; it is loaded first in any case so thread attach/detach events are hooked.
398 if (!ensure_primary_tls_host()) return {};
399 if (slot == 0) return g_tls_hosts[0];
400
401 std::filesystem::path clone_path;
402 TlsHostModule loaded = load_tls_host_clone(std::to_wstring(slot), clone_path);
403 if (loaded.index == TLS_OUT_OF_INDEXES) return {};
404 // Index 0 is the runtime EXE's, and after the move the home clone's index holds that EXE's TLS.
405 bool taken = loaded.index == 0 || loaded.index == g_index0.home.index;
406 for (size_t i = 0; i < kMaxMappedTlsModules; ++i) taken |= i != slot && g_tls_hosts[i].index == loaded.index;
407 if (taken) {
408 FreeLibrary(loaded.module);
324 DeleteFileW(clone_path.c_str()); 409 DeleteFileW(clone_path.c_str());
325 return {}; 410 return {};
326 } 411 }
327 for (size_t i = 0; i < kMaxMappedTlsModules; ++i) { 412 if (!g_tls_clones) {
328 if (i != slot && g_tls_hosts[i].index == loaded.index) { 413 g_tls_clones = new std::vector<TlsCloneRecord>;
329 FreeLibrary(loaded.module); 414 std::atexit(&cleanup_tls_clones_at_exit);
330 DeleteFileW(clone_path.c_str());
331 return {};
332 }
333 } 415 }
334 g_tls_clones.push_back({loaded.module, clone_path}); 416 g_tls_clones->push_back({loaded.module, clone_path});
335 g_tls_hosts[slot] = loaded; 417 g_tls_hosts[slot] = loaded;
336 return g_tls_hosts[slot]; 418 return g_tls_hosts[slot];
337} 419}
@@ -347,7 +429,7 @@ struct ThreadTlsSlot {
347}; 429};
348 430
349// Per-thread installation state for each reserved TLS slot. 431// Per-thread installation state for each reserved TLS slot.
350thread_local std::array<ThreadTlsSlot, kMaxMappedTlsModules> g_thread_tls_slots{}; 432thread_local std::array<ThreadTlsSlot, kTlsSlotCount> g_thread_tls_slots{};
351 433
352// Orders the TLS owners' publication, their `initialised` flags and their retirement against the thread events. Shared 434// Orders the TLS owners' publication, their `initialised` flags and their retirement against the thread events. Shared
353// in on_host_thread_event, exclusive only for those short writes (no allocation and no call that takes the Windows 435// in on_host_thread_event, exclusive only for those short writes (no allocation and no call that takes the Windows
@@ -366,10 +448,185 @@ struct ExclusiveTlsLock {
366 ExclusiveTlsLock& operator=(const ExclusiveTlsLock&) = delete; 448 ExclusiveTlsLock& operator=(const ExclusiveTlsLock&) = delete;
367}; 449};
368 450
451// gta6rt_tls_host.dll's exports that the home clone's TLS directory is pointed at (tls_host.cpp): a zero array in its
452// .rdata and that array's size.
453constexpr char kHomeTemplateExport[] = "gta6rt_tls_home_template";
454constexpr char kHomeTemplateSizeExport[] = "gta6rt_tls_home_template_size";
455
456// File offset of `len` bytes at `rva` in an image file held in memory, or SIZE_MAX when they are not all inside one
457// section's raw data.
458size_t file_offset(const std::vector<uint8_t>& file, const IMAGE_NT_HEADERS64* nt, uint64_t rva, uint64_t len) {
459 const auto* sec = IMAGE_FIRST_SECTION(nt);
460 for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) {
461 if (reinterpret_cast<const uint8_t*>(sec + 1) > file.data() + file.size()) break;
462 if (rva < sec->VirtualAddress || rva + len > static_cast<uint64_t>(sec->VirtualAddress) + sec->SizeOfRawData)
463 continue;
464 const uint64_t off = sec->PointerToRawData + (rva - sec->VirtualAddress);
465 return off + len <= file.size() ? static_cast<size_t>(off) : SIZE_MAX;
466 }
467 return SIZE_MAX;
468}
469
470// The RVA of a named export in an image file held in memory, 0 when it has none.
471uint32_t file_export(const std::vector<uint8_t>& file, const IMAGE_NT_HEADERS64* nt, const char* wanted) {
472 const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_EXPORT);
473 const size_t ed_off = file_offset(file, nt, dir.VirtualAddress, sizeof(IMAGE_EXPORT_DIRECTORY));
474 if (!dir.Size || ed_off == SIZE_MAX) return 0;
475 const auto* ed = reinterpret_cast<const IMAGE_EXPORT_DIRECTORY*>(file.data() + ed_off);
476 const size_t names = file_offset(file, nt, ed->AddressOfNames, uint64_t{4} * ed->NumberOfNames);
477 const size_t ords = file_offset(file, nt, ed->AddressOfNameOrdinals, uint64_t{2} * ed->NumberOfNames);
478 const size_t funcs = file_offset(file, nt, ed->AddressOfFunctions, uint64_t{4} * ed->NumberOfFunctions);
479 if (names == SIZE_MAX || ords == SIZE_MAX || funcs == SIZE_MAX) return 0;
480 const size_t wanted_len = std::strlen(wanted) + 1;
481 for (uint32_t i = 0; i < ed->NumberOfNames; ++i) {
482 uint32_t name_rva, func_rva;
483 uint16_t ord;
484 std::memcpy(&name_rva, file.data() + names + 4 * i, 4);
485 std::memcpy(&ord, file.data() + ords + 2 * i, 2);
486 const size_t name = file_offset(file, nt, name_rva, wanted_len);
487 if (name == SIZE_MAX || std::memcmp(file.data() + name, wanted, wanted_len) != 0) continue;
488 if (ord >= ed->NumberOfFunctions) return 0;
489 std::memcpy(&func_rva, file.data() + funcs + 4 * ord, 4);
490 return func_rva;
491 }
492 return 0;
493}
494
495// Turns gta6rt_tls_host.dll's bytes into the home clone: its TLS directory now covers gta6rt_tls_home_template, which
496// starts with a copy of the owner's template (taken from the mapped owner, so its pointers are already relocated; the
497// array itself has no relocations), and takes the owner's alignment. The OS then gives every thread, at the home
498// index, a block that is a fresh copy of the owner's TLS. The zero fill goes into the covered range too:
499// LdrpAllocateTls allocates and copies End - Start only (Windows 11 26300) and ignores SizeOfZeroFill. The directory's
500// Start and End have base relocations, so they follow the clone wherever it loads. Empty on success, else why not.
501std::string make_home_clone_image(std::vector<uint8_t>& file, const IMAGE_TLS_DIRECTORY64& owner) {
502 if (file.size() < sizeof(IMAGE_DOS_HEADER)) return "gta6rt_tls_host.dll is truncated";
503 const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(file.data());
504 if (dos->e_magic != IMAGE_DOS_SIGNATURE || dos->e_lfanew < 0 ||
505 static_cast<size_t>(dos->e_lfanew) + sizeof(IMAGE_NT_HEADERS64) > file.size())
506 return "gta6rt_tls_host.dll has no PE header";
507 auto* nt = reinterpret_cast<IMAGE_NT_HEADERS64*>(file.data() + dos->e_lfanew);
508 if (nt->Signature != IMAGE_NT_SIGNATURE || nt->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC)
509 return "gta6rt_tls_host.dll is not a 64-bit image";
510 const uint32_t array_rva = file_export(file, nt, kHomeTemplateExport);
511 const uint32_t size_rva = file_export(file, nt, kHomeTemplateSizeExport);
512 const size_t size_off = file_offset(file, nt, size_rva, sizeof(uint32_t));
513 if (!array_rva || !size_rva || size_off == SIZE_MAX)
514 return "gta6rt_tls_host.dll has no gta6rt_tls_home_template";
515 uint32_t capacity;
516 std::memcpy(&capacity, file.data() + size_off, sizeof(capacity));
517 const uint64_t raw = owner.EndAddressOfRawData - owner.StartAddressOfRawData;
518 const uint64_t total = raw + owner.SizeOfZeroFill;
519 if (owner.EndAddressOfRawData < owner.StartAddressOfRawData || total > capacity)
520 return "the owner's TLS (" + std::to_string(total) + " bytes) does not fit gta6rt_tls_home_template (" +
521 std::to_string(capacity) + " bytes)";
522 const size_t array_off = file_offset(file, nt, array_rva, capacity);
523 const auto tls_dir = directory(nt, IMAGE_DIRECTORY_ENTRY_TLS);
524 const size_t tls_off = file_offset(file, nt, tls_dir.VirtualAddress, sizeof(IMAGE_TLS_DIRECTORY64));
525 if (array_off == SIZE_MAX || !tls_dir.Size || tls_off == SIZE_MAX)
526 return "gta6rt_tls_host.dll's TLS directory or home template lies outside its file";
527 std::memcpy(file.data() + array_off, reinterpret_cast<const void*>(owner.StartAddressOfRawData), raw);
528 std::memset(file.data() + array_off + raw, 0, capacity - raw);
529 auto* tls = reinterpret_cast<IMAGE_TLS_DIRECTORY64*>(file.data() + tls_off);
530 tls->StartAddressOfRawData = nt->OptionalHeader.ImageBase + array_rva;
531 tls->EndAddressOfRawData = tls->StartAddressOfRawData + total;
532 tls->SizeOfZeroFill = 0;
533 tls->Characteristics =
534 (tls->Characteristics & ~IMAGE_SCN_ALIGN_MASK) | (owner.Characteristics & IMAGE_SCN_ALIGN_MASK);
535 return {};
536}
537
538std::string module_file_name(HMODULE module) {
539 wchar_t path[MAX_PATH];
540 const DWORD n = GetModuleFileNameW(module, path, MAX_PATH);
541 if (!n || n >= MAX_PATH) return "?";
542 const wchar_t* name = path;
543 for (const wchar_t* p = path; *p; ++p)
544 if (*p == L'\\' || *p == L'/') name = p + 1;
545 const int bytes = WideCharToMultiByte(CP_UTF8, 0, name, -1, nullptr, 0, nullptr, nullptr);
546 if (bytes <= 1) return "?";
547 std::string out(static_cast<size_t>(bytes - 1), '\0');
548 WideCharToMultiByte(CP_UTF8, 0, name, -1, out.data(), bytes, nullptr, nullptr);
549 return out;
550}
551
552// The move on the calling thread, kept apart so that no frame of reserve_index0 holds a slot address across it. After
553// it the owner's live block is at `home` and slot 0 holds the home clone's fresh copy, which nothing reads.
554__declspec(noinline) void move_index0_on_this_thread(DWORD* owner_index, DWORD home) {
555 void** slots = module_tls_slots();
556 std::swap(slots[0], slots[home]);
557 *owner_index = home;
558}
559
560// See reserve_tls_index0. Empty on success, else why not; nothing has changed then. g_tls_alloc_mutex held. It reads
561// no thread_local data and runs no code that does, before or after the move.
562std::string reserve_index0() {
563 // Windows gives index 0 to the process executable when it has TLS; a DLL can only hold it in a process whose EXE
564 // has none, and a DLL that is still loading or was loaded without its references resolved shows 0 too.
565 const HMODULE exe = GetModuleHandleW(nullptr);
566 auto* base = reinterpret_cast<uint8_t*>(exe);
567 auto* nt = at<IMAGE_NT_HEADERS64>(base, reinterpret_cast<IMAGE_DOS_HEADER*>(base)->e_lfanew);
568 const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_TLS);
569 if (!dir.Size || !dir.VirtualAddress) return "the process executable has no TLS, so index 0 is not its";
570 const IMAGE_TLS_DIRECTORY64 owner = *at<IMAGE_TLS_DIRECTORY64>(base, dir.VirtualAddress);
571 auto* owner_index = reinterpret_cast<DWORD*>(owner.AddressOfIndex);
572 if (!owner_index) return "the process executable's TLS directory has no index";
573 if (*owner_index != 0) return "the process executable's _tls_index is " + std::to_string(*owner_index) + ", not 0";
574 if (!module_tls_slots()) return "this thread has no TLS array";
575 if (!ensure_primary_tls_host())
576 return "gta6rt_tls_host.dll is missing, has no module TLS index or lacks gta6rt_tls_host_set_thread_event";
577
578 std::vector<uint8_t> image;
579 try {
580 image = read_file(tls_host_base_path());
581 } catch (const std::exception& e) {
582 return e.what();
583 }
584 if (std::string why = make_home_clone_image(image, owner); !why.empty()) return why;
585 std::filesystem::path path;
586 const TlsHostModule home = load_tls_host_clone(L"home", path, &image);
587 if (home.index == TLS_OUT_OF_INDEXES) return "the home clone of gta6rt_tls_host.dll cannot be loaded";
588 auto drop = [&](std::string why) {
589 FreeLibrary(home.module); // safe until the move below: nothing lives at its index yet
590 DeleteFileW(path.c_str());
591 return why;
592 };
593 bool taken = home.index == 0 || home.index >= kMaxModuleTlsSlots;
594 for (const auto& host : g_tls_hosts) taken |= host.index == home.index;
595 if (taken) return drop("the home clone got an unusable module TLS index");
596 // The OS must have taken the changed directory: the mapped clone's template is the owner's, at full size.
597 auto* home_base = reinterpret_cast<uint8_t*>(home.module);
598 auto* home_nt = at<IMAGE_NT_HEADERS64>(home_base, reinterpret_cast<IMAGE_DOS_HEADER*>(home_base)->e_lfanew);
599 const auto* home_tls =
600 at<IMAGE_TLS_DIRECTORY64>(home_base, directory(home_nt, IMAGE_DIRECTORY_ENTRY_TLS).VirtualAddress);
601 const uint64_t raw = owner.EndAddressOfRawData - owner.StartAddressOfRawData;
602 if (home_tls->EndAddressOfRawData - home_tls->StartAddressOfRawData != raw + owner.SizeOfZeroFill ||
603 std::memcmp(reinterpret_cast<const void*>(home_tls->StartAddressOfRawData),
604 reinterpret_cast<const void*>(owner.StartAddressOfRawData), raw) != 0)
605 return drop("the home clone's mapped TLS template is not the owner's");
606
607 // Everything that can throw comes first: past the move this records the result and nothing more.
608 const std::string name = module_file_name(exe);
609 // _tls_index sits in .data; made writable first in case a linker merged it into a read-only section.
610 DWORD old_protect = 0;
611 if (!VirtualProtect(owner_index, sizeof(DWORD), PAGE_READWRITE, &old_protect))
612 return drop("the owner's _tls_index cannot be written");
613 move_index0_on_this_thread(owner_index, home.index);
614 VirtualProtect(owner_index, sizeof(DWORD), old_protect, &old_protect);
615
616 // Kept loaded for the process lifetime: FreeLibrary would make the OS free every thread's block at its index, the
617 // owner's from now on. Not in g_tls_clones for that reason. Its file cannot be deleted while it is mapped
618 // (DeleteFileW and a POSIX-semantics delete both fail with ERROR_ACCESS_DENIED on Windows 11), so it stays until
619 // a later run's sweep.
620 g_index0.home = home;
621 std::snprintf(g_index0.owner, sizeof(g_index0.owner), "%s", name.c_str());
622 g_index0.moved = true;
623 return {};
624}
625
369// Puts the helper DLL's own block back in this thread's slot and frees the copy that replaced it. Uses only this 626// Puts the helper DLL's own block back in this thread's slot and frees the copy that replaced it. Uses only this
370// thread's record, so it also works after the module that installed the copy is gone. 627// thread's record, so it also works after the module that installed the copy is gone.
371void release_thread_slot(size_t slot) { 628void release_thread_slot(size_t slot) {
372 if (slot >= kMaxMappedTlsModules) return; 629 if (slot >= kTlsSlotCount) return;
373 ThreadTlsSlot& entry = g_thread_tls_slots[slot]; 630 ThreadTlsSlot& entry = g_thread_tls_slots[slot];
374 if (!entry.module && !entry.block) return; 631 if (!entry.module && !entry.block) return;
375 if (entry.ga_view) { 632 if (entry.ga_view) {
@@ -438,7 +695,7 @@ void** make_ga_view(const Module& m, void* block) {
438} 695}
439 696
440void install_thread_block(Module& m) { 697void install_thread_block(Module& m) {
441 if (m.tls_slot >= kMaxMappedTlsModules) return; 698 if (m.tls_slot >= kTlsSlotCount) return;
442 const size_t slot = m.tls_slot; 699 const size_t slot = m.tls_slot;
443 ThreadTlsSlot& entry = g_thread_tls_slots[slot]; 700 ThreadTlsSlot& entry = g_thread_tls_slots[slot];
444 if (entry.module == &m && entry.generation == m.tls_generation) return; 701 if (entry.module == &m && entry.generation == m.tls_generation) return;
@@ -530,7 +787,7 @@ bool ga_tls_patch_enabled() {
530} 787}
531 788
532void uninstall_thread_block(Module& m) { 789void uninstall_thread_block(Module& m) {
533 if (m.tls_slot >= kMaxMappedTlsModules) return; 790 if (m.tls_slot >= kTlsSlotCount) return;
534 const size_t slot = m.tls_slot; 791 const size_t slot = m.tls_slot;
535 ThreadTlsSlot& entry = g_thread_tls_slots[slot]; 792 ThreadTlsSlot& entry = g_thread_tls_slots[slot];
536 if (entry.module != &m || entry.generation != m.tls_generation) return; 793 if (entry.module != &m || entry.generation != m.tls_generation) return;
@@ -697,7 +954,7 @@ constexpr size_t kMaxEndedThreads = 1024;
697// load(): every other running thread gets its own copy of m's template. Not fatal where it cannot be done. 954// load(): every other running thread gets its own copy of m's template. Not fatal where it cannot be done.
698void install_on_existing_threads(Module& m) { 955void install_on_existing_threads(Module& m) {
699 const uint64_t total = static_cast<uint64_t>(m.tls_raw_size) + m.tls_zero_fill; 956 const uint64_t total = static_cast<uint64_t>(m.tls_raw_size) + m.tls_zero_fill;
700 if (!total || m.tls_index >= kMaxModuleTlsSlots || m.tls_slot >= kMaxMappedTlsModules) return; 957 if (!total || m.tls_index >= kMaxModuleTlsSlots || m.tls_slot >= kTlsSlotCount) return;
701 // Stays ahead of the TLS lock: the first call resolves the function with GetModuleHandle and GetProcAddress, which 958 // Stays ahead of the TLS lock: the first call resolves the function with GetModuleHandle and GetProcAddress, which
702 // take the Windows loader lock, and a thread inside its attach event holds that lock while it waits for ours. 959 // take the Windows loader lock, and a thread inside its attach event holds that lock while it waits for ours.
703 if (!query_thread_fn()) return; 960 if (!query_thread_fn()) return;
@@ -882,7 +1139,11 @@ void release_existing_blocks_of_this_thread() {
882// Runs in gta6rt_tls_host.dll's DllMain for each thread the process starts or ends once the helper is loaded, under 1139// Runs in gta6rt_tls_host.dll's DllMain for each thread the process starts or ends once the helper is loaded, under
883// the Windows loader lock, on that thread. A new thread gets its own copy of each active TLS owner's template; an 1140// the Windows loader lock, on that thread. A new thread gets its own copy of each active TLS owner's template; an
884// ending one gives each helper's block back before the Windows loader frees it. TLS callbacks get the thread events 1141// ending one gives each helper's block back before the Windows loader frees it. TLS callbacks get the thread events
885// only after the module's DLL_PROCESS_ATTACH (initialise()), as the Windows loader orders them. 1142// only after the module's DLL_PROCESS_ATTACH (initialise()), as the Windows loader orders them. Windows allocates
1143// every module's block before the first DllMain of a new thread, and runs an EXE's TLS callbacks after every DllMain,
1144// for attach and for detach (measured on Windows 11 26300). So attach installs all copies first and then runs the
1145// callbacks, the DLL slots in order and the executable's last; detach runs the DLL slots in reverse and then the
1146// executable's slot, each releasing its copy after its callbacks.
886void __cdecl on_host_thread_event(DWORD reason) { 1147void __cdecl on_host_thread_event(DWORD reason) {
887 SharedTlsLock lock; 1148 SharedTlsLock lock;
888 // The try/catch is per slot: a throw from one module's install or callbacks must not take the thread events 1149 // The try/catch is per slot: a throw from one module's install or callbacks must not take the thread events
@@ -893,14 +1154,25 @@ void __cdecl on_host_thread_event(DWORD reason) {
893 } catch (const std::exception& e) { 1154 } catch (const std::exception& e) {
894 std::fprintf(stderr, "[rt] loader: thread attach: %s\n", e.what()); 1155 std::fprintf(stderr, "[rt] loader: thread attach: %s\n", e.what());
895 } 1156 }
896 for (size_t slot = 0; slot < kMaxMappedTlsModules; ++slot) { 1157 std::array<Module*, kTlsSlotCount> installed{};
1158 for (size_t slot = 0; slot < kTlsSlotCount; ++slot) {
897 Module* m = g_tls_slot_owners[slot].load(); 1159 Module* m = g_tls_slot_owners[slot].load();
898 if (!m) continue; 1160 if (!m) continue;
899 try { 1161 try {
900 install_thread_block(*m); 1162 install_thread_block(*m);
901 if (m->initialised) run_callbacks(*m, DLL_THREAD_ATTACH); 1163 installed[slot] = m;
1164 } catch (const std::exception& e) {
1165 // The thread runs on without this module's TLS (and its callbacks); later slots still get theirs.
1166 std::fprintf(stderr, "[rt] loader: thread attach, slot %zu (%s): %s\n", slot, m->name.c_str(),
1167 e.what());
1168 }
1169 }
1170 for (size_t slot = 0; slot < kTlsSlotCount; ++slot) {
1171 Module* m = installed[slot];
1172 if (!m || !m->initialised) continue;
1173 try {
1174 run_callbacks(*m, DLL_THREAD_ATTACH);
902 } catch (const std::exception& e) { 1175 } catch (const std::exception& e) {
903 // The thread runs on without this module's TLS; later slots still get theirs.
904 std::fprintf(stderr, "[rt] loader: thread attach, slot %zu (%s): %s\n", slot, m->name.c_str(), 1176 std::fprintf(stderr, "[rt] loader: thread attach, slot %zu (%s): %s\n", slot, m->name.c_str(),
905 e.what()); 1177 e.what());
906 } 1178 }
@@ -913,7 +1185,8 @@ void __cdecl on_host_thread_event(DWORD reason) {
913 } catch (const std::exception& e) { 1185 } catch (const std::exception& e) {
914 std::fprintf(stderr, "[rt] loader: thread detach: %s\n", e.what()); 1186 std::fprintf(stderr, "[rt] loader: thread detach: %s\n", e.what());
915 } 1187 }
916 for (size_t i = kMaxMappedTlsModules; i-- > 0;) { 1188 for (size_t step = 0; step < kTlsSlotCount; ++step) {
1189 const size_t i = step < kMaxMappedTlsModules ? kMaxMappedTlsModules - 1 - step : kMainImageSlot;
917 Module* m = g_tls_slot_owners[i].load(); 1190 Module* m = g_tls_slot_owners[i].load();
918 if (m && g_thread_tls_slots[i].module == m && 1191 if (m && g_thread_tls_slots[i].module == m &&
919 g_thread_tls_slots[i].generation == m->tls_generation) { 1192 g_thread_tls_slots[i].generation == m->tls_generation) {
@@ -1017,6 +1290,26 @@ void redirect_pc_to_file_header_at(const void* resolved) {
1017// Declared in pe_loader.h; the body needs the internal clone registry above. 1290// Declared in pe_loader.h; the body needs the internal clone registry above.
1018void cleanup_tls_clones() { cleanup_tls_clones_internal(); } 1291void cleanup_tls_clones() { cleanup_tls_clones_internal(); }
1019 1292
1293bool reserve_tls_index0(std::string* why) {
1294 std::lock_guard alloc_lock(g_tls_alloc_mutex);
1295 static bool attempted = false; // once: a later attempt could meet threads that already run this EXE's code
1296 if (!attempted) {
1297 attempted = true;
1298 // A throw (std::filesystem::temp_directory_path when GetTempPathW fails, an allocation) is a failed
1299 // reservation like any other: gta6rt calls this before main, where an exception would end it with no message.
1300 try {
1301 const std::string reason = reserve_index0();
1302 std::snprintf(g_index0.why, sizeof(g_index0.why), "%s", reason.c_str());
1303 } catch (const std::exception& e) {
1304 std::snprintf(g_index0.why, sizeof(g_index0.why), "%s", e.what());
1305 } catch (...) {
1306 std::snprintf(g_index0.why, sizeof(g_index0.why), "an unknown error while reserving it");
1307 }
1308 }
1309 if (why) *why = g_index0.moved ? std::string() : std::string(g_index0.why);
1310 return g_index0.moved;
1311}
1312
1020namespace { 1313namespace {
1021bool lookup_in_loader(void* ctx, uint64_t address, std::string& module, uint32_t& rva) { 1314bool lookup_in_loader(void* ctx, uint64_t address, std::string& module, uint32_t& rva) {
1022 return static_cast<Loader*>(ctx)->find_address(address, module, rva); 1315 return static_cast<Loader*>(ctx)->find_address(address, module, rva);
@@ -1099,7 +1392,7 @@ Loader::~Loader() {
1099 shims::remove_module_lookup(this); 1392 shims::remove_module_lookup(this);
1100 for (auto* m : order_) { 1393 for (auto* m : order_) {
1101 // TLS state must go away before the image and its TLS block are unmapped. 1394 // TLS state must go away before the image and its TLS block are unmapped.
1102 if (m->tls_index != kNoTlsIndex && m->tls_slot < kMaxMappedTlsModules) { 1395 if (m->tls_index != kNoTlsIndex && m->tls_slot < kTlsSlotCount) {
1103 // Retired first, under the lock: no thread event installs it or runs its callbacks after this, and a 1396 // Retired first, under the lock: no thread event installs it or runs its callbacks after this, and a
1104 // thread that still holds a copy frees it when it ends (on_host_thread_event). 1397 // thread that still holds a copy frees it when it ends (on_host_thread_event).
1105 { 1398 {
@@ -1514,7 +1807,7 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string&
1514// Only the OS loader can allocate that module index, so the loader reuses the index the OS assigned to 1807// Only the OS loader can allocate that module index, so the loader reuses the index the OS assigned to
1515// gta6rt_tls_host.dll and maps a fresh clone of the helper for every additional simultaneous TLS module, each clone 1808// gta6rt_tls_host.dll and maps a fresh clone of the helper for every additional simultaneous TLS module, each clone
1516// getting its own index. All kMaxMappedTlsModules slots can be live at once; a further module is rejected rather than 1809// getting its own index. All kMaxMappedTlsModules slots can be live at once; a further module is rejected rather than
1517// silently sharing (and corrupting) a slot. 1810// silently sharing (and corrupting) a slot. An executable takes index 0 instead (kMainImageSlot), as on Windows.
1518void Loader::initialize_tls(Module& m) { 1811void Loader::initialize_tls(Module& m) {
1519 auto* tls = tls_directory(m); 1812 auto* tls = tls_directory(m);
1520 if (!tls) return; 1813 if (!tls) return;
@@ -1543,26 +1836,51 @@ void Loader::initialize_tls(Module& m) {
1543 1836
1544 if (!module_tls_slots()) throw std::runtime_error(m.name + ": this thread has no TLS array"); 1837 if (!module_tls_slots()) throw std::runtime_error(m.name + ": this thread has no TLS array");
1545 1838
1546 size_t slot = kMaxMappedTlsModules; 1839 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew);
1840 const bool executable = (nt->FileHeader.Characteristics & IMAGE_FILE_DLL) == 0;
1841
1842 size_t slot = kTlsSlotCount;
1547 DWORD index = TLS_OUT_OF_INDEXES; 1843 DWORD index = TLS_OUT_OF_INDEXES;
1548 { 1844 {
1549 std::lock_guard alloc_lock(g_tls_alloc_mutex); 1845 std::lock_guard alloc_lock(g_tls_alloc_mutex);
1550 for (size_t i = 0; i < kMaxMappedTlsModules; ++i) { 1846 if (executable) {
1551 if (g_tls_slot_owners[i].load() == nullptr) { 1847 if (g_index0.moved && g_tls_slot_owners[kMainImageSlot].load() == nullptr) {
1552 slot = i; 1848 slot = kMainImageSlot;
1553 break; 1849 index = 0;
1850 if (!g_index0.traced && startup_trace::enabled()) {
1851 g_index0.traced = true;
1852 startup_trace::event("tls_index0", "\"owner\":" + startup_trace::quote(g_index0.owner) +
1853 ",\"moved_to\":" + std::to_string(g_index0.home.index));
1854 }
1855 } else {
1856 // Mapped on as a DLL is: its code that reads _tls_index works, but its /GA code would read and write
1857 // the block in slot 0, which is the runtime's own TLS or the other executable's. gta6rt refuses to
1858 // run such an image (main.cpp); a Loader user must not run its code either.
1859 std::fprintf(stderr,
1860 "[rt] loader: %s does not get module TLS index 0 (%s); its code built with /GA would use "
1861 "another module's TLS\n",
1862 m.name.c_str(), g_index0.moved ? "another mapped executable holds it" : g_index0.why);
1863 }
1864 }
1865 if (slot == kTlsSlotCount) {
1866 for (size_t i = 0; i < kMaxMappedTlsModules; ++i) {
1867 if (g_tls_slot_owners[i].load() == nullptr) {
1868 slot = i;
1869 break;
1870 }
1554 } 1871 }
1872 if (slot >= kMaxMappedTlsModules)
1873 throw std::runtime_error(m.name + ": all " + std::to_string(kMaxMappedTlsModules) +
1874 " manually mapped static TLS slots are in use");
1875
1876 // Load/clone gta6rt_tls_host.dll OUTSIDE ExclusiveTlsLock so LoadLibraryExW cannot deadlock with
1877 // on_host_thread_event (which runs under the Windows loader lock and takes SharedTlsLock).
1878 index = ensure_tls_host(slot).index;
1879 if (index == TLS_OUT_OF_INDEXES)
1880 throw std::runtime_error(m.name + ": gta6rt_tls_host.dll is missing or has no module TLS index");
1881 if (index >= kMaxModuleTlsSlots)
1882 throw std::runtime_error(m.name + ": reserved TLS index is out of range");
1555 } 1883 }
1556 if (slot >= kMaxMappedTlsModules)
1557 throw std::runtime_error(m.name + ": all " + std::to_string(kMaxMappedTlsModules) +
1558 " manually mapped static TLS slots are in use");
1559
1560 // Load/clone gta6rt_tls_host.dll OUTSIDE ExclusiveTlsLock so LoadLibraryExW cannot deadlock with
1561 // on_host_thread_event (which runs under the Windows loader lock and takes SharedTlsLock).
1562 index = ensure_tls_host(slot).index;
1563 if (index == TLS_OUT_OF_INDEXES)
1564 throw std::runtime_error(m.name + ": gta6rt_tls_host.dll is missing or has no module TLS index");
1565 if (index >= kMaxModuleTlsSlots) throw std::runtime_error(m.name + ": reserved TLS index is out of range");
1566 1884
1567 // The fields are complete before a thread event can see the owner. 1885 // The fields are complete before a thread event can see the owner.
1568 ExclusiveTlsLock lock; 1886 ExclusiveTlsLock lock;
diff --git a/runtime/src/pe_loader.h b/runtime/src/pe_loader.h
index fda924440..f75426e41 100644
--- a/runtime/src/pe_loader.h
+++ b/runtime/src/pe_loader.h
@@ -54,11 +54,15 @@ struct Module {
54 // the image's _tls_index. tls_index names TEB->ThreadLocalStoragePointer[tls_index], the array 54 // the image's _tls_index. tls_index names TEB->ThreadLocalStoragePointer[tls_index], the array
55 // __declspec(thread) reads; it is not a TlsAlloc slot. The loader reserves distinct indices by loading 55 // __declspec(thread) reads; it is not a TlsAlloc slot. The loader reserves distinct indices by loading
56 // gta6rt_tls_host.dll (and cloning it on demand for additional simultaneous TLS modules, up to 16 at a time). 56 // gta6rt_tls_host.dll (and cloning it on demand for additional simultaneous TLS modules, up to 16 at a time).
57 // An executable gets index 0, as Windows gives the process EXE, because code built with /GA reads slot 0 without
58 // _tls_index. That needs reserve_tls_index0() at process start; without it, and for a second executable mapped
59 // while one holds index 0, the executable gets a helper index and a note on stderr, and its /GA code would use
60 // another module's TLS, so its code must not run (gta6rt refuses).
57 // Every thread started after load() gets its own copy through the helper's DLL_THREAD_ATTACH, and gives it back 61 // Every thread started after load() gets its own copy through the helper's DLL_THREAD_ATTACH, and gives it back
58 // at DLL_THREAD_DETACH. A thread that was already running gets its copy from load() itself, as it would from 62 // at DLL_THREAD_DETACH. A thread that was already running gets its copy from load() itself, as it would from
59 // Windows for a DLL Windows loads: a block, no DLL_THREAD_ATTACH, and DLL_THREAD_DETACH when it ends. 63 // Windows for a DLL Windows loads: a block, no DLL_THREAD_ATTACH, and DLL_THREAD_DETACH when it ends.
60 uint32_t tls_index = kNoTlsIndex; 64 uint32_t tls_index = kNoTlsIndex;
61 uint32_t tls_slot = kNoTlsIndex; // index into the loader's reserved TLS-host slot pool 65 uint32_t tls_slot = kNoTlsIndex; // index into the loader's reserved TLS-host slot pool ; 16 is index 0, an executable's
62 uint64_t tls_generation = 0; // unique token per TLS initialisation, distinguishing reused slots/addresses 66 uint64_t tls_generation = 0; // unique token per TLS initialisation, distinguishing reused slots/addresses
63 void* tls_block = nullptr; // calling thread's copy of the image's template 67 void* tls_block = nullptr; // calling thread's copy of the image's template
64 void* tls_saved_block = nullptr; // helper DLL block replaced in that thread, restored by ~Loader 68 void* tls_saved_block = nullptr; // helper DLL block replaced in that thread, restored by ~Loader
@@ -182,6 +186,14 @@ private:
182// skips the atexit table. Call it when no mapped code can run again: it unmaps the helper images. 186// skips the atexit table. Call it when no mapped code can run again: it unmaps the helper images.
183void cleanup_tls_clones(); 187void cleanup_tls_clones();
184 188
189// Moves the runtime's own EXE off module TLS index 0, which Windows gave it, so that a mapped executable can have it
190// (Module::tls_index): its TLS moves to the index of one more helper clone, whose template is a copy of the EXE's.
191// Call it once at process start, before any other thread has run this EXE's code (gta6rt does it from a CRT
192// initializer): MSVC code keeps the address of its TLS slot across calls, so a thread that is already running cannot
193// be moved, and its TLS would stay at index 0. Returns false, with the reason in *why, when it cannot; later calls
194// return the first result.
195bool reserve_tls_index0(std::string* why = nullptr);
196
185std::string lower(std::string s); 197std::string lower(std::string s);
186 198
187} // namespace rt 199} // namespace rt
diff --git a/runtime/src/pipeline_cache_file.h b/runtime/src/pipeline_cache_file.h
new file mode 100644
index 000000000..95afbd10a
--- /dev/null
+++ b/runtime/src/pipeline_cache_file.h
@@ -0,0 +1,67 @@
1// Publish a checkpoint only after every byte has reached a closed, same-directory staging file.
2//
3// Used by vk_pipeline_check (its corpus checkpoints) and by the runtime itself, which writes the session cache on
4// device teardown (pipeline_cache_store.h). A reader of the old file keeps it open until its rename completes.
5#pragma once
6
7#include <algorithm>
8#include <cerrno>
9#include <chrono>
10#include <cstdio>
11#include <filesystem>
12#include <string>
13#include <system_error>
14
15#ifdef _WIN32
16#include <thread>
17#include <windows.h>
18#endif
19
20inline std::error_code write_pipeline_cache_file(const std::filesystem::path& destination,
21 const char* data, size_t size) {
22 namespace fs = std::filesystem;
23 const auto stamp = std::chrono::steady_clock::now().time_since_epoch().count();
24 fs::path staged;
25 std::FILE* file = nullptr;
26 for (int attempt = 0; attempt < 8; ++attempt) {
27 staged = destination;
28 staged += ".tmp." + std::to_string(stamp) + "." + std::to_string(attempt);
29#ifdef _WIN32
30 file = _wfopen(staged.c_str(), L"wbx");
31#else
32 file = std::fopen(staged.c_str(), "wbx");
33#endif
34 if (file || errno != EEXIST) break;
35 }
36 if (!file) return {errno, std::generic_category()};
37
38 std::error_code error;
39 // Keep individual CRT writes small even when the cache is several GiB.
40 while (size > 0) {
41 const size_t chunk = (std::min)(size, size_t{16} << 20);
42 if (std::fwrite(data, 1, chunk, file) != chunk || std::ferror(file)) {
43 error = {errno ? errno : EIO, std::generic_category()};
44 break;
45 }
46 data += chunk;
47 size -= chunk;
48 }
49 if (std::fflush(file) != 0 && !error) error = {errno ? errno : EIO, std::generic_category()};
50 if (std::fclose(file) != 0 && !error) error = {errno ? errno : EIO, std::generic_category()};
51 if (!error) {
52 fs::rename(staged, destination, error);
53#ifdef _WIN32
54 // A checker reading the previous cache can briefly block replacement if it did not share delete access.
55 for (int retry = 0; retry < 8; ++retry) {
56 if (error != std::errc::permission_denied && error.value() != ERROR_SHARING_VIOLATION) break;
57 std::this_thread::sleep_for(std::chrono::milliseconds(25));
58 fs::rename(staged, destination, error);
59 }
60#endif
61 }
62 if (error) {
63 std::error_code ignored;
64 fs::remove(staged, ignored);
65 }
66 return error;
67}
diff --git a/runtime/src/pipeline_cache_store.h b/runtime/src/pipeline_cache_store.h
new file mode 100644
index 000000000..6d519d99b
--- /dev/null
+++ b/runtime/src/pipeline_cache_store.h
@@ -0,0 +1,69 @@
1// Persisting the runtime's VkPipelineCache across launches (D3D-704).
2//
3// Two files sit beside gta6rt.exe, and they are not interchangeable:
4//
5// pipeline_cache.bin the offline corpus seed the `pipelines` build stage writes (#367). Read only.
6// pipeline_cache.session.bin what the runtime compiled last time. Written on device teardown.
7//
8// Keeping them apart means a run can never replace the multi-GB corpus cache with the handful of pipelines it
9// happened to compile. On the next launch both are loaded and merged, so the offline entries and the previous
10// session's entries are available together.
11//
12// This header is pure stdlib on purpose (it does not include vulkan.h): pipeline_cache_store_test builds on hosts
13// where CMake has no Vulkan headers. The byte layout below is VkPipelineCacheHeaderVersionOne, whose 32 bytes are
14// part of Vulkan's ABI, not something a driver chooses.
15#pragma once
16
17#include <cstddef>
18#include <cstdint>
19#include <cstring>
20#include <limits>
21
22#include "cached_pso.h"
23
24namespace leonida::pipeline_cache_store {
25
26// A session cache normally holds what one boot compiled (a few MB to a few hundred MB). The cap is what keeps a
27// cache seeded from the multi-GB corpus file -- whose data comes back as the whole union -- from being rewritten
28// at every exit. Past it the previous session file is left alone; raise the limit with
29// LEONIDA_PIPELINE_CACHE_BYTES when a session really compiles that much.
30inline constexpr std::size_t default_save_limit = std::size_t{256} << 20; // 256 MiB
31
32struct SaveLimit {
33 std::size_t bytes = default_save_limit;
34 bool valid = true; // false when the text was not a byte count; bytes then stays at the default
35};
36
37// LEONIDA_PIPELINE_CACHE_BYTES: a decimal byte count, 0 turning the session file off entirely. Empty or absent
38// means the default; stray text, a sign or an overflow is reported by the caller and the default is used.
39inline SaveLimit parse_save_limit(const char* text) {
40 if (!text || !*text) return {};
41 std::size_t value = 0;
42 for (const char* p = text; *p; ++p) {
43 if (*p < '0' || *p > '9') return {default_save_limit, false};
44 const std::size_t digit = static_cast<std::size_t>(*p - '0');
45 if (value > (std::numeric_limits<std::size_t>::max() - digit) / 10) return {default_save_limit, false};
46 value = value * 10 + digit;
47 }
48 return {value, true};
49}
50
51inline constexpr std::size_t header_bytes = 32;
52inline constexpr std::uint32_t header_version_one = 1;
53
54inline std::uint32_t read_u32(const std::uint8_t* p) {
55 return std::uint32_t(p[0]) | (std::uint32_t(p[1]) << 8) | (std::uint32_t(p[2]) << 16) |
56 (std::uint32_t(p[3]) << 24);
57}
58
59// True when the blob's header names this physical device and pipeline-cache UUID, which is what a driver requires
60// before it will read the opaque payload. The header is little-endian, like the host.
61inline bool header_matches(const void* data, std::size_t size, const cached_pso::Identity& identity) {
62 if (!data || size < header_bytes) return false;
63 const auto* bytes = static_cast<const std::uint8_t*>(data);
64 return read_u32(bytes) == header_bytes && read_u32(bytes + 4) == header_version_one &&
65 read_u32(bytes + 8) == identity.vendor && read_u32(bytes + 12) == identity.device &&
66 std::memcmp(bytes + 16, identity.cache_uuid, sizeof(identity.cache_uuid)) == 0;
67}
68
69} // namespace leonida::pipeline_cache_store
diff --git a/runtime/src/present_dump.h b/runtime/src/present_dump.h
new file mode 100644
index 000000000..2e594fcb5
--- /dev/null
+++ b/runtime/src/present_dump.h
@@ -0,0 +1,256 @@
1#pragma once
2
3// LEONIDA_PRESENT_DUMP: the final swapchain texels, encoded on a worker after their frame fence signals.
4#include <vulkan/vulkan.h>
5
6#include <algorithm>
7#include <array>
8#include <atomic>
9#include <charconv>
10#include <cmath>
11#include <cstdint>
12#include <cstdio>
13#include <cstdlib>
14#include <cstring>
15#include <filesystem>
16#include <memory>
17#include <mutex>
18#include <span>
19#include <string>
20#include <thread>
21#include <vector>
22
23namespace leonida::present_dump {
24
25inline unsigned texel_size(VkFormat format) {
26 switch (format) {
27 case VK_FORMAT_B8G8R8A8_UNORM: case VK_FORMAT_B8G8R8A8_SRGB:
28 case VK_FORMAT_R8G8B8A8_UNORM: case VK_FORMAT_R8G8B8A8_SRGB:
29 case VK_FORMAT_A2B10G10R10_UNORM_PACK32: case VK_FORMAT_A2R10G10B10_UNORM_PACK32: return 4;
30 case VK_FORMAT_R16G16B16A16_SFLOAT: return 8;
31 case VK_FORMAT_R32G32B32A32_SFLOAT: return 16;
32 default: return 0;
33 }
34}
35
36inline std::uint8_t unorm8(float v) {
37 return v > 0 ? std::uint8_t(std::min(v, 1.0f) * 255 + 0.5f) : 0;
38}
39
40inline std::uint8_t half_unorm8(std::uint16_t bits) {
41 const int exponent = bits >> 10;
42 const int fraction = bits & 1023;
43 if (bits >= 0x8000 || !exponent || (exponent == 31 && fraction)) return 0;
44 return unorm8(std::ldexp(float(1024 + fraction), exponent - 25));
45}
46
47inline void rgba_row(std::uint8_t* dst, const std::uint8_t* src, unsigned width, VkFormat format, bool pq) {
48 if (format == VK_FORMAT_R8G8B8A8_UNORM || format == VK_FORMAT_R8G8B8A8_SRGB) {
49 std::memcpy(dst, src, size_t(width) * 4);
50 return;
51 }
52 const unsigned stride = texel_size(format);
53 for (unsigned x = 0; x < width; ++x, src += stride, dst += 4) {
54 if (format == VK_FORMAT_B8G8R8A8_UNORM || format == VK_FORMAT_B8G8R8A8_SRGB) {
55 dst[0] = src[2]; dst[1] = src[1]; dst[2] = src[0]; dst[3] = src[3];
56 } else if (format == VK_FORMAT_R16G16B16A16_SFLOAT) {
57 std::uint16_t v[4];
58 std::memcpy(v, src, sizeof(v));
59 std::transform(v, v + 4, dst, half_unorm8);
60 } else if (format == VK_FORMAT_R32G32B32A32_SFLOAT) {
61 float v[4];
62 std::memcpy(v, src, sizeof(v));
63 std::transform(v, v + 4, dst, unorm8);
64 } else {
65 // A cheap HDR10 preview: decode ST.2084 per component, clip at 203 nits and encode for SDR.
66 // Keep the source primaries. A 10-bit SDR swapchain just scales its code values to eight bits.
67 static const auto pq_to_sdr = [] {
68 std::array<std::uint8_t, 1024> table{};
69 for (unsigned i = 0; i < table.size(); ++i) {
70 const double p = std::pow(i / 1023.0, 1.0 / 78.84375);
71 const double linear = (10000.0 / 203.0) *
72 std::pow(std::max(0.0, p - 0.8359375) / (18.8515625 - 18.6875 * p), 1.0 / 0.1593017578125);
73 const double srgb = linear <= 0.0031308 ? 12.92 * linear : 1.055 * std::pow(linear, 1.0 / 2.4) - 0.055;
74 table[i] = unorm8(float(srgb));
75 }
76 return table;
77 }();
78 std::uint32_t packed;
79 std::memcpy(&packed, src, sizeof(packed));
80 for (unsigned channel = 0; channel < 3; ++channel) {
81 const unsigned bits = (packed >> (10 * channel)) & 1023;
82 dst[channel] = pq ? pq_to_sdr[bits] : std::uint8_t((bits * 255 + 511) / 1023);
83 }
84 if (format == VK_FORMAT_A2R10G10B10_UNORM_PACK32) std::swap(dst[0], dst[2]);
85 dst[3] = std::uint8_t((packed >> 30) * 85);
86 }
87 }
88}
89
90inline std::array<std::uint8_t, 4> big_endian(std::uint32_t n) {
91 return {std::uint8_t(n >> 24), std::uint8_t(n >> 16), std::uint8_t(n >> 8), std::uint8_t(n)};
92}
93
94inline bool chunk(std::FILE* file, const char (&type)[5], std::span<const std::uint8_t> data,
95 std::span<const std::uint8_t> prefix = {}) {
96 static constexpr auto crc_table = [] {
97 std::array<std::uint32_t, 256> table{};
98 for (unsigned i = 0; i < table.size(); ++i) {
99 unsigned c = i;
100 for (int bit = 0; bit < 8; ++bit) c = (c >> 1) ^ ((c & 1) ? 0xedb88320u : 0);
101 table[i] = c;
102 }
103 return table;
104 }();
105 std::uint32_t crc = ~0u;
106 const auto write = [&](std::span<const std::uint8_t> bytes) {
107 for (auto b : bytes) crc = crc_table[(crc ^ b) & 255] ^ (crc >> 8);
108 return bytes.empty() || std::fwrite(bytes.data(), 1, bytes.size(), file) == bytes.size();
109 };
110 return std::fwrite(big_endian(std::uint32_t(prefix.size() + data.size())).data(), 1, 4, file) == 4 &&
111 write({reinterpret_cast<const std::uint8_t*>(type), 4}) && write(prefix) && write(data) &&
112 std::fwrite(big_endian(~crc).data(), 1, 4, file) == 4;
113}
114
115inline bool write_png(std::FILE* file, VkExtent2D extent, VkFormat format, bool pq, const std::uint8_t* src) {
116 constexpr std::uint8_t signature[]{137, 80, 78, 71, 13, 10, 26, 10};
117 std::array<std::uint8_t, 13> ihdr{};
118 const auto w = big_endian(extent.width), h = big_endian(extent.height);
119 std::copy(w.begin(), w.end(), ihdr.begin());
120 std::copy(h.begin(), h.end(), ihdr.begin() + 4);
121 ihdr[8] = 8;
122 ihdr[9] = 6; // 8-bit RGBA
123 constexpr std::uint8_t zlib_header[]{0x78, 0x01};
124 if (std::fwrite(signature, 1, sizeof(signature), file) != sizeof(signature) ||
125 !chunk(file, "IHDR", ihdr) || !chunk(file, "IDAT", zlib_header)) return false;
126
127 // IDAT chunks concatenate to one zlib stream. Each scanline starts with PNG filter 0 and occupies
128 // one or more stored DEFLATE blocks (16-bit little-endian length and its ones' complement).
129 std::vector<std::uint8_t> row(1 + size_t(extent.width) * 4);
130 std::uint32_t a = 1, b = 0;
131 for (unsigned y = 0; y < extent.height; ++y, src += size_t(extent.width) * texel_size(format)) {
132 rgba_row(row.data() + 1, src, extent.width, format, pq);
133 std::span<const std::uint8_t> rest(row);
134 while (!rest.empty()) {
135 auto block = rest.first(std::min<size_t>(rest.size(), 65535));
136 rest = rest.subspan(block.size());
137 const auto len = std::uint16_t(block.size());
138 const std::uint8_t header[]{std::uint8_t(y + 1 == extent.height && rest.empty()),
139 std::uint8_t(len), std::uint8_t(len >> 8), std::uint8_t(~len), std::uint8_t((len >> 8) ^ 255)};
140 for (auto byte : block) {
141 a = (a + byte) % 65521;
142 b = (b + a) % 65521;
143 }
144 if (!chunk(file, "IDAT", block, header)) return false;
145 }
146 }
147 return chunk(file, "IDAT", big_endian((b << 16) | a)) && chunk(file, "IEND", {});
148}
149
150class PresentDump {
151public:
152 PresentDump() {
153#ifdef _WIN32
154 wchar_t* env = nullptr;
155 size_t length = 0;
156 if (_wdupenv_s(&env, &length, L"LEONIDA_PRESENT_DUMP") != 0) {
157 bad_value();
158 return;
159 }
160 const std::unique_ptr<wchar_t, decltype(&std::free)> owned(env, &std::free);
161#else
162 const auto* env = std::getenv("LEONIDA_PRESENT_DUMP");
163#endif
164 if (!env) return;
165 try {
166 auto value = std::filesystem::path(env).native();
167 std::uint64_t interval = 60;
168 const auto comma = value.rfind(',');
169 if (comma != value.npos) {
170 const auto n = std::filesystem::path(value.substr(comma + 1)).string();
171 const auto end = n.data() + n.size();
172 const auto parsed = std::from_chars(n.data(), end, interval);
173 if (parsed.ec != std::errc{} || parsed.ptr != end || !interval) {
174 bad_value();
175 return;
176 }
177 value.resize(comma);
178 }
179 if (value.empty()) {
180 bad_value();
181 return;
182 }
183 dir_ = std::filesystem::absolute(value);
184 std::filesystem::create_directories(dir_);
185 interval_ = interval;
186 } catch (const std::exception&) { bad_value(); }
187 }
188
189 bool enabled() const { return interval_ != 0; }
190 bool due(std::uint64_t frames_shown) const {
191 const auto n = interval_.load();
192 return n && frames_shown % n == 0;
193 }
194 void disable(const char* why) {
195 if (interval_.exchange(0)) std::fprintf(stderr, "[rt] present: %s; LEONIDA_PRESENT_DUMP disabled\n", why);
196 }
197 void save(std::uint64_t frame, VkExtent2D extent, VkFormat format, bool pq, const std::uint8_t* src, size_t size) {
198 try {
199 // Bound memory to one outstanding write even at N=1. Teardown joins the final writer.
200 if (writer_.joinable()) writer_.join();
201 if (!enabled()) return;
202 char name[48];
203 std::snprintf(name, sizeof(name), "present_%06llu.png", static_cast<unsigned long long>(frame));
204 writer_ = std::jthread([this, frame, extent, format, pq, path = dir_ / name,
205 bytes = std::vector<std::uint8_t>(src, src + size)] {
206 try {
207 if (publish(path, extent, format, pq, bytes.data())) {
208 const auto utf8 = path.u8string();
209 std::fprintf(stderr, "[rt] present: dumped frame %llu to %s\n",
210 static_cast<unsigned long long>(frame), reinterpret_cast<const char*>(utf8.c_str()));
211 return;
212 }
213 } catch (const std::exception&) {}
214 disable("could not write the present dump");
215 });
216 } catch (const std::exception&) { disable("could not queue the present dump"); }
217 }
218
219private:
220 static void bad_value() {
221 static std::once_flag once;
222 std::call_once(once, [] {
223 std::fprintf(stderr, "[rt] present: invalid LEONIDA_PRESENT_DUMP (expected a writable dir[,N], N > 0); disabled\n");
224 });
225 }
226 static bool publish(const std::filesystem::path& path, VkExtent2D extent, VkFormat format, bool pq,
227 const std::uint8_t* src) {
228 // Never open an existing output for writing: it could be a link to a file outside the dump directory.
229 // Build a complete sibling exclusively, then replace the directory entry in a single rename.
230 auto tmp = path;
231 tmp += ".tmp";
232#ifdef _WIN32
233 std::FILE* file = nullptr;
234 _wfopen_s(&file, tmp.c_str(), L"wbx");
235#else
236 auto* file = std::fopen(tmp.c_str(), "wbx");
237#endif
238 if (!file) return false;
239 bool ok = false;
240 try { ok = write_png(file, extent, format, pq, src); } catch (const std::exception&) {}
241 if (std::fclose(file) != 0) ok = false;
242 std::error_code ec;
243 if (ok) {
244 std::filesystem::rename(tmp, path, ec);
245 if (!ec) return true;
246 }
247 std::filesystem::remove(tmp, ec);
248 return false;
249 }
250
251 std::filesystem::path dir_;
252 std::atomic<std::uint64_t> interval_{0};
253 std::jthread writer_; // joined before the state it uses is destroyed
254};
255
256} // namespace leonida::present_dump
diff --git a/runtime/src/queue_families.h b/runtime/src/queue_families.h
index 3148d0ad1..51a8c40c1 100644
--- a/runtime/src/queue_families.h
+++ b/runtime/src/queue_families.h
@@ -12,6 +12,16 @@
12 12
13namespace leonida { 13namespace leonida {
14 14
15// The device's distinct family indices. An object used on more than one family keeps its contents
16// across fenced D3D12 queue handoffs without explicit Vulkan ownership transfers.
17template<typename CreateInfo>
18void share_across_queue_families(CreateInfo& create, std::span<const std::uint32_t> families) {
19 if (families.size() < 2) return;
20 create.sharingMode = VK_SHARING_MODE_CONCURRENT;
21 create.queueFamilyIndexCount = static_cast<std::uint32_t>(families.size());
22 create.pQueueFamilyIndices = families.data();
23}
24
15// Queue families for D3D12's three queue types. Direct needs graphics. Compute prefers a family with compute and no 25// Queue families for D3D12's three queue types. Direct needs graphics. Compute prefers a family with compute and no
16// graphics (async compute), copy one with transfer and neither (a DMA engine); each falls back to a more capable 26// graphics (async compute), copy one with transfer and neither (a DMA engine); each falls back to a more capable
17// family, ending at the graphics one. A dedicated copy family is only used when its image transfer granularity is 27// family, ending at the graphics one. A dedicated copy family is only used when its image transfer granularity is
diff --git a/runtime/src/rgba4_fragment.h b/runtime/src/rgba4_fragment.h
new file mode 100644
index 000000000..b62162848
--- /dev/null
+++ b/runtime/src/rgba4_fragment.h
@@ -0,0 +1,81 @@
1#pragma once
2#include <array>
3#include <bit>
4#include <cstdint>
5#include <cstring>
6#include <map>
7#include <string>
8#include <vector>
9namespace leonida::rgba4 {
10using Inst=std::vector<std::uint32_t>;
11inline Inst instruction(std::uint32_t op,std::initializer_list<std::uint32_t> args) {
12 Inst w{(std::uint32_t(args.size()+1)<<16)|op};w.insert(w.end(),args);return w;
13}
14// Quantize only written color outputs at the requested locations. For a wider fallback attachment
15// this reproduces four-bit UNORM writes for pipelines whose affected attachments use no blending.
16inline bool quantize(Inst& words,unsigned mask) {
17 if(!mask)return true;
18 if(words.size()<5 || words[0]!=0x07230203)return false;
19 std::vector<Inst> code,declarations;
20 std::map<unsigned,unsigned> locations, pointer_type, width, scalar, variables;
21 unsigned import_id=0,next=words[3],float_type=0;
22 for(std::size_t at=5;at<words.size();) {
23 const unsigned n=words[at]>>16,op=words[at]&65535u;
24 if(!n || n>words.size()-at)return false;
25 Inst i(words.begin()+at,words.begin()+at+n);at+=n;
26 if(op==11 && n>=3) {
27 const char* s=reinterpret_cast<const char*>(i.data()+2);const auto bytes=(n-2)*4;
28 if(bytes>=13 && std::memcmp(s,"GLSL.std.450",13)==0)import_id=i[1];
29 } else if(op==71 && n==4 && i[2]==30)locations[i[1]]=i[3];
30 else if(op==22 && n==3 && i[2]==32){float_type=i[1];width[i[1]]=1;scalar[i[1]]=i[1];}
31 else if(op==23 && n==4){width[i[1]]=i[3];scalar[i[1]]=i[2];}
32 else if(op==32 && n==4 && i[2]==3)pointer_type[i[1]]=i[3];
33 else if(op==59 && n>=4 && i[3]==3)variables[i[2]]=i[1];
34 code.push_back(std::move(i));
35 }
36 if(!float_type)return false;
37 std::map<unsigned,unsigned> outputs;
38 for(auto [id,ptr]:variables)if(locations.count(id)&&locations[id]<8&&(mask&(1u<<locations[id]))&&pointer_type.count(ptr))
39 outputs[id]=pointer_type[ptr];
40 if(outputs.empty())return true;
41 const bool add_import=!import_id;if(add_import)import_id=next++;
42 std::map<unsigned,std::array<unsigned,4>> constants;
43 auto components=[&](unsigned type) -> const std::array<unsigned,4>& {
44 auto [it,inserted]=constants.try_emplace(type);
45 if(!inserted)return it->second;
46 constexpr std::array<float,4> vals{0.f,1.f,15.f,1.f/15.f};
47 std::array<unsigned,4> base{};
48 for(unsigned j=0;j<4;++j){base[j]=next++;declarations.push_back(instruction(43,{scalar[type],base[j],std::bit_cast<unsigned>(vals[j])}));}
49 if(width[type]==1){it->second=base;return it->second;}
50 for(unsigned j=0;j<4;++j){const auto id=next++;Inst c=instruction(44,{type,id});c.resize(3+width[type],base[j]);c[0]=(unsigned(c.size())<<16)|44u;declarations.push_back(std::move(c));it->second[j]=id;}
51 return it->second;
52 };
53 std::vector<Inst> rewritten;bool changed=false;
54 for(auto& i:code) {
55 const auto op=i[0]&65535u;
56 if((op==65||op==66||op==83) && i.size()>=4 && outputs.count(i[3]) && pointer_type.count(i[1]))
57 outputs[i[2]]=pointer_type[i[1]];
58 if(op==63 && i.size()>=3 && outputs.count(i[1]))return false;
59 if(op==62 && i.size()>=3 && outputs.count(i[1])) {
60 const auto type=outputs[i[1]];
61 if(!width.count(type)||width[type]<1||width[type]>4||scalar[type]!=float_type)return false;
62 const auto& c=components(type);
63 const auto clamped=next++,scaled=next++,rounded=next++,value=next++;
64 rewritten.push_back(instruction(12,{type,clamped,import_id,43,i[2],c[0],c[1]})); // GLSL FClamp
65 rewritten.push_back(instruction(133,{type,scaled,clamped,c[2]}));
66 rewritten.push_back(instruction(12,{type,rounded,import_id,2,scaled})); // GLSL RoundEven
67 rewritten.push_back(instruction(133,{type,value,rounded,c[3]}));i[2]=value;changed=true;
68 }
69 rewritten.push_back(std::move(i));
70 }
71 if(!changed)return false;
72 Inst result(words.begin(),words.begin()+5);result[3]=next;bool declared=false;
73 for(const auto& i:rewritten) {
74 const auto op=i[0]&65535u;
75 if(op==14 && add_import){Inst imp=instruction(11,{import_id,0,0,0,0});std::memcpy(imp.data()+2,"GLSL.std.450",13);result.insert(result.end(),imp.begin(),imp.end());}
76 if(op==54&&!declared){for(const auto& dec:declarations)result.insert(result.end(),dec.begin(),dec.end());declared=true;}
77 result.insert(result.end(),i.begin(),i.end());
78 }
79 if(!declared)return false;words=std::move(result);return true;
80}
81}
diff --git a/runtime/src/shader_library.h b/runtime/src/shader_library.h
index 9f752317e..e1ac82cb1 100644
--- a/runtime/src/shader_library.h
+++ b/runtime/src/shader_library.h
@@ -843,16 +843,18 @@ struct ShaderEntry {
843 843
844class ShaderLibrary { 844class ShaderLibrary {
845public: 845public:
846 // Reads <dir>/index.json, then the indexes of the programs make_game.py translates from the package's DLLs, each 846 // Reads <dir>/index.json, then the indexes of the programs make_game.py translates outside the game's shader
847 // when it is there: 847 // entries, each when it is there:
848 // - <dir>/fspx/index.json, the FidelityFX DLL's FSPX programs, entries named "fspx/<name>" (docs/fspx.md); 848 // - <dir>/fspx/index.json, the FidelityFX DLL's FSPX programs, entries named "fspx/<name>" (docs/fspx.md);
849 // - <dir>/bvh/index.json, XboxBvhBuilder.dll's FSSM programs, entries named "bvh/<name>" and found by 849 // - <dir>/bvh/index.json, XboxBvhBuilder.dll's FSSM programs, entries named "bvh/<name>" and found by
850 // fssm_sha256 like the game's own shaders (docs/embedded_shaders.md); 850 // fssm_sha256 like the game's own shaders (docs/embedded_shaders.md);
851 // - <dir>/library/index.json, the compute programs of the pipeline library in shaders.rpf, which the executable 851 // - <dir>/library/index.json, the compute programs of the pipeline library in shaders.rpf, which the executable
852 // creates with slot 67; entries named "library/<name>" and found by fspx_code_sha256 and fspx_state_sha256 852 // creates with slot 67; entries named "library/<name>" and found by fspx_code_sha256 and fspx_state_sha256
853 // like the FSPX ones (docs/shader_library.md). 853 // like the FSPX ones (docs/shader_library.md);
854 // Entries with neither fssm_sha256 nor fspx_code_sha256 cannot be found by content and are skipped. Both folders 854 // - <dir>/exe/index.json, game_scarlett_master.exe's embedded FSSM programs, entries named "exe/<name>" and
855 // are optional: a missing or unreadable index there leaves the main one, and the other folder's, loaded. 855 // found by fssm_sha256 like the game's own shaders (docs/embedded_shaders.md).
856 // Entries with neither fssm_sha256 nor fspx_code_sha256 cannot be found by content and are skipped. The folders
857 // are optional: a missing or unreadable index there leaves the main one, and the other folders', loaded.
856 bool load(const std::filesystem::path& dir, std::string* error = nullptr) { 858 bool load(const std::filesystem::path& dir, std::string* error = nullptr) {
857 const auto fail = [&](const std::string& why) { 859 const auto fail = [&](const std::string& why) {
858 if (error) *error = why; 860 if (error) *error = why;
@@ -870,7 +872,7 @@ public:
870 } catch (...) { 872 } catch (...) {
871 return fail("index.json could not be read"); 873 return fail("index.json could not be read");
872 } 874 }
873 for (const char* sub_folder : {"fspx", "bvh", "library"}) { 875 for (const char* sub_folder : {"fspx", "bvh", "library", "exe"}) {
874 try { 876 try {
875 const auto ignore = [](const std::string&) { return false; }; 877 const auto ignore = [](const std::string&) { return false; };
876 const std::filesystem::path sub = folder / sub_folder; 878 const std::filesystem::path sub = folder / sub_folder;
@@ -893,6 +895,9 @@ public:
893 // Entries loaded from <dir>/bvh/index.json. No RPF container reaches these either: XboxBvhBuilder.dll passes 895 // Entries loaded from <dir>/bvh/index.json. No RPF container reaches these either: XboxBvhBuilder.dll passes
894 // their containers itself. 896 // their containers itself.
895 std::size_t bvh_size() const { return bvh_count_; } 897 std::size_t bvh_size() const { return bvh_count_; }
898 // Entries loaded from <dir>/exe/index.json. No RPF container reaches these either: game_scarlett_master.exe
899 // embeds their containers itself.
900 std::size_t exe_size() const { return exe_count_; }
896 901
897 // The first entry for this program. Two containers can hold the same FSSM program with different input 902 // The first entry for this program. Two containers can hold the same FSSM program with different input
898 // signatures; `candidates` returns all of them. 903 // signatures; `candidates` returns all of them.
@@ -1000,6 +1005,7 @@ private:
1000 count_ = 0; 1005 count_ = 0;
1001 fspx_count_ = 0; 1006 fspx_count_ = 0;
1002 bvh_count_ = 0; 1007 bvh_count_ = 0;
1008 exe_count_ = 0;
1003 } 1009 }
1004 for (const auto& [name, meta] : root.object) { 1010 for (const auto& [name, meta] : root.object) {
1005 const Json* hash = meta.find("fssm_sha256"); 1011 const Json* hash = meta.find("fssm_sha256");
@@ -1065,6 +1071,7 @@ private:
1065 if (by_fssm) entries_[{e.stage, e.fssm_sha256}].push_back(std::move(e)); 1071 if (by_fssm) entries_[{e.stage, e.fssm_sha256}].push_back(std::move(e));
1066 if (by_fspx && (prefix == "fspx/" || prefix == "library/")) ++fspx_count_; 1072 if (by_fspx && (prefix == "fspx/" || prefix == "library/")) ++fspx_count_;
1067 if (prefix == "bvh/") ++bvh_count_; 1073 if (prefix == "bvh/") ++bvh_count_;
1074 if (prefix == "exe/") ++exe_count_;
1068 ++count_; 1075 ++count_;
1069 } 1076 }
1070 return true; 1077 return true;
@@ -1074,6 +1081,7 @@ private:
1074 std::size_t count_ = 0; 1081 std::size_t count_ = 0;
1075 std::size_t fspx_count_ = 0; 1082 std::size_t fspx_count_ = 0;
1076 std::size_t bvh_count_ = 0; 1083 std::size_t bvh_count_ = 0;
1084 std::size_t exe_count_ = 0;
1077 // Entries by (stage, fssm_sha256) and by (stage, fspx_code_sha256), in index order. 1085 // Entries by (stage, fssm_sha256) and by (stage, fspx_code_sha256), in index order.
1078 Entries entries_; 1086 Entries entries_;
1079 Entries fspx_entries_; 1087 Entries fspx_entries_;
diff --git a/runtime/src/title_va_alias.h b/runtime/src/title_va_alias.h
new file mode 100644
index 000000000..ac1871e17
--- /dev/null
+++ b/runtime/src/title_va_alias.h
@@ -0,0 +1,232 @@
1#pragma once
2// Buffer addresses in the title's own memory and the console VA a translated shader reaches them by
3// (docs/d3d12_vulkan.md section 3.3, "Title-chosen addresses").
4//
5// A translated shader computes heap_base + console_va, with heap_base the GPU address arena's device address. The
6// layer chooses every console VA it hands out, so they all land in the arena. The title does not always use them:
7// - 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);
8// - the title points V#s and root views at its own memory (a per-frame constant ring, #8862 section 3.5).
9// Both are far past the arena, so heap_base + VA reads nothing the layer made. An address inside such a range is
10// therefore replaced, wherever the layer can see it, by the console VA of a GPU copy of that range: its arena offset
11// when the copy is an arena range (a slot-133 shadow, or a window of the title's pages copied before every
12// submission), or its device address minus heap_base (mod 2^64) when it has its own memory (an imported slot-133
13// buffer). Addresses that are not in the title's memory are passed through unchanged.
14//
15// The table is process-wide, like the title's address space. A resolver makes a GPU copy for an address in the
16// title's memory that has none yet. Without it the table only translates previously added ranges.
17#include <algorithm>
18#include <array>
19#include <atomic>
20#include <cstddef>
21#include <cstdint>
22#include <iterator>
23#include <map>
24#include <mutex>
25#include <shared_mutex>
26
27namespace leonida {
28
29class TitleVaAliases {
30public:
31 // Where the layer saw the address, for the counters.
32 enum Kind : unsigned { root_view, created_view, table_view, vertex_view, index_view, kind_count };
33 static constexpr const char* kKindNames[kind_count] = {"root view", "created view", "table V#", "vertex view",
34 "index view"};
35
36 // An address in the title's memory: true, with `shader_va` what a shader must be given (the address itself when
37 // no copy could be made). False: not the title's memory (an arena VA, a buffer of the layer's).
38 using Resolver = bool (*)(void* context, std::uint64_t va, std::uint64_t bytes, std::uint64_t& shader_va);
39
40 // [title_va, title_va + bytes) is reached as [shader_va, shader_va + bytes). A range that overlaps a live one
41 // replaces it (the title has placed a new buffer over pages it released). False for an empty or wrapping range.
42 bool add(std::uint64_t title_va, std::uint64_t bytes, std::uint64_t shader_va) {
43 if (!bytes || title_va > UINT64_MAX - bytes) return false;
44 std::unique_lock lock(mutex_);
45 erase_overlapping(title_va, title_va + bytes);
46 ranges_[title_va] = {title_va + bytes, shader_va};
47 count_.store(ranges_.size(), std::memory_order_release);
48 return true;
49 }
50
51 // Forgets the range that starts at title_va, if it still maps to shader_va (a newer range at the same VA keeps
52 // its own entry).
53 void remove(std::uint64_t title_va, std::uint64_t shader_va) {
54 std::unique_lock lock(mutex_);
55 const auto it = ranges_.find(title_va);
56 if (it != ranges_.end() && it->second.shader_va == shader_va) ranges_.erase(it);
57 count_.store(ranges_.size(), std::memory_order_release);
58 }
59
60 // The address a shader must be given for `va` from the ranges added so far: translated inside one, unchanged
61 // elsewhere. No copy is made here.
62 std::uint64_t shader_va(std::uint64_t va) const {
63 if (!count_.load(std::memory_order_acquire)) return va; // the common case: no title range at all
64 std::shared_lock lock(mutex_);
65 auto it = ranges_.upper_bound(va);
66 if (it == ranges_.begin()) return va;
67 --it;
68 if (va >= it->second.end) return va;
69 return it->second.shader_va + (va - it->first);
70 }
71
72 // The free span around `va` (not in any range): [lo, hi). A copy made for `va` must stay inside it, so it never
73 // replaces a range another buffer still uses.
74 void gap(std::uint64_t va, std::uint64_t& lo, std::uint64_t& hi) const {
75 std::shared_lock lock(mutex_);
76 lo = 0;
77 hi = UINT64_MAX;
78 auto it = ranges_.upper_bound(va);
79 if (it != ranges_.end()) hi = it->first;
80 if (it != ranges_.begin()) lo = std::prev(it)->second.end;
81 }
82
83 // shader_va, and when `va` is in the title's memory with no copy yet, a copy made by the device's resolver.
84 // Counted by kind: translated, or in the title's memory and left as it was.
85 std::uint64_t resolve(std::uint64_t va, std::uint64_t bytes, Kind kind) {
86 if (!va) return va;
87 std::uint64_t to = shader_va(va);
88 if (to != va) {
89 translated_[kind].fetch_add(1, std::memory_order_relaxed);
90 return to;
91 }
92 Resolver resolver;
93 void* context;
94 {
95 std::lock_guard lock(hook_mutex_);
96 resolver = resolver_;
97 context = hook_context_;
98 }
99 if (!resolver || !resolver(context, va, bytes, to)) return va;
100 (to != va ? translated_ : untranslated_)[kind].fetch_add(1, std::memory_order_relaxed);
101 return to;
102 }
103
104 // Counts an address that the layer resolves through its buffer index instead (vertex and index views): only
105 // whether it is in a title range.
106 void note(std::uint64_t va, Kind kind) {
107 if (va && shader_va(va) != va) untranslated_[kind].fetch_add(1, std::memory_order_relaxed);
108 }
109
110 // The scan's cost, per ExecuteCommandLists that had tables to scan.
111 void note_scan(std::uint64_t nanoseconds) {
112 scans_.fetch_add(1, std::memory_order_relaxed);
113 scan_ns_.fetch_add(nanoseconds, std::memory_order_relaxed);
114 std::uint64_t seen = scan_max_ns_.load(std::memory_order_relaxed);
115 while (nanoseconds > seen && !scan_max_ns_.compare_exchange_weak(seen, nanoseconds)) {
116 }
117 }
118 std::uint64_t scans() const { return scans_.load(std::memory_order_relaxed); }
119 std::uint64_t scan_ns() const { return scan_ns_.load(std::memory_order_relaxed); }
120 std::uint64_t scan_max_ns() const { return scan_max_ns_.load(std::memory_order_relaxed); }
121
122 // The title's own memory, as the xmem shims hand it out (XMemAlloc, XMemVirtualAlloc, the title's VirtualAlloc):
123 // only an address in one of these ranges gets a copy. A base anywhere else (the runtime's own heap, a host DLL)
124 // is left as it was and counted.
125 void add_title_memory(std::uint64_t base, std::uint64_t bytes) {
126 if (!base || !bytes || base > UINT64_MAX - bytes) return;
127 std::uint64_t begin = base, end = base + bytes;
128 std::unique_lock lock(memory_mutex_);
129 // A commit inside a reserved range, or two that overlap, are one range.
130 auto it = memory_.upper_bound(begin);
131 if (it != memory_.begin() && std::prev(it)->second > begin) --it;
132 while (it != memory_.end() && it->first < end) {
133 begin = std::min(begin, it->first);
134 end = std::max(end, it->second);
135 it = memory_.erase(it);
136 }
137 memory_[begin] = end;
138 }
139 void remove_title_memory(std::uint64_t base) {
140 std::unique_lock lock(memory_mutex_);
141 memory_.erase(base);
142 }
143 // The title range that holds `va`: [lo, hi). False when none does.
144 bool title_memory(std::uint64_t va, std::uint64_t& lo, std::uint64_t& hi) const {
145 std::shared_lock lock(memory_mutex_);
146 auto it = memory_.upper_bound(va);
147 if (it == memory_.begin()) return false;
148 --it;
149 if (va >= it->second) return false;
150 lo = it->first;
151 hi = it->second;
152 return true;
153 }
154
155 // A title that gives a descriptor heap its own backing memory (__XMemAllocationHooks__) writes descriptors there
156 // itself, while shaders read the layer's heap. The layer that keeps that mapping registers a source: before a
157 // bound table is scanned, it copies the slots the title wrote in its own memory over the layer's copy
158 // ([real, real + bytes) is the layer heap's CPU memory). Returns how many slots it copied.
159 using DescriptorSource = std::uint64_t (*)(void* context, std::uint8_t* real, std::size_t bytes);
160 void set_descriptor_source(void* context, DescriptorSource source) {
161 std::lock_guard lock(hook_mutex_);
162 source_context_ = context;
163 source_ = source;
164 }
165 void pull_descriptors(std::uint8_t* real, std::size_t bytes) {
166 DescriptorSource source;
167 void* context;
168 {
169 std::lock_guard lock(hook_mutex_);
170 source = source_;
171 context = source_context_;
172 }
173 if (source) pulled_.fetch_add(source(context, real, bytes), std::memory_order_relaxed);
174 }
175 std::uint64_t pulled() const { return pulled_.load(std::memory_order_relaxed); }
176
177 // The first device to register keeps the resolver until it clears it.
178 void set_resolver(void* context, Resolver resolver) {
179 std::lock_guard lock(hook_mutex_);
180 if (hook_context_) return;
181 hook_context_ = context;
182 resolver_ = resolver;
183 }
184 void clear_resolver(void* context) {
185 std::lock_guard lock(hook_mutex_);
186 if (hook_context_ != context) return;
187 hook_context_ = nullptr;
188 resolver_ = nullptr;
189 }
190
191 std::size_t size() const { return count_.load(std::memory_order_acquire); }
192 std::uint64_t translated(Kind kind) const { return translated_[kind].load(std::memory_order_relaxed); }
193 std::uint64_t untranslated(Kind kind) const { return untranslated_[kind].load(std::memory_order_relaxed); }
194
195private:
196 struct Range {
197 std::uint64_t end; // exclusive
198 std::uint64_t shader_va; // what the range's first byte becomes
199 };
200
201 void erase_overlapping(std::uint64_t begin, std::uint64_t end) {
202 auto it = ranges_.lower_bound(begin);
203 if (it != ranges_.begin()) {
204 auto previous = std::prev(it);
205 if (previous->second.end > begin) it = previous;
206 }
207 while (it != ranges_.end() && it->first < end) it = ranges_.erase(it);
208 }
209
210 mutable std::shared_mutex mutex_;
211 std::map<std::uint64_t, Range> ranges_; // by title VA
212 std::atomic<std::size_t> count_{0};
213 std::mutex hook_mutex_;
214 void* hook_context_ = nullptr;
215 Resolver resolver_ = nullptr;
216 void* source_context_ = nullptr;
217 DescriptorSource source_ = nullptr;
218 std::atomic<std::uint64_t> pulled_{0};
219 std::array<std::atomic<std::uint64_t>, kind_count> translated_{};
220 std::array<std::atomic<std::uint64_t>, kind_count> untranslated_{};
221 std::atomic<std::uint64_t> scans_{0}, scan_ns_{0}, scan_max_ns_{0};
222 mutable std::shared_mutex memory_mutex_;
223 std::map<std::uint64_t, std::uint64_t> memory_; // the title's memory: base -> end
224};
225
226// The process's table: the device's title ranges and hooks, read by the command lists and descriptor writers.
227inline TitleVaAliases& title_va_aliases() {
228 static TitleVaAliases aliases;
229 return aliases;
230}
231
232} // namespace leonida
diff --git a/runtime/src/tls_host.cpp b/runtime/src/tls_host.cpp
index ab234cbd9..6cf5e70ae 100644
--- a/runtime/src/tls_host.cpp
+++ b/runtime/src/tls_host.cpp
@@ -5,6 +5,12 @@
5// __declspec(thread) access in mapped code reads a valid TEB slot. The anchor itself is never used; the loader saves 5// __declspec(thread) access in mapped code reads a valid TEB slot. The anchor itself is never used; the loader saves
6// and restores the helper's own block, so the helper's CRT TLS state is not disturbed. 6// and restores the helper's own block, so the helper's CRT TLS state is not disturbed.
7// 7//
8// One more clone, leonida_tls_host_<pid>_home.dll, is made at process start by reserve_tls_index0: its TLS directory
9// is pointed at gta6rt_tls_home_template below, filled with a copy of the runtime EXE's template, and the runtime EXE
10// moves its TLS from index 0 (which Windows gave it) to that clone's index, so a mapped executable can take index 0.
11// That clone stays loaded until the process ends, and its slot then holds the runtime's live TLS, so nothing in this
12// DLL may read or write its own TLS (gta6rt_tls_host_keep is never called).
13//
8// The Windows loader also calls this DLL's DllMain with DLL_THREAD_ATTACH on every new thread (after it has built that 14// The Windows loader also calls this DLL's DllMain with DLL_THREAD_ATTACH on every new thread (after it has built that
9// thread's TLS array) and with DLL_THREAD_DETACH when a thread exits (before it frees the array). The loader registers 15// thread's TLS array) and with DLL_THREAD_DETACH when a thread exits (before it frees the array). The loader registers
10// a callback here so it can give each new thread its own copy of the mapped image's TLS, and put this DLL's block back 16// a callback here so it can give each new thread its own copy of the mapped image's TLS, and put this DLL's block back
@@ -26,6 +32,13 @@ void* volatile g_thread_event = nullptr;
26// the linker without making DllMain touch TLS during thread attach/detach. 32// the linker without making DllMain touch TLS during thread attach/detach.
27extern "C" __declspec(dllexport) void gta6rt_tls_host_keep() { g_tls_host_anchor = 1; } 33extern "C" __declspec(dllexport) void gta6rt_tls_host_keep() { g_tls_host_anchor = 1; }
28 34
35// The home clone's TLS template (pe_loader.cpp, make_home_clone_image): zeros here, the runtime EXE's template in the
36// clone's file. 16 KiB: gta6rt.exe's own TLS template was 1398 bytes when measured; the loader refuses the move when
37// the EXE's TLS does not fit. Each thread gets a block of the EXE's size, not of this array's. Clones of this DLL for
38// mapped DLLs keep the 514-byte TLS directory and do not use the array.
39extern "C" __declspec(dllexport) const unsigned char gta6rt_tls_home_template[16384] = {};
40extern "C" __declspec(dllexport) const unsigned int gta6rt_tls_home_template_size = sizeof(gta6rt_tls_home_template);
41
29// Called by the loader. `fn` runs inside DllMain (under the Windows loader lock) for DLL_THREAD_ATTACH and 42// Called by the loader. `fn` runs inside DllMain (under the Windows loader lock) for DLL_THREAD_ATTACH and
30// DLL_THREAD_DETACH; nullptr stops the calls. 43// DLL_THREAD_DETACH; nullptr stops the calls.
31extern "C" __declspec(dllexport) void gta6rt_tls_host_set_thread_event(ThreadEventFn fn) { 44extern "C" __declspec(dllexport) void gta6rt_tls_host_set_thread_event(ThreadEventFn fn) {
diff --git a/runtime/src/vulkan13_features.h b/runtime/src/vulkan13_features.h
index ea65caa2d..8f2dd61f8 100644
--- a/runtime/src/vulkan13_features.h
+++ b/runtime/src/vulkan13_features.h
@@ -32,6 +32,8 @@ public:
32 Vulkan13Features& operator=(const Vulkan13Features&) = delete; 32 Vulkan13Features& operator=(const Vulkan13Features&) = delete;
33 33
34 bool core = false; // a Vulkan 1.3 device: the features are core 34 bool core = false; // a Vulkan 1.3 device: the features are core
35 bool pipeline_cache_control = false;
36 bool enable_pipeline_cache_control = false;
35 bool dynamic_rendering = false; // supported, as a core feature or through VK_KHR_dynamic_rendering 37 bool dynamic_rendering = false; // supported, as a core feature or through VK_KHR_dynamic_rendering
36 bool synchronization2 = false; // supported, as a core feature or through VK_KHR_synchronization2 38 bool synchronization2 = false; // supported, as a core feature or through VK_KHR_synchronization2
37 // Optional 1.3 core features, available through VK_EXT_subgroup_size_control on a 1.2 device. 39 // Optional 1.3 core features, available through VK_EXT_subgroup_size_control on a 1.2 device.
@@ -45,6 +47,7 @@ public:
45 void query(VkPhysicalDevice physical, std::uint32_t api_version, PFN_vkGetPhysicalDeviceFeatures2 features2, 47 void query(VkPhysicalDevice physical, std::uint32_t api_version, PFN_vkGetPhysicalDeviceFeatures2 features2,
46 PFN_vkEnumerateDeviceExtensionProperties enumerate_extensions) { 48 PFN_vkEnumerateDeviceExtensionProperties enumerate_extensions) {
47 core = api_version >= VK_API_VERSION_1_3; 49 core = api_version >= VK_API_VERSION_1_3;
50 pipeline_cache_control=false;enable_pipeline_cache_control=false;
48 dynamic_rendering = synchronization2 = subgroup_size_control = compute_full_subgroups = false; 51 dynamic_rendering = synchronization2 = subgroup_size_control = compute_full_subgroups = false;
49 extended_dynamic_state = false; 52 extended_dynamic_state = false;
50 if (!features2) return; 53 if (!features2) return;
@@ -53,6 +56,7 @@ public:
53 VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &f13}; 56 VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &f13};
54 features2(physical, &query); 57 features2(physical, &query);
55 dynamic_rendering = f13.dynamicRendering == VK_TRUE; 58 dynamic_rendering = f13.dynamicRendering == VK_TRUE;
59 pipeline_cache_control = f13.pipelineCreationCacheControl == VK_TRUE;
56 synchronization2 = f13.synchronization2 == VK_TRUE; 60 synchronization2 = f13.synchronization2 == VK_TRUE;
57 subgroup_size_control = f13.subgroupSizeControl == VK_TRUE; 61 subgroup_size_control = f13.subgroupSizeControl == VK_TRUE;
58 compute_full_subgroups = f13.computeFullSubgroups == VK_TRUE; 62 compute_full_subgroups = f13.computeFullSubgroups == VK_TRUE;
@@ -98,6 +102,7 @@ public:
98 // Copies the flags of the device query() chose (a later query() for another candidate overwrites them). 102 // Copies the flags of the device query() chose (a later query() for another candidate overwrites them).
99 void choose(const Vulkan13Features& from) { 103 void choose(const Vulkan13Features& from) {
100 core = from.core; 104 core = from.core;
105 pipeline_cache_control=from.pipeline_cache_control;enable_pipeline_cache_control=false;
101 dynamic_rendering = from.dynamic_rendering; 106 dynamic_rendering = from.dynamic_rendering;
102 synchronization2 = from.synchronization2; 107 synchronization2 = from.synchronization2;
103 subgroup_size_control = from.subgroup_size_control; 108 subgroup_size_control = from.subgroup_size_control;
@@ -111,6 +116,7 @@ public:
111 if (core) { 116 if (core) {
112 enable13_.pNext = chain; 117 enable13_.pNext = chain;
113 enable13_.dynamicRendering = VK_TRUE; 118 enable13_.dynamicRendering = VK_TRUE;
119 enable13_.pipelineCreationCacheControl = pipeline_cache_control && enable_pipeline_cache_control ? VK_TRUE : VK_FALSE;
114 enable13_.synchronization2 = VK_TRUE; 120 enable13_.synchronization2 = VK_TRUE;
115 enable13_.subgroupSizeControl = subgroup_size_control ? VK_TRUE : VK_FALSE; 121 enable13_.subgroupSizeControl = subgroup_size_control ? VK_TRUE : VK_FALSE;
116 enable13_.computeFullSubgroups = compute_full_subgroups ? VK_TRUE : VK_FALSE; 122 enable13_.computeFullSubgroups = compute_full_subgroups ? VK_TRUE : VK_FALSE;
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h
index a041825c2..568fa5253 100644
--- a/runtime/src/vulkan_backend.h
+++ b/runtime/src/vulkan_backend.h
@@ -1,4 +1,5 @@
1#pragma once 1#pragma once
2#include "vulkan_gpu_labels.h"
2 3
3// The execution side of the D3D12 layer, without COM: the per-device Vulkan context (resources, layout tracker, 4// The execution side of the D3D12 layer, without COM: the per-device Vulkan context (resources, layout tracker,
4// image views), queues that execute command lists, and timeline-semaphore fences. The COM objects in 5// image views), queues that execute command lists, and timeline-semaphore fences. The COM objects in
@@ -85,7 +86,7 @@ struct VulkanDeviceFunctions {
85 X(vkCmdClearAttachments) X(vkDeviceWaitIdle) X(vkCreateImage) X(vkDestroyImage) \ 86 X(vkCmdClearAttachments) X(vkDeviceWaitIdle) X(vkCreateImage) X(vkDestroyImage) \
86 X(vkGetImageMemoryRequirements) X(vkBindImageMemory) X(vkCreateBuffer) X(vkDestroyBuffer) \ 87 X(vkGetImageMemoryRequirements) X(vkBindImageMemory) X(vkCreateBuffer) X(vkDestroyBuffer) \
87 X(vkGetBufferMemoryRequirements) X(vkBindBufferMemory) X(vkAllocateMemory) X(vkFreeMemory) X(vkMapMemory) \ 88 X(vkGetBufferMemoryRequirements) X(vkBindBufferMemory) X(vkAllocateMemory) X(vkFreeMemory) X(vkMapMemory) \
88 X(vkUnmapMemory) X(vkCmdCopyBuffer) X(vkCmdCopyBufferToImage) X(vkCmdCopyImageToBuffer) X(vkCmdCopyImage) \ 89 X(vkUnmapMemory) X(vkCmdCopyBuffer) X(vkCmdCopyBufferToImage) X(vkCmdCopyImageToBuffer) X(vkCmdCopyImage) X(vkCmdBlitImage) \
89 X(vkCmdResolveImage) X(vkCmdFillBuffer) X(vkCmdUpdateBuffer) X(vkCreateSampler) X(vkDestroySampler) \ 90 X(vkCmdResolveImage) X(vkCmdFillBuffer) X(vkCmdUpdateBuffer) X(vkCreateSampler) X(vkDestroySampler) \
90 X(vkCmdBeginConditionalRenderingEXT) X(vkCmdEndConditionalRenderingEXT) X(vkCreateQueryPool) \ 91 X(vkCmdBeginConditionalRenderingEXT) X(vkCmdEndConditionalRenderingEXT) X(vkCreateQueryPool) \
91 X(vkDestroyQueryPool) X(vkCmdResetQueryPool) X(vkCmdBeginQuery) X(vkCmdEndQuery) X(vkCmdWriteTimestamp) \ 92 X(vkDestroyQueryPool) X(vkCmdResetQueryPool) X(vkCmdBeginQuery) X(vkCmdEndQuery) X(vkCmdWriteTimestamp) \
@@ -104,7 +105,7 @@ struct VulkanDeviceFunctions {
104 X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \ 105 X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \
105 X(vkCmdSetBlendConstants) X(vkCmdDraw) \ 106 X(vkCmdSetBlendConstants) X(vkCmdDraw) \
106 X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) X(vkGetImageSparseMemoryRequirements) \ 107 X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) X(vkGetImageSparseMemoryRequirements) \
107 X(vkCreatePipelineCache) X(vkDestroyPipelineCache) \ 108 X(vkCreatePipelineCache) X(vkDestroyPipelineCache) X(vkGetPipelineCacheData) X(vkMergePipelineCaches) \
108 X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents) X(vkCmdDrawMeshTasksEXT) \ 109 X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents) X(vkCmdDrawMeshTasksEXT) \
109 X(vkCreateRenderPass2) X(vkDestroyRenderPass) X(vkCreateFramebuffer) X(vkDestroyFramebuffer) \ 110 X(vkCreateRenderPass2) X(vkDestroyRenderPass) X(vkCreateFramebuffer) X(vkDestroyFramebuffer) \
110 X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass) 111 X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass)
@@ -941,6 +942,7 @@ public:
941 replay_.copy_buffer_to_image = vk.vkCmdCopyBufferToImage; 942 replay_.copy_buffer_to_image = vk.vkCmdCopyBufferToImage;
942 replay_.copy_image_to_buffer = vk.vkCmdCopyImageToBuffer; 943 replay_.copy_image_to_buffer = vk.vkCmdCopyImageToBuffer;
943 replay_.copy_image = vk.vkCmdCopyImage; 944 replay_.copy_image = vk.vkCmdCopyImage;
945 replay_.blit_image = vk.vkCmdBlitImage;
944 replay_.resolve_image = vk.vkCmdResolveImage; 946 replay_.resolve_image = vk.vkCmdResolveImage;
945 replay_.fill_buffer = vk.vkCmdFillBuffer; 947 replay_.fill_buffer = vk.vkCmdFillBuffer;
946 replay_.update_buffer = vk.vkCmdUpdateBuffer; 948 replay_.update_buffer = vk.vkCmdUpdateBuffer;
@@ -1142,6 +1144,12 @@ public:
1142 std::unique_lock lock(resource_mutex_); 1144 std::unique_lock lock(resource_mutex_);
1143 set_resource_locked(id, binding); 1145 set_resource_locked(id, binding);
1144 } 1146 }
1147 // Whether `va` is in a buffer this context knows by VA (the index buffer_at searches).
1148 bool knows_buffer_va(std::uint64_t va) {
1149 std::shared_lock lock(resource_mutex_);
1150 BufferVaIndex<ResourceId>::Hit hit{};
1151 return buffer_vas_.find(va, hit);
1152 }
1145 void add_resource(ResourceId id, const ResourceBinding& binding, VkImageLayout current_layout) { 1153 void add_resource(ResourceId id, const ResourceBinding& binding, VkImageLayout current_layout) {
1146 std::unique_lock rlock(resource_mutex_); 1154 std::unique_lock rlock(resource_mutex_);
1147 set_resource_locked(id, binding); 1155 set_resource_locked(id, binding);
@@ -1203,6 +1211,7 @@ public:
1203 } 1211 }
1204 { 1212 {
1205 std::lock_guard lock(storage_mutex_); // a buffer destroyed before any submission is not filled 1213 std::lock_guard lock(storage_mutex_); // a buffer destroyed before any submission is not filled
1214 storage_pending_.erase(id);
1206 std::erase_if(zero_pending_, [id](const PendingZero& zero) { return zero.id == id; }); 1215 std::erase_if(zero_pending_, [id](const PendingZero& zero) { return zero.id == id; });
1207 } 1216 }
1208 if (img) { 1217 if (img) {
@@ -1275,6 +1284,24 @@ public:
1275 replay_.zero_size = size; 1284 replay_.zero_size = size;
1276 } 1285 }
1277 1286
1287 struct GeometryUpload {
1288 std::uint64_t source{}, size{};
1289 VkBuffer buffer{};
1290 VkDeviceSize offset{};
1291 std::shared_ptr<void> owner;
1292 };
1293 using GeometryProvider = std::function<bool(std::uint64_t,std::uint64_t,GeometryUpload&)>;
1294 void set_geometry_provider(GeometryProvider provider) {
1295 std::unique_lock lock(resource_mutex_);
1296 geometry_provider_=std::move(provider);
1297 }
1298
1299 // LOCAL: the copy-in fallback for vertex and index views in title memory (ReplayFunctions::title_memory).
1300 void set_title_memory(std::function<bool(std::uint64_t, std::uint64_t, VkBuffer&, VkDeviceSize&)> copy) {
1301 std::unique_lock lock(resource_mutex_);
1302 replay_.title_memory = std::move(copy);
1303 }
1304
1278 // Pre-expanded 32-bit triangle indices for non-indexed quad lists (ReplayFunctions::quad_indices). 1305 // Pre-expanded 32-bit triangle indices for non-indexed quad lists (ReplayFunctions::quad_indices).
1279 void set_quad_indices(VkBuffer buffer, VkDeviceSize offset, std::uint32_t count) { 1306 void set_quad_indices(VkBuffer buffer, VkDeviceSize offset, std::uint32_t count) {
1280 std::unique_lock lock(resource_mutex_); 1307 std::unique_lock lock(resource_mutex_);
@@ -1323,6 +1350,23 @@ public:
1323 return resources_.find(id) != resources_.end(); 1350 return resources_.find(id) != resources_.end();
1324 } 1351 }
1325 1352
1353 // The registered buffer whose VA range holds `va`, preferring one that holds [va, va + bytes) as buffer_at does: its
1354 // ID, first VA and size in bytes. False when none does, or when `acquire(id)` returns false. `acquire` runs with
1355 // the registry locked, so the resource cannot finish being removed under it: it takes the caller's reference
1356 // (Resource's destructor removes its entry first, which waits for this lock). Used where a console call names a
1357 // buffer by VA only (Xbox device slot 70).
1358 template<class Acquire>
1359 bool buffer_resource_at(std::uint64_t va, std::uint64_t bytes, ResourceId& id, std::uint64_t& start,
1360 std::uint64_t& size, Acquire&& acquire) {
1361 std::shared_lock lock(resource_mutex_);
1362 BufferVaIndex<ResourceId>::Hit hit{};
1363 if (!buffer_vas_.find(va, hit, bytes) || !acquire(hit.id)) return false;
1364 id = hit.id;
1365 start = hit.start;
1366 size = hit.size;
1367 return true;
1368 }
1369
1326 bool ray_tracing_supported() const { return ray_tracing_ && vk.vkCmdBuildAccelerationStructuresKHR != nullptr; } 1370 bool ray_tracing_supported() const { return ray_tracing_ && vk.vkCmdBuildAccelerationStructuresKHR != nullptr; }
1327 bool xdxr_acceleration_structures() const { return xdxr_ != nullptr; } 1371 bool xdxr_acceleration_structures() const { return xdxr_ != nullptr; }
1328 1372
@@ -1397,6 +1441,28 @@ public:
1397 // written: the device brings the bindless set 0 of the translated shaders up to date there (vulkan_bindless.h) 1441 // written: the device brings the bindless set 0 of the translated shaders up to date there (vulkan_bindless.h)
1398 // and records what the set needs first. When it fails, nothing of that call is executed. 1442 // and records what the set needs first. When it fails, nothing of that call is executed.
1399 void set_transfer_only_family(std::uint32_t family) { transfer_only_family_ = family; } 1443 void set_transfer_only_family(std::uint32_t family) { transfer_only_family_ = family; }
1444 void set_graphics_family(std::uint32_t family) { graphics_family_ = family; }
1445 void set_compute_copy_aspects(std::function<VkImageAspectFlags(VkFormat)> check) {
1446 replay_.compute_copy_aspects = std::move(check);
1447 }
1448
1449 // `before` is called at the start of every submission of command lists (a held batch: when it is released),
1450 // before any lock here is taken: the device re-copies its slot-133 shadow buffers from the title's pages there.
1451 // Set once, before the first queue exists.
1452 void set_before_execute(std::function<void()> before) { before_execute_ = std::move(before); }
1453
1454 // Table VAs are offsets in this device's arena. Install its scanner before creating any queues.
1455 using TableScanner = std::function<void(std::uint64_t, std::uint32_t)>;
1456 void set_table_scanner(TableScanner scan) { table_scanner_ = std::move(scan); }
1457 void set_cpu_texture_publisher(std::function<bool()> f) { cpu_texture_publisher_ = std::move(f); }
1458 bool publish_cpu_textures() const { return !cpu_texture_publisher_ || cpu_texture_publisher_(); }
1459 void set_sample_table_resolver(std::function<bool(std::uint64_t,std::uint32_t)> f) { sample_table_resolver_ = std::move(f); }
1460 bool prepare_sample_table(std::uint64_t address, std::uint32_t count) const {
1461 return !sample_table_resolver_ || sample_table_resolver_(address,count);
1462 }
1463 void scan_table(std::uint64_t va, std::uint32_t descriptors) const {
1464 if (table_scanner_) table_scanner_(va, descriptors);
1465 }
1400 1466
1401 void set_bindless_prepare(std::function<bool(VkCommandBuffer)> prepare) { 1467 void set_bindless_prepare(std::function<bool(VkCommandBuffer)> prepare) {
1402 std::unique_lock lock(resource_mutex_); 1468 std::unique_lock lock(resource_mutex_);
@@ -1423,9 +1489,9 @@ public:
1423 // `allocate`. Without this such a copy is refused as unsupported. `extra_usage` is added to the chunks' transfer 1489 // `allocate`. Without this such a copy is refused as unsupported. `extra_usage` is added to the chunks' transfer
1424 // usage, for configure_quad_indices. 1490 // usage, for configure_quad_indices.
1425 void enable_copy_scratch(PFN_vkGetDeviceProcAddr get, ScratchBuffers::Allocate allocate, 1491 void enable_copy_scratch(PFN_vkGetDeviceProcAddr get, ScratchBuffers::Allocate allocate,
1426 VkBufferUsageFlags extra_usage = 0) { 1492 VkBufferUsageFlags extra_usage = 0, std::vector<std::uint32_t> families = {}) {
1427 std::unique_lock lock(resource_mutex_); 1493 std::unique_lock lock(resource_mutex_);
1428 scratch_ = std::make_unique<ScratchBuffers>(get, device_, std::move(allocate), extra_usage); 1494 scratch_ = std::make_unique<ScratchBuffers>(get, device_, std::move(allocate), extra_usage, std::move(families));
1429 if (!scratch_->loaded()) scratch_.reset(); 1495 if (!scratch_->loaded()) scratch_.reset();
1430 } 1496 }
1431 1497
@@ -1586,7 +1652,11 @@ private:
1586 1652
1587 const ResourceBinding* resolve(ResourceId id) const { 1653 const ResourceBinding* resolve(ResourceId id) const {
1588 const auto it = resources_.find(id); 1654 const auto it = resources_.find(id);
1589 return it == resources_.end() ? nullptr : &it->second; 1655 if (it == resources_.end()) return nullptr;
1656 const auto& binding = it->second;
1657 // The caller holds resource_mutex_, so the registered owner's lifetime includes this bind.
1658 if (binding.ensure_residency && !binding.ensure_residency(binding.residency_owner)) return nullptr;
1659 return &binding;
1590 } 1660 }
1591 1661
1592 // Called from prepare; protected by views_mutex_ so concurrent shared_lock readers are safe. 1662 // Called from prepare; protected by views_mutex_ so concurrent shared_lock readers are safe.
@@ -1713,6 +1783,11 @@ private:
1713 std::map<std::tuple<VkFormat, std::uint32_t, VkImageLayout, VkImageLayout, VkResolveModeFlagBits>, VkRenderPass> 1783 std::map<std::tuple<VkFormat, std::uint32_t, VkImageLayout, VkImageLayout, VkResolveModeFlagBits>, VkRenderPass>
1714 resolve_passes_; 1784 resolve_passes_;
1715 std::map<std::tuple<VkImage, VkImage, VkImageView, VkImageView, VkRenderPass>, VkFramebuffer> resolve_framebuffers_; 1785 std::map<std::tuple<VkImage, VkImage, VkImageView, VkImageView, VkRenderPass>, VkFramebuffer> resolve_framebuffers_;
1786 std::function<void()> before_execute_;
1787 TableScanner table_scanner_;
1788 GeometryProvider geometry_provider_;
1789 std::function<bool(std::uint64_t,std::uint32_t)> sample_table_resolver_;
1790 std::function<bool()> cpu_texture_publisher_;
1716 std::function<bool(VkCommandBuffer)> bindless_prepare_; 1791 std::function<bool(VkCommandBuffer)> bindless_prepare_;
1717 std::function<VkDescriptorSet()> bindless_current_; 1792 std::function<VkDescriptorSet()> bindless_current_;
1718 bool bindless_upload_pending_ = false; // tracker_mutex_ 1793 bool bindless_upload_pending_ = false; // tracker_mutex_
@@ -1735,6 +1810,7 @@ private:
1735 std::unique_ptr<QuadIndexExpander> quad_indices_; 1810 std::unique_ptr<QuadIndexExpander> quad_indices_;
1736 std::uint32_t predicate_family_ = UINT32_MAX; 1811 std::uint32_t predicate_family_ = UINT32_MAX;
1737 std::uint32_t transfer_only_family_ = UINT32_MAX; 1812 std::uint32_t transfer_only_family_ = UINT32_MAX;
1813 std::uint32_t graphics_family_ = UINT32_MAX;
1738 DebugLabelFunctions labels_; 1814 DebugLabelFunctions labels_;
1739}; 1815};
1740#ifdef _MSC_VER 1816#ifdef _MSC_VER
@@ -2268,6 +2344,7 @@ private:
2268 2344
2269 ReplayResult execute_now(std::span<const CommandList* const> lists) { 2345 ReplayResult execute_now(std::span<const CommandList* const> lists) {
2270 if (context_.is_device_lost() || !wait_for_room()) return ReplayResult::unsupported; 2346 if (context_.is_device_lost() || !wait_for_room()) return ReplayResult::unsupported;
2347 if (context_.before_execute_) context_.before_execute_();
2271 if (kind_ != QueueKind::direct) 2348 if (kind_ != QueueKind::direct)
2272 for (const auto* list : lists) 2349 for (const auto* list : lists)
2273 for (const auto& command : list->commands()) 2350 for (const auto& command : list->commands())
@@ -2319,6 +2396,23 @@ private:
2319 // use only the first lists.size() entries, so stale entries are never prepared, queried or emitted. 2396 // use only the first lists.size() entries, so stale entries are never prepared, queried or emitted.
2320 if (prepared.size() < lists.size()) prepared.resize(lists.size()); 2397 if (prepared.size() < lists.size()) prepared.resize(lists.size());
2321 ReplayFunctions replay = context_.replay_; 2398 ReplayFunctions replay = context_.replay_;
2399 std::vector<VulkanContext::GeometryUpload> geometry;
2400 if (context_.geometry_provider_) {
2401 replay.title_memory = [&](std::uint64_t va, std::uint64_t bytes, VkBuffer& buffer, VkDeviceSize& offset) {
2402 if (!va || !bytes || bytes>UINT64_MAX-va) return false;
2403 for (const auto& upload : geometry) {
2404 if (va < upload.source || va-upload.source > upload.size || bytes > upload.size-(va-upload.source)) continue;
2405 buffer=upload.buffer; offset=upload.offset+(va-upload.source);
2406 return true;
2407 }
2408 VulkanContext::GeometryUpload upload;
2409 if (!context_.geometry_provider_(va,bytes,upload)) return false;
2410 buffer=upload.buffer;offset=upload.offset;
2411 geometry.push_back(std::move(upload));
2412 return true;
2413 };
2414 }
2415 replay.graphics_family = family_ == context_.graphics_family_;
2322 replay.queue_stages = kind_ == QueueKind::copy ? detail::queue_stages_copy 2416 replay.queue_stages = kind_ == QueueKind::copy ? detail::queue_stages_copy
2323 : kind_ == QueueKind::compute ? detail::queue_stages_compute 2417 : kind_ == QueueKind::compute ? detail::queue_stages_compute
2324 : 0; 2418 : 0;
@@ -2542,6 +2636,7 @@ private:
2542 }; 2636 };
2543 VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; 2637 VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO};
2544 begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; 2638 begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
2639 label::completions().begin_record(command_buffer);
2545 if (context_.vk.vkBeginCommandBuffer(command_buffer, &begin) != VK_SUCCESS) { 2640 if (context_.vk.vkBeginCommandBuffer(command_buffer, &begin) != VK_SUCCESS) {
2546 discard(); 2641 discard();
2547 return ReplayResult::unsupported; 2642 return ReplayResult::unsupported;
@@ -2585,8 +2680,7 @@ private:
2585 storage_init_seen_ = context_.storage_init_version_; 2680 storage_init_seen_ = context_.storage_init_version_;
2586 } 2681 }
2587 // The set this submission binds may be a new generation whose table another queue's submission uploads: 2682 // The set this submission binds may be a new generation whose table another queue's submission uploads:
2588 // wait for that one, as for the storage images (the table's buffers are used by one queue family only: 2683 // wait for that one, as for the storage images. The table and fallback images share the device's families.
2589 // every D3D12 queue of the device is made in info.queue_family).
2590 if (context_.bindless_upload_semaphore_ && context_.bindless_upload_semaphore_ != progress_ && 2684 if (context_.bindless_upload_semaphore_ && context_.bindless_upload_semaphore_ != progress_ &&
2591 context_.bindless_upload_version_ != bindless_upload_seen_) { 2685 context_.bindless_upload_version_ != bindless_upload_seen_) {
2592 waits_.push_back(context_.bindless_upload_semaphore_); 2686 waits_.push_back(context_.bindless_upload_semaphore_);
@@ -2693,6 +2787,7 @@ private:
2693 slot->counted_dispatch = std::move(counted_batch); 2787 slot->counted_dispatch = std::move(counted_batch);
2694 queries.commit(); 2788 queries.commit();
2695 slot->segments = std::move(queries.retained); 2789 slot->segments = std::move(queries.retained);
2790 slot->geometry = std::move(geometry);
2696 } else { 2791 } else {
2697 discard(); 2792 discard();
2698 } 2793 }
@@ -2927,6 +3022,7 @@ private:
2927 std::unique_ptr<PredicateReducer::Batch> predicate; // retained until this slot completes 3022 std::unique_ptr<PredicateReducer::Batch> predicate; // retained until this slot completes
2928 std::vector<KhrInstanceStage> khr_instances; // KHR ARRAY_OF_POINTERS staging, same lifetime 3023 std::vector<KhrInstanceStage> khr_instances; // KHR ARRAY_OF_POINTERS staging, same lifetime
2929 std::vector<KhrAsQueryPool> khr_as_queries; // KHR postbuild COMPACTED_SIZE query pools, same lifetime 3024 std::vector<KhrAsQueryPool> khr_as_queries; // KHR postbuild COMPACTED_SIZE query pools, same lifetime
3025 std::vector<VulkanContext::GeometryUpload> geometry;
2930 }; 3026 };
2931 3027
2932 struct PendingBindings { 3028 struct PendingBindings {
@@ -2949,6 +3045,7 @@ private:
2949 auto& vk = context_.vk; 3045 auto& vk = context_.vk;
2950 VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; 3046 VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO};
2951 begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; 3047 begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
3048 label::completions().begin_record(command_buffer);
2952 if (vk.vkBeginCommandBuffer(command_buffer, &begin) != VK_SUCCESS) { 3049 if (vk.vkBeginCommandBuffer(command_buffer, &begin) != VK_SUCCESS) {
2953 slot->ticket = 0; 3050 slot->ticket = 0;
2954 return false; 3051 return false;
@@ -3087,6 +3184,7 @@ private:
3087 for (auto& slot : buffers_) { 3184 for (auto& slot : buffers_) {
3088 if (slot.ticket > done) continue; 3185 if (slot.ticket > done) continue;
3089 slot.segments.clear(); 3186 slot.segments.clear();
3187 slot.geometry.clear();
3090 recycle_khr_stages(slot.khr_instances); 3188 recycle_khr_stages(slot.khr_instances);
3091 recycle_khr_as_queries(slot.khr_as_queries); 3189 recycle_khr_as_queries(slot.khr_as_queries);
3092 for (VkEvent event : slot.events) 3190 for (VkEvent event : slot.events)
@@ -3223,7 +3321,9 @@ private:
3223 submit.pCommandBuffers = &command_buffer; 3321 submit.pCommandBuffers = &command_buffer;
3224 submit.signalSemaphoreCount = signal_count; 3322 submit.signalSemaphoreCount = signal_count;
3225 submit.pSignalSemaphores = signals; 3323 submit.pSignalSemaphores = signals;
3226 res = context_.vk.vkQueueSubmit(queue_, 1, &submit, VK_NULL_HANDLE); 3324 const auto label_fence=label::completions().submit_fence(command_buffer);
3325 res = context_.vk.vkQueueSubmit(queue_, 1, &submit, label_fence);
3326 label::completions().submitted(command_buffer,res==VK_SUCCESS);
3227 if (res == VK_SUCCESS) { 3327 if (res == VK_SUCCESS) {
3228 context_.record_submit_locked(progress_, ticket); 3328 context_.record_submit_locked(progress_, ticket);
3229 if (signals_fence) context_.holds().signaled(fence, value); 3329 if (signals_fence) context_.holds().signaled(fence, value);
diff --git a/runtime/src/vulkan_bindless.h b/runtime/src/vulkan_bindless.h
index cb5b61f65..1477a9924 100644
--- a/runtime/src/vulkan_bindless.h
+++ b/runtime/src/vulkan_bindless.h
@@ -8,9 +8,10 @@
8// 2 the descriptor hash table 1 7 3D r32ui storage images 256 8// 2 the descriptor hash table 1 7 3D r32ui storage images 256
9// 3 sampled 2D-array images 1024 8 + 3 * dimension + class 256 each: 9// 3 sampled 2D-array images 1024 8 + 3 * dimension + class 256 each:
10// 4 2D r32ui storage images 1024 storage images by component class 10// 4 2D r32ui storage images 1024 storage images by component class
11// dimension: 0 = 2D, 1 = 2D array, 2 = 3D, 3 = 1D (the translator's STORE_DIMS); class: 0 = float, 1 = uint, 2 = sint. 11// dimension: 0 = 2D, 1 = 2D array, 2 = 3D, 3 = 1D (the first four STORE_DIMS); class: 0 = float, 1 = uint, 2 = sint.
12// bindings 20/21: sampled multisample 2D images / 2D arrays, 256 each (runtime SRVs). 12// bindings 20/21: sampled multisample 2D images / 2D arrays, 256 each (runtime SRVs).
13// bindings 22/23 and 24/25 are their UINT and SINT equivalents on devices supporting those classes. 13// bindings 22/23 and 24/25 are their UINT and SINT equivalents on devices supporting those classes.
14// bindings 26-28: storage-only 1D-array images by component class, 256 each (STORE_DIMS index 4).
14// These are the default counts (BindlessFeatures::counts). size_bindings() sizes the 2D, sampler and storage arrays 15// These are the default counts (BindlessFeatures::counts). size_bindings() sizes the 2D, sampler and storage arrays
15// from the device's limits instead; the shaders declare runtime arrays, so any count works for them. 16// from the device's limits instead; the shaders declare runtime arrays, so any count works for them.
16// 17//
@@ -43,6 +44,7 @@
43#define VK_NO_PROTOTYPES 44#define VK_NO_PROTOTYPES
44#endif 45#endif
45#include "descriptor_table.h" 46#include "descriptor_table.h"
47#include "queue_families.h"
46 48
47#include <vulkan/vulkan.h> 49#include <vulkan/vulkan.h>
48 50
@@ -52,12 +54,13 @@
52#include <cstring> 54#include <cstring>
53#include <functional> 55#include <functional>
54#include <unordered_map> 56#include <unordered_map>
57#include <utility>
55#include <vector> 58#include <vector>
56 59
57namespace leonida { 60namespace leonida {
58 61
59// The first four dimensions are the translator's STORE_DIMS indices. A cube is a 2D array of six layers. 62// The first five dimensions are the translator's STORE_DIMS indices. A cube is a 2D array of six layers.
60enum class ImageDimension : std::uint32_t { dim_2d, dim_2d_array, dim_3d, dim_1d, dim_2d_ms, dim_2d_ms_array }; 63enum class ImageDimension : std::uint32_t { dim_2d, dim_2d_array, dim_3d, dim_1d, dim_1d_array, dim_2d_ms, dim_2d_ms_array };
61 64
62// Storage views of one image by the component type a shader reads or writes it with (the translator picks by the 65// Storage views of one image by the component type a shader reads or writes it with (the translator picks by the
63// T# format at run time). r32ui is for the atomic instructions, whose image type is R32ui (2D and 3D only). 66// T# format at run time). r32ui is for the atomic instructions, whose image type is R32ui (2D and 3D only).
@@ -70,7 +73,7 @@ struct StorageViews {
70}; 73};
71 74
72namespace bindless { 75namespace bindless {
73inline constexpr std::uint32_t binding_count = 26; 76inline constexpr std::uint32_t binding_count = 29;
74constexpr std::array<std::uint32_t, binding_count> default_counts(); 77constexpr std::array<std::uint32_t, binding_count> default_counts();
75} // namespace bindless 78} // namespace bindless
76 79
@@ -94,10 +97,12 @@ struct Binding {
94inline constexpr std::uint32_t table_binding = 2; 97inline constexpr std::uint32_t table_binding = 2;
95inline constexpr std::uint32_t sampler_binding = 1; 98inline constexpr std::uint32_t sampler_binding = 1;
96inline constexpr std::uint32_t first_ms_binding = 20; 99inline constexpr std::uint32_t first_ms_binding = 20;
100inline constexpr std::uint32_t ms_binding_count = 6;
101inline constexpr std::uint32_t first_1d_array_storage_binding = first_ms_binding + ms_binding_count;
97inline constexpr std::uint32_t no_binding = 0xffffffffu; 102inline constexpr std::uint32_t no_binding = 0xffffffffu;
98 103
99// Indexed by binding number. 104// Indexed by binding number. Keep the literal extent for tools/spirv_metal_set0.py.
100inline constexpr std::array<Binding, 26> bindings = {{ 105inline constexpr std::array<Binding, 29> bindings = {{
101 {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 4096}, {VK_DESCRIPTOR_TYPE_SAMPLER, 1024}, 106 {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 4096}, {VK_DESCRIPTOR_TYPE_SAMPLER, 1024},
102 {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1024}, 107 {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1024},
103 {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1024}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, 108 {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1024}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256},
@@ -111,6 +116,8 @@ inline constexpr std::array<Binding, 26> bindings = {{
111 {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, 116 {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256},
112 {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, 117 {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256},
113 {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, 118 {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256},
119 {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256},
120 {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256},
114}}; 121}};
115 122
116static_assert(bindings.size() == binding_count); 123static_assert(bindings.size() == binding_count);
@@ -121,8 +128,12 @@ constexpr std::array<std::uint32_t, binding_count> default_counts() {
121 return counts; 128 return counts;
122} 129}
123 130
131constexpr bool ms_binding(std::uint32_t binding) {
132 return binding >= first_ms_binding && binding < first_ms_binding + ms_binding_count;
133}
134
124constexpr bool binding_enabled(std::uint32_t binding, const BindlessFeatures& features) { 135constexpr bool binding_enabled(std::uint32_t binding, const BindlessFeatures& features) {
125 return binding < first_ms_binding || features.ms_samples[(binding - first_ms_binding) / 2] != VK_SAMPLE_COUNT_1_BIT; 136 return !ms_binding(binding) || features.ms_samples[(binding - first_ms_binding) / 2] != VK_SAMPLE_COUNT_1_BIT;
126} 137}
127 138
128// Every binding is visible to every shader stage. Preserve the single-sample layout on devices whose 139// Every binding is visible to every shader stage. Preserve the single-sample layout on devices whose
@@ -131,7 +142,8 @@ constexpr void limit_ms_bindings(BindlessFeatures& features, std::uint32_t sampl
131 std::uint32_t resource_limit) { 142 std::uint32_t resource_limit) {
132 const auto& counts = features.counts; 143 const auto& counts = features.counts;
133 std::uint32_t sampled = 0, total = 0; 144 std::uint32_t sampled = 0, total = 0;
134 for (std::uint32_t b = 0; b < first_ms_binding; ++b) { 145 for (std::uint32_t b = 0; b < binding_count; ++b) {
146 if (ms_binding(b)) continue;
135 if (bindings[b].type == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) sampled += counts[b]; 147 if (bindings[b].type == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) sampled += counts[b];
136 if (bindings[b].type != VK_DESCRIPTOR_TYPE_SAMPLER) total += counts[b]; 148 if (bindings[b].type != VK_DESCRIPTOR_TYPE_SAMPLER) total += counts[b];
137 } 149 }
@@ -153,12 +165,13 @@ constexpr bool multisampled(ImageDimension dimension) {
153} 165}
154 166
155constexpr std::uint32_t sampled_binding(ImageDimension dimension, std::uint32_t component_class = 0) { 167constexpr std::uint32_t sampled_binding(ImageDimension dimension, std::uint32_t component_class = 0) {
156 constexpr std::uint32_t by_dimension[] = {0, 3, 6, 5, first_ms_binding, first_ms_binding + 1}; 168 constexpr std::uint32_t by_dimension[] = {0, 3, 6, 5, no_binding, first_ms_binding, first_ms_binding + 1};
157 return by_dimension[std::uint32_t(dimension)] + (multisampled(dimension) ? component_class * 2 : 0); 169 return by_dimension[std::uint32_t(dimension)] + (multisampled(dimension) ? component_class * 2 : 0);
158} 170}
159 171
160// component_class: 0 = float, 1 = uint, 2 = sint. 172// component_class: 0 = float, 1 = uint, 2 = sint.
161constexpr std::uint32_t storage_binding(ImageDimension dimension, std::uint32_t component_class) { 173constexpr std::uint32_t storage_binding(ImageDimension dimension, std::uint32_t component_class) {
174 if (dimension == ImageDimension::dim_1d_array) return first_1d_array_storage_binding + component_class;
162 return multisampled(dimension) ? no_binding : 8 + 3 * std::uint32_t(dimension) + component_class; 175 return multisampled(dimension) ? no_binding : 8 + 3 * std::uint32_t(dimension) + component_class;
163} 176}
164 177
@@ -196,8 +209,9 @@ struct SetLayout {
196}; 209};
197 210
198// What size_bindings() grows to where the device's limits allow. At 32-64 bytes a descriptor the whole set is then 211// What size_bindings() grows to where the device's limits allow. At 32-64 bytes a descriptor the whole set is then
199// 3-6 MiB (93793 descriptors on an RTX 5070). 212// roughly 4-8 MiB with 119137 descriptors when all MS classes and array bindings reach their limits.
200inline constexpr std::uint32_t max_2d_images = 65536; 213inline constexpr std::uint32_t max_2d_images = 65536;
214inline constexpr std::uint32_t max_2d_array_images = 16384;
201inline constexpr std::uint32_t max_storage_indices = 4096; // in each storage array, at most its dimension's images 215inline constexpr std::uint32_t max_storage_indices = 4096; // in each storage array, at most its dimension's images
202// A full D3D12 shader-visible sampler heap (2048) and room for literal and static S#s, within what the device can 216// A full D3D12 shader-visible sampler heap (2048) and room for literal and static S#s, within what the device can
203// create (maxSamplerAllocationCount, at least 4000) less the samplers that are not in the set. 217// create (maxSamplerAllocationCount, at least 4000) less the samplers that are not in the set.
@@ -214,8 +228,9 @@ inline constexpr std::uint32_t growth_headroom = 64;
214// 2. The MS pairs that fit beside them (limit_ms_bindings, which may turn classes off). 228// 2. The MS pairs that fit beside them (limit_ms_bindings, which may turn classes off).
215// 3. Growth towards the maximums above, in the same order, within maxPerSetDescriptors. That limit only says 229// 3. Growth towards the maximums above, in the same order, within maxPerSetDescriptors. That limit only says
216// what is sure to work (vkGetDescriptorSetLayoutSupport may allow more), so it never shrinks step 1. 230// what is sure to work (vkGetDescriptorSetLayoutSupport may allow more), so it never shrinks step 1.
217// A storage array holds the smaller of the storage count and its dimension's images: add_image never gives a 231// A storage array holds the smaller of the storage count and its dimension's sampled count: add_image never
218// storage view an index past the sampled array. The other bindings keep their default counts. 232// gives a storage view an index past the sampled array. The storage-only 1D array is capped at its default of 256.
233// The other bindings keep their default counts.
219// layout_supported, when given, answers vkGetDescriptorSetLayoutSupport for set 0 at the counts in its argument: 234// layout_supported, when given, answers vkGetDescriptorSetLayoutSupport for set 0 at the counts in its argument:
220// step 3 then also grows past maxPerSetDescriptors where the device says the layout works (Intel's Xe-LP reports 235// step 3 then also grows past maxPerSetDescriptors where the device says the layout works (Intel's Xe-LP reports
221// 6159 and supports the full sizes, D3D-219). It is asked only once the sum is above maxPerSetDescriptors. 236// 6159 and supports the full sizes, D3D-219). It is asked only once the sum is above maxPerSetDescriptors.
@@ -243,15 +258,20 @@ inline bool size_bindings(BindlessFeatures& features, const VkPhysicalDeviceLimi
243 auto& counts = features.counts; 258 auto& counts = features.counts;
244 counts = default_counts(); 259 counts = default_counts();
245 std::uint32_t images = 1, samplers = 1, storage = 1; 260 std::uint32_t images = 1, samplers = 1, storage = 1;
261 std::uint32_t array_images = bindings[sampled_binding(ImageDimension::dim_2d_array)].count;
246 // Until the end the 2D storage arrays are not capped by the 2D images, which grow after them: capping can only 262 // Until the end the 2D storage arrays are not capped by the 2D images, which grow after them: capping can only
247 // take descriptors away. 263 // take descriptors away.
248 const auto apply = [&](bool final) { 264 const auto apply = [&](bool final) {
249 counts[sampled_binding(ImageDimension::dim_2d)] = images; 265 counts[sampled_binding(ImageDimension::dim_2d)] = images;
266 counts[sampled_binding(ImageDimension::dim_2d_array)] = array_images;
250 counts[sampler_binding] = samplers; 267 counts[sampler_binding] = samplers;
251 for (std::uint32_t d = 0; d < 4; ++d) { 268 for (std::uint32_t d = 0; d <= std::uint32_t(ImageDimension::dim_1d_array); ++d) {
252 const auto dimension = ImageDimension(d); 269 const auto dimension = ImageDimension(d);
270 const auto sampled_at = sampled_binding(dimension);
271 const auto capacity = sampled_at == no_binding ? bindings[storage_binding(dimension, 0)].count
272 : counts[sampled_at];
253 const bool capped = final || dimension != ImageDimension::dim_2d; 273 const bool capped = final || dimension != ImageDimension::dim_2d;
254 const std::uint32_t held = capped ? std::min(storage, counts[sampled_binding(dimension)]) : storage; 274 const std::uint32_t held = capped ? std::min(storage, capacity) : storage;
255 for (std::uint32_t c = 0; c < 3; ++c) counts[storage_binding(dimension, c)] = held; 275 for (std::uint32_t c = 0; c < 3; ++c) counts[storage_binding(dimension, c)] = held;
256 if (r32ui_binding(dimension) != no_binding) counts[r32ui_binding(dimension)] = held; 276 if (r32ui_binding(dimension) != no_binding) counts[r32ui_binding(dimension)] = held;
257 } 277 }
@@ -305,6 +325,9 @@ inline bool size_bindings(BindlessFeatures& features, const VkPhysicalDeviceLimi
305 grow(samplers, std::max(samplers, std::min(max_samplers, creatable)), growth_headroom, set_limit); 325 grow(samplers, std::max(samplers, std::min(max_samplers, creatable)), growth_headroom, set_limit);
306 grow(images, std::max(images, max_2d_images), growth_headroom, set_limit); 326 grow(images, std::max(images, max_2d_images), growth_headroom, set_limit);
307 grow(storage, std::max(storage, max_storage_indices), growth_headroom, set_limit); 327 grow(storage, std::max(storage, max_storage_indices), growth_headroom, set_limit);
328 // A material can keep many array-layer and cube views alive at once. Grow them only out of
329 // the remaining set budget, including any storage bindings that share their index range.
330 grow(array_images, max_2d_array_images, growth_headroom, set_limit);
308 apply(true); 331 apply(true);
309 return full; 332 return full;
310} 333}
@@ -314,8 +337,8 @@ inline bool size_bindings(BindlessFeatures& features, const VkPhysicalDeviceLimi
314class BindlessSet { 337class BindlessSet {
315public: 338public:
316 BindlessSet(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceMemoryProperties& memory, 339 BindlessSet(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceMemoryProperties& memory,
317 BindlessFeatures features = {}) 340 BindlessFeatures features = {}, std::vector<std::uint32_t> families = {})
318 : device_(device), memory_(memory), features_(features) { 341 : device_(device), memory_(memory), features_(features), families_(std::move(families)) {
319 ok_ = vk_.load(get, device) && create_layout() && create_fallbacks() && create_table_buffers() && fill(); 342 ok_ = vk_.load(get, device) && create_layout() && create_fallbacks() && create_table_buffers() && fill();
320 } 343 }
321 344
@@ -342,7 +365,8 @@ public:
342 // How many images of a dimension the set holds, the fallback included, and how many of the lowest of those 365 // How many images of a dimension the set holds, the fallback included, and how many of the lowest of those
343 // indices its storage arrays hold (0 for the MS dimensions, which have none). The same for samplers. 366 // indices its storage arrays hold (0 for the MS dimensions, which have none). The same for samplers.
344 std::uint32_t image_capacity(ImageDimension dimension) const { 367 std::uint32_t image_capacity(ImageDimension dimension) const {
345 return features_.counts[bindless::sampled_binding(dimension)]; 368 const auto binding = bindless::sampled_binding(dimension);
369 return binding == bindless::no_binding ? storage_capacity(dimension) : features_.counts[binding];
346 } 370 }
347 std::uint32_t storage_capacity(ImageDimension dimension) const { 371 std::uint32_t storage_capacity(ImageDimension dimension) const {
348 return bindless::multisampled(dimension) ? 0 : features_.counts[bindless::storage_binding(dimension, 0)]; 372 return bindless::multisampled(dimension) ? 0 : features_.counts[bindless::storage_binding(dimension, 0)];
@@ -401,6 +425,7 @@ public:
401 std::uint32_t add_image(ImageDimension dimension, VkImageView sampled, VkImageLayout sampled_layout, 425 std::uint32_t add_image(ImageDimension dimension, VkImageView sampled, VkImageLayout sampled_layout,
402 const StorageViews& storage = {}, std::uint32_t sampled_class = 0) { 426 const StorageViews& storage = {}, std::uint32_t sampled_class = 0) {
403 const bool stores = storage.as_float || storage.as_uint || storage.as_sint || storage.r32ui; 427 const bool stores = storage.as_float || storage.as_uint || storage.as_sint || storage.r32ui;
428 if (!stores && bindless::sampled_binding(dimension) == bindless::no_binding) return 0;
404 if (bindless::multisampled(dimension) && (stores || !supports_ms_class(sampled_class))) return 0; 429 if (bindless::multisampled(dimension) && (stores || !supports_ms_class(sampled_class))) return 0;
405 auto& used = image_used_[std::uint32_t(dimension)]; 430 auto& used = image_used_[std::uint32_t(dimension)];
406 const std::uint32_t low_end = std::min(std::uint32_t(used.size()), storage_capacity(dimension)); 431 const std::uint32_t low_end = std::min(std::uint32_t(used.size()), storage_capacity(dimension));
@@ -597,7 +622,7 @@ private:
597 VkDescriptorImageInfo info; 622 VkDescriptorImageInfo info;
598 }; 623 };
599 624
600 static constexpr std::uint32_t dimensions = 6, classes = 3; 625 static constexpr std::uint32_t dimensions = 7, classes = 3;
601 626
602 // The first free index in [begin, end), marked used; 0 when there is none. 627 // The first free index in [begin, end), marked used; 0 when there is none.
603 static std::uint32_t allocate(std::vector<std::uint8_t>& used, std::uint32_t begin, std::uint32_t end) { 628 static std::uint32_t allocate(std::vector<std::uint8_t>& used, std::uint32_t begin, std::uint32_t end) {
@@ -695,10 +720,11 @@ private:
695 constexpr std::uint32_t ms_type = 3; 720 constexpr std::uint32_t ms_type = 3;
696 constexpr VkFormat formats[classes] = {VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R32_UINT, VK_FORMAT_R32_SINT}; 721 constexpr VkFormat formats[classes] = {VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R32_UINT, VK_FORMAT_R32_SINT};
697 // dimension -> (index into types, view type) 722 // dimension -> (index into types, view type)
698 constexpr std::uint32_t type_of[dimensions] = {0, 0, 1, 2, ms_type, ms_type}; 723 constexpr std::uint32_t type_of[dimensions] = {0, 0, 1, 2, 2, ms_type, ms_type};
699 constexpr VkImageViewType view_types[dimensions] = {VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_VIEW_TYPE_2D_ARRAY, 724 constexpr VkImageViewType view_types[dimensions] = {VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_VIEW_TYPE_2D_ARRAY,
700 VK_IMAGE_VIEW_TYPE_3D, VK_IMAGE_VIEW_TYPE_1D, 725 VK_IMAGE_VIEW_TYPE_3D, VK_IMAGE_VIEW_TYPE_1D,
701 VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_VIEW_TYPE_2D_ARRAY}; 726 VK_IMAGE_VIEW_TYPE_1D_ARRAY,
727 VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_VIEW_TYPE_2D_ARRAY};
702 for (std::uint32_t t = 0; t < std::size(types); ++t) { 728 for (std::uint32_t t = 0; t < std::size(types); ++t) {
703 for (std::uint32_t c = 0; c < classes; ++c) { 729 for (std::uint32_t c = 0; c < classes; ++c) {
704 if (t == ms_type && !supports_ms_class(c)) continue; 730 if (t == ms_type && !supports_ms_class(c)) continue;
@@ -713,6 +739,7 @@ private:
713 if (t != ms_type) info.usage |= VK_IMAGE_USAGE_STORAGE_BIT; 739 if (t != ms_type) info.usage |= VK_IMAGE_USAGE_STORAGE_BIT;
714 if (t == ms_type || c == 0) info.usage |= VK_IMAGE_USAGE_SAMPLED_BIT; 740 if (t == ms_type || c == 0) info.usage |= VK_IMAGE_USAGE_SAMPLED_BIT;
715 FallbackImage& image = fallback_images_[t * classes + c]; 741 FallbackImage& image = fallback_images_[t * classes + c];
742 share_across_queue_families(info, families_);
716 if (vk_.vkCreateImage(device_, &info, nullptr, &image.image) != VK_SUCCESS) return false; 743 if (vk_.vkCreateImage(device_, &info, nullptr, &image.image) != VK_SUCCESS) return false;
717 VkMemoryRequirements requirements{}; 744 VkMemoryRequirements requirements{};
718 vk_.vkGetImageMemoryRequirements(device_, image.image, &requirements); 745 vk_.vkGetImageMemoryRequirements(device_, image.image, &requirements);
@@ -737,8 +764,9 @@ private:
737 VkImageView view = VK_NULL_HANDLE; 764 VkImageView view = VK_NULL_HANDLE;
738 if (vk_.vkCreateImageView(device_, &info, nullptr, &view) != VK_SUCCESS) return false; 765 if (vk_.vkCreateImageView(device_, &info, nullptr, &view) != VK_SUCCESS) return false;
739 fallback_views_.push_back(view); 766 fallback_views_.push_back(view);
740 if (c == 0 || bindless::multisampled(dimension)) 767 const auto sampled_at = bindless::sampled_binding(dimension, c);
741 fallback_by_binding_[bindless::sampled_binding(dimension, c)] = view; 768 if (sampled_at != bindless::no_binding && (c == 0 || bindless::multisampled(dimension)))
769 fallback_by_binding_[sampled_at] = view;
742 const auto storage_at = bindless::storage_binding(dimension, c); 770 const auto storage_at = bindless::storage_binding(dimension, c);
743 if (storage_at != bindless::no_binding) fallback_by_binding_[storage_at] = view; 771 if (storage_at != bindless::no_binding) fallback_by_binding_[storage_at] = view;
744 const auto r32ui_at = bindless::r32ui_binding(dimension); 772 const auto r32ui_at = bindless::r32ui_binding(dimension);
@@ -760,6 +788,7 @@ private:
760 (device_local ? VK_BUFFER_USAGE_TRANSFER_DST_BIT : VK_BUFFER_USAGE_TRANSFER_SRC_BIT); 788 (device_local ? VK_BUFFER_USAGE_TRANSFER_DST_BIT : VK_BUFFER_USAGE_TRANSFER_SRC_BIT);
761 TableBuffer made; 789 TableBuffer made;
762 made.size = bytes; 790 made.size = bytes;
791 share_across_queue_families(info, families_);
763 if (vk_.vkCreateBuffer(device_, &info, nullptr, &made.buffer) != VK_SUCCESS) return false; 792 if (vk_.vkCreateBuffer(device_, &info, nullptr, &made.buffer) != VK_SUCCESS) return false;
764 VkMemoryRequirements requirements{}; 793 VkMemoryRequirements requirements{};
765 vk_.vkGetBufferMemoryRequirements(device_, made.buffer, &requirements); 794 vk_.vkGetBufferMemoryRequirements(device_, made.buffer, &requirements);
@@ -998,8 +1027,9 @@ private:
998 return; 1027 return;
999 } 1028 }
1000 const std::uint32_t sampled_at = bindless::sampled_binding(dimension); 1029 const std::uint32_t sampled_at = bindless::sampled_binding(dimension);
1001 queue(sampled_at, index, 1030 if (sampled_at != bindless::no_binding)
1002 sampled ? VkDescriptorImageInfo{VK_NULL_HANDLE, sampled, sampled_layout} : fallback_info(sampled_at)); 1031 queue(sampled_at, index,
1032 sampled ? VkDescriptorImageInfo{VK_NULL_HANDLE, sampled, sampled_layout} : fallback_info(sampled_at));
1003 const auto store = [&](std::uint32_t binding, VkImageView view) { 1033 const auto store = [&](std::uint32_t binding, VkImageView view) {
1004 if (binding == bindless::no_binding || index >= features_.counts[binding]) return; 1034 if (binding == bindless::no_binding || index >= features_.counts[binding]) return;
1005 queue(binding, index, 1035 queue(binding, index,
@@ -1014,6 +1044,7 @@ private:
1014 VkDevice device_; 1044 VkDevice device_;
1015 VkPhysicalDeviceMemoryProperties memory_; 1045 VkPhysicalDeviceMemoryProperties memory_;
1016 BindlessFeatures features_; 1046 BindlessFeatures features_;
1047 std::vector<std::uint32_t> families_;
1017 Functions vk_; 1048 Functions vk_;
1018 bool ok_ = false; 1049 bool ok_ = false;
1019 VkDescriptorSetLayout layout_ = VK_NULL_HANDLE; 1050 VkDescriptorSetLayout layout_ = VK_NULL_HANDLE;
diff --git a/runtime/src/vulkan_gpu_labels.h b/runtime/src/vulkan_gpu_labels.h
new file mode 100644
index 000000000..d507fb171
--- /dev/null
+++ b/runtime/src/vulkan_gpu_labels.h
@@ -0,0 +1,156 @@
1#pragma once
2#include "gpu_label_memory.h"
3#include <vulkan/vulkan.h>
4#include <algorithm>
5#include <atomic>
6#include <chrono>
7#include <condition_variable>
8#include <cstdio>
9#include <cstdlib>
10#include <memory>
11#include <mutex>
12#include <thread>
13#include <unordered_map>
14#include <utility>
15#include <vector>
16#ifdef _WIN32
17#include <windows.h>
18#endif
19
20namespace leonida::label {
21inline bool enabled() {
22 static const bool active=[] {const char* v=std::getenv("LEONIDA_GPU_LABELS");return v && v[0]=='1';}();
23 return active;
24}
25// Each submitted Vulkan command buffer owns a fence and its query slots until the GPU finishes it.
26// The CPU destination is a generation-checked title data allocation. No guest pointer is a GPU command destination.
27class Completions {
28 static constexpr unsigned per_pool=64;
29 struct Batch {
30 VkFence fence{};
31 std::vector<VkQueryPool> pools;
32 std::vector<Write> labels;
33 };
34 std::mutex mutex_; std::condition_variable changed_; bool closing_=false;
35 std::thread worker_; bool process_shutdown_=false; VkDevice device_{};
36 std::unordered_map<VkCommandBuffer,std::unique_ptr<Batch>> recording_;
37 std::vector<std::unique_ptr<Batch>> pending_;
38 std::vector<VkQueryPool> idle_pools_; std::vector<VkFence> idle_fences_;
39 PFN_vkCreateQueryPool create_pool_{}; PFN_vkDestroyQueryPool destroy_pool_{};
40 PFN_vkCmdResetQueryPool reset_query_{}; PFN_vkCmdWriteTimestamp timestamp_{}; PFN_vkGetQueryPoolResults results_{};
41 PFN_vkCreateFence create_fence_{}; PFN_vkDestroyFence destroy_fence_{}; PFN_vkGetFenceStatus fence_status_{};
42 PFN_vkResetFences reset_fences_{}; PFN_vkDeviceWaitIdle device_idle_{};
43 std::uint64_t published_[3]{},lost_{},errors_{};
44 VkQueryPool pool() {
45 if(!idle_pools_.empty()){auto h=idle_pools_.back();idle_pools_.pop_back();return h;}
46 VkQueryPoolCreateInfo c{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO};c.queryType=VK_QUERY_TYPE_TIMESTAMP;c.queryCount=per_pool;
47 VkQueryPool p{};return create_pool_(device_,&c,nullptr,&p)==VK_SUCCESS?p:VK_NULL_HANDLE;
48 }
49 VkFence fence() {
50 if(!idle_fences_.empty()){auto f=idle_fences_.back();idle_fences_.pop_back();if(reset_fences_(device_,1,&f)==VK_SUCCESS)return f;destroy_fence_(device_,f,nullptr);}
51 VkFenceCreateInfo c{VK_STRUCTURE_TYPE_FENCE_CREATE_INFO};VkFence f{};return create_fence_(device_,&c,nullptr,&f)==VK_SUCCESS?f:VK_NULL_HANDLE;
52 }
53 void recycle(Batch& b) {for(auto p:b.pools)idle_pools_.push_back(p);if(b.fence)idle_fences_.push_back(b.fence);}
54 static bool store(const Target& target,std::uint64_t value) {
55#ifdef _WIN32
56 return memory().publish(target,[&](std::uintptr_t address,unsigned width,std::uintptr_t allocation_base){
57 MEMORY_BASIC_INFORMATION mbi{};
58 if(!VirtualQuery(reinterpret_cast<const void*>(address),&mbi,sizeof(mbi)) || mbi.State!=MEM_COMMIT ||
59 mbi.Type!=MEM_PRIVATE || reinterpret_cast<std::uintptr_t>(mbi.AllocationBase)!=allocation_base ||
60 (mbi.Protect&PAGE_GUARD) || ((mbi.Protect&0xff)!=PAGE_READWRITE && (mbi.Protect&0xff)!=PAGE_WRITECOPY)) return false;
61 const auto begin=reinterpret_cast<std::uintptr_t>(mbi.BaseAddress);
62 if(address<begin || address-begin>mbi.RegionSize || mbi.RegionSize-(address-begin)<width)return false;
63 if(width==4) InterlockedExchange(reinterpret_cast<volatile LONG*>(address),static_cast<LONG>(value));
64 else InterlockedExchange64(reinterpret_cast<volatile LONG64*>(address),static_cast<LONG64>(value));
65 return true;
66 });
67#else
68 (void)target;(void)value;return false;
69#endif
70 }
71 void publish(const Batch& batch) {
72 for(std::size_t i=0;i<batch.labels.size();++i) {
73 const Write& op=batch.labels[i];std::uint64_t value=op.value;
74 if(op.clock==1) {
75 if(results_(device_,batch.pools[i/per_pool],static_cast<unsigned>(i%per_pool),1,sizeof(value),&value,
76 sizeof(value),VK_QUERY_RESULT_64_BIT)!=VK_SUCCESS){++errors_;continue;}
77 } else if(op.clock==2) {
78#ifdef _WIN32
79 LARGE_INTEGER qpc{}; if(!QueryPerformanceCounter(&qpc)){++errors_;continue;}
80 value=static_cast<std::uint64_t>(qpc.QuadPart);
81#else
82 ++errors_;continue;
83#endif
84 }
85 if(store(op.target,value))++published_[op.clock];else ++lost_;
86 }
87 }
88 void run() {
89 std::unique_lock lock(mutex_);
90 for(;;) {
91 if(pending_.empty() && !closing_) changed_.wait(lock,[&]{return closing_ || !pending_.empty();});
92 if(process_shutdown_)return;
93 for(auto i=pending_.begin();i!=pending_.end();) {
94 auto& b=**i;const auto status=fence_status_(device_,b.fence);
95 if(status==VK_NOT_READY && !closing_){++i;continue;}
96 if(status==VK_SUCCESS)publish(b);else ++errors_;
97 recycle(b);i=pending_.erase(i);
98 }
99 if(closing_)return;
100 if(!pending_.empty())changed_.wait_for(lock,std::chrono::milliseconds(1));
101 }
102 }
103public:
104 ~Completions() {
105 if(!worker_.joinable())return;
106 {std::lock_guard lock(mutex_);process_shutdown_=true;closing_=true;changed_.notify_all();}
107 worker_.join();
108 }
109 void initialize(VkDevice dev,PFN_vkGetDeviceProcAddr get) {
110 if(!enabled() || !dev || !get)return;
111 std::lock_guard lock(mutex_);if(device_)return;
112#define LABEL_FN(name) reinterpret_cast<PFN_##name>(get(dev,#name))
113 create_pool_=LABEL_FN(vkCreateQueryPool);destroy_pool_=LABEL_FN(vkDestroyQueryPool);
114 reset_query_=LABEL_FN(vkCmdResetQueryPool);timestamp_=LABEL_FN(vkCmdWriteTimestamp);results_=LABEL_FN(vkGetQueryPoolResults);
115 create_fence_=LABEL_FN(vkCreateFence);destroy_fence_=LABEL_FN(vkDestroyFence);fence_status_=LABEL_FN(vkGetFenceStatus);
116 reset_fences_=LABEL_FN(vkResetFences);device_idle_=LABEL_FN(vkDeviceWaitIdle);
117#undef LABEL_FN
118 if(!create_pool_||!destroy_pool_||!reset_query_||!timestamp_||!results_||!create_fence_||!destroy_fence_||!fence_status_||!reset_fences_||!device_idle_)return;
119 device_=dev;closing_=false;worker_=std::thread([this]{run();});
120 }
121 void begin_record(VkCommandBuffer cb) {
122 if(!enabled())return;std::lock_guard lock(mutex_);auto i=recording_.find(cb);
123 if(i!=recording_.end()){recycle(*i->second);recording_.erase(i);}
124 }
125 void record(VkCommandBuffer cb,const Write& op) {
126 if(!enabled())return;std::lock_guard lock(mutex_);if(!device_||closing_){++errors_;return;}
127 auto& slot=recording_[cb];
128 if(!slot){slot=std::make_unique<Batch>();slot->fence=fence();}
129 if(!slot->fence){++errors_;return;}
130 const auto i=slot->labels.size();const auto j=static_cast<unsigned>(i%per_pool);
131 if(!j){auto p=pool();if(!p){++errors_;return;}slot->pools.push_back(p);}
132 auto p=slot->pools[i/per_pool];reset_query_(cb,p,j,1);timestamp_(cb,VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,p,j);
133 slot->labels.push_back(op);
134 }
135 VkFence submit_fence(VkCommandBuffer cb) {
136 if(!enabled()||!cb)return VK_NULL_HANDLE;std::lock_guard lock(mutex_);auto i=recording_.find(cb);
137 return i==recording_.end()?VK_NULL_HANDLE:i->second->fence;
138 }
139 void submitted(VkCommandBuffer cb,bool ok) {
140 if(!enabled()||!cb)return;std::lock_guard lock(mutex_);auto i=recording_.find(cb);if(i==recording_.end())return;
141 if(ok && i->second->fence){pending_.push_back(std::move(i->second));changed_.notify_one();}else recycle(*i->second);
142 recording_.erase(i);
143 }
144 void stop(VkDevice dev) {
145 {std::lock_guard lock(mutex_);if(!dev||device_!=dev)return;}
146 device_idle_(dev);
147 {std::lock_guard lock(mutex_);closing_=true;changed_.notify_all();}
148 if(worker_.joinable())worker_.join();std::lock_guard lock(mutex_);
149 for(auto& pair:recording_)recycle(*pair.second);recording_.clear();
150 for(auto f:idle_fences_)destroy_fence_(dev,f,nullptr);idle_fences_.clear();
151 for(auto p:idle_pools_)destroy_pool_(dev,p,nullptr);idle_pools_.clear();
152 device_=VK_NULL_HANDLE;
153 }
154};
155inline Completions& completions(){static Completions engine;return engine;}
156} // namespace leonida::label
diff --git a/runtime/src/vulkan_graphics_shader_modules.h b/runtime/src/vulkan_graphics_shader_modules.h
new file mode 100644
index 000000000..5c2b1bd71
--- /dev/null
+++ b/runtime/src/vulkan_graphics_shader_modules.h
@@ -0,0 +1,61 @@
1#pragma once
2
3#include <vulkan/vulkan.h>
4#include <algorithm>
5#include <cstdint>
6#include <memory>
7#include <mutex>
8#include <span>
9#include <unordered_map>
10#include <vector>
11
12namespace leonida {
13class GraphicsShaderModules {
14public:
15 struct Module {
16 VkDevice device;
17 PFN_vkDestroyShaderModule destroy;
18 std::vector<std::uint32_t> words;
19 VkShaderModule handle = VK_NULL_HANDLE;
20 Module(VkDevice d, PFN_vkDestroyShaderModule fn, std::span<const std::uint32_t> input)
21 : device(d), destroy(fn), words(input.begin(), input.end()) {}
22 ~Module() { if (handle) destroy(device, handle, nullptr); }
23 };
24 using Reference = std::shared_ptr<const Module>;
25 Reference acquire(VkDevice device, PFN_vkCreateShaderModule create, PFN_vkDestroyShaderModule destroy,
26 std::span<const std::uint32_t> words, bool reuse = true) {
27 if (words.empty()) return {};
28 std::uint64_t hash = 14695981039346656037ull;
29 if (reuse) {
30 for (std::uint32_t word : words) hash = (hash ^ word) * 1099511628211ull;
31 std::lock_guard lock(mutex_);
32 if (auto found = find_locked(hash, words)) { ++hits_; return found; }
33 }
34 auto result = std::make_shared<Module>(device, destroy, words);
35 VkShaderModuleCreateInfo info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};
36 info.pCode = words.data(); info.codeSize = words.size_bytes();
37 if (create(device, &info, nullptr, &result->handle) != VK_SUCCESS) { result->handle=VK_NULL_HANDLE; return {}; }
38 if (!reuse) return result;
39 std::lock_guard lock(mutex_);
40 if (auto found = find_locked(hash, words)) { ++hits_; return found; }
41 if ((++created_ % 1024) == 0)
42 std::erase_if(modules_, [](const auto& entry) { return entry.second.expired(); });
43 modules_.emplace(hash,result);
44 return result;
45 }
46 std::pair<std::uint64_t,std::uint64_t> counts() {
47 std::lock_guard lock(mutex_); return {created_,hits_};
48 }
49private:
50 Reference find_locked(std::uint64_t hash, std::span<const std::uint32_t> words) {
51 const auto [first,last] = modules_.equal_range(hash);
52 for (auto i=first; i!=last; ++i)
53 if (auto live=i->second.lock(); live && std::equal(words.begin(),words.end(),live->words.begin(),live->words.end()))
54 return live;
55 return {};
56 }
57 std::mutex mutex_;
58 std::unordered_multimap<std::uint64_t,std::weak_ptr<const Module>> modules_;
59 std::uint64_t created_=0,hits_=0;
60};
61} // namespace leonida
diff --git a/runtime/src/vulkan_present.h b/runtime/src/vulkan_present.h
index 97c365b5f..efdbd583d 100644
--- a/runtime/src/vulkan_present.h
+++ b/runtime/src/vulkan_present.h
@@ -27,6 +27,7 @@
27 27
28#include "vulkan_backend.h" 28#include "vulkan_backend.h"
29#include "vulkan_present_compose.h" 29#include "vulkan_present_compose.h"
30#include "present_dump.h"
30 31
31// Use the original EXT spellings. They are aliases of the promoted KHR types and are available in older headers. 32// Use the original EXT spellings. They are aliases of the promoted KHR types and are available in older headers.
32#if defined(VK_EXT_SWAPCHAIN_MAINTENANCE_1_EXTENSION_NAME) && defined(VK_EXT_SURFACE_MAINTENANCE_1_EXTENSION_NAME) 33#if defined(VK_EXT_SWAPCHAIN_MAINTENANCE_1_EXTENSION_NAME) && defined(VK_EXT_SURFACE_MAINTENANCE_1_EXTENSION_NAME)
@@ -618,7 +619,15 @@ private:
618 // Only a present the engine took counts (SUBOPTIMAL is shown too). OUT_OF_DATE was not shown: the swapchain 619 // Only a present the engine took counts (SUBOPTIMAL is shown too). OUT_OF_DATE was not shown: the swapchain
619 // is recreated next time, and the caller sees VK_SUCCESS, since its work was submitted. 620 // is recreated next time, and the caller sees VK_SUCCESS, since its work was submitted.
620 if (result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR) { 621 if (result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR) {
621 ++presented_; 622 const auto shown = ++presented_;
623 if (dump_.due(shown - 1)) {
624 // Presentation is already queued and the queue/tracker locks are released. A sampled frame
625 // may stall here for its transfer fence and a private CPU copy. PNG and disk I/O run on a worker.
626 if (vkWaitForFences_(device, 1, &frame.done, VK_TRUE, UINT64_MAX) == VK_SUCCESS)
627 dump_.save(shown, extent_, format_, dump_pq_, capture_ptr_, size_t(capture_size_));
628 else
629 dump_.disable("present dump fence wait failed");
630 }
622 if (planes) ++composed_; 631 if (planes) ++composed_;
623 if (tearing) { 632 if (tearing) {
624 last_tore_ = true; 633 last_tore_ = true;
@@ -953,7 +962,7 @@ private:
953 const VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; 962 const VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
954 VkImageLayout layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; 963 VkImageLayout layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
955 VkAccessFlags access = VK_ACCESS_TRANSFER_WRITE_BIT; 964 VkAccessFlags access = VK_ACCESS_TRANSFER_WRITE_BIT;
956 if (capture_ && capture_buffer_) { 965 if (capture_buffer_ && (capture_ || dump_.due(presented_))) {
957 // Two frames may be in flight and share `capture_buffer_`: serialize the prior frame's capture copy 966 // Two frames may be in flight and share `capture_buffer_`: serialize the prior frame's capture copy
958 // before overwriting it, while moving this frame's swapchain image to TRANSFER_SRC. 967 // before overwriting it, while moving this frame's swapchain image to TRANSFER_SRC.
959 VkBufferMemoryBarrier capture_waw{VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER}; 968 VkBufferMemoryBarrier capture_waw{VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER};
@@ -980,6 +989,10 @@ private:
980 copy.imageExtent = {extent_.width, extent_.height, 1}; 989 copy.imageExtent = {extent_.width, extent_.height, 1};
981 fn.copy_image_to_buffer(commands, images_[image], VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, capture_buffer_, 1, 990 fn.copy_image_to_buffer(commands, images_[image], VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, capture_buffer_, 1,
982 &copy); 991 &copy);
992 auto to_host = capture_waw;
993 to_host.dstAccessMask = VK_ACCESS_HOST_READ_BIT;
994 fn.pipeline_barrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0,
995 0, nullptr, 1, &to_host, 0, nullptr);
983 layout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; 996 layout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
984 access = VK_ACCESS_TRANSFER_READ_BIT; 997 access = VK_ACCESS_TRANSFER_READ_BIT;
985 } 998 }
@@ -992,7 +1005,7 @@ private:
992 release_capture(); 1005 release_capture();
993 auto& vk = context_.vk; 1006 auto& vk = context_.vk;
994 const VkDevice device = context_.device(); 1007 const VkDevice device = context_.device();
995 capture_size_ = VkDeviceSize(extent_.width) * extent_.height * 4; 1008 capture_size_ = VkDeviceSize(extent_.width) * extent_.height * present_dump::texel_size(format_);
996 VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; 1009 VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
997 info.size = capture_size_; 1010 info.size = capture_size_;
998 info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT; 1011 info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT;
@@ -1180,7 +1193,9 @@ private:
1180 return true; 1193 return true;
1181 } 1194 }
1182 VkImageUsageFlags usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT; 1195 VkImageUsageFlags usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT;
1183 if (capture_) usage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; 1196 if (dump_.enabled() && !(caps.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_SRC_BIT))
1197 dump_.disable("surface does not support swapchain readback");
1198 if (capture_ || dump_.enabled()) usage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
1184 if ((caps.supportedUsageFlags & usage) != usage) return false; 1199 if ((caps.supportedUsageFlags & usage) != usage) return false;
1185 // Not used by the presenter itself (it blits or copies into the images), but overlays that hook the swapchain 1200 // Not used by the presenter itself (it blits or copies into the images), but overlays that hook the swapchain
1186 // draw their own frame into its images through a framebuffer, which needs COLOR_ATTACHMENT: without it 1201 // draw their own frame into its images through a framebuffer, which needs COLOR_ATTACHMENT: without it
@@ -1324,13 +1339,14 @@ private:
1324 extent_ = extent; 1339 extent_ = extent;
1325 extent_packed_ = (std::uint64_t(extent.width) << 32) | extent.height; 1340 extent_packed_ = (std::uint64_t(extent.width) << 32) | extent.height;
1326 hdr_active_ = chose_hdr; 1341 hdr_active_ = chose_hdr;
1327 if (capture_) { 1342 dump_pq_ = chosen.colorSpace == VK_COLOR_SPACE_HDR10_ST2084_EXT;
1328 // A capture that cannot be made fails the recreation with the swapchain in place and stale_ still set. 1343 if (capture_ || dump_.enabled()) {
1329 const bool four_bytes = format_ == VK_FORMAT_B8G8R8A8_UNORM || format_ == VK_FORMAT_R8G8B8A8_UNORM || 1344 const auto stride = present_dump::texel_size(format_);
1330 format_ == VK_FORMAT_B8G8R8A8_SRGB || format_ == VK_FORMAT_R8G8B8A8_SRGB || 1345 if (capture_ && stride != 4) return false; // read_back() promises four bytes per texel
1331 format_ == VK_FORMAT_A2B10G10R10_UNORM_PACK32 || 1346 if (!stride || !make_capture_buffer()) {
1332 format_ == VK_FORMAT_A2R10G10B10_UNORM_PACK32; 1347 dump_.disable("cannot read back this swapchain format or allocate its capture buffer");
1333 if (!four_bytes || !make_capture_buffer()) return false; 1348 if (capture_) return false;
1349 }
1334 } 1350 }
1335 vsync_ = vsync; 1351 vsync_ = vsync;
1336 swapchain_srgb_ = srgb; 1352 swapchain_srgb_ = srgb;
@@ -1441,6 +1457,8 @@ private:
1441 std::map<VkFormat, VkFormatFeatureFlags> features_; 1457 std::map<VkFormat, VkFormatFeatureFlags> features_;
1442 bool warned_srgb_ = false; 1458 bool warned_srgb_ = false;
1443 bool capture_ = false; 1459 bool capture_ = false;
1460 present_dump::PresentDump dump_;
1461 bool dump_pq_ = false;
1444 VkBuffer capture_buffer_ = VK_NULL_HANDLE; 1462 VkBuffer capture_buffer_ = VK_NULL_HANDLE;
1445 VkDeviceMemory capture_memory_ = VK_NULL_HANDLE; 1463 VkDeviceMemory capture_memory_ = VK_NULL_HANDLE;
1446 VkDeviceSize capture_size_ = 0; 1464 VkDeviceSize capture_size_ = 0;
diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h
index fc6ed9234..d0847aa97 100644
--- a/runtime/src/vulkan_replay.h
+++ b/runtime/src/vulkan_replay.h
@@ -1,4 +1,7 @@
1#include <atomic>
1#pragma once 2#pragma once
3#include <cfloat>
4#include "vulkan_gpu_labels.h"
2 5
3#include "resource_tiling.h" 6#include "resource_tiling.h"
4 7
@@ -100,6 +103,13 @@ struct ResourceBinding {
100 bool sampled = false; // has SAMPLED usage (no DENY_SHADER_RESOURCE): the present compose pass reads it 103 bool sampled = false; // has SAMPLED usage (no DENY_SHADER_RESOURCE): the present compose pass reads it
101 bool host_readable = false; // D3D12_HEAP_TYPE_READBACK (or CUSTOM write-back): needs host-read flush 104 bool host_readable = false; // D3D12_HEAP_TYPE_READBACK (or CUSTOM write-back): needs host-read flush
102 bool sparse_buffer = false; 105 bool sparse_buffer = false;
106 bool xbox_depth16_stencil8=false;
107 bool rgba4_render_fallback=false;
108 // The two independently addressable storage images of an Xbox depth/stencil UAV.
109 ResourceId depth_uav = 0, stencil_uav = 0;
110 void* residency_owner = nullptr;
111 bool (*ensure_residency)(void*) = nullptr;
112 ResourceId depth_conversion = 0; // R32_FLOAT transfer image for a widened Xbox D16+S8 attachment
103}; 113};
104 114
105struct VulkanAccess { 115struct VulkanAccess {
@@ -465,11 +475,16 @@ inline BlockFormat block_format(VkFormat format, VkImageAspectFlags aspect) {
465 case VK_FORMAT_R16_SINT: 475 case VK_FORMAT_R16_SINT:
466 case VK_FORMAT_A4R4G4B4_UNORM_PACK16: 476 case VK_FORMAT_A4R4G4B4_UNORM_PACK16:
467 case VK_FORMAT_R4G4B4A4_UNORM_PACK16: 477 case VK_FORMAT_R4G4B4A4_UNORM_PACK16:
478 case VK_FORMAT_D16_UNORM_S8_UINT:
468 case VK_FORMAT_D16_UNORM: return {2, 1}; 479 case VK_FORMAT_D16_UNORM: return {2, 1};
469 case VK_FORMAT_R8_UNORM: 480 case VK_FORMAT_R8_UNORM:
470 case VK_FORMAT_R8_SNORM: 481 case VK_FORMAT_R8_SNORM:
471 case VK_FORMAT_R8_UINT: 482 case VK_FORMAT_R8_UINT:
472 case VK_FORMAT_R8_SINT: return {1, 1}; 483 case VK_FORMAT_R8_SINT:
484#ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME
485 case VK_FORMAT_A8_UNORM_KHR: // an A8_UNORM render target (VulkanDeviceInfo::a8_render_target)
486#endif
487 return {1, 1};
473 case VK_FORMAT_BC1_RGBA_UNORM_BLOCK: 488 case VK_FORMAT_BC1_RGBA_UNORM_BLOCK:
474 case VK_FORMAT_BC1_RGBA_SRGB_BLOCK: 489 case VK_FORMAT_BC1_RGBA_SRGB_BLOCK:
475 case VK_FORMAT_BC4_UNORM_BLOCK: 490 case VK_FORMAT_BC4_UNORM_BLOCK:
@@ -755,6 +770,7 @@ struct ComputePipeline {
755 VkPipelineLayout layout = VK_NULL_HANDLE; 770 VkPipelineLayout layout = VK_NULL_HANDLE;
756 std::uint64_t code_base = 0; 771 std::uint64_t code_base = 0;
757 VkDescriptorSet bindless_set = VK_NULL_HANDLE; // set 0 of the layout, bound at every dispatch; null: none 772 VkDescriptorSet bindless_set = VK_NULL_HANDLE; // set 0 of the layout, bound at every dispatch; null: none
773 std::function<VkPipeline()> materialize;
758}; 774};
759 775
760// A graphics pipeline as replay needs it: the formats its attachments must have and which vertex-input slots it 776// A graphics pipeline as replay needs it: the formats its attachments must have and which vertex-input slots it
@@ -781,6 +797,7 @@ struct GraphicsPipeline {
781 std::uint32_t rectangle_variant_topology = 0; 797 std::uint32_t rectangle_variant_topology = 0;
782 std::function<VkPipeline(std::uint32_t flags)> variant; 798 std::function<VkPipeline(std::uint32_t flags)> variant;
783 std::uint32_t samples = 1; // rasterizationSamples; every bound attachment must have this count 799 std::uint32_t samples = 1; // rasterizationSamples; every bound attachment must have this count
800 bool pending_base_compile = false;
784}; 801};
785 802
786// The 144-byte push-constant block every translated shader declares: s0..s31, heap base, code base. 803// The 144-byte push-constant block every translated shader declares: s0..s31, heap base, code base.
@@ -808,7 +825,6 @@ enum class ReplayResult {
808 invalid_draw, // DispatchMesh with a pipeline that has no mesh shader, or a vertex draw with one that has 825 invalid_draw, // DispatchMesh with a pipeline that has no mesh shader, or a vertex draw with one that has
809 unsupported 826 unsupported
810}; 827};
811
812struct ReplayFunctions { 828struct ReplayFunctions {
813 // Set 0 for the pipelines that declare one (their own `bindless_set` is only the marker): the device's current 829 // Set 0 for the pipelines that declare one (their own `bindless_set` is only the marker): the device's current
814 // generation of it, which a flush may have replaced since the pipeline was made. Null: the pipeline's. 830 // generation of it, which a flush may have replaced since the pipeline was made. Null: the pipeline's.
@@ -819,6 +835,9 @@ struct ReplayFunctions {
819 // Optional; a list that needs a missing one is rejected with ReplayResult::unsupported. 835 // Optional; a list that needs a missing one is rejected with ReplayResult::unsupported.
820 PFN_vkCmdPipelineBarrier2 pipeline_barrier2 = nullptr; // enhanced barriers 836 PFN_vkCmdPipelineBarrier2 pipeline_barrier2 = nullptr; // enhanced barriers
821 VkPipelineStageFlags2 queue_stages = 0; 837 VkPipelineStageFlags2 queue_stages = 0;
838 bool graphics_family = true;
839 // Aspects with maintenance10 depth/stencil transfer support on a dedicated compute family.
840 std::function<VkImageAspectFlags(VkFormat)> compute_copy_aspects;
822 PFN_vkCmdBeginRendering begin_rendering = nullptr; // rectangle clears 841 PFN_vkCmdBeginRendering begin_rendering = nullptr; // rectangle clears
823 PFN_vkCmdEndRendering end_rendering = nullptr; 842 PFN_vkCmdEndRendering end_rendering = nullptr;
824 PFN_vkCmdClearAttachments clear_attachments = nullptr; 843 PFN_vkCmdClearAttachments clear_attachments = nullptr;
@@ -826,6 +845,7 @@ struct ReplayFunctions {
826 PFN_vkCmdCopyBufferToImage copy_buffer_to_image = nullptr; 845 PFN_vkCmdCopyBufferToImage copy_buffer_to_image = nullptr;
827 PFN_vkCmdCopyImageToBuffer copy_image_to_buffer = nullptr; 846 PFN_vkCmdCopyImageToBuffer copy_image_to_buffer = nullptr;
828 PFN_vkCmdCopyImage copy_image = nullptr; 847 PFN_vkCmdCopyImage copy_image = nullptr;
848 PFN_vkCmdBlitImage blit_image = nullptr;
829 PFN_vkCmdResolveImage resolve_image = nullptr; // resolves 849 PFN_vkCmdResolveImage resolve_image = nullptr; // resolves
830 PFN_vkCmdFillBuffer fill_buffer = nullptr; // unordered-access buffer clears, with copy_buffer 850 PFN_vkCmdFillBuffer fill_buffer = nullptr; // unordered-access buffer clears, with copy_buffer
831 PFN_vkCmdUpdateBuffer update_buffer = nullptr; // WriteBufferImmediate, unordered-access clears 851 PFN_vkCmdUpdateBuffer update_buffer = nullptr; // WriteBufferImmediate, unordered-access clears
@@ -868,6 +888,10 @@ struct ReplayFunctions {
868 // cut to what the buffer holds from there: vertex and index views use what fits, WriteBufferImmediate needs all 888 // cut to what the buffer holds from there: vertex and index views use what fits, WriteBufferImmediate needs all
869 // of it. 889 // of it.
870 std::function<bool(std::uint64_t va, std::uint64_t& size, VkBuffer&, VkDeviceSize&)> buffer_at; 890 std::function<bool(std::uint64_t va, std::uint64_t& size, VkBuffer&, VkDeviceSize&)> buffer_at;
891 // A vertex or index view whose VA is the title's own CPU memory, not a registered buffer (on the console
892 // the GPU reads title memory directly). Copies [va, va + size) into a GPU-visible ring and names the copy; false
893 // when the range is not readable host memory.
894 std::function<bool(std::uint64_t va, std::uint64_t size, VkBuffer&, VkDeviceSize&)> title_memory;
871 // Host bytes for a whole console VA range; `not_cpu_written` when it names GPU-writable memory. For small 895 // Host bytes for a whole console VA range; `not_cpu_written` when it names GPU-writable memory. For small
872 // CPU-written inputs, such as the pointer list of an ARRAY_OF_POINTERS TLAS build. 896 // CPU-written inputs, such as the pointer list of an ARRAY_OF_POINTERS TLAS build.
873 std::function<HostReadStatus(std::uint64_t va, std::uint64_t bytes, const std::uint8_t*&)> host_at; 897 std::function<HostReadStatus(std::uint64_t va, std::uint64_t bytes, const std::uint8_t*&)> host_at;
@@ -1044,6 +1068,7 @@ struct Prepared {
1044 // A depth <-> colour copy: the source into `staged` (image to buffer), then `staged` into the destination. 1068 // A depth <-> colour copy: the source into `staged` (image to buffer), then `staged` into the destination.
1045 VkBuffer staged = VK_NULL_HANDLE; 1069 VkBuffer staged = VK_NULL_HANDLE;
1046 std::vector<VkBufferImageCopy> staged_reads, staged_writes; 1070 std::vector<VkBufferImageCopy> staged_reads, staged_writes;
1071 VkDeviceSize clear_pattern_bytes = 0; // rectangular UAV clear on a compute-only queue
1047 std::vector<VkImageSubresourceRange> discards; // DiscardResource: the subresources to discard 1072 std::vector<VkImageSubresourceRange> discards; // DiscardResource: the subresources to discard
1048 VkBuffer write_buffer = VK_NULL_HANDLE; // WriteBufferImmediate: where the address lands 1073 VkBuffer write_buffer = VK_NULL_HANDLE; // WriteBufferImmediate: where the address lands
1049 VkDeviceSize write_offset = 0; 1074 VkDeviceSize write_offset = 0;
@@ -1055,6 +1080,8 @@ struct Prepared {
1055 QueryPool* queries = nullptr; // query commands: the heap 1080 QueryPool* queries = nullptr; // query commands: the heap
1056 ComputePipeline pipeline; // dispatches 1081 ComputePipeline pipeline; // dispatches
1057 std::uint32_t draw = 0; // draws: its PreparedDraw in PreparedList::draws 1082 std::uint32_t draw = 0; // draws: its PreparedDraw in PreparedList::draws
1083 std::uint32_t depth_uav_copy = UINT32_MAX;
1084 bool order_depth_uav = false;
1058 VkAccelerationStructureKHR accel_dst = VK_NULL_HANDLE; 1085 VkAccelerationStructureKHR accel_dst = VK_NULL_HANDLE;
1059 VkDeviceAddress khr_instances = 0; // staged ARRAY_OF_POINTERS instance list for a KHR TLAS; 0: use the VA directly 1086 VkDeviceAddress khr_instances = 0; // staged ARRAY_OF_POINTERS instance list for a KHR TLAS; 0: use the VA directly
1060 std::uint64_t xdxr_bytes = 0; // CopyAccelerationStructure: the most bytes the copy may write 1087 std::uint64_t xdxr_bytes = 0; // CopyAccelerationStructure: the most bytes the copy may write
@@ -1062,6 +1089,26 @@ struct Prepared {
1062 std::uint32_t khr_postbuild = ~0u; // index into PreparedList::khr_postbuilds; ~0u: skipped or XDXR 1089 std::uint32_t khr_postbuild = ~0u; // index into PreparedList::khr_postbuilds; ~0u: skipped or XDXR
1063}; 1090};
1064 1091
1092struct DepthUavCopy {
1093 std::array<ResourceBinding, 2> storage;
1094 ResourceBinding conversion{};
1095 VkBuffer scratch;
1096 VkDeviceSize offset;
1097 bool to_storage;
1098};
1099
1100inline bool texture_uav_layout(std::uint32_t layout) {
1101 return layout == d3d12_layout::unordered_access || layout == d3d12_layout::direct_queue_unordered_access ||
1102 layout == d3d12_layout::compute_queue_unordered_access;
1103}
1104
1105inline bool unsupported_depth_uav_access(std::uint32_t layout, std::uint32_t access) {
1106 // A queue-specific COMMON layout permits implicit storage writes. Generic COMMON permits only
1107 // sampling and copies, even when the access scope is COMMON (zero).
1108 return layout == d3d12_layout::direct_queue_common || layout == d3d12_layout::compute_queue_common ||
1109 (layout == d3d12_layout::common && (access & d3d12_access::unordered_access));
1110}
1111
1065inline constexpr std::size_t max_render_targets = 8; // D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT 1112inline constexpr std::size_t max_render_targets = 8; // D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT
1066 1113
1067// What a draw needs beyond Prepared, kept apart in PreparedList::draws: every command's entry is refilled on every 1114// What a draw needs beyond Prepared, kept apart in PreparedList::draws: every command's entry is refilled on every
@@ -1179,6 +1226,9 @@ inline VkClearColorValue render_target_clear_color(VkFormat format, const ClearC
1179 case VK_FORMAT_R8G8_UNORM: 1226 case VK_FORMAT_R8G8_UNORM:
1180 case VK_FORMAT_R8G8B8A8_UNORM: 1227 case VK_FORMAT_R8G8B8A8_UNORM:
1181 case VK_FORMAT_B8G8R8A8_UNORM: is_integer = false; unorm = {255, 255, 255, 255}; break; 1228 case VK_FORMAT_B8G8R8A8_UNORM: is_integer = false; unorm = {255, 255, 255, 255}; break;
1229#ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME
1230 case VK_FORMAT_A8_UNORM_KHR: is_integer = false; unorm = {0, 0, 0, 255}; break; // alpha only
1231#endif
1182 case VK_FORMAT_R8G8B8A8_SRGB: 1232 case VK_FORMAT_R8G8B8A8_SRGB:
1183 case VK_FORMAT_B8G8R8A8_SRGB: // the colour channels go through the sRGB curve on the GPU 1233 case VK_FORMAT_B8G8R8A8_SRGB: // the colour channels go through the sRGB curve on the GPU
1184 is_integer = false; 1234 is_integer = false;
@@ -1377,14 +1427,12 @@ inline LayoutPieces current(const LayoutTracker* tracker, ResourceId id, const V
1377 return out; 1427 return out;
1378} 1428}
1379 1429
1380// Zero-fills a block-compressed image range via vkCmdCopyBufferToImage from either the device's zero page 1430// Copies zeroes from the device's zero page or transfer scratch. A buffer can initialize block-compressed
1381// (`vk.zero_buffer`) or a zeroed transfer-scratch chunk (`vk.copy_scratch` + `vk.fill_buffer`). Vulkan forbids 1431// images and, with maintenance10, a depth or stencil aspect on a compute-only queue where a clear is illegal.
1382// vkCmdClearColorImage on BC formats, yet D3D12 committed resources start zeroed unless CREATE_NOT_ZEROED is set 1432inline bool zero_image_aspect(const ReplayFunctions& vk, VkCommandBuffer command_buffer,
1383// (D3D-220). 1433 const ResourceBinding& resource, const VkImageSubresourceRange& range,
1384inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer command_buffer, 1434 VkImageAspectFlags aspect, VkImageLayout dst_layout) {
1385 const ResourceBinding& resource, const VkImageSubresourceRange& range, 1435 const BlockFormat fmt = block_format(resource.format, aspect);
1386 VkImageLayout dst_layout) {
1387 const BlockFormat fmt = block_format(resource.format, VK_IMAGE_ASPECT_COLOR_BIT);
1388 if (fmt.block < 1 || !fmt.bytes || !vk.copy_buffer_to_image) return false; 1436 if (fmt.block < 1 || !fmt.bytes || !vk.copy_buffer_to_image) return false;
1389 const std::uint32_t mip_begin = range.baseMipLevel; 1437 const std::uint32_t mip_begin = range.baseMipLevel;
1390 const std::uint32_t mip_end = 1438 const std::uint32_t mip_end =
@@ -1418,7 +1466,7 @@ inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer com
1418 VkDeviceSize zero_off = 0; 1466 VkDeviceSize zero_off = 0;
1419 VkDeviceSize zero_cap = 0; 1467 VkDeviceSize zero_cap = 0;
1420 if (vk.zero_buffer && vk.zero_size >= fmt.bytes) { 1468 if (vk.zero_buffer && vk.zero_size >= fmt.bytes) {
1421 const VkDeviceSize align = fmt.bytes; 1469 const VkDeviceSize align = std::max<VkDeviceSize>(4, fmt.bytes);
1422 const VkDeviceSize pad = (align - (vk.zero_offset % align)) % align; 1470 const VkDeviceSize pad = (align - (vk.zero_offset % align)) % align;
1423 if (vk.zero_size >= pad + fmt.bytes) { 1471 if (vk.zero_size >= pad + fmt.bytes) {
1424 zero_buf = vk.zero_buffer; 1472 zero_buf = vk.zero_buffer;
@@ -1427,12 +1475,11 @@ inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer com
1427 } 1475 }
1428 } 1476 }
1429 if (!zero_buf && vk.copy_scratch && vk.fill_buffer) { 1477 if (!zero_buf && vk.copy_scratch && vk.fill_buffer) {
1430 // Round up to a multiple of fmt.bytes (8 or 16, always a multiple of 4 for vkCmdFillBuffer). 1478 const VkDeviceSize align = std::max<VkDeviceSize>(4, fmt.bytes);
1431 const VkDeviceSize fill_bytes = ((needed + fmt.bytes - 1) / fmt.bytes) * fmt.bytes; 1479 const VkDeviceSize fill_bytes = ((needed + align - 1) / align) * align;
1432 VkBuffer scratch = VK_NULL_HANDLE; 1480 VkBuffer scratch = VK_NULL_HANDLE;
1433 VkDeviceSize offset = 0; 1481 VkDeviceSize offset = 0;
1434 if (vk.copy_scratch(fill_bytes, scratch, offset)) { 1482 if (vk.copy_scratch(fill_bytes, scratch, offset)) {
1435 const VkDeviceSize align = fmt.bytes;
1436 const VkDeviceSize pad = (align - (offset % align)) % align; 1483 const VkDeviceSize pad = (align - (offset % align)) % align;
1437 if (fill_bytes >= pad + fmt.bytes) { 1484 if (fill_bytes >= pad + fmt.bytes) {
1438 vk.fill_buffer(command_buffer, scratch, offset + pad, fill_bytes - pad, 0); 1485 vk.fill_buffer(command_buffer, scratch, offset + pad, fill_bytes - pad, 0);
@@ -1457,7 +1504,7 @@ inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer com
1457 layer_count <= zero_cap / (slice_bytes * mip_d)) { 1504 layer_count <= zero_cap / (slice_bytes * mip_d)) {
1458 VkBufferImageCopy r{}; 1505 VkBufferImageCopy r{};
1459 r.bufferOffset = zero_off; 1506 r.bufferOffset = zero_off;
1460 r.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, mip, layer_begin, layer_count}; 1507 r.imageSubresource = {aspect, mip, layer_begin, layer_count};
1461 r.imageExtent = {ext.width, ext.height, mip_d}; 1508 r.imageExtent = {ext.width, ext.height, mip_d};
1462 regions.push_back(r); 1509 regions.push_back(r);
1463 continue; 1510 continue;
@@ -1470,7 +1517,7 @@ inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer com
1470 for (std::uint32_t z = 0; z < mip_d; z += slices_per_copy) { 1517 for (std::uint32_t z = 0; z < mip_d; z += slices_per_copy) {
1471 VkBufferImageCopy r{}; 1518 VkBufferImageCopy r{};
1472 r.bufferOffset = zero_off; 1519 r.bufferOffset = zero_off;
1473 r.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, mip, layer, 1}; 1520 r.imageSubresource = {aspect, mip, layer, 1};
1474 r.imageOffset = {0, 0, std::int32_t(z)}; 1521 r.imageOffset = {0, 0, std::int32_t(z)};
1475 r.imageExtent = {ext.width, ext.height, std::min(slices_per_copy, mip_d - z)}; 1522 r.imageExtent = {ext.width, ext.height, std::min(slices_per_copy, mip_d - z)};
1476 regions.push_back(r); 1523 regions.push_back(r);
@@ -1484,7 +1531,7 @@ inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer com
1484 const std::uint32_t eh = std::min<std::uint32_t>(rows_per_copy * fmt.block, ext.height - oy); 1531 const std::uint32_t eh = std::min<std::uint32_t>(rows_per_copy * fmt.block, ext.height - oy);
1485 VkBufferImageCopy r{}; 1532 VkBufferImageCopy r{};
1486 r.bufferOffset = zero_off; 1533 r.bufferOffset = zero_off;
1487 r.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, mip, layer, 1}; 1534 r.imageSubresource = {aspect, mip, layer, 1};
1488 r.imageOffset = {0, std::int32_t(oy), std::int32_t(z)}; 1535 r.imageOffset = {0, std::int32_t(oy), std::int32_t(z)};
1489 r.imageExtent = {ext.width, eh, 1}; 1536 r.imageExtent = {ext.width, eh, 1};
1490 regions.push_back(r); 1537 regions.push_back(r);
@@ -1503,7 +1550,7 @@ inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer com
1503 std::min<std::uint32_t>(cols_per_copy * fmt.block, ext.width - ox); 1550 std::min<std::uint32_t>(cols_per_copy * fmt.block, ext.width - ox);
1504 VkBufferImageCopy r{}; 1551 VkBufferImageCopy r{};
1505 r.bufferOffset = zero_off; 1552 r.bufferOffset = zero_off;
1506 r.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, mip, layer, 1}; 1553 r.imageSubresource = {aspect, mip, layer, 1};
1507 r.imageOffset = {std::int32_t(ox), std::int32_t(oy), std::int32_t(z)}; 1554 r.imageOffset = {std::int32_t(ox), std::int32_t(oy), std::int32_t(z)};
1508 r.imageExtent = {ew, eh, 1}; 1555 r.imageExtent = {ew, eh, 1};
1509 regions.push_back(r); 1556 regions.push_back(r);
@@ -1530,12 +1577,15 @@ inline void initialize(const ReplayFunctions& vk, VkCommandBuffer command_buffer
1530 if (piece.layout != VK_IMAGE_LAYOUT_UNDEFINED) continue; 1577 if (piece.layout != VK_IMAGE_LAYOUT_UNDEFINED) continue;
1531 const BlockFormat fmt = block_format(resource.format, VK_IMAGE_ASPECT_COLOR_BIT); 1578 const BlockFormat fmt = block_format(resource.format, VK_IMAGE_ASPECT_COLOR_BIT);
1532 const bool color = piece.range.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT; 1579 const bool color = piece.range.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT;
1533 const bool can_clear = !vk.queue_stages || ((vk.queue_stages & VK_PIPELINE_STAGE_2_CLEAR_BIT) && color); 1580 const bool can_clear = !vk.queue_stages || ((vk.queue_stages & VK_PIPELINE_STAGE_2_CLEAR_BIT) && color) ||
1534 const bool compressed = fmt.block > 1 || (!can_clear && color); 1581 (resource.depth_uav && vk.graphics_family);
1535 if (resource.not_zeroed || (!can_clear && !color)) { 1582 const bool compute_depth = !color && resource.depth_uav && !vk.graphics_family &&
1583 (vk.queue_stages & VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT) && vk.compute_copy_aspects &&
1584 (vk.compute_copy_aspects(resource.format) & piece.range.aspectMask) == piece.range.aspectMask;
1585 if (resource.not_zeroed || (!can_clear && !color && !compute_depth)) {
1536 image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, layout, 0, 1586 image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, layout, 0,
1537 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); 1587 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
1538 } else if (compressed) { 1588 } else if (fmt.block > 1 || !can_clear) {
1539 const bool can_zero = 1589 const bool can_zero =
1540 vk.copy_buffer_to_image && 1590 vk.copy_buffer_to_image &&
1541 ((vk.zero_buffer && vk.zero_size >= fmt.bytes) || (vk.copy_scratch && vk.fill_buffer)); 1591 ((vk.zero_buffer && vk.zero_size >= fmt.bytes) || (vk.copy_scratch && vk.fill_buffer));
@@ -1544,7 +1594,10 @@ inline void initialize(const ReplayFunctions& vk, VkCommandBuffer command_buffer
1544 image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, dst, 0, 1594 image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, dst, 0,
1545 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, 1595 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT,
1546 VK_PIPELINE_STAGE_TRANSFER_BIT); 1596 VK_PIPELINE_STAGE_TRANSFER_BIT);
1547 const bool zeroed = zero_compressed_image(vk, command_buffer, resource, piece.range, dst); 1597 bool zeroed = true;
1598 for (auto aspect : {VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_ASPECT_DEPTH_BIT, VK_IMAGE_ASPECT_STENCIL_BIT})
1599 if (piece.range.aspectMask & aspect)
1600 zeroed &= zero_image_aspect(vk, command_buffer, resource, piece.range, aspect, dst);
1548 image_barrier(vk, command_buffer, resource, piece.range, dst, layout, 1601 image_barrier(vk, command_buffer, resource, piece.range, dst, layout,
1549 zeroed ? VK_ACCESS_TRANSFER_WRITE_BIT : 0, 1602 zeroed ? VK_ACCESS_TRANSFER_WRITE_BIT : 0,
1550 zeroed ? VK_PIPELINE_STAGE_TRANSFER_BIT : VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory, 1603 zeroed ? VK_PIPELINE_STAGE_TRANSFER_BIT : VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory,
@@ -2108,6 +2161,77 @@ void round_trip(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const
2108 } 2161 }
2109} 2162}
2110 2163
2164// Vulkan cannot copy a depth or stencil image aspect directly to or from a color image. The transfer
2165// buffer preserves the native D16, D32 or S8 bits. Only the requested layers and planes are copied, even when the device
2166// requires both parent aspects to transition layouts together. A storage descriptor always names GENERAL.
2167inline void copy_depth_uav(const ReplayFunctions& vk, VkCommandBuffer cb, const Prepared& p, const DepthUavCopy& copy,
2168 VkImageLayout parent_layout, LayoutTracker* tracker) {
2169 constexpr auto all = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
2170 constexpr auto transfer = VK_PIPELINE_STAGE_TRANSFER_BIT;
2171 constexpr VkAccessFlags any = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
2172 const auto parent_access = copy.to_storage ? VK_ACCESS_TRANSFER_READ_BIT : VK_ACCESS_TRANSFER_WRITE_BIT;
2173 const auto child_access = copy.to_storage ? VK_ACCESS_TRANSFER_WRITE_BIT : VK_ACCESS_TRANSFER_READ_BIT;
2174 const auto parent_range = planes_for_layout(p.binding, p.range, vk.separate_depth_stencil_layouts);
2175 image_barrier(vk, cb, p.binding, parent_range, parent_layout, VK_IMAGE_LAYOUT_GENERAL,
2176 any, all, parent_access, transfer);
2177 auto color = p.range;
2178 color.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
2179 for (unsigned plane = 0; plane < copy.storage.size(); ++plane) {
2180 const ResourceBinding& child = copy.storage[plane];
2181 if (!child.image) continue;
2182 const ResourceId child_id = plane ? p.binding.stencil_uav : p.binding.depth_uav;
2183 auto pieces = current(tracker, child_id, color, VK_IMAGE_LAYOUT_GENERAL);
2184 if (!copy.to_storage) initialize(vk, cb, child, child_id, pieces, VK_IMAGE_LAYOUT_GENERAL, tracker);
2185 for (const auto& piece : pieces)
2186 image_barrier(vk, cb, child, piece.range, piece.layout, VK_IMAGE_LAYOUT_GENERAL,
2187 piece.layout == VK_IMAGE_LAYOUT_UNDEFINED ? 0 : any, all, child_access, transfer);
2188 if (tracker) tracker->set(child_id, color, VK_IMAGE_LAYOUT_GENERAL);
2189 VkBufferImageCopy parent_region{};
2190 parent_region.bufferOffset = copy.offset;
2191 const VkImageAspectFlags aspect = plane ? VK_IMAGE_ASPECT_STENCIL_BIT : VK_IMAGE_ASPECT_DEPTH_BIT;
2192 parent_region.imageSubresource = {aspect, p.range.baseMipLevel, p.range.baseArrayLayer, p.range.layerCount};
2193 parent_region.imageExtent = {p.binding.width, p.binding.height, 1};
2194 VkBufferImageCopy child_region = parent_region;
2195 child_region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
2196 // Last use of this staging range was a read by CopyBufferToImage, possibly on the previous barrier.
2197 memory_barrier(vk, cb, VK_ACCESS_TRANSFER_READ_BIT, transfer, VK_ACCESS_TRANSFER_WRITE_BIT, transfer);
2198 // A D32 depth aspect and R32_FLOAT colour carry the same bits through transfer scratch. The
2199 // intermediate colour image permits a real normalized blit between R32_FLOAT and R16_UNORM;
2200 // shaders see the latter's exact bits through an R16_UINT view.
2201 const bool convert = plane == 0 && copy.conversion.image;
2202 const VkImage colour = convert ? copy.conversion.image : child.image;
2203 VkImageBlit blit{};
2204 if (convert) {
2205 const auto id = p.binding.depth_conversion;
2206 const auto previous = current(tracker, id, color, VK_IMAGE_LAYOUT_UNDEFINED);
2207 for (const auto& piece : previous)
2208 image_barrier(vk, cb, copy.conversion, piece.range, piece.layout, VK_IMAGE_LAYOUT_GENERAL,
2209 piece.layout == VK_IMAGE_LAYOUT_UNDEFINED ? 0 : any, all,
2210 VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, transfer);
2211 if (tracker) tracker->set(id, color, VK_IMAGE_LAYOUT_GENERAL);
2212 blit.srcSubresource = blit.dstSubresource = child_region.imageSubresource;
2213 blit.srcOffsets[1] = blit.dstOffsets[1] = {int32_t(p.binding.width), int32_t(p.binding.height), 1};
2214 if (!copy.to_storage) {
2215 vk.blit_image(cb, child.image, VK_IMAGE_LAYOUT_GENERAL, colour, VK_IMAGE_LAYOUT_GENERAL, 1, &blit, VK_FILTER_NEAREST);
2216 memory_barrier(vk, cb, VK_ACCESS_TRANSFER_WRITE_BIT, transfer, VK_ACCESS_TRANSFER_READ_BIT, transfer);
2217 }
2218 }
2219 vk.copy_image_to_buffer(cb, copy.to_storage ? p.binding.image : colour, VK_IMAGE_LAYOUT_GENERAL,
2220 copy.scratch, 1, copy.to_storage ? &parent_region : &child_region);
2221 memory_barrier(vk, cb, VK_ACCESS_TRANSFER_WRITE_BIT, transfer, VK_ACCESS_TRANSFER_READ_BIT, transfer);
2222 vk.copy_buffer_to_image(cb, copy.scratch, copy.to_storage ? colour : p.binding.image, VK_IMAGE_LAYOUT_GENERAL,
2223 1, copy.to_storage ? &child_region : &parent_region);
2224 if (convert && copy.to_storage) {
2225 memory_barrier(vk, cb, VK_ACCESS_TRANSFER_WRITE_BIT, transfer, VK_ACCESS_TRANSFER_READ_BIT, transfer);
2226 vk.blit_image(cb, colour, VK_IMAGE_LAYOUT_GENERAL, child.image, VK_IMAGE_LAYOUT_GENERAL, 1, &blit, VK_FILTER_NEAREST);
2227 }
2228 image_barrier(vk, cb, child, color, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_GENERAL,
2229 child_access, transfer, any, all);
2230 }
2231 image_barrier(vk, cb, p.binding, parent_range, VK_IMAGE_LAYOUT_GENERAL, parent_layout,
2232 parent_access, transfer, any, all);
2233}
2234
2111} // namespace detail 2235} // namespace detail
2112 2236
2113namespace detail { 2237namespace detail {
@@ -2123,7 +2247,7 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct
2123 !vk.draw_indexed || !vk.bind_pipeline || !vk.push_constants) 2247 !vk.draw_indexed || !vk.bind_pipeline || !vk.push_constants)
2124 return ReplayResult::unsupported; 2248 return ReplayResult::unsupported;
2125 const GraphicsPipeline* pipeline = vk.graphics_pipeline(draw.pipeline); 2249 const GraphicsPipeline* pipeline = vk.graphics_pipeline(draw.pipeline);
2126 if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; 2250 if (!pipeline || (!pipeline->pipeline && !pipeline->pending_base_compile)) return ReplayResult::unresolved_resource;
2127 if (pipeline->mesh != draw.mesh) return ReplayResult::invalid_draw; 2251 if (pipeline->mesh != draw.mesh) return ReplayResult::invalid_draw;
2128 if (draw.mesh && !vk.draw_mesh_tasks) return ReplayResult::unsupported; 2252 if (draw.mesh && !vk.draw_mesh_tasks) return ReplayResult::unsupported;
2129 if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; 2253 if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported;
@@ -2188,7 +2312,7 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct
2188 for (std::size_t slot = 0; slot < p.colors.size(); ++slot) 2312 for (std::size_t slot = 0; slot < p.colors.size(); ++slot)
2189 if (pipeline->color_formats[slot] != VK_FORMAT_UNDEFINED && !p.colors[slot].id) unbound |= 1u << slot; 2313 if (pipeline->color_formats[slot] != VK_FORMAT_UNDEFINED && !p.colors[slot].id) unbound |= 1u << slot;
2190 if (pipeline->depth_format != VK_FORMAT_UNDEFINED && !p.depth.id) unbound |= GraphicsPipeline::unbound_depth; 2314 if (pipeline->depth_format != VK_FORMAT_UNDEFINED && !p.depth.id) unbound |= GraphicsPipeline::unbound_depth;
2191 if (unbound) { 2315 if (unbound || (!p.pipeline && pipeline->pending_base_compile)) {
2192 p.pipeline = pipeline->variant ? pipeline->variant(unbound) : VK_NULL_HANDLE; 2316 p.pipeline = pipeline->variant ? pipeline->variant(unbound) : VK_NULL_HANDLE;
2193 if (!p.pipeline) return ReplayResult::unsupported; 2317 if (!p.pipeline) return ReplayResult::unsupported;
2194 } 2318 }
@@ -2213,8 +2337,11 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct
2213 } 2337 }
2214 const VertexBufferView& view = draw.views->vertex_buffers[slot]; 2338 const VertexBufferView& view = draw.views->vertex_buffers[slot];
2215 std::uint64_t size = view.size; 2339 std::uint64_t size = view.size;
2216 if (!vk.buffer_at(view.va, size, p.vertex_buffers[slot], p.vertex_offsets[slot])) 2340 if (!vk.buffer_at(view.va, size, p.vertex_buffers[slot], p.vertex_offsets[slot])) {
2217 return ReplayResult::unresolved_resource; 2341 size = view.size;
2342 if (!vk.title_memory || !vk.title_memory(view.va, size, p.vertex_buffers[slot], p.vertex_offsets[slot]))
2343 return ReplayResult::unresolved_resource;
2344 }
2218 p.vertex_sizes[slot] = size; 2345 p.vertex_sizes[slot] = size;
2219 p.vertex_strides[slot] = (pipeline->zero_step_slots & (1u << slot)) ? 0 : view.stride; 2346 p.vertex_strides[slot] = (pipeline->zero_step_slots & (1u << slot)) ? 0 : view.stride;
2220 } 2347 }
@@ -2231,8 +2358,11 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct
2231 p.index_offset = vk.zero_offset; 2358 p.index_offset = vk.zero_offset;
2232 } else { 2359 } else {
2233 std::uint64_t size = draw.index.size; 2360 std::uint64_t size = draw.index.size;
2234 if (!vk.buffer_at(draw.index.va, size, p.index_buffer, p.index_offset)) 2361 if (!vk.buffer_at(draw.index.va, size, p.index_buffer, p.index_offset)) {
2235 return ReplayResult::unresolved_resource; 2362 size = draw.index.size;
2363 if (!vk.title_memory || !vk.title_memory(draw.index.va, size, p.index_buffer, p.index_offset))
2364 return ReplayResult::unresolved_resource;
2365 }
2236 p.index_size = size; 2366 p.index_size = size;
2237 } 2367 }
2238 } 2368 }
@@ -2341,6 +2471,7 @@ public:
2341 // The draws' own data, by Prepared::draw. Kept from one execution to the next like the PreparedList itself: the 2471 // The draws' own data, by Prepared::draw. Kept from one execution to the next like the PreparedList itself: the
2342 // first draw_count entries are this list's, and the rest keep their vectors' storage for later draws. 2472 // first draw_count entries are this list's, and the rest keep their vectors' storage for later draws.
2343 std::vector<detail::PreparedDraw> draws; 2473 std::vector<detail::PreparedDraw> draws;
2474 std::vector<detail::DepthUavCopy> depth_uav_copies;
2344 std::size_t draw_count = 0; 2475 std::size_t draw_count = 0;
2345 std::vector<detail::PreparedQuery> queries; 2476 std::vector<detail::PreparedQuery> queries;
2346 VkQueryPool segment_pool = VK_NULL_HANDLE; 2477 VkQueryPool segment_pool = VK_NULL_HANDLE;
@@ -2610,6 +2741,13 @@ inline bool zero_clear_unavailable(const PreparedList& prepared, const ReplayFun
2610 }, 2741 },
2611 command); 2742 command);
2612 if (missing(id, p.binding, p.range)) return true; 2743 if (missing(id, p.binding, p.range)) return true;
2744 if (p.depth_uav_copy != UINT32_MAX) {
2745 const auto& copy = prepared.depth_uav_copies[p.depth_uav_copy];
2746 auto color = p.range;
2747 color.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
2748 if (!copy.to_storage && (missing(p.binding.depth_uav, copy.storage[0], color) ||
2749 missing(p.binding.stencil_uav, copy.storage[1], color))) return true;
2750 }
2613 } 2751 }
2614 return false; 2752 return false;
2615} 2753}
@@ -2627,6 +2765,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2627 out.list = &list; 2765 out.list = &list;
2628 out.commands.assign(commands.size(), {}); 2766 out.commands.assign(commands.size(), {});
2629 out.draw_count = 0; 2767 out.draw_count = 0;
2768 out.depth_uav_copies.clear();
2630 out.queries.clear(); 2769 out.queries.clear();
2631 out.segment_pool = VK_NULL_HANDLE; 2770 out.segment_pool = VK_NULL_HANDLE;
2632 out.segment_base = out.segment_count = 0; 2771 out.segment_base = out.segment_count = 0;
@@ -2657,6 +2796,60 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2657 out.wrote_readback = false; 2796 out.wrote_readback = false;
2658 out.readback_src_stages = 0; 2797 out.readback_src_stages = 0;
2659 2798
2799 // Successive plane transfers use the same transient range and order their buffer accesses in emit().
2800 VkBuffer plane_scratch = VK_NULL_HANDLE;
2801 VkDeviceSize plane_capacity = 0, plane_offset = 0;
2802 const auto prepare_depth_uav = [&](detail::Prepared& p, bool before, bool after) {
2803 if (!p.binding.depth_uav && !p.binding.stencil_uav) return ReplayResult::success;
2804 if (before == after) {
2805 p.order_depth_uav = after;
2806 return ReplayResult::success;
2807 }
2808 if (!vk.copy_image_to_buffer || !vk.copy_buffer_to_image || !vk.copy_scratch)
2809 return ReplayResult::unsupported;
2810 if (!vk.graphics_family) {
2811 // Coupled layouts can also need to zero-initialize the sibling plane on first use.
2812 const auto aspects = detail::planes_for_layout(p.binding, p.range, vk.separate_depth_stencil_layouts).aspectMask;
2813 if (!(vk.queue_stages & VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT) || !vk.compute_copy_aspects ||
2814 (vk.compute_copy_aspects(p.binding.format) & aspects) != aspects)
2815 return ReplayResult::unsupported;
2816 }
2817 if (p.range.baseMipLevel || p.range.levelCount != 1) return ReplayResult::unsupported;
2818 detail::DepthUavCopy copy{};
2819 if (p.binding.depth_conversion && (p.range.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT)) {
2820 if (!vk.graphics_family || !vk.blit_image) return ReplayResult::unsupported;
2821 const auto* middle = resolve(p.binding.depth_conversion);
2822 if (!middle || !middle->image) return ReplayResult::unresolved_resource;
2823 copy.conversion = *middle;
2824 }
2825 const ResourceId ids[] = {p.binding.depth_uav, p.binding.stencil_uav};
2826 for (unsigned plane = 0; plane < 2; ++plane) {
2827 const auto aspect = plane ? VK_IMAGE_ASPECT_STENCIL_BIT : VK_IMAGE_ASPECT_DEPTH_BIT;
2828 if (!(p.range.aspectMask & aspect)) continue;
2829 const auto* child = resolve(ids[plane]);
2830 if (!child || !child->image) return ReplayResult::unresolved_resource;
2831 copy.storage[plane] = *child;
2832 }
2833 const VkDeviceSize texels = VkDeviceSize(p.binding.width) * p.binding.height;
2834 const auto largest_aspect = p.range.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT ? VK_IMAGE_ASPECT_DEPTH_BIT :
2835 VK_IMAGE_ASPECT_STENCIL_BIT;
2836 const VkDeviceSize bytes_per_texel = block_format(p.binding.format, largest_aspect).bytes;
2837 if (!texels || !bytes_per_texel || texels > UINT64_MAX / bytes_per_texel / p.range.layerCount)
2838 return ReplayResult::unsupported;
2839 const VkDeviceSize bytes = texels * bytes_per_texel * p.range.layerCount;
2840 if (bytes > plane_capacity) {
2841 if (!vk.copy_scratch(bytes, plane_scratch, plane_offset) || !plane_scratch || plane_offset % 4)
2842 return ReplayResult::unsupported;
2843 plane_capacity = bytes;
2844 }
2845 copy.scratch = plane_scratch;
2846 copy.offset = plane_offset;
2847 copy.to_storage = after;
2848 p.depth_uav_copy = static_cast<std::uint32_t>(out.depth_uav_copies.size());
2849 out.depth_uav_copies.push_back(copy);
2850 return ReplayResult::success;
2851 };
2852
2660 for (std::size_t i = 0; i < commands.size(); ++i) { 2853 for (std::size_t i = 0; i < commands.size(); ++i) {
2661 const auto& command = commands[i]; 2854 const auto& command = commands[i];
2662 auto& p = out.commands[i]; 2855 auto& p = out.commands[i];
@@ -2694,6 +2887,9 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2694 } else if (!image_range(p.binding, transition->subresource, p.range)) { 2887 } else if (!image_range(p.binding, transition->subresource, p.range)) {
2695 return ReplayResult::invalid_subresource; 2888 return ReplayResult::invalid_subresource;
2696 } 2889 }
2890 const auto result = prepare_depth_uav(p, transition->before & d3d12_state::unordered_access,
2891 transition->after & d3d12_state::unordered_access);
2892 if (result != ReplayResult::success) return result;
2697 } else if (std::holds_alternative<GlobalBarrier>(command) || std::holds_alternative<BufferBarrier>(command)) { 2893 } else if (std::holds_alternative<GlobalBarrier>(command) || std::holds_alternative<BufferBarrier>(command)) {
2698 if (!vk.pipeline_barrier2) return ReplayResult::unsupported; 2894 if (!vk.pipeline_barrier2) return ReplayResult::unsupported;
2699 if (const auto* buffer_barrier = std::get_if<BufferBarrier>(&command)) 2895 if (const auto* buffer_barrier = std::get_if<BufferBarrier>(&command))
@@ -2703,6 +2899,18 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2703 if (!bind(texture->resource)) return ReplayResult::unresolved_resource; 2899 if (!bind(texture->resource)) return ReplayResult::unresolved_resource;
2704 if (!p.binding.image || !barrier_range(p.binding, texture->range, p.range)) 2900 if (!p.binding.image || !barrier_range(p.binding, texture->range, p.range))
2705 return ReplayResult::invalid_subresource; 2901 return ReplayResult::invalid_subresource;
2902 // In a queue-specific COMMON layout shaders can write a UAV then read the SRV or copy the
2903 // parent after only a global barrier. Bindless shaders need no per-resource bind command, so
2904 // there is no observable ownership transition at which to synchronize the two images.
2905 if (p.binding.depth_uav &&
2906 (detail::unsupported_depth_uav_access(texture->layout_before, texture->access_before) ||
2907 detail::unsupported_depth_uav_access(texture->layout_after, texture->access_after)))
2908 return ReplayResult::unsupported;
2909 if (!(texture->flags & texture_barrier_discard) && texture->layout_before != d3d12_layout::undefined) {
2910 const auto result = prepare_depth_uav(p, detail::texture_uav_layout(texture->layout_before),
2911 detail::texture_uav_layout(texture->layout_after));
2912 if (result != ReplayResult::success) return result;
2913 }
2706 } else if (const auto* color_clear = std::get_if<ClearRenderTarget>(&command)) { 2914 } else if (const auto* color_clear = std::get_if<ClearRenderTarget>(&command)) {
2707 if (!bind(color_clear->target.resource)) return ReplayResult::unresolved_resource; 2915 if (!bind(color_clear->target.resource)) return ReplayResult::unresolved_resource;
2708 if (!p.binding.image || p.binding.aspects != VK_IMAGE_ASPECT_COLOR_BIT) return ReplayResult::invalid_clear; 2916 if (!p.binding.image || p.binding.aspects != VK_IMAGE_ASPECT_COLOR_BIT) return ReplayResult::invalid_clear;
@@ -2775,20 +2983,55 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2775 // Emulated R9G9B9E5_SHAREDEXP images (backed by R32_UINT) lack COLOR_ATTACHMENT on E5B9G9R9 and keep the 2983 // Emulated R9G9B9E5_SHAREDEXP images (backed by R32_UINT) lack COLOR_ATTACHMENT on E5B9G9R9 and keep the
2776 // bit-exact R32_UINT backing path. 2984 // bit-exact R32_UINT backing path.
2777 const VkFormat view_format = view.format ? VkFormat(view.format) : p.binding.format; 2985 const VkFormat view_format = view.format ? VkFormat(view.format) : p.binding.format;
2986 const bool packed_rgb9e5 = view_format == VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 &&
2987 p.binding.format == VK_FORMAT_R32_UINT;
2778 if (!uav_clear::encode(view_format, uav->is_float, uav->values, p.element)) 2988 if (!uav_clear::encode(view_format, uav->is_float, uav->values, p.element))
2779 return ReplayResult::unsupported; 2989 return ReplayResult::unsupported;
2780 const auto* image_layout = uav_clear::layout(p.binding.format); 2990 const auto* image_layout = uav_clear::layout(p.binding.format);
2781 if (!image_layout || image_layout->bytes != p.element.size) 2991 if (!image_layout || image_layout->bytes != p.element.size)
2782 return ReplayResult::unsupported; 2992 return ReplayResult::unsupported;
2783 const bool attachment = p.binding.color_attachment && !p.binding.volume; 2993 // The UAV attachment path supports 1D-array and 2D-array views. Keep 3D clears on the transfer
2994 // path and retain the exact-format restriction for 1D/3D UAVs below.
2995 const bool attachment = p.binding.color_attachment && !p.binding.volume &&
2996 (!view.exact_clear_format || p.binding.line);
2784 const bool view_attachable = vk.color_attachment_format 2997 const bool view_attachable = vk.color_attachment_format
2785 ? vk.color_attachment_format(view_format) 2998 ? vk.color_attachment_format(view_format)
2786 : view_format != VK_FORMAT_E5B9G9R9_UFLOAT_PACK32; 2999 : view_format != VK_FORMAT_E5B9G9R9_UFLOAT_PACK32;
2787 const bool reinterpret = view_format != p.binding.format && attachment && view_attachable; 3000 const bool reinterpret = view_format != p.binding.format && attachment && view_attachable && !packed_rgb9e5;
3001 if (view.exact_clear_format && view_format != p.binding.format && !packed_rgb9e5)
3002 return ReplayResult::unsupported;
2788 const VkFormat clear_format = reinterpret ? view_format : p.binding.format; 3003 const VkFormat clear_format = reinterpret ? view_format : p.binding.format;
2789 if (!uav_clear::decode(clear_format, p.element, p.clear_color)) 3004 if (!uav_clear::decode(clear_format, p.element, p.clear_color))
2790 return ReplayResult::unsupported; 3005 return ReplayResult::unsupported;
2791 if (reinterpret) p.clear_format = view_format; 3006 if (reinterpret) p.clear_format = view_format;
3007 // Compute list barriers have no attachment stages, and a dedicated compute queue cannot render.
3008 // Copy the encoded texel bits from a filled buffer. Transfers cannot implement a predicated clear.
3009 if ((vk.queue_stages & VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT) &&
3010 (!uav->rects.empty() || reinterpret || predicated)) {
3011 if (predicated || p.binding.volume || !vk.copy_scratch || !vk.fill_buffer || !vk.copy_buffer_to_image ||
3012 (p.element.size != 1 && p.element.size != 2 && p.element.size != 4))
3013 return ReplayResult::unsupported;
3014 const auto rects = uav->rects.empty() ? std::span<const Rect>(&whole_view, 1) :
3015 std::span<const Rect>(uav->rects);
3016 detail::clip(rects, detail::mip_extent(p.binding, view.mip), view.layer_count, p.rects);
3017 if (p.rects.empty()) { p.skip = true; continue; }
3018 for (const auto& rect : p.rects) {
3019 VkBufferImageCopy region{};
3020 region.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, view.mip, view.first_layer, view.layer_count};
3021 region.imageOffset = {rect.rect.offset.x, rect.rect.offset.y, 0};
3022 region.imageExtent = {rect.rect.extent.width, rect.rect.extent.height, 1};
3023 const VkDeviceSize pixels = VkDeviceSize(region.imageExtent.width) * region.imageExtent.height;
3024 const VkDeviceSize stride = VkDeviceSize(view.layer_count) * p.element.size;
3025 if (pixels > (UINT64_MAX - 3) / stride) return ReplayResult::unsupported;
3026 p.clear_pattern_bytes = std::max(p.clear_pattern_bytes, (pixels * stride + 3) & ~VkDeviceSize(3));
3027 p.staged_writes.push_back(region);
3028 }
3029 VkDeviceSize offset = 0;
3030 if (!vk.copy_scratch(p.clear_pattern_bytes, p.staged, offset) || !p.staged || offset % 4)
3031 return ReplayResult::unsupported;
3032 for (auto& region : p.staged_writes) region.bufferOffset = offset;
3033 continue;
3034 }
2792 if (!uav->rects.empty() && !attachment) 3035 if (!uav->rects.empty() && !attachment)
2793 return ReplayResult::unsupported; 3036 return ReplayResult::unsupported;
2794 // Under a predicate a whole view is cleared as one rectangle where the image can be an attachment, as 3037 // Under a predicate a whole view is cleared as one rectangle where the image can be an attachment, as
@@ -2854,6 +3097,9 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2854 if (result == ReplayResult::success && texture_copy->tile_footprint && !p.buffer_image_copies.empty() && 3097 if (result == ReplayResult::success && texture_copy->tile_footprint && !p.buffer_image_copies.empty() &&
2855 p.buffer_image_copies.front().bufferOffset % 4 && !detail::stage_unaligned_tile(vk, p, upload)) 3098 p.buffer_image_copies.front().bufferOffset % 4 && !detail::stage_unaligned_tile(vk, p, upload))
2856 return ReplayResult::unsupported; 3099 return ReplayResult::unsupported;
3100 if(result==ReplayResult::success && image.rgba4_render_fallback) return ReplayResult::unsupported;
3101 if(result==ReplayResult::success && image.xbox_depth16_stencil8 && image.format!=VK_FORMAT_D16_UNORM_S8_UINT &&
3102 !p.buffer_image_copies.empty() && p.buffer_image_copies[0].imageSubresource.aspectMask==VK_IMAGE_ASPECT_DEPTH_BIT) return ReplayResult::unsupported;
2857 const bool depth24_footprint = result == ReplayResult::success && image.depth24_as_float && 3103 const bool depth24_footprint = result == ReplayResult::success && image.depth24_as_float &&
2858 !p.buffer_image_copies.empty() && 3104 !p.buffer_image_copies.empty() &&
2859 p.buffer_image_copies[0].imageSubresource.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT; 3105 p.buffer_image_copies[0].imageSubresource.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT;
@@ -2986,6 +3232,8 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2986 if (!discard->partial) p.discards.push_back(range); 3232 if (!discard->partial) p.discards.push_back(range);
2987 } 3233 }
2988 } 3234 }
3235 } else if (std::holds_alternative<label::Write>(command)) {
3236 // No GPU destination pointer is expected: the batch publishes only a registered title allocation.
2989 } else if (const auto* write = std::get_if<WriteImmediate>(&command)) { 3237 } else if (const auto* write = std::get_if<WriteImmediate>(&command)) {
2990 if (!vk.update_buffer || !vk.buffer_at) return ReplayResult::unsupported; 3238 if (!vk.update_buffer || !vk.buffer_at) return ReplayResult::unsupported;
2991 std::uint64_t bytes = 4; 3239 std::uint64_t bytes = 4;
@@ -3118,9 +3366,13 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
3118 if (ind->kind == IndirectKind::dispatch && ind->pipeline) { // the pipeline and root arguments it was recorded 3366 if (ind->kind == IndirectKind::dispatch && ind->pipeline) { // the pipeline and root arguments it was recorded
3119 if (!vk.bind_pipeline || !vk.push_constants || !vk.compute_pipeline) return ReplayResult::unsupported; 3367 if (!vk.bind_pipeline || !vk.push_constants || !vk.compute_pipeline) return ReplayResult::unsupported;
3120 const ComputePipeline* pipeline = vk.compute_pipeline(ind->pipeline); 3368 const ComputePipeline* pipeline = vk.compute_pipeline(ind->pipeline);
3121 if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; 3369 if (!pipeline || (!pipeline->pipeline && !pipeline->materialize)) return ReplayResult::unresolved_resource;
3122 if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; 3370 if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported;
3123 p.pipeline = *pipeline; 3371 p.pipeline = *pipeline;
3372 if (!p.pipeline.pipeline) {
3373 p.pipeline.pipeline=pipeline->materialize();
3374 if (!p.pipeline.pipeline) return ReplayResult::unsupported;
3375 }
3124 } 3376 }
3125 } else if (const auto* build = std::get_if<BuildAccelerationStructure>(&command)) { 3377 } else if (const auto* build = std::get_if<BuildAccelerationStructure>(&command)) {
3126 p.khr_instances = 0; 3378 p.khr_instances = 0;
@@ -3206,9 +3458,13 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
3206 if (!vk.bind_pipeline || !vk.push_constants || !vk.dispatch || !vk.compute_pipeline) 3458 if (!vk.bind_pipeline || !vk.push_constants || !vk.dispatch || !vk.compute_pipeline)
3207 return ReplayResult::unsupported; 3459 return ReplayResult::unsupported;
3208 const ComputePipeline* pipeline = vk.compute_pipeline(dispatch->pipeline); 3460 const ComputePipeline* pipeline = vk.compute_pipeline(dispatch->pipeline);
3209 if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; 3461 if (!pipeline || (!pipeline->pipeline && !pipeline->materialize)) return ReplayResult::unresolved_resource;
3210 if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; 3462 if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported;
3211 p.pipeline = *pipeline; 3463 p.pipeline = *pipeline;
3464 if (!p.pipeline.pipeline) {
3465 p.pipeline.pipeline=pipeline->materialize();
3466 if (!p.pipeline.pipeline) return ReplayResult::unsupported;
3467 }
3212 } else if (const auto* draw = std::get_if<Draw>(&command)) { 3468 } else if (const auto* draw = std::get_if<Draw>(&command)) {
3213 if (out.draw_count == out.draws.size()) out.draws.emplace_back(); 3469 if (out.draw_count == out.draws.size()) out.draws.emplace_back();
3214 auto& prepared_draw = out.draws[out.draw_count]; 3470 auto& prepared_draw = out.draws[out.draw_count];
@@ -3498,6 +3754,15 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3498 vk.depth24_run(command_buffer, job); 3754 vk.depth24_run(command_buffer, job);
3499 if (predicate.buffer) vk.begin_conditional_rendering(command_buffer, &predicate); 3755 if (predicate.buffer) vk.begin_conditional_rendering(command_buffer, &predicate);
3500 }; 3756 };
3757 const auto finish_depth_uav_barrier = [&](const detail::Prepared& p, VkImageLayout layout) {
3758 if (p.depth_uav_copy != UINT32_MAX) {
3759 detail::copy_depth_uav(vk, command_buffer, p, prepared.depth_uav_copies[p.depth_uav_copy], layout, tracker);
3760 } else if (p.order_depth_uav) {
3761 // A UAV-to-UAV texture barrier names the parent, but the actual shader accesses target its children.
3762 detail::memory_barrier(vk, command_buffer, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
3763 VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
3764 }
3765 };
3501 3766
3502 for (std::size_t i = 0; i < commands.size(); ++i) { 3767 for (std::size_t i = 0; i < commands.size(); ++i) {
3503 const auto& command = commands[i]; 3768 const auto& command = commands[i];
@@ -3569,6 +3834,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3569 detail::image_barrier(vk, command_buffer, p.binding, piece.range, piece.layout, new_layout, 3834 detail::image_barrier(vk, command_buffer, p.binding, piece.range, piece.layout, new_layout,
3570 from.access, from.stages, to.access, to.stages); 3835 from.access, from.stages, to.access, to.stages);
3571 if (tracker) tracker->set(id, range, new_layout); 3836 if (tracker) tracker->set(id, range, new_layout);
3837 finish_depth_uav_barrier(p, new_layout);
3572 } else if (std::holds_alternative<UavBarrier>(command)) { 3838 } else if (std::holds_alternative<UavBarrier>(command)) {
3573 const VulkanAccess uav = vulkan_access(d3d12_state::unordered_access, false); 3839 const VulkanAccess uav = vulkan_access(d3d12_state::unordered_access, false);
3574 VkAccessFlags src_access = VK_ACCESS_SHADER_WRITE_BIT; 3840 VkAccessFlags src_access = VK_ACCESS_SHADER_WRITE_BIT;
@@ -3585,7 +3851,10 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3585 detail::memory_barrier(vk, command_buffer, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 3851 detail::memory_barrier(vk, command_buffer, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
3586 VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT, 3852 VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT,
3587 VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); 3853 VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
3588 } else if (std::holds_alternative<GlobalBarrier>(command) || std::holds_alternative<BufferBarrier>(command)) { 3854 } else if (const auto* texture_memory = std::get_if<TextureBarrier>(&command);
3855 std::holds_alternative<GlobalBarrier>(command) || std::holds_alternative<BufferBarrier>(command) ||
3856 (texture_memory && p.binding.depth_uav && texture_memory->layout_before == d3d12_layout::undefined &&
3857 texture_memory->layout_after == d3d12_layout::undefined)) {
3589 const auto [sync_before, sync_after, access_before, access_after] = std::visit( 3858 const auto [sync_before, sync_after, access_before, access_after] = std::visit(
3590 [](const auto& c) -> std::array<std::uint32_t, 4> { 3859 [](const auto& c) -> std::array<std::uint32_t, 4> {
3591 if constexpr (requires { c.sync_before; }) 3860 if constexpr (requires { c.sync_before; })
@@ -3614,10 +3883,13 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3614 const VkImageLayout new_layout = 3883 const VkImageLayout new_layout =
3615 image_layout(p.binding, vulkan_layout(texture->layout_after, p.binding.presentable)); 3884 image_layout(p.binding, vulkan_layout(texture->layout_after, p.binding.presentable));
3616 LayoutPieces pieces; 3885 LayoutPieces pieces;
3617 if (discard) 3886 // With coupled layouts, discarding a single plane must preserve the other plane's data.
3887 const bool keep_sibling = p.binding.depth_uav && range.aspectMask != p.range.aspectMask;
3888 if (discard && !keep_sibling)
3618 pieces.push_back({range, VK_IMAGE_LAYOUT_UNDEFINED}); 3889 pieces.push_back({range, VK_IMAGE_LAYOUT_UNDEFINED});
3619 else { 3890 else {
3620 const VkImageLayout before = 3891 const VkImageLayout before =
3892 texture->layout_before == d3d12_layout::undefined ? VK_IMAGE_LAYOUT_GENERAL :
3621 image_layout(p.binding, vulkan_layout(texture->layout_before, p.binding.presentable)); 3893 image_layout(p.binding, vulkan_layout(texture->layout_before, p.binding.presentable));
3622 pieces = detail::current(tracker, id, range, before); 3894 pieces = detail::current(tracker, id, range, before);
3623 detail::initialize(vk, command_buffer, p.binding, id, pieces, before, tracker); 3895 detail::initialize(vk, command_buffer, p.binding, id, pieces, before, tracker);
@@ -3651,12 +3923,16 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3651 dependency.pImageMemoryBarriers = barriers; 3923 dependency.pImageMemoryBarriers = barriers;
3652 vk.pipeline_barrier2(command_buffer, &dependency); 3924 vk.pipeline_barrier2(command_buffer, &dependency);
3653 if (tracker) tracker->set(id, range, new_layout); 3925 if (tracker) tracker->set(id, range, new_layout);
3926 finish_depth_uav_barrier(p, new_layout);
3654 } else if (const auto* color_clear = std::get_if<ClearRenderTarget>(&command)) { 3927 } else if (const auto* color_clear = std::get_if<ClearRenderTarget>(&command)) {
3655 if (p.skip) continue; 3928 if (p.skip) continue;
3656 const VulkanAccess state = vulkan_access(d3d12_state::render_target, false); 3929 const VulkanAccess state = vulkan_access(d3d12_state::render_target, false);
3657 auto pieces = detail::current(tracker, id, p.range, image_layout(p.binding, state.layout)); 3930 auto pieces = detail::current(tracker, id, p.range, image_layout(p.binding, state.layout));
3658 detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker); 3931 detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker);
3659 const VkClearColorValue color = detail::render_target_clear_color(p.clear_format, color_clear->color); 3932 auto clear_value=color_clear->color;
3933 if(p.binding.rgba4_render_fallback)for(auto& channel:clear_value)
3934 channel=std::nearbyint(std::clamp(channel,0.0f,1.0f)*15.0f)/15.0f;
3935 const VkClearColorValue color=detail::render_target_clear_color(p.clear_format,clear_value);
3660 if (p.rects.empty()) { 3936 if (p.rects.empty()) {
3661 detail::round_trip(vk, command_buffer, p.binding, pieces, image_layout(p.binding, transfer_dst.layout), 3937 detail::round_trip(vk, command_buffer, p.binding, pieces, image_layout(p.binding, transfer_dst.layout),
3662 state, transfer_dst.access, transfer_dst.stages, [&] { 3938 state, transfer_dst.access, transfer_dst.stages, [&] {
@@ -3691,7 +3967,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3691 const VulkanAccess state = vulkan_access(d3d12_state::depth_write, false); 3967 const VulkanAccess state = vulkan_access(d3d12_state::depth_write, false);
3692 auto pieces = detail::current(tracker, id, range, image_layout(p.binding, state.layout)); 3968 auto pieces = detail::current(tracker, id, range, image_layout(p.binding, state.layout));
3693 detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker); 3969 detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker);
3694 const float depth = p.binding.depth24 ? depth24_clear_value(depth_clear->depth) // see depth24.h 3970 const float depth = p.binding.xbox_depth16_stencil8 ? std::round(std::clamp(depth_clear->depth,0.0f,1.0f)*65535.0f)/65535.0f : p.binding.depth24 ? depth24_clear_value(depth_clear->depth) // see depth24.h
3695 : p.binding.format == VK_FORMAT_D16_UNORM 3971 : p.binding.format == VK_FORMAT_D16_UNORM
3696 ? detail::quantize_unorm(depth_clear->depth, 65535.0) // see quantize_unorm 3972 ? detail::quantize_unorm(depth_clear->depth, 65535.0) // see quantize_unorm
3697 : depth_clear->depth; 3973 : depth_clear->depth;
@@ -3749,6 +4025,21 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3749 const VkImageLayout layout = image_layout(p.binding, state.layout); 4025 const VkImageLayout layout = image_layout(p.binding, state.layout);
3750 auto pieces = detail::current(tracker, id, p.range, layout); 4026 auto pieces = detail::current(tracker, id, p.range, layout);
3751 detail::initialize(vk, command_buffer, p.binding, id, pieces, layout, tracker); 4027 detail::initialize(vk, command_buffer, p.binding, id, pieces, layout, tracker);
4028 if (p.clear_pattern_bytes) {
4029 detail::round_trip(vk, command_buffer, p.binding, pieces, layout, state, VK_ACCESS_TRANSFER_WRITE_BIT,
4030 VK_PIPELINE_STAGE_TRANSFER_BIT, [&] {
4031 detail::emit_buffer_fill(vk, command_buffer, p.staged, p.element, p.staged_writes.front().bufferOffset,
4032 p.clear_pattern_bytes);
4033 for (const auto& region : p.staged_writes) {
4034 // The fill must be visible, and two clear rectangles may overlap.
4035 detail::memory_barrier(vk, command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
4036 VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT,
4037 VK_PIPELINE_STAGE_TRANSFER_BIT);
4038 vk.copy_buffer_to_image(command_buffer, p.staged, p.binding.image, layout, 1, &region);
4039 }
4040 });
4041 continue;
4042 }
3752 if (p.rects.empty()) { 4043 if (p.rects.empty()) {
3753 detail::round_trip(vk, command_buffer, p.binding, pieces, layout, state, 4044 detail::round_trip(vk, command_buffer, p.binding, pieces, layout, state,
3754 VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, [&] { 4045 VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, [&] {
@@ -4020,6 +4311,8 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
4020 piece.layout, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 4311 piece.layout, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
4021 any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); 4312 any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
4022 } 4313 }
4314 } else if (const auto* label_write=std::get_if<label::Write>(&command)) {
4315 label::completions().record(command_buffer,*label_write);
4023 } else if (const auto* write = std::get_if<WriteImmediate>(&command)) { 4316 } else if (const auto* write = std::get_if<WriteImmediate>(&command)) {
4024 // vkCmdUpdateBuffer runs in the transfer stage. MARKER_OUT waits for every earlier command to finish 4317 // vkCmdUpdateBuffer runs in the transfer stage. MARKER_OUT waits for every earlier command to finish
4025 // and sees its writes. MARKER_IN only needs them started, which Vulkan cannot express (TOP_OF_PIPE in a 4318 // and sees its writes. MARKER_IN only needs them started, which Vulkan cannot express (TOP_OF_PIPE in a
@@ -4266,7 +4559,8 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
4266 // A mesh pipeline has no input assembly: its topology comes from the shader, and neither the topology 4559 // A mesh pipeline has no input assembly: its topology comes from the shader, and neither the topology
4267 // nor primitive restart is dynamic state there (VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-07065). 4560 // nor primitive restart is dynamic state there (VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-07065).
4268 if (!draw->mesh) { 4561 if (!draw->mesh) {
4269 const VkPrimitiveTopology topology = detail::vulkan_topology(draw->topology); 4562 const VkPrimitiveTopology topology = draw->topology == topology_quad_list && !draw->indexed
4563 ? VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST : detail::vulkan_topology(draw->topology);
4270 vk.set_primitive_topology(command_buffer, topology); 4564 vk.set_primitive_topology(command_buffer, topology);
4271 const bool restart = draw->indexed && detail::strip_topology(topology) && 4565 const bool restart = draw->indexed && detail::strip_topology(topology) &&
4272 ((graphics.strip_cut == 1 && d.index_type == VK_INDEX_TYPE_UINT16) || 4566 ((graphics.strip_cut == 1 && d.index_type == VK_INDEX_TYPE_UINT16) ||
diff --git a/runtime/src/vulkan_scratch.h b/runtime/src/vulkan_scratch.h
index c12d909e6..a7187441e 100644
--- a/runtime/src/vulkan_scratch.h
+++ b/runtime/src/vulkan_scratch.h
@@ -11,6 +11,7 @@
11#define VK_NO_PROTOTYPES 11#define VK_NO_PROTOTYPES
12#endif 12#endif
13#include <vulkan/vulkan.h> 13#include <vulkan/vulkan.h>
14#include "queue_families.h"
14 15
15#include <algorithm> 16#include <algorithm>
16#include <cstdint> 17#include <cstdint>
@@ -25,8 +26,9 @@ public:
25 // A device-local allocation for a chunk; null on failure. 26 // A device-local allocation for a chunk; null on failure.
26 using Allocate = std::function<VkDeviceMemory(const VkMemoryRequirements&)>; 27 using Allocate = std::function<VkDeviceMemory(const VkMemoryRequirements&)>;
27 28
28 ScratchBuffers(PFN_vkGetDeviceProcAddr get, VkDevice device, Allocate allocate, VkBufferUsageFlags extra_usage = 0) 29 ScratchBuffers(PFN_vkGetDeviceProcAddr get, VkDevice device, Allocate allocate, VkBufferUsageFlags extra_usage = 0,
29 : device_(device), allocate_(std::move(allocate)), extra_usage_(extra_usage) { 30 std::vector<std::uint32_t> families = {})
31 : device_(device), allocate_(std::move(allocate)), extra_usage_(extra_usage), families_(std::move(families)) {
30 loaded_ = vk_.load(get, device); 32 loaded_ = vk_.load(get, device);
31 } 33 }
32 34
@@ -151,6 +153,8 @@ private:
151 VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; 153 VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
152 info.size = size; 154 info.size = size;
153 info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | extra_usage_; 155 info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | extra_usage_;
156 // A retired chunk can be reused by a submission on a different queue family.
157 share_across_queue_families(info, families_);
154 if (vk_.vkCreateBuffer(device_, &info, nullptr, &out.buffer) != VK_SUCCESS) return false; 158 if (vk_.vkCreateBuffer(device_, &info, nullptr, &out.buffer) != VK_SUCCESS) return false;
155 VkMemoryRequirements requirements{}; 159 VkMemoryRequirements requirements{};
156 vk_.vkGetBufferMemoryRequirements(device_, out.buffer, &requirements); 160 vk_.vkGetBufferMemoryRequirements(device_, out.buffer, &requirements);
@@ -175,6 +179,7 @@ private:
175 VkDevice device_; 179 VkDevice device_;
176 Allocate allocate_; 180 Allocate allocate_;
177 VkBufferUsageFlags extra_usage_ = 0; 181 VkBufferUsageFlags extra_usage_ = 0;
182 std::vector<std::uint32_t> families_;
178 Functions vk_; 183 Functions vk_;
179 bool loaded_ = false; 184 bool loaded_ = false;
180 Batch current_; // handed out, not yet submitted 185 Batch current_; // handed out, not yet submitted