rendering_context_driver_vulkan.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  1. /**************************************************************************/
  2. /* rendering_context_driver_vulkan.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #ifdef VULKAN_ENABLED
  31. #include "rendering_context_driver_vulkan.h"
  32. #include "vk_enum_string_helper.h"
  33. #include "core/config/project_settings.h"
  34. #include "core/version.h"
  35. #include "rendering_device_driver_vulkan.h"
  36. #include "vulkan_hooks.h"
  37. RenderingContextDriverVulkan::RenderingContextDriverVulkan() {
  38. // Empty constructor.
  39. }
  40. RenderingContextDriverVulkan::~RenderingContextDriverVulkan() {
  41. if (debug_messenger != VK_NULL_HANDLE && functions.DestroyDebugUtilsMessengerEXT != nullptr) {
  42. functions.DestroyDebugUtilsMessengerEXT(instance, debug_messenger, nullptr);
  43. }
  44. if (debug_report != VK_NULL_HANDLE && functions.DestroyDebugReportCallbackEXT != nullptr) {
  45. functions.DestroyDebugReportCallbackEXT(instance, debug_report, nullptr);
  46. }
  47. if (instance != VK_NULL_HANDLE) {
  48. vkDestroyInstance(instance, nullptr);
  49. }
  50. }
  51. Error RenderingContextDriverVulkan::_initialize_vulkan_version() {
  52. // https://www.khronos.org/registry/vulkan/specs/1.2-extensions/man/html/VkApplicationInfo.html#_description
  53. // For Vulkan 1.0 vkEnumerateInstanceVersion is not available, including not in the loader we compile against on Android.
  54. typedef VkResult(VKAPI_PTR * _vkEnumerateInstanceVersion)(uint32_t *);
  55. _vkEnumerateInstanceVersion func = (_vkEnumerateInstanceVersion)vkGetInstanceProcAddr(nullptr, "vkEnumerateInstanceVersion");
  56. if (func != nullptr) {
  57. uint32_t api_version;
  58. VkResult res = func(&api_version);
  59. if (res == VK_SUCCESS) {
  60. instance_api_version = api_version;
  61. } else {
  62. // According to the documentation this shouldn't fail with anything except a memory allocation error
  63. // in which case we're in deep trouble anyway.
  64. ERR_FAIL_V(ERR_CANT_CREATE);
  65. }
  66. } else {
  67. print_line("vkEnumerateInstanceVersion not available, assuming Vulkan 1.0.");
  68. instance_api_version = VK_API_VERSION_1_0;
  69. }
  70. return OK;
  71. }
  72. void RenderingContextDriverVulkan::_register_requested_instance_extension(const CharString &p_extension_name, bool p_required) {
  73. ERR_FAIL_COND(requested_instance_extensions.has(p_extension_name));
  74. requested_instance_extensions[p_extension_name] = p_required;
  75. }
  76. Error RenderingContextDriverVulkan::_initialize_instance_extensions() {
  77. enabled_instance_extension_names.clear();
  78. // The surface extension and the platform-specific surface extension are core requirements.
  79. _register_requested_instance_extension(VK_KHR_SURFACE_EXTENSION_NAME, true);
  80. if (_get_platform_surface_extension()) {
  81. _register_requested_instance_extension(_get_platform_surface_extension(), true);
  82. }
  83. if (_use_validation_layers()) {
  84. _register_requested_instance_extension(VK_EXT_DEBUG_REPORT_EXTENSION_NAME, false);
  85. }
  86. // This extension allows us to use the properties2 features to query additional device capabilities.
  87. _register_requested_instance_extension(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME, false);
  88. // Only enable debug utils in verbose mode or DEV_ENABLED.
  89. // End users would get spammed with messages of varying verbosity due to the
  90. // mess that thirdparty layers/extensions and drivers seem to leave in their
  91. // wake, making the Windows registry a bottomless pit of broken layer JSON.
  92. #ifdef DEV_ENABLED
  93. bool want_debug_utils = true;
  94. #else
  95. bool want_debug_utils = OS::get_singleton()->is_stdout_verbose();
  96. #endif
  97. if (want_debug_utils) {
  98. _register_requested_instance_extension(VK_EXT_DEBUG_UTILS_EXTENSION_NAME, false);
  99. }
  100. // Load instance extensions that are available.
  101. uint32_t instance_extension_count = 0;
  102. VkResult err = vkEnumerateInstanceExtensionProperties(nullptr, &instance_extension_count, nullptr);
  103. ERR_FAIL_COND_V(err != VK_SUCCESS && err != VK_INCOMPLETE, ERR_CANT_CREATE);
  104. ERR_FAIL_COND_V_MSG(instance_extension_count == 0, ERR_CANT_CREATE, "No instance extensions were found.");
  105. TightLocalVector<VkExtensionProperties> instance_extensions;
  106. instance_extensions.resize(instance_extension_count);
  107. err = vkEnumerateInstanceExtensionProperties(nullptr, &instance_extension_count, instance_extensions.ptr());
  108. if (err != VK_SUCCESS && err != VK_INCOMPLETE) {
  109. ERR_FAIL_V(ERR_CANT_CREATE);
  110. }
  111. #ifdef DEV_ENABLED
  112. for (uint32_t i = 0; i < instance_extension_count; i++) {
  113. print_verbose(String("VULKAN: Found instance extension ") + String::utf8(instance_extensions[i].extensionName) + String("."));
  114. }
  115. #endif
  116. // Enable all extensions that are supported and requested.
  117. for (uint32_t i = 0; i < instance_extension_count; i++) {
  118. CharString extension_name(instance_extensions[i].extensionName);
  119. if (requested_instance_extensions.has(extension_name)) {
  120. enabled_instance_extension_names.insert(extension_name);
  121. }
  122. }
  123. // Now check our requested extensions.
  124. for (KeyValue<CharString, bool> &requested_extension : requested_instance_extensions) {
  125. if (!enabled_instance_extension_names.has(requested_extension.key)) {
  126. if (requested_extension.value) {
  127. ERR_FAIL_V_MSG(ERR_BUG, String("Required extension ") + String::utf8(requested_extension.key) + String(" not found."));
  128. } else {
  129. print_verbose(String("Optional extension ") + String::utf8(requested_extension.key) + String(" not found."));
  130. }
  131. }
  132. }
  133. return OK;
  134. }
  135. Error RenderingContextDriverVulkan::_find_validation_layers(TightLocalVector<const char *> &r_layer_names) const {
  136. r_layer_names.clear();
  137. uint32_t instance_layer_count = 0;
  138. VkResult err = vkEnumerateInstanceLayerProperties(&instance_layer_count, nullptr);
  139. ERR_FAIL_COND_V(err != VK_SUCCESS, ERR_CANT_CREATE);
  140. if (instance_layer_count > 0) {
  141. TightLocalVector<VkLayerProperties> layer_properties;
  142. layer_properties.resize(instance_layer_count);
  143. err = vkEnumerateInstanceLayerProperties(&instance_layer_count, layer_properties.ptr());
  144. ERR_FAIL_COND_V(err != VK_SUCCESS, ERR_CANT_CREATE);
  145. // Preferred set of validation layers.
  146. const std::initializer_list<const char *> preferred = { "VK_LAYER_KHRONOS_validation" };
  147. // Alternative (deprecated, removed in SDK 1.1.126.0) set of validation layers.
  148. const std::initializer_list<const char *> lunarg = { "VK_LAYER_LUNARG_standard_validation" };
  149. // Alternative (deprecated, removed in SDK 1.1.121.1) set of validation layers.
  150. const std::initializer_list<const char *> google = { "VK_LAYER_GOOGLE_threading", "VK_LAYER_LUNARG_parameter_validation", "VK_LAYER_LUNARG_object_tracker", "VK_LAYER_LUNARG_core_validation", "VK_LAYER_GOOGLE_unique_objects" };
  151. // Verify all the layers of the list are present.
  152. for (const std::initializer_list<const char *> &list : { preferred, lunarg, google }) {
  153. bool layers_found = false;
  154. for (const char *layer_name : list) {
  155. layers_found = false;
  156. for (const VkLayerProperties &properties : layer_properties) {
  157. if (!strcmp(properties.layerName, layer_name)) {
  158. layers_found = true;
  159. break;
  160. }
  161. }
  162. if (!layers_found) {
  163. break;
  164. }
  165. }
  166. if (layers_found) {
  167. r_layer_names.reserve(list.size());
  168. for (const char *layer_name : list) {
  169. r_layer_names.push_back(layer_name);
  170. }
  171. break;
  172. }
  173. }
  174. }
  175. return OK;
  176. }
  177. VKAPI_ATTR VkBool32 VKAPI_CALL RenderingContextDriverVulkan::_debug_messenger_callback(VkDebugUtilsMessageSeverityFlagBitsEXT p_message_severity, VkDebugUtilsMessageTypeFlagsEXT p_message_type, const VkDebugUtilsMessengerCallbackDataEXT *p_callback_data, void *p_user_data) {
  178. // This error needs to be ignored because the AMD allocator will mix up memory types on IGP processors.
  179. if (strstr(p_callback_data->pMessage, "Mapping an image with layout") != nullptr && strstr(p_callback_data->pMessage, "can result in undefined behavior if this memory is used by the device") != nullptr) {
  180. return VK_FALSE;
  181. }
  182. // This needs to be ignored because Validator is wrong here.
  183. if (strstr(p_callback_data->pMessage, "Invalid SPIR-V binary version 1.3") != nullptr) {
  184. return VK_FALSE;
  185. }
  186. // This needs to be ignored because Validator is wrong here.
  187. if (strstr(p_callback_data->pMessage, "Shader requires flag") != nullptr) {
  188. return VK_FALSE;
  189. }
  190. // This needs to be ignored because Validator is wrong here.
  191. if (strstr(p_callback_data->pMessage, "SPIR-V module not valid: Pointer operand") != nullptr && strstr(p_callback_data->pMessage, "must be a memory object") != nullptr) {
  192. return VK_FALSE;
  193. }
  194. if (p_callback_data->pMessageIdName && strstr(p_callback_data->pMessageIdName, "UNASSIGNED-CoreValidation-DrawState-ClearCmdBeforeDraw") != nullptr) {
  195. return VK_FALSE;
  196. }
  197. String type_string;
  198. switch (p_message_type) {
  199. case (VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT):
  200. type_string = "GENERAL";
  201. break;
  202. case (VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT):
  203. type_string = "VALIDATION";
  204. break;
  205. case (VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT):
  206. type_string = "PERFORMANCE";
  207. break;
  208. case (VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT & VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT):
  209. type_string = "VALIDATION|PERFORMANCE";
  210. break;
  211. }
  212. String objects_string;
  213. if (p_callback_data->objectCount > 0) {
  214. objects_string = "\n\tObjects - " + String::num_int64(p_callback_data->objectCount);
  215. for (uint32_t object = 0; object < p_callback_data->objectCount; ++object) {
  216. objects_string +=
  217. "\n\t\tObject[" + String::num_int64(object) + "]" +
  218. " - " + string_VkObjectType(p_callback_data->pObjects[object].objectType) +
  219. ", Handle " + String::num_int64(p_callback_data->pObjects[object].objectHandle);
  220. if (p_callback_data->pObjects[object].pObjectName != nullptr && strlen(p_callback_data->pObjects[object].pObjectName) > 0) {
  221. objects_string += ", Name \"" + String(p_callback_data->pObjects[object].pObjectName) + "\"";
  222. }
  223. }
  224. }
  225. String labels_string;
  226. if (p_callback_data->cmdBufLabelCount > 0) {
  227. labels_string = "\n\tCommand Buffer Labels - " + String::num_int64(p_callback_data->cmdBufLabelCount);
  228. for (uint32_t cmd_buf_label = 0; cmd_buf_label < p_callback_data->cmdBufLabelCount; ++cmd_buf_label) {
  229. labels_string +=
  230. "\n\t\tLabel[" + String::num_int64(cmd_buf_label) + "]" +
  231. " - " + p_callback_data->pCmdBufLabels[cmd_buf_label].pLabelName +
  232. "{ ";
  233. for (int color_idx = 0; color_idx < 4; ++color_idx) {
  234. labels_string += String::num(p_callback_data->pCmdBufLabels[cmd_buf_label].color[color_idx]);
  235. if (color_idx < 3) {
  236. labels_string += ", ";
  237. }
  238. }
  239. labels_string += " }";
  240. }
  241. }
  242. String error_message(type_string +
  243. " - Message Id Number: " + String::num_int64(p_callback_data->messageIdNumber) +
  244. " | Message Id Name: " + p_callback_data->pMessageIdName +
  245. "\n\t" + p_callback_data->pMessage +
  246. objects_string + labels_string);
  247. // Convert VK severity to our own log macros.
  248. switch (p_message_severity) {
  249. case VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT:
  250. print_verbose(error_message);
  251. break;
  252. case VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT:
  253. print_line(error_message);
  254. break;
  255. case VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT:
  256. WARN_PRINT(error_message);
  257. break;
  258. case VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT:
  259. ERR_PRINT(error_message);
  260. CRASH_COND_MSG(Engine::get_singleton()->is_abort_on_gpu_errors_enabled(), "Crashing, because abort on GPU errors is enabled.");
  261. break;
  262. case VK_DEBUG_UTILS_MESSAGE_SEVERITY_FLAG_BITS_MAX_ENUM_EXT:
  263. break; // Shouldn't happen, only handling to make compilers happy.
  264. }
  265. return VK_FALSE;
  266. }
  267. VKAPI_ATTR VkBool32 VKAPI_CALL RenderingContextDriverVulkan::_debug_report_callback(VkDebugReportFlagsEXT p_flags, VkDebugReportObjectTypeEXT p_object_type, uint64_t p_object, size_t p_location, int32_t p_message_code, const char *p_layer_prefix, const char *p_message, void *p_user_data) {
  268. String debug_message = String("Vulkan Debug Report: object - ") + String::num_int64(p_object) + "\n" + p_message;
  269. switch (p_flags) {
  270. case VK_DEBUG_REPORT_DEBUG_BIT_EXT:
  271. case VK_DEBUG_REPORT_INFORMATION_BIT_EXT:
  272. print_line(debug_message);
  273. break;
  274. case VK_DEBUG_REPORT_WARNING_BIT_EXT:
  275. case VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT:
  276. WARN_PRINT(debug_message);
  277. break;
  278. case VK_DEBUG_REPORT_ERROR_BIT_EXT:
  279. ERR_PRINT(debug_message);
  280. break;
  281. }
  282. return VK_FALSE;
  283. }
  284. Error RenderingContextDriverVulkan::_initialize_instance() {
  285. Error err;
  286. TightLocalVector<const char *> enabled_extension_names;
  287. enabled_extension_names.reserve(enabled_instance_extension_names.size());
  288. for (const CharString &extension_name : enabled_instance_extension_names) {
  289. enabled_extension_names.push_back(extension_name.ptr());
  290. }
  291. // We'll set application version to the Vulkan version we're developing against, even if our instance is based on an older Vulkan
  292. // version, devices can still support newer versions of Vulkan. The exception is when we're on Vulkan 1.0, we should not set this
  293. // to anything but 1.0. Note that this value is only used by validation layers to warn us about version issues.
  294. uint32_t application_api_version = instance_api_version == VK_API_VERSION_1_0 ? VK_API_VERSION_1_0 : VK_API_VERSION_1_2;
  295. CharString cs = GLOBAL_GET("application/config/name").operator String().utf8();
  296. VkApplicationInfo app_info = {};
  297. app_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
  298. app_info.pApplicationName = cs.get_data();
  299. app_info.pEngineName = VERSION_NAME;
  300. app_info.engineVersion = VK_MAKE_VERSION(VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH);
  301. app_info.apiVersion = application_api_version;
  302. TightLocalVector<const char *> enabled_layer_names;
  303. if (_use_validation_layers()) {
  304. err = _find_validation_layers(enabled_layer_names);
  305. ERR_FAIL_COND_V(err != OK, err);
  306. }
  307. VkInstanceCreateInfo instance_info = {};
  308. instance_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
  309. instance_info.pApplicationInfo = &app_info;
  310. instance_info.enabledExtensionCount = enabled_extension_names.size();
  311. instance_info.ppEnabledExtensionNames = enabled_extension_names.ptr();
  312. instance_info.enabledLayerCount = enabled_layer_names.size();
  313. instance_info.ppEnabledLayerNames = enabled_layer_names.ptr();
  314. // This is info for a temp callback to use during CreateInstance. After the instance is created, we use the instance-based function to register the final callback.
  315. VkDebugUtilsMessengerCreateInfoEXT debug_messenger_create_info = {};
  316. VkDebugReportCallbackCreateInfoEXT debug_report_callback_create_info = {};
  317. const bool has_debug_utils_extension = enabled_instance_extension_names.has(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
  318. const bool has_debug_report_extension = enabled_instance_extension_names.has(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
  319. if (has_debug_utils_extension) {
  320. debug_messenger_create_info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
  321. debug_messenger_create_info.pNext = nullptr;
  322. debug_messenger_create_info.flags = 0;
  323. debug_messenger_create_info.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
  324. debug_messenger_create_info.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
  325. debug_messenger_create_info.pfnUserCallback = _debug_messenger_callback;
  326. debug_messenger_create_info.pUserData = this;
  327. instance_info.pNext = &debug_messenger_create_info;
  328. } else if (has_debug_report_extension) {
  329. debug_report_callback_create_info.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT;
  330. debug_report_callback_create_info.flags = VK_DEBUG_REPORT_INFORMATION_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT | VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_DEBUG_BIT_EXT;
  331. debug_report_callback_create_info.pfnCallback = _debug_report_callback;
  332. debug_report_callback_create_info.pUserData = this;
  333. instance_info.pNext = &debug_report_callback_create_info;
  334. }
  335. err = _create_vulkan_instance(&instance_info, &instance);
  336. ERR_FAIL_COND_V(err != OK, err);
  337. #ifdef USE_VOLK
  338. volkLoadInstance(instance);
  339. #endif
  340. // Physical device.
  341. if (enabled_instance_extension_names.has(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
  342. functions.GetPhysicalDeviceFeatures2 = PFN_vkGetPhysicalDeviceFeatures2(vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceFeatures2"));
  343. functions.GetPhysicalDeviceProperties2 = PFN_vkGetPhysicalDeviceProperties2(vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceProperties2"));
  344. // In Vulkan 1.0, the functions might be accessible under their original extension names.
  345. if (functions.GetPhysicalDeviceFeatures2 == nullptr) {
  346. functions.GetPhysicalDeviceFeatures2 = PFN_vkGetPhysicalDeviceFeatures2(vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceFeatures2KHR"));
  347. }
  348. if (functions.GetPhysicalDeviceProperties2 == nullptr) {
  349. functions.GetPhysicalDeviceProperties2 = PFN_vkGetPhysicalDeviceProperties2(vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceProperties2KHR"));
  350. }
  351. }
  352. // Device.
  353. functions.GetDeviceProcAddr = PFN_vkGetDeviceProcAddr(vkGetInstanceProcAddr(instance, "vkGetDeviceProcAddr"));
  354. // Surfaces.
  355. functions.GetPhysicalDeviceSurfaceSupportKHR = PFN_vkGetPhysicalDeviceSurfaceSupportKHR(vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceSurfaceSupportKHR"));
  356. functions.GetPhysicalDeviceSurfaceFormatsKHR = PFN_vkGetPhysicalDeviceSurfaceFormatsKHR(vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceSurfaceFormatsKHR"));
  357. functions.GetPhysicalDeviceSurfaceCapabilitiesKHR = PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR(vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceSurfaceCapabilitiesKHR"));
  358. functions.GetPhysicalDeviceSurfacePresentModesKHR = PFN_vkGetPhysicalDeviceSurfacePresentModesKHR(vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceSurfacePresentModesKHR"));
  359. // Debug utils and report.
  360. if (has_debug_utils_extension) {
  361. // Setup VK_EXT_debug_utils function pointers always (we use them for debug labels and names).
  362. functions.CreateDebugUtilsMessengerEXT = (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkCreateDebugUtilsMessengerEXT");
  363. functions.DestroyDebugUtilsMessengerEXT = (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkDestroyDebugUtilsMessengerEXT");
  364. functions.CmdBeginDebugUtilsLabelEXT = (PFN_vkCmdBeginDebugUtilsLabelEXT)vkGetInstanceProcAddr(instance, "vkCmdBeginDebugUtilsLabelEXT");
  365. functions.CmdEndDebugUtilsLabelEXT = (PFN_vkCmdEndDebugUtilsLabelEXT)vkGetInstanceProcAddr(instance, "vkCmdEndDebugUtilsLabelEXT");
  366. functions.SetDebugUtilsObjectNameEXT = (PFN_vkSetDebugUtilsObjectNameEXT)vkGetInstanceProcAddr(instance, "vkSetDebugUtilsObjectNameEXT");
  367. if (!functions.debug_util_functions_available()) {
  368. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "GetProcAddr: Failed to init VK_EXT_debug_utils\nGetProcAddr: Failure");
  369. }
  370. VkResult res = functions.CreateDebugUtilsMessengerEXT(instance, &debug_messenger_create_info, nullptr, &debug_messenger);
  371. switch (res) {
  372. case VK_SUCCESS:
  373. break;
  374. case VK_ERROR_OUT_OF_HOST_MEMORY:
  375. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "CreateDebugUtilsMessengerEXT: out of host memory\nCreateDebugUtilsMessengerEXT Failure");
  376. break;
  377. default:
  378. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "CreateDebugUtilsMessengerEXT: unknown failure\nCreateDebugUtilsMessengerEXT Failure");
  379. break;
  380. }
  381. } else if (has_debug_report_extension) {
  382. functions.CreateDebugReportCallbackEXT = (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(instance, "vkCreateDebugReportCallbackEXT");
  383. functions.DebugReportMessageEXT = (PFN_vkDebugReportMessageEXT)vkGetInstanceProcAddr(instance, "vkDebugReportMessageEXT");
  384. functions.DestroyDebugReportCallbackEXT = (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(instance, "vkDestroyDebugReportCallbackEXT");
  385. if (!functions.debug_report_functions_available()) {
  386. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "GetProcAddr: Failed to init VK_EXT_debug_report\nGetProcAddr: Failure");
  387. }
  388. VkResult res = functions.CreateDebugReportCallbackEXT(instance, &debug_report_callback_create_info, nullptr, &debug_report);
  389. switch (res) {
  390. case VK_SUCCESS:
  391. break;
  392. case VK_ERROR_OUT_OF_HOST_MEMORY:
  393. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "CreateDebugReportCallbackEXT: out of host memory\nCreateDebugReportCallbackEXT Failure");
  394. break;
  395. default:
  396. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "CreateDebugReportCallbackEXT: unknown failure\nCreateDebugReportCallbackEXT Failure");
  397. break;
  398. }
  399. }
  400. return OK;
  401. }
  402. Error RenderingContextDriverVulkan::_initialize_devices() {
  403. if (VulkanHooks::get_singleton() != nullptr) {
  404. VkPhysicalDevice physical_device;
  405. bool device_retrieved = VulkanHooks::get_singleton()->get_physical_device(&physical_device);
  406. ERR_FAIL_COND_V(!device_retrieved, ERR_CANT_CREATE);
  407. // When a hook is active, pretend the device returned by the hook is the only device available.
  408. driver_devices.resize(1);
  409. physical_devices.resize(1);
  410. device_queue_families.resize(1);
  411. physical_devices[0] = physical_device;
  412. } else {
  413. uint32_t physical_device_count = 0;
  414. VkResult err = vkEnumeratePhysicalDevices(instance, &physical_device_count, nullptr);
  415. ERR_FAIL_COND_V(err != VK_SUCCESS, ERR_CANT_CREATE);
  416. ERR_FAIL_COND_V_MSG(physical_device_count == 0, ERR_CANT_CREATE, "vkEnumeratePhysicalDevices reported zero accessible devices.\n\nDo you have a compatible Vulkan installable client driver (ICD) installed?\nvkEnumeratePhysicalDevices Failure.");
  417. driver_devices.resize(physical_device_count);
  418. physical_devices.resize(physical_device_count);
  419. device_queue_families.resize(physical_device_count);
  420. err = vkEnumeratePhysicalDevices(instance, &physical_device_count, physical_devices.ptr());
  421. ERR_FAIL_COND_V(err != VK_SUCCESS, ERR_CANT_CREATE);
  422. }
  423. // Fill the list of driver devices with the properties from the physical devices.
  424. for (uint32_t i = 0; i < physical_devices.size(); i++) {
  425. VkPhysicalDeviceProperties props;
  426. vkGetPhysicalDeviceProperties(physical_devices[i], &props);
  427. Device &driver_device = driver_devices[i];
  428. driver_device.name = String::utf8(props.deviceName);
  429. driver_device.vendor = Vendor(props.vendorID);
  430. driver_device.type = DeviceType(props.deviceType);
  431. uint32_t queue_family_properties_count = 0;
  432. vkGetPhysicalDeviceQueueFamilyProperties(physical_devices[i], &queue_family_properties_count, nullptr);
  433. if (queue_family_properties_count > 0) {
  434. device_queue_families[i].properties.resize(queue_family_properties_count);
  435. vkGetPhysicalDeviceQueueFamilyProperties(physical_devices[i], &queue_family_properties_count, device_queue_families[i].properties.ptr());
  436. }
  437. }
  438. return OK;
  439. }
  440. bool RenderingContextDriverVulkan::_use_validation_layers() const {
  441. return Engine::get_singleton()->is_validation_layers_enabled();
  442. }
  443. Error RenderingContextDriverVulkan::_create_vulkan_instance(const VkInstanceCreateInfo *p_create_info, VkInstance *r_instance) {
  444. if (VulkanHooks::get_singleton() != nullptr) {
  445. return VulkanHooks::get_singleton()->create_vulkan_instance(p_create_info, r_instance) ? OK : ERR_CANT_CREATE;
  446. } else {
  447. VkResult err = vkCreateInstance(p_create_info, nullptr, r_instance);
  448. ERR_FAIL_COND_V_MSG(err == VK_ERROR_INCOMPATIBLE_DRIVER, ERR_CANT_CREATE,
  449. "Cannot find a compatible Vulkan installable client driver (ICD).\n\n"
  450. "vkCreateInstance Failure");
  451. ERR_FAIL_COND_V_MSG(err == VK_ERROR_EXTENSION_NOT_PRESENT, ERR_CANT_CREATE,
  452. "Cannot find a specified extension library.\n"
  453. "Make sure your layers path is set appropriately.\n"
  454. "vkCreateInstance Failure");
  455. ERR_FAIL_COND_V_MSG(err, ERR_CANT_CREATE,
  456. "vkCreateInstance failed.\n\n"
  457. "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
  458. "Please look at the Getting Started guide for additional information.\n"
  459. "vkCreateInstance Failure");
  460. }
  461. return OK;
  462. }
  463. Error RenderingContextDriverVulkan::initialize() {
  464. Error err;
  465. #ifdef USE_VOLK
  466. if (volkInitialize() != VK_SUCCESS) {
  467. return FAILED;
  468. }
  469. #endif
  470. err = _initialize_vulkan_version();
  471. ERR_FAIL_COND_V(err != OK, err);
  472. err = _initialize_instance_extensions();
  473. ERR_FAIL_COND_V(err != OK, err);
  474. err = _initialize_instance();
  475. ERR_FAIL_COND_V(err != OK, err);
  476. err = _initialize_devices();
  477. ERR_FAIL_COND_V(err != OK, err);
  478. return OK;
  479. }
  480. const RenderingContextDriver::Device &RenderingContextDriverVulkan::device_get(uint32_t p_device_index) const {
  481. DEV_ASSERT(p_device_index < driver_devices.size());
  482. return driver_devices[p_device_index];
  483. }
  484. uint32_t RenderingContextDriverVulkan::device_get_count() const {
  485. return driver_devices.size();
  486. }
  487. bool RenderingContextDriverVulkan::device_supports_present(uint32_t p_device_index, SurfaceID p_surface) const {
  488. DEV_ASSERT(p_device_index < physical_devices.size());
  489. // Check if any of the queues supported by the device supports presenting to the window's surface.
  490. const VkPhysicalDevice physical_device = physical_devices[p_device_index];
  491. const DeviceQueueFamilies &queue_families = device_queue_families[p_device_index];
  492. for (uint32_t i = 0; i < queue_families.properties.size(); i++) {
  493. if ((queue_families.properties[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) && queue_family_supports_present(physical_device, i, p_surface)) {
  494. return true;
  495. }
  496. }
  497. return false;
  498. }
  499. RenderingDeviceDriver *RenderingContextDriverVulkan::driver_create() {
  500. return memnew(RenderingDeviceDriverVulkan(this));
  501. }
  502. void RenderingContextDriverVulkan::driver_free(RenderingDeviceDriver *p_driver) {
  503. memdelete(p_driver);
  504. }
  505. RenderingContextDriver::SurfaceID RenderingContextDriverVulkan::surface_create(const void *p_platform_data) {
  506. DEV_ASSERT(false && "Surface creation should not be called on the platform-agnostic version of the driver.");
  507. return SurfaceID();
  508. }
  509. void RenderingContextDriverVulkan::surface_set_size(SurfaceID p_surface, uint32_t p_width, uint32_t p_height) {
  510. Surface *surface = (Surface *)(p_surface);
  511. surface->width = p_width;
  512. surface->height = p_height;
  513. surface->needs_resize = true;
  514. }
  515. void RenderingContextDriverVulkan::surface_set_vsync_mode(SurfaceID p_surface, DisplayServer::VSyncMode p_vsync_mode) {
  516. Surface *surface = (Surface *)(p_surface);
  517. surface->vsync_mode = p_vsync_mode;
  518. surface->needs_resize = true;
  519. }
  520. DisplayServer::VSyncMode RenderingContextDriverVulkan::surface_get_vsync_mode(SurfaceID p_surface) const {
  521. Surface *surface = (Surface *)(p_surface);
  522. return surface->vsync_mode;
  523. }
  524. uint32_t RenderingContextDriverVulkan::surface_get_width(SurfaceID p_surface) const {
  525. Surface *surface = (Surface *)(p_surface);
  526. return surface->width;
  527. }
  528. uint32_t RenderingContextDriverVulkan::surface_get_height(SurfaceID p_surface) const {
  529. Surface *surface = (Surface *)(p_surface);
  530. return surface->height;
  531. }
  532. void RenderingContextDriverVulkan::surface_set_needs_resize(SurfaceID p_surface, bool p_needs_resize) {
  533. Surface *surface = (Surface *)(p_surface);
  534. surface->needs_resize = p_needs_resize;
  535. }
  536. bool RenderingContextDriverVulkan::surface_get_needs_resize(SurfaceID p_surface) const {
  537. Surface *surface = (Surface *)(p_surface);
  538. return surface->needs_resize;
  539. }
  540. void RenderingContextDriverVulkan::surface_destroy(SurfaceID p_surface) {
  541. Surface *surface = (Surface *)(p_surface);
  542. vkDestroySurfaceKHR(instance, surface->vk_surface, nullptr);
  543. memdelete(surface);
  544. }
  545. bool RenderingContextDriverVulkan::is_debug_utils_enabled() const {
  546. return enabled_instance_extension_names.has(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
  547. }
  548. VkInstance RenderingContextDriverVulkan::instance_get() const {
  549. return instance;
  550. }
  551. VkPhysicalDevice RenderingContextDriverVulkan::physical_device_get(uint32_t p_device_index) const {
  552. DEV_ASSERT(p_device_index < physical_devices.size());
  553. return physical_devices[p_device_index];
  554. }
  555. uint32_t RenderingContextDriverVulkan::queue_family_get_count(uint32_t p_device_index) const {
  556. DEV_ASSERT(p_device_index < physical_devices.size());
  557. return device_queue_families[p_device_index].properties.size();
  558. }
  559. VkQueueFamilyProperties RenderingContextDriverVulkan::queue_family_get(uint32_t p_device_index, uint32_t p_queue_family_index) const {
  560. DEV_ASSERT(p_device_index < physical_devices.size());
  561. DEV_ASSERT(p_queue_family_index < queue_family_get_count(p_device_index));
  562. return device_queue_families[p_device_index].properties[p_queue_family_index];
  563. }
  564. bool RenderingContextDriverVulkan::queue_family_supports_present(VkPhysicalDevice p_physical_device, uint32_t p_queue_family_index, SurfaceID p_surface) const {
  565. DEV_ASSERT(p_physical_device != VK_NULL_HANDLE);
  566. DEV_ASSERT(p_surface != 0);
  567. Surface *surface = (Surface *)(p_surface);
  568. VkBool32 present_supported = false;
  569. VkResult err = vkGetPhysicalDeviceSurfaceSupportKHR(p_physical_device, p_queue_family_index, surface->vk_surface, &present_supported);
  570. return err == VK_SUCCESS && present_supported;
  571. }
  572. const RenderingContextDriverVulkan::Functions &RenderingContextDriverVulkan::functions_get() const {
  573. return functions;
  574. }
  575. #endif // VULKAN_ENABLED