vulkan_context.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. /**************************************************************************/
  2. /* vulkan_context.h */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #ifndef VULKAN_CONTEXT_H
  31. #define VULKAN_CONTEXT_H
  32. #include "core/error/error_list.h"
  33. #include "core/os/mutex.h"
  34. #include "core/string/ustring.h"
  35. #include "core/templates/hash_map.h"
  36. #include "core/templates/rb_map.h"
  37. #include "core/templates/rid_owner.h"
  38. #include "servers/display_server.h"
  39. #include "servers/rendering/rendering_device.h"
  40. #ifdef USE_VOLK
  41. #include <volk.h>
  42. #else
  43. #include <vulkan/vulkan.h>
  44. #endif
  45. #include "vulkan_hooks.h"
  46. class VulkanContext {
  47. public:
  48. struct SubgroupCapabilities {
  49. uint32_t size;
  50. VkShaderStageFlags supportedStages;
  51. VkSubgroupFeatureFlags supportedOperations;
  52. VkBool32 quadOperationsInAllStages;
  53. uint32_t supported_stages_flags_rd() const;
  54. String supported_stages_desc() const;
  55. uint32_t supported_operations_flags_rd() const;
  56. String supported_operations_desc() const;
  57. };
  58. struct MultiviewCapabilities {
  59. bool is_supported;
  60. bool geometry_shader_is_supported;
  61. bool tessellation_shader_is_supported;
  62. uint32_t max_view_count;
  63. uint32_t max_instance_count;
  64. };
  65. struct VRSCapabilities {
  66. bool pipeline_vrs_supported; // We can specify our fragment rate on a pipeline level.
  67. bool primitive_vrs_supported; // We can specify our fragment rate on each drawcall.
  68. bool attachment_vrs_supported; // We can provide a density map attachment on our framebuffer.
  69. Size2i min_texel_size;
  70. Size2i max_texel_size;
  71. Size2i texel_size; // The texel size we'll use
  72. };
  73. struct ShaderCapabilities {
  74. bool shader_float16_is_supported;
  75. bool shader_int8_is_supported;
  76. };
  77. struct StorageBufferCapabilities {
  78. bool storage_buffer_16_bit_access_is_supported;
  79. bool uniform_and_storage_buffer_16_bit_access_is_supported;
  80. bool storage_push_constant_16_is_supported;
  81. bool storage_input_output_16;
  82. };
  83. private:
  84. enum {
  85. MAX_EXTENSIONS = 128,
  86. MAX_LAYERS = 64,
  87. FRAME_LAG = 2
  88. };
  89. static VulkanHooks *vulkan_hooks;
  90. VkInstance inst = VK_NULL_HANDLE;
  91. VkPhysicalDevice gpu = VK_NULL_HANDLE;
  92. VkPhysicalDeviceProperties gpu_props;
  93. uint32_t queue_family_count = 0;
  94. VkQueueFamilyProperties *queue_props = nullptr;
  95. VkDevice device = VK_NULL_HANDLE;
  96. bool device_initialized = false;
  97. bool inst_initialized = false;
  98. uint32_t instance_api_version = VK_API_VERSION_1_0;
  99. SubgroupCapabilities subgroup_capabilities;
  100. MultiviewCapabilities multiview_capabilities;
  101. VRSCapabilities vrs_capabilities;
  102. ShaderCapabilities shader_capabilities;
  103. StorageBufferCapabilities storage_buffer_capabilities;
  104. String device_vendor;
  105. String device_name;
  106. VkPhysicalDeviceType device_type;
  107. String pipeline_cache_id;
  108. uint32_t device_api_version = 0;
  109. bool buffers_prepared = false;
  110. // Present queue.
  111. bool queues_initialized = false;
  112. uint32_t graphics_queue_family_index = UINT32_MAX;
  113. uint32_t present_queue_family_index = UINT32_MAX;
  114. bool separate_present_queue = false;
  115. VkQueue graphics_queue = VK_NULL_HANDLE;
  116. VkQueue present_queue = VK_NULL_HANDLE;
  117. VkColorSpaceKHR color_space;
  118. VkFormat format;
  119. VkSemaphore draw_complete_semaphores[FRAME_LAG];
  120. VkSemaphore image_ownership_semaphores[FRAME_LAG];
  121. int frame_index = 0;
  122. VkFence fences[FRAME_LAG];
  123. VkPhysicalDeviceMemoryProperties memory_properties;
  124. VkPhysicalDeviceFeatures physical_device_features;
  125. typedef struct {
  126. VkImage image;
  127. VkCommandBuffer graphics_to_present_cmd;
  128. VkImageView view;
  129. VkFramebuffer framebuffer;
  130. } SwapchainImageResources;
  131. struct Window {
  132. VkSurfaceKHR surface = VK_NULL_HANDLE;
  133. VkSwapchainKHR swapchain = VK_NULL_HANDLE;
  134. SwapchainImageResources *swapchain_image_resources = VK_NULL_HANDLE;
  135. VkPresentModeKHR presentMode = VK_PRESENT_MODE_FIFO_KHR;
  136. VkSemaphore image_acquired_semaphores[FRAME_LAG];
  137. bool semaphore_acquired = false;
  138. uint32_t current_buffer = 0;
  139. int width = 0;
  140. int height = 0;
  141. DisplayServer::VSyncMode vsync_mode = DisplayServer::VSYNC_ENABLED;
  142. VkCommandPool present_cmd_pool = VK_NULL_HANDLE; // For separate present queue.
  143. VkRenderPass render_pass = VK_NULL_HANDLE;
  144. };
  145. struct LocalDevice {
  146. bool waiting = false;
  147. VkDevice device = VK_NULL_HANDLE;
  148. VkQueue queue = VK_NULL_HANDLE;
  149. };
  150. RID_Owner<LocalDevice, true> local_device_owner;
  151. HashMap<DisplayServer::WindowID, Window> windows;
  152. uint32_t swapchainImageCount = 0;
  153. // Commands.
  154. bool prepared = false;
  155. Vector<VkCommandBuffer> command_buffer_queue;
  156. int command_buffer_count = 1;
  157. // Extensions.
  158. static bool instance_extensions_initialized;
  159. static HashMap<CharString, bool> requested_instance_extensions;
  160. HashSet<CharString> enabled_instance_extension_names;
  161. static bool device_extensions_initialized;
  162. static HashMap<CharString, bool> requested_device_extensions;
  163. HashSet<CharString> enabled_device_extension_names;
  164. bool VK_KHR_incremental_present_enabled = true;
  165. bool VK_GOOGLE_display_timing_enabled = true;
  166. PFN_vkCreateDebugUtilsMessengerEXT CreateDebugUtilsMessengerEXT = nullptr;
  167. PFN_vkDestroyDebugUtilsMessengerEXT DestroyDebugUtilsMessengerEXT = nullptr;
  168. PFN_vkSubmitDebugUtilsMessageEXT SubmitDebugUtilsMessageEXT = nullptr;
  169. PFN_vkCmdBeginDebugUtilsLabelEXT CmdBeginDebugUtilsLabelEXT = nullptr;
  170. PFN_vkCmdEndDebugUtilsLabelEXT CmdEndDebugUtilsLabelEXT = nullptr;
  171. PFN_vkCmdInsertDebugUtilsLabelEXT CmdInsertDebugUtilsLabelEXT = nullptr;
  172. PFN_vkSetDebugUtilsObjectNameEXT SetDebugUtilsObjectNameEXT = nullptr;
  173. PFN_vkCreateDebugReportCallbackEXT CreateDebugReportCallbackEXT = nullptr;
  174. PFN_vkDebugReportMessageEXT DebugReportMessageEXT = nullptr;
  175. PFN_vkDestroyDebugReportCallbackEXT DestroyDebugReportCallbackEXT = nullptr;
  176. PFN_vkGetPhysicalDeviceSurfaceSupportKHR fpGetPhysicalDeviceSurfaceSupportKHR = nullptr;
  177. PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR fpGetPhysicalDeviceSurfaceCapabilitiesKHR = nullptr;
  178. PFN_vkGetPhysicalDeviceSurfaceFormatsKHR fpGetPhysicalDeviceSurfaceFormatsKHR = nullptr;
  179. PFN_vkGetPhysicalDeviceSurfacePresentModesKHR fpGetPhysicalDeviceSurfacePresentModesKHR = nullptr;
  180. PFN_vkCreateSwapchainKHR fpCreateSwapchainKHR = nullptr;
  181. PFN_vkDestroySwapchainKHR fpDestroySwapchainKHR = nullptr;
  182. PFN_vkGetSwapchainImagesKHR fpGetSwapchainImagesKHR = nullptr;
  183. PFN_vkAcquireNextImageKHR fpAcquireNextImageKHR = nullptr;
  184. PFN_vkQueuePresentKHR fpQueuePresentKHR = nullptr;
  185. PFN_vkGetRefreshCycleDurationGOOGLE fpGetRefreshCycleDurationGOOGLE = nullptr;
  186. PFN_vkGetPastPresentationTimingGOOGLE fpGetPastPresentationTimingGOOGLE = nullptr;
  187. PFN_vkCreateRenderPass2KHR fpCreateRenderPass2KHR = nullptr;
  188. VkDebugUtilsMessengerEXT dbg_messenger = VK_NULL_HANDLE;
  189. VkDebugReportCallbackEXT dbg_debug_report = VK_NULL_HANDLE;
  190. Error _obtain_vulkan_version();
  191. Error _initialize_instance_extensions();
  192. Error _initialize_device_extensions();
  193. Error _check_capabilities();
  194. VkBool32 _check_layers(uint32_t check_count, const char *const *check_names, uint32_t layer_count, VkLayerProperties *layers);
  195. static VKAPI_ATTR VkBool32 VKAPI_CALL _debug_messenger_callback(
  196. VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
  197. VkDebugUtilsMessageTypeFlagsEXT messageType,
  198. const VkDebugUtilsMessengerCallbackDataEXT *pCallbackData,
  199. void *pUserData);
  200. static VKAPI_ATTR VkBool32 VKAPI_CALL _debug_report_callback(
  201. VkDebugReportFlagsEXT flags,
  202. VkDebugReportObjectTypeEXT objectType,
  203. uint64_t object,
  204. size_t location,
  205. int32_t messageCode,
  206. const char *pLayerPrefix,
  207. const char *pMessage,
  208. void *pUserData);
  209. Error _create_instance();
  210. Error _create_physical_device(VkSurfaceKHR p_surface);
  211. Error _initialize_queues(VkSurfaceKHR p_surface);
  212. Error _create_device();
  213. Error _clean_up_swap_chain(Window *window);
  214. Error _update_swap_chain(Window *window);
  215. Error _create_swap_chain();
  216. Error _create_semaphores();
  217. Vector<VkAttachmentReference> _convert_VkAttachmentReference2(uint32_t p_count, const VkAttachmentReference2 *p_refs);
  218. protected:
  219. virtual const char *_get_platform_surface_extension() const = 0;
  220. virtual Error _window_create(DisplayServer::WindowID p_window_id, DisplayServer::VSyncMode p_vsync_mode, VkSurfaceKHR p_surface, int p_width, int p_height);
  221. virtual bool _use_validation_layers();
  222. Error _get_preferred_validation_layers(uint32_t *count, const char *const **names);
  223. virtual VkExtent2D _compute_swapchain_extent(const VkSurfaceCapabilitiesKHR &p_surf_capabilities, int *p_window_width, int *p_window_height) const;
  224. public:
  225. // Extension calls.
  226. bool supports_renderpass2() const { return is_device_extension_enabled(VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME); }
  227. VkResult vkCreateRenderPass2KHR(VkDevice p_device, const VkRenderPassCreateInfo2 *p_create_info, const VkAllocationCallbacks *p_allocator, VkRenderPass *p_render_pass);
  228. uint32_t get_vulkan_major() const { return VK_API_VERSION_MAJOR(device_api_version); };
  229. uint32_t get_vulkan_minor() const { return VK_API_VERSION_MINOR(device_api_version); };
  230. const SubgroupCapabilities &get_subgroup_capabilities() const { return subgroup_capabilities; };
  231. const MultiviewCapabilities &get_multiview_capabilities() const { return multiview_capabilities; };
  232. const VRSCapabilities &get_vrs_capabilities() const { return vrs_capabilities; };
  233. const ShaderCapabilities &get_shader_capabilities() const { return shader_capabilities; };
  234. const StorageBufferCapabilities &get_storage_buffer_capabilities() const { return storage_buffer_capabilities; };
  235. const VkPhysicalDeviceFeatures &get_physical_device_features() const { return physical_device_features; };
  236. VkDevice get_device();
  237. VkPhysicalDevice get_physical_device();
  238. VkInstance get_instance() { return inst; }
  239. int get_swapchain_image_count() const;
  240. VkQueue get_graphics_queue() const;
  241. uint32_t get_graphics_queue_family_index() const;
  242. static void set_vulkan_hooks(VulkanHooks *p_vulkan_hooks) { vulkan_hooks = p_vulkan_hooks; };
  243. static void register_requested_instance_extension(const CharString &extension_name, bool p_required);
  244. bool is_instance_extension_enabled(const CharString &extension_name) const {
  245. return enabled_instance_extension_names.has(extension_name);
  246. }
  247. static void register_requested_device_extension(const CharString &extension_name, bool p_required);
  248. bool is_device_extension_enabled(const CharString &extension_name) const {
  249. return enabled_device_extension_names.has(extension_name);
  250. }
  251. void window_resize(DisplayServer::WindowID p_window_id, int p_width, int p_height);
  252. int window_get_width(DisplayServer::WindowID p_window = 0);
  253. int window_get_height(DisplayServer::WindowID p_window = 0);
  254. bool window_is_valid_swapchain(DisplayServer::WindowID p_window = 0);
  255. void window_destroy(DisplayServer::WindowID p_window_id);
  256. VkFramebuffer window_get_framebuffer(DisplayServer::WindowID p_window = 0);
  257. VkRenderPass window_get_render_pass(DisplayServer::WindowID p_window = 0);
  258. RID local_device_create();
  259. VkDevice local_device_get_vk_device(RID p_local_device);
  260. void local_device_push_command_buffers(RID p_local_device, const VkCommandBuffer *p_buffers, int p_count);
  261. void local_device_sync(RID p_local_device);
  262. void local_device_free(RID p_local_device);
  263. VkFormat get_screen_format() const;
  264. VkPhysicalDeviceLimits get_device_limits() const;
  265. void set_setup_buffer(VkCommandBuffer p_command_buffer);
  266. void append_command_buffer(VkCommandBuffer p_command_buffer);
  267. void resize_notify();
  268. void flush(bool p_flush_setup = false, bool p_flush_pending = false);
  269. Error prepare_buffers();
  270. Error swap_buffers();
  271. Error initialize();
  272. void command_begin_label(VkCommandBuffer p_command_buffer, String p_label_name, const Color p_color);
  273. void command_insert_label(VkCommandBuffer p_command_buffer, String p_label_name, const Color p_color);
  274. void command_end_label(VkCommandBuffer p_command_buffer);
  275. void set_object_name(VkObjectType p_object_type, uint64_t p_object_handle, String p_object_name);
  276. String get_device_vendor_name() const;
  277. String get_device_name() const;
  278. RenderingDevice::DeviceType get_device_type() const;
  279. String get_device_api_version() const;
  280. String get_device_pipeline_cache_uuid() const;
  281. void set_vsync_mode(DisplayServer::WindowID p_window, DisplayServer::VSyncMode p_mode);
  282. DisplayServer::VSyncMode get_vsync_mode(DisplayServer::WindowID p_window = 0) const;
  283. VulkanContext();
  284. virtual ~VulkanContext();
  285. };
  286. #endif // VULKAN_CONTEXT_H