diff options
Diffstat (limited to 'drivers/d3d12')
| -rw-r--r-- | drivers/d3d12/SCsub | 151 | ||||
| -rw-r--r-- | drivers/d3d12/d3d12_context.cpp | 1067 | ||||
| -rw-r--r-- | drivers/d3d12/d3d12_context.h | 248 | ||||
| -rw-r--r-- | drivers/d3d12/d3d12_godot_nir_bridge.h | 60 | ||||
| -rw-r--r-- | drivers/d3d12/d3d12ma.cpp | 34 | ||||
| -rw-r--r-- | drivers/d3d12/rendering_device_d3d12.cpp | 9480 | ||||
| -rw-r--r-- | drivers/d3d12/rendering_device_d3d12.h | 1277 |
7 files changed, 12317 insertions, 0 deletions
diff --git a/drivers/d3d12/SCsub b/drivers/d3d12/SCsub new file mode 100644 index 0000000000..ce7134fb77 --- /dev/null +++ b/drivers/d3d12/SCsub @@ -0,0 +1,151 @@ +#!/usr/bin/env python + +import os +from pathlib import Path + +Import("env") + +env_d3d12_rd = env.Clone() + +thirdparty_obj = [] + + +# DirectX Headers (must take precedence over Windows SDK's). + +env.Prepend(CPPPATH=["#thirdparty/directx_headers"]) +env_d3d12_rd.Prepend(CPPPATH=["#thirdparty/directx_headers"]) + + +# Direct3D 12 Memory Allocator. + +env.Append(CPPPATH=["#thirdparty/d3d12ma"]) +env_d3d12_rd.Append(CPPPATH=["#thirdparty/d3d12ma"]) + + +# Agility SDK. + +if env["agility_sdk_path"] != "": + env_d3d12_rd.Append(CPPDEFINES=["AGILITY_SDK_ENABLED"]) + if env["agility_sdk_multiarch"]: + env_d3d12_rd.Append(CPPDEFINES=["AGILITY_SDK_MULTIARCH_ENABLED"]) + + +# PIX. + +if env["pix_path"] != "": + env_d3d12_rd.Append(CPPDEFINES=["PIX_ENABLED"]) + env_d3d12_rd.Append(CPPPATH=[env["pix_path"] + "/Include"]) + + +# Mesa (SPIR-V to DXIL functionality). + +mesa_dir = (env["mesa_libs"] + "/godot-mesa").replace("\\", "/") +mesa_gen_dir = (env["mesa_libs"] + "/godot-mesa/generated").replace("\\", "/") +mesa_absdir = Dir(mesa_dir).abspath +mesa_gen_absdir = Dir(mesa_dir + "/generated").abspath + +custom_build_steps = [ + [ + "src/compiler", + "glsl/ir_expression_operation.py enum > %s/ir_expression_operation.h", + "ir_expression_operation.h", + ], + ["src/compiler/nir", "nir_builder_opcodes_h.py > %s/nir_builder_opcodes.h", "nir_builder_opcodes.h"], + ["src/compiler/nir", "nir_constant_expressions.py > %s/nir_constant_expressions.c", "nir_constant_expressions.c"], + ["src/compiler/nir", "nir_intrinsics_h.py --outdir %s", "nir_intrinsics.h"], + ["src/compiler/nir", "nir_intrinsics_c.py --outdir %s", "nir_intrinsics.c"], + ["src/compiler/nir", "nir_intrinsics_indices_h.py --outdir %s", "nir_intrinsics_indices.h"], + ["src/compiler/nir", "nir_opcodes_h.py > %s/nir_opcodes.h", "nir_opcodes.h"], + ["src/compiler/nir", "nir_opcodes_c.py > %s/nir_opcodes.c", "nir_opcodes.c"], + ["src/compiler/nir", "nir_opt_algebraic.py > %s/nir_opt_algebraic.c", "nir_opt_algebraic.c"], + ["src/compiler/spirv", "vtn_generator_ids_h.py spir-v.xml %s/vtn_generator_ids.h", "vtn_generator_ids.h"], + [ + "src/microsoft/compiler", + "dxil_nir_algebraic.py -p ../../../src/compiler/nir > %s/dxil_nir_algebraic.c", + "dxil_nir_algebraic.c", + ], + ["src/util", "format_srgb.py > %s/format_srgb.c", "format_srgb.c"], + ["src/util/format", "u_format_table.py u_format.csv --header > %s/u_format_pack.h", "u_format_pack.h"], + ["src/util/format", "u_format_table.py u_format.csv > %s/u_format_table.c", "u_format_table.c"], +] + +mesa_gen_include_paths = [mesa_gen_dir + "/src"] + +# See update_mesa.sh for explanation. +for v in custom_build_steps: + subdir = v[0] + cmd = v[1] + gen_filename = v[2] + + in_dir = str(Path(mesa_absdir + "/" + subdir)) + out_full_path = mesa_dir + "/generated/" + subdir + out_file_full_path = out_full_path + "/" + gen_filename + + if gen_filename.endswith(".h"): + mesa_gen_include_paths += [out_full_path.replace("\\", "/")] + +mesa_private_inc_paths = [v[0] for v in os.walk(mesa_absdir)] +mesa_private_inc_paths = [v.replace(mesa_absdir, mesa_dir) for v in mesa_private_inc_paths] +mesa_private_inc_paths = [v.replace("\\", "/") for v in mesa_private_inc_paths] +# Avoid build results depending on if generated files already exist. +mesa_private_inc_paths = [v for v in mesa_private_inc_paths if not v.startswith(mesa_gen_dir)] +mesa_private_inc_paths.sort() +# Include the list of the generated ones now, so out-of-the-box sources can include generated headers. +mesa_private_inc_paths += mesa_gen_include_paths +# We have to blacklist some because we are bindly adding every Mesa directory +# to the include path and in some cases that causes the wrong header to be included. +mesa_blacklist_inc_paths = [ + "src/c11", +] +mesa_blacklist_inc_paths = [mesa_dir + "/" + v for v in mesa_blacklist_inc_paths] +mesa_private_inc_paths = [v for v in mesa_private_inc_paths if v not in mesa_blacklist_inc_paths] + +# Added by ourselves. +extra_defines = [ + "WINDOWS_NO_FUTEX", +] + +# These defines are inspired by the Meson build scripts in the original repo. +extra_defines += [ + "__STDC_CONSTANT_MACROS", + "__STDC_FORMAT_MACROS", + "__STDC_LIMIT_MACROS", + ("PACKAGE_VERSION", '\\"' + Path(mesa_absdir + "/VERSION").read_text().strip() + '\\"'), + ("PACKAGE_BUGREPORT", '\\"https://gitlab.freedesktop.org/mesa/mesa/-/issues\\"'), + "PIPE_SUBSYSTEM_WINDOWS_USER", + ("_Static_assert", "static_assert"), +] + +if env.msvc: + extra_defines += [ + "_USE_MATH_DEFINES", + "VC_EXTRALEAN", + "_CRT_SECURE_NO_WARNINGS", + "_CRT_SECURE_NO_DEPRECATE", + "_SCL_SECURE_NO_WARNINGS", + "_SCL_SECURE_NO_DEPRECATE", + "_ALLOW_KEYWORD_MACROS", + ("_HAS_EXCEPTIONS", 0), + "NOMINMAX", + "HAVE_STRUCT_TIMESPEC", + ] + +# This is needed since rendering_device_d3d12.cpp needs to include some Mesa internals. +env_d3d12_rd.Prepend(CPPPATH=mesa_private_inc_paths) +# For the same reason as above, the defines must be the same as in the 3rd-party code itself. +env_d3d12_rd.Append(CPPDEFINES=extra_defines) + + +# Add all. + +env.drivers_sources += thirdparty_obj + + +# Godot source files. + +driver_obj = [] +env_d3d12_rd.add_source_files(driver_obj, "*.cpp") +env.drivers_sources += driver_obj + +# Needed to force rebuilding the driver files when the thirdparty code is updated. +env.Depends(driver_obj, thirdparty_obj) diff --git a/drivers/d3d12/d3d12_context.cpp b/drivers/d3d12/d3d12_context.cpp new file mode 100644 index 0000000000..6933089208 --- /dev/null +++ b/drivers/d3d12/d3d12_context.cpp @@ -0,0 +1,1067 @@ +/**************************************************************************/ +/* d3d12_context.cpp */ +/**************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/**************************************************************************/ +/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ +/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/**************************************************************************/ + +#include "d3d12_context.h" + +#include "core/config/engine.h" +#include "core/config/project_settings.h" +#include "core/string/ustring.h" +#include "core/templates/local_vector.h" +#include "core/version.h" +#include "servers/rendering/rendering_device.h" + +#include "dxcapi.h" + +extern "C" { +char godot_nir_arch_name[32]; + +#ifdef AGILITY_SDK_ENABLED +__declspec(dllexport) extern const UINT D3D12SDKVersion = 610; +#ifdef AGILITY_SDK_MULTIARCH_ENABLED +#if defined(__aarch64__) || defined(_M_ARM64) || defined(_M_ARM64EC) +__declspec(dllexport) extern const char *D3D12SDKPath = "\\.\\arm64"; +#else +__declspec(dllexport) extern const char *D3D12SDKPath = "\\.\\x86_64"; +#endif +#else +__declspec(dllexport) extern const char *D3D12SDKPath = "\\."; +#endif // AGILITY_SDK_MULTIARCH +#endif // AGILITY_SDK_ENABLED +} + +#ifdef PIX_ENABLED +#define USE_PIX +#include "WinPixEventRuntime/pix3.h" +#endif + +#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0])) + +void D3D12Context::_debug_message_func( + D3D12_MESSAGE_CATEGORY p_category, + D3D12_MESSAGE_SEVERITY p_severity, + D3D12_MESSAGE_ID p_id, + LPCSTR p_description, + void *p_context) { + String type_string; + switch (p_category) { + case D3D12_MESSAGE_CATEGORY_APPLICATION_DEFINED: + type_string = "APPLICATION_DEFINED"; + break; + case D3D12_MESSAGE_CATEGORY_MISCELLANEOUS: + type_string = "MISCELLANEOUS"; + break; + case D3D12_MESSAGE_CATEGORY_INITIALIZATION: + type_string = "INITIALIZATION"; + break; + case D3D12_MESSAGE_CATEGORY_CLEANUP: + type_string = "CLEANUP"; + break; + case D3D12_MESSAGE_CATEGORY_COMPILATION: + type_string = "COMPILATION"; + break; + case D3D12_MESSAGE_CATEGORY_STATE_CREATION: + type_string = "STATE_CREATION"; + break; + case D3D12_MESSAGE_CATEGORY_STATE_SETTING: + type_string = "STATE_SETTING"; + break; + case D3D12_MESSAGE_CATEGORY_STATE_GETTING: + type_string = "STATE_GETTING"; + break; + case D3D12_MESSAGE_CATEGORY_RESOURCE_MANIPULATION: + type_string = "RESOURCE_MANIPULATION"; + break; + case D3D12_MESSAGE_CATEGORY_EXECUTION: + type_string = "EXECUTION"; + break; + case D3D12_MESSAGE_CATEGORY_SHADER: + type_string = "SHADER"; + break; + } + + String error_message(type_string + + " - Message Id Number: " + String::num_int64(p_id) + + "\n\t" + p_description); + + // Convert D3D12 severity to our own log macros. + switch (p_severity) { + case D3D12_MESSAGE_SEVERITY_MESSAGE: + print_verbose(error_message); + break; + case D3D12_MESSAGE_SEVERITY_INFO: + print_line(error_message); + break; + case D3D12_MESSAGE_SEVERITY_WARNING: + WARN_PRINT(error_message); + break; + case D3D12_MESSAGE_SEVERITY_ERROR: + case D3D12_MESSAGE_SEVERITY_CORRUPTION: + ERR_PRINT(error_message); + CRASH_COND_MSG(Engine::get_singleton()->is_abort_on_gpu_errors_enabled(), + "Crashing, because abort on GPU errors is enabled."); + break; + } +} + +uint32_t D3D12Context::SubgroupCapabilities::supported_stages_flags_rd() const { + // If there's a way to check exactly which are supported, I have yet to find it. + return ( + RenderingDevice::ShaderStage::SHADER_STAGE_FRAGMENT_BIT | + RenderingDevice::ShaderStage::SHADER_STAGE_COMPUTE_BIT); +} + +uint32_t D3D12Context::SubgroupCapabilities::supported_operations_flags_rd() const { + if (!wave_ops_supported) { + return 0; + } else { + return ( + RenderingDevice::SubgroupOperations::SUBGROUP_BASIC_BIT | + RenderingDevice::SubgroupOperations::SUBGROUP_BALLOT_BIT | + RenderingDevice::SubgroupOperations::SUBGROUP_VOTE_BIT | + RenderingDevice::SubgroupOperations::SUBGROUP_SHUFFLE_BIT | + RenderingDevice::SubgroupOperations::SUBGROUP_SHUFFLE_RELATIVE_BIT | + RenderingDevice::SubgroupOperations::SUBGROUP_QUAD_BIT | + RenderingDevice::SubgroupOperations::SUBGROUP_ARITHMETIC_BIT | + RenderingDevice::SubgroupOperations::SUBGROUP_CLUSTERED_BIT); + } +} + +Error D3D12Context::_check_capabilities() { + // Assume not supported until proven otherwise. + vrs_capabilities.draw_call_supported = false; + vrs_capabilities.primitive_supported = false; + vrs_capabilities.primitive_in_multiviewport = false; + vrs_capabilities.ss_image_supported = false; + vrs_capabilities.ss_image_tile_size = 1; + vrs_capabilities.additional_rates_supported = false; + multiview_capabilities.is_supported = false; + multiview_capabilities.geometry_shader_is_supported = false; + multiview_capabilities.tessellation_shader_is_supported = false; + multiview_capabilities.max_view_count = 0; + multiview_capabilities.max_instance_count = 0; + multiview_capabilities.is_supported = false; + subgroup_capabilities.size = 0; + subgroup_capabilities.wave_ops_supported = false; + shader_capabilities.shader_model = D3D_SHADER_MODEL_6_0; + shader_capabilities.native_16bit_ops = false; + storage_buffer_capabilities.storage_buffer_16_bit_access_is_supported = false; + format_capabilities.relaxed_casting_supported = false; + + { + D3D12_FEATURE_DATA_SHADER_MODEL shader_model = {}; + shader_model.HighestShaderModel = MIN(D3D_HIGHEST_SHADER_MODEL, D3D_SHADER_MODEL_6_6); + HRESULT res = md.device->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &shader_model, sizeof(shader_model)); + ERR_FAIL_COND_V_MSG(res, ERR_CANT_CREATE, "CheckFeatureSupport failed with error " + vformat("0x%08ux", res) + "."); + shader_capabilities.shader_model = shader_model.HighestShaderModel; + } + print_verbose("- Shader:"); + print_verbose(" model: " + itos(shader_capabilities.shader_model >> 4) + "." + itos(shader_capabilities.shader_model & 0xf)); + + D3D12_FEATURE_DATA_D3D12_OPTIONS options = {}; + HRESULT res = md.device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options)); + if (SUCCEEDED(res)) { + storage_buffer_capabilities.storage_buffer_16_bit_access_is_supported = options.TypedUAVLoadAdditionalFormats; + } + + D3D12_FEATURE_DATA_D3D12_OPTIONS1 options1 = {}; + res = md.device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, &options1, sizeof(options1)); + if (SUCCEEDED(res)) { + subgroup_capabilities.size = options1.WaveLaneCountMin; + subgroup_capabilities.wave_ops_supported = options1.WaveOps; + } + + D3D12_FEATURE_DATA_D3D12_OPTIONS3 options3 = {}; + res = md.device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS3, &options3, sizeof(options3)); + if (SUCCEEDED(res)) { + // https://docs.microsoft.com/en-us/windows/win32/api/d3d12/ne-d3d12-d3d12_view_instancing_tier + // https://microsoft.github.io/DirectX-Specs/d3d/ViewInstancing.html#sv_viewid + if (options3.ViewInstancingTier >= D3D12_VIEW_INSTANCING_TIER_1) { + multiview_capabilities.is_supported = true; + multiview_capabilities.geometry_shader_is_supported = options3.ViewInstancingTier >= D3D12_VIEW_INSTANCING_TIER_3; + multiview_capabilities.tessellation_shader_is_supported = options3.ViewInstancingTier >= D3D12_VIEW_INSTANCING_TIER_3; + multiview_capabilities.max_view_count = D3D12_MAX_VIEW_INSTANCE_COUNT; + multiview_capabilities.max_instance_count = UINT32_MAX; + } + } + + D3D12_FEATURE_DATA_D3D12_OPTIONS6 options6 = {}; + res = md.device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS6, &options6, sizeof(options6)); + if (SUCCEEDED(res)) { + if (options6.VariableShadingRateTier >= D3D12_VARIABLE_SHADING_RATE_TIER_1) { + vrs_capabilities.draw_call_supported = true; + if (options6.VariableShadingRateTier >= D3D12_VARIABLE_SHADING_RATE_TIER_2) { + vrs_capabilities.primitive_supported = true; + vrs_capabilities.primitive_in_multiviewport = options6.PerPrimitiveShadingRateSupportedWithViewportIndexing; + vrs_capabilities.ss_image_supported = true; + vrs_capabilities.ss_image_tile_size = options6.ShadingRateImageTileSize; + vrs_capabilities.additional_rates_supported = options6.AdditionalShadingRatesSupported; + } + } + } + + D3D12_FEATURE_DATA_D3D12_OPTIONS12 options12 = {}; + res = md.device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS12, &options12, sizeof(options12)); + if (SUCCEEDED(res)) { + format_capabilities.relaxed_casting_supported = options12.RelaxedFormatCastingSupported; + } + + if (vrs_capabilities.draw_call_supported || vrs_capabilities.primitive_supported || vrs_capabilities.ss_image_supported) { + print_verbose("- D3D12 Variable Rate Shading supported:"); + if (vrs_capabilities.draw_call_supported) { + print_verbose(" Draw call"); + } + if (vrs_capabilities.primitive_supported) { + print_verbose(String(" Per-primitive (multi-viewport: ") + (vrs_capabilities.primitive_in_multiviewport ? "yes" : "no") + ")"); + } + if (vrs_capabilities.ss_image_supported) { + print_verbose(String(" Screen-space image (tile size: ") + itos(vrs_capabilities.ss_image_tile_size) + ")"); + } + if (vrs_capabilities.additional_rates_supported) { + print_verbose(String(" Additional rates: ") + (vrs_capabilities.additional_rates_supported ? "yes" : "no")); + } + } else { + print_verbose("- D3D12 Variable Rate Shading not supported"); + } + + if (multiview_capabilities.is_supported) { + print_verbose("- D3D12 multiview supported:"); + print_verbose(" max view count: " + itos(multiview_capabilities.max_view_count)); + //print_verbose(" max instances: " + itos(multiview_capabilities.max_instance_count)); // Hardcoded; not very useful at the moment. + } else { + print_verbose("- D3D12 multiview not supported"); + } + + if (format_capabilities.relaxed_casting_supported) { + print_verbose("- Relaxed casting supported"); + } else { + print_verbose("- Relaxed casting not supported"); + } + + return OK; +} + +Error D3D12Context::_initialize_debug_layers() { + ComPtr<ID3D12Debug> debug_controller; + HRESULT res = D3D12GetDebugInterface(IID_PPV_ARGS(&debug_controller)); + ERR_FAIL_COND_V(res, ERR_QUERY_FAILED); + debug_controller->EnableDebugLayer(); + return OK; +} + +Error D3D12Context::_select_adapter(int &r_index) { + { + UINT flags = _use_validation_layers() ? DXGI_CREATE_FACTORY_DEBUG : 0; + HRESULT res = CreateDXGIFactory2(flags, IID_PPV_ARGS(&dxgi_factory)); + ERR_FAIL_COND_V(!SUCCEEDED(res), ERR_CANT_CREATE); + } + + ComPtr<IDXGIFactory6> factory6; + dxgi_factory.As(&factory6); + + // TODO: Use IDXCoreAdapterList, which gives more comprehensive information. + LocalVector<IDXGIAdapter1 *> adapters; + while (true) { + IDXGIAdapter1 *curr_adapter = nullptr; + if (factory6) { + if (factory6->EnumAdapterByGpuPreference(adapters.size(), DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&curr_adapter)) == DXGI_ERROR_NOT_FOUND) { + break; + } + } else { + if (dxgi_factory->EnumAdapters1(adapters.size(), &curr_adapter) == DXGI_ERROR_NOT_FOUND) { + break; + } + } + adapters.push_back(curr_adapter); + } + + ERR_FAIL_COND_V_MSG(adapters.size() == 0, ERR_CANT_CREATE, "Adapters enumeration reported zero accessible devices."); + + // The device should really be a preference, but for now choosing a discrete GPU over the + // integrated one is better than the default. + + int32_t adapter_index = -1; + int type_selected = -1; + LocalVector<RenderingDevice::DeviceType> adapter_types; + print_verbose("D3D12 devices:"); + for (uint32_t i = 0; i < adapters.size(); ++i) { + DXGI_ADAPTER_DESC1 desc = {}; + adapters[i]->GetDesc1(&desc); + + String name = desc.Description; + String dev_type; + RenderingDevice::DeviceType type = {}; + if (((desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE))) { + type = RenderingDevice::DEVICE_TYPE_CPU; + } else { + type = desc.DedicatedVideoMemory ? RenderingDevice::DEVICE_TYPE_DISCRETE_GPU : RenderingDevice::DEVICE_TYPE_INTEGRATED_GPU; + } + adapter_types.push_back(type); + + switch (type) { + case RenderingDevice::DEVICE_TYPE_DISCRETE_GPU: { + dev_type = "Discrete"; + } break; + case RenderingDevice::DEVICE_TYPE_INTEGRATED_GPU: { + dev_type = "Integrated"; + } break; + case RenderingDevice::DEVICE_TYPE_VIRTUAL_GPU: { + dev_type = "Virtual"; + } break; + case RenderingDevice::DEVICE_TYPE_CPU: { + dev_type = "CPU"; + } break; + default: { + dev_type = "Other"; + } break; + } + print_verbose(" #" + itos(i) + ": " + name + ", " + dev_type); + + switch (type) { + case RenderingDevice::DEVICE_TYPE_DISCRETE_GPU: { + if (type_selected < 4) { + type_selected = 4; + adapter_index = i; + } + } break; + case RenderingDevice::DEVICE_TYPE_INTEGRATED_GPU: { + if (type_selected < 3) { + type_selected = 3; + adapter_index = i; + } + } break; + case RenderingDevice::DEVICE_TYPE_VIRTUAL_GPU: { + if (type_selected < 2) { + type_selected = 2; + adapter_index = i; + } + } break; + case RenderingDevice::DEVICE_TYPE_CPU: { + if (type_selected < 1) { + type_selected = 1; + adapter_index = i; + } + } break; + default: { + if (type_selected < 0) { + type_selected = 0; + adapter_index = i; + } + } break; + } + } + + int32_t user_adapter_index = Engine::get_singleton()->get_gpu_index(); // Force user selected GPU. + if (user_adapter_index >= 0 && user_adapter_index < (int32_t)adapters.size()) { + adapter_index = user_adapter_index; + } + + ERR_FAIL_COND_V_MSG(adapter_index == -1, ERR_CANT_CREATE, "None of D3D12 devices supports hardware rendering."); + + gpu = adapters[adapter_index]; + for (uint32_t i = 0; i < adapters.size(); ++i) { + adapters[i]->Release(); + } + + adapter_type = adapter_types[adapter_index]; + + ComPtr<IDXGIFactory5> factory5; + dxgi_factory.As(&factory5); + if (factory5) { + BOOL result = FALSE; // sizeof(bool) != sizeof(BOOL), in general. + HRESULT res = factory5->CheckFeatureSupport(DXGI_FEATURE_PRESENT_ALLOW_TEARING, &result, sizeof(result)); + if (SUCCEEDED(res)) { + tearing_supported = result; + } else { + ERR_PRINT("CheckFeatureSupport failed with error " + vformat("0x%08ux", res) + "."); + } + } + + r_index = adapter_index; + + return OK; +} + +void D3D12Context::_dump_adapter_info(int p_index) { + { + const D3D_FEATURE_LEVEL FEATURE_LEVELS[] = { + D3D_FEATURE_LEVEL_11_0, + D3D_FEATURE_LEVEL_11_1, + D3D_FEATURE_LEVEL_12_0, + D3D_FEATURE_LEVEL_12_1, + D3D_FEATURE_LEVEL_12_2, + }; + + D3D12_FEATURE_DATA_FEATURE_LEVELS feat_levels = {}; + feat_levels.NumFeatureLevels = ARRAY_SIZE(FEATURE_LEVELS); + feat_levels.pFeatureLevelsRequested = FEATURE_LEVELS; + + HRESULT res = md.device->CheckFeatureSupport(D3D12_FEATURE_FEATURE_LEVELS, &feat_levels, sizeof(feat_levels)); + ERR_FAIL_COND_MSG(res, "CheckFeatureSupport failed with error " + vformat("0x%08ux", res) + "."); + + // Example: D3D_FEATURE_LEVEL_12_1 = 0xc100. + uint32_t feat_level_major = feat_levels.MaxSupportedFeatureLevel >> 12; + uint32_t feat_level_minor = (feat_levels.MaxSupportedFeatureLevel >> 16) & 0xff; + feature_level = feat_level_major * 10 + feat_level_minor; + } + + String rendering_method; + if (OS::get_singleton()->get_current_rendering_method() == "mobile") { + rendering_method = "Forward Mobile"; + } else { + rendering_method = "Forward+"; + } + + static const struct { + uint32_t id; + const char *name; + } vendor_names[] = { + { 0x1002, "AMD" }, + { 0x1010, "ImgTec" }, + { 0x106B, "Apple" }, + { 0x10DE, "NVIDIA" }, + { 0x13B5, "ARM" }, + { 0x1414, "Microsoft" }, + { 0x5143, "Qualcomm" }, + { 0x8086, "Intel" }, + { 0, nullptr }, + }; + + DXGI_ADAPTER_DESC gpu_desc = {}; + gpu->GetDesc(&gpu_desc); + + adapter_name = gpu_desc.Description; + pipeline_cache_id = String::hex_encode_buffer((uint8_t *)&gpu_desc.AdapterLuid, sizeof(LUID)); + pipeline_cache_id += "-driver-" + itos(gpu_desc.Revision); + { + adapter_vendor = "Unknown"; + uint32_t vendor_idx = 0; + while (vendor_names[vendor_idx].name != nullptr) { + if (gpu_desc.VendorId == vendor_names[vendor_idx].id) { + adapter_vendor = vendor_names[vendor_idx].name; + break; + } + vendor_idx++; + } + } + + print_line(vformat("D3D12 feature level %s - %s - Using D3D12 Adapter #%d: %s", get_device_api_version(), rendering_method, p_index, adapter_name)); +} + +Error D3D12Context::_create_device(DeviceBasics &r_basics) { + HRESULT res = D3D12CreateDevice(gpu.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(r_basics.device.GetAddressOf())); + ERR_FAIL_COND_V_MSG(res, ERR_CANT_CREATE, "D3D12CreateDevice failed with error " + vformat("0x%08ux", res) + "."); + + // Create direct command queue. + D3D12_COMMAND_QUEUE_DESC queue_desc = {}; + queue_desc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE; + queue_desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; + res = r_basics.device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(r_basics.queue.GetAddressOf())); + ERR_FAIL_COND_V(res, ERR_CANT_CREATE); + + // Create sync objects. + res = r_basics.device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(r_basics.fence.GetAddressOf())); + ERR_FAIL_COND_V(res, ERR_CANT_CREATE); + r_basics.fence_event = CreateEvent(nullptr, FALSE, FALSE, nullptr); + ERR_FAIL_NULL_V(r_basics.fence_event, ERR_CANT_CREATE); + + if (_use_validation_layers()) { + ComPtr<ID3D12InfoQueue> info_queue; + res = r_basics.device.As(&info_queue); + ERR_FAIL_COND_V(res, ERR_CANT_CREATE); + +#if 0 // This causes crashes. Needs investigation. + ComPtr<ID3D12InfoQueue1> info_queue_1; + device.As(&info_queue_1); + if (info_queue_1) { + // Custom printing supported (added in Windows 10 Release Preview build 20236). + + info_queue_1->SetMuteDebugOutput(TRUE); + + res = info_queue_1->RegisterMessageCallback(&_debug_message_func, D3D12_MESSAGE_CALLBACK_IGNORE_FILTERS, nullptr, 0); + ERR_FAIL_COND_V(res, ERR_CANT_CREATE); + } else +#endif + { + // Rely on D3D12's own debug printing. + + if (Engine::get_singleton()->is_abort_on_gpu_errors_enabled()) { + res = info_queue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_WARNING, TRUE); + ERR_FAIL_COND_V(res, ERR_CANT_CREATE); + } + } + D3D12_MESSAGE_SEVERITY severities_to_mute[] = { + D3D12_MESSAGE_SEVERITY_INFO, + }; + + D3D12_MESSAGE_ID messages_to_mute[] = { + D3D12_MESSAGE_ID_CLEARRENDERTARGETVIEW_MISMATCHINGCLEARVALUE, + D3D12_MESSAGE_ID_CLEARDEPTHSTENCILVIEW_MISMATCHINGCLEARVALUE, + // These happen due to how D3D12MA manages buffers; seem bening. + D3D12_MESSAGE_ID_HEAP_ADDRESS_RANGE_HAS_NO_RESOURCE, + D3D12_MESSAGE_ID_HEAP_ADDRESS_RANGE_INTERSECTS_MULTIPLE_BUFFERS, + }; + + D3D12_INFO_QUEUE_FILTER filter = {}; + filter.DenyList.NumSeverities = ARRAY_SIZE(severities_to_mute); + filter.DenyList.pSeverityList = severities_to_mute; + filter.DenyList.NumIDs = ARRAY_SIZE(messages_to_mute); + filter.DenyList.pIDList = messages_to_mute; + + res = info_queue->PushStorageFilter(&filter); + ERR_FAIL_COND_V(res, ERR_CANT_CREATE); + } + + return OK; +} + +Error D3D12Context::_get_device_limits() { + D3D12_FEATURE_DATA_D3D12_OPTIONS options = {}; + HRESULT res = md.device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options)); + ERR_FAIL_COND_V_MSG(res, ERR_UNAVAILABLE, "CheckFeatureSupport failed with error " + vformat("0x%08ux", res) + "."); + + // https://docs.microsoft.com/en-us/windows/win32/direct3d12/hardware-support + gpu_limits.max_srvs_per_shader_stage = options.ResourceBindingTier == D3D12_RESOURCE_BINDING_TIER_1 ? 128 : UINT64_MAX; + gpu_limits.max_cbvs_per_shader_stage = options.ResourceBindingTier <= D3D12_RESOURCE_BINDING_TIER_2 ? 14 : UINT64_MAX; + gpu_limits.max_samplers_across_all_stages = options.ResourceBindingTier == D3D12_RESOURCE_BINDING_TIER_1 ? 16 : 2048; + if (options.ResourceBindingTier == D3D12_RESOURCE_BINDING_TIER_1) { + gpu_limits.max_uavs_across_all_stages = feature_level <= 110 ? 8 : 64; + } else if (options.ResourceBindingTier == D3D12_RESOURCE_BINDING_TIER_2) { + gpu_limits.max_uavs_across_all_stages = 64; + } else { + gpu_limits.max_uavs_across_all_stages = UINT64_MAX; + } + + md.queue->GetTimestampFrequency(&gpu_limits.timestamp_frequency); + + return OK; +} + +bool D3D12Context::_use_validation_layers() { + return Engine::get_singleton()->is_validation_layers_enabled(); +} + +Error D3D12Context::window_create(DisplayServer::WindowID p_window_id, DisplayServer::VSyncMode p_vsync_mode, HWND p_window, HINSTANCE p_instance, int p_width, int p_height) { + ERR_FAIL_COND_V(windows.has(p_window_id), ERR_INVALID_PARAMETER); + + Window window; + window.hwnd = p_window; + window.width = p_width; + window.height = p_height; + window.vsync_mode = p_vsync_mode; + Error err = _update_swap_chain(&window); + ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE); + + windows[p_window_id] = window; + return OK; +} + +void D3D12Context::window_resize(DisplayServer::WindowID p_window, int p_width, int p_height) { + ERR_FAIL_COND(!windows.has(p_window)); + windows[p_window].width = p_width; + windows[p_window].height = p_height; + _update_swap_chain(&windows[p_window]); +} + +int D3D12Context::window_get_width(DisplayServer::WindowID p_window) { + ERR_FAIL_COND_V(!windows.has(p_window), -1); + return windows[p_window].width; +} + +int D3D12Context::window_get_height(DisplayServer::WindowID p_window) { + ERR_FAIL_COND_V(!windows.has(p_window), -1); + return windows[p_window].height; +} + +bool D3D12Context::window_is_valid_swapchain(DisplayServer::WindowID p_window) { + ERR_FAIL_COND_V(!windows.has(p_window), false); + Window *w = &windows[p_window]; + return (bool)w->swapchain; +} + +CD3DX12_CPU_DESCRIPTOR_HANDLE D3D12Context::window_get_framebuffer_rtv_handle(DisplayServer::WindowID p_window) { + ERR_FAIL_COND_V(!windows.has(p_window), CD3DX12_CPU_DESCRIPTOR_HANDLE(CD3DX12_DEFAULT())); + ERR_FAIL_COND_V(!buffers_prepared, CD3DX12_CPU_DESCRIPTOR_HANDLE(CD3DX12_DEFAULT())); + Window *w = &windows[p_window]; + CD3DX12_CPU_DESCRIPTOR_HANDLE rtv_handle( + w->rtv_heap->GetCPUDescriptorHandleForHeapStart(), + w->current_buffer, + md.device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV)); + return rtv_handle; +} + +ID3D12Resource *D3D12Context::window_get_framebuffer_texture(DisplayServer::WindowID p_window) { + ERR_FAIL_COND_V(!windows.has(p_window), nullptr); + ERR_FAIL_COND_V(!buffers_prepared, nullptr); + Window *w = &windows[p_window]; + if (w->swapchain) { + return w->render_targets[w->current_buffer].Get(); + } else { + return nullptr; + } +} + +void D3D12Context::window_destroy(DisplayServer::WindowID p_window_id) { + ERR_FAIL_COND(!windows.has(p_window_id)); + _wait_for_idle_queue(md.queue.Get()); + windows.erase(p_window_id); +} + +Error D3D12Context::_update_swap_chain(Window *window) { + if (window->width == 0 || window->height == 0) { + // Likely window minimized, no swapchain created. + return ERR_SKIP; + } + + DisplayServer::VSyncMode curr_vsync_mode = window->vsync_mode; + bool vsync_mode_available = false; + UINT swapchain_flags = 0; + do { + switch (window->vsync_mode) { + case DisplayServer::VSYNC_MAILBOX: { + window->sync_interval = 1; + window->present_flags = DXGI_PRESENT_RESTART; + swapchain_flags = 0; + vsync_mode_available = true; + } break; + case DisplayServer::VSYNC_ADAPTIVE: { + vsync_mode_available = false; // I don't know how to set this up. + } break; + case DisplayServer::VSYNC_ENABLED: { + window->sync_interval = 1; + window->present_flags = 0; + swapchain_flags = 0; + vsync_mode_available = true; + } break; + case DisplayServer::VSYNC_DISABLED: { + window->sync_interval = 0; + window->present_flags = tearing_supported ? DXGI_PRESENT_ALLOW_TEARING : 0; + swapchain_flags = tearing_supported ? DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING : 0; + vsync_mode_available = true; + } break; + } + + // Set the windows swap effect if it is available, otherwise FLIP_DISCARD is used. + if (vsync_mode_available) { + if (window->vsync_mode != curr_vsync_mode || !window->swapchain) { + window->vsync_mode = curr_vsync_mode; + print_verbose("Using swapchain flags: " + itos(swapchain_flags) + ", sync interval: " + itos(window->sync_interval) + ", present flags: " + itos(window->present_flags)); + } + } else { + String present_mode_string; + switch (window->vsync_mode) { + case DisplayServer::VSYNC_MAILBOX: + present_mode_string = "Mailbox"; + break; + case DisplayServer::VSYNC_ADAPTIVE: + present_mode_string = "Adaptive"; + break; + case DisplayServer::VSYNC_ENABLED: + present_mode_string = "Enabled"; + break; + case DisplayServer::VSYNC_DISABLED: + present_mode_string = "Disabled"; + break; + } + WARN_PRINT(vformat("The requested V-Sync mode %s is not available. Falling back to V-Sync mode Enabled.", present_mode_string)); + window->vsync_mode = DisplayServer::VSYNC_ENABLED; // Set to default. + } + } while (!vsync_mode_available); + + if (window->swapchain) { + _wait_for_idle_queue(md.queue.Get()); + for (uint32_t i = 0; i < IMAGE_COUNT; i++) { + window->render_targets[i].Reset(); + } + window->rtv_heap.Reset(); + + // D3D12 docs: "IDXGISwapChain::ResizeBuffers can't be used to add or remove this flag." + bool allow_tearing_flag_changed = (swapchain_flags & DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING) != (window->swapchain_flags & DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING); + if (allow_tearing_flag_changed) { + window->swapchain.Reset(); + } + } + + if (!window->swapchain) { + DXGI_SWAP_CHAIN_DESC1 swapchain_desc = {}; + swapchain_desc.BufferCount = IMAGE_COUNT; + swapchain_desc.Width = 0; + swapchain_desc.Height = 0; + swapchain_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + swapchain_desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; + swapchain_desc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; + swapchain_desc.SampleDesc.Count = 1; + swapchain_desc.Flags = swapchain_flags; + swapchain_desc.Scaling = DXGI_SCALING_NONE; + + ComPtr<IDXGISwapChain1> swapchain; + HRESULT res = dxgi_factory->CreateSwapChainForHwnd(md.queue.Get(), window->hwnd, &swapchain_desc, nullptr, nullptr, swapchain.GetAddressOf()); + ERR_FAIL_COND_V(res, ERR_CANT_CREATE); + swapchain.As(&window->swapchain); + ERR_FAIL_NULL_V(window->swapchain, ERR_CANT_CREATE); + + format = swapchain_desc.Format; + + res = dxgi_factory->MakeWindowAssociation(window->hwnd, DXGI_MWA_NO_ALT_ENTER | DXGI_MWA_NO_WINDOW_CHANGES); + ERR_FAIL_COND_V(res, ERR_CANT_CREATE); + + res = window->swapchain->GetDesc1(&swapchain_desc); + ERR_FAIL_COND_V(res, ERR_CANT_CREATE); + ERR_FAIL_COND_V(swapchain_desc.BufferCount != IMAGE_COUNT, ERR_BUG); + window->width = swapchain_desc.Width; + window->height = swapchain_desc.Height; + + } else { + HRESULT res = window->swapchain->ResizeBuffers(IMAGE_COUNT, window->width, window->height, DXGI_FORMAT_UNKNOWN, swapchain_flags); + ERR_FAIL_COND_V(res, ERR_UNAVAILABLE); + } + + window->swapchain_flags = swapchain_flags; + window->current_buffer = window->swapchain->GetCurrentBackBufferIndex(); + + // Describe and create a render target view (RTV) descriptor heap. + D3D12_DESCRIPTOR_HEAP_DESC rtv_heap_desc = {}; + rtv_heap_desc.NumDescriptors = IMAGE_COUNT; + rtv_heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV; + rtv_heap_desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE; + HRESULT res = md.device->CreateDescriptorHeap(&rtv_heap_desc, IID_PPV_ARGS(window->rtv_heap.GetAddressOf())); + ERR_FAIL_COND_V(res, ERR_CANT_CREATE); + + CD3DX12_CPU_DESCRIPTOR_HANDLE rtv_handle(window->rtv_heap->GetCPUDescriptorHandleForHeapStart()); + + for (uint32_t i = 0; i < IMAGE_COUNT; i++) { + res = window->swapchain->GetBuffer(i, IID_PPV_ARGS(&window->render_targets[i])); + ERR_FAIL_COND_V(res, ERR_CANT_CREATE); + + md.device->CreateRenderTargetView(window->render_targets[i].Get(), nullptr, rtv_handle); + rtv_handle.Offset(1, md.device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV)); + } + + return OK; +} + +Error D3D12Context::initialize() { + if (_use_validation_layers()) { + Error err = _initialize_debug_layers(); + ERR_FAIL_COND_V(err, ERR_CANT_CREATE); + } + + int adapter_index = 0; + + Error err = _select_adapter(adapter_index); + ERR_FAIL_COND_V(err, ERR_CANT_CREATE); + + err = _create_device(md); + ERR_FAIL_COND_V(err, ERR_CANT_CREATE); + + _dump_adapter_info(adapter_index); + + err = _check_capabilities(); + ERR_FAIL_COND_V(err, ERR_CANT_CREATE); + + err = _get_device_limits(); + ERR_FAIL_COND_V(err, ERR_CANT_CREATE); + + { + HRESULT res = md.device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(frame_fence.GetAddressOf())); + ERR_FAIL_COND_V(res, ERR_CANT_CREATE); + frame_fence_event = CreateEvent(nullptr, FALSE, FALSE, nullptr); + ERR_FAIL_NULL_V(frame_fence_event, ERR_CANT_CREATE); + } + + { // Initialize allocator. + D3D12MA::ALLOCATOR_DESC allocator_desc = {}; + allocator_desc.pDevice = md.device.Get(); + allocator_desc.pAdapter = gpu.Get(); + + HRESULT res = D3D12MA::CreateAllocator(&allocator_desc, &allocator); + ERR_FAIL_COND_V_MSG(res, ERR_CANT_CREATE, "D3D12MA::CreateAllocator failed with error " + vformat("0x%08ux", res) + "."); + } + + return OK; +} + +void D3D12Context::set_setup_list(ID3D12CommandList *p_command_list) { + command_list_queue.write[0] = p_command_list; +} + +void D3D12Context::append_command_list(ID3D12CommandList *p_command_list) { + if (command_list_queue.size() <= command_list_count) { + command_list_queue.resize(command_list_count + 1); + } + + command_list_queue.write[command_list_count] = p_command_list; + command_list_count++; +} + +void D3D12Context::_wait_for_idle_queue(ID3D12CommandQueue *p_queue) { + md.fence_value++; + p_queue->Signal(md.fence.Get(), md.fence_value); + md.fence->SetEventOnCompletion(md.fence_value, md.fence_event); + WaitForSingleObjectEx(md.fence_event, INFINITE, FALSE); +#ifdef PIX_ENABLED + PIXNotifyWakeFromFenceSignal(md.fence_event); +#endif +} + +void D3D12Context::flush(bool p_flush_setup, bool p_flush_pending) { + if (p_flush_setup && command_list_queue[0]) { + md.queue->ExecuteCommandLists(1, command_list_queue.ptr()); + command_list_queue.write[0] = nullptr; + } + + if (p_flush_pending && command_list_count > 1) { + md.queue->ExecuteCommandLists(command_list_count - 1, command_list_queue.ptr() + 1); + command_list_count = 1; + } + + if (p_flush_setup || p_flush_pending) { + _wait_for_idle_queue(md.queue.Get()); + } +} + +void D3D12Context::prepare_buffers(ID3D12GraphicsCommandList *p_command_list) { + // Ensure no more than FRAME_LAG renderings are outstanding. + if (frame >= IMAGE_COUNT) { + UINT64 min_value = frame - IMAGE_COUNT; + if (frame_fence->GetCompletedValue() < min_value) { + frame_fence->SetEventOnCompletion(min_value, frame_fence_event); + WaitForSingleObjectEx(frame_fence_event, INFINITE, FALSE); +#ifdef PIX_ENABLED + PIXNotifyWakeFromFenceSignal(frame_fence_event); +#endif + } + } + + D3D12_RESOURCE_BARRIER *barriers = (D3D12_RESOURCE_BARRIER *)alloca(windows.size() * sizeof(D3D12_RESOURCE_BARRIER)); + + uint32_t n = 0; + for (KeyValue<int, Window> &E : windows) { + Window *w = &E.value; + w->current_buffer = w->swapchain->GetCurrentBackBufferIndex(); + barriers[n++] = CD3DX12_RESOURCE_BARRIER::Transition(w->render_targets[w->current_buffer].Get(), D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET); + } + + p_command_list->ResourceBarrier(n, barriers); + + buffers_prepared = true; +} + +void D3D12Context::postpare_buffers(ID3D12GraphicsCommandList *p_command_list) { + D3D12_RESOURCE_BARRIER *barriers = (D3D12_RESOURCE_BARRIER *)alloca(windows.size() * sizeof(D3D12_RESOURCE_BARRIER)); + + uint32_t n = 0; + for (KeyValue<int, Window> &E : windows) { + Window *w = &E.value; + barriers[n++] = CD3DX12_RESOURCE_BARRIER::Transition(w->render_targets[w->current_buffer].Get(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT); + } + + p_command_list->ResourceBarrier(n, barriers); +} + +Error D3D12Context::swap_buffers() { + ID3D12CommandList *const *commands_ptr = nullptr; + UINT commands_to_submit = 0; + + if (command_list_queue[0] == nullptr) { + // No setup command, but commands to submit, submit from the first and skip command. + if (command_list_count > 1) { + commands_ptr = command_list_queue.ptr() + 1; + commands_to_submit = command_list_count - 1; + } + } else { + commands_ptr = command_list_queue.ptr(); + commands_to_submit = command_list_count; + } + + md.queue->ExecuteCommandLists(commands_to_submit, commands_ptr); + + command_list_queue.write[0] = nullptr; + command_list_count = 1; + + for (KeyValue<int, Window> &E : windows) { + Window *w = &E.value; + + if (!w->swapchain) { + continue; + } + HRESULT res = w->swapchain->Present(w->sync_interval, w->present_flags); + if (res) { + print_verbose("D3D12: Presenting swapchain of window " + itos(E.key) + " failed with error " + vformat("0x%08ux", res) + "."); + } + } + + md.queue->Signal(frame_fence.Get(), frame); + frame++; + + buffers_prepared = false; + return OK; +} + +void D3D12Context::resize_notify() { +} + +ComPtr<ID3D12Device> D3D12Context::get_device() { + return md.device; +} + +ComPtr<IDXGIAdapter> D3D12Context::get_adapter() { + return gpu; +} + +D3D12MA::Allocator *D3D12Context::get_allocator() { + return allocator.Get(); +} + +int D3D12Context::get_swapchain_image_count() const { + return IMAGE_COUNT; +} + +DXGI_FORMAT D3D12Context::get_screen_format() const { + return format; +} + +D3D12Context::DeviceLimits D3D12Context::get_device_limits() const { + return gpu_limits; +} + +RID D3D12Context::local_device_create() { + LocalDevice ld; + _create_device(ld); + return local_device_owner.make_rid(ld); +} + +ComPtr<ID3D12Device> D3D12Context::local_device_get_d3d12_device(RID p_local_device) { + LocalDevice *ld = local_device_owner.get_or_null(p_local_device); + return ld->device; +} + +void D3D12Context::local_device_push_command_lists(RID p_local_device, ID3D12CommandList *const *p_lists, int p_count) { + LocalDevice *ld = local_device_owner.get_or_null(p_local_device); + ERR_FAIL_COND(ld->waiting); + + ld->queue->ExecuteCommandLists(p_count, p_lists); + + ld->waiting = true; +} + +void D3D12Context::local_device_sync(RID p_local_device) { + LocalDevice *ld = local_device_owner.get_or_null(p_local_device); + ERR_FAIL_COND(!ld->waiting); + + ld->fence_value++; + ld->queue->Signal(ld->fence.Get(), ld->fence_value); + ld->fence->SetEventOnCompletion(ld->fence_value, ld->fence_event); + WaitForSingleObjectEx(ld->fence_event, INFINITE, FALSE); +#ifdef PIX_ENABLED + PIXNotifyWakeFromFenceSignal(ld->fence_event); +#endif + + ld->waiting = false; +} + +void D3D12Context::local_device_free(RID p_local_device) { + LocalDevice *ld = local_device_owner.get_or_null(p_local_device); + + CloseHandle(ld->fence_event); + + local_device_owner.free(p_local_device); +} + +void D3D12Context::command_begin_label(ID3D12GraphicsCommandList *p_command_list, String p_label_name, const Color p_color) { +#ifdef PIX_ENABLED + PIXBeginEvent(p_command_list, p_color.to_argb32(), p_label_name.utf8().get_data()); +#endif +} + +void D3D12Context::command_insert_label(ID3D12GraphicsCommandList *p_command_list, String p_label_name, const Color p_color) { +#ifdef PIX_ENABLED + PIXSetMarker(p_command_list, p_color.to_argb32(), p_label_name.utf8().get_data()); +#endif +} + +void D3D12Context::command_end_label(ID3D12GraphicsCommandList *p_command_list) { +#ifdef PIX_ENABLED + PIXEndEvent(p_command_list); +#endif +} + +void D3D12Context::set_object_name(ID3D12Object *p_object, String p_object_name) { + ERR_FAIL_NULL(p_object); + int name_len = p_object_name.size(); + WCHAR *name_w = (WCHAR *)alloca(sizeof(WCHAR) * (name_len + 1)); + MultiByteToWideChar(CP_UTF8, 0, p_object_name.utf8().get_data(), -1, name_w, name_len); + p_object->SetName(name_w); +} + +String D3D12Context::get_device_vendor_name() const { + return adapter_vendor; +} +String D3D12Context::get_device_name() const { + return adapter_name; +} + +RenderingDevice::DeviceType D3D12Context::get_device_type() const { + return adapter_type; +} + +String D3D12Context::get_device_api_version() const { + return vformat("%d_%d", feature_level / 10, feature_level % 10); +} + +String D3D12Context::get_device_pipeline_cache_uuid() const { + return pipeline_cache_id; +} + +DisplayServer::VSyncMode D3D12Context::get_vsync_mode(DisplayServer::WindowID p_window) const { + ERR_FAIL_COND_V_MSG(!windows.has(p_window), DisplayServer::VSYNC_ENABLED, "Could not get V-Sync mode for window with WindowID " + itos(p_window) + " because it does not exist."); + return windows[p_window].vsync_mode; +} + +void D3D12Context::set_vsync_mode(DisplayServer::WindowID p_window, DisplayServer::VSyncMode p_mode) { + ERR_FAIL_COND_MSG(!windows.has(p_window), "Could not set V-Sync mode for window with WindowID " + itos(p_window) + " because it does not exist."); + windows[p_window].vsync_mode = p_mode; + _update_swap_chain(&windows[p_window]); +} + +D3D12Context::D3D12Context() { + command_list_queue.resize(1); // First one is always the setup command. + command_list_queue.write[0] = nullptr; + + strcpy(godot_nir_arch_name, Engine::get_singleton()->get_architecture_name().ascii().get_data()); +} + +D3D12Context::~D3D12Context() { + if (md.fence_event) { + CloseHandle(md.fence_event); + } + if (frame_fence_event) { + CloseHandle(frame_fence_event); + } +} diff --git a/drivers/d3d12/d3d12_context.h b/drivers/d3d12/d3d12_context.h new file mode 100644 index 0000000000..31e75affd0 --- /dev/null +++ b/drivers/d3d12/d3d12_context.h @@ -0,0 +1,248 @@ +/**************************************************************************/ +/* d3d12_context.h */ +/**************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/**************************************************************************/ +/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ +/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/**************************************************************************/ + +#ifndef D3D12_CONTEXT_H +#define D3D12_CONTEXT_H + +#include "core/error/error_list.h" +#include "core/os/mutex.h" +#include "core/string/ustring.h" +#include "core/templates/rb_map.h" +#include "core/templates/rid_owner.h" +#include "servers/display_server.h" +#include "servers/rendering/rendering_device.h" + +#include "d3dx12.h" +#include <dxgi1_6.h> +#define D3D12MA_D3D12_HEADERS_ALREADY_INCLUDED +#include "D3D12MemAlloc.h" + +#include <wrl/client.h> +using Microsoft::WRL::ComPtr; + +class D3D12Context { +public: + struct DeviceLimits { + uint64_t max_srvs_per_shader_stage; + uint64_t max_cbvs_per_shader_stage; + uint64_t max_samplers_across_all_stages; + uint64_t max_uavs_across_all_stages; + uint64_t timestamp_frequency; + }; + + struct SubgroupCapabilities { + uint32_t size; + bool wave_ops_supported; + uint32_t supported_stages_flags_rd() const; + uint32_t supported_operations_flags_rd() const; + }; + + // Following VulkanContext definition. + struct MultiviewCapabilities { + bool is_supported; + bool geometry_shader_is_supported; + bool tessellation_shader_is_supported; + uint32_t max_view_count; + uint32_t max_instance_count; + }; + + struct VRSCapabilities { + bool draw_call_supported; // We can specify our fragment rate on a draw call level. + bool primitive_supported; // We can specify our fragment rate on each drawcall. + bool primitive_in_multiviewport; + bool ss_image_supported; // We can provide a density map attachment on our framebuffer. + uint32_t ss_image_tile_size; + bool additional_rates_supported; + }; + + struct ShaderCapabilities { + D3D_SHADER_MODEL shader_model; + bool native_16bit_ops; + }; + + struct StorageBufferCapabilities { + bool storage_buffer_16_bit_access_is_supported; + }; + + struct FormatCapabilities { + bool relaxed_casting_supported; + }; + +private: + enum { + FRAME_LAG = 2, + IMAGE_COUNT = FRAME_LAG + 1, + }; + + ComPtr<IDXGIFactory2> dxgi_factory; + ComPtr<IDXGIAdapter> gpu; + DeviceLimits gpu_limits = {}; + struct DeviceBasics { + ComPtr<ID3D12Device> device; + ComPtr<ID3D12CommandQueue> queue; + ComPtr<ID3D12Fence> fence; + HANDLE fence_event = nullptr; + UINT64 fence_value = 0; + } md; // 'Main device', as opposed to local device. + + uint32_t feature_level = 0; // Major * 10 + minor. + bool tearing_supported = false; + SubgroupCapabilities subgroup_capabilities; + MultiviewCapabilities multiview_capabilities; + VRSCapabilities vrs_capabilities; + ShaderCapabilities shader_capabilities; + StorageBufferCapabilities storage_buffer_capabilities; + FormatCapabilities format_capabilities; + + String adapter_vendor; + String adapter_name; + RenderingDevice::DeviceType adapter_type = {}; + String pipeline_cache_id; + + ComPtr<D3D12MA::Allocator> allocator; + + bool buffers_prepared = false; + + DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN; + uint32_t frame = 0; + ComPtr<ID3D12Fence> frame_fence; + HANDLE frame_fence_event = nullptr; + + struct Window { + HWND hwnd = nullptr; + ComPtr<IDXGISwapChain3> swapchain; + UINT swapchain_flags = 0; + UINT sync_interval = 1; + UINT present_flags = 0; + ComPtr<ID3D12Resource> render_targets[IMAGE_COUNT]; + uint32_t current_buffer = 0; + int width = 0; + int height = 0; + DisplayServer::VSyncMode vsync_mode = DisplayServer::VSYNC_ENABLED; + ComPtr<ID3D12DescriptorHeap> rtv_heap; + }; + + struct LocalDevice : public DeviceBasics { + bool waiting = false; + HANDLE fence_event = nullptr; + UINT64 fence_value = 0; + }; + + RID_Owner<LocalDevice, true> local_device_owner; + + HashMap<DisplayServer::WindowID, Window> windows; + + // Commands. + + Vector<ID3D12CommandList *> command_list_queue; + int command_list_count = 1; + + static void _debug_message_func( + D3D12_MESSAGE_CATEGORY p_category, + D3D12_MESSAGE_SEVERITY p_severity, + D3D12_MESSAGE_ID p_id, + LPCSTR p_description, + void *p_context); + + Error _initialize_debug_layers(); + + Error _select_adapter(int &r_index); + void _dump_adapter_info(int p_index); + Error _create_device(DeviceBasics &r_basics); + Error _get_device_limits(); + Error _check_capabilities(); + + Error _update_swap_chain(Window *window); + + void _wait_for_idle_queue(ID3D12CommandQueue *p_queue); + +protected: + virtual bool _use_validation_layers(); + +public: + uint32_t get_feat_level_major() const { return feature_level / 10; }; + uint32_t get_feat_level_minor() const { return feature_level % 10; }; + const SubgroupCapabilities &get_subgroup_capabilities() const { return subgroup_capabilities; }; + const MultiviewCapabilities &get_multiview_capabilities() const { return multiview_capabilities; }; + const VRSCapabilities &get_vrs_capabilities() const { return vrs_capabilities; }; + const ShaderCapabilities &get_shader_capabilities() const { return shader_capabilities; }; + const StorageBufferCapabilities &get_storage_buffer_capabilities() const { return storage_buffer_capabilities; }; + const FormatCapabilities &get_format_capabilities() const { return format_capabilities; }; + + ComPtr<ID3D12Device> get_device(); + ComPtr<IDXGIAdapter> get_adapter(); + D3D12MA::Allocator *get_allocator(); + int get_swapchain_image_count() const; + Error window_create(DisplayServer::WindowID p_window_id, DisplayServer::VSyncMode p_vsync_mode, HWND p_window, HINSTANCE p_instance, int p_width, int p_height); + void window_resize(DisplayServer::WindowID p_window_id, int p_width, int p_height); + int window_get_width(DisplayServer::WindowID p_window = 0); + int window_get_height(DisplayServer::WindowID p_window = 0); + bool window_is_valid_swapchain(DisplayServer::WindowID p_window = 0); + void window_destroy(DisplayServer::WindowID p_window_id); + CD3DX12_CPU_DESCRIPTOR_HANDLE window_get_framebuffer_rtv_handle(DisplayServer::WindowID p_window = 0); + ID3D12Resource *window_get_framebuffer_texture(DisplayServer::WindowID p_window = 0); + + RID local_device_create(); + ComPtr<ID3D12Device> local_device_get_d3d12_device(RID p_local_device); + void local_device_push_command_lists(RID p_local_device, ID3D12CommandList *const *p_lists, int p_count); + void local_device_sync(RID p_local_device); + void local_device_free(RID p_local_device); + + DXGI_FORMAT get_screen_format() const; + DeviceLimits get_device_limits() const; + + void set_setup_list(ID3D12CommandList *p_command_list); + void append_command_list(ID3D12CommandList *p_command_list); + void resize_notify(); + void flush(bool p_flush_setup = false, bool p_flush_pending = false); + void prepare_buffers(ID3D12GraphicsCommandList *p_command_list); + void postpare_buffers(ID3D12GraphicsCommandList *p_command_list); + Error swap_buffers(); + Error initialize(); + + void command_begin_label(ID3D12GraphicsCommandList *p_command_list, String p_label_name, const Color p_color); + void command_insert_label(ID3D12GraphicsCommandList *p_command_list, String p_label_name, const Color p_color); + void command_end_label(ID3D12GraphicsCommandList *p_command_list); + void set_object_name(ID3D12Object *p_object, String p_object_name); + + String get_device_vendor_name() const; + String get_device_name() const; + RenderingDevice::DeviceType get_device_type() const; + String get_device_api_version() const; + String get_device_pipeline_cache_uuid() const; + + void set_vsync_mode(DisplayServer::WindowID p_window, DisplayServer::VSyncMode p_mode); + DisplayServer::VSyncMode get_vsync_mode(DisplayServer::WindowID p_window = 0) const; + + D3D12Context(); + virtual ~D3D12Context(); +}; + +#endif // D3D12_CONTEXT_H diff --git a/drivers/d3d12/d3d12_godot_nir_bridge.h b/drivers/d3d12/d3d12_godot_nir_bridge.h new file mode 100644 index 0000000000..f66c4edf89 --- /dev/null +++ b/drivers/d3d12/d3d12_godot_nir_bridge.h @@ -0,0 +1,60 @@ +/**************************************************************************/ +/* d3d12_godot_nir_bridge.h */ +/**************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/**************************************************************************/ +/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ +/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/**************************************************************************/ + +#ifndef D3D12_GODOT_NIR_BRIDGE_H +#define D3D12_GODOT_NIR_BRIDGE_H + +#include <stdint.h> + +#ifdef __cplusplus +extern "C" { +#endif + +// This one leaves room for potentially extremely copious bindings in a set. +static const uint32_t GODOT_NIR_DESCRIPTOR_SET_MULTIPLIER = 100000000; +// This one leaves room for potentially big sized arrays. +static const uint32_t GODOT_NIR_BINDING_MULTIPLIER = 100000; + +static const uint64_t GODOT_NIR_SC_SENTINEL_MAGIC = 0x45678900; // This must be as big as to be VBR-ed as a 32 bits number. +static const uint64_t GODOT_NIR_SC_SENTINEL_MAGIC_MASK = 0xffffffffffffff00; +static const uint64_t GODOT_NIR_SC_SENTINEL_ID_MASK = 0x00000000000000ff; + +typedef struct GodotNirCallbacks { + void *data; + void (*report_resource)(uint32_t p_register, uint32_t p_space, uint32_t p_dxil_type, void *p_data); + void (*report_sc_bit_offset_fn)(uint32_t p_sc_id, uint64_t p_bit_offset, void *p_data); + void (*report_bitcode_bit_offset_fn)(uint64_t p_bit_offset, void *p_data); +} GodotNirCallbacks; + +#ifdef __cplusplus +} +#endif + +#endif // D3D12_GODOT_NIR_BRIDGE_H diff --git a/drivers/d3d12/d3d12ma.cpp b/drivers/d3d12/d3d12ma.cpp new file mode 100644 index 0000000000..0ac2f71074 --- /dev/null +++ b/drivers/d3d12/d3d12ma.cpp @@ -0,0 +1,34 @@ +/**************************************************************************/ +/* d3d12ma.cpp */ +/**************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/**************************************************************************/ +/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ +/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/**************************************************************************/ + +#include "d3d12_context.h" + +#pragma warning(disable : 4189 4324 4505) +#include "thirdparty/d3d12ma/D3D12MemAlloc.cpp" diff --git a/drivers/d3d12/rendering_device_d3d12.cpp b/drivers/d3d12/rendering_device_d3d12.cpp new file mode 100644 index 0000000000..839bcf6bc7 --- /dev/null +++ b/drivers/d3d12/rendering_device_d3d12.cpp @@ -0,0 +1,9480 @@ +/**************************************************************************/ +/* rendering_device_d3d12.cpp */ +/**************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/**************************************************************************/ +/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ +/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/**************************************************************************/ + +#include "rendering_device_d3d12.h" + +#include "core/config/project_settings.h" +#include "core/io/compression.h" +#include "core/io/file_access.h" +#include "core/io/marshalls.h" +#include "core/object/worker_thread_pool.h" +#include "core/os/os.h" +#include "core/templates/hashfuncs.h" +#include "d3d12_godot_nir_bridge.h" +#include "modules/regex/regex.h" +#include "thirdparty/zlib/zlib.h" + +#ifdef DEV_ENABLED +#include "core/crypto/hashing_context.h" +#endif + +// No point in fighting warnings in Mesa. +#pragma warning(push) +#pragma warning(disable : 4200) // "nonstandard extension used: zero-sized array in struct/union". +#pragma warning(disable : 4806) // "'&': unsafe operation: no value of type 'bool' promoted to type 'uint32_t' can equal the given constant". +#include "dxil_validator.h" +#include "nir_spirv.h" +#include "nir_to_dxil.h" +#include "spirv_to_dxil.h" +extern "C" { +#include "dxil_spirv_nir.h" +} +#pragma warning(pop) + +#define ALIGN(m_number, m_alignment) ((((m_number) + ((m_alignment)-1)) / (m_alignment)) * (m_alignment)) + +#ifdef USE_SMALL_ALLOCS_POOL +static const uint32_t SMALL_ALLOCATION_MAX_SIZE = 4096; +#endif + +static const D3D12_RANGE VOID_RANGE = {}; + +static const uint32_t MAX_VULKAN_SETS = 16; +static const uint32_t ROOT_CONSTANT_SPACE = MAX_VULKAN_SETS + 1; +static const uint32_t ROOT_CONSTANT_REGISTER = 0; +static const uint32_t RUNTIME_DATA_SPACE = MAX_VULKAN_SETS + 2; +static const uint32_t RUNTIME_DATA_REGISTER = 0; + +static const uint32_t MAX_IMAGE_FORMAT_PLANES = 2; + +#ifdef DEV_ENABLED +//#define DEBUG_COUNT_BARRIERS +#endif + +RenderingDeviceD3D12::Buffer *RenderingDeviceD3D12::_get_buffer_from_owner(RID p_buffer) { + Buffer *buffer = nullptr; + if (vertex_buffer_owner.owns(p_buffer)) { + buffer = vertex_buffer_owner.get_or_null(p_buffer); + } else if (index_buffer_owner.owns(p_buffer)) { + buffer = index_buffer_owner.get_or_null(p_buffer); + } else if (uniform_buffer_owner.owns(p_buffer)) { + buffer = uniform_buffer_owner.get_or_null(p_buffer); + } else if (texture_buffer_owner.owns(p_buffer)) { + buffer = &texture_buffer_owner.get_or_null(p_buffer)->buffer; + } else if (storage_buffer_owner.owns(p_buffer)) { + buffer = storage_buffer_owner.get_or_null(p_buffer); + } + return buffer; +} + +void RenderingDeviceD3D12::_add_dependency(RID p_id, RID p_depends_on) { + if (!dependency_map.has(p_depends_on)) { + dependency_map[p_depends_on] = HashSet<RID>(); + } + + dependency_map[p_depends_on].insert(p_id); + + if (!reverse_dependency_map.has(p_id)) { + reverse_dependency_map[p_id] = HashSet<RID>(); + } + + reverse_dependency_map[p_id].insert(p_depends_on); +} + +void RenderingDeviceD3D12::_free_dependencies(RID p_id) { + // Direct dependencies must be freed. + + HashMap<RID, HashSet<RID>>::Iterator E = dependency_map.find(p_id); + if (E) { + while (E->value.size()) { + free(*E->value.begin()); + } + dependency_map.remove(E); + } + + // Reverse dependencies must be unreferenced. + E = reverse_dependency_map.find(p_id); + + if (E) { + for (const RID &F : E->value) { + HashMap<RID, HashSet<RID>>::Iterator G = dependency_map.find(F); + ERR_CONTINUE(!G); + ERR_CONTINUE(!G->value.has(p_id)); + G->value.erase(p_id); + } + + reverse_dependency_map.remove(E); + } +} + +// NOTE: RD's packed format names are reversed in relation to DXGI's; e.g.:. +// - DATA_FORMAT_A8B8G8R8_UNORM_PACK32 -> DXGI_FORMAT_R8G8B8A8_UNORM (packed; note ABGR vs. RGBA). +// - DATA_FORMAT_B8G8R8A8_UNORM -> DXGI_FORMAT_B8G8R8A8_UNORM (not packed; note BGRA order matches). +// TODO: Add YUV formats properly, which would require better support for planes in the RD API. +const RenderingDeviceD3D12::D3D12Format RenderingDeviceD3D12::d3d12_formats[RenderingDevice::DATA_FORMAT_MAX] = { + /* DATA_FORMAT_R4G4_UNORM_PACK8 */ {}, + /* DATA_FORMAT_R4G4B4A4_UNORM_PACK16 */ { DXGI_FORMAT_B4G4R4A4_UNORM, DXGI_FORMAT_B4G4R4A4_UNORM, D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(1, 2, 3, 0) }, + /* DATA_FORMAT_B4G4R4A4_UNORM_PACK16 */ { DXGI_FORMAT_B4G4R4A4_UNORM, DXGI_FORMAT_B4G4R4A4_UNORM, D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(3, 2, 1, 0) }, + /* DATA_FORMAT_R5G6B5_UNORM_PACK16 */ { DXGI_FORMAT_B5G6R5_UNORM, DXGI_FORMAT_B5G6R5_UNORM }, + /* DATA_FORMAT_B5G6R5_UNORM_PACK16 */ { DXGI_FORMAT_B5G6R5_UNORM, DXGI_FORMAT_B5G6R5_UNORM, D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(2, 1, 0, 3) }, + /* DATA_FORMAT_R5G5B5A1_UNORM_PACK16 */ { DXGI_FORMAT_B5G6R5_UNORM, DXGI_FORMAT_B5G5R5A1_UNORM, D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(1, 2, 3, 0) }, + /* DATA_FORMAT_B5G5R5A1_UNORM_PACK16 */ { DXGI_FORMAT_B5G6R5_UNORM, DXGI_FORMAT_B5G5R5A1_UNORM, D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(3, 2, 1, 0) }, + /* DATA_FORMAT_A1R5G5B5_UNORM_PACK16 */ { DXGI_FORMAT_B5G6R5_UNORM, DXGI_FORMAT_B5G5R5A1_UNORM }, + /* DATA_FORMAT_R8_UNORM */ { DXGI_FORMAT_R8_TYPELESS, DXGI_FORMAT_R8_UNORM }, + /* DATA_FORMAT_R8_SNORM */ { DXGI_FORMAT_R8_TYPELESS, DXGI_FORMAT_R8_SNORM }, + /* DATA_FORMAT_R8_USCALED */ { DXGI_FORMAT_R8_TYPELESS, DXGI_FORMAT_R8_UINT }, + /* DATA_FORMAT_R8_SSCALED */ { DXGI_FORMAT_R8_TYPELESS, DXGI_FORMAT_R8_SINT }, + /* DATA_FORMAT_R8_UINT */ { DXGI_FORMAT_R8_TYPELESS, DXGI_FORMAT_R8_UINT }, + /* DATA_FORMAT_R8_SINT */ { DXGI_FORMAT_R8_TYPELESS, DXGI_FORMAT_R8_SINT }, + /* DATA_FORMAT_R8_SRGB */ {}, + /* DATA_FORMAT_R8G8_UNORM */ { DXGI_FORMAT_R8G8_TYPELESS, DXGI_FORMAT_R8G8_UNORM }, + /* DATA_FORMAT_R8G8_SNORM */ { DXGI_FORMAT_R8G8_TYPELESS, DXGI_FORMAT_R8G8_SNORM }, + /* DATA_FORMAT_R8G8_USCALED */ { DXGI_FORMAT_R8G8_TYPELESS, DXGI_FORMAT_R8G8_UINT }, + /* DATA_FORMAT_R8G8_SSCALED */ { DXGI_FORMAT_R8G8_TYPELESS, DXGI_FORMAT_R8G8_SINT }, + /* DATA_FORMAT_R8G8_UINT */ { DXGI_FORMAT_R8G8_TYPELESS, DXGI_FORMAT_R8G8_UINT }, + /* DATA_FORMAT_R8G8_SINT */ { DXGI_FORMAT_R8G8_TYPELESS, DXGI_FORMAT_R8G8_SINT }, + /* DATA_FORMAT_R8G8_SRGB */ {}, + /* DATA_FORMAT_R8G8B8_UNORM */ {}, + /* DATA_FORMAT_R8G8B8_SNORM */ {}, + /* DATA_FORMAT_R8G8B8_USCALED */ {}, + /* DATA_FORMAT_R8G8B8_SSCALED */ {}, + /* DATA_FORMAT_R8G8B8_UINT */ {}, + /* DATA_FORMAT_R8G8B8_SINT */ {}, + /* DATA_FORMAT_R8G8B8_SRGB */ {}, + /* DATA_FORMAT_B8G8R8_UNORM */ {}, + /* DATA_FORMAT_B8G8R8_SNORM */ {}, + /* DATA_FORMAT_B8G8R8_USCALED */ {}, + /* DATA_FORMAT_B8G8R8_SSCALED */ {}, + /* DATA_FORMAT_B8G8R8_UINT */ {}, + /* DATA_FORMAT_B8G8R8_SINT */ {}, + /* DATA_FORMAT_B8G8R8_SRGB */ {}, + /* DATA_FORMAT_R8G8B8A8_UNORM */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UNORM }, + /* DATA_FORMAT_R8G8B8A8_SNORM */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_SNORM }, + /* DATA_FORMAT_R8G8B8A8_USCALED */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UINT }, + /* DATA_FORMAT_R8G8B8A8_SSCALED */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_SINT }, + /* DATA_FORMAT_R8G8B8A8_UINT */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UINT }, + /* DATA_FORMAT_R8G8B8A8_SINT */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_SINT }, + /* DATA_FORMAT_R8G8B8A8_SRGB */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB }, + /* DATA_FORMAT_B8G8R8A8_UNORM */ { DXGI_FORMAT_B8G8R8A8_TYPELESS, DXGI_FORMAT_B8G8R8A8_UNORM }, + /* DATA_FORMAT_B8G8R8A8_SNORM */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_SNORM }, + /* DATA_FORMAT_B8G8R8A8_USCALED */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UINT }, + /* DATA_FORMAT_B8G8R8A8_SSCALED */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_SINT }, + /* DATA_FORMAT_B8G8R8A8_UINT */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UINT }, + /* DATA_FORMAT_B8G8R8A8_SINT */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_SINT }, + /* DATA_FORMAT_B8G8R8A8_SRGB */ { DXGI_FORMAT_B8G8R8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB }, + /* DATA_FORMAT_A8B8G8R8_UNORM_PACK32 */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UNORM }, + /* DATA_FORMAT_A8B8G8R8_SNORM_PACK32 */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_SNORM }, + /* DATA_FORMAT_A8B8G8R8_USCALED_PACK32 */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UINT }, + /* DATA_FORMAT_A8B8G8R8_SSCALED_PACK32 */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_SINT }, + /* DATA_FORMAT_A8B8G8R8_UINT_PACK32 */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UINT }, + /* DATA_FORMAT_A8B8G8R8_SINT_PACK32 */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_SINT }, + /* DATA_FORMAT_A8B8G8R8_SRGB_PACK32 */ { DXGI_FORMAT_B8G8R8A8_TYPELESS, DXGI_FORMAT_B8G8R8A8_UNORM_SRGB }, + /* DATA_FORMAT_A2R10G10B10_UNORM_PACK32 */ { DXGI_FORMAT_R10G10B10A2_TYPELESS, DXGI_FORMAT_R10G10B10A2_UNORM, D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(2, 1, 0, 3) }, + /* DATA_FORMAT_A2R10G10B10_SNORM_PACK32 */ {}, + /* DATA_FORMAT_A2R10G10B10_USCALED_PACK32 */ { DXGI_FORMAT_R10G10B10A2_TYPELESS, DXGI_FORMAT_R10G10B10A2_UINT, D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(2, 1, 0, 3) }, + /* DATA_FORMAT_A2R10G10B10_SSCALED_PACK32 */ {}, + /* DATA_FORMAT_A2R10G10B10_UINT_PACK32 */ { DXGI_FORMAT_R10G10B10A2_TYPELESS, DXGI_FORMAT_R10G10B10A2_UINT, D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(2, 1, 0, 3) }, + /* DATA_FORMAT_A2R10G10B10_SINT_PACK32 */ {}, + /* DATA_FORMAT_A2B10G10R10_UNORM_PACK32 */ { DXGI_FORMAT_R10G10B10A2_TYPELESS, DXGI_FORMAT_R10G10B10A2_UNORM }, + /* DATA_FORMAT_A2B10G10R10_SNORM_PACK32 */ {}, + /* DATA_FORMAT_A2B10G10R10_USCALED_PACK32 */ { DXGI_FORMAT_R10G10B10A2_TYPELESS, DXGI_FORMAT_R10G10B10A2_UINT }, + /* DATA_FORMAT_A2B10G10R10_SSCALED_PACK32 */ {}, + /* DATA_FORMAT_A2B10G10R10_UINT_PACK32 */ { DXGI_FORMAT_R10G10B10A2_TYPELESS, DXGI_FORMAT_R10G10B10A2_UINT }, + /* DATA_FORMAT_A2B10G10R10_SINT_PACK32 */ {}, + /* DATA_FORMAT_R16_UNORM */ { DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R16_UNORM }, + /* DATA_FORMAT_R16_SNORM */ { DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R16_SNORM }, + /* DATA_FORMAT_R16_USCALED */ { DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R16_UINT }, + /* DATA_FORMAT_R16_SSCALED */ { DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R16_SINT }, + /* DATA_FORMAT_R16_UINT */ { DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R16_UINT }, + /* DATA_FORMAT_R16_SINT */ { DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R16_SINT }, + /* DATA_FORMAT_R16_SFLOAT */ { DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R16_FLOAT }, + /* DATA_FORMAT_R16G16_UNORM */ { DXGI_FORMAT_R16G16_TYPELESS, DXGI_FORMAT_R16G16_UNORM }, + /* DATA_FORMAT_R16G16_SNORM */ { DXGI_FORMAT_R16G16_TYPELESS, DXGI_FORMAT_R16G16_SNORM }, + /* DATA_FORMAT_R16G16_USCALED */ { DXGI_FORMAT_R16G16_TYPELESS, DXGI_FORMAT_R16G16_UINT }, + /* DATA_FORMAT_R16G16_SSCALED */ { DXGI_FORMAT_R16G16_TYPELESS, DXGI_FORMAT_R16G16_SINT }, + /* DATA_FORMAT_R16G16_UINT */ { DXGI_FORMAT_R16G16_TYPELESS, DXGI_FORMAT_R16G16_UINT }, + /* DATA_FORMAT_R16G16_SINT */ { DXGI_FORMAT_R16G16_TYPELESS, DXGI_FORMAT_R16G16_SINT }, + /* DATA_FORMAT_R16G16_SFLOAT */ { DXGI_FORMAT_R16G16_TYPELESS, DXGI_FORMAT_R16G16_FLOAT }, + /* DATA_FORMAT_R16G16B16_UNORM */ {}, + /* DATA_FORMAT_R16G16B16_SNORM */ {}, + /* DATA_FORMAT_R16G16B16_USCALED */ {}, + /* DATA_FORMAT_R16G16B16_SSCALED */ {}, + /* DATA_FORMAT_R16G16B16_UINT */ {}, + /* DATA_FORMAT_R16G16B16_SINT */ {}, + /* DATA_FORMAT_R16G16B16_SFLOAT */ {}, + /* DATA_FORMAT_R16G16B16A16_UNORM */ { DXGI_FORMAT_R16G16B16A16_TYPELESS, DXGI_FORMAT_R16G16B16A16_UNORM }, + /* DATA_FORMAT_R16G16B16A16_SNORM */ { DXGI_FORMAT_R16G16B16A16_TYPELESS, DXGI_FORMAT_R16G16B16A16_SNORM }, + /* DATA_FORMAT_R16G16B16A16_USCALED */ { DXGI_FORMAT_R16G16B16A16_TYPELESS, DXGI_FORMAT_R16G16B16A16_UINT }, + /* DATA_FORMAT_R16G16B16A16_SSCALED */ { DXGI_FORMAT_R16G16B16A16_TYPELESS, DXGI_FORMAT_R16G16B16A16_SINT }, + /* DATA_FORMAT_R16G16B16A16_UINT */ { DXGI_FORMAT_R16G16B16A16_TYPELESS, DXGI_FORMAT_R16G16B16A16_UINT }, + /* DATA_FORMAT_R16G16B16A16_SINT */ { DXGI_FORMAT_R16G16B16A16_TYPELESS, DXGI_FORMAT_R16G16B16A16_SINT }, + /* DATA_FORMAT_R16G16B16A16_SFLOAT */ { DXGI_FORMAT_R16G16B16A16_TYPELESS, DXGI_FORMAT_R16G16B16A16_FLOAT }, + /* DATA_FORMAT_R32_UINT */ { DXGI_FORMAT_R32_TYPELESS, DXGI_FORMAT_R32_UINT }, + /* DATA_FORMAT_R32_SINT */ { DXGI_FORMAT_R32_TYPELESS, DXGI_FORMAT_R32_SINT }, + /* DATA_FORMAT_R32_SFLOAT */ { DXGI_FORMAT_R32_TYPELESS, DXGI_FORMAT_R32_FLOAT }, + /* DATA_FORMAT_R32G32_UINT */ { DXGI_FORMAT_R32G32_TYPELESS, DXGI_FORMAT_R32G32_UINT }, + /* DATA_FORMAT_R32G32_SINT */ { DXGI_FORMAT_R32G32_TYPELESS, DXGI_FORMAT_R32G32_SINT }, + /* DATA_FORMAT_R32G32_SFLOAT */ { DXGI_FORMAT_R32G32_TYPELESS, DXGI_FORMAT_R32G32_FLOAT }, + /* DATA_FORMAT_R32G32B32_UINT */ { DXGI_FORMAT_R32G32B32_TYPELESS, DXGI_FORMAT_R32G32B32_UINT }, + /* DATA_FORMAT_R32G32B32_SINT */ { DXGI_FORMAT_R32G32B32_TYPELESS, DXGI_FORMAT_R32G32B32_SINT }, + /* DATA_FORMAT_R32G32B32_SFLOAT */ { DXGI_FORMAT_R32G32B32_TYPELESS, DXGI_FORMAT_R32G32B32_FLOAT }, + /* DATA_FORMAT_R32G32B32A32_UINT */ { DXGI_FORMAT_R32G32B32A32_TYPELESS, DXGI_FORMAT_R32G32B32A32_UINT }, + /* DATA_FORMAT_R32G32B32A32_SINT */ { DXGI_FORMAT_R32G32B32A32_TYPELESS, DXGI_FORMAT_R32G32B32A32_SINT }, + /* DATA_FORMAT_R32G32B32A32_SFLOAT */ { DXGI_FORMAT_R32G32B32A32_TYPELESS, DXGI_FORMAT_R32G32B32A32_FLOAT }, + /* DATA_FORMAT_R64_UINT */ {}, + /* DATA_FORMAT_R64_SINT */ {}, + /* DATA_FORMAT_R64_SFLOAT */ {}, + /* DATA_FORMAT_R64G64_UINT */ {}, + /* DATA_FORMAT_R64G64_SINT */ {}, + /* DATA_FORMAT_R64G64_SFLOAT */ {}, + /* DATA_FORMAT_R64G64B64_UINT */ {}, + /* DATA_FORMAT_R64G64B64_SINT */ {}, + /* DATA_FORMAT_R64G64B64_SFLOAT */ {}, + /* DATA_FORMAT_R64G64B64A64_UINT */ {}, + /* DATA_FORMAT_R64G64B64A64_SINT */ {}, + /* DATA_FORMAT_R64G64B64A64_SFLOAT */ {}, + /* DATA_FORMAT_B10G11R11_UFLOAT_PACK32 */ { DXGI_FORMAT_R11G11B10_FLOAT, DXGI_FORMAT_R11G11B10_FLOAT }, + /* DATA_FORMAT_E5B9G9R9_UFLOAT_PACK32 */ { DXGI_FORMAT_R9G9B9E5_SHAREDEXP, DXGI_FORMAT_R9G9B9E5_SHAREDEXP }, + /* DATA_FORMAT_D16_UNORM */ { DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R16_UNORM, 0, DXGI_FORMAT_D16_UNORM }, + /* DATA_FORMAT_X8_D24_UNORM_PACK32 */ { DXGI_FORMAT_R24G8_TYPELESS, DXGI_FORMAT_UNKNOWN, 0, DXGI_FORMAT_D24_UNORM_S8_UINT }, + /* DATA_FORMAT_D32_SFLOAT */ { DXGI_FORMAT_R32_TYPELESS, DXGI_FORMAT_R32_FLOAT, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, DXGI_FORMAT_D32_FLOAT }, + /* DATA_FORMAT_S8_UINT */ {}, + /* DATA_FORMAT_D16_UNORM_S8_UINT */ {}, + /* DATA_FORMAT_D24_UNORM_S8_UINT */ { DXGI_FORMAT_R24G8_TYPELESS, DXGI_FORMAT_UNKNOWN, 0, DXGI_FORMAT_D24_UNORM_S8_UINT }, + /* DATA_FORMAT_D32_SFLOAT_S8_UINT */ { DXGI_FORMAT_R32G8X24_TYPELESS, DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, DXGI_FORMAT_D32_FLOAT_S8X24_UINT }, + /* DATA_FORMAT_BC1_RGB_UNORM_BLOCK */ { DXGI_FORMAT_BC1_TYPELESS, DXGI_FORMAT_BC1_UNORM, D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(0, 1, 2, D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_1) }, + /* DATA_FORMAT_BC1_RGB_SRGB_BLOCK */ { DXGI_FORMAT_BC1_TYPELESS, DXGI_FORMAT_BC1_UNORM_SRGB, D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(0, 1, 2, D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_1) }, + /* DATA_FORMAT_BC1_RGBA_UNORM_BLOCK */ { DXGI_FORMAT_BC1_TYPELESS, DXGI_FORMAT_BC1_UNORM }, + /* DATA_FORMAT_BC1_RGBA_SRGB_BLOCK */ { DXGI_FORMAT_BC1_TYPELESS, DXGI_FORMAT_BC1_UNORM_SRGB }, + /* DATA_FORMAT_BC2_UNORM_BLOCK */ { DXGI_FORMAT_BC2_TYPELESS, DXGI_FORMAT_BC2_UNORM }, + /* DATA_FORMAT_BC2_SRGB_BLOCK */ { DXGI_FORMAT_BC2_TYPELESS, DXGI_FORMAT_BC2_UNORM_SRGB }, + /* DATA_FORMAT_BC3_UNORM_BLOCK */ { DXGI_FORMAT_BC3_TYPELESS, DXGI_FORMAT_BC3_UNORM }, + /* DATA_FORMAT_BC3_SRGB_BLOCK */ { DXGI_FORMAT_BC3_TYPELESS, DXGI_FORMAT_BC3_UNORM_SRGB }, + /* DATA_FORMAT_BC4_UNORM_BLOCK */ { DXGI_FORMAT_BC4_TYPELESS, DXGI_FORMAT_BC4_UNORM }, + /* DATA_FORMAT_BC4_SNORM_BLOCK */ { DXGI_FORMAT_BC4_TYPELESS, DXGI_FORMAT_BC4_SNORM }, + /* DATA_FORMAT_BC5_UNORM_BLOCK */ { DXGI_FORMAT_BC5_TYPELESS, DXGI_FORMAT_BC5_UNORM }, + /* DATA_FORMAT_BC5_SNORM_BLOCK */ { DXGI_FORMAT_BC5_TYPELESS, DXGI_FORMAT_BC5_SNORM }, + /* DATA_FORMAT_BC6H_UFLOAT_BLOCK */ { DXGI_FORMAT_BC6H_TYPELESS, DXGI_FORMAT_BC6H_UF16 }, + /* DATA_FORMAT_BC6H_SFLOAT_BLOCK */ { DXGI_FORMAT_BC6H_TYPELESS, DXGI_FORMAT_BC6H_SF16 }, + /* DATA_FORMAT_BC7_UNORM_BLOCK */ { DXGI_FORMAT_BC7_TYPELESS, DXGI_FORMAT_BC7_UNORM }, + /* DATA_FORMAT_BC7_SRGB_BLOCK */ { DXGI_FORMAT_BC7_TYPELESS, DXGI_FORMAT_BC7_UNORM_SRGB }, + /* DATA_FORMAT_ETC2_R8G8B8_UNORM_BLOCK */ {}, + /* DATA_FORMAT_ETC2_R8G8B8_SRGB_BLOCK */ {}, + /* DATA_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK */ {}, + /* DATA_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK */ {}, + /* DATA_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK */ {}, + /* DATA_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK */ {}, + /* DATA_FORMAT_EAC_R11_UNORM_BLOCK */ {}, + /* DATA_FORMAT_EAC_R11_SNORM_BLOCK */ {}, + /* DATA_FORMAT_EAC_R11G11_UNORM_BLOCK */ {}, + /* DATA_FORMAT_EAC_R11G11_SNORM_BLOCK */ {}, + /* DATA_FORMAT_ASTC_4x4_UNORM_BLOCK */ {}, + /* DATA_FORMAT_ASTC_4x4_SRGB_BLOCK */ {}, + /* DATA_FORMAT_ASTC_5x4_UNORM_BLOCK */ {}, + /* DATA_FORMAT_ASTC_5x4_SRGB_BLOCK */ {}, + /* DATA_FORMAT_ASTC_5x5_UNORM_BLOCK */ {}, + /* DATA_FORMAT_ASTC_5x5_SRGB_BLOCK */ {}, + /* DATA_FORMAT_ASTC_6x5_UNORM_BLOCK */ {}, + /* DATA_FORMAT_ASTC_6x5_SRGB_BLOCK */ {}, + /* DATA_FORMAT_ASTC_6x6_UNORM_BLOCK */ {}, + /* DATA_FORMAT_ASTC_6x6_SRGB_BLOCK */ {}, + /* DATA_FORMAT_ASTC_8x5_UNORM_BLOCK */ {}, + /* DATA_FORMAT_ASTC_8x5_SRGB_BLOCK */ {}, + /* DATA_FORMAT_ASTC_8x6_UNORM_BLOCK */ {}, + /* DATA_FORMAT_ASTC_8x6_SRGB_BLOCK */ {}, + /* DATA_FORMAT_ASTC_8x8_UNORM_BLOCK */ {}, + /* DATA_FORMAT_ASTC_8x8_SRGB_BLOCK */ {}, + /* DATA_FORMAT_ASTC_10x5_UNORM_BLOCK */ {}, + /* DATA_FORMAT_ASTC_10x5_SRGB_BLOCK */ {}, + /* DATA_FORMAT_ASTC_10x6_UNORM_BLOCK */ {}, + /* DATA_FORMAT_ASTC_10x6_SRGB_BLOCK */ {}, + /* DATA_FORMAT_ASTC_10x8_UNORM_BLOCK */ {}, + /* DATA_FORMAT_ASTC_10x8_SRGB_BLOCK */ {}, + /* DATA_FORMAT_ASTC_10x10_UNORM_BLOCK */ {}, + /* DATA_FORMAT_ASTC_10x10_SRGB_BLOCK */ {}, + /* DATA_FORMAT_ASTC_12x10_UNORM_BLOCK */ {}, + /* DATA_FORMAT_ASTC_12x10_SRGB_BLOCK */ {}, + /* DATA_FORMAT_ASTC_12x12_UNORM_BLOCK */ {}, + /* DATA_FORMAT_ASTC_12x12_SRGB_BLOCK */ {}, + /* DATA_FORMAT_G8B8G8R8_422_UNORM */ {}, + /* DATA_FORMAT_B8G8R8G8_422_UNORM */ {}, + /* DATA_FORMAT_G8_B8_R8_3PLANE_420_UNORM */ {}, + /* DATA_FORMAT_G8_B8R8_2PLANE_420_UNORM */ {}, + /* DATA_FORMAT_G8_B8_R8_3PLANE_422_UNORM */ {}, + /* DATA_FORMAT_G8_B8R8_2PLANE_422_UNORM */ {}, + /* DATA_FORMAT_G8_B8_R8_3PLANE_444_UNORM */ {}, + /* DATA_FORMAT_R10X6_UNORM_PACK16 */ {}, + /* DATA_FORMAT_R10X6G10X6_UNORM_2PACK16 */ {}, + /* DATA_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16 */ {}, + /* DATA_FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16 */ {}, + /* DATA_FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16 */ {}, + /* DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_420_UNORM_3PACK16 */ {}, + /* DATA_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16 */ {}, + /* DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_422_UNORM_3PACK16 */ {}, + /* DATA_FORMAT_G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16 */ {}, + /* DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16 */ {}, + /* DATA_FORMAT_R12X4_UNORM_PACK16 */ {}, + /* DATA_FORMAT_R12X4G12X4_UNORM_2PACK16 */ {}, + /* DATA_FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16 */ {}, + /* DATA_FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16 */ {}, + /* DATA_FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16 */ {}, + /* DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_420_UNORM_3PACK16 */ {}, + /* DATA_FORMAT_G12X4_B12X4R12X4_2PLANE_420_UNORM_3PACK16 */ {}, + /* DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_422_UNORM_3PACK16 */ {}, + /* DATA_FORMAT_G12X4_B12X4R12X4_2PLANE_422_UNORM_3PACK16 */ {}, + /* DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_444_UNORM_3PACK16 */ {}, + /* DATA_FORMAT_G16B16G16R16_422_UNORM */ {}, + /* DATA_FORMAT_B16G16R16G16_422_UNORM */ {}, + /* DATA_FORMAT_G16_B16_R16_3PLANE_420_UNORM */ {}, + /* DATA_FORMAT_G16_B16R16_2PLANE_420_UNORM */ {}, + /* DATA_FORMAT_G16_B16_R16_3PLANE_422_UNORM */ {}, + /* DATA_FORMAT_G16_B16R16_2PLANE_422_UNORM */ {}, + /* DATA_FORMAT_G16_B16_R16_3PLANE_444_UNORM */ {}, +}; + +const char *RenderingDeviceD3D12::named_formats[RenderingDevice::DATA_FORMAT_MAX] = { + "R4G4_Unorm_Pack8", + "R4G4B4A4_Unorm_Pack16", + "B4G4R4A4_Unorm_Pack16", + "R5G6B5_Unorm_Pack16", + "B5G6R5_Unorm_Pack16", + "R5G5B5A1_Unorm_Pack16", + "B5G5R5A1_Unorm_Pack16", + "A1R5G5B5_Unorm_Pack16", + "R8_Unorm", + "R8_Snorm", + "R8_Uscaled", + "R8_Sscaled", + "R8_Uint", + "R8_Sint", + "R8_Srgb", + "R8G8_Unorm", + "R8G8_Snorm", + "R8G8_Uscaled", + "R8G8_Sscaled", + "R8G8_Uint", + "R8G8_Sint", + "R8G8_Srgb", + "R8G8B8_Unorm", + "R8G8B8_Snorm", + "R8G8B8_Uscaled", + "R8G8B8_Sscaled", + "R8G8B8_Uint", + "R8G8B8_Sint", + "R8G8B8_Srgb", + "B8G8R8_Unorm", + "B8G8R8_Snorm", + "B8G8R8_Uscaled", + "B8G8R8_Sscaled", + "B8G8R8_Uint", + "B8G8R8_Sint", + "B8G8R8_Srgb", + "R8G8B8A8_Unorm", + "R8G8B8A8_Snorm", + "R8G8B8A8_Uscaled", + "R8G8B8A8_Sscaled", + "R8G8B8A8_Uint", + "R8G8B8A8_Sint", + "R8G8B8A8_Srgb", + "B8G8R8A8_Unorm", + "B8G8R8A8_Snorm", + "B8G8R8A8_Uscaled", + "B8G8R8A8_Sscaled", + "B8G8R8A8_Uint", + "B8G8R8A8_Sint", + "B8G8R8A8_Srgb", + "A8B8G8R8_Unorm_Pack32", + "A8B8G8R8_Snorm_Pack32", + "A8B8G8R8_Uscaled_Pack32", + "A8B8G8R8_Sscaled_Pack32", + "A8B8G8R8_Uint_Pack32", + "A8B8G8R8_Sint_Pack32", + "A8B8G8R8_Srgb_Pack32", + "A2R10G10B10_Unorm_Pack32", + "A2R10G10B10_Snorm_Pack32", + "A2R10G10B10_Uscaled_Pack32", + "A2R10G10B10_Sscaled_Pack32", + "A2R10G10B10_Uint_Pack32", + "A2R10G10B10_Sint_Pack32", + "A2B10G10R10_Unorm_Pack32", + "A2B10G10R10_Snorm_Pack32", + "A2B10G10R10_Uscaled_Pack32", + "A2B10G10R10_Sscaled_Pack32", + "A2B10G10R10_Uint_Pack32", + "A2B10G10R10_Sint_Pack32", + "R16_Unorm", + "R16_Snorm", + "R16_Uscaled", + "R16_Sscaled", + "R16_Uint", + "R16_Sint", + "R16_Sfloat", + "R16G16_Unorm", + "R16G16_Snorm", + "R16G16_Uscaled", + "R16G16_Sscaled", + "R16G16_Uint", + "R16G16_Sint", + "R16G16_Sfloat", + "R16G16B16_Unorm", + "R16G16B16_Snorm", + "R16G16B16_Uscaled", + "R16G16B16_Sscaled", + "R16G16B16_Uint", + "R16G16B16_Sint", + "R16G16B16_Sfloat", + "R16G16B16A16_Unorm", + "R16G16B16A16_Snorm", + "R16G16B16A16_Uscaled", + "R16G16B16A16_Sscaled", + "R16G16B16A16_Uint", + "R16G16B16A16_Sint", + "R16G16B16A16_Sfloat", + "R32_Uint", + "R32_Sint", + "R32_Sfloat", + "R32G32_Uint", + "R32G32_Sint", + "R32G32_Sfloat", + "R32G32B32_Uint", + "R32G32B32_Sint", + "R32G32B32_Sfloat", + "R32G32B32A32_Uint", + "R32G32B32A32_Sint", + "R32G32B32A32_Sfloat", + "R64_Uint", + "R64_Sint", + "R64_Sfloat", + "R64G64_Uint", + "R64G64_Sint", + "R64G64_Sfloat", + "R64G64B64_Uint", + "R64G64B64_Sint", + "R64G64B64_Sfloat", + "R64G64B64A64_Uint", + "R64G64B64A64_Sint", + "R64G64B64A64_Sfloat", + "B10G11R11_Ufloat_Pack32", + "E5B9G9R9_Ufloat_Pack32", + "D16_Unorm", + "X8_D24_Unorm_Pack32", + "D32_Sfloat", + "S8_Uint", + "D16_Unorm_S8_Uint", + "D24_Unorm_S8_Uint", + "D32_Sfloat_S8_Uint", + "Bc1_Rgb_Unorm_Block", + "Bc1_Rgb_Srgb_Block", + "Bc1_Rgba_Unorm_Block", + "Bc1_Rgba_Srgb_Block", + "Bc2_Unorm_Block", + "Bc2_Srgb_Block", + "Bc3_Unorm_Block", + "Bc3_Srgb_Block", + "Bc4_Unorm_Block", + "Bc4_Snorm_Block", + "Bc5_Unorm_Block", + "Bc5_Snorm_Block", + "Bc6H_Ufloat_Block", + "Bc6H_Sfloat_Block", + "Bc7_Unorm_Block", + "Bc7_Srgb_Block", + "Etc2_R8G8B8_Unorm_Block", + "Etc2_R8G8B8_Srgb_Block", + "Etc2_R8G8B8A1_Unorm_Block", + "Etc2_R8G8B8A1_Srgb_Block", + "Etc2_R8G8B8A8_Unorm_Block", + "Etc2_R8G8B8A8_Srgb_Block", + "Eac_R11_Unorm_Block", + "Eac_R11_Snorm_Block", + "Eac_R11G11_Unorm_Block", + "Eac_R11G11_Snorm_Block", + "Astc_4X4_Unorm_Block", + "Astc_4X4_Srgb_Block", + "Astc_5X4_Unorm_Block", + "Astc_5X4_Srgb_Block", + "Astc_5X5_Unorm_Block", + "Astc_5X5_Srgb_Block", + "Astc_6X5_Unorm_Block", + "Astc_6X5_Srgb_Block", + "Astc_6X6_Unorm_Block", + "Astc_6X6_Srgb_Block", + "Astc_8X5_Unorm_Block", + "Astc_8X5_Srgb_Block", + "Astc_8X6_Unorm_Block", + "Astc_8X6_Srgb_Block", + "Astc_8X8_Unorm_Block", + "Astc_8X8_Srgb_Block", + "Astc_10X5_Unorm_Block", + "Astc_10X5_Srgb_Block", + "Astc_10X6_Unorm_Block", + "Astc_10X6_Srgb_Block", + "Astc_10X8_Unorm_Block", + "Astc_10X8_Srgb_Block", + "Astc_10X10_Unorm_Block", + "Astc_10X10_Srgb_Block", + "Astc_12X10_Unorm_Block", + "Astc_12X10_Srgb_Block", + "Astc_12X12_Unorm_Block", + "Astc_12X12_Srgb_Block", + "G8B8G8R8_422_Unorm", + "B8G8R8G8_422_Unorm", + "G8_B8_R8_3Plane_420_Unorm", + "G8_B8R8_2Plane_420_Unorm", + "G8_B8_R8_3Plane_422_Unorm", + "G8_B8R8_2Plane_422_Unorm", + "G8_B8_R8_3Plane_444_Unorm", + "R10X6_Unorm_Pack16", + "R10X6G10X6_Unorm_2Pack16", + "R10X6G10X6B10X6A10X6_Unorm_4Pack16", + "G10X6B10X6G10X6R10X6_422_Unorm_4Pack16", + "B10X6G10X6R10X6G10X6_422_Unorm_4Pack16", + "G10X6_B10X6_R10X6_3Plane_420_Unorm_3Pack16", + "G10X6_B10X6R10X6_2Plane_420_Unorm_3Pack16", + "G10X6_B10X6_R10X6_3Plane_422_Unorm_3Pack16", + "G10X6_B10X6R10X6_2Plane_422_Unorm_3Pack16", + "G10X6_B10X6_R10X6_3Plane_444_Unorm_3Pack16", + "R12X4_Unorm_Pack16", + "R12X4G12X4_Unorm_2Pack16", + "R12X4G12X4B12X4A12X4_Unorm_4Pack16", + "G12X4B12X4G12X4R12X4_422_Unorm_4Pack16", + "B12X4G12X4R12X4G12X4_422_Unorm_4Pack16", + "G12X4_B12X4_R12X4_3Plane_420_Unorm_3Pack16", + "G12X4_B12X4R12X4_2Plane_420_Unorm_3Pack16", + "G12X4_B12X4_R12X4_3Plane_422_Unorm_3Pack16", + "G12X4_B12X4R12X4_2Plane_422_Unorm_3Pack16", + "G12X4_B12X4_R12X4_3Plane_444_Unorm_3Pack16", + "G16B16G16R16_422_Unorm", + "B16G16R16G16_422_Unorm", + "G16_B16_R16_3Plane_420_Unorm", + "G16_B16R16_2Plane_420_Unorm", + "G16_B16_R16_3Plane_422_Unorm", + "G16_B16R16_2Plane_422_Unorm", + "G16_B16_R16_3Plane_444_Unorm", +}; + +int RenderingDeviceD3D12::get_format_vertex_size(DataFormat p_format) { + switch (p_format) { + case DATA_FORMAT_R8_UNORM: + case DATA_FORMAT_R8_SNORM: + case DATA_FORMAT_R8_UINT: + case DATA_FORMAT_R8_SINT: + case DATA_FORMAT_R8G8_UNORM: + case DATA_FORMAT_R8G8_SNORM: + case DATA_FORMAT_R8G8_UINT: + case DATA_FORMAT_R8G8_SINT: + case DATA_FORMAT_R8G8B8_UNORM: + case DATA_FORMAT_R8G8B8_SNORM: + case DATA_FORMAT_R8G8B8_UINT: + case DATA_FORMAT_R8G8B8_SINT: + case DATA_FORMAT_B8G8R8_UNORM: + case DATA_FORMAT_B8G8R8_SNORM: + case DATA_FORMAT_B8G8R8_UINT: + case DATA_FORMAT_B8G8R8_SINT: + case DATA_FORMAT_R8G8B8A8_UNORM: + case DATA_FORMAT_R8G8B8A8_SNORM: + case DATA_FORMAT_R8G8B8A8_UINT: + case DATA_FORMAT_R8G8B8A8_SINT: + case DATA_FORMAT_B8G8R8A8_UNORM: + case DATA_FORMAT_B8G8R8A8_SNORM: + case DATA_FORMAT_B8G8R8A8_UINT: + case DATA_FORMAT_B8G8R8A8_SINT: + case DATA_FORMAT_A2B10G10R10_UNORM_PACK32: + return 4; + case DATA_FORMAT_R16_UNORM: + case DATA_FORMAT_R16_SNORM: + case DATA_FORMAT_R16_UINT: + case DATA_FORMAT_R16_SINT: + case DATA_FORMAT_R16_SFLOAT: + return 4; + case DATA_FORMAT_R16G16_UNORM: + case DATA_FORMAT_R16G16_SNORM: + case DATA_FORMAT_R16G16_UINT: + case DATA_FORMAT_R16G16_SINT: + case DATA_FORMAT_R16G16_SFLOAT: + return 4; + case DATA_FORMAT_R16G16B16_UNORM: + case DATA_FORMAT_R16G16B16_SNORM: + case DATA_FORMAT_R16G16B16_UINT: + case DATA_FORMAT_R16G16B16_SINT: + case DATA_FORMAT_R16G16B16_SFLOAT: + return 8; + case DATA_FORMAT_R16G16B16A16_UNORM: + case DATA_FORMAT_R16G16B16A16_SNORM: + case DATA_FORMAT_R16G16B16A16_UINT: + case DATA_FORMAT_R16G16B16A16_SINT: + case DATA_FORMAT_R16G16B16A16_SFLOAT: + return 8; + case DATA_FORMAT_R32_UINT: + case DATA_FORMAT_R32_SINT: + case DATA_FORMAT_R32_SFLOAT: + return 4; + case DATA_FORMAT_R32G32_UINT: + case DATA_FORMAT_R32G32_SINT: + case DATA_FORMAT_R32G32_SFLOAT: + return 8; + case DATA_FORMAT_R32G32B32_UINT: + case DATA_FORMAT_R32G32B32_SINT: + case DATA_FORMAT_R32G32B32_SFLOAT: + return 12; + case DATA_FORMAT_R32G32B32A32_UINT: + case DATA_FORMAT_R32G32B32A32_SINT: + case DATA_FORMAT_R32G32B32A32_SFLOAT: + return 16; + case DATA_FORMAT_R64_UINT: + case DATA_FORMAT_R64_SINT: + case DATA_FORMAT_R64_SFLOAT: + return 8; + case DATA_FORMAT_R64G64_UINT: + case DATA_FORMAT_R64G64_SINT: + case DATA_FORMAT_R64G64_SFLOAT: + return 16; + case DATA_FORMAT_R64G64B64_UINT: + case DATA_FORMAT_R64G64B64_SINT: + case DATA_FORMAT_R64G64B64_SFLOAT: + return 24; + case DATA_FORMAT_R64G64B64A64_UINT: + case DATA_FORMAT_R64G64B64A64_SINT: + case DATA_FORMAT_R64G64B64A64_SFLOAT: + return 32; + default: + return 0; + } +} + +uint32_t RenderingDeviceD3D12::get_image_format_pixel_size(DataFormat p_format) { + switch (p_format) { + case DATA_FORMAT_R4G4_UNORM_PACK8: + return 1; + case DATA_FORMAT_R4G4B4A4_UNORM_PACK16: + case DATA_FORMAT_B4G4R4A4_UNORM_PACK16: + case DATA_FORMAT_R5G6B5_UNORM_PACK16: + case DATA_FORMAT_B5G6R5_UNORM_PACK16: + case DATA_FORMAT_R5G5B5A1_UNORM_PACK16: + case DATA_FORMAT_B5G5R5A1_UNORM_PACK16: + case DATA_FORMAT_A1R5G5B5_UNORM_PACK16: + return 2; + case DATA_FORMAT_R8_UNORM: + case DATA_FORMAT_R8_SNORM: + case DATA_FORMAT_R8_USCALED: + case DATA_FORMAT_R8_SSCALED: + case DATA_FORMAT_R8_UINT: + case DATA_FORMAT_R8_SINT: + case DATA_FORMAT_R8_SRGB: + return 1; + case DATA_FORMAT_R8G8_UNORM: + case DATA_FORMAT_R8G8_SNORM: + case DATA_FORMAT_R8G8_USCALED: + case DATA_FORMAT_R8G8_SSCALED: + case DATA_FORMAT_R8G8_UINT: + case DATA_FORMAT_R8G8_SINT: + case DATA_FORMAT_R8G8_SRGB: + return 2; + case DATA_FORMAT_R8G8B8_UNORM: + case DATA_FORMAT_R8G8B8_SNORM: + case DATA_FORMAT_R8G8B8_USCALED: + case DATA_FORMAT_R8G8B8_SSCALED: + case DATA_FORMAT_R8G8B8_UINT: + case DATA_FORMAT_R8G8B8_SINT: + case DATA_FORMAT_R8G8B8_SRGB: + case DATA_FORMAT_B8G8R8_UNORM: + case DATA_FORMAT_B8G8R8_SNORM: + case DATA_FORMAT_B8G8R8_USCALED: + case DATA_FORMAT_B8G8R8_SSCALED: + case DATA_FORMAT_B8G8R8_UINT: + case DATA_FORMAT_B8G8R8_SINT: + case DATA_FORMAT_B8G8R8_SRGB: + return 3; + case DATA_FORMAT_R8G8B8A8_UNORM: + case DATA_FORMAT_R8G8B8A8_SNORM: + case DATA_FORMAT_R8G8B8A8_USCALED: + case DATA_FORMAT_R8G8B8A8_SSCALED: + case DATA_FORMAT_R8G8B8A8_UINT: + case DATA_FORMAT_R8G8B8A8_SINT: + case DATA_FORMAT_R8G8B8A8_SRGB: + case DATA_FORMAT_B8G8R8A8_UNORM: + case DATA_FORMAT_B8G8R8A8_SNORM: + case DATA_FORMAT_B8G8R8A8_USCALED: + case DATA_FORMAT_B8G8R8A8_SSCALED: + case DATA_FORMAT_B8G8R8A8_UINT: + case DATA_FORMAT_B8G8R8A8_SINT: + case DATA_FORMAT_B8G8R8A8_SRGB: + return 4; + case DATA_FORMAT_A8B8G8R8_UNORM_PACK32: + case DATA_FORMAT_A8B8G8R8_SNORM_PACK32: + case DATA_FORMAT_A8B8G8R8_USCALED_PACK32: + case DATA_FORMAT_A8B8G8R8_SSCALED_PACK32: + case DATA_FORMAT_A8B8G8R8_UINT_PACK32: + case DATA_FORMAT_A8B8G8R8_SINT_PACK32: + case DATA_FORMAT_A8B8G8R8_SRGB_PACK32: + case DATA_FORMAT_A2R10G10B10_UNORM_PACK32: + case DATA_FORMAT_A2R10G10B10_SNORM_PACK32: + case DATA_FORMAT_A2R10G10B10_USCALED_PACK32: + case DATA_FORMAT_A2R10G10B10_SSCALED_PACK32: + case DATA_FORMAT_A2R10G10B10_UINT_PACK32: + case DATA_FORMAT_A2R10G10B10_SINT_PACK32: + case DATA_FORMAT_A2B10G10R10_UNORM_PACK32: + case DATA_FORMAT_A2B10G10R10_SNORM_PACK32: + case DATA_FORMAT_A2B10G10R10_USCALED_PACK32: + case DATA_FORMAT_A2B10G10R10_SSCALED_PACK32: + case DATA_FORMAT_A2B10G10R10_UINT_PACK32: + case DATA_FORMAT_A2B10G10R10_SINT_PACK32: + return 4; + case DATA_FORMAT_R16_UNORM: + case DATA_FORMAT_R16_SNORM: + case DATA_FORMAT_R16_USCALED: + case DATA_FORMAT_R16_SSCALED: + case DATA_FORMAT_R16_UINT: + case DATA_FORMAT_R16_SINT: + case DATA_FORMAT_R16_SFLOAT: + return 2; + case DATA_FORMAT_R16G16_UNORM: + case DATA_FORMAT_R16G16_SNORM: + case DATA_FORMAT_R16G16_USCALED: + case DATA_FORMAT_R16G16_SSCALED: + case DATA_FORMAT_R16G16_UINT: + case DATA_FORMAT_R16G16_SINT: + case DATA_FORMAT_R16G16_SFLOAT: + return 4; + case DATA_FORMAT_R16G16B16_UNORM: + case DATA_FORMAT_R16G16B16_SNORM: + case DATA_FORMAT_R16G16B16_USCALED: + case DATA_FORMAT_R16G16B16_SSCALED: + case DATA_FORMAT_R16G16B16_UINT: + case DATA_FORMAT_R16G16B16_SINT: + case DATA_FORMAT_R16G16B16_SFLOAT: + return 6; + case DATA_FORMAT_R16G16B16A16_UNORM: + case DATA_FORMAT_R16G16B16A16_SNORM: + case DATA_FORMAT_R16G16B16A16_USCALED: + case DATA_FORMAT_R16G16B16A16_SSCALED: + case DATA_FORMAT_R16G16B16A16_UINT: + case DATA_FORMAT_R16G16B16A16_SINT: + case DATA_FORMAT_R16G16B16A16_SFLOAT: + return 8; + case DATA_FORMAT_R32_UINT: + case DATA_FORMAT_R32_SINT: + case DATA_FORMAT_R32_SFLOAT: + return 4; + case DATA_FORMAT_R32G32_UINT: + case DATA_FORMAT_R32G32_SINT: + case DATA_FORMAT_R32G32_SFLOAT: + return 8; + case DATA_FORMAT_R32G32B32_UINT: + case DATA_FORMAT_R32G32B32_SINT: + case DATA_FORMAT_R32G32B32_SFLOAT: + return 12; + case DATA_FORMAT_R32G32B32A32_UINT: + case DATA_FORMAT_R32G32B32A32_SINT: + case DATA_FORMAT_R32G32B32A32_SFLOAT: + return 16; + case DATA_FORMAT_R64_UINT: + case DATA_FORMAT_R64_SINT: + case DATA_FORMAT_R64_SFLOAT: + return 8; + case DATA_FORMAT_R64G64_UINT: + case DATA_FORMAT_R64G64_SINT: + case DATA_FORMAT_R64G64_SFLOAT: + return 16; + case DATA_FORMAT_R64G64B64_UINT: + case DATA_FORMAT_R64G64B64_SINT: + case DATA_FORMAT_R64G64B64_SFLOAT: + return 24; + case DATA_FORMAT_R64G64B64A64_UINT: + case DATA_FORMAT_R64G64B64A64_SINT: + case DATA_FORMAT_R64G64B64A64_SFLOAT: + return 32; + case DATA_FORMAT_B10G11R11_UFLOAT_PACK32: + case DATA_FORMAT_E5B9G9R9_UFLOAT_PACK32: + return 4; + case DATA_FORMAT_D16_UNORM: + return 2; + case DATA_FORMAT_X8_D24_UNORM_PACK32: + return 4; + case DATA_FORMAT_D32_SFLOAT: + return 4; + case DATA_FORMAT_S8_UINT: + return 1; + case DATA_FORMAT_D16_UNORM_S8_UINT: + return 4; + case DATA_FORMAT_D24_UNORM_S8_UINT: + return 4; + case DATA_FORMAT_D32_SFLOAT_S8_UINT: + return 5; // ? + case DATA_FORMAT_BC1_RGB_UNORM_BLOCK: + case DATA_FORMAT_BC1_RGB_SRGB_BLOCK: + case DATA_FORMAT_BC1_RGBA_UNORM_BLOCK: + case DATA_FORMAT_BC1_RGBA_SRGB_BLOCK: + case DATA_FORMAT_BC2_UNORM_BLOCK: + case DATA_FORMAT_BC2_SRGB_BLOCK: + case DATA_FORMAT_BC3_UNORM_BLOCK: + case DATA_FORMAT_BC3_SRGB_BLOCK: + case DATA_FORMAT_BC4_UNORM_BLOCK: + case DATA_FORMAT_BC4_SNORM_BLOCK: + case DATA_FORMAT_BC5_UNORM_BLOCK: + case DATA_FORMAT_BC5_SNORM_BLOCK: + case DATA_FORMAT_BC6H_UFLOAT_BLOCK: + case DATA_FORMAT_BC6H_SFLOAT_BLOCK: + case DATA_FORMAT_BC7_UNORM_BLOCK: + case DATA_FORMAT_BC7_SRGB_BLOCK: + return 1; + case DATA_FORMAT_ETC2_R8G8B8_UNORM_BLOCK: + case DATA_FORMAT_ETC2_R8G8B8_SRGB_BLOCK: + case DATA_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK: + case DATA_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK: + case DATA_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK: + case DATA_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK: + return 1; + case DATA_FORMAT_EAC_R11_UNORM_BLOCK: + case DATA_FORMAT_EAC_R11_SNORM_BLOCK: + case DATA_FORMAT_EAC_R11G11_UNORM_BLOCK: + case DATA_FORMAT_EAC_R11G11_SNORM_BLOCK: + return 1; + case DATA_FORMAT_ASTC_4x4_UNORM_BLOCK: + case DATA_FORMAT_ASTC_4x4_SRGB_BLOCK: + case DATA_FORMAT_ASTC_5x4_UNORM_BLOCK: + case DATA_FORMAT_ASTC_5x4_SRGB_BLOCK: + case DATA_FORMAT_ASTC_5x5_UNORM_BLOCK: + case DATA_FORMAT_ASTC_5x5_SRGB_BLOCK: + case DATA_FORMAT_ASTC_6x5_UNORM_BLOCK: + case DATA_FORMAT_ASTC_6x5_SRGB_BLOCK: + case DATA_FORMAT_ASTC_6x6_UNORM_BLOCK: + case DATA_FORMAT_ASTC_6x6_SRGB_BLOCK: + case DATA_FORMAT_ASTC_8x5_UNORM_BLOCK: + case DATA_FORMAT_ASTC_8x5_SRGB_BLOCK: + case DATA_FORMAT_ASTC_8x6_UNORM_BLOCK: + case DATA_FORMAT_ASTC_8x6_SRGB_BLOCK: + case DATA_FORMAT_ASTC_8x8_UNORM_BLOCK: + case DATA_FORMAT_ASTC_8x8_SRGB_BLOCK: + case DATA_FORMAT_ASTC_10x5_UNORM_BLOCK: + case DATA_FORMAT_ASTC_10x5_SRGB_BLOCK: + case DATA_FORMAT_ASTC_10x6_UNORM_BLOCK: + case DATA_FORMAT_ASTC_10x6_SRGB_BLOCK: + case DATA_FORMAT_ASTC_10x8_UNORM_BLOCK: + case DATA_FORMAT_ASTC_10x8_SRGB_BLOCK: + case DATA_FORMAT_ASTC_10x10_UNORM_BLOCK: + case DATA_FORMAT_ASTC_10x10_SRGB_BLOCK: + case DATA_FORMAT_ASTC_12x10_UNORM_BLOCK: + case DATA_FORMAT_ASTC_12x10_SRGB_BLOCK: + case DATA_FORMAT_ASTC_12x12_UNORM_BLOCK: + case DATA_FORMAT_ASTC_12x12_SRGB_BLOCK: + return 1; + case DATA_FORMAT_G8B8G8R8_422_UNORM: + case DATA_FORMAT_B8G8R8G8_422_UNORM: + return 4; + case DATA_FORMAT_G8_B8_R8_3PLANE_420_UNORM: + case DATA_FORMAT_G8_B8R8_2PLANE_420_UNORM: + case DATA_FORMAT_G8_B8_R8_3PLANE_422_UNORM: + case DATA_FORMAT_G8_B8R8_2PLANE_422_UNORM: + case DATA_FORMAT_G8_B8_R8_3PLANE_444_UNORM: + return 4; + case DATA_FORMAT_R10X6_UNORM_PACK16: + case DATA_FORMAT_R10X6G10X6_UNORM_2PACK16: + case DATA_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16: + case DATA_FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16: + case DATA_FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16: + case DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_420_UNORM_3PACK16: + case DATA_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16: + case DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_422_UNORM_3PACK16: + case DATA_FORMAT_G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16: + case DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16: + case DATA_FORMAT_R12X4_UNORM_PACK16: + case DATA_FORMAT_R12X4G12X4_UNORM_2PACK16: + case DATA_FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16: + case DATA_FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16: + case DATA_FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16: + case DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_420_UNORM_3PACK16: + case DATA_FORMAT_G12X4_B12X4R12X4_2PLANE_420_UNORM_3PACK16: + case DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_422_UNORM_3PACK16: + case DATA_FORMAT_G12X4_B12X4R12X4_2PLANE_422_UNORM_3PACK16: + case DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_444_UNORM_3PACK16: + return 2; + case DATA_FORMAT_G16B16G16R16_422_UNORM: + case DATA_FORMAT_B16G16R16G16_422_UNORM: + case DATA_FORMAT_G16_B16_R16_3PLANE_420_UNORM: + case DATA_FORMAT_G16_B16R16_2PLANE_420_UNORM: + case DATA_FORMAT_G16_B16_R16_3PLANE_422_UNORM: + case DATA_FORMAT_G16_B16R16_2PLANE_422_UNORM: + case DATA_FORMAT_G16_B16_R16_3PLANE_444_UNORM: + return 8; + default: { + ERR_PRINT("Format not handled, bug"); + } + } + + return 1; +} + +// https://www.khronos.org/registry/DataFormat/specs/1.1/dataformat.1.1.pdf + +void RenderingDeviceD3D12::get_compressed_image_format_block_dimensions(DataFormat p_format, uint32_t &r_w, uint32_t &r_h) { + switch (p_format) { + case DATA_FORMAT_BC1_RGB_UNORM_BLOCK: + case DATA_FORMAT_BC1_RGB_SRGB_BLOCK: + case DATA_FORMAT_BC1_RGBA_UNORM_BLOCK: + case DATA_FORMAT_BC1_RGBA_SRGB_BLOCK: + case DATA_FORMAT_BC2_UNORM_BLOCK: + case DATA_FORMAT_BC2_SRGB_BLOCK: + case DATA_FORMAT_BC3_UNORM_BLOCK: + case DATA_FORMAT_BC3_SRGB_BLOCK: + case DATA_FORMAT_BC4_UNORM_BLOCK: + case DATA_FORMAT_BC4_SNORM_BLOCK: + case DATA_FORMAT_BC5_UNORM_BLOCK: + case DATA_FORMAT_BC5_SNORM_BLOCK: + case DATA_FORMAT_BC6H_UFLOAT_BLOCK: + case DATA_FORMAT_BC6H_SFLOAT_BLOCK: + case DATA_FORMAT_BC7_UNORM_BLOCK: + case DATA_FORMAT_BC7_SRGB_BLOCK: + case DATA_FORMAT_ETC2_R8G8B8_UNORM_BLOCK: + case DATA_FORMAT_ETC2_R8G8B8_SRGB_BLOCK: + case DATA_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK: + case DATA_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK: + case DATA_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK: + case DATA_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK: + case DATA_FORMAT_EAC_R11_UNORM_BLOCK: + case DATA_FORMAT_EAC_R11_SNORM_BLOCK: + case DATA_FORMAT_EAC_R11G11_UNORM_BLOCK: + case DATA_FORMAT_EAC_R11G11_SNORM_BLOCK: + case DATA_FORMAT_ASTC_4x4_UNORM_BLOCK: // Again, not sure about astc. + case DATA_FORMAT_ASTC_4x4_SRGB_BLOCK: + case DATA_FORMAT_ASTC_5x4_UNORM_BLOCK: + case DATA_FORMAT_ASTC_5x4_SRGB_BLOCK: + case DATA_FORMAT_ASTC_5x5_UNORM_BLOCK: + case DATA_FORMAT_ASTC_5x5_SRGB_BLOCK: + case DATA_FORMAT_ASTC_6x5_UNORM_BLOCK: + case DATA_FORMAT_ASTC_6x5_SRGB_BLOCK: + case DATA_FORMAT_ASTC_6x6_UNORM_BLOCK: + case DATA_FORMAT_ASTC_6x6_SRGB_BLOCK: + case DATA_FORMAT_ASTC_8x5_UNORM_BLOCK: + case DATA_FORMAT_ASTC_8x5_SRGB_BLOCK: + case DATA_FORMAT_ASTC_8x6_UNORM_BLOCK: + case DATA_FORMAT_ASTC_8x6_SRGB_BLOCK: + case DATA_FORMAT_ASTC_8x8_UNORM_BLOCK: + case DATA_FORMAT_ASTC_8x8_SRGB_BLOCK: + case DATA_FORMAT_ASTC_10x5_UNORM_BLOCK: + case DATA_FORMAT_ASTC_10x5_SRGB_BLOCK: + case DATA_FORMAT_ASTC_10x6_UNORM_BLOCK: + case DATA_FORMAT_ASTC_10x6_SRGB_BLOCK: + case DATA_FORMAT_ASTC_10x8_UNORM_BLOCK: + case DATA_FORMAT_ASTC_10x8_SRGB_BLOCK: + case DATA_FORMAT_ASTC_10x10_UNORM_BLOCK: + case DATA_FORMAT_ASTC_10x10_SRGB_BLOCK: + case DATA_FORMAT_ASTC_12x10_UNORM_BLOCK: + case DATA_FORMAT_ASTC_12x10_SRGB_BLOCK: + case DATA_FORMAT_ASTC_12x12_UNORM_BLOCK: + case DATA_FORMAT_ASTC_12x12_SRGB_BLOCK: + r_w = 4; + r_h = 4; + return; + default: { + r_w = 1; + r_h = 1; + } + } +} + +uint32_t RenderingDeviceD3D12::get_compressed_image_format_block_byte_size(DataFormat p_format) { + switch (p_format) { + case DATA_FORMAT_BC1_RGB_UNORM_BLOCK: + case DATA_FORMAT_BC1_RGB_SRGB_BLOCK: + case DATA_FORMAT_BC1_RGBA_UNORM_BLOCK: + case DATA_FORMAT_BC1_RGBA_SRGB_BLOCK: + return 8; + case DATA_FORMAT_BC2_UNORM_BLOCK: + case DATA_FORMAT_BC2_SRGB_BLOCK: + return 16; + case DATA_FORMAT_BC3_UNORM_BLOCK: + case DATA_FORMAT_BC3_SRGB_BLOCK: + return 16; + case DATA_FORMAT_BC4_UNORM_BLOCK: + case DATA_FORMAT_BC4_SNORM_BLOCK: + return 8; + case DATA_FORMAT_BC5_UNORM_BLOCK: + case DATA_FORMAT_BC5_SNORM_BLOCK: + return 16; + case DATA_FORMAT_BC6H_UFLOAT_BLOCK: + case DATA_FORMAT_BC6H_SFLOAT_BLOCK: + return 16; + case DATA_FORMAT_BC7_UNORM_BLOCK: + case DATA_FORMAT_BC7_SRGB_BLOCK: + return 16; + case DATA_FORMAT_ETC2_R8G8B8_UNORM_BLOCK: + case DATA_FORMAT_ETC2_R8G8B8_SRGB_BLOCK: + return 8; + case DATA_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK: + case DATA_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK: + return 8; + case DATA_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK: + case DATA_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK: + return 16; + case DATA_FORMAT_EAC_R11_UNORM_BLOCK: + case DATA_FORMAT_EAC_R11_SNORM_BLOCK: + return 8; + case DATA_FORMAT_EAC_R11G11_UNORM_BLOCK: + case DATA_FORMAT_EAC_R11G11_SNORM_BLOCK: + return 16; + case DATA_FORMAT_ASTC_4x4_UNORM_BLOCK: // Again, not sure about astc. + case DATA_FORMAT_ASTC_4x4_SRGB_BLOCK: + case DATA_FORMAT_ASTC_5x4_UNORM_BLOCK: + case DATA_FORMAT_ASTC_5x4_SRGB_BLOCK: + case DATA_FORMAT_ASTC_5x5_UNORM_BLOCK: + case DATA_FORMAT_ASTC_5x5_SRGB_BLOCK: + case DATA_FORMAT_ASTC_6x5_UNORM_BLOCK: + case DATA_FORMAT_ASTC_6x5_SRGB_BLOCK: + case DATA_FORMAT_ASTC_6x6_UNORM_BLOCK: + case DATA_FORMAT_ASTC_6x6_SRGB_BLOCK: + case DATA_FORMAT_ASTC_8x5_UNORM_BLOCK: + case DATA_FORMAT_ASTC_8x5_SRGB_BLOCK: + case DATA_FORMAT_ASTC_8x6_UNORM_BLOCK: + case DATA_FORMAT_ASTC_8x6_SRGB_BLOCK: + case DATA_FORMAT_ASTC_8x8_UNORM_BLOCK: + case DATA_FORMAT_ASTC_8x8_SRGB_BLOCK: + case DATA_FORMAT_ASTC_10x5_UNORM_BLOCK: + case DATA_FORMAT_ASTC_10x5_SRGB_BLOCK: + case DATA_FORMAT_ASTC_10x6_UNORM_BLOCK: + case DATA_FORMAT_ASTC_10x6_SRGB_BLOCK: + case DATA_FORMAT_ASTC_10x8_UNORM_BLOCK: + case DATA_FORMAT_ASTC_10x8_SRGB_BLOCK: + case DATA_FORMAT_ASTC_10x10_UNORM_BLOCK: + case DATA_FORMAT_ASTC_10x10_SRGB_BLOCK: + case DATA_FORMAT_ASTC_12x10_UNORM_BLOCK: + case DATA_FORMAT_ASTC_12x10_SRGB_BLOCK: + case DATA_FORMAT_ASTC_12x12_UNORM_BLOCK: + case DATA_FORMAT_ASTC_12x12_SRGB_BLOCK: + return 8; // Wrong. + default: { + } + } + return 1; +} + +uint32_t RenderingDeviceD3D12::get_compressed_image_format_pixel_rshift(DataFormat p_format) { + switch (p_format) { + case DATA_FORMAT_BC1_RGB_UNORM_BLOCK: // These formats are half byte size, so rshift is 1. + case DATA_FORMAT_BC1_RGB_SRGB_BLOCK: + case DATA_FORMAT_BC1_RGBA_UNORM_BLOCK: + case DATA_FORMAT_BC1_RGBA_SRGB_BLOCK: + case DATA_FORMAT_BC4_UNORM_BLOCK: + case DATA_FORMAT_BC4_SNORM_BLOCK: + case DATA_FORMAT_ETC2_R8G8B8_UNORM_BLOCK: + case DATA_FORMAT_ETC2_R8G8B8_SRGB_BLOCK: + case DATA_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK: + case DATA_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK: + case DATA_FORMAT_EAC_R11_UNORM_BLOCK: + case DATA_FORMAT_EAC_R11_SNORM_BLOCK: + return 1; + default: { + } + } + + return 0; +} + +uint32_t RenderingDeviceD3D12::get_image_format_plane_count(DataFormat p_format) { + uint32_t planes = 1; + switch (p_format) { + case DATA_FORMAT_D16_UNORM_S8_UINT: + case DATA_FORMAT_D24_UNORM_S8_UINT: + case DATA_FORMAT_D32_SFLOAT_S8_UINT: { + planes = 2; + } + default: { + } + } + DEV_ASSERT(planes <= MAX_IMAGE_FORMAT_PLANES); + return planes; +} + +uint32_t RenderingDeviceD3D12::get_image_format_required_size(DataFormat p_format, uint32_t p_width, uint32_t p_height, uint32_t p_depth, uint32_t p_mipmaps, uint32_t *r_blockw, uint32_t *r_blockh, uint32_t *r_depth) { + ERR_FAIL_COND_V(p_mipmaps == 0, 0); + uint32_t w = p_width; + uint32_t h = p_height; + uint32_t d = p_depth; + + uint32_t size = 0; + + uint32_t pixel_size = get_image_format_pixel_size(p_format); + uint32_t pixel_rshift = get_compressed_image_format_pixel_rshift(p_format); + uint32_t blockw, blockh; + get_compressed_image_format_block_dimensions(p_format, blockw, blockh); + + for (uint32_t i = 0; i < p_mipmaps; i++) { + uint32_t bw = w % blockw != 0 ? w + (blockw - w % blockw) : w; + uint32_t bh = h % blockh != 0 ? h + (blockh - h % blockh) : h; + + uint32_t s = bw * bh; + + s *= pixel_size; + s >>= pixel_rshift; + size += s * d; + if (r_blockw) { + *r_blockw = bw; + } + if (r_blockh) { + *r_blockh = bh; + } + if (r_depth) { + *r_depth = d; + } + w = MAX(blockw, w >> 1); + h = MAX(blockh, h >> 1); + d = MAX(1u, d >> 1); + } + + return size; +} + +uint32_t RenderingDeviceD3D12::get_image_required_mipmaps(uint32_t p_width, uint32_t p_height, uint32_t p_depth) { + // Formats and block size don't really matter here since they can all go down to 1px (even if block is larger). + uint32_t w = p_width; + uint32_t h = p_height; + uint32_t d = p_depth; + + uint32_t mipmaps = 1; + + while (true) { + if (w == 1 && h == 1 && d == 1) { + break; + } + + w = MAX(1u, w >> 1); + h = MAX(1u, h >> 1); + d = MAX(1u, d >> 1); + + mipmaps++; + } + + return mipmaps; +} + +/////////////////////// + +const D3D12_COMPARISON_FUNC RenderingDeviceD3D12::compare_operators[RenderingDevice::COMPARE_OP_MAX] = { + D3D12_COMPARISON_FUNC_NEVER, + D3D12_COMPARISON_FUNC_LESS, + D3D12_COMPARISON_FUNC_EQUAL, + D3D12_COMPARISON_FUNC_LESS_EQUAL, + D3D12_COMPARISON_FUNC_GREATER, + D3D12_COMPARISON_FUNC_NOT_EQUAL, + D3D12_COMPARISON_FUNC_GREATER_EQUAL, + D3D12_COMPARISON_FUNC_ALWAYS, +}; + +const D3D12_STENCIL_OP RenderingDeviceD3D12::stencil_operations[RenderingDevice::STENCIL_OP_MAX] = { + D3D12_STENCIL_OP_KEEP, + D3D12_STENCIL_OP_ZERO, + D3D12_STENCIL_OP_REPLACE, + D3D12_STENCIL_OP_INCR_SAT, + D3D12_STENCIL_OP_DECR_SAT, + D3D12_STENCIL_OP_INVERT, + D3D12_STENCIL_OP_INCR, + D3D12_STENCIL_OP_DECR, +}; + +const UINT RenderingDeviceD3D12::rasterization_sample_count[RenderingDevice::TEXTURE_SAMPLES_MAX] = { + 1, + 2, + 4, + 8, + 16, + 32, + 64, +}; + +const D3D12_LOGIC_OP RenderingDeviceD3D12::logic_operations[RenderingDevice::LOGIC_OP_MAX] = { + D3D12_LOGIC_OP_CLEAR, + D3D12_LOGIC_OP_AND, + D3D12_LOGIC_OP_AND_REVERSE, + D3D12_LOGIC_OP_COPY, + D3D12_LOGIC_OP_AND_INVERTED, + D3D12_LOGIC_OP_NOOP, + D3D12_LOGIC_OP_XOR, + D3D12_LOGIC_OP_OR, + D3D12_LOGIC_OP_NOR, + D3D12_LOGIC_OP_EQUIV, + D3D12_LOGIC_OP_INVERT, + D3D12_LOGIC_OP_OR_REVERSE, + D3D12_LOGIC_OP_COPY_INVERTED, + D3D12_LOGIC_OP_OR_INVERTED, + D3D12_LOGIC_OP_NAND, + D3D12_LOGIC_OP_SET, +}; + +const D3D12_BLEND RenderingDeviceD3D12::blend_factors[RenderingDevice::BLEND_FACTOR_MAX] = { + D3D12_BLEND_ZERO, + D3D12_BLEND_ONE, + D3D12_BLEND_SRC_COLOR, + D3D12_BLEND_INV_SRC_COLOR, + D3D12_BLEND_DEST_COLOR, + D3D12_BLEND_INV_DEST_COLOR, + D3D12_BLEND_SRC_ALPHA, + D3D12_BLEND_INV_SRC_ALPHA, + D3D12_BLEND_DEST_ALPHA, + D3D12_BLEND_INV_DEST_ALPHA, + D3D12_BLEND_BLEND_FACTOR, + D3D12_BLEND_INV_BLEND_FACTOR, + D3D12_BLEND_BLEND_FACTOR, + D3D12_BLEND_INV_BLEND_FACTOR, + D3D12_BLEND_SRC_ALPHA_SAT, + D3D12_BLEND_SRC1_COLOR, + D3D12_BLEND_INV_SRC1_COLOR, + D3D12_BLEND_SRC1_ALPHA, + D3D12_BLEND_INV_SRC1_ALPHA, +}; + +const D3D12_BLEND_OP RenderingDeviceD3D12::blend_operations[RenderingDevice::BLEND_OP_MAX] = { + D3D12_BLEND_OP_ADD, + D3D12_BLEND_OP_SUBTRACT, + D3D12_BLEND_OP_REV_SUBTRACT, + D3D12_BLEND_OP_MIN, + D3D12_BLEND_OP_MAX, +}; + +const D3D12_TEXTURE_ADDRESS_MODE RenderingDeviceD3D12::address_modes[RenderingDevice::SAMPLER_REPEAT_MODE_MAX] = { + D3D12_TEXTURE_ADDRESS_MODE_WRAP, + D3D12_TEXTURE_ADDRESS_MODE_MIRROR, + D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + D3D12_TEXTURE_ADDRESS_MODE_BORDER, + D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE, +}; + +const FLOAT RenderingDeviceD3D12::sampler_border_colors[RenderingDevice::SAMPLER_BORDER_COLOR_MAX][4] = { + { 0, 0, 0, 0 }, + { 0, 0, 0, 0 }, + { 0, 0, 0, 1 }, + { 0, 0, 0, 1 }, + { 1, 1, 1, 1 }, + { 1, 1, 1, 1 }, +}; + +const D3D12_RESOURCE_DIMENSION RenderingDeviceD3D12::d3d12_texture_dimension[RenderingDevice::TEXTURE_TYPE_MAX] = { + D3D12_RESOURCE_DIMENSION_TEXTURE1D, + D3D12_RESOURCE_DIMENSION_TEXTURE2D, + D3D12_RESOURCE_DIMENSION_TEXTURE3D, + D3D12_RESOURCE_DIMENSION_TEXTURE2D, + D3D12_RESOURCE_DIMENSION_TEXTURE1D, + D3D12_RESOURCE_DIMENSION_TEXTURE2D, + D3D12_RESOURCE_DIMENSION_TEXTURE2D, +}; + +/******************/ +/**** RESOURCE ****/ +/******************/ + +static const D3D12_RESOURCE_STATES RESOURCE_READ_STATES = + D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER | + D3D12_RESOURCE_STATE_INDEX_BUFFER | + D3D12_RESOURCE_STATE_DEPTH_READ | + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE | + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT | + D3D12_RESOURCE_STATE_COPY_SOURCE | + D3D12_RESOURCE_STATE_RESOLVE_SOURCE | + D3D12_RESOURCE_STATE_SHADING_RATE_SOURCE; + +static const D3D12_RESOURCE_STATES RESOURCE_WRITE_STATES = + D3D12_RESOURCE_STATE_RENDER_TARGET | + D3D12_RESOURCE_STATE_DEPTH_WRITE | + D3D12_RESOURCE_STATE_COPY_DEST | + D3D12_RESOURCE_STATE_RESOLVE_DEST; + +static const D3D12_RESOURCE_STATES RESOURCE_RW_STATES = + D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + +void RenderingDeviceD3D12::ResourceState::extend(D3D12_RESOURCE_STATES p_states_to_add) { + states |= p_states_to_add; + +#ifdef DEV_ENABLED + if ((states & RESOURCE_RW_STATES)) { + if ((states & RESOURCE_READ_STATES)) { + // Thanks to [[SRV_UAV_AMBIGUITY]], this is not necessarily an error. + } + if ((states & RESOURCE_WRITE_STATES)) { + ERR_PRINT("Error in new state mask: has R/W state plus some W/O state(s)."); + } + } else { + if ((states & RESOURCE_WRITE_STATES)) { + if ((states & RESOURCE_READ_STATES)) { + ERR_PRINT("Error in new state mask: mixes R/O and W/O states."); + } else { + uint32_t num_w_states = 0; + for (uint32_t i = 0; i < sizeof(D3D12_RESOURCE_STATES) * 8; i++) { + num_w_states += ((states & RESOURCE_WRITE_STATES) & (1 << i)) ? 1 : 0; + } + ERR_PRINT("Error in new state mask: has multiple W/O states."); + } + } + } +#endif +} + +void RenderingDeviceD3D12::_resource_transition_batch(Resource *p_resource, uint32_t p_subresource, uint32_t p_num_planes, D3D12_RESOURCE_STATES p_new_state, ID3D12Resource *p_resource_override) { + DEV_ASSERT(p_subresource != UINT32_MAX); // We don't support an "all-resources" command here. + DEV_ASSERT(p_new_state != D3D12_RESOURCE_STATE_COMMON); // No need to support this for now. + +#ifdef DEBUG_COUNT_BARRIERS + uint64_t start = OS::get_singleton()->get_ticks_usec(); +#endif + + Resource::States *res_states = p_resource->get_states_ptr(); + D3D12_RESOURCE_STATES *curr_state = &res_states->subresource_states[p_subresource]; + + ID3D12Resource *res_to_transition = p_resource_override ? p_resource_override : p_resource->resource; + + bool redundant_transition = ((*curr_state) & p_new_state) == p_new_state; + if (redundant_transition) { + bool just_written = *curr_state == D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + bool needs_uav_barrier = just_written && res_states->last_batch_with_uav_barrier != res_barriers_batch; + if (needs_uav_barrier) { + if (res_barriers.size() < res_barriers_count + 1) { + res_barriers.resize(res_barriers_count + 1); + } + res_barriers[res_barriers_count] = CD3DX12_RESOURCE_BARRIER::UAV(res_to_transition); + res_barriers_count++; + res_states->last_batch_with_uav_barrier = res_barriers_batch; + } + } else { + uint64_t subres_mask_piece = ((uint64_t)1 << (p_subresource & 0b111111)); + uint8_t subres_qword = p_subresource >> 6; + + if (res_barriers_requests.has(res_states)) { + BarrierRequest &br = res_barriers_requests.get(res_states); + DEV_ASSERT(br.dx_resource == res_to_transition); + DEV_ASSERT(br.subres_mask_qwords == ALIGN(res_states->subresource_states.size(), 64) / 64); + DEV_ASSERT(br.planes == p_num_planes); + + // First, find if the subresource already has a barrier scheduled. + uint8_t curr_group_idx = 0; + bool same_transition_scheduled = false; + for (curr_group_idx = 0; curr_group_idx < br.groups_count; curr_group_idx++) { + if (unlikely(br.groups[curr_group_idx].state.get_state_mask() == BarrierRequest::DELETED_GROUP)) { + continue; + } + if ((br.groups[curr_group_idx].subres_mask[subres_qword] & subres_mask_piece)) { + uint32_t state_mask = br.groups[curr_group_idx].state.get_state_mask(); + same_transition_scheduled = (state_mask & (uint32_t)p_new_state) == (uint32_t)p_new_state; + break; + } + } + if (!same_transition_scheduled) { + bool subres_already_there = curr_group_idx != br.groups_count; + ResourceState final_state; + if (subres_already_there) { + final_state = br.groups[curr_group_idx].state; + final_state.extend(p_new_state); + bool subres_alone = true; + for (uint8_t i = 0; i < br.subres_mask_qwords; i++) { + if (i == subres_qword) { + if (br.groups[curr_group_idx].subres_mask[i] != subres_mask_piece) { + subres_alone = false; + break; + } + } else { + if (br.groups[curr_group_idx].subres_mask[i] != 0) { + subres_alone = false; + break; + } + } + } + bool relocated = false; + if (subres_alone) { + // Subresource is there by itself. + for (uint8_t i = 0; i < br.groups_count; i++) { + if (unlikely(i == curr_group_idx)) { + continue; + } + if (unlikely(br.groups[i].state.get_state_mask() == BarrierRequest::DELETED_GROUP)) { + continue; + } + // There's another group with the final state; relocate to it. + if (br.groups[i].state.get_state_mask() == final_state.get_state_mask()) { + br.groups[curr_group_idx].subres_mask[subres_qword] &= ~subres_mask_piece; + relocated = true; + break; + } + } + if (relocated) { + // Let's delete the group where it used to be by itself. + if (curr_group_idx == br.groups_count - 1) { + br.groups_count--; + } else { + br.groups[curr_group_idx].state = ResourceState(BarrierRequest::DELETED_GROUP); + } + } else { + // Its current group, where it's alone, can extend its state. + br.groups[curr_group_idx].state = final_state; + } + } else { + // Already there, but not by itself and the state mask is different, so it now belongs to a different group. + br.groups[curr_group_idx].subres_mask[subres_qword] &= ~subres_mask_piece; + subres_already_there = false; + } + } else { + final_state = p_new_state; + } + if (!subres_already_there) { + // See if it fits exactly the state of some of the groups to fit it there. + for (uint8_t i = 0; i < br.groups_count; i++) { + if (unlikely(i == curr_group_idx)) { + continue; + } + if (unlikely(br.groups[i].state.get_state_mask() == BarrierRequest::DELETED_GROUP)) { + continue; + } + if (br.groups[i].state.get_state_mask() == final_state.get_state_mask()) { + br.groups[i].subres_mask[subres_qword] |= subres_mask_piece; + subres_already_there = true; + break; + } + } + if (!subres_already_there) { + // Add a new group to accommodate this subresource. + uint8_t group_to_fill = 0; + if (br.groups_count < BarrierRequest::MAX_GROUPS) { + // There are still free groups. + group_to_fill = br.groups_count; + br.groups_count++; + } else { + // Let's try to take over a deleted one. + for (; group_to_fill < br.groups_count; group_to_fill++) { + if (unlikely(br.groups[group_to_fill].state.get_state_mask() == BarrierRequest::DELETED_GROUP)) { + break; + } + } + CRASH_COND(group_to_fill == br.groups_count); + } + + br.groups[group_to_fill].state = final_state; + for (uint8_t i = 0; i < br.subres_mask_qwords; i++) { + if (unlikely(i == subres_qword)) { + br.groups[group_to_fill].subres_mask[i] = subres_mask_piece; + } else { + br.groups[group_to_fill].subres_mask[i] = 0; + } + } + } + } + } + } else { + BarrierRequest &br = res_barriers_requests[res_states]; + br.dx_resource = res_to_transition; + br.subres_mask_qwords = ALIGN(p_resource->get_states_ptr()->subresource_states.size(), 64) / 64; + CRASH_COND(p_resource->get_states_ptr()->subresource_states.size() > BarrierRequest::MAX_SUBRESOURCES); + br.planes = p_num_planes; + br.groups[0].state = p_new_state; + for (uint8_t i = 0; i < br.subres_mask_qwords; i++) { + if (unlikely(i == subres_qword)) { + br.groups[0].subres_mask[i] = subres_mask_piece; + } else { + br.groups[0].subres_mask[i] = 0; + } + } + br.groups_count = 1; + } + } + + if (p_new_state == D3D12_RESOURCE_STATE_UNORDERED_ACCESS) { + res_states->last_batch_transitioned_to_uav = res_barriers_batch; + } + +#ifdef DEBUG_COUNT_BARRIERS + frame_barriers_cpu_time += OS::get_singleton()->get_ticks_usec() - start; +#endif +} + +void RenderingDeviceD3D12::_resource_transitions_flush(ID3D12GraphicsCommandList *p_command_list) { +#ifdef DEBUG_COUNT_BARRIERS + uint64_t start = OS::get_singleton()->get_ticks_usec(); +#endif + + for (const KeyValue<Resource::States *, BarrierRequest> &E : res_barriers_requests) { + Resource::States *res_states = E.key; + const BarrierRequest &br = E.value; + + uint32_t num_subresources = res_states->subresource_states.size(); + + // When there's not a lot of subresources, the empirical finding is that it's better + // to avoid attempting the single-barrier optimization. + static const uint32_t SINGLE_BARRIER_ATTEMPT_MAX_NUM_SUBRESOURCES = 48; + + bool may_do_single_barrier = br.groups_count == 1 && num_subresources * br.planes >= SINGLE_BARRIER_ATTEMPT_MAX_NUM_SUBRESOURCES; + if (may_do_single_barrier) { + // A single group means we may be able to do a single all-subresources barrier. + + { + // First requisite is that all subresources are involved. + + uint8_t subres_mask_full_qwords = num_subresources / 64; + for (uint32_t i = 0; i < subres_mask_full_qwords; i++) { + if (br.groups[0].subres_mask[i] != UINT64_MAX) { + may_do_single_barrier = false; + break; + } + } + if (may_do_single_barrier) { + if (num_subresources % 64) { + DEV_ASSERT(br.subres_mask_qwords == subres_mask_full_qwords + 1); + uint64_t mask_tail_qword = 0; + for (uint8_t i = 0; i < num_subresources % 64; i++) { + mask_tail_qword |= ((uint64_t)1 << i); + } + if ((br.groups[0].subres_mask[subres_mask_full_qwords] & mask_tail_qword) != mask_tail_qword) { + may_do_single_barrier = false; + } + } + } + } + + if (may_do_single_barrier) { + // Second requisite is that the source state is the same for all. + + for (uint32_t i = 1; i < num_subresources; i++) { + if (res_states->subresource_states[i] != res_states->subresource_states[0]) { + may_do_single_barrier = false; + break; + } + } + + if (may_do_single_barrier) { + // Hurray!, we can do a single barrier (plus maybe a UAV one, too). + + bool just_written = res_states->subresource_states[0] == D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + bool needs_uav_barrier = just_written && res_states->last_batch_with_uav_barrier != res_barriers_batch; + + uint32_t needed_barriers = (needs_uav_barrier ? 1 : 0) + 1; + if (res_barriers.size() < res_barriers_count + needed_barriers) { + res_barriers.resize(res_barriers_count + needed_barriers); + } + + if (needs_uav_barrier) { + res_barriers[res_barriers_count] = CD3DX12_RESOURCE_BARRIER::UAV(br.dx_resource); + res_barriers_count++; + res_states->last_batch_with_uav_barrier = res_barriers_batch; + } + + if (res_states->subresource_states[0] != br.groups[0].state.get_state_mask()) { + res_barriers[res_barriers_count] = CD3DX12_RESOURCE_BARRIER::Transition(br.dx_resource, res_states->subresource_states[0], br.groups[0].state.get_state_mask(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES); + res_barriers_count++; + } + + for (uint32_t i = 0; i < num_subresources; i++) { + res_states->subresource_states[i] = br.groups[0].state.get_state_mask(); + } + } + } + } + + if (!may_do_single_barrier) { + for (uint8_t i = 0; i < br.groups_count; i++) { + const BarrierRequest::Group &g = E.value.groups[i]; + + if (unlikely(g.state.get_state_mask() == BarrierRequest::DELETED_GROUP)) { + continue; + } + + uint32_t subresource = 0; + do { + uint64_t subres_mask_piece = ((uint64_t)1 << (subresource % 64)); + uint8_t subres_qword = subresource / 64; + + if (likely(g.subres_mask[subres_qword] == 0)) { + subresource += 64; + continue; + } + + if (likely(!(g.subres_mask[subres_qword] & subres_mask_piece))) { + subresource++; + continue; + } + + D3D12_RESOURCE_STATES *curr_state = &res_states->subresource_states[subresource]; + + bool just_written = *curr_state == D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + bool needs_uav_barrier = just_written && res_states->last_batch_with_uav_barrier != res_barriers_batch; + + uint32_t needed_barriers = (needs_uav_barrier ? 1 : 0) + br.planes; + if (res_barriers.size() < res_barriers_count + needed_barriers) { + res_barriers.resize(res_barriers_count + needed_barriers); + } + + if (needs_uav_barrier) { + res_barriers[res_barriers_count] = CD3DX12_RESOURCE_BARRIER::UAV(br.dx_resource); + res_barriers_count++; + res_states->last_batch_with_uav_barrier = res_barriers_batch; + } + + if (*curr_state != g.state.get_state_mask()) { + for (uint8_t k = 0; k < br.planes; k++) { + res_barriers[res_barriers_count] = CD3DX12_RESOURCE_BARRIER::Transition(br.dx_resource, *curr_state, g.state.get_state_mask(), subresource + k * num_subresources); + res_barriers_count++; + } + } + + *curr_state = g.state.get_state_mask(); + + subresource++; + } while (subresource < num_subresources); + } + } + } + + if (res_barriers_count) { + p_command_list->ResourceBarrier(res_barriers_count, res_barriers.ptr()); + res_barriers_requests.clear(); + } + +#ifdef DEBUG_COUNT_BARRIERS + frame_barriers_count += res_barriers_count; + frame_barriers_batches_count++; + frame_barriers_cpu_time += OS::get_singleton()->get_ticks_usec() - start; +#endif + + res_barriers_count = 0; + res_barriers_batch++; +} + +/***************************/ +/**** BUFFER MANAGEMENT ****/ +/***************************/ + +Error RenderingDeviceD3D12::_buffer_allocate(Buffer *p_buffer, uint32_t p_size, D3D12_RESOURCE_STATES p_usage, D3D12_HEAP_TYPE p_heap_type) { + ERR_FAIL_COND_V(p_heap_type != D3D12_HEAP_TYPE_DEFAULT && p_heap_type != D3D12_HEAP_TYPE_READBACK, ERR_INVALID_PARAMETER); + + // D3D12 debug layers complain at CBV creation time if the size is not multiple of the value per the spec + // but also if you give a rounded size at that point because it will extend beyond the + // memory of the resource. Therefore, it seems the only way is to create it with a + // rounded size. + CD3DX12_RESOURCE_DESC resource_desc = CD3DX12_RESOURCE_DESC::Buffer(ALIGN(p_size, D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT)); + if ((p_usage & D3D12_RESOURCE_STATE_UNORDERED_ACCESS)) { + resource_desc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + } + + D3D12MA::ALLOCATION_DESC allocation_desc = {}; + allocation_desc.HeapType = p_heap_type; +#ifdef USE_SMALL_ALLOCS_POOL + if (p_size <= SMALL_ALLOCATION_MAX_SIZE) { + allocation_desc.CustomPool = _find_or_create_small_allocs_pool(p_heap_type, D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS); + } +#endif + + HRESULT res = context->get_allocator()->CreateResource( + &allocation_desc, + &resource_desc, + D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, + &p_buffer->allocation, + IID_PPV_ARGS(&p_buffer->resource)); + ERR_FAIL_COND_V_MSG(res, ERR_CANT_CREATE, "Can't create buffer of size: " + itos(p_size) + ", error " + vformat("0x%08ux", res) + "."); + + p_buffer->size = p_size; + p_buffer->usage = p_usage; + p_buffer->own_states.subresource_states.push_back(D3D12_RESOURCE_STATE_COPY_DEST); + + buffer_memory += p_size; + + return OK; +} + +Error RenderingDeviceD3D12::_buffer_free(Buffer *p_buffer) { + ERR_FAIL_COND_V(p_buffer->size == 0, ERR_INVALID_PARAMETER); + + buffer_memory -= p_buffer->size; + + p_buffer->resource->Release(); + p_buffer->resource = nullptr; + p_buffer->allocation->Release(); + p_buffer->allocation = nullptr; + p_buffer->size = 0; + + return OK; +} + +Error RenderingDeviceD3D12::_insert_staging_block() { + StagingBufferBlock block; + + D3D12_RESOURCE_DESC resource_desc = {}; + resource_desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + resource_desc.Alignment = 0; + resource_desc.Width = staging_buffer_block_size; + resource_desc.Height = 1; + resource_desc.DepthOrArraySize = 1; + resource_desc.MipLevels = 1; + resource_desc.Format = DXGI_FORMAT_UNKNOWN; + resource_desc.SampleDesc.Count = 1; + resource_desc.SampleDesc.Quality = 0; + resource_desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + resource_desc.Flags = D3D12_RESOURCE_FLAG_NONE; + + D3D12MA::ALLOCATION_DESC allocation_desc = {}; + allocation_desc.HeapType = D3D12_HEAP_TYPE_UPLOAD; + + HRESULT res = context->get_allocator()->CreateResource( + &allocation_desc, + &resource_desc, + D3D12_RESOURCE_STATE_GENERIC_READ, + NULL, + &block.allocation, + IID_PPV_ARGS(&block.resource)); + ERR_FAIL_COND_V_MSG(res, ERR_CANT_CREATE, "CreateResource failed with error " + vformat("0x%08ux", res) + "."); + + staging_buffer_blocks.insert(staging_buffer_current, block); + return OK; +} + +Error RenderingDeviceD3D12::_staging_buffer_allocate(uint32_t p_amount, uint32_t p_required_align, uint32_t &r_alloc_offset, uint32_t &r_alloc_size, bool p_can_segment) { + // Determine a block to use. + + r_alloc_size = p_amount; + + while (true) { + r_alloc_offset = 0; + + // See if we can use current block. + if (staging_buffer_blocks[staging_buffer_current].frame_used == frames_drawn) { + // We used this block this frame, let's see if there is still room. + + uint32_t write_from = staging_buffer_blocks[staging_buffer_current].fill_amount; + + { + uint32_t align_remainder = write_from % p_required_align; + if (align_remainder != 0) { + write_from += p_required_align - align_remainder; + } + } + + int32_t available_bytes = int32_t(staging_buffer_block_size) - int32_t(write_from); + + if ((int32_t)p_amount < available_bytes) { + // All is good, we should be ok, all will fit. + r_alloc_offset = write_from; + } else if (p_can_segment && available_bytes >= (int32_t)p_required_align) { + // Ok all won't fit but at least we can fit a chunkie. + // All is good, update what needs to be written to. + r_alloc_offset = write_from; + r_alloc_size = available_bytes - (available_bytes % p_required_align); + + } else { + // Can't fit it into this buffer. + // Will need to try next buffer. + + staging_buffer_current = (staging_buffer_current + 1) % staging_buffer_blocks.size(); + + // Before doing anything, though, let's check that we didn't manage to fill all functions. + // Possible in a single frame. + if (staging_buffer_blocks[staging_buffer_current].frame_used == frames_drawn) { + // Guess we did.. ok, let's see if we can insert a new block. + if ((uint64_t)staging_buffer_blocks.size() * staging_buffer_block_size < staging_buffer_max_size) { + // We can, so we are safe. + Error err = _insert_staging_block(); + if (err) { + return err; + } + // Claim for this frame. + staging_buffer_blocks.write[staging_buffer_current].frame_used = frames_drawn; + } else { + // Ok, worst case scenario, all the staging buffers belong to this frame + // and this frame is not even done + // If this is the main thread, it means the user is likely loading a lot of resources at once,. + // Otherwise, the thread should just be blocked until the next frame (currently unimplemented). + + if (false) { // Separate thread from render. + + //block_until_next_frame() + continue; + } else { + // Flush EVERYTHING including setup commands. IF not immediate, also need to flush the draw commands. + _flush(true); + + // Clear the whole staging buffer. + for (int i = 0; i < staging_buffer_blocks.size(); i++) { + staging_buffer_blocks.write[i].frame_used = 0; + staging_buffer_blocks.write[i].fill_amount = 0; + } + // Claim current. + staging_buffer_blocks.write[staging_buffer_current].frame_used = frames_drawn; + } + } + + } else { + // Not from current frame, so continue and try again. + continue; + } + } + + } else if (staging_buffer_blocks[staging_buffer_current].frame_used <= frames_drawn - frame_count) { + // This is an old block, which was already processed, let's reuse. + staging_buffer_blocks.write[staging_buffer_current].frame_used = frames_drawn; + staging_buffer_blocks.write[staging_buffer_current].fill_amount = 0; + } else { + // This block may still be in use, let's not touch it unless we have to, so.. can we create a new one? + if ((uint64_t)staging_buffer_blocks.size() * staging_buffer_block_size < staging_buffer_max_size) { + // We are still allowed to create a new block, so let's do that and insert it for current pos. + Error err = _insert_staging_block(); + if (err) { + return err; + } + // Claim for this frame. + staging_buffer_blocks.write[staging_buffer_current].frame_used = frames_drawn; + } else { + // Oops, we are out of room and we can't create more. + // Let's flush older frames. + // The logic here is that if a game is loading a lot of data from the main thread, it will need to be stalled anyway. + // If loading from a separate thread, we can block that thread until next frame when more room is made (not currently implemented, though). + + if (false) { + // Separate thread from render. + //block_until_next_frame() + continue; // And try again. + } else { + _flush(false); + + for (int i = 0; i < staging_buffer_blocks.size(); i++) { + // Clear all functions but the ones from this frame. + int block_idx = (i + staging_buffer_current) % staging_buffer_blocks.size(); + if (staging_buffer_blocks[block_idx].frame_used == frames_drawn) { + break; // Ok, we reached something from this frame, abort. + } + + staging_buffer_blocks.write[block_idx].frame_used = 0; + staging_buffer_blocks.write[block_idx].fill_amount = 0; + } + + // Claim for current frame. + staging_buffer_blocks.write[staging_buffer_current].frame_used = frames_drawn; + } + } + } + + // All was good, break. + break; + } + + staging_buffer_used = true; + + return OK; +} + +Error RenderingDeviceD3D12::_buffer_update(Buffer *p_buffer, size_t p_offset, const uint8_t *p_data, size_t p_data_size, bool p_use_draw_command_list, uint32_t p_required_align) { + // Submitting may get chunked for various reasons, so convert this to a task. + size_t to_submit = p_data_size; + size_t submit_from = 0; + + while (to_submit > 0) { + uint32_t block_write_offset; + uint32_t block_write_amount; + + Error err = _staging_buffer_allocate(MIN(to_submit, staging_buffer_block_size), p_required_align, block_write_offset, block_write_amount); + if (err) { + return err; + } + + // Map staging buffer. + + void *data_ptr = nullptr; + { + HRESULT res = staging_buffer_blocks[staging_buffer_current].resource->Map(0, &VOID_RANGE, &data_ptr); + ERR_FAIL_COND_V_MSG(res, ERR_CANT_CREATE, "Map failed with error " + vformat("0x%08ux", res) + "."); + } + + // Copy to staging buffer. + memcpy(((uint8_t *)data_ptr) + block_write_offset, p_data + submit_from, block_write_amount); + + // Unmap. + staging_buffer_blocks[staging_buffer_current].resource->Unmap(0, &VOID_RANGE); + + // Insert a command to copy this. + ID3D12GraphicsCommandList *command_list = (p_use_draw_command_list ? frames[frame].draw_command_list : frames[frame].setup_command_list).Get(); + command_list->CopyBufferRegion(p_buffer->resource, submit_from + p_offset, staging_buffer_blocks[staging_buffer_current].resource, block_write_offset, block_write_amount); + + staging_buffer_blocks.write[staging_buffer_current].fill_amount = block_write_offset + block_write_amount; + + to_submit -= block_write_amount; + submit_from += block_write_amount; + } + + return OK; +} + +/*****************/ +/**** TEXTURE ****/ +/*****************/ + +RID RenderingDeviceD3D12::texture_create(const TextureFormat &p_format, const TextureView &p_view, const Vector<Vector<uint8_t>> &p_data) { + _THREAD_SAFE_METHOD_ + + D3D12_RESOURCE_DESC1 resource_desc = {}; // Using D3D12_RESOURCE_DESC1. Thanks to the layout, it's sliceable down to D3D12_RESOURCE_DESC if needed. + resource_desc.Alignment = 0; // D3D12MA will override this to use a smaller alignment than the default if possible. + + Vector<DataFormat> allowed_formats; + if (p_format.shareable_formats.size()) { + ERR_FAIL_COND_V_MSG(p_format.shareable_formats.find(p_format.format) == -1, RID(), + "If supplied a list of shareable formats, the current format must be present in the list"); + ERR_FAIL_COND_V_MSG(p_view.format_override != DATA_FORMAT_MAX && p_format.shareable_formats.find(p_view.format_override) == -1, RID(), + "If supplied a list of shareable formats, the current view format override must be present in the list"); + allowed_formats = p_format.shareable_formats; + } else { + allowed_formats.push_back(p_format.format); + if (p_view.format_override != DATA_FORMAT_MAX) { + allowed_formats.push_back(p_view.format_override); + } + } + + ERR_FAIL_INDEX_V(p_format.texture_type, TEXTURE_TYPE_MAX, RID()); + + resource_desc.Dimension = d3d12_texture_dimension[p_format.texture_type]; + + ERR_FAIL_COND_V_MSG(p_format.width < 1, RID(), "Width must be equal or greater than 1 for all textures"); + + resource_desc.Format = d3d12_formats[p_format.format].family; + + resource_desc.Width = p_format.width; + if (resource_desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D || resource_desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D) { + ERR_FAIL_COND_V_MSG(p_format.height < 1, RID(), "Height must be equal or greater than 1 for 2D and 3D textures"); + resource_desc.Height = p_format.height; + } else { + resource_desc.Height = 1; + } + + if (resource_desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D) { + ERR_FAIL_COND_V_MSG(p_format.depth < 1, RID(), "Depth must be equal or greater than 1 for 3D textures"); + resource_desc.DepthOrArraySize = p_format.depth; + } else { + resource_desc.DepthOrArraySize = 1; + } + + ERR_FAIL_COND_V(p_format.mipmaps < 1, RID()); + + resource_desc.MipLevels = p_format.mipmaps; + + if (p_format.texture_type == TEXTURE_TYPE_1D_ARRAY || p_format.texture_type == TEXTURE_TYPE_2D_ARRAY || p_format.texture_type == TEXTURE_TYPE_CUBE_ARRAY || p_format.texture_type == TEXTURE_TYPE_CUBE) { + ERR_FAIL_COND_V_MSG(p_format.array_layers < 1, RID(), + "Amount of layers must be equal or greater than 1 for arrays and cubemaps."); + ERR_FAIL_COND_V_MSG((p_format.texture_type == TEXTURE_TYPE_CUBE_ARRAY || p_format.texture_type == TEXTURE_TYPE_CUBE) && (p_format.array_layers % 6) != 0, RID(), + "Cubemap and cubemap array textures must provide a layer number that is multiple of 6"); + resource_desc.DepthOrArraySize *= p_format.array_layers; + } + + ERR_FAIL_INDEX_V(p_format.samples, TEXTURE_SAMPLES_MAX, RID()); + + // Usage. + + if ((p_format.usage_bits & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT)) { + resource_desc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + } else { + if ((p_format.usage_bits & TEXTURE_USAGE_CAN_COPY_TO_BIT)) { + resource_desc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; // For clearing via UAV. + } + } + + if (p_format.usage_bits & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) { + resource_desc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; + } + + if (p_format.usage_bits & TEXTURE_USAGE_STORAGE_BIT) { + resource_desc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + } + + resource_desc.SampleDesc = {}; + DXGI_FORMAT format_to_test = (resource_desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) ? d3d12_formats[p_format.format].dsv_format : d3d12_formats[p_format.format].general_format; + if (!(resource_desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { + resource_desc.SampleDesc.Count = MIN( + _find_max_common_supported_sample_count(&format_to_test, 1), + rasterization_sample_count[p_format.samples]); + } else { + // No MSAA in D3D12 if storage. May have become possible recently where supported, though. + resource_desc.SampleDesc.Count = 1; + } + resource_desc.SampleDesc.Quality = resource_desc.SampleDesc.Count == 1 ? 0 : DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN; + + uint32_t required_mipmaps = get_image_required_mipmaps(p_format.width, p_format.height, p_format.depth); + + ERR_FAIL_COND_V_MSG(required_mipmaps < p_format.mipmaps, RID(), + "Too many mipmaps requested for texture format and dimensions (" + itos(p_format.mipmaps) + "), maximum allowed: (" + itos(required_mipmaps) + ")."); + + if (p_data.size()) { + ERR_FAIL_COND_V_MSG(!(p_format.usage_bits & TEXTURE_USAGE_CAN_UPDATE_BIT), RID(), + "Texture needs the TEXTURE_USAGE_CAN_UPDATE_BIT usage flag in order to be updated at initialization or later"); + + int expected_images = p_format.array_layers; + ERR_FAIL_COND_V_MSG(p_data.size() != expected_images, RID(), + "Default supplied data for image format is of invalid length (" + itos(p_data.size()) + "), should be (" + itos(expected_images) + ")."); + + for (uint32_t i = 0; i < p_format.array_layers; i++) { + uint32_t required_size = get_image_format_required_size(p_format.format, p_format.width, p_format.height, p_format.depth, p_format.mipmaps); + ERR_FAIL_COND_V_MSG((uint32_t)p_data[i].size() != required_size, RID(), + "Data for slice index " + itos(i) + " (mapped to layer " + itos(i) + ") differs in size (supplied: " + itos(p_data[i].size()) + ") than what is required by the format (" + itos(required_size) + ")."); + } + } + + // Validate that this image is supported for the intended use. + + // If views of different families are wanted, special setup is needed for proper sharing among them. + // Two options here: + // 1. If ID3DDevice10 is present and driver reports relaxed casting is, leverage its new extended resource creation API (via D3D12MA). + // 2. Otherwise, fall back to an approach based on abusing aliasing, hoping for the best. + bool cross_family_sharing = false; + ComPtr<ID3D12Device10> device10; + device.As(&device10); + bool relaxed_casting_available = device10.Get() && context->get_format_capabilities().relaxed_casting_supported; + LocalVector<DXGI_FORMAT> castable_formats; + + HashMap<DataFormat, D3D12_RESOURCE_FLAGS> aliases_forbidden_flags; + D3D12_RESOURCE_FLAGS accum_forbidden_flags = {}; + for (DataFormat curr_format : allowed_formats) { + // For now, we'll validate usages only the main format, to match what Vulkan RD does. + // TODO: The aliasing trick assumes the main format is the only writable one. We should either validate for that or handle a different order gracefully. + bool checking_main_format = curr_format == p_format.format; + + String format_text = "'" + String(named_formats[p_format.format]) + "'"; + + ERR_FAIL_COND_V_MSG(d3d12_formats[curr_format].family == DXGI_FORMAT_UNKNOWN, RID(), "Format " + format_text + " is not supported."); + + if (d3d12_formats[curr_format].family != d3d12_formats[allowed_formats[0]].family) { + cross_family_sharing = true; + } + if (relaxed_casting_available) { + castable_formats.push_back(d3d12_formats[curr_format].general_format); + } + + D3D12_FEATURE_DATA_FORMAT_SUPPORT srv_rtv_support = {}; + srv_rtv_support.Format = d3d12_formats[curr_format].general_format; + HRESULT res = device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &srv_rtv_support, sizeof(srv_rtv_support)); + ERR_FAIL_COND_V_MSG(res, RID(), "CheckFeatureSupport failed with error " + vformat("0x%08ux", res) + "."); + + D3D12_FEATURE_DATA_FORMAT_SUPPORT uav_support = srv_rtv_support; // Fine for now. + + D3D12_FEATURE_DATA_FORMAT_SUPPORT dsv_support = {}; + dsv_support.Format = d3d12_formats[curr_format].dsv_format; + res = device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &dsv_support, sizeof(dsv_support)); + ERR_FAIL_COND_V_MSG(res, RID(), "CheckFeatureSupport failed with error " + vformat("0x%08ux", res) + "."); + + if (checking_main_format) { + if ((p_format.usage_bits & (TEXTURE_USAGE_SAMPLING_BIT | TEXTURE_USAGE_COLOR_ATTACHMENT_BIT))) { + if (p_format.mipmaps && !(srv_rtv_support.Support1 & D3D12_FORMAT_SUPPORT1_MIP)) { + ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support mip.maps."); + } + } + + // Per https://docs.microsoft.com/en-us/windows/win32/api/d3d12/ne-d3d12-d3d12_format_support1, + // as long as the resource can be used as a texture, Sample() will work with point filter at least. + // However, we've empirically found that checking for at least D3D12_FORMAT_SUPPORT1_SHADER_LOAD is needed. + // That's almost good for integer formats. The problem is that theoretically there may be + // float formats that support LOAD but not SAMPLE fully, so this check will not detect + // such a flaw in the format. Linearly interpolated sampling would just not work on them. + // [[IMPLICIT_SAMPLE]] + if ((p_format.usage_bits & TEXTURE_USAGE_SAMPLING_BIT) && !(srv_rtv_support.Support1 & (D3D12_FORMAT_SUPPORT1_SHADER_LOAD | D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE))) { + ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as a sampled texture."); + } + + if ((p_format.usage_bits & TEXTURE_USAGE_SAMPLING_BIT) && d3d12_formats[curr_format].general_format == DXGI_FORMAT_UNKNOWN) { + ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as a sampled texture."); + } + + if ((p_format.usage_bits & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) && !(srv_rtv_support.Support1 & D3D12_FORMAT_SUPPORT1_RENDER_TARGET)) { + ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as color attachment."); + } + } + + if ((p_format.usage_bits & TEXTURE_USAGE_CAN_COPY_TO_BIT)) { + // We need to check if the texture can be cleared; if it's not flagged for color attachment , we have to see if it's possible via a UAV. + if (!(p_format.usage_bits & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT)) { + if (!(uav_support.Support1 & D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW)) { + if (checking_main_format) { + ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as a copy-to texture, because clearing it is not supported."); + } else { + aliases_forbidden_flags[curr_format] |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + accum_forbidden_flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + } + } + } + } + + if ((p_format.usage_bits & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) && !(dsv_support.Support1 & D3D12_FORMAT_SUPPORT1_DEPTH_STENCIL)) { + if (checking_main_format) { + printf("dxgiformat: %x\n", resource_desc.Format); + ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as depth-stencil attachment."); + } else { + aliases_forbidden_flags[curr_format] |= D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; + accum_forbidden_flags |= D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; + } + } + + if ((p_format.usage_bits & TEXTURE_USAGE_STORAGE_BIT)) { + if (!(uav_support.Support1 & D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW)) { // Maybe check LOAD/STORE, too? + if (checking_main_format) { + ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as storage image."); + } else { + aliases_forbidden_flags[curr_format] |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + accum_forbidden_flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + } + } + } + + if (checking_main_format) { + if ((p_format.usage_bits & TEXTURE_USAGE_STORAGE_ATOMIC_BIT) && !(uav_support.Support2 & D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_ADD)) { // Check a basic atomic at least. + ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as atomic storage image."); + } + + if ((p_format.usage_bits & TEXTURE_USAGE_VRS_ATTACHMENT_BIT) && d3d12_formats[curr_format].general_format != DXGI_FORMAT_R8_UINT) { + ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as VRS attachment."); + } + } + } + + if (cross_family_sharing && !relaxed_casting_available) { + // At least guarantee the same layout among aliases. + resource_desc.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE; + + // Per https://docs.microsoft.com/en-us/windows/win32/api/d3d12/ne-d3d12-d3d12_texture_layout. + if (p_format.texture_type == TEXTURE_TYPE_1D) { + ERR_FAIL_V_MSG(RID(), "This texture's views require aliasing, but that's not supported for a 1D texture."); + } + if (p_format.samples != TEXTURE_SAMPLES_1) { + ERR_FAIL_V_MSG(RID(), "This texture's views require aliasing, but that's not supported for a multi-sample texture."); + } + if ((p_format.usage_bits & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) { + ERR_FAIL_V_MSG(RID(), "This texture's views require aliasing, but that's not supported for a depth-stencil texture."); + } + if (d3d12_formats[p_format.format].family == DXGI_FORMAT_R32G32B32_TYPELESS) { + ERR_FAIL_V_MSG(RID(), "This texture's views require aliasing, but that's not supported for an R32G32B32 texture."); + } + } else { + resource_desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + } + + if ((p_format.usage_bits & TEXTURE_USAGE_VRS_ATTACHMENT_BIT)) { + // For VRS images we can't use the typeless format. + resource_desc.Format = DXGI_FORMAT_R8_UINT; + } + + // Some view validation. + + if (p_view.format_override != DATA_FORMAT_MAX) { + ERR_FAIL_INDEX_V(p_view.format_override, DATA_FORMAT_MAX, RID()); + } + ERR_FAIL_INDEX_V(p_view.swizzle_r, TEXTURE_SWIZZLE_MAX, RID()); + ERR_FAIL_INDEX_V(p_view.swizzle_g, TEXTURE_SWIZZLE_MAX, RID()); + ERR_FAIL_INDEX_V(p_view.swizzle_b, TEXTURE_SWIZZLE_MAX, RID()); + ERR_FAIL_INDEX_V(p_view.swizzle_a, TEXTURE_SWIZZLE_MAX, RID()); + + // Allocate memory. + + D3D12MA::ALLOCATION_DESC allocation_desc = {}; + if (cross_family_sharing && !relaxed_casting_available) { + allocation_desc.Flags = D3D12MA::ALLOCATION_FLAG_CAN_ALIAS; + } + allocation_desc.HeapType = (p_format.usage_bits & TEXTURE_USAGE_CPU_READ_BIT) ? D3D12_HEAP_TYPE_READBACK : D3D12_HEAP_TYPE_DEFAULT; + if ((resource_desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL))) { + if (!(accum_forbidden_flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL))) { + allocation_desc.ExtraHeapFlags = D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES; + } + } else { + allocation_desc.ExtraHeapFlags = D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES; + } + if ((resource_desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { + if (!(accum_forbidden_flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { + allocation_desc.ExtraHeapFlags |= D3D12_HEAP_FLAG_ALLOW_SHADER_ATOMICS; + } + } + +#ifdef USE_SMALL_ALLOCS_POOL + uint32_t width, height; + uint32_t image_size = get_image_format_required_size(p_format.format, p_format.width, p_format.height, p_format.depth, p_format.mipmaps, &width, &height); + if (image_size <= SMALL_ALLOCATION_MAX_SIZE) { + allocation_desc.CustomPool = _find_or_create_small_allocs_pool(allocation_desc.HeapType, allocation_desc.ExtraHeapFlags); + } +#endif + + Texture texture; + + D3D12_RESOURCE_STATES initial_state = p_data.size() || (p_format.usage_bits & TEXTURE_USAGE_CPU_READ_BIT) ? D3D12_RESOURCE_STATE_COPY_DEST : D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE; + FLOAT black[4] = {}; + D3D12_CLEAR_VALUE clear_value = CD3DX12_CLEAR_VALUE(d3d12_formats[p_format.format].general_format, black); + D3D12_CLEAR_VALUE *clear_value_ptr = (resource_desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) ? &clear_value : nullptr; + HRESULT res = {}; + if (cross_family_sharing && relaxed_casting_available) { + res = context->get_allocator()->CreateResource3( + &allocation_desc, + &resource_desc, + D3D12_BARRIER_LAYOUT_COMMON, // Needed for barrier interop. + clear_value_ptr, + castable_formats.size(), + castable_formats.ptr(), + &texture.allocation, + IID_PPV_ARGS(&texture.owner_resource)); + initial_state = D3D12_RESOURCE_STATE_COMMON; // Needed for barrier interop. + } else { + res = context->get_allocator()->CreateResource( + &allocation_desc, + (D3D12_RESOURCE_DESC *)&resource_desc, + initial_state, + clear_value_ptr, + &texture.allocation, + IID_PPV_ARGS(&texture.owner_resource)); + } + ERR_FAIL_COND_V_MSG(res, RID(), "CreateResource failed with error " + vformat("0x%08ux", res) + "."); + texture.resource = texture.owner_resource; + image_memory += texture.allocation->GetSize(); + texture.type = p_format.texture_type; + texture.format = p_format.format; + texture.planes = get_image_format_plane_count(p_format.format); + texture.width = p_format.width; + texture.height = p_format.height; + texture.depth = p_format.depth; + texture.layers = p_format.array_layers; + texture.mipmaps = p_format.mipmaps; + texture.owner_layers = texture.layers; + texture.owner_mipmaps = texture.mipmaps; + texture.base_mipmap = 0; + texture.base_layer = 0; + texture.is_resolve_buffer = p_format.is_resolve_buffer; + texture.usage_flags = p_format.usage_bits; + texture.samples = p_format.samples; + texture.allowed_shared_formats = p_format.shareable_formats; + texture.own_states.subresource_states.resize(texture.mipmaps * texture.layers); + for (uint32_t i = 0; i < texture.own_states.subresource_states.size(); i++) { + texture.own_states.subresource_states[i] = initial_state; + } + texture.bound = false; + + // Describe view. + + static const D3D12_SRV_DIMENSION view_dimensions[TEXTURE_TYPE_MAX] = { + D3D12_SRV_DIMENSION_TEXTURE1D, + D3D12_SRV_DIMENSION_TEXTURE2D, + D3D12_SRV_DIMENSION_TEXTURE3D, + D3D12_SRV_DIMENSION_TEXTURECUBE, + D3D12_SRV_DIMENSION_TEXTURE1DARRAY, + D3D12_SRV_DIMENSION_TEXTURE2DARRAY, + D3D12_SRV_DIMENSION_TEXTURECUBEARRAY, + }; + static const D3D12_SRV_DIMENSION view_dimensions_ms[TEXTURE_TYPE_MAX] = { + D3D12_SRV_DIMENSION_UNKNOWN, + D3D12_SRV_DIMENSION_TEXTURE2DMS, + D3D12_SRV_DIMENSION_UNKNOWN, + D3D12_SRV_DIMENSION_UNKNOWN, + D3D12_SRV_DIMENSION_UNKNOWN, + D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY, + D3D12_SRV_DIMENSION_UNKNOWN, + }; + static const D3D12_UAV_DIMENSION uav_dimensions[TEXTURE_TYPE_MAX] = { + D3D12_UAV_DIMENSION_TEXTURE1D, + D3D12_UAV_DIMENSION_TEXTURE2D, + D3D12_UAV_DIMENSION_TEXTURE3D, + D3D12_UAV_DIMENSION_TEXTURE2DARRAY, + D3D12_UAV_DIMENSION_TEXTURE1DARRAY, + D3D12_UAV_DIMENSION_TEXTURE2DARRAY, + D3D12_UAV_DIMENSION_TEXTURE2DARRAY, + }; + + texture.srv_desc.ViewDimension = p_format.samples == TEXTURE_SAMPLES_1 ? view_dimensions[p_format.texture_type] : view_dimensions_ms[p_format.texture_type]; + + texture.owner_uav_desc.Format = d3d12_formats[p_format.format].general_format; + texture.owner_uav_desc.ViewDimension = p_format.samples == TEXTURE_SAMPLES_1 ? uav_dimensions[p_format.texture_type] : D3D12_UAV_DIMENSION_UNKNOWN; + + UINT base_swizzle = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + if (p_view.format_override == DATA_FORMAT_MAX) { + texture.srv_desc.Format = d3d12_formats[p_format.format].general_format; + base_swizzle = d3d12_formats[p_format.format].swizzle; + } else { + texture.srv_desc.Format = d3d12_formats[p_view.format_override].general_format; + base_swizzle = d3d12_formats[p_view.format_override].swizzle; + } + + // Apply requested swizzle (component mapping) on top of the one from the format database. + + D3D12_SHADER_COMPONENT_MAPPING component_swizzles[TEXTURE_SWIZZLE_MAX] = { + D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_0, // Unused. + D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_0, + D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_1, + // These will be D3D12_SHADER_COMPONENT_MAPPING_FROM_MEMORY_COMPONENT_*. + D3D12_DECODE_SHADER_4_COMPONENT_MAPPING(0, base_swizzle), + D3D12_DECODE_SHADER_4_COMPONENT_MAPPING(1, base_swizzle), + D3D12_DECODE_SHADER_4_COMPONENT_MAPPING(2, base_swizzle), + D3D12_DECODE_SHADER_4_COMPONENT_MAPPING(3, base_swizzle), + }; + + texture.srv_desc.Shader4ComponentMapping = D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING( + p_view.swizzle_r == TEXTURE_SWIZZLE_IDENTITY ? component_swizzles[TEXTURE_SWIZZLE_R] : component_swizzles[p_view.swizzle_r], + p_view.swizzle_g == TEXTURE_SWIZZLE_IDENTITY ? component_swizzles[TEXTURE_SWIZZLE_G] : component_swizzles[p_view.swizzle_g], + p_view.swizzle_b == TEXTURE_SWIZZLE_IDENTITY ? component_swizzles[TEXTURE_SWIZZLE_B] : component_swizzles[p_view.swizzle_b], + p_view.swizzle_a == TEXTURE_SWIZZLE_IDENTITY ? component_swizzles[TEXTURE_SWIZZLE_A] : component_swizzles[p_view.swizzle_a]); + + switch (texture.srv_desc.ViewDimension) { + case D3D12_SRV_DIMENSION_TEXTURE1D: { + texture.srv_desc.Texture1D.MipLevels = p_format.mipmaps; + } break; + case D3D12_SRV_DIMENSION_TEXTURE1DARRAY: { + texture.srv_desc.Texture1DArray.MipLevels = p_format.mipmaps; + texture.srv_desc.Texture1DArray.ArraySize = p_format.array_layers; + } break; + case D3D12_SRV_DIMENSION_TEXTURE2D: { + texture.srv_desc.Texture2D.MipLevels = p_format.mipmaps; + } break; + case D3D12_SRV_DIMENSION_TEXTURE2DMS: { + } break; + case D3D12_SRV_DIMENSION_TEXTURE2DARRAY: { + texture.srv_desc.Texture2DArray.MipLevels = p_format.mipmaps; + texture.srv_desc.Texture2DArray.ArraySize = p_format.array_layers; + } break; + case D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY: { + texture.srv_desc.Texture2DMSArray.ArraySize = p_format.array_layers; + } break; + case D3D12_SRV_DIMENSION_TEXTURECUBEARRAY: { + texture.srv_desc.TextureCubeArray.MipLevels = p_format.mipmaps; + texture.srv_desc.TextureCubeArray.NumCubes = p_format.array_layers / 6; + } break; + case D3D12_SRV_DIMENSION_TEXTURE3D: { + texture.srv_desc.Texture3D.MipLevels = p_format.mipmaps; + } break; + case D3D12_SRV_DIMENSION_TEXTURECUBE: { + texture.srv_desc.TextureCube.MipLevels = p_format.mipmaps; + } break; + } + + switch (texture.owner_uav_desc.ViewDimension) { + case D3D12_UAV_DIMENSION_TEXTURE1DARRAY: { + texture.owner_uav_desc.Texture1DArray.ArraySize = p_format.array_layers; + } break; + case D3D12_UAV_DIMENSION_TEXTURE2DARRAY: { + // Either for an actual 2D texture array, cubemap or cubemap array. + texture.owner_uav_desc.Texture2DArray.ArraySize = p_format.array_layers; + } break; + case D3D12_UAV_DIMENSION_TEXTURE3D: { + texture.owner_uav_desc.Texture3D.WSize = p_format.depth; + } break; + default: { + } + } + + texture.uav_desc = texture.owner_uav_desc; + if (p_view.format_override != DATA_FORMAT_MAX) { + texture.uav_desc.Format = d3d12_formats[p_view.format_override].general_format; + } + + if (cross_family_sharing && !relaxed_casting_available) { + D3D12_RESOURCE_DESC resource_desc_backup = *(D3D12_RESOURCE_DESC *)&resource_desc; + D3D12MA::ALLOCATION_DESC allocation_desc_backup = allocation_desc; + + texture.aliases.resize(texture.allowed_shared_formats.size()); + for (int i = 0; i < texture.allowed_shared_formats.size(); i++) { + DataFormat curr_format = texture.allowed_shared_formats[i]; + + DXGI_FORMAT format_family = d3d12_formats[curr_format].family; + if (format_family == d3d12_formats[p_format.format].family) { + texture.aliases[i] = nullptr; + continue; + } + + D3D12_RESOURCE_DESC alias_resource_desc = *(D3D12_RESOURCE_DESC *)&resource_desc; + alias_resource_desc.Format = format_family; + if (aliases_forbidden_flags.has(curr_format)) { + alias_resource_desc.Flags &= ~aliases_forbidden_flags[curr_format]; + } + clear_value.Format = format_family; + res = context->get_allocator()->CreateAliasingResource( + texture.allocation, + 0, + &alias_resource_desc, + initial_state, + (alias_resource_desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) ? clear_value_ptr : nullptr, + IID_PPV_ARGS(&texture.aliases[i])); + ERR_FAIL_COND_V_MSG(res, RID(), "CreateAliasingResource failed with error " + vformat("0x%08ux", res) + "."); + + if (curr_format == p_view.format_override) { + texture.resource = texture.aliases[i]; + } + } + } + + RID id = texture_owner.make_rid(texture); +#ifdef DEV_ENABLED + set_resource_name(id, "RID:" + itos(id.get_id())); +#endif + + if (p_data.size()) { + Texture *texture_ptr = texture_owner.get_or_null(id); + ERR_FAIL_NULL_V(texture_ptr, RID()); + + ID3D12GraphicsCommandList *command_list = frames[frame].setup_command_list.Get(); + + for (uint32_t i = 0; i < p_format.array_layers; i++) { + _texture_update(texture_ptr, i, p_data[i], RD::BARRIER_MASK_ALL_BARRIERS, command_list); + } + } + return id; +} + +RID RenderingDeviceD3D12::texture_create_shared(const TextureView &p_view, RID p_with_texture) { + _THREAD_SAFE_METHOD_ + + Texture *src_texture = texture_owner.get_or_null(p_with_texture); + ERR_FAIL_NULL_V(src_texture, RID()); + + if (src_texture->owner.is_valid()) { // Ahh this is a share. + p_with_texture = src_texture->owner; + src_texture = texture_owner.get_or_null(src_texture->owner); + ERR_FAIL_NULL_V(src_texture, RID()); // This is a bug. + } + + // Describe view. + + Texture texture = *src_texture; + texture.own_states.subresource_states.clear(); + texture.states = &src_texture->own_states; + + UINT base_swizzle = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + if (p_view.format_override == DATA_FORMAT_MAX || p_view.format_override == texture.format) { + texture.srv_desc.Format = d3d12_formats[texture.format].general_format; + base_swizzle = d3d12_formats[texture.format].swizzle; + texture.uav_desc.Format = d3d12_formats[texture.format].general_format; + } else { + ERR_FAIL_INDEX_V(p_view.format_override, DATA_FORMAT_MAX, RID()); + + ERR_FAIL_COND_V_MSG(texture.allowed_shared_formats.find(p_view.format_override) == -1, RID(), + "Format override is not in the list of allowed shareable formats for original texture."); + texture.srv_desc.Format = d3d12_formats[p_view.format_override].general_format; + base_swizzle = d3d12_formats[p_view.format_override].swizzle; + texture.uav_desc.Format = d3d12_formats[p_view.format_override].general_format; + + if (texture.aliases.size()) { + for (int i = 0; i < texture.allowed_shared_formats.size(); i++) { + if (texture.allowed_shared_formats[i] == p_view.format_override) { + texture.resource = texture.aliases[i]; + break; + } + } + } + } + + // Apply requested swizzle (component mapping) on top of the one from the format database. + + D3D12_SHADER_COMPONENT_MAPPING component_swizzles[TEXTURE_SWIZZLE_MAX] = { + D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_0, // Unused. + D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_0, + D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_1, + // These will be D3D12_SHADER_COMPONENT_MAPPING_FROM_MEMORY_COMPONENT_*. + D3D12_DECODE_SHADER_4_COMPONENT_MAPPING(0, base_swizzle), + D3D12_DECODE_SHADER_4_COMPONENT_MAPPING(1, base_swizzle), + D3D12_DECODE_SHADER_4_COMPONENT_MAPPING(2, base_swizzle), + D3D12_DECODE_SHADER_4_COMPONENT_MAPPING(3, base_swizzle), + }; + + texture.srv_desc.Shader4ComponentMapping = D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING( + p_view.swizzle_r == TEXTURE_SWIZZLE_IDENTITY ? component_swizzles[TEXTURE_SWIZZLE_R] : component_swizzles[p_view.swizzle_r], + p_view.swizzle_g == TEXTURE_SWIZZLE_IDENTITY ? component_swizzles[TEXTURE_SWIZZLE_G] : component_swizzles[p_view.swizzle_g], + p_view.swizzle_b == TEXTURE_SWIZZLE_IDENTITY ? component_swizzles[TEXTURE_SWIZZLE_B] : component_swizzles[p_view.swizzle_b], + p_view.swizzle_a == TEXTURE_SWIZZLE_IDENTITY ? component_swizzles[TEXTURE_SWIZZLE_A] : component_swizzles[p_view.swizzle_a]); + + texture.owner = p_with_texture; + RID id = texture_owner.make_rid(texture); +#ifdef DEV_ENABLED + set_resource_name(id, "RID:" + itos(id.get_id())); +#endif + _add_dependency(id, p_with_texture); + + return id; +} + +RID RenderingDeviceD3D12::texture_create_from_extension(TextureType p_type, DataFormat p_format, TextureSamples p_samples, BitField<RenderingDevice::TextureUsageBits> p_flags, uint64_t p_image, uint64_t p_width, uint64_t p_height, uint64_t p_depth, uint64_t p_layers) { + ERR_FAIL_V_MSG(RID(), "Unimplemented!"); +} + +RID RenderingDeviceD3D12::texture_create_shared_from_slice(const TextureView &p_view, RID p_with_texture, uint32_t p_layer, uint32_t p_mipmap, uint32_t p_mipmaps, TextureSliceType p_slice_type, uint32_t p_layers) { + _THREAD_SAFE_METHOD_ + + Texture *src_texture = texture_owner.get_or_null(p_with_texture); + ERR_FAIL_NULL_V(src_texture, RID()); + + if (src_texture->owner.is_valid()) { // Ahh this is a share. + p_with_texture = src_texture->owner; + src_texture = texture_owner.get_or_null(src_texture->owner); + ERR_FAIL_NULL_V(src_texture, RID()); // This is a bug. + } + + ERR_FAIL_COND_V_MSG(p_slice_type == TEXTURE_SLICE_CUBEMAP && (src_texture->type != TEXTURE_TYPE_CUBE && src_texture->type != TEXTURE_TYPE_CUBE_ARRAY), RID(), + "Can only create a cubemap slice from a cubemap or cubemap array mipmap"); + + ERR_FAIL_COND_V_MSG(p_slice_type == TEXTURE_SLICE_3D && src_texture->type != TEXTURE_TYPE_3D, RID(), + "Can only create a 3D slice from a 3D texture"); + + ERR_FAIL_COND_V_MSG(p_slice_type == TEXTURE_SLICE_2D_ARRAY && (src_texture->type != TEXTURE_TYPE_2D_ARRAY), RID(), + "Can only create an array slice from a 2D array mipmap"); + + // Describe view. + + ERR_FAIL_UNSIGNED_INDEX_V(p_mipmap, src_texture->mipmaps, RID()); + ERR_FAIL_COND_V(p_mipmap + p_mipmaps > src_texture->mipmaps, RID()); + ERR_FAIL_UNSIGNED_INDEX_V(p_layer, src_texture->layers, RID()); + + int slice_layers = 1; + if (p_layers != 0) { + ERR_FAIL_COND_V_MSG(p_layers > 1 && p_slice_type != TEXTURE_SLICE_2D_ARRAY, RID(), "layer slicing only supported for 2D arrays"); + ERR_FAIL_COND_V_MSG(p_layer + p_layers > src_texture->layers, RID(), "layer slice is out of bounds"); + slice_layers = p_layers; + } else if (p_slice_type == TEXTURE_SLICE_2D_ARRAY) { + ERR_FAIL_COND_V_MSG(p_layer != 0, RID(), "layer must be 0 when obtaining a 2D array mipmap slice"); + slice_layers = src_texture->layers; + } else if (p_slice_type == TEXTURE_SLICE_CUBEMAP) { + slice_layers = 6; + } + + Texture texture = *src_texture; + get_image_format_required_size(texture.format, texture.width, texture.height, texture.depth, p_mipmap + 1, &texture.width, &texture.height); + texture.mipmaps = p_mipmaps; + texture.layers = slice_layers; + texture.base_mipmap = p_mipmap; + texture.base_layer = p_layer; + texture.own_states.subresource_states.clear(); + texture.states = &src_texture->own_states; + + UINT base_swizzle = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + if (p_view.format_override == DATA_FORMAT_MAX || p_view.format_override == texture.format) { + texture.srv_desc.Format = d3d12_formats[texture.format].general_format; + base_swizzle = d3d12_formats[texture.format].swizzle; + texture.uav_desc.Format = d3d12_formats[texture.format].general_format; + } else { + ERR_FAIL_INDEX_V(p_view.format_override, DATA_FORMAT_MAX, RID()); + + ERR_FAIL_COND_V_MSG(texture.allowed_shared_formats.find(p_view.format_override) == -1, RID(), + "Format override is not in the list of allowed shareable formats for original texture."); + texture.srv_desc.Format = d3d12_formats[p_view.format_override].general_format; + base_swizzle = d3d12_formats[p_view.format_override].swizzle; + texture.uav_desc.Format = d3d12_formats[p_view.format_override].general_format; + + if (texture.aliases.size()) { + for (int i = 0; i < texture.allowed_shared_formats.size(); i++) { + if (texture.allowed_shared_formats[i] == p_view.format_override) { + texture.resource = texture.aliases[i]; + break; + } + } + } + } + + // Apply requested swizzle (component mapping) on top of the one from the format database. + + D3D12_SHADER_COMPONENT_MAPPING component_swizzles[TEXTURE_SWIZZLE_MAX] = { + D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_0, // Unused. + D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_0, + D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_1, + // These will be D3D12_SHADER_COMPONENT_MAPPING_FROM_MEMORY_COMPONENT_*. + D3D12_DECODE_SHADER_4_COMPONENT_MAPPING(0, base_swizzle), + D3D12_DECODE_SHADER_4_COMPONENT_MAPPING(1, base_swizzle), + D3D12_DECODE_SHADER_4_COMPONENT_MAPPING(2, base_swizzle), + D3D12_DECODE_SHADER_4_COMPONENT_MAPPING(3, base_swizzle), + }; + + texture.srv_desc.Shader4ComponentMapping = D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING( + p_view.swizzle_r == TEXTURE_SWIZZLE_IDENTITY ? component_swizzles[TEXTURE_SWIZZLE_R] : component_swizzles[p_view.swizzle_r], + p_view.swizzle_g == TEXTURE_SWIZZLE_IDENTITY ? component_swizzles[TEXTURE_SWIZZLE_G] : component_swizzles[p_view.swizzle_g], + p_view.swizzle_b == TEXTURE_SWIZZLE_IDENTITY ? component_swizzles[TEXTURE_SWIZZLE_B] : component_swizzles[p_view.swizzle_b], + p_view.swizzle_a == TEXTURE_SWIZZLE_IDENTITY ? component_swizzles[TEXTURE_SWIZZLE_A] : component_swizzles[p_view.swizzle_a]); + + if (p_slice_type == TEXTURE_SLICE_CUBEMAP) { + ERR_FAIL_COND_V_MSG(p_layer >= src_texture->layers, RID(), + "Specified layer is invalid for cubemap"); + ERR_FAIL_COND_V_MSG((p_layer % 6) != 0, RID(), + "Specified layer must be a multiple of 6."); + } + + // Leveraging aliasing in members of the union as much as possible. + + texture.srv_desc.Texture1D.MostDetailedMip = p_mipmap; + texture.srv_desc.Texture1D.MipLevels = 1; + + texture.uav_desc.Texture1D.MipSlice = p_mipmap; + + switch (p_slice_type) { + case TEXTURE_SLICE_2D: { + if (texture.srv_desc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2D && p_layer == 0) { + CRASH_COND(texture.uav_desc.ViewDimension != D3D12_UAV_DIMENSION_TEXTURE2D); + } else if (texture.srv_desc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2DMS && p_layer == 0) { + CRASH_COND(texture.uav_desc.ViewDimension != D3D12_UAV_DIMENSION_UNKNOWN); + } else if ((texture.srv_desc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2DARRAY || (texture.srv_desc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2D && p_layer)) || texture.srv_desc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURECUBE || texture.srv_desc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURECUBEARRAY) { + texture.srv_desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; + texture.srv_desc.Texture2DArray.FirstArraySlice = p_layer; + texture.srv_desc.Texture2DArray.ArraySize = 1; + texture.srv_desc.Texture2DArray.PlaneSlice = 0; + texture.srv_desc.Texture2DArray.ResourceMinLODClamp = 0.0f; + + texture.uav_desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + texture.uav_desc.Texture2DArray.FirstArraySlice = p_layer; + texture.uav_desc.Texture2DArray.ArraySize = 1; + texture.uav_desc.Texture2DArray.PlaneSlice = 0; + } else if ((texture.srv_desc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY || (texture.srv_desc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2DMS && p_layer))) { + texture.srv_desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; + texture.srv_desc.Texture2DMSArray.FirstArraySlice = p_layer; + texture.srv_desc.Texture2DMSArray.ArraySize = 1; + + texture.uav_desc.ViewDimension = D3D12_UAV_DIMENSION_UNKNOWN; + } else { + CRASH_NOW(); + } + } break; + case TEXTURE_SLICE_CUBEMAP: { + if (texture.srv_desc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURECUBE) { + CRASH_COND(texture.uav_desc.ViewDimension != D3D12_UAV_DIMENSION_TEXTURE2DARRAY); + } else if (texture.srv_desc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURECUBE || p_layer == 0) { + texture.srv_desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBE; + + CRASH_COND(texture.uav_desc.ViewDimension != D3D12_UAV_DIMENSION_TEXTURE2DARRAY); + texture.uav_desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + texture.uav_desc.Texture2DArray.FirstArraySlice = 0; + texture.uav_desc.Texture2DArray.ArraySize = 6; + texture.uav_desc.Texture2DArray.PlaneSlice = 0; + } else if (texture.srv_desc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURECUBEARRAY || p_layer != 0) { + texture.srv_desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBEARRAY; + texture.srv_desc.TextureCubeArray.First2DArrayFace = p_layer; + texture.srv_desc.TextureCubeArray.NumCubes = 1; + texture.srv_desc.TextureCubeArray.ResourceMinLODClamp = 0.0f; + + CRASH_COND(texture.uav_desc.ViewDimension != D3D12_UAV_DIMENSION_TEXTURE2DARRAY); + texture.uav_desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + texture.uav_desc.Texture2DArray.FirstArraySlice = p_layer; + texture.uav_desc.Texture2DArray.ArraySize = 6; + texture.uav_desc.Texture2DArray.PlaneSlice = 0; + } else { + CRASH_NOW(); + } + } break; + case TEXTURE_SLICE_3D: { + CRASH_COND(texture.srv_desc.ViewDimension != D3D12_SRV_DIMENSION_TEXTURE3D); + CRASH_COND(texture.uav_desc.ViewDimension != D3D12_UAV_DIMENSION_TEXTURE3D); + texture.uav_desc.Texture3D.WSize = -1; + } break; + case TEXTURE_SLICE_2D_ARRAY: { + CRASH_COND(texture.srv_desc.ViewDimension != D3D12_SRV_DIMENSION_TEXTURE2DARRAY); + texture.srv_desc.Texture2DArray.FirstArraySlice = p_layer; + texture.srv_desc.Texture2DArray.ArraySize = slice_layers; + + CRASH_COND(texture.uav_desc.ViewDimension != D3D12_UAV_DIMENSION_TEXTURE2DARRAY); + texture.uav_desc.Texture2DArray.FirstArraySlice = p_layer; + texture.uav_desc.Texture2DArray.ArraySize = slice_layers; + } break; + } + + texture.owner = p_with_texture; + RID id = texture_owner.make_rid(texture); +#ifdef DEV_ENABLED + set_resource_name(id, "RID:" + itos(id.get_id())); +#endif + _add_dependency(id, p_with_texture); + + return id; +} + +Error RenderingDeviceD3D12::texture_update(RID p_texture, uint32_t p_layer, const Vector<uint8_t> &p_data, BitField<BarrierMask> p_post_barrier) { + ERR_FAIL_COND_V_MSG((draw_list || compute_list), ERR_INVALID_PARAMETER, + "Updating textures is forbidden during creation of a draw or compute list"); + + Texture *texture = texture_owner.get_or_null(p_texture); + ERR_FAIL_NULL_V(texture, ERR_INVALID_PARAMETER); + + if (texture->owner != RID()) { + texture = texture_owner.get_or_null(texture->owner); + ERR_FAIL_NULL_V(texture, ERR_BUG); // This is a bug. + } + + ID3D12GraphicsCommandList *command_list = frames[frame].draw_command_list.Get(); + + uint32_t subresource = D3D12CalcSubresource(0, p_layer, 0, texture->mipmaps, texture->layers); + _resource_transition_batch(texture, subresource, texture->planes, D3D12_RESOURCE_STATE_COPY_DEST); + _resource_transitions_flush(command_list); + Error err = _texture_update(texture, p_layer, p_data, p_post_barrier, command_list); + + return err; +} + +static _ALWAYS_INLINE_ void _copy_region(uint8_t const *__restrict p_src, uint8_t *__restrict p_dst, uint32_t p_src_x, uint32_t p_src_y, uint32_t p_src_w, uint32_t p_src_h, uint32_t p_src_full_w, uint32_t p_dst_pitch, uint32_t p_unit_size) { + uint32_t src_offset = (p_src_y * p_src_full_w + p_src_x) * p_unit_size; + uint32_t dst_offset = 0; + for (uint32_t y = p_src_h; y > 0; y--) { + uint8_t const *__restrict src = p_src + src_offset; + uint8_t *__restrict dst = p_dst + dst_offset; + for (uint32_t x = p_src_w * p_unit_size; x > 0; x--) { + *dst = *src; + src++; + dst++; + } + src_offset += p_src_full_w * p_unit_size; + dst_offset += p_dst_pitch; + } +} + +Error RenderingDeviceD3D12::_texture_update(Texture *p_texture, uint32_t p_layer, const Vector<uint8_t> &p_data, BitField<BarrierMask> p_post_barrier, ID3D12GraphicsCommandList *p_command_list) { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND_V_MSG(p_texture->bound, ERR_CANT_ACQUIRE_RESOURCE, + "Texture can't be updated while a render pass that uses it is being created. Ensure render pass is finalized (and that it was created with RENDER_PASS_CONTENTS_FINISH) to unbind this texture."); + + ERR_FAIL_COND_V_MSG(!(p_texture->usage_flags & TEXTURE_USAGE_CAN_UPDATE_BIT), ERR_INVALID_PARAMETER, + "Texture requires the TEXTURE_USAGE_CAN_UPDATE_BIT in order to be updatable."); + + uint32_t layer_count = p_texture->layers; + if (p_texture->type == TEXTURE_TYPE_CUBE || p_texture->type == TEXTURE_TYPE_CUBE_ARRAY) { + layer_count *= 6; + } + ERR_FAIL_COND_V(p_layer >= layer_count, ERR_INVALID_PARAMETER); + + uint32_t width, height; + uint32_t image_size = get_image_format_required_size(p_texture->format, p_texture->width, p_texture->height, p_texture->depth, p_texture->mipmaps, &width, &height); + uint32_t required_size = image_size; + uint32_t required_align = get_compressed_image_format_block_byte_size(p_texture->format); + if (required_align == 1) { + required_align = get_image_format_pixel_size(p_texture->format); + } + if ((required_align % 4) != 0) { // Alignment rules are really strange. + required_align *= 4; + } + + required_align = ALIGN(required_align, D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT); + + ERR_FAIL_COND_V_MSG(required_size != (uint32_t)p_data.size(), ERR_INVALID_PARAMETER, + "Required size for texture update (" + itos(required_size) + ") does not match data supplied size (" + itos(p_data.size()) + ")."); + + uint32_t region_size = texture_upload_region_size_px; + + const uint8_t *r = p_data.ptr(); + + uint32_t mipmap_offset = 0; + + uint32_t logic_width = p_texture->width; + uint32_t logic_height = p_texture->height; + + for (uint32_t mm_i = 0; mm_i < p_texture->mipmaps; mm_i++) { + uint32_t depth; + uint32_t image_total = get_image_format_required_size(p_texture->format, p_texture->width, p_texture->height, p_texture->depth, mm_i + 1, &width, &height, &depth); + + const uint8_t *read_ptr_mipmap = r + mipmap_offset; + image_size = image_total - mipmap_offset; + + UINT dst_subresource = D3D12CalcSubresource(mm_i, p_layer, 0, p_texture->mipmaps, p_texture->layers); + CD3DX12_TEXTURE_COPY_LOCATION copy_dst(p_texture->resource, dst_subresource); + + for (uint32_t z = 0; z < depth; z++) { // For 3D textures, depth may be > 0. + + const uint8_t *read_ptr = read_ptr_mipmap + image_size * z / depth; + + for (uint32_t y = 0; y < height; y += region_size) { + for (uint32_t x = 0; x < width; x += region_size) { + uint32_t region_w = MIN(region_size, width - x); + uint32_t region_h = MIN(region_size, height - y); + + uint32_t pixel_size = get_image_format_pixel_size(p_texture->format); + uint32_t block_w, block_h; + get_compressed_image_format_block_dimensions(p_texture->format, block_w, block_h); + + uint32_t region_pitch = (region_w * pixel_size * block_w) >> get_compressed_image_format_pixel_rshift(p_texture->format); + region_pitch = ALIGN(region_pitch, D3D12_TEXTURE_DATA_PITCH_ALIGNMENT); + uint32_t to_allocate = region_pitch * region_h; + + uint32_t alloc_offset, alloc_size; + Error err = _staging_buffer_allocate(to_allocate, required_align, alloc_offset, alloc_size, false); + ERR_FAIL_COND_V(err, ERR_CANT_CREATE); + + uint8_t *write_ptr; + + { // Map. + void *data_ptr = nullptr; + HRESULT res = staging_buffer_blocks[staging_buffer_current].resource->Map(0, &VOID_RANGE, &data_ptr); + ERR_FAIL_COND_V_MSG(res, ERR_CANT_CREATE, "Map failed with error " + vformat("0x%08ux", res) + "."); + write_ptr = (uint8_t *)data_ptr; + write_ptr += alloc_offset; + } + + ERR_FAIL_COND_V(region_w % block_w, ERR_BUG); + ERR_FAIL_COND_V(region_pitch % block_w, ERR_BUG); + ERR_FAIL_COND_V(region_h % block_h, ERR_BUG); + + if (block_w != 1 || block_h != 1) { + // Compressed image (functions). + // Must copy a block region. + + uint32_t block_size = get_compressed_image_format_block_byte_size(p_texture->format); + // Re-create current variables in blocky format. + uint32_t xb = x / block_w; + uint32_t yb = y / block_h; + uint32_t wb = width / block_w; + // Uint32_t hb = height / block_h;. + uint32_t region_wb = region_w / block_w; + uint32_t region_hb = region_h / block_h; + _copy_region(read_ptr, write_ptr, xb, yb, region_wb, region_hb, wb, region_pitch, block_size); + } else { + // Regular image (pixels). + // Must copy a pixel region. + _copy_region(read_ptr, write_ptr, x, y, region_w, region_h, width, region_pitch, pixel_size); + } + + { // Unmap. + staging_buffer_blocks[staging_buffer_current].resource->Unmap(0, &VOID_RANGE); + } + + D3D12_PLACED_SUBRESOURCE_FOOTPRINT src_footprint = {}; + src_footprint.Offset = alloc_offset; + src_footprint.Footprint = CD3DX12_SUBRESOURCE_FOOTPRINT( + d3d12_formats[p_texture->format].family, + region_w, + region_h, + 1, + region_pitch); + CD3DX12_TEXTURE_COPY_LOCATION copy_src(staging_buffer_blocks[staging_buffer_current].resource, src_footprint); + + CD3DX12_BOX src_box(0, 0, region_w, region_h); + p_command_list->CopyTextureRegion(©_dst, x, y, z, ©_src, &src_box); + + staging_buffer_blocks.write[staging_buffer_current].fill_amount = alloc_offset + alloc_size; + } + } + } + + mipmap_offset = image_total; + logic_width = MAX(1u, logic_width >> 1); + logic_height = MAX(1u, logic_height >> 1); + } + + return OK; +} + +Vector<uint8_t> RenderingDeviceD3D12::_texture_get_data_from_image(Texture *tex, uint32_t p_layer, bool p_2d) { + uint32_t width, height, depth; + uint32_t image_size = get_image_format_required_size(tex->format, tex->width, tex->height, p_2d ? 1 : tex->depth, tex->mipmaps, &width, &height, &depth); + + Vector<uint8_t> image_data; + image_data.resize(image_size); + + D3D12_RESOURCE_DESC res_desc = tex->resource->GetDesc(); + + uint32_t blockw, blockh; + get_compressed_image_format_block_dimensions(tex->format, blockw, blockh); + uint32_t block_size = get_compressed_image_format_block_byte_size(tex->format); + uint32_t pixel_size = get_image_format_pixel_size(tex->format); + + { + uint8_t *w = image_data.ptrw(); + + uint32_t mipmap_offset = 0; + for (uint32_t mm_i = 0; mm_i < tex->mipmaps; mm_i++) { + uint32_t image_total = get_image_format_required_size(tex->format, tex->width, tex->height, p_2d ? 1 : tex->depth, mm_i + 1, &width, &height, &depth); + + uint8_t *write_ptr_mipmap = w + mipmap_offset; + image_size = image_total - mipmap_offset; + + UINT subresource = 0; + + uint64_t image_total_src = 0; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT layout = {}; + device->GetCopyableFootprints( + &res_desc, + subresource, + 1, + 0, + &layout, + nullptr, + nullptr, + &image_total_src); + + void *img_mem; + HRESULT res = tex->resource->Map(subresource, nullptr, &img_mem); + ERR_FAIL_COND_V_MSG(res, Vector<uint8_t>(), "Map failed with error " + vformat("0x%08ux", res) + "."); + + for (uint32_t z = 0; z < depth; z++) { + uint8_t *write_ptr = write_ptr_mipmap + z * image_size / depth; + const uint8_t *slice_read_ptr = ((uint8_t *)img_mem) + layout.Offset + z * image_total_src / depth; + + if (block_size > 1) { + // Compressed. + uint32_t line_width = (block_size * (width / blockw)); + for (uint32_t y = 0; y < height / blockh; y++) { + const uint8_t *rptr = slice_read_ptr + y * layout.Footprint.RowPitch; + uint8_t *wptr = write_ptr + y * line_width; + + memcpy(wptr, rptr, line_width); + } + + } else { + // Uncompressed. + for (uint32_t y = 0; y < height; y++) { + const uint8_t *rptr = slice_read_ptr + y * layout.Footprint.RowPitch; + uint8_t *wptr = write_ptr + y * pixel_size * width; + memcpy(wptr, rptr, (uint64_t)pixel_size * width); + } + } + } + + tex->resource->Unmap(subresource, nullptr); + + mipmap_offset = image_total; + } + } + + return image_data; +} + +Vector<uint8_t> RenderingDeviceD3D12::texture_get_data(RID p_texture, uint32_t p_layer) { + _THREAD_SAFE_METHOD_ + + Texture *tex = texture_owner.get_or_null(p_texture); + ERR_FAIL_NULL_V(tex, Vector<uint8_t>()); + + ERR_FAIL_COND_V_MSG(tex->bound, Vector<uint8_t>(), + "Texture can't be retrieved while a render pass that uses it is being created. Ensure render pass is finalized (and that it was created with RENDER_PASS_CONTENTS_FINISH) to unbind this texture."); + ERR_FAIL_COND_V_MSG(!(tex->usage_flags & TEXTURE_USAGE_CAN_COPY_FROM_BIT), Vector<uint8_t>(), + "Texture requires the TEXTURE_USAGE_CAN_COPY_FROM_BIT in order to be retrieved."); + + uint32_t layer_count = tex->layers; + if (tex->type == TEXTURE_TYPE_CUBE || tex->type == TEXTURE_TYPE_CUBE_ARRAY) { + layer_count *= 6; + } + ERR_FAIL_COND_V(p_layer >= layer_count, Vector<uint8_t>()); + + if (tex->usage_flags & TEXTURE_USAGE_CPU_READ_BIT) { + // Does not need anything fancy, map and read. + return _texture_get_data_from_image(tex, p_layer); + } else { + // Compute total image size. + uint32_t width, height, depth; + uint32_t final_buffer_size = get_image_format_required_size(tex->format, tex->width, tex->height, tex->depth, tex->mipmaps, &width, &height, &depth); + + uint32_t block_w, block_h; + get_compressed_image_format_block_dimensions(tex->format, block_w, block_h); + uint32_t alignment = D3D12_TEXTURE_DATA_PITCH_ALIGNMENT; + + // We'll use a potentially bigger buffer to account for mip sizes in which we need to use a bigger pitch to keep D3D12 happy. + uint32_t buffer_size = 0; + { + uint32_t computed_h = tex->height; + uint32_t computed_d = tex->depth; + + uint32_t prev_size = 0; + for (uint32_t i = 0; i < tex->mipmaps; i++) { + uint32_t image_size = get_image_format_required_size(tex->format, tex->width, tex->height, tex->depth, i + 1); + uint32_t inferred_row_pitch = image_size / (computed_h * computed_d) * block_h; + uint32_t adjusted_row_pitch = ALIGN(inferred_row_pitch, alignment); + uint32_t adjusted_image_size = adjusted_row_pitch / block_h * computed_h * tex->depth; + uint32_t size = adjusted_image_size - prev_size; + prev_size = image_size; + + buffer_size = ALIGN(buffer_size + size, D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT); + + computed_h = MAX(1u, computed_h >> 1); + computed_d = MAX(1u, computed_d >> 1); + } + } + + // Allocate buffer. + ID3D12GraphicsCommandList *command_list = frames[frame].draw_command_list.Get(); // Makes more sense to retrieve. + + Buffer tmp_buffer; + Error err = _buffer_allocate(&tmp_buffer, buffer_size, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_HEAP_TYPE_READBACK); + ERR_FAIL_COND_V(err != OK, Vector<uint8_t>()); + + for (uint32_t i = 0; i < tex->mipmaps; i++) { + uint32_t subresource = D3D12CalcSubresource(i, p_layer, 0, tex->owner_mipmaps, tex->owner_layers); + _resource_transition_batch(tex, subresource, tex->planes, D3D12_RESOURCE_STATE_COPY_SOURCE); + } + _resource_transitions_flush(command_list); + + uint32_t computed_w = tex->width; + uint32_t computed_h = tex->height; + uint32_t computed_d = tex->depth; + + uint32_t prev_size = 0; + uint32_t offset = 0; + for (uint32_t i = 0; i < tex->mipmaps; i++) { + uint32_t image_size = get_image_format_required_size(tex->format, tex->width, tex->height, tex->depth, i + 1); + uint32_t size = image_size - prev_size; + prev_size = image_size; + + D3D12_PLACED_SUBRESOURCE_FOOTPRINT dst_footprint = {}; + dst_footprint.Offset = offset; + dst_footprint.Footprint.Width = MAX(block_w, computed_w); + dst_footprint.Footprint.Height = MAX(block_h, computed_h); + dst_footprint.Footprint.Depth = computed_d; + uint32_t inferred_row_pitch = size / (dst_footprint.Footprint.Height * computed_d) * block_h; + dst_footprint.Footprint.RowPitch = inferred_row_pitch; + dst_footprint.Footprint.Format = d3d12_formats[tex->format].family; + CD3DX12_TEXTURE_COPY_LOCATION copy_dst(tmp_buffer.resource, dst_footprint); + + UINT src_subresource = D3D12CalcSubresource(i, p_layer, 0, tex->owner_mipmaps, tex->owner_layers); + CD3DX12_TEXTURE_COPY_LOCATION copy_src(tex->resource, src_subresource); + + if (dst_footprint.Footprint.RowPitch % alignment) { + // Dammit! Now we must copy with an imposed pitch and then adjust row by row. + copy_dst.PlacedFootprint.Offset = ALIGN(offset, D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT); + + uint32_t adjusted_row_pitch = ALIGN(inferred_row_pitch, alignment); + copy_dst.PlacedFootprint.Footprint.RowPitch = adjusted_row_pitch; + command_list->CopyTextureRegion(©_dst, 0, 0, 0, ©_src, nullptr); + _flush(true); + + void *buffer_mem; + uint32_t adjusted_size = adjusted_row_pitch / block_h * dst_footprint.Footprint.Height * computed_d; + CD3DX12_RANGE range(offset, copy_dst.PlacedFootprint.Offset + adjusted_size); + HRESULT res = tmp_buffer.resource->Map(0, &range, &buffer_mem); + ERR_FAIL_COND_V_MSG(res, Vector<uint8_t>(), "Map failed with error " + vformat("0x%08ux", res) + "."); + + for (uint32_t j = 0; j < dst_footprint.Footprint.Height / block_h * computed_d; j++) { + memmove((uint8_t *)buffer_mem + offset + j * inferred_row_pitch, (uint8_t *)buffer_mem + copy_dst.PlacedFootprint.Offset + j * adjusted_row_pitch, inferred_row_pitch); + } + + tmp_buffer.resource->Unmap(0, nullptr); + } else if (offset % D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT) { + // Row pitch is fine, but offset alignment is not good. + copy_dst.PlacedFootprint.Offset = ALIGN(offset, D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT); + + command_list->CopyTextureRegion(©_dst, 0, 0, 0, ©_src, nullptr); + _flush(true); + + void *buffer_mem; + CD3DX12_RANGE range(copy_dst.PlacedFootprint.Offset, size); + HRESULT res = tmp_buffer.resource->Map(0, &range, &buffer_mem); + ERR_FAIL_COND_V_MSG(res, Vector<uint8_t>(), "Map failed with error " + vformat("0x%08ux", res) + "."); + + memmove((uint8_t *)buffer_mem + offset, (uint8_t *)buffer_mem + copy_dst.PlacedFootprint.Offset, size); + + tmp_buffer.resource->Unmap(0, nullptr); + } else { + command_list->CopyTextureRegion(©_dst, 0, 0, 0, ©_src, nullptr); + } + + computed_w = MAX(1u, computed_w >> 1); + computed_h = MAX(1u, computed_h >> 1); + computed_d = MAX(1u, computed_d >> 1); + offset += size; + } + + _flush(true); + + void *buffer_mem; + CD3DX12_RANGE range(0, final_buffer_size); + HRESULT res = tmp_buffer.resource->Map(0, &range, &buffer_mem); + ERR_FAIL_COND_V_MSG(res, Vector<uint8_t>(), "Map failed with error " + vformat("0x%08ux", res) + "."); + + Vector<uint8_t> buffer_data; + buffer_data.resize(final_buffer_size); + { + uint8_t *w = buffer_data.ptrw(); + memcpy(w, buffer_mem, final_buffer_size); + } + + tmp_buffer.resource->Unmap(0, nullptr); + + _buffer_free(&tmp_buffer); + + return buffer_data; + } +} + +bool RenderingDeviceD3D12::texture_is_shared(RID p_texture) { + _THREAD_SAFE_METHOD_ + + Texture *tex = texture_owner.get_or_null(p_texture); + ERR_FAIL_NULL_V(tex, false); + return tex->owner.is_valid(); +} + +bool RenderingDeviceD3D12::texture_is_valid(RID p_texture) { + return texture_owner.owns(p_texture); +} + +RenderingDevice::TextureFormat RenderingDeviceD3D12::texture_get_format(RID p_texture) { + _THREAD_SAFE_METHOD_ + + Texture *tex = texture_owner.get_or_null(p_texture); + ERR_FAIL_NULL_V(tex, TextureFormat()); + + TextureFormat tf; + + tf.format = tex->format; + tf.width = tex->width; + tf.height = tex->height; + tf.depth = tex->depth; + tf.array_layers = tex->layers; + tf.mipmaps = tex->mipmaps; + tf.texture_type = tex->type; + tf.samples = tex->samples; + tf.usage_bits = tex->usage_flags; + tf.shareable_formats = tex->allowed_shared_formats; + tf.is_resolve_buffer = tex->is_resolve_buffer; + + return tf; +} + +Size2i RenderingDeviceD3D12::texture_size(RID p_texture) { + _THREAD_SAFE_METHOD_ + + Texture *tex = texture_owner.get_or_null(p_texture); + ERR_FAIL_NULL_V(tex, Size2i()); + return Size2i(tex->width, tex->height); +} + +uint64_t RenderingDeviceD3D12::texture_get_native_handle(RID p_texture) { + _THREAD_SAFE_METHOD_ + + Texture *tex = texture_owner.get_or_null(p_texture); + ERR_FAIL_NULL_V(tex, 0); + + return (uint64_t)tex->resource; +} + +Error RenderingDeviceD3D12::texture_copy(RID p_from_texture, RID p_to_texture, const Vector3 &p_from, const Vector3 &p_to, const Vector3 &p_size, uint32_t p_src_mipmap, uint32_t p_dst_mipmap, uint32_t p_src_layer, uint32_t p_dst_layer, BitField<BarrierMask> p_post_barrier) { + _THREAD_SAFE_METHOD_ + + Texture *src_tex = texture_owner.get_or_null(p_from_texture); + ERR_FAIL_NULL_V(src_tex, ERR_INVALID_PARAMETER); + + ERR_FAIL_COND_V_MSG(src_tex->bound, ERR_INVALID_PARAMETER, + "Source texture can't be copied while a render pass that uses it is being created. Ensure render pass is finalized (and that it was created with RENDER_PASS_CONTENTS_FINISH) to unbind this texture."); + ERR_FAIL_COND_V_MSG(!(src_tex->usage_flags & TEXTURE_USAGE_CAN_COPY_FROM_BIT), ERR_INVALID_PARAMETER, + "Source texture requires the TEXTURE_USAGE_CAN_COPY_FROM_BIT in order to be retrieved."); + + uint32_t src_layer_count = src_tex->layers; + uint32_t src_width, src_height, src_depth; + get_image_format_required_size(src_tex->format, src_tex->width, src_tex->height, src_tex->depth, p_src_mipmap + 1, &src_width, &src_height, &src_depth); + if (src_tex->type == TEXTURE_TYPE_CUBE || src_tex->type == TEXTURE_TYPE_CUBE_ARRAY) { + src_layer_count *= 6; + } + + ERR_FAIL_COND_V(p_from.x < 0 || p_from.x + p_size.x > src_width, ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(p_from.y < 0 || p_from.y + p_size.y > src_height, ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(p_from.z < 0 || p_from.z + p_size.z > src_depth, ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(p_src_mipmap >= src_tex->mipmaps, ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(p_src_layer >= src_layer_count, ERR_INVALID_PARAMETER); + + Texture *dst_tex = texture_owner.get_or_null(p_to_texture); + ERR_FAIL_NULL_V(dst_tex, ERR_INVALID_PARAMETER); + + ERR_FAIL_COND_V_MSG(dst_tex->bound, ERR_INVALID_PARAMETER, + "Destination texture can't be copied while a render pass that uses it is being created. Ensure render pass is finalized (and that it was created with RENDER_PASS_CONTENTS_FINISH) to unbind this texture."); + ERR_FAIL_COND_V_MSG(!(dst_tex->usage_flags & TEXTURE_USAGE_CAN_COPY_TO_BIT), ERR_INVALID_PARAMETER, + "Destination texture requires the TEXTURE_USAGE_CAN_COPY_TO_BIT in order to be retrieved."); + + uint32_t dst_layer_count = dst_tex->layers; + uint32_t dst_width, dst_height, dst_depth; + get_image_format_required_size(dst_tex->format, dst_tex->width, dst_tex->height, dst_tex->depth, p_dst_mipmap + 1, &dst_width, &dst_height, &dst_depth); + if (dst_tex->type == TEXTURE_TYPE_CUBE || dst_tex->type == TEXTURE_TYPE_CUBE_ARRAY) { + dst_layer_count *= 6; + } + + ERR_FAIL_COND_V(p_to.x < 0 || p_to.x + p_size.x > dst_width, ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(p_to.y < 0 || p_to.y + p_size.y > dst_height, ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(p_to.z < 0 || p_to.z + p_size.z > dst_depth, ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(p_dst_mipmap >= dst_tex->mipmaps, ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(p_dst_layer >= dst_layer_count, ERR_INVALID_PARAMETER); + + ERR_FAIL_COND_V_MSG((src_tex->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) != (dst_tex->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT), ERR_INVALID_PARAMETER, + "Source and destination texture must be of the same type (color or depth)."); + + ID3D12GraphicsCommandList *command_list = frames[frame].draw_command_list.Get(); + + uint32_t src_subresource = D3D12CalcSubresource(p_src_mipmap, p_src_layer, 0, src_tex->owner_mipmaps, src_tex->owner_layers); + _resource_transition_batch(src_tex, src_subresource, src_tex->planes, D3D12_RESOURCE_STATE_COPY_SOURCE); + + uint32_t dst_subresource = D3D12CalcSubresource(p_dst_mipmap, p_dst_layer, 0, dst_tex->owner_mipmaps, dst_tex->owner_layers); + _resource_transition_batch(dst_tex, dst_subresource, dst_tex->planes, D3D12_RESOURCE_STATE_COPY_DEST); + + _resource_transitions_flush(command_list); + + { + CD3DX12_TEXTURE_COPY_LOCATION src_location(src_tex->resource, src_subresource); + CD3DX12_BOX src_box(p_from.x, p_from.y, p_from.z, p_from.x + p_size.x, p_from.y + p_size.y, p_from.z + p_size.z); + CD3DX12_TEXTURE_COPY_LOCATION dst_location(dst_tex->resource, dst_subresource); + command_list->CopyTextureRegion( + &dst_location, + p_to.x, p_to.y, p_to.z, + &src_location, + &src_box); + } + + return OK; +} + +Error RenderingDeviceD3D12::texture_resolve_multisample(RID p_from_texture, RID p_to_texture, BitField<BarrierMask> p_post_barrier) { + _THREAD_SAFE_METHOD_ + + Texture *src_tex = texture_owner.get_or_null(p_from_texture); + ERR_FAIL_NULL_V(src_tex, ERR_INVALID_PARAMETER); + + ERR_FAIL_COND_V_MSG(src_tex->bound, ERR_INVALID_PARAMETER, + "Source texture can't be copied while a render pass that uses it is being created. Ensure render pass is finalized (and that it was created with RENDER_PASS_CONTENTS_FINISH) to unbind this texture."); + ERR_FAIL_COND_V_MSG(!(src_tex->usage_flags & TEXTURE_USAGE_CAN_COPY_FROM_BIT), ERR_INVALID_PARAMETER, + "Source texture requires the TEXTURE_USAGE_CAN_COPY_FROM_BIT in order to be retrieved."); + + ERR_FAIL_COND_V_MSG(src_tex->type != TEXTURE_TYPE_2D, ERR_INVALID_PARAMETER, "Source texture must be 2D (or a slice of a 3D/Cube texture)"); + ERR_FAIL_COND_V_MSG(src_tex->samples == TEXTURE_SAMPLES_1, ERR_INVALID_PARAMETER, "Source texture must be multisampled."); + + Texture *dst_tex = texture_owner.get_or_null(p_to_texture); + ERR_FAIL_NULL_V(dst_tex, ERR_INVALID_PARAMETER); + + ERR_FAIL_COND_V_MSG(dst_tex->bound, ERR_INVALID_PARAMETER, + "Destination texture can't be copied while a render pass that uses it is being created. Ensure render pass is finalized (and that it was created with RENDER_PASS_CONTENTS_FINISH) to unbind this texture."); + ERR_FAIL_COND_V_MSG(!(dst_tex->usage_flags & TEXTURE_USAGE_CAN_COPY_TO_BIT), ERR_INVALID_PARAMETER, + "Destination texture requires the TEXTURE_USAGE_CAN_COPY_TO_BIT in order to be retrieved."); + + ERR_FAIL_COND_V_MSG(dst_tex->type != TEXTURE_TYPE_2D, ERR_INVALID_PARAMETER, "Destination texture must be 2D (or a slice of a 3D/Cube texture)."); + ERR_FAIL_COND_V_MSG(dst_tex->samples != TEXTURE_SAMPLES_1, ERR_INVALID_PARAMETER, "Destination texture must not be multisampled."); + + ERR_FAIL_COND_V_MSG(src_tex->format != dst_tex->format, ERR_INVALID_PARAMETER, "Source and Destination textures must be the same format."); + ERR_FAIL_COND_V_MSG(src_tex->width != dst_tex->width && src_tex->height != dst_tex->height && src_tex->depth != dst_tex->depth, ERR_INVALID_PARAMETER, "Source and Destination textures must have the same dimensions."); + + ERR_FAIL_COND_V_MSG((src_tex->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) != (dst_tex->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT), ERR_INVALID_PARAMETER, + "Source and destination texture must be of the same type (color or depth)."); + + ID3D12GraphicsCommandList *command_list = frames[frame].draw_command_list.Get(); + + uint32_t src_subresource = D3D12CalcSubresource(src_tex->base_mipmap, src_tex->base_layer, 0, src_tex->owner_mipmaps, src_tex->owner_layers); + _resource_transition_batch(src_tex, src_subresource, src_tex->planes, D3D12_RESOURCE_STATE_RESOLVE_SOURCE); + + uint32_t dst_subresource = D3D12CalcSubresource(dst_tex->base_mipmap, dst_tex->base_layer, 0, dst_tex->owner_mipmaps, dst_tex->owner_layers); + _resource_transition_batch(dst_tex, dst_subresource, dst_tex->planes, D3D12_RESOURCE_STATE_RESOLVE_DEST); + + _resource_transitions_flush(command_list); + + command_list->ResolveSubresource(dst_tex->resource, dst_subresource, src_tex->resource, src_subresource, d3d12_formats[src_tex->format].general_format); + + return OK; +} + +Error RenderingDeviceD3D12::texture_clear(RID p_texture, const Color &p_color, uint32_t p_base_mipmap, uint32_t p_mipmaps, uint32_t p_base_layer, uint32_t p_layers, BitField<BarrierMask> p_post_barrier) { + _THREAD_SAFE_METHOD_ + + Texture *src_tex = texture_owner.get_or_null(p_texture); + ERR_FAIL_NULL_V(src_tex, ERR_INVALID_PARAMETER); + + ERR_FAIL_COND_V_MSG(src_tex->bound, ERR_INVALID_PARAMETER, + "Source texture can't be cleared while a render pass that uses it is being created. Ensure render pass is finalized (and that it was created with RENDER_PASS_CONTENTS_FINISH) to unbind this texture."); + + ERR_FAIL_COND_V(p_layers == 0, ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(p_mipmaps == 0, ERR_INVALID_PARAMETER); + + ERR_FAIL_COND_V_MSG(!(src_tex->usage_flags & TEXTURE_USAGE_CAN_COPY_TO_BIT), ERR_INVALID_PARAMETER, + "Source texture requires the TEXTURE_USAGE_CAN_COPY_TO_BIT in order to be cleared."); + + uint32_t src_layer_count = src_tex->layers; + if (src_tex->type == TEXTURE_TYPE_CUBE || src_tex->type == TEXTURE_TYPE_CUBE_ARRAY) { + src_layer_count *= 6; + } + + ERR_FAIL_COND_V(p_base_mipmap + p_mipmaps > src_tex->mipmaps, ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(p_base_layer + p_layers > src_layer_count, ERR_INVALID_PARAMETER); + + if ((src_tex->usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT)) { + // Clear via RTV. + + if (frames[frame].desc_heap_walkers.rtv.is_at_eof()) { + if (!frames[frame].desc_heaps_exhausted_reported.rtv) { + frames[frame].desc_heaps_exhausted_reported.rtv = true; + ERR_FAIL_V_MSG(ERR_BUSY, + "Cannot clear texture because there's no enough room in current frame's RENDER TARGET descriptors heap.\n" + "Please increase the value of the rendering/rendering_device/d3d12/max_misc_descriptors_per_frame project setting."); + } else { + return ERR_BUSY; + } + } + + D3D12_RENDER_TARGET_VIEW_DESC rtv_desc = _make_rtv_for_texture(src_tex, p_base_mipmap, p_base_layer, p_layers); + rtv_desc.Format = src_tex->owner_uav_desc.Format; + + ID3D12GraphicsCommandList *command_list = frames[frame].draw_command_list.Get(); + + for (uint32_t i = 0; i < p_layers; i++) { + for (uint32_t j = 0; j < p_mipmaps; j++) { + uint32_t subresource = D3D12CalcSubresource(src_tex->base_mipmap + p_base_mipmap + j, src_tex->base_layer + p_base_layer + i, 0, src_tex->owner_mipmaps, src_tex->owner_layers); + _resource_transition_batch(src_tex, subresource, src_tex->planes, D3D12_RESOURCE_STATE_RENDER_TARGET, src_tex->owner_resource); + } + } + _resource_transitions_flush(command_list); + + device->CreateRenderTargetView( + src_tex->owner_resource, + &rtv_desc, + frames[frame].desc_heap_walkers.rtv.get_curr_cpu_handle()); + command_list->ClearRenderTargetView( + frames[frame].desc_heap_walkers.rtv.get_curr_cpu_handle(), + p_color.components, + 0, + nullptr); + frames[frame].desc_heap_walkers.rtv.advance(); + } else { + // Clear via UAV. + + if (frames[frame].desc_heap_walkers.resources.is_at_eof()) { + if (!frames[frame].desc_heaps_exhausted_reported.resources) { + frames[frame].desc_heaps_exhausted_reported.resources = true; + ERR_FAIL_V_MSG(ERR_BUSY, + "Cannot clear texture because there's no enough room in current frame's RESOURCE descriptors heap.\n" + "Please increase the value of the rendering/rendering_device/d3d12/max_resource_descriptors_per_frame project setting."); + } else { + return ERR_BUSY; + } + } + if (frames[frame].desc_heap_walkers.aux.is_at_eof()) { + if (!frames[frame].desc_heaps_exhausted_reported.aux) { + frames[frame].desc_heaps_exhausted_reported.aux = true; + ERR_FAIL_V_MSG(ERR_BUSY, + "Cannot clear texture because there's no enough room in current frame's AUX descriptors heap.\n" + "Please increase the value of the rendering/rendering_device/d3d12/max_misc_descriptors_per_frame project setting."); + } else { + return ERR_BUSY; + } + } + + ID3D12GraphicsCommandList *command_list = frames[frame].draw_command_list.Get(); + + for (uint32_t i = 0; i < p_layers; i++) { + for (uint32_t j = 0; j < p_mipmaps; j++) { + uint32_t subresource = D3D12CalcSubresource(src_tex->base_mipmap + p_base_mipmap + j, src_tex->base_layer + p_base_layer + i, 0, src_tex->owner_mipmaps, src_tex->owner_layers); + _resource_transition_batch(src_tex, subresource, src_tex->planes, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, src_tex->owner_resource); + } + } + _resource_transitions_flush(command_list); + + device->CreateUnorderedAccessView( + src_tex->owner_resource, + nullptr, + &src_tex->owner_uav_desc, + frames[frame].desc_heap_walkers.aux.get_curr_cpu_handle()); + + device->CopyDescriptorsSimple( + 1, + frames[frame].desc_heap_walkers.resources.get_curr_cpu_handle(), + frames[frame].desc_heap_walkers.aux.get_curr_cpu_handle(), + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + + UINT values[4] = { + (UINT)p_color.get_r8(), + (UINT)p_color.get_g8(), + (UINT)p_color.get_b8(), + (UINT)p_color.get_a8(), + }; + command_list->ClearUnorderedAccessViewUint( + frames[frame].desc_heap_walkers.resources.get_curr_gpu_handle(), + frames[frame].desc_heap_walkers.aux.get_curr_cpu_handle(), + src_tex->owner_resource, + values, + 0, + nullptr); + + frames[frame].desc_heap_walkers.resources.advance(); + frames[frame].desc_heap_walkers.aux.advance(); + } + + return OK; +} + +bool RenderingDeviceD3D12::texture_is_format_supported_for_usage(DataFormat p_format, BitField<RenderingDevice::TextureUsageBits> p_usage) const { + ERR_FAIL_INDEX_V(p_format, DATA_FORMAT_MAX, false); + + _THREAD_SAFE_METHOD_ + + D3D12_FEATURE_DATA_FORMAT_SUPPORT srv_rtv_support = {}; + srv_rtv_support.Format = d3d12_formats[p_format].general_format; + HRESULT res = device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &srv_rtv_support, sizeof(srv_rtv_support)); + ERR_FAIL_COND_V_MSG(res, false, "CheckFeatureSupport failed with error " + vformat("0x%08ux", res) + "."); + + D3D12_FEATURE_DATA_FORMAT_SUPPORT &uav_support = srv_rtv_support; // Fine for now. + + D3D12_FEATURE_DATA_FORMAT_SUPPORT dsv_support = {}; + dsv_support.Format = d3d12_formats[p_format].dsv_format; + res = device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &dsv_support, sizeof(dsv_support)); + ERR_FAIL_COND_V_MSG(res, false, "CheckFeatureSupport failed with error " + vformat("0x%08ux", res) + "."); + + if ((p_usage & TEXTURE_USAGE_SAMPLING_BIT) && !(srv_rtv_support.Support1 & (D3D12_FORMAT_SUPPORT1_SHADER_LOAD | D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE)) && d3d12_formats[p_format].general_format != DXGI_FORMAT_UNKNOWN) { + return false; + } + + if ((p_usage & TEXTURE_USAGE_SAMPLING_BIT) && d3d12_formats[p_format].general_format == DXGI_FORMAT_UNKNOWN) { + return false; + } + + if ((p_usage & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) && !(srv_rtv_support.Support1 & D3D12_FORMAT_SUPPORT1_RENDER_TARGET)) { + return false; + } + + if ((p_usage & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) && !(dsv_support.Support1 & D3D12_FORMAT_SUPPORT1_DEPTH_STENCIL)) { + printf("dxgiformat: %x\n", d3d12_formats[p_format].dsv_format); + return false; + } + + if ((p_usage & TEXTURE_USAGE_STORAGE_BIT) && !(uav_support.Support1 & D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW)) { // Maybe check LOAD/STORE, too? + return false; + } + + if ((p_usage & TEXTURE_USAGE_STORAGE_ATOMIC_BIT) && !(uav_support.Support2 & D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_ADD)) { // Check a basic atomic at least. + return false; + } + + if ((p_usage & TEXTURE_USAGE_VRS_ATTACHMENT_BIT) && d3d12_formats[p_format].general_format != DXGI_FORMAT_R8_UINT) { + return false; + } + + return true; +} + +/********************/ +/**** ATTACHMENT ****/ +/********************/ + +bool RenderingDeviceD3D12::_framebuffer_format_preprocess(FramebufferFormat *p_fb_format, uint32_t p_view_count) { + const Vector<AttachmentFormat> &attachments = p_fb_format->attachments; + + LocalVector<int32_t> attachment_last_pass; + attachment_last_pass.resize(attachments.size()); + + if (p_view_count > 1) { + const D3D12Context::MultiviewCapabilities &capabilities = context->get_multiview_capabilities(); + + // This only works with multiview! + ERR_FAIL_COND_V_MSG(!capabilities.is_supported, false, "Multiview not supported"); + + // Make sure we limit this to the number of views we support. + ERR_FAIL_COND_V_MSG(p_view_count > capabilities.max_view_count, false, "Hardware does not support requested number of views for Multiview render pass"); + } + + int attachment_count = 0; + HashSet<DXGI_FORMAT> ms_attachment_formats; + for (int i = 0; i < attachments.size(); i++) { + if (attachments[i].usage_flags == AttachmentFormat::UNUSED_ATTACHMENT) { + continue; + } + + ERR_FAIL_INDEX_V(attachments[i].format, DATA_FORMAT_MAX, false); + ERR_FAIL_INDEX_V(attachments[i].samples, TEXTURE_SAMPLES_MAX, false); + ERR_FAIL_COND_V_MSG(!(attachments[i].usage_flags & (TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | TEXTURE_USAGE_INPUT_ATTACHMENT_BIT | TEXTURE_USAGE_VRS_ATTACHMENT_BIT)), + ERR_INVALID_PARAMETER, "Texture format for index (" + itos(i) + ") requires an attachment (color, depth-stencil, input or VRS) bit set."); + + attachment_last_pass[i] = -1; + attachment_count++; + + if (attachments[i].samples != TEXTURE_SAMPLES_1) { + if ((attachments[i].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT)) { + ms_attachment_formats.insert(d3d12_formats[attachments[i].format].general_format); + } else if ((attachments[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) { + ms_attachment_formats.insert(d3d12_formats[attachments[i].format].dsv_format); + } + } + } + + Vector<FramebufferPass> &passes = p_fb_format->passes; + for (int i = 0; i < passes.size(); i++) { + FramebufferPass *pass = &passes.write[i]; + + TextureSamples texture_samples = TEXTURE_SAMPLES_1; + bool is_multisample_first = true; + + ERR_FAIL_COND_V(pass->color_attachments.size() > D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT, false); + for (int j = 0; j < pass->color_attachments.size(); j++) { + int32_t attachment = pass->color_attachments[j]; + if (attachment != FramebufferPass::ATTACHMENT_UNUSED) { + ERR_FAIL_INDEX_V_MSG(attachment, attachments.size(), false, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), color attachment (" + itos(j) + ")."); + ERR_FAIL_COND_V_MSG(!(attachments[attachment].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT), false, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it's marked as depth, but it's not usable as color attachment."); + ERR_FAIL_COND_V_MSG(attachment_last_pass[attachment] == i, false, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it already was used for something else before in this pass."); + + if (is_multisample_first) { + texture_samples = attachments[attachment].samples; + is_multisample_first = false; + } else { + ERR_FAIL_COND_V_MSG(texture_samples != attachments[attachment].samples, false, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), if an attachment is marked as multisample, all of them should be multisample and use the same number of samples."); + } + attachment_last_pass[attachment] = i; + } + } + + for (int j = 0; j < pass->input_attachments.size(); j++) { + int32_t attachment = pass->input_attachments[j]; + if (attachment != FramebufferPass::ATTACHMENT_UNUSED) { + ERR_FAIL_INDEX_V_MSG(attachment, attachments.size(), false, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), input attachment (" + itos(j) + ")."); + ERR_FAIL_COND_V_MSG(!(attachments[attachment].usage_flags & TEXTURE_USAGE_INPUT_ATTACHMENT_BIT), false, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it isn't marked as an input texture."); + ERR_FAIL_COND_V_MSG(attachment_last_pass[attachment] == i, false, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it already was used for something else before in this pass."); + + if ((attachments[attachment].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) { + ERR_FAIL_V_MSG(false, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), the D3D12 driver doesn't yet support using depth-stencil targets as input attachments."); + } + + attachment_last_pass[attachment] = i; + } + } + + if (pass->resolve_attachments.size() > 0) { + ERR_FAIL_COND_V_MSG(pass->resolve_attachments.size() != pass->color_attachments.size(), false, "The amount of resolve attachments (" + itos(pass->resolve_attachments.size()) + ") must match the number of color attachments (" + itos(pass->color_attachments.size()) + ")."); + ERR_FAIL_COND_V_MSG(texture_samples == TEXTURE_SAMPLES_1, false, "Resolve attachments specified, but color attachments are not multisample."); + } + for (int j = 0; j < pass->resolve_attachments.size(); j++) { + int32_t attachment = pass->resolve_attachments[j]; + if (attachment != FramebufferPass::ATTACHMENT_UNUSED) { + ERR_FAIL_INDEX_V_MSG(attachment, attachments.size(), false, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), resolve attachment (" + itos(j) + ")."); + ERR_FAIL_COND_V_MSG(pass->color_attachments[j] == FramebufferPass::ATTACHMENT_UNUSED, false, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), resolve attachment (" + itos(j) + "), the respective color attachment is marked as unused."); + ERR_FAIL_COND_V_MSG(!(attachments[attachment].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT), false, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), resolve attachment, it isn't marked as a color texture."); + ERR_FAIL_COND_V_MSG(attachment_last_pass[attachment] == i, false, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it already was used for something else before in this pass."); + bool multisample = attachments[attachment].samples > TEXTURE_SAMPLES_1; + ERR_FAIL_COND_V_MSG(multisample, false, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), resolve attachments can't be multisample."); + attachment_last_pass[attachment] = i; + } + } + + if (pass->depth_attachment != FramebufferPass::ATTACHMENT_UNUSED) { + int32_t attachment = pass->depth_attachment; + ERR_FAIL_INDEX_V_MSG(attachment, attachments.size(), false, "Invalid framebuffer depth format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), depth attachment."); + ERR_FAIL_COND_V_MSG(!(attachments[attachment].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT), false, "Invalid framebuffer depth format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it's marked as depth, but it's not a depth attachment."); + ERR_FAIL_COND_V_MSG(attachment_last_pass[attachment] == i, false, "Invalid framebuffer depth format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it already was used for something else before in this pass."); + attachment_last_pass[attachment] = i; + + if (is_multisample_first) { + texture_samples = attachments[attachment].samples; + is_multisample_first = false; + } else { + ERR_FAIL_COND_V_MSG(texture_samples != attachments[attachment].samples, false, "Invalid framebuffer depth format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), if an attachment is marked as multisample, all of them should be multisample and use the same number of samples including the depth."); + } + } + + if (context->get_vrs_capabilities().ss_image_supported && pass->vrs_attachment != FramebufferPass::ATTACHMENT_UNUSED) { + int32_t attachment = pass->vrs_attachment; + ERR_FAIL_INDEX_V_MSG(attachment, attachments.size(), false, "Invalid framebuffer VRS format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), VRS attachment."); + ERR_FAIL_COND_V_MSG(!(attachments[attachment].usage_flags & TEXTURE_USAGE_VRS_ATTACHMENT_BIT), false, "Invalid framebuffer VRS format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it's marked as VRS, but it's not a VRS attachment."); + ERR_FAIL_COND_V_MSG(attachment_last_pass[attachment] == i, false, "Invalid framebuffer VRS attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it already was used for something else before in this pass."); + attachment_last_pass[attachment] = i; + } + + for (int j = 0; j < pass->preserve_attachments.size(); j++) { + int32_t attachment = pass->preserve_attachments[j]; + + ERR_FAIL_COND_V_MSG(attachment == FramebufferPass::ATTACHMENT_UNUSED, false, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), preserve attachment (" + itos(j) + "). Preserve attachments can't be unused."); + + ERR_FAIL_INDEX_V_MSG(attachment, attachments.size(), false, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), preserve attachment (" + itos(j) + ")."); + + if (attachment_last_pass[attachment] != i) { + // Preserve can still be used to keep depth or color from being discarded after use. + attachment_last_pass[attachment] = i; + } + } + + p_fb_format->pass_samples.push_back(texture_samples); + } + + if (p_fb_format->view_count > 1) { + const D3D12Context::MultiviewCapabilities capabilities = context->get_multiview_capabilities(); + + // For now this only works with multiview! + ERR_FAIL_COND_V_MSG(!capabilities.is_supported, ERR_UNAVAILABLE, "Multiview not supported"); + + // Make sure we limit this to the number of views we support. + ERR_FAIL_COND_V_MSG(p_fb_format->view_count > capabilities.max_view_count, ERR_UNAVAILABLE, "Hardware does not support requested number of views for Multiview render pass"); + } + + if (!ms_attachment_formats.is_empty()) { + LocalVector<DXGI_FORMAT> formats; + for (DXGI_FORMAT f : ms_attachment_formats) { + formats.push_back(f); + } + p_fb_format->max_supported_sample_count = _find_max_common_supported_sample_count(formats.ptr(), formats.size()); + } + + return true; +} + +uint32_t RenderingDeviceD3D12::_find_max_common_supported_sample_count(const DXGI_FORMAT *p_formats, uint32_t p_num_formats) { + uint32_t common = UINT32_MAX; + + for (uint32_t i = 0; i < p_num_formats; i++) { + if (format_sample_counts_mask_cache.has(p_formats[i])) { + common &= format_sample_counts_mask_cache[p_formats[i]]; + } else { + D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS msql = {}; + msql.Format = p_formats[i]; + uint32_t mask = 0; + for (int samples = 1 << (TEXTURE_SAMPLES_MAX - 1); samples >= 1; samples /= 2) { + msql.SampleCount = (UINT)samples; + HRESULT res = device->CheckFeatureSupport(D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, &msql, sizeof(msql)); + if (SUCCEEDED(res) && msql.NumQualityLevels) { + int bit = get_shift_from_power_of_2(samples); + ERR_FAIL_COND_V(bit == -1, 1); + mask |= (uint32_t)(1 << bit); + } + } + format_sample_counts_mask_cache.insert(p_formats[i], mask); + common &= mask; + } + } + if (common == UINT32_MAX) { + return 1; + } else { + return (uint32_t)1 << nearest_shift(common); + } +} + +RenderingDevice::FramebufferFormatID RenderingDeviceD3D12::framebuffer_format_create(const Vector<AttachmentFormat> &p_format, uint32_t p_view_count) { + FramebufferPass pass; + for (int i = 0; i < p_format.size(); i++) { + if (p_format[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) { + pass.depth_attachment = i; + } else { + pass.color_attachments.push_back(i); + } + } + + Vector<FramebufferPass> passes; + passes.push_back(pass); + return framebuffer_format_create_multipass(p_format, passes, p_view_count); +} + +RenderingDevice::FramebufferFormatID RenderingDeviceD3D12::framebuffer_format_create_multipass(const Vector<AttachmentFormat> &p_attachments, const Vector<FramebufferPass> &p_passes, uint32_t p_view_count) { + _THREAD_SAFE_METHOD_ + + FramebufferFormat fb_format; + fb_format.attachments = p_attachments; + fb_format.passes = p_passes; + fb_format.view_count = p_view_count; + if (!_framebuffer_format_preprocess(&fb_format, p_view_count)) { + return INVALID_ID; + } + + FramebufferFormatID id = FramebufferFormatID(framebuffer_formats.size()) | (FramebufferFormatID(ID_TYPE_FRAMEBUFFER_FORMAT) << FramebufferFormatID(ID_BASE_SHIFT)); + framebuffer_formats[id] = fb_format; + return id; +} + +RenderingDevice::FramebufferFormatID RenderingDeviceD3D12::framebuffer_format_create_empty(TextureSamples p_samples) { + _THREAD_SAFE_METHOD_ + + FramebufferFormat fb_format; + fb_format.passes.push_back(FramebufferPass()); + fb_format.pass_samples.push_back(p_samples); + + FramebufferFormatID id = FramebufferFormatID(framebuffer_formats.size()) | (FramebufferFormatID(ID_TYPE_FRAMEBUFFER_FORMAT) << FramebufferFormatID(ID_BASE_SHIFT)); + framebuffer_formats[id] = fb_format; + return id; +} + +RenderingDevice::TextureSamples RenderingDeviceD3D12::framebuffer_format_get_texture_samples(FramebufferFormatID p_format, uint32_t p_pass) { + HashMap<FramebufferFormatID, FramebufferFormat>::Iterator E = framebuffer_formats.find(p_format); + ERR_FAIL_NULL_V(E, TEXTURE_SAMPLES_1); + ERR_FAIL_COND_V(p_pass >= uint32_t(E->value.pass_samples.size()), TEXTURE_SAMPLES_1); + + return E->value.pass_samples[p_pass]; +} + +/***********************/ +/**** RENDER TARGET ****/ +/***********************/ + +RID RenderingDeviceD3D12::framebuffer_create_empty(const Size2i &p_size, TextureSamples p_samples, FramebufferFormatID p_format_check) { + _THREAD_SAFE_METHOD_ + Framebuffer framebuffer; + framebuffer.format_id = framebuffer_format_create_empty(p_samples); + ERR_FAIL_COND_V(p_format_check != INVALID_FORMAT_ID && framebuffer.format_id != p_format_check, RID()); + framebuffer.size = p_size; + + return framebuffer_owner.make_rid(framebuffer); +} + +RID RenderingDeviceD3D12::framebuffer_create(const Vector<RID> &p_texture_attachments, FramebufferFormatID p_format_check, uint32_t p_view_count) { + _THREAD_SAFE_METHOD_ + + FramebufferPass pass; + + for (int i = 0; i < p_texture_attachments.size(); i++) { + Texture *texture = texture_owner.get_or_null(p_texture_attachments[i]); + + ERR_FAIL_COND_V_MSG(texture && texture->layers != p_view_count, RID(), "Layers of our texture doesn't match view count for this framebuffer"); + + if (texture && texture->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) { + pass.depth_attachment = i; + } else if (texture && texture->usage_flags & TEXTURE_USAGE_VRS_ATTACHMENT_BIT) { + pass.vrs_attachment = i; + } else { + if (texture && texture->is_resolve_buffer) { + pass.resolve_attachments.push_back(i); + } else { + pass.color_attachments.push_back(texture ? i : FramebufferPass::ATTACHMENT_UNUSED); + } + } + } + + Vector<FramebufferPass> passes; + passes.push_back(pass); + + return framebuffer_create_multipass(p_texture_attachments, passes, p_format_check, p_view_count); +} + +D3D12_RENDER_TARGET_VIEW_DESC RenderingDeviceD3D12::_make_rtv_for_texture(const RenderingDeviceD3D12::Texture *p_texture, uint32_t p_mipmap_offset, uint32_t p_layer_offset, uint32_t p_layers) { + D3D12_RENDER_TARGET_VIEW_DESC rtv_desc = {}; + rtv_desc.Format = p_texture->srv_desc.Format; + + switch (p_texture->srv_desc.ViewDimension) { + case D3D12_SRV_DIMENSION_TEXTURE1D: { + rtv_desc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE1D; + rtv_desc.Texture1D.MipSlice = p_texture->srv_desc.Texture1D.MostDetailedMip + p_mipmap_offset; + } break; + case D3D12_SRV_DIMENSION_TEXTURE1DARRAY: { + rtv_desc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE1DARRAY; + rtv_desc.Texture1DArray.MipSlice = p_texture->srv_desc.Texture1DArray.MostDetailedMip + p_mipmap_offset; + rtv_desc.Texture1DArray.FirstArraySlice = p_texture->srv_desc.Texture1DArray.FirstArraySlice + p_layer_offset; + rtv_desc.Texture1DArray.ArraySize = p_layers == UINT32_MAX ? p_texture->srv_desc.Texture1DArray.ArraySize : p_layers; + } break; + case D3D12_SRV_DIMENSION_TEXTURE2D: { + rtv_desc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D; + rtv_desc.Texture2D.MipSlice = p_texture->srv_desc.Texture2D.MostDetailedMip + p_mipmap_offset; + rtv_desc.Texture2D.PlaneSlice = p_texture->srv_desc.Texture2D.PlaneSlice; + } break; + case D3D12_SRV_DIMENSION_TEXTURE2DARRAY: { + rtv_desc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DARRAY; + rtv_desc.Texture2DArray.MipSlice = p_texture->srv_desc.Texture2DArray.MostDetailedMip + p_mipmap_offset; + rtv_desc.Texture2DArray.FirstArraySlice = p_texture->srv_desc.Texture2DArray.FirstArraySlice + p_layer_offset; + rtv_desc.Texture2DArray.ArraySize = p_layers == UINT32_MAX ? p_texture->srv_desc.Texture2DArray.ArraySize : p_layers; + rtv_desc.Texture2DArray.PlaneSlice = p_texture->srv_desc.Texture2DArray.PlaneSlice; + } break; + case D3D12_SRV_DIMENSION_TEXTURE2DMS: { + rtv_desc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DMS; + } break; + case D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY: { + rtv_desc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY; + rtv_desc.Texture2DMSArray.FirstArraySlice = p_texture->srv_desc.Texture2DMSArray.FirstArraySlice + p_layer_offset; + rtv_desc.Texture2DMSArray.ArraySize = p_layers == UINT32_MAX ? p_texture->srv_desc.Texture2DMSArray.ArraySize : p_layers; + } break; + case D3D12_SRV_DIMENSION_TEXTURE3D: { + rtv_desc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE3D; + rtv_desc.Texture3D.MipSlice = p_texture->srv_desc.Texture3D.MostDetailedMip + p_mipmap_offset; + rtv_desc.Texture3D.FirstWSlice = 0; + rtv_desc.Texture3D.WSize = p_texture->depth; + } break; + default: { + ERR_FAIL_V_MSG(D3D12_RENDER_TARGET_VIEW_DESC(), "Can't create an RTV from an SRV whose view dimension is " + itos(p_texture->srv_desc.ViewDimension) + "."); + } + } + + return rtv_desc; +} + +D3D12_DEPTH_STENCIL_VIEW_DESC RenderingDeviceD3D12::_make_dsv_for_texture(const RenderingDeviceD3D12::Texture *p_texture) { + D3D12_DEPTH_STENCIL_VIEW_DESC dsv_desc = {}; + dsv_desc.Format = d3d12_formats[p_texture->format].dsv_format; + dsv_desc.Flags = D3D12_DSV_FLAG_NONE; + + switch (p_texture->srv_desc.ViewDimension) { + case D3D12_SRV_DIMENSION_TEXTURE1D: { + dsv_desc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE1D; + dsv_desc.Texture1D.MipSlice = p_texture->srv_desc.Texture1D.MostDetailedMip; + } break; + case D3D12_SRV_DIMENSION_TEXTURE1DARRAY: { + dsv_desc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE1DARRAY; + dsv_desc.Texture1DArray.MipSlice = p_texture->srv_desc.Texture1DArray.MostDetailedMip; + dsv_desc.Texture1DArray.FirstArraySlice = p_texture->srv_desc.Texture1DArray.FirstArraySlice; + dsv_desc.Texture1DArray.ArraySize = p_texture->srv_desc.Texture1DArray.ArraySize; + } break; + case D3D12_SRV_DIMENSION_TEXTURE2D: { + dsv_desc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D; + dsv_desc.Texture2D.MipSlice = p_texture->srv_desc.Texture2D.MostDetailedMip; + } break; + case D3D12_SRV_DIMENSION_TEXTURE2DARRAY: { + dsv_desc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DARRAY; + dsv_desc.Texture2DArray.MipSlice = p_texture->srv_desc.Texture2DArray.MostDetailedMip; + dsv_desc.Texture2DArray.FirstArraySlice = p_texture->srv_desc.Texture2DArray.FirstArraySlice; + dsv_desc.Texture2DArray.ArraySize = p_texture->srv_desc.Texture2DArray.ArraySize; + } break; + case D3D12_SRV_DIMENSION_TEXTURE2DMS: { + dsv_desc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DMS; + dsv_desc.Texture2DMS.UnusedField_NothingToDefine = p_texture->srv_desc.Texture2DMS.UnusedField_NothingToDefine; + } break; + case D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY: { + dsv_desc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DMSARRAY; + dsv_desc.Texture2DMSArray.FirstArraySlice = p_texture->srv_desc.Texture2DMSArray.FirstArraySlice; + dsv_desc.Texture2DMSArray.ArraySize = p_texture->srv_desc.Texture2DMSArray.ArraySize; + } break; + default: { + ERR_FAIL_V_MSG(D3D12_DEPTH_STENCIL_VIEW_DESC(), "Can't create an RTV from an SRV whose view dimension is " + itos(p_texture->srv_desc.ViewDimension) + "."); + } + } + + return dsv_desc; +} + +RID RenderingDeviceD3D12::framebuffer_create_multipass(const Vector<RID> &p_texture_attachments, const Vector<FramebufferPass> &p_passes, FramebufferFormatID p_format_check, uint32_t p_view_count) { + _THREAD_SAFE_METHOD_ + + Vector<AttachmentFormat> attachments; + attachments.resize(p_texture_attachments.size()); + Vector<uint32_t> attachments_handle_inds; + attachments_handle_inds.resize(p_texture_attachments.size()); + Size2i size; + bool size_set = false; + int num_color = 0; + int num_depth = 0; + for (int i = 0; i < p_texture_attachments.size(); i++) { + AttachmentFormat af; + Texture *texture = texture_owner.get_or_null(p_texture_attachments[i]); + if (!texture) { + af.usage_flags = AttachmentFormat::UNUSED_ATTACHMENT; + attachments_handle_inds.write[i] = UINT32_MAX; + } else { + ERR_FAIL_COND_V_MSG(texture->layers != p_view_count, RID(), "Layers of our texture doesn't match view count for this framebuffer"); + + if (!size_set) { + size.width = texture->width; + size.height = texture->height; + size_set = true; + } else if (texture->usage_flags & TEXTURE_USAGE_VRS_ATTACHMENT_BIT) { + // If this is not the first attachment we assume this is used as the VRS attachment. + // In this case this texture will be 1/16th the size of the color attachment. + // So we skip the size check. + } else { + ERR_FAIL_COND_V_MSG((uint32_t)size.width != texture->width || (uint32_t)size.height != texture->height, RID(), + "All textures in a framebuffer should be the same size."); + } + + af.format = texture->format; + af.samples = texture->samples; + af.usage_flags = texture->usage_flags; + + bool is_vrs = texture->usage_flags & TEXTURE_USAGE_VRS_ATTACHMENT_BIT && i == p_passes[0].vrs_attachment; + if (is_vrs) { + } else if ((texture->usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT)) { + attachments_handle_inds.write[i] = num_color; + num_color++; + } else if ((texture->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) { + attachments_handle_inds.write[i] = num_depth; + num_depth++; + } else { + attachments_handle_inds.write[i] = UINT32_MAX; + } + } + attachments.write[i] = af; + } + + ERR_FAIL_COND_V_MSG(!size_set, RID(), "All attachments unused."); + + FramebufferFormatID format_id = framebuffer_format_create_multipass(attachments, p_passes, p_view_count); + if (format_id == INVALID_ID) { + return RID(); + } + + ERR_FAIL_COND_V_MSG(p_format_check != INVALID_ID && format_id != p_format_check, RID(), + "The format used to check this framebuffer differs from the intended framebuffer format."); + + Framebuffer framebuffer; + framebuffer.format_id = format_id; + framebuffer.texture_ids = p_texture_attachments; + framebuffer.attachments_handle_inds = attachments_handle_inds; + framebuffer.size = size; + framebuffer.view_count = p_view_count; + + { + if (num_color) { + Error err = framebuffer.rtv_heap.allocate(device.Get(), D3D12_DESCRIPTOR_HEAP_TYPE_RTV, num_color, false); + ERR_FAIL_COND_V(err, RID()); + } + DescriptorsHeap::Walker rtv_heap_walker = framebuffer.rtv_heap.make_walker(); + + if (num_depth) { + Error err = framebuffer.dsv_heap.allocate(device.Get(), D3D12_DESCRIPTOR_HEAP_TYPE_DSV, num_depth, false); + ERR_FAIL_COND_V(err, RID()); + } + DescriptorsHeap::Walker dsv_heap_walker = framebuffer.dsv_heap.make_walker(); + + for (int i = 0; i < p_texture_attachments.size(); i++) { + Texture *texture = texture_owner.get_or_null(p_texture_attachments[i]); + if (!texture) { + continue; + } + + bool is_vrs = texture->usage_flags & TEXTURE_USAGE_VRS_ATTACHMENT_BIT && i == p_passes[0].vrs_attachment; + if (is_vrs) { + } else if ((texture->usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT)) { + D3D12_RENDER_TARGET_VIEW_DESC rtv_desc = _make_rtv_for_texture(texture); + device->CreateRenderTargetView(texture->resource, &rtv_desc, rtv_heap_walker.get_curr_cpu_handle()); + rtv_heap_walker.advance(); + } else if ((texture->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) { + D3D12_DEPTH_STENCIL_VIEW_DESC dsv_desc = _make_dsv_for_texture(texture); + device->CreateDepthStencilView(texture->resource, &dsv_desc, dsv_heap_walker.get_curr_cpu_handle()); + dsv_heap_walker.advance(); + } + } + + DEV_ASSERT(rtv_heap_walker.is_at_eof()); + DEV_ASSERT(dsv_heap_walker.is_at_eof()); + } + + RID id = framebuffer_owner.make_rid(framebuffer); + + for (int i = 0; i < p_texture_attachments.size(); i++) { + if (p_texture_attachments[i].is_valid()) { + _add_dependency(id, p_texture_attachments[i]); + } + } + + return id; +} + +RenderingDevice::FramebufferFormatID RenderingDeviceD3D12::framebuffer_get_format(RID p_framebuffer) { + _THREAD_SAFE_METHOD_ + + Framebuffer *framebuffer = framebuffer_owner.get_or_null(p_framebuffer); + ERR_FAIL_NULL_V(framebuffer, INVALID_ID); + + return framebuffer->format_id; +} + +bool RenderingDeviceD3D12::framebuffer_is_valid(RID p_framebuffer) const { + _THREAD_SAFE_METHOD_ + + return framebuffer_owner.owns(p_framebuffer); +} + +void RenderingDeviceD3D12::framebuffer_set_invalidation_callback(RID p_framebuffer, InvalidationCallback p_callback, void *p_userdata) { + _THREAD_SAFE_METHOD_ + + Framebuffer *framebuffer = framebuffer_owner.get_or_null(p_framebuffer); + ERR_FAIL_NULL(framebuffer); + + framebuffer->invalidated_callback = p_callback; + framebuffer->invalidated_callback_userdata = p_userdata; +} + +/*****************/ +/**** SAMPLER ****/ +/*****************/ + +RID RenderingDeviceD3D12::sampler_create(const SamplerState &p_state) { + _THREAD_SAFE_METHOD_ + + D3D12_SAMPLER_DESC sampler_desc = {}; + + if (p_state.use_anisotropy) { + sampler_desc.Filter = D3D12_ENCODE_ANISOTROPIC_FILTER(D3D12_FILTER_REDUCTION_TYPE_STANDARD); + sampler_desc.MaxAnisotropy = p_state.anisotropy_max; + } else { + static const D3D12_FILTER_TYPE d3d12_filter_types[] = { + D3D12_FILTER_TYPE_POINT, // SAMPLER_FILTER_NEAREST. + D3D12_FILTER_TYPE_LINEAR, // SAMPLER_FILTER_LINEAR. + }; + sampler_desc.Filter = D3D12_ENCODE_BASIC_FILTER( + d3d12_filter_types[p_state.min_filter], + d3d12_filter_types[p_state.mag_filter], + d3d12_filter_types[p_state.mip_filter], + p_state.enable_compare ? D3D12_FILTER_REDUCTION_TYPE_COMPARISON : D3D12_FILTER_REDUCTION_TYPE_STANDARD); + } + + ERR_FAIL_INDEX_V(p_state.repeat_u, SAMPLER_REPEAT_MODE_MAX, RID()); + sampler_desc.AddressU = address_modes[p_state.repeat_u]; + ERR_FAIL_INDEX_V(p_state.repeat_v, SAMPLER_REPEAT_MODE_MAX, RID()); + sampler_desc.AddressV = address_modes[p_state.repeat_v]; + ERR_FAIL_INDEX_V(p_state.repeat_w, SAMPLER_REPEAT_MODE_MAX, RID()); + sampler_desc.AddressW = address_modes[p_state.repeat_w]; + + ERR_FAIL_INDEX_V(p_state.border_color, SAMPLER_BORDER_COLOR_MAX, RID()); + for (int i = 0; i < 4; i++) { + sampler_desc.BorderColor[i] = sampler_border_colors[p_state.border_color][i]; + } + + sampler_desc.MinLOD = p_state.min_lod; + sampler_desc.MaxLOD = p_state.max_lod; + sampler_desc.MipLODBias = p_state.lod_bias; + + ERR_FAIL_INDEX_V(p_state.compare_op, COMPARE_OP_MAX, RID()); + sampler_desc.ComparisonFunc = p_state.enable_compare ? compare_operators[p_state.compare_op] : D3D12_COMPARISON_FUNC_NEVER; + + // TODO: Emulate somehow? + if (p_state.unnormalized_uvw) { + WARN_PRINT("Creating a sampler with unnormalized UVW, which is not supported."); + } + + return sampler_owner.make_rid(sampler_desc); +} + +bool RenderingDeviceD3D12::sampler_is_format_supported_for_filter(DataFormat p_format, SamplerFilter p_sampler_filter) const { + ERR_FAIL_INDEX_V(p_format, DATA_FORMAT_MAX, false); + + _THREAD_SAFE_METHOD_ + + D3D12_FEATURE_DATA_FORMAT_SUPPORT srv_rtv_support = {}; + srv_rtv_support.Format = d3d12_formats[p_format].general_format; + HRESULT res = device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &srv_rtv_support, sizeof(srv_rtv_support)); + ERR_FAIL_COND_V_MSG(res, false, "CheckFeatureSupport failed with error " + vformat("0x%08ux", res) + "."); + + return (srv_rtv_support.Support1 & D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE); +} + +/**********************/ +/**** VERTEX ARRAY ****/ +/**********************/ + +RID RenderingDeviceD3D12::vertex_buffer_create(uint32_t p_size_bytes, const Vector<uint8_t> &p_data, bool p_use_as_storage) { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND_V(p_data.size() && (uint32_t)p_data.size() != p_size_bytes, RID()); + + Buffer buffer; + D3D12_RESOURCE_STATES usage = D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER; + if (p_use_as_storage) { + usage |= D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + } + Error err = _buffer_allocate(&buffer, p_size_bytes, usage, D3D12_HEAP_TYPE_DEFAULT); + ERR_FAIL_COND_V(err != OK, RID()); + + if (p_data.size()) { + uint64_t data_size = p_data.size(); + const uint8_t *r = p_data.ptr(); + _buffer_update(&buffer, 0, r, data_size); + } + + RID id = vertex_buffer_owner.make_rid(buffer); +#ifdef DEV_ENABLED + set_resource_name(id, "RID:" + itos(id.get_id())); +#endif + return id; +} + +// Internally reference counted, this ID is warranted to be unique for the same description, but needs to be freed as many times as it was allocated. +RenderingDevice::VertexFormatID RenderingDeviceD3D12::vertex_format_create(const Vector<VertexAttribute> &p_vertex_formats) { + _THREAD_SAFE_METHOD_ + + VertexDescriptionKey key; + key.vertex_formats = p_vertex_formats; + + VertexFormatID *idptr = vertex_format_cache.getptr(key); + if (idptr) { + return *idptr; + } + + // Does not exist, create one and cache it. + VertexDescriptionCache vdcache; + vdcache.elements_desc.resize(p_vertex_formats.size()); + + HashSet<int> used_locations; + for (int i = 0; i < p_vertex_formats.size(); i++) { + ERR_CONTINUE(p_vertex_formats[i].format >= DATA_FORMAT_MAX); + ERR_FAIL_COND_V(used_locations.has(p_vertex_formats[i].location), INVALID_ID); + + ERR_FAIL_COND_V_MSG(get_format_vertex_size(p_vertex_formats[i].format) == 0, INVALID_ID, + "Data format for attachment (" + itos(i) + "), '" + named_formats[p_vertex_formats[i].format] + "', is not valid for a vertex array."); + + // SPIRV-Cross maps `layout(location = <N>) in` to `TEXCOORD<N>`. + vdcache.elements_desc.write[i].SemanticName = "TEXCOORD"; // SPIRV-Cross will apply TEXCOORD semantic to vertex attributes. + vdcache.elements_desc.write[i].SemanticIndex = p_vertex_formats[i].location; + vdcache.elements_desc.write[i].Format = d3d12_formats[p_vertex_formats[i].format].general_format; + vdcache.elements_desc.write[i].InputSlot = i; // TODO: Can the same slot be used if data comes from the same buffer (regardless format)? + vdcache.elements_desc.write[i].AlignedByteOffset = p_vertex_formats[i].offset; + if (p_vertex_formats[i].frequency == VERTEX_FREQUENCY_INSTANCE) { + vdcache.elements_desc.write[i].InputSlotClass = D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA; + vdcache.elements_desc.write[i].InstanceDataStepRate = 1; + } else { + vdcache.elements_desc.write[i].InputSlotClass = D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA; + vdcache.elements_desc.write[i].InstanceDataStepRate = 0; + } + used_locations.insert(p_vertex_formats[i].location); + } + + vdcache.vertex_formats = p_vertex_formats; + + VertexFormatID id = VertexFormatID(vertex_format_cache.size()) | (VertexFormatID(ID_TYPE_VERTEX_FORMAT) << ID_BASE_SHIFT); + vertex_format_cache[key] = id; + vertex_formats[id] = vdcache; + return id; +} + +RID RenderingDeviceD3D12::vertex_array_create(uint32_t p_vertex_count, VertexFormatID p_vertex_format, const Vector<RID> &p_src_buffers, const Vector<uint64_t> &p_offsets) { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND_V(!vertex_formats.has(p_vertex_format), RID()); + const VertexDescriptionCache &vd = vertex_formats[p_vertex_format]; + + ERR_FAIL_COND_V(vd.vertex_formats.size() != p_src_buffers.size(), RID()); + + for (int i = 0; i < p_src_buffers.size(); i++) { + ERR_FAIL_COND_V(!vertex_buffer_owner.owns(p_src_buffers[i]), RID()); + } + + VertexArray vertex_array; + + if (!p_offsets.is_empty()) { + ERR_FAIL_COND_V(p_offsets.size() != p_src_buffers.size(), RID()); + } + + vertex_array.vertex_count = p_vertex_count; + vertex_array.description = p_vertex_format; + vertex_array.max_instances_allowed = 0xFFFFFFFF; // By default as many as you want. + HashSet<Buffer *> unique_buffers; + for (int i = 0; i < p_src_buffers.size(); i++) { + Buffer *buffer = vertex_buffer_owner.get_or_null(p_src_buffers[i]); + + const VertexAttribute &atf = vd.vertex_formats[i]; + + // Validate with buffer. + { + uint32_t element_size = get_format_vertex_size(atf.format); + ERR_FAIL_COND_V(element_size == 0, RID()); // Should never happens since this was prevalidated. + + if (atf.frequency == VERTEX_FREQUENCY_VERTEX) { + // Validate size for regular drawing. + uint64_t total_size = uint64_t(atf.stride) * (p_vertex_count - 1) + atf.offset + element_size; + ERR_FAIL_COND_V_MSG(total_size > buffer->size, RID(), + "Attachment (" + itos(i) + ") will read past the end of the buffer."); + + } else { + // Validate size for instances drawing. + uint64_t available = buffer->size - atf.offset; + ERR_FAIL_COND_V_MSG(available < element_size, RID(), + "Attachment (" + itos(i) + ") uses instancing, but it's just too small."); + + uint32_t instances_allowed = available / atf.stride; + vertex_array.max_instances_allowed = MIN(instances_allowed, vertex_array.max_instances_allowed); + } + } + + unique_buffers.insert(buffer); + + D3D12_VERTEX_BUFFER_VIEW view = {}; + uint64_t data_offset = p_offsets.is_empty() ? 0 : p_offsets[i]; + view.BufferLocation = buffer->resource->GetGPUVirtualAddress() + data_offset; + view.SizeInBytes = buffer->size; + view.StrideInBytes = atf.stride; + vertex_array.views.push_back(view); + } + + for (Buffer *buffer : unique_buffers) { + vertex_array.unique_buffers.push_back(buffer); + } + + RID id = vertex_array_owner.make_rid(vertex_array); + for (int i = 0; i < p_src_buffers.size(); i++) { + _add_dependency(id, p_src_buffers[i]); + } + + return id; +} + +RID RenderingDeviceD3D12::index_buffer_create(uint32_t p_index_count, IndexBufferFormat p_format, const Vector<uint8_t> &p_data, bool p_use_restart_indices) { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND_V(p_index_count == 0, RID()); + + IndexBuffer index_buffer; + index_buffer.index_format = (p_format == INDEX_BUFFER_FORMAT_UINT16) ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT; + index_buffer.supports_restart_indices = p_use_restart_indices; + index_buffer.index_count = p_index_count; + uint32_t size_bytes = p_index_count * ((p_format == INDEX_BUFFER_FORMAT_UINT16) ? 2 : 4); +#ifdef DEBUG_ENABLED + if (p_data.size()) { + index_buffer.max_index = 0; + ERR_FAIL_COND_V_MSG((uint32_t)p_data.size() != size_bytes, RID(), + "Default index buffer initializer array size (" + itos(p_data.size()) + ") does not match format required size (" + itos(size_bytes) + ")."); + const uint8_t *r = p_data.ptr(); + if (p_format == INDEX_BUFFER_FORMAT_UINT16) { + const uint16_t *index16 = (const uint16_t *)r; + for (uint32_t i = 0; i < p_index_count; i++) { + if (p_use_restart_indices && index16[i] == 0xFFFF) { + continue; // Restart index, ignore. + } + index_buffer.max_index = MAX(index16[i], index_buffer.max_index); + } + } else { + const uint32_t *index32 = (const uint32_t *)r; + for (uint32_t i = 0; i < p_index_count; i++) { + if (p_use_restart_indices && index32[i] == 0xFFFFFFFF) { + continue; // Restart index, ignore. + } + index_buffer.max_index = MAX(index32[i], index_buffer.max_index); + } + } + } else { + index_buffer.max_index = 0xFFFFFFFF; + } +#else + index_buffer.max_index = 0xFFFFFFFF; +#endif + Error err = _buffer_allocate(&index_buffer, size_bytes, D3D12_RESOURCE_STATE_INDEX_BUFFER, D3D12_HEAP_TYPE_DEFAULT); + ERR_FAIL_COND_V(err != OK, RID()); + + if (p_data.size()) { + uint64_t data_size = p_data.size(); + const uint8_t *r = p_data.ptr(); + _buffer_update(&index_buffer, 0, r, data_size); + } + RID id = index_buffer_owner.make_rid(index_buffer); +#ifdef DEV_ENABLED + set_resource_name(id, "RID:" + itos(id.get_id())); +#endif + return id; +} + +RID RenderingDeviceD3D12::index_array_create(RID p_index_buffer, uint32_t p_index_offset, uint32_t p_index_count) { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND_V(!index_buffer_owner.owns(p_index_buffer), RID()); + + IndexBuffer *index_buffer = index_buffer_owner.get_or_null(p_index_buffer); + + ERR_FAIL_COND_V(p_index_count == 0, RID()); + ERR_FAIL_COND_V(p_index_offset + p_index_count > index_buffer->index_count, RID()); + + IndexArray index_array; + index_array.buffer = index_buffer; + index_array.max_index = index_buffer->max_index; + index_array.offset = p_index_offset; + index_array.indices = p_index_count; + index_array.supports_restart_indices = index_buffer->supports_restart_indices; + index_array.view.BufferLocation = index_buffer->resource->GetGPUVirtualAddress(); + index_array.view.SizeInBytes = p_index_count * (index_buffer->index_format == DXGI_FORMAT_R16_UINT ? 2 : 4); + index_array.view.Format = index_buffer->index_format; + + RID id = index_array_owner.make_rid(index_array); + _add_dependency(id, p_index_buffer); + return id; +} + +/****************/ +/**** SHADER ****/ +/****************/ + +static const char *shader_uniform_names[RenderingDevice::UNIFORM_TYPE_MAX + 1] = { + "Sampler", "CombinedSampler", "Texture", "Image", "TextureBuffer", "SamplerTextureBuffer", "ImageBuffer", "UniformBuffer", "StorageBuffer", "InputAttachment", "N/A" +}; + +static uint32_t shader_stage_bit_offset_indices[RenderingDevice::SHADER_STAGE_MAX] = { + /* SHADER_STAGE_VERTEX */ 0, + /* SHADER_STAGE_FRAGMENT */ 1, + /* SHADER_STAGE_TESSELATION_CONTROL */ UINT32_MAX, + /* SHADER_STAGE_TESSELATION_EVALUATION */ UINT32_MAX, + /* SHADER_STAGE_COMPUTE */ 2, +}; + +String RenderingDeviceD3D12::_shader_uniform_debug(RID p_shader, int p_set) { + String ret; + const Shader *shader = shader_owner.get_or_null(p_shader); + ERR_FAIL_NULL_V(shader, String()); + for (int i = 0; i < shader->sets.size(); i++) { + if (p_set >= 0 && i != p_set) { + continue; + } + for (int j = 0; j < shader->sets[i].uniforms.size(); j++) { + const UniformInfo &ui = shader->sets[i].uniforms[j].info; + if (!ret.is_empty()) { + ret += "\n"; + } + ret += "Set: " + itos(i) + " Binding: " + itos(ui.binding) + " Type: " + shader_uniform_names[ui.type] + " Writable: " + (ui.writable ? "Y" : "N") + " Length: " + itos(ui.length); + } + } + return ret; +} + +uint32_t RenderingDeviceD3D12::_shader_patch_dxil_specialization_constant( + PipelineSpecializationConstantType p_type, + const void *p_value, + const uint64_t (&p_stages_bit_offsets)[D3D12_BITCODE_OFFSETS_NUM_STAGES], + HashMap<ShaderStage, Vector<uint8_t>> &r_stages_bytecodes, + bool p_is_first_patch) { + uint32_t patch_val = 0; + switch (p_type) { + case PIPELINE_SPECIALIZATION_CONSTANT_TYPE_INT: { + uint32_t int_value = *((const int *)p_value); + ERR_FAIL_COND_V(int_value & (1 << 31), 0); + patch_val = int_value; + } break; + case PIPELINE_SPECIALIZATION_CONSTANT_TYPE_BOOL: { + bool bool_value = *((const bool *)p_value); + patch_val = (uint32_t)bool_value; + } break; + case PIPELINE_SPECIALIZATION_CONSTANT_TYPE_FLOAT: { + uint32_t int_value = *((const int *)p_value); + ERR_FAIL_COND_V(int_value & (1 << 31), 0); + patch_val = (int_value >> 1); + } break; + } + // For VBR encoding to encode the number of bits we expect (32), we need to set the MSB unconditionally. + // However, signed VBR moves the MSB to the LSB, so setting the MSB to 1 wouldn't help. Therefore, + // the bit we set to 1 is the one at index 30. + patch_val |= (1 << 30); + patch_val <<= 1; // What signed VBR does. + + auto tamper_bits = [](uint8_t *p_start, uint64_t p_bit_offset, uint64_t p_value) -> uint64_t { + uint64_t original = 0; + uint32_t curr_input_byte = p_bit_offset / 8; + uint8_t curr_input_bit = p_bit_offset % 8; + auto get_curr_input_bit = [&]() -> bool { + return ((p_start[curr_input_byte] >> curr_input_bit) & 1); + }; + auto move_to_next_input_bit = [&]() { + if (curr_input_bit == 7) { + curr_input_bit = 0; + curr_input_byte++; + } else { + curr_input_bit++; + } + }; + auto tamper_input_bit = [&](bool p_new_bit) { + p_start[curr_input_byte] &= ~((uint8_t)1 << curr_input_bit); + if (p_new_bit) { + p_start[curr_input_byte] |= (uint8_t)1 << curr_input_bit; + } + }; + uint8_t value_bit_idx = 0; + for (uint32_t i = 0; i < 5; i++) { // 32 bits take 5 full bytes in VBR. + for (uint32_t j = 0; j < 7; j++) { + bool input_bit = get_curr_input_bit(); + original |= (uint64_t)(input_bit ? 1 : 0) << value_bit_idx; + tamper_input_bit((p_value >> value_bit_idx) & 1); + move_to_next_input_bit(); + value_bit_idx++; + } +#ifdef DEV_ENABLED + bool input_bit = get_curr_input_bit(); + DEV_ASSERT(i < 4 && input_bit || i == 4 && !input_bit); +#endif + move_to_next_input_bit(); + } + return original; + }; + uint32_t stages_patched_mask = 0; + for (int stage = 0; stage < SHADER_STAGE_MAX; stage++) { + if (!r_stages_bytecodes.has((ShaderStage)stage)) { + continue; + } + + uint64_t offset = p_stages_bit_offsets[shader_stage_bit_offset_indices[stage]]; + if (offset == 0) { + // This constant does not appear at this stage. + continue; + } + + Vector<uint8_t> &bytecode = r_stages_bytecodes[(ShaderStage)stage]; +#ifdef DEV_ENABLED + uint64_t orig_patch_val = tamper_bits(bytecode.ptrw(), offset, patch_val); + // Checking against the value the NIR patch should have set. + DEV_ASSERT(!p_is_first_patch || ((orig_patch_val >> 1) & GODOT_NIR_SC_SENTINEL_MAGIC_MASK) == GODOT_NIR_SC_SENTINEL_MAGIC); + uint64_t readback_patch_val = tamper_bits(bytecode.ptrw(), offset, patch_val); + DEV_ASSERT(readback_patch_val == patch_val); +#else + tamper_bits(bytecode.ptrw(), offset, patch_val); +#endif + + stages_patched_mask |= (1 << stage); + } + return stages_patched_mask; +} + +bool RenderingDeviceD3D12::_shader_sign_dxil_bytecode(ShaderStage p_stage, Vector<uint8_t> &r_dxil_blob) { + dxil_validator *validator = get_dxil_validator_for_current_thread(); + + char *err = nullptr; + bool res = dxil_validate_module(validator, r_dxil_blob.ptrw(), r_dxil_blob.size(), &err); + if (!res) { + if (err) { + ERR_FAIL_COND_V_MSG(!res, false, "Shader signing invocation at stage " + String(shader_stage_names[p_stage]) + " failed:\n" + String(err)); + } else { + ERR_FAIL_COND_V_MSG(!res, false, "Shader signing invocation at stage " + String(shader_stage_names[p_stage]) + " failed."); + } + } + + return true; +} + +// Version 1: Initial. +// Version 2: 64-bit vertex input mask. +#define SHADER_BINARY_VERSION 2 + +String RenderingDeviceD3D12::shader_get_binary_cache_key() const { + return "D3D12-SV" + itos(SHADER_BINARY_VERSION); +} + +enum RootSignatureLocationType { + RS_LOC_TYPE_RESOURCE, + RS_LOC_TYPE_SAMPLER, +}; + +enum ResourceClass { + RES_CLASS_INVALID, + RES_CLASS_CBV, + RES_CLASS_SRV, + RES_CLASS_UAV, +}; + +// Phase 1: SPIR-V reflection, where the Vulkan/RD interface of the shader is discovered. +// Phase 2: SPIR-V to DXIL translation, where the DXIL interface is discovered, which may have gaps due to optimizations. + +struct RenderingDeviceD3D12ShaderBinaryDataBinding { + // - Phase 1. + uint32_t type; + uint32_t binding; + uint32_t stages; + uint32_t length; // Size of arrays (in total elements), or ubos (in bytes * total elements). + uint32_t writable; + // - Phase 2. + uint32_t res_class; + uint32_t has_sampler; + uint32_t dxil_stages; + struct RootSignatureLocation { + uint32_t root_param_idx = UINT32_MAX; // UINT32_MAX if unused. + uint32_t range_idx = UINT32_MAX; // UINT32_MAX if unused. + }; + RootSignatureLocation root_sig_locations[2]; // Index is RootSignatureLocationType. + + // We need to sort these to fill the root signature locations properly. + bool operator<(const RenderingDeviceD3D12ShaderBinaryDataBinding &p_other) const { + return binding < p_other.binding; + } +}; + +struct RenderingDeviceD3D12ShaderBinarySpecializationConstant { + // - Phase 1. + uint32_t type; + uint32_t constant_id; + union { + uint32_t int_value; + float float_value; + bool bool_value; + }; + // - Phase 2. + uint64_t stages_bit_offsets[D3D12_BITCODE_OFFSETS_NUM_STAGES]; +}; + +struct RenderingDeviceD3D12ShaderBinaryData { + uint64_t vertex_input_mask; + uint32_t fragment_output_mask; + uint32_t specialization_constants_count; + uint32_t spirv_specialization_constants_ids_mask; + uint32_t is_compute; + uint32_t compute_local_size[3]; + uint32_t set_count; + uint32_t push_constant_size; + uint32_t dxil_push_constant_stages; // Phase 2. + uint32_t nir_runtime_data_root_param_idx; // Phase 2. + uint32_t stage_count; + uint32_t shader_name_len; + uint32_t root_signature_len; + uint32_t root_signature_crc; +}; + +Vector<uint8_t> RenderingDeviceD3D12::shader_compile_binary_from_spirv(const Vector<ShaderStageSPIRVData> &p_spirv, const String &p_shader_name) { + SpirvReflectionData spirv_data; + if (_reflect_spirv(p_spirv, spirv_data) != OK) { + return Vector<uint8_t>(); + } + + // Collect reflection data into binary data. + RenderingDeviceD3D12ShaderBinaryData binary_data = {}; + Vector<Vector<RenderingDeviceD3D12ShaderBinaryDataBinding>> uniform_info; + Vector<RenderingDeviceD3D12ShaderBinarySpecializationConstant> specialization_constants; + { + binary_data.vertex_input_mask = spirv_data.vertex_input_mask; + binary_data.fragment_output_mask = spirv_data.fragment_output_mask; + binary_data.specialization_constants_count = spirv_data.specialization_constants.size(); + binary_data.is_compute = spirv_data.is_compute; + binary_data.compute_local_size[0] = spirv_data.compute_local_size[0]; + binary_data.compute_local_size[1] = spirv_data.compute_local_size[1]; + binary_data.compute_local_size[2] = spirv_data.compute_local_size[2]; + binary_data.set_count = spirv_data.uniforms.size(); + binary_data.push_constant_size = spirv_data.push_constant_size; + binary_data.nir_runtime_data_root_param_idx = UINT32_MAX; + binary_data.stage_count = p_spirv.size(); + + for (const Vector<SpirvReflectionData::Uniform> &spirv_set : spirv_data.uniforms) { + Vector<RenderingDeviceD3D12ShaderBinaryDataBinding> set_bindings; + for (const SpirvReflectionData::Uniform &spirv_uniform : spirv_set) { + RenderingDeviceD3D12ShaderBinaryDataBinding binding{}; + binding.type = (uint32_t)spirv_uniform.type; + binding.binding = spirv_uniform.binding; + binding.stages = (uint32_t)spirv_uniform.stages_mask; + binding.length = spirv_uniform.length; + binding.writable = (uint32_t)spirv_uniform.writable; + set_bindings.push_back(binding); + } + uniform_info.push_back(set_bindings); + } + + for (const SpirvReflectionData::SpecializationConstant &spirv_sc : spirv_data.specialization_constants) { + RenderingDeviceD3D12ShaderBinarySpecializationConstant spec_constant{}; + spec_constant.type = (uint32_t)spirv_sc.type; + spec_constant.constant_id = spirv_sc.constant_id; + spec_constant.int_value = spirv_sc.int_value; + specialization_constants.push_back(spec_constant); + + binary_data.spirv_specialization_constants_ids_mask |= (1 << spirv_sc.constant_id); + } + } + + // Translate SPIR-V shaders to DXIL, and collect shader info from the new representation. + HashMap<ShaderStage, Vector<uint8_t>> dxil_blobs; + BitField<ShaderStage> stages_processed; + { + HashMap<int, nir_shader *> stages_nir_shaders; + + auto free_nir_shaders = [&]() { + for (KeyValue<int, nir_shader *> &E : stages_nir_shaders) { + ralloc_free(E.value); + } + stages_nir_shaders.clear(); + }; + + // This is based on spirv2dxil.c. May need updates when it changes. + // Also, this has to stay around until after linking. + nir_shader_compiler_options nir_options = *dxil_get_nir_compiler_options(); + nir_options.lower_base_vertex = false; + + dxil_spirv_runtime_conf dxil_runtime_conf = {}; + dxil_runtime_conf.runtime_data_cbv.register_space = RUNTIME_DATA_SPACE; + dxil_runtime_conf.runtime_data_cbv.base_shader_register = RUNTIME_DATA_REGISTER; + dxil_runtime_conf.push_constant_cbv.register_space = ROOT_CONSTANT_SPACE; + dxil_runtime_conf.push_constant_cbv.base_shader_register = ROOT_CONSTANT_REGISTER; + dxil_runtime_conf.zero_based_vertex_instance_id = true; + dxil_runtime_conf.zero_based_compute_workgroup_id = true; + dxil_runtime_conf.declared_read_only_images_as_srvs = true; + // Making this explicit to let maintainers know that in practice this didn't improve performance, + // probably because data generated by one shader and consumed by another one forces the resource + // to transition from UAV to SRV, and back, instead of being an UAV all the time. + // In case someone wants to try, care must be taken so in case of incompatible bindings across stages + // happen as a result, all the stages are re-translated. That can happen if, for instance, a stage only + // uses an allegedly writable resource only for reading but the next stage doesn't. + dxil_runtime_conf.inferred_read_only_images_as_srvs = false; + + // - Translate SPIR-V to NIR. + for (int i = 0; i < p_spirv.size(); i++) { + ShaderStage stage = (ShaderStage)p_spirv[i].shader_stage; + ShaderStage stage_flag = (ShaderStage)(1 << p_spirv[i].shader_stage); + + stages_processed.set_flag(stage_flag); + + { + char *entry_point = "main"; + + static const gl_shader_stage SPIRV_TO_MESA_STAGES[SHADER_STAGE_MAX] = { + /* SHADER_STAGE_VERTEX */ MESA_SHADER_VERTEX, + /* SHADER_STAGE_FRAGMENT */ MESA_SHADER_FRAGMENT, + /* SHADER_STAGE_TESSELATION_CONTROL */ MESA_SHADER_TESS_CTRL, + /* SHADER_STAGE_TESSELATION_EVALUATION */ MESA_SHADER_TESS_EVAL, + /* SHADER_STAGE_COMPUTE */ MESA_SHADER_COMPUTE, + }; + + nir_shader *nir_shader = spirv_to_nir( + (const uint32_t *)p_spirv[i].spir_v.ptr(), + p_spirv[i].spir_v.size() / sizeof(uint32_t), + nullptr, + 0, + SPIRV_TO_MESA_STAGES[stage], + entry_point, + dxil_spirv_nir_get_spirv_options(), &nir_options); + if (!nir_shader) { + free_nir_shaders(); + ERR_FAIL_V_MSG(Vector<uint8_t>(), "Shader translation (step 1) at stage " + String(shader_stage_names[stage]) + " failed."); + } + +#ifdef DEV_ENABLED + nir_validate_shader(nir_shader, "Validate before feeding NIR to the DXIL compiler"); +#endif + + if (stage == SHADER_STAGE_VERTEX) { + dxil_runtime_conf.yz_flip.y_mask = 0xffff; + dxil_runtime_conf.yz_flip.mode = DXIL_SPIRV_Y_FLIP_UNCONDITIONAL; + } else { + dxil_runtime_conf.yz_flip.y_mask = 0; + dxil_runtime_conf.yz_flip.mode = DXIL_SPIRV_YZ_FLIP_NONE; + } + + // This is based on spirv2dxil.c. May need updates when it changes. + dxil_spirv_nir_prep(nir_shader); + bool requires_runtime_data = {}; + dxil_spirv_nir_passes(nir_shader, &dxil_runtime_conf, &requires_runtime_data); + + stages_nir_shaders[stage] = nir_shader; + } + } + + // - Link NIR shaders. + for (int i = SHADER_STAGE_MAX - 1; i >= 0; i--) { + if (!stages_nir_shaders.has(i)) { + continue; + } + nir_shader *shader = stages_nir_shaders[i]; + nir_shader *prev_shader = nullptr; + for (int j = i - 1; j >= 0; j--) { + if (stages_nir_shaders.has(j)) { + prev_shader = stages_nir_shaders[j]; + break; + } + } + if (prev_shader) { + bool requires_runtime_data = {}; + dxil_spirv_nir_link(shader, prev_shader, &dxil_runtime_conf, &requires_runtime_data); + } + } + + // - Translate NIR to DXIL. + for (int i = 0; i < p_spirv.size(); i++) { + ShaderStage stage = (ShaderStage)p_spirv[i].shader_stage; + + struct ShaderData { + ShaderStage stage; + RenderingDeviceD3D12ShaderBinaryData &binary_data; + Vector<Vector<RenderingDeviceD3D12ShaderBinaryDataBinding>> &uniform_info; + Vector<RenderingDeviceD3D12ShaderBinarySpecializationConstant> &specialization_constants; + } shader_data{ stage, binary_data, uniform_info, specialization_constants }; + + GodotNirCallbacks godot_nir_callbacks = {}; + godot_nir_callbacks.data = &shader_data; + + godot_nir_callbacks.report_resource = [](uint32_t p_register, uint32_t p_space, uint32_t p_dxil_type, void *p_data) { + ShaderData &shader_data = *(ShaderData *)p_data; + + // Types based on Mesa's dxil_container.h. + static const uint32_t DXIL_RES_SAMPLER = 1; + static const ResourceClass DXIL_TYPE_TO_CLASS[] = { + /* DXIL_RES_INVALID */ RES_CLASS_INVALID, + /* DXIL_RES_SAMPLER */ RES_CLASS_INVALID, // Handling sampler as a flag. + /* DXIL_RES_CBV */ RES_CLASS_CBV, + /* DXIL_RES_SRV_TYPED */ RES_CLASS_SRV, + /* DXIL_RES_SRV_RAW */ RES_CLASS_SRV, + /* DXIL_RES_SRV_STRUCTURED */ RES_CLASS_SRV, + /* DXIL_RES_UAV_TYPED */ RES_CLASS_UAV, + /* DXIL_RES_UAV_RAW */ RES_CLASS_UAV, + /* DXIL_RES_UAV_STRUCTURED */ RES_CLASS_UAV, + /* DXIL_RES_UAV_STRUCTURED_WITH_COUNTER */ RES_CLASS_INVALID, + }; + DEV_ASSERT(p_dxil_type < ARRAY_SIZE(DXIL_TYPE_TO_CLASS)); + ResourceClass res_class = DXIL_TYPE_TO_CLASS[p_dxil_type]; + + if (p_register == ROOT_CONSTANT_REGISTER && p_space == ROOT_CONSTANT_SPACE) { + DEV_ASSERT(res_class == RES_CLASS_CBV); + shader_data.binary_data.dxil_push_constant_stages |= (1 << shader_data.stage); + } else if (p_register == RUNTIME_DATA_REGISTER && p_space == RUNTIME_DATA_SPACE) { + DEV_ASSERT(res_class == RES_CLASS_CBV); + shader_data.binary_data.nir_runtime_data_root_param_idx = 1; // Temporary, to be determined later. + } else { + DEV_ASSERT(p_space == 0); + + uint32_t set = p_register / GODOT_NIR_DESCRIPTOR_SET_MULTIPLIER; + uint32_t binding = (p_register % GODOT_NIR_DESCRIPTOR_SET_MULTIPLIER) / GODOT_NIR_BINDING_MULTIPLIER; + + DEV_ASSERT(set < (uint32_t)shader_data.uniform_info.size()); + bool found = false; + for (int i = 0; i < shader_data.uniform_info[set].size(); i++) { + if (shader_data.uniform_info[set][i].binding != binding) { + continue; + } + + RenderingDeviceD3D12ShaderBinaryDataBinding &binding_info = shader_data.uniform_info.write[set].write[i]; + + binding_info.dxil_stages |= (1 << shader_data.stage); + + if (res_class != RES_CLASS_INVALID) { + DEV_ASSERT(binding_info.res_class == (uint32_t)RES_CLASS_INVALID || binding_info.res_class == (uint32_t)res_class); + binding_info.res_class = res_class; + } else if (p_dxil_type == DXIL_RES_SAMPLER) { + binding_info.has_sampler = (uint32_t) true; + } else { + CRASH_NOW(); + } + + found = true; + break; + } + DEV_ASSERT(found); + } + }; + + godot_nir_callbacks.report_sc_bit_offset_fn = [](uint32_t p_sc_id, uint64_t p_bit_offset, void *p_data) { + ShaderData &shader_data = *(ShaderData *)p_data; + + bool found = false; + for (int i = 0; i < shader_data.specialization_constants.size(); i++) { + if (shader_data.specialization_constants[i].constant_id != p_sc_id) { + continue; + } + + uint32_t offset_idx = shader_stage_bit_offset_indices[shader_data.stage]; + DEV_ASSERT(shader_data.specialization_constants.write[i].stages_bit_offsets[offset_idx] == 0); + shader_data.specialization_constants.write[i].stages_bit_offsets[offset_idx] = p_bit_offset; + + found = true; + break; + } + DEV_ASSERT(found); + }; + + godot_nir_callbacks.report_bitcode_bit_offset_fn = [](uint64_t p_bit_offset, void *p_data) { + DEV_ASSERT(p_bit_offset % 8 == 0); + ShaderData &shader_data = *(ShaderData *)p_data; + uint32_t offset_idx = shader_stage_bit_offset_indices[shader_data.stage]; + for (int i = 0; i < shader_data.specialization_constants.size(); i++) { + if (shader_data.specialization_constants.write[i].stages_bit_offsets[offset_idx] == 0) { + // This SC has been optimized out from this stage. + continue; + } + shader_data.specialization_constants.write[i].stages_bit_offsets[offset_idx] += p_bit_offset; + } + }; + + auto shader_model_d3d_to_dxil = [](D3D_SHADER_MODEL p_d3d_shader_model) -> dxil_shader_model { + static_assert(SHADER_MODEL_6_0 == 0x60000); + static_assert(SHADER_MODEL_6_3 == 0x60003); + static_assert(D3D_SHADER_MODEL_6_0 == 0x60); + static_assert(D3D_SHADER_MODEL_6_3 == 0x63); + return (dxil_shader_model)((p_d3d_shader_model >> 4) * 0x10000 + (p_d3d_shader_model & 0xf)); + }; + + nir_to_dxil_options nir_to_dxil_options = {}; + nir_to_dxil_options.environment = DXIL_ENVIRONMENT_VULKAN; + nir_to_dxil_options.shader_model_max = shader_model_d3d_to_dxil(context->get_shader_capabilities().shader_model); + nir_to_dxil_options.validator_version_max = dxil_get_validator_version(get_dxil_validator_for_current_thread()); + nir_to_dxil_options.godot_nir_callbacks = &godot_nir_callbacks; + + dxil_logger logger = {}; + logger.log = [](void *p_priv, const char *p_msg) { +#ifdef DEBUG_ENABLED + print_verbose(p_msg); +#endif + }; + + blob dxil_blob = {}; + bool ok = nir_to_dxil(stages_nir_shaders[stage], &nir_to_dxil_options, &logger, &dxil_blob); + ralloc_free(stages_nir_shaders[stage]); + stages_nir_shaders.erase(stage); + if (!ok) { + free_nir_shaders(); + ERR_FAIL_V_MSG(Vector<uint8_t>(), "Shader translation at stage " + String(shader_stage_names[stage]) + " failed."); + } + + Vector<uint8_t> blob_copy; + blob_copy.resize(dxil_blob.size); + memcpy(blob_copy.ptrw(), dxil_blob.data, dxil_blob.size); + blob_finish(&dxil_blob); + dxil_blobs.insert(stage, blob_copy); + } + } + +#if 0 + if (dxil_blobs.has(SHADER_STAGE_FRAGMENT)) { + Ref<FileAccess> f = FileAccess::open("res://1.dxil", FileAccess::WRITE); + f->store_buffer(dxil_blobs[SHADER_STAGE_FRAGMENT].ptr(), dxil_blobs[SHADER_STAGE_FRAGMENT].size()); + } +#endif + + // Patch with default values of specialization constants. + if (specialization_constants.size()) { + for (const RenderingDeviceD3D12ShaderBinarySpecializationConstant &sc : specialization_constants) { + _shader_patch_dxil_specialization_constant((PipelineSpecializationConstantType)sc.type, &sc.int_value, sc.stages_bit_offsets, dxil_blobs, true); + } +#if 0 + if (dxil_blobs.has(SHADER_STAGE_FRAGMENT)) { + Ref<FileAccess> f = FileAccess::open("res://2.dxil", FileAccess::WRITE); + f->store_buffer(dxil_blobs[SHADER_STAGE_FRAGMENT].ptr(), dxil_blobs[SHADER_STAGE_FRAGMENT].size()); + } +#endif + } + + // Sign. + for (KeyValue<ShaderStage, Vector<uint8_t>> &E : dxil_blobs) { + ShaderStage stage = E.key; + Vector<uint8_t> &dxil_blob = E.value; + bool sign_ok = _shader_sign_dxil_bytecode(stage, dxil_blob); + ERR_FAIL_COND_V(!sign_ok, Vector<uint8_t>()); + } + + // Build the root signature. + ComPtr<ID3DBlob> root_sig_blob; + { + auto stages_to_d3d12_visibility = [](uint32_t p_stages_mask) -> D3D12_SHADER_VISIBILITY { + switch (p_stages_mask) { + case SHADER_STAGE_VERTEX_BIT: { + return D3D12_SHADER_VISIBILITY_VERTEX; + } + case SHADER_STAGE_FRAGMENT_BIT: { + return D3D12_SHADER_VISIBILITY_PIXEL; + } + default: { + return D3D12_SHADER_VISIBILITY_ALL; + } + } + }; + + LocalVector<D3D12_ROOT_PARAMETER1> root_params; + + // Root (push) constants. + if (binary_data.dxil_push_constant_stages) { + CD3DX12_ROOT_PARAMETER1 push_constant; + push_constant.InitAsConstants( + binary_data.push_constant_size / sizeof(uint32_t), + ROOT_CONSTANT_REGISTER, + ROOT_CONSTANT_SPACE, + stages_to_d3d12_visibility(binary_data.dxil_push_constant_stages)); + root_params.push_back(push_constant); + } + + // NIR-DXIL runtime data. + if (binary_data.nir_runtime_data_root_param_idx == 1) { // Set above to 1 when discovering runtime data is needed. + DEV_ASSERT(!binary_data.is_compute); // Could be supported if needed, but it's pointless as of now. + binary_data.nir_runtime_data_root_param_idx = root_params.size(); + CD3DX12_ROOT_PARAMETER1 nir_runtime_data; + nir_runtime_data.InitAsConstants( + sizeof(dxil_spirv_vertex_runtime_data) / sizeof(uint32_t), + RUNTIME_DATA_REGISTER, + RUNTIME_DATA_SPACE, + D3D12_SHADER_VISIBILITY_VERTEX); + root_params.push_back(nir_runtime_data); + } + + // Descriptor tables (up to two per uniform set, for resources and/or samplers). + + // These have to stay around until serialization! + struct TraceableDescriptorTable { + uint32_t stages_mask = {}; + Vector<D3D12_DESCRIPTOR_RANGE1> ranges; + Vector<RenderingDeviceD3D12ShaderBinaryDataBinding::RootSignatureLocation *> root_sig_locations; + }; + Vector<TraceableDescriptorTable> resource_tables_maps; + Vector<TraceableDescriptorTable> sampler_tables_maps; + + for (int set = 0; set < uniform_info.size(); set++) { + bool first_resource_in_set = true; + bool first_sampler_in_set = true; + uniform_info.write[set].sort(); + for (int i = 0; i < uniform_info[set].size(); i++) { + const RenderingDeviceD3D12ShaderBinaryDataBinding &binding = uniform_info[set][i]; + + bool really_used = binding.dxil_stages != 0; +#ifdef DEV_ENABLED + bool anybody_home = (ResourceClass)binding.res_class != RES_CLASS_INVALID || binding.has_sampler; + DEV_ASSERT(anybody_home == really_used); +#endif + if (!really_used) { + continue; // Existed in SPIR-V; went away in DXIL. + } + + auto insert_range = [](D3D12_DESCRIPTOR_RANGE_TYPE p_range_type, + uint32_t p_num_descriptors, + uint32_t p_dxil_register, + uint32_t p_dxil_stages_mask, + RenderingDeviceD3D12ShaderBinaryDataBinding::RootSignatureLocation(&p_root_sig_locations), + Vector<TraceableDescriptorTable> &r_tables, + bool &r_first_in_set) { + if (r_first_in_set) { + r_tables.resize(r_tables.size() + 1); + r_first_in_set = false; + } + TraceableDescriptorTable &table = r_tables.write[r_tables.size() - 1]; + table.stages_mask |= p_dxil_stages_mask; + + CD3DX12_DESCRIPTOR_RANGE1 range; + // Due to the aliasing hack for SRV-UAV of different families, + // we can be causing an unintended change of data (sometimes the validation layers catch it). + D3D12_DESCRIPTOR_RANGE_FLAGS flags = D3D12_DESCRIPTOR_RANGE_FLAG_NONE; + if (p_range_type == D3D12_DESCRIPTOR_RANGE_TYPE_SRV || p_range_type == D3D12_DESCRIPTOR_RANGE_TYPE_UAV) { + flags = D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE; + } else if (p_range_type == D3D12_DESCRIPTOR_RANGE_TYPE_CBV) { + flags = D3D12_DESCRIPTOR_RANGE_FLAG_DATA_STATIC_WHILE_SET_AT_EXECUTE; + } + range.Init(p_range_type, p_num_descriptors, p_dxil_register, 0, flags); + + table.ranges.push_back(range); + table.root_sig_locations.push_back(&p_root_sig_locations); + }; + + uint32_t num_descriptors = 1; + + D3D12_DESCRIPTOR_RANGE_TYPE resource_range_type = {}; + switch ((ResourceClass)binding.res_class) { + case RES_CLASS_INVALID: { + num_descriptors = binding.length; + DEV_ASSERT(binding.has_sampler); + } break; + case RES_CLASS_CBV: { + resource_range_type = D3D12_DESCRIPTOR_RANGE_TYPE_CBV; + DEV_ASSERT(!binding.has_sampler); + } break; + case RES_CLASS_SRV: { + resource_range_type = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; + num_descriptors = MAX(1u, binding.length); // An unbound R/O buffer is reflected as zero-size. + } break; + case RES_CLASS_UAV: { + resource_range_type = D3D12_DESCRIPTOR_RANGE_TYPE_UAV; + num_descriptors = MAX(1u, binding.length); // An unbound R/W buffer is reflected as zero-size. + DEV_ASSERT(!binding.has_sampler); + } break; + } + + uint32_t dxil_register = set * GODOT_NIR_DESCRIPTOR_SET_MULTIPLIER + binding.binding * GODOT_NIR_BINDING_MULTIPLIER; + + if (binding.res_class != RES_CLASS_INVALID) { + insert_range( + resource_range_type, + num_descriptors, + dxil_register, + uniform_info[set][i].dxil_stages, + uniform_info.write[set].write[i].root_sig_locations[RS_LOC_TYPE_RESOURCE], + resource_tables_maps, + first_resource_in_set); + } + if (binding.has_sampler) { + insert_range( + D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, + num_descriptors, + dxil_register, + uniform_info[set][i].dxil_stages, + uniform_info.write[set].write[i].root_sig_locations[RS_LOC_TYPE_SAMPLER], + sampler_tables_maps, + first_sampler_in_set); + } + } + } + + auto make_descriptor_tables = [&root_params, &stages_to_d3d12_visibility](const Vector<TraceableDescriptorTable> &p_tables) { + for (const TraceableDescriptorTable &table : p_tables) { + D3D12_SHADER_VISIBILITY visibility = stages_to_d3d12_visibility(table.stages_mask); + DEV_ASSERT(table.ranges.size() == table.root_sig_locations.size()); + for (int i = 0; i < table.ranges.size(); i++) { + // By now we know very well which root signature location corresponds to the pointed uniform. + table.root_sig_locations[i]->root_param_idx = root_params.size(); + table.root_sig_locations[i]->range_idx = i; + } + + CD3DX12_ROOT_PARAMETER1 root_table; + root_table.InitAsDescriptorTable(table.ranges.size(), table.ranges.ptr(), visibility); + root_params.push_back(root_table); + } + }; + + make_descriptor_tables(resource_tables_maps); + make_descriptor_tables(sampler_tables_maps); + + CD3DX12_VERSIONED_ROOT_SIGNATURE_DESC root_sig_desc = {}; + D3D12_ROOT_SIGNATURE_FLAGS root_sig_flags = + D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS | + D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS | + D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS | + D3D12_ROOT_SIGNATURE_FLAG_DENY_AMPLIFICATION_SHADER_ROOT_ACCESS | + D3D12_ROOT_SIGNATURE_FLAG_DENY_MESH_SHADER_ROOT_ACCESS; + if (!stages_processed.has_flag(SHADER_STAGE_VERTEX_BIT)) { + root_sig_flags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_VERTEX_SHADER_ROOT_ACCESS; + } + if (!stages_processed.has_flag(SHADER_STAGE_FRAGMENT_BIT)) { + root_sig_flags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS; + } + if (binary_data.vertex_input_mask) { + root_sig_flags |= D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT; + } + root_sig_desc.Init_1_1(root_params.size(), root_params.ptr(), 0, nullptr, root_sig_flags); + + ComPtr<ID3DBlob> error_blob; + HRESULT res = D3DX12SerializeVersionedRootSignature(&root_sig_desc, D3D_ROOT_SIGNATURE_VERSION_1_1, root_sig_blob.GetAddressOf(), error_blob.GetAddressOf()); + ERR_FAIL_COND_V_MSG(res, Vector<uint8_t>(), + "Serialization of root signature failed with error " + vformat("0x%08ux", res) + " and the following message:\n" + String((char *)error_blob->GetBufferPointer(), error_blob->GetBufferSize())); + + binary_data.root_signature_crc = crc32(0, nullptr, 0); + binary_data.root_signature_crc = crc32(binary_data.root_signature_crc, (const Bytef *)root_sig_blob->GetBufferPointer(), root_sig_blob->GetBufferSize()); + } + + Vector<Vector<uint8_t>> compressed_stages; + Vector<uint32_t> zstd_size; + + uint32_t stages_binary_size = 0; + + for (int i = 0; i < p_spirv.size(); i++) { + Vector<uint8_t> zstd; + Vector<uint8_t> &dxil_blob = dxil_blobs[p_spirv[i].shader_stage]; + zstd.resize(Compression::get_max_compressed_buffer_size(dxil_blob.size(), Compression::MODE_ZSTD)); + int dst_size = Compression::compress(zstd.ptrw(), dxil_blob.ptr(), dxil_blob.size(), Compression::MODE_ZSTD); + + zstd_size.push_back(dst_size); + zstd.resize(dst_size); + compressed_stages.push_back(zstd); + + uint32_t s = compressed_stages[i].size(); + if (s % 4 != 0) { + s += 4 - (s % 4); + } + stages_binary_size += s; + } + + CharString shader_name_utf = p_shader_name.utf8(); + + binary_data.shader_name_len = shader_name_utf.length(); + + uint32_t total_size = sizeof(uint32_t) * 3; // Header + version + main datasize;. + total_size += sizeof(RenderingDeviceD3D12ShaderBinaryData); + + total_size += binary_data.shader_name_len; + if ((binary_data.shader_name_len % 4) != 0) { // Alignment rules are really strange. + total_size += 4 - (binary_data.shader_name_len % 4); + } + + for (int i = 0; i < uniform_info.size(); i++) { + total_size += sizeof(uint32_t); + total_size += uniform_info[i].size() * sizeof(RenderingDeviceD3D12ShaderBinaryDataBinding); + } + + total_size += sizeof(RenderingDeviceD3D12ShaderBinarySpecializationConstant) * specialization_constants.size(); + + total_size += compressed_stages.size() * sizeof(uint32_t) * 3; // Sizes. + total_size += stages_binary_size; + + binary_data.root_signature_len = root_sig_blob->GetBufferSize(); + total_size += binary_data.root_signature_len; + + Vector<uint8_t> ret; + ret.resize(total_size); + { + uint32_t offset = 0; + uint8_t *binptr = ret.ptrw(); + binptr[0] = 'G'; + binptr[1] = 'S'; + binptr[2] = 'B'; + binptr[3] = 'D'; // Godot shader binary data. + offset += 4; + encode_uint32(SHADER_BINARY_VERSION, binptr + offset); + offset += sizeof(uint32_t); + encode_uint32(sizeof(RenderingDeviceD3D12ShaderBinaryData), binptr + offset); + offset += sizeof(uint32_t); + memcpy(binptr + offset, &binary_data, sizeof(RenderingDeviceD3D12ShaderBinaryData)); + offset += sizeof(RenderingDeviceD3D12ShaderBinaryData); + + if (binary_data.shader_name_len > 0) { + memcpy(binptr + offset, shader_name_utf.ptr(), binary_data.shader_name_len); + offset += binary_data.shader_name_len; + + if ((binary_data.shader_name_len % 4) != 0) { // Alignment rules are really strange. + offset += 4 - (binary_data.shader_name_len % 4); + } + } + + for (int i = 0; i < uniform_info.size(); i++) { + int count = uniform_info[i].size(); + encode_uint32(count, binptr + offset); + offset += sizeof(uint32_t); + if (count > 0) { + memcpy(binptr + offset, uniform_info[i].ptr(), sizeof(RenderingDeviceD3D12ShaderBinaryDataBinding) * count); + offset += sizeof(RenderingDeviceD3D12ShaderBinaryDataBinding) * count; + } + } + + if (specialization_constants.size()) { + memcpy(binptr + offset, specialization_constants.ptr(), sizeof(RenderingDeviceD3D12ShaderBinarySpecializationConstant) * specialization_constants.size()); + offset += sizeof(RenderingDeviceD3D12ShaderBinarySpecializationConstant) * specialization_constants.size(); + } + + for (int i = 0; i < compressed_stages.size(); i++) { + encode_uint32(p_spirv[i].shader_stage, binptr + offset); + offset += sizeof(uint32_t); + encode_uint32(dxil_blobs[p_spirv[i].shader_stage].size(), binptr + offset); + offset += sizeof(uint32_t); + encode_uint32(zstd_size[i], binptr + offset); + offset += sizeof(uint32_t); + memcpy(binptr + offset, compressed_stages[i].ptr(), compressed_stages[i].size()); + + uint32_t s = compressed_stages[i].size(); + + if (s % 4 != 0) { + s += 4 - (s % 4); + } + + offset += s; + } + + memcpy(binptr + offset, root_sig_blob->GetBufferPointer(), root_sig_blob->GetBufferSize()); + offset += root_sig_blob->GetBufferSize(); + + ERR_FAIL_COND_V(offset != (uint32_t)ret.size(), Vector<uint8_t>()); + } + + return ret; +} + +RID RenderingDeviceD3D12::shader_create_from_bytecode(const Vector<uint8_t> &p_shader_binary, RID p_placeholder) { + const uint8_t *binptr = p_shader_binary.ptr(); + uint32_t binsize = p_shader_binary.size(); + + uint32_t read_offset = 0; + // Consistency check. + ERR_FAIL_COND_V(binsize < sizeof(uint32_t) * 3 + sizeof(RenderingDeviceD3D12ShaderBinaryData), RID()); + ERR_FAIL_COND_V(binptr[0] != 'G' || binptr[1] != 'S' || binptr[2] != 'B' || binptr[3] != 'D', RID()); + + uint32_t bin_version = decode_uint32(binptr + 4); + ERR_FAIL_COND_V(bin_version != SHADER_BINARY_VERSION, RID()); + + uint32_t bin_data_size = decode_uint32(binptr + 8); + + const RenderingDeviceD3D12ShaderBinaryData &binary_data = *(reinterpret_cast<const RenderingDeviceD3D12ShaderBinaryData *>(binptr + 12)); + + uint64_t vertex_input_mask = binary_data.vertex_input_mask; + + uint32_t fragment_output_mask = binary_data.fragment_output_mask; + + bool is_compute = binary_data.is_compute; + + const uint32_t compute_local_size[3] = { binary_data.compute_local_size[0], binary_data.compute_local_size[1], binary_data.compute_local_size[2] }; + + read_offset += sizeof(uint32_t) * 3 + bin_data_size; + + String name; + + if (binary_data.shader_name_len) { + name.parse_utf8((const char *)(binptr + read_offset), binary_data.shader_name_len); + read_offset += binary_data.shader_name_len; + if ((binary_data.shader_name_len % 4) != 0) { // Alignment rules are really strange. + read_offset += 4 - (binary_data.shader_name_len % 4); + } + } + + Vector<Shader::Set> set_info; + set_info.resize(binary_data.set_count); + + for (uint32_t i = 0; i < binary_data.set_count; i++) { + ERR_FAIL_COND_V(read_offset + sizeof(uint32_t) >= binsize, RID()); + uint32_t set_count = decode_uint32(binptr + read_offset); + read_offset += sizeof(uint32_t); + const RenderingDeviceD3D12ShaderBinaryDataBinding *set_ptr = reinterpret_cast<const RenderingDeviceD3D12ShaderBinaryDataBinding *>(binptr + read_offset); + uint32_t set_size = set_count * sizeof(RenderingDeviceD3D12ShaderBinaryDataBinding); + ERR_FAIL_COND_V(read_offset + set_size >= binsize, RID()); + + for (uint32_t j = 0; j < set_count; j++) { + Shader::ShaderUniformInfo sui; + + sui.info.type = UniformType(set_ptr[j].type); + sui.info.writable = set_ptr[j].writable; + sui.info.length = set_ptr[j].length; + sui.info.binding = set_ptr[j].binding; + + sui.binding.stages = set_ptr[j].dxil_stages; + sui.binding.res_class = (ResourceClass)set_ptr[j].res_class; + static_assert(sizeof(UniformBindingInfo::root_sig_locations) == sizeof(RenderingDeviceD3D12ShaderBinaryDataBinding::root_sig_locations)); + memcpy(&sui.binding.root_sig_locations, &set_ptr[j].root_sig_locations, sizeof(UniformBindingInfo::root_sig_locations)); + + set_info.write[i].uniforms.push_back(sui); + + if (sui.binding.root_sig_locations.resource.root_param_idx != UINT32_MAX) { + set_info.write[i].num_root_params.resources++; + } + if (sui.binding.root_sig_locations.sampler.root_param_idx != UINT32_MAX) { + set_info.write[i].num_root_params.samplers++; + } + } + + read_offset += set_size; + } + + ERR_FAIL_COND_V(read_offset + binary_data.specialization_constants_count * sizeof(RenderingDeviceD3D12ShaderBinarySpecializationConstant) >= binsize, RID()); + + Vector<Shader::SpecializationConstant> specialization_constants; + + for (uint32_t i = 0; i < binary_data.specialization_constants_count; i++) { + const RenderingDeviceD3D12ShaderBinarySpecializationConstant &src_sc = *(reinterpret_cast<const RenderingDeviceD3D12ShaderBinarySpecializationConstant *>(binptr + read_offset)); + Shader::SpecializationConstant sc; + sc.constant.int_value = src_sc.int_value; + sc.constant.type = PipelineSpecializationConstantType(src_sc.type); + sc.constant.constant_id = src_sc.constant_id; + memcpy(sc.stages_bit_offsets, src_sc.stages_bit_offsets, sizeof(sc.stages_bit_offsets)); + specialization_constants.push_back(sc); + + read_offset += sizeof(RenderingDeviceD3D12ShaderBinarySpecializationConstant); + } + + HashMap<ShaderStage, Vector<uint8_t>> stages_bytecode; + + for (uint32_t i = 0; i < binary_data.stage_count; i++) { + ERR_FAIL_COND_V(read_offset + sizeof(uint32_t) * 3 >= binsize, RID()); + uint32_t stage = decode_uint32(binptr + read_offset); + read_offset += sizeof(uint32_t); + uint32_t dxil_size = decode_uint32(binptr + read_offset); + read_offset += sizeof(uint32_t); + uint32_t zstd_size = decode_uint32(binptr + read_offset); + read_offset += sizeof(uint32_t); + + // Decompress. + Vector<uint8_t> dxil; + dxil.resize(dxil_size); + int dec_dxil_size = Compression::decompress(dxil.ptrw(), dxil.size(), binptr + read_offset, zstd_size, Compression::MODE_ZSTD); + ERR_FAIL_COND_V(dec_dxil_size != (int32_t)dxil_size, RID()); + stages_bytecode[ShaderStage(stage)] = dxil; + + if (zstd_size % 4 != 0) { + zstd_size += 4 - (zstd_size % 4); + } + + ERR_FAIL_COND_V(read_offset + zstd_size > binsize, RID()); + + read_offset += zstd_size; + } + + const uint8_t *root_sig_data_ptr = binptr + read_offset; + + ComPtr<ID3D12RootSignatureDeserializer> root_sig_deserializer; + HRESULT res = D3D12CreateRootSignatureDeserializer(root_sig_data_ptr, binary_data.root_signature_len, IID_PPV_ARGS(root_sig_deserializer.GetAddressOf())); + ERR_FAIL_COND_V_MSG(res, RID(), "D3D12CreateRootSignatureDeserializer failed with error " + vformat("0x%08ux", res) + "."); + read_offset += binary_data.root_signature_len; + + ERR_FAIL_COND_V(read_offset != binsize, RID()); + + // TODO: Need to lock? + _THREAD_SAFE_METHOD_ + + ComPtr<ID3D12RootSignature> root_signature; + res = device->CreateRootSignature(0, root_sig_data_ptr, binary_data.root_signature_len, IID_PPV_ARGS(root_signature.GetAddressOf())); + ERR_FAIL_COND_V_MSG(res, RID(), "CreateRootSignature failed with error " + vformat("0x%08ux", res) + "."); + + RID id; + if (p_placeholder.is_null()) { + id = shader_owner.make_rid(); + } else { + id = p_placeholder; + } + + Shader *shader = shader_owner.get_or_null(id); + ERR_FAIL_NULL_V(shader, RID()); + + shader->vertex_input_mask = vertex_input_mask; + shader->fragment_output_mask = fragment_output_mask; + shader->spirv_push_constant_size = binary_data.push_constant_size; + shader->dxil_push_constant_size = binary_data.dxil_push_constant_stages ? binary_data.push_constant_size : 0; + shader->nir_runtime_data_root_param_idx = binary_data.nir_runtime_data_root_param_idx; + shader->is_compute = is_compute; + shader->compute_local_size[0] = compute_local_size[0]; + shader->compute_local_size[1] = compute_local_size[1]; + shader->compute_local_size[2] = compute_local_size[2]; + shader->specialization_constants = specialization_constants; + shader->spirv_specialization_constants_ids_mask = binary_data.spirv_specialization_constants_ids_mask; + shader->name = name; + shader->root_signature = root_signature; + shader->root_signature_deserializer = root_sig_deserializer; + shader->root_signature_desc = root_sig_deserializer->GetRootSignatureDesc(); + shader->root_signature_crc = binary_data.root_signature_crc; + shader->stages_bytecode = stages_bytecode; + + // Proceed to create descriptor sets. + for (uint32_t i = 0; i < binary_data.set_count; i++) { + uint32_t format = 0; // No format, default. + + Shader::Set &set = set_info.write[i]; + if (set.uniforms.size()) { + // Has data, needs an actual format;. + UniformSetFormat usformat; + usformat.uniform_info.resize(set.uniforms.size()); + for (int j = 0; j < set.uniforms.size(); j++) { + usformat.uniform_info.write[j] = set.uniforms[j].info; + } + RBMap<UniformSetFormat, uint32_t>::Element *E = uniform_set_format_cache.find(usformat); + if (E) { + format = E->get(); + } else { + format = uniform_set_format_cache.size() + 1; + E = uniform_set_format_cache.insert(usformat, format); + uniform_set_format_cache_reverse.push_back(E); + DEV_ASSERT(uniform_set_format_cache_reverse.size() == uniform_set_format_cache.size()); + } + } + + shader->sets.push_back(set); + shader->set_formats.push_back(format); + } + +#ifdef DEV_ENABLED + set_resource_name(id, "RID:" + itos(id.get_id())); +#endif + return id; +} + +RID RenderingDeviceD3D12::shader_create_placeholder() { + Shader shader; + return shader_owner.make_rid(shader); +} + +uint64_t RenderingDeviceD3D12::shader_get_vertex_input_attribute_mask(RID p_shader) { + _THREAD_SAFE_METHOD_ + + const Shader *shader = shader_owner.get_or_null(p_shader); + ERR_FAIL_NULL_V(shader, 0); + return shader->vertex_input_mask; +} + +/******************/ +/**** UNIFORMS ****/ +/******************/ + +RID RenderingDeviceD3D12::uniform_buffer_create(uint32_t p_size_bytes, const Vector<uint8_t> &p_data) { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND_V(p_data.size() && (uint32_t)p_data.size() != p_size_bytes, RID()); + + Buffer buffer; + Error err = _buffer_allocate(&buffer, p_size_bytes, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER, D3D12_HEAP_TYPE_DEFAULT); + ERR_FAIL_COND_V(err != OK, RID()); + + if (p_data.size()) { + uint64_t data_size = p_data.size(); + const uint8_t *r = p_data.ptr(); + _buffer_update(&buffer, 0, r, data_size); + } + RID id = uniform_buffer_owner.make_rid(buffer); +#ifdef DEV_ENABLED + set_resource_name(id, "RID:" + itos(id.get_id())); +#endif + return id; +} + +RID RenderingDeviceD3D12::storage_buffer_create(uint32_t p_size_bytes, const Vector<uint8_t> &p_data, BitField<StorageBufferUsage> p_usage) { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND_V(p_data.size() && (uint32_t)p_data.size() != p_size_bytes, RID()); + + Buffer buffer; + D3D12_RESOURCE_STATES states = D3D12_RESOURCE_STATE_COPY_SOURCE | D3D12_RESOURCE_STATE_COPY_DEST | D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + if (p_usage.has_flag(STORAGE_BUFFER_USAGE_DISPATCH_INDIRECT)) { + states |= D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + } + Error err = _buffer_allocate(&buffer, p_size_bytes, states, D3D12_HEAP_TYPE_DEFAULT); + ERR_FAIL_COND_V(err != OK, RID()); + + if (p_data.size()) { + uint64_t data_size = p_data.size(); + const uint8_t *r = p_data.ptr(); + _buffer_update(&buffer, 0, r, data_size); + } + return storage_buffer_owner.make_rid(buffer); +} + +RID RenderingDeviceD3D12::texture_buffer_create(uint32_t p_size_elements, DataFormat p_format, const Vector<uint8_t> &p_data) { + _THREAD_SAFE_METHOD_ + + uint32_t element_size = get_format_vertex_size(p_format); + ERR_FAIL_COND_V_MSG(element_size == 0, RID(), "Format requested is not supported for texture buffers"); + uint64_t size_bytes = uint64_t(element_size) * p_size_elements; + + ERR_FAIL_COND_V(p_data.size() && (uint32_t)p_data.size() != size_bytes, RID()); + + TextureBuffer texture_buffer; + Error err = _buffer_allocate(&texture_buffer.buffer, size_bytes, D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE, D3D12_HEAP_TYPE_DEFAULT); + ERR_FAIL_COND_V(err != OK, RID()); + + if (p_data.size()) { + uint64_t data_size = p_data.size(); + const uint8_t *r = p_data.ptr(); + _buffer_update(&texture_buffer.buffer, 0, r, data_size); + } + + // Allocate the view. + RID id = texture_buffer_owner.make_rid(texture_buffer); +#ifdef DEV_ENABLED + set_resource_name(id, "RID:" + itos(id.get_id())); +#endif + return id; +} + +Error RenderingDeviceD3D12::DescriptorsHeap::allocate(ID3D12Device *p_device, D3D12_DESCRIPTOR_HEAP_TYPE p_type, uint32_t p_descriptor_count, bool p_for_gpu) { + ERR_FAIL_COND_V(heap, ERR_ALREADY_EXISTS); + ERR_FAIL_COND_V(p_descriptor_count == 0, ERR_INVALID_PARAMETER); + + handle_size = p_device->GetDescriptorHandleIncrementSize(p_type); + + desc.Type = p_type; + desc.NumDescriptors = p_descriptor_count; + desc.Flags = p_for_gpu ? D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE : D3D12_DESCRIPTOR_HEAP_FLAG_NONE; + HRESULT res = p_device->CreateDescriptorHeap(&desc, IID_PPV_ARGS(heap.GetAddressOf())); + ERR_FAIL_COND_V_MSG(res, ERR_CANT_CREATE, "CreateDescriptorHeap failed with error " + vformat("0x%08ux", res) + "."); + + return OK; +} + +RenderingDeviceD3D12::DescriptorsHeap::Walker RenderingDeviceD3D12::DescriptorsHeap::make_walker() const { + Walker walker; + walker.handle_size = handle_size; + walker.handle_count = desc.NumDescriptors; + if (heap) { + walker.first_cpu_handle = heap->GetCPUDescriptorHandleForHeapStart(); + if ((desc.Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE)) { + walker.first_gpu_handle = heap->GetGPUDescriptorHandleForHeapStart(); + } + } + return walker; +} + +void RenderingDeviceD3D12::DescriptorsHeap::Walker::advance(uint32_t p_count) { + ERR_FAIL_COND_MSG(handle_index + p_count > handle_count, "Would advance past EOF."); + handle_index += p_count; +} + +D3D12_CPU_DESCRIPTOR_HANDLE RenderingDeviceD3D12::DescriptorsHeap::Walker::get_curr_cpu_handle() { + ERR_FAIL_COND_V_MSG(is_at_eof(), D3D12_CPU_DESCRIPTOR_HANDLE(), "Heap walker is at EOF."); + return D3D12_CPU_DESCRIPTOR_HANDLE{ first_cpu_handle.ptr + handle_index * handle_size }; +} + +D3D12_GPU_DESCRIPTOR_HANDLE RenderingDeviceD3D12::DescriptorsHeap::Walker::get_curr_gpu_handle() { + ERR_FAIL_COND_V_MSG(!first_gpu_handle.ptr, D3D12_GPU_DESCRIPTOR_HANDLE(), "Can't provide a GPU handle from a non-GPU descriptors heap."); + ERR_FAIL_COND_V_MSG(is_at_eof(), D3D12_GPU_DESCRIPTOR_HANDLE(), "Heap walker is at EOF."); + return D3D12_GPU_DESCRIPTOR_HANDLE{ first_gpu_handle.ptr + handle_index * handle_size }; +} + +static void _add_descriptor_count_for_uniform(RenderingDevice::UniformType p_type, uint32_t p_binding_length, bool p_dobule_srv_uav_ambiguous, uint32_t &r_num_resources, uint32_t &r_num_samplers, bool &r_srv_uav_ambiguity) { + r_srv_uav_ambiguity = false; + + // Some resource types can be SRV or UAV, depending on what NIR-DXIL decided for a specific shader variant. + // The goal is to generate both SRV and UAV for the descriptor sets' heaps and copy only the relevant one + // to the frame descriptor heap at binding time. + // [[SRV_UAV_AMBIGUITY]] + + switch (p_type) { + case RenderingDevice::UNIFORM_TYPE_SAMPLER: { + r_num_samplers += p_binding_length; + } break; + case RenderingDevice::UNIFORM_TYPE_SAMPLER_WITH_TEXTURE: + case RenderingDevice::UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER: { + r_num_resources += p_binding_length; + r_num_samplers += p_binding_length; + } break; + case RenderingDevice::UNIFORM_TYPE_UNIFORM_BUFFER: { + r_num_resources += 1; + } break; + case RenderingDevice::UNIFORM_TYPE_STORAGE_BUFFER: { + r_num_resources += p_dobule_srv_uav_ambiguous ? 2 : 1; + r_srv_uav_ambiguity = true; + } break; + case RenderingDevice::UNIFORM_TYPE_IMAGE: { + r_num_resources += p_binding_length * (p_dobule_srv_uav_ambiguous ? 2 : 1); + r_srv_uav_ambiguity = true; + } break; + default: { + r_num_resources += p_binding_length; + } + } +} + +RID RenderingDeviceD3D12::uniform_set_create(const Vector<Uniform> &p_uniforms, RID p_shader, uint32_t p_shader_set) { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND_V(p_uniforms.size() == 0, RID()); + + Shader *shader = shader_owner.get_or_null(p_shader); + ERR_FAIL_NULL_V(shader, RID()); + + ERR_FAIL_COND_V_MSG(p_shader_set >= (uint32_t)shader->sets.size() || shader->sets[p_shader_set].uniforms.size() == 0, RID(), + "Desired set (" + itos(p_shader_set) + ") not used by shader."); + // See that all sets in shader are satisfied. + + const Shader::Set &set = shader->sets[p_shader_set]; + + uint32_t uniform_count = p_uniforms.size(); + const Uniform *uniforms = p_uniforms.ptr(); + + uint32_t set_uniform_count = set.uniforms.size(); + const Shader::ShaderUniformInfo *set_uniforms = set.uniforms.ptr(); + + // Do a first pass to count resources and samplers, and error checking. + uint32_t num_resource_descs = 0; + uint32_t num_sampler_descs = 0; + LocalVector<int> uniform_indices; + uniform_indices.resize(set_uniform_count); + for (uint32_t i = 0; i < set_uniform_count; i++) { + const UniformInfo &set_uniform = set_uniforms[i].info; + int uniform_idx = -1; + for (int j = 0; j < (int)uniform_count; j++) { + if (uniforms[j].binding == set_uniform.binding) { + uniform_idx = j; + } + } + ERR_FAIL_COND_V_MSG(uniform_idx == -1, RID(), + "All the shader bindings for the given set must be covered by the uniforms provided. Binding (" + itos(set_uniform.binding) + "), set (" + itos(p_shader_set) + ") was not provided."); + uniform_indices[i] = uniform_idx; + + const Uniform &uniform = uniforms[uniform_idx]; + ERR_FAIL_COND_V_MSG(uniform.uniform_type != set_uniform.type, RID(), + "Mismatch uniform type for binding (" + itos(set_uniform.binding) + "), set (" + itos(p_shader_set) + "). Expected '" + shader_uniform_names[set_uniform.type] + "', supplied: '" + shader_uniform_names[uniform.uniform_type] + "'."); + + // Since the uniform set may be created for a shader different than the one that will be actually bound, + // which may have a different set of uniforms optimized out, the stages mask we can check now is not reliable. + // Therefore, we can't make any assumptions here about descriptors that we may not need to create, + // pixel or vertex-only shader resource states, etc. + + bool srv_uav_ambiguity = false; + _add_descriptor_count_for_uniform(uniform.uniform_type, set_uniform.length, true, num_resource_descs, num_sampler_descs, srv_uav_ambiguity); + } + + struct { + DescriptorsHeap resources; + DescriptorsHeap samplers; + } desc_heaps; +#ifdef DEV_ENABLED + LocalVector<UniformSet::ResourceDescInfo> resources_desc_info; +#endif + + if (num_resource_descs) { + Error err = desc_heaps.resources.allocate(device.Get(), D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, num_resource_descs, false); + ERR_FAIL_COND_V(err, RID()); + } + if (num_sampler_descs) { + Error err = desc_heaps.samplers.allocate(device.Get(), D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, num_sampler_descs, false); + ERR_FAIL_COND_V(err, RID()); + } + struct { + DescriptorsHeap::Walker resources; + DescriptorsHeap::Walker samplers; + } desc_heap_walkers; + desc_heap_walkers.resources = desc_heaps.resources.make_walker(); + desc_heap_walkers.samplers = desc_heaps.samplers.make_walker(); + + // Used for verification to make sure a uniform set does not use a framebuffer bound texture. + LocalVector<UniformSet::AttachableTexture> attachable_textures; + struct RIDState { + bool is_buffer = false; + uint64_t shader_uniform_idx_mask = 0; + ResourceState state; + }; + HashMap<Resource *, RIDState> resource_states; + + for (uint32_t i = 0; i < set_uniform_count; i++) { + const Shader::ShaderUniformInfo &set_uniform = set_uniforms[i]; + const Uniform &uniform = uniforms[uniform_indices[i]]; + + // Stages defined in the shader may be missing for a uniform due to the optimizer, + // but the opposite (extraneous stages present in the uniform stages mask) would be an error. + DEV_ASSERT(!(shader->is_compute && (set_uniform.binding.stages & (SHADER_STAGE_VERTEX_BIT | SHADER_STAGE_FRAGMENT_BIT)))); + DEV_ASSERT(!(!shader->is_compute && (set_uniform.binding.stages & SHADER_STAGE_COMPUTE_BIT))); + + switch (uniform.uniform_type) { + case UNIFORM_TYPE_SAMPLER: { + if (uniform.get_id_count() != (uint32_t)set_uniform.info.length) { + if (set_uniform.info.length > 1) { + ERR_FAIL_V_MSG(RID(), "Sampler (binding: " + itos(uniform.binding) + ") is an array of (" + itos(set_uniform.info.length) + ") sampler elements, so it should be provided equal number of sampler IDs to satisfy it (IDs provided: " + itos(uniform.get_id_count()) + ")."); + } else { + ERR_FAIL_V_MSG(RID(), "Sampler (binding: " + itos(uniform.binding) + ") should provide one ID referencing a sampler (IDs provided: " + itos(uniform.get_id_count()) + ")."); + } + } + + for (uint32_t j = 0; j < uniform.get_id_count(); j++) { + D3D12_SAMPLER_DESC *sampler_desc = sampler_owner.get_or_null(uniform.get_id(j)); + ERR_FAIL_COND_V_MSG(!sampler_desc, RID(), "Sampler (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid sampler."); + + device->CreateSampler(sampler_desc, desc_heap_walkers.samplers.get_curr_cpu_handle()); + desc_heap_walkers.samplers.advance(); + } + } break; + case UNIFORM_TYPE_SAMPLER_WITH_TEXTURE: { + if (uniform.get_id_count() != (uint32_t)set_uniform.info.length * 2) { + if (set_uniform.info.length > 1) { + ERR_FAIL_V_MSG(RID(), "SamplerTexture (binding: " + itos(uniform.binding) + ") is an array of (" + itos(set_uniform.info.length) + ") sampler&texture elements, so it should provided twice the amount of IDs (sampler,texture pairs) to satisfy it (IDs provided: " + itos(uniform.get_id_count()) + ")."); + } else { + ERR_FAIL_V_MSG(RID(), "SamplerTexture (binding: " + itos(uniform.binding) + ") should provide two IDs referencing a sampler and then a texture (IDs provided: " + itos(uniform.get_id_count()) + ")."); + } + } + + for (uint32_t j = 0; j < uniform.get_id_count(); j += 2) { + D3D12_SAMPLER_DESC *sampler_desc = sampler_owner.get_or_null(uniform.get_id(j)); + ERR_FAIL_COND_V_MSG(!sampler_desc, RID(), "SamplerTexture (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid sampler."); + + RID rid = uniform.get_id(j + 1); + Texture *texture = texture_owner.get_or_null(rid); + ERR_FAIL_COND_V_MSG(!texture, RID(), "SamplerTexture (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture."); + + ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_SAMPLING_BIT), RID(), + "Texture (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") needs the TEXTURE_USAGE_SAMPLING_BIT usage flag set in order to be used as uniform."); + + device->CreateSampler(sampler_desc, desc_heap_walkers.samplers.get_curr_cpu_handle()); + desc_heap_walkers.samplers.advance(); + device->CreateShaderResourceView(texture->resource, &texture->srv_desc, desc_heap_walkers.resources.get_curr_cpu_handle()); +#ifdef DEV_ENABLED + resources_desc_info.push_back({ D3D12_DESCRIPTOR_RANGE_TYPE_SRV, texture->srv_desc.ViewDimension }); +#endif + desc_heap_walkers.resources.advance(); + + RIDState &rs = resource_states[texture]; + rs.shader_uniform_idx_mask |= ((uint64_t)1 << i); + rs.state.extend(D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE); + + if (texture->usage_flags & (TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | TEXTURE_USAGE_INPUT_ATTACHMENT_BIT)) { + UniformSet::AttachableTexture attachable_texture; + attachable_texture.bind = set_uniform.info.binding; + attachable_texture.texture = texture->owner.is_valid() ? texture->owner : uniform.get_id(j + 1); + attachable_textures.push_back(attachable_texture); + } + + DEV_ASSERT(!texture->owner.is_valid() || texture_owner.get_or_null(texture->owner)); + } + } break; + case UNIFORM_TYPE_TEXTURE: { + if (uniform.get_id_count() != (uint32_t)set_uniform.info.length) { + if (set_uniform.info.length > 1) { + ERR_FAIL_V_MSG(RID(), "Texture (binding: " + itos(uniform.binding) + ") is an array of (" + itos(set_uniform.info.length) + ") textures, so it should be provided equal number of texture IDs to satisfy it (IDs provided: " + itos(uniform.get_id_count()) + ")."); + } else { + ERR_FAIL_V_MSG(RID(), "Texture (binding: " + itos(uniform.binding) + ") should provide one ID referencing a texture (IDs provided: " + itos(uniform.get_id_count()) + ")."); + } + } + + for (uint32_t j = 0; j < uniform.get_id_count(); j++) { + RID rid = uniform.get_id(j); + Texture *texture = texture_owner.get_or_null(rid); + ERR_FAIL_COND_V_MSG(!texture, RID(), "Texture (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture."); + + ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_SAMPLING_BIT), RID(), + "Texture (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") needs the TEXTURE_USAGE_SAMPLING_BIT usage flag set in order to be used as uniform."); + + device->CreateShaderResourceView(texture->resource, &texture->srv_desc, desc_heap_walkers.resources.get_curr_cpu_handle()); +#ifdef DEV_ENABLED + resources_desc_info.push_back({ D3D12_DESCRIPTOR_RANGE_TYPE_SRV, texture->srv_desc.ViewDimension }); +#endif + desc_heap_walkers.resources.advance(); + + RIDState &rs = resource_states[texture]; + rs.shader_uniform_idx_mask |= ((uint64_t)1 << i); + rs.state.extend(D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE); + + if ((texture->usage_flags & (TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | TEXTURE_USAGE_INPUT_ATTACHMENT_BIT))) { + UniformSet::AttachableTexture attachable_texture; + attachable_texture.bind = set_uniform.info.binding; + attachable_texture.texture = texture->owner.is_valid() ? texture->owner : uniform.get_id(j); + attachable_textures.push_back(attachable_texture); + } + + DEV_ASSERT(!texture->owner.is_valid() || texture_owner.get_or_null(texture->owner)); + } + } break; + case UNIFORM_TYPE_IMAGE: { + if (uniform.get_id_count() != (uint32_t)set_uniform.info.length) { + if (set_uniform.info.length > 1) { + ERR_FAIL_V_MSG(RID(), "Image (binding: " + itos(uniform.binding) + ") is an array of (" + itos(set_uniform.info.length) + ") textures, so it should be provided equal number of texture IDs to satisfy it (IDs provided: " + itos(uniform.get_id_count()) + ")."); + } else { + ERR_FAIL_V_MSG(RID(), "Image (binding: " + itos(uniform.binding) + ") should provide one ID referencing a texture (IDs provided: " + itos(uniform.get_id_count()) + ")."); + } + } + + for (uint32_t j = 0; j < uniform.get_id_count(); j++) { + RID rid = uniform.get_id(j); + Texture *texture = texture_owner.get_or_null(rid); + + ERR_FAIL_COND_V_MSG(!texture, RID(), + "Image (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture."); + + ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_STORAGE_BIT), RID(), + "Image (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") needs the TEXTURE_USAGE_STORAGE_BIT usage flag set in order to be used as uniform."); + + RIDState &rs = resource_states[texture]; + rs.shader_uniform_idx_mask |= ((uint64_t)1 << i); + rs.state.extend(D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + } + + // SRVs first. [[SRV_UAV_AMBIGUITY]] + for (uint32_t j = 0; j < uniform.get_id_count(); j++) { + RID rid = uniform.get_id(j); + Texture *texture = texture_owner.get_or_null(rid); + + ERR_FAIL_COND_V_MSG(!texture, RID(), + "Image (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture."); + + ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_STORAGE_BIT), RID(), + "Image (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") needs the TEXTURE_USAGE_STORAGE_BIT usage flag set in order to be used as uniform."); + + device->CreateShaderResourceView(texture->resource, &texture->srv_desc, desc_heap_walkers.resources.get_curr_cpu_handle()); +#ifdef DEV_ENABLED + resources_desc_info.push_back({ D3D12_DESCRIPTOR_RANGE_TYPE_SRV, texture->srv_desc.ViewDimension }); +#endif + desc_heap_walkers.resources.advance(); + + DEV_ASSERT(!texture->owner.is_valid() || texture_owner.get_or_null(texture->owner)); + } + + // UAVs then. [[SRV_UAV_AMBIGUITY]] + for (uint32_t j = 0; j < uniform.get_id_count(); j++) { + RID rid = uniform.get_id(j); + Texture *texture = texture_owner.get_or_null(rid); + + device->CreateUnorderedAccessView(texture->resource, nullptr, &texture->uav_desc, desc_heap_walkers.resources.get_curr_cpu_handle()); +#ifdef DEV_ENABLED + resources_desc_info.push_back({ D3D12_DESCRIPTOR_RANGE_TYPE_UAV, {} }); +#endif + desc_heap_walkers.resources.advance(); + } + } break; + case UNIFORM_TYPE_TEXTURE_BUFFER: { + if (uniform.get_id_count() != (uint32_t)set_uniform.info.length) { + if (set_uniform.info.length > 1) { + ERR_FAIL_V_MSG(RID(), "Buffer (binding: " + itos(uniform.binding) + ") is an array of (" + itos(set_uniform.info.length) + ") texture buffer elements, so it should be provided equal number of texture buffer IDs to satisfy it (IDs provided: " + itos(uniform.get_id_count()) + ")."); + } else { + ERR_FAIL_V_MSG(RID(), "Buffer (binding: " + itos(uniform.binding) + ") should provide one ID referencing a texture buffer (IDs provided: " + itos(uniform.get_id_count()) + ")."); + } + } + + for (uint32_t j = 0; j < uniform.get_id_count(); j++) { + TextureBuffer *buffer = texture_buffer_owner.get_or_null(uniform.get_id(j)); + ERR_FAIL_COND_V_MSG(!buffer, RID(), "Texture Buffer (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture buffer."); + + CRASH_NOW_MSG("Unimplemented!"); + } + } break; + case UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER: { + CRASH_NOW(); + if (uniform.get_id_count() != (uint32_t)set_uniform.info.length * 2) { + if (set_uniform.info.length > 1) { + ERR_FAIL_V_MSG(RID(), "SamplerBuffer (binding: " + itos(uniform.binding) + ") is an array of (" + itos(set_uniform.info.length) + ") sampler buffer elements, so it should provided twice the amount of IDs (sampler,buffer pairs) to satisfy it (IDs provided: " + itos(uniform.get_id_count()) + ")."); + } else { + ERR_FAIL_V_MSG(RID(), "SamplerBuffer (binding: " + itos(uniform.binding) + ") should provide two IDs referencing a sampler and then a texture buffer (IDs provided: " + itos(uniform.get_id_count()) + ")."); + } + } + + for (uint32_t j = 0; j < uniform.get_id_count(); j += 2) { + D3D12_SAMPLER_DESC *sampler_desc = sampler_owner.get_or_null(uniform.get_id(j)); + ERR_FAIL_COND_V_MSG(!sampler_desc, RID(), "SamplerBuffer (binding: " + itos(uniform.binding) + ", index " + itos(j + 1) + ") is not a valid sampler."); + + TextureBuffer *buffer = texture_buffer_owner.get_or_null(uniform.get_id(j + 1)); + ERR_FAIL_COND_V_MSG(!buffer, RID(), "SamplerBuffer (binding: " + itos(uniform.binding) + ", index " + itos(j + 1) + ") is not a valid texture buffer."); + + device->CreateSampler(sampler_desc, desc_heap_walkers.samplers.get_curr_cpu_handle()); + desc_heap_walkers.samplers.advance(); + + CRASH_NOW_MSG("Unimplemented!"); + } + } break; + case UNIFORM_TYPE_IMAGE_BUFFER: { + // Todo. + + } break; + case UNIFORM_TYPE_UNIFORM_BUFFER: { + ERR_FAIL_COND_V_MSG(uniform.get_id_count() != 1, RID(), + "Uniform buffer supplied (binding: " + itos(uniform.binding) + ") must provide one ID (" + itos(uniform.get_id_count()) + " provided)."); + + RID rid = uniform.get_id(0); + Buffer *buffer = uniform_buffer_owner.get_or_null(rid); + ERR_FAIL_COND_V_MSG(!buffer, RID(), "Uniform buffer supplied (binding: " + itos(uniform.binding) + ") is invalid."); + + ERR_FAIL_COND_V_MSG(buffer->size < (uint32_t)set_uniform.info.length, RID(), + "Uniform buffer supplied (binding: " + itos(uniform.binding) + ") size (" + itos(buffer->size) + " is smaller than size of shader uniform: (" + itos(set_uniform.info.length) + ")."); + + D3D12_CONSTANT_BUFFER_VIEW_DESC cbv_desc = {}; + cbv_desc.BufferLocation = buffer->resource->GetGPUVirtualAddress(); + cbv_desc.SizeInBytes = ALIGN(buffer->size, 256); + device->CreateConstantBufferView(&cbv_desc, desc_heap_walkers.resources.get_curr_cpu_handle()); + desc_heap_walkers.resources.advance(); +#ifdef DEV_ENABLED + resources_desc_info.push_back({ D3D12_DESCRIPTOR_RANGE_TYPE_CBV, {} }); +#endif + + RIDState &rs = resource_states[buffer]; + rs.is_buffer = true; + rs.shader_uniform_idx_mask |= ((uint64_t)1 << i); + rs.state.extend(D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER); + } break; + case UNIFORM_TYPE_STORAGE_BUFFER: { + ERR_FAIL_COND_V_MSG(uniform.get_id_count() != 1, RID(), + "Storage buffer supplied (binding: " + itos(uniform.binding) + ") must provide one ID (" + itos(uniform.get_id_count()) + " provided)."); + + RID rid = uniform.get_id(0); + Buffer *buffer = nullptr; + + if (storage_buffer_owner.owns(rid)) { + buffer = storage_buffer_owner.get_or_null(rid); + } else if (vertex_buffer_owner.owns(rid)) { + buffer = vertex_buffer_owner.get_or_null(rid); + // Due to [[SRV_UAV_AMBIGUITY]] we can't make this check because it wouldn't make sense in the case of an SRV (r/o storage buffer). + //ERR_FAIL_COND_V_MSG(!(buffer->usage & D3D12_RESOURCE_STATE_UNORDERED_ACCESS), RID(), "Vertex buffer supplied (binding: " + itos(uniform.binding) + ") was not created with storage flag."); + } + ERR_FAIL_COND_V_MSG(!buffer, RID(), "Storage buffer supplied (binding: " + itos(uniform.binding) + ") is invalid."); + + // If 0, then it's sized at link time. + ERR_FAIL_COND_V_MSG(set_uniform.info.length > 0 && buffer->size != (uint32_t)set_uniform.info.length, RID(), + "Storage buffer supplied (binding: " + itos(uniform.binding) + ") size (" + itos(buffer->size) + " does not match size of shader uniform: (" + itos(set_uniform.info.length) + ")."); + + RIDState &rs = resource_states[buffer]; + rs.shader_uniform_idx_mask |= ((uint64_t)1 << i); + rs.is_buffer = true; + rs.state.extend(D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + + // SRV first. [[SRV_UAV_AMBIGUITY]] + { + D3D12_SHADER_RESOURCE_VIEW_DESC srv_desc = {}; + srv_desc.Format = DXGI_FORMAT_R32_TYPELESS; + srv_desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + srv_desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv_desc.Buffer.FirstElement = 0; + srv_desc.Buffer.NumElements = (buffer->size + 3) / 4; + srv_desc.Buffer.StructureByteStride = 0; + srv_desc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + device->CreateShaderResourceView(buffer->resource, &srv_desc, desc_heap_walkers.resources.get_curr_cpu_handle()); +#ifdef DEV_ENABLED + resources_desc_info.push_back({ D3D12_DESCRIPTOR_RANGE_TYPE_SRV, srv_desc.ViewDimension }); +#endif + desc_heap_walkers.resources.advance(); + } + + // UAV then. [[SRV_UAV_AMBIGUITY]] + { + if ((buffer->usage & D3D12_RESOURCE_STATE_UNORDERED_ACCESS)) { + D3D12_UNORDERED_ACCESS_VIEW_DESC uav_desc = {}; + uav_desc.Format = DXGI_FORMAT_R32_TYPELESS; + uav_desc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + uav_desc.Buffer.FirstElement = 0; + uav_desc.Buffer.NumElements = (buffer->size + 3) / 4; + uav_desc.Buffer.StructureByteStride = 0; + uav_desc.Buffer.CounterOffsetInBytes = 0; + uav_desc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + device->CreateUnorderedAccessView(buffer->resource, nullptr, &uav_desc, desc_heap_walkers.resources.get_curr_cpu_handle()); +#ifdef DEV_ENABLED + resources_desc_info.push_back({ D3D12_DESCRIPTOR_RANGE_TYPE_UAV, {} }); +#endif + } else { + // If can't transition to UAV, leave this one empty since it won't be + // used, and trying to create an UAV view would trigger a validation error. + } + + desc_heap_walkers.resources.advance(); + } + } break; + case UNIFORM_TYPE_INPUT_ATTACHMENT: { + ERR_FAIL_COND_V_MSG(shader->is_compute, RID(), "InputAttachment (binding: " + itos(uniform.binding) + ") supplied for compute shader (this is not allowed)."); + + if (uniform.get_id_count() != (uint32_t)set_uniform.info.length) { + if (set_uniform.info.length > 1) { + ERR_FAIL_V_MSG(RID(), "InputAttachment (binding: " + itos(uniform.binding) + ") is an array of (" + itos(set_uniform.info.length) + ") textures, so it should be provided equal number of texture IDs to satisfy it (IDs provided: " + itos(uniform.get_id_count()) + ")."); + } else { + ERR_FAIL_V_MSG(RID(), "InputAttachment (binding: " + itos(uniform.binding) + ") should provide one ID referencing a texture (IDs provided: " + itos(uniform.get_id_count()) + ")."); + } + } + + for (uint32_t j = 0; j < uniform.get_id_count(); j++) { + RID rid = uniform.get_id(j); + Texture *texture = texture_owner.get_or_null(rid); + ERR_FAIL_COND_V_MSG(!texture, RID(), + "InputAttachment (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture."); + + ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_SAMPLING_BIT), RID(), + "InputAttachment (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") needs the TEXTURE_USAGE_SAMPLING_BIT usage flag set in order to be used as uniform."); + + device->CreateShaderResourceView(texture->resource, &texture->srv_desc, desc_heap_walkers.resources.get_curr_cpu_handle()); +#ifdef DEV_ENABLED + resources_desc_info.push_back({ D3D12_DESCRIPTOR_RANGE_TYPE_SRV, texture->srv_desc.ViewDimension }); +#endif + desc_heap_walkers.resources.advance(); + + RIDState &rs = resource_states[texture]; + rs.shader_uniform_idx_mask |= ((uint64_t)1 << i); + rs.state.extend(D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); + + DEV_ASSERT(!texture->owner.is_valid() || texture_owner.get_or_null(texture->owner)); + } + } break; + default: { + } + } + } + + DEV_ASSERT(desc_heap_walkers.resources.is_at_eof()); + DEV_ASSERT(desc_heap_walkers.samplers.is_at_eof()); + + UniformSet uniform_set; + uniform_set.desc_heaps.resources = desc_heaps.resources; + uniform_set.desc_heaps.samplers = desc_heaps.samplers; + uniform_set.format = shader->set_formats[p_shader_set]; + uniform_set.attachable_textures = attachable_textures; + uniform_set.shader_set = p_shader_set; + uniform_set.shader_id = p_shader; +#ifdef DEV_ENABLED + uniform_set._resources_desc_info = resources_desc_info; + uniform_set._shader = shader; +#endif + + { + uniform_set.resource_states.resize(resource_states.size()); + uint32_t i = 0; + for (const KeyValue<Resource *, RIDState> &E : resource_states) { + UniformSet::StateRequirement sr; + sr.resource = E.key; + sr.is_buffer = E.value.is_buffer; + sr.states = E.value.state.get_state_mask(); + sr.shader_uniform_idx_mask = E.value.shader_uniform_idx_mask; + uniform_set.resource_states.write[i] = sr; + i++; + } + } + + RID id = uniform_set_owner.make_rid(uniform_set); + // Add dependencies. + _add_dependency(id, p_shader); + for (uint32_t i = 0; i < uniform_count; i++) { + const Uniform &uniform = uniforms[i]; + int id_count = uniform.get_id_count(); + for (int j = 0; j < id_count; j++) { + _add_dependency(id, uniform.get_id(j)); + } + } + + return id; +} + +bool RenderingDeviceD3D12::uniform_set_is_valid(RID p_uniform_set) { + return uniform_set_owner.owns(p_uniform_set); +} + +void RenderingDeviceD3D12::uniform_set_set_invalidation_callback(RID p_uniform_set, InvalidationCallback p_callback, void *p_userdata) { + UniformSet *us = uniform_set_owner.get_or_null(p_uniform_set); + ERR_FAIL_NULL(us); + us->invalidated_callback = p_callback; + us->invalidated_callback_userdata = p_userdata; +} + +Error RenderingDeviceD3D12::buffer_copy(RID p_src_buffer, RID p_dst_buffer, uint32_t p_src_offset, uint32_t p_dst_offset, uint32_t p_size, BitField<BarrierMask> p_post_barrier) { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND_V_MSG(draw_list, ERR_INVALID_PARAMETER, + "Copying buffers is forbidden during creation of a draw list"); + ERR_FAIL_COND_V_MSG(compute_list, ERR_INVALID_PARAMETER, + "Copying buffers is forbidden during creation of a compute list"); + + Buffer *src_buffer = _get_buffer_from_owner(p_src_buffer); + if (!src_buffer) { + ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Source buffer argument is not a valid buffer of any type."); + } + + Buffer *dst_buffer = _get_buffer_from_owner(p_dst_buffer); + if (!dst_buffer) { + ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Destination buffer argument is not a valid buffer of any type."); + } + + // Validate the copy's dimensions for both buffers. + ERR_FAIL_COND_V_MSG((p_size + p_src_offset) > src_buffer->size, ERR_INVALID_PARAMETER, "Size is larger than the source buffer."); + ERR_FAIL_COND_V_MSG((p_size + p_dst_offset) > dst_buffer->size, ERR_INVALID_PARAMETER, "Size is larger than the destination buffer."); + + // Perform the copy. + + ID3D12GraphicsCommandList *command_list = frames[frame].draw_command_list.Get(); + + _resource_transition_batch(src_buffer, 0, 1, D3D12_RESOURCE_STATE_COPY_SOURCE); + _resource_transition_batch(src_buffer, 0, 1, D3D12_RESOURCE_STATE_COPY_DEST); + _resource_transitions_flush(command_list); + + command_list->CopyBufferRegion(dst_buffer->resource, p_dst_offset, src_buffer->resource, p_src_offset, p_size); + + return OK; +} + +Error RenderingDeviceD3D12::buffer_update(RID p_buffer, uint32_t p_offset, uint32_t p_size, const void *p_data, BitField<BarrierMask> p_post_barrier) { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND_V_MSG(draw_list, ERR_INVALID_PARAMETER, + "Updating buffers is forbidden during creation of a draw list"); + ERR_FAIL_COND_V_MSG(compute_list, ERR_INVALID_PARAMETER, + "Updating buffers is forbidden during creation of a compute list"); + + Buffer *buffer = _get_buffer_from_owner(p_buffer); + if (!buffer) { + ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Buffer argument is not a valid buffer of any type."); + } + + ERR_FAIL_COND_V_MSG(p_offset + p_size > buffer->size, ERR_INVALID_PARAMETER, + "Attempted to write buffer (" + itos((p_offset + p_size) - buffer->size) + " bytes) past the end."); + + ID3D12GraphicsCommandList *command_list = frames[frame].draw_command_list.Get(); + + _resource_transition_batch(buffer, 0, 1, D3D12_RESOURCE_STATE_COPY_DEST); + _resource_transitions_flush(command_list); + + Error err = _buffer_update(buffer, p_offset, (uint8_t *)p_data, p_size, p_post_barrier); + if (err) { + return err; + } + + return OK; +} + +Error RenderingDeviceD3D12::buffer_clear(RID p_buffer, uint32_t p_offset, uint32_t p_size, BitField<BarrierMask> p_post_barrier) { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND_V_MSG((p_size % 4) != 0, ERR_INVALID_PARAMETER, + "Size must be a multiple of four"); + ERR_FAIL_COND_V_MSG(draw_list, ERR_INVALID_PARAMETER, + "Updating buffers in is forbidden during creation of a draw list"); + ERR_FAIL_COND_V_MSG(compute_list, ERR_INVALID_PARAMETER, + "Updating buffers is forbidden during creation of a compute list"); + + Buffer *buffer = _get_buffer_from_owner(p_buffer); + if (!buffer) { + ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Buffer argument is not a valid buffer of any type."); + } + + ERR_FAIL_COND_V_MSG(p_offset + p_size > buffer->size, ERR_INVALID_PARAMETER, + "Attempted to write buffer (" + itos((p_offset + p_size) - buffer->size) + " bytes) past the end."); + + if (frames[frame].desc_heap_walkers.resources.is_at_eof()) { + if (!frames[frame].desc_heaps_exhausted_reported.resources) { + frames[frame].desc_heaps_exhausted_reported.resources = true; + ERR_FAIL_V_MSG(ERR_BUSY, + "Cannot clear buffer because there's no enough room in current frame's RESOURCE descriptors heap.\n" + "Please increase the value of the rendering/rendering_device/d3d12/max_resource_descriptors_per_frame project setting."); + } else { + return ERR_BUSY; + } + } + if (frames[frame].desc_heap_walkers.aux.is_at_eof()) { + if (!frames[frame].desc_heaps_exhausted_reported.aux) { + frames[frame].desc_heaps_exhausted_reported.aux = true; + ERR_FAIL_V_MSG(ERR_BUSY, + "Cannot clear buffer because there's no enough room in current frame's AUX descriptors heap.\n" + "Please increase the value of the rendering/rendering_device/d3d12/max_misc_descriptors_per_frame project setting."); + } else { + return ERR_BUSY; + } + } + + ID3D12GraphicsCommandList *command_list = frames[frame].draw_command_list.Get(); + + _resource_transition_batch(buffer, 0, 1, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + _resource_transitions_flush(command_list); + + D3D12_UNORDERED_ACCESS_VIEW_DESC uav_desc = {}; + uav_desc.Format = DXGI_FORMAT_R32_TYPELESS; + uav_desc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + uav_desc.Buffer.FirstElement = 0; + uav_desc.Buffer.NumElements = (buffer->size + 3) / 4; + uav_desc.Buffer.StructureByteStride = 0; + uav_desc.Buffer.CounterOffsetInBytes = 0; + uav_desc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + device->CreateUnorderedAccessView( + buffer->resource, + nullptr, + &uav_desc, + frames[frame].desc_heap_walkers.aux.get_curr_cpu_handle()); + + device->CopyDescriptorsSimple( + 1, + frames[frame].desc_heap_walkers.resources.get_curr_cpu_handle(), + frames[frame].desc_heap_walkers.aux.get_curr_cpu_handle(), + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + + static const UINT values[4] = {}; + command_list->ClearUnorderedAccessViewUint( + frames[frame].desc_heap_walkers.resources.get_curr_gpu_handle(), + frames[frame].desc_heap_walkers.aux.get_curr_cpu_handle(), + buffer->resource, + values, + 0, + nullptr); + + frames[frame].desc_heap_walkers.resources.advance(); + frames[frame].desc_heap_walkers.aux.advance(); + + return OK; +} + +Vector<uint8_t> RenderingDeviceD3D12::buffer_get_data(RID p_buffer, uint32_t p_offset, uint32_t p_size) { + _THREAD_SAFE_METHOD_ + + // Get the vulkan buffer and the potential stage/access possible. + Buffer *buffer = _get_buffer_from_owner(p_buffer); + if (!buffer) { + ERR_FAIL_V_MSG(Vector<uint8_t>(), "Buffer is either invalid or this type of buffer can't be retrieved. Only Index and Vertex buffers allow retrieving."); + } + + ID3D12GraphicsCommandList *command_list = frames[frame].draw_command_list.Get(); + + // Size of buffer to retrieve. + if (!p_size) { + p_size = buffer->size; + } else { + ERR_FAIL_COND_V_MSG(p_size + p_offset > buffer->size, Vector<uint8_t>(), + "Size is larger than the buffer."); + } + + _resource_transition_batch(buffer, 0, 1, D3D12_RESOURCE_STATE_COPY_SOURCE); + _resource_transitions_flush(command_list); + + Buffer tmp_buffer; + Error err = _buffer_allocate(&tmp_buffer, p_size, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_HEAP_TYPE_READBACK); + ERR_FAIL_COND_V(err != OK, Vector<uint8_t>()); + + command_list->CopyBufferRegion(tmp_buffer.resource, 0, buffer->resource, p_offset, p_size); + + // Flush everything so memory can be safely mapped. + _flush(true); + + void *buffer_mem; + HRESULT res = tmp_buffer.resource->Map(0, &VOID_RANGE, &buffer_mem); + ERR_FAIL_COND_V_MSG(res, Vector<uint8_t>(), "Map failed with error " + vformat("0x%08ux", res) + "."); + + Vector<uint8_t> buffer_data; + { + buffer_data.resize(buffer->size); + uint8_t *w = buffer_data.ptrw(); + memcpy(w, buffer_mem, buffer->size); + } + + tmp_buffer.resource->Unmap(0, &VOID_RANGE); + + _buffer_free(&tmp_buffer); + + return buffer_data; +} + +/*******************/ +/**** PIPELINES ****/ +/*******************/ + +Error RenderingDeviceD3D12::_apply_specialization_constants( + const Shader *p_shader, + const Vector<PipelineSpecializationConstant> &p_specialization_constants, + HashMap<ShaderStage, Vector<uint8_t>> &r_final_stages_bytecode) { + // If something needs to be patched, COW will do the trick. + r_final_stages_bytecode = p_shader->stages_bytecode; + uint32_t stages_re_sign_mask = 0; + for (const PipelineSpecializationConstant &psc : p_specialization_constants) { + if (!(p_shader->spirv_specialization_constants_ids_mask & (1 << psc.constant_id))) { + // This SC wasn't even in the original SPIR-V shader. + continue; + } + for (const Shader::SpecializationConstant &sc : p_shader->specialization_constants) { + if (psc.constant_id == sc.constant.constant_id) { + ERR_FAIL_COND_V_MSG(psc.type != sc.constant.type, ERR_INVALID_PARAMETER, "Specialization constant provided for id (" + itos(sc.constant.constant_id) + ") is of the wrong type."); + if (psc.int_value != sc.constant.int_value) { + stages_re_sign_mask |= _shader_patch_dxil_specialization_constant(psc.type, &psc.int_value, sc.stages_bit_offsets, r_final_stages_bytecode, false); + } + break; + } + } + } + // Re-sign patched stages. + for (KeyValue<ShaderStage, Vector<uint8_t>> &E : r_final_stages_bytecode) { + ShaderStage stage = E.key; + if ((stages_re_sign_mask & (1 << stage))) { + Vector<uint8_t> &bytecode = E.value; + bool sign_ok = _shader_sign_dxil_bytecode(stage, bytecode); + ERR_FAIL_COND_V(!sign_ok, ERR_QUERY_FAILED); + } + } + + return OK; +} + +#ifdef DEV_ENABLED +String RenderingDeviceD3D12::_build_pipeline_blob_filename( + const Vector<uint8_t> &p_blob, + const Shader *p_shader, + const Vector<PipelineSpecializationConstant> &p_specialization_constants, + const String &p_extra_name_suffix, + const String &p_forced_id) { + String id; + if (p_forced_id == "") { + HashingContext hc; + hc.start(HashingContext::HASH_MD5); + hc.update(p_blob); + Vector<uint8_t> hash_bin = hc.finish(); + String hash_str = String::hex_encode_buffer(hash_bin.ptr(), hash_bin.size()); + } else { + id = p_forced_id; + } + + Vector<String> sc_str_pieces; + for (const Shader::SpecializationConstant &sc : p_shader->specialization_constants) { + uint32_t int_value = sc.constant.int_value; + for (const PipelineSpecializationConstant &psc : p_specialization_constants) { + if (psc.constant_id == sc.constant.constant_id) { + int_value = psc.int_value; + break; + } + } + sc_str_pieces.push_back(itos(sc.constant.constant_id) + "=" + itos(int_value)); + } + + String res = p_shader->name.replace(":", "-"); + res += "." + id; + res += "." + String("_").join(sc_str_pieces); + if (p_extra_name_suffix != "") { + res += "." + p_extra_name_suffix; + } + return res; +} + +void RenderingDeviceD3D12::_save_pso_blob( + ID3D12PipelineState *p_pso, + const Shader *p_shader, + const Vector<PipelineSpecializationConstant> &p_specialization_constants) { + ComPtr<ID3DBlob> pso_blob; + p_pso->GetCachedBlob(pso_blob.GetAddressOf()); + Vector<uint8_t> pso_vector; + pso_vector.resize(pso_blob->GetBufferSize()); + memcpy(pso_vector.ptrw(), pso_blob->GetBufferPointer(), pso_blob->GetBufferSize()); + + String base_filename = _build_pipeline_blob_filename(pso_vector, p_shader, p_specialization_constants); + + Ref<FileAccess> fa = FileAccess::open("pso." + base_filename + ".bin", FileAccess::WRITE); + fa->store_buffer((const uint8_t *)pso_blob->GetBufferPointer(), pso_blob->GetBufferSize()); +} + +void RenderingDeviceD3D12::_save_stages_bytecode( + const HashMap<ShaderStage, Vector<uint8_t>> &p_stages_bytecode, + const Shader *p_shader, + const RID p_shader_rid, + const Vector<PipelineSpecializationConstant> &p_specialization_constants) { + for (const KeyValue<ShaderStage, Vector<uint8_t>> &E : p_stages_bytecode) { + ShaderStage stage = E.key; + const Vector<uint8_t> &bytecode = E.value; + + String base_filename = _build_pipeline_blob_filename(bytecode, p_shader, p_specialization_constants, shader_stage_names[stage], itos(p_shader_rid.get_id())); + + Ref<FileAccess> fa = FileAccess::open("dxil." + base_filename + ".bin", FileAccess::WRITE); + fa->store_buffer(bytecode.ptr(), bytecode.size()); + } +} +#endif + +/*************************/ +/**** RENDER PIPELINE ****/ +/*************************/ + +RID RenderingDeviceD3D12::render_pipeline_create(RID p_shader, FramebufferFormatID p_framebuffer_format, VertexFormatID p_vertex_format, RenderPrimitive p_render_primitive, const PipelineRasterizationState &p_rasterization_state, const PipelineMultisampleState &p_multisample_state, const PipelineDepthStencilState &p_depth_stencil_state, const PipelineColorBlendState &p_blend_state, BitField<PipelineDynamicStateFlags> p_dynamic_state_flags, uint32_t p_for_render_pass, const Vector<PipelineSpecializationConstant> &p_specialization_constants) { +#ifdef DEV_ENABLED +//#define DEBUG_CREATE_DEBUG_PSO +//#define DEBUG_SAVE_PSO_BLOBS +//#define DEBUG_SAVE_DXIL_BLOBS +#endif + _THREAD_SAFE_METHOD_ + + // Needs a shader. + Shader *shader = shader_owner.get_or_null(p_shader); + ERR_FAIL_NULL_V(shader, RID()); + + ERR_FAIL_COND_V_MSG(shader->is_compute, RID(), + "Compute shaders can't be used in render pipelines"); + + if (p_framebuffer_format == INVALID_ID) { + // If nothing provided, use an empty one (no attachments). + p_framebuffer_format = framebuffer_format_create(Vector<AttachmentFormat>()); + } + ERR_FAIL_COND_V(!framebuffer_formats.has(p_framebuffer_format), RID()); + const FramebufferFormat &fb_format = framebuffer_formats[p_framebuffer_format]; + const FramebufferPass &pass = fb_format.passes[p_for_render_pass]; + + { // Validate shader vs framebuffer. + + ERR_FAIL_COND_V_MSG(p_for_render_pass >= uint32_t(fb_format.passes.size()), RID(), "Render pass requested for pipeline creation (" + itos(p_for_render_pass) + ") is out of bounds"); + uint32_t output_mask = 0; + for (int i = 0; i < pass.color_attachments.size(); i++) { + if (pass.color_attachments[i] != FramebufferPass::ATTACHMENT_UNUSED) { + output_mask |= 1 << i; + } + } + ERR_FAIL_COND_V_MSG(shader->fragment_output_mask != output_mask, RID(), + "Mismatch fragment shader output mask (" + itos(shader->fragment_output_mask) + ") and framebuffer color output mask (" + itos(output_mask) + ") when binding both in render pipeline."); + } + + CD3DX12_PIPELINE_STATE_STREAM pipeline_desc; + RenderPipeline::DynamicParams dyn_params; + + // Attachment formats. + { + for (int i = 0; i < pass.color_attachments.size(); i++) { + int32_t attachment = pass.color_attachments[i]; + if (attachment == FramebufferPass::ATTACHMENT_UNUSED) { + (&pipeline_desc.RTVFormats)->RTFormats[i] = DXGI_FORMAT_UNKNOWN; + } else { + (&pipeline_desc.RTVFormats)->RTFormats[i] = d3d12_formats[fb_format.attachments[attachment].format].general_format; + } + } + (&pipeline_desc.RTVFormats)->NumRenderTargets = pass.color_attachments.size(); + + if (pass.depth_attachment == FramebufferPass::ATTACHMENT_UNUSED) { + pipeline_desc.DSVFormat = DXGI_FORMAT_UNKNOWN; + } else { + pipeline_desc.DSVFormat = d3d12_formats[fb_format.attachments[pass.depth_attachment].format].dsv_format; + } + } + + // Vertex. + if (p_vertex_format != INVALID_ID) { + // Uses vertices, else it does not. + ERR_FAIL_COND_V(!vertex_formats.has(p_vertex_format), RID()); + const VertexDescriptionCache &vd = vertex_formats[p_vertex_format]; + + (&pipeline_desc.InputLayout)->pInputElementDescs = vd.elements_desc.ptr(); + (&pipeline_desc.InputLayout)->NumElements = vd.elements_desc.size(); + + // Validate with inputs. + for (uint32_t i = 0; i < 64; i++) { + if (!(shader->vertex_input_mask & (1ULL << i))) { + continue; + } + bool found = false; + for (int j = 0; j < vd.vertex_formats.size(); j++) { + if (vd.vertex_formats[j].location == i) { + found = true; + } + } + + ERR_FAIL_COND_V_MSG(!found, RID(), + "Shader vertex input location (" + itos(i) + ") not provided in vertex input description for pipeline creation."); + } + + } else { + // Does not use vertices. + + ERR_FAIL_COND_V_MSG(shader->vertex_input_mask != 0, RID(), + "Shader contains vertex inputs, but no vertex input description was provided for pipeline creation."); + } + + // Input assembly & tessellation. + + ERR_FAIL_INDEX_V(p_render_primitive, RENDER_PRIMITIVE_MAX, RID()); + + static const D3D12_PRIMITIVE_TOPOLOGY_TYPE topology_types[RENDER_PRIMITIVE_MAX] = { + D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT, + D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE, + D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE, + D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE, + D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE, + D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + D3D12_PRIMITIVE_TOPOLOGY_TYPE_PATCH, + }; + + static const D3D12_PRIMITIVE_TOPOLOGY topologies[RENDER_PRIMITIVE_MAX] = { + D3D_PRIMITIVE_TOPOLOGY_POINTLIST, + D3D_PRIMITIVE_TOPOLOGY_LINELIST, + D3D_PRIMITIVE_TOPOLOGY_LINELIST_ADJ, + D3D_PRIMITIVE_TOPOLOGY_LINESTRIP, + D3D_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ, + D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, + D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ, + D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP, + D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ, + D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP, + D3D_PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST, + }; + + pipeline_desc.PrimitiveTopologyType = topology_types[p_render_primitive]; + if (p_render_primitive == RENDER_PRIMITIVE_TESSELATION_PATCH) { + ERR_FAIL_COND_V(p_rasterization_state.patch_control_points < 1 || p_rasterization_state.patch_control_points > 32, RID()); // Is there any way to get the true point count limit? + dyn_params.primitive_topology = (D3D12_PRIMITIVE_TOPOLOGY)((int)D3D_PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST + p_rasterization_state.patch_control_points); + } else { + dyn_params.primitive_topology = topologies[p_render_primitive]; + } + if (p_render_primitive == RENDER_PRIMITIVE_TRIANGLE_STRIPS_WITH_RESTART_INDEX) { + // TODO: This is right for 16-bit indices; for 32-bit there's a different enum value to set, but we don't know at this point. + pipeline_desc.IBStripCutValue = D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFF; + } else { + pipeline_desc.IBStripCutValue = D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED; + } + + // Rasterization. + (&pipeline_desc.RasterizerState)->DepthClipEnable = !p_rasterization_state.enable_depth_clamp; + // In D3D12, discard can be supported with some extra effort (empty pixel shader + disable depth/stencil test); that said, unsupported by now. + ERR_FAIL_COND_V(p_rasterization_state.discard_primitives, RID()); + (&pipeline_desc.RasterizerState)->FillMode = p_rasterization_state.wireframe ? D3D12_FILL_MODE_WIREFRAME : D3D12_FILL_MODE_SOLID; + static const D3D12_CULL_MODE cull_mode[3] = { + D3D12_CULL_MODE_NONE, + D3D12_CULL_MODE_FRONT, + D3D12_CULL_MODE_BACK, + }; + + ERR_FAIL_INDEX_V(p_rasterization_state.cull_mode, 3, RID()); + (&pipeline_desc.RasterizerState)->CullMode = cull_mode[p_rasterization_state.cull_mode]; + (&pipeline_desc.RasterizerState)->FrontCounterClockwise = p_rasterization_state.front_face == POLYGON_FRONT_FACE_COUNTER_CLOCKWISE; + // In D3D12, there's still a point in setting up depth bias with no depth buffer, but just zeroing (disabling) it all in such case is closer to Vulkan. + if (p_rasterization_state.depth_bias_enabled && fb_format.passes[p_for_render_pass].depth_attachment != FramebufferPass::ATTACHMENT_UNUSED) { + (&pipeline_desc.RasterizerState)->DepthBias = p_rasterization_state.depth_bias_constant_factor; + (&pipeline_desc.RasterizerState)->DepthBiasClamp = p_rasterization_state.depth_bias_clamp; + (&pipeline_desc.RasterizerState)->SlopeScaledDepthBias = p_rasterization_state.depth_bias_slope_factor; + } else { + (&pipeline_desc.RasterizerState)->DepthBias = 0; + (&pipeline_desc.RasterizerState)->DepthBiasClamp = 0.0f; + (&pipeline_desc.RasterizerState)->SlopeScaledDepthBias = 0.0f; + } + + (&pipeline_desc.RasterizerState)->ForcedSampleCount = 0; + (&pipeline_desc.RasterizerState)->ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF; + (&pipeline_desc.RasterizerState)->MultisampleEnable = rasterization_sample_count[p_multisample_state.sample_count] != 1; + (&pipeline_desc.RasterizerState)->AntialiasedLineEnable = true; + + // In D3D12, there's no line width. + ERR_FAIL_COND_V(!Math::is_equal_approx(p_rasterization_state.line_width, 1.0f), RID()); + + // Multisample. + ERR_FAIL_COND_V(p_multisample_state.enable_sample_shading, RID()); // How one enables this in D3D12? + if ((&pipeline_desc.RTVFormats)->NumRenderTargets || pipeline_desc.DSVFormat != DXGI_FORMAT_UNKNOWN) { + uint32_t sample_count = MIN( + fb_format.max_supported_sample_count, + rasterization_sample_count[p_multisample_state.sample_count]); + (&pipeline_desc.SampleDesc)->Count = sample_count; + } else { + (&pipeline_desc.SampleDesc)->Count = 1; + } + if ((&pipeline_desc.SampleDesc)->Count > 1) { + (&pipeline_desc.SampleDesc)->Quality = DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN; + } else { + (&pipeline_desc.SampleDesc)->Quality = 0; + } + if (p_multisample_state.sample_mask.size()) { + // Use sample mask. + ERR_FAIL_COND_V(rasterization_sample_count[p_multisample_state.sample_count] != (uint32_t)p_multisample_state.sample_mask.size(), RID()); + for (int i = 1; i < p_multisample_state.sample_mask.size(); i++) { + // In D3D12 there's a single sample mask for every pixel. + ERR_FAIL_COND_V(p_multisample_state.sample_mask[i] != p_multisample_state.sample_mask[0], RID()); + } + pipeline_desc.SampleMask = p_multisample_state.sample_mask[0]; + } else { + pipeline_desc.SampleMask = 0xffffffff; + } + + // Depth stencil. + + if (pass.depth_attachment == FramebufferPass::ATTACHMENT_UNUSED) { + (&pipeline_desc.DepthStencilState)->DepthEnable = false; + (&pipeline_desc.DepthStencilState)->StencilEnable = false; + } else { + (&pipeline_desc.DepthStencilState)->DepthEnable = p_depth_stencil_state.enable_depth_test; + (&pipeline_desc.DepthStencilState)->DepthWriteMask = p_depth_stencil_state.enable_depth_write ? D3D12_DEPTH_WRITE_MASK_ALL : D3D12_DEPTH_WRITE_MASK_ZERO; + ERR_FAIL_INDEX_V(p_depth_stencil_state.depth_compare_operator, COMPARE_OP_MAX, RID()); + (&pipeline_desc.DepthStencilState)->DepthFunc = compare_operators[p_depth_stencil_state.depth_compare_operator]; + (&pipeline_desc.DepthStencilState)->DepthBoundsTestEnable = p_depth_stencil_state.enable_depth_range; + (&pipeline_desc.DepthStencilState)->StencilEnable = p_depth_stencil_state.enable_stencil; + + // In D3D12 some elements can't be different across front and back. + ERR_FAIL_COND_V(p_depth_stencil_state.front_op.compare_mask != p_depth_stencil_state.back_op.compare_mask, RID()); + ERR_FAIL_COND_V(p_depth_stencil_state.front_op.write_mask != p_depth_stencil_state.back_op.write_mask, RID()); + ERR_FAIL_COND_V(p_depth_stencil_state.front_op.reference != p_depth_stencil_state.back_op.reference, RID()); + (&pipeline_desc.DepthStencilState)->StencilReadMask = p_depth_stencil_state.front_op.compare_mask; + (&pipeline_desc.DepthStencilState)->StencilWriteMask = p_depth_stencil_state.front_op.write_mask; + + ERR_FAIL_INDEX_V(p_depth_stencil_state.front_op.fail, STENCIL_OP_MAX, RID()); + (&pipeline_desc.DepthStencilState)->FrontFace.StencilFailOp = stencil_operations[p_depth_stencil_state.front_op.fail]; + ERR_FAIL_INDEX_V(p_depth_stencil_state.front_op.pass, STENCIL_OP_MAX, RID()); + (&pipeline_desc.DepthStencilState)->FrontFace.StencilPassOp = stencil_operations[p_depth_stencil_state.front_op.pass]; + ERR_FAIL_INDEX_V(p_depth_stencil_state.front_op.depth_fail, STENCIL_OP_MAX, RID()); + (&pipeline_desc.DepthStencilState)->FrontFace.StencilDepthFailOp = stencil_operations[p_depth_stencil_state.front_op.depth_fail]; + ERR_FAIL_INDEX_V(p_depth_stencil_state.front_op.compare, COMPARE_OP_MAX, RID()); + (&pipeline_desc.DepthStencilState)->FrontFace.StencilFunc = compare_operators[p_depth_stencil_state.front_op.compare]; + + ERR_FAIL_INDEX_V(p_depth_stencil_state.back_op.fail, STENCIL_OP_MAX, RID()); + (&pipeline_desc.DepthStencilState)->BackFace.StencilFailOp = stencil_operations[p_depth_stencil_state.back_op.fail]; + ERR_FAIL_INDEX_V(p_depth_stencil_state.back_op.pass, STENCIL_OP_MAX, RID()); + (&pipeline_desc.DepthStencilState)->BackFace.StencilPassOp = stencil_operations[p_depth_stencil_state.back_op.pass]; + ERR_FAIL_INDEX_V(p_depth_stencil_state.back_op.depth_fail, STENCIL_OP_MAX, RID()); + (&pipeline_desc.DepthStencilState)->BackFace.StencilDepthFailOp = stencil_operations[p_depth_stencil_state.back_op.depth_fail]; + ERR_FAIL_INDEX_V(p_depth_stencil_state.back_op.compare, COMPARE_OP_MAX, RID()); + (&pipeline_desc.DepthStencilState)->BackFace.StencilFunc = compare_operators[p_depth_stencil_state.back_op.compare]; + + dyn_params.depth_bounds_min = p_depth_stencil_state.enable_depth_range ? p_depth_stencil_state.depth_range_min : 0.0f; + dyn_params.depth_bounds_max = p_depth_stencil_state.enable_depth_range ? p_depth_stencil_state.depth_range_max : 1.0f; + dyn_params.stencil_reference = p_depth_stencil_state.front_op.reference; + } + + // Blend state. + (&pipeline_desc.BlendState)->AlphaToCoverageEnable = p_multisample_state.enable_alpha_to_coverage; + { + ERR_FAIL_COND_V(p_blend_state.attachments.size() < pass.color_attachments.size(), RID()); + + bool all_attachments_same_blend = true; + for (int i = 0; i < pass.color_attachments.size(); i++) { + const PipelineColorBlendState::Attachment &bs = p_blend_state.attachments[i]; + D3D12_RENDER_TARGET_BLEND_DESC &bd = (&pipeline_desc.BlendState)->RenderTarget[i]; + + bd.BlendEnable = bs.enable_blend; + bd.LogicOpEnable = p_blend_state.enable_logic_op; + bd.LogicOp = logic_operations[p_blend_state.logic_op]; + + ERR_FAIL_INDEX_V(bs.src_color_blend_factor, BLEND_FACTOR_MAX, RID()); + bd.SrcBlend = blend_factors[bs.src_color_blend_factor]; + ERR_FAIL_INDEX_V(bs.dst_color_blend_factor, BLEND_FACTOR_MAX, RID()); + bd.DestBlend = blend_factors[bs.dst_color_blend_factor]; + ERR_FAIL_INDEX_V(bs.color_blend_op, BLEND_OP_MAX, RID()); + bd.BlendOp = blend_operations[bs.color_blend_op]; + + ERR_FAIL_INDEX_V(bs.src_alpha_blend_factor, BLEND_FACTOR_MAX, RID()); + bd.SrcBlendAlpha = blend_factors[bs.src_alpha_blend_factor]; + ERR_FAIL_INDEX_V(bs.dst_alpha_blend_factor, BLEND_FACTOR_MAX, RID()); + bd.DestBlendAlpha = blend_factors[bs.dst_alpha_blend_factor]; + ERR_FAIL_INDEX_V(bs.alpha_blend_op, BLEND_OP_MAX, RID()); + bd.BlendOpAlpha = blend_operations[bs.alpha_blend_op]; + + if (bs.write_r) { + bd.RenderTargetWriteMask |= D3D12_COLOR_WRITE_ENABLE_RED; + } + if (bs.write_g) { + bd.RenderTargetWriteMask |= D3D12_COLOR_WRITE_ENABLE_GREEN; + } + if (bs.write_b) { + bd.RenderTargetWriteMask |= D3D12_COLOR_WRITE_ENABLE_BLUE; + } + if (bs.write_a) { + bd.RenderTargetWriteMask |= D3D12_COLOR_WRITE_ENABLE_ALPHA; + } + + if (i > 0 && all_attachments_same_blend) { + all_attachments_same_blend = &(&pipeline_desc.BlendState)->RenderTarget[i] == &(&pipeline_desc.BlendState)->RenderTarget[0]; + } + } + + // Per D3D12 docs, if logic op used, independent blending is not supported. + ERR_FAIL_COND_V(p_blend_state.enable_logic_op && !all_attachments_same_blend, RID()); + + (&pipeline_desc.BlendState)->IndependentBlendEnable = !all_attachments_same_blend; + } + + dyn_params.blend_constant = p_blend_state.blend_constant; + + // Stages bytecodes + specialization constants. + + pipeline_desc.pRootSignature = shader->root_signature.Get(); + +#ifdef DEBUG_CREATE_DEBUG_PSO + pipeline_desc.Flags = D3D12_PIPELINE_STATE_FLAG_TOOL_DEBUG; +#endif + + HashMap<ShaderStage, Vector<uint8_t>> final_stages_bytecode; + Error err = _apply_specialization_constants(shader, p_specialization_constants, final_stages_bytecode); + ERR_FAIL_COND_V(err, RID()); + +#ifdef DEV_ENABLED + // Ensure signing worked. + for (KeyValue<ShaderStage, Vector<uint8_t>> &E : final_stages_bytecode) { + bool any_non_zero = false; + for (int j = 0; j < 16; j++) { + if (E.value.ptr()[4 + j]) { + any_non_zero = true; + break; + } + } + DEV_ASSERT(any_non_zero); + } +#endif + + if (shader->stages_bytecode.has(SHADER_STAGE_VERTEX)) { + pipeline_desc.VS = D3D12_SHADER_BYTECODE{ + final_stages_bytecode[SHADER_STAGE_VERTEX].ptr(), + (SIZE_T)final_stages_bytecode[SHADER_STAGE_VERTEX].size() + }; + } + if (shader->stages_bytecode.has(SHADER_STAGE_FRAGMENT)) { + pipeline_desc.PS = D3D12_SHADER_BYTECODE{ + final_stages_bytecode[SHADER_STAGE_FRAGMENT].ptr(), + (SIZE_T)final_stages_bytecode[SHADER_STAGE_FRAGMENT].size() + }; + } + + RenderPipeline pipeline; + { + ComPtr<ID3D12Device2> device2; + device.As(&device2); + HRESULT res = {}; + if (device2) { + D3D12_PIPELINE_STATE_STREAM_DESC pssd = {}; + pssd.pPipelineStateSubobjectStream = &pipeline_desc; + pssd.SizeInBytes = sizeof(pipeline_desc); + res = device2->CreatePipelineState(&pssd, IID_PPV_ARGS(pipeline.pso.GetAddressOf())); + } else { + // Some features won't be available (like depth bounds). + // TODO: Check and/or report error then? + D3D12_GRAPHICS_PIPELINE_STATE_DESC desc = pipeline_desc.GraphicsDescV0(); + res = device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(pipeline.pso.GetAddressOf())); + } + ERR_FAIL_COND_V_MSG(res, RID(), "CreateGraphicsPipelineState failed with error " + vformat("0x%08ux", res) + " for shader '" + shader->name + "'."); + +#ifdef DEBUG_SAVE_PSO_BLOBS + _save_pso_blob(pipeline.pso.Get(), shader, p_specialization_constants); +#endif +#ifdef DEBUG_SAVE_DXIL_BLOBS + _save_stages_bytecode(final_stages_bytecode, shader, p_shader, p_specialization_constants); +#endif + } + + { + Vector<Vector<UniformBindingInfo>> bindings; + bindings.resize(shader->sets.size()); + for (int i = 0; i < shader->sets.size(); i++) { + bindings.write[i].resize(shader->sets[i].uniforms.size()); + for (int j = 0; j < shader->sets[i].uniforms.size(); j++) { + bindings.write[i].write[j] = shader->sets[i].uniforms[j].binding; + } + } + pipeline_bindings[next_pipeline_binding_id] = bindings; + pipeline.bindings_id = next_pipeline_binding_id; + next_pipeline_binding_id++; + } + + pipeline.root_signature_crc = shader->root_signature_crc; + pipeline.set_formats = shader->set_formats; + pipeline.shader = p_shader; + pipeline.spirv_push_constant_size = shader->spirv_push_constant_size; + pipeline.dxil_push_constant_size = shader->dxil_push_constant_size; + pipeline.nir_runtime_data_root_param_idx = shader->nir_runtime_data_root_param_idx; + pipeline.dyn_params = dyn_params; + +#ifdef DEBUG_ENABLED + pipeline.validation.dynamic_state = p_dynamic_state_flags; + pipeline.validation.framebuffer_format = p_framebuffer_format; + pipeline.validation.render_pass = p_for_render_pass; + pipeline.validation.vertex_format = p_vertex_format; + pipeline.validation.uses_restart_indices = pipeline_desc.IBStripCutValue != D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED; + + static const uint32_t primitive_divisor[RENDER_PRIMITIVE_MAX] = { + 1, 2, 1, 1, 1, 3, 1, 1, 1, 1, 1 + }; + pipeline.validation.primitive_divisor = primitive_divisor[p_render_primitive]; + static const uint32_t primitive_minimum[RENDER_PRIMITIVE_MAX] = { + 1, + 2, + 2, + 2, + 2, + 3, + 3, + 3, + 3, + 3, + 1, + }; + pipeline.validation.primitive_minimum = primitive_minimum[p_render_primitive]; +#endif + // Create ID to associate with this pipeline. + RID id = render_pipeline_owner.make_rid(pipeline); +#ifdef DEV_ENABLED + set_resource_name(id, "RID:" + itos(id.get_id())); +#endif + // Now add all the dependencies. + _add_dependency(id, p_shader); + return id; +} + +bool RenderingDeviceD3D12::render_pipeline_is_valid(RID p_pipeline) { + _THREAD_SAFE_METHOD_ + return render_pipeline_owner.owns(p_pipeline); +} + +/**************************/ +/**** COMPUTE PIPELINE ****/ +/**************************/ + +RID RenderingDeviceD3D12::compute_pipeline_create(RID p_shader, const Vector<PipelineSpecializationConstant> &p_specialization_constants) { +#ifdef DEV_ENABLED +//#define DEBUG_CREATE_DEBUG_PSO +//#define DEBUG_SAVE_PSO_BLOBS +//#define DEBUG_SAVE_DXIL_BLOBS +#endif + _THREAD_SAFE_METHOD_ + + // Needs a shader. + Shader *shader = shader_owner.get_or_null(p_shader); + ERR_FAIL_NULL_V(shader, RID()); + + ERR_FAIL_COND_V_MSG(!shader->is_compute, RID(), + "Non-compute shaders can't be used in compute pipelines"); + + CD3DX12_PIPELINE_STATE_STREAM pipeline_desc = {}; + + // Stages bytecodes + specialization constants. + + pipeline_desc.pRootSignature = shader->root_signature.Get(); + +#ifdef DEBUG_CREATE_DEBUG_PSO + pipeline_desc.Flags = D3D12_PIPELINE_STATE_FLAG_TOOL_DEBUG; +#endif + + HashMap<ShaderStage, Vector<uint8_t>> final_stages_bytecode; + Error err = _apply_specialization_constants(shader, p_specialization_constants, final_stages_bytecode); + ERR_FAIL_COND_V(err, RID()); + + pipeline_desc.CS = D3D12_SHADER_BYTECODE{ + final_stages_bytecode[SHADER_STAGE_COMPUTE].ptr(), + (SIZE_T)final_stages_bytecode[SHADER_STAGE_COMPUTE].size() + }; + + ComputePipeline pipeline; + { + ComPtr<ID3D12Device2> device2; + device.As(&device2); + HRESULT res = {}; + if (device2) { + D3D12_PIPELINE_STATE_STREAM_DESC pssd = {}; + pssd.pPipelineStateSubobjectStream = &pipeline_desc; + pssd.SizeInBytes = sizeof(pipeline_desc); + res = device2->CreatePipelineState(&pssd, IID_PPV_ARGS(pipeline.pso.GetAddressOf())); + } else { + D3D12_COMPUTE_PIPELINE_STATE_DESC desc = pipeline_desc.ComputeDescV0(); + res = device->CreateComputePipelineState(&desc, IID_PPV_ARGS(pipeline.pso.GetAddressOf())); + } + ERR_FAIL_COND_V_MSG(res, RID(), "CreateComputePipelineState failed with error " + vformat("0x%08ux", res) + " for shader '" + shader->name + "'."); + +#ifdef DEBUG_SAVE_PSO_BLOBS + _save_pso_blob(pipeline.pso.Get(), shader, p_specialization_constants); +#endif +#ifdef DEBUG_SAVE_DXIL_BLOBS + _save_stages_bytecode(final_stages_bytecode, shader, p_shader, p_specialization_constants); +#endif + } + + { + Vector<Vector<UniformBindingInfo>> bindings; + bindings.resize(shader->sets.size()); + for (int i = 0; i < shader->sets.size(); i++) { + bindings.write[i].resize(shader->sets[i].uniforms.size()); + for (int j = 0; j < shader->sets[i].uniforms.size(); j++) { + bindings.write[i].write[j] = shader->sets[i].uniforms[j].binding; + } + } + pipeline_bindings[next_pipeline_binding_id] = bindings; + pipeline.bindings_id = next_pipeline_binding_id; + next_pipeline_binding_id++; + } + + pipeline.root_signature_crc = shader->root_signature_crc; + pipeline.set_formats = shader->set_formats; + pipeline.shader = p_shader; + pipeline.spirv_push_constant_size = shader->spirv_push_constant_size; + pipeline.dxil_push_constant_size = shader->dxil_push_constant_size; + pipeline.local_group_size[0] = shader->compute_local_size[0]; + pipeline.local_group_size[1] = shader->compute_local_size[1]; + pipeline.local_group_size[2] = shader->compute_local_size[2]; + + // Create ID to associate with this pipeline. + RID id = compute_pipeline_owner.make_rid(pipeline); +#ifdef DEV_ENABLED + set_resource_name(id, "RID:" + itos(id.get_id())); +#endif + // Now add all the dependencies. + _add_dependency(id, p_shader); + return id; +} + +bool RenderingDeviceD3D12::compute_pipeline_is_valid(RID p_pipeline) { + return compute_pipeline_owner.owns(p_pipeline); +} + +/****************/ +/**** SCREEN ****/ +/****************/ + +int RenderingDeviceD3D12::screen_get_width(DisplayServer::WindowID p_screen) const { + _THREAD_SAFE_METHOD_ + ERR_FAIL_COND_V_MSG(local_device.is_valid(), -1, "Local devices have no screen"); + return context->window_get_width(p_screen); +} + +int RenderingDeviceD3D12::screen_get_height(DisplayServer::WindowID p_screen) const { + _THREAD_SAFE_METHOD_ + ERR_FAIL_COND_V_MSG(local_device.is_valid(), -1, "Local devices have no screen"); + + return context->window_get_height(p_screen); +} + +RenderingDevice::FramebufferFormatID RenderingDeviceD3D12::screen_get_framebuffer_format() const { + _THREAD_SAFE_METHOD_ + ERR_FAIL_COND_V_MSG(local_device.is_valid(), INVALID_ID, "Local devices have no screen"); + + // Very hacky, but not used often per frame so I guess ok. + DXGI_FORMAT d3d12_format = context->get_screen_format(); + DataFormat format = DATA_FORMAT_MAX; + for (int i = 0; i < DATA_FORMAT_MAX; i++) { + if (d3d12_format == d3d12_formats[i].general_format) { + format = DataFormat(i); + break; + } + } + + ERR_FAIL_COND_V(format == DATA_FORMAT_MAX, INVALID_ID); + + AttachmentFormat attachment; + attachment.format = format; + attachment.samples = TEXTURE_SAMPLES_1; + attachment.usage_flags = TEXTURE_USAGE_COLOR_ATTACHMENT_BIT; + Vector<AttachmentFormat> screen_attachment; + screen_attachment.push_back(attachment); + return const_cast<RenderingDeviceD3D12 *>(this)->framebuffer_format_create(screen_attachment); +} + +/*******************/ +/**** DRAW LIST ****/ +/*******************/ + +RenderingDevice::DrawListID RenderingDeviceD3D12::draw_list_begin_for_screen(DisplayServer::WindowID p_screen, const Color &p_clear_color) { + _THREAD_SAFE_METHOD_ + ERR_FAIL_COND_V_MSG(local_device.is_valid(), INVALID_ID, "Local devices have no screen"); + + ERR_FAIL_COND_V_MSG(draw_list != nullptr, INVALID_ID, "Only one draw list can be active at the same time."); + ERR_FAIL_COND_V_MSG(compute_list != nullptr, INVALID_ID, "Only one draw/compute list can be active at the same time."); + + if (!context->window_is_valid_swapchain(p_screen)) { + return INVALID_ID; + } + + Size2i size = Size2i(context->window_get_width(p_screen), context->window_get_height(p_screen)); + + _draw_list_allocate(Rect2i(Vector2i(), size), 0, 0); + + Vector<Color> clear_colors; + clear_colors.push_back(p_clear_color); + + curr_screen_framebuffer = Framebuffer(); + curr_screen_framebuffer.window_id = p_screen; + curr_screen_framebuffer.format_id = screen_get_framebuffer_format(); + curr_screen_framebuffer.size = size; + curr_screen_framebuffer.screen_rtv_handle = context->window_get_framebuffer_rtv_handle(p_screen); + + ID3D12GraphicsCommandList *command_list = frames[frame].draw_command_list.Get(); + Error err = _draw_list_render_pass_begin(&curr_screen_framebuffer, INITIAL_ACTION_CLEAR, FINAL_ACTION_READ, INITIAL_ACTION_DROP, FINAL_ACTION_DISCARD, clear_colors, 0.0f, 0, Rect2i(), Point2i(), size, command_list, Vector<RID>()); + + if (err != OK) { + return INVALID_ID; + } + + return int64_t(ID_TYPE_DRAW_LIST) << ID_BASE_SHIFT; +} + +Error RenderingDeviceD3D12::_draw_list_render_pass_begin(Framebuffer *framebuffer, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector<Color> &p_clear_colors, float p_clear_depth, uint32_t p_clear_stencil, const Rect2 &p_region, Point2i viewport_offset, Point2i viewport_size, ID3D12GraphicsCommandList *command_list, const Vector<RID> &p_storage_textures) { + const FramebufferFormat &fb_format = framebuffer_formats[framebuffer->format_id]; + + bool is_screen = framebuffer->window_id != DisplayServer::INVALID_WINDOW_ID; + if (!is_screen) { + ERR_FAIL_COND_V(fb_format.attachments.size() != framebuffer->texture_ids.size(), ERR_BUG); + } + + CD3DX12_RECT region_rect(0, 0, framebuffer->size.x, framebuffer->size.y); + if (p_region != Rect2() && p_region != Rect2(Vector2(), viewport_size)) { // Check custom region. + Rect2i viewport(viewport_offset, viewport_size); + Rect2i regioni = p_region; + if (!viewport.encloses(regioni)) { + ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "When supplying a custom region, it must be contained within the framebuffer rectangle"); + } + viewport_offset = regioni.position; + viewport_size = regioni.size; + + region_rect = CD3DX12_RECT( + p_region.position.x, + p_region.position.y, + p_region.position.x + p_region.size.x, + p_region.position.y + p_region.size.y); + } + + if (p_initial_color_action == INITIAL_ACTION_CLEAR) { // Check clear values. + int color_count = 0; + if (is_screen) { + color_count = 1; + + } else { + for (int i = 0; i < framebuffer->texture_ids.size(); i++) { + Texture *texture = texture_owner.get_or_null(framebuffer->texture_ids[i]); + if (!texture || (!(texture->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) && !(i != 0 && texture->usage_flags & TEXTURE_USAGE_VRS_ATTACHMENT_BIT))) { + if (!texture || !texture->is_resolve_buffer) { + color_count++; + } + } + } + } + ERR_FAIL_COND_V_MSG(p_clear_colors.size() != color_count, ERR_INVALID_PARAMETER, + "Clear color values supplied (" + itos(p_clear_colors.size()) + ") differ from the amount required for framebuffer color attachments (" + itos(color_count) + ")."); + } + + struct SetupInfo { + enum { + ACTION_NONE, + ACTION_DISCARD, + ACTION_CLEAR, + } action = ACTION_NONE; + UINT num_rects = 0; + D3D12_RECT *rect_ptr = nullptr; + D3D12_RESOURCE_STATES new_state = {}; + + SetupInfo(InitialAction p_action, D3D12_RECT *p_region_rect, bool p_is_color) { + switch (p_action) { + case INITIAL_ACTION_CLEAR: { + action = ACTION_CLEAR; + } break; + case INITIAL_ACTION_CLEAR_REGION: { + action = ACTION_CLEAR; + num_rects = 1; + rect_ptr = p_region_rect; + } break; + case INITIAL_ACTION_CLEAR_REGION_CONTINUE: { + action = ACTION_CLEAR; + num_rects = 1; + rect_ptr = p_region_rect; + } break; + case INITIAL_ACTION_KEEP: { + } break; + case INITIAL_ACTION_DROP: { + action = ACTION_DISCARD; // TODO: Are we really intended to do a resource Discard() as initial action, when final action can already do? + } break; + case INITIAL_ACTION_CONTINUE: { + } break; + } + } + }; + + SetupInfo setup_color(p_initial_color_action, ®ion_rect, true); + SetupInfo setup_depth(p_initial_depth_action, ®ion_rect, false); + + draw_list_bound_textures.clear(); + draw_list_unbind_color_textures = p_final_color_action != FINAL_ACTION_CONTINUE; + draw_list_unbind_depth_textures = p_final_depth_action != FINAL_ACTION_CONTINUE; + + ID3D12Resource **discards = (ID3D12Resource **)alloca(sizeof(ID3D12Resource *) * fb_format.attachments.size()); + uint32_t num_discards = 0; + + struct RTVClear { + D3D12_CPU_DESCRIPTOR_HANDLE handle; + Color color; + }; + RTVClear *rtv_clears = (RTVClear *)alloca(sizeof(RTVClear) * fb_format.attachments.size()); + uint32_t num_rtv_clears = 0; + + bool dsv_clear = false; + + DescriptorsHeap::Walker rtv_heap_walker = framebuffer->rtv_heap.make_walker(); + + int color_index = 0; + for (int i = 0; i < fb_format.attachments.size(); i++) { + RID texture_rid; + Texture *texture = nullptr; + if (!is_screen) { + texture_rid = framebuffer->texture_ids[i]; + if (texture_rid.is_null()) { + color_index++; + continue; + } + + texture = texture_owner.get_or_null(texture_rid); + ERR_FAIL_NULL_V(texture, ERR_BUG); + + texture->bound = true; + draw_list_bound_textures.push_back(texture_rid); + } + + // We can setup a framebuffer where we write to our VRS texture to set it up. + // We make the assumption here that if our texture is actually used as our VRS attachment, + // it is used as such for each subpass. This is fairly certain seeing the restrictions on subpasses (in Vulkan). + // [[VRS_EVERY_SUBPASS_OR_NONE]] + bool is_vrs = fb_format.attachments[i].usage_flags & TEXTURE_USAGE_VRS_ATTACHMENT_BIT && i == fb_format.passes[0].vrs_attachment; + if (is_vrs) { + DEV_ASSERT(!is_screen); + + DEV_ASSERT(texture->owner_mipmaps == 1); + DEV_ASSERT(texture->owner_layers == 1); + _resource_transition_batch(texture, 0, texture->planes, D3D12_RESOURCE_STATE_SHADING_RATE_SOURCE); + } else { + if ((fb_format.attachments[i].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT)) { + if (!is_screen) { // Screen backbuffers are transitioned in prepare_buffers(). + for (uint32_t j = 0; j < texture->layers; j++) { + for (uint32_t k = 0; k < texture->mipmaps; k++) { + uint32_t subresource = D3D12CalcSubresource(texture->base_mipmap + k, texture->base_layer + j, 0, texture->owner_mipmaps, texture->owner_layers); + _resource_transition_batch(texture, subresource, texture->planes, D3D12_RESOURCE_STATE_RENDER_TARGET); + } + } + } + + if (setup_color.action == SetupInfo::ACTION_DISCARD) { + ID3D12Resource *resource = is_screen ? context->window_get_framebuffer_texture(framebuffer->window_id) : texture->resource; + discards[num_discards++] = resource; + } else if (setup_color.action == SetupInfo::ACTION_CLEAR) { + D3D12_CPU_DESCRIPTOR_HANDLE handle = is_screen ? framebuffer->screen_rtv_handle : rtv_heap_walker.get_curr_cpu_handle(); + Color clear_color = color_index < p_clear_colors.size() ? p_clear_colors[color_index] : Color(); + rtv_clears[num_rtv_clears++] = RTVClear{ handle, clear_color }; + } + + color_index++; + if (!is_screen) { + rtv_heap_walker.advance(); + } + } else if ((fb_format.attachments[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) { + DEV_ASSERT(!is_screen); + + for (uint32_t j = 0; j < texture->layers; j++) { + for (uint32_t k = 0; k < texture->mipmaps; k++) { + uint32_t subresource = D3D12CalcSubresource(texture->base_mipmap + k, texture->base_layer + j, 0, texture->owner_mipmaps, texture->owner_layers); + _resource_transition_batch(texture, subresource, texture->planes, D3D12_RESOURCE_STATE_DEPTH_WRITE); + } + } + + if (setup_depth.action == SetupInfo::ACTION_DISCARD) { + discards[num_discards++] = texture->resource; + } else if (setup_depth.action == SetupInfo::ACTION_CLEAR) { + dsv_clear = true; + } + } + } + } + + for (int i = 0; i < p_storage_textures.size(); i++) { + Texture *texture = texture_owner.get_or_null(p_storage_textures[i]); + if (!texture) { + continue; + } + ERR_CONTINUE_MSG(!(texture->usage_flags & TEXTURE_USAGE_STORAGE_BIT), "Supplied storage texture " + itos(i) + " for draw list is not set to be used for storage."); + } + + _resource_transitions_flush(frames[frame].draw_command_list.Get()); + + for (uint32_t i = 0; i < num_discards; i++) { + command_list->DiscardResource(discards[i], nullptr); + } + for (uint32_t i = 0; i < num_rtv_clears; i++) { + command_list->ClearRenderTargetView( + rtv_clears[i].handle, + rtv_clears[i].color.components, + setup_color.num_rects, + setup_color.rect_ptr); + } + + if (dsv_clear) { + command_list->ClearDepthStencilView( + framebuffer->dsv_heap.get_heap()->GetCPUDescriptorHandleForHeapStart(), + D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, + p_clear_depth, + p_clear_stencil, + setup_depth.num_rects, + setup_depth.rect_ptr); + } + + { + CD3DX12_VIEWPORT viewport( + viewport_offset.x, + viewport_offset.y, + viewport_size.x, + viewport_size.y, + 0.0f, + 1.0f); + command_list->RSSetViewports(1, &viewport); + + CD3DX12_RECT scissor( + viewport_offset.x, + viewport_offset.y, + viewport_offset.x + viewport_size.x, + viewport_offset.y + viewport_size.y); + command_list->RSSetScissorRects(1, &scissor); + } + + draw_list_subpass_count = fb_format.passes.size(); + draw_list_current_subpass = 0; + draw_list_final_color_action = p_final_color_action; + draw_list_final_depth_action = p_final_depth_action; + draw_list_framebuffer = framebuffer; + draw_list_viewport_size = viewport_size; + + _draw_list_subpass_begin(); + + return OK; +} + +RenderingDevice::DrawListID RenderingDeviceD3D12::draw_list_begin(RID p_framebuffer, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector<Color> &p_clear_color_values, float p_clear_depth, uint32_t p_clear_stencil, const Rect2 &p_region, const Vector<RID> &p_storage_textures) { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND_V_MSG(draw_list != nullptr, INVALID_ID, "Only one draw list can be active at the same time."); + ERR_FAIL_COND_V_MSG(compute_list != nullptr && !compute_list->state.allow_draw_overlap, INVALID_ID, "Only one draw/compute list can be active at the same time."); + + Framebuffer *framebuffer = framebuffer_owner.get_or_null(p_framebuffer); + ERR_FAIL_NULL_V(framebuffer, INVALID_ID); + + ID3D12GraphicsCommandList *command_list = frames[frame].draw_command_list.Get(); + Error err = _draw_list_render_pass_begin(framebuffer, p_initial_color_action, p_final_color_action, p_initial_depth_action, p_final_depth_action, p_clear_color_values, p_clear_depth, p_clear_stencil, p_region, Point2i(), framebuffer->size, command_list, p_storage_textures); + + if (err != OK) { + return INVALID_ID; + } + + _draw_list_allocate(Rect2i(Point2i(), framebuffer->size), 0, 0); + + return int64_t(ID_TYPE_DRAW_LIST) << ID_BASE_SHIFT; +} + +Error RenderingDeviceD3D12::draw_list_begin_split(RID p_framebuffer, uint32_t p_splits, DrawListID *r_split_ids, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector<Color> &p_clear_color_values, float p_clear_depth, uint32_t p_clear_stencil, const Rect2 &p_region, const Vector<RID> &p_storage_textures) { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND_V_MSG(draw_list != nullptr, ERR_BUSY, "Only one draw list can be active at the same time."); + ERR_FAIL_COND_V_MSG(compute_list != nullptr && !compute_list->state.allow_draw_overlap, ERR_BUSY, "Only one draw/compute list can be active at the same time."); + + ERR_FAIL_COND_V(p_splits < 1, ERR_INVALID_DECLARATION); + + Framebuffer *framebuffer = framebuffer_owner.get_or_null(p_framebuffer); + ERR_FAIL_NULL_V(framebuffer, ERR_INVALID_DECLARATION); + + ID3D12GraphicsCommandList *frame_command_list = frames[frame].draw_command_list.Get(); + Error err = _draw_list_render_pass_begin(framebuffer, p_initial_color_action, p_final_color_action, p_initial_depth_action, p_final_depth_action, p_clear_color_values, p_clear_depth, p_clear_stencil, p_region, Point2i(), framebuffer->size, frame_command_list, p_storage_textures); + + if (err != OK) { + return ERR_CANT_CREATE; + } + + err = _draw_list_allocate(Rect2i(Point2i(), framebuffer->size), p_splits, 0); + if (err != OK) { + return err; + } + + for (uint32_t i = 0; i < p_splits; i++) { + // In Vulkan, we'd be setting viewports and scissors for each split here; + // D3D12 doesn't need it (it's even forbidden, for that matter). + + r_split_ids[i] = (int64_t(ID_TYPE_SPLIT_DRAW_LIST) << ID_BASE_SHIFT) + i; + } + + return OK; +} + +RenderingDeviceD3D12::DrawList *RenderingDeviceD3D12::_get_draw_list_ptr(DrawListID p_id) { + if (p_id < 0) { + return nullptr; + } + + if (!draw_list) { + return nullptr; + } else if (p_id == (int64_t(ID_TYPE_DRAW_LIST) << ID_BASE_SHIFT)) { + if (draw_list_split) { + return nullptr; + } + return draw_list; + } else if (p_id >> DrawListID(ID_BASE_SHIFT) == ID_TYPE_SPLIT_DRAW_LIST) { + if (!draw_list_split) { + return nullptr; + } + + uint64_t index = p_id & ((DrawListID(1) << DrawListID(ID_BASE_SHIFT)) - 1); // Mask. + + if (index >= draw_list_count) { + return nullptr; + } + + return &draw_list[index]; + } else { + return nullptr; + } +} + +void RenderingDeviceD3D12::draw_list_set_blend_constants(DrawListID p_list, const Color &p_color) { + DrawList *dl = _get_draw_list_ptr(p_list); + ERR_FAIL_NULL(dl); +#ifdef DEBUG_ENABLED + ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified."); +#endif + + dl->command_list->OMSetBlendFactor(p_color.components); +} + +void RenderingDeviceD3D12::draw_list_bind_render_pipeline(DrawListID p_list, RID p_render_pipeline) { + DrawList *dl = _get_draw_list_ptr(p_list); + ERR_FAIL_NULL(dl); +#ifdef DEBUG_ENABLED + ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified."); +#endif + + const RenderPipeline *pipeline = render_pipeline_owner.get_or_null(p_render_pipeline); + ERR_FAIL_NULL(pipeline); +#ifdef DEBUG_ENABLED + ERR_FAIL_COND(pipeline->validation.framebuffer_format != draw_list_framebuffer->format_id && pipeline->validation.render_pass != draw_list_current_subpass); +#endif + + if (p_render_pipeline == dl->state.pipeline) { + return; // Redundant state, return. + } + + dl->state.pipeline = p_render_pipeline; + dl->state.pso = pipeline->pso.Get(); + + dl->command_list->IASetPrimitiveTopology(pipeline->dyn_params.primitive_topology); + dl->command_list->OMSetBlendFactor(pipeline->dyn_params.blend_constant.components); + dl->command_list->OMSetStencilRef(pipeline->dyn_params.stencil_reference); + + ID3D12GraphicsCommandList1 *command_list_1 = nullptr; + dl->command_list->QueryInterface<ID3D12GraphicsCommandList1>(&command_list_1); + if (command_list_1) { + command_list_1->OMSetDepthBounds(pipeline->dyn_params.depth_bounds_min, pipeline->dyn_params.depth_bounds_max); + command_list_1->Release(); + } + + Shader *shader = shader_owner.get_or_null(pipeline->shader); + + if (dl->state.pipeline_shader != pipeline->shader) { + if (dl->state.root_signature_crc != pipeline->root_signature_crc) { + dl->command_list->SetGraphicsRootSignature(shader->root_signature.Get()); + dl->state.root_signature_crc = pipeline->root_signature_crc; + + // Root signature changed, so current descriptor set bindings become invalid. + for (uint32_t i = 0; i < dl->state.set_count; i++) { + dl->state.sets[i].bound = false; + } + + if (pipeline->nir_runtime_data_root_param_idx != UINT32_MAX) { + // Set the viewport size part of the DXIL-NIR runtime data, which is the only we know to need currently. + constexpr dxil_spirv_vertex_runtime_data dummy_data = {}; + uint32_t offset = constexpr((char *)&dummy_data.viewport_width - (char *)&dummy_data) / 4; + dl->command_list->SetGraphicsRoot32BitConstants(pipeline->nir_runtime_data_root_param_idx, 2, &draw_list_viewport_size, offset); + } + } + + const uint32_t *pformats = pipeline->set_formats.ptr(); // Pipeline set formats. + dl->state.set_count = pipeline->set_formats.size(); // Update set count. + for (uint32_t i = 0; i < dl->state.set_count; i++) { + dl->state.sets[i].pipeline_expected_format = pformats[i]; +#ifdef DEV_ENABLED + dl->state.sets[i]._pipeline_expected_format = pformats[i] ? &uniform_set_format_cache_reverse[pformats[i] - 1]->key().uniform_info : nullptr; +#endif + } + + if (pipeline->spirv_push_constant_size) { +#ifdef DEBUG_ENABLED + dl->validation.pipeline_push_constant_supplied = false; +#endif + } + + dl->state.pipeline_shader = pipeline->shader; + dl->state.pipeline_dxil_push_constant_size = pipeline->dxil_push_constant_size; + dl->state.pipeline_bindings_id = pipeline->bindings_id; +#ifdef DEV_ENABLED + dl->state._shader = shader; +#endif + } + +#ifdef DEBUG_ENABLED + // Update render pass pipeline info. + dl->validation.pipeline_active = true; + dl->validation.pipeline_dynamic_state = pipeline->validation.dynamic_state; + dl->validation.pipeline_vertex_format = pipeline->validation.vertex_format; + dl->validation.pipeline_uses_restart_indices = pipeline->validation.uses_restart_indices; + dl->validation.pipeline_primitive_divisor = pipeline->validation.primitive_divisor; + dl->validation.pipeline_primitive_minimum = pipeline->validation.primitive_minimum; + dl->validation.pipeline_spirv_push_constant_size = pipeline->spirv_push_constant_size; +#endif +} + +void RenderingDeviceD3D12::draw_list_bind_uniform_set(DrawListID p_list, RID p_uniform_set, uint32_t p_index) { + DrawList *dl = _get_draw_list_ptr(p_list); + ERR_FAIL_NULL(dl); + +#ifdef DEBUG_ENABLED + ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified."); +#endif + + const UniformSet *uniform_set = uniform_set_owner.get_or_null(p_uniform_set); + ERR_FAIL_NULL(uniform_set); + + if (p_index > dl->state.set_count) { + dl->state.set_count = p_index; + } + + dl->state.sets[p_index].bound = false; // Needs rebind. + dl->state.sets[p_index].uniform_set_format = uniform_set->format; + dl->state.sets[p_index].uniform_set = p_uniform_set; +#ifdef DEV_ENABLED + dl->state.sets[p_index]._uniform_set = uniform_set_owner.get_or_null(p_uniform_set); +#endif + +#ifdef DEBUG_ENABLED + { // Validate that textures bound are not attached as framebuffer bindings. + uint32_t attachable_count = uniform_set->attachable_textures.size(); + const UniformSet::AttachableTexture *attachable_ptr = uniform_set->attachable_textures.ptr(); + uint32_t bound_count = draw_list_bound_textures.size(); + const RID *bound_ptr = draw_list_bound_textures.ptr(); + for (uint32_t i = 0; i < attachable_count; i++) { + for (uint32_t j = 0; j < bound_count; j++) { + ERR_FAIL_COND_MSG(attachable_ptr[i].texture == bound_ptr[j], + "Attempted to use the same texture in framebuffer attachment and a uniform (set: " + itos(p_index) + ", binding: " + itos(attachable_ptr[i].bind) + "), this is not allowed."); + } + } + } +#endif +} + +void RenderingDeviceD3D12::draw_list_bind_vertex_array(DrawListID p_list, RID p_vertex_array) { + DrawList *dl = _get_draw_list_ptr(p_list); + ERR_FAIL_NULL(dl); +#ifdef DEBUG_ENABLED + ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified."); +#endif + + const VertexArray *vertex_array = vertex_array_owner.get_or_null(p_vertex_array); + ERR_FAIL_NULL(vertex_array); + + if (dl->state.vertex_array == p_vertex_array) { + return; // Already set. + } + + dl->state.vertex_array = p_vertex_array; + +#ifdef DEBUG_ENABLED + dl->validation.vertex_format = vertex_array->description; + dl->validation.vertex_max_instances_allowed = vertex_array->max_instances_allowed; +#endif + dl->validation.vertex_array_size = vertex_array->vertex_count; + + for (Buffer *buffer : vertex_array->unique_buffers) { + _resource_transition_batch(buffer, 0, 1, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER); + } + _resource_transitions_flush(dl->command_list); + + dl->command_list->IASetVertexBuffers(0, vertex_array->views.size(), vertex_array->views.ptr()); +} + +void RenderingDeviceD3D12::draw_list_bind_index_array(DrawListID p_list, RID p_index_array) { + DrawList *dl = _get_draw_list_ptr(p_list); + ERR_FAIL_NULL(dl); +#ifdef DEBUG_ENABLED + ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified."); +#endif + + const IndexArray *index_array = index_array_owner.get_or_null(p_index_array); + ERR_FAIL_NULL(index_array); + + if (dl->state.index_array == p_index_array) { + return; // Already set. + } + + dl->state.index_array = p_index_array; +#ifdef DEBUG_ENABLED + dl->validation.index_array_max_index = index_array->max_index; +#endif + dl->validation.index_array_size = index_array->indices; + dl->validation.index_array_offset = index_array->offset; + + _resource_transition_batch(index_array->buffer, 0, 1, D3D12_RESOURCE_STATE_INDEX_BUFFER); + _resource_transitions_flush(dl->command_list); + + dl->command_list->IASetIndexBuffer(&index_array->view); +} + +void RenderingDeviceD3D12::draw_list_set_line_width(DrawListID p_list, float p_width) { + DrawList *dl = _get_draw_list_ptr(p_list); + ERR_FAIL_NULL(dl); +#ifdef DEBUG_ENABLED + ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified."); +#endif + + if (!Math::is_equal_approx(p_width, 1.0f)) { + ERR_FAIL_MSG("Setting line widths other than 1.0 is not supported by the Direct3D 12 rendering driver."); + } +} + +void RenderingDeviceD3D12::_bind_uniform_set(UniformSet *p_uniform_set, const Shader::Set &p_shader_set, const Vector<UniformBindingInfo> &p_bindings, ID3D12GraphicsCommandList *p_command_list, bool p_for_compute) { + using SetRootDescriptorTableFn = void (STDMETHODCALLTYPE ID3D12GraphicsCommandList::*)(UINT, D3D12_GPU_DESCRIPTOR_HANDLE); + SetRootDescriptorTableFn set_root_desc_table_fn = p_for_compute ? &ID3D12GraphicsCommandList::SetComputeRootDescriptorTable : &ID3D12GraphicsCommandList1::SetGraphicsRootDescriptorTable; + + // If this set's descriptors have already been set for the current execution and a compatible root signature, reuse! + uint32_t root_sig_crc = p_for_compute ? compute_list->state.root_signature_crc : draw_list->state.root_signature_crc; + UniformSet::RecentBind *last_bind = nullptr; + for (int i = 0; i < ARRAY_SIZE(p_uniform_set->recent_binds); i++) { + if (p_uniform_set->recent_binds[i].execution_index == frames[frame].execution_index) { + if (p_uniform_set->recent_binds[i].root_signature_crc == root_sig_crc) { + for (const RootDescriptorTable &table : p_uniform_set->recent_binds[i].root_tables.resources) { + (p_command_list->*set_root_desc_table_fn)(table.root_param_idx, table.start_gpu_handle); + } + for (const RootDescriptorTable &table : p_uniform_set->recent_binds[i].root_tables.samplers) { + (p_command_list->*set_root_desc_table_fn)(table.root_param_idx, table.start_gpu_handle); + } +#ifdef DEV_ENABLED + p_uniform_set->recent_binds[i].uses++; + frames[frame].uniform_set_reused++; +#endif + return; + } else { + if (!last_bind || p_uniform_set->recent_binds[i].uses < last_bind->uses) { + // Prefer this one since it's been used less or we still haven't a better option. + last_bind = &p_uniform_set->recent_binds[i]; + } + } + } else { + // Prefer this one since it's unused. + last_bind = &p_uniform_set->recent_binds[i]; + last_bind->uses = 0; + } + } + + struct { + DescriptorsHeap::Walker *resources = nullptr; + DescriptorsHeap::Walker *samplers = nullptr; + } frame_heap_walkers; + frame_heap_walkers.resources = &frames[frame].desc_heap_walkers.resources; + frame_heap_walkers.samplers = &frames[frame].desc_heap_walkers.samplers; + + struct { + DescriptorsHeap::Walker resources; + DescriptorsHeap::Walker samplers; + } set_heap_walkers; + set_heap_walkers.resources = p_uniform_set->desc_heaps.resources.make_walker(); + set_heap_walkers.samplers = p_uniform_set->desc_heaps.samplers.make_walker(); + +#ifdef DEV_ENABLED + // Whether we have stages where the uniform is actually used should match + // whether we have any root signature locations for it. + for (int i = 0; i < p_shader_set.uniforms.size(); i++) { + bool has_rs_locations = false; + if (p_bindings[i].root_sig_locations.resource.root_param_idx != UINT32_MAX || + p_bindings[i].root_sig_locations.sampler.root_param_idx != UINT32_MAX) { + has_rs_locations = true; + break; + } + + bool has_stages = p_bindings[i].stages; + + DEV_ASSERT(has_rs_locations == has_stages); + } +#endif + + last_bind->root_tables.resources.reserve(p_shader_set.num_root_params.resources); + last_bind->root_tables.resources.clear(); + last_bind->root_tables.samplers.reserve(p_shader_set.num_root_params.samplers); + last_bind->root_tables.samplers.clear(); + last_bind->uses++; + + struct { + RootDescriptorTable *resources = nullptr; + RootDescriptorTable *samplers = nullptr; + } tables; + for (int i = 0; i < p_shader_set.uniforms.size(); i++) { + const Shader::ShaderUniformInfo &uniform_info = p_shader_set.uniforms[i]; + + uint32_t num_resource_descs = 0; + uint32_t num_sampler_descs = 0; + bool srv_uav_ambiguity = false; + _add_descriptor_count_for_uniform(uniform_info.info.type, uniform_info.info.length, false, num_resource_descs, num_sampler_descs, srv_uav_ambiguity); + + bool resource_used = false; + if (p_bindings[i].stages) { + { + const UniformBindingInfo::RootSignatureLocation &rs_loc_resource = p_bindings[i].root_sig_locations.resource; + if (rs_loc_resource.root_param_idx != UINT32_MAX) { // Location used? + DEV_ASSERT(num_resource_descs); + DEV_ASSERT(!(srv_uav_ambiguity && (p_bindings[i].res_class != RES_CLASS_SRV && p_bindings[i].res_class != RES_CLASS_UAV))); // [[SRV_UAV_AMBIGUITY]] + + bool must_flush_table = tables.resources && rs_loc_resource.root_param_idx != tables.resources->root_param_idx; + if (must_flush_table) { + // Check the root signature data has been filled ordered. + DEV_ASSERT(rs_loc_resource.root_param_idx > tables.resources->root_param_idx); + + (p_command_list->*set_root_desc_table_fn)(tables.resources->root_param_idx, tables.resources->start_gpu_handle); + tables.resources = nullptr; + } + + if (unlikely(frame_heap_walkers.resources->get_free_handles() < num_resource_descs)) { + if (!frames[frame].desc_heaps_exhausted_reported.resources) { + frames[frame].desc_heaps_exhausted_reported.resources = true; + ERR_FAIL_MSG("Cannot bind uniform set because there's no enough room in current frame's RESOURCES descriptor heap.\n" + "Please increase the value of the rendering/rendering_device/d3d12/max_resource_descriptors_per_frame project setting."); + } else { + return; + } + } + + if (!tables.resources) { + DEV_ASSERT(last_bind->root_tables.resources.size() < last_bind->root_tables.resources.get_capacity()); + last_bind->root_tables.resources.resize(last_bind->root_tables.resources.size() + 1); + tables.resources = &last_bind->root_tables.resources[last_bind->root_tables.resources.size() - 1]; + tables.resources->root_param_idx = rs_loc_resource.root_param_idx; + tables.resources->start_gpu_handle = frame_heap_walkers.resources->get_curr_gpu_handle(); + } + + // If there is ambiguity and it didn't clarify as SRVs, skip them, which come first. [[SRV_UAV_AMBIGUITY]] + if (srv_uav_ambiguity && p_bindings[i].res_class != RES_CLASS_SRV) { + set_heap_walkers.resources.advance(num_resource_descs); + } + + // TODO: Batch to avoid multiple calls where possible (in any case, flush before setting root descriptor tables, or even batch that as well). + device->CopyDescriptorsSimple( + num_resource_descs, + frame_heap_walkers.resources->get_curr_cpu_handle(), + set_heap_walkers.resources.get_curr_cpu_handle(), + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + frame_heap_walkers.resources->advance(num_resource_descs); + + // If there is ambiguity and it didn't clarify as UAVs, skip them, which come later. [[SRV_UAV_AMBIGUITY]] + if (srv_uav_ambiguity && p_bindings[i].res_class != RES_CLASS_UAV) { + set_heap_walkers.resources.advance(num_resource_descs); + } + + resource_used = true; + } + } + + { + const UniformBindingInfo::RootSignatureLocation &rs_loc_sampler = p_bindings[i].root_sig_locations.sampler; + if (rs_loc_sampler.root_param_idx != UINT32_MAX) { // Location used? + DEV_ASSERT(num_sampler_descs); + DEV_ASSERT(!srv_uav_ambiguity); // [[SRV_UAV_AMBIGUITY]] + + bool must_flush_table = tables.samplers && rs_loc_sampler.root_param_idx != tables.samplers->root_param_idx; + if (must_flush_table) { + // Check the root signature data has been filled ordered. + DEV_ASSERT(rs_loc_sampler.root_param_idx > tables.samplers->root_param_idx); + + (p_command_list->*set_root_desc_table_fn)(tables.samplers->root_param_idx, tables.samplers->start_gpu_handle); + tables.samplers = nullptr; + } + + if (unlikely(frame_heap_walkers.samplers->get_free_handles() < num_sampler_descs)) { + if (!frames[frame].desc_heaps_exhausted_reported.samplers) { + frames[frame].desc_heaps_exhausted_reported.samplers = true; + ERR_FAIL_MSG("Cannot bind uniform set because there's no enough room in current frame's SAMPLERS descriptors heap.\n" + "Please increase the value of the rendering/rendering_device/d3d12/max_sampler_descriptors_per_frame project setting."); + } else { + return; + } + } + + if (!tables.samplers) { + DEV_ASSERT(last_bind->root_tables.samplers.size() < last_bind->root_tables.samplers.get_capacity()); + last_bind->root_tables.samplers.resize(last_bind->root_tables.samplers.size() + 1); + tables.samplers = &last_bind->root_tables.samplers[last_bind->root_tables.samplers.size() - 1]; + tables.samplers->root_param_idx = rs_loc_sampler.root_param_idx; + tables.samplers->start_gpu_handle = frame_heap_walkers.samplers->get_curr_gpu_handle(); + } + + // TODO: Batch to avoid multiple calls where possible (in any case, flush before setting root descriptor tables, or even batch that as well). + device->CopyDescriptorsSimple( + num_sampler_descs, + frame_heap_walkers.samplers->get_curr_cpu_handle(), + set_heap_walkers.samplers.get_curr_cpu_handle(), + D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER); + frame_heap_walkers.samplers->advance(num_sampler_descs); + } + } + } + + // Uniform set descriptor heaps are always full (descriptors are created for every uniform in them) despite + // the shader variant a given set is created upon may not need all of them due to DXC optimizations. + // Therefore, at this point we have to advance through the descriptor set descriptor's heap unconditionally. + + set_heap_walkers.resources.advance(num_resource_descs); + if (srv_uav_ambiguity) { + DEV_ASSERT(num_resource_descs); + if (!resource_used) { + set_heap_walkers.resources.advance(num_resource_descs); // Additional skip, since both SRVs and UAVs have to be bypassed. + } + } + + set_heap_walkers.samplers.advance(num_sampler_descs); + } + + DEV_ASSERT(set_heap_walkers.resources.is_at_eof()); + DEV_ASSERT(set_heap_walkers.samplers.is_at_eof()); + + { + bool must_flush_table = tables.resources; + if (must_flush_table) { + (p_command_list->*set_root_desc_table_fn)(tables.resources->root_param_idx, tables.resources->start_gpu_handle); + } + } + { + bool must_flush_table = tables.samplers; + if (must_flush_table) { + (p_command_list->*set_root_desc_table_fn)(tables.samplers->root_param_idx, tables.samplers->start_gpu_handle); + } + } + + last_bind->root_signature_crc = root_sig_crc; + last_bind->execution_index = frames[frame].execution_index; +} + +void RenderingDeviceD3D12::_apply_uniform_set_resource_states(const UniformSet *p_uniform_set, const Shader::Set &p_shader_set) { + for (const UniformSet::StateRequirement &sr : p_uniform_set->resource_states) { +#ifdef DEV_ENABLED + { + uint32_t stages = 0; + D3D12_RESOURCE_STATES wanted_state = {}; + bool writable = false; + // Doing the full loop for debugging since the real one below may break early, + // but we want an exhaustive check + uint64_t inv_uniforms_mask = ~sr.shader_uniform_idx_mask; // Inverting the mask saves operations. + for (uint8_t bit = 0; inv_uniforms_mask != UINT64_MAX; bit++) { + uint64_t bit_mask = ((uint64_t)1 << bit); + if (likely((inv_uniforms_mask & bit_mask))) { + continue; + } + inv_uniforms_mask |= bit_mask; + + const Shader::ShaderUniformInfo &info = p_shader_set.uniforms[bit]; + if (unlikely(!info.binding.stages)) { + continue; + } + + D3D12_RESOURCE_STATES required_states = sr.states; + + // Resolve a case of SRV/UAV ambiguity now. [[SRV_UAV_AMBIGUITY]] + if ((required_states & D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE) && (required_states & D3D12_RESOURCE_STATE_UNORDERED_ACCESS)) { + if (info.binding.res_class == RES_CLASS_SRV) { + required_states &= ~D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + } else { + required_states = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + } + } + + if (stages) { // Second occurrence at least? + CRASH_COND_MSG(info.info.writable != writable, "A resource is used in the same uniform set both as R/O and R/W. That's not supported and shouldn't happen."); + CRASH_COND_MSG(required_states != wanted_state, "A resource is used in the same uniform set with different resource states. The code needs to be enhanced to support that."); + } else { + wanted_state = required_states; + stages |= info.binding.stages; + writable = info.info.writable; + } + + DEV_ASSERT((wanted_state == D3D12_RESOURCE_STATE_UNORDERED_ACCESS) == (bool)(wanted_state & D3D12_RESOURCE_STATE_UNORDERED_ACCESS)); + + if (wanted_state == D3D12_RESOURCE_STATE_UNORDERED_ACCESS || wanted_state == D3D12_RESOURCE_STATE_RENDER_TARGET) { + if (!sr.is_buffer) { + Texture *texture = (Texture *)sr.resource; + CRASH_COND_MSG(texture->resource != texture->owner_resource, "The texture format used for UAV or RTV must be the main one."); + } + } + } + } +#endif + + // We may have assumed D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE for a resource, + // because at uniform set creation time we couldn't know for sure which stages + // it would be used in (due to the fact that a set can be created against a different, + // albeit compatible, shader, which may make a different usage in the end). + // However, now we know and can exclude up to one unneeded state. + + // TODO: If subresources involved already in the needed state, or scheduled for it, + // maybe it's more optimal not to do anything here + + uint32_t stages = 0; + D3D12_RESOURCE_STATES wanted_state = {}; + uint64_t inv_uniforms_mask = ~sr.shader_uniform_idx_mask; // Inverting the mask saves operations. + for (uint8_t bit = 0; inv_uniforms_mask != UINT64_MAX; bit++) { + uint64_t bit_mask = ((uint64_t)1 << bit); + if (likely((inv_uniforms_mask & bit_mask))) { + continue; + } + inv_uniforms_mask |= bit_mask; + + const Shader::ShaderUniformInfo &info = p_shader_set.uniforms[bit]; + if (unlikely(!info.binding.stages)) { + continue; + } + + if (!stages) { + D3D12_RESOURCE_STATES required_states = sr.states; + + // Resolve a case of SRV/UAV ambiguity now. [[SRV_UAV_AMBIGUITY]] + if ((required_states & D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE) && (required_states & D3D12_RESOURCE_STATE_UNORDERED_ACCESS)) { + if (info.binding.res_class == RES_CLASS_SRV) { + required_states &= ~D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + } else { + required_states = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + } + } + + wanted_state = required_states; + + if (!(wanted_state & D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE)) { + // By now, we already know the resource is used, and with no PS/NON_PS disjuntive; no need to check further. + break; + } + } + + stages |= info.binding.stages; + + if (stages == (SHADER_STAGE_VERTEX_BIT | SHADER_STAGE_FRAGMENT_BIT) || stages == SHADER_STAGE_COMPUTE_BIT) { + // By now, we already know the resource is used, and as both PS/NON_PS; no need to check further. + break; + } + } + + if (likely(wanted_state)) { + if ((wanted_state & D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE)) { + if (stages == SHADER_STAGE_VERTEX_BIT || stages == SHADER_STAGE_COMPUTE_BIT) { + D3D12_RESOURCE_STATES unneeded_states = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; + wanted_state &= ~unneeded_states; + } else if (stages == SHADER_STAGE_FRAGMENT_BIT) { + D3D12_RESOURCE_STATES unneeded_states = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + wanted_state &= ~unneeded_states; + } + } + + if (likely(wanted_state)) { + if (sr.is_buffer) { + _resource_transition_batch(sr.resource, 0, 1, wanted_state); + } else { + Texture *texture = (Texture *)sr.resource; + for (uint32_t i = 0; i < texture->layers; i++) { + for (uint32_t j = 0; j < texture->mipmaps; j++) { + uint32_t subresource = D3D12CalcSubresource(texture->base_mipmap + j, texture->base_layer + i, 0, texture->owner_mipmaps, texture->owner_layers); + _resource_transition_batch(texture, subresource, texture->planes, wanted_state, texture->owner_resource); + } + } + } + } + } + } +} + +void RenderingDeviceD3D12::draw_list_set_push_constant(DrawListID p_list, const void *p_data, uint32_t p_data_size) { + DrawList *dl = _get_draw_list_ptr(p_list); + ERR_FAIL_NULL(dl); + +#ifdef DEBUG_ENABLED + ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified."); +#endif + +#ifdef DEBUG_ENABLED + ERR_FAIL_COND_MSG(p_data_size != dl->validation.pipeline_spirv_push_constant_size, + "This render pipeline requires (" + itos(dl->validation.pipeline_spirv_push_constant_size) + ") bytes of push constant data, supplied: (" + itos(p_data_size) + ")"); +#endif + if (dl->state.pipeline_dxil_push_constant_size) { + dl->command_list->SetGraphicsRoot32BitConstants(0, p_data_size / sizeof(uint32_t), p_data, 0); + } +#ifdef DEBUG_ENABLED + dl->validation.pipeline_push_constant_supplied = true; +#endif +} + +void RenderingDeviceD3D12::draw_list_draw(DrawListID p_list, bool p_use_indices, uint32_t p_instances, uint32_t p_procedural_vertices) { + DrawList *dl = _get_draw_list_ptr(p_list); + ERR_FAIL_NULL(dl); +#ifdef DEBUG_ENABLED + ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified."); +#endif + +#ifdef DEBUG_ENABLED + ERR_FAIL_COND_MSG(!dl->validation.pipeline_active, + "No render pipeline was set before attempting to draw."); + if (dl->validation.pipeline_vertex_format != INVALID_ID) { + // Pipeline uses vertices, validate format. + ERR_FAIL_COND_MSG(dl->validation.vertex_format == INVALID_ID, + "No vertex array was bound, and render pipeline expects vertices."); + // Make sure format is right. + ERR_FAIL_COND_MSG(dl->validation.pipeline_vertex_format != dl->validation.vertex_format, + "The vertex format used to create the pipeline does not match the vertex format bound."); + // Make sure number of instances is valid. + ERR_FAIL_COND_MSG(p_instances > dl->validation.vertex_max_instances_allowed, + "Number of instances requested (" + itos(p_instances) + " is larger than the maximum number supported by the bound vertex array (" + itos(dl->validation.vertex_max_instances_allowed) + ")."); + } + + if (dl->validation.pipeline_spirv_push_constant_size) { + // Using push constants, check that they were supplied. + ERR_FAIL_COND_MSG(!dl->validation.pipeline_push_constant_supplied, + "The shader in this pipeline requires a push constant to be set before drawing, but it's not present."); + } +#endif + + // Bind descriptor sets. + + Shader *shader = shader_owner.get_or_null(dl->state.pipeline_shader); + struct SetToBind { + uint32_t set; + UniformSet *uniform_set; + const Shader::Set *shader_set; + }; + SetToBind *sets_to_bind = (SetToBind *)alloca(sizeof(SetToBind) * dl->state.set_count); + uint32_t num_sets_to_bind = 0; + for (uint32_t i = 0; i < dl->state.set_count; i++) { + if (dl->state.sets[i].pipeline_expected_format == 0) { + continue; // Nothing expected by this pipeline. + } +#ifdef DEBUG_ENABLED + if (dl->state.sets[i].pipeline_expected_format != dl->state.sets[i].uniform_set_format) { + if (dl->state.sets[i].uniform_set_format == 0) { + ERR_FAIL_MSG("Uniforms were never supplied for set (" + itos(i) + ") at the time of drawing, which are required by the pipeline"); + } else if (uniform_set_owner.owns(dl->state.sets[i].uniform_set)) { + UniformSet *us = uniform_set_owner.get_or_null(dl->state.sets[i].uniform_set); + ERR_FAIL_MSG("Uniforms supplied for set (" + itos(i) + "):\n" + _shader_uniform_debug(us->shader_id, us->shader_set) + "\nare not the same format as required by the pipeline shader. Pipeline shader requires the following bindings:\n" + _shader_uniform_debug(dl->state.pipeline_shader)); + } else { + ERR_FAIL_MSG("Uniforms supplied for set (" + itos(i) + ", which was was just freed) are not the same format as required by the pipeline shader. Pipeline shader requires the following bindings:\n" + _shader_uniform_debug(dl->state.pipeline_shader)); + } + } +#endif + UniformSet *uniform_set = uniform_set_owner.get_or_null(dl->state.sets[i].uniform_set); + const Shader::Set &shader_set = shader->sets[i]; + _apply_uniform_set_resource_states(uniform_set, shader_set); + if (!dl->state.sets[i].bound) { + sets_to_bind[num_sets_to_bind].set = i; + sets_to_bind[num_sets_to_bind].uniform_set = uniform_set; + sets_to_bind[num_sets_to_bind].shader_set = &shader_set; + num_sets_to_bind++; + dl->state.sets[i].bound = true; + } + } + + _resource_transitions_flush(dl->command_list); + + for (uint32_t i = 0; i < num_sets_to_bind; i++) { + _bind_uniform_set(sets_to_bind[i].uniform_set, *sets_to_bind[i].shader_set, pipeline_bindings[dl->state.pipeline_bindings_id][sets_to_bind[i].set], dl->command_list, false); + } + + if (dl->state.bound_pso != dl->state.pso) { + dl->command_list->SetPipelineState(dl->state.pso); + dl->state.bound_pso = dl->state.pso; + } + if (p_use_indices) { +#ifdef DEBUG_ENABLED + ERR_FAIL_COND_MSG(p_procedural_vertices > 0, + "Procedural vertices can't be used together with indices."); + + ERR_FAIL_COND_MSG(!dl->validation.index_array_size, + "Draw command requested indices, but no index buffer was set."); + + ERR_FAIL_COND_MSG(dl->validation.pipeline_uses_restart_indices != dl->validation.index_buffer_uses_restart_indices, + "The usage of restart indices in index buffer does not match the render primitive in the pipeline."); +#endif + uint32_t to_draw = dl->validation.index_array_size; + +#ifdef DEBUG_ENABLED + ERR_FAIL_COND_MSG(to_draw < dl->validation.pipeline_primitive_minimum, + "Too few indices (" + itos(to_draw) + ") for the render primitive set in the render pipeline (" + itos(dl->validation.pipeline_primitive_minimum) + ")."); + + ERR_FAIL_COND_MSG((to_draw % dl->validation.pipeline_primitive_divisor) != 0, + "Index amount (" + itos(to_draw) + ") must be a multiple of the amount of indices required by the render primitive (" + itos(dl->validation.pipeline_primitive_divisor) + ")."); +#endif + + dl->command_list->DrawIndexedInstanced(to_draw, p_instances, dl->validation.index_array_offset, 0, 0); + } else { + uint32_t to_draw; + + if (p_procedural_vertices > 0) { +#ifdef DEBUG_ENABLED + ERR_FAIL_COND_MSG(dl->validation.pipeline_vertex_format != INVALID_ID, + "Procedural vertices requested, but pipeline expects a vertex array."); +#endif + to_draw = p_procedural_vertices; + } else { +#ifdef DEBUG_ENABLED + ERR_FAIL_COND_MSG(dl->validation.pipeline_vertex_format == INVALID_ID, + "Draw command lacks indices, but pipeline format does not use vertices."); +#endif + to_draw = dl->validation.vertex_array_size; + } + +#ifdef DEBUG_ENABLED + ERR_FAIL_COND_MSG(to_draw < dl->validation.pipeline_primitive_minimum, + "Too few vertices (" + itos(to_draw) + ") for the render primitive set in the render pipeline (" + itos(dl->validation.pipeline_primitive_minimum) + ")."); + + ERR_FAIL_COND_MSG((to_draw % dl->validation.pipeline_primitive_divisor) != 0, + "Vertex amount (" + itos(to_draw) + ") must be a multiple of the amount of vertices required by the render primitive (" + itos(dl->validation.pipeline_primitive_divisor) + ")."); +#endif + + dl->command_list->DrawInstanced(to_draw, p_instances, 0, 0); + } +} + +void RenderingDeviceD3D12::draw_list_enable_scissor(DrawListID p_list, const Rect2 &p_rect) { + DrawList *dl = _get_draw_list_ptr(p_list); + + ERR_FAIL_NULL(dl); +#ifdef DEBUG_ENABLED + ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified."); +#endif + Rect2i rect = p_rect; + rect.position += dl->viewport.position; + + rect = dl->viewport.intersection(rect); + + if (rect.get_area() == 0) { + return; + } + CD3DX12_RECT scissor( + rect.position.x, + rect.position.y, + rect.position.x + rect.size.width, + rect.position.y + rect.size.height); + + dl->command_list->RSSetScissorRects(1, &scissor); +} + +void RenderingDeviceD3D12::draw_list_disable_scissor(DrawListID p_list) { + DrawList *dl = _get_draw_list_ptr(p_list); + ERR_FAIL_NULL(dl); +#ifdef DEBUG_ENABLED + ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified."); +#endif + + CD3DX12_RECT scissor( + dl->viewport.position.x, + dl->viewport.position.y, + dl->viewport.position.x + dl->viewport.size.width, + dl->viewport.position.y + dl->viewport.size.height); + dl->command_list->RSSetScissorRects(1, &scissor); +} + +uint32_t RenderingDeviceD3D12::draw_list_get_current_pass() { + return draw_list_current_subpass; +} + +void RenderingDeviceD3D12::_draw_list_subpass_begin() { // [[MANUAL_SUBPASSES]] + const FramebufferFormat &fb_format = framebuffer_formats[draw_list_framebuffer->format_id]; + const FramebufferPass &pass = fb_format.passes[draw_list_current_subpass]; + + ID3D12GraphicsCommandList *command_list = frames[frame].draw_command_list.Get(); + + bool is_screen = draw_list_framebuffer->window_id != DisplayServer::INVALID_WINDOW_ID; + + if (is_screen) { + DEV_ASSERT(!draw_list_framebuffer->dsv_heap.get_descriptor_count()); + command_list->OMSetRenderTargets(1, &draw_list_framebuffer->screen_rtv_handle, true, nullptr); + } else { + D3D12_CPU_DESCRIPTOR_HANDLE *rtv_handles = (D3D12_CPU_DESCRIPTOR_HANDLE *)alloca(sizeof(D3D12_CPU_DESCRIPTOR_HANDLE) * pass.color_attachments.size()); + DescriptorsHeap::Walker rtv_heap_walker = draw_list_framebuffer->rtv_heap.make_walker(); + for (int i = 0; i < pass.color_attachments.size(); i++) { + uint32_t attachment = pass.color_attachments[i]; + if (attachment == FramebufferPass::ATTACHMENT_UNUSED) { + if (!frames[frame].null_rtv_handle.ptr) { + // No null descriptor-handle created for this frame yet. + + if (frames[frame].desc_heap_walkers.rtv.is_at_eof()) { + if (!frames[frame].desc_heaps_exhausted_reported.rtv) { + frames[frame].desc_heaps_exhausted_reported.rtv = true; + ERR_FAIL_MSG("Cannot begin subpass because there's no enough room in current frame's RENDER TARGET descriptors heap.\n" + "Please increase the value of the rendering/rendering_device/d3d12/max_misc_descriptors_per_frame project setting."); + } else { + return; + } + } + + D3D12_RENDER_TARGET_VIEW_DESC rtv_desc_null = {}; + rtv_desc_null.Format = DXGI_FORMAT_R8_UINT; + rtv_desc_null.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D; + frames[frame].null_rtv_handle = frames[frame].desc_heap_walkers.rtv.get_curr_cpu_handle(); + device->CreateRenderTargetView(nullptr, &rtv_desc_null, frames[frame].null_rtv_handle); + frames[frame].desc_heap_walkers.rtv.advance(); + } + rtv_handles[i] = frames[frame].null_rtv_handle; + } else { + uint32_t rt_index = draw_list_framebuffer->attachments_handle_inds[attachment]; + rtv_heap_walker.rewind(); + rtv_heap_walker.advance(rt_index); + rtv_handles[i] = rtv_heap_walker.get_curr_cpu_handle(); + } + } + + D3D12_CPU_DESCRIPTOR_HANDLE dsv_handle = {}; + { + DescriptorsHeap::Walker dsv_heap_walker = draw_list_framebuffer->dsv_heap.make_walker(); + if (pass.depth_attachment != FramebufferPass::ATTACHMENT_UNUSED) { + uint32_t ds_index = draw_list_framebuffer->attachments_handle_inds[pass.depth_attachment]; + dsv_heap_walker.rewind(); + dsv_heap_walker.advance(ds_index); + dsv_handle = dsv_heap_walker.get_curr_cpu_handle(); + } + } + + command_list->OMSetRenderTargets(pass.color_attachments.size(), rtv_handles, false, dsv_handle.ptr ? &dsv_handle : nullptr); + + // [[VRS_EVERY_SUBPASS_OR_NONE]] + if (context->get_vrs_capabilities().ss_image_supported && draw_list_current_subpass == 0) { + if (execution_index != vrs_state_execution_index) { + vrs_state = {}; + } + + Texture *vrs_texture = nullptr; + RID vrs_texture_id; + if (pass.vrs_attachment != FramebufferPass::ATTACHMENT_UNUSED) { + vrs_texture_id = draw_list_framebuffer->texture_ids[pass.vrs_attachment]; + vrs_texture = texture_owner.get_or_null(vrs_texture_id); + if (!vrs_texture) { + vrs_texture_id = RID(); + } + } + + if (vrs_texture_id != vrs_state.texture_bound) { + ID3D12GraphicsCommandList5 *command_list_5 = nullptr; + command_list->QueryInterface<ID3D12GraphicsCommandList5>(&command_list_5); + DEV_ASSERT(command_list_5); + + if (vrs_texture_id.is_valid()) { + if (!vrs_state.configured) { + static const D3D12_SHADING_RATE_COMBINER combiners[D3D12_RS_SET_SHADING_RATE_COMBINER_COUNT] = { + D3D12_SHADING_RATE_COMBINER_PASSTHROUGH, + D3D12_SHADING_RATE_COMBINER_OVERRIDE, + }; + command_list_5->RSSetShadingRate(D3D12_SHADING_RATE_1X1, combiners); + vrs_state.configured = true; + + command_list_5->RSSetShadingRateImage(vrs_texture->resource); + vrs_state.texture_bound = vrs_texture_id; + } + } else { + command_list_5->RSSetShadingRateImage(nullptr); + vrs_state.texture_bound = RID(); + } + + command_list_5->Release(); + } + + vrs_state_execution_index = execution_index; + } + } +} + +void RenderingDeviceD3D12::_draw_list_subpass_end() { // [[MANUAL_SUBPASSES]] + const FramebufferFormat &fb_format = framebuffer_formats[draw_list_framebuffer->format_id]; + const FramebufferPass &pass = fb_format.passes[draw_list_current_subpass]; + + ID3D12GraphicsCommandList *command_list = frames[frame].draw_command_list.Get(); + + struct Resolve { + ID3D12Resource *src_res; + uint32_t src_subres; + ID3D12Resource *dst_res; + uint32_t dst_subres; + DXGI_FORMAT format; + }; + Resolve *resolves = (Resolve *)alloca(sizeof(Resolve) * pass.resolve_attachments.size()); + uint32_t num_resolves = 0; + + for (int i = 0; i < pass.resolve_attachments.size(); i++) { + int32_t color_index = pass.color_attachments[i]; + int32_t resolve_index = pass.resolve_attachments[i]; + DEV_ASSERT((color_index == FramebufferPass::ATTACHMENT_UNUSED) == (resolve_index == FramebufferPass::ATTACHMENT_UNUSED)); + if (color_index == FramebufferPass::ATTACHMENT_UNUSED || draw_list_framebuffer->texture_ids[color_index].is_null()) { + continue; + } + + Texture *src_tex = texture_owner.get_or_null(draw_list_framebuffer->texture_ids[color_index]); + uint32_t src_subresource = D3D12CalcSubresource(src_tex->base_mipmap, src_tex->base_layer, 0, src_tex->owner_mipmaps, src_tex->owner_layers); + _resource_transition_batch(src_tex, src_subresource, src_tex->planes, D3D12_RESOURCE_STATE_RESOLVE_SOURCE); + + Texture *dst_tex = texture_owner.get_or_null(draw_list_framebuffer->texture_ids[resolve_index]); + uint32_t dst_subresource = D3D12CalcSubresource(dst_tex->base_mipmap, dst_tex->base_layer, 0, dst_tex->owner_mipmaps, dst_tex->owner_layers); + _resource_transition_batch(dst_tex, dst_subresource, dst_tex->planes, D3D12_RESOURCE_STATE_RESOLVE_DEST); + + resolves[num_resolves].src_res = src_tex->resource; + resolves[num_resolves].src_subres = src_subresource; + resolves[num_resolves].dst_res = dst_tex->resource; + resolves[num_resolves].dst_subres = dst_subresource; + resolves[num_resolves].format = d3d12_formats[src_tex->format].general_format; + num_resolves++; + } + + _resource_transitions_flush(command_list); + + for (uint32_t i = 0; i < num_resolves; i++) { + command_list->ResolveSubresource(resolves[i].dst_res, resolves[i].dst_subres, resolves[i].src_res, resolves[i].src_subres, resolves[i].format); + } +} + +RenderingDevice::DrawListID RenderingDeviceD3D12::draw_list_switch_to_next_pass() { + _THREAD_SAFE_METHOD_ + ERR_FAIL_COND_V(draw_list == nullptr, INVALID_ID); + ERR_FAIL_COND_V(draw_list_current_subpass >= draw_list_subpass_count - 1, INVALID_FORMAT_ID); + + _draw_list_subpass_end(); + draw_list_current_subpass++; + _draw_list_subpass_begin(); + + Rect2i viewport; + _draw_list_free(&viewport); + + _draw_list_allocate(viewport, 0, draw_list_current_subpass); + + return int64_t(ID_TYPE_DRAW_LIST) << ID_BASE_SHIFT; +} + +Error RenderingDeviceD3D12::draw_list_switch_to_next_pass_split(uint32_t p_splits, DrawListID *r_split_ids) { + _THREAD_SAFE_METHOD_ + ERR_FAIL_COND_V(draw_list == nullptr, ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(draw_list_current_subpass >= draw_list_subpass_count - 1, ERR_INVALID_PARAMETER); + + _draw_list_subpass_end(); + draw_list_current_subpass++; + _draw_list_subpass_begin(); + + Rect2i viewport; + _draw_list_free(&viewport); + + _draw_list_allocate(viewport, p_splits, draw_list_current_subpass); + + for (uint32_t i = 0; i < p_splits; i++) { + r_split_ids[i] = (int64_t(ID_TYPE_SPLIT_DRAW_LIST) << ID_BASE_SHIFT) + i; + } + + return OK; +} + +Error RenderingDeviceD3D12::_draw_list_allocate(const Rect2i &p_viewport, uint32_t p_splits, uint32_t p_subpass) { + if (p_splits == 0) { + draw_list = memnew(DrawList); + draw_list->command_list = frames[frame].draw_command_list.Get(); + draw_list->viewport = p_viewport; + draw_list_count = 0; + draw_list_split = false; + } else { + if (p_splits > (uint32_t)split_draw_list_allocators.size()) { + uint32_t from = split_draw_list_allocators.size(); + split_draw_list_allocators.resize(p_splits); + for (uint32_t i = from; i < p_splits; i++) { + HRESULT res = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_BUNDLE, IID_PPV_ARGS(&split_draw_list_allocators.write[i].command_allocator)); + ERR_FAIL_COND_V_MSG(res, ERR_CANT_CREATE, "CreateCommandAllocator failed with error " + vformat("0x%08ux", res) + "."); + + for (int j = 0; j < frame_count; j++) { + ID3D12GraphicsCommandList *command_list = nullptr; + + res = device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_BUNDLE, split_draw_list_allocators[i].command_allocator, nullptr, IID_PPV_ARGS(&command_list)); + ERR_FAIL_COND_V_MSG(res, ERR_CANT_CREATE, "CreateCommandList failed with error " + vformat("0x%08ux", res) + "."); + + split_draw_list_allocators.write[i].command_lists.push_back(command_list); + } + } + } + draw_list = memnew_arr(DrawList, p_splits); + draw_list_count = p_splits; + draw_list_split = true; + + for (uint32_t i = 0; i < p_splits; i++) { + ID3D12GraphicsCommandList *command_list = split_draw_list_allocators[i].command_lists[frame]; + + HRESULT res = frames[frame].setup_command_allocator->Reset(); + ERR_FAIL_COND_V_MSG(ERR_CANT_CREATE, ERR_CANT_CREATE, "Command allocator Reset failed with error " + vformat("0x%08ux", res) + "."); + res = command_list->Reset(split_draw_list_allocators[i].command_allocator, nullptr); + if (res) { + memdelete_arr(draw_list); + draw_list = nullptr; + ERR_FAIL_V_MSG(ERR_CANT_CREATE, "Command allocator Reset failed with error " + vformat("0x%08ux", res) + "."); + } + + draw_list[i].command_list = command_list; + draw_list[i].viewport = p_viewport; + } + } + + return OK; +} + +void RenderingDeviceD3D12::_draw_list_free(Rect2i *r_last_viewport) { + if (draw_list_split) { + // Send all command buffers. + for (uint32_t i = 0; i < draw_list_count; i++) { + draw_list[i].command_list->Close(); + frames[frame].draw_command_list->ExecuteBundle(draw_list[i].command_list); + if (r_last_viewport) { + if (i == 0 || draw_list[i].viewport_set) { + *r_last_viewport = draw_list[i].viewport; + } + } + } + + memdelete_arr(draw_list); + draw_list = nullptr; + + } else { + if (r_last_viewport) { + *r_last_viewport = draw_list->viewport; + } + // Just end the list. + memdelete(draw_list); + draw_list = nullptr; + } + + draw_list_count = 0; +} + +void RenderingDeviceD3D12::draw_list_end(BitField<BarrierMask> p_post_barrier) { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND_MSG(!draw_list, "Immediate draw list is already inactive."); + + _draw_list_subpass_end(); + + const FramebufferFormat &fb_format = framebuffer_formats[draw_list_framebuffer->format_id]; + bool is_screen = draw_list_framebuffer->window_id != DisplayServer::INVALID_WINDOW_ID; + + ID3D12GraphicsCommandList *command_list = frames[frame].draw_command_list.Get(); + + for (int i = 0; i < fb_format.attachments.size(); i++) { + Texture *texture = nullptr; + if (!is_screen) { + texture = texture_owner.get_or_null(draw_list_framebuffer->texture_ids[i]); + } + if ((fb_format.attachments[i].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT)) { + switch (draw_list_final_color_action) { + case FINAL_ACTION_READ: { + // Nothing to do now. + } break; + case FINAL_ACTION_DISCARD: { + ID3D12Resource *resource = is_screen ? context->window_get_framebuffer_texture(draw_list_framebuffer->window_id) : texture->resource; + command_list->DiscardResource(resource, nullptr); + } break; + case FINAL_ACTION_CONTINUE: { + ERR_FAIL_COND(draw_list_unbind_color_textures); // Bug! + } break; + } + } else if ((fb_format.attachments[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) { + ERR_FAIL_COND(is_screen); // Bug! + switch (draw_list_final_depth_action) { + case FINAL_ACTION_READ: { + // Nothing to do now. + } break; + case FINAL_ACTION_DISCARD: { + ID3D12Resource *resource = is_screen ? context->window_get_framebuffer_texture(draw_list_framebuffer->window_id) : texture->resource; + command_list->DiscardResource(resource, nullptr); + } break; + case FINAL_ACTION_CONTINUE: { + ERR_FAIL_COND(draw_list_unbind_depth_textures); // Bug! + } break; + } + } + } + + draw_list_subpass_count = 0; + draw_list_current_subpass = 0; + draw_list_framebuffer = nullptr; + + _draw_list_free(); + + for (int i = 0; i < draw_list_bound_textures.size(); i++) { + Texture *texture = texture_owner.get_or_null(draw_list_bound_textures[i]); + ERR_CONTINUE(!texture); // Wtf. + if (draw_list_unbind_color_textures && (texture->usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT)) { + texture->bound = false; + } + if (draw_list_unbind_depth_textures && (texture->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) { + texture->bound = false; + } + } + draw_list_bound_textures.clear(); +} + +/***********************/ +/**** COMPUTE LISTS ****/ +/***********************/ + +RenderingDevice::ComputeListID RenderingDeviceD3D12::compute_list_begin(bool p_allow_draw_overlap) { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND_V_MSG(!p_allow_draw_overlap && draw_list != nullptr, INVALID_ID, "Only one draw list can be active at the same time."); + ERR_FAIL_COND_V_MSG(compute_list != nullptr, INVALID_ID, "Only one draw/compute list can be active at the same time."); + + compute_list = memnew(ComputeList); + compute_list->command_list = frames[frame].draw_command_list.Get(); + compute_list->state.allow_draw_overlap = p_allow_draw_overlap; + + return ID_TYPE_COMPUTE_LIST; +} + +void RenderingDeviceD3D12::compute_list_bind_compute_pipeline(ComputeListID p_list, RID p_compute_pipeline) { + // Must be called within a compute list, the class mutex is locked during that time + + ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST); + ERR_FAIL_NULL(compute_list); + + ComputeList *cl = compute_list; + + const ComputePipeline *pipeline = compute_pipeline_owner.get_or_null(p_compute_pipeline); + ERR_FAIL_NULL(pipeline); + + if (p_compute_pipeline == cl->state.pipeline) { + return; // Redundant state, return. + } + + cl->state.pipeline = p_compute_pipeline; + cl->state.pso = pipeline->pso.Get(); + + Shader *shader = shader_owner.get_or_null(pipeline->shader); + + if (cl->state.pipeline_shader != pipeline->shader) { + if (cl->state.root_signature_crc != pipeline->root_signature_crc) { + cl->command_list->SetComputeRootSignature(shader->root_signature.Get()); + cl->state.root_signature_crc = pipeline->root_signature_crc; + // Root signature changed, so current descriptor set bindings become invalid. + for (uint32_t i = 0; i < cl->state.set_count; i++) { + cl->state.sets[i].bound = false; + } + } + + const uint32_t *pformats = pipeline->set_formats.ptr(); // Pipeline set formats. + cl->state.set_count = pipeline->set_formats.size(); // Update set count. + for (uint32_t i = 0; i < cl->state.set_count; i++) { + cl->state.sets[i].pipeline_expected_format = pformats[i]; +#ifdef DEV_ENABLED + cl->state.sets[i]._pipeline_expected_format = pformats[i] ? &uniform_set_format_cache_reverse[pformats[i] - 1]->key().uniform_info : nullptr; +#endif + } + + if (pipeline->spirv_push_constant_size) { +#ifdef DEBUG_ENABLED + cl->validation.pipeline_push_constant_supplied = false; +#endif + } + + cl->state.pipeline_shader = pipeline->shader; + cl->state.pipeline_dxil_push_constant_size = pipeline->dxil_push_constant_size; + cl->state.pipeline_bindings_id = pipeline->bindings_id; + cl->state.local_group_size[0] = pipeline->local_group_size[0]; + cl->state.local_group_size[1] = pipeline->local_group_size[1]; + cl->state.local_group_size[2] = pipeline->local_group_size[2]; +#ifdef DEV_ENABLED + cl->state._shader = shader; +#endif + } + +#ifdef DEBUG_ENABLED + // Update compute pass pipeline info. + cl->validation.pipeline_active = true; + cl->validation.pipeline_spirv_push_constant_size = pipeline->spirv_push_constant_size; +#endif +} + +void RenderingDeviceD3D12::compute_list_bind_uniform_set(ComputeListID p_list, RID p_uniform_set, uint32_t p_index) { + // Must be called within a compute list, the class mutex is locked during that time + + ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST); + ERR_FAIL_NULL(compute_list); + + ComputeList *cl = compute_list; + +#ifdef DEBUG_ENABLED + ERR_FAIL_COND_MSG(!cl->validation.active, "Submitted Compute Lists can no longer be modified."); +#endif + + UniformSet *uniform_set = uniform_set_owner.get_or_null(p_uniform_set); + ERR_FAIL_NULL(uniform_set); + + if (p_index > cl->state.set_count) { + cl->state.set_count = p_index; + } + + cl->state.sets[p_index].bound = false; // Needs rebind. + cl->state.sets[p_index].uniform_set_format = uniform_set->format; + cl->state.sets[p_index].uniform_set = p_uniform_set; +#ifdef DEV_ENABLED + cl->state.sets[p_index]._uniform_set = uniform_set_owner.get_or_null(p_uniform_set); +#endif +} + +void RenderingDeviceD3D12::compute_list_set_push_constant(ComputeListID p_list, const void *p_data, uint32_t p_data_size) { + ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST); + ERR_FAIL_NULL(compute_list); + + ComputeList *cl = compute_list; + +#ifdef DEBUG_ENABLED + ERR_FAIL_COND_MSG(!cl->validation.active, "Submitted Compute Lists can no longer be modified."); +#endif + +#ifdef DEBUG_ENABLED + ERR_FAIL_COND_MSG(p_data_size != cl->validation.pipeline_spirv_push_constant_size, + "This render pipeline requires (" + itos(cl->validation.pipeline_spirv_push_constant_size) + ") bytes of push constant data, supplied: (" + itos(p_data_size) + ")"); +#endif + if (cl->state.pipeline_dxil_push_constant_size) { + cl->command_list->SetComputeRoot32BitConstants(0, p_data_size / sizeof(uint32_t), p_data, 0); + } +#ifdef DEBUG_ENABLED + cl->validation.pipeline_push_constant_supplied = true; +#endif +} + +void RenderingDeviceD3D12::compute_list_dispatch(ComputeListID p_list, uint32_t p_x_groups, uint32_t p_y_groups, uint32_t p_z_groups) { + // Must be called within a compute list, the class mutex is locked during that time + + ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST); + ERR_FAIL_NULL(compute_list); + + ComputeList *cl = compute_list; + +#ifdef DEBUG_ENABLED + ERR_FAIL_COND_MSG(p_x_groups == 0, "Dispatch amount of X compute groups (" + itos(p_x_groups) + ") is zero."); + ERR_FAIL_COND_MSG(p_z_groups == 0, "Dispatch amount of Z compute groups (" + itos(p_z_groups) + ") is zero."); + ERR_FAIL_COND_MSG(p_y_groups == 0, "Dispatch amount of Y compute groups (" + itos(p_y_groups) + ") is zero."); + ERR_FAIL_COND_MSG(p_x_groups > D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION, + "Dispatch amount of X compute groups (" + itos(p_x_groups) + ") is larger than device limit (" + itos(D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION) + ")"); + ERR_FAIL_COND_MSG(p_y_groups > D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION, + "Dispatch amount of Y compute groups (" + itos(p_x_groups) + ") is larger than device limit (" + itos(D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION) + ")"); + ERR_FAIL_COND_MSG(p_z_groups > D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION, + "Dispatch amount of Z compute groups (" + itos(p_x_groups) + ") is larger than device limit (" + itos(D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION) + ")"); + + ERR_FAIL_COND_MSG(!cl->validation.active, "Submitted Compute Lists can no longer be modified."); +#endif + +#ifdef DEBUG_ENABLED + + ERR_FAIL_COND_MSG(!cl->validation.pipeline_active, "No compute pipeline was set before attempting to draw."); + + if (cl->validation.pipeline_spirv_push_constant_size) { + // Using push constants, check that they were supplied. + ERR_FAIL_COND_MSG(!cl->validation.pipeline_push_constant_supplied, + "The shader in this pipeline requires a push constant to be set before drawing, but it's not present."); + } + +#endif + + // Bind descriptor sets. + Shader *shader = shader_owner.get_or_null(cl->state.pipeline_shader); + struct SetToBind { + uint32_t set; + UniformSet *uniform_set; + const Shader::Set *shader_set; + }; + SetToBind *sets_to_bind = (SetToBind *)alloca(sizeof(SetToBind) * cl->state.set_count); + uint32_t num_sets_to_bind = 0; + for (uint32_t i = 0; i < cl->state.set_count; i++) { + if (cl->state.sets[i].pipeline_expected_format == 0) { + continue; // Nothing expected by this pipeline. + } +#ifdef DEBUG_ENABLED + if (cl->state.sets[i].pipeline_expected_format != cl->state.sets[i].uniform_set_format) { + if (cl->state.sets[i].uniform_set_format == 0) { + ERR_FAIL_MSG("Uniforms were never supplied for set (" + itos(i) + ") at the time of drawing, which are required by the pipeline"); + } else if (uniform_set_owner.owns(cl->state.sets[i].uniform_set)) { + UniformSet *us = uniform_set_owner.get_or_null(cl->state.sets[i].uniform_set); + ERR_FAIL_MSG("Uniforms supplied for set (" + itos(i) + "):\n" + _shader_uniform_debug(us->shader_id, us->shader_set) + "\nare not the same format as required by the pipeline shader. Pipeline shader requires the following bindings:\n" + _shader_uniform_debug(cl->state.pipeline_shader)); + } else { + ERR_FAIL_MSG("Uniforms supplied for set (" + itos(i) + ", which was was just freed) are not the same format as required by the pipeline shader. Pipeline shader requires the following bindings:\n" + _shader_uniform_debug(cl->state.pipeline_shader)); + } + } +#endif + UniformSet *uniform_set = uniform_set_owner.get_or_null(cl->state.sets[i].uniform_set); + const Shader::Set &shader_set = shader->sets[i]; + _apply_uniform_set_resource_states(uniform_set, shader_set); + if (!cl->state.sets[i].bound) { + sets_to_bind[num_sets_to_bind].set = i; + sets_to_bind[num_sets_to_bind].uniform_set = uniform_set; + sets_to_bind[num_sets_to_bind].shader_set = &shader_set; + num_sets_to_bind++; + cl->state.sets[i].bound = true; + } + } + + _resource_transitions_flush(cl->command_list); + + for (uint32_t i = 0; i < num_sets_to_bind; i++) { + _bind_uniform_set(sets_to_bind[i].uniform_set, *sets_to_bind[i].shader_set, pipeline_bindings[cl->state.pipeline_bindings_id][sets_to_bind[i].set], cl->command_list, true); + } + + if (cl->state.bound_pso != cl->state.pso) { + cl->command_list->SetPipelineState(cl->state.pso); + cl->state.bound_pso = cl->state.pso; + } + cl->command_list->Dispatch(p_x_groups, p_y_groups, p_z_groups); +} + +void RenderingDeviceD3D12::compute_list_dispatch_threads(ComputeListID p_list, uint32_t p_x_threads, uint32_t p_y_threads, uint32_t p_z_threads) { + ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST); + ERR_FAIL_NULL(compute_list); + +#ifdef DEBUG_ENABLED + ERR_FAIL_COND_MSG(p_x_threads == 0, "Dispatch amount of X compute threads (" + itos(p_x_threads) + ") is zero."); + ERR_FAIL_COND_MSG(p_y_threads == 0, "Dispatch amount of Y compute threads (" + itos(p_y_threads) + ") is zero."); + ERR_FAIL_COND_MSG(p_z_threads == 0, "Dispatch amount of Z compute threads (" + itos(p_z_threads) + ") is zero."); +#endif + + ComputeList *cl = compute_list; + +#ifdef DEBUG_ENABLED + + ERR_FAIL_COND_MSG(!cl->validation.pipeline_active, "No compute pipeline was set before attempting to draw."); + + if (cl->validation.pipeline_spirv_push_constant_size) { + // Using push constants, check that they were supplied. + ERR_FAIL_COND_MSG(!cl->validation.pipeline_push_constant_supplied, + "The shader in this pipeline requires a push constant to be set before drawing, but it's not present."); + } + +#endif + + compute_list_dispatch(p_list, (p_x_threads - 1) / cl->state.local_group_size[0] + 1, (p_y_threads - 1) / cl->state.local_group_size[1] + 1, (p_z_threads - 1) / cl->state.local_group_size[2] + 1); +} + +void RenderingDeviceD3D12::compute_list_dispatch_indirect(ComputeListID p_list, RID p_buffer, uint32_t p_offset) { + ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST); + ERR_FAIL_NULL(compute_list); + + ComputeList *cl = compute_list; + Buffer *buffer = storage_buffer_owner.get_or_null(p_buffer); + ERR_FAIL_NULL(buffer); + + ERR_FAIL_COND_MSG(!(buffer->usage & D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT), "Buffer provided was not created to do indirect dispatch."); + + ERR_FAIL_COND_MSG(p_offset + 12 > buffer->size, "Offset provided (+12) is past the end of buffer."); + +#ifdef DEBUG_ENABLED + + ERR_FAIL_COND_MSG(!cl->validation.pipeline_active, "No compute pipeline was set before attempting to draw."); + + if (cl->validation.pipeline_spirv_push_constant_size) { + // Using push constants, check that they were supplied. + ERR_FAIL_COND_MSG(!cl->validation.pipeline_push_constant_supplied, + "The shader in this pipeline requires a push constant to be set before drawing, but it's not present."); + } + +#endif + + // Bind descriptor sets. + + Shader *shader = shader_owner.get_or_null(cl->state.pipeline_shader); + struct SetToBind { + uint32_t set; + UniformSet *uniform_set; + const Shader::Set *shader_set; + }; + SetToBind *sets_to_bind = (SetToBind *)alloca(sizeof(SetToBind) * cl->state.set_count); + uint32_t num_sets_to_bind = 0; + for (uint32_t i = 0; i < cl->state.set_count; i++) { + if (cl->state.sets[i].pipeline_expected_format == 0) { + continue; // Nothing expected by this pipeline. + } +#ifdef DEBUG_ENABLED + if (cl->state.sets[i].pipeline_expected_format != cl->state.sets[i].uniform_set_format) { + if (cl->state.sets[i].uniform_set_format == 0) { + ERR_FAIL_MSG("Uniforms were never supplied for set (" + itos(i) + ") at the time of drawing, which are required by the pipeline"); + } else if (uniform_set_owner.owns(cl->state.sets[i].uniform_set)) { + UniformSet *us = uniform_set_owner.get_or_null(cl->state.sets[i].uniform_set); + ERR_FAIL_MSG("Uniforms supplied for set (" + itos(i) + "):\n" + _shader_uniform_debug(us->shader_id, us->shader_set) + "\nare not the same format as required by the pipeline shader. Pipeline shader requires the following bindings:\n" + _shader_uniform_debug(cl->state.pipeline_shader)); + } else { + ERR_FAIL_MSG("Uniforms supplied for set (" + itos(i) + ", which was was just freed) are not the same format as required by the pipeline shader. Pipeline shader requires the following bindings:\n" + _shader_uniform_debug(cl->state.pipeline_shader)); + } + } +#endif + UniformSet *uniform_set = uniform_set_owner.get_or_null(cl->state.sets[i].uniform_set); + const Shader::Set &shader_set = shader->sets[i]; + _apply_uniform_set_resource_states(uniform_set, shader_set); + if (!cl->state.sets[i].bound) { + sets_to_bind[num_sets_to_bind].set = i; + sets_to_bind[num_sets_to_bind].uniform_set = uniform_set; + sets_to_bind[num_sets_to_bind].shader_set = &shader_set; + num_sets_to_bind++; + cl->state.sets[i].bound = true; + } + } + + _resource_transition_batch(buffer, 0, 1, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + + _resource_transitions_flush(cl->command_list); + + for (uint32_t i = 0; i < num_sets_to_bind; i++) { + _bind_uniform_set(sets_to_bind[i].uniform_set, *sets_to_bind[i].shader_set, pipeline_bindings[cl->state.pipeline_bindings_id][sets_to_bind[i].set], cl->command_list, true); + } + + if (cl->state.bound_pso != cl->state.pso) { + cl->command_list->SetPipelineState(cl->state.pso); + cl->state.bound_pso = cl->state.pso; + } + cl->command_list->ExecuteIndirect(indirect_dispatch_cmd_sig.Get(), 1, buffer->resource, p_offset, nullptr, 0); +} + +void RenderingDeviceD3D12::compute_list_add_barrier(ComputeListID p_list) { + // Must be called within a compute list, the class mutex is locked during that time + +#ifdef FORCE_FULL_BARRIER + full_barrier(); +#else + // Due to D3D12 resource-wise barriers, this is no op. +#endif +} + +void RenderingDeviceD3D12::compute_list_end(BitField<BarrierMask> p_post_barrier) { + ERR_FAIL_NULL(compute_list); + +#ifdef FORCE_FULL_BARRIER + full_barrier(); +#endif + + memdelete(compute_list); + compute_list = nullptr; +} + +void RenderingDeviceD3D12::barrier(BitField<BarrierMask> p_from, BitField<BarrierMask> p_to) { + // Due to D3D12 resource-wise barriers, this is no op. +} + +void RenderingDeviceD3D12::full_barrier() { +#ifndef DEBUG_ENABLED + ERR_PRINT("Full barrier is debug-only, should not be used in production"); +#endif + + // In the resource barriers world, we can force a full barrier by discarding some resource, as per + // https://microsoft.github.io/DirectX-Specs/d3d/D3D12EnhancedBarriers.html#synchronous-copy-discard-and-resolve. + frames[frame].draw_command_list->DiscardResource(texture_owner.get_or_null(aux_resource)->resource, nullptr); +} + +void RenderingDeviceD3D12::_free_internal(RID p_id) { +#ifdef DEV_ENABLED + String resource_name; + if (resource_names.has(p_id)) { + resource_name = resource_names[p_id]; + resource_names.erase(p_id); + } +#endif + + // Push everything so it's disposed of next time this frame index is processed (means, it's safe to do it). + if (texture_owner.owns(p_id)) { + Texture *texture = texture_owner.get_or_null(p_id); + frames[frame].textures_to_dispose_of.push_back(*texture); + texture_owner.free(p_id); + } else if (framebuffer_owner.owns(p_id)) { + Framebuffer *framebuffer = framebuffer_owner.get_or_null(p_id); + frames[frame].framebuffers_to_dispose_of.push_back(*framebuffer); + + if (framebuffer->invalidated_callback != nullptr) { + framebuffer->invalidated_callback(framebuffer->invalidated_callback_userdata); + } + framebuffer_owner.free(p_id); + } else if (sampler_owner.owns(p_id)) { + sampler_owner.free(p_id); + } else if (vertex_buffer_owner.owns(p_id)) { + Buffer *vertex_buffer = vertex_buffer_owner.get_or_null(p_id); + frames[frame].buffers_to_dispose_of.push_back(*vertex_buffer); + vertex_buffer_owner.free(p_id); + } else if (vertex_array_owner.owns(p_id)) { + vertex_array_owner.free(p_id); + } else if (index_buffer_owner.owns(p_id)) { + IndexBuffer *index_buffer = index_buffer_owner.get_or_null(p_id); + frames[frame].buffers_to_dispose_of.push_back(*index_buffer); + index_buffer_owner.free(p_id); + } else if (index_array_owner.owns(p_id)) { + index_array_owner.free(p_id); + } else if (shader_owner.owns(p_id)) { + Shader *shader = shader_owner.get_or_null(p_id); + frames[frame].shaders_to_dispose_of.push_back(*shader); + shader_owner.free(p_id); + } else if (uniform_buffer_owner.owns(p_id)) { + Buffer *uniform_buffer = uniform_buffer_owner.get_or_null(p_id); + frames[frame].buffers_to_dispose_of.push_back(*uniform_buffer); + uniform_buffer_owner.free(p_id); + } else if (texture_buffer_owner.owns(p_id)) { + TextureBuffer *texture_buffer = texture_buffer_owner.get_or_null(p_id); + frames[frame].buffers_to_dispose_of.push_back(texture_buffer->buffer); + texture_buffer_owner.free(p_id); + } else if (storage_buffer_owner.owns(p_id)) { + Buffer *storage_buffer = storage_buffer_owner.get_or_null(p_id); + frames[frame].buffers_to_dispose_of.push_back(*storage_buffer); + storage_buffer_owner.free(p_id); + } else if (uniform_set_owner.owns(p_id)) { + UniformSet *uniform_set = uniform_set_owner.get_or_null(p_id); + uniform_set_owner.free(p_id); + + if (uniform_set->invalidated_callback != nullptr) { + uniform_set->invalidated_callback(uniform_set->invalidated_callback_userdata); + } + } else if (render_pipeline_owner.owns(p_id)) { + RenderPipeline *pipeline = render_pipeline_owner.get_or_null(p_id); + frames[frame].render_pipelines_to_dispose_of.push_back(*pipeline); + render_pipeline_owner.free(p_id); + } else if (compute_pipeline_owner.owns(p_id)) { + ComputePipeline *pipeline = compute_pipeline_owner.get_or_null(p_id); + frames[frame].compute_pipelines_to_dispose_of.push_back(*pipeline); + compute_pipeline_owner.free(p_id); + } else { +#ifdef DEV_ENABLED + ERR_PRINT("Attempted to free invalid ID: " + itos(p_id.get_id()) + " " + resource_name); +#else + ERR_PRINT("Attempted to free invalid ID: " + itos(p_id.get_id())); +#endif + } +} + +void RenderingDeviceD3D12::free(RID p_id) { + _THREAD_SAFE_METHOD_ + + _free_dependencies(p_id); // Recursively erase dependencies first, to avoid potential API problems. + _free_internal(p_id); +} + +void RenderingDeviceD3D12::set_resource_name(RID p_id, const String p_name) { + if (texture_owner.owns(p_id)) { + Texture *texture = texture_owner.get_or_null(p_id); + // Don't set the source texture's name when calling on a texture view. + if (texture->owner.is_null()) { + context->set_object_name(texture->resource, p_name); + } + } else if (framebuffer_owner.owns(p_id)) { + // No D3D12 object to name. + } else if (sampler_owner.owns(p_id)) { + // No D3D12 object to name. + } else if (shader_owner.owns(p_id)) { + Shader *shader = shader_owner.get_or_null(p_id); + context->set_object_name(shader->root_signature.Get(), p_name + " Root Signature"); + } else if (uniform_set_owner.owns(p_id)) { + // No D3D12 object to name. + } else if (render_pipeline_owner.owns(p_id)) { + RenderPipeline *pipeline = render_pipeline_owner.get_or_null(p_id); + context->set_object_name(pipeline->pso.Get(), p_name); + } else if (compute_pipeline_owner.owns(p_id)) { + ComputePipeline *pipeline = compute_pipeline_owner.get_or_null(p_id); + context->set_object_name(pipeline->pso.Get(), p_name); + } else { + Buffer *buffer = _get_buffer_from_owner(p_id); + if (buffer) { + context->set_object_name(buffer->resource, p_name); + } else { + ERR_PRINT("Attempted to name invalid ID: " + itos(p_id.get_id())); + return; + } + } +#ifdef DEV_ENABLED + resource_names[p_id] = p_name; +#endif +} + +void RenderingDeviceD3D12::draw_command_begin_label(String p_label_name, const Color p_color) { + _THREAD_SAFE_METHOD_ + context->command_begin_label(frames[frame].draw_command_list.Get(), p_label_name, p_color); +} + +void RenderingDeviceD3D12::draw_command_insert_label(String p_label_name, const Color p_color) { + _THREAD_SAFE_METHOD_ + context->command_insert_label(frames[frame].draw_command_list.Get(), p_label_name, p_color); +} + +void RenderingDeviceD3D12::draw_command_end_label() { + _THREAD_SAFE_METHOD_ + context->command_end_label(frames[frame].draw_command_list.Get()); +} + +String RenderingDeviceD3D12::get_device_vendor_name() const { + return context->get_device_vendor_name(); +} + +String RenderingDeviceD3D12::get_device_name() const { + return context->get_device_name(); +} + +RenderingDevice::DeviceType RenderingDeviceD3D12::get_device_type() const { + return context->get_device_type(); +} + +String RenderingDeviceD3D12::get_device_api_version() const { + return context->get_device_api_version(); +} + +String RenderingDeviceD3D12::get_device_pipeline_cache_uuid() const { + return context->get_device_pipeline_cache_uuid(); +} + +void RenderingDeviceD3D12::_finalize_command_bufers() { + if (draw_list) { + ERR_PRINT("Found open draw list at the end of the frame, this should never happen (further drawing will likely not work)."); + } + + if (compute_list) { + ERR_PRINT("Found open compute list at the end of the frame, this should never happen (further compute will likely not work)."); + } + + { // Complete the setup buffer (that needs to be processed before anything else). + frames[frame].setup_command_list->Close(); + frames[frame].draw_command_list->Close(); + } +} + +void RenderingDeviceD3D12::_begin_frame() { + // Erase pending resources. + _free_pending_resources(frame); + + HRESULT res = frames[frame].setup_command_allocator->Reset(); + ERR_FAIL_COND_MSG(res, "Command allocator Reset failed with error " + vformat("0x%08ux", res) + "."); + res = frames[frame].setup_command_list->Reset(frames[frame].setup_command_allocator.Get(), nullptr); + ERR_FAIL_COND_MSG(res, "Command list Reset failed with error " + vformat("0x%08ux", res) + "."); + res = frames[frame].draw_command_allocator->Reset(); + ERR_FAIL_COND_MSG(res, "Command allocator Reset failed with error " + vformat("0x%08ux", res) + "."); + res = frames[frame].draw_command_list->Reset(frames[frame].draw_command_allocator.Get(), nullptr); + ERR_FAIL_COND_MSG(res, "Command list Reset failed with error " + vformat("0x%08ux", res) + "."); + + ID3D12DescriptorHeap *heaps[] = { + frames[frame].desc_heaps.resources.get_heap(), + frames[frame].desc_heaps.samplers.get_heap(), + }; + frames[frame].draw_command_list->SetDescriptorHeaps(2, heaps); + + frames[frame].desc_heap_walkers.resources.rewind(); + frames[frame].desc_heap_walkers.samplers.rewind(); + frames[frame].desc_heap_walkers.aux.rewind(); + frames[frame].desc_heap_walkers.rtv.rewind(); + frames[frame].desc_heaps_exhausted_reported = {}; + frames[frame].null_rtv_handle = {}; + +#ifdef DEBUG_COUNT_BARRIERS + print_verbose(vformat("Last frame: %d barriers (%d batches); %.1f ms", frame_barriers_count, frame_barriers_batches_count, frame_barriers_cpu_time * 0.001f)); + frame_barriers_count = 0; + frame_barriers_batches_count = 0; + frame_barriers_cpu_time = 0; +#endif + + if (local_device.is_null()) { + context->append_command_list(frames[frame].draw_command_list.Get()); + context->set_setup_list(frames[frame].setup_command_list.Get()); // Append now so it's added before everything else. + } + + // Advance current frame. + frames_drawn++; + // Advance staging buffer if used. + if (staging_buffer_used) { + staging_buffer_current = (staging_buffer_current + 1) % staging_buffer_blocks.size(); + staging_buffer_used = false; + } + + context->get_allocator()->SetCurrentFrameIndex(Engine::get_singleton()->get_frames_drawn()); + if (frames[frame].timestamp_count) { + frames[frame].setup_command_list->ResolveQueryData(frames[frame].timestamp_heap.Get(), D3D12_QUERY_TYPE_TIMESTAMP, 0, frames[frame].timestamp_count, frames[frame].timestamp_result_values_buffer.resource, 0); + uint64_t *gpu_timestamps = nullptr; + res = frames[frame].timestamp_result_values_buffer.resource->Map(0, nullptr, (void **)&gpu_timestamps); + if (SUCCEEDED(res)) { + memcpy(frames[frame].timestamp_result_values.ptr(), gpu_timestamps, sizeof(uint64_t) * frames[frame].timestamp_count); + frames[frame].timestamp_result_values_buffer.resource->Unmap(0, nullptr); + } + SWAP(frames[frame].timestamp_names, frames[frame].timestamp_result_names); + SWAP(frames[frame].timestamp_cpu_values, frames[frame].timestamp_cpu_result_values); + } + + frames[frame].timestamp_result_count = frames[frame].timestamp_count; + frames[frame].timestamp_count = 0; + frames[frame].index = Engine::get_singleton()->get_frames_drawn(); + frames[frame].execution_index = execution_index; +#ifdef DEV_ENABLED + frames[frame].uniform_set_reused = 0; +#endif +} + +void RenderingDeviceD3D12::swap_buffers() { + ERR_FAIL_COND_MSG(local_device.is_valid(), "Local devices can't swap buffers."); + _THREAD_SAFE_METHOD_ + + context->postpare_buffers(frames[frame].draw_command_list.Get()); + screen_prepared = false; + + _finalize_command_bufers(); + + context->swap_buffers(); + execution_index++; + + frame = (frame + 1) % frame_count; + + _begin_frame(); +} + +void RenderingDeviceD3D12::submit() { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND_MSG(local_device.is_null(), "Only local devices can submit and sync."); + ERR_FAIL_COND_MSG(local_device_processing, "device already submitted, call sync to wait until done."); + + _finalize_command_bufers(); + + ID3D12CommandList *command_lists[2] = { frames[frame].setup_command_list.Get(), frames[frame].draw_command_list.Get() }; + context->local_device_push_command_lists(local_device, command_lists, 2); + execution_index++; + + local_device_processing = true; +} + +void RenderingDeviceD3D12::sync() { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND_MSG(local_device.is_null(), "Only local devices can submit and sync."); + ERR_FAIL_COND_MSG(!local_device_processing, "sync can only be called after a submit"); + + context->local_device_sync(local_device); + _begin_frame(); + local_device_processing = false; +} + +#ifdef USE_SMALL_ALLOCS_POOL +D3D12MA::Pool *RenderingDeviceD3D12::_find_or_create_small_allocs_pool(D3D12_HEAP_TYPE p_heap_type, D3D12_HEAP_FLAGS p_heap_flags) { + D3D12_HEAP_FLAGS effective_heap_flags = p_heap_flags; + if (context->get_allocator()->GetD3D12Options().ResourceHeapTier != D3D12_RESOURCE_HEAP_TIER_1) { + // Heap tier 2 allows mixing resource types liberally. + effective_heap_flags &= ~(D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS | D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES | D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES); + } + + AllocPoolKey pool_key; + pool_key.heap_type = p_heap_type; + pool_key.heap_flags = effective_heap_flags; + if (small_allocs_pools.has(pool_key.key)) { + return small_allocs_pools[pool_key.key].Get(); + } + +#ifdef DEV_ENABLED + print_verbose("Creating D3D12MA small objects pool for heap type " + itos(p_heap_type) + " and heap flags " + itos(p_heap_flags)); +#endif + + D3D12MA::POOL_DESC poolDesc = {}; + poolDesc.HeapProperties.Type = p_heap_type; + poolDesc.HeapFlags = effective_heap_flags; + + ComPtr<D3D12MA::Pool> pool; + HRESULT res = context->get_allocator()->CreatePool(&poolDesc, pool.GetAddressOf()); + small_allocs_pools[pool_key.key] = pool; // Don't try to create it again if failed the first time. + ERR_FAIL_COND_V_MSG(res, nullptr, "CreatePool failed with error " + vformat("0x%08ux", res) + "."); + + return pool.Get(); +} +#endif + +void RenderingDeviceD3D12::_free_pending_resources(int p_frame) { + // Free in dependency usage order, so nothing weird happens. + // Pipelines. + while (frames[p_frame].render_pipelines_to_dispose_of.front()) { + RenderPipeline *rp = &frames[p_frame].render_pipelines_to_dispose_of.front()->get(); + pipeline_bindings.erase(rp->bindings_id); + frames[p_frame].render_pipelines_to_dispose_of.pop_front(); + } + while (frames[p_frame].compute_pipelines_to_dispose_of.front()) { + ComputePipeline *cp = &frames[p_frame].compute_pipelines_to_dispose_of.front()->get(); + pipeline_bindings.erase(cp->bindings_id); + frames[p_frame].compute_pipelines_to_dispose_of.pop_front(); + } + + // Shaders. + frames[p_frame].shaders_to_dispose_of.clear(); + + // Framebuffers. + frames[p_frame].framebuffers_to_dispose_of.clear(); + + // Textures. + while (frames[p_frame].textures_to_dispose_of.front()) { + Texture *texture = &frames[p_frame].textures_to_dispose_of.front()->get(); + + if (texture->bound) { + WARN_PRINT("Deleted a texture while it was bound."); + } + if (texture->owner.is_null()) { + // Actually owns the image and the allocation too. + image_memory -= texture->allocation->GetSize(); + for (uint32_t i = 0; i < texture->aliases.size(); i++) { + if (texture->aliases[i]) { + texture->aliases[i]->Release(); + } + } + texture->resource->Release(); + texture->resource = nullptr; + texture->allocation->Release(); + texture->allocation = nullptr; + } + frames[p_frame].textures_to_dispose_of.pop_front(); + } + + // Buffers. + while (frames[p_frame].buffers_to_dispose_of.front()) { + _buffer_free(&frames[p_frame].buffers_to_dispose_of.front()->get()); + + frames[p_frame].buffers_to_dispose_of.pop_front(); + } +} + +void RenderingDeviceD3D12::prepare_screen_for_drawing() { + _THREAD_SAFE_METHOD_ + context->prepare_buffers(frames[frame].draw_command_list.Get()); + screen_prepared = true; +} + +uint32_t RenderingDeviceD3D12::get_frame_delay() const { + return frame_count; +} + +uint64_t RenderingDeviceD3D12::get_memory_usage(MemoryType p_type) const { + if (p_type == MEMORY_BUFFERS) { + return buffer_memory; + } else if (p_type == MEMORY_TEXTURES) { + return image_memory; + } else { + D3D12MA::TotalStatistics stats; + context->get_allocator()->CalculateStatistics(&stats); + return stats.Total.Stats.BlockBytes; + } +} + +void RenderingDeviceD3D12::_flush(bool p_flush_current_frame) { + if (local_device.is_valid() && !p_flush_current_frame) { + return; // Flushing previous frames has no effect with local device. + } + + if (p_flush_current_frame) { + frames[frame].setup_command_list->Close(); + frames[frame].draw_command_list->Close(); + } + + if (local_device.is_valid()) { + ID3D12CommandList *command_lists[2] = { frames[frame].setup_command_list.Get(), frames[frame].draw_command_list.Get() }; + context->local_device_push_command_lists(local_device, command_lists, 2); + execution_index++; + context->local_device_sync(local_device); + + HRESULT res = frames[frame].setup_command_allocator->Reset(); + ERR_FAIL_COND_MSG(res, "Command allocator Reset failed with error " + vformat("0x%08ux", res) + "."); + res = frames[frame].setup_command_list->Reset(frames[frame].setup_command_allocator.Get(), nullptr); + ERR_FAIL_COND_MSG(res, "Command allocator Reset failed with error " + vformat("0x%08ux", res) + "."); + res = frames[frame].draw_command_allocator->Reset(); + ERR_FAIL_COND_MSG(res, "Command allocator Reset failed with error " + vformat("0x%08ux", res) + "."); + res = frames[frame].draw_command_list->Reset(frames[frame].draw_command_allocator.Get(), nullptr); + ERR_FAIL_COND_MSG(res, "Command allocator Reset failed with error " + vformat("0x%08ux", res) + "."); + + ID3D12DescriptorHeap *heaps[] = { + frames[frame].desc_heaps.resources.get_heap(), + frames[frame].desc_heaps.samplers.get_heap(), + }; + frames[frame].draw_command_list->SetDescriptorHeaps(2, heaps); + frames[frame].desc_heap_walkers.resources.rewind(); + frames[frame].desc_heap_walkers.samplers.rewind(); + frames[frame].desc_heap_walkers.aux.rewind(); + frames[frame].desc_heap_walkers.rtv.rewind(); + frames[frame].desc_heaps_exhausted_reported = {}; + frames[frame].null_rtv_handle = {}; + frames[frame].execution_index = execution_index; + } else { + context->flush(p_flush_current_frame, p_flush_current_frame); + // Re-create the setup command. + if (p_flush_current_frame) { + execution_index++; + + HRESULT res = frames[frame].setup_command_allocator->Reset(); + ERR_FAIL_COND_MSG(res, "Command allocator Reset failed with error " + vformat("0x%08ux", res) + "."); + res = frames[frame].draw_command_allocator->Reset(); + ERR_FAIL_COND_MSG(res, "Command allocator Reset failed with error " + vformat("0x%08ux", res) + "."); + res = frames[frame].setup_command_list->Reset(frames[frame].setup_command_allocator.Get(), nullptr); + ERR_FAIL_COND_MSG(res, "Command list Reset failed with error " + vformat("0x%08ux", res) + "."); + res = frames[frame].draw_command_list->Reset(frames[frame].draw_command_allocator.Get(), nullptr); + ERR_FAIL_COND_MSG(res, "Command list Reset failed with error " + vformat("0x%08ux", res) + "."); + + ID3D12DescriptorHeap *heaps[] = { + frames[frame].desc_heaps.resources.get_heap(), + frames[frame].desc_heaps.samplers.get_heap(), + }; + frames[frame].draw_command_list->SetDescriptorHeaps(2, heaps); + + frames[frame].desc_heap_walkers.resources.rewind(); + frames[frame].desc_heap_walkers.samplers.rewind(); + frames[frame].desc_heap_walkers.aux.rewind(); + frames[frame].desc_heap_walkers.rtv.rewind(); + frames[frame].desc_heaps_exhausted_reported = {}; + frames[frame].null_rtv_handle = {}; + frames[frame].execution_index = execution_index; + + context->set_setup_list(frames[frame].setup_command_list.Get()); // Append now so it's added before everything else. + context->append_command_list(frames[frame].draw_command_list.Get()); + } + } +} + +void RenderingDeviceD3D12::initialize(D3D12Context *p_context, bool p_local_device) { + // Get our device capabilities. + { + device_capabilities.version_major = p_context->get_feat_level_major(); + device_capabilities.version_minor = p_context->get_feat_level_minor(); + } + + context = p_context; + device = p_context->get_device(); + if (p_local_device) { + frame_count = 1; + local_device = p_context->local_device_create(); + device = p_context->local_device_get_d3d12_device(local_device); + } else { + frame_count = p_context->get_swapchain_image_count() + 1; + } + limits = p_context->get_device_limits(); + max_timestamp_query_elements = 256; + + { // Create command signature for indirect dispatch. + D3D12_INDIRECT_ARGUMENT_DESC iarg_desc = {}; + iarg_desc.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH; + D3D12_COMMAND_SIGNATURE_DESC cs_desc = {}; + cs_desc.ByteStride = sizeof(D3D12_DISPATCH_ARGUMENTS); + cs_desc.NumArgumentDescs = 1; + cs_desc.pArgumentDescs = &iarg_desc; + cs_desc.NodeMask = 0; + HRESULT res = device->CreateCommandSignature(&cs_desc, nullptr, IID_PPV_ARGS(indirect_dispatch_cmd_sig.GetAddressOf())); + ERR_FAIL_COND_MSG(res, "CreateCommandSignature failed with error " + vformat("0x%08ux", res) + "."); + } + + uint32_t resource_descriptors_per_frame = GLOBAL_DEF("rendering/rendering_device/d3d12/max_resource_descriptors_per_frame", 16384); + uint32_t sampler_descriptors_per_frame = GLOBAL_DEF("rendering/rendering_device/d3d12/max_sampler_descriptors_per_frame", 1024); + uint32_t misc_descriptors_per_frame = GLOBAL_DEF("rendering/rendering_device/d3d12/max_misc_descriptors_per_frame", 512); + + frames.resize(frame_count); + frame = 0; + // Create setup and frame buffers. + for (int i = 0; i < frame_count; i++) { + frames[i].index = 0; + + { // Create descriptor heaps. + Error err = frames[i].desc_heaps.resources.allocate(device.Get(), D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, resource_descriptors_per_frame, true); + ERR_FAIL_COND_MSG(err, "Creating the frame's RESOURCE descriptors heap failed."); + + err = frames[i].desc_heaps.samplers.allocate(device.Get(), D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, sampler_descriptors_per_frame, true); + ERR_FAIL_COND_MSG(err, "Creating the frame's SAMPLER descriptors heap failed."); + + err = frames[i].desc_heaps.aux.allocate(device.Get(), D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, misc_descriptors_per_frame, false); + ERR_FAIL_COND_MSG(err, "Creating the frame's AUX descriptors heap failed."); + + err = frames[i].desc_heaps.rtv.allocate(device.Get(), D3D12_DESCRIPTOR_HEAP_TYPE_RTV, misc_descriptors_per_frame, false); + ERR_FAIL_COND_MSG(err, "Creating the frame's RENDER TARGET descriptors heap failed."); + + frames[i].desc_heap_walkers.resources = frames[i].desc_heaps.resources.make_walker(); + frames[i].desc_heap_walkers.samplers = frames[i].desc_heaps.samplers.make_walker(); + frames[i].desc_heap_walkers.aux = frames[i].desc_heaps.aux.make_walker(); + frames[i].desc_heap_walkers.rtv = frames[i].desc_heaps.rtv.make_walker(); + } + + { // Create command allocators. + HRESULT res = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(frames[i].setup_command_allocator.GetAddressOf())); + ERR_CONTINUE_MSG(res, "CreateCommandAllocator failed with error " + vformat("0x%08ux", res) + "."); + + res = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(frames[i].draw_command_allocator.GetAddressOf())); + ERR_CONTINUE_MSG(res, "CreateCommandAllocator failed with error " + vformat("0x%08ux", res) + "."); + } + + { // Create command lists. + HRESULT res = device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, frames[i].setup_command_allocator.Get(), nullptr, IID_PPV_ARGS(frames[i].setup_command_list.GetAddressOf())); + ERR_CONTINUE_MSG(res, "CreateCommandList failed with error " + vformat("0x%08ux", res) + "."); + + res = device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, frames[i].draw_command_allocator.Get(), nullptr, IID_PPV_ARGS(frames[i].draw_command_list.GetAddressOf())); + ERR_CONTINUE_MSG(res, "CreateCommandList failed with error " + vformat("0x%08ux", res) + "."); + + if (i > 0) { + frames[i].setup_command_list->Close(); + frames[i].draw_command_list->Close(); + } + } + + if (i == 0) { + ID3D12DescriptorHeap *heaps[] = { + frames[frame].desc_heaps.resources.get_heap(), + frames[frame].desc_heaps.samplers.get_heap(), + }; + frames[frame].draw_command_list->SetDescriptorHeaps(2, heaps); + } + + { + // Create query heap. + D3D12_QUERY_HEAP_DESC qh_desc = {}; + qh_desc.Type = D3D12_QUERY_HEAP_TYPE_TIMESTAMP; + qh_desc.Count = max_timestamp_query_elements; + qh_desc.NodeMask = 0; + HRESULT res = device->CreateQueryHeap(&qh_desc, IID_PPV_ARGS(frames[i].timestamp_heap.GetAddressOf())); + ERR_CONTINUE_MSG(res, "CreateQueryHeap failed with error " + vformat("0x%08ux", res) + "."); + + frames[i].timestamp_names.resize(max_timestamp_query_elements); + frames[i].timestamp_cpu_values.resize(max_timestamp_query_elements); + frames[i].timestamp_count = 0; + frames[i].timestamp_result_names.resize(max_timestamp_query_elements); + frames[i].timestamp_cpu_result_values.resize(max_timestamp_query_elements); + frames[i].timestamp_result_values.resize(max_timestamp_query_elements); + Error err = _buffer_allocate(&frames[i].timestamp_result_values_buffer, sizeof(uint64_t) * max_timestamp_query_elements, D3D12_RESOURCE_STATE_COMMON, D3D12_HEAP_TYPE_READBACK); + ERR_CONTINUE(err); + frames[i].timestamp_result_count = 0; + } + } + + if (local_device.is_null()) { + context->set_setup_list(frames[0].setup_command_list.Get()); // Append now so it's added before everything else. + context->append_command_list(frames[0].draw_command_list.Get()); + } + + staging_buffer_block_size = GLOBAL_GET("rendering/rendering_device/staging_buffer/block_size_kb"); + staging_buffer_block_size = MAX(4u, staging_buffer_block_size); + staging_buffer_block_size *= 1024; // Kb -> bytes. + staging_buffer_max_size = GLOBAL_GET("rendering/rendering_device/staging_buffer/max_size_mb"); + staging_buffer_max_size = MAX(1u, staging_buffer_max_size); + staging_buffer_max_size *= 1024 * 1024; + + if (staging_buffer_max_size < staging_buffer_block_size * 4) { + // Validate enough functions. + staging_buffer_max_size = staging_buffer_block_size * 4; + } + texture_upload_region_size_px = GLOBAL_GET("rendering/rendering_device/staging_buffer/texture_upload_region_size_px"); + texture_upload_region_size_px = nearest_power_of_2_templated(texture_upload_region_size_px); + + frames_drawn = frame_count; // Start from frame count, so everything else is immediately old. + execution_index = 1; + + // Ensure current staging block is valid and at least one per frame exists. + staging_buffer_current = 0; + staging_buffer_used = false; + + for (int i = 0; i < frame_count; i++) { + // Staging was never used, create a block. + Error err = _insert_staging_block(); + ERR_CONTINUE(err != OK); + } + + { + aux_resource = texture_create(TextureFormat(), TextureView()); + ERR_FAIL_COND(!aux_resource.is_valid()); + } + + draw_list = nullptr; + draw_list_count = 0; + draw_list_split = false; + + vrs_state_execution_index = 0; + vrs_state = {}; + + compute_list = nullptr; + + glsl_type_singleton_init_or_ref(); +} + +dxil_validator *RenderingDeviceD3D12::get_dxil_validator_for_current_thread() { + MutexLock lock(dxil_mutex); + + int thread_idx = WorkerThreadPool::get_singleton()->get_thread_index(); + if (dxil_validators.has(thread_idx)) { + return dxil_validators[thread_idx]; + } + +#ifdef DEV_ENABLED + print_verbose("Creating DXIL validator for worker thread index " + itos(thread_idx)); +#endif + + dxil_validator *dxil_validator = dxil_create_validator(nullptr); + CRASH_COND(!dxil_validator); + + dxil_validators.insert(thread_idx, dxil_validator); + return dxil_validator; +} + +template <class T> +void RenderingDeviceD3D12::_free_rids(T &p_owner, const char *p_type) { + List<RID> owned; + p_owner.get_owned_list(&owned); + if (owned.size()) { + if (owned.size() == 1) { + WARN_PRINT(vformat("1 RID of type \"%s\" was leaked.", p_type)); + } else { + WARN_PRINT(vformat("%d RIDs of type \"%s\" were leaked.", owned.size(), p_type)); + } + for (const RID &E : owned) { +#ifdef DEV_ENABLED + if (resource_names.has(E)) { + print_line(String(" - ") + resource_names[E]); + } +#endif + free(E); + } + } +} + +void RenderingDeviceD3D12::capture_timestamp(const String &p_name) { + ERR_FAIL_COND_MSG(draw_list != nullptr, "Capturing timestamps during draw list creation is not allowed. Offending timestamp was: " + p_name); + ERR_FAIL_COND(frames[frame].timestamp_count >= max_timestamp_query_elements); + + // This should be optional for profiling, else it will slow things down. + full_barrier(); + + frames[frame].draw_command_list->EndQuery(frames[frame].timestamp_heap.Get(), D3D12_QUERY_TYPE_TIMESTAMP, frames[frame].timestamp_count); + frames[frame].timestamp_names[frames[frame].timestamp_count] = p_name; + frames[frame].timestamp_cpu_values[frames[frame].timestamp_count] = OS::get_singleton()->get_ticks_usec(); + frames[frame].timestamp_count++; +} + +uint64_t RenderingDeviceD3D12::get_driver_resource(DriverResource p_resource, RID p_rid, uint64_t p_index) { + _THREAD_SAFE_METHOD_ + return 0; +} + +uint32_t RenderingDeviceD3D12::get_captured_timestamps_count() const { + return frames[frame].timestamp_result_count; +} + +uint64_t RenderingDeviceD3D12::get_captured_timestamps_frame() const { + return frames[frame].index; +} + +uint64_t RenderingDeviceD3D12::get_captured_timestamp_gpu_time(uint32_t p_index) const { + ERR_FAIL_UNSIGNED_INDEX_V(p_index, frames[frame].timestamp_result_count, 0); + + return frames[frame].timestamp_result_values[p_index] / (double)limits.timestamp_frequency * 1000000000.0; +} + +uint64_t RenderingDeviceD3D12::get_captured_timestamp_cpu_time(uint32_t p_index) const { + ERR_FAIL_UNSIGNED_INDEX_V(p_index, frames[frame].timestamp_result_count, 0); + return frames[frame].timestamp_cpu_result_values[p_index]; +} + +String RenderingDeviceD3D12::get_captured_timestamp_name(uint32_t p_index) const { + ERR_FAIL_UNSIGNED_INDEX_V(p_index, frames[frame].timestamp_result_count, String()); + return frames[frame].timestamp_result_names[p_index]; +} + +uint64_t RenderingDeviceD3D12::limit_get(Limit p_limit) const { + switch (p_limit) { + case LIMIT_MAX_TEXTURES_PER_SHADER_STAGE: + return limits.max_srvs_per_shader_stage; + case LIMIT_MAX_UNIFORM_BUFFER_SIZE: + return 65536; + case LIMIT_MAX_VIEWPORT_DIMENSIONS_X: + case LIMIT_MAX_VIEWPORT_DIMENSIONS_Y: + return 16384; // Based on max. texture size. Maybe not correct. + case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_X: + return D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION; + case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Y: + return D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION; + case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Z: + return D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION; + case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_X: + return D3D12_CS_THREAD_GROUP_MAX_X; + case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Y: + return D3D12_CS_THREAD_GROUP_MAX_Y; + case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Z: + return D3D12_CS_THREAD_GROUP_MAX_Z; + case LIMIT_SUBGROUP_SIZE: + // Note in min/max. Shader model 6.6 supports it (see https://microsoft.github.io/DirectX-Specs/d3d/HLSL_SM_6_6_WaveSize.html), + // but at this time I don't know the implications on the transpilation to DXIL, etc. + case LIMIT_SUBGROUP_MIN_SIZE: + case LIMIT_SUBGROUP_MAX_SIZE: { + D3D12Context::SubgroupCapabilities subgroup_capabilities = context->get_subgroup_capabilities(); + return subgroup_capabilities.size; + } + case LIMIT_SUBGROUP_IN_SHADERS: { + D3D12Context::SubgroupCapabilities subgroup_capabilities = context->get_subgroup_capabilities(); + return subgroup_capabilities.supported_stages_flags_rd(); + } + case LIMIT_SUBGROUP_OPERATIONS: { + D3D12Context::SubgroupCapabilities subgroup_capabilities = context->get_subgroup_capabilities(); + return subgroup_capabilities.supported_operations_flags_rd(); + } + case LIMIT_VRS_TEXEL_WIDTH: + case LIMIT_VRS_TEXEL_HEIGHT: { + return context->get_vrs_capabilities().ss_image_tile_size; + } + default: + // It's important to return a number that at least won't overflow any typical integer type. +#ifdef DEV_ENABLED + WARN_PRINT("Returning maximum value for unknown limit " + itos(p_limit) + "."); +#endif + return (uint64_t)1 << 30; + } +} + +bool RenderingDeviceD3D12::has_feature(const Features p_feature) const { + switch (p_feature) { + case SUPPORTS_MULTIVIEW: { + D3D12Context::MultiviewCapabilities multiview_capabilies = context->get_multiview_capabilities(); + return multiview_capabilies.is_supported && multiview_capabilies.max_view_count > 1; + } break; + case SUPPORTS_FSR_HALF_FLOAT: { + return context->get_shader_capabilities().native_16bit_ops && context->get_storage_buffer_capabilities().storage_buffer_16_bit_access_is_supported; + } break; + case SUPPORTS_ATTACHMENT_VRS: { + D3D12Context::VRSCapabilities vrs_capabilities = context->get_vrs_capabilities(); + return vrs_capabilities.ss_image_supported; + } break; + case SUPPORTS_FRAGMENT_SHADER_WITH_ONLY_SIDE_EFFECTS: { + return true; + } break; + default: { + return false; + } + } +} + +void RenderingDeviceD3D12::finalize() { + // Free all resources. + + _flush(false); + + free(aux_resource); + + _free_rids(render_pipeline_owner, "Pipeline"); + _free_rids(compute_pipeline_owner, "Compute"); + _free_rids(uniform_set_owner, "UniformSet"); + _free_rids(texture_buffer_owner, "TextureBuffer"); + _free_rids(storage_buffer_owner, "StorageBuffer"); + _free_rids(uniform_buffer_owner, "UniformBuffer"); + _free_rids(shader_owner, "Shader"); + _free_rids(index_array_owner, "IndexArray"); + _free_rids(index_buffer_owner, "IndexBuffer"); + _free_rids(vertex_array_owner, "VertexArray"); + _free_rids(vertex_buffer_owner, "VertexBuffer"); + _free_rids(framebuffer_owner, "Framebuffer"); + _free_rids(sampler_owner, "Sampler"); + { + // For textures it's a bit more difficult because they may be shared. + List<RID> owned; + texture_owner.get_owned_list(&owned); + if (owned.size()) { + if (owned.size() == 1) { + WARN_PRINT("1 RID of type \"Texture\" was leaked."); + } else { + WARN_PRINT(vformat("%d RIDs of type \"Texture\" were leaked.", owned.size())); + } + // Free shared first. + for (List<RID>::Element *E = owned.front(); E;) { + List<RID>::Element *N = E->next(); + if (texture_is_shared(E->get())) { +#ifdef DEV_ENABLED + if (resource_names.has(E->get())) { + print_line(String(" - ") + resource_names[E->get()]); + } +#endif + free(E->get()); + owned.erase(E); + } + E = N; + } + // Free non shared second, this will avoid an error trying to free unexisting textures due to dependencies. + for (const RID &E : owned) { +#ifdef DEV_ENABLED + if (resource_names.has(E)) { + print_line(String(" - ") + resource_names[E]); + } +#endif + free(E); + } + } + } + + // Free everything pending. + for (int i = 0; i < frame_count; i++) { + int f = (frame + i) % frame_count; + _free_pending_resources(f); + frames[i].timestamp_result_values_buffer.allocation->Release(); + frames[i].timestamp_result_values_buffer.resource->Release(); + } + + frames.clear(); + + pipeline_bindings.clear(); + next_pipeline_binding_id = 1; + + for (int i = 0; i < split_draw_list_allocators.size(); i++) { + for (int j = 0; i < split_draw_list_allocators[i].command_lists.size(); j++) { + split_draw_list_allocators[i].command_lists[j]->Release(); + } + split_draw_list_allocators[i].command_allocator->Release(); + } + + res_barriers_requests.clear(); + res_barriers.clear(); + + for (int i = 0; i < staging_buffer_blocks.size(); i++) { + staging_buffer_blocks[i].allocation->Release(); + staging_buffer_blocks[i].resource->Release(); + } +#ifdef USE_SMALL_ALLOCS_POOL + small_allocs_pools.clear(); +#endif + + indirect_dispatch_cmd_sig.Reset(); + + vertex_formats.clear(); + + framebuffer_formats.clear(); + + // All these should be clear at this point. + ERR_FAIL_COND(dependency_map.size()); + ERR_FAIL_COND(reverse_dependency_map.size()); + + { + MutexLock lock(dxil_mutex); + for (const KeyValue<int, dxil_validator *> &E : dxil_validators) { + dxil_destroy_validator(E.value); + } + } + + glsl_type_singleton_decref(); +} + +RenderingDevice *RenderingDeviceD3D12::create_local_device() { + RenderingDeviceD3D12 *rd = memnew(RenderingDeviceD3D12); + rd->initialize(context, true); + return rd; +} + +RenderingDeviceD3D12::RenderingDeviceD3D12() { + device_capabilities.device_family = DEVICE_DIRECTX; +} + +RenderingDeviceD3D12::~RenderingDeviceD3D12() { + if (local_device.is_valid()) { + finalize(); + context->local_device_free(local_device); + } +} diff --git a/drivers/d3d12/rendering_device_d3d12.h b/drivers/d3d12/rendering_device_d3d12.h new file mode 100644 index 0000000000..92ae2f78fb --- /dev/null +++ b/drivers/d3d12/rendering_device_d3d12.h @@ -0,0 +1,1277 @@ +/**************************************************************************/ +/* rendering_device_d3d12.h */ +/**************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/**************************************************************************/ +/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ +/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/**************************************************************************/ + +#ifndef RENDERING_DEVICE_D3D12_H +#define RENDERING_DEVICE_D3D12_H + +#include "core/os/thread_safe.h" +#include "core/templates/local_vector.h" +#include "core/templates/oa_hash_map.h" +#include "core/templates/rid_owner.h" +#include "drivers/d3d12/d3d12_context.h" +#include "servers/rendering/rendering_device.h" + +#include <wrl/client.h> + +using Microsoft::WRL::ComPtr; + +#define D3D12_BITCODE_OFFSETS_NUM_STAGES 3 + +struct dxil_validator; + +class RenderingDeviceD3D12 : public RenderingDevice { + _THREAD_SAFE_CLASS_ + // Miscellaneous tables that map + // our enums to enums used + // by DXGI/D3D12. + + D3D12Context::DeviceLimits limits = {}; + struct D3D12Format { + DXGI_FORMAT family = DXGI_FORMAT_UNKNOWN; + DXGI_FORMAT general_format = DXGI_FORMAT_UNKNOWN; + UINT swizzle = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + DXGI_FORMAT dsv_format = DXGI_FORMAT_UNKNOWN; + }; + static const D3D12Format d3d12_formats[DATA_FORMAT_MAX]; + static const char *named_formats[DATA_FORMAT_MAX]; + static const D3D12_COMPARISON_FUNC compare_operators[COMPARE_OP_MAX]; + static const D3D12_STENCIL_OP stencil_operations[STENCIL_OP_MAX]; + static const UINT rasterization_sample_count[TEXTURE_SAMPLES_MAX]; + static const D3D12_LOGIC_OP logic_operations[RenderingDevice::LOGIC_OP_MAX]; + static const D3D12_BLEND blend_factors[RenderingDevice::BLEND_FACTOR_MAX]; + static const D3D12_BLEND_OP blend_operations[RenderingDevice::BLEND_OP_MAX]; + static const D3D12_TEXTURE_ADDRESS_MODE address_modes[SAMPLER_REPEAT_MODE_MAX]; + static const FLOAT sampler_border_colors[SAMPLER_BORDER_COLOR_MAX][4]; + static const D3D12_RESOURCE_DIMENSION d3d12_texture_dimension[TEXTURE_TYPE_MAX]; + + // Functions used for format + // validation, and ensures the + // user passes valid data. + + static int get_format_vertex_size(DataFormat p_format); + static uint32_t get_image_format_pixel_size(DataFormat p_format); + static void get_compressed_image_format_block_dimensions(DataFormat p_format, uint32_t &r_w, uint32_t &r_h); + uint32_t get_compressed_image_format_block_byte_size(DataFormat p_format); + static uint32_t get_compressed_image_format_pixel_rshift(DataFormat p_format); + static uint32_t get_image_format_plane_count(DataFormat p_format); + static uint32_t get_image_format_required_size(DataFormat p_format, uint32_t p_width, uint32_t p_height, uint32_t p_depth, uint32_t p_mipmaps, uint32_t *r_blockw = nullptr, uint32_t *r_blockh = nullptr, uint32_t *r_depth = nullptr); + static uint32_t get_image_required_mipmaps(uint32_t p_width, uint32_t p_height, uint32_t p_depth); + static bool format_has_stencil(DataFormat p_format); + + Mutex dxil_mutex; + HashMap<int, dxil_validator *> dxil_validators; // One per WorkerThreadPool thread used for shader compilation, plus one (-1) for all the other. + + dxil_validator *get_dxil_validator_for_current_thread(); + + class DescriptorsHeap { + D3D12_DESCRIPTOR_HEAP_DESC desc = {}; + ComPtr<ID3D12DescriptorHeap> heap; + uint32_t handle_size = 0; + + public: + class Walker { // Texas Ranger. + friend class DescriptorsHeap; + + uint32_t handle_size = 0; + uint32_t handle_count = 0; + D3D12_CPU_DESCRIPTOR_HANDLE first_cpu_handle = {}; + D3D12_GPU_DESCRIPTOR_HANDLE first_gpu_handle = {}; + uint32_t handle_index = 0; + + public: + D3D12_CPU_DESCRIPTOR_HANDLE get_curr_cpu_handle(); + D3D12_GPU_DESCRIPTOR_HANDLE get_curr_gpu_handle(); + _FORCE_INLINE_ void rewind() { handle_index = 0; } + void advance(uint32_t p_count = 1); + uint32_t get_current_handle_index() const { return handle_index; } + uint32_t get_free_handles() { return handle_count - handle_index; } + bool is_at_eof() { return handle_index == handle_count; } + }; + + Error allocate(ID3D12Device *m_device, D3D12_DESCRIPTOR_HEAP_TYPE m_type, uint32_t m_descriptor_count, bool p_for_gpu); + uint32_t get_descriptor_count() const { return desc.NumDescriptors; } + ID3D12DescriptorHeap *get_heap() const { return heap.Get(); } + + Walker make_walker() const; + }; + + /***************************/ + /**** ID INFRASTRUCTURE ****/ + /***************************/ + + enum IDType { + ID_TYPE_FRAMEBUFFER_FORMAT, + ID_TYPE_VERTEX_FORMAT, + ID_TYPE_DRAW_LIST, + ID_TYPE_SPLIT_DRAW_LIST, + ID_TYPE_COMPUTE_LIST, + ID_TYPE_MAX, + ID_BASE_SHIFT = 58 // 5 bits for ID types. + }; + + ComPtr<ID3D12Device> device; + + HashMap<RID, HashSet<RID>> dependency_map; // IDs to IDs that depend on it. + HashMap<RID, HashSet<RID>> reverse_dependency_map; // Same as above, but in reverse. + + void _add_dependency(RID p_id, RID p_depends_on); + void _free_dependencies(RID p_id); + + /******************/ + /**** RESOURCE ****/ + /******************/ + + class ResourceState { + D3D12_RESOURCE_STATES states = D3D12_RESOURCE_STATE_COMMON; + + public: + void extend(D3D12_RESOURCE_STATES p_states_to_add); + D3D12_RESOURCE_STATES get_state_mask() const { return states; } + + ResourceState() {} + ResourceState(D3D12_RESOURCE_STATES p_states) : + states(p_states) {} + }; + + struct Resource { + struct States { + // As many subresources as mipmaps * layers; planes (for depth-stencil) are tracked together. + LocalVector<D3D12_RESOURCE_STATES> subresource_states; // Used only if not a view. + uint32_t last_batch_transitioned_to_uav = 0; + uint32_t last_batch_with_uav_barrier = 0; + }; + + ID3D12Resource *resource = nullptr; + D3D12MA::Allocation *allocation = nullptr; + + States own_states; // Used only if not a view. + States *states = nullptr; // Non-null only if a view. + + States *get_states_ptr() { return states ? states : &own_states; } + }; + + struct BarrierRequest { + static const uint32_t MAX_GROUPS = 4; + // Maybe this is too much data to have it locally. Benchmarking may reveal that + // cache would be used better by having a maximum of local subresource masks and beyond + // that have an allocated vector with the rest. + static const uint32_t MAX_SUBRESOURCES = 4096; // Must be multiple of 64. + ID3D12Resource *dx_resource; + uint8_t subres_mask_qwords; + uint8_t planes; + struct Group { + ResourceState state; + uint64_t subres_mask[MAX_SUBRESOURCES / 64]; + } groups[MAX_GROUPS]; + uint8_t groups_count; + static const D3D12_RESOURCE_STATES DELETED_GROUP = D3D12_RESOURCE_STATE_COMMON; + }; + HashMap<Resource::States *, BarrierRequest> res_barriers_requests; + + LocalVector<D3D12_RESOURCE_BARRIER> res_barriers; + uint32_t res_barriers_count = 0; + uint32_t res_barriers_batch = 0; +#ifdef DEV_ENABLED + int frame_barriers_count = 0; + int frame_barriers_batches_count = 0; + uint64_t frame_barriers_cpu_time = 0; +#endif + + void _resource_transition_batch(Resource *p_resource, uint32_t p_subresource, uint32_t p_num_planes, D3D12_RESOURCE_STATES p_new_state, ID3D12Resource *p_resource_override = nullptr); + void _resource_transitions_flush(ID3D12GraphicsCommandList *p_command_list); + + /*****************/ + /**** TEXTURE ****/ + /*****************/ + + struct Texture : Resource { + D3D12_SHADER_RESOURCE_VIEW_DESC srv_desc = {}; + D3D12_UNORDERED_ACCESS_VIEW_DESC uav_desc = {}; + D3D12_UNORDERED_ACCESS_VIEW_DESC owner_uav_desc = {}; // [[CROSS_FAMILY_ALIASING]]. + + TextureType type; + DataFormat format; + uint32_t planes = 1; + TextureSamples samples; + uint32_t width = 0; + uint32_t height = 0; + uint32_t depth = 0; + uint32_t layers = 0; + uint32_t mipmaps = 0; + uint32_t owner_layers = 0; + uint32_t owner_mipmaps = 0; + uint32_t usage_flags = 0; + uint32_t base_mipmap = 0; + uint32_t base_layer = 0; + + Vector<DataFormat> allowed_shared_formats; + TightLocalVector<ID3D12Resource *> aliases; // [[CROSS_FAMILY_ALIASING]]. + ID3D12Resource *owner_resource = nullptr; // Always the one of the main format passed to creation. [[CROSS_FAMILY_ALIASING]]. + + bool is_resolve_buffer = false; + + bool bound = false; // Bound to framebffer. + RID owner; + }; + + RID_Owner<Texture, true> texture_owner; + uint32_t texture_upload_region_size_px = 0; + + Vector<uint8_t> _texture_get_data_from_image(Texture *tex, uint32_t p_layer, bool p_2d = false); + Error _texture_update(Texture *p_texture, uint32_t p_layer, const Vector<uint8_t> &p_data, BitField<BarrierMask> p_post_barrier, ID3D12GraphicsCommandList *p_command_list); + + /*****************/ + /**** SAMPLER ****/ + /*****************/ + + RID_Owner<D3D12_SAMPLER_DESC> sampler_owner; + + /***************************/ + /**** BUFFER MANAGEMENT ****/ + /***************************/ + + // These are temporary buffers on CPU memory that hold + // the information until the CPU fetches it and places it + // either on GPU buffers, or images (textures). It ensures + // updates are properly synchronized with whatever the + // GPU is doing. + // + // The logic here is as follows, only 3 of these + // blocks are created at the beginning (one per frame) + // they can each belong to a frame (assigned to current when + // used) and they can only be reused after the same frame is + // recycled. + // + // When CPU requires to allocate more than what is available, + // more of these buffers are created. If a limit is reached, + // then a fence will ensure will wait for blocks allocated + // in previous frames are processed. If that fails, then + // another fence will ensure everything pending for the current + // frame is processed (effectively stalling). + // + // See the comments in the code to understand better how it works. + + struct StagingBufferBlock { + ID3D12Resource *resource = nullptr; // Owned, but ComPtr would have too much overhead in a Vector. + D3D12MA::Allocation *allocation = nullptr; + uint64_t frame_used = 0; + uint32_t fill_amount = 0; + }; + + Vector<StagingBufferBlock> staging_buffer_blocks; + int staging_buffer_current = 0; + uint32_t staging_buffer_block_size = 0; + uint64_t staging_buffer_max_size = 0; + bool staging_buffer_used = false; + + Error _staging_buffer_allocate(uint32_t p_amount, uint32_t p_required_align, uint32_t &r_alloc_offset, uint32_t &r_alloc_size, bool p_can_segment = true); + Error _insert_staging_block(); + + struct Buffer : Resource { + uint32_t size = 0; + D3D12_RESOURCE_STATES usage = {}; + uint32_t last_execution = 0; + }; + + Error _buffer_allocate(Buffer *p_buffer, uint32_t p_size, D3D12_RESOURCE_STATES p_usage, D3D12_HEAP_TYPE p_heap_type); + Error _buffer_free(Buffer *p_buffer); + Error _buffer_update(Buffer *p_buffer, size_t p_offset, const uint8_t *p_data, size_t p_data_size, bool p_use_draw_command_list = false, uint32_t p_required_align = 32); + + /*********************/ + /**** FRAMEBUFFER ****/ + /*********************/ + + static D3D12_RENDER_TARGET_VIEW_DESC _make_rtv_for_texture(const RenderingDeviceD3D12::Texture *p_texture, uint32_t p_mipmap_offset = 0, uint32_t p_layer_offset = 0, uint32_t p_layers = UINT32_MAX); + static D3D12_DEPTH_STENCIL_VIEW_DESC _make_dsv_for_texture(const RenderingDeviceD3D12::Texture *p_texture); + + // In Vulkan we'd create some structures the driver uses for render pass based rendering. + // (Dynamic rendering is supported on Vulkan 1.3+, though, but Godot is not using it.) + // In contrast, in D3D12 we'll go the dynamic rendering way, since it's more convenient + // and render pass based render setup is not available on every version. + // Therefore, we just need to keep the data at hand and use it where appropriate. + + struct FramebufferFormat { + Vector<AttachmentFormat> attachments; + Vector<FramebufferPass> passes; + Vector<TextureSamples> pass_samples; + uint32_t view_count = 1; + uint32_t max_supported_sample_count = 1; + }; + + bool _framebuffer_format_preprocess(FramebufferFormat *p_fb_format, uint32_t p_view_count); + + HashMap<FramebufferFormatID, FramebufferFormat> framebuffer_formats; + + struct Framebuffer { + DisplayServer::WindowID window_id = DisplayServer::INVALID_WINDOW_ID; + FramebufferFormatID format_id = 0; + Vector<RID> texture_ids; // Empty if for screen. + InvalidationCallback invalidated_callback = nullptr; + void *invalidated_callback_userdata = nullptr; + Vector<uint32_t> attachments_handle_inds; // RTV heap index for color; DSV heap index for DSV. + Size2 size; + uint32_t view_count = 1; + DescriptorsHeap rtv_heap; // Used only if not for screen and some color attachments. + D3D12_CPU_DESCRIPTOR_HANDLE screen_rtv_handle = {}; // Used only if for screen. + DescriptorsHeap dsv_heap; // Used only if not for screen and some depth-stencil attachments. + }; + + RID_Owner<Framebuffer, true> framebuffer_owner; + + /***********************/ + /**** VERTEX BUFFER ****/ + /***********************/ + + RID_Owner<Buffer, true> vertex_buffer_owner; + + struct VertexDescriptionKey { + Vector<VertexAttribute> vertex_formats; + bool operator==(const VertexDescriptionKey &p_key) const { + int vdc = vertex_formats.size(); + int vdck = p_key.vertex_formats.size(); + + if (vdc != vdck) { + return false; + } else { + const VertexAttribute *a_ptr = vertex_formats.ptr(); + const VertexAttribute *b_ptr = p_key.vertex_formats.ptr(); + for (int i = 0; i < vdc; i++) { + const VertexAttribute &a = a_ptr[i]; + const VertexAttribute &b = b_ptr[i]; + + if (a.location != b.location) { + return false; + } + if (a.offset != b.offset) { + return false; + } + if (a.format != b.format) { + return false; + } + if (a.stride != b.stride) { + return false; + } + if (a.frequency != b.frequency) { + return false; + } + } + return true; // They are equal. + } + } + + uint32_t hash() const { + int vdc = vertex_formats.size(); + uint32_t h = hash_murmur3_one_32(vdc); + const VertexAttribute *ptr = vertex_formats.ptr(); + for (int i = 0; i < vdc; i++) { + const VertexAttribute &vd = ptr[i]; + h = hash_murmur3_one_32(vd.location, h); + h = hash_murmur3_one_32(vd.offset, h); + h = hash_murmur3_one_32(vd.format, h); + h = hash_murmur3_one_32(vd.stride, h); + h = hash_murmur3_one_32(vd.frequency, h); + } + return hash_fmix32(h); + } + }; + + struct VertexDescriptionHash { + static _FORCE_INLINE_ uint32_t hash(const VertexDescriptionKey &p_key) { + return p_key.hash(); + } + }; + + // This is a cache and it's never freed, it ensures that + // ID used for a specific format always remain the same. + HashMap<VertexDescriptionKey, VertexFormatID, VertexDescriptionHash> vertex_format_cache; + + struct VertexDescriptionCache { + Vector<VertexAttribute> vertex_formats; + Vector<D3D12_INPUT_ELEMENT_DESC> elements_desc; + }; + + HashMap<VertexFormatID, VertexDescriptionCache> vertex_formats; + + struct VertexArray { + Vector<Buffer *> unique_buffers; + VertexFormatID description = 0; + int vertex_count = 0; + uint32_t max_instances_allowed = 0; + Vector<D3D12_VERTEX_BUFFER_VIEW> views; + }; + + RID_Owner<VertexArray, true> vertex_array_owner; + + struct IndexBuffer : public Buffer { + uint32_t max_index = 0; // Used for validation. + uint32_t index_count = 0; + DXGI_FORMAT index_format = {}; + bool supports_restart_indices = false; + }; + + RID_Owner<IndexBuffer, true> index_buffer_owner; + + struct IndexArray { + IndexBuffer *buffer = nullptr; + uint32_t max_index = 0; // Remember the maximum index here too, for validation. + uint32_t offset = 0; + uint32_t indices = 0; + bool supports_restart_indices = false; + D3D12_INDEX_BUFFER_VIEW view = {}; + }; + + RID_Owner<IndexArray, true> index_array_owner; + + /****************/ + /**** SHADER ****/ + /****************/ + + static const uint32_t ROOT_SIGNATURE_SIZE = 256; + static const uint32_t PUSH_CONSTANT_SIZE = 128; // Mimicking Vulkan. + + enum { + // We can only aim to set a maximum here, since depending on the shader + // there may be more or less root signature free for descriptor tables. + // Therefore, we'll have to rely on the final check at runtime, when building + // the root signature structure for a given shader. + // To be precise, these may be present or not, and their size vary statically: + // - Push constant (we'll assume this is always present to avoid reserving much + // more space for descriptor sets than needed for almost any imaginable case, + // given that most shader templates feature push constants). + // - NIR-DXIL runtime data. + MAX_UNIFORM_SETS = (ROOT_SIGNATURE_SIZE - PUSH_CONSTANT_SIZE) / sizeof(uint32_t), + }; + + enum ResourceClass { + RES_CLASS_INVALID, + RES_CLASS_CBV, + RES_CLASS_SRV, + RES_CLASS_UAV, + }; + + struct UniformBindingInfo { + uint32_t stages = 0; // Actual shader stages using the uniform (0 if totally optimized out). + ResourceClass res_class = RES_CLASS_INVALID; + struct RootSignatureLocation { + uint32_t root_param_idx = UINT32_MAX; + uint32_t range_idx = UINT32_MAX; + }; + struct { + RootSignatureLocation resource; + RootSignatureLocation sampler; + } root_sig_locations; + }; + + struct UniformInfo { + UniformType type = UniformType::UNIFORM_TYPE_MAX; + bool writable = false; + int binding = 0; + int length = 0; // Size of arrays (in total elements), or ubos (in bytes * total elements). + + bool operator!=(const UniformInfo &p_info) const { + return (binding != p_info.binding || type != p_info.type || writable != p_info.writable || length != p_info.length); + } + + bool operator<(const UniformInfo &p_info) const { + if (binding != p_info.binding) { + return binding < p_info.binding; + } + if (type != p_info.type) { + return type < p_info.type; + } + if (writable != p_info.writable) { + return writable < p_info.writable; + } + return length < p_info.length; + } + }; + + struct UniformSetFormat { + Vector<UniformInfo> uniform_info; + bool operator<(const UniformSetFormat &p_format) const { + uint32_t size = uniform_info.size(); + uint32_t psize = p_format.uniform_info.size(); + + if (size != psize) { + return size < psize; + } + + const UniformInfo *infoptr = uniform_info.ptr(); + const UniformInfo *pinfoptr = p_format.uniform_info.ptr(); + + for (uint32_t i = 0; i < size; i++) { + if (infoptr[i] != pinfoptr[i]) { + return infoptr[i] < pinfoptr[i]; + } + } + + return false; + } + }; + + // Always grows, never shrinks, ensuring unique IDs, but we assume + // the amount of formats will never be a problem, as the amount of shaders + // in a game is limited. + RBMap<UniformSetFormat, uint32_t> uniform_set_format_cache; + Vector<RBMap<UniformSetFormat, uint32_t>::Element *> uniform_set_format_cache_reverse; + + struct Shader { + struct ShaderUniformInfo { + UniformInfo info; + UniformBindingInfo binding; + + bool operator<(const ShaderUniformInfo &p_info) const { + return *((UniformInfo *)this) < (const UniformInfo &)p_info; + } + }; + struct Set { + Vector<ShaderUniformInfo> uniforms; + struct { + uint32_t resources = 0; + uint32_t samplers = 0; + } num_root_params; + }; + + uint64_t vertex_input_mask = 0; // Inputs used, this is mostly for validation. + uint32_t fragment_output_mask = 0; + + uint32_t spirv_push_constant_size = 0; + uint32_t dxil_push_constant_size = 0; + uint32_t nir_runtime_data_root_param_idx = UINT32_MAX; + + uint32_t compute_local_size[3] = { 0, 0, 0 }; + + struct SpecializationConstant { + PipelineSpecializationConstant constant; + uint64_t stages_bit_offsets[D3D12_BITCODE_OFFSETS_NUM_STAGES]; + }; + + bool is_compute = false; + Vector<Set> sets; + Vector<uint32_t> set_formats; + Vector<SpecializationConstant> specialization_constants; + uint32_t spirv_specialization_constants_ids_mask = 0; + HashMap<ShaderStage, Vector<uint8_t>> stages_bytecode; + String name; // Used for debug. + + ComPtr<ID3D12RootSignature> root_signature; + ComPtr<ID3D12RootSignatureDeserializer> root_signature_deserializer; + const D3D12_ROOT_SIGNATURE_DESC *root_signature_desc = nullptr; // Owned by the deserializer. + uint32_t root_signature_crc = 0; + }; + + String _shader_uniform_debug(RID p_shader, int p_set = -1); + + RID_Owner<Shader, true> shader_owner; + + uint32_t _shader_patch_dxil_specialization_constant( + PipelineSpecializationConstantType p_type, + const void *p_value, + const uint64_t (&p_stages_bit_offsets)[D3D12_BITCODE_OFFSETS_NUM_STAGES], + HashMap<ShaderStage, Vector<uint8_t>> &r_stages_bytecodes, + bool p_is_first_patch); + bool _shader_sign_dxil_bytecode(ShaderStage p_stage, Vector<uint8_t> &r_dxil_blob); + + /******************/ + /**** UNIFORMS ****/ + /******************/ + + RID_Owner<Buffer, true> uniform_buffer_owner; + RID_Owner<Buffer, true> storage_buffer_owner; + + // Texture buffer needs a view. + struct TextureBuffer { + Buffer buffer; + }; + + RID_Owner<TextureBuffer, true> texture_buffer_owner; + + struct RootDescriptorTable { + uint32_t root_param_idx = UINT32_MAX; + D3D12_GPU_DESCRIPTOR_HANDLE start_gpu_handle = {}; + }; + + // This structure contains the descriptor set. They _need_ to be allocated + // for a shader (and will be erased when this shader is erased), but should + // work for other shaders as long as the hash matches. This covers using + // them in shader variants. + // + // Keep also in mind that you can share buffers between descriptor sets, so + // the above restriction is not too serious. + + struct UniformSet { + uint32_t format = 0; + RID shader_id; + uint32_t shader_set = 0; + struct { + DescriptorsHeap resources; + DescriptorsHeap samplers; + } desc_heaps; + struct StateRequirement { + Resource *resource; + bool is_buffer; + D3D12_RESOURCE_STATES states; + uint64_t shader_uniform_idx_mask; + }; + struct AttachableTexture { + uint32_t bind; + RID texture; + }; + + struct RecentBind { + uint64_t execution_index = 0; + uint32_t root_signature_crc = 0; + struct { + LocalVector<RootDescriptorTable> resources; + LocalVector<RootDescriptorTable> samplers; + } root_tables; + int uses = 0; + } recent_binds[4]; // A better amount may be empirically found. + + LocalVector<AttachableTexture> attachable_textures; // Used for validation. + Vector<StateRequirement> resource_states; + InvalidationCallback invalidated_callback = nullptr; + void *invalidated_callback_userdata = nullptr; + +#ifdef DEV_ENABLED + // Filthy, but useful for dev. + struct ResourceDescInfo { + D3D12_DESCRIPTOR_RANGE_TYPE type; + D3D12_SRV_DIMENSION srv_dimension; + }; + LocalVector<ResourceDescInfo> _resources_desc_info; + const Shader *_shader = nullptr; +#endif + }; + + RID_Owner<UniformSet, true> uniform_set_owner; + + void _bind_uniform_set(UniformSet *p_uniform_set, const Shader::Set &p_shader_set, const Vector<UniformBindingInfo> &p_bindings, ID3D12GraphicsCommandList *p_command_list, bool p_for_compute); + void _apply_uniform_set_resource_states(const UniformSet *p_uniform_set, const Shader::Set &p_shader_set); + + /*******************/ + /**** PIPELINES ****/ + /*******************/ + + Error _apply_specialization_constants( + const Shader *p_shader, + const Vector<PipelineSpecializationConstant> &p_specialization_constants, + HashMap<ShaderStage, Vector<uint8_t>> &r_final_stages_bytecode); +#ifdef DEV_ENABLED + String _build_pipeline_blob_filename( + const Vector<uint8_t> &p_blob, + const Shader *p_shader, + const Vector<PipelineSpecializationConstant> &p_specialization_constants, + const String &p_extra_name_suffix = "", + const String &p_forced_id = ""); + void _save_pso_blob( + ID3D12PipelineState *p_pso, + const Shader *p_shader, + const Vector<PipelineSpecializationConstant> &p_specialization_constants); + void _save_stages_bytecode( + const HashMap<ShaderStage, Vector<uint8_t>> &p_stages_bytecode, + const Shader *p_shader, + const RID p_shader_rid, + const Vector<PipelineSpecializationConstant> &p_specialization_constants); +#endif + + // Render pipeline contains ALL the + // information required for drawing. + // This includes all the rasterizer state + // as well as shader used, framebuffer format, + // etc. + // Some parameters aren't fixed in D3D12, + // so they are stored in an ancillary + // dynamic parameters structure to be set + // on pipeline activation via several calls. + + struct RenderPipeline { + // Cached values for validation. +#ifdef DEBUG_ENABLED + struct Validation { + FramebufferFormatID framebuffer_format = 0; + uint32_t render_pass = 0; + uint32_t dynamic_state = 0; + VertexFormatID vertex_format = 0; + bool uses_restart_indices = false; + uint32_t primitive_minimum = 0; + uint32_t primitive_divisor = 0; + } validation; +#endif + RID shader; + Vector<uint32_t> set_formats; + uint32_t bindings_id = 0; + ComPtr<ID3D12PipelineState> pso; + uint32_t root_signature_crc = 0; + uint32_t spirv_push_constant_size = 0; + uint32_t dxil_push_constant_size = 0; + uint32_t nir_runtime_data_root_param_idx = UINT32_MAX; + struct DynamicParams { + D3D12_PRIMITIVE_TOPOLOGY primitive_topology = {}; + Color blend_constant; + float depth_bounds_min = 0.0f; + float depth_bounds_max = 0.0f; + uint32_t stencil_reference = 0; + } dyn_params; + }; + + HashMap<uint32_t, Vector<Vector<UniformBindingInfo>>> pipeline_bindings; + uint32_t next_pipeline_binding_id = 1; + + RID_Owner<RenderPipeline, true> render_pipeline_owner; + + struct ComputePipeline { + RID shader; + Vector<uint32_t> set_formats; + uint32_t bindings_id = 0; + ComPtr<ID3D12PipelineState> pso; + uint32_t root_signature_crc = 0; + uint32_t spirv_push_constant_size = 0; + uint32_t dxil_push_constant_size = 0; + uint32_t local_group_size[3] = { 0, 0, 0 }; + }; + + RID_Owner<ComputePipeline, true> compute_pipeline_owner; + + /*******************/ + /**** DRAW LIST ****/ + /*******************/ + + // Draw list contains both the command buffer + // used for drawing as well as a LOT of + // information used for validation. This + // validation is cheap so most of it can + // also run in release builds. + + // When using split command lists, this is + // implemented internally using bundles. + // As they can be created in threads, + // each needs its own command allocator. + + struct SplitDrawListAllocator { + // All pointers are owned, but not using ComPtr to avoid overhead in the vector. + ID3D12CommandAllocator *command_allocator = nullptr; + Vector<ID3D12GraphicsCommandList *> command_lists; // One for each frame. + }; + + Vector<SplitDrawListAllocator> split_draw_list_allocators; + + struct DrawList { + ID3D12GraphicsCommandList *command_list = nullptr; // If persistent, this is owned, otherwise it's shared with the ringbuffer. + Rect2i viewport; + bool viewport_set = false; + + struct SetState { + uint32_t pipeline_expected_format = 0; + uint32_t uniform_set_format = 0; + RID uniform_set; + bool bound = false; +#ifdef DEV_ENABLED + // Filthy, but useful for dev. + const Vector<UniformInfo> *_pipeline_expected_format = nullptr; + const UniformSet *_uniform_set = nullptr; +#endif + }; + + struct State { + SetState sets[MAX_UNIFORM_SETS]; + uint32_t set_count = 0; + RID pipeline; + ID3D12PipelineState *pso = nullptr; + ID3D12PipelineState *bound_pso = nullptr; + RID pipeline_shader; + uint32_t pipeline_dxil_push_constant_size = 0; + uint32_t pipeline_bindings_id = 0; + uint32_t root_signature_crc = 0; + RID vertex_array; + RID index_array; +#ifdef DEV_ENABLED + // Filthy, but useful for dev. + Shader *_shader = nullptr; +#endif + } state; + +#ifdef DEBUG_ENABLED + struct Validation { + bool active = true; // Means command buffer was not closed, so you can keep adding things. + // Actual render pass values. + uint32_t dynamic_state = 0; + VertexFormatID vertex_format = INVALID_ID; + uint32_t vertex_array_size = 0; + uint32_t vertex_max_instances_allowed = 0xFFFFFFFF; + bool index_buffer_uses_restart_indices = false; + uint32_t index_array_size = 0; + uint32_t index_array_max_index = 0; + uint32_t index_array_offset = 0; + Vector<uint32_t> set_formats; + Vector<bool> set_bound; + Vector<RID> set_rids; + // Last pipeline set values. + bool pipeline_active = false; + uint32_t pipeline_dynamic_state = 0; + VertexFormatID pipeline_vertex_format = INVALID_ID; + RID pipeline_shader; + bool pipeline_uses_restart_indices = false; + uint32_t pipeline_primitive_divisor = 0; + uint32_t pipeline_primitive_minimum = 0; + uint32_t pipeline_spirv_push_constant_size = 0; + bool pipeline_push_constant_supplied = false; + } validation; +#else + struct Validation { + uint32_t vertex_array_size = 0; + uint32_t index_array_size = 0; + uint32_t index_array_offset; + } validation; +#endif + }; + + DrawList *draw_list = nullptr; // One for regular draw lists, multiple for split. + uint32_t draw_list_subpass_count = 0; + uint32_t draw_list_count = 0; + Framebuffer curr_screen_framebuffer; // Only valid while a screen draw list is open. + Framebuffer *draw_list_framebuffer = nullptr; + FinalAction draw_list_final_color_action = FINAL_ACTION_DISCARD; + FinalAction draw_list_final_depth_action = FINAL_ACTION_DISCARD; + Vector2 draw_list_viewport_size = {}; + uint32_t draw_list_current_subpass = 0; + + bool draw_list_split = false; + Vector<RID> draw_list_bound_textures; + bool draw_list_unbind_color_textures = false; + bool draw_list_unbind_depth_textures = false; + + struct { + RID texture_bound; + bool configured = false; + } vrs_state; + uint32_t vrs_state_execution_index = 0; + + Error _draw_list_render_pass_begin(Framebuffer *framebuffer, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector<Color> &p_clear_colors, float p_clear_depth, uint32_t p_clear_stencil, const Rect2 &p_region, Point2i viewport_offset, Point2i viewport_size, ID3D12GraphicsCommandList *command_list, const Vector<RID> &p_storage_textures); + _FORCE_INLINE_ DrawList *_get_draw_list_ptr(DrawListID p_id); + Buffer *_get_buffer_from_owner(RID p_buffer); + Error _draw_list_allocate(const Rect2i &p_viewport, uint32_t p_splits, uint32_t p_subpass); + void _draw_list_free(Rect2i *r_last_viewport = nullptr); + void _draw_list_subpass_begin(); + void _draw_list_subpass_end(); + + /**********************/ + /**** COMPUTE LIST ****/ + /**********************/ + + struct ComputeList { + ID3D12GraphicsCommandList *command_list = nullptr; // If persistent, this is owned, otherwise it's shared with the ringbuffer. + + struct SetState { + uint32_t pipeline_expected_format = 0; + uint32_t uniform_set_format = 0; + RID uniform_set; + bool bound = false; +#ifdef DEV_ENABLED + // Filthy, but useful for dev. + const Vector<UniformInfo> *_pipeline_expected_format = nullptr; + const UniformSet *_uniform_set = nullptr; +#endif + }; + + struct State { + HashSet<Texture *> textures_to_sampled_layout; + SetState sets[MAX_UNIFORM_SETS]; + uint32_t set_count = 0; + RID pipeline; + ID3D12PipelineState *pso = nullptr; + ID3D12PipelineState *bound_pso = nullptr; + RID pipeline_shader; + uint32_t pipeline_dxil_push_constant_size = 0; + uint32_t pipeline_bindings_id = 0; + uint32_t root_signature_crc = 0; + uint32_t local_group_size[3] = { 0, 0, 0 }; + bool allow_draw_overlap; +#ifdef DEV_ENABLED + // Filthy, but useful for dev. + Shader *_shader = nullptr; +#endif + } state; + +#ifdef DEBUG_ENABLED + struct Validation { + bool active = true; // Means command buffer was not closed, so you can keep adding things. + Vector<uint32_t> set_formats; + Vector<bool> set_bound; + Vector<RID> set_rids; + // Last pipeline set values. + bool pipeline_active = false; + RID pipeline_shader; + uint32_t pipeline_spirv_push_constant_size = 0; + bool pipeline_push_constant_supplied = false; + } validation; +#endif + }; + + ComputeList *compute_list = nullptr; + + /**************************/ + /**** FRAME MANAGEMENT ****/ + /**************************/ + + // This is the frame structure. There are normally + // 3 of these (used for triple buffering), or 2 + // (double buffering). They are cycled constantly. + // + // It contains two command buffers, one that is + // used internally for setting up (creating stuff) + // and another used mostly for drawing. + // + // They also contains a list of things that need + // to be disposed of when deleted, which can't + // happen immediately due to the asynchronous + // nature of the GPU. They will get deleted + // when the frame is cycled. + + struct Frame { + // List in usage order, from last to free to first to free. + List<Buffer> buffers_to_dispose_of; + List<Texture> textures_to_dispose_of; + List<Framebuffer> framebuffers_to_dispose_of; + List<Shader> shaders_to_dispose_of; + List<RenderPipeline> render_pipelines_to_dispose_of; + List<ComputePipeline> compute_pipelines_to_dispose_of; + struct { + DescriptorsHeap resources; + DescriptorsHeap samplers; + DescriptorsHeap aux; + DescriptorsHeap rtv; + } desc_heaps; + struct { + DescriptorsHeap::Walker resources; + DescriptorsHeap::Walker samplers; + DescriptorsHeap::Walker aux; + DescriptorsHeap::Walker rtv; + } desc_heap_walkers; + struct { + bool resources; + bool samplers; + bool aux; + bool rtv; + } desc_heaps_exhausted_reported; + CD3DX12_CPU_DESCRIPTOR_HANDLE null_rtv_handle = {}; // For [[MANUAL_SUBPASSES]]. + + ComPtr<ID3D12CommandAllocator> setup_command_allocator; + ComPtr<ID3D12CommandAllocator> draw_command_allocator; + ComPtr<ID3D12GraphicsCommandList> setup_command_list; // Used at the beginning of every frame for set-up. + ComPtr<ID3D12GraphicsCommandList> draw_command_list; + + struct Timestamp { + String description; + uint64_t value = 0; + }; + + ComPtr<ID3D12QueryHeap> timestamp_heap; + + TightLocalVector<String> timestamp_names; + TightLocalVector<uint64_t> timestamp_cpu_values; + uint32_t timestamp_count = 0; + TightLocalVector<String> timestamp_result_names; + TightLocalVector<uint64_t> timestamp_cpu_result_values; + Buffer timestamp_result_values_buffer; + TightLocalVector<uint64_t> timestamp_result_values; + uint32_t timestamp_result_count = 0; + uint64_t index = 0; + uint64_t execution_index = 0; +#ifdef DEV_ENABLED + uint32_t uniform_set_reused = 0; +#endif + }; + + uint32_t max_timestamp_query_elements = 0; + + TightLocalVector<Frame> frames; // Frames available, for main device they are cycled (usually 3), for local devices only 1. + int frame = 0; // Current frame. + int frame_count = 0; // Total amount of frames. + uint64_t frames_drawn = 0; + uint32_t execution_index = 0; // Gets incremented on every call to ExecuteCommandLists (each frame and each flush). + RID local_device; + bool local_device_processing = false; + + void _free_pending_resources(int p_frame); + +//#define USE_SMALL_ALLOCS_POOL // Disabled by now; seems not to be beneficial as it is in Vulkan. +#ifdef USE_SMALL_ALLOCS_POOL + union AllocPoolKey { + struct { + D3D12_HEAP_TYPE heap_type; + D3D12_HEAP_FLAGS heap_flags; + }; + uint64_t key; + }; + HashMap<uint64_t, ComPtr<D3D12MA::Pool>> small_allocs_pools; + D3D12MA::Pool *_find_or_create_small_allocs_pool(D3D12_HEAP_TYPE p_heap_type, D3D12_HEAP_FLAGS p_heap_flags); +#endif + + ComPtr<ID3D12CommandSignature> indirect_dispatch_cmd_sig; + RID aux_resource; // Used for causing full barriers. + + D3D12Context *context = nullptr; + + uint64_t image_memory = 0; + uint64_t buffer_memory = 0; + + void _free_internal(RID p_id); + void _flush(bool p_flush_current_frame); + + bool screen_prepared = false; + + template <class T> + void _free_rids(T &p_owner, const char *p_type); + + void _finalize_command_bufers(); + void _begin_frame(); + +#ifdef DEV_ENABLED + HashMap<RID, String> resource_names; +#endif + + HashMap<DXGI_FORMAT, uint32_t> format_sample_counts_mask_cache; + uint32_t _find_max_common_supported_sample_count(const DXGI_FORMAT *p_formats, uint32_t p_num_formats); + +public: + virtual RID texture_create(const TextureFormat &p_format, const TextureView &p_view, const Vector<Vector<uint8_t>> &p_data = Vector<Vector<uint8_t>>()); + virtual RID texture_create_shared(const TextureView &p_view, RID p_with_texture); + virtual RID texture_create_from_extension(TextureType p_type, DataFormat p_format, TextureSamples p_samples, BitField<RenderingDevice::TextureUsageBits> p_flags, uint64_t p_image, uint64_t p_width, uint64_t p_height, uint64_t p_depth, uint64_t p_layers); + + virtual RID texture_create_shared_from_slice(const TextureView &p_view, RID p_with_texture, uint32_t p_layer, uint32_t p_mipmap, uint32_t p_mipmaps = 1, TextureSliceType p_slice_type = TEXTURE_SLICE_2D, uint32_t p_layers = 0); + virtual Error texture_update(RID p_texture, uint32_t p_layer, const Vector<uint8_t> &p_data, BitField<BarrierMask> p_post_barrier = BARRIER_MASK_ALL_BARRIERS); + virtual Vector<uint8_t> texture_get_data(RID p_texture, uint32_t p_layer); + + virtual bool texture_is_format_supported_for_usage(DataFormat p_format, BitField<RenderingDevice::TextureUsageBits> p_usage) const; + virtual bool texture_is_shared(RID p_texture); + virtual bool texture_is_valid(RID p_texture); + virtual TextureFormat texture_get_format(RID p_texture); + virtual Size2i texture_size(RID p_texture); + virtual uint64_t texture_get_native_handle(RID p_texture); + + virtual Error texture_copy(RID p_from_texture, RID p_to_texture, const Vector3 &p_from, const Vector3 &p_to, const Vector3 &p_size, uint32_t p_src_mipmap, uint32_t p_dst_mipmap, uint32_t p_src_layer, uint32_t p_dst_layer, BitField<BarrierMask> p_post_barrier = BARRIER_MASK_ALL_BARRIERS); + virtual Error texture_clear(RID p_texture, const Color &p_color, uint32_t p_base_mipmap, uint32_t p_mipmaps, uint32_t p_base_layer, uint32_t p_layers, BitField<BarrierMask> p_post_barrier = BARRIER_MASK_ALL_BARRIERS); + virtual Error texture_resolve_multisample(RID p_from_texture, RID p_to_texture, BitField<BarrierMask> p_post_barrier = BARRIER_MASK_ALL_BARRIERS); + + /*********************/ + /**** FRAMEBUFFER ****/ + /*********************/ + + virtual FramebufferFormatID framebuffer_format_create(const Vector<AttachmentFormat> &p_format, uint32_t p_view_count = 1); + virtual FramebufferFormatID framebuffer_format_create_multipass(const Vector<AttachmentFormat> &p_attachments, const Vector<FramebufferPass> &p_passes, uint32_t p_view_count = 1); + virtual FramebufferFormatID framebuffer_format_create_empty(TextureSamples p_samples = TEXTURE_SAMPLES_1); + virtual TextureSamples framebuffer_format_get_texture_samples(FramebufferFormatID p_format, uint32_t p_pass = 0); + + virtual RID framebuffer_create(const Vector<RID> &p_texture_attachments, FramebufferFormatID p_format_check = INVALID_ID, uint32_t p_view_count = 1); + virtual RID framebuffer_create_multipass(const Vector<RID> &p_texture_attachments, const Vector<FramebufferPass> &p_passes, FramebufferFormatID p_format_check = INVALID_ID, uint32_t p_view_count = 1); + virtual RID framebuffer_create_empty(const Size2i &p_size, TextureSamples p_samples = TEXTURE_SAMPLES_1, FramebufferFormatID p_format_check = INVALID_ID); + virtual bool framebuffer_is_valid(RID p_framebuffer) const; + virtual void framebuffer_set_invalidation_callback(RID p_framebuffer, InvalidationCallback p_callback, void *p_userdata); + + virtual FramebufferFormatID framebuffer_get_format(RID p_framebuffer); + + /*****************/ + /**** SAMPLER ****/ + /*****************/ + + virtual RID sampler_create(const SamplerState &p_state); + virtual bool sampler_is_format_supported_for_filter(DataFormat p_format, SamplerFilter p_sampler_filter) const; + + /**********************/ + /**** VERTEX ARRAY ****/ + /**********************/ + + virtual RID vertex_buffer_create(uint32_t p_size_bytes, const Vector<uint8_t> &p_data = Vector<uint8_t>(), bool p_use_as_storage = false); + + // Internally reference counted, this ID is warranted to be unique for the same description, but needs to be freed as many times as it was allocated. + virtual VertexFormatID vertex_format_create(const Vector<VertexAttribute> &p_vertex_formats); + virtual RID vertex_array_create(uint32_t p_vertex_count, VertexFormatID p_vertex_format, const Vector<RID> &p_src_buffers, const Vector<uint64_t> &p_offsets = Vector<uint64_t>()); + + virtual RID index_buffer_create(uint32_t p_size_indices, IndexBufferFormat p_format, const Vector<uint8_t> &p_data = Vector<uint8_t>(), bool p_use_restart_indices = false); + + virtual RID index_array_create(RID p_index_buffer, uint32_t p_index_offset, uint32_t p_index_count); + + /****************/ + /**** SHADER ****/ + /****************/ + + virtual String shader_get_binary_cache_key() const; + virtual Vector<uint8_t> shader_compile_binary_from_spirv(const Vector<ShaderStageSPIRVData> &p_spirv, const String &p_shader_name = ""); + + virtual RID shader_create_from_bytecode(const Vector<uint8_t> &p_shader_binary, RID p_placeholder = RID()); + virtual RID shader_create_placeholder(); + + virtual uint64_t shader_get_vertex_input_attribute_mask(RID p_shader); + + /*****************/ + /**** UNIFORM ****/ + /*****************/ + + virtual RID uniform_buffer_create(uint32_t p_size_bytes, const Vector<uint8_t> &p_data = Vector<uint8_t>()); + virtual RID storage_buffer_create(uint32_t p_size_bytes, const Vector<uint8_t> &p_data = Vector<uint8_t>(), BitField<StorageBufferUsage> p_usage = 0); + virtual RID texture_buffer_create(uint32_t p_size_elements, DataFormat p_format, const Vector<uint8_t> &p_data = Vector<uint8_t>()); + + virtual RID uniform_set_create(const Vector<Uniform> &p_uniforms, RID p_shader, uint32_t p_shader_set); + virtual bool uniform_set_is_valid(RID p_uniform_set); + virtual void uniform_set_set_invalidation_callback(RID p_uniform_set, InvalidationCallback p_callback, void *p_userdata); + + virtual Error buffer_copy(RID p_src_buffer, RID p_dst_buffer, uint32_t p_src_offset, uint32_t p_dst_offset, uint32_t p_size, BitField<BarrierMask> p_post_barrier = BARRIER_MASK_ALL_BARRIERS); + virtual Error buffer_update(RID p_buffer, uint32_t p_offset, uint32_t p_size, const void *p_data, BitField<BarrierMask> p_post_barrier = BARRIER_MASK_ALL_BARRIERS); // Works for any buffer. + virtual Error buffer_clear(RID p_buffer, uint32_t p_offset, uint32_t p_size, BitField<BarrierMask> p_post_barrier = BARRIER_MASK_ALL_BARRIERS); + virtual Vector<uint8_t> buffer_get_data(RID p_buffer, uint32_t p_offset = 0, uint32_t p_size = 0); + + /*************************/ + /**** RENDER PIPELINE ****/ + /*************************/ + + virtual RID render_pipeline_create(RID p_shader, FramebufferFormatID p_framebuffer_format, VertexFormatID p_vertex_format, RenderPrimitive p_render_primitive, const PipelineRasterizationState &p_rasterization_state, const PipelineMultisampleState &p_multisample_state, const PipelineDepthStencilState &p_depth_stencil_state, const PipelineColorBlendState &p_blend_state, BitField<PipelineDynamicStateFlags> p_dynamic_state_flags = 0, uint32_t p_for_render_pass = 0, const Vector<PipelineSpecializationConstant> &p_specialization_constants = Vector<PipelineSpecializationConstant>()); + virtual bool render_pipeline_is_valid(RID p_pipeline); + + /**************************/ + /**** COMPUTE PIPELINE ****/ + /**************************/ + + virtual RID compute_pipeline_create(RID p_shader, const Vector<PipelineSpecializationConstant> &p_specialization_constants = Vector<PipelineSpecializationConstant>()); + virtual bool compute_pipeline_is_valid(RID p_pipeline); + + /****************/ + /**** SCREEN ****/ + /****************/ + + virtual int screen_get_width(DisplayServer::WindowID p_screen = 0) const; + virtual int screen_get_height(DisplayServer::WindowID p_screen = 0) const; + virtual FramebufferFormatID screen_get_framebuffer_format() const; + + /********************/ + /**** DRAW LISTS ****/ + /********************/ + + virtual DrawListID draw_list_begin_for_screen(DisplayServer::WindowID p_screen = 0, const Color &p_clear_color = Color()); + virtual DrawListID draw_list_begin(RID p_framebuffer, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector<Color> &p_clear_color_values = Vector<Color>(), float p_clear_depth = 1.0, uint32_t p_clear_stencil = 0, const Rect2 &p_region = Rect2(), const Vector<RID> &p_storage_textures = Vector<RID>()); + virtual Error draw_list_begin_split(RID p_framebuffer, uint32_t p_splits, DrawListID *r_split_ids, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector<Color> &p_clear_color_values = Vector<Color>(), float p_clear_depth = 1.0, uint32_t p_clear_stencil = 0, const Rect2 &p_region = Rect2(), const Vector<RID> &p_storage_textures = Vector<RID>()); + + virtual void draw_list_set_blend_constants(DrawListID p_list, const Color &p_color); + virtual void draw_list_bind_render_pipeline(DrawListID p_list, RID p_render_pipeline); + virtual void draw_list_bind_uniform_set(DrawListID p_list, RID p_uniform_set, uint32_t p_index); + virtual void draw_list_bind_vertex_array(DrawListID p_list, RID p_vertex_array); + virtual void draw_list_bind_index_array(DrawListID p_list, RID p_index_array); + virtual void draw_list_set_line_width(DrawListID p_list, float p_width); + virtual void draw_list_set_push_constant(DrawListID p_list, const void *p_data, uint32_t p_data_size); + + virtual void draw_list_draw(DrawListID p_list, bool p_use_indices, uint32_t p_instances = 1, uint32_t p_procedural_vertices = 0); + + virtual void draw_list_enable_scissor(DrawListID p_list, const Rect2 &p_rect); + virtual void draw_list_disable_scissor(DrawListID p_list); + + virtual uint32_t draw_list_get_current_pass(); + virtual DrawListID draw_list_switch_to_next_pass(); + virtual Error draw_list_switch_to_next_pass_split(uint32_t p_splits, DrawListID *r_split_ids); + + virtual void draw_list_end(BitField<BarrierMask> p_post_barrier = BARRIER_MASK_ALL_BARRIERS); + + /***********************/ + /**** COMPUTE LISTS ****/ + /***********************/ + + virtual ComputeListID compute_list_begin(bool p_allow_draw_overlap = false); + virtual void compute_list_bind_compute_pipeline(ComputeListID p_list, RID p_compute_pipeline); + virtual void compute_list_bind_uniform_set(ComputeListID p_list, RID p_uniform_set, uint32_t p_index); + virtual void compute_list_set_push_constant(ComputeListID p_list, const void *p_data, uint32_t p_data_size); + virtual void compute_list_add_barrier(ComputeListID p_list); + + virtual void compute_list_dispatch(ComputeListID p_list, uint32_t p_x_groups, uint32_t p_y_groups, uint32_t p_z_groups); + virtual void compute_list_dispatch_threads(ComputeListID p_list, uint32_t p_x_threads, uint32_t p_y_threads, uint32_t p_z_threads); + virtual void compute_list_dispatch_indirect(ComputeListID p_list, RID p_buffer, uint32_t p_offset); + virtual void compute_list_end(BitField<BarrierMask> p_post_barrier = BARRIER_MASK_ALL_BARRIERS); + + virtual void barrier(BitField<BarrierMask> p_from = BARRIER_MASK_ALL_BARRIERS, BitField<BarrierMask> p_to = BARRIER_MASK_ALL_BARRIERS); + virtual void full_barrier(); + + /**************/ + /**** FREE ****/ + /**************/ + + virtual void free(RID p_id); + + /****************/ + /**** Timing ****/ + /****************/ + + virtual void capture_timestamp(const String &p_name); + virtual uint32_t get_captured_timestamps_count() const; + virtual uint64_t get_captured_timestamps_frame() const; + virtual uint64_t get_captured_timestamp_gpu_time(uint32_t p_index) const; + virtual uint64_t get_captured_timestamp_cpu_time(uint32_t p_index) const; + virtual String get_captured_timestamp_name(uint32_t p_index) const; + + /****************/ + /**** Limits ****/ + /****************/ + + virtual uint64_t limit_get(Limit p_limit) const; + + virtual void prepare_screen_for_drawing(); + + void initialize(D3D12Context *p_context, bool p_local_device = false); + void finalize(); + + virtual void swap_buffers(); // For main device. + + virtual void submit(); // For local device. + virtual void sync(); // For local device. + + virtual uint32_t get_frame_delay() const; + + virtual RenderingDevice *create_local_device(); + + virtual uint64_t get_memory_usage(MemoryType p_type) const; + + virtual void set_resource_name(RID p_id, const String p_name); + + virtual void draw_command_begin_label(String p_label_name, const Color p_color = Color(1, 1, 1, 1)); + virtual void draw_command_insert_label(String p_label_name, const Color p_color = Color(1, 1, 1, 1)); + virtual void draw_command_end_label(); + + virtual String get_device_vendor_name() const; + virtual String get_device_name() const; + virtual RenderingDevice::DeviceType get_device_type() const; + virtual String get_device_api_version() const; + virtual String get_device_pipeline_cache_uuid() const; + + virtual uint64_t get_driver_resource(DriverResource p_resource, RID p_rid = RID(), uint64_t p_index = 0); + + virtual bool has_feature(const Features p_feature) const; + + RenderingDeviceD3D12(); + ~RenderingDeviceD3D12(); +}; + +#endif // RENDERING_DEVICE_D3D12_H |
