upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/src/vulkan_present.h
diff options
context:
space:
mode:
Diffstat (limited to 'runtime/src/vulkan_present.h')
-rw-r--r--runtime/src/vulkan_present.h398
1 files changed, 379 insertions, 19 deletions
diff --git a/runtime/src/vulkan_present.h b/runtime/src/vulkan_present.h
index efdbd583d..f01167cf4 100644
--- a/runtime/src/vulkan_present.h
+++ b/runtime/src/vulkan_present.h
@@ -27,6 +27,8 @@
27 27
28#include "vulkan_backend.h" 28#include "vulkan_backend.h"
29#include "vulkan_present_compose.h" 29#include "vulkan_present_compose.h"
30#include "fsdraw_probe.h" // LOCAL DIAGNOSTIC
31#include "local_diagnostics.h"
30#include "present_dump.h" 32#include "present_dump.h"
31 33
32// Use the original EXT spellings. They are aliases of the promoted KHR types and are available in older headers. 34// Use the original EXT spellings. They are aliases of the promoted KHR types and are available in older headers.
@@ -186,6 +188,11 @@ public:
186 if (const char* limit = std::getenv("LEONIDA_CAPTURE_LIMIT")) capture_limit_ = std::max(1, std::atoi(limit)); 188 if (const char* limit = std::getenv("LEONIDA_CAPTURE_LIMIT")) capture_limit_ = std::max(1, std::atoi(limit));
187 std::fprintf(stderr, "[rt] present: capture on: every %d presented frame(s), at most %d, into %s\n", 189 std::fprintf(stderr, "[rt] present: capture on: every %d presented frame(s), at most %d, into %s\n",
188 capture_every_, capture_limit_, capture_dir_.c_str()); 190 capture_every_, capture_limit_, capture_dir_.c_str());
191 // LOCAL DIAGNOSTIC: LEONIDA_CAPTURE_SOURCE=1 also reads back the presented source texture itself.
192 if (const char* source = std::getenv("LEONIDA_CAPTURE_SOURCE"); source && *source && *source != '0') {
193 probe_source_ = true;
194 std::fprintf(stderr, "[rt] present-probe: source capture on\n");
195 }
189 } 196 }
190 ok_ = recreate(true, false); 197 ok_ = recreate(true, false);
191 if (!ok_ && capture_to_disk_) { 198 if (!ok_ && capture_to_disk_) {
@@ -205,7 +212,7 @@ public:
205 const VkDevice device = context_.device(); 212 const VkDevice device = context_.device();
206 { 213 {
207 std::lock_guard lock(context_.submit_mutex()); 214 std::lock_guard lock(context_.submit_mutex());
208 vk.vkQueueWaitIdle(queue_); 215 context_.observe_result(vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle (present)");
209 // A WSI layer may perform a device-wide idle while destroying the swapchain. 216 // A WSI layer may perform a device-wide idle while destroying the swapchain.
210 // Keep that implicit idle serialized with submits from every context queue. 217 // Keep that implicit idle serialized with submits from every context queue.
211 release(swapchain_); 218 release(swapchain_);
@@ -220,6 +227,7 @@ public:
220 if (frame.done) vkDestroyFence_(device, frame.done, nullptr); 227 if (frame.done) vkDestroyFence_(device, frame.done, nullptr);
221 if (frame.acquired) vk.vkDestroySemaphore(device, frame.acquired, nullptr); 228 if (frame.acquired) vk.vkDestroySemaphore(device, frame.acquired, nullptr);
222 } 229 }
230 if (probe_fence_) vkDestroyFence_(device, probe_fence_, nullptr); // LOCAL DIAGNOSTIC
223 if (pool_) vk.vkDestroyCommandPool(device, pool_, nullptr); 231 if (pool_) vk.vkDestroyCommandPool(device, pool_, nullptr);
224 if (surface_ && vkDestroySurfaceKHR_) vkDestroySurfaceKHR_(instance_, surface_, nullptr); 232 if (surface_ && vkDestroySurfaceKHR_) vkDestroySurfaceKHR_(instance_, surface_, nullptr);
225 } 233 }
@@ -341,6 +349,7 @@ public:
341 bool enable_capture() { 349 bool enable_capture() {
342 std::lock_guard lock(present_mutex_); 350 std::lock_guard lock(present_mutex_);
343 if (!ok_) return false; 351 if (!ok_) return false;
352 splash_capture_only_ = false;
344 capture_ = true; 353 capture_ = true;
345 stale_ = true; 354 stale_ = true;
346 if (!recreate(vsync_, swapchain_srgb_, swapchain_hdr_req_) || (swapchain_ && !capture_buffer_)) { 355 if (!recreate(vsync_, swapchain_srgb_, swapchain_hdr_req_) || (swapchain_ && !capture_buffer_)) {
@@ -350,6 +359,9 @@ public:
350 return true; 359 return true;
351 } 360 }
352 361
362 // Present the shell image immediately. Keep it on screen until the window has a non-black title frame.
363 bool present_splash(ResourceId source, std::shared_ptr<void> owner);
364
353 // The last presented frame as the swapchain stores it (4 bytes a texel, rows tightly packed, format() order). 365 // The last presented frame as the swapchain stores it (4 bytes a texel, rows tightly packed, format() order).
354 // Waits for the frame to finish. False when nothing was presented since enable_capture(), after a present 366 // Waits for the frame to finish. False when nothing was presented since enable_capture(), after a present
355 // that was skipped because the window is minimised (it returned VK_SUCCESS but showed nothing), until the next 367 // that was skipped because the window is minimised (it returned VK_SUCCESS but showed nothing), until the next
@@ -358,7 +370,8 @@ public:
358 std::lock_guard lock(present_mutex_); 370 std::lock_guard lock(present_mutex_);
359 if (!capture_ || !capture_ptr_ || !captured_) return false; 371 if (!capture_ || !capture_ptr_ || !captured_) return false;
360 const Frame& frame = frames_[(frame_index_ + frames_.size() - 1) % frames_.size()]; 372 const Frame& frame = frames_[(frame_index_ + frames_.size() - 1) % frames_.size()];
361 if (vkWaitForFences_(context_.device(), 1, &frame.done, VK_TRUE, UINT64_MAX) != VK_SUCCESS) 373 if (context_.observe_result(vkWaitForFences_(context_.device(), 1, &frame.done, VK_TRUE, UINT64_MAX),
374 "vkWaitForFences (present readback)") != VK_SUCCESS)
362 return false; 375 return false;
363 pixels.assign(capture_ptr_, capture_ptr_ + std::size_t(captured_extent_.width) * captured_extent_.height * 4); 376 pixels.assign(capture_ptr_, capture_ptr_ + std::size_t(captured_extent_.width) * captured_extent_.height * 4);
364 if (extent) *extent = captured_extent_; 377 if (extent) *extent = captured_extent_;
@@ -394,6 +407,9 @@ public:
394 if (source_rect) pending.rect = *source_rect; 407 if (source_rect) pending.rect = *source_rect;
395 if (planes) pending.planes = *planes; 408 if (planes) pending.planes = *planes;
396 deferred_.push_back(pending); 409 deferred_.push_back(pending);
410 if (const std::uint64_t n = ++probe_deferred_; local_diagnostics() && (n <= 8 || n % 600 == 0))
411 std::fprintf(stderr, "[rt] present-probe: present #%llu queued behind held work (%zu queued)\n",
412 static_cast<unsigned long long>(n), deferred_.size());
397 last_tore_ = false; 413 last_tore_ = false;
398 context_.holds().after_held(this, [this] { run_deferred(); }); 414 context_.holds().after_held(this, [this] { run_deferred(); });
399 return VK_SUCCESS; 415 return VK_SUCCESS;
@@ -456,6 +472,7 @@ private:
456 VkResult submit_now(const ResourceBinding* binding, ResourceId source, bool vsync, const PresentRect* source_rect, 472 VkResult submit_now(const ResourceBinding* binding, ResourceId source, bool vsync, const PresentRect* source_rect,
457 bool srgb, bool tear = false, const PresentPlanes* planes = nullptr) { 473 bool srgb, bool tear = false, const PresentPlanes* planes = nullptr) {
458 last_tore_ = false; 474 last_tore_ = false;
475 probe_path(binding, source, planes); // LOCAL DIAGNOSTIC
459 if (!ok_) return VK_ERROR_INITIALIZATION_FAILED; 476 if (!ok_) return VK_ERROR_INITIALIZATION_FAILED;
460 if (surface_lost_) { // the window's display went away under a presented swapchain 477 if (surface_lost_) { // the window's display went away under a presented swapchain
461 // Try to make a new surface for the same window (the hwnd is retained by the factory's callback). 478 // Try to make a new surface for the same window (the hwnd is retained by the factory's callback).
@@ -479,7 +496,7 @@ private:
479 if (vsync != vsync_ || stale_ || srgb != swapchain_srgb_ || want_hdr != swapchain_hdr_req_) { 496 if (vsync != vsync_ || stale_ || srgb != swapchain_srgb_ || want_hdr != swapchain_hdr_req_) {
480 // The swapchain's colour encoding is only recorded once the new swapchain exists, so a failed 497 // The swapchain's colour encoding is only recorded once the new swapchain exists, so a failed
481 // recreate is tried again at the next present. 498 // recreate is tried again at the next present.
482 if (!recreate(vsync, srgb, want_hdr)) return VK_ERROR_OUT_OF_DATE_KHR; 499 if (!recreate_for_present(vsync, srgb, want_hdr)) return VK_ERROR_OUT_OF_DATE_KHR;
483 } 500 }
484 if (!swapchain_) { // minimised: try again next frame 501 if (!swapchain_) { // minimised: try again next frame
485 stale_ = true; 502 stale_ = true;
@@ -493,7 +510,9 @@ private:
493 auto& vk = context_.vk; 510 auto& vk = context_.vk;
494 const VkDevice device = context_.device(); 511 const VkDevice device = context_.device();
495 Frame& frame = frames_[frame_index_ % frames_.size()]; 512 Frame& frame = frames_[frame_index_ % frames_.size()];
496 if (const VkResult waited = vkWaitForFences_(device, 1, &frame.done, VK_TRUE, UINT64_MAX); waited != VK_SUCCESS) 513 if (const VkResult waited = context_.observe_result(
514 vkWaitForFences_(device, 1, &frame.done, VK_TRUE, UINT64_MAX), "vkWaitForFences (present)");
515 waited != VK_SUCCESS)
497 return stop(waited); 516 return stop(waited);
498 // Every submit copies into the same mapped buffer, even if its frame is outside the disk capture stride. 517 // Every submit copies into the same mapped buffer, even if its frame is outside the disk capture stride.
499 if (const VkResult r = finish_pending_capture(); r != VK_SUCCESS) return stop(r); 518 if (const VkResult r = finish_pending_capture(); r != VK_SUCCESS) return stop(r);
@@ -501,7 +520,7 @@ private:
501 std::uint32_t image = 0; 520 std::uint32_t image = 0;
502 VkResult acquired = acquire(frame.acquired, &image); 521 VkResult acquired = acquire(frame.acquired, &image);
503 if (acquired == VK_ERROR_OUT_OF_DATE_KHR) { 522 if (acquired == VK_ERROR_OUT_OF_DATE_KHR) {
504 if (!recreate(vsync, swapchain_srgb_, swapchain_hdr_req_)) return acquired; 523 if (!recreate_for_present(vsync, swapchain_srgb_, swapchain_hdr_req_)) return acquired;
505 if (!swapchain_) { // minimised since the last present: skipped, as above 524 if (!swapchain_) { // minimised since the last present: skipped, as above
506 captured_ = false; 525 captured_ = false;
507 return VK_SUCCESS; 526 return VK_SUCCESS;
@@ -572,7 +591,8 @@ private:
572 plane_rollbacks[i].layout); 591 plane_rollbacks[i].layout);
573 }; 592 };
574 if (!recorded) return give_back(frame, VK_ERROR_UNKNOWN); // released by another thread since presentable() 593 if (!recorded) return give_back(frame, VK_ERROR_UNKNOWN); // released by another thread since presentable()
575 if (const VkResult reset = vkResetFences_(device, 1, &frame.done); reset != VK_SUCCESS) { 594 if (const VkResult reset = context_.observe_result(vkResetFences_(device, 1, &frame.done),
595 "vkResetFences (present)"); reset != VK_SUCCESS) {
576 rollback(); 596 rollback();
577 return stop(reset); 597 return stop(reset);
578 } 598 }
@@ -604,15 +624,34 @@ private:
604 const bool tearing = false; 624 const bool tearing = false;
605 (void)tear; 625 (void)tear;
606#endif 626#endif
627 const bool inspect = splash_owner_ && capture_ptr_;
628 bool show_title = false;
629 if (inspect) {
630 submit_info.signalSemaphoreCount = 0; // signal ready only after choosing the image the window will show
631 if (!tracker_lock.owns_lock()) tracker_lock.lock();
632 }
607 VkResult submitted, result = VK_SUCCESS; 633 VkResult submitted, result = VK_SUCCESS;
608 { 634 {
609 std::lock_guard lock(context_.submit_mutex()); 635 std::lock_guard lock(context_.submit_mutex());
610 submitted = vk.vkQueueSubmit(queue_, 1, &submit_info, frame.done); 636 submitted = context_.observe_result(vk.vkQueueSubmit(queue_, 1, &submit_info, frame.done),
637 "vkQueueSubmit (present)");
638 if (submitted == VK_SUCCESS) context_.note_image_work_locked();
611 if (submitted != VK_SUCCESS) rollback(); 639 if (submitted != VK_SUCCESS) rollback();
612 // Commit/rollback happened before releasing tracker_mutex_ inside submit_mutex(), preserving submission 640 if (submitted == VK_SUCCESS && inspect) {
613 // order without holding tracker_mutex_ across vkQueuePresentKHR. 641 result = finish_startup_frame(frame, image, show_title);
642 if (result != VK_SUCCESS) return stop(result);
643 }
614 if (tracker_lock.owns_lock()) tracker_lock.unlock(); 644 if (tracker_lock.owns_lock()) tracker_lock.unlock();
615 if (submitted == VK_SUCCESS) result = vkQueuePresentKHR_(queue_, &present); 645 if (submitted == VK_SUCCESS)
646 result = context_.observe_result(vkQueuePresentKHR_(queue_, &present), "vkQueuePresentKHR");
647 }
648 if (show_title && (result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR)) {
649 splash_owner_.reset();
650 if (splash_capture_only_) {
651 splash_capture_only_ = false;
652 capture_ = false;
653 release_capture();
654 }
616 } 655 }
617 if (submitted != VK_SUCCESS) return give_back(frame, submitted); 656 if (submitted != VK_SUCCESS) return give_back(frame, submitted);
618 ++frame_index_; 657 ++frame_index_;
@@ -657,6 +696,310 @@ private:
657 } 696 }
658 697
659private: 698private:
699 // ---- LOCAL DIAGNOSTIC (not for upstream): which path each present takes, and the source texture's contents ----
700 bool probe_source_ = false;
701 std::uint64_t probe_calls_ = 0, probe_blit_ = 0, probe_compose_ = 0, probe_blank_ = 0, probe_unresolved_ = 0;
702 std::atomic<std::uint64_t> probe_deferred_{0};
703 int probe_written_ = 0;
704 VkCommandBuffer probe_commands_ = VK_NULL_HANDLE;
705 VkFence probe_fence_ = VK_NULL_HANDLE;
706
707 static float probe_half(std::uint16_t h) {
708 const std::uint32_t sign = (h >> 15) & 1, exponent = (h >> 10) & 0x1f, mantissa = h & 0x3ff;
709 float v;
710 if (exponent == 0) v = std::ldexp(float(mantissa), -24);
711 else if (exponent == 31) v = mantissa ? 0.0f : 65504.0f; // NaN reads as 0, inf as the largest half
712 else v = std::ldexp(float(mantissa | 0x400), int(exponent) - 25);
713 return sign ? -v : v;
714 }
715 static float probe_uf11(std::uint32_t bits, int mantissa_bits) { // B10G11R11 channels (5-bit exponent)
716 const std::uint32_t exponent = (bits >> mantissa_bits) & 0x1f, mantissa = bits & ((1u << mantissa_bits) - 1);
717 if (exponent == 0) return std::ldexp(float(mantissa), -14 - mantissa_bits);
718 if (exponent == 31) return 65504.0f;
719 return std::ldexp(float(mantissa | (1u << mantissa_bits)), int(exponent) - 15 - mantissa_bits);
720 }
721 // RGB in 0..1 (float formats unclamped) of one texel; false for a format this probe does not decode.
722 static bool probe_decode(VkFormat format, const std::uint8_t* t, float rgb[3]) {
723 switch (format) {
724 case VK_FORMAT_B8G8R8A8_UNORM: case VK_FORMAT_B8G8R8A8_SRGB:
725 rgb[0] = t[2] / 255.0f; rgb[1] = t[1] / 255.0f; rgb[2] = t[0] / 255.0f; return true;
726 case VK_FORMAT_R8G8B8A8_UNORM: case VK_FORMAT_R8G8B8A8_SRGB:
727 rgb[0] = t[0] / 255.0f; rgb[1] = t[1] / 255.0f; rgb[2] = t[2] / 255.0f; return true;
728 case VK_FORMAT_A2B10G10R10_UNORM_PACK32: case VK_FORMAT_A2R10G10B10_UNORM_PACK32: {
729 std::uint32_t w; std::memcpy(&w, t, 4);
730 const float lo = (w & 0x3ff) / 1023.0f, mid = ((w >> 10) & 0x3ff) / 1023.0f, hi = ((w >> 20) & 0x3ff) / 1023.0f;
731 const bool bgra = format == VK_FORMAT_A2R10G10B10_UNORM_PACK32;
732 rgb[0] = bgra ? hi : lo; rgb[1] = mid; rgb[2] = bgra ? lo : hi; return true;
733 }
734 case VK_FORMAT_R16G16B16A16_SFLOAT: {
735 std::uint16_t h[3]; std::memcpy(h, t, 6);
736 for (int i = 0; i < 3; ++i) rgb[i] = probe_half(h[i]);
737 return true;
738 }
739 case VK_FORMAT_R16G16B16A16_UNORM: {
740 std::uint16_t h[3]; std::memcpy(h, t, 6);
741 for (int i = 0; i < 3; ++i) rgb[i] = h[i] / 65535.0f;
742 return true;
743 }
744 case VK_FORMAT_B10G11R11_UFLOAT_PACK32: {
745 std::uint32_t w; std::memcpy(&w, t, 4);
746 rgb[0] = probe_uf11(w & 0x7ff, 6); rgb[1] = probe_uf11((w >> 11) & 0x7ff, 6); rgb[2] = probe_uf11(w >> 22, 5);
747 return true;
748 }
749 case VK_FORMAT_R32G32B32A32_SFLOAT:
750 std::memcpy(rgb, t, 12); return true;
751 default:
752 return false;
753 }
754 }
755
756 // Called at the top of submit_now(), so after any held work it was queued behind.
757 void probe_path(const ResourceBinding* binding, ResourceId source, const PresentPlanes* planes) {
758 const std::uint64_t n = ++probe_calls_;
759 const char* path = planes ? "present_planes(compose)" : binding ? "present(blit)" : "present_blank";
760 (planes ? probe_compose_ : binding ? probe_blit_ : probe_blank_)++;
761 const ResourceId id = planes ? planes->plane[0].source : binding ? source : ResourceId{};
762 ResourceBinding found{};
763 bool resolved = false;
764 if (id) {
765 std::shared_lock lock(context_.resource_mutex_);
766 if (const ResourceBinding* b = context_.resolve(id)) {
767 found = *b;
768 resolved = true;
769 }
770 }
771 if (id && !resolved) ++probe_unresolved_;
772 if (local_diagnostics() && (n <= 6 || n % 600 == 0))
773 std::fprintf(stderr,
774 "[rt] present-probe: submit #%llu path %s source 0x%llx resolved %d image %p format %d %ux%u "
775 "mips %u layers %u samples %u sampled %d (blit %llu compose %llu blank %llu unresolved %llu)\n",
776 static_cast<unsigned long long>(n), path, static_cast<unsigned long long>(id), int(resolved),
777 reinterpret_cast<void*>(found.image), int(found.format), found.width, found.height,
778 found.mip_levels, found.array_layers, found.samples, int(found.sampled),
779 static_cast<unsigned long long>(probe_blit_), static_cast<unsigned long long>(probe_compose_),
780 static_cast<unsigned long long>(probe_blank_), static_cast<unsigned long long>(probe_unresolved_));
781 // The same frames the swapchain capture takes: the one presented_ becomes when this present is shown.
782 if (probe_source_ && resolved && found.image && probe_written_ < capture_limit_ &&
783 presented_ % std::uint64_t(capture_every_) == 0)
784 {
785 probe_read_source(id, presented_ + 1, path);
786 // LOCAL DIAGNOSTIC (fsdraw): the render targets of the frame's fullscreen draws, read back with it.
787 for (const std::uint64_t target : fsdraw::targets())
788 if (target != id) probe_read_source(target, presented_ + 1, "fullscreen-draw target", "target");
789 }
790 }
791
792 // Copies mip 0, layer 0 of `id` to host memory on the presenter's queue (waited for), logs and writes it.
793 void probe_read_source(ResourceId id, std::uint64_t number, const char* path, const char* prefix = "source") {
794 const bool is_source = std::strcmp(prefix, "source") == 0;
795 auto& vk = context_.vk;
796 const VkDevice device = context_.device();
797 const ReplayFunctions& fn = context_.replay_;
798 if (!probe_commands_) {
799 VkCommandBufferAllocateInfo allocate{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO};
800 allocate.commandPool = pool_;
801 allocate.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
802 allocate.commandBufferCount = 1;
803 VkFenceCreateInfo fence{VK_STRUCTURE_TYPE_FENCE_CREATE_INFO};
804 if (vk.vkAllocateCommandBuffers(device, &allocate, &probe_commands_) != VK_SUCCESS ||
805 vkCreateFence_(device, &fence, nullptr, &probe_fence_) != VK_SUCCESS) {
806 std::fprintf(stderr, "[rt] present-probe: cannot make the readback command buffer\n");
807 probe_source_ = false;
808 return;
809 }
810 }
811 std::shared_lock resource_lock(context_.resource_mutex_);
812 const ResourceBinding* found = context_.resolve(id);
813 if (!found || !found->image) return;
814 const ResourceBinding binding = *found;
815 const BlockFormat bf = block_format(binding.format, VK_IMAGE_ASPECT_COLOR_BIT);
816 // Held only while the copy is recorded (fsdraw: holding them through the wait, the slow host reads and the
817 // file write stalled every resource creation and the boot ran out of memory).
818 std::unique_lock tracker_lock(context_.tracker_mutex_);
819 const bool tracked = context_.tracker_.tracked(id);
820 const VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
821 const VkImageLayout common = image_layout(binding, VK_IMAGE_LAYOUT_GENERAL);
822 LayoutPieces pieces = detail::current(&context_.tracker_, id, range, common);
823 const VkImageLayout layout = pieces.empty() ? VK_IMAGE_LAYOUT_UNDEFINED : pieces[0].layout;
824 std::fprintf(stderr,
825 "[rt] present-probe: %s frame %llu via %s: id 0x%llx format %d %ux%u mips %u layers %u samples %u "
826 "texel bytes %u tracked %d layout %d\n",
827 prefix, static_cast<unsigned long long>(number), path, static_cast<unsigned long long>(id),
828 int(binding.format), binding.width, binding.height, binding.mip_levels, binding.array_layers,
829 binding.samples, bf.bytes, int(tracked), int(layout));
830 if (layout == VK_IMAGE_LAYOUT_UNDEFINED) {
831 std::fprintf(stderr, "[rt] present-probe: %s frame %llu is UNDEFINED in the tracker: no tracked GPU "
832 "operation ever wrote it (the present zero-fills it)\n",
833 prefix, static_cast<unsigned long long>(number));
834 if (is_source) ++probe_written_;
835 return;
836 }
837 if (binding.samples > 1 || bf.block != 1 || !bf.bytes) {
838 std::fprintf(stderr, "[rt] present-probe: %s format %d not read back\n", prefix, int(binding.format));
839 return;
840 }
841 const VkDeviceSize size = VkDeviceSize(binding.width) * binding.height * bf.bytes;
842 VkBuffer buffer = VK_NULL_HANDLE;
843 VkDeviceMemory memory = VK_NULL_HANDLE;
844 void* mapped = nullptr;
845 VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
846 info.size = size;
847 info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT;
848 if (vk.vkCreateBuffer(device, &info, nullptr, &buffer) != VK_SUCCESS) return;
849 VkMemoryRequirements requirements{};
850 vk.vkGetBufferMemoryRequirements(device, buffer, &requirements);
851 VkPhysicalDeviceMemoryProperties props{};
852 vkGetPhysicalDeviceMemoryProperties_(physical_, &props);
853 constexpr VkMemoryPropertyFlags wanted = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
854 std::uint32_t type = UINT32_MAX;
855 // Host-cached system memory first (fsdraw): a resizable-BAR type is uncached for host reads.
856 for (int pass = 0; pass < 2 && type == UINT32_MAX; ++pass)
857 for (std::uint32_t i = 0; i < props.memoryTypeCount; ++i) {
858 const VkMemoryPropertyFlags f = props.memoryTypes[i].propertyFlags;
859 const bool cached = (f & VK_MEMORY_PROPERTY_HOST_CACHED_BIT) && !(f & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
860 if ((requirements.memoryTypeBits & (1u << i)) && (f & wanted) == wanted && (pass || cached)) {
861 type = i;
862 break;
863 }
864 }
865 VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
866 allocate.allocationSize = requirements.size;
867 allocate.memoryTypeIndex = type;
868 const auto cleanup = [&] {
869 if (memory) vk.vkFreeMemory(device, memory, nullptr);
870 if (buffer) vk.vkDestroyBuffer(device, buffer, nullptr);
871 };
872 if (type == UINT32_MAX || vk.vkAllocateMemory(device, &allocate, nullptr, &memory) != VK_SUCCESS ||
873 vk.vkBindBufferMemory(device, buffer, memory, 0) != VK_SUCCESS ||
874 vk.vkMapMemory(device, memory, 0, VK_WHOLE_SIZE, 0, &mapped) != VK_SUCCESS) {
875 cleanup();
876 return;
877 }
878 VkCommandBuffer commands = probe_commands_;
879 vk.vkResetCommandBuffer(commands, 0);
880 VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO};
881 begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
882 vk.vkBeginCommandBuffer(commands, &begin);
883 constexpr VkAccessFlags any = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
884 for (const auto& piece : pieces)
885 detail::image_barrier(fn, commands, binding, piece.range, piece.layout, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
886 any, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_TRANSFER_READ_BIT,
887 VK_PIPELINE_STAGE_TRANSFER_BIT);
888 VkBufferImageCopy copy{};
889 copy.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
890 copy.imageExtent = {binding.width, binding.height, 1};
891 fn.copy_image_to_buffer(commands, binding.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, buffer, 1, &copy);
892 for (const auto& piece : pieces)
893 detail::image_barrier(fn, commands, binding, piece.range, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, piece.layout,
894 VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, any,
895 VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
896 VkBufferMemoryBarrier to_host{VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER};
897 to_host.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
898 to_host.dstAccessMask = VK_ACCESS_HOST_READ_BIT;
899 to_host.srcQueueFamilyIndex = to_host.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
900 to_host.buffer = buffer;
901 to_host.size = VK_WHOLE_SIZE;
902 fn.pipeline_barrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, 0, nullptr, 1,
903 &to_host, 0, nullptr);
904 vk.vkEndCommandBuffer(commands);
905 tracker_lock.unlock();
906 resource_lock.unlock();
907 vkResetFences_(device, 1, &probe_fence_);
908 VkSubmitInfo submit_info{VK_STRUCTURE_TYPE_SUBMIT_INFO};
909 submit_info.commandBufferCount = 1;
910 submit_info.pCommandBuffers = &commands;
911 VkResult submitted;
912 {
913 std::lock_guard lock(context_.submit_mutex());
914 submitted = context_.observe_result(vk.vkQueueSubmit(queue_, 1, &submit_info, probe_fence_),
915 "vkQueueSubmit (present probe)");
916 if (submitted == VK_SUCCESS) context_.note_image_work_locked();
917 }
918 if (submitted != VK_SUCCESS ||
919 context_.observe_result(vkWaitForFences_(device, 1, &probe_fence_, VK_TRUE, 5'000'000'000ull),
920 "vkWaitForFences (present probe)") != VK_SUCCESS) {
921 std::fprintf(stderr, "[rt] present-probe: readback submit/wait failed (%d)\n", int(submitted));
922 cleanup();
923 return;
924 }
925 const std::size_t texels = std::size_t(binding.width) * binding.height;
926 const auto* bytes = static_cast<const std::uint8_t*>(mapped);
927 std::vector<std::uint8_t> rgb(texels * 3);
928 double sum[3] = {0, 0, 0};
929 float peak = 0.0f;
930 std::size_t nonzero = 0;
931 bool decoded = true;
932 for (std::size_t i = 0; i < texels && decoded; ++i) {
933 float c[3];
934 if (!probe_decode(binding.format, bytes + i * bf.bytes, c)) {
935 decoded = false;
936 break;
937 }
938 bool any_set = false;
939 for (int k = 0; k < 3; ++k) {
940 sum[k] += c[k];
941 peak = std::max(peak, c[k]);
942 if (c[k] != 0.0f) any_set = true;
943 rgb[i * 3 + k] = std::uint8_t(std::clamp(c[k], 0.0f, 1.0f) * 255.0f + 0.5f);
944 }
945 nonzero += any_set;
946 }
947 // Raw bytes too: a format the probe cannot decode still says whether anything was written.
948 std::size_t raw_nonzero = 0;
949 std::size_t first_nonzero = SIZE_MAX;
950 for (std::size_t i = 0; i < std::size_t(size); ++i)
951 if (bytes[i]) {
952 if (first_nonzero == SIZE_MAX) first_nonzero = i;
953 ++raw_nonzero;
954 }
955 { // LOCAL DIAGNOSTIC (fsdraw): raw texels at the centre and at the first non-zero byte
956 const std::size_t centre = (std::size_t(binding.height / 2) * binding.width + binding.width / 2) * bf.bytes;
957 std::string c, f;
958 char b[8];
959 for (std::uint32_t k = 0; k < bf.bytes && k < 16; ++k) {
960 std::snprintf(b, sizeof b, "%02x", bytes[centre + k]);
961 c += b;
962 }
963 if (first_nonzero != SIZE_MAX) {
964 const std::size_t t = first_nonzero / bf.bytes * bf.bytes;
965 for (std::uint32_t k = 0; k < bf.bytes && k < 16; ++k) {
966 std::snprintf(b, sizeof b, "%02x", bytes[t + k]);
967 f += b;
968 }
969 }
970 std::fprintf(stderr, "[rt] present-probe: %s frame %llu raw centre texel %s first non-zero texel %lld (%s)\n",
971 prefix, static_cast<unsigned long long>(number), c.c_str(),
972 first_nonzero == SIZE_MAX ? -1ll : static_cast<long long>(first_nonzero / bf.bytes), f.c_str());
973 }
974 cleanup();
975 const double scale = 255.0 / double(texels);
976 std::fprintf(stderr,
977 "[rt] present-probe: %s frame %llu mean rgb %.2f %.2f %.2f (0..255 scale) peak %.3f nonzero "
978 "texels %zu of %zu, nonzero bytes %zu of %llu%s\n",
979 prefix, static_cast<unsigned long long>(number), sum[0] * scale, sum[1] * scale, sum[2] * scale, peak,
980 nonzero, texels, raw_nonzero, static_cast<unsigned long long>(size),
981 decoded ? "" : " (format not decoded)");
982 std::string dir = capture_dir_;
983 if (dir.back() != '/' && dir.back() != '\\') dir += '/';
984 if (decoded && (is_source || nonzero)) {
985 char name[64];
986 std::snprintf(name, sizeof name, "%s_%05llu.ppm", prefix, static_cast<unsigned long long>(number));
987 std::ofstream file(dir + name, std::ios::binary | std::ios::trunc);
988 if (file) {
989 file << "P6\n" << binding.width << ' ' << binding.height << "\n255\n";
990 file.write(reinterpret_cast<const char*>(rgb.data()), std::streamsize(rgb.size()));
991 }
992 }
993 std::ofstream index(dir + "source_index.txt", std::ios::app);
994 if (index)
995 index << prefix << " frame " << number << " id 0x" << std::hex << id << std::dec << " path " << path << " format " << int(binding.format) << " extent "
996 << binding.width << 'x' << binding.height << " layout " << int(layout) << " mean rgb " << std::fixed
997 << std::setprecision(2) << sum[0] * scale << ' ' << sum[1] * scale << ' ' << sum[2] * scale
998 << " nonzero texels " << nonzero << " nonzero bytes " << raw_nonzero << '\n';
999 if (is_source) ++probe_written_;
1000 }
1001 // ---- end LOCAL DIAGNOSTIC ----
1002
660 struct Frame { 1003 struct Frame {
661 VkCommandBuffer commands = VK_NULL_HANDLE; 1004 VkCommandBuffer commands = VK_NULL_HANDLE;
662 VkFence done = VK_NULL_HANDLE; 1005 VkFence done = VK_NULL_HANDLE;
@@ -664,6 +1007,9 @@ private:
664 std::array<VkImageView, 2> views{}; // the plane views of the last composed present, until the frame is reused 1007 std::array<VkImageView, 2> views{}; // the plane views of the last composed present, until the frame is reused
665 }; 1008 };
666 1009
1010 bool recreate_for_present(bool vsync, bool srgb, bool hdr);
1011 VkResult finish_startup_frame(Frame& frame, std::uint32_t image, bool& show_title);
1012
667 // Whether `source` is a colour texture the device knows, so present() can refuse it before acquiring an image. 1013 // Whether `source` is a colour texture the device knows, so present() can refuse it before acquiring an image.
668 bool presentable(ResourceId source) { 1014 bool presentable(ResourceId source) {
669 std::shared_lock lock(context_.resource_mutex_); // the resource table (vulkan_backend.h) 1015 std::shared_lock lock(context_.resource_mutex_); // the resource table (vulkan_backend.h)
@@ -676,7 +1022,8 @@ private:
676 // present, which gives back the image that was never presented. Returns `failure`, the error to report. 1022 // present, which gives back the image that was never presented. Returns `failure`, the error to report.
677 VkResult give_back(Frame& frame, VkResult failure) { 1023 VkResult give_back(Frame& frame, VkResult failure) {
678 const VkDevice device = context_.device(); 1024 const VkDevice device = context_.device();
679 if (vkResetFences_(device, 1, &frame.done) != VK_SUCCESS) return stop(failure); 1025 if (context_.observe_result(vkResetFences_(device, 1, &frame.done), "vkResetFences (present)") != VK_SUCCESS)
1026 return stop(failure);
680 const VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; 1027 const VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
681 VkSubmitInfo submit_info{VK_STRUCTURE_TYPE_SUBMIT_INFO}; 1028 VkSubmitInfo submit_info{VK_STRUCTURE_TYPE_SUBMIT_INFO};
682 submit_info.waitSemaphoreCount = 1; 1029 submit_info.waitSemaphoreCount = 1;
@@ -685,7 +1032,8 @@ private:
685 VkResult submitted; 1032 VkResult submitted;
686 { 1033 {
687 std::lock_guard lock(context_.submit_mutex()); 1034 std::lock_guard lock(context_.submit_mutex());
688 submitted = context_.vk.vkQueueSubmit(queue_, 1, &submit_info, frame.done); 1035 submitted = context_.observe_result(context_.vk.vkQueueSubmit(queue_, 1, &submit_info, frame.done),
1036 "vkQueueSubmit (return present image)");
689 } 1037 }
690 if (submitted != VK_SUCCESS) return stop(failure); 1038 if (submitted != VK_SUCCESS) return stop(failure);
691 stale_ = true; 1039 stale_ = true;
@@ -716,7 +1064,8 @@ private:
716 const VkDevice device = context_.device(); 1064 const VkDevice device = context_.device();
717 { 1065 {
718 std::lock_guard lock(context_.submit_mutex()); 1066 std::lock_guard lock(context_.submit_mutex());
719 vk.vkQueueWaitIdle(queue_); // the old swapchain's images and semaphores may still be in use 1067 // The old swapchain's images and semaphores may still be in use.
1068 context_.observe_result(vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle (present)");
720 release(swapchain_); 1069 release(swapchain_);
721 } 1070 }
722 swapchain_ = VK_NULL_HANDLE; 1071 swapchain_ = VK_NULL_HANDLE;
@@ -805,7 +1154,8 @@ private:
805 return true; 1154 return true;
806 { 1155 {
807 std::lock_guard lock(context_.submit_mutex()); 1156 std::lock_guard lock(context_.submit_mutex());
808 context_.vk.vkQueueWaitIdle(queue_); // the old target may still be in use 1157 // The old target may still be in use.
1158 context_.observe_result(context_.vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle (present)");
809 } 1159 }
810 bool changed = false; 1160 bool changed = false;
811 return composer_->ensure_target(extent_, changed); 1161 return composer_->ensure_target(extent_, changed);
@@ -930,8 +1280,9 @@ private:
930 1280
931 VkResult acquire(VkSemaphore semaphore, std::uint32_t* image) { 1281 VkResult acquire(VkSemaphore semaphore, std::uint32_t* image) {
932 for (;;) { 1282 for (;;) {
933 const VkResult result = vkAcquireNextImageKHR_(context_.device(), swapchain_, 50'000'000, semaphore, 1283 const VkResult result = context_.observe_result(
934 VK_NULL_HANDLE, image); 1284 vkAcquireNextImageKHR_(context_.device(), swapchain_, 50'000'000, semaphore, VK_NULL_HANDLE, image),
1285 "vkAcquireNextImageKHR");
935 if (result != VK_TIMEOUT && result != VK_NOT_READY) return result; 1286 if (result != VK_TIMEOUT && result != VK_NOT_READY) return result;
936 if (should_abort()) return VK_NOT_READY; 1287 if (should_abort()) return VK_NOT_READY;
937 } 1288 }
@@ -1063,7 +1414,8 @@ private:
1063 1414
1064 VkResult finish_pending_capture() { 1415 VkResult finish_pending_capture() {
1065 if (!pending_capture_) return VK_SUCCESS; 1416 if (!pending_capture_) return VK_SUCCESS;
1066 const VkResult waited = vkWaitForFences_(context_.device(), 1, &pending_capture_, VK_TRUE, UINT64_MAX); 1417 const VkResult waited = context_.observe_result(
1418 vkWaitForFences_(context_.device(), 1, &pending_capture_, VK_TRUE, UINT64_MAX), "vkWaitForFences (capture)");
1067 pending_capture_ = VK_NULL_HANDLE; 1419 pending_capture_ = VK_NULL_HANDLE;
1068 if (waited == VK_SUCCESS) write_capture(); 1420 if (waited == VK_SUCCESS) write_capture();
1069 return waited; 1421 return waited;
@@ -1158,7 +1510,8 @@ private:
1158 const VkDevice device = context_.device(); 1510 const VkDevice device = context_.device();
1159 { 1511 {
1160 std::lock_guard lock(context_.submit_mutex()); 1512 std::lock_guard lock(context_.submit_mutex());
1161 vk.vkQueueWaitIdle(queue_); // the old swapchain's images and semaphores may still be in use 1513 // The old swapchain's images and semaphores may still be in use.
1514 context_.observe_result(vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle (present)");
1162 } 1515 }
1163 if (finish_pending_capture() != VK_SUCCESS) return false; 1516 if (finish_pending_capture() != VK_SUCCESS) return false;
1164 stale_ = true; // until this succeeds 1517 stale_ = true; // until this succeeds
@@ -1303,7 +1656,8 @@ private:
1303 swapchain_ = VK_NULL_HANDLE; 1656 swapchain_ = VK_NULL_HANDLE;
1304 info.oldSwapchain = old; 1657 info.oldSwapchain = old;
1305 VkSwapchainKHR fresh = VK_NULL_HANDLE; 1658 VkSwapchainKHR fresh = VK_NULL_HANDLE;
1306 const VkResult created = vkCreateSwapchainKHR_(device, &info, nullptr, &fresh); 1659 const VkResult created = context_.observe_result(vkCreateSwapchainKHR_(device, &info, nullptr, &fresh),
1660 "vkCreateSwapchainKHR");
1307 { 1661 {
1308 std::lock_guard lock(context_.submit_mutex()); 1662 std::lock_guard lock(context_.submit_mutex());
1309 release(old); // retired by the creation attempt, whether or not it succeeded 1663 release(old); // retired by the creation attempt, whether or not it succeeded
@@ -1456,6 +1810,10 @@ private:
1456 bool surface_lost_ = false; // set by mark_surface_lost(); cleared once a new surface was created 1810 bool surface_lost_ = false; // set by mark_surface_lost(); cleared once a new surface was created
1457 std::map<VkFormat, VkFormatFeatureFlags> features_; 1811 std::map<VkFormat, VkFormatFeatureFlags> features_;
1458 bool warned_srgb_ = false; 1812 bool warned_srgb_ = false;
1813 std::shared_ptr<void> splash_owner_;
1814 ResourceBinding splash_binding_{};
1815 ResourceId splash_source_{};
1816 bool splash_capture_only_ = false;
1459 bool capture_ = false; 1817 bool capture_ = false;
1460 present_dump::PresentDump dump_; 1818 present_dump::PresentDump dump_;
1461 bool dump_pq_ = false; 1819 bool dump_pq_ = false;
@@ -1497,3 +1855,5 @@ private:
1497}; 1855};
1498 1856
1499} // namespace leonida 1857} // namespace leonida
1858
1859#include "vulkan_present_splash.h"