Path: blob/master/drivers/d3d12/rendering_context_driver_d3d12.cpp
22517 views
/**************************************************************************/1/* rendering_context_driver_d3d12.cpp */2/**************************************************************************/3/* This file is part of: */4/* GODOT ENGINE */5/* https://godotengine.org */6/**************************************************************************/7/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */8/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */9/* */10/* Permission is hereby granted, free of charge, to any person obtaining */11/* a copy of this software and associated documentation files (the */12/* "Software"), to deal in the Software without restriction, including */13/* without limitation the rights to use, copy, modify, merge, publish, */14/* distribute, sublicense, and/or sell copies of the Software, and to */15/* permit persons to whom the Software is furnished to do so, subject to */16/* the following conditions: */17/* */18/* The above copyright notice and this permission notice shall be */19/* included in all copies or substantial portions of the Software. */20/* */21/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */22/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */23/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */24/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */25/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */26/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */27/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */28/**************************************************************************/2930#include "rendering_context_driver_d3d12.h"3132#include "d3d12_hooks.h"3334#include "core/config/engine.h"35#include "core/config/project_settings.h"36#include "core/string/ustring.h"37#include "core/templates/local_vector.h"38#include "core/version.h"3940GODOT_GCC_WARNING_PUSH41GODOT_GCC_WARNING_IGNORE("-Wmissing-field-initializers")42GODOT_GCC_WARNING_IGNORE("-Wnon-virtual-dtor")43GODOT_GCC_WARNING_IGNORE("-Wshadow")44GODOT_GCC_WARNING_IGNORE("-Wswitch")45GODOT_CLANG_WARNING_PUSH46GODOT_CLANG_WARNING_IGNORE("-Wmissing-field-initializers")47GODOT_CLANG_WARNING_IGNORE("-Wnon-virtual-dtor")48GODOT_CLANG_WARNING_IGNORE("-Wstring-plus-int")49GODOT_CLANG_WARNING_IGNORE("-Wswitch")5051#include <dxcapi.h>52#include <dxgi1_6.h>5354GODOT_GCC_WARNING_POP55GODOT_CLANG_WARNING_POP5657#if !defined(_MSC_VER)58#include <guiddef.h>5960#include <thirdparty/directx_headers/include/dxguids/dxguids.h>61#endif6263using Microsoft::WRL::ComPtr;6465// Note: symbols are not available in MinGW and old MSVC import libraries.66// GUID values from https://github.com/microsoft/DirectX-Headers/blob/7a9f4d06911d30eecb56a4956dab29dcca2709ed/include/directx/d3d12.idl#L5877-L588167const GUID CLSID_D3D12DebugGodot = { 0xf2352aeb, 0xdd84, 0x49fe, { 0xb9, 0x7b, 0xa9, 0xdc, 0xfd, 0xcc, 0x1b, 0x4f } };68const GUID CLSID_D3D12SDKConfigurationGodot = { 0x7cda6aca, 0xa03e, 0x49c8, { 0x94, 0x58, 0x03, 0x34, 0xd2, 0x0e, 0x07, 0xce } };6970#ifdef PIX_ENABLED71#if defined(__GNUC__)72#define _MSC_VER 180073#endif74#define USE_PIX75#include <WinPixEventRuntime/pix3.h>76#if defined(__GNUC__)77#undef _MSC_VER78#endif79#endif8081RenderingContextDriverD3D12::RenderingContextDriverD3D12() {}8283RenderingContextDriverD3D12::~RenderingContextDriverD3D12() {84// Let's release manually everything that may still be holding85// onto the DLLs before freeing them.86device_factory.Reset();87dxgi_factory.Reset();8889if (lib_d3d12) {90FreeLibrary(lib_d3d12);91}92if (lib_dxgi) {93FreeLibrary(lib_dxgi);94}95#ifdef DCOMP_ENABLED96if (lib_dcomp) {97FreeLibrary(lib_dcomp);98}99#endif100}101102Error RenderingContextDriverD3D12::_init_device_factory() {103uint32_t agility_sdk_version = GLOBAL_GET("rendering/rendering_device/d3d12/agility_sdk_version");104String agility_sdk_path = String(".\\") + Engine::get_singleton()->get_architecture_name();105106lib_d3d12 = LoadLibraryW(L"D3D12.dll");107ERR_FAIL_NULL_V(lib_d3d12, ERR_CANT_CREATE);108109lib_dxgi = LoadLibraryW(L"DXGI.dll");110ERR_FAIL_NULL_V(lib_dxgi, ERR_CANT_CREATE);111112#ifdef DCOMP_ENABLED113lib_dcomp = LoadLibraryW(L"Dcomp.dll");114ERR_FAIL_NULL_V(lib_dcomp, ERR_CANT_CREATE);115#endif116117// Note: symbol is not available in MinGW import library.118PFN_D3D12_GET_INTERFACE d3d_D3D12GetInterface = (PFN_D3D12_GET_INTERFACE)(void *)GetProcAddress(lib_d3d12, "D3D12GetInterface");119if (!d3d_D3D12GetInterface) {120return OK; // Fallback to the system loader.121}122123ComPtr<ID3D12SDKConfiguration1> sdk_config;124HRESULT hr = d3d_D3D12GetInterface(CLSID_D3D12SDKConfigurationGodot, IID_PPV_ARGS(sdk_config.GetAddressOf()));125if (SUCCEEDED(hr)) {126hr = sdk_config->CreateDeviceFactory(agility_sdk_version, agility_sdk_path.ascii().get_data(), IID_PPV_ARGS(device_factory.GetAddressOf()));127if (FAILED(hr)) {128sdk_config->CreateDeviceFactory(agility_sdk_version, ".\\", IID_PPV_ARGS(device_factory.GetAddressOf()));129}130// If both calls failed, device factory is going to be nullptr, and D3D12CreateDevice is going to be used as fallback.131}132return OK;133}134135Error RenderingContextDriverD3D12::_initialize_debug_layers() {136ComPtr<ID3D12Debug> debug_controller;137HRESULT res;138139if (device_factory) {140res = device_factory->GetConfigurationInterface(CLSID_D3D12DebugGodot, IID_PPV_ARGS(&debug_controller));141} else {142PFN_D3D12_GET_DEBUG_INTERFACE d3d_D3D12GetDebugInterface = (PFN_D3D12_GET_DEBUG_INTERFACE)(void *)GetProcAddress(lib_d3d12, "D3D12GetDebugInterface");143ERR_FAIL_NULL_V(d3d_D3D12GetDebugInterface, ERR_CANT_CREATE);144145res = d3d_D3D12GetDebugInterface(IID_PPV_ARGS(&debug_controller));146}147148ERR_FAIL_COND_V(!SUCCEEDED(res), ERR_QUERY_FAILED);149debug_controller->EnableDebugLayer();150return OK;151}152153Error RenderingContextDriverD3D12::_create_dxgi_factory() {154const UINT dxgi_factory_flags = use_validation_layers() ? DXGI_CREATE_FACTORY_DEBUG : 0;155156typedef HRESULT(WINAPI * PFN_DXGI_CREATE_DXGI_FACTORY2)(UINT, REFIID, void **);157PFN_DXGI_CREATE_DXGI_FACTORY2 dxgi_CreateDXGIFactory2 = (PFN_DXGI_CREATE_DXGI_FACTORY2)(void *)GetProcAddress(lib_dxgi, "CreateDXGIFactory2");158ERR_FAIL_NULL_V(dxgi_CreateDXGIFactory2, ERR_CANT_CREATE);159160HRESULT res = dxgi_CreateDXGIFactory2(dxgi_factory_flags, IID_PPV_ARGS(&dxgi_factory));161ERR_FAIL_COND_V(!SUCCEEDED(res), ERR_CANT_CREATE);162163return OK;164}165166Error RenderingContextDriverD3D12::_initialize_devices() {167// Create the initial DXGI factory.168Error err = _create_dxgi_factory();169ERR_FAIL_COND_V(err != OK, err);170171HRESULT res;172173// Enumerate all possible adapters.174LocalVector<IDXGIAdapter1 *> adapters;175IDXGIAdapter1 *adapter = nullptr;176do {177adapter = create_adapter(adapters.size());178if (adapter != nullptr) {179adapters.push_back(adapter);180}181} while (adapter != nullptr);182183ERR_FAIL_COND_V_MSG(adapters.is_empty(), ERR_CANT_CREATE, "Adapters enumeration reported zero accessible devices.");184185// Fill the device descriptions with the adapters.186driver_devices.resize(adapters.size());187for (uint32_t i = 0; i < adapters.size(); ++i) {188DXGI_ADAPTER_DESC1 desc = {};189adapters[i]->GetDesc1(&desc);190191Device &device = driver_devices[i];192device.name = desc.Description;193device.vendor = desc.VendorId;194device.workarounds = Workarounds();195196if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) {197device.type = DEVICE_TYPE_CPU;198} else {199const bool has_dedicated_vram = desc.DedicatedVideoMemory > 0;200device.type = has_dedicated_vram ? DEVICE_TYPE_DISCRETE_GPU : DEVICE_TYPE_INTEGRATED_GPU;201}202}203204// Release all created adapters.205for (uint32_t i = 0; i < adapters.size(); ++i) {206adapters[i]->Release();207}208209ComPtr<IDXGIFactory5> factory_5;210dxgi_factory.As(&factory_5);211if (factory_5 != nullptr) {212// The type is important as in general, sizeof(bool) != sizeof(BOOL).213BOOL feature_supported = FALSE;214res = factory_5->CheckFeatureSupport(DXGI_FEATURE_PRESENT_ALLOW_TEARING, &feature_supported, sizeof(feature_supported));215if (SUCCEEDED(res)) {216tearing_supported = feature_supported;217} else {218ERR_PRINT("CheckFeatureSupport failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");219}220}221222return OK;223}224225bool RenderingContextDriverD3D12::use_validation_layers() const {226return Engine::get_singleton()->is_validation_layers_enabled();227}228229Error RenderingContextDriverD3D12::initialize() {230Error err = _init_device_factory();231ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);232233if (use_validation_layers()) {234err = _initialize_debug_layers();235ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);236}237238err = _initialize_devices();239ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);240241return OK;242}243244const RenderingContextDriver::Device &RenderingContextDriverD3D12::device_get(uint32_t p_device_index) const {245DEV_ASSERT(p_device_index < driver_devices.size());246return driver_devices[p_device_index];247}248249uint32_t RenderingContextDriverD3D12::device_get_count() const {250return driver_devices.size();251}252253bool RenderingContextDriverD3D12::device_supports_present(uint32_t p_device_index, SurfaceID p_surface) const {254// All devices should support presenting to any surface.255return true;256}257258RenderingDeviceDriver *RenderingContextDriverD3D12::driver_create() {259return memnew(RenderingDeviceDriverD3D12(this));260}261262void RenderingContextDriverD3D12::driver_free(RenderingDeviceDriver *p_driver) {263memdelete(p_driver);264}265266RenderingContextDriver::SurfaceID RenderingContextDriverD3D12::surface_create(const void *p_platform_data) {267const WindowPlatformData *wpd = (const WindowPlatformData *)(p_platform_data);268Surface *surface = memnew(Surface);269surface->hwnd = wpd->window;270return SurfaceID(surface);271}272273void RenderingContextDriverD3D12::surface_set_size(SurfaceID p_surface, uint32_t p_width, uint32_t p_height) {274Surface *surface = (Surface *)(p_surface);275surface->width = p_width;276surface->height = p_height;277surface->needs_resize = true;278}279280void RenderingContextDriverD3D12::surface_set_vsync_mode(SurfaceID p_surface, DisplayServer::VSyncMode p_vsync_mode) {281Surface *surface = (Surface *)(p_surface);282surface->vsync_mode = p_vsync_mode;283surface->needs_resize = true;284}285286DisplayServer::VSyncMode RenderingContextDriverD3D12::surface_get_vsync_mode(SurfaceID p_surface) const {287Surface *surface = (Surface *)(p_surface);288return surface->vsync_mode;289}290291void RenderingContextDriverD3D12::surface_set_hdr_output_enabled(SurfaceID p_surface, bool p_enabled) {292Surface *surface = (Surface *)(p_surface);293surface->hdr_output = p_enabled;294surface->needs_resize = true;295}296297bool RenderingContextDriverD3D12::surface_get_hdr_output_enabled(SurfaceID p_surface) const {298Surface *surface = (Surface *)(p_surface);299return surface->hdr_output;300}301302void RenderingContextDriverD3D12::surface_set_hdr_output_reference_luminance(SurfaceID p_surface, float p_reference_luminance) {303Surface *surface = (Surface *)(p_surface);304surface->hdr_reference_luminance = p_reference_luminance;305}306307float RenderingContextDriverD3D12::surface_get_hdr_output_reference_luminance(SurfaceID p_surface) const {308Surface *surface = (Surface *)(p_surface);309return surface->hdr_reference_luminance;310}311312void RenderingContextDriverD3D12::surface_set_hdr_output_max_luminance(SurfaceID p_surface, float p_max_luminance) {313Surface *surface = (Surface *)(p_surface);314surface->hdr_max_luminance = p_max_luminance;315}316317float RenderingContextDriverD3D12::surface_get_hdr_output_max_luminance(SurfaceID p_surface) const {318Surface *surface = (Surface *)(p_surface);319return surface->hdr_max_luminance;320}321322void RenderingContextDriverD3D12::surface_set_hdr_output_linear_luminance_scale(SurfaceID p_surface, float p_linear_luminance_scale) {323Surface *surface = (Surface *)(p_surface);324surface->hdr_linear_luminance_scale = p_linear_luminance_scale;325}326327float RenderingContextDriverD3D12::surface_get_hdr_output_linear_luminance_scale(SurfaceID p_surface) const {328Surface *surface = (Surface *)(p_surface);329return surface->hdr_linear_luminance_scale;330}331332float RenderingContextDriverD3D12::surface_get_hdr_output_max_value(SurfaceID p_surface) const {333Surface *surface = (Surface *)(p_surface);334return MAX(surface->hdr_max_luminance / MAX(surface->hdr_reference_luminance, 1.0f), 1.0f);335}336337uint32_t RenderingContextDriverD3D12::surface_get_width(SurfaceID p_surface) const {338Surface *surface = (Surface *)(p_surface);339return surface->width;340}341342uint32_t RenderingContextDriverD3D12::surface_get_height(SurfaceID p_surface) const {343Surface *surface = (Surface *)(p_surface);344return surface->height;345}346347void RenderingContextDriverD3D12::surface_set_needs_resize(SurfaceID p_surface, bool p_needs_resize) {348Surface *surface = (Surface *)(p_surface);349surface->needs_resize = p_needs_resize;350}351352bool RenderingContextDriverD3D12::surface_get_needs_resize(SurfaceID p_surface) const {353Surface *surface = (Surface *)(p_surface);354return surface->needs_resize;355}356357void RenderingContextDriverD3D12::surface_destroy(SurfaceID p_surface) {358Surface *surface = (Surface *)(p_surface);359memdelete(surface);360}361362bool RenderingContextDriverD3D12::is_debug_utils_enabled() const {363#ifdef PIX_ENABLED364return true;365#else366return false;367#endif368}369370IDXGIAdapter1 *RenderingContextDriverD3D12::create_adapter(uint32_t p_adapter_index) const {371ComPtr<IDXGIFactory6> factory_6;372dxgi_factory.As(&factory_6);373374// TODO: Use IDXCoreAdapterList, which gives more comprehensive information.375IDXGIAdapter1 *adapter = nullptr;376if (factory_6) {377if (factory_6->EnumAdapterByGpuPreference(p_adapter_index, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&adapter)) == DXGI_ERROR_NOT_FOUND) {378return nullptr;379}380} else {381if (dxgi_factory->EnumAdapters1(p_adapter_index, &adapter) == DXGI_ERROR_NOT_FOUND) {382return nullptr;383}384}385386return adapter;387}388389ID3D12DeviceFactory *RenderingContextDriverD3D12::device_factory_get() const {390return device_factory.Get();391}392393IDXGIFactory2 *RenderingContextDriverD3D12::dxgi_factory_get() {394// Check if the factory is still current. It can become invalid if displays change395if (dxgi_factory && !dxgi_factory->IsCurrent()) {396dxgi_factory.Reset();397_create_dxgi_factory();398}399return dxgi_factory.Get();400}401402bool RenderingContextDriverD3D12::get_tearing_supported() const {403return tearing_supported;404}405406407