rendering_device.h 69 KB

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