rendering_device_driver_d3d12.h 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928
  1. /**************************************************************************/
  2. /* rendering_device_driver_d3d12.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. #pragma once
  31. #include "core/templates/hash_map.h"
  32. #include "core/templates/paged_allocator.h"
  33. #include "core/templates/self_list.h"
  34. #include "rendering_shader_container_d3d12.h"
  35. #include "servers/rendering/rendering_device_driver.h"
  36. #ifndef _MSC_VER
  37. // Match current version used by MinGW, MSVC and Direct3D 12 headers use 500.
  38. #define __REQUIRED_RPCNDR_H_VERSION__ 475
  39. #endif
  40. #include <d3dx12.h>
  41. #include <dxgi1_6.h>
  42. #define D3D12MA_D3D12_HEADERS_ALREADY_INCLUDED
  43. #include <D3D12MemAlloc.h>
  44. #include <wrl/client.h>
  45. #if defined(_MSC_VER) && defined(MemoryBarrier)
  46. // Annoying define from winnt.h. Reintroduced by some of the headers above.
  47. #undef MemoryBarrier
  48. #endif
  49. using Microsoft::WRL::ComPtr;
  50. #ifdef DEV_ENABLED
  51. #define CUSTOM_INFO_QUEUE_ENABLED 0
  52. #endif
  53. class RenderingContextDriverD3D12;
  54. // Design principles:
  55. // - D3D12 structs are zero-initialized and fields not requiring a non-zero value are omitted (except in cases where expresivity reasons apply).
  56. class RenderingDeviceDriverD3D12 : public RenderingDeviceDriver {
  57. /*****************/
  58. /**** GENERIC ****/
  59. /*****************/
  60. struct D3D12Format {
  61. DXGI_FORMAT family = DXGI_FORMAT_UNKNOWN;
  62. DXGI_FORMAT general_format = DXGI_FORMAT_UNKNOWN;
  63. UINT swizzle = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
  64. DXGI_FORMAT dsv_format = DXGI_FORMAT_UNKNOWN;
  65. };
  66. static const D3D12Format RD_TO_D3D12_FORMAT[RDD::DATA_FORMAT_MAX];
  67. struct DeviceLimits {
  68. uint64_t max_srvs_per_shader_stage = 0;
  69. uint64_t max_cbvs_per_shader_stage = 0;
  70. uint64_t max_samplers_across_all_stages = 0;
  71. uint64_t max_uavs_across_all_stages = 0;
  72. uint64_t timestamp_frequency = 0;
  73. };
  74. struct SubgroupCapabilities {
  75. uint32_t size = 0;
  76. bool wave_ops_supported = false;
  77. uint32_t supported_stages_flags_rd() const;
  78. uint32_t supported_operations_flags_rd() const;
  79. };
  80. struct ShaderCapabilities {
  81. D3D_SHADER_MODEL shader_model = (D3D_SHADER_MODEL)0;
  82. bool native_16bit_ops = false;
  83. };
  84. struct StorageBufferCapabilities {
  85. bool storage_buffer_16_bit_access_is_supported = false;
  86. };
  87. struct FormatCapabilities {
  88. bool relaxed_casting_supported = false;
  89. };
  90. struct BarrierCapabilities {
  91. bool enhanced_barriers_supported = false;
  92. };
  93. struct MiscFeaturesSupport {
  94. bool depth_bounds_supported = false;
  95. };
  96. RenderingContextDriverD3D12 *context_driver = nullptr;
  97. RenderingContextDriver::Device context_device;
  98. ComPtr<IDXGIAdapter> adapter;
  99. DXGI_ADAPTER_DESC adapter_desc;
  100. ComPtr<ID3D12Device> device;
  101. DeviceLimits device_limits;
  102. RDD::Capabilities device_capabilities;
  103. uint32_t feature_level = 0; // Major * 10 + minor.
  104. SubgroupCapabilities subgroup_capabilities;
  105. RDD::MultiviewCapabilities multiview_capabilities;
  106. FragmentShadingRateCapabilities fsr_capabilities;
  107. FragmentDensityMapCapabilities fdm_capabilities;
  108. ShaderCapabilities shader_capabilities;
  109. StorageBufferCapabilities storage_buffer_capabilities;
  110. FormatCapabilities format_capabilities;
  111. BarrierCapabilities barrier_capabilities;
  112. MiscFeaturesSupport misc_features_support;
  113. RenderingShaderContainerFormatD3D12 shader_container_format;
  114. String pipeline_cache_id;
  115. class DescriptorsHeap {
  116. D3D12_DESCRIPTOR_HEAP_DESC desc = {};
  117. ComPtr<ID3D12DescriptorHeap> heap;
  118. uint32_t handle_size = 0;
  119. public:
  120. class Walker { // Texas Ranger.
  121. friend class DescriptorsHeap;
  122. uint32_t handle_size = 0;
  123. uint32_t handle_count = 0;
  124. D3D12_CPU_DESCRIPTOR_HANDLE first_cpu_handle = {};
  125. D3D12_GPU_DESCRIPTOR_HANDLE first_gpu_handle = {};
  126. uint32_t handle_index = 0;
  127. public:
  128. D3D12_CPU_DESCRIPTOR_HANDLE get_curr_cpu_handle();
  129. D3D12_GPU_DESCRIPTOR_HANDLE get_curr_gpu_handle();
  130. _FORCE_INLINE_ void rewind() { handle_index = 0; }
  131. void advance(uint32_t p_count = 1);
  132. uint32_t get_current_handle_index() const { return handle_index; }
  133. uint32_t get_free_handles() { return handle_count - handle_index; }
  134. bool is_at_eof() { return handle_index == handle_count; }
  135. };
  136. Error allocate(ID3D12Device *m_device, D3D12_DESCRIPTOR_HEAP_TYPE m_type, uint32_t m_descriptor_count, bool p_for_gpu);
  137. uint32_t get_descriptor_count() const { return desc.NumDescriptors; }
  138. ID3D12DescriptorHeap *get_heap() const { return heap.Get(); }
  139. Walker make_walker() const;
  140. };
  141. struct {
  142. ComPtr<ID3D12CommandSignature> draw;
  143. ComPtr<ID3D12CommandSignature> draw_indexed;
  144. ComPtr<ID3D12CommandSignature> dispatch;
  145. } indirect_cmd_signatures;
  146. static void STDMETHODCALLTYPE _debug_message_func(D3D12_MESSAGE_CATEGORY p_category, D3D12_MESSAGE_SEVERITY p_severity, D3D12_MESSAGE_ID p_id, LPCSTR p_description, void *p_context);
  147. void _set_object_name(ID3D12Object *p_object, String p_object_name);
  148. Error _initialize_device();
  149. Error _check_capabilities();
  150. Error _get_device_limits();
  151. Error _initialize_allocator();
  152. Error _initialize_frames(uint32_t p_frame_count);
  153. Error _initialize_command_signatures();
  154. public:
  155. Error initialize(uint32_t p_device_index, uint32_t p_frame_count) override final;
  156. private:
  157. /****************/
  158. /**** MEMORY ****/
  159. /****************/
  160. ComPtr<D3D12MA::Allocator> allocator;
  161. /******************/
  162. /**** RESOURCE ****/
  163. /******************/
  164. struct ResourceInfo {
  165. struct States {
  166. // As many subresources as mipmaps * layers; planes (for depth-stencil) are tracked together.
  167. TightLocalVector<D3D12_RESOURCE_STATES> subresource_states; // Used only if not a view.
  168. uint32_t last_batch_with_uav_barrier = 0;
  169. };
  170. ID3D12Resource *resource = nullptr; // Non-null even if not owned.
  171. struct {
  172. ComPtr<ID3D12Resource> resource;
  173. ComPtr<D3D12MA::Allocation> allocation;
  174. States states;
  175. } owner_info; // All empty if the resource is not owned.
  176. States *states_ptr = nullptr; // Own or from another if it doesn't own the D3D12 resource.
  177. };
  178. struct BarrierRequest {
  179. static const uint32_t MAX_GROUPS = 4;
  180. // Maybe this is too much data to have it locally. Benchmarking may reveal that
  181. // cache would be used better by having a maximum of local subresource masks and beyond
  182. // that have an allocated vector with the rest.
  183. static const uint32_t MAX_SUBRESOURCES = 4096;
  184. ID3D12Resource *dx_resource = nullptr;
  185. uint8_t subres_mask_qwords = 0;
  186. uint8_t planes = 0;
  187. struct Group {
  188. D3D12_RESOURCE_STATES states = {};
  189. static_assert(MAX_SUBRESOURCES % 64 == 0);
  190. uint64_t subres_mask[MAX_SUBRESOURCES / 64] = {};
  191. } groups[MAX_GROUPS];
  192. uint8_t groups_count = 0;
  193. static const D3D12_RESOURCE_STATES DELETED_GROUP = D3D12_RESOURCE_STATES(0xFFFFFFFFU);
  194. };
  195. struct CommandBufferInfo;
  196. void _resource_transition_batch(CommandBufferInfo *p_command_buffer, ResourceInfo *p_resource, uint32_t p_subresource, uint32_t p_num_planes, D3D12_RESOURCE_STATES p_new_state);
  197. void _resource_transitions_flush(CommandBufferInfo *p_command_buffer);
  198. /*****************/
  199. /**** BUFFERS ****/
  200. /*****************/
  201. struct BufferInfo : public ResourceInfo {
  202. DataFormat texel_format = DATA_FORMAT_MAX;
  203. uint64_t size = 0;
  204. struct {
  205. bool usable_as_uav : 1;
  206. } flags = {};
  207. };
  208. public:
  209. virtual BufferID buffer_create(uint64_t p_size, BitField<BufferUsageBits> p_usage, MemoryAllocationType p_allocation_type) override final;
  210. virtual bool buffer_set_texel_format(BufferID p_buffer, DataFormat p_format) override final;
  211. virtual void buffer_free(BufferID p_buffer) override final;
  212. virtual uint64_t buffer_get_allocation_size(BufferID p_buffer) override final;
  213. virtual uint8_t *buffer_map(BufferID p_buffer) override final;
  214. virtual void buffer_unmap(BufferID p_buffer) override final;
  215. virtual uint64_t buffer_get_device_address(BufferID p_buffer) override final;
  216. /*****************/
  217. /**** TEXTURE ****/
  218. /*****************/
  219. private:
  220. struct TextureInfo : public ResourceInfo {
  221. DataFormat format = DATA_FORMAT_MAX;
  222. CD3DX12_RESOURCE_DESC desc = {};
  223. uint32_t base_layer = 0;
  224. uint32_t layers = 0;
  225. uint32_t base_mip = 0;
  226. uint32_t mipmaps = 0;
  227. struct {
  228. D3D12_SHADER_RESOURCE_VIEW_DESC srv;
  229. D3D12_UNORDERED_ACCESS_VIEW_DESC uav;
  230. } view_descs = {};
  231. TextureInfo *main_texture = nullptr;
  232. UINT mapped_subresource = UINT_MAX;
  233. SelfList<TextureInfo> pending_clear{ this };
  234. #ifdef DEBUG_ENABLED
  235. bool created_from_extension = false;
  236. #endif
  237. };
  238. SelfList<TextureInfo>::List textures_pending_clear;
  239. HashMap<DXGI_FORMAT, uint32_t> format_sample_counts_mask_cache;
  240. Mutex format_sample_counts_mask_cache_mutex;
  241. uint32_t _find_max_common_supported_sample_count(VectorView<DXGI_FORMAT> p_formats);
  242. UINT _compute_component_mapping(const TextureView &p_view);
  243. UINT _compute_plane_slice(DataFormat p_format, BitField<TextureAspectBits> p_aspect_bits);
  244. UINT _compute_plane_slice(DataFormat p_format, TextureAspect p_aspect);
  245. UINT _compute_subresource_from_layers(TextureInfo *p_texture, const TextureSubresourceLayers &p_layers, uint32_t p_layer_offset);
  246. void _discard_texture_subresources(const TextureInfo *p_tex_info, const CommandBufferInfo *p_cmd_buf_info);
  247. protected:
  248. virtual bool _unordered_access_supported_by_format(DataFormat p_format);
  249. public:
  250. virtual TextureID texture_create(const TextureFormat &p_format, const TextureView &p_view) override final;
  251. virtual TextureID texture_create_from_extension(uint64_t p_native_texture, TextureType p_type, DataFormat p_format, uint32_t p_array_layers, bool p_depth_stencil, uint32_t p_mipmaps) override final;
  252. virtual TextureID texture_create_shared(TextureID p_original_texture, const TextureView &p_view) override final;
  253. virtual TextureID texture_create_shared_from_slice(TextureID p_original_texture, const TextureView &p_view, TextureSliceType p_slice_type, uint32_t p_layer, uint32_t p_layers, uint32_t p_mipmap, uint32_t p_mipmaps) override final;
  254. virtual void texture_free(TextureID p_texture) override final;
  255. virtual uint64_t texture_get_allocation_size(TextureID p_texture) override final;
  256. virtual void texture_get_copyable_layout(TextureID p_texture, const TextureSubresource &p_subresource, TextureCopyableLayout *r_layout) override final;
  257. virtual uint8_t *texture_map(TextureID p_texture, const TextureSubresource &p_subresource) override final;
  258. virtual void texture_unmap(TextureID p_texture) override final;
  259. virtual BitField<TextureUsageBits> texture_get_usages_supported_by_format(DataFormat p_format, bool p_cpu_readable) override final;
  260. virtual bool texture_can_make_shared_with_format(TextureID p_texture, DataFormat p_format, bool &r_raw_reinterpretation) override final;
  261. private:
  262. TextureID _texture_create_shared_from_slice(TextureID p_original_texture, const TextureView &p_view, TextureSliceType p_slice_type, uint32_t p_layer, uint32_t p_layers, uint32_t p_mipmap, uint32_t p_mipmaps);
  263. public:
  264. /*****************/
  265. /**** SAMPLER ****/
  266. /*****************/
  267. private:
  268. LocalVector<D3D12_SAMPLER_DESC> samplers;
  269. public:
  270. virtual SamplerID sampler_create(const SamplerState &p_state) final override;
  271. virtual void sampler_free(SamplerID p_sampler) final override;
  272. virtual bool sampler_is_format_supported_for_filter(DataFormat p_format, SamplerFilter p_filter) override final;
  273. /**********************/
  274. /**** VERTEX ARRAY ****/
  275. /**********************/
  276. private:
  277. struct VertexFormatInfo {
  278. TightLocalVector<D3D12_INPUT_ELEMENT_DESC> input_elem_descs;
  279. TightLocalVector<UINT> vertex_buffer_strides;
  280. };
  281. public:
  282. virtual VertexFormatID vertex_format_create(VectorView<VertexAttribute> p_vertex_attribs) override final;
  283. virtual void vertex_format_free(VertexFormatID p_vertex_format) override final;
  284. /******************/
  285. /**** BARRIERS ****/
  286. /******************/
  287. virtual void command_pipeline_barrier(
  288. CommandBufferID p_cmd_buffer,
  289. BitField<PipelineStageBits> p_src_stages,
  290. BitField<PipelineStageBits> p_dst_stages,
  291. VectorView<RDD::MemoryBarrier> p_memory_barriers,
  292. VectorView<RDD::BufferBarrier> p_buffer_barriers,
  293. VectorView<RDD::TextureBarrier> p_texture_barriers) override final;
  294. private:
  295. /****************/
  296. /**** FENCES ****/
  297. /****************/
  298. struct FenceInfo {
  299. ComPtr<ID3D12Fence> d3d_fence = nullptr;
  300. HANDLE event_handle = nullptr;
  301. UINT64 fence_value = 0;
  302. };
  303. public:
  304. virtual FenceID fence_create() override;
  305. virtual Error fence_wait(FenceID p_fence) override;
  306. virtual void fence_free(FenceID p_fence) override;
  307. private:
  308. /********************/
  309. /**** SEMAPHORES ****/
  310. /********************/
  311. struct SemaphoreInfo {
  312. ComPtr<ID3D12Fence> d3d_fence = nullptr;
  313. UINT64 fence_value = 0;
  314. };
  315. virtual SemaphoreID semaphore_create() override;
  316. virtual void semaphore_free(SemaphoreID p_semaphore) override;
  317. /******************/
  318. /**** COMMANDS ****/
  319. /******************/
  320. // ----- QUEUE FAMILY -----
  321. virtual CommandQueueFamilyID command_queue_family_get(BitField<CommandQueueFamilyBits> p_cmd_queue_family_bits, RenderingContextDriver::SurfaceID p_surface = 0) override;
  322. private:
  323. // ----- QUEUE -----
  324. struct CommandQueueInfo {
  325. ComPtr<ID3D12CommandQueue> d3d_queue;
  326. };
  327. public:
  328. virtual CommandQueueID command_queue_create(CommandQueueFamilyID p_cmd_queue_family, bool p_identify_as_main_queue = false) override;
  329. virtual Error command_queue_execute_and_present(CommandQueueID p_cmd_queue, VectorView<SemaphoreID> p_wait_semaphores, VectorView<CommandBufferID> p_cmd_buffers, VectorView<SemaphoreID> p_cmd_semaphores, FenceID p_cmd_fence, VectorView<SwapChainID> p_swap_chains) override;
  330. virtual void command_queue_free(CommandQueueID p_cmd_queue) override;
  331. private:
  332. // ----- POOL -----
  333. struct CommandPoolInfo {
  334. CommandQueueFamilyID queue_family;
  335. CommandBufferType buffer_type = COMMAND_BUFFER_TYPE_PRIMARY;
  336. // Since there are no command pools in D3D12, we need to track the command buffers created by this pool
  337. // so that we can free them when the pool is freed.
  338. SelfList<CommandBufferInfo>::List command_buffers;
  339. };
  340. public:
  341. virtual CommandPoolID command_pool_create(CommandQueueFamilyID p_cmd_queue_family, CommandBufferType p_cmd_buffer_type) override final;
  342. virtual bool command_pool_reset(CommandPoolID p_cmd_pool) override final;
  343. virtual void command_pool_free(CommandPoolID p_cmd_pool) override final;
  344. // ----- BUFFER -----
  345. private:
  346. // Belongs to RENDERING-SUBPASS, but needed here.
  347. struct FramebufferInfo;
  348. struct RenderPassInfo;
  349. struct RenderPassState {
  350. uint32_t current_subpass = UINT32_MAX;
  351. const FramebufferInfo *fb_info = nullptr;
  352. const RenderPassInfo *pass_info = nullptr;
  353. CD3DX12_RECT region_rect = {};
  354. bool region_is_all = false;
  355. const VertexFormatInfo *vf_info = nullptr;
  356. D3D12_VERTEX_BUFFER_VIEW vertex_buffer_views[8] = {};
  357. uint32_t vertex_buffer_count = 0;
  358. };
  359. // Leveraging knowledge of actual usage and D3D12 specifics (namely, command lists from the same allocator
  360. // can't be freely begun and ended), an allocator per list works better.
  361. struct CommandBufferInfo {
  362. // Store a self list reference to be used by the command pool.
  363. SelfList<CommandBufferInfo> command_buffer_info_elem{ this };
  364. ComPtr<ID3D12CommandAllocator> cmd_allocator;
  365. ComPtr<ID3D12GraphicsCommandList> cmd_list;
  366. ID3D12PipelineState *graphics_pso = nullptr;
  367. ID3D12PipelineState *compute_pso = nullptr;
  368. uint32_t graphics_root_signature_crc = 0;
  369. uint32_t compute_root_signature_crc = 0;
  370. RenderPassState render_pass_state;
  371. bool descriptor_heaps_set = false;
  372. HashMap<ResourceInfo::States *, BarrierRequest> res_barriers_requests;
  373. LocalVector<D3D12_RESOURCE_BARRIER> res_barriers;
  374. uint32_t res_barriers_count = 0;
  375. uint32_t res_barriers_batch = 0;
  376. };
  377. public:
  378. virtual CommandBufferID command_buffer_create(CommandPoolID p_cmd_pool) override final;
  379. virtual bool command_buffer_begin(CommandBufferID p_cmd_buffer) override final;
  380. virtual bool command_buffer_begin_secondary(CommandBufferID p_cmd_buffer, RenderPassID p_render_pass, uint32_t p_subpass, FramebufferID p_framebuffer) override final;
  381. virtual void command_buffer_end(CommandBufferID p_cmd_buffer) override final;
  382. virtual void command_buffer_execute_secondary(CommandBufferID p_cmd_buffer, VectorView<CommandBufferID> p_secondary_cmd_buffers) override final;
  383. private:
  384. /********************/
  385. /**** SWAP CHAIN ****/
  386. /********************/
  387. struct SwapChain {
  388. ComPtr<IDXGISwapChain3> d3d_swap_chain;
  389. RenderingContextDriver::SurfaceID surface = RenderingContextDriver::SurfaceID();
  390. UINT present_flags = 0;
  391. UINT sync_interval = 1;
  392. UINT creation_flags = 0;
  393. RenderPassID render_pass;
  394. TightLocalVector<ID3D12Resource *> render_targets;
  395. TightLocalVector<TextureInfo> render_targets_info;
  396. TightLocalVector<FramebufferID> framebuffers;
  397. RDD::DataFormat data_format = DATA_FORMAT_MAX;
  398. };
  399. void _swap_chain_release(SwapChain *p_swap_chain);
  400. void _swap_chain_release_buffers(SwapChain *p_swap_chain);
  401. public:
  402. virtual SwapChainID swap_chain_create(RenderingContextDriver::SurfaceID p_surface) override;
  403. virtual Error swap_chain_resize(CommandQueueID p_cmd_queue, SwapChainID p_swap_chain, uint32_t p_desired_framebuffer_count) override;
  404. virtual FramebufferID swap_chain_acquire_framebuffer(CommandQueueID p_cmd_queue, SwapChainID p_swap_chain, bool &r_resize_required) override;
  405. virtual RenderPassID swap_chain_get_render_pass(SwapChainID p_swap_chain) override;
  406. virtual DataFormat swap_chain_get_format(SwapChainID p_swap_chain) override;
  407. virtual void swap_chain_free(SwapChainID p_swap_chain) override;
  408. /*********************/
  409. /**** FRAMEBUFFER ****/
  410. /*********************/
  411. private:
  412. struct FramebufferInfo {
  413. bool is_screen = false;
  414. Size2i size;
  415. TightLocalVector<uint32_t> attachments_handle_inds; // RTV heap index for color; DSV heap index for DSV.
  416. DescriptorsHeap rtv_heap;
  417. DescriptorsHeap dsv_heap; // Used only if not for screen and some depth-stencil attachments.
  418. TightLocalVector<TextureID> attachments; // Color and depth-stencil. Used if not screen.
  419. TextureID vrs_attachment;
  420. };
  421. D3D12_RENDER_TARGET_VIEW_DESC _make_rtv_for_texture(const TextureInfo *p_texture_info, uint32_t p_mipmap_offset, uint32_t p_layer_offset, uint32_t p_layers, bool p_add_bases = true);
  422. D3D12_UNORDERED_ACCESS_VIEW_DESC _make_ranged_uav_for_texture(const TextureInfo *p_texture_info, uint32_t p_mipmap_offset, uint32_t p_layer_offset, uint32_t p_layers, bool p_add_bases = true);
  423. D3D12_DEPTH_STENCIL_VIEW_DESC _make_dsv_for_texture(const TextureInfo *p_texture_info);
  424. FramebufferID _framebuffer_create(RenderPassID p_render_pass, VectorView<TextureID> p_attachments, uint32_t p_width, uint32_t p_height, bool p_is_screen);
  425. public:
  426. virtual FramebufferID framebuffer_create(RenderPassID p_render_pass, VectorView<TextureID> p_attachments, uint32_t p_width, uint32_t p_height) override final;
  427. virtual void framebuffer_free(FramebufferID p_framebuffer) override final;
  428. /****************/
  429. /**** SHADER ****/
  430. /****************/
  431. private:
  432. static const uint32_t ROOT_SIGNATURE_SIZE = 256;
  433. static const uint32_t PUSH_CONSTANT_SIZE = 128; // Mimicking Vulkan.
  434. enum {
  435. // We can only aim to set a maximum here, since depending on the shader
  436. // there may be more or less root signature free for descriptor tables.
  437. // Therefore, we'll have to rely on the final check at runtime, when building
  438. // the root signature structure for a given shader.
  439. // To be precise, these may be present or not, and their size vary statically:
  440. // - Push constant (we'll assume this is always present to avoid reserving much
  441. // more space for descriptor sets than needed for almost any imaginable case,
  442. // given that most shader templates feature push constants).
  443. // - NIR-DXIL runtime data.
  444. MAX_UNIFORM_SETS = (ROOT_SIGNATURE_SIZE - PUSH_CONSTANT_SIZE) / sizeof(uint32_t),
  445. };
  446. struct ShaderInfo {
  447. uint32_t dxil_push_constant_size = 0;
  448. uint32_t nir_runtime_data_root_param_idx = UINT32_MAX;
  449. bool is_compute = false;
  450. struct UniformBindingInfo {
  451. uint32_t stages = 0; // Actual shader stages using the uniform (0 if totally optimized out).
  452. ResourceClass res_class = RES_CLASS_INVALID;
  453. UniformType type = UNIFORM_TYPE_MAX;
  454. uint32_t length = UINT32_MAX;
  455. #ifdef DEV_ENABLED
  456. bool writable = false;
  457. #endif
  458. struct RootSignatureLocation {
  459. uint32_t root_param_idx = UINT32_MAX;
  460. uint32_t range_idx = UINT32_MAX;
  461. };
  462. struct {
  463. RootSignatureLocation resource;
  464. RootSignatureLocation sampler;
  465. } root_sig_locations;
  466. };
  467. struct UniformSet {
  468. TightLocalVector<UniformBindingInfo> bindings;
  469. struct {
  470. uint32_t resources = 0;
  471. uint32_t samplers = 0;
  472. } num_root_params;
  473. };
  474. TightLocalVector<UniformSet> sets;
  475. struct SpecializationConstant {
  476. uint32_t constant_id = UINT32_MAX;
  477. uint32_t int_value = UINT32_MAX;
  478. uint64_t stages_bit_offsets[D3D12_BITCODE_OFFSETS_NUM_STAGES] = {};
  479. };
  480. TightLocalVector<SpecializationConstant> specialization_constants;
  481. uint32_t spirv_specialization_constants_ids_mask = 0;
  482. HashMap<ShaderStage, Vector<uint8_t>> stages_bytecode;
  483. ComPtr<ID3D12RootSignature> root_signature;
  484. ComPtr<ID3D12RootSignatureDeserializer> root_signature_deserializer;
  485. const D3D12_ROOT_SIGNATURE_DESC *root_signature_desc = nullptr; // Owned by the deserializer.
  486. uint32_t root_signature_crc = 0;
  487. };
  488. bool _shader_apply_specialization_constants(
  489. const ShaderInfo *p_shader_info,
  490. VectorView<PipelineSpecializationConstant> p_specialization_constants,
  491. HashMap<ShaderStage, Vector<uint8_t>> &r_final_stages_bytecode);
  492. public:
  493. virtual ShaderID shader_create_from_container(const Ref<RenderingShaderContainer> &p_shader_container, const Vector<ImmutableSampler> &p_immutable_samplers) override final;
  494. virtual uint32_t shader_get_layout_hash(ShaderID p_shader) override final;
  495. virtual void shader_free(ShaderID p_shader) override final;
  496. virtual void shader_destroy_modules(ShaderID p_shader) override final;
  497. /*********************/
  498. /**** UNIFORM SET ****/
  499. /*********************/
  500. private:
  501. struct RootDescriptorTable {
  502. uint32_t root_param_idx = UINT32_MAX;
  503. D3D12_GPU_DESCRIPTOR_HANDLE start_gpu_handle = {};
  504. };
  505. struct UniformSetInfo {
  506. struct {
  507. DescriptorsHeap resources;
  508. DescriptorsHeap samplers;
  509. } desc_heaps;
  510. struct StateRequirement {
  511. ResourceInfo *resource = nullptr;
  512. bool is_buffer = false;
  513. D3D12_RESOURCE_STATES states = {};
  514. uint64_t shader_uniform_idx_mask = 0;
  515. };
  516. TightLocalVector<StateRequirement> resource_states;
  517. struct RecentBind {
  518. uint64_t segment_serial = 0;
  519. uint32_t root_signature_crc = 0;
  520. struct {
  521. TightLocalVector<RootDescriptorTable> resources;
  522. TightLocalVector<RootDescriptorTable> samplers;
  523. } root_tables;
  524. int uses = 0;
  525. } recent_binds[4]; // A better amount may be empirically found.
  526. #ifdef DEV_ENABLED
  527. // Filthy, but useful for dev.
  528. struct ResourceDescInfo {
  529. D3D12_DESCRIPTOR_RANGE_TYPE type;
  530. D3D12_SRV_DIMENSION srv_dimension;
  531. };
  532. TightLocalVector<ResourceDescInfo> resources_desc_info;
  533. #endif
  534. };
  535. public:
  536. virtual UniformSetID uniform_set_create(VectorView<BoundUniform> p_uniforms, ShaderID p_shader, uint32_t p_set_index, int p_linear_pool_index) override final;
  537. virtual void uniform_set_free(UniformSetID p_uniform_set) override final;
  538. // ----- COMMANDS -----
  539. virtual void command_uniform_set_prepare_for_use(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index) override final;
  540. private:
  541. void _command_check_descriptor_sets(CommandBufferID p_cmd_buffer);
  542. void _command_bind_uniform_set(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index, bool p_for_compute);
  543. void _command_bind_uniform_sets(CommandBufferID p_cmd_buffer, VectorView<UniformSetID> p_uniform_sets, ShaderID p_shader, uint32_t p_first_set_index, uint32_t p_set_count, bool p_for_compute);
  544. public:
  545. /******************/
  546. /**** TRANSFER ****/
  547. /******************/
  548. virtual void command_clear_buffer(CommandBufferID p_cmd_buffer, BufferID p_buffer, uint64_t p_offset, uint64_t p_size) override final;
  549. virtual void command_copy_buffer(CommandBufferID p_cmd_buffer, BufferID p_src_buffer, BufferID p_dst_buffer, VectorView<BufferCopyRegion> p_regions) override final;
  550. virtual void command_copy_texture(CommandBufferID p_cmd_buffer, TextureID p_src_texture, TextureLayout p_src_texture_layout, TextureID p_dst_texture, TextureLayout p_dst_texture_layout, VectorView<TextureCopyRegion> p_regions) override final;
  551. virtual void command_resolve_texture(CommandBufferID p_cmd_buffer, TextureID p_src_texture, TextureLayout p_src_texture_layout, uint32_t p_src_layer, uint32_t p_src_mipmap, TextureID p_dst_texture, TextureLayout p_dst_texture_layout, uint32_t p_dst_layer, uint32_t p_dst_mipmap) override final;
  552. virtual void command_clear_color_texture(CommandBufferID p_cmd_buffer, TextureID p_texture, TextureLayout p_texture_layout, const Color &p_color, const TextureSubresourceRange &p_subresources) override final;
  553. public:
  554. virtual void command_copy_buffer_to_texture(CommandBufferID p_cmd_buffer, BufferID p_src_buffer, TextureID p_dst_texture, TextureLayout p_dst_texture_layout, VectorView<BufferTextureCopyRegion> p_regions) override final;
  555. virtual void command_copy_texture_to_buffer(CommandBufferID p_cmd_buffer, TextureID p_src_texture, TextureLayout p_src_texture_layout, BufferID p_dst_buffer, VectorView<BufferTextureCopyRegion> p_regions) override final;
  556. /******************/
  557. /**** PIPELINE ****/
  558. /******************/
  559. struct RenderPipelineInfo {
  560. const VertexFormatInfo *vf_info = nullptr;
  561. struct {
  562. D3D12_PRIMITIVE_TOPOLOGY primitive_topology = {};
  563. Color blend_constant;
  564. float depth_bounds_min = 0.0f;
  565. float depth_bounds_max = 0.0f;
  566. uint32_t stencil_reference = 0;
  567. } dyn_params;
  568. };
  569. struct PipelineInfo {
  570. ID3D12PipelineState *pso = nullptr;
  571. const ShaderInfo *shader_info = nullptr;
  572. RenderPipelineInfo render_info;
  573. };
  574. virtual void pipeline_free(PipelineID p_pipeline) override final;
  575. public:
  576. // ----- BINDING -----
  577. virtual void command_bind_push_constants(CommandBufferID p_cmd_buffer, ShaderID p_shader, uint32_t p_dst_first_index, VectorView<uint32_t> p_data) override final;
  578. // ----- CACHE -----
  579. virtual bool pipeline_cache_create(const Vector<uint8_t> &p_data) override final;
  580. virtual void pipeline_cache_free() override final;
  581. virtual size_t pipeline_cache_query_size() override final;
  582. virtual Vector<uint8_t> pipeline_cache_serialize() override final;
  583. /*******************/
  584. /**** RENDERING ****/
  585. /*******************/
  586. // ----- SUBPASS -----
  587. private:
  588. struct RenderPassInfo {
  589. TightLocalVector<Attachment> attachments;
  590. TightLocalVector<Subpass> subpasses;
  591. uint32_t view_count = 0;
  592. uint32_t max_supported_sample_count = 0;
  593. };
  594. public:
  595. virtual RenderPassID render_pass_create(VectorView<Attachment> p_attachments, VectorView<Subpass> p_subpasses, VectorView<SubpassDependency> p_subpass_dependencies, uint32_t p_view_count, AttachmentReference p_fragment_density_map_attachment) override final;
  596. virtual void render_pass_free(RenderPassID p_render_pass) override final;
  597. // ----- COMMANDS -----
  598. virtual void command_begin_render_pass(CommandBufferID p_cmd_buffer, RenderPassID p_render_pass, FramebufferID p_framebuffer, CommandBufferType p_cmd_buffer_type, const Rect2i &p_rect, VectorView<RenderPassClearValue> p_clear_values) override final;
  599. private:
  600. void _end_render_pass(CommandBufferID p_cmd_buffer);
  601. public:
  602. virtual void command_end_render_pass(CommandBufferID p_cmd_buffer) override final;
  603. virtual void command_next_render_subpass(CommandBufferID p_cmd_buffer, CommandBufferType p_cmd_buffer_type) override final;
  604. virtual void command_render_set_viewport(CommandBufferID p_cmd_buffer, VectorView<Rect2i> p_viewports) override final;
  605. virtual void command_render_set_scissor(CommandBufferID p_cmd_buffer, VectorView<Rect2i> p_scissors) override final;
  606. virtual void command_render_clear_attachments(CommandBufferID p_cmd_buffer, VectorView<AttachmentClear> p_attachment_clears, VectorView<Rect2i> p_rects) override final;
  607. // Binding.
  608. virtual void command_bind_render_pipeline(CommandBufferID p_cmd_buffer, PipelineID p_pipeline) override final;
  609. virtual void command_bind_render_uniform_set(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index) override final;
  610. virtual void command_bind_render_uniform_sets(CommandBufferID p_cmd_buffer, VectorView<UniformSetID> p_uniform_sets, ShaderID p_shader, uint32_t p_first_set_index, uint32_t p_set_count) override final;
  611. // Drawing.
  612. virtual void command_render_draw(CommandBufferID p_cmd_buffer, uint32_t p_vertex_count, uint32_t p_instance_count, uint32_t p_base_vertex, uint32_t p_first_instance) override final;
  613. virtual void command_render_draw_indexed(CommandBufferID p_cmd_buffer, uint32_t p_index_count, uint32_t p_instance_count, uint32_t p_first_index, int32_t p_vertex_offset, uint32_t p_first_instance) override final;
  614. virtual void command_render_draw_indexed_indirect(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset, uint32_t p_draw_count, uint32_t p_stride) override final;
  615. virtual void command_render_draw_indexed_indirect_count(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset, BufferID p_count_buffer, uint64_t p_count_buffer_offset, uint32_t p_max_draw_count, uint32_t p_stride) override final;
  616. virtual void command_render_draw_indirect(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset, uint32_t p_draw_count, uint32_t p_stride) override final;
  617. virtual void command_render_draw_indirect_count(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset, BufferID p_count_buffer, uint64_t p_count_buffer_offset, uint32_t p_max_draw_count, uint32_t p_stride) override final;
  618. // Buffer binding.
  619. virtual void command_render_bind_vertex_buffers(CommandBufferID p_cmd_buffer, uint32_t p_binding_count, const BufferID *p_buffers, const uint64_t *p_offsets) override final;
  620. virtual void command_render_bind_index_buffer(CommandBufferID p_cmd_buffer, BufferID p_buffer, IndexBufferFormat p_format, uint64_t p_offset) override final;
  621. private:
  622. void _bind_vertex_buffers(CommandBufferInfo *p_cmd_buf_info);
  623. public:
  624. // Dynamic state.
  625. virtual void command_render_set_blend_constants(CommandBufferID p_cmd_buffer, const Color &p_constants) override final;
  626. virtual void command_render_set_line_width(CommandBufferID p_cmd_buffer, float p_width) override final;
  627. // ----- PIPELINE -----
  628. public:
  629. virtual PipelineID render_pipeline_create(
  630. ShaderID p_shader,
  631. VertexFormatID p_vertex_format,
  632. RenderPrimitive p_render_primitive,
  633. PipelineRasterizationState p_rasterization_state,
  634. PipelineMultisampleState p_multisample_state,
  635. PipelineDepthStencilState p_depth_stencil_state,
  636. PipelineColorBlendState p_blend_state,
  637. VectorView<int32_t> p_color_attachments,
  638. BitField<PipelineDynamicStateFlags> p_dynamic_state,
  639. RenderPassID p_render_pass,
  640. uint32_t p_render_subpass,
  641. VectorView<PipelineSpecializationConstant> p_specialization_constants) override final;
  642. /*****************/
  643. /**** COMPUTE ****/
  644. /*****************/
  645. // ----- COMMANDS -----
  646. // Binding.
  647. virtual void command_bind_compute_pipeline(CommandBufferID p_cmd_buffer, PipelineID p_pipeline) override final;
  648. virtual void command_bind_compute_uniform_set(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index) override final;
  649. virtual void command_bind_compute_uniform_sets(CommandBufferID p_cmd_buffer, VectorView<UniformSetID> p_uniform_sets, ShaderID p_shader, uint32_t p_first_set_index, uint32_t p_set_count) override final;
  650. // Dispatching.
  651. virtual void command_compute_dispatch(CommandBufferID p_cmd_buffer, uint32_t p_x_groups, uint32_t p_y_groups, uint32_t p_z_groups) override final;
  652. virtual void command_compute_dispatch_indirect(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset) override final;
  653. // ----- PIPELINE -----
  654. virtual PipelineID compute_pipeline_create(ShaderID p_shader, VectorView<PipelineSpecializationConstant> p_specialization_constants) override final;
  655. /*****************/
  656. /**** QUERIES ****/
  657. /*****************/
  658. // ----- TIMESTAMP -----
  659. private:
  660. struct TimestampQueryPoolInfo {
  661. ComPtr<ID3D12QueryHeap> query_heap;
  662. uint32_t query_count = 0;
  663. ComPtr<D3D12MA::Allocation> results_buffer_allocation;
  664. };
  665. public:
  666. // Basic.
  667. virtual QueryPoolID timestamp_query_pool_create(uint32_t p_query_count) override final;
  668. virtual void timestamp_query_pool_free(QueryPoolID p_pool_id) override final;
  669. virtual void timestamp_query_pool_get_results(QueryPoolID p_pool_id, uint32_t p_query_count, uint64_t *r_results) override final;
  670. virtual uint64_t timestamp_query_result_to_time(uint64_t p_result) override final;
  671. // Commands.
  672. virtual void command_timestamp_query_pool_reset(CommandBufferID p_cmd_buffer, QueryPoolID p_pool_id, uint32_t p_query_count) override final;
  673. virtual void command_timestamp_write(CommandBufferID p_cmd_buffer, QueryPoolID p_pool_id, uint32_t p_index) override final;
  674. /****************/
  675. /**** LABELS ****/
  676. /****************/
  677. virtual void command_begin_label(CommandBufferID p_cmd_buffer, const char *p_label_name, const Color &p_color) override final;
  678. virtual void command_end_label(CommandBufferID p_cmd_buffer) override final;
  679. /****************/
  680. /**** DEBUG *****/
  681. /****************/
  682. virtual void command_insert_breadcrumb(CommandBufferID p_cmd_buffer, uint32_t p_data) override final;
  683. /********************/
  684. /**** SUBMISSION ****/
  685. /********************/
  686. private:
  687. struct FrameInfo {
  688. struct {
  689. DescriptorsHeap resources;
  690. DescriptorsHeap samplers;
  691. DescriptorsHeap aux;
  692. DescriptorsHeap rtv;
  693. } desc_heaps;
  694. struct {
  695. DescriptorsHeap::Walker resources;
  696. DescriptorsHeap::Walker samplers;
  697. DescriptorsHeap::Walker aux;
  698. DescriptorsHeap::Walker rtv;
  699. } desc_heap_walkers;
  700. struct {
  701. bool resources = false;
  702. bool samplers = false;
  703. bool aux = false;
  704. bool rtv = false;
  705. } desc_heaps_exhausted_reported;
  706. CD3DX12_CPU_DESCRIPTOR_HANDLE null_rtv_handle = {}; // For [[MANUAL_SUBPASSES]].
  707. uint32_t segment_serial = 0;
  708. #ifdef DEV_ENABLED
  709. uint32_t uniform_set_reused = 0;
  710. #endif
  711. };
  712. TightLocalVector<FrameInfo> frames;
  713. uint32_t frame_idx = 0;
  714. uint32_t frames_drawn = 0;
  715. uint32_t segment_serial = 0;
  716. bool segment_begun = false;
  717. HashMap<uint64_t, bool> has_comp_alpha;
  718. public:
  719. virtual void begin_segment(uint32_t p_frame_index, uint32_t p_frames_drawn) override final;
  720. virtual void end_segment() override final;
  721. /**************/
  722. /**** MISC ****/
  723. /**************/
  724. virtual void set_object_name(ObjectType p_type, ID p_driver_id, const String &p_name) override final;
  725. virtual uint64_t get_resource_native_handle(DriverResource p_type, ID p_driver_id) override final;
  726. virtual uint64_t get_total_memory_used() override final;
  727. virtual uint64_t get_lazily_memory_used() override final;
  728. virtual uint64_t limit_get(Limit p_limit) override final;
  729. virtual uint64_t api_trait_get(ApiTrait p_trait) override final;
  730. virtual bool has_feature(Features p_feature) override final;
  731. virtual const MultiviewCapabilities &get_multiview_capabilities() override final;
  732. virtual const FragmentShadingRateCapabilities &get_fragment_shading_rate_capabilities() override final;
  733. virtual const FragmentDensityMapCapabilities &get_fragment_density_map_capabilities() override final;
  734. virtual String get_api_name() const override final;
  735. virtual String get_api_version() const override final;
  736. virtual String get_pipeline_cache_uuid() const override final;
  737. virtual const Capabilities &get_capabilities() const override final;
  738. virtual const RenderingShaderContainerFormat &get_shader_container_format() const override final;
  739. virtual bool is_composite_alpha_supported(CommandQueueID p_queue) const override final;
  740. static bool is_in_developer_mode();
  741. private:
  742. /*********************/
  743. /**** BOOKKEEPING ****/
  744. /*********************/
  745. using VersatileResource = VersatileResourceTemplate<
  746. BufferInfo,
  747. TextureInfo,
  748. TextureInfo,
  749. TextureInfo,
  750. VertexFormatInfo,
  751. CommandBufferInfo,
  752. FramebufferInfo,
  753. ShaderInfo,
  754. UniformSetInfo,
  755. RenderPassInfo,
  756. TimestampQueryPoolInfo>;
  757. PagedAllocator<VersatileResource, true> resources_allocator;
  758. /******************/
  759. public:
  760. RenderingDeviceDriverD3D12(RenderingContextDriverD3D12 *p_context_driver);
  761. virtual ~RenderingDeviceDriverD3D12();
  762. };