vulkan_context.cpp 102 KB

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