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
19#include "GPUCommonDef.h"
21#include "GPUDisplay.h"
22
23#include <mutex>
24
25using namespace o2::gpu;
26
28QGET_LD_BINARY_SYMBOLS(shaders_shaders_vertex_vert_spv);
29QGET_LD_BINARY_SYMBOLS(shaders_shaders_fragment_frag_spv);
30QGET_LD_BINARY_SYMBOLS(shaders_shaders_vertexPoint_vert_spv);
31QGET_LD_BINARY_SYMBOLS(shaders_shaders_vertexTexture_vert_spv);
32QGET_LD_BINARY_SYMBOLS(shaders_shaders_fragmentTexture_frag_spv);
33QGET_LD_BINARY_SYMBOLS(shaders_shaders_fragmentText_frag_spv);
34
35// #define CHKERR(cmd) {cmd;}
36#define CHKERR(cmd) \
37 do { \
38 auto tmp_internal_retVal = cmd; \
39 if ((int32_t)tmp_internal_retVal < 0) { \
40 GPUError("VULKAN ERROR: %d: %s (%s: %d)", (int32_t)tmp_internal_retVal, "ERROR", __FILE__, __LINE__); \
41 throw std::runtime_error("Vulkan Failure"); \
42 } \
43 } while (false)
44
51
52// ---------------------------- VULKAN HELPERS ----------------------------
53
54static int32_t checkVulkanLayersSupported(const std::vector<const char*>& validationLayers)
55{
56 std::vector<vk::LayerProperties> availableLayers = vk::enumerateInstanceLayerProperties();
57 for (const char* layerName : validationLayers) {
58 bool layerFound = false;
59
60 for (const auto& layerProperties : availableLayers) {
61 if (strcmp(layerName, layerProperties.layerName) == 0) {
62 layerFound = true;
63 break;
64 }
65 }
66
67 if (!layerFound) {
68 return 1;
69 }
70 }
71 return 0;
72}
73
74static uint32_t findMemoryType(uint32_t typeFilter, vk::MemoryPropertyFlags properties, vk::PhysicalDevice physDev)
75{
76 vk::PhysicalDeviceMemoryProperties memProperties = physDev.getMemoryProperties();
77
78 for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++) {
79 if ((typeFilter & (1 << i)) && (memProperties.memoryTypes[i].propertyFlags & properties) == properties) {
80 return i;
81 }
82 }
83
84 throw std::runtime_error("failed to find suitable memory type!");
85}
86
87static vk::SurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<vk::SurfaceFormatKHR>& availableFormats)
88{
89 for (const auto& availableFormat : availableFormats) {
90 if (availableFormat.format == vk::Format::eB8G8R8A8Unorm && availableFormat.colorSpace == vk::ColorSpaceKHR::eSrgbNonlinear) {
91 return availableFormat;
92 }
93 }
94 return availableFormats[0];
95}
96
97static vk::PresentModeKHR chooseSwapPresentMode(const std::vector<vk::PresentModeKHR>& availablePresentModes, vk::PresentModeKHR desiredMode = vk::PresentModeKHR::eMailbox)
98{
99 for (const auto& availablePresentMode : availablePresentModes) {
100 if (availablePresentMode == desiredMode) {
101 return availablePresentMode;
102 }
103 }
104 static bool errorShown = false;
105 if (!errorShown) {
106 errorShown = true;
107 GPUError("VULKAN ERROR: Desired present mode not available, using FIFO mode");
108 }
109 return vk::PresentModeKHR::eFifo;
110}
111
112vk::Extent2D GPUDisplayBackendVulkan::chooseSwapExtent(const vk::SurfaceCapabilitiesKHR& capabilities)
113{
114 if (capabilities.currentExtent.width != std::numeric_limits<uint32_t>::max()) {
115 return capabilities.currentExtent;
116 } else {
117 int32_t width, height;
119 vk::Extent2D actualExtent = {(uint32_t)width, (uint32_t)height};
120 actualExtent.width = std::clamp(actualExtent.width, capabilities.minImageExtent.width, capabilities.maxImageExtent.width);
121 actualExtent.height = std::clamp(actualExtent.height, capabilities.minImageExtent.height, capabilities.maxImageExtent.height);
122 return actualExtent;
123 }
124}
125
126static vk::ShaderModule createShaderModule(const char* code, size_t size, vk::Device device)
127{
128 vk::ShaderModuleCreateInfo createInfo{};
129 createInfo.codeSize = size;
130 createInfo.pCode = reinterpret_cast<const uint32_t*>(code);
131 return device.createShaderModule(createInfo, nullptr);
132}
133
134static void cmdImageMemoryBarrier(vk::CommandBuffer cmdbuffer, vk::Image image, vk::AccessFlags srcAccessMask, vk::AccessFlags dstAccessMask, vk::ImageLayout oldLayout, vk::ImageLayout newLayout, vk::PipelineStageFlags srcStageMask, vk::PipelineStageFlags dstStageMask)
135{
136 vk::ImageSubresourceRange range{vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1};
137 vk::ImageMemoryBarrier barrier{};
138 barrier.srcAccessMask = srcAccessMask;
139 barrier.dstAccessMask = dstAccessMask;
140 barrier.oldLayout = oldLayout;
141 barrier.newLayout = newLayout;
142 barrier.image = image;
143 barrier.subresourceRange = range;
144 cmdbuffer.pipelineBarrier(srcStageMask, dstStageMask, {}, 0, nullptr, 0, nullptr, 1, &barrier);
145}
146
147void GPUDisplayBackendVulkan::updateSwapChainDetails(const vk::PhysicalDevice& device)
148{
149 mSwapChainDetails.capabilities = device.getSurfaceCapabilitiesKHR(mSurface);
150 mSwapChainDetails.formats = device.getSurfaceFormatsKHR(mSurface);
151 mSwapChainDetails.presentModes = device.getSurfacePresentModesKHR(mSurface);
152}
153
155{
156 vk::CommandBufferAllocateInfo allocInfo{};
157 allocInfo.level = vk::CommandBufferLevel::ePrimary;
158 allocInfo.commandPool = mCommandPool;
159 allocInfo.commandBufferCount = 1;
160 vk::CommandBuffer commandBuffer = mDevice.allocateCommandBuffers(allocInfo)[0];
161 vk::CommandBufferBeginInfo beginInfo{};
162 beginInfo.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit;
163 commandBuffer.begin(beginInfo);
164 return commandBuffer;
165}
166
168{
169 commandBuffer.end();
170 vk::SubmitInfo submitInfo{};
171 submitInfo.commandBufferCount = 1;
172 submitInfo.pCommandBuffers = &commandBuffer;
173 static std::mutex fenceMutex;
174 {
175 std::lock_guard<std::mutex> guard(fenceMutex);
176 CHKERR(mGraphicsQueue.submit(1, &submitInfo, mSingleCommitFence));
177 CHKERR(mDevice.waitForFences(1, &mSingleCommitFence, true, UINT64_MAX));
178 CHKERR(mDevice.resetFences(1, &mSingleCommitFence));
179 }
180 mDevice.freeCommandBuffers(mCommandPool, 1, &commandBuffer);
181}
182
183static vk::ImageView createImageViewI(vk::Device device, vk::Image image, vk::Format format, vk::ImageAspectFlags aspectFlags = vk::ImageAspectFlagBits::eColor, uint32_t mipLevels = 1)
184{
185 vk::ImageViewCreateInfo viewInfo{};
186 viewInfo.image = image;
187 viewInfo.viewType = vk::ImageViewType::e2D;
188 viewInfo.format = format;
189 viewInfo.subresourceRange.aspectMask = aspectFlags;
190 viewInfo.subresourceRange.baseMipLevel = 0;
191 viewInfo.subresourceRange.levelCount = mipLevels;
192 viewInfo.subresourceRange.baseArrayLayer = 0;
193 viewInfo.subresourceRange.layerCount = 1;
194 return device.createImageView(viewInfo, nullptr);
195}
196
197static 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)
198{
199 vk::ImageCreateInfo imageInfo{};
200 imageInfo.imageType = vk::ImageType::e2D;
201 imageInfo.extent.width = width;
202 imageInfo.extent.height = height;
203 imageInfo.extent.depth = 1;
204 imageInfo.mipLevels = mipLevels;
205 imageInfo.arrayLayers = 1;
206 imageInfo.format = format;
207 imageInfo.tiling = tiling;
208 imageInfo.initialLayout = layout;
209 imageInfo.usage = usage;
210 imageInfo.samples = numSamples;
211 imageInfo.sharingMode = vk::SharingMode::eExclusive;
212 image = device.createImage(imageInfo);
213
214 vk::MemoryRequirements memRequirements;
215 memRequirements = device.getImageMemoryRequirements(image);
216
217 vk::MemoryAllocateInfo allocInfo{};
218 allocInfo.allocationSize = memRequirements.size;
219 allocInfo.memoryTypeIndex = findMemoryType(memRequirements.memoryTypeBits, properties, physicalDevice);
220 imageMemory = device.allocateMemory(allocInfo, nullptr);
221
222 device.bindImageMemory(image, imageMemory, 0);
223}
224
225static uint32_t getMaxUsableSampleCount(vk::PhysicalDeviceProperties& physicalDeviceProperties)
226{
227 vk::SampleCountFlags counts = physicalDeviceProperties.limits.framebufferColorSampleCounts & physicalDeviceProperties.limits.framebufferDepthSampleCounts;
228 if (counts & vk::SampleCountFlagBits::e64) {
229 return 64;
230 } else if (counts & vk::SampleCountFlagBits::e32) {
231 return 32;
232 } else if (counts & vk::SampleCountFlagBits::e16) {
233 return 16;
234 } else if (counts & vk::SampleCountFlagBits::e8) {
235 return 8;
236 } else if (counts & vk::SampleCountFlagBits::e4) {
237 return 4;
238 } else if (counts & vk::SampleCountFlagBits::e2) {
239 return 2;
240 }
241 return 1;
242}
243
244static vk::SampleCountFlagBits getMSAASamplesFlag(uint32_t msaa)
245{
246 if (msaa == 2) {
247 return vk::SampleCountFlagBits::e2;
248 } else if (msaa == 4) {
249 return vk::SampleCountFlagBits::e4;
250 } else if (msaa == 8) {
251 return vk::SampleCountFlagBits::e8;
252 } else if (msaa == 16) {
253 return vk::SampleCountFlagBits::e16;
254 } else if (msaa == 32) {
255 return vk::SampleCountFlagBits::e32;
256 } else if (msaa == 64) {
257 return vk::SampleCountFlagBits::e64;
258 }
259 return vk::SampleCountFlagBits::e1;
260}
261
262template <class T, class S>
263static inline void clearVector(T& v, S func, bool downsize = true)
264{
265 std::for_each(v.begin(), v.end(), func);
266 if (downsize) {
267 v.clear();
268 }
269}
270
271// ---------------------------- VULKAN DEVICE MANAGEMENT ----------------------------
272
273double GPUDisplayBackendVulkan::checkDevice(vk::PhysicalDevice device, const std::vector<const char*>& reqDeviceExtensions)
274{
275 double score = -1.;
276 vk::PhysicalDeviceProperties deviceProperties = device.getProperties();
277 vk::PhysicalDeviceFeatures deviceFeatures = device.getFeatures();
278 vk::PhysicalDeviceMemoryProperties memoryProperties = device.getMemoryProperties();
279 if (!deviceFeatures.geometryShader || !deviceFeatures.wideLines || !deviceFeatures.largePoints) {
280 return (-1);
281 }
282
283 std::vector<vk::QueueFamilyProperties> queueFamilies = device.getQueueFamilyProperties();
284 bool found = false;
285 for (uint32_t i = 0; i < queueFamilies.size(); i++) {
286 if (!(queueFamilies[i].queueFlags & vk::QueueFlagBits::eGraphics)) {
287 return (-1);
288 }
289 vk::Bool32 presentSupport = device.getSurfaceSupportKHR(i, mSurface);
290 if (!presentSupport) {
291 return (-1);
292 }
294 found = true;
295 break;
296 }
297 if (!found) {
298 GPUInfo("%s ignored due to missing queue properties", &deviceProperties.deviceName[0]);
299 return (-1);
300 }
301
302 std::vector<vk::ExtensionProperties> availableExtensions = device.enumerateDeviceExtensionProperties(nullptr);
303 uint32_t extensionsFound = 0;
304 for (uint32_t i = 0; i < reqDeviceExtensions.size(); i++) {
305 for (uint32_t j = 0; j < availableExtensions.size(); j++) {
306 if (strcmp(reqDeviceExtensions[i], availableExtensions[j].extensionName) == 0) {
307 extensionsFound++;
308 break;
309 }
310 }
311 }
312 if (extensionsFound < reqDeviceExtensions.size()) {
313 GPUInfo("%s ignored due to missing extensions", &deviceProperties.deviceName[0]);
314 return (-1);
315 }
316
319 GPUInfo("%s ignored due to incompatible swap chain", &deviceProperties.deviceName[0]);
320 return (-1);
321 }
322
323 score = 1;
324 if (deviceProperties.deviceType == vk::PhysicalDeviceType::eDiscreteGpu) {
325 score += 1e12;
326 } else if (deviceProperties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu) {
327 score += 1e11;
328 }
329
330 for (uint32_t i = 0; i < memoryProperties.memoryHeapCount; i++) {
331 if (memoryProperties.memoryHeaps[i].flags & vk::MemoryHeapFlagBits::eDeviceLocal) {
332 score += memoryProperties.memoryHeaps[i].size;
333 }
334 }
335
336 return score;
337}
338
340{
341 VULKAN_HPP_DEFAULT_DISPATCHER.init();
342 vk::ApplicationInfo appInfo{};
343 appInfo.pApplicationName = "GPU CA Standalone display";
344 appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
345 appInfo.pEngineName = "GPU CI Standalone Engine";
346 appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
347 appInfo.apiVersion = VK_API_VERSION_1_0;
348
349 vk::InstanceCreateInfo instanceCreateInfo;
350 instanceCreateInfo.pApplicationInfo = &appInfo;
351
352 const char** frontendExtensions;
353 uint32_t frontendExtensionCount = mDisplay->frontend()->getReqVulkanExtensions(frontendExtensions);
354 std::vector<const char*> reqInstanceExtensions(frontendExtensions, frontendExtensions + frontendExtensionCount);
355
356 const std::vector<const char*> reqValidationLayers = {
357 "VK_LAYER_KHRONOS_validation"};
358 auto debugCallback = [](vk::DebugUtilsMessageSeverityFlagBitsEXT messageSeverity, vk::DebugUtilsMessageTypeFlagsEXT messageType, const vk::DebugUtilsMessengerCallbackDataEXT* pCallbackData, void* pUserData) -> VkBool32 {
359 static int32_t throwOnError = getenv("GPUCA_VULKAN_VALIDATION_THROW") ? atoi(getenv("GPUCA_VULKAN_VALIDATION_THROW")) : 0;
360 static bool showVulkanValidationInfo = getenv("GPUCA_VULKAN_VALIDATION_INFO") && atoi(getenv("GPUCA_VULKAN_VALIDATION_INFO"));
361 switch (messageSeverity) {
362 case vk::DebugUtilsMessageSeverityFlagBitsEXT::eVerbose:
363 if (showVulkanValidationInfo) {
364 GPUInfo("%s", pCallbackData->pMessage);
365 }
366 break;
367 case vk::DebugUtilsMessageSeverityFlagBitsEXT::eWarning:
368 GPUWarning("%s", pCallbackData->pMessage);
369 if (throwOnError > 1) {
370 throw std::logic_error("break_on_validation_warning");
371 }
372 break;
373 case vk::DebugUtilsMessageSeverityFlagBitsEXT::eError:
374 GPUError("%s", pCallbackData->pMessage);
375 if (throwOnError) {
376 throw std::logic_error("break_on_validation_error");
377 }
378 break;
379 case vk::DebugUtilsMessageSeverityFlagBitsEXT::eInfo:
380 default:
381 GPUInfo("%s", pCallbackData->pMessage);
382 break;
383 }
384 return false;
385 };
386 vk::DebugUtilsMessengerCreateInfoEXT debugCreateInfo{};
388 if (checkVulkanLayersSupported(reqValidationLayers)) {
389 throw std::runtime_error("Requested validation layer support not available");
390 }
391 reqInstanceExtensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
392 instanceCreateInfo.enabledLayerCount = static_cast<uint32_t>(reqValidationLayers.size());
393 instanceCreateInfo.ppEnabledLayerNames = reqValidationLayers.data();
394 instanceCreateInfo.pNext = (VkDebugUtilsMessengerCreateInfoEXT*)&debugCreateInfo;
395
396 debugCreateInfo.messageSeverity = vk::DebugUtilsMessageSeverityFlagBitsEXT::eVerbose | vk::DebugUtilsMessageSeverityFlagBitsEXT::eWarning | vk::DebugUtilsMessageSeverityFlagBitsEXT::eError;
397 debugCreateInfo.messageType = vk::DebugUtilsMessageTypeFlagBitsEXT::eGeneral | vk::DebugUtilsMessageTypeFlagBitsEXT::eValidation | vk::DebugUtilsMessageTypeFlagBitsEXT::ePerformance;
398 debugCreateInfo.pfnUserCallback = debugCallback;
399 debugCreateInfo.pUserData = nullptr;
400 } else {
401 instanceCreateInfo.enabledLayerCount = 0;
402 }
403
404 instanceCreateInfo.enabledExtensionCount = static_cast<uint32_t>(reqInstanceExtensions.size());
405 instanceCreateInfo.ppEnabledExtensionNames = reqInstanceExtensions.data();
406
407 mInstance = vk::createInstance(instanceCreateInfo, nullptr);
408 VULKAN_HPP_DEFAULT_DISPATCHER.init(mInstance);
409
411 GPUInfo("Enabling Vulkan Validation Layers");
412 mDebugMessenger = mInstance.createDebugUtilsMessengerEXT(debugCreateInfo, nullptr);
413 }
414 std::vector<vk::ExtensionProperties> extensions = vk::enumerateInstanceExtensionProperties(nullptr);
415 if (mDisplay->param()->par.debugLevel >= 3) {
416 std::cout << "available instance extensions: " << extensions.size() << "\n";
417 for (const auto& extension : extensions) {
418 std::cout << '\t' << extension.extensionName << '\n';
419 }
420 }
421
423 throw std::runtime_error("Frontend does not provide Vulkan surface");
424 }
425
426 const std::vector<const char*> reqDeviceExtensions = {
427 VK_KHR_SWAPCHAIN_EXTENSION_NAME};
428
429 mPhysicalDevice = VkPhysicalDevice(VK_NULL_HANDLE);
430 std::vector<vk::PhysicalDevice> devices = mInstance.enumeratePhysicalDevices();
431 if (devices.size() == 0) {
432 throw std::runtime_error("No Vulkan device present!");
433 }
434 double bestScore = -1.;
435 for (uint32_t i = 0; i < devices.size(); i++) {
436 double score = checkDevice(devices[i], reqDeviceExtensions);
437 if (mDisplay->param()->par.debugLevel >= 2) {
438 vk::PhysicalDeviceProperties deviceProperties = devices[i].getProperties();
439 GPUInfo("Available Vulkan device %d: %s - Score %f", i, &deviceProperties.deviceName[0], score);
440 }
441 if (score > bestScore && score > 0) {
442 mPhysicalDevice = devices[i];
443 bestScore = score;
444 }
445 }
446 if (mDisplay->cfg().vulkan.forceDevice != -1) {
447 if (mDisplay->cfg().vulkan.forceDevice < 0 || mDisplay->cfg().vulkan.forceDevice >= (int32_t)devices.size()) {
448 throw std::runtime_error("Invalid Vulkan device selected");
449 }
450 mPhysicalDevice = devices[mDisplay->cfg().vulkan.forceDevice];
451 }
452 if (!mPhysicalDevice) {
453 throw std::runtime_error("All available Vulkan devices unsuited");
454 }
455
457 vk::PhysicalDeviceProperties deviceProperties = mPhysicalDevice.getProperties();
458 vk::PhysicalDeviceFeatures deviceFeatures = mPhysicalDevice.getFeatures();
459 vk::FormatProperties depth32FormatProperties = mPhysicalDevice.getFormatProperties(vk::Format::eD32Sfloat);
460 vk::FormatProperties depth64FormatProperties = mPhysicalDevice.getFormatProperties(vk::Format::eD32SfloatS8Uint);
461 vk::FormatProperties formatProperties = mPhysicalDevice.getFormatProperties(mSurfaceFormat.format);
462 GPUInfo("Using physical Vulkan device %s", &deviceProperties.deviceName[0]);
463 mMaxMSAAsupported = getMaxUsableSampleCount(deviceProperties);
464 mZSupported = (bool)(depth32FormatProperties.optimalTilingFeatures & vk::FormatFeatureFlagBits::eDepthStencilAttachment);
465 mStencilSupported = (bool)(depth64FormatProperties.optimalTilingFeatures & vk::FormatFeatureFlagBits::eDepthStencilAttachment);
466 mCubicFilterSupported = (bool)(formatProperties.optimalTilingFeatures & vk::FormatFeatureFlagBits::eSampledImageFilterCubicEXT);
467 bool mailboxSupported = std::find(mSwapChainDetails.presentModes.begin(), mSwapChainDetails.presentModes.end(), vk::PresentModeKHR::eMailbox) != mSwapChainDetails.presentModes.end();
468 if (mDisplay->param()->par.debugLevel >= 2) {
469 GPUInfo("Max MSAA: %d, 32 bit Z buffer %d, 32 bit Z buffer + stencil buffer %d, Cubic Filtering %d, Mailbox present mode %d\n", (int32_t)mMaxMSAAsupported, (int32_t)mZSupported, (int32_t)mStencilSupported, (int32_t)mCubicFilterSupported, (int32_t)mailboxSupported);
470 }
471
472 vk::DeviceQueueCreateInfo queueCreateInfo{};
473 queueCreateInfo.queueFamilyIndex = mGraphicsFamily;
474 queueCreateInfo.queueCount = 1;
475 float queuePriority = 1.0f;
476 queueCreateInfo.pQueuePriorities = &queuePriority;
477 vk::DeviceCreateInfo deviceCreateInfo{};
478 deviceCreateInfo.pQueueCreateInfos = &queueCreateInfo;
479 deviceCreateInfo.queueCreateInfoCount = 1;
480 deviceCreateInfo.pEnabledFeatures = &deviceFeatures;
481 deviceCreateInfo.enabledExtensionCount = static_cast<uint32_t>(reqDeviceExtensions.size());
482 deviceCreateInfo.ppEnabledExtensionNames = reqDeviceExtensions.data();
483 deviceCreateInfo.enabledLayerCount = instanceCreateInfo.enabledLayerCount;
484 deviceCreateInfo.ppEnabledLayerNames = instanceCreateInfo.ppEnabledLayerNames;
485 mDevice = mPhysicalDevice.createDevice(deviceCreateInfo, nullptr);
486 VULKAN_HPP_DEFAULT_DISPATCHER.init(mDevice);
488
489 vk::CommandPoolCreateInfo poolInfo{};
490 poolInfo.flags = vk::CommandPoolCreateFlagBits::eResetCommandBuffer;
491 poolInfo.queueFamilyIndex = mGraphicsFamily;
492 mCommandPool = mDevice.createCommandPool(poolInfo, nullptr);
493}
494
496{
497 mDevice.destroyCommandPool(mCommandPool, nullptr);
498 mDevice.destroy(nullptr);
499 mInstance.destroySurfaceKHR(mSurface, nullptr);
501 mInstance.destroyDebugUtilsMessengerEXT(mDebugMessenger, nullptr);
502 }
503}
504
505// ---------------------------- VULKAN COMMAND BUFFERS ----------------------------
506
508{
509 vk::CommandBufferAllocateInfo allocInfo{};
510 allocInfo.commandPool = mCommandPool;
511 allocInfo.level = vk::CommandBufferLevel::ePrimary;
512 allocInfo.commandBufferCount = mFramesInFlight;
514 mCommandBuffers = mDevice.allocateCommandBuffers(allocInfo);
515 mCommandBuffersText = mDevice.allocateCommandBuffers(allocInfo);
516 mCommandBuffersTexture = mDevice.allocateCommandBuffers(allocInfo);
517 mCommandBuffersDownsample = mDevice.allocateCommandBuffers(allocInfo);
518 mCommandBuffersMix = mDevice.allocateCommandBuffers(allocInfo);
519}
520
522{
523 mDevice.freeCommandBuffers(mCommandPool, mCommandBuffers.size(), mCommandBuffers.data());
524 mDevice.freeCommandBuffers(mCommandPool, mCommandBuffersText.size(), mCommandBuffersText.data());
525 mDevice.freeCommandBuffers(mCommandPool, mCommandBuffersTexture.size(), mCommandBuffersTexture.data());
527 mDevice.freeCommandBuffers(mCommandPool, mCommandBuffersMix.size(), mCommandBuffersMix.data());
528}
529
530// ---------------------------- VULKAN SEMAPHORES AND FENCES ----------------------------
531
533{
534 vk::SemaphoreCreateInfo semaphoreInfo{};
535 vk::FenceCreateInfo fenceInfo{};
536 fenceInfo.flags = vk::FenceCreateFlagBits::eSignaled;
543 for (uint32_t i = 0; i < mFramesInFlight; i++) {
544 mImageAvailableSemaphore[i] = mDevice.createSemaphore(semaphoreInfo, nullptr);
545 mRenderFinishedSemaphore[i] = mDevice.createSemaphore(semaphoreInfo, nullptr);
546 mTextFinishedSemaphore[i] = mDevice.createSemaphore(semaphoreInfo, nullptr);
547 mMixFinishedSemaphore[i] = mDevice.createSemaphore(semaphoreInfo, nullptr);
548 mDownsampleFinishedSemaphore[i] = mDevice.createSemaphore(semaphoreInfo, nullptr);
549 mInFlightFence[i] = mDevice.createFence(fenceInfo, nullptr);
550 }
551 fenceInfo.flags = {};
552 mSingleCommitFence = mDevice.createFence(fenceInfo, nullptr);
553}
554
556{
557 clearVector(mImageAvailableSemaphore, [&](auto& x) { mDevice.destroySemaphore(x, nullptr); });
558 clearVector(mRenderFinishedSemaphore, [&](auto& x) { mDevice.destroySemaphore(x, nullptr); });
559 clearVector(mTextFinishedSemaphore, [&](auto& x) { mDevice.destroySemaphore(x, nullptr); });
560 clearVector(mMixFinishedSemaphore, [&](auto& x) { mDevice.destroySemaphore(x, nullptr); });
561 clearVector(mDownsampleFinishedSemaphore, [&](auto& x) { mDevice.destroySemaphore(x, nullptr); });
562 clearVector(mInFlightFence, [&](auto& x) { mDevice.destroyFence(x, nullptr); });
563 mDevice.destroyFence(mSingleCommitFence, nullptr);
564}
565
566// ---------------------------- VULKAN UNIFORM LAYOUTS AND BUFFERS ----------------------------
567
569{
570 for (int32_t j = 0; j < 3; j++) {
573 for (uint32_t i = 0; i < mFramesInFlight; i++) {
574 mUniformBuffersMat[j][i] = createBuffer(sizeof(hmm_mat4), nullptr, vk::BufferUsageFlagBits::eUniformBuffer, mDisplay->cfg().vulkan.uniformBuffersInDeviceMemory ? 2 : 0);
575 mUniformBuffersCol[j][i] = createBuffer(sizeof(float) * 4, nullptr, vk::BufferUsageFlagBits::eUniformBuffer, mDisplay->cfg().vulkan.uniformBuffersInDeviceMemory ? 2 : 0);
576 }
577 }
578
579 std::array<vk::DescriptorPoolSize, 2> poolSizes{};
580 poolSizes[0].type = vk::DescriptorType::eUniformBuffer;
581 poolSizes[0].descriptorCount = (uint32_t)mFramesInFlight * (2 * 3);
582 poolSizes[1].type = vk::DescriptorType::eCombinedImageSampler;
583 poolSizes[1].descriptorCount = (uint32_t)mFramesInFlight * 2;
584 vk::DescriptorPoolCreateInfo poolInfo{};
585 poolInfo.poolSizeCount = poolSizes.size();
586 poolInfo.pPoolSizes = poolSizes.data();
587 poolInfo.maxSets = (uint32_t)mFramesInFlight * 3;
588 mDescriptorPool = mDevice.createDescriptorPool(poolInfo, nullptr);
589
590 vk::DescriptorSetLayoutBinding uboLayoutBindingMat{};
591 uboLayoutBindingMat.binding = 0;
592 uboLayoutBindingMat.descriptorType = vk::DescriptorType::eUniformBuffer;
593 uboLayoutBindingMat.descriptorCount = 1;
594 uboLayoutBindingMat.stageFlags = vk::ShaderStageFlagBits::eVertex;
595 vk::DescriptorSetLayoutBinding uboLayoutBindingCol = uboLayoutBindingMat;
596 uboLayoutBindingCol.binding = 1;
597 uboLayoutBindingCol.stageFlags = vk::ShaderStageFlagBits::eFragment;
598 vk::DescriptorSetLayoutBinding samplerLayoutBinding{};
599 samplerLayoutBinding.binding = 2;
600 samplerLayoutBinding.descriptorCount = 1;
601 samplerLayoutBinding.descriptorType = vk::DescriptorType::eCombinedImageSampler;
602 samplerLayoutBinding.stageFlags = vk::ShaderStageFlagBits::eFragment;
603 vk::DescriptorSetLayoutBinding bindings[3] = {uboLayoutBindingMat, uboLayoutBindingCol, samplerLayoutBinding};
604
605 vk::DescriptorSetLayoutCreateInfo layoutInfo{};
606 layoutInfo.bindingCount = 2;
607 layoutInfo.pBindings = bindings;
608 mUniformDescriptor = mDevice.createDescriptorSetLayout(layoutInfo, nullptr);
609 layoutInfo.bindingCount = 3;
610 mUniformDescriptorTexture = mDevice.createDescriptorSetLayout(layoutInfo, nullptr);
611
612 vk::DescriptorSetAllocateInfo allocInfo{};
613 allocInfo.descriptorPool = mDescriptorPool;
614 allocInfo.descriptorSetCount = (uint32_t)mFramesInFlight;
615 for (int32_t j = 0; j < 3; j++) { // 0 = Render, 1 = Text, 2 = Texture
616 std::vector<vk::DescriptorSetLayout> layouts(mFramesInFlight, j ? mUniformDescriptorTexture : mUniformDescriptor);
617 allocInfo.pSetLayouts = layouts.data();
618 mDescriptorSets[j] = mDevice.allocateDescriptorSets(allocInfo);
619
620 for (int32_t k = 0; k < 2; k++) {
621 auto& mUniformBuffers = k ? mUniformBuffersCol[j] : mUniformBuffersMat[j];
622 for (uint32_t i = 0; i < mFramesInFlight; i++) {
623 vk::DescriptorBufferInfo bufferInfo{};
624 bufferInfo.buffer = mUniformBuffers[i].buffer;
625 bufferInfo.offset = 0;
626 bufferInfo.range = mUniformBuffers[i].size;
627
628 vk::WriteDescriptorSet descriptorWrite{};
629 descriptorWrite.dstSet = mDescriptorSets[j][i];
630 descriptorWrite.dstBinding = k;
631 descriptorWrite.dstArrayElement = 0;
632 descriptorWrite.descriptorType = vk::DescriptorType::eUniformBuffer;
633 descriptorWrite.descriptorCount = 1;
634 descriptorWrite.pBufferInfo = &bufferInfo;
635 descriptorWrite.pImageInfo = nullptr;
636 descriptorWrite.pTexelBufferView = nullptr;
637 mDevice.updateDescriptorSets(1, &descriptorWrite, 0, nullptr);
638 }
639 }
640 }
641
644 }
645}
646
648{
649 mDevice.destroyDescriptorSetLayout(mUniformDescriptor, nullptr);
650 mDevice.destroyDescriptorSetLayout(mUniformDescriptorTexture, nullptr);
651 mDevice.destroyDescriptorPool(mDescriptorPool, nullptr);
652 for (int32_t j = 0; j < 3; j++) {
653 clearVector(mUniformBuffersMat[j], [&](auto& x) { clearBuffer(x); });
654 clearVector(mUniformBuffersCol[j], [&](auto& x) { clearBuffer(x); });
655 }
656}
657
658void GPUDisplayBackendVulkan::setMixDescriptor(int32_t descriptorIndex, int32_t imageIndex)
659{
660 vk::DescriptorImageInfo imageInfo{};
661 imageInfo.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
662 imageInfo.sampler = mTextureSampler;
663 imageInfo.imageView = *mRenderTargetView[imageIndex + mImageCount];
664 vk::WriteDescriptorSet descriptorWrite{};
665 descriptorWrite.dstSet = mDescriptorSets[2][descriptorIndex];
666 descriptorWrite.dstBinding = 2;
667 descriptorWrite.dstArrayElement = 0;
668 descriptorWrite.descriptorType = vk::DescriptorType::eCombinedImageSampler;
669 descriptorWrite.descriptorCount = 1;
670 descriptorWrite.pImageInfo = &imageInfo;
671 mDevice.updateDescriptorSets(1, &descriptorWrite, 0, nullptr);
672}
673
674// ---------------------------- VULKAN TEXTURE SAMPLER ----------------------------
675
677{
678 vk::SamplerCreateInfo samplerInfo{};
679 samplerInfo.magFilter = vk::Filter::eLinear;
680 samplerInfo.minFilter = vk::Filter::eLinear;
681 samplerInfo.addressModeU = vk::SamplerAddressMode::eRepeat;
682 samplerInfo.addressModeV = vk::SamplerAddressMode::eRepeat;
683 samplerInfo.addressModeW = vk::SamplerAddressMode::eRepeat;
684 samplerInfo.compareEnable = false;
685 samplerInfo.compareOp = vk::CompareOp::eAlways;
686 samplerInfo.borderColor = vk::BorderColor::eIntOpaqueBlack;
687 samplerInfo.unnormalizedCoordinates = false;
688 samplerInfo.mipmapMode = vk::SamplerMipmapMode::eLinear;
689 samplerInfo.mipLodBias = 0.0f;
690 samplerInfo.minLod = 0.0f;
691 samplerInfo.maxLod = 0.0f;
692 mTextureSampler = mDevice.createSampler(samplerInfo, nullptr);
693}
694
696{
697 mDevice.destroySampler(mTextureSampler, nullptr);
698}
699
700// ---------------------------- VULKAN SWAPCHAIN MANAGEMENT ----------------------------
701
702void GPUDisplayBackendVulkan::createSwapChain(bool forScreenshot, bool forMixing)
703{
704 mDownsampleFactor = getDownsampleFactor(forScreenshot);
706 mSwapchainImageReadable = forScreenshot;
707
709 mSurfaceFormat = chooseSwapSurfaceFormat(mSwapChainDetails.formats);
710 mPresentMode = chooseSwapPresentMode(mSwapChainDetails.presentModes, mDisplay->cfgR().drawQualityVSync ? vk::PresentModeKHR::eMailbox : vk::PresentModeKHR::eImmediate);
711 vk::Extent2D extent = chooseSwapExtent(mSwapChainDetails.capabilities);
712
713 uint32_t imageCount = mSwapChainDetails.capabilities.minImageCount + 1;
714 if (mSwapChainDetails.capabilities.maxImageCount > 0 && imageCount > mSwapChainDetails.capabilities.maxImageCount) {
715 imageCount = mSwapChainDetails.capabilities.maxImageCount;
716 }
717
718 mScreenWidth = extent.width;
719 mScreenHeight = extent.height;
722
723 vk::SwapchainCreateInfoKHR swapCreateInfo{};
724 swapCreateInfo.surface = mSurface;
725 swapCreateInfo.minImageCount = imageCount;
726 swapCreateInfo.imageFormat = mSurfaceFormat.format;
727 swapCreateInfo.imageColorSpace = mSurfaceFormat.colorSpace;
728 swapCreateInfo.imageExtent = extent;
729 swapCreateInfo.imageArrayLayers = 1;
730 swapCreateInfo.imageUsage = vk::ImageUsageFlagBits::eColorAttachment;
731 swapCreateInfo.imageSharingMode = vk::SharingMode::eExclusive;
732 swapCreateInfo.queueFamilyIndexCount = 0; // Optional
733 swapCreateInfo.pQueueFamilyIndices = nullptr; // Optional
734 swapCreateInfo.preTransform = mSwapChainDetails.capabilities.currentTransform;
735 swapCreateInfo.compositeAlpha = vk::CompositeAlphaFlagBitsKHR::eOpaque;
736 swapCreateInfo.presentMode = mPresentMode;
737 swapCreateInfo.clipped = true;
738 swapCreateInfo.oldSwapchain = VkSwapchainKHR(VK_NULL_HANDLE);
740 swapCreateInfo.imageUsage |= vk::ImageUsageFlagBits::eTransferSrc;
741 }
742 if (mDownsampleFSAA) {
743 swapCreateInfo.imageUsage |= vk::ImageUsageFlagBits::eTransferDst;
744 }
745 mSwapChain = mDevice.createSwapchainKHR(swapCreateInfo, nullptr);
746
747 mSwapChainImages = mDevice.getSwapchainImagesKHR(mSwapChain);
748 uint32_t oldFramesInFlight = mFramesInFlight;
750 mFramesInFlight = mDisplay->cfg().vulkan.nFramesInFlight == 0 ? mImageCount : mDisplay->cfg().vulkan.nFramesInFlight;
752
753 if (mFramesInFlight > oldFramesInFlight || !mCommandInfrastructureCreated) {
758 }
763 }
764
766 for (uint32_t i = 0; i < mImageCount; i++) {
767 mSwapChainImageViews[i] = createImageViewI(mDevice, mSwapChainImages[i], mSurfaceFormat.format);
768 }
769}
770
772{
773 clearVector(mSwapChainImageViews, [&](auto& x) { mDevice.destroyImageView(x, nullptr); });
774 mDevice.destroySwapchainKHR(mSwapChain, nullptr);
775}
776
777void GPUDisplayBackendVulkan::recreateRendering(bool forScreenshot, bool forMixing)
778{
779 mDevice.waitIdle();
780 bool needUpdateSwapChain = mMustUpdateSwapChain || mDownsampleFactor != getDownsampleFactor(forScreenshot) || mSwapchainImageReadable != forScreenshot;
781 bool needUpdateOffscreenBuffers = needUpdateSwapChain || mMSAASampleCount != getMSAASamplesFlag(std::min<uint32_t>(mMaxMSAAsupported, mDisplay->cfgR().drawQualityMSAA)) || mZActive != (mZSupported && mDisplay->cfgL().depthBuffer) || mMixingSupported != forMixing;
783 if (needUpdateOffscreenBuffers) {
785 if (needUpdateSwapChain) {
787 createSwapChain(forScreenshot, forMixing);
788 }
789 createOffscreenBuffers(forScreenshot, forMixing);
790 }
793}
794
795// ---------------------------- VULKAN OFFSCREEN BUFFERS ----------------------------
796
797void GPUDisplayBackendVulkan::createOffscreenBuffers(bool forScreenshot, bool forMixing)
798{
799 mMSAASampleCount = getMSAASamplesFlag(std::min<uint32_t>(mMaxMSAAsupported, mDisplay->cfgR().drawQualityMSAA));
800 mZActive = mZSupported && mDisplay->cfgL().depthBuffer;
801 mMixingSupported = forMixing;
802
803 vk::AttachmentDescription colorAttachment{};
804 colorAttachment.format = mSurfaceFormat.format;
805 colorAttachment.samples = mMSAASampleCount;
806 colorAttachment.loadOp = vk::AttachmentLoadOp::eClear;
807 colorAttachment.storeOp = vk::AttachmentStoreOp::eStore;
808 colorAttachment.stencilLoadOp = vk::AttachmentLoadOp::eDontCare;
809 colorAttachment.stencilStoreOp = vk::AttachmentStoreOp::eDontCare;
810 colorAttachment.initialLayout = vk::ImageLayout::eUndefined;
811 colorAttachment.finalLayout = (mMSAASampleCount != vk::SampleCountFlagBits::e1 || mDownsampleFSAA) ? vk::ImageLayout::eColorAttachmentOptimal : vk::ImageLayout::ePresentSrcKHR;
812 vk::AttachmentDescription depthAttachment{};
813 depthAttachment.format = vk::Format::eD32Sfloat;
814 depthAttachment.samples = mMSAASampleCount;
815 depthAttachment.loadOp = vk::AttachmentLoadOp::eClear;
816 depthAttachment.storeOp = vk::AttachmentStoreOp::eDontCare;
817 depthAttachment.stencilLoadOp = vk::AttachmentLoadOp::eDontCare;
818 depthAttachment.stencilStoreOp = vk::AttachmentStoreOp::eDontCare;
819 depthAttachment.initialLayout = vk::ImageLayout::eUndefined;
820 depthAttachment.finalLayout = vk::ImageLayout::eDepthStencilAttachmentOptimal;
821 vk::AttachmentDescription colorAttachmentResolve{};
822 colorAttachmentResolve.format = mSurfaceFormat.format;
823 colorAttachmentResolve.samples = vk::SampleCountFlagBits::e1;
824 colorAttachmentResolve.loadOp = vk::AttachmentLoadOp::eDontCare;
825 colorAttachmentResolve.storeOp = vk::AttachmentStoreOp::eStore;
826 colorAttachmentResolve.stencilLoadOp = vk::AttachmentLoadOp::eDontCare;
827 colorAttachmentResolve.stencilStoreOp = vk::AttachmentStoreOp::eDontCare;
828 colorAttachmentResolve.initialLayout = vk::ImageLayout::eUndefined;
829 colorAttachmentResolve.finalLayout = mDownsampleFSAA ? vk::ImageLayout::eColorAttachmentOptimal : vk::ImageLayout::ePresentSrcKHR;
830 int32_t nAttachments = 0;
831 vk::AttachmentReference colorAttachmentRef{};
832 colorAttachmentRef.attachment = nAttachments++;
833 colorAttachmentRef.layout = vk::ImageLayout::eColorAttachmentOptimal;
834 vk::AttachmentReference depthAttachmentRef{};
835 // depthAttachmentRef.attachment // below
836 depthAttachmentRef.layout = vk::ImageLayout::eDepthStencilAttachmentOptimal;
837 vk::AttachmentReference colorAttachmentResolveRef{};
838 // colorAttachmentResolveRef.attachment // below
839 colorAttachmentResolveRef.layout = vk::ImageLayout::eColorAttachmentOptimal;
840 vk::SubpassDescription subpass{};
841 subpass.pipelineBindPoint = vk::PipelineBindPoint::eGraphics;
842 subpass.colorAttachmentCount = 1;
843 subpass.pColorAttachments = &colorAttachmentRef;
844 vk::SubpassDependency dependency{};
845 dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
846 dependency.dstSubpass = 0;
847 dependency.srcStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput | vk::PipelineStageFlagBits::eEarlyFragmentTests;
848 dependency.srcAccessMask = {};
849 dependency.dstStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput | vk::PipelineStageFlagBits::eEarlyFragmentTests;
850 dependency.dstAccessMask = vk::AccessFlagBits::eColorAttachmentWrite | vk::AccessFlagBits::eDepthStencilAttachmentWrite;
851
852 std::vector<vk::AttachmentDescription> attachments = {colorAttachment};
853 if (mZActive) {
854 attachments.emplace_back(depthAttachment);
855 depthAttachmentRef.attachment = nAttachments++;
856 subpass.pDepthStencilAttachment = &depthAttachmentRef;
857 }
858 if (mMSAASampleCount != vk::SampleCountFlagBits::e1) {
859 attachments.emplace_back(colorAttachmentResolve);
860 colorAttachmentResolveRef.attachment = nAttachments++;
861 subpass.pResolveAttachments = &colorAttachmentResolveRef;
862 }
863
864 vk::RenderPassCreateInfo renderPassInfo{};
865 renderPassInfo.attachmentCount = attachments.size();
866 renderPassInfo.pAttachments = attachments.data();
867 renderPassInfo.subpassCount = 1;
868 renderPassInfo.pSubpasses = &subpass;
869 renderPassInfo.dependencyCount = 1;
870 renderPassInfo.pDependencies = &dependency;
871 mRenderPass = mDevice.createRenderPass(renderPassInfo, nullptr);
872
873 const uint32_t imageCountWithMixImages = mImageCount * (mMixingSupported ? 2 : 1);
874 mRenderTargetView.resize(imageCountWithMixImages);
875 mFramebuffers.resize(imageCountWithMixImages);
876 if (mDownsampleFSAA) {
877 mDownsampleImages.resize(imageCountWithMixImages);
878 }
879 if (mMSAASampleCount != vk::SampleCountFlagBits::e1) {
880 mMSAAImages.resize(imageCountWithMixImages);
881 }
882 if (mZActive) {
883 mZImages.resize(imageCountWithMixImages);
884 }
885 if (mMSAASampleCount != vk::SampleCountFlagBits::e1 || mZActive || mDownsampleFSAA) {
887 }
888 if (mMixingSupported) {
889 if (mMSAASampleCount != vk::SampleCountFlagBits::e1 || mZActive || mDownsampleFSAA) {
891 }
892 if (!mDownsampleFSAA) {
893 mMixImages.resize(mImageCount);
894 }
895 }
896
897 // Text overlay goes as extra rendering path
898 renderPassInfo.attachmentCount = 1; // Remove depth and MSAA attachments
899 renderPassInfo.pAttachments = &colorAttachment;
900 subpass.pDepthStencilAttachment = nullptr;
901 subpass.pResolveAttachments = nullptr;
902 if (mFramebuffersText.size()) {
903 dependency.srcStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput; // Remove early fragment test
904 dependency.dstStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput;
905 dependency.dstAccessMask = vk::AccessFlagBits::eColorAttachmentWrite; // Remove depth/stencil dependencies
906 }
907 colorAttachment.loadOp = vk::AttachmentLoadOp::eLoad; // Don't clear the frame buffer
908 colorAttachment.initialLayout = vk::ImageLayout::ePresentSrcKHR; // Initial layout is not undefined after 1st pass
909 colorAttachment.samples = vk::SampleCountFlagBits::e1; // No MSAA for Text
910 colorAttachment.finalLayout = vk::ImageLayout::ePresentSrcKHR; // Might have been overwritten above for 1st pass in case of MSAA
911 mRenderPassText = mDevice.createRenderPass(renderPassInfo, nullptr);
912
913 if (mMixingSupported) {
914 if (mDownsampleFSAA) {
915 colorAttachment.initialLayout = vk::ImageLayout::eColorAttachmentOptimal;
916 colorAttachment.finalLayout = mDownsampleFSAA ? vk::ImageLayout::eColorAttachmentOptimal : vk::ImageLayout::ePresentSrcKHR;
917 }
918 if (mFramebuffersTexture.size()) {
919 dependency.srcStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput; // Remove early fragment test
920 dependency.dstStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput;
921 dependency.dstAccessMask = vk::AccessFlagBits::eColorAttachmentWrite; // Remove depth/stencil dependencies
922 }
923 mRenderPassTexture = mDevice.createRenderPass(renderPassInfo, nullptr);
924 }
925
926 for (uint32_t i = 0; i < imageCountWithMixImages; i++) {
927 if (i < mImageCount) { // Main render chain
928 // primary buffer mSwapChainImageViews[i] created as part of createSwapChain, not here
929 } else if (!mDownsampleFSAA) { // for rendering to mixBuffer
930 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);
931 mMixImages[i - mImageCount].view = createImageViewI(mDevice, mMixImages[i - mImageCount].image, mSurfaceFormat.format, vk::ImageAspectFlagBits::eColor, 1);
932 }
933 std::vector<vk::ImageView> att;
934 if (mDownsampleFSAA) {
935 vk::ImageUsageFlags usage = vk::ImageUsageFlagBits::eColorAttachment | (i >= mImageCount ? vk::ImageUsageFlagBits::eSampled : vk::ImageUsageFlagBits::eTransferSrc);
936 createImageI(mDevice, mPhysicalDevice, mDownsampleImages[i].image, mDownsampleImages[i].memory, mRenderWidth, mRenderHeight, mSurfaceFormat.format, usage, vk::MemoryPropertyFlagBits::eDeviceLocal, vk::ImageTiling::eOptimal);
937 mDownsampleImages[i].view = createImageViewI(mDevice, mDownsampleImages[i].image, mSurfaceFormat.format, vk::ImageAspectFlagBits::eColor, 1);
939 } else {
941 }
942 if (mMSAASampleCount != vk::SampleCountFlagBits::e1) { // First attachment is the render target, either the MSAA buffer or the framebuffer
943 createImageI(mDevice, mPhysicalDevice, mMSAAImages[i].image, mMSAAImages[i].memory, mRenderWidth, mRenderHeight, mSurfaceFormat.format, vk::ImageUsageFlagBits::eColorAttachment, vk::MemoryPropertyFlagBits::eDeviceLocal, vk::ImageTiling::eOptimal, mMSAASampleCount);
944 mMSAAImages[i].view = createImageViewI(mDevice, mMSAAImages[i].image, mSurfaceFormat.format, vk::ImageAspectFlagBits::eColor, 1);
945 att.emplace_back(mMSAAImages[i].view);
946 } else {
947 att.emplace_back(*mRenderTargetView[i]);
948 }
949 if (mZActive) {
950 createImageI(mDevice, mPhysicalDevice, mZImages[i].image, mZImages[i].memory, mRenderWidth, mRenderHeight, vk::Format::eD32Sfloat, vk::ImageUsageFlagBits::eDepthStencilAttachment, vk::MemoryPropertyFlagBits::eDeviceLocal, vk::ImageTiling::eOptimal, mMSAASampleCount);
951 mZImages[i].view = createImageViewI(mDevice, mZImages[i].image, vk::Format::eD32Sfloat, vk::ImageAspectFlagBits::eDepth, 1);
952 att.emplace_back(mZImages[i].view);
953 }
954 if (mMSAASampleCount != vk::SampleCountFlagBits::e1) { // If we use MSAA, we have to resolve to the framebuffer as the last target
955 att.emplace_back(*mRenderTargetView[i]);
956 }
957
958 vk::FramebufferCreateInfo framebufferInfo{};
959 framebufferInfo.renderPass = mRenderPass;
960 framebufferInfo.attachmentCount = att.size();
961 framebufferInfo.pAttachments = att.data();
962 framebufferInfo.width = mRenderWidth;
963 framebufferInfo.height = mRenderHeight;
964 framebufferInfo.layers = 1;
965 mFramebuffers[i] = mDevice.createFramebuffer(framebufferInfo, nullptr);
966
967 if (i < mImageCount && mFramebuffersText.size()) {
968 framebufferInfo.attachmentCount = 1;
969 framebufferInfo.pAttachments = &mSwapChainImageViews[i];
970 framebufferInfo.renderPass = mRenderPassText;
971 framebufferInfo.width = mScreenWidth;
972 framebufferInfo.height = mScreenHeight;
973 mFramebuffersText[i] = mDevice.createFramebuffer(framebufferInfo, nullptr);
974 }
975
976 if (i >= mImageCount && mFramebuffersTexture.size()) {
977 framebufferInfo.attachmentCount = 1;
978 framebufferInfo.pAttachments = mRenderTargetView[i - mImageCount];
979 framebufferInfo.renderPass = mRenderPassTexture;
980 framebufferInfo.width = mRenderWidth;
981 framebufferInfo.height = mRenderHeight;
982 mFramebuffersTexture[i - mImageCount] = mDevice.createFramebuffer(framebufferInfo, nullptr);
983 }
984 }
985
986 if (mMixingSupported) {
987 float vertices[6][4] = {
988 {0, (float)mRenderHeight, 0.0f, 1.0f},
989 {0, 0, 0.0f, 0.0f},
990 {(float)mRenderWidth, 0, 1.0f, 0.0f},
991 {0, (float)mRenderHeight, 0.0f, 1.0f},
992 {(float)mRenderWidth, 0, 1.0f, 0.0f},
993 {(float)mRenderWidth, (float)mRenderHeight, 1.0f, 1.0f}};
994 mMixingTextureVertexArray = createBuffer(sizeof(vertices), &vertices[0][0], vk::BufferUsageFlagBits::eVertexBuffer, 1);
995
997 for (uint32_t i = 0; i < mFramesInFlight; i++) {
999 }
1000 }
1001 }
1002
1004}
1005
1007{
1008 clearVector(mFramebuffers, [&](auto& x) { mDevice.destroyFramebuffer(x, nullptr); });
1009 clearVector(mMSAAImages, [&](auto& x) { clearImage(x); });
1010 clearVector(mDownsampleImages, [&](auto& x) { clearImage(x); });
1011 clearVector(mZImages, [&](auto& x) { clearImage(x); });
1012 clearVector(mMixImages, [&](auto& x) { clearImage(x); });
1013 clearVector(mFramebuffersText, [&](auto& x) { mDevice.destroyFramebuffer(x, nullptr); });
1014 clearVector(mFramebuffersTexture, [&](auto& x) { mDevice.destroyFramebuffer(x, nullptr); });
1015 mDevice.destroyRenderPass(mRenderPass, nullptr);
1016 mDevice.destroyRenderPass(mRenderPassText, nullptr);
1017 if (mMixingSupported) {
1018 mDevice.destroyRenderPass(mRenderPassTexture, nullptr);
1020 }
1021}
1022
1023// ---------------------------- VULKAN PIPELINE ----------------------------
1024
1026{
1027 vk::PipelineShaderStageCreateInfo shaderStages[2] = {vk::PipelineShaderStageCreateInfo{}, vk::PipelineShaderStageCreateInfo{}};
1028 vk::PipelineShaderStageCreateInfo& vertShaderStageInfo = shaderStages[0];
1029 vertShaderStageInfo.stage = vk::ShaderStageFlagBits::eVertex;
1030 // vertShaderStageInfo.module // below
1031 vertShaderStageInfo.pName = "main";
1032 vk::PipelineShaderStageCreateInfo& fragShaderStageInfo = shaderStages[1];
1033 fragShaderStageInfo.stage = vk::ShaderStageFlagBits::eFragment;
1034 // fragShaderStageInfo.module // below
1035 fragShaderStageInfo.pName = "main";
1036
1037 vk::VertexInputBindingDescription bindingDescription{};
1038 bindingDescription.binding = 0;
1039 // bindingDescription.stride // below
1040 bindingDescription.inputRate = vk::VertexInputRate::eVertex;
1041
1042 vk::VertexInputAttributeDescription attributeDescriptions{};
1043 attributeDescriptions.binding = 0;
1044 attributeDescriptions.location = 0;
1045 // attributeDescriptions.format // below
1046 attributeDescriptions.offset = 0;
1047
1048 vk::PipelineVertexInputStateCreateInfo vertexInputInfo{};
1049 vertexInputInfo.vertexBindingDescriptionCount = 1;
1050 vertexInputInfo.pVertexBindingDescriptions = &bindingDescription;
1051 vertexInputInfo.vertexAttributeDescriptionCount = 1;
1052 vertexInputInfo.pVertexAttributeDescriptions = &attributeDescriptions;
1053 vk::PipelineInputAssemblyStateCreateInfo inputAssembly{};
1054 // inputAssembly.topology // below
1055 inputAssembly.primitiveRestartEnable = false;
1056
1057 vk::Viewport viewport{};
1058 viewport.x = 0.0f;
1059 viewport.y = 0.0f;
1060 // viewport.width // below
1061 // viewport.height // below
1062 viewport.minDepth = 0.0f;
1063 viewport.maxDepth = 1.0f;
1064
1065 vk::Rect2D scissor{};
1066 scissor.offset = vk::Offset2D{0, 0};
1067 // scissor.extent // below
1068
1069 vk::PipelineViewportStateCreateInfo viewportState{};
1070 viewportState.viewportCount = 1;
1071 viewportState.pViewports = &viewport;
1072 viewportState.scissorCount = 1;
1073 viewportState.pScissors = &scissor;
1074
1075 vk::PipelineRasterizationStateCreateInfo rasterizer{};
1076 rasterizer.depthClampEnable = false;
1077 rasterizer.rasterizerDiscardEnable = false;
1078 rasterizer.polygonMode = vk::PolygonMode::eFill;
1079 rasterizer.lineWidth = mDisplay->cfgL().lineWidth;
1080 rasterizer.cullMode = vk::CullModeFlagBits::eBack;
1081 rasterizer.frontFace = vk::FrontFace::eClockwise;
1082 rasterizer.depthBiasEnable = false;
1083 rasterizer.depthBiasConstantFactor = 0.0f; // Optional
1084 rasterizer.depthBiasClamp = 0.0f; // Optional
1085 rasterizer.depthBiasSlopeFactor = 0.0f; // Optional
1086
1087 vk::PipelineMultisampleStateCreateInfo multisampling{};
1088 multisampling.sampleShadingEnable = false;
1089 // multisampling.rasterizationSamples // below
1090 multisampling.minSampleShading = 1.0f; // Optional
1091 multisampling.pSampleMask = nullptr; // Optional
1092 multisampling.alphaToCoverageEnable = false; // Optional
1093 multisampling.alphaToOneEnable = false; // Optional
1094
1095 vk::PipelineColorBlendAttachmentState colorBlendAttachment{};
1096 colorBlendAttachment.colorWriteMask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA;
1097 // colorBlendAttachment.blendEnable // below
1098 colorBlendAttachment.colorWriteMask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA;
1099 colorBlendAttachment.srcColorBlendFactor = vk::BlendFactor::eSrcAlpha;
1100 colorBlendAttachment.dstColorBlendFactor = vk::BlendFactor::eOneMinusSrcAlpha;
1101 colorBlendAttachment.colorBlendOp = vk::BlendOp::eAdd;
1102 colorBlendAttachment.srcAlphaBlendFactor = vk::BlendFactor::eOneMinusSrcAlpha;
1103 colorBlendAttachment.dstAlphaBlendFactor = vk::BlendFactor::eZero;
1104 colorBlendAttachment.alphaBlendOp = vk::BlendOp::eAdd;
1105
1106 vk::PipelineColorBlendStateCreateInfo colorBlending{};
1107 colorBlending.logicOpEnable = false;
1108 colorBlending.logicOp = vk::LogicOp::eCopy;
1109 colorBlending.attachmentCount = 1;
1110 colorBlending.pAttachments = &colorBlendAttachment;
1111 colorBlending.blendConstants[0] = 0.0f;
1112 colorBlending.blendConstants[1] = 0.0f;
1113 colorBlending.blendConstants[2] = 0.0f;
1114 colorBlending.blendConstants[3] = 0.0f;
1115
1116 vk::PipelineDepthStencilStateCreateInfo depthStencil{};
1117 depthStencil.depthTestEnable = true;
1118 depthStencil.depthWriteEnable = true;
1119 depthStencil.depthCompareOp = vk::CompareOp::eLess;
1120 depthStencil.depthBoundsTestEnable = false;
1121 depthStencil.stencilTestEnable = false;
1122
1123 vk::DynamicState dynamicStates[] = {vk::DynamicState::eLineWidth};
1124 vk::PipelineDynamicStateCreateInfo dynamicState{};
1125 dynamicState.dynamicStateCount = 1;
1126 dynamicState.pDynamicStates = dynamicStates;
1127
1128 vk::PushConstantRange pushConstantRanges[2] = {vk::PushConstantRange{}, vk::PushConstantRange{}};
1129 pushConstantRanges[0].stageFlags = vk::ShaderStageFlagBits::eFragment;
1130 pushConstantRanges[0].offset = 0;
1131 pushConstantRanges[0].size = sizeof(float) * 4;
1132 pushConstantRanges[1].stageFlags = vk::ShaderStageFlagBits::eVertex;
1133 pushConstantRanges[1].offset = pushConstantRanges[0].size;
1134 pushConstantRanges[1].size = sizeof(float);
1135 vk::PipelineLayoutCreateInfo pipelineLayoutInfo{};
1136 pipelineLayoutInfo.setLayoutCount = 1;
1137 pipelineLayoutInfo.pSetLayouts = &mUniformDescriptor;
1138 pipelineLayoutInfo.pushConstantRangeCount = 2;
1139 pipelineLayoutInfo.pPushConstantRanges = pushConstantRanges;
1140 mPipelineLayout = mDevice.createPipelineLayout(pipelineLayoutInfo, nullptr);
1141 pipelineLayoutInfo.setLayoutCount = 1;
1142 pipelineLayoutInfo.pSetLayouts = &mUniformDescriptorTexture;
1143 mPipelineLayoutTexture = mDevice.createPipelineLayout(pipelineLayoutInfo, nullptr);
1144
1145 vk::GraphicsPipelineCreateInfo pipelineInfo{};
1146 pipelineInfo.stageCount = 2;
1147 pipelineInfo.pVertexInputState = &vertexInputInfo;
1148 pipelineInfo.pInputAssemblyState = &inputAssembly;
1149 pipelineInfo.pViewportState = &viewportState;
1150 pipelineInfo.pRasterizationState = &rasterizer;
1151 pipelineInfo.pMultisampleState = &multisampling;
1152 // pipelineInfo.pDepthStencilState // below
1153 pipelineInfo.pColorBlendState = &colorBlending;
1154 pipelineInfo.pDynamicState = &dynamicState;
1155 // pipelineInfo.layout // below
1156 // pipelineInfo.renderPass // below
1157 pipelineInfo.subpass = 0;
1158 pipelineInfo.pStages = shaderStages;
1159 pipelineInfo.basePipelineHandle = VkPipeline(VK_NULL_HANDLE); // Optional
1160 pipelineInfo.basePipelineIndex = -1; // Optional
1161
1162 mPipelines.resize(mMixingSupported ? 5 : 4);
1163 static constexpr vk::PrimitiveTopology types[3] = {vk::PrimitiveTopology::ePointList, vk::PrimitiveTopology::eLineList, vk::PrimitiveTopology::eLineStrip};
1164 for (uint32_t i = 0; i < mPipelines.size(); i++) {
1165 if (i == 4) { // Texture rendering
1166 bindingDescription.stride = 4 * sizeof(float);
1167 attributeDescriptions.format = vk::Format::eR32G32B32A32Sfloat;
1168 inputAssembly.topology = vk::PrimitiveTopology::eTriangleList;
1169 vertShaderStageInfo.module = mShaders["vertexTexture"];
1170 fragShaderStageInfo.module = mShaders["fragmentTexture"];
1171 pipelineInfo.layout = mPipelineLayoutTexture;
1172 pipelineInfo.renderPass = mRenderPassTexture;
1173 pipelineInfo.pDepthStencilState = nullptr;
1174 colorBlendAttachment.blendEnable = true;
1175 multisampling.rasterizationSamples = vk::SampleCountFlagBits::e1;
1176 viewport.width = scissor.extent.width = mRenderWidth;
1177 viewport.height = scissor.extent.height = mRenderHeight;
1178 } else if (i == 3) { // Text rendering
1179 bindingDescription.stride = 4 * sizeof(float);
1180 attributeDescriptions.format = vk::Format::eR32G32B32A32Sfloat;
1181 inputAssembly.topology = vk::PrimitiveTopology::eTriangleList;
1182 vertShaderStageInfo.module = mShaders["vertexTexture"];
1183 fragShaderStageInfo.module = mShaders["fragmentText"];
1184 pipelineInfo.layout = mPipelineLayoutTexture;
1185 pipelineInfo.renderPass = mRenderPassText;
1186 pipelineInfo.pDepthStencilState = nullptr;
1187 colorBlendAttachment.blendEnable = true;
1188 multisampling.rasterizationSamples = vk::SampleCountFlagBits::e1;
1189 viewport.width = scissor.extent.width = mScreenWidth;
1190 viewport.height = scissor.extent.height = mScreenHeight;
1191 } else { // Point / line / line-strip rendering
1192 bindingDescription.stride = 3 * sizeof(float);
1193 attributeDescriptions.format = vk::Format::eR32G32B32Sfloat;
1194 inputAssembly.topology = types[i];
1195 vertShaderStageInfo.module = mShaders[types[i] == vk::PrimitiveTopology::ePointList ? "vertexPoint" : "vertex"];
1196 fragShaderStageInfo.module = mShaders["fragment"];
1197 pipelineInfo.layout = mPipelineLayout;
1198 pipelineInfo.renderPass = mRenderPass;
1199 pipelineInfo.pDepthStencilState = mZActive ? &depthStencil : nullptr;
1200 colorBlendAttachment.blendEnable = true;
1201 multisampling.rasterizationSamples = mMSAASampleCount;
1202 viewport.width = scissor.extent.width = mRenderWidth;
1203 viewport.height = scissor.extent.height = mRenderHeight;
1204 }
1205
1206 CHKERR(mDevice.createGraphicsPipelines(VkPipelineCache(VK_NULL_HANDLE), 1, &pipelineInfo, nullptr, &mPipelines[i])); // TODO: multiple at once + cache?
1207 }
1208}
1209
1210void GPUDisplayBackendVulkan::startFillCommandBuffer(vk::CommandBuffer& commandBuffer, uint32_t imageIndex, bool toMixBuffer)
1211{
1212 commandBuffer.reset({});
1213
1214 vk::CommandBufferBeginInfo beginInfo{};
1215 beginInfo.flags = {};
1216 commandBuffer.begin(beginInfo);
1217
1218 vk::ClearValue clearValues[2];
1219 clearValues[0].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}};
1220 clearValues[1].depthStencil = vk::ClearDepthStencilValue{{1.0f, 0}};
1221
1222 vk::RenderPassBeginInfo renderPassInfo{};
1223 renderPassInfo.renderPass = mRenderPass;
1224 renderPassInfo.framebuffer = toMixBuffer ? mFramebuffers[imageIndex + mImageCount] : mFramebuffers[imageIndex];
1225 renderPassInfo.renderArea.offset = vk::Offset2D{0, 0};
1226 renderPassInfo.renderArea.extent = vk::Extent2D{mRenderWidth, mRenderHeight};
1227 renderPassInfo.clearValueCount = mZActive ? 2 : 1;
1228 renderPassInfo.pClearValues = clearValues;
1229 commandBuffer.beginRenderPass(&renderPassInfo, vk::SubpassContents::eInline);
1230
1231 vk::DeviceSize offsets[] = {0};
1232 commandBuffer.bindVertexBuffers(0, 1, &mVBO.buffer, offsets);
1233 commandBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, mPipelineLayout, 0, 1, &mDescriptorSets[0][mCurrentBufferSet], 0, nullptr);
1234}
1235
1236void GPUDisplayBackendVulkan::endFillCommandBuffer(vk::CommandBuffer& commandBuffer)
1237{
1238 commandBuffer.endRenderPass();
1239 commandBuffer.end();
1240}
1241
1243{
1244 clearVector(mPipelines, [&](auto& x) { mDevice.destroyPipeline(x, nullptr); });
1245 mDevice.destroyPipelineLayout(mPipelineLayout, nullptr);
1246 mDevice.destroyPipelineLayout(mPipelineLayoutTexture, nullptr);
1247}
1248
1249// ---------------------------- VULKAN SHADERS ----------------------------
1250
1251#define LOAD_SHADER(file, ext) \
1252 mShaders[#file] = createShaderModule(_binary_shaders_shaders_##file##_##ext##_spv_start, _binary_shaders_shaders_##file##_##ext##_spv_len, mDevice)
1253
1255{
1256 LOAD_SHADER(vertex, vert);
1257 LOAD_SHADER(fragment, frag);
1258 LOAD_SHADER(vertexPoint, vert);
1259 LOAD_SHADER(vertexTexture, vert);
1260 LOAD_SHADER(fragmentTexture, frag);
1261 LOAD_SHADER(fragmentText, frag);
1262}
1263
1265{
1266 clearVector(mShaders, [&](auto& x) { mDevice.destroyShaderModule(x.second, nullptr); });
1267}
1268
1269// ---------------------------- VULKAN BUFFERS ----------------------------
1270
1272{
1273 if (buffer.deviceMemory != 1) {
1274 void* dstData;
1275 CHKERR(mDevice.mapMemory(buffer.memory, 0, buffer.size, {}, &dstData));
1276 memcpy(dstData, srcData, size);
1277 mDevice.unmapMemory(buffer.memory);
1278 } else {
1279 auto tmp = createBuffer(size, srcData, vk::BufferUsageFlagBits::eTransferSrc, 0);
1280
1281 vk::CommandBuffer commandBuffer = getSingleTimeCommandBuffer();
1282 vk::BufferCopy copyRegion{};
1283 copyRegion.size = size;
1284 commandBuffer.copyBuffer(tmp.buffer, buffer.buffer, 1, &copyRegion);
1285 submitSingleTimeCommandBuffer(commandBuffer);
1286
1287 clearBuffer(tmp);
1288 }
1289}
1290
1291GPUDisplayBackendVulkan::VulkanBuffer GPUDisplayBackendVulkan::createBuffer(size_t size, const void* srcData, vk::BufferUsageFlags type, int32_t deviceMemory)
1292{
1293 vk::MemoryPropertyFlags properties;
1294 if (deviceMemory) {
1295 properties |= vk::MemoryPropertyFlagBits::eDeviceLocal;
1296 }
1297 if (deviceMemory == 0 || deviceMemory == 2) {
1298 properties |= (vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
1299 }
1300 if (deviceMemory == 1) {
1301 type |= vk::BufferUsageFlagBits::eTransferDst;
1302 }
1303
1305 vk::BufferCreateInfo bufferInfo{};
1306 bufferInfo.size = size;
1307 bufferInfo.usage = type;
1308 bufferInfo.sharingMode = vk::SharingMode::eExclusive;
1309 buffer.buffer = mDevice.createBuffer(bufferInfo, nullptr);
1310
1311 vk::MemoryRequirements memRequirements;
1312 memRequirements = mDevice.getBufferMemoryRequirements(buffer.buffer);
1313 vk::MemoryAllocateInfo allocInfo{};
1314 allocInfo.allocationSize = memRequirements.size;
1315 allocInfo.memoryTypeIndex = findMemoryType(memRequirements.memoryTypeBits, properties, mPhysicalDevice);
1316 buffer.memory = mDevice.allocateMemory(allocInfo, nullptr);
1317
1318 mDevice.bindBufferMemory(buffer.buffer, buffer.memory, 0);
1319
1320 buffer.size = size;
1321 buffer.deviceMemory = deviceMemory;
1322
1323 if (srcData != nullptr) {
1324 writeToBuffer(buffer, size, srcData);
1325 }
1326
1327 return buffer;
1328}
1329
1331{
1332 mDevice.destroyBuffer(buffer.buffer, nullptr);
1333 mDevice.freeMemory(buffer.memory, nullptr);
1334}
1335
1337{
1338 if (mVBO.size) {
1340 mVBO.size = 0;
1341 }
1345 }
1346 for (auto& buf : mFontVertexBuffer) {
1347 if (buf.size) {
1349 }
1350 buf.size = 0;
1351 }
1352}
1353
1354// ---------------------------- VULKAN TEXTURES ----------------------------
1355
1356void GPUDisplayBackendVulkan::writeToImage(VulkanImage& image, const void* srcData, size_t srcSize)
1357{
1358 auto tmp = createBuffer(srcSize, srcData, vk::BufferUsageFlagBits::eTransferSrc, 0);
1359
1360 vk::CommandBuffer commandBuffer = getSingleTimeCommandBuffer();
1361 cmdImageMemoryBarrier(commandBuffer, image.image, {}, vk::AccessFlagBits::eTransferWrite, vk::ImageLayout::eUndefined, vk::ImageLayout::eTransferDstOptimal, vk::PipelineStageFlagBits::eTopOfPipe, vk::PipelineStageFlagBits::eTransfer);
1362 vk::BufferImageCopy region{};
1363 region.bufferOffset = 0;
1364 region.bufferRowLength = 0;
1365 region.bufferImageHeight = 0;
1366 region.imageSubresource.aspectMask = vk::ImageAspectFlagBits::eColor;
1367 region.imageSubresource.mipLevel = 0;
1368 region.imageSubresource.baseArrayLayer = 0;
1369 region.imageSubresource.layerCount = 1;
1370 region.imageOffset = vk::Offset3D{0, 0, 0};
1371 region.imageExtent = vk::Extent3D{image.sizex, image.sizey, 1};
1372 commandBuffer.copyBufferToImage(tmp.buffer, image.image, vk::ImageLayout::eTransferDstOptimal, 1, &region);
1373 cmdImageMemoryBarrier(commandBuffer, image.image, vk::AccessFlagBits::eTransferWrite, vk::AccessFlagBits::eShaderRead, vk::ImageLayout::eTransferDstOptimal, vk::ImageLayout::eShaderReadOnlyOptimal, vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eFragmentShader);
1374 submitSingleTimeCommandBuffer(commandBuffer);
1375
1376 clearBuffer(tmp);
1377}
1378
1379GPUDisplayBackendVulkan::VulkanImage GPUDisplayBackendVulkan::createImage(uint32_t sizex, uint32_t sizey, const void* srcData, size_t srcSize, vk::Format format)
1380{
1382 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);
1383
1384 image.view = createImageViewI(mDevice, image.image, format);
1385
1386 image.sizex = sizex;
1387 image.sizey = sizey;
1388 image.format = format;
1389
1390 if (srcData) {
1391 writeToImage(image, srcData, srcSize);
1392 }
1393 return image;
1394}
1395
1397{
1398 mDevice.destroyImageView(image.view, nullptr);
1399 mDevice.destroyImage(image.image, nullptr);
1400 mDevice.freeMemory(image.memory, nullptr);
1401}
1402
1403// ---------------------------- VULKAN INIT EXIT ----------------------------
1404
1406{
1407 mEnableValidationLayers = mDisplay->param() && mDisplay->param()->par.debugLevel >= 2;
1408 mFramesInFlight = 2;
1409
1410 createDevice();
1411 createShaders();
1416
1417 return (0);
1418}
1419
1440
1441// ---------------------------- USER CODE ----------------------------
1442
1444{
1445 if (mScreenWidth == width && mScreenHeight == height) {
1446 return;
1447 }
1449 vk::Extent2D extent = chooseSwapExtent(mSwapChainDetails.capabilities);
1450 if (extent.width != mScreenWidth || extent.height != mScreenHeight) {
1451 mMustUpdateSwapChain = true;
1452 }
1453}
1454
1456{
1457 mDevice.waitIdle();
1459 mVBO = createBuffer(totalVertizes * sizeof(mDisplay->vertexBuffer()[0][0]), mDisplay->vertexBuffer()[0].data(), vk::BufferUsageFlagBits::eVertexBuffer, 1);
1460 if (mDisplay->cfgR().useGLIndirectDraw) {
1462 mIndirectCommandBuffer = createBuffer(mCmdBuffer.size() * sizeof(mCmdBuffer[0]), mCmdBuffer.data(), vk::BufferUsageFlagBits::eIndirectBuffer, 1);
1463 mCmdBuffer.clear();
1464 }
1466}
1467
1469{
1470 auto first = std::get<0>(v);
1471 auto count = std::get<1>(v);
1472 auto iSector = std::get<2>(v);
1473 if (count == 0) {
1474 return 0;
1475 }
1477 return count;
1478 }
1479
1481 mCurrentCommandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, mPipelines[tt]);
1483 }
1484 if (mDisplay->cfgR().useGLIndirectDraw) {
1486 } else {
1487 for (uint32_t k = 0; k < count; k++) {
1488 mCurrentCommandBuffer.draw(mDisplay->vertexBufferCount()[iSector][first + k], 1, mDisplay->vertexBufferStart()[iSector][first + k], 0);
1489 }
1490 }
1491
1492 return count;
1493}
1494
1495void GPUDisplayBackendVulkan::prepareDraw(const hmm_mat4& proj, const hmm_mat4& view, bool requestScreenshot, bool toMixBuffer, float includeMixImage)
1496{
1497 if (mDisplay->updateDrawCommands() || toMixBuffer || includeMixImage > 0) {
1499 }
1500
1501 if (includeMixImage == 0.f) {
1503 CHKERR(mDevice.waitForFences(1, &mInFlightFence[mCurrentFrame], true, UINT64_MAX));
1504 auto getImage = [&]() {
1505 vk::Fence fen = VkFence(VK_NULL_HANDLE);
1506 vk::Semaphore sem = VkSemaphore(VK_NULL_HANDLE);
1509 CHKERR(mDevice.resetFences(1, &fen));
1510 } else {
1512 }
1513 return mDevice.acquireNextImageKHR(mSwapChain, UINT64_MAX, sem, fen, &mCurrentImageIndex);
1514 };
1515
1516 vk::Result retVal = vk::Result::eSuccess;
1517 bool mustUpdateRendering = mMustUpdateSwapChain;
1518 if (mDisplay->updateRenderPipeline() || (requestScreenshot && !mSwapchainImageReadable) || (toMixBuffer && !mMixingSupported) || mDownsampleFactor != getDownsampleFactor(requestScreenshot)) {
1519 mustUpdateRendering = true;
1520 } else if (!mMustUpdateSwapChain) {
1521 retVal = getImage();
1522 }
1523 if (mMustUpdateSwapChain || mustUpdateRendering || retVal == vk::Result::eErrorOutOfDateKHR || retVal == vk::Result::eSuboptimalKHR) {
1524 if (!mustUpdateRendering) {
1525 GPUInfo("Pipeline out of data / suboptimal, recreating");
1526 }
1527 recreateRendering(requestScreenshot, toMixBuffer);
1528 retVal = getImage();
1529 }
1530 CHKERR(retVal);
1532 CHKERR(mDevice.waitForFences(1, &mInFlightFence[mCurrentFrame], true, UINT64_MAX));
1533 }
1534 CHKERR(mDevice.resetFences(1, &mInFlightFence[mCurrentFrame]));
1535 mMustUpdateSwapChain = false;
1536 mHasDrawnText = false;
1538
1539 const hmm_mat4 modelViewProj = proj * view;
1540 writeToBuffer(mUniformBuffersMat[0][mCurrentBufferSet], sizeof(modelViewProj), &modelViewProj);
1541 }
1542
1547 }
1548}
1549
1550void GPUDisplayBackendVulkan::finishDraw(bool doScreenshot, bool toMixBuffer, float includeMixImage)
1551{
1554 if (!toMixBuffer && includeMixImage == 0.f && mCommandBufferPerImage) {
1556 }
1557 }
1558}
1559
1560void GPUDisplayBackendVulkan::finishFrame(bool doScreenshot, bool toMixBuffer, float includeMixImage)
1561{
1562 vk::Semaphore* stageFinishedSemaphore = &mRenderFinishedSemaphore[mCurrentFrame];
1563 const vk::Fence noFence = VkFence(VK_NULL_HANDLE);
1564
1565 vk::SubmitInfo submitInfo{};
1566 vk::PipelineStageFlags waitStages[] = {vk::PipelineStageFlagBits::eColorAttachmentOutput};
1567 submitInfo.pWaitSemaphores = includeMixImage > 0.f ? &mRenderFinishedSemaphore[mCurrentFrame] : (!mCommandBufferPerImage ? &mImageAvailableSemaphore[mCurrentFrame] : nullptr);
1568 submitInfo.waitSemaphoreCount = submitInfo.pWaitSemaphores != nullptr ? 1 : 0;
1569 submitInfo.pWaitDstStageMask = waitStages;
1570 submitInfo.commandBufferCount = 1;
1571 submitInfo.pCommandBuffers = &mCurrentCommandBuffer;
1572 submitInfo.signalSemaphoreCount = 1;
1573 submitInfo.pSignalSemaphores = stageFinishedSemaphore;
1574 CHKERR(mGraphicsQueue.submit(1, &submitInfo, includeMixImage > 0 || toMixBuffer || mHasDrawnText || mDownsampleFSAA ? noFence : mInFlightFence[mCurrentFrame]));
1575 if (!toMixBuffer) {
1576 if (includeMixImage > 0.f) {
1578 submitInfo.pWaitSemaphores = stageFinishedSemaphore;
1579 waitStages[0] = {vk::PipelineStageFlagBits::eColorAttachmentOutput};
1580 submitInfo.waitSemaphoreCount = 1;
1581 submitInfo.pCommandBuffers = &mCommandBuffersTexture[mCurrentBufferSet];
1582 stageFinishedSemaphore = &mMixFinishedSemaphore[mCurrentFrame];
1583 submitInfo.pSignalSemaphores = stageFinishedSemaphore;
1584 CHKERR(mGraphicsQueue.submit(1, &submitInfo, mHasDrawnText || mDownsampleFSAA ? noFence : mInFlightFence[mCurrentFrame]));
1585 }
1586
1587 if (mDownsampleFSAA) {
1589 submitInfo.pCommandBuffers = &mCommandBuffersDownsample[mCurrentBufferSet];
1590 submitInfo.pWaitSemaphores = stageFinishedSemaphore;
1591 waitStages[0] = {vk::PipelineStageFlagBits::eTransfer};
1592 submitInfo.waitSemaphoreCount = 1;
1593 stageFinishedSemaphore = &mDownsampleFinishedSemaphore[mCurrentFrame];
1594 submitInfo.pSignalSemaphores = stageFinishedSemaphore;
1595 CHKERR(mGraphicsQueue.submit(1, &submitInfo, mHasDrawnText ? noFence : mInFlightFence[mCurrentFrame]));
1596 }
1597
1598 if (doScreenshot) {
1599 mDevice.waitIdle();
1600 if (mDisplay->cfgR().screenshotScaleFactor != 1) {
1601 readImageToPixels(mDownsampleImages[mCurrentImageIndex].image, vk::ImageLayout::eColorAttachmentOptimal, mScreenshotPixels);
1602 } else {
1603 readImageToPixels(mSwapChainImages[mCurrentImageIndex], vk::ImageLayout::ePresentSrcKHR, mScreenshotPixels);
1604 }
1605 }
1606
1607 if (mHasDrawnText) {
1608 submitInfo.pWaitSemaphores = stageFinishedSemaphore;
1609 waitStages[0] = {vk::PipelineStageFlagBits::eColorAttachmentOutput};
1610 submitInfo.waitSemaphoreCount = 1;
1611 submitInfo.pCommandBuffers = &mCommandBuffersText[mCurrentBufferSet];
1612 stageFinishedSemaphore = &mTextFinishedSemaphore[mCurrentFrame];
1613 submitInfo.pSignalSemaphores = stageFinishedSemaphore;
1614 CHKERR(mGraphicsQueue.submit(1, &submitInfo, mInFlightFence[mCurrentFrame]));
1615 }
1616
1617 CHKERR(mDevice.waitForFences(1, &mInFlightFence[mCurrentFrame], true, UINT64_MAX)); // TODO: I think we need to wait for the fence, so that the image was acquired before we present. Perhaps we can present later to avoid delays
1618 vk::PresentInfoKHR presentInfo{};
1619 presentInfo.waitSemaphoreCount = 1;
1620 presentInfo.pWaitSemaphores = stageFinishedSemaphore;
1621 presentInfo.swapchainCount = 1;
1622 presentInfo.pSwapchains = &mSwapChain;
1623 presentInfo.pImageIndices = &mCurrentImageIndex;
1624 presentInfo.pResults = nullptr;
1625 vk::Result retVal = mGraphicsQueue.presentKHR(&presentInfo);
1626 if (retVal == vk::Result::eErrorOutOfDateKHR) {
1627 mMustUpdateSwapChain = true;
1628 } else {
1629 CHKERR(retVal);
1630 }
1631 }
1632}
1633
1634void GPUDisplayBackendVulkan::downsampleToFramebuffer(vk::CommandBuffer& commandBuffer)
1635{
1636 commandBuffer.reset({});
1637 vk::CommandBufferBeginInfo beginInfo{};
1638 beginInfo.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit;
1639 commandBuffer.begin(beginInfo);
1640
1641 cmdImageMemoryBarrier(commandBuffer, mSwapChainImages[mCurrentImageIndex], {}, vk::AccessFlagBits::eTransferWrite, vk::ImageLayout::eUndefined, vk::ImageLayout::eTransferDstOptimal, vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eTransfer);
1642 cmdImageMemoryBarrier(commandBuffer, mDownsampleImages[mCurrentImageIndex].image, vk::AccessFlagBits::eMemoryRead, vk::AccessFlagBits::eTransferRead, vk::ImageLayout::eColorAttachmentOptimal, vk::ImageLayout::eTransferSrcOptimal, vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eTransfer);
1643
1644 vk::Offset3D blitSizeSrc;
1645 blitSizeSrc.x = mRenderWidth;
1646 blitSizeSrc.y = mRenderHeight;
1647 blitSizeSrc.z = 1;
1648 vk::Offset3D blitSizeDst;
1649 blitSizeDst.x = mScreenWidth;
1650 blitSizeDst.y = mScreenHeight;
1651 blitSizeDst.z = 1;
1652 vk::ImageBlit imageBlitRegion{};
1653 imageBlitRegion.srcSubresource.aspectMask = vk::ImageAspectFlagBits::eColor;
1654 imageBlitRegion.srcSubresource.layerCount = 1;
1655 imageBlitRegion.srcOffsets[1] = blitSizeSrc;
1656 imageBlitRegion.dstSubresource.aspectMask = vk::ImageAspectFlagBits::eColor;
1657 imageBlitRegion.dstSubresource.layerCount = 1;
1658 imageBlitRegion.dstOffsets[1] = blitSizeDst;
1659 commandBuffer.blitImage(mDownsampleImages[mCurrentImageIndex].image, vk::ImageLayout::eTransferSrcOptimal, mSwapChainImages[mCurrentImageIndex], vk::ImageLayout::eTransferDstOptimal, 1, &imageBlitRegion, vk::Filter::eLinear);
1660
1661 cmdImageMemoryBarrier(commandBuffer, mSwapChainImages[mCurrentImageIndex], vk::AccessFlagBits::eTransferWrite, vk::AccessFlagBits::eMemoryRead, vk::ImageLayout::eTransferDstOptimal, vk::ImageLayout::ePresentSrcKHR, vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eTransfer);
1662 cmdImageMemoryBarrier(commandBuffer, mDownsampleImages[mCurrentImageIndex].image, vk::AccessFlagBits::eTransferRead, vk::AccessFlagBits::eMemoryRead, vk::ImageLayout::eUndefined, vk::ImageLayout::eColorAttachmentOptimal, vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eTransfer);
1663
1664 commandBuffer.end();
1665}
1666
1668{
1669 hmm_mat4 proj = HMM_Orthographic(0.f, mScreenWidth, 0.f, mScreenHeight, -1, 1);
1670 writeToBuffer(mUniformBuffersMat[1][mCurrentBufferSet], sizeof(proj), &proj);
1671
1672 mFontVertexBufferHost.clear();
1673 mTextDrawCommands.clear();
1674}
1675
1677{
1678 if (!mHasDrawnText) {
1679 return;
1680 }
1681
1683
1684 vk::CommandBufferBeginInfo beginInfo{};
1685 beginInfo.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit;
1686 mCommandBuffersText[mCurrentBufferSet].begin(beginInfo);
1687
1688 vk::RenderPassBeginInfo renderPassInfo{};
1689 renderPassInfo.renderPass = mRenderPassText;
1691 renderPassInfo.renderArea.offset = vk::Offset2D{0, 0};
1692 renderPassInfo.renderArea.extent = vk::Extent2D{mScreenWidth, mScreenHeight};
1693 renderPassInfo.clearValueCount = 0;
1694 mCommandBuffersText[mCurrentBufferSet].beginRenderPass(renderPassInfo, vk::SubpassContents::eInline);
1695
1698 }
1699 mFontVertexBuffer[mCurrentBufferSet] = createBuffer(mFontVertexBufferHost.size() * sizeof(float), mFontVertexBufferHost.data(), vk::BufferUsageFlagBits::eVertexBuffer, 0);
1700
1701 mCommandBuffersText[mCurrentBufferSet].bindPipeline(vk::PipelineBindPoint::eGraphics, mPipelines[3]);
1702 mCommandBuffersText[mCurrentBufferSet].bindDescriptorSets(vk::PipelineBindPoint::eGraphics, mPipelineLayoutTexture, 0, 1, &mDescriptorSets[1][mCurrentBufferSet], 0, nullptr);
1703 vk::DeviceSize offsets[] = {0};
1705
1706 for (const auto& cmd : mTextDrawCommands) {
1707 mCommandBuffersText[mCurrentBufferSet].pushConstants(mPipelineLayoutTexture, vk::ShaderStageFlagBits::eFragment, 0, sizeof(cmd.color), cmd.color);
1708 mCommandBuffersText[mCurrentBufferSet].draw(cmd.nVertices, 1, cmd.firstVertex, 0);
1709 }
1710
1711 mFontVertexBufferHost.clear();
1712
1713 mCommandBuffersText[mCurrentBufferSet].endRenderPass();
1715}
1716
1717void GPUDisplayBackendVulkan::mixImages(vk::CommandBuffer commandBuffer, float mixSlaveImage)
1718{
1719 hmm_mat4 proj = HMM_Orthographic(0.f, mRenderWidth, 0.f, mRenderHeight, -1, 1);
1720 writeToBuffer(mUniformBuffersMat[2][mCurrentBufferSet], sizeof(proj), &proj);
1721
1722 commandBuffer.reset({});
1723 vk::CommandBufferBeginInfo beginInfo{};
1724 beginInfo.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit;
1725 commandBuffer.begin(beginInfo);
1726
1728 vk::ImageLayout srcLayout = mDownsampleFSAA ? vk::ImageLayout::eColorAttachmentOptimal : vk::ImageLayout::ePresentSrcKHR;
1729 cmdImageMemoryBarrier(commandBuffer, image, {}, vk::AccessFlagBits::eMemoryRead, srcLayout, vk::ImageLayout::eShaderReadOnlyOptimal, vk::PipelineStageFlagBits::eAllCommands, vk::PipelineStageFlagBits::eFragmentShader);
1730
1731 vk::RenderPassBeginInfo renderPassInfo{};
1732 renderPassInfo.renderPass = mRenderPassTexture;
1734 renderPassInfo.renderArea.offset = vk::Offset2D{0, 0};
1735 renderPassInfo.renderArea.extent = vk::Extent2D{mRenderWidth, mRenderHeight};
1736 renderPassInfo.clearValueCount = 0;
1737 commandBuffer.beginRenderPass(renderPassInfo, vk::SubpassContents::eInline);
1738
1739 commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, mPipelines[4]);
1742 }
1743 commandBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, mPipelineLayoutTexture, 0, 1, &mDescriptorSets[2][mCurrentBufferSet], 0, nullptr);
1744 vk::DeviceSize offsets[] = {0};
1745 commandBuffer.bindVertexBuffers(0, 1, &mMixingTextureVertexArray.buffer, offsets);
1746
1747 commandBuffer.pushConstants(mPipelineLayoutTexture, vk::ShaderStageFlagBits::eFragment, 0, sizeof(mixSlaveImage), &mixSlaveImage);
1748 commandBuffer.draw(6, 1, 0, 0);
1749
1750 commandBuffer.endRenderPass();
1751 commandBuffer.end();
1752}
1753
1755{
1757 return;
1758 }
1759 mCurrentCommandBuffer.pushConstants(mPipelineLayout, vk::ShaderStageFlagBits::eFragment, 0, sizeof(color), color.data());
1760}
1761
1763{
1765 return;
1766 }
1767 float size = mDisplay->cfgL().pointSize * mDownsampleFactor * factor;
1768 mCurrentCommandBuffer.pushConstants(mPipelineLayout, vk::ShaderStageFlagBits::eVertex, sizeof(std::array<float, 4>), sizeof(size), &size);
1769}
1770
1772{
1774 return;
1775 }
1776 mCurrentCommandBuffer.setLineWidth(mDisplay->cfgL().lineWidth * mDownsampleFactor * factor);
1777}
1778
1783
1784void GPUDisplayBackendVulkan::addFontSymbol(int32_t symbol, int32_t sizex, int32_t sizey, int32_t offsetx, int32_t offsety, int32_t advance, void* data)
1785{
1786 if (symbol != (int32_t)mFontSymbols.size()) {
1787 throw std::runtime_error("Incorrect symbol ID");
1788 }
1789 mFontSymbols.emplace_back(FontSymbolVulkan{{{sizex, sizey}, {offsetx, offsety}, advance}, nullptr, 0.f, 0.f, 0.f, 0.f});
1790 auto& buffer = mFontSymbols.back().data;
1791 if (sizex && sizey) {
1792 buffer.reset(new char[sizex * sizey]);
1793 memcpy(buffer.get(), data, sizex * sizey);
1794 }
1795}
1796
1798{
1799 int32_t maxSizeX = 0, maxSizeY = 0, maxBigX = 0, maxBigY = 0, maxRowY = 0;
1800 bool smooth = smoothFont();
1801 // Build a mega texture containing all fonts
1802 for (auto& symbol : mFontSymbols) {
1803 maxSizeX = std::max(maxSizeX, symbol.size[0]);
1804 maxSizeY = std::max(maxSizeY, symbol.size[1]);
1805 }
1806 uint32_t nn = ceil(std::sqrt(mFontSymbols.size()));
1807 int32_t sizex = nn * maxSizeX;
1808 int32_t sizey = nn * maxSizeY;
1809 std::unique_ptr<char[]> bigImage{new char[sizex * sizey]};
1810 memset(bigImage.get(), 0, sizex * sizey);
1811 int32_t rowy = 0, colx = 0;
1812 for (uint32_t i = 0; i < mFontSymbols.size(); i++) {
1813 auto& s = mFontSymbols[i];
1814 if (colx + s.size[0] > sizex) {
1815 colx = 0;
1816 rowy += maxRowY;
1817 maxRowY = 0;
1818 }
1819 for (int32_t k = 0; k < s.size[1]; k++) {
1820 for (int32_t j = 0; j < s.size[0]; j++) {
1821 int8_t val = s.data.get()[j + k * s.size[0]];
1822 if (!smooth) {
1823 val = val < 0 ? 0xFF : 0;
1824 }
1825 bigImage.get()[(colx + j) + (rowy + k) * sizex] = val;
1826 }
1827 }
1828 s.data.reset();
1829 s.x0 = colx;
1830 s.x1 = colx + s.size[0];
1831 s.y0 = rowy;
1832 s.y1 = rowy + s.size[1];
1833 maxBigX = std::max(maxBigX, colx + s.size[0]);
1834 maxBigY = std::max(maxBigY, rowy + s.size[1]);
1835 maxRowY = std::max(maxRowY, s.size[1]);
1836 colx += s.size[0];
1837 }
1838 if (maxBigX != sizex) {
1839 for (int32_t y = 1; y < maxBigY; y++) {
1840 memmove(bigImage.get() + y * maxBigX, bigImage.get() + y * sizex, maxBigX);
1841 }
1842 }
1843 sizex = maxBigX;
1844 sizey = maxBigY;
1845 for (uint32_t i = 0; i < mFontSymbols.size(); i++) {
1846 auto& s = mFontSymbols[i];
1847 s.x0 /= sizex;
1848 s.x1 /= sizex;
1849 s.y0 /= sizey;
1850 s.y1 /= sizey;
1851 }
1852
1853 mFontImage = createImage(sizex, sizey, bigImage.get(), sizex * sizey, vk::Format::eR8Unorm);
1855}
1856
1858{
1859 vk::DescriptorImageInfo imageInfo{};
1860 imageInfo.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
1861 imageInfo.imageView = mFontImage.view;
1862 imageInfo.sampler = mTextureSampler;
1863 for (uint32_t i = 0; i < mFramesInFlight; i++) {
1864 vk::WriteDescriptorSet descriptorWrite{};
1865 descriptorWrite.dstSet = mDescriptorSets[1][i];
1866 descriptorWrite.dstBinding = 2;
1867 descriptorWrite.dstArrayElement = 0;
1868 descriptorWrite.descriptorType = vk::DescriptorType::eCombinedImageSampler;
1869 descriptorWrite.descriptorCount = 1;
1870 descriptorWrite.pImageInfo = &imageInfo;
1871 mDevice.updateDescriptorSets(1, &descriptorWrite, 0, nullptr);
1872 }
1873}
1874
1875void GPUDisplayBackendVulkan::OpenGLPrint(const char* s, float x, float y, float* color, float scale)
1876{
1878 return;
1879 }
1880
1881 size_t firstVertex = mFontVertexBufferHost.size() / 4;
1882 if (smoothFont()) {
1883 scale *= 0.25f; // Font size is 48 to have nice bitmap, scale to size 12
1884 }
1885
1886 for (const char* c = s; *c; c++) {
1887 if ((int32_t)*c > (int32_t)mFontSymbols.size()) {
1888 GPUError("Trying to draw unsupported symbol: %d > %d\n", (int32_t)*c, (int32_t)mFontSymbols.size());
1889 continue;
1890 }
1891 const FontSymbolVulkan& sym = mFontSymbols[*c];
1892 if (sym.size[0] && sym.size[1]) {
1893 mHasDrawnText = true;
1894 float xpos = x + sym.offset[0] * scale;
1895 float ypos = y - (sym.size[1] - sym.offset[1]) * scale;
1896 float w = sym.size[0] * scale;
1897 float h = sym.size[1] * scale;
1898 float vertices[6][4] = {
1899 {xpos, mScreenHeight - 1 - ypos, sym.x0, sym.y1},
1900 {xpos, mScreenHeight - 1 - (ypos + h), sym.x0, sym.y0},
1901 {xpos + w, mScreenHeight - 1 - ypos, sym.x1, sym.y1},
1902 {xpos + w, mScreenHeight - 1 - ypos, sym.x1, sym.y1},
1903 {xpos, mScreenHeight - 1 - (ypos + h), sym.x0, sym.y0},
1904 {xpos + w, mScreenHeight - 1 - (ypos + h), sym.x1, sym.y0}};
1905 size_t oldSize = mFontVertexBufferHost.size();
1906 mFontVertexBufferHost.resize(oldSize + 4 * 6);
1907 memcpy(&mFontVertexBufferHost[oldSize], &vertices[0][0], sizeof(vertices));
1908 }
1909 x += (sym.advance >> 6) * scale; // shift is in 1/64th of a pixel
1910 }
1911
1912 size_t nVertices = mFontVertexBufferHost.size() / 4 - firstVertex;
1913
1914 if (nVertices) {
1915 auto& c = mTextDrawCommands;
1916 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]) {
1917 c.back().nVertices += nVertices;
1918 } else {
1919 c.emplace_back(TextDrawCommand{firstVertex, nVertices, {color[0], color[1], color[2], color[3]}});
1920 }
1921 }
1922}
1923
1924void GPUDisplayBackendVulkan::readImageToPixels(vk::Image image, vk::ImageLayout layout, std::vector<char>& pixels)
1925{
1926 uint32_t width = mScreenWidth * mDisplay->cfgR().screenshotScaleFactor;
1927 uint32_t height = mScreenHeight * mDisplay->cfgR().screenshotScaleFactor;
1928 static constexpr int32_t bytesPerPixel = 4;
1929 pixels.resize(width * height * bytesPerPixel);
1930
1931 vk::Image dstImage, dstImage2, src2;
1932 vk::DeviceMemory dstImageMemory, dstImageMemory2;
1933 createImageI(mDevice, mPhysicalDevice, dstImage, dstImageMemory, width, height, vk::Format::eR8G8B8A8Unorm, vk::ImageUsageFlagBits::eTransferDst, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent, vk::ImageTiling::eLinear);
1934 vk::CommandBuffer cmdBuffer = getSingleTimeCommandBuffer();
1935 cmdImageMemoryBarrier(cmdBuffer, image, vk::AccessFlagBits::eMemoryRead, vk::AccessFlagBits::eTransferRead, layout, vk::ImageLayout::eTransferSrcOptimal, vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eTransfer);
1936 if (mDisplay->cfgR().screenshotScaleFactor != 1) {
1937 createImageI(mDevice, mPhysicalDevice, dstImage2, dstImageMemory2, width, height, mSurfaceFormat.format, vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eTransferSrc | vk::ImageUsageFlagBits::eTransferDst, vk::MemoryPropertyFlagBits::eDeviceLocal, vk::ImageTiling::eOptimal);
1938 cmdImageMemoryBarrier(cmdBuffer, dstImage2, {}, vk::AccessFlagBits::eTransferWrite, vk::ImageLayout::eUndefined, vk::ImageLayout::eTransferDstOptimal, vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eTransfer);
1939 vk::Offset3D blitSizeSrc = {(int32_t)mRenderWidth, (int32_t)mRenderHeight, 1};
1940 vk::Offset3D blitSizeDst = {(int32_t)width, (int32_t)height, 1};
1941 vk::ImageBlit imageBlitRegion{};
1942 imageBlitRegion.srcSubresource.aspectMask = vk::ImageAspectFlagBits::eColor;
1943 imageBlitRegion.srcSubresource.layerCount = 1;
1944 imageBlitRegion.srcOffsets[1] = blitSizeSrc;
1945 imageBlitRegion.dstSubresource.aspectMask = vk::ImageAspectFlagBits::eColor;
1946 imageBlitRegion.dstSubresource.layerCount = 1;
1947 imageBlitRegion.dstOffsets[1] = blitSizeDst;
1948 cmdBuffer.blitImage(image, vk::ImageLayout::eTransferSrcOptimal, dstImage2, vk::ImageLayout::eTransferDstOptimal, 1, &imageBlitRegion, vk::Filter::eLinear);
1949 src2 = dstImage2;
1950 cmdImageMemoryBarrier(cmdBuffer, dstImage2, vk::AccessFlagBits::eMemoryRead, vk::AccessFlagBits::eTransferRead, vk::ImageLayout::eTransferDstOptimal, vk::ImageLayout::eTransferSrcOptimal, vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eTransfer);
1951 } else {
1952 src2 = image;
1953 }
1954
1955 cmdImageMemoryBarrier(cmdBuffer, dstImage, {}, vk::AccessFlagBits::eTransferWrite, vk::ImageLayout::eUndefined, vk::ImageLayout::eTransferDstOptimal, vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eTransfer);
1956 vk::ImageCopy imageCopyRegion{};
1957 imageCopyRegion.srcSubresource.aspectMask = vk::ImageAspectFlagBits::eColor;
1958 imageCopyRegion.srcSubresource.layerCount = 1;
1959 imageCopyRegion.dstSubresource.aspectMask = vk::ImageAspectFlagBits::eColor;
1960 imageCopyRegion.dstSubresource.layerCount = 1;
1961 imageCopyRegion.extent.width = width;
1962 imageCopyRegion.extent.height = height;
1963 imageCopyRegion.extent.depth = 1;
1964 cmdBuffer.copyImage(src2, vk::ImageLayout::eTransferSrcOptimal, dstImage, vk::ImageLayout::eTransferDstOptimal, 1, &imageCopyRegion);
1965
1966 cmdImageMemoryBarrier(cmdBuffer, dstImage, vk::AccessFlagBits::eTransferWrite, vk::AccessFlagBits::eMemoryRead, vk::ImageLayout::eTransferDstOptimal, vk::ImageLayout::eGeneral, vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eTransfer);
1967 cmdImageMemoryBarrier(cmdBuffer, image, vk::AccessFlagBits::eTransferRead, vk::AccessFlagBits::eMemoryRead, vk::ImageLayout::eTransferSrcOptimal, layout, vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eTransfer);
1969
1970 vk::ImageSubresource subResource{vk::ImageAspectFlagBits::eColor, 0, 0};
1971 vk::SubresourceLayout subResourceLayout = mDevice.getImageSubresourceLayout(dstImage, subResource);
1972 const char* data;
1973 CHKERR(mDevice.mapMemory(dstImageMemory, 0, VK_WHOLE_SIZE, {}, (void**)&data));
1974 data += subResourceLayout.offset;
1975 for (uint32_t i = 0; i < height; i++) {
1976 memcpy(pixels.data() + i * width * bytesPerPixel, data + (height - i - 1) * width * bytesPerPixel, width * bytesPerPixel);
1977 }
1978 mDevice.unmapMemory(dstImageMemory);
1979 mDevice.freeMemory(dstImageMemory, nullptr);
1980 mDevice.destroyImage(dstImage, nullptr);
1981 if (mDisplay->cfgR().screenshotScaleFactor != 1) {
1982 mDevice.freeMemory(dstImageMemory2, nullptr);
1983 mDevice.destroyImage(dstImage2, nullptr);
1984 }
1985}
1986
1988{
1989 return 32;
1990}
1991
uint64_t vertex
Definition RawEventData.h:9
int32_t i
#define CHKERR(cmd)
#define LOAD_SHADER(file, ext)
int32_t retVal
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.
void OpenGLPrint(const char *s, float x, float y, float *color, float scale) override
std::vector< vk::CommandBuffer > mCommandBuffersMix
std::vector< vk::CommandBuffer > mCommandBuffers
void setMixDescriptor(int32_t descriptorIndex, int32_t imageIndex)
std::vector< vk::Semaphore > mRenderFinishedSemaphore
void prepareDraw(const hmm_mat4 &proj, const hmm_mat4 &view, bool requestScreenshot, bool toMixBuffer, float includeMixImage) override
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
void pointSizeFactor(float factor) override
std::vector< FontSymbolVulkan > mFontSymbols
std::vector< vk::ImageView * > mRenderTargetView
std::vector< vk::Framebuffer > mFramebuffersTexture
void addFontSymbol(int32_t symbol, int32_t sizex, int32_t sizey, int32_t offsetx, int32_t offsety, int32_t advance, void *data) override
std::vector< vk::Framebuffer > mFramebuffersText
void mixImages(vk::CommandBuffer cmdBuffer, float mixSlaveImage)
void recreateRendering(bool forScreenshot=false, bool forMixing=false)
std::vector< VulkanBuffer > mFontVertexBuffer
void endFillCommandBuffer(vk::CommandBuffer &commandBuffer)
uint32_t drawVertices(const vboList &v, const drawType t) override
std::vector< vk::CommandBuffer > mCommandBuffersDownsample
void ActivateColor(std::array< float, 4 > &color) override
std::vector< vk::Semaphore > mMixFinishedSemaphore
std::vector< vk::Semaphore > mTextFinishedSemaphore
std::vector< VulkanBuffer > mUniformBuffersMat[3]
double checkDevice(vk::PhysicalDevice device, const std::vector< const char * > &reqDeviceExtensions)
void updateSwapChainDetails(const vk::PhysicalDevice &device)
void finishDraw(bool doScreenshot, bool toMixBuffer, float includeMixImage) override
void writeToImage(VulkanImage &image, const void *srcData, size_t srcSize)
std::vector< vk::DescriptorSet > mDescriptorSets[3]
vk::DescriptorSetLayout mUniformDescriptorTexture
void downsampleToFramebuffer(vk::CommandBuffer &commandBuffer)
vk::Extent2D chooseSwapExtent(const vk::SurfaceCapabilitiesKHR &capabilities)
std::vector< vk::Framebuffer > mFramebuffers
void readImageToPixels(vk::Image image, vk::ImageLayout layout, std::vector< char > &pixels)
VulkanImage createImage(uint32_t sizex, uint32_t sizey, const void *srcData=nullptr, size_t srcSize=0, vk::Format format=vk::Format::eR8G8B8A8Srgb)
std::vector< vk::Semaphore > mDownsampleFinishedSemaphore
std::vector< TextDrawCommand > mTextDrawCommands
std::unordered_map< std::string, vk::ShaderModule > mShaders
void finishFrame(bool doScreenshot, bool toMixBuffer, float includeMixImage) override
void createSwapChain(bool forScreenshot=false, bool forMixing=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
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
std::vector< vk::CommandBuffer > mCommandBuffersText
void loadDataToGPU(size_t totalVertizes) override
std::vector< VulkanBuffer > mUniformBuffersCol[3]
vecpod< DrawArraysIndirectCommand > mCmdBuffer
std::vector< int32_t > mIndirectSectorOffset
std::vector< char > mScreenshotPixels
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:60
const GPUParam * param()
Definition GPUDisplay.h:74
int32_t updateRenderPipeline() const
Definition GPUDisplay.h:65
const GPUSettingsDisplayRenderer & cfgR() const
Definition GPUDisplay.h:59
vecpod< vtx > * vertexBuffer()
Definition GPUDisplay.h:73
bool drawTextInCompatMode() const
Definition GPUDisplay.h:76
int32_t updateDrawCommands() const
Definition GPUDisplay.h:64
GPUDisplayFrontend * frontend()
Definition GPUDisplay.h:75
const vecpod< uint32_t > * vertexBufferCount() const
Definition GPUDisplay.h:68
const GPUSettingsDisplay & cfg() const
Definition GPUDisplay.h:62
vecpod< int32_t > * vertexBufferStart()
Definition GPUDisplay.h:67
GLeglImageOES image
Definition glcorearb.h:4021
GLint GLenum GLint x
Definition glcorearb.h:403
GLenum func
Definition glcorearb.h:778
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 GLsizei width
Definition glcorearb.h:270
GLenum GLint * range
Definition glcorearb.h:1899
GLint GLint GLsizei GLint GLenum GLenum type
Definition glcorearb.h:275
GLboolean * data
Definition glcorearb.h:298
GLint GLint GLsizei GLint GLenum GLenum const void * pixels
Definition glcorearb.h:275
GLuint GLfloat * val
Definition glcorearb.h:1582
GLsizei const GLenum * attachments
Definition glcorearb.h:2492
GLenum GLuint GLenum GLsizei const GLchar * buf
Definition glcorearb.h:2514
GLubyte GLubyte GLubyte GLubyte w
Definition glcorearb.h:852
GLint GLint GLsizei GLint GLenum format
Definition glcorearb.h:275
GLuint memory
Definition glcorearb.h:5234
GLsizeiptr const void GLenum usage
Definition glcorearb.h:659
#define QGET_LD_BINARY_SYMBOLS(filename)