vk_swapchain.cpp 10 KB

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