Project
Loading...
Searching...
No Matches
GPUDisplayBackendVulkan.cxx
Go to the documentation of this file.
1// Copyright 2019-2020 CERN and copyright holders of ALICE O2.
2// See https://alice-o2.web.cern.ch/copyright for details of the copyright holders.
3// All rights not expressly granted are reserved.
4//
5// This software is distributed under the terms of the GNU General Public
6// License v3 (GPL Version 3), copied verbatim in the file "COPYING".
7//
8// In applying this license CERN does not waive the privileges and immunities
9// granted to it by virtue of its status as an Intergovernmental Organization
10// or submit itself to any jurisdiction.
11
14
15#define VULKAN_HPP_DISPATCH_LOADER_DYNAMIC 1
16#include <vulkan/vulkan.hpp>
17VULKAN_HPP_DEFAULT_DISPATCH_LOADER_DYNAMIC_STORAGE
18#include "HandMadeMath.h"
19
20#include "GPUCommonDef.h"
22#include "GPUDisplay.h"
23#include "GPULogging.h"
24#include "GPUParam.h"
25
26#include <mutex>
27#include <iostream>
28
29using namespace o2::gpu;
30
31#define GPUCA_DISPLAY_SHADER_TYPE_VULKAN
32#include "GPUDisplayLoadShaders.h"
33
34// #define CHKERR(cmd) {cmd;}
35#define CHKERR(cmd) \
36 do { \
37 auto tmp_internal_retVal = cmd; \
38 if ((int32_t)tmp_internal_retVal < 0) { \
39 GPUError("VULKAN ERROR: %d: %s (%s: %d)", (int32_t)tmp_internal_retVal, "ERROR", __FILE__, __LINE__); \
40 throw std::runtime_error("Vulkan Failure"); \
41 } \
42 } while (false)
43
50
51// ---------------------------- VULKAN HELPERS ----------------------------
52
53static int32_t checkVulkanLayersSupported(const std::vector<const char*>& validationLayers)
54{
55 std::vector<vk::LayerProperties> availableLayers = vk::enumerateInstanceLayerProperties();
56 for (const char* layerName : validationLayers) {
57 bool layerFound = false;
58
59 for (const auto& layerProperties : availableLayers) {
60 if (strcmp(layerName, layerProperties.layerName) == 0) {
61 layerFound = true;
62 break;
63 }
64 }
65
66 if (!layerFound) {
67 return 1;
68 }
69 }
70 return 0;
71}
72
73static uint32_t findMemoryType(uint32_t typeFilter, vk::MemoryPropertyFlags properties, vk::PhysicalDevice physDev)
74{
75 vk::PhysicalDeviceMemoryProperties memProperties = physDev.getMemoryProperties();
76
77 for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++) {
78 if ((typeFilter & (1 << i)) && (memProperties.memoryTypes[i].propertyFlags & properties) == properties) {
79 return i;
80 }
81 }
82 if ((properties & vk::MemoryPropertyFlagBits::eDeviceLocal) && (properties & vk::MemoryPropertyFlagBits::eHostVisible)) { // No host-visible device memory (e.g. no ReBAR), fall back to host memory
83 return findMemoryType(typeFilter, properties & ~vk::MemoryPropertyFlags(vk::MemoryPropertyFlagBits::eDeviceLocal), physDev);
84 }
85
86 throw std::runtime_error("failed to find suitable memory type!");
87}
88
89static vk::SurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<vk::SurfaceFormatKHR>& availableFormats)
90{
91 for (const auto& availableFormat : availableFormats) {
92 if (availableFormat.format == vk::Format::eB8G8R8A8Unorm && availableFormat.colorSpace == vk::ColorSpaceKHR::eSrgbNonlinear) {
93 return availableFormat;
94 }
95 }
96 return availableFormats[0];
97}
98
100{
101 // Lowest latency first. VSync: no tearing, MAILBOX, then FIFO_LATEST_READY (shows the newest ready image at each vblank). No VSync: IMMEDIATE, else the same (often no IMMEDIATE on Wayland). FIFO is always supported.
104 return vk::PresentModeKHR::eFifo; // Refresh rate limit: one frame per refresh, queue depth limited by present wait
105 }
106 const bool vsync = mDisplay->cfgR().drawQualityVSync;
107 const auto& available = mSwapChainDetails.presentModes;
108 for (vk::PresentModeKHR mode : {vk::PresentModeKHR::eImmediate, vk::PresentModeKHR::eMailbox, vk::PresentModeKHR::eFifoLatestReady, vk::PresentModeKHR::eFifo}) {
109 if ((mode == vk::PresentModeKHR::eImmediate && vsync) || (mode == vk::PresentModeKHR::eFifoLatestReady && !mFifoLatestReadySupported) || std::find(available.begin(), available.end(), mode) == available.end()) {
110 continue;
111 }
112 if (mode != (vsync ? vk::PresentModeKHR::eMailbox : vk::PresentModeKHR::eImmediate) && !mPresentModeErrorShown) {
114 GPUError("VULKAN ERROR: Desired present mode %s not available, using %s", vsync ? "MAILBOX" : "IMMEDIATE", vk::to_string(mode).c_str());
115 }
116 return mode;
117 }
118 return vk::PresentModeKHR::eFifo; // Unreachable, FIFO is always supported
119}
120
121vk::Extent2D GPUDisplayBackendVulkan::chooseSwapExtent(const vk::SurfaceCapabilitiesKHR& capabilities)
122{
123 if (capabilities.currentExtent.width != std::numeric_limits<uint32_t>::max()) {
124 return capabilities.currentExtent;
125 } else {
128 vk::Extent2D actualExtent = {(uint32_t)width, (uint32_t)height};
129 actualExtent.width = std::clamp(actualExtent.width, capabilities.minImageExtent.width, capabilities.maxImageExtent.width);
130 actualExtent.height = std::clamp(actualExtent.height, capabilities.minImageExtent.height, capabilities.maxImageExtent.height);
131 return actualExtent;
132 }
133}
134
135static void cmdImageMemoryBarrier(vk::CommandBuffer cmdbuffer, vk::Image image, vk::PipelineStageFlags2 srcStageMask, vk::AccessFlags2 srcAccessMask, vk::PipelineStageFlags2 dstStageMask, vk::AccessFlags2 dstAccessMask, vk::ImageLayout oldLayout, vk::ImageLayout newLayout, vk::ImageAspectFlags aspect = vk::ImageAspectFlagBits::eColor)
136{
137 vk::ImageMemoryBarrier2 barrier{srcStageMask, srcAccessMask, dstStageMask, dstAccessMask, oldLayout, newLayout, VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED, image, {aspect, 0, 1, 0, 1}};
138 cmdbuffer.pipelineBarrier2(vk::DependencyInfo{{}, 0, nullptr, 0, nullptr, 1, &barrier});
139}
140
141static void cmdBeginRendering(vk::CommandBuffer cmdbuffer, uint32_t width, uint32_t height, const vk::RenderingAttachmentInfo& color, const vk::RenderingAttachmentInfo* depth = nullptr)
142{
143 cmdbuffer.beginRendering(vk::RenderingInfo{{}, vk::Rect2D{{0, 0}, {width, height}}, 1, 0, 1, &color, depth});
144 vk::Viewport viewport{0.f, 0.f, (float)width, (float)height, 0.f, 1.f};
145 vk::Rect2D scissor{{0, 0}, {width, height}};
146 cmdbuffer.setViewport(0, 1, &viewport);
147 cmdbuffer.setScissor(0, 1, &scissor);
148}
149
150static void cmdBeginRenderingLoad(vk::CommandBuffer cmdbuffer, vk::Image image, vk::ImageView view, uint32_t width, uint32_t height) // Render on top of the content of a color attachment written by a previous pass
151{
152 cmdImageMemoryBarrier(cmdbuffer, image, vk::PipelineStageFlagBits2::eColorAttachmentOutput, vk::AccessFlagBits2::eColorAttachmentWrite, vk::PipelineStageFlagBits2::eColorAttachmentOutput, vk::AccessFlagBits2::eColorAttachmentRead | vk::AccessFlagBits2::eColorAttachmentWrite, vk::ImageLayout::eColorAttachmentOptimal, vk::ImageLayout::eColorAttachmentOptimal);
153 cmdBeginRendering(cmdbuffer, width, height, vk::RenderingAttachmentInfo{view, vk::ImageLayout::eColorAttachmentOptimal}); // loadOp eLoad, storeOp eStore
154}
155
157{
158 mSwapChainDetails.capabilities = device.getSurfaceCapabilitiesKHR(mSurface);
159 mSwapChainDetails.formats = device.getSurfaceFormatsKHR(mSurface);
160 mSwapChainDetails.presentModes = device.getSurfacePresentModesKHR(mSurface);
161}
162
164{
165 vk::CommandBufferAllocateInfo allocInfo{};
166 allocInfo.level = vk::CommandBufferLevel::ePrimary;
167 allocInfo.commandPool = mCommandPool;
168 allocInfo.commandBufferCount = 1;
169 vk::CommandBuffer commandBuffer = mDevice.allocateCommandBuffers(allocInfo)[0];
170 vk::CommandBufferBeginInfo beginInfo{};
171 beginInfo.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit;
172 commandBuffer.begin(beginInfo);
173 return commandBuffer;
174}
175
176template <class... Args>
177uint64_t GPUDisplayBackendVulkan::queueSubmit(uint64_t* timelineSignalValue, Args&&... args)
178{
179 std::lock_guard<std::mutex> guard(mQueueMutex);
180 if (timelineSignalValue) {
181 *timelineSignalValue = ++mTimelineValue;
182 }
183 CHKERR(mGraphicsQueue.submit2(std::forward<Args>(args)...));
184 return mTimelineValue;
185}
186
188{
189 commandBuffer.end();
190 vk::CommandBufferSubmitInfo commandBufferInfo{commandBuffer};
191 vk::SemaphoreSubmitInfo signalInfo{mTimelineSemaphore, 0, vk::PipelineStageFlagBits2::eAllCommands};
192 vk::SubmitInfo2 submitInfo{{}, 0, nullptr, 1, &commandBufferInfo, 1, &signalInfo};
193 waitTimeline(queueSubmit(&signalInfo.value, 1, &submitInfo, VkFence(VK_NULL_HANDLE)));
194 mDevice.freeCommandBuffers(mCommandPool, 1, &commandBuffer);
195}
196
198{
199 if (value) {
200 vk::SemaphoreWaitInfo waitInfo{{}, 1, &mTimelineSemaphore, &value};
201 CHKERR(mDevice.waitSemaphores(&waitInfo, UINT64_MAX));
202 }
203}
204
205static vk::ImageView createImageViewI(vk::Device device, vk::Image image, vk::Format format, vk::ImageAspectFlags aspectFlags = vk::ImageAspectFlagBits::eColor, uint32_t mipLevels = 1)
206{
207 vk::ImageViewCreateInfo viewInfo{};
208 viewInfo.image = image;
209 viewInfo.viewType = vk::ImageViewType::e2D;
210 viewInfo.format = format;
211 viewInfo.subresourceRange.aspectMask = aspectFlags;
212 viewInfo.subresourceRange.baseMipLevel = 0;
213 viewInfo.subresourceRange.levelCount = mipLevels;
214 viewInfo.subresourceRange.baseArrayLayer = 0;
215 viewInfo.subresourceRange.layerCount = 1;
216 return device.createImageView(viewInfo, nullptr);
217}
218
219static void createImageI(vk::Device device, vk::PhysicalDevice physicalDevice, vk::Image& image, vk::DeviceMemory& imageMemory, uint32_t width, uint32_t height, vk::Format format, vk::ImageUsageFlags usage, vk::MemoryPropertyFlags properties, vk::ImageTiling tiling = vk::ImageTiling::eOptimal, vk::SampleCountFlagBits numSamples = vk::SampleCountFlagBits::e1, vk::ImageLayout layout = vk::ImageLayout::eUndefined, uint32_t mipLevels = 1)
220{
221 vk::ImageCreateInfo imageInfo{};
222 imageInfo.imageType = vk::ImageType::e2D;
223 imageInfo.extent.width = width;
224 imageInfo.extent.height = height;
225 imageInfo.extent.depth = 1;
226 imageInfo.mipLevels = mipLevels;
227 imageInfo.arrayLayers = 1;
228 imageInfo.format = format;
229 imageInfo.tiling = tiling;
230 imageInfo.initialLayout = layout;
231 imageInfo.usage = usage;
232 imageInfo.samples = numSamples;
233 imageInfo.sharingMode = vk::SharingMode::eExclusive;
234 image = device.createImage(imageInfo);
235
236 vk::MemoryRequirements memRequirements;
237 memRequirements = device.getImageMemoryRequirements(image);
238
239 vk::MemoryAllocateInfo allocInfo{};
240 allocInfo.allocationSize = memRequirements.size;
241 allocInfo.memoryTypeIndex = findMemoryType(memRequirements.memoryTypeBits, properties, physicalDevice);
242 imageMemory = device.allocateMemory(allocInfo, nullptr);
243
244 device.bindImageMemory(image, imageMemory, 0);
245}
246
247static uint32_t getMaxUsableSampleCount(vk::PhysicalDeviceProperties& physicalDeviceProperties)
248{
249 vk::SampleCountFlags counts = physicalDeviceProperties.limits.framebufferColorSampleCounts & physicalDeviceProperties.limits.framebufferDepthSampleCounts;
250 if (counts & vk::SampleCountFlagBits::e64) {
251 return 64;
252 } else if (counts & vk::SampleCountFlagBits::e32) {
253 return 32;
254 } else if (counts & vk::SampleCountFlagBits::e16) {
255 return 16;
256 } else if (counts & vk::SampleCountFlagBits::e8) {
257 return 8;
258 } else if (counts & vk::SampleCountFlagBits::e4) {
259 return 4;
260 } else if (counts & vk::SampleCountFlagBits::e2) {
261 return 2;
262 }
263 return 1;
264}
265
266static vk::SampleCountFlagBits getMSAASamplesFlag(uint32_t msaa)
267{
268 if (msaa == 2) {
269 return vk::SampleCountFlagBits::e2;
270 } else if (msaa == 4) {
271 return vk::SampleCountFlagBits::e4;
272 } else if (msaa == 8) {
273 return vk::SampleCountFlagBits::e8;
274 } else if (msaa == 16) {
275 return vk::SampleCountFlagBits::e16;
276 } else if (msaa == 32) {
277 return vk::SampleCountFlagBits::e32;
278 } else if (msaa == 64) {
279 return vk::SampleCountFlagBits::e64;
280 }
281 return vk::SampleCountFlagBits::e1;
282}
283
284template <class T, class S>
285static inline void clearVector(T& v, S func, bool downsize = true)
286{
287 std::for_each(v.begin(), v.end(), func);
288 if (downsize) {
289 v.clear();
290 }
291}
292
293// ---------------------------- VULKAN DEVICE MANAGEMENT ----------------------------
294
295template <class T> // Feature structs: sType, pNext, then only VkBool32 members (possibly followed by padding)
296static bool hasFeatures(const T& available, const T& required)
297{
298 const vk::Bool32* a = reinterpret_cast<const vk::Bool32*>(reinterpret_cast<const char*>(&available) + sizeof(VkBaseOutStructure));
299 const vk::Bool32* r = reinterpret_cast<const vk::Bool32*>(reinterpret_cast<const char*>(&required) + sizeof(VkBaseOutStructure));
300 for (size_t i = 0; i < (sizeof(T) - sizeof(VkBaseOutStructure)) / sizeof(vk::Bool32); i++) {
301 if (r[i] && !a[i]) {
302 return false;
303 }
304 }
305 return true;
306}
307
308template <class... T>
309static bool hasFeatures(const vk::StructureChain<T...>& available, const vk::StructureChain<T...>& required)
310{
311 return (hasFeatures(available.template get<T>(), required.template get<T>()) && ...);
312}
313
314template <class... T>
315static void clearFeatures(vk::StructureChain<T...>& chain) // Zero all feature flags including padding, which the member-wise comparison in hasFeatures reads
316{
317 ((memset(reinterpret_cast<char*>(&chain.template get<T>()) + sizeof(VkBaseOutStructure), 0, sizeof(T) - sizeof(VkBaseOutStructure))), ...);
318}
319
320template <class T> // Enable the first available of the extensions (aliases) if the device supports the feature, chaining the feature struct in front of chain
321static bool enableOptionalFeature(vk::PhysicalDevice device, const std::vector<vk::ExtensionProperties>& available, std::initializer_list<const char*> extensions, vk::Bool32 T::* feature, T& featureStruct, std::vector<const char*>& enabledExtensions, void*& chain)
322{
323 for (const char* ext : extensions) {
324 if (std::none_of(available.begin(), available.end(), [ext](const auto& e) { return strcmp(ext, e.extensionName) == 0; })) {
325 continue;
326 }
327 if (!(device.getFeatures2<vk::PhysicalDeviceFeatures2, T>().template get<T>().*feature)) {
328 return false;
329 }
330 enabledExtensions.emplace_back(ext);
331 featureStruct.*feature = VK_TRUE;
332 featureStruct.pNext = chain;
333 chain = &featureStruct;
334 return true;
335 }
336 return false;
337}
338
339template <class... T>
340static vk::StructureChain<T...> getFeatures(vk::PhysicalDevice device, const vk::StructureChain<T...>&)
341{
342 return device.getFeatures2<T...>();
343}
344
345double GPUDisplayBackendVulkan::checkDevice(vk::PhysicalDevice device, const std::vector<const char*>& reqDeviceExtensions, const FeatureChain& reqDeviceFeatures, bool silent)
346{
347 double score = -1.;
348 vk::PhysicalDeviceProperties deviceProperties = device.getProperties();
349 vk::PhysicalDeviceMemoryProperties memoryProperties = device.getMemoryProperties();
350 if (deviceProperties.apiVersion < VK_API_VERSION_1_4) {
351 if (!silent) {
352 GPUInfo("%s ignored, supports only Vulkan %u.%u", &deviceProperties.deviceName[0], VK_API_VERSION_MAJOR(deviceProperties.apiVersion), VK_API_VERSION_MINOR(deviceProperties.apiVersion));
353 }
354 return (-1);
355 }
356
357 std::vector<vk::ExtensionProperties> availableExtensions = device.enumerateDeviceExtensionProperties(nullptr);
358 uint32_t extensionsFound = 0;
359 for (uint32_t i = 0; i < reqDeviceExtensions.size(); i++) {
360 for (uint32_t j = 0; j < availableExtensions.size(); j++) {
361 if (strcmp(reqDeviceExtensions[i], availableExtensions[j].extensionName) == 0) {
362 extensionsFound++;
363 break;
364 }
365 }
366 }
367 if (extensionsFound < reqDeviceExtensions.size()) {
368 if (!silent) {
369 GPUInfo("%s ignored due to missing extensions", &deviceProperties.deviceName[0]);
370 }
371 return (-1);
372 }
373
374 if (!hasFeatures(getFeatures(device, reqDeviceFeatures), reqDeviceFeatures)) { // Query only after the version and extension checks, the chain contains 1.4 and extension structs
375 if (!silent) {
376 GPUInfo("%s ignored due to missing features", &deviceProperties.deviceName[0]);
377 }
378 return (-1);
379 }
380
381 std::vector<vk::QueueFamilyProperties> queueFamilies = device.getQueueFamilyProperties();
382 bool found = false;
383 for (uint32_t i = 0; i < queueFamilies.size(); i++) {
384 if (!(queueFamilies[i].queueFlags & vk::QueueFlagBits::eGraphics)) {
385 continue;
386 }
387 vk::Bool32 presentSupport = device.getSurfaceSupportKHR(i, mSurface);
388 if (!presentSupport) {
389 continue;
390 }
392 found = true;
393 break;
394 }
395 if (!found) {
396 if (!silent) {
397 GPUInfo("%s ignored due to missing queue properties", &deviceProperties.deviceName[0]);
398 }
399 return (-1);
400 }
401
404 if (!silent) {
405 GPUInfo("%s ignored due to incompatible swap chain", &deviceProperties.deviceName[0]);
406 }
407 return (-1);
408 }
409
410 score = 1;
411 if (deviceProperties.deviceType == vk::PhysicalDeviceType::eDiscreteGpu) {
412 score += 1e12;
413 } else if (deviceProperties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu) {
414 score += 1e11;
415 }
416
417 for (uint32_t i = 0; i < memoryProperties.memoryHeapCount; i++) {
418 if (memoryProperties.memoryHeaps[i].flags & vk::MemoryHeapFlagBits::eDeviceLocal) {
419 score += memoryProperties.memoryHeaps[i].size;
420 }
421 }
422
423 return score;
424}
425
427{
428 VULKAN_HPP_DEFAULT_DISPATCHER.init(vkGetInstanceProcAddr);
429 vk::ApplicationInfo appInfo{};
430 appInfo.pApplicationName = "GPU CA Standalone display";
431 appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
432 appInfo.pEngineName = "GPU CI Standalone Engine";
433 appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
434 appInfo.apiVersion = VK_API_VERSION_1_4;
435
436 vk::InstanceCreateInfo instanceCreateInfo;
437 instanceCreateInfo.pApplicationInfo = &appInfo;
438
439 const char** frontendExtensions;
440 uint32_t frontendExtensionCount = mDisplay->frontend()->getReqVulkanExtensions(frontendExtensions);
441 std::vector<const char*> reqInstanceExtensions(frontendExtensions, frontendExtensions + frontendExtensionCount);
442 reqInstanceExtensions.insert(reqInstanceExtensions.end(), {VK_EXT_DEBUG_UTILS_EXTENSION_NAME, VK_KHR_GET_SURFACE_CAPABILITIES_2_EXTENSION_NAME, VK_KHR_SURFACE_MAINTENANCE_1_EXTENSION_NAME}); // The latter two are required by VK_KHR_swapchain_maintenance1
443 std::vector<vk::ExtensionProperties> availableInstanceExtensions = vk::enumerateInstanceExtensionProperties(nullptr);
444 if (mDisplay->GetProcessingSettings().debugLevel >= 3) {
445 std::cout << "available instance extensions: " << availableInstanceExtensions.size() << "\n";
446 for (const auto& extension : availableInstanceExtensions) {
447 std::cout << '\t' << extension.extensionName << '\n';
448 }
449 }
450 for (const char* ext : reqInstanceExtensions) {
451 if (std::none_of(availableInstanceExtensions.begin(), availableInstanceExtensions.end(), [ext](const auto& e) { return strcmp(ext, e.extensionName) == 0; })) {
452 throw std::runtime_error(std::string("Required Vulkan instance extension not available: ") + ext);
453 }
454 }
455
456 const std::vector<const char*> reqValidationLayers = {"VK_LAYER_KHRONOS_validation"};
457 auto debugCallback = [](vk::DebugUtilsMessageSeverityFlagBitsEXT messageSeverity, vk::DebugUtilsMessageTypeFlagsEXT messageType, const vk::DebugUtilsMessengerCallbackDataEXT* pCallbackData, void* pUserData) -> VkBool32 {
458 static int32_t throwOnError = getenv("GPUCA_VULKAN_VALIDATION_THROW") ? atoi(getenv("GPUCA_VULKAN_VALIDATION_THROW")) : 0;
459 static bool showVulkanValidationInfo = getenv("GPUCA_VULKAN_VALIDATION_INFO") && atoi(getenv("GPUCA_VULKAN_VALIDATION_INFO"));
460 switch (messageSeverity) {
461 case vk::DebugUtilsMessageSeverityFlagBitsEXT::eVerbose:
462 if (showVulkanValidationInfo) {
463 GPUInfo("%s", pCallbackData->pMessage);
464 }
465 break;
466 case vk::DebugUtilsMessageSeverityFlagBitsEXT::eWarning:
467 GPUWarning("%s", pCallbackData->pMessage);
468 if (throwOnError > 1) {
469 throw std::logic_error("break_on_validation_warning");
470 }
471 break;
472 case vk::DebugUtilsMessageSeverityFlagBitsEXT::eError:
473 GPUError("%s", pCallbackData->pMessage);
474 if (throwOnError) {
475 throw std::logic_error("break_on_validation_error");
476 }
477 break;
478 case vk::DebugUtilsMessageSeverityFlagBitsEXT::eInfo:
479 default:
480 GPUInfo("%s", pCallbackData->pMessage);
481 break;
482 }
483 return false;
484 };
485 vk::DebugUtilsMessengerCreateInfoEXT debugCreateInfo{};
487 if (checkVulkanLayersSupported(reqValidationLayers)) {
488 throw std::runtime_error("Requested validation layer support not available");
489 }
490 instanceCreateInfo.enabledLayerCount = static_cast<uint32_t>(reqValidationLayers.size());
491 instanceCreateInfo.ppEnabledLayerNames = reqValidationLayers.data();
492 instanceCreateInfo.pNext = (VkDebugUtilsMessengerCreateInfoEXT*)&debugCreateInfo;
493
494 debugCreateInfo.messageSeverity = vk::DebugUtilsMessageSeverityFlagBitsEXT::eVerbose | vk::DebugUtilsMessageSeverityFlagBitsEXT::eWarning | vk::DebugUtilsMessageSeverityFlagBitsEXT::eError;
495 debugCreateInfo.messageType = vk::DebugUtilsMessageTypeFlagBitsEXT::eGeneral | vk::DebugUtilsMessageTypeFlagBitsEXT::eValidation | vk::DebugUtilsMessageTypeFlagBitsEXT::ePerformance;
496 debugCreateInfo.pfnUserCallback = debugCallback;
497 debugCreateInfo.pUserData = nullptr;
498 } else {
499 instanceCreateInfo.enabledLayerCount = 0;
500 }
501
502 instanceCreateInfo.enabledExtensionCount = static_cast<uint32_t>(reqInstanceExtensions.size());
503 instanceCreateInfo.ppEnabledExtensionNames = reqInstanceExtensions.data();
504
505 mInstance = vk::createInstance(instanceCreateInfo, nullptr);
506 VULKAN_HPP_DEFAULT_DISPATCHER.init(mInstance);
507
509 GPUInfo("Enabling Vulkan Validation Layers");
510 mDebugMessenger = mInstance.createDebugUtilsMessengerEXT(debugCreateInfo, nullptr);
511 }
512
514 throw std::runtime_error("Frontend does not provide Vulkan surface");
515 }
516
517 const std::vector<const char*> reqDeviceExtensions = {VK_KHR_SWAPCHAIN_EXTENSION_NAME, VK_KHR_SWAPCHAIN_MAINTENANCE_1_EXTENSION_NAME, VK_KHR_PRESENT_ID_EXTENSION_NAME, VK_KHR_PRESENT_WAIT_EXTENSION_NAME};
518 FeatureChain reqDeviceFeatures; // Exactly these features are required and enabled
519 clearFeatures(reqDeviceFeatures);
520 auto& reqFeatures10 = reqDeviceFeatures.get<vk::PhysicalDeviceFeatures2>().features;
521 reqFeatures10.geometryShader = reqFeatures10.wideLines = reqFeatures10.largePoints = reqFeatures10.multiDrawIndirect = VK_TRUE;
522 reqDeviceFeatures.get<vk::PhysicalDeviceVulkan12Features>().timelineSemaphore = VK_TRUE;
523 reqDeviceFeatures.get<vk::PhysicalDeviceVulkan14Features>().pushDescriptor = reqDeviceFeatures.get<vk::PhysicalDeviceVulkan14Features>().maintenance5 = VK_TRUE;
524 reqDeviceFeatures.get<vk::PhysicalDeviceVulkan13Features>().dynamicRendering = reqDeviceFeatures.get<vk::PhysicalDeviceVulkan13Features>().synchronization2 = VK_TRUE;
525 reqDeviceFeatures.get<vk::PhysicalDeviceVulkan13Features>().shaderDemoteToHelperInvocation = VK_TRUE; // discard in SPIR-V 1.6
526 reqDeviceFeatures.get<vk::PhysicalDeviceSwapchainMaintenance1FeaturesKHR>().swapchainMaintenance1 = VK_TRUE;
527 reqDeviceFeatures.get<vk::PhysicalDevicePresentIdFeaturesKHR>().presentId = VK_TRUE;
528 reqDeviceFeatures.get<vk::PhysicalDevicePresentWaitFeaturesKHR>().presentWait = VK_TRUE;
529
530 mPhysicalDevice = VkPhysicalDevice(VK_NULL_HANDLE);
531 std::vector<vk::PhysicalDevice> devices = mInstance.enumeratePhysicalDevices();
532 if (devices.size() == 0) {
533 throw std::runtime_error("No Vulkan device present!");
534 }
535 double bestScore = -1.;
536 for (uint32_t i = 0; i < devices.size(); i++) {
537 double score = checkDevice(devices[i], reqDeviceExtensions, reqDeviceFeatures);
538 if (mDisplay->GetProcessingSettings().debugLevel >= 2) {
539 vk::PhysicalDeviceProperties deviceProperties = devices[i].getProperties();
540 GPUInfo("Available Vulkan device %d: %s - Score %f", i, &deviceProperties.deviceName[0], score);
541 }
542 if (score > bestScore && score > 0) {
543 mPhysicalDevice = devices[i];
544 bestScore = score;
545 }
546 }
547 if (mDisplay->cfg().vulkan.forceDevice != -1) {
548 if (mDisplay->cfg().vulkan.forceDevice < 0 || mDisplay->cfg().vulkan.forceDevice >= (int32_t)devices.size()) {
549 throw std::runtime_error("Invalid Vulkan device selected");
550 }
551 mPhysicalDevice = devices[mDisplay->cfg().vulkan.forceDevice];
552 }
553 if (!mPhysicalDevice) {
554 throw std::runtime_error("All available Vulkan devices unsuited");
555 }
556 if (checkDevice(mPhysicalDevice, reqDeviceExtensions, reqDeviceFeatures, true) <= 0) {
557 throw std::runtime_error("Selected vulkan device is incompatible");
558 }
559 std::vector<const char*> deviceExtensions = reqDeviceExtensions;
560 void* featureChain = &reqDeviceFeatures.get<vk::PhysicalDeviceFeatures2>();
561 const std::vector<vk::ExtensionProperties> availableDeviceExtensions = mPhysicalDevice.enumerateDeviceExtensionProperties(nullptr);
562 vk::PhysicalDevicePresentModeFifoLatestReadyFeaturesKHR fifoLatestReadyFeatures{};
563 mFifoLatestReadySupported = enableOptionalFeature(mPhysicalDevice, availableDeviceExtensions, {VK_KHR_PRESENT_MODE_FIFO_LATEST_READY_EXTENSION_NAME, VK_EXT_PRESENT_MODE_FIFO_LATEST_READY_EXTENSION_NAME}, &vk::PhysicalDevicePresentModeFifoLatestReadyFeaturesKHR::presentModeFifoLatestReady, fifoLatestReadyFeatures, deviceExtensions, featureChain);
564
566 vk::PhysicalDeviceProperties deviceProperties = mPhysicalDevice.getProperties();
567 vk::FormatProperties depth32FormatProperties = mPhysicalDevice.getFormatProperties(vk::Format::eD32Sfloat);
568 vk::FormatProperties depth64FormatProperties = mPhysicalDevice.getFormatProperties(vk::Format::eD32SfloatS8Uint);
569 GPUInfo("Using physical Vulkan device %s", &deviceProperties.deviceName[0]);
570 mMaxMSAAsupported = getMaxUsableSampleCount(deviceProperties);
571 mStrictLines = deviceProperties.limits.strictLines;
572 mMaxLineWidth = deviceProperties.limits.lineWidthRange[1];
573 mMaxPointSize = deviceProperties.limits.pointSizeRange[1];
574 mMaxRenderSize = std::min({deviceProperties.limits.maxImageDimension2D, deviceProperties.limits.maxFramebufferWidth, deviceProperties.limits.maxFramebufferHeight});
575 mZSupported = (bool)(depth32FormatProperties.optimalTilingFeatures & vk::FormatFeatureFlagBits::eDepthStencilAttachment);
576 mStencilSupported = (bool)(depth64FormatProperties.optimalTilingFeatures & vk::FormatFeatureFlagBits::eDepthStencilAttachment);
577 bool mailboxSupported = std::find(mSwapChainDetails.presentModes.begin(), mSwapChainDetails.presentModes.end(), vk::PresentModeKHR::eMailbox) != mSwapChainDetails.presentModes.end();
578 if (mDisplay->GetProcessingSettings().debugLevel >= 2) {
579 GPUInfo("Max MSAA: %d, 32 bit Z buffer %d, 32 bit Z buffer + stencil buffer %d, Mailbox present mode %d, FIFO latest ready present mode %d\n", (int32_t)mMaxMSAAsupported, (int32_t)mZSupported, (int32_t)mStencilSupported, (int32_t)mailboxSupported, (int32_t)mFifoLatestReadySupported);
580 }
581
582 vk::DeviceQueueCreateInfo queueCreateInfo{};
583 queueCreateInfo.queueFamilyIndex = mGraphicsFamily;
584 queueCreateInfo.queueCount = 1;
585 float queuePriority = 1.0f;
586 queueCreateInfo.pQueuePriorities = &queuePriority;
587 vk::DeviceCreateInfo deviceCreateInfo{};
588 deviceCreateInfo.pQueueCreateInfos = &queueCreateInfo;
589 deviceCreateInfo.queueCreateInfoCount = 1;
590 deviceCreateInfo.pNext = featureChain;
591 deviceCreateInfo.pEnabledFeatures = nullptr;
592 deviceCreateInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size());
593 deviceCreateInfo.ppEnabledExtensionNames = deviceExtensions.data();
594 mDevice = mPhysicalDevice.createDevice(deviceCreateInfo, nullptr);
595 VULKAN_HPP_DEFAULT_DISPATCHER.init(mDevice);
597
598 vk::CommandPoolCreateInfo poolInfo{};
599 poolInfo.flags = vk::CommandPoolCreateFlagBits::eResetCommandBuffer;
600 poolInfo.queueFamilyIndex = mGraphicsFamily;
601 mCommandPool = mDevice.createCommandPool(poolInfo, nullptr);
602 mPipelineCache = mDevice.createPipelineCache(vk::PipelineCacheCreateInfo{}, nullptr);
603}
604
606{
607 mDevice.destroyCommandPool(mCommandPool, nullptr);
608 mDevice.destroyPipelineCache(mPipelineCache, nullptr);
609 mDevice.destroy(nullptr);
610 mInstance.destroySurfaceKHR(mSurface, nullptr);
612 mInstance.destroyDebugUtilsMessengerEXT(mDebugMessenger, nullptr);
613 }
614}
615
616// ---------------------------- VULKAN COMMAND BUFFERS ----------------------------
617
619{
620 vk::CommandBufferAllocateInfo allocInfo{};
621 allocInfo.commandPool = mCommandPool;
622 allocInfo.level = vk::CommandBufferLevel::ePrimary;
623 allocInfo.commandBufferCount = mImageCount;
624 mCommandBufferUpToDate.assign(mImageCount, false);
625 mCommandBuffers = mDevice.allocateCommandBuffers(allocInfo);
626 mCommandBuffersText = mDevice.allocateCommandBuffers(allocInfo);
627 mCommandBuffersTexture = mDevice.allocateCommandBuffers(allocInfo);
628 mCommandBuffersDownsample = mDevice.allocateCommandBuffers(allocInfo);
629 mCommandBuffersMix = mDevice.allocateCommandBuffers(allocInfo);
630 mCommandBuffersPresent = mDevice.allocateCommandBuffers(allocInfo);
631}
632
634{
635 mDevice.freeCommandBuffers(mCommandPool, mCommandBuffers.size(), mCommandBuffers.data());
636 mDevice.freeCommandBuffers(mCommandPool, mCommandBuffersText.size(), mCommandBuffersText.data());
637 mDevice.freeCommandBuffers(mCommandPool, mCommandBuffersTexture.size(), mCommandBuffersTexture.data());
639 mDevice.freeCommandBuffers(mCommandPool, mCommandBuffersMix.size(), mCommandBuffersMix.data());
640 mDevice.freeCommandBuffers(mCommandPool, mCommandBuffersPresent.size(), mCommandBuffersPresent.data());
641}
642
643// ---------------------------- VULKAN SEMAPHORES AND FENCES ----------------------------
644
646{
647 vk::SemaphoreCreateInfo semaphoreInfo{};
649 for (uint32_t i = 0; i < mFramesInFlight; i++) {
650 mImageAvailableSemaphore[i] = mDevice.createSemaphore(semaphoreInfo, nullptr);
651 }
652 vk::SemaphoreTypeCreateInfo timelineTypeInfo{vk::SemaphoreType::eTimeline, 0};
653 semaphoreInfo.pNext = &timelineTypeInfo;
654 mTimelineSemaphore = mDevice.createSemaphore(semaphoreInfo, nullptr);
655 mTimelineValue = 0;
657}
658
660{
662 for (uint32_t i = 0; i < mImageCount; i++) {
663 mPresentSemaphore[i] = mDevice.createSemaphore(vk::SemaphoreCreateInfo{}, nullptr);
664 }
666 for (uint32_t i = 0; i < mImageCount; i++) {
667 mPresentFences.emplace_back(mDevice.createFence(vk::FenceCreateInfo{vk::FenceCreateFlagBits::eSignaled}, nullptr));
668 }
669}
670
672{
673 if (mPresentFences.size()) { // Timeout in case a failed present did not signal its fence
674 vk::Result retVal = mDevice.waitForFences(mPresentFences.size(), mPresentFences.data(), true, 1'000'000'000);
675 if (retVal != vk::Result::eTimeout) {
676 CHKERR(retVal);
677 }
678 }
679}
680
682{
683 clearVector(mImageAvailableSemaphore, [&](auto& x) { mDevice.destroySemaphore(x, nullptr); });
684 mDevice.destroySemaphore(mTimelineSemaphore, nullptr);
685}
686
688{
689 clearVector(mPresentSemaphore, [&](auto& x) { mDevice.destroySemaphore(x, nullptr); });
690 clearVector(mPresentFences, [&](auto& x) { mDevice.destroyFence(x, nullptr); });
691}
692
693// ---------------------------- VULKAN UNIFORM LAYOUTS AND BUFFERS ----------------------------
694
696{
697 vk::DescriptorSetLayoutBinding uboLayoutBindingMat{};
698 uboLayoutBindingMat.binding = 0;
699 uboLayoutBindingMat.descriptorType = vk::DescriptorType::eUniformBuffer;
700 uboLayoutBindingMat.descriptorCount = 1;
701 uboLayoutBindingMat.stageFlags = vk::ShaderStageFlagBits::eVertex;
702 vk::DescriptorSetLayoutBinding samplerLayoutBinding{};
703 samplerLayoutBinding.binding = 2;
704 samplerLayoutBinding.descriptorCount = 1;
705 samplerLayoutBinding.descriptorType = vk::DescriptorType::eCombinedImageSampler;
706 samplerLayoutBinding.stageFlags = vk::ShaderStageFlagBits::eFragment;
707 vk::DescriptorSetLayoutBinding bindings[2] = {uboLayoutBindingMat, samplerLayoutBinding};
708
709 vk::DescriptorSetLayoutCreateInfo layoutInfo{};
710 layoutInfo.flags = vk::DescriptorSetLayoutCreateFlagBits::ePushDescriptor;
711 layoutInfo.bindingCount = 1;
712 layoutInfo.pBindings = bindings;
713 mUniformDescriptor = mDevice.createDescriptorSetLayout(layoutInfo, nullptr);
714 layoutInfo.bindingCount = 2;
715 mUniformDescriptorTexture = mDevice.createDescriptorSetLayout(layoutInfo, nullptr);
716}
717
719{
720 for (int32_t j = 0; j < 3; j++) {
722 for (uint32_t i = 0; i < mImageCount; i++) {
723 mUniformBuffersMat[j][i] = createBuffer(sizeof(hmm_mat4), nullptr, vk::BufferUsageFlagBits::eUniformBuffer, mDisplay->cfg().vulkan.uniformBuffersInDeviceMemory ? 2 : 0);
724 }
725 }
727}
728
730{
731 mDevice.destroyDescriptorSetLayout(mUniformDescriptor, nullptr);
732 mDevice.destroyDescriptorSetLayout(mUniformDescriptorTexture, nullptr);
733}
734
736{
737 for (int32_t j = 0; j < 3; j++) {
738 clearVector(mUniformBuffersMat[j], [&](auto& x) { clearBuffer(x); });
739 }
740}
741
742void GPUDisplayBackendVulkan::cmdPushDescriptors(vk::CommandBuffer commandBuffer, vk::PipelineLayout layout, const VulkanBuffer& ubo, vk::ImageView textureView)
743{
744 vk::DescriptorBufferInfo bufferInfo{ubo.buffer, 0, ubo.size};
745 vk::DescriptorImageInfo imageInfo{mTextureSampler, textureView, vk::ImageLayout::eShaderReadOnlyOptimal};
746 const vk::WriteDescriptorSet writes[2] = {{{}, 0, 0, 1, vk::DescriptorType::eUniformBuffer, nullptr, &bufferInfo}, {{}, 2, 0, 1, vk::DescriptorType::eCombinedImageSampler, &imageInfo}};
747 commandBuffer.pushDescriptorSet(vk::PipelineBindPoint::eGraphics, layout, 0, textureView ? 2 : 1, writes);
748}
749
750// ---------------------------- VULKAN TEXTURE SAMPLER ----------------------------
751
753{
754 vk::SamplerCreateInfo samplerInfo{};
755 samplerInfo.magFilter = vk::Filter::eLinear;
756 samplerInfo.minFilter = vk::Filter::eLinear;
757 samplerInfo.addressModeU = vk::SamplerAddressMode::eRepeat;
758 samplerInfo.addressModeV = vk::SamplerAddressMode::eRepeat;
759 samplerInfo.addressModeW = vk::SamplerAddressMode::eRepeat;
760 samplerInfo.compareEnable = false;
761 samplerInfo.compareOp = vk::CompareOp::eAlways;
762 samplerInfo.borderColor = vk::BorderColor::eIntOpaqueBlack;
763 samplerInfo.unnormalizedCoordinates = false;
764 samplerInfo.mipmapMode = vk::SamplerMipmapMode::eLinear;
765 samplerInfo.mipLodBias = 0.0f;
766 samplerInfo.minLod = 0.0f;
767 samplerInfo.maxLod = 0.0f;
768 mTextureSampler = mDevice.createSampler(samplerInfo, nullptr);
769}
770
772{
773 mDevice.destroySampler(mTextureSampler, nullptr);
774}
775
776// ---------------------------- VULKAN SWAPCHAIN MANAGEMENT ----------------------------
777
778void GPUDisplayBackendVulkan::createSwapChain(vk::SwapchainKHR oldSwapChain)
779{
781 mSurfaceFormat = chooseSwapSurfaceFormat(mSwapChainDetails.formats);
783 if (mDisplay->GetProcessingSettings().debugLevel >= 2) {
784 GPUInfo("Vulkan present mode %s (VSync %d)", vk::to_string(mPresentMode).c_str(), (int32_t)mDisplay->cfgR().drawQualityVSync);
785 }
786 vk::Extent2D extent = chooseSwapExtent(mSwapChainDetails.capabilities);
787
788 uint32_t imageCount = std::max<uint32_t>(mSwapChainDetails.capabilities.minImageCount + 1, mDisplay->cfg().vulkan.nFramesInFlight + 1);
789 if (mSwapChainDetails.capabilities.maxImageCount > 0 && imageCount > mSwapChainDetails.capabilities.maxImageCount) {
790 imageCount = mSwapChainDetails.capabilities.maxImageCount;
791 }
792
793 mScreenWidth = extent.width;
794 mScreenHeight = extent.height;
795
796 vk::SwapchainCreateInfoKHR swapCreateInfo{};
797 swapCreateInfo.surface = mSurface;
798 swapCreateInfo.minImageCount = imageCount;
799 swapCreateInfo.imageFormat = mSurfaceFormat.format;
800 swapCreateInfo.imageColorSpace = mSurfaceFormat.colorSpace;
801 swapCreateInfo.imageExtent = extent;
802 swapCreateInfo.imageArrayLayers = 1;
803 swapCreateInfo.imageUsage = vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eTransferSrc | vk::ImageUsageFlagBits::eTransferDst; // Transfer for screenshots / FSAA downsampling, so that they need no swapchain recreation
804 swapCreateInfo.imageSharingMode = vk::SharingMode::eExclusive;
805 swapCreateInfo.queueFamilyIndexCount = 0; // Optional
806 swapCreateInfo.pQueueFamilyIndices = nullptr; // Optional
807 swapCreateInfo.preTransform = mSwapChainDetails.capabilities.currentTransform;
808 swapCreateInfo.compositeAlpha = vk::CompositeAlphaFlagBitsKHR::eOpaque;
809 swapCreateInfo.presentMode = mPresentMode;
810 swapCreateInfo.clipped = true;
811 swapCreateInfo.oldSwapchain = oldSwapChain;
812 vk::SwapchainPresentScalingCreateInfoKHR scalingInfo{};
813 { // Let the compositor scale the last image while resizing, until the new swapchain is presented
814 const vk::SurfacePresentModeKHR surfacePresentMode{mPresentMode};
815 const auto caps = mPhysicalDevice.getSurfaceCapabilities2KHR<vk::SurfaceCapabilities2KHR, vk::SurfacePresentScalingCapabilitiesKHR>(vk::PhysicalDeviceSurfaceInfo2KHR{mSurface, &surfacePresentMode}).get<vk::SurfacePresentScalingCapabilitiesKHR>();
816 auto gravity = [](vk::PresentGravityFlagsKHR f) { return (f & vk::PresentGravityFlagBitsKHR::eCentered) ? vk::PresentGravityFlagBitsKHR::eCentered : ((f & vk::PresentGravityFlagBitsKHR::eMin) ? vk::PresentGravityFlagBitsKHR::eMin : vk::PresentGravityFlagsKHR(f & vk::PresentGravityFlagBitsKHR::eMax)); };
817 scalingInfo.scalingBehavior = (caps.supportedPresentScaling & vk::PresentScalingFlagBitsKHR::eAspectRatioStretch) ? vk::PresentScalingFlagBitsKHR::eAspectRatioStretch : vk::PresentScalingFlagsKHR(caps.supportedPresentScaling & vk::PresentScalingFlagBitsKHR::eStretch);
818 scalingInfo.presentGravityX = gravity(caps.supportedPresentGravityX);
819 scalingInfo.presentGravityY = gravity(caps.supportedPresentGravityY);
820 if (scalingInfo.scalingBehavior && scalingInfo.presentGravityX && scalingInfo.presentGravityY) {
821 swapCreateInfo.pNext = &scalingInfo;
822 }
823 }
824 mSwapChain = mDevice.createSwapchainKHR(swapCreateInfo, nullptr);
825 mLastPresentId = 0; // Present IDs are per swapchain
826 if (oldSwapChain) {
827 waitPresentFences(); // Presentation engine done with the old swapchain
828 mDevice.destroySwapchainKHR(oldSwapChain, nullptr);
829 }
830
831 mSwapChainImages = mDevice.getSwapchainImagesKHR(mSwapChain);
832 uint32_t oldImageCount = mImageCount;
834 if (mImageCount > sizeof(mUpdateUBOdrawMatrix) * 8) {
835 throw std::runtime_error("Too many swapchain images");
836 }
837
838 if (mImageCount != oldImageCount || !mCommandInfrastructureCreated) {
843 } else {
846 }
851 }
852
854 for (uint32_t i = 0; i < mImageCount; i++) {
855 mSwapChainImageViews[i] = createImageViewI(mDevice, mSwapChainImages[i], mSurfaceFormat.format);
856 mCommandBuffersPresent[i].reset({});
857 mCommandBuffersPresent[i].begin(vk::CommandBufferBeginInfo{});
858 cmdImageMemoryBarrier(mCommandBuffersPresent[i], mSwapChainImages[i], vk::PipelineStageFlagBits2::eColorAttachmentOutput, vk::AccessFlagBits2::eColorAttachmentWrite, vk::PipelineStageFlagBits2::eNone, vk::AccessFlagBits2::eNone, vk::ImageLayout::eColorAttachmentOptimal, vk::ImageLayout::ePresentSrcKHR);
860 }
861}
862
864{
865 clearVector(mSwapChainImageViews, [&](auto& x) { mDevice.destroyImageView(x, nullptr); });
866 if (!keepSwapChain) {
868 mDevice.destroySwapchainKHR(mSwapChain, nullptr);
869 }
870}
871
872void GPUDisplayBackendVulkan::recreateRendering(bool forScreenshot, bool forMixing)
873{
875 const bool needUpdateSwapChain = mMustUpdateSwapChain;
876 const bool needUpdateOffscreenBuffers = needUpdateSwapChain || mDownsampleFactor != getDownsampleFactor(forScreenshot) || mMSAASampleCount != getMSAASamplesFlag(std::min<uint32_t>(mMaxMSAAsupported, mDisplay->cfgR().drawQualityMSAA)) || mZActive != (mZSupported && mDisplay->cfgL().depthBuffer) || mMixingSupported != forMixing;
877 if (!needUpdateOffscreenBuffers) {
878 return;
879 }
880 mDevice.waitIdle();
881 const vk::Format oldFormat = mSurfaceFormat.format;
882 const vk::SampleCountFlagBits oldMSAASampleCount = mMSAASampleCount;
883 const bool oldZActive = mZActive;
885 if (needUpdateSwapChain) {
886 clearSwapChain(true);
888 }
889 createOffscreenBuffers(forScreenshot, forMixing);
890 mUpdateUBOtextMatrix = mUpdateUBOmixMatrix = -1; // Screen / render size may have changed
891 if (mSurfaceFormat.format != oldFormat || mMSAASampleCount != oldMSAASampleCount || mZActive != oldZActive) { // Viewport / scissor are dynamic
894 }
895}
896
897// ---------------------------- VULKAN OFFSCREEN BUFFERS ----------------------------
898
899void GPUDisplayBackendVulkan::createOffscreenBuffers(bool forScreenshot, bool forMixing)
900{
901 mMSAASampleCount = getMSAASamplesFlag(std::min<uint32_t>(mMaxMSAAsupported, mDisplay->cfgR().drawQualityMSAA));
902 mZActive = mZSupported && mDisplay->cfgL().depthBuffer;
903 mMixingSupported = forMixing;
904 mDownsampleFactor = getDownsampleFactor(forScreenshot);
908
909 const uint32_t imageCountWithMixImages = mImageCount * (mMixingSupported ? 2 : 1);
910 mRenderTargetView.resize(imageCountWithMixImages);
911 mRenderTargetImage.resize(imageCountWithMixImages);
912 if (mDownsampleFSAA) {
913 mDownsampleImages.resize(imageCountWithMixImages);
914 }
915 if (mMSAASampleCount != vk::SampleCountFlagBits::e1) {
916 mMSAAImages.resize(imageCountWithMixImages);
917 }
918 if (mZActive) {
919 mZImages.resize(imageCountWithMixImages);
920 }
922 mMixImages.resize(mImageCount);
923 }
924
925 for (uint32_t i = 0; i < imageCountWithMixImages; i++) {
926 if (i < mImageCount) { // Main render chain
927 // primary buffer mSwapChainImageViews[i] created as part of createSwapChain, not here
928 } else if (!mDownsampleFSAA) { // for rendering to mixBuffer
929 createImageI(mDevice, mPhysicalDevice, mMixImages[i - mImageCount].image, mMixImages[i - mImageCount].memory, mRenderWidth, mRenderHeight, mSurfaceFormat.format, vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eSampled, vk::MemoryPropertyFlagBits::eDeviceLocal, vk::ImageTiling::eOptimal);
930 mMixImages[i - mImageCount].view = createImageViewI(mDevice, mMixImages[i - mImageCount].image, mSurfaceFormat.format, vk::ImageAspectFlagBits::eColor, 1);
931 }
932 if (mDownsampleFSAA) {
933 vk::ImageUsageFlags usage = vk::ImageUsageFlagBits::eColorAttachment;
934 if (i >= mImageCount || mDownsampleFactor != 2) {
935 usage |= vk::ImageUsageFlagBits::eSampled; // Mixing, shader downsampling
936 }
937 if (i < mImageCount && (mDownsampleFactor == 2 || forScreenshot)) {
938 usage |= vk::ImageUsageFlagBits::eTransferSrc; // Blit downsampling, scaled screenshots (blit or copy for screenshot factor <= 2)
939 }
940 createImageI(mDevice, mPhysicalDevice, mDownsampleImages[i].image, mDownsampleImages[i].memory, mRenderWidth, mRenderHeight, mSurfaceFormat.format, usage, vk::MemoryPropertyFlagBits::eDeviceLocal, vk::ImageTiling::eOptimal);
941 mDownsampleImages[i].view = createImageViewI(mDevice, mDownsampleImages[i].image, mSurfaceFormat.format, vk::ImageAspectFlagBits::eColor, 1);
944 } else {
947 }
948 if (mMSAASampleCount != vk::SampleCountFlagBits::e1) {
949 createImageI(mDevice, mPhysicalDevice, mMSAAImages[i].image, mMSAAImages[i].memory, mRenderWidth, mRenderHeight, mSurfaceFormat.format, vk::ImageUsageFlagBits::eColorAttachment, vk::MemoryPropertyFlagBits::eDeviceLocal, vk::ImageTiling::eOptimal, mMSAASampleCount);
950 mMSAAImages[i].view = createImageViewI(mDevice, mMSAAImages[i].image, mSurfaceFormat.format, vk::ImageAspectFlagBits::eColor, 1);
951 }
952 if (mZActive) {
953 createImageI(mDevice, mPhysicalDevice, mZImages[i].image, mZImages[i].memory, mRenderWidth, mRenderHeight, vk::Format::eD32Sfloat, vk::ImageUsageFlagBits::eDepthStencilAttachment, vk::MemoryPropertyFlagBits::eDeviceLocal, vk::ImageTiling::eOptimal, mMSAASampleCount);
954 mZImages[i].view = createImageViewI(mDevice, mZImages[i].image, vk::Format::eD32Sfloat, vk::ImageAspectFlagBits::eDepth, 1);
955 }
956 }
957
958 if (mMixingSupported) {
959 float vertices[6][4] = {
960 {0, (float)mRenderHeight, 0.0f, 1.0f},
961 {0, 0, 0.0f, 0.0f},
962 {(float)mRenderWidth, 0, 1.0f, 0.0f},
963 {0, (float)mRenderHeight, 0.0f, 1.0f},
964 {(float)mRenderWidth, 0, 1.0f, 0.0f},
965 {(float)mRenderWidth, (float)mRenderHeight, 1.0f, 1.0f}};
966 mMixingTextureVertexArray = createBuffer(sizeof(vertices), &vertices[0][0], vk::BufferUsageFlagBits::eVertexBuffer, 1);
967 }
968
970}
971
973{
974 clearVector(mMSAAImages, [&](auto& x) { clearImage(x); });
975 clearVector(mDownsampleImages, [&](auto& x) { clearImage(x); });
976 clearVector(mZImages, [&](auto& x) { clearImage(x); });
977 clearVector(mMixImages, [&](auto& x) { clearImage(x); });
978 clearVector(mFontVertexBuffer, [&](auto& x) { if (x.size) { clearBuffer(x); } });
979 if (mMixingSupported) {
981 }
982}
983
984// ---------------------------- VULKAN PIPELINE ----------------------------
985
987{
988 vk::PipelineShaderStageCreateInfo shaderStages[2] = {vk::PipelineShaderStageCreateInfo{}, vk::PipelineShaderStageCreateInfo{}};
989 vk::PipelineShaderStageCreateInfo& vertShaderStageInfo = shaderStages[0];
990 vertShaderStageInfo.stage = vk::ShaderStageFlagBits::eVertex;
991 // vertShaderStageInfo.pNext // below: SPIR-V
992 vertShaderStageInfo.pName = "main";
993 vk::PipelineShaderStageCreateInfo& fragShaderStageInfo = shaderStages[1];
994 fragShaderStageInfo.stage = vk::ShaderStageFlagBits::eFragment;
995 // fragShaderStageInfo.pNext // below: SPIR-V
996 fragShaderStageInfo.pName = "main";
997
998 vk::VertexInputBindingDescription bindingDescription{};
999 bindingDescription.binding = 0;
1000 // bindingDescription.stride // below
1001 bindingDescription.inputRate = vk::VertexInputRate::eVertex;
1002
1003 vk::VertexInputAttributeDescription attributeDescriptions{};
1004 attributeDescriptions.binding = 0;
1005 attributeDescriptions.location = 0;
1006 // attributeDescriptions.format // below
1007 attributeDescriptions.offset = 0;
1008
1009 vk::PipelineVertexInputStateCreateInfo vertexInputInfo{};
1010 vertexInputInfo.vertexBindingDescriptionCount = 1;
1011 vertexInputInfo.pVertexBindingDescriptions = &bindingDescription;
1012 vertexInputInfo.vertexAttributeDescriptionCount = 1;
1013 vertexInputInfo.pVertexAttributeDescriptions = &attributeDescriptions;
1014 vk::PipelineInputAssemblyStateCreateInfo inputAssembly{};
1015 // inputAssembly.topology // below
1016 inputAssembly.primitiveRestartEnable = false;
1017
1018 vk::PipelineViewportStateCreateInfo viewportState{}; // Viewport and scissor are dynamic
1019 viewportState.viewportCount = 1;
1020 viewportState.scissorCount = 1;
1021
1022 vk::PipelineRasterizationStateCreateInfo rasterizer{};
1023 rasterizer.depthClampEnable = false;
1024 rasterizer.rasterizerDiscardEnable = false;
1025 rasterizer.polygonMode = vk::PolygonMode::eFill;
1026 rasterizer.lineWidth = mDisplay->cfgL().lineWidth;
1027 rasterizer.cullMode = vk::CullModeFlagBits::eBack;
1028 rasterizer.frontFace = vk::FrontFace::eClockwise;
1029 rasterizer.depthBiasEnable = false;
1030 rasterizer.depthBiasConstantFactor = 0.0f; // Optional
1031 rasterizer.depthBiasClamp = 0.0f; // Optional
1032 rasterizer.depthBiasSlopeFactor = 0.0f; // Optional
1033
1034 vk::PipelineMultisampleStateCreateInfo multisampling{};
1035 multisampling.sampleShadingEnable = false;
1036 // multisampling.rasterizationSamples // below
1037 multisampling.minSampleShading = 1.0f; // Optional
1038 multisampling.pSampleMask = nullptr; // Optional
1039 multisampling.alphaToCoverageEnable = false; // Optional
1040 multisampling.alphaToOneEnable = false; // Optional
1041
1042 vk::PipelineColorBlendAttachmentState colorBlendAttachment{};
1043 colorBlendAttachment.colorWriteMask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA;
1044 // colorBlendAttachment.blendEnable // below
1045 colorBlendAttachment.colorWriteMask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA;
1046 colorBlendAttachment.srcColorBlendFactor = vk::BlendFactor::eSrcAlpha;
1047 colorBlendAttachment.dstColorBlendFactor = vk::BlendFactor::eOneMinusSrcAlpha;
1048 colorBlendAttachment.colorBlendOp = vk::BlendOp::eAdd;
1049 colorBlendAttachment.srcAlphaBlendFactor = vk::BlendFactor::eOneMinusSrcAlpha;
1050 colorBlendAttachment.dstAlphaBlendFactor = vk::BlendFactor::eZero;
1051 colorBlendAttachment.alphaBlendOp = vk::BlendOp::eAdd;
1052
1053 vk::PipelineColorBlendStateCreateInfo colorBlending{};
1054 colorBlending.logicOpEnable = false;
1055 colorBlending.logicOp = vk::LogicOp::eCopy;
1056 colorBlending.attachmentCount = 1;
1057 colorBlending.pAttachments = &colorBlendAttachment;
1058 colorBlending.blendConstants[0] = 0.0f;
1059 colorBlending.blendConstants[1] = 0.0f;
1060 colorBlending.blendConstants[2] = 0.0f;
1061 colorBlending.blendConstants[3] = 0.0f;
1062
1063 vk::PipelineDepthStencilStateCreateInfo depthStencil{};
1064 depthStencil.depthTestEnable = true;
1065 depthStencil.depthWriteEnable = true;
1066 depthStencil.depthCompareOp = vk::CompareOp::eLess;
1067 depthStencil.depthBoundsTestEnable = false;
1068 depthStencil.stencilTestEnable = false;
1069
1070 vk::DynamicState dynamicStates[] = {vk::DynamicState::eViewport, vk::DynamicState::eScissor, vk::DynamicState::eLineWidth};
1071 vk::PipelineDynamicStateCreateInfo dynamicState{};
1072 // dynamicState.dynamicStateCount // below: viewport + scissor for text / texture, + line width for the main pipelines
1073 dynamicState.pDynamicStates = dynamicStates;
1074
1075 vk::PushConstantRange pushConstantRanges[2] = {vk::PushConstantRange{}, vk::PushConstantRange{}};
1076 pushConstantRanges[0].stageFlags = vk::ShaderStageFlagBits::eFragment;
1077 pushConstantRanges[0].offset = 0;
1078 pushConstantRanges[0].size = sizeof(float) * 4;
1079 pushConstantRanges[1].stageFlags = vk::ShaderStageFlagBits::eVertex;
1080 pushConstantRanges[1].offset = pushConstantRanges[0].size;
1081 pushConstantRanges[1].size = 4 * sizeof(float); // Point size, line width, viewport
1082 vk::PipelineLayoutCreateInfo pipelineLayoutInfo{};
1083 pipelineLayoutInfo.setLayoutCount = 1;
1084 pipelineLayoutInfo.pSetLayouts = &mUniformDescriptor;
1085 pipelineLayoutInfo.pushConstantRangeCount = 2;
1086 pipelineLayoutInfo.pPushConstantRanges = pushConstantRanges;
1087 mPipelineLayout = mDevice.createPipelineLayout(pipelineLayoutInfo, nullptr);
1088 pipelineLayoutInfo.setLayoutCount = 1;
1089 pipelineLayoutInfo.pSetLayouts = &mUniformDescriptorTexture;
1090 mPipelineLayoutTexture = mDevice.createPipelineLayout(pipelineLayoutInfo, nullptr);
1091
1092 vk::GraphicsPipelineCreateInfo pipelineInfo{};
1093 pipelineInfo.stageCount = 2;
1094 pipelineInfo.pVertexInputState = &vertexInputInfo;
1095 pipelineInfo.pInputAssemblyState = &inputAssembly;
1096 pipelineInfo.pViewportState = &viewportState;
1097 pipelineInfo.pRasterizationState = &rasterizer;
1098 pipelineInfo.pMultisampleState = &multisampling;
1099 // pipelineInfo.pDepthStencilState // below
1100 pipelineInfo.pColorBlendState = &colorBlending;
1101 pipelineInfo.pDynamicState = &dynamicState;
1102 // pipelineInfo.layout // below
1103 vk::PipelineRenderingCreateInfo renderingInfo{0, 1, &mSurfaceFormat.format};
1104 pipelineInfo.pNext = &renderingInfo;
1105 pipelineInfo.pStages = shaderStages;
1106 pipelineInfo.basePipelineHandle = VkPipeline(VK_NULL_HANDLE); // Optional
1107 pipelineInfo.basePipelineIndex = -1; // Optional
1108
1109 mPipelines.resize(9); // 0 points, 1 lines, 2 line strip (drawType index), 3 text, 4 texture, 5-7 smooth (shader-based) points, lines, line strip, 8 FSAA downsampling
1110 static constexpr vk::PrimitiveTopology types[3] = {vk::PrimitiveTopology::ePointList, vk::PrimitiveTopology::eLineList, vk::PrimitiveTopology::eLineStrip};
1111 for (uint32_t i = 0; i < mPipelines.size(); i++) {
1112 if (i == 8) { // FSAA downsampling, full-screen triangle without vertex input (last pipeline, the changed states are not reset)
1113 rasterizer.cullMode = vk::CullModeFlagBits::eNone;
1114 vertexInputInfo.vertexBindingDescriptionCount = vertexInputInfo.vertexAttributeDescriptionCount = 0;
1115 inputAssembly.topology = vk::PrimitiveTopology::eTriangleList;
1116 vertShaderStageInfo.pNext = &mShaders.at("vertexFullscreen");
1117 fragShaderStageInfo.pNext = &mShaders.at("fragmentDownsample");
1118 dynamicState.dynamicStateCount = 2;
1119 pipelineInfo.layout = mPipelineLayoutTexture;
1120 renderingInfo.depthAttachmentFormat = vk::Format::eUndefined;
1121 pipelineInfo.pDepthStencilState = nullptr;
1122 colorBlendAttachment.blendEnable = false;
1123 multisampling.rasterizationSamples = vk::SampleCountFlagBits::e1;
1124 } else if (i == 4) { // Texture rendering
1125 bindingDescription.stride = 4 * sizeof(float);
1126 attributeDescriptions.format = vk::Format::eR32G32B32A32Sfloat;
1127 inputAssembly.topology = vk::PrimitiveTopology::eTriangleList;
1128 vertShaderStageInfo.pNext = &mShaders.at("vertexTexture");
1129 fragShaderStageInfo.pNext = &mShaders.at("fragmentTexture");
1130 dynamicState.dynamicStateCount = 2;
1131 pipelineInfo.layout = mPipelineLayoutTexture;
1132 renderingInfo.depthAttachmentFormat = vk::Format::eUndefined;
1133 pipelineInfo.pDepthStencilState = nullptr;
1134 colorBlendAttachment.blendEnable = true;
1135 multisampling.rasterizationSamples = vk::SampleCountFlagBits::e1;
1136 } else if (i == 3) { // Text rendering
1137 bindingDescription.stride = 4 * sizeof(float);
1138 attributeDescriptions.format = vk::Format::eR32G32B32A32Sfloat;
1139 inputAssembly.topology = vk::PrimitiveTopology::eTriangleList;
1140 vertShaderStageInfo.pNext = &mShaders.at("vertexTexture");
1141 fragShaderStageInfo.pNext = &mShaders.at("fragmentText");
1142 dynamicState.dynamicStateCount = 2;
1143 pipelineInfo.layout = mPipelineLayoutTexture;
1144 renderingInfo.depthAttachmentFormat = vk::Format::eUndefined;
1145 pipelineInfo.pDepthStencilState = nullptr;
1146 colorBlendAttachment.blendEnable = true;
1147 multisampling.rasterizationSamples = vk::SampleCountFlagBits::e1;
1148 } else { // Point / line / line-strip rendering
1149 bindingDescription.stride = 3 * sizeof(float);
1150 attributeDescriptions.format = vk::Format::eR32G32B32Sfloat;
1151 const uint32_t drawIdx = i >= 5 ? i - 5 : i;
1152 inputAssembly.topology = types[drawIdx];
1153 vertShaderStageInfo.pNext = &mShaders.at(i < 5 ? (drawIdx == 0 ? "vertexPoint" : "vertex") : (drawIdx == 0 ? "vertexSmoothPoint" : "vertexSmoothLine"));
1154 fragShaderStageInfo.pNext = &mShaders.at(i < 5 ? "fragment" : (drawIdx == 0 ? "fragmentSmoothPoint" : "fragmentSmoothLine"));
1155 pipelineInfo.layout = mPipelineLayout;
1156 renderingInfo.depthAttachmentFormat = mZActive ? vk::Format::eD32Sfloat : vk::Format::eUndefined;
1157 pipelineInfo.pDepthStencilState = mZActive ? &depthStencil : nullptr;
1158 dynamicState.dynamicStateCount = 3;
1159 colorBlendAttachment.blendEnable = true;
1160 multisampling.rasterizationSamples = mMSAASampleCount;
1161 }
1162
1163 CHKERR(mDevice.createGraphicsPipelines(mPipelineCache, 1, &pipelineInfo, nullptr, &mPipelines[i]));
1164 }
1165}
1166
1167void GPUDisplayBackendVulkan::startFillCommandBuffer(vk::CommandBuffer& commandBuffer, uint32_t imageIndex, bool toMixBuffer)
1168{
1169 commandBuffer.reset({});
1170
1171 vk::CommandBufferBeginInfo beginInfo{};
1172 beginInfo.flags = {};
1173 commandBuffer.begin(beginInfo);
1174
1175 const uint32_t idx = toMixBuffer ? imageIndex + mImageCount : imageIndex;
1176 const bool msaa = mMSAASampleCount != vk::SampleCountFlagBits::e1;
1177 const vk::PipelineStageFlags2 prevStages = vk::PipelineStageFlagBits2::eColorAttachmentOutput | vk::PipelineStageFlagBits2::eTransfer | vk::PipelineStageFlagBits2::eFragmentShader; // Previous use of the render target (rendering, blit, mix texture), and the wait stage of the acquire semaphore
1178 cmdImageMemoryBarrier(commandBuffer, mRenderTargetImage[idx], prevStages, vk::AccessFlagBits2::eColorAttachmentWrite | vk::AccessFlagBits2::eTransferWrite, vk::PipelineStageFlagBits2::eColorAttachmentOutput, vk::AccessFlagBits2::eColorAttachmentWrite, vk::ImageLayout::eUndefined, vk::ImageLayout::eColorAttachmentOptimal);
1179 if (msaa) {
1180 cmdImageMemoryBarrier(commandBuffer, mMSAAImages[idx].image, vk::PipelineStageFlagBits2::eColorAttachmentOutput, vk::AccessFlagBits2::eColorAttachmentWrite, vk::PipelineStageFlagBits2::eColorAttachmentOutput, vk::AccessFlagBits2::eColorAttachmentWrite, vk::ImageLayout::eUndefined, vk::ImageLayout::eColorAttachmentOptimal);
1181 }
1182 if (mZActive) {
1183 const vk::PipelineStageFlags2 depthStages = vk::PipelineStageFlagBits2::eEarlyFragmentTests | vk::PipelineStageFlagBits2::eLateFragmentTests;
1184 cmdImageMemoryBarrier(commandBuffer, mZImages[idx].image, depthStages, vk::AccessFlagBits2::eDepthStencilAttachmentWrite, depthStages, vk::AccessFlagBits2::eDepthStencilAttachmentRead | vk::AccessFlagBits2::eDepthStencilAttachmentWrite, vk::ImageLayout::eUndefined, vk::ImageLayout::eDepthStencilAttachmentOptimal, vk::ImageAspectFlagBits::eDepth);
1185 }
1186
1187 vk::RenderingAttachmentInfo colorAttachment{msaa ? mMSAAImages[idx].view : *mRenderTargetView[idx], vk::ImageLayout::eColorAttachmentOptimal};
1188 colorAttachment.loadOp = vk::AttachmentLoadOp::eClear;
1189 colorAttachment.storeOp = msaa ? vk::AttachmentStoreOp::eDontCare : vk::AttachmentStoreOp::eStore;
1190 colorAttachment.clearValue.color = mDisplay->cfgL().invertColors ? vk::ClearColorValue{std::array<float, 4>{1.0f, 1.0f, 1.0f, 1.0f}} : vk::ClearColorValue{std::array<float, 4>{0.0f, 0.0f, 0.0f, 1.0f}};
1191 if (msaa) {
1192 colorAttachment.resolveMode = vk::ResolveModeFlagBits::eAverage;
1193 colorAttachment.resolveImageView = *mRenderTargetView[idx];
1194 colorAttachment.resolveImageLayout = vk::ImageLayout::eColorAttachmentOptimal;
1195 }
1196 vk::RenderingAttachmentInfo depthAttachment{mZActive ? mZImages[idx].view : vk::ImageView{}, vk::ImageLayout::eDepthStencilAttachmentOptimal};
1197 depthAttachment.loadOp = vk::AttachmentLoadOp::eClear;
1198 depthAttachment.storeOp = vk::AttachmentStoreOp::eDontCare;
1199 depthAttachment.clearValue.depthStencil = vk::ClearDepthStencilValue{1.0f, 0};
1200 cmdBeginRendering(commandBuffer, mRenderWidth, mRenderHeight, colorAttachment, mZActive ? &depthAttachment : nullptr);
1201
1202 vk::DeviceSize offsets[] = {0};
1203 if (mVBO.size) {
1204 commandBuffer.bindVertexBuffers(0, 1, &mVBO.buffer, offsets);
1205 }
1206 cmdPushDescriptors(commandBuffer, mPipelineLayout, mUniformBuffersMat[0][imageIndex]);
1207 const float viewport[2] = {(float)mRenderWidth, (float)mRenderHeight};
1208 commandBuffer.pushConstants(mPipelineLayout, vk::ShaderStageFlagBits::eVertex, 6 * sizeof(float), sizeof(viewport), viewport);
1209}
1210
1211void GPUDisplayBackendVulkan::endFillCommandBuffer(vk::CommandBuffer& commandBuffer)
1212{
1213 commandBuffer.endRendering();
1214 commandBuffer.end();
1215}
1216
1218{
1219 clearVector(mPipelines, [&](auto& x) { mDevice.destroyPipeline(x, nullptr); });
1220 mDevice.destroyPipelineLayout(mPipelineLayout, nullptr);
1221 mDevice.destroyPipelineLayout(mPipelineLayoutTexture, nullptr);
1222}
1223
1224// ---------------------------- VULKAN SHADERS ----------------------------
1225
1226#define LOAD_SHADER(file, ext) \
1227 mShaders[#file] = vk::ShaderModuleCreateInfo { {}, _binary_vulkan_##file##_##ext##_spv_len, reinterpret_cast<const uint32_t*>(_binary_vulkan_##file##_##ext##_spv_start) }
1228
1230{
1231 LOAD_SHADER(vertex, vert);
1232 LOAD_SHADER(fragment, frag);
1233 LOAD_SHADER(fragmentSmoothPoint, frag);
1234 LOAD_SHADER(vertexSmoothLine, vert);
1235 LOAD_SHADER(vertexSmoothPoint, vert);
1236 LOAD_SHADER(fragmentSmoothLine, frag);
1237 LOAD_SHADER(vertexPoint, vert);
1238 LOAD_SHADER(vertexTexture, vert);
1239 LOAD_SHADER(fragmentTexture, frag);
1240 LOAD_SHADER(fragmentText, frag);
1241 LOAD_SHADER(vertexFullscreen, vert);
1242 LOAD_SHADER(fragmentDownsample, frag);
1243}
1244
1245// ---------------------------- VULKAN BUFFERS ----------------------------
1246
1248{
1249 if (buffer.mapped) {
1250 memcpy(buffer.mapped, srcData, size);
1251 } else {
1252 auto tmp = createBuffer(size, srcData, vk::BufferUsageFlagBits::eTransferSrc, 0);
1253
1254 vk::CommandBuffer commandBuffer = getSingleTimeCommandBuffer();
1255 vk::BufferCopy copyRegion{};
1256 copyRegion.size = size;
1257 commandBuffer.copyBuffer(tmp.buffer, buffer.buffer, 1, &copyRegion);
1258 submitSingleTimeCommandBuffer(commandBuffer);
1259
1260 clearBuffer(tmp);
1261 }
1262}
1263
1264GPUDisplayBackendVulkan::VulkanBuffer GPUDisplayBackendVulkan::createBuffer(size_t size, const void* srcData, vk::BufferUsageFlags type, int32_t deviceMemory)
1265{
1266 vk::MemoryPropertyFlags properties;
1267 if (deviceMemory) {
1268 properties |= vk::MemoryPropertyFlagBits::eDeviceLocal;
1269 }
1270 if (deviceMemory == 0 || deviceMemory == 2) {
1271 properties |= (vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
1272 }
1273 if (deviceMemory == 1) {
1274 type |= vk::BufferUsageFlagBits::eTransferDst;
1275 }
1276
1278 vk::BufferCreateInfo bufferInfo{};
1279 bufferInfo.size = size;
1280 bufferInfo.usage = type;
1281 bufferInfo.sharingMode = vk::SharingMode::eExclusive;
1282 buffer.buffer = mDevice.createBuffer(bufferInfo, nullptr);
1283
1284 vk::MemoryRequirements memRequirements;
1285 memRequirements = mDevice.getBufferMemoryRequirements(buffer.buffer);
1286 vk::MemoryAllocateInfo allocInfo{};
1287 allocInfo.allocationSize = memRequirements.size;
1288 allocInfo.memoryTypeIndex = findMemoryType(memRequirements.memoryTypeBits, properties, mPhysicalDevice);
1289 buffer.memory = mDevice.allocateMemory(allocInfo, nullptr);
1290
1291 mDevice.bindBufferMemory(buffer.buffer, buffer.memory, 0);
1292
1293 buffer.size = size;
1294 buffer.deviceMemory = deviceMemory;
1295 if (deviceMemory != 1) {
1296 CHKERR(mDevice.mapMemory(buffer.memory, 0, VK_WHOLE_SIZE, {}, &buffer.mapped));
1297 }
1298
1299 if (srcData != nullptr) {
1300 writeToBuffer(buffer, size, srcData);
1301 }
1302
1303 return buffer;
1304}
1305
1307{
1308 mDevice.destroyBuffer(buffer.buffer, nullptr);
1309 mDevice.freeMemory(buffer.memory, nullptr); // Implicitly unmaps
1310}
1311
1323
1324// ---------------------------- VULKAN TEXTURES ----------------------------
1325
1326void GPUDisplayBackendVulkan::writeToImage(VulkanImage& image, const void* srcData, size_t srcSize)
1327{
1328 auto tmp = createBuffer(srcSize, srcData, vk::BufferUsageFlagBits::eTransferSrc, 0);
1329
1330 vk::CommandBuffer commandBuffer = getSingleTimeCommandBuffer();
1331 cmdImageMemoryBarrier(commandBuffer, image.image, vk::PipelineStageFlagBits2::eNone, vk::AccessFlagBits2::eNone, vk::PipelineStageFlagBits2::eTransfer, vk::AccessFlagBits2::eTransferWrite, vk::ImageLayout::eUndefined, vk::ImageLayout::eTransferDstOptimal);
1332 vk::BufferImageCopy region{};
1333 region.bufferOffset = 0;
1334 region.bufferRowLength = 0;
1335 region.bufferImageHeight = 0;
1336 region.imageSubresource.aspectMask = vk::ImageAspectFlagBits::eColor;
1337 region.imageSubresource.mipLevel = 0;
1338 region.imageSubresource.baseArrayLayer = 0;
1339 region.imageSubresource.layerCount = 1;
1340 region.imageOffset = vk::Offset3D{0, 0, 0};
1341 region.imageExtent = vk::Extent3D{image.sizex, image.sizey, 1};
1342 commandBuffer.copyBufferToImage(tmp.buffer, image.image, vk::ImageLayout::eTransferDstOptimal, 1, &region);
1343 cmdImageMemoryBarrier(commandBuffer, image.image, vk::PipelineStageFlagBits2::eTransfer, vk::AccessFlagBits2::eTransferWrite, vk::PipelineStageFlagBits2::eFragmentShader, vk::AccessFlagBits2::eShaderSampledRead, vk::ImageLayout::eTransferDstOptimal, vk::ImageLayout::eShaderReadOnlyOptimal);
1344 submitSingleTimeCommandBuffer(commandBuffer);
1345
1346 clearBuffer(tmp);
1347}
1348
1349GPUDisplayBackendVulkan::VulkanImage GPUDisplayBackendVulkan::createImage(uint32_t sizex, uint32_t sizey, const void* srcData, size_t srcSize, vk::Format format)
1350{
1352 createImageI(mDevice, mPhysicalDevice, image.image, image.memory, sizex, sizey, format, vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled, vk::MemoryPropertyFlagBits::eDeviceLocal, vk::ImageTiling::eOptimal, vk::SampleCountFlagBits::e1);
1353
1354 image.view = createImageViewI(mDevice, image.image, format);
1355
1356 image.sizex = sizex;
1357 image.sizey = sizey;
1358 image.format = format;
1359
1360 if (srcData) {
1361 writeToImage(image, srcData, srcSize);
1362 }
1363 return image;
1364}
1365
1367{
1368 mDevice.destroyImageView(image.view, nullptr);
1369 mDevice.destroyImage(image.image, nullptr);
1370 mDevice.freeMemory(image.memory, nullptr);
1371}
1372
1373// ---------------------------- VULKAN INIT EXIT ----------------------------
1374
1376{
1377 mEnableValidationLayers = (mDisplay->param() && mDisplay->GetProcessingSettings().debugLevel >= 2) || (getenv("GPUCA_VULKAN_VALIDATION") && atoi(getenv("GPUCA_VULKAN_VALIDATION")));
1378 mFramesInFlight = mDisplay->cfg().vulkan.nFramesInFlight;
1379
1380 createDevice();
1381 loadShaders();
1386
1387 return (0);
1388}
1389
1416
1417// ---------------------------- USER CODE ----------------------------
1418
1420{
1421 if (mScreenWidth == width && mScreenHeight == height) {
1422 return;
1423 }
1425 vk::Extent2D extent = chooseSwapExtent(mSwapChainDetails.capabilities);
1426 if (extent.width != mScreenWidth || extent.height != mScreenHeight) {
1427 mMustUpdateSwapChain = true;
1428 }
1429}
1430
1432{
1433 mDevice.waitIdle();
1435 if (totalVertizes) { // Zero-size buffers are invalid (empty event)
1436 mVBO = createBuffer(totalVertizes * sizeof(mDisplay->vertexBuffer()[0][0]), mDisplay->vertexBuffer()[0].data(), vk::BufferUsageFlagBits::eVertexBuffer, 1);
1437 }
1438 if (mDisplay->cfgR().useGLIndirectDraw) {
1440 if (mCmdBuffer.size()) {
1441 mIndirectCommandBuffer = createBuffer(mCmdBuffer.size() * sizeof(mCmdBuffer[0]), mCmdBuffer.data(), vk::BufferUsageFlagBits::eIndirectBuffer, 1);
1442 }
1443 mCmdBuffer.clear();
1444 }
1446}
1447
1449{
1450 auto first = std::get<0>(v);
1451 auto count = std::get<1>(v);
1452 auto iSector = std::get<2>(v);
1453 if (count == 0) {
1454 return 0;
1455 }
1457 return count;
1458 }
1459
1460 const int32_t pipeline = tt + ((tt == POINTS ? mDisplay->cfgL().smoothPoints : mDisplay->cfgL().smoothLines) ? 5 : 0);
1461 if (mCurrentCommandBufferLastPipeline != pipeline) {
1462 mCurrentCommandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, mPipelines[pipeline]);
1464 }
1465 if (mDisplay->cfgR().useGLIndirectDraw) {
1467 } else {
1468 for (uint32_t k = 0; k < count; k++) {
1470 }
1471 }
1472
1473 return count;
1474}
1475
1476bool GPUDisplayBackendVulkan::prepareDraw(const hmm_mat4& proj, const hmm_mat4& view, bool requestScreenshot, bool toMixBuffer, float includeMixImage)
1477{
1478 if (mDisplay->updateDrawCommands()) { // Main and mix command buffers stay cached while mixing, only the blend pass with the alpha value is recorded per frame
1480 }
1481
1482 if (includeMixImage > 0.f && mFrameSkipped) {
1483 return false; // The render to the mix buffer of this frame did not get an image
1484 }
1485 if (includeMixImage == 0.f) {
1488 if (mLastPresentId > 1 && fpsLimitMode() == FPS_LIMIT_VSYNC) { // Refresh rate limit (FIFO): at most one frame queued (wait for the second-last present), keeps the rate if a frame misses the deadline, timeout in case the window is hidden
1489 const vk::Result retVal = (vk::Result)VULKAN_HPP_DEFAULT_DISPATCHER.vkWaitForPresentKHR(static_cast<VkDevice>(mDevice), static_cast<VkSwapchainKHR>(mSwapChain), mLastPresentId - 1, 100'000'000);
1491 if (retVal != vk::Result::eTimeout && retVal != vk::Result::eErrorOutOfDateKHR) {
1492 CHKERR(retVal);
1493 }
1494 }
1495 auto getImage = [&]() { // Timeout so that a hidden window cannot block the thread (which may also dispatch the window system events) forever
1496 return mDevice.acquireNextImageKHR(mSwapChain, 100'000'000, mImageAvailableSemaphore[mCurrentFrame], VkFence(VK_NULL_HANDLE), &mCurrentImageIndex);
1497 };
1498
1499 vk::Result retVal = vk::Result::eSuccess;
1500 if (mPresentModeForVSyncLimit != (fpsLimitMode() == FPS_LIMIT_VSYNC)) { // Present mode depends on the FPS limit mode
1501 mMustUpdateSwapChain = true;
1502 }
1503 bool mustUpdateSwapChain = mMustUpdateSwapChain || mDisplay->updateRenderPipeline() || (toMixBuffer && !mMixingSupported) || mDownsampleFactor != getDownsampleFactor(requestScreenshot);
1504 if (!mustUpdateSwapChain) {
1505 retVal = getImage();
1506 if (retVal == vk::Result::eErrorOutOfDateKHR) {
1507 mustUpdateSwapChain = mMustUpdateSwapChain = true;
1508 }
1509 }
1510 if (mustUpdateSwapChain) {
1511 recreateRendering(requestScreenshot, toMixBuffer);
1512 retVal = getImage();
1513 mMustUpdateSwapChain = false;
1514 }
1516 mFrameSkipped = retVal == vk::Result::eTimeout || retVal == vk::Result::eNotReady || retVal == vk::Result::eErrorOutOfDateKHR;
1517 if (mFrameSkipped) {
1518 return false;
1519 }
1520 CHKERR(retVal);
1521 waitTimeline(mImageTimelineValue[mCurrentImageIndex]); // Previous frame using this image's resources (command buffers, uniform buffer, ...) finished
1522 if (mPresentFences.size()) { // Previous present of this image done, its present semaphore can be signaled again
1523 CHKERR(mDevice.waitForFences(1, &mPresentFences[mCurrentImageIndex], true, 1'000'000'000)); // Timeout (positive result, not an error) in case a failed present did not signal it
1525 }
1526
1527 mHasDrawnText = false;
1528 mFrameCommandBuffers.clear();
1529 const hmm_mat4 modelViewProj = proj * view;
1530 static_assert(sizeof(modelViewProj) == sizeof(mLastMVP));
1531 if (memcmp(&modelViewProj, mLastMVP, sizeof(mLastMVP))) {
1532 memcpy(mLastMVP, &modelViewProj, sizeof(mLastMVP));
1534 }
1538 }
1539 }
1540
1545 }
1546 return true;
1547}
1548
1549void GPUDisplayBackendVulkan::handleSwapChainResult(vk::Result retVal, uint8_t suboptimalBit)
1550{
1551 if (retVal == vk::Result::eErrorOutOfDateKHR || (retVal == vk::Result::eSuboptimalKHR && !(mSwapChainSuboptimal & suboptimalBit))) {
1552 mMustUpdateSwapChain = true;
1553 if (retVal == vk::Result::eSuboptimalKHR) {
1554 mSwapChainSuboptimal |= suboptimalBit;
1555 }
1556 }
1557 if (retVal == vk::Result::eSuccess && !mMustUpdateSwapChain) {
1558 mSwapChainSuboptimal &= ~suboptimalBit;
1559 }
1560}
1561
1562void GPUDisplayBackendVulkan::finishDraw(bool doScreenshot, bool toMixBuffer, float includeMixImage)
1563{
1566 if (!toMixBuffer) { // The mix pass is recorded before the main pass of the same frame, both are valid only after the latter
1568 }
1569 }
1570}
1571
1572void GPUDisplayBackendVulkan::finishFrame(bool doScreenshot, bool toMixBuffer, float includeMixImage)
1573{
1575 if (!toMixBuffer) {
1576 if (includeMixImage > 0.f) {
1579 }
1580 if (mDownsampleFSAA) {
1583 }
1584
1585 vk::SemaphoreSubmitInfo waitInfo{mImageAvailableSemaphore[mCurrentFrame], 0, vk::PipelineStageFlagBits2::eColorAttachmentOutput | vk::PipelineStageFlagBits2::eTransfer};
1586 vk::SubmitInfo2 submitInfo{{}, 1, &waitInfo};
1587 if (doScreenshot) {
1588 submitInfo.commandBufferInfoCount = mFrameCommandBuffers.size();
1589 submitInfo.pCommandBufferInfos = mFrameCommandBuffers.data();
1590 queueSubmit(nullptr, 1, &submitInfo, VkFence(VK_NULL_HANDLE));
1591 mDevice.waitIdle();
1592 if (mDisplay->cfgR().screenshotScaleFactor != 1) {
1593 readImageToPixels(mDownsampleImages[mCurrentImageIndex].image, mDownsampleImages[mCurrentImageIndex].view, mDownsampleFactor == 2 ? vk::ImageLayout::eTransferSrcOptimal : vk::ImageLayout::eShaderReadOnlyOptimal, mScreenshotPixels);
1594 } else {
1596 }
1597 mFrameCommandBuffers.clear();
1598 submitInfo.waitSemaphoreInfoCount = 0;
1599 }
1600 if (mHasDrawnText) {
1602 }
1604 submitInfo.commandBufferInfoCount = mFrameCommandBuffers.size();
1605 submitInfo.pCommandBufferInfos = mFrameCommandBuffers.data();
1606 vk::SemaphoreSubmitInfo signalInfos[2] = {{mPresentSemaphore[mCurrentImageIndex], 0, vk::PipelineStageFlagBits2::eAllCommands}, {mTimelineSemaphore, 0, vk::PipelineStageFlagBits2::eAllCommands}};
1607 submitInfo.signalSemaphoreInfoCount = 2;
1608 submitInfo.pSignalSemaphoreInfos = signalInfos;
1609 mFrameTimelineValue[mCurrentFrame] = mImageTimelineValue[mCurrentImageIndex] = queueSubmit(&signalInfos[1].value, 1, &submitInfo, VkFence(VK_NULL_HANDLE));
1610
1611 vk::PresentInfoKHR presentInfo{};
1612 presentInfo.waitSemaphoreCount = 1;
1613 presentInfo.pWaitSemaphores = &mPresentSemaphore[mCurrentImageIndex];
1614 presentInfo.swapchainCount = 1;
1615 presentInfo.pSwapchains = &mSwapChain;
1616 presentInfo.pImageIndices = &mCurrentImageIndex;
1617 presentInfo.pResults = nullptr;
1618 const uint64_t presentId = mLastPresentId + 1;
1619 vk::PresentIdKHR presentIdInfo{1, &presentId};
1620 if (fpsLimitMode() == FPS_LIMIT_VSYNC) { // Present wait only for the refresh rate limit, the fpsRate limit (frontend timer) must not be capped at the refresh rate
1621 presentInfo.pNext = &presentIdInfo;
1622 mLastPresentId = presentId;
1623 }
1624 vk::SwapchainPresentFenceInfoKHR presentFenceInfo{};
1625 if (mPresentFences.size()) {
1626 presentFenceInfo = vk::SwapchainPresentFenceInfoKHR{1, &mPresentFences[mCurrentImageIndex], presentInfo.pNext};
1627 presentInfo.pNext = &presentFenceInfo;
1628 }
1629 vk::Result retVal;
1630 {
1631 std::lock_guard<std::mutex> guard(mQueueMutex);
1632 retVal = mGraphicsQueue.presentKHR(&presentInfo);
1633 }
1635 if (retVal != vk::Result::eErrorOutOfDateKHR) {
1636 CHKERR(retVal);
1637 }
1638 }
1639}
1640
1641void GPUDisplayBackendVulkan::downsampleToFramebuffer(vk::CommandBuffer& commandBuffer)
1642{
1643 commandBuffer.reset({});
1644 vk::CommandBufferBeginInfo beginInfo{};
1645 beginInfo.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit;
1646 commandBuffer.begin(beginInfo);
1647
1648 if (mDownsampleFactor != 2) { // Exact box filter by shader, the linear blit below is only exact for factor 2
1649 cmdImageMemoryBarrier(commandBuffer, mSwapChainImages[mCurrentImageIndex], vk::PipelineStageFlagBits2::eColorAttachmentOutput, vk::AccessFlagBits2::eNone, vk::PipelineStageFlagBits2::eColorAttachmentOutput, vk::AccessFlagBits2::eColorAttachmentWrite, vk::ImageLayout::eUndefined, vk::ImageLayout::eColorAttachmentOptimal); // Src stage chains with the acquire semaphore wait
1650 cmdImageMemoryBarrier(commandBuffer, mDownsampleImages[mCurrentImageIndex].image, vk::PipelineStageFlagBits2::eColorAttachmentOutput, vk::AccessFlagBits2::eColorAttachmentWrite, vk::PipelineStageFlagBits2::eFragmentShader, vk::AccessFlagBits2::eShaderSampledRead, vk::ImageLayout::eColorAttachmentOptimal, vk::ImageLayout::eShaderReadOnlyOptimal);
1652 commandBuffer.end();
1653 return;
1654 }
1655 cmdImageMemoryBarrier(commandBuffer, mSwapChainImages[mCurrentImageIndex], vk::PipelineStageFlagBits2::eTransfer, vk::AccessFlagBits2::eNone, vk::PipelineStageFlagBits2::eTransfer, vk::AccessFlagBits2::eTransferWrite, vk::ImageLayout::eUndefined, vk::ImageLayout::eTransferDstOptimal); // Src stage chains with the acquire semaphore wait
1656 cmdImageMemoryBarrier(commandBuffer, mDownsampleImages[mCurrentImageIndex].image, vk::PipelineStageFlagBits2::eColorAttachmentOutput, vk::AccessFlagBits2::eColorAttachmentWrite, vk::PipelineStageFlagBits2::eTransfer, vk::AccessFlagBits2::eTransferRead, vk::ImageLayout::eColorAttachmentOptimal, vk::ImageLayout::eTransferSrcOptimal);
1657
1658 vk::Offset3D blitSizeSrc;
1659 blitSizeSrc.x = mRenderWidth;
1660 blitSizeSrc.y = mRenderHeight;
1661 blitSizeSrc.z = 1;
1662 vk::Offset3D blitSizeDst;
1663 blitSizeDst.x = mScreenWidth;
1664 blitSizeDst.y = mScreenHeight;
1665 blitSizeDst.z = 1;
1666 vk::ImageBlit imageBlitRegion{};
1667 imageBlitRegion.srcSubresource.aspectMask = vk::ImageAspectFlagBits::eColor;
1668 imageBlitRegion.srcSubresource.layerCount = 1;
1669 imageBlitRegion.srcOffsets[1] = blitSizeSrc;
1670 imageBlitRegion.dstSubresource.aspectMask = vk::ImageAspectFlagBits::eColor;
1671 imageBlitRegion.dstSubresource.layerCount = 1;
1672 imageBlitRegion.dstOffsets[1] = blitSizeDst;
1673 commandBuffer.blitImage(mDownsampleImages[mCurrentImageIndex].image, vk::ImageLayout::eTransferSrcOptimal, mSwapChainImages[mCurrentImageIndex], vk::ImageLayout::eTransferDstOptimal, 1, &imageBlitRegion, vk::Filter::eLinear);
1674
1675 cmdImageMemoryBarrier(commandBuffer, mSwapChainImages[mCurrentImageIndex], vk::PipelineStageFlagBits2::eTransfer, vk::AccessFlagBits2::eTransferWrite, vk::PipelineStageFlagBits2::eColorAttachmentOutput, vk::AccessFlagBits2::eColorAttachmentRead | vk::AccessFlagBits2::eColorAttachmentWrite, vk::ImageLayout::eTransferDstOptimal, vk::ImageLayout::eColorAttachmentOptimal); // Next: text pass and / or present transition
1676
1677 commandBuffer.end();
1678}
1679
1680void GPUDisplayBackendVulkan::cmdDownsample(vk::CommandBuffer commandBuffer, vk::ImageView src, vk::ImageView dst, uint32_t width, uint32_t height, int32_t factor)
1681{
1682 vk::RenderingAttachmentInfo colorAttachment{dst, vk::ImageLayout::eColorAttachmentOptimal};
1683 colorAttachment.loadOp = vk::AttachmentLoadOp::eDontCare; // Fully overwritten
1684 cmdBeginRendering(commandBuffer, width, height, colorAttachment);
1685 commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, mPipelines[8]);
1686 cmdPushDescriptors(commandBuffer, mPipelineLayoutTexture, mUniformBuffersMat[2][mCurrentImageIndex], src); // The UBO is not used by the shader
1687 commandBuffer.pushConstants(mPipelineLayoutTexture, vk::ShaderStageFlagBits::eFragment, 0, sizeof(factor), &factor);
1688 commandBuffer.draw(3, 1, 0, 0);
1689 commandBuffer.endRendering();
1690}
1691
1693{
1696 hmm_mat4 proj = HMM_Orthographic(0.f, mScreenWidth, 0.f, mScreenHeight, -1, 1);
1697 writeToBuffer(mUniformBuffersMat[1][mCurrentImageIndex], sizeof(proj), &proj);
1698 }
1699 mFontVertexBufferHost.clear();
1700 mTextDrawCommands.clear();
1701}
1702
1704{
1705 if (!mHasDrawnText) {
1706 return;
1707 }
1708
1710
1711 vk::CommandBufferBeginInfo beginInfo{};
1712 beginInfo.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit;
1713 mCommandBuffersText[mCurrentImageIndex].begin(beginInfo);
1714
1716
1718 const size_t fontBufferSize = mFontVertexBufferHost.size() * sizeof(mFontVertexBufferHost[0]);
1719 if (fontBuffer.size < fontBufferSize) { // Persistent per image, only grows
1720 if (fontBuffer.size) {
1721 clearBuffer(fontBuffer);
1722 }
1723 fontBuffer = createBuffer(std::max(fontBufferSize, 2 * fontBuffer.size), nullptr, vk::BufferUsageFlagBits::eVertexBuffer, 0);
1724 }
1725 writeToBuffer(fontBuffer, fontBufferSize, mFontVertexBufferHost.data());
1726
1727 mCommandBuffersText[mCurrentImageIndex].bindPipeline(vk::PipelineBindPoint::eGraphics, mPipelines[3]);
1729 vk::DeviceSize offsets[] = {0};
1730 mCommandBuffersText[mCurrentImageIndex].bindVertexBuffers(0, 1, &fontBuffer.buffer, offsets);
1731
1732 for (const auto& cmd : mTextDrawCommands) {
1733 mCommandBuffersText[mCurrentImageIndex].pushConstants(mPipelineLayoutTexture, vk::ShaderStageFlagBits::eFragment, 0, sizeof(cmd.color), cmd.color);
1734 mCommandBuffersText[mCurrentImageIndex].draw(cmd.nVertices, 1, cmd.firstVertex, 0);
1735 }
1736
1737 mFontVertexBufferHost.clear();
1738
1741}
1742
1743void GPUDisplayBackendVulkan::mixImages(vk::CommandBuffer commandBuffer, float mixSlaveImage)
1744{
1747 hmm_mat4 proj = HMM_Orthographic(0.f, mRenderWidth, 0.f, mRenderHeight, -1, 1);
1748 writeToBuffer(mUniformBuffersMat[2][mCurrentImageIndex], sizeof(proj), &proj);
1749 }
1750 commandBuffer.reset({});
1751 vk::CommandBufferBeginInfo beginInfo{};
1752 beginInfo.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit;
1753 commandBuffer.begin(beginInfo);
1754
1756 cmdImageMemoryBarrier(commandBuffer, image, vk::PipelineStageFlagBits2::eColorAttachmentOutput, vk::AccessFlagBits2::eColorAttachmentWrite, vk::PipelineStageFlagBits2::eFragmentShader, vk::AccessFlagBits2::eShaderSampledRead, vk::ImageLayout::eColorAttachmentOptimal, vk::ImageLayout::eShaderReadOnlyOptimal);
1758
1759 commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, mPipelines[4]);
1761 vk::DeviceSize offsets[] = {0};
1762 commandBuffer.bindVertexBuffers(0, 1, &mMixingTextureVertexArray.buffer, offsets);
1763
1764 commandBuffer.pushConstants(mPipelineLayoutTexture, vk::ShaderStageFlagBits::eFragment, 0, sizeof(mixSlaveImage), &mixSlaveImage);
1765 commandBuffer.draw(6, 1, 0, 0);
1766
1767 commandBuffer.endRendering();
1768 commandBuffer.end();
1769}
1770
1772{
1774 return;
1775 }
1776 mCurrentCommandBuffer.pushConstants(mPipelineLayout, vk::ShaderStageFlagBits::eFragment, 0, sizeof(color), color.data());
1777}
1778
1780{
1782 return;
1783 }
1784 float size = std::min(mDisplay->cfgL().pointSize * mDownsampleFactor * factor + (mDisplay->cfgL().smoothPoints ? SMOOTH_POINT_EXTRA_SIZE : 0.f), mMaxPointSize);
1785 mCurrentCommandBuffer.pushConstants(mPipelineLayout, vk::ShaderStageFlagBits::eVertex, sizeof(std::array<float, 4>), sizeof(size), &size);
1786}
1787
1789{
1791 return;
1792 }
1793 float width = mDisplay->cfgL().lineWidth * mDownsampleFactor * factor;
1794 if (mDisplay->cfgL().smoothLines) {
1795 const float expand = mStrictLines ? 1.f : 1.4143f; // Non-strict wide lines may be parallelograms, widen so that the perpendicular width is covered
1796 width = std::min(width + SMOOTH_LINE_EXTRA_WIDTH, mMaxLineWidth / expand); // The shader must see the width that is actually rasterized
1797 mCurrentCommandBuffer.pushConstants(mPipelineLayout, vk::ShaderStageFlagBits::eVertex, 5 * sizeof(float), sizeof(width), &width);
1798 width *= expand;
1799 }
1800 mCurrentCommandBuffer.setLineWidth(std::min(width, mMaxLineWidth));
1801}
1802
1807
1808void GPUDisplayBackendVulkan::addFontSymbol(int32_t symbol, int32_t sizex, int32_t sizey, int32_t offsetx, int32_t offsety, int32_t advance, void* data)
1809{
1810 if (symbol != (int32_t)mFontSymbols.size()) {
1811 throw std::runtime_error("Incorrect symbol ID");
1812 }
1813 mFontSymbols.emplace_back(FontSymbolVulkan{{{sizex, sizey}, {offsetx, offsety}, advance}, nullptr, 0.f, 0.f, 0.f, 0.f});
1814 auto& buffer = mFontSymbols.back().data;
1815 if (sizex && sizey) {
1816 buffer.reset(new char[sizex * sizey]);
1817 memcpy(buffer.get(), data, sizex * sizey);
1818 }
1819}
1820
1822{
1823 int32_t maxSizeX = 0, maxSizeY = 0, maxBigX = 0, maxBigY = 0, maxRowY = 0;
1824 bool smooth = smoothFont();
1825 // Build a mega texture containing all fonts
1826 for (auto& symbol : mFontSymbols) {
1827 maxSizeX = std::max(maxSizeX, symbol.size[0]);
1828 maxSizeY = std::max(maxSizeY, symbol.size[1]);
1829 }
1830 uint32_t nn = ceil(std::sqrt(mFontSymbols.size()));
1831 int32_t sizex = nn * maxSizeX;
1832 int32_t sizey = nn * maxSizeY;
1833 std::unique_ptr<char[]> bigImage{new char[sizex * sizey]};
1834 memset(bigImage.get(), 0, sizex * sizey);
1835 int32_t rowy = 0, colx = 0;
1836 for (uint32_t i = 0; i < mFontSymbols.size(); i++) {
1837 auto& s = mFontSymbols[i];
1838 if (colx + s.size[0] > sizex) {
1839 colx = 0;
1840 rowy += maxRowY;
1841 maxRowY = 0;
1842 }
1843 for (int32_t k = 0; k < s.size[1]; k++) {
1844 for (int32_t j = 0; j < s.size[0]; j++) {
1845 int8_t val = s.data.get()[j + k * s.size[0]];
1846 if (!smooth) {
1847 val = val < 0 ? 0xFF : 0;
1848 }
1849 bigImage.get()[(colx + j) + (rowy + k) * sizex] = val;
1850 }
1851 }
1852 s.data.reset();
1853 s.x0 = colx;
1854 s.x1 = colx + s.size[0];
1855 s.y0 = rowy;
1856 s.y1 = rowy + s.size[1];
1857 maxBigX = std::max(maxBigX, colx + s.size[0]);
1858 maxBigY = std::max(maxBigY, rowy + s.size[1]);
1859 maxRowY = std::max(maxRowY, s.size[1]);
1860 colx += s.size[0];
1861 }
1862 if (maxBigX != sizex) {
1863 for (int32_t y = 1; y < maxBigY; y++) {
1864 memmove(bigImage.get() + y * maxBigX, bigImage.get() + y * sizex, maxBigX);
1865 }
1866 }
1867 sizex = maxBigX;
1868 sizey = maxBigY;
1869 for (uint32_t i = 0; i < mFontSymbols.size(); i++) {
1870 auto& s = mFontSymbols[i];
1871 s.x0 /= sizex;
1872 s.x1 /= sizex;
1873 s.y0 /= sizey;
1874 s.y1 /= sizey;
1875 }
1876
1877 mFontImage = createImage(sizex, sizey, bigImage.get(), sizex * sizey, vk::Format::eR8Unorm);
1878}
1879
1881{
1882 mDevice.waitIdle();
1886 }
1887 mFontSymbols.clear();
1888}
1889
1890void GPUDisplayBackendVulkan::GLPrintText(const char* s, float x, float y, float* color, float scale, uint32_t nCharacters)
1891{
1892 if (!mFreetypeInitialized) {
1893 return;
1894 }
1895
1896 size_t firstVertex = mFontVertexBufferHost.size() / 4;
1897 if (smoothFont()) {
1898 scale *= 0.25f; // Font size is 48 to have nice bitmap, scale to size 12
1899 }
1900
1901 for (const unsigned char* c = (const unsigned char*)s; *c && (nCharacters == 0 || c < (const unsigned char*)s + nCharacters); c++) {
1902 if (*c < 32 || *c >= SOLID_GLYPH) { // Printable ASCII only, SOLID_GLYPH is not a character
1903 GPUError("Trying to draw unsupported symbol: %d", (int32_t)*c);
1904 continue;
1905 }
1906 const FontSymbolVulkan& sym = mFontSymbols[*c];
1907 if (sym.size[0] && sym.size[1]) {
1908 mHasDrawnText = true;
1909 float xpos = x + sym.offset[0] * scale;
1910 float ypos = y - (sym.size[1] - sym.offset[1]) * scale;
1911 float w = sym.size[0] * scale;
1912 float h = sym.size[1] * scale;
1913 float vertices[6][4] = {
1914 {xpos, mScreenHeight - 1 - ypos, sym.x0, sym.y1},
1915 {xpos, mScreenHeight - 1 - (ypos + h), sym.x0, sym.y0},
1916 {xpos + w, mScreenHeight - 1 - ypos, sym.x1, sym.y1},
1917 {xpos + w, mScreenHeight - 1 - ypos, sym.x1, sym.y1},
1918 {xpos, mScreenHeight - 1 - (ypos + h), sym.x0, sym.y0},
1919 {xpos + w, mScreenHeight - 1 - (ypos + h), sym.x1, sym.y0}};
1920 size_t oldSize = mFontVertexBufferHost.size();
1921 mFontVertexBufferHost.resize(oldSize + 4 * 6);
1922 memcpy(&mFontVertexBufferHost[oldSize], &vertices[0][0], sizeof(vertices));
1923 }
1924 x += (sym.advance >> 6) * scale; // shift is in 1/64th of a pixel
1925 }
1926
1927 addTextDrawCommand(firstVertex, color);
1928}
1929
1930void GPUDisplayBackendVulkan::addTextDrawCommand(size_t firstVertex, const float* color)
1931{
1932 size_t nVertices = mFontVertexBufferHost.size() / 4 - firstVertex;
1933
1934 if (nVertices) {
1935 auto& c = mTextDrawCommands;
1936 if (c.size() && c.back().color[0] == color[0] && c.back().color[1] == color[1] && c.back().color[2] == color[2] && c.back().color[3] == color[3]) {
1937 c.back().nVertices += nVertices;
1938 } else {
1939 c.emplace_back(TextDrawCommand{firstVertex, nVertices, {color[0], color[1], color[2], color[3]}});
1940 }
1941 }
1942}
1943
1944void GPUDisplayBackendVulkan::GLDrawQuad(const float (&corners)[4][2], const float* color)
1945{
1946 if (!mFreetypeInitialized) {
1947 return;
1948 }
1950 const float u = (sym.x0 + sym.x1) * 0.5f, v = (sym.y0 + sym.y1) * 0.5f; // Center of the opaque glyph in the font atlas
1951 const size_t firstVertex = mFontVertexBufferHost.size() / 4;
1952 for (int32_t i : {0, 2, 1, 0, 3, 2}) { // Winding as the glyph quads of GLPrintText, the text pipeline culls back faces
1953 mFontVertexBufferHost.insert(mFontVertexBufferHost.end(), {corners[i][0], mScreenHeight - 1 - corners[i][1], u, v});
1954 }
1955 mHasDrawnText = true;
1956 addTextDrawCommand(firstVertex, color);
1957}
1958
1959void GPUDisplayBackendVulkan::readImageToPixels(vk::Image image, vk::ImageView view, vk::ImageLayout layout, std::vector<char>& pixels)
1960{
1961 const vk::Format format = mSurfaceFormat.format;
1962 if (format != vk::Format::eB8G8R8A8Unorm && format != vk::Format::eB8G8R8A8Srgb && format != vk::Format::eR8G8B8A8Unorm && format != vk::Format::eR8G8B8A8Srgb) {
1963 GPUError("Screenshot not supported for swapchain format %s, only 8 bit BGRA / RGBA", vk::to_string(format).c_str());
1964 pixels.clear();
1965 return;
1966 }
1967 uint32_t width = mScreenWidth * mDisplay->cfgR().screenshotScaleFactor;
1968 uint32_t height = mScreenHeight * mDisplay->cfgR().screenshotScaleFactor;
1969 static constexpr int32_t bytesPerPixel = 4;
1970 pixels.resize(width * height * bytesPerPixel);
1971
1972 vk::Image dstImage, src;
1973 vk::ImageView dstView;
1974 vk::DeviceMemory dstImageMemory;
1975 const bool scaled = mDisplay->cfgR().screenshotScaleFactor != 1;
1976 const int32_t factor = mRenderWidth / width; // FSAA factor between the rendered image and the screenshot
1977 const bool shaderDownsample = scaled && factor != 1 && factor != 2; // Exact box filter, the linear blit is only exact for factor 2
1978 const vk::ImageLayout srcLayout = shaderDownsample ? vk::ImageLayout::eShaderReadOnlyOptimal : vk::ImageLayout::eTransferSrcOptimal;
1979 const vk::PipelineStageFlags2 srcStage = shaderDownsample ? vk::PipelineStageFlagBits2::eFragmentShader : vk::PipelineStageFlagBits2::eTransfer;
1980 VulkanBuffer readBuffer = createBuffer(width * height * bytesPerPixel, nullptr, vk::BufferUsageFlagBits::eTransferDst, 0);
1981 vk::CommandBuffer cmdBuffer = getSingleTimeCommandBuffer();
1982 cmdImageMemoryBarrier(cmdBuffer, image, vk::PipelineStageFlagBits2::eColorAttachmentOutput | vk::PipelineStageFlagBits2::eTransfer | vk::PipelineStageFlagBits2::eFragmentShader, vk::AccessFlagBits2::eColorAttachmentWrite | vk::AccessFlagBits2::eTransferWrite, srcStage, shaderDownsample ? vk::AccessFlagBits2::eShaderSampledRead : vk::AccessFlagBits2::eTransferRead, layout, srcLayout);
1983 if (shaderDownsample) {
1984 createImageI(mDevice, mPhysicalDevice, dstImage, dstImageMemory, width, height, mSurfaceFormat.format, vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eTransferSrc, vk::MemoryPropertyFlagBits::eDeviceLocal, vk::ImageTiling::eOptimal);
1985 dstView = createImageViewI(mDevice, dstImage, mSurfaceFormat.format);
1986 cmdImageMemoryBarrier(cmdBuffer, dstImage, vk::PipelineStageFlagBits2::eNone, vk::AccessFlagBits2::eNone, vk::PipelineStageFlagBits2::eColorAttachmentOutput, vk::AccessFlagBits2::eColorAttachmentWrite, vk::ImageLayout::eUndefined, vk::ImageLayout::eColorAttachmentOptimal);
1987 cmdDownsample(cmdBuffer, view, dstView, width, height, factor);
1988 cmdImageMemoryBarrier(cmdBuffer, dstImage, vk::PipelineStageFlagBits2::eColorAttachmentOutput, vk::AccessFlagBits2::eColorAttachmentWrite, vk::PipelineStageFlagBits2::eTransfer, vk::AccessFlagBits2::eTransferRead, vk::ImageLayout::eColorAttachmentOptimal, vk::ImageLayout::eTransferSrcOptimal);
1989 src = dstImage;
1990 } else if (scaled) {
1991 createImageI(mDevice, mPhysicalDevice, dstImage, dstImageMemory, width, height, mSurfaceFormat.format, vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eTransferSrc | vk::ImageUsageFlagBits::eTransferDst, vk::MemoryPropertyFlagBits::eDeviceLocal, vk::ImageTiling::eOptimal);
1992 cmdImageMemoryBarrier(cmdBuffer, dstImage, vk::PipelineStageFlagBits2::eNone, vk::AccessFlagBits2::eNone, vk::PipelineStageFlagBits2::eTransfer, vk::AccessFlagBits2::eTransferWrite, vk::ImageLayout::eUndefined, vk::ImageLayout::eTransferDstOptimal);
1993 vk::Offset3D blitSizeSrc = {(int32_t)mRenderWidth, (int32_t)mRenderHeight, 1};
1994 vk::Offset3D blitSizeDst = {(int32_t)width, (int32_t)height, 1};
1995 vk::ImageBlit imageBlitRegion{};
1996 imageBlitRegion.srcSubresource.aspectMask = vk::ImageAspectFlagBits::eColor;
1997 imageBlitRegion.srcSubresource.layerCount = 1;
1998 imageBlitRegion.srcOffsets[1] = blitSizeSrc;
1999 imageBlitRegion.dstSubresource.aspectMask = vk::ImageAspectFlagBits::eColor;
2000 imageBlitRegion.dstSubresource.layerCount = 1;
2001 imageBlitRegion.dstOffsets[1] = blitSizeDst;
2002 cmdBuffer.blitImage(image, vk::ImageLayout::eTransferSrcOptimal, dstImage, vk::ImageLayout::eTransferDstOptimal, 1, &imageBlitRegion, vk::Filter::eLinear);
2003 src = dstImage;
2004 cmdImageMemoryBarrier(cmdBuffer, dstImage, vk::PipelineStageFlagBits2::eTransfer, vk::AccessFlagBits2::eTransferWrite, vk::PipelineStageFlagBits2::eTransfer, vk::AccessFlagBits2::eTransferRead, vk::ImageLayout::eTransferDstOptimal, vk::ImageLayout::eTransferSrcOptimal);
2005 } else {
2006 src = image;
2007 }
2008
2009 vk::BufferImageCopy copyRegion{};
2010 copyRegion.imageSubresource.aspectMask = vk::ImageAspectFlagBits::eColor;
2011 copyRegion.imageSubresource.layerCount = 1;
2012 copyRegion.imageExtent = vk::Extent3D{width, height, 1};
2013 cmdBuffer.copyImageToBuffer(src, vk::ImageLayout::eTransferSrcOptimal, readBuffer.buffer, 1, &copyRegion);
2014
2015 vk::BufferMemoryBarrier2 hostBarrier{vk::PipelineStageFlagBits2::eTransfer, vk::AccessFlagBits2::eTransferWrite, vk::PipelineStageFlagBits2::eHost, vk::AccessFlagBits2::eHostRead, VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED, readBuffer.buffer, 0, VK_WHOLE_SIZE};
2016 cmdBuffer.pipelineBarrier2(vk::DependencyInfo{{}, 0, nullptr, 1, &hostBarrier, 0, nullptr});
2017 cmdImageMemoryBarrier(cmdBuffer, image, srcStage, vk::AccessFlagBits2::eNone, vk::PipelineStageFlagBits2::eColorAttachmentOutput | vk::PipelineStageFlagBits2::eTransfer, vk::AccessFlagBits2::eNone, srcLayout, layout); // Back to the layout the following passes expect
2019
2020 const bool swapRB = format == vk::Format::eR8G8B8A8Unorm || format == vk::Format::eR8G8B8A8Srgb; // Raw copy in swapchain format, the BMP needs BGRA
2021 const char* data = (const char*)readBuffer.mapped;
2022 for (uint32_t i = 0; i < height; i++) { // BMP rows are bottom-up
2023 char* dst = pixels.data() + i * width * bytesPerPixel;
2024 memcpy(dst, data + (height - i - 1) * width * bytesPerPixel, width * bytesPerPixel);
2025 if (swapRB) {
2026 for (uint32_t j = 0; j < width; j++) {
2027 std::swap(dst[j * bytesPerPixel], dst[j * bytesPerPixel + 2]);
2028 }
2029 }
2030 }
2031 clearBuffer(readBuffer);
2032 if (scaled) {
2033 if (dstView) {
2034 mDevice.destroyImageView(dstView, nullptr);
2035 }
2036 mDevice.freeMemory(dstImageMemory, nullptr);
2037 mDevice.destroyImage(dstImage, nullptr);
2038 }
2039}
2040
uint64_t vertex
Definition RawEventData.h:9
unsigned int uint32_t
int32_t i
#define CHKERR(cmd)
#define LOAD_SHADER(file, ext)
uint32_t iSector
int32_t retVal
GPUChain * chain
Timeframe settings Average distance in cm of events merged into Randomize distance around average distance of merged events Simulate correct bunch interactions instead of placing only the average number of events A value[n] sets TFlen for[n] collisions in Number of bunches per trainsort Number of bunch trains Instantaneous interaction rate Do not simulate border Total number of collisions to be placed in the interior of all time Do not select random but walk over array of events in stride steps h Event generator settings h configStandalone Use CPU for GPU Force usage of the specified GPU device no CPU fallback Continue processing after an error s
Timeframe settings Average distance in cm of events merged into Randomize distance around average distance of merged events Simulate correct bunch interactions instead of placing only the average number of events A value[n] sets TFlen for[n] collisions in Number of bunches per trainsort Number of bunch trains Instantaneous interaction rate Do not simulate border Total number of collisions to be placed in the interior of all time Do not select random but walk over array of events in stride steps h Event generator settings h configStandalone Use CPU for GPU Force usage of the specified GPU device no CPU fallback Continue processing after an error First event to Number of events to Number of iterations to Number of iterations to Number of initial iterations excluded from const char Directory with events to Events directory is and not inside events Show standalone event Run event generator maximum time bin of continuous for triggered for automatic continuous for automatic continuous triggered uint64_t
Timeframe settings Average distance in cm of events merged into Randomize distance around average distance of merged events Simulate correct bunch interactions instead of placing only the average number of events A value[n] sets TFlen for[n] collisions in Number of bunches per trainsort Number of bunch trains Instantaneous interaction rate Do not simulate border Total number of collisions to be placed in the interior of all time Do not select random but walk over array of events in stride steps h Event generator settings h configStandalone Use CPU for GPU Force usage of the specified GPU device no CPU fallback Continue processing after an error First event to Number of events to Number of iterations to Number of iterations to Number of initial iterations excluded from const char e
configStandalone Reconstruction rec_tpc multiplier for the combined cluster track error during track following area in cm for the search of for z only used if decrease removal by when above this local occupancy rowx Shift of TPC revert cluster flag edge bit distance to edge exceeds this ZOffset for secondary multiple of radius max P of electron K BB bands crossing max P of electron p BB bands crossing max P of electron d BB bands crossing max P of electron t BB bands crossing min accepted dEdxMaxTPC of the track Additive extra cluster error for Y2 if edge flag set Additive extra cluster error for Y2 if single set Additive extra cluster error for Y2 if or single set Additive extra cluster error for Z2 if or single set Extra errors to add to track when crossing depending on addErrorsCECrossing Inner portion of y range in sector that is not used in searching for extrapolated track candidates factor2YS for track merging factor2K for track merging Margin in cm of Y position when rejecting edge clusters based on uncorrected track Y Max fraction of shared clusters for tracklet Except pad from cluster finding if total number of charges in a fragment is above this Except pad from cluster finding if number of consecutive charges in a fragment is above this Threshold where a timebin is considered disabling the noisy pad check for that pad Treat signal above this minimum as saturated Smoothing factor for the exponential Highly Ionising Particle tail filter Number of timebins to use for the averaging Add additional custom track errors when crossing relative as fraction of Do N fit passes in final fit of< 0:reject at max -n hits") AddOptionRTC(rejectIFCLowRadiusCluster, uint8_t, 1, "", 0, "Reject clusters that get the IFC mask error during refit") AddOptionRTC(dEdxTruncLow, uint8_t, 2, "", 0, "Low truncation threshold, fraction of 128") AddOptionRTC(dEdxTruncHigh, uint8_t, 77, "", 0, "High truncation threshold, fraction of 128") AddOptionRTC(extrapolationTracking, int8_t, 1, "", 0, "Enable Extrapolation Tracking(prolong tracks to adjacent sectors to find short segments)") AddOptionRTC(disableRefitAttachment, uint8_t, 0, "", 0, "Bitmask to disable certain attachment steps during refit(1:attachment, 2:propagation, 4:loop following, 8:mirroring)") AddOptionRTC(rejectionStrategy, uint8_t, o2::gpu::GPUSettings::RejectionStrategyA, "", 0, "Enable rejection of TPC clusters for compression(0=no, 1=strategy A, 2=strategy B)") AddOptionRTC(mergeLoopersAfterburner, uint8_t, 1, "", 0, "Run afterburner for additional looper merging") AddOptionRTC(compressionTypeMask, uint8_t, o2::gpu::GPUSettings::CompressionFull, "", 0, "TPC Compression mode bits(1=truncate charge/width LSB, 2=differences, 4=track-model)") AddOptionRTC(compressionSortOrder, uint8_t, o2::gpu::GPUSettings::SortTime, "", 0, "Sort order of TPC compression(0=time, 1=pad, 2=Z-time-pad, 3=Z-pad-time, 4=no sorting(use incoming order))") AddOptionRTC(sigBitsCharge, uint8_t, 4, "", 0, "Number of significant bits for TPC cluster charge in compression mode 1") AddOptionRTC(sigBitsWidth, uint8_t, 3, "", 0, "Number of significant bits for TPC cluster width in compression mode 1") AddOptionRTC(dropLoopers, uint8_t, 0, "", 0, "Drop looping tracks starting from second loop") AddOptionRTC(mergerInterpolateErrors, uint8_t, 1, "", 0, "Use interpolation instead of extrapolation for chi2 based cluster rejection") AddOptionRTC(mergerInterpolateRejectAlsoOnCurrentPosition, uint8_t, 1, "", 0, "When using mergerInterpolateErrors, reject based on chi2 twice computed with interpolated and current track position starting from NDF > mergerNonInterpolateRejectMinNDF Merge tracks accross the central electrode Enable PID response Add sub threshold clusters in TPC dEdx computation OR mask of TPC flags that will reject the cluster in alternative dEdx Reject edge clusters based on uncorrected track Y during track fit Increase decrease removal by when on this number of pads from the edge h configStandalone Reconstruction rec_trd Max chi2 for TRD tracklets to be matched to a track Chi2 cut for strict matching mode Number of sigmas for ITS TPC track time error estimate Addition to search road around track prolongation along Y in cm Optimal tracklet rphi resolution in maximum chi2 per attached tracklet for TRD tracks take into account the full likelihood of the slope including exponential tails Tracks with less attached tracklets are discarded after the tracking Post trigger Pile up integration time in BCs fits all iterations but the last one in projections Use material lookup table for TPC refit Apply workarounds to avoid cyclic merge should not be needed tpc dyn configStandalone Processing proc_rtc Replace constant variables static by constexpr expressions Compile RTC in deterministic with NO_FAST_MATH flags and GPUCA_DETERMINISTIC_MODE define Use RTC to optimize GPU code h configStandalone Processing proc_rtctech Use a file lock to serialize access to the cache folder int32_t
configStandalone Reconstruction rec_tpc multiplier for the combined cluster track error during track following area in cm for the search of for z only used if decrease removal by when above this local occupancy rowx Shift of TPC revert cluster flag edge bit distance to edge exceeds this ZOffset for secondary multiple of radius max P of electron K BB bands crossing max P of electron p BB bands crossing max P of electron d BB bands crossing max P of electron t BB bands crossing min accepted dEdxMaxTPC of the track Additive extra cluster error for Y2 if edge flag set Additive extra cluster error for Y2 if single set Additive extra cluster error for Y2 if or single set Additive extra cluster error for Z2 if or single set Extra errors to add to track when crossing depending on addErrorsCECrossing Inner portion of y range in sector that is not used in searching for extrapolated track candidates factor2YS for track merging factor2K for track merging Margin in cm of Y position when rejecting edge clusters based on uncorrected track Y Max fraction of shared clusters for tracklet Except pad from cluster finding if total number of charges in a fragment is above this Except pad from cluster finding if number of consecutive charges in a fragment is above this Threshold where a timebin is considered disabling the noisy pad check for that pad Treat signal above this minimum as saturated Smoothing factor for the exponential Highly Ionising Particle tail filter Number of timebins to use for the averaging Add additional custom track errors when crossing relative as fraction of Do N fit passes in final fit of< 0:reject at max -n hits") AddOptionRTC(rejectIFCLowRadiusCluster, uint8_t, 1, "", 0, "Reject clusters that get the IFC mask error during refit") AddOptionRTC(dEdxTruncLow, uint8_t, 2, "", 0, "Low truncation threshold, fraction of 128") AddOptionRTC(dEdxTruncHigh, uint8_t, 77, "", 0, "High truncation threshold, fraction of 128") AddOptionRTC(extrapolationTracking, int8_t, 1, "", 0, "Enable Extrapolation Tracking(prolong tracks to adjacent sectors to find short segments)") AddOptionRTC(disableRefitAttachment, uint8_t, 0, "", 0, "Bitmask to disable certain attachment steps during refit(1:attachment, 2:propagation, 4:loop following, 8:mirroring)") AddOptionRTC(rejectionStrategy, uint8_t, o2::gpu::GPUSettings::RejectionStrategyA, "", 0, "Enable rejection of TPC clusters for compression(0=no, 1=strategy A, 2=strategy B)") AddOptionRTC(mergeLoopersAfterburner, uint8_t, 1, "", 0, "Run afterburner for additional looper merging") AddOptionRTC(compressionTypeMask, uint8_t, o2::gpu::GPUSettings::CompressionFull, "", 0, "TPC Compression mode bits(1=truncate charge/width LSB, 2=differences, 4=track-model)") AddOptionRTC(compressionSortOrder, uint8_t, o2::gpu::GPUSettings::SortTime, "", 0, "Sort order of TPC compression(0=time, 1=pad, 2=Z-time-pad, 3=Z-pad-time, 4=no sorting(use incoming order))") AddOptionRTC(sigBitsCharge, uint8_t, 4, "", 0, "Number of significant bits for TPC cluster charge in compression mode 1") AddOptionRTC(sigBitsWidth, uint8_t, 3, "", 0, "Number of significant bits for TPC cluster width in compression mode 1") AddOptionRTC(dropLoopers, uint8_t, 0, "", 0, "Drop looping tracks starting from second loop") AddOptionRTC(mergerInterpolateErrors, uint8_t, 1, "", 0, "Use interpolation instead of extrapolation for chi2 based cluster rejection") AddOptionRTC(mergerInterpolateRejectAlsoOnCurrentPosition, uint8_t, 1, "", 0, "When using mergerInterpolateErrors, reject based on chi2 twice computed with interpolated and current track position starting from NDF > mergerNonInterpolateRejectMinNDF Merge tracks accross the central electrode Enable PID response Add sub threshold clusters in TPC dEdx computation OR mask of TPC flags that will reject the cluster in alternative dEdx Reject edge clusters based on uncorrected track Y during track fit Increase decrease removal by when on this number of pads from the edge h configStandalone Reconstruction rec_trd Max chi2 for TRD tracklets to be matched to a track Chi2 cut for strict matching mode Number of sigmas for ITS TPC track time error estimate Addition to search road around track prolongation along Y in cm Optimal tracklet rphi resolution in maximum chi2 per attached tracklet for TRD tracks take into account the full likelihood of the slope including exponential tails Tracks with less attached tracklets are discarded after the tracking Post trigger Pile up integration time in BCs fits all iterations but the last one in projections Use material lookup table for TPC refit Apply workarounds to avoid cyclic merge should not be needed tpc dyn configStandalone Processing proc_rtc Replace constant variables static by constexpr expressions Compile RTC in deterministic with NO_FAST_MATH flags and GPUCA_DETERMINISTIC_MODE define Use RTC to optimize GPU code h configStandalone Processing proc_rtctech Use a file lock to serialize access to the cache folder Print launch bounds used for RTC code as debugging for exit after Allow RTC with slave GPUReconstruction instances with optConstexpr and optSpecialcode Maximum number of RTC cache files per backend in the cache the oldest are Prepend RTC compilation commands by this string Load a parameter object containing the launch bounds from a file h configStandalone Processing proc_param TPC Cluster Z Error Parameterization h nn
configStandalone Reconstruction rec_tpc multiplier for the combined cluster track error during track following area in cm for the search of for z only used if decrease removal by factor
configStandalone Reconstruction rec_tpc multiplier for the combined cluster track error during track following area in cm for the search of for z only used if decrease removal by when above this local occupancy rowx Shift of TPC revert cluster flag edge bit distance to edge exceeds this ZOffset for secondary multiple of radius max P of electron K BB bands crossing max P of electron p BB bands crossing max P of electron d BB bands crossing max P of electron t BB bands crossing min accepted dEdxMaxTPC of the track Additive extra cluster error for Y2 if edge flag set Additive extra cluster error for Y2 if single set Additive extra cluster error for Y2 if or single set Additive extra cluster error for Z2 if or single set Extra errors to add to track when crossing depending on addErrorsCECrossing Inner portion of y range in sector that is not used in searching for extrapolated track candidates factor2YS for track merging factor2K for track merging Margin in cm of Y position when rejecting edge clusters based on uncorrected track Y Max fraction of shared clusters for tracklet Except pad from cluster finding if total number of charges in a fragment is above this Except pad from cluster finding if number of consecutive charges in a fragment is above this Threshold where a timebin is considered disabling the noisy pad check for that pad Treat signal above this minimum as saturated Smoothing factor for the exponential Highly Ionising Particle tail filter Number of timebins to use for the averaging Add additional custom track errors when crossing relative as fraction of Do N fit passes in final fit of< 0:reject at max -n hits") AddOptionRTC(rejectIFCLowRadiusCluster, uint8_t, 1, "", 0, "Reject clusters that get the IFC mask error during refit") AddOptionRTC(dEdxTruncLow, uint8_t, 2, "", 0, "Low truncation threshold, fraction of 128") AddOptionRTC(dEdxTruncHigh, uint8_t, 77, "", 0, "High truncation threshold, fraction of 128") AddOptionRTC(extrapolationTracking, int8_t, 1, "", 0, "Enable Extrapolation Tracking(prolong tracks to adjacent sectors to find short segments)") AddOptionRTC(disableRefitAttachment, uint8_t, 0, "", 0, "Bitmask to disable certain attachment steps during refit(1:attachment, 2:propagation, 4:loop following, 8:mirroring)") AddOptionRTC(rejectionStrategy, uint8_t, o2::gpu::GPUSettings::RejectionStrategyA, "", 0, "Enable rejection of TPC clusters for compression(0=no, 1=strategy A, 2=strategy B)") AddOptionRTC(mergeLoopersAfterburner, uint8_t, 1, "", 0, "Run afterburner for additional looper merging") AddOptionRTC(compressionTypeMask, uint8_t, o2::gpu::GPUSettings::CompressionFull, "", 0, "TPC Compression mode bits(1=truncate charge/width LSB, 2=differences, 4=track-model)") AddOptionRTC(compressionSortOrder, uint8_t, o2::gpu::GPUSettings::SortTime, "", 0, "Sort order of TPC compression(0=time, 1=pad, 2=Z-time-pad, 3=Z-pad-time, 4=no sorting(use incoming order))") AddOptionRTC(sigBitsCharge, uint8_t, 4, "", 0, "Number of significant bits for TPC cluster charge in compression mode 1") AddOptionRTC(sigBitsWidth, uint8_t, 3, "", 0, "Number of significant bits for TPC cluster width in compression mode 1") AddOptionRTC(dropLoopers, uint8_t, 0, "", 0, "Drop looping tracks starting from second loop") AddOptionRTC(mergerInterpolateErrors, uint8_t, 1, "", 0, "Use interpolation instead of extrapolation for chi2 based cluster rejection") AddOptionRTC(mergerInterpolateRejectAlsoOnCurrentPosition, uint8_t, 1, "", 0, "When using mergerInterpolateErrors, reject based on chi2 twice computed with interpolated and current track position starting from NDF > mergerNonInterpolateRejectMinNDF Merge tracks accross the central electrode Enable PID response Add sub threshold clusters in TPC dEdx computation OR mask of TPC flags that will reject the cluster in alternative dEdx Reject edge clusters based on uncorrected track Y during track fit Increase decrease removal by when on this number of pads from the edge h configStandalone Reconstruction rec_trd Max chi2 for TRD tracklets to be matched to a track Chi2 cut for strict matching mode Number of sigmas for ITS TPC track time error estimate Addition to search road around track prolongation along Y in cm Optimal tracklet rphi resolution in maximum chi2 per attached tracklet for TRD tracks take into account the full likelihood of the slope including exponential tails Tracks with less attached tracklets are discarded after the tracking Post trigger Pile up integration time in BCs fits all iterations but the last one in projections Use material lookup table for TPC refit Apply workarounds to avoid cyclic merge should not be needed tpc dyn configStandalone Processing proc_rtc Replace constant variables static by constexpr expressions Compile RTC in deterministic with NO_FAST_MATH flags and GPUCA_DETERMINISTIC_MODE define Use RTC to optimize GPU code h configStandalone Processing proc_rtctech Use a file lock to serialize access to the cache folder Print launch bounds used for RTC code as debugging for exit after Allow RTC with slave GPUReconstruction instances with optConstexpr and optSpecialcode Maximum number of RTC cache files per backend in the cache the oldest are Prepend RTC compilation commands by this string Load a parameter object containing the launch bounds from a file h configStandalone Processing proc_param TPC Cluster Z Error Parameterization h configStandalone Processing settings for neural network proc_nn std::string Specify inference device(cpu(default), rocm, cuda)") AddOption(nnInferenceDeviceId
configStandalone Reconstruction rec_tpc float
HMM_INLINE hmm_mat4 HMM_Orthographic(float Left, float Right, float Bottom, float Top, float Near, float Far)
uint32_t j
Definition RawData.h:0
uint32_t c
Definition RawData.h:2
Class for time synchronization of RawReader instances.
std::vector< vk::CommandBuffer > mCommandBuffersMix
std::vector< vk::CommandBuffer > mCommandBuffers
std::vector< vk::Semaphore > mPresentSemaphore
std::vector< vk::Image > mRenderTargetImage
std::vector< vk::Pipeline > mPipelines
void resizeScene(uint32_t width, uint32_t height) override
void submitSingleTimeCommandBuffer(vk::CommandBuffer commandBuffer)
std::vector< VulkanImage > mDownsampleImages
void writeToBuffer(VulkanBuffer &buffer, size_t size, const void *srcData)
std::vector< vk::ImageView > mSwapChainImageViews
std::vector< vk::CommandBufferSubmitInfo > mFrameCommandBuffers
void pointSizeFactor(float factor) override
void GLDrawQuad(const float(&corners)[4][2], const float *color) override
std::vector< FontSymbolVulkan > mFontSymbols
std::vector< vk::ImageView * > mRenderTargetView
bool prepareDraw(const hmm_mat4 &proj, const hmm_mat4 &view, bool requestScreenshot, bool toMixBuffer, float includeMixImage) override
void addFontSymbol(int32_t symbol, int32_t sizex, int32_t sizey, int32_t offsetx, int32_t offsety, int32_t advance, void *data) override
void addTextDrawCommand(size_t firstVertex, const float *color)
void mixImages(vk::CommandBuffer cmdBuffer, float mixSlaveImage)
void recreateRendering(bool forScreenshot=false, bool forMixing=false)
std::vector< VulkanBuffer > mFontVertexBuffer
double checkDevice(vk::PhysicalDevice device, const std::vector< const char * > &reqDeviceExtensions, const FeatureChain &reqDeviceFeatures, bool silent=false)
void endFillCommandBuffer(vk::CommandBuffer &commandBuffer)
uint32_t drawVertices(const vboList &v, const drawType t) override
std::vector< vk::CommandBuffer > mCommandBuffersPresent
std::vector< vk::CommandBuffer > mCommandBuffersDownsample
void ActivateColor(std::array< float, 4 > &color) override
uint64_t queueSubmit(uint64_t *timelineSignalValue, Args &&... args)
std::vector< VulkanBuffer > mUniformBuffersMat[3]
void updateSwapChainDetails(const vk::PhysicalDevice &device)
void handleSwapChainResult(vk::Result retVal, uint8_t suboptimalBit)
vk::StructureChain< vk::PhysicalDeviceFeatures2, vk::PhysicalDeviceVulkan11Features, vk::PhysicalDeviceVulkan12Features, vk::PhysicalDeviceVulkan13Features, vk::PhysicalDeviceVulkan14Features, vk::PhysicalDeviceSwapchainMaintenance1FeaturesKHR, vk::PhysicalDevicePresentIdFeaturesKHR, vk::PhysicalDevicePresentWaitFeaturesKHR > FeatureChain
void finishDraw(bool doScreenshot, bool toMixBuffer, float includeMixImage) override
void writeToImage(VulkanImage &image, const void *srcData, size_t srcSize)
std::unordered_map< std::string, vk::ShaderModuleCreateInfo > mShaders
vk::DescriptorSetLayout mUniformDescriptorTexture
void downsampleToFramebuffer(vk::CommandBuffer &commandBuffer)
void createSwapChain(vk::SwapchainKHR oldSwapChain={})
vk::Extent2D chooseSwapExtent(const vk::SurfaceCapabilitiesKHR &capabilities)
VulkanImage createImage(uint32_t sizex, uint32_t sizey, const void *srcData=nullptr, size_t srcSize=0, vk::Format format=vk::Format::eR8G8B8A8Srgb)
std::vector< TextDrawCommand > mTextDrawCommands
void cmdPushDescriptors(vk::CommandBuffer commandBuffer, vk::PipelineLayout layout, const VulkanBuffer &ubo, vk::ImageView textureView={})
void finishFrame(bool doScreenshot, bool toMixBuffer, float includeMixImage) override
void clearSwapChain(bool keepSwapChain=false)
std::vector< vk::Semaphore > mImageAvailableSemaphore
void startFillCommandBuffer(vk::CommandBuffer &commandBuffer, uint32_t imageIndex, bool toMixBuffer=false)
std::vector< vk::CommandBuffer > mCommandBuffersTexture
vk::DebugUtilsMessengerEXT mDebugMessenger
void GLPrintText(const char *s, float x, float y, float *color, float scale, uint32_t nCharacters) override
void cmdDownsample(vk::CommandBuffer commandBuffer, vk::ImageView src, vk::ImageView dst, uint32_t width, uint32_t height, int32_t factor)
VulkanBuffer createBuffer(size_t size, const void *srcData=nullptr, vk::BufferUsageFlags type=vk::BufferUsageFlagBits::eVertexBuffer, int32_t deviceMemory=1)
void createOffscreenBuffers(bool forScreenshot=false, bool forMixing=false)
void lineWidthFactor(float factor) override
void readImageToPixels(vk::Image image, vk::ImageView view, vk::ImageLayout layout, std::vector< char > &pixels)
std::vector< vk::CommandBuffer > mCommandBuffersText
void loadDataToGPU(size_t totalVertizes) override
static constexpr int32_t SOLID_GLYPH
vecpod< DrawArraysIndirectCommand > mCmdBuffer
std::vector< int32_t > mIndirectSectorOffset
static constexpr float SMOOTH_LINE_EXTRA_WIDTH
std::vector< char > mScreenshotPixels
static constexpr float SMOOTH_POINT_EXTRA_SIZE
float getDownsampleFactor(bool screenshot=false)
std::tuple< uint32_t, uint32_t, int32_t > vboList
virtual uint32_t getReqVulkanExtensions(const char **&p)
virtual void getSize(int32_t &width, int32_t &height)
virtual int32_t getVulkanSurface(void *instance, void *surface)
const GPUSettingsDisplayLight & cfgL() const
Definition GPUDisplay.h:73
const GPUParam * param()
Definition GPUDisplay.h:87
int32_t updateRenderPipeline() const
Definition GPUDisplay.h:78
const GPUSettingsDisplayRenderer & cfgR() const
Definition GPUDisplay.h:72
vecpod< vtx > * vertexBuffer()
Definition GPUDisplay.h:86
int32_t updateDrawCommands() const
Definition GPUDisplay.h:77
GPUDisplayFrontend * frontend()
Definition GPUDisplay.h:89
const vecpod< uint32_t > * vertexBufferCount() const
Definition GPUDisplay.h:81
const GPUSettingsDisplay & cfg() const
Definition GPUDisplay.h:75
vecpod< int32_t > * vertexBufferStart()
Definition GPUDisplay.h:80
const GPUSettingsProcessing & GetProcessingSettings() const
Definition GPUDisplay.h:88
GLeglImageOES image
Definition glcorearb.h:4021
GLint GLenum GLint x
Definition glcorearb.h:403
GLenum mode
Definition glcorearb.h:266
GLenum src
Definition glcorearb.h:1767
GLint GLsizei count
Definition glcorearb.h:399
GLuint buffer
Definition glcorearb.h:655
GLsizeiptr size
Definition glcorearb.h:659
GLuint color
Definition glcorearb.h:1272
GLuint GLsizei const GLuint const GLintptr * offsets
Definition glcorearb.h:2595
const GLdouble * v
Definition glcorearb.h:832
GLsizei GLenum GLenum * types
Definition glcorearb.h:2516
GLint GLsizei GLsizei height
Definition glcorearb.h:270
GLint first
Definition glcorearb.h:399
GLint GLsizei width
Definition glcorearb.h:270
GLdouble f
Definition glcorearb.h:310
GLint y
Definition glcorearb.h:270
GLsizei const GLfloat * value
Definition glcorearb.h:819
GLint GLint GLsizei GLint GLenum GLenum type
Definition glcorearb.h:275
GLenum GLenum dst
Definition glcorearb.h:1767
typedef void(APIENTRYP PFNGLCULLFACEPROC)(GLenum mode)
GLint GLint GLsizei GLint GLenum GLenum const void * pixels
Definition glcorearb.h:275
GLuint GLfloat * val
Definition glcorearb.h:1582
GLint GLint GLsizei GLsizei GLsizei depth
Definition glcorearb.h:470
GLboolean GLboolean GLboolean GLboolean a
Definition glcorearb.h:1233
GLubyte GLubyte GLubyte GLubyte w
Definition glcorearb.h:852
GLint GLint GLsizei GLint GLenum format
Definition glcorearb.h:275
GLsizeiptr const void GLenum usage
Definition glcorearb.h:659
std::vector< T, fair::mq::pmr::polymorphic_allocator< T > > vector