rendering_shader_container_d3d12.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  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. #ifndef _MSC_VER
  35. // Match current version used by MinGW, MSVC and Direct3D 12 headers use 500.
  36. #define __REQUIRED_RPCNDR_H_VERSION__ 475
  37. #endif
  38. #include <d3dx12.h>
  39. #include <dxgi1_6.h>
  40. #define D3D12MA_D3D12_HEADERS_ALREADY_INCLUDED
  41. #include <D3D12MemAlloc.h>
  42. #include <wrl/client.h>
  43. #if defined(_MSC_VER) && defined(MemoryBarrier)
  44. // Annoying define from winnt.h. Reintroduced by some of the headers above.
  45. #undef MemoryBarrier
  46. #endif
  47. GODOT_GCC_WARNING_PUSH
  48. GODOT_GCC_WARNING_IGNORE("-Wimplicit-fallthrough")
  49. GODOT_GCC_WARNING_IGNORE("-Wlogical-not-parentheses")
  50. GODOT_GCC_WARNING_IGNORE("-Wmissing-field-initializers")
  51. GODOT_GCC_WARNING_IGNORE("-Wnon-virtual-dtor")
  52. GODOT_GCC_WARNING_IGNORE("-Wshadow")
  53. GODOT_GCC_WARNING_IGNORE("-Wswitch")
  54. GODOT_CLANG_WARNING_PUSH
  55. GODOT_CLANG_WARNING_IGNORE("-Wimplicit-fallthrough")
  56. GODOT_CLANG_WARNING_IGNORE("-Wlogical-not-parentheses")
  57. GODOT_CLANG_WARNING_IGNORE("-Wmissing-field-initializers")
  58. GODOT_CLANG_WARNING_IGNORE("-Wnon-virtual-dtor")
  59. GODOT_CLANG_WARNING_IGNORE("-Wstring-plus-int")
  60. GODOT_CLANG_WARNING_IGNORE("-Wswitch")
  61. GODOT_MSVC_WARNING_PUSH
  62. GODOT_MSVC_WARNING_IGNORE(4200) // "nonstandard extension used: zero-sized array in struct/union".
  63. GODOT_MSVC_WARNING_IGNORE(4806) // "'&': unsafe operation: no value of type 'bool' promoted to type 'uint32_t' can equal the given constant".
  64. #include <nir_spirv.h>
  65. #include <nir_to_dxil.h>
  66. #include <spirv_to_dxil.h>
  67. extern "C" {
  68. #include <dxil_spirv_nir.h>
  69. }
  70. GODOT_GCC_WARNING_POP
  71. GODOT_CLANG_WARNING_POP
  72. GODOT_MSVC_WARNING_POP
  73. static D3D12_SHADER_VISIBILITY stages_to_d3d12_visibility(uint32_t p_stages_mask) {
  74. switch (p_stages_mask) {
  75. case RenderingDeviceCommons::SHADER_STAGE_VERTEX_BIT:
  76. return D3D12_SHADER_VISIBILITY_VERTEX;
  77. case RenderingDeviceCommons::SHADER_STAGE_FRAGMENT_BIT:
  78. return D3D12_SHADER_VISIBILITY_PIXEL;
  79. default:
  80. return D3D12_SHADER_VISIBILITY_ALL;
  81. }
  82. }
  83. uint32_t RenderingDXIL::patch_specialization_constant(
  84. RenderingDeviceCommons::PipelineSpecializationConstantType p_type,
  85. const void *p_value,
  86. const uint64_t (&p_stages_bit_offsets)[D3D12_BITCODE_OFFSETS_NUM_STAGES],
  87. HashMap<RenderingDeviceCommons::ShaderStage, Vector<uint8_t>> &r_stages_bytecodes,
  88. bool p_is_first_patch) {
  89. uint32_t patch_val = 0;
  90. switch (p_type) {
  91. case RenderingDeviceCommons::PIPELINE_SPECIALIZATION_CONSTANT_TYPE_INT: {
  92. uint32_t int_value = *((const int *)p_value);
  93. ERR_FAIL_COND_V(int_value & (1 << 31), 0);
  94. patch_val = int_value;
  95. } break;
  96. case RenderingDeviceCommons::PIPELINE_SPECIALIZATION_CONSTANT_TYPE_BOOL: {
  97. bool bool_value = *((const bool *)p_value);
  98. patch_val = (uint32_t)bool_value;
  99. } break;
  100. case RenderingDeviceCommons::PIPELINE_SPECIALIZATION_CONSTANT_TYPE_FLOAT: {
  101. uint32_t int_value = *((const int *)p_value);
  102. ERR_FAIL_COND_V(int_value & (1 << 31), 0);
  103. patch_val = (int_value >> 1);
  104. } break;
  105. }
  106. // For VBR encoding to encode the number of bits we expect (32), we need to set the MSB unconditionally.
  107. // However, signed VBR moves the MSB to the LSB, so setting the MSB to 1 wouldn't help. Therefore,
  108. // the bit we set to 1 is the one at index 30.
  109. patch_val |= (1 << 30);
  110. patch_val <<= 1; // What signed VBR does.
  111. auto tamper_bits = [](uint8_t *p_start, uint64_t p_bit_offset, uint64_t p_tb_value) -> uint64_t {
  112. uint64_t original = 0;
  113. uint32_t curr_input_byte = p_bit_offset / 8;
  114. uint8_t curr_input_bit = p_bit_offset % 8;
  115. auto get_curr_input_bit = [&]() -> bool {
  116. return ((p_start[curr_input_byte] >> curr_input_bit) & 1);
  117. };
  118. auto move_to_next_input_bit = [&]() {
  119. if (curr_input_bit == 7) {
  120. curr_input_bit = 0;
  121. curr_input_byte++;
  122. } else {
  123. curr_input_bit++;
  124. }
  125. };
  126. auto tamper_input_bit = [&](bool p_new_bit) {
  127. p_start[curr_input_byte] &= ~((uint8_t)1 << curr_input_bit);
  128. if (p_new_bit) {
  129. p_start[curr_input_byte] |= (uint8_t)1 << curr_input_bit;
  130. }
  131. };
  132. uint8_t value_bit_idx = 0;
  133. for (uint32_t i = 0; i < 5; i++) { // 32 bits take 5 full bytes in VBR.
  134. for (uint32_t j = 0; j < 7; j++) {
  135. bool input_bit = get_curr_input_bit();
  136. original |= (uint64_t)(input_bit ? 1 : 0) << value_bit_idx;
  137. tamper_input_bit((p_tb_value >> value_bit_idx) & 1);
  138. move_to_next_input_bit();
  139. value_bit_idx++;
  140. }
  141. #ifdef DEV_ENABLED
  142. bool input_bit = get_curr_input_bit();
  143. DEV_ASSERT((i < 4 && input_bit) || (i == 4 && !input_bit));
  144. #endif
  145. move_to_next_input_bit();
  146. }
  147. return original;
  148. };
  149. uint32_t stages_patched_mask = 0;
  150. for (int stage = 0; stage < RenderingDeviceCommons::SHADER_STAGE_MAX; stage++) {
  151. if (!r_stages_bytecodes.has((RenderingDeviceCommons::ShaderStage)stage)) {
  152. continue;
  153. }
  154. uint64_t offset = p_stages_bit_offsets[RenderingShaderContainerD3D12::SHADER_STAGES_BIT_OFFSET_INDICES[stage]];
  155. if (offset == 0) {
  156. // This constant does not appear at this stage.
  157. continue;
  158. }
  159. Vector<uint8_t> &bytecode = r_stages_bytecodes[(RenderingDeviceCommons::ShaderStage)stage];
  160. #ifdef DEV_ENABLED
  161. uint64_t orig_patch_val = tamper_bits(bytecode.ptrw(), offset, patch_val);
  162. // Checking against the value the NIR patch should have set.
  163. DEV_ASSERT(!p_is_first_patch || ((orig_patch_val >> 1) & GODOT_NIR_SC_SENTINEL_MAGIC_MASK) == GODOT_NIR_SC_SENTINEL_MAGIC);
  164. uint64_t readback_patch_val = tamper_bits(bytecode.ptrw(), offset, patch_val);
  165. DEV_ASSERT(readback_patch_val == patch_val);
  166. #else
  167. tamper_bits(bytecode.ptrw(), offset, patch_val);
  168. #endif
  169. stages_patched_mask |= (1 << stage);
  170. }
  171. return stages_patched_mask;
  172. }
  173. void RenderingDXIL::sign_bytecode(RenderingDeviceCommons::ShaderStage p_stage, Vector<uint8_t> &r_dxil_blob) {
  174. uint8_t *w = r_dxil_blob.ptrw();
  175. compute_dxil_hash(w + 20, r_dxil_blob.size() - 20, w + 4);
  176. }
  177. // RenderingShaderContainerD3D12
  178. uint32_t RenderingShaderContainerD3D12::_format() const {
  179. return 0x43443344;
  180. }
  181. uint32_t RenderingShaderContainerD3D12::_format_version() const {
  182. return FORMAT_VERSION;
  183. }
  184. uint32_t RenderingShaderContainerD3D12::_from_bytes_reflection_extra_data(const uint8_t *p_bytes) {
  185. reflection_data_d3d12 = *(const ReflectionDataD3D12 *)(p_bytes);
  186. return sizeof(ReflectionDataD3D12);
  187. }
  188. uint32_t RenderingShaderContainerD3D12::_from_bytes_reflection_binding_uniform_extra_data_start(const uint8_t *p_bytes) {
  189. reflection_binding_set_uniforms_data_d3d12.resize(reflection_binding_set_uniforms_data.size());
  190. return 0;
  191. }
  192. uint32_t RenderingShaderContainerD3D12::_from_bytes_reflection_binding_uniform_extra_data(const uint8_t *p_bytes, uint32_t p_index) {
  193. reflection_binding_set_uniforms_data_d3d12.ptrw()[p_index] = *(const ReflectionBindingDataD3D12 *)(p_bytes);
  194. return sizeof(ReflectionBindingDataD3D12);
  195. }
  196. uint32_t RenderingShaderContainerD3D12::_from_bytes_reflection_specialization_extra_data_start(const uint8_t *p_bytes) {
  197. reflection_specialization_data_d3d12.resize(reflection_specialization_data.size());
  198. return 0;
  199. }
  200. uint32_t RenderingShaderContainerD3D12::_from_bytes_reflection_specialization_extra_data(const uint8_t *p_bytes, uint32_t p_index) {
  201. reflection_specialization_data_d3d12.ptrw()[p_index] = *(const ReflectionSpecializationDataD3D12 *)(p_bytes);
  202. return sizeof(ReflectionSpecializationDataD3D12);
  203. }
  204. uint32_t RenderingShaderContainerD3D12::_from_bytes_footer_extra_data(const uint8_t *p_bytes) {
  205. ContainerFooterD3D12 footer = *(const ContainerFooterD3D12 *)(p_bytes);
  206. root_signature_crc = footer.root_signature_crc;
  207. root_signature_bytes.resize(footer.root_signature_length);
  208. memcpy(root_signature_bytes.ptrw(), p_bytes + sizeof(ContainerFooterD3D12), root_signature_bytes.size());
  209. return sizeof(ContainerFooterD3D12) + footer.root_signature_length;
  210. }
  211. uint32_t RenderingShaderContainerD3D12::_to_bytes_reflection_extra_data(uint8_t *p_bytes) const {
  212. if (p_bytes != nullptr) {
  213. *(ReflectionDataD3D12 *)(p_bytes) = reflection_data_d3d12;
  214. }
  215. return sizeof(ReflectionDataD3D12);
  216. }
  217. uint32_t RenderingShaderContainerD3D12::_to_bytes_reflection_binding_uniform_extra_data(uint8_t *p_bytes, uint32_t p_index) const {
  218. if (p_bytes != nullptr) {
  219. *(ReflectionBindingDataD3D12 *)(p_bytes) = reflection_binding_set_uniforms_data_d3d12[p_index];
  220. }
  221. return sizeof(ReflectionBindingDataD3D12);
  222. }
  223. uint32_t RenderingShaderContainerD3D12::_to_bytes_reflection_specialization_extra_data(uint8_t *p_bytes, uint32_t p_index) const {
  224. if (p_bytes != nullptr) {
  225. *(ReflectionSpecializationDataD3D12 *)(p_bytes) = reflection_specialization_data_d3d12[p_index];
  226. }
  227. return sizeof(ReflectionSpecializationDataD3D12);
  228. }
  229. uint32_t RenderingShaderContainerD3D12::_to_bytes_footer_extra_data(uint8_t *p_bytes) const {
  230. if (p_bytes != nullptr) {
  231. ContainerFooterD3D12 &footer = *(ContainerFooterD3D12 *)(p_bytes);
  232. footer.root_signature_length = root_signature_bytes.size();
  233. footer.root_signature_crc = root_signature_crc;
  234. memcpy(p_bytes + sizeof(ContainerFooterD3D12), root_signature_bytes.ptr(), root_signature_bytes.size());
  235. }
  236. return sizeof(ContainerFooterD3D12) + root_signature_bytes.size();
  237. }
  238. #if NIR_ENABLED
  239. bool RenderingShaderContainerD3D12::_convert_spirv_to_nir(const Vector<RenderingDeviceCommons::ShaderStageSPIRVData> &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) {
  240. r_stages_processed.clear();
  241. dxil_spirv_runtime_conf dxil_runtime_conf = {};
  242. dxil_runtime_conf.runtime_data_cbv.base_shader_register = RUNTIME_DATA_REGISTER;
  243. dxil_runtime_conf.push_constant_cbv.base_shader_register = ROOT_CONSTANT_REGISTER;
  244. dxil_runtime_conf.zero_based_vertex_instance_id = true;
  245. dxil_runtime_conf.zero_based_compute_workgroup_id = true;
  246. dxil_runtime_conf.declared_read_only_images_as_srvs = true;
  247. // Making this explicit to let maintainers know that in practice this didn't improve performance,
  248. // probably because data generated by one shader and consumed by another one forces the resource
  249. // to transition from UAV to SRV, and back, instead of being an UAV all the time.
  250. // In case someone wants to try, care must be taken so in case of incompatible bindings across stages
  251. // happen as a result, all the stages are re-translated. That can happen if, for instance, a stage only
  252. // uses an allegedly writable resource only for reading but the next stage doesn't.
  253. dxil_runtime_conf.inferred_read_only_images_as_srvs = false;
  254. // Translate SPIR-V to NIR.
  255. for (int64_t i = 0; i < p_spirv.size(); i++) {
  256. RenderingDeviceCommons::ShaderStage stage = p_spirv[i].shader_stage;
  257. RenderingDeviceCommons::ShaderStage stage_flag = (RenderingDeviceCommons::ShaderStage)(1 << stage);
  258. r_stages.push_back(stage);
  259. r_stages_processed.set_flag(stage_flag);
  260. const char *entry_point = "main";
  261. static const gl_shader_stage SPIRV_TO_MESA_STAGES[RenderingDeviceCommons::SHADER_STAGE_MAX] = {
  262. MESA_SHADER_VERTEX, // SHADER_STAGE_VERTEX
  263. MESA_SHADER_FRAGMENT, // SHADER_STAGE_FRAGMENT
  264. MESA_SHADER_TESS_CTRL, // SHADER_STAGE_TESSELATION_CONTROL
  265. MESA_SHADER_TESS_EVAL, // SHADER_STAGE_TESSELATION_EVALUATION
  266. MESA_SHADER_COMPUTE, // SHADER_STAGE_COMPUTE
  267. };
  268. nir_shader *shader = spirv_to_nir(
  269. (const uint32_t *)(p_spirv[i].spirv.ptr()),
  270. p_spirv[i].spirv.size() / sizeof(uint32_t),
  271. nullptr,
  272. 0,
  273. SPIRV_TO_MESA_STAGES[stage],
  274. entry_point,
  275. dxil_spirv_nir_get_spirv_options(),
  276. p_compiler_options);
  277. ERR_FAIL_NULL_V_MSG(shader, false, "Shader translation (step 1) at stage " + String(RenderingDeviceCommons::SHADER_STAGE_NAMES[stage]) + " failed.");
  278. #ifdef DEV_ENABLED
  279. nir_validate_shader(shader, "Validate before feeding NIR to the DXIL compiler");
  280. #endif
  281. if (stage == RenderingDeviceCommons::SHADER_STAGE_VERTEX) {
  282. dxil_runtime_conf.yz_flip.y_mask = 0xffff;
  283. dxil_runtime_conf.yz_flip.mode = DXIL_SPIRV_Y_FLIP_UNCONDITIONAL;
  284. } else {
  285. dxil_runtime_conf.yz_flip.y_mask = 0;
  286. dxil_runtime_conf.yz_flip.mode = DXIL_SPIRV_YZ_FLIP_NONE;
  287. }
  288. dxil_spirv_nir_prep(shader);
  289. bool requires_runtime_data = false;
  290. dxil_spirv_nir_passes(shader, &dxil_runtime_conf, &requires_runtime_data);
  291. r_stages_nir_shaders[stage] = shader;
  292. }
  293. // Link NIR shaders.
  294. for (int i = RenderingDeviceCommons::SHADER_STAGE_MAX - 1; i >= 0; i--) {
  295. if (!r_stages_nir_shaders.has(i)) {
  296. continue;
  297. }
  298. nir_shader *shader = r_stages_nir_shaders[i];
  299. nir_shader *prev_shader = nullptr;
  300. for (int j = i - 1; j >= 0; j--) {
  301. if (r_stages_nir_shaders.has(j)) {
  302. prev_shader = r_stages_nir_shaders[j];
  303. break;
  304. }
  305. }
  306. // There is a bug in the Direct3D runtime during creation of a PSO with view instancing. If a fragment
  307. // shader uses front/back face detection (SV_IsFrontFace), its signature must include the pixel position
  308. // builtin variable (SV_Position), otherwise an Internal Runtime error will occur.
  309. if (i == RenderingDeviceCommons::SHADER_STAGE_FRAGMENT) {
  310. const bool use_front_face =
  311. nir_find_variable_with_location(shader, nir_var_shader_in, VARYING_SLOT_FACE) ||
  312. (shader->info.inputs_read & VARYING_BIT_FACE) ||
  313. nir_find_variable_with_location(shader, nir_var_system_value, SYSTEM_VALUE_FRONT_FACE) ||
  314. BITSET_TEST(shader->info.system_values_read, SYSTEM_VALUE_FRONT_FACE);
  315. const bool use_position =
  316. nir_find_variable_with_location(shader, nir_var_shader_in, VARYING_SLOT_POS) ||
  317. (shader->info.inputs_read & VARYING_BIT_POS) ||
  318. nir_find_variable_with_location(shader, nir_var_system_value, SYSTEM_VALUE_FRAG_COORD) ||
  319. BITSET_TEST(shader->info.system_values_read, SYSTEM_VALUE_FRAG_COORD);
  320. if (use_front_face && !use_position) {
  321. nir_variable *const pos = nir_variable_create(shader, nir_var_shader_in, glsl_vec4_type(), "gl_FragCoord");
  322. pos->data.location = VARYING_SLOT_POS;
  323. shader->info.inputs_read |= VARYING_BIT_POS;
  324. }
  325. }
  326. if (prev_shader) {
  327. bool requires_runtime_data = {};
  328. dxil_spirv_nir_link(shader, prev_shader, &dxil_runtime_conf, &requires_runtime_data);
  329. }
  330. }
  331. return true;
  332. }
  333. struct GodotNirCallbackUserData {
  334. RenderingShaderContainerD3D12 *container;
  335. RenderingDeviceCommons::ShaderStage stage;
  336. };
  337. static dxil_shader_model shader_model_d3d_to_dxil(D3D_SHADER_MODEL p_d3d_shader_model) {
  338. static_assert(SHADER_MODEL_6_0 == 0x60000);
  339. static_assert(SHADER_MODEL_6_3 == 0x60003);
  340. static_assert(D3D_SHADER_MODEL_6_0 == 0x60);
  341. static_assert(D3D_SHADER_MODEL_6_3 == 0x63);
  342. return (dxil_shader_model)((p_d3d_shader_model >> 4) * 0x10000 + (p_d3d_shader_model & 0xf));
  343. }
  344. 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) {
  345. // Translate NIR to DXIL.
  346. for (KeyValue<int, nir_shader *> it : p_stages_nir_shaders) {
  347. RenderingDeviceCommons::ShaderStage stage = (RenderingDeviceCommons::ShaderStage)(it.key);
  348. GodotNirCallbackUserData godot_nir_callback_user_data;
  349. godot_nir_callback_user_data.container = this;
  350. godot_nir_callback_user_data.stage = stage;
  351. GodotNirCallbacks godot_nir_callbacks = {};
  352. godot_nir_callbacks.data = &godot_nir_callback_user_data;
  353. godot_nir_callbacks.report_resource = _nir_report_resource;
  354. godot_nir_callbacks.report_sc_bit_offset_fn = _nir_report_sc_bit_offset;
  355. godot_nir_callbacks.report_bitcode_bit_offset_fn = _nir_report_bitcode_bit_offset;
  356. nir_to_dxil_options nir_to_dxil_options = {};
  357. nir_to_dxil_options.environment = DXIL_ENVIRONMENT_VULKAN;
  358. nir_to_dxil_options.shader_model_max = shader_model_d3d_to_dxil(D3D_SHADER_MODEL(REQUIRED_SHADER_MODEL));
  359. nir_to_dxil_options.validator_version_max = NO_DXIL_VALIDATION;
  360. nir_to_dxil_options.godot_nir_callbacks = &godot_nir_callbacks;
  361. dxil_logger logger = {};
  362. logger.log = [](void *p_priv, const char *p_msg) {
  363. #ifdef DEBUG_ENABLED
  364. print_verbose(p_msg);
  365. #endif
  366. };
  367. blob dxil_blob = {};
  368. bool ok = nir_to_dxil(it.value, &nir_to_dxil_options, &logger, &dxil_blob);
  369. ERR_FAIL_COND_V_MSG(!ok, false, "Shader translation at stage " + String(RenderingDeviceCommons::SHADER_STAGE_NAMES[stage]) + " failed.");
  370. Vector<uint8_t> blob_copy;
  371. blob_copy.resize(dxil_blob.size);
  372. memcpy(blob_copy.ptrw(), dxil_blob.data, dxil_blob.size);
  373. blob_finish(&dxil_blob);
  374. r_dxil_blobs.insert(stage, blob_copy);
  375. }
  376. return true;
  377. }
  378. bool RenderingShaderContainerD3D12::_convert_spirv_to_dxil(const Vector<RenderingDeviceCommons::ShaderStageSPIRVData> &p_spirv, HashMap<RenderingDeviceCommons::ShaderStage, Vector<uint8_t>> &r_dxil_blobs, Vector<RenderingDeviceCommons::ShaderStage> &r_stages, BitField<RenderingDeviceCommons::ShaderStage> &r_stages_processed) {
  379. r_dxil_blobs.clear();
  380. HashMap<int, nir_shader *> stages_nir_shaders;
  381. auto free_nir_shaders = [&]() {
  382. for (KeyValue<int, nir_shader *> &E : stages_nir_shaders) {
  383. ralloc_free(E.value);
  384. }
  385. stages_nir_shaders.clear();
  386. };
  387. // This structure must live as long as the shaders are alive.
  388. nir_shader_compiler_options compiler_options = *dxil_get_nir_compiler_options();
  389. compiler_options.lower_base_vertex = false;
  390. // This is based on spirv2dxil.c. May need updates when it changes.
  391. // Also, this has to stay around until after linking.
  392. if (!_convert_spirv_to_nir(p_spirv, &compiler_options, stages_nir_shaders, r_stages, r_stages_processed)) {
  393. free_nir_shaders();
  394. return false;
  395. }
  396. if (!_convert_nir_to_dxil(stages_nir_shaders, r_stages_processed, r_dxil_blobs)) {
  397. free_nir_shaders();
  398. return false;
  399. }
  400. free_nir_shaders();
  401. return true;
  402. }
  403. bool RenderingShaderContainerD3D12::_generate_root_signature(BitField<RenderingDeviceCommons::ShaderStage> p_stages_processed) {
  404. // Root (push) constants.
  405. LocalVector<D3D12_ROOT_PARAMETER1> root_params;
  406. if (reflection_data_d3d12.dxil_push_constant_stages) {
  407. CD3DX12_ROOT_PARAMETER1 push_constant;
  408. push_constant.InitAsConstants(
  409. reflection_data.push_constant_size / sizeof(uint32_t),
  410. ROOT_CONSTANT_REGISTER,
  411. 0,
  412. stages_to_d3d12_visibility(reflection_data_d3d12.dxil_push_constant_stages));
  413. root_params.push_back(push_constant);
  414. }
  415. // NIR-DXIL runtime data.
  416. if (reflection_data_d3d12.nir_runtime_data_root_param_idx == 1) { // Set above to 1 when discovering runtime data is needed.
  417. DEV_ASSERT(!reflection_data.is_compute); // Could be supported if needed, but it's pointless as of now.
  418. reflection_data_d3d12.nir_runtime_data_root_param_idx = root_params.size();
  419. CD3DX12_ROOT_PARAMETER1 nir_runtime_data;
  420. nir_runtime_data.InitAsConstants(
  421. sizeof(dxil_spirv_vertex_runtime_data) / sizeof(uint32_t),
  422. RUNTIME_DATA_REGISTER,
  423. 0,
  424. D3D12_SHADER_VISIBILITY_VERTEX);
  425. root_params.push_back(nir_runtime_data);
  426. }
  427. // Descriptor tables (up to two per uniform set, for resources and/or samplers).
  428. // These have to stay around until serialization!
  429. struct TraceableDescriptorTable {
  430. uint32_t stages_mask = {};
  431. Vector<D3D12_DESCRIPTOR_RANGE1> ranges;
  432. Vector<RootSignatureLocation *> root_signature_locations;
  433. };
  434. uint32_t binding_start = 0;
  435. Vector<TraceableDescriptorTable> resource_tables_maps;
  436. Vector<TraceableDescriptorTable> sampler_tables_maps;
  437. for (uint32_t i = 0; i < reflection_binding_set_uniforms_count.size(); i++) {
  438. bool first_resource_in_set = true;
  439. bool first_sampler_in_set = true;
  440. uint32_t uniform_count = reflection_binding_set_uniforms_count[i];
  441. for (uint32_t j = 0; j < uniform_count; j++) {
  442. const ReflectionBindingData &uniform = reflection_binding_set_uniforms_data[binding_start + j];
  443. ReflectionBindingDataD3D12 &uniform_d3d12 = reflection_binding_set_uniforms_data_d3d12.ptrw()[binding_start + j];
  444. bool really_used = uniform_d3d12.dxil_stages != 0;
  445. #ifdef DEV_ENABLED
  446. bool anybody_home = (ResourceClass)(uniform_d3d12.resource_class) != RES_CLASS_INVALID || uniform_d3d12.has_sampler;
  447. DEV_ASSERT(anybody_home == really_used);
  448. #endif
  449. if (!really_used) {
  450. continue; // Existed in SPIR-V; went away in DXIL.
  451. }
  452. auto insert_range = [](D3D12_DESCRIPTOR_RANGE_TYPE p_range_type,
  453. uint32_t p_num_descriptors,
  454. uint32_t p_dxil_register,
  455. uint32_t p_dxil_stages_mask,
  456. RootSignatureLocation *p_root_sig_locations,
  457. Vector<TraceableDescriptorTable> &r_tables,
  458. bool &r_first_in_set) {
  459. if (r_first_in_set) {
  460. r_tables.resize(r_tables.size() + 1);
  461. r_first_in_set = false;
  462. }
  463. TraceableDescriptorTable &table = r_tables.write[r_tables.size() - 1];
  464. table.stages_mask |= p_dxil_stages_mask;
  465. CD3DX12_DESCRIPTOR_RANGE1 range;
  466. // Due to the aliasing hack for SRV-UAV of different families,
  467. // we can be causing an unintended change of data (sometimes the validation layers catch it).
  468. D3D12_DESCRIPTOR_RANGE_FLAGS flags = D3D12_DESCRIPTOR_RANGE_FLAG_NONE;
  469. if (p_range_type == D3D12_DESCRIPTOR_RANGE_TYPE_SRV || p_range_type == D3D12_DESCRIPTOR_RANGE_TYPE_UAV) {
  470. flags = D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE;
  471. } else if (p_range_type == D3D12_DESCRIPTOR_RANGE_TYPE_CBV) {
  472. flags = D3D12_DESCRIPTOR_RANGE_FLAG_DATA_STATIC_WHILE_SET_AT_EXECUTE;
  473. }
  474. range.Init(p_range_type, p_num_descriptors, p_dxil_register, 0, flags);
  475. table.ranges.push_back(range);
  476. table.root_signature_locations.push_back(p_root_sig_locations);
  477. };
  478. uint32_t num_descriptors = 1;
  479. D3D12_DESCRIPTOR_RANGE_TYPE resource_range_type = {};
  480. switch ((ResourceClass)(uniform_d3d12.resource_class)) {
  481. case RES_CLASS_INVALID: {
  482. num_descriptors = uniform.length;
  483. DEV_ASSERT(uniform_d3d12.has_sampler);
  484. } break;
  485. case RES_CLASS_CBV: {
  486. resource_range_type = D3D12_DESCRIPTOR_RANGE_TYPE_CBV;
  487. DEV_ASSERT(!uniform_d3d12.has_sampler);
  488. } break;
  489. case RES_CLASS_SRV: {
  490. resource_range_type = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
  491. num_descriptors = MAX(1u, uniform.length); // An unbound R/O buffer is reflected as zero-size.
  492. } break;
  493. case RES_CLASS_UAV: {
  494. resource_range_type = D3D12_DESCRIPTOR_RANGE_TYPE_UAV;
  495. num_descriptors = MAX(1u, uniform.length); // An unbound R/W buffer is reflected as zero-size.
  496. DEV_ASSERT(!uniform_d3d12.has_sampler);
  497. } break;
  498. }
  499. uint32_t dxil_register = i * GODOT_NIR_DESCRIPTOR_SET_MULTIPLIER + uniform.binding * GODOT_NIR_BINDING_MULTIPLIER;
  500. if (uniform_d3d12.resource_class != RES_CLASS_INVALID) {
  501. insert_range(
  502. resource_range_type,
  503. num_descriptors,
  504. dxil_register,
  505. uniform_d3d12.dxil_stages,
  506. &uniform_d3d12.root_signature_locations[RS_LOC_TYPE_RESOURCE],
  507. resource_tables_maps,
  508. first_resource_in_set);
  509. }
  510. if (uniform_d3d12.has_sampler) {
  511. insert_range(
  512. D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER,
  513. num_descriptors,
  514. dxil_register,
  515. uniform_d3d12.dxil_stages,
  516. &uniform_d3d12.root_signature_locations[RS_LOC_TYPE_SAMPLER],
  517. sampler_tables_maps,
  518. first_sampler_in_set);
  519. }
  520. }
  521. binding_start += uniform_count;
  522. }
  523. auto make_descriptor_tables = [&root_params](const Vector<TraceableDescriptorTable> &p_tables) {
  524. for (const TraceableDescriptorTable &table : p_tables) {
  525. D3D12_SHADER_VISIBILITY visibility = stages_to_d3d12_visibility(table.stages_mask);
  526. DEV_ASSERT(table.ranges.size() == table.root_signature_locations.size());
  527. for (int i = 0; i < table.ranges.size(); i++) {
  528. // By now we know very well which root signature location corresponds to the pointed uniform.
  529. table.root_signature_locations[i]->root_param_index = root_params.size();
  530. table.root_signature_locations[i]->range_index = i;
  531. }
  532. CD3DX12_ROOT_PARAMETER1 root_table;
  533. root_table.InitAsDescriptorTable(table.ranges.size(), table.ranges.ptr(), visibility);
  534. root_params.push_back(root_table);
  535. }
  536. };
  537. make_descriptor_tables(resource_tables_maps);
  538. make_descriptor_tables(sampler_tables_maps);
  539. CD3DX12_VERSIONED_ROOT_SIGNATURE_DESC root_sig_desc = {};
  540. D3D12_ROOT_SIGNATURE_FLAGS root_sig_flags =
  541. D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS |
  542. D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS |
  543. D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS |
  544. D3D12_ROOT_SIGNATURE_FLAG_DENY_AMPLIFICATION_SHADER_ROOT_ACCESS |
  545. D3D12_ROOT_SIGNATURE_FLAG_DENY_MESH_SHADER_ROOT_ACCESS;
  546. if (!p_stages_processed.has_flag(RenderingDeviceCommons::SHADER_STAGE_VERTEX_BIT)) {
  547. root_sig_flags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_VERTEX_SHADER_ROOT_ACCESS;
  548. }
  549. if (!p_stages_processed.has_flag(RenderingDeviceCommons::SHADER_STAGE_FRAGMENT_BIT)) {
  550. root_sig_flags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS;
  551. }
  552. if (reflection_data.vertex_input_mask) {
  553. root_sig_flags |= D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;
  554. }
  555. root_sig_desc.Init_1_1(root_params.size(), root_params.ptr(), 0, nullptr, root_sig_flags);
  556. // Create and store the root signature and its CRC32.
  557. ID3DBlob *error_blob = nullptr;
  558. ID3DBlob *root_sig_blob = nullptr;
  559. HRESULT res = D3DX12SerializeVersionedRootSignature(HMODULE(lib_d3d12), &root_sig_desc, D3D_ROOT_SIGNATURE_VERSION_1_1, &root_sig_blob, &error_blob);
  560. if (SUCCEEDED(res)) {
  561. root_signature_bytes.resize(root_sig_blob->GetBufferSize());
  562. memcpy(root_signature_bytes.ptrw(), root_sig_blob->GetBufferPointer(), root_sig_blob->GetBufferSize());
  563. root_signature_crc = crc32(0, nullptr, 0);
  564. root_signature_crc = crc32(root_signature_crc, (const Bytef *)root_sig_blob->GetBufferPointer(), root_sig_blob->GetBufferSize());
  565. return true;
  566. } else {
  567. if (root_sig_blob != nullptr) {
  568. root_sig_blob->Release();
  569. }
  570. String error_string;
  571. if (error_blob != nullptr) {
  572. 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())));
  573. error_blob->Release();
  574. } else {
  575. error_string = vformat("Serialization of root signature failed with error 0x%08ux", uint32_t(res));
  576. }
  577. ERR_FAIL_V_MSG(false, error_string);
  578. }
  579. }
  580. void RenderingShaderContainerD3D12::_nir_report_resource(uint32_t p_register, uint32_t p_space, uint32_t p_dxil_type, void *p_data) {
  581. const GodotNirCallbackUserData &user_data = *(GodotNirCallbackUserData *)p_data;
  582. // Types based on Mesa's dxil_container.h.
  583. static const uint32_t DXIL_RES_SAMPLER = 1;
  584. static const ResourceClass DXIL_TYPE_TO_CLASS[] = {
  585. RES_CLASS_INVALID, // DXIL_RES_INVALID
  586. RES_CLASS_INVALID, // DXIL_RES_SAMPLER
  587. RES_CLASS_CBV, // DXIL_RES_CBV
  588. RES_CLASS_SRV, // DXIL_RES_SRV_TYPED
  589. RES_CLASS_SRV, // DXIL_RES_SRV_RAW
  590. RES_CLASS_SRV, // DXIL_RES_SRV_STRUCTURED
  591. RES_CLASS_UAV, // DXIL_RES_UAV_TYPED
  592. RES_CLASS_UAV, // DXIL_RES_UAV_RAW
  593. RES_CLASS_UAV, // DXIL_RES_UAV_STRUCTURED
  594. RES_CLASS_INVALID, // DXIL_RES_UAV_STRUCTURED_WITH_COUNTER
  595. };
  596. DEV_ASSERT(p_dxil_type < ARRAY_SIZE(DXIL_TYPE_TO_CLASS));
  597. ResourceClass resource_class = DXIL_TYPE_TO_CLASS[p_dxil_type];
  598. if (p_register == ROOT_CONSTANT_REGISTER && p_space == 0) {
  599. DEV_ASSERT(resource_class == RES_CLASS_CBV);
  600. user_data.container->reflection_data_d3d12.dxil_push_constant_stages |= (1 << user_data.stage);
  601. } else if (p_register == RUNTIME_DATA_REGISTER && p_space == 0) {
  602. DEV_ASSERT(resource_class == RES_CLASS_CBV);
  603. user_data.container->reflection_data_d3d12.nir_runtime_data_root_param_idx = 1; // Temporary, to be determined later.
  604. } else {
  605. DEV_ASSERT(p_space == 0);
  606. uint32_t set = p_register / GODOT_NIR_DESCRIPTOR_SET_MULTIPLIER;
  607. uint32_t binding = (p_register % GODOT_NIR_DESCRIPTOR_SET_MULTIPLIER) / GODOT_NIR_BINDING_MULTIPLIER;
  608. DEV_ASSERT(set < (uint32_t)user_data.container->reflection_binding_set_uniforms_count.size());
  609. uint32_t binding_start = 0;
  610. for (uint32_t i = 0; i < set; i++) {
  611. binding_start += user_data.container->reflection_binding_set_uniforms_count[i];
  612. }
  613. [[maybe_unused]] bool found = false;
  614. for (uint32_t i = 0; i < user_data.container->reflection_binding_set_uniforms_count[set]; i++) {
  615. const ReflectionBindingData &uniform = user_data.container->reflection_binding_set_uniforms_data[binding_start + i];
  616. ReflectionBindingDataD3D12 &uniform_d3d12 = user_data.container->reflection_binding_set_uniforms_data_d3d12.ptrw()[binding_start + i];
  617. if (uniform.binding != binding) {
  618. continue;
  619. }
  620. uniform_d3d12.dxil_stages |= (1 << user_data.stage);
  621. if (resource_class != RES_CLASS_INVALID) {
  622. DEV_ASSERT(uniform_d3d12.resource_class == (uint32_t)RES_CLASS_INVALID || uniform_d3d12.resource_class == (uint32_t)resource_class);
  623. uniform_d3d12.resource_class = resource_class;
  624. } else if (p_dxil_type == DXIL_RES_SAMPLER) {
  625. uniform_d3d12.has_sampler = (uint32_t)true;
  626. } else {
  627. DEV_ASSERT(false && "Unknown resource class.");
  628. }
  629. found = true;
  630. }
  631. DEV_ASSERT(found);
  632. }
  633. }
  634. void RenderingShaderContainerD3D12::_nir_report_sc_bit_offset(uint32_t p_sc_id, uint64_t p_bit_offset, void *p_data) {
  635. const GodotNirCallbackUserData &user_data = *(GodotNirCallbackUserData *)p_data;
  636. [[maybe_unused]] bool found = false;
  637. for (int64_t i = 0; i < user_data.container->reflection_specialization_data.size(); i++) {
  638. const ReflectionSpecializationData &sc = user_data.container->reflection_specialization_data[i];
  639. ReflectionSpecializationDataD3D12 &sc_d3d12 = user_data.container->reflection_specialization_data_d3d12.ptrw()[i];
  640. if (sc.constant_id != p_sc_id) {
  641. continue;
  642. }
  643. uint32_t offset_idx = SHADER_STAGES_BIT_OFFSET_INDICES[user_data.stage];
  644. DEV_ASSERT(sc_d3d12.stages_bit_offsets[offset_idx] == 0);
  645. sc_d3d12.stages_bit_offsets[offset_idx] = p_bit_offset;
  646. found = true;
  647. break;
  648. }
  649. DEV_ASSERT(found);
  650. }
  651. void RenderingShaderContainerD3D12::_nir_report_bitcode_bit_offset(uint64_t p_bit_offset, void *p_data) {
  652. DEV_ASSERT(p_bit_offset % 8 == 0);
  653. const GodotNirCallbackUserData &user_data = *(GodotNirCallbackUserData *)p_data;
  654. uint32_t offset_idx = SHADER_STAGES_BIT_OFFSET_INDICES[user_data.stage];
  655. for (int64_t i = 0; i < user_data.container->reflection_specialization_data.size(); i++) {
  656. ReflectionSpecializationDataD3D12 &sc_d3d12 = user_data.container->reflection_specialization_data_d3d12.ptrw()[i];
  657. if (sc_d3d12.stages_bit_offsets[offset_idx] == 0) {
  658. // This SC has been optimized out from this stage.
  659. continue;
  660. }
  661. sc_d3d12.stages_bit_offsets[offset_idx] += p_bit_offset;
  662. }
  663. }
  664. #endif
  665. void RenderingShaderContainerD3D12::_set_from_shader_reflection_post(const String &p_shader_name, const RenderingDeviceCommons::ShaderReflection &p_reflection) {
  666. reflection_binding_set_uniforms_data_d3d12.resize(reflection_binding_set_uniforms_data.size());
  667. reflection_specialization_data_d3d12.resize(reflection_specialization_data.size());
  668. // Sort bindings inside each uniform set. This guarantees the root signature will be generated in the correct order.
  669. SortArray<ReflectionBindingData> sorter;
  670. uint32_t binding_start = 0;
  671. for (uint32_t i = 0; i < reflection_binding_set_uniforms_count.size(); i++) {
  672. uint32_t uniform_count = reflection_binding_set_uniforms_count[i];
  673. if (uniform_count > 0) {
  674. sorter.sort(&reflection_binding_set_uniforms_data.ptrw()[binding_start], uniform_count);
  675. binding_start += uniform_count;
  676. }
  677. }
  678. }
  679. bool RenderingShaderContainerD3D12::_set_code_from_spirv(const Vector<RenderingDeviceCommons::ShaderStageSPIRVData> &p_spirv) {
  680. #if NIR_ENABLED
  681. reflection_data_d3d12.nir_runtime_data_root_param_idx = UINT32_MAX;
  682. for (int64_t i = 0; i < reflection_specialization_data.size(); i++) {
  683. 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.");
  684. reflection_data_d3d12.spirv_specialization_constants_ids_mask |= (1 << reflection_specialization_data[i].constant_id);
  685. }
  686. // Translate SPIR-V shaders to DXIL, and collect shader info from the new representation.
  687. HashMap<RenderingDeviceCommons::ShaderStage, Vector<uint8_t>> dxil_blobs;
  688. Vector<RenderingDeviceCommons::ShaderStage> stages;
  689. BitField<RenderingDeviceCommons::ShaderStage> stages_processed = {};
  690. if (!_convert_spirv_to_dxil(p_spirv, dxil_blobs, stages, stages_processed)) {
  691. return false;
  692. }
  693. // Patch with default values of specialization constants.
  694. DEV_ASSERT(reflection_specialization_data.size() == reflection_specialization_data_d3d12.size());
  695. for (int32_t i = 0; i < reflection_specialization_data.size(); i++) {
  696. const ReflectionSpecializationData &sc = reflection_specialization_data[i];
  697. const ReflectionSpecializationDataD3D12 &sc_d3d12 = reflection_specialization_data_d3d12[i];
  698. RenderingDXIL::patch_specialization_constant((RenderingDeviceCommons::PipelineSpecializationConstantType)(sc.type), &sc.int_value, sc_d3d12.stages_bit_offsets, dxil_blobs, true);
  699. }
  700. // Sign.
  701. uint32_t shader_index = 0;
  702. for (KeyValue<RenderingDeviceCommons::ShaderStage, Vector<uint8_t>> &E : dxil_blobs) {
  703. RenderingDXIL::sign_bytecode(E.key, E.value);
  704. }
  705. // Store compressed DXIL blobs as the shaders.
  706. shaders.resize(p_spirv.size());
  707. for (int64_t i = 0; i < shaders.size(); i++) {
  708. const PackedByteArray &dxil_bytes = dxil_blobs[stages[i]];
  709. RenderingShaderContainer::Shader &shader = shaders.ptrw()[i];
  710. uint32_t compressed_size = 0;
  711. shader.shader_stage = stages[i];
  712. shader.code_decompressed_size = dxil_bytes.size();
  713. shader.code_compressed_bytes.resize(dxil_bytes.size());
  714. bool compressed = compress_code(dxil_bytes.ptr(), dxil_bytes.size(), shader.code_compressed_bytes.ptrw(), &compressed_size, &shader.code_compression_flags);
  715. ERR_FAIL_COND_V_MSG(!compressed, false, vformat("Failed to compress native code to native for SPIR-V #%d.", shader_index));
  716. shader.code_compressed_bytes.resize(compressed_size);
  717. }
  718. if (!_generate_root_signature(stages_processed)) {
  719. return false;
  720. }
  721. return true;
  722. #else
  723. ERR_FAIL_V_MSG(false, "Shader compilation is not supported at runtime without NIR.");
  724. #endif
  725. }
  726. RenderingShaderContainerD3D12::RenderingShaderContainerD3D12() {
  727. // Default empty constructor.
  728. }
  729. RenderingShaderContainerD3D12::RenderingShaderContainerD3D12(void *p_lib_d3d12) {
  730. lib_d3d12 = p_lib_d3d12;
  731. }
  732. RenderingShaderContainerD3D12::ShaderReflectionD3D12 RenderingShaderContainerD3D12::get_shader_reflection_d3d12() const {
  733. ShaderReflectionD3D12 reflection;
  734. reflection.spirv_specialization_constants_ids_mask = reflection_data_d3d12.spirv_specialization_constants_ids_mask;
  735. reflection.dxil_push_constant_stages = reflection_data_d3d12.dxil_push_constant_stages;
  736. reflection.nir_runtime_data_root_param_idx = reflection_data_d3d12.nir_runtime_data_root_param_idx;
  737. reflection.reflection_specialization_data_d3d12 = reflection_specialization_data_d3d12;
  738. reflection.root_signature_bytes = root_signature_bytes;
  739. reflection.root_signature_crc = root_signature_crc;
  740. // Transform data vector into a vector of vectors that's easier to user.
  741. uint32_t uniform_index = 0;
  742. reflection.reflection_binding_set_uniforms_d3d12.resize(reflection_binding_set_uniforms_count.size());
  743. for (int64_t i = 0; i < reflection.reflection_binding_set_uniforms_d3d12.size(); i++) {
  744. Vector<ReflectionBindingDataD3D12> &uniforms = reflection.reflection_binding_set_uniforms_d3d12.ptrw()[i];
  745. uniforms.resize(reflection_binding_set_uniforms_count[i]);
  746. for (int64_t j = 0; j < uniforms.size(); j++) {
  747. uniforms.ptrw()[j] = reflection_binding_set_uniforms_data_d3d12[uniform_index];
  748. uniform_index++;
  749. }
  750. }
  751. return reflection;
  752. }
  753. // RenderingShaderContainerFormatD3D12
  754. void RenderingShaderContainerFormatD3D12::set_lib_d3d12(void *p_lib_d3d12) {
  755. lib_d3d12 = p_lib_d3d12;
  756. }
  757. Ref<RenderingShaderContainer> RenderingShaderContainerFormatD3D12::create_container() const {
  758. return memnew(RenderingShaderContainerD3D12(lib_d3d12));
  759. }
  760. RenderingDeviceCommons::ShaderLanguageVersion RenderingShaderContainerFormatD3D12::get_shader_language_version() const {
  761. // NIR-DXIL is Vulkan 1.1-conformant.
  762. return SHADER_LANGUAGE_VULKAN_VERSION_1_1;
  763. }
  764. RenderingDeviceCommons::ShaderSpirvVersion RenderingShaderContainerFormatD3D12::get_shader_spirv_version() const {
  765. // The SPIR-V part of Mesa supports 1.6, but:
  766. // - SPIRV-Reflect won't be able to parse the compute workgroup size.
  767. // - We want to play it safe with NIR-DXIL.
  768. return SHADER_SPIRV_VERSION_1_5;
  769. }
  770. RenderingShaderContainerFormatD3D12::RenderingShaderContainerFormatD3D12() {}
  771. RenderingShaderContainerFormatD3D12::~RenderingShaderContainerFormatD3D12() {}