Skip to content
0.2.0-dev Download ZIP
835 lines ·38.8 KB Raw
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
31#pragma once
32
33#include "core/templates/hash_map.h"
34#include "core/templates/paged_allocator.h"
35#include "core/templates/rb_map.h"
36#include "drivers/vulkan/rendering_context_driver_vulkan.h"
37#include "drivers/vulkan/rendering_shader_container_vulkan.h"
38#include "servers/rendering/rendering_device_driver.h"
39
40#ifdef DEBUG_ENABLED
41#ifndef _MSC_VER
42#define _DEBUG
43#endif
44#endif
45#include <thirdparty/re-spirv/re-spirv.h>
46#include <thirdparty/vulkan/vk_mem_alloc.h>
47
48#include <drivers/vulkan/godot_vulkan.h>
49
50class FileAccess;
51
52// Design principles:
53// - Vulkan structs are zero-initialized and fields not requiring a non-zero value are omitted (except in cases where expresivity reasons apply).
54class RenderingDeviceDriverVulkan : public RenderingDeviceDriver {
55 /*****************/
56 /**** GENERIC ****/
57 /*****************/
58
59 struct CommandQueue;
60 struct SwapChain;
61 struct CommandBufferInfo;
62 struct RenderPassInfo;
63 struct Framebuffer;
64
65 struct Queue {
66 VkQueue queue = VK_NULL_HANDLE;
67 uint32_t virtual_count = 0;
68 BinaryMutex submit_mutex;
69 };
70
71 struct SubgroupCapabilities {
72 uint32_t size = 0;
73 uint32_t min_size = 0;
74 uint32_t max_size = 0;
75 VkShaderStageFlags supported_stages = 0;
76 VkSubgroupFeatureFlags supported_operations = 0;
77 VkBool32 quad_operations_in_all_stages = false;
78 bool size_control_is_supported = false;
79
80 uint32_t supported_stages_flags_rd() const;
81 String supported_stages_desc() const;
82 uint32_t supported_operations_flags_rd() const;
83 String supported_operations_desc() const;
84 };
85
86 struct ShaderCapabilities {
87 bool shader_float16_is_supported = false;
88 bool shader_int8_is_supported = false;
89 };
90
91 struct StorageBufferCapabilities {
92 bool storage_buffer_16_bit_access_is_supported = false;
93 bool uniform_and_storage_buffer_16_bit_access_is_supported = false;
94 bool storage_push_constant_16_is_supported = false;
95 bool storage_input_output_16 = false;
96 };
97
98 struct AccelerationStructureCapabilities {
99 bool acceleration_structure_support = false;
100 uint32_t min_acceleration_structure_scratch_offset_alignment = 0;
101 };
102
103 struct RaytracingCapabilities {
104 bool raytracing_pipeline_support = false;
105 uint32_t shader_group_handle_size = 0;
106 uint32_t shader_group_handle_alignment = 0;
107 uint32_t shader_group_handle_size_aligned = 0;
108 uint32_t shader_group_base_alignment = 0;
109 bool validation = false;
110 };
111
112 struct DeviceFunctions {
113 PFN_vkCreateSwapchainKHR CreateSwapchainKHR = nullptr;
114 PFN_vkDestroySwapchainKHR DestroySwapchainKHR = nullptr;
115 PFN_vkGetSwapchainImagesKHR GetSwapchainImagesKHR = nullptr;
116 PFN_vkAcquireNextImageKHR AcquireNextImageKHR = nullptr;
117 PFN_vkQueuePresentKHR QueuePresentKHR = nullptr;
118 PFN_vkCreateRenderPass2KHR CreateRenderPass2KHR = nullptr;
119 PFN_vkCmdEndRenderPass2KHR EndRenderPass2KHR = nullptr;
120
121 // Debug marker extensions.
122 PFN_vkCmdDebugMarkerBeginEXT CmdDebugMarkerBeginEXT = nullptr;
123 PFN_vkCmdDebugMarkerEndEXT CmdDebugMarkerEndEXT = nullptr;
124 PFN_vkCmdDebugMarkerInsertEXT CmdDebugMarkerInsertEXT = nullptr;
125 PFN_vkDebugMarkerSetObjectNameEXT DebugMarkerSetObjectNameEXT = nullptr;
126
127 // Debug device fault.
128 PFN_vkGetDeviceFaultInfoEXT GetDeviceFaultInfoEXT = nullptr;
129
130 // Raytracing extensions.
131 PFN_vkCreateAccelerationStructureKHR CreateAccelerationStructureKHR = nullptr;
132 PFN_vkDestroyAccelerationStructureKHR DestroyAccelerationStructureKHR = nullptr;
133 PFN_vkGetAccelerationStructureBuildSizesKHR GetAccelerationStructureBuildSizesKHR = nullptr;
134 PFN_vkCmdBuildAccelerationStructuresKHR CmdBuildAccelerationStructuresKHR = nullptr;
135 PFN_vkCreateRayTracingPipelinesKHR CreateRaytracingPipelinesKHR = nullptr;
136 PFN_vkGetRayTracingShaderGroupHandlesKHR GetRayTracingShaderGroupHandlesKHR = nullptr;
137 PFN_vkCmdTraceRaysKHR CmdTraceRaysKHR = nullptr;
138 };
139 // Debug marker extensions.
140 VkDebugReportObjectTypeEXT _convert_to_debug_report_objectType(VkObjectType p_object_type);
141
142 VkDevice vk_device = VK_NULL_HANDLE;
143 RenderingContextDriverVulkan *context_driver = nullptr;
144 RenderingContextDriver::Device context_device = {};
145 uint32_t frame_count = 1;
146 VkPhysicalDevice physical_device = VK_NULL_HANDLE;
147 VkPhysicalDeviceProperties physical_device_properties = {};
148 VkPhysicalDeviceFeatures physical_device_features = {};
149 VkPhysicalDeviceFeatures requested_device_features = {};
150 HashMap<CharString, bool> requested_device_extensions;
151 HashSet<CharString> enabled_device_extension_names;
152 TightLocalVector<TightLocalVector<Queue>> queue_families;
153 TightLocalVector<VkQueueFamilyProperties> queue_family_properties;
154 RDD::Capabilities device_capabilities;
155 SubgroupCapabilities subgroup_capabilities;
156 MultiviewCapabilities multiview_capabilities;
157 FragmentShadingRateCapabilities fsr_capabilities;
158 FragmentDensityMapCapabilities fdm_capabilities;
159 ShaderCapabilities shader_capabilities;
160 StorageBufferCapabilities storage_buffer_capabilities;
161 RenderingShaderContainerFormatVulkan shader_container_format;
162 bool buffer_device_address_support = false;
163 bool vulkan_memory_model_support = false;
164 bool vulkan_memory_model_device_scope_support = false;
165 AccelerationStructureCapabilities acceleration_structure_capabilities;
166 bool ray_query_support = false;
167 RaytracingCapabilities raytracing_capabilities;
168 bool pipeline_cache_control_support = false;
169 bool device_fault_support = false;
170 bool framebuffer_depth_resolve = false;
171#if defined(VK_TRACK_DEVICE_MEMORY)
172 bool device_memory_report_support = false;
173#endif
174 bool device_local_host_visible_host_coherent_memory_support = false;
175#if defined(SWAPPY_FRAME_PACING_ENABLED)
176 // Swappy frame pacer for Android.
177 bool swappy_frame_pacer_enable = false;
178 uint8_t swappy_mode = 2; // See default value for display/window/frame_pacing/android/swappy_mode.
179#endif
180 DeviceFunctions device_functions;
181
182 struct PendingFlushes {
183 LocalVector<VmaAllocation> allocations;
184 LocalVector<VkDeviceSize> offsets;
185 LocalVector<VkDeviceSize> sizes;
186 };
187
188 PendingFlushes pending_flushes;
189
190 struct PipelineStatistics {
191 Ref<FileAccess> file_access;
192 Mutex file_access_mutex;
193 };
194
195 PipelineStatistics pipeline_statistics;
196 DriverWorkarounds driver_workarounds;
197 BinaryMutex *powervr_rogue_shader_crash_workaround_mutex = nullptr;
198
199 void _register_requested_device_extension(const CharString &p_extension_name, bool p_required);
200 Error _initialize_device_extensions();
201 void _check_driver_workarounds(const VkPhysicalDeviceProperties &p_device_properties, const VkPhysicalDeviceDriverPropertiesKHR *p_driver_properties);
202 void _get_device_properties();
203 Error _check_device_features();
204 Error _check_device_capabilities();
205 void _choose_vrs_capabilities();
206 Error _add_queue_create_info(LocalVector<VkDeviceQueueCreateInfo> &r_queue_create_info);
207 Error _initialize_device(const LocalVector<VkDeviceQueueCreateInfo> &p_queue_create_info);
208 Error _initialize_allocator();
209 Error _initialize_pipeline_cache();
210 VkResult _create_render_pass(VkDevice p_device, const VkRenderPassCreateInfo2 *p_create_info, const VkAllocationCallbacks *p_allocator, VkRenderPass *p_render_pass);
211 bool _release_image_semaphore(CommandQueue *p_command_queue, uint32_t p_semaphore_index, bool p_release_on_swap_chain);
212 bool _recreate_image_semaphore(CommandQueue *p_command_queue, uint32_t p_semaphore_index, bool p_release_on_swap_chain);
213 void _set_object_name(VkObjectType p_object_type, uint64_t p_object_handle, String p_object_name);
214
215public:
216 Error initialize(uint32_t p_device_index, uint32_t p_frame_count) override final;
217
218private:
219 /****************/
220 /**** MEMORY ****/
221 /****************/
222
223 VmaAllocator allocator = nullptr;
224 HashMap<uint32_t, VmaPool> small_allocs_pools;
225
226 VmaPool _find_or_create_small_allocs_pool(uint32_t p_mem_type_index);
227
228private:
229#if defined(DEBUG_ENABLED) || defined(DEV_ENABLED)
230 // It's a circular buffer.
231 BufferID breadcrumb_buffer;
232 uint32_t breadcrumb_offset = 0u;
233 uint32_t breadcrumb_id = 0u;
234#endif
235
236public:
237 /*****************/
238 /**** BUFFERS ****/
239 /*****************/
240 struct BufferInfo {
241 VkBuffer vk_buffer = VK_NULL_HANDLE;
242 struct {
243 VmaAllocation handle = nullptr;
244 uint64_t size = UINT64_MAX;
245 } allocation;
246 uint64_t size = 0;
247 VkBufferView vk_view = VK_NULL_HANDLE; // For texel buffers.
248 // If dynamic buffer, then its range is [0; RenderingDeviceDriverVulkan::frame_count)
249 // else it's UINT32_MAX.
250 uint32_t frame_idx = UINT32_MAX;
251
252 bool is_dynamic() const { return frame_idx != UINT32_MAX; }
253 };
254
255 struct BufferDynamicInfo : BufferInfo {
256 uint8_t *persistent_ptr = nullptr;
257#ifdef DEBUG_ENABLED
258 // For tracking that a persistent buffer isn't mapped twice in the same frame.
259 uint64_t last_frame_mapped = 0;
260#endif
261 };
262
263 virtual BufferID buffer_create(uint64_t p_size, BitField<BufferUsageBits> p_usage, MemoryAllocationType p_allocation_type, uint64_t p_frames_drawn) override final;
264 virtual bool buffer_set_texel_format(BufferID p_buffer, DataFormat p_format) override final;
265 virtual void buffer_free(BufferID p_buffer) override final;
266 virtual uint64_t buffer_get_allocation_size(BufferID p_buffer) override final;
267 virtual uint8_t *buffer_map(BufferID p_buffer) override final;
268 virtual void buffer_unmap(BufferID p_buffer) override final;
269 virtual uint8_t *buffer_persistent_map_advance(BufferID p_buffer, uint64_t p_frames_drawn) override final;
270 virtual uint64_t buffer_get_dynamic_offsets(Span<BufferID> p_buffers) override final;
271 virtual void buffer_flush(BufferID p_buffer) override final;
272 virtual uint64_t buffer_get_device_address(BufferID p_buffer) override final;
273
274 /*****************/
275 /**** TEXTURE ****/
276 /*****************/
277
278 struct TextureInfo {
279 VkImage vk_image = VK_NULL_HANDLE;
280 VkImageView vk_view = VK_NULL_HANDLE;
281 DataFormat rd_format = DATA_FORMAT_MAX;
282 VkImageCreateInfo vk_create_info = {};
283 VkImageViewCreateInfo vk_view_create_info = {};
284 struct {
285 VmaAllocation handle = nullptr;
286 VmaAllocationInfo info = {};
287 } allocation; // All 0/null if just a view.
288 bool is_subsampled = false;
289#ifdef DEBUG_ENABLED
290 bool created_from_extension = false;
291 bool transient = false;
292#endif
293 };
294
295 VkSampleCountFlagBits _ensure_supported_sample_count(TextureSamples p_requested_sample_count);
296
297public:
298 virtual TextureID texture_create(const TextureFormat &p_format, const TextureView &p_view) override final;
299 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, uint32_t p_mipmaps) override final;
300 virtual TextureID texture_create_shared(TextureID p_original_texture, const TextureView &p_view) override final;
301 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;
302 virtual void texture_free(TextureID p_texture) override final;
303 virtual uint64_t texture_get_allocation_size(TextureID p_texture) override final;
304 virtual void texture_get_copyable_layout(TextureID p_texture, const TextureSubresource &p_subresource, TextureCopyableLayout *r_layout) override final;
305 virtual Vector<uint8_t> texture_get_data(TextureID p_texture, uint32_t p_layer) override final;
306 virtual BitField<TextureUsageBits> texture_get_usages_supported_by_format(DataFormat p_format, bool p_cpu_readable) override final;
307 virtual bool texture_can_make_shared_with_format(TextureID p_texture, DataFormat p_format, bool &r_raw_reinterpretation) override final;
308
309 /*****************/
310 /**** SAMPLER ****/
311 /*****************/
312public:
313 virtual SamplerID sampler_create(const SamplerState &p_state) final override;
314 virtual void sampler_free(SamplerID p_sampler) final override;
315 virtual bool sampler_is_format_supported_for_filter(DataFormat p_format, SamplerFilter p_filter) override final;
316
317 /**********************/
318 /**** VERTEX ARRAY ****/
319 /**********************/
320private:
321 struct VertexFormatInfo {
322 TightLocalVector<VkVertexInputBindingDescription> vk_bindings;
323 TightLocalVector<VkVertexInputAttributeDescription> vk_attributes;
324 VkPipelineVertexInputStateCreateInfo vk_create_info = {};
325 };
326
327public:
328 virtual VertexFormatID vertex_format_create(Span<VertexAttribute> p_vertex_attribs, const VertexAttributeBindingsMap &p_vertex_bindings) override final;
329 virtual void vertex_format_free(VertexFormatID p_vertex_format) override final;
330
331 /******************/
332 /**** BARRIERS ****/
333 /******************/
334
335 virtual void command_pipeline_barrier(
336 CommandBufferID p_cmd_buffer,
337 BitField<PipelineStageBits> p_src_stages,
338 BitField<PipelineStageBits> p_dst_stages,
339 VectorView<MemoryAccessBarrier> p_memory_barriers,
340 VectorView<BufferBarrier> p_buffer_barriers,
341 VectorView<TextureBarrier> p_texture_barriers,
342 VectorView<AccelerationStructureBarrier> p_acceleration_structure_barriers) override final;
343
344 /****************/
345 /**** FENCES ****/
346 /****************/
347
348private:
349 struct Fence {
350 VkFence vk_fence = VK_NULL_HANDLE;
351 CommandQueue *queue_signaled_from = nullptr;
352 };
353
354public:
355 virtual FenceID fence_create() override final;
356 virtual Error fence_wait(FenceID p_fence) override final;
357 virtual void fence_free(FenceID p_fence) override final;
358
359 /********************/
360 /**** SEMAPHORES ****/
361 /********************/
362
363 virtual SemaphoreID semaphore_create() override final;
364 virtual void semaphore_free(SemaphoreID p_semaphore) override final;
365
366 /******************/
367 /**** COMMANDS ****/
368 /******************/
369
370 // ----- QUEUE FAMILY -----
371
372 virtual CommandQueueFamilyID command_queue_family_get(BitField<CommandQueueFamilyBits> p_cmd_queue_family_bits, RenderingContextDriver::SurfaceID p_surface = 0) override final;
373
374 // ----- QUEUE -----
375private:
376 struct CommandQueue {
377 LocalVector<VkSemaphore> image_semaphores;
378 LocalVector<SwapChain *> image_semaphores_swap_chains;
379 LocalVector<uint32_t> pending_semaphores_for_execute;
380 LocalVector<uint32_t> pending_semaphores_for_fence;
381 LocalVector<uint32_t> free_image_semaphores;
382 LocalVector<Pair<Fence *, uint32_t>> image_semaphores_for_fences;
383 uint32_t queue_family = 0;
384 uint32_t queue_index = 0;
385 };
386
387public:
388 virtual CommandQueueID command_queue_create(CommandQueueFamilyID p_cmd_queue_family, bool p_identify_as_main_queue = false) override final;
389 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;
390 virtual void command_queue_free(CommandQueueID p_cmd_queue) override final;
391
392private:
393 // ----- POOL -----
394
395 struct CommandPool {
396 VkCommandPool vk_command_pool = VK_NULL_HANDLE;
397 CommandBufferType buffer_type = COMMAND_BUFFER_TYPE_PRIMARY;
398 LocalVector<CommandBufferInfo *> command_buffers_created;
399 };
400
401public:
402 virtual CommandPoolID command_pool_create(CommandQueueFamilyID p_cmd_queue_family, CommandBufferType p_cmd_buffer_type) override final;
403 virtual bool command_pool_reset(CommandPoolID p_cmd_pool) override final;
404 virtual void command_pool_free(CommandPoolID p_cmd_pool) override final;
405
406private:
407 // ----- BUFFER -----
408
409 struct CommandBufferInfo {
410 VkCommandBuffer vk_command_buffer = VK_NULL_HANDLE;
411 Framebuffer *active_framebuffer = nullptr;
412 RenderPassInfo *active_render_pass = nullptr;
413 };
414
415public:
416 virtual CommandBufferID command_buffer_create(CommandPoolID p_cmd_pool) override final;
417 virtual bool command_buffer_begin(CommandBufferID p_cmd_buffer) override final;
418 virtual bool command_buffer_begin_secondary(CommandBufferID p_cmd_buffer, RenderPassID p_render_pass, uint32_t p_subpass, FramebufferID p_framebuffer) override final;
419 virtual void command_buffer_end(CommandBufferID p_cmd_buffer) override final;
420 virtual void command_buffer_execute_secondary(CommandBufferID p_cmd_buffer, VectorView<CommandBufferID> p_secondary_cmd_buffers) override final;
421
422 /********************/
423 /**** SWAP CHAIN ****/
424 /********************/
425
426private:
427 struct SwapChain {
428 VkSwapchainKHR vk_swapchain = VK_NULL_HANDLE;
429 RenderingContextDriver::SurfaceID surface = RenderingContextDriver::SurfaceID();
430 VkFormat format = VK_FORMAT_UNDEFINED;
431 VkColorSpaceKHR color_space = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR;
432 RDD::ColorSpace rdd_color_space = RDD::COLOR_SPACE_REC709_NONLINEAR_SRGB;
433 TightLocalVector<VkImage> images;
434 TightLocalVector<VkImageView> image_views;
435 TightLocalVector<VkSemaphore> present_semaphores;
436 TightLocalVector<FramebufferID> framebuffers;
437 LocalVector<CommandQueue *> command_queues_acquired;
438 LocalVector<uint32_t> command_queues_acquired_semaphores;
439 RenderPassID render_pass;
440 int pre_transform_rotation_degrees = 0;
441 uint32_t image_index = 0;
442#ifdef ANDROID_ENABLED
443 uint64_t refresh_duration = 0;
444#endif
445 };
446
447 bool _determine_swap_chain_format(RenderingContextDriver::SurfaceID p_surface, VkFormat &r_format, VkColorSpaceKHR &r_color_space, RDD::ColorSpace &r_rdd_color_space);
448 void _swap_chain_release(SwapChain *p_swap_chain);
449
450public:
451 virtual SwapChainID swap_chain_create(RenderingContextDriver::SurfaceID p_surface) override final;
452 virtual Error swap_chain_resize(CommandQueueID p_cmd_queue, SwapChainID p_swap_chain, uint32_t p_desired_framebuffer_count) override final;
453 virtual FramebufferID swap_chain_acquire_framebuffer(CommandQueueID p_cmd_queue, SwapChainID p_swap_chain, bool &r_resize_required) override final;
454 virtual RenderPassID swap_chain_get_render_pass(SwapChainID p_swap_chain) override final;
455 virtual int swap_chain_get_pre_rotation_degrees(SwapChainID p_swap_chain) override final;
456 virtual DataFormat swap_chain_get_format(SwapChainID p_swap_chain) override final;
457 virtual ColorSpace swap_chain_get_color_space(SwapChainID p_swap_chain) override final;
458 virtual bool swap_chain_get_hdr_output_supported(SwapChainID p_swap_chain) override final;
459 virtual void swap_chain_set_max_fps(SwapChainID p_swap_chain, int p_max_fps) override final;
460 virtual void swap_chain_free(SwapChainID p_swap_chain) override final;
461
462private:
463 /*********************/
464 /**** FRAMEBUFFER ****/
465 /*********************/
466
467 struct Framebuffer {
468 VkFramebuffer vk_framebuffer = VK_NULL_HANDLE;
469
470 // Only filled in if the framebuffer uses a fragment density map with offsets. Unused otherwise.
471 uint32_t fragment_density_map_offsets_layers = 0;
472
473 // Only filled in by a framebuffer created by a swap chain. Unused otherwise.
474 VkImage swap_chain_image = VK_NULL_HANDLE;
475 VkImageSubresourceRange swap_chain_image_subresource_range = {};
476 bool swap_chain_acquired = false;
477 };
478
479public:
480 virtual FramebufferID framebuffer_create(RenderPassID p_render_pass, VectorView<TextureID> p_attachments, uint32_t p_width, uint32_t p_height) override final;
481 virtual void framebuffer_free(FramebufferID p_framebuffer) override final;
482
483 /****************/
484 /**** SHADER ****/
485 /****************/
486private:
487 struct ShaderInfo {
488 String name;
489 VkShaderStageFlags vk_push_constant_stages = 0;
490 TightLocalVector<VkPipelineShaderStageCreateInfo> vk_stages_create_info;
491 TightLocalVector<VkDescriptorSetLayout> vk_descriptor_set_layouts;
492 TightLocalVector<respv::Shader> respv_stage_shaders;
493 TightLocalVector<Vector<uint8_t>> spirv_stage_bytes;
494 TightLocalVector<uint64_t> original_stage_size;
495 VkPipelineLayout vk_pipeline_layout = VK_NULL_HANDLE;
496 };
497
498public:
499 virtual ShaderID shader_create_from_container(const Ref<RenderingShaderContainer> &p_shader_container, const Vector<ImmutableSampler> &p_immutable_samplers) override final;
500 virtual void shader_free(ShaderID p_shader) override final;
501
502 virtual void shader_destroy_modules(ShaderID p_shader) override final;
503 /*********************/
504 /**** UNIFORM SET ****/
505 /*********************/
506
507 // Descriptor sets require allocation from a pool.
508 // The documentation on how to use pools properly
509 // is scarce, and the documentation is strange.
510 //
511 // Basically, you can mix and match pools as you
512 // like, but you'll run into fragmentation issues.
513 // Because of this, the recommended approach is to
514 // create a pool for every descriptor set type, as
515 // this prevents fragmentation.
516 //
517 // This is implemented here as a having a list of
518 // pools (each can contain up to 64 sets) for each
519 // set layout. The amount of sets for each type
520 // is used as the key.
521
522private:
523 static const uint32_t MAX_UNIFORM_POOL_ELEMENT = 65535;
524
525 struct DescriptorSetPoolKey {
526 uint16_t uniform_type[UNIFORM_TYPE_MAX] = {};
527
528 bool operator<(const DescriptorSetPoolKey &p_other) const {
529 return memcmp(uniform_type, p_other.uniform_type, sizeof(uniform_type)) < 0;
530 }
531 };
532
533 using DescriptorSetPools = RBMap<DescriptorSetPoolKey, HashMap<VkDescriptorPool, uint32_t>>;
534 DescriptorSetPools descriptor_set_pools;
535 uint32_t max_descriptor_sets_per_pool = 0;
536
537 HashMap<int, DescriptorSetPools> linear_descriptor_set_pools;
538 bool linear_descriptor_pools_enabled = true;
539 VkDescriptorPool _descriptor_set_pool_create(const DescriptorSetPoolKey &p_key, bool p_linear_pool);
540 void _descriptor_set_pool_unreference(DescriptorSetPools::Iterator p_pool_sets_it, VkDescriptorPool p_vk_descriptor_pool, int p_linear_pool_index);
541
542 // Global flag to toggle usage of immutable sampler when creating pipeline layouts.
543 // It cannot change after creating the PSOs, since we need to skipping samplers when creating uniform sets.
544 bool immutable_samplers_enabled = true;
545
546 struct UniformSetInfo {
547 VkDescriptorSet vk_descriptor_set = VK_NULL_HANDLE;
548 VkDescriptorPool vk_descriptor_pool = VK_NULL_HANDLE;
549 VkDescriptorPool vk_linear_descriptor_pool = VK_NULL_HANDLE;
550 DescriptorSetPools::Iterator pool_sets_it;
551 TightLocalVector<const BufferInfo *, uint32_t> dynamic_buffers;
552 };
553
554 bool adreno_5xx_empty_descriptor_set_layout_workaround = false;
555
556public:
557 virtual UniformSetID uniform_set_create(VectorView<BoundUniform> p_uniforms, ShaderID p_shader, uint32_t p_set_index, int p_linear_pool_index) override final;
558 virtual void linear_uniform_set_pools_reset(int p_linear_pool_index) override final;
559 virtual void uniform_set_free(UniformSetID p_uniform_set) override final;
560 virtual bool uniform_sets_have_linear_pools() const override final;
561 virtual uint32_t uniform_sets_get_dynamic_offsets(VectorView<UniformSetID> p_uniform_sets, ShaderID p_shader, uint32_t p_first_set_index, uint32_t p_set_count) const override final;
562
563 // ----- COMMANDS -----
564
565 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;
566
567 /******************/
568 /**** TRANSFER ****/
569 /******************/
570
571 virtual void command_clear_buffer(CommandBufferID p_cmd_buffer, BufferID p_buffer, uint64_t p_offset, uint64_t p_size) override final;
572 virtual void command_copy_buffer(CommandBufferID p_cmd_buffer, BufferID p_src_buffer, BufferID p_dst_buffer, VectorView<BufferCopyRegion> p_regions) override final;
573
574 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;
575 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;
576 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;
577 virtual void command_clear_depth_stencil_texture(CommandBufferID p_cmd_buffer, TextureID p_texture, TextureLayout p_texture_layout, float p_depth, uint8_t p_stencil, const TextureSubresourceRange &p_subresources) override final;
578
579 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;
580 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;
581
582 /******************/
583 /**** PIPELINE ****/
584 /******************/
585private:
586 struct PipelineCacheHeader {
587 uint32_t magic = 0;
588 uint32_t data_size = 0;
589 uint64_t data_hash = 0;
590 uint32_t vendor_id = 0;
591 uint32_t device_id = 0;
592 uint32_t driver_version = 0;
593 uint8_t uuid[VK_UUID_SIZE] = {};
594 uint8_t driver_abi = 0;
595 };
596
597 struct PipelineCache {
598 String file_path;
599 size_t current_size = 0;
600 Vector<uint8_t> buffer; // Header then data.
601 VkPipelineCache vk_cache = VK_NULL_HANDLE;
602 };
603
604 static int caching_instance_count;
605 PipelineCache pipelines_cache;
606 String pipeline_cache_id;
607 HashMap<uint64_t, bool> has_comp_alpha;
608
609public:
610 virtual void pipeline_free(PipelineID p_pipeline) override final;
611
612 // ----- BINDING -----
613
614 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;
615
616 // ----- CACHE -----
617
618 virtual bool pipeline_cache_create(const Vector<uint8_t> &p_data) override final;
619 virtual void pipeline_cache_free() override final;
620 virtual size_t pipeline_cache_query_size() override final;
621 virtual Vector<uint8_t> pipeline_cache_serialize() override final;
622
623 /*******************/
624 /**** RENDERING ****/
625 /*******************/
626
627private:
628 // ----- SUBPASS -----
629
630 struct RenderPassInfo {
631 VkRenderPass vk_render_pass = VK_NULL_HANDLE;
632 bool uses_fragment_density_map = false;
633 };
634
635public:
636 virtual RenderPassID render_pass_create(VectorView<Attachment> p_attachments, VectorView<Subpass> p_subpasses, VectorView<SubpassDependency> p_subpass_dependencies, uint32_t p_view_count, AttachmentReference p_fragment_density_map_attachment) override final;
637 virtual void render_pass_free(RenderPassID p_render_pass) override final;
638
639 // ----- COMMANDS -----
640
641 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;
642 virtual void command_end_render_pass(CommandBufferID p_cmd_buffer) override final;
643 virtual void command_next_render_subpass(CommandBufferID p_cmd_buffer, CommandBufferType p_cmd_buffer_type) override final;
644 virtual void command_render_set_viewport(CommandBufferID p_cmd_buffer, VectorView<Rect2i> p_viewports) override final;
645 virtual void command_render_set_scissor(CommandBufferID p_cmd_buffer, VectorView<Rect2i> p_scissors) override final;
646 virtual void command_render_clear_attachments(CommandBufferID p_cmd_buffer, VectorView<AttachmentClear> p_attachment_clears, VectorView<Rect2i> p_rects) override final;
647
648 // Binding.
649 virtual void command_bind_render_pipeline(CommandBufferID p_cmd_buffer, PipelineID p_pipeline) override final;
650 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, uint32_t p_dynamic_offsets) override final;
651
652 // Drawing.
653 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;
654 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;
655 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;
656 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;
657 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;
658 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;
659
660 // Buffer binding.
661 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, uint64_t p_dynamic_offsets) override final;
662 virtual void command_render_bind_index_buffer(CommandBufferID p_cmd_buffer, BufferID p_buffer, IndexBufferFormat p_format, uint64_t p_offset) override final;
663
664 // Dynamic state.
665 virtual void command_render_set_blend_constants(CommandBufferID p_cmd_buffer, const Color &p_constants) override final;
666 virtual void command_render_set_line_width(CommandBufferID p_cmd_buffer, float p_width) override final;
667
668 // ----- PIPELINE -----
669
670 virtual PipelineID render_pipeline_create(
671 ShaderID p_shader,
672 VertexFormatID p_vertex_format,
673 RenderPrimitive p_render_primitive,
674 PipelineRasterizationState p_rasterization_state,
675 PipelineMultisampleState p_multisample_state,
676 PipelineDepthStencilState p_depth_stencil_state,
677 PipelineColorBlendState p_blend_state,
678 VectorView<int32_t> p_color_attachments,
679 BitField<PipelineDynamicStateFlags> p_dynamic_state,
680 RenderPassID p_render_pass,
681 uint32_t p_render_subpass,
682 VectorView<PipelineSpecializationConstant> p_specialization_constants) override final;
683
684 /*****************/
685 /**** COMPUTE ****/
686 /*****************/
687
688 // ----- COMMANDS -----
689
690 // Binding.
691 virtual void command_bind_compute_pipeline(CommandBufferID p_cmd_buffer, PipelineID p_pipeline) override final;
692 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, uint32_t p_dynamic_offsets) override final;
693
694 // Dispatching.
695 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;
696 virtual void command_compute_dispatch_indirect(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset) override final;
697
698 // ----- PIPELINE -----
699
700 virtual PipelineID compute_pipeline_create(ShaderID p_shader, VectorView<PipelineSpecializationConstant> p_specialization_constants) override final;
701
702 /********************/
703 /**** RAYTRACING ****/
704 /********************/
705
706 // ----- ACCELERATION STRUCTURE -----
707
708 struct AccelerationStructureInfo {
709 VkAccelerationStructureKHR vk_acceleration_structure = VK_NULL_HANDLE;
710 // Buffer used for the structure
711 RDD::BufferID buffer;
712
713 // Alignment of the scratch buffer for building the structure
714 uint32_t scratch_alignment;
715 // Size of the scratch buffer for building the structure
716 uint32_t scratch_size;
717
718 // Required for building
719 TightLocalVector<VkAccelerationStructureGeometryKHR> geometries;
720 VkAccelerationStructureBuildGeometryInfoKHR build_info;
721 TightLocalVector<VkAccelerationStructureBuildRangeInfoKHR> range_infos;
722 };
723
724 virtual AccelerationStructureID blas_create(VectorView<AccelerationStructureGeometry> p_geometries, BitField<AccelerationStructureFlagBits> p_flags) override final;
725 virtual AccelerationStructureID tlas_create(uint32_t p_max_instance_count, BitField<AccelerationStructureFlagBits> p_flags) override final;
726 virtual void acceleration_structure_instance_write(uint8_t *r_driver_instance, const AccelerationStructureInstance &p_instance) override final;
727 virtual void acceleration_structure_free(AccelerationStructureID p_acceleration_structure) override final;
728 virtual uint32_t acceleration_structure_get_scratch_size_bytes(AccelerationStructureID p_acceleration_structure) override final;
729
730private:
731 void _acceleration_structure_create(VkAccelerationStructureTypeKHR p_type, VkAccelerationStructureBuildSizesInfoKHR p_size_info, AccelerationStructureInfo *r_accel_info);
732
733private:
734 VkStridedDeviceAddressRegionKHR _sbt_to_vk_strided_device_address_region(const ShaderBindingTable &p_sbt);
735
736public:
737 // ----- COMMANDS -----
738 virtual void command_build_blas(CommandBufferID p_cmd_buffer, AccelerationStructureID p_acceleration_structure, BufferID p_scratch_buffer) override final;
739 virtual void command_build_tlas(CommandBufferID p_cmd_buffer, AccelerationStructureID p_acceleration_structure, BufferID p_scratch_buffer, BufferID p_instance_buffer, uint32_t p_instance_offset, uint32_t p_instance_count) override final;
740 virtual void command_bind_raytracing_pipeline(CommandBufferID p_cmd_buffer, RaytracingPipelineID p_pipeline) override final;
741 virtual void command_bind_raytracing_uniform_set(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index) override final;
742 virtual void command_trace_rays(CommandBufferID p_cmd_buffer, const ShaderBindingTable &p_raygen_sbt, const ShaderBindingTable &p_miss_sbt, const ShaderBindingTable &p_hit_sbt, uint32_t p_width, uint32_t p_height, uint32_t p_depth) override final;
743
744public:
745 // ----- PIPELINE -----
746 virtual RaytracingPipelineID raytracing_pipeline_create(VectorView<PipelineShader> p_shaders, VectorView<uint32_t> p_raygen_shader_indices, VectorView<uint32_t> p_miss_shader_indices, VectorView<HitGroup> p_hit_groups, uint32_t p_max_trace_recursion_depth, ShaderID p_layout_defining_shader) override final;
747 virtual void raytracing_pipeline_free(RaytracingPipelineID p_pipeline) override final;
748
749 virtual bool raytracing_pipeline_get_shader_group_handles(RaytracingPipelineID p_pipeline, uint32_t p_group_index_offset, VectorView<uint32_t> p_group_indices, uint8_t *r_data, uint32_t p_data_stride_bytes) override final;
750
751 /*****************/
752 /**** QUERIES ****/
753 /*****************/
754
755 // ----- TIMESTAMP -----
756
757 // Basic.
758 virtual QueryPoolID timestamp_query_pool_create(uint32_t p_query_count) override final;
759 virtual void timestamp_query_pool_free(QueryPoolID p_pool_id) override final;
760 virtual void timestamp_query_pool_get_results(QueryPoolID p_pool_id, uint32_t p_query_count, uint64_t *r_results) override final;
761 virtual uint64_t timestamp_query_result_to_time(uint64_t p_result) override final;
762
763 // Commands.
764 virtual void command_timestamp_query_pool_reset(CommandBufferID p_cmd_buffer, QueryPoolID p_pool_id, uint32_t p_query_count) override final;
765 virtual void command_timestamp_write(CommandBufferID p_cmd_buffer, QueryPoolID p_pool_id, uint32_t p_index) override final;
766
767 /****************/
768 /**** LABELS ****/
769 /****************/
770
771 virtual void command_begin_label(CommandBufferID p_cmd_buffer, const char *p_label_name, const Color &p_color) override final;
772 virtual void command_end_label(CommandBufferID p_cmd_buffer) override final;
773
774 /****************/
775 /**** DEBUG *****/
776 /****************/
777 virtual void command_insert_breadcrumb(CommandBufferID p_cmd_buffer, uint32_t p_data) override final;
778 void print_lost_device_info();
779 void on_device_lost() const;
780 static String get_vulkan_result(VkResult err);
781
782 /********************/
783 /**** SUBMISSION ****/
784 /********************/
785
786 virtual void begin_segment(uint32_t p_frame_index, uint32_t p_frames_drawn) override final;
787 virtual void end_segment() override final;
788
789 /**************/
790 /**** MISC ****/
791 /**************/
792
793 virtual void set_object_name(ObjectType p_type, ID p_driver_id, const String &p_name) override final;
794 virtual uint64_t get_resource_native_handle(DriverResource p_type, ID p_driver_id) override final;
795 virtual uint64_t get_total_memory_used() override final;
796 virtual uint64_t get_lazily_memory_used() override final;
797 virtual uint64_t limit_get(Limit p_limit) override final;
798 virtual uint64_t api_trait_get(ApiTrait p_trait) override final;
799 virtual bool has_feature(Features p_feature) override final;
800 virtual const MultiviewCapabilities &get_multiview_capabilities() override final;
801 virtual const FragmentShadingRateCapabilities &get_fragment_shading_rate_capabilities() override final;
802 virtual const FragmentDensityMapCapabilities &get_fragment_density_map_capabilities() override final;
803 virtual String get_api_name() const override final;
804 virtual String get_api_version() const override final;
805 virtual String get_pipeline_cache_uuid() const override final;
806 virtual const Capabilities &get_capabilities() const override final;
807 virtual const RenderingShaderContainerFormat &get_shader_container_format() const override final;
808
809 virtual bool is_composite_alpha_supported(CommandQueueID p_queue) const override final;
810
811 virtual DriverWorkarounds get_driver_workarounds() const override final;
812
813private:
814 /*********************/
815 /**** BOOKKEEPING ****/
816 /*********************/
817
818 using VersatileResource = VersatileResourceTemplate<
819 BufferInfo,
820 TextureInfo,
821 VertexFormatInfo,
822 ShaderInfo,
823 UniformSetInfo,
824 RenderPassInfo,
825 CommandBufferInfo>;
826 PagedAllocator<VersatileResource, true> resources_allocator;
827
828 /******************/
829
830public:
831 RenderingDeviceDriverVulkan(RenderingContextDriverVulkan *p_context_driver);
832 virtual ~RenderingDeviceDriverVulkan();
833};
834
835using VKC = RenderingContextDriverVulkan;