rendering_shader_container_d3d12.cpp 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040
  1. /**************************************************************************/
  2. /* rendering_shader_container_d3d12.cpp */
  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. #include "rendering_shader_container_d3d12.h"
  31. #include "core/templates/sort_array.h"
  32. #include "dxil_hash.h"
  33. #include <zlib.h>
  34. GODOT_GCC_WARNING_PUSH
  35. GODOT_GCC_WARNING_IGNORE("-Wimplicit-fallthrough")
  36. GODOT_GCC_WARNING_IGNORE("-Wlogical-not-parentheses")
  37. GODOT_GCC_WARNING_IGNORE("-Wmissing-field-initializers")
  38. GODOT_GCC_WARNING_IGNORE("-Wnon-virtual-dtor")
  39. GODOT_GCC_WARNING_IGNORE("-Wshadow")
  40. GODOT_GCC_WARNING_IGNORE("-Wswitch")
  41. GODOT_CLANG_WARNING_PUSH
  42. GODOT_CLANG_WARNING_IGNORE("-Wimplicit-fallthrough")
  43. GODOT_CLANG_WARNING_IGNORE("-Wlogical-not-parentheses")
  44. GODOT_CLANG_WARNING_IGNORE("-Wmissing-field-initializers")
  45. GODOT_CLANG_WARNING_IGNORE("-Wnon-virtual-dtor")
  46. GODOT_CLANG_WARNING_IGNORE("-Wstring-plus-int")
  47. GODOT_CLANG_WARNING_IGNORE("-Wswitch")
  48. GODOT_MSVC_WARNING_PUSH
  49. GODOT_MSVC_WARNING_IGNORE(4200) // "nonstandard extension used: zero-sized array in struct/union".
  50. GODOT_MSVC_WARNING_IGNORE(4806) // "'&': unsafe operation: no value of type 'bool' promoted to type 'uint32_t' can equal the given constant".
  51. #include <dxgi1_6.h>
  52. #include <thirdparty/directx_headers/include/directx/d3dx12.h>
  53. #define D3D12MA_D3D12_HEADERS_ALREADY_INCLUDED
  54. #include <thirdparty/d3d12ma/D3D12MemAlloc.h>
  55. #include <wrl/client.h>
  56. #include <nir_spirv.h>
  57. #include <nir_to_dxil.h>
  58. #include <spirv_to_dxil.h>
  59. extern "C" {
  60. #include <dxil_spirv_nir.h>
  61. }
  62. GODOT_GCC_WARNING_POP
  63. GODOT_CLANG_WARNING_POP
  64. GODOT_MSVC_WARNING_POP
  65. // SPIR-V to DXIL does way too many allocations, which causes worker threads
  66. // to bottleneck each other due to sharing the same global process heap.
  67. // This can be solved by making each thread allocate from its own heap.
  68. #define SPIRV_TO_DXIL_ENABLE_HEAP_PER_THREAD
  69. #ifdef SPIRV_TO_DXIL_ENABLE_HEAP_PER_THREAD
  70. namespace {
  71. struct Win32Heap {
  72. HANDLE handle;
  73. SafeRefCount ref_count;
  74. Win32Heap() {
  75. handle = HeapCreate(0, 0, 0);
  76. ref_count.init();
  77. }
  78. ~Win32Heap() {
  79. HeapDestroy(handle);
  80. }
  81. };
  82. constexpr size_t ALLOC_HEADER_SIZE = sizeof(Win32Heap *) * 2;
  83. } //namespace
  84. extern "C" {
  85. void *godot_nir_malloc(size_t p_size) {
  86. // This RAII helper is for allowing the heap to be destroyed when the thread quits.
  87. struct Win32HeapHolder {
  88. Win32Heap *win32_heap = nullptr;
  89. Win32HeapHolder() {
  90. win32_heap = memnew(Win32Heap);
  91. }
  92. ~Win32HeapHolder() {
  93. if (win32_heap->ref_count.unref()) {
  94. memdelete(win32_heap);
  95. }
  96. }
  97. };
  98. thread_local Win32HeapHolder holder;
  99. void *block = HeapAlloc(holder.win32_heap->handle, 0, p_size + ALLOC_HEADER_SIZE);
  100. // Store the heap in the allocation for the realloc/free operations.
  101. *(Win32Heap **)block = holder.win32_heap;
  102. holder.win32_heap->ref_count.ref();
  103. return (uint8_t *)block + ALLOC_HEADER_SIZE;
  104. }
  105. void *godot_nir_realloc(void *p_block, size_t p_size) {
  106. uint8_t *actual_block = (uint8_t *)p_block - ALLOC_HEADER_SIZE;
  107. Win32Heap *win32_heap = *(Win32Heap **)actual_block;
  108. return (uint8_t *)HeapReAlloc(win32_heap->handle, 0, actual_block, p_size + ALLOC_HEADER_SIZE) + ALLOC_HEADER_SIZE;
  109. }
  110. void godot_nir_free(void *p_block) {
  111. if (p_block != nullptr) {
  112. uint8_t *actual_block = (uint8_t *)p_block - ALLOC_HEADER_SIZE;
  113. Win32Heap *win32_heap = *(Win32Heap **)actual_block;
  114. HeapFree(win32_heap->handle, 0, actual_block);
  115. // Allocations can outlive the threads they were created in if they were stored globally.
  116. if (win32_heap->ref_count.unref()) {
  117. memdelete(win32_heap);
  118. }
  119. }
  120. }
  121. }
  122. #else
  123. extern "C" {
  124. void *godot_nir_malloc(size_t p_size) {
  125. return malloc(p_size);
  126. }
  127. void *godot_nir_realloc(void *p_block, size_t p_size) {
  128. return realloc(p_block, p_size);
  129. }
  130. void godot_nir_free(void *p_block) {
  131. return free(p_block);
  132. }
  133. }
  134. #endif
  135. static D3D12_SHADER_VISIBILITY stages_to_d3d12_visibility(uint32_t p_stages_mask) {
  136. switch (p_stages_mask) {
  137. case RenderingDeviceCommons::SHADER_STAGE_VERTEX_BIT:
  138. return D3D12_SHADER_VISIBILITY_VERTEX;
  139. case RenderingDeviceCommons::SHADER_STAGE_FRAGMENT_BIT:
  140. return D3D12_SHADER_VISIBILITY_PIXEL;
  141. default:
  142. return D3D12_SHADER_VISIBILITY_ALL;
  143. }
  144. }
  145. uint32_t RenderingDXIL::patch_specialization_constant(
  146. RenderingDeviceCommons::PipelineSpecializationConstantType p_type,
  147. const void *p_value,
  148. const uint64_t (&p_stages_bit_offsets)[D3D12_BITCODE_OFFSETS_NUM_STAGES],
  149. HashMap<RenderingDeviceCommons::ShaderStage, Vector<uint8_t>> &r_stages_bytecodes,
  150. bool p_is_first_patch) {
  151. int64_t patch_val = 0;
  152. switch (p_type) {
  153. case RenderingDeviceCommons::PIPELINE_SPECIALIZATION_CONSTANT_TYPE_INT: {
  154. patch_val = *((const int32_t *)p_value);
  155. } break;
  156. case RenderingDeviceCommons::PIPELINE_SPECIALIZATION_CONSTANT_TYPE_BOOL: {
  157. bool bool_value = *((const bool *)p_value);
  158. patch_val = (int32_t)bool_value;
  159. } break;
  160. case RenderingDeviceCommons::PIPELINE_SPECIALIZATION_CONSTANT_TYPE_FLOAT: {
  161. patch_val = *((const int32_t *)p_value);
  162. } break;
  163. }
  164. // Encode to signed VBR.
  165. if (patch_val >= 0) {
  166. patch_val <<= 1;
  167. } else {
  168. patch_val = ((-patch_val) << 1) | 1;
  169. }
  170. auto tamper_bits = [](uint8_t *p_start, uint64_t p_bit_offset, uint64_t p_tb_value) -> uint64_t {
  171. uint64_t original = 0;
  172. uint32_t curr_input_byte = p_bit_offset / 8;
  173. uint8_t curr_input_bit = p_bit_offset % 8;
  174. auto get_curr_input_bit = [&]() -> bool {
  175. return ((p_start[curr_input_byte] >> curr_input_bit) & 1);
  176. };
  177. auto move_to_next_input_bit = [&]() {
  178. if (curr_input_bit == 7) {
  179. curr_input_bit = 0;
  180. curr_input_byte++;
  181. } else {
  182. curr_input_bit++;
  183. }
  184. };
  185. auto tamper_input_bit = [&](bool p_new_bit) {
  186. p_start[curr_input_byte] &= ~((uint8_t)1 << curr_input_bit);
  187. if (p_new_bit) {
  188. p_start[curr_input_byte] |= (uint8_t)1 << curr_input_bit;
  189. }
  190. };
  191. uint8_t value_bit_idx = 0;
  192. for (uint32_t i = 0; i < 5; i++) { // 32 bits take 5 full bytes in VBR.
  193. for (uint32_t j = 0; j < 7; j++) {
  194. bool input_bit = get_curr_input_bit();
  195. original |= (uint64_t)(input_bit ? 1 : 0) << value_bit_idx;
  196. tamper_input_bit((p_tb_value >> value_bit_idx) & 1);
  197. move_to_next_input_bit();
  198. value_bit_idx++;
  199. }
  200. #ifdef DEV_ENABLED
  201. bool input_bit = get_curr_input_bit();
  202. DEV_ASSERT((i < 4 && input_bit) || (i == 4 && !input_bit));
  203. #endif
  204. move_to_next_input_bit();
  205. }
  206. return original;
  207. };
  208. uint32_t stages_patched_mask = 0;
  209. for (int stage = 0; stage < RenderingDeviceCommons::SHADER_STAGE_MAX; stage++) {
  210. if (!r_stages_bytecodes.has((RenderingDeviceCommons::ShaderStage)stage)) {
  211. continue;
  212. }
  213. uint64_t offset = p_stages_bit_offsets[RenderingShaderContainerD3D12::SHADER_STAGES_BIT_OFFSET_INDICES[stage]];
  214. if (offset == 0) {
  215. // This constant does not appear at this stage.
  216. continue;
  217. }
  218. Vector<uint8_t> &bytecode = r_stages_bytecodes[(RenderingDeviceCommons::ShaderStage)stage];
  219. #ifdef DEV_ENABLED
  220. uint64_t orig_patch_val = tamper_bits(bytecode.ptrw(), offset, (uint64_t)patch_val);
  221. // Checking against the value the NIR patch should have set.
  222. DEV_ASSERT(!p_is_first_patch || ((orig_patch_val >> 1) & GODOT_NIR_SC_SENTINEL_MAGIC_MASK) == GODOT_NIR_SC_SENTINEL_MAGIC);
  223. uint64_t readback_patch_val = tamper_bits(bytecode.ptrw(), offset, (uint64_t)patch_val);
  224. DEV_ASSERT(readback_patch_val == (uint64_t)patch_val);
  225. #else
  226. tamper_bits(bytecode.ptrw(), offset, (uint64_t)patch_val);
  227. #endif
  228. stages_patched_mask |= (1 << stage);
  229. }
  230. return stages_patched_mask;
  231. }
  232. void RenderingDXIL::sign_bytecode(RenderingDeviceCommons::ShaderStage p_stage, Vector<uint8_t> &r_dxil_blob) {
  233. uint8_t *w = r_dxil_blob.ptrw();
  234. compute_dxil_hash(w + 20, r_dxil_blob.size() - 20, w + 4);
  235. }
  236. // RenderingShaderContainerD3D12
  237. uint32_t RenderingShaderContainerD3D12::_format() const {
  238. return 0x43443344;
  239. }
  240. uint32_t RenderingShaderContainerD3D12::_format_version() const {
  241. return FORMAT_VERSION;
  242. }
  243. uint32_t RenderingShaderContainerD3D12::_from_bytes_reflection_extra_data(const uint8_t *p_bytes) {
  244. reflection_data_d3d12 = *(const ReflectionDataD3D12 *)(p_bytes);
  245. reflection_binding_set_data_d3d12.resize(reflection_data.set_count);
  246. for (uint32_t i = 0; i < reflection_binding_set_data_d3d12.size(); i++) {
  247. reflection_binding_set_data_d3d12.ptrw()[i] = *(const ReflectionBindingSetDataD3D12 *)(p_bytes + sizeof(ReflectionDataD3D12) + (i * sizeof(ReflectionBindingSetDataD3D12)));
  248. }
  249. return sizeof(ReflectionDataD3D12) + (reflection_binding_set_data_d3d12.size() * sizeof(ReflectionBindingSetDataD3D12));
  250. }
  251. uint32_t RenderingShaderContainerD3D12::_from_bytes_reflection_binding_uniform_extra_data_start(const uint8_t *p_bytes) {
  252. reflection_binding_set_uniforms_data_d3d12.resize(reflection_binding_set_uniforms_data.size());
  253. return 0;
  254. }
  255. uint32_t RenderingShaderContainerD3D12::_from_bytes_reflection_binding_uniform_extra_data(const uint8_t *p_bytes, uint32_t p_index) {
  256. reflection_binding_set_uniforms_data_d3d12.ptrw()[p_index] = *(const ReflectionBindingDataD3D12 *)(p_bytes);
  257. return sizeof(ReflectionBindingDataD3D12);
  258. }
  259. uint32_t RenderingShaderContainerD3D12::_from_bytes_reflection_specialization_extra_data_start(const uint8_t *p_bytes) {
  260. reflection_specialization_data_d3d12.resize(reflection_specialization_data.size());
  261. return 0;
  262. }
  263. uint32_t RenderingShaderContainerD3D12::_from_bytes_reflection_specialization_extra_data(const uint8_t *p_bytes, uint32_t p_index) {
  264. reflection_specialization_data_d3d12.ptrw()[p_index] = *(const ReflectionSpecializationDataD3D12 *)(p_bytes);
  265. return sizeof(ReflectionSpecializationDataD3D12);
  266. }
  267. uint32_t RenderingShaderContainerD3D12::_from_bytes_footer_extra_data(const uint8_t *p_bytes) {
  268. ContainerFooterD3D12 footer = *(const ContainerFooterD3D12 *)(p_bytes);
  269. root_signature_crc = footer.root_signature_crc;
  270. root_signature_bytes.resize(footer.root_signature_length);
  271. memcpy(root_signature_bytes.ptrw(), p_bytes + sizeof(ContainerFooterD3D12), root_signature_bytes.size());
  272. return sizeof(ContainerFooterD3D12) + footer.root_signature_length;
  273. }
  274. uint32_t RenderingShaderContainerD3D12::_to_bytes_reflection_extra_data(uint8_t *p_bytes) const {
  275. if (p_bytes != nullptr) {
  276. *(ReflectionDataD3D12 *)(p_bytes) = reflection_data_d3d12;
  277. for (uint32_t i = 0; i < reflection_binding_set_data_d3d12.size(); i++) {
  278. *(ReflectionBindingSetDataD3D12 *)(p_bytes + sizeof(ReflectionDataD3D12) + (i * sizeof(ReflectionBindingSetDataD3D12))) = reflection_binding_set_data_d3d12[i];
  279. }
  280. }
  281. return sizeof(ReflectionDataD3D12) + (reflection_binding_set_data_d3d12.size() * sizeof(ReflectionBindingSetDataD3D12));
  282. }
  283. uint32_t RenderingShaderContainerD3D12::_to_bytes_reflection_binding_uniform_extra_data(uint8_t *p_bytes, uint32_t p_index) const {
  284. if (p_bytes != nullptr) {
  285. *(ReflectionBindingDataD3D12 *)(p_bytes) = reflection_binding_set_uniforms_data_d3d12[p_index];
  286. }
  287. return sizeof(ReflectionBindingDataD3D12);
  288. }
  289. uint32_t RenderingShaderContainerD3D12::_to_bytes_reflection_specialization_extra_data(uint8_t *p_bytes, uint32_t p_index) const {
  290. if (p_bytes != nullptr) {
  291. *(ReflectionSpecializationDataD3D12 *)(p_bytes) = reflection_specialization_data_d3d12[p_index];
  292. }
  293. return sizeof(ReflectionSpecializationDataD3D12);
  294. }
  295. uint32_t RenderingShaderContainerD3D12::_to_bytes_footer_extra_data(uint8_t *p_bytes) const {
  296. if (p_bytes != nullptr) {
  297. ContainerFooterD3D12 &footer = *(ContainerFooterD3D12 *)(p_bytes);
  298. footer.root_signature_length = root_signature_bytes.size();
  299. footer.root_signature_crc = root_signature_crc;
  300. memcpy(p_bytes + sizeof(ContainerFooterD3D12), root_signature_bytes.ptr(), root_signature_bytes.size());
  301. }
  302. return sizeof(ContainerFooterD3D12) + root_signature_bytes.size();
  303. }
  304. #if NIR_ENABLED
  305. bool RenderingShaderContainerD3D12::_convert_spirv_to_nir(Span<ReflectShaderStage> p_spirv, const nir_shader_compiler_options *p_compiler_options, HashMap<int, nir_shader *> &r_stages_nir_shaders, Vector<RenderingDeviceCommons::ShaderStage> &r_stages, BitField<RenderingDeviceCommons::ShaderStage> &r_stages_processed) {
  306. r_stages_processed.clear();
  307. dxil_spirv_runtime_conf dxil_runtime_conf = {};
  308. dxil_runtime_conf.runtime_data_cbv.base_shader_register = RUNTIME_DATA_REGISTER;
  309. dxil_runtime_conf.push_constant_cbv.base_shader_register = ROOT_CONSTANT_REGISTER;
  310. dxil_runtime_conf.first_vertex_and_base_instance_mode = DXIL_SPIRV_SYSVAL_TYPE_ZERO;
  311. dxil_runtime_conf.workgroup_id_mode = DXIL_SPIRV_SYSVAL_TYPE_ZERO;
  312. // Explicitly keeping these false because converting UAV descriptors to SRVs do not seem to have real performance benefits on desktop GPUs.
  313. // It also makes it easier to implement descriptor heaps and enhanced barriers.
  314. dxil_runtime_conf.declared_read_only_images_as_srvs = false;
  315. dxil_runtime_conf.inferred_read_only_images_as_srvs = false;
  316. // Translate SPIR-V to NIR.
  317. for (uint64_t i = 0; i < p_spirv.size(); i++) {
  318. RenderingDeviceCommons::ShaderStage stage = p_spirv[i].shader_stage;
  319. RenderingDeviceCommons::ShaderStage stage_flag = (RenderingDeviceCommons::ShaderStage)(1 << stage);
  320. r_stages.push_back(stage);
  321. r_stages_processed.set_flag(stage_flag);
  322. const char *entry_point = "main";
  323. static const mesa_shader_stage SPIRV_TO_MESA_STAGES[RenderingDeviceCommons::SHADER_STAGE_MAX] = {
  324. MESA_SHADER_VERTEX, // SHADER_STAGE_VERTEX
  325. MESA_SHADER_FRAGMENT, // SHADER_STAGE_FRAGMENT
  326. MESA_SHADER_TESS_CTRL, // SHADER_STAGE_TESSELATION_CONTROL
  327. MESA_SHADER_TESS_EVAL, // SHADER_STAGE_TESSELATION_EVALUATION
  328. MESA_SHADER_COMPUTE, // SHADER_STAGE_COMPUTE
  329. };
  330. Span<uint32_t> code = p_spirv[i].spirv();
  331. nir_shader *shader = spirv_to_nir(
  332. code.ptr(),
  333. code.size(),
  334. nullptr,
  335. 0,
  336. SPIRV_TO_MESA_STAGES[stage],
  337. entry_point,
  338. dxil_spirv_nir_get_spirv_options(),
  339. p_compiler_options);
  340. ERR_FAIL_NULL_V_MSG(shader, false, "Shader translation (step 1) at stage " + String(RenderingDeviceCommons::SHADER_STAGE_NAMES[stage]) + " failed.");
  341. if (stage == RenderingDeviceCommons::SHADER_STAGE_VERTEX) {
  342. dxil_runtime_conf.yz_flip.y_mask = 0xffff;
  343. dxil_runtime_conf.yz_flip.mode = DXIL_SPIRV_Y_FLIP_UNCONDITIONAL;
  344. } else {
  345. dxil_runtime_conf.yz_flip.y_mask = 0;
  346. dxil_runtime_conf.yz_flip.mode = DXIL_SPIRV_YZ_FLIP_NONE;
  347. }
  348. dxil_spirv_nir_prep(shader);
  349. dxil_spirv_metadata dxil_metadata = {};
  350. dxil_spirv_nir_passes(shader, &dxil_runtime_conf, &dxil_metadata);
  351. r_stages_nir_shaders[stage] = shader;
  352. }
  353. // Link NIR shaders.
  354. for (int i = RenderingDeviceCommons::SHADER_STAGE_MAX - 1; i >= 0; i--) {
  355. if (!r_stages_nir_shaders.has(i)) {
  356. continue;
  357. }
  358. nir_shader *shader = r_stages_nir_shaders[i];
  359. nir_shader *prev_shader = nullptr;
  360. for (int j = i - 1; j >= 0; j--) {
  361. if (r_stages_nir_shaders.has(j)) {
  362. prev_shader = r_stages_nir_shaders[j];
  363. break;
  364. }
  365. }
  366. // There is a bug in the Direct3D runtime during creation of a PSO with view instancing. If a fragment
  367. // shader uses front/back face detection (SV_IsFrontFace), its signature must include the pixel position
  368. // builtin variable (SV_Position), otherwise an Internal Runtime error will occur.
  369. if (i == RenderingDeviceCommons::SHADER_STAGE_FRAGMENT) {
  370. const bool use_front_face =
  371. nir_find_variable_with_location(shader, nir_var_shader_in, VARYING_SLOT_FACE) ||
  372. (shader->info.inputs_read & VARYING_BIT_FACE) ||
  373. nir_find_variable_with_location(shader, nir_var_system_value, SYSTEM_VALUE_FRONT_FACE) ||
  374. BITSET_TEST(shader->info.system_values_read, SYSTEM_VALUE_FRONT_FACE);
  375. const bool use_position =
  376. nir_find_variable_with_location(shader, nir_var_shader_in, VARYING_SLOT_POS) ||
  377. (shader->info.inputs_read & VARYING_BIT_POS) ||
  378. nir_find_variable_with_location(shader, nir_var_system_value, SYSTEM_VALUE_FRAG_COORD) ||
  379. BITSET_TEST(shader->info.system_values_read, SYSTEM_VALUE_FRAG_COORD);
  380. if (use_front_face && !use_position) {
  381. nir_variable *const pos = nir_variable_create(shader, nir_var_shader_in, glsl_vec4_type(), "gl_FragCoord");
  382. pos->data.location = VARYING_SLOT_POS;
  383. shader->info.inputs_read |= VARYING_BIT_POS;
  384. }
  385. }
  386. if (prev_shader) {
  387. dxil_spirv_metadata dxil_metadata = {};
  388. dxil_spirv_nir_link(shader, prev_shader, &dxil_runtime_conf, &dxil_metadata);
  389. }
  390. }
  391. return true;
  392. }
  393. struct GodotNirCallbackUserData {
  394. RenderingShaderContainerD3D12 *container;
  395. RenderingDeviceCommons::ShaderStage stage;
  396. };
  397. static dxil_shader_model shader_model_d3d_to_dxil(D3D_SHADER_MODEL p_d3d_shader_model) {
  398. static_assert(SHADER_MODEL_6_0 == 0x60000);
  399. static_assert(SHADER_MODEL_6_3 == 0x60003);
  400. static_assert(D3D_SHADER_MODEL_6_0 == 0x60);
  401. static_assert(D3D_SHADER_MODEL_6_3 == 0x63);
  402. return (dxil_shader_model)((p_d3d_shader_model >> 4) * 0x10000 + (p_d3d_shader_model & 0xf));
  403. }
  404. bool RenderingShaderContainerD3D12::_convert_nir_to_dxil(const HashMap<int, nir_shader *> &p_stages_nir_shaders, BitField<RenderingDeviceCommons::ShaderStage> p_stages_processed, HashMap<RenderingDeviceCommons::ShaderStage, Vector<uint8_t>> &r_dxil_blobs) {
  405. // Translate NIR to DXIL.
  406. for (KeyValue<int, nir_shader *> it : p_stages_nir_shaders) {
  407. RenderingDeviceCommons::ShaderStage stage = (RenderingDeviceCommons::ShaderStage)(it.key);
  408. GodotNirCallbackUserData godot_nir_callback_user_data;
  409. godot_nir_callback_user_data.container = this;
  410. godot_nir_callback_user_data.stage = stage;
  411. GodotNirCallbacks godot_nir_callbacks = {};
  412. godot_nir_callbacks.data = &godot_nir_callback_user_data;
  413. godot_nir_callbacks.report_resource = _nir_report_resource;
  414. godot_nir_callbacks.report_sc_bit_offset_fn = _nir_report_sc_bit_offset;
  415. godot_nir_callbacks.report_bitcode_bit_offset_fn = _nir_report_bitcode_bit_offset;
  416. nir_to_dxil_options nir_to_dxil_options = {};
  417. nir_to_dxil_options.environment = DXIL_ENVIRONMENT_VULKAN;
  418. nir_to_dxil_options.shader_model_max = shader_model_d3d_to_dxil(D3D_SHADER_MODEL(REQUIRED_SHADER_MODEL));
  419. nir_to_dxil_options.validator_version_max = NO_DXIL_VALIDATION;
  420. nir_to_dxil_options.godot_nir_callbacks = &godot_nir_callbacks;
  421. dxil_logger logger = {};
  422. logger.log = [](void *p_priv, const char *p_msg) {
  423. #ifdef DEBUG_ENABLED
  424. print_verbose(p_msg);
  425. #endif
  426. };
  427. blob dxil_blob = {};
  428. bool ok = nir_to_dxil(it.value, &nir_to_dxil_options, &logger, &dxil_blob);
  429. ERR_FAIL_COND_V_MSG(!ok, false, "Shader translation at stage " + String(RenderingDeviceCommons::SHADER_STAGE_NAMES[stage]) + " failed.");
  430. Vector<uint8_t> blob_copy;
  431. blob_copy.resize(dxil_blob.size);
  432. memcpy(blob_copy.ptrw(), dxil_blob.data, dxil_blob.size);
  433. blob_finish(&dxil_blob);
  434. r_dxil_blobs.insert(stage, blob_copy);
  435. }
  436. return true;
  437. }
  438. bool RenderingShaderContainerD3D12::_convert_spirv_to_dxil(Span<ReflectShaderStage> p_spirv, HashMap<RenderingDeviceCommons::ShaderStage, Vector<uint8_t>> &r_dxil_blobs, Vector<RenderingDeviceCommons::ShaderStage> &r_stages, BitField<RenderingDeviceCommons::ShaderStage> &r_stages_processed) {
  439. r_dxil_blobs.clear();
  440. HashMap<int, nir_shader *> stages_nir_shaders;
  441. auto free_nir_shaders = [&]() {
  442. for (KeyValue<int, nir_shader *> &E : stages_nir_shaders) {
  443. ralloc_free(E.value);
  444. }
  445. stages_nir_shaders.clear();
  446. };
  447. // This structure must live as long as the shaders are alive.
  448. nir_shader_compiler_options compiler_options = {};
  449. const unsigned supported_bit_sizes = 16 | 32 | 64;
  450. dxil_get_nir_compiler_options(&compiler_options, shader_model_d3d_to_dxil(D3D_SHADER_MODEL(REQUIRED_SHADER_MODEL)), supported_bit_sizes, supported_bit_sizes);
  451. compiler_options.lower_base_vertex = false;
  452. // This is based on spirv2dxil.c. May need updates when it changes.
  453. // Also, this has to stay around until after linking.
  454. if (!_convert_spirv_to_nir(p_spirv, &compiler_options, stages_nir_shaders, r_stages, r_stages_processed)) {
  455. free_nir_shaders();
  456. return false;
  457. }
  458. if (!_convert_nir_to_dxil(stages_nir_shaders, r_stages_processed, r_dxil_blobs)) {
  459. free_nir_shaders();
  460. return false;
  461. }
  462. free_nir_shaders();
  463. return true;
  464. }
  465. bool RenderingShaderContainerD3D12::_generate_root_signature(BitField<RenderingDeviceCommons::ShaderStage> p_stages_processed) {
  466. // Root (push) constants.
  467. LocalVector<D3D12_ROOT_PARAMETER1> root_params;
  468. if (reflection_data_d3d12.dxil_push_constant_stages) {
  469. CD3DX12_ROOT_PARAMETER1 push_constant;
  470. push_constant.InitAsConstants(
  471. reflection_data.push_constant_size / sizeof(uint32_t),
  472. ROOT_CONSTANT_REGISTER,
  473. 0,
  474. stages_to_d3d12_visibility(reflection_data_d3d12.dxil_push_constant_stages));
  475. root_params.push_back(push_constant);
  476. }
  477. // NIR-DXIL runtime data.
  478. if (reflection_data_d3d12.nir_runtime_data_root_param_idx == 1) { // Set above to 1 when discovering runtime data is needed.
  479. DEV_ASSERT(!reflection_data.is_compute); // Could be supported if needed, but it's pointless as of now.
  480. reflection_data_d3d12.nir_runtime_data_root_param_idx = root_params.size();
  481. CD3DX12_ROOT_PARAMETER1 nir_runtime_data;
  482. nir_runtime_data.InitAsConstants(
  483. sizeof(dxil_spirv_vertex_runtime_data) / sizeof(uint32_t),
  484. RUNTIME_DATA_REGISTER,
  485. 0,
  486. D3D12_SHADER_VISIBILITY_VERTEX);
  487. root_params.push_back(nir_runtime_data);
  488. }
  489. // Descriptor tables (up to two per uniform set, for resources and/or samplers).
  490. // These have to stay around until serialization!
  491. struct TraceableDescriptorTable {
  492. uint32_t stages_mask = {};
  493. Vector<D3D12_DESCRIPTOR_RANGE1> ranges;
  494. uint32_t set = UINT_MAX;
  495. };
  496. uint32_t binding_start = 0;
  497. Vector<TraceableDescriptorTable> resource_tables_maps;
  498. Vector<TraceableDescriptorTable> sampler_tables_maps;
  499. for (uint32_t i = 0; i < reflection_binding_set_uniforms_count.size(); i++) {
  500. bool first_resource_in_set = true;
  501. bool first_sampler_in_set = true;
  502. uint32_t uniform_count = reflection_binding_set_uniforms_count[i];
  503. for (uint32_t j = 0; j < uniform_count; j++) {
  504. const ReflectionBindingData &uniform = reflection_binding_set_uniforms_data[binding_start + j];
  505. ReflectionBindingDataD3D12 &uniform_d3d12 = reflection_binding_set_uniforms_data_d3d12.ptrw()[binding_start + j];
  506. #ifdef DEV_ENABLED
  507. bool really_used = uniform_d3d12.dxil_stages != 0;
  508. bool anybody_home = (ResourceClass)(uniform_d3d12.resource_class) != RES_CLASS_INVALID || uniform_d3d12.has_sampler;
  509. DEV_ASSERT(anybody_home == really_used);
  510. #endif
  511. auto insert_range = [i](D3D12_DESCRIPTOR_RANGE_TYPE p_range_type,
  512. uint32_t p_num_descriptors,
  513. uint32_t p_dxil_register,
  514. uint32_t p_dxil_stages_mask,
  515. uint32_t &r_descriptor_offset,
  516. uint32_t &r_descriptor_count,
  517. bool &r_first_in_set,
  518. Vector<TraceableDescriptorTable> &r_tables) {
  519. r_descriptor_offset = r_descriptor_count;
  520. if (r_first_in_set) {
  521. r_tables.resize(r_tables.size() + 1);
  522. r_first_in_set = false;
  523. }
  524. TraceableDescriptorTable &table = r_tables.write[r_tables.size() - 1];
  525. DEV_ASSERT(table.set == UINT_MAX || table.set == i);
  526. table.stages_mask |= p_dxil_stages_mask;
  527. table.set = i;
  528. CD3DX12_DESCRIPTOR_RANGE1 range;
  529. // Due to the aliasing hack for SRV-UAV of different families,
  530. // we can be causing an unintended change of data (sometimes the validation layers catch it).
  531. D3D12_DESCRIPTOR_RANGE_FLAGS flags = D3D12_DESCRIPTOR_RANGE_FLAG_NONE;
  532. if (p_range_type == D3D12_DESCRIPTOR_RANGE_TYPE_SRV || p_range_type == D3D12_DESCRIPTOR_RANGE_TYPE_UAV) {
  533. flags = D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE;
  534. } else if (p_range_type == D3D12_DESCRIPTOR_RANGE_TYPE_CBV) {
  535. flags = D3D12_DESCRIPTOR_RANGE_FLAG_DATA_STATIC_WHILE_SET_AT_EXECUTE;
  536. }
  537. range.Init(p_range_type, p_num_descriptors, p_dxil_register, 0, flags, r_descriptor_offset);
  538. r_descriptor_count += p_num_descriptors;
  539. table.ranges.push_back(range);
  540. };
  541. D3D12_DESCRIPTOR_RANGE_TYPE range_type = (D3D12_DESCRIPTOR_RANGE_TYPE)UINT_MAX;
  542. bool has_sampler = false;
  543. uint32_t num_descriptors = 1;
  544. switch (uniform.type) {
  545. case RDC::UNIFORM_TYPE_SAMPLER: {
  546. has_sampler = true;
  547. num_descriptors = uniform.length;
  548. } break;
  549. case RDC::UNIFORM_TYPE_SAMPLER_WITH_TEXTURE: {
  550. range_type = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
  551. has_sampler = true;
  552. num_descriptors = MAX(1u, uniform.length);
  553. } break;
  554. case RDC::UNIFORM_TYPE_TEXTURE: {
  555. range_type = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
  556. num_descriptors = MAX(1u, uniform.length);
  557. } break;
  558. case RDC::UNIFORM_TYPE_IMAGE: {
  559. range_type = D3D12_DESCRIPTOR_RANGE_TYPE_UAV;
  560. num_descriptors = MAX(1u, uniform.length);
  561. } break;
  562. case RDC::UNIFORM_TYPE_TEXTURE_BUFFER: {
  563. CRASH_NOW_MSG("Unimplemented!");
  564. } break;
  565. case RDC::UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER: {
  566. CRASH_NOW_MSG("Unimplemented!");
  567. } break;
  568. case RDC::UNIFORM_TYPE_IMAGE_BUFFER: {
  569. CRASH_NOW_MSG("Unimplemented!");
  570. } break;
  571. case RDC::UNIFORM_TYPE_UNIFORM_BUFFER: {
  572. range_type = D3D12_DESCRIPTOR_RANGE_TYPE_CBV;
  573. } break;
  574. case RDC::UNIFORM_TYPE_UNIFORM_BUFFER_DYNAMIC: {
  575. range_type = D3D12_DESCRIPTOR_RANGE_TYPE_CBV;
  576. } break;
  577. case RDC::UNIFORM_TYPE_STORAGE_BUFFER: {
  578. range_type = uniform.writable ? D3D12_DESCRIPTOR_RANGE_TYPE_UAV : D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
  579. } break;
  580. case RDC::UNIFORM_TYPE_STORAGE_BUFFER_DYNAMIC: {
  581. range_type = uniform.writable ? D3D12_DESCRIPTOR_RANGE_TYPE_UAV : D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
  582. } break;
  583. case RDC::UNIFORM_TYPE_INPUT_ATTACHMENT: {
  584. range_type = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
  585. } break;
  586. default: {
  587. DEV_ASSERT(false);
  588. }
  589. }
  590. uint32_t dxil_register = i * GODOT_NIR_DESCRIPTOR_SET_MULTIPLIER + uniform.binding * GODOT_NIR_BINDING_MULTIPLIER;
  591. if (range_type != (D3D12_DESCRIPTOR_RANGE_TYPE)UINT_MAX) {
  592. // Dynamic buffers are converted to root descriptors to prevent copying descriptors during command recording.
  593. // Out of bounds accesses are not a concern because that's already undefined behavior on Vulkan.
  594. if (uniform.type == RDC::UNIFORM_TYPE_UNIFORM_BUFFER_DYNAMIC || uniform.type == RDC::UNIFORM_TYPE_STORAGE_BUFFER_DYNAMIC) {
  595. CD3DX12_ROOT_PARAMETER1 root_param = {};
  596. D3D12_SHADER_VISIBILITY visibility = stages_to_d3d12_visibility(uniform.stages);
  597. switch (range_type) {
  598. case D3D12_DESCRIPTOR_RANGE_TYPE_CBV: {
  599. root_param.InitAsConstantBufferView(dxil_register, 0, D3D12_ROOT_DESCRIPTOR_FLAG_DATA_STATIC_WHILE_SET_AT_EXECUTE, visibility);
  600. } break;
  601. case D3D12_DESCRIPTOR_RANGE_TYPE_SRV: {
  602. root_param.InitAsShaderResourceView(dxil_register, 0, D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE, visibility);
  603. } break;
  604. case D3D12_DESCRIPTOR_RANGE_TYPE_UAV: {
  605. root_param.InitAsUnorderedAccessView(dxil_register, 0, D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE, visibility);
  606. } break;
  607. default: {
  608. DEV_ASSERT(false && "Unrecognized range type.");
  609. } break;
  610. }
  611. uniform_d3d12.root_param_idx = root_params.size();
  612. root_params.push_back(root_param);
  613. } else {
  614. insert_range(
  615. range_type,
  616. num_descriptors,
  617. dxil_register,
  618. uniform.stages,
  619. uniform_d3d12.resource_descriptor_offset,
  620. reflection_binding_set_data_d3d12.ptrw()[i].resource_descriptor_count,
  621. first_resource_in_set,
  622. resource_tables_maps);
  623. }
  624. }
  625. if (has_sampler) {
  626. insert_range(
  627. D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER,
  628. num_descriptors,
  629. dxil_register,
  630. uniform.stages,
  631. uniform_d3d12.sampler_descriptor_offset,
  632. reflection_binding_set_data_d3d12.ptrw()[i].sampler_descriptor_count,
  633. first_sampler_in_set,
  634. sampler_tables_maps);
  635. }
  636. }
  637. binding_start += uniform_count;
  638. }
  639. for (const TraceableDescriptorTable &table : resource_tables_maps) {
  640. CD3DX12_ROOT_PARAMETER1 root_table = {};
  641. root_table.InitAsDescriptorTable(table.ranges.size(), table.ranges.ptr(), stages_to_d3d12_visibility(table.stages_mask));
  642. reflection_binding_set_data_d3d12.ptrw()[table.set].resource_root_param_idx = root_params.size();
  643. root_params.push_back(root_table);
  644. }
  645. for (const TraceableDescriptorTable &table : sampler_tables_maps) {
  646. CD3DX12_ROOT_PARAMETER1 root_table = {};
  647. root_table.InitAsDescriptorTable(table.ranges.size(), table.ranges.ptr(), stages_to_d3d12_visibility(table.stages_mask));
  648. reflection_binding_set_data_d3d12.ptrw()[table.set].sampler_root_param_idx = root_params.size();
  649. root_params.push_back(root_table);
  650. }
  651. CD3DX12_VERSIONED_ROOT_SIGNATURE_DESC root_sig_desc = {};
  652. D3D12_ROOT_SIGNATURE_FLAGS root_sig_flags =
  653. D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS |
  654. D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS |
  655. D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS |
  656. D3D12_ROOT_SIGNATURE_FLAG_DENY_AMPLIFICATION_SHADER_ROOT_ACCESS |
  657. D3D12_ROOT_SIGNATURE_FLAG_DENY_MESH_SHADER_ROOT_ACCESS;
  658. if (!p_stages_processed.has_flag(RenderingDeviceCommons::SHADER_STAGE_VERTEX_BIT)) {
  659. root_sig_flags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_VERTEX_SHADER_ROOT_ACCESS;
  660. }
  661. if (!p_stages_processed.has_flag(RenderingDeviceCommons::SHADER_STAGE_FRAGMENT_BIT)) {
  662. root_sig_flags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS;
  663. }
  664. if (reflection_data.vertex_input_mask) {
  665. root_sig_flags |= D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;
  666. }
  667. root_sig_desc.Init_1_1(root_params.size(), root_params.ptr(), 0, nullptr, root_sig_flags);
  668. // Create and store the root signature and its CRC32.
  669. ID3DBlob *error_blob = nullptr;
  670. ID3DBlob *root_sig_blob = nullptr;
  671. HRESULT res = D3DX12SerializeVersionedRootSignature(HMODULE(lib_d3d12), &root_sig_desc, D3D_ROOT_SIGNATURE_VERSION_1_1, &root_sig_blob, &error_blob);
  672. if (SUCCEEDED(res)) {
  673. root_signature_bytes.resize(root_sig_blob->GetBufferSize());
  674. memcpy(root_signature_bytes.ptrw(), root_sig_blob->GetBufferPointer(), root_sig_blob->GetBufferSize());
  675. root_signature_crc = crc32(0, nullptr, 0);
  676. root_signature_crc = crc32(root_signature_crc, (const Bytef *)root_sig_blob->GetBufferPointer(), root_sig_blob->GetBufferSize());
  677. return true;
  678. } else {
  679. if (root_sig_blob != nullptr) {
  680. root_sig_blob->Release();
  681. }
  682. String error_string;
  683. if (error_blob != nullptr) {
  684. error_string = vformat("Serialization of root signature failed with error 0x%08ux and the following message:\n%s", uint32_t(res), String::ascii(Span((char *)error_blob->GetBufferPointer(), error_blob->GetBufferSize())));
  685. error_blob->Release();
  686. } else {
  687. error_string = vformat("Serialization of root signature failed with error 0x%08ux", uint32_t(res));
  688. }
  689. ERR_FAIL_V_MSG(false, error_string);
  690. }
  691. }
  692. void RenderingShaderContainerD3D12::_nir_report_resource(uint32_t p_register, uint32_t p_space, uint32_t p_dxil_type, void *p_data) {
  693. const GodotNirCallbackUserData &user_data = *(GodotNirCallbackUserData *)p_data;
  694. // Types based on Mesa's dxil_container.h.
  695. static const uint32_t DXIL_RES_SAMPLER = 1;
  696. static const ResourceClass DXIL_TYPE_TO_CLASS[] = {
  697. RES_CLASS_INVALID, // DXIL_RES_INVALID
  698. RES_CLASS_INVALID, // DXIL_RES_SAMPLER
  699. RES_CLASS_CBV, // DXIL_RES_CBV
  700. RES_CLASS_SRV, // DXIL_RES_SRV_TYPED
  701. RES_CLASS_SRV, // DXIL_RES_SRV_RAW
  702. RES_CLASS_SRV, // DXIL_RES_SRV_STRUCTURED
  703. RES_CLASS_UAV, // DXIL_RES_UAV_TYPED
  704. RES_CLASS_UAV, // DXIL_RES_UAV_RAW
  705. RES_CLASS_UAV, // DXIL_RES_UAV_STRUCTURED
  706. RES_CLASS_INVALID, // DXIL_RES_UAV_STRUCTURED_WITH_COUNTER
  707. };
  708. DEV_ASSERT(p_dxil_type < ARRAY_SIZE(DXIL_TYPE_TO_CLASS));
  709. ResourceClass resource_class = DXIL_TYPE_TO_CLASS[p_dxil_type];
  710. if (p_register == ROOT_CONSTANT_REGISTER && p_space == 0) {
  711. DEV_ASSERT(resource_class == RES_CLASS_CBV);
  712. user_data.container->reflection_data_d3d12.dxil_push_constant_stages |= (1 << user_data.stage);
  713. } else if (p_register == RUNTIME_DATA_REGISTER && p_space == 0) {
  714. DEV_ASSERT(resource_class == RES_CLASS_CBV);
  715. user_data.container->reflection_data_d3d12.nir_runtime_data_root_param_idx = 1; // Temporary, to be determined later.
  716. } else {
  717. DEV_ASSERT(p_space == 0);
  718. uint32_t set = p_register / GODOT_NIR_DESCRIPTOR_SET_MULTIPLIER;
  719. uint32_t binding = (p_register % GODOT_NIR_DESCRIPTOR_SET_MULTIPLIER) / GODOT_NIR_BINDING_MULTIPLIER;
  720. DEV_ASSERT(set < (uint32_t)user_data.container->reflection_binding_set_uniforms_count.size());
  721. uint32_t binding_start = 0;
  722. for (uint32_t i = 0; i < set; i++) {
  723. binding_start += user_data.container->reflection_binding_set_uniforms_count[i];
  724. }
  725. [[maybe_unused]] bool found = false;
  726. for (uint32_t i = 0; i < user_data.container->reflection_binding_set_uniforms_count[set]; i++) {
  727. const ReflectionBindingData &uniform = user_data.container->reflection_binding_set_uniforms_data[binding_start + i];
  728. ReflectionBindingDataD3D12 &uniform_d3d12 = user_data.container->reflection_binding_set_uniforms_data_d3d12.ptrw()[binding_start + i];
  729. if (uniform.binding != binding) {
  730. continue;
  731. }
  732. uniform_d3d12.dxil_stages |= (1 << user_data.stage);
  733. if (resource_class != RES_CLASS_INVALID) {
  734. DEV_ASSERT(uniform_d3d12.resource_class == (uint32_t)RES_CLASS_INVALID || uniform_d3d12.resource_class == (uint32_t)resource_class);
  735. uniform_d3d12.resource_class = resource_class;
  736. } else if (p_dxil_type == DXIL_RES_SAMPLER) {
  737. uniform_d3d12.has_sampler = (uint32_t)true;
  738. } else {
  739. DEV_ASSERT(false && "Unknown resource class.");
  740. }
  741. found = true;
  742. }
  743. DEV_ASSERT(found);
  744. }
  745. }
  746. void RenderingShaderContainerD3D12::_nir_report_sc_bit_offset(uint32_t p_sc_id, uint64_t p_bit_offset, void *p_data) {
  747. const GodotNirCallbackUserData &user_data = *(GodotNirCallbackUserData *)p_data;
  748. [[maybe_unused]] bool found = false;
  749. for (int64_t i = 0; i < user_data.container->reflection_specialization_data.size(); i++) {
  750. const ReflectionSpecializationData &sc = user_data.container->reflection_specialization_data[i];
  751. ReflectionSpecializationDataD3D12 &sc_d3d12 = user_data.container->reflection_specialization_data_d3d12.ptrw()[i];
  752. if (sc.constant_id != p_sc_id) {
  753. continue;
  754. }
  755. uint32_t offset_idx = SHADER_STAGES_BIT_OFFSET_INDICES[user_data.stage];
  756. DEV_ASSERT(sc_d3d12.stages_bit_offsets[offset_idx] == 0);
  757. sc_d3d12.stages_bit_offsets[offset_idx] = p_bit_offset;
  758. found = true;
  759. break;
  760. }
  761. DEV_ASSERT(found);
  762. }
  763. void RenderingShaderContainerD3D12::_nir_report_bitcode_bit_offset(uint64_t p_bit_offset, void *p_data) {
  764. DEV_ASSERT(p_bit_offset % 8 == 0);
  765. const GodotNirCallbackUserData &user_data = *(GodotNirCallbackUserData *)p_data;
  766. uint32_t offset_idx = SHADER_STAGES_BIT_OFFSET_INDICES[user_data.stage];
  767. for (int64_t i = 0; i < user_data.container->reflection_specialization_data.size(); i++) {
  768. ReflectionSpecializationDataD3D12 &sc_d3d12 = user_data.container->reflection_specialization_data_d3d12.ptrw()[i];
  769. if (sc_d3d12.stages_bit_offsets[offset_idx] == 0) {
  770. // This SC has been optimized out from this stage.
  771. continue;
  772. }
  773. sc_d3d12.stages_bit_offsets[offset_idx] += p_bit_offset;
  774. }
  775. }
  776. #endif
  777. void RenderingShaderContainerD3D12::_set_from_shader_reflection_post(const ReflectShader &p_shader) {
  778. reflection_binding_set_data_d3d12.resize(reflection_binding_set_uniforms_count.size());
  779. reflection_binding_set_uniforms_data_d3d12.resize(reflection_binding_set_uniforms_data.size());
  780. reflection_specialization_data_d3d12.resize(reflection_specialization_data.size());
  781. // Sort bindings inside each uniform set. This guarantees the root signature will be generated in the correct order.
  782. SortArray<ReflectionBindingData> sorter;
  783. uint32_t binding_start = 0;
  784. for (uint32_t i = 0; i < reflection_binding_set_uniforms_count.size(); i++) {
  785. uint32_t uniform_count = reflection_binding_set_uniforms_count[i];
  786. if (uniform_count > 0) {
  787. sorter.sort(&reflection_binding_set_uniforms_data.ptrw()[binding_start], uniform_count);
  788. binding_start += uniform_count;
  789. }
  790. }
  791. }
  792. bool RenderingShaderContainerD3D12::_set_code_from_spirv(const ReflectShader &p_shader) {
  793. #if NIR_ENABLED
  794. const LocalVector<ReflectShaderStage> &p_spirv = p_shader.shader_stages;
  795. reflection_data_d3d12.nir_runtime_data_root_param_idx = UINT32_MAX;
  796. for (int64_t i = 0; i < reflection_specialization_data.size(); i++) {
  797. DEV_ASSERT(reflection_specialization_data[i].constant_id < (sizeof(reflection_data_d3d12.spirv_specialization_constants_ids_mask) * 8) && "Constant IDs with values above 31 are not supported.");
  798. reflection_data_d3d12.spirv_specialization_constants_ids_mask |= (1 << reflection_specialization_data[i].constant_id);
  799. }
  800. // Translate SPIR-V shaders to DXIL, and collect shader info from the new representation.
  801. HashMap<RenderingDeviceCommons::ShaderStage, Vector<uint8_t>> dxil_blobs;
  802. Vector<RenderingDeviceCommons::ShaderStage> stages;
  803. BitField<RenderingDeviceCommons::ShaderStage> stages_processed = {};
  804. if (!_convert_spirv_to_dxil(p_spirv, dxil_blobs, stages, stages_processed)) {
  805. return false;
  806. }
  807. // Patch with default values of specialization constants.
  808. DEV_ASSERT(reflection_specialization_data.size() == reflection_specialization_data_d3d12.size());
  809. for (int32_t i = 0; i < reflection_specialization_data.size(); i++) {
  810. const ReflectionSpecializationData &sc = reflection_specialization_data[i];
  811. const ReflectionSpecializationDataD3D12 &sc_d3d12 = reflection_specialization_data_d3d12[i];
  812. RenderingDXIL::patch_specialization_constant((RenderingDeviceCommons::PipelineSpecializationConstantType)(sc.type), &sc.int_value, sc_d3d12.stages_bit_offsets, dxil_blobs, true);
  813. }
  814. // Sign.
  815. uint32_t shader_index = 0;
  816. for (KeyValue<RenderingDeviceCommons::ShaderStage, Vector<uint8_t>> &E : dxil_blobs) {
  817. RenderingDXIL::sign_bytecode(E.key, E.value);
  818. }
  819. // Store compressed DXIL blobs as the shaders.
  820. shaders.resize(p_spirv.size());
  821. for (int64_t i = 0; i < shaders.size(); i++) {
  822. const PackedByteArray &dxil_bytes = dxil_blobs[stages[i]];
  823. RenderingShaderContainer::Shader &shader = shaders.ptrw()[i];
  824. uint32_t compressed_size = 0;
  825. shader.shader_stage = stages[i];
  826. shader.code_decompressed_size = dxil_bytes.size();
  827. shader.code_compressed_bytes.resize(dxil_bytes.size());
  828. bool compressed = compress_code(dxil_bytes.ptr(), dxil_bytes.size(), shader.code_compressed_bytes.ptrw(), &compressed_size, &shader.code_compression_flags);
  829. ERR_FAIL_COND_V_MSG(!compressed, false, vformat("Failed to compress native code to native for SPIR-V #%d.", shader_index));
  830. shader.code_compressed_bytes.resize(compressed_size);
  831. }
  832. if (!_generate_root_signature(stages_processed)) {
  833. return false;
  834. }
  835. return true;
  836. #else
  837. ERR_FAIL_V_MSG(false, "Shader compilation is not supported at runtime without NIR.");
  838. #endif
  839. }
  840. RenderingShaderContainerD3D12::RenderingShaderContainerD3D12() {
  841. // Default empty constructor.
  842. }
  843. RenderingShaderContainerD3D12::RenderingShaderContainerD3D12(void *p_lib_d3d12) {
  844. lib_d3d12 = p_lib_d3d12;
  845. }
  846. RenderingShaderContainerD3D12::ShaderReflectionD3D12 RenderingShaderContainerD3D12::get_shader_reflection_d3d12() const {
  847. ShaderReflectionD3D12 reflection;
  848. reflection.spirv_specialization_constants_ids_mask = reflection_data_d3d12.spirv_specialization_constants_ids_mask;
  849. reflection.dxil_push_constant_stages = reflection_data_d3d12.dxil_push_constant_stages;
  850. reflection.nir_runtime_data_root_param_idx = reflection_data_d3d12.nir_runtime_data_root_param_idx;
  851. reflection.reflection_binding_sets_d3d12 = reflection_binding_set_data_d3d12;
  852. reflection.reflection_specialization_data_d3d12 = reflection_specialization_data_d3d12;
  853. reflection.root_signature_bytes = root_signature_bytes;
  854. reflection.root_signature_crc = root_signature_crc;
  855. // Transform data vector into a vector of vectors that's easier to user.
  856. uint32_t uniform_index = 0;
  857. reflection.reflection_binding_set_uniforms_d3d12.resize(reflection_binding_set_uniforms_count.size());
  858. for (int64_t i = 0; i < reflection.reflection_binding_set_uniforms_d3d12.size(); i++) {
  859. Vector<ReflectionBindingDataD3D12> &uniforms = reflection.reflection_binding_set_uniforms_d3d12.ptrw()[i];
  860. uniforms.resize(reflection_binding_set_uniforms_count[i]);
  861. for (int64_t j = 0; j < uniforms.size(); j++) {
  862. uniforms.ptrw()[j] = reflection_binding_set_uniforms_data_d3d12[uniform_index];
  863. uniform_index++;
  864. }
  865. }
  866. return reflection;
  867. }
  868. // RenderingShaderContainerFormatD3D12
  869. void RenderingShaderContainerFormatD3D12::set_lib_d3d12(void *p_lib_d3d12) {
  870. lib_d3d12 = p_lib_d3d12;
  871. }
  872. Ref<RenderingShaderContainer> RenderingShaderContainerFormatD3D12::create_container() const {
  873. return memnew(RenderingShaderContainerD3D12(lib_d3d12));
  874. }
  875. RenderingDeviceCommons::ShaderLanguageVersion RenderingShaderContainerFormatD3D12::get_shader_language_version() const {
  876. // NIR-DXIL is Vulkan 1.1-conformant.
  877. return SHADER_LANGUAGE_VULKAN_VERSION_1_1;
  878. }
  879. RenderingDeviceCommons::ShaderSpirvVersion RenderingShaderContainerFormatD3D12::get_shader_spirv_version() const {
  880. // The SPIR-V part of Mesa supports 1.6, but:
  881. // - SPIRV-Reflect won't be able to parse the compute workgroup size.
  882. // - We want to play it safe with NIR-DXIL.
  883. return SHADER_SPIRV_VERSION_1_5;
  884. }
  885. RenderingShaderContainerFormatD3D12::RenderingShaderContainerFormatD3D12() {}
  886. RenderingShaderContainerFormatD3D12::~RenderingShaderContainerFormatD3D12() {}