15#define VULKAN_HPP_DISPATCH_LOADER_DYNAMIC 1
16#include <vulkan/vulkan.hpp>
17VULKAN_HPP_DEFAULT_DISPATCH_LOADER_DYNAMIC_STORAGE
31#define GPUCA_DISPLAY_SHADER_TYPE_VULKAN
32#include "GPUDisplayLoadShaders.h"
37 auto tmp_internal_retVal = cmd; \
38 if ((int32_t)tmp_internal_retVal < 0) { \
39 GPUError("VULKAN ERROR: %d: %s (%s: %d)", (int32_t)tmp_internal_retVal, "ERROR", __FILE__, __LINE__); \
40 throw std::runtime_error("Vulkan Failure"); \
53static int32_t checkVulkanLayersSupported(
const std::vector<const char*>& validationLayers)
55 std::vector<vk::LayerProperties> availableLayers = vk::enumerateInstanceLayerProperties();
56 for (
const char* layerName : validationLayers) {
57 bool layerFound =
false;
59 for (
const auto& layerProperties : availableLayers) {
60 if (strcmp(layerName, layerProperties.layerName) == 0) {
73static uint32_t findMemoryType(
uint32_t typeFilter, vk::MemoryPropertyFlags properties, vk::PhysicalDevice physDev)
75 vk::PhysicalDeviceMemoryProperties memProperties = physDev.getMemoryProperties();
77 for (
uint32_t i = 0;
i < memProperties.memoryTypeCount;
i++) {
78 if ((typeFilter & (1 <<
i)) && (memProperties.memoryTypes[
i].propertyFlags & properties) == properties) {
82 if ((properties & vk::MemoryPropertyFlagBits::eDeviceLocal) && (properties & vk::MemoryPropertyFlagBits::eHostVisible)) {
83 return findMemoryType(typeFilter, properties & ~vk::MemoryPropertyFlags(vk::MemoryPropertyFlagBits::eDeviceLocal), physDev);
86 throw std::runtime_error(
"failed to find suitable memory type!");
89static vk::SurfaceFormatKHR chooseSwapSurfaceFormat(
const std::vector<vk::SurfaceFormatKHR>& availableFormats)
91 for (
const auto& availableFormat : availableFormats) {
92 if (availableFormat.format == vk::Format::eB8G8R8A8Unorm && availableFormat.colorSpace == vk::ColorSpaceKHR::eSrgbNonlinear) {
93 return availableFormat;
96 return availableFormats[0];
104 return vk::PresentModeKHR::eFifo;
108 for (vk::PresentModeKHR
mode : {vk::PresentModeKHR::eImmediate, vk::PresentModeKHR::eMailbox, vk::PresentModeKHR::eFifoLatestReady, vk::PresentModeKHR::eFifo}) {
109 if ((
mode == vk::PresentModeKHR::eImmediate && vsync) || (
mode == vk::PresentModeKHR::eFifoLatestReady && !
mFifoLatestReadySupported) || std::find(available.begin(), available.end(),
mode) == available.end()) {
114 GPUError(
"VULKAN ERROR: Desired present mode %s not available, using %s", vsync ?
"MAILBOX" :
"IMMEDIATE", vk::to_string(
mode).c_str());
118 return vk::PresentModeKHR::eFifo;
123 if (capabilities.currentExtent.width != std::numeric_limits<uint32_t>::max()) {
124 return capabilities.currentExtent;
129 actualExtent.width = std::clamp(actualExtent.width, capabilities.minImageExtent.width, capabilities.maxImageExtent.width);
130 actualExtent.height = std::clamp(actualExtent.height, capabilities.minImageExtent.height, capabilities.maxImageExtent.height);
135static void cmdImageMemoryBarrier(vk::CommandBuffer cmdbuffer, vk::Image
image, vk::PipelineStageFlags2 srcStageMask, vk::AccessFlags2 srcAccessMask, vk::PipelineStageFlags2 dstStageMask, vk::AccessFlags2 dstAccessMask, vk::ImageLayout oldLayout, vk::ImageLayout newLayout, vk::ImageAspectFlags aspect = vk::ImageAspectFlagBits::eColor)
137 vk::ImageMemoryBarrier2 barrier{srcStageMask, srcAccessMask, dstStageMask, dstAccessMask, oldLayout, newLayout, VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED,
image, {aspect, 0, 1, 0, 1}};
138 cmdbuffer.pipelineBarrier2(vk::DependencyInfo{{}, 0,
nullptr, 0,
nullptr, 1, &barrier});
141static void cmdBeginRendering(vk::CommandBuffer cmdbuffer,
uint32_t width,
uint32_t height,
const vk::RenderingAttachmentInfo&
color,
const vk::RenderingAttachmentInfo*
depth =
nullptr)
143 cmdbuffer.beginRendering(vk::RenderingInfo{{}, vk::Rect2D{{0, 0}, {
width,
height}}, 1, 0, 1, &
color,
depth});
146 cmdbuffer.setViewport(0, 1, &viewport);
147 cmdbuffer.setScissor(0, 1, &scissor);
152 cmdImageMemoryBarrier(cmdbuffer,
image, vk::PipelineStageFlagBits2::eColorAttachmentOutput, vk::AccessFlagBits2::eColorAttachmentWrite, vk::PipelineStageFlagBits2::eColorAttachmentOutput, vk::AccessFlagBits2::eColorAttachmentRead | vk::AccessFlagBits2::eColorAttachmentWrite, vk::ImageLayout::eColorAttachmentOptimal, vk::ImageLayout::eColorAttachmentOptimal);
153 cmdBeginRendering(cmdbuffer,
width,
height, vk::RenderingAttachmentInfo{view, vk::ImageLayout::eColorAttachmentOptimal});
165 vk::CommandBufferAllocateInfo allocInfo{};
166 allocInfo.level = vk::CommandBufferLevel::ePrimary;
168 allocInfo.commandBufferCount = 1;
169 vk::CommandBuffer commandBuffer =
mDevice.allocateCommandBuffers(allocInfo)[0];
170 vk::CommandBufferBeginInfo beginInfo{};
171 beginInfo.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit;
172 commandBuffer.begin(beginInfo);
173 return commandBuffer;
176template <
class... Args>
180 if (timelineSignalValue) {
190 vk::CommandBufferSubmitInfo commandBufferInfo{commandBuffer};
191 vk::SemaphoreSubmitInfo signalInfo{
mTimelineSemaphore, 0, vk::PipelineStageFlagBits2::eAllCommands};
192 vk::SubmitInfo2 submitInfo{{}, 0,
nullptr, 1, &commandBufferInfo, 1, &signalInfo};
205static vk::ImageView createImageViewI(vk::Device
device, vk::Image
image, vk::Format
format, vk::ImageAspectFlags aspectFlags = vk::ImageAspectFlagBits::eColor, uint32_t mipLevels = 1)
207 vk::ImageViewCreateInfo viewInfo{};
208 viewInfo.image =
image;
209 viewInfo.viewType = vk::ImageViewType::e2D;
211 viewInfo.subresourceRange.aspectMask = aspectFlags;
212 viewInfo.subresourceRange.baseMipLevel = 0;
213 viewInfo.subresourceRange.levelCount = mipLevels;
214 viewInfo.subresourceRange.baseArrayLayer = 0;
215 viewInfo.subresourceRange.layerCount = 1;
216 return device.createImageView(viewInfo,
nullptr);
219static void createImageI(vk::Device
device, vk::PhysicalDevice physicalDevice, vk::Image&
image, vk::DeviceMemory& imageMemory,
uint32_t width,
uint32_t height, vk::Format
format, vk::ImageUsageFlags
usage, vk::MemoryPropertyFlags properties, vk::ImageTiling tiling = vk::ImageTiling::eOptimal, vk::SampleCountFlagBits numSamples = vk::SampleCountFlagBits::e1, vk::ImageLayout layout = vk::ImageLayout::eUndefined,
uint32_t mipLevels = 1)
221 vk::ImageCreateInfo imageInfo{};
222 imageInfo.imageType = vk::ImageType::e2D;
223 imageInfo.extent.width =
width;
224 imageInfo.extent.height =
height;
225 imageInfo.extent.depth = 1;
226 imageInfo.mipLevels = mipLevels;
227 imageInfo.arrayLayers = 1;
228 imageInfo.format =
format;
229 imageInfo.tiling = tiling;
230 imageInfo.initialLayout = layout;
231 imageInfo.usage =
usage;
232 imageInfo.samples = numSamples;
233 imageInfo.sharingMode = vk::SharingMode::eExclusive;
236 vk::MemoryRequirements memRequirements;
237 memRequirements =
device.getImageMemoryRequirements(
image);
239 vk::MemoryAllocateInfo allocInfo{};
240 allocInfo.allocationSize = memRequirements.size;
241 allocInfo.memoryTypeIndex = findMemoryType(memRequirements.memoryTypeBits, properties, physicalDevice);
242 imageMemory =
device.allocateMemory(allocInfo,
nullptr);
247static uint32_t getMaxUsableSampleCount(vk::PhysicalDeviceProperties& physicalDeviceProperties)
249 vk::SampleCountFlags counts = physicalDeviceProperties.limits.framebufferColorSampleCounts & physicalDeviceProperties.limits.framebufferDepthSampleCounts;
250 if (counts & vk::SampleCountFlagBits::e64) {
252 }
else if (counts & vk::SampleCountFlagBits::e32) {
254 }
else if (counts & vk::SampleCountFlagBits::e16) {
256 }
else if (counts & vk::SampleCountFlagBits::e8) {
258 }
else if (counts & vk::SampleCountFlagBits::e4) {
260 }
else if (counts & vk::SampleCountFlagBits::e2) {
266static vk::SampleCountFlagBits getMSAASamplesFlag(
uint32_t msaa)
269 return vk::SampleCountFlagBits::e2;
270 }
else if (msaa == 4) {
271 return vk::SampleCountFlagBits::e4;
272 }
else if (msaa == 8) {
273 return vk::SampleCountFlagBits::e8;
274 }
else if (msaa == 16) {
275 return vk::SampleCountFlagBits::e16;
276 }
else if (msaa == 32) {
277 return vk::SampleCountFlagBits::e32;
278 }
else if (msaa == 64) {
279 return vk::SampleCountFlagBits::e64;
281 return vk::SampleCountFlagBits::e1;
284template <
class T,
class S>
285static inline void clearVector(T&
v,
S func,
bool downsize =
true)
287 std::for_each(
v.begin(),
v.end(),
func);
296static bool hasFeatures(
const T& available,
const T& required)
298 const vk::Bool32*
a =
reinterpret_cast<const vk::Bool32*
>(
reinterpret_cast<const char*
>(&available) +
sizeof(VkBaseOutStructure));
299 const vk::Bool32*
r =
reinterpret_cast<const vk::Bool32*
>(
reinterpret_cast<const char*
>(&required) +
sizeof(VkBaseOutStructure));
300 for (
size_t i = 0;
i < (
sizeof(
T) -
sizeof(VkBaseOutStructure)) /
sizeof(vk::Bool32);
i++) {
309static bool hasFeatures(
const vk::StructureChain<T...>& available,
const vk::StructureChain<T...>& required)
311 return (hasFeatures(available.template get<T>(), required.template get<T>()) && ...);
315static void clearFeatures(vk::StructureChain<T...>&
chain)
317 ((memset(
reinterpret_cast<char*
>(&
chain.template get<T>()) +
sizeof(VkBaseOutStructure), 0,
sizeof(T) -
sizeof(VkBaseOutStructure))), ...);
321static bool enableOptionalFeature(vk::PhysicalDevice
device,
const std::vector<vk::ExtensionProperties>& available, std::initializer_list<const char*> extensions, vk::Bool32 T::* feature,
T& featureStruct,
std::
vector<const
char*>& enabledExtensions,
void*&
chain)
323 for (
const char* ext : extensions) {
324 if (std::none_of(available.begin(), available.end(), [ext](
const auto&
e) { return strcmp(ext, e.extensionName) == 0; })) {
327 if (!(
device.getFeatures2<vk::PhysicalDeviceFeatures2, T>().template get<T>().*feature)) {
330 enabledExtensions.emplace_back(ext);
331 featureStruct.*feature = VK_TRUE;
332 featureStruct.pNext =
chain;
333 chain = &featureStruct;
340static vk::StructureChain<
T...> getFeatures(vk::PhysicalDevice
device,
const vk::StructureChain<T...>&)
342 return device.getFeatures2<
T...>();
348 vk::PhysicalDeviceProperties deviceProperties =
device.getProperties();
349 vk::PhysicalDeviceMemoryProperties memoryProperties =
device.getMemoryProperties();
350 if (deviceProperties.apiVersion < VK_API_VERSION_1_4) {
352 GPUInfo(
"%s ignored, supports only Vulkan %u.%u", &deviceProperties.deviceName[0], VK_API_VERSION_MAJOR(deviceProperties.apiVersion), VK_API_VERSION_MINOR(deviceProperties.apiVersion));
357 std::vector<vk::ExtensionProperties> availableExtensions =
device.enumerateDeviceExtensionProperties(
nullptr);
359 for (
uint32_t i = 0;
i < reqDeviceExtensions.size();
i++) {
360 for (
uint32_t j = 0;
j < availableExtensions.size();
j++) {
361 if (strcmp(reqDeviceExtensions[
i], availableExtensions[
j].extensionName) == 0) {
367 if (extensionsFound < reqDeviceExtensions.size()) {
369 GPUInfo(
"%s ignored due to missing extensions", &deviceProperties.deviceName[0]);
374 if (!hasFeatures(getFeatures(
device, reqDeviceFeatures), reqDeviceFeatures)) {
376 GPUInfo(
"%s ignored due to missing features", &deviceProperties.deviceName[0]);
381 std::vector<vk::QueueFamilyProperties> queueFamilies =
device.getQueueFamilyProperties();
383 for (
uint32_t i = 0;
i < queueFamilies.size();
i++) {
384 if (!(queueFamilies[
i].queueFlags & vk::QueueFlagBits::eGraphics)) {
388 if (!presentSupport) {
397 GPUInfo(
"%s ignored due to missing queue properties", &deviceProperties.deviceName[0]);
405 GPUInfo(
"%s ignored due to incompatible swap chain", &deviceProperties.deviceName[0]);
411 if (deviceProperties.deviceType == vk::PhysicalDeviceType::eDiscreteGpu) {
413 }
else if (deviceProperties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu) {
417 for (
uint32_t i = 0;
i < memoryProperties.memoryHeapCount;
i++) {
418 if (memoryProperties.memoryHeaps[
i].flags & vk::MemoryHeapFlagBits::eDeviceLocal) {
419 score += memoryProperties.memoryHeaps[
i].size;
428 VULKAN_HPP_DEFAULT_DISPATCHER.init(vkGetInstanceProcAddr);
429 vk::ApplicationInfo appInfo{};
430 appInfo.pApplicationName =
"GPU CA Standalone display";
431 appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
432 appInfo.pEngineName =
"GPU CI Standalone Engine";
433 appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
434 appInfo.apiVersion = VK_API_VERSION_1_4;
436 vk::InstanceCreateInfo instanceCreateInfo;
437 instanceCreateInfo.pApplicationInfo = &appInfo;
439 const char** frontendExtensions;
441 std::vector<const char*> reqInstanceExtensions(frontendExtensions, frontendExtensions + frontendExtensionCount);
442 reqInstanceExtensions.insert(reqInstanceExtensions.end(), {VK_EXT_DEBUG_UTILS_EXTENSION_NAME, VK_KHR_GET_SURFACE_CAPABILITIES_2_EXTENSION_NAME, VK_KHR_SURFACE_MAINTENANCE_1_EXTENSION_NAME});
443 std::vector<vk::ExtensionProperties> availableInstanceExtensions = vk::enumerateInstanceExtensionProperties(
nullptr);
445 std::cout <<
"available instance extensions: " << availableInstanceExtensions.size() <<
"\n";
446 for (
const auto& extension : availableInstanceExtensions) {
447 std::cout <<
'\t' << extension.extensionName <<
'\n';
450 for (
const char* ext : reqInstanceExtensions) {
451 if (std::none_of(availableInstanceExtensions.begin(), availableInstanceExtensions.end(), [ext](
const auto&
e) { return strcmp(ext, e.extensionName) == 0; })) {
452 throw std::runtime_error(std::string(
"Required Vulkan instance extension not available: ") + ext);
456 const std::vector<const char*> reqValidationLayers = {
"VK_LAYER_KHRONOS_validation"};
457 auto debugCallback = [](vk::DebugUtilsMessageSeverityFlagBitsEXT messageSeverity, vk::DebugUtilsMessageTypeFlagsEXT messageType,
const vk::DebugUtilsMessengerCallbackDataEXT* pCallbackData,
void* pUserData) -> VkBool32 {
458 static int32_t throwOnError = getenv(
"GPUCA_VULKAN_VALIDATION_THROW") ? atoi(getenv(
"GPUCA_VULKAN_VALIDATION_THROW")) : 0;
459 static bool showVulkanValidationInfo = getenv(
"GPUCA_VULKAN_VALIDATION_INFO") && atoi(getenv(
"GPUCA_VULKAN_VALIDATION_INFO"));
460 switch (messageSeverity) {
461 case vk::DebugUtilsMessageSeverityFlagBitsEXT::eVerbose:
462 if (showVulkanValidationInfo) {
463 GPUInfo(
"%s", pCallbackData->pMessage);
466 case vk::DebugUtilsMessageSeverityFlagBitsEXT::eWarning:
467 GPUWarning(
"%s", pCallbackData->pMessage);
468 if (throwOnError > 1) {
469 throw std::logic_error(
"break_on_validation_warning");
472 case vk::DebugUtilsMessageSeverityFlagBitsEXT::eError:
473 GPUError(
"%s", pCallbackData->pMessage);
475 throw std::logic_error(
"break_on_validation_error");
478 case vk::DebugUtilsMessageSeverityFlagBitsEXT::eInfo:
480 GPUInfo(
"%s", pCallbackData->pMessage);
485 vk::DebugUtilsMessengerCreateInfoEXT debugCreateInfo{};
487 if (checkVulkanLayersSupported(reqValidationLayers)) {
488 throw std::runtime_error(
"Requested validation layer support not available");
490 instanceCreateInfo.enabledLayerCount =
static_cast<uint32_t>(reqValidationLayers.size());
491 instanceCreateInfo.ppEnabledLayerNames = reqValidationLayers.data();
492 instanceCreateInfo.pNext = (VkDebugUtilsMessengerCreateInfoEXT*)&debugCreateInfo;
494 debugCreateInfo.messageSeverity = vk::DebugUtilsMessageSeverityFlagBitsEXT::eVerbose | vk::DebugUtilsMessageSeverityFlagBitsEXT::eWarning | vk::DebugUtilsMessageSeverityFlagBitsEXT::eError;
495 debugCreateInfo.messageType = vk::DebugUtilsMessageTypeFlagBitsEXT::eGeneral | vk::DebugUtilsMessageTypeFlagBitsEXT::eValidation | vk::DebugUtilsMessageTypeFlagBitsEXT::ePerformance;
496 debugCreateInfo.pfnUserCallback = debugCallback;
497 debugCreateInfo.pUserData =
nullptr;
499 instanceCreateInfo.enabledLayerCount = 0;
502 instanceCreateInfo.enabledExtensionCount =
static_cast<uint32_t>(reqInstanceExtensions.size());
503 instanceCreateInfo.ppEnabledExtensionNames = reqInstanceExtensions.data();
505 mInstance = vk::createInstance(instanceCreateInfo,
nullptr);
506 VULKAN_HPP_DEFAULT_DISPATCHER.init(
mInstance);
509 GPUInfo(
"Enabling Vulkan Validation Layers");
514 throw std::runtime_error(
"Frontend does not provide Vulkan surface");
517 const std::vector<const char*> reqDeviceExtensions = {VK_KHR_SWAPCHAIN_EXTENSION_NAME, VK_KHR_SWAPCHAIN_MAINTENANCE_1_EXTENSION_NAME, VK_KHR_PRESENT_ID_EXTENSION_NAME, VK_KHR_PRESENT_WAIT_EXTENSION_NAME};
519 clearFeatures(reqDeviceFeatures);
520 auto& reqFeatures10 = reqDeviceFeatures.get<vk::PhysicalDeviceFeatures2>().features;
521 reqFeatures10.geometryShader = reqFeatures10.wideLines = reqFeatures10.largePoints = reqFeatures10.multiDrawIndirect = VK_TRUE;
522 reqDeviceFeatures.get<vk::PhysicalDeviceVulkan12Features>().timelineSemaphore = VK_TRUE;
523 reqDeviceFeatures.get<vk::PhysicalDeviceVulkan14Features>().pushDescriptor = reqDeviceFeatures.get<vk::PhysicalDeviceVulkan14Features>().maintenance5 = VK_TRUE;
524 reqDeviceFeatures.get<vk::PhysicalDeviceVulkan13Features>().dynamicRendering = reqDeviceFeatures.get<vk::PhysicalDeviceVulkan13Features>().synchronization2 = VK_TRUE;
525 reqDeviceFeatures.get<vk::PhysicalDeviceVulkan13Features>().shaderDemoteToHelperInvocation = VK_TRUE;
526 reqDeviceFeatures.get<vk::PhysicalDeviceSwapchainMaintenance1FeaturesKHR>().swapchainMaintenance1 = VK_TRUE;
527 reqDeviceFeatures.get<vk::PhysicalDevicePresentIdFeaturesKHR>().presentId = VK_TRUE;
528 reqDeviceFeatures.get<vk::PhysicalDevicePresentWaitFeaturesKHR>().presentWait = VK_TRUE;
531 std::vector<vk::PhysicalDevice> devices =
mInstance.enumeratePhysicalDevices();
532 if (devices.size() == 0) {
533 throw std::runtime_error(
"No Vulkan device present!");
535 double bestScore = -1.;
537 double score =
checkDevice(devices[
i], reqDeviceExtensions, reqDeviceFeatures);
539 vk::PhysicalDeviceProperties deviceProperties = devices[
i].getProperties();
540 GPUInfo(
"Available Vulkan device %d: %s - Score %f",
i, &deviceProperties.deviceName[0], score);
542 if (score > bestScore && score > 0) {
549 throw std::runtime_error(
"Invalid Vulkan device selected");
554 throw std::runtime_error(
"All available Vulkan devices unsuited");
557 throw std::runtime_error(
"Selected vulkan device is incompatible");
559 std::vector<const char*> deviceExtensions = reqDeviceExtensions;
560 void* featureChain = &reqDeviceFeatures.get<vk::PhysicalDeviceFeatures2>();
561 const std::vector<vk::ExtensionProperties> availableDeviceExtensions =
mPhysicalDevice.enumerateDeviceExtensionProperties(
nullptr);
562 vk::PhysicalDevicePresentModeFifoLatestReadyFeaturesKHR fifoLatestReadyFeatures{};
563 mFifoLatestReadySupported = enableOptionalFeature(
mPhysicalDevice, availableDeviceExtensions, {VK_KHR_PRESENT_MODE_FIFO_LATEST_READY_EXTENSION_NAME, VK_EXT_PRESENT_MODE_FIFO_LATEST_READY_EXTENSION_NAME}, &vk::PhysicalDevicePresentModeFifoLatestReadyFeaturesKHR::presentModeFifoLatestReady, fifoLatestReadyFeatures, deviceExtensions, featureChain);
566 vk::PhysicalDeviceProperties deviceProperties =
mPhysicalDevice.getProperties();
567 vk::FormatProperties depth32FormatProperties =
mPhysicalDevice.getFormatProperties(vk::Format::eD32Sfloat);
568 vk::FormatProperties depth64FormatProperties =
mPhysicalDevice.getFormatProperties(vk::Format::eD32SfloatS8Uint);
569 GPUInfo(
"Using physical Vulkan device %s", &deviceProperties.deviceName[0]);
574 mMaxRenderSize = std::min({deviceProperties.limits.maxImageDimension2D, deviceProperties.limits.maxFramebufferWidth, deviceProperties.limits.maxFramebufferHeight});
575 mZSupported = (bool)(depth32FormatProperties.optimalTilingFeatures & vk::FormatFeatureFlagBits::eDepthStencilAttachment);
576 mStencilSupported = (bool)(depth64FormatProperties.optimalTilingFeatures & vk::FormatFeatureFlagBits::eDepthStencilAttachment);
582 vk::DeviceQueueCreateInfo queueCreateInfo{};
584 queueCreateInfo.queueCount = 1;
585 float queuePriority = 1.0f;
586 queueCreateInfo.pQueuePriorities = &queuePriority;
587 vk::DeviceCreateInfo deviceCreateInfo{};
588 deviceCreateInfo.pQueueCreateInfos = &queueCreateInfo;
589 deviceCreateInfo.queueCreateInfoCount = 1;
590 deviceCreateInfo.pNext = featureChain;
591 deviceCreateInfo.pEnabledFeatures =
nullptr;
592 deviceCreateInfo.enabledExtensionCount =
static_cast<uint32_t>(deviceExtensions.size());
593 deviceCreateInfo.ppEnabledExtensionNames = deviceExtensions.data();
595 VULKAN_HPP_DEFAULT_DISPATCHER.init(
mDevice);
598 vk::CommandPoolCreateInfo poolInfo{};
599 poolInfo.flags = vk::CommandPoolCreateFlagBits::eResetCommandBuffer;
620 vk::CommandBufferAllocateInfo allocInfo{};
622 allocInfo.level = vk::CommandBufferLevel::ePrimary;
647 vk::SemaphoreCreateInfo semaphoreInfo{};
652 vk::SemaphoreTypeCreateInfo timelineTypeInfo{vk::SemaphoreType::eTimeline, 0};
653 semaphoreInfo.pNext = &timelineTypeInfo;
667 mPresentFences.emplace_back(
mDevice.createFence(vk::FenceCreateInfo{vk::FenceCreateFlagBits::eSignaled},
nullptr));
675 if (
retVal != vk::Result::eTimeout) {
697 vk::DescriptorSetLayoutBinding uboLayoutBindingMat{};
698 uboLayoutBindingMat.binding = 0;
699 uboLayoutBindingMat.descriptorType = vk::DescriptorType::eUniformBuffer;
700 uboLayoutBindingMat.descriptorCount = 1;
701 uboLayoutBindingMat.stageFlags = vk::ShaderStageFlagBits::eVertex;
702 vk::DescriptorSetLayoutBinding samplerLayoutBinding{};
703 samplerLayoutBinding.binding = 2;
704 samplerLayoutBinding.descriptorCount = 1;
705 samplerLayoutBinding.descriptorType = vk::DescriptorType::eCombinedImageSampler;
706 samplerLayoutBinding.stageFlags = vk::ShaderStageFlagBits::eFragment;
707 vk::DescriptorSetLayoutBinding bindings[2] = {uboLayoutBindingMat, samplerLayoutBinding};
709 vk::DescriptorSetLayoutCreateInfo layoutInfo{};
710 layoutInfo.flags = vk::DescriptorSetLayoutCreateFlagBits::ePushDescriptor;
711 layoutInfo.bindingCount = 1;
712 layoutInfo.pBindings = bindings;
714 layoutInfo.bindingCount = 2;
744 vk::DescriptorBufferInfo bufferInfo{ubo.
buffer, 0, ubo.
size};
745 vk::DescriptorImageInfo imageInfo{
mTextureSampler, textureView, vk::ImageLayout::eShaderReadOnlyOptimal};
746 const vk::WriteDescriptorSet writes[2] = {{{}, 0, 0, 1, vk::DescriptorType::eUniformBuffer,
nullptr, &bufferInfo}, {{}, 2, 0, 1, vk::DescriptorType::eCombinedImageSampler, &imageInfo}};
747 commandBuffer.pushDescriptorSet(vk::PipelineBindPoint::eGraphics, layout, 0, textureView ? 2 : 1, writes);
754 vk::SamplerCreateInfo samplerInfo{};
755 samplerInfo.magFilter = vk::Filter::eLinear;
756 samplerInfo.minFilter = vk::Filter::eLinear;
757 samplerInfo.addressModeU = vk::SamplerAddressMode::eRepeat;
758 samplerInfo.addressModeV = vk::SamplerAddressMode::eRepeat;
759 samplerInfo.addressModeW = vk::SamplerAddressMode::eRepeat;
760 samplerInfo.compareEnable =
false;
761 samplerInfo.compareOp = vk::CompareOp::eAlways;
762 samplerInfo.borderColor = vk::BorderColor::eIntOpaqueBlack;
763 samplerInfo.unnormalizedCoordinates =
false;
764 samplerInfo.mipmapMode = vk::SamplerMipmapMode::eLinear;
765 samplerInfo.mipLodBias = 0.0f;
766 samplerInfo.minLod = 0.0f;
767 samplerInfo.maxLod = 0.0f;
796 vk::SwapchainCreateInfoKHR swapCreateInfo{};
798 swapCreateInfo.minImageCount = imageCount;
801 swapCreateInfo.imageExtent = extent;
802 swapCreateInfo.imageArrayLayers = 1;
803 swapCreateInfo.imageUsage = vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eTransferSrc | vk::ImageUsageFlagBits::eTransferDst;
804 swapCreateInfo.imageSharingMode = vk::SharingMode::eExclusive;
805 swapCreateInfo.queueFamilyIndexCount = 0;
806 swapCreateInfo.pQueueFamilyIndices =
nullptr;
808 swapCreateInfo.compositeAlpha = vk::CompositeAlphaFlagBitsKHR::eOpaque;
810 swapCreateInfo.clipped =
true;
811 swapCreateInfo.oldSwapchain = oldSwapChain;
812 vk::SwapchainPresentScalingCreateInfoKHR scalingInfo{};
814 const vk::SurfacePresentModeKHR surfacePresentMode{
mPresentMode};
815 const auto caps =
mPhysicalDevice.getSurfaceCapabilities2KHR<vk::SurfaceCapabilities2KHR, vk::SurfacePresentScalingCapabilitiesKHR>(vk::PhysicalDeviceSurfaceInfo2KHR{
mSurface, &surfacePresentMode}).get<vk::SurfacePresentScalingCapabilitiesKHR>();
816 auto gravity = [](vk::PresentGravityFlagsKHR
f) {
return (
f & vk::PresentGravityFlagBitsKHR::eCentered) ? vk::PresentGravityFlagBitsKHR::eCentered : ((
f & vk::PresentGravityFlagBitsKHR::eMin) ? vk::PresentGravityFlagBitsKHR::eMin : vk::PresentGravityFlagsKHR(
f & vk::PresentGravityFlagBitsKHR::eMax)); };
817 scalingInfo.scalingBehavior = (caps.supportedPresentScaling & vk::PresentScalingFlagBitsKHR::eAspectRatioStretch) ? vk::PresentScalingFlagBitsKHR::eAspectRatioStretch : vk::PresentScalingFlagsKHR(caps.supportedPresentScaling & vk::PresentScalingFlagBitsKHR::eStretch);
818 scalingInfo.presentGravityX = gravity(caps.supportedPresentGravityX);
819 scalingInfo.presentGravityY = gravity(caps.supportedPresentGravityY);
820 if (scalingInfo.scalingBehavior && scalingInfo.presentGravityX && scalingInfo.presentGravityY) {
821 swapCreateInfo.pNext = &scalingInfo;
828 mDevice.destroySwapchainKHR(oldSwapChain,
nullptr);
835 throw std::runtime_error(
"Too many swapchain images");
858 cmdImageMemoryBarrier(
mCommandBuffersPresent[
i],
mSwapChainImages[
i], vk::PipelineStageFlagBits2::eColorAttachmentOutput, vk::AccessFlagBits2::eColorAttachmentWrite, vk::PipelineStageFlagBits2::eNone, vk::AccessFlagBits2::eNone, vk::ImageLayout::eColorAttachmentOptimal, vk::ImageLayout::ePresentSrcKHR);
866 if (!keepSwapChain) {
877 if (!needUpdateOffscreenBuffers) {
885 if (needUpdateSwapChain) {
919 mZImages.resize(imageCountWithMixImages);
925 for (
uint32_t i = 0;
i < imageCountWithMixImages;
i++) {
933 vk::ImageUsageFlags
usage = vk::ImageUsageFlagBits::eColorAttachment;
935 usage |= vk::ImageUsageFlagBits::eSampled;
938 usage |= vk::ImageUsageFlagBits::eTransferSrc;
949 createImageI(
mDevice,
mPhysicalDevice,
mMSAAImages[
i].
image,
mMSAAImages[
i].
memory,
mRenderWidth,
mRenderHeight,
mSurfaceFormat.format, vk::ImageUsageFlagBits::eColorAttachment, vk::MemoryPropertyFlagBits::eDeviceLocal, vk::ImageTiling::eOptimal,
mMSAASampleCount);
953 createImageI(
mDevice,
mPhysicalDevice,
mZImages[
i].
image,
mZImages[
i].
memory,
mRenderWidth,
mRenderHeight, vk::Format::eD32Sfloat, vk::ImageUsageFlagBits::eDepthStencilAttachment, vk::MemoryPropertyFlagBits::eDeviceLocal, vk::ImageTiling::eOptimal,
mMSAASampleCount);
959 float vertices[6][4] = {
988 vk::PipelineShaderStageCreateInfo shaderStages[2] = {vk::PipelineShaderStageCreateInfo{}, vk::PipelineShaderStageCreateInfo{}};
989 vk::PipelineShaderStageCreateInfo& vertShaderStageInfo = shaderStages[0];
990 vertShaderStageInfo.stage = vk::ShaderStageFlagBits::eVertex;
992 vertShaderStageInfo.pName =
"main";
993 vk::PipelineShaderStageCreateInfo& fragShaderStageInfo = shaderStages[1];
994 fragShaderStageInfo.stage = vk::ShaderStageFlagBits::eFragment;
996 fragShaderStageInfo.pName =
"main";
998 vk::VertexInputBindingDescription bindingDescription{};
999 bindingDescription.binding = 0;
1001 bindingDescription.inputRate = vk::VertexInputRate::eVertex;
1003 vk::VertexInputAttributeDescription attributeDescriptions{};
1004 attributeDescriptions.binding = 0;
1005 attributeDescriptions.location = 0;
1007 attributeDescriptions.offset = 0;
1009 vk::PipelineVertexInputStateCreateInfo vertexInputInfo{};
1010 vertexInputInfo.vertexBindingDescriptionCount = 1;
1011 vertexInputInfo.pVertexBindingDescriptions = &bindingDescription;
1012 vertexInputInfo.vertexAttributeDescriptionCount = 1;
1013 vertexInputInfo.pVertexAttributeDescriptions = &attributeDescriptions;
1014 vk::PipelineInputAssemblyStateCreateInfo inputAssembly{};
1016 inputAssembly.primitiveRestartEnable =
false;
1018 vk::PipelineViewportStateCreateInfo viewportState{};
1019 viewportState.viewportCount = 1;
1020 viewportState.scissorCount = 1;
1022 vk::PipelineRasterizationStateCreateInfo rasterizer{};
1023 rasterizer.depthClampEnable =
false;
1024 rasterizer.rasterizerDiscardEnable =
false;
1025 rasterizer.polygonMode = vk::PolygonMode::eFill;
1027 rasterizer.cullMode = vk::CullModeFlagBits::eBack;
1028 rasterizer.frontFace = vk::FrontFace::eClockwise;
1029 rasterizer.depthBiasEnable =
false;
1030 rasterizer.depthBiasConstantFactor = 0.0f;
1031 rasterizer.depthBiasClamp = 0.0f;
1032 rasterizer.depthBiasSlopeFactor = 0.0f;
1034 vk::PipelineMultisampleStateCreateInfo multisampling{};
1035 multisampling.sampleShadingEnable =
false;
1037 multisampling.minSampleShading = 1.0f;
1038 multisampling.pSampleMask =
nullptr;
1039 multisampling.alphaToCoverageEnable =
false;
1040 multisampling.alphaToOneEnable =
false;
1042 vk::PipelineColorBlendAttachmentState colorBlendAttachment{};
1043 colorBlendAttachment.colorWriteMask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA;
1045 colorBlendAttachment.colorWriteMask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA;
1046 colorBlendAttachment.srcColorBlendFactor = vk::BlendFactor::eSrcAlpha;
1047 colorBlendAttachment.dstColorBlendFactor = vk::BlendFactor::eOneMinusSrcAlpha;
1048 colorBlendAttachment.colorBlendOp = vk::BlendOp::eAdd;
1049 colorBlendAttachment.srcAlphaBlendFactor = vk::BlendFactor::eOneMinusSrcAlpha;
1050 colorBlendAttachment.dstAlphaBlendFactor = vk::BlendFactor::eZero;
1051 colorBlendAttachment.alphaBlendOp = vk::BlendOp::eAdd;
1053 vk::PipelineColorBlendStateCreateInfo colorBlending{};
1054 colorBlending.logicOpEnable =
false;
1055 colorBlending.logicOp = vk::LogicOp::eCopy;
1056 colorBlending.attachmentCount = 1;
1057 colorBlending.pAttachments = &colorBlendAttachment;
1058 colorBlending.blendConstants[0] = 0.0f;
1059 colorBlending.blendConstants[1] = 0.0f;
1060 colorBlending.blendConstants[2] = 0.0f;
1061 colorBlending.blendConstants[3] = 0.0f;
1063 vk::PipelineDepthStencilStateCreateInfo depthStencil{};
1064 depthStencil.depthTestEnable =
true;
1065 depthStencil.depthWriteEnable =
true;
1066 depthStencil.depthCompareOp = vk::CompareOp::eLess;
1067 depthStencil.depthBoundsTestEnable =
false;
1068 depthStencil.stencilTestEnable =
false;
1070 vk::DynamicState dynamicStates[] = {vk::DynamicState::eViewport, vk::DynamicState::eScissor, vk::DynamicState::eLineWidth};
1071 vk::PipelineDynamicStateCreateInfo dynamicState{};
1073 dynamicState.pDynamicStates = dynamicStates;
1075 vk::PushConstantRange pushConstantRanges[2] = {vk::PushConstantRange{}, vk::PushConstantRange{}};
1076 pushConstantRanges[0].stageFlags = vk::ShaderStageFlagBits::eFragment;
1077 pushConstantRanges[0].offset = 0;
1078 pushConstantRanges[0].size =
sizeof(
float) * 4;
1079 pushConstantRanges[1].stageFlags = vk::ShaderStageFlagBits::eVertex;
1080 pushConstantRanges[1].offset = pushConstantRanges[0].size;
1081 pushConstantRanges[1].size = 4 *
sizeof(
float);
1082 vk::PipelineLayoutCreateInfo pipelineLayoutInfo{};
1083 pipelineLayoutInfo.setLayoutCount = 1;
1085 pipelineLayoutInfo.pushConstantRangeCount = 2;
1086 pipelineLayoutInfo.pPushConstantRanges = pushConstantRanges;
1088 pipelineLayoutInfo.setLayoutCount = 1;
1092 vk::GraphicsPipelineCreateInfo pipelineInfo{};
1093 pipelineInfo.stageCount = 2;
1094 pipelineInfo.pVertexInputState = &vertexInputInfo;
1095 pipelineInfo.pInputAssemblyState = &inputAssembly;
1096 pipelineInfo.pViewportState = &viewportState;
1097 pipelineInfo.pRasterizationState = &rasterizer;
1098 pipelineInfo.pMultisampleState = &multisampling;
1100 pipelineInfo.pColorBlendState = &colorBlending;
1101 pipelineInfo.pDynamicState = &dynamicState;
1103 vk::PipelineRenderingCreateInfo renderingInfo{0, 1, &
mSurfaceFormat.format};
1104 pipelineInfo.pNext = &renderingInfo;
1105 pipelineInfo.pStages = shaderStages;
1106 pipelineInfo.basePipelineHandle = VkPipeline(VK_NULL_HANDLE);
1107 pipelineInfo.basePipelineIndex = -1;
1110 static constexpr vk::PrimitiveTopology
types[3] = {vk::PrimitiveTopology::ePointList, vk::PrimitiveTopology::eLineList, vk::PrimitiveTopology::eLineStrip};
1113 rasterizer.cullMode = vk::CullModeFlagBits::eNone;
1114 vertexInputInfo.vertexBindingDescriptionCount = vertexInputInfo.vertexAttributeDescriptionCount = 0;
1115 inputAssembly.topology = vk::PrimitiveTopology::eTriangleList;
1116 vertShaderStageInfo.pNext = &
mShaders.at(
"vertexFullscreen");
1117 fragShaderStageInfo.pNext = &
mShaders.at(
"fragmentDownsample");
1118 dynamicState.dynamicStateCount = 2;
1120 renderingInfo.depthAttachmentFormat = vk::Format::eUndefined;
1121 pipelineInfo.pDepthStencilState =
nullptr;
1122 colorBlendAttachment.blendEnable =
false;
1123 multisampling.rasterizationSamples = vk::SampleCountFlagBits::e1;
1124 }
else if (
i == 4) {
1125 bindingDescription.stride = 4 *
sizeof(
float);
1126 attributeDescriptions.format = vk::Format::eR32G32B32A32Sfloat;
1127 inputAssembly.topology = vk::PrimitiveTopology::eTriangleList;
1128 vertShaderStageInfo.pNext = &
mShaders.at(
"vertexTexture");
1129 fragShaderStageInfo.pNext = &
mShaders.at(
"fragmentTexture");
1130 dynamicState.dynamicStateCount = 2;
1132 renderingInfo.depthAttachmentFormat = vk::Format::eUndefined;
1133 pipelineInfo.pDepthStencilState =
nullptr;
1134 colorBlendAttachment.blendEnable =
true;
1135 multisampling.rasterizationSamples = vk::SampleCountFlagBits::e1;
1136 }
else if (
i == 3) {
1137 bindingDescription.stride = 4 *
sizeof(
float);
1138 attributeDescriptions.format = vk::Format::eR32G32B32A32Sfloat;
1139 inputAssembly.topology = vk::PrimitiveTopology::eTriangleList;
1140 vertShaderStageInfo.pNext = &
mShaders.at(
"vertexTexture");
1141 fragShaderStageInfo.pNext = &
mShaders.at(
"fragmentText");
1142 dynamicState.dynamicStateCount = 2;
1144 renderingInfo.depthAttachmentFormat = vk::Format::eUndefined;
1145 pipelineInfo.pDepthStencilState =
nullptr;
1146 colorBlendAttachment.blendEnable =
true;
1147 multisampling.rasterizationSamples = vk::SampleCountFlagBits::e1;
1149 bindingDescription.stride = 3 *
sizeof(
float);
1150 attributeDescriptions.format = vk::Format::eR32G32B32Sfloat;
1152 inputAssembly.topology =
types[drawIdx];
1153 vertShaderStageInfo.pNext = &
mShaders.at(
i < 5 ? (drawIdx == 0 ?
"vertexPoint" :
"vertex") : (drawIdx == 0 ?
"vertexSmoothPoint" :
"vertexSmoothLine"));
1154 fragShaderStageInfo.pNext = &
mShaders.at(
i < 5 ?
"fragment" : (drawIdx == 0 ?
"fragmentSmoothPoint" :
"fragmentSmoothLine"));
1156 renderingInfo.depthAttachmentFormat =
mZActive ? vk::Format::eD32Sfloat : vk::Format::eUndefined;
1157 pipelineInfo.pDepthStencilState =
mZActive ? &depthStencil :
nullptr;
1158 dynamicState.dynamicStateCount = 3;
1159 colorBlendAttachment.blendEnable =
true;
1169 commandBuffer.reset({});
1171 vk::CommandBufferBeginInfo beginInfo{};
1172 beginInfo.flags = {};
1173 commandBuffer.begin(beginInfo);
1177 const vk::PipelineStageFlags2 prevStages = vk::PipelineStageFlagBits2::eColorAttachmentOutput | vk::PipelineStageFlagBits2::eTransfer | vk::PipelineStageFlagBits2::eFragmentShader;
1178 cmdImageMemoryBarrier(commandBuffer,
mRenderTargetImage[idx], prevStages, vk::AccessFlagBits2::eColorAttachmentWrite | vk::AccessFlagBits2::eTransferWrite, vk::PipelineStageFlagBits2::eColorAttachmentOutput, vk::AccessFlagBits2::eColorAttachmentWrite, vk::ImageLayout::eUndefined, vk::ImageLayout::eColorAttachmentOptimal);
1180 cmdImageMemoryBarrier(commandBuffer,
mMSAAImages[idx].
image, vk::PipelineStageFlagBits2::eColorAttachmentOutput, vk::AccessFlagBits2::eColorAttachmentWrite, vk::PipelineStageFlagBits2::eColorAttachmentOutput, vk::AccessFlagBits2::eColorAttachmentWrite, vk::ImageLayout::eUndefined, vk::ImageLayout::eColorAttachmentOptimal);
1183 const vk::PipelineStageFlags2 depthStages = vk::PipelineStageFlagBits2::eEarlyFragmentTests | vk::PipelineStageFlagBits2::eLateFragmentTests;
1184 cmdImageMemoryBarrier(commandBuffer,
mZImages[idx].
image, depthStages, vk::AccessFlagBits2::eDepthStencilAttachmentWrite, depthStages, vk::AccessFlagBits2::eDepthStencilAttachmentRead | vk::AccessFlagBits2::eDepthStencilAttachmentWrite, vk::ImageLayout::eUndefined, vk::ImageLayout::eDepthStencilAttachmentOptimal, vk::ImageAspectFlagBits::eDepth);
1187 vk::RenderingAttachmentInfo colorAttachment{msaa ?
mMSAAImages[idx].view : *
mRenderTargetView[idx], vk::ImageLayout::eColorAttachmentOptimal};
1188 colorAttachment.loadOp = vk::AttachmentLoadOp::eClear;
1189 colorAttachment.storeOp = msaa ? vk::AttachmentStoreOp::eDontCare : vk::AttachmentStoreOp::eStore;
1190 colorAttachment.clearValue.color =
mDisplay->
cfgL().invertColors ? vk::ClearColorValue{std::array<float, 4>{1.0f, 1.0f, 1.0f, 1.0f}} : vk::ClearColorValue{std::array<float, 4>{0.0f, 0.0f, 0.0f, 1.0f}};
1192 colorAttachment.resolveMode = vk::ResolveModeFlagBits::eAverage;
1194 colorAttachment.resolveImageLayout = vk::ImageLayout::eColorAttachmentOptimal;
1196 vk::RenderingAttachmentInfo depthAttachment{
mZActive ?
mZImages[idx].view : vk::ImageView{}, vk::ImageLayout::eDepthStencilAttachmentOptimal};
1197 depthAttachment.loadOp = vk::AttachmentLoadOp::eClear;
1198 depthAttachment.storeOp = vk::AttachmentStoreOp::eDontCare;
1199 depthAttachment.clearValue.depthStencil = vk::ClearDepthStencilValue{1.0f, 0};
1202 vk::DeviceSize
offsets[] = {0};
1208 commandBuffer.pushConstants(
mPipelineLayout, vk::ShaderStageFlagBits::eVertex, 6 *
sizeof(
float),
sizeof(viewport), viewport);
1213 commandBuffer.endRendering();
1214 commandBuffer.end();
1226#define LOAD_SHADER(file, ext) \
1227 mShaders[#file] = vk::ShaderModuleCreateInfo { {}, _binary_vulkan_##file##_##ext##_spv_len, reinterpret_cast<const uint32_t*>(_binary_vulkan_##file##_##ext##_spv_start) }
1252 auto tmp =
createBuffer(
size, srcData, vk::BufferUsageFlagBits::eTransferSrc, 0);
1255 vk::BufferCopy copyRegion{};
1256 copyRegion.size =
size;
1257 commandBuffer.copyBuffer(tmp.buffer,
buffer.buffer, 1, ©Region);
1266 vk::MemoryPropertyFlags properties;
1268 properties |= vk::MemoryPropertyFlagBits::eDeviceLocal;
1270 if (deviceMemory == 0 || deviceMemory == 2) {
1271 properties |= (vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
1273 if (deviceMemory == 1) {
1274 type |= vk::BufferUsageFlagBits::eTransferDst;
1278 vk::BufferCreateInfo bufferInfo{};
1279 bufferInfo.size =
size;
1280 bufferInfo.usage =
type;
1281 bufferInfo.sharingMode = vk::SharingMode::eExclusive;
1284 vk::MemoryRequirements memRequirements;
1285 memRequirements =
mDevice.getBufferMemoryRequirements(
buffer.buffer);
1286 vk::MemoryAllocateInfo allocInfo{};
1287 allocInfo.allocationSize = memRequirements.size;
1288 allocInfo.memoryTypeIndex = findMemoryType(memRequirements.memoryTypeBits, properties,
mPhysicalDevice);
1294 buffer.deviceMemory = deviceMemory;
1295 if (deviceMemory != 1) {
1299 if (srcData !=
nullptr) {
1328 auto tmp =
createBuffer(srcSize, srcData, vk::BufferUsageFlagBits::eTransferSrc, 0);
1331 cmdImageMemoryBarrier(commandBuffer,
image.image, vk::PipelineStageFlagBits2::eNone, vk::AccessFlagBits2::eNone, vk::PipelineStageFlagBits2::eTransfer, vk::AccessFlagBits2::eTransferWrite, vk::ImageLayout::eUndefined, vk::ImageLayout::eTransferDstOptimal);
1332 vk::BufferImageCopy region{};
1333 region.bufferOffset = 0;
1334 region.bufferRowLength = 0;
1335 region.bufferImageHeight = 0;
1336 region.imageSubresource.aspectMask = vk::ImageAspectFlagBits::eColor;
1337 region.imageSubresource.mipLevel = 0;
1338 region.imageSubresource.baseArrayLayer = 0;
1339 region.imageSubresource.layerCount = 1;
1340 region.imageOffset = vk::Offset3D{0, 0, 0};
1341 region.imageExtent = vk::Extent3D{
image.sizex,
image.sizey, 1};
1342 commandBuffer.copyBufferToImage(tmp.buffer,
image.image, vk::ImageLayout::eTransferDstOptimal, 1, ®ion);
1343 cmdImageMemoryBarrier(commandBuffer,
image.image, vk::PipelineStageFlagBits2::eTransfer, vk::AccessFlagBits2::eTransferWrite, vk::PipelineStageFlagBits2::eFragmentShader, vk::AccessFlagBits2::eShaderSampledRead, vk::ImageLayout::eTransferDstOptimal, vk::ImageLayout::eShaderReadOnlyOptimal);
1352 createImageI(
mDevice,
mPhysicalDevice,
image.image,
image.memory, sizex, sizey,
format, vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled, vk::MemoryPropertyFlagBits::eDeviceLocal, vk::ImageTiling::eOptimal, vk::SampleCountFlagBits::e1);
1356 image.sizex = sizex;
1357 image.sizey = sizey;
1435 if (totalVertizes) {
1450 auto first = std::get<0>(
v);
1451 auto count = std::get<1>(
v);
1485 if (includeMixImage == 0.f) {
1489 const vk::Result
retVal = (vk::Result)VULKAN_HPP_DEFAULT_DISPATCHER.vkWaitForPresentKHR(
static_cast<VkDevice
>(
mDevice),
static_cast<VkSwapchainKHR
>(
mSwapChain),
mLastPresentId - 1, 100'000'000);
1491 if (
retVal != vk::Result::eTimeout &&
retVal != vk::Result::eErrorOutOfDateKHR) {
1495 auto getImage = [&]() {
1499 vk::Result
retVal = vk::Result::eSuccess;
1504 if (!mustUpdateSwapChain) {
1506 if (
retVal == vk::Result::eErrorOutOfDateKHR) {
1510 if (mustUpdateSwapChain) {
1529 const hmm_mat4 modelViewProj = proj * view;
1530 static_assert(
sizeof(modelViewProj) ==
sizeof(
mLastMVP));
1553 if (
retVal == vk::Result::eSuboptimalKHR) {
1576 if (includeMixImage > 0.f) {
1586 vk::SubmitInfo2 submitInfo{{}, 1, &waitInfo};
1590 queueSubmit(
nullptr, 1, &submitInfo, VkFence(VK_NULL_HANDLE));
1598 submitInfo.waitSemaphoreInfoCount = 0;
1607 submitInfo.signalSemaphoreInfoCount = 2;
1608 submitInfo.pSignalSemaphoreInfos = signalInfos;
1611 vk::PresentInfoKHR presentInfo{};
1612 presentInfo.waitSemaphoreCount = 1;
1614 presentInfo.swapchainCount = 1;
1617 presentInfo.pResults =
nullptr;
1619 vk::PresentIdKHR presentIdInfo{1, &presentId};
1621 presentInfo.pNext = &presentIdInfo;
1624 vk::SwapchainPresentFenceInfoKHR presentFenceInfo{};
1627 presentInfo.pNext = &presentFenceInfo;
1635 if (
retVal != vk::Result::eErrorOutOfDateKHR) {
1643 commandBuffer.reset({});
1644 vk::CommandBufferBeginInfo beginInfo{};
1645 beginInfo.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit;
1646 commandBuffer.begin(beginInfo);
1649 cmdImageMemoryBarrier(commandBuffer,
mSwapChainImages[
mCurrentImageIndex], vk::PipelineStageFlagBits2::eColorAttachmentOutput, vk::AccessFlagBits2::eNone, vk::PipelineStageFlagBits2::eColorAttachmentOutput, vk::AccessFlagBits2::eColorAttachmentWrite, vk::ImageLayout::eUndefined, vk::ImageLayout::eColorAttachmentOptimal);
1650 cmdImageMemoryBarrier(commandBuffer,
mDownsampleImages[
mCurrentImageIndex].
image, vk::PipelineStageFlagBits2::eColorAttachmentOutput, vk::AccessFlagBits2::eColorAttachmentWrite, vk::PipelineStageFlagBits2::eFragmentShader, vk::AccessFlagBits2::eShaderSampledRead, vk::ImageLayout::eColorAttachmentOptimal, vk::ImageLayout::eShaderReadOnlyOptimal);
1652 commandBuffer.end();
1655 cmdImageMemoryBarrier(commandBuffer,
mSwapChainImages[
mCurrentImageIndex], vk::PipelineStageFlagBits2::eTransfer, vk::AccessFlagBits2::eNone, vk::PipelineStageFlagBits2::eTransfer, vk::AccessFlagBits2::eTransferWrite, vk::ImageLayout::eUndefined, vk::ImageLayout::eTransferDstOptimal);
1656 cmdImageMemoryBarrier(commandBuffer,
mDownsampleImages[
mCurrentImageIndex].
image, vk::PipelineStageFlagBits2::eColorAttachmentOutput, vk::AccessFlagBits2::eColorAttachmentWrite, vk::PipelineStageFlagBits2::eTransfer, vk::AccessFlagBits2::eTransferRead, vk::ImageLayout::eColorAttachmentOptimal, vk::ImageLayout::eTransferSrcOptimal);
1658 vk::Offset3D blitSizeSrc;
1662 vk::Offset3D blitSizeDst;
1666 vk::ImageBlit imageBlitRegion{};
1667 imageBlitRegion.srcSubresource.aspectMask = vk::ImageAspectFlagBits::eColor;
1668 imageBlitRegion.srcSubresource.layerCount = 1;
1669 imageBlitRegion.srcOffsets[1] = blitSizeSrc;
1670 imageBlitRegion.dstSubresource.aspectMask = vk::ImageAspectFlagBits::eColor;
1671 imageBlitRegion.dstSubresource.layerCount = 1;
1672 imageBlitRegion.dstOffsets[1] = blitSizeDst;
1675 cmdImageMemoryBarrier(commandBuffer,
mSwapChainImages[
mCurrentImageIndex], vk::PipelineStageFlagBits2::eTransfer, vk::AccessFlagBits2::eTransferWrite, vk::PipelineStageFlagBits2::eColorAttachmentOutput, vk::AccessFlagBits2::eColorAttachmentRead | vk::AccessFlagBits2::eColorAttachmentWrite, vk::ImageLayout::eTransferDstOptimal, vk::ImageLayout::eColorAttachmentOptimal);
1677 commandBuffer.end();
1682 vk::RenderingAttachmentInfo colorAttachment{
dst, vk::ImageLayout::eColorAttachmentOptimal};
1683 colorAttachment.loadOp = vk::AttachmentLoadOp::eDontCare;
1684 cmdBeginRendering(commandBuffer,
width,
height, colorAttachment);
1685 commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics,
mPipelines[8]);
1688 commandBuffer.draw(3, 1, 0, 0);
1689 commandBuffer.endRendering();
1711 vk::CommandBufferBeginInfo beginInfo{};
1712 beginInfo.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit;
1719 if (fontBuffer.
size < fontBufferSize) {
1720 if (fontBuffer.
size) {
1723 fontBuffer =
createBuffer(std::max(fontBufferSize, 2 * fontBuffer.
size),
nullptr, vk::BufferUsageFlagBits::eVertexBuffer, 0);
1729 vk::DeviceSize
offsets[] = {0};
1750 commandBuffer.reset({});
1751 vk::CommandBufferBeginInfo beginInfo{};
1752 beginInfo.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit;
1753 commandBuffer.begin(beginInfo);
1756 cmdImageMemoryBarrier(commandBuffer,
image, vk::PipelineStageFlagBits2::eColorAttachmentOutput, vk::AccessFlagBits2::eColorAttachmentWrite, vk::PipelineStageFlagBits2::eFragmentShader, vk::AccessFlagBits2::eShaderSampledRead, vk::ImageLayout::eColorAttachmentOptimal, vk::ImageLayout::eShaderReadOnlyOptimal);
1759 commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics,
mPipelines[4]);
1761 vk::DeviceSize
offsets[] = {0};
1764 commandBuffer.pushConstants(
mPipelineLayoutTexture, vk::ShaderStageFlagBits::eFragment, 0,
sizeof(mixSlaveImage), &mixSlaveImage);
1765 commandBuffer.draw(6, 1, 0, 0);
1767 commandBuffer.endRendering();
1768 commandBuffer.end();
1811 throw std::runtime_error(
"Incorrect symbol ID");
1815 if (sizex && sizey) {
1816 buffer.reset(
new char[sizex * sizey]);
1823 int32_t maxSizeX = 0, maxSizeY = 0, maxBigX = 0, maxBigY = 0, maxRowY = 0;
1827 maxSizeX = std::max(maxSizeX, symbol.size[0]);
1828 maxSizeY = std::max(maxSizeY, symbol.size[1]);
1833 std::unique_ptr<char[]> bigImage{
new char[sizex * sizey]};
1834 memset(bigImage.get(), 0, sizex * sizey);
1838 if (colx +
s.size[0] > sizex) {
1843 for (
int32_t k = 0; k <
s.size[1]; k++) {
1847 val =
val < 0 ? 0xFF : 0;
1849 bigImage.get()[(colx +
j) + (rowy + k) * sizex] =
val;
1854 s.x1 = colx +
s.size[0];
1856 s.y1 = rowy +
s.size[1];
1857 maxBigX = std::max(maxBigX, colx +
s.size[0]);
1858 maxBigY = std::max(maxBigY, rowy +
s.size[1]);
1859 maxRowY = std::max(maxRowY,
s.size[1]);
1862 if (maxBigX != sizex) {
1864 memmove(bigImage.get() +
y * maxBigX, bigImage.get() +
y * sizex, maxBigX);
1901 for (
const unsigned char*
c = (
const unsigned char*)
s; *
c && (nCharacters == 0 ||
c < (
const unsigned char*)
s + nCharacters);
c++) {
1903 GPUError(
"Trying to draw unsupported symbol: %d", (
int32_t)*
c);
1909 float xpos =
x + sym.
offset[0] * scale;
1910 float ypos =
y - (sym.
size[1] - sym.
offset[1]) * scale;
1911 float w = sym.
size[0] * scale;
1912 float h = sym.
size[1] * scale;
1913 float vertices[6][4] = {
1936 if (
c.size() &&
c.back().color[0] ==
color[0] &&
c.back().color[1] ==
color[1] &&
c.back().color[2] ==
color[2] &&
c.back().color[3] ==
color[3]) {
1937 c.back().nVertices += nVertices;
1950 const float u = (sym.
x0 + sym.
x1) * 0.5f,
v = (sym.
y0 + sym.
y1) * 0.5f;
1952 for (
int32_t i : {0, 2, 1, 0, 3, 2}) {
1962 if (
format != vk::Format::eB8G8R8A8Unorm &&
format != vk::Format::eB8G8R8A8Srgb &&
format != vk::Format::eR8G8B8A8Unorm &&
format != vk::Format::eR8G8B8A8Srgb) {
1963 GPUError(
"Screenshot not supported for swapchain format %s, only 8 bit BGRA / RGBA", vk::to_string(
format).c_str());
1969 static constexpr int32_t bytesPerPixel = 4;
1972 vk::Image dstImage,
src;
1973 vk::ImageView dstView;
1974 vk::DeviceMemory dstImageMemory;
1975 const bool scaled =
mDisplay->
cfgR().screenshotScaleFactor != 1;
1977 const bool shaderDownsample = scaled &&
factor != 1 &&
factor != 2;
1978 const vk::ImageLayout srcLayout = shaderDownsample ? vk::ImageLayout::eShaderReadOnlyOptimal : vk::ImageLayout::eTransferSrcOptimal;
1979 const vk::PipelineStageFlags2 srcStage = shaderDownsample ? vk::PipelineStageFlagBits2::eFragmentShader : vk::PipelineStageFlagBits2::eTransfer;
1982 cmdImageMemoryBarrier(cmdBuffer,
image, vk::PipelineStageFlagBits2::eColorAttachmentOutput | vk::PipelineStageFlagBits2::eTransfer | vk::PipelineStageFlagBits2::eFragmentShader, vk::AccessFlagBits2::eColorAttachmentWrite | vk::AccessFlagBits2::eTransferWrite, srcStage, shaderDownsample ? vk::AccessFlagBits2::eShaderSampledRead : vk::AccessFlagBits2::eTransferRead, layout, srcLayout);
1983 if (shaderDownsample) {
1984 createImageI(
mDevice,
mPhysicalDevice, dstImage, dstImageMemory,
width,
height,
mSurfaceFormat.format, vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eTransferSrc, vk::MemoryPropertyFlagBits::eDeviceLocal, vk::ImageTiling::eOptimal);
1986 cmdImageMemoryBarrier(cmdBuffer, dstImage, vk::PipelineStageFlagBits2::eNone, vk::AccessFlagBits2::eNone, vk::PipelineStageFlagBits2::eColorAttachmentOutput, vk::AccessFlagBits2::eColorAttachmentWrite, vk::ImageLayout::eUndefined, vk::ImageLayout::eColorAttachmentOptimal);
1988 cmdImageMemoryBarrier(cmdBuffer, dstImage, vk::PipelineStageFlagBits2::eColorAttachmentOutput, vk::AccessFlagBits2::eColorAttachmentWrite, vk::PipelineStageFlagBits2::eTransfer, vk::AccessFlagBits2::eTransferRead, vk::ImageLayout::eColorAttachmentOptimal, vk::ImageLayout::eTransferSrcOptimal);
1990 }
else if (scaled) {
1991 createImageI(
mDevice,
mPhysicalDevice, dstImage, dstImageMemory,
width,
height,
mSurfaceFormat.format, vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eTransferSrc | vk::ImageUsageFlagBits::eTransferDst, vk::MemoryPropertyFlagBits::eDeviceLocal, vk::ImageTiling::eOptimal);
1992 cmdImageMemoryBarrier(cmdBuffer, dstImage, vk::PipelineStageFlagBits2::eNone, vk::AccessFlagBits2::eNone, vk::PipelineStageFlagBits2::eTransfer, vk::AccessFlagBits2::eTransferWrite, vk::ImageLayout::eUndefined, vk::ImageLayout::eTransferDstOptimal);
1995 vk::ImageBlit imageBlitRegion{};
1996 imageBlitRegion.srcSubresource.aspectMask = vk::ImageAspectFlagBits::eColor;
1997 imageBlitRegion.srcSubresource.layerCount = 1;
1998 imageBlitRegion.srcOffsets[1] = blitSizeSrc;
1999 imageBlitRegion.dstSubresource.aspectMask = vk::ImageAspectFlagBits::eColor;
2000 imageBlitRegion.dstSubresource.layerCount = 1;
2001 imageBlitRegion.dstOffsets[1] = blitSizeDst;
2002 cmdBuffer.blitImage(
image, vk::ImageLayout::eTransferSrcOptimal, dstImage, vk::ImageLayout::eTransferDstOptimal, 1, &imageBlitRegion, vk::Filter::eLinear);
2004 cmdImageMemoryBarrier(cmdBuffer, dstImage, vk::PipelineStageFlagBits2::eTransfer, vk::AccessFlagBits2::eTransferWrite, vk::PipelineStageFlagBits2::eTransfer, vk::AccessFlagBits2::eTransferRead, vk::ImageLayout::eTransferDstOptimal, vk::ImageLayout::eTransferSrcOptimal);
2009 vk::BufferImageCopy copyRegion{};
2010 copyRegion.imageSubresource.aspectMask = vk::ImageAspectFlagBits::eColor;
2011 copyRegion.imageSubresource.layerCount = 1;
2012 copyRegion.imageExtent = vk::Extent3D{
width,
height, 1};
2013 cmdBuffer.copyImageToBuffer(
src, vk::ImageLayout::eTransferSrcOptimal, readBuffer.
buffer, 1, ©Region);
2015 vk::BufferMemoryBarrier2 hostBarrier{vk::PipelineStageFlagBits2::eTransfer, vk::AccessFlagBits2::eTransferWrite, vk::PipelineStageFlagBits2::eHost, vk::AccessFlagBits2::eHostRead, VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED, readBuffer.
buffer, 0, VK_WHOLE_SIZE};
2016 cmdBuffer.pipelineBarrier2(vk::DependencyInfo{{}, 0,
nullptr, 1, &hostBarrier, 0,
nullptr});
2017 cmdImageMemoryBarrier(cmdBuffer,
image, srcStage, vk::AccessFlagBits2::eNone, vk::PipelineStageFlagBits2::eColorAttachmentOutput | vk::PipelineStageFlagBits2::eTransfer, vk::AccessFlagBits2::eNone, srcLayout, layout);
2020 const bool swapRB =
format == vk::Format::eR8G8B8A8Unorm ||
format == vk::Format::eR8G8B8A8Srgb;
2021 const char*
data = (
const char*)readBuffer.
mapped;
2027 std::swap(
dst[
j * bytesPerPixel],
dst[
j * bytesPerPixel + 2]);
2034 mDevice.destroyImageView(dstView,
nullptr);
2036 mDevice.freeMemory(dstImageMemory,
nullptr);
2037 mDevice.destroyImage(dstImage,
nullptr);
#define LOAD_SHADER(file, ext)
Timeframe settings Average distance in cm of events merged into Randomize distance around average distance of merged events Simulate correct bunch interactions instead of placing only the average number of events A value[n] sets TFlen for[n] collisions in Number of bunches per trainsort Number of bunch trains Instantaneous interaction rate Do not simulate border Total number of collisions to be placed in the interior of all time Do not select random but walk over array of events in stride steps h Event generator settings h configStandalone Use CPU for GPU Force usage of the specified GPU device no CPU fallback Continue processing after an error s
Timeframe settings Average distance in cm of events merged into Randomize distance around average distance of merged events Simulate correct bunch interactions instead of placing only the average number of events A value[n] sets TFlen for[n] collisions in Number of bunches per trainsort Number of bunch trains Instantaneous interaction rate Do not simulate border Total number of collisions to be placed in the interior of all time Do not select random but walk over array of events in stride steps h Event generator settings h configStandalone Use CPU for GPU Force usage of the specified GPU device no CPU fallback Continue processing after an error First event to Number of events to Number of iterations to Number of iterations to Number of initial iterations excluded from const char Directory with events to Events directory is and not inside events Show standalone event Run event generator maximum time bin of continuous for triggered for automatic continuous for automatic continuous triggered uint64_t
Timeframe settings Average distance in cm of events merged into Randomize distance around average distance of merged events Simulate correct bunch interactions instead of placing only the average number of events A value[n] sets TFlen for[n] collisions in Number of bunches per trainsort Number of bunch trains Instantaneous interaction rate Do not simulate border Total number of collisions to be placed in the interior of all time Do not select random but walk over array of events in stride steps h Event generator settings h configStandalone Use CPU for GPU Force usage of the specified GPU device no CPU fallback Continue processing after an error First event to Number of events to Number of iterations to Number of iterations to Number of initial iterations excluded from const char e
configStandalone Reconstruction rec_tpc multiplier for the combined cluster track error during track following area in cm for the search of for z only used if decrease removal by when above this local occupancy rowx Shift of TPC revert cluster flag edge bit distance to edge exceeds this ZOffset for secondary multiple of radius max P of electron K BB bands crossing max P of electron p BB bands crossing max P of electron d BB bands crossing max P of electron t BB bands crossing min accepted dEdxMaxTPC of the track Additive extra cluster error for Y2 if edge flag set Additive extra cluster error for Y2 if single set Additive extra cluster error for Y2 if or single set Additive extra cluster error for Z2 if or single set Extra errors to add to track when crossing depending on addErrorsCECrossing Inner portion of y range in sector that is not used in searching for extrapolated track candidates factor2YS for track merging factor2K for track merging Margin in cm of Y position when rejecting edge clusters based on uncorrected track Y Max fraction of shared clusters for tracklet Except pad from cluster finding if total number of charges in a fragment is above this Except pad from cluster finding if number of consecutive charges in a fragment is above this Threshold where a timebin is considered disabling the noisy pad check for that pad Treat signal above this minimum as saturated Smoothing factor for the exponential Highly Ionising Particle tail filter Number of timebins to use for the averaging Add additional custom track errors when crossing relative as fraction of Do N fit passes in final fit of< 0:reject at max -n hits") AddOptionRTC(rejectIFCLowRadiusCluster, uint8_t, 1, "", 0, "Reject clusters that get the IFC mask error during refit") AddOptionRTC(dEdxTruncLow, uint8_t, 2, "", 0, "Low truncation threshold, fraction of 128") AddOptionRTC(dEdxTruncHigh, uint8_t, 77, "", 0, "High truncation threshold, fraction of 128") AddOptionRTC(extrapolationTracking, int8_t, 1, "", 0, "Enable Extrapolation Tracking(prolong tracks to adjacent sectors to find short segments)") AddOptionRTC(disableRefitAttachment, uint8_t, 0, "", 0, "Bitmask to disable certain attachment steps during refit(1:attachment, 2:propagation, 4:loop following, 8:mirroring)") AddOptionRTC(rejectionStrategy, uint8_t, o2::gpu::GPUSettings::RejectionStrategyA, "", 0, "Enable rejection of TPC clusters for compression(0=no, 1=strategy A, 2=strategy B)") AddOptionRTC(mergeLoopersAfterburner, uint8_t, 1, "", 0, "Run afterburner for additional looper merging") AddOptionRTC(compressionTypeMask, uint8_t, o2::gpu::GPUSettings::CompressionFull, "", 0, "TPC Compression mode bits(1=truncate charge/width LSB, 2=differences, 4=track-model)") AddOptionRTC(compressionSortOrder, uint8_t, o2::gpu::GPUSettings::SortTime, "", 0, "Sort order of TPC compression(0=time, 1=pad, 2=Z-time-pad, 3=Z-pad-time, 4=no sorting(use incoming order))") AddOptionRTC(sigBitsCharge, uint8_t, 4, "", 0, "Number of significant bits for TPC cluster charge in compression mode 1") AddOptionRTC(sigBitsWidth, uint8_t, 3, "", 0, "Number of significant bits for TPC cluster width in compression mode 1") AddOptionRTC(dropLoopers, uint8_t, 0, "", 0, "Drop looping tracks starting from second loop") AddOptionRTC(mergerInterpolateErrors, uint8_t, 1, "", 0, "Use interpolation instead of extrapolation for chi2 based cluster rejection") AddOptionRTC(mergerInterpolateRejectAlsoOnCurrentPosition, uint8_t, 1, "", 0, "When using mergerInterpolateErrors, reject based on chi2 twice computed with interpolated and current track position starting from NDF > mergerNonInterpolateRejectMinNDF Merge tracks accross the central electrode Enable PID response Add sub threshold clusters in TPC dEdx computation OR mask of TPC flags that will reject the cluster in alternative dEdx Reject edge clusters based on uncorrected track Y during track fit Increase decrease removal by when on this number of pads from the edge h configStandalone Reconstruction rec_trd Max chi2 for TRD tracklets to be matched to a track Chi2 cut for strict matching mode Number of sigmas for ITS TPC track time error estimate Addition to search road around track prolongation along Y in cm Optimal tracklet rphi resolution in maximum chi2 per attached tracklet for TRD tracks take into account the full likelihood of the slope including exponential tails Tracks with less attached tracklets are discarded after the tracking Post trigger Pile up integration time in BCs fits all iterations but the last one in projections Use material lookup table for TPC refit Apply workarounds to avoid cyclic merge should not be needed tpc dyn configStandalone Processing proc_rtc Replace constant variables static by constexpr expressions Compile RTC in deterministic with NO_FAST_MATH flags and GPUCA_DETERMINISTIC_MODE define Use RTC to optimize GPU code h configStandalone Processing proc_rtctech Use a file lock to serialize access to the cache folder int32_t
configStandalone Reconstruction rec_tpc multiplier for the combined cluster track error during track following area in cm for the search of for z only used if decrease removal by when above this local occupancy rowx Shift of TPC revert cluster flag edge bit distance to edge exceeds this ZOffset for secondary multiple of radius max P of electron K BB bands crossing max P of electron p BB bands crossing max P of electron d BB bands crossing max P of electron t BB bands crossing min accepted dEdxMaxTPC of the track Additive extra cluster error for Y2 if edge flag set Additive extra cluster error for Y2 if single set Additive extra cluster error for Y2 if or single set Additive extra cluster error for Z2 if or single set Extra errors to add to track when crossing depending on addErrorsCECrossing Inner portion of y range in sector that is not used in searching for extrapolated track candidates factor2YS for track merging factor2K for track merging Margin in cm of Y position when rejecting edge clusters based on uncorrected track Y Max fraction of shared clusters for tracklet Except pad from cluster finding if total number of charges in a fragment is above this Except pad from cluster finding if number of consecutive charges in a fragment is above this Threshold where a timebin is considered disabling the noisy pad check for that pad Treat signal above this minimum as saturated Smoothing factor for the exponential Highly Ionising Particle tail filter Number of timebins to use for the averaging Add additional custom track errors when crossing relative as fraction of Do N fit passes in final fit of< 0:reject at max -n hits") AddOptionRTC(rejectIFCLowRadiusCluster, uint8_t, 1, "", 0, "Reject clusters that get the IFC mask error during refit") AddOptionRTC(dEdxTruncLow, uint8_t, 2, "", 0, "Low truncation threshold, fraction of 128") AddOptionRTC(dEdxTruncHigh, uint8_t, 77, "", 0, "High truncation threshold, fraction of 128") AddOptionRTC(extrapolationTracking, int8_t, 1, "", 0, "Enable Extrapolation Tracking(prolong tracks to adjacent sectors to find short segments)") AddOptionRTC(disableRefitAttachment, uint8_t, 0, "", 0, "Bitmask to disable certain attachment steps during refit(1:attachment, 2:propagation, 4:loop following, 8:mirroring)") AddOptionRTC(rejectionStrategy, uint8_t, o2::gpu::GPUSettings::RejectionStrategyA, "", 0, "Enable rejection of TPC clusters for compression(0=no, 1=strategy A, 2=strategy B)") AddOptionRTC(mergeLoopersAfterburner, uint8_t, 1, "", 0, "Run afterburner for additional looper merging") AddOptionRTC(compressionTypeMask, uint8_t, o2::gpu::GPUSettings::CompressionFull, "", 0, "TPC Compression mode bits(1=truncate charge/width LSB, 2=differences, 4=track-model)") AddOptionRTC(compressionSortOrder, uint8_t, o2::gpu::GPUSettings::SortTime, "", 0, "Sort order of TPC compression(0=time, 1=pad, 2=Z-time-pad, 3=Z-pad-time, 4=no sorting(use incoming order))") AddOptionRTC(sigBitsCharge, uint8_t, 4, "", 0, "Number of significant bits for TPC cluster charge in compression mode 1") AddOptionRTC(sigBitsWidth, uint8_t, 3, "", 0, "Number of significant bits for TPC cluster width in compression mode 1") AddOptionRTC(dropLoopers, uint8_t, 0, "", 0, "Drop looping tracks starting from second loop") AddOptionRTC(mergerInterpolateErrors, uint8_t, 1, "", 0, "Use interpolation instead of extrapolation for chi2 based cluster rejection") AddOptionRTC(mergerInterpolateRejectAlsoOnCurrentPosition, uint8_t, 1, "", 0, "When using mergerInterpolateErrors, reject based on chi2 twice computed with interpolated and current track position starting from NDF > mergerNonInterpolateRejectMinNDF Merge tracks accross the central electrode Enable PID response Add sub threshold clusters in TPC dEdx computation OR mask of TPC flags that will reject the cluster in alternative dEdx Reject edge clusters based on uncorrected track Y during track fit Increase decrease removal by when on this number of pads from the edge h configStandalone Reconstruction rec_trd Max chi2 for TRD tracklets to be matched to a track Chi2 cut for strict matching mode Number of sigmas for ITS TPC track time error estimate Addition to search road around track prolongation along Y in cm Optimal tracklet rphi resolution in maximum chi2 per attached tracklet for TRD tracks take into account the full likelihood of the slope including exponential tails Tracks with less attached tracklets are discarded after the tracking Post trigger Pile up integration time in BCs fits all iterations but the last one in projections Use material lookup table for TPC refit Apply workarounds to avoid cyclic merge should not be needed tpc dyn configStandalone Processing proc_rtc Replace constant variables static by constexpr expressions Compile RTC in deterministic with NO_FAST_MATH flags and GPUCA_DETERMINISTIC_MODE define Use RTC to optimize GPU code h configStandalone Processing proc_rtctech Use a file lock to serialize access to the cache folder Print launch bounds used for RTC code as debugging for exit after Allow RTC with slave GPUReconstruction instances with optConstexpr and optSpecialcode Maximum number of RTC cache files per backend in the cache the oldest are Prepend RTC compilation commands by this string Load a parameter object containing the launch bounds from a file h configStandalone Processing proc_param TPC Cluster Z Error Parameterization h nn
configStandalone Reconstruction rec_tpc multiplier for the combined cluster track error during track following area in cm for the search of for z only used if decrease removal by factor
configStandalone Reconstruction rec_tpc multiplier for the combined cluster track error during track following area in cm for the search of for z only used if decrease removal by when above this local occupancy rowx Shift of TPC revert cluster flag edge bit distance to edge exceeds this ZOffset for secondary multiple of radius max P of electron K BB bands crossing max P of electron p BB bands crossing max P of electron d BB bands crossing max P of electron t BB bands crossing min accepted dEdxMaxTPC of the track Additive extra cluster error for Y2 if edge flag set Additive extra cluster error for Y2 if single set Additive extra cluster error for Y2 if or single set Additive extra cluster error for Z2 if or single set Extra errors to add to track when crossing depending on addErrorsCECrossing Inner portion of y range in sector that is not used in searching for extrapolated track candidates factor2YS for track merging factor2K for track merging Margin in cm of Y position when rejecting edge clusters based on uncorrected track Y Max fraction of shared clusters for tracklet Except pad from cluster finding if total number of charges in a fragment is above this Except pad from cluster finding if number of consecutive charges in a fragment is above this Threshold where a timebin is considered disabling the noisy pad check for that pad Treat signal above this minimum as saturated Smoothing factor for the exponential Highly Ionising Particle tail filter Number of timebins to use for the averaging Add additional custom track errors when crossing relative as fraction of Do N fit passes in final fit of< 0:reject at max -n hits") AddOptionRTC(rejectIFCLowRadiusCluster, uint8_t, 1, "", 0, "Reject clusters that get the IFC mask error during refit") AddOptionRTC(dEdxTruncLow, uint8_t, 2, "", 0, "Low truncation threshold, fraction of 128") AddOptionRTC(dEdxTruncHigh, uint8_t, 77, "", 0, "High truncation threshold, fraction of 128") AddOptionRTC(extrapolationTracking, int8_t, 1, "", 0, "Enable Extrapolation Tracking(prolong tracks to adjacent sectors to find short segments)") AddOptionRTC(disableRefitAttachment, uint8_t, 0, "", 0, "Bitmask to disable certain attachment steps during refit(1:attachment, 2:propagation, 4:loop following, 8:mirroring)") AddOptionRTC(rejectionStrategy, uint8_t, o2::gpu::GPUSettings::RejectionStrategyA, "", 0, "Enable rejection of TPC clusters for compression(0=no, 1=strategy A, 2=strategy B)") AddOptionRTC(mergeLoopersAfterburner, uint8_t, 1, "", 0, "Run afterburner for additional looper merging") AddOptionRTC(compressionTypeMask, uint8_t, o2::gpu::GPUSettings::CompressionFull, "", 0, "TPC Compression mode bits(1=truncate charge/width LSB, 2=differences, 4=track-model)") AddOptionRTC(compressionSortOrder, uint8_t, o2::gpu::GPUSettings::SortTime, "", 0, "Sort order of TPC compression(0=time, 1=pad, 2=Z-time-pad, 3=Z-pad-time, 4=no sorting(use incoming order))") AddOptionRTC(sigBitsCharge, uint8_t, 4, "", 0, "Number of significant bits for TPC cluster charge in compression mode 1") AddOptionRTC(sigBitsWidth, uint8_t, 3, "", 0, "Number of significant bits for TPC cluster width in compression mode 1") AddOptionRTC(dropLoopers, uint8_t, 0, "", 0, "Drop looping tracks starting from second loop") AddOptionRTC(mergerInterpolateErrors, uint8_t, 1, "", 0, "Use interpolation instead of extrapolation for chi2 based cluster rejection") AddOptionRTC(mergerInterpolateRejectAlsoOnCurrentPosition, uint8_t, 1, "", 0, "When using mergerInterpolateErrors, reject based on chi2 twice computed with interpolated and current track position starting from NDF > mergerNonInterpolateRejectMinNDF Merge tracks accross the central electrode Enable PID response Add sub threshold clusters in TPC dEdx computation OR mask of TPC flags that will reject the cluster in alternative dEdx Reject edge clusters based on uncorrected track Y during track fit Increase decrease removal by when on this number of pads from the edge h configStandalone Reconstruction rec_trd Max chi2 for TRD tracklets to be matched to a track Chi2 cut for strict matching mode Number of sigmas for ITS TPC track time error estimate Addition to search road around track prolongation along Y in cm Optimal tracklet rphi resolution in maximum chi2 per attached tracklet for TRD tracks take into account the full likelihood of the slope including exponential tails Tracks with less attached tracklets are discarded after the tracking Post trigger Pile up integration time in BCs fits all iterations but the last one in projections Use material lookup table for TPC refit Apply workarounds to avoid cyclic merge should not be needed tpc dyn configStandalone Processing proc_rtc Replace constant variables static by constexpr expressions Compile RTC in deterministic with NO_FAST_MATH flags and GPUCA_DETERMINISTIC_MODE define Use RTC to optimize GPU code h configStandalone Processing proc_rtctech Use a file lock to serialize access to the cache folder Print launch bounds used for RTC code as debugging for exit after Allow RTC with slave GPUReconstruction instances with optConstexpr and optSpecialcode Maximum number of RTC cache files per backend in the cache the oldest are Prepend RTC compilation commands by this string Load a parameter object containing the launch bounds from a file h configStandalone Processing proc_param TPC Cluster Z Error Parameterization h configStandalone Processing settings for neural network proc_nn std::string Specify inference device(cpu(default), rocm, cuda)") AddOption(nnInferenceDeviceId
configStandalone Reconstruction rec_tpc float
HMM_INLINE hmm_mat4 HMM_Orthographic(float Left, float Right, float Bottom, float Top, float Near, float Far)
Class for time synchronization of RawReader instances.
vk::CommandBuffer getSingleTimeCommandBuffer()
void createSemaphoresForImages()
std::vector< vk::CommandBuffer > mCommandBuffersMix
std::vector< vk::CommandBuffer > mCommandBuffers
std::vector< vk::Semaphore > mPresentSemaphore
vk::DescriptorSetLayout mUniformDescriptor
VulkanBuffer mIndirectCommandBuffer
void createCommandBuffersForImages()
std::vector< vk::Image > mRenderTargetImage
std::vector< vk::Pipeline > mPipelines
vk::CommandBuffer mCurrentCommandBuffer
void resizeScene(uint32_t width, uint32_t height) override
bool mFifoLatestReadySupported
int32_t mCurrentCommandBufferLastPipeline
void submitSingleTimeCommandBuffer(vk::CommandBuffer commandBuffer)
uint8_t mSwapChainSuboptimal
std::vector< VulkanImage > mDownsampleImages
void clearUniformLayoutsAndBuffers()
void writeToBuffer(VulkanBuffer &buffer, size_t size, const void *srcData)
std::vector< vk::ImageView > mSwapChainImageViews
std::vector< vk::CommandBufferSubmitInfo > mFrameCommandBuffers
std::vector< VulkanImage > mMSAAImages
void pointSizeFactor(float factor) override
void GLDrawQuad(const float(&corners)[4][2], const float *color) override
uint32_t mUpdateUBOmixMatrix
std::vector< FontSymbolVulkan > mFontSymbols
vk::SwapchainKHR mSwapChain
void clearUniformLayoutsAndBuffersForImages()
int32_t InitBackendA() override
void clearImage(VulkanImage &image)
std::vector< vk::ImageView * > mRenderTargetView
vk::PipelineCache mPipelineCache
void finishText() override
bool prepareDraw(const hmm_mat4 &proj, const hmm_mat4 &view, bool requestScreenshot, bool toMixBuffer, float includeMixImage) override
void addFontSymbol(int32_t symbol, int32_t sizex, int32_t sizey, int32_t offsetx, int32_t offsety, int32_t advance, void *data) override
void addTextDrawCommand(size_t firstVertex, const float *color)
bool backendNeedRedraw() override
vk::SampleCountFlagBits mMSAASampleCount
void mixImages(vk::CommandBuffer cmdBuffer, float mixSlaveImage)
void clearVertexBuffers()
void createTextureSampler()
void recreateRendering(bool forScreenshot=false, bool forMixing=false)
std::vector< VulkanBuffer > mFontVertexBuffer
double checkDevice(vk::PhysicalDevice device, const std::vector< const char * > &reqDeviceExtensions, const FeatureChain &reqDeviceFeatures, bool silent=false)
void endFillCommandBuffer(vk::CommandBuffer &commandBuffer)
std::vector< uint64_t > mImageTimelineValue
uint32_t drawVertices(const vboList &v, const drawType t) override
vk::SurfaceFormatKHR mSurfaceFormat
std::vector< vk::CommandBuffer > mCommandBuffersPresent
std::vector< vk::CommandBuffer > mCommandBuffersDownsample
void ActivateColor(std::array< float, 4 > &color) override
std::vector< vk::Image > mSwapChainImages
void clearCommandBuffersForImages()
uint32_t mUpdateUBOdrawMatrix
uint32_t mUpdateUBOtextMatrix
uint64_t queueSubmit(uint64_t *timelineSignalValue, Args &&... args)
void initializeTextDrawing() override
void clearBuffer(VulkanBuffer &buffer)
VulkanBuffer mMixingTextureVertexArray
vk::Sampler mTextureSampler
vk::Semaphore mTimelineSemaphore
uint32_t mCurrentImageIndex
void createUniformLayoutsAndBuffers()
void needRecordCommandBuffers()
std::vector< VulkanBuffer > mUniformBuffersMat[3]
bool mCommandInfrastructureCreated
void updateSwapChainDetails(const vk::PhysicalDevice &device)
void handleSwapChainResult(vk::Result retVal, uint8_t suboptimalBit)
std::vector< VulkanImage > mMixImages
std::vector< uint64_t > mFrameTimelineValue
vk::CommandPool mCommandPool
vk::StructureChain< vk::PhysicalDeviceFeatures2, vk::PhysicalDeviceVulkan11Features, vk::PhysicalDeviceVulkan12Features, vk::PhysicalDeviceVulkan13Features, vk::PhysicalDeviceVulkan14Features, vk::PhysicalDeviceSwapchainMaintenance1FeaturesKHR, vk::PhysicalDevicePresentIdFeaturesKHR, vk::PhysicalDevicePresentWaitFeaturesKHR > FeatureChain
void finishDraw(bool doScreenshot, bool toMixBuffer, float includeMixImage) override
void writeToImage(VulkanImage &image, const void *srcData, size_t srcSize)
vecpod< float > mFontVertexBufferHost
vk::PresentModeKHR chooseSwapPresentMode()
vk::PipelineLayout mPipelineLayout
void clearOffscreenBuffers()
std::unordered_map< std::string, vk::ShaderModuleCreateInfo > mShaders
vk::DescriptorSetLayout mUniformDescriptorTexture
void downsampleToFramebuffer(vk::CommandBuffer &commandBuffer)
void createSwapChain(vk::SwapchainKHR oldSwapChain={})
void ExitBackendA() override
vk::Extent2D chooseSwapExtent(const vk::SurfaceCapabilitiesKHR &capabilities)
void clearSemaphoresForImages()
~GPUDisplayBackendVulkan() override
bool mPresentModeErrorShown
VulkanImage createImage(uint32_t sizex, uint32_t sizey, const void *srcData=nullptr, size_t srcSize=0, vk::Format format=vk::Format::eR8G8B8A8Srgb)
std::vector< TextDrawCommand > mTextDrawCommands
void clearTextureSampler()
vk::PipelineLayout mPipelineLayoutTexture
SwapChainSupportDetails mSwapChainDetails
uint32_t mMaxMSAAsupported
void cmdPushDescriptors(vk::CommandBuffer commandBuffer, vk::PipelineLayout layout, const VulkanBuffer &ubo, vk::ImageView textureView={})
void finishFrame(bool doScreenshot, bool toMixBuffer, float includeMixImage) override
bool mPresentModeForVSyncLimit
void clearSwapChain(bool keepSwapChain=false)
std::vector< vk::Semaphore > mImageAvailableSemaphore
void startFillCommandBuffer(vk::CommandBuffer &commandBuffer, uint32_t imageIndex, bool toMixBuffer=false)
void waitTimeline(uint64_t value)
std::vector< vk::CommandBuffer > mCommandBuffersTexture
vk::PhysicalDevice mPhysicalDevice
vk::DebugUtilsMessengerEXT mDebugMessenger
GPUDisplayBackendVulkan()
void clearFontSymbols() override
std::vector< vk::Fence > mPresentFences
void GLPrintText(const char *s, float x, float y, float *color, float scale, uint32_t nCharacters) override
void cmdDownsample(vk::CommandBuffer commandBuffer, vk::ImageView src, vk::ImageView dst, uint32_t width, uint32_t height, int32_t factor)
VulkanBuffer createBuffer(size_t size, const void *srcData=nullptr, vk::BufferUsageFlags type=vk::BufferUsageFlagBits::eVertexBuffer, int32_t deviceMemory=1)
std::vector< VulkanImage > mZImages
void createOffscreenBuffers(bool forScreenshot=false, bool forMixing=false)
void createUniformLayoutsAndBuffersForImages()
bool mEnableValidationLayers
std::vector< bool > mCommandBufferUpToDate
void lineWidthFactor(float factor) override
void prepareText() override
void readImageToPixels(vk::Image image, vk::ImageView view, vk::ImageLayout layout, std::vector< char > &pixels)
std::vector< vk::CommandBuffer > mCommandBuffersText
bool mMustUpdateSwapChain
vk::PresentModeKHR mPresentMode
void loadDataToGPU(size_t totalVertizes) override
int32_t fpsLimitMode() const
static constexpr int32_t SOLID_GLYPH
vecpod< DrawArraysIndirectCommand > mCmdBuffer
std::vector< int32_t > mIndirectSectorOffset
void fillIndirectCmdBuffer()
static constexpr float SMOOTH_LINE_EXTRA_WIDTH
bool mFreetypeInitialized
std::vector< char > mScreenshotPixels
static constexpr float SMOOTH_POINT_EXTRA_SIZE
backendTypes mBackendType
const char * mBackendName
float getDownsampleFactor(bool screenshot=false)
int32_t mDownsampleFactor
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
int32_t updateRenderPipeline() const
const GPUSettingsDisplayRenderer & cfgR() const
vecpod< vtx > * vertexBuffer()
int32_t updateDrawCommands() const
GPUDisplayFrontend * frontend()
const vecpod< uint32_t > * vertexBufferCount() const
const GPUSettingsDisplay & cfg() const
vecpod< int32_t > * vertexBufferStart()
const GPUSettingsProcessing & GetProcessingSettings() const
GLuint GLsizei const GLuint const GLintptr * offsets
GLsizei GLenum GLenum * types
GLint GLsizei GLsizei height
GLsizei const GLfloat * value
GLint GLint GLsizei GLint GLenum GLenum type
typedef void(APIENTRYP PFNGLCULLFACEPROC)(GLenum mode)
GLint GLint GLsizei GLint GLenum GLenum const void * pixels
GLint GLint GLsizei GLsizei GLsizei depth
GLboolean GLboolean GLboolean GLboolean a
GLubyte GLubyte GLubyte GLubyte w
GLint GLint GLsizei GLint GLenum format
GLsizeiptr const void GLenum usage
std::vector< T, fair::mq::pmr::polymorphic_allocator< T > > vector
std::vector< vk::SurfaceFormatKHR > formats
vk::SurfaceCapabilitiesKHR capabilities
std::vector< vk::PresentModeKHR > presentModes