rendering_shader_container_d3d12.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897
  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. GODOT_GCC_WARNING_PUSH
  39. GODOT_GCC_WARNING_IGNORE("-Wimplicit-fallthrough")
  40. GODOT_GCC_WARNING_IGNORE("-Wlogical-not-parentheses")
  41. GODOT_GCC_WARNING_IGNORE("-Wmissing-field-initializers")
  42. GODOT_GCC_WARNING_IGNORE("-Wnon-virtual-dtor")
  43. GODOT_GCC_WARNING_IGNORE("-Wshadow")
  44. GODOT_GCC_WARNING_IGNORE("-Wswitch")
  45. GODOT_CLANG_WARNING_PUSH
  46. GODOT_CLANG_WARNING_IGNORE("-Wimplicit-fallthrough")
  47. GODOT_CLANG_WARNING_IGNORE("-Wlogical-not-parentheses")
  48. GODOT_CLANG_WARNING_IGNORE("-Wmissing-field-initializers")
  49. GODOT_CLANG_WARNING_IGNORE("-Wnon-virtual-dtor")
  50. GODOT_CLANG_WARNING_IGNORE("-Wstring-plus-int")
  51. GODOT_CLANG_WARNING_IGNORE("-Wswitch")
  52. GODOT_MSVC_WARNING_PUSH
  53. GODOT_MSVC_WARNING_IGNORE(4200) // "nonstandard extension used: zero-sized array in struct/union".
  54. GODOT_MSVC_WARNING_IGNORE(4806) // "'&': unsafe operation: no value of type 'bool' promoted to type 'uint32_t' can equal the given constant".
  55. #include <d3dx12.h>
  56. #include <dxgi1_6.h>
  57. #define D3D12MA_D3D12_HEADERS_ALREADY_INCLUDED
  58. #include <D3D12MemAlloc.h>
  59. #include <wrl/client.h>
  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(Span<ReflectedShaderStage> 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 (uint64_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. Span<uint32_t> code = p_spirv[i].spirv();
  265. nir_shader *shader = spirv_to_nir(
  266. code.ptr(),
  267. code.size(),
  268. nullptr,
  269. 0,
  270. SPIRV_TO_MESA_STAGES[stage],
  271. entry_point,
  272. dxil_spirv_nir_get_spirv_options(),
  273. p_compiler_options);
  274. ERR_FAIL_NULL_V_MSG(shader, false, "Shader translation (step 1) at stage " + String(RenderingDeviceCommons::SHADER_STAGE_NAMES[stage]) + " failed.");
  275. #ifdef DEV_ENABLED
  276. nir_validate_shader(shader, "Validate before feeding NIR to the DXIL compiler");
  277. #endif
  278. if (stage == RenderingDeviceCommons::SHADER_STAGE_VERTEX) {
  279. dxil_runtime_conf.yz_flip.y_mask = 0xffff;
  280. dxil_runtime_conf.yz_flip.mode = DXIL_SPIRV_Y_FLIP_UNCONDITIONAL;
  281. } else {
  282. dxil_runtime_conf.yz_flip.y_mask = 0;
  283. dxil_runtime_conf.yz_flip.mode = DXIL_SPIRV_YZ_FLIP_NONE;
  284. }
  285. dxil_spirv_nir_prep(shader);
  286. bool requires_runtime_data = false;
  287. dxil_spirv_nir_passes(shader, &dxil_runtime_conf, &requires_runtime_data);
  288. r_stages_nir_shaders[stage] = shader;
  289. }
  290. // Link NIR shaders.
  291. for (int i = RenderingDeviceCommons::SHADER_STAGE_MAX - 1; i >= 0; i--) {
  292. if (!r_stages_nir_shaders.has(i)) {
  293. continue;
  294. }
  295. nir_shader *shader = r_stages_nir_shaders[i];
  296. nir_shader *prev_shader = nullptr;
  297. for (int j = i - 1; j >= 0; j--) {
  298. if (r_stages_nir_shaders.has(j)) {
  299. prev_shader = r_stages_nir_shaders[j];
  300. break;
  301. }
  302. }
  303. // There is a bug in the Direct3D runtime during creation of a PSO with view instancing. If a fragment
  304. // shader uses front/back face detection (SV_IsFrontFace), its signature must include the pixel position
  305. // builtin variable (SV_Position), otherwise an Internal Runtime error will occur.
  306. if (i == RenderingDeviceCommons::SHADER_STAGE_FRAGMENT) {
  307. const bool use_front_face =
  308. nir_find_variable_with_location(shader, nir_var_shader_in, VARYING_SLOT_FACE) ||
  309. (shader->info.inputs_read & VARYING_BIT_FACE) ||
  310. nir_find_variable_with_location(shader, nir_var_system_value, SYSTEM_VALUE_FRONT_FACE) ||
  311. BITSET_TEST(shader->info.system_values_read, SYSTEM_VALUE_FRONT_FACE);
  312. const bool use_position =
  313. nir_find_variable_with_location(shader, nir_var_shader_in, VARYING_SLOT_POS) ||
  314. (shader->info.inputs_read & VARYING_BIT_POS) ||
  315. nir_find_variable_with_location(shader, nir_var_system_value, SYSTEM_VALUE_FRAG_COORD) ||
  316. BITSET_TEST(shader->info.system_values_read, SYSTEM_VALUE_FRAG_COORD);
  317. if (use_front_face && !use_position) {
  318. nir_variable *const pos = nir_variable_create(shader, nir_var_shader_in, glsl_vec4_type(), "gl_FragCoord");
  319. pos->data.location = VARYING_SLOT_POS;
  320. shader->info.inputs_read |= VARYING_BIT_POS;
  321. }
  322. }
  323. if (prev_shader) {
  324. bool requires_runtime_data = {};
  325. dxil_spirv_nir_link(shader, prev_shader, &dxil_runtime_conf, &requires_runtime_data);
  326. }
  327. }
  328. return true;
  329. }
  330. struct GodotNirCallbackUserData {
  331. RenderingShaderContainerD3D12 *container;
  332. RenderingDeviceCommons::ShaderStage stage;
  333. };
  334. static dxil_shader_model shader_model_d3d_to_dxil(D3D_SHADER_MODEL p_d3d_shader_model) {
  335. static_assert(SHADER_MODEL_6_0 == 0x60000);
  336. static_assert(SHADER_MODEL_6_3 == 0x60003);
  337. static_assert(D3D_SHADER_MODEL_6_0 == 0x60);
  338. static_assert(D3D_SHADER_MODEL_6_3 == 0x63);
  339. return (dxil_shader_model)((p_d3d_shader_model >> 4) * 0x10000 + (p_d3d_shader_model & 0xf));
  340. }
  341. 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) {
  342. // Translate NIR to DXIL.
  343. for (KeyValue<int, nir_shader *> it : p_stages_nir_shaders) {
  344. RenderingDeviceCommons::ShaderStage stage = (RenderingDeviceCommons::ShaderStage)(it.key);
  345. GodotNirCallbackUserData godot_nir_callback_user_data;
  346. godot_nir_callback_user_data.container = this;
  347. godot_nir_callback_user_data.stage = stage;
  348. GodotNirCallbacks godot_nir_callbacks = {};
  349. godot_nir_callbacks.data = &godot_nir_callback_user_data;
  350. godot_nir_callbacks.report_resource = _nir_report_resource;
  351. godot_nir_callbacks.report_sc_bit_offset_fn = _nir_report_sc_bit_offset;
  352. godot_nir_callbacks.report_bitcode_bit_offset_fn = _nir_report_bitcode_bit_offset;
  353. nir_to_dxil_options nir_to_dxil_options = {};
  354. nir_to_dxil_options.environment = DXIL_ENVIRONMENT_VULKAN;
  355. nir_to_dxil_options.shader_model_max = shader_model_d3d_to_dxil(D3D_SHADER_MODEL(REQUIRED_SHADER_MODEL));
  356. nir_to_dxil_options.validator_version_max = NO_DXIL_VALIDATION;
  357. nir_to_dxil_options.godot_nir_callbacks = &godot_nir_callbacks;
  358. dxil_logger logger = {};
  359. logger.log = [](void *p_priv, const char *p_msg) {
  360. #ifdef DEBUG_ENABLED
  361. print_verbose(p_msg);
  362. #endif
  363. };
  364. blob dxil_blob = {};
  365. bool ok = nir_to_dxil(it.value, &nir_to_dxil_options, &logger, &dxil_blob);
  366. ERR_FAIL_COND_V_MSG(!ok, false, "Shader translation at stage " + String(RenderingDeviceCommons::SHADER_STAGE_NAMES[stage]) + " failed.");
  367. Vector<uint8_t> blob_copy;
  368. blob_copy.resize(dxil_blob.size);
  369. memcpy(blob_copy.ptrw(), dxil_blob.data, dxil_blob.size);
  370. blob_finish(&dxil_blob);
  371. r_dxil_blobs.insert(stage, blob_copy);
  372. }
  373. return true;
  374. }
  375. bool RenderingShaderContainerD3D12::_convert_spirv_to_dxil(Span<ReflectedShaderStage> p_spirv, HashMap<RenderingDeviceCommons::ShaderStage, Vector<uint8_t>> &r_dxil_blobs, Vector<RenderingDeviceCommons::ShaderStage> &r_stages, BitField<RenderingDeviceCommons::ShaderStage> &r_stages_processed) {
  376. r_dxil_blobs.clear();
  377. HashMap<int, nir_shader *> stages_nir_shaders;
  378. auto free_nir_shaders = [&]() {
  379. for (KeyValue<int, nir_shader *> &E : stages_nir_shaders) {
  380. ralloc_free(E.value);
  381. }
  382. stages_nir_shaders.clear();
  383. };
  384. // This structure must live as long as the shaders are alive.
  385. nir_shader_compiler_options compiler_options = *dxil_get_nir_compiler_options();
  386. compiler_options.lower_base_vertex = false;
  387. // This is based on spirv2dxil.c. May need updates when it changes.
  388. // Also, this has to stay around until after linking.
  389. if (!_convert_spirv_to_nir(p_spirv, &compiler_options, stages_nir_shaders, r_stages, r_stages_processed)) {
  390. free_nir_shaders();
  391. return false;
  392. }
  393. if (!_convert_nir_to_dxil(stages_nir_shaders, r_stages_processed, r_dxil_blobs)) {
  394. free_nir_shaders();
  395. return false;
  396. }
  397. free_nir_shaders();
  398. return true;
  399. }
  400. bool RenderingShaderContainerD3D12::_generate_root_signature(BitField<RenderingDeviceCommons::ShaderStage> p_stages_processed) {
  401. // Root (push) constants.
  402. LocalVector<D3D12_ROOT_PARAMETER1> root_params;
  403. if (reflection_data_d3d12.dxil_push_constant_stages) {
  404. CD3DX12_ROOT_PARAMETER1 push_constant;
  405. push_constant.InitAsConstants(
  406. reflection_data.push_constant_size / sizeof(uint32_t),
  407. ROOT_CONSTANT_REGISTER,
  408. 0,
  409. stages_to_d3d12_visibility(reflection_data_d3d12.dxil_push_constant_stages));
  410. root_params.push_back(push_constant);
  411. }
  412. // NIR-DXIL runtime data.
  413. if (reflection_data_d3d12.nir_runtime_data_root_param_idx == 1) { // Set above to 1 when discovering runtime data is needed.
  414. DEV_ASSERT(!reflection_data.is_compute); // Could be supported if needed, but it's pointless as of now.
  415. reflection_data_d3d12.nir_runtime_data_root_param_idx = root_params.size();
  416. CD3DX12_ROOT_PARAMETER1 nir_runtime_data;
  417. nir_runtime_data.InitAsConstants(
  418. sizeof(dxil_spirv_vertex_runtime_data) / sizeof(uint32_t),
  419. RUNTIME_DATA_REGISTER,
  420. 0,
  421. D3D12_SHADER_VISIBILITY_VERTEX);
  422. root_params.push_back(nir_runtime_data);
  423. }
  424. // Descriptor tables (up to two per uniform set, for resources and/or samplers).
  425. // These have to stay around until serialization!
  426. struct TraceableDescriptorTable {
  427. uint32_t stages_mask = {};
  428. Vector<D3D12_DESCRIPTOR_RANGE1> ranges;
  429. Vector<RootSignatureLocation *> root_signature_locations;
  430. };
  431. uint32_t binding_start = 0;
  432. Vector<TraceableDescriptorTable> resource_tables_maps;
  433. Vector<TraceableDescriptorTable> sampler_tables_maps;
  434. for (uint32_t i = 0; i < reflection_binding_set_uniforms_count.size(); i++) {
  435. bool first_resource_in_set = true;
  436. bool first_sampler_in_set = true;
  437. uint32_t uniform_count = reflection_binding_set_uniforms_count[i];
  438. for (uint32_t j = 0; j < uniform_count; j++) {
  439. const ReflectionBindingData &uniform = reflection_binding_set_uniforms_data[binding_start + j];
  440. ReflectionBindingDataD3D12 &uniform_d3d12 = reflection_binding_set_uniforms_data_d3d12.ptrw()[binding_start + j];
  441. bool really_used = uniform_d3d12.dxil_stages != 0;
  442. #ifdef DEV_ENABLED
  443. bool anybody_home = (ResourceClass)(uniform_d3d12.resource_class) != RES_CLASS_INVALID || uniform_d3d12.has_sampler;
  444. DEV_ASSERT(anybody_home == really_used);
  445. #endif
  446. if (!really_used) {
  447. continue; // Existed in SPIR-V; went away in DXIL.
  448. }
  449. auto insert_range = [](D3D12_DESCRIPTOR_RANGE_TYPE p_range_type,
  450. uint32_t p_num_descriptors,
  451. uint32_t p_dxil_register,
  452. uint32_t p_dxil_stages_mask,
  453. RootSignatureLocation *p_root_sig_locations,
  454. Vector<TraceableDescriptorTable> &r_tables,
  455. bool &r_first_in_set) {
  456. if (r_first_in_set) {
  457. r_tables.resize(r_tables.size() + 1);
  458. r_first_in_set = false;
  459. }
  460. TraceableDescriptorTable &table = r_tables.write[r_tables.size() - 1];
  461. table.stages_mask |= p_dxil_stages_mask;
  462. CD3DX12_DESCRIPTOR_RANGE1 range;
  463. // Due to the aliasing hack for SRV-UAV of different families,
  464. // we can be causing an unintended change of data (sometimes the validation layers catch it).
  465. D3D12_DESCRIPTOR_RANGE_FLAGS flags = D3D12_DESCRIPTOR_RANGE_FLAG_NONE;
  466. if (p_range_type == D3D12_DESCRIPTOR_RANGE_TYPE_SRV || p_range_type == D3D12_DESCRIPTOR_RANGE_TYPE_UAV) {
  467. flags = D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE;
  468. } else if (p_range_type == D3D12_DESCRIPTOR_RANGE_TYPE_CBV) {
  469. flags = D3D12_DESCRIPTOR_RANGE_FLAG_DATA_STATIC_WHILE_SET_AT_EXECUTE;
  470. }
  471. range.Init(p_range_type, p_num_descriptors, p_dxil_register, 0, flags);
  472. table.ranges.push_back(range);
  473. table.root_signature_locations.push_back(p_root_sig_locations);
  474. };
  475. uint32_t num_descriptors = 1;
  476. D3D12_DESCRIPTOR_RANGE_TYPE resource_range_type = {};
  477. switch ((ResourceClass)(uniform_d3d12.resource_class)) {
  478. case RES_CLASS_INVALID: {
  479. num_descriptors = uniform.length;
  480. DEV_ASSERT(uniform_d3d12.has_sampler);
  481. } break;
  482. case RES_CLASS_CBV: {
  483. resource_range_type = D3D12_DESCRIPTOR_RANGE_TYPE_CBV;
  484. DEV_ASSERT(!uniform_d3d12.has_sampler);
  485. } break;
  486. case RES_CLASS_SRV: {
  487. resource_range_type = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
  488. num_descriptors = MAX(1u, uniform.length); // An unbound R/O buffer is reflected as zero-size.
  489. } break;
  490. case RES_CLASS_UAV: {
  491. resource_range_type = D3D12_DESCRIPTOR_RANGE_TYPE_UAV;
  492. num_descriptors = MAX(1u, uniform.length); // An unbound R/W buffer is reflected as zero-size.
  493. DEV_ASSERT(!uniform_d3d12.has_sampler);
  494. } break;
  495. }
  496. uint32_t dxil_register = i * GODOT_NIR_DESCRIPTOR_SET_MULTIPLIER + uniform.binding * GODOT_NIR_BINDING_MULTIPLIER;
  497. if (uniform_d3d12.resource_class != RES_CLASS_INVALID) {
  498. insert_range(
  499. resource_range_type,
  500. num_descriptors,
  501. dxil_register,
  502. uniform_d3d12.dxil_stages,
  503. &uniform_d3d12.root_signature_locations[RS_LOC_TYPE_RESOURCE],
  504. resource_tables_maps,
  505. first_resource_in_set);
  506. }
  507. if (uniform_d3d12.has_sampler) {
  508. insert_range(
  509. D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER,
  510. num_descriptors,
  511. dxil_register,
  512. uniform_d3d12.dxil_stages,
  513. &uniform_d3d12.root_signature_locations[RS_LOC_TYPE_SAMPLER],
  514. sampler_tables_maps,
  515. first_sampler_in_set);
  516. }
  517. }
  518. binding_start += uniform_count;
  519. }
  520. auto make_descriptor_tables = [&root_params](const Vector<TraceableDescriptorTable> &p_tables) {
  521. for (const TraceableDescriptorTable &table : p_tables) {
  522. D3D12_SHADER_VISIBILITY visibility = stages_to_d3d12_visibility(table.stages_mask);
  523. DEV_ASSERT(table.ranges.size() == table.root_signature_locations.size());
  524. for (int i = 0; i < table.ranges.size(); i++) {
  525. // By now we know very well which root signature location corresponds to the pointed uniform.
  526. table.root_signature_locations[i]->root_param_index = root_params.size();
  527. table.root_signature_locations[i]->range_index = i;
  528. }
  529. CD3DX12_ROOT_PARAMETER1 root_table;
  530. root_table.InitAsDescriptorTable(table.ranges.size(), table.ranges.ptr(), visibility);
  531. root_params.push_back(root_table);
  532. }
  533. };
  534. make_descriptor_tables(resource_tables_maps);
  535. make_descriptor_tables(sampler_tables_maps);
  536. CD3DX12_VERSIONED_ROOT_SIGNATURE_DESC root_sig_desc = {};
  537. D3D12_ROOT_SIGNATURE_FLAGS root_sig_flags =
  538. D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS |
  539. D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS |
  540. D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS |
  541. D3D12_ROOT_SIGNATURE_FLAG_DENY_AMPLIFICATION_SHADER_ROOT_ACCESS |
  542. D3D12_ROOT_SIGNATURE_FLAG_DENY_MESH_SHADER_ROOT_ACCESS;
  543. if (!p_stages_processed.has_flag(RenderingDeviceCommons::SHADER_STAGE_VERTEX_BIT)) {
  544. root_sig_flags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_VERTEX_SHADER_ROOT_ACCESS;
  545. }
  546. if (!p_stages_processed.has_flag(RenderingDeviceCommons::SHADER_STAGE_FRAGMENT_BIT)) {
  547. root_sig_flags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS;
  548. }
  549. if (reflection_data.vertex_input_mask) {
  550. root_sig_flags |= D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;
  551. }
  552. root_sig_desc.Init_1_1(root_params.size(), root_params.ptr(), 0, nullptr, root_sig_flags);
  553. // Create and store the root signature and its CRC32.
  554. ID3DBlob *error_blob = nullptr;
  555. ID3DBlob *root_sig_blob = nullptr;
  556. HRESULT res = D3DX12SerializeVersionedRootSignature(HMODULE(lib_d3d12), &root_sig_desc, D3D_ROOT_SIGNATURE_VERSION_1_1, &root_sig_blob, &error_blob);
  557. if (SUCCEEDED(res)) {
  558. root_signature_bytes.resize(root_sig_blob->GetBufferSize());
  559. memcpy(root_signature_bytes.ptrw(), root_sig_blob->GetBufferPointer(), root_sig_blob->GetBufferSize());
  560. root_signature_crc = crc32(0, nullptr, 0);
  561. root_signature_crc = crc32(root_signature_crc, (const Bytef *)root_sig_blob->GetBufferPointer(), root_sig_blob->GetBufferSize());
  562. return true;
  563. } else {
  564. if (root_sig_blob != nullptr) {
  565. root_sig_blob->Release();
  566. }
  567. String error_string;
  568. if (error_blob != nullptr) {
  569. 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())));
  570. error_blob->Release();
  571. } else {
  572. error_string = vformat("Serialization of root signature failed with error 0x%08ux", uint32_t(res));
  573. }
  574. ERR_FAIL_V_MSG(false, error_string);
  575. }
  576. }
  577. void RenderingShaderContainerD3D12::_nir_report_resource(uint32_t p_register, uint32_t p_space, uint32_t p_dxil_type, void *p_data) {
  578. const GodotNirCallbackUserData &user_data = *(GodotNirCallbackUserData *)p_data;
  579. // Types based on Mesa's dxil_container.h.
  580. static const uint32_t DXIL_RES_SAMPLER = 1;
  581. static const ResourceClass DXIL_TYPE_TO_CLASS[] = {
  582. RES_CLASS_INVALID, // DXIL_RES_INVALID
  583. RES_CLASS_INVALID, // DXIL_RES_SAMPLER
  584. RES_CLASS_CBV, // DXIL_RES_CBV
  585. RES_CLASS_SRV, // DXIL_RES_SRV_TYPED
  586. RES_CLASS_SRV, // DXIL_RES_SRV_RAW
  587. RES_CLASS_SRV, // DXIL_RES_SRV_STRUCTURED
  588. RES_CLASS_UAV, // DXIL_RES_UAV_TYPED
  589. RES_CLASS_UAV, // DXIL_RES_UAV_RAW
  590. RES_CLASS_UAV, // DXIL_RES_UAV_STRUCTURED
  591. RES_CLASS_INVALID, // DXIL_RES_UAV_STRUCTURED_WITH_COUNTER
  592. };
  593. DEV_ASSERT(p_dxil_type < ARRAY_SIZE(DXIL_TYPE_TO_CLASS));
  594. ResourceClass resource_class = DXIL_TYPE_TO_CLASS[p_dxil_type];
  595. if (p_register == ROOT_CONSTANT_REGISTER && p_space == 0) {
  596. DEV_ASSERT(resource_class == RES_CLASS_CBV);
  597. user_data.container->reflection_data_d3d12.dxil_push_constant_stages |= (1 << user_data.stage);
  598. } else if (p_register == RUNTIME_DATA_REGISTER && p_space == 0) {
  599. DEV_ASSERT(resource_class == RES_CLASS_CBV);
  600. user_data.container->reflection_data_d3d12.nir_runtime_data_root_param_idx = 1; // Temporary, to be determined later.
  601. } else {
  602. DEV_ASSERT(p_space == 0);
  603. uint32_t set = p_register / GODOT_NIR_DESCRIPTOR_SET_MULTIPLIER;
  604. uint32_t binding = (p_register % GODOT_NIR_DESCRIPTOR_SET_MULTIPLIER) / GODOT_NIR_BINDING_MULTIPLIER;
  605. DEV_ASSERT(set < (uint32_t)user_data.container->reflection_binding_set_uniforms_count.size());
  606. uint32_t binding_start = 0;
  607. for (uint32_t i = 0; i < set; i++) {
  608. binding_start += user_data.container->reflection_binding_set_uniforms_count[i];
  609. }
  610. [[maybe_unused]] bool found = false;
  611. for (uint32_t i = 0; i < user_data.container->reflection_binding_set_uniforms_count[set]; i++) {
  612. const ReflectionBindingData &uniform = user_data.container->reflection_binding_set_uniforms_data[binding_start + i];
  613. ReflectionBindingDataD3D12 &uniform_d3d12 = user_data.container->reflection_binding_set_uniforms_data_d3d12.ptrw()[binding_start + i];
  614. if (uniform.binding != binding) {
  615. continue;
  616. }
  617. uniform_d3d12.dxil_stages |= (1 << user_data.stage);
  618. if (resource_class != RES_CLASS_INVALID) {
  619. DEV_ASSERT(uniform_d3d12.resource_class == (uint32_t)RES_CLASS_INVALID || uniform_d3d12.resource_class == (uint32_t)resource_class);
  620. uniform_d3d12.resource_class = resource_class;
  621. } else if (p_dxil_type == DXIL_RES_SAMPLER) {
  622. uniform_d3d12.has_sampler = (uint32_t)true;
  623. } else {
  624. DEV_ASSERT(false && "Unknown resource class.");
  625. }
  626. found = true;
  627. }
  628. DEV_ASSERT(found);
  629. }
  630. }
  631. void RenderingShaderContainerD3D12::_nir_report_sc_bit_offset(uint32_t p_sc_id, uint64_t p_bit_offset, void *p_data) {
  632. const GodotNirCallbackUserData &user_data = *(GodotNirCallbackUserData *)p_data;
  633. [[maybe_unused]] bool found = false;
  634. for (int64_t i = 0; i < user_data.container->reflection_specialization_data.size(); i++) {
  635. const ReflectionSpecializationData &sc = user_data.container->reflection_specialization_data[i];
  636. ReflectionSpecializationDataD3D12 &sc_d3d12 = user_data.container->reflection_specialization_data_d3d12.ptrw()[i];
  637. if (sc.constant_id != p_sc_id) {
  638. continue;
  639. }
  640. uint32_t offset_idx = SHADER_STAGES_BIT_OFFSET_INDICES[user_data.stage];
  641. DEV_ASSERT(sc_d3d12.stages_bit_offsets[offset_idx] == 0);
  642. sc_d3d12.stages_bit_offsets[offset_idx] = p_bit_offset;
  643. found = true;
  644. break;
  645. }
  646. DEV_ASSERT(found);
  647. }
  648. void RenderingShaderContainerD3D12::_nir_report_bitcode_bit_offset(uint64_t p_bit_offset, void *p_data) {
  649. DEV_ASSERT(p_bit_offset % 8 == 0);
  650. const GodotNirCallbackUserData &user_data = *(GodotNirCallbackUserData *)p_data;
  651. uint32_t offset_idx = SHADER_STAGES_BIT_OFFSET_INDICES[user_data.stage];
  652. for (int64_t i = 0; i < user_data.container->reflection_specialization_data.size(); i++) {
  653. ReflectionSpecializationDataD3D12 &sc_d3d12 = user_data.container->reflection_specialization_data_d3d12.ptrw()[i];
  654. if (sc_d3d12.stages_bit_offsets[offset_idx] == 0) {
  655. // This SC has been optimized out from this stage.
  656. continue;
  657. }
  658. sc_d3d12.stages_bit_offsets[offset_idx] += p_bit_offset;
  659. }
  660. }
  661. #endif
  662. void RenderingShaderContainerD3D12::_set_from_shader_reflection_post(const RenderingDeviceCommons::ShaderReflection &p_reflection) {
  663. reflection_binding_set_uniforms_data_d3d12.resize(reflection_binding_set_uniforms_data.size());
  664. reflection_specialization_data_d3d12.resize(reflection_specialization_data.size());
  665. // Sort bindings inside each uniform set. This guarantees the root signature will be generated in the correct order.
  666. SortArray<ReflectionBindingData> sorter;
  667. uint32_t binding_start = 0;
  668. for (uint32_t i = 0; i < reflection_binding_set_uniforms_count.size(); i++) {
  669. uint32_t uniform_count = reflection_binding_set_uniforms_count[i];
  670. if (uniform_count > 0) {
  671. sorter.sort(&reflection_binding_set_uniforms_data.ptrw()[binding_start], uniform_count);
  672. binding_start += uniform_count;
  673. }
  674. }
  675. }
  676. bool RenderingShaderContainerD3D12::_set_code_from_spirv(Span<ReflectedShaderStage> p_spirv) {
  677. #if NIR_ENABLED
  678. reflection_data_d3d12.nir_runtime_data_root_param_idx = UINT32_MAX;
  679. for (int64_t i = 0; i < reflection_specialization_data.size(); i++) {
  680. 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.");
  681. reflection_data_d3d12.spirv_specialization_constants_ids_mask |= (1 << reflection_specialization_data[i].constant_id);
  682. }
  683. // Translate SPIR-V shaders to DXIL, and collect shader info from the new representation.
  684. HashMap<RenderingDeviceCommons::ShaderStage, Vector<uint8_t>> dxil_blobs;
  685. Vector<RenderingDeviceCommons::ShaderStage> stages;
  686. BitField<RenderingDeviceCommons::ShaderStage> stages_processed = {};
  687. if (!_convert_spirv_to_dxil(p_spirv, dxil_blobs, stages, stages_processed)) {
  688. return false;
  689. }
  690. // Patch with default values of specialization constants.
  691. DEV_ASSERT(reflection_specialization_data.size() == reflection_specialization_data_d3d12.size());
  692. for (int32_t i = 0; i < reflection_specialization_data.size(); i++) {
  693. const ReflectionSpecializationData &sc = reflection_specialization_data[i];
  694. const ReflectionSpecializationDataD3D12 &sc_d3d12 = reflection_specialization_data_d3d12[i];
  695. RenderingDXIL::patch_specialization_constant((RenderingDeviceCommons::PipelineSpecializationConstantType)(sc.type), &sc.int_value, sc_d3d12.stages_bit_offsets, dxil_blobs, true);
  696. }
  697. // Sign.
  698. uint32_t shader_index = 0;
  699. for (KeyValue<RenderingDeviceCommons::ShaderStage, Vector<uint8_t>> &E : dxil_blobs) {
  700. RenderingDXIL::sign_bytecode(E.key, E.value);
  701. }
  702. // Store compressed DXIL blobs as the shaders.
  703. shaders.resize(p_spirv.size());
  704. for (int64_t i = 0; i < shaders.size(); i++) {
  705. const PackedByteArray &dxil_bytes = dxil_blobs[stages[i]];
  706. RenderingShaderContainer::Shader &shader = shaders.ptrw()[i];
  707. uint32_t compressed_size = 0;
  708. shader.shader_stage = stages[i];
  709. shader.code_decompressed_size = dxil_bytes.size();
  710. shader.code_compressed_bytes.resize(dxil_bytes.size());
  711. bool compressed = compress_code(dxil_bytes.ptr(), dxil_bytes.size(), shader.code_compressed_bytes.ptrw(), &compressed_size, &shader.code_compression_flags);
  712. ERR_FAIL_COND_V_MSG(!compressed, false, vformat("Failed to compress native code to native for SPIR-V #%d.", shader_index));
  713. shader.code_compressed_bytes.resize(compressed_size);
  714. }
  715. if (!_generate_root_signature(stages_processed)) {
  716. return false;
  717. }
  718. return true;
  719. #else
  720. ERR_FAIL_V_MSG(false, "Shader compilation is not supported at runtime without NIR.");
  721. #endif
  722. }
  723. RenderingShaderContainerD3D12::RenderingShaderContainerD3D12() {
  724. // Default empty constructor.
  725. }
  726. RenderingShaderContainerD3D12::RenderingShaderContainerD3D12(void *p_lib_d3d12) {
  727. lib_d3d12 = p_lib_d3d12;
  728. }
  729. RenderingShaderContainerD3D12::ShaderReflectionD3D12 RenderingShaderContainerD3D12::get_shader_reflection_d3d12() const {
  730. ShaderReflectionD3D12 reflection;
  731. reflection.spirv_specialization_constants_ids_mask = reflection_data_d3d12.spirv_specialization_constants_ids_mask;
  732. reflection.dxil_push_constant_stages = reflection_data_d3d12.dxil_push_constant_stages;
  733. reflection.nir_runtime_data_root_param_idx = reflection_data_d3d12.nir_runtime_data_root_param_idx;
  734. reflection.reflection_specialization_data_d3d12 = reflection_specialization_data_d3d12;
  735. reflection.root_signature_bytes = root_signature_bytes;
  736. reflection.root_signature_crc = root_signature_crc;
  737. // Transform data vector into a vector of vectors that's easier to user.
  738. uint32_t uniform_index = 0;
  739. reflection.reflection_binding_set_uniforms_d3d12.resize(reflection_binding_set_uniforms_count.size());
  740. for (int64_t i = 0; i < reflection.reflection_binding_set_uniforms_d3d12.size(); i++) {
  741. Vector<ReflectionBindingDataD3D12> &uniforms = reflection.reflection_binding_set_uniforms_d3d12.ptrw()[i];
  742. uniforms.resize(reflection_binding_set_uniforms_count[i]);
  743. for (int64_t j = 0; j < uniforms.size(); j++) {
  744. uniforms.ptrw()[j] = reflection_binding_set_uniforms_data_d3d12[uniform_index];
  745. uniform_index++;
  746. }
  747. }
  748. return reflection;
  749. }
  750. // RenderingShaderContainerFormatD3D12
  751. void RenderingShaderContainerFormatD3D12::set_lib_d3d12(void *p_lib_d3d12) {
  752. lib_d3d12 = p_lib_d3d12;
  753. }
  754. Ref<RenderingShaderContainer> RenderingShaderContainerFormatD3D12::create_container() const {
  755. return memnew(RenderingShaderContainerD3D12(lib_d3d12));
  756. }
  757. RenderingDeviceCommons::ShaderLanguageVersion RenderingShaderContainerFormatD3D12::get_shader_language_version() const {
  758. // NIR-DXIL is Vulkan 1.1-conformant.
  759. return SHADER_LANGUAGE_VULKAN_VERSION_1_1;
  760. }
  761. RenderingDeviceCommons::ShaderSpirvVersion RenderingShaderContainerFormatD3D12::get_shader_spirv_version() const {
  762. // The SPIR-V part of Mesa supports 1.6, but:
  763. // - SPIRV-Reflect won't be able to parse the compute workgroup size.
  764. // - We want to play it safe with NIR-DXIL.
  765. return SHADER_SPIRV_VERSION_1_5;
  766. }
  767. RenderingShaderContainerFormatD3D12::RenderingShaderContainerFormatD3D12() {}
  768. RenderingShaderContainerFormatD3D12::~RenderingShaderContainerFormatD3D12() {}