diff options
| author | kovaaper <kovaaker@gmail.com> | 2026-11-22 13:48:37 +0300 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-11-22 13:48:37 +0300 |
| commit | 2811597fd9a56811b8d345c25d51ea2eb779b3fb (patch) | |
| tree | ec09f4d1c0d642cdf6a57e9ee978c1c02b7ebcf2 /runtime/src | |
| parent | aa87b9459689245124809586c94a6e847a193cc1 (diff) | |
| parent | f85582e23d4ab9e19acbf694358f137d6b8531b1 (diff) | |
Merge branch 'ItsNotRexed:main' into codex/d3d97-separate-queues
Diffstat (limited to 'runtime/src')
| -rw-r--r-- | runtime/src/command_list.h | 12 | ||||
| -rw-r--r-- | runtime/src/depth24_convert.comp | 11 | ||||
| -rw-r--r-- | runtime/src/depth24_convert.inc | 127 | ||||
| -rw-r--r-- | runtime/src/gfx10_descriptors.h | 13 | ||||
| -rw-r--r-- | runtime/src/occlusion_sum.comp | 19 | ||||
| -rw-r--r-- | runtime/src/occlusion_sum_spirv.h | 47 | ||||
| -rw-r--r-- | runtime/src/pe_loader.cpp | 58 | ||||
| -rw-r--r-- | runtime/src/pe_loader.h | 11 | ||||
| -rw-r--r-- | runtime/src/predicate_reduce.comp | 6 | ||||
| -rw-r--r-- | runtime/src/predicate_reduce_spv.h | 36 | ||||
| -rw-r--r-- | runtime/src/predicated_copy.comp | 11 | ||||
| -rw-r--r-- | runtime/src/predicated_copy_spv.h | 54 | ||||
| -rw-r--r-- | runtime/src/resource_tiling.h | 14 | ||||
| -rw-r--r-- | runtime/src/uav_clear.h | 55 | ||||
| -rw-r--r-- | runtime/src/vulkan_backend.h | 973 | ||||
| -rw-r--r-- | runtime/src/vulkan_bindless.h | 184 | ||||
| -rw-r--r-- | runtime/src/vulkan_predicate.h | 183 | ||||
| -rw-r--r-- | runtime/src/vulkan_predicated_copy.h | 154 | ||||
| -rw-r--r-- | runtime/src/vulkan_replay.h | 505 |
19 files changed, 2120 insertions, 353 deletions
diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h index f786ce60f..080f94a84 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h | |||
| @@ -330,10 +330,18 @@ struct CopyResource { | |||
| 330 | ResourceId src; | 330 | ResourceId src; |
| 331 | }; | 331 | }; |
| 332 | 332 | ||
| 333 | // D3D12_RESOLVE_MODE values a region resolve replays. | ||
| 334 | namespace d3d12_resolve_mode { | ||
| 335 | inline constexpr std::uint32_t minimum = 1; | ||
| 336 | inline constexpr std::uint32_t maximum = 2; | ||
| 337 | inline constexpr std::uint32_t average = 3; | ||
| 338 | } | ||
| 339 | |||
| 333 | struct ResolveRegion { | 340 | struct ResolveRegion { |
| 334 | std::uint32_t dst_x; | 341 | std::uint32_t dst_x; |
| 335 | std::uint32_t dst_y; | 342 | std::uint32_t dst_y; |
| 336 | std::optional<Rect> src_rect; | 343 | std::optional<Rect> src_rect; |
| 344 | std::uint32_t mode = d3d12_resolve_mode::average; // colour: average only; stencil: minimum or maximum | ||
| 337 | }; | 345 | }; |
| 338 | 346 | ||
| 339 | // Without a region, both subresources have the same extent. A region with no source rectangle takes the | 347 | // Without a region, both subresources have the same extent. A region with no source rectangle takes the |
| @@ -577,7 +585,8 @@ public: | |||
| 577 | // Copies. The rules D3D12 states for the call itself are checked here; ranges against the resources are | 585 | // Copies. The rules D3D12 states for the call itself are checked here; ranges against the resources are |
| 578 | // checked at replay, when the resources are known. | 586 | // checked at replay, when the resources are known. |
| 579 | bool copy_buffer(const CopyBuffer& copy) { | 587 | bool copy_buffer(const CopyBuffer& copy) { |
| 580 | if (!copy.dst || !copy.src || !copy.size) return false; | 588 | if (!copy.dst || !copy.src) return false; |
| 589 | if (!copy.size) return !closed_; // Native D3D12 accepts a zero-byte CopyBufferRegion as a no-op. | ||
| 581 | return append(copy); | 590 | return append(copy); |
| 582 | } | 591 | } |
| 583 | 592 | ||
| @@ -599,6 +608,7 @@ public: | |||
| 599 | if (!resolve.dst || !resolve.src || resolve.dst == resolve.src) return false; | 608 | if (!resolve.dst || !resolve.src || resolve.dst == resolve.src) return false; |
| 600 | if (const auto& region = resolve.region) { | 609 | if (const auto& region = resolve.region) { |
| 601 | if (region->dst_x > INT32_MAX || region->dst_y > INT32_MAX) return false; | 610 | if (region->dst_x > INT32_MAX || region->dst_y > INT32_MAX) return false; |
| 611 | if (region->mode < d3d12_resolve_mode::minimum || region->mode > d3d12_resolve_mode::average) return false; | ||
| 602 | if (const auto& r = region->src_rect; | 612 | if (const auto& r = region->src_rect; |
| 603 | r && (r->left < 0 || r->top < 0 || r->right <= r->left || r->bottom <= r->top)) | 613 | r && (r->left < 0 || r->top < 0 || r->right <= r->left || r->bottom <= r->top)) |
| 604 | return false; | 614 | return false; |
diff --git a/runtime/src/depth24_convert.comp b/runtime/src/depth24_convert.comp index eb4795a35..688f68d78 100644 --- a/runtime/src/depth24_convert.comp +++ b/runtime/src/depth24_convert.comp | |||
| @@ -36,10 +36,11 @@ float depth24_to_float(uint d) { | |||
| 36 | // The 24-bit UNORM of f as WARP and AMD's D3D12 drivers write it: the product with 2^24 - 1 is rounded to a float | 36 | // The 24-bit UNORM of f as WARP and AMD's D3D12 drivers write it: the product with 2^24 - 1 is rounded to a float |
| 37 | // first, then to the nearest integer with ties to even (NVIDIA's hardware breaks some ties the other way; see | 37 | // first, then to the nearest integer with ties to even (NVIDIA's hardware breaks some ties the other way; see |
| 38 | // depth24.h). NaN and negatives give 0, 1 and above the maximum. | 38 | // depth24.h). NaN and negatives give 0, 1 and above the maximum. |
| 39 | uint depth24_from_float(float f) { | 39 | uint depth24_from_bits(uint bits) { |
| 40 | if (!(f > 0.0)) return 0u; | 40 | // In unsigned order, all negative encodings and positive NaNs lie above positive infinity. |
| 41 | if (f >= 1.0) return 0xffffffu; | 41 | if (bits > 0x7f800000u) return 0u; |
| 42 | return uint(roundEven(f * 16777215.0)); | 42 | if (bits >= 0x3f800000u) return 0xffffffu; |
| 43 | return uint(roundEven(uintBitsToFloat(bits) * 16777215.0)); | ||
| 43 | } | 44 | } |
| 44 | 45 | ||
| 45 | void main() { | 46 | void main() { |
| @@ -48,5 +49,5 @@ void main() { | |||
| 48 | uint a = pc.app_base + g.z * pc.app_slice + g.y * pc.app_row + g.x; | 49 | uint a = pc.app_base + g.z * pc.app_slice + g.y * pc.app_row + g.x; |
| 49 | uint s = pc.scratch_base + (g.z * pc.height + g.y) * pc.width + g.x; | 50 | uint s = pc.scratch_base + (g.z * pc.height + g.y) * pc.width + g.x; |
| 50 | if (pc.to_float != 0u) scratch[s] = floatBitsToUint(depth24_to_float(app[a] & 0xffffffu)); | 51 | if (pc.to_float != 0u) scratch[s] = floatBitsToUint(depth24_to_float(app[a] & 0xffffffu)); |
| 51 | else app[a] = depth24_from_float(uintBitsToFloat(scratch[s])); | 52 | else app[a] = depth24_from_bits(scratch[s]); |
| 52 | } | 53 | } |
diff --git a/runtime/src/depth24_convert.inc b/runtime/src/depth24_convert.inc index a237a5af4..9438af65b 100644 --- a/runtime/src/depth24_convert.inc +++ b/runtime/src/depth24_convert.inc | |||
| @@ -27,17 +27,18 @@ | |||
| 27 | 0x00000000,0x00000023,0x00000000,0x00040047, | 27 | 0x00000000,0x00000023,0x00000000,0x00040047, |
| 28 | 0x000000a7,0x00000021,0x00000000,0x00040047, | 28 | 0x000000a7,0x00000021,0x00000000,0x00040047, |
| 29 | 0x000000a7,0x00000022,0x00000000,0x00040047, | 29 | 0x000000a7,0x00000022,0x00000000,0x00040047, |
| 30 | 0x000000bb,0x0000000b,0x00000019,0x00020013, | 30 | 0x000000ba,0x0000000b,0x00000019,0x00020013, |
| 31 | 0x00000002,0x00030021,0x00000003,0x00000002, | 31 | 0x00000002,0x00030021,0x00000003,0x00000002, |
| 32 | 0x00040015,0x00000006,0x00000020,0x00000000, | 32 | 0x00040015,0x00000006,0x00000020,0x00000000, |
| 33 | 0x00030016,0x00000008,0x00000020,0x0004002b, | 33 | 0x00030016,0x00000008,0x00000020,0x0004002b, |
| 34 | 0x00000006,0x00000013,0x00000000,0x00020014, | 34 | 0x00000006,0x00000012,0x00000000,0x00020014, |
| 35 | 0x00000014,0x0004002b,0x00000008,0x00000018, | 35 | 0x00000013,0x0004002b,0x00000008,0x00000017, |
| 36 | 0x00000000,0x00040015,0x0000001a,0x00000020, | 36 | 0x00000000,0x00040015,0x00000019,0x00000020, |
| 37 | 0x00000001,0x0004002b,0x0000001a,0x00000021, | 37 | 0x00000001,0x0004002b,0x00000019,0x00000020, |
| 38 | 0x00000017,0x0004002b,0x00000006,0x00000027, | 38 | 0x00000017,0x0004002b,0x00000006,0x00000026, |
| 39 | 0x00000001,0x0004002b,0x00000008,0x0000003c, | 39 | 0x00000001,0x0004002b,0x00000006,0x00000035, |
| 40 | 0x3f800000,0x0004002b,0x00000006,0x00000040, | 40 | 0x7f800000,0x0004002b,0x00000006,0x0000003b, |
| 41 | 0x3f800000,0x0004002b,0x00000006,0x0000003f, | ||
| 41 | 0x00ffffff,0x0004002b,0x00000008,0x00000043, | 42 | 0x00ffffff,0x0004002b,0x00000008,0x00000043, |
| 42 | 0x4b7fffff,0x00040017,0x00000049,0x00000006, | 43 | 0x4b7fffff,0x00040017,0x00000049,0x00000006, |
| 43 | 0x00000003,0x00040020,0x0000004c,0x00000001, | 44 | 0x00000003,0x00040020,0x0000004c,0x00000001, |
| @@ -47,15 +48,15 @@ | |||
| 47 | 0x00000006,0x00000006,0x00000006,0x00040020, | 48 | 0x00000006,0x00000006,0x00000006,0x00040020, |
| 48 | 0x00000052,0x00000009,0x00000051,0x0004003b, | 49 | 0x00000052,0x00000009,0x00000051,0x0004003b, |
| 49 | 0x00000052,0x00000053,0x00000009,0x0004002b, | 50 | 0x00000052,0x00000053,0x00000009,0x0004002b, |
| 50 | 0x0000001a,0x00000054,0x00000000,0x00040020, | 51 | 0x00000019,0x00000054,0x00000000,0x00040020, |
| 51 | 0x00000055,0x00000009,0x00000006,0x0004002b, | 52 | 0x00000055,0x00000009,0x00000006,0x0004002b, |
| 52 | 0x0000001a,0x0000005e,0x00000001,0x0004002b, | 53 | 0x00000019,0x0000005e,0x00000001,0x0004002b, |
| 53 | 0x0000001a,0x00000069,0x00000002,0x0004002b, | 54 | 0x00000019,0x00000069,0x00000002,0x0004002b, |
| 54 | 0x0000001a,0x00000072,0x00000004,0x0004002b, | 55 | 0x00000019,0x00000072,0x00000004,0x0004002b, |
| 55 | 0x0000001a,0x00000077,0x00000006,0x0004002b, | 56 | 0x00000019,0x00000077,0x00000006,0x0004002b, |
| 56 | 0x0000001a,0x0000007e,0x00000005,0x0004002b, | 57 | 0x00000019,0x0000007e,0x00000005,0x0004002b, |
| 57 | 0x0000001a,0x00000087,0x00000007,0x0004002b, | 58 | 0x00000019,0x00000087,0x00000007,0x0004002b, |
| 58 | 0x0000001a,0x00000099,0x00000003,0x0003001d, | 59 | 0x00000019,0x00000099,0x00000003,0x0003001d, |
| 59 | 0x0000009f,0x00000006,0x0003001e,0x000000a0, | 60 | 0x0000009f,0x00000006,0x0003001e,0x000000a0, |
| 60 | 0x0000009f,0x00040020,0x000000a1,0x0000000c, | 61 | 0x0000009f,0x00040020,0x000000a1,0x0000000c, |
| 61 | 0x000000a0,0x0004003b,0x000000a1,0x000000a2, | 62 | 0x000000a0,0x0004003b,0x000000a1,0x000000a2, |
| @@ -64,43 +65,43 @@ | |||
| 64 | 0x000000a6,0x0000000c,0x000000a5,0x0004003b, | 65 | 0x000000a6,0x0000000c,0x000000a5,0x0004003b, |
| 65 | 0x000000a6,0x000000a7,0x0000000c,0x00040020, | 66 | 0x000000a6,0x000000a7,0x0000000c,0x00040020, |
| 66 | 0x000000a9,0x0000000c,0x00000006,0x0004002b, | 67 | 0x000000a9,0x0000000c,0x00000006,0x0004002b, |
| 67 | 0x00000006,0x000000ba,0x00000008,0x0006002c, | 68 | 0x00000006,0x000000b9,0x00000008,0x0006002c, |
| 68 | 0x00000049,0x000000bb,0x000000ba,0x000000ba, | 69 | 0x00000049,0x000000ba,0x000000b9,0x000000b9, |
| 69 | 0x00000027,0x0004002b,0x0000001a,0x00000109, | 70 | 0x00000026,0x0004002b,0x00000019,0x00000109, |
| 70 | 0x00000050,0x00050036,0x00000002,0x00000004, | 71 | 0x00000050,0x00050036,0x00000002,0x00000004, |
| 71 | 0x00000000,0x00000003,0x000200f8,0x00000005, | 72 | 0x00000000,0x00000003,0x000200f8,0x00000005, |
| 72 | 0x000300f7,0x000000bc,0x00000000,0x000300fb, | 73 | 0x000300f7,0x000000bb,0x00000000,0x000300fb, |
| 73 | 0x00000013,0x000000bd,0x000200f8,0x000000bd, | 74 | 0x00000012,0x000000bc,0x000200f8,0x000000bc, |
| 74 | 0x0004003d,0x00000049,0x0000004e,0x0000004d, | 75 | 0x0004003d,0x00000049,0x0000004e,0x0000004d, |
| 75 | 0x00050051,0x00000006,0x00000050,0x0000004e, | 76 | 0x00050051,0x00000006,0x00000050,0x0000004e, |
| 76 | 0x00000000,0x00050041,0x00000055,0x00000056, | 77 | 0x00000000,0x00050041,0x00000055,0x00000056, |
| 77 | 0x00000053,0x00000054,0x0004003d,0x00000006, | 78 | 0x00000053,0x00000054,0x0004003d,0x00000006, |
| 78 | 0x00000057,0x00000056,0x000500ae,0x00000014, | 79 | 0x00000057,0x00000056,0x000500ae,0x00000013, |
| 79 | 0x00000058,0x00000050,0x00000057,0x000400a8, | 80 | 0x00000058,0x00000050,0x00000057,0x000400a8, |
| 80 | 0x00000014,0x00000059,0x00000058,0x000300f7, | 81 | 0x00000013,0x00000059,0x00000058,0x000300f7, |
| 81 | 0x0000005b,0x00000000,0x000400fa,0x00000059, | 82 | 0x0000005b,0x00000000,0x000400fa,0x00000059, |
| 82 | 0x0000005a,0x0000005b,0x000200f8,0x0000005a, | 83 | 0x0000005a,0x0000005b,0x000200f8,0x0000005a, |
| 83 | 0x00050051,0x00000006,0x0000005d,0x0000004e, | 84 | 0x00050051,0x00000006,0x0000005d,0x0000004e, |
| 84 | 0x00000001,0x00050041,0x00000055,0x0000005f, | 85 | 0x00000001,0x00050041,0x00000055,0x0000005f, |
| 85 | 0x00000053,0x0000005e,0x0004003d,0x00000006, | 86 | 0x00000053,0x0000005e,0x0004003d,0x00000006, |
| 86 | 0x00000060,0x0000005f,0x000500ae,0x00000014, | 87 | 0x00000060,0x0000005f,0x000500ae,0x00000013, |
| 87 | 0x00000061,0x0000005d,0x00000060,0x000200f9, | 88 | 0x00000061,0x0000005d,0x00000060,0x000200f9, |
| 88 | 0x0000005b,0x000200f8,0x0000005b,0x000700f5, | 89 | 0x0000005b,0x000200f8,0x0000005b,0x000700f5, |
| 89 | 0x00000014,0x00000062,0x00000058,0x000000bd, | 90 | 0x00000013,0x00000062,0x00000058,0x000000bc, |
| 90 | 0x00000061,0x0000005a,0x000400a8,0x00000014, | 91 | 0x00000061,0x0000005a,0x000400a8,0x00000013, |
| 91 | 0x00000063,0x00000062,0x000300f7,0x00000065, | 92 | 0x00000063,0x00000062,0x000300f7,0x00000065, |
| 92 | 0x00000000,0x000400fa,0x00000063,0x00000064, | 93 | 0x00000000,0x000400fa,0x00000063,0x00000064, |
| 93 | 0x00000065,0x000200f8,0x00000064,0x00050051, | 94 | 0x00000065,0x000200f8,0x00000064,0x00050051, |
| 94 | 0x00000006,0x00000068,0x0000004e,0x00000002, | 95 | 0x00000006,0x00000068,0x0000004e,0x00000002, |
| 95 | 0x00050041,0x00000055,0x0000006a,0x00000053, | 96 | 0x00050041,0x00000055,0x0000006a,0x00000053, |
| 96 | 0x00000069,0x0004003d,0x00000006,0x0000006b, | 97 | 0x00000069,0x0004003d,0x00000006,0x0000006b, |
| 97 | 0x0000006a,0x000500ae,0x00000014,0x0000006c, | 98 | 0x0000006a,0x000500ae,0x00000013,0x0000006c, |
| 98 | 0x00000068,0x0000006b,0x000200f9,0x00000065, | 99 | 0x00000068,0x0000006b,0x000200f9,0x00000065, |
| 99 | 0x000200f8,0x00000065,0x000700f5,0x00000014, | 100 | 0x000200f8,0x00000065,0x000700f5,0x00000013, |
| 100 | 0x0000006d,0x00000062,0x0000005b,0x0000006c, | 101 | 0x0000006d,0x00000062,0x0000005b,0x0000006c, |
| 101 | 0x00000064,0x000300f7,0x0000006f,0x00000000, | 102 | 0x00000064,0x000300f7,0x0000006f,0x00000000, |
| 102 | 0x000400fa,0x0000006d,0x0000006e,0x0000006f, | 103 | 0x000400fa,0x0000006d,0x0000006e,0x0000006f, |
| 103 | 0x000200f8,0x0000006e,0x000200f9,0x000000bc, | 104 | 0x000200f8,0x0000006e,0x000200f9,0x000000bb, |
| 104 | 0x000200f8,0x0000006f,0x00050041,0x00000055, | 105 | 0x000200f8,0x0000006f,0x00050041,0x00000055, |
| 105 | 0x00000073,0x00000053,0x00000072,0x0004003d, | 106 | 0x00000073,0x00000053,0x00000072,0x0004003d, |
| 106 | 0x00000006,0x00000074,0x00000073,0x00050051, | 107 | 0x00000006,0x00000074,0x00000073,0x00050051, |
| @@ -130,63 +131,63 @@ | |||
| 130 | 0x00000098,0x00000095,0x00000050,0x00050041, | 131 | 0x00000098,0x00000095,0x00000050,0x00050041, |
| 131 | 0x00000055,0x0000009a,0x00000053,0x00000099, | 132 | 0x00000055,0x0000009a,0x00000053,0x00000099, |
| 132 | 0x0004003d,0x00000006,0x0000009b,0x0000009a, | 133 | 0x0004003d,0x00000006,0x0000009b,0x0000009a, |
| 133 | 0x000500ab,0x00000014,0x0000009c,0x0000009b, | 134 | 0x000500ab,0x00000013,0x0000009c,0x0000009b, |
| 134 | 0x00000013,0x000300f7,0x0000009e,0x00000000, | 135 | 0x00000012,0x000300f7,0x0000009e,0x00000000, |
| 135 | 0x000400fa,0x0000009c,0x0000009d,0x000000b1, | 136 | 0x000400fa,0x0000009c,0x0000009d,0x000000b1, |
| 136 | 0x000200f8,0x0000009d,0x00060041,0x000000a9, | 137 | 0x000200f8,0x0000009d,0x00060041,0x000000a9, |
| 137 | 0x000000aa,0x000000a7,0x00000054,0x00000085, | 138 | 0x000000aa,0x000000a7,0x00000054,0x00000085, |
| 138 | 0x0004003d,0x00000006,0x000000ab,0x000000aa, | 139 | 0x0004003d,0x00000006,0x000000ab,0x000000aa, |
| 139 | 0x000500c7,0x00000006,0x000000ac,0x000000ab, | 140 | 0x000500c7,0x00000006,0x000000ac,0x000000ab, |
| 140 | 0x00000040,0x000300f7,0x000000e8,0x00000000, | 141 | 0x0000003f,0x000300f7,0x000000e8,0x00000000, |
| 141 | 0x000300fb,0x00000013,0x000000d2,0x000200f8, | 142 | 0x000300fb,0x00000012,0x000000d2,0x000200f8, |
| 142 | 0x000000d2,0x000500aa,0x00000014,0x000000d4, | 143 | 0x000000d2,0x000500aa,0x00000013,0x000000d4, |
| 143 | 0x000000ac,0x00000013,0x000300f7,0x000000d6, | 144 | 0x000000ac,0x00000012,0x000300f7,0x000000d6, |
| 144 | 0x00000000,0x000400fa,0x000000d4,0x000000d5, | 145 | 0x00000000,0x000400fa,0x000000d4,0x000000d5, |
| 145 | 0x000000d6,0x000200f8,0x000000d5,0x000200f9, | 146 | 0x000000d6,0x000200f8,0x000000d5,0x000200f9, |
| 146 | 0x000000e8,0x000200f8,0x000000d6,0x0006000c, | 147 | 0x000000e8,0x000200f8,0x000000d6,0x0006000c, |
| 147 | 0x0000001a,0x000000d8,0x00000001,0x0000004b, | 148 | 0x00000019,0x000000d8,0x00000001,0x0000004b, |
| 148 | 0x000000ac,0x00050082,0x0000001a,0x000000db, | 149 | 0x000000ac,0x00050082,0x00000019,0x000000db, |
| 149 | 0x00000021,0x000000d8,0x0004007c,0x00000006, | 150 | 0x00000020,0x000000d8,0x0004007c,0x00000006, |
| 150 | 0x000000dc,0x000000db,0x000500c4,0x00000006, | 151 | 0x000000dc,0x000000db,0x000500c4,0x00000006, |
| 151 | 0x000000dd,0x000000ac,0x000000dc,0x00050080, | 152 | 0x000000dd,0x000000ac,0x000000dc,0x00050080, |
| 152 | 0x00000006,0x000000df,0x000000dd,0x00000027, | 153 | 0x00000006,0x000000df,0x000000dd,0x00000026, |
| 153 | 0x00040070,0x00000008,0x000000e0,0x000000df, | 154 | 0x00040070,0x00000008,0x000000e0,0x000000df, |
| 154 | 0x00050080,0x0000001a,0x000000e3,0x000000d8, | 155 | 0x00050080,0x00000019,0x000000e3,0x000000d8, |
| 155 | 0x00000109,0x0004007c,0x00000006,0x000000e4, | 156 | 0x00000109,0x0004007c,0x00000006,0x000000e4, |
| 156 | 0x000000e3,0x000500c4,0x00000006,0x000000e5, | 157 | 0x000000e3,0x000500c4,0x00000006,0x000000e5, |
| 157 | 0x000000e4,0x00000021,0x0004007c,0x00000008, | 158 | 0x000000e4,0x00000020,0x0004007c,0x00000008, |
| 158 | 0x000000e6,0x000000e5,0x00050085,0x00000008, | 159 | 0x000000e6,0x000000e5,0x00050085,0x00000008, |
| 159 | 0x000000e7,0x000000e0,0x000000e6,0x000200f9, | 160 | 0x000000e7,0x000000e0,0x000000e6,0x000200f9, |
| 160 | 0x000000e8,0x000200f8,0x000000e8,0x000700f5, | 161 | 0x000000e8,0x000200f8,0x000000e8,0x000700f5, |
| 161 | 0x00000008,0x00000108,0x00000018,0x000000d5, | 162 | 0x00000008,0x00000108,0x00000017,0x000000d5, |
| 162 | 0x000000e7,0x000000d6,0x0004007c,0x00000006, | 163 | 0x000000e7,0x000000d6,0x0004007c,0x00000006, |
| 163 | 0x000000af,0x00000108,0x00060041,0x000000a9, | 164 | 0x000000af,0x00000108,0x00060041,0x000000a9, |
| 164 | 0x000000b0,0x000000a2,0x00000054,0x00000098, | 165 | 0x000000b0,0x000000a2,0x00000054,0x00000098, |
| 165 | 0x0003003e,0x000000b0,0x000000af,0x000200f9, | 166 | 0x0003003e,0x000000b0,0x000000af,0x000200f9, |
| 166 | 0x0000009e,0x000200f8,0x000000b1,0x00060041, | 167 | 0x0000009e,0x000200f8,0x000000b1,0x00060041, |
| 167 | 0x000000a9,0x000000b4,0x000000a2,0x00000054, | 168 | 0x000000a9,0x000000b5,0x000000a2,0x00000054, |
| 168 | 0x00000098,0x0004003d,0x00000006,0x000000b5, | 169 | 0x00000098,0x0004003d,0x00000006,0x000000b6, |
| 169 | 0x000000b4,0x0004007c,0x00000008,0x000000b6, | ||
| 170 | 0x000000b5,0x000300f7,0x000000fc,0x00000000, | 170 | 0x000000b5,0x000300f7,0x000000fc,0x00000000, |
| 171 | 0x000300fb,0x00000013,0x000000ee,0x000200f8, | 171 | 0x000300fb,0x00000012,0x000000ee,0x000200f8, |
| 172 | 0x000000ee,0x000500bd,0x00000014,0x000000f1, | 172 | 0x000000ee,0x000500ac,0x00000013,0x000000f0, |
| 173 | 0x000000b6,0x00000018,0x000300f7,0x000000f3, | 173 | 0x000000b6,0x00000035,0x000300f7,0x000000f2, |
| 174 | 0x00000000,0x000400fa,0x000000f1,0x000000f2, | 174 | 0x00000000,0x000400fa,0x000000f0,0x000000f1, |
| 175 | 0x000000f3,0x000200f8,0x000000f2,0x000200f9, | 175 | 0x000000f2,0x000200f8,0x000000f1,0x000200f9, |
| 176 | 0x000000fc,0x000200f8,0x000000f3,0x000500be, | 176 | 0x000000fc,0x000200f8,0x000000f2,0x000500ae, |
| 177 | 0x00000014,0x000000f5,0x000000b6,0x0000003c, | 177 | 0x00000013,0x000000f4,0x000000b6,0x0000003b, |
| 178 | 0x000300f7,0x000000f7,0x00000000,0x000400fa, | 178 | 0x000300f7,0x000000f6,0x00000000,0x000400fa, |
| 179 | 0x000000f5,0x000000f6,0x000000f7,0x000200f8, | 179 | 0x000000f4,0x000000f5,0x000000f6,0x000200f8, |
| 180 | 0x000000f6,0x000200f9,0x000000fc,0x000200f8, | 180 | 0x000000f5,0x000200f9,0x000000fc,0x000200f8, |
| 181 | 0x000000f7,0x00050085,0x00000008,0x000000f9, | 181 | 0x000000f6,0x0004007c,0x00000008,0x000000f8, |
| 182 | 0x000000b6,0x00000043,0x0006000c,0x00000008, | 182 | 0x000000b6,0x00050085,0x00000008,0x000000f9, |
| 183 | 0x000000f8,0x00000043,0x0006000c,0x00000008, | ||
| 183 | 0x000000fa,0x00000001,0x00000002,0x000000f9, | 184 | 0x000000fa,0x00000001,0x00000002,0x000000f9, |
| 184 | 0x0004006d,0x00000006,0x000000fb,0x000000fa, | 185 | 0x0004006d,0x00000006,0x000000fb,0x000000fa, |
| 185 | 0x000200f9,0x000000fc,0x000200f8,0x000000fc, | 186 | 0x000200f9,0x000000fc,0x000200f8,0x000000fc, |
| 186 | 0x000900f5,0x00000006,0x00000107,0x00000013, | 187 | 0x000900f5,0x00000006,0x00000107,0x00000012, |
| 187 | 0x000000f2,0x00000040,0x000000f6,0x000000fb, | 188 | 0x000000f1,0x0000003f,0x000000f5,0x000000fb, |
| 188 | 0x000000f7,0x00060041,0x000000a9,0x000000b9, | 189 | 0x000000f6,0x00060041,0x000000a9,0x000000b8, |
| 189 | 0x000000a7,0x00000054,0x00000085,0x0003003e, | 190 | 0x000000a7,0x00000054,0x00000085,0x0003003e, |
| 190 | 0x000000b9,0x00000107,0x000200f9,0x0000009e, | 191 | 0x000000b8,0x00000107,0x000200f9,0x0000009e, |
| 191 | 0x000200f8,0x0000009e,0x000200f9,0x000000bc, | 192 | 0x000200f8,0x0000009e,0x000200f9,0x000000bb, |
| 192 | 0x000200f8,0x000000bc,0x000100fd,0x00010038} | 193 | 0x000200f8,0x000000bb,0x000100fd,0x00010038} |
diff --git a/runtime/src/gfx10_descriptors.h b/runtime/src/gfx10_descriptors.h index 2a5e4533a..ad3605d4e 100644 --- a/runtime/src/gfx10_descriptors.h +++ b/runtime/src/gfx10_descriptors.h | |||
| @@ -556,7 +556,8 @@ inline constexpr VkSamplerReductionMode vulkan_reduction_mode(FilterMode mode) { | |||
| 556 | // MIP_FILTER_NONE samples the base level only, which Vulkan expresses as nearest mip filtering with the LOD held | 556 | // MIP_FILTER_NONE samples the base level only, which Vulkan expresses as nearest mip filtering with the LOD held |
| 557 | // in [0, 0.25] (the Vulkan specification's note on samplers without mipmapping). An unnormalised sampler gets | 557 | // in [0, 0.25] (the Vulkan specification's note on samplers without mipmapping). An unnormalised sampler gets |
| 558 | // what Vulkan requires of one: no mips, no anisotropy, no comparison. | 558 | // what Vulkan requires of one: no mips, no anisotropy, no comparison. |
| 559 | inline VkSamplerCreateInfo vulkan_sampler(const Sampler& sampler) { | 559 | // A decoded GFX10 bias has absolute value at most 32. When creating a device sampler, pass its smaller limit. |
| 560 | inline VkSamplerCreateInfo vulkan_sampler(const Sampler& sampler, float max_lod_bias = 32.0f) { | ||
| 560 | static_assert(int(CompareFunction::never) == int(VK_COMPARE_OP_NEVER) && | 561 | static_assert(int(CompareFunction::never) == int(VK_COMPARE_OP_NEVER) && |
| 561 | int(CompareFunction::less) == int(VK_COMPARE_OP_LESS) && | 562 | int(CompareFunction::less) == int(VK_COMPARE_OP_LESS) && |
| 562 | int(CompareFunction::equal) == int(VK_COMPARE_OP_EQUAL) && | 563 | int(CompareFunction::equal) == int(VK_COMPARE_OP_EQUAL) && |
| @@ -576,7 +577,7 @@ inline VkSamplerCreateInfo vulkan_sampler(const Sampler& sampler) { | |||
| 576 | info.addressModeU = vulkan_address_mode(sampler.address_u); | 577 | info.addressModeU = vulkan_address_mode(sampler.address_u); |
| 577 | info.addressModeV = vulkan_address_mode(sampler.address_v); | 578 | info.addressModeV = vulkan_address_mode(sampler.address_v); |
| 578 | info.addressModeW = vulkan_address_mode(sampler.address_w); | 579 | info.addressModeW = vulkan_address_mode(sampler.address_w); |
| 579 | info.mipLodBias = sampler.lod_bias; | 580 | info.mipLodBias = std::clamp(sampler.lod_bias, -max_lod_bias, max_lod_bias); |
| 580 | info.anisotropyEnable = sampler.max_anisotropy > 1 ? VK_TRUE : VK_FALSE; | 581 | info.anisotropyEnable = sampler.max_anisotropy > 1 ? VK_TRUE : VK_FALSE; |
| 581 | info.maxAnisotropy = float(std::max(sampler.max_anisotropy, 1u)); | 582 | info.maxAnisotropy = float(std::max(sampler.max_anisotropy, 1u)); |
| 582 | info.compareEnable = (sampler.compare_never || sampler.compare != CompareFunction::never) ? VK_TRUE : VK_FALSE; | 583 | info.compareEnable = (sampler.compare_never || sampler.compare != CompareFunction::never) ? VK_TRUE : VK_FALSE; |
| @@ -614,9 +615,11 @@ inline VkSamplerCreateInfo vulkan_sampler(const Sampler& sampler) { | |||
| 614 | 615 | ||
| 615 | // ---- V#: SQ_BUF_RSRC_WORD0..3 ---- | 616 | // ---- V#: SQ_BUF_RSRC_WORD0..3 ---- |
| 616 | 617 | ||
| 617 | // SQ_BUF_RSRC_WORD3.OOB_SELECT: the bounds check the hardware makes. The translator makes its own from the | 618 | // SQ_BUF_RSRC_WORD3.OOB_SELECT: the bounds check the hardware makes, and the one the translator makes too |
| 618 | // stride (tools/rdna2spirv.py, buffer_address): stride 0 checks the byte offset against num_records, otherwise | 619 | // (tools/rdna2spirv.py, buffer_address; docs/design.md, Buffer bounds checking): structured_with_offset is out of |
| 619 | // the index, or the offset against num_records * stride. | 620 | // range at index >= num_records or offset + 4 > stride, structured at index >= num_records, disabled only at |
| 621 | // num_records == 0, raw at offset + 4 > num_records (docs/buffer_bounds.md). A V# built here for a shader to read must say which: the default | ||
| 622 | // below makes every stride-0 access out of range. | ||
| 620 | enum class OobSelect : std::uint32_t { | 623 | enum class OobSelect : std::uint32_t { |
| 621 | structured_with_offset = 0, | 624 | structured_with_offset = 0, |
| 622 | structured = 1, | 625 | structured = 1, |
diff --git a/runtime/src/occlusion_sum.comp b/runtime/src/occlusion_sum.comp new file mode 100644 index 000000000..ade324229 --- /dev/null +++ b/runtime/src/occlusion_sum.comp | |||
| @@ -0,0 +1,19 @@ | |||
| 1 | #version 450 | ||
| 2 | |||
| 3 | layout(local_size_x = 1) in; | ||
| 4 | layout(set = 0, binding = 0, std430) buffer QueryResults { | ||
| 5 | uvec2 total; | ||
| 6 | uvec2 segments[]; | ||
| 7 | }; | ||
| 8 | layout(push_constant) uniform ResolveRange { uint count; }; | ||
| 9 | |||
| 10 | void main() { | ||
| 11 | uvec2 sum = total; | ||
| 12 | for (uint i = 0; i < count; ++i) { | ||
| 13 | uvec2 segment = segments[i]; | ||
| 14 | uint low = sum.x + segment.x; | ||
| 15 | sum.y += segment.y + uint(low < sum.x); | ||
| 16 | sum.x = low; | ||
| 17 | } | ||
| 18 | total = sum; | ||
| 19 | } | ||
diff --git a/runtime/src/occlusion_sum_spirv.h b/runtime/src/occlusion_sum_spirv.h new file mode 100644 index 000000000..54fc938de --- /dev/null +++ b/runtime/src/occlusion_sum_spirv.h | |||
| @@ -0,0 +1,47 @@ | |||
| 1 | #pragma once | ||
| 2 | |||
| 3 | #include <cstdint> | ||
| 4 | |||
| 5 | namespace leonida { | ||
| 6 | |||
| 7 | // From occlusion_sum.comp. Compile with glslangValidator -V --target-env vulkan1.0 -Os -g0, | ||
| 8 | // then encode the little-endian SPIR-V as uint32_t words. No shader compiler is needed at runtime build time. | ||
| 9 | inline constexpr std::uint32_t occlusion_sum_spirv[] = { | ||
| 10 | 0x07230203, 0x00010000, 0x0008000b, 0x00000050, 0x00000000, 0x00020011, 0x00000001, 0x0006000b, | ||
| 11 | 0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001, | ||
| 12 | 0x0005000f, 0x00000005, 0x00000004, 0x6e69616d, 0x00000000, 0x00060010, 0x00000004, 0x00000011, | ||
| 13 | 0x00000001, 0x00000001, 0x00000001, 0x00040047, 0x0000000a, 0x00000006, 0x00000008, 0x00030047, | ||
| 14 | 0x0000000b, 0x00000003, 0x00050048, 0x0000000b, 0x00000000, 0x00000023, 0x00000000, 0x00050048, | ||
| 15 | 0x0000000b, 0x00000001, 0x00000023, 0x00000008, 0x00040047, 0x0000000d, 0x00000021, 0x00000000, | ||
| 16 | 0x00040047, 0x0000000d, 0x00000022, 0x00000000, 0x00030047, 0x0000001c, 0x00000002, 0x00050048, | ||
| 17 | 0x0000001c, 0x00000000, 0x00000023, 0x00000000, 0x00040047, 0x00000043, 0x0000000b, 0x00000019, | ||
| 18 | 0x00020013, 0x00000002, 0x00030021, 0x00000003, 0x00000002, 0x00040015, 0x00000006, 0x00000020, | ||
| 19 | 0x00000000, 0x00040017, 0x00000007, 0x00000006, 0x00000002, 0x0003001d, 0x0000000a, 0x00000007, | ||
| 20 | 0x0004001e, 0x0000000b, 0x00000007, 0x0000000a, 0x00040020, 0x0000000c, 0x00000002, 0x0000000b, | ||
| 21 | 0x0004003b, 0x0000000c, 0x0000000d, 0x00000002, 0x00040015, 0x0000000e, 0x00000020, 0x00000001, | ||
| 22 | 0x0004002b, 0x0000000e, 0x0000000f, 0x00000000, 0x00040020, 0x00000010, 0x00000002, 0x00000007, | ||
| 23 | 0x0004002b, 0x00000006, 0x00000015, 0x00000000, 0x0003001e, 0x0000001c, 0x00000006, 0x00040020, | ||
| 24 | 0x0000001d, 0x00000009, 0x0000001c, 0x0004003b, 0x0000001d, 0x0000001e, 0x00000009, 0x00040020, | ||
| 25 | 0x0000001f, 0x00000009, 0x00000006, 0x00020014, 0x00000022, 0x0004002b, 0x0000000e, 0x00000025, | ||
| 26 | 0x00000001, 0x0004002b, 0x00000006, 0x0000002f, 0x00000001, 0x00040017, 0x00000042, 0x00000006, | ||
| 27 | 0x00000003, 0x0006002c, 0x00000042, 0x00000043, 0x0000002f, 0x0000002f, 0x0000002f, 0x00050036, | ||
| 28 | 0x00000002, 0x00000004, 0x00000000, 0x00000003, 0x000200f8, 0x00000005, 0x00050041, 0x00000010, | ||
| 29 | 0x00000011, 0x0000000d, 0x0000000f, 0x0004003d, 0x00000007, 0x00000012, 0x00000011, 0x000200f9, | ||
| 30 | 0x00000016, 0x000200f8, 0x00000016, 0x000700f5, 0x00000007, 0x0000004e, 0x00000012, 0x00000005, | ||
| 31 | 0x0000004f, 0x00000017, 0x000700f5, 0x00000006, 0x00000044, 0x00000015, 0x00000005, 0x0000003f, | ||
| 32 | 0x00000017, 0x00050041, 0x0000001f, 0x00000020, 0x0000001e, 0x0000000f, 0x0004003d, 0x00000006, | ||
| 33 | 0x00000021, 0x00000020, 0x000500b0, 0x00000022, 0x00000023, 0x00000044, 0x00000021, 0x000400f6, | ||
| 34 | 0x00000018, 0x00000017, 0x00000000, 0x000400fa, 0x00000023, 0x00000017, 0x00000018, 0x000200f8, | ||
| 35 | 0x00000017, 0x00060041, 0x00000010, 0x00000027, 0x0000000d, 0x00000025, 0x00000044, 0x0004003d, | ||
| 36 | 0x00000007, 0x00000028, 0x00000027, 0x00050051, 0x00000006, 0x0000002b, 0x0000004e, 0x00000000, | ||
| 37 | 0x00050051, 0x00000006, 0x0000002d, 0x00000028, 0x00000000, 0x00050080, 0x00000006, 0x0000002e, | ||
| 38 | 0x0000002b, 0x0000002d, 0x00050051, 0x00000006, 0x00000031, 0x00000028, 0x00000001, 0x000500b0, | ||
| 39 | 0x00000022, 0x00000035, 0x0000002e, 0x0000002b, 0x000600a9, 0x00000006, 0x00000036, 0x00000035, | ||
| 40 | 0x0000002f, 0x00000015, 0x00050080, 0x00000006, 0x00000037, 0x00000031, 0x00000036, 0x00050051, | ||
| 41 | 0x00000006, 0x00000039, 0x0000004e, 0x00000001, 0x00050080, 0x00000006, 0x0000003a, 0x00000039, | ||
| 42 | 0x00000037, 0x00050050, 0x00000007, 0x0000004f, 0x0000002e, 0x0000003a, 0x00050080, 0x00000006, | ||
| 43 | 0x0000003f, 0x00000044, 0x00000025, 0x000200f9, 0x00000016, 0x000200f8, 0x00000018, 0x0003003e, | ||
| 44 | 0x00000011, 0x0000004e, 0x000100fd, 0x00010038, | ||
| 45 | }; | ||
| 46 | |||
| 47 | } // namespace leonida | ||
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index ef6fab7a8..15a62d9b4 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp | |||
| @@ -47,6 +47,11 @@ std::string read_string(const std::string& name, uint8_t* base, uint32_t image_s | |||
| 47 | return {s, end}; | 47 | return {s, end}; |
| 48 | } | 48 | } |
| 49 | 49 | ||
| 50 | // PE/COFF: NumberOfRvaAndSizes counts the data directories; entries past it are not directories, whatever they hold. | ||
| 51 | IMAGE_DATA_DIRECTORY directory(const IMAGE_NT_HEADERS64* nt, unsigned index) { | ||
| 52 | return index < nt->OptionalHeader.NumberOfRvaAndSizes ? nt->OptionalHeader.DataDirectory[index] : IMAGE_DATA_DIRECTORY{}; | ||
| 53 | } | ||
| 54 | |||
| 50 | // The TLS directory holds virtual addresses, which relocations have already moved to this mapping. | 55 | // The TLS directory holds virtual addresses, which relocations have already moved to this mapping. |
| 51 | uint64_t rva_in(const Module& m, uint64_t va, const char* what) { | 56 | uint64_t rva_in(const Module& m, uint64_t va, const char* what) { |
| 52 | const uint64_t base = reinterpret_cast<uint64_t>(m.base); | 57 | const uint64_t base = reinterpret_cast<uint64_t>(m.base); |
| @@ -77,9 +82,20 @@ struct TlsHostModule { | |||
| 77 | 82 | ||
| 78 | TlsHostModule load_tls_host() { | 83 | TlsHostModule load_tls_host() { |
| 79 | TlsHostModule host; | 84 | TlsHostModule host; |
| 80 | wchar_t exe[MAX_PATH] = {}; | 85 | // Dynamic buffer loop for paths that exceed MAX_PATH |
| 81 | if (!GetModuleFileNameW(nullptr, exe, MAX_PATH)) return host; | 86 | std::wstring exe_path; |
| 82 | const std::filesystem::path path = std::filesystem::path(exe).parent_path() / L"gta6rt_tls_host.dll"; | 87 | DWORD size = MAX_PATH; |
| 88 | while (true) { | ||
| 89 | exe_path.resize(size); | ||
| 90 | DWORD len = GetModuleFileNameW(nullptr, exe_path.data(), size); | ||
| 91 | if (len == 0) return host; | ||
| 92 | if (len < size - 1) { | ||
| 93 | exe_path.resize(len); | ||
| 94 | break; | ||
| 95 | } | ||
| 96 | size *= 2; | ||
| 97 | } | ||
| 98 | const std::filesystem::path path = std::filesystem::path(exe_path).parent_path() / L"gta6rt_tls_host.dll"; | ||
| 83 | // The helper is linked with the static CRT (/MT), so it needs only system DLLs. Restricting the dependency search | 99 | // The helper is linked with the static CRT (/MT), so it needs only system DLLs. Restricting the dependency search |
| 84 | // to System32 keeps a game-supplied vcruntime next to the executable from being picked up. | 100 | // to System32 keeps a game-supplied vcruntime next to the executable from being picked up. |
| 85 | host.module = LoadLibraryExW(path.c_str(), nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); | 101 | host.module = LoadLibraryExW(path.c_str(), nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); |
| @@ -150,6 +166,26 @@ Loader::Loader(std::filesystem::path game_dir) : game_dir_(std::move(game_dir)) | |||
| 150 | } | 166 | } |
| 151 | 167 | ||
| 152 | Loader::~Loader() { | 168 | Loader::~Loader() { |
| 169 | // Importers must release their resources before their dependencies. Keep every mapping, unwind table and TLS | ||
| 170 | // block alive throughout the notifications: a detach handler can still call an imported function or free an | ||
| 171 | // FLS slot whose destructor lives in another mapped image. | ||
| 172 | for (auto it = init_order_.rbegin(); it != init_order_.rend(); ++it) { | ||
| 173 | Module& m = **it; | ||
| 174 | if (!m.initialised) continue; // a map-only load never opts in to running image code | ||
| 175 | m.initialised = false; | ||
| 176 | try { | ||
| 177 | run_tls_callbacks(m, DLL_PROCESS_DETACH); | ||
| 178 | } catch (const std::exception& e) { | ||
| 179 | // A module may have changed its callback table since attach. A destructor cannot propagate the validation | ||
| 180 | // error; report it and still let DllMain release resources before the image is freed. | ||
| 181 | std::fprintf(stderr, "[rt] TLS process detach failed for %s: %s\n", m.name.c_str(), e.what()); | ||
| 182 | } | ||
| 183 | auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); | ||
| 184 | if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && m.entry_rva) { | ||
| 185 | auto entry = reinterpret_cast<BOOL(NTAPI*)(void*, DWORD, void*)>(m.base + m.entry_rva); | ||
| 186 | entry(m.base, DLL_PROCESS_DETACH, nullptr); // explicit unload; the return value is ignored | ||
| 187 | } | ||
| 188 | } | ||
| 153 | shims::remove_module_lookup(this); | 189 | shims::remove_module_lookup(this); |
| 154 | for (auto* m : order_) { | 190 | for (auto* m : order_) { |
| 155 | // TLS state must go away before the image and its TLS block are unmapped. | 191 | // TLS state must go away before the image and its TLS block are unmapped. |
| @@ -190,8 +226,7 @@ Module& Loader::load(const std::filesystem::path& image) { | |||
| 190 | // allowed. No entry in that set uses the indirect form (UnwindData bit 0). | 226 | // allowed. No entry in that set uses the indirect form (UnwindData bit 0). |
| 191 | void Loader::register_unwind(Module& m) { | 227 | void Loader::register_unwind(Module& m) { |
| 192 | auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); | 228 | auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); |
| 193 | if (nt->OptionalHeader.NumberOfRvaAndSizes <= IMAGE_DIRECTORY_ENTRY_EXCEPTION) return; | 229 | const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_EXCEPTION); |
| 194 | auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION]; | ||
| 195 | // Like the system loader, a trailing partial entry is ignored. | 230 | // Like the system loader, a trailing partial entry is ignored. |
| 196 | const uint32_t count = dir.Size / sizeof(RUNTIME_FUNCTION); | 231 | const uint32_t count = dir.Size / sizeof(RUNTIME_FUNCTION); |
| 197 | if (!count) return; | 232 | if (!count) return; |
| @@ -276,7 +311,7 @@ Module& Loader::map_image(const std::filesystem::path& path) { | |||
| 276 | m->base = static_cast<uint8_t*>( | 311 | m->base = static_cast<uint8_t*>( |
| 277 | VirtualAlloc(reinterpret_cast<void*>(oh.ImageBase), oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); | 312 | VirtualAlloc(reinterpret_cast<void*>(oh.ImageBase), oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); |
| 278 | if (!m->base) { | 313 | if (!m->base) { |
| 279 | auto& relocs = oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC]; | 314 | const auto relocs = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC); |
| 280 | if (!relocs.Size) | 315 | if (!relocs.Size) |
| 281 | throw std::runtime_error(m->name + ": preferred base is taken and the image has no relocations"); | 316 | throw std::runtime_error(m->name + ": preferred base is taken and the image has no relocations"); |
| 282 | m->base = static_cast<uint8_t*>(VirtualAlloc(nullptr, oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); | 317 | m->base = static_cast<uint8_t*>(VirtualAlloc(nullptr, oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); |
| @@ -297,7 +332,7 @@ Module& Loader::map_image(const std::filesystem::path& path) { | |||
| 297 | int64_t delta = reinterpret_cast<int64_t>(m->base) - static_cast<int64_t>(oh.ImageBase); | 332 | int64_t delta = reinterpret_cast<int64_t>(m->base) - static_cast<int64_t>(oh.ImageBase); |
| 298 | if (delta) { | 333 | if (delta) { |
| 299 | m->relocated = true; | 334 | m->relocated = true; |
| 300 | auto& dir = oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC]; | 335 | const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC); |
| 301 | if (!dir.Size) throw std::runtime_error(m->name + ": the image has no relocations and isn't at its base"); | 336 | if (!dir.Size) throw std::runtime_error(m->name + ": the image has no relocations and isn't at its base"); |
| 302 | require_range(m->name, dir.VirtualAddress, dir.Size, m->size, "the relocation table"); | 337 | require_range(m->name, dir.VirtualAddress, dir.Size, m->size, "the relocation table"); |
| 303 | auto* block = at<IMAGE_BASE_RELOCATION>(m->base, dir.VirtualAddress); | 338 | auto* block = at<IMAGE_BASE_RELOCATION>(m->base, dir.VirtualAddress); |
| @@ -455,7 +490,7 @@ void Loader::run_tls_callbacks(Module& m, uint32_t reason) { | |||
| 455 | 490 | ||
| 456 | void Loader::parse_exports(Module& m) { | 491 | void Loader::parse_exports(Module& m) { |
| 457 | auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); | 492 | auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); |
| 458 | auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]; | 493 | const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_EXPORT); |
| 459 | if (!dir.Size) return; | 494 | if (!dir.Size) return; |
| 460 | require_range(m.name, dir.VirtualAddress, sizeof(IMAGE_EXPORT_DIRECTORY), m.size, "the export directory"); | 495 | require_range(m.name, dir.VirtualAddress, sizeof(IMAGE_EXPORT_DIRECTORY), m.size, "the export directory"); |
| 461 | auto* ed = at<IMAGE_EXPORT_DIRECTORY>(m.base, dir.VirtualAddress); | 496 | auto* ed = at<IMAGE_EXPORT_DIRECTORY>(m.base, dir.VirtualAddress); |
| @@ -509,8 +544,9 @@ void* Loader::resolve_forwarder(const std::string& spec, Binding& binding, int d | |||
| 509 | uint32_t ordinal = 0; | 544 | uint32_t ordinal = 0; |
| 510 | if (by_ordinal) { | 545 | if (by_ordinal) { |
| 511 | for (size_t i = 1; i < symbol.size(); ++i) { | 546 | for (size_t i = 1; i < symbol.size(); ++i) { |
| 512 | if (symbol[i] < '0' || symbol[i] > '9' || ordinal > 0xFFFF) return nullptr; | 547 | if (symbol[i] < '0' || symbol[i] > '9') return nullptr; |
| 513 | ordinal = ordinal * 10 + static_cast<uint32_t>(symbol[i] - '0'); | 548 | ordinal = ordinal * 10 + static_cast<uint32_t>(symbol[i] - '0'); |
| 549 | if (ordinal > 0xFFFF) return nullptr; // checked after the digit, so "#65537" can't truncate to 1 | ||
| 514 | } | 550 | } |
| 515 | } | 551 | } |
| 516 | 552 | ||
| @@ -595,7 +631,7 @@ void Loader::bind_imports(Module& m) { | |||
| 595 | } | 631 | } |
| 596 | }; | 632 | }; |
| 597 | 633 | ||
| 598 | auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; | 634 | const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_IMPORT); |
| 599 | if (dir.Size) { | 635 | if (dir.Size) { |
| 600 | for (uint64_t i = 0;; ++i) { | 636 | for (uint64_t i = 0;; ++i) { |
| 601 | uint64_t rva = dir.VirtualAddress + i * sizeof(IMAGE_IMPORT_DESCRIPTOR); | 637 | uint64_t rva = dir.VirtualAddress + i * sizeof(IMAGE_IMPORT_DESCRIPTOR); |
| @@ -608,7 +644,7 @@ void Loader::bind_imports(Module& m) { | |||
| 608 | } | 644 | } |
| 609 | } | 645 | } |
| 610 | // Delay imports are bound eagerly: simpler, and the full import surface shows up in --dry-run. | 646 | // Delay imports are bound eagerly: simpler, and the full import surface shows up in --dry-run. |
| 611 | auto& ddir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT]; | 647 | const auto ddir = directory(nt, IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT); |
| 612 | if (ddir.Size) { | 648 | if (ddir.Size) { |
| 613 | for (uint64_t i = 0;; ++i) { | 649 | for (uint64_t i = 0;; ++i) { |
| 614 | uint64_t rva = ddir.VirtualAddress + i * sizeof(IMAGE_DELAYLOAD_DESCRIPTOR); | 650 | uint64_t rva = ddir.VirtualAddress + i * sizeof(IMAGE_DELAYLOAD_DESCRIPTOR); |
diff --git a/runtime/src/pe_loader.h b/runtime/src/pe_loader.h index ebcf411ec..6d6c94751 100644 --- a/runtime/src/pe_loader.h +++ b/runtime/src/pe_loader.h | |||
| @@ -1,8 +1,8 @@ | |||
| 1 | // Native PE mapper for Xbox Series (x86-64) images. | 1 | // Native PE mapper for Xbox Series (x86-64) images. |
| 2 | // Maps an image, applies relocations, binds every import through the shim registry, registers its unwind table and | 2 | // Maps an image, applies relocations, binds every import through the shim registry, registers its unwind table and |
| 3 | // installs static TLS for the calling thread. | 3 | // installs static TLS for the calling thread. |
| 4 | // Mapping never runs code from the image. Loader::initialise() is the one call that does: it sets up the module's TLS | 4 | // Mapping never runs code from the image. Loader::initialise() delivers process attach to TLS callbacks and DllMain; |
| 5 | // (slot, template and callbacks) and calls a DLL's entry point as DllMain. | 5 | // ~Loader() delivers process detach before unmapping initialised modules. The TLS slot and template are set up by load(). |
| 6 | // gta6rt_tls_host.dll must sit next to the executable; the loader reuses the module TLS index the OS assigns it. | 6 | // gta6rt_tls_host.dll must sit next to the executable; the loader reuses the module TLS index the OS assigns it. |
| 7 | #pragma once | 7 | #pragma once |
| 8 | #include <cstdint> | 8 | #include <cstdint> |
| @@ -65,8 +65,9 @@ public: | |||
| 65 | explicit Loader(std::filesystem::path game_dir); | 65 | explicit Loader(std::filesystem::path game_dir); |
| 66 | Loader(const Loader&) = delete; | 66 | Loader(const Loader&) = delete; |
| 67 | Loader& operator=(const Loader&) = delete; | 67 | Loader& operator=(const Loader&) = delete; |
| 68 | // Restores the TLS slot for the calling thread. Destroy the Loader on the thread | 68 | // Delivers process detach to initialised modules in reverse dependency order before freeing any mappings or TLS. |
| 69 | // that called load() while any mapped TLS module is still live. | 69 | // Restores the TLS slot for the calling thread. Destroy the Loader on the thread that called load() while any |
| 70 | // mapped TLS module is still live; all other threads executing mapped code must have finished first. | ||
| 70 | ~Loader(); | 71 | ~Loader(); |
| 71 | 72 | ||
| 72 | // Loads an image and (recursively) the bundled modules it imports. Throws std::runtime_error on failure. | 73 | // Loads an image and (recursively) the bundled modules it imports. Throws std::runtime_error on failure. |
| @@ -86,7 +87,7 @@ public: | |||
| 86 | void initialise(); | 87 | void initialise(); |
| 87 | 88 | ||
| 88 | // Calls the image's IMAGE_TLS_DIRECTORY64 callbacks in order with (base, reason, nullptr). This is opt-in: | 89 | // Calls the image's IMAGE_TLS_DIRECTORY64 callbacks in order with (base, reason, nullptr). This is opt-in: |
| 89 | // load() never runs image code, and initialise() is the only call inside the Loader that uses it. No-op for | 90 | // load() never runs image code; initialise() and ~Loader() use it for process attach/detach. No-op for |
| 90 | // images without TLS callbacks. The loader does not deliver thread attach/detach events: install the thread's | 91 | // images without TLS callbacks. The loader does not deliver thread attach/detach events: install the thread's |
| 91 | // TLS first, then call this with DLL_THREAD_ATTACH/DETACH, and uninstall after the detach callbacks. | 92 | // TLS first, then call this with DLL_THREAD_ATTACH/DETACH, and uninstall after the detach callbacks. |
| 92 | void run_tls_callbacks(Module& m, uint32_t reason); | 93 | void run_tls_callbacks(Module& m, uint32_t reason); |
diff --git a/runtime/src/predicate_reduce.comp b/runtime/src/predicate_reduce.comp new file mode 100644 index 000000000..86b07d67f --- /dev/null +++ b/runtime/src/predicate_reduce.comp | |||
| @@ -0,0 +1,6 @@ | |||
| 1 | // Synthetic internal shader: one invocation captures a D3D12 64-bit predicate as a Vulkan condition. | ||
| 2 | #version 450 | ||
| 3 | layout(local_size_x=1) in; | ||
| 4 | layout(set=0,binding=0,std430) buffer Words { uint words[]; } data; | ||
| 5 | layout(push_constant) uniform Index { uint base; } index; | ||
| 6 | void main() { data.words[index.base+2] = data.words[index.base] | data.words[index.base+1]; } | ||
diff --git a/runtime/src/predicate_reduce_spv.h b/runtime/src/predicate_reduce_spv.h new file mode 100644 index 000000000..2d703597f --- /dev/null +++ b/runtime/src/predicate_reduce_spv.h | |||
| @@ -0,0 +1,36 @@ | |||
| 1 | // Generated with glslang 16.6.0: | ||
| 2 | // glslang -V --target-env vulkan1.1 -Os --spirv-val predicate_reduce.comp -o predicate_reduce.spv | ||
| 3 | #pragma once | ||
| 4 | #include <cstdint> | ||
| 5 | namespace leonida { | ||
| 6 | inline constexpr std::uint32_t predicate_reduce_spirv[] = { | ||
| 7 | 0x07230203u, 0x00010300u, 0x0008000bu, 0x00000024u, 0x00000000u, 0x00020011u, 0x00000001u, 0x0006000bu, | ||
| 8 | 0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, 0x00000000u, 0x00000001u, | ||
| 9 | 0x0005000fu, 0x00000005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00060010u, 0x00000004u, 0x00000011u, | ||
| 10 | 0x00000001u, 0x00000001u, 0x00000001u, 0x00030003u, 0x00000002u, 0x000001c2u, 0x00040005u, 0x00000004u, | ||
| 11 | 0x6e69616du, 0x00000000u, 0x00040005u, 0x00000008u, 0x64726f57u, 0x00000073u, 0x00050006u, 0x00000008u, | ||
| 12 | 0x00000000u, 0x64726f77u, 0x00000073u, 0x00040005u, 0x0000000au, 0x61746164u, 0x00000000u, 0x00040005u, | ||
| 13 | 0x0000000du, 0x65646e49u, 0x00000078u, 0x00050006u, 0x0000000du, 0x00000000u, 0x65736162u, 0x00000000u, | ||
| 14 | 0x00040005u, 0x0000000fu, 0x65646e69u, 0x00000078u, 0x00040047u, 0x00000007u, 0x00000006u, 0x00000004u, | ||
| 15 | 0x00030047u, 0x00000008u, 0x00000002u, 0x00050048u, 0x00000008u, 0x00000000u, 0x00000023u, 0x00000000u, | ||
| 16 | 0x00040047u, 0x0000000au, 0x00000021u, 0x00000000u, 0x00040047u, 0x0000000au, 0x00000022u, 0x00000000u, | ||
| 17 | 0x00030047u, 0x0000000du, 0x00000002u, 0x00050048u, 0x0000000du, 0x00000000u, 0x00000023u, 0x00000000u, | ||
| 18 | 0x00040047u, 0x00000023u, 0x0000000bu, 0x00000019u, 0x00020013u, 0x00000002u, 0x00030021u, 0x00000003u, | ||
| 19 | 0x00000002u, 0x00040015u, 0x00000006u, 0x00000020u, 0x00000000u, 0x0003001du, 0x00000007u, 0x00000006u, | ||
| 20 | 0x0003001eu, 0x00000008u, 0x00000007u, 0x00040020u, 0x00000009u, 0x0000000cu, 0x00000008u, 0x0004003bu, | ||
| 21 | 0x00000009u, 0x0000000au, 0x0000000cu, 0x00040015u, 0x0000000bu, 0x00000020u, 0x00000001u, 0x0004002bu, | ||
| 22 | 0x0000000bu, 0x0000000cu, 0x00000000u, 0x0003001eu, 0x0000000du, 0x00000006u, 0x00040020u, 0x0000000eu, | ||
| 23 | 0x00000009u, 0x0000000du, 0x0004003bu, 0x0000000eu, 0x0000000fu, 0x00000009u, 0x00040020u, 0x00000010u, | ||
| 24 | 0x00000009u, 0x00000006u, 0x0004002bu, 0x00000006u, 0x00000013u, 0x00000002u, 0x00040020u, 0x00000017u, | ||
| 25 | 0x0000000cu, 0x00000006u, 0x0004002bu, 0x00000006u, 0x0000001cu, 0x00000001u, 0x00040017u, 0x00000022u, | ||
| 26 | 0x00000006u, 0x00000003u, 0x0006002cu, 0x00000022u, 0x00000023u, 0x0000001cu, 0x0000001cu, 0x0000001cu, | ||
| 27 | 0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u, 0x00000003u, 0x000200f8u, 0x00000005u, 0x00050041u, | ||
| 28 | 0x00000010u, 0x00000011u, 0x0000000fu, 0x0000000cu, 0x0004003du, 0x00000006u, 0x00000012u, 0x00000011u, | ||
| 29 | 0x00050080u, 0x00000006u, 0x00000014u, 0x00000012u, 0x00000013u, 0x00060041u, 0x00000017u, 0x00000018u, | ||
| 30 | 0x0000000au, 0x0000000cu, 0x00000012u, 0x0004003du, 0x00000006u, 0x00000019u, 0x00000018u, 0x00050080u, | ||
| 31 | 0x00000006u, 0x0000001du, 0x00000012u, 0x0000001cu, 0x00060041u, 0x00000017u, 0x0000001eu, 0x0000000au, | ||
| 32 | 0x0000000cu, 0x0000001du, 0x0004003du, 0x00000006u, 0x0000001fu, 0x0000001eu, 0x000500c5u, 0x00000006u, | ||
| 33 | 0x00000020u, 0x00000019u, 0x0000001fu, 0x00060041u, 0x00000017u, 0x00000021u, 0x0000000au, 0x0000000cu, | ||
| 34 | 0x00000014u, 0x0003003eu, 0x00000021u, 0x00000020u, 0x000100fdu, 0x00010038u, | ||
| 35 | }; | ||
| 36 | } | ||
diff --git a/runtime/src/predicated_copy.comp b/runtime/src/predicated_copy.comp new file mode 100644 index 000000000..0a105554d --- /dev/null +++ b/runtime/src/predicated_copy.comp | |||
| @@ -0,0 +1,11 @@ | |||
| 1 | // Synthetic byte-granular buffer copy, executed inside the captured conditional-rendering scope. | ||
| 2 | #version 450 | ||
| 3 | #extension GL_EXT_shader_8bit_storage : require | ||
| 4 | layout(local_size_x=64) in; | ||
| 5 | layout(set=0,binding=0,std430) readonly buffer Source { uint8_t bytes[]; } source; | ||
| 6 | layout(set=0,binding=1,std430) buffer Destination { uint8_t bytes[]; } destination; | ||
| 7 | layout(push_constant) uniform Copy { uint source_offset; uint destination_offset; uint size; } copy; | ||
| 8 | void main() { | ||
| 9 | uint i=gl_GlobalInvocationID.x; | ||
| 10 | if(i<copy.size) destination.bytes[copy.destination_offset+i]=source.bytes[copy.source_offset+i]; | ||
| 11 | } | ||
diff --git a/runtime/src/predicated_copy_spv.h b/runtime/src/predicated_copy_spv.h new file mode 100644 index 000000000..3cf9f30fe --- /dev/null +++ b/runtime/src/predicated_copy_spv.h | |||
| @@ -0,0 +1,54 @@ | |||
| 1 | // glslang 16.6.0: glslang -V --target-env vulkan1.2 -Os --spirv-val predicated_copy.comp -o predicated_copy.spv | ||
| 2 | #pragma once | ||
| 3 | #include <cstdint> | ||
| 4 | namespace leonida { inline constexpr std::uint32_t predicated_copy_spirv[] = { | ||
| 5 | 0x07230203u, 0x00010500u, 0x0008000bu, 0x00000037u, 0x00000000u, 0x00020011u, 0x00000001u, 0x00020011u, | ||
| 6 | 0x00001160u, 0x0006000bu, 0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, | ||
| 7 | 0x00000000u, 0x00000001u, 0x0009000fu, 0x00000005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x0000000bu, | ||
| 8 | 0x00000013u, 0x00000021u, 0x0000002bu, 0x00060010u, 0x00000004u, 0x00000011u, 0x00000040u, 0x00000001u, | ||
| 9 | 0x00000001u, 0x00030003u, 0x00000002u, 0x000001c2u, 0x00080004u, 0x455f4c47u, 0x735f5458u, 0x65646168u, | ||
| 10 | 0x62385f72u, 0x735f7469u, 0x61726f74u, 0x00006567u, 0x00040005u, 0x00000004u, 0x6e69616du, 0x00000000u, | ||
| 11 | 0x00080005u, 0x0000000bu, 0x475f6c67u, 0x61626f6cu, 0x766e496cu, 0x7461636fu, 0x496e6f69u, 0x00000044u, | ||
| 12 | 0x00040005u, 0x00000011u, 0x79706f43u, 0x00000000u, 0x00070006u, 0x00000011u, 0x00000000u, 0x72756f73u, | ||
| 13 | 0x6f5f6563u, 0x65736666u, 0x00000074u, 0x00080006u, 0x00000011u, 0x00000001u, 0x74736564u, 0x74616e69u, | ||
| 14 | 0x5f6e6f69u, 0x7366666fu, 0x00007465u, 0x00050006u, 0x00000011u, 0x00000002u, 0x657a6973u, 0x00000000u, | ||
| 15 | 0x00040005u, 0x00000013u, 0x79706f63u, 0x00000000u, 0x00050005u, 0x0000001fu, 0x74736544u, 0x74616e69u, | ||
| 16 | 0x006e6f69u, 0x00050006u, 0x0000001fu, 0x00000000u, 0x65747962u, 0x00000073u, 0x00050005u, 0x00000021u, | ||
| 17 | 0x74736564u, 0x74616e69u, 0x006e6f69u, 0x00040005u, 0x00000029u, 0x72756f53u, 0x00006563u, 0x00050006u, | ||
| 18 | 0x00000029u, 0x00000000u, 0x65747962u, 0x00000073u, 0x00040005u, 0x0000002bu, 0x72756f73u, 0x00006563u, | ||
| 19 | 0x00040047u, 0x0000000bu, 0x0000000bu, 0x0000001cu, 0x00030047u, 0x00000011u, 0x00000002u, 0x00050048u, | ||
| 20 | 0x00000011u, 0x00000000u, 0x00000023u, 0x00000000u, 0x00050048u, 0x00000011u, 0x00000001u, 0x00000023u, | ||
| 21 | 0x00000004u, 0x00050048u, 0x00000011u, 0x00000002u, 0x00000023u, 0x00000008u, 0x00040047u, 0x0000001eu, | ||
| 22 | 0x00000006u, 0x00000001u, 0x00030047u, 0x0000001fu, 0x00000002u, 0x00050048u, 0x0000001fu, 0x00000000u, | ||
| 23 | 0x00000023u, 0x00000000u, 0x00040047u, 0x00000021u, 0x00000021u, 0x00000001u, 0x00040047u, 0x00000021u, | ||
| 24 | 0x00000022u, 0x00000000u, 0x00040047u, 0x00000028u, 0x00000006u, 0x00000001u, 0x00030047u, 0x00000029u, | ||
| 25 | 0x00000002u, 0x00040048u, 0x00000029u, 0x00000000u, 0x00000018u, 0x00050048u, 0x00000029u, 0x00000000u, | ||
| 26 | 0x00000023u, 0x00000000u, 0x00030047u, 0x0000002bu, 0x00000018u, 0x00040047u, 0x0000002bu, 0x00000021u, | ||
| 27 | 0x00000000u, 0x00040047u, 0x0000002bu, 0x00000022u, 0x00000000u, 0x00040047u, 0x00000036u, 0x0000000bu, | ||
| 28 | 0x00000019u, 0x00020013u, 0x00000002u, 0x00030021u, 0x00000003u, 0x00000002u, 0x00040015u, 0x00000006u, | ||
| 29 | 0x00000020u, 0x00000000u, 0x00040017u, 0x00000009u, 0x00000006u, 0x00000003u, 0x00040020u, 0x0000000au, | ||
| 30 | 0x00000001u, 0x00000009u, 0x0004003bu, 0x0000000au, 0x0000000bu, 0x00000001u, 0x0004002bu, 0x00000006u, | ||
| 31 | 0x0000000cu, 0x00000000u, 0x00040020u, 0x0000000du, 0x00000001u, 0x00000006u, 0x0005001eu, 0x00000011u, | ||
| 32 | 0x00000006u, 0x00000006u, 0x00000006u, 0x00040020u, 0x00000012u, 0x00000009u, 0x00000011u, 0x0004003bu, | ||
| 33 | 0x00000012u, 0x00000013u, 0x00000009u, 0x00040015u, 0x00000014u, 0x00000020u, 0x00000001u, 0x0004002bu, | ||
| 34 | 0x00000014u, 0x00000015u, 0x00000002u, 0x00040020u, 0x00000016u, 0x00000009u, 0x00000006u, 0x00020014u, | ||
| 35 | 0x00000019u, 0x00040015u, 0x0000001du, 0x00000008u, 0x00000000u, 0x0003001du, 0x0000001eu, 0x0000001du, | ||
| 36 | 0x0003001eu, 0x0000001fu, 0x0000001eu, 0x00040020u, 0x00000020u, 0x0000000cu, 0x0000001fu, 0x0004003bu, | ||
| 37 | 0x00000020u, 0x00000021u, 0x0000000cu, 0x0004002bu, 0x00000014u, 0x00000022u, 0x00000000u, 0x0004002bu, | ||
| 38 | 0x00000014u, 0x00000023u, 0x00000001u, 0x0003001du, 0x00000028u, 0x0000001du, 0x0003001eu, 0x00000029u, | ||
| 39 | 0x00000028u, 0x00040020u, 0x0000002au, 0x0000000cu, 0x00000029u, 0x0004003bu, 0x0000002au, 0x0000002bu, | ||
| 40 | 0x0000000cu, 0x00040020u, 0x00000030u, 0x0000000cu, 0x0000001du, 0x0004002bu, 0x00000006u, 0x00000034u, | ||
| 41 | 0x00000040u, 0x0004002bu, 0x00000006u, 0x00000035u, 0x00000001u, 0x0006002cu, 0x00000009u, 0x00000036u, | ||
| 42 | 0x00000034u, 0x00000035u, 0x00000035u, 0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u, 0x00000003u, | ||
| 43 | 0x000200f8u, 0x00000005u, 0x00050041u, 0x0000000du, 0x0000000eu, 0x0000000bu, 0x0000000cu, 0x0004003du, | ||
| 44 | 0x00000006u, 0x0000000fu, 0x0000000eu, 0x00050041u, 0x00000016u, 0x00000017u, 0x00000013u, 0x00000015u, | ||
| 45 | 0x0004003du, 0x00000006u, 0x00000018u, 0x00000017u, 0x000500b0u, 0x00000019u, 0x0000001au, 0x0000000fu, | ||
| 46 | 0x00000018u, 0x000300f7u, 0x0000001cu, 0x00000000u, 0x000400fau, 0x0000001au, 0x0000001bu, 0x0000001cu, | ||
| 47 | 0x000200f8u, 0x0000001bu, 0x00050041u, 0x00000016u, 0x00000024u, 0x00000013u, 0x00000023u, 0x0004003du, | ||
| 48 | 0x00000006u, 0x00000025u, 0x00000024u, 0x00050080u, 0x00000006u, 0x00000027u, 0x00000025u, 0x0000000fu, | ||
| 49 | 0x00050041u, 0x00000016u, 0x0000002cu, 0x00000013u, 0x00000022u, 0x0004003du, 0x00000006u, 0x0000002du, | ||
| 50 | 0x0000002cu, 0x00050080u, 0x00000006u, 0x0000002fu, 0x0000002du, 0x0000000fu, 0x00060041u, 0x00000030u, | ||
| 51 | 0x00000031u, 0x0000002bu, 0x00000022u, 0x0000002fu, 0x0004003du, 0x0000001du, 0x00000032u, 0x00000031u, | ||
| 52 | 0x00060041u, 0x00000030u, 0x00000033u, 0x00000021u, 0x00000022u, 0x00000027u, 0x0003003eu, 0x00000033u, | ||
| 53 | 0x00000032u, 0x000200f9u, 0x0000001cu, 0x000200f8u, 0x0000001cu, 0x000100fdu, 0x00010038u, | ||
| 54 | }; } | ||
diff --git a/runtime/src/resource_tiling.h b/runtime/src/resource_tiling.h index 3a472d872..6bd890ae8 100644 --- a/runtime/src/resource_tiling.h +++ b/runtime/src/resource_tiling.h | |||
| @@ -76,6 +76,20 @@ constexpr TileShape element_tile_shape(bool volume, std::uint32_t element_bytes) | |||
| 76 | } | 76 | } |
| 77 | } | 77 | } |
| 78 | 78 | ||
| 79 | // The 4 KiB tile shape in elements the PC runtime counts to allow D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT (16 of | ||
| 80 | // them must cover a texture's top mip), or {} as above. Measured with GetResourceAllocationInfo on an RTX 5070 and | ||
| 81 | // WARP (d3d12_vulkan_device_test). | ||
| 82 | constexpr TileShape small_tile_shape(bool volume, std::uint32_t element_bytes) { | ||
| 83 | switch (element_bytes) { | ||
| 84 | case 1: return volume ? TileShape{16, 16, 16} : TileShape{64, 64, 1}; | ||
| 85 | case 2: return volume ? TileShape{16, 16, 8} : TileShape{64, 32, 1}; | ||
| 86 | case 4: return volume ? TileShape{16, 8, 8} : TileShape{32, 32, 1}; | ||
| 87 | case 8: return volume ? TileShape{8, 8, 8} : TileShape{32, 16, 1}; | ||
| 88 | case 16: return volume ? TileShape{8, 8, 4} : TileShape{16, 16, 1}; | ||
| 89 | default: return {}; | ||
| 90 | } | ||
| 91 | } | ||
| 92 | |||
| 79 | // False when the resource cannot be tiled: an untileable element size, no mips, or more than 2^32 tiles. | 93 | // False when the resource cannot be tiled: an untileable element size, no mips, or more than 2^32 tiles. |
| 80 | inline bool resource_tiling(const TilingDesc& desc, ResourceTiling& out) { | 94 | inline bool resource_tiling(const TilingDesc& desc, ResourceTiling& out) { |
| 81 | out = {}; | 95 | out = {}; |
diff --git a/runtime/src/uav_clear.h b/runtime/src/uav_clear.h index 73ec54dea..a27da8d7a 100644 --- a/runtime/src/uav_clear.h +++ b/runtime/src/uav_clear.h | |||
| @@ -8,10 +8,13 @@ | |||
| 8 | // and ...Float, which the D3D12 methods keep): | 8 | // and ...Float, which the D3D12 methods keep): |
| 9 | // - Uint copies the low n bits of value i into channel i, where n is the channel's width, with no conversion, | 9 | // - Uint copies the low n bits of value i into channel i, where n is the channel's width, with no conversion, |
| 10 | // whatever the format's type: 0x3f800000 into an R32_FLOAT channel is 1.0, 0xff into an R8_UNORM one is 1.0. | 10 | // whatever the format's type: 0x3f800000 into an R32_FLOAT channel is 1.0, 0xff into an R8_UNORM one is 1.0. |
| 11 | // A raw or structured buffer view takes value 0 for every 32-bit word. | 11 | // A raw or structured buffer view takes value 0 for every 32-bit word. R9G9B9E5_SHAREDEXP has no independent |
| 12 | // per-channel integer bit layout and WARP clears it to 0 for any uint input. | ||
| 12 | // - Float converts to the format: UNORM and SNORM clamp to [0, 1] / [-1, 1] and round to nearest (NaN is 0); | 13 | // - Float converts to the format: UNORM and SNORM clamp to [0, 1] / [-1, 1] and round to nearest (NaN is 0); |
| 13 | // 16-bit and the packed 11/10-bit floats round toward zero, a finite value too large becoming the largest finite | 14 | // 16-bit and the packed 11/10-bit floats round toward zero, a finite value too large becoming the largest finite |
| 14 | // (D3D11.3 3.2.2; WARP and NVIDIA agree), and the small floats have no sign: negative is 0. | 15 | // (D3D11.3 3.2.2; WARP and NVIDIA agree), and the small floats have no sign: negative is 0. |
| 16 | // R9G9B9E5_SHAREDEXP clamps negative/NaN to 0 and +Inf/overflow to 65408.0, shares the largest channel's | ||
| 17 | // exponent and rounds mantissas half-up (bumping the exponent on 512), matching WARP. | ||
| 15 | // D3D11 calls Float on an integer view invalid and D3D12 does not say; here the value is converted to the | 18 | // D3D11 calls Float on an integer view invalid and D3D12 does not say; here the value is converted to the |
| 16 | // integer (rounded toward zero, clamped, NaN is 0) so the result is defined. A raw or structured buffer view | 19 | // integer (rounded toward zero, clamped, NaN is 0) so the result is defined. A raw or structured buffer view |
| 17 | // takes value 0's bits. | 20 | // takes value 0's bits. |
| @@ -35,7 +38,7 @@ | |||
| 35 | 38 | ||
| 36 | namespace leonida::uav_clear { | 39 | namespace leonida::uav_clear { |
| 37 | 40 | ||
| 38 | enum class Kind : std::uint8_t { unorm, snorm, uint, sint, sfloat, ufloat }; | 41 | enum class Kind : std::uint8_t { unorm, snorm, uint, sint, sfloat, ufloat, shared_exp }; |
| 39 | 42 | ||
| 40 | // One channel: where its bits are in the element (little-endian, from bit 0 of byte 0) and how many. | 43 | // One channel: where its bits are in the element (little-endian, from bit 0 of byte 0) and how many. |
| 41 | struct Channel { | 44 | struct Channel { |
| @@ -66,6 +69,7 @@ inline constexpr Layout layouts[] = { | |||
| 66 | {VK_FORMAT_A2B10G10R10_UNORM_PACK32, Kind::unorm, 4, {{{0, 10}, {10, 10}, {20, 10}, {30, 2}}}}, | 69 | {VK_FORMAT_A2B10G10R10_UNORM_PACK32, Kind::unorm, 4, {{{0, 10}, {10, 10}, {20, 10}, {30, 2}}}}, |
| 67 | {VK_FORMAT_A2B10G10R10_UINT_PACK32, Kind::uint, 4, {{{0, 10}, {10, 10}, {20, 10}, {30, 2}}}}, | 70 | {VK_FORMAT_A2B10G10R10_UINT_PACK32, Kind::uint, 4, {{{0, 10}, {10, 10}, {20, 10}, {30, 2}}}}, |
| 68 | {VK_FORMAT_B10G11R11_UFLOAT_PACK32, Kind::ufloat, 4, {{{0, 11}, {11, 11}, {22, 10}, {}}}}, | 71 | {VK_FORMAT_B10G11R11_UFLOAT_PACK32, Kind::ufloat, 4, {{{0, 11}, {11, 11}, {22, 10}, {}}}}, |
| 72 | {VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, Kind::shared_exp, 4, {{{0, 9}, {9, 9}, {18, 9}, {27, 5}}}}, | ||
| 69 | {VK_FORMAT_R8G8B8A8_UNORM, Kind::unorm, 4, {{{0, 8}, {8, 8}, {16, 8}, {24, 8}}}}, | 73 | {VK_FORMAT_R8G8B8A8_UNORM, Kind::unorm, 4, {{{0, 8}, {8, 8}, {16, 8}, {24, 8}}}}, |
| 70 | {VK_FORMAT_R8G8B8A8_SNORM, Kind::snorm, 4, {{{0, 8}, {8, 8}, {16, 8}, {24, 8}}}}, | 74 | {VK_FORMAT_R8G8B8A8_SNORM, Kind::snorm, 4, {{{0, 8}, {8, 8}, {16, 8}, {24, 8}}}}, |
| 71 | {VK_FORMAT_R8G8B8A8_UINT, Kind::uint, 4, {{{0, 8}, {8, 8}, {16, 8}, {24, 8}}}}, | 75 | {VK_FORMAT_R8G8B8A8_UINT, Kind::uint, 4, {{{0, 8}, {8, 8}, {16, 8}, {24, 8}}}}, |
| @@ -184,6 +188,33 @@ inline std::uint32_t to_integer(float value, bool is_signed, unsigned bits) { | |||
| 184 | return std::uint32_t(std::clamp(std::trunc(double(value)), 0.0, std::ldexp(1.0, int(bits)) - 1)); | 188 | return std::uint32_t(std::clamp(std::trunc(double(value)), 0.0, std::ldexp(1.0, int(bits)) - 1)); |
| 185 | } | 189 | } |
| 186 | 190 | ||
| 191 | // Shared-exponent 9:9:9:5 unsigned float (EXT_texture_shared_exponent / D3D11.3). | ||
| 192 | // Clamps negative and NaN to 0 and overflow/+Inf to 65408.0 ((511/512) * 2^16), shares the largest channel's | ||
| 193 | // exponent, rounds mantissas half-up (floor(c / denom + 0.5)), and bumps the exponent if the largest mantissa | ||
| 194 | // rounds to 512. Matches ClearUnorderedAccessViewFloat on WARP. | ||
| 195 | inline std::uint32_t to_rgb9e5(float r, float g, float b) { | ||
| 196 | constexpr float max_value = 65408.0f; | ||
| 197 | const auto clamp_channel = [](float v) { return !(v > 0.0f) ? 0.0f : (v > max_value ? max_value : v); }; | ||
| 198 | r = clamp_channel(r); | ||
| 199 | g = clamp_channel(g); | ||
| 200 | b = clamp_channel(b); | ||
| 201 | const float max_c = std::max(r, std::max(g, b)); | ||
| 202 | if (max_c == 0.0f) return 0u; | ||
| 203 | int exp_raw = 0; | ||
| 204 | std::frexp(max_c, &exp_raw); // floor(log2(max_c)) == exp_raw - 1 | ||
| 205 | int exp_shared = std::max(0, exp_raw + 15); | ||
| 206 | double denom = std::ldexp(1.0, exp_shared - 24); // 2^(exp_shared - 15 - 9) | ||
| 207 | const int max_m = static_cast<int>(std::floor(double(max_c) / denom + 0.5)); | ||
| 208 | if (max_m == 512) { | ||
| 209 | ++exp_shared; | ||
| 210 | denom *= 2.0; | ||
| 211 | } | ||
| 212 | const auto rm = static_cast<std::uint32_t>(std::floor(double(r) / denom + 0.5)); | ||
| 213 | const auto gm = static_cast<std::uint32_t>(std::floor(double(g) / denom + 0.5)); | ||
| 214 | const auto bm = static_cast<std::uint32_t>(std::floor(double(b) / denom + 0.5)); | ||
| 215 | return rm | (gm << 9) | (bm << 18) | (static_cast<std::uint32_t>(exp_shared) << 27); | ||
| 216 | } | ||
| 217 | |||
| 187 | } // namespace detail | 218 | } // namespace detail |
| 188 | 219 | ||
| 189 | // The element a clear writes into a view of `format`. `values` are the call's four UINTs, or the bits of its four | 220 | // The element a clear writes into a view of `format`. `values` are the call's four UINTs, or the bits of its four |
| @@ -193,6 +224,14 @@ inline bool encode(VkFormat format, bool is_float, const std::array<std::uint32_ | |||
| 193 | if (!l) return false; | 224 | if (!l) return false; |
| 194 | out = {}; | 225 | out = {}; |
| 195 | out.size = l->bytes; | 226 | out.size = l->bytes; |
| 227 | if (l->kind == Kind::shared_exp) { | ||
| 228 | const std::uint32_t word = is_float ? detail::to_rgb9e5(std::bit_cast<float>(values[0]), | ||
| 229 | std::bit_cast<float>(values[1]), | ||
| 230 | std::bit_cast<float>(values[2])) | ||
| 231 | : 0u; | ||
| 232 | std::memcpy(out.bytes.data(), &word, 4); | ||
| 233 | return true; | ||
| 234 | } | ||
| 196 | for (unsigned i = 0; i < 4; ++i) { | 235 | for (unsigned i = 0; i < 4; ++i) { |
| 197 | const Channel c = l->rgba[i]; | 236 | const Channel c = l->rgba[i]; |
| 198 | if (!c.bits) continue; | 237 | if (!c.bits) continue; |
| @@ -215,6 +254,7 @@ inline bool encode(VkFormat format, bool is_float, const std::array<std::uint32_ | |||
| 215 | case Kind::sint: detail::put(out, c, detail::to_integer(v, true, c.bits)); break; | 254 | case Kind::sint: detail::put(out, c, detail::to_integer(v, true, c.bits)); break; |
| 216 | case Kind::sfloat: | 255 | case Kind::sfloat: |
| 217 | case Kind::ufloat: detail::put(out, c, detail::to_float_bits(v, *l, c.bits)); break; | 256 | case Kind::ufloat: detail::put(out, c, detail::to_float_bits(v, *l, c.bits)); break; |
| 257 | case Kind::shared_exp: break; | ||
| 218 | } | 258 | } |
| 219 | } | 259 | } |
| 220 | return true; | 260 | return true; |
| @@ -226,6 +266,16 @@ inline bool decode(VkFormat format, const Element& element, VkClearColorValue& o | |||
| 226 | const Layout* l = layout(format); | 266 | const Layout* l = layout(format); |
| 227 | if (!l || l->bytes != element.size) return false; | 267 | if (!l || l->bytes != element.size) return false; |
| 228 | out = {}; | 268 | out = {}; |
| 269 | if (l->kind == Kind::shared_exp) { | ||
| 270 | std::uint32_t word = 0; | ||
| 271 | std::memcpy(&word, element.bytes.data(), 4); | ||
| 272 | const float scale = std::ldexp(1.0f, static_cast<int>(word >> 27) - 24); | ||
| 273 | out.float32[0] = float(word & 0x1ffu) * scale; | ||
| 274 | out.float32[1] = float((word >> 9) & 0x1ffu) * scale; | ||
| 275 | out.float32[2] = float((word >> 18) & 0x1ffu) * scale; | ||
| 276 | out.float32[3] = 1.0f; | ||
| 277 | return true; | ||
| 278 | } | ||
| 229 | for (unsigned i = 0; i < 4; ++i) { | 279 | for (unsigned i = 0; i < 4; ++i) { |
| 230 | const Channel c = l->rgba[i]; | 280 | const Channel c = l->rgba[i]; |
| 231 | if (!c.bits) continue; | 281 | if (!c.bits) continue; |
| @@ -246,6 +296,7 @@ inline bool decode(VkFormat format, const Element& element, VkClearColorValue& o | |||
| 246 | } | 296 | } |
| 247 | case Kind::sfloat: | 297 | case Kind::sfloat: |
| 248 | case Kind::ufloat: out.float32[i] = detail::from_float_bits(raw, *l, c.bits); break; | 298 | case Kind::ufloat: out.float32[i] = detail::from_float_bits(raw, *l, c.bits); break; |
| 299 | case Kind::shared_exp: break; | ||
| 249 | } | 300 | } |
| 250 | } | 301 | } |
| 251 | return true; | 302 | return true; |
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index d8b129a3d..8a222c86f 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h | |||
| @@ -9,16 +9,23 @@ | |||
| 9 | #define VK_NO_PROTOTYPES | 9 | #define VK_NO_PROTOTYPES |
| 10 | #endif | 10 | #endif |
| 11 | #include "binary_occlusion_spirv.h" | 11 | #include "binary_occlusion_spirv.h" |
| 12 | #include "occlusion_sum_spirv.h" | ||
| 12 | #include "vulkan_depth24.h" | 13 | #include "vulkan_depth24.h" |
| 13 | #include "vulkan_replay.h" | 14 | #include "vulkan_replay.h" |
| 14 | 15 | ||
| 16 | #include <algorithm> | ||
| 17 | #include <atomic> | ||
| 18 | #include <condition_variable> | ||
| 15 | #include <cstdint> | 19 | #include <cstdint> |
| 16 | #include <cstdio> | 20 | #include <cstdio> |
| 21 | #include <cstring> | ||
| 17 | #include <functional> | 22 | #include <functional> |
| 18 | #include <map> | 23 | #include <map> |
| 19 | #include <memory> | 24 | #include <memory> |
| 20 | #include <mutex> | 25 | #include <mutex> |
| 26 | #include <shared_mutex> | ||
| 21 | #include <span> | 27 | #include <span> |
| 28 | #include <thread> | ||
| 22 | #include <tuple> | 29 | #include <tuple> |
| 23 | #include <unordered_map> | 30 | #include <unordered_map> |
| 24 | #include <vector> | 31 | #include <vector> |
| @@ -67,7 +74,7 @@ struct VulkanDeviceFunctions { | |||
| 67 | 74 | ||
| 68 | // The Vulkan 1.3 entry points may be null on older devices, the extension ones (conditional rendering) when the | 75 | // The Vulkan 1.3 entry points may be null on older devices, the extension ones (conditional rendering) when the |
| 69 | // extension is not enabled, and the query functions are optional (a list that uses queries without them is | 76 | // extension is not enabled, and the query functions are optional (a list that uses queries without them is |
| 70 | // unsupported). The compute and descriptor functions are needed only for binary occlusion resolves. | 77 | // unsupported). The compute and descriptor functions are needed for normalized or summed occlusion results. |
| 71 | bool load(PFN_vkGetDeviceProcAddr get, VkDevice device) { | 78 | bool load(PFN_vkGetDeviceProcAddr get, VkDevice device) { |
| 72 | #define LEONIDA_VK_LOAD(name) name = reinterpret_cast<PFN_##name>(get(device, #name)); | 79 | #define LEONIDA_VK_LOAD(name) name = reinterpret_cast<PFN_##name>(get(device, #name)); |
| 73 | LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_LOAD) | 80 | LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_LOAD) |
| @@ -85,16 +92,17 @@ struct VulkanDeviceFunctions { | |||
| 85 | } | 92 | } |
| 86 | }; | 93 | }; |
| 87 | 94 | ||
| 88 | // The scratch buffer belongs to one queue. Each chunk copies raw results into it, normalizes them in place, | 95 | // Both kinds of compute resolve use the same storage buffer, descriptor set and pipeline layout. |
| 89 | // then transfers UINT64s to the application buffer, which needs no storage-buffer usage. | 96 | // The destination needs transfer usage only. Pipelines are created on first use. |
| 90 | class BinaryOcclusionResolve { | 97 | class OcclusionResolve { |
| 91 | public: | 98 | public: |
| 92 | BinaryOcclusionResolve(const VulkanDeviceFunctions& vk, VkDevice device) : vk_(vk), device_(device) {} | 99 | OcclusionResolve(const VulkanDeviceFunctions& vk, VkDevice device) : vk_(vk), device_(device) {} |
| 93 | BinaryOcclusionResolve(const BinaryOcclusionResolve&) = delete; | 100 | OcclusionResolve(const OcclusionResolve&) = delete; |
| 94 | BinaryOcclusionResolve& operator=(const BinaryOcclusionResolve&) = delete; | 101 | OcclusionResolve& operator=(const OcclusionResolve&) = delete; |
| 95 | 102 | ||
| 96 | ~BinaryOcclusionResolve() { | 103 | ~OcclusionResolve() { |
| 97 | if (pipeline_) vk_.vkDestroyPipeline(device_, pipeline_, nullptr); | 104 | if (sum_pipeline_) vk_.vkDestroyPipeline(device_, sum_pipeline_, nullptr); |
| 105 | if (binary_pipeline_) vk_.vkDestroyPipeline(device_, binary_pipeline_, nullptr); | ||
| 98 | if (layout_) vk_.vkDestroyPipelineLayout(device_, layout_, nullptr); | 106 | if (layout_) vk_.vkDestroyPipelineLayout(device_, layout_, nullptr); |
| 99 | if (pool_) vk_.vkDestroyDescriptorPool(device_, pool_, nullptr); | 107 | if (pool_) vk_.vkDestroyDescriptorPool(device_, pool_, nullptr); |
| 100 | if (set_layout_) vk_.vkDestroyDescriptorSetLayout(device_, set_layout_, nullptr); | 108 | if (set_layout_) vk_.vkDestroyDescriptorSetLayout(device_, set_layout_, nullptr); |
| @@ -166,65 +174,112 @@ public: | |||
| 166 | layout.pSetLayouts = &set_layout_; | 174 | layout.pSetLayouts = &set_layout_; |
| 167 | layout.pushConstantRangeCount = 1; | 175 | layout.pushConstantRangeCount = 1; |
| 168 | layout.pPushConstantRanges = &count; | 176 | layout.pPushConstantRanges = &count; |
| 169 | if (vk_.vkCreatePipelineLayout(device_, &layout, nullptr, &layout_) != VK_SUCCESS) return false; | 177 | return vk_.vkCreatePipelineLayout(device_, &layout, nullptr, &layout_) == VK_SUCCESS; |
| 178 | } | ||
| 179 | |||
| 180 | bool prepare(bool needs_sum, bool needs_binary) { | ||
| 181 | return (!needs_sum || sum_pipeline_ || create_pipeline(occlusion_sum_spirv, sum_pipeline_)) && | ||
| 182 | (!needs_binary || binary_pipeline_ || create_pipeline(binary_occlusion_spirv, binary_pipeline_)); | ||
| 183 | } | ||
| 184 | |||
| 185 | void sum(VkCommandBuffer cb, VkQueryPool queries, std::uint32_t first, std::uint32_t count, | ||
| 186 | VkBuffer dst, VkDeviceSize offset) const { | ||
| 187 | begin_scratch_write(cb); | ||
| 188 | vk_.vkCmdFillBuffer(cb, scratch_, 0, word_size, 0); | ||
| 189 | bind(cb, sum_pipeline_); | ||
| 190 | while (count) { | ||
| 191 | const auto chunk = std::min(count, sum_capacity); | ||
| 192 | vk_.vkCmdCopyQueryPoolResults(cb, queries, first, chunk, scratch_, word_size, word_size, | ||
| 193 | VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); | ||
| 194 | barrier(cb, transfer | compute, compute, VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT, | ||
| 195 | shader_access); | ||
| 196 | dispatch(cb, chunk, 1); | ||
| 197 | first += chunk; | ||
| 198 | count -= chunk; | ||
| 199 | if (count) barrier(cb, compute, transfer, shader_access, VK_ACCESS_TRANSFER_WRITE_BIT); | ||
| 200 | } | ||
| 201 | copy_result(cb, dst, offset, word_size); | ||
| 202 | } | ||
| 203 | |||
| 204 | void normalize(VkCommandBuffer cb, VkQueryPool queries, std::uint32_t first, std::uint32_t count, | ||
| 205 | VkBuffer dst, VkDeviceSize offset) const { | ||
| 206 | bind(cb, binary_pipeline_); | ||
| 207 | while (count) { | ||
| 208 | const auto chunk = std::min(count, binary_capacity); | ||
| 209 | const VkDeviceSize bytes = VkDeviceSize(chunk) * word_size; | ||
| 210 | begin_scratch_write(cb); | ||
| 211 | vk_.vkCmdCopyQueryPoolResults(cb, queries, first, chunk, scratch_, 0, word_size, | ||
| 212 | VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); | ||
| 213 | barrier(cb, transfer, compute, VK_ACCESS_TRANSFER_WRITE_BIT, shader_access); | ||
| 214 | dispatch(cb, chunk, (chunk + binary_group_size - 1) / binary_group_size); | ||
| 215 | copy_result(cb, dst, offset, bytes); | ||
| 216 | first += chunk; | ||
| 217 | count -= chunk; | ||
| 218 | offset += bytes; | ||
| 219 | } | ||
| 220 | } | ||
| 221 | |||
| 222 | private: | ||
| 223 | bool create_pipeline(std::span<const std::uint32_t> code, VkPipeline& out) const { | ||
| 170 | VkShaderModuleCreateInfo module{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; | 224 | VkShaderModuleCreateInfo module{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; |
| 171 | module.codeSize = sizeof(binary_occlusion_spirv); | 225 | module.codeSize = code.size_bytes(); |
| 172 | module.pCode = binary_occlusion_spirv; | 226 | module.pCode = code.data(); |
| 173 | VkShaderModule shader = VK_NULL_HANDLE; | 227 | VkShaderModule shader = VK_NULL_HANDLE; |
| 174 | if (vk_.vkCreateShaderModule(device_, &module, nullptr, &shader) != VK_SUCCESS) return false; | 228 | if (vk_.vkCreateShaderModule(device_, &module, nullptr, &shader) != VK_SUCCESS) return false; |
| 175 | VkComputePipelineCreateInfo pipeline{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; | 229 | VkComputePipelineCreateInfo pipeline{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; |
| 176 | pipeline.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, nullptr, 0, | 230 | pipeline.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, nullptr, 0, |
| 177 | VK_SHADER_STAGE_COMPUTE_BIT, shader, "main", nullptr}; | 231 | VK_SHADER_STAGE_COMPUTE_BIT, shader, "main", nullptr}; |
| 178 | pipeline.layout = layout_; | 232 | pipeline.layout = layout_; |
| 179 | const VkResult result = vk_.vkCreateComputePipelines(device_, VK_NULL_HANDLE, 1, &pipeline, nullptr, &pipeline_); | 233 | VkPipeline handle = VK_NULL_HANDLE; |
| 234 | const VkResult result = vk_.vkCreateComputePipelines(device_, VK_NULL_HANDLE, 1, &pipeline, nullptr, &handle); | ||
| 180 | vk_.vkDestroyShaderModule(device_, shader, nullptr); | 235 | vk_.vkDestroyShaderModule(device_, shader, nullptr); |
| 236 | if (result == VK_SUCCESS) out = handle; | ||
| 237 | else if (handle) vk_.vkDestroyPipeline(device_, handle, nullptr); | ||
| 181 | return result == VK_SUCCESS; | 238 | return result == VK_SUCCESS; |
| 182 | } | 239 | } |
| 183 | 240 | ||
| 184 | void record(VkCommandBuffer cb, VkQueryPool queries, std::uint32_t first, std::uint32_t count, | 241 | void bind(VkCommandBuffer cb, VkPipeline pipeline) const { |
| 185 | VkBuffer dst, VkDeviceSize offset) const { | 242 | vk_.vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline); |
| 186 | constexpr auto transfer = VK_PIPELINE_STAGE_TRANSFER_BIT; | ||
| 187 | constexpr auto compute = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; | ||
| 188 | vk_.vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_); | ||
| 189 | vk_.vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, layout_, 0, 1, &set_, 0, nullptr); | 243 | vk_.vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, layout_, 0, 1, &set_, 0, nullptr); |
| 190 | while (count) { | ||
| 191 | const std::uint32_t chunk = std::min(count, scratch_count); | ||
| 192 | const VkDeviceSize bytes = VkDeviceSize(chunk) * result_size; | ||
| 193 | // Reuse is ordered even across submissions on this queue. Each previous copy has read the scratch | ||
| 194 | // words before the query pool can write them again. | ||
| 195 | scratch_barrier(cb, transfer, transfer, VK_ACCESS_TRANSFER_READ_BIT, VK_ACCESS_TRANSFER_WRITE_BIT); | ||
| 196 | vk_.vkCmdCopyQueryPoolResults(cb, queries, first, chunk, scratch_, 0, result_size, | ||
| 197 | VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); | ||
| 198 | scratch_barrier(cb, transfer, compute, VK_ACCESS_TRANSFER_WRITE_BIT, | ||
| 199 | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT); | ||
| 200 | vk_.vkCmdPushConstants(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(chunk), &chunk); | ||
| 201 | vk_.vkCmdDispatch(cb, (chunk + group_size - 1) / group_size, 1, 1); | ||
| 202 | scratch_barrier(cb, compute, transfer, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT); | ||
| 203 | const VkBufferCopy copy{0, offset, bytes}; | ||
| 204 | vk_.vkCmdCopyBuffer(cb, scratch_, dst, 1, ©); | ||
| 205 | first += chunk; | ||
| 206 | count -= chunk; | ||
| 207 | offset += bytes; | ||
| 208 | } | ||
| 209 | } | 244 | } |
| 210 | 245 | ||
| 211 | private: | 246 | void dispatch(VkCommandBuffer cb, std::uint32_t chunk, std::uint32_t groups) const { |
| 212 | void scratch_barrier(VkCommandBuffer cb, VkPipelineStageFlags src, VkPipelineStageFlags dst, | 247 | vk_.vkCmdPushConstants(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(chunk), &chunk); |
| 213 | VkAccessFlags src_access, VkAccessFlags dst_access) const { | 248 | vk_.vkCmdDispatch(cb, groups, 1, 1); |
| 214 | VkBufferMemoryBarrier barrier{VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER}; | 249 | } |
| 215 | barrier.srcAccessMask = src_access; | 250 | |
| 216 | barrier.dstAccessMask = dst_access; | 251 | void begin_scratch_write(VkCommandBuffer cb) const { |
| 217 | barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; | 252 | // A sum or a normalization in an earlier submission may still use this buffer. |
| 218 | barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; | 253 | barrier(cb, transfer | compute, transfer, |
| 219 | barrier.buffer = scratch_; | 254 | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | shader_access, |
| 220 | barrier.size = scratch_size; | 255 | VK_ACCESS_TRANSFER_WRITE_BIT); |
| 221 | vk_.vkCmdPipelineBarrier(cb, src, dst, 0, 0, nullptr, 1, &barrier, 0, nullptr); | 256 | } |
| 222 | } | 257 | |
| 223 | 258 | void copy_result(VkCommandBuffer cb, VkBuffer dst, VkDeviceSize offset, VkDeviceSize bytes) const { | |
| 224 | static constexpr std::uint32_t scratch_count = 1024; | 259 | barrier(cb, compute, transfer, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT); |
| 225 | static constexpr std::uint32_t group_size = 64; // local_size_x in binary_occlusion.comp | 260 | const VkBufferCopy copy{0, offset, bytes}; |
| 226 | static constexpr VkDeviceSize result_size = sizeof(std::uint64_t); | 261 | vk_.vkCmdCopyBuffer(cb, scratch_, dst, 1, ©); |
| 227 | static constexpr VkDeviceSize scratch_size = scratch_count * result_size; | 262 | } |
| 263 | |||
| 264 | void barrier(VkCommandBuffer cb, VkPipelineStageFlags src, VkPipelineStageFlags dst, | ||
| 265 | VkAccessFlags before, VkAccessFlags after) const { | ||
| 266 | VkBufferMemoryBarrier memory{VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER}; | ||
| 267 | memory.srcAccessMask = before; | ||
| 268 | memory.dstAccessMask = after; | ||
| 269 | memory.srcQueueFamilyIndex = memory.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; | ||
| 270 | memory.buffer = scratch_; | ||
| 271 | memory.size = scratch_size; | ||
| 272 | vk_.vkCmdPipelineBarrier(cb, src, dst, 0, 0, nullptr, 1, &memory, 0, nullptr); | ||
| 273 | } | ||
| 274 | |||
| 275 | static constexpr auto transfer = VK_PIPELINE_STAGE_TRANSFER_BIT; | ||
| 276 | static constexpr auto compute = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; | ||
| 277 | static constexpr VkAccessFlags shader_access = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; | ||
| 278 | static constexpr std::uint32_t sum_capacity = 256; // one more word holds the running sum | ||
| 279 | static constexpr std::uint32_t binary_capacity = 1024; | ||
| 280 | static constexpr std::uint32_t binary_group_size = 64; // local_size_x in binary_occlusion.comp | ||
| 281 | static constexpr VkDeviceSize word_size = sizeof(std::uint64_t); | ||
| 282 | static constexpr VkDeviceSize scratch_size = std::max(sum_capacity + 1, binary_capacity) * word_size; | ||
| 228 | const VulkanDeviceFunctions& vk_; | 283 | const VulkanDeviceFunctions& vk_; |
| 229 | VkDevice device_; | 284 | VkDevice device_; |
| 230 | VkBuffer scratch_ = VK_NULL_HANDLE; | 285 | VkBuffer scratch_ = VK_NULL_HANDLE; |
| @@ -233,10 +288,316 @@ private: | |||
| 233 | VkDescriptorPool pool_ = VK_NULL_HANDLE; | 288 | VkDescriptorPool pool_ = VK_NULL_HANDLE; |
| 234 | VkDescriptorSet set_ = VK_NULL_HANDLE; | 289 | VkDescriptorSet set_ = VK_NULL_HANDLE; |
| 235 | VkPipelineLayout layout_ = VK_NULL_HANDLE; | 290 | VkPipelineLayout layout_ = VK_NULL_HANDLE; |
| 236 | VkPipeline pipeline_ = VK_NULL_HANDLE; | 291 | VkPipeline sum_pipeline_ = VK_NULL_HANDLE; |
| 292 | VkPipeline binary_pipeline_ = VK_NULL_HANDLE; | ||
| 293 | }; | ||
| 294 | |||
| 295 | // Zero-allocation O(1) Ring Buffer deferred deletion queue tied to the device timeline semaphore. | ||
| 296 | class DeferredDeletionQueue { | ||
| 297 | public: | ||
| 298 | enum class Kind : std::uint8_t { | ||
| 299 | bindless_slot, | ||
| 300 | image_view, | ||
| 301 | image, | ||
| 302 | buffer, | ||
| 303 | device_memory, | ||
| 304 | acceleration_structure, | ||
| 305 | }; | ||
| 306 | |||
| 307 | struct Item { | ||
| 308 | std::uint64_t ticket = 0; | ||
| 309 | std::uint64_t handle = 0; // for bindless_slot: (uint64_t(dimension) << 32) | index | ||
| 310 | Kind kind = Kind::image_view; | ||
| 311 | }; | ||
| 312 | |||
| 313 | using BindlessReleaseFn = void (*)(void* user, std::uint32_t dimension, std::uint32_t index); | ||
| 314 | |||
| 315 | explicit DeferredDeletionQueue(std::size_t initial_capacity = 256) : pending_(next_pow2(initial_capacity)) {} | ||
| 316 | |||
| 317 | void set_bindless_release(BindlessReleaseFn fn, void* user) { | ||
| 318 | std::lock_guard lock(mutex_); | ||
| 319 | bindless_release_fn_ = fn; | ||
| 320 | bindless_release_user_ = user; | ||
| 321 | } | ||
| 322 | |||
| 323 | void push(std::uint64_t retire_ticket, Kind kind, std::uint64_t handle) { | ||
| 324 | if (!handle && kind != Kind::bindless_slot) return; | ||
| 325 | std::lock_guard lock(mutex_); | ||
| 326 | if (count_ == pending_.size()) { | ||
| 327 | const std::size_t old_cap = pending_.size(); | ||
| 328 | std::vector<Item> grown(old_cap * 2); | ||
| 329 | const std::size_t first = old_cap - head_; | ||
| 330 | std::memcpy(grown.data(), pending_.data() + head_, first * sizeof(Item)); | ||
| 331 | if (head_ > 0) std::memcpy(grown.data() + first, pending_.data(), head_ * sizeof(Item)); | ||
| 332 | pending_ = std::move(grown); | ||
| 333 | head_ = 0; | ||
| 334 | tail_ = count_; | ||
| 335 | } | ||
| 336 | pending_[tail_] = {retire_ticket, handle, kind}; | ||
| 337 | tail_ = (tail_ + 1) & (pending_.size() - 1); | ||
| 338 | ++count_; | ||
| 339 | } | ||
| 340 | |||
| 341 | // Drains all items with ticket <= current_ticket in O(k), invoking vkDestroy* outside the lock. | ||
| 342 | // Uses a stack-local batch vector so concurrent drain() calls from multiple queues never race. | ||
| 343 | void drain(std::uint64_t current_ticket, VkDevice device, const VulkanDeviceFunctions& vk) { | ||
| 344 | BindlessReleaseFn release_fn = nullptr; | ||
| 345 | void* release_user = nullptr; | ||
| 346 | std::vector<Item> to_destroy; | ||
| 347 | { | ||
| 348 | std::lock_guard lock(mutex_); | ||
| 349 | if (count_ == 0 || pending_[head_].ticket > current_ticket) return; | ||
| 350 | release_fn = bindless_release_fn_; | ||
| 351 | release_user = bindless_release_user_; | ||
| 352 | const std::size_t mask = pending_.size() - 1; | ||
| 353 | while (count_ > 0 && pending_[head_].ticket <= current_ticket) { | ||
| 354 | to_destroy.push_back(pending_[head_]); | ||
| 355 | head_ = (head_ + 1) & mask; | ||
| 356 | --count_; | ||
| 357 | } | ||
| 358 | if (count_ == 0) { | ||
| 359 | head_ = 0; | ||
| 360 | tail_ = 0; | ||
| 361 | } | ||
| 362 | } | ||
| 363 | |||
| 364 | for (const Item& item : to_destroy) { | ||
| 365 | switch (item.kind) { | ||
| 366 | case Kind::bindless_slot: | ||
| 367 | if (release_fn) { | ||
| 368 | release_fn(release_user, static_cast<std::uint32_t>(item.handle >> 32), | ||
| 369 | static_cast<std::uint32_t>(item.handle & 0xFFFFFFFFu)); | ||
| 370 | } | ||
| 371 | break; | ||
| 372 | case Kind::image_view: | ||
| 373 | vk.vkDestroyImageView(device, reinterpret_cast<VkImageView>(item.handle), nullptr); | ||
| 374 | break; | ||
| 375 | case Kind::image: | ||
| 376 | vk.vkDestroyImage(device, reinterpret_cast<VkImage>(item.handle), nullptr); | ||
| 377 | break; | ||
| 378 | case Kind::buffer: | ||
| 379 | vk.vkDestroyBuffer(device, reinterpret_cast<VkBuffer>(item.handle), nullptr); | ||
| 380 | break; | ||
| 381 | case Kind::device_memory: | ||
| 382 | vk.vkFreeMemory(device, reinterpret_cast<VkDeviceMemory>(item.handle), nullptr); | ||
| 383 | break; | ||
| 384 | case Kind::acceleration_structure: | ||
| 385 | if (vk.vkDestroyAccelerationStructureKHR) | ||
| 386 | vk.vkDestroyAccelerationStructureKHR( | ||
| 387 | device, reinterpret_cast<VkAccelerationStructureKHR>(item.handle), nullptr); | ||
| 388 | break; | ||
| 389 | } | ||
| 390 | } | ||
| 391 | } | ||
| 392 | |||
| 393 | private: | ||
| 394 | static std::size_t next_pow2(std::size_t n) { | ||
| 395 | std::size_t p = 16; | ||
| 396 | while (p < n) p <<= 1; | ||
| 397 | return p; | ||
| 398 | } | ||
| 399 | |||
| 400 | std::mutex mutex_; | ||
| 401 | std::vector<Item> pending_; | ||
| 402 | std::size_t head_ = 0; | ||
| 403 | std::size_t tail_ = 0; | ||
| 404 | std::size_t count_ = 0; | ||
| 405 | BindlessReleaseFn bindless_release_fn_ = nullptr; | ||
| 406 | void* bindless_release_user_ = nullptr; | ||
| 407 | }; | ||
| 408 | |||
| 409 | // Centralized single-thread fence dispatcher using Vulkan 1.2 vkWaitSemaphores(VK_SEMAPHORE_WAIT_ANY_BIT). | ||
| 410 | // Eliminates per-fence OS threads and 10ms polling: a synthetic timeline semaphore (wakeup_sem_) at index 0 | ||
| 411 | // wakes vkWaitSemaphores immediately whenever a new wait, a released fence, or shutdown arrives while waiting_ == true. | ||
| 412 | class FenceWaitDispatcher { | ||
| 413 | public: | ||
| 414 | struct Entry { | ||
| 415 | VkSemaphore semaphore = VK_NULL_HANDLE; | ||
| 416 | std::uint64_t value = 0; | ||
| 417 | void* event_handle = nullptr; | ||
| 418 | std::function<void()> callback; | ||
| 419 | }; | ||
| 420 | |||
| 421 | using SignalEventFn = void (*)(void* event_handle); | ||
| 422 | |||
| 423 | FenceWaitDispatcher(VkDevice device, const VulkanDeviceFunctions& vk, std::atomic<bool>& device_lost) | ||
| 424 | : device_(device), vk_(vk), device_lost_(device_lost) { | ||
| 425 | VkSemaphoreTypeCreateInfo type{VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO}; | ||
| 426 | type.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE; | ||
| 427 | type.initialValue = 0; | ||
| 428 | VkSemaphoreCreateInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, &type}; | ||
| 429 | if (vk_.vkCreateSemaphore(device_, &info, nullptr, &wakeup_sem_) != VK_SUCCESS) | ||
| 430 | wakeup_sem_ = VK_NULL_HANDLE; | ||
| 431 | semaphores_.reserve(64); | ||
| 432 | values_.reserve(64); | ||
| 433 | } | ||
| 434 | |||
| 435 | ~FenceWaitDispatcher() { | ||
| 436 | stop(); | ||
| 437 | if (wakeup_sem_) vk_.vkDestroySemaphore(device_, wakeup_sem_, nullptr); | ||
| 438 | } | ||
| 439 | |||
| 440 | FenceWaitDispatcher(const FenceWaitDispatcher&) = delete; | ||
| 441 | FenceWaitDispatcher& operator=(const FenceWaitDispatcher&) = delete; | ||
| 442 | |||
| 443 | void set_signal_event_fn(SignalEventFn fn) { | ||
| 444 | std::lock_guard lock(mutex_); | ||
| 445 | signal_event_ = fn; | ||
| 446 | } | ||
| 447 | |||
| 448 | void enqueue(VkSemaphore sem, std::uint64_t value, void* event_handle) { | ||
| 449 | if (!sem || !event_handle) return; | ||
| 450 | if (device_lost_.load(std::memory_order_acquire)) { | ||
| 451 | SignalEventFn fn = nullptr; | ||
| 452 | { | ||
| 453 | std::lock_guard lock(mutex_); | ||
| 454 | fn = signal_event_; | ||
| 455 | } | ||
| 456 | if (fn) fn(event_handle); | ||
| 457 | return; | ||
| 458 | } | ||
| 459 | { | ||
| 460 | std::lock_guard lock(mutex_); | ||
| 461 | pending_.push_back({sem, value, event_handle, {}}); | ||
| 462 | if (!thread_.joinable() && wakeup_sem_) thread_ = std::thread([this] { run(); }); | ||
| 463 | signal_wakeup_locked(); | ||
| 464 | } | ||
| 465 | cv_.notify_one(); | ||
| 466 | } | ||
| 467 | |||
| 468 | void enqueue_callback(VkSemaphore sem, std::uint64_t value, std::function<void()> cb) { | ||
| 469 | if (!sem || !cb) return; | ||
| 470 | if (device_lost_.load(std::memory_order_acquire)) { | ||
| 471 | cb(); | ||
| 472 | return; | ||
| 473 | } | ||
| 474 | { | ||
| 475 | std::lock_guard lock(mutex_); | ||
| 476 | pending_.push_back({sem, value, nullptr, std::move(cb)}); | ||
| 477 | if (!thread_.joinable() && wakeup_sem_) thread_ = std::thread([this] { run(); }); | ||
| 478 | signal_wakeup_locked(); | ||
| 479 | } | ||
| 480 | cv_.notify_one(); | ||
| 481 | } | ||
| 482 | |||
| 483 | // Completes the pending waits for `sem` (a released D3D12 fence counts as reached, as on the PC runtime) and | ||
| 484 | // blocks until any in-flight vkWaitSemaphores releases `sem` before the caller destroys the VkSemaphore. | ||
| 485 | void cancel(VkSemaphore sem) { | ||
| 486 | if (!sem) return; | ||
| 487 | std::unique_lock lock(mutex_); | ||
| 488 | std::erase_if(pending_, [this, sem](const Entry& e) { | ||
| 489 | if (e.semaphore != sem) return false; | ||
| 490 | if (e.callback) e.callback(); | ||
| 491 | else if (signal_event_ && e.event_handle) signal_event_(e.event_handle); | ||
| 492 | return true; | ||
| 493 | }); | ||
| 494 | if (!thread_.joinable()) return; | ||
| 495 | if (waiting_) { | ||
| 496 | const std::uint64_t target_epoch = epoch_ + 1; | ||
| 497 | signal_wakeup_locked(); | ||
| 498 | epoch_cv_.wait(lock, [this, target_epoch] { return !waiting_ || epoch_ >= target_epoch; }); | ||
| 499 | } | ||
| 500 | } | ||
| 501 | |||
| 502 | void stop() { | ||
| 503 | { | ||
| 504 | std::lock_guard lock(mutex_); | ||
| 505 | if (stop_) return; | ||
| 506 | stop_ = true; | ||
| 507 | signal_wakeup_locked(); | ||
| 508 | } | ||
| 509 | cv_.notify_all(); | ||
| 510 | if (thread_.joinable()) thread_.join(); | ||
| 511 | } | ||
| 512 | |||
| 513 | private: | ||
| 514 | // Only signals wakeup_sem_ when run() is actively waiting (waiting_ == true) on wakeup_val_ + 1, | ||
| 515 | // eliminating any lost-wakeup race between snapshot construction and vkWaitSemaphores. | ||
| 516 | void signal_wakeup_locked() { | ||
| 517 | if (!waiting_ || !wakeup_sem_ || device_lost_.load(std::memory_order_relaxed)) return; | ||
| 518 | const std::uint64_t next = ++wakeup_val_; | ||
| 519 | VkSemaphoreSignalInfo si{VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO}; | ||
| 520 | si.semaphore = wakeup_sem_; | ||
| 521 | si.value = next; | ||
| 522 | vk_.vkSignalSemaphore(device_, &si); | ||
| 523 | } | ||
| 524 | |||
| 525 | void run() { | ||
| 526 | std::unique_lock lock(mutex_); | ||
| 527 | while (true) { | ||
| 528 | cv_.wait(lock, [this] { return stop_ || !pending_.empty(); }); | ||
| 529 | if (stop_) return; | ||
| 530 | |||
| 531 | semaphores_.clear(); | ||
| 532 | values_.clear(); | ||
| 533 | semaphores_.push_back(wakeup_sem_); | ||
| 534 | values_.push_back(wakeup_val_ + 1); | ||
| 535 | for (const Entry& e : pending_) { | ||
| 536 | semaphores_.push_back(e.semaphore); | ||
| 537 | values_.push_back(e.value); | ||
| 538 | } | ||
| 539 | |||
| 540 | waiting_ = true; | ||
| 541 | lock.unlock(); | ||
| 542 | |||
| 543 | VkSemaphoreWaitInfo wi{VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO}; | ||
| 544 | wi.flags = VK_SEMAPHORE_WAIT_ANY_BIT; | ||
| 545 | wi.semaphoreCount = static_cast<std::uint32_t>(semaphores_.size()); | ||
| 546 | wi.pSemaphores = semaphores_.data(); | ||
| 547 | wi.pValues = values_.data(); | ||
| 548 | const VkResult res = vk_.vkWaitSemaphores(device_, &wi, UINT64_MAX); | ||
| 549 | |||
| 550 | lock.lock(); | ||
| 551 | waiting_ = false; | ||
| 552 | ++epoch_; | ||
| 553 | epoch_cv_.notify_all(); | ||
| 554 | |||
| 555 | if (res == VK_ERROR_DEVICE_LOST) { | ||
| 556 | device_lost_.store(true, std::memory_order_release); | ||
| 557 | for (const Entry& e : pending_) { | ||
| 558 | if (e.callback) e.callback(); | ||
| 559 | else if (signal_event_ && e.event_handle) signal_event_(e.event_handle); | ||
| 560 | } | ||
| 561 | pending_.clear(); | ||
| 562 | return; | ||
| 563 | } | ||
| 564 | if (stop_) return; | ||
| 565 | |||
| 566 | std::erase_if(pending_, [this](const Entry& e) { | ||
| 567 | std::uint64_t done = 0; | ||
| 568 | if (vk_.vkGetSemaphoreCounterValue(device_, e.semaphore, &done) != VK_SUCCESS) return false; | ||
| 569 | if (done < e.value) return false; | ||
| 570 | if (e.callback) e.callback(); | ||
| 571 | else if (signal_event_ && e.event_handle) signal_event_(e.event_handle); | ||
| 572 | return true; | ||
| 573 | }); | ||
| 574 | } | ||
| 575 | } | ||
| 576 | |||
| 577 | VkDevice device_; | ||
| 578 | const VulkanDeviceFunctions& vk_; | ||
| 579 | std::atomic<bool>& device_lost_; | ||
| 580 | SignalEventFn signal_event_ = nullptr; | ||
| 581 | VkSemaphore wakeup_sem_ = VK_NULL_HANDLE; | ||
| 582 | std::uint64_t wakeup_val_ = 0; | ||
| 583 | |||
| 584 | std::mutex mutex_; | ||
| 585 | std::condition_variable cv_; | ||
| 586 | std::condition_variable epoch_cv_; | ||
| 587 | std::vector<Entry> pending_; | ||
| 588 | std::vector<VkSemaphore> semaphores_; | ||
| 589 | std::vector<std::uint64_t> values_; | ||
| 590 | std::uint64_t epoch_ = 0; | ||
| 591 | bool waiting_ = false; | ||
| 592 | bool stop_ = false; | ||
| 593 | std::thread thread_; | ||
| 237 | }; | 594 | }; |
| 238 | 595 | ||
| 239 | // Per device: what the queues share. Resources are registered by their stable ID (the COM resource pointer). | 596 | // Per device: what the queues share. Resources are registered by their stable ID (the COM resource pointer). |
| 597 | #ifdef _MSC_VER | ||
| 598 | #pragma warning(push) | ||
| 599 | #pragma warning(disable : 4324) // intentional alignas(64) cache-line padding to prevent false sharing | ||
| 600 | #endif | ||
| 240 | class VulkanContext { | 601 | class VulkanContext { |
| 241 | public: | 602 | public: |
| 242 | // conditional_rendering: VK_EXT_conditional_rendering is enabled on `device` (SetPredication). | 603 | // conditional_rendering: VK_EXT_conditional_rendering is enabled on `device` (SetPredication). |
| @@ -299,16 +660,39 @@ public: | |||
| 299 | return it == query_pools_.end() ? nullptr : &it->second; | 660 | return it == query_pools_.end() ? nullptr : &it->second; |
| 300 | }; | 661 | }; |
| 301 | replay_.separate_depth_stencil_layouts = separate_depth_stencil_layouts; | 662 | replay_.separate_depth_stencil_layouts = separate_depth_stencil_layouts; |
| 663 | if (loaded_) { | ||
| 664 | VkSemaphoreTypeCreateInfo type{VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO}; | ||
| 665 | type.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE; | ||
| 666 | type.initialValue = 0; | ||
| 667 | VkSemaphoreCreateInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, &type}; | ||
| 668 | if (vk.vkCreateSemaphore(device_, &info, nullptr, &retire_timeline_) != VK_SUCCESS) | ||
| 669 | retire_timeline_ = VK_NULL_HANDLE; | ||
| 670 | fence_dispatcher_ = std::make_unique<FenceWaitDispatcher>(device_, vk, device_lost_); | ||
| 671 | } | ||
| 302 | } | 672 | } |
| 303 | 673 | ||
| 304 | ~VulkanContext() { | 674 | ~VulkanContext() { |
| 675 | fence_dispatcher_.reset(); | ||
| 676 | deletion_queue_.drain(UINT64_MAX, device_, vk); | ||
| 305 | for (const auto& [key, view] : views_) vk.vkDestroyImageView(device_, view, nullptr); | 677 | for (const auto& [key, view] : views_) vk.vkDestroyImageView(device_, view, nullptr); |
| 678 | if (retire_timeline_) vk.vkDestroySemaphore(device_, retire_timeline_, nullptr); | ||
| 306 | } | 679 | } |
| 307 | 680 | ||
| 308 | VulkanContext(const VulkanContext&) = delete; | 681 | VulkanContext(const VulkanContext&) = delete; |
| 309 | VulkanContext& operator=(const VulkanContext&) = delete; | 682 | VulkanContext& operator=(const VulkanContext&) = delete; |
| 310 | 683 | ||
| 311 | bool loaded() const { return loaded_; } | 684 | bool loaded() const { return loaded_; } |
| 685 | void configure_predication(PFN_vkGetDeviceProcAddr get, const VkPhysicalDeviceMemoryProperties& memory, | ||
| 686 | VkDeviceSize max_range, std::uint32_t family) { | ||
| 687 | std::unique_lock lock(resource_mutex_); | ||
| 688 | predicate_family_ = family; | ||
| 689 | predicate_reducer_ = std::make_unique<PredicateReducer>(get, device_, memory, max_range); | ||
| 690 | } | ||
| 691 | // Configure before submitting work, only when storageBuffer8BitAccess is enabled on the device. | ||
| 692 | void configure_predicated_copy(PFN_vkGetDeviceProcAddr get, const VkPhysicalDeviceLimits& limits) { | ||
| 693 | std::unique_lock lock(resource_mutex_); | ||
| 694 | predicated_copier_ = std::make_unique<PredicatedBufferCopier>(get, device_, limits); | ||
| 695 | } | ||
| 312 | VkDevice device() const { return device_; } | 696 | VkDevice device() const { return device_; } |
| 313 | 697 | ||
| 314 | // Debug markers become labels from here on; call before any queue or list uses the context. Incomplete sets | 698 | // Debug markers become labels from here on; call before any queue or list uses the context. Incomplete sets |
| @@ -325,41 +709,58 @@ public: | |||
| 325 | // Registers a resource in its D3D12 initial state (a legacy state; images get the matching layout). | 709 | // Registers a resource in its D3D12 initial state (a legacy state; images get the matching layout). |
| 326 | // The image must already be in that layout, e.g. transitioned from UNDEFINED at creation. | 710 | // The image must already be in that layout, e.g. transitioned from UNDEFINED at creation. |
| 327 | void add_resource(ResourceId id, const ResourceBinding& binding) { | 711 | void add_resource(ResourceId id, const ResourceBinding& binding) { |
| 328 | std::lock_guard lock(mutex_); | 712 | std::unique_lock lock(resource_mutex_); |
| 329 | resources_[id] = binding; | 713 | resources_[id] = binding; |
| 330 | } | 714 | } |
| 331 | void add_resource(ResourceId id, const ResourceBinding& binding, VkImageLayout current_layout) { | 715 | void add_resource(ResourceId id, const ResourceBinding& binding, VkImageLayout current_layout) { |
| 332 | std::lock_guard lock(mutex_); | 716 | std::unique_lock rlock(resource_mutex_); |
| 333 | resources_[id] = binding; | 717 | resources_[id] = binding; |
| 334 | if (binding.image) tracker_.track(id, binding, current_layout); | 718 | if (binding.image) { |
| 719 | std::lock_guard tlock(tracker_mutex_); | ||
| 720 | tracker_.track(id, binding, current_layout); | ||
| 721 | } | ||
| 335 | } | 722 | } |
| 336 | 723 | ||
| 337 | void remove_resource(ResourceId id) { | 724 | void remove_resource(ResourceId id) { |
| 338 | std::lock_guard lock(mutex_); | 725 | VkImage img = VK_NULL_HANDLE; |
| 339 | const auto it = resources_.find(id); | 726 | { |
| 340 | if (it == resources_.end()) return; | 727 | std::unique_lock rlock(resource_mutex_); |
| 341 | for (auto v = views_.begin(); v != views_.end();) { | 728 | const auto it = resources_.find(id); |
| 342 | if (std::get<0>(v->first) == it->second.image) { | 729 | if (it == resources_.end()) return; |
| 343 | vk.vkDestroyImageView(device_, v->second, nullptr); | 730 | img = it->second.image; |
| 344 | v = views_.erase(v); | 731 | resources_.erase(it); |
| 345 | } else { | 732 | } |
| 346 | ++v; | 733 | if (img) { |
| 734 | std::lock_guard vlock(views_mutex_); | ||
| 735 | for (auto v = views_.begin(); v != views_.end();) { | ||
| 736 | if (std::get<0>(v->first) == img) { | ||
| 737 | defer_destroy(DeferredDeletionQueue::Kind::image_view, v->second); | ||
| 738 | v = views_.erase(v); | ||
| 739 | } else { | ||
| 740 | ++v; | ||
| 741 | } | ||
| 347 | } | 742 | } |
| 348 | } | 743 | } |
| 744 | std::lock_guard tlock(tracker_mutex_); | ||
| 349 | tracker_.forget(id); | 745 | tracker_.forget(id); |
| 350 | resources_.erase(it); | ||
| 351 | } | 746 | } |
| 352 | 747 | ||
| 353 | // A query heap, by its stable ID (the COM query heap pointer). The pool stays the caller's to destroy, after | 748 | // A query heap, by its stable ID (the COM query heap pointer). The pool stays the caller's to destroy, after |
| 354 | // remove_query_pool. | 749 | // remove_query_pool. |
| 355 | void add_query_pool(QueryHeapId id, const QueryPool& pool) { | 750 | void add_query_pool(QueryHeapId id, const QueryPool& pool) { |
| 356 | std::lock_guard lock(mutex_); | 751 | std::unique_lock lock(resource_mutex_); |
| 357 | query_pools_[id] = pool; | 752 | query_pools_[id] = pool; |
| 358 | } | 753 | } |
| 359 | void remove_query_pool(QueryHeapId id) { | 754 | void remove_query_pool(QueryHeapId id) { |
| 360 | std::lock_guard lock(mutex_); | 755 | std::unique_lock lock(resource_mutex_); |
| 361 | query_pools_.erase(id); | 756 | query_pools_.erase(id); |
| 362 | } | 757 | } |
| 758 | // The heap's d3d12_query_heap type, or ~0u for a heap that is not registered. | ||
| 759 | std::uint32_t query_heap_type(QueryHeapId id) { | ||
| 760 | std::shared_lock lock(resource_mutex_); // query_pools_ is guarded by resource_mutex_, like add/remove | ||
| 761 | const auto it = query_pools_.find(id); | ||
| 762 | return it == query_pools_.end() ? ~0u : it->second.heap_type; | ||
| 763 | } | ||
| 363 | 764 | ||
| 364 | // VkPhysicalDeviceLimits::timestampPeriod (nanoseconds per tick), or 0 when the queue writes no timestamps | 765 | // VkPhysicalDeviceLimits::timestampPeriod (nanoseconds per tick), or 0 when the queue writes no timestamps |
| 365 | // (timestampValidBits 0). Set by the device before any queue uses it. | 766 | // (timestampValidBits 0). Set by the device before any queue uses it. |
| @@ -367,18 +768,18 @@ public: | |||
| 367 | void set_timestamp_period(double period) { timestamp_period_ = period; } | 768 | void set_timestamp_period(double period) { timestamp_period_ = period; } |
| 368 | 769 | ||
| 369 | // Configure before queue creation, when the selected queue family supports compute. | 770 | // Configure before queue creation, when the selected queue family supports compute. |
| 370 | void set_binary_occlusion_memory(const VkPhysicalDeviceMemoryProperties& memory) { | 771 | void set_occlusion_resolve_memory(const VkPhysicalDeviceMemoryProperties& memory) { |
| 371 | binary_occlusion_memory_ = memory; | 772 | occlusion_resolve_memory_ = memory; |
| 372 | } | 773 | } |
| 373 | 774 | ||
| 374 | // For tests and traces. | 775 | // For tests and traces. |
| 375 | VkImageLayout layout(ResourceId id, std::uint32_t subresource) { | 776 | VkImageLayout layout(ResourceId id, std::uint32_t subresource) { |
| 376 | std::lock_guard lock(mutex_); | 777 | std::lock_guard lock(tracker_mutex_); |
| 377 | return tracker_.layout(id, subresource); | 778 | return tracker_.layout(id, subresource); |
| 378 | } | 779 | } |
| 379 | 780 | ||
| 380 | bool has_resource(ResourceId id) { | 781 | bool has_resource(ResourceId id) { |
| 381 | std::lock_guard lock(mutex_); | 782 | std::shared_lock lock(resource_mutex_); |
| 382 | return resources_.find(id) != resources_.end(); | 783 | return resources_.find(id) != resources_.end(); |
| 383 | } | 784 | } |
| 384 | 785 | ||
| @@ -386,28 +787,27 @@ public: | |||
| 386 | 787 | ||
| 387 | void register_acceleration_structure(std::uint64_t va, VkAccelerationStructureKHR as) { | 788 | void register_acceleration_structure(std::uint64_t va, VkAccelerationStructureKHR as) { |
| 388 | if (!va || !as) return; | 789 | if (!va || !as) return; |
| 389 | std::lock_guard lock(mutex_); | 790 | std::unique_lock lock(resource_mutex_); |
| 390 | acceleration_structures_[va] = as; | 791 | acceleration_structures_[va] = as; |
| 391 | } | 792 | } |
| 392 | 793 | ||
| 393 | void unregister_acceleration_structure(std::uint64_t va) { | 794 | void unregister_acceleration_structure(std::uint64_t va) { |
| 394 | if (!va) return; | 795 | if (!va) return; |
| 395 | std::lock_guard lock(mutex_); | 796 | std::unique_lock lock(resource_mutex_); |
| 396 | acceleration_structures_.erase(va); | 797 | acceleration_structures_.erase(va); |
| 397 | } | 798 | } |
| 398 | 799 | ||
| 399 | VkAccelerationStructureKHR resolve_acceleration_structure(std::uint64_t va) { | 800 | VkAccelerationStructureKHR resolve_acceleration_structure(std::uint64_t va) { |
| 400 | std::lock_guard lock(mutex_); | 801 | std::shared_lock lock(resource_mutex_); |
| 401 | const auto it = acceleration_structures_.find(va); | 802 | const auto it = acceleration_structures_.find(va); |
| 402 | return it == acceleration_structures_.end() ? VK_NULL_HANDLE : it->second; | 803 | return it == acceleration_structures_.end() ? VK_NULL_HANDLE : it->second; |
| 403 | } | 804 | } |
| 404 | 805 | ||
| 405 | // `prepare` is called with the context locked, at the start of the command buffer of every | 806 | // `prepare` is called at the start of the command buffer of every ExecuteCommandLists, before the lists are |
| 406 | // ExecuteCommandLists, before the lists are written: the device brings the bindless set 0 of the translated | 807 | // written: the device brings the bindless set 0 of the translated shaders up to date there (vulkan_bindless.h) |
| 407 | // shaders up to date there (vulkan_bindless.h) and records what the set needs first. When it fails, nothing | 808 | // and records what the set needs first. When it fails, nothing of that call is executed. |
| 408 | // of that call is executed. | ||
| 409 | void set_bindless_prepare(std::function<bool(VkCommandBuffer)> prepare) { | 809 | void set_bindless_prepare(std::function<bool(VkCommandBuffer)> prepare) { |
| 410 | std::lock_guard lock(mutex_); | 810 | std::unique_lock lock(resource_mutex_); |
| 411 | bindless_prepare_ = std::move(prepare); | 811 | bindless_prepare_ = std::move(prepare); |
| 412 | } | 812 | } |
| 413 | 813 | ||
| @@ -415,7 +815,7 @@ public: | |||
| 415 | // gives the scratch buffers device-local memory. Without this such a copy is refused as unsupported. | 815 | // gives the scratch buffers device-local memory. Without this such a copy is refused as unsupported. |
| 416 | void enable_depth24(PFN_vkGetDeviceProcAddr get, Depth24Converter::Allocate allocate, | 816 | void enable_depth24(PFN_vkGetDeviceProcAddr get, Depth24Converter::Allocate allocate, |
| 417 | std::uint64_t max_storage_range = 1u << 27) { | 817 | std::uint64_t max_storage_range = 1u << 27) { |
| 418 | std::lock_guard lock(mutex_); | 818 | std::unique_lock lock(resource_mutex_); |
| 419 | depth24_ = std::make_unique<Depth24Converter>(get, device_, std::move(allocate), max_storage_range); | 819 | depth24_ = std::make_unique<Depth24Converter>(get, device_, std::move(allocate), max_storage_range); |
| 420 | if (!depth24_->loaded()) { | 820 | if (!depth24_->loaded()) { |
| 421 | depth24_.reset(); | 821 | depth24_.reset(); |
| @@ -430,15 +830,65 @@ public: | |||
| 430 | // Called after that command buffer's submit: true when it was accepted, false when vkQueueSubmit failed. The | 830 | // Called after that command buffer's submit: true when it was accepted, false when vkQueueSubmit failed. The |
| 431 | // set keeps its upload pending in the second case, because the copy never reached the GPU. | 831 | // set keeps its upload pending in the second case, because the copy never reached the GPU. |
| 432 | void set_bindless_commit(std::function<void(bool)> commit) { | 832 | void set_bindless_commit(std::function<void(bool)> commit) { |
| 433 | std::lock_guard lock(mutex_); | 833 | std::unique_lock lock(resource_mutex_); |
| 434 | bindless_commit_ = std::move(commit); | 834 | bindless_commit_ = std::move(commit); |
| 435 | } | 835 | } |
| 436 | 836 | ||
| 837 | void set_bindless_release(DeferredDeletionQueue::BindlessReleaseFn fn, void* user) { | ||
| 838 | deletion_queue_.set_bindless_release(fn, user); | ||
| 839 | } | ||
| 840 | |||
| 841 | template<typename VkHandle> | ||
| 842 | void defer_destroy(DeferredDeletionQueue::Kind kind, VkHandle handle) { | ||
| 843 | const auto raw = static_cast<std::uint64_t>(reinterpret_cast<std::uintptr_t>(handle)); | ||
| 844 | if (!raw) return; | ||
| 845 | const std::uint64_t safe_ticket = submitted_ticket_.load(std::memory_order_acquire) + 1; | ||
| 846 | deletion_queue_.push(safe_ticket, kind, raw); | ||
| 847 | } | ||
| 848 | |||
| 849 | void defer_destroy(DeferredDeletionQueue::Kind kind, std::uint64_t raw_handle) { | ||
| 850 | if (!raw_handle && kind != DeferredDeletionQueue::Kind::bindless_slot) return; | ||
| 851 | const std::uint64_t safe_ticket = submitted_ticket_.load(std::memory_order_acquire) + 1; | ||
| 852 | deletion_queue_.push(safe_ticket, kind, raw_handle); | ||
| 853 | } | ||
| 854 | |||
| 855 | std::uint64_t completed_retire_ticket() const { | ||
| 856 | if (!retire_timeline_) return submitted_ticket_.load(std::memory_order_acquire); | ||
| 857 | std::uint64_t done = 0; | ||
| 858 | vk.vkGetSemaphoreCounterValue(device_, retire_timeline_, &done); | ||
| 859 | return done; | ||
| 860 | } | ||
| 861 | |||
| 862 | void drain_deleted_resources(std::uint64_t current_ticket) { | ||
| 863 | deletion_queue_.drain(current_ticket, device_, vk); | ||
| 864 | } | ||
| 865 | |||
| 866 | VkSemaphore retire_timeline() const noexcept { return retire_timeline_; } | ||
| 867 | std::uint64_t advance_retire_ticket() noexcept { | ||
| 868 | return submitted_ticket_.fetch_add(1, std::memory_order_acq_rel) + 1; | ||
| 869 | } | ||
| 870 | |||
| 437 | VulkanDeviceFunctions vk; | 871 | VulkanDeviceFunctions vk; |
| 438 | 872 | ||
| 439 | // Vulkan requires external synchronisation of a VkQueue; every D3D12 queue of the device may share one. | 873 | // Vulkan requires external synchronisation of a VkQueue; every D3D12 queue of the device may share one. |
| 440 | std::mutex& submit_mutex() { return submit_mutex_; } | 874 | std::mutex& submit_mutex() { return submit_mutex_; } |
| 441 | 875 | ||
| 876 | void mark_device_lost() noexcept { device_lost_.store(true, std::memory_order_release); } | ||
| 877 | bool is_device_lost() const noexcept { return device_lost_.load(std::memory_order_acquire); } | ||
| 878 | |||
| 879 | void set_signal_event_fn(FenceWaitDispatcher::SignalEventFn fn) { | ||
| 880 | if (fence_dispatcher_) fence_dispatcher_->set_signal_event_fn(fn); | ||
| 881 | } | ||
| 882 | void enqueue_fence_wait(VkSemaphore sem, std::uint64_t value, void* event_handle) { | ||
| 883 | if (fence_dispatcher_) fence_dispatcher_->enqueue(sem, value, event_handle); | ||
| 884 | } | ||
| 885 | void enqueue_fence_callback(VkSemaphore sem, std::uint64_t value, std::function<void()> cb) { | ||
| 886 | if (fence_dispatcher_) fence_dispatcher_->enqueue_callback(sem, value, std::move(cb)); | ||
| 887 | } | ||
| 888 | void cancel_fence_waits(VkSemaphore sem) { | ||
| 889 | if (fence_dispatcher_) fence_dispatcher_->cancel(sem); | ||
| 890 | } | ||
| 891 | |||
| 442 | private: | 892 | private: |
| 443 | friend class VulkanQueue; | 893 | friend class VulkanQueue; |
| 444 | 894 | ||
| @@ -447,8 +897,9 @@ private: | |||
| 447 | return it == resources_.end() ? nullptr : &it->second; | 897 | return it == resources_.end() ? nullptr : &it->second; |
| 448 | } | 898 | } |
| 449 | 899 | ||
| 450 | // Called with mutex_ held (from prepare). Views live until their image is removed. | 900 | // Called from prepare; protected by views_mutex_ so concurrent shared_lock readers are safe. |
| 451 | VkImageView view(const ResourceBinding& r, const VkImageSubresourceRange& range) { | 901 | VkImageView view(const ResourceBinding& r, const VkImageSubresourceRange& range) { |
| 902 | std::lock_guard lock(views_mutex_); | ||
| 452 | const auto key = std::make_tuple(r.image, range.aspectMask, range.baseMipLevel, range.baseArrayLayer, | 903 | const auto key = std::make_tuple(r.image, range.aspectMask, range.baseMipLevel, range.baseArrayLayer, |
| 453 | range.layerCount, r.format); | 904 | range.layerCount, r.format); |
| 454 | if (const auto it = views_.find(key); it != views_.end()) return it->second; | 905 | if (const auto it = views_.find(key); it != views_.end()) return it->second; |
| @@ -457,11 +908,12 @@ private: | |||
| 457 | info.viewType = VK_IMAGE_VIEW_TYPE_2D_ARRAY; | 908 | info.viewType = VK_IMAGE_VIEW_TYPE_2D_ARRAY; |
| 458 | info.format = r.format; | 909 | info.format = r.format; |
| 459 | info.subresourceRange = range; | 910 | info.subresourceRange = range; |
| 460 | // Reinterpreted RTVs need only color-attachment usage. Inheriting STORAGE usage from the resource | 911 | // Attachment views need only color-attachment usage. Inheriting STORAGE usage from a mutable/extended |
| 461 | // would incorrectly require it from an sRGB view, even though this view is never used as storage. | 912 | // resource (typeless RGBA8 sRGB views, or R32_UINT-backed R9G9B9E5 UAV images) would require unrelated usages. |
| 462 | VkImageViewUsageCreateInfo usage{VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO}; | 913 | VkImageViewUsageCreateInfo usage{VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO}; |
| 463 | usage.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; | 914 | usage.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; |
| 464 | if (r.rgba8_typeless) info.pNext = &usage; | 915 | if (r.rgba8_typeless || (range.aspectMask == VK_IMAGE_ASPECT_COLOR_BIT && r.color_attachment)) |
| 916 | info.pNext = &usage; | ||
| 465 | VkImageView view = VK_NULL_HANDLE; | 917 | VkImageView view = VK_NULL_HANDLE; |
| 466 | if (vk.vkCreateImageView(device_, &info, nullptr, &view) != VK_SUCCESS) return VK_NULL_HANDLE; | 918 | if (vk.vkCreateImageView(device_, &info, nullptr, &view) != VK_SUCCESS) return VK_NULL_HANDLE; |
| 467 | views_[key] = view; | 919 | views_[key] = view; |
| @@ -471,8 +923,15 @@ private: | |||
| 471 | VkDevice device_; | 923 | VkDevice device_; |
| 472 | bool loaded_ = false; | 924 | bool loaded_ = false; |
| 473 | bool ray_tracing_ = false; | 925 | bool ray_tracing_ = false; |
| 474 | std::mutex mutex_; // resources, tracker and views; held while a queue prepares and emits | 926 | std::atomic<bool> device_lost_{false}; |
| 475 | std::mutex submit_mutex_; | 927 | alignas(64) std::shared_mutex resource_mutex_; // shared for prepare lookups, unique for add/remove |
| 928 | alignas(64) std::mutex tracker_mutex_; | ||
| 929 | alignas(64) std::mutex views_mutex_; | ||
| 930 | alignas(64) std::mutex submit_mutex_; | ||
| 931 | VkSemaphore retire_timeline_ = VK_NULL_HANDLE; | ||
| 932 | std::atomic<std::uint64_t> submitted_ticket_{0}; | ||
| 933 | DeferredDeletionQueue deletion_queue_; | ||
| 934 | std::unique_ptr<FenceWaitDispatcher> fence_dispatcher_; | ||
| 476 | std::unordered_map<ResourceId, ResourceBinding> resources_; | 935 | std::unordered_map<ResourceId, ResourceBinding> resources_; |
| 477 | std::unordered_map<std::uint64_t, VkAccelerationStructureKHR> acceleration_structures_; | 936 | std::unordered_map<std::uint64_t, VkAccelerationStructureKHR> acceleration_structures_; |
| 478 | LayoutTracker tracker_; | 937 | LayoutTracker tracker_; |
| @@ -482,10 +941,16 @@ private: | |||
| 482 | std::function<void(bool)> bindless_commit_; | 941 | std::function<void(bool)> bindless_commit_; |
| 483 | std::unordered_map<QueryHeapId, QueryPool> query_pools_; // element pointers stay valid across inserts | 942 | std::unordered_map<QueryHeapId, QueryPool> query_pools_; // element pointers stay valid across inserts |
| 484 | double timestamp_period_ = 0; | 943 | double timestamp_period_ = 0; |
| 485 | VkPhysicalDeviceMemoryProperties binary_occlusion_memory_{}; | 944 | VkPhysicalDeviceMemoryProperties occlusion_resolve_memory_{}; |
| 486 | ReplayFunctions replay_; | 945 | ReplayFunctions replay_; |
| 946 | std::unique_ptr<PredicateReducer> predicate_reducer_; | ||
| 947 | std::unique_ptr<PredicatedBufferCopier> predicated_copier_; | ||
| 948 | std::uint32_t predicate_family_ = UINT32_MAX; | ||
| 487 | DebugLabelFunctions labels_; | 949 | DebugLabelFunctions labels_; |
| 488 | }; | 950 | }; |
| 951 | #ifdef _MSC_VER | ||
| 952 | #pragma warning(pop) | ||
| 953 | #endif | ||
| 489 | 954 | ||
| 490 | // A Vulkan timeline semaphore with D3D12 fence semantics for the host side. | 955 | // A Vulkan timeline semaphore with D3D12 fence semantics for the host side. |
| 491 | class VulkanFence { | 956 | class VulkanFence { |
| @@ -540,7 +1005,24 @@ private: | |||
| 540 | // per call, and the COM wrapper serialises its calls. | 1005 | // per call, and the COM wrapper serialises its calls. |
| 541 | class VulkanQueue { | 1006 | class VulkanQueue { |
| 542 | public: | 1007 | public: |
| 543 | VulkanQueue(VulkanContext& context, VkQueue queue, std::uint32_t family) : context_(context), queue_(queue) { | 1008 | enum class QueueKind : std::uint8_t { direct, compute, copy }; |
| 1009 | |||
| 1010 | static constexpr VkPipelineStageFlags2 queue_supported_stages(QueueKind kind) noexcept { | ||
| 1011 | switch (kind) { | ||
| 1012 | case QueueKind::copy: | ||
| 1013 | return VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_TRANSFER_BIT; | ||
| 1014 | case QueueKind::compute: | ||
| 1015 | return VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_TRANSFER_BIT | | ||
| 1016 | VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT; | ||
| 1017 | case QueueKind::direct: | ||
| 1018 | default: | ||
| 1019 | return VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_TRANSFER_BIT | | ||
| 1020 | VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT; | ||
| 1021 | } | ||
| 1022 | } | ||
| 1023 | |||
| 1024 | VulkanQueue(VulkanContext& context, VkQueue queue, std::uint32_t family, QueueKind kind = QueueKind::direct) | ||
| 1025 | : context_(context), queue_(queue), kind_(kind), family_(family) { | ||
| 544 | auto& vk = context.vk; | 1026 | auto& vk = context.vk; |
| 545 | VkCommandPoolCreateInfo pool{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; | 1027 | VkCommandPoolCreateInfo pool{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; |
| 546 | pool.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; | 1028 | pool.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; |
| @@ -560,7 +1042,7 @@ public: | |||
| 560 | vk.vkQueueWaitIdle(queue_); | 1042 | vk.vkQueueWaitIdle(queue_); |
| 561 | } | 1043 | } |
| 562 | if (progress_) { | 1044 | if (progress_) { |
| 563 | std::lock_guard lock(context_.mutex_); | 1045 | std::lock_guard lock(context_.tracker_mutex_); |
| 564 | if (context_.depth24_) context_.depth24_->forget(progress_); // its scratch is idle now | 1046 | if (context_.depth24_) context_.depth24_->forget(progress_); // its scratch is idle now |
| 565 | } | 1047 | } |
| 566 | if (pool_) vk.vkDestroyCommandPool(context_.device(), pool_, nullptr); | 1048 | if (pool_) vk.vkDestroyCommandPool(context_.device(), pool_, nullptr); |
| @@ -575,54 +1057,205 @@ public: | |||
| 575 | // ExecuteCommandLists: every list is checked before any is written, so a failure submits nothing and leaves | 1057 | // ExecuteCommandLists: every list is checked before any is written, so a failure submits nothing and leaves |
| 576 | // the layout tracker as it was. Pending Wait()s are attached to this submission. | 1058 | // the layout tracker as it was. Pending Wait()s are attached to this submission. |
| 577 | ReplayResult execute(std::span<const CommandList* const> lists) { | 1059 | ReplayResult execute(std::span<const CommandList* const> lists) { |
| 578 | std::lock_guard lock(context_.mutex_); | 1060 | if (context_.is_device_lost()) return ReplayResult::unsupported; |
| 579 | if (context_.depth24_) context_.depth24_->collect(); | 1061 | VkCommandBuffer command_buffer = VK_NULL_HANDLE; |
| 1062 | std::function<void(bool)> bindless_commit; | ||
| 1063 | // Lock hierarchy: resource_mutex_ -> tracker_mutex_ -> submit_mutex_. | ||
| 1064 | // Shared read-lock allows concurrent prepare() across queues; tracker_mutex_ is acquired lazily during | ||
| 1065 | // prepare() only if a list actually converts a depth24_as_float copy, and otherwise right before | ||
| 1066 | // bindless_prepare_/emit() through submit() so bindless flushes, layout emits, and submissions stay in order. | ||
| 1067 | std::shared_lock resource_lock(context_.resource_mutex_); | ||
| 1068 | std::unique_lock tracker_lock(context_.tracker_mutex_, std::defer_lock); | ||
| 1069 | // Declared after tracker_lock so any early return after depth24_->prepare() retires uncommitted scratch/pools | ||
| 1070 | // with ticket 0 while tracker_lock is still held. | ||
| 1071 | struct Depth24Guard { | ||
| 1072 | Depth24Converter* d24 = nullptr; | ||
| 1073 | VkSemaphore progress = VK_NULL_HANDLE; | ||
| 1074 | bool active = false; | ||
| 1075 | ~Depth24Guard() { | ||
| 1076 | if (active && d24) d24->retire(progress, 0); | ||
| 1077 | } | ||
| 1078 | } depth24_guard{context_.depth24_.get(), progress_, false}; | ||
| 1079 | bindless_commit = context_.bindless_commit_; | ||
| 580 | std::vector<PreparedList> prepared(lists.size()); | 1080 | std::vector<PreparedList> prepared(lists.size()); |
| 581 | ReplayFunctions replay = context_.replay_; | 1081 | ReplayFunctions replay = context_.replay_; |
| 582 | if (context_.binary_occlusion_memory_.memoryTypeCount) { | 1082 | std::uint64_t captures = 0; |
| 1083 | for (const auto* list : lists) | ||
| 1084 | for (const auto& command : list->commands()) | ||
| 1085 | if (const auto* p = std::get_if<Predication>(&command); p && p->buffer) ++captures; | ||
| 1086 | std::unique_ptr<PredicateReducer::Batch> batch; | ||
| 1087 | std::unique_ptr<PredicatedBufferCopier::Batch> copy_batch; | ||
| 1088 | if (captures) { | ||
| 1089 | if (kind_ == QueueKind::copy || !context_.predicate_reducer_ || family_ != context_.predicate_family_) | ||
| 1090 | return ReplayResult::unsupported; | ||
| 1091 | // The helper's lazy pipeline is shared by queues. Serialize preparation with the tracker lock, | ||
| 1092 | // retaining main's resource -> tracker -> submit lock order through emit and submission. | ||
| 1093 | if (!tracker_lock.owns_lock()) tracker_lock.lock(); | ||
| 1094 | batch = context_.predicate_reducer_->batch(captures); | ||
| 1095 | if (!batch) return ReplayResult::unsupported; | ||
| 1096 | replay.prepare_predicate = [&](VkBuffer buffer, VkDeviceSize offset, PredicateCapture& out) { | ||
| 1097 | return batch->prepare(buffer, offset, out); | ||
| 1098 | }; | ||
| 1099 | replay.capture_predicate = [&](VkCommandBuffer cb, const PredicateCapture& p) { | ||
| 1100 | context_.predicate_reducer_->capture(cb, p); | ||
| 1101 | }; | ||
| 1102 | if (context_.predicated_copier_) { | ||
| 1103 | copy_batch = context_.predicated_copier_->batch(); | ||
| 1104 | replay.prepare_predicated_copy = [&](VkBuffer source, VkBuffer destination, VkDeviceSize src, | ||
| 1105 | VkDeviceSize dst, VkDeviceSize size, | ||
| 1106 | std::vector<PredicatedCopyDispatch>& out) { | ||
| 1107 | return copy_batch->prepare(source, destination, src, dst, size, out); | ||
| 1108 | }; | ||
| 1109 | replay.emit_predicated_copy = [&](VkCommandBuffer cb, const std::vector<PredicatedCopyDispatch>& jobs) { | ||
| 1110 | context_.predicated_copier_->emit(cb, jobs); | ||
| 1111 | }; | ||
| 1112 | } | ||
| 1113 | } | ||
| 1114 | if (context_.depth24_) { | ||
| 1115 | replay.depth24_prepare = [this, &tracker_lock, &depth24_guard](Depth24Job& job, | ||
| 1116 | std::vector<Depth24Job>& parts) { | ||
| 1117 | if (!tracker_lock.owns_lock()) tracker_lock.lock(); | ||
| 1118 | if (!depth24_guard.active) { | ||
| 1119 | context_.depth24_->collect(); | ||
| 1120 | depth24_guard.active = true; | ||
| 1121 | } | ||
| 1122 | return context_.depth24_->prepare(job, parts); | ||
| 1123 | }; | ||
| 1124 | } | ||
| 1125 | const auto& occlusion_memory = context_.occlusion_resolve_memory_; | ||
| 1126 | const bool can_resolve_occlusion = occlusion_memory.memoryTypeCount != 0; | ||
| 1127 | if (can_resolve_occlusion) { | ||
| 1128 | replay.sum_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, | ||
| 1129 | std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { | ||
| 1130 | occlusion_resolve_->sum(cb, pool, first, count, dst, offset); | ||
| 1131 | }; | ||
| 583 | replay.resolve_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, | 1132 | replay.resolve_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, |
| 584 | std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { | 1133 | std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { |
| 585 | binary_occlusion_->record(cb, pool, first, count, dst, offset); | 1134 | occlusion_resolve_->normalize(cb, pool, first, count, dst, offset); |
| 586 | }; | 1135 | }; |
| 587 | } | 1136 | } |
| 588 | const auto resolve = [this](ResourceId id) { return context_.resolve(id); }; | 1137 | const auto resolve = [this](ResourceId id) { return context_.resolve(id); }; |
| 589 | bool binary_occlusion_needed = false; | 1138 | std::uint32_t segments = 0; |
| 590 | for (std::size_t i = 0; i < lists.size(); ++i) { | 1139 | for (std::size_t i = 0; i < lists.size(); ++i) { |
| 591 | const auto result = prepare(*lists[i], resolve, replay, prepared[i]); | 1140 | const auto result = prepare(*lists[i], resolve, replay, prepared[i]); |
| 592 | if (result != ReplayResult::success) return result; | 1141 | if (result != ReplayResult::success) return result; |
| 593 | binary_occlusion_needed |= prepared[i].binary_occlusion; | 1142 | if (prepared[i].segment_count > UINT32_MAX - segments) return ReplayResult::unsupported; |
| 1143 | segments += prepared[i].segment_count; | ||
| 1144 | } | ||
| 1145 | std::shared_ptr<OcclusionSegmentPool> physical; | ||
| 1146 | if (segments) { | ||
| 1147 | const auto& vk = context_.vk; | ||
| 1148 | if (!vk.vkCreateQueryPool || !vk.vkDestroyQueryPool) return ReplayResult::unsupported; | ||
| 1149 | physical = std::make_shared<OcclusionSegmentPool>(); | ||
| 1150 | physical->device = context_.device(); | ||
| 1151 | physical->destroy = vk.vkDestroyQueryPool; | ||
| 1152 | VkQueryPoolCreateInfo info{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO}; | ||
| 1153 | info.queryType = VK_QUERY_TYPE_OCCLUSION; | ||
| 1154 | info.queryCount = segments; | ||
| 1155 | if (vk.vkCreateQueryPool(physical->device, &info, nullptr, &physical->pool) != VK_SUCCESS) | ||
| 1156 | return ReplayResult::unsupported; | ||
| 594 | } | 1157 | } |
| 595 | if (binary_occlusion_needed && !binary_occlusion_) { | 1158 | QueryReplay queries; |
| 596 | auto helper = std::make_unique<BinaryOcclusionResolve>(context_.vk, context_.device()); | 1159 | std::uint32_t base = 0; |
| 597 | if (!helper->initialize(context_.binary_occlusion_memory_)) return ReplayResult::unsupported; | 1160 | for (auto& list : prepared) { |
| 598 | binary_occlusion_ = std::move(helper); | 1161 | const auto result = queries.plan(list, physical, base, can_resolve_occlusion); |
| 1162 | if (result != ReplayResult::success) return result; | ||
| 1163 | base += list.segment_count; | ||
| 599 | } | 1164 | } |
| 600 | VkCommandBuffer command_buffer = acquire(); | 1165 | if (queries.needs_sum || queries.needs_binary) { |
| 601 | if (!command_buffer) return ReplayResult::unsupported; | 1166 | if (!occlusion_resolve_) { |
| 1167 | auto helper = std::make_unique<OcclusionResolve>(context_.vk, context_.device()); | ||
| 1168 | if (!helper->initialize(occlusion_memory)) return ReplayResult::unsupported; | ||
| 1169 | occlusion_resolve_ = std::move(helper); | ||
| 1170 | } | ||
| 1171 | if (!occlusion_resolve_->prepare(queries.needs_sum, queries.needs_binary)) | ||
| 1172 | return ReplayResult::unsupported; | ||
| 1173 | } | ||
| 1174 | |||
| 1175 | CommandSlot* slot = acquire(); | ||
| 1176 | if (!slot) return ReplayResult::unsupported; | ||
| 1177 | command_buffer = slot->buffer; | ||
| 1178 | const auto discard = [&] { | ||
| 1179 | if (context_.vk.vkResetCommandBuffer(command_buffer, 0) == VK_SUCCESS) slot->ticket = 0; | ||
| 1180 | }; | ||
| 602 | VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; | 1181 | VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; |
| 603 | begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; | 1182 | begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; |
| 604 | context_.vk.vkBeginCommandBuffer(command_buffer, &begin); | 1183 | if (context_.vk.vkBeginCommandBuffer(command_buffer, &begin) != VK_SUCCESS) { |
| 1184 | discard(); | ||
| 1185 | return ReplayResult::unsupported; | ||
| 1186 | } | ||
| 1187 | if (!tracker_lock.owns_lock()) tracker_lock.lock(); | ||
| 605 | if (context_.bindless_prepare_ && !context_.bindless_prepare_(command_buffer)) { | 1188 | if (context_.bindless_prepare_ && !context_.bindless_prepare_(command_buffer)) { |
| 606 | // The command buffer holds at most what the set recorded for itself; submit it so the buffer is reused. | 1189 | const bool ended = context_.vk.vkEndCommandBuffer(command_buffer) == VK_SUCCESS; |
| 607 | context_.vk.vkEndCommandBuffer(command_buffer); | 1190 | resource_lock.unlock(); |
| 608 | const bool submitted = submit(command_buffer, VK_NULL_HANDLE, 0); | 1191 | const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0); |
| 609 | if (context_.bindless_commit_) context_.bindless_commit_(submitted); | 1192 | if (!submitted) discard(); |
| 1193 | if (depth24_guard.active) { | ||
| 1194 | context_.depth24_->retire(progress_, 0); | ||
| 1195 | depth24_guard.active = false; | ||
| 1196 | } | ||
| 1197 | tracker_lock.unlock(); | ||
| 1198 | if (bindless_commit) bindless_commit(submitted); | ||
| 610 | return ReplayResult::unsupported; | 1199 | return ReplayResult::unsupported; |
| 611 | } | 1200 | } |
| 1201 | auto next_tracker = context_.tracker_; | ||
| 1202 | bool wrote_readback = false; | ||
| 1203 | VkPipelineStageFlags2 readback_stages = 0; | ||
| 612 | std::uint32_t open_labels = 0; // events may span the lists of one ExecuteCommandLists | 1204 | std::uint32_t open_labels = 0; // events may span the lists of one ExecuteCommandLists |
| 613 | for (const auto& list : prepared) emit(list, command_buffer, replay, &context_.tracker_, &open_labels); | 1205 | for (const auto& list : prepared) { |
| 1206 | emit(list, command_buffer, replay, &next_tracker, &open_labels); | ||
| 1207 | wrote_readback |= list.wrote_readback; | ||
| 1208 | readback_stages |= list.readback_src_stages; | ||
| 1209 | } | ||
| 614 | close_labels(command_buffer, replay, open_labels); | 1210 | close_labels(command_buffer, replay, open_labels); |
| 615 | // A fence wait on the CPU makes GPU writes visible to the host only after a barrier to the host domain: | 1211 | // Only flush GPU writes to the host domain when this batch actually wrote to a readback buffer. |
| 616 | // readback buffers are read through Map once the application has waited. | 1212 | if (wrote_readback) { |
| 617 | VkMemoryBarrier host{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; | 1213 | const VkPipelineStageFlags2 allowed = queue_supported_stages(kind_); |
| 618 | host.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT; | 1214 | VkPipelineStageFlags2 src_stages = readback_stages & allowed; |
| 619 | host.dstAccessMask = VK_ACCESS_HOST_READ_BIT; | 1215 | if (!src_stages) src_stages = VK_PIPELINE_STAGE_2_TRANSFER_BIT; |
| 620 | context_.vk.vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_HOST_BIT, | 1216 | const bool copy_only = |
| 621 | 0, 1, &host, 0, nullptr, 0, nullptr); | 1217 | (src_stages & ~(VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_TRANSFER_BIT)) == 0; |
| 622 | context_.vk.vkEndCommandBuffer(command_buffer); | 1218 | const VkAccessFlags2 src_access = |
| 623 | const bool submitted = submit(command_buffer, VK_NULL_HANDLE, 0); | 1219 | copy_only ? VK_ACCESS_2_TRANSFER_WRITE_BIT : VK_ACCESS_2_MEMORY_WRITE_BIT; |
| 624 | if (context_.depth24_) context_.depth24_->retire(progress_, submitted_); // what this list's copies prepared | 1220 | |
| 625 | if (context_.bindless_commit_) context_.bindless_commit_(submitted); | 1221 | if (context_.vk.vkCmdPipelineBarrier2) { |
| 1222 | VkMemoryBarrier2 host{VK_STRUCTURE_TYPE_MEMORY_BARRIER_2}; | ||
| 1223 | host.srcStageMask = src_stages; | ||
| 1224 | host.srcAccessMask = src_access; | ||
| 1225 | host.dstStageMask = VK_PIPELINE_STAGE_2_HOST_BIT; | ||
| 1226 | host.dstAccessMask = VK_ACCESS_2_HOST_READ_BIT; | ||
| 1227 | VkDependencyInfo dep{VK_STRUCTURE_TYPE_DEPENDENCY_INFO}; | ||
| 1228 | dep.memoryBarrierCount = 1; | ||
| 1229 | dep.pMemoryBarriers = &host; | ||
| 1230 | context_.vk.vkCmdPipelineBarrier2(command_buffer, &dep); | ||
| 1231 | } else { | ||
| 1232 | const VkPipelineStageFlags legacy_src = | ||
| 1233 | copy_only ? VK_PIPELINE_STAGE_TRANSFER_BIT : VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; | ||
| 1234 | VkMemoryBarrier host{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; | ||
| 1235 | host.srcAccessMask = copy_only ? VK_ACCESS_TRANSFER_WRITE_BIT : VK_ACCESS_MEMORY_WRITE_BIT; | ||
| 1236 | host.dstAccessMask = VK_ACCESS_HOST_READ_BIT; | ||
| 1237 | context_.vk.vkCmdPipelineBarrier(command_buffer, legacy_src, VK_PIPELINE_STAGE_HOST_BIT, | ||
| 1238 | 0, 1, &host, 0, nullptr, 0, nullptr); | ||
| 1239 | } | ||
| 1240 | } | ||
| 1241 | const bool ended = context_.vk.vkEndCommandBuffer(command_buffer) == VK_SUCCESS; | ||
| 1242 | resource_lock.unlock(); // release resource_mutex_ before vkQueueSubmit while keeping tracker_lock held | ||
| 1243 | const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0); | ||
| 1244 | if (submitted) { | ||
| 1245 | context_.tracker_ = std::move(next_tracker); | ||
| 1246 | slot->predicate = std::move(batch); | ||
| 1247 | slot->predicated_copy = std::move(copy_batch); | ||
| 1248 | queries.commit(); | ||
| 1249 | slot->segments = std::move(queries.retained); | ||
| 1250 | } else { | ||
| 1251 | discard(); | ||
| 1252 | } | ||
| 1253 | if (depth24_guard.active) { | ||
| 1254 | context_.depth24_->retire(progress_, submitted ? submitted_ : 0); | ||
| 1255 | depth24_guard.active = false; | ||
| 1256 | } | ||
| 1257 | tracker_lock.unlock(); | ||
| 1258 | if (bindless_commit) bindless_commit(submitted); | ||
| 626 | return submitted ? ReplayResult::success : ReplayResult::unsupported; | 1259 | return submitted ? ReplayResult::success : ReplayResult::unsupported; |
| 627 | } | 1260 | } |
| 628 | 1261 | ||
| @@ -662,14 +1295,31 @@ public: | |||
| 662 | } | 1295 | } |
| 663 | 1296 | ||
| 664 | private: | 1297 | private: |
| 665 | VkCommandBuffer acquire() { | 1298 | struct CommandSlot { |
| 1299 | VkCommandBuffer buffer; | ||
| 1300 | std::uint64_t ticket; | ||
| 1301 | std::vector<std::shared_ptr<const OcclusionSegmentPool>> segments; | ||
| 1302 | std::unique_ptr<PredicatedBufferCopier::Batch> predicated_copy; | ||
| 1303 | std::unique_ptr<PredicateReducer::Batch> predicate; // retained until this slot completes | ||
| 1304 | }; | ||
| 1305 | |||
| 1306 | CommandSlot* acquire() { | ||
| 1307 | if (context_.is_device_lost()) return nullptr; | ||
| 1308 | context_.drain_deleted_resources(context_.completed_retire_ticket()); | ||
| 666 | std::uint64_t done = 0; | 1309 | std::uint64_t done = 0; |
| 667 | context_.vk.vkGetSemaphoreCounterValue(context_.device(), progress_, &done); | 1310 | context_.vk.vkGetSemaphoreCounterValue(context_.device(), progress_, &done); |
| 1311 | CommandSlot* reuse = nullptr; | ||
| 668 | for (auto& slot : buffers_) { | 1312 | for (auto& slot : buffers_) { |
| 669 | if (slot.second > done) continue; | 1313 | if (slot.ticket > done) continue; |
| 670 | context_.vk.vkResetCommandBuffer(slot.first, 0); | 1314 | slot.segments.clear(); |
| 671 | slot.second = UINT64_MAX; // in use until submitted | 1315 | if (!reuse) reuse = &slot; |
| 672 | return slot.first; | 1316 | } |
| 1317 | if (reuse) { | ||
| 1318 | if (context_.vk.vkResetCommandBuffer(reuse->buffer, 0) != VK_SUCCESS) return nullptr; | ||
| 1319 | reuse->predicate.reset(); | ||
| 1320 | reuse->predicated_copy.reset(); | ||
| 1321 | reuse->ticket = UINT64_MAX; // in use until submitted | ||
| 1322 | return reuse; | ||
| 673 | } | 1323 | } |
| 674 | VkCommandBufferAllocateInfo info{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; | 1324 | VkCommandBufferAllocateInfo info{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; |
| 675 | info.commandPool = pool_; | 1325 | info.commandPool = pool_; |
| @@ -677,54 +1327,71 @@ private: | |||
| 677 | info.commandBufferCount = 1; | 1327 | info.commandBufferCount = 1; |
| 678 | VkCommandBuffer command_buffer = VK_NULL_HANDLE; | 1328 | VkCommandBuffer command_buffer = VK_NULL_HANDLE; |
| 679 | if (context_.vk.vkAllocateCommandBuffers(context_.device(), &info, &command_buffer) != VK_SUCCESS) | 1329 | if (context_.vk.vkAllocateCommandBuffers(context_.device(), &info, &command_buffer) != VK_SUCCESS) |
| 680 | return VK_NULL_HANDLE; | 1330 | return nullptr; |
| 681 | buffers_.push_back({command_buffer, UINT64_MAX}); | 1331 | buffers_.push_back({command_buffer, UINT64_MAX}); |
| 682 | return command_buffer; | 1332 | return &buffers_.back(); |
| 683 | } | 1333 | } |
| 684 | 1334 | ||
| 685 | bool submit(VkCommandBuffer command_buffer, VkSemaphore fence, std::uint64_t value) { | 1335 | bool submit(VkCommandBuffer command_buffer, VkSemaphore fence, std::uint64_t value) { |
| 1336 | if (context_.is_device_lost()) return false; | ||
| 686 | const std::uint64_t ticket = ++submitted_; | 1337 | const std::uint64_t ticket = ++submitted_; |
| 687 | std::vector<VkSemaphore> signals{progress_}; | ||
| 688 | std::vector<std::uint64_t> signal_values{ticket}; | ||
| 689 | if (fence) { | ||
| 690 | signals.push_back(fence); | ||
| 691 | signal_values.push_back(value); | ||
| 692 | } | ||
| 693 | const std::vector<VkPipelineStageFlags> stages(waits_.size(), VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); | 1338 | const std::vector<VkPipelineStageFlags> stages(waits_.size(), VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); |
| 694 | VkTimelineSemaphoreSubmitInfo timeline{VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO}; | 1339 | VkResult res = VK_SUCCESS; |
| 695 | timeline.waitSemaphoreValueCount = std::uint32_t(wait_values_.size()); | ||
| 696 | timeline.pWaitSemaphoreValues = wait_values_.data(); | ||
| 697 | timeline.signalSemaphoreValueCount = std::uint32_t(signal_values.size()); | ||
| 698 | timeline.pSignalSemaphoreValues = signal_values.data(); | ||
| 699 | VkSubmitInfo submit{VK_STRUCTURE_TYPE_SUBMIT_INFO, &timeline}; | ||
| 700 | submit.waitSemaphoreCount = std::uint32_t(waits_.size()); | ||
| 701 | submit.pWaitSemaphores = waits_.data(); | ||
| 702 | submit.pWaitDstStageMask = stages.data(); | ||
| 703 | submit.commandBufferCount = command_buffer ? 1 : 0; | ||
| 704 | submit.pCommandBuffers = &command_buffer; | ||
| 705 | submit.signalSemaphoreCount = std::uint32_t(signals.size()); | ||
| 706 | submit.pSignalSemaphores = signals.data(); | ||
| 707 | bool ok; | ||
| 708 | { | 1340 | { |
| 709 | std::lock_guard lock(context_.submit_mutex()); | 1341 | std::lock_guard lock(context_.submit_mutex()); |
| 710 | ok = context_.vk.vkQueueSubmit(queue_, 1, &submit, VK_NULL_HANDLE) == VK_SUCCESS; | 1342 | VkSemaphore signals[3]{progress_, VK_NULL_HANDLE, VK_NULL_HANDLE}; |
| 1343 | std::uint64_t signal_values[3]{ticket, 0, 0}; | ||
| 1344 | std::uint32_t signal_count = 1; | ||
| 1345 | if (context_.retire_timeline()) { | ||
| 1346 | signals[signal_count] = context_.retire_timeline(); | ||
| 1347 | signal_values[signal_count] = context_.advance_retire_ticket(); | ||
| 1348 | ++signal_count; | ||
| 1349 | } | ||
| 1350 | if (fence) { | ||
| 1351 | signals[signal_count] = fence; | ||
| 1352 | signal_values[signal_count] = value; | ||
| 1353 | ++signal_count; | ||
| 1354 | } | ||
| 1355 | VkTimelineSemaphoreSubmitInfo timeline{VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO}; | ||
| 1356 | timeline.waitSemaphoreValueCount = std::uint32_t(wait_values_.size()); | ||
| 1357 | timeline.pWaitSemaphoreValues = wait_values_.data(); | ||
| 1358 | timeline.signalSemaphoreValueCount = signal_count; | ||
| 1359 | timeline.pSignalSemaphoreValues = signal_values; | ||
| 1360 | VkSubmitInfo submit{VK_STRUCTURE_TYPE_SUBMIT_INFO, &timeline}; | ||
| 1361 | submit.waitSemaphoreCount = std::uint32_t(waits_.size()); | ||
| 1362 | submit.pWaitSemaphores = waits_.data(); | ||
| 1363 | submit.pWaitDstStageMask = stages.data(); | ||
| 1364 | submit.commandBufferCount = command_buffer ? 1 : 0; | ||
| 1365 | submit.pCommandBuffers = &command_buffer; | ||
| 1366 | submit.signalSemaphoreCount = signal_count; | ||
| 1367 | submit.pSignalSemaphores = signals; | ||
| 1368 | res = context_.vk.vkQueueSubmit(queue_, 1, &submit, VK_NULL_HANDLE); | ||
| 1369 | } | ||
| 1370 | if (res == VK_ERROR_DEVICE_LOST) { | ||
| 1371 | context_.mark_device_lost(); | ||
| 1372 | waits_.clear(); | ||
| 1373 | wait_values_.clear(); | ||
| 1374 | return false; | ||
| 711 | } | 1375 | } |
| 1376 | const bool ok = (res == VK_SUCCESS); | ||
| 712 | waits_.clear(); | 1377 | waits_.clear(); |
| 713 | wait_values_.clear(); | 1378 | wait_values_.clear(); |
| 714 | for (auto& slot : buffers_) | 1379 | for (auto& slot : buffers_) |
| 715 | if (slot.first == command_buffer) slot.second = ticket; | 1380 | if (slot.buffer == command_buffer) slot.ticket = ticket; |
| 716 | return ok; | 1381 | return ok; |
| 717 | } | 1382 | } |
| 718 | 1383 | ||
| 719 | VulkanContext& context_; | 1384 | VulkanContext& context_; |
| 720 | VkQueue queue_; | 1385 | VkQueue queue_; |
| 1386 | QueueKind kind_ = QueueKind::direct; | ||
| 1387 | std::uint32_t family_; | ||
| 721 | VkCommandPool pool_ = VK_NULL_HANDLE; | 1388 | VkCommandPool pool_ = VK_NULL_HANDLE; |
| 722 | VkSemaphore progress_ = VK_NULL_HANDLE; // our own timeline: which command buffers are done | 1389 | VkSemaphore progress_ = VK_NULL_HANDLE; // our own timeline: which command buffers are done |
| 723 | std::uint64_t submitted_ = 0; | 1390 | std::uint64_t submitted_ = 0; |
| 724 | std::vector<std::pair<VkCommandBuffer, std::uint64_t>> buffers_; // buffer, ticket that frees it | 1391 | std::vector<CommandSlot> buffers_; |
| 1392 | std::unique_ptr<OcclusionResolve> occlusion_resolve_; | ||
| 725 | std::vector<VkSemaphore> waits_; | 1393 | std::vector<VkSemaphore> waits_; |
| 726 | std::vector<std::uint64_t> wait_values_; | 1394 | std::vector<std::uint64_t> wait_values_; |
| 727 | std::unique_ptr<BinaryOcclusionResolve> binary_occlusion_; | ||
| 728 | std::uint32_t open_labels_ = 0; // queue labels begun and not ended | 1395 | std::uint32_t open_labels_ = 0; // queue labels begun and not ended |
| 729 | bool ok_ = false; | 1396 | bool ok_ = false; |
| 730 | }; | 1397 | }; |
diff --git a/runtime/src/vulkan_bindless.h b/runtime/src/vulkan_bindless.h index f68b6f292..3bf07fa5d 100644 --- a/runtime/src/vulkan_bindless.h +++ b/runtime/src/vulkan_bindless.h | |||
| @@ -11,14 +11,17 @@ | |||
| 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 translator's 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 | // 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. | ||
| 14 | // | 16 | // |
| 15 | // A shader turns a T# or S# into an index through the hash table (descriptor_table.h) and uses that index in | 17 | // A shader turns a T# or S# into an index through the hash table (descriptor_table.h) and uses that index in |
| 16 | // whichever binding the instruction calls for: the sampled array of the image's dimension, or one of its storage | 18 | // whichever binding the instruction calls for: the sampled array of the image's dimension, or one of its storage |
| 17 | // arrays. So an image has one index, the same in every binding of its dimension, and each dimension has its own | 19 | // arrays. So an image has one index, the same in every binding of its dimension, and each dimension has its own |
| 18 | // index space. The storage arrays hold 256, so an image with storage views gets an index below 256; one without | 20 | // index space. The storage arrays are shorter (storage_capacity()), so an image with storage views gets an index |
| 19 | // takes a higher index while there is one. Index 0 of every array is a fallback, because a miss gives 0: a 1x1 | 21 | // they hold; one without takes a higher index while there is one. Index 0 of every array is a fallback, because a |
| 20 | // image of zeros, a nearest clamping sampler, and 1x1 storage images. The caller owns the views and samplers it | 22 | // miss gives 0: a 1x1 image of zeros, a nearest clamping sampler, and 1x1 storage images. The caller owns the views |
| 21 | // adds and keeps them alive while they are in the set; this class owns only the fallbacks and the table's buffer. | 23 | // and samplers it adds and keeps them alive while they are in the set; this class owns only the fallbacks and the |
| 24 | // table's buffer. | ||
| 22 | // | 25 | // |
| 23 | // Device features: runtimeDescriptorArray for the shaders. With BindlessFeatures::update_after_bind | 26 | // Device features: runtimeDescriptorArray for the shaders. With BindlessFeatures::update_after_bind |
| 24 | // (descriptorBindingSampledImageUpdateAfterBind, ...StorageImage..., ...StorageBuffer...) flush() may run while | 27 | // (descriptorBindingSampledImageUpdateAfterBind, ...StorageImage..., ...StorageBuffer...) flush() may run while |
| @@ -62,12 +65,19 @@ struct StorageViews { | |||
| 62 | VkImageView r32ui = VK_NULL_HANDLE; | 65 | VkImageView r32ui = VK_NULL_HANDLE; |
| 63 | }; | 66 | }; |
| 64 | 67 | ||
| 68 | namespace bindless { | ||
| 69 | inline constexpr std::uint32_t binding_count = 26; | ||
| 70 | constexpr std::array<std::uint32_t, binding_count> default_counts(); | ||
| 71 | } // namespace bindless | ||
| 72 | |||
| 65 | struct BindlessFeatures { | 73 | struct BindlessFeatures { |
| 66 | bool update_after_bind = false; | 74 | bool update_after_bind = false; |
| 67 | bool partially_bound = false; | 75 | bool partially_bound = false; |
| 68 | // Fallback sample counts for RGBA8_UNORM, R32_UINT, R32_SINT. A single sample omits that class's MS bindings. | 76 | // Fallback sample counts for RGBA8_UNORM, R32_UINT, R32_SINT. A single sample omits that class's MS bindings. |
| 69 | std::array<VkSampleCountFlagBits, 3> ms_samples{ | 77 | std::array<VkSampleCountFlagBits, 3> ms_samples{ |
| 70 | VK_SAMPLE_COUNT_1_BIT, VK_SAMPLE_COUNT_1_BIT, VK_SAMPLE_COUNT_1_BIT}; | 78 | VK_SAMPLE_COUNT_1_BIT, VK_SAMPLE_COUNT_1_BIT, VK_SAMPLE_COUNT_1_BIT}; |
| 79 | // Descriptors in each binding, by binding number: bindless::bindings by default, or what size_bindings() chose. | ||
| 80 | std::array<std::uint32_t, bindless::binding_count> counts = bindless::default_counts(); | ||
| 71 | }; | 81 | }; |
| 72 | 82 | ||
| 73 | namespace bindless { | 83 | namespace bindless { |
| @@ -79,7 +89,6 @@ struct Binding { | |||
| 79 | 89 | ||
| 80 | inline constexpr std::uint32_t table_binding = 2; | 90 | inline constexpr std::uint32_t table_binding = 2; |
| 81 | inline constexpr std::uint32_t sampler_binding = 1; | 91 | inline constexpr std::uint32_t sampler_binding = 1; |
| 82 | inline constexpr std::uint32_t storage_indices = 256; // what every storage array of bindings 8-19 holds | ||
| 83 | inline constexpr std::uint32_t first_ms_binding = 20; | 92 | inline constexpr std::uint32_t first_ms_binding = 20; |
| 84 | inline constexpr std::uint32_t no_binding = 0xffffffffu; | 93 | inline constexpr std::uint32_t no_binding = 0xffffffffu; |
| 85 | 94 | ||
| @@ -100,6 +109,14 @@ inline constexpr std::array<Binding, 26> bindings = {{ | |||
| 100 | {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, | 109 | {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, |
| 101 | }}; | 110 | }}; |
| 102 | 111 | ||
| 112 | static_assert(bindings.size() == binding_count); | ||
| 113 | |||
| 114 | constexpr std::array<std::uint32_t, binding_count> default_counts() { | ||
| 115 | std::array<std::uint32_t, binding_count> counts{}; | ||
| 116 | for (std::uint32_t b = 0; b < binding_count; ++b) counts[b] = bindings[b].count; | ||
| 117 | return counts; | ||
| 118 | } | ||
| 119 | |||
| 103 | constexpr bool binding_enabled(std::uint32_t binding, const BindlessFeatures& features) { | 120 | constexpr bool binding_enabled(std::uint32_t binding, const BindlessFeatures& features) { |
| 104 | return binding < first_ms_binding || features.ms_samples[(binding - first_ms_binding) / 2] != VK_SAMPLE_COUNT_1_BIT; | 121 | return binding < first_ms_binding || features.ms_samples[(binding - first_ms_binding) / 2] != VK_SAMPLE_COUNT_1_BIT; |
| 105 | } | 122 | } |
| @@ -108,15 +125,16 @@ constexpr bool binding_enabled(std::uint32_t binding, const BindlessFeatures& fe | |||
| 108 | // per-stage or per-set limits have no room for additional pairs of MS arrays. | 125 | // per-stage or per-set limits have no room for additional pairs of MS arrays. |
| 109 | constexpr void limit_ms_bindings(BindlessFeatures& features, std::uint32_t sampled_limit, | 126 | constexpr void limit_ms_bindings(BindlessFeatures& features, std::uint32_t sampled_limit, |
| 110 | std::uint32_t resource_limit) { | 127 | std::uint32_t resource_limit) { |
| 128 | const auto& counts = features.counts; | ||
| 111 | std::uint32_t sampled = 0, total = 0; | 129 | std::uint32_t sampled = 0, total = 0; |
| 112 | for (std::uint32_t b = 0; b < first_ms_binding; ++b) { | 130 | for (std::uint32_t b = 0; b < first_ms_binding; ++b) { |
| 113 | if (bindings[b].type == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) sampled += bindings[b].count; | 131 | if (bindings[b].type == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) sampled += counts[b]; |
| 114 | if (bindings[b].type != VK_DESCRIPTOR_TYPE_SAMPLER) total += bindings[b].count; | 132 | if (bindings[b].type != VK_DESCRIPTOR_TYPE_SAMPLER) total += counts[b]; |
| 115 | } | 133 | } |
| 116 | for (std::uint32_t c = 0; c < features.ms_samples.size(); ++c) { | 134 | for (std::uint32_t c = 0; c < features.ms_samples.size(); ++c) { |
| 117 | if (features.ms_samples[c] == VK_SAMPLE_COUNT_1_BIT) continue; | 135 | if (features.ms_samples[c] == VK_SAMPLE_COUNT_1_BIT) continue; |
| 118 | const auto b = first_ms_binding + 2 * c; | 136 | const auto b = first_ms_binding + 2 * c; |
| 119 | const auto pair = bindings[b].count + bindings[b + 1].count; | 137 | const auto pair = counts[b] + counts[b + 1]; |
| 120 | if (sampled + pair > sampled_limit || total + pair > resource_limit) { | 138 | if (sampled + pair > sampled_limit || total + pair > resource_limit) { |
| 121 | features.ms_samples[c] = VK_SAMPLE_COUNT_1_BIT; | 139 | features.ms_samples[c] = VK_SAMPLE_COUNT_1_BIT; |
| 122 | } else { | 140 | } else { |
| @@ -126,23 +144,6 @@ constexpr void limit_ms_bindings(BindlessFeatures& features, std::uint32_t sampl | |||
| 126 | } | 144 | } |
| 127 | } | 145 | } |
| 128 | 146 | ||
| 129 | inline void limit_ms_bindings(BindlessFeatures& features, const VkPhysicalDeviceLimits& limits, | ||
| 130 | const VkPhysicalDeviceVulkan12Properties& indexed) { | ||
| 131 | const auto sampled = features.update_after_bind | ||
| 132 | ? std::min(indexed.maxPerStageDescriptorUpdateAfterBindSampledImages, | ||
| 133 | indexed.maxDescriptorSetUpdateAfterBindSampledImages) | ||
| 134 | : std::min(limits.maxPerStageDescriptorSampledImages, limits.maxDescriptorSetSampledImages); | ||
| 135 | auto resources = features.update_after_bind ? indexed.maxPerStageUpdateAfterBindResources : limits.maxPerStageResources; | ||
| 136 | // Fragment outputs count as stage resources. D3D12 allows up to eight render targets. | ||
| 137 | resources -= std::min(resources, std::min(limits.maxColorAttachments, 8u)); | ||
| 138 | if (features.update_after_bind) { | ||
| 139 | // Standalone samplers count in the pool, but do not count against the per-stage resource limit. | ||
| 140 | const auto pool = indexed.maxUpdateAfterBindDescriptorsInAllPools; | ||
| 141 | resources = std::min(resources, pool - std::min(pool, bindings[sampler_binding].count)); | ||
| 142 | } | ||
| 143 | limit_ms_bindings(features, sampled, resources); | ||
| 144 | } | ||
| 145 | |||
| 146 | constexpr bool multisampled(ImageDimension dimension) { | 147 | constexpr bool multisampled(ImageDimension dimension) { |
| 147 | return dimension == ImageDimension::dim_2d_ms || dimension == ImageDimension::dim_2d_ms_array; | 148 | return dimension == ImageDimension::dim_2d_ms || dimension == ImageDimension::dim_2d_ms_array; |
| 148 | } | 149 | } |
| @@ -161,8 +162,114 @@ constexpr std::uint32_t r32ui_binding(ImageDimension dimension) { | |||
| 161 | return dimension == ImageDimension::dim_2d ? 4 : dimension == ImageDimension::dim_3d ? 7 : no_binding; | 162 | return dimension == ImageDimension::dim_2d ? 4 : dimension == ImageDimension::dim_3d ? 7 : no_binding; |
| 162 | } | 163 | } |
| 163 | 164 | ||
| 164 | // How many images of a dimension the set holds, the fallback included. | 165 | // What size_bindings() grows to where the device's limits allow. At 32-64 bytes a descriptor the whole set is then |
| 165 | constexpr std::uint32_t image_capacity(ImageDimension dimension) { return bindings[sampled_binding(dimension)].count; } | 166 | // 3-6 MiB (93793 descriptors on an RTX 5070). |
| 167 | inline constexpr std::uint32_t max_2d_images = 65536; | ||
| 168 | inline constexpr std::uint32_t max_storage_indices = 4096; // in each storage array, at most its dimension's images | ||
| 169 | // A full D3D12 shader-visible sampler heap (2048) and room for literal and static S#s, within what the device can | ||
| 170 | // create (maxSamplerAllocationCount, at least 4000) less the samplers that are not in the set. | ||
| 171 | inline constexpr std::uint32_t max_samplers = 4096; | ||
| 172 | inline constexpr std::uint32_t reserved_samplers = 64; | ||
| 173 | // Growth leaves this many descriptors of each limit to the other sets of a pipeline layout. | ||
| 174 | inline constexpr std::uint32_t growth_headroom = 64; | ||
| 175 | |||
| 176 | // Sizes the 2D image, sampler and storage arrays from the device's limits: the update-after-bind ones with | ||
| 177 | // features.update_after_bind, the plain ones otherwise. Every binding is visible to every stage, so the per-stage | ||
| 178 | // limits apply to the whole set; fragment outputs count as stage resources (D3D12 allows eight render targets) and | ||
| 179 | // standalone samplers do not, though they count in an update-after-bind pool. | ||
| 180 | // 1. The default counts, or as much of them as the device holds: samplers, then storage, then 2D images. | ||
| 181 | // 2. The MS pairs that fit beside them (limit_ms_bindings, which may turn classes off). | ||
| 182 | // 3. Growth towards the maximums above, in the same order, within maxPerSetDescriptors. That limit only says | ||
| 183 | // what is sure to work (vkGetDescriptorSetLayoutSupport may allow more), so it never shrinks step 1. | ||
| 184 | // A storage array holds the smaller of the storage count and its dimension's images: add_image never gives a | ||
| 185 | // storage view an index past the sampled array. The other bindings keep their default counts. | ||
| 186 | // Sets features.counts; returns false when a count is below its default because the device's limits are. | ||
| 187 | inline bool size_bindings(BindlessFeatures& features, const VkPhysicalDeviceLimits& limits, | ||
| 188 | const VkPhysicalDeviceVulkan11Properties& v11, | ||
| 189 | const VkPhysicalDeviceVulkan12Properties& v12) { | ||
| 190 | const bool uab = features.update_after_bind; | ||
| 191 | const std::uint32_t sampled_limit = | ||
| 192 | uab ? std::min(v12.maxPerStageDescriptorUpdateAfterBindSampledImages, | ||
| 193 | v12.maxDescriptorSetUpdateAfterBindSampledImages) | ||
| 194 | : std::min(limits.maxPerStageDescriptorSampledImages, limits.maxDescriptorSetSampledImages); | ||
| 195 | const std::uint32_t sampler_limit = | ||
| 196 | uab ? std::min(v12.maxPerStageDescriptorUpdateAfterBindSamplers, v12.maxDescriptorSetUpdateAfterBindSamplers) | ||
| 197 | : std::min(limits.maxPerStageDescriptorSamplers, limits.maxDescriptorSetSamplers); | ||
| 198 | const std::uint32_t storage_limit = | ||
| 199 | uab ? std::min(v12.maxPerStageDescriptorUpdateAfterBindStorageImages, | ||
| 200 | v12.maxDescriptorSetUpdateAfterBindStorageImages) | ||
| 201 | : std::min(limits.maxPerStageDescriptorStorageImages, limits.maxDescriptorSetStorageImages); | ||
| 202 | std::uint32_t resource_limit = uab ? v12.maxPerStageUpdateAfterBindResources : limits.maxPerStageResources; | ||
| 203 | resource_limit -= std::min(resource_limit, std::min(limits.maxColorAttachments, 8u)); | ||
| 204 | const std::uint32_t pool_limit = uab ? v12.maxUpdateAfterBindDescriptorsInAllPools : 0xffffffffu; | ||
| 205 | |||
| 206 | auto& counts = features.counts; | ||
| 207 | counts = default_counts(); | ||
| 208 | std::uint32_t images = 1, samplers = 1, storage = 1; | ||
| 209 | // Until the end the 2D storage arrays are not capped by the 2D images, which grow after them: capping can only | ||
| 210 | // take descriptors away. | ||
| 211 | const auto apply = [&](bool final) { | ||
| 212 | counts[sampled_binding(ImageDimension::dim_2d)] = images; | ||
| 213 | counts[sampler_binding] = samplers; | ||
| 214 | for (std::uint32_t d = 0; d < 4; ++d) { | ||
| 215 | const auto dimension = ImageDimension(d); | ||
| 216 | const bool capped = final || dimension != ImageDimension::dim_2d; | ||
| 217 | const std::uint32_t held = capped ? std::min(storage, counts[sampled_binding(dimension)]) : storage; | ||
| 218 | for (std::uint32_t c = 0; c < 3; ++c) counts[storage_binding(dimension, c)] = held; | ||
| 219 | if (r32ui_binding(dimension) != no_binding) counts[r32ui_binding(dimension)] = held; | ||
| 220 | } | ||
| 221 | }; | ||
| 222 | const auto fits = [&](std::uint32_t headroom, std::uint64_t set_limit) { | ||
| 223 | apply(false); | ||
| 224 | std::uint64_t sampled = 0, sampler = 0, stored = 0, buffers = 0; | ||
| 225 | for (std::uint32_t b = 0; b < binding_count; ++b) { | ||
| 226 | if (!binding_enabled(b, features)) continue; | ||
| 227 | const auto type = bindings[b].type; | ||
| 228 | (type == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE ? sampled | ||
| 229 | : type == VK_DESCRIPTOR_TYPE_SAMPLER ? sampler | ||
| 230 | : type == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE ? stored | ||
| 231 | : buffers) += counts[b]; | ||
| 232 | } | ||
| 233 | const auto within = [&](std::uint64_t n, std::uint32_t limit) { return n + headroom <= limit; }; | ||
| 234 | const std::uint64_t all = sampled + sampler + stored + buffers; | ||
| 235 | return within(sampled, sampled_limit) && within(sampler, sampler_limit) && within(stored, storage_limit) && | ||
| 236 | within(sampled + stored + buffers, resource_limit) && all <= pool_limit && all <= set_limit; | ||
| 237 | }; | ||
| 238 | // Raises n to the largest value up to `high` that fits; leaves it where it is when none does. | ||
| 239 | const auto grow = [&](std::uint32_t& n, std::uint32_t high, std::uint32_t headroom, std::uint64_t set_limit) { | ||
| 240 | std::uint32_t low = n; | ||
| 241 | while (low < high) { | ||
| 242 | n = low + (high - low + 1) / 2; | ||
| 243 | if (fits(headroom, set_limit)) low = n; | ||
| 244 | else high = n - 1; | ||
| 245 | } | ||
| 246 | n = low; | ||
| 247 | }; | ||
| 248 | |||
| 249 | constexpr std::uint64_t no_limit = ~0ull; | ||
| 250 | const auto ms_samples = features.ms_samples; | ||
| 251 | features.ms_samples.fill(VK_SAMPLE_COUNT_1_BIT); | ||
| 252 | grow(samplers, bindings[sampler_binding].count, 0, no_limit); | ||
| 253 | grow(storage, bindings[storage_binding(ImageDimension::dim_2d, 0)].count, 0, no_limit); | ||
| 254 | grow(images, bindings[sampled_binding(ImageDimension::dim_2d)].count, 0, no_limit); | ||
| 255 | apply(false); | ||
| 256 | const bool full = images == bindings[0].count && samplers == bindings[sampler_binding].count && | ||
| 257 | storage == bindings[storage_binding(ImageDimension::dim_2d, 0)].count; | ||
| 258 | features.ms_samples = ms_samples; | ||
| 259 | limit_ms_bindings(features, sampled_limit, std::min(resource_limit, pool_limit - std::min(pool_limit, samplers))); | ||
| 260 | |||
| 261 | std::uint64_t set_limit = 0; | ||
| 262 | for (std::uint32_t b = 0; b < binding_count; ++b) | ||
| 263 | if (binding_enabled(b, features)) set_limit += counts[b]; | ||
| 264 | set_limit = std::max(set_limit, std::uint64_t(v11.maxPerSetDescriptors)); | ||
| 265 | const std::uint32_t creatable = | ||
| 266 | limits.maxSamplerAllocationCount - std::min(limits.maxSamplerAllocationCount, reserved_samplers); | ||
| 267 | grow(samplers, std::max(samplers, std::min(max_samplers, creatable)), growth_headroom, set_limit); | ||
| 268 | grow(images, std::max(images, max_2d_images), growth_headroom, set_limit); | ||
| 269 | grow(storage, std::max(storage, max_storage_indices), growth_headroom, set_limit); | ||
| 270 | apply(true); | ||
| 271 | return full; | ||
| 272 | } | ||
| 166 | 273 | ||
| 167 | } // namespace bindless | 274 | } // namespace bindless |
| 168 | 275 | ||
| @@ -194,6 +301,15 @@ public: | |||
| 194 | bool supports_ms_class(std::uint32_t component_class) const { | 301 | bool supports_ms_class(std::uint32_t component_class) const { |
| 195 | return component_class < classes && features_.ms_samples[component_class] != VK_SAMPLE_COUNT_1_BIT; | 302 | return component_class < classes && features_.ms_samples[component_class] != VK_SAMPLE_COUNT_1_BIT; |
| 196 | } | 303 | } |
| 304 | // How many images of a dimension the set holds, the fallback included, and how many of the lowest of those | ||
| 305 | // indices its storage arrays hold (0 for the MS dimensions, which have none). The same for samplers. | ||
| 306 | std::uint32_t image_capacity(ImageDimension dimension) const { | ||
| 307 | return features_.counts[bindless::sampled_binding(dimension)]; | ||
| 308 | } | ||
| 309 | std::uint32_t storage_capacity(ImageDimension dimension) const { | ||
| 310 | return bindless::multisampled(dimension) ? 0 : features_.counts[bindless::storage_binding(dimension, 0)]; | ||
| 311 | } | ||
| 312 | std::uint32_t sampler_capacity() const { return features_.counts[bindless::sampler_binding]; } | ||
| 197 | // Set 0 of every pipeline layout made for translated shaders. | 313 | // Set 0 of every pipeline layout made for translated shaders. |
| 198 | VkDescriptorSetLayout layout() const { return layout_; } | 314 | VkDescriptorSetLayout layout() const { return layout_; } |
| 199 | // Bound at set 0. The same set for the life of this object: flush() updates it in place. | 315 | // Bound at set 0. The same set for the life of this object: flush() updates it in place. |
| @@ -239,7 +355,7 @@ public: | |||
| 239 | const bool stores = storage.as_float || storage.as_uint || storage.as_sint || storage.r32ui; | 355 | const bool stores = storage.as_float || storage.as_uint || storage.as_sint || storage.r32ui; |
| 240 | if (bindless::multisampled(dimension) && (stores || !supports_ms_class(sampled_class))) return 0; | 356 | if (bindless::multisampled(dimension) && (stores || !supports_ms_class(sampled_class))) return 0; |
| 241 | auto& used = image_used_[std::uint32_t(dimension)]; | 357 | auto& used = image_used_[std::uint32_t(dimension)]; |
| 242 | const std::uint32_t low_end = std::min(std::uint32_t(used.size()), bindless::storage_indices); | 358 | const std::uint32_t low_end = std::min(std::uint32_t(used.size()), storage_capacity(dimension)); |
| 243 | std::uint32_t index = stores ? 0 : allocate(used, low_end, std::uint32_t(used.size())); | 359 | std::uint32_t index = stores ? 0 : allocate(used, low_end, std::uint32_t(used.size())); |
| 244 | if (!index) index = allocate(used, 1, low_end); | 360 | if (!index) index = allocate(used, 1, low_end); |
| 245 | if (index) write_image(dimension, index, sampled, sampled_layout, storage, sampled_class); | 361 | if (index) write_image(dimension, index, sampled, sampled_layout, storage, sampled_class); |
| @@ -422,10 +538,10 @@ private: | |||
| 422 | std::uint32_t count = 0; | 538 | std::uint32_t count = 0; |
| 423 | for (std::uint32_t b = 0; b < bindless::bindings.size(); ++b) { | 539 | for (std::uint32_t b = 0; b < bindless::bindings.size(); ++b) { |
| 424 | if (!bindless::binding_enabled(b, features_)) continue; | 540 | if (!bindless::binding_enabled(b, features_)) continue; |
| 425 | entries[count] = {b, bindless::bindings[b].type, bindless::bindings[b].count, VK_SHADER_STAGE_ALL, nullptr}; | 541 | entries[count] = {b, bindless::bindings[b].type, features_.counts[b], VK_SHADER_STAGE_ALL, nullptr}; |
| 426 | flags[count] = (features_.update_after_bind ? VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT : 0) | | 542 | flags[count] = (features_.update_after_bind ? VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT : 0) | |
| 427 | (features_.partially_bound ? VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT : 0); | 543 | (features_.partially_bound ? VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT : 0); |
| 428 | sizes[count] = {bindless::bindings[b].type, bindless::bindings[b].count}; | 544 | sizes[count] = {bindless::bindings[b].type, features_.counts[b]}; |
| 429 | ++count; | 545 | ++count; |
| 430 | } | 546 | } |
| 431 | VkDescriptorSetLayoutBindingFlagsCreateInfo flags_info{ | 547 | VkDescriptorSetLayoutBindingFlagsCreateInfo flags_info{ |
| @@ -451,10 +567,10 @@ private: | |||
| 451 | if (vk_.vkAllocateDescriptorSets(device_, &set_info, &set_) != VK_SUCCESS) return false; | 567 | if (vk_.vkAllocateDescriptorSets(device_, &set_info, &set_) != VK_SUCCESS) return false; |
| 452 | 568 | ||
| 453 | for (std::uint32_t d = 0; d < dimensions; ++d) { | 569 | for (std::uint32_t d = 0; d < dimensions; ++d) { |
| 454 | image_used_[d].assign(bindless::image_capacity(ImageDimension(d)), 0); | 570 | image_used_[d].assign(image_capacity(ImageDimension(d)), 0); |
| 455 | image_used_[d][0] = 1; | 571 | image_used_[d][0] = 1; |
| 456 | } | 572 | } |
| 457 | sampler_used_.assign(bindless::bindings[bindless::sampler_binding].count, 0); | 573 | sampler_used_.assign(sampler_capacity(), 0); |
| 458 | sampler_used_[0] = 1; | 574 | sampler_used_[0] = 1; |
| 459 | return true; | 575 | return true; |
| 460 | } | 576 | } |
| @@ -716,7 +832,7 @@ private: | |||
| 716 | infos.reserve(bindless::bindings.size()); | 832 | infos.reserve(bindless::bindings.size()); |
| 717 | for (std::uint32_t b = 0; b < bindless::bindings.size(); ++b) { | 833 | for (std::uint32_t b = 0; b < bindless::bindings.size(); ++b) { |
| 718 | if (b == bindless::table_binding || !bindless::binding_enabled(b, features_)) continue; | 834 | if (b == bindless::table_binding || !bindless::binding_enabled(b, features_)) continue; |
| 719 | const std::uint32_t count = features_.partially_bound ? 1 : bindless::bindings[b].count; | 835 | const std::uint32_t count = features_.partially_bound ? 1 : features_.counts[b]; |
| 720 | infos.emplace_back(count, fallback_info(b)); | 836 | infos.emplace_back(count, fallback_info(b)); |
| 721 | VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET}; | 837 | VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET}; |
| 722 | write.dstSet = set_; | 838 | write.dstSet = set_; |
| @@ -762,7 +878,7 @@ private: | |||
| 762 | queue(sampled_at, index, | 878 | queue(sampled_at, index, |
| 763 | sampled ? VkDescriptorImageInfo{VK_NULL_HANDLE, sampled, sampled_layout} : fallback_info(sampled_at)); | 879 | sampled ? VkDescriptorImageInfo{VK_NULL_HANDLE, sampled, sampled_layout} : fallback_info(sampled_at)); |
| 764 | const auto store = [&](std::uint32_t binding, VkImageView view) { | 880 | const auto store = [&](std::uint32_t binding, VkImageView view) { |
| 765 | if (binding == bindless::no_binding || index >= bindless::bindings[binding].count) return; | 881 | if (binding == bindless::no_binding || index >= features_.counts[binding]) return; |
| 766 | queue(binding, index, | 882 | queue(binding, index, |
| 767 | view ? VkDescriptorImageInfo{VK_NULL_HANDLE, view, VK_IMAGE_LAYOUT_GENERAL} : fallback_info(binding)); | 883 | view ? VkDescriptorImageInfo{VK_NULL_HANDLE, view, VK_IMAGE_LAYOUT_GENERAL} : fallback_info(binding)); |
| 768 | }; | 884 | }; |
diff --git a/runtime/src/vulkan_predicate.h b/runtime/src/vulkan_predicate.h new file mode 100644 index 000000000..cedb8af81 --- /dev/null +++ b/runtime/src/vulkan_predicate.h | |||
| @@ -0,0 +1,183 @@ | |||
| 1 | // GPU snapshot of D3D12's 64-bit predicate. No host readback and no per-predicate queue wait. | ||
| 2 | #pragma once | ||
| 3 | #ifndef VK_NO_PROTOTYPES | ||
| 4 | #define VK_NO_PROTOTYPES | ||
| 5 | #endif | ||
| 6 | #include <vulkan/vulkan.h> | ||
| 7 | #include <cstdint> | ||
| 8 | #include <memory> | ||
| 9 | #include <initializer_list> | ||
| 10 | #include "predicate_reduce_spv.h" | ||
| 11 | |||
| 12 | namespace leonida { | ||
| 13 | struct PredicateCapture { | ||
| 14 | VkBuffer source = VK_NULL_HANDLE; | ||
| 15 | VkDeviceSize source_offset = 0; | ||
| 16 | VkBuffer scratch = VK_NULL_HANDLE; | ||
| 17 | VkDeviceSize offset = 0; // two input words, then the reduced condition | ||
| 18 | VkDescriptorSet set = VK_NULL_HANDLE; | ||
| 19 | }; | ||
| 20 | |||
| 21 | class PredicateReducer { | ||
| 22 | public: | ||
| 23 | PredicateReducer(PFN_vkGetDeviceProcAddr get, VkDevice device, VkPhysicalDeviceMemoryProperties memory, | ||
| 24 | VkDeviceSize max_range) : get_(get), device_(device), memory_(memory), max_range_(max_range) {} | ||
| 25 | ~PredicateReducer() { | ||
| 26 | if (pipeline_) fn<PFN_vkDestroyPipeline>("vkDestroyPipeline")(device_, pipeline_, nullptr); | ||
| 27 | if (layout_) fn<PFN_vkDestroyPipelineLayout>("vkDestroyPipelineLayout")(device_, layout_, nullptr); | ||
| 28 | if (set_layout_) fn<PFN_vkDestroyDescriptorSetLayout>("vkDestroyDescriptorSetLayout")(device_, set_layout_, nullptr); | ||
| 29 | } | ||
| 30 | PredicateReducer(const PredicateReducer&) = delete; | ||
| 31 | PredicateReducer& operator=(const PredicateReducer&) = delete; | ||
| 32 | |||
| 33 | // Owned by a command-buffer slot until its timeline ticket completes (or a failed recording is reset). | ||
| 34 | struct Batch { | ||
| 35 | PredicateReducer& owner; | ||
| 36 | VkBuffer buffer = VK_NULL_HANDLE; | ||
| 37 | VkDeviceMemory memory = VK_NULL_HANDLE; | ||
| 38 | VkDescriptorPool pool = VK_NULL_HANDLE; | ||
| 39 | VkDescriptorSet set = VK_NULL_HANDLE; | ||
| 40 | VkDeviceSize bytes = 0; | ||
| 41 | std::uint32_t count = 0, next = 0; | ||
| 42 | explicit Batch(PredicateReducer& r) : owner(r) {} | ||
| 43 | ~Batch() { | ||
| 44 | if (pool) owner.fn<PFN_vkDestroyDescriptorPool>("vkDestroyDescriptorPool")(owner.device_, pool, nullptr); | ||
| 45 | if (buffer) owner.fn<PFN_vkDestroyBuffer>("vkDestroyBuffer")(owner.device_, buffer, nullptr); | ||
| 46 | if (memory) owner.fn<PFN_vkFreeMemory>("vkFreeMemory")(owner.device_, memory, nullptr); | ||
| 47 | } | ||
| 48 | Batch(const Batch&) = delete; | ||
| 49 | Batch& operator=(const Batch&) = delete; | ||
| 50 | bool prepare(VkBuffer source, VkDeviceSize offset, PredicateCapture& out) { | ||
| 51 | if (next >= count || !source) return false; | ||
| 52 | out = {source, offset, buffer, VkDeviceSize(next++) * 16, set}; | ||
| 53 | return true; | ||
| 54 | } | ||
| 55 | }; | ||
| 56 | |||
| 57 | std::unique_ptr<Batch> batch(std::uint64_t count) { | ||
| 58 | // One descriptor starts at offset zero; a push constant selects each aligned 16-byte slot. | ||
| 59 | if (!count || count > max_range_ / 16 || count > UINT32_MAX / 4 || !make_pipeline()) return {}; | ||
| 60 | auto b = std::make_unique<Batch>(*this); | ||
| 61 | b->count = static_cast<std::uint32_t>(count); | ||
| 62 | b->bytes = count * 16; | ||
| 63 | VkBufferCreateInfo buffer{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; | ||
| 64 | buffer.size = b->bytes; | ||
| 65 | buffer.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | | ||
| 66 | VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT; | ||
| 67 | if (fn<PFN_vkCreateBuffer>("vkCreateBuffer")(device_, &buffer, nullptr, &b->buffer) != VK_SUCCESS) return {}; | ||
| 68 | VkMemoryRequirements requirements{}; | ||
| 69 | fn<PFN_vkGetBufferMemoryRequirements>("vkGetBufferMemoryRequirements")(device_, b->buffer, &requirements); | ||
| 70 | std::uint32_t type = UINT32_MAX; | ||
| 71 | for (std::uint32_t i = 0; i < memory_.memoryTypeCount; ++i) { | ||
| 72 | if (!(requirements.memoryTypeBits & (1u << i))) continue; | ||
| 73 | if (type == UINT32_MAX) type = i; | ||
| 74 | if (memory_.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) { type = i; break; } | ||
| 75 | } | ||
| 76 | if (type == UINT32_MAX) return {}; | ||
| 77 | VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; | ||
| 78 | allocation.allocationSize = requirements.size; | ||
| 79 | allocation.memoryTypeIndex = type; | ||
| 80 | if (fn<PFN_vkAllocateMemory>("vkAllocateMemory")(device_, &allocation, nullptr, &b->memory) != VK_SUCCESS || | ||
| 81 | fn<PFN_vkBindBufferMemory>("vkBindBufferMemory")(device_, b->buffer, b->memory, 0) != VK_SUCCESS) return {}; | ||
| 82 | const VkDescriptorPoolSize size{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}; | ||
| 83 | VkDescriptorPoolCreateInfo pool{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; | ||
| 84 | pool.maxSets = 1; pool.poolSizeCount = 1; pool.pPoolSizes = &size; | ||
| 85 | if (fn<PFN_vkCreateDescriptorPool>("vkCreateDescriptorPool")(device_, &pool, nullptr, &b->pool) != VK_SUCCESS) return {}; | ||
| 86 | VkDescriptorSetAllocateInfo sets{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; | ||
| 87 | sets.descriptorPool = b->pool; sets.descriptorSetCount = 1; sets.pSetLayouts = &set_layout_; | ||
| 88 | if (fn<PFN_vkAllocateDescriptorSets>("vkAllocateDescriptorSets")(device_, &sets, &b->set) != VK_SUCCESS) return {}; | ||
| 89 | const VkDescriptorBufferInfo info{b->buffer, 0, b->bytes}; | ||
| 90 | VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET}; | ||
| 91 | write.dstSet = b->set; write.dstBinding = 0; write.descriptorCount = 1; | ||
| 92 | write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; write.pBufferInfo = &info; | ||
| 93 | fn<PFN_vkUpdateDescriptorSets>("vkUpdateDescriptorSets")(device_, 1, &write, 0, nullptr); | ||
| 94 | return b; | ||
| 95 | } | ||
| 96 | |||
| 97 | void capture(VkCommandBuffer cb, const PredicateCapture& p) const { | ||
| 98 | // End an earlier conditional scope before entering this helper: dispatch is itself conditional. | ||
| 99 | // The descriptor spans the arena, so order all prior accesses before reusing it for another slot. | ||
| 100 | VkMemoryBarrier before{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; | ||
| 101 | before.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT | VK_ACCESS_MEMORY_READ_BIT; | ||
| 102 | before.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT; | ||
| 103 | const auto barrier = fn<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier"); | ||
| 104 | barrier(cb, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1, &before, 0, nullptr, 0, nullptr); | ||
| 105 | const VkBufferCopy copy{p.source_offset, p.offset, 8}; | ||
| 106 | fn<PFN_vkCmdCopyBuffer>("vkCmdCopyBuffer")(cb, p.source, p.scratch, 1, ©); | ||
| 107 | // The application's PREDICATION state does not describe this internal transfer read. Preserve snapshot | ||
| 108 | // semantics when it subsequently transitions and overwrites the source in the same command list. | ||
| 109 | VkBufferMemoryBarrier source_done{VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER}; | ||
| 110 | source_done.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT; | ||
| 111 | source_done.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; | ||
| 112 | source_done.srcQueueFamilyIndex = source_done.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; | ||
| 113 | source_done.buffer = p.source; source_done.offset = p.source_offset; source_done.size = 8; | ||
| 114 | barrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, | ||
| 115 | 0, 0, nullptr, 1, &source_done, 0, nullptr); | ||
| 116 | VkMemoryBarrier compute{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; | ||
| 117 | compute.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; | ||
| 118 | compute.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; | ||
| 119 | barrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1, &compute, 0, nullptr, 0, nullptr); | ||
| 120 | fn<PFN_vkCmdBindPipeline>("vkCmdBindPipeline")(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_); | ||
| 121 | fn<PFN_vkCmdBindDescriptorSets>("vkCmdBindDescriptorSets")(cb, VK_PIPELINE_BIND_POINT_COMPUTE, layout_, 0, 1, &p.set, 0, nullptr); | ||
| 122 | const std::uint32_t index = static_cast<std::uint32_t>(p.offset / 4); | ||
| 123 | fn<PFN_vkCmdPushConstants>("vkCmdPushConstants")(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, 4, &index); | ||
| 124 | fn<PFN_vkCmdDispatch>("vkCmdDispatch")(cb, 1, 1, 1); | ||
| 125 | VkMemoryBarrier condition{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; | ||
| 126 | condition.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; | ||
| 127 | condition.dstAccessMask = VK_ACCESS_CONDITIONAL_RENDERING_READ_BIT_EXT; | ||
| 128 | barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_CONDITIONAL_RENDERING_BIT_EXT, | ||
| 129 | 0, 1, &condition, 0, nullptr, 0, nullptr); | ||
| 130 | } | ||
| 131 | |||
| 132 | private: | ||
| 133 | template<class T> T fn(const char* name) const { return reinterpret_cast<T>(get_(device_, name)); } | ||
| 134 | bool make_pipeline() { | ||
| 135 | if (pipeline_) return true; | ||
| 136 | // No entry-point assumptions for partial/mock devices: fail before allocating or recording anything. | ||
| 137 | for (const char* name : {"vkCreateBuffer", "vkDestroyBuffer", "vkGetBufferMemoryRequirements", "vkAllocateMemory", | ||
| 138 | "vkFreeMemory", "vkBindBufferMemory", "vkCreateDescriptorPool", "vkDestroyDescriptorPool", | ||
| 139 | "vkAllocateDescriptorSets", "vkUpdateDescriptorSets", "vkCreateShaderModule", "vkDestroyShaderModule", | ||
| 140 | "vkCreateDescriptorSetLayout", "vkDestroyDescriptorSetLayout", "vkCreatePipelineLayout", | ||
| 141 | "vkDestroyPipelineLayout", "vkCreateComputePipelines", "vkDestroyPipeline", "vkCmdCopyBuffer", | ||
| 142 | "vkCmdPipelineBarrier", "vkCmdBindPipeline", "vkCmdBindDescriptorSets", "vkCmdPushConstants", "vkCmdDispatch"}) | ||
| 143 | if (!get_(device_, name)) return false; | ||
| 144 | VkDescriptorSetLayout set = VK_NULL_HANDLE; | ||
| 145 | VkPipelineLayout layout = VK_NULL_HANDLE; | ||
| 146 | VkShaderModule shader = VK_NULL_HANDLE; | ||
| 147 | VkPipeline pipeline = VK_NULL_HANDLE; | ||
| 148 | const VkDescriptorSetLayoutBinding binding{0, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; | ||
| 149 | VkDescriptorSetLayoutCreateInfo set_info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; | ||
| 150 | set_info.bindingCount = 1; set_info.pBindings = &binding; | ||
| 151 | bool ok = fn<PFN_vkCreateDescriptorSetLayout>("vkCreateDescriptorSetLayout")(device_, &set_info, nullptr, &set) == VK_SUCCESS; | ||
| 152 | const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, 4}; | ||
| 153 | VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; | ||
| 154 | layout_info.setLayoutCount = 1; layout_info.pSetLayouts = &set; | ||
| 155 | layout_info.pushConstantRangeCount = 1; layout_info.pPushConstantRanges = &push; | ||
| 156 | ok = ok && fn<PFN_vkCreatePipelineLayout>("vkCreatePipelineLayout")(device_, &layout_info, nullptr, &layout) == VK_SUCCESS; | ||
| 157 | VkShaderModuleCreateInfo module{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; | ||
| 158 | module.codeSize = sizeof(predicate_reduce_spirv); module.pCode = predicate_reduce_spirv; | ||
| 159 | ok = ok && fn<PFN_vkCreateShaderModule>("vkCreateShaderModule")(device_, &module, nullptr, &shader) == VK_SUCCESS; | ||
| 160 | VkComputePipelineCreateInfo info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; | ||
| 161 | info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; | ||
| 162 | info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; info.stage.module = shader; info.stage.pName = "main"; | ||
| 163 | info.layout = layout; | ||
| 164 | ok = ok && fn<PFN_vkCreateComputePipelines>("vkCreateComputePipelines")(device_, VK_NULL_HANDLE, 1, &info, nullptr, &pipeline) == VK_SUCCESS; | ||
| 165 | if (shader) fn<PFN_vkDestroyShaderModule>("vkDestroyShaderModule")(device_, shader, nullptr); | ||
| 166 | if (!ok) { | ||
| 167 | if (pipeline) fn<PFN_vkDestroyPipeline>("vkDestroyPipeline")(device_, pipeline, nullptr); | ||
| 168 | if (layout) fn<PFN_vkDestroyPipelineLayout>("vkDestroyPipelineLayout")(device_, layout, nullptr); | ||
| 169 | if (set) fn<PFN_vkDestroyDescriptorSetLayout>("vkDestroyDescriptorSetLayout")(device_, set, nullptr); | ||
| 170 | return false; | ||
| 171 | } | ||
| 172 | set_layout_ = set; layout_ = layout; pipeline_ = pipeline; | ||
| 173 | return true; | ||
| 174 | } | ||
| 175 | PFN_vkGetDeviceProcAddr get_; | ||
| 176 | VkDevice device_; | ||
| 177 | VkPhysicalDeviceMemoryProperties memory_; | ||
| 178 | VkDeviceSize max_range_; | ||
| 179 | VkDescriptorSetLayout set_layout_ = VK_NULL_HANDLE; | ||
| 180 | VkPipelineLayout layout_ = VK_NULL_HANDLE; | ||
| 181 | VkPipeline pipeline_ = VK_NULL_HANDLE; | ||
| 182 | }; | ||
| 183 | } // namespace leonida | ||
diff --git a/runtime/src/vulkan_predicated_copy.h b/runtime/src/vulkan_predicated_copy.h new file mode 100644 index 000000000..6a225ced7 --- /dev/null +++ b/runtime/src/vulkan_predicated_copy.h | |||
| @@ -0,0 +1,154 @@ | |||
| 1 | // Byte-granular conditional CopyBufferRegion. Requires enabled storageBuffer8BitAccess, not shaderInt8. | ||
| 2 | #pragma once | ||
| 3 | #ifndef VK_NO_PROTOTYPES | ||
| 4 | #define VK_NO_PROTOTYPES | ||
| 5 | #endif | ||
| 6 | #include <vulkan/vulkan.h> | ||
| 7 | #include <algorithm> | ||
| 8 | #include <cstdint> | ||
| 9 | #include <memory> | ||
| 10 | #include <initializer_list> | ||
| 11 | #include <vector> | ||
| 12 | #include "predicated_copy_spv.h" | ||
| 13 | namespace leonida { | ||
| 14 | struct PredicatedCopyDispatch { | ||
| 15 | VkDescriptorSet set = VK_NULL_HANDLE; | ||
| 16 | std::uint32_t source = 0, destination = 0, bytes = 0; | ||
| 17 | }; | ||
| 18 | class PredicatedBufferCopier { | ||
| 19 | public: | ||
| 20 | PredicatedBufferCopier(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceLimits& limits) | ||
| 21 | : get_(get), device_(device), limits_(limits) {} | ||
| 22 | ~PredicatedBufferCopier() { | ||
| 23 | if(pipeline_)fn<PFN_vkDestroyPipeline>("vkDestroyPipeline")(device_,pipeline_,nullptr); | ||
| 24 | if(layout_)fn<PFN_vkDestroyPipelineLayout>("vkDestroyPipelineLayout")(device_,layout_,nullptr); | ||
| 25 | if(set_layout_)fn<PFN_vkDestroyDescriptorSetLayout>("vkDestroyDescriptorSetLayout")(device_,set_layout_,nullptr); | ||
| 26 | } | ||
| 27 | PredicatedBufferCopier(const PredicatedBufferCopier&)=delete; | ||
| 28 | PredicatedBufferCopier& operator=(const PredicatedBufferCopier&)=delete; | ||
| 29 | struct Batch { | ||
| 30 | PredicatedBufferCopier& owner; | ||
| 31 | std::vector<VkDescriptorPool> pools; | ||
| 32 | explicit Batch(PredicatedBufferCopier& value):owner(value){} | ||
| 33 | ~Batch(){for(auto pool:pools)owner.fn<PFN_vkDestroyDescriptorPool>("vkDestroyDescriptorPool")(owner.device_,pool,nullptr);} | ||
| 34 | bool prepare(VkBuffer source,VkBuffer destination,VkDeviceSize src,VkDeviceSize dst,VkDeviceSize bytes, | ||
| 35 | std::vector<PredicatedCopyDispatch>& out) { | ||
| 36 | out.clear(); | ||
| 37 | if(!bytes)return true; | ||
| 38 | if(!source||!destination||bytes>UINT64_MAX-src||bytes>UINT64_MAX-dst)return false; | ||
| 39 | if(source==destination && src<dst+bytes && dst<src+bytes)return false; | ||
| 40 | if(!owner.make_pipeline())return false; | ||
| 41 | // Align each descriptor base down, keeping byte prefixes in push constants. Split at the smaller | ||
| 42 | // remaining descriptor range or dispatch limit, so no uint32 shader index can wrap or overread. | ||
| 43 | struct Window{VkDescriptorBufferInfo source,destination;std::uint32_t src,dst,bytes;}; | ||
| 44 | std::vector<Window> windows; | ||
| 45 | const auto alignment=std::max<VkDeviceSize>(1,owner.limits_.minStorageBufferOffsetAlignment); | ||
| 46 | const VkDeviceSize maximum=owner.limits_.maxStorageBufferRange; | ||
| 47 | const VkDeviceSize threads=VkDeviceSize(owner.limits_.maxComputeWorkGroupCount[0])*64; | ||
| 48 | for(VkDeviceSize done=0;done<bytes;){ | ||
| 49 | const auto s=src+done,d=dst+done,sp=s%alignment,dp=d%alignment; | ||
| 50 | if(sp>=maximum||dp>=maximum||!threads)return false; | ||
| 51 | const auto n=std::min({bytes-done,maximum-sp,maximum-dp,threads}); | ||
| 52 | if(!n||n>UINT32_MAX)return false; | ||
| 53 | windows.push_back({{source,s-sp,sp+n},{destination,d-dp,dp+n}, | ||
| 54 | static_cast<std::uint32_t>(sp),static_cast<std::uint32_t>(dp),static_cast<std::uint32_t>(n)}); | ||
| 55 | if(windows.size()>UINT32_MAX/2)return false; | ||
| 56 | done+=n; | ||
| 57 | } | ||
| 58 | const auto count=static_cast<std::uint32_t>(windows.size()); | ||
| 59 | const VkDescriptorPoolSize size{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,count*2}; | ||
| 60 | VkDescriptorPoolCreateInfo pool_info{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; | ||
| 61 | pool_info.maxSets=count;pool_info.poolSizeCount=1;pool_info.pPoolSizes=&size; | ||
| 62 | VkDescriptorPool pool=VK_NULL_HANDLE; | ||
| 63 | if(owner.fn<PFN_vkCreateDescriptorPool>("vkCreateDescriptorPool")(owner.device_,&pool_info,nullptr,&pool)!=VK_SUCCESS)return false; | ||
| 64 | // The batch is retained with the command buffer until its timeline ticket completes. | ||
| 65 | pools.push_back(pool); | ||
| 66 | const std::vector<VkDescriptorSetLayout> layouts(count,owner.set_layout_); | ||
| 67 | std::vector<VkDescriptorSet> sets(count); | ||
| 68 | VkDescriptorSetAllocateInfo allocate{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; | ||
| 69 | allocate.descriptorPool=pool;allocate.descriptorSetCount=count;allocate.pSetLayouts=layouts.data(); | ||
| 70 | if(owner.fn<PFN_vkAllocateDescriptorSets>("vkAllocateDescriptorSets")(owner.device_,&allocate,sets.data())!=VK_SUCCESS)return false; | ||
| 71 | for(std::uint32_t i=0;i<count;++i){ | ||
| 72 | VkWriteDescriptorSet writes[2]{}; | ||
| 73 | const VkDescriptorBufferInfo* infos[]={&windows[i].source,&windows[i].destination}; | ||
| 74 | for(std::uint32_t binding=0;binding<2;++binding){ | ||
| 75 | auto& w=writes[binding];w.sType=VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;w.dstSet=sets[i]; | ||
| 76 | w.dstBinding=binding;w.descriptorCount=1;w.descriptorType=VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;w.pBufferInfo=infos[binding]; | ||
| 77 | } | ||
| 78 | owner.fn<PFN_vkUpdateDescriptorSets>("vkUpdateDescriptorSets")(owner.device_,2,writes,0,nullptr); | ||
| 79 | out.push_back({sets[i],windows[i].src,windows[i].dst,windows[i].bytes}); | ||
| 80 | } | ||
| 81 | return true; | ||
| 82 | } | ||
| 83 | }; | ||
| 84 | std::unique_ptr<Batch> batch(){return std::make_unique<Batch>(*this);} | ||
| 85 | void emit(VkCommandBuffer cb,const std::vector<PredicatedCopyDispatch>& jobs)const{ | ||
| 86 | const auto barrier=fn<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier"); | ||
| 87 | // Barriers are unconditional even when the dispatch is skipped by conditional rendering. They order | ||
| 88 | // transfer producers, dependent copies, and adjacent windows whose aligned descriptors may overlap. | ||
| 89 | for(const auto& job:jobs){ | ||
| 90 | VkMemoryBarrier before{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; | ||
| 91 | before.srcAccessMask=VK_ACCESS_MEMORY_WRITE_BIT|VK_ACCESS_MEMORY_READ_BIT; | ||
| 92 | before.dstAccessMask=VK_ACCESS_SHADER_READ_BIT|VK_ACCESS_SHADER_WRITE_BIT; | ||
| 93 | barrier(cb,VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,0,1,&before,0,nullptr,0,nullptr); | ||
| 94 | fn<PFN_vkCmdBindPipeline>("vkCmdBindPipeline")(cb,VK_PIPELINE_BIND_POINT_COMPUTE,pipeline_); | ||
| 95 | fn<PFN_vkCmdBindDescriptorSets>("vkCmdBindDescriptorSets")(cb,VK_PIPELINE_BIND_POINT_COMPUTE,layout_,0,1,&job.set,0,nullptr); | ||
| 96 | const std::uint32_t push[]={job.source,job.destination,job.bytes}; | ||
| 97 | fn<PFN_vkCmdPushConstants>("vkCmdPushConstants")(cb,layout_,VK_SHADER_STAGE_COMPUTE_BIT,0,sizeof(push),push); | ||
| 98 | fn<PFN_vkCmdDispatch>("vkCmdDispatch")(cb,(job.bytes-1u)/64u+1u,1,1); | ||
| 99 | VkMemoryBarrier after{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; | ||
| 100 | after.srcAccessMask=VK_ACCESS_SHADER_WRITE_BIT|VK_ACCESS_SHADER_READ_BIT; | ||
| 101 | after.dstAccessMask=VK_ACCESS_MEMORY_READ_BIT|VK_ACCESS_MEMORY_WRITE_BIT; | ||
| 102 | barrier(cb,VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,0,1,&after,0,nullptr,0,nullptr); | ||
| 103 | } | ||
| 104 | } | ||
| 105 | private: | ||
| 106 | template<class T>T fn(const char* name)const{return reinterpret_cast<T>(get_(device_,name));} | ||
| 107 | bool make_pipeline() { | ||
| 108 | if (pipeline_) return true; | ||
| 109 | // No entry-point assumptions for partial/mock devices: fail before allocating or recording anything. | ||
| 110 | for (const char* name : {"vkCreateDescriptorPool", "vkDestroyDescriptorPool", | ||
| 111 | "vkAllocateDescriptorSets", "vkUpdateDescriptorSets", "vkCreateShaderModule", "vkDestroyShaderModule", | ||
| 112 | "vkCreateDescriptorSetLayout", "vkDestroyDescriptorSetLayout", "vkCreatePipelineLayout", | ||
| 113 | "vkDestroyPipelineLayout", "vkCreateComputePipelines", "vkDestroyPipeline", | ||
| 114 | "vkCmdPipelineBarrier", "vkCmdBindPipeline", "vkCmdBindDescriptorSets", "vkCmdPushConstants", "vkCmdDispatch"}) | ||
| 115 | if (!get_(device_, name)) return false; | ||
| 116 | VkDescriptorSetLayout set = VK_NULL_HANDLE; | ||
| 117 | VkPipelineLayout layout = VK_NULL_HANDLE; | ||
| 118 | VkShaderModule shader = VK_NULL_HANDLE; | ||
| 119 | VkPipeline pipeline = VK_NULL_HANDLE; | ||
| 120 | const VkDescriptorSetLayoutBinding bindings[]={{0,VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,1,VK_SHADER_STAGE_COMPUTE_BIT,nullptr},{1,VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,1,VK_SHADER_STAGE_COMPUTE_BIT,nullptr}}; | ||
| 121 | VkDescriptorSetLayoutCreateInfo set_info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; | ||
| 122 | set_info.bindingCount = 2; set_info.pBindings = bindings; | ||
| 123 | bool ok = fn<PFN_vkCreateDescriptorSetLayout>("vkCreateDescriptorSetLayout")(device_, &set_info, nullptr, &set) == VK_SUCCESS; | ||
| 124 | const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, 12}; | ||
| 125 | VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; | ||
| 126 | layout_info.setLayoutCount = 1; layout_info.pSetLayouts = &set; | ||
| 127 | layout_info.pushConstantRangeCount = 1; layout_info.pPushConstantRanges = &push; | ||
| 128 | ok = ok && fn<PFN_vkCreatePipelineLayout>("vkCreatePipelineLayout")(device_, &layout_info, nullptr, &layout) == VK_SUCCESS; | ||
| 129 | VkShaderModuleCreateInfo module{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; | ||
| 130 | module.codeSize = sizeof(predicated_copy_spirv); module.pCode = predicated_copy_spirv; | ||
| 131 | ok = ok && fn<PFN_vkCreateShaderModule>("vkCreateShaderModule")(device_, &module, nullptr, &shader) == VK_SUCCESS; | ||
| 132 | VkComputePipelineCreateInfo info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; | ||
| 133 | info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; | ||
| 134 | info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; info.stage.module = shader; info.stage.pName = "main"; | ||
| 135 | info.layout = layout; | ||
| 136 | ok = ok && fn<PFN_vkCreateComputePipelines>("vkCreateComputePipelines")(device_, VK_NULL_HANDLE, 1, &info, nullptr, &pipeline) == VK_SUCCESS; | ||
| 137 | if (shader) fn<PFN_vkDestroyShaderModule>("vkDestroyShaderModule")(device_, shader, nullptr); | ||
| 138 | if (!ok) { | ||
| 139 | if (pipeline) fn<PFN_vkDestroyPipeline>("vkDestroyPipeline")(device_, pipeline, nullptr); | ||
| 140 | if (layout) fn<PFN_vkDestroyPipelineLayout>("vkDestroyPipelineLayout")(device_, layout, nullptr); | ||
| 141 | if (set) fn<PFN_vkDestroyDescriptorSetLayout>("vkDestroyDescriptorSetLayout")(device_, set, nullptr); | ||
| 142 | return false; | ||
| 143 | } | ||
| 144 | set_layout_ = set; layout_ = layout; pipeline_ = pipeline; | ||
| 145 | return true; | ||
| 146 | } | ||
| 147 | PFN_vkGetDeviceProcAddr get_; | ||
| 148 | VkDevice device_; | ||
| 149 | VkPhysicalDeviceLimits limits_; | ||
| 150 | VkDescriptorSetLayout set_layout_=VK_NULL_HANDLE; | ||
| 151 | VkPipelineLayout layout_=VK_NULL_HANDLE; | ||
| 152 | VkPipeline pipeline_=VK_NULL_HANDLE; | ||
| 153 | }; | ||
| 154 | } | ||
diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index f42be50a3..6df4beba5 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h | |||
| @@ -24,6 +24,8 @@ | |||
| 24 | // rectangles need color_attachment usage on the image (ResourceBinding::color_attachment); | 24 | // rectangles need color_attachment usage on the image (ResourceBinding::color_attachment); |
| 25 | // - query commands need the query functions, fill_buffer and query_pool; resolve destinations have TRANSFER_DST | 25 | // - query commands need the query functions, fill_buffer and query_pool; resolve destinations have TRANSFER_DST |
| 26 | // usage and binary occlusion resolves need resolve_binary_occlusion. | 26 | // usage and binary occlusion resolves need resolve_binary_occlusion. |
| 27 | // - predicated buffer copies need the byte-copy helper and buffers with STORAGE_BUFFER usage; helper descriptors | ||
| 28 | // must remain alive through submission completion (VulkanQueue owns them). | ||
| 27 | // A list that needs a missing function fails with ReplayResult::unsupported before anything is written. | 29 | // A list that needs a missing function fails with ReplayResult::unsupported before anything is written. |
| 28 | 30 | ||
| 29 | #include "command_list.h" | 31 | #include "command_list.h" |
| @@ -31,12 +33,16 @@ | |||
| 31 | #include "uav_clear.h" | 33 | #include "uav_clear.h" |
| 32 | 34 | ||
| 33 | #include <vulkan/vulkan.h> | 35 | #include <vulkan/vulkan.h> |
| 36 | #include "vulkan_predicate.h" | ||
| 37 | #include "vulkan_predicated_copy.h" | ||
| 34 | 38 | ||
| 35 | #include <algorithm> | 39 | #include <algorithm> |
| 36 | #include <array> | 40 | #include <array> |
| 37 | #include <cstdint> | 41 | #include <cstdint> |
| 38 | #include <functional> | 42 | #include <functional> |
| 39 | #include <limits> | 43 | #include <limits> |
| 44 | #include <map> | ||
| 45 | #include <memory> | ||
| 40 | #include <type_traits> | 46 | #include <type_traits> |
| 41 | #include <unordered_map> | 47 | #include <unordered_map> |
| 42 | #include <utility> | 48 | #include <utility> |
| @@ -74,6 +80,7 @@ struct ResourceBinding { | |||
| 74 | bool depth24_as_float = false; | 80 | bool depth24_as_float = false; |
| 75 | bool depth24 = false; // a D24 family format, native or not: depth clears are quantised to 24 bits first | 81 | bool depth24 = false; // a D24 family format, native or not: depth clears are quantised to 24 bits first |
| 76 | bool color_attachment = false; // has COLOR_ATTACHMENT usage: unordered-access rectangle clears need it | 82 | bool color_attachment = false; // has COLOR_ATTACHMENT usage: unordered-access rectangle clears need it |
| 83 | bool host_readable = false; // D3D12_HEAP_TYPE_READBACK (or CUSTOM write-back): needs host-read flush | ||
| 77 | }; | 84 | }; |
| 78 | 85 | ||
| 79 | struct VulkanAccess { | 86 | struct VulkanAccess { |
| @@ -597,14 +604,33 @@ private: | |||
| 597 | std::unordered_map<ResourceId, Entry> entries_; | 604 | std::unordered_map<ResourceId, Entry> entries_; |
| 598 | }; | 605 | }; |
| 599 | 606 | ||
| 600 | // A D3D12 query heap on Vulkan. `ended` is kept on the host: which queries hold a result, updated as lists are | 607 | // Each physical slot records one non-overlapping interval. Logical queries can share slots. |
| 601 | // emitted in submission order. A resolve of a query that was never ended writes zeros instead of waiting on it. | 608 | struct OcclusionSegmentPool { |
| 609 | VkDevice device = VK_NULL_HANDLE; | ||
| 610 | PFN_vkDestroyQueryPool destroy = nullptr; | ||
| 611 | VkQueryPool pool = VK_NULL_HANDLE; | ||
| 612 | |||
| 613 | OcclusionSegmentPool() = default; | ||
| 614 | OcclusionSegmentPool(const OcclusionSegmentPool&) = delete; | ||
| 615 | OcclusionSegmentPool& operator=(const OcclusionSegmentPool&) = delete; | ||
| 616 | ~OcclusionSegmentPool() { if (pool) destroy(device, pool, nullptr); } | ||
| 617 | }; | ||
| 618 | |||
| 619 | struct OcclusionResult { | ||
| 620 | std::shared_ptr<const OcclusionSegmentPool> segments; | ||
| 621 | std::uint32_t first = 0; | ||
| 622 | std::uint32_t count = 0; | ||
| 623 | }; | ||
| 624 | |||
| 625 | // A D3D12 query heap on Vulkan. The host tracks which queries hold a result. A resolve of a query that | ||
| 626 | // was never ended writes zeros instead of waiting on it. | ||
| 602 | struct QueryPool { | 627 | struct QueryPool { |
| 603 | VkQueryPool pool = VK_NULL_HANDLE; | 628 | VkQueryPool pool = VK_NULL_HANDLE; |
| 604 | std::uint32_t heap_type = 0; // d3d12_query_heap | 629 | std::uint32_t heap_type = 0; // d3d12_query_heap |
| 605 | std::uint32_t count = 0; | 630 | std::uint32_t count = 0; |
| 606 | bool precise = false; // occlusionQueryPrecise: D3D12_QUERY_TYPE_OCCLUSION counts exact samples | 631 | bool precise = false; // occlusionQueryPrecise: D3D12_QUERY_TYPE_OCCLUSION counts exact samples |
| 607 | std::vector<bool> ended; | 632 | std::vector<bool> ended; |
| 633 | std::unordered_map<std::uint32_t, OcclusionResult> occlusion; | ||
| 608 | }; | 634 | }; |
| 609 | 635 | ||
| 610 | struct ReplayFunctions { | 636 | struct ReplayFunctions { |
| @@ -634,6 +660,8 @@ struct ReplayFunctions { | |||
| 634 | PFN_vkCmdEndQuery end_query = nullptr; | 660 | PFN_vkCmdEndQuery end_query = nullptr; |
| 635 | PFN_vkCmdWriteTimestamp write_timestamp = nullptr; | 661 | PFN_vkCmdWriteTimestamp write_timestamp = nullptr; |
| 636 | PFN_vkCmdCopyQueryPoolResults copy_query_pool_results = nullptr; | 662 | PFN_vkCmdCopyQueryPoolResults copy_query_pool_results = nullptr; |
| 663 | std::function<void(VkCommandBuffer, VkQueryPool, std::uint32_t, std::uint32_t, VkBuffer, VkDeviceSize)> | ||
| 664 | sum_occlusion; | ||
| 637 | // Resolves available binary-occlusion queries to 64-bit 0/1 values, outside conditional rendering. | 665 | // Resolves available binary-occlusion queries to 64-bit 0/1 values, outside conditional rendering. |
| 638 | std::function<void(VkCommandBuffer, VkQueryPool, std::uint32_t first, std::uint32_t count, | 666 | std::function<void(VkCommandBuffer, VkQueryPool, std::uint32_t first, std::uint32_t count, |
| 639 | VkBuffer dst, VkDeviceSize offset)> resolve_binary_occlusion; | 667 | VkBuffer dst, VkDeviceSize offset)> resolve_binary_occlusion; |
| @@ -650,6 +678,12 @@ struct ReplayFunctions { | |||
| 650 | // Optional VK_KHR_acceleration_structure: BuildRaytracingAccelerationStructure. | 678 | // Optional VK_KHR_acceleration_structure: BuildRaytracingAccelerationStructure. |
| 651 | PFN_vkCmdBuildAccelerationStructuresKHR build_acceleration_structures = nullptr; | 679 | PFN_vkCmdBuildAccelerationStructuresKHR build_acceleration_structures = nullptr; |
| 652 | std::function<VkAccelerationStructureKHR(std::uint64_t)> resolve_acceleration_structure; | 680 | std::function<VkAccelerationStructureKHR(std::uint64_t)> resolve_acceleration_structure; |
| 681 | // Preparation only allocates a slot; capture records the GPU snapshot at the SetPredication command. | ||
| 682 | std::function<bool(VkBuffer, VkDeviceSize, PredicateCapture&)> prepare_predicate; | ||
| 683 | std::function<void(VkCommandBuffer, const PredicateCapture&)> capture_predicate; | ||
| 684 | std::function<bool(VkBuffer, VkBuffer, VkDeviceSize, VkDeviceSize, VkDeviceSize, | ||
| 685 | std::vector<PredicatedCopyDispatch>&)> prepare_predicated_copy; | ||
| 686 | std::function<void(VkCommandBuffer, const std::vector<PredicatedCopyDispatch>&)> emit_predicated_copy; | ||
| 653 | // Returns a 2D-array view of the range (caller-owned, alive until execution completes); rectangle clears. | 687 | // Returns a 2D-array view of the range (caller-owned, alive until execution completes); rectangle clears. |
| 654 | std::function<VkImageView(const ResourceBinding&, const VkImageSubresourceRange&)> image_view; | 688 | std::function<VkImageView(const ResourceBinding&, const VkImageSubresourceRange&)> image_view; |
| 655 | // Footprint copies of a depth24_as_float texture (depth24.h): `depth24_prepare` makes the scratch and descriptors | 689 | // Footprint copies of a depth24_as_float texture (depth24.h): `depth24_prepare` makes the scratch and descriptors |
| @@ -675,7 +709,29 @@ enum class ReplayResult { | |||
| 675 | 709 | ||
| 676 | namespace detail { | 710 | namespace detail { |
| 677 | 711 | ||
| 712 | struct QueryResolveRun { | ||
| 713 | VkQueryPool pool = VK_NULL_HANDLE; // null: zero fill for queries that were never ended | ||
| 714 | std::uint32_t first = 0; | ||
| 715 | std::uint32_t count = 0; | ||
| 716 | VkDeviceSize offset = 0; | ||
| 717 | bool sum = false; | ||
| 718 | }; | ||
| 719 | |||
| 720 | struct PreparedQuery { | ||
| 721 | static constexpr std::uint32_t no_segment = UINT32_MAX; | ||
| 722 | std::size_t command = 0; | ||
| 723 | QueryPool* heap = nullptr; | ||
| 724 | bool statistics_active = false; | ||
| 725 | std::uint32_t begin_segment = no_segment; | ||
| 726 | std::uint32_t end_segment = no_segment; | ||
| 727 | std::uint32_t first_result = 0; | ||
| 728 | std::uint32_t result_count = 0; | ||
| 729 | std::vector<QueryResolveRun> resolves; | ||
| 730 | }; | ||
| 731 | |||
| 678 | struct Prepared { | 732 | struct Prepared { |
| 733 | PredicateCapture predicate; | ||
| 734 | std::vector<PredicatedCopyDispatch> predicated_copy; | ||
| 679 | ResourceBinding binding; | 735 | ResourceBinding binding; |
| 680 | VkImageSubresourceRange range{}; // the barrier range, or the cleared view (cleared aspects only) | 736 | VkImageSubresourceRange range{}; // the barrier range, or the cleared view (cleared aspects only) |
| 681 | VkImageView view = VK_NULL_HANDLE; | 737 | VkImageView view = VK_NULL_HANDLE; |
| @@ -688,6 +744,9 @@ struct Prepared { | |||
| 688 | std::vector<VkBufferImageCopy> buffer_image_copies; // one direction, given by which side is an image | 744 | std::vector<VkBufferImageCopy> buffer_image_copies; // one direction, given by which side is an image |
| 689 | std::vector<VkImageCopy> image_copies; | 745 | std::vector<VkImageCopy> image_copies; |
| 690 | VkImageResolve resolve{}; // resolves | 746 | VkImageResolve resolve{}; // resolves |
| 747 | // Depth or stencil resolves: the mode, and the destination view (`view` is the source's). | ||
| 748 | VkResolveModeFlagBits resolve_mode = VK_RESOLVE_MODE_NONE; | ||
| 749 | VkImageView resolve_view = VK_NULL_HANDLE; | ||
| 691 | bool has_depth24 = false; // a depth plane copy of a depth24_as_float texture: convert through depth24 | 750 | bool has_depth24 = false; // a depth plane copy of a depth24_as_float texture: convert through depth24 |
| 692 | Depth24Job depth24; // the whole copy: where its scratch floats are | 751 | Depth24Job depth24; // the whole copy: where its scratch floats are |
| 693 | std::vector<Depth24Job> depth24_parts; // the dispatches that convert it | 752 | std::vector<Depth24Job> depth24_parts; // the dispatches that convert it |
| @@ -697,7 +756,6 @@ struct Prepared { | |||
| 697 | uav_clear::Element element; // unordered-access clears: one element of the view's format | 756 | uav_clear::Element element; // unordered-access clears: one element of the view's format |
| 698 | VkClearColorValue clear_color{}; // ... the value that writes it into the image | 757 | VkClearColorValue clear_color{}; // ... the value that writes it into the image |
| 699 | std::vector<std::array<VkDeviceSize, 2>> fills; // ... buffer byte ranges, offset and size | 758 | std::vector<std::array<VkDeviceSize, 2>> fills; // ... buffer byte ranges, offset and size |
| 700 | QueryPool* queries = nullptr; // query commands: the heap | ||
| 701 | VkAccelerationStructureKHR accel_dst = VK_NULL_HANDLE; | 759 | VkAccelerationStructureKHR accel_dst = VK_NULL_HANDLE; |
| 702 | VkAccelerationStructureKHR accel_src = VK_NULL_HANDLE; | 760 | VkAccelerationStructureKHR accel_src = VK_NULL_HANDLE; |
| 703 | }; | 761 | }; |
| @@ -995,6 +1053,33 @@ inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) { | |||
| 995 | const auto padded = [block](std::uint32_t size) { return (size + block - 1) / block * block; }; | 1053 | const auto padded = [block](std::uint32_t size) { return (size + block - 1) / block * block; }; |
| 996 | if (box.right > padded(from.width) || box.bottom > padded(from.height) || box.back > from_depth) | 1054 | if (box.right > padded(from.width) || box.bottom > padded(from.height) || box.back > from_depth) |
| 997 | return ReplayResult::invalid_copy; | 1055 | return ReplayResult::invalid_copy; |
| 1056 | if (const std::uint32_t dst_block = block_format(p.binding.format, dst.aspectMask).block; dst_block != block) { | ||
| 1057 | // A BC format and its uncompressed equivalent ("Format Conversion using Direct3D 10.1"): one texel of the | ||
| 1058 | // uncompressed side is one block of the other. The box is in source texels, the offset in destination | ||
| 1059 | // texels, and Vulkan takes the extent in source texels, cut at the source's mip edge. | ||
| 1060 | const auto blocks = [](std::uint32_t size, std::uint32_t b) { return (size + b - 1) / b; }; | ||
| 1061 | const bool same_bytes = | ||
| 1062 | block_format(p.binding.format, dst.aspectMask).bytes == block_format(p.source.format, src.aspectMask).bytes; | ||
| 1063 | if (!same_bytes || (box.left | box.top) % block || (copy.x | copy.y) % dst_block || box.left >= from.width || | ||
| 1064 | box.top >= from.height || !within(copy.z, box.back - box.front, to_depth) || | ||
| 1065 | copy.x / dst_block + blocks(box.right - box.left, block) > blocks(to.width, dst_block) || | ||
| 1066 | copy.y / dst_block + blocks(box.bottom - box.top, block) > blocks(to.height, dst_block)) | ||
| 1067 | return ReplayResult::invalid_copy; | ||
| 1068 | const std::uint32_t w = std::min(padded(box.right - box.left), from.width - box.left); | ||
| 1069 | const std::uint32_t h = std::min(padded(box.bottom - box.top), from.height - box.top); | ||
| 1070 | // shortcut: into a BC mip whose edge block is partial, Vulkan's extent cannot reach the padded edge; such | ||
| 1071 | // a copy is refused until it is staged through a buffer. | ||
| 1072 | if (dst_block > 1 && (copy.x + w * dst_block > to.width || copy.y + h * dst_block > to.height)) | ||
| 1073 | return ReplayResult::invalid_copy; | ||
| 1074 | p.image_copies.push_back({{src.aspectMask, src.baseMipLevel, src.baseArrayLayer, 1}, | ||
| 1075 | {std::int32_t(box.left), std::int32_t(box.top), std::int32_t(box.front)}, | ||
| 1076 | {dst.aspectMask, dst.baseMipLevel, dst.baseArrayLayer, 1}, | ||
| 1077 | {std::int32_t(copy.x), std::int32_t(copy.y), std::int32_t(copy.z)}, | ||
| 1078 | {w, h, box.back - box.front}}); | ||
| 1079 | p.range = dst; | ||
| 1080 | p.source_range = src; | ||
| 1081 | return ReplayResult::success; | ||
| 1082 | } | ||
| 998 | std::uint32_t w = box.right - box.left, h = box.bottom - box.top; | 1083 | std::uint32_t w = box.right - box.left, h = box.bottom - box.top; |
| 999 | const std::uint32_t d = box.back - box.front; | 1084 | const std::uint32_t d = box.back - box.front; |
| 1000 | if (block > 1) { | 1085 | if (block > 1) { |
| @@ -1096,7 +1181,15 @@ inline ReplayResult prepare_resource_copy(Prepared& p) { | |||
| 1096 | return ReplayResult::success; | 1181 | return ReplayResult::success; |
| 1097 | } | 1182 | } |
| 1098 | const ResourceBinding &dst = p.binding, &src = p.source; | 1183 | const ResourceBinding &dst = p.binding, &src = p.source; |
| 1099 | if (!dst.image || !src.image || dst.width != src.width || dst.height != src.height || | 1184 | // A BC texture and one of its uncompressed equivalent match block for texel ("Format Conversion using |
| 1185 | // Direct3D 10.1"); the Vulkan extent is in source texels. | ||
| 1186 | const std::uint32_t sb = block_format(src.format, VK_IMAGE_ASPECT_COLOR_BIT).block; | ||
| 1187 | const std::uint32_t db = block_format(dst.format, VK_IMAGE_ASPECT_COLOR_BIT).block; | ||
| 1188 | const auto blocks = [](std::uint32_t size, std::uint32_t b) { return (size + b - 1) / b; }; | ||
| 1189 | const bool same_shape = sb == db ? dst.width == src.width && dst.height == src.height | ||
| 1190 | : blocks(dst.width, db) == blocks(src.width, sb) && | ||
| 1191 | blocks(dst.height, db) == blocks(src.height, sb); | ||
| 1192 | if (!dst.image || !src.image || !same_shape || | ||
| 1100 | dst.depth != src.depth || dst.volume != src.volume || dst.mip_levels != src.mip_levels || | 1193 | dst.depth != src.depth || dst.volume != src.volume || dst.mip_levels != src.mip_levels || |
| 1101 | dst.array_layers != src.array_layers || dst.aspects != src.aspects || dst.samples != src.samples || | 1194 | dst.array_layers != src.array_layers || dst.aspects != src.aspects || dst.samples != src.samples || |
| 1102 | block_format(dst.format, VK_IMAGE_ASPECT_COLOR_BIT).bytes != block_format(src.format, VK_IMAGE_ASPECT_COLOR_BIT).bytes) | 1195 | block_format(dst.format, VK_IMAGE_ASPECT_COLOR_BIT).bytes != block_format(src.format, VK_IMAGE_ASPECT_COLOR_BIT).bytes) |
| @@ -1104,7 +1197,13 @@ inline ReplayResult prepare_resource_copy(Prepared& p) { | |||
| 1104 | for (const VkImageAspectFlags aspect : {VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_ASPECT_DEPTH_BIT, VK_IMAGE_ASPECT_STENCIL_BIT}) { | 1197 | for (const VkImageAspectFlags aspect : {VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_ASPECT_DEPTH_BIT, VK_IMAGE_ASPECT_STENCIL_BIT}) { |
| 1105 | if (!(dst.aspects & aspect)) continue; | 1198 | if (!(dst.aspects & aspect)) continue; |
| 1106 | for (std::uint32_t mip = 0; mip < dst.mip_levels; ++mip) { | 1199 | for (std::uint32_t mip = 0; mip < dst.mip_levels; ++mip) { |
| 1107 | const VkExtent2D extent = mip_extent(dst, mip); | 1200 | const VkExtent2D extent = mip_extent(src, mip), to = mip_extent(dst, mip); |
| 1201 | // Lower mips can differ in blocks (BC 12x8 mip 1 is 2x1 blocks, R32G32 3x2 mip 1 is 1x1): more source | ||
| 1202 | // blocks than the destination holds is refused, as by WARP. shortcut: a BC destination mip with a partial | ||
| 1203 | // edge block cannot take a whole uncompressed texel per block in one vkCmdCopyImage; refused until such | ||
| 1204 | // a copy is staged through a buffer. | ||
| 1205 | if (sb != db && (blocks(extent.width, sb) * db > to.width || blocks(extent.height, sb) * db > to.height)) | ||
| 1206 | return ReplayResult::invalid_copy; | ||
| 1108 | p.image_copies.push_back({{aspect, mip, 0, dst.array_layers}, {0, 0, 0}, {aspect, mip, 0, dst.array_layers}, | 1207 | p.image_copies.push_back({{aspect, mip, 0, dst.array_layers}, {0, 0, 0}, {aspect, mip, 0, dst.array_layers}, |
| 1109 | {0, 0, 0}, {extent.width, extent.height, std::max(1u, src.depth >> mip)}}); | 1208 | {0, 0, 0}, {extent.width, extent.height, std::max(1u, src.depth >> mip)}}); |
| 1110 | } | 1209 | } |
| @@ -1114,7 +1213,8 @@ inline ReplayResult prepare_resource_copy(Prepared& p) { | |||
| 1114 | return ReplayResult::success; | 1213 | return ReplayResult::success; |
| 1115 | } | 1214 | } |
| 1116 | 1215 | ||
| 1117 | // Resolve a multisampled colour image into a single-sampled image of the same format. | 1216 | // Resolve a multisampled colour image into a single-sampled image of the same format, or (a region) one plane of a |
| 1217 | // depth/stencil image into the same plane of another: MIN or MAX, or AVERAGE of depth. | ||
| 1118 | inline ReplayResult prepare_resolve(const ResolveSubresource& resolve, Prepared& p) { | 1218 | inline ReplayResult prepare_resolve(const ResolveSubresource& resolve, Prepared& p) { |
| 1119 | VkImageSubresourceRange dst{}, src{}; | 1219 | VkImageSubresourceRange dst{}, src{}; |
| 1120 | if (!copy_subresource(p.binding, resolve.dst_subresource, dst) || | 1220 | if (!copy_subresource(p.binding, resolve.dst_subresource, dst) || |
| @@ -1137,9 +1237,19 @@ inline ReplayResult prepare_resolve(const ResolveSubresource& resolve, Prepared& | |||
| 1137 | } else if (from.width != to.width || from.height != to.height) { | 1237 | } else if (from.width != to.width || from.height != to.height) { |
| 1138 | return ReplayResult::invalid_copy; | 1238 | return ReplayResult::invalid_copy; |
| 1139 | } | 1239 | } |
| 1140 | if (src.aspectMask != VK_IMAGE_ASPECT_COLOR_BIT || dst.aspectMask != VK_IMAGE_ASPECT_COLOR_BIT || | 1240 | if (src.aspectMask != dst.aspectMask || p.source.format != p.binding.format) return ReplayResult::unsupported; |
| 1141 | p.source.format != p.binding.format) | 1241 | const auto& region = resolve.region; |
| 1142 | return ReplayResult::unsupported; | 1242 | if (src.aspectMask == VK_IMAGE_ASPECT_COLOR_BIT) { |
| 1243 | if (region && region->mode != d3d12_resolve_mode::average) return ReplayResult::unsupported; | ||
| 1244 | } else { | ||
| 1245 | // A rendering scope resolves each pixel in place, so the destination offset must be the source's. | ||
| 1246 | if (!region || dst_offset.x != src_offset.x || dst_offset.y != src_offset.y || | ||
| 1247 | (region->mode == d3d12_resolve_mode::average && src.aspectMask != VK_IMAGE_ASPECT_DEPTH_BIT)) | ||
| 1248 | return ReplayResult::unsupported; | ||
| 1249 | p.resolve_mode = region->mode == d3d12_resolve_mode::minimum ? VK_RESOLVE_MODE_MIN_BIT | ||
| 1250 | : region->mode == d3d12_resolve_mode::maximum ? VK_RESOLVE_MODE_MAX_BIT | ||
| 1251 | : VK_RESOLVE_MODE_AVERAGE_BIT; | ||
| 1252 | } | ||
| 1143 | p.resolve = {{src.aspectMask, src.baseMipLevel, src.baseArrayLayer, 1}, src_offset, | 1253 | p.resolve = {{src.aspectMask, src.baseMipLevel, src.baseArrayLayer, 1}, src_offset, |
| 1144 | {dst.aspectMask, dst.baseMipLevel, dst.baseArrayLayer, 1}, dst_offset, extent}; | 1254 | {dst.aspectMask, dst.baseMipLevel, dst.baseArrayLayer, 1}, dst_offset, extent}; |
| 1145 | p.range = dst; | 1255 | p.range = dst; |
| @@ -1238,13 +1348,49 @@ class PreparedList { | |||
| 1238 | public: | 1348 | public: |
| 1239 | const CommandList* list = nullptr; | 1349 | const CommandList* list = nullptr; |
| 1240 | std::vector<detail::Prepared> commands; | 1350 | std::vector<detail::Prepared> commands; |
| 1241 | bool binary_occlusion = false; // the queue needs its internal resolve resources | 1351 | std::vector<detail::PreparedQuery> queries; |
| 1352 | VkQueryPool segment_pool = VK_NULL_HANDLE; | ||
| 1353 | std::uint32_t segment_base = 0; | ||
| 1354 | std::uint32_t segment_count = 0; | ||
| 1355 | bool precise_segments = false; | ||
| 1242 | // Copies, resolves and UAV clears that run as transfers, recorded while a predicate was set. D3D12 skips them | 1356 | // Copies, resolves and UAV clears that run as transfers, recorded while a predicate was set. D3D12 skips them |
| 1243 | // when the predicate says so, but Vulkan's conditional rendering does not cover transfer commands, so they run | 1357 | // when the predicate says so, but Vulkan's conditional rendering does not cover transfer commands, so they run |
| 1244 | // unconditionally (docs/d3d12_vulkan.md section 4.7). Counted so the caller can report it. | 1358 | // unconditionally (docs/d3d12_vulkan.md section 4.7). Counted so the caller can report it. |
| 1245 | std::size_t unpredicated_copies = 0; | 1359 | std::size_t unpredicated_copies = 0; |
| 1360 | // Set when any command writes to a host_readable (READBACK) buffer so VulkanQueue only flushes to HOST_BIT when needed. | ||
| 1361 | bool wrote_readback = false; | ||
| 1362 | VkPipelineStageFlags2 readback_src_stages = 0; | ||
| 1246 | }; | 1363 | }; |
| 1247 | 1364 | ||
| 1365 | inline ReplayResult plan_occlusion_segments(PreparedList& out) { | ||
| 1366 | // Active logical queries cover a contiguous range of physical slots. A Begin or End closes the old | ||
| 1367 | // slot and opens a new one if any query remains active. Each shared interval is recorded only once. | ||
| 1368 | std::map<std::pair<QueryHeapId, std::uint32_t>, std::uint32_t> active; | ||
| 1369 | std::uint32_t current = detail::PreparedQuery::no_segment; | ||
| 1370 | for (auto& query : out.queries) { | ||
| 1371 | const Command& command = out.list->commands()[query.command]; | ||
| 1372 | if (std::holds_alternative<ResolveQueries>(command)) continue; | ||
| 1373 | const auto range = query_range(command); | ||
| 1374 | if (range.type != d3d12_query::occlusion) continue; | ||
| 1375 | const auto key = std::pair{range.heap, range.first}; | ||
| 1376 | query.end_segment = current; | ||
| 1377 | if (std::holds_alternative<BeginQuery>(command)) { | ||
| 1378 | // A flattened bundle can reuse a slot already active in the parent list. | ||
| 1379 | if (!active.emplace(key, out.segment_count).second) return ReplayResult::invalid_query; | ||
| 1380 | out.precise_segments |= query.heap->precise; | ||
| 1381 | } else { | ||
| 1382 | const auto start = active.find(key); | ||
| 1383 | if (start == active.end()) return ReplayResult::invalid_query; | ||
| 1384 | query.first_result = start->second; | ||
| 1385 | query.result_count = out.segment_count - start->second; | ||
| 1386 | active.erase(start); | ||
| 1387 | } | ||
| 1388 | current = active.empty() ? detail::PreparedQuery::no_segment : out.segment_count++; | ||
| 1389 | query.begin_segment = current; | ||
| 1390 | } | ||
| 1391 | return active.empty() ? ReplayResult::success : ReplayResult::invalid_query; | ||
| 1392 | } | ||
| 1393 | |||
| 1248 | // detail::initialize zero-clears an image piece the tracker holds in UNDEFINED (D3D12 committed resources start | 1394 | // detail::initialize zero-clears an image piece the tracker holds in UNDEFINED (D3D12 committed resources start |
| 1249 | // zeroed) the first time a command touches it, with vkCmdClearColorImage or vkCmdClearDepthStencilImage. True when | 1395 | // zeroed) the first time a command touches it, with vkCmdClearColorImage or vkCmdClearDepthStencilImage. True when |
| 1250 | // a command of the list would need one of those and it is unset; replay() then refuses the list as unsupported, as | 1396 | // a command of the list would need one of those and it is unset; replay() then refuses the list as unsupported, as |
| @@ -1302,7 +1448,10 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 1302 | const auto commands = list.commands(); | 1448 | const auto commands = list.commands(); |
| 1303 | out.list = &list; | 1449 | out.list = &list; |
| 1304 | out.commands.assign(commands.size(), {}); | 1450 | out.commands.assign(commands.size(), {}); |
| 1305 | out.binary_occlusion = false; | 1451 | out.queries.clear(); |
| 1452 | out.segment_pool = VK_NULL_HANDLE; | ||
| 1453 | out.segment_base = out.segment_count = 0; | ||
| 1454 | out.precise_segments = false; | ||
| 1306 | const bool rendering = vk.begin_rendering && vk.end_rendering && vk.clear_attachments && vk.image_view; | 1455 | const bool rendering = vk.begin_rendering && vk.end_rendering && vk.clear_attachments && vk.image_view; |
| 1307 | const bool copies = vk.copy_buffer && vk.copy_buffer_to_image && vk.copy_image_to_buffer && vk.copy_image; | 1456 | const bool copies = vk.copy_buffer && vk.copy_buffer_to_image && vk.copy_image_to_buffer && vk.copy_image; |
| 1308 | const bool conditional = vk.begin_conditional_rendering && vk.end_conditional_rendering; | 1457 | const bool conditional = vk.begin_conditional_rendering && vk.end_conditional_rendering; |
| @@ -1316,10 +1465,11 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 1316 | out.unpredicated_copies = 0; | 1465 | out.unpredicated_copies = 0; |
| 1317 | const bool queries = vk.reset_query_pool && vk.begin_query && vk.end_query && vk.write_timestamp && | 1466 | const bool queries = vk.reset_query_pool && vk.begin_query && vk.end_query && vk.write_timestamp && |
| 1318 | vk.copy_query_pool_results && vk.fill_buffer && vk.query_pool; | 1467 | vk.copy_query_pool_results && vk.fill_buffer && vk.query_pool; |
| 1319 | // Vulkan allows one active query of each type in a command buffer (VUID-vkCmdBeginQuery-queryPool-01922); | 1468 | // Vulkan allows one active query per type. Only ordinary occlusion uses virtual segments. |
| 1320 | // D3D12 lets queries overlap. Overlapping occlusion (either kind) or pipeline-statistics queries need virtual | 1469 | std::size_t ordinary_active = 0; |
| 1321 | // queries (end the running Vulkan query, start another, sum on resolve); until then such a list is unsupported. | 1470 | bool overlaps = false, binary_active = false, statistics_active = false; |
| 1322 | bool occlusion_active = false, statistics_active = false; | 1471 | out.wrote_readback = false; |
| 1472 | out.readback_src_stages = 0; | ||
| 1323 | 1473 | ||
| 1324 | for (std::size_t i = 0; i < commands.size(); ++i) { | 1474 | for (std::size_t i = 0; i < commands.size(); ++i) { |
| 1325 | const auto& command = commands[i]; | 1475 | const auto& command = commands[i]; |
| @@ -1434,10 +1584,15 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 1434 | } else if (std::holds_alternative<CopyBuffer>(command) || std::holds_alternative<CopyTexture>(command) || | 1584 | } else if (std::holds_alternative<CopyBuffer>(command) || std::holds_alternative<CopyTexture>(command) || |
| 1435 | std::holds_alternative<CopyResource>(command)) { | 1585 | std::holds_alternative<CopyResource>(command)) { |
| 1436 | if (!copies) return ReplayResult::unsupported; | 1586 | if (!copies) return ReplayResult::unsupported; |
| 1437 | if (predicated) ++out.unpredicated_copies; | 1587 | if (predicated && !std::holds_alternative<CopyBuffer>(command)) ++out.unpredicated_copies; |
| 1438 | const auto [dst_id, src_id] = copy_ids(command); | 1588 | const auto [dst_id, src_id] = copy_ids(command); |
| 1439 | const ResourceBinding* source = resolve(src_id); | 1589 | const ResourceBinding* source = resolve(src_id); |
| 1440 | if (!bind(dst_id) || !source) return ReplayResult::unresolved_resource; | 1590 | if (!bind(dst_id) || !source) return ReplayResult::unresolved_resource; |
| 1591 | if (p.binding.host_readable) { | ||
| 1592 | out.wrote_readback = true; | ||
| 1593 | out.readback_src_stages |= predicated && std::holds_alternative<CopyBuffer>(command) | ||
| 1594 | ? VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT : VK_PIPELINE_STAGE_2_COPY_BIT; | ||
| 1595 | } | ||
| 1441 | p.source = *source; | 1596 | p.source = *source; |
| 1442 | ReplayResult result = ReplayResult::success; | 1597 | ReplayResult result = ReplayResult::success; |
| 1443 | if (const auto* buffer_copy = std::get_if<CopyBuffer>(&command)) { | 1598 | if (const auto* buffer_copy = std::get_if<CopyBuffer>(&command)) { |
| @@ -1445,7 +1600,19 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 1445 | !detail::within(buffer_copy->dst_offset, buffer_copy->size, p.binding.size) || | 1600 | !detail::within(buffer_copy->dst_offset, buffer_copy->size, p.binding.size) || |
| 1446 | !detail::within(buffer_copy->src_offset, buffer_copy->size, p.source.size)) | 1601 | !detail::within(buffer_copy->src_offset, buffer_copy->size, p.source.size)) |
| 1447 | return ReplayResult::invalid_copy; | 1602 | return ReplayResult::invalid_copy; |
| 1448 | p.buffer_copies.push_back({buffer_copy->src_offset, buffer_copy->dst_offset, buffer_copy->size}); | 1603 | if (buffer_copy->src_offset > UINT64_MAX - p.source.buffer_offset || |
| 1604 | buffer_copy->dst_offset > UINT64_MAX - p.binding.buffer_offset) return ReplayResult::invalid_copy; | ||
| 1605 | const VkDeviceSize src = p.source.buffer_offset + buffer_copy->src_offset; | ||
| 1606 | const VkDeviceSize dst = p.binding.buffer_offset + buffer_copy->dst_offset; | ||
| 1607 | if (buffer_copy->size > UINT64_MAX - src || buffer_copy->size > UINT64_MAX - dst) | ||
| 1608 | return ReplayResult::invalid_copy; | ||
| 1609 | if (p.source.buffer == p.binding.buffer && src < dst + buffer_copy->size && dst < src + buffer_copy->size) | ||
| 1610 | return ReplayResult::invalid_copy; | ||
| 1611 | if (predicated) { | ||
| 1612 | if (statistics_active || !vk.prepare_predicated_copy || !vk.emit_predicated_copy || | ||
| 1613 | !vk.prepare_predicated_copy(p.source.buffer, p.binding.buffer, src, dst, buffer_copy->size, p.predicated_copy)) | ||
| 1614 | return ReplayResult::unsupported; | ||
| 1615 | } else p.buffer_copies.push_back({src, dst, buffer_copy->size}); | ||
| 1449 | } else if (const auto* texture_copy = std::get_if<CopyTexture>(&command)) { | 1616 | } else if (const auto* texture_copy = std::get_if<CopyTexture>(&command)) { |
| 1450 | result = detail::prepare_texture_copy(*texture_copy, p); | 1617 | result = detail::prepare_texture_copy(*texture_copy, p); |
| 1451 | // A depth plane footprint of a D24 texture stored as D32: words of 24-bit UNORM, floats in the image. | 1618 | // A depth plane footprint of a D24 texture stored as D32: words of 24-bit UNORM, floats in the image. |
| @@ -1480,6 +1647,12 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 1480 | p.source = *source; | 1647 | p.source = *source; |
| 1481 | if (const auto result = detail::prepare_resolve(*resolve_command, p); result != ReplayResult::success) | 1648 | if (const auto result = detail::prepare_resolve(*resolve_command, p); result != ReplayResult::success) |
| 1482 | return result; | 1649 | return result; |
| 1650 | if (p.resolve_mode != VK_RESOLVE_MODE_NONE) { | ||
| 1651 | if (!vk.begin_rendering || !vk.end_rendering || !vk.image_view) return ReplayResult::unsupported; | ||
| 1652 | p.view = vk.image_view(p.source, p.source_range); | ||
| 1653 | p.resolve_view = vk.image_view(p.binding, p.range); | ||
| 1654 | if (!p.view || !p.resolve_view) return ReplayResult::unsupported; | ||
| 1655 | } | ||
| 1483 | } else if (const auto* discard = std::get_if<DiscardResource>(&command)) { | 1656 | } else if (const auto* discard = std::get_if<DiscardResource>(&command)) { |
| 1484 | // Buffers and partial (rectangle) discards keep their contents, which "undefined" allows. | 1657 | // Buffers and partial (rectangle) discards keep their contents, which "undefined" allows. |
| 1485 | if (!bind(discard->resource)) return ReplayResult::unresolved_resource; | 1658 | if (!bind(discard->resource)) return ReplayResult::unresolved_resource; |
| @@ -1502,6 +1675,9 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 1502 | if (!vk.update_buffer || !vk.buffer_at) return ReplayResult::unsupported; | 1675 | if (!vk.update_buffer || !vk.buffer_at) return ReplayResult::unsupported; |
| 1503 | if (!vk.buffer_at(write->address, 4, p.write_buffer, p.write_offset)) return ReplayResult::unresolved_resource; | 1676 | if (!vk.buffer_at(write->address, 4, p.write_buffer, p.write_offset)) return ReplayResult::unresolved_resource; |
| 1504 | if (p.write_offset % 4) return ReplayResult::invalid_copy; | 1677 | if (p.write_offset % 4) return ReplayResult::invalid_copy; |
| 1678 | // WriteBufferImmediate resolves by VA and may target a readback buffer in COPY_DEST. | ||
| 1679 | out.wrote_readback = true; | ||
| 1680 | out.readback_src_stages |= VK_PIPELINE_STAGE_2_TRANSFER_BIT; | ||
| 1505 | } else if (const auto* atomic = std::get_if<AtomicCopyBuffer>(&command)) { | 1681 | } else if (const auto* atomic = std::get_if<AtomicCopyBuffer>(&command)) { |
| 1506 | if (!vk.copy_buffer) return ReplayResult::unsupported; | 1682 | if (!vk.copy_buffer) return ReplayResult::unsupported; |
| 1507 | if (predicated) ++out.unpredicated_copies; // a transfer command, like the copies | 1683 | if (predicated) ++out.unpredicated_copies; // a transfer command, like the copies |
| @@ -1519,30 +1695,47 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 1519 | } | 1695 | } |
| 1520 | p.buffer_copies.push_back({p.source.buffer_offset + atomic->src_offset, | 1696 | p.buffer_copies.push_back({p.source.buffer_offset + atomic->src_offset, |
| 1521 | p.binding.buffer_offset + atomic->dst_offset, atomic->bytes}); | 1697 | p.binding.buffer_offset + atomic->dst_offset, atomic->bytes}); |
| 1698 | if (p.binding.host_readable) { | ||
| 1699 | out.wrote_readback = true; | ||
| 1700 | out.readback_src_stages |= VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_TRANSFER_BIT; | ||
| 1701 | } | ||
| 1522 | } else if (const auto* predication = std::get_if<Predication>(&command)) { | 1702 | } else if (const auto* predication = std::get_if<Predication>(&command)) { |
| 1523 | predicated = predication->buffer != 0; | 1703 | predicated = predication->buffer != 0; |
| 1524 | if (!predicated) continue; | 1704 | if (!predicated) continue; |
| 1525 | if (!conditional) return ReplayResult::unsupported; | 1705 | if (!conditional) return ReplayResult::unsupported; |
| 1706 | // The internal dispatch must not appear in the application's pipeline-statistics result. Virtualising | ||
| 1707 | // that query is separate work; reject the combination before emitting any commands instead of lying. | ||
| 1708 | if (statistics_active) return ReplayResult::unsupported; | ||
| 1526 | if (!bind(predication->buffer)) return ReplayResult::unresolved_resource; | 1709 | if (!bind(predication->buffer)) return ReplayResult::unresolved_resource; |
| 1527 | // Vulkan reads one 32-bit word at a 4-byte aligned offset; D3D12's value is 64 bits at an 8-byte | 1710 | if (!p.binding.buffer || !detail::within(predication->offset, 8, p.binding.size) || |
| 1528 | // aligned one, so its low word is read (docs/d3d12_vulkan.md section 4.7). | 1711 | predication->offset > UINT64_MAX - p.binding.buffer_offset) |
| 1529 | if (!p.binding.buffer || !detail::within(predication->offset, 4, p.binding.size)) | ||
| 1530 | return ReplayResult::invalid_predication; | 1712 | return ReplayResult::invalid_predication; |
| 1713 | if (!vk.prepare_predicate || !vk.capture_predicate || | ||
| 1714 | !vk.prepare_predicate(p.binding.buffer, p.binding.buffer_offset + predication->offset, p.predicate)) | ||
| 1715 | return ReplayResult::unsupported; | ||
| 1531 | } else if (const QueryRange range = query_range(command); range.count) { | 1716 | } else if (const QueryRange range = query_range(command); range.count) { |
| 1532 | // BeginQuery, EndQuery and ResolveQueryData are not among D3D12's predicated calls, and Vulkan's | 1717 | // BeginQuery, EndQuery and ResolveQueryData are not among D3D12's predicated calls, and Vulkan's |
| 1533 | // conditional rendering leaves query commands and transfers alone, so a predicate changes nothing here. | 1718 | // conditional rendering leaves query commands and transfers alone, so a predicate changes nothing here. |
| 1534 | if (!queries) return ReplayResult::unsupported; | 1719 | if (!queries) return ReplayResult::unsupported; |
| 1535 | p.queries = vk.query_pool(range.heap); | 1720 | QueryPool* heap = vk.query_pool(range.heap); |
| 1536 | if (!p.queries) return ReplayResult::unresolved_resource; | 1721 | if (!heap) return ReplayResult::unresolved_resource; |
| 1537 | if (!query_fits_heap(p.queries->heap_type, range.type)) return ReplayResult::invalid_query; | 1722 | if (!query_fits_heap(heap->heap_type, range.type)) return ReplayResult::invalid_query; |
| 1538 | if (range.first >= p.queries->count || range.count > p.queries->count - range.first) | 1723 | if (range.first >= heap->count || range.count > heap->count - range.first) |
| 1539 | return ReplayResult::invalid_query; | 1724 | return ReplayResult::invalid_query; |
| 1540 | if (!query_result_size(range.type)) return ReplayResult::unsupported; | 1725 | if (!query_result_size(range.type)) return ReplayResult::unsupported; |
| 1541 | if (range.type != d3d12_query::timestamp && !std::holds_alternative<ResolveQueries>(command)) { | 1726 | if (range.type != d3d12_query::timestamp && !std::holds_alternative<ResolveQueries>(command)) { |
| 1542 | bool& active = range.type == d3d12_query::pipeline_statistics ? statistics_active : occlusion_active; | ||
| 1543 | const bool begin = std::holds_alternative<BeginQuery>(command); | 1727 | const bool begin = std::holds_alternative<BeginQuery>(command); |
| 1544 | if (begin && active) return ReplayResult::unsupported; | 1728 | if (range.type == d3d12_query::occlusion) { |
| 1545 | active = begin; // the list pairs every End with its Begin | 1729 | if (begin && binary_active) return ReplayResult::unsupported; |
| 1730 | if (begin) overlaps |= ordinary_active++ != 0; | ||
| 1731 | else --ordinary_active; | ||
| 1732 | } else if (range.type == d3d12_query::binary_occlusion) { | ||
| 1733 | if (begin && (binary_active || ordinary_active)) return ReplayResult::unsupported; | ||
| 1734 | binary_active = begin; | ||
| 1735 | } else { | ||
| 1736 | if (begin && statistics_active) return ReplayResult::unsupported; | ||
| 1737 | statistics_active = begin; | ||
| 1738 | } | ||
| 1546 | } | 1739 | } |
| 1547 | if (const auto* resolve_queries = std::get_if<ResolveQueries>(&command)) { | 1740 | if (const auto* resolve_queries = std::get_if<ResolveQueries>(&command)) { |
| 1548 | // The destination is a buffer, as D3D12 requires, large enough for every result. | 1741 | // The destination is a buffer, as D3D12 requires, large enough for every result. |
| @@ -1556,9 +1749,13 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 1556 | if (range.type == d3d12_query::binary_occlusion) { | 1749 | if (range.type == d3d12_query::binary_occlusion) { |
| 1557 | // The internal dispatch would otherwise count towards the application's CSInvocations. | 1750 | // The internal dispatch would otherwise count towards the application's CSInvocations. |
| 1558 | if (!vk.resolve_binary_occlusion || statistics_active) return ReplayResult::unsupported; | 1751 | if (!vk.resolve_binary_occlusion || statistics_active) return ReplayResult::unsupported; |
| 1559 | out.binary_occlusion = true; | 1752 | } |
| 1753 | if (p.binding.host_readable) { | ||
| 1754 | out.wrote_readback = true; | ||
| 1755 | out.readback_src_stages |= VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_TRANSFER_BIT; | ||
| 1560 | } | 1756 | } |
| 1561 | } | 1757 | } |
| 1758 | out.queries.push_back({i, heap, statistics_active}); | ||
| 1562 | } else if (const auto* ind = std::get_if<ExecuteIndirect>(&command)) { | 1759 | } else if (const auto* ind = std::get_if<ExecuteIndirect>(&command)) { |
| 1563 | if (!bind(ind->argument_buffer) || !p.binding.buffer) return ReplayResult::unresolved_resource; | 1760 | if (!bind(ind->argument_buffer) || !p.binding.buffer) return ReplayResult::unresolved_resource; |
| 1564 | if (ind->count_buffer) { | 1761 | if (ind->count_buffer) { |
| @@ -1586,9 +1783,152 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 1586 | } | 1783 | } |
| 1587 | } | 1784 | } |
| 1588 | } | 1785 | } |
| 1786 | if (ordinary_active) return ReplayResult::invalid_query; | ||
| 1787 | if (overlaps) { | ||
| 1788 | if (!vk.sum_occlusion || out.queries.size() >= detail::PreparedQuery::no_segment) | ||
| 1789 | return ReplayResult::unsupported; | ||
| 1790 | return plan_occlusion_segments(out); | ||
| 1791 | } | ||
| 1589 | return ReplayResult::success; | 1792 | return ReplayResult::success; |
| 1590 | } | 1793 | } |
| 1591 | 1794 | ||
| 1795 | // A submission is planned against the currently published query state plus its own earlier lists. | ||
| 1796 | // Keep every physical pool referenced by the recorded batch alive until that batch completes. | ||
| 1797 | class QueryReplay { | ||
| 1798 | public: | ||
| 1799 | ReplayResult plan(PreparedList& list, const std::shared_ptr<const OcclusionSegmentPool>& pool = {}, | ||
| 1800 | std::uint32_t base = 0, bool can_sum = false) { | ||
| 1801 | if (list.segment_count) { | ||
| 1802 | if (!pool) return ReplayResult::unsupported; | ||
| 1803 | retain(pool); | ||
| 1804 | list.segment_pool = pool->pool; | ||
| 1805 | list.segment_base = base; | ||
| 1806 | } | ||
| 1807 | for (auto& query : list.queries) { | ||
| 1808 | const Command& command = list.list->commands()[query.command]; | ||
| 1809 | if (const auto* begin = std::get_if<BeginQuery>(&command)) { | ||
| 1810 | pending_[{query.heap, begin->index}] = {}; | ||
| 1811 | } else if (const auto* end = std::get_if<EndQuery>(&command)) { | ||
| 1812 | Value result{true, {}}; | ||
| 1813 | if (query.result_count) result.occlusion = {pool, base + query.first_result, query.result_count}; | ||
| 1814 | pending_[{query.heap, end->index}] = std::move(result); | ||
| 1815 | } else { | ||
| 1816 | const auto& resolve = std::get<ResolveQueries>(command); | ||
| 1817 | const bool binary = resolve.type == d3d12_query::binary_occlusion; | ||
| 1818 | const std::uint32_t size = query_result_size(resolve.type); | ||
| 1819 | const auto offset = list.commands[query.command].binding.buffer_offset + resolve.offset; | ||
| 1820 | for (std::uint32_t i = 0; i < resolve.count; ++i) { | ||
| 1821 | const auto index = resolve.first + i; | ||
| 1822 | const auto value = lookup(*query.heap, index); | ||
| 1823 | needs_binary |= binary && value.ended; | ||
| 1824 | detail::QueryResolveRun run{value.ended ? query.heap->pool : VK_NULL_HANDLE, | ||
| 1825 | index, 1, offset + VkDeviceSize(i) * size}; | ||
| 1826 | if (value.occlusion.segments) { | ||
| 1827 | if (resolve.type != d3d12_query::occlusion) return ReplayResult::invalid_query; | ||
| 1828 | // A helper dispatch would otherwise change the application's pipeline statistics. | ||
| 1829 | const auto& saved = value.occlusion; | ||
| 1830 | run = {saved.segments->pool, saved.first, saved.count, run.offset, saved.count > 1}; | ||
| 1831 | if (!can_sum || (run.sum && query.statistics_active)) return ReplayResult::unsupported; | ||
| 1832 | needs_sum |= run.sum; | ||
| 1833 | retain(saved.segments); | ||
| 1834 | } | ||
| 1835 | if (!query.resolves.empty() && !run.sum && run.count == 1) { | ||
| 1836 | auto& last = query.resolves.back(); | ||
| 1837 | if (!last.sum && last.pool == run.pool && last.first + last.count == run.first) { | ||
| 1838 | ++last.count; | ||
| 1839 | continue; | ||
| 1840 | } | ||
| 1841 | } | ||
| 1842 | query.resolves.push_back(run); | ||
| 1843 | } | ||
| 1844 | } | ||
| 1845 | } | ||
| 1846 | return ReplayResult::success; | ||
| 1847 | } | ||
| 1848 | |||
| 1849 | void commit() { | ||
| 1850 | for (auto& [key, result] : pending_) { | ||
| 1851 | const auto [heap, index] = key; | ||
| 1852 | heap->ended[index] = result.ended; | ||
| 1853 | if (result.occlusion.segments) heap->occlusion[index] = std::move(result.occlusion); | ||
| 1854 | else heap->occlusion.erase(index); | ||
| 1855 | } | ||
| 1856 | } | ||
| 1857 | |||
| 1858 | bool needs_sum = false; | ||
| 1859 | bool needs_binary = false; | ||
| 1860 | std::vector<std::shared_ptr<const OcclusionSegmentPool>> retained; | ||
| 1861 | |||
| 1862 | private: | ||
| 1863 | struct Value { | ||
| 1864 | bool ended = false; | ||
| 1865 | OcclusionResult occlusion; | ||
| 1866 | }; | ||
| 1867 | |||
| 1868 | Value lookup(QueryPool& heap, std::uint32_t index) const { | ||
| 1869 | if (const auto it = pending_.find({&heap, index}); it != pending_.end()) return it->second; | ||
| 1870 | if (const auto it = heap.occlusion.find(index); it != heap.occlusion.end()) return {true, it->second}; | ||
| 1871 | return {heap.ended[index], {}}; | ||
| 1872 | } | ||
| 1873 | |||
| 1874 | void retain(const std::shared_ptr<const OcclusionSegmentPool>& pool) { | ||
| 1875 | if (std::find(retained.begin(), retained.end(), pool) == retained.end()) retained.push_back(pool); | ||
| 1876 | } | ||
| 1877 | |||
| 1878 | std::map<std::pair<QueryPool*, std::uint32_t>, Value> pending_; | ||
| 1879 | }; | ||
| 1880 | |||
| 1881 | inline void emit_query(const PreparedList& list, const detail::PreparedQuery& query, VkCommandBuffer cb, | ||
| 1882 | const ReplayFunctions& vk, const VkConditionalRenderingBeginInfoEXT& predicate) { | ||
| 1883 | constexpr auto none = detail::PreparedQuery::no_segment; | ||
| 1884 | if (query.end_segment != none || query.begin_segment != none) { | ||
| 1885 | if (query.end_segment != none) vk.end_query(cb, list.segment_pool, list.segment_base + query.end_segment); | ||
| 1886 | if (query.begin_segment != none) { | ||
| 1887 | const auto index = list.segment_base + query.begin_segment; | ||
| 1888 | vk.reset_query_pool(cb, list.segment_pool, index, 1); | ||
| 1889 | vk.begin_query(cb, list.segment_pool, index, list.precise_segments ? VK_QUERY_CONTROL_PRECISE_BIT : 0); | ||
| 1890 | } | ||
| 1891 | return; | ||
| 1892 | } | ||
| 1893 | const auto& command = list.list->commands()[query.command]; | ||
| 1894 | const QueryPool& heap = *query.heap; | ||
| 1895 | if (const auto* begin = std::get_if<BeginQuery>(&command)) { | ||
| 1896 | vk.reset_query_pool(cb, heap.pool, begin->index, 1); | ||
| 1897 | const bool precise = begin->type == d3d12_query::occlusion && heap.precise; | ||
| 1898 | vk.begin_query(cb, heap.pool, begin->index, precise ? VK_QUERY_CONTROL_PRECISE_BIT : 0); | ||
| 1899 | } else if (const auto* end = std::get_if<EndQuery>(&command)) { | ||
| 1900 | if (end->type == d3d12_query::timestamp) { | ||
| 1901 | vk.reset_query_pool(cb, heap.pool, end->index, 1); | ||
| 1902 | vk.write_timestamp(cb, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, heap.pool, end->index); | ||
| 1903 | } else { | ||
| 1904 | vk.end_query(cb, heap.pool, end->index); | ||
| 1905 | } | ||
| 1906 | } else { | ||
| 1907 | const auto& resolve = std::get<ResolveQueries>(command); | ||
| 1908 | const bool binary = resolve.type == d3d12_query::binary_occlusion; | ||
| 1909 | const auto size = query_result_size(resolve.type); | ||
| 1910 | const auto dst = list.commands[query.command].binding.buffer; | ||
| 1911 | bool suspended = false; | ||
| 1912 | for (const auto& run : query.resolves) { | ||
| 1913 | if (!run.pool) { | ||
| 1914 | vk.fill_buffer(cb, dst, run.offset, VkDeviceSize(run.count) * size, 0); | ||
| 1915 | } else if (run.sum || binary) { | ||
| 1916 | // ResolveQueryData is unconditional even when the helper uses a dispatch. | ||
| 1917 | if (predicate.buffer && !suspended) { | ||
| 1918 | vk.end_conditional_rendering(cb); | ||
| 1919 | suspended = true; | ||
| 1920 | } | ||
| 1921 | const auto& resolve_occlusion = run.sum ? vk.sum_occlusion : vk.resolve_binary_occlusion; | ||
| 1922 | resolve_occlusion(cb, run.pool, run.first, run.count, dst, run.offset); | ||
| 1923 | } else { | ||
| 1924 | vk.copy_query_pool_results(cb, run.pool, run.first, run.count, dst, run.offset, size, | ||
| 1925 | VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); | ||
| 1926 | } | ||
| 1927 | } | ||
| 1928 | if (suspended) vk.begin_conditional_rendering(cb, &predicate); | ||
| 1929 | } | ||
| 1930 | } | ||
| 1931 | |||
| 1592 | // Ends the debug labels a submission left open, so every command buffer is balanced as Vulkan requires. | 1932 | // Ends the debug labels a submission left open, so every command buffer is balanced as Vulkan requires. |
| 1593 | inline void close_labels(VkCommandBuffer command_buffer, const ReplayFunctions& vk, std::uint32_t& open_labels) { | 1933 | inline void close_labels(VkCommandBuffer command_buffer, const ReplayFunctions& vk, std::uint32_t& open_labels) { |
| 1594 | for (; open_labels && vk.end_label; --open_labels) vk.end_label(command_buffer); | 1934 | for (; open_labels && vk.end_label; --open_labels) vk.end_label(command_buffer); |
| @@ -1609,6 +1949,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 1609 | // The extension is enabled: barriers into and out of PREDICATION also cover conditional rendering's read. | 1949 | // The extension is enabled: barriers into and out of PREDICATION also cover conditional rendering's read. |
| 1610 | const bool predicates = vk.begin_conditional_rendering != nullptr; | 1950 | const bool predicates = vk.begin_conditional_rendering != nullptr; |
| 1611 | VkConditionalRenderingBeginInfoEXT predicate{VK_STRUCTURE_TYPE_CONDITIONAL_RENDERING_BEGIN_INFO_EXT}; | 1951 | VkConditionalRenderingBeginInfoEXT predicate{VK_STRUCTURE_TYPE_CONDITIONAL_RENDERING_BEGIN_INFO_EXT}; |
| 1952 | std::size_t next_query = 0; | ||
| 1612 | // A dispatch honours conditional rendering and a copy does not (the layer runs copies unpredicated), so the | 1953 | // A dispatch honours conditional rendering and a copy does not (the layer runs copies unpredicated), so the |
| 1613 | // conversion around a copy must run whatever the predicate says: end it for the dispatch and begin it again. | 1954 | // conversion around a copy must run whatever the predicate says: end it for the dispatch and begin it again. |
| 1614 | const auto run_depth24 = [&](const Depth24Job& job) { | 1955 | const auto run_depth24 = [&](const Depth24Job& job) { |
| @@ -1620,12 +1961,17 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 1620 | for (std::size_t i = 0; i < commands.size(); ++i) { | 1961 | for (std::size_t i = 0; i < commands.size(); ++i) { |
| 1621 | const auto& command = commands[i]; | 1962 | const auto& command = commands[i]; |
| 1622 | const auto& p = prepared.commands[i]; | 1963 | const auto& p = prepared.commands[i]; |
| 1964 | if (next_query < prepared.queries.size() && prepared.queries[next_query].command == i) { | ||
| 1965 | emit_query(prepared, prepared.queries[next_query++], command_buffer, vk, predicate); | ||
| 1966 | continue; | ||
| 1967 | } | ||
| 1623 | if (const auto* predication = std::get_if<Predication>(&command)) { | 1968 | if (const auto* predication = std::get_if<Predication>(&command)) { |
| 1624 | // Conditional rendering cannot nest, so a new predicate ends the previous one first. | 1969 | // Conditional rendering cannot nest, so a new predicate ends the previous one first. |
| 1625 | if (predicate.buffer) vk.end_conditional_rendering(command_buffer); | 1970 | if (predicate.buffer) vk.end_conditional_rendering(command_buffer); |
| 1626 | predicate.buffer = p.binding.buffer; | 1971 | predicate.buffer = predication->buffer ? p.predicate.scratch : VK_NULL_HANDLE; |
| 1627 | if (predicate.buffer) { | 1972 | if (predicate.buffer) { |
| 1628 | predicate.offset = predication->offset; | 1973 | vk.capture_predicate(command_buffer, p.predicate); |
| 1974 | predicate.offset = p.predicate.offset + 8; | ||
| 1629 | // Vulkan discards the commands when the word is 0, which is EQUAL_ZERO; INVERTED gives NOT_EQUAL_ZERO. | 1975 | // Vulkan discards the commands when the word is 0, which is EQUAL_ZERO; INVERTED gives NOT_EQUAL_ZERO. |
| 1630 | predicate.flags = predication->op == d3d12_predication::not_equal_zero | 1976 | predicate.flags = predication->op == d3d12_predication::not_equal_zero |
| 1631 | ? VK_CONDITIONAL_RENDERING_INVERTED_BIT_EXT | 1977 | ? VK_CONDITIONAL_RENDERING_INVERTED_BIT_EXT |
| @@ -1861,7 +2207,9 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 1861 | } else if (std::holds_alternative<CopyBuffer>(command) || std::holds_alternative<CopyTexture>(command) || | 2207 | } else if (std::holds_alternative<CopyBuffer>(command) || std::holds_alternative<CopyTexture>(command) || |
| 1862 | std::holds_alternative<CopyResource>(command)) { | 2208 | std::holds_alternative<CopyResource>(command)) { |
| 1863 | const auto [dst_id, src_id] = copy_ids(command); | 2209 | const auto [dst_id, src_id] = copy_ids(command); |
| 1864 | if (!p.buffer_copies.empty()) { | 2210 | if (!p.predicated_copy.empty()) { |
| 2211 | vk.emit_predicated_copy(command_buffer, p.predicated_copy); | ||
| 2212 | } else if (!p.buffer_copies.empty()) { | ||
| 1865 | vk.copy_buffer(command_buffer, p.source.buffer, p.binding.buffer, std::uint32_t(p.buffer_copies.size()), | 2213 | vk.copy_buffer(command_buffer, p.source.buffer, p.binding.buffer, std::uint32_t(p.buffer_copies.size()), |
| 1866 | p.buffer_copies.data()); | 2214 | p.buffer_copies.data()); |
| 1867 | } else if (!p.image_copies.empty()) { | 2215 | } else if (!p.image_copies.empty()) { |
| @@ -1923,6 +2271,55 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 1923 | } else if (std::holds_alternative<ResolveSubresource>(command)) { | 2271 | } else if (std::holds_alternative<ResolveSubresource>(command)) { |
| 1924 | // resolve_source and resolve_dest are the transfer layouts, as copy_source and copy_dest are. | 2272 | // resolve_source and resolve_dest are the transfer layouts, as copy_source and copy_dest are. |
| 1925 | const auto [dst_id, src_id] = copy_ids(command); | 2273 | const auto [dst_id, src_id] = copy_ids(command); |
| 2274 | if (p.resolve_mode != VK_RESOLVE_MODE_NONE) { | ||
| 2275 | // A rendering scope of its own, with no draws: the source plane as the attachment, the destination | ||
| 2276 | // as its resolve target. Both go to the attachment layout and back. Resolves run in the colour | ||
| 2277 | // attachment output stage with colour attachment accesses, depth and stencil ones included. | ||
| 2278 | constexpr VkAccessFlags attachment_access = | ||
| 2279 | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | | ||
| 2280 | VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; | ||
| 2281 | constexpr VkPipelineStageFlags attachment_stages = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | | ||
| 2282 | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT | | ||
| 2283 | VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; | ||
| 2284 | const VulkanAccess source_state = vulkan_access(d3d12_state::resolve_source, false); | ||
| 2285 | const VulkanAccess dest_state = vulkan_access(d3d12_state::resolve_dest, false); | ||
| 2286 | const VkImageLayout source_layout = image_layout(p.source, source_state.layout); | ||
| 2287 | const VkImageLayout dest_layout = image_layout(p.binding, dest_state.layout); | ||
| 2288 | auto source_pieces = detail::current( | ||
| 2289 | tracker, src_id, detail::planes_for_layout(p.source, p.source_range, separate), source_layout); | ||
| 2290 | detail::initialize(vk, command_buffer, p.source, src_id, source_pieces, source_layout, tracker); | ||
| 2291 | auto dest_pieces = detail::current( | ||
| 2292 | tracker, dst_id, detail::planes_for_layout(p.binding, p.range, separate), dest_layout); | ||
| 2293 | detail::initialize(vk, command_buffer, p.binding, dst_id, dest_pieces, dest_layout, tracker); | ||
| 2294 | const VkImageLayout source_attachment = | ||
| 2295 | image_layout(p.source, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); | ||
| 2296 | const VkImageLayout dest_attachment = | ||
| 2297 | image_layout(p.binding, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); | ||
| 2298 | detail::round_trip(vk, command_buffer, p.source, source_pieces, source_attachment, source_state, | ||
| 2299 | attachment_access, attachment_stages, [&] { | ||
| 2300 | detail::round_trip(vk, command_buffer, p.binding, dest_pieces, dest_attachment, dest_state, | ||
| 2301 | attachment_access, attachment_stages, [&] { | ||
| 2302 | VkRenderingAttachmentInfo info{VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO}; | ||
| 2303 | info.imageView = p.view; | ||
| 2304 | info.imageLayout = source_attachment; | ||
| 2305 | info.resolveMode = p.resolve_mode; | ||
| 2306 | info.resolveImageView = p.resolve_view; | ||
| 2307 | info.resolveImageLayout = dest_attachment; | ||
| 2308 | info.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; | ||
| 2309 | info.storeOp = VK_ATTACHMENT_STORE_OP_NONE; // the source is only read | ||
| 2310 | VkRenderingInfo rendering{VK_STRUCTURE_TYPE_RENDERING_INFO}; | ||
| 2311 | rendering.renderArea = {{p.resolve.srcOffset.x, p.resolve.srcOffset.y}, | ||
| 2312 | {p.resolve.extent.width, p.resolve.extent.height}}; | ||
| 2313 | rendering.layerCount = 1; | ||
| 2314 | // One plane only, so independentResolve(None) never applies. | ||
| 2315 | if (p.range.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT) rendering.pDepthAttachment = &info; | ||
| 2316 | else rendering.pStencilAttachment = &info; | ||
| 2317 | vk.begin_rendering(command_buffer, &rendering); | ||
| 2318 | vk.end_rendering(command_buffer); | ||
| 2319 | }); | ||
| 2320 | }); | ||
| 2321 | continue; | ||
| 2322 | } | ||
| 1926 | const VkImageLayout src_layout = detail::copy_layout( | 2323 | const VkImageLayout src_layout = detail::copy_layout( |
| 1927 | vk, command_buffer, p.source, src_id, detail::planes_for_layout(p.source, p.source_range, separate), | 2324 | vk, command_buffer, p.source, src_id, detail::planes_for_layout(p.source, p.source_range, separate), |
| 1928 | VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, tracker); | 2325 | VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, tracker); |
| @@ -1980,49 +2377,6 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 1980 | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, | 2377 | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, |
| 1981 | VK_PIPELINE_STAGE_TRANSFER_BIT); | 2378 | VK_PIPELINE_STAGE_TRANSFER_BIT); |
| 1982 | vk.copy_buffer(command_buffer, p.source.buffer, p.binding.buffer, 1, p.buffer_copies.data()); | 2379 | vk.copy_buffer(command_buffer, p.source.buffer, p.binding.buffer, 1, p.buffer_copies.data()); |
| 1983 | } else if (const auto* begin = std::get_if<BeginQuery>(&command)) { | ||
| 1984 | // D3D12 queries need no reset; a Vulkan query is reset before every use. Nothing here runs inside a | ||
| 1985 | // render pass, where a reset is not allowed: a draw path that opens one around queries must reset | ||
| 1986 | // them before it. | ||
| 1987 | QueryPool& heap = *p.queries; | ||
| 1988 | vk.reset_query_pool(command_buffer, heap.pool, begin->index, 1); | ||
| 1989 | heap.ended[begin->index] = false; | ||
| 1990 | const bool precise = begin->type == d3d12_query::occlusion && heap.precise; | ||
| 1991 | vk.begin_query(command_buffer, heap.pool, begin->index, precise ? VK_QUERY_CONTROL_PRECISE_BIT : 0); | ||
| 1992 | } else if (const auto* end = std::get_if<EndQuery>(&command)) { | ||
| 1993 | QueryPool& heap = *p.queries; | ||
| 1994 | if (end->type == d3d12_query::timestamp) { | ||
| 1995 | vk.reset_query_pool(command_buffer, heap.pool, end->index, 1); | ||
| 1996 | vk.write_timestamp(command_buffer, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, heap.pool, end->index); | ||
| 1997 | } else { | ||
| 1998 | vk.end_query(command_buffer, heap.pool, end->index); | ||
| 1999 | } | ||
| 2000 | heap.ended[end->index] = true; | ||
| 2001 | } else if (const auto* resolve = std::get_if<ResolveQueries>(&command)) { | ||
| 2002 | // D3D12 leaves a query that was never ended undefined. Write zeros instead of waiting forever. | ||
| 2003 | const QueryPool& heap = *p.queries; | ||
| 2004 | const std::uint32_t size = query_result_size(resolve->type); | ||
| 2005 | const bool binary = resolve->type == d3d12_query::binary_occlusion; | ||
| 2006 | // ResolveQueryData is unconditional in D3D12, including our internal dispatch. | ||
| 2007 | if (binary && predicate.buffer) vk.end_conditional_rendering(command_buffer); | ||
| 2008 | std::uint32_t index = resolve->first; | ||
| 2009 | const std::uint32_t last = resolve->first + resolve->count; | ||
| 2010 | while (index < last) { | ||
| 2011 | const bool ended = heap.ended[index]; | ||
| 2012 | std::uint32_t run = 1; | ||
| 2013 | while (index + run < last && heap.ended[index + run] == ended) ++run; | ||
| 2014 | const VkDeviceSize offset = p.binding.buffer_offset + resolve->offset + | ||
| 2015 | VkDeviceSize(index - resolve->first) * size; | ||
| 2016 | if (!ended) | ||
| 2017 | vk.fill_buffer(command_buffer, p.binding.buffer, offset, VkDeviceSize(run) * size, 0); | ||
| 2018 | else if (binary) | ||
| 2019 | vk.resolve_binary_occlusion(command_buffer, heap.pool, index, run, p.binding.buffer, offset); | ||
| 2020 | else | ||
| 2021 | vk.copy_query_pool_results(command_buffer, heap.pool, index, run, p.binding.buffer, offset, size, | ||
| 2022 | VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); | ||
| 2023 | index += run; | ||
| 2024 | } | ||
| 2025 | if (binary && predicate.buffer) vk.begin_conditional_rendering(command_buffer, &predicate); | ||
| 2026 | } else if (const auto* ind = std::get_if<ExecuteIndirect>(&command)) { | 2380 | } else if (const auto* ind = std::get_if<ExecuteIndirect>(&command)) { |
| 2027 | if (ind->count_buffer) { | 2381 | if (ind->count_buffer) { |
| 2028 | if (ind->kind == IndirectKind::draw) { | 2382 | if (ind->kind == IndirectKind::draw) { |
| @@ -2111,7 +2465,10 @@ ReplayResult replay(const CommandList& list, VkCommandBuffer command_buffer, Res | |||
| 2111 | PreparedList prepared; | 2465 | PreparedList prepared; |
| 2112 | if (const auto result = prepare(list, resolve, vk, prepared); result != ReplayResult::success) return result; | 2466 | if (const auto result = prepare(list, resolve, vk, prepared); result != ReplayResult::success) return result; |
| 2113 | if (tracker && zero_clear_unavailable(prepared, vk, *tracker)) return ReplayResult::unsupported; | 2467 | if (tracker && zero_clear_unavailable(prepared, vk, *tracker)) return ReplayResult::unsupported; |
| 2468 | QueryReplay queries; | ||
| 2469 | if (const auto result = queries.plan(prepared); result != ReplayResult::success) return result; | ||
| 2114 | emit(prepared, command_buffer, vk, tracker); | 2470 | emit(prepared, command_buffer, vk, tracker); |
| 2471 | queries.commit(); // the caller owns submission of the legacy command buffer | ||
| 2115 | return ReplayResult::success; | 2472 | return ReplayResult::success; |
| 2116 | } | 2473 | } |
| 2117 | 2474 | ||