vulkan_context.cpp 105 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744
  1. /**************************************************************************/
  2. /* vulkan_context.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. #include "vulkan_context.h"
  31. #include "core/config/engine.h"
  32. #include "core/config/project_settings.h"
  33. #include "core/string/ustring.h"
  34. #include "core/templates/local_vector.h"
  35. #include "core/version.h"
  36. #include "servers/rendering/rendering_device.h"
  37. #include "vk_enum_string_helper.h"
  38. #include <stdio.h>
  39. #include <stdlib.h>
  40. #include <string.h>
  41. #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
  42. #define APP_SHORT_NAME "GodotEngine"
  43. VulkanHooks *VulkanContext::vulkan_hooks = nullptr;
  44. Vector<VkAttachmentReference> VulkanContext::_convert_VkAttachmentReference2(uint32_t p_count, const VkAttachmentReference2 *p_refs) {
  45. Vector<VkAttachmentReference> att_refs;
  46. if (p_refs != nullptr) {
  47. for (uint32_t i = 0; i < p_count; i++) {
  48. // We lose aspectMask in this conversion but we don't use it currently.
  49. VkAttachmentReference ref = {
  50. p_refs[i].attachment, /* attachment */
  51. p_refs[i].layout /* layout */
  52. };
  53. att_refs.push_back(ref);
  54. }
  55. }
  56. return att_refs;
  57. }
  58. VkResult VulkanContext::vkCreateRenderPass2KHR(VkDevice p_device, const VkRenderPassCreateInfo2 *p_create_info, const VkAllocationCallbacks *p_allocator, VkRenderPass *p_render_pass) {
  59. if (is_device_extension_enabled(VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME)) {
  60. if (fpCreateRenderPass2KHR == nullptr) {
  61. fpCreateRenderPass2KHR = (PFN_vkCreateRenderPass2KHR)vkGetDeviceProcAddr(p_device, "vkCreateRenderPass2KHR");
  62. }
  63. if (fpCreateRenderPass2KHR == nullptr) {
  64. return VK_ERROR_EXTENSION_NOT_PRESENT;
  65. } else {
  66. return (fpCreateRenderPass2KHR)(p_device, p_create_info, p_allocator, p_render_pass);
  67. }
  68. } else {
  69. // need to fall back on vkCreateRenderPass
  70. const void *next = p_create_info->pNext; // ATM we only support multiview which should work if supported.
  71. Vector<VkAttachmentDescription> attachments;
  72. for (uint32_t i = 0; i < p_create_info->attachmentCount; i++) {
  73. // Basically the old layout just misses type and next.
  74. VkAttachmentDescription att = {
  75. p_create_info->pAttachments[i].flags, /* flags */
  76. p_create_info->pAttachments[i].format, /* format */
  77. p_create_info->pAttachments[i].samples, /* samples */
  78. p_create_info->pAttachments[i].loadOp, /* loadOp */
  79. p_create_info->pAttachments[i].storeOp, /* storeOp */
  80. p_create_info->pAttachments[i].stencilLoadOp, /* stencilLoadOp */
  81. p_create_info->pAttachments[i].stencilStoreOp, /* stencilStoreOp */
  82. p_create_info->pAttachments[i].initialLayout, /* initialLayout */
  83. p_create_info->pAttachments[i].finalLayout /* finalLayout */
  84. };
  85. attachments.push_back(att);
  86. }
  87. Vector<VkSubpassDescription> subpasses;
  88. for (uint32_t i = 0; i < p_create_info->subpassCount; i++) {
  89. // Here we need to do more, again it's just stripping out type and next
  90. // but we have VkAttachmentReference2 to convert to VkAttachmentReference.
  91. // Also viewmask is not supported but we don't use it outside of multiview.
  92. Vector<VkAttachmentReference> input_attachments = _convert_VkAttachmentReference2(p_create_info->pSubpasses[i].inputAttachmentCount, p_create_info->pSubpasses[i].pInputAttachments);
  93. Vector<VkAttachmentReference> color_attachments = _convert_VkAttachmentReference2(p_create_info->pSubpasses[i].colorAttachmentCount, p_create_info->pSubpasses[i].pColorAttachments);
  94. Vector<VkAttachmentReference> resolve_attachments = _convert_VkAttachmentReference2(p_create_info->pSubpasses[i].colorAttachmentCount, p_create_info->pSubpasses[i].pResolveAttachments);
  95. Vector<VkAttachmentReference> depth_attachments = _convert_VkAttachmentReference2(p_create_info->pSubpasses[i].colorAttachmentCount, p_create_info->pSubpasses[i].pDepthStencilAttachment);
  96. VkSubpassDescription subpass = {
  97. p_create_info->pSubpasses[i].flags, /* flags */
  98. p_create_info->pSubpasses[i].pipelineBindPoint, /* pipelineBindPoint */
  99. p_create_info->pSubpasses[i].inputAttachmentCount, /* inputAttachmentCount */
  100. input_attachments.size() == 0 ? nullptr : input_attachments.ptr(), /* pInputAttachments */
  101. p_create_info->pSubpasses[i].colorAttachmentCount, /* colorAttachmentCount */
  102. color_attachments.size() == 0 ? nullptr : color_attachments.ptr(), /* pColorAttachments */
  103. resolve_attachments.size() == 0 ? nullptr : resolve_attachments.ptr(), /* pResolveAttachments */
  104. depth_attachments.size() == 0 ? nullptr : depth_attachments.ptr(), /* pDepthStencilAttachment */
  105. p_create_info->pSubpasses[i].preserveAttachmentCount, /* preserveAttachmentCount */
  106. p_create_info->pSubpasses[i].pPreserveAttachments /* pPreserveAttachments */
  107. };
  108. subpasses.push_back(subpass);
  109. }
  110. Vector<VkSubpassDependency> dependencies;
  111. for (uint32_t i = 0; i < p_create_info->dependencyCount; i++) {
  112. // We lose viewOffset here but again I don't believe we use this anywhere.
  113. VkSubpassDependency dep = {
  114. p_create_info->pDependencies[i].srcSubpass, /* srcSubpass */
  115. p_create_info->pDependencies[i].dstSubpass, /* dstSubpass */
  116. p_create_info->pDependencies[i].srcStageMask, /* srcStageMask */
  117. p_create_info->pDependencies[i].dstStageMask, /* dstStageMask */
  118. p_create_info->pDependencies[i].srcAccessMask, /* srcAccessMask */
  119. p_create_info->pDependencies[i].dstAccessMask, /* dstAccessMask */
  120. p_create_info->pDependencies[i].dependencyFlags, /* dependencyFlags */
  121. };
  122. dependencies.push_back(dep);
  123. }
  124. // CorrelatedViewMask is not supported in vkCreateRenderPass but we
  125. // currently only use this for multiview.
  126. // We'll need to look into this.
  127. VkRenderPassCreateInfo create_info = {
  128. VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, /* sType */
  129. next, /* pNext*/
  130. p_create_info->flags, /* flags */
  131. (uint32_t)attachments.size(), /* attachmentCount */
  132. attachments.ptr(), /* pAttachments */
  133. (uint32_t)subpasses.size(), /* subpassCount */
  134. subpasses.ptr(), /* pSubpasses */
  135. (uint32_t)dependencies.size(), /* */
  136. dependencies.ptr(), /* */
  137. };
  138. return vkCreateRenderPass(device, &create_info, p_allocator, p_render_pass);
  139. }
  140. }
  141. VKAPI_ATTR VkBool32 VKAPI_CALL VulkanContext::_debug_messenger_callback(
  142. VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
  143. VkDebugUtilsMessageTypeFlagsEXT messageType,
  144. const VkDebugUtilsMessengerCallbackDataEXT *pCallbackData,
  145. void *pUserData) {
  146. // This error needs to be ignored because the AMD allocator will mix up memory types on IGP processors.
  147. if (strstr(pCallbackData->pMessage, "Mapping an image with layout") != nullptr &&
  148. strstr(pCallbackData->pMessage, "can result in undefined behavior if this memory is used by the device") != nullptr) {
  149. return VK_FALSE;
  150. }
  151. // This needs to be ignored because Validator is wrong here.
  152. if (strstr(pCallbackData->pMessage, "Invalid SPIR-V binary version 1.3") != nullptr) {
  153. return VK_FALSE;
  154. }
  155. // This needs to be ignored because Validator is wrong here.
  156. if (strstr(pCallbackData->pMessage, "Shader requires flag") != nullptr) {
  157. return VK_FALSE;
  158. }
  159. // This needs to be ignored because Validator is wrong here.
  160. if (strstr(pCallbackData->pMessage, "SPIR-V module not valid: Pointer operand") != nullptr &&
  161. strstr(pCallbackData->pMessage, "must be a memory object") != nullptr) {
  162. return VK_FALSE;
  163. }
  164. if (pCallbackData->pMessageIdName && strstr(pCallbackData->pMessageIdName, "UNASSIGNED-CoreValidation-DrawState-ClearCmdBeforeDraw") != nullptr) {
  165. return VK_FALSE;
  166. }
  167. String type_string;
  168. switch (messageType) {
  169. case (VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT):
  170. type_string = "GENERAL";
  171. break;
  172. case (VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT):
  173. type_string = "VALIDATION";
  174. break;
  175. case (VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT):
  176. type_string = "PERFORMANCE";
  177. break;
  178. case (VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT & VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT):
  179. type_string = "VALIDATION|PERFORMANCE";
  180. break;
  181. }
  182. String objects_string;
  183. if (pCallbackData->objectCount > 0) {
  184. objects_string = "\n\tObjects - " + String::num_int64(pCallbackData->objectCount);
  185. for (uint32_t object = 0; object < pCallbackData->objectCount; ++object) {
  186. objects_string +=
  187. "\n\t\tObject[" + String::num_int64(object) + "]" +
  188. " - " + string_VkObjectType(pCallbackData->pObjects[object].objectType) +
  189. ", Handle " + String::num_int64(pCallbackData->pObjects[object].objectHandle);
  190. if (nullptr != pCallbackData->pObjects[object].pObjectName && strlen(pCallbackData->pObjects[object].pObjectName) > 0) {
  191. objects_string += ", Name \"" + String(pCallbackData->pObjects[object].pObjectName) + "\"";
  192. }
  193. }
  194. }
  195. String labels_string;
  196. if (pCallbackData->cmdBufLabelCount > 0) {
  197. labels_string = "\n\tCommand Buffer Labels - " + String::num_int64(pCallbackData->cmdBufLabelCount);
  198. for (uint32_t cmd_buf_label = 0; cmd_buf_label < pCallbackData->cmdBufLabelCount; ++cmd_buf_label) {
  199. labels_string +=
  200. "\n\t\tLabel[" + String::num_int64(cmd_buf_label) + "]" +
  201. " - " + pCallbackData->pCmdBufLabels[cmd_buf_label].pLabelName +
  202. "{ ";
  203. for (int color_idx = 0; color_idx < 4; ++color_idx) {
  204. labels_string += String::num(pCallbackData->pCmdBufLabels[cmd_buf_label].color[color_idx]);
  205. if (color_idx < 3) {
  206. labels_string += ", ";
  207. }
  208. }
  209. labels_string += " }";
  210. }
  211. }
  212. String error_message(type_string +
  213. " - Message Id Number: " + String::num_int64(pCallbackData->messageIdNumber) +
  214. " | Message Id Name: " + pCallbackData->pMessageIdName +
  215. "\n\t" + pCallbackData->pMessage +
  216. objects_string + labels_string);
  217. // Convert VK severity to our own log macros.
  218. switch (messageSeverity) {
  219. case VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT:
  220. print_verbose(error_message);
  221. break;
  222. case VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT:
  223. print_line(error_message);
  224. break;
  225. case VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT:
  226. WARN_PRINT(error_message);
  227. break;
  228. case VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT:
  229. ERR_PRINT(error_message);
  230. CRASH_COND_MSG(Engine::get_singleton()->is_abort_on_gpu_errors_enabled(),
  231. "Crashing, because abort on GPU errors is enabled.");
  232. break;
  233. case VK_DEBUG_UTILS_MESSAGE_SEVERITY_FLAG_BITS_MAX_ENUM_EXT:
  234. break; // Shouldn't happen, only handling to make compilers happy.
  235. }
  236. return VK_FALSE;
  237. }
  238. VKAPI_ATTR VkBool32 VKAPI_CALL VulkanContext::_debug_report_callback(
  239. VkDebugReportFlagsEXT flags,
  240. VkDebugReportObjectTypeEXT objectType,
  241. uint64_t object,
  242. size_t location,
  243. int32_t messageCode,
  244. const char *pLayerPrefix,
  245. const char *pMessage,
  246. void *pUserData) {
  247. String debugMessage = String("Vulkan Debug Report: object - ") +
  248. String::num_int64(object) + "\n" + pMessage;
  249. switch (flags) {
  250. case VK_DEBUG_REPORT_DEBUG_BIT_EXT:
  251. case VK_DEBUG_REPORT_INFORMATION_BIT_EXT:
  252. print_line(debugMessage);
  253. break;
  254. case VK_DEBUG_REPORT_WARNING_BIT_EXT:
  255. case VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT:
  256. WARN_PRINT(debugMessage);
  257. break;
  258. case VK_DEBUG_REPORT_ERROR_BIT_EXT:
  259. ERR_PRINT(debugMessage);
  260. break;
  261. }
  262. return VK_FALSE;
  263. }
  264. VkBool32 VulkanContext::_check_layers(uint32_t check_count, const char *const *check_names, uint32_t layer_count, VkLayerProperties *layers) {
  265. for (uint32_t i = 0; i < check_count; i++) {
  266. VkBool32 found = 0;
  267. for (uint32_t j = 0; j < layer_count; j++) {
  268. if (!strcmp(check_names[i], layers[j].layerName)) {
  269. found = 1;
  270. break;
  271. }
  272. }
  273. if (!found) {
  274. WARN_PRINT("Can't find layer: " + String(check_names[i]));
  275. return 0;
  276. }
  277. }
  278. return 1;
  279. }
  280. Error VulkanContext::_get_preferred_validation_layers(uint32_t *count, const char *const **names) {
  281. static const LocalVector<LocalVector<const char *>> instance_validation_layers_alt{
  282. // Preferred set of validation layers.
  283. { "VK_LAYER_KHRONOS_validation" },
  284. // Alternative (deprecated, removed in SDK 1.1.126.0) set of validation layers.
  285. { "VK_LAYER_LUNARG_standard_validation" },
  286. // Alternative (deprecated, removed in SDK 1.1.121.1) set of validation layers.
  287. { "VK_LAYER_GOOGLE_threading", "VK_LAYER_LUNARG_parameter_validation", "VK_LAYER_LUNARG_object_tracker", "VK_LAYER_LUNARG_core_validation", "VK_LAYER_GOOGLE_unique_objects" }
  288. };
  289. // Clear out-arguments.
  290. *count = 0;
  291. if (names != nullptr) {
  292. *names = nullptr;
  293. }
  294. VkResult err;
  295. uint32_t instance_layer_count;
  296. err = vkEnumerateInstanceLayerProperties(&instance_layer_count, nullptr);
  297. if (err) {
  298. ERR_FAIL_V(ERR_CANT_CREATE);
  299. }
  300. if (instance_layer_count < 1) {
  301. return OK;
  302. }
  303. VkLayerProperties *instance_layers = (VkLayerProperties *)malloc(sizeof(VkLayerProperties) * instance_layer_count);
  304. err = vkEnumerateInstanceLayerProperties(&instance_layer_count, instance_layers);
  305. if (err) {
  306. free(instance_layers);
  307. ERR_FAIL_V(ERR_CANT_CREATE);
  308. }
  309. for (const LocalVector<const char *> &layer : instance_validation_layers_alt) {
  310. if (_check_layers(layer.size(), layer.ptr(), instance_layer_count, instance_layers)) {
  311. *count = layer.size();
  312. if (names != nullptr) {
  313. *names = layer.ptr();
  314. }
  315. break;
  316. }
  317. }
  318. free(instance_layers);
  319. return OK;
  320. }
  321. typedef VkResult(VKAPI_PTR *_vkEnumerateInstanceVersion)(uint32_t *);
  322. Error VulkanContext::_obtain_vulkan_version() {
  323. // https://www.khronos.org/registry/vulkan/specs/1.2-extensions/man/html/VkApplicationInfo.html#_description
  324. // For Vulkan 1.0 vkEnumerateInstanceVersion is not available, including not in the loader we compile against on Android.
  325. _vkEnumerateInstanceVersion func = (_vkEnumerateInstanceVersion)vkGetInstanceProcAddr(nullptr, "vkEnumerateInstanceVersion");
  326. if (func != nullptr) {
  327. uint32_t api_version;
  328. VkResult res = func(&api_version);
  329. if (res == VK_SUCCESS) {
  330. instance_api_version = api_version;
  331. } else {
  332. // According to the documentation this shouldn't fail with anything except a memory allocation error
  333. // in which case we're in deep trouble anyway.
  334. ERR_FAIL_V(ERR_CANT_CREATE);
  335. }
  336. } else {
  337. print_line("vkEnumerateInstanceVersion not available, assuming Vulkan 1.0.");
  338. instance_api_version = VK_API_VERSION_1_0;
  339. }
  340. return OK;
  341. }
  342. bool VulkanContext::instance_extensions_initialized = false;
  343. HashMap<CharString, bool> VulkanContext::requested_instance_extensions;
  344. void VulkanContext::register_requested_instance_extension(const CharString &extension_name, bool p_required) {
  345. ERR_FAIL_COND_MSG(instance_extensions_initialized, "You can only registered extensions before the Vulkan instance is created");
  346. ERR_FAIL_COND(requested_instance_extensions.has(extension_name));
  347. requested_instance_extensions[extension_name] = p_required;
  348. }
  349. Error VulkanContext::_initialize_instance_extensions() {
  350. enabled_instance_extension_names.clear();
  351. // Make sure our core extensions are here
  352. register_requested_instance_extension(VK_KHR_SURFACE_EXTENSION_NAME, true);
  353. register_requested_instance_extension(_get_platform_surface_extension(), true);
  354. if (_use_validation_layers()) {
  355. register_requested_instance_extension(VK_EXT_DEBUG_REPORT_EXTENSION_NAME, false);
  356. }
  357. // This extension allows us to use the properties2 features to query additional device capabilities
  358. register_requested_instance_extension(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME, false);
  359. // Only enable debug utils in verbose mode or DEV_ENABLED.
  360. // End users would get spammed with messages of varying verbosity due to the
  361. // mess that thirdparty layers/extensions and drivers seem to leave in their
  362. // wake, making the Windows registry a bottomless pit of broken layer JSON.
  363. #ifdef DEV_ENABLED
  364. bool want_debug_utils = true;
  365. #else
  366. bool want_debug_utils = OS::get_singleton()->is_stdout_verbose();
  367. #endif
  368. if (want_debug_utils) {
  369. register_requested_instance_extension(VK_EXT_DEBUG_UTILS_EXTENSION_NAME, false);
  370. }
  371. // Load instance extensions that are available...
  372. uint32_t instance_extension_count = 0;
  373. VkResult err = vkEnumerateInstanceExtensionProperties(nullptr, &instance_extension_count, nullptr);
  374. ERR_FAIL_COND_V(err != VK_SUCCESS && err != VK_INCOMPLETE, ERR_CANT_CREATE);
  375. ERR_FAIL_COND_V_MSG(instance_extension_count == 0, ERR_CANT_CREATE, "No instance extensions found, is a driver installed?");
  376. VkExtensionProperties *instance_extensions = (VkExtensionProperties *)malloc(sizeof(VkExtensionProperties) * instance_extension_count);
  377. err = vkEnumerateInstanceExtensionProperties(nullptr, &instance_extension_count, instance_extensions);
  378. if (err != VK_SUCCESS && err != VK_INCOMPLETE) {
  379. free(instance_extensions);
  380. ERR_FAIL_V(ERR_CANT_CREATE);
  381. }
  382. #ifdef DEV_ENABLED
  383. for (uint32_t i = 0; i < instance_extension_count; i++) {
  384. print_verbose(String("VULKAN: Found instance extension ") + String(instance_extensions[i].extensionName));
  385. }
  386. #endif
  387. // Enable all extensions that are supported and requested
  388. for (uint32_t i = 0; i < instance_extension_count; i++) {
  389. CharString extension_name(instance_extensions[i].extensionName);
  390. if (requested_instance_extensions.has(extension_name)) {
  391. enabled_instance_extension_names.insert(extension_name);
  392. }
  393. }
  394. // Now check our requested extensions
  395. for (KeyValue<CharString, bool> &requested_extension : requested_instance_extensions) {
  396. if (!enabled_instance_extension_names.has(requested_extension.key)) {
  397. if (requested_extension.value) {
  398. free(instance_extensions);
  399. ERR_FAIL_V_MSG(ERR_BUG, String("Required extension ") + String(requested_extension.key) + String(" not found, is a driver installed?"));
  400. } else {
  401. print_verbose(String("Optional extension ") + String(requested_extension.key) + String(" not found"));
  402. }
  403. }
  404. }
  405. free(instance_extensions);
  406. instance_extensions_initialized = true;
  407. return OK;
  408. }
  409. bool VulkanContext::device_extensions_initialized = false;
  410. HashMap<CharString, bool> VulkanContext::requested_device_extensions;
  411. void VulkanContext::register_requested_device_extension(const CharString &extension_name, bool p_required) {
  412. ERR_FAIL_COND_MSG(device_extensions_initialized, "You can only registered extensions before the Vulkan instance is created");
  413. ERR_FAIL_COND(requested_device_extensions.has(extension_name));
  414. requested_device_extensions[extension_name] = p_required;
  415. }
  416. Error VulkanContext::_initialize_device_extensions() {
  417. // Look for device extensions.
  418. enabled_device_extension_names.clear();
  419. // Make sure our core extensions are here
  420. register_requested_device_extension(VK_KHR_SWAPCHAIN_EXTENSION_NAME, true);
  421. register_requested_device_extension(VK_KHR_MULTIVIEW_EXTENSION_NAME, false);
  422. register_requested_device_extension(VK_KHR_FRAGMENT_SHADING_RATE_EXTENSION_NAME, false);
  423. register_requested_device_extension(VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME, false);
  424. register_requested_device_extension(VK_KHR_SHADER_FLOAT16_INT8_EXTENSION_NAME, false);
  425. register_requested_device_extension(VK_KHR_STORAGE_BUFFER_STORAGE_CLASS_EXTENSION_NAME, false);
  426. register_requested_device_extension(VK_KHR_16BIT_STORAGE_EXTENSION_NAME, false);
  427. register_requested_device_extension(VK_KHR_IMAGE_FORMAT_LIST_EXTENSION_NAME, false);
  428. register_requested_device_extension(VK_KHR_MAINTENANCE_2_EXTENSION_NAME, false);
  429. // TODO consider the following extensions:
  430. // - VK_KHR_spirv_1_4
  431. // - VK_KHR_swapchain_mutable_format
  432. // - VK_EXT_full_screen_exclusive
  433. // - VK_EXT_hdr_metadata
  434. // - VK_KHR_depth_stencil_resolve
  435. // Even though the user "enabled" the extension via the command
  436. // line, we must make sure that it's enumerated for use with the
  437. // device. Therefore, disable it here, and re-enable it again if
  438. // enumerated.
  439. if (VK_KHR_incremental_present_enabled) {
  440. register_requested_device_extension(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME, false);
  441. }
  442. if (VK_GOOGLE_display_timing_enabled) {
  443. register_requested_device_extension(VK_GOOGLE_DISPLAY_TIMING_EXTENSION_NAME, false);
  444. }
  445. // obtain available device extensions
  446. uint32_t device_extension_count = 0;
  447. VkResult err = vkEnumerateDeviceExtensionProperties(gpu, nullptr, &device_extension_count, nullptr);
  448. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  449. ERR_FAIL_COND_V_MSG(device_extension_count == 0, ERR_CANT_CREATE,
  450. "vkEnumerateDeviceExtensionProperties failed to find any extensions\n\n"
  451. "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
  452. "vkCreateInstance Failure");
  453. VkExtensionProperties *device_extensions = (VkExtensionProperties *)malloc(sizeof(VkExtensionProperties) * device_extension_count);
  454. err = vkEnumerateDeviceExtensionProperties(gpu, nullptr, &device_extension_count, device_extensions);
  455. if (err) {
  456. free(device_extensions);
  457. ERR_FAIL_V(ERR_CANT_CREATE);
  458. }
  459. #ifdef DEV_ENABLED
  460. for (uint32_t i = 0; i < device_extension_count; i++) {
  461. print_verbose(String("VULKAN: Found device extension ") + String(device_extensions[i].extensionName));
  462. }
  463. #endif
  464. // Enable all extensions that are supported and requested
  465. for (uint32_t i = 0; i < device_extension_count; i++) {
  466. CharString extension_name(device_extensions[i].extensionName);
  467. if (requested_device_extensions.has(extension_name)) {
  468. enabled_device_extension_names.insert(extension_name);
  469. }
  470. }
  471. // Now check our requested extensions
  472. for (KeyValue<CharString, bool> &requested_extension : requested_device_extensions) {
  473. if (!enabled_device_extension_names.has(requested_extension.key)) {
  474. if (requested_extension.value) {
  475. free(device_extensions);
  476. ERR_FAIL_V_MSG(ERR_BUG,
  477. String("vkEnumerateDeviceExtensionProperties failed to find the ") + String(requested_extension.key) + String(" extension.\n\nDo you have a compatible Vulkan installable client driver (ICD) installed?\nvkCreateInstance Failure"));
  478. } else {
  479. print_verbose(String("Optional extension ") + String(requested_extension.key) + String(" not found"));
  480. }
  481. }
  482. }
  483. free(device_extensions);
  484. device_extensions_initialized = true;
  485. return OK;
  486. }
  487. uint32_t VulkanContext::SubgroupCapabilities::supported_stages_flags_rd() const {
  488. uint32_t flags = 0;
  489. if (supportedStages & VK_SHADER_STAGE_VERTEX_BIT) {
  490. flags += RenderingDevice::ShaderStage::SHADER_STAGE_VERTEX_BIT;
  491. }
  492. if (supportedStages & VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT) {
  493. flags += RenderingDevice::ShaderStage::SHADER_STAGE_TESSELATION_CONTROL_BIT;
  494. }
  495. if (supportedStages & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT) {
  496. flags += RenderingDevice::ShaderStage::SHADER_STAGE_TESSELATION_EVALUATION_BIT;
  497. }
  498. // if (supportedStages & VK_SHADER_STAGE_GEOMETRY_BIT) {
  499. // flags += RenderingDevice::ShaderStage::SHADER_STAGE_GEOMETRY_BIT;
  500. // }
  501. if (supportedStages & VK_SHADER_STAGE_FRAGMENT_BIT) {
  502. flags += RenderingDevice::ShaderStage::SHADER_STAGE_FRAGMENT_BIT;
  503. }
  504. if (supportedStages & VK_SHADER_STAGE_COMPUTE_BIT) {
  505. flags += RenderingDevice::ShaderStage::SHADER_STAGE_COMPUTE_BIT;
  506. }
  507. return flags;
  508. }
  509. String VulkanContext::SubgroupCapabilities::supported_stages_desc() const {
  510. String res;
  511. if (supportedStages & VK_SHADER_STAGE_VERTEX_BIT) {
  512. res += ", STAGE_VERTEX";
  513. }
  514. if (supportedStages & VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT) {
  515. res += ", STAGE_TESSELLATION_CONTROL";
  516. }
  517. if (supportedStages & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT) {
  518. res += ", STAGE_TESSELLATION_EVALUATION";
  519. }
  520. if (supportedStages & VK_SHADER_STAGE_GEOMETRY_BIT) {
  521. res += ", STAGE_GEOMETRY";
  522. }
  523. if (supportedStages & VK_SHADER_STAGE_FRAGMENT_BIT) {
  524. res += ", STAGE_FRAGMENT";
  525. }
  526. if (supportedStages & VK_SHADER_STAGE_COMPUTE_BIT) {
  527. res += ", STAGE_COMPUTE";
  528. }
  529. // These are not defined on Android GRMBL.
  530. if (supportedStages & 0x00000100 /* VK_SHADER_STAGE_RAYGEN_BIT_KHR */) {
  531. res += ", STAGE_RAYGEN_KHR";
  532. }
  533. if (supportedStages & 0x00000200 /* VK_SHADER_STAGE_ANY_HIT_BIT_KHR */) {
  534. res += ", STAGE_ANY_HIT_KHR";
  535. }
  536. if (supportedStages & 0x00000400 /* VK_SHADER_STAGE_CLOSEST_HIT_BIT_KHR */) {
  537. res += ", STAGE_CLOSEST_HIT_KHR";
  538. }
  539. if (supportedStages & 0x00000800 /* VK_SHADER_STAGE_MISS_BIT_KHR */) {
  540. res += ", STAGE_MISS_KHR";
  541. }
  542. if (supportedStages & 0x00001000 /* VK_SHADER_STAGE_INTERSECTION_BIT_KHR */) {
  543. res += ", STAGE_INTERSECTION_KHR";
  544. }
  545. if (supportedStages & 0x00002000 /* VK_SHADER_STAGE_CALLABLE_BIT_KHR */) {
  546. res += ", STAGE_CALLABLE_KHR";
  547. }
  548. if (supportedStages & 0x00000040 /* VK_SHADER_STAGE_TASK_BIT_NV */) {
  549. res += ", STAGE_TASK_NV";
  550. }
  551. if (supportedStages & 0x00000080 /* VK_SHADER_STAGE_MESH_BIT_NV */) {
  552. res += ", STAGE_MESH_NV";
  553. }
  554. return res.substr(2); // Remove first ", ".
  555. }
  556. uint32_t VulkanContext::SubgroupCapabilities::supported_operations_flags_rd() const {
  557. uint32_t flags = 0;
  558. if (supportedOperations & VK_SUBGROUP_FEATURE_BASIC_BIT) {
  559. flags += RenderingDevice::SubgroupOperations::SUBGROUP_BASIC_BIT;
  560. }
  561. if (supportedOperations & VK_SUBGROUP_FEATURE_VOTE_BIT) {
  562. flags += RenderingDevice::SubgroupOperations::SUBGROUP_VOTE_BIT;
  563. }
  564. if (supportedOperations & VK_SUBGROUP_FEATURE_ARITHMETIC_BIT) {
  565. flags += RenderingDevice::SubgroupOperations::SUBGROUP_ARITHMETIC_BIT;
  566. }
  567. if (supportedOperations & VK_SUBGROUP_FEATURE_BALLOT_BIT) {
  568. flags += RenderingDevice::SubgroupOperations::SUBGROUP_BALLOT_BIT;
  569. }
  570. if (supportedOperations & VK_SUBGROUP_FEATURE_SHUFFLE_BIT) {
  571. flags += RenderingDevice::SubgroupOperations::SUBGROUP_SHUFFLE_BIT;
  572. }
  573. if (supportedOperations & VK_SUBGROUP_FEATURE_SHUFFLE_RELATIVE_BIT) {
  574. flags += RenderingDevice::SubgroupOperations::SUBGROUP_SHUFFLE_RELATIVE_BIT;
  575. }
  576. if (supportedOperations & VK_SUBGROUP_FEATURE_CLUSTERED_BIT) {
  577. flags += RenderingDevice::SubgroupOperations::SUBGROUP_CLUSTERED_BIT;
  578. }
  579. if (supportedOperations & VK_SUBGROUP_FEATURE_QUAD_BIT) {
  580. flags += RenderingDevice::SubgroupOperations::SUBGROUP_QUAD_BIT;
  581. }
  582. return flags;
  583. }
  584. String VulkanContext::SubgroupCapabilities::supported_operations_desc() const {
  585. String res;
  586. if (supportedOperations & VK_SUBGROUP_FEATURE_BASIC_BIT) {
  587. res += ", FEATURE_BASIC";
  588. }
  589. if (supportedOperations & VK_SUBGROUP_FEATURE_VOTE_BIT) {
  590. res += ", FEATURE_VOTE";
  591. }
  592. if (supportedOperations & VK_SUBGROUP_FEATURE_ARITHMETIC_BIT) {
  593. res += ", FEATURE_ARITHMETIC";
  594. }
  595. if (supportedOperations & VK_SUBGROUP_FEATURE_BALLOT_BIT) {
  596. res += ", FEATURE_BALLOT";
  597. }
  598. if (supportedOperations & VK_SUBGROUP_FEATURE_SHUFFLE_BIT) {
  599. res += ", FEATURE_SHUFFLE";
  600. }
  601. if (supportedOperations & VK_SUBGROUP_FEATURE_SHUFFLE_RELATIVE_BIT) {
  602. res += ", FEATURE_SHUFFLE_RELATIVE";
  603. }
  604. if (supportedOperations & VK_SUBGROUP_FEATURE_CLUSTERED_BIT) {
  605. res += ", FEATURE_CLUSTERED";
  606. }
  607. if (supportedOperations & VK_SUBGROUP_FEATURE_QUAD_BIT) {
  608. res += ", FEATURE_QUAD";
  609. }
  610. if (supportedOperations & VK_SUBGROUP_FEATURE_PARTITIONED_BIT_NV) {
  611. res += ", FEATURE_PARTITIONED_NV";
  612. }
  613. return res.substr(2); // Remove first ", ".
  614. }
  615. Error VulkanContext::_check_capabilities() {
  616. // https://www.khronos.org/registry/vulkan/specs/1.2-extensions/man/html/VK_KHR_multiview.html
  617. // https://www.khronos.org/blog/vulkan-subgroup-tutorial
  618. // For Vulkan 1.0 vkGetPhysicalDeviceProperties2 is not available, including not in the loader we compile against on Android.
  619. // So we check if the functions are accessible by getting their function pointers and skipping if not
  620. // (note that the desktop loader does a better job here but the android loader doesn't.)
  621. // Assume not supported until proven otherwise.
  622. vrs_capabilities.pipeline_vrs_supported = false;
  623. vrs_capabilities.primitive_vrs_supported = false;
  624. vrs_capabilities.attachment_vrs_supported = false;
  625. vrs_capabilities.min_texel_size = Size2i();
  626. vrs_capabilities.max_texel_size = Size2i();
  627. vrs_capabilities.texel_size = Size2i();
  628. multiview_capabilities.is_supported = false;
  629. multiview_capabilities.geometry_shader_is_supported = false;
  630. multiview_capabilities.tessellation_shader_is_supported = false;
  631. multiview_capabilities.max_view_count = 0;
  632. multiview_capabilities.max_instance_count = 0;
  633. subgroup_capabilities.size = 0;
  634. subgroup_capabilities.supportedStages = 0;
  635. subgroup_capabilities.supportedOperations = 0;
  636. subgroup_capabilities.quadOperationsInAllStages = false;
  637. shader_capabilities.shader_float16_is_supported = false;
  638. shader_capabilities.shader_int8_is_supported = false;
  639. storage_buffer_capabilities.storage_buffer_16_bit_access_is_supported = false;
  640. storage_buffer_capabilities.uniform_and_storage_buffer_16_bit_access_is_supported = false;
  641. storage_buffer_capabilities.storage_push_constant_16_is_supported = false;
  642. storage_buffer_capabilities.storage_input_output_16 = false;
  643. if (is_instance_extension_enabled(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
  644. // Check for extended features.
  645. PFN_vkGetPhysicalDeviceFeatures2 vkGetPhysicalDeviceFeatures2_func = (PFN_vkGetPhysicalDeviceFeatures2)vkGetInstanceProcAddr(inst, "vkGetPhysicalDeviceFeatures2");
  646. if (vkGetPhysicalDeviceFeatures2_func == nullptr) {
  647. // In Vulkan 1.0 might be accessible under its original extension name.
  648. vkGetPhysicalDeviceFeatures2_func = (PFN_vkGetPhysicalDeviceFeatures2)vkGetInstanceProcAddr(inst, "vkGetPhysicalDeviceFeatures2KHR");
  649. }
  650. if (vkGetPhysicalDeviceFeatures2_func != nullptr) {
  651. // Check our extended features.
  652. void *next = nullptr;
  653. // We must check that the relative extension is present before assuming a
  654. // feature as enabled.
  655. // See also: https://github.com/godotengine/godot/issues/65409
  656. VkPhysicalDeviceVulkan12Features device_features_vk12 = {};
  657. VkPhysicalDeviceShaderFloat16Int8FeaturesKHR shader_features = {};
  658. VkPhysicalDeviceFragmentShadingRateFeaturesKHR vrs_features = {};
  659. VkPhysicalDevice16BitStorageFeaturesKHR storage_feature = {};
  660. VkPhysicalDeviceMultiviewFeatures multiview_features = {};
  661. if (device_api_version >= VK_API_VERSION_1_2) {
  662. device_features_vk12.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  663. device_features_vk12.pNext = next;
  664. next = &device_features_vk12;
  665. } else {
  666. if (is_device_extension_enabled(VK_KHR_SHADER_FLOAT16_INT8_EXTENSION_NAME)) {
  667. shader_features = {
  668. /*sType*/ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_FLOAT16_INT8_FEATURES_KHR,
  669. /*pNext*/ next,
  670. /*shaderFloat16*/ false,
  671. /*shaderInt8*/ false,
  672. };
  673. next = &shader_features;
  674. }
  675. }
  676. if (is_device_extension_enabled(VK_KHR_FRAGMENT_SHADING_RATE_EXTENSION_NAME)) {
  677. vrs_features = {
  678. /*sType*/ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADING_RATE_FEATURES_KHR,
  679. /*pNext*/ next,
  680. /*pipelineFragmentShadingRate*/ false,
  681. /*primitiveFragmentShadingRate*/ false,
  682. /*attachmentFragmentShadingRate*/ false,
  683. };
  684. next = &vrs_features;
  685. }
  686. if (is_device_extension_enabled(VK_KHR_16BIT_STORAGE_EXTENSION_NAME)) {
  687. storage_feature = {
  688. /*sType*/ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES_KHR,
  689. /*pNext*/ next,
  690. /*storageBuffer16BitAccess*/ false,
  691. /*uniformAndStorageBuffer16BitAccess*/ false,
  692. /*storagePushConstant16*/ false,
  693. /*storageInputOutput16*/ false,
  694. };
  695. next = &storage_feature;
  696. }
  697. if (is_device_extension_enabled(VK_KHR_MULTIVIEW_EXTENSION_NAME)) {
  698. multiview_features = {
  699. /*sType*/ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES,
  700. /*pNext*/ next,
  701. /*multiview*/ false,
  702. /*multiviewGeometryShader*/ false,
  703. /*multiviewTessellationShader*/ false,
  704. };
  705. next = &multiview_features;
  706. }
  707. VkPhysicalDeviceFeatures2 device_features;
  708. device_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  709. device_features.pNext = next;
  710. vkGetPhysicalDeviceFeatures2_func(gpu, &device_features);
  711. if (device_api_version >= VK_API_VERSION_1_2) {
  712. #ifdef MACOS_ENABLED
  713. ERR_FAIL_COND_V_MSG(!device_features_vk12.shaderSampledImageArrayNonUniformIndexing, ERR_CANT_CREATE, "Your GPU doesn't support shaderSampledImageArrayNonUniformIndexing which is required to use the Vulkan-based renderers in Godot.");
  714. #endif
  715. if (is_device_extension_enabled(VK_KHR_SHADER_FLOAT16_INT8_EXTENSION_NAME)) {
  716. shader_capabilities.shader_float16_is_supported = device_features_vk12.shaderFloat16;
  717. shader_capabilities.shader_int8_is_supported = device_features_vk12.shaderInt8;
  718. }
  719. } else {
  720. if (is_device_extension_enabled(VK_KHR_SHADER_FLOAT16_INT8_EXTENSION_NAME)) {
  721. shader_capabilities.shader_float16_is_supported = shader_features.shaderFloat16;
  722. shader_capabilities.shader_int8_is_supported = shader_features.shaderInt8;
  723. }
  724. }
  725. if (is_device_extension_enabled(VK_KHR_FRAGMENT_SHADING_RATE_EXTENSION_NAME)) {
  726. vrs_capabilities.pipeline_vrs_supported = vrs_features.pipelineFragmentShadingRate;
  727. vrs_capabilities.primitive_vrs_supported = vrs_features.primitiveFragmentShadingRate;
  728. vrs_capabilities.attachment_vrs_supported = vrs_features.attachmentFragmentShadingRate;
  729. }
  730. if (is_device_extension_enabled(VK_KHR_MULTIVIEW_EXTENSION_NAME)) {
  731. multiview_capabilities.is_supported = multiview_features.multiview;
  732. multiview_capabilities.geometry_shader_is_supported = multiview_features.multiviewGeometryShader;
  733. multiview_capabilities.tessellation_shader_is_supported = multiview_features.multiviewTessellationShader;
  734. }
  735. if (is_device_extension_enabled(VK_KHR_16BIT_STORAGE_EXTENSION_NAME)) {
  736. storage_buffer_capabilities.storage_buffer_16_bit_access_is_supported = storage_feature.storageBuffer16BitAccess;
  737. storage_buffer_capabilities.uniform_and_storage_buffer_16_bit_access_is_supported = storage_feature.uniformAndStorageBuffer16BitAccess;
  738. storage_buffer_capabilities.storage_push_constant_16_is_supported = storage_feature.storagePushConstant16;
  739. storage_buffer_capabilities.storage_input_output_16 = storage_feature.storageInputOutput16;
  740. }
  741. }
  742. // Check extended properties.
  743. PFN_vkGetPhysicalDeviceProperties2 device_properties_func = (PFN_vkGetPhysicalDeviceProperties2)vkGetInstanceProcAddr(inst, "vkGetPhysicalDeviceProperties2");
  744. if (device_properties_func == nullptr) {
  745. // In Vulkan 1.0 might be accessible under its original extension name.
  746. device_properties_func = (PFN_vkGetPhysicalDeviceProperties2)vkGetInstanceProcAddr(inst, "vkGetPhysicalDeviceProperties2KHR");
  747. }
  748. if (device_properties_func != nullptr) {
  749. VkPhysicalDeviceFragmentShadingRatePropertiesKHR vrsProperties{};
  750. VkPhysicalDeviceMultiviewProperties multiviewProperties{};
  751. VkPhysicalDeviceSubgroupProperties subgroupProperties{};
  752. VkPhysicalDeviceProperties2 physicalDeviceProperties{};
  753. void *nextptr = nullptr;
  754. if (device_api_version >= VK_API_VERSION_1_1) { // Vulkan 1.1 or higher
  755. subgroupProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES;
  756. subgroupProperties.pNext = nextptr;
  757. nextptr = &subgroupProperties;
  758. }
  759. if (multiview_capabilities.is_supported) {
  760. multiviewProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES;
  761. multiviewProperties.pNext = nextptr;
  762. nextptr = &multiviewProperties;
  763. }
  764. if (vrs_capabilities.attachment_vrs_supported) {
  765. vrsProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADING_RATE_PROPERTIES_KHR;
  766. vrsProperties.pNext = nextptr;
  767. nextptr = &vrsProperties;
  768. }
  769. physicalDeviceProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
  770. physicalDeviceProperties.pNext = nextptr;
  771. device_properties_func(gpu, &physicalDeviceProperties);
  772. subgroup_capabilities.size = subgroupProperties.subgroupSize;
  773. subgroup_capabilities.supportedStages = subgroupProperties.supportedStages;
  774. subgroup_capabilities.supportedOperations = subgroupProperties.supportedOperations;
  775. // Note: quadOperationsInAllStages will be true if:
  776. // - supportedStages has VK_SHADER_STAGE_ALL_GRAPHICS + VK_SHADER_STAGE_COMPUTE_BIT.
  777. // - supportedOperations has VK_SUBGROUP_FEATURE_QUAD_BIT.
  778. subgroup_capabilities.quadOperationsInAllStages = subgroupProperties.quadOperationsInAllStages;
  779. if (vrs_capabilities.pipeline_vrs_supported || vrs_capabilities.primitive_vrs_supported || vrs_capabilities.attachment_vrs_supported) {
  780. print_verbose("- Vulkan Variable Rate Shading supported:");
  781. if (vrs_capabilities.pipeline_vrs_supported) {
  782. print_verbose(" Pipeline fragment shading rate");
  783. }
  784. if (vrs_capabilities.primitive_vrs_supported) {
  785. print_verbose(" Primitive fragment shading rate");
  786. }
  787. if (vrs_capabilities.attachment_vrs_supported) {
  788. // TODO expose these somehow to the end user.
  789. vrs_capabilities.min_texel_size.x = vrsProperties.minFragmentShadingRateAttachmentTexelSize.width;
  790. vrs_capabilities.min_texel_size.y = vrsProperties.minFragmentShadingRateAttachmentTexelSize.height;
  791. vrs_capabilities.max_texel_size.x = vrsProperties.maxFragmentShadingRateAttachmentTexelSize.width;
  792. vrs_capabilities.max_texel_size.y = vrsProperties.maxFragmentShadingRateAttachmentTexelSize.height;
  793. // We'll attempt to default to a texel size of 16x16
  794. vrs_capabilities.texel_size.x = CLAMP(16, vrs_capabilities.min_texel_size.x, vrs_capabilities.max_texel_size.x);
  795. vrs_capabilities.texel_size.y = CLAMP(16, vrs_capabilities.min_texel_size.y, vrs_capabilities.max_texel_size.y);
  796. print_verbose(String(" Attachment fragment shading rate") + String(", min texel size: (") + itos(vrs_capabilities.min_texel_size.x) + String(", ") + itos(vrs_capabilities.min_texel_size.y) + String(")") + String(", max texel size: (") + itos(vrs_capabilities.max_texel_size.x) + String(", ") + itos(vrs_capabilities.max_texel_size.y) + String(")"));
  797. }
  798. } else {
  799. print_verbose("- Vulkan Variable Rate Shading not supported");
  800. }
  801. if (multiview_capabilities.is_supported) {
  802. multiview_capabilities.max_view_count = multiviewProperties.maxMultiviewViewCount;
  803. multiview_capabilities.max_instance_count = multiviewProperties.maxMultiviewInstanceIndex;
  804. print_verbose("- Vulkan multiview supported:");
  805. print_verbose(" max view count: " + itos(multiview_capabilities.max_view_count));
  806. print_verbose(" max instances: " + itos(multiview_capabilities.max_instance_count));
  807. } else {
  808. print_verbose("- Vulkan multiview not supported");
  809. }
  810. print_verbose("- Vulkan subgroup:");
  811. print_verbose(" size: " + itos(subgroup_capabilities.size));
  812. print_verbose(" stages: " + subgroup_capabilities.supported_stages_desc());
  813. print_verbose(" supported ops: " + subgroup_capabilities.supported_operations_desc());
  814. if (subgroup_capabilities.quadOperationsInAllStages) {
  815. print_verbose(" quad operations in all stages");
  816. }
  817. } else {
  818. print_verbose("- Couldn't call vkGetPhysicalDeviceProperties2");
  819. }
  820. }
  821. return OK;
  822. }
  823. Error VulkanContext::_create_instance() {
  824. // Obtain Vulkan version.
  825. _obtain_vulkan_version();
  826. // Initialize extensions.
  827. {
  828. Error err = _initialize_instance_extensions();
  829. if (err != OK) {
  830. return err;
  831. }
  832. }
  833. int enabled_extension_count = 0;
  834. const char *enabled_extension_names[MAX_EXTENSIONS];
  835. ERR_FAIL_COND_V(enabled_instance_extension_names.size() > MAX_EXTENSIONS, ERR_CANT_CREATE);
  836. for (const CharString &extension_name : enabled_instance_extension_names) {
  837. enabled_extension_names[enabled_extension_count++] = extension_name.ptr();
  838. }
  839. // We'll set application version to the Vulkan version we're developing against, even if our instance is based on
  840. // an older Vulkan version, devices can still support newer versions of Vulkan.
  841. // The exception is when we're on Vulkan 1.0, we should not set this to anything but 1.0.
  842. // Note that this value is only used by validation layers to warn us about version issues.
  843. uint32_t application_api_version = instance_api_version == VK_API_VERSION_1_0 ? VK_API_VERSION_1_0 : VK_API_VERSION_1_2;
  844. CharString cs = GLOBAL_GET("application/config/name").operator String().utf8();
  845. const VkApplicationInfo app = {
  846. /*sType*/ VK_STRUCTURE_TYPE_APPLICATION_INFO,
  847. /*pNext*/ nullptr,
  848. /*pApplicationName*/ cs.get_data(),
  849. /*applicationVersion*/ 0, // It would be really nice if we store a version number in project settings, say "application/config/version"
  850. /*pEngineName*/ VERSION_NAME,
  851. /*engineVersion*/ VK_MAKE_VERSION(VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH),
  852. /*apiVersion*/ application_api_version
  853. };
  854. VkInstanceCreateInfo inst_info{};
  855. inst_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
  856. inst_info.pApplicationInfo = &app;
  857. inst_info.enabledExtensionCount = enabled_extension_count;
  858. inst_info.ppEnabledExtensionNames = (const char *const *)enabled_extension_names;
  859. if (_use_validation_layers()) {
  860. _get_preferred_validation_layers(&inst_info.enabledLayerCount, &inst_info.ppEnabledLayerNames);
  861. }
  862. /*
  863. * This is info for a temp callback to use during CreateInstance.
  864. * After the instance is created, we use the instance-based
  865. * function to register the final callback.
  866. */
  867. VkDebugUtilsMessengerCreateInfoEXT dbg_messenger_create_info = {};
  868. VkDebugReportCallbackCreateInfoEXT dbg_report_callback_create_info = {};
  869. if (is_instance_extension_enabled(VK_EXT_DEBUG_UTILS_EXTENSION_NAME)) {
  870. // VK_EXT_debug_utils style.
  871. dbg_messenger_create_info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
  872. dbg_messenger_create_info.pNext = nullptr;
  873. dbg_messenger_create_info.flags = 0;
  874. dbg_messenger_create_info.messageSeverity =
  875. VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
  876. dbg_messenger_create_info.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
  877. VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
  878. VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
  879. dbg_messenger_create_info.pfnUserCallback = _debug_messenger_callback;
  880. dbg_messenger_create_info.pUserData = this;
  881. inst_info.pNext = &dbg_messenger_create_info;
  882. } else if (is_instance_extension_enabled(VK_EXT_DEBUG_REPORT_EXTENSION_NAME)) {
  883. dbg_report_callback_create_info.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT;
  884. dbg_report_callback_create_info.flags = VK_DEBUG_REPORT_INFORMATION_BIT_EXT |
  885. VK_DEBUG_REPORT_WARNING_BIT_EXT |
  886. VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT |
  887. VK_DEBUG_REPORT_ERROR_BIT_EXT |
  888. VK_DEBUG_REPORT_DEBUG_BIT_EXT;
  889. dbg_report_callback_create_info.pfnCallback = _debug_report_callback;
  890. dbg_report_callback_create_info.pUserData = this;
  891. inst_info.pNext = &dbg_report_callback_create_info;
  892. }
  893. VkResult err;
  894. if (vulkan_hooks) {
  895. if (!vulkan_hooks->create_vulkan_instance(&inst_info, &inst)) {
  896. return ERR_CANT_CREATE;
  897. }
  898. } else {
  899. err = vkCreateInstance(&inst_info, nullptr, &inst);
  900. ERR_FAIL_COND_V_MSG(err == VK_ERROR_INCOMPATIBLE_DRIVER, ERR_CANT_CREATE,
  901. "Cannot find a compatible Vulkan installable client driver (ICD).\n\n"
  902. "vkCreateInstance Failure");
  903. ERR_FAIL_COND_V_MSG(err == VK_ERROR_EXTENSION_NOT_PRESENT, ERR_CANT_CREATE,
  904. "Cannot find a specified extension library.\n"
  905. "Make sure your layers path is set appropriately.\n"
  906. "vkCreateInstance Failure");
  907. ERR_FAIL_COND_V_MSG(err, ERR_CANT_CREATE,
  908. "vkCreateInstance failed.\n\n"
  909. "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
  910. "Please look at the Getting Started guide for additional information.\n"
  911. "vkCreateInstance Failure");
  912. }
  913. inst_initialized = true;
  914. #ifdef USE_VOLK
  915. volkLoadInstance(inst);
  916. #endif
  917. if (is_instance_extension_enabled(VK_EXT_DEBUG_UTILS_EXTENSION_NAME)) {
  918. // Setup VK_EXT_debug_utils function pointers always (we use them for debug labels and names).
  919. CreateDebugUtilsMessengerEXT =
  920. (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr(inst, "vkCreateDebugUtilsMessengerEXT");
  921. DestroyDebugUtilsMessengerEXT =
  922. (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr(inst, "vkDestroyDebugUtilsMessengerEXT");
  923. SubmitDebugUtilsMessageEXT =
  924. (PFN_vkSubmitDebugUtilsMessageEXT)vkGetInstanceProcAddr(inst, "vkSubmitDebugUtilsMessageEXT");
  925. CmdBeginDebugUtilsLabelEXT =
  926. (PFN_vkCmdBeginDebugUtilsLabelEXT)vkGetInstanceProcAddr(inst, "vkCmdBeginDebugUtilsLabelEXT");
  927. CmdEndDebugUtilsLabelEXT =
  928. (PFN_vkCmdEndDebugUtilsLabelEXT)vkGetInstanceProcAddr(inst, "vkCmdEndDebugUtilsLabelEXT");
  929. CmdInsertDebugUtilsLabelEXT =
  930. (PFN_vkCmdInsertDebugUtilsLabelEXT)vkGetInstanceProcAddr(inst, "vkCmdInsertDebugUtilsLabelEXT");
  931. SetDebugUtilsObjectNameEXT =
  932. (PFN_vkSetDebugUtilsObjectNameEXT)vkGetInstanceProcAddr(inst, "vkSetDebugUtilsObjectNameEXT");
  933. if (nullptr == CreateDebugUtilsMessengerEXT || nullptr == DestroyDebugUtilsMessengerEXT ||
  934. nullptr == SubmitDebugUtilsMessageEXT || nullptr == CmdBeginDebugUtilsLabelEXT ||
  935. nullptr == CmdEndDebugUtilsLabelEXT || nullptr == CmdInsertDebugUtilsLabelEXT ||
  936. nullptr == SetDebugUtilsObjectNameEXT) {
  937. ERR_FAIL_V_MSG(ERR_CANT_CREATE,
  938. "GetProcAddr: Failed to init VK_EXT_debug_utils\n"
  939. "GetProcAddr: Failure");
  940. }
  941. err = CreateDebugUtilsMessengerEXT(inst, &dbg_messenger_create_info, nullptr, &dbg_messenger);
  942. switch (err) {
  943. case VK_SUCCESS:
  944. break;
  945. case VK_ERROR_OUT_OF_HOST_MEMORY:
  946. ERR_FAIL_V_MSG(ERR_CANT_CREATE,
  947. "CreateDebugUtilsMessengerEXT: out of host memory\n"
  948. "CreateDebugUtilsMessengerEXT Failure");
  949. break;
  950. default:
  951. ERR_FAIL_V_MSG(ERR_CANT_CREATE,
  952. "CreateDebugUtilsMessengerEXT: unknown failure\n"
  953. "CreateDebugUtilsMessengerEXT Failure");
  954. ERR_FAIL_V(ERR_CANT_CREATE);
  955. break;
  956. }
  957. } else if (is_instance_extension_enabled(VK_EXT_DEBUG_REPORT_EXTENSION_NAME)) {
  958. CreateDebugReportCallbackEXT = (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(inst, "vkCreateDebugReportCallbackEXT");
  959. DebugReportMessageEXT = (PFN_vkDebugReportMessageEXT)vkGetInstanceProcAddr(inst, "vkDebugReportMessageEXT");
  960. DestroyDebugReportCallbackEXT = (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(inst, "vkDestroyDebugReportCallbackEXT");
  961. if (nullptr == CreateDebugReportCallbackEXT || nullptr == DebugReportMessageEXT || nullptr == DestroyDebugReportCallbackEXT) {
  962. ERR_FAIL_V_MSG(ERR_CANT_CREATE,
  963. "GetProcAddr: Failed to init VK_EXT_debug_report\n"
  964. "GetProcAddr: Failure");
  965. }
  966. err = CreateDebugReportCallbackEXT(inst, &dbg_report_callback_create_info, nullptr, &dbg_debug_report);
  967. switch (err) {
  968. case VK_SUCCESS:
  969. break;
  970. case VK_ERROR_OUT_OF_HOST_MEMORY:
  971. ERR_FAIL_V_MSG(ERR_CANT_CREATE,
  972. "CreateDebugReportCallbackEXT: out of host memory\n"
  973. "CreateDebugReportCallbackEXT Failure");
  974. break;
  975. default:
  976. ERR_FAIL_V_MSG(ERR_CANT_CREATE,
  977. "CreateDebugReportCallbackEXT: unknown failure\n"
  978. "CreateDebugReportCallbackEXT Failure");
  979. ERR_FAIL_V(ERR_CANT_CREATE);
  980. break;
  981. }
  982. }
  983. return OK;
  984. }
  985. Error VulkanContext::_create_physical_device(VkSurfaceKHR p_surface) {
  986. // Make initial call to query gpu_count, then second call for gpu info.
  987. uint32_t gpu_count = 0;
  988. VkResult err = vkEnumeratePhysicalDevices(inst, &gpu_count, nullptr);
  989. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  990. ERR_FAIL_COND_V_MSG(gpu_count == 0, ERR_CANT_CREATE,
  991. "vkEnumeratePhysicalDevices reported zero accessible devices.\n\n"
  992. "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
  993. "vkEnumeratePhysicalDevices Failure");
  994. VkPhysicalDevice *physical_devices = (VkPhysicalDevice *)malloc(sizeof(VkPhysicalDevice) * gpu_count);
  995. err = vkEnumeratePhysicalDevices(inst, &gpu_count, physical_devices);
  996. if (err) {
  997. free(physical_devices);
  998. ERR_FAIL_V(ERR_CANT_CREATE);
  999. }
  1000. static const struct {
  1001. uint32_t id;
  1002. const char *name;
  1003. } vendor_names[] = {
  1004. { 0x1002, "AMD" },
  1005. { 0x1010, "ImgTec" },
  1006. { 0x106B, "Apple" },
  1007. { 0x10DE, "NVIDIA" },
  1008. { 0x13B5, "ARM" },
  1009. { 0x5143, "Qualcomm" },
  1010. { 0x8086, "Intel" },
  1011. { 0, nullptr },
  1012. };
  1013. int32_t device_index = -1;
  1014. if (vulkan_hooks) {
  1015. if (!vulkan_hooks->get_physical_device(&gpu)) {
  1016. return ERR_CANT_CREATE;
  1017. }
  1018. // Not really needed but nice to print the correct entry.
  1019. for (uint32_t i = 0; i < gpu_count; ++i) {
  1020. if (physical_devices[i] == gpu) {
  1021. device_index = i;
  1022. break;
  1023. }
  1024. }
  1025. } else {
  1026. // TODO: At least on Linux Laptops integrated GPUs fail with Vulkan in many instances.
  1027. // The device should really be a preference, but for now choosing a discrete GPU over the
  1028. // integrated one is better than the default.
  1029. int type_selected = -1;
  1030. print_verbose("Vulkan devices:");
  1031. for (uint32_t i = 0; i < gpu_count; ++i) {
  1032. VkPhysicalDeviceProperties props;
  1033. vkGetPhysicalDeviceProperties(physical_devices[i], &props);
  1034. bool present_supported = false;
  1035. uint32_t device_queue_family_count = 0;
  1036. vkGetPhysicalDeviceQueueFamilyProperties(physical_devices[i], &device_queue_family_count, nullptr);
  1037. VkQueueFamilyProperties *device_queue_props = (VkQueueFamilyProperties *)malloc(device_queue_family_count * sizeof(VkQueueFamilyProperties));
  1038. vkGetPhysicalDeviceQueueFamilyProperties(physical_devices[i], &device_queue_family_count, device_queue_props);
  1039. for (uint32_t j = 0; j < device_queue_family_count; j++) {
  1040. VkBool32 supports;
  1041. vkGetPhysicalDeviceSurfaceSupportKHR(physical_devices[i], j, p_surface, &supports);
  1042. if (supports && ((device_queue_props[j].queueFlags & VK_QUEUE_GRAPHICS_BIT) != 0)) {
  1043. present_supported = true;
  1044. } else {
  1045. continue;
  1046. }
  1047. }
  1048. String name = props.deviceName;
  1049. String vendor = "Unknown";
  1050. String dev_type;
  1051. switch (props.deviceType) {
  1052. case VkPhysicalDeviceType::VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU: {
  1053. dev_type = "Discrete";
  1054. } break;
  1055. case VkPhysicalDeviceType::VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU: {
  1056. dev_type = "Integrated";
  1057. } break;
  1058. case VkPhysicalDeviceType::VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU: {
  1059. dev_type = "Virtual";
  1060. } break;
  1061. case VkPhysicalDeviceType::VK_PHYSICAL_DEVICE_TYPE_CPU: {
  1062. dev_type = "CPU";
  1063. } break;
  1064. default: {
  1065. dev_type = "Other";
  1066. } break;
  1067. }
  1068. uint32_t vendor_idx = 0;
  1069. while (vendor_names[vendor_idx].name != nullptr) {
  1070. if (props.vendorID == vendor_names[vendor_idx].id) {
  1071. vendor = vendor_names[vendor_idx].name;
  1072. break;
  1073. }
  1074. vendor_idx++;
  1075. }
  1076. free(device_queue_props);
  1077. print_verbose(" #" + itos(i) + ": " + vendor + " " + name + " - " + (present_supported ? "Supported" : "Unsupported") + ", " + dev_type);
  1078. if (present_supported) { // Select first supported device of preferred type: Discrete > Integrated > Virtual > CPU > Other.
  1079. switch (props.deviceType) {
  1080. case VkPhysicalDeviceType::VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU: {
  1081. if (type_selected < 4) {
  1082. type_selected = 4;
  1083. device_index = i;
  1084. }
  1085. } break;
  1086. case VkPhysicalDeviceType::VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU: {
  1087. if (type_selected < 3) {
  1088. type_selected = 3;
  1089. device_index = i;
  1090. }
  1091. } break;
  1092. case VkPhysicalDeviceType::VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU: {
  1093. if (type_selected < 2) {
  1094. type_selected = 2;
  1095. device_index = i;
  1096. }
  1097. } break;
  1098. case VkPhysicalDeviceType::VK_PHYSICAL_DEVICE_TYPE_CPU: {
  1099. if (type_selected < 1) {
  1100. type_selected = 1;
  1101. device_index = i;
  1102. }
  1103. } break;
  1104. default: {
  1105. if (type_selected < 0) {
  1106. type_selected = 0;
  1107. device_index = i;
  1108. }
  1109. } break;
  1110. }
  1111. }
  1112. }
  1113. int32_t user_device_index = Engine::get_singleton()->get_gpu_index(); // Force user selected GPU.
  1114. if (user_device_index >= 0 && user_device_index < (int32_t)gpu_count) {
  1115. device_index = user_device_index;
  1116. }
  1117. ERR_FAIL_COND_V_MSG(device_index == -1, ERR_CANT_CREATE, "None of Vulkan devices supports both graphics and present queues.");
  1118. gpu = physical_devices[device_index];
  1119. }
  1120. free(physical_devices);
  1121. // Get identifier properties.
  1122. vkGetPhysicalDeviceProperties(gpu, &gpu_props);
  1123. device_name = gpu_props.deviceName;
  1124. device_type = gpu_props.deviceType;
  1125. pipeline_cache_id = String::hex_encode_buffer(gpu_props.pipelineCacheUUID, VK_UUID_SIZE);
  1126. pipeline_cache_id += "-driver-" + itos(gpu_props.driverVersion);
  1127. {
  1128. device_vendor = "Unknown";
  1129. uint32_t vendor_idx = 0;
  1130. while (vendor_names[vendor_idx].name != nullptr) {
  1131. if (gpu_props.vendorID == vendor_names[vendor_idx].id) {
  1132. device_vendor = vendor_names[vendor_idx].name;
  1133. break;
  1134. }
  1135. vendor_idx++;
  1136. }
  1137. }
  1138. // Get device version
  1139. device_api_version = gpu_props.apiVersion;
  1140. String rendering_method;
  1141. if (OS::get_singleton()->get_current_rendering_method() == "mobile") {
  1142. rendering_method = "Forward Mobile";
  1143. } else {
  1144. rendering_method = "Forward+";
  1145. }
  1146. // Output our device version
  1147. print_line(vformat("Vulkan API %s - %s - Using Vulkan Device #%d: %s - %s", get_device_api_version(), rendering_method, device_index, device_vendor, device_name));
  1148. {
  1149. Error _err = _initialize_device_extensions();
  1150. if (_err != OK) {
  1151. return _err;
  1152. }
  1153. }
  1154. // Call with nullptr data to get count.
  1155. vkGetPhysicalDeviceQueueFamilyProperties(gpu, &queue_family_count, nullptr);
  1156. ERR_FAIL_COND_V(queue_family_count == 0, ERR_CANT_CREATE);
  1157. queue_props = (VkQueueFamilyProperties *)malloc(queue_family_count * sizeof(VkQueueFamilyProperties));
  1158. vkGetPhysicalDeviceQueueFamilyProperties(gpu, &queue_family_count, queue_props);
  1159. // Query fine-grained feature support for this device.
  1160. // If app has specific feature requirements it should check supported
  1161. // features based on this query
  1162. vkGetPhysicalDeviceFeatures(gpu, &physical_device_features);
  1163. // Check required features
  1164. ERR_FAIL_COND_V_MSG(!physical_device_features.imageCubeArray, ERR_CANT_CREATE, "Your GPU doesn't support image cube arrays which are required to use the Vulkan-based renderers in Godot.");
  1165. ERR_FAIL_COND_V_MSG(!physical_device_features.independentBlend, ERR_CANT_CREATE, "Your GPU doesn't support independentBlend which is required to use the Vulkan-based renderers in Godot.");
  1166. physical_device_features.robustBufferAccess = false; // Turn off robust buffer access, which can hamper performance on some hardware.
  1167. #define GET_INSTANCE_PROC_ADDR(inst, entrypoint) \
  1168. { \
  1169. fp##entrypoint = (PFN_vk##entrypoint)vkGetInstanceProcAddr(inst, "vk" #entrypoint); \
  1170. ERR_FAIL_COND_V_MSG(fp##entrypoint == nullptr, ERR_CANT_CREATE, \
  1171. "vkGetInstanceProcAddr failed to find vk" #entrypoint); \
  1172. }
  1173. GET_INSTANCE_PROC_ADDR(inst, GetPhysicalDeviceSurfaceSupportKHR);
  1174. GET_INSTANCE_PROC_ADDR(inst, GetPhysicalDeviceSurfaceCapabilitiesKHR);
  1175. GET_INSTANCE_PROC_ADDR(inst, GetPhysicalDeviceSurfaceFormatsKHR);
  1176. GET_INSTANCE_PROC_ADDR(inst, GetPhysicalDeviceSurfacePresentModesKHR);
  1177. GET_INSTANCE_PROC_ADDR(inst, GetSwapchainImagesKHR);
  1178. // Gets capability info for current Vulkan driver.
  1179. {
  1180. Error res = _check_capabilities();
  1181. if (res != OK) {
  1182. return res;
  1183. }
  1184. }
  1185. device_initialized = true;
  1186. return OK;
  1187. }
  1188. Error VulkanContext::_create_device() {
  1189. VkResult err;
  1190. float queue_priorities[1] = { 0.0 };
  1191. VkDeviceQueueCreateInfo queues[2];
  1192. queues[0].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
  1193. queues[0].pNext = nullptr;
  1194. queues[0].queueFamilyIndex = graphics_queue_family_index;
  1195. queues[0].queueCount = 1;
  1196. queues[0].pQueuePriorities = queue_priorities;
  1197. queues[0].flags = 0;
  1198. // Before we retrieved what is supported, here we tell Vulkan we want to enable these features using the same structs.
  1199. void *nextptr = nullptr;
  1200. VkPhysicalDeviceShaderFloat16Int8FeaturesKHR shader_features = {
  1201. /*sType*/ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_FLOAT16_INT8_FEATURES_KHR,
  1202. /*pNext*/ nextptr,
  1203. /*shaderFloat16*/ shader_capabilities.shader_float16_is_supported,
  1204. /*shaderInt8*/ shader_capabilities.shader_int8_is_supported,
  1205. };
  1206. nextptr = &shader_features;
  1207. VkPhysicalDeviceFragmentShadingRateFeaturesKHR vrs_features = {};
  1208. if (vrs_capabilities.pipeline_vrs_supported || vrs_capabilities.primitive_vrs_supported || vrs_capabilities.attachment_vrs_supported) {
  1209. // Insert into our chain to enable these features if they are available.
  1210. vrs_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADING_RATE_FEATURES_KHR;
  1211. vrs_features.pNext = nextptr;
  1212. vrs_features.pipelineFragmentShadingRate = vrs_capabilities.pipeline_vrs_supported;
  1213. vrs_features.primitiveFragmentShadingRate = vrs_capabilities.primitive_vrs_supported;
  1214. vrs_features.attachmentFragmentShadingRate = vrs_capabilities.attachment_vrs_supported;
  1215. nextptr = &vrs_features;
  1216. }
  1217. VkPhysicalDeviceVulkan11Features vulkan11features = {};
  1218. VkPhysicalDevice16BitStorageFeaturesKHR storage_feature = {};
  1219. VkPhysicalDeviceMultiviewFeatures multiview_features = {};
  1220. if (device_api_version >= VK_API_VERSION_1_2) {
  1221. // In Vulkan 1.2 and newer we use a newer struct to enable various features.
  1222. vulkan11features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  1223. vulkan11features.pNext = nextptr;
  1224. vulkan11features.storageBuffer16BitAccess = storage_buffer_capabilities.storage_buffer_16_bit_access_is_supported;
  1225. vulkan11features.uniformAndStorageBuffer16BitAccess = storage_buffer_capabilities.uniform_and_storage_buffer_16_bit_access_is_supported;
  1226. vulkan11features.storagePushConstant16 = storage_buffer_capabilities.storage_push_constant_16_is_supported;
  1227. vulkan11features.storageInputOutput16 = storage_buffer_capabilities.storage_input_output_16;
  1228. vulkan11features.multiview = multiview_capabilities.is_supported;
  1229. vulkan11features.multiviewGeometryShader = multiview_capabilities.geometry_shader_is_supported;
  1230. vulkan11features.multiviewTessellationShader = multiview_capabilities.tessellation_shader_is_supported;
  1231. vulkan11features.variablePointersStorageBuffer = 0;
  1232. vulkan11features.variablePointers = 0;
  1233. vulkan11features.protectedMemory = 0;
  1234. vulkan11features.samplerYcbcrConversion = 0;
  1235. vulkan11features.shaderDrawParameters = 0;
  1236. nextptr = &vulkan11features;
  1237. } else {
  1238. // On Vulkan 1.0 and 1.1 we use our older structs to initialize these features.
  1239. storage_feature.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES_KHR;
  1240. storage_feature.pNext = nextptr;
  1241. storage_feature.storageBuffer16BitAccess = storage_buffer_capabilities.storage_buffer_16_bit_access_is_supported;
  1242. storage_feature.uniformAndStorageBuffer16BitAccess = storage_buffer_capabilities.uniform_and_storage_buffer_16_bit_access_is_supported;
  1243. storage_feature.storagePushConstant16 = storage_buffer_capabilities.storage_push_constant_16_is_supported;
  1244. storage_feature.storageInputOutput16 = storage_buffer_capabilities.storage_input_output_16;
  1245. nextptr = &storage_feature;
  1246. if (device_api_version >= VK_API_VERSION_1_1) { // any Vulkan 1.1.x version
  1247. multiview_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES;
  1248. multiview_features.pNext = nextptr;
  1249. multiview_features.multiview = multiview_capabilities.is_supported;
  1250. multiview_features.multiviewGeometryShader = multiview_capabilities.geometry_shader_is_supported;
  1251. multiview_features.multiviewTessellationShader = multiview_capabilities.tessellation_shader_is_supported;
  1252. nextptr = &multiview_features;
  1253. }
  1254. }
  1255. uint32_t enabled_extension_count = 0;
  1256. const char *enabled_extension_names[MAX_EXTENSIONS];
  1257. ERR_FAIL_COND_V(enabled_device_extension_names.size() > MAX_EXTENSIONS, ERR_CANT_CREATE);
  1258. for (const CharString &extension_name : enabled_device_extension_names) {
  1259. enabled_extension_names[enabled_extension_count++] = extension_name.ptr();
  1260. }
  1261. VkDeviceCreateInfo sdevice = {
  1262. /*sType*/ VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
  1263. /*pNext*/ nextptr,
  1264. /*flags*/ 0,
  1265. /*queueCreateInfoCount*/ 1,
  1266. /*pQueueCreateInfos*/ queues,
  1267. /*enabledLayerCount*/ 0,
  1268. /*ppEnabledLayerNames*/ nullptr,
  1269. /*enabledExtensionCount*/ enabled_extension_count,
  1270. /*ppEnabledExtensionNames*/ (const char *const *)enabled_extension_names,
  1271. /*pEnabledFeatures*/ &physical_device_features, // If specific features are required, pass them in here.
  1272. };
  1273. if (separate_present_queue) {
  1274. queues[1].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
  1275. queues[1].pNext = nullptr;
  1276. queues[1].queueFamilyIndex = present_queue_family_index;
  1277. queues[1].queueCount = 1;
  1278. queues[1].pQueuePriorities = queue_priorities;
  1279. queues[1].flags = 0;
  1280. sdevice.queueCreateInfoCount = 2;
  1281. }
  1282. if (vulkan_hooks) {
  1283. if (!vulkan_hooks->create_vulkan_device(&sdevice, &device)) {
  1284. return ERR_CANT_CREATE;
  1285. }
  1286. } else {
  1287. err = vkCreateDevice(gpu, &sdevice, nullptr, &device);
  1288. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  1289. }
  1290. return OK;
  1291. }
  1292. Error VulkanContext::_initialize_queues(VkSurfaceKHR p_surface) {
  1293. // Iterate over each queue to learn whether it supports presenting:
  1294. VkBool32 *supportsPresent = (VkBool32 *)malloc(queue_family_count * sizeof(VkBool32));
  1295. for (uint32_t i = 0; i < queue_family_count; i++) {
  1296. fpGetPhysicalDeviceSurfaceSupportKHR(gpu, i, p_surface, &supportsPresent[i]);
  1297. }
  1298. // Search for a graphics and a present queue in the array of queue
  1299. // families, try to find one that supports both.
  1300. uint32_t graphicsQueueFamilyIndex = UINT32_MAX;
  1301. uint32_t presentQueueFamilyIndex = UINT32_MAX;
  1302. for (uint32_t i = 0; i < queue_family_count; i++) {
  1303. if ((queue_props[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) != 0) {
  1304. if (graphicsQueueFamilyIndex == UINT32_MAX) {
  1305. graphicsQueueFamilyIndex = i;
  1306. }
  1307. if (supportsPresent[i] == VK_TRUE) {
  1308. graphicsQueueFamilyIndex = i;
  1309. presentQueueFamilyIndex = i;
  1310. break;
  1311. }
  1312. }
  1313. }
  1314. if (presentQueueFamilyIndex == UINT32_MAX) {
  1315. // If didn't find a queue that supports both graphics and present, then
  1316. // find a separate present queue.
  1317. for (uint32_t i = 0; i < queue_family_count; ++i) {
  1318. if (supportsPresent[i] == VK_TRUE) {
  1319. presentQueueFamilyIndex = i;
  1320. break;
  1321. }
  1322. }
  1323. }
  1324. free(supportsPresent);
  1325. // Generate error if could not find both a graphics and a present queue.
  1326. ERR_FAIL_COND_V_MSG(graphicsQueueFamilyIndex == UINT32_MAX || presentQueueFamilyIndex == UINT32_MAX, ERR_CANT_CREATE,
  1327. "Could not find both graphics and present queues\n");
  1328. graphics_queue_family_index = graphicsQueueFamilyIndex;
  1329. present_queue_family_index = presentQueueFamilyIndex;
  1330. separate_present_queue = (graphics_queue_family_index != present_queue_family_index);
  1331. _create_device();
  1332. static PFN_vkGetDeviceProcAddr g_gdpa = nullptr;
  1333. #define GET_DEVICE_PROC_ADDR(dev, entrypoint) \
  1334. { \
  1335. if (!g_gdpa) \
  1336. g_gdpa = (PFN_vkGetDeviceProcAddr)vkGetInstanceProcAddr(inst, "vkGetDeviceProcAddr"); \
  1337. fp##entrypoint = (PFN_vk##entrypoint)g_gdpa(dev, "vk" #entrypoint); \
  1338. ERR_FAIL_COND_V_MSG(fp##entrypoint == nullptr, ERR_CANT_CREATE, \
  1339. "vkGetDeviceProcAddr failed to find vk" #entrypoint); \
  1340. }
  1341. GET_DEVICE_PROC_ADDR(device, CreateSwapchainKHR);
  1342. GET_DEVICE_PROC_ADDR(device, DestroySwapchainKHR);
  1343. GET_DEVICE_PROC_ADDR(device, GetSwapchainImagesKHR);
  1344. GET_DEVICE_PROC_ADDR(device, AcquireNextImageKHR);
  1345. GET_DEVICE_PROC_ADDR(device, QueuePresentKHR);
  1346. if (is_device_extension_enabled(VK_GOOGLE_DISPLAY_TIMING_EXTENSION_NAME)) {
  1347. GET_DEVICE_PROC_ADDR(device, GetRefreshCycleDurationGOOGLE);
  1348. GET_DEVICE_PROC_ADDR(device, GetPastPresentationTimingGOOGLE);
  1349. }
  1350. vkGetDeviceQueue(device, graphics_queue_family_index, 0, &graphics_queue);
  1351. if (!separate_present_queue) {
  1352. present_queue = graphics_queue;
  1353. } else {
  1354. vkGetDeviceQueue(device, present_queue_family_index, 0, &present_queue);
  1355. }
  1356. // Get the list of VkFormat's that are supported:
  1357. uint32_t formatCount;
  1358. VkResult err = fpGetPhysicalDeviceSurfaceFormatsKHR(gpu, p_surface, &formatCount, nullptr);
  1359. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  1360. VkSurfaceFormatKHR *surfFormats = (VkSurfaceFormatKHR *)malloc(formatCount * sizeof(VkSurfaceFormatKHR));
  1361. err = fpGetPhysicalDeviceSurfaceFormatsKHR(gpu, p_surface, &formatCount, surfFormats);
  1362. if (err) {
  1363. free(surfFormats);
  1364. ERR_FAIL_V(ERR_CANT_CREATE);
  1365. }
  1366. // If the format list includes just one entry of VK_FORMAT_UNDEFINED,
  1367. // the surface has no preferred format. Otherwise, at least one
  1368. // supported format will be returned.
  1369. if (formatCount == 1 && surfFormats[0].format == VK_FORMAT_UNDEFINED) {
  1370. format = VK_FORMAT_B8G8R8A8_UNORM;
  1371. color_space = surfFormats[0].colorSpace;
  1372. } else {
  1373. // These should be ordered with the ones we want to use on top and fallback modes further down
  1374. // we want a 32bit RGBA unsigned normalized buffer or similar.
  1375. const VkFormat allowed_formats[] = {
  1376. VK_FORMAT_B8G8R8A8_UNORM,
  1377. VK_FORMAT_R8G8B8A8_UNORM
  1378. };
  1379. uint32_t allowed_formats_count = sizeof(allowed_formats) / sizeof(VkFormat);
  1380. if (formatCount < 1) {
  1381. free(surfFormats);
  1382. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "formatCount less than 1");
  1383. }
  1384. // Find the first format that we support.
  1385. format = VK_FORMAT_UNDEFINED;
  1386. for (uint32_t af = 0; af < allowed_formats_count && format == VK_FORMAT_UNDEFINED; af++) {
  1387. for (uint32_t sf = 0; sf < formatCount && format == VK_FORMAT_UNDEFINED; sf++) {
  1388. if (surfFormats[sf].format == allowed_formats[af]) {
  1389. format = surfFormats[sf].format;
  1390. color_space = surfFormats[sf].colorSpace;
  1391. }
  1392. }
  1393. }
  1394. if (format == VK_FORMAT_UNDEFINED) {
  1395. free(surfFormats);
  1396. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "No usable surface format found.");
  1397. }
  1398. }
  1399. free(surfFormats);
  1400. Error serr = _create_semaphores();
  1401. if (serr) {
  1402. return serr;
  1403. }
  1404. queues_initialized = true;
  1405. return OK;
  1406. }
  1407. Error VulkanContext::_create_semaphores() {
  1408. VkResult err;
  1409. // Create semaphores to synchronize acquiring presentable buffers before
  1410. // rendering and waiting for drawing to be complete before presenting.
  1411. VkSemaphoreCreateInfo semaphoreCreateInfo = {
  1412. /*sType*/ VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
  1413. /*pNext*/ nullptr,
  1414. /*flags*/ 0,
  1415. };
  1416. // Create fences that we can use to throttle if we get too far
  1417. // ahead of the image presents.
  1418. VkFenceCreateInfo fence_ci = {
  1419. /*sType*/ VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,
  1420. /*pNext*/ nullptr,
  1421. /*flags*/ VK_FENCE_CREATE_SIGNALED_BIT
  1422. };
  1423. for (uint32_t i = 0; i < FRAME_LAG; i++) {
  1424. err = vkCreateFence(device, &fence_ci, nullptr, &fences[i]);
  1425. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  1426. err = vkCreateSemaphore(device, &semaphoreCreateInfo, nullptr, &draw_complete_semaphores[i]);
  1427. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  1428. if (separate_present_queue) {
  1429. err = vkCreateSemaphore(device, &semaphoreCreateInfo, nullptr, &image_ownership_semaphores[i]);
  1430. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  1431. }
  1432. }
  1433. frame_index = 0;
  1434. // Get Memory information and properties.
  1435. vkGetPhysicalDeviceMemoryProperties(gpu, &memory_properties);
  1436. return OK;
  1437. }
  1438. bool VulkanContext::_use_validation_layers() {
  1439. return Engine::get_singleton()->is_validation_layers_enabled();
  1440. }
  1441. VkExtent2D VulkanContext::_compute_swapchain_extent(const VkSurfaceCapabilitiesKHR &p_surf_capabilities, int *p_window_width, int *p_window_height) const {
  1442. // Width and height are either both 0xFFFFFFFF, or both not 0xFFFFFFFF.
  1443. if (p_surf_capabilities.currentExtent.width == 0xFFFFFFFF) {
  1444. // If the surface size is undefined, the size is set to the size
  1445. // of the images requested, which must fit within the minimum and
  1446. // maximum values.
  1447. VkExtent2D extent = {};
  1448. extent.width = CLAMP((uint32_t)(*p_window_width), p_surf_capabilities.minImageExtent.width, p_surf_capabilities.maxImageExtent.width);
  1449. extent.height = CLAMP((uint32_t)(*p_window_height), p_surf_capabilities.minImageExtent.height, p_surf_capabilities.maxImageExtent.height);
  1450. return extent;
  1451. } else {
  1452. // If the surface size is defined, the swap chain size must match.
  1453. *p_window_width = p_surf_capabilities.currentExtent.width;
  1454. *p_window_height = p_surf_capabilities.currentExtent.height;
  1455. return p_surf_capabilities.currentExtent;
  1456. }
  1457. }
  1458. Error VulkanContext::_window_create(DisplayServer::WindowID p_window_id, DisplayServer::VSyncMode p_vsync_mode, VkSurfaceKHR p_surface, int p_width, int p_height) {
  1459. ERR_FAIL_COND_V(windows.has(p_window_id), ERR_INVALID_PARAMETER);
  1460. if (!device_initialized) {
  1461. Error err = _create_physical_device(p_surface);
  1462. ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
  1463. }
  1464. if (!queues_initialized) {
  1465. // We use a single GPU, but we need a surface to initialize the
  1466. // queues, so this process must be deferred until a surface
  1467. // is created.
  1468. Error err = _initialize_queues(p_surface);
  1469. ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
  1470. }
  1471. Window window;
  1472. window.surface = p_surface;
  1473. window.width = p_width;
  1474. window.height = p_height;
  1475. window.vsync_mode = p_vsync_mode;
  1476. Error err = _update_swap_chain(&window);
  1477. ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
  1478. VkSemaphoreCreateInfo semaphoreCreateInfo = {
  1479. /*sType*/ VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
  1480. /*pNext*/ nullptr,
  1481. /*flags*/ 0,
  1482. };
  1483. for (uint32_t i = 0; i < FRAME_LAG; i++) {
  1484. VkResult vkerr = vkCreateSemaphore(device, &semaphoreCreateInfo, nullptr, &window.image_acquired_semaphores[i]);
  1485. ERR_FAIL_COND_V(vkerr, ERR_CANT_CREATE);
  1486. }
  1487. windows[p_window_id] = window;
  1488. return OK;
  1489. }
  1490. void VulkanContext::window_resize(DisplayServer::WindowID p_window, int p_width, int p_height) {
  1491. ERR_FAIL_COND(!windows.has(p_window));
  1492. windows[p_window].width = p_width;
  1493. windows[p_window].height = p_height;
  1494. _update_swap_chain(&windows[p_window]);
  1495. }
  1496. int VulkanContext::window_get_width(DisplayServer::WindowID p_window) {
  1497. ERR_FAIL_COND_V(!windows.has(p_window), -1);
  1498. return windows[p_window].width;
  1499. }
  1500. int VulkanContext::window_get_height(DisplayServer::WindowID p_window) {
  1501. ERR_FAIL_COND_V(!windows.has(p_window), -1);
  1502. return windows[p_window].height;
  1503. }
  1504. bool VulkanContext::window_is_valid_swapchain(DisplayServer::WindowID p_window) {
  1505. ERR_FAIL_COND_V(!windows.has(p_window), false);
  1506. Window *w = &windows[p_window];
  1507. return w->swapchain_image_resources != VK_NULL_HANDLE;
  1508. }
  1509. VkRenderPass VulkanContext::window_get_render_pass(DisplayServer::WindowID p_window) {
  1510. ERR_FAIL_COND_V(!windows.has(p_window), VK_NULL_HANDLE);
  1511. Window *w = &windows[p_window];
  1512. // Vulkan use of currentbuffer.
  1513. return w->render_pass;
  1514. }
  1515. VkFramebuffer VulkanContext::window_get_framebuffer(DisplayServer::WindowID p_window) {
  1516. ERR_FAIL_COND_V(!windows.has(p_window), VK_NULL_HANDLE);
  1517. ERR_FAIL_COND_V(!buffers_prepared, VK_NULL_HANDLE);
  1518. Window *w = &windows[p_window];
  1519. // Vulkan use of currentbuffer.
  1520. if (w->swapchain_image_resources != VK_NULL_HANDLE) {
  1521. return w->swapchain_image_resources[w->current_buffer].framebuffer;
  1522. } else {
  1523. return VK_NULL_HANDLE;
  1524. }
  1525. }
  1526. void VulkanContext::window_destroy(DisplayServer::WindowID p_window_id) {
  1527. ERR_FAIL_COND(!windows.has(p_window_id));
  1528. _clean_up_swap_chain(&windows[p_window_id]);
  1529. for (uint32_t i = 0; i < FRAME_LAG; i++) {
  1530. vkDestroySemaphore(device, windows[p_window_id].image_acquired_semaphores[i], nullptr);
  1531. }
  1532. vkDestroySurfaceKHR(inst, windows[p_window_id].surface, nullptr);
  1533. windows.erase(p_window_id);
  1534. }
  1535. Error VulkanContext::_clean_up_swap_chain(Window *window) {
  1536. if (!window->swapchain) {
  1537. return OK;
  1538. }
  1539. vkDeviceWaitIdle(device);
  1540. // This destroys images associated it seems.
  1541. fpDestroySwapchainKHR(device, window->swapchain, nullptr);
  1542. window->swapchain = VK_NULL_HANDLE;
  1543. vkDestroyRenderPass(device, window->render_pass, nullptr);
  1544. if (window->swapchain_image_resources) {
  1545. for (uint32_t i = 0; i < swapchainImageCount; i++) {
  1546. vkDestroyImageView(device, window->swapchain_image_resources[i].view, nullptr);
  1547. vkDestroyFramebuffer(device, window->swapchain_image_resources[i].framebuffer, nullptr);
  1548. }
  1549. free(window->swapchain_image_resources);
  1550. window->swapchain_image_resources = nullptr;
  1551. }
  1552. if (separate_present_queue) {
  1553. vkDestroyCommandPool(device, window->present_cmd_pool, nullptr);
  1554. }
  1555. return OK;
  1556. }
  1557. Error VulkanContext::_update_swap_chain(Window *window) {
  1558. VkResult err;
  1559. if (window->swapchain) {
  1560. _clean_up_swap_chain(window);
  1561. }
  1562. // Check the surface capabilities and formats.
  1563. VkSurfaceCapabilitiesKHR surfCapabilities;
  1564. err = fpGetPhysicalDeviceSurfaceCapabilitiesKHR(gpu, window->surface, &surfCapabilities);
  1565. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  1566. uint32_t presentModeCount;
  1567. err = fpGetPhysicalDeviceSurfacePresentModesKHR(gpu, window->surface, &presentModeCount, nullptr);
  1568. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  1569. VkPresentModeKHR *presentModes = (VkPresentModeKHR *)malloc(presentModeCount * sizeof(VkPresentModeKHR));
  1570. ERR_FAIL_COND_V(!presentModes, ERR_CANT_CREATE);
  1571. err = fpGetPhysicalDeviceSurfacePresentModesKHR(gpu, window->surface, &presentModeCount, presentModes);
  1572. if (err) {
  1573. free(presentModes);
  1574. ERR_FAIL_V(ERR_CANT_CREATE);
  1575. }
  1576. VkExtent2D swapchainExtent = _compute_swapchain_extent(surfCapabilities, &window->width, &window->height);
  1577. if (window->width == 0 || window->height == 0) {
  1578. free(presentModes);
  1579. // Likely window minimized, no swapchain created.
  1580. return OK;
  1581. }
  1582. // The FIFO present mode is guaranteed by the spec to be supported
  1583. // and to have no tearing. It's a great default present mode to use.
  1584. // There are times when you may wish to use another present mode. The
  1585. // following code shows how to select them, and the comments provide some
  1586. // reasons you may wish to use them.
  1587. //
  1588. // It should be noted that Vulkan 1.0 doesn't provide a method for
  1589. // synchronizing rendering with the presentation engine's display. There
  1590. // is a method provided for throttling rendering with the display, but
  1591. // there are some presentation engines for which this method will not work.
  1592. // If an application doesn't throttle its rendering, and if it renders much
  1593. // faster than the refresh rate of the display, this can waste power on
  1594. // mobile devices. That is because power is being spent rendering images
  1595. // that may never be seen.
  1596. // VK_PRESENT_MODE_IMMEDIATE_KHR is for applications that don't care about
  1597. // tearing, or have some way of synchronizing their rendering with the
  1598. // display.
  1599. // VK_PRESENT_MODE_MAILBOX_KHR may be useful for applications that
  1600. // generally render a new presentable image every refresh cycle, but are
  1601. // occasionally early. In this case, the application wants the new image
  1602. // to be displayed instead of the previously-queued-for-presentation image
  1603. // that has not yet been displayed.
  1604. // VK_PRESENT_MODE_FIFO_RELAXED_KHR is for applications that generally
  1605. // render a new presentable image every refresh cycle, but are occasionally
  1606. // late. In this case (perhaps because of stuttering/latency concerns),
  1607. // the application wants the late image to be immediately displayed, even
  1608. // though that may mean some tearing.
  1609. VkPresentModeKHR requested_present_mode = VkPresentModeKHR::VK_PRESENT_MODE_FIFO_KHR;
  1610. switch (window->vsync_mode) {
  1611. case DisplayServer::VSYNC_MAILBOX:
  1612. requested_present_mode = VkPresentModeKHR::VK_PRESENT_MODE_MAILBOX_KHR;
  1613. break;
  1614. case DisplayServer::VSYNC_ADAPTIVE:
  1615. requested_present_mode = VkPresentModeKHR::VK_PRESENT_MODE_FIFO_RELAXED_KHR;
  1616. break;
  1617. case DisplayServer::VSYNC_ENABLED:
  1618. requested_present_mode = VkPresentModeKHR::VK_PRESENT_MODE_FIFO_KHR;
  1619. break;
  1620. case DisplayServer::VSYNC_DISABLED:
  1621. requested_present_mode = VkPresentModeKHR::VK_PRESENT_MODE_IMMEDIATE_KHR;
  1622. break;
  1623. }
  1624. // Check if the requested mode is available.
  1625. bool present_mode_available = false;
  1626. for (uint32_t i = 0; i < presentModeCount; i++) {
  1627. if (presentModes[i] == requested_present_mode) {
  1628. present_mode_available = true;
  1629. }
  1630. }
  1631. // Set the windows present mode if it is available, otherwise FIFO is used (guaranteed supported).
  1632. if (present_mode_available) {
  1633. if (window->presentMode != requested_present_mode) {
  1634. window->presentMode = requested_present_mode;
  1635. print_verbose("Using present mode: " + String(string_VkPresentModeKHR(window->presentMode)));
  1636. }
  1637. } else {
  1638. String present_mode_string;
  1639. switch (window->vsync_mode) {
  1640. case DisplayServer::VSYNC_MAILBOX:
  1641. present_mode_string = "Mailbox";
  1642. break;
  1643. case DisplayServer::VSYNC_ADAPTIVE:
  1644. present_mode_string = "Adaptive";
  1645. break;
  1646. case DisplayServer::VSYNC_ENABLED:
  1647. present_mode_string = "Enabled";
  1648. break;
  1649. case DisplayServer::VSYNC_DISABLED:
  1650. present_mode_string = "Disabled";
  1651. break;
  1652. }
  1653. WARN_PRINT(vformat("The requested V-Sync mode %s is not available. Falling back to V-Sync mode Enabled.", present_mode_string));
  1654. window->vsync_mode = DisplayServer::VSYNC_ENABLED; // Set to default.
  1655. }
  1656. free(presentModes);
  1657. // Determine the number of VkImages to use in the swap chain.
  1658. // Application desires to acquire 3 images at a time for triple
  1659. // buffering.
  1660. uint32_t desiredNumOfSwapchainImages = 3;
  1661. if (desiredNumOfSwapchainImages < surfCapabilities.minImageCount) {
  1662. desiredNumOfSwapchainImages = surfCapabilities.minImageCount;
  1663. }
  1664. // If maxImageCount is 0, we can ask for as many images as we want;
  1665. // otherwise we're limited to maxImageCount.
  1666. if ((surfCapabilities.maxImageCount > 0) && (desiredNumOfSwapchainImages > surfCapabilities.maxImageCount)) {
  1667. // Application must settle for fewer images than desired.
  1668. desiredNumOfSwapchainImages = surfCapabilities.maxImageCount;
  1669. }
  1670. VkSurfaceTransformFlagsKHR preTransform;
  1671. if (surfCapabilities.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR) {
  1672. preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
  1673. } else {
  1674. preTransform = surfCapabilities.currentTransform;
  1675. }
  1676. VkCompositeAlphaFlagBitsKHR compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
  1677. if (OS::get_singleton()->is_layered_allowed() || !(surfCapabilities.supportedCompositeAlpha & compositeAlpha)) {
  1678. // Find a supported composite alpha mode - one of these is guaranteed to be set.
  1679. VkCompositeAlphaFlagBitsKHR compositeAlphaFlags[4] = {
  1680. VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR,
  1681. VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR,
  1682. VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR,
  1683. VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
  1684. };
  1685. for (uint32_t i = 0; i < ARRAY_SIZE(compositeAlphaFlags); i++) {
  1686. if (surfCapabilities.supportedCompositeAlpha & compositeAlphaFlags[i]) {
  1687. compositeAlpha = compositeAlphaFlags[i];
  1688. break;
  1689. }
  1690. }
  1691. }
  1692. VkSwapchainCreateInfoKHR swapchain_ci = {
  1693. /*sType*/ VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR,
  1694. /*pNext*/ nullptr,
  1695. /*flags*/ 0,
  1696. /*surface*/ window->surface,
  1697. /*minImageCount*/ desiredNumOfSwapchainImages,
  1698. /*imageFormat*/ format,
  1699. /*imageColorSpace*/ color_space,
  1700. /*imageExtent*/ {
  1701. /*width*/ swapchainExtent.width,
  1702. /*height*/ swapchainExtent.height,
  1703. },
  1704. /*imageArrayLayers*/ 1,
  1705. /*imageUsage*/ VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
  1706. /*imageSharingMode*/ VK_SHARING_MODE_EXCLUSIVE,
  1707. /*queueFamilyIndexCount*/ 0,
  1708. /*pQueueFamilyIndices*/ nullptr,
  1709. /*preTransform*/ (VkSurfaceTransformFlagBitsKHR)preTransform,
  1710. /*compositeAlpha*/ compositeAlpha,
  1711. /*presentMode*/ window->presentMode,
  1712. /*clipped*/ true,
  1713. /*oldSwapchain*/ VK_NULL_HANDLE,
  1714. };
  1715. err = fpCreateSwapchainKHR(device, &swapchain_ci, nullptr, &window->swapchain);
  1716. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  1717. uint32_t sp_image_count;
  1718. err = fpGetSwapchainImagesKHR(device, window->swapchain, &sp_image_count, nullptr);
  1719. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  1720. if (swapchainImageCount == 0) {
  1721. // Assign here for the first time.
  1722. swapchainImageCount = sp_image_count;
  1723. } else {
  1724. ERR_FAIL_COND_V(swapchainImageCount != sp_image_count, ERR_BUG);
  1725. }
  1726. VkImage *swapchainImages = (VkImage *)malloc(swapchainImageCount * sizeof(VkImage));
  1727. ERR_FAIL_COND_V(!swapchainImages, ERR_CANT_CREATE);
  1728. err = fpGetSwapchainImagesKHR(device, window->swapchain, &swapchainImageCount, swapchainImages);
  1729. if (err) {
  1730. free(swapchainImages);
  1731. ERR_FAIL_V(ERR_CANT_CREATE);
  1732. }
  1733. window->swapchain_image_resources =
  1734. (SwapchainImageResources *)malloc(sizeof(SwapchainImageResources) * swapchainImageCount);
  1735. if (!window->swapchain_image_resources) {
  1736. free(swapchainImages);
  1737. ERR_FAIL_V(ERR_CANT_CREATE);
  1738. }
  1739. for (uint32_t i = 0; i < swapchainImageCount; i++) {
  1740. VkImageViewCreateInfo color_image_view = {
  1741. /*sType*/ VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
  1742. /*pNext*/ nullptr,
  1743. /*flags*/ 0,
  1744. /*image*/ swapchainImages[i],
  1745. /*viewType*/ VK_IMAGE_VIEW_TYPE_2D,
  1746. /*format*/ format,
  1747. /*components*/ {
  1748. /*r*/ VK_COMPONENT_SWIZZLE_R,
  1749. /*g*/ VK_COMPONENT_SWIZZLE_G,
  1750. /*b*/ VK_COMPONENT_SWIZZLE_B,
  1751. /*a*/ VK_COMPONENT_SWIZZLE_A,
  1752. },
  1753. /*subresourceRange*/ { /*aspectMask*/ VK_IMAGE_ASPECT_COLOR_BIT,
  1754. /*baseMipLevel*/ 0,
  1755. /*levelCount*/ 1,
  1756. /*baseArrayLayer*/ 0,
  1757. /*layerCount*/ 1 },
  1758. };
  1759. window->swapchain_image_resources[i].image = swapchainImages[i];
  1760. color_image_view.image = window->swapchain_image_resources[i].image;
  1761. err = vkCreateImageView(device, &color_image_view, nullptr, &window->swapchain_image_resources[i].view);
  1762. if (err) {
  1763. free(swapchainImages);
  1764. ERR_FAIL_V(ERR_CANT_CREATE);
  1765. }
  1766. }
  1767. free(swapchainImages);
  1768. /******** FRAMEBUFFER ************/
  1769. {
  1770. const VkAttachmentDescription2KHR attachment = {
  1771. /*sType*/ VK_STRUCTURE_TYPE_ATTACHMENT_DESCRIPTION_2_KHR,
  1772. /*pNext*/ nullptr,
  1773. /*flags*/ 0,
  1774. /*format*/ format,
  1775. /*samples*/ VK_SAMPLE_COUNT_1_BIT,
  1776. /*loadOp*/ VK_ATTACHMENT_LOAD_OP_CLEAR,
  1777. /*storeOp*/ VK_ATTACHMENT_STORE_OP_STORE,
  1778. /*stencilLoadOp*/ VK_ATTACHMENT_LOAD_OP_DONT_CARE,
  1779. /*stencilStoreOp*/ VK_ATTACHMENT_STORE_OP_DONT_CARE,
  1780. /*initialLayout*/ VK_IMAGE_LAYOUT_UNDEFINED,
  1781. /*finalLayout*/ VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
  1782. };
  1783. const VkAttachmentReference2KHR color_reference = {
  1784. /*sType*/ VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2_KHR,
  1785. /*pNext*/ nullptr,
  1786. /*attachment*/ 0,
  1787. /*layout*/ VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
  1788. /*aspectMask*/ 0,
  1789. };
  1790. const VkSubpassDescription2KHR subpass = {
  1791. /*sType*/ VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_2_KHR,
  1792. /*pNext*/ nullptr,
  1793. /*flags*/ 0,
  1794. /*pipelineBindPoint*/ VK_PIPELINE_BIND_POINT_GRAPHICS,
  1795. /*viewMask*/ 0,
  1796. /*inputAttachmentCount*/ 0,
  1797. /*pInputAttachments*/ nullptr,
  1798. /*colorAttachmentCount*/ 1,
  1799. /*pColorAttachments*/ &color_reference,
  1800. /*pResolveAttachments*/ nullptr,
  1801. /*pDepthStencilAttachment*/ nullptr,
  1802. /*preserveAttachmentCount*/ 0,
  1803. /*pPreserveAttachments*/ nullptr,
  1804. };
  1805. const VkRenderPassCreateInfo2KHR rp_info = {
  1806. /*sType*/ VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO_2_KHR,
  1807. /*pNext*/ nullptr,
  1808. /*flags*/ 0,
  1809. /*attachmentCount*/ 1,
  1810. /*pAttachments*/ &attachment,
  1811. /*subpassCount*/ 1,
  1812. /*pSubpasses*/ &subpass,
  1813. /*dependencyCount*/ 0,
  1814. /*pDependencies*/ nullptr,
  1815. /*correlatedViewMaskCount*/ 0,
  1816. /*pCorrelatedViewMasks*/ nullptr,
  1817. };
  1818. err = vkCreateRenderPass2KHR(device, &rp_info, nullptr, &window->render_pass);
  1819. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  1820. for (uint32_t i = 0; i < swapchainImageCount; i++) {
  1821. const VkFramebufferCreateInfo fb_info = {
  1822. /*sType*/ VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO,
  1823. /*pNext*/ nullptr,
  1824. /*flags*/ 0,
  1825. /*renderPass*/ window->render_pass,
  1826. /*attachmentCount*/ 1,
  1827. /*pAttachments*/ &window->swapchain_image_resources[i].view,
  1828. /*width*/ (uint32_t)window->width,
  1829. /*height*/ (uint32_t)window->height,
  1830. /*layers*/ 1,
  1831. };
  1832. err = vkCreateFramebuffer(device, &fb_info, nullptr, &window->swapchain_image_resources[i].framebuffer);
  1833. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  1834. }
  1835. }
  1836. /******** SEPARATE PRESENT QUEUE ************/
  1837. if (separate_present_queue) {
  1838. const VkCommandPoolCreateInfo present_cmd_pool_info = {
  1839. /*sType*/ VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
  1840. /*pNext*/ nullptr,
  1841. /*flags*/ 0,
  1842. /*queueFamilyIndex*/ present_queue_family_index,
  1843. };
  1844. err = vkCreateCommandPool(device, &present_cmd_pool_info, nullptr, &window->present_cmd_pool);
  1845. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  1846. const VkCommandBufferAllocateInfo present_cmd_info = {
  1847. /*sType*/ VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
  1848. /*pNext*/ nullptr,
  1849. /*commandPool*/ window->present_cmd_pool,
  1850. /*level*/ VK_COMMAND_BUFFER_LEVEL_PRIMARY,
  1851. /*commandBufferCount*/ 1,
  1852. };
  1853. for (uint32_t i = 0; i < swapchainImageCount; i++) {
  1854. err = vkAllocateCommandBuffers(device, &present_cmd_info,
  1855. &window->swapchain_image_resources[i].graphics_to_present_cmd);
  1856. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  1857. const VkCommandBufferBeginInfo cmd_buf_info = {
  1858. /*sType*/ VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
  1859. /*pNext*/ nullptr,
  1860. /*flags*/ VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT,
  1861. /*pInheritanceInfo*/ nullptr,
  1862. };
  1863. err = vkBeginCommandBuffer(window->swapchain_image_resources[i].graphics_to_present_cmd, &cmd_buf_info);
  1864. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  1865. VkImageMemoryBarrier image_ownership_barrier = {
  1866. /*sType*/ VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
  1867. /*pNext*/ nullptr,
  1868. /*srcAccessMask*/ 0,
  1869. /*dstAccessMask*/ VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
  1870. /*oldLayout*/ VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
  1871. /*newLayout*/ VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
  1872. /*srcQueueFamilyIndex*/ graphics_queue_family_index,
  1873. /*dstQueueFamilyIndex*/ present_queue_family_index,
  1874. /*image*/ window->swapchain_image_resources[i].image,
  1875. /*subresourceRange*/ { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }
  1876. };
  1877. vkCmdPipelineBarrier(window->swapchain_image_resources[i].graphics_to_present_cmd, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
  1878. VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_ownership_barrier);
  1879. err = vkEndCommandBuffer(window->swapchain_image_resources[i].graphics_to_present_cmd);
  1880. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  1881. }
  1882. }
  1883. // Reset current buffer.
  1884. window->current_buffer = 0;
  1885. return OK;
  1886. }
  1887. Error VulkanContext::initialize() {
  1888. #ifdef USE_VOLK
  1889. if (volkInitialize() != VK_SUCCESS) {
  1890. return FAILED;
  1891. }
  1892. #endif
  1893. Error err = _create_instance();
  1894. if (err != OK) {
  1895. return err;
  1896. }
  1897. return OK;
  1898. }
  1899. void VulkanContext::set_setup_buffer(VkCommandBuffer p_command_buffer) {
  1900. command_buffer_queue.write[0] = p_command_buffer;
  1901. }
  1902. void VulkanContext::append_command_buffer(VkCommandBuffer p_command_buffer) {
  1903. if (command_buffer_queue.size() <= command_buffer_count) {
  1904. command_buffer_queue.resize(command_buffer_count + 1);
  1905. }
  1906. command_buffer_queue.write[command_buffer_count] = p_command_buffer;
  1907. command_buffer_count++;
  1908. }
  1909. void VulkanContext::flush(bool p_flush_setup, bool p_flush_pending) {
  1910. // Ensure everything else pending is executed.
  1911. vkDeviceWaitIdle(device);
  1912. // Flush the pending setup buffer.
  1913. bool setup_flushable = p_flush_setup && command_buffer_queue[0];
  1914. bool pending_flushable = p_flush_pending && command_buffer_count > 1;
  1915. if (setup_flushable) {
  1916. // Use a fence to wait for everything done.
  1917. VkSubmitInfo submit_info;
  1918. submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
  1919. submit_info.pNext = nullptr;
  1920. submit_info.pWaitDstStageMask = nullptr;
  1921. submit_info.waitSemaphoreCount = 0;
  1922. submit_info.pWaitSemaphores = nullptr;
  1923. submit_info.commandBufferCount = 1;
  1924. submit_info.pCommandBuffers = command_buffer_queue.ptr();
  1925. submit_info.signalSemaphoreCount = pending_flushable ? 1 : 0;
  1926. submit_info.pSignalSemaphores = pending_flushable ? &draw_complete_semaphores[frame_index] : nullptr;
  1927. VkResult err = vkQueueSubmit(graphics_queue, 1, &submit_info, VK_NULL_HANDLE);
  1928. command_buffer_queue.write[0] = nullptr;
  1929. ERR_FAIL_COND(err);
  1930. }
  1931. if (pending_flushable) {
  1932. // Use a fence to wait for everything to finish.
  1933. VkSubmitInfo submit_info;
  1934. submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
  1935. submit_info.pNext = nullptr;
  1936. VkPipelineStageFlags wait_stage_mask = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
  1937. submit_info.pWaitDstStageMask = setup_flushable ? &wait_stage_mask : nullptr;
  1938. submit_info.waitSemaphoreCount = setup_flushable ? 1 : 0;
  1939. submit_info.pWaitSemaphores = setup_flushable ? &draw_complete_semaphores[frame_index] : nullptr;
  1940. submit_info.commandBufferCount = command_buffer_count - 1;
  1941. submit_info.pCommandBuffers = command_buffer_queue.ptr() + 1;
  1942. submit_info.signalSemaphoreCount = 0;
  1943. submit_info.pSignalSemaphores = nullptr;
  1944. VkResult err = vkQueueSubmit(graphics_queue, 1, &submit_info, VK_NULL_HANDLE);
  1945. command_buffer_count = 1;
  1946. ERR_FAIL_COND(err);
  1947. }
  1948. vkDeviceWaitIdle(device);
  1949. }
  1950. Error VulkanContext::prepare_buffers() {
  1951. if (!queues_initialized) {
  1952. return OK;
  1953. }
  1954. VkResult err;
  1955. // Ensure no more than FRAME_LAG renderings are outstanding.
  1956. vkWaitForFences(device, 1, &fences[frame_index], VK_TRUE, UINT64_MAX);
  1957. vkResetFences(device, 1, &fences[frame_index]);
  1958. for (KeyValue<int, Window> &E : windows) {
  1959. Window *w = &E.value;
  1960. w->semaphore_acquired = false;
  1961. if (w->swapchain == VK_NULL_HANDLE) {
  1962. continue;
  1963. }
  1964. do {
  1965. // Get the index of the next available swapchain image.
  1966. err =
  1967. fpAcquireNextImageKHR(device, w->swapchain, UINT64_MAX,
  1968. w->image_acquired_semaphores[frame_index], VK_NULL_HANDLE, &w->current_buffer);
  1969. if (err == VK_ERROR_OUT_OF_DATE_KHR) {
  1970. // Swapchain is out of date (e.g. the window was resized) and
  1971. // must be recreated.
  1972. print_verbose("Vulkan: Early out of date swapchain, recreating.");
  1973. // resize_notify();
  1974. _update_swap_chain(w);
  1975. } else if (err == VK_SUBOPTIMAL_KHR) {
  1976. // Swapchain is not as optimal as it could be, but the platform's
  1977. // presentation engine will still present the image correctly.
  1978. print_verbose("Vulkan: Early suboptimal swapchain.");
  1979. break;
  1980. } else if (err != VK_SUCCESS) {
  1981. ERR_BREAK_MSG(err != VK_SUCCESS, "Vulkan: Did not create swapchain successfully. Error code: " + String(string_VkResult(err)));
  1982. } else {
  1983. w->semaphore_acquired = true;
  1984. }
  1985. } while (err != VK_SUCCESS);
  1986. }
  1987. buffers_prepared = true;
  1988. return OK;
  1989. }
  1990. Error VulkanContext::swap_buffers() {
  1991. if (!queues_initialized) {
  1992. return OK;
  1993. }
  1994. // print_line("swapbuffers?");
  1995. VkResult err;
  1996. #if 0
  1997. if (is_device_extension_enabled(VK_GOOGLE_DISPLAY_TIMING_EXTENSION_NAME)) {
  1998. // Look at what happened to previous presents, and make appropriate
  1999. // adjustments in timing.
  2000. DemoUpdateTargetIPD(demo);
  2001. // Note: a real application would position its geometry to that it's in
  2002. // the correct location for when the next image is presented. It might
  2003. // also wait, so that there's less latency between any input and when
  2004. // the next image is rendered/presented. This demo program is so
  2005. // simple that it doesn't do either of those.
  2006. }
  2007. #endif
  2008. // Wait for the image acquired semaphore to be signaled to ensure
  2009. // that the image won't be rendered to until the presentation
  2010. // engine has fully released ownership to the application, and it is
  2011. // okay to render to the image.
  2012. const VkCommandBuffer *commands_ptr = nullptr;
  2013. uint32_t commands_to_submit = 0;
  2014. if (command_buffer_queue[0] == nullptr) {
  2015. // No setup command, but commands to submit, submit from the first and skip command.
  2016. if (command_buffer_count > 1) {
  2017. commands_ptr = command_buffer_queue.ptr() + 1;
  2018. commands_to_submit = command_buffer_count - 1;
  2019. }
  2020. } else {
  2021. commands_ptr = command_buffer_queue.ptr();
  2022. commands_to_submit = command_buffer_count;
  2023. }
  2024. VkSemaphore *semaphores_to_acquire = (VkSemaphore *)alloca(windows.size() * sizeof(VkSemaphore));
  2025. VkPipelineStageFlags *pipe_stage_flags = (VkPipelineStageFlags *)alloca(windows.size() * sizeof(VkPipelineStageFlags));
  2026. uint32_t semaphores_to_acquire_count = 0;
  2027. for (KeyValue<int, Window> &E : windows) {
  2028. Window *w = &E.value;
  2029. if (w->semaphore_acquired) {
  2030. semaphores_to_acquire[semaphores_to_acquire_count] = w->image_acquired_semaphores[frame_index];
  2031. pipe_stage_flags[semaphores_to_acquire_count] = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
  2032. semaphores_to_acquire_count++;
  2033. }
  2034. }
  2035. VkSubmitInfo submit_info;
  2036. submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
  2037. submit_info.pNext = nullptr;
  2038. submit_info.waitSemaphoreCount = semaphores_to_acquire_count;
  2039. submit_info.pWaitSemaphores = semaphores_to_acquire;
  2040. submit_info.pWaitDstStageMask = pipe_stage_flags;
  2041. submit_info.commandBufferCount = commands_to_submit;
  2042. submit_info.pCommandBuffers = commands_ptr;
  2043. submit_info.signalSemaphoreCount = 1;
  2044. submit_info.pSignalSemaphores = &draw_complete_semaphores[frame_index];
  2045. err = vkQueueSubmit(graphics_queue, 1, &submit_info, fences[frame_index]);
  2046. ERR_FAIL_COND_V_MSG(err, ERR_CANT_CREATE, "Vulkan: Cannot submit graphics queue. Error code: " + String(string_VkResult(err)));
  2047. command_buffer_queue.write[0] = nullptr;
  2048. command_buffer_count = 1;
  2049. if (separate_present_queue) {
  2050. // If we are using separate queues, change image ownership to the
  2051. // present queue before presenting, waiting for the draw complete
  2052. // semaphore and signaling the ownership released semaphore when finished.
  2053. VkFence nullFence = VK_NULL_HANDLE;
  2054. pipe_stage_flags[0] = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
  2055. submit_info.waitSemaphoreCount = 1;
  2056. submit_info.pWaitSemaphores = &draw_complete_semaphores[frame_index];
  2057. submit_info.commandBufferCount = 0;
  2058. VkCommandBuffer *cmdbufptr = (VkCommandBuffer *)alloca(sizeof(VkCommandBuffer *) * windows.size());
  2059. submit_info.pCommandBuffers = cmdbufptr;
  2060. for (KeyValue<int, Window> &E : windows) {
  2061. Window *w = &E.value;
  2062. if (w->swapchain == VK_NULL_HANDLE) {
  2063. continue;
  2064. }
  2065. cmdbufptr[submit_info.commandBufferCount] = w->swapchain_image_resources[w->current_buffer].graphics_to_present_cmd;
  2066. submit_info.commandBufferCount++;
  2067. }
  2068. submit_info.signalSemaphoreCount = 1;
  2069. submit_info.pSignalSemaphores = &image_ownership_semaphores[frame_index];
  2070. err = vkQueueSubmit(present_queue, 1, &submit_info, nullFence);
  2071. ERR_FAIL_COND_V_MSG(err, ERR_CANT_CREATE, "Vulkan: Cannot submit present queue. Error code: " + String(string_VkResult(err)));
  2072. }
  2073. // If we are using separate queues, we have to wait for image ownership,
  2074. // otherwise wait for draw complete.
  2075. VkPresentInfoKHR present = {
  2076. /*sType*/ VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
  2077. /*pNext*/ nullptr,
  2078. /*waitSemaphoreCount*/ 1,
  2079. /*pWaitSemaphores*/ (separate_present_queue) ? &image_ownership_semaphores[frame_index] : &draw_complete_semaphores[frame_index],
  2080. /*swapchainCount*/ 0,
  2081. /*pSwapchain*/ nullptr,
  2082. /*pImageIndices*/ nullptr,
  2083. /*pResults*/ nullptr,
  2084. };
  2085. VkSwapchainKHR *pSwapchains = (VkSwapchainKHR *)alloca(sizeof(VkSwapchainKHR *) * windows.size());
  2086. uint32_t *pImageIndices = (uint32_t *)alloca(sizeof(uint32_t *) * windows.size());
  2087. present.pSwapchains = pSwapchains;
  2088. present.pImageIndices = pImageIndices;
  2089. for (KeyValue<int, Window> &E : windows) {
  2090. Window *w = &E.value;
  2091. if (w->swapchain == VK_NULL_HANDLE) {
  2092. continue;
  2093. }
  2094. pSwapchains[present.swapchainCount] = w->swapchain;
  2095. pImageIndices[present.swapchainCount] = w->current_buffer;
  2096. present.swapchainCount++;
  2097. }
  2098. #if 0
  2099. if (is_device_extension_enabled(VK_KHR_incremental_present_enabled)) {
  2100. // If using VK_KHR_incremental_present, we provide a hint of the region
  2101. // that contains changed content relative to the previously-presented
  2102. // image. The implementation can use this hint in order to save
  2103. // work/power (by only copying the region in the hint). The
  2104. // implementation is free to ignore the hint though, and so we must
  2105. // ensure that the entire image has the correctly-drawn content.
  2106. uint32_t eighthOfWidth = width / 8;
  2107. uint32_t eighthOfHeight = height / 8;
  2108. VkRectLayerKHR rect = {
  2109. /*offset.x*/ eighthOfWidth,
  2110. /*offset.y*/ eighthOfHeight,
  2111. /*extent.width*/ eighthOfWidth * 6,
  2112. /*extent.height*/ eighthOfHeight * 6,
  2113. /*layer*/ 0,
  2114. };
  2115. VkPresentRegionKHR region = {
  2116. /*rectangleCount*/ 1,
  2117. /*pRectangles*/ &rect,
  2118. };
  2119. VkPresentRegionsKHR regions = {
  2120. /*sType*/ VK_STRUCTURE_TYPE_PRESENT_REGIONS_KHR,
  2121. /*pNext*/ present.pNext,
  2122. /*swapchainCount*/ present.swapchainCount,
  2123. /*pRegions*/ &region,
  2124. };
  2125. present.pNext = &regions;
  2126. }
  2127. #endif
  2128. #if 0
  2129. if (is_device_extension_enabled(VK_GOOGLE_DISPLAY_TIMING_EXTENSION_NAME)) {
  2130. VkPresentTimeGOOGLE ptime;
  2131. if (prev_desired_present_time == 0) {
  2132. // This must be the first present for this swapchain.
  2133. //
  2134. // We don't know where we are relative to the presentation engine's
  2135. // display's refresh cycle. We also don't know how long rendering
  2136. // takes. Let's make a grossly-simplified assumption that the
  2137. // desiredPresentTime should be half way between now and
  2138. // now+target_IPD. We will adjust over time.
  2139. uint64_t curtime = getTimeInNanoseconds();
  2140. if (curtime == 0) {
  2141. // Since we didn't find out the current time, don't give a
  2142. // desiredPresentTime.
  2143. ptime.desiredPresentTime = 0;
  2144. } else {
  2145. ptime.desiredPresentTime = curtime + (target_IPD >> 1);
  2146. }
  2147. } else {
  2148. ptime.desiredPresentTime = (prev_desired_present_time + target_IPD);
  2149. }
  2150. ptime.presentID = next_present_id++;
  2151. prev_desired_present_time = ptime.desiredPresentTime;
  2152. VkPresentTimesInfoGOOGLE present_time = {
  2153. /*sType*/ VK_STRUCTURE_TYPE_PRESENT_TIMES_INFO_GOOGLE,
  2154. /*pNext*/ present.pNext,
  2155. /*swapchainCount*/ present.swapchainCount,
  2156. /*pTimes*/ &ptime,
  2157. };
  2158. if (is_device_extension_enabled(VK_GOOGLE_DISPLAY_TIMING_EXTENSION_NAME)) {
  2159. present.pNext = &present_time;
  2160. }
  2161. }
  2162. #endif
  2163. // print_line("current buffer: " + itos(current_buffer));
  2164. err = fpQueuePresentKHR(present_queue, &present);
  2165. frame_index += 1;
  2166. frame_index %= FRAME_LAG;
  2167. if (err == VK_ERROR_OUT_OF_DATE_KHR) {
  2168. // Swapchain is out of date (e.g. the window was resized) and
  2169. // must be recreated.
  2170. print_verbose("Vulkan queue submit: Swapchain is out of date, recreating.");
  2171. resize_notify();
  2172. } else if (err == VK_SUBOPTIMAL_KHR) {
  2173. // Swapchain is not as optimal as it could be, but the platform's
  2174. // presentation engine will still present the image correctly.
  2175. print_verbose("Vulkan queue submit: Swapchain is suboptimal.");
  2176. } else {
  2177. ERR_FAIL_COND_V_MSG(err, ERR_CANT_CREATE, "Error code: " + String(string_VkResult(err)));
  2178. }
  2179. buffers_prepared = false;
  2180. return OK;
  2181. }
  2182. void VulkanContext::resize_notify() {
  2183. }
  2184. VkDevice VulkanContext::get_device() {
  2185. return device;
  2186. }
  2187. VkPhysicalDevice VulkanContext::get_physical_device() {
  2188. return gpu;
  2189. }
  2190. int VulkanContext::get_swapchain_image_count() const {
  2191. return swapchainImageCount;
  2192. }
  2193. VkQueue VulkanContext::get_graphics_queue() const {
  2194. return graphics_queue;
  2195. }
  2196. uint32_t VulkanContext::get_graphics_queue_family_index() const {
  2197. return graphics_queue_family_index;
  2198. }
  2199. VkFormat VulkanContext::get_screen_format() const {
  2200. return format;
  2201. }
  2202. VkPhysicalDeviceLimits VulkanContext::get_device_limits() const {
  2203. return gpu_props.limits;
  2204. }
  2205. RID VulkanContext::local_device_create() {
  2206. LocalDevice ld;
  2207. { // Create device.
  2208. VkResult err;
  2209. float queue_priorities[1] = { 0.0 };
  2210. VkDeviceQueueCreateInfo queues[2];
  2211. queues[0].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
  2212. queues[0].pNext = nullptr;
  2213. queues[0].queueFamilyIndex = graphics_queue_family_index;
  2214. queues[0].queueCount = 1;
  2215. queues[0].pQueuePriorities = queue_priorities;
  2216. queues[0].flags = 0;
  2217. uint32_t enabled_extension_count = 0;
  2218. const char *enabled_extension_names[MAX_EXTENSIONS];
  2219. ERR_FAIL_COND_V(enabled_device_extension_names.size() > MAX_EXTENSIONS, RID());
  2220. for (const CharString &extension_name : enabled_device_extension_names) {
  2221. enabled_extension_names[enabled_extension_count++] = extension_name.ptr();
  2222. }
  2223. VkDeviceCreateInfo sdevice = {
  2224. /*sType =*/VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
  2225. /*pNext */ nullptr,
  2226. /*flags */ 0,
  2227. /*queueCreateInfoCount */ 1,
  2228. /*pQueueCreateInfos */ queues,
  2229. /*enabledLayerCount */ 0,
  2230. /*ppEnabledLayerNames */ nullptr,
  2231. /*enabledExtensionCount */ enabled_extension_count,
  2232. /*ppEnabledExtensionNames */ (const char *const *)enabled_extension_names,
  2233. /*pEnabledFeatures */ &physical_device_features, // If specific features are required, pass them in here.
  2234. };
  2235. err = vkCreateDevice(gpu, &sdevice, nullptr, &ld.device);
  2236. ERR_FAIL_COND_V(err, RID());
  2237. }
  2238. { // Create graphics queue.
  2239. vkGetDeviceQueue(ld.device, graphics_queue_family_index, 0, &ld.queue);
  2240. }
  2241. return local_device_owner.make_rid(ld);
  2242. }
  2243. VkDevice VulkanContext::local_device_get_vk_device(RID p_local_device) {
  2244. LocalDevice *ld = local_device_owner.get_or_null(p_local_device);
  2245. return ld->device;
  2246. }
  2247. void VulkanContext::local_device_push_command_buffers(RID p_local_device, const VkCommandBuffer *p_buffers, int p_count) {
  2248. LocalDevice *ld = local_device_owner.get_or_null(p_local_device);
  2249. ERR_FAIL_COND(ld->waiting);
  2250. VkSubmitInfo submit_info;
  2251. submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
  2252. submit_info.pNext = nullptr;
  2253. submit_info.pWaitDstStageMask = nullptr;
  2254. submit_info.waitSemaphoreCount = 0;
  2255. submit_info.pWaitSemaphores = nullptr;
  2256. submit_info.commandBufferCount = p_count;
  2257. submit_info.pCommandBuffers = p_buffers;
  2258. submit_info.signalSemaphoreCount = 0;
  2259. submit_info.pSignalSemaphores = nullptr;
  2260. VkResult err = vkQueueSubmit(ld->queue, 1, &submit_info, VK_NULL_HANDLE);
  2261. if (err == VK_ERROR_OUT_OF_HOST_MEMORY) {
  2262. print_line("Vulkan: Out of host memory!");
  2263. }
  2264. if (err == VK_ERROR_OUT_OF_DEVICE_MEMORY) {
  2265. print_line("Vulkan: Out of device memory!");
  2266. }
  2267. if (err == VK_ERROR_DEVICE_LOST) {
  2268. print_line("Vulkan: Device lost!");
  2269. }
  2270. ERR_FAIL_COND(err);
  2271. ld->waiting = true;
  2272. }
  2273. void VulkanContext::local_device_sync(RID p_local_device) {
  2274. LocalDevice *ld = local_device_owner.get_or_null(p_local_device);
  2275. ERR_FAIL_COND(!ld->waiting);
  2276. vkDeviceWaitIdle(ld->device);
  2277. ld->waiting = false;
  2278. }
  2279. void VulkanContext::local_device_free(RID p_local_device) {
  2280. LocalDevice *ld = local_device_owner.get_or_null(p_local_device);
  2281. vkDestroyDevice(ld->device, nullptr);
  2282. local_device_owner.free(p_local_device);
  2283. }
  2284. void VulkanContext::command_begin_label(VkCommandBuffer p_command_buffer, String p_label_name, const Color p_color) {
  2285. if (!is_instance_extension_enabled(VK_EXT_DEBUG_UTILS_EXTENSION_NAME)) {
  2286. return;
  2287. }
  2288. CharString cs = p_label_name.utf8();
  2289. VkDebugUtilsLabelEXT label;
  2290. label.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT;
  2291. label.pNext = nullptr;
  2292. label.pLabelName = cs.get_data();
  2293. label.color[0] = p_color[0];
  2294. label.color[1] = p_color[1];
  2295. label.color[2] = p_color[2];
  2296. label.color[3] = p_color[3];
  2297. CmdBeginDebugUtilsLabelEXT(p_command_buffer, &label);
  2298. }
  2299. void VulkanContext::command_insert_label(VkCommandBuffer p_command_buffer, String p_label_name, const Color p_color) {
  2300. if (!is_instance_extension_enabled(VK_EXT_DEBUG_UTILS_EXTENSION_NAME)) {
  2301. return;
  2302. }
  2303. CharString cs = p_label_name.utf8();
  2304. VkDebugUtilsLabelEXT label;
  2305. label.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT;
  2306. label.pNext = nullptr;
  2307. label.pLabelName = cs.get_data();
  2308. label.color[0] = p_color[0];
  2309. label.color[1] = p_color[1];
  2310. label.color[2] = p_color[2];
  2311. label.color[3] = p_color[3];
  2312. CmdInsertDebugUtilsLabelEXT(p_command_buffer, &label);
  2313. }
  2314. void VulkanContext::command_end_label(VkCommandBuffer p_command_buffer) {
  2315. if (!is_instance_extension_enabled(VK_EXT_DEBUG_UTILS_EXTENSION_NAME)) {
  2316. return;
  2317. }
  2318. CmdEndDebugUtilsLabelEXT(p_command_buffer);
  2319. }
  2320. void VulkanContext::set_object_name(VkObjectType p_object_type, uint64_t p_object_handle, String p_object_name) {
  2321. if (!is_instance_extension_enabled(VK_EXT_DEBUG_UTILS_EXTENSION_NAME)) {
  2322. return;
  2323. }
  2324. CharString obj_data = p_object_name.utf8();
  2325. VkDebugUtilsObjectNameInfoEXT name_info;
  2326. name_info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT;
  2327. name_info.pNext = nullptr;
  2328. name_info.objectType = p_object_type;
  2329. name_info.objectHandle = p_object_handle;
  2330. name_info.pObjectName = obj_data.get_data();
  2331. SetDebugUtilsObjectNameEXT(device, &name_info);
  2332. }
  2333. String VulkanContext::get_device_vendor_name() const {
  2334. return device_vendor;
  2335. }
  2336. String VulkanContext::get_device_name() const {
  2337. return device_name;
  2338. }
  2339. RenderingDevice::DeviceType VulkanContext::get_device_type() const {
  2340. return RenderingDevice::DeviceType(device_type);
  2341. }
  2342. String VulkanContext::get_device_api_version() const {
  2343. return vformat("%d.%d.%d", VK_API_VERSION_MAJOR(device_api_version), VK_API_VERSION_MINOR(device_api_version), VK_API_VERSION_PATCH(device_api_version));
  2344. }
  2345. String VulkanContext::get_device_pipeline_cache_uuid() const {
  2346. return pipeline_cache_id;
  2347. }
  2348. DisplayServer::VSyncMode VulkanContext::get_vsync_mode(DisplayServer::WindowID p_window) const {
  2349. ERR_FAIL_COND_V_MSG(!windows.has(p_window), DisplayServer::VSYNC_ENABLED, "Could not get V-Sync mode for window with WindowID " + itos(p_window) + " because it does not exist.");
  2350. return windows[p_window].vsync_mode;
  2351. }
  2352. void VulkanContext::set_vsync_mode(DisplayServer::WindowID p_window, DisplayServer::VSyncMode p_mode) {
  2353. ERR_FAIL_COND_MSG(!windows.has(p_window), "Could not set V-Sync mode for window with WindowID " + itos(p_window) + " because it does not exist.");
  2354. windows[p_window].vsync_mode = p_mode;
  2355. _update_swap_chain(&windows[p_window]);
  2356. }
  2357. VulkanContext::VulkanContext() {
  2358. command_buffer_queue.resize(1); // First one is always the setup command.
  2359. command_buffer_queue.write[0] = nullptr;
  2360. }
  2361. VulkanContext::~VulkanContext() {
  2362. if (queue_props) {
  2363. free(queue_props);
  2364. }
  2365. if (device_initialized) {
  2366. for (uint32_t i = 0; i < FRAME_LAG; i++) {
  2367. vkDestroyFence(device, fences[i], nullptr);
  2368. vkDestroySemaphore(device, draw_complete_semaphores[i], nullptr);
  2369. if (separate_present_queue) {
  2370. vkDestroySemaphore(device, image_ownership_semaphores[i], nullptr);
  2371. }
  2372. }
  2373. if (inst_initialized && is_instance_extension_enabled(VK_EXT_DEBUG_UTILS_EXTENSION_NAME)) {
  2374. DestroyDebugUtilsMessengerEXT(inst, dbg_messenger, nullptr);
  2375. }
  2376. if (inst_initialized && dbg_debug_report != VK_NULL_HANDLE) {
  2377. DestroyDebugReportCallbackEXT(inst, dbg_debug_report, nullptr);
  2378. }
  2379. vkDestroyDevice(device, nullptr);
  2380. }
  2381. if (inst_initialized) {
  2382. vkDestroyInstance(inst, nullptr);
  2383. }
  2384. }