rendering_device_vulkan.h 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129
  1. /*************************************************************************/
  2. /* rendering_device_vulkan.h */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #ifndef RENDERING_DEVICE_VULKAN_H
  31. #define RENDERING_DEVICE_VULKAN_H
  32. #include "core/oa_hash_map.h"
  33. #include "core/os/thread_safe.h"
  34. #include "core/rid_owner.h"
  35. #include "servers/rendering/rendering_device.h"
  36. #ifdef DEBUG_ENABLED
  37. #define _DEBUG
  38. #endif
  39. #include "vk_mem_alloc.h"
  40. #include <vulkan/vulkan.h>
  41. //todo:
  42. //compute
  43. //push constants
  44. //views of texture slices
  45. class VulkanContext;
  46. class RenderingDeviceVulkan : public RenderingDevice {
  47. _THREAD_SAFE_CLASS_
  48. // Miscellaneous tables that map
  49. // our enums to enums used
  50. // by vulkan.
  51. VkPhysicalDeviceLimits limits;
  52. static const VkFormat vulkan_formats[DATA_FORMAT_MAX];
  53. static const char *named_formats[DATA_FORMAT_MAX];
  54. static const VkCompareOp compare_operators[COMPARE_OP_MAX];
  55. static const VkStencilOp stencil_operations[STENCIL_OP_MAX];
  56. static const VkSampleCountFlagBits rasterization_sample_count[TEXTURE_SAMPLES_MAX];
  57. static const VkLogicOp logic_operations[RenderingDevice::LOGIC_OP_MAX];
  58. static const VkBlendFactor blend_factors[RenderingDevice::BLEND_FACTOR_MAX];
  59. static const VkBlendOp blend_operations[RenderingDevice::BLEND_OP_MAX];
  60. static const VkSamplerAddressMode address_modes[SAMPLER_REPEAT_MODE_MAX];
  61. static const VkBorderColor sampler_border_colors[SAMPLER_BORDER_COLOR_MAX];
  62. static const VkImageType vulkan_image_type[TEXTURE_TYPE_MAX];
  63. // Functions used for format
  64. // validation, and ensures the
  65. // user passes valid data.
  66. static int get_format_vertex_size(DataFormat p_format);
  67. static uint32_t get_image_format_pixel_size(DataFormat p_format);
  68. static void get_compressed_image_format_block_dimensions(DataFormat p_format, uint32_t &r_w, uint32_t &r_h);
  69. uint32_t get_compressed_image_format_block_byte_size(DataFormat p_format);
  70. static uint32_t get_compressed_image_format_pixel_rshift(DataFormat p_format);
  71. static uint32_t get_image_format_required_size(DataFormat p_format, uint32_t p_width, uint32_t p_height, uint32_t p_depth, uint32_t p_mipmaps, uint32_t *r_blockw = NULL, uint32_t *r_blockh = NULL, uint32_t *r_depth = NULL);
  72. static uint32_t get_image_required_mipmaps(uint32_t p_width, uint32_t p_height, uint32_t p_depth);
  73. static bool format_has_stencil(DataFormat p_format);
  74. /***************************/
  75. /**** ID INFRASTRUCTURE ****/
  76. /***************************/
  77. enum IDType {
  78. ID_TYPE_FRAMEBUFFER_FORMAT,
  79. ID_TYPE_VERTEX_FORMAT,
  80. ID_TYPE_DRAW_LIST,
  81. ID_TYPE_SPLIT_DRAW_LIST,
  82. ID_TYPE_COMPUTE_LIST,
  83. ID_TYPE_MAX,
  84. ID_BASE_SHIFT = 58 //5 bits for ID types
  85. };
  86. VkDevice device;
  87. Map<RID, Set<RID>> dependency_map; //IDs to IDs that depend on it
  88. Map<RID, Set<RID>> reverse_dependency_map; //same as above, but in reverse
  89. void _add_dependency(RID p_id, RID p_depends_on);
  90. void _free_dependencies(RID p_id);
  91. /*****************/
  92. /**** TEXTURE ****/
  93. /*****************/
  94. // In Vulkan, the concept of textures does not exist,
  95. // intead there is the image (the memory prety much,
  96. // the view (how the memory is interpreted) and the
  97. // sampler (how it's sampled from the shader).
  98. //
  99. // Texture here includes the first two stages, but
  100. // It's possible to create textures sharing the image
  101. // but with different views. The main use case for this
  102. // is textures that can be read as both SRGB/Linear,
  103. // or slices of a texture (a mipmap, a layer, a 3D slice)
  104. // for a framebuffer to render into it.
  105. struct Texture {
  106. VkImage image;
  107. VmaAllocation allocation;
  108. VmaAllocationInfo allocation_info;
  109. VkImageView view;
  110. TextureType type;
  111. DataFormat format;
  112. TextureSamples samples;
  113. uint32_t width;
  114. uint32_t height;
  115. uint32_t depth;
  116. uint32_t layers;
  117. uint32_t mipmaps;
  118. uint32_t usage_flags;
  119. Vector<DataFormat> allowed_shared_formats;
  120. VkImageLayout layout;
  121. uint32_t read_aspect_mask;
  122. uint32_t barrier_aspect_mask;
  123. bool bound; //bound to framebffer
  124. RID owner;
  125. };
  126. RID_Owner<Texture, true> texture_owner;
  127. uint32_t texture_upload_region_size_px;
  128. Vector<uint8_t> _texture_get_data_from_image(Texture *tex, VkImage p_image, VmaAllocation p_allocation, uint32_t p_layer, bool p_2d = false);
  129. /*****************/
  130. /**** SAMPLER ****/
  131. /*****************/
  132. RID_Owner<VkSampler> sampler_owner;
  133. /***************************/
  134. /**** BUFFER MANAGEMENT ****/
  135. /***************************/
  136. // These are temporary buffers on CPU memory that hold
  137. // the information until the CPU fetches it and places it
  138. // either on GPU buffers, or images (textures). It ensures
  139. // updates are properly synchronized with whathever the
  140. // GPU is doing.
  141. //
  142. // The logic here is as follows, only 3 of these
  143. // blocks are created at the beginning (one per frame)
  144. // they can each belong to a frame (assigned to current when
  145. // used) and they can only be reused after the same frame is
  146. // recycled.
  147. //
  148. // When CPU requires to allocate more than what is available,
  149. // more of these buffers are created. If a limit is reached,
  150. // then a fence will ensure will wait for blocks allocated
  151. // in previous frames are processed. If that fails, then
  152. // another fence will ensure everything pending for the current
  153. // frame is processed (effectively stalling).
  154. //
  155. // See the comments in the code to understand better how it works.
  156. struct StagingBufferBlock {
  157. VkBuffer buffer;
  158. VmaAllocation allocation;
  159. uint64_t frame_used;
  160. uint32_t fill_amount;
  161. };
  162. Vector<StagingBufferBlock> staging_buffer_blocks;
  163. int staging_buffer_current;
  164. uint32_t staging_buffer_block_size;
  165. uint64_t staging_buffer_max_size;
  166. bool staging_buffer_used;
  167. Error _staging_buffer_allocate(uint32_t p_amount, uint32_t p_required_align, uint32_t &r_alloc_offset, uint32_t &r_alloc_size, bool p_can_segment = true, bool p_on_draw_command_buffer = false);
  168. Error _insert_staging_block();
  169. struct Buffer {
  170. uint32_t size;
  171. VkBuffer buffer;
  172. VmaAllocation allocation;
  173. VkDescriptorBufferInfo buffer_info; //used for binding
  174. Buffer() {
  175. size = 0;
  176. buffer = NULL;
  177. allocation = NULL;
  178. }
  179. };
  180. Error _buffer_allocate(Buffer *p_buffer, uint32_t p_size, uint32_t p_usage, VmaMemoryUsage p_mapping);
  181. Error _buffer_free(Buffer *p_buffer);
  182. Error _buffer_update(Buffer *p_buffer, size_t p_offset, const uint8_t *p_data, size_t p_data_size, bool p_use_draw_command_buffer = false, uint32_t p_required_align = 32);
  183. void _full_barrier(bool p_sync_with_draw);
  184. void _memory_barrier(VkPipelineStageFlags p_src_stage_mask, VkPipelineStageFlags p_dst_stage_mask, VkAccessFlags p_src_access, VkAccessFlags p_dst_sccess, bool p_sync_with_draw);
  185. void _buffer_memory_barrier(VkBuffer buffer, uint64_t p_from, uint64_t p_size, VkPipelineStageFlags p_src_stage_mask, VkPipelineStageFlags p_dst_stage_mask, VkAccessFlags p_src_access, VkAccessFlags p_dst_sccess, bool p_sync_with_draw);
  186. /*********************/
  187. /**** FRAMEBUFFER ****/
  188. /*********************/
  189. // In Vulkan, framebuffers work similar to how they
  190. // do in OpenGL, with the exception that
  191. // the "format" (vkRenderPass) is not dynamic
  192. // and must be more or less the same as the one
  193. // used for the render pipelines.
  194. struct FramebufferFormatKey {
  195. Vector<AttachmentFormat> attachments;
  196. bool operator<(const FramebufferFormatKey &p_key) const {
  197. int as = attachments.size();
  198. int bs = p_key.attachments.size();
  199. if (as != bs) {
  200. return as < bs;
  201. }
  202. const AttachmentFormat *af_a = attachments.ptr();
  203. const AttachmentFormat *af_b = p_key.attachments.ptr();
  204. for (int i = 0; i < as; i++) {
  205. const AttachmentFormat &a = af_a[i];
  206. const AttachmentFormat &b = af_b[i];
  207. if (a.format != b.format) {
  208. return a.format < b.format;
  209. }
  210. if (a.samples != b.samples) {
  211. return a.samples < b.samples;
  212. }
  213. if (a.usage_flags != b.usage_flags) {
  214. return a.usage_flags < b.usage_flags;
  215. }
  216. }
  217. return false; //equal
  218. }
  219. };
  220. VkRenderPass _render_pass_create(const Vector<AttachmentFormat> &p_format, InitialAction p_initial_action, FinalAction p_final_action, InitialAction p_initial_depth_action, FinalAction p_final_depthcolor_action, int *r_color_attachment_count = NULL);
  221. // This is a cache and it's never freed, it ensures
  222. // IDs for a given format are always unique.
  223. Map<FramebufferFormatKey, FramebufferFormatID> framebuffer_format_cache;
  224. struct FramebufferFormat {
  225. const Map<FramebufferFormatKey, FramebufferFormatID>::Element *E;
  226. VkRenderPass render_pass; //here for constructing shaders, never used, see section (7.2. Render Pass Compatibility from Vulkan spec)
  227. int color_attachments; //used for pipeline validation
  228. TextureSamples samples;
  229. };
  230. Map<FramebufferFormatID, FramebufferFormat> framebuffer_formats;
  231. struct Framebuffer {
  232. FramebufferFormatID format_id;
  233. struct VersionKey {
  234. InitialAction initial_color_action;
  235. FinalAction final_color_action;
  236. InitialAction initial_depth_action;
  237. FinalAction final_depth_action;
  238. bool operator<(const VersionKey &p_key) const {
  239. if (initial_color_action == p_key.initial_color_action) {
  240. if (final_color_action == p_key.final_color_action) {
  241. if (initial_depth_action == p_key.initial_depth_action) {
  242. return final_depth_action < p_key.final_depth_action;
  243. } else {
  244. return initial_depth_action < p_key.initial_depth_action;
  245. }
  246. } else {
  247. return final_color_action < p_key.final_color_action;
  248. }
  249. } else {
  250. return initial_color_action < p_key.initial_color_action;
  251. }
  252. }
  253. };
  254. uint32_t storage_mask;
  255. Vector<RID> texture_ids;
  256. struct Version {
  257. VkFramebuffer framebuffer;
  258. VkRenderPass render_pass; //this one is owned
  259. };
  260. Map<VersionKey, Version> framebuffers;
  261. Size2 size;
  262. };
  263. RID_Owner<Framebuffer, true> framebuffer_owner;
  264. /***********************/
  265. /**** VERTEX BUFFER ****/
  266. /***********************/
  267. // Vertex buffers in Vulkan are similar to how
  268. // they work in OpenGL, except that instead of
  269. // an attribtue index, there is a buffer binding
  270. // index (for binding the buffers in real-time)
  271. // and a location index (what is used in the shader).
  272. //
  273. // This mapping is done here internally, and it's not
  274. // exposed.
  275. RID_Owner<Buffer, true> vertex_buffer_owner;
  276. struct VertexDescriptionKey {
  277. Vector<VertexDescription> vertex_formats;
  278. bool operator==(const VertexDescriptionKey &p_key) const {
  279. int vdc = vertex_formats.size();
  280. int vdck = p_key.vertex_formats.size();
  281. if (vdc != vdck) {
  282. return false;
  283. } else {
  284. const VertexDescription *a_ptr = vertex_formats.ptr();
  285. const VertexDescription *b_ptr = p_key.vertex_formats.ptr();
  286. for (int i = 0; i < vdc; i++) {
  287. const VertexDescription &a = a_ptr[i];
  288. const VertexDescription &b = b_ptr[i];
  289. if (a.location != b.location) {
  290. return false;
  291. }
  292. if (a.offset != b.offset) {
  293. return false;
  294. }
  295. if (a.format != b.format) {
  296. return false;
  297. }
  298. if (a.stride != b.stride) {
  299. return false;
  300. }
  301. if (a.frequency != b.frequency) {
  302. return false;
  303. }
  304. }
  305. return true; //they are equal
  306. }
  307. }
  308. uint32_t hash() const {
  309. int vdc = vertex_formats.size();
  310. uint32_t h = hash_djb2_one_32(vdc);
  311. const VertexDescription *ptr = vertex_formats.ptr();
  312. for (int i = 0; i < vdc; i++) {
  313. const VertexDescription &vd = ptr[i];
  314. h = hash_djb2_one_32(vd.location, h);
  315. h = hash_djb2_one_32(vd.offset, h);
  316. h = hash_djb2_one_32(vd.format, h);
  317. h = hash_djb2_one_32(vd.stride, h);
  318. h = hash_djb2_one_32(vd.frequency, h);
  319. }
  320. return h;
  321. }
  322. };
  323. struct VertexDescriptionHash {
  324. static _FORCE_INLINE_ uint32_t hash(const VertexDescriptionKey &p_key) {
  325. return p_key.hash();
  326. }
  327. };
  328. // This is a cache and it's never freed, it ensures that
  329. // ID used for a specific format always remain the same.
  330. HashMap<VertexDescriptionKey, VertexFormatID, VertexDescriptionHash> vertex_format_cache;
  331. struct VertexDescriptionCache {
  332. Vector<VertexDescription> vertex_formats;
  333. VkVertexInputBindingDescription *bindings;
  334. VkVertexInputAttributeDescription *attributes;
  335. VkPipelineVertexInputStateCreateInfo create_info;
  336. };
  337. Map<VertexFormatID, VertexDescriptionCache> vertex_formats;
  338. struct VertexArray {
  339. RID buffer;
  340. VertexFormatID description;
  341. int vertex_count;
  342. uint32_t max_instances_allowed;
  343. Vector<VkBuffer> buffers; //not owned, just referenced
  344. Vector<VkDeviceSize> offsets;
  345. };
  346. RID_Owner<VertexArray, true> vertex_array_owner;
  347. struct IndexBuffer : public Buffer {
  348. uint32_t max_index; //used for validation
  349. uint32_t index_count;
  350. VkIndexType index_type;
  351. bool supports_restart_indices;
  352. };
  353. RID_Owner<IndexBuffer, true> index_buffer_owner;
  354. struct IndexArray {
  355. uint32_t max_index; //remember the maximum index here too, for validation
  356. VkBuffer buffer; //not owned, inherited from index buffer
  357. uint32_t offset;
  358. uint32_t indices;
  359. VkIndexType index_type;
  360. bool supports_restart_indices;
  361. };
  362. RID_Owner<IndexArray, true> index_array_owner;
  363. /****************/
  364. /**** SHADER ****/
  365. /****************/
  366. // Vulkan specifies a really complex behavior for the application
  367. // in order to tell when descriptor sets need to be re-bound (or not).
  368. // "When binding a descriptor set (see Descriptor Set Binding) to set
  369. // number N, if the previously bound descriptor sets for sets zero
  370. // through N-1 were all bound using compatible pipeline layouts,
  371. // then performing this binding does not disturb any of the lower numbered sets.
  372. // If, additionally, the previous bound descriptor set for set N was
  373. // bound using a pipeline layout compatible for set N, then the bindings
  374. // in sets numbered greater than N are also not disturbed."
  375. // As a result, we need to figure out quickly when something is no longer "compatible".
  376. // in order to avoid costly rebinds.
  377. enum {
  378. MAX_UNIFORM_SETS = 16
  379. };
  380. struct UniformInfo {
  381. UniformType type;
  382. int binding;
  383. uint32_t stages;
  384. int length; //size of arrays (in total elements), or ubos (in bytes * total elements)
  385. bool operator!=(const UniformInfo &p_info) const {
  386. return (binding != p_info.binding || type != p_info.type || stages != p_info.stages || length != p_info.length);
  387. }
  388. bool operator<(const UniformInfo &p_info) const {
  389. if (binding != p_info.binding) {
  390. return binding < p_info.binding;
  391. }
  392. if (type != p_info.type) {
  393. return type < p_info.type;
  394. }
  395. if (stages != p_info.stages) {
  396. return stages < p_info.stages;
  397. }
  398. return length < p_info.length;
  399. }
  400. };
  401. struct UniformSetFormat {
  402. Vector<UniformInfo> uniform_info;
  403. bool operator<(const UniformSetFormat &p_format) const {
  404. uint32_t size = uniform_info.size();
  405. uint32_t psize = p_format.uniform_info.size();
  406. if (size != psize) {
  407. return size < psize;
  408. }
  409. const UniformInfo *infoptr = uniform_info.ptr();
  410. const UniformInfo *pinfoptr = p_format.uniform_info.ptr();
  411. for (uint32_t i = 0; i < size; i++) {
  412. if (infoptr[i] != pinfoptr[i]) {
  413. return infoptr[i] < pinfoptr[i];
  414. }
  415. }
  416. return false;
  417. }
  418. };
  419. // Always grows, never shrinks, ensuring unique IDs, but we assume
  420. // the amount of formats will never be a problem, as the amount of shaders
  421. // in a game is limited.
  422. Map<UniformSetFormat, uint32_t> uniform_set_format_cache;
  423. // Shaders in Vulkan are just pretty much
  424. // precompiled blocks of SPIR-V bytecode. They
  425. // are most likely not really compiled to host
  426. // assembly until a pipeline is created.
  427. //
  428. // When supplying the shaders, this implementation
  429. // will use the reflection abilities of glslang to
  430. // understand and cache everything required to
  431. // create and use the descriptor sets (Vulkan's
  432. // biggest pain).
  433. //
  434. // Additionally, hashes are created for every set
  435. // to do quick validation and ensuring the user
  436. // does not submit something invalid.
  437. struct Shader {
  438. struct Set {
  439. Vector<UniformInfo> uniform_info;
  440. VkDescriptorSetLayout descriptor_set_layout;
  441. };
  442. uint32_t vertex_input_mask; //inputs used, this is mostly for validation
  443. int fragment_outputs;
  444. struct PushConstant {
  445. uint32_t push_constant_size;
  446. uint32_t push_constants_vk_stage;
  447. };
  448. PushConstant push_constant;
  449. bool is_compute = false;
  450. int max_output;
  451. Vector<Set> sets;
  452. Vector<uint32_t> set_formats;
  453. Vector<VkPipelineShaderStageCreateInfo> pipeline_stages;
  454. VkPipelineLayout pipeline_layout;
  455. };
  456. String _shader_uniform_debug(RID p_shader, int p_set = -1);
  457. RID_Owner<Shader, true> shader_owner;
  458. /******************/
  459. /**** UNIFORMS ****/
  460. /******************/
  461. // Descriptor sets require allocation from a pool.
  462. // The documentation on how to use pools properly
  463. // is scarce, and the documentation is strange.
  464. //
  465. // Basically, you can mix and match pools as you
  466. // like, but you'll run into fragmentation issues.
  467. // Because of this, the recommended approach is to
  468. // create a a pool for every descriptor set type,
  469. // as this prevents fragmentation.
  470. //
  471. // This is implemented here as a having a list of
  472. // pools (each can contain up to 64 sets) for each
  473. // set layout. The amount of sets for each type
  474. // is used as the key.
  475. enum {
  476. MAX_DESCRIPTOR_POOL_ELEMENT = 65535
  477. };
  478. struct DescriptorPoolKey {
  479. union {
  480. struct {
  481. uint16_t uniform_type[UNIFORM_TYPE_MAX]; //using 16 bits because, for sending arrays, each element is a pool set.
  482. };
  483. struct {
  484. uint64_t key1;
  485. uint64_t key2;
  486. uint64_t key3;
  487. };
  488. };
  489. bool operator<(const DescriptorPoolKey &p_key) const {
  490. if (key1 != p_key.key1) {
  491. return key1 < p_key.key1;
  492. }
  493. if (key2 != p_key.key2) {
  494. return key2 < p_key.key2;
  495. }
  496. return key3 < p_key.key3;
  497. }
  498. DescriptorPoolKey() {
  499. key1 = 0;
  500. key2 = 0;
  501. key3 = 0;
  502. }
  503. };
  504. struct DescriptorPool {
  505. VkDescriptorPool pool;
  506. uint32_t usage;
  507. };
  508. Map<DescriptorPoolKey, Set<DescriptorPool *>> descriptor_pools;
  509. uint32_t max_descriptors_per_pool;
  510. DescriptorPool *_descriptor_pool_allocate(const DescriptorPoolKey &p_key);
  511. void _descriptor_pool_free(const DescriptorPoolKey &p_key, DescriptorPool *p_pool);
  512. RID_Owner<Buffer, true> uniform_buffer_owner;
  513. RID_Owner<Buffer, true> storage_buffer_owner;
  514. //texture buffer needs a view
  515. struct TextureBuffer {
  516. Buffer buffer;
  517. VkBufferView view;
  518. };
  519. RID_Owner<TextureBuffer, true> texture_buffer_owner;
  520. // This structure contains the descriptor set. They _need_ to be allocated
  521. // for a shader (and will be erased when this shader is erased), but should
  522. // work for other shaders as long as the hash matches. This covers using
  523. // them in shader variants.
  524. //
  525. // Keep also in mind that you can share buffers between descriptor sets, so
  526. // the above restriction is not too serious.
  527. struct UniformSet {
  528. uint32_t format;
  529. RID shader_id;
  530. uint32_t shader_set;
  531. DescriptorPool *pool;
  532. DescriptorPoolKey pool_key;
  533. VkDescriptorSet descriptor_set;
  534. //VkPipelineLayout pipeline_layout; //not owned, inherited from shader
  535. Vector<RID> attachable_textures; //used for validation
  536. Vector<Texture *> mutable_sampled_textures; //used for layout change
  537. Vector<Texture *> mutable_storage_textures; //used for layout change
  538. };
  539. RID_Owner<UniformSet, true> uniform_set_owner;
  540. /*******************/
  541. /**** PIPELINES ****/
  542. /*******************/
  543. // Render pipeline contains ALL the
  544. // information required for drawing.
  545. // This includes all the rasterizer state
  546. // as well as shader used, framebuffer format,
  547. // etc.
  548. // While the pipeline is just a single object
  549. // (VkPipeline) a lot of values are also saved
  550. // here to do validation (vulkan does none by
  551. // default) and warn the user if something
  552. // was not supplied as intended.
  553. struct RenderPipeline {
  554. //Cached values for validation
  555. #ifdef DEBUG_ENABLED
  556. struct Validation {
  557. FramebufferFormatID framebuffer_format;
  558. uint32_t dynamic_state;
  559. VertexFormatID vertex_format;
  560. bool uses_restart_indices;
  561. uint32_t primitive_minimum;
  562. uint32_t primitive_divisor;
  563. } validation;
  564. #endif
  565. //Actual pipeline
  566. RID shader;
  567. Vector<uint32_t> set_formats;
  568. VkPipelineLayout pipeline_layout; // not owned, needed for push constants
  569. VkPipeline pipeline;
  570. uint32_t push_constant_size;
  571. uint32_t push_constant_stages;
  572. };
  573. RID_Owner<RenderPipeline, true> render_pipeline_owner;
  574. struct ComputePipeline {
  575. RID shader;
  576. Vector<uint32_t> set_formats;
  577. VkPipelineLayout pipeline_layout; // not owned, needed for push constants
  578. VkPipeline pipeline;
  579. uint32_t push_constant_size;
  580. uint32_t push_constant_stages;
  581. };
  582. RID_Owner<ComputePipeline, true> compute_pipeline_owner;
  583. /*******************/
  584. /**** DRAW LIST ****/
  585. /*******************/
  586. // Draw list contains both the command buffer
  587. // used for drawing as well as a LOT of
  588. // information used for validation. This
  589. // validation is cheap so most of it can
  590. // also run in release builds.
  591. // When using split command lists, this is
  592. // implemented internally using secondary command
  593. // buffers. As they can be created in threads,
  594. // each needs it's own command pool.
  595. struct SplitDrawListAllocator {
  596. VkCommandPool command_pool;
  597. Vector<VkCommandBuffer> command_buffers; //one for each frame
  598. };
  599. Vector<SplitDrawListAllocator> split_draw_list_allocators;
  600. struct DrawList {
  601. VkCommandBuffer command_buffer; //if persistent, this is owned, otherwise it's shared with the ringbuffer
  602. Rect2i viewport;
  603. struct SetState {
  604. uint32_t pipeline_expected_format;
  605. uint32_t uniform_set_format;
  606. VkDescriptorSet descriptor_set;
  607. RID uniform_set;
  608. bool bound;
  609. SetState() {
  610. bound = false;
  611. pipeline_expected_format = 0;
  612. uniform_set_format = 0;
  613. descriptor_set = VK_NULL_HANDLE;
  614. }
  615. };
  616. struct State {
  617. SetState sets[MAX_UNIFORM_SETS];
  618. uint32_t set_count;
  619. RID pipeline;
  620. RID pipeline_shader;
  621. VkPipelineLayout pipeline_layout;
  622. RID vertex_array;
  623. RID index_array;
  624. uint32_t pipeline_push_constant_stages;
  625. State() {
  626. set_count = 0;
  627. pipeline_layout = VK_NULL_HANDLE;
  628. pipeline_push_constant_stages = 0;
  629. }
  630. } state;
  631. #ifdef DEBUG_ENABLED
  632. struct Validation {
  633. bool active; //means command buffer was not closes, so you can keep adding things
  634. FramebufferFormatID framebuffer_format;
  635. //actual render pass values
  636. uint32_t dynamic_state;
  637. VertexFormatID vertex_format; //INVALID_ID if not set
  638. uint32_t vertex_array_size; //0 if not set
  639. uint32_t vertex_max_instances_allowed;
  640. bool index_buffer_uses_restart_indices;
  641. uint32_t index_array_size; //0 if index buffer not set
  642. uint32_t index_array_max_index;
  643. uint32_t index_array_offset;
  644. Vector<uint32_t> set_formats;
  645. Vector<bool> set_bound;
  646. Vector<RID> set_rids;
  647. //last pipeline set values
  648. bool pipeline_active;
  649. uint32_t pipeline_dynamic_state;
  650. VertexFormatID pipeline_vertex_format;
  651. RID pipeline_shader;
  652. uint32_t invalid_set_from;
  653. bool pipeline_uses_restart_indices;
  654. uint32_t pipeline_primitive_divisor;
  655. uint32_t pipeline_primitive_minimum;
  656. Vector<uint32_t> pipeline_set_formats;
  657. uint32_t pipeline_push_constant_size;
  658. bool pipeline_push_constant_suppplied;
  659. Validation() {
  660. active = true;
  661. dynamic_state = 0;
  662. vertex_format = INVALID_ID;
  663. vertex_array_size = 0;
  664. vertex_max_instances_allowed = 0xFFFFFFFF;
  665. framebuffer_format = INVALID_ID;
  666. index_array_size = 0; //not sent
  667. index_array_max_index = 0; //not set
  668. index_buffer_uses_restart_indices = false;
  669. invalid_set_from = 0;
  670. //pipeline state initalize
  671. pipeline_active = false;
  672. pipeline_dynamic_state = 0;
  673. pipeline_vertex_format = INVALID_ID;
  674. pipeline_uses_restart_indices = false;
  675. pipeline_push_constant_size = 0;
  676. pipeline_push_constant_suppplied = false;
  677. }
  678. } validation;
  679. #else
  680. struct Validation {
  681. uint32_t vertex_array_size; //0 if not set
  682. uint32_t index_array_size; //0 if index buffer not set
  683. uint32_t index_array_offset;
  684. Validation() {
  685. vertex_array_size = 0;
  686. index_array_size = 0; //not sent
  687. }
  688. } validation;
  689. #endif
  690. };
  691. DrawList *draw_list; //one for regular draw lists, multiple for split.
  692. uint32_t draw_list_count;
  693. bool draw_list_split;
  694. Vector<RID> draw_list_bound_textures;
  695. bool draw_list_unbind_color_textures;
  696. bool draw_list_unbind_depth_textures;
  697. void _draw_list_insert_clear_region(DrawList *draw_list, Framebuffer *framebuffer, Point2i viewport_offset, Point2i viewport_size, bool p_clear_color, const Vector<Color> &p_clear_colors, bool p_clear_depth, float p_depth, uint32_t p_stencil);
  698. Error _draw_list_setup_framebuffer(Framebuffer *p_framebuffer, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, VkFramebuffer *r_framebuffer, VkRenderPass *r_render_pass);
  699. Error _draw_list_render_pass_begin(Framebuffer *framebuffer, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector<Color> &p_clear_colors, float p_clear_depth, uint32_t p_clear_stencil, Point2i viewport_offset, Point2i viewport_size, VkFramebuffer vkframebuffer, VkRenderPass render_pass, VkCommandBuffer command_buffer, VkSubpassContents subpass_contents);
  700. _FORCE_INLINE_ DrawList *_get_draw_list_ptr(DrawListID p_id);
  701. /**********************/
  702. /**** COMPUTE LIST ****/
  703. /**********************/
  704. struct ComputeList {
  705. VkCommandBuffer command_buffer; //if persistent, this is owned, otherwise it's shared with the ringbuffer
  706. struct SetState {
  707. uint32_t pipeline_expected_format;
  708. uint32_t uniform_set_format;
  709. VkDescriptorSet descriptor_set;
  710. RID uniform_set;
  711. bool bound;
  712. SetState() {
  713. bound = false;
  714. pipeline_expected_format = 0;
  715. uniform_set_format = 0;
  716. descriptor_set = VK_NULL_HANDLE;
  717. }
  718. };
  719. struct State {
  720. Set<Texture *> textures_to_sampled_layout;
  721. SetState sets[MAX_UNIFORM_SETS];
  722. uint32_t set_count;
  723. RID pipeline;
  724. RID pipeline_shader;
  725. VkPipelineLayout pipeline_layout;
  726. uint32_t pipeline_push_constant_stages;
  727. State() {
  728. set_count = 0;
  729. pipeline_layout = VK_NULL_HANDLE;
  730. pipeline_push_constant_stages = 0;
  731. }
  732. } state;
  733. #ifdef DEBUG_ENABLED
  734. struct Validation {
  735. bool active; //means command buffer was not closes, so you can keep adding things
  736. Vector<uint32_t> set_formats;
  737. Vector<bool> set_bound;
  738. Vector<RID> set_rids;
  739. //last pipeline set values
  740. bool pipeline_active;
  741. RID pipeline_shader;
  742. uint32_t invalid_set_from;
  743. Vector<uint32_t> pipeline_set_formats;
  744. uint32_t pipeline_push_constant_size;
  745. bool pipeline_push_constant_suppplied;
  746. Validation() {
  747. active = true;
  748. invalid_set_from = 0;
  749. //pipeline state initalize
  750. pipeline_active = false;
  751. pipeline_push_constant_size = 0;
  752. pipeline_push_constant_suppplied = false;
  753. }
  754. } validation;
  755. #endif
  756. };
  757. ComputeList *compute_list;
  758. /**************************/
  759. /**** FRAME MANAGEMENT ****/
  760. /**************************/
  761. // This is the frame structure. There are normally
  762. // 3 of these (used for triple buffering), or 2
  763. // (double buffering). They are cycled constantly.
  764. //
  765. // It contains two command buffers, one that is
  766. // used internally for setting up (creating stuff)
  767. // and another used mostly for drawing.
  768. //
  769. // They also contains a list of things that need
  770. // to be disposed of when deleted, which can't
  771. // happen immediately due to the asynchronous
  772. // nature of the GPU. They will get deleted
  773. // when the frame is cycled.
  774. struct Frame {
  775. //list in usage order, from last to free to first to free
  776. List<Buffer> buffers_to_dispose_of;
  777. List<Texture> textures_to_dispose_of;
  778. List<Framebuffer> framebuffers_to_dispose_of;
  779. List<VkSampler> samplers_to_dispose_of;
  780. List<Shader> shaders_to_dispose_of;
  781. List<VkBufferView> buffer_views_to_dispose_of;
  782. List<UniformSet> uniform_sets_to_dispose_of;
  783. List<RenderPipeline> render_pipelines_to_dispose_of;
  784. List<ComputePipeline> compute_pipelines_to_dispose_of;
  785. VkCommandPool command_pool;
  786. VkCommandBuffer setup_command_buffer; //used at the begining of every frame for set-up
  787. VkCommandBuffer draw_command_buffer; //used at the begining of every frame for set-up
  788. struct Timestamp {
  789. String description;
  790. uint64_t value;
  791. };
  792. VkQueryPool timestamp_pool;
  793. String *timestamp_names;
  794. uint64_t *timestamp_cpu_values;
  795. uint32_t timestamp_count;
  796. String *timestamp_result_names;
  797. uint64_t *timestamp_cpu_result_values;
  798. uint64_t *timestamp_result_values;
  799. uint32_t timestamp_result_count;
  800. uint64_t index;
  801. };
  802. uint32_t max_timestamp_query_elements;
  803. Frame *frames; //frames available, they are cycled (usually 3)
  804. int frame; //current frame
  805. int frame_count; //total amount of frames
  806. uint64_t frames_drawn;
  807. void _free_pending_resources(int p_frame);
  808. VmaAllocator allocator;
  809. VulkanContext *context;
  810. void _free_internal(RID p_id);
  811. void _flush(bool p_current_frame);
  812. bool screen_prepared;
  813. template <class T>
  814. void _free_rids(T &p_owner, const char *p_type);
  815. public:
  816. virtual RID texture_create(const TextureFormat &p_format, const TextureView &p_view, const Vector<Vector<uint8_t>> &p_data = Vector<Vector<uint8_t>>());
  817. virtual RID texture_create_shared(const TextureView &p_view, RID p_with_texture);
  818. virtual RID texture_create_shared_from_slice(const TextureView &p_view, RID p_with_texture, uint32_t p_layer, uint32_t p_mipmap, TextureSliceType p_slice_type = TEXTURE_SLICE_2D);
  819. virtual Error texture_update(RID p_texture, uint32_t p_layer, const Vector<uint8_t> &p_data, bool p_sync_with_draw = false);
  820. virtual Vector<uint8_t> texture_get_data(RID p_texture, uint32_t p_layer);
  821. virtual bool texture_is_format_supported_for_usage(DataFormat p_format, uint32_t p_usage) const;
  822. virtual bool texture_is_shared(RID p_texture);
  823. virtual bool texture_is_valid(RID p_texture);
  824. virtual Error texture_copy(RID p_from_texture, RID p_to_texture, const Vector3 &p_from, const Vector3 &p_to, const Vector3 &p_size, uint32_t p_src_mipmap, uint32_t p_dst_mipmap, uint32_t p_src_layer, uint32_t p_dst_layer, bool p_sync_with_draw = false);
  825. virtual Error texture_clear(RID p_texture, const Color &p_color, uint32_t p_base_mipmap, uint32_t p_mipmaps, uint32_t p_base_layer, uint32_t p_layers, bool p_sync_with_draw = false);
  826. /*********************/
  827. /**** FRAMEBUFFER ****/
  828. /*********************/
  829. virtual FramebufferFormatID framebuffer_format_create(const Vector<AttachmentFormat> &p_format);
  830. virtual TextureSamples framebuffer_format_get_texture_samples(FramebufferFormatID p_format);
  831. virtual RID framebuffer_create(const Vector<RID> &p_texture_attachments, FramebufferFormatID p_format_check = INVALID_ID);
  832. virtual FramebufferFormatID framebuffer_get_format(RID p_framebuffer);
  833. /*****************/
  834. /**** SAMPLER ****/
  835. /*****************/
  836. virtual RID sampler_create(const SamplerState &p_state);
  837. /**********************/
  838. /**** VERTEX ARRAY ****/
  839. /**********************/
  840. virtual RID vertex_buffer_create(uint32_t p_size_bytes, const Vector<uint8_t> &p_data = Vector<uint8_t>());
  841. // Internally reference counted, this ID is warranted to be unique for the same description, but needs to be freed as many times as it was allocated
  842. virtual VertexFormatID vertex_format_create(const Vector<VertexDescription> &p_vertex_formats);
  843. virtual RID vertex_array_create(uint32_t p_vertex_count, VertexFormatID p_vertex_format, const Vector<RID> &p_src_buffers);
  844. virtual RID index_buffer_create(uint32_t p_size_indices, IndexBufferFormat p_format, const Vector<uint8_t> &p_data = Vector<uint8_t>(), bool p_use_restart_indices = false);
  845. virtual RID index_array_create(RID p_index_buffer, uint32_t p_index_offset, uint32_t p_index_count);
  846. /****************/
  847. /**** SHADER ****/
  848. /****************/
  849. virtual RID shader_create(const Vector<ShaderStageData> &p_stages);
  850. virtual uint32_t shader_get_vertex_input_attribute_mask(RID p_shader);
  851. /*****************/
  852. /**** UNIFORM ****/
  853. /*****************/
  854. virtual RID uniform_buffer_create(uint32_t p_size_bytes, const Vector<uint8_t> &p_data = Vector<uint8_t>());
  855. virtual RID storage_buffer_create(uint32_t p_size_bytes, const Vector<uint8_t> &p_data = Vector<uint8_t>());
  856. virtual RID texture_buffer_create(uint32_t p_size_elements, DataFormat p_format, const Vector<uint8_t> &p_data = Vector<uint8_t>());
  857. virtual RID uniform_set_create(const Vector<Uniform> &p_uniforms, RID p_shader, uint32_t p_shader_set);
  858. virtual bool uniform_set_is_valid(RID p_uniform_set);
  859. virtual Error buffer_update(RID p_buffer, uint32_t p_offset, uint32_t p_size, const void *p_data, bool p_sync_with_draw = false); //works for any buffer
  860. virtual Vector<uint8_t> buffer_get_data(RID p_buffer);
  861. /*************************/
  862. /**** RENDER PIPELINE ****/
  863. /*************************/
  864. virtual RID render_pipeline_create(RID p_shader, FramebufferFormatID p_framebuffer_format, VertexFormatID p_vertex_format, RenderPrimitive p_render_primitive, const PipelineRasterizationState &p_rasterization_state, const PipelineMultisampleState &p_multisample_state, const PipelineDepthStencilState &p_depth_stencil_state, const PipelineColorBlendState &p_blend_state, int p_dynamic_state_flags = 0);
  865. virtual bool render_pipeline_is_valid(RID p_pipeline);
  866. /**************************/
  867. /**** COMPUTE PIPELINE ****/
  868. /**************************/
  869. virtual RID compute_pipeline_create(RID p_shader);
  870. virtual bool compute_pipeline_is_valid(RID p_pipeline);
  871. /****************/
  872. /**** SCREEN ****/
  873. /****************/
  874. virtual int screen_get_width(DisplayServer::WindowID p_screen = 0) const;
  875. virtual int screen_get_height(DisplayServer::WindowID p_screen = 0) const;
  876. virtual FramebufferFormatID screen_get_framebuffer_format() const;
  877. /********************/
  878. /**** DRAW LISTS ****/
  879. /********************/
  880. virtual DrawListID draw_list_begin_for_screen(DisplayServer::WindowID p_screen = 0, const Color &p_clear_color = Color());
  881. virtual DrawListID draw_list_begin(RID p_framebuffer, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector<Color> &p_clear_color_values = Vector<Color>(), float p_clear_depth = 1.0, uint32_t p_clear_stencil = 0, const Rect2 &p_region = Rect2());
  882. virtual Error draw_list_begin_split(RID p_framebuffer, uint32_t p_splits, DrawListID *r_split_ids, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector<Color> &p_clear_color_values = Vector<Color>(), float p_clear_depth = 1.0, uint32_t p_clear_stencil = 0, const Rect2 &p_region = Rect2());
  883. virtual void draw_list_bind_render_pipeline(DrawListID p_list, RID p_render_pipeline);
  884. virtual void draw_list_bind_uniform_set(DrawListID p_list, RID p_uniform_set, uint32_t p_index);
  885. virtual void draw_list_bind_vertex_array(DrawListID p_list, RID p_vertex_array);
  886. virtual void draw_list_bind_index_array(DrawListID p_list, RID p_index_array);
  887. virtual void draw_list_set_line_width(DrawListID p_list, float p_width);
  888. virtual void draw_list_set_push_constant(DrawListID p_list, void *p_data, uint32_t p_data_size);
  889. virtual void draw_list_draw(DrawListID p_list, bool p_use_indices, uint32_t p_instances = 1, uint32_t p_procedural_vertices = 0);
  890. virtual void draw_list_enable_scissor(DrawListID p_list, const Rect2 &p_rect);
  891. virtual void draw_list_disable_scissor(DrawListID p_list);
  892. virtual void draw_list_end();
  893. /***********************/
  894. /**** COMPUTE LISTS ****/
  895. /***********************/
  896. virtual ComputeListID compute_list_begin();
  897. virtual void compute_list_bind_compute_pipeline(ComputeListID p_list, RID p_compute_pipeline);
  898. virtual void compute_list_bind_uniform_set(ComputeListID p_list, RID p_uniform_set, uint32_t p_index);
  899. virtual void compute_list_set_push_constant(ComputeListID p_list, void *p_data, uint32_t p_data_size);
  900. virtual void compute_list_add_barrier(ComputeListID p_list);
  901. virtual void compute_list_dispatch(ComputeListID p_list, uint32_t p_x_groups, uint32_t p_y_groups, uint32_t p_z_groups);
  902. virtual void compute_list_end();
  903. /**************/
  904. /**** FREE ****/
  905. /**************/
  906. virtual void free(RID p_id);
  907. /****************/
  908. /**** Timing ****/
  909. /****************/
  910. virtual void capture_timestamp(const String &p_name, bool p_sync_to_draw);
  911. virtual uint32_t get_captured_timestamps_count() const;
  912. virtual uint64_t get_captured_timestamps_frame() const;
  913. virtual uint64_t get_captured_timestamp_gpu_time(uint32_t p_index) const;
  914. virtual uint64_t get_captured_timestamp_cpu_time(uint32_t p_index) const;
  915. virtual String get_captured_timestamp_name(uint32_t p_index) const;
  916. /****************/
  917. /**** Limits ****/
  918. /****************/
  919. virtual int limit_get(Limit p_limit);
  920. virtual void prepare_screen_for_drawing();
  921. void initialize(VulkanContext *p_context);
  922. void finalize();
  923. virtual void swap_buffers();
  924. virtual uint32_t get_frame_delay() const;
  925. RenderingDeviceVulkan();
  926. };
  927. #endif // RENDERING_DEVICE_VULKAN_H