| 1 | // Copyright 2016 Dolphin Emulator Project |
| 2 | // SPDX-License-Identifier: GPL-2.0-or-later |
| 3 | |
| 4 | #include "VideoBackends/Vulkan/VideoBackend.h" |
| 5 | |
| 6 | #include "Common/Logging/LogManager.h" |
| 7 | #include "Common/MsgHandler.h" |
| 8 | |
| 9 | #include "VideoBackends/Vulkan/CommandBufferManager.h" |
| 10 | #include "VideoBackends/Vulkan/ObjectCache.h" |
| 11 | #include "VideoBackends/Vulkan/StateTracker.h" |
| 12 | #include "VideoBackends/Vulkan/VKBoundingBox.h" |
| 13 | #include "VideoBackends/Vulkan/VKGfx.h" |
| 14 | #include "VideoBackends/Vulkan/VKPerfQuery.h" |
| 15 | #include "VideoBackends/Vulkan/VKSwapChain.h" |
| 16 | #include "VideoBackends/Vulkan/VKVertexManager.h" |
| 17 | #include "VideoBackends/Vulkan/VulkanContext.h" |
| 18 | |
| 19 | #include "VideoCommon/TextureCacheBase.h" |
| 20 | #include "VideoCommon/VideoConfig.h" |
| 21 | |
| 22 | #if defined(VK_USE_PLATFORM_METAL_EXT) |
| 23 | #include <objc/message.h> |
| 24 | #endif |
| 25 | |
| 26 | namespace Vulkan |
| 27 | { |
| 28 | void VideoBackend::InitBackendInfo(const WindowSystemInfo& wsi) |
| 29 | { |
| 30 | VulkanContext::PopulateBackendInfo(&g_backend_info); |
| 31 | |
| 32 | if (LoadVulkanLibrary()) |
| 33 | { |
| 34 | u32 vk_api_version = 0; |
| 35 | VkInstance temp_instance = VulkanContext::CreateVulkanInstance(WindowSystemType::Headless, |
| 36 | false, false, &vk_api_version); |
| 37 | if (temp_instance) |
| 38 | { |
| 39 | if (LoadVulkanInstanceFunctions(temp_instance)) |
| 40 | { |
| 41 | VulkanContext::GPUList gpu_list = VulkanContext::EnumerateGPUs(temp_instance); |
| 42 | VulkanContext::PopulateBackendInfoAdapters(&g_backend_info, gpu_list); |
| 43 | |
| 44 | if (!gpu_list.empty()) |
| 45 | { |
| 46 | // Use the selected adapter, or the first to fill features. |
| 47 | size_t device_index = static_cast<size_t>(g_Config.iAdapter); |
| 48 | if (device_index >= gpu_list.size()) |
| 49 | device_index = 0; |
| 50 | |
| 51 | VkPhysicalDevice gpu = gpu_list[device_index]; |
| 52 | VulkanContext::PhysicalDeviceInfo properties(gpu); |
| 53 | VulkanContext::PopulateBackendInfoFeatures(&g_backend_info, gpu, properties); |
| 54 | VulkanContext::PopulateBackendInfoMultisampleModes(&g_backend_info, gpu, properties); |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | vkDestroyInstance(temp_instance, nullptr); |
| 59 | } |
| 60 | else |
| 61 | { |
| 62 | PanicAlertFmt("Failed to create Vulkan instance."); |
| 63 | } |
| 64 | |
| 65 | UnloadVulkanLibrary(); |
| 66 | } |
| 67 | else |
| 68 | { |
| 69 | PanicAlertFmt("Failed to load Vulkan library."); |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | // Helper method to check whether the Host GPU logging category is enabled. |
| 74 | static bool IsHostGPULoggingEnabled() |
| 75 | { |
| 76 | return Common::Log::LogManager::GetInstance()->IsEnabled(Common::Log::LogType::HOST_GPU, |
| 77 | Common::Log::LogLevel::LERROR); |
| 78 | } |
| 79 | |
| 80 | // Helper method to determine whether to enable the debug utils extension. |
| 81 | static bool ShouldEnableDebugUtils(bool enable_validation_layers) |
| 82 | { |
| 83 | // Enable debug utils if the Host GPU log option is checked, or validation layers are enabled. |
| 84 | // The only issue here is that if Host GPU is not checked when the instance is created, the debug |
| 85 | // report extension will not be enabled, requiring the game to be restarted before any reports |
| 86 | // will be logged. Otherwise, we'd have to enable debug utils on every instance, when most |
| 87 | // users will never check the Host GPU logging category. |
| 88 | return enable_validation_layers || IsHostGPULoggingEnabled(); |
| 89 | } |
| 90 | |
| 91 | bool VideoBackend::Initialize(const WindowSystemInfo& wsi) |
| 92 | { |
| 93 | if (!LoadVulkanLibrary()) |
| 94 | { |
| 95 | PanicAlertFmt("Failed to load Vulkan library."); |
| 96 | return false; |
| 97 | } |
| 98 | |
| 99 | // Check for presence of the validation layers before trying to enable it |
| 100 | bool enable_validation_layer = g_Config.bEnableValidationLayer; |
| 101 | if (enable_validation_layer && !VulkanContext::CheckValidationLayerAvailablility()) |
| 102 | { |
| 103 | WARN_LOG_FMT(VIDEO, "Validation layer requested but not available, disabling."); |
| 104 | enable_validation_layer = false; |
| 105 | } |
| 106 | |
| 107 | // Create Vulkan instance, needed before we can create a surface, or enumerate devices. |
| 108 | // We use this instance to fill in backend info, then re-use it for the actual device. |
| 109 | bool enable_surface = wsi.type != WindowSystemType::Headless; |
| 110 | bool enable_debug_utils = ShouldEnableDebugUtils(enable_validation_layer); |
| 111 | u32 vk_api_version = 0; |
| 112 | VkInstance instance = VulkanContext::CreateVulkanInstance( |
| 113 | wsi.type, enable_debug_utils, enable_validation_layer, &vk_api_version); |
| 114 | if (instance == VK_NULL_HANDLE) |
| 115 | { |
| 116 | PanicAlertFmt("Failed to create Vulkan instance."); |
| 117 | UnloadVulkanLibrary(); |
| 118 | return false; |
| 119 | } |
| 120 | |
| 121 | // Load instance function pointers. |
| 122 | if (!LoadVulkanInstanceFunctions(instance)) |
| 123 | { |
| 124 | PanicAlertFmt("Failed to load Vulkan instance functions."); |
| 125 | vkDestroyInstance(instance, nullptr); |
| 126 | UnloadVulkanLibrary(); |
| 127 | return false; |
| 128 | } |
| 129 | |
| 130 | // Obtain a list of physical devices (GPUs) from the instance. |
| 131 | // We'll re-use this list later when creating the device. |
| 132 | VulkanContext::GPUList gpu_list = VulkanContext::EnumerateGPUs(instance); |
| 133 | if (gpu_list.empty()) |
| 134 | { |
| 135 | PanicAlertFmt("No Vulkan physical devices available."); |
| 136 | vkDestroyInstance(instance, nullptr); |
| 137 | UnloadVulkanLibrary(); |
| 138 | return false; |
| 139 | } |
| 140 | |
| 141 | // Populate BackendInfo with as much information as we can at this point. |
| 142 | VulkanContext::PopulateBackendInfo(&g_backend_info); |
| 143 | VulkanContext::PopulateBackendInfoAdapters(&g_backend_info, gpu_list); |
| 144 | |
| 145 | // We need the surface before we can create a device, as some parameters depend on it. |
| 146 | VkSurfaceKHR surface = VK_NULL_HANDLE; |
| 147 | if (enable_surface) |
| 148 | { |
| 149 | surface = SwapChain::CreateVulkanSurface(instance, wsi); |
| 150 | if (surface == VK_NULL_HANDLE) |
| 151 | { |
| 152 | PanicAlertFmt("Failed to create Vulkan surface."); |
| 153 | vkDestroyInstance(instance, nullptr); |
| 154 | UnloadVulkanLibrary(); |
| 155 | return false; |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | // Since we haven't called InitializeShared yet, iAdapter may be out of range, |
| 160 | // so we have to check it ourselves. |
| 161 | size_t selected_adapter_index = static_cast<size_t>(g_Config.iAdapter); |
| 162 | if (selected_adapter_index >= gpu_list.size()) |
| 163 | { |
| 164 | WARN_LOG_FMT(VIDEO, "Vulkan adapter index out of range, selecting first adapter."); |
| 165 | selected_adapter_index = 0; |
| 166 | } |
| 167 | |
| 168 | // Now we can create the Vulkan device. VulkanContext takes ownership of the instance and surface. |
| 169 | g_vulkan_context = |
| 170 | VulkanContext::Create(instance, gpu_list[selected_adapter_index], surface, enable_debug_utils, |
| 171 | enable_validation_layer, vk_api_version); |
| 172 | if (!g_vulkan_context) |
| 173 | { |
| 174 | PanicAlertFmt("Failed to create Vulkan device"); |
| 175 | UnloadVulkanLibrary(); |
| 176 | return false; |
| 177 | } |
| 178 | |
| 179 | // Since VulkanContext maintains a copy of the device features and properties, we can use this |
| 180 | // to initialize the backend information, so that we don't need to enumerate everything again. |
| 181 | VulkanContext::PopulateBackendInfoFeatures(&g_backend_info, g_vulkan_context->GetPhysicalDevice(), |
| 182 | g_vulkan_context->GetDeviceInfo()); |
| 183 | VulkanContext::PopulateBackendInfoMultisampleModes( |
| 184 | &g_backend_info, g_vulkan_context->GetPhysicalDevice(), g_vulkan_context->GetDeviceInfo()); |
| 185 | g_backend_info.bSupportsExclusiveFullscreen = |
| 186 | enable_surface && g_vulkan_context->SupportsExclusiveFullscreen(wsi, surface); |
| 187 | |
| 188 | UpdateActiveConfig(); |
| 189 | |
| 190 | // Remaining classes are also dependent on object cache. |
| 191 | g_object_cache = std::make_unique<ObjectCache>(); |
| 192 | if (!g_object_cache->Initialize()) |
| 193 | { |
| 194 | PanicAlertFmt("Failed to initialize Vulkan object cache."); |
| 195 | Shutdown(); |
| 196 | return false; |
| 197 | } |
| 198 | |
| 199 | // Create swap chain. This has to be done early so that the target size is correct for auto-scale. |
| 200 | std::unique_ptr<SwapChain> swap_chain; |
| 201 | if (surface != VK_NULL_HANDLE) |
| 202 | { |
| 203 | swap_chain = SwapChain::Create(wsi, surface, g_ActiveConfig.bVSyncActive); |
| 204 | if (!swap_chain) |
| 205 | { |
| 206 | PanicAlertFmt("Failed to create Vulkan swap chain."); |
| 207 | Shutdown(); |
| 208 | return false; |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | // Create command buffers. We do this separately because the other classes depend on it. |
| 213 | g_command_buffer_mgr = std::make_unique<CommandBufferManager>(g_Config.bBackendMultithreading); |
| 214 | size_t swapchain_image_count = |
| 215 | surface != VK_NULL_HANDLE ? swap_chain->GetSwapChainImageCount() : 0; |
| 216 | if (!g_command_buffer_mgr->Initialize(swapchain_image_count)) |
| 217 | { |
| 218 | PanicAlertFmt("Failed to create Vulkan command buffers"); |
| 219 | Shutdown(); |
| 220 | return false; |
| 221 | } |
| 222 | |
| 223 | if (!StateTracker::CreateInstance()) |
| 224 | { |
| 225 | PanicAlertFmt("Failed to create state tracker"); |
| 226 | Shutdown(); |
| 227 | return false; |
| 228 | } |
| 229 | |
| 230 | auto gfx = std::make_unique<VKGfx>(std::move(swap_chain), wsi.render_surface_scale); |
| 231 | auto vertex_manager = std::make_unique<VertexManager>(); |
| 232 | auto perf_query = std::make_unique<PerfQuery>(); |
| 233 | auto bounding_box = std::make_unique<VKBoundingBox>(); |
| 234 | |
| 235 | return InitializeShared(std::move(gfx), std::move(vertex_manager), std::move(perf_query), |
| 236 | std::move(bounding_box)); |
| 237 | } |
| 238 | |
| 239 | void VideoBackend::Shutdown() |
| 240 | { |
| 241 | if (g_vulkan_context) |
| 242 | vkDeviceWaitIdle(g_vulkan_context->GetDevice()); |
| 243 | |
| 244 | if (g_object_cache) |
| 245 | g_object_cache->Shutdown(); |
| 246 | |
| 247 | ShutdownShared(); |
| 248 | |
| 249 | g_object_cache.reset(); |
| 250 | StateTracker::DestroyInstance(); |
| 251 | g_command_buffer_mgr.reset(); |
| 252 | g_vulkan_context.reset(); |
| 253 | UnloadVulkanLibrary(); |
| 254 | } |
| 255 | |
| 256 | void VideoBackend::PrepareWindow(WindowSystemInfo& wsi) |
| 257 | { |
| 258 | #if defined(VK_USE_PLATFORM_METAL_EXT) |
| 259 | // We only need to manually create the CAMetalLayer on macOS. |
| 260 | if (wsi.type != WindowSystemType::MacOS) |
| 261 | return; |
| 262 | |
| 263 | // This is kinda messy, but it avoids having to write Objective C++ just to create a metal layer. |
| 264 | id view = reinterpret_cast<id>(wsi.render_surface); |
| 265 | Class clsCAMetalLayer = objc_getClass("CAMetalLayer"); |
| 266 | if (!clsCAMetalLayer) |
| 267 | { |
| 268 | ERROR_LOG_FMT(VIDEO, "Failed to get CAMetalLayer class."); |
| 269 | return; |
| 270 | } |
| 271 | |
| 272 | // [CAMetalLayer layer] |
| 273 | id layer = reinterpret_cast<id (*)(Class, SEL)>(objc_msgSend)(objc_getClass("CAMetalLayer"), |
| 274 | sel_getUid("layer")); |
| 275 | if (!layer) |
| 276 | { |
| 277 | ERROR_LOG_FMT(VIDEO, "Failed to create Metal layer."); |
| 278 | return; |
| 279 | } |
| 280 | |
| 281 | // [view setWantsLayer:YES] |
| 282 | reinterpret_cast<void (*)(id, SEL, BOOL)>(objc_msgSend)(view, sel_getUid("setWantsLayer:"), YES); |
| 283 | |
| 284 | // [view setLayer:layer] |
| 285 | reinterpret_cast<void (*)(id, SEL, id)>(objc_msgSend)(view, sel_getUid("setLayer:"), layer); |
| 286 | |
| 287 | // NSScreen* screen = [NSScreen mainScreen] |
| 288 | id screen = reinterpret_cast<id (*)(Class, SEL)>(objc_msgSend)(objc_getClass("NSScreen"), |
| 289 | sel_getUid("mainScreen")); |
| 290 | |
| 291 | // CGFloat factor = [screen backingScaleFactor] |
| 292 | double factor = |
| 293 | reinterpret_cast<double (*)(id, SEL)>(objc_msgSend)(screen, sel_getUid("backingScaleFactor")); |
| 294 | |
| 295 | // layer.contentsScale = factor |
| 296 | reinterpret_cast<void (*)(id, SEL, double)>(objc_msgSend)(layer, sel_getUid("setContentsScale:"), |
| 297 | factor); |
| 298 | |
| 299 | // Store the layer pointer, that way MoltenVK doesn't call [NSView layer] outside the main thread. |
| 300 | wsi.render_surface = layer; |
| 301 | #endif |
| 302 | } |
| 303 | } // namespace Vulkan |