rendering_shader_container_d3d12.cpp 38 KB

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