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