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