| 1 | // Copyright 2019 Dolphin Emulator Project |
| 2 | // SPDX-License-Identifier: GPL-2.0-or-later |
| 3 | |
| 4 | #include "VideoBackends/D3D12/DX12Context.h" |
| 5 | |
| 6 | #include <algorithm> |
| 7 | #include <array> |
| 8 | #include <dxgi1_6.h> |
| 9 | #include <queue> |
| 10 | #include <vector> |
| 11 | |
| 12 | #include "Common/Assert.h" |
| 13 | #include "Common/DynamicLibrary.h" |
| 14 | #include "Common/StringUtil.h" |
| 15 | |
| 16 | #include "VideoBackends/D3D12/Common.h" |
| 17 | #include "VideoBackends/D3D12/D3D12StreamBuffer.h" |
| 18 | #include "VideoBackends/D3D12/DescriptorHeapManager.h" |
| 19 | #include "VideoCommon/FramebufferManager.h" |
| 20 | #include "VideoCommon/VideoConfig.h" |
| 21 | |
| 22 | namespace DX12 |
| 23 | { |
| 24 | std::unique_ptr<DXContext> g_dx_context; |
| 25 | |
| 26 | // Private D3D12 state |
| 27 | static Common::DynamicLibrary s_d3d12_library; |
| 28 | static PFN_D3D12_CREATE_DEVICE s_d3d12_create_device; |
| 29 | static PFN_D3D12_GET_DEBUG_INTERFACE s_d3d12_get_debug_interface; |
| 30 | static PFN_D3D12_SERIALIZE_ROOT_SIGNATURE s_d3d12_serialize_root_signature; |
| 31 | |
| 32 | DXContext::DXContext() = default; |
| 33 | |
| 34 | DXContext::~DXContext() |
| 35 | { |
| 36 | if (m_fence_event) |
| 37 | CloseHandle(m_fence_event); |
| 38 | } |
| 39 | |
| 40 | std::vector<u32> DXContext::GetAAModes(u32 adapter_index) |
| 41 | { |
| 42 | // Use a temporary device if we aren't booting. |
| 43 | Common::DynamicLibrary temp_lib; |
| 44 | ComPtr<ID3D12Device> temp_device = g_dx_context ? g_dx_context->m_device : nullptr; |
| 45 | if (!temp_device) |
| 46 | { |
| 47 | ComPtr<IDXGIFactory> temp_dxgi_factory = D3DCommon::CreateDXGIFactory(false); |
| 48 | if (!temp_dxgi_factory) |
| 49 | return {}; |
| 50 | |
| 51 | ComPtr<IDXGIAdapter> adapter; |
| 52 | HRESULT hr = temp_dxgi_factory->EnumAdapters(adapter_index, &adapter); |
| 53 | |
| 54 | if (!SUCCEEDED(hr)) |
| 55 | return {}; |
| 56 | |
| 57 | PFN_D3D12_CREATE_DEVICE d3d12_create_device; |
| 58 | if (!temp_lib.Open("d3d12.dll") || |
| 59 | !temp_lib.GetSymbol("D3D12CreateDevice", &d3d12_create_device)) |
| 60 | { |
| 61 | return {}; |
| 62 | } |
| 63 | |
| 64 | hr = d3d12_create_device(adapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&temp_device)); |
| 65 | if (!SUCCEEDED(hr)) |
| 66 | return {}; |
| 67 | } |
| 68 | |
| 69 | const DXGI_FORMAT target_format = |
| 70 | D3DCommon::GetDXGIFormatForAbstractFormat(FramebufferManager::GetEFBColorFormat(), false); |
| 71 | std::vector<u32> aa_modes; |
| 72 | for (u32 samples = 1; samples < D3D12_MAX_MULTISAMPLE_SAMPLE_COUNT; ++samples) |
| 73 | { |
| 74 | D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS multisample_quality_levels = {}; |
| 75 | multisample_quality_levels.Format = target_format; |
| 76 | multisample_quality_levels.SampleCount = samples; |
| 77 | |
| 78 | temp_device->CheckFeatureSupport(D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, |
| 79 | &multisample_quality_levels, |
| 80 | sizeof(multisample_quality_levels)); |
| 81 | |
| 82 | if (multisample_quality_levels.NumQualityLevels > 0) |
| 83 | aa_modes.push_back(samples); |
| 84 | } |
| 85 | |
| 86 | return aa_modes; |
| 87 | } |
| 88 | |
| 89 | bool DXContext::SupportsTextureFormat(DXGI_FORMAT format) |
| 90 | { |
| 91 | constexpr u32 required = D3D12_FORMAT_SUPPORT1_TEXTURE2D | D3D12_FORMAT_SUPPORT1_TEXTURECUBE | |
| 92 | D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE; |
| 93 | |
| 94 | D3D12_FEATURE_DATA_FORMAT_SUPPORT support = {format}; |
| 95 | return SUCCEEDED(m_device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &support, |
| 96 | sizeof(support))) && |
| 97 | (support.Support1 & required) == required; |
| 98 | } |
| 99 | |
| 100 | bool DXContext::Create(u32 adapter_index, bool enable_debug_layer) |
| 101 | { |
| 102 | ASSERT(!g_dx_context); |
| 103 | if (!s_d3d12_library.Open("d3d12.dll") || |
| 104 | !s_d3d12_library.GetSymbol("D3D12CreateDevice", &s_d3d12_create_device) || |
| 105 | !s_d3d12_library.GetSymbol("D3D12GetDebugInterface", &s_d3d12_get_debug_interface) || |
| 106 | !s_d3d12_library.GetSymbol("D3D12SerializeRootSignature", &s_d3d12_serialize_root_signature)) |
| 107 | { |
| 108 | PanicAlertFmtT("d3d12.dll could not be loaded."); |
| 109 | s_d3d12_library.Close(); |
| 110 | return false; |
| 111 | } |
| 112 | |
| 113 | if (!D3DCommon::LoadLibraries()) |
| 114 | { |
| 115 | s_d3d12_library.Close(); |
| 116 | return false; |
| 117 | } |
| 118 | |
| 119 | g_dx_context.reset(new DXContext()); |
| 120 | if (!g_dx_context->CreateDXGIFactory(enable_debug_layer) || |
| 121 | !g_dx_context->CreateDevice(adapter_index, enable_debug_layer) || |
| 122 | !g_dx_context->CreateCommandQueue() || !g_dx_context->CreateFence()) |
| 123 | { |
| 124 | Destroy(); |
| 125 | return false; |
| 126 | } |
| 127 | |
| 128 | return true; |
| 129 | } |
| 130 | |
| 131 | bool DXContext::CreateGlobalResources() |
| 132 | { |
| 133 | return g_dx_context->CreateDescriptorHeaps() && g_dx_context->CreateRootSignatures() && |
| 134 | g_dx_context->CreateTextureUploadBuffer() && g_dx_context->CreateCommandLists(); |
| 135 | } |
| 136 | |
| 137 | void DXContext::Destroy() |
| 138 | { |
| 139 | if (g_dx_context) |
| 140 | g_dx_context.reset(); |
| 141 | |
| 142 | s_d3d12_serialize_root_signature = nullptr; |
| 143 | s_d3d12_get_debug_interface = nullptr; |
| 144 | s_d3d12_create_device = nullptr; |
| 145 | s_d3d12_library.Close(); |
| 146 | D3DCommon::UnloadLibraries(); |
| 147 | } |
| 148 | |
| 149 | bool DXContext::CreateDXGIFactory(bool enable_debug_layer) |
| 150 | { |
| 151 | m_dxgi_factory = D3DCommon::CreateDXGIFactory(enable_debug_layer); |
| 152 | return m_dxgi_factory != nullptr; |
| 153 | } |
| 154 | |
| 155 | bool DXContext::CreateDevice(u32 adapter_index, bool enable_debug_layer) |
| 156 | { |
| 157 | ComPtr<IDXGIAdapter> adapter; |
| 158 | HRESULT hr = m_dxgi_factory->EnumAdapters(adapter_index, &adapter); |
| 159 | if (FAILED(hr)) |
| 160 | { |
| 161 | ERROR_LOG_FMT(VIDEO, "Adapter {} not found, using default: {}", adapter_index, DX12HRWrap(hr)); |
| 162 | adapter = nullptr; |
| 163 | } |
| 164 | |
| 165 | // Enabling the debug layer will fail if the Graphics Tools feature is not installed. |
| 166 | if (enable_debug_layer) |
| 167 | { |
| 168 | hr = s_d3d12_get_debug_interface(IID_PPV_ARGS(&m_debug_interface)); |
| 169 | if (SUCCEEDED(hr)) |
| 170 | { |
| 171 | m_debug_interface->EnableDebugLayer(); |
| 172 | } |
| 173 | else |
| 174 | { |
| 175 | ERROR_LOG_FMT(VIDEO, "Debug layer requested but not available: {}", DX12HRWrap(hr)); |
| 176 | enable_debug_layer = false; |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | // Create the actual device. |
| 181 | hr = s_d3d12_create_device(adapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&m_device)); |
| 182 | ASSERT_MSG(VIDEO, SUCCEEDED(hr), "Failed to create D3D12 device: {}", DX12HRWrap(hr)); |
| 183 | if (FAILED(hr)) |
| 184 | return false; |
| 185 | |
| 186 | if (enable_debug_layer) |
| 187 | { |
| 188 | ComPtr<ID3D12InfoQueue> info_queue; |
| 189 | if (SUCCEEDED(m_device.As(&info_queue))) |
| 190 | { |
| 191 | info_queue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_ERROR, TRUE); |
| 192 | info_queue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_WARNING, TRUE); |
| 193 | |
| 194 | D3D12_INFO_QUEUE_FILTER filter = {}; |
| 195 | std::array<D3D12_MESSAGE_ID, 5> id_list{ |
| 196 | D3D12_MESSAGE_ID_CLEARRENDERTARGETVIEW_MISMATCHINGCLEARVALUE, |
| 197 | D3D12_MESSAGE_ID_CLEARDEPTHSTENCILVIEW_MISMATCHINGCLEARVALUE, |
| 198 | D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_RENDERTARGETVIEW_NOT_SET, |
| 199 | D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_TYPE_MISMATCH, |
| 200 | D3D12_MESSAGE_ID_DRAW_EMPTY_SCISSOR_RECTANGLE, |
| 201 | }; |
| 202 | filter.DenyList.NumIDs = static_cast<UINT>(id_list.size()); |
| 203 | filter.DenyList.pIDList = id_list.data(); |
| 204 | info_queue->PushStorageFilter(&filter); |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | return true; |
| 209 | } |
| 210 | |
| 211 | bool DXContext::CreateCommandQueue() |
| 212 | { |
| 213 | const D3D12_COMMAND_QUEUE_DESC queue_desc = {D3D12_COMMAND_LIST_TYPE_DIRECT, |
| 214 | D3D12_COMMAND_QUEUE_PRIORITY_NORMAL, |
| 215 | D3D12_COMMAND_QUEUE_FLAG_NONE}; |
| 216 | HRESULT hr = m_device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&m_command_queue)); |
| 217 | ASSERT_MSG(VIDEO, SUCCEEDED(hr), "Failed to create command queue: {}", DX12HRWrap(hr)); |
| 218 | return SUCCEEDED(hr); |
| 219 | } |
| 220 | |
| 221 | bool DXContext::CreateFence() |
| 222 | { |
| 223 | HRESULT hr = |
| 224 | m_device->CreateFence(m_completed_fence_value, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&m_fence)); |
| 225 | ASSERT_MSG(VIDEO, SUCCEEDED(hr), "Failed to create fence: {}", DX12HRWrap(hr)); |
| 226 | if (FAILED(hr)) |
| 227 | return false; |
| 228 | |
| 229 | m_fence_event = CreateEvent(nullptr, FALSE, FALSE, nullptr); |
| 230 | ASSERT_MSG(VIDEO, m_fence_event != nullptr, "Failed to create fence event"); |
| 231 | if (!m_fence_event) |
| 232 | return false; |
| 233 | |
| 234 | return true; |
| 235 | } |
| 236 | |
| 237 | bool DXContext::CreateDescriptorHeaps() |
| 238 | { |
| 239 | static constexpr size_t MAX_SRVS = 16384; |
| 240 | static constexpr size_t MAX_RTVS = 8192; |
| 241 | static constexpr size_t MAX_DSVS = 128; |
| 242 | static constexpr size_t MAX_SAMPLERS = 16384; |
| 243 | |
| 244 | if (!m_descriptor_heap_manager.Create(m_device.Get(), D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, |
| 245 | MAX_SRVS) || |
| 246 | !m_rtv_heap_manager.Create(m_device.Get(), D3D12_DESCRIPTOR_HEAP_TYPE_RTV, MAX_RTVS) || |
| 247 | !m_dsv_heap_manager.Create(m_device.Get(), D3D12_DESCRIPTOR_HEAP_TYPE_DSV, MAX_DSVS) || |
| 248 | !m_sampler_heap_manager.Create(m_device.Get(), MAX_SAMPLERS)) |
| 249 | { |
| 250 | return false; |
| 251 | } |
| 252 | |
| 253 | m_gpu_descriptor_heaps[1] = m_sampler_heap_manager.GetDescriptorHeap(); |
| 254 | |
| 255 | // Allocate null SRV descriptor for unbound textures. |
| 256 | constexpr D3D12_SHADER_RESOURCE_VIEW_DESC null_srv_desc = { |
| 257 | DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_SRV_DIMENSION_TEXTURE2D, |
| 258 | D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; |
| 259 | |
| 260 | if (!m_descriptor_heap_manager.Allocate(&m_null_srv_descriptor)) |
| 261 | { |
| 262 | PanicAlertFmt("Failed to allocate null descriptor"); |
| 263 | return false; |
| 264 | } |
| 265 | |
| 266 | m_device->CreateShaderResourceView(nullptr, &null_srv_desc, m_null_srv_descriptor.cpu_handle); |
| 267 | return true; |
| 268 | } |
| 269 | |
| 270 | static void SetRootParamConstant(D3D12_ROOT_PARAMETER* rp, u32 shader_reg, u32 num_values, |
| 271 | D3D12_SHADER_VISIBILITY visibility) |
| 272 | { |
| 273 | rp->ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; |
| 274 | rp->Constants.Num32BitValues = num_values; |
| 275 | rp->Constants.ShaderRegister = shader_reg; |
| 276 | rp->Constants.RegisterSpace = 0; |
| 277 | rp->ShaderVisibility = visibility; |
| 278 | } |
| 279 | |
| 280 | static void SetRootParamCBV(D3D12_ROOT_PARAMETER* rp, u32 shader_reg, |
| 281 | D3D12_SHADER_VISIBILITY visibility) |
| 282 | { |
| 283 | rp->ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; |
| 284 | rp->Descriptor.ShaderRegister = shader_reg; |
| 285 | rp->Descriptor.RegisterSpace = 0; |
| 286 | rp->ShaderVisibility = visibility; |
| 287 | } |
| 288 | |
| 289 | static void SetRootParamTable(D3D12_ROOT_PARAMETER* rp, D3D12_DESCRIPTOR_RANGE* dr, |
| 290 | D3D12_DESCRIPTOR_RANGE_TYPE rt, u32 start_shader_reg, |
| 291 | u32 num_shader_regs, D3D12_SHADER_VISIBILITY visibility) |
| 292 | { |
| 293 | dr->RangeType = rt; |
| 294 | dr->NumDescriptors = num_shader_regs; |
| 295 | dr->BaseShaderRegister = start_shader_reg; |
| 296 | dr->RegisterSpace = 0; |
| 297 | dr->OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND; |
| 298 | |
| 299 | rp->ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; |
| 300 | rp->DescriptorTable.pDescriptorRanges = dr; |
| 301 | rp->DescriptorTable.NumDescriptorRanges = 1; |
| 302 | rp->ShaderVisibility = visibility; |
| 303 | } |
| 304 | |
| 305 | static bool BuildRootSignature(ID3D12Device* device, ID3D12RootSignature** sig_ptr, |
| 306 | const D3D12_ROOT_PARAMETER* params, u32 num_params) |
| 307 | { |
| 308 | D3D12_ROOT_SIGNATURE_DESC desc = {}; |
| 309 | desc.pParameters = params; |
| 310 | desc.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT | |
| 311 | D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS | |
| 312 | D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS; |
| 313 | desc.NumParameters = num_params; |
| 314 | |
| 315 | ComPtr<ID3DBlob> root_signature_blob; |
| 316 | ComPtr<ID3DBlob> root_signature_error_blob; |
| 317 | |
| 318 | HRESULT hr = s_d3d12_serialize_root_signature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, |
| 319 | &root_signature_blob, &root_signature_error_blob); |
| 320 | if (FAILED(hr)) |
| 321 | { |
| 322 | PanicAlertFmt("Failed to serialize root signature: {}\n{}", |
| 323 | static_cast<const char*>(root_signature_error_blob->GetBufferPointer()), |
| 324 | DX12HRWrap(hr)); |
| 325 | return false; |
| 326 | } |
| 327 | |
| 328 | hr = device->CreateRootSignature(0, root_signature_blob->GetBufferPointer(), |
| 329 | root_signature_blob->GetBufferSize(), IID_PPV_ARGS(sig_ptr)); |
| 330 | ASSERT_MSG(VIDEO, SUCCEEDED(hr), "Failed to create root signature: {}", DX12HRWrap(hr)); |
| 331 | return true; |
| 332 | } |
| 333 | |
| 334 | bool DXContext::CreateRootSignatures() |
| 335 | { |
| 336 | return CreateGXRootSignature() && CreateUtilityRootSignature() && CreateComputeRootSignature(); |
| 337 | } |
| 338 | |
| 339 | bool DXContext::CreateGXRootSignature() |
| 340 | { |
| 341 | // GX: |
| 342 | // - 4 constant buffers (bindings 0-3), 0/1/2 visible in PS, 3 visible in VS, 1 visible in GS. |
| 343 | // - VideoCommon::MAX_PIXEL_SHADER_SAMPLERS textures (visible in PS). |
| 344 | // - VideoCommon::MAX_PIXEL_SHADER_SAMPLERS samplers (visible in PS). |
| 345 | // - 1 UAV (visible in PS). |
| 346 | |
| 347 | std::array<D3D12_ROOT_PARAMETER, NUM_ROOT_PARAMETERS> params; |
| 348 | std::array<D3D12_DESCRIPTOR_RANGE, NUM_ROOT_PARAMETERS> ranges; |
| 349 | u32 param_count = 0; |
| 350 | SetRootParamCBV(¶ms[param_count], 0, D3D12_SHADER_VISIBILITY_PIXEL); |
| 351 | param_count++; |
| 352 | SetRootParamTable(¶ms[param_count], &ranges[param_count], D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 0, |
| 353 | VideoCommon::MAX_PIXEL_SHADER_SAMPLERS, D3D12_SHADER_VISIBILITY_PIXEL); |
| 354 | param_count++; |
| 355 | SetRootParamTable(¶ms[param_count], &ranges[param_count], D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, |
| 356 | 0, VideoCommon::MAX_PIXEL_SHADER_SAMPLERS, D3D12_SHADER_VISIBILITY_PIXEL); |
| 357 | param_count++; |
| 358 | SetRootParamCBV(¶ms[param_count], 0, D3D12_SHADER_VISIBILITY_VERTEX); |
| 359 | param_count++; |
| 360 | SetRootParamCBV(¶ms[param_count], 1, D3D12_SHADER_VISIBILITY_VERTEX); |
| 361 | param_count++; |
| 362 | SetRootParamCBV(¶ms[param_count], 2, D3D12_SHADER_VISIBILITY_VERTEX); |
| 363 | param_count++; |
| 364 | if (g_ActiveConfig.UseVSForLinePointExpand()) |
| 365 | SetRootParamCBV(¶ms[param_count], 3, D3D12_SHADER_VISIBILITY_VERTEX); |
| 366 | else |
| 367 | SetRootParamCBV(¶ms[param_count], 0, D3D12_SHADER_VISIBILITY_GEOMETRY); |
| 368 | param_count++; |
| 369 | SetRootParamTable(¶ms[param_count], &ranges[param_count], D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 3, |
| 370 | 1, D3D12_SHADER_VISIBILITY_VERTEX); |
| 371 | param_count++; |
| 372 | SetRootParamConstant(¶ms[param_count], 4, 1, D3D12_SHADER_VISIBILITY_VERTEX); |
| 373 | param_count++; |
| 374 | |
| 375 | SetRootParamCBV(¶ms[param_count], 2, D3D12_SHADER_VISIBILITY_PIXEL); |
| 376 | param_count++; |
| 377 | |
| 378 | // Since these must be contiguous, pixel lighting goes to bbox if not enabled. |
| 379 | if (g_ActiveConfig.bBBoxEnable) |
| 380 | { |
| 381 | SetRootParamTable(¶ms[param_count], &ranges[param_count], D3D12_DESCRIPTOR_RANGE_TYPE_UAV, |
| 382 | 2, 1, D3D12_SHADER_VISIBILITY_PIXEL); |
| 383 | param_count++; |
| 384 | } |
| 385 | if (g_ActiveConfig.bEnablePixelLighting) |
| 386 | { |
| 387 | SetRootParamCBV(¶ms[param_count], 1, D3D12_SHADER_VISIBILITY_PIXEL); |
| 388 | param_count++; |
| 389 | } |
| 390 | |
| 391 | return BuildRootSignature(m_device.Get(), &m_gx_root_signature, params.data(), param_count); |
| 392 | } |
| 393 | |
| 394 | bool DXContext::CreateUtilityRootSignature() |
| 395 | { |
| 396 | // Utility: |
| 397 | // - 1 constant buffer (binding 0, visible in VS/PS). |
| 398 | // - 8 textures (visible in PS). |
| 399 | // - 8 samplers (visible in PS). |
| 400 | |
| 401 | std::array<D3D12_ROOT_PARAMETER, NUM_ROOT_PARAMETERS> params; |
| 402 | std::array<D3D12_DESCRIPTOR_RANGE, NUM_ROOT_PARAMETERS> ranges; |
| 403 | SetRootParamCBV(¶ms[ROOT_PARAMETER_PS_CBV], 0, D3D12_SHADER_VISIBILITY_ALL); |
| 404 | SetRootParamTable(¶ms[ROOT_PARAMETER_PS_SRV], &ranges[ROOT_PARAMETER_PS_SRV], |
| 405 | D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 0, 8, D3D12_SHADER_VISIBILITY_PIXEL); |
| 406 | SetRootParamTable(¶ms[ROOT_PARAMETER_PS_SAMPLERS], &ranges[ROOT_PARAMETER_PS_SAMPLERS], |
| 407 | D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, 0, 8, D3D12_SHADER_VISIBILITY_PIXEL); |
| 408 | return BuildRootSignature(m_device.Get(), &m_utility_root_signature, params.data(), 3); |
| 409 | } |
| 410 | |
| 411 | bool DXContext::CreateComputeRootSignature() |
| 412 | { |
| 413 | // Compute: |
| 414 | // - 1 constant buffer (binding 0). |
| 415 | // - 8 textures. |
| 416 | // - 8 samplers. |
| 417 | // - 1 UAV. |
| 418 | |
| 419 | std::array<D3D12_ROOT_PARAMETER, NUM_ROOT_PARAMETERS> params; |
| 420 | std::array<D3D12_DESCRIPTOR_RANGE, NUM_ROOT_PARAMETERS> ranges; |
| 421 | SetRootParamCBV(¶ms[CS_ROOT_PARAMETER_CBV], 0, D3D12_SHADER_VISIBILITY_ALL); |
| 422 | SetRootParamTable(¶ms[CS_ROOT_PARAMETER_SRV], &ranges[CS_ROOT_PARAMETER_CBV], |
| 423 | D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 0, 8, D3D12_SHADER_VISIBILITY_ALL); |
| 424 | SetRootParamTable(¶ms[CS_ROOT_PARAMETER_SAMPLERS], &ranges[CS_ROOT_PARAMETER_SAMPLERS], |
| 425 | D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, 0, 8, D3D12_SHADER_VISIBILITY_ALL); |
| 426 | SetRootParamTable(¶ms[CS_ROOT_PARAMETER_UAV], &ranges[CS_ROOT_PARAMETER_UAV], |
| 427 | D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 0, 1, D3D12_SHADER_VISIBILITY_ALL); |
| 428 | return BuildRootSignature(m_device.Get(), &m_compute_root_signature, params.data(), 4); |
| 429 | } |
| 430 | |
| 431 | bool DXContext::CreateTextureUploadBuffer() |
| 432 | { |
| 433 | if (!m_texture_upload_buffer.AllocateBuffer(TEXTURE_UPLOAD_BUFFER_SIZE)) |
| 434 | { |
| 435 | PanicAlertFmt("Failed to create texture upload buffer"); |
| 436 | return false; |
| 437 | } |
| 438 | |
| 439 | return true; |
| 440 | } |
| 441 | |
| 442 | bool DXContext::CreateCommandLists() |
| 443 | { |
| 444 | static constexpr size_t MAX_DRAWS_PER_FRAME = 8192; |
| 445 | static constexpr size_t TEMPORARY_SLOTS = MAX_DRAWS_PER_FRAME * 8; |
| 446 | |
| 447 | for (u32 i = 0; i < NUM_COMMAND_LISTS; i++) |
| 448 | { |
| 449 | CommandListResources& res = m_command_lists[i]; |
| 450 | HRESULT hr = m_device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, |
| 451 | IID_PPV_ARGS(&res.command_allocator)); |
| 452 | ASSERT_MSG(VIDEO, SUCCEEDED(hr), "Failed to create command allocator: {}", DX12HRWrap(hr)); |
| 453 | if (FAILED(hr)) |
| 454 | return false; |
| 455 | |
| 456 | hr = m_device->CreateCommandList(1, D3D12_COMMAND_LIST_TYPE_DIRECT, res.command_allocator.Get(), |
| 457 | nullptr, IID_PPV_ARGS(&res.command_list)); |
| 458 | ASSERT_MSG(VIDEO, SUCCEEDED(hr), "Failed to create command list: {}", DX12HRWrap(hr)); |
| 459 | if (FAILED(hr)) |
| 460 | { |
| 461 | return false; |
| 462 | } |
| 463 | |
| 464 | // Close the command list, since the first thing we do is reset them. |
| 465 | hr = res.command_list->Close(); |
| 466 | ASSERT_MSG(VIDEO, SUCCEEDED(hr), "Closing new command list failed: {}", DX12HRWrap(hr)); |
| 467 | if (FAILED(hr)) |
| 468 | return false; |
| 469 | |
| 470 | if (!res.descriptor_allocator.Create(m_device.Get(), D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, |
| 471 | TEMPORARY_SLOTS) || |
| 472 | !res.sampler_allocator.Create(m_device.Get())) |
| 473 | { |
| 474 | return false; |
| 475 | } |
| 476 | } |
| 477 | |
| 478 | MoveToNextCommandList(); |
| 479 | return true; |
| 480 | } |
| 481 | |
| 482 | void DXContext::MoveToNextCommandList() |
| 483 | { |
| 484 | m_current_command_list = (m_current_command_list + 1) % NUM_COMMAND_LISTS; |
| 485 | m_current_fence_value++; |
| 486 | |
| 487 | // We may have to wait if this command list hasn't finished on the GPU. |
| 488 | CommandListResources& res = m_command_lists[m_current_command_list]; |
| 489 | WaitForFence(res.ready_fence_value); |
| 490 | |
| 491 | // Begin command list. |
| 492 | res.command_allocator->Reset(); |
| 493 | res.command_list->Reset(res.command_allocator.Get(), nullptr); |
| 494 | res.descriptor_allocator.Reset(); |
| 495 | if (res.sampler_allocator.ShouldReset()) |
| 496 | res.sampler_allocator.Reset(); |
| 497 | m_gpu_descriptor_heaps[0] = res.descriptor_allocator.GetDescriptorHeap(); |
| 498 | m_gpu_descriptor_heaps[1] = res.sampler_allocator.GetDescriptorHeap(); |
| 499 | res.ready_fence_value = m_current_fence_value; |
| 500 | } |
| 501 | |
| 502 | void DXContext::ExecuteCommandList(bool wait_for_completion) |
| 503 | { |
| 504 | CommandListResources& res = m_command_lists[m_current_command_list]; |
| 505 | |
| 506 | // Close and queue command list. |
| 507 | HRESULT hr = res.command_list->Close(); |
| 508 | ASSERT_MSG(VIDEO, SUCCEEDED(hr), "Failed to close command list: {}", DX12HRWrap(hr)); |
| 509 | const std::array<ID3D12CommandList*, 1> execute_lists{res.command_list.Get()}; |
| 510 | m_command_queue->ExecuteCommandLists(static_cast<UINT>(execute_lists.size()), |
| 511 | execute_lists.data()); |
| 512 | |
| 513 | // Update fence when GPU has completed. |
| 514 | hr = m_command_queue->Signal(m_fence.Get(), m_current_fence_value); |
| 515 | |
| 516 | ASSERT_MSG(VIDEO, SUCCEEDED(hr), "Failed to signal fence: {}", DX12HRWrap(hr)); |
| 517 | |
| 518 | MoveToNextCommandList(); |
| 519 | if (wait_for_completion) |
| 520 | WaitForFence(res.ready_fence_value); |
| 521 | } |
| 522 | |
| 523 | void DXContext::DeferResourceDestruction(ID3D12Resource* resource) |
| 524 | { |
| 525 | resource->AddRef(); |
| 526 | m_command_lists[m_current_command_list].pending_resources.push_back(resource); |
| 527 | } |
| 528 | |
| 529 | void DXContext::DeferDescriptorDestruction(DescriptorHeapManager& manager, u32 index) |
| 530 | { |
| 531 | m_command_lists[m_current_command_list].pending_descriptors.emplace_back(manager, index); |
| 532 | } |
| 533 | |
| 534 | void DXContext::ResetSamplerAllocators() |
| 535 | { |
| 536 | for (CommandListResources& res : m_command_lists) |
| 537 | res.sampler_allocator.Reset(); |
| 538 | } |
| 539 | |
| 540 | void DXContext::RecreateGXRootSignature() |
| 541 | { |
| 542 | m_gx_root_signature.Reset(); |
| 543 | if (!CreateGXRootSignature()) |
| 544 | PanicAlertFmt("Failed to re-create GX root signature."); |
| 545 | } |
| 546 | |
| 547 | void DXContext::DestroyPendingResources(CommandListResources& cmdlist) |
| 548 | { |
| 549 | for (const auto& dd : cmdlist.pending_descriptors) |
| 550 | dd.first.Free(dd.second); |
| 551 | cmdlist.pending_descriptors.clear(); |
| 552 | |
| 553 | for (ID3D12Resource* res : cmdlist.pending_resources) |
| 554 | res->Release(); |
| 555 | cmdlist.pending_resources.clear(); |
| 556 | } |
| 557 | |
| 558 | void DXContext::WaitForFence(u64 fence) |
| 559 | { |
| 560 | if (m_completed_fence_value >= fence) |
| 561 | return; |
| 562 | |
| 563 | // Try non-blocking check. |
| 564 | m_completed_fence_value = m_fence->GetCompletedValue(); |
| 565 | if (m_completed_fence_value < fence) |
| 566 | { |
| 567 | // Fall back to event. |
| 568 | HRESULT hr = m_fence->SetEventOnCompletion(fence, m_fence_event); |
| 569 | ASSERT_MSG(VIDEO, SUCCEEDED(hr), "Failed to set fence event on completion: {}", DX12HRWrap(hr)); |
| 570 | WaitForSingleObject(m_fence_event, INFINITE); |
| 571 | m_completed_fence_value = m_fence->GetCompletedValue(); |
| 572 | } |
| 573 | |
| 574 | // Release resources for as many command lists which have completed. |
| 575 | u32 index = (m_current_command_list + 1) % NUM_COMMAND_LISTS; |
| 576 | for (u32 i = 0; i < NUM_COMMAND_LISTS; i++) |
| 577 | { |
| 578 | CommandListResources& res = m_command_lists[index]; |
| 579 | if (m_completed_fence_value < res.ready_fence_value) |
| 580 | break; |
| 581 | |
| 582 | DestroyPendingResources(res); |
| 583 | index = (index + 1) % NUM_COMMAND_LISTS; |
| 584 | } |
| 585 | } |
| 586 | } // namespace DX12 |