rendering_shader_container_d3d12.cpp 38 KB

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