rendering_device_driver_vulkan.h 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  1. /**************************************************************************/
  2. /* rendering_device_driver_vulkan.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 RENDERING_DEVICE_DRIVER_VULKAN_H
  31. #define RENDERING_DEVICE_DRIVER_VULKAN_H
  32. #include "core/templates/hash_map.h"
  33. #include "core/templates/paged_allocator.h"
  34. #include "drivers/vulkan/rendering_context_driver_vulkan.h"
  35. #include "servers/rendering/rendering_device_driver.h"
  36. #ifdef DEBUG_ENABLED
  37. #ifndef _MSC_VER
  38. #define _DEBUG
  39. #endif
  40. #endif
  41. #include "thirdparty/vulkan/vk_mem_alloc.h"
  42. #include "drivers/vulkan/godot_vulkan.h"
  43. // Design principles:
  44. // - Vulkan structs are zero-initialized and fields not requiring a non-zero value are omitted (except in cases where expresivity reasons apply).
  45. class RenderingDeviceDriverVulkan : public RenderingDeviceDriver {
  46. /*****************/
  47. /**** GENERIC ****/
  48. /*****************/
  49. struct CommandQueue;
  50. struct SwapChain;
  51. struct Queue {
  52. VkQueue queue = VK_NULL_HANDLE;
  53. uint32_t virtual_count = 0;
  54. BinaryMutex submit_mutex;
  55. };
  56. struct SubgroupCapabilities {
  57. uint32_t size = 0;
  58. uint32_t min_size = 0;
  59. uint32_t max_size = 0;
  60. VkShaderStageFlags supported_stages = 0;
  61. VkSubgroupFeatureFlags supported_operations = 0;
  62. VkBool32 quad_operations_in_all_stages = false;
  63. bool size_control_is_supported = false;
  64. uint32_t supported_stages_flags_rd() const;
  65. String supported_stages_desc() const;
  66. uint32_t supported_operations_flags_rd() const;
  67. String supported_operations_desc() const;
  68. };
  69. struct VRSCapabilities {
  70. bool pipeline_vrs_supported = false; // We can specify our fragment rate on a pipeline level.
  71. bool primitive_vrs_supported = false; // We can specify our fragment rate on each drawcall.
  72. bool attachment_vrs_supported = false; // We can provide a density map attachment on our framebuffer.
  73. Size2i min_texel_size;
  74. Size2i max_texel_size;
  75. Size2i max_fragment_size;
  76. Size2i texel_size; // The texel size we'll use
  77. };
  78. struct ShaderCapabilities {
  79. bool shader_float16_is_supported = false;
  80. bool shader_int8_is_supported = false;
  81. };
  82. struct StorageBufferCapabilities {
  83. bool storage_buffer_16_bit_access_is_supported = false;
  84. bool uniform_and_storage_buffer_16_bit_access_is_supported = false;
  85. bool storage_push_constant_16_is_supported = false;
  86. bool storage_input_output_16 = false;
  87. };
  88. struct DeviceFunctions {
  89. PFN_vkCreateSwapchainKHR CreateSwapchainKHR = nullptr;
  90. PFN_vkDestroySwapchainKHR DestroySwapchainKHR = nullptr;
  91. PFN_vkGetSwapchainImagesKHR GetSwapchainImagesKHR = nullptr;
  92. PFN_vkAcquireNextImageKHR AcquireNextImageKHR = nullptr;
  93. PFN_vkQueuePresentKHR QueuePresentKHR = nullptr;
  94. PFN_vkCreateRenderPass2KHR CreateRenderPass2KHR = nullptr;
  95. // Debug marker extensions.
  96. PFN_vkCmdDebugMarkerBeginEXT CmdDebugMarkerBeginEXT = nullptr;
  97. PFN_vkCmdDebugMarkerEndEXT CmdDebugMarkerEndEXT = nullptr;
  98. PFN_vkCmdDebugMarkerInsertEXT CmdDebugMarkerInsertEXT = nullptr;
  99. PFN_vkDebugMarkerSetObjectNameEXT DebugMarkerSetObjectNameEXT = nullptr;
  100. // Debug device fault.
  101. PFN_vkGetDeviceFaultInfoEXT GetDeviceFaultInfoEXT = nullptr;
  102. };
  103. // Debug marker extensions.
  104. VkDebugReportObjectTypeEXT _convert_to_debug_report_objectType(VkObjectType p_object_type);
  105. VkDevice vk_device = VK_NULL_HANDLE;
  106. RenderingContextDriverVulkan *context_driver = nullptr;
  107. RenderingContextDriver::Device context_device = {};
  108. uint32_t frame_count = 1;
  109. VkPhysicalDevice physical_device = VK_NULL_HANDLE;
  110. VkPhysicalDeviceProperties physical_device_properties = {};
  111. VkPhysicalDeviceFeatures physical_device_features = {};
  112. VkPhysicalDeviceFeatures requested_device_features = {};
  113. HashMap<CharString, bool> requested_device_extensions;
  114. HashSet<CharString> enabled_device_extension_names;
  115. TightLocalVector<TightLocalVector<Queue>> queue_families;
  116. TightLocalVector<VkQueueFamilyProperties> queue_family_properties;
  117. RDD::Capabilities device_capabilities;
  118. SubgroupCapabilities subgroup_capabilities;
  119. MultiviewCapabilities multiview_capabilities;
  120. VRSCapabilities vrs_capabilities;
  121. ShaderCapabilities shader_capabilities;
  122. StorageBufferCapabilities storage_buffer_capabilities;
  123. bool pipeline_cache_control_support = false;
  124. bool device_fault_support = false;
  125. #if defined(VK_TRACK_DEVICE_MEMORY)
  126. bool device_memory_report_support = false;
  127. #endif
  128. #if defined(SWAPPY_FRAME_PACING_ENABLED)
  129. // Swappy frame pacer for Android.
  130. bool swappy_frame_pacer_enable = false;
  131. uint8_t swappy_mode = 2; // See default value for display/window/frame_pacing/android/swappy_mode.
  132. #endif
  133. DeviceFunctions device_functions;
  134. void _register_requested_device_extension(const CharString &p_extension_name, bool p_required);
  135. Error _initialize_device_extensions();
  136. Error _check_device_features();
  137. Error _check_device_capabilities();
  138. Error _add_queue_create_info(LocalVector<VkDeviceQueueCreateInfo> &r_queue_create_info);
  139. Error _initialize_device(const LocalVector<VkDeviceQueueCreateInfo> &p_queue_create_info);
  140. Error _initialize_allocator();
  141. Error _initialize_pipeline_cache();
  142. VkResult _create_render_pass(VkDevice p_device, const VkRenderPassCreateInfo2 *p_create_info, const VkAllocationCallbacks *p_allocator, VkRenderPass *p_render_pass);
  143. bool _release_image_semaphore(CommandQueue *p_command_queue, uint32_t p_semaphore_index, bool p_release_on_swap_chain);
  144. bool _recreate_image_semaphore(CommandQueue *p_command_queue, uint32_t p_semaphore_index, bool p_release_on_swap_chain);
  145. void _set_object_name(VkObjectType p_object_type, uint64_t p_object_handle, String p_object_name);
  146. public:
  147. Error initialize(uint32_t p_device_index, uint32_t p_frame_count) override final;
  148. private:
  149. /****************/
  150. /**** MEMORY ****/
  151. /****************/
  152. VmaAllocator allocator = nullptr;
  153. HashMap<uint32_t, VmaPool> small_allocs_pools;
  154. VmaPool _find_or_create_small_allocs_pool(uint32_t p_mem_type_index);
  155. private:
  156. #if defined(DEBUG_ENABLED) || defined(DEV_ENABLED)
  157. // It's a circular buffer.
  158. BufferID breadcrumb_buffer;
  159. uint32_t breadcrumb_offset = 0u;
  160. uint32_t breadcrumb_id = 0u;
  161. #endif
  162. public:
  163. /*****************/
  164. /**** BUFFERS ****/
  165. /*****************/
  166. struct BufferInfo {
  167. VkBuffer vk_buffer = VK_NULL_HANDLE;
  168. struct {
  169. VmaAllocation handle = nullptr;
  170. uint64_t size = UINT64_MAX;
  171. } allocation;
  172. uint64_t size = 0;
  173. VkBufferView vk_view = VK_NULL_HANDLE; // For texel buffers.
  174. };
  175. virtual BufferID buffer_create(uint64_t p_size, BitField<BufferUsageBits> p_usage, MemoryAllocationType p_allocation_type) override final;
  176. virtual bool buffer_set_texel_format(BufferID p_buffer, DataFormat p_format) override final;
  177. virtual void buffer_free(BufferID p_buffer) override final;
  178. virtual uint64_t buffer_get_allocation_size(BufferID p_buffer) override final;
  179. virtual uint8_t *buffer_map(BufferID p_buffer) override final;
  180. virtual void buffer_unmap(BufferID p_buffer) override final;
  181. /*****************/
  182. /**** TEXTURE ****/
  183. /*****************/
  184. struct TextureInfo {
  185. VkImage vk_image = VK_NULL_HANDLE;
  186. VkImageView vk_view = VK_NULL_HANDLE;
  187. DataFormat rd_format = DATA_FORMAT_MAX;
  188. VkImageCreateInfo vk_create_info = {};
  189. VkImageViewCreateInfo vk_view_create_info = {};
  190. struct {
  191. VmaAllocation handle = nullptr;
  192. VmaAllocationInfo info = {};
  193. } allocation; // All 0/null if just a view.
  194. #ifdef DEBUG_ENABLED
  195. bool created_from_extension = false;
  196. bool transient = false;
  197. #endif
  198. };
  199. VkSampleCountFlagBits _ensure_supported_sample_count(TextureSamples p_requested_sample_count);
  200. public:
  201. virtual TextureID texture_create(const TextureFormat &p_format, const TextureView &p_view) override final;
  202. virtual TextureID texture_create_from_extension(uint64_t p_native_texture, TextureType p_type, DataFormat p_format, uint32_t p_array_layers, bool p_depth_stencil) override final;
  203. virtual TextureID texture_create_shared(TextureID p_original_texture, const TextureView &p_view) override final;
  204. virtual TextureID texture_create_shared_from_slice(TextureID p_original_texture, const TextureView &p_view, TextureSliceType p_slice_type, uint32_t p_layer, uint32_t p_layers, uint32_t p_mipmap, uint32_t p_mipmaps) override final;
  205. virtual void texture_free(TextureID p_texture) override final;
  206. virtual uint64_t texture_get_allocation_size(TextureID p_texture) override final;
  207. virtual void texture_get_copyable_layout(TextureID p_texture, const TextureSubresource &p_subresource, TextureCopyableLayout *r_layout) override final;
  208. virtual uint8_t *texture_map(TextureID p_texture, const TextureSubresource &p_subresource) override final;
  209. virtual void texture_unmap(TextureID p_texture) override final;
  210. virtual BitField<TextureUsageBits> texture_get_usages_supported_by_format(DataFormat p_format, bool p_cpu_readable) override final;
  211. virtual bool texture_can_make_shared_with_format(TextureID p_texture, DataFormat p_format, bool &r_raw_reinterpretation) override final;
  212. /*****************/
  213. /**** SAMPLER ****/
  214. /*****************/
  215. public:
  216. virtual SamplerID sampler_create(const SamplerState &p_state) final override;
  217. virtual void sampler_free(SamplerID p_sampler) final override;
  218. virtual bool sampler_is_format_supported_for_filter(DataFormat p_format, SamplerFilter p_filter) override final;
  219. /**********************/
  220. /**** VERTEX ARRAY ****/
  221. /**********************/
  222. private:
  223. struct VertexFormatInfo {
  224. TightLocalVector<VkVertexInputBindingDescription> vk_bindings;
  225. TightLocalVector<VkVertexInputAttributeDescription> vk_attributes;
  226. VkPipelineVertexInputStateCreateInfo vk_create_info = {};
  227. };
  228. public:
  229. virtual VertexFormatID vertex_format_create(VectorView<VertexAttribute> p_vertex_attribs) override final;
  230. virtual void vertex_format_free(VertexFormatID p_vertex_format) override final;
  231. /******************/
  232. /**** BARRIERS ****/
  233. /******************/
  234. virtual void command_pipeline_barrier(
  235. CommandBufferID p_cmd_buffer,
  236. BitField<PipelineStageBits> p_src_stages,
  237. BitField<PipelineStageBits> p_dst_stages,
  238. VectorView<MemoryBarrier> p_memory_barriers,
  239. VectorView<BufferBarrier> p_buffer_barriers,
  240. VectorView<TextureBarrier> p_texture_barriers) override final;
  241. /****************/
  242. /**** FENCES ****/
  243. /****************/
  244. private:
  245. struct Fence {
  246. VkFence vk_fence = VK_NULL_HANDLE;
  247. CommandQueue *queue_signaled_from = nullptr;
  248. };
  249. public:
  250. virtual FenceID fence_create() override final;
  251. virtual Error fence_wait(FenceID p_fence) override final;
  252. virtual void fence_free(FenceID p_fence) override final;
  253. /********************/
  254. /**** SEMAPHORES ****/
  255. /********************/
  256. virtual SemaphoreID semaphore_create() override final;
  257. virtual void semaphore_free(SemaphoreID p_semaphore) override final;
  258. /******************/
  259. /**** COMMANDS ****/
  260. /******************/
  261. // ----- QUEUE FAMILY -----
  262. virtual CommandQueueFamilyID command_queue_family_get(BitField<CommandQueueFamilyBits> p_cmd_queue_family_bits, RenderingContextDriver::SurfaceID p_surface = 0) override final;
  263. // ----- QUEUE -----
  264. private:
  265. struct CommandQueue {
  266. LocalVector<VkSemaphore> present_semaphores;
  267. LocalVector<VkSemaphore> image_semaphores;
  268. LocalVector<SwapChain *> image_semaphores_swap_chains;
  269. LocalVector<uint32_t> pending_semaphores_for_execute;
  270. LocalVector<uint32_t> pending_semaphores_for_fence;
  271. LocalVector<uint32_t> free_image_semaphores;
  272. LocalVector<Pair<Fence *, uint32_t>> image_semaphores_for_fences;
  273. uint32_t queue_family = 0;
  274. uint32_t queue_index = 0;
  275. uint32_t present_semaphore_index = 0;
  276. };
  277. public:
  278. virtual CommandQueueID command_queue_create(CommandQueueFamilyID p_cmd_queue_family, bool p_identify_as_main_queue = false) override final;
  279. virtual Error command_queue_execute_and_present(CommandQueueID p_cmd_queue, VectorView<SemaphoreID> p_wait_semaphores, VectorView<CommandBufferID> p_cmd_buffers, VectorView<SemaphoreID> p_cmd_semaphores, FenceID p_cmd_fence, VectorView<SwapChainID> p_swap_chains) override final;
  280. virtual void command_queue_free(CommandQueueID p_cmd_queue) override final;
  281. private:
  282. // ----- POOL -----
  283. struct CommandPool {
  284. VkCommandPool vk_command_pool = VK_NULL_HANDLE;
  285. CommandBufferType buffer_type = COMMAND_BUFFER_TYPE_PRIMARY;
  286. };
  287. public:
  288. virtual CommandPoolID command_pool_create(CommandQueueFamilyID p_cmd_queue_family, CommandBufferType p_cmd_buffer_type) override final;
  289. virtual bool command_pool_reset(CommandPoolID p_cmd_pool) override final;
  290. virtual void command_pool_free(CommandPoolID p_cmd_pool) override final;
  291. // ----- BUFFER -----
  292. virtual CommandBufferID command_buffer_create(CommandPoolID p_cmd_pool) override final;
  293. virtual bool command_buffer_begin(CommandBufferID p_cmd_buffer) override final;
  294. virtual bool command_buffer_begin_secondary(CommandBufferID p_cmd_buffer, RenderPassID p_render_pass, uint32_t p_subpass, FramebufferID p_framebuffer) override final;
  295. virtual void command_buffer_end(CommandBufferID p_cmd_buffer) override final;
  296. virtual void command_buffer_execute_secondary(CommandBufferID p_cmd_buffer, VectorView<CommandBufferID> p_secondary_cmd_buffers) override final;
  297. /********************/
  298. /**** SWAP CHAIN ****/
  299. /********************/
  300. private:
  301. struct SwapChain {
  302. VkSwapchainKHR vk_swapchain = VK_NULL_HANDLE;
  303. RenderingContextDriver::SurfaceID surface = RenderingContextDriver::SurfaceID();
  304. VkFormat format = VK_FORMAT_UNDEFINED;
  305. VkColorSpaceKHR color_space = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR;
  306. TightLocalVector<VkImage> images;
  307. TightLocalVector<VkImageView> image_views;
  308. TightLocalVector<FramebufferID> framebuffers;
  309. LocalVector<CommandQueue *> command_queues_acquired;
  310. LocalVector<uint32_t> command_queues_acquired_semaphores;
  311. RenderPassID render_pass;
  312. int pre_transform_rotation_degrees = 0;
  313. uint32_t image_index = 0;
  314. #ifdef ANDROID_ENABLED
  315. uint64_t refresh_duration = 0;
  316. #endif
  317. };
  318. void _swap_chain_release(SwapChain *p_swap_chain);
  319. public:
  320. virtual SwapChainID swap_chain_create(RenderingContextDriver::SurfaceID p_surface) override final;
  321. virtual Error swap_chain_resize(CommandQueueID p_cmd_queue, SwapChainID p_swap_chain, uint32_t p_desired_framebuffer_count) override final;
  322. virtual FramebufferID swap_chain_acquire_framebuffer(CommandQueueID p_cmd_queue, SwapChainID p_swap_chain, bool &r_resize_required) override final;
  323. virtual RenderPassID swap_chain_get_render_pass(SwapChainID p_swap_chain) override final;
  324. virtual int swap_chain_get_pre_rotation_degrees(SwapChainID p_swap_chain) override final;
  325. virtual DataFormat swap_chain_get_format(SwapChainID p_swap_chain) override final;
  326. virtual void swap_chain_set_max_fps(SwapChainID p_swap_chain, int p_max_fps) override final;
  327. virtual void swap_chain_free(SwapChainID p_swap_chain) override final;
  328. /*********************/
  329. /**** FRAMEBUFFER ****/
  330. /*********************/
  331. struct Framebuffer {
  332. VkFramebuffer vk_framebuffer = VK_NULL_HANDLE;
  333. // Only filled in by a framebuffer created by a swap chain. Unused otherwise.
  334. VkImage swap_chain_image = VK_NULL_HANDLE;
  335. VkImageSubresourceRange swap_chain_image_subresource_range = {};
  336. bool swap_chain_acquired = false;
  337. };
  338. virtual FramebufferID framebuffer_create(RenderPassID p_render_pass, VectorView<TextureID> p_attachments, uint32_t p_width, uint32_t p_height) override final;
  339. virtual void framebuffer_free(FramebufferID p_framebuffer) override final;
  340. /****************/
  341. /**** SHADER ****/
  342. /****************/
  343. private:
  344. struct ShaderBinary {
  345. // Version 1: initial.
  346. // Version 2: Added shader name.
  347. // Version 3: Added writable.
  348. // Version 4: 64-bit vertex input mask.
  349. static const uint32_t VERSION = 4;
  350. struct DataBinding {
  351. uint32_t type = 0;
  352. uint32_t binding = 0;
  353. uint32_t stages = 0;
  354. uint32_t length = 0; // Size of arrays (in total elements), or UBOs (in bytes * total elements).
  355. uint32_t writable = 0;
  356. };
  357. struct SpecializationConstant {
  358. uint32_t type = 0;
  359. uint32_t constant_id = 0;
  360. uint32_t int_value = 0;
  361. uint32_t stage_flags = 0;
  362. };
  363. struct Data {
  364. uint64_t vertex_input_mask = 0;
  365. uint32_t fragment_output_mask = 0;
  366. uint32_t specialization_constants_count = 0;
  367. uint32_t is_compute = 0;
  368. uint32_t compute_local_size[3] = {};
  369. uint32_t set_count = 0;
  370. uint32_t push_constant_size = 0;
  371. uint32_t vk_push_constant_stages_mask = 0;
  372. uint32_t stage_count = 0;
  373. uint32_t shader_name_len = 0;
  374. };
  375. };
  376. struct ShaderInfo {
  377. VkShaderStageFlags vk_push_constant_stages = 0;
  378. TightLocalVector<VkPipelineShaderStageCreateInfo> vk_stages_create_info;
  379. TightLocalVector<VkDescriptorSetLayout> vk_descriptor_set_layouts;
  380. VkPipelineLayout vk_pipeline_layout = VK_NULL_HANDLE;
  381. };
  382. public:
  383. virtual String shader_get_binary_cache_key() override final;
  384. virtual Vector<uint8_t> shader_compile_binary_from_spirv(VectorView<ShaderStageSPIRVData> p_spirv, const String &p_shader_name) override final;
  385. virtual ShaderID shader_create_from_bytecode(const Vector<uint8_t> &p_shader_binary, ShaderDescription &r_shader_desc, String &r_name, const Vector<ImmutableSampler> &p_immutable_samplers) override final;
  386. virtual void shader_free(ShaderID p_shader) override final;
  387. virtual void shader_destroy_modules(ShaderID p_shader) override final;
  388. /*********************/
  389. /**** UNIFORM SET ****/
  390. /*********************/
  391. // Descriptor sets require allocation from a pool.
  392. // The documentation on how to use pools properly
  393. // is scarce, and the documentation is strange.
  394. //
  395. // Basically, you can mix and match pools as you
  396. // like, but you'll run into fragmentation issues.
  397. // Because of this, the recommended approach is to
  398. // create a pool for every descriptor set type, as
  399. // this prevents fragmentation.
  400. //
  401. // This is implemented here as a having a list of
  402. // pools (each can contain up to 64 sets) for each
  403. // set layout. The amount of sets for each type
  404. // is used as the key.
  405. private:
  406. static const uint32_t MAX_UNIFORM_POOL_ELEMENT = 65535;
  407. struct DescriptorSetPoolKey {
  408. uint16_t uniform_type[UNIFORM_TYPE_MAX] = {};
  409. bool operator<(const DescriptorSetPoolKey &p_other) const {
  410. return memcmp(uniform_type, p_other.uniform_type, sizeof(uniform_type)) < 0;
  411. }
  412. };
  413. using DescriptorSetPools = RBMap<DescriptorSetPoolKey, HashMap<VkDescriptorPool, uint32_t>>;
  414. DescriptorSetPools descriptor_set_pools;
  415. uint32_t max_descriptor_sets_per_pool = 0;
  416. HashMap<int, DescriptorSetPools> linear_descriptor_set_pools;
  417. bool linear_descriptor_pools_enabled = true;
  418. VkDescriptorPool _descriptor_set_pool_find_or_create(const DescriptorSetPoolKey &p_key, DescriptorSetPools::Iterator *r_pool_sets_it, int p_linear_pool_index);
  419. void _descriptor_set_pool_unreference(DescriptorSetPools::Iterator p_pool_sets_it, VkDescriptorPool p_vk_descriptor_pool, int p_linear_pool_index);
  420. // Global flag to toggle usage of immutable sampler when creating pipeline layouts.
  421. // It cannot change after creating the PSOs, since we need to skipping samplers when creating uniform sets.
  422. bool immutable_samplers_enabled = true;
  423. struct UniformSetInfo {
  424. VkDescriptorSet vk_descriptor_set = VK_NULL_HANDLE;
  425. VkDescriptorPool vk_descriptor_pool = VK_NULL_HANDLE;
  426. VkDescriptorPool vk_linear_descriptor_pool = VK_NULL_HANDLE;
  427. DescriptorSetPools::Iterator pool_sets_it;
  428. };
  429. public:
  430. virtual UniformSetID uniform_set_create(VectorView<BoundUniform> p_uniforms, ShaderID p_shader, uint32_t p_set_index, int p_linear_pool_index) override final;
  431. virtual void linear_uniform_set_pools_reset(int p_linear_pool_index) override final;
  432. virtual void uniform_set_free(UniformSetID p_uniform_set) override final;
  433. virtual bool uniform_sets_have_linear_pools() const override final;
  434. // ----- COMMANDS -----
  435. virtual void command_uniform_set_prepare_for_use(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index) override final;
  436. /******************/
  437. /**** TRANSFER ****/
  438. /******************/
  439. virtual void command_clear_buffer(CommandBufferID p_cmd_buffer, BufferID p_buffer, uint64_t p_offset, uint64_t p_size) override final;
  440. virtual void command_copy_buffer(CommandBufferID p_cmd_buffer, BufferID p_src_buffer, BufferID p_dst_buffer, VectorView<BufferCopyRegion> p_regions) override final;
  441. virtual void command_copy_texture(CommandBufferID p_cmd_buffer, TextureID p_src_texture, TextureLayout p_src_texture_layout, TextureID p_dst_texture, TextureLayout p_dst_texture_layout, VectorView<TextureCopyRegion> p_regions) override final;
  442. virtual void command_resolve_texture(CommandBufferID p_cmd_buffer, TextureID p_src_texture, TextureLayout p_src_texture_layout, uint32_t p_src_layer, uint32_t p_src_mipmap, TextureID p_dst_texture, TextureLayout p_dst_texture_layout, uint32_t p_dst_layer, uint32_t p_dst_mipmap) override final;
  443. virtual void command_clear_color_texture(CommandBufferID p_cmd_buffer, TextureID p_texture, TextureLayout p_texture_layout, const Color &p_color, const TextureSubresourceRange &p_subresources) override final;
  444. virtual void command_copy_buffer_to_texture(CommandBufferID p_cmd_buffer, BufferID p_src_buffer, TextureID p_dst_texture, TextureLayout p_dst_texture_layout, VectorView<BufferTextureCopyRegion> p_regions) override final;
  445. virtual void command_copy_texture_to_buffer(CommandBufferID p_cmd_buffer, TextureID p_src_texture, TextureLayout p_src_texture_layout, BufferID p_dst_buffer, VectorView<BufferTextureCopyRegion> p_regions) override final;
  446. /******************/
  447. /**** PIPELINE ****/
  448. /******************/
  449. private:
  450. struct PipelineCacheHeader {
  451. uint32_t magic = 0;
  452. uint32_t data_size = 0;
  453. uint64_t data_hash = 0;
  454. uint32_t vendor_id = 0;
  455. uint32_t device_id = 0;
  456. uint32_t driver_version = 0;
  457. uint8_t uuid[VK_UUID_SIZE] = {};
  458. uint8_t driver_abi = 0;
  459. };
  460. struct PipelineCache {
  461. String file_path;
  462. size_t current_size = 0;
  463. Vector<uint8_t> buffer; // Header then data.
  464. VkPipelineCache vk_cache = VK_NULL_HANDLE;
  465. };
  466. static int caching_instance_count;
  467. PipelineCache pipelines_cache;
  468. String pipeline_cache_id;
  469. HashMap<uint64_t, bool> has_comp_alpha;
  470. public:
  471. virtual void pipeline_free(PipelineID p_pipeline) override final;
  472. // ----- BINDING -----
  473. virtual void command_bind_push_constants(CommandBufferID p_cmd_buffer, ShaderID p_shader, uint32_t p_first_index, VectorView<uint32_t> p_data) override final;
  474. // ----- CACHE -----
  475. virtual bool pipeline_cache_create(const Vector<uint8_t> &p_data) override final;
  476. virtual void pipeline_cache_free() override final;
  477. virtual size_t pipeline_cache_query_size() override final;
  478. virtual Vector<uint8_t> pipeline_cache_serialize() override final;
  479. /*******************/
  480. /**** RENDERING ****/
  481. /*******************/
  482. // ----- SUBPASS -----
  483. virtual RenderPassID render_pass_create(VectorView<Attachment> p_attachments, VectorView<Subpass> p_subpasses, VectorView<SubpassDependency> p_subpass_dependencies, uint32_t p_view_count) override final;
  484. virtual void render_pass_free(RenderPassID p_render_pass) override final;
  485. // ----- COMMANDS -----
  486. virtual void command_begin_render_pass(CommandBufferID p_cmd_buffer, RenderPassID p_render_pass, FramebufferID p_framebuffer, CommandBufferType p_cmd_buffer_type, const Rect2i &p_rect, VectorView<RenderPassClearValue> p_clear_values) override final;
  487. virtual void command_end_render_pass(CommandBufferID p_cmd_buffer) override final;
  488. virtual void command_next_render_subpass(CommandBufferID p_cmd_buffer, CommandBufferType p_cmd_buffer_type) override final;
  489. virtual void command_render_set_viewport(CommandBufferID p_cmd_buffer, VectorView<Rect2i> p_viewports) override final;
  490. virtual void command_render_set_scissor(CommandBufferID p_cmd_buffer, VectorView<Rect2i> p_scissors) override final;
  491. virtual void command_render_clear_attachments(CommandBufferID p_cmd_buffer, VectorView<AttachmentClear> p_attachment_clears, VectorView<Rect2i> p_rects) override final;
  492. // Binding.
  493. virtual void command_bind_render_pipeline(CommandBufferID p_cmd_buffer, PipelineID p_pipeline) override final;
  494. virtual void command_bind_render_uniform_set(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index) override final;
  495. virtual void command_bind_render_uniform_sets(CommandBufferID p_cmd_buffer, VectorView<UniformSetID> p_uniform_sets, ShaderID p_shader, uint32_t p_first_set_index, uint32_t p_set_count) override final;
  496. // Drawing.
  497. virtual void command_render_draw(CommandBufferID p_cmd_buffer, uint32_t p_vertex_count, uint32_t p_instance_count, uint32_t p_base_vertex, uint32_t p_first_instance) override final;
  498. virtual void command_render_draw_indexed(CommandBufferID p_cmd_buffer, uint32_t p_index_count, uint32_t p_instance_count, uint32_t p_first_index, int32_t p_vertex_offset, uint32_t p_first_instance) override final;
  499. virtual void command_render_draw_indexed_indirect(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset, uint32_t p_draw_count, uint32_t p_stride) override final;
  500. virtual void command_render_draw_indexed_indirect_count(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset, BufferID p_count_buffer, uint64_t p_count_buffer_offset, uint32_t p_max_draw_count, uint32_t p_stride) override final;
  501. virtual void command_render_draw_indirect(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset, uint32_t p_draw_count, uint32_t p_stride) override final;
  502. virtual void command_render_draw_indirect_count(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset, BufferID p_count_buffer, uint64_t p_count_buffer_offset, uint32_t p_max_draw_count, uint32_t p_stride) override final;
  503. // Buffer binding.
  504. virtual void command_render_bind_vertex_buffers(CommandBufferID p_cmd_buffer, uint32_t p_binding_count, const BufferID *p_buffers, const uint64_t *p_offsets) override final;
  505. virtual void command_render_bind_index_buffer(CommandBufferID p_cmd_buffer, BufferID p_buffer, IndexBufferFormat p_format, uint64_t p_offset) override final;
  506. // Dynamic state.
  507. virtual void command_render_set_blend_constants(CommandBufferID p_cmd_buffer, const Color &p_constants) override final;
  508. virtual void command_render_set_line_width(CommandBufferID p_cmd_buffer, float p_width) override final;
  509. // ----- PIPELINE -----
  510. virtual PipelineID render_pipeline_create(
  511. ShaderID p_shader,
  512. VertexFormatID p_vertex_format,
  513. RenderPrimitive p_render_primitive,
  514. PipelineRasterizationState p_rasterization_state,
  515. PipelineMultisampleState p_multisample_state,
  516. PipelineDepthStencilState p_depth_stencil_state,
  517. PipelineColorBlendState p_blend_state,
  518. VectorView<int32_t> p_color_attachments,
  519. BitField<PipelineDynamicStateFlags> p_dynamic_state,
  520. RenderPassID p_render_pass,
  521. uint32_t p_render_subpass,
  522. VectorView<PipelineSpecializationConstant> p_specialization_constants) override final;
  523. /*****************/
  524. /**** COMPUTE ****/
  525. /*****************/
  526. // ----- COMMANDS -----
  527. // Binding.
  528. virtual void command_bind_compute_pipeline(CommandBufferID p_cmd_buffer, PipelineID p_pipeline) override final;
  529. virtual void command_bind_compute_uniform_set(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index) override final;
  530. virtual void command_bind_compute_uniform_sets(CommandBufferID p_cmd_buffer, VectorView<UniformSetID> p_uniform_sets, ShaderID p_shader, uint32_t p_first_set_index, uint32_t p_set_count) override final;
  531. // Dispatching.
  532. virtual void command_compute_dispatch(CommandBufferID p_cmd_buffer, uint32_t p_x_groups, uint32_t p_y_groups, uint32_t p_z_groups) override final;
  533. virtual void command_compute_dispatch_indirect(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset) override final;
  534. // ----- PIPELINE -----
  535. virtual PipelineID compute_pipeline_create(ShaderID p_shader, VectorView<PipelineSpecializationConstant> p_specialization_constants) override final;
  536. /*****************/
  537. /**** QUERIES ****/
  538. /*****************/
  539. // ----- TIMESTAMP -----
  540. // Basic.
  541. virtual QueryPoolID timestamp_query_pool_create(uint32_t p_query_count) override final;
  542. virtual void timestamp_query_pool_free(QueryPoolID p_pool_id) override final;
  543. virtual void timestamp_query_pool_get_results(QueryPoolID p_pool_id, uint32_t p_query_count, uint64_t *r_results) override final;
  544. virtual uint64_t timestamp_query_result_to_time(uint64_t p_result) override final;
  545. // Commands.
  546. virtual void command_timestamp_query_pool_reset(CommandBufferID p_cmd_buffer, QueryPoolID p_pool_id, uint32_t p_query_count) override final;
  547. virtual void command_timestamp_write(CommandBufferID p_cmd_buffer, QueryPoolID p_pool_id, uint32_t p_index) override final;
  548. /****************/
  549. /**** LABELS ****/
  550. /****************/
  551. virtual void command_begin_label(CommandBufferID p_cmd_buffer, const char *p_label_name, const Color &p_color) override final;
  552. virtual void command_end_label(CommandBufferID p_cmd_buffer) override final;
  553. /****************/
  554. /**** DEBUG *****/
  555. /****************/
  556. virtual void command_insert_breadcrumb(CommandBufferID p_cmd_buffer, uint32_t p_data) override final;
  557. void print_lost_device_info();
  558. void on_device_lost() const;
  559. static String get_vulkan_result(VkResult err);
  560. /********************/
  561. /**** SUBMISSION ****/
  562. /********************/
  563. virtual void begin_segment(uint32_t p_frame_index, uint32_t p_frames_drawn) override final;
  564. virtual void end_segment() override final;
  565. /**************/
  566. /**** MISC ****/
  567. /**************/
  568. virtual void set_object_name(ObjectType p_type, ID p_driver_id, const String &p_name) override final;
  569. virtual uint64_t get_resource_native_handle(DriverResource p_type, ID p_driver_id) override final;
  570. virtual uint64_t get_total_memory_used() override final;
  571. virtual uint64_t get_lazily_memory_used() override final;
  572. virtual uint64_t limit_get(Limit p_limit) override final;
  573. virtual uint64_t api_trait_get(ApiTrait p_trait) override final;
  574. virtual bool has_feature(Features p_feature) override final;
  575. virtual const MultiviewCapabilities &get_multiview_capabilities() override final;
  576. virtual String get_api_name() const override final;
  577. virtual String get_api_version() const override final;
  578. virtual String get_pipeline_cache_uuid() const override final;
  579. virtual const Capabilities &get_capabilities() const override final;
  580. virtual bool is_composite_alpha_supported(CommandQueueID p_queue) const override final;
  581. private:
  582. /*********************/
  583. /**** BOOKKEEPING ****/
  584. /*********************/
  585. using VersatileResource = VersatileResourceTemplate<
  586. BufferInfo,
  587. TextureInfo,
  588. VertexFormatInfo,
  589. ShaderInfo,
  590. UniformSetInfo>;
  591. PagedAllocator<VersatileResource, true> resources_allocator;
  592. /******************/
  593. public:
  594. RenderingDeviceDriverVulkan(RenderingContextDriverVulkan *p_context_driver);
  595. virtual ~RenderingDeviceDriverVulkan();
  596. };
  597. using VKC = RenderingContextDriverVulkan;
  598. #endif // RENDERING_DEVICE_DRIVER_VULKAN_H