vulkan_context.cpp 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606
  1. /*************************************************************************/
  2. /* vulkan_context.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 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/engine.h"
  32. #include "core/project_settings.h"
  33. #include "core/ustring.h"
  34. #include "core/version.h"
  35. #include "vk_enum_string_helper.h"
  36. #include <stdio.h>
  37. #include <stdlib.h>
  38. #include <string.h>
  39. #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
  40. #define APP_SHORT_NAME "GodotEngine"
  41. VKAPI_ATTR VkBool32 VKAPI_CALL VulkanContext::_debug_messenger_callback(
  42. VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
  43. VkDebugUtilsMessageTypeFlagsEXT messageType,
  44. const VkDebugUtilsMessengerCallbackDataEXT *pCallbackData,
  45. void *pUserData) {
  46. // This error needs to be ignored because the AMD allocator will mix up memory types on IGP processors.
  47. if (strstr(pCallbackData->pMessage, "Mapping an image with layout") != nullptr &&
  48. strstr(pCallbackData->pMessage, "can result in undefined behavior if this memory is used by the device") != nullptr) {
  49. return VK_FALSE;
  50. }
  51. // This needs to be ignored because Validator is wrong here.
  52. if (strstr(pCallbackData->pMessage, "SPIR-V module not valid: Pointer operand") != nullptr &&
  53. strstr(pCallbackData->pMessage, "must be a memory object") != nullptr) {
  54. return VK_FALSE;
  55. }
  56. // Workaround for Vulkan-Loader usability bug: https://github.com/KhronosGroup/Vulkan-Loader/issues/262.
  57. if (strstr(pCallbackData->pMessage, "wrong ELF class: ELFCLASS32") != nullptr) {
  58. return VK_FALSE;
  59. }
  60. if (pCallbackData->pMessageIdName && strstr(pCallbackData->pMessageIdName, "UNASSIGNED-CoreValidation-DrawState-ClearCmdBeforeDraw") != nullptr) {
  61. return VK_FALSE;
  62. }
  63. String type_string;
  64. switch (messageType) {
  65. case (VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT):
  66. type_string = "GENERAL";
  67. break;
  68. case (VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT):
  69. type_string = "VALIDATION";
  70. break;
  71. case (VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT):
  72. type_string = "PERFORMANCE";
  73. break;
  74. case (VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT & VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT):
  75. type_string = "VALIDATION|PERFORMANCE";
  76. break;
  77. }
  78. String objects_string;
  79. if (pCallbackData->objectCount > 0) {
  80. objects_string = "\n\tObjects - " + String::num_int64(pCallbackData->objectCount);
  81. for (uint32_t object = 0; object < pCallbackData->objectCount; ++object) {
  82. objects_string +=
  83. "\n\t\tObject[" + String::num_int64(object) + "]" +
  84. " - " + string_VkObjectType(pCallbackData->pObjects[object].objectType) +
  85. ", Handle " + String::num_int64(pCallbackData->pObjects[object].objectHandle);
  86. if (nullptr != pCallbackData->pObjects[object].pObjectName && strlen(pCallbackData->pObjects[object].pObjectName) > 0) {
  87. objects_string += ", Name \"" + String(pCallbackData->pObjects[object].pObjectName) + "\"";
  88. }
  89. }
  90. }
  91. String labels_string;
  92. if (pCallbackData->cmdBufLabelCount > 0) {
  93. labels_string = "\n\tCommand Buffer Labels - " + String::num_int64(pCallbackData->cmdBufLabelCount);
  94. for (uint32_t cmd_buf_label = 0; cmd_buf_label < pCallbackData->cmdBufLabelCount; ++cmd_buf_label) {
  95. labels_string +=
  96. "\n\t\tLabel[" + String::num_int64(cmd_buf_label) + "]" +
  97. " - " + pCallbackData->pCmdBufLabels[cmd_buf_label].pLabelName +
  98. "{ ";
  99. for (int color_idx = 0; color_idx < 4; ++color_idx) {
  100. labels_string += String::num(pCallbackData->pCmdBufLabels[cmd_buf_label].color[color_idx]);
  101. if (color_idx < 3) {
  102. labels_string += ", ";
  103. }
  104. }
  105. labels_string += " }";
  106. }
  107. }
  108. String error_message(type_string +
  109. " - Message Id Number: " + String::num_int64(pCallbackData->messageIdNumber) +
  110. " | Message Id Name: " + pCallbackData->pMessageIdName +
  111. "\n\t" + pCallbackData->pMessage +
  112. objects_string + labels_string);
  113. // Convert VK severity to our own log macros.
  114. switch (messageSeverity) {
  115. case VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT:
  116. print_verbose(error_message);
  117. break;
  118. case VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT:
  119. print_line(error_message);
  120. break;
  121. case VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT:
  122. WARN_PRINT(error_message);
  123. break;
  124. case VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT:
  125. ERR_PRINT(error_message);
  126. CRASH_COND_MSG(Engine::get_singleton()->is_abort_on_gpu_errors_enabled(),
  127. "Crashing, because abort on GPU errors is enabled.");
  128. break;
  129. case VK_DEBUG_UTILS_MESSAGE_SEVERITY_FLAG_BITS_MAX_ENUM_EXT:
  130. break; // Shouldn't happen, only handling to make compilers happy.
  131. }
  132. return VK_FALSE;
  133. }
  134. VkBool32 VulkanContext::_check_layers(uint32_t check_count, const char **check_names, uint32_t layer_count, VkLayerProperties *layers) {
  135. for (uint32_t i = 0; i < check_count; i++) {
  136. VkBool32 found = 0;
  137. for (uint32_t j = 0; j < layer_count; j++) {
  138. if (!strcmp(check_names[i], layers[j].layerName)) {
  139. found = 1;
  140. break;
  141. }
  142. }
  143. if (!found) {
  144. ERR_PRINT("Cant find layer: " + String(check_names[i]));
  145. return 0;
  146. }
  147. }
  148. return 1;
  149. }
  150. Error VulkanContext::_create_validation_layers() {
  151. VkResult err;
  152. const char *instance_validation_layers_alt1[] = { "VK_LAYER_KHRONOS_validation" };
  153. const char *instance_validation_layers_alt2[] = { "VK_LAYER_LUNARG_standard_validation" };
  154. const char *instance_validation_layers_alt3[] = { "VK_LAYER_GOOGLE_threading", "VK_LAYER_LUNARG_parameter_validation", "VK_LAYER_LUNARG_object_tracker", "VK_LAYER_LUNARG_core_validation", "VK_LAYER_GOOGLE_unique_objects" };
  155. uint32_t instance_layer_count = 0;
  156. err = vkEnumerateInstanceLayerProperties(&instance_layer_count, nullptr);
  157. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  158. VkBool32 validation_found = 0;
  159. uint32_t validation_layer_count = 0;
  160. const char **instance_validation_layers = nullptr;
  161. if (instance_layer_count > 0) {
  162. VkLayerProperties *instance_layers = (VkLayerProperties *)malloc(sizeof(VkLayerProperties) * instance_layer_count);
  163. err = vkEnumerateInstanceLayerProperties(&instance_layer_count, instance_layers);
  164. if (err) {
  165. free(instance_layers);
  166. ERR_FAIL_V(ERR_CANT_CREATE);
  167. }
  168. validation_layer_count = ARRAY_SIZE(instance_validation_layers_alt1);
  169. instance_validation_layers = instance_validation_layers_alt1;
  170. validation_found = _check_layers(validation_layer_count, instance_validation_layers, instance_layer_count, instance_layers);
  171. // use alternative (deprecated, removed in SDK 1.1.126.0) set of validation layers
  172. if (!validation_found) {
  173. validation_layer_count = ARRAY_SIZE(instance_validation_layers_alt2);
  174. instance_validation_layers = instance_validation_layers_alt2;
  175. validation_found = _check_layers(validation_layer_count, instance_validation_layers, instance_layer_count, instance_layers);
  176. }
  177. // use alternative (deprecated, removed in SDK 1.1.121.1) set of validation layers
  178. if (!validation_found) {
  179. validation_layer_count = ARRAY_SIZE(instance_validation_layers_alt3);
  180. instance_validation_layers = instance_validation_layers_alt3;
  181. validation_found = _check_layers(validation_layer_count, instance_validation_layers, instance_layer_count, instance_layers);
  182. }
  183. free(instance_layers);
  184. }
  185. if (validation_found) {
  186. enabled_layer_count = validation_layer_count;
  187. for (uint32_t i = 0; i < validation_layer_count; i++) {
  188. enabled_layers[i] = instance_validation_layers[i];
  189. }
  190. } else {
  191. return ERR_CANT_CREATE;
  192. }
  193. return OK;
  194. }
  195. Error VulkanContext::_initialize_extensions() {
  196. VkResult err;
  197. uint32_t instance_extension_count = 0;
  198. enabled_extension_count = 0;
  199. enabled_layer_count = 0;
  200. /* Look for instance extensions */
  201. VkBool32 surfaceExtFound = 0;
  202. VkBool32 platformSurfaceExtFound = 0;
  203. memset(extension_names, 0, sizeof(extension_names));
  204. err = vkEnumerateInstanceExtensionProperties(nullptr, &instance_extension_count, nullptr);
  205. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  206. if (instance_extension_count > 0) {
  207. VkExtensionProperties *instance_extensions = (VkExtensionProperties *)malloc(sizeof(VkExtensionProperties) * instance_extension_count);
  208. err = vkEnumerateInstanceExtensionProperties(nullptr, &instance_extension_count, instance_extensions);
  209. if (err) {
  210. free(instance_extensions);
  211. ERR_FAIL_V(ERR_CANT_CREATE);
  212. }
  213. for (uint32_t i = 0; i < instance_extension_count; i++) {
  214. if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
  215. surfaceExtFound = 1;
  216. extension_names[enabled_extension_count++] = VK_KHR_SURFACE_EXTENSION_NAME;
  217. }
  218. if (!strcmp(_get_platform_surface_extension(), instance_extensions[i].extensionName)) {
  219. platformSurfaceExtFound = 1;
  220. extension_names[enabled_extension_count++] = _get_platform_surface_extension();
  221. }
  222. if (!strcmp(VK_EXT_DEBUG_REPORT_EXTENSION_NAME, instance_extensions[i].extensionName)) {
  223. if (use_validation_layers) {
  224. extension_names[enabled_extension_count++] = VK_EXT_DEBUG_REPORT_EXTENSION_NAME;
  225. }
  226. }
  227. if (!strcmp(VK_EXT_DEBUG_UTILS_EXTENSION_NAME, instance_extensions[i].extensionName)) {
  228. if (use_validation_layers) {
  229. extension_names[enabled_extension_count++] = VK_EXT_DEBUG_UTILS_EXTENSION_NAME;
  230. }
  231. }
  232. if (enabled_extension_count >= MAX_EXTENSIONS) {
  233. free(instance_extensions);
  234. ERR_FAIL_V_MSG(ERR_BUG, "Enabled extension count reaches MAX_EXTENSIONS, BUG");
  235. }
  236. }
  237. free(instance_extensions);
  238. }
  239. ERR_FAIL_COND_V_MSG(!surfaceExtFound, ERR_CANT_CREATE, "No surface extension found, is a driver installed?");
  240. ERR_FAIL_COND_V_MSG(!platformSurfaceExtFound, ERR_CANT_CREATE, "No platform surface extension found, is a driver installed?");
  241. return OK;
  242. }
  243. Error VulkanContext::_create_physical_device() {
  244. /* Look for validation layers */
  245. if (use_validation_layers) {
  246. _create_validation_layers();
  247. }
  248. {
  249. Error err = _initialize_extensions();
  250. if (err != OK) {
  251. return err;
  252. }
  253. }
  254. CharString cs = ProjectSettings::get_singleton()->get("application/config/name").operator String().utf8();
  255. String name = "GodotEngine " + String(VERSION_FULL_NAME);
  256. CharString namecs = name.utf8();
  257. const VkApplicationInfo app = {
  258. /*sType*/ VK_STRUCTURE_TYPE_APPLICATION_INFO,
  259. /*pNext*/ nullptr,
  260. /*pApplicationName*/ cs.get_data(),
  261. /*applicationVersion*/ 0,
  262. /*pEngineName*/ namecs.get_data(),
  263. /*engineVersion*/ 0,
  264. /*apiVersion*/ VK_API_VERSION_1_0,
  265. };
  266. VkInstanceCreateInfo inst_info = {
  267. /*sType*/ VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
  268. /*pNext*/ nullptr,
  269. /*flags*/ 0,
  270. /*pApplicationInfo*/ &app,
  271. /*enabledLayerCount*/ enabled_layer_count,
  272. /*ppEnabledLayerNames*/ (const char *const *)instance_validation_layers,
  273. /*enabledExtensionCount*/ enabled_extension_count,
  274. /*ppEnabledExtensionNames*/ (const char *const *)extension_names,
  275. };
  276. /*
  277. * This is info for a temp callback to use during CreateInstance.
  278. * After the instance is created, we use the instance-based
  279. * function to register the final callback.
  280. */
  281. VkDebugUtilsMessengerCreateInfoEXT dbg_messenger_create_info;
  282. if (use_validation_layers) {
  283. // VK_EXT_debug_utils style
  284. dbg_messenger_create_info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
  285. dbg_messenger_create_info.pNext = nullptr;
  286. dbg_messenger_create_info.flags = 0;
  287. dbg_messenger_create_info.messageSeverity =
  288. VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
  289. dbg_messenger_create_info.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
  290. VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
  291. VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
  292. dbg_messenger_create_info.pfnUserCallback = _debug_messenger_callback;
  293. dbg_messenger_create_info.pUserData = this;
  294. inst_info.pNext = &dbg_messenger_create_info;
  295. }
  296. uint32_t gpu_count;
  297. VkResult err = vkCreateInstance(&inst_info, nullptr, &inst);
  298. ERR_FAIL_COND_V_MSG(err == VK_ERROR_INCOMPATIBLE_DRIVER, ERR_CANT_CREATE,
  299. "Cannot find a compatible Vulkan installable client driver (ICD).\n\n"
  300. "vkCreateInstance Failure");
  301. ERR_FAIL_COND_V_MSG(err == VK_ERROR_EXTENSION_NOT_PRESENT, ERR_CANT_CREATE,
  302. "Cannot find a specified extension library.\n"
  303. "Make sure your layers path is set appropriately.\n"
  304. "vkCreateInstance Failure");
  305. ERR_FAIL_COND_V_MSG(err, ERR_CANT_CREATE,
  306. "vkCreateInstance failed.\n\n"
  307. "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
  308. "Please look at the Getting Started guide for additional information.\n"
  309. "vkCreateInstance Failure");
  310. /* Make initial call to query gpu_count, then second call for gpu info*/
  311. err = vkEnumeratePhysicalDevices(inst, &gpu_count, nullptr);
  312. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  313. ERR_FAIL_COND_V_MSG(gpu_count == 0, ERR_CANT_CREATE,
  314. "vkEnumeratePhysicalDevices reported zero accessible devices.\n\n"
  315. "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
  316. "vkEnumeratePhysicalDevices Failure");
  317. VkPhysicalDevice *physical_devices = (VkPhysicalDevice *)malloc(sizeof(VkPhysicalDevice) * gpu_count);
  318. err = vkEnumeratePhysicalDevices(inst, &gpu_count, physical_devices);
  319. if (err) {
  320. free(physical_devices);
  321. ERR_FAIL_V(ERR_CANT_CREATE);
  322. }
  323. /* for now, just grab the first physical device */
  324. gpu = physical_devices[0];
  325. free(physical_devices);
  326. /* Look for device extensions */
  327. uint32_t device_extension_count = 0;
  328. VkBool32 swapchainExtFound = 0;
  329. enabled_extension_count = 0;
  330. memset(extension_names, 0, sizeof(extension_names));
  331. err = vkEnumerateDeviceExtensionProperties(gpu, nullptr, &device_extension_count, nullptr);
  332. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  333. if (device_extension_count > 0) {
  334. VkExtensionProperties *device_extensions = (VkExtensionProperties *)malloc(sizeof(VkExtensionProperties) * device_extension_count);
  335. err = vkEnumerateDeviceExtensionProperties(gpu, nullptr, &device_extension_count, device_extensions);
  336. if (err) {
  337. free(device_extensions);
  338. ERR_FAIL_V(ERR_CANT_CREATE);
  339. }
  340. for (uint32_t i = 0; i < device_extension_count; i++) {
  341. if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, device_extensions[i].extensionName)) {
  342. swapchainExtFound = 1;
  343. extension_names[enabled_extension_count++] = VK_KHR_SWAPCHAIN_EXTENSION_NAME;
  344. }
  345. if (enabled_extension_count >= MAX_EXTENSIONS) {
  346. free(device_extensions);
  347. ERR_FAIL_V_MSG(ERR_BUG, "Enabled extension count reaches MAX_EXTENSIONS, BUG");
  348. }
  349. }
  350. if (VK_KHR_incremental_present_enabled) {
  351. // Even though the user "enabled" the extension via the command
  352. // line, we must make sure that it's enumerated for use with the
  353. // device. Therefore, disable it here, and re-enable it again if
  354. // enumerated.
  355. VK_KHR_incremental_present_enabled = false;
  356. for (uint32_t i = 0; i < device_extension_count; i++) {
  357. if (!strcmp(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME, device_extensions[i].extensionName)) {
  358. extension_names[enabled_extension_count++] = VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME;
  359. VK_KHR_incremental_present_enabled = true;
  360. }
  361. if (enabled_extension_count >= MAX_EXTENSIONS) {
  362. free(device_extensions);
  363. ERR_FAIL_V_MSG(ERR_BUG, "Enabled extension count reaches MAX_EXTENSIONS, BUG");
  364. }
  365. }
  366. }
  367. if (VK_GOOGLE_display_timing_enabled) {
  368. // Even though the user "enabled" the extension via the command
  369. // line, we must make sure that it's enumerated for use with the
  370. // device. Therefore, disable it here, and re-enable it again if
  371. // enumerated.
  372. VK_GOOGLE_display_timing_enabled = false;
  373. for (uint32_t i = 0; i < device_extension_count; i++) {
  374. if (!strcmp(VK_GOOGLE_DISPLAY_TIMING_EXTENSION_NAME, device_extensions[i].extensionName)) {
  375. extension_names[enabled_extension_count++] = VK_GOOGLE_DISPLAY_TIMING_EXTENSION_NAME;
  376. VK_GOOGLE_display_timing_enabled = true;
  377. }
  378. if (enabled_extension_count >= MAX_EXTENSIONS) {
  379. free(device_extensions);
  380. ERR_FAIL_V_MSG(ERR_BUG, "Enabled extension count reaches MAX_EXTENSIONS, BUG");
  381. }
  382. }
  383. }
  384. free(device_extensions);
  385. }
  386. ERR_FAIL_COND_V_MSG(!swapchainExtFound, ERR_CANT_CREATE,
  387. "vkEnumerateDeviceExtensionProperties failed to find the " VK_KHR_SWAPCHAIN_EXTENSION_NAME
  388. " extension.\n\nDo you have a compatible Vulkan installable client driver (ICD) installed?\n"
  389. "vkCreateInstance Failure");
  390. if (use_validation_layers) {
  391. // Setup VK_EXT_debug_utils function pointers always (we use them for
  392. // debug labels and names).
  393. CreateDebugUtilsMessengerEXT =
  394. (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr(inst, "vkCreateDebugUtilsMessengerEXT");
  395. DestroyDebugUtilsMessengerEXT =
  396. (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr(inst, "vkDestroyDebugUtilsMessengerEXT");
  397. SubmitDebugUtilsMessageEXT =
  398. (PFN_vkSubmitDebugUtilsMessageEXT)vkGetInstanceProcAddr(inst, "vkSubmitDebugUtilsMessageEXT");
  399. CmdBeginDebugUtilsLabelEXT =
  400. (PFN_vkCmdBeginDebugUtilsLabelEXT)vkGetInstanceProcAddr(inst, "vkCmdBeginDebugUtilsLabelEXT");
  401. CmdEndDebugUtilsLabelEXT =
  402. (PFN_vkCmdEndDebugUtilsLabelEXT)vkGetInstanceProcAddr(inst, "vkCmdEndDebugUtilsLabelEXT");
  403. CmdInsertDebugUtilsLabelEXT =
  404. (PFN_vkCmdInsertDebugUtilsLabelEXT)vkGetInstanceProcAddr(inst, "vkCmdInsertDebugUtilsLabelEXT");
  405. SetDebugUtilsObjectNameEXT =
  406. (PFN_vkSetDebugUtilsObjectNameEXT)vkGetInstanceProcAddr(inst, "vkSetDebugUtilsObjectNameEXT");
  407. if (nullptr == CreateDebugUtilsMessengerEXT || nullptr == DestroyDebugUtilsMessengerEXT ||
  408. nullptr == SubmitDebugUtilsMessageEXT || nullptr == CmdBeginDebugUtilsLabelEXT ||
  409. nullptr == CmdEndDebugUtilsLabelEXT || nullptr == CmdInsertDebugUtilsLabelEXT ||
  410. nullptr == SetDebugUtilsObjectNameEXT) {
  411. ERR_FAIL_V_MSG(ERR_CANT_CREATE,
  412. "GetProcAddr: Failed to init VK_EXT_debug_utils\n"
  413. "GetProcAddr: Failure");
  414. }
  415. err = CreateDebugUtilsMessengerEXT(inst, &dbg_messenger_create_info, nullptr, &dbg_messenger);
  416. switch (err) {
  417. case VK_SUCCESS:
  418. break;
  419. case VK_ERROR_OUT_OF_HOST_MEMORY:
  420. ERR_FAIL_V_MSG(ERR_CANT_CREATE,
  421. "CreateDebugUtilsMessengerEXT: out of host memory\n"
  422. "CreateDebugUtilsMessengerEXT Failure");
  423. break;
  424. default:
  425. ERR_FAIL_V_MSG(ERR_CANT_CREATE,
  426. "CreateDebugUtilsMessengerEXT: unknown failure\n"
  427. "CreateDebugUtilsMessengerEXT Failure");
  428. ERR_FAIL_V(ERR_CANT_CREATE);
  429. break;
  430. }
  431. }
  432. vkGetPhysicalDeviceProperties(gpu, &gpu_props);
  433. /* Call with NULL data to get count */
  434. vkGetPhysicalDeviceQueueFamilyProperties(gpu, &queue_family_count, nullptr);
  435. ERR_FAIL_COND_V(queue_family_count == 0, ERR_CANT_CREATE);
  436. queue_props = (VkQueueFamilyProperties *)malloc(queue_family_count * sizeof(VkQueueFamilyProperties));
  437. vkGetPhysicalDeviceQueueFamilyProperties(gpu, &queue_family_count, queue_props);
  438. // Query fine-grained feature support for this device.
  439. // If app has specific feature requirements it should check supported
  440. // features based on this query
  441. vkGetPhysicalDeviceFeatures(gpu, &physical_device_features);
  442. #define GET_INSTANCE_PROC_ADDR(inst, entrypoint) \
  443. { \
  444. fp##entrypoint = (PFN_vk##entrypoint)vkGetInstanceProcAddr(inst, "vk" #entrypoint); \
  445. ERR_FAIL_COND_V_MSG(fp##entrypoint == nullptr, ERR_CANT_CREATE, \
  446. "vkGetInstanceProcAddr failed to find vk" #entrypoint); \
  447. }
  448. GET_INSTANCE_PROC_ADDR(inst, GetPhysicalDeviceSurfaceSupportKHR);
  449. GET_INSTANCE_PROC_ADDR(inst, GetPhysicalDeviceSurfaceCapabilitiesKHR);
  450. GET_INSTANCE_PROC_ADDR(inst, GetPhysicalDeviceSurfaceFormatsKHR);
  451. GET_INSTANCE_PROC_ADDR(inst, GetPhysicalDeviceSurfacePresentModesKHR);
  452. GET_INSTANCE_PROC_ADDR(inst, GetSwapchainImagesKHR);
  453. return OK;
  454. }
  455. Error VulkanContext::_create_device() {
  456. VkResult err;
  457. float queue_priorities[1] = { 0.0 };
  458. VkDeviceQueueCreateInfo queues[2];
  459. queues[0].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
  460. queues[0].pNext = nullptr;
  461. queues[0].queueFamilyIndex = graphics_queue_family_index;
  462. queues[0].queueCount = 1;
  463. queues[0].pQueuePriorities = queue_priorities;
  464. queues[0].flags = 0;
  465. VkDeviceCreateInfo sdevice = {
  466. /*sType*/ VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
  467. /*pNext*/ nullptr,
  468. /*flags*/ 0,
  469. /*queueCreateInfoCount*/ 1,
  470. /*pQueueCreateInfos*/ queues,
  471. /*enabledLayerCount*/ 0,
  472. /*ppEnabledLayerNames*/ nullptr,
  473. /*enabledExtensionCount*/ enabled_extension_count,
  474. /*ppEnabledExtensionNames*/ (const char *const *)extension_names,
  475. /*pEnabledFeatures*/ &physical_device_features, // If specific features are required, pass them in here
  476. };
  477. if (separate_present_queue) {
  478. queues[1].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
  479. queues[1].pNext = nullptr;
  480. queues[1].queueFamilyIndex = present_queue_family_index;
  481. queues[1].queueCount = 1;
  482. queues[1].pQueuePriorities = queue_priorities;
  483. queues[1].flags = 0;
  484. sdevice.queueCreateInfoCount = 2;
  485. }
  486. err = vkCreateDevice(gpu, &sdevice, nullptr, &device);
  487. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  488. return OK;
  489. }
  490. Error VulkanContext::_initialize_queues(VkSurfaceKHR surface) {
  491. // Iterate over each queue to learn whether it supports presenting:
  492. VkBool32 *supportsPresent = (VkBool32 *)malloc(queue_family_count * sizeof(VkBool32));
  493. for (uint32_t i = 0; i < queue_family_count; i++) {
  494. fpGetPhysicalDeviceSurfaceSupportKHR(gpu, i, surface, &supportsPresent[i]);
  495. }
  496. // Search for a graphics and a present queue in the array of queue
  497. // families, try to find one that supports both
  498. uint32_t graphicsQueueFamilyIndex = UINT32_MAX;
  499. uint32_t presentQueueFamilyIndex = UINT32_MAX;
  500. for (uint32_t i = 0; i < queue_family_count; i++) {
  501. if ((queue_props[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) != 0) {
  502. if (graphicsQueueFamilyIndex == UINT32_MAX) {
  503. graphicsQueueFamilyIndex = i;
  504. }
  505. if (supportsPresent[i] == VK_TRUE) {
  506. graphicsQueueFamilyIndex = i;
  507. presentQueueFamilyIndex = i;
  508. break;
  509. }
  510. }
  511. }
  512. if (presentQueueFamilyIndex == UINT32_MAX) {
  513. // If didn't find a queue that supports both graphics and present, then
  514. // find a separate present queue.
  515. for (uint32_t i = 0; i < queue_family_count; ++i) {
  516. if (supportsPresent[i] == VK_TRUE) {
  517. presentQueueFamilyIndex = i;
  518. break;
  519. }
  520. }
  521. }
  522. free(supportsPresent);
  523. // Generate error if could not find both a graphics and a present queue
  524. ERR_FAIL_COND_V_MSG(graphicsQueueFamilyIndex == UINT32_MAX || presentQueueFamilyIndex == UINT32_MAX, ERR_CANT_CREATE,
  525. "Could not find both graphics and present queues\n");
  526. graphics_queue_family_index = graphicsQueueFamilyIndex;
  527. present_queue_family_index = presentQueueFamilyIndex;
  528. separate_present_queue = (graphics_queue_family_index != present_queue_family_index);
  529. _create_device();
  530. static PFN_vkGetDeviceProcAddr g_gdpa = nullptr;
  531. #define GET_DEVICE_PROC_ADDR(dev, entrypoint) \
  532. { \
  533. if (!g_gdpa) \
  534. g_gdpa = (PFN_vkGetDeviceProcAddr)vkGetInstanceProcAddr(inst, "vkGetDeviceProcAddr"); \
  535. fp##entrypoint = (PFN_vk##entrypoint)g_gdpa(dev, "vk" #entrypoint); \
  536. ERR_FAIL_COND_V_MSG(fp##entrypoint == nullptr, ERR_CANT_CREATE, \
  537. "vkGetDeviceProcAddr failed to find vk" #entrypoint); \
  538. }
  539. GET_DEVICE_PROC_ADDR(device, CreateSwapchainKHR);
  540. GET_DEVICE_PROC_ADDR(device, DestroySwapchainKHR);
  541. GET_DEVICE_PROC_ADDR(device, GetSwapchainImagesKHR);
  542. GET_DEVICE_PROC_ADDR(device, AcquireNextImageKHR);
  543. GET_DEVICE_PROC_ADDR(device, QueuePresentKHR);
  544. if (VK_GOOGLE_display_timing_enabled) {
  545. GET_DEVICE_PROC_ADDR(device, GetRefreshCycleDurationGOOGLE);
  546. GET_DEVICE_PROC_ADDR(device, GetPastPresentationTimingGOOGLE);
  547. }
  548. vkGetDeviceQueue(device, graphics_queue_family_index, 0, &graphics_queue);
  549. if (!separate_present_queue) {
  550. present_queue = graphics_queue;
  551. } else {
  552. vkGetDeviceQueue(device, present_queue_family_index, 0, &present_queue);
  553. }
  554. // Get the list of VkFormat's that are supported:
  555. uint32_t formatCount;
  556. VkResult err = fpGetPhysicalDeviceSurfaceFormatsKHR(gpu, surface, &formatCount, nullptr);
  557. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  558. VkSurfaceFormatKHR *surfFormats = (VkSurfaceFormatKHR *)malloc(formatCount * sizeof(VkSurfaceFormatKHR));
  559. err = fpGetPhysicalDeviceSurfaceFormatsKHR(gpu, surface, &formatCount, surfFormats);
  560. if (err) {
  561. free(surfFormats);
  562. ERR_FAIL_V(ERR_CANT_CREATE);
  563. }
  564. // If the format list includes just one entry of VK_FORMAT_UNDEFINED,
  565. // the surface has no preferred format. Otherwise, at least one
  566. // supported format will be returned.
  567. if (true || (formatCount == 1 && surfFormats[0].format == VK_FORMAT_UNDEFINED)) {
  568. format = VK_FORMAT_B8G8R8A8_UNORM;
  569. } else {
  570. if (formatCount < 1) {
  571. free(surfFormats);
  572. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "formatCount less than 1");
  573. }
  574. format = surfFormats[0].format;
  575. }
  576. color_space = surfFormats[0].colorSpace;
  577. free(surfFormats);
  578. Error serr = _create_semaphores();
  579. if (serr) {
  580. return serr;
  581. }
  582. queues_initialized = true;
  583. return OK;
  584. }
  585. Error VulkanContext::_create_semaphores() {
  586. VkResult err;
  587. // Create semaphores to synchronize acquiring presentable buffers before
  588. // rendering and waiting for drawing to be complete before presenting
  589. VkSemaphoreCreateInfo semaphoreCreateInfo = {
  590. /*sType*/ VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
  591. /*pNext*/ nullptr,
  592. /*flags*/ 0,
  593. };
  594. // Create fences that we can use to throttle if we get too far
  595. // ahead of the image presents
  596. VkFenceCreateInfo fence_ci = {
  597. /*sType*/ VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,
  598. /*pNext*/ nullptr,
  599. /*flags*/ VK_FENCE_CREATE_SIGNALED_BIT
  600. };
  601. for (uint32_t i = 0; i < FRAME_LAG; i++) {
  602. err = vkCreateFence(device, &fence_ci, nullptr, &fences[i]);
  603. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  604. err = vkCreateSemaphore(device, &semaphoreCreateInfo, nullptr, &image_acquired_semaphores[i]);
  605. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  606. err = vkCreateSemaphore(device, &semaphoreCreateInfo, nullptr, &draw_complete_semaphores[i]);
  607. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  608. if (separate_present_queue) {
  609. err = vkCreateSemaphore(device, &semaphoreCreateInfo, nullptr, &image_ownership_semaphores[i]);
  610. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  611. }
  612. }
  613. frame_index = 0;
  614. // Get Memory information and properties
  615. vkGetPhysicalDeviceMemoryProperties(gpu, &memory_properties);
  616. return OK;
  617. }
  618. Error VulkanContext::_window_create(DisplayServer::WindowID p_window_id, VkSurfaceKHR p_surface, int p_width, int p_height) {
  619. ERR_FAIL_COND_V(windows.has(p_window_id), ERR_INVALID_PARAMETER);
  620. if (!queues_initialized) {
  621. // We use a single GPU, but we need a surface to initialize the
  622. // queues, so this process must be deferred until a surface
  623. // is created.
  624. _initialize_queues(p_surface);
  625. }
  626. Window window;
  627. window.surface = p_surface;
  628. window.width = p_width;
  629. window.height = p_height;
  630. Error err = _update_swap_chain(&window);
  631. ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
  632. windows[p_window_id] = window;
  633. return OK;
  634. }
  635. void VulkanContext::window_resize(DisplayServer::WindowID p_window, int p_width, int p_height) {
  636. ERR_FAIL_COND(!windows.has(p_window));
  637. windows[p_window].width = p_width;
  638. windows[p_window].height = p_height;
  639. _update_swap_chain(&windows[p_window]);
  640. }
  641. int VulkanContext::window_get_width(DisplayServer::WindowID p_window) {
  642. ERR_FAIL_COND_V(!windows.has(p_window), -1);
  643. return windows[p_window].width;
  644. }
  645. int VulkanContext::window_get_height(DisplayServer::WindowID p_window) {
  646. ERR_FAIL_COND_V(!windows.has(p_window), -1);
  647. return windows[p_window].height;
  648. }
  649. VkRenderPass VulkanContext::window_get_render_pass(DisplayServer::WindowID p_window) {
  650. ERR_FAIL_COND_V(!windows.has(p_window), VK_NULL_HANDLE);
  651. Window *w = &windows[p_window];
  652. //vulkan use of currentbuffer
  653. return w->render_pass;
  654. }
  655. VkFramebuffer VulkanContext::window_get_framebuffer(DisplayServer::WindowID p_window) {
  656. ERR_FAIL_COND_V(!windows.has(p_window), VK_NULL_HANDLE);
  657. ERR_FAIL_COND_V(!buffers_prepared, VK_NULL_HANDLE);
  658. Window *w = &windows[p_window];
  659. //vulkan use of currentbuffer
  660. return w->swapchain_image_resources[w->current_buffer].framebuffer;
  661. }
  662. void VulkanContext::window_destroy(DisplayServer::WindowID p_window_id) {
  663. ERR_FAIL_COND(!windows.has(p_window_id));
  664. _clean_up_swap_chain(&windows[p_window_id]);
  665. vkDestroySurfaceKHR(inst, windows[p_window_id].surface, nullptr);
  666. windows.erase(p_window_id);
  667. }
  668. Error VulkanContext::_clean_up_swap_chain(Window *window) {
  669. if (!window->swapchain) {
  670. return OK;
  671. }
  672. vkDeviceWaitIdle(device);
  673. //this destroys images associated it seems
  674. fpDestroySwapchainKHR(device, window->swapchain, nullptr);
  675. window->swapchain = VK_NULL_HANDLE;
  676. vkDestroyRenderPass(device, window->render_pass, nullptr);
  677. if (window->swapchain_image_resources) {
  678. for (uint32_t i = 0; i < swapchainImageCount; i++) {
  679. vkDestroyImageView(device, window->swapchain_image_resources[i].view, nullptr);
  680. vkDestroyFramebuffer(device, window->swapchain_image_resources[i].framebuffer, nullptr);
  681. }
  682. free(window->swapchain_image_resources);
  683. window->swapchain_image_resources = nullptr;
  684. }
  685. if (separate_present_queue) {
  686. vkDestroyCommandPool(device, window->present_cmd_pool, nullptr);
  687. }
  688. return OK;
  689. }
  690. Error VulkanContext::_update_swap_chain(Window *window) {
  691. VkResult err;
  692. if (window->swapchain) {
  693. _clean_up_swap_chain(window);
  694. }
  695. // Check the surface capabilities and formats
  696. VkSurfaceCapabilitiesKHR surfCapabilities;
  697. err = fpGetPhysicalDeviceSurfaceCapabilitiesKHR(gpu, window->surface, &surfCapabilities);
  698. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  699. uint32_t presentModeCount;
  700. err = fpGetPhysicalDeviceSurfacePresentModesKHR(gpu, window->surface, &presentModeCount, nullptr);
  701. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  702. VkPresentModeKHR *presentModes = (VkPresentModeKHR *)malloc(presentModeCount * sizeof(VkPresentModeKHR));
  703. ERR_FAIL_COND_V(!presentModes, ERR_CANT_CREATE);
  704. err = fpGetPhysicalDeviceSurfacePresentModesKHR(gpu, window->surface, &presentModeCount, presentModes);
  705. if (err) {
  706. free(presentModes);
  707. ERR_FAIL_V(ERR_CANT_CREATE);
  708. }
  709. VkExtent2D swapchainExtent;
  710. // width and height are either both 0xFFFFFFFF, or both not 0xFFFFFFFF.
  711. if (surfCapabilities.currentExtent.width == 0xFFFFFFFF) {
  712. // If the surface size is undefined, the size is set to the size
  713. // of the images requested, which must fit within the minimum and
  714. // maximum values.
  715. swapchainExtent.width = window->width;
  716. swapchainExtent.height = window->height;
  717. if (swapchainExtent.width < surfCapabilities.minImageExtent.width) {
  718. swapchainExtent.width = surfCapabilities.minImageExtent.width;
  719. } else if (swapchainExtent.width > surfCapabilities.maxImageExtent.width) {
  720. swapchainExtent.width = surfCapabilities.maxImageExtent.width;
  721. }
  722. if (swapchainExtent.height < surfCapabilities.minImageExtent.height) {
  723. swapchainExtent.height = surfCapabilities.minImageExtent.height;
  724. } else if (swapchainExtent.height > surfCapabilities.maxImageExtent.height) {
  725. swapchainExtent.height = surfCapabilities.maxImageExtent.height;
  726. }
  727. } else {
  728. // If the surface size is defined, the swap chain size must match
  729. swapchainExtent = surfCapabilities.currentExtent;
  730. window->width = surfCapabilities.currentExtent.width;
  731. window->height = surfCapabilities.currentExtent.height;
  732. }
  733. if (window->width == 0 || window->height == 0) {
  734. free(presentModes);
  735. //likely window minimized, no swapchain created
  736. return OK;
  737. }
  738. // The FIFO present mode is guaranteed by the spec to be supported
  739. // and to have no tearing. It's a great default present mode to use.
  740. VkPresentModeKHR swapchainPresentMode = VK_PRESENT_MODE_FIFO_KHR;
  741. // There are times when you may wish to use another present mode. The
  742. // following code shows how to select them, and the comments provide some
  743. // reasons you may wish to use them.
  744. //
  745. // It should be noted that Vulkan 1.0 doesn't provide a method for
  746. // synchronizing rendering with the presentation engine's display. There
  747. // is a method provided for throttling rendering with the display, but
  748. // there are some presentation engines for which this method will not work.
  749. // If an application doesn't throttle its rendering, and if it renders much
  750. // faster than the refresh rate of the display, this can waste power on
  751. // mobile devices. That is because power is being spent rendering images
  752. // that may never be seen.
  753. // VK_PRESENT_MODE_IMMEDIATE_KHR is for applications that don't care about
  754. // tearing, or have some way of synchronizing their rendering with the
  755. // display.
  756. // VK_PRESENT_MODE_MAILBOX_KHR may be useful for applications that
  757. // generally render a new presentable image every refresh cycle, but are
  758. // occasionally early. In this case, the application wants the new image
  759. // to be displayed instead of the previously-queued-for-presentation image
  760. // that has not yet been displayed.
  761. // VK_PRESENT_MODE_FIFO_RELAXED_KHR is for applications that generally
  762. // render a new presentable image every refresh cycle, but are occasionally
  763. // late. In this case (perhaps because of stuttering/latency concerns),
  764. // the application wants the late image to be immediately displayed, even
  765. // though that may mean some tearing.
  766. if (window->presentMode != swapchainPresentMode) {
  767. for (size_t i = 0; i < presentModeCount; ++i) {
  768. if (presentModes[i] == window->presentMode) {
  769. swapchainPresentMode = window->presentMode;
  770. break;
  771. }
  772. }
  773. }
  774. free(presentModes);
  775. ERR_FAIL_COND_V_MSG(swapchainPresentMode != window->presentMode, ERR_CANT_CREATE, "Present mode specified is not supported\n");
  776. // Determine the number of VkImages to use in the swap chain.
  777. // Application desires to acquire 3 images at a time for triple
  778. // buffering
  779. uint32_t desiredNumOfSwapchainImages = 3;
  780. if (desiredNumOfSwapchainImages < surfCapabilities.minImageCount) {
  781. desiredNumOfSwapchainImages = surfCapabilities.minImageCount;
  782. }
  783. // If maxImageCount is 0, we can ask for as many images as we want;
  784. // otherwise we're limited to maxImageCount
  785. if ((surfCapabilities.maxImageCount > 0) && (desiredNumOfSwapchainImages > surfCapabilities.maxImageCount)) {
  786. // Application must settle for fewer images than desired:
  787. desiredNumOfSwapchainImages = surfCapabilities.maxImageCount;
  788. }
  789. VkSurfaceTransformFlagsKHR preTransform;
  790. if (surfCapabilities.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR) {
  791. preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
  792. } else {
  793. preTransform = surfCapabilities.currentTransform;
  794. }
  795. // Find a supported composite alpha mode - one of these is guaranteed to be set
  796. VkCompositeAlphaFlagBitsKHR compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
  797. VkCompositeAlphaFlagBitsKHR compositeAlphaFlags[4] = {
  798. VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
  799. VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR,
  800. VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR,
  801. VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR,
  802. };
  803. for (uint32_t i = 0; i < ARRAY_SIZE(compositeAlphaFlags); i++) {
  804. if (surfCapabilities.supportedCompositeAlpha & compositeAlphaFlags[i]) {
  805. compositeAlpha = compositeAlphaFlags[i];
  806. break;
  807. }
  808. }
  809. VkSwapchainCreateInfoKHR swapchain_ci = {
  810. /*sType*/ VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR,
  811. /*pNext*/ nullptr,
  812. /*flags*/ 0,
  813. /*surface*/ window->surface,
  814. /*minImageCount*/ desiredNumOfSwapchainImages,
  815. /*imageFormat*/ format,
  816. /*imageColorSpace*/ color_space,
  817. /*imageExtent*/ {
  818. /*width*/ swapchainExtent.width,
  819. /*height*/ swapchainExtent.height,
  820. },
  821. /*imageArrayLayers*/ 1,
  822. /*imageUsage*/ VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
  823. /*imageSharingMode*/ VK_SHARING_MODE_EXCLUSIVE,
  824. /*queueFamilyIndexCount*/ 0,
  825. /*pQueueFamilyIndices*/ nullptr,
  826. /*preTransform*/ (VkSurfaceTransformFlagBitsKHR)preTransform,
  827. /*compositeAlpha*/ compositeAlpha,
  828. /*presentMode*/ swapchainPresentMode,
  829. /*clipped*/ true,
  830. /*oldSwapchain*/ VK_NULL_HANDLE,
  831. };
  832. err = fpCreateSwapchainKHR(device, &swapchain_ci, nullptr, &window->swapchain);
  833. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  834. uint32_t sp_image_count;
  835. err = fpGetSwapchainImagesKHR(device, window->swapchain, &sp_image_count, nullptr);
  836. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  837. if (swapchainImageCount == 0) {
  838. //assign here for the first time.
  839. swapchainImageCount = sp_image_count;
  840. } else {
  841. ERR_FAIL_COND_V(swapchainImageCount != sp_image_count, ERR_BUG);
  842. }
  843. VkImage *swapchainImages = (VkImage *)malloc(swapchainImageCount * sizeof(VkImage));
  844. ERR_FAIL_COND_V(!swapchainImages, ERR_CANT_CREATE);
  845. err = fpGetSwapchainImagesKHR(device, window->swapchain, &swapchainImageCount, swapchainImages);
  846. if (err) {
  847. free(swapchainImages);
  848. ERR_FAIL_V(ERR_CANT_CREATE);
  849. }
  850. window->swapchain_image_resources =
  851. (SwapchainImageResources *)malloc(sizeof(SwapchainImageResources) * swapchainImageCount);
  852. if (!window->swapchain_image_resources) {
  853. free(swapchainImages);
  854. ERR_FAIL_V(ERR_CANT_CREATE);
  855. }
  856. for (uint32_t i = 0; i < swapchainImageCount; i++) {
  857. VkImageViewCreateInfo color_image_view = {
  858. /*sType*/ VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
  859. /*pNext*/ nullptr,
  860. /*flags*/ 0,
  861. /*image*/ swapchainImages[i],
  862. /*viewType*/ VK_IMAGE_VIEW_TYPE_2D,
  863. /*format*/ format,
  864. /*components*/ {
  865. /*r*/ VK_COMPONENT_SWIZZLE_R,
  866. /*g*/ VK_COMPONENT_SWIZZLE_G,
  867. /*b*/ VK_COMPONENT_SWIZZLE_B,
  868. /*a*/ VK_COMPONENT_SWIZZLE_A,
  869. },
  870. /*subresourceRange*/ { /*aspectMask*/ VK_IMAGE_ASPECT_COLOR_BIT,
  871. /*baseMipLevel*/ 0,
  872. /*levelCount*/ 1,
  873. /*baseArrayLayer*/ 0,
  874. /*layerCount*/ 1 },
  875. };
  876. window->swapchain_image_resources[i].image = swapchainImages[i];
  877. color_image_view.image = window->swapchain_image_resources[i].image;
  878. err = vkCreateImageView(device, &color_image_view, nullptr, &window->swapchain_image_resources[i].view);
  879. if (err) {
  880. free(swapchainImages);
  881. ERR_FAIL_V(ERR_CANT_CREATE);
  882. }
  883. }
  884. free(swapchainImages);
  885. /******** FRAMEBUFFER ************/
  886. {
  887. const VkAttachmentDescription attachment = {
  888. /*flags*/ 0,
  889. /*format*/ format,
  890. /*samples*/ VK_SAMPLE_COUNT_1_BIT,
  891. /*loadOp*/ VK_ATTACHMENT_LOAD_OP_CLEAR,
  892. /*storeOp*/ VK_ATTACHMENT_STORE_OP_STORE,
  893. /*stencilLoadOp*/ VK_ATTACHMENT_LOAD_OP_DONT_CARE,
  894. /*stencilStoreOp*/ VK_ATTACHMENT_STORE_OP_DONT_CARE,
  895. /*initialLayout*/ VK_IMAGE_LAYOUT_UNDEFINED,
  896. /*finalLayout*/ VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
  897. };
  898. const VkAttachmentReference color_reference = {
  899. /*attachment*/ 0,
  900. /*layout*/ VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
  901. };
  902. const VkSubpassDescription subpass = {
  903. /*flags*/ 0,
  904. /*pipelineBindPoint*/ VK_PIPELINE_BIND_POINT_GRAPHICS,
  905. /*inputAttachmentCount*/ 0,
  906. /*pInputAttachments*/ nullptr,
  907. /*colorAttachmentCount*/ 1,
  908. /*pColorAttachments*/ &color_reference,
  909. /*pResolveAttachments*/ nullptr,
  910. /*pDepthStencilAttachment*/ nullptr,
  911. /*preserveAttachmentCount*/ 0,
  912. /*pPreserveAttachments*/ nullptr,
  913. };
  914. const VkRenderPassCreateInfo rp_info = {
  915. /*sTyp*/ VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO,
  916. /*pNext*/ nullptr,
  917. /*flags*/ 0,
  918. /*attachmentCount*/ 1,
  919. /*pAttachments*/ &attachment,
  920. /*subpassCount*/ 1,
  921. /*pSubpasses*/ &subpass,
  922. /*dependencyCount*/ 0,
  923. /*pDependencies*/ nullptr,
  924. };
  925. err = vkCreateRenderPass(device, &rp_info, nullptr, &window->render_pass);
  926. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  927. for (uint32_t i = 0; i < swapchainImageCount; i++) {
  928. const VkFramebufferCreateInfo fb_info = {
  929. /*sType*/ VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO,
  930. /*pNext*/ nullptr,
  931. /*flags*/ 0,
  932. /*renderPass*/ window->render_pass,
  933. /*attachmentCount*/ 1,
  934. /*pAttachments*/ &window->swapchain_image_resources[i].view,
  935. /*width*/ (uint32_t)window->width,
  936. /*height*/ (uint32_t)window->height,
  937. /*layers*/ 1,
  938. };
  939. err = vkCreateFramebuffer(device, &fb_info, nullptr, &window->swapchain_image_resources[i].framebuffer);
  940. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  941. }
  942. }
  943. /******** SEPARATE PRESENT QUEUE ************/
  944. if (separate_present_queue) {
  945. const VkCommandPoolCreateInfo present_cmd_pool_info = {
  946. /*sType*/ VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
  947. /*pNext*/ nullptr,
  948. /*flags*/ 0,
  949. /*queueFamilyIndex*/ present_queue_family_index,
  950. };
  951. err = vkCreateCommandPool(device, &present_cmd_pool_info, nullptr, &window->present_cmd_pool);
  952. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  953. const VkCommandBufferAllocateInfo present_cmd_info = {
  954. /*sType*/ VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
  955. /*pNext*/ nullptr,
  956. /*commandPool*/ window->present_cmd_pool,
  957. /*level*/ VK_COMMAND_BUFFER_LEVEL_PRIMARY,
  958. /*commandBufferCount*/ 1,
  959. };
  960. for (uint32_t i = 0; i < swapchainImageCount; i++) {
  961. err = vkAllocateCommandBuffers(device, &present_cmd_info,
  962. &window->swapchain_image_resources[i].graphics_to_present_cmd);
  963. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  964. const VkCommandBufferBeginInfo cmd_buf_info = {
  965. /*sType*/ VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
  966. /*pNext*/ nullptr,
  967. /*flags*/ VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT,
  968. /*pInheritanceInfo*/ nullptr,
  969. };
  970. err = vkBeginCommandBuffer(window->swapchain_image_resources[i].graphics_to_present_cmd, &cmd_buf_info);
  971. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  972. VkImageMemoryBarrier image_ownership_barrier = {
  973. /*sType*/ VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
  974. /*pNext*/ nullptr,
  975. /*srcAccessMask*/ 0,
  976. /*dstAccessMask*/ VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
  977. /*oldLayout*/ VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
  978. /*newLayout*/ VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
  979. /*srcQueueFamilyIndex*/ graphics_queue_family_index,
  980. /*dstQueueFamilyIndex*/ present_queue_family_index,
  981. /*image*/ window->swapchain_image_resources[i].image,
  982. /*subresourceRange*/ { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }
  983. };
  984. vkCmdPipelineBarrier(window->swapchain_image_resources[i].graphics_to_present_cmd, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
  985. VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_ownership_barrier);
  986. err = vkEndCommandBuffer(window->swapchain_image_resources[i].graphics_to_present_cmd);
  987. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  988. }
  989. }
  990. //reset current buffer
  991. window->current_buffer = 0;
  992. return OK;
  993. }
  994. Error VulkanContext::initialize() {
  995. Error err = _create_physical_device();
  996. if (err) {
  997. return err;
  998. }
  999. return OK;
  1000. }
  1001. void VulkanContext::set_setup_buffer(const VkCommandBuffer &pCommandBuffer) {
  1002. command_buffer_queue.write[0] = pCommandBuffer;
  1003. }
  1004. void VulkanContext::append_command_buffer(const VkCommandBuffer &pCommandBuffer) {
  1005. if (command_buffer_queue.size() <= command_buffer_count) {
  1006. command_buffer_queue.resize(command_buffer_count + 1);
  1007. }
  1008. command_buffer_queue.write[command_buffer_count] = pCommandBuffer;
  1009. command_buffer_count++;
  1010. }
  1011. void VulkanContext::flush(bool p_flush_setup, bool p_flush_pending) {
  1012. // ensure everything else pending is executed
  1013. vkDeviceWaitIdle(device);
  1014. //flush the pending setup buffer
  1015. if (p_flush_setup && command_buffer_queue[0]) {
  1016. //use a fence to wait for everything done
  1017. VkSubmitInfo submit_info;
  1018. submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
  1019. submit_info.pNext = nullptr;
  1020. submit_info.pWaitDstStageMask = nullptr;
  1021. submit_info.waitSemaphoreCount = 0;
  1022. submit_info.pWaitSemaphores = nullptr;
  1023. submit_info.commandBufferCount = 1;
  1024. submit_info.pCommandBuffers = command_buffer_queue.ptr();
  1025. submit_info.signalSemaphoreCount = 0;
  1026. submit_info.pSignalSemaphores = nullptr;
  1027. VkResult err = vkQueueSubmit(graphics_queue, 1, &submit_info, VK_NULL_HANDLE);
  1028. command_buffer_queue.write[0] = nullptr;
  1029. ERR_FAIL_COND(err);
  1030. vkDeviceWaitIdle(device);
  1031. }
  1032. if (p_flush_pending && command_buffer_count > 1) {
  1033. //use a fence to wait for everything done
  1034. VkSubmitInfo submit_info;
  1035. submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
  1036. submit_info.pNext = nullptr;
  1037. submit_info.pWaitDstStageMask = nullptr;
  1038. submit_info.waitSemaphoreCount = 0;
  1039. submit_info.pWaitSemaphores = nullptr;
  1040. submit_info.commandBufferCount = command_buffer_count - 1;
  1041. submit_info.pCommandBuffers = command_buffer_queue.ptr() + 1;
  1042. submit_info.signalSemaphoreCount = 0;
  1043. submit_info.pSignalSemaphores = nullptr;
  1044. VkResult err = vkQueueSubmit(graphics_queue, 1, &submit_info, VK_NULL_HANDLE);
  1045. ERR_FAIL_COND(err);
  1046. vkDeviceWaitIdle(device);
  1047. command_buffer_count = 1;
  1048. }
  1049. }
  1050. Error VulkanContext::prepare_buffers() {
  1051. if (!queues_initialized) {
  1052. return OK;
  1053. }
  1054. VkResult err;
  1055. // Ensure no more than FRAME_LAG renderings are outstanding
  1056. vkWaitForFences(device, 1, &fences[frame_index], VK_TRUE, UINT64_MAX);
  1057. vkResetFences(device, 1, &fences[frame_index]);
  1058. for (Map<int, Window>::Element *E = windows.front(); E; E = E->next()) {
  1059. Window *w = &E->get();
  1060. if (w->swapchain == VK_NULL_HANDLE) {
  1061. continue;
  1062. }
  1063. do {
  1064. // Get the index of the next available swapchain image:
  1065. err =
  1066. fpAcquireNextImageKHR(device, w->swapchain, UINT64_MAX,
  1067. image_acquired_semaphores[frame_index], VK_NULL_HANDLE, &w->current_buffer);
  1068. if (err == VK_ERROR_OUT_OF_DATE_KHR) {
  1069. // swapchain is out of date (e.g. the window was resized) and
  1070. // must be recreated:
  1071. print_line("early out of data");
  1072. //resize_notify();
  1073. _update_swap_chain(w);
  1074. } else if (err == VK_SUBOPTIMAL_KHR) {
  1075. print_line("early suboptimal");
  1076. // swapchain is not as optimal as it could be, but the platform's
  1077. // presentation engine will still present the image correctly.
  1078. break;
  1079. } else {
  1080. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  1081. }
  1082. } while (err != VK_SUCCESS);
  1083. }
  1084. buffers_prepared = true;
  1085. return OK;
  1086. }
  1087. Error VulkanContext::swap_buffers() {
  1088. if (!queues_initialized) {
  1089. return OK;
  1090. }
  1091. // print_line("swapbuffers?");
  1092. VkResult err;
  1093. #if 0
  1094. if (VK_GOOGLE_display_timing_enabled) {
  1095. // Look at what happened to previous presents, and make appropriate
  1096. // adjustments in timing:
  1097. DemoUpdateTargetIPD(demo);
  1098. // Note: a real application would position its geometry to that it's in
  1099. // the correct locatoin for when the next image is presented. It might
  1100. // also wait, so that there's less latency between any input and when
  1101. // the next image is rendered/presented. This demo program is so
  1102. // simple that it doesn't do either of those.
  1103. }
  1104. #endif
  1105. // Wait for the image acquired semaphore to be signaled to ensure
  1106. // that the image won't be rendered to until the presentation
  1107. // engine has fully released ownership to the application, and it is
  1108. // okay to render to the image.
  1109. const VkCommandBuffer *commands_ptr = nullptr;
  1110. uint32_t commands_to_submit = 0;
  1111. if (command_buffer_queue[0] == nullptr) {
  1112. //no setup command, but commands to submit, submit from the first and skip command
  1113. if (command_buffer_count > 1) {
  1114. commands_ptr = command_buffer_queue.ptr() + 1;
  1115. commands_to_submit = command_buffer_count - 1;
  1116. }
  1117. } else {
  1118. commands_ptr = command_buffer_queue.ptr();
  1119. commands_to_submit = command_buffer_count;
  1120. }
  1121. VkPipelineStageFlags pipe_stage_flags;
  1122. VkSubmitInfo submit_info;
  1123. submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
  1124. submit_info.pNext = nullptr;
  1125. submit_info.pWaitDstStageMask = &pipe_stage_flags;
  1126. pipe_stage_flags = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
  1127. submit_info.waitSemaphoreCount = 1;
  1128. submit_info.pWaitSemaphores = &image_acquired_semaphores[frame_index];
  1129. submit_info.commandBufferCount = commands_to_submit;
  1130. submit_info.pCommandBuffers = commands_ptr;
  1131. submit_info.signalSemaphoreCount = 1;
  1132. submit_info.pSignalSemaphores = &draw_complete_semaphores[frame_index];
  1133. err = vkQueueSubmit(graphics_queue, 1, &submit_info, fences[frame_index]);
  1134. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  1135. command_buffer_queue.write[0] = nullptr;
  1136. command_buffer_count = 1;
  1137. if (separate_present_queue) {
  1138. // If we are using separate queues, change image ownership to the
  1139. // present queue before presenting, waiting for the draw complete
  1140. // semaphore and signalling the ownership released semaphore when finished
  1141. VkFence nullFence = VK_NULL_HANDLE;
  1142. pipe_stage_flags = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
  1143. submit_info.waitSemaphoreCount = 1;
  1144. submit_info.pWaitSemaphores = &draw_complete_semaphores[frame_index];
  1145. submit_info.commandBufferCount = 0;
  1146. VkCommandBuffer *cmdbufptr = (VkCommandBuffer *)alloca(sizeof(VkCommandBuffer *) * windows.size());
  1147. submit_info.pCommandBuffers = cmdbufptr;
  1148. for (Map<int, Window>::Element *E = windows.front(); E; E = E->next()) {
  1149. Window *w = &E->get();
  1150. if (w->swapchain == VK_NULL_HANDLE) {
  1151. continue;
  1152. }
  1153. cmdbufptr[submit_info.commandBufferCount] = w->swapchain_image_resources[w->current_buffer].graphics_to_present_cmd;
  1154. submit_info.commandBufferCount++;
  1155. }
  1156. submit_info.signalSemaphoreCount = 1;
  1157. submit_info.pSignalSemaphores = &image_ownership_semaphores[frame_index];
  1158. err = vkQueueSubmit(present_queue, 1, &submit_info, nullFence);
  1159. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  1160. }
  1161. // If we are using separate queues we have to wait for image ownership,
  1162. // otherwise wait for draw complete
  1163. VkPresentInfoKHR present = {
  1164. /*sType*/ VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
  1165. /*pNext*/ nullptr,
  1166. /*waitSemaphoreCount*/ 1,
  1167. /*pWaitSemaphores*/ (separate_present_queue) ? &image_ownership_semaphores[frame_index] : &draw_complete_semaphores[frame_index],
  1168. /*swapchainCount*/ 0,
  1169. /*pSwapchain*/ nullptr,
  1170. /*pImageIndices*/ nullptr,
  1171. /*pResults*/ nullptr,
  1172. };
  1173. VkSwapchainKHR *pSwapchains = (VkSwapchainKHR *)alloca(sizeof(VkSwapchainKHR *) * windows.size());
  1174. uint32_t *pImageIndices = (uint32_t *)alloca(sizeof(uint32_t *) * windows.size());
  1175. present.pSwapchains = pSwapchains;
  1176. present.pImageIndices = pImageIndices;
  1177. for (Map<int, Window>::Element *E = windows.front(); E; E = E->next()) {
  1178. Window *w = &E->get();
  1179. if (w->swapchain == VK_NULL_HANDLE) {
  1180. continue;
  1181. }
  1182. pSwapchains[present.swapchainCount] = w->swapchain;
  1183. pImageIndices[present.swapchainCount] = w->current_buffer;
  1184. present.swapchainCount++;
  1185. }
  1186. #if 0
  1187. if (VK_KHR_incremental_present_enabled) {
  1188. // If using VK_KHR_incremental_present, we provide a hint of the region
  1189. // that contains changed content relative to the previously-presented
  1190. // image. The implementation can use this hint in order to save
  1191. // work/power (by only copying the region in the hint). The
  1192. // implementation is free to ignore the hint though, and so we must
  1193. // ensure that the entire image has the correctly-drawn content.
  1194. uint32_t eighthOfWidth = width / 8;
  1195. uint32_t eighthOfHeight = height / 8;
  1196. VkRectLayerKHR rect = {
  1197. /*offset.x*/ eighthOfWidth,
  1198. /*offset.y*/ eighthOfHeight,
  1199. /*extent.width*/ eighthOfWidth * 6,
  1200. /*extent.height*/ eighthOfHeight * 6,
  1201. /*layer*/ 0,
  1202. };
  1203. VkPresentRegionKHR region = {
  1204. /*rectangleCount*/ 1,
  1205. /*pRectangles*/ &rect,
  1206. };
  1207. VkPresentRegionsKHR regions = {
  1208. /*sType*/ VK_STRUCTURE_TYPE_PRESENT_REGIONS_KHR,
  1209. /*pNext*/ present.pNext,
  1210. /*swapchainCount*/ present.swapchainCount,
  1211. /*pRegions*/ &region,
  1212. };
  1213. present.pNext = &regions;
  1214. }
  1215. #endif
  1216. #if 0
  1217. if (VK_GOOGLE_display_timing_enabled) {
  1218. VkPresentTimeGOOGLE ptime;
  1219. if (prev_desired_present_time == 0) {
  1220. // This must be the first present for this swapchain.
  1221. //
  1222. // We don't know where we are relative to the presentation engine's
  1223. // display's refresh cycle. We also don't know how long rendering
  1224. // takes. Let's make a grossly-simplified assumption that the
  1225. // desiredPresentTime should be half way between now and
  1226. // now+target_IPD. We will adjust over time.
  1227. uint64_t curtime = getTimeInNanoseconds();
  1228. if (curtime == 0) {
  1229. // Since we didn't find out the current time, don't give a
  1230. // desiredPresentTime:
  1231. ptime.desiredPresentTime = 0;
  1232. } else {
  1233. ptime.desiredPresentTime = curtime + (target_IPD >> 1);
  1234. }
  1235. } else {
  1236. ptime.desiredPresentTime = (prev_desired_present_time + target_IPD);
  1237. }
  1238. ptime.presentID = next_present_id++;
  1239. prev_desired_present_time = ptime.desiredPresentTime;
  1240. VkPresentTimesInfoGOOGLE present_time = {
  1241. /*sType*/ VK_STRUCTURE_TYPE_PRESENT_TIMES_INFO_GOOGLE,
  1242. /*pNext*/ present.pNext,
  1243. /*swapchainCount*/ present.swapchainCount,
  1244. /*pTimes*/ &ptime,
  1245. };
  1246. if (VK_GOOGLE_display_timing_enabled) {
  1247. present.pNext = &present_time;
  1248. }
  1249. }
  1250. #endif
  1251. static int total_frames = 0;
  1252. total_frames++;
  1253. // print_line("current buffer: " + itos(current_buffer));
  1254. err = fpQueuePresentKHR(present_queue, &present);
  1255. frame_index += 1;
  1256. frame_index %= FRAME_LAG;
  1257. if (err == VK_ERROR_OUT_OF_DATE_KHR) {
  1258. // swapchain is out of date (e.g. the window was resized) and
  1259. // must be recreated:
  1260. print_line("out of date");
  1261. resize_notify();
  1262. } else if (err == VK_SUBOPTIMAL_KHR) {
  1263. // swapchain is not as optimal as it could be, but the platform's
  1264. // presentation engine will still present the image correctly.
  1265. print_line("suboptimal");
  1266. } else {
  1267. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  1268. }
  1269. buffers_prepared = false;
  1270. return OK;
  1271. }
  1272. void VulkanContext::resize_notify() {
  1273. }
  1274. VkDevice VulkanContext::get_device() {
  1275. return device;
  1276. }
  1277. VkPhysicalDevice VulkanContext::get_physical_device() {
  1278. return gpu;
  1279. }
  1280. int VulkanContext::get_swapchain_image_count() const {
  1281. return swapchainImageCount;
  1282. }
  1283. uint32_t VulkanContext::get_graphics_queue() const {
  1284. return graphics_queue_family_index;
  1285. }
  1286. VkFormat VulkanContext::get_screen_format() const {
  1287. return format;
  1288. }
  1289. VkPhysicalDeviceLimits VulkanContext::get_device_limits() const {
  1290. return gpu_props.limits;
  1291. }
  1292. VulkanContext::VulkanContext() {
  1293. queue_props = nullptr;
  1294. command_buffer_count = 0;
  1295. instance_validation_layers = nullptr;
  1296. use_validation_layers = true;
  1297. VK_KHR_incremental_present_enabled = true;
  1298. VK_GOOGLE_display_timing_enabled = true;
  1299. command_buffer_queue.resize(1); //first one is the setup command always
  1300. command_buffer_queue.write[0] = nullptr;
  1301. command_buffer_count = 1;
  1302. queues_initialized = false;
  1303. buffers_prepared = false;
  1304. swapchainImageCount = 0;
  1305. }
  1306. RID VulkanContext::local_device_create() {
  1307. LocalDevice ld;
  1308. { //create device
  1309. VkResult err;
  1310. float queue_priorities[1] = { 0.0 };
  1311. VkDeviceQueueCreateInfo queues[2];
  1312. queues[0].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
  1313. queues[0].pNext = nullptr;
  1314. queues[0].queueFamilyIndex = graphics_queue_family_index;
  1315. queues[0].queueCount = 1;
  1316. queues[0].pQueuePriorities = queue_priorities;
  1317. queues[0].flags = 0;
  1318. VkDeviceCreateInfo sdevice = {
  1319. /*sType =*/VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
  1320. /*pNext */ nullptr,
  1321. /*flags */ 0,
  1322. /*queueCreateInfoCount */ 1,
  1323. /*pQueueCreateInfos */ queues,
  1324. /*enabledLayerCount */ 0,
  1325. /*ppEnabledLayerNames */ nullptr,
  1326. /*enabledExtensionCount */ enabled_extension_count,
  1327. /*ppEnabledExtensionNames */ (const char *const *)extension_names,
  1328. /*pEnabledFeatures */ &physical_device_features, // If specific features are required, pass them in here
  1329. };
  1330. err = vkCreateDevice(gpu, &sdevice, nullptr, &ld.device);
  1331. ERR_FAIL_COND_V(err, RID());
  1332. }
  1333. { //create graphics queue
  1334. vkGetDeviceQueue(ld.device, graphics_queue_family_index, 0, &ld.queue);
  1335. }
  1336. return local_device_owner.make_rid(ld);
  1337. }
  1338. VkDevice VulkanContext::local_device_get_vk_device(RID p_local_device) {
  1339. LocalDevice *ld = local_device_owner.getornull(p_local_device);
  1340. return ld->device;
  1341. }
  1342. void VulkanContext::local_device_push_command_buffers(RID p_local_device, const VkCommandBuffer *p_buffers, int p_count) {
  1343. LocalDevice *ld = local_device_owner.getornull(p_local_device);
  1344. ERR_FAIL_COND(ld->waiting);
  1345. VkSubmitInfo submit_info;
  1346. submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
  1347. submit_info.pNext = nullptr;
  1348. submit_info.pWaitDstStageMask = nullptr;
  1349. submit_info.waitSemaphoreCount = 0;
  1350. submit_info.pWaitSemaphores = nullptr;
  1351. submit_info.commandBufferCount = p_count;
  1352. submit_info.pCommandBuffers = p_buffers;
  1353. submit_info.signalSemaphoreCount = 0;
  1354. submit_info.pSignalSemaphores = nullptr;
  1355. VkResult err = vkQueueSubmit(ld->queue, 1, &submit_info, VK_NULL_HANDLE);
  1356. ERR_FAIL_COND(err);
  1357. ld->waiting = true;
  1358. }
  1359. void VulkanContext::local_device_sync(RID p_local_device) {
  1360. LocalDevice *ld = local_device_owner.getornull(p_local_device);
  1361. ERR_FAIL_COND(!ld->waiting);
  1362. vkDeviceWaitIdle(ld->device);
  1363. ld->waiting = false;
  1364. }
  1365. void VulkanContext::local_device_free(RID p_local_device) {
  1366. LocalDevice *ld = local_device_owner.getornull(p_local_device);
  1367. vkDestroyDevice(ld->device, nullptr);
  1368. local_device_owner.free(p_local_device);
  1369. }
  1370. VulkanContext::~VulkanContext() {
  1371. if (queue_props) {
  1372. free(queue_props);
  1373. }
  1374. for (uint32_t i = 0; i < FRAME_LAG; i++) {
  1375. vkDestroyFence(device, fences[i], nullptr);
  1376. vkDestroySemaphore(device, image_acquired_semaphores[i], nullptr);
  1377. vkDestroySemaphore(device, draw_complete_semaphores[i], nullptr);
  1378. if (separate_present_queue) {
  1379. vkDestroySemaphore(device, image_ownership_semaphores[i], nullptr);
  1380. }
  1381. }
  1382. DestroyDebugUtilsMessengerEXT(inst, dbg_messenger, nullptr);
  1383. vkDestroyDevice(device, nullptr);
  1384. vkDestroyInstance(inst, nullptr);
  1385. }