Path: blob/master/drivers/d3d12/rendering_shader_container_d3d12.cpp
9973 views
/**************************************************************************/1/* rendering_shader_container_d3d12.cpp */2/**************************************************************************/3/* This file is part of: */4/* GODOT ENGINE */5/* https://godotengine.org */6/**************************************************************************/7/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */8/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */9/* */10/* Permission is hereby granted, free of charge, to any person obtaining */11/* a copy of this software and associated documentation files (the */12/* "Software"), to deal in the Software without restriction, including */13/* without limitation the rights to use, copy, modify, merge, publish, */14/* distribute, sublicense, and/or sell copies of the Software, and to */15/* permit persons to whom the Software is furnished to do so, subject to */16/* the following conditions: */17/* */18/* The above copyright notice and this permission notice shall be */19/* included in all copies or substantial portions of the Software. */20/* */21/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */22/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */23/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */24/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */25/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */26/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */27/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */28/**************************************************************************/2930#include "rendering_shader_container_d3d12.h"3132#include "core/templates/sort_array.h"3334#include "dxil_hash.h"3536#include <zlib.h>3738#ifndef _MSC_VER39// Match current version used by MinGW, MSVC and Direct3D 12 headers use 500.40#define __REQUIRED_RPCNDR_H_VERSION__ 47541#endif4243#include <d3dx12.h>44#include <dxgi1_6.h>45#define D3D12MA_D3D12_HEADERS_ALREADY_INCLUDED46#include <D3D12MemAlloc.h>4748#include <wrl/client.h>4950#if defined(_MSC_VER) && defined(MemoryBarrier)51// Annoying define from winnt.h. Reintroduced by some of the headers above.52#undef MemoryBarrier53#endif5455GODOT_GCC_WARNING_PUSH56GODOT_GCC_WARNING_IGNORE("-Wimplicit-fallthrough")57GODOT_GCC_WARNING_IGNORE("-Wlogical-not-parentheses")58GODOT_GCC_WARNING_IGNORE("-Wmissing-field-initializers")59GODOT_GCC_WARNING_IGNORE("-Wnon-virtual-dtor")60GODOT_GCC_WARNING_IGNORE("-Wshadow")61GODOT_GCC_WARNING_IGNORE("-Wswitch")62GODOT_CLANG_WARNING_PUSH63GODOT_CLANG_WARNING_IGNORE("-Wimplicit-fallthrough")64GODOT_CLANG_WARNING_IGNORE("-Wlogical-not-parentheses")65GODOT_CLANG_WARNING_IGNORE("-Wmissing-field-initializers")66GODOT_CLANG_WARNING_IGNORE("-Wnon-virtual-dtor")67GODOT_CLANG_WARNING_IGNORE("-Wstring-plus-int")68GODOT_CLANG_WARNING_IGNORE("-Wswitch")69GODOT_MSVC_WARNING_PUSH70GODOT_MSVC_WARNING_IGNORE(4200) // "nonstandard extension used: zero-sized array in struct/union".71GODOT_MSVC_WARNING_IGNORE(4806) // "'&': unsafe operation: no value of type 'bool' promoted to type 'uint32_t' can equal the given constant".7273#include <nir_spirv.h>74#include <nir_to_dxil.h>75#include <spirv_to_dxil.h>76extern "C" {77#include <dxil_spirv_nir.h>78}7980GODOT_GCC_WARNING_POP81GODOT_CLANG_WARNING_POP82GODOT_MSVC_WARNING_POP8384static D3D12_SHADER_VISIBILITY stages_to_d3d12_visibility(uint32_t p_stages_mask) {85switch (p_stages_mask) {86case RenderingDeviceCommons::SHADER_STAGE_VERTEX_BIT:87return D3D12_SHADER_VISIBILITY_VERTEX;88case RenderingDeviceCommons::SHADER_STAGE_FRAGMENT_BIT:89return D3D12_SHADER_VISIBILITY_PIXEL;90default:91return D3D12_SHADER_VISIBILITY_ALL;92}93}9495uint32_t RenderingDXIL::patch_specialization_constant(96RenderingDeviceCommons::PipelineSpecializationConstantType p_type,97const void *p_value,98const uint64_t (&p_stages_bit_offsets)[D3D12_BITCODE_OFFSETS_NUM_STAGES],99HashMap<RenderingDeviceCommons::ShaderStage, Vector<uint8_t>> &r_stages_bytecodes,100bool p_is_first_patch) {101uint32_t patch_val = 0;102switch (p_type) {103case RenderingDeviceCommons::PIPELINE_SPECIALIZATION_CONSTANT_TYPE_INT: {104uint32_t int_value = *((const int *)p_value);105ERR_FAIL_COND_V(int_value & (1 << 31), 0);106patch_val = int_value;107} break;108case RenderingDeviceCommons::PIPELINE_SPECIALIZATION_CONSTANT_TYPE_BOOL: {109bool bool_value = *((const bool *)p_value);110patch_val = (uint32_t)bool_value;111} break;112case RenderingDeviceCommons::PIPELINE_SPECIALIZATION_CONSTANT_TYPE_FLOAT: {113uint32_t int_value = *((const int *)p_value);114ERR_FAIL_COND_V(int_value & (1 << 31), 0);115patch_val = (int_value >> 1);116} break;117}118// For VBR encoding to encode the number of bits we expect (32), we need to set the MSB unconditionally.119// However, signed VBR moves the MSB to the LSB, so setting the MSB to 1 wouldn't help. Therefore,120// the bit we set to 1 is the one at index 30.121patch_val |= (1 << 30);122patch_val <<= 1; // What signed VBR does.123124auto tamper_bits = [](uint8_t *p_start, uint64_t p_bit_offset, uint64_t p_tb_value) -> uint64_t {125uint64_t original = 0;126uint32_t curr_input_byte = p_bit_offset / 8;127uint8_t curr_input_bit = p_bit_offset % 8;128auto get_curr_input_bit = [&]() -> bool {129return ((p_start[curr_input_byte] >> curr_input_bit) & 1);130};131auto move_to_next_input_bit = [&]() {132if (curr_input_bit == 7) {133curr_input_bit = 0;134curr_input_byte++;135} else {136curr_input_bit++;137}138};139auto tamper_input_bit = [&](bool p_new_bit) {140p_start[curr_input_byte] &= ~((uint8_t)1 << curr_input_bit);141if (p_new_bit) {142p_start[curr_input_byte] |= (uint8_t)1 << curr_input_bit;143}144};145uint8_t value_bit_idx = 0;146for (uint32_t i = 0; i < 5; i++) { // 32 bits take 5 full bytes in VBR.147for (uint32_t j = 0; j < 7; j++) {148bool input_bit = get_curr_input_bit();149original |= (uint64_t)(input_bit ? 1 : 0) << value_bit_idx;150tamper_input_bit((p_tb_value >> value_bit_idx) & 1);151move_to_next_input_bit();152value_bit_idx++;153}154#ifdef DEV_ENABLED155bool input_bit = get_curr_input_bit();156DEV_ASSERT((i < 4 && input_bit) || (i == 4 && !input_bit));157#endif158move_to_next_input_bit();159}160return original;161};162uint32_t stages_patched_mask = 0;163for (int stage = 0; stage < RenderingDeviceCommons::SHADER_STAGE_MAX; stage++) {164if (!r_stages_bytecodes.has((RenderingDeviceCommons::ShaderStage)stage)) {165continue;166}167168uint64_t offset = p_stages_bit_offsets[RenderingShaderContainerD3D12::SHADER_STAGES_BIT_OFFSET_INDICES[stage]];169if (offset == 0) {170// This constant does not appear at this stage.171continue;172}173174Vector<uint8_t> &bytecode = r_stages_bytecodes[(RenderingDeviceCommons::ShaderStage)stage];175#ifdef DEV_ENABLED176uint64_t orig_patch_val = tamper_bits(bytecode.ptrw(), offset, patch_val);177// Checking against the value the NIR patch should have set.178DEV_ASSERT(!p_is_first_patch || ((orig_patch_val >> 1) & GODOT_NIR_SC_SENTINEL_MAGIC_MASK) == GODOT_NIR_SC_SENTINEL_MAGIC);179uint64_t readback_patch_val = tamper_bits(bytecode.ptrw(), offset, patch_val);180DEV_ASSERT(readback_patch_val == patch_val);181#else182tamper_bits(bytecode.ptrw(), offset, patch_val);183#endif184185stages_patched_mask |= (1 << stage);186}187188return stages_patched_mask;189}190191void RenderingDXIL::sign_bytecode(RenderingDeviceCommons::ShaderStage p_stage, Vector<uint8_t> &r_dxil_blob) {192uint8_t *w = r_dxil_blob.ptrw();193compute_dxil_hash(w + 20, r_dxil_blob.size() - 20, w + 4);194}195196// RenderingShaderContainerD3D12197198uint32_t RenderingShaderContainerD3D12::_format() const {199return 0x43443344;200}201202uint32_t RenderingShaderContainerD3D12::_format_version() const {203return FORMAT_VERSION;204}205206uint32_t RenderingShaderContainerD3D12::_from_bytes_reflection_extra_data(const uint8_t *p_bytes) {207reflection_data_d3d12 = *(const ReflectionDataD3D12 *)(p_bytes);208return sizeof(ReflectionDataD3D12);209}210211uint32_t RenderingShaderContainerD3D12::_from_bytes_reflection_binding_uniform_extra_data_start(const uint8_t *p_bytes) {212reflection_binding_set_uniforms_data_d3d12.resize(reflection_binding_set_uniforms_data.size());213return 0;214}215216uint32_t RenderingShaderContainerD3D12::_from_bytes_reflection_binding_uniform_extra_data(const uint8_t *p_bytes, uint32_t p_index) {217reflection_binding_set_uniforms_data_d3d12.ptrw()[p_index] = *(const ReflectionBindingDataD3D12 *)(p_bytes);218return sizeof(ReflectionBindingDataD3D12);219}220221uint32_t RenderingShaderContainerD3D12::_from_bytes_reflection_specialization_extra_data_start(const uint8_t *p_bytes) {222reflection_specialization_data_d3d12.resize(reflection_specialization_data.size());223return 0;224}225226uint32_t RenderingShaderContainerD3D12::_from_bytes_reflection_specialization_extra_data(const uint8_t *p_bytes, uint32_t p_index) {227reflection_specialization_data_d3d12.ptrw()[p_index] = *(const ReflectionSpecializationDataD3D12 *)(p_bytes);228return sizeof(ReflectionSpecializationDataD3D12);229}230231uint32_t RenderingShaderContainerD3D12::_from_bytes_footer_extra_data(const uint8_t *p_bytes) {232ContainerFooterD3D12 footer = *(const ContainerFooterD3D12 *)(p_bytes);233root_signature_crc = footer.root_signature_crc;234root_signature_bytes.resize(footer.root_signature_length);235memcpy(root_signature_bytes.ptrw(), p_bytes + sizeof(ContainerFooterD3D12), root_signature_bytes.size());236return sizeof(ContainerFooterD3D12) + footer.root_signature_length;237}238239uint32_t RenderingShaderContainerD3D12::_to_bytes_reflection_extra_data(uint8_t *p_bytes) const {240if (p_bytes != nullptr) {241*(ReflectionDataD3D12 *)(p_bytes) = reflection_data_d3d12;242}243244return sizeof(ReflectionDataD3D12);245}246247uint32_t RenderingShaderContainerD3D12::_to_bytes_reflection_binding_uniform_extra_data(uint8_t *p_bytes, uint32_t p_index) const {248if (p_bytes != nullptr) {249*(ReflectionBindingDataD3D12 *)(p_bytes) = reflection_binding_set_uniforms_data_d3d12[p_index];250}251252return sizeof(ReflectionBindingDataD3D12);253}254255uint32_t RenderingShaderContainerD3D12::_to_bytes_reflection_specialization_extra_data(uint8_t *p_bytes, uint32_t p_index) const {256if (p_bytes != nullptr) {257*(ReflectionSpecializationDataD3D12 *)(p_bytes) = reflection_specialization_data_d3d12[p_index];258}259260return sizeof(ReflectionSpecializationDataD3D12);261}262263uint32_t RenderingShaderContainerD3D12::_to_bytes_footer_extra_data(uint8_t *p_bytes) const {264if (p_bytes != nullptr) {265ContainerFooterD3D12 &footer = *(ContainerFooterD3D12 *)(p_bytes);266footer.root_signature_length = root_signature_bytes.size();267footer.root_signature_crc = root_signature_crc;268memcpy(p_bytes + sizeof(ContainerFooterD3D12), root_signature_bytes.ptr(), root_signature_bytes.size());269}270271return sizeof(ContainerFooterD3D12) + root_signature_bytes.size();272}273274#if NIR_ENABLED275bool 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) {276r_stages_processed.clear();277278dxil_spirv_runtime_conf dxil_runtime_conf = {};279dxil_runtime_conf.runtime_data_cbv.base_shader_register = RUNTIME_DATA_REGISTER;280dxil_runtime_conf.push_constant_cbv.base_shader_register = ROOT_CONSTANT_REGISTER;281dxil_runtime_conf.zero_based_vertex_instance_id = true;282dxil_runtime_conf.zero_based_compute_workgroup_id = true;283dxil_runtime_conf.declared_read_only_images_as_srvs = true;284285// Making this explicit to let maintainers know that in practice this didn't improve performance,286// probably because data generated by one shader and consumed by another one forces the resource287// to transition from UAV to SRV, and back, instead of being an UAV all the time.288// In case someone wants to try, care must be taken so in case of incompatible bindings across stages289// happen as a result, all the stages are re-translated. That can happen if, for instance, a stage only290// uses an allegedly writable resource only for reading but the next stage doesn't.291dxil_runtime_conf.inferred_read_only_images_as_srvs = false;292293// Translate SPIR-V to NIR.294for (int64_t i = 0; i < p_spirv.size(); i++) {295RenderingDeviceCommons::ShaderStage stage = p_spirv[i].shader_stage;296RenderingDeviceCommons::ShaderStage stage_flag = (RenderingDeviceCommons::ShaderStage)(1 << stage);297r_stages.push_back(stage);298r_stages_processed.set_flag(stage_flag);299300const char *entry_point = "main";301static const gl_shader_stage SPIRV_TO_MESA_STAGES[RenderingDeviceCommons::SHADER_STAGE_MAX] = {302MESA_SHADER_VERTEX, // SHADER_STAGE_VERTEX303MESA_SHADER_FRAGMENT, // SHADER_STAGE_FRAGMENT304MESA_SHADER_TESS_CTRL, // SHADER_STAGE_TESSELATION_CONTROL305MESA_SHADER_TESS_EVAL, // SHADER_STAGE_TESSELATION_EVALUATION306MESA_SHADER_COMPUTE, // SHADER_STAGE_COMPUTE307};308309nir_shader *shader = spirv_to_nir(310(const uint32_t *)(p_spirv[i].spirv.ptr()),311p_spirv[i].spirv.size() / sizeof(uint32_t),312nullptr,3130,314SPIRV_TO_MESA_STAGES[stage],315entry_point,316dxil_spirv_nir_get_spirv_options(),317p_compiler_options);318319ERR_FAIL_NULL_V_MSG(shader, false, "Shader translation (step 1) at stage " + String(RenderingDeviceCommons::SHADER_STAGE_NAMES[stage]) + " failed.");320321#ifdef DEV_ENABLED322nir_validate_shader(shader, "Validate before feeding NIR to the DXIL compiler");323#endif324325if (stage == RenderingDeviceCommons::SHADER_STAGE_VERTEX) {326dxil_runtime_conf.yz_flip.y_mask = 0xffff;327dxil_runtime_conf.yz_flip.mode = DXIL_SPIRV_Y_FLIP_UNCONDITIONAL;328} else {329dxil_runtime_conf.yz_flip.y_mask = 0;330dxil_runtime_conf.yz_flip.mode = DXIL_SPIRV_YZ_FLIP_NONE;331}332333dxil_spirv_nir_prep(shader);334bool requires_runtime_data = false;335dxil_spirv_nir_passes(shader, &dxil_runtime_conf, &requires_runtime_data);336337r_stages_nir_shaders[stage] = shader;338}339340// Link NIR shaders.341for (int i = RenderingDeviceCommons::SHADER_STAGE_MAX - 1; i >= 0; i--) {342if (!r_stages_nir_shaders.has(i)) {343continue;344}345nir_shader *shader = r_stages_nir_shaders[i];346nir_shader *prev_shader = nullptr;347for (int j = i - 1; j >= 0; j--) {348if (r_stages_nir_shaders.has(j)) {349prev_shader = r_stages_nir_shaders[j];350break;351}352}353// There is a bug in the Direct3D runtime during creation of a PSO with view instancing. If a fragment354// shader uses front/back face detection (SV_IsFrontFace), its signature must include the pixel position355// builtin variable (SV_Position), otherwise an Internal Runtime error will occur.356if (i == RenderingDeviceCommons::SHADER_STAGE_FRAGMENT) {357const bool use_front_face =358nir_find_variable_with_location(shader, nir_var_shader_in, VARYING_SLOT_FACE) ||359(shader->info.inputs_read & VARYING_BIT_FACE) ||360nir_find_variable_with_location(shader, nir_var_system_value, SYSTEM_VALUE_FRONT_FACE) ||361BITSET_TEST(shader->info.system_values_read, SYSTEM_VALUE_FRONT_FACE);362const bool use_position =363nir_find_variable_with_location(shader, nir_var_shader_in, VARYING_SLOT_POS) ||364(shader->info.inputs_read & VARYING_BIT_POS) ||365nir_find_variable_with_location(shader, nir_var_system_value, SYSTEM_VALUE_FRAG_COORD) ||366BITSET_TEST(shader->info.system_values_read, SYSTEM_VALUE_FRAG_COORD);367if (use_front_face && !use_position) {368nir_variable *const pos = nir_variable_create(shader, nir_var_shader_in, glsl_vec4_type(), "gl_FragCoord");369pos->data.location = VARYING_SLOT_POS;370shader->info.inputs_read |= VARYING_BIT_POS;371}372}373if (prev_shader) {374bool requires_runtime_data = {};375dxil_spirv_nir_link(shader, prev_shader, &dxil_runtime_conf, &requires_runtime_data);376}377}378379return true;380}381382struct GodotNirCallbackUserData {383RenderingShaderContainerD3D12 *container;384RenderingDeviceCommons::ShaderStage stage;385};386387static dxil_shader_model shader_model_d3d_to_dxil(D3D_SHADER_MODEL p_d3d_shader_model) {388static_assert(SHADER_MODEL_6_0 == 0x60000);389static_assert(SHADER_MODEL_6_3 == 0x60003);390static_assert(D3D_SHADER_MODEL_6_0 == 0x60);391static_assert(D3D_SHADER_MODEL_6_3 == 0x63);392return (dxil_shader_model)((p_d3d_shader_model >> 4) * 0x10000 + (p_d3d_shader_model & 0xf));393}394395bool 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) {396// Translate NIR to DXIL.397for (KeyValue<int, nir_shader *> it : p_stages_nir_shaders) {398RenderingDeviceCommons::ShaderStage stage = (RenderingDeviceCommons::ShaderStage)(it.key);399GodotNirCallbackUserData godot_nir_callback_user_data;400godot_nir_callback_user_data.container = this;401godot_nir_callback_user_data.stage = stage;402403GodotNirCallbacks godot_nir_callbacks = {};404godot_nir_callbacks.data = &godot_nir_callback_user_data;405godot_nir_callbacks.report_resource = _nir_report_resource;406godot_nir_callbacks.report_sc_bit_offset_fn = _nir_report_sc_bit_offset;407godot_nir_callbacks.report_bitcode_bit_offset_fn = _nir_report_bitcode_bit_offset;408409nir_to_dxil_options nir_to_dxil_options = {};410nir_to_dxil_options.environment = DXIL_ENVIRONMENT_VULKAN;411nir_to_dxil_options.shader_model_max = shader_model_d3d_to_dxil(D3D_SHADER_MODEL(REQUIRED_SHADER_MODEL));412nir_to_dxil_options.validator_version_max = NO_DXIL_VALIDATION;413nir_to_dxil_options.godot_nir_callbacks = &godot_nir_callbacks;414415dxil_logger logger = {};416logger.log = [](void *p_priv, const char *p_msg) {417#ifdef DEBUG_ENABLED418print_verbose(p_msg);419#endif420};421422blob dxil_blob = {};423bool ok = nir_to_dxil(it.value, &nir_to_dxil_options, &logger, &dxil_blob);424ERR_FAIL_COND_V_MSG(!ok, false, "Shader translation at stage " + String(RenderingDeviceCommons::SHADER_STAGE_NAMES[stage]) + " failed.");425426Vector<uint8_t> blob_copy;427blob_copy.resize(dxil_blob.size);428memcpy(blob_copy.ptrw(), dxil_blob.data, dxil_blob.size);429blob_finish(&dxil_blob);430r_dxil_blobs.insert(stage, blob_copy);431}432433return true;434}435436bool 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) {437r_dxil_blobs.clear();438439HashMap<int, nir_shader *> stages_nir_shaders;440auto free_nir_shaders = [&]() {441for (KeyValue<int, nir_shader *> &E : stages_nir_shaders) {442ralloc_free(E.value);443}444stages_nir_shaders.clear();445};446447// This structure must live as long as the shaders are alive.448nir_shader_compiler_options compiler_options = *dxil_get_nir_compiler_options();449compiler_options.lower_base_vertex = false;450451// This is based on spirv2dxil.c. May need updates when it changes.452// Also, this has to stay around until after linking.453if (!_convert_spirv_to_nir(p_spirv, &compiler_options, stages_nir_shaders, r_stages, r_stages_processed)) {454free_nir_shaders();455return false;456}457458if (!_convert_nir_to_dxil(stages_nir_shaders, r_stages_processed, r_dxil_blobs)) {459free_nir_shaders();460return false;461}462463free_nir_shaders();464return true;465}466467bool RenderingShaderContainerD3D12::_generate_root_signature(BitField<RenderingDeviceCommons::ShaderStage> p_stages_processed) {468// Root (push) constants.469LocalVector<D3D12_ROOT_PARAMETER1> root_params;470if (reflection_data_d3d12.dxil_push_constant_stages) {471CD3DX12_ROOT_PARAMETER1 push_constant;472push_constant.InitAsConstants(473reflection_data.push_constant_size / sizeof(uint32_t),474ROOT_CONSTANT_REGISTER,4750,476stages_to_d3d12_visibility(reflection_data_d3d12.dxil_push_constant_stages));477478root_params.push_back(push_constant);479}480481// NIR-DXIL runtime data.482if (reflection_data_d3d12.nir_runtime_data_root_param_idx == 1) { // Set above to 1 when discovering runtime data is needed.483DEV_ASSERT(!reflection_data.is_compute); // Could be supported if needed, but it's pointless as of now.484reflection_data_d3d12.nir_runtime_data_root_param_idx = root_params.size();485CD3DX12_ROOT_PARAMETER1 nir_runtime_data;486nir_runtime_data.InitAsConstants(487sizeof(dxil_spirv_vertex_runtime_data) / sizeof(uint32_t),488RUNTIME_DATA_REGISTER,4890,490D3D12_SHADER_VISIBILITY_VERTEX);491root_params.push_back(nir_runtime_data);492}493494// Descriptor tables (up to two per uniform set, for resources and/or samplers).495// These have to stay around until serialization!496struct TraceableDescriptorTable {497uint32_t stages_mask = {};498Vector<D3D12_DESCRIPTOR_RANGE1> ranges;499Vector<RootSignatureLocation *> root_signature_locations;500};501502uint32_t binding_start = 0;503Vector<TraceableDescriptorTable> resource_tables_maps;504Vector<TraceableDescriptorTable> sampler_tables_maps;505for (uint32_t i = 0; i < reflection_binding_set_uniforms_count.size(); i++) {506bool first_resource_in_set = true;507bool first_sampler_in_set = true;508uint32_t uniform_count = reflection_binding_set_uniforms_count[i];509for (uint32_t j = 0; j < uniform_count; j++) {510const ReflectionBindingData &uniform = reflection_binding_set_uniforms_data[binding_start + j];511ReflectionBindingDataD3D12 &uniform_d3d12 = reflection_binding_set_uniforms_data_d3d12.ptrw()[binding_start + j];512bool really_used = uniform_d3d12.dxil_stages != 0;513#ifdef DEV_ENABLED514bool anybody_home = (ResourceClass)(uniform_d3d12.resource_class) != RES_CLASS_INVALID || uniform_d3d12.has_sampler;515DEV_ASSERT(anybody_home == really_used);516#endif517if (!really_used) {518continue; // Existed in SPIR-V; went away in DXIL.519}520521auto insert_range = [](D3D12_DESCRIPTOR_RANGE_TYPE p_range_type,522uint32_t p_num_descriptors,523uint32_t p_dxil_register,524uint32_t p_dxil_stages_mask,525RootSignatureLocation *p_root_sig_locations,526Vector<TraceableDescriptorTable> &r_tables,527bool &r_first_in_set) {528if (r_first_in_set) {529r_tables.resize(r_tables.size() + 1);530r_first_in_set = false;531}532533TraceableDescriptorTable &table = r_tables.write[r_tables.size() - 1];534table.stages_mask |= p_dxil_stages_mask;535536CD3DX12_DESCRIPTOR_RANGE1 range;537// Due to the aliasing hack for SRV-UAV of different families,538// we can be causing an unintended change of data (sometimes the validation layers catch it).539D3D12_DESCRIPTOR_RANGE_FLAGS flags = D3D12_DESCRIPTOR_RANGE_FLAG_NONE;540if (p_range_type == D3D12_DESCRIPTOR_RANGE_TYPE_SRV || p_range_type == D3D12_DESCRIPTOR_RANGE_TYPE_UAV) {541flags = D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE;542} else if (p_range_type == D3D12_DESCRIPTOR_RANGE_TYPE_CBV) {543flags = D3D12_DESCRIPTOR_RANGE_FLAG_DATA_STATIC_WHILE_SET_AT_EXECUTE;544}545range.Init(p_range_type, p_num_descriptors, p_dxil_register, 0, flags);546547table.ranges.push_back(range);548table.root_signature_locations.push_back(p_root_sig_locations);549};550551uint32_t num_descriptors = 1;552D3D12_DESCRIPTOR_RANGE_TYPE resource_range_type = {};553switch ((ResourceClass)(uniform_d3d12.resource_class)) {554case RES_CLASS_INVALID: {555num_descriptors = uniform.length;556DEV_ASSERT(uniform_d3d12.has_sampler);557} break;558case RES_CLASS_CBV: {559resource_range_type = D3D12_DESCRIPTOR_RANGE_TYPE_CBV;560DEV_ASSERT(!uniform_d3d12.has_sampler);561} break;562case RES_CLASS_SRV: {563resource_range_type = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;564num_descriptors = MAX(1u, uniform.length); // An unbound R/O buffer is reflected as zero-size.565} break;566case RES_CLASS_UAV: {567resource_range_type = D3D12_DESCRIPTOR_RANGE_TYPE_UAV;568num_descriptors = MAX(1u, uniform.length); // An unbound R/W buffer is reflected as zero-size.569DEV_ASSERT(!uniform_d3d12.has_sampler);570} break;571}572573uint32_t dxil_register = i * GODOT_NIR_DESCRIPTOR_SET_MULTIPLIER + uniform.binding * GODOT_NIR_BINDING_MULTIPLIER;574if (uniform_d3d12.resource_class != RES_CLASS_INVALID) {575insert_range(576resource_range_type,577num_descriptors,578dxil_register,579uniform_d3d12.dxil_stages,580&uniform_d3d12.root_signature_locations[RS_LOC_TYPE_RESOURCE],581resource_tables_maps,582first_resource_in_set);583}584585if (uniform_d3d12.has_sampler) {586insert_range(587D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER,588num_descriptors,589dxil_register,590uniform_d3d12.dxil_stages,591&uniform_d3d12.root_signature_locations[RS_LOC_TYPE_SAMPLER],592sampler_tables_maps,593first_sampler_in_set);594}595}596597binding_start += uniform_count;598}599600auto make_descriptor_tables = [&root_params](const Vector<TraceableDescriptorTable> &p_tables) {601for (const TraceableDescriptorTable &table : p_tables) {602D3D12_SHADER_VISIBILITY visibility = stages_to_d3d12_visibility(table.stages_mask);603DEV_ASSERT(table.ranges.size() == table.root_signature_locations.size());604for (int i = 0; i < table.ranges.size(); i++) {605// By now we know very well which root signature location corresponds to the pointed uniform.606table.root_signature_locations[i]->root_param_index = root_params.size();607table.root_signature_locations[i]->range_index = i;608}609610CD3DX12_ROOT_PARAMETER1 root_table;611root_table.InitAsDescriptorTable(table.ranges.size(), table.ranges.ptr(), visibility);612root_params.push_back(root_table);613}614};615616make_descriptor_tables(resource_tables_maps);617make_descriptor_tables(sampler_tables_maps);618619CD3DX12_VERSIONED_ROOT_SIGNATURE_DESC root_sig_desc = {};620D3D12_ROOT_SIGNATURE_FLAGS root_sig_flags =621D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS |622D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS |623D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS |624D3D12_ROOT_SIGNATURE_FLAG_DENY_AMPLIFICATION_SHADER_ROOT_ACCESS |625D3D12_ROOT_SIGNATURE_FLAG_DENY_MESH_SHADER_ROOT_ACCESS;626627if (!p_stages_processed.has_flag(RenderingDeviceCommons::SHADER_STAGE_VERTEX_BIT)) {628root_sig_flags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_VERTEX_SHADER_ROOT_ACCESS;629}630631if (!p_stages_processed.has_flag(RenderingDeviceCommons::SHADER_STAGE_FRAGMENT_BIT)) {632root_sig_flags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS;633}634635if (reflection_data.vertex_input_mask) {636root_sig_flags |= D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;637}638639root_sig_desc.Init_1_1(root_params.size(), root_params.ptr(), 0, nullptr, root_sig_flags);640641// Create and store the root signature and its CRC32.642ID3DBlob *error_blob = nullptr;643ID3DBlob *root_sig_blob = nullptr;644HRESULT res = D3DX12SerializeVersionedRootSignature(HMODULE(lib_d3d12), &root_sig_desc, D3D_ROOT_SIGNATURE_VERSION_1_1, &root_sig_blob, &error_blob);645if (SUCCEEDED(res)) {646root_signature_bytes.resize(root_sig_blob->GetBufferSize());647memcpy(root_signature_bytes.ptrw(), root_sig_blob->GetBufferPointer(), root_sig_blob->GetBufferSize());648649root_signature_crc = crc32(0, nullptr, 0);650root_signature_crc = crc32(root_signature_crc, (const Bytef *)root_sig_blob->GetBufferPointer(), root_sig_blob->GetBufferSize());651652return true;653} else {654if (root_sig_blob != nullptr) {655root_sig_blob->Release();656}657658String error_string;659if (error_blob != nullptr) {660error_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())));661error_blob->Release();662} else {663error_string = vformat("Serialization of root signature failed with error 0x%08ux", uint32_t(res));664}665666ERR_FAIL_V_MSG(false, error_string);667}668}669670void RenderingShaderContainerD3D12::_nir_report_resource(uint32_t p_register, uint32_t p_space, uint32_t p_dxil_type, void *p_data) {671const GodotNirCallbackUserData &user_data = *(GodotNirCallbackUserData *)p_data;672673// Types based on Mesa's dxil_container.h.674static const uint32_t DXIL_RES_SAMPLER = 1;675static const ResourceClass DXIL_TYPE_TO_CLASS[] = {676RES_CLASS_INVALID, // DXIL_RES_INVALID677RES_CLASS_INVALID, // DXIL_RES_SAMPLER678RES_CLASS_CBV, // DXIL_RES_CBV679RES_CLASS_SRV, // DXIL_RES_SRV_TYPED680RES_CLASS_SRV, // DXIL_RES_SRV_RAW681RES_CLASS_SRV, // DXIL_RES_SRV_STRUCTURED682RES_CLASS_UAV, // DXIL_RES_UAV_TYPED683RES_CLASS_UAV, // DXIL_RES_UAV_RAW684RES_CLASS_UAV, // DXIL_RES_UAV_STRUCTURED685RES_CLASS_INVALID, // DXIL_RES_UAV_STRUCTURED_WITH_COUNTER686};687688DEV_ASSERT(p_dxil_type < ARRAY_SIZE(DXIL_TYPE_TO_CLASS));689ResourceClass resource_class = DXIL_TYPE_TO_CLASS[p_dxil_type];690691if (p_register == ROOT_CONSTANT_REGISTER && p_space == 0) {692DEV_ASSERT(resource_class == RES_CLASS_CBV);693user_data.container->reflection_data_d3d12.dxil_push_constant_stages |= (1 << user_data.stage);694} else if (p_register == RUNTIME_DATA_REGISTER && p_space == 0) {695DEV_ASSERT(resource_class == RES_CLASS_CBV);696user_data.container->reflection_data_d3d12.nir_runtime_data_root_param_idx = 1; // Temporary, to be determined later.697} else {698DEV_ASSERT(p_space == 0);699700uint32_t set = p_register / GODOT_NIR_DESCRIPTOR_SET_MULTIPLIER;701uint32_t binding = (p_register % GODOT_NIR_DESCRIPTOR_SET_MULTIPLIER) / GODOT_NIR_BINDING_MULTIPLIER;702703DEV_ASSERT(set < (uint32_t)user_data.container->reflection_binding_set_uniforms_count.size());704705uint32_t binding_start = 0;706for (uint32_t i = 0; i < set; i++) {707binding_start += user_data.container->reflection_binding_set_uniforms_count[i];708}709710[[maybe_unused]] bool found = false;711for (uint32_t i = 0; i < user_data.container->reflection_binding_set_uniforms_count[set]; i++) {712const ReflectionBindingData &uniform = user_data.container->reflection_binding_set_uniforms_data[binding_start + i];713ReflectionBindingDataD3D12 &uniform_d3d12 = user_data.container->reflection_binding_set_uniforms_data_d3d12.ptrw()[binding_start + i];714if (uniform.binding != binding) {715continue;716}717718uniform_d3d12.dxil_stages |= (1 << user_data.stage);719if (resource_class != RES_CLASS_INVALID) {720DEV_ASSERT(uniform_d3d12.resource_class == (uint32_t)RES_CLASS_INVALID || uniform_d3d12.resource_class == (uint32_t)resource_class);721uniform_d3d12.resource_class = resource_class;722} else if (p_dxil_type == DXIL_RES_SAMPLER) {723uniform_d3d12.has_sampler = (uint32_t)true;724} else {725DEV_ASSERT(false && "Unknown resource class.");726}727found = true;728}729730DEV_ASSERT(found);731}732}733734void RenderingShaderContainerD3D12::_nir_report_sc_bit_offset(uint32_t p_sc_id, uint64_t p_bit_offset, void *p_data) {735const GodotNirCallbackUserData &user_data = *(GodotNirCallbackUserData *)p_data;736[[maybe_unused]] bool found = false;737for (int64_t i = 0; i < user_data.container->reflection_specialization_data.size(); i++) {738const ReflectionSpecializationData &sc = user_data.container->reflection_specialization_data[i];739ReflectionSpecializationDataD3D12 &sc_d3d12 = user_data.container->reflection_specialization_data_d3d12.ptrw()[i];740if (sc.constant_id != p_sc_id) {741continue;742}743744uint32_t offset_idx = SHADER_STAGES_BIT_OFFSET_INDICES[user_data.stage];745DEV_ASSERT(sc_d3d12.stages_bit_offsets[offset_idx] == 0);746sc_d3d12.stages_bit_offsets[offset_idx] = p_bit_offset;747found = true;748break;749}750751DEV_ASSERT(found);752}753754void RenderingShaderContainerD3D12::_nir_report_bitcode_bit_offset(uint64_t p_bit_offset, void *p_data) {755DEV_ASSERT(p_bit_offset % 8 == 0);756757const GodotNirCallbackUserData &user_data = *(GodotNirCallbackUserData *)p_data;758uint32_t offset_idx = SHADER_STAGES_BIT_OFFSET_INDICES[user_data.stage];759for (int64_t i = 0; i < user_data.container->reflection_specialization_data.size(); i++) {760ReflectionSpecializationDataD3D12 &sc_d3d12 = user_data.container->reflection_specialization_data_d3d12.ptrw()[i];761if (sc_d3d12.stages_bit_offsets[offset_idx] == 0) {762// This SC has been optimized out from this stage.763continue;764}765766sc_d3d12.stages_bit_offsets[offset_idx] += p_bit_offset;767}768}769#endif770771void RenderingShaderContainerD3D12::_set_from_shader_reflection_post(const String &p_shader_name, const RenderingDeviceCommons::ShaderReflection &p_reflection) {772reflection_binding_set_uniforms_data_d3d12.resize(reflection_binding_set_uniforms_data.size());773reflection_specialization_data_d3d12.resize(reflection_specialization_data.size());774775// Sort bindings inside each uniform set. This guarantees the root signature will be generated in the correct order.776SortArray<ReflectionBindingData> sorter;777uint32_t binding_start = 0;778for (uint32_t i = 0; i < reflection_binding_set_uniforms_count.size(); i++) {779uint32_t uniform_count = reflection_binding_set_uniforms_count[i];780if (uniform_count > 0) {781sorter.sort(&reflection_binding_set_uniforms_data.ptrw()[binding_start], uniform_count);782binding_start += uniform_count;783}784}785}786787bool RenderingShaderContainerD3D12::_set_code_from_spirv(const Vector<RenderingDeviceCommons::ShaderStageSPIRVData> &p_spirv) {788#if NIR_ENABLED789reflection_data_d3d12.nir_runtime_data_root_param_idx = UINT32_MAX;790791for (int64_t i = 0; i < reflection_specialization_data.size(); i++) {792DEV_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.");793reflection_data_d3d12.spirv_specialization_constants_ids_mask |= (1 << reflection_specialization_data[i].constant_id);794}795796// Translate SPIR-V shaders to DXIL, and collect shader info from the new representation.797HashMap<RenderingDeviceCommons::ShaderStage, Vector<uint8_t>> dxil_blobs;798Vector<RenderingDeviceCommons::ShaderStage> stages;799BitField<RenderingDeviceCommons::ShaderStage> stages_processed = {};800if (!_convert_spirv_to_dxil(p_spirv, dxil_blobs, stages, stages_processed)) {801return false;802}803804// Patch with default values of specialization constants.805DEV_ASSERT(reflection_specialization_data.size() == reflection_specialization_data_d3d12.size());806for (int32_t i = 0; i < reflection_specialization_data.size(); i++) {807const ReflectionSpecializationData &sc = reflection_specialization_data[i];808const ReflectionSpecializationDataD3D12 &sc_d3d12 = reflection_specialization_data_d3d12[i];809RenderingDXIL::patch_specialization_constant((RenderingDeviceCommons::PipelineSpecializationConstantType)(sc.type), &sc.int_value, sc_d3d12.stages_bit_offsets, dxil_blobs, true);810}811812// Sign.813uint32_t shader_index = 0;814for (KeyValue<RenderingDeviceCommons::ShaderStage, Vector<uint8_t>> &E : dxil_blobs) {815RenderingDXIL::sign_bytecode(E.key, E.value);816}817818// Store compressed DXIL blobs as the shaders.819shaders.resize(p_spirv.size());820for (int64_t i = 0; i < shaders.size(); i++) {821const PackedByteArray &dxil_bytes = dxil_blobs[stages[i]];822RenderingShaderContainer::Shader &shader = shaders.ptrw()[i];823uint32_t compressed_size = 0;824shader.shader_stage = stages[i];825shader.code_decompressed_size = dxil_bytes.size();826shader.code_compressed_bytes.resize(dxil_bytes.size());827828bool compressed = compress_code(dxil_bytes.ptr(), dxil_bytes.size(), shader.code_compressed_bytes.ptrw(), &compressed_size, &shader.code_compression_flags);829ERR_FAIL_COND_V_MSG(!compressed, false, vformat("Failed to compress native code to native for SPIR-V #%d.", shader_index));830831shader.code_compressed_bytes.resize(compressed_size);832}833834if (!_generate_root_signature(stages_processed)) {835return false;836}837838return true;839#else840ERR_FAIL_V_MSG(false, "Shader compilation is not supported at runtime without NIR.");841#endif842}843844RenderingShaderContainerD3D12::RenderingShaderContainerD3D12() {845// Default empty constructor.846}847848RenderingShaderContainerD3D12::RenderingShaderContainerD3D12(void *p_lib_d3d12) {849lib_d3d12 = p_lib_d3d12;850}851852RenderingShaderContainerD3D12::ShaderReflectionD3D12 RenderingShaderContainerD3D12::get_shader_reflection_d3d12() const {853ShaderReflectionD3D12 reflection;854reflection.spirv_specialization_constants_ids_mask = reflection_data_d3d12.spirv_specialization_constants_ids_mask;855reflection.dxil_push_constant_stages = reflection_data_d3d12.dxil_push_constant_stages;856reflection.nir_runtime_data_root_param_idx = reflection_data_d3d12.nir_runtime_data_root_param_idx;857reflection.reflection_specialization_data_d3d12 = reflection_specialization_data_d3d12;858reflection.root_signature_bytes = root_signature_bytes;859reflection.root_signature_crc = root_signature_crc;860861// Transform data vector into a vector of vectors that's easier to user.862uint32_t uniform_index = 0;863reflection.reflection_binding_set_uniforms_d3d12.resize(reflection_binding_set_uniforms_count.size());864for (int64_t i = 0; i < reflection.reflection_binding_set_uniforms_d3d12.size(); i++) {865Vector<ReflectionBindingDataD3D12> &uniforms = reflection.reflection_binding_set_uniforms_d3d12.ptrw()[i];866uniforms.resize(reflection_binding_set_uniforms_count[i]);867for (int64_t j = 0; j < uniforms.size(); j++) {868uniforms.ptrw()[j] = reflection_binding_set_uniforms_data_d3d12[uniform_index];869uniform_index++;870}871}872873return reflection;874}875876// RenderingShaderContainerFormatD3D12877878void RenderingShaderContainerFormatD3D12::set_lib_d3d12(void *p_lib_d3d12) {879lib_d3d12 = p_lib_d3d12;880}881882Ref<RenderingShaderContainer> RenderingShaderContainerFormatD3D12::create_container() const {883return memnew(RenderingShaderContainerD3D12(lib_d3d12));884}885886RenderingDeviceCommons::ShaderLanguageVersion RenderingShaderContainerFormatD3D12::get_shader_language_version() const {887// NIR-DXIL is Vulkan 1.1-conformant.888return SHADER_LANGUAGE_VULKAN_VERSION_1_1;889}890891RenderingDeviceCommons::ShaderSpirvVersion RenderingShaderContainerFormatD3D12::get_shader_spirv_version() const {892// The SPIR-V part of Mesa supports 1.6, but:893// - SPIRV-Reflect won't be able to parse the compute workgroup size.894// - We want to play it safe with NIR-DXIL.895return SHADER_SPIRV_VERSION_1_5;896}897898RenderingShaderContainerFormatD3D12::RenderingShaderContainerFormatD3D12() {}899900RenderingShaderContainerFormatD3D12::~RenderingShaderContainerFormatD3D12() {}901902903