upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/src/vulkan_backend.h
diff options
context:
space:
mode:
authorJan Trencansky <jan.trencansky@protonmail.com>2026-11-25 17:04:49 -0500
committerJan Trencansky <jan.trencansky@protonmail.com>2026-11-25 17:04:49 -0500
commitdd6d3fd8a5c61840e822aa6469214c65c534cd7b (patch)
treea0d59e7d36b3fbf683aea20eb5c6ec1b3ceaf305 /runtime/src/vulkan_backend.h
parent6af9c80a990c6543a4593665d2465f2f14b502e7 (diff)
parentd3b8251bc390418cdbc1f2d30727b6b31d889cfa (diff)
Merge main into stream-output (#1630)
Brings #1630 up to date with main; no conflicts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'runtime/src/vulkan_backend.h')
-rw-r--r--runtime/src/vulkan_backend.h457
1 files changed, 267 insertions, 190 deletions
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h
index d86b3ded7..68ab9b194 100644
--- a/runtime/src/vulkan_backend.h
+++ b/runtime/src/vulkan_backend.h
@@ -1337,12 +1337,13 @@ public:
1337 // device-local memory, and must set VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT. LEONIDA_INDIRECT_CLAMP=0 turns the 1337 // device-local memory, and must set VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT. LEONIDA_INDIRECT_CLAMP=0 turns the
1338 // pass off at replay time. 1338 // pass off at replay time.
1339 void enable_indirect_clamp(PFN_vkGetDeviceProcAddr get, const VkPhysicalDeviceMemoryProperties& memory, 1339 void enable_indirect_clamp(PFN_vkGetDeviceProcAddr get, const VkPhysicalDeviceMemoryProperties& memory,
1340 const VkPhysicalDeviceLimits& limits, ScratchBuffers::Allocate allocate) { 1340 const VkPhysicalDeviceLimits& limits, ScratchBuffers::Allocate allocate,
1341 std::vector<std::uint32_t> families = {}) {
1341 std::unique_lock lock(resource_mutex_); 1342 std::unique_lock lock(resource_mutex_);
1342 replay_.require_indirect_clamp = indirect_clamp_enabled(); 1343 replay_.require_indirect_clamp = indirect_clamp_enabled();
1343 if (!replay_.require_indirect_clamp) return; 1344 if (!replay_.require_indirect_clamp) return;
1344 indirect_clamp_ = std::make_unique<IndirectArgumentClamp>(get, device_, memory, limits, std::move(allocate), 1345 indirect_clamp_ = std::make_unique<IndirectArgumentClamp>(get, device_, memory, limits, std::move(allocate),
1345 device_fault_.get()); 1346 device_fault_.get(), std::move(families));
1346 if (!indirect_clamp_->loaded()) { 1347 if (!indirect_clamp_->loaded()) {
1347 indirect_clamp_.reset(); 1348 indirect_clamp_.reset();
1348 return; 1349 return;
@@ -1556,32 +1557,42 @@ public:
1556 } 1557 }
1557 1558
1558 // Pipelines are registered by an opaque id (the PSO object) for as long as the PSO lives. 1559 // Pipelines are registered by an opaque id (the PSO object) for as long as the PSO lives.
1560 // Guarded by pipeline_mutex_ (separate from resource_mutex_) so shader compilation on one queue does not block
1561 // resource registration or destruction on the render thread.
1559 void add_pipeline(std::uintptr_t id, const ComputePipeline& pipeline, const char* shader = nullptr) { 1562 void add_pipeline(std::uintptr_t id, const ComputePipeline& pipeline, const char* shader = nullptr) {
1560 std::unique_lock lock(resource_mutex_); 1563 std::unique_lock lock(pipeline_mutex_);
1561 pipelines_[id] = pipeline; 1564 pipelines_[id] = pipeline;
1562 if (shader && device_fault_) device_fault_->pipeline_names[id] = {shader}; 1565 if (shader && device_fault_) device_fault_->pipeline_names[id] = {shader};
1563 } 1566 }
1564 void remove_pipeline(std::uintptr_t id) { 1567 void remove_pipeline(std::uintptr_t id) {
1565 std::unique_lock lock(resource_mutex_); 1568 std::unique_lock lock(pipeline_mutex_);
1566 pipelines_.erase(id); 1569 pipelines_.erase(id);
1567 graphics_pipelines_.erase(id); 1570 graphics_pipelines_.erase(id);
1568 if (device_fault_) device_fault_->pipeline_names.erase(id); 1571 if (device_fault_) device_fault_->pipeline_names.erase(id);
1569 } 1572 }
1570 void add_graphics_pipeline(std::uintptr_t id, const GraphicsPipeline& pipeline, 1573 void add_graphics_pipeline(std::uintptr_t id, const GraphicsPipeline& pipeline,
1571 const CheckpointShaders* shaders = nullptr) { 1574 const CheckpointShaders* shaders = nullptr) {
1572 std::unique_lock lock(resource_mutex_); 1575 std::unique_lock lock(pipeline_mutex_);
1573 graphics_pipelines_[id] = pipeline; 1576 graphics_pipelines_[id] = pipeline;
1574 if (shaders && device_fault_) device_fault_->pipeline_names[id] = *shaders; 1577 if (shaders && device_fault_) device_fault_->pipeline_names[id] = *shaders;
1575 } 1578 }
1576 // Workers for the pipelines a submission needs and that are not built yet. Null (the default): each is built where 1579 // Workers for the pipelines a submission needs and that are not built yet. Null (the default): compiled serially on
1577 // prepare() meets it, on the submitting thread. Replacing it waits for submissions that are compiling, and ends the 1580 // the submitting thread once resource_mutex_ is released. Replacing it waits for submissions that are compiling, and
1578 // workers it had. 1581 // ends the workers it had.
1579 void set_pipeline_workers(std::unique_ptr<PipelineWorkers> workers) { 1582 void set_pipeline_workers(std::unique_ptr<PipelineWorkers> workers) {
1580 std::unique_lock lock(resource_mutex_); 1583 std::unique_lock lock(pipeline_mutex_);
1581 pipeline_workers_.swap(workers); 1584 pipeline_workers_.swap(workers);
1582 } 1585 }
1586 // For the large pipelines of a submission: the memory they may use while they compile together
1587 // (PipelineCompiles::build), and what is kept while they do (LargeModuleGate::Demand). None (the default): they compile
1588 // one after another.
1589 void set_large_compiles(std::function<std::uint64_t()> budget, std::function<std::shared_ptr<void>()> demand) {
1590 std::unique_lock lock(pipeline_mutex_);
1591 large_compile_budget_ = std::move(budget);
1592 large_compile_demand_ = std::move(demand);
1593 }
1583 PipelineWorkers::Stats pipeline_worker_stats() { 1594 PipelineWorkers::Stats pipeline_worker_stats() {
1584 std::shared_lock lock(resource_mutex_); 1595 std::shared_lock lock(pipeline_mutex_);
1585 return pipeline_workers_ ? pipeline_workers_->stats() : PipelineWorkers::Stats{}; 1596 return pipeline_workers_ ? pipeline_workers_->stats() : PipelineWorkers::Stats{};
1586 } 1597 }
1587 // Configure before queue creation, when the selected queue family supports compute. 1598 // Configure before queue creation, when the selected queue family supports compute.
@@ -1785,7 +1796,7 @@ public:
1785 return true; 1796 return true;
1786 } 1797 }
1787 const char* diagnostic_compute_name(std::uintptr_t id) { 1798 const char* diagnostic_compute_name(std::uintptr_t id) {
1788 std::shared_lock lock(resource_mutex_); 1799 std::shared_lock lock(pipeline_mutex_);
1789 if (!device_fault_) return nullptr; 1800 if (!device_fault_) return nullptr;
1790 const auto it = device_fault_->pipeline_names.find(id); 1801 const auto it = device_fault_->pipeline_names.find(id);
1791 return it == device_fault_->pipeline_names.end() ? nullptr : it->second[0]; 1802 return it == device_fault_->pipeline_names.end() ? nullptr : it->second[0];
@@ -2177,6 +2188,7 @@ private:
2177 bool ray_tracing_ = false; 2188 bool ray_tracing_ = false;
2178 std::unique_ptr<XdxrBuilder> xdxr_; // set: acceleration structures are XDXR BVH4 records 2189 std::unique_ptr<XdxrBuilder> xdxr_; // set: acceleration structures are XDXR BVH4 records
2179 std::atomic<bool> device_lost_{false}; 2190 std::atomic<bool> device_lost_{false};
2191 alignas(64) std::shared_mutex pipeline_mutex_; // shared for prepare/compile/emit pipeline lookups, unique for add/remove/workers
2180 alignas(64) std::shared_mutex resource_mutex_; // shared for prepare lookups, unique for add/remove 2192 alignas(64) std::shared_mutex resource_mutex_; // shared for prepare lookups, unique for add/remove
2181 alignas(64) std::mutex tracker_mutex_; 2193 alignas(64) std::mutex tracker_mutex_;
2182 alignas(64) std::mutex views_mutex_; 2194 alignas(64) std::mutex views_mutex_;
@@ -2196,6 +2208,8 @@ private:
2196 std::unordered_map<std::uintptr_t, ComputePipeline> pipelines_; 2208 std::unordered_map<std::uintptr_t, ComputePipeline> pipelines_;
2197 std::unordered_map<std::uintptr_t, GraphicsPipeline> graphics_pipelines_; 2209 std::unordered_map<std::uintptr_t, GraphicsPipeline> graphics_pipelines_;
2198 std::unique_ptr<PipelineWorkers> pipeline_workers_; 2210 std::unique_ptr<PipelineWorkers> pipeline_workers_;
2211 std::function<std::uint64_t()> large_compile_budget_;
2212 std::function<std::shared_ptr<void>()> large_compile_demand_;
2199 std::unordered_map<std::uint64_t, VkAccelerationStructureKHR> acceleration_structures_; 2213 std::unordered_map<std::uint64_t, VkAccelerationStructureKHR> acceleration_structures_;
2200 LayoutTracker tracker_; 2214 LayoutTracker tracker_;
2201 std::mutex storage_mutex_; // a leaf lock: guards storage_pending_ and zero_pending_ only 2215 std::mutex storage_mutex_; // a leaf lock: guards storage_pending_ and zero_pending_ only
@@ -2910,11 +2924,15 @@ private:
2910 } 2924 }
2911 } khr_guard{this}; 2925 } khr_guard{this};
2912 std::function<void(bool)> bindless_commit; 2926 std::function<void(bool)> bindless_commit;
2913 // Lock hierarchy: resource_mutex_ -> tracker_mutex_ -> submit_mutex_. 2927 // Lock hierarchy: state_mutex_ -> pipeline_mutex_ -> resource_mutex_ -> tracker_mutex_ -> submit_mutex_.
2914 // Shared read-lock allows concurrent prepare() across queues; tracker_mutex_ is acquired lazily during 2928 // Shared pipeline_lock keeps registered pipelines, pipeline_names, and pipeline_workers_ alive across
2915 // prepare() only if a list actually converts a depth24_as_float copy, and otherwise right before 2929 // preparation, compilation, and emit. Shared resource_lock allows concurrent prepare() across queues and is
2916 // bindless_prepare_/emit() through submit() so bindless flushes, layout emits, and submissions stay in order. 2930 // released while unbuilt pipelines compile so add_resource()/remove_resource() never stall behind shader
2917 std::shared_lock resource_lock(context_.resource_mutex_); 2931 // compiles; tracker_mutex_ is acquired lazily during prepare() only if a list uses a shared helper, and
2932 // otherwise right before bindless_prepare_/emit() through submit() so bindless flushes, layout emits, and
2933 // submissions stay in order.
2934 std::shared_lock pipeline_lock(context_.pipeline_mutex_);
2935 std::shared_lock resource_lock(context_.resource_mutex_, std::defer_lock);
2918 std::unique_lock tracker_lock(context_.tracker_mutex_, std::defer_lock); 2936 std::unique_lock tracker_lock(context_.tracker_mutex_, std::defer_lock);
2919 // Declared after tracker_lock so any early return after depth24_->prepare() retires uncommitted scratch/pools 2937 // Declared after tracker_lock so any early return after depth24_->prepare() retires uncommitted scratch/pools
2920 // with ticket 0 while tracker_lock is still held. 2938 // with ticket 0 while tracker_lock is still held.
@@ -2925,7 +2943,7 @@ private:
2925 ~Depth24Guard() { 2943 ~Depth24Guard() {
2926 if (active && d24) d24->retire(progress, 0); 2944 if (active && d24) d24->retire(progress, 0);
2927 } 2945 }
2928 } depth24_guard{context_.depth24_.get(), progress_, false}; 2946 } depth24_guard{nullptr, progress_, false};
2929 struct ScratchGuard { // the same for the copy scratch 2947 struct ScratchGuard { // the same for the copy scratch
2930 ScratchBuffers* scratch = nullptr; 2948 ScratchBuffers* scratch = nullptr;
2931 VkSemaphore progress = VK_NULL_HANDLE; 2949 VkSemaphore progress = VK_NULL_HANDLE;
@@ -2933,7 +2951,7 @@ private:
2933 ~ScratchGuard() { 2951 ~ScratchGuard() {
2934 if (active && scratch) scratch->retire(progress, 0); 2952 if (active && scratch) scratch->retire(progress, 0);
2935 } 2953 }
2936 } scratch_guard{context_.scratch_.get(), progress_, false}; 2954 } scratch_guard{nullptr, progress_, false};
2937 struct ClampGuard { // and for the ExecuteIndirect clamp's record scratch 2955 struct ClampGuard { // and for the ExecuteIndirect clamp's record scratch
2938 IndirectArgumentClamp* clamp = nullptr; 2956 IndirectArgumentClamp* clamp = nullptr;
2939 VkSemaphore progress = VK_NULL_HANDLE; 2957 VkSemaphore progress = VK_NULL_HANDLE;
@@ -2941,9 +2959,8 @@ private:
2941 ~ClampGuard() { 2959 ~ClampGuard() {
2942 if (active && clamp) clamp->retire(progress, 0); 2960 if (active && clamp) clamp->retire(progress, 0);
2943 } 2961 }
2944 } clamp_guard{context_.indirect_clamp_.get(), progress_, false}; 2962 } clamp_guard{nullptr, progress_, false};
2945 const bool transfer_only = family_ == context_.transfer_only_family_; 2963 const bool transfer_only = family_ == context_.transfer_only_family_;
2946 if (!transfer_only) bindless_commit = context_.bindless_commit_;
2947 // Kept between executions: prepare refills each list's entries in the storage the last execution left, where 2964 // Kept between executions: prepare refills each list's entries in the storage the last execution left, where
2948 // making them fresh for every command was about half the layer's CPU cost per command (replay_cpu_bench). 2965 // making them fresh for every command was about half the layer's CPU cost per command (replay_cpu_bench).
2949 auto& prepared = prepared_; 2966 auto& prepared = prepared_;
@@ -2951,42 +2968,9 @@ private:
2951 // a queue that sees 8 lists and then 1 in every frame would rebuild them on each execution. The loops below 2968 // a queue that sees 8 lists and then 1 in every frame would rebuild them on each execution. The loops below
2952 // use only the first lists.size() entries, so stale entries are never prepared, queried or emitted. 2969 // use only the first lists.size() entries, so stale entries are never prepared, queried or emitted.
2953 if (prepared.size() < lists.size()) prepared.resize(lists.size()); 2970 if (prepared.size() < lists.size()) prepared.resize(lists.size());
2954 ReplayFunctions replay = context_.replay_; 2971 ReplayFunctions replay{};
2955 unsigned mesh_draws = 0; 2972 unsigned mesh_draws = 0;
2956 if (pipeline_profile::enabled()) replay.mesh_draw_count = &mesh_draws;
2957 std::vector<VulkanContext::GeometryUpload> geometry; 2973 std::vector<VulkanContext::GeometryUpload> geometry;
2958 if (context_.geometry_provider_) {
2959 replay.title_memory = [&](std::uint64_t va, std::uint64_t bytes, VkBuffer& buffer, VkDeviceSize& offset) {
2960 if (!va || !bytes || bytes>UINT64_MAX-va) return false;
2961 for (const auto& upload : geometry) {
2962 if (va < upload.source || va-upload.source > upload.size || bytes > upload.size-(va-upload.source)) continue;
2963 buffer=upload.buffer; offset=upload.offset+(va-upload.source);
2964 return true;
2965 }
2966 VulkanContext::GeometryUpload upload;
2967 if (!context_.geometry_provider_(va,bytes,upload)) return false;
2968 buffer=upload.buffer;offset=upload.offset;
2969 geometry.push_back(std::move(upload));
2970 return true;
2971 };
2972 }
2973 replay.graphics_family = family_ == context_.graphics_family_;
2974 replay.queue_stages = kind_ == QueueKind::copy ? detail::queue_stages_copy
2975 : kind_ == QueueKind::compute ? detail::queue_stages_compute
2976 : 0;
2977 replay.prepare_khr_instances = [this, &replay, &khr_guard](const BuildAccelerationStructure& build,
2978 VkDeviceAddress& address) {
2979 return stage_khr_instances(replay, build, khr_guard.stages, address);
2980 };
2981 replay.prepare_xdxr_table = [this, &khr_guard](VkDeviceAddress& address, std::uint32_t& count) {
2982 return stage_xdxr_table(khr_guard.stages, address, count);
2983 };
2984 if (replay.write_acceleration_structures_properties) {
2985 replay.prepare_khr_postbuild = [this, &khr_guard](std::uint32_t count, VkQueryPool& pool,
2986 std::uint32_t& first) {
2987 return allocate_khr_as_queries(count, khr_guard.as_queries, pool, first);
2988 };
2989 }
2990 std::uint64_t captures = 0; 2974 std::uint64_t captures = 0;
2991 for (const auto* list : lists) 2975 for (const auto* list : lists)
2992 for (const auto& command : list->commands()) 2976 for (const auto& command : list->commands())
@@ -2995,149 +2979,239 @@ private:
2995 std::unique_ptr<PredicatedBufferCopier::Batch> copy_batch; 2979 std::unique_ptr<PredicatedBufferCopier::Batch> copy_batch;
2996 std::unique_ptr<IndirectDispatchCounter::Batch> counted_batch; 2980 std::unique_ptr<IndirectDispatchCounter::Batch> counted_batch;
2997 std::unique_ptr<IndirectArgumentClamp::Batch> clamp_batch; 2981 std::unique_ptr<IndirectArgumentClamp::Batch> clamp_batch;
2998 if (captures) { 2982 const auto& occlusion_memory = context_.occlusion_resolve_memory_;
2999 if (kind_ == QueueKind::copy || !context_.predicate_reducer_ || family_ != context_.predicate_family_) 2983 const bool can_resolve_occlusion = occlusion_memory.memoryTypeCount != 0;
3000 return queue_unsupported(__LINE__); 2984 const auto resolve = [this](ResourceId id) { return context_.resolve(id); };
3001 // The helper's lazy pipeline is shared by queues. Serialize preparation with the tracker lock, 2985 std::uint32_t segments = 0, statistics_segments = 0;
3002 // retaining main's resource -> tracker -> submit lock order through emit and submission. 2986 bool has_queries = false;
3003 if (!tracker_lock.owns_lock()) tracker_lock.lock(); 2987 const auto run_compiles = [this](std::size_t count, const std::function<void(std::size_t)>& job) {
3004 batch = context_.predicate_reducer_->batch(captures); 2988 context_.pipeline_workers_->run(count, job);
3005 if (!batch) return queue_unsupported(__LINE__); 2989 };
3006 replay.prepare_predicate = [&](VkBuffer buffer, VkDeviceSize offset, PredicateCapture& out) { 2990 PipelineCompiles prior_compiles;
3007 return batch->prepare(buffer, offset, out); 2991 bool has_prior_compiles = false;
2992 for (int pass = 0;; ++pass) {
2993 resource_lock.lock();
2994 bindless_commit = !transfer_only ? context_.bindless_commit_ : std::function<void(bool)>{};
2995 replay = context_.replay_;
2996 mesh_draws = 0;
2997 if (pipeline_profile::enabled()) replay.mesh_draw_count = &mesh_draws;
2998 if (context_.geometry_provider_) {
2999 replay.title_memory = [&](std::uint64_t va, std::uint64_t bytes, VkBuffer& buffer, VkDeviceSize& offset) {
3000 if (!va || !bytes || bytes>UINT64_MAX-va) return false;
3001 for (const auto& upload : geometry) {
3002 if (va < upload.source || va-upload.source > upload.size || bytes > upload.size-(va-upload.source)) continue;
3003 buffer=upload.buffer; offset=upload.offset+(va-upload.source);
3004 return true;
3005 }
3006 VulkanContext::GeometryUpload upload;
3007 if (!context_.geometry_provider_(va,bytes,upload)) return false;
3008 buffer=upload.buffer;offset=upload.offset;
3009 geometry.push_back(std::move(upload));
3010 return true;
3011 };
3012 }
3013 replay.graphics_family = family_ == context_.graphics_family_;
3014 replay.queue_stages = kind_ == QueueKind::copy ? detail::queue_stages_copy
3015 : kind_ == QueueKind::compute ? detail::queue_stages_compute
3016 : 0;
3017 replay.prepare_khr_instances = [this, &replay, &khr_guard](const BuildAccelerationStructure& build,
3018 VkDeviceAddress& address) {
3019 return stage_khr_instances(replay, build, khr_guard.stages, address);
3008 }; 3020 };
3009 replay.capture_predicate = [&](VkCommandBuffer cb, const PredicateCapture& p) { 3021 replay.prepare_xdxr_table = [this, &khr_guard](VkDeviceAddress& address, std::uint32_t& count) {
3010 context_.predicate_reducer_->capture(cb, p); 3022 return stage_xdxr_table(khr_guard.stages, address, count);
3011 }; 3023 };
3012 if (context_.predicated_copier_) { 3024 if (replay.write_acceleration_structures_properties) {
3013 copy_batch = context_.predicated_copier_->batch(); 3025 replay.prepare_khr_postbuild = [this, &khr_guard](std::uint32_t count, VkQueryPool& pool,
3014 replay.prepare_predicated_copy = [&](VkBuffer source, VkBuffer destination, VkDeviceSize src, 3026 std::uint32_t& first) {
3015 VkDeviceSize dst, VkDeviceSize size, 3027 return allocate_khr_as_queries(count, khr_guard.as_queries, pool, first);
3016 std::vector<PredicatedCopyDispatch>& out) {
3017 return copy_batch->prepare(source, destination, src, dst, size, out);
3018 };
3019 replay.emit_predicated_copy = [&](VkCommandBuffer cb, const std::vector<PredicatedCopyDispatch>& jobs) {
3020 context_.predicated_copier_->emit(cb, jobs);
3021 }; 3028 };
3022 } 3029 }
3023 } 3030 if (captures) {
3024 if (context_.scratch_) { 3031 if (kind_ == QueueKind::copy || !context_.predicate_reducer_ || family_ != context_.predicate_family_)
3025 replay.copy_scratch = [this, &tracker_lock, &scratch_guard](VkDeviceSize bytes, VkBuffer& buffer, 3032 return queue_unsupported(__LINE__);
3026 VkDeviceSize& offset) { 3033 // The helper's lazy pipeline is shared by queues. Serialize preparation with the tracker lock,
3034 // retaining pipeline -> resource -> tracker -> submit lock order through emit and submission.
3027 if (!tracker_lock.owns_lock()) tracker_lock.lock(); 3035 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3028 if (!scratch_guard.active) { 3036 batch = context_.predicate_reducer_->batch(captures);
3029 context_.scratch_->collect(); 3037 if (!batch) return queue_unsupported(__LINE__);
3030 scratch_guard.active = true; 3038 replay.prepare_predicate = [&](VkBuffer buffer, VkDeviceSize offset, PredicateCapture& out) {
3039 return batch->prepare(buffer, offset, out);
3040 };
3041 replay.capture_predicate = [&](VkCommandBuffer cb, const PredicateCapture& p) {
3042 context_.predicate_reducer_->capture(cb, p);
3043 };
3044 if (context_.predicated_copier_) {
3045 copy_batch = context_.predicated_copier_->batch();
3046 replay.prepare_predicated_copy = [&](VkBuffer source, VkBuffer destination, VkDeviceSize src,
3047 VkDeviceSize dst, VkDeviceSize size,
3048 std::vector<PredicatedCopyDispatch>& out) {
3049 return copy_batch->prepare(source, destination, src, dst, size, out);
3050 };
3051 replay.emit_predicated_copy = [&](VkCommandBuffer cb, const std::vector<PredicatedCopyDispatch>& jobs) {
3052 context_.predicated_copier_->emit(cb, jobs);
3053 };
3031 } 3054 }
3032 return context_.scratch_->get(bytes, buffer, offset); 3055 }
3033 }; 3056 if (context_.scratch_) {
3034 } 3057 replay.copy_scratch = [this, &tracker_lock, &scratch_guard](VkDeviceSize bytes, VkBuffer& buffer,
3035 if (kind_ != QueueKind::copy && context_.indirect_clamp_) { 3058 VkDeviceSize& offset) {
3036 // The record scratch belongs to this submission: collected here, retired below with its ticket. The 3059 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3037 // counter slots are read back once that ticket completes (the batch's destructor). 3060 if (!scratch_guard.active) {
3038 replay.prepare_indirect_clamp = [this, &tracker_lock, &clamp_batch, &clamp_guard]( 3061 scratch_guard.scratch = context_.scratch_.get();
3039 VkBuffer arguments, VkDeviceSize argument_offset, VkBuffer count, 3062 context_.scratch_->collect();
3040 VkDeviceSize count_offset, std::uint32_t kind, std::uint32_t stride, 3063 scratch_guard.active = true;
3041 std::uint32_t max_count, ClampedIndirect& out) { 3064 }
3042 // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation. 3065 return context_.scratch_->get(bytes, buffer, offset);
3043 if (!tracker_lock.owns_lock()) tracker_lock.lock(); 3066 };
3044 if (!clamp_batch) clamp_batch = context_.indirect_clamp_->batch(); 3067 }
3045 if (!clamp_guard.active) { 3068 if (kind_ != QueueKind::copy && context_.indirect_clamp_) {
3046 context_.indirect_clamp_->collect(); 3069 // The record scratch belongs to this submission: collected here, retired below with its ticket. The
3047 clamp_guard.active = true; 3070 // counter slots are read back once that ticket completes (the batch's destructor).
3071 replay.prepare_indirect_clamp = [this, &tracker_lock, &clamp_batch, &clamp_guard](
3072 VkBuffer arguments, VkDeviceSize argument_offset, VkBuffer count,
3073 VkDeviceSize count_offset, std::uint32_t kind, std::uint32_t stride,
3074 std::uint32_t max_count, ClampedIndirect& out) {
3075 // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation.
3076 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3077 if (!clamp_batch) clamp_batch = context_.indirect_clamp_->batch();
3078 if (!clamp_guard.active) {
3079 clamp_guard.clamp = context_.indirect_clamp_.get();
3080 context_.indirect_clamp_->collect();
3081 clamp_guard.active = true;
3082 }
3083 return clamp_batch->prepare(arguments, argument_offset, count, count_offset, kind, stride,
3084 max_count, out);
3085 };
3086 }
3087 if (kind_ != QueueKind::copy && context_.counted_dispatch_) {
3088 replay.prepare_counted_dispatch = [this, &tracker_lock, &counted_batch](
3089 VkBuffer args, VkDeviceSize args_offset, VkBuffer count, VkDeviceSize count_offset,
3090 std::uint32_t stride, std::uint32_t maximum, CountedDispatch& out) {
3091 // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation.
3092 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3093 if (!counted_batch) counted_batch = context_.counted_dispatch_->batch();
3094 return counted_batch->prepare(args, args_offset, count, count_offset, stride, maximum, out);
3095 };
3096 replay.emit_counted_dispatch = [this](VkCommandBuffer cb, const CountedDispatch& job) {
3097 context_.counted_dispatch_->emit(cb, job);
3098 };
3099 }
3100 if (kind_ != QueueKind::copy && context_.quad_indices_ && context_.scratch_) {
3101 replay.prepare_quad_indices = [this, &tracker_lock](
3102 VkBuffer indices, VkDeviceSize offset, VkIndexType type, std::uint64_t readable, std::uint32_t quads,
3103 VkBuffer scratch, VkDeviceSize scratch_offset, QuadIndexExpansion& out) {
3104 // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation.
3105 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3106 return context_.quad_indices_->prepare(indices, offset, type, readable, quads, scratch,
3107 scratch_offset, out);
3108 };
3109 replay.emit_quad_indices = [this](VkCommandBuffer cb, const QuadIndexExpansion& job) {
3110 context_.quad_indices_->emit(cb, job);
3111 };
3112 }
3113 if (context_.depth24_ && !transfer_only) {
3114 replay.depth24_prepare = [this, &tracker_lock, &depth24_guard](Depth24Job& job,
3115 std::vector<Depth24Job>& parts) {
3116 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3117 if (!depth24_guard.active) {
3118 depth24_guard.d24 = context_.depth24_.get();
3119 context_.depth24_->collect();
3120 depth24_guard.active = true;
3121 }
3122 return context_.depth24_->prepare(job, parts);
3123 };
3124 }
3125 if (can_resolve_occlusion) {
3126 replay.sum_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first,
3127 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) {
3128 occlusion_resolve_->sum(cb, pool, first, count, dst, offset);
3129 };
3130 replay.resolve_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first,
3131 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) {
3132 occlusion_resolve_->normalize(cb, pool, first, count, dst, offset);
3133 };
3134 replay.sum_statistics = [this](VkCommandBuffer cb, VkQueryPool pool, VkQueryPool mesh_pool,
3135 VkQueryPool primitives_pool, const std::uint8_t* mesh,
3136 std::uint32_t first, std::uint32_t count, VkBuffer dst,
3137 VkDeviceSize offset) {
3138 occlusion_resolve_->sum_statistics(cb, pool, mesh_pool, primitives_pool, mesh, first, count, dst,
3139 offset);
3140 };
3141 replay.sum_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first,
3142 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) {
3143 occlusion_resolve_->sum_binary(cb, pool, first, count, dst, offset);
3144 };
3145 }
3146 segments = 0;
3147 statistics_segments = 0;
3148 has_queries = false;
3149 // Collect unbuilt pipelines via PipelineCompiles (whether pipeline_workers_ is enabled or serial).
3150 // On pass 0, if any pipeline must be compiled, release pass-0 transient state along with tracker_lock
3151 // and resource_lock before invoking the compiler (keeping pipeline_lock so registered pipelines and
3152 // workers stay alive), then re-prepare on pass 1 against current resources.
3153 PipelineCompiles compiles;
3154 replay.compiles = &compiles;
3155 ReplayResult prepare_result = ReplayResult::success;
3156 for (std::size_t i = 0; i < lists.size(); ++i) {
3157 const auto result = prepare(*lists[i], resolve, replay, prepared[i], can_resolve_occlusion);
3158 if (result != ReplayResult::success) {
3159 prepare_result = result;
3160 break;
3048 } 3161 }
3049 return clamp_batch->prepare(arguments, argument_offset, count, count_offset, kind, stride, max_count, 3162 if (prepared[i].segment_count > UINT32_MAX - segments ||
3050 out); 3163 prepared[i].statistics_segment_count > UINT32_MAX - statistics_segments)
3051 }; 3164 return queue_unsupported(__LINE__);
3052 } 3165 segments += prepared[i].segment_count;
3053 if (kind_ != QueueKind::copy && context_.counted_dispatch_) { 3166 statistics_segments += prepared[i].statistics_segment_count;
3054 replay.prepare_counted_dispatch = [this, &tracker_lock, &counted_batch]( 3167 has_queries = has_queries || !prepared[i].queries.empty();
3055 VkBuffer args, VkDeviceSize args_offset, VkBuffer count, VkDeviceSize count_offset, 3168 }
3056 std::uint32_t stride, std::uint32_t maximum, CountedDispatch& out) { 3169 if (pass == 0 && !compiles.empty()) {
3057 // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation. 3170 if (depth24_guard.active) {
3058 if (!tracker_lock.owns_lock()) tracker_lock.lock(); 3171 context_.depth24_->retire(progress_, 0);
3059 if (!counted_batch) counted_batch = context_.counted_dispatch_->batch(); 3172 depth24_guard.active = false;
3060 return counted_batch->prepare(args, args_offset, count, count_offset, stride, maximum, out);
3061 };
3062 replay.emit_counted_dispatch = [this](VkCommandBuffer cb, const CountedDispatch& job) {
3063 context_.counted_dispatch_->emit(cb, job);
3064 };
3065 }
3066 if (kind_ != QueueKind::copy && context_.quad_indices_ && context_.scratch_) {
3067 replay.prepare_quad_indices = [this, &tracker_lock](
3068 VkBuffer indices, VkDeviceSize offset, VkIndexType type, std::uint64_t readable, std::uint32_t quads,
3069 VkBuffer scratch, VkDeviceSize scratch_offset, QuadIndexExpansion& out) {
3070 // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation.
3071 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3072 return context_.quad_indices_->prepare(indices, offset, type, readable, quads, scratch,
3073 scratch_offset, out);
3074 };
3075 replay.emit_quad_indices = [this](VkCommandBuffer cb, const QuadIndexExpansion& job) {
3076 context_.quad_indices_->emit(cb, job);
3077 };
3078 }
3079 if (context_.depth24_ && !transfer_only) {
3080 replay.depth24_prepare = [this, &tracker_lock, &depth24_guard](Depth24Job& job,
3081 std::vector<Depth24Job>& parts) {
3082 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3083 if (!depth24_guard.active) {
3084 context_.depth24_->collect();
3085 depth24_guard.active = true;
3086 } 3173 }
3087 return context_.depth24_->prepare(job, parts); 3174 if (scratch_guard.active) {
3088 }; 3175 context_.scratch_->retire(progress_, 0);
3089 } 3176 scratch_guard.active = false;
3090 const auto& occlusion_memory = context_.occlusion_resolve_memory_; 3177 }
3091 const bool can_resolve_occlusion = occlusion_memory.memoryTypeCount != 0; 3178 if (clamp_guard.active) {
3092 if (can_resolve_occlusion) { 3179 context_.indirect_clamp_->retire(progress_, 0);
3093 replay.sum_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, 3180 clamp_guard.active = false;
3094 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { 3181 }
3095 occlusion_resolve_->sum(cb, pool, first, count, dst, offset); 3182 batch.reset();
3096 }; 3183 copy_batch.reset();
3097 replay.resolve_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, 3184 counted_batch.reset();
3098 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { 3185 clamp_batch.reset();
3099 occlusion_resolve_->normalize(cb, pool, first, count, dst, offset); 3186 if (tracker_lock.owns_lock()) tracker_lock.unlock();
3100 }; 3187 resource_lock.unlock();
3101 replay.sum_statistics = [this](VkCommandBuffer cb, VkQueryPool pool, VkQueryPool mesh_pool, 3188 recycle_khr_stages(khr_guard.stages);
3102 VkQueryPool primitives_pool, const std::uint8_t* mesh, 3189 recycle_khr_as_queries(khr_guard.as_queries);
3103 std::uint32_t first, std::uint32_t count, VkBuffer dst, 3190 geometry.clear();
3104 VkDeviceSize offset) { 3191
3105 occlusion_resolve_->sum_statistics(cb, pool, mesh_pool, primitives_pool, mesh, first, count, dst, 3192 std::shared_ptr<void> demand;
3106 offset); 3193 if (context_.large_compile_demand_ && compiles.any_large()) demand = context_.large_compile_demand_();
3107 }; 3194 if (context_.pipeline_workers_)
3108 replay.sum_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, 3195 compiles.build(run_compiles, context_.large_compile_budget_);
3109 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { 3196 else
3110 occlusion_resolve_->sum_binary(cb, pool, first, count, dst, offset); 3197 compiles.build_serial();
3111 }; 3198 demand.reset();
3112 } 3199 const ReplayResult compile_result = check_compiled_pipelines(compiles, prepare_result);
3113 const auto resolve = [this](ResourceId id) { return context_.resolve(id); }; 3200 if (compile_result != ReplayResult::success) return compile_result;
3114 std::uint32_t segments = 0, statistics_segments = 0; 3201 prior_compiles = std::move(compiles);
3115 bool has_queries = false; 3202 has_prior_compiles = true;
3116 // With workers, the pipelines the lists need and that are not built yet are compiled together below instead of 3203 continue;
3117 // one after another in prepare(). resource_lock is held until they are all built, which keeps the pipeline
3118 // states that own them alive (remove_pipeline takes it uniquely).
3119 PipelineCompiles compiles;
3120 if (context_.pipeline_workers_) replay.compiles = &compiles;
3121 ReplayResult prepare_result = ReplayResult::success;
3122 for (std::size_t i = 0; i < lists.size(); ++i) {
3123 const auto result = prepare(*lists[i], resolve, replay, prepared[i], can_resolve_occlusion);
3124 if (result != ReplayResult::success) {
3125 prepare_result = result;
3126 break;
3127 } 3204 }
3128 if (prepared[i].segment_count > UINT32_MAX - segments || 3205 const PipelineCompiles* prior = has_prior_compiles ? &prior_compiles : nullptr;
3129 prepared[i].statistics_segment_count > UINT32_MAX - statistics_segments) 3206 prepare_result = context_.pipeline_workers_
3130 return queue_unsupported(__LINE__); 3207 ? build_pipelines(compiles, std::span(prepared).first(lists.size()), prepare_result,
3131 segments += prepared[i].segment_count; 3208 run_compiles, context_.large_compile_budget_, prior)
3132 statistics_segments += prepared[i].statistics_segment_count; 3209 : build_pipelines_serial(compiles, std::span(prepared).first(lists.size()),
3133 has_queries = has_queries || !prepared[i].queries.empty(); 3210 prepare_result, prior);
3134 } 3211 replay.compiles = nullptr;
3135 prepare_result = build_pipelines( 3212 if (prepare_result != ReplayResult::success) return prepare_result;
3136 compiles, std::span(prepared).first(lists.size()), prepare_result, 3213 break;
3137 [this](std::size_t count, const std::function<void(std::size_t)>& job) { 3214 }
3138 context_.pipeline_workers_->run(count, job);
3139 });
3140 if (prepare_result != ReplayResult::success) return prepare_result;
3141 const auto segment_pool = [this](VkQueryType type, std::uint32_t count, 3215 const auto segment_pool = [this](VkQueryType type, std::uint32_t count,
3142 std::shared_ptr<OcclusionSegmentPool>& out) { 3216 std::shared_ptr<OcclusionSegmentPool>& out) {
3143 const auto& vk = context_.vk; 3217 const auto& vk = context_.vk;
@@ -3264,6 +3338,7 @@ private:
3264 const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer), 3338 const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer),
3265 "vkEndCommandBuffer") == VK_SUCCESS; 3339 "vkEndCommandBuffer") == VK_SUCCESS;
3266 resource_lock.unlock(); 3340 resource_lock.unlock();
3341 pipeline_lock.unlock();
3267 const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0); 3342 const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0);
3268 if (!submitted) discard(); 3343 if (!submitted) discard();
3269 if (depth24_guard.active) { 3344 if (depth24_guard.active) {
@@ -3397,7 +3472,8 @@ private:
3397 } 3472 }
3398 const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer), 3473 const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer),
3399 "vkEndCommandBuffer") == VK_SUCCESS; 3474 "vkEndCommandBuffer") == VK_SUCCESS;
3400 resource_lock.unlock(); // release resource_mutex_ before vkQueueSubmit while keeping tracker_lock held 3475 resource_lock.unlock(); // release resource_mutex_ and pipeline_mutex_ before vkQueueSubmit while keeping tracker_lock held
3476 pipeline_lock.unlock();
3401 const bool wait_previous = ordered_timestamps && submitted_; 3477 const bool wait_previous = ordered_timestamps && submitted_;
3402 if (wait_previous) { 3478 if (wait_previous) {
3403 waits_.push_back(progress_); 3479 waits_.push_back(progress_);
@@ -4082,7 +4158,8 @@ private:
4082 std::vector<PreparedList> prepared_; 4158 std::vector<PreparedList> prepared_;
4083 std::uint32_t open_labels_ = 0; // queue labels begun and not ended 4159 std::uint32_t open_labels_ = 0; // queue labels begun and not ended
4084 bool ok_ = false; 4160 bool ok_ = false;
4085 // Wait-before-Signal. state_mutex_ is outermost (before resource_mutex_ -> tracker_mutex_ -> submit_mutex_) and 4161 // Wait-before-Signal. state_mutex_ is outermost (before pipeline_mutex_ -> resource_mutex_ -> tracker_mutex_ ->
4162 // submit_mutex_) and
4086 // guards the members above that execute, signal, wait and marker touch. 4163 // guards the members above that execute, signal, wait and marker touch.
4087 std::mutex state_mutex_; 4164 std::mutex state_mutex_;
4088 std::deque<Deferred> held_; 4165 std::deque<Deferred> held_;