rendering_device_vulkan.h 38 KB

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