rendering_context_driver_vulkan.cpp 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058
  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. #if defined(VK_TRACK_DRIVER_MEMORY)
  38. /*************************************************/
  39. // Driver memory tracking
  40. /*************************************************/
  41. // Total driver memory and allocation amount.
  42. SafeNumeric<size_t> driver_memory_total_memory;
  43. SafeNumeric<size_t> driver_memory_total_alloc_count;
  44. // Amount of driver memory for every object type.
  45. SafeNumeric<size_t> driver_memory_tracker[RenderingContextDriverVulkan::VK_TRACKED_OBJECT_TYPE_COUNT][RenderingContextDriverVulkan::VK_TRACKED_SYSTEM_ALLOCATION_SCOPE_COUNT];
  46. // Amount of allocations for every object type.
  47. SafeNumeric<uint32_t> driver_memory_allocation_count[RenderingContextDriverVulkan::VK_TRACKED_OBJECT_TYPE_COUNT][RenderingContextDriverVulkan::VK_TRACKED_SYSTEM_ALLOCATION_SCOPE_COUNT];
  48. #endif
  49. #if defined(VK_TRACK_DEVICE_MEMORY)
  50. /*************************************************/
  51. // Device memory report
  52. /*************************************************/
  53. // Total device memory and allocation amount.
  54. HashMap<uint64_t, size_t> memory_report_table;
  55. // Total memory and allocation amount.
  56. SafeNumeric<uint64_t> memory_report_total_memory;
  57. SafeNumeric<uint64_t> memory_report_total_alloc_count;
  58. // Amount of device memory for every object type.
  59. SafeNumeric<size_t> memory_report_mem_usage[RenderingContextDriverVulkan::VK_TRACKED_OBJECT_TYPE_COUNT];
  60. // Amount of device memory allocations for every object type.
  61. SafeNumeric<size_t> memory_report_allocation_count[RenderingContextDriverVulkan::VK_TRACKED_OBJECT_TYPE_COUNT];
  62. #endif
  63. const char *RenderingContextDriverVulkan::get_tracked_object_name(uint32_t p_type_index) const {
  64. #if defined(VK_TRACK_DRIVER_MEMORY) || defined(VK_TRACK_DEVICE_MEMORY)
  65. static constexpr const char *vkTrackedObjectTypeNames[] = { "UNKNOWN",
  66. "INSTANCE",
  67. "PHYSICAL_DEVICE",
  68. "DEVICE",
  69. "QUEUE",
  70. "SEMAPHORE",
  71. "COMMAND_BUFFER",
  72. "FENCE",
  73. "DEVICE_MEMORY",
  74. "BUFFER",
  75. "IMAGE",
  76. "EVENT",
  77. "QUERY_POOL",
  78. "BUFFER_VIEW",
  79. "IMAGE_VIEW",
  80. "SHADER_MODULE",
  81. "PIPELINE_CACHE",
  82. "PIPELINE_LAYOUT",
  83. "RENDER_PASS",
  84. "PIPELINE",
  85. "DESCRIPTOR_SET_LAYOUT",
  86. "SAMPLER",
  87. "DESCRIPTOR_POOL",
  88. "DESCRIPTOR_SET",
  89. "FRAMEBUFFER",
  90. "COMMAND_POOL",
  91. "DESCRIPTOR_UPDATE_TEMPLATE_KHR",
  92. "SURFACE_KHR",
  93. "SWAPCHAIN_KHR",
  94. "DEBUG_UTILS_MESSENGER_EXT",
  95. "DEBUG_REPORT_CALLBACK_EXT",
  96. "ACCELERATION_STRUCTURE",
  97. "VMA_BUFFER_OR_IMAGE" };
  98. return vkTrackedObjectTypeNames[p_type_index];
  99. #else
  100. return "VK_TRACK_*_MEMORY disabled at build time";
  101. #endif
  102. }
  103. #if defined(VK_TRACK_DRIVER_MEMORY) || defined(VK_TRACK_DEVICE_MEMORY)
  104. uint64_t RenderingContextDriverVulkan::get_tracked_object_type_count() const {
  105. return VK_TRACKED_OBJECT_TYPE_COUNT;
  106. }
  107. #endif
  108. #if defined(VK_TRACK_DRIVER_MEMORY) || defined(VK_TRACK_DEVICE_MEMORY)
  109. RenderingContextDriverVulkan::VkTrackedObjectType vk_object_to_tracked_object(VkObjectType p_type) {
  110. if (p_type > VK_OBJECT_TYPE_COMMAND_POOL && p_type != (VkObjectType)RenderingContextDriverVulkan::VK_TRACKED_OBJECT_TYPE_VMA) {
  111. switch (p_type) {
  112. case VK_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE:
  113. return RenderingContextDriverVulkan::VK_TRACKED_OBJECT_DESCRIPTOR_UPDATE_TEMPLATE_KHR;
  114. case VK_OBJECT_TYPE_SURFACE_KHR:
  115. return RenderingContextDriverVulkan::VK_TRACKED_OBJECT_TYPE_SURFACE;
  116. case VK_OBJECT_TYPE_SWAPCHAIN_KHR:
  117. return RenderingContextDriverVulkan::VK_TRACKED_OBJECT_TYPE_SWAPCHAIN;
  118. case VK_OBJECT_TYPE_DEBUG_UTILS_MESSENGER_EXT:
  119. return RenderingContextDriverVulkan::VK_TRACKED_OBJECT_TYPE_DEBUG_UTILS_MESSENGER_EXT;
  120. case VK_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT:
  121. return RenderingContextDriverVulkan::VK_TRACKED_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT;
  122. case VK_OBJECT_TYPE_ACCELERATION_STRUCTURE_KHR:
  123. case VK_OBJECT_TYPE_ACCELERATION_STRUCTURE_NV:
  124. return RenderingContextDriverVulkan::VK_TRACKED_OBJECT_TYPE_ACCELERATION_STRUCTURE;
  125. default:
  126. _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Unknown VkObjectType enum value " + itos((uint32_t)p_type) + ".Please add it to VkTrackedObjectType, switch statement in "
  127. "vk_object_to_tracked_object and get_tracked_object_name.",
  128. (int)p_type);
  129. return (RenderingContextDriverVulkan::VkTrackedObjectType)VK_OBJECT_TYPE_UNKNOWN;
  130. }
  131. }
  132. return (RenderingContextDriverVulkan::VkTrackedObjectType)p_type;
  133. }
  134. #endif
  135. #if defined(VK_TRACK_DEVICE_MEMORY)
  136. uint64_t RenderingContextDriverVulkan::get_device_total_memory() const {
  137. return memory_report_total_memory.get();
  138. }
  139. uint64_t RenderingContextDriverVulkan::get_device_allocation_count() const {
  140. return memory_report_total_alloc_count.get();
  141. }
  142. uint64_t RenderingContextDriverVulkan::get_device_memory_by_object_type(uint32_t p_type) const {
  143. return memory_report_mem_usage[p_type].get();
  144. }
  145. uint64_t RenderingContextDriverVulkan::get_device_allocs_by_object_type(uint32_t p_type) const {
  146. return memory_report_allocation_count[p_type].get();
  147. }
  148. #endif
  149. #if defined(VK_TRACK_DRIVER_MEMORY)
  150. uint64_t RenderingContextDriverVulkan::get_driver_total_memory() const {
  151. return driver_memory_total_memory.get();
  152. }
  153. uint64_t RenderingContextDriverVulkan::get_driver_allocation_count() const {
  154. return driver_memory_total_alloc_count.get();
  155. }
  156. uint64_t RenderingContextDriverVulkan::get_driver_memory_by_object_type(uint32_t p_type) const {
  157. uint64_t ret = 0;
  158. for (uint32_t i = 0; i < VK_TRACKED_SYSTEM_ALLOCATION_SCOPE_COUNT; i++) {
  159. ret += driver_memory_tracker[p_type][i].get();
  160. }
  161. return ret;
  162. }
  163. uint64_t RenderingContextDriverVulkan::get_driver_allocs_by_object_type(uint32_t p_type) const {
  164. uint64_t ret = 0;
  165. for (uint32_t i = 0; i < VK_TRACKED_SYSTEM_ALLOCATION_SCOPE_COUNT; i++) {
  166. ret += driver_memory_allocation_count[p_type][i].get();
  167. }
  168. return ret;
  169. }
  170. #endif
  171. #if defined(VK_TRACK_DEVICE_MEMORY)
  172. void RenderingContextDriverVulkan::memory_report_callback(const VkDeviceMemoryReportCallbackDataEXT *p_callback_data, void *p_user_data) {
  173. if (!p_callback_data) {
  174. return;
  175. }
  176. const RenderingContextDriverVulkan::VkTrackedObjectType obj_type = vk_object_to_tracked_object(p_callback_data->objectType);
  177. uint64_t obj_id = p_callback_data->memoryObjectId;
  178. if (p_callback_data->type == VK_DEVICE_MEMORY_REPORT_EVENT_TYPE_ALLOCATE_EXT) {
  179. // Realloc, update size
  180. if (memory_report_table.has(obj_id)) {
  181. memory_report_total_memory.sub(memory_report_table[obj_id]);
  182. memory_report_mem_usage[obj_type].sub(memory_report_table[obj_id]);
  183. memory_report_total_memory.add(p_callback_data->size);
  184. memory_report_mem_usage[obj_type].add(p_callback_data->size);
  185. memory_report_table[p_callback_data->memoryObjectId] = p_callback_data->size;
  186. } else {
  187. memory_report_table[obj_id] = p_callback_data->size;
  188. memory_report_total_alloc_count.increment();
  189. memory_report_allocation_count[obj_type].increment();
  190. memory_report_mem_usage[obj_type].add(p_callback_data->size);
  191. memory_report_total_memory.add(p_callback_data->size);
  192. }
  193. } else if (p_callback_data->type == VK_DEVICE_MEMORY_REPORT_EVENT_TYPE_FREE_EXT) {
  194. if (memory_report_table.has(obj_id)) {
  195. memory_report_total_alloc_count.decrement();
  196. memory_report_allocation_count[obj_type].decrement();
  197. memory_report_mem_usage[obj_type].sub(p_callback_data->size);
  198. memory_report_total_memory.sub(p_callback_data->size);
  199. memory_report_table.remove(memory_report_table.find(obj_id));
  200. }
  201. }
  202. }
  203. #endif
  204. VkAllocationCallbacks *RenderingContextDriverVulkan::get_allocation_callbacks(VkObjectType p_type) {
  205. #if !defined(VK_TRACK_DRIVER_MEMORY)
  206. return nullptr;
  207. #else
  208. if (!Engine::get_singleton()->is_extra_gpu_memory_tracking_enabled()) {
  209. return nullptr;
  210. }
  211. #ifdef _MSC_VER
  212. #define LAMBDA_VK_CALL_CONV
  213. #else
  214. #define LAMBDA_VK_CALL_CONV VKAPI_PTR
  215. #endif
  216. struct TrackedMemHeader {
  217. size_t size;
  218. VkSystemAllocationScope allocation_scope;
  219. VkTrackedObjectType type;
  220. };
  221. VkAllocationCallbacks tracking_callbacks = {
  222. // Allocation function
  223. nullptr,
  224. [](
  225. void *p_user_data,
  226. size_t size,
  227. size_t alignment,
  228. VkSystemAllocationScope allocation_scope) LAMBDA_VK_CALL_CONV -> void * {
  229. static constexpr size_t tracking_data_size = 32;
  230. VkTrackedObjectType type = static_cast<VkTrackedObjectType>(*reinterpret_cast<VkTrackedObjectType *>(p_user_data));
  231. driver_memory_total_memory.add(size);
  232. driver_memory_total_alloc_count.increment();
  233. driver_memory_tracker[type][allocation_scope].add(size);
  234. driver_memory_allocation_count[type][allocation_scope].increment();
  235. alignment = MAX(alignment, tracking_data_size);
  236. uint8_t *ret = reinterpret_cast<uint8_t *>(Memory::alloc_aligned_static(size + alignment, alignment));
  237. if (ret == nullptr) {
  238. return nullptr;
  239. }
  240. // Track allocation
  241. TrackedMemHeader *header = reinterpret_cast<TrackedMemHeader *>(ret);
  242. header->size = size;
  243. header->allocation_scope = allocation_scope;
  244. header->type = type;
  245. *reinterpret_cast<size_t *>(ret + alignment - sizeof(size_t)) = alignment;
  246. // Return first available chunk of memory
  247. return ret + alignment;
  248. },
  249. // Reallocation function
  250. [](
  251. void *p_user_data,
  252. void *p_original,
  253. size_t size,
  254. size_t alignment,
  255. VkSystemAllocationScope allocation_scope) LAMBDA_VK_CALL_CONV -> void * {
  256. if (p_original == nullptr) {
  257. VkObjectType type = static_cast<VkObjectType>(*reinterpret_cast<uint32_t *>(p_user_data));
  258. return get_allocation_callbacks(type)->pfnAllocation(p_user_data, size, alignment, allocation_scope);
  259. }
  260. uint8_t *mem = reinterpret_cast<uint8_t *>(p_original);
  261. // Retrieve alignment
  262. alignment = *reinterpret_cast<size_t *>(mem - sizeof(size_t));
  263. // Retrieve allocation data
  264. TrackedMemHeader *header = reinterpret_cast<TrackedMemHeader *>(mem - alignment);
  265. // Update allocation size
  266. driver_memory_total_memory.sub(header->size);
  267. driver_memory_total_memory.add(size);
  268. driver_memory_tracker[header->type][header->allocation_scope].sub(header->size);
  269. driver_memory_tracker[header->type][header->allocation_scope].add(size);
  270. uint8_t *ret = reinterpret_cast<uint8_t *>(Memory::realloc_aligned_static(header, size + alignment, header->size + alignment, alignment));
  271. if (ret == nullptr) {
  272. return nullptr;
  273. }
  274. // Update tracker
  275. header = reinterpret_cast<TrackedMemHeader *>(ret);
  276. header->size = size;
  277. return ret + alignment;
  278. },
  279. // Free function
  280. [](
  281. void *p_user_data,
  282. void *p_memory) LAMBDA_VK_CALL_CONV {
  283. if (!p_memory) {
  284. return;
  285. }
  286. uint8_t *mem = reinterpret_cast<uint8_t *>(p_memory);
  287. size_t alignment = *reinterpret_cast<size_t *>(mem - sizeof(size_t));
  288. TrackedMemHeader *header = reinterpret_cast<TrackedMemHeader *>(mem - alignment);
  289. driver_memory_total_alloc_count.decrement();
  290. driver_memory_total_memory.sub(header->size);
  291. driver_memory_tracker[header->type][header->allocation_scope].sub(header->size);
  292. driver_memory_allocation_count[header->type][header->allocation_scope].decrement();
  293. Memory::free_aligned_static(header);
  294. },
  295. // Internal allocation / deallocation. We don't track them as they cannot really be controlled or optimized by the programmer.
  296. [](
  297. void *p_user_data,
  298. size_t size,
  299. VkInternalAllocationType allocation_type,
  300. VkSystemAllocationScope allocation_scope) LAMBDA_VK_CALL_CONV {
  301. },
  302. [](
  303. void *p_user_data,
  304. size_t size,
  305. VkInternalAllocationType allocation_type,
  306. VkSystemAllocationScope allocation_scope) LAMBDA_VK_CALL_CONV {
  307. },
  308. };
  309. // Create a callback per object type
  310. static VkAllocationCallbacks object_callbacks[VK_TRACKED_OBJECT_TYPE_COUNT] = {};
  311. static uint32_t object_user_data[VK_TRACKED_OBJECT_TYPE_COUNT] = {};
  312. // Only build the first time
  313. if (!object_callbacks[0].pfnAllocation) {
  314. for (uint32_t c = 0; c < VK_TRACKED_OBJECT_TYPE_COUNT; ++c) {
  315. object_callbacks[c] = tracking_callbacks;
  316. object_user_data[c] = c;
  317. object_callbacks[c].pUserData = &object_user_data[c];
  318. for (uint32_t i = 0; i < VK_TRACKED_SYSTEM_ALLOCATION_SCOPE_COUNT; i++) {
  319. driver_memory_tracker[c][i].set(0);
  320. driver_memory_allocation_count[c][i].set(0);
  321. }
  322. }
  323. }
  324. uint32_t type_index = vk_object_to_tracked_object(p_type);
  325. return &object_callbacks[type_index];
  326. #endif
  327. }
  328. RenderingContextDriverVulkan::RenderingContextDriverVulkan() {
  329. // Empty constructor.
  330. }
  331. RenderingContextDriverVulkan::~RenderingContextDriverVulkan() {
  332. if (debug_messenger != VK_NULL_HANDLE && functions.DestroyDebugUtilsMessengerEXT != nullptr) {
  333. functions.DestroyDebugUtilsMessengerEXT(instance, debug_messenger, get_allocation_callbacks(VK_OBJECT_TYPE_DEBUG_UTILS_MESSENGER_EXT));
  334. }
  335. if (debug_report != VK_NULL_HANDLE && functions.DestroyDebugReportCallbackEXT != nullptr) {
  336. functions.DestroyDebugReportCallbackEXT(instance, debug_report, get_allocation_callbacks(VK_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT));
  337. }
  338. if (instance != VK_NULL_HANDLE) {
  339. vkDestroyInstance(instance, get_allocation_callbacks(VK_OBJECT_TYPE_INSTANCE));
  340. }
  341. }
  342. Error RenderingContextDriverVulkan::_initialize_vulkan_version() {
  343. // https://www.khronos.org/registry/vulkan/specs/1.2-extensions/man/html/VkApplicationInfo.html#_description
  344. // For Vulkan 1.0 vkEnumerateInstanceVersion is not available, including not in the loader we compile against on Android.
  345. typedef VkResult(VKAPI_PTR * _vkEnumerateInstanceVersion)(uint32_t *);
  346. _vkEnumerateInstanceVersion func = (_vkEnumerateInstanceVersion)vkGetInstanceProcAddr(nullptr, "vkEnumerateInstanceVersion");
  347. if (func != nullptr) {
  348. uint32_t api_version;
  349. VkResult res = func(&api_version);
  350. if (res == VK_SUCCESS) {
  351. instance_api_version = api_version;
  352. } else {
  353. // According to the documentation this shouldn't fail with anything except a memory allocation error
  354. // in which case we're in deep trouble anyway.
  355. ERR_FAIL_V(ERR_CANT_CREATE);
  356. }
  357. } else {
  358. print_line("vkEnumerateInstanceVersion not available, assuming Vulkan 1.0.");
  359. instance_api_version = VK_API_VERSION_1_0;
  360. }
  361. return OK;
  362. }
  363. void RenderingContextDriverVulkan::_register_requested_instance_extension(const CharString &p_extension_name, bool p_required) {
  364. ERR_FAIL_COND(requested_instance_extensions.has(p_extension_name));
  365. requested_instance_extensions[p_extension_name] = p_required;
  366. }
  367. Error RenderingContextDriverVulkan::_initialize_instance_extensions() {
  368. enabled_instance_extension_names.clear();
  369. // The surface extension and the platform-specific surface extension are core requirements.
  370. _register_requested_instance_extension(VK_KHR_SURFACE_EXTENSION_NAME, true);
  371. if (_get_platform_surface_extension()) {
  372. _register_requested_instance_extension(_get_platform_surface_extension(), true);
  373. }
  374. if (_use_validation_layers()) {
  375. _register_requested_instance_extension(VK_EXT_DEBUG_REPORT_EXTENSION_NAME, false);
  376. }
  377. // This extension allows us to use the properties2 features to query additional device capabilities.
  378. _register_requested_instance_extension(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME, false);
  379. #if defined(USE_VOLK) && (defined(MACOS_ENABLED) || defined(IOS_ENABLED))
  380. _register_requested_instance_extension(VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME, true);
  381. #endif
  382. // Only enable debug utils in verbose mode or DEV_ENABLED.
  383. // End users would get spammed with messages of varying verbosity due to the
  384. // mess that thirdparty layers/extensions and drivers seem to leave in their
  385. // wake, making the Windows registry a bottomless pit of broken layer JSON.
  386. #ifdef DEV_ENABLED
  387. bool want_debug_utils = true;
  388. #else
  389. bool want_debug_utils = OS::get_singleton()->is_stdout_verbose();
  390. #endif
  391. if (want_debug_utils) {
  392. _register_requested_instance_extension(VK_EXT_DEBUG_UTILS_EXTENSION_NAME, false);
  393. }
  394. // Load instance extensions that are available.
  395. uint32_t instance_extension_count = 0;
  396. VkResult err = vkEnumerateInstanceExtensionProperties(nullptr, &instance_extension_count, nullptr);
  397. ERR_FAIL_COND_V(err != VK_SUCCESS && err != VK_INCOMPLETE, ERR_CANT_CREATE);
  398. ERR_FAIL_COND_V_MSG(instance_extension_count == 0, ERR_CANT_CREATE, "No instance extensions were found.");
  399. TightLocalVector<VkExtensionProperties> instance_extensions;
  400. instance_extensions.resize(instance_extension_count);
  401. err = vkEnumerateInstanceExtensionProperties(nullptr, &instance_extension_count, instance_extensions.ptr());
  402. if (err != VK_SUCCESS && err != VK_INCOMPLETE) {
  403. ERR_FAIL_V(ERR_CANT_CREATE);
  404. }
  405. #ifdef DEV_ENABLED
  406. for (uint32_t i = 0; i < instance_extension_count; i++) {
  407. print_verbose(String("VULKAN: Found instance extension ") + String::utf8(instance_extensions[i].extensionName) + String("."));
  408. }
  409. #endif
  410. // Enable all extensions that are supported and requested.
  411. for (uint32_t i = 0; i < instance_extension_count; i++) {
  412. CharString extension_name(instance_extensions[i].extensionName);
  413. if (requested_instance_extensions.has(extension_name)) {
  414. enabled_instance_extension_names.insert(extension_name);
  415. }
  416. }
  417. // Now check our requested extensions.
  418. for (KeyValue<CharString, bool> &requested_extension : requested_instance_extensions) {
  419. if (!enabled_instance_extension_names.has(requested_extension.key)) {
  420. if (requested_extension.value) {
  421. ERR_FAIL_V_MSG(ERR_BUG, String("Required extension ") + String::utf8(requested_extension.key) + String(" not found."));
  422. } else {
  423. print_verbose(String("Optional extension ") + String::utf8(requested_extension.key) + String(" not found."));
  424. }
  425. }
  426. }
  427. return OK;
  428. }
  429. Error RenderingContextDriverVulkan::_find_validation_layers(TightLocalVector<const char *> &r_layer_names) const {
  430. r_layer_names.clear();
  431. uint32_t instance_layer_count = 0;
  432. VkResult err = vkEnumerateInstanceLayerProperties(&instance_layer_count, nullptr);
  433. ERR_FAIL_COND_V(err != VK_SUCCESS, ERR_CANT_CREATE);
  434. if (instance_layer_count > 0) {
  435. TightLocalVector<VkLayerProperties> layer_properties;
  436. layer_properties.resize(instance_layer_count);
  437. err = vkEnumerateInstanceLayerProperties(&instance_layer_count, layer_properties.ptr());
  438. ERR_FAIL_COND_V(err != VK_SUCCESS, ERR_CANT_CREATE);
  439. // Preferred set of validation layers.
  440. const std::initializer_list<const char *> preferred = { "VK_LAYER_KHRONOS_validation" };
  441. // Alternative (deprecated, removed in SDK 1.1.126.0) set of validation layers.
  442. const std::initializer_list<const char *> lunarg = { "VK_LAYER_LUNARG_standard_validation" };
  443. // Alternative (deprecated, removed in SDK 1.1.121.1) set of validation layers.
  444. 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" };
  445. // Verify all the layers of the list are present.
  446. for (const std::initializer_list<const char *> &list : { preferred, lunarg, google }) {
  447. bool layers_found = false;
  448. for (const char *layer_name : list) {
  449. layers_found = false;
  450. for (const VkLayerProperties &properties : layer_properties) {
  451. if (!strcmp(properties.layerName, layer_name)) {
  452. layers_found = true;
  453. break;
  454. }
  455. }
  456. if (!layers_found) {
  457. break;
  458. }
  459. }
  460. if (layers_found) {
  461. r_layer_names.reserve(list.size());
  462. for (const char *layer_name : list) {
  463. r_layer_names.push_back(layer_name);
  464. }
  465. break;
  466. }
  467. }
  468. }
  469. return OK;
  470. }
  471. 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) {
  472. // This error needs to be ignored because the AMD allocator will mix up memory types on IGP processors.
  473. 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) {
  474. return VK_FALSE;
  475. }
  476. // This needs to be ignored because Validator is wrong here.
  477. if (strstr(p_callback_data->pMessage, "Invalid SPIR-V binary version 1.3") != nullptr) {
  478. return VK_FALSE;
  479. }
  480. // This needs to be ignored because Validator is wrong here.
  481. if (strstr(p_callback_data->pMessage, "Shader requires flag") != nullptr) {
  482. return VK_FALSE;
  483. }
  484. // This needs to be ignored because Validator is wrong here.
  485. 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) {
  486. return VK_FALSE;
  487. }
  488. if (p_callback_data->pMessageIdName && strstr(p_callback_data->pMessageIdName, "UNASSIGNED-CoreValidation-DrawState-ClearCmdBeforeDraw") != nullptr) {
  489. return VK_FALSE;
  490. }
  491. String type_string;
  492. switch (p_message_type) {
  493. case (VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT):
  494. type_string = "GENERAL";
  495. break;
  496. case (VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT):
  497. type_string = "VALIDATION";
  498. break;
  499. case (VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT):
  500. type_string = "PERFORMANCE";
  501. break;
  502. case (VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT & VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT):
  503. type_string = "VALIDATION|PERFORMANCE";
  504. break;
  505. }
  506. String objects_string;
  507. if (p_callback_data->objectCount > 0) {
  508. objects_string = "\n\tObjects - " + String::num_int64(p_callback_data->objectCount);
  509. for (uint32_t object = 0; object < p_callback_data->objectCount; ++object) {
  510. objects_string +=
  511. "\n\t\tObject[" + String::num_int64(object) + "]" +
  512. " - " + string_VkObjectType(p_callback_data->pObjects[object].objectType) +
  513. ", Handle " + String::num_int64(p_callback_data->pObjects[object].objectHandle);
  514. if (p_callback_data->pObjects[object].pObjectName != nullptr && strlen(p_callback_data->pObjects[object].pObjectName) > 0) {
  515. objects_string += ", Name \"" + String(p_callback_data->pObjects[object].pObjectName) + "\"";
  516. }
  517. }
  518. }
  519. String labels_string;
  520. if (p_callback_data->cmdBufLabelCount > 0) {
  521. labels_string = "\n\tCommand Buffer Labels - " + String::num_int64(p_callback_data->cmdBufLabelCount);
  522. for (uint32_t cmd_buf_label = 0; cmd_buf_label < p_callback_data->cmdBufLabelCount; ++cmd_buf_label) {
  523. labels_string +=
  524. "\n\t\tLabel[" + String::num_int64(cmd_buf_label) + "]" +
  525. " - " + p_callback_data->pCmdBufLabels[cmd_buf_label].pLabelName +
  526. "{ ";
  527. for (int color_idx = 0; color_idx < 4; ++color_idx) {
  528. labels_string += String::num(p_callback_data->pCmdBufLabels[cmd_buf_label].color[color_idx]);
  529. if (color_idx < 3) {
  530. labels_string += ", ";
  531. }
  532. }
  533. labels_string += " }";
  534. }
  535. }
  536. String error_message(type_string +
  537. " - Message Id Number: " + String::num_int64(p_callback_data->messageIdNumber) +
  538. " | Message Id Name: " + p_callback_data->pMessageIdName +
  539. "\n\t" + p_callback_data->pMessage +
  540. objects_string + labels_string);
  541. // Convert VK severity to our own log macros.
  542. switch (p_message_severity) {
  543. case VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT:
  544. print_verbose(error_message);
  545. break;
  546. case VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT:
  547. print_line(error_message);
  548. break;
  549. case VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT:
  550. WARN_PRINT(error_message);
  551. break;
  552. case VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT:
  553. ERR_PRINT(error_message);
  554. CRASH_COND_MSG(Engine::get_singleton()->is_abort_on_gpu_errors_enabled(), "Crashing, because abort on GPU errors is enabled.");
  555. break;
  556. case VK_DEBUG_UTILS_MESSAGE_SEVERITY_FLAG_BITS_MAX_ENUM_EXT:
  557. break; // Shouldn't happen, only handling to make compilers happy.
  558. }
  559. return VK_FALSE;
  560. }
  561. 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) {
  562. String debug_message = String("Vulkan Debug Report: object - ") + String::num_int64(p_object) + "\n" + p_message;
  563. switch (p_flags) {
  564. case VK_DEBUG_REPORT_DEBUG_BIT_EXT:
  565. case VK_DEBUG_REPORT_INFORMATION_BIT_EXT:
  566. print_line(debug_message);
  567. break;
  568. case VK_DEBUG_REPORT_WARNING_BIT_EXT:
  569. case VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT:
  570. WARN_PRINT(debug_message);
  571. break;
  572. case VK_DEBUG_REPORT_ERROR_BIT_EXT:
  573. ERR_PRINT(debug_message);
  574. break;
  575. }
  576. return VK_FALSE;
  577. }
  578. Error RenderingContextDriverVulkan::_initialize_instance() {
  579. Error err;
  580. TightLocalVector<const char *> enabled_extension_names;
  581. enabled_extension_names.reserve(enabled_instance_extension_names.size());
  582. for (const CharString &extension_name : enabled_instance_extension_names) {
  583. enabled_extension_names.push_back(extension_name.ptr());
  584. }
  585. // We'll set application version to the Vulkan version we're developing against, even if our instance is based on an older Vulkan
  586. // version, devices can still support newer versions of Vulkan. The exception is when we're on Vulkan 1.0, we should not set this
  587. // to anything but 1.0. Note that this value is only used by validation layers to warn us about version issues.
  588. uint32_t application_api_version = instance_api_version == VK_API_VERSION_1_0 ? VK_API_VERSION_1_0 : VK_API_VERSION_1_2;
  589. CharString cs = GLOBAL_GET("application/config/name").operator String().utf8();
  590. VkApplicationInfo app_info = {};
  591. app_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
  592. app_info.pApplicationName = cs.get_data();
  593. app_info.pEngineName = VERSION_NAME;
  594. app_info.engineVersion = VK_MAKE_VERSION(VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH);
  595. app_info.apiVersion = application_api_version;
  596. TightLocalVector<const char *> enabled_layer_names;
  597. if (_use_validation_layers()) {
  598. err = _find_validation_layers(enabled_layer_names);
  599. ERR_FAIL_COND_V(err != OK, err);
  600. }
  601. VkInstanceCreateInfo instance_info = {};
  602. instance_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
  603. #if defined(USE_VOLK) && (defined(MACOS_ENABLED) || defined(IOS_ENABLED))
  604. instance_info.flags = VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR;
  605. #endif
  606. instance_info.pApplicationInfo = &app_info;
  607. instance_info.enabledExtensionCount = enabled_extension_names.size();
  608. instance_info.ppEnabledExtensionNames = enabled_extension_names.ptr();
  609. instance_info.enabledLayerCount = enabled_layer_names.size();
  610. instance_info.ppEnabledLayerNames = enabled_layer_names.ptr();
  611. // 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.
  612. VkDebugUtilsMessengerCreateInfoEXT debug_messenger_create_info = {};
  613. VkDebugReportCallbackCreateInfoEXT debug_report_callback_create_info = {};
  614. const bool has_debug_utils_extension = enabled_instance_extension_names.has(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
  615. const bool has_debug_report_extension = enabled_instance_extension_names.has(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
  616. if (has_debug_utils_extension) {
  617. debug_messenger_create_info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
  618. debug_messenger_create_info.pNext = nullptr;
  619. debug_messenger_create_info.flags = 0;
  620. debug_messenger_create_info.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
  621. 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;
  622. debug_messenger_create_info.pfnUserCallback = _debug_messenger_callback;
  623. debug_messenger_create_info.pUserData = this;
  624. instance_info.pNext = &debug_messenger_create_info;
  625. } else if (has_debug_report_extension) {
  626. debug_report_callback_create_info.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT;
  627. 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;
  628. debug_report_callback_create_info.pfnCallback = _debug_report_callback;
  629. debug_report_callback_create_info.pUserData = this;
  630. instance_info.pNext = &debug_report_callback_create_info;
  631. }
  632. err = _create_vulkan_instance(&instance_info, &instance);
  633. ERR_FAIL_COND_V(err != OK, err);
  634. #ifdef USE_VOLK
  635. volkLoadInstance(instance);
  636. #endif
  637. // Physical device.
  638. if (enabled_instance_extension_names.has(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
  639. functions.GetPhysicalDeviceFeatures2 = PFN_vkGetPhysicalDeviceFeatures2(vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceFeatures2"));
  640. functions.GetPhysicalDeviceProperties2 = PFN_vkGetPhysicalDeviceProperties2(vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceProperties2"));
  641. // In Vulkan 1.0, the functions might be accessible under their original extension names.
  642. if (functions.GetPhysicalDeviceFeatures2 == nullptr) {
  643. functions.GetPhysicalDeviceFeatures2 = PFN_vkGetPhysicalDeviceFeatures2(vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceFeatures2KHR"));
  644. }
  645. if (functions.GetPhysicalDeviceProperties2 == nullptr) {
  646. functions.GetPhysicalDeviceProperties2 = PFN_vkGetPhysicalDeviceProperties2(vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceProperties2KHR"));
  647. }
  648. }
  649. // Device.
  650. functions.GetDeviceProcAddr = PFN_vkGetDeviceProcAddr(vkGetInstanceProcAddr(instance, "vkGetDeviceProcAddr"));
  651. // Surfaces.
  652. functions.GetPhysicalDeviceSurfaceSupportKHR = PFN_vkGetPhysicalDeviceSurfaceSupportKHR(vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceSurfaceSupportKHR"));
  653. functions.GetPhysicalDeviceSurfaceFormatsKHR = PFN_vkGetPhysicalDeviceSurfaceFormatsKHR(vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceSurfaceFormatsKHR"));
  654. functions.GetPhysicalDeviceSurfaceCapabilitiesKHR = PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR(vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceSurfaceCapabilitiesKHR"));
  655. functions.GetPhysicalDeviceSurfacePresentModesKHR = PFN_vkGetPhysicalDeviceSurfacePresentModesKHR(vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceSurfacePresentModesKHR"));
  656. // Debug utils and report.
  657. if (has_debug_utils_extension) {
  658. // Setup VK_EXT_debug_utils function pointers always (we use them for debug labels and names).
  659. functions.CreateDebugUtilsMessengerEXT = (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkCreateDebugUtilsMessengerEXT");
  660. functions.DestroyDebugUtilsMessengerEXT = (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkDestroyDebugUtilsMessengerEXT");
  661. functions.CmdBeginDebugUtilsLabelEXT = (PFN_vkCmdBeginDebugUtilsLabelEXT)vkGetInstanceProcAddr(instance, "vkCmdBeginDebugUtilsLabelEXT");
  662. functions.CmdEndDebugUtilsLabelEXT = (PFN_vkCmdEndDebugUtilsLabelEXT)vkGetInstanceProcAddr(instance, "vkCmdEndDebugUtilsLabelEXT");
  663. functions.SetDebugUtilsObjectNameEXT = (PFN_vkSetDebugUtilsObjectNameEXT)vkGetInstanceProcAddr(instance, "vkSetDebugUtilsObjectNameEXT");
  664. if (!functions.debug_util_functions_available()) {
  665. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "GetProcAddr: Failed to init VK_EXT_debug_utils\nGetProcAddr: Failure");
  666. }
  667. VkResult res = functions.CreateDebugUtilsMessengerEXT(instance, &debug_messenger_create_info, get_allocation_callbacks(VK_OBJECT_TYPE_DEBUG_UTILS_MESSENGER_EXT), &debug_messenger);
  668. switch (res) {
  669. case VK_SUCCESS:
  670. break;
  671. case VK_ERROR_OUT_OF_HOST_MEMORY:
  672. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "CreateDebugUtilsMessengerEXT: out of host memory\nCreateDebugUtilsMessengerEXT Failure");
  673. break;
  674. default:
  675. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "CreateDebugUtilsMessengerEXT: unknown failure\nCreateDebugUtilsMessengerEXT Failure");
  676. break;
  677. }
  678. } else if (has_debug_report_extension) {
  679. functions.CreateDebugReportCallbackEXT = (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(instance, "vkCreateDebugReportCallbackEXT");
  680. functions.DebugReportMessageEXT = (PFN_vkDebugReportMessageEXT)vkGetInstanceProcAddr(instance, "vkDebugReportMessageEXT");
  681. functions.DestroyDebugReportCallbackEXT = (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(instance, "vkDestroyDebugReportCallbackEXT");
  682. if (!functions.debug_report_functions_available()) {
  683. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "GetProcAddr: Failed to init VK_EXT_debug_report\nGetProcAddr: Failure");
  684. }
  685. VkResult res = functions.CreateDebugReportCallbackEXT(instance, &debug_report_callback_create_info, get_allocation_callbacks(VK_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT), &debug_report);
  686. switch (res) {
  687. case VK_SUCCESS:
  688. break;
  689. case VK_ERROR_OUT_OF_HOST_MEMORY:
  690. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "CreateDebugReportCallbackEXT: out of host memory\nCreateDebugReportCallbackEXT Failure");
  691. break;
  692. default:
  693. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "CreateDebugReportCallbackEXT: unknown failure\nCreateDebugReportCallbackEXT Failure");
  694. break;
  695. }
  696. }
  697. return OK;
  698. }
  699. Error RenderingContextDriverVulkan::_initialize_devices() {
  700. if (VulkanHooks::get_singleton() != nullptr) {
  701. VkPhysicalDevice physical_device;
  702. bool device_retrieved = VulkanHooks::get_singleton()->get_physical_device(&physical_device);
  703. ERR_FAIL_COND_V(!device_retrieved, ERR_CANT_CREATE);
  704. // When a hook is active, pretend the device returned by the hook is the only device available.
  705. driver_devices.resize(1);
  706. physical_devices.resize(1);
  707. device_queue_families.resize(1);
  708. physical_devices[0] = physical_device;
  709. } else {
  710. uint32_t physical_device_count = 0;
  711. VkResult err = vkEnumeratePhysicalDevices(instance, &physical_device_count, nullptr);
  712. ERR_FAIL_COND_V(err != VK_SUCCESS, ERR_CANT_CREATE);
  713. 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.");
  714. driver_devices.resize(physical_device_count);
  715. physical_devices.resize(physical_device_count);
  716. device_queue_families.resize(physical_device_count);
  717. err = vkEnumeratePhysicalDevices(instance, &physical_device_count, physical_devices.ptr());
  718. ERR_FAIL_COND_V(err != VK_SUCCESS, ERR_CANT_CREATE);
  719. }
  720. // Fill the list of driver devices with the properties from the physical devices.
  721. for (uint32_t i = 0; i < physical_devices.size(); i++) {
  722. VkPhysicalDeviceProperties props;
  723. vkGetPhysicalDeviceProperties(physical_devices[i], &props);
  724. Device &driver_device = driver_devices[i];
  725. driver_device.name = String::utf8(props.deviceName);
  726. driver_device.vendor = props.vendorID;
  727. driver_device.type = DeviceType(props.deviceType);
  728. driver_device.workarounds = Workarounds();
  729. _check_driver_workarounds(props, driver_device);
  730. uint32_t queue_family_properties_count = 0;
  731. vkGetPhysicalDeviceQueueFamilyProperties(physical_devices[i], &queue_family_properties_count, nullptr);
  732. if (queue_family_properties_count > 0) {
  733. device_queue_families[i].properties.resize(queue_family_properties_count);
  734. vkGetPhysicalDeviceQueueFamilyProperties(physical_devices[i], &queue_family_properties_count, device_queue_families[i].properties.ptr());
  735. }
  736. }
  737. return OK;
  738. }
  739. void RenderingContextDriverVulkan::_check_driver_workarounds(const VkPhysicalDeviceProperties &p_device_properties, Device &r_device) {
  740. // Workaround for the Adreno 6XX family of devices.
  741. //
  742. // There's a known issue with the Vulkan driver in this family of devices where it'll crash if a dynamic state for drawing is
  743. // used in a command buffer before a dispatch call is issued. As both dynamic scissor and viewport are basic requirements for
  744. // the engine to not bake this state into the PSO, the only known way to fix this issue is to reset the command buffer entirely.
  745. //
  746. // As the render graph has no built in limitations of whether it'll issue compute work before anything needs to draw on the
  747. // frame, and there's no guarantee that compute work will never be dependent on rasterization in the future, this workaround
  748. // will end recording on the current command buffer any time a compute list is encountered after a draw list was executed.
  749. // A new command buffer will be created afterwards and the appropriate synchronization primitives will be inserted.
  750. //
  751. // Executing this workaround has the added cost of synchronization between all the command buffers that are created as well as
  752. // all the individual submissions. This performance hit is accepted for the sake of being able to support these devices without
  753. // limiting the design of the renderer.
  754. //
  755. // This bug was fixed in driver version 512.503.0, so we only enabled it on devices older than this.
  756. //
  757. r_device.workarounds.avoid_compute_after_draw =
  758. r_device.vendor == Vendor::VENDOR_QUALCOMM &&
  759. p_device_properties.deviceID >= 0x6000000 && // Adreno 6xx
  760. p_device_properties.driverVersion < VK_MAKE_VERSION(512, 503, 0) &&
  761. r_device.name.find("Turnip") < 0;
  762. }
  763. bool RenderingContextDriverVulkan::_use_validation_layers() const {
  764. return Engine::get_singleton()->is_validation_layers_enabled();
  765. }
  766. Error RenderingContextDriverVulkan::_create_vulkan_instance(const VkInstanceCreateInfo *p_create_info, VkInstance *r_instance) {
  767. if (VulkanHooks::get_singleton() != nullptr) {
  768. return VulkanHooks::get_singleton()->create_vulkan_instance(p_create_info, r_instance) ? OK : ERR_CANT_CREATE;
  769. } else {
  770. VkResult err = vkCreateInstance(p_create_info, get_allocation_callbacks(VK_OBJECT_TYPE_INSTANCE), r_instance);
  771. ERR_FAIL_COND_V_MSG(err == VK_ERROR_INCOMPATIBLE_DRIVER, ERR_CANT_CREATE,
  772. "Cannot find a compatible Vulkan installable client driver (ICD).\n\n"
  773. "vkCreateInstance Failure");
  774. ERR_FAIL_COND_V_MSG(err == VK_ERROR_EXTENSION_NOT_PRESENT, ERR_CANT_CREATE,
  775. "Cannot find a specified extension library.\n"
  776. "Make sure your layers path is set appropriately.\n"
  777. "vkCreateInstance Failure");
  778. ERR_FAIL_COND_V_MSG(err, ERR_CANT_CREATE,
  779. "vkCreateInstance failed.\n\n"
  780. "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
  781. "Please look at the Getting Started guide for additional information.\n"
  782. "vkCreateInstance Failure");
  783. }
  784. return OK;
  785. }
  786. Error RenderingContextDriverVulkan::initialize() {
  787. Error err;
  788. #ifdef USE_VOLK
  789. if (volkInitialize() != VK_SUCCESS) {
  790. return FAILED;
  791. }
  792. #endif
  793. err = _initialize_vulkan_version();
  794. ERR_FAIL_COND_V(err != OK, err);
  795. err = _initialize_instance_extensions();
  796. ERR_FAIL_COND_V(err != OK, err);
  797. err = _initialize_instance();
  798. ERR_FAIL_COND_V(err != OK, err);
  799. err = _initialize_devices();
  800. ERR_FAIL_COND_V(err != OK, err);
  801. return OK;
  802. }
  803. const RenderingContextDriver::Device &RenderingContextDriverVulkan::device_get(uint32_t p_device_index) const {
  804. DEV_ASSERT(p_device_index < driver_devices.size());
  805. return driver_devices[p_device_index];
  806. }
  807. uint32_t RenderingContextDriverVulkan::device_get_count() const {
  808. return driver_devices.size();
  809. }
  810. bool RenderingContextDriverVulkan::device_supports_present(uint32_t p_device_index, SurfaceID p_surface) const {
  811. DEV_ASSERT(p_device_index < physical_devices.size());
  812. // Check if any of the queues supported by the device supports presenting to the window's surface.
  813. const VkPhysicalDevice physical_device = physical_devices[p_device_index];
  814. const DeviceQueueFamilies &queue_families = device_queue_families[p_device_index];
  815. for (uint32_t i = 0; i < queue_families.properties.size(); i++) {
  816. if ((queue_families.properties[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) && queue_family_supports_present(physical_device, i, p_surface)) {
  817. return true;
  818. }
  819. }
  820. return false;
  821. }
  822. RenderingDeviceDriver *RenderingContextDriverVulkan::driver_create() {
  823. return memnew(RenderingDeviceDriverVulkan(this));
  824. }
  825. void RenderingContextDriverVulkan::driver_free(RenderingDeviceDriver *p_driver) {
  826. memdelete(p_driver);
  827. }
  828. RenderingContextDriver::SurfaceID RenderingContextDriverVulkan::surface_create(const void *p_platform_data) {
  829. DEV_ASSERT(false && "Surface creation should not be called on the platform-agnostic version of the driver.");
  830. return SurfaceID();
  831. }
  832. void RenderingContextDriverVulkan::surface_set_size(SurfaceID p_surface, uint32_t p_width, uint32_t p_height) {
  833. Surface *surface = (Surface *)(p_surface);
  834. surface->width = p_width;
  835. surface->height = p_height;
  836. surface->needs_resize = true;
  837. }
  838. void RenderingContextDriverVulkan::surface_set_vsync_mode(SurfaceID p_surface, DisplayServer::VSyncMode p_vsync_mode) {
  839. Surface *surface = (Surface *)(p_surface);
  840. surface->vsync_mode = p_vsync_mode;
  841. surface->needs_resize = true;
  842. }
  843. DisplayServer::VSyncMode RenderingContextDriverVulkan::surface_get_vsync_mode(SurfaceID p_surface) const {
  844. Surface *surface = (Surface *)(p_surface);
  845. return surface->vsync_mode;
  846. }
  847. uint32_t RenderingContextDriverVulkan::surface_get_width(SurfaceID p_surface) const {
  848. Surface *surface = (Surface *)(p_surface);
  849. return surface->width;
  850. }
  851. uint32_t RenderingContextDriverVulkan::surface_get_height(SurfaceID p_surface) const {
  852. Surface *surface = (Surface *)(p_surface);
  853. return surface->height;
  854. }
  855. void RenderingContextDriverVulkan::surface_set_needs_resize(SurfaceID p_surface, bool p_needs_resize) {
  856. Surface *surface = (Surface *)(p_surface);
  857. surface->needs_resize = p_needs_resize;
  858. }
  859. bool RenderingContextDriverVulkan::surface_get_needs_resize(SurfaceID p_surface) const {
  860. Surface *surface = (Surface *)(p_surface);
  861. return surface->needs_resize;
  862. }
  863. void RenderingContextDriverVulkan::surface_destroy(SurfaceID p_surface) {
  864. Surface *surface = (Surface *)(p_surface);
  865. vkDestroySurfaceKHR(instance, surface->vk_surface, get_allocation_callbacks(VK_OBJECT_TYPE_SURFACE_KHR));
  866. memdelete(surface);
  867. }
  868. bool RenderingContextDriverVulkan::is_debug_utils_enabled() const {
  869. return enabled_instance_extension_names.has(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
  870. }
  871. VkInstance RenderingContextDriverVulkan::instance_get() const {
  872. return instance;
  873. }
  874. VkPhysicalDevice RenderingContextDriverVulkan::physical_device_get(uint32_t p_device_index) const {
  875. DEV_ASSERT(p_device_index < physical_devices.size());
  876. return physical_devices[p_device_index];
  877. }
  878. uint32_t RenderingContextDriverVulkan::queue_family_get_count(uint32_t p_device_index) const {
  879. DEV_ASSERT(p_device_index < physical_devices.size());
  880. return device_queue_families[p_device_index].properties.size();
  881. }
  882. VkQueueFamilyProperties RenderingContextDriverVulkan::queue_family_get(uint32_t p_device_index, uint32_t p_queue_family_index) const {
  883. DEV_ASSERT(p_device_index < physical_devices.size());
  884. DEV_ASSERT(p_queue_family_index < queue_family_get_count(p_device_index));
  885. return device_queue_families[p_device_index].properties[p_queue_family_index];
  886. }
  887. bool RenderingContextDriverVulkan::queue_family_supports_present(VkPhysicalDevice p_physical_device, uint32_t p_queue_family_index, SurfaceID p_surface) const {
  888. DEV_ASSERT(p_physical_device != VK_NULL_HANDLE);
  889. DEV_ASSERT(p_surface != 0);
  890. Surface *surface = (Surface *)(p_surface);
  891. VkBool32 present_supported = false;
  892. VkResult err = vkGetPhysicalDeviceSurfaceSupportKHR(p_physical_device, p_queue_family_index, surface->vk_surface, &present_supported);
  893. return err == VK_SUCCESS && present_supported;
  894. }
  895. const RenderingContextDriverVulkan::Functions &RenderingContextDriverVulkan::functions_get() const {
  896. return functions;
  897. }
  898. #endif // VULKAN_ENABLED