upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime
diff options
context:
space:
mode:
Diffstat (limited to 'runtime')
-rw-r--r--runtime/src/vulkan_present.h164
-rw-r--r--runtime/test/d3d12_present_test.cpp57
2 files changed, 221 insertions, 0 deletions
diff --git a/runtime/src/vulkan_present.h b/runtime/src/vulkan_present.h
index 8644346c5..0a5344d67 100644
--- a/runtime/src/vulkan_present.h
+++ b/runtime/src/vulkan_present.h
@@ -40,12 +40,18 @@
40#include <cmath> 40#include <cmath>
41#include <cstdint> 41#include <cstdint>
42#include <cstdio> 42#include <cstdio>
43#include <cstdlib>
44#include <filesystem>
45#include <system_error>
43#include <cstring> 46#include <cstring>
47#include <fstream>
44#include <functional> 48#include <functional>
49#include <iomanip>
45#include <map> 50#include <map>
46#include <deque> 51#include <deque>
47#include <memory> 52#include <memory>
48#include <mutex> 53#include <mutex>
54#include <string>
49#include <thread> 55#include <thread>
50#include <vector> 56#include <vector>
51 57
@@ -164,7 +170,32 @@ public:
164 vk.vkCreateSemaphore(device, &semaphore, nullptr, &frame.acquired) != VK_SUCCESS) 170 vk.vkCreateSemaphore(device, &semaphore, nullptr, &frame.acquired) != VK_SUCCESS)
165 return; 171 return;
166 } 172 }
173 // LEONIDA_CAPTURE=<dir>: besides presenting, copy the swapchain image to host memory and write it out as a
174 // binary PPM, every LEONIDA_CAPTURE_EVERY presented frames (default 30), at most LEONIDA_CAPTURE_LIMIT of
175 // them (default 24). Off unless the variable is set; a capture that cannot be made shows nothing and is
176 // reported here instead of failing the presenter.
177 if (const char* dir = std::getenv("LEONIDA_CAPTURE"); dir && *dir) {
178 capture_dir_ = dir;
179 // Create the folder: a capture run names its own output folder and should not have to make it first.
180 std::error_code created;
181 std::filesystem::create_directories(capture_dir_, created);
182 capture_to_disk_ = true;
183 capture_ = true; // the swapchain needs TRANSFER_SRC, and every frame copies into a staging buffer
184 if (const char* every = std::getenv("LEONIDA_CAPTURE_EVERY")) capture_every_ = std::max(1, std::atoi(every));
185 if (const char* limit = std::getenv("LEONIDA_CAPTURE_LIMIT")) capture_limit_ = std::max(1, std::atoi(limit));
186 std::fprintf(stderr, "[rt] present: capture on: every %d presented frame(s), at most %d, into %s\n",
187 capture_every_, capture_limit_, capture_dir_.c_str());
188 }
167 ok_ = recreate(true, false); 189 ok_ = recreate(true, false);
190 if (!ok_ && capture_to_disk_) {
191 // The surface refused a TRANSFER_SRC swapchain, or the staging buffer could not be made: present
192 // without the capture rather than not at all.
193 std::fprintf(stderr, "[rt] present: capture is unavailable on this surface; presenting without it\n");
194 capture_to_disk_ = false;
195 capture_ = false;
196 capture_dir_.clear();
197 ok_ = recreate(true, false);
198 }
168 } 199 }
169 200
170 ~VulkanPresenter() { 201 ~VulkanPresenter() {
@@ -179,6 +210,8 @@ public:
179 release(swapchain_); 210 release(swapchain_);
180 } 211 }
181 swapchain_ = VK_NULL_HANDLE; 212 swapchain_ = VK_NULL_HANDLE;
213 // A capture still pending has its copy complete once the queue is idle: write it before the buffer goes.
214 for (Frame& frame : frames_) write_pending_capture(frame);
182 release_capture(); 215 release_capture();
183 composer_.reset(); 216 composer_.reset();
184 for (Frame& frame : frames_) { 217 for (Frame& frame : frames_) {
@@ -461,6 +494,8 @@ private:
461 Frame& frame = frames_[frame_index_ % frames_.size()]; 494 Frame& frame = frames_[frame_index_ % frames_.size()];
462 if (const VkResult waited = vkWaitForFences_(device, 1, &frame.done, VK_TRUE, UINT64_MAX); waited != VK_SUCCESS) 495 if (const VkResult waited = vkWaitForFences_(device, 1, &frame.done, VK_TRUE, UINT64_MAX); waited != VK_SUCCESS)
463 return stop(waited); 496 return stop(waited);
497 // That fence also covers the capture copy this slot made two presents ago: its pixels are now readable.
498 write_pending_capture(frame);
464 499
465 std::uint32_t image = 0; 500 std::uint32_t image = 0;
466 VkResult acquired = acquire(frame.acquired, &image); 501 VkResult acquired = acquire(frame.acquired, &image);
@@ -589,6 +624,21 @@ private:
589 last_tore_ = true; 624 last_tore_ = true;
590 ++tear_presents_; 625 ++tear_presents_;
591 } 626 }
627 // LEONIDA_CAPTURE: this frame's copy is in the staging buffer. Its fence, waited when the slot comes
628 // round again, says when the pixels are readable; write_pending_capture() then writes the file.
629 if (capture_to_disk_ && capture_ && capture_ptr_ && capture_written_ < capture_limit_ &&
630 (presented_ - 1) % std::uint64_t(capture_every_) == 0) {
631 // The buffer is shared by the two frames in flight: a capture still pending in the other slot
632 // (only with a stride of 1) is written now, after its fence, before this frame overwrites it.
633 Frame& other = frames_[frame_index_ % frames_.size()];
634 if (other.capture_serial &&
635 vkWaitForFences_(device, 1, &other.done, VK_TRUE, UINT64_MAX) == VK_SUCCESS)
636 write_pending_capture(other);
637 frame.capture_serial = ++capture_serial_;
638 frame.capture_number = presented_;
639 frame.capture_extent = extent_;
640 frame.capture_format = format_;
641 }
592 } 642 }
593 if (capture_ && capture_ptr_) { 643 if (capture_ && capture_ptr_) {
594 captured_ = true; 644 captured_ = true;
@@ -615,6 +665,11 @@ private:
615 VkFence done = VK_NULL_HANDLE; 665 VkFence done = VK_NULL_HANDLE;
616 VkSemaphore acquired = VK_NULL_HANDLE; 666 VkSemaphore acquired = VK_NULL_HANDLE;
617 std::array<VkImageView, 2> views{}; // the plane views of the last composed present, until the frame is reused 667 std::array<VkImageView, 2> views{}; // the plane views of the last composed present, until the frame is reused
668 // LEONIDA_CAPTURE: the capture serial this frame's copy wrote, once that fence has been waited (0: none).
669 std::uint64_t capture_serial = 0;
670 std::uint64_t capture_number = 0; // the present number the file is named after
671 VkExtent2D capture_extent{};
672 VkFormat capture_format = VK_FORMAT_UNDEFINED;
618 }; 673 };
619 674
620 // Whether `source` is a colour texture the device knows, so present() can refuse it before acquiring an image. 675 // Whether `source` is a colour texture the device knows, so present() can refuse it before acquiring an image.
@@ -997,6 +1052,108 @@ private:
997 captured_ = false; 1052 captured_ = false;
998 } 1053 }
999 1054
1055 // The name VkFormat has in the index; the few formats a capture can be written from, else its number.
1056 static const char* capture_format_name(VkFormat format) {
1057 switch (format) {
1058 case VK_FORMAT_B8G8R8A8_UNORM: return "VK_FORMAT_B8G8R8A8_UNORM";
1059 case VK_FORMAT_B8G8R8A8_SRGB: return "VK_FORMAT_B8G8R8A8_SRGB";
1060 case VK_FORMAT_R8G8B8A8_UNORM: return "VK_FORMAT_R8G8B8A8_UNORM";
1061 case VK_FORMAT_R8G8B8A8_SRGB: return "VK_FORMAT_R8G8B8A8_SRGB";
1062 case VK_FORMAT_A2B10G10R10_UNORM_PACK32: return "VK_FORMAT_A2B10G10R10_UNORM_PACK32";
1063 case VK_FORMAT_A2R10G10B10_UNORM_PACK32: return "VK_FORMAT_A2R10G10B10_UNORM_PACK32";
1064 default: return "unknown";
1065 }
1066 }
1067
1068 // Writes the captured frame in `frame` as <dir>/frame_NNNNN.ppm, once the fence covering its copy has been waited
1069 // and while the staging buffer is still mapped. The shared buffer holds the newest captured copy, so a frame
1070 // whose serial a later capture has overtaken is dropped (only with a stride below the frames in flight).
1071 void write_pending_capture(Frame& frame) {
1072 const std::uint64_t serial = frame.capture_serial;
1073 if (!serial) return;
1074 frame.capture_serial = 0;
1075 if (!capture_to_disk_ || !capture_ptr_ || serial != capture_serial_) return;
1076 if (capture_written_ >= std::uint64_t(capture_limit_) || capture_dir_.empty()) return;
1077 const VkExtent2D extent = frame.capture_extent;
1078 const VkFormat format = frame.capture_format;
1079 const std::uint64_t number = frame.capture_number;
1080 const std::size_t texels = std::size_t(extent.width) * extent.height;
1081 if (!texels) return;
1082 std::vector<std::uint8_t> rgb(texels * 3);
1083 std::uint64_t sum[3] = {0, 0, 0};
1084 const std::uint8_t* src = capture_ptr_;
1085 switch (format) {
1086 case VK_FORMAT_B8G8R8A8_UNORM:
1087 case VK_FORMAT_B8G8R8A8_SRGB:
1088 for (std::size_t i = 0; i < texels; ++i) {
1089 const std::uint8_t b = src[i * 4 + 0], g = src[i * 4 + 1], r = src[i * 4 + 2];
1090 rgb[i * 3 + 0] = r;
1091 rgb[i * 3 + 1] = g;
1092 rgb[i * 3 + 2] = b;
1093 sum[0] += r;
1094 sum[1] += g;
1095 sum[2] += b;
1096 }
1097 break;
1098 case VK_FORMAT_R8G8B8A8_UNORM:
1099 case VK_FORMAT_R8G8B8A8_SRGB:
1100 for (std::size_t i = 0; i < texels; ++i) {
1101 const std::uint8_t r = src[i * 4 + 0], g = src[i * 4 + 1], b = src[i * 4 + 2];
1102 rgb[i * 3 + 0] = r;
1103 rgb[i * 3 + 1] = g;
1104 rgb[i * 3 + 2] = b;
1105 sum[0] += r;
1106 sum[1] += g;
1107 sum[2] += b;
1108 }
1109 break;
1110 case VK_FORMAT_A2B10G10R10_UNORM_PACK32:
1111 case VK_FORMAT_A2R10G10B10_UNORM_PACK32: {
1112 const bool bgra = format == VK_FORMAT_A2R10G10B10_UNORM_PACK32; // B in the low bits
1113 for (std::size_t i = 0; i < texels; ++i) {
1114 std::uint32_t word = 0;
1115 std::memcpy(&word, src + i * 4, sizeof word);
1116 const std::uint32_t low = word & 0x3ffu, mid = (word >> 10) & 0x3ffu, high = (word >> 20) & 0x3ffu;
1117 const auto to8 = [](std::uint32_t v) { return std::uint8_t((v * 255u + 511u) / 1023u); };
1118 const std::uint8_t r = to8(bgra ? high : low), g = to8(mid), b = to8(bgra ? low : high);
1119 rgb[i * 3 + 0] = r;
1120 rgb[i * 3 + 1] = g;
1121 rgb[i * 3 + 2] = b;
1122 sum[0] += r;
1123 sum[1] += g;
1124 sum[2] += b;
1125 }
1126 break;
1127 }
1128 default: return; // not a format the capture can be written from (recreate() refused the others)
1129 }
1130 char name[64];
1131 std::snprintf(name, sizeof name, "frame_%05llu.ppm", static_cast<unsigned long long>(number));
1132 std::string path = capture_dir_;
1133 if (path.back() != '/' && path.back() != '\\') path += '/';
1134 path += name;
1135 std::ofstream file(path, std::ios::binary | std::ios::trunc);
1136 if (!file) {
1137 std::fprintf(stderr, "[rt] present: cannot write %s\n", path.c_str());
1138 return;
1139 }
1140 file << "P6\n" << extent.width << ' ' << extent.height << "\n255\n";
1141 file.write(reinterpret_cast<const char*>(rgb.data()), std::streamsize(rgb.size()));
1142 file.close();
1143 const double scale = 1.0 / double(texels);
1144 const double mean[3] = {sum[0] * scale, sum[1] * scale, sum[2] * scale};
1145 path.resize(path.size() - std::strlen(name));
1146 path += "index.txt";
1147 std::ofstream index(path, std::ios::app);
1148 if (index)
1149 index << "frame " << number << " format " << int(format) << " (" << capture_format_name(format)
1150 << ") extent " << extent.width << 'x' << extent.height << " mean rgb " << std::fixed
1151 << std::setprecision(2) << mean[0] << ' ' << mean[1] << ' ' << mean[2] << '\n';
1152 ++capture_written_;
1153 std::fprintf(stderr, "[rt] present: capture %s (%ux%u, mean rgb %.2f %.2f %.2f)\n", name, extent.width,
1154 extent.height, mean[0], mean[1], mean[2]);
1155 }
1156
1000 // (Re)creates the swapchain for the surface's current size. A zero-sized surface (minimised) leaves no 1157 // (Re)creates the swapchain for the surface's current size. A zero-sized surface (minimised) leaves no
1001 // swapchain and is retried on the next present. Keep the old swapchain until the surface queries succeed and 1158 // swapchain and is retried on the next present. Keep the old swapchain until the surface queries succeed and
1002 // the replacement can be attempted. An incomplete replacement stays stale so the next present tries again. 1159 // the replacement can be attempted. An incomplete replacement stays stale so the next present tries again.
@@ -1307,6 +1464,13 @@ private:
1307 bool captured_ = false; 1464 bool captured_ = false;
1308 VkExtent2D captured_extent_{}; 1465 VkExtent2D captured_extent_{};
1309 VkFormat captured_format_ = VK_FORMAT_UNDEFINED; 1466 VkFormat captured_format_ = VK_FORMAT_UNDEFINED;
1467 // LEONIDA_CAPTURE: write the copies the staging buffer makes to <capture_dir_> (see write_pending_capture()).
1468 bool capture_to_disk_ = false;
1469 std::string capture_dir_;
1470 int capture_every_ = 30; // presented frames between files
1471 int capture_limit_ = 24; // files at most
1472 std::uint64_t capture_serial_ = 0; // the copy counter, so a write knows the buffer still holds its frame
1473 std::uint64_t capture_written_ = 0;
1310 1474
1311 PFN_vkGetPhysicalDeviceSurfaceSupportKHR vkGetPhysicalDeviceSurfaceSupportKHR_ = nullptr; 1475 PFN_vkGetPhysicalDeviceSurfaceSupportKHR vkGetPhysicalDeviceSurfaceSupportKHR_ = nullptr;
1312 PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR vkGetPhysicalDeviceSurfaceCapabilitiesKHR_ = nullptr; 1476 PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR vkGetPhysicalDeviceSurfaceCapabilitiesKHR_ = nullptr;
diff --git a/runtime/test/d3d12_present_test.cpp b/runtime/test/d3d12_present_test.cpp
index d7aef95b5..df69d1e1d 100644
--- a/runtime/test/d3d12_present_test.cpp
+++ b/runtime/test/d3d12_present_test.cpp
@@ -19,9 +19,13 @@
19 19
20#include <dxgi1_6.h> 20#include <dxgi1_6.h>
21 21
22#include <cmath>
22#include <cstdint> 23#include <cstdint>
24#include <cstdio>
23#include <cstdlib> 25#include <cstdlib>
24#include <cstring> 26#include <cstring>
27#include <fstream>
28#include <string>
25#include <functional> 29#include <functional>
26#include <string_view> 30#include <string_view>
27#include <vector> 31#include <vector>
@@ -304,6 +308,22 @@ void install(PFN_vkGetInstanceProcAddr instance_proc, VkInstance instance, VkDev
304 308
305int main() { 309int main() {
306 vktest::Device d; 310 vktest::Device d;
311 // LEONIDA_CAPTURE writes every presented frame to disk. Turn it on here so the path is exercised with the rest of
312 // the presenter, and check its files against the colour this test clears to.
313 wchar_t capture_dir[MAX_PATH]{};
314 {
315 wchar_t temp[MAX_PATH]{};
316 if (GetTempPathW(MAX_PATH, temp))
317 swprintf_s(capture_dir, L"%sleonida_present_capture_%lu", temp, GetCurrentProcessId());
318 if (capture_dir[0]) {
319 CreateDirectoryW(capture_dir, nullptr);
320 // The presenter reads these with std::getenv, so they have to go into the CRT's environment too, which
321 // SetEnvironmentVariableW alone does not update.
322 _wputenv_s(L"LEONIDA_CAPTURE", capture_dir);
323 _wputenv_s(L"LEONIDA_CAPTURE_EVERY", L"1");
324 _wputenv_s(L"LEONIDA_CAPTURE_LIMIT", L"4");
325 }
326 }
307 const auto device_status = d.initialize(true); 327 const auto device_status = d.initialize(true);
308 if (device_status == vktest::DeviceStatus::unavailable) { 328 if (device_status == vktest::DeviceStatus::unavailable) {
309 std::fprintf(stderr, "SKIP: no usable Vulkan presentation device\n"); 329 std::fprintf(stderr, "SKIP: no usable Vulkan presentation device\n");
@@ -623,6 +643,43 @@ int main() {
623 std::printf("the window is not in front: on-screen colour check skipped\n"); 643 std::printf("the window is not in front: on-screen colour check skipped\n");
624 } 644 }
625 645
646 // The capture files must hold the colour the presented images hold: the frame written is the swapchain image
647 // as the presentation engine got it, so a capture that reads the wrong buffer shows up here.
648 if (capture_dir[0]) {
649 char narrow[MAX_PATH * 3]{};
650 WideCharToMultiByte(CP_ACP, 0, capture_dir, -1, narrow, static_cast<int>(sizeof narrow), nullptr, nullptr);
651 char path[MAX_PATH * 3 + 32]{};
652 int files = 0;
653 for (int i = 1; i <= 4; ++i) {
654 std::snprintf(path, sizeof path, "%s\\frame_%05d.ppm", narrow, i);
655 if (GetFileAttributesA(path) != INVALID_FILE_ATTRIBUTES) ++files;
656 DeleteFileA(path);
657 }
658 int lines = 0, matching = 0, black = 0;
659 std::ifstream index(std::string(narrow) + "\\index.txt");
660 for (std::string line; std::getline(index, line);) {
661 const auto at = line.find("mean rgb ");
662 double r = -1, g = -1, b = -1;
663 if (at == std::string::npos || std::sscanf(line.c_str() + at, "mean rgb %lf %lf %lf", &r, &g, &b) != 3)
664 continue;
665 ++lines;
666 if (std::fabs(r - 51) <= 3.0 && std::fabs(g - 153) <= 3.0 && std::fabs(b - 230) <= 3.0) ++matching;
667 if (r < 8 && g < 8 && b < 8) ++black;
668 }
669 // The test resizes and injects failures on purpose, so a frame caught mid-transition is a near miss rather
670 // than a bug; half the frames with the cleared colour is the signal, and a capture reading the wrong
671 // buffer shows up as black frames, which is a hard failure.
672 EXPECT(files >= 2);
673 EXPECT(lines >= 2);
674 EXPECT(matching * 2 >= lines);
675 EXPECT(black == 0);
676 std::printf("capture: %d file(s), %d line(s), %d with the cleared colour, %d black\n", files, lines,
677 matching, black);
678 index.close();
679 DeleteFileA((std::string(narrow) + "\\index.txt").c_str());
680 RemoveDirectoryA(narrow);
681 }
682
626 presenter.reset(); // before the device's queue and resources go 683 presenter.reset(); // before the device's queue and resources go
627 } 684 }
628 DestroyWindow(window); 685 DestroyWindow(window);