vk_swapchain.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. // SPDX-FileCopyrightText: Copyright 2019 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <algorithm>
  4. #include <array>
  5. #include <limits>
  6. #include <vector>
  7. #include "common/logging/log.h"
  8. #include "common/polyfill_ranges.h"
  9. #include "common/settings.h"
  10. #include "core/core.h"
  11. #include "video_core/renderer_vulkan/vk_scheduler.h"
  12. #include "video_core/renderer_vulkan/vk_swapchain.h"
  13. #include "video_core/vulkan_common/vulkan_device.h"
  14. #include "video_core/vulkan_common/vulkan_wrapper.h"
  15. namespace Vulkan {
  16. namespace {
  17. VkSurfaceFormatKHR ChooseSwapSurfaceFormat(vk::Span<VkSurfaceFormatKHR> formats) {
  18. if (formats.size() == 1 && formats[0].format == VK_FORMAT_UNDEFINED) {
  19. VkSurfaceFormatKHR format;
  20. format.format = VK_FORMAT_B8G8R8A8_UNORM;
  21. format.colorSpace = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR;
  22. return format;
  23. }
  24. const auto& found = std::find_if(formats.begin(), formats.end(), [](const auto& format) {
  25. return format.format == VK_FORMAT_B8G8R8A8_UNORM &&
  26. format.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR;
  27. });
  28. return found != formats.end() ? *found : formats[0];
  29. }
  30. VkPresentModeKHR ChooseSwapPresentMode(vk::Span<VkPresentModeKHR> modes) {
  31. // Mailbox (triple buffering) doesn't lock the application like FIFO (vsync)
  32. // FIFO present mode locks the framerate to the monitor's refresh rate
  33. const bool has_mailbox =
  34. std::find(modes.begin(), modes.end(), VK_PRESENT_MODE_MAILBOX_KHR) != modes.end();
  35. const bool has_imm =
  36. std::find(modes.begin(), modes.end(), VK_PRESENT_MODE_IMMEDIATE_KHR) != modes.end();
  37. const Settings::VSyncMode mode = Settings::values.vsync_mode.GetValue();
  38. if (mode == Settings::VSyncMode::Immediate && has_imm) {
  39. LOG_INFO(Render_Vulkan, "Using swap present mode Immediate");
  40. return VK_PRESENT_MODE_IMMEDIATE_KHR;
  41. } else if (mode == Settings::VSyncMode::Mailbox && has_mailbox) {
  42. LOG_INFO(Render_Vulkan, "Using swap present mode Mailbox");
  43. return VK_PRESENT_MODE_MAILBOX_KHR;
  44. }
  45. LOG_INFO(Render_Vulkan, "Using swap present mode FIFO");
  46. return VK_PRESENT_MODE_FIFO_KHR;
  47. }
  48. VkExtent2D ChooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, u32 width, u32 height) {
  49. constexpr auto undefined_size{std::numeric_limits<u32>::max()};
  50. if (capabilities.currentExtent.width != undefined_size) {
  51. return capabilities.currentExtent;
  52. }
  53. VkExtent2D extent;
  54. extent.width = std::max(capabilities.minImageExtent.width,
  55. std::min(capabilities.maxImageExtent.width, width));
  56. extent.height = std::max(capabilities.minImageExtent.height,
  57. std::min(capabilities.maxImageExtent.height, height));
  58. return extent;
  59. }
  60. VkCompositeAlphaFlagBitsKHR ChooseAlphaFlags(const VkSurfaceCapabilitiesKHR& capabilities) {
  61. if (capabilities.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR) {
  62. return VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
  63. } else if (capabilities.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR) {
  64. return VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
  65. } else {
  66. LOG_ERROR(Render_Vulkan, "Unknown composite alpha flags value {:#x}",
  67. capabilities.supportedCompositeAlpha);
  68. return VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
  69. }
  70. }
  71. } // Anonymous namespace
  72. Swapchain::Swapchain(VkSurfaceKHR surface_, const Device& device_, Scheduler& scheduler_,
  73. u32 width_, u32 height_, bool srgb)
  74. : surface{surface_}, device{device_}, scheduler{scheduler_} {
  75. Create(width_, height_, srgb);
  76. }
  77. Swapchain::~Swapchain() = default;
  78. void Swapchain::Create(u32 width_, u32 height_, bool srgb) {
  79. is_outdated = false;
  80. is_suboptimal = false;
  81. width = width_;
  82. height = height_;
  83. const auto physical_device = device.GetPhysical();
  84. const auto capabilities{physical_device.GetSurfaceCapabilitiesKHR(surface)};
  85. if (capabilities.maxImageExtent.width == 0 || capabilities.maxImageExtent.height == 0) {
  86. return;
  87. }
  88. Destroy();
  89. CreateSwapchain(capabilities, srgb);
  90. CreateSemaphores();
  91. resource_ticks.clear();
  92. resource_ticks.resize(image_count);
  93. }
  94. bool Swapchain::AcquireNextImage() {
  95. const VkResult result = device.GetLogical().AcquireNextImageKHR(
  96. *swapchain, std::numeric_limits<u64>::max(), *present_semaphores[frame_index],
  97. VK_NULL_HANDLE, &image_index);
  98. switch (result) {
  99. case VK_SUCCESS:
  100. break;
  101. case VK_SUBOPTIMAL_KHR:
  102. is_suboptimal = true;
  103. break;
  104. case VK_ERROR_OUT_OF_DATE_KHR:
  105. is_outdated = true;
  106. break;
  107. default:
  108. LOG_ERROR(Render_Vulkan, "vkAcquireNextImageKHR returned {}", vk::ToString(result));
  109. break;
  110. }
  111. scheduler.Wait(resource_ticks[image_index]);
  112. resource_ticks[image_index] = scheduler.CurrentTick();
  113. return is_suboptimal || is_outdated;
  114. }
  115. void Swapchain::Present(VkSemaphore render_semaphore) {
  116. const auto present_queue{device.GetPresentQueue()};
  117. const VkPresentInfoKHR present_info{
  118. .sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
  119. .pNext = nullptr,
  120. .waitSemaphoreCount = render_semaphore ? 1U : 0U,
  121. .pWaitSemaphores = &render_semaphore,
  122. .swapchainCount = 1,
  123. .pSwapchains = swapchain.address(),
  124. .pImageIndices = &image_index,
  125. .pResults = nullptr,
  126. };
  127. std::scoped_lock lock{scheduler.submit_mutex};
  128. switch (const VkResult result = present_queue.Present(present_info)) {
  129. case VK_SUCCESS:
  130. break;
  131. case VK_SUBOPTIMAL_KHR:
  132. LOG_DEBUG(Render_Vulkan, "Suboptimal swapchain");
  133. break;
  134. case VK_ERROR_OUT_OF_DATE_KHR:
  135. is_outdated = true;
  136. break;
  137. default:
  138. LOG_CRITICAL(Render_Vulkan, "Failed to present with error {}", vk::ToString(result));
  139. break;
  140. }
  141. ++frame_index;
  142. if (frame_index >= image_count) {
  143. frame_index = 0;
  144. }
  145. }
  146. void Swapchain::CreateSwapchain(const VkSurfaceCapabilitiesKHR& capabilities, bool srgb) {
  147. const auto physical_device{device.GetPhysical()};
  148. const auto formats{physical_device.GetSurfaceFormatsKHR(surface)};
  149. const auto present_modes{physical_device.GetSurfacePresentModesKHR(surface)};
  150. const VkCompositeAlphaFlagBitsKHR alpha_flags{ChooseAlphaFlags(capabilities)};
  151. surface_format = ChooseSwapSurfaceFormat(formats);
  152. present_mode = ChooseSwapPresentMode(present_modes);
  153. u32 requested_image_count{capabilities.minImageCount + 1};
  154. // Ensure Triple buffering if possible.
  155. if (capabilities.maxImageCount > 0) {
  156. if (requested_image_count > capabilities.maxImageCount) {
  157. requested_image_count = capabilities.maxImageCount;
  158. } else {
  159. requested_image_count =
  160. std::max(requested_image_count, std::min(3U, capabilities.maxImageCount));
  161. }
  162. } else {
  163. requested_image_count = std::max(requested_image_count, 3U);
  164. }
  165. VkSwapchainCreateInfoKHR swapchain_ci{
  166. .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR,
  167. .pNext = nullptr,
  168. .flags = 0,
  169. .surface = surface,
  170. .minImageCount = requested_image_count,
  171. .imageFormat = surface_format.format,
  172. .imageColorSpace = surface_format.colorSpace,
  173. .imageExtent = {},
  174. .imageArrayLayers = 1,
  175. .imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT,
  176. .imageSharingMode = VK_SHARING_MODE_EXCLUSIVE,
  177. .queueFamilyIndexCount = 0,
  178. .pQueueFamilyIndices = nullptr,
  179. .preTransform = capabilities.currentTransform,
  180. .compositeAlpha = alpha_flags,
  181. .presentMode = present_mode,
  182. .clipped = VK_FALSE,
  183. .oldSwapchain = nullptr,
  184. };
  185. const u32 graphics_family{device.GetGraphicsFamily()};
  186. const u32 present_family{device.GetPresentFamily()};
  187. const std::array<u32, 2> queue_indices{graphics_family, present_family};
  188. if (graphics_family != present_family) {
  189. swapchain_ci.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
  190. swapchain_ci.queueFamilyIndexCount = static_cast<u32>(queue_indices.size());
  191. swapchain_ci.pQueueFamilyIndices = queue_indices.data();
  192. }
  193. static constexpr std::array view_formats{VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_B8G8R8A8_SRGB};
  194. VkImageFormatListCreateInfo format_list{
  195. .sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_LIST_CREATE_INFO_KHR,
  196. .pNext = nullptr,
  197. .viewFormatCount = static_cast<u32>(view_formats.size()),
  198. .pViewFormats = view_formats.data(),
  199. };
  200. if (device.IsKhrSwapchainMutableFormatEnabled()) {
  201. format_list.pNext = std::exchange(swapchain_ci.pNext, &format_list);
  202. swapchain_ci.flags |= VK_SWAPCHAIN_CREATE_MUTABLE_FORMAT_BIT_KHR;
  203. }
  204. // Request the size again to reduce the possibility of a TOCTOU race condition.
  205. const auto updated_capabilities = physical_device.GetSurfaceCapabilitiesKHR(surface);
  206. swapchain_ci.imageExtent = ChooseSwapExtent(updated_capabilities, width, height);
  207. // Don't add code within this and the swapchain creation.
  208. swapchain = device.GetLogical().CreateSwapchainKHR(swapchain_ci);
  209. extent = swapchain_ci.imageExtent;
  210. current_srgb = srgb;
  211. current_fps_unlocked = !Settings::values.use_speed_limit.GetValue();
  212. images = swapchain.GetImages();
  213. image_count = static_cast<u32>(images.size());
  214. image_view_format = srgb ? VK_FORMAT_B8G8R8A8_SRGB : VK_FORMAT_B8G8R8A8_UNORM;
  215. }
  216. void Swapchain::CreateSemaphores() {
  217. present_semaphores.resize(image_count);
  218. std::ranges::generate(present_semaphores,
  219. [this] { return device.GetLogical().CreateSemaphore(); });
  220. render_semaphores.resize(image_count);
  221. std::ranges::generate(render_semaphores,
  222. [this] { return device.GetLogical().CreateSemaphore(); });
  223. }
  224. void Swapchain::Destroy() {
  225. frame_index = 0;
  226. present_semaphores.clear();
  227. swapchain.reset();
  228. }
  229. bool Swapchain::HasFpsUnlockChanged() const {
  230. return current_fps_unlocked != !Settings::values.use_speed_limit.GetValue();
  231. }
  232. bool Swapchain::NeedsPresentModeUpdate() const {
  233. // Mailbox present mode is the ideal for all scenarios. If it is not available,
  234. // A different present mode is needed to support unlocked FPS above the monitor's refresh rate.
  235. return present_mode != VK_PRESENT_MODE_MAILBOX_KHR && HasFpsUnlockChanged();
  236. }
  237. } // namespace Vulkan