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:
authorItsNotRexed <300290919+ItsNotRexed@users.noreply.github.com>2026-11-22 07:07:45 -0500
committerItsNotRexed <300290919+ItsNotRexed@users.noreply.github.com>2026-11-22 07:07:45 -0500
commit9b60294e2841ce351dbf2d82b7204021ad88a3f2 (patch)
tree562877bee9b2175eff1872677aa87f6f07c7863c /runtime/src
parentf3a6204413de5f8f13edcaf06412f645011f3c10 (diff)
parente1b3fca96d5d004e8b20de06a5a148b7da1b4363 (diff)
Merge pull request #1324 from lloyd
Diffstat (limited to 'runtime/src')
-rw-r--r--runtime/src/vulkan_backend.h38
-rw-r--r--runtime/src/vulkan_replay.h92
-rw-r--r--runtime/src/vulkan_scratch.h179
3 files changed, 304 insertions, 5 deletions
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h
index 35409710e..85ee68594 100644
--- a/runtime/src/vulkan_backend.h
+++ b/runtime/src/vulkan_backend.h
@@ -11,6 +11,7 @@
11#include "binary_occlusion_spirv.h" 11#include "binary_occlusion_spirv.h"
12#include "occlusion_sum_spirv.h" 12#include "occlusion_sum_spirv.h"
13#include "vulkan_depth24.h" 13#include "vulkan_depth24.h"
14#include "vulkan_scratch.h"
14#include "vulkan_replay.h" 15#include "vulkan_replay.h"
15 16
16#include <algorithm> 17#include <algorithm>
@@ -895,6 +896,14 @@ public:
895 }; 896 };
896 } 897 }
897 898
899 // Copies the replay stages through a buffer (depth <-> colour, vulkan_replay.h) take device-local scratch from
900 // `allocate`. Without this such a copy is refused as unsupported.
901 void enable_copy_scratch(PFN_vkGetDeviceProcAddr get, ScratchBuffers::Allocate allocate) {
902 std::unique_lock lock(resource_mutex_);
903 scratch_ = std::make_unique<ScratchBuffers>(get, device_, std::move(allocate));
904 if (!scratch_->loaded()) scratch_.reset();
905 }
906
898 // Called after that command buffer's submit: true when it was accepted, false when vkQueueSubmit failed. The 907 // Called after that command buffer's submit: true when it was accepted, false when vkQueueSubmit failed. The
899 // set keeps its upload pending in the second case, because the copy never reached the GPU. 908 // set keeps its upload pending in the second case, because the copy never reached the GPU.
900 void set_bindless_commit(std::function<void(bool)> commit) { 909 void set_bindless_commit(std::function<void(bool)> commit) {
@@ -1009,6 +1018,7 @@ private:
1009 std::map<std::tuple<VkImage, VkImageAspectFlags, std::uint32_t, std::uint32_t, std::uint32_t, VkFormat>, VkImageView> views_; 1018 std::map<std::tuple<VkImage, VkImageAspectFlags, std::uint32_t, std::uint32_t, std::uint32_t, VkFormat>, VkImageView> views_;
1010 std::function<bool(VkCommandBuffer)> bindless_prepare_; 1019 std::function<bool(VkCommandBuffer)> bindless_prepare_;
1011 std::unique_ptr<Depth24Converter> depth24_; 1020 std::unique_ptr<Depth24Converter> depth24_;
1021 std::unique_ptr<ScratchBuffers> scratch_; // copies staged through a buffer (depth <-> colour)
1012 std::function<void(bool)> bindless_commit_; 1022 std::function<void(bool)> bindless_commit_;
1013 std::unordered_map<QueryHeapId, QueryPool> query_pools_; // element pointers stay valid across inserts 1023 std::unordered_map<QueryHeapId, QueryPool> query_pools_; // element pointers stay valid across inserts
1014 double timestamp_period_ = 0; 1024 double timestamp_period_ = 0;
@@ -1115,6 +1125,7 @@ public:
1115 if (progress_) { 1125 if (progress_) {
1116 std::lock_guard lock(context_.tracker_mutex_); 1126 std::lock_guard lock(context_.tracker_mutex_);
1117 if (context_.depth24_) context_.depth24_->forget(progress_); // its scratch is idle now 1127 if (context_.depth24_) context_.depth24_->forget(progress_); // its scratch is idle now
1128 if (context_.scratch_) context_.scratch_->forget(progress_);
1118 } 1129 }
1119 if (pool_) vk.vkDestroyCommandPool(context_.device(), pool_, nullptr); 1130 if (pool_) vk.vkDestroyCommandPool(context_.device(), pool_, nullptr);
1120 if (progress_) vk.vkDestroySemaphore(context_.device(), progress_, nullptr); 1131 if (progress_) vk.vkDestroySemaphore(context_.device(), progress_, nullptr);
@@ -1147,6 +1158,14 @@ public:
1147 if (active && d24) d24->retire(progress, 0); 1158 if (active && d24) d24->retire(progress, 0);
1148 } 1159 }
1149 } depth24_guard{context_.depth24_.get(), progress_, false}; 1160 } depth24_guard{context_.depth24_.get(), progress_, false};
1161 struct ScratchGuard { // the same for the copy scratch
1162 ScratchBuffers* scratch = nullptr;
1163 VkSemaphore progress = VK_NULL_HANDLE;
1164 bool active = false;
1165 ~ScratchGuard() {
1166 if (active && scratch) scratch->retire(progress, 0);
1167 }
1168 } scratch_guard{context_.scratch_.get(), progress_, false};
1150 bindless_commit = context_.bindless_commit_; 1169 bindless_commit = context_.bindless_commit_;
1151 std::vector<PreparedList> prepared(lists.size()); 1170 std::vector<PreparedList> prepared(lists.size());
1152 ReplayFunctions replay = context_.replay_; 1171 ReplayFunctions replay = context_.replay_;
@@ -1182,6 +1201,17 @@ public:
1182 }; 1201 };
1183 } 1202 }
1184 } 1203 }
1204 if (context_.scratch_) {
1205 replay.copy_scratch = [this, &tracker_lock, &scratch_guard](VkDeviceSize bytes, VkBuffer& buffer,
1206 VkDeviceSize& offset) {
1207 if (!tracker_lock.owns_lock()) tracker_lock.lock();
1208 if (!scratch_guard.active) {
1209 context_.scratch_->collect();
1210 scratch_guard.active = true;
1211 }
1212 return context_.scratch_->get(bytes, buffer, offset);
1213 };
1214 }
1185 if (context_.depth24_) { 1215 if (context_.depth24_) {
1186 replay.depth24_prepare = [this, &tracker_lock, &depth24_guard](Depth24Job& job, 1216 replay.depth24_prepare = [this, &tracker_lock, &depth24_guard](Depth24Job& job,
1187 std::vector<Depth24Job>& parts) { 1217 std::vector<Depth24Job>& parts) {
@@ -1265,6 +1295,10 @@ public:
1265 context_.depth24_->retire(progress_, 0); 1295 context_.depth24_->retire(progress_, 0);
1266 depth24_guard.active = false; 1296 depth24_guard.active = false;
1267 } 1297 }
1298 if (scratch_guard.active) {
1299 context_.scratch_->retire(progress_, 0);
1300 scratch_guard.active = false;
1301 }
1268 tracker_lock.unlock(); 1302 tracker_lock.unlock();
1269 if (bindless_commit) bindless_commit(submitted); 1303 if (bindless_commit) bindless_commit(submitted);
1270 return ReplayResult::unsupported; 1304 return ReplayResult::unsupported;
@@ -1325,6 +1359,10 @@ public:
1325 context_.depth24_->retire(progress_, submitted ? submitted_ : 0); 1359 context_.depth24_->retire(progress_, submitted ? submitted_ : 0);
1326 depth24_guard.active = false; 1360 depth24_guard.active = false;
1327 } 1361 }
1362 if (scratch_guard.active) {
1363 context_.scratch_->retire(progress_, submitted ? submitted_ : 0);
1364 scratch_guard.active = false;
1365 }
1328 tracker_lock.unlock(); 1366 tracker_lock.unlock();
1329 if (bindless_commit) bindless_commit(submitted); 1367 if (bindless_commit) bindless_commit(submitted);
1330 return submitted ? ReplayResult::success : ReplayResult::unsupported; 1368 return submitted ? ReplayResult::success : ReplayResult::unsupported;
diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h
index 8f1e17213..c7b30d88c 100644
--- a/runtime/src/vulkan_replay.h
+++ b/runtime/src/vulkan_replay.h
@@ -476,6 +476,34 @@ inline bool two_planes(const ResourceBinding& resource) {
476 return (resource.aspects & depth_stencil_aspects) == depth_stencil_aspects; 476 return (resource.aspects & depth_stencil_aspects) == depth_stencil_aspects;
477} 477}
478 478
479// D3D12 copies between a depth format and a colour format of the same typeless family, bit for bit: D32_FLOAT with
480// R32_FLOAT/UINT/SINT (R32_TYPELESS) and D16_UNORM with R16_FLOAT/UNORM (R16_TYPELESS; the other R16 formats have no
481// copy layout here yet). Single-sampled, single-plane depth only: D24 and D32 with stencil have two planes, and a D24
482// stored as D32 would need the depth24 conversion. Vulkan's vkCmdCopyImage refuses mismatched aspects, so the replay
483// stages these through a buffer.
484inline bool depth_colour_pair(const ResourceBinding& a, const ResourceBinding& b) {
485 const auto family = [](VkFormat format) -> int {
486 switch (format) {
487 case VK_FORMAT_D32_SFLOAT:
488 case VK_FORMAT_R32_SFLOAT:
489 case VK_FORMAT_R32_UINT:
490 case VK_FORMAT_R32_SINT: return 32;
491 case VK_FORMAT_D16_UNORM:
492 case VK_FORMAT_R16_SFLOAT:
493 case VK_FORMAT_R16_UNORM: return 16;
494 default: return 0;
495 }
496 };
497 const auto depth_only = [](const ResourceBinding& r) {
498 return r.aspects == VK_IMAGE_ASPECT_DEPTH_BIT && !r.depth24_as_float;
499 };
500 const ResourceBinding *depth = &a, *colour = &b;
501 if (!depth_only(*depth)) std::swap(depth, colour);
502 return depth_only(*depth) && colour->aspects == VK_IMAGE_ASPECT_COLOR_BIT && a.image && b.image &&
503 a.samples == 1 && b.samples == 1 && !a.volume && !b.volume && family(a.format) &&
504 family(a.format) == family(b.format);
505}
506
479// Decodes a D3D12 subresource index. Combined depth-stencil images have two planes (0 depth, 1 stencil); 507// Decodes a D3D12 subresource index. Combined depth-stencil images have two planes (0 depth, 1 stencil);
480// every other image has one. 508// every other image has one.
481inline bool image_range(const ResourceBinding& resource, std::uint32_t subresource, VkImageSubresourceRange& out) { 509inline bool image_range(const ResourceBinding& resource, std::uint32_t subresource, VkImageSubresourceRange& out) {
@@ -760,6 +788,9 @@ struct ReplayFunctions {
760 // for a job while the list is checked, `depth24_run` records its dispatch. Without them such a copy is unsupported. 788 // for a job while the list is checked, `depth24_run` records its dispatch. Without them such a copy is unsupported.
761 std::function<bool(Depth24Job&, std::vector<Depth24Job>&)> depth24_prepare; // whole copy in, dispatches out 789 std::function<bool(Depth24Job&, std::vector<Depth24Job>&)> depth24_prepare; // whole copy in, dispatches out
762 std::function<void(VkCommandBuffer, const Depth24Job&)> depth24_run; 790 std::function<void(VkCommandBuffer, const Depth24Job&)> depth24_run;
791 // `bytes` of transfer scratch that stays alive until the submission completes (vulkan_scratch.h): depth <-> colour
792 // copies go through it, image to buffer to image. Without it such a copy is unsupported.
793 std::function<bool(VkDeviceSize bytes, VkBuffer&, VkDeviceSize&)> copy_scratch;
763 // Returns the query heap with that ID, or nullptr; it stays valid while the lists that use it run. 794 // Returns the query heap with that ID, or nullptr; it stays valid while the lists that use it run.
764 std::function<QueryPool*(QueryHeapId)> query_pool; 795 std::function<QueryPool*(QueryHeapId)> query_pool;
765 bool separate_depth_stencil_layouts = false; // must match the LayoutTracker, if one is used 796 bool separate_depth_stencil_layouts = false; // must match the LayoutTracker, if one is used
@@ -824,6 +855,9 @@ struct Prepared {
824 std::uint32_t rgb96_slice_words = 0; 855 std::uint32_t rgb96_slice_words = 0;
825 Depth24Job depth24; // the whole copy: where its scratch floats are 856 Depth24Job depth24; // the whole copy: where its scratch floats are
826 std::vector<Depth24Job> depth24_parts; // the dispatches that convert it 857 std::vector<Depth24Job> depth24_parts; // the dispatches that convert it
858 // A depth <-> colour copy: the source into `staged` (image to buffer), then `staged` into the destination.
859 VkBuffer staged = VK_NULL_HANDLE;
860 std::vector<VkBufferImageCopy> staged_reads, staged_writes;
827 std::vector<VkImageSubresourceRange> discards; // DiscardResource: the subresources to discard 861 std::vector<VkImageSubresourceRange> discards; // DiscardResource: the subresources to discard
828 VkBuffer write_buffer = VK_NULL_HANDLE; // WriteBufferImmediate: where the address lands 862 VkBuffer write_buffer = VK_NULL_HANDLE; // WriteBufferImmediate: where the address lands
829 VkDeviceSize write_offset = 0; 863 VkDeviceSize write_offset = 0;
@@ -1153,8 +1187,9 @@ inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) {
1153 if (!copy_subresource(p.binding, copy.dst.subresource, dst) || 1187 if (!copy_subresource(p.binding, copy.dst.subresource, dst) ||
1154 !copy_subresource(p.source, copy.src.subresource, src)) 1188 !copy_subresource(p.source, copy.src.subresource, src))
1155 return ReplayResult::invalid_subresource; 1189 return ReplayResult::invalid_subresource;
1156 if (dst.aspectMask != src.aspectMask || p.binding.volume != p.source.volume || 1190 if ((dst.aspectMask != src.aspectMask && !depth_colour_pair(p.binding, p.source)) ||
1157 p.binding.samples != p.source.samples || p.binding.rgb96 != p.source.rgb96) 1191 p.binding.volume != p.source.volume || p.binding.samples != p.source.samples ||
1192 p.binding.rgb96 != p.source.rgb96)
1158 return ReplayResult::invalid_copy; 1193 return ReplayResult::invalid_copy;
1159 const VkExtent2D from = mip_extent(p.source, src.baseMipLevel), to = mip_extent(p.binding, dst.baseMipLevel); 1194 const VkExtent2D from = mip_extent(p.source, src.baseMipLevel), to = mip_extent(p.binding, dst.baseMipLevel);
1160 const auto from_depth = std::max(1u, p.source.depth >> src.baseMipLevel); 1195 const auto from_depth = std::max(1u, p.source.depth >> src.baseMipLevel);
@@ -1325,12 +1360,15 @@ inline ReplayResult prepare_resource_copy(Prepared& p) {
1325 blocks(dst.height, db) == blocks(src.height, sb); 1360 blocks(dst.height, db) == blocks(src.height, sb);
1326 if (!dst.image || !src.image || !same_shape || 1361 if (!dst.image || !src.image || !same_shape ||
1327 dst.depth != src.depth || dst.volume != src.volume || dst.mip_levels != src.mip_levels || 1362 dst.depth != src.depth || dst.volume != src.volume || dst.mip_levels != src.mip_levels ||
1328 dst.array_layers != src.array_layers || dst.aspects != src.aspects || dst.samples != src.samples || 1363 dst.array_layers != src.array_layers || (dst.aspects != src.aspects && !depth_colour_pair(dst, src)) ||
1329 dst.rgb96 != src.rgb96 || 1364 dst.samples != src.samples || dst.rgb96 != src.rgb96 ||
1330 block_format(dst.format, VK_IMAGE_ASPECT_COLOR_BIT).bytes != block_format(src.format, VK_IMAGE_ASPECT_COLOR_BIT).bytes) 1365 block_format(dst.format, VK_IMAGE_ASPECT_COLOR_BIT).bytes != block_format(src.format, VK_IMAGE_ASPECT_COLOR_BIT).bytes)
1331 return ReplayResult::invalid_copy; 1366 return ReplayResult::invalid_copy;
1367 // A depth <-> colour pair has one aspect on each side; the copies name each side's own (staged by the caller).
1368 const bool cross = dst.aspects != src.aspects;
1332 for (const VkImageAspectFlags aspect : {VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_ASPECT_DEPTH_BIT, VK_IMAGE_ASPECT_STENCIL_BIT}) { 1369 for (const VkImageAspectFlags aspect : {VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_ASPECT_DEPTH_BIT, VK_IMAGE_ASPECT_STENCIL_BIT}) {
1333 if (!(dst.aspects & aspect)) continue; 1370 if (!(dst.aspects & aspect)) continue;
1371 const VkImageAspectFlags src_aspect = cross ? src.aspects : aspect;
1334 for (std::uint32_t mip = 0; mip < dst.mip_levels; ++mip) { 1372 for (std::uint32_t mip = 0; mip < dst.mip_levels; ++mip) {
1335 const VkExtent2D extent = mip_extent(src, mip), to = mip_extent(dst, mip); 1373 const VkExtent2D extent = mip_extent(src, mip), to = mip_extent(dst, mip);
1336 // Lower mips can differ in blocks (BC 12x8 mip 1 is 2x1 blocks, R32G32 3x2 mip 1 is 1x1): more source 1374 // Lower mips can differ in blocks (BC 12x8 mip 1 is 2x1 blocks, R32G32 3x2 mip 1 is 1x1): more source
@@ -1339,7 +1377,7 @@ inline ReplayResult prepare_resource_copy(Prepared& p) {
1339 // a copy is staged through a buffer. 1377 // a copy is staged through a buffer.
1340 if (sb != db && (blocks(extent.width, sb) * db > to.width || blocks(extent.height, sb) * db > to.height)) 1378 if (sb != db && (blocks(extent.width, sb) * db > to.width || blocks(extent.height, sb) * db > to.height))
1341 return ReplayResult::invalid_copy; 1379 return ReplayResult::invalid_copy;
1342 p.image_copies.push_back({{aspect, mip, 0, dst.array_layers}, {0, 0, 0}, {aspect, mip, 0, dst.array_layers}, 1380 p.image_copies.push_back({{src_aspect, mip, 0, dst.array_layers}, {0, 0, 0}, {aspect, mip, 0, dst.array_layers},
1343 {0, 0, 0}, {extent.width, extent.height, std::max(1u, src.depth >> mip)}}); 1381 {0, 0, 0}, {extent.width, extent.height, std::max(1u, src.depth >> mip)}});
1344 } 1382 }
1345 } 1383 }
@@ -1937,6 +1975,36 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
1937 } else { 1975 } else {
1938 result = detail::prepare_resource_copy(p); 1976 result = detail::prepare_resource_copy(p);
1939 } 1977 }
1978 if (result == ReplayResult::success && !p.image_copies.empty() &&
1979 p.image_copies[0].srcSubresource.aspectMask != p.image_copies[0].dstSubresource.aspectMask) {
1980 // Depth <-> colour: vkCmdCopyImage cannot mix aspects, so each region goes image -> scratch -> image,
1981 // tightly packed. Depth aspects want 4-byte buffer offsets; 16 covers every texel size here.
1982 const std::uint32_t texel =
1983 block_format(p.source.format, p.image_copies[0].srcSubresource.aspectMask).bytes;
1984 VkDeviceSize total = 0;
1985 std::vector<VkDeviceSize> offsets;
1986 for (const VkImageCopy& c : p.image_copies) {
1987 offsets.push_back(total);
1988 total += (VkDeviceSize(c.extent.width) * c.extent.height * c.extent.depth *
1989 c.srcSubresource.layerCount * texel + 15) / 16 * 16;
1990 }
1991 VkDeviceSize base = 0;
1992 if (!texel || !vk.copy_scratch || !vk.copy_scratch(total, p.staged, base))
1993 return ReplayResult::unsupported;
1994 for (std::size_t r = 0; r < p.image_copies.size(); ++r) {
1995 const VkImageCopy& c = p.image_copies[r];
1996 VkBufferImageCopy region{};
1997 region.bufferOffset = base + offsets[r];
1998 region.imageSubresource = c.srcSubresource;
1999 region.imageOffset = c.srcOffset;
2000 region.imageExtent = c.extent;
2001 p.staged_reads.push_back(region);
2002 region.imageSubresource = c.dstSubresource;
2003 region.imageOffset = c.dstOffset;
2004 p.staged_writes.push_back(region);
2005 }
2006 p.image_copies.clear();
2007 }
1940 if (result != ReplayResult::success) return result; 2008 if (result != ReplayResult::success) return result;
1941 } else if (const auto* resolve_command = std::get_if<ResolveSubresource>(&command)) { 2009 } else if (const auto* resolve_command = std::get_if<ResolveSubresource>(&command)) {
1942 if (!vk.resolve_image) return ReplayResult::unsupported; 2010 if (!vk.resolve_image) return ReplayResult::unsupported;
@@ -2529,6 +2597,20 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
2529 } else if (!p.buffer_copies.empty()) { 2597 } else if (!p.buffer_copies.empty()) {
2530 vk.copy_buffer(command_buffer, p.source.buffer, p.binding.buffer, std::uint32_t(p.buffer_copies.size()), 2598 vk.copy_buffer(command_buffer, p.source.buffer, p.binding.buffer, std::uint32_t(p.buffer_copies.size()),
2531 p.buffer_copies.data()); 2599 p.buffer_copies.data());
2600 } else if (p.staged) {
2601 // Depth <-> colour: the source into the scratch, then the scratch into the destination.
2602 const VkImageLayout src_layout = detail::copy_layout(
2603 vk, command_buffer, p.source, src_id, detail::planes_for_layout(p.source, p.source_range, separate),
2604 VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, tracker);
2605 vk.copy_image_to_buffer(command_buffer, p.source.image, src_layout, p.staged,
2606 std::uint32_t(p.staged_reads.size()), p.staged_reads.data());
2607 detail::memory_barrier(vk, command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
2608 VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
2609 const VkImageLayout dst_layout = detail::copy_layout(
2610 vk, command_buffer, p.binding, dst_id, detail::planes_for_layout(p.binding, p.range, separate),
2611 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, tracker);
2612 vk.copy_buffer_to_image(command_buffer, p.staged, p.binding.image, dst_layout,
2613 std::uint32_t(p.staged_writes.size()), p.staged_writes.data());
2532 } else if (!p.image_copies.empty()) { 2614 } else if (!p.image_copies.empty()) {
2533 const VkImageLayout src_layout = detail::copy_layout( 2615 const VkImageLayout src_layout = detail::copy_layout(
2534 vk, command_buffer, p.source, src_id, detail::planes_for_layout(p.source, p.source_range, separate), 2616 vk, command_buffer, p.source, src_id, detail::planes_for_layout(p.source, p.source_range, separate),
diff --git a/runtime/src/vulkan_scratch.h b/runtime/src/vulkan_scratch.h
new file mode 100644
index 000000000..fe29d1a5c
--- /dev/null
+++ b/runtime/src/vulkan_scratch.h
@@ -0,0 +1,179 @@
1// Scratch buffers that live until the submission that used them has completed: device-local chunks handed out
2// while a list is prepared, retired with the submission's timeline value, and reused (or freed) once the GPU is past
3// it. The replay stages copies Vulkan cannot do in one command through them (vulkan_replay.h, depth <-> colour
4// copies). Single-threaded: the caller holds the context's lock. The same life cycle as the depth24 converter's own
5// scratch (vulkan_depth24.h), which also needs descriptor pools and exists only on GPUs without D24.
6#pragma once
7
8#ifndef VK_NO_PROTOTYPES
9#define VK_NO_PROTOTYPES
10#endif
11#include <vulkan/vulkan.h>
12
13#include <algorithm>
14#include <cstdint>
15#include <functional>
16#include <utility>
17#include <vector>
18
19namespace leonida {
20
21class ScratchBuffers {
22public:
23 // A device-local allocation for a chunk; null on failure.
24 using Allocate = std::function<VkDeviceMemory(const VkMemoryRequirements&)>;
25
26 ScratchBuffers(PFN_vkGetDeviceProcAddr get, VkDevice device, Allocate allocate)
27 : device_(device), allocate_(std::move(allocate)) {
28 loaded_ = vk_.load(get, device);
29 }
30
31 ~ScratchBuffers() {
32 if (!loaded_) return;
33 vk_.vkDeviceWaitIdle(device_);
34 release(current_);
35 for (auto& batch : retired_) release(batch);
36 for (auto& chunk : spare_) destroy(chunk);
37 }
38
39 ScratchBuffers(const ScratchBuffers&) = delete;
40 ScratchBuffers& operator=(const ScratchBuffers&) = delete;
41
42 bool loaded() const { return loaded_; }
43
44 // `bytes` of transfer scratch for the next submission, at a 256-byte aligned offset (more than any copy needs).
45 bool get(std::uint64_t bytes, VkBuffer& buffer, VkDeviceSize& offset) {
46 constexpr VkDeviceSize alignment = 256, minimum = 4u << 20;
47 if (!loaded_ || !bytes) return false;
48 for (auto& chunk : current_.chunks) {
49 const VkDeviceSize start = (chunk.used + alignment - 1) / alignment * alignment;
50 if (start <= chunk.size && bytes <= chunk.size - start) {
51 chunk.used = start + bytes;
52 buffer = chunk.buffer;
53 offset = start;
54 return true;
55 }
56 }
57 Chunk chunk;
58 for (std::size_t i = 0; i < spare_.size(); ++i)
59 if (spare_[i].size >= bytes) {
60 chunk = spare_[i];
61 spare_.erase(spare_.begin() + std::ptrdiff_t(i));
62 break;
63 }
64 if (!chunk.buffer && !make_chunk(std::max<std::uint64_t>(bytes, minimum), chunk)) return false;
65 chunk.used = bytes;
66 buffer = chunk.buffer;
67 offset = 0;
68 current_.chunks.push_back(chunk);
69 return true;
70 }
71
72 // The chunks handed out since the last call belong to a submission that `timeline` reaches `ticket` for
73 // (ticket 0: nothing was submitted, they are free once `collect` runs).
74 void retire(VkSemaphore timeline, std::uint64_t ticket) {
75 if (current_.chunks.empty()) return;
76 current_.timeline = timeline;
77 current_.ticket = ticket;
78 retired_.push_back(std::move(current_));
79 current_ = {};
80 }
81
82 // The submissions on `timeline` are over and the semaphore is about to go (its queue is idle).
83 void forget(VkSemaphore timeline) {
84 for (std::size_t i = 0; i < retired_.size();) {
85 if (retired_[i].timeline != timeline) {
86 ++i;
87 continue;
88 }
89 release(retired_[i]);
90 retired_.erase(retired_.begin() + std::ptrdiff_t(i));
91 }
92 }
93
94 // Keeps for reuse (or frees) the chunks of finished submissions.
95 void collect() {
96 for (std::size_t i = 0; i < retired_.size();) {
97 std::uint64_t done = 0;
98 if (retired_[i].timeline) vk_.vkGetSemaphoreCounterValue(device_, retired_[i].timeline, &done);
99 if (done < retired_[i].ticket) {
100 ++i;
101 continue;
102 }
103 for (auto& chunk : retired_[i].chunks) {
104 chunk.used = 0;
105 if (spare_.size() < 4) spare_.push_back(chunk);
106 else destroy(chunk);
107 }
108 retired_[i].chunks.clear();
109 retired_.erase(retired_.begin() + std::ptrdiff_t(i));
110 }
111 }
112
113private:
114 struct Chunk {
115 VkBuffer buffer = VK_NULL_HANDLE;
116 VkDeviceMemory memory = VK_NULL_HANDLE;
117 VkDeviceSize size = 0, used = 0;
118 };
119 struct Batch {
120 std::vector<Chunk> chunks;
121 VkSemaphore timeline = VK_NULL_HANDLE;
122 std::uint64_t ticket = 0;
123 };
124
125 struct Functions {
126#define LEONIDA_SCRATCH_FUNCTIONS(X) \
127 X(vkCreateBuffer) X(vkDestroyBuffer) X(vkGetBufferMemoryRequirements) X(vkBindBufferMemory) X(vkFreeMemory) \
128 X(vkGetSemaphoreCounterValue) X(vkDeviceWaitIdle)
129#define LEONIDA_SCRATCH_MEMBER(name) PFN_##name name = nullptr;
130 LEONIDA_SCRATCH_FUNCTIONS(LEONIDA_SCRATCH_MEMBER)
131#undef LEONIDA_SCRATCH_MEMBER
132
133 bool load(PFN_vkGetDeviceProcAddr get, VkDevice device) {
134 bool all = true;
135#define LEONIDA_SCRATCH_LOAD(name) \
136 name = reinterpret_cast<PFN_##name>(get(device, #name)); \
137 all = all && name != nullptr;
138 LEONIDA_SCRATCH_FUNCTIONS(LEONIDA_SCRATCH_LOAD)
139#undef LEONIDA_SCRATCH_LOAD
140#undef LEONIDA_SCRATCH_FUNCTIONS
141 return all;
142 }
143 };
144
145 bool make_chunk(std::uint64_t size, Chunk& out) {
146 VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
147 info.size = size;
148 info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
149 if (vk_.vkCreateBuffer(device_, &info, nullptr, &out.buffer) != VK_SUCCESS) return false;
150 VkMemoryRequirements requirements{};
151 vk_.vkGetBufferMemoryRequirements(device_, out.buffer, &requirements);
152 out.memory = allocate_ ? allocate_(requirements) : VK_NULL_HANDLE;
153 if (!out.memory || vk_.vkBindBufferMemory(device_, out.buffer, out.memory, 0) != VK_SUCCESS) {
154 destroy(out);
155 return false;
156 }
157 out.size = size;
158 return true;
159 }
160 void destroy(Chunk& chunk) {
161 if (chunk.buffer) vk_.vkDestroyBuffer(device_, chunk.buffer, nullptr);
162 if (chunk.memory) vk_.vkFreeMemory(device_, chunk.memory, nullptr);
163 chunk = {};
164 }
165 void release(Batch& batch) {
166 for (auto& chunk : batch.chunks) destroy(chunk);
167 batch.chunks.clear();
168 }
169
170 VkDevice device_;
171 Allocate allocate_;
172 Functions vk_;
173 bool loaded_ = false;
174 Batch current_; // handed out, not yet submitted
175 std::vector<Batch> retired_; // submitted, waiting for the GPU
176 std::vector<Chunk> spare_; // finished chunks kept for reuse
177};
178
179} // namespace leonida