rendering_device.h 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654
  1. /**************************************************************************/
  2. /* rendering_device.h */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #ifndef RENDERING_DEVICE_H
  31. #define RENDERING_DEVICE_H
  32. #include "core/object/class_db.h"
  33. #include "core/object/worker_thread_pool.h"
  34. #include "core/os/condition_variable.h"
  35. #include "core/os/thread_safe.h"
  36. #include "core/templates/local_vector.h"
  37. #include "core/templates/oa_hash_map.h"
  38. #include "core/templates/rid_owner.h"
  39. #include "core/variant/typed_array.h"
  40. #include "servers/display_server.h"
  41. #include "servers/rendering/rendering_device_commons.h"
  42. #include "servers/rendering/rendering_device_driver.h"
  43. #include "servers/rendering/rendering_device_graph.h"
  44. class RDTextureFormat;
  45. class RDTextureView;
  46. class RDAttachmentFormat;
  47. class RDSamplerState;
  48. class RDVertexAttribute;
  49. class RDShaderSource;
  50. class RDShaderSPIRV;
  51. class RDUniform;
  52. class RDPipelineRasterizationState;
  53. class RDPipelineMultisampleState;
  54. class RDPipelineDepthStencilState;
  55. class RDPipelineColorBlendState;
  56. class RDFramebufferPass;
  57. class RDPipelineSpecializationConstant;
  58. class RenderingDevice : public RenderingDeviceCommons {
  59. GDCLASS(RenderingDevice, Object)
  60. _THREAD_SAFE_CLASS_
  61. private:
  62. Thread::ID render_thread_id;
  63. public:
  64. enum ShaderLanguage {
  65. SHADER_LANGUAGE_GLSL,
  66. SHADER_LANGUAGE_HLSL
  67. };
  68. typedef int64_t DrawListID;
  69. typedef int64_t ComputeListID;
  70. typedef String (*ShaderSPIRVGetCacheKeyFunction)(const RenderingDevice *p_render_device);
  71. typedef Vector<uint8_t> (*ShaderCompileToSPIRVFunction)(ShaderStage p_stage, const String &p_source_code, ShaderLanguage p_language, String *r_error, const RenderingDevice *p_render_device);
  72. typedef Vector<uint8_t> (*ShaderCacheFunction)(ShaderStage p_stage, const String &p_source_code, ShaderLanguage p_language);
  73. typedef void (*InvalidationCallback)(void *);
  74. private:
  75. static ShaderCompileToSPIRVFunction compile_to_spirv_function;
  76. static ShaderCacheFunction cache_function;
  77. static ShaderSPIRVGetCacheKeyFunction get_spirv_cache_key_function;
  78. static RenderingDevice *singleton;
  79. RenderingContextDriver *context = nullptr;
  80. RenderingDeviceDriver *driver = nullptr;
  81. RenderingContextDriver::Device device;
  82. bool local_device_processing = false;
  83. bool is_main_instance = false;
  84. protected:
  85. static void _bind_methods();
  86. #ifndef DISABLE_DEPRECATED
  87. RID _shader_create_from_bytecode_bind_compat_79606(const Vector<uint8_t> &p_shader_binary);
  88. static void _bind_compatibility_methods();
  89. #endif
  90. /***************************/
  91. /**** ID INFRASTRUCTURE ****/
  92. /***************************/
  93. public:
  94. //base numeric ID for all types
  95. enum {
  96. INVALID_FORMAT_ID = -1
  97. };
  98. enum IDType {
  99. ID_TYPE_FRAMEBUFFER_FORMAT,
  100. ID_TYPE_VERTEX_FORMAT,
  101. ID_TYPE_DRAW_LIST,
  102. ID_TYPE_COMPUTE_LIST = 4,
  103. ID_TYPE_MAX,
  104. ID_BASE_SHIFT = 58, // 5 bits for ID types.
  105. ID_MASK = (ID_BASE_SHIFT - 1),
  106. };
  107. private:
  108. HashMap<RID, HashSet<RID>> dependency_map; // IDs to IDs that depend on it.
  109. HashMap<RID, HashSet<RID>> reverse_dependency_map; // Same as above, but in reverse.
  110. void _add_dependency(RID p_id, RID p_depends_on);
  111. void _free_dependencies(RID p_id);
  112. private:
  113. /***************************/
  114. /**** BUFFER MANAGEMENT ****/
  115. /***************************/
  116. // These are temporary buffers on CPU memory that hold
  117. // the information until the CPU fetches it and places it
  118. // either on GPU buffers, or images (textures). It ensures
  119. // updates are properly synchronized with whatever the
  120. // GPU is doing.
  121. //
  122. // The logic here is as follows, only 3 of these
  123. // blocks are created at the beginning (one per frame)
  124. // they can each belong to a frame (assigned to current when
  125. // used) and they can only be reused after the same frame is
  126. // recycled.
  127. //
  128. // When CPU requires to allocate more than what is available,
  129. // more of these buffers are created. If a limit is reached,
  130. // then a fence will ensure will wait for blocks allocated
  131. // in previous frames are processed. If that fails, then
  132. // another fence will ensure everything pending for the current
  133. // frame is processed (effectively stalling).
  134. //
  135. // See the comments in the code to understand better how it works.
  136. enum StagingRequiredAction {
  137. STAGING_REQUIRED_ACTION_NONE,
  138. STAGING_REQUIRED_ACTION_FLUSH_AND_STALL_ALL,
  139. STAGING_REQUIRED_ACTION_STALL_PREVIOUS,
  140. };
  141. struct StagingBufferBlock {
  142. RDD::BufferID driver_id;
  143. uint64_t frame_used = 0;
  144. uint32_t fill_amount = 0;
  145. };
  146. struct StagingBuffers {
  147. Vector<StagingBufferBlock> blocks;
  148. int current = 0;
  149. uint32_t block_size = 0;
  150. uint64_t max_size = 0;
  151. BitField<RDD::BufferUsageBits> usage_bits;
  152. bool used = false;
  153. };
  154. Error _staging_buffer_allocate(StagingBuffers &p_staging_buffers, uint32_t p_amount, uint32_t p_required_align, uint32_t &r_alloc_offset, uint32_t &r_alloc_size, StagingRequiredAction &r_required_action, bool p_can_segment = true);
  155. void _staging_buffer_execute_required_action(StagingBuffers &p_staging_buffers, StagingRequiredAction p_required_action);
  156. Error _insert_staging_block(StagingBuffers &p_staging_buffers);
  157. StagingBuffers upload_staging_buffers;
  158. StagingBuffers download_staging_buffers;
  159. struct Buffer {
  160. RDD::BufferID driver_id;
  161. uint32_t size = 0;
  162. BitField<RDD::BufferUsageBits> usage;
  163. RDG::ResourceTracker *draw_tracker = nullptr;
  164. int32_t transfer_worker_index = -1;
  165. uint64_t transfer_worker_operation = 0;
  166. };
  167. Buffer *_get_buffer_from_owner(RID p_buffer);
  168. Error _buffer_initialize(Buffer *p_buffer, const uint8_t *p_data, size_t p_data_size, uint32_t p_required_align = 32);
  169. void update_perf_report();
  170. // flag for batching descriptor sets
  171. bool descriptor_set_batching = true;
  172. // When true, the final draw call that copies our offscreen result into the Swapchain is put into its
  173. // own cmd buffer, so that the whole rendering can start early instead of having to wait for the
  174. // swapchain semaphore to be signaled (which causes bubbles).
  175. bool split_swapchain_into_its_own_cmd_buffer = true;
  176. uint32_t gpu_copy_count = 0;
  177. uint32_t copy_bytes_count = 0;
  178. String perf_report_text;
  179. RID_Owner<Buffer, true> uniform_buffer_owner;
  180. RID_Owner<Buffer, true> storage_buffer_owner;
  181. RID_Owner<Buffer, true> texture_buffer_owner;
  182. struct BufferGetDataRequest {
  183. uint32_t frame_local_index = 0;
  184. uint32_t frame_local_count = 0;
  185. Callable callback;
  186. uint32_t size = 0;
  187. };
  188. public:
  189. Error buffer_copy(RID p_src_buffer, RID p_dst_buffer, uint32_t p_src_offset, uint32_t p_dst_offset, uint32_t p_size);
  190. Error buffer_update(RID p_buffer, uint32_t p_offset, uint32_t p_size, const void *p_data);
  191. Error buffer_clear(RID p_buffer, uint32_t p_offset, uint32_t p_size);
  192. Vector<uint8_t> buffer_get_data(RID p_buffer, uint32_t p_offset = 0, uint32_t p_size = 0); // This causes stall, only use to retrieve large buffers for saving.
  193. Error buffer_get_data_async(RID p_buffer, const Callable &p_callback, uint32_t p_offset = 0, uint32_t p_size = 0);
  194. /*****************/
  195. /**** TEXTURE ****/
  196. /*****************/
  197. // In modern APIs, the concept of textures may not exist;
  198. // instead there is the image (the memory pretty much,
  199. // the view (how the memory is interpreted) and the
  200. // sampler (how it's sampled from the shader).
  201. //
  202. // Texture here includes the first two stages, but
  203. // It's possible to create textures sharing the image
  204. // but with different views. The main use case for this
  205. // is textures that can be read as both SRGB/Linear,
  206. // or slices of a texture (a mipmap, a layer, a 3D slice)
  207. // for a framebuffer to render into it.
  208. struct Texture {
  209. struct SharedFallback {
  210. uint32_t revision = 1;
  211. RDD::TextureID texture;
  212. RDG::ResourceTracker *texture_tracker = nullptr;
  213. RDD::BufferID buffer;
  214. RDG::ResourceTracker *buffer_tracker = nullptr;
  215. bool raw_reinterpretation = false;
  216. };
  217. RDD::TextureID driver_id;
  218. TextureType type = TEXTURE_TYPE_MAX;
  219. DataFormat format = DATA_FORMAT_MAX;
  220. TextureSamples samples = TEXTURE_SAMPLES_MAX;
  221. TextureSliceType slice_type = TEXTURE_SLICE_MAX;
  222. Rect2i slice_rect;
  223. uint32_t width = 0;
  224. uint32_t height = 0;
  225. uint32_t depth = 0;
  226. uint32_t layers = 0;
  227. uint32_t mipmaps = 0;
  228. uint32_t usage_flags = 0;
  229. uint32_t base_mipmap = 0;
  230. uint32_t base_layer = 0;
  231. Vector<DataFormat> allowed_shared_formats;
  232. bool is_resolve_buffer = false;
  233. bool is_discardable = false;
  234. bool has_initial_data = false;
  235. BitField<RDD::TextureAspectBits> read_aspect_flags;
  236. BitField<RDD::TextureAspectBits> barrier_aspect_flags;
  237. bool bound = false; // Bound to framebuffer.
  238. RID owner;
  239. RDG::ResourceTracker *draw_tracker = nullptr;
  240. HashMap<Rect2i, RDG::ResourceTracker *> slice_trackers;
  241. SharedFallback *shared_fallback = nullptr;
  242. int32_t transfer_worker_index = -1;
  243. uint64_t transfer_worker_operation = 0;
  244. RDD::TextureSubresourceRange barrier_range() const {
  245. RDD::TextureSubresourceRange r;
  246. r.aspect = barrier_aspect_flags;
  247. r.base_mipmap = base_mipmap;
  248. r.mipmap_count = mipmaps;
  249. r.base_layer = base_layer;
  250. r.layer_count = layers;
  251. return r;
  252. }
  253. TextureFormat texture_format() const {
  254. TextureFormat tf;
  255. tf.format = format;
  256. tf.width = width;
  257. tf.height = height;
  258. tf.depth = depth;
  259. tf.array_layers = layers;
  260. tf.mipmaps = mipmaps;
  261. tf.texture_type = type;
  262. tf.samples = samples;
  263. tf.usage_bits = usage_flags;
  264. tf.shareable_formats = allowed_shared_formats;
  265. tf.is_resolve_buffer = is_resolve_buffer;
  266. tf.is_discardable = is_discardable;
  267. return tf;
  268. }
  269. };
  270. RID_Owner<Texture, true> texture_owner;
  271. uint32_t texture_upload_region_size_px = 0;
  272. uint32_t texture_download_region_size_px = 0;
  273. Vector<uint8_t> _texture_get_data(Texture *tex, uint32_t p_layer, bool p_2d = false);
  274. uint32_t _texture_layer_count(Texture *p_texture) const;
  275. uint32_t _texture_alignment(Texture *p_texture) const;
  276. Error _texture_initialize(RID p_texture, uint32_t p_layer, const Vector<uint8_t> &p_data);
  277. void _texture_check_shared_fallback(Texture *p_texture);
  278. void _texture_update_shared_fallback(RID p_texture_rid, Texture *p_texture, bool p_for_writing);
  279. void _texture_free_shared_fallback(Texture *p_texture);
  280. void _texture_copy_shared(RID p_src_texture_rid, Texture *p_src_texture, RID p_dst_texture_rid, Texture *p_dst_texture);
  281. void _texture_create_reinterpret_buffer(Texture *p_texture);
  282. struct TextureGetDataRequest {
  283. uint32_t frame_local_index = 0;
  284. uint32_t frame_local_count = 0;
  285. Callable callback;
  286. uint32_t width = 0;
  287. uint32_t height = 0;
  288. uint32_t depth = 0;
  289. uint32_t mipmaps = 0;
  290. RDD::DataFormat format = RDD::DATA_FORMAT_MAX;
  291. };
  292. public:
  293. struct TextureView {
  294. DataFormat format_override = DATA_FORMAT_MAX; // // Means, use same as format.
  295. TextureSwizzle swizzle_r = TEXTURE_SWIZZLE_R;
  296. TextureSwizzle swizzle_g = TEXTURE_SWIZZLE_G;
  297. TextureSwizzle swizzle_b = TEXTURE_SWIZZLE_B;
  298. TextureSwizzle swizzle_a = TEXTURE_SWIZZLE_A;
  299. bool operator==(const TextureView &p_other) const {
  300. if (format_override != p_other.format_override) {
  301. return false;
  302. } else if (swizzle_r != p_other.swizzle_r) {
  303. return false;
  304. } else if (swizzle_g != p_other.swizzle_g) {
  305. return false;
  306. } else if (swizzle_b != p_other.swizzle_b) {
  307. return false;
  308. } else if (swizzle_a != p_other.swizzle_a) {
  309. return false;
  310. } else {
  311. return true;
  312. }
  313. }
  314. };
  315. RID texture_create(const TextureFormat &p_format, const TextureView &p_view, const Vector<Vector<uint8_t>> &p_data = Vector<Vector<uint8_t>>());
  316. RID texture_create_shared(const TextureView &p_view, RID p_with_texture);
  317. RID texture_create_from_extension(TextureType p_type, DataFormat p_format, TextureSamples p_samples, BitField<RenderingDevice::TextureUsageBits> p_usage, uint64_t p_image, uint64_t p_width, uint64_t p_height, uint64_t p_depth, uint64_t p_layers);
  318. RID texture_create_shared_from_slice(const TextureView &p_view, RID p_with_texture, uint32_t p_layer, uint32_t p_mipmap, uint32_t p_mipmaps = 1, TextureSliceType p_slice_type = TEXTURE_SLICE_2D, uint32_t p_layers = 0);
  319. Error texture_update(RID p_texture, uint32_t p_layer, const Vector<uint8_t> &p_data);
  320. Vector<uint8_t> texture_get_data(RID p_texture, uint32_t p_layer); // CPU textures will return immediately, while GPU textures will most likely force a flush
  321. Error texture_get_data_async(RID p_texture, uint32_t p_layer, const Callable &p_callback);
  322. bool texture_is_format_supported_for_usage(DataFormat p_format, BitField<TextureUsageBits> p_usage) const;
  323. bool texture_is_shared(RID p_texture);
  324. bool texture_is_valid(RID p_texture);
  325. TextureFormat texture_get_format(RID p_texture);
  326. Size2i texture_size(RID p_texture);
  327. #ifndef DISABLE_DEPRECATED
  328. uint64_t texture_get_native_handle(RID p_texture);
  329. #endif
  330. 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);
  331. 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);
  332. Error texture_resolve_multisample(RID p_from_texture, RID p_to_texture);
  333. void texture_set_discardable(RID p_texture, bool p_discardable);
  334. bool texture_is_discardable(RID p_texture);
  335. /*********************/
  336. /**** FRAMEBUFFER ****/
  337. /*********************/
  338. // In modern APIs, generally, framebuffers work similar to how they
  339. // do in OpenGL, with the exception that
  340. // the "format" (RDD::RenderPassID) is not dynamic
  341. // and must be more or less the same as the one
  342. // used for the render pipelines.
  343. struct AttachmentFormat {
  344. enum : uint32_t {
  345. UNUSED_ATTACHMENT = 0xFFFFFFFF
  346. };
  347. DataFormat format;
  348. TextureSamples samples;
  349. uint32_t usage_flags;
  350. AttachmentFormat() {
  351. format = DATA_FORMAT_R8G8B8A8_UNORM;
  352. samples = TEXTURE_SAMPLES_1;
  353. usage_flags = 0;
  354. }
  355. };
  356. struct FramebufferPass {
  357. Vector<int32_t> color_attachments;
  358. Vector<int32_t> input_attachments;
  359. Vector<int32_t> resolve_attachments;
  360. Vector<int32_t> preserve_attachments;
  361. int32_t depth_attachment = ATTACHMENT_UNUSED;
  362. int32_t vrs_attachment = ATTACHMENT_UNUSED; // density map for VRS, only used if supported
  363. };
  364. typedef int64_t FramebufferFormatID;
  365. private:
  366. struct FramebufferFormatKey {
  367. Vector<AttachmentFormat> attachments;
  368. Vector<FramebufferPass> passes;
  369. uint32_t view_count = 1;
  370. bool operator<(const FramebufferFormatKey &p_key) const {
  371. if (view_count != p_key.view_count) {
  372. return view_count < p_key.view_count;
  373. }
  374. uint32_t pass_size = passes.size();
  375. uint32_t key_pass_size = p_key.passes.size();
  376. if (pass_size != key_pass_size) {
  377. return pass_size < key_pass_size;
  378. }
  379. const FramebufferPass *pass_ptr = passes.ptr();
  380. const FramebufferPass *key_pass_ptr = p_key.passes.ptr();
  381. for (uint32_t i = 0; i < pass_size; i++) {
  382. { // Compare color attachments.
  383. uint32_t attachment_size = pass_ptr[i].color_attachments.size();
  384. uint32_t key_attachment_size = key_pass_ptr[i].color_attachments.size();
  385. if (attachment_size != key_attachment_size) {
  386. return attachment_size < key_attachment_size;
  387. }
  388. const int32_t *pass_attachment_ptr = pass_ptr[i].color_attachments.ptr();
  389. const int32_t *key_pass_attachment_ptr = key_pass_ptr[i].color_attachments.ptr();
  390. for (uint32_t j = 0; j < attachment_size; j++) {
  391. if (pass_attachment_ptr[j] != key_pass_attachment_ptr[j]) {
  392. return pass_attachment_ptr[j] < key_pass_attachment_ptr[j];
  393. }
  394. }
  395. }
  396. { // Compare input attachments.
  397. uint32_t attachment_size = pass_ptr[i].input_attachments.size();
  398. uint32_t key_attachment_size = key_pass_ptr[i].input_attachments.size();
  399. if (attachment_size != key_attachment_size) {
  400. return attachment_size < key_attachment_size;
  401. }
  402. const int32_t *pass_attachment_ptr = pass_ptr[i].input_attachments.ptr();
  403. const int32_t *key_pass_attachment_ptr = key_pass_ptr[i].input_attachments.ptr();
  404. for (uint32_t j = 0; j < attachment_size; j++) {
  405. if (pass_attachment_ptr[j] != key_pass_attachment_ptr[j]) {
  406. return pass_attachment_ptr[j] < key_pass_attachment_ptr[j];
  407. }
  408. }
  409. }
  410. { // Compare resolve attachments.
  411. uint32_t attachment_size = pass_ptr[i].resolve_attachments.size();
  412. uint32_t key_attachment_size = key_pass_ptr[i].resolve_attachments.size();
  413. if (attachment_size != key_attachment_size) {
  414. return attachment_size < key_attachment_size;
  415. }
  416. const int32_t *pass_attachment_ptr = pass_ptr[i].resolve_attachments.ptr();
  417. const int32_t *key_pass_attachment_ptr = key_pass_ptr[i].resolve_attachments.ptr();
  418. for (uint32_t j = 0; j < attachment_size; j++) {
  419. if (pass_attachment_ptr[j] != key_pass_attachment_ptr[j]) {
  420. return pass_attachment_ptr[j] < key_pass_attachment_ptr[j];
  421. }
  422. }
  423. }
  424. { // Compare preserve attachments.
  425. uint32_t attachment_size = pass_ptr[i].preserve_attachments.size();
  426. uint32_t key_attachment_size = key_pass_ptr[i].preserve_attachments.size();
  427. if (attachment_size != key_attachment_size) {
  428. return attachment_size < key_attachment_size;
  429. }
  430. const int32_t *pass_attachment_ptr = pass_ptr[i].preserve_attachments.ptr();
  431. const int32_t *key_pass_attachment_ptr = key_pass_ptr[i].preserve_attachments.ptr();
  432. for (uint32_t j = 0; j < attachment_size; j++) {
  433. if (pass_attachment_ptr[j] != key_pass_attachment_ptr[j]) {
  434. return pass_attachment_ptr[j] < key_pass_attachment_ptr[j];
  435. }
  436. }
  437. }
  438. if (pass_ptr[i].depth_attachment != key_pass_ptr[i].depth_attachment) {
  439. return pass_ptr[i].depth_attachment < key_pass_ptr[i].depth_attachment;
  440. }
  441. }
  442. int as = attachments.size();
  443. int bs = p_key.attachments.size();
  444. if (as != bs) {
  445. return as < bs;
  446. }
  447. const AttachmentFormat *af_a = attachments.ptr();
  448. const AttachmentFormat *af_b = p_key.attachments.ptr();
  449. for (int i = 0; i < as; i++) {
  450. const AttachmentFormat &a = af_a[i];
  451. const AttachmentFormat &b = af_b[i];
  452. if (a.format != b.format) {
  453. return a.format < b.format;
  454. }
  455. if (a.samples != b.samples) {
  456. return a.samples < b.samples;
  457. }
  458. if (a.usage_flags != b.usage_flags) {
  459. return a.usage_flags < b.usage_flags;
  460. }
  461. }
  462. return false; // Equal.
  463. }
  464. };
  465. static RDD::RenderPassID _render_pass_create(RenderingDeviceDriver *p_driver, const Vector<AttachmentFormat> &p_attachments, const Vector<FramebufferPass> &p_passes, VectorView<RDD::AttachmentLoadOp> p_load_ops, VectorView<RDD::AttachmentStoreOp> p_store_ops, uint32_t p_view_count = 1, Vector<TextureSamples> *r_samples = nullptr);
  466. static RDD::RenderPassID _render_pass_create_from_graph(RenderingDeviceDriver *p_driver, VectorView<RDD::AttachmentLoadOp> p_load_ops, VectorView<RDD::AttachmentStoreOp> p_store_ops, void *p_user_data);
  467. // This is a cache and it's never freed, it ensures
  468. // IDs for a given format are always unique.
  469. RBMap<FramebufferFormatKey, FramebufferFormatID> framebuffer_format_cache;
  470. struct FramebufferFormat {
  471. const RBMap<FramebufferFormatKey, FramebufferFormatID>::Element *E;
  472. RDD::RenderPassID render_pass; // Here for constructing shaders, never used, see section (7.2. Render Pass Compatibility from Vulkan spec).
  473. Vector<TextureSamples> pass_samples;
  474. uint32_t view_count = 1; // Number of views.
  475. };
  476. HashMap<FramebufferFormatID, FramebufferFormat> framebuffer_formats;
  477. struct Framebuffer {
  478. RenderingDevice *rendering_device = nullptr;
  479. FramebufferFormatID format_id;
  480. uint32_t storage_mask = 0;
  481. Vector<RID> texture_ids;
  482. InvalidationCallback invalidated_callback = nullptr;
  483. void *invalidated_callback_userdata = nullptr;
  484. RDG::FramebufferCache *framebuffer_cache = nullptr;
  485. Size2 size;
  486. uint32_t view_count;
  487. };
  488. RID_Owner<Framebuffer, true> framebuffer_owner;
  489. public:
  490. // This ID is warranted to be unique for the same formats, does not need to be freed
  491. FramebufferFormatID framebuffer_format_create(const Vector<AttachmentFormat> &p_format, uint32_t p_view_count = 1);
  492. FramebufferFormatID framebuffer_format_create_multipass(const Vector<AttachmentFormat> &p_attachments, const Vector<FramebufferPass> &p_passes, uint32_t p_view_count = 1);
  493. FramebufferFormatID framebuffer_format_create_empty(TextureSamples p_samples = TEXTURE_SAMPLES_1);
  494. TextureSamples framebuffer_format_get_texture_samples(FramebufferFormatID p_format, uint32_t p_pass = 0);
  495. RID framebuffer_create(const Vector<RID> &p_texture_attachments, FramebufferFormatID p_format_check = INVALID_ID, uint32_t p_view_count = 1);
  496. RID framebuffer_create_multipass(const Vector<RID> &p_texture_attachments, const Vector<FramebufferPass> &p_passes, FramebufferFormatID p_format_check = INVALID_ID, uint32_t p_view_count = 1);
  497. RID framebuffer_create_empty(const Size2i &p_size, TextureSamples p_samples = TEXTURE_SAMPLES_1, FramebufferFormatID p_format_check = INVALID_ID);
  498. bool framebuffer_is_valid(RID p_framebuffer) const;
  499. void framebuffer_set_invalidation_callback(RID p_framebuffer, InvalidationCallback p_callback, void *p_userdata);
  500. FramebufferFormatID framebuffer_get_format(RID p_framebuffer);
  501. Size2 framebuffer_get_size(RID p_framebuffer);
  502. /*****************/
  503. /**** SAMPLER ****/
  504. /*****************/
  505. private:
  506. RID_Owner<RDD::SamplerID, true> sampler_owner;
  507. public:
  508. RID sampler_create(const SamplerState &p_state);
  509. bool sampler_is_format_supported_for_filter(DataFormat p_format, SamplerFilter p_sampler_filter) const;
  510. /**********************/
  511. /**** VERTEX ARRAY ****/
  512. /**********************/
  513. typedef int64_t VertexFormatID;
  514. private:
  515. // Vertex buffers in Vulkan are similar to how
  516. // they work in OpenGL, except that instead of
  517. // an attribute index, there is a buffer binding
  518. // index (for binding the buffers in real-time)
  519. // and a location index (what is used in the shader).
  520. //
  521. // This mapping is done here internally, and it's not
  522. // exposed.
  523. RID_Owner<Buffer, true> vertex_buffer_owner;
  524. struct VertexDescriptionKey {
  525. Vector<VertexAttribute> vertex_formats;
  526. bool operator==(const VertexDescriptionKey &p_key) const {
  527. int vdc = vertex_formats.size();
  528. int vdck = p_key.vertex_formats.size();
  529. if (vdc != vdck) {
  530. return false;
  531. } else {
  532. const VertexAttribute *a_ptr = vertex_formats.ptr();
  533. const VertexAttribute *b_ptr = p_key.vertex_formats.ptr();
  534. for (int i = 0; i < vdc; i++) {
  535. const VertexAttribute &a = a_ptr[i];
  536. const VertexAttribute &b = b_ptr[i];
  537. if (a.location != b.location) {
  538. return false;
  539. }
  540. if (a.offset != b.offset) {
  541. return false;
  542. }
  543. if (a.format != b.format) {
  544. return false;
  545. }
  546. if (a.stride != b.stride) {
  547. return false;
  548. }
  549. if (a.frequency != b.frequency) {
  550. return false;
  551. }
  552. }
  553. return true; // They are equal.
  554. }
  555. }
  556. uint32_t hash() const {
  557. int vdc = vertex_formats.size();
  558. uint32_t h = hash_murmur3_one_32(vdc);
  559. const VertexAttribute *ptr = vertex_formats.ptr();
  560. for (int i = 0; i < vdc; i++) {
  561. const VertexAttribute &vd = ptr[i];
  562. h = hash_murmur3_one_32(vd.location, h);
  563. h = hash_murmur3_one_32(vd.offset, h);
  564. h = hash_murmur3_one_32(vd.format, h);
  565. h = hash_murmur3_one_32(vd.stride, h);
  566. h = hash_murmur3_one_32(vd.frequency, h);
  567. }
  568. return hash_fmix32(h);
  569. }
  570. };
  571. struct VertexDescriptionHash {
  572. static _FORCE_INLINE_ uint32_t hash(const VertexDescriptionKey &p_key) {
  573. return p_key.hash();
  574. }
  575. };
  576. // This is a cache and it's never freed, it ensures that
  577. // ID used for a specific format always remain the same.
  578. HashMap<VertexDescriptionKey, VertexFormatID, VertexDescriptionHash> vertex_format_cache;
  579. struct VertexDescriptionCache {
  580. Vector<VertexAttribute> vertex_formats;
  581. RDD::VertexFormatID driver_id;
  582. };
  583. HashMap<VertexFormatID, VertexDescriptionCache> vertex_formats;
  584. struct VertexArray {
  585. RID buffer;
  586. VertexFormatID description;
  587. int vertex_count = 0;
  588. uint32_t max_instances_allowed = 0;
  589. Vector<RDD::BufferID> buffers; // Not owned, just referenced.
  590. Vector<RDG::ResourceTracker *> draw_trackers; // Not owned, just referenced.
  591. Vector<uint64_t> offsets;
  592. Vector<int32_t> transfer_worker_indices;
  593. Vector<uint64_t> transfer_worker_operations;
  594. HashSet<RID> untracked_buffers;
  595. };
  596. RID_Owner<VertexArray, true> vertex_array_owner;
  597. struct IndexBuffer : public Buffer {
  598. uint32_t max_index = 0; // Used for validation.
  599. uint32_t index_count = 0;
  600. IndexBufferFormat format = INDEX_BUFFER_FORMAT_UINT16;
  601. bool supports_restart_indices = false;
  602. };
  603. RID_Owner<IndexBuffer, true> index_buffer_owner;
  604. struct IndexArray {
  605. uint32_t max_index = 0; // Remember the maximum index here too, for validation.
  606. RDD::BufferID driver_id; // Not owned, inherited from index buffer.
  607. RDG::ResourceTracker *draw_tracker = nullptr; // Not owned, inherited from index buffer.
  608. uint32_t offset = 0;
  609. uint32_t indices = 0;
  610. IndexBufferFormat format = INDEX_BUFFER_FORMAT_UINT16;
  611. bool supports_restart_indices = false;
  612. int32_t transfer_worker_index = -1;
  613. uint64_t transfer_worker_operation = 0;
  614. };
  615. RID_Owner<IndexArray, true> index_array_owner;
  616. public:
  617. RID vertex_buffer_create(uint32_t p_size_bytes, const Vector<uint8_t> &p_data = Vector<uint8_t>(), bool p_use_as_storage = false);
  618. // This ID is warranted to be unique for the same formats, does not need to be freed
  619. VertexFormatID vertex_format_create(const Vector<VertexAttribute> &p_vertex_descriptions);
  620. RID vertex_array_create(uint32_t p_vertex_count, VertexFormatID p_vertex_format, const Vector<RID> &p_src_buffers, const Vector<uint64_t> &p_offsets = Vector<uint64_t>());
  621. 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);
  622. RID index_array_create(RID p_index_buffer, uint32_t p_index_offset, uint32_t p_index_count);
  623. /****************/
  624. /**** SHADER ****/
  625. /****************/
  626. // Some APIs (e.g., Vulkan) specifies a really complex behavior for the application
  627. // in order to tell when descriptor sets need to be re-bound (or not).
  628. // "When binding a descriptor set (see Descriptor Set Binding) to set
  629. // number N, if the previously bound descriptor sets for sets zero
  630. // through N-1 were all bound using compatible pipeline layouts,
  631. // then performing this binding does not disturb any of the lower numbered sets.
  632. // If, additionally, the previous bound descriptor set for set N was
  633. // bound using a pipeline layout compatible for set N, then the bindings
  634. // in sets numbered greater than N are also not disturbed."
  635. // As a result, we need to figure out quickly when something is no longer "compatible".
  636. // in order to avoid costly rebinds.
  637. private:
  638. struct UniformSetFormat {
  639. Vector<ShaderUniform> uniforms;
  640. _FORCE_INLINE_ bool operator<(const UniformSetFormat &p_other) const {
  641. if (uniforms.size() != p_other.uniforms.size()) {
  642. return uniforms.size() < p_other.uniforms.size();
  643. }
  644. for (int i = 0; i < uniforms.size(); i++) {
  645. if (uniforms[i] < p_other.uniforms[i]) {
  646. return true;
  647. } else if (p_other.uniforms[i] < uniforms[i]) {
  648. return false;
  649. }
  650. }
  651. return false;
  652. }
  653. };
  654. // Always grows, never shrinks, ensuring unique IDs, but we assume
  655. // the amount of formats will never be a problem, as the amount of shaders
  656. // in a game is limited.
  657. RBMap<UniformSetFormat, uint32_t> uniform_set_format_cache;
  658. // Shaders in Vulkan are just pretty much
  659. // precompiled blocks of SPIR-V bytecode. They
  660. // are most likely not really compiled to host
  661. // assembly until a pipeline is created.
  662. //
  663. // When supplying the shaders, this implementation
  664. // will use the reflection abilities of glslang to
  665. // understand and cache everything required to
  666. // create and use the descriptor sets (Vulkan's
  667. // biggest pain).
  668. //
  669. // Additionally, hashes are created for every set
  670. // to do quick validation and ensuring the user
  671. // does not submit something invalid.
  672. struct Shader : public ShaderDescription {
  673. String name; // Used for debug.
  674. RDD::ShaderID driver_id;
  675. uint32_t layout_hash = 0;
  676. BitField<RDD::PipelineStageBits> stage_bits;
  677. Vector<uint32_t> set_formats;
  678. };
  679. String _shader_uniform_debug(RID p_shader, int p_set = -1);
  680. RID_Owner<Shader, true> shader_owner;
  681. #ifndef DISABLE_DEPRECATED
  682. public:
  683. enum BarrierMask {
  684. BARRIER_MASK_VERTEX = 1,
  685. BARRIER_MASK_FRAGMENT = 8,
  686. BARRIER_MASK_COMPUTE = 2,
  687. BARRIER_MASK_TRANSFER = 4,
  688. BARRIER_MASK_RASTER = BARRIER_MASK_VERTEX | BARRIER_MASK_FRAGMENT, // 9,
  689. BARRIER_MASK_ALL_BARRIERS = 0x7FFF, // all flags set
  690. BARRIER_MASK_NO_BARRIER = 0x8000,
  691. };
  692. enum InitialAction {
  693. INITIAL_ACTION_LOAD,
  694. INITIAL_ACTION_CLEAR,
  695. INITIAL_ACTION_DISCARD,
  696. INITIAL_ACTION_MAX,
  697. INITIAL_ACTION_CLEAR_REGION = INITIAL_ACTION_CLEAR,
  698. INITIAL_ACTION_CLEAR_REGION_CONTINUE = INITIAL_ACTION_CLEAR,
  699. INITIAL_ACTION_KEEP = INITIAL_ACTION_LOAD,
  700. INITIAL_ACTION_DROP = INITIAL_ACTION_DISCARD,
  701. INITIAL_ACTION_CONTINUE = INITIAL_ACTION_LOAD,
  702. };
  703. enum FinalAction {
  704. FINAL_ACTION_STORE,
  705. FINAL_ACTION_DISCARD,
  706. FINAL_ACTION_MAX,
  707. FINAL_ACTION_READ = FINAL_ACTION_STORE,
  708. FINAL_ACTION_CONTINUE = FINAL_ACTION_STORE,
  709. };
  710. void barrier(BitField<BarrierMask> p_from = BARRIER_MASK_ALL_BARRIERS, BitField<BarrierMask> p_to = BARRIER_MASK_ALL_BARRIERS);
  711. void full_barrier();
  712. void draw_command_insert_label(String p_label_name, const Color &p_color = Color(1, 1, 1, 1));
  713. 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>());
  714. Error draw_list_switch_to_next_pass_split(uint32_t p_splits, DrawListID *r_split_ids);
  715. Vector<int64_t> _draw_list_begin_split(RID p_framebuffer, uint32_t p_splits, 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 TypedArray<RID> &p_storage_textures = TypedArray<RID>());
  716. Vector<int64_t> _draw_list_switch_to_next_pass_split(uint32_t p_splits);
  717. private:
  718. void _draw_list_end_bind_compat_81356(BitField<BarrierMask> p_post_barrier);
  719. void _compute_list_end_bind_compat_81356(BitField<BarrierMask> p_post_barrier);
  720. void _barrier_bind_compat_81356(BitField<BarrierMask> p_from, BitField<BarrierMask> p_to);
  721. void _draw_list_end_bind_compat_84976(BitField<BarrierMask> p_post_barrier);
  722. void _compute_list_end_bind_compat_84976(BitField<BarrierMask> p_post_barrier);
  723. InitialAction _convert_initial_action_84976(InitialAction p_old_initial_action);
  724. FinalAction _convert_final_action_84976(FinalAction p_old_final_action);
  725. DrawListID _draw_list_begin_bind_compat_84976(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, float p_clear_depth, uint32_t p_clear_stencil, const Rect2 &p_region, const TypedArray<RID> &p_storage_textures);
  726. ComputeListID _compute_list_begin_bind_compat_84976(bool p_allow_draw_overlap);
  727. Error _buffer_update_bind_compat_84976(RID p_buffer, uint32_t p_offset, uint32_t p_size, const Vector<uint8_t> &p_data, BitField<BarrierMask> p_post_barrier);
  728. Error _buffer_clear_bind_compat_84976(RID p_buffer, uint32_t p_offset, uint32_t p_size, BitField<BarrierMask> p_post_barrier);
  729. Error _texture_update_bind_compat_84976(RID p_texture, uint32_t p_layer, const Vector<uint8_t> &p_data, BitField<BarrierMask> p_post_barrier);
  730. Error _texture_copy_bind_compat_84976(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, BitField<BarrierMask> p_post_barrier);
  731. Error _texture_clear_bind_compat_84976(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, BitField<BarrierMask> p_post_barrier);
  732. Error _texture_resolve_multisample_bind_compat_84976(RID p_from_texture, RID p_to_texture, BitField<BarrierMask> p_post_barrier);
  733. FramebufferFormatID _screen_get_framebuffer_format_bind_compat_87340() const;
  734. DrawListID _draw_list_begin_bind_compat_90993(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, float p_clear_depth, uint32_t p_clear_stencil, const Rect2 &p_region);
  735. DrawListID _draw_list_begin_bind_compat_98670(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, float p_clear_depth, uint32_t p_clear_stencil, const Rect2 &p_region, uint32_t p_breadcrumb);
  736. #endif
  737. public:
  738. RenderingContextDriver *get_context_driver() const { return context; }
  739. const RDD::Capabilities &get_device_capabilities() const { return driver->get_capabilities(); }
  740. bool has_feature(const Features p_feature) const;
  741. Vector<uint8_t> shader_compile_spirv_from_source(ShaderStage p_stage, const String &p_source_code, ShaderLanguage p_language = SHADER_LANGUAGE_GLSL, String *r_error = nullptr, bool p_allow_cache = true);
  742. String shader_get_spirv_cache_key() const;
  743. static void shader_set_compile_to_spirv_function(ShaderCompileToSPIRVFunction p_function);
  744. static void shader_set_spirv_cache_function(ShaderCacheFunction p_function);
  745. static void shader_set_get_cache_key_function(ShaderSPIRVGetCacheKeyFunction p_function);
  746. String shader_get_binary_cache_key() const;
  747. Vector<uint8_t> shader_compile_binary_from_spirv(const Vector<ShaderStageSPIRVData> &p_spirv, const String &p_shader_name = "");
  748. RID shader_create_from_spirv(const Vector<ShaderStageSPIRVData> &p_spirv, const String &p_shader_name = "");
  749. RID shader_create_from_bytecode(const Vector<uint8_t> &p_shader_binary, RID p_placeholder = RID());
  750. RID shader_create_placeholder();
  751. void shader_destroy_modules(RID p_shader);
  752. uint64_t shader_get_vertex_input_attribute_mask(RID p_shader);
  753. /******************/
  754. /**** UNIFORMS ****/
  755. /******************/
  756. String get_perf_report() const;
  757. enum StorageBufferUsage {
  758. STORAGE_BUFFER_USAGE_DISPATCH_INDIRECT = 1,
  759. };
  760. /*****************/
  761. /**** BUFFERS ****/
  762. /*****************/
  763. RID uniform_buffer_create(uint32_t p_size_bytes, const Vector<uint8_t> &p_data = Vector<uint8_t>());
  764. RID storage_buffer_create(uint32_t p_size, const Vector<uint8_t> &p_data = Vector<uint8_t>(), BitField<StorageBufferUsage> p_usage = 0);
  765. RID texture_buffer_create(uint32_t p_size_elements, DataFormat p_format, const Vector<uint8_t> &p_data = Vector<uint8_t>());
  766. struct Uniform {
  767. UniformType uniform_type = UNIFORM_TYPE_IMAGE;
  768. uint32_t binding = 0; // Binding index as specified in shader.
  769. // This flag specifies that this is an immutable sampler to be set when creating pipeline layout.
  770. bool immutable_sampler = false;
  771. private:
  772. // In most cases only one ID is provided per binding, so avoid allocating memory unnecessarily for performance.
  773. RID id; // If only one is provided, this is used.
  774. Vector<RID> ids; // If multiple ones are provided, this is used instead.
  775. public:
  776. _FORCE_INLINE_ uint32_t get_id_count() const {
  777. return (id.is_valid() ? 1 : ids.size());
  778. }
  779. _FORCE_INLINE_ RID get_id(uint32_t p_idx) const {
  780. if (id.is_valid()) {
  781. ERR_FAIL_COND_V(p_idx != 0, RID());
  782. return id;
  783. } else {
  784. return ids[p_idx];
  785. }
  786. }
  787. _FORCE_INLINE_ void set_id(uint32_t p_idx, RID p_id) {
  788. if (id.is_valid()) {
  789. ERR_FAIL_COND(p_idx != 0);
  790. id = p_id;
  791. } else {
  792. ids.write[p_idx] = p_id;
  793. }
  794. }
  795. _FORCE_INLINE_ void append_id(RID p_id) {
  796. if (ids.is_empty()) {
  797. if (id == RID()) {
  798. id = p_id;
  799. } else {
  800. ids.push_back(id);
  801. ids.push_back(p_id);
  802. id = RID();
  803. }
  804. } else {
  805. ids.push_back(p_id);
  806. }
  807. }
  808. _FORCE_INLINE_ void clear_ids() {
  809. id = RID();
  810. ids.clear();
  811. }
  812. _FORCE_INLINE_ Uniform(UniformType p_type, int p_binding, RID p_id) {
  813. uniform_type = p_type;
  814. binding = p_binding;
  815. id = p_id;
  816. }
  817. _FORCE_INLINE_ Uniform(UniformType p_type, int p_binding, const Vector<RID> &p_ids) {
  818. uniform_type = p_type;
  819. binding = p_binding;
  820. ids = p_ids;
  821. }
  822. _FORCE_INLINE_ Uniform() = default;
  823. };
  824. typedef Uniform PipelineImmutableSampler;
  825. RID shader_create_from_bytecode_with_samplers(const Vector<uint8_t> &p_shader_binary, RID p_placeholder = RID(), const Vector<PipelineImmutableSampler> &p_immutable_samplers = Vector<PipelineImmutableSampler>());
  826. private:
  827. static const uint32_t MAX_UNIFORM_SETS = 16;
  828. static const uint32_t MAX_PUSH_CONSTANT_SIZE = 128;
  829. // This structure contains the descriptor set. They _need_ to be allocated
  830. // for a shader (and will be erased when this shader is erased), but should
  831. // work for other shaders as long as the hash matches. This covers using
  832. // them in shader variants.
  833. //
  834. // Keep also in mind that you can share buffers between descriptor sets, so
  835. // the above restriction is not too serious.
  836. struct UniformSet {
  837. uint32_t format = 0;
  838. RID shader_id;
  839. uint32_t shader_set = 0;
  840. RDD::UniformSetID driver_id;
  841. struct AttachableTexture {
  842. uint32_t bind = 0;
  843. RID texture;
  844. };
  845. struct SharedTexture {
  846. uint32_t writing = 0;
  847. RID texture;
  848. };
  849. LocalVector<AttachableTexture> attachable_textures; // Used for validation.
  850. Vector<RDG::ResourceTracker *> draw_trackers;
  851. Vector<RDG::ResourceUsage> draw_trackers_usage;
  852. HashMap<RID, RDG::ResourceUsage> untracked_usage;
  853. LocalVector<SharedTexture> shared_textures_to_update;
  854. InvalidationCallback invalidated_callback = nullptr;
  855. void *invalidated_callback_userdata = nullptr;
  856. };
  857. RID_Owner<UniformSet, true> uniform_set_owner;
  858. void _uniform_set_update_shared(UniformSet *p_uniform_set);
  859. public:
  860. /** Bake a set of uniforms that can be bound at runtime with the given shader.
  861. * @remark Setting p_linear_pool = true while keeping the RID around for longer than the current frame will result in undefined behavior.
  862. * @param p_uniforms The uniforms to bake into a set.
  863. * @param p_shader The shader you intend to bind these uniforms with.
  864. * @param p_set_index The set. Should be in range [0; 4)
  865. * The value 4 comes from physical_device_properties.limits.maxBoundDescriptorSets. Vulkan only guarantees maxBoundDescriptorSets >= 4 (== 4 is very common on Mobile).
  866. * @param p_linear_pool If you call this function every frame (and free the returned RID within the same frame!), set it to true for better performance.
  867. * If you plan on keeping the return value around for more than one frame (e.g. Sets that are created once and reused forever) you MUST set it to false.
  868. * @return Baked descriptor set.
  869. */
  870. template <typename Collection>
  871. RID uniform_set_create(const Collection &p_uniforms, RID p_shader, uint32_t p_shader_set, bool p_linear_pool = false);
  872. bool uniform_set_is_valid(RID p_uniform_set);
  873. void uniform_set_set_invalidation_callback(RID p_uniform_set, InvalidationCallback p_callback, void *p_userdata);
  874. bool uniform_sets_have_linear_pools() const;
  875. /*******************/
  876. /**** PIPELINES ****/
  877. /*******************/
  878. // Render pipeline contains ALL the
  879. // information required for drawing.
  880. // This includes all the rasterizer state
  881. // as well as shader used, framebuffer format,
  882. // etc.
  883. // While the pipeline is just a single object
  884. // (VkPipeline) a lot of values are also saved
  885. // here to do validation (vulkan does none by
  886. // default) and warn the user if something
  887. // was not supplied as intended.
  888. private:
  889. struct RenderPipeline {
  890. // Cached values for validation.
  891. #ifdef DEBUG_ENABLED
  892. struct Validation {
  893. FramebufferFormatID framebuffer_format;
  894. uint32_t render_pass = 0;
  895. uint32_t dynamic_state = 0;
  896. VertexFormatID vertex_format;
  897. bool uses_restart_indices = false;
  898. uint32_t primitive_minimum = 0;
  899. uint32_t primitive_divisor = 0;
  900. } validation;
  901. #endif
  902. // Actual pipeline.
  903. RID shader;
  904. RDD::ShaderID shader_driver_id;
  905. uint32_t shader_layout_hash = 0;
  906. Vector<uint32_t> set_formats;
  907. RDD::PipelineID driver_id;
  908. BitField<RDD::PipelineStageBits> stage_bits;
  909. uint32_t push_constant_size = 0;
  910. };
  911. RID_Owner<RenderPipeline, true> render_pipeline_owner;
  912. bool pipeline_cache_enabled = false;
  913. size_t pipeline_cache_size = 0;
  914. String pipeline_cache_file_path;
  915. WorkerThreadPool::TaskID pipeline_cache_save_task = WorkerThreadPool::INVALID_TASK_ID;
  916. Vector<uint8_t> _load_pipeline_cache();
  917. void _update_pipeline_cache(bool p_closing = false);
  918. static void _save_pipeline_cache(void *p_data);
  919. struct ComputePipeline {
  920. RID shader;
  921. RDD::ShaderID shader_driver_id;
  922. uint32_t shader_layout_hash = 0;
  923. Vector<uint32_t> set_formats;
  924. RDD::PipelineID driver_id;
  925. uint32_t push_constant_size = 0;
  926. uint32_t local_group_size[3] = { 0, 0, 0 };
  927. };
  928. RID_Owner<ComputePipeline, true> compute_pipeline_owner;
  929. public:
  930. 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, BitField<PipelineDynamicStateFlags> p_dynamic_state_flags = 0, uint32_t p_for_render_pass = 0, const Vector<PipelineSpecializationConstant> &p_specialization_constants = Vector<PipelineSpecializationConstant>());
  931. bool render_pipeline_is_valid(RID p_pipeline);
  932. RID compute_pipeline_create(RID p_shader, const Vector<PipelineSpecializationConstant> &p_specialization_constants = Vector<PipelineSpecializationConstant>());
  933. bool compute_pipeline_is_valid(RID p_pipeline);
  934. private:
  935. /****************/
  936. /**** SCREEN ****/
  937. /****************/
  938. HashMap<DisplayServer::WindowID, RDD::SwapChainID> screen_swap_chains;
  939. HashMap<DisplayServer::WindowID, RDD::FramebufferID> screen_framebuffers;
  940. uint32_t _get_swap_chain_desired_count() const;
  941. public:
  942. Error screen_create(DisplayServer::WindowID p_screen = DisplayServer::MAIN_WINDOW_ID);
  943. Error screen_prepare_for_drawing(DisplayServer::WindowID p_screen = DisplayServer::MAIN_WINDOW_ID);
  944. int screen_get_width(DisplayServer::WindowID p_screen = DisplayServer::MAIN_WINDOW_ID) const;
  945. int screen_get_height(DisplayServer::WindowID p_screen = DisplayServer::MAIN_WINDOW_ID) const;
  946. int screen_get_pre_rotation_degrees(DisplayServer::WindowID p_screen = DisplayServer::MAIN_WINDOW_ID) const;
  947. FramebufferFormatID screen_get_framebuffer_format(DisplayServer::WindowID p_screen = DisplayServer::MAIN_WINDOW_ID) const;
  948. Error screen_free(DisplayServer::WindowID p_screen = DisplayServer::MAIN_WINDOW_ID);
  949. /*************************/
  950. /**** DRAW LISTS (II) ****/
  951. /*************************/
  952. private:
  953. // Draw list contains both the command buffer
  954. // used for drawing as well as a LOT of
  955. // information used for validation. This
  956. // validation is cheap so most of it can
  957. // also run in release builds.
  958. struct DrawList {
  959. Rect2i viewport;
  960. bool viewport_set = false;
  961. struct SetState {
  962. uint32_t pipeline_expected_format = 0;
  963. uint32_t uniform_set_format = 0;
  964. RDD::UniformSetID uniform_set_driver_id;
  965. RID uniform_set;
  966. bool bound = false;
  967. };
  968. struct State {
  969. SetState sets[MAX_UNIFORM_SETS];
  970. uint32_t set_count = 0;
  971. RID pipeline;
  972. RID pipeline_shader;
  973. RDD::ShaderID pipeline_shader_driver_id;
  974. uint32_t pipeline_shader_layout_hash = 0;
  975. uint32_t pipeline_push_constant_size = 0;
  976. RID vertex_array;
  977. RID index_array;
  978. uint32_t draw_count = 0;
  979. } state;
  980. #ifdef DEBUG_ENABLED
  981. struct Validation {
  982. bool active = true; // Means command buffer was not closed, so you can keep adding things.
  983. // Actual render pass values.
  984. uint32_t dynamic_state = 0;
  985. VertexFormatID vertex_format = INVALID_ID;
  986. uint32_t vertex_array_size = 0;
  987. uint32_t vertex_max_instances_allowed = 0xFFFFFFFF;
  988. bool index_buffer_uses_restart_indices = false;
  989. uint32_t index_array_count = 0;
  990. uint32_t index_array_max_index = 0;
  991. Vector<uint32_t> set_formats;
  992. Vector<bool> set_bound;
  993. Vector<RID> set_rids;
  994. // Last pipeline set values.
  995. bool pipeline_active = false;
  996. uint32_t pipeline_dynamic_state = 0;
  997. VertexFormatID pipeline_vertex_format = INVALID_ID;
  998. RID pipeline_shader;
  999. bool pipeline_uses_restart_indices = false;
  1000. uint32_t pipeline_primitive_divisor = 0;
  1001. uint32_t pipeline_primitive_minimum = 0;
  1002. uint32_t pipeline_push_constant_size = 0;
  1003. bool pipeline_push_constant_supplied = false;
  1004. } validation;
  1005. #else
  1006. struct Validation {
  1007. uint32_t vertex_array_size = 0;
  1008. uint32_t index_array_count = 0;
  1009. } validation;
  1010. #endif
  1011. };
  1012. DrawList *draw_list = nullptr;
  1013. uint32_t draw_list_subpass_count = 0;
  1014. #ifdef DEBUG_ENABLED
  1015. FramebufferFormatID draw_list_framebuffer_format = INVALID_ID;
  1016. #endif
  1017. uint32_t draw_list_current_subpass = 0;
  1018. Vector<RID> draw_list_bound_textures;
  1019. _FORCE_INLINE_ DrawList *_get_draw_list_ptr(DrawListID p_id);
  1020. Error _draw_list_allocate(const Rect2i &p_viewport, uint32_t p_subpass);
  1021. void _draw_list_free(Rect2i *r_last_viewport = nullptr);
  1022. public:
  1023. enum DrawFlags {
  1024. DRAW_DEFAULT_ALL = 0,
  1025. DRAW_CLEAR_COLOR_0 = (1 << 0),
  1026. DRAW_CLEAR_COLOR_1 = (1 << 1),
  1027. DRAW_CLEAR_COLOR_2 = (1 << 2),
  1028. DRAW_CLEAR_COLOR_3 = (1 << 3),
  1029. DRAW_CLEAR_COLOR_4 = (1 << 4),
  1030. DRAW_CLEAR_COLOR_5 = (1 << 5),
  1031. DRAW_CLEAR_COLOR_6 = (1 << 6),
  1032. DRAW_CLEAR_COLOR_7 = (1 << 7),
  1033. DRAW_CLEAR_COLOR_MASK = 0xFF,
  1034. DRAW_CLEAR_COLOR_ALL = DRAW_CLEAR_COLOR_MASK,
  1035. DRAW_IGNORE_COLOR_0 = (1 << 8),
  1036. DRAW_IGNORE_COLOR_1 = (1 << 9),
  1037. DRAW_IGNORE_COLOR_2 = (1 << 10),
  1038. DRAW_IGNORE_COLOR_3 = (1 << 11),
  1039. DRAW_IGNORE_COLOR_4 = (1 << 12),
  1040. DRAW_IGNORE_COLOR_5 = (1 << 13),
  1041. DRAW_IGNORE_COLOR_6 = (1 << 14),
  1042. DRAW_IGNORE_COLOR_7 = (1 << 15),
  1043. DRAW_IGNORE_COLOR_MASK = 0xFF00,
  1044. DRAW_IGNORE_COLOR_ALL = DRAW_IGNORE_COLOR_MASK,
  1045. DRAW_CLEAR_DEPTH = (1 << 16),
  1046. DRAW_IGNORE_DEPTH = (1 << 17),
  1047. DRAW_CLEAR_STENCIL = (1 << 18),
  1048. DRAW_IGNORE_STENCIL = (1 << 19),
  1049. DRAW_CLEAR_ALL = DRAW_CLEAR_COLOR_ALL | DRAW_CLEAR_DEPTH | DRAW_CLEAR_STENCIL,
  1050. DRAW_IGNORE_ALL = DRAW_IGNORE_COLOR_ALL | DRAW_IGNORE_DEPTH | DRAW_IGNORE_STENCIL
  1051. };
  1052. DrawListID draw_list_begin_for_screen(DisplayServer::WindowID p_screen = 0, const Color &p_clear_color = Color());
  1053. DrawListID draw_list_begin(RID p_framebuffer, BitField<DrawFlags> p_draw_flags = DRAW_DEFAULT_ALL, const Vector<Color> &p_clear_color_values = Vector<Color>(), float p_clear_depth_value = 1.0f, uint32_t p_clear_stencil_value = 0, const Rect2 &p_region = Rect2(), uint32_t p_breadcrumb = 0);
  1054. void draw_list_set_blend_constants(DrawListID p_list, const Color &p_color);
  1055. void draw_list_bind_render_pipeline(DrawListID p_list, RID p_render_pipeline);
  1056. void draw_list_bind_uniform_set(DrawListID p_list, RID p_uniform_set, uint32_t p_index);
  1057. void draw_list_bind_vertex_array(DrawListID p_list, RID p_vertex_array);
  1058. void draw_list_bind_index_array(DrawListID p_list, RID p_index_array);
  1059. void draw_list_set_line_width(DrawListID p_list, float p_width);
  1060. void draw_list_set_push_constant(DrawListID p_list, const void *p_data, uint32_t p_data_size);
  1061. void draw_list_draw(DrawListID p_list, bool p_use_indices, uint32_t p_instances = 1, uint32_t p_procedural_vertices = 0);
  1062. void draw_list_draw_indirect(DrawListID p_list, bool p_use_indices, RID p_buffer, uint32_t p_offset = 0, uint32_t p_draw_count = 1, uint32_t p_stride = 0);
  1063. void draw_list_set_viewport(DrawListID p_list, const Rect2 &p_rect);
  1064. void draw_list_enable_scissor(DrawListID p_list, const Rect2 &p_rect);
  1065. void draw_list_disable_scissor(DrawListID p_list);
  1066. uint32_t draw_list_get_current_pass();
  1067. DrawListID draw_list_switch_to_next_pass();
  1068. void draw_list_end();
  1069. private:
  1070. /***********************/
  1071. /**** COMPUTE LISTS ****/
  1072. /***********************/
  1073. struct ComputeList {
  1074. struct SetState {
  1075. uint32_t pipeline_expected_format = 0;
  1076. uint32_t uniform_set_format = 0;
  1077. RDD::UniformSetID uniform_set_driver_id;
  1078. RID uniform_set;
  1079. bool bound = false;
  1080. };
  1081. struct State {
  1082. SetState sets[MAX_UNIFORM_SETS];
  1083. uint32_t set_count = 0;
  1084. RID pipeline;
  1085. RID pipeline_shader;
  1086. RDD::ShaderID pipeline_shader_driver_id;
  1087. uint32_t pipeline_shader_layout_hash = 0;
  1088. uint32_t local_group_size[3] = { 0, 0, 0 };
  1089. uint8_t push_constant_data[MAX_PUSH_CONSTANT_SIZE] = {};
  1090. uint32_t push_constant_size = 0;
  1091. uint32_t dispatch_count = 0;
  1092. } state;
  1093. #ifdef DEBUG_ENABLED
  1094. struct Validation {
  1095. bool active = true; // Means command buffer was not closed, so you can keep adding things.
  1096. Vector<uint32_t> set_formats;
  1097. Vector<bool> set_bound;
  1098. Vector<RID> set_rids;
  1099. // Last pipeline set values.
  1100. bool pipeline_active = false;
  1101. RID pipeline_shader;
  1102. uint32_t invalid_set_from = 0;
  1103. uint32_t pipeline_push_constant_size = 0;
  1104. bool pipeline_push_constant_supplied = false;
  1105. } validation;
  1106. #endif
  1107. };
  1108. ComputeList *compute_list = nullptr;
  1109. ComputeList::State compute_list_barrier_state;
  1110. public:
  1111. ComputeListID compute_list_begin();
  1112. void compute_list_bind_compute_pipeline(ComputeListID p_list, RID p_compute_pipeline);
  1113. void compute_list_bind_uniform_set(ComputeListID p_list, RID p_uniform_set, uint32_t p_index);
  1114. void compute_list_set_push_constant(ComputeListID p_list, const void *p_data, uint32_t p_data_size);
  1115. void compute_list_dispatch(ComputeListID p_list, uint32_t p_x_groups, uint32_t p_y_groups, uint32_t p_z_groups);
  1116. void compute_list_dispatch_threads(ComputeListID p_list, uint32_t p_x_threads, uint32_t p_y_threads, uint32_t p_z_threads);
  1117. void compute_list_dispatch_indirect(ComputeListID p_list, RID p_buffer, uint32_t p_offset);
  1118. void compute_list_add_barrier(ComputeListID p_list);
  1119. void compute_list_end();
  1120. private:
  1121. /*************************/
  1122. /**** TRANSFER WORKER ****/
  1123. /*************************/
  1124. struct TransferWorker {
  1125. uint32_t index = 0;
  1126. RDD::BufferID staging_buffer;
  1127. uint32_t max_transfer_size = 0;
  1128. uint32_t staging_buffer_size_in_use = 0;
  1129. uint32_t staging_buffer_size_allocated = 0;
  1130. RDD::CommandBufferID command_buffer;
  1131. RDD::CommandPoolID command_pool;
  1132. RDD::FenceID command_fence;
  1133. LocalVector<RDD::TextureBarrier> texture_barriers;
  1134. bool recording = false;
  1135. bool submitted = false;
  1136. BinaryMutex thread_mutex;
  1137. uint64_t operations_processed = 0;
  1138. uint64_t operations_submitted = 0;
  1139. uint64_t operations_counter = 0;
  1140. BinaryMutex operations_mutex;
  1141. };
  1142. LocalVector<TransferWorker *> transfer_worker_pool;
  1143. uint32_t transfer_worker_pool_max_size = 1;
  1144. LocalVector<uint64_t> transfer_worker_operation_used_by_draw;
  1145. LocalVector<uint32_t> transfer_worker_pool_available_list;
  1146. LocalVector<RDD::TextureBarrier> transfer_worker_pool_texture_barriers;
  1147. BinaryMutex transfer_worker_pool_mutex;
  1148. BinaryMutex transfer_worker_pool_texture_barriers_mutex;
  1149. ConditionVariable transfer_worker_pool_condition;
  1150. TransferWorker *_acquire_transfer_worker(uint32_t p_transfer_size, uint32_t p_required_align, uint32_t &r_staging_offset);
  1151. void _release_transfer_worker(TransferWorker *p_transfer_worker);
  1152. void _end_transfer_worker(TransferWorker *p_transfer_worker);
  1153. void _submit_transfer_worker(TransferWorker *p_transfer_worker, VectorView<RDD::SemaphoreID> p_signal_semaphores = VectorView<RDD::SemaphoreID>());
  1154. void _wait_for_transfer_worker(TransferWorker *p_transfer_worker);
  1155. void _flush_barriers_for_transfer_worker(TransferWorker *p_transfer_worker);
  1156. void _check_transfer_worker_operation(uint32_t p_transfer_worker_index, uint64_t p_transfer_worker_operation);
  1157. void _check_transfer_worker_buffer(Buffer *p_buffer);
  1158. void _check_transfer_worker_texture(Texture *p_texture);
  1159. void _check_transfer_worker_vertex_array(VertexArray *p_vertex_array);
  1160. void _check_transfer_worker_index_array(IndexArray *p_index_array);
  1161. void _submit_transfer_workers(RDD::CommandBufferID p_draw_command_buffer = RDD::CommandBufferID());
  1162. void _submit_transfer_barriers(RDD::CommandBufferID p_draw_command_buffer);
  1163. void _wait_for_transfer_workers();
  1164. void _free_transfer_workers();
  1165. /***********************/
  1166. /**** COMMAND GRAPH ****/
  1167. /***********************/
  1168. bool _texture_make_mutable(Texture *p_texture, RID p_texture_id);
  1169. bool _buffer_make_mutable(Buffer *p_buffer, RID p_buffer_id);
  1170. bool _vertex_array_make_mutable(VertexArray *p_vertex_array, RID p_resource_id, RDG::ResourceTracker *p_resource_tracker);
  1171. bool _index_array_make_mutable(IndexArray *p_index_array, RDG::ResourceTracker *p_resource_tracker);
  1172. bool _uniform_set_make_mutable(UniformSet *p_uniform_set, RID p_resource_id, RDG::ResourceTracker *p_resource_tracker);
  1173. bool _dependency_make_mutable(RID p_id, RID p_resource_id, RDG::ResourceTracker *p_resource_tracker);
  1174. bool _dependencies_make_mutable_recursive(RID p_id, RDG::ResourceTracker *p_resource_tracker);
  1175. bool _dependencies_make_mutable(RID p_id, RDG::ResourceTracker *p_resource_tracker);
  1176. RenderingDeviceGraph draw_graph;
  1177. /**************************/
  1178. /**** QUEUE MANAGEMENT ****/
  1179. /**************************/
  1180. RDD::CommandQueueFamilyID main_queue_family;
  1181. RDD::CommandQueueFamilyID transfer_queue_family;
  1182. RDD::CommandQueueFamilyID present_queue_family;
  1183. RDD::CommandQueueID main_queue;
  1184. RDD::CommandQueueID transfer_queue;
  1185. RDD::CommandQueueID present_queue;
  1186. /**************************/
  1187. /**** FRAME MANAGEMENT ****/
  1188. /**************************/
  1189. // This is the frame structure. There are normally
  1190. // 3 of these (used for triple buffering), or 2
  1191. // (double buffering). They are cycled constantly.
  1192. //
  1193. // It contains two command buffers, one that is
  1194. // used internally for setting up (creating stuff)
  1195. // and another used mostly for drawing.
  1196. //
  1197. // They also contains a list of things that need
  1198. // to be disposed of when deleted, which can't
  1199. // happen immediately due to the asynchronous
  1200. // nature of the GPU. They will get deleted
  1201. // when the frame is cycled.
  1202. struct Frame {
  1203. // List in usage order, from last to free to first to free.
  1204. List<Buffer> buffers_to_dispose_of;
  1205. List<Texture> textures_to_dispose_of;
  1206. List<Framebuffer> framebuffers_to_dispose_of;
  1207. List<RDD::SamplerID> samplers_to_dispose_of;
  1208. List<Shader> shaders_to_dispose_of;
  1209. List<UniformSet> uniform_sets_to_dispose_of;
  1210. List<RenderPipeline> render_pipelines_to_dispose_of;
  1211. List<ComputePipeline> compute_pipelines_to_dispose_of;
  1212. // Pending asynchronous data transfer for buffers.
  1213. LocalVector<RDD::BufferID> download_buffer_staging_buffers;
  1214. LocalVector<RDD::BufferCopyRegion> download_buffer_copy_regions;
  1215. LocalVector<BufferGetDataRequest> download_buffer_get_data_requests;
  1216. // Pending asynchronous data transfer for textures.
  1217. LocalVector<RDD::BufferID> download_texture_staging_buffers;
  1218. LocalVector<RDD::BufferTextureCopyRegion> download_buffer_texture_copy_regions;
  1219. LocalVector<uint32_t> download_texture_mipmap_offsets;
  1220. LocalVector<TextureGetDataRequest> download_texture_get_data_requests;
  1221. // The command pool used by the command buffer.
  1222. RDD::CommandPoolID command_pool;
  1223. // The command buffer used by the main thread when recording the frame.
  1224. RDD::CommandBufferID command_buffer;
  1225. // Signaled by the command buffer submission. Present must wait on this semaphore.
  1226. RDD::SemaphoreID semaphore;
  1227. // Signaled by the command buffer submission. Must wait on this fence before beginning command recording for the frame.
  1228. RDD::FenceID fence;
  1229. bool fence_signaled = false;
  1230. // Semaphores the frame must wait on before executing the command buffer.
  1231. LocalVector<RDD::SemaphoreID> semaphores_to_wait_on;
  1232. // Swap chains prepared for drawing during the frame that must be presented.
  1233. LocalVector<RDD::SwapChainID> swap_chains_to_present;
  1234. // Semaphores the transfer workers can use to wait before rendering the frame.
  1235. // This must have the same size of the transfer worker pool.
  1236. TightLocalVector<RDD::SemaphoreID> transfer_worker_semaphores;
  1237. // Extra command buffer pool used for driver workarounds or to reduce GPU bubbles by
  1238. // splitting the final render pass to the swapchain into its own cmd buffer.
  1239. RDG::CommandBufferPool command_buffer_pool;
  1240. struct Timestamp {
  1241. String description;
  1242. uint64_t value = 0;
  1243. };
  1244. RDD::QueryPoolID timestamp_pool;
  1245. TightLocalVector<String> timestamp_names;
  1246. TightLocalVector<uint64_t> timestamp_cpu_values;
  1247. uint32_t timestamp_count = 0;
  1248. TightLocalVector<String> timestamp_result_names;
  1249. TightLocalVector<uint64_t> timestamp_cpu_result_values;
  1250. TightLocalVector<uint64_t> timestamp_result_values;
  1251. uint32_t timestamp_result_count = 0;
  1252. uint64_t index = 0;
  1253. };
  1254. uint32_t max_timestamp_query_elements = 0;
  1255. int frame = 0;
  1256. TightLocalVector<Frame> frames;
  1257. uint64_t frames_drawn = 0;
  1258. void _free_pending_resources(int p_frame);
  1259. uint64_t texture_memory = 0;
  1260. uint64_t buffer_memory = 0;
  1261. protected:
  1262. void execute_chained_cmds(bool p_present_swap_chain,
  1263. RenderingDeviceDriver::FenceID p_draw_fence,
  1264. RenderingDeviceDriver::SemaphoreID p_dst_draw_semaphore_to_signal);
  1265. public:
  1266. void _free_internal(RID p_id);
  1267. void _begin_frame(bool p_presented = false);
  1268. void _end_frame();
  1269. void _execute_frame(bool p_present);
  1270. void _stall_for_frame(uint32_t p_frame);
  1271. void _stall_for_previous_frames();
  1272. void _flush_and_stall_for_all_frames();
  1273. template <typename T>
  1274. void _free_rids(T &p_owner, const char *p_type);
  1275. #ifdef DEV_ENABLED
  1276. HashMap<RID, String> resource_names;
  1277. #endif
  1278. public:
  1279. Error initialize(RenderingContextDriver *p_context, DisplayServer::WindowID p_main_window = DisplayServer::INVALID_WINDOW_ID);
  1280. void finalize();
  1281. void _set_max_fps(int p_max_fps);
  1282. void free(RID p_id);
  1283. /****************/
  1284. /**** Timing ****/
  1285. /****************/
  1286. void capture_timestamp(const String &p_name);
  1287. uint32_t get_captured_timestamps_count() const;
  1288. uint64_t get_captured_timestamps_frame() const;
  1289. uint64_t get_captured_timestamp_gpu_time(uint32_t p_index) const;
  1290. uint64_t get_captured_timestamp_cpu_time(uint32_t p_index) const;
  1291. String get_captured_timestamp_name(uint32_t p_index) const;
  1292. /****************/
  1293. /**** LIMITS ****/
  1294. /****************/
  1295. uint64_t limit_get(Limit p_limit) const;
  1296. void swap_buffers();
  1297. uint32_t get_frame_delay() const;
  1298. void submit();
  1299. void sync();
  1300. enum MemoryType {
  1301. MEMORY_TEXTURES,
  1302. MEMORY_BUFFERS,
  1303. MEMORY_TOTAL
  1304. };
  1305. uint64_t get_memory_usage(MemoryType p_type) const;
  1306. RenderingDevice *create_local_device();
  1307. void set_resource_name(RID p_id, const String &p_name);
  1308. void draw_command_begin_label(String p_label_name, const Color &p_color = Color(1, 1, 1, 1));
  1309. void draw_command_end_label();
  1310. String get_device_vendor_name() const;
  1311. String get_device_name() const;
  1312. DeviceType get_device_type() const;
  1313. String get_device_api_name() const;
  1314. String get_device_api_version() const;
  1315. String get_device_pipeline_cache_uuid() const;
  1316. bool is_composite_alpha_supported() const;
  1317. uint64_t get_driver_resource(DriverResource p_resource, RID p_rid = RID(), uint64_t p_index = 0);
  1318. String get_driver_and_device_memory_report() const;
  1319. String get_tracked_object_name(uint32_t p_type_index) const;
  1320. uint64_t get_tracked_object_type_count() const;
  1321. uint64_t get_driver_total_memory() const;
  1322. uint64_t get_driver_allocation_count() const;
  1323. uint64_t get_driver_memory_by_object_type(uint32_t p_type) const;
  1324. uint64_t get_driver_allocs_by_object_type(uint32_t p_type) const;
  1325. uint64_t get_device_total_memory() const;
  1326. uint64_t get_device_allocation_count() const;
  1327. uint64_t get_device_memory_by_object_type(uint32_t p_type) const;
  1328. uint64_t get_device_allocs_by_object_type(uint32_t p_type) const;
  1329. static RenderingDevice *get_singleton();
  1330. void make_current();
  1331. RenderingDevice();
  1332. ~RenderingDevice();
  1333. private:
  1334. /*****************/
  1335. /**** BINDERS ****/
  1336. /*****************/
  1337. RID _texture_create(const Ref<RDTextureFormat> &p_format, const Ref<RDTextureView> &p_view, const TypedArray<PackedByteArray> &p_data = Array());
  1338. RID _texture_create_shared(const Ref<RDTextureView> &p_view, RID p_with_texture);
  1339. RID _texture_create_shared_from_slice(const Ref<RDTextureView> &p_view, RID p_with_texture, uint32_t p_layer, uint32_t p_mipmap, uint32_t p_mipmaps = 1, TextureSliceType p_slice_type = TEXTURE_SLICE_2D);
  1340. Ref<RDTextureFormat> _texture_get_format(RID p_rd_texture);
  1341. FramebufferFormatID _framebuffer_format_create(const TypedArray<RDAttachmentFormat> &p_attachments, uint32_t p_view_count);
  1342. FramebufferFormatID _framebuffer_format_create_multipass(const TypedArray<RDAttachmentFormat> &p_attachments, const TypedArray<RDFramebufferPass> &p_passes, uint32_t p_view_count);
  1343. RID _framebuffer_create(const TypedArray<RID> &p_textures, FramebufferFormatID p_format_check = INVALID_ID, uint32_t p_view_count = 1);
  1344. RID _framebuffer_create_multipass(const TypedArray<RID> &p_textures, const TypedArray<RDFramebufferPass> &p_passes, FramebufferFormatID p_format_check = INVALID_ID, uint32_t p_view_count = 1);
  1345. RID _sampler_create(const Ref<RDSamplerState> &p_state);
  1346. VertexFormatID _vertex_format_create(const TypedArray<RDVertexAttribute> &p_vertex_formats);
  1347. RID _vertex_array_create(uint32_t p_vertex_count, VertexFormatID p_vertex_format, const TypedArray<RID> &p_src_buffers, const Vector<int64_t> &p_offsets = Vector<int64_t>());
  1348. Ref<RDShaderSPIRV> _shader_compile_spirv_from_source(const Ref<RDShaderSource> &p_source, bool p_allow_cache = true);
  1349. Vector<uint8_t> _shader_compile_binary_from_spirv(const Ref<RDShaderSPIRV> &p_bytecode, const String &p_shader_name = "");
  1350. RID _shader_create_from_spirv(const Ref<RDShaderSPIRV> &p_spirv, const String &p_shader_name = "");
  1351. RID _uniform_set_create(const TypedArray<RDUniform> &p_uniforms, RID p_shader, uint32_t p_shader_set);
  1352. Error _buffer_update_bind(RID p_buffer, uint32_t p_offset, uint32_t p_size, const Vector<uint8_t> &p_data);
  1353. RID _render_pipeline_create(RID p_shader, FramebufferFormatID p_framebuffer_format, VertexFormatID p_vertex_format, RenderPrimitive p_render_primitive, const Ref<RDPipelineRasterizationState> &p_rasterization_state, const Ref<RDPipelineMultisampleState> &p_multisample_state, const Ref<RDPipelineDepthStencilState> &p_depth_stencil_state, const Ref<RDPipelineColorBlendState> &p_blend_state, BitField<PipelineDynamicStateFlags> p_dynamic_state_flags, uint32_t p_for_render_pass, const TypedArray<RDPipelineSpecializationConstant> &p_specialization_constants);
  1354. RID _compute_pipeline_create(RID p_shader, const TypedArray<RDPipelineSpecializationConstant> &p_specialization_constants);
  1355. void _draw_list_set_push_constant(DrawListID p_list, const Vector<uint8_t> &p_data, uint32_t p_data_size);
  1356. void _compute_list_set_push_constant(ComputeListID p_list, const Vector<uint8_t> &p_data, uint32_t p_data_size);
  1357. };
  1358. VARIANT_ENUM_CAST(RenderingDevice::DeviceType)
  1359. VARIANT_ENUM_CAST(RenderingDevice::DriverResource)
  1360. VARIANT_ENUM_CAST(RenderingDevice::ShaderStage)
  1361. VARIANT_ENUM_CAST(RenderingDevice::ShaderLanguage)
  1362. VARIANT_ENUM_CAST(RenderingDevice::CompareOperator)
  1363. VARIANT_ENUM_CAST(RenderingDevice::DataFormat)
  1364. VARIANT_ENUM_CAST(RenderingDevice::TextureType)
  1365. VARIANT_ENUM_CAST(RenderingDevice::TextureSamples)
  1366. VARIANT_BITFIELD_CAST(RenderingDevice::TextureUsageBits)
  1367. VARIANT_ENUM_CAST(RenderingDevice::TextureSwizzle)
  1368. VARIANT_ENUM_CAST(RenderingDevice::TextureSliceType)
  1369. VARIANT_ENUM_CAST(RenderingDevice::SamplerFilter)
  1370. VARIANT_ENUM_CAST(RenderingDevice::SamplerRepeatMode)
  1371. VARIANT_ENUM_CAST(RenderingDevice::SamplerBorderColor)
  1372. VARIANT_ENUM_CAST(RenderingDevice::VertexFrequency)
  1373. VARIANT_ENUM_CAST(RenderingDevice::IndexBufferFormat)
  1374. VARIANT_BITFIELD_CAST(RenderingDevice::StorageBufferUsage)
  1375. VARIANT_ENUM_CAST(RenderingDevice::UniformType)
  1376. VARIANT_ENUM_CAST(RenderingDevice::RenderPrimitive)
  1377. VARIANT_ENUM_CAST(RenderingDevice::PolygonCullMode)
  1378. VARIANT_ENUM_CAST(RenderingDevice::PolygonFrontFace)
  1379. VARIANT_ENUM_CAST(RenderingDevice::StencilOperation)
  1380. VARIANT_ENUM_CAST(RenderingDevice::LogicOperation)
  1381. VARIANT_ENUM_CAST(RenderingDevice::BlendFactor)
  1382. VARIANT_ENUM_CAST(RenderingDevice::BlendOperation)
  1383. VARIANT_BITFIELD_CAST(RenderingDevice::PipelineDynamicStateFlags)
  1384. VARIANT_ENUM_CAST(RenderingDevice::PipelineSpecializationConstantType)
  1385. VARIANT_ENUM_CAST(RenderingDevice::Limit)
  1386. VARIANT_ENUM_CAST(RenderingDevice::MemoryType)
  1387. VARIANT_ENUM_CAST(RenderingDevice::Features)
  1388. VARIANT_ENUM_CAST(RenderingDevice::BreadcrumbMarker)
  1389. VARIANT_BITFIELD_CAST(RenderingDevice::DrawFlags);
  1390. #ifndef DISABLE_DEPRECATED
  1391. VARIANT_BITFIELD_CAST(RenderingDevice::BarrierMask);
  1392. VARIANT_ENUM_CAST(RenderingDevice::InitialAction)
  1393. VARIANT_ENUM_CAST(RenderingDevice::FinalAction)
  1394. #endif
  1395. typedef RenderingDevice RD;
  1396. #endif // RENDERING_DEVICE_H