upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/src
diff options
context:
space:
mode:
authorismailchaka1 <chakankar111@gmail.com>2026-11-22 02:05:52 +0000
committerismailchaka1 <chakankar111@gmail.com>2026-11-22 02:05:52 +0000
commite80485e24e31adf4a8b68d00e4253c324b214032 (patch)
tree2292f1bc0f9c86d3d44c4d9b19714e934c7ddd87 /runtime/src
parent9b70afedb85dcb4908171fc67ffaa25c8b3513b2 (diff)
parent762893fd6056c08c174a66479aed3a51739eeaa3 (diff)
Merge main into d3d-61-b4g4r4a4
The only conflict: block_format's two-byte list, where main added R5G6B5_UNORM_PACK16 (#587) next to this PR's A4R4G4B4_UNORM_PACK16. Both kept.
Diffstat (limited to 'runtime/src')
-rw-r--r--runtime/src/command_list.h41
-rw-r--r--runtime/src/uav_clear.h262
-rw-r--r--runtime/src/vulkan_backend.h7
-rw-r--r--runtime/src/vulkan_replay.h244
4 files changed, 523 insertions, 31 deletions
diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h
index 19dab43d7..4c2e38c85 100644
--- a/runtime/src/command_list.h
+++ b/runtime/src/command_list.h
@@ -2,8 +2,8 @@
2 2
3// The command-list IR (docs/d3d12_vulkan.md section 3.2): what a D3D12 command list records, kept until 3// The command-list IR (docs/d3d12_vulkan.md section 3.2): what a D3D12 command list records, kept until
4// ExecuteCommandLists replays it on Vulkan (vulkan_replay.h). This slice covers legacy and enhanced barriers and 4// ExecuteCommandLists replays it on Vulkan (vulkan_replay.h). This slice covers legacy and enhanced barriers and
5// render-target and depth-stencil clears (whole views or rectangles), copies, resolves and predication. It has no 5// render-target, depth-stencil and unordered-access clears (whole views or rectangles), copies, resolves and
6// Windows or Vulkan dependency. 6// predication. It has no Windows or Vulkan dependency.
7 7
8#include <array> 8#include <array>
9#include <cstdint> 9#include <cstdint>
@@ -308,6 +308,30 @@ struct ClearDepthStencil {
308 std::vector<Rect> rects; 308 std::vector<Rect> rects;
309}; 309};
310 310
311// What a UAV descriptor said when ClearUnorderedAccessView* was recorded (the CPU slot may be rewritten after).
312// A buffer view is a byte range of the buffer and an element format; a texture view is one mip and a layer range.
313struct UavView {
314 ResourceId resource;
315 bool buffer;
316 std::uint32_t format; // the view's VkFormat value; 0 (VK_FORMAT_UNDEFINED): a raw or structured buffer
317 std::uint64_t offset; // buffer: first byte of the view
318 std::uint64_t size; // buffer: bytes in the view
319 std::uint32_t element_size; // buffer: bytes an element (rects count elements), 4 for a raw view
320 std::uint32_t mip; // texture
321 std::uint32_t first_layer;
322 std::uint32_t layer_count;
323};
324
325// ClearUnorderedAccessViewUint / ...Float; the resource must be in unordered_access state at execution. values are
326// the four UINTs, or the four FLOATs' bits. rects empty: the whole view. A buffer view's rects are element ranges
327// [left, right) (top and bottom must cover row 0).
328struct ClearUnorderedAccess {
329 UavView view;
330 bool is_float;
331 std::array<std::uint32_t, 4> values;
332 std::vector<Rect> rects;
333};
334
311// D3D12_PREDICATION_OP. 335// D3D12_PREDICATION_OP.
312namespace d3d12_predication { 336namespace d3d12_predication {
313inline constexpr std::uint32_t equal_zero = 0; // skip the predicated commands when the value is 0 337inline constexpr std::uint32_t equal_zero = 0; // skip the predicated commands when the value is 0
@@ -327,7 +351,7 @@ struct Predication {
327 351
328using Command = std::variant<TransitionBarrier, UavBarrier, AliasingBarrier, GlobalBarrier, BufferBarrier, 352using Command = std::variant<TransitionBarrier, UavBarrier, AliasingBarrier, GlobalBarrier, BufferBarrier,
329 TextureBarrier, ClearRenderTarget, ClearDepthStencil, CopyBuffer, CopyTexture, 353 TextureBarrier, ClearRenderTarget, ClearDepthStencil, CopyBuffer, CopyTexture,
330 CopyResource, ResolveSubresource, Predication>; 354 CopyResource, ResolveSubresource, Predication, ClearUnorderedAccess>;
331 355
332class CommandList { 356class CommandList {
333public: 357public:
@@ -417,6 +441,17 @@ public:
417 return append(ClearDepthStencil{target, flags, depth, stencil, {rects.begin(), rects.end()}}); 441 return append(ClearDepthStencil{target, flags, depth, stencil, {rects.begin(), rects.end()}});
418 } 442 }
419 443
444 // A view of nothing (no resource, an empty buffer range or no layers) is invalid, as is a rectangle that is
445 // inside out. Ranges against the resource are checked at replay.
446 bool clear_unordered_access(const UavView& view, bool is_float, const std::array<std::uint32_t, 4>& values,
447 std::span<const Rect> rects = {}) {
448 if (!view.resource) return false;
449 if (view.buffer ? (!view.size || !view.element_size) : !view.layer_count) return false;
450 for (const Rect& r : rects)
451 if (r.right < r.left || r.bottom < r.top) return false;
452 return append(ClearUnorderedAccess{view, is_float, values, {rects.begin(), rects.end()}});
453 }
454
420 // ExecuteBundle copies the closed bundle's commands at the call site. The COM layer validates D3D12 list 455 // ExecuteBundle copies the closed bundle's commands at the call site. The COM layer validates D3D12 list
421 // types and bundle-only restrictions before calling this method. 456 // types and bundle-only restrictions before calling this method.
422 bool execute_bundle(const CommandList& bundle) { 457 bool execute_bundle(const CommandList& bundle) {
diff --git a/runtime/src/uav_clear.h b/runtime/src/uav_clear.h
new file mode 100644
index 000000000..6b5c53fc3
--- /dev/null
+++ b/runtime/src/uav_clear.h
@@ -0,0 +1,262 @@
1#pragma once
2
3// ClearUnorderedAccessViewUint / ClearUnorderedAccessViewFloat values as the bytes of one element of a view's
4// format, and those bytes as the VkClearColorValue that writes them into an image of another format of the same
5// size (a typeless resource viewed through a typed UAV). Needs the Vulkan headers only.
6//
7// The conversion rules are D3D's (Microsoft's documentation of ID3D11DeviceContext::ClearUnorderedAccessViewUint
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,
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.
12// - 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 to nearest even (the small floats have no sign: negative is 0).
14// D3D11 calls Float on an integer view invalid and D3D12 does not say; here the value is converted to the
15// integer (rounded toward zero, clamped, NaN is 0) so the result is defined. A raw or structured buffer view
16// takes value 0's bits.
17//
18// An image is cleared with the value that decodes those bytes in the image's own format, which is exact for every
19// format here except the SNORM pattern 0x80..00 (Vulkan writes -1.0 as 0x81..), and NaN payloads, which a driver
20// may canonicalise.
21
22#ifndef VK_NO_PROTOTYPES
23#define VK_NO_PROTOTYPES
24#endif
25#include <vulkan/vulkan.h>
26
27#include <algorithm>
28#include <array>
29#include <bit>
30#include <cmath>
31#include <cstdint>
32#include <cstring>
33#include <limits>
34
35namespace leonida::uav_clear {
36
37enum class Kind : std::uint8_t { unorm, snorm, uint, sint, sfloat, ufloat };
38
39// One channel: where its bits are in the element (little-endian, from bit 0 of byte 0) and how many.
40struct Channel {
41 std::uint8_t offset = 0;
42 std::uint8_t bits = 0; // 0: the format has no such channel
43};
44
45struct Layout {
46 VkFormat format;
47 Kind kind;
48 std::uint8_t bytes; // of one element
49 std::array<Channel, 4> rgba; // R, G, B, A
50};
51
52// The formats D3D12 allows for typed UAVs (D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE), as their Vulkan formats.
53inline constexpr Layout layouts[] = {
54 {VK_FORMAT_R32G32B32A32_SFLOAT, Kind::sfloat, 16, {{{0, 32}, {32, 32}, {64, 32}, {96, 32}}}},
55 {VK_FORMAT_R32G32B32A32_UINT, Kind::uint, 16, {{{0, 32}, {32, 32}, {64, 32}, {96, 32}}}},
56 {VK_FORMAT_R32G32B32A32_SINT, Kind::sint, 16, {{{0, 32}, {32, 32}, {64, 32}, {96, 32}}}},
57 {VK_FORMAT_R16G16B16A16_SFLOAT, Kind::sfloat, 8, {{{0, 16}, {16, 16}, {32, 16}, {48, 16}}}},
58 {VK_FORMAT_R16G16B16A16_UNORM, Kind::unorm, 8, {{{0, 16}, {16, 16}, {32, 16}, {48, 16}}}},
59 {VK_FORMAT_R16G16B16A16_SNORM, Kind::snorm, 8, {{{0, 16}, {16, 16}, {32, 16}, {48, 16}}}},
60 {VK_FORMAT_R16G16B16A16_UINT, Kind::uint, 8, {{{0, 16}, {16, 16}, {32, 16}, {48, 16}}}},
61 {VK_FORMAT_R16G16B16A16_SINT, Kind::sint, 8, {{{0, 16}, {16, 16}, {32, 16}, {48, 16}}}},
62 {VK_FORMAT_R32G32_SFLOAT, Kind::sfloat, 8, {{{0, 32}, {32, 32}, {}, {}}}},
63 {VK_FORMAT_R32G32_UINT, Kind::uint, 8, {{{0, 32}, {32, 32}, {}, {}}}},
64 {VK_FORMAT_R32G32_SINT, Kind::sint, 8, {{{0, 32}, {32, 32}, {}, {}}}},
65 {VK_FORMAT_A2B10G10R10_UNORM_PACK32, Kind::unorm, 4, {{{0, 10}, {10, 10}, {20, 10}, {30, 2}}}},
66 {VK_FORMAT_A2B10G10R10_UINT_PACK32, Kind::uint, 4, {{{0, 10}, {10, 10}, {20, 10}, {30, 2}}}},
67 {VK_FORMAT_B10G11R11_UFLOAT_PACK32, Kind::ufloat, 4, {{{0, 11}, {11, 11}, {22, 10}, {}}}},
68 {VK_FORMAT_R8G8B8A8_UNORM, Kind::unorm, 4, {{{0, 8}, {8, 8}, {16, 8}, {24, 8}}}},
69 {VK_FORMAT_R8G8B8A8_SNORM, Kind::snorm, 4, {{{0, 8}, {8, 8}, {16, 8}, {24, 8}}}},
70 {VK_FORMAT_R8G8B8A8_UINT, Kind::uint, 4, {{{0, 8}, {8, 8}, {16, 8}, {24, 8}}}},
71 {VK_FORMAT_R8G8B8A8_SINT, Kind::sint, 4, {{{0, 8}, {8, 8}, {16, 8}, {24, 8}}}},
72 {VK_FORMAT_B8G8R8A8_UNORM, Kind::unorm, 4, {{{16, 8}, {8, 8}, {0, 8}, {24, 8}}}},
73 {VK_FORMAT_R16G16_SFLOAT, Kind::sfloat, 4, {{{0, 16}, {16, 16}, {}, {}}}},
74 {VK_FORMAT_R16G16_UNORM, Kind::unorm, 4, {{{0, 16}, {16, 16}, {}, {}}}},
75 {VK_FORMAT_R16G16_SNORM, Kind::snorm, 4, {{{0, 16}, {16, 16}, {}, {}}}},
76 {VK_FORMAT_R16G16_UINT, Kind::uint, 4, {{{0, 16}, {16, 16}, {}, {}}}},
77 {VK_FORMAT_R16G16_SINT, Kind::sint, 4, {{{0, 16}, {16, 16}, {}, {}}}},
78 {VK_FORMAT_R32_SFLOAT, Kind::sfloat, 4, {{{0, 32}, {}, {}, {}}}},
79 {VK_FORMAT_R32_UINT, Kind::uint, 4, {{{0, 32}, {}, {}, {}}}},
80 {VK_FORMAT_R32_SINT, Kind::sint, 4, {{{0, 32}, {}, {}, {}}}},
81 {VK_FORMAT_R8G8_UNORM, Kind::unorm, 2, {{{0, 8}, {8, 8}, {}, {}}}},
82 {VK_FORMAT_R8G8_SNORM, Kind::snorm, 2, {{{0, 8}, {8, 8}, {}, {}}}},
83 {VK_FORMAT_R8G8_UINT, Kind::uint, 2, {{{0, 8}, {8, 8}, {}, {}}}},
84 {VK_FORMAT_R8G8_SINT, Kind::sint, 2, {{{0, 8}, {8, 8}, {}, {}}}},
85 {VK_FORMAT_R16_SFLOAT, Kind::sfloat, 2, {{{0, 16}, {}, {}, {}}}},
86 {VK_FORMAT_R16_UNORM, Kind::unorm, 2, {{{0, 16}, {}, {}, {}}}},
87 {VK_FORMAT_R16_SNORM, Kind::snorm, 2, {{{0, 16}, {}, {}, {}}}},
88 {VK_FORMAT_R16_UINT, Kind::uint, 2, {{{0, 16}, {}, {}, {}}}},
89 {VK_FORMAT_R16_SINT, Kind::sint, 2, {{{0, 16}, {}, {}, {}}}},
90 {VK_FORMAT_R8_UNORM, Kind::unorm, 1, {{{0, 8}, {}, {}, {}}}},
91 {VK_FORMAT_R8_SNORM, Kind::snorm, 1, {{{0, 8}, {}, {}, {}}}},
92 {VK_FORMAT_R8_UINT, Kind::uint, 1, {{{0, 8}, {}, {}, {}}}},
93 {VK_FORMAT_R8_SINT, Kind::sint, 1, {{{0, 8}, {}, {}, {}}}},
94};
95
96inline constexpr const Layout* layout(VkFormat format) {
97 for (const Layout& l : layouts)
98 if (l.format == format) return &l;
99 return nullptr;
100}
101
102// Up to one element of the largest format.
103struct Element {
104 std::array<std::uint8_t, 16> bytes{};
105 std::uint32_t size = 0;
106};
107
108namespace detail {
109
110inline constexpr std::uint32_t mask(unsigned bits) { return bits >= 32 ? 0xffffffffu : (1u << bits) - 1; }
111
112inline void put(Element& e, Channel c, std::uint32_t value) {
113 value &= mask(c.bits);
114 for (unsigned i = 0; i < c.bits; ++i)
115 if (value >> i & 1) e.bytes[(c.offset + i) / 8] |= std::uint8_t(1u << ((c.offset + i) % 8));
116}
117
118inline std::uint32_t get(const Element& e, Channel c) {
119 std::uint32_t value = 0;
120 for (unsigned i = 0; i < c.bits; ++i)
121 value |= std::uint32_t(e.bytes[(c.offset + i) / 8] >> ((c.offset + i) % 8) & 1) << i;
122 return value;
123}
124
125// A float32 as a float with `mantissa` fraction bits, `exponent` exponent bits and an optional sign bit (IEEE
126// half: 10, 5, signed; the packed formats: 6 or 5, 5, unsigned), rounded to nearest even. Too large is infinity.
127inline std::uint32_t small_float(float value, unsigned mantissa, unsigned exponent, bool sign) {
128 const std::uint32_t f = std::bit_cast<std::uint32_t>(value);
129 const std::uint32_t negative = f >> 31;
130 const std::uint32_t max_exponent = mask(exponent);
131 const std::uint32_t sign_bit = sign ? negative << (mantissa + exponent) : 0;
132 if (std::isnan(value)) return sign_bit | (max_exponent << mantissa) | (1u << (mantissa - 1));
133 if (!sign && negative) return 0;
134 const std::uint32_t magnitude = f & 0x7fffffffu;
135 const int bias = int(max_exponent >> 1);
136 const int e = int(magnitude >> 23) - 127 + bias; // the exponent field in the small format
137 if (e >= int(max_exponent)) return sign_bit | (max_exponent << mantissa); // overflow, or infinity
138 const std::uint32_t full = (magnitude & 0x7fffffu) | 0x800000u; // 24-bit significand
139 // A normal result keeps `mantissa` bits; a subnormal one shifts further right.
140 const int shift = (e > 0 ? 0 : 1 - e) + int(23 - mantissa);
141 if (shift > 24) return sign_bit; // rounds to zero
142 std::uint32_t kept = full >> shift;
143 const std::uint32_t rest = full & mask(unsigned(shift));
144 const std::uint32_t half = 1u << (shift - 1);
145 if (rest > half || (rest == half && (kept & 1))) ++kept; // may carry into the exponent, which is right
146 const std::uint32_t biased = e > 0 ? (std::uint32_t(e) << mantissa) + (kept - (1u << mantissa)) : kept;
147 return sign_bit | std::min(biased, max_exponent << mantissa);
148}
149
150inline float from_small_float(std::uint32_t bits, unsigned mantissa, unsigned exponent, bool sign) {
151 const bool negative = sign && (bits >> (mantissa + exponent) & 1);
152 const std::uint32_t e = bits >> mantissa & mask(exponent);
153 const std::uint32_t m = bits & mask(mantissa);
154 const int bias = int(mask(exponent) >> 1);
155 float value;
156 if (e == mask(exponent))
157 value = m ? std::numeric_limits<float>::quiet_NaN() : std::numeric_limits<float>::infinity();
158 else if (e == 0)
159 value = std::ldexp(float(m), 1 - bias - int(mantissa));
160 else
161 value = std::ldexp(float(m | (1u << mantissa)), int(e) - bias - int(mantissa));
162 return negative ? -value : value;
163}
164
165inline std::uint32_t to_float_bits(float value, const Layout& l, unsigned bits) {
166 if (l.kind == Kind::ufloat) return small_float(value, bits - 5, 5, false);
167 if (bits == 16) return small_float(value, 10, 5, true);
168 return std::bit_cast<std::uint32_t>(value);
169}
170
171inline float from_float_bits(std::uint32_t raw, const Layout& l, unsigned bits) {
172 if (l.kind == Kind::ufloat) return from_small_float(raw, bits - 5, 5, false);
173 if (bits == 16) return from_small_float(raw, 10, 5, true);
174 return std::bit_cast<float>(raw);
175}
176
177// Float to an integer channel: rounded toward zero, clamped, NaN is 0.
178inline std::uint32_t to_integer(float value, bool is_signed, unsigned bits) {
179 if (std::isnan(value)) return 0;
180 if (is_signed) {
181 const double low = -std::ldexp(1.0, int(bits) - 1), high = std::ldexp(1.0, int(bits) - 1) - 1;
182 return std::uint32_t(std::int64_t(std::clamp(std::trunc(double(value)), low, high)));
183 }
184 return std::uint32_t(std::clamp(std::trunc(double(value)), 0.0, std::ldexp(1.0, int(bits)) - 1));
185}
186
187} // namespace detail
188
189// The element a clear writes into a view of `format`. `values` are the call's four UINTs, or the bits of its four
190// FLOATs when is_float. False: not a typed-UAV format.
191inline bool encode(VkFormat format, bool is_float, const std::array<std::uint32_t, 4>& values, Element& out) {
192 const Layout* l = layout(format);
193 if (!l) return false;
194 out = {};
195 out.size = l->bytes;
196 for (unsigned i = 0; i < 4; ++i) {
197 const Channel c = l->rgba[i];
198 if (!c.bits) continue;
199 if (!is_float) {
200 detail::put(out, c, values[i]);
201 continue;
202 }
203 const float v = std::bit_cast<float>(values[i]);
204 const double scale = double(detail::mask(c.bits));
205 switch (l->kind) {
206 case Kind::unorm:
207 detail::put(out, c, std::isnan(v) ? 0 : std::uint32_t(std::lround(std::clamp(double(v), 0.0, 1.0) * scale)));
208 break;
209 case Kind::snorm: {
210 const double max = double(detail::mask(c.bits - 1));
211 detail::put(out, c, std::isnan(v) ? 0 : std::uint32_t(std::lround(std::clamp(double(v), -1.0, 1.0) * max)));
212 break;
213 }
214 case Kind::uint: detail::put(out, c, detail::to_integer(v, false, c.bits)); break;
215 case Kind::sint: detail::put(out, c, detail::to_integer(v, true, c.bits)); break;
216 case Kind::sfloat:
217 case Kind::ufloat: detail::put(out, c, detail::to_float_bits(v, *l, c.bits)); break;
218 }
219 }
220 return true;
221}
222
223// The clear value that writes `element` into an image of `format` (same element size). False: not a format here,
224// or a different size.
225inline bool decode(VkFormat format, const Element& element, VkClearColorValue& out) {
226 const Layout* l = layout(format);
227 if (!l || l->bytes != element.size) return false;
228 out = {};
229 for (unsigned i = 0; i < 4; ++i) {
230 const Channel c = l->rgba[i];
231 if (!c.bits) continue;
232 const std::uint32_t raw = detail::get(element, c);
233 switch (l->kind) {
234 case Kind::uint: out.uint32[i] = raw; break;
235 case Kind::sint: {
236 const std::uint32_t sign = 1u << (c.bits - 1);
237 out.int32[i] = c.bits >= 32 ? std::int32_t(raw) : std::int32_t((raw ^ sign)) - std::int32_t(sign);
238 break;
239 }
240 case Kind::unorm: out.float32[i] = float(double(raw) / double(detail::mask(c.bits))); break;
241 case Kind::snorm: {
242 const std::uint32_t sign = 1u << (c.bits - 1);
243 const std::int32_t s = std::int32_t(raw ^ sign) - std::int32_t(sign);
244 out.float32[i] = std::max(-1.0f, float(double(s) / double(sign - 1)));
245 break;
246 }
247 case Kind::sfloat:
248 case Kind::ufloat: out.float32[i] = detail::from_float_bits(raw, *l, c.bits); break;
249 }
250 }
251 return true;
252}
253
254// A raw or structured buffer view: every 32-bit word gets value 0 (its bits, for Float).
255inline Element raw_element(const std::array<std::uint32_t, 4>& values) {
256 Element e{};
257 e.size = 4;
258 std::memcpy(e.bytes.data(), &values[0], 4);
259 return e;
260}
261
262} // namespace leonida::uav_clear
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h
index 4cc24b158..a99e7e5f1 100644
--- a/runtime/src/vulkan_backend.h
+++ b/runtime/src/vulkan_backend.h
@@ -33,7 +33,7 @@ struct VulkanDeviceFunctions {
33 X(vkGetImageMemoryRequirements) X(vkBindImageMemory) X(vkCreateBuffer) X(vkDestroyBuffer) \ 33 X(vkGetImageMemoryRequirements) X(vkBindImageMemory) X(vkCreateBuffer) X(vkDestroyBuffer) \
34 X(vkGetBufferMemoryRequirements) X(vkBindBufferMemory) X(vkAllocateMemory) X(vkFreeMemory) X(vkMapMemory) \ 34 X(vkGetBufferMemoryRequirements) X(vkBindBufferMemory) X(vkAllocateMemory) X(vkFreeMemory) X(vkMapMemory) \
35 X(vkUnmapMemory) X(vkCmdCopyBuffer) X(vkCmdCopyBufferToImage) X(vkCmdCopyImageToBuffer) X(vkCmdCopyImage) \ 35 X(vkUnmapMemory) X(vkCmdCopyBuffer) X(vkCmdCopyBufferToImage) X(vkCmdCopyImageToBuffer) X(vkCmdCopyImage) \
36 X(vkCmdResolveImage) X(vkCreateSampler) X(vkDestroySampler) \ 36 X(vkCmdResolveImage) X(vkCmdFillBuffer) X(vkCmdUpdateBuffer) X(vkCreateSampler) X(vkDestroySampler) \
37 X(vkCmdBeginConditionalRenderingEXT) X(vkCmdEndConditionalRenderingEXT) 37 X(vkCmdBeginConditionalRenderingEXT) X(vkCmdEndConditionalRenderingEXT)
38#define LEONIDA_VK_MEMBER(name) PFN_##name name = nullptr; 38#define LEONIDA_VK_MEMBER(name) PFN_##name name = nullptr;
39 LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_MEMBER) 39 LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_MEMBER)
@@ -53,7 +53,8 @@ struct VulkanDeviceFunctions {
53 vkDestroyImage && vkGetImageMemoryRequirements && vkBindImageMemory && vkCreateBuffer && 53 vkDestroyImage && vkGetImageMemoryRequirements && vkBindImageMemory && vkCreateBuffer &&
54 vkDestroyBuffer && vkGetBufferMemoryRequirements && vkBindBufferMemory && vkAllocateMemory && 54 vkDestroyBuffer && vkGetBufferMemoryRequirements && vkBindBufferMemory && vkAllocateMemory &&
55 vkFreeMemory && vkMapMemory && vkUnmapMemory && vkCmdCopyBuffer && vkCmdCopyBufferToImage && 55 vkFreeMemory && vkMapMemory && vkUnmapMemory && vkCmdCopyBuffer && vkCmdCopyBufferToImage &&
56 vkCmdCopyImageToBuffer && vkCmdCopyImage && vkCmdResolveImage; 56 vkCmdCopyImageToBuffer && vkCmdCopyImage && vkCmdResolveImage && vkCmdFillBuffer &&
57 vkCmdUpdateBuffer;
57 } 58 }
58}; 59};
59 60
@@ -77,6 +78,8 @@ public:
77 replay_.copy_image_to_buffer = vk.vkCmdCopyImageToBuffer; 78 replay_.copy_image_to_buffer = vk.vkCmdCopyImageToBuffer;
78 replay_.copy_image = vk.vkCmdCopyImage; 79 replay_.copy_image = vk.vkCmdCopyImage;
79 replay_.resolve_image = vk.vkCmdResolveImage; 80 replay_.resolve_image = vk.vkCmdResolveImage;
81 replay_.fill_buffer = vk.vkCmdFillBuffer;
82 replay_.update_buffer = vk.vkCmdUpdateBuffer;
80 if (conditional_rendering) { // a driver may hand out these pointers even when the extension is off 83 if (conditional_rendering) { // a driver may hand out these pointers even when the extension is off
81 replay_.begin_conditional_rendering = vk.vkCmdBeginConditionalRenderingEXT; 84 replay_.begin_conditional_rendering = vk.vkCmdBeginConditionalRenderingEXT;
82 replay_.end_conditional_rendering = vk.vkCmdEndConditionalRenderingEXT; 85 replay_.end_conditional_rendering = vk.vkCmdEndConditionalRenderingEXT;
diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h
index 34b924bc4..fbe5e688f 100644
--- a/runtime/src/vulkan_replay.h
+++ b/runtime/src/vulkan_replay.h
@@ -19,14 +19,18 @@
19// - images cleared without rectangles have TRANSFER_DST usage; images cleared with rectangles have attachment usage 19// - images cleared without rectangles have TRANSFER_DST usage; images cleared with rectangles have attachment usage
20// and image_view must return views for them (dynamicRendering, Vulkan 1.3); reinterpreted whole-view clears 20// and image_view must return views for them (dynamicRendering, Vulkan 1.3); reinterpreted whole-view clears
21// use the same attachment path because vkCmdClearColorImage has no view-format argument; 21// use the same attachment path because vkCmdClearColorImage has no view-format argument;
22// - enhanced barriers need pipeline_barrier2 (synchronization2, Vulkan 1.3). 22// - enhanced barriers need pipeline_barrier2 (synchronization2, Vulkan 1.3);
23// - unordered-access clears need fill_buffer, update_buffer and copy_buffer for buffers; texture views cleared with
24// rectangles need color_attachment usage on the image (ResourceBinding::color_attachment).
23// A list that needs a missing function fails with ReplayResult::unsupported before anything is written. 25// A list that needs a missing function fails with ReplayResult::unsupported before anything is written.
24 26
25#include "command_list.h" 27#include "command_list.h"
28#include "uav_clear.h"
26 29
27#include <vulkan/vulkan.h> 30#include <vulkan/vulkan.h>
28 31
29#include <algorithm> 32#include <algorithm>
33#include <array>
30#include <cstdint> 34#include <cstdint>
31#include <functional> 35#include <functional>
32#include <limits> 36#include <limits>
@@ -60,6 +64,7 @@ struct ResourceBinding {
60 bool volume = false; // one array layer, including at mips with a single slice 64 bool volume = false; // one array layer, including at mips with a single slice
61 std::uint32_t samples = 1; // more than one: a multisampled 2D texture 65 std::uint32_t samples = 1; // more than one: a multisampled 2D texture
62 bool rgba8_typeless = false; // Original resource was R8G8B8A8_TYPELESS; views may reinterpret it. 66 bool rgba8_typeless = false; // Original resource was R8G8B8A8_TYPELESS; views may reinterpret it.
67 bool color_attachment = false; // has COLOR_ATTACHMENT usage: unordered-access rectangle clears need it
63}; 68};
64 69
65struct VulkanAccess { 70struct VulkanAccess {
@@ -373,6 +378,7 @@ inline BlockFormat block_format(VkFormat format, VkImageAspectFlags aspect) {
373 case VK_FORMAT_R32G32_SINT: return {8, 1}; 378 case VK_FORMAT_R32G32_SINT: return {8, 1};
374 case VK_FORMAT_A2B10G10R10_UNORM_PACK32: 379 case VK_FORMAT_A2B10G10R10_UNORM_PACK32:
375 case VK_FORMAT_A2B10G10R10_UINT_PACK32: 380 case VK_FORMAT_A2B10G10R10_UINT_PACK32:
381 case VK_FORMAT_E5B9G9R9_UFLOAT_PACK32:
376 case VK_FORMAT_B10G11R11_UFLOAT_PACK32: 382 case VK_FORMAT_B10G11R11_UFLOAT_PACK32:
377 case VK_FORMAT_R8G8B8A8_UNORM: 383 case VK_FORMAT_R8G8B8A8_UNORM:
378 case VK_FORMAT_R8G8B8A8_SRGB: 384 case VK_FORMAT_R8G8B8A8_SRGB:
@@ -396,6 +402,7 @@ inline BlockFormat block_format(VkFormat format, VkImageAspectFlags aspect) {
396 case VK_FORMAT_R16_SFLOAT: 402 case VK_FORMAT_R16_SFLOAT:
397 case VK_FORMAT_R16_UNORM: 403 case VK_FORMAT_R16_UNORM:
398 case VK_FORMAT_A4R4G4B4_UNORM_PACK16: 404 case VK_FORMAT_A4R4G4B4_UNORM_PACK16:
405 case VK_FORMAT_R5G6B5_UNORM_PACK16:
399 case VK_FORMAT_D16_UNORM: return {2, 1}; 406 case VK_FORMAT_D16_UNORM: return {2, 1};
400 case VK_FORMAT_R8_UNORM: return {1, 1}; 407 case VK_FORMAT_R8_UNORM: return {1, 1};
401 case VK_FORMAT_BC1_RGBA_UNORM_BLOCK: 408 case VK_FORMAT_BC1_RGBA_UNORM_BLOCK:
@@ -576,6 +583,8 @@ struct ReplayFunctions {
576 PFN_vkCmdCopyImageToBuffer copy_image_to_buffer = nullptr; 583 PFN_vkCmdCopyImageToBuffer copy_image_to_buffer = nullptr;
577 PFN_vkCmdCopyImage copy_image = nullptr; 584 PFN_vkCmdCopyImage copy_image = nullptr;
578 PFN_vkCmdResolveImage resolve_image = nullptr; // resolves 585 PFN_vkCmdResolveImage resolve_image = nullptr; // resolves
586 PFN_vkCmdFillBuffer fill_buffer = nullptr; // unordered-access buffer clears, with copy_buffer
587 PFN_vkCmdUpdateBuffer update_buffer = nullptr;
579 // VK_EXT_conditional_rendering: SetPredication. The predicate buffer must have been created with 588 // VK_EXT_conditional_rendering: SetPredication. The predicate buffer must have been created with
580 // VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT. 589 // VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT.
581 PFN_vkCmdBeginConditionalRenderingEXT begin_conditional_rendering = nullptr; 590 PFN_vkCmdBeginConditionalRenderingEXT begin_conditional_rendering = nullptr;
@@ -611,6 +620,9 @@ struct Prepared {
611 std::vector<VkBufferImageCopy> buffer_image_copies; // one direction, given by which side is an image 620 std::vector<VkBufferImageCopy> buffer_image_copies; // one direction, given by which side is an image
612 std::vector<VkImageCopy> image_copies; 621 std::vector<VkImageCopy> image_copies;
613 VkImageResolve resolve{}; // resolves 622 VkImageResolve resolve{}; // resolves
623 uav_clear::Element element; // unordered-access clears: one element of the view's format
624 VkClearColorValue clear_color{}; // ... the value that writes it into the image
625 std::vector<std::array<VkDeviceSize, 2>> fills; // ... buffer byte ranges, offset and size
614}; 626};
615 627
616// ClearRenderTargetView takes FLOATs even for integer RTVs. For the UINT formats currently exposed by 628// ClearRenderTargetView takes FLOATs even for integer RTVs. For the UINT formats currently exposed by
@@ -675,9 +687,7 @@ inline VkFormat color_view_format(const ResourceBinding& resource, const TargetV
675 default: return VK_FORMAT_UNDEFINED; 687 default: return VK_FORMAT_UNDEFINED;
676 } 688 }
677 if (!resource.rgba8_typeless) return format == resource.format ? format : VK_FORMAT_UNDEFINED; 689 if (!resource.rgba8_typeless) return format == resource.format ? format : VK_FORMAT_UNDEFINED;
678 if (resource.format != VK_FORMAT_R8G8B8A8_UNORM || resource.mip_levels != 1 || resource.array_layers != 1 || 690 if (resource.format != VK_FORMAT_R8G8B8A8_UNORM || resource.volume || resource.depth != 1 || resource.samples != 1)
679 resource.volume || resource.depth != 1 || resource.samples != 1 ||
680 target.mip || target.first_layer || target.layer_count != 1)
681 return VK_FORMAT_UNDEFINED; 691 return VK_FORMAT_UNDEFINED;
682 return format; 692 return format;
683} 693}
@@ -685,6 +695,14 @@ inline VkFormat color_view_format(const ResourceBinding& resource, const TargetV
685inline bool view_range(const ResourceBinding& resource, const TargetView& view, VkImageAspectFlags aspects, 695inline bool view_range(const ResourceBinding& resource, const TargetView& view, VkImageAspectFlags aspects,
686 VkImageSubresourceRange& out) { 696 VkImageSubresourceRange& out) {
687 if (view.mip >= resource.mip_levels) return false; 697 if (view.mip >= resource.mip_levels) return false;
698 if (resource.volume) {
699 const auto depth = std::max(1u, resource.depth >> view.mip);
700 if (aspects != VK_IMAGE_ASPECT_COLOR_BIT || view.first_layer >= depth ||
701 !view.layer_count || view.layer_count > depth - view.first_layer) return false;
702 // Layouts and transfers address one array layer for the whole 3D mip.
703 out = {aspects, view.mip, 1, 0, 1};
704 return true;
705 }
688 if (view.first_layer >= resource.array_layers || view.layer_count > resource.array_layers - view.first_layer) 706 if (view.first_layer >= resource.array_layers || view.layer_count > resource.array_layers - view.first_layer)
689 return false; 707 return false;
690 out = {aspects, view.mip, 1, view.first_layer, view.layer_count}; 708 out = {aspects, view.mip, 1, view.first_layer, view.layer_count};
@@ -715,7 +733,13 @@ inline std::vector<VkClearRect> clip(std::span<const Rect> rects, VkExtent2D ext
715 return out; 733 return out;
716} 734}
717 735
718inline void image_barrier(const ReplayFunctions& vk, VkCommandBuffer command_buffer, VkImage image, 736// A D3D12 barrier on a volume mip covers every W slice, including on devices with maintenance9.
737inline VkImageSubresourceRange layout_range(const ResourceBinding& resource, VkImageSubresourceRange range) {
738 if (resource.volume) range.layerCount = VK_REMAINING_ARRAY_LAYERS;
739 return range;
740}
741
742inline void image_barrier(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const ResourceBinding& resource,
719 const VkImageSubresourceRange& range, VkImageLayout old_layout, VkImageLayout new_layout, 743 const VkImageSubresourceRange& range, VkImageLayout old_layout, VkImageLayout new_layout,
720 VkAccessFlags src_access, VkPipelineStageFlags src_stages, VkAccessFlags dst_access, 744 VkAccessFlags src_access, VkPipelineStageFlags src_stages, VkAccessFlags dst_access,
721 VkPipelineStageFlags dst_stages) { 745 VkPipelineStageFlags dst_stages) {
@@ -727,8 +751,8 @@ inline void image_barrier(const ReplayFunctions& vk, VkCommandBuffer command_buf
727 barrier.newLayout = new_layout; 751 barrier.newLayout = new_layout;
728 barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; 752 barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
729 barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; 753 barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
730 barrier.image = image; 754 barrier.image = resource.image;
731 barrier.subresourceRange = range; 755 barrier.subresourceRange = layout_range(resource, range);
732 vk.pipeline_barrier(command_buffer, src_stages, dst_stages, 0, 0, nullptr, 0, nullptr, 1, &barrier); 756 vk.pipeline_barrier(command_buffer, src_stages, dst_stages, 0, 0, nullptr, 0, nullptr, 1, &barrier);
733} 757}
734 758
@@ -761,11 +785,11 @@ inline void initialize(const ReplayFunctions& vk, VkCommandBuffer command_buffer
761 // Vulkan cannot clear block-compressed images; those start undefined (applications upload them first). 785 // Vulkan cannot clear block-compressed images; those start undefined (applications upload them first).
762 const bool compressed = block_format(resource.format, VK_IMAGE_ASPECT_COLOR_BIT).block > 1; 786 const bool compressed = block_format(resource.format, VK_IMAGE_ASPECT_COLOR_BIT).block > 1;
763 if (resource.not_zeroed || compressed) { 787 if (resource.not_zeroed || compressed) {
764 image_barrier(vk, command_buffer, resource.image, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, layout, 0, 788 image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, layout, 0,
765 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); 789 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
766 } else { 790 } else {
767 const VkImageLayout dst = image_layout(resource, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); 791 const VkImageLayout dst = image_layout(resource, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
768 image_barrier(vk, command_buffer, resource.image, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, dst, 0, 792 image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, dst, 0,
769 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, 793 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT,
770 VK_PIPELINE_STAGE_TRANSFER_BIT); 794 VK_PIPELINE_STAGE_TRANSFER_BIT);
771 if (piece.range.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) { 795 if (piece.range.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
@@ -775,7 +799,7 @@ inline void initialize(const ReplayFunctions& vk, VkCommandBuffer command_buffer
775 const VkClearDepthStencilValue zero{}; 799 const VkClearDepthStencilValue zero{};
776 vk.clear_depth_stencil_image(command_buffer, resource.image, dst, &zero, 1, &piece.range); 800 vk.clear_depth_stencil_image(command_buffer, resource.image, dst, &zero, 1, &piece.range);
777 } 801 }
778 image_barrier(vk, command_buffer, resource.image, piece.range, dst, layout, VK_ACCESS_TRANSFER_WRITE_BIT, 802 image_barrier(vk, command_buffer, resource, piece.range, dst, layout, VK_ACCESS_TRANSFER_WRITE_BIT,
779 VK_PIPELINE_STAGE_TRANSFER_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); 803 VK_PIPELINE_STAGE_TRANSFER_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
780 } 804 }
781 piece.layout = layout; 805 piece.layout = layout;
@@ -787,6 +811,87 @@ inline bool within(std::uint64_t offset, std::uint64_t size, std::uint64_t total
787 return offset <= total && size <= total - offset; 811 return offset <= total && size <= total - offset;
788} 812}
789 813
814// The bytes of a buffer UAV clear, and whether the transfer commands can write them. Elements of up to 4 bytes
815// repeat in every aligned word, so vkCmdFillBuffer writes the aligned middle and copies from it the unaligned ends
816// (vkCmdCopyBuffer has no alignment rule); that needs one whole word in the middle. Wider elements are written
817// with vkCmdUpdateBuffer and doubled with copies, which needs a word-aligned range.
818inline ReplayResult prepare_buffer_uav_clear(const ClearUnorderedAccess& clear, Prepared& p) {
819 const UavView& view = clear.view;
820 if (!p.binding.buffer || p.binding.image) return ReplayResult::invalid_clear;
821 if (view.offset >= p.binding.size) return ReplayResult::invalid_subresource;
822 // A V# may reach past the end of the buffer (the hardware bounds-checks it); the clear stops at the end.
823 const std::uint64_t size = std::min(view.size, p.binding.size - view.offset);
824 if (view.format) {
825 if (!uav_clear::encode(VkFormat(view.format), clear.is_float, clear.values, p.element))
826 return ReplayResult::unsupported;
827 if (view.element_size != p.element.size) return ReplayResult::invalid_clear;
828 } else {
829 p.element = uav_clear::raw_element(clear.values);
830 }
831 const std::uint32_t e = p.element.size;
832 const auto add = [&](std::uint64_t offset, std::uint64_t bytes) {
833 if (!bytes) return ReplayResult::success;
834 if (offset % std::min(e, 4u)) return ReplayResult::invalid_clear;
835 if (e <= 4) {
836 const std::uint64_t a0 = (offset + 3) / 4 * 4, a1 = (offset + bytes) / 4 * 4;
837 if ((a0 != offset || a1 != offset + bytes) && a1 < a0 + 4) return ReplayResult::unsupported;
838 } else if (bytes % 4) {
839 return ReplayResult::unsupported;
840 }
841 p.fills.push_back({offset, bytes});
842 return ReplayResult::success;
843 };
844 if (clear.rects.empty()) return add(view.offset, size);
845 const std::uint64_t elements = size / view.element_size;
846 for (const Rect& r : clear.rects) {
847 if (r.top > 0 || r.bottom <= 0) continue; // a buffer has one row
848 const std::uint64_t left = std::uint64_t(std::max<std::int64_t>(r.left, 0));
849 const std::uint64_t right = std::min<std::uint64_t>(std::uint64_t(std::max<std::int64_t>(r.right, 0)), elements);
850 if (right <= left) continue;
851 if (const auto result = add(view.offset + left * view.element_size, (right - left) * view.element_size);
852 result != ReplayResult::success)
853 return result;
854 }
855 if (p.fills.empty()) p.skip = true;
856 return ReplayResult::success;
857}
858
859// Writes one prepared range; the caller has made the buffer writable by transfers.
860inline void emit_buffer_fill(const ReplayFunctions& vk, VkCommandBuffer command_buffer, VkBuffer buffer,
861 const uav_clear::Element& element, VkDeviceSize offset, VkDeviceSize size) {
862 const auto transfer_barrier = [&] {
863 memory_barrier(vk, command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
864 VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
865 };
866 if (element.size <= 4) {
867 std::uint32_t word = 0;
868 for (unsigned i = 0; i < 4; ++i) word |= std::uint32_t(element.bytes[i % element.size]) << (8 * i);
869 const VkDeviceSize a0 = (offset + 3) / 4 * 4, a1 = (offset + size) / 4 * 4;
870 if (a1 > a0) vk.fill_buffer(command_buffer, buffer, a0, a1 - a0, word);
871 VkBufferCopy ends[2]{};
872 std::uint32_t count = 0;
873 if (a0 > offset) ends[count++] = {offset + 4, offset, a0 - offset};
874 if (a1 < offset + size) ends[count++] = {a1 - 4, a1, offset + size - a1};
875 if (count) {
876 transfer_barrier();
877 vk.copy_buffer(command_buffer, buffer, buffer, count, ends);
878 }
879 return;
880 }
881 constexpr VkDeviceSize update_limit = 65536; // vkCmdUpdateBuffer's, a multiple of every element size
882 const VkDeviceSize first = std::min(size, update_limit);
883 std::vector<std::uint8_t> data(static_cast<std::size_t>(first));
884 for (std::size_t i = 0; i < data.size(); ++i) data[i] = element.bytes[i % element.size];
885 vk.update_buffer(command_buffer, buffer, offset, first, data.data());
886 for (VkDeviceSize filled = first; filled < size;) {
887 const VkDeviceSize step = std::min(filled, size - filled);
888 transfer_barrier();
889 const VkBufferCopy copy{offset, offset + filled, step};
890 vk.copy_buffer(command_buffer, buffer, buffer, 1, &copy);
891 filled += step;
892 }
893}
894
790// The one plane of one subresource a texture copy location names. 895// The one plane of one subresource a texture copy location names.
791inline bool copy_subresource(const ResourceBinding& resource, std::uint32_t subresource, VkImageSubresourceRange& out) { 896inline bool copy_subresource(const ResourceBinding& resource, std::uint32_t subresource, VkImageSubresourceRange& out) {
792 return resource.image && subresource != all_subresources && image_range(resource, subresource, out); 897 return resource.image && subresource != all_subresources && image_range(resource, subresource, out);
@@ -952,7 +1057,7 @@ inline VkImageLayout copy_layout(const ReplayFunctions& vk, VkCommandBuffer comm
952 return pieces[0].layout; 1057 return pieces[0].layout;
953 for (const auto& piece : pieces) { 1058 for (const auto& piece : pieces) {
954 if (piece.layout == target) continue; 1059 if (piece.layout == target) continue;
955 image_barrier(vk, command_buffer, resource.image, piece.range, piece.layout, target, 1060 image_barrier(vk, command_buffer, resource, piece.range, piece.layout, target,
956 VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, access, 1061 VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, access,
957 VK_PIPELINE_STAGE_TRANSFER_BIT); 1062 VK_PIPELINE_STAGE_TRANSFER_BIT);
958 } 1063 }
@@ -963,7 +1068,7 @@ inline VkImageLayout copy_layout(const ReplayFunctions& vk, VkCommandBuffer comm
963// Moves every piece to `target` (src: the D3D12 state the operation requires), runs `body`, and moves the pieces 1068// Moves every piece to `target` (src: the D3D12 state the operation requires), runs `body`, and moves the pieces
964// back to where they were. Pieces already in `target` need no transition. 1069// back to where they were. Pieces already in `target` need no transition.
965template<typename Body> 1070template<typename Body>
966void round_trip(const ReplayFunctions& vk, VkCommandBuffer command_buffer, VkImage image, 1071void round_trip(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const ResourceBinding& resource,
967 const std::vector<LayoutPiece>& pieces, VkImageLayout target, const VulkanAccess& state, 1072 const std::vector<LayoutPiece>& pieces, VkImageLayout target, const VulkanAccess& state,
968 VkAccessFlags target_access, VkPipelineStageFlags target_stages, Body&& body) { 1073 VkAccessFlags target_access, VkPipelineStageFlags target_stages, Body&& body) {
969 for (const auto& piece : pieces) { 1074 for (const auto& piece : pieces) {
@@ -971,7 +1076,7 @@ void round_trip(const ReplayFunctions& vk, VkCommandBuffer command_buffer, VkIma
971 memory_barrier(vk, command_buffer, state.access, state.stages, target_access, target_stages); 1076 memory_barrier(vk, command_buffer, state.access, state.stages, target_access, target_stages);
972 continue; 1077 continue;
973 } 1078 }
974 image_barrier(vk, command_buffer, image, piece.range, piece.layout, target, state.access, state.stages, 1079 image_barrier(vk, command_buffer, resource, piece.range, piece.layout, target, state.access, state.stages,
975 target_access, target_stages); 1080 target_access, target_stages);
976 } 1081 }
977 body(); 1082 body();
@@ -980,7 +1085,7 @@ void round_trip(const ReplayFunctions& vk, VkCommandBuffer command_buffer, VkIma
980 memory_barrier(vk, command_buffer, target_access, target_stages, state.access, state.stages); 1085 memory_barrier(vk, command_buffer, target_access, target_stages, state.access, state.stages);
981 continue; 1086 continue;
982 } 1087 }
983 image_barrier(vk, command_buffer, image, piece.range, target, piece.layout, target_access, target_stages, 1088 image_barrier(vk, command_buffer, resource, piece.range, target, piece.layout, target_access, target_stages,
984 state.access, state.stages); 1089 state.access, state.stages);
985 } 1090 }
986} 1091}
@@ -1001,9 +1106,9 @@ class PreparedList {
1001public: 1106public:
1002 const CommandList* list = nullptr; 1107 const CommandList* list = nullptr;
1003 std::vector<detail::Prepared> commands; 1108 std::vector<detail::Prepared> commands;
1004 // Copies and resolves recorded while a predicate was set. D3D12 skips them when the predicate says so, but 1109 // Copies, resolves and UAV clears that run as transfers, recorded while a predicate was set. D3D12 skips them
1005 // Vulkan's conditional rendering does not cover transfer commands, so they run unconditionally 1110 // when the predicate says so, but Vulkan's conditional rendering does not cover transfer commands, so they run
1006 // (docs/d3d12_vulkan.md section 4.7). Counted so the caller can report it. 1111 // unconditionally (docs/d3d12_vulkan.md section 4.7). Counted so the caller can report it.
1007 std::size_t unpredicated_copies = 0; 1112 std::size_t unpredicated_copies = 0;
1008}; 1113};
1009 1114
@@ -1045,6 +1150,11 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
1045 } 1150 }
1046 VkImageSubresourceRange range = p.range; 1151 VkImageSubresourceRange range = p.range;
1047 range.aspectMask = view_aspects; 1152 range.aspectMask = view_aspects;
1153 if (p.binding.volume) {
1154 // A 2D-array attachment view of a 3D image selects W slices here.
1155 range.baseArrayLayer = target.first_layer;
1156 range.layerCount = target.layer_count;
1157 }
1048 ResourceBinding view_binding = p.binding; 1158 ResourceBinding view_binding = p.binding;
1049 if (p.clear_format != VK_FORMAT_UNDEFINED) view_binding.format = p.clear_format; 1159 if (p.clear_format != VK_FORMAT_UNDEFINED) view_binding.format = p.clear_format;
1050 p.view = vk.image_view(view_binding, range); 1160 p.view = vk.image_view(view_binding, range);
@@ -1079,9 +1189,10 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
1079 if (p.clear_format == VK_FORMAT_UNDEFINED && 1189 if (p.clear_format == VK_FORMAT_UNDEFINED &&
1080 (p.binding.rgba8_typeless || color_clear->target.format != ColorViewFormat::resource)) 1190 (p.binding.rgba8_typeless || color_clear->target.format != ColorViewFormat::resource))
1081 return ReplayResult::invalid_clear; 1191 return ReplayResult::invalid_clear;
1082 if (p.clear_format != p.binding.format && color_clear->rects.empty()) { 1192 const bool partial_volume = p.binding.volume &&
1083 // vkCmdClearColorImage has no view-format parameter. Reinterpreted whole-view clears need 1193 color_clear->target.layer_count != std::max(1u, p.binding.depth >> color_clear->target.mip);
1084 // an attachment view too, including sRGB conversion and UINT numeric interpretation. 1194 if ((p.clear_format != p.binding.format || partial_volume) && color_clear->rects.empty()) {
1195 // vkCmdClearColorImage can neither reinterpret the format nor select W slices of a mip.
1085 const auto extent = detail::mip_extent(p.binding, color_clear->target.mip); 1196 const auto extent = detail::mip_extent(p.binding, color_clear->target.mip);
1086 const Rect full{0, 0, std::int32_t(extent.width), std::int32_t(extent.height)}; 1197 const Rect full{0, 0, std::int32_t(extent.width), std::int32_t(extent.height)};
1087 if (const auto r = rect_view(std::span<const Rect>(&full, 1), color_clear->target, 1198 if (const auto r = rect_view(std::span<const Rect>(&full, 1), color_clear->target,
@@ -1101,6 +1212,33 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
1101 if (const auto r = rect_view(clear_rects(depth_clear->rects), depth_clear->target, p.binding.aspects); 1212 if (const auto r = rect_view(clear_rects(depth_clear->rects), depth_clear->target, p.binding.aspects);
1102 r != ReplayResult::success) 1213 r != ReplayResult::success)
1103 return r; 1214 return r;
1215 } else if (const auto* uav = std::get_if<ClearUnorderedAccess>(&command)) {
1216 const UavView& view = uav->view;
1217 if (!bind(view.resource)) return ReplayResult::unresolved_resource;
1218 if (view.buffer) {
1219 if (!vk.fill_buffer || !vk.update_buffer || !vk.copy_buffer) return ReplayResult::unsupported;
1220 if (predicated) ++out.unpredicated_copies; // fills and copies are transfer commands
1221 if (const auto r = detail::prepare_buffer_uav_clear(*uav, p); r != ReplayResult::success) return r;
1222 continue;
1223 }
1224 if (!p.binding.image || p.binding.aspects != VK_IMAGE_ASPECT_COLOR_BIT) return ReplayResult::invalid_clear;
1225 const TargetView target{view.resource, view.mip, view.first_layer, view.layer_count};
1226 if (!detail::view_range(p.binding, target, VK_IMAGE_ASPECT_COLOR_BIT, p.range))
1227 return ReplayResult::invalid_subresource;
1228 // The view's format turns the values into bytes; the image's own format clears them in.
1229 const VkFormat view_format = view.format ? VkFormat(view.format) : p.binding.format;
1230 if (!uav_clear::encode(view_format, uav->is_float, uav->values, p.element) ||
1231 !uav_clear::decode(p.binding.format, p.element, p.clear_color))
1232 return ReplayResult::unsupported;
1233 if (!uav->rects.empty() && (!p.binding.color_attachment || p.binding.volume))
1234 return ReplayResult::unsupported;
1235 // Under a predicate a whole view is cleared as one rectangle where the image can be an attachment, as
1236 // render targets are; otherwise vkCmdClearColorImage runs unconditionally and is counted.
1237 const bool attachment = p.binding.color_attachment && !p.binding.volume;
1238 if (predicated && uav->rects.empty() && !attachment) ++out.unpredicated_copies;
1239 const auto rects = attachment ? clear_rects(uav->rects) : std::span<const Rect>(uav->rects);
1240 if (const auto r = rect_view(rects, target, VK_IMAGE_ASPECT_COLOR_BIT); r != ReplayResult::success)
1241 return r;
1104 } else if (std::holds_alternative<CopyBuffer>(command) || std::holds_alternative<CopyTexture>(command) || 1242 } else if (std::holds_alternative<CopyBuffer>(command) || std::holds_alternative<CopyTexture>(command) ||
1105 std::holds_alternative<CopyResource>(command)) { 1243 std::holds_alternative<CopyResource>(command)) {
1106 if (!copies) return ReplayResult::unsupported; 1244 if (!copies) return ReplayResult::unsupported;
@@ -1176,6 +1314,8 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
1176 using T = std::decay_t<decltype(c)>; 1314 using T = std::decay_t<decltype(c)>;
1177 if constexpr (std::is_same_v<T, ClearRenderTarget> || std::is_same_v<T, ClearDepthStencil>) 1315 if constexpr (std::is_same_v<T, ClearRenderTarget> || std::is_same_v<T, ClearDepthStencil>)
1178 return c.target.resource; 1316 return c.target.resource;
1317 else if constexpr (std::is_same_v<T, ClearUnorderedAccess>)
1318 return c.view.resource;
1179 else if constexpr (requires { c.resource; }) 1319 else if constexpr (requires { c.resource; })
1180 return c.resource; 1320 return c.resource;
1181 else 1321 else
@@ -1195,7 +1335,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
1195 auto pieces = detail::current(tracker, id, range, image_layout(p.binding, from.layout)); 1335 auto pieces = detail::current(tracker, id, range, image_layout(p.binding, from.layout));
1196 detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, from.layout), tracker); 1336 detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, from.layout), tracker);
1197 for (const auto& piece : pieces) 1337 for (const auto& piece : pieces)
1198 detail::image_barrier(vk, command_buffer, p.binding.image, piece.range, piece.layout, new_layout, 1338 detail::image_barrier(vk, command_buffer, p.binding, piece.range, piece.layout, new_layout,
1199 from.access, from.stages, to.access, to.stages); 1339 from.access, from.stages, to.access, to.stages);
1200 if (tracker) tracker->set(id, range, new_layout); 1340 if (tracker) tracker->set(id, range, new_layout);
1201 } else if (std::holds_alternative<UavBarrier>(command)) { 1341 } else if (std::holds_alternative<UavBarrier>(command)) {
@@ -1254,7 +1394,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
1254 b.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; 1394 b.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1255 b.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; 1395 b.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1256 b.image = p.binding.image; 1396 b.image = p.binding.image;
1257 b.subresourceRange = piece.range; 1397 b.subresourceRange = detail::layout_range(p.binding, piece.range);
1258 barriers.push_back(b); 1398 barriers.push_back(b);
1259 } 1399 }
1260 VkDependencyInfo dependency{VK_STRUCTURE_TYPE_DEPENDENCY_INFO}; 1400 VkDependencyInfo dependency{VK_STRUCTURE_TYPE_DEPENDENCY_INFO};
@@ -1269,7 +1409,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
1269 detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker); 1409 detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker);
1270 const VkClearColorValue color = detail::render_target_clear_color(p.clear_format, color_clear->color); 1410 const VkClearColorValue color = detail::render_target_clear_color(p.clear_format, color_clear->color);
1271 if (p.rects.empty()) { 1411 if (p.rects.empty()) {
1272 detail::round_trip(vk, command_buffer, p.binding.image, pieces, image_layout(p.binding, transfer_dst.layout), 1412 detail::round_trip(vk, command_buffer, p.binding, pieces, image_layout(p.binding, transfer_dst.layout),
1273 state, transfer_dst.access, transfer_dst.stages, [&] { 1413 state, transfer_dst.access, transfer_dst.stages, [&] {
1274 vk.clear_color_image(command_buffer, p.binding.image, image_layout(p.binding, transfer_dst.layout), 1414 vk.clear_color_image(command_buffer, p.binding.image, image_layout(p.binding, transfer_dst.layout),
1275 &color, 1, &p.range); 1415 &color, 1, &p.range);
@@ -1277,7 +1417,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
1277 continue; 1417 continue;
1278 } 1418 }
1279 const VkImageLayout attachment = image_layout(p.binding, state.layout); 1419 const VkImageLayout attachment = image_layout(p.binding, state.layout);
1280 detail::round_trip(vk, command_buffer, p.binding.image, pieces, attachment, state, state.access, 1420 detail::round_trip(vk, command_buffer, p.binding, pieces, attachment, state, state.access,
1281 state.stages, [&] { 1421 state.stages, [&] {
1282 VkRenderingAttachmentInfo info{VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO}; 1422 VkRenderingAttachmentInfo info{VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO};
1283 info.imageView = p.view; 1423 info.imageView = p.view;
@@ -1304,7 +1444,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
1304 detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker); 1444 detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker);
1305 const VkClearDepthStencilValue value{depth_clear->depth, depth_clear->stencil}; 1445 const VkClearDepthStencilValue value{depth_clear->depth, depth_clear->stencil};
1306 if (p.rects.empty()) { 1446 if (p.rects.empty()) {
1307 detail::round_trip(vk, command_buffer, p.binding.image, pieces, image_layout(p.binding, transfer_dst.layout), 1447 detail::round_trip(vk, command_buffer, p.binding, pieces, image_layout(p.binding, transfer_dst.layout),
1308 state, transfer_dst.access, transfer_dst.stages, [&] { 1448 state, transfer_dst.access, transfer_dst.stages, [&] {
1309 vk.clear_depth_stencil_image(command_buffer, p.binding.image, 1449 vk.clear_depth_stencil_image(command_buffer, p.binding.image,
1310 image_layout(p.binding, transfer_dst.layout), &value, 1, &p.range); 1450 image_layout(p.binding, transfer_dst.layout), &value, 1, &p.range);
@@ -1312,7 +1452,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
1312 continue; 1452 continue;
1313 } 1453 }
1314 const VkImageLayout attachment = image_layout(p.binding, state.layout); 1454 const VkImageLayout attachment = image_layout(p.binding, state.layout);
1315 detail::round_trip(vk, command_buffer, p.binding.image, pieces, attachment, state, state.access, 1455 detail::round_trip(vk, command_buffer, p.binding, pieces, attachment, state, state.access,
1316 state.stages, [&] { 1456 state.stages, [&] {
1317 VkRenderingAttachmentInfo info{VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO}; 1457 VkRenderingAttachmentInfo info{VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO};
1318 info.imageView = p.view; 1458 info.imageView = p.view;
@@ -1330,6 +1470,58 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
1330 vk.clear_attachments(command_buffer, 1, &attachment_clear, std::uint32_t(p.rects.size()), p.rects.data()); 1470 vk.clear_attachments(command_buffer, 1, &attachment_clear, std::uint32_t(p.rects.size()), p.rects.data());
1331 vk.end_rendering(command_buffer); 1471 vk.end_rendering(command_buffer);
1332 }); 1472 });
1473 } else if (const auto* uav = std::get_if<ClearUnorderedAccess>(&command)) {
1474 if (p.skip) continue;
1475 // The UAV state, widened to transfers: a later barrier from SYNC_CLEAR_UNORDERED_ACCESS_VIEW names the
1476 // clear stage, which is a transfer stage in the legacy masks.
1477 VulkanAccess state = vulkan_access(d3d12_state::unordered_access, false);
1478 state.access |= VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT;
1479 state.stages |= VK_PIPELINE_STAGE_TRANSFER_BIT;
1480 if (uav->view.buffer) {
1481 constexpr VkAccessFlags transfer = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT;
1482 detail::memory_barrier(vk, command_buffer, state.access, state.stages, transfer,
1483 VK_PIPELINE_STAGE_TRANSFER_BIT);
1484 for (std::size_t f = 0; f < p.fills.size(); ++f) {
1485 if (f) // rectangles may overlap
1486 detail::memory_barrier(vk, command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT,
1487 VK_PIPELINE_STAGE_TRANSFER_BIT, transfer, VK_PIPELINE_STAGE_TRANSFER_BIT);
1488 detail::emit_buffer_fill(vk, command_buffer, p.binding.buffer, p.element, p.fills[f][0],
1489 p.fills[f][1]);
1490 }
1491 detail::memory_barrier(vk, command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
1492 state.access, state.stages);
1493 continue;
1494 }
1495 // Cleared in place in GENERAL, the UAV layout, which transfer clears and attachments both accept.
1496 const VkImageLayout layout = image_layout(p.binding, state.layout);
1497 auto pieces = detail::current(tracker, id, p.range, layout);
1498 detail::initialize(vk, command_buffer, p.binding, id, pieces, layout, tracker);
1499 if (p.rects.empty()) {
1500 detail::round_trip(vk, command_buffer, p.binding, pieces, layout, state,
1501 VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, [&] {
1502 vk.clear_color_image(command_buffer, p.binding.image, layout, &p.clear_color, 1, &p.range);
1503 });
1504 continue;
1505 }
1506 detail::round_trip(vk, command_buffer, p.binding, pieces, layout, state,
1507 VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
1508 VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, [&] {
1509 VkRenderingAttachmentInfo info{VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO};
1510 info.imageView = p.view;
1511 info.imageLayout = layout;
1512 info.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
1513 info.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
1514 VkRenderingInfo rendering{VK_STRUCTURE_TYPE_RENDERING_INFO};
1515 rendering.renderArea = {{0, 0}, detail::mip_extent(p.binding, uav->view.mip)};
1516 rendering.layerCount = uav->view.layer_count;
1517 rendering.colorAttachmentCount = 1;
1518 rendering.pColorAttachments = &info;
1519 vk.begin_rendering(command_buffer, &rendering);
1520 VkClearAttachment attachment_clear{VK_IMAGE_ASPECT_COLOR_BIT, 0, {}};
1521 attachment_clear.clearValue.color = p.clear_color;
1522 vk.clear_attachments(command_buffer, 1, &attachment_clear, std::uint32_t(p.rects.size()), p.rects.data());
1523 vk.end_rendering(command_buffer);
1524 });
1333 } else if (std::holds_alternative<CopyBuffer>(command) || std::holds_alternative<CopyTexture>(command) || 1525 } else if (std::holds_alternative<CopyBuffer>(command) || std::holds_alternative<CopyTexture>(command) ||
1334 std::holds_alternative<CopyResource>(command)) { 1526 std::holds_alternative<CopyResource>(command)) {
1335 const auto [dst_id, src_id] = copy_ids(command); 1527 const auto [dst_id, src_id] = copy_ids(command);