mirror of
https://github.com/WinampDesktop/winamp.git
synced 2025-06-18 18:45:45 -04:00
GPU: Add D3D12 renderer
This commit is contained in:
@ -51,10 +51,14 @@ if(WIN32)
|
||||
target_sources(frontend-common PRIVATE
|
||||
d3d11_host_display.cpp
|
||||
d3d11_host_display.h
|
||||
d3d12_host_display.cpp
|
||||
d3d12_host_display.h
|
||||
dinput_controller_interface.cpp
|
||||
dinput_controller_interface.h
|
||||
imgui_impl_dx11.cpp
|
||||
imgui_impl_dx11.h
|
||||
imgui_impl_dx12.cpp
|
||||
imgui_impl_dx12.h
|
||||
xaudio2_audio_stream.cpp
|
||||
xaudio2_audio_stream.h
|
||||
xinput_controller_interface.cpp
|
||||
|
871
src/frontend-common/d3d12_host_display.cpp
Normal file
871
src/frontend-common/d3d12_host_display.cpp
Normal file
@ -0,0 +1,871 @@
|
||||
#include "d3d12_host_display.h"
|
||||
#include "common/assert.h"
|
||||
#include "common/d3d11/shader_compiler.h"
|
||||
#include "common/d3d12/context.h"
|
||||
#include "common/d3d12/util.h"
|
||||
#include "common/log.h"
|
||||
#include "common/string_util.h"
|
||||
#include "core/host_interface.h"
|
||||
#include "core/settings.h"
|
||||
#include "display_ps.hlsl.h"
|
||||
#include "display_vs.hlsl.h"
|
||||
#include "frontend-common/postprocessing_shadergen.h"
|
||||
#include "imgui.h"
|
||||
#include "imgui_impl_dx12.h"
|
||||
#include <array>
|
||||
#include <dxgi1_5.h>
|
||||
Log_SetChannel(D3D12HostDisplay);
|
||||
|
||||
namespace FrontendCommon {
|
||||
|
||||
static constexpr std::array<DXGI_FORMAT, static_cast<u32>(HostDisplayPixelFormat::Count)>
|
||||
s_display_pixel_format_mapping = {{DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_B8G8R8A8_UNORM,
|
||||
DXGI_FORMAT_B5G6R5_UNORM, DXGI_FORMAT_B5G5R5A1_UNORM}};
|
||||
|
||||
class D3D12HostDisplayTexture : public HostDisplayTexture
|
||||
{
|
||||
public:
|
||||
D3D12HostDisplayTexture(D3D12::Texture texture) : m_texture(std::move(texture)) {}
|
||||
~D3D12HostDisplayTexture() override = default;
|
||||
|
||||
void* GetHandle() const override { return const_cast<D3D12::Texture*>(&m_texture); }
|
||||
u32 GetWidth() const override { return m_texture.GetWidth(); }
|
||||
u32 GetHeight() const override { return m_texture.GetHeight(); }
|
||||
u32 GetLayers() const override { return 1; }
|
||||
u32 GetLevels() const override { return 1; }
|
||||
u32 GetSamples() const override { return m_texture.GetSamples(); }
|
||||
|
||||
HostDisplayPixelFormat GetFormat() const override
|
||||
{
|
||||
for (u32 i = 0; i < static_cast<u32>(s_display_pixel_format_mapping.size()); i++)
|
||||
{
|
||||
if (m_texture.GetFormat() == s_display_pixel_format_mapping[i])
|
||||
return static_cast<HostDisplayPixelFormat>(i);
|
||||
}
|
||||
|
||||
return HostDisplayPixelFormat::Count;
|
||||
}
|
||||
|
||||
const D3D12::Texture& GetTexture() const { return m_texture; }
|
||||
D3D12::Texture& GetTexture() { return m_texture; }
|
||||
|
||||
private:
|
||||
D3D12::Texture m_texture;
|
||||
};
|
||||
|
||||
D3D12HostDisplay::D3D12HostDisplay() = default;
|
||||
|
||||
D3D12HostDisplay::~D3D12HostDisplay()
|
||||
{
|
||||
AssertMsg(!g_d3d12_context, "Context should have been destroyed by now");
|
||||
AssertMsg(!m_swap_chain, "Swap chain should have been destroyed by now");
|
||||
}
|
||||
|
||||
HostDisplay::RenderAPI D3D12HostDisplay::GetRenderAPI() const
|
||||
{
|
||||
return HostDisplay::RenderAPI::D3D12;
|
||||
}
|
||||
|
||||
void* D3D12HostDisplay::GetRenderDevice() const
|
||||
{
|
||||
return g_d3d12_context->GetDevice();
|
||||
}
|
||||
|
||||
void* D3D12HostDisplay::GetRenderContext() const
|
||||
{
|
||||
return g_d3d12_context.get();
|
||||
}
|
||||
|
||||
bool D3D12HostDisplay::HasRenderDevice() const
|
||||
{
|
||||
return static_cast<bool>(g_d3d12_context);
|
||||
}
|
||||
|
||||
bool D3D12HostDisplay::HasRenderSurface() const
|
||||
{
|
||||
return static_cast<bool>(m_swap_chain);
|
||||
}
|
||||
|
||||
std::unique_ptr<HostDisplayTexture> D3D12HostDisplay::CreateTexture(u32 width, u32 height, u32 layers, u32 levels,
|
||||
u32 samples, HostDisplayPixelFormat format,
|
||||
const void* data, u32 data_stride,
|
||||
bool dynamic /* = false */)
|
||||
{
|
||||
if (layers != 1)
|
||||
return {};
|
||||
|
||||
const DXGI_FORMAT dxgi_format = s_display_pixel_format_mapping[static_cast<u32>(format)];
|
||||
D3D12::Texture tex;
|
||||
if (!tex.Create(width, height, samples, dxgi_format, dxgi_format, DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN,
|
||||
D3D12_RESOURCE_FLAG_NONE))
|
||||
{
|
||||
return {};
|
||||
}
|
||||
|
||||
if (data && !tex.LoadData(0, 0, width, height, data, data_stride))
|
||||
return {};
|
||||
|
||||
return std::make_unique<D3D12HostDisplayTexture>(std::move(tex));
|
||||
}
|
||||
|
||||
void D3D12HostDisplay::UpdateTexture(HostDisplayTexture* texture, u32 x, u32 y, u32 width, u32 height,
|
||||
const void* texture_data, u32 texture_data_stride)
|
||||
{
|
||||
static_cast<D3D12HostDisplayTexture*>(texture)->GetTexture().LoadData(x, y, width, height, texture_data,
|
||||
texture_data_stride);
|
||||
}
|
||||
|
||||
bool D3D12HostDisplay::DownloadTexture(const void* texture_handle, HostDisplayPixelFormat texture_format, u32 x, u32 y,
|
||||
u32 width, u32 height, void* out_data, u32 out_data_stride)
|
||||
{
|
||||
const D3D12::Texture* texture = static_cast<const D3D12::Texture*>(texture_handle);
|
||||
|
||||
if (!m_readback_staging_texture.EnsureSize(width, height, texture->GetFormat(), false))
|
||||
return false;
|
||||
|
||||
m_readback_staging_texture.CopyFromTexture(texture->GetResource(), 0, x, y, 0, 0, width, height);
|
||||
return m_readback_staging_texture.ReadPixels(0, 0, width, height, out_data, out_data_stride);
|
||||
}
|
||||
|
||||
bool D3D12HostDisplay::SupportsDisplayPixelFormat(HostDisplayPixelFormat format) const
|
||||
{
|
||||
const DXGI_FORMAT dfmt = s_display_pixel_format_mapping[static_cast<u32>(format)];
|
||||
if (dfmt == DXGI_FORMAT_UNKNOWN)
|
||||
return false;
|
||||
|
||||
return g_d3d12_context->SupportsTextureFormat(dfmt);
|
||||
}
|
||||
|
||||
bool D3D12HostDisplay::BeginSetDisplayPixels(HostDisplayPixelFormat format, u32 width, u32 height, void** out_buffer,
|
||||
u32* out_pitch)
|
||||
{
|
||||
ClearDisplayTexture();
|
||||
|
||||
const DXGI_FORMAT dxgi_format = s_display_pixel_format_mapping[static_cast<u32>(format)];
|
||||
if (m_display_pixels_texture.GetWidth() < width || m_display_pixels_texture.GetHeight() < height ||
|
||||
m_display_pixels_texture.GetFormat() != dxgi_format)
|
||||
{
|
||||
if (!m_display_pixels_texture.Create(width, height, 1, dxgi_format, dxgi_format, DXGI_FORMAT_UNKNOWN,
|
||||
DXGI_FORMAT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (!m_display_pixels_texture.BeginStreamUpdate(0, 0, width, height, out_buffer, out_pitch))
|
||||
return false;
|
||||
|
||||
SetDisplayTexture(&m_display_pixels_texture, format, m_display_pixels_texture.GetWidth(),
|
||||
m_display_pixels_texture.GetHeight(), 0, 0, static_cast<u32>(width), static_cast<u32>(height));
|
||||
return true;
|
||||
}
|
||||
|
||||
void D3D12HostDisplay::EndSetDisplayPixels()
|
||||
{
|
||||
m_display_pixels_texture.EndStreamUpdate(0, 0, m_display_pixels_texture.GetWidth(),
|
||||
m_display_pixels_texture.GetHeight());
|
||||
}
|
||||
|
||||
bool D3D12HostDisplay::GetHostRefreshRate(float* refresh_rate)
|
||||
{
|
||||
if (m_swap_chain && IsFullscreen())
|
||||
{
|
||||
DXGI_SWAP_CHAIN_DESC desc;
|
||||
if (SUCCEEDED(m_swap_chain->GetDesc(&desc)) && desc.BufferDesc.RefreshRate.Numerator > 0 &&
|
||||
desc.BufferDesc.RefreshRate.Denominator > 0)
|
||||
{
|
||||
Log_InfoPrintf("using fs rr: %u %u", desc.BufferDesc.RefreshRate.Numerator,
|
||||
desc.BufferDesc.RefreshRate.Denominator);
|
||||
*refresh_rate = static_cast<float>(desc.BufferDesc.RefreshRate.Numerator) /
|
||||
static_cast<float>(desc.BufferDesc.RefreshRate.Denominator);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return HostDisplay::GetHostRefreshRate(refresh_rate);
|
||||
}
|
||||
|
||||
void D3D12HostDisplay::SetVSync(bool enabled)
|
||||
{
|
||||
m_vsync = enabled;
|
||||
}
|
||||
|
||||
bool D3D12HostDisplay::CreateRenderDevice(const WindowInfo& wi, std::string_view adapter_name, bool debug_device,
|
||||
bool threaded_presentation)
|
||||
{
|
||||
ComPtr<IDXGIFactory> temp_dxgi_factory;
|
||||
#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
|
||||
HRESULT hr = CreateDXGIFactory(IID_PPV_ARGS(temp_dxgi_factory.GetAddressOf()));
|
||||
#else
|
||||
HRESULT hr = CreateDXGIFactory2(0, IID_PPV_ARGS(temp_dxgi_factory.GetAddressOf()));
|
||||
#endif
|
||||
|
||||
if (FAILED(hr))
|
||||
{
|
||||
Log_ErrorPrintf("Failed to create DXGI factory: 0x%08X", hr);
|
||||
return false;
|
||||
}
|
||||
|
||||
u32 adapter_index;
|
||||
if (!adapter_name.empty())
|
||||
{
|
||||
AdapterAndModeList adapter_info(GetAdapterAndModeList(temp_dxgi_factory.Get()));
|
||||
for (adapter_index = 0; adapter_index < static_cast<u32>(adapter_info.adapter_names.size()); adapter_index++)
|
||||
{
|
||||
if (adapter_name == adapter_info.adapter_names[adapter_index])
|
||||
break;
|
||||
}
|
||||
if (adapter_index == static_cast<u32>(adapter_info.adapter_names.size()))
|
||||
{
|
||||
Log_WarningPrintf("Could not find adapter '%*s', using first (%s)", static_cast<int>(adapter_name.size()),
|
||||
adapter_name.data(), adapter_info.adapter_names[0].c_str());
|
||||
adapter_index = 0;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Log_InfoPrintf("No adapter selected, using first.");
|
||||
adapter_index = 0;
|
||||
}
|
||||
|
||||
if (!D3D12::Context::Create(temp_dxgi_factory.Get(), adapter_index, debug_device))
|
||||
return false;
|
||||
|
||||
if (FAILED(hr))
|
||||
{
|
||||
Log_ErrorPrintf("Failed to create D3D device: 0x%08X", hr);
|
||||
return false;
|
||||
}
|
||||
|
||||
#if 0
|
||||
// we need the specific factory for the device, otherwise MakeWindowAssociation() is flaky.
|
||||
ComPtr<IDXGIDevice> dxgi_device;
|
||||
if (FAILED(m_device.As(&dxgi_device)) || FAILED(dxgi_device->GetParent(IID_PPV_ARGS(dxgi_adapter.GetAddressOf()))) ||
|
||||
FAILED(dxgi_adapter->GetParent(IID_PPV_ARGS(m_dxgi_factory.GetAddressOf()))))
|
||||
{
|
||||
Log_WarningPrint("Failed to get parent adapter/device/factory");
|
||||
return false;
|
||||
}
|
||||
#else
|
||||
m_dxgi_factory = std::move(temp_dxgi_factory);
|
||||
#endif
|
||||
|
||||
m_allow_tearing_supported = false;
|
||||
ComPtr<IDXGIFactory5> dxgi_factory5;
|
||||
hr = m_dxgi_factory.As(&dxgi_factory5);
|
||||
if (SUCCEEDED(hr))
|
||||
{
|
||||
BOOL allow_tearing_supported = false;
|
||||
hr = dxgi_factory5->CheckFeatureSupport(DXGI_FEATURE_PRESENT_ALLOW_TEARING, &allow_tearing_supported,
|
||||
sizeof(allow_tearing_supported));
|
||||
if (SUCCEEDED(hr))
|
||||
m_allow_tearing_supported = (allow_tearing_supported == TRUE);
|
||||
}
|
||||
|
||||
m_window_info = wi;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool D3D12HostDisplay::InitializeRenderDevice(std::string_view shader_cache_directory, bool debug_device,
|
||||
bool threaded_presentation)
|
||||
{
|
||||
if (m_window_info.type != WindowInfo::Type::Surfaceless && !CreateSwapChain(nullptr))
|
||||
return false;
|
||||
|
||||
if (!CreateResources())
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void D3D12HostDisplay::DestroyRenderDevice()
|
||||
{
|
||||
g_d3d12_context->ExecuteCommandList(true);
|
||||
|
||||
DestroyResources();
|
||||
DestroyRenderSurface();
|
||||
if (g_d3d12_context)
|
||||
g_d3d12_context->Destroy();
|
||||
}
|
||||
|
||||
bool D3D12HostDisplay::MakeRenderContextCurrent()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
bool D3D12HostDisplay::DoneRenderContextCurrent()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
bool D3D12HostDisplay::CreateSwapChain(const DXGI_MODE_DESC* fullscreen_mode)
|
||||
{
|
||||
HRESULT hr;
|
||||
|
||||
#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
|
||||
if (m_window_info.type != WindowInfo::Type::Win32)
|
||||
return false;
|
||||
|
||||
const HWND window_hwnd = reinterpret_cast<HWND>(m_window_info.window_handle);
|
||||
RECT client_rc{};
|
||||
GetClientRect(window_hwnd, &client_rc);
|
||||
const u32 width = static_cast<u32>(client_rc.right - client_rc.left);
|
||||
const u32 height = static_cast<u32>(client_rc.bottom - client_rc.top);
|
||||
|
||||
DXGI_SWAP_CHAIN_DESC swap_chain_desc = {};
|
||||
swap_chain_desc.BufferDesc.Width = width;
|
||||
swap_chain_desc.BufferDesc.Height = height;
|
||||
swap_chain_desc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
swap_chain_desc.SampleDesc.Count = 1;
|
||||
swap_chain_desc.BufferCount = 3;
|
||||
swap_chain_desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
|
||||
swap_chain_desc.OutputWindow = window_hwnd;
|
||||
swap_chain_desc.Windowed = TRUE;
|
||||
swap_chain_desc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
|
||||
|
||||
m_using_allow_tearing = (m_allow_tearing_supported && !fullscreen_mode);
|
||||
if (m_using_allow_tearing)
|
||||
swap_chain_desc.Flags |= DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING;
|
||||
|
||||
if (fullscreen_mode)
|
||||
{
|
||||
swap_chain_desc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
|
||||
swap_chain_desc.Windowed = FALSE;
|
||||
swap_chain_desc.BufferDesc = *fullscreen_mode;
|
||||
}
|
||||
|
||||
Log_InfoPrintf("Creating a %dx%d %s swap chain", swap_chain_desc.BufferDesc.Width, swap_chain_desc.BufferDesc.Height,
|
||||
swap_chain_desc.Windowed ? "windowed" : "full-screen");
|
||||
|
||||
hr =
|
||||
m_dxgi_factory->CreateSwapChain(g_d3d12_context->GetCommandQueue(), &swap_chain_desc, m_swap_chain.GetAddressOf());
|
||||
if (FAILED(hr))
|
||||
{
|
||||
Log_ErrorPrintf("CreateSwapChain failed: 0x%08X", hr);
|
||||
return false;
|
||||
}
|
||||
|
||||
hr = m_dxgi_factory->MakeWindowAssociation(swap_chain_desc.OutputWindow, DXGI_MWA_NO_WINDOW_CHANGES);
|
||||
if (FAILED(hr))
|
||||
Log_WarningPrintf("MakeWindowAssociation() to disable ALT+ENTER failed");
|
||||
#else
|
||||
if (m_window_info.type != WindowInfo::Type::WinRT)
|
||||
return false;
|
||||
|
||||
ComPtr<IDXGIFactory2> factory2;
|
||||
hr = m_dxgi_factory.As(&factory2);
|
||||
if (FAILED(hr))
|
||||
{
|
||||
Log_ErrorPrintf("Failed to get DXGI factory: %08X", hr);
|
||||
return false;
|
||||
}
|
||||
|
||||
DXGI_SWAP_CHAIN_DESC1 swap_chain_desc = {};
|
||||
swap_chain_desc.Width = m_window_info.surface_width;
|
||||
swap_chain_desc.Height = m_window_info.surface_height;
|
||||
swap_chain_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
swap_chain_desc.SampleDesc.Count = 1;
|
||||
swap_chain_desc.BufferCount = 3;
|
||||
swap_chain_desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
|
||||
swap_chain_desc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
|
||||
|
||||
m_using_allow_tearing = (m_allow_tearing_supported && !fullscreen_mode);
|
||||
if (m_using_allow_tearing)
|
||||
swap_chain_desc.Flags |= DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING;
|
||||
|
||||
ComPtr<IDXGISwapChain1> swap_chain1;
|
||||
hr = factory2->CreateSwapChainForCoreWindow(g_d3d12_context->GetCommandQueue(),
|
||||
static_cast<IUnknown*>(m_window_info.window_handle), &swap_chain_desc,
|
||||
nullptr, swap_chain1.GetAddressOf());
|
||||
if (FAILED(hr))
|
||||
{
|
||||
Log_ErrorPrintf("CreateSwapChainForCoreWindow failed: 0x%08X", hr);
|
||||
return false;
|
||||
}
|
||||
|
||||
m_swap_chain = swap_chain1;
|
||||
#endif
|
||||
|
||||
return CreateSwapChainRTV();
|
||||
}
|
||||
|
||||
bool D3D12HostDisplay::CreateSwapChainRTV()
|
||||
{
|
||||
DXGI_SWAP_CHAIN_DESC swap_chain_desc;
|
||||
HRESULT hr = m_swap_chain->GetDesc(&swap_chain_desc);
|
||||
if (FAILED(hr))
|
||||
return false;
|
||||
|
||||
for (u32 i = 0; i < swap_chain_desc.BufferCount; i++)
|
||||
{
|
||||
ComPtr<ID3D12Resource> backbuffer;
|
||||
hr = m_swap_chain->GetBuffer(i, IID_PPV_ARGS(backbuffer.GetAddressOf()));
|
||||
if (FAILED(hr))
|
||||
{
|
||||
Log_ErrorPrintf("GetBuffer for RTV failed: 0x%08X", hr);
|
||||
return false;
|
||||
}
|
||||
|
||||
D3D12::Texture tex;
|
||||
if (!tex.Adopt(std::move(backbuffer), DXGI_FORMAT_UNKNOWN, swap_chain_desc.BufferDesc.Format, DXGI_FORMAT_UNKNOWN,
|
||||
D3D12_RESOURCE_STATE_PRESENT))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
m_swap_chain_buffers.push_back(std::move(tex));
|
||||
}
|
||||
|
||||
m_window_info.surface_width = swap_chain_desc.BufferDesc.Width;
|
||||
m_window_info.surface_height = swap_chain_desc.BufferDesc.Height;
|
||||
Log_InfoPrintf("Swap chain buffer size: %ux%u", m_window_info.surface_width, m_window_info.surface_height);
|
||||
|
||||
if (m_window_info.type == WindowInfo::Type::Win32)
|
||||
{
|
||||
BOOL fullscreen = FALSE;
|
||||
DXGI_SWAP_CHAIN_DESC desc;
|
||||
if (SUCCEEDED(m_swap_chain->GetFullscreenState(&fullscreen, nullptr)) && fullscreen &&
|
||||
SUCCEEDED(m_swap_chain->GetDesc(&desc)))
|
||||
{
|
||||
m_window_info.surface_refresh_rate = static_cast<float>(desc.BufferDesc.RefreshRate.Numerator) /
|
||||
static_cast<float>(desc.BufferDesc.RefreshRate.Denominator);
|
||||
}
|
||||
else
|
||||
{
|
||||
m_window_info.surface_refresh_rate = 0.0f;
|
||||
}
|
||||
}
|
||||
|
||||
m_current_swap_chain_buffer = 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
void D3D12HostDisplay::DestroySwapChainRTVs()
|
||||
{
|
||||
for (D3D12::Texture& buffer : m_swap_chain_buffers)
|
||||
buffer.Destroy(false);
|
||||
m_swap_chain_buffers.clear();
|
||||
m_current_swap_chain_buffer = 0;
|
||||
}
|
||||
|
||||
bool D3D12HostDisplay::ChangeRenderWindow(const WindowInfo& new_wi)
|
||||
{
|
||||
DestroyRenderSurface();
|
||||
|
||||
m_window_info = new_wi;
|
||||
return CreateSwapChain(nullptr);
|
||||
}
|
||||
|
||||
void D3D12HostDisplay::DestroyRenderSurface()
|
||||
{
|
||||
if (IsFullscreen())
|
||||
SetFullscreen(false, 0, 0, 0.0f);
|
||||
|
||||
DestroySwapChainRTVs();
|
||||
m_swap_chain.Reset();
|
||||
}
|
||||
|
||||
void D3D12HostDisplay::ResizeRenderWindow(s32 new_window_width, s32 new_window_height)
|
||||
{
|
||||
if (!m_swap_chain)
|
||||
return;
|
||||
|
||||
// For some reason if we don't execute the command list here, the swap chain is in use.. not sure where.
|
||||
g_d3d12_context->ExecuteCommandList(true);
|
||||
|
||||
DestroySwapChainRTVs();
|
||||
|
||||
HRESULT hr = m_swap_chain->ResizeBuffers(0, 0, 0, DXGI_FORMAT_UNKNOWN,
|
||||
m_using_allow_tearing ? DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING : 0);
|
||||
if (FAILED(hr))
|
||||
Log_ErrorPrintf("ResizeBuffers() failed: 0x%08X", hr);
|
||||
|
||||
if (!CreateSwapChainRTV())
|
||||
Panic("Failed to recreate swap chain RTV after resize");
|
||||
}
|
||||
|
||||
bool D3D12HostDisplay::SupportsFullscreen() const
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
bool D3D12HostDisplay::IsFullscreen()
|
||||
{
|
||||
BOOL is_fullscreen = FALSE;
|
||||
return (m_swap_chain && SUCCEEDED(m_swap_chain->GetFullscreenState(&is_fullscreen, nullptr)) && is_fullscreen);
|
||||
}
|
||||
|
||||
bool D3D12HostDisplay::SetFullscreen(bool fullscreen, u32 width, u32 height, float refresh_rate)
|
||||
{
|
||||
if (!m_swap_chain)
|
||||
return false;
|
||||
|
||||
BOOL is_fullscreen = FALSE;
|
||||
HRESULT hr = m_swap_chain->GetFullscreenState(&is_fullscreen, nullptr);
|
||||
if (!fullscreen)
|
||||
{
|
||||
// leaving fullscreen
|
||||
if (is_fullscreen)
|
||||
return SUCCEEDED(m_swap_chain->SetFullscreenState(FALSE, nullptr));
|
||||
else
|
||||
return true;
|
||||
}
|
||||
|
||||
IDXGIOutput* output;
|
||||
if (FAILED(hr = m_swap_chain->GetContainingOutput(&output)))
|
||||
return false;
|
||||
|
||||
DXGI_SWAP_CHAIN_DESC current_desc;
|
||||
hr = m_swap_chain->GetDesc(¤t_desc);
|
||||
if (FAILED(hr))
|
||||
return false;
|
||||
|
||||
DXGI_MODE_DESC new_mode = current_desc.BufferDesc;
|
||||
new_mode.Width = width;
|
||||
new_mode.Height = height;
|
||||
new_mode.RefreshRate.Numerator = static_cast<UINT>(std::floor(refresh_rate * 1000.0f));
|
||||
new_mode.RefreshRate.Denominator = 1000u;
|
||||
|
||||
DXGI_MODE_DESC closest_mode;
|
||||
if (FAILED(hr = output->FindClosestMatchingMode(&new_mode, &closest_mode, nullptr)) ||
|
||||
new_mode.Format != current_desc.BufferDesc.Format)
|
||||
{
|
||||
Log_ErrorPrintf("Failed to find closest matching mode, hr=%08X", hr);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (new_mode.Width == current_desc.BufferDesc.Width && new_mode.Height == current_desc.BufferDesc.Width &&
|
||||
new_mode.RefreshRate.Numerator == current_desc.BufferDesc.RefreshRate.Numerator &&
|
||||
new_mode.RefreshRate.Denominator == current_desc.BufferDesc.RefreshRate.Denominator)
|
||||
{
|
||||
Log_InfoPrintf("Fullscreen mode already set");
|
||||
return true;
|
||||
}
|
||||
|
||||
DestroySwapChainRTVs();
|
||||
m_swap_chain.Reset();
|
||||
|
||||
if (!CreateSwapChain(&closest_mode))
|
||||
{
|
||||
Log_ErrorPrintf("Failed to create a fullscreen swap chain");
|
||||
if (!CreateSwapChain(nullptr))
|
||||
Panic("Failed to recreate windowed swap chain");
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
HostDisplay::AdapterAndModeList D3D12HostDisplay::GetAdapterAndModeList()
|
||||
{
|
||||
return GetAdapterAndModeList(m_dxgi_factory.Get());
|
||||
}
|
||||
|
||||
bool D3D12HostDisplay::CreateResources()
|
||||
{
|
||||
D3D12::RootSignatureBuilder rsbuilder;
|
||||
rsbuilder.AddCBVParameter(0, D3D12_SHADER_VISIBILITY_ALL);
|
||||
rsbuilder.AddDescriptorTable(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 0, 1, D3D12_SHADER_VISIBILITY_ALL);
|
||||
rsbuilder.AddDescriptorTable(D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, 0, 1, D3D12_SHADER_VISIBILITY_ALL);
|
||||
m_display_root_signature = rsbuilder.Create();
|
||||
if (!m_display_root_signature)
|
||||
return false;
|
||||
|
||||
D3D12::GraphicsPipelineBuilder gpbuilder;
|
||||
gpbuilder.SetPrimitiveTopologyType(D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE);
|
||||
gpbuilder.SetRootSignature(m_display_root_signature.Get());
|
||||
gpbuilder.SetVertexShader(s_display_vs_bytecode, sizeof(s_display_vs_bytecode));
|
||||
gpbuilder.SetPixelShader(s_display_ps_bytecode, sizeof(s_display_ps_bytecode));
|
||||
gpbuilder.SetNoCullRasterizationState();
|
||||
gpbuilder.SetNoDepthTestState();
|
||||
gpbuilder.SetNoBlendingState();
|
||||
gpbuilder.SetRenderTarget(0, DXGI_FORMAT_R8G8B8A8_UNORM);
|
||||
m_display_pipeline = gpbuilder.Create(g_d3d12_context->GetDevice(), false);
|
||||
if (!m_display_pipeline)
|
||||
return false;
|
||||
|
||||
gpbuilder.SetBlendState(0, true, D3D12_BLEND_SRC_ALPHA, D3D12_BLEND_INV_SRC_ALPHA, D3D12_BLEND_OP_ADD,
|
||||
D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD, D3D12_COLOR_WRITE_ENABLE_ALL);
|
||||
m_software_cursor_pipeline = gpbuilder.Create(g_d3d12_context->GetDevice(), false);
|
||||
if (!m_software_cursor_pipeline)
|
||||
return false;
|
||||
|
||||
D3D12_SAMPLER_DESC desc = {};
|
||||
D3D12::SetDefaultSampler(&desc);
|
||||
desc.AddressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
|
||||
desc.AddressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
|
||||
desc.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT;
|
||||
|
||||
if (!g_d3d12_context->GetSamplerHeapManager().Allocate(&m_point_sampler))
|
||||
return false;
|
||||
|
||||
g_d3d12_context->GetDevice()->CreateSampler(&desc, m_point_sampler.cpu_handle);
|
||||
|
||||
desc.Filter = D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT;
|
||||
|
||||
if (!g_d3d12_context->GetSamplerHeapManager().Allocate(&m_linear_sampler))
|
||||
return false;
|
||||
|
||||
g_d3d12_context->GetDevice()->CreateSampler(&desc, m_linear_sampler.cpu_handle);
|
||||
|
||||
if (!m_display_uniform_buffer.Create(DISPLAY_UNIFORM_BUFFER_SIZE))
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void D3D12HostDisplay::DestroyResources()
|
||||
{
|
||||
// m_post_processing_chain.ClearStages();
|
||||
// m_post_processing_input_texture.Destroy();
|
||||
// m_post_processing_stages.clear();
|
||||
|
||||
m_readback_staging_texture.Destroy(false);
|
||||
m_display_uniform_buffer.Destroy(false);
|
||||
g_d3d12_context->GetSamplerHeapManager().Free(&m_linear_sampler);
|
||||
g_d3d12_context->GetSamplerHeapManager().Free(&m_point_sampler);
|
||||
m_software_cursor_pipeline.Reset();
|
||||
m_display_pipeline.Reset();
|
||||
m_display_root_signature.Reset();
|
||||
}
|
||||
|
||||
bool D3D12HostDisplay::CreateImGuiContext()
|
||||
{
|
||||
ImGui::GetIO().DisplaySize.x = static_cast<float>(m_window_info.surface_width);
|
||||
ImGui::GetIO().DisplaySize.y = static_cast<float>(m_window_info.surface_height);
|
||||
|
||||
return ImGui_ImplDX12_Init(g_d3d12_context->GetDevice(), D3D12::Context::NUM_COMMAND_LISTS,
|
||||
DXGI_FORMAT_R8G8B8A8_UNORM);
|
||||
}
|
||||
|
||||
void D3D12HostDisplay::DestroyImGuiContext()
|
||||
{
|
||||
g_d3d12_context->WaitForGPUIdle();
|
||||
|
||||
ImGui_ImplDX12_Shutdown();
|
||||
}
|
||||
|
||||
bool D3D12HostDisplay::UpdateImGuiFontTexture()
|
||||
{
|
||||
return ImGui_ImplDX12_CreateFontsTexture();
|
||||
}
|
||||
|
||||
bool D3D12HostDisplay::Render()
|
||||
{
|
||||
if (ShouldSkipDisplayingFrame())
|
||||
{
|
||||
if (ImGui::GetCurrentContext())
|
||||
ImGui::Render();
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
static constexpr std::array<float, 4> clear_color = {};
|
||||
D3D12::Texture& swap_chain_buf = m_swap_chain_buffers[m_current_swap_chain_buffer];
|
||||
m_current_swap_chain_buffer = ((m_current_swap_chain_buffer + 1) % static_cast<u32>(m_swap_chain_buffers.size()));
|
||||
|
||||
ID3D12GraphicsCommandList* cmdlist = g_d3d12_context->GetCommandList();
|
||||
swap_chain_buf.TransitionToState(D3D12_RESOURCE_STATE_RENDER_TARGET);
|
||||
cmdlist->ClearRenderTargetView(swap_chain_buf.GetRTVOrDSVDescriptor(), clear_color.data(), 0, nullptr);
|
||||
cmdlist->OMSetRenderTargets(1, &swap_chain_buf.GetRTVOrDSVDescriptor().cpu_handle, FALSE, nullptr);
|
||||
cmdlist->SetGraphicsRootSignature(m_display_root_signature.Get());
|
||||
|
||||
RenderDisplay(cmdlist);
|
||||
|
||||
if (ImGui::GetCurrentContext())
|
||||
RenderImGui(cmdlist);
|
||||
|
||||
RenderSoftwareCursor(cmdlist);
|
||||
|
||||
swap_chain_buf.TransitionToState(D3D12_RESOURCE_STATE_PRESENT);
|
||||
g_d3d12_context->ExecuteCommandList(false);
|
||||
|
||||
if (!m_vsync && m_using_allow_tearing)
|
||||
m_swap_chain->Present(0, DXGI_PRESENT_ALLOW_TEARING);
|
||||
else
|
||||
m_swap_chain->Present(BoolToUInt32(m_vsync), 0);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool D3D12HostDisplay::RenderScreenshot(u32 width, u32 height, std::vector<u32>* out_pixels, u32* out_stride,
|
||||
HostDisplayPixelFormat* out_format)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
void D3D12HostDisplay::RenderImGui(ID3D12GraphicsCommandList* cmdlist)
|
||||
{
|
||||
ImGui::Render();
|
||||
ImGui_ImplDX12_RenderDrawData(ImGui::GetDrawData(), cmdlist);
|
||||
}
|
||||
|
||||
void D3D12HostDisplay::RenderDisplay(ID3D12GraphicsCommandList* cmdlist)
|
||||
{
|
||||
if (!HasDisplayTexture())
|
||||
return;
|
||||
|
||||
const auto [left, top, width, height] = CalculateDrawRect(GetWindowWidth(), GetWindowHeight(), m_display_top_margin);
|
||||
|
||||
// if (!m_post_processing_chain.IsEmpty())
|
||||
// {
|
||||
// ApplyPostProcessingChain(m_swap_chain_rtv.Get(), left, top, width, height, m_display_texture_handle,
|
||||
// m_display_texture_width, m_display_texture_height, m_display_texture_view_x,
|
||||
// m_display_texture_view_y, m_display_texture_view_width,
|
||||
// m_display_texture_view_height);
|
||||
// return;
|
||||
// }
|
||||
|
||||
RenderDisplay(cmdlist, left, top, width, height, m_display_texture_handle, m_display_texture_width,
|
||||
m_display_texture_height, m_display_texture_view_x, m_display_texture_view_y,
|
||||
m_display_texture_view_width, m_display_texture_view_height, m_display_linear_filtering);
|
||||
}
|
||||
|
||||
void D3D12HostDisplay::RenderDisplay(ID3D12GraphicsCommandList* cmdlist, s32 left, s32 top, s32 width, s32 height,
|
||||
void* texture_handle, u32 texture_width, s32 texture_height, s32 texture_view_x,
|
||||
s32 texture_view_y, s32 texture_view_width, s32 texture_view_height,
|
||||
bool linear_filter)
|
||||
{
|
||||
const float uniforms[4] = {static_cast<float>(texture_view_x) / static_cast<float>(texture_width),
|
||||
static_cast<float>(texture_view_y) / static_cast<float>(texture_height),
|
||||
(static_cast<float>(texture_view_width) - 0.5f) / static_cast<float>(texture_width),
|
||||
(static_cast<float>(texture_view_height) - 0.5f) / static_cast<float>(texture_height)};
|
||||
if (!m_display_uniform_buffer.ReserveMemory(sizeof(uniforms), D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT))
|
||||
Panic("Failed to reserve UBO space");
|
||||
|
||||
const u32 ubo_offset = m_display_uniform_buffer.GetCurrentOffset();
|
||||
std::memcpy(m_display_uniform_buffer.GetCurrentHostPointer(), uniforms, sizeof(uniforms));
|
||||
m_display_uniform_buffer.CommitMemory(sizeof(uniforms));
|
||||
|
||||
cmdlist->SetPipelineState(m_display_pipeline.Get());
|
||||
cmdlist->SetGraphicsRootConstantBufferView(0, m_display_uniform_buffer.GetGPUPointer() + ubo_offset);
|
||||
cmdlist->SetGraphicsRootDescriptorTable(1, reinterpret_cast<D3D12::Texture*>(texture_handle)->GetSRVDescriptor());
|
||||
cmdlist->SetGraphicsRootDescriptorTable(2, linear_filter ? m_linear_sampler : m_point_sampler);
|
||||
|
||||
D3D12::SetViewportAndScissor(cmdlist, left, top, width, height);
|
||||
|
||||
cmdlist->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
|
||||
cmdlist->DrawInstanced(3, 1, 0, 0);
|
||||
}
|
||||
|
||||
void D3D12HostDisplay::RenderSoftwareCursor(ID3D12GraphicsCommandList* cmdlist)
|
||||
{
|
||||
if (!HasSoftwareCursor())
|
||||
return;
|
||||
|
||||
const auto [left, top, width, height] = CalculateSoftwareCursorDrawRect();
|
||||
RenderSoftwareCursor(cmdlist, left, top, width, height, m_cursor_texture.get());
|
||||
}
|
||||
|
||||
void D3D12HostDisplay::RenderSoftwareCursor(ID3D12GraphicsCommandList* cmdlist, s32 left, s32 top, s32 width,
|
||||
s32 height, HostDisplayTexture* texture_handle)
|
||||
{
|
||||
const float uniforms[4] = {0.0f, 0.0f, 1.0f, 1.0f};
|
||||
if (!m_display_uniform_buffer.ReserveMemory(sizeof(uniforms), D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT))
|
||||
Panic("Failed to reserve UBO space");
|
||||
|
||||
const u32 ubo_offset = m_display_uniform_buffer.GetCurrentOffset();
|
||||
std::memcpy(m_display_uniform_buffer.GetCurrentHostPointer(), uniforms, sizeof(uniforms));
|
||||
m_display_uniform_buffer.CommitMemory(sizeof(uniforms));
|
||||
|
||||
cmdlist->SetPipelineState(m_display_pipeline.Get());
|
||||
cmdlist->SetGraphicsRootConstantBufferView(0, m_display_uniform_buffer.GetGPUPointer() + ubo_offset);
|
||||
cmdlist->SetGraphicsRootDescriptorTable(
|
||||
1, static_cast<D3D12HostDisplayTexture*>(texture_handle)->GetTexture().GetRTVOrDSVDescriptor());
|
||||
cmdlist->SetGraphicsRootDescriptorTable(2, m_linear_sampler);
|
||||
|
||||
D3D12::SetViewportAndScissor(cmdlist, left, top, width, height);
|
||||
|
||||
cmdlist->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
|
||||
cmdlist->DrawInstanced(3, 1, 0, 0);
|
||||
}
|
||||
|
||||
HostDisplay::AdapterAndModeList D3D12HostDisplay::StaticGetAdapterAndModeList()
|
||||
{
|
||||
ComPtr<IDXGIFactory> dxgi_factory;
|
||||
#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
|
||||
HRESULT hr = CreateDXGIFactory(IID_PPV_ARGS(dxgi_factory.GetAddressOf()));
|
||||
#else
|
||||
HRESULT hr = CreateDXGIFactory2(0, IID_PPV_ARGS(dxgi_factory.GetAddressOf()));
|
||||
#endif
|
||||
if (FAILED(hr))
|
||||
return {};
|
||||
|
||||
return GetAdapterAndModeList(dxgi_factory.Get());
|
||||
}
|
||||
|
||||
HostDisplay::AdapterAndModeList D3D12HostDisplay::GetAdapterAndModeList(IDXGIFactory* dxgi_factory)
|
||||
{
|
||||
AdapterAndModeList adapter_info;
|
||||
ComPtr<IDXGIAdapter> current_adapter;
|
||||
while (SUCCEEDED(dxgi_factory->EnumAdapters(static_cast<UINT>(adapter_info.adapter_names.size()),
|
||||
current_adapter.ReleaseAndGetAddressOf())))
|
||||
{
|
||||
DXGI_ADAPTER_DESC adapter_desc;
|
||||
std::string adapter_name;
|
||||
if (SUCCEEDED(current_adapter->GetDesc(&adapter_desc)))
|
||||
{
|
||||
char adapter_name_buffer[128];
|
||||
const int name_length = WideCharToMultiByte(CP_UTF8, 0, adapter_desc.Description,
|
||||
static_cast<int>(std::wcslen(adapter_desc.Description)),
|
||||
adapter_name_buffer, countof(adapter_name_buffer), 0, nullptr);
|
||||
if (name_length >= 0)
|
||||
adapter_name.assign(adapter_name_buffer, static_cast<size_t>(name_length));
|
||||
else
|
||||
adapter_name.assign("(Unknown)");
|
||||
}
|
||||
else
|
||||
{
|
||||
adapter_name.assign("(Unknown)");
|
||||
}
|
||||
|
||||
if (adapter_info.fullscreen_modes.empty())
|
||||
{
|
||||
ComPtr<IDXGIOutput> output;
|
||||
if (SUCCEEDED(current_adapter->EnumOutputs(0, &output)))
|
||||
{
|
||||
UINT num_modes = 0;
|
||||
if (SUCCEEDED(output->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, 0, &num_modes, nullptr)))
|
||||
{
|
||||
std::vector<DXGI_MODE_DESC> modes(num_modes);
|
||||
if (SUCCEEDED(output->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, 0, &num_modes, modes.data())))
|
||||
{
|
||||
for (const DXGI_MODE_DESC& mode : modes)
|
||||
{
|
||||
adapter_info.fullscreen_modes.push_back(StringUtil::StdStringFromFormat(
|
||||
"%u x %u @ %f hz", mode.Width, mode.Height,
|
||||
static_cast<float>(mode.RefreshRate.Numerator) / static_cast<float>(mode.RefreshRate.Denominator)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// handle duplicate adapter names
|
||||
if (std::any_of(adapter_info.adapter_names.begin(), adapter_info.adapter_names.end(),
|
||||
[&adapter_name](const std::string& other) { return (adapter_name == other); }))
|
||||
{
|
||||
std::string original_adapter_name = std::move(adapter_name);
|
||||
|
||||
u32 current_extra = 2;
|
||||
do
|
||||
{
|
||||
adapter_name = StringUtil::StdStringFromFormat("%s (%u)", original_adapter_name.c_str(), current_extra);
|
||||
current_extra++;
|
||||
} while (std::any_of(adapter_info.adapter_names.begin(), adapter_info.adapter_names.end(),
|
||||
[&adapter_name](const std::string& other) { return (adapter_name == other); }));
|
||||
}
|
||||
|
||||
adapter_info.adapter_names.push_back(std::move(adapter_name));
|
||||
}
|
||||
|
||||
return adapter_info;
|
||||
}
|
||||
|
||||
bool D3D12HostDisplay::SetPostProcessingChain(const std::string_view& config)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace FrontendCommon
|
127
src/frontend-common/d3d12_host_display.h
Normal file
127
src/frontend-common/d3d12_host_display.h
Normal file
@ -0,0 +1,127 @@
|
||||
#pragma once
|
||||
#pragma once
|
||||
#include "common/d3d12/descriptor_heap_manager.h"
|
||||
#include "common/d3d12/staging_texture.h"
|
||||
#include "common/d3d12/stream_buffer.h"
|
||||
#include "common/d3d12/texture.h"
|
||||
#include "common/window_info.h"
|
||||
#include "common/windows_headers.h"
|
||||
#include "core/host_display.h"
|
||||
#include <d3d12.h>
|
||||
#include <dxgi.h>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
#include <wrl/client.h>
|
||||
|
||||
namespace FrontendCommon {
|
||||
|
||||
class D3D12HostDisplay : public HostDisplay
|
||||
{
|
||||
public:
|
||||
template<typename T>
|
||||
using ComPtr = Microsoft::WRL::ComPtr<T>;
|
||||
|
||||
D3D12HostDisplay();
|
||||
~D3D12HostDisplay();
|
||||
|
||||
virtual RenderAPI GetRenderAPI() const override;
|
||||
virtual void* GetRenderDevice() const override;
|
||||
virtual void* GetRenderContext() const override;
|
||||
|
||||
virtual bool HasRenderDevice() const override;
|
||||
virtual bool HasRenderSurface() const override;
|
||||
|
||||
virtual bool CreateRenderDevice(const WindowInfo& wi, std::string_view adapter_name, bool debug_device,
|
||||
bool threaded_presentation) override;
|
||||
virtual bool InitializeRenderDevice(std::string_view shader_cache_directory, bool debug_device,
|
||||
bool threaded_presentation) override;
|
||||
virtual void DestroyRenderDevice() override;
|
||||
|
||||
virtual bool MakeRenderContextCurrent() override;
|
||||
virtual bool DoneRenderContextCurrent() override;
|
||||
|
||||
virtual bool ChangeRenderWindow(const WindowInfo& new_wi) override;
|
||||
virtual void ResizeRenderWindow(s32 new_window_width, s32 new_window_height) override;
|
||||
virtual bool SupportsFullscreen() const override;
|
||||
virtual bool IsFullscreen() override;
|
||||
virtual bool SetFullscreen(bool fullscreen, u32 width, u32 height, float refresh_rate) override;
|
||||
virtual AdapterAndModeList GetAdapterAndModeList() override;
|
||||
virtual void DestroyRenderSurface() override;
|
||||
|
||||
virtual bool SetPostProcessingChain(const std::string_view& config) override;
|
||||
|
||||
std::unique_ptr<HostDisplayTexture> CreateTexture(u32 width, u32 height, u32 layers, u32 levels, u32 samples,
|
||||
HostDisplayPixelFormat format, const void* data, u32 data_stride,
|
||||
bool dynamic = false) override;
|
||||
void UpdateTexture(HostDisplayTexture* texture, u32 x, u32 y, u32 width, u32 height, const void* texture_data,
|
||||
u32 texture_data_stride) override;
|
||||
bool DownloadTexture(const void* texture_handle, HostDisplayPixelFormat texture_format, u32 x, u32 y, u32 width,
|
||||
u32 height, void* out_data, u32 out_data_stride) override;
|
||||
bool SupportsDisplayPixelFormat(HostDisplayPixelFormat format) const override;
|
||||
bool BeginSetDisplayPixels(HostDisplayPixelFormat format, u32 width, u32 height, void** out_buffer,
|
||||
u32* out_pitch) override;
|
||||
void EndSetDisplayPixels() override;
|
||||
|
||||
bool GetHostRefreshRate(float* refresh_rate) override;
|
||||
|
||||
virtual void SetVSync(bool enabled) override;
|
||||
|
||||
virtual bool Render() override;
|
||||
virtual bool RenderScreenshot(u32 width, u32 height, std::vector<u32>* out_pixels, u32* out_stride,
|
||||
HostDisplayPixelFormat* out_format) override;
|
||||
|
||||
static AdapterAndModeList StaticGetAdapterAndModeList();
|
||||
|
||||
protected:
|
||||
enum : u32
|
||||
{
|
||||
DISPLAY_UNIFORM_BUFFER_SIZE = 65536,
|
||||
TEXTURE_STREAMING_BUFFER_SIZE = 4 * 1024 * 1024
|
||||
};
|
||||
|
||||
static AdapterAndModeList GetAdapterAndModeList(IDXGIFactory* dxgi_factory);
|
||||
|
||||
virtual bool CreateResources() override;
|
||||
virtual void DestroyResources() override;
|
||||
|
||||
virtual bool CreateImGuiContext();
|
||||
virtual void DestroyImGuiContext();
|
||||
virtual bool UpdateImGuiFontTexture() override;
|
||||
|
||||
bool CreateSwapChain(const DXGI_MODE_DESC* fullscreen_mode);
|
||||
bool CreateSwapChainRTV();
|
||||
void DestroySwapChainRTVs();
|
||||
|
||||
void RenderDisplay(ID3D12GraphicsCommandList* cmdlist);
|
||||
void RenderSoftwareCursor(ID3D12GraphicsCommandList* cmdlist);
|
||||
void RenderImGui(ID3D12GraphicsCommandList* cmdlist);
|
||||
|
||||
void RenderDisplay(ID3D12GraphicsCommandList* cmdlist, s32 left, s32 top, s32 width, s32 height, void* texture_handle,
|
||||
u32 texture_width, s32 texture_height, s32 texture_view_x, s32 texture_view_y,
|
||||
s32 texture_view_width, s32 texture_view_height, bool linear_filter);
|
||||
void RenderSoftwareCursor(ID3D12GraphicsCommandList* cmdlist, s32 left, s32 top, s32 width, s32 height,
|
||||
HostDisplayTexture* texture_handle);
|
||||
|
||||
ComPtr<IDXGIFactory> m_dxgi_factory;
|
||||
ComPtr<IDXGISwapChain> m_swap_chain;
|
||||
std::vector<D3D12::Texture> m_swap_chain_buffers;
|
||||
u32 m_current_swap_chain_buffer = 0;
|
||||
|
||||
ComPtr<ID3D12RootSignature> m_display_root_signature;
|
||||
ComPtr<ID3D12PipelineState> m_display_pipeline;
|
||||
ComPtr<ID3D12PipelineState> m_software_cursor_pipeline;
|
||||
D3D12::DescriptorHandle m_point_sampler;
|
||||
D3D12::DescriptorHandle m_linear_sampler;
|
||||
|
||||
D3D12::Texture m_display_pixels_texture;
|
||||
D3D12::StreamBuffer m_display_uniform_buffer;
|
||||
D3D12::StagingTexture m_readback_staging_texture;
|
||||
|
||||
bool m_allow_tearing_supported = false;
|
||||
bool m_using_allow_tearing = false;
|
||||
bool m_vsync = true;
|
||||
};
|
||||
|
||||
} // namespace FrontendCommon
|
@ -10,6 +10,7 @@
|
||||
<ClCompile Include="fullscreen_ui.cpp" />
|
||||
<ClCompile Include="fullscreen_ui_progress_callback.cpp" />
|
||||
<ClCompile Include="game_database.cpp" />
|
||||
<ClCompile Include="d3d12_host_display.cpp" />
|
||||
<ClCompile Include="game_list.cpp" />
|
||||
<ClCompile Include="game_settings.cpp" />
|
||||
<ClCompile Include="http_downloader.cpp" />
|
||||
@ -17,6 +18,7 @@
|
||||
<ClCompile Include="icon.cpp" />
|
||||
<ClCompile Include="imgui_fullscreen.cpp" />
|
||||
<ClCompile Include="imgui_impl_dx11.cpp" />
|
||||
<ClCompile Include="imgui_impl_dx12.cpp" />
|
||||
<ClCompile Include="imgui_impl_opengl3.cpp" />
|
||||
<ClCompile Include="imgui_impl_vulkan.cpp" />
|
||||
<ClCompile Include="imgui_styles.cpp" />
|
||||
@ -45,6 +47,7 @@
|
||||
<ClInclude Include="fullscreen_ui.h" />
|
||||
<ClInclude Include="fullscreen_ui_progress_callback.h" />
|
||||
<ClInclude Include="game_database.h" />
|
||||
<ClInclude Include="d3d12_host_display.h" />
|
||||
<ClInclude Include="game_list.h" />
|
||||
<ClInclude Include="game_settings.h" />
|
||||
<ClInclude Include="http_downloader.h" />
|
||||
@ -52,6 +55,7 @@
|
||||
<ClInclude Include="icon.h" />
|
||||
<ClInclude Include="imgui_fullscreen.h" />
|
||||
<ClInclude Include="imgui_impl_dx11.h" />
|
||||
<ClInclude Include="imgui_impl_dx12.h" />
|
||||
<ClInclude Include="imgui_impl_opengl3.h" />
|
||||
<ClInclude Include="imgui_impl_vulkan.h" />
|
||||
<ClInclude Include="imgui_styles.h" />
|
||||
|
@ -34,6 +34,8 @@
|
||||
<ClCompile Include="game_database.cpp" />
|
||||
<ClCompile Include="inhibit_screensaver.cpp" />
|
||||
<ClCompile Include="xaudio2_audio_stream.cpp" />
|
||||
<ClCompile Include="d3d12_host_display.cpp" />
|
||||
<ClCompile Include="imgui_impl_dx12.cpp" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="icon.h" />
|
||||
@ -69,6 +71,8 @@
|
||||
<ClInclude Include="game_database.h" />
|
||||
<ClInclude Include="inhibit_screensaver.h" />
|
||||
<ClInclude Include="xaudio2_audio_stream.h" />
|
||||
<ClInclude Include="d3d12_host_display.h" />
|
||||
<ClInclude Include="imgui_impl_dx12.h" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="font_roboto_regular.inl" />
|
||||
|
533
src/frontend-common/imgui_impl_dx12.cpp
Normal file
533
src/frontend-common/imgui_impl_dx12.cpp
Normal file
@ -0,0 +1,533 @@
|
||||
// dear imgui: Renderer Backend for DirectX12
|
||||
// This needs to be used along with a Platform Backend (e.g. Win32)
|
||||
|
||||
// Implemented features:
|
||||
// [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as ImTextureID. Read the FAQ about ImTextureID!
|
||||
// [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices.
|
||||
|
||||
// Important: to compile on 32-bit systems, this backend requires code to be compiled with '#define ImTextureID ImU64'.
|
||||
// This is because we need ImTextureID to carry a 64-bit value and by default ImTextureID is defined as void*.
|
||||
// This define is set in the example .vcxproj file and need to be replicated in your app or by adding it to your imconfig.h file.
|
||||
|
||||
// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
|
||||
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
|
||||
// Read online: https://github.com/ocornut/imgui/tree/master/docs
|
||||
|
||||
// CHANGELOG
|
||||
// (minor and older changes stripped away, please see git history for details)
|
||||
// 2021-01-11: DirectX12: Improve Windows 7 compatibility (for D3D12On7) by loading d3d12.dll dynamically.
|
||||
// 2020-09-16: DirectX12: Avoid rendering calls with zero-sized scissor rectangle since it generates a validation layer warning.
|
||||
// 2020-09-08: DirectX12: Clarified support for building on 32-bit systems by redefining ImTextureID.
|
||||
// 2019-10-18: DirectX12: *BREAKING CHANGE* Added extra ID3D12DescriptorHeap parameter to ImGui_ImplDX12_Init() function.
|
||||
// 2019-05-29: DirectX12: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
|
||||
// 2019-04-30: DirectX12: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
|
||||
// 2019-03-29: Misc: Various minor tidying up.
|
||||
// 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile().
|
||||
// 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
|
||||
// 2018-06-12: DirectX12: Moved the ID3D12GraphicsCommandList* parameter from NewFrame() to RenderDrawData().
|
||||
// 2018-06-08: Misc: Extracted imgui_impl_dx12.cpp/.h away from the old combined DX12+Win32 example.
|
||||
// 2018-06-08: DirectX12: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle (to ease support for future multi-viewport).
|
||||
// 2018-02-22: Merged into master with all Win32 code synchronized to other examples.
|
||||
|
||||
#include "imgui.h"
|
||||
#include "imgui_impl_dx12.h"
|
||||
|
||||
// DirectX
|
||||
#include <d3d12.h>
|
||||
#include <dxgi1_4.h>
|
||||
#include <d3dcompiler.h>
|
||||
#ifdef _MSC_VER
|
||||
#pragma comment(lib, "d3dcompiler") // Automatically link with d3dcompiler.lib as we are using D3DCompile() below.
|
||||
#endif
|
||||
|
||||
#include "common/d3d12/texture.h"
|
||||
#include "common/d3d12/context.h"
|
||||
|
||||
// DirectX data
|
||||
static ID3D12Device* g_pd3dDevice = NULL;
|
||||
static ID3D12RootSignature* g_pRootSignature = NULL;
|
||||
static ID3D12PipelineState* g_pPipelineState = NULL;
|
||||
static DXGI_FORMAT g_RTVFormat = DXGI_FORMAT_UNKNOWN;
|
||||
static D3D12::Texture g_FontTexture;
|
||||
|
||||
struct FrameResources
|
||||
{
|
||||
ID3D12Resource* IndexBuffer;
|
||||
ID3D12Resource* VertexBuffer;
|
||||
int IndexBufferSize;
|
||||
int VertexBufferSize;
|
||||
};
|
||||
static FrameResources* g_pFrameResources = NULL;
|
||||
static UINT g_numFramesInFlight = 0;
|
||||
static UINT g_frameIndex = UINT_MAX;
|
||||
|
||||
template<typename T>
|
||||
static void SafeRelease(T*& res)
|
||||
{
|
||||
if (res)
|
||||
res->Release();
|
||||
res = NULL;
|
||||
}
|
||||
|
||||
struct VERTEX_CONSTANT_BUFFER
|
||||
{
|
||||
float mvp[4][4];
|
||||
};
|
||||
|
||||
static void ImGui_ImplDX12_SetupRenderState(ImDrawData* draw_data, ID3D12GraphicsCommandList* ctx, FrameResources* fr)
|
||||
{
|
||||
// Setup orthographic projection matrix into our constant buffer
|
||||
// Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right).
|
||||
VERTEX_CONSTANT_BUFFER vertex_constant_buffer;
|
||||
{
|
||||
float L = draw_data->DisplayPos.x;
|
||||
float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
|
||||
float T = draw_data->DisplayPos.y;
|
||||
float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
|
||||
float mvp[4][4] =
|
||||
{
|
||||
{ 2.0f / (R - L), 0.0f, 0.0f, 0.0f },
|
||||
{ 0.0f, 2.0f / (T - B), 0.0f, 0.0f },
|
||||
{ 0.0f, 0.0f, 0.5f, 0.0f },
|
||||
{ (R + L) / (L - R), (T + B) / (B - T), 0.5f, 1.0f },
|
||||
};
|
||||
memcpy(&vertex_constant_buffer.mvp, mvp, sizeof(mvp));
|
||||
}
|
||||
|
||||
// Setup viewport
|
||||
D3D12_VIEWPORT vp;
|
||||
memset(&vp, 0, sizeof(D3D12_VIEWPORT));
|
||||
vp.Width = draw_data->DisplaySize.x;
|
||||
vp.Height = draw_data->DisplaySize.y;
|
||||
vp.MinDepth = 0.0f;
|
||||
vp.MaxDepth = 1.0f;
|
||||
vp.TopLeftX = vp.TopLeftY = 0.0f;
|
||||
ctx->RSSetViewports(1, &vp);
|
||||
|
||||
// Bind shader and vertex buffers
|
||||
unsigned int stride = sizeof(ImDrawVert);
|
||||
unsigned int offset = 0;
|
||||
D3D12_VERTEX_BUFFER_VIEW vbv;
|
||||
memset(&vbv, 0, sizeof(D3D12_VERTEX_BUFFER_VIEW));
|
||||
vbv.BufferLocation = fr->VertexBuffer->GetGPUVirtualAddress() + offset;
|
||||
vbv.SizeInBytes = fr->VertexBufferSize * stride;
|
||||
vbv.StrideInBytes = stride;
|
||||
ctx->IASetVertexBuffers(0, 1, &vbv);
|
||||
D3D12_INDEX_BUFFER_VIEW ibv;
|
||||
memset(&ibv, 0, sizeof(D3D12_INDEX_BUFFER_VIEW));
|
||||
ibv.BufferLocation = fr->IndexBuffer->GetGPUVirtualAddress();
|
||||
ibv.SizeInBytes = fr->IndexBufferSize * sizeof(ImDrawIdx);
|
||||
ibv.Format = sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT;
|
||||
ctx->IASetIndexBuffer(&ibv);
|
||||
ctx->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
|
||||
ctx->SetPipelineState(g_pPipelineState);
|
||||
ctx->SetGraphicsRootSignature(g_pRootSignature);
|
||||
ctx->SetGraphicsRoot32BitConstants(0, 16, &vertex_constant_buffer, 0);
|
||||
|
||||
// Setup blend factor
|
||||
const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
|
||||
ctx->OMSetBlendFactor(blend_factor);
|
||||
}
|
||||
|
||||
// Render function
|
||||
void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandList* ctx)
|
||||
{
|
||||
// Avoid rendering when minimized
|
||||
if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
|
||||
return;
|
||||
|
||||
// FIXME: I'm assuming that this only gets called once per frame!
|
||||
// If not, we can't just re-allocate the IB or VB, we'll have to do a proper allocator.
|
||||
g_frameIndex = g_frameIndex + 1;
|
||||
FrameResources* fr = &g_pFrameResources[g_frameIndex % g_numFramesInFlight];
|
||||
|
||||
// Create and grow vertex/index buffers if needed
|
||||
if (fr->VertexBuffer == NULL || fr->VertexBufferSize < draw_data->TotalVtxCount)
|
||||
{
|
||||
SafeRelease(fr->VertexBuffer);
|
||||
fr->VertexBufferSize = draw_data->TotalVtxCount + 5000;
|
||||
D3D12_HEAP_PROPERTIES props;
|
||||
memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES));
|
||||
props.Type = D3D12_HEAP_TYPE_UPLOAD;
|
||||
props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
|
||||
props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
|
||||
D3D12_RESOURCE_DESC desc;
|
||||
memset(&desc, 0, sizeof(D3D12_RESOURCE_DESC));
|
||||
desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
|
||||
desc.Width = fr->VertexBufferSize * sizeof(ImDrawVert);
|
||||
desc.Height = 1;
|
||||
desc.DepthOrArraySize = 1;
|
||||
desc.MipLevels = 1;
|
||||
desc.Format = DXGI_FORMAT_UNKNOWN;
|
||||
desc.SampleDesc.Count = 1;
|
||||
desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
|
||||
desc.Flags = D3D12_RESOURCE_FLAG_NONE;
|
||||
if (g_pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, NULL, IID_PPV_ARGS(&fr->VertexBuffer)) < 0)
|
||||
return;
|
||||
}
|
||||
if (fr->IndexBuffer == NULL || fr->IndexBufferSize < draw_data->TotalIdxCount)
|
||||
{
|
||||
SafeRelease(fr->IndexBuffer);
|
||||
fr->IndexBufferSize = draw_data->TotalIdxCount + 10000;
|
||||
D3D12_HEAP_PROPERTIES props;
|
||||
memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES));
|
||||
props.Type = D3D12_HEAP_TYPE_UPLOAD;
|
||||
props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
|
||||
props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
|
||||
D3D12_RESOURCE_DESC desc;
|
||||
memset(&desc, 0, sizeof(D3D12_RESOURCE_DESC));
|
||||
desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
|
||||
desc.Width = fr->IndexBufferSize * sizeof(ImDrawIdx);
|
||||
desc.Height = 1;
|
||||
desc.DepthOrArraySize = 1;
|
||||
desc.MipLevels = 1;
|
||||
desc.Format = DXGI_FORMAT_UNKNOWN;
|
||||
desc.SampleDesc.Count = 1;
|
||||
desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
|
||||
desc.Flags = D3D12_RESOURCE_FLAG_NONE;
|
||||
if (g_pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, NULL, IID_PPV_ARGS(&fr->IndexBuffer)) < 0)
|
||||
return;
|
||||
}
|
||||
|
||||
// Upload vertex/index data into a single contiguous GPU buffer
|
||||
void* vtx_resource, * idx_resource;
|
||||
D3D12_RANGE range;
|
||||
memset(&range, 0, sizeof(D3D12_RANGE));
|
||||
if (fr->VertexBuffer->Map(0, &range, &vtx_resource) != S_OK)
|
||||
return;
|
||||
if (fr->IndexBuffer->Map(0, &range, &idx_resource) != S_OK)
|
||||
return;
|
||||
ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource;
|
||||
ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource;
|
||||
for (int n = 0; n < draw_data->CmdListsCount; n++)
|
||||
{
|
||||
const ImDrawList* cmd_list = draw_data->CmdLists[n];
|
||||
memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert));
|
||||
memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
|
||||
vtx_dst += cmd_list->VtxBuffer.Size;
|
||||
idx_dst += cmd_list->IdxBuffer.Size;
|
||||
}
|
||||
fr->VertexBuffer->Unmap(0, &range);
|
||||
fr->IndexBuffer->Unmap(0, &range);
|
||||
|
||||
// Setup desired DX state
|
||||
ImGui_ImplDX12_SetupRenderState(draw_data, ctx, fr);
|
||||
|
||||
// Render command lists
|
||||
// (Because we merged all buffers into a single one, we maintain our own offset into them)
|
||||
int global_vtx_offset = 0;
|
||||
int global_idx_offset = 0;
|
||||
ImVec2 clip_off = draw_data->DisplayPos;
|
||||
for (int n = 0; n < draw_data->CmdListsCount; n++)
|
||||
{
|
||||
const ImDrawList* cmd_list = draw_data->CmdLists[n];
|
||||
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
|
||||
{
|
||||
const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
|
||||
if (pcmd->UserCallback != NULL)
|
||||
{
|
||||
// User callback, registered via ImDrawList::AddCallback()
|
||||
// (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
|
||||
if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
|
||||
ImGui_ImplDX12_SetupRenderState(draw_data, ctx, fr);
|
||||
else
|
||||
pcmd->UserCallback(cmd_list, pcmd);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Apply Scissor, Bind texture, Draw
|
||||
const D3D12_RECT r = { (LONG)(pcmd->ClipRect.x - clip_off.x), (LONG)(pcmd->ClipRect.y - clip_off.y), (LONG)(pcmd->ClipRect.z - clip_off.x), (LONG)(pcmd->ClipRect.w - clip_off.y) };
|
||||
if (r.right > r.left && r.bottom > r.top)
|
||||
{
|
||||
ctx->SetGraphicsRootDescriptorTable(1, reinterpret_cast<D3D12::Texture*>(pcmd->TextureId)->GetSRVDescriptor());
|
||||
ctx->RSSetScissorRects(1, &r);
|
||||
ctx->DrawIndexedInstanced(pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
global_idx_offset += cmd_list->IdxBuffer.Size;
|
||||
global_vtx_offset += cmd_list->VtxBuffer.Size;
|
||||
}
|
||||
}
|
||||
|
||||
bool ImGui_ImplDX12_CreateFontsTexture()
|
||||
{
|
||||
// Build texture atlas
|
||||
ImGuiIO & io = ImGui::GetIO();
|
||||
unsigned char* pixels;
|
||||
int width, height;
|
||||
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
|
||||
|
||||
// Upload texture to graphics system
|
||||
D3D12::Texture texture;
|
||||
if (!texture.Create(width, height, 1, DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE) ||
|
||||
!texture.LoadData(0, 0, width, height, pixels, width * sizeof(u32)))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
g_FontTexture = std::move(texture);
|
||||
|
||||
// Store our identifier
|
||||
io.Fonts->TexID = reinterpret_cast<ImTextureID>(&g_FontTexture);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ImGui_ImplDX12_CreateDeviceObjects()
|
||||
{
|
||||
if (!g_pd3dDevice)
|
||||
return false;
|
||||
if (g_pPipelineState)
|
||||
ImGui_ImplDX12_InvalidateDeviceObjects();
|
||||
|
||||
// Create the root signature
|
||||
{
|
||||
D3D12_DESCRIPTOR_RANGE descRange = {};
|
||||
descRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
|
||||
descRange.NumDescriptors = 1;
|
||||
descRange.BaseShaderRegister = 0;
|
||||
descRange.RegisterSpace = 0;
|
||||
descRange.OffsetInDescriptorsFromTableStart = 0;
|
||||
|
||||
D3D12_ROOT_PARAMETER param[2] = {};
|
||||
|
||||
param[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
|
||||
param[0].Constants.ShaderRegister = 0;
|
||||
param[0].Constants.RegisterSpace = 0;
|
||||
param[0].Constants.Num32BitValues = 16;
|
||||
param[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;
|
||||
|
||||
param[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
|
||||
param[1].DescriptorTable.NumDescriptorRanges = 1;
|
||||
param[1].DescriptorTable.pDescriptorRanges = &descRange;
|
||||
param[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
|
||||
|
||||
D3D12_STATIC_SAMPLER_DESC staticSampler = {};
|
||||
staticSampler.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR;
|
||||
staticSampler.AddressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
|
||||
staticSampler.AddressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
|
||||
staticSampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
|
||||
staticSampler.MipLODBias = 0.f;
|
||||
staticSampler.MaxAnisotropy = 0;
|
||||
staticSampler.ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS;
|
||||
staticSampler.BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK;
|
||||
staticSampler.MinLOD = 0.f;
|
||||
staticSampler.MaxLOD = 0.f;
|
||||
staticSampler.ShaderRegister = 0;
|
||||
staticSampler.RegisterSpace = 0;
|
||||
staticSampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
|
||||
|
||||
D3D12_ROOT_SIGNATURE_DESC desc = {};
|
||||
desc.NumParameters = _countof(param);
|
||||
desc.pParameters = param;
|
||||
desc.NumStaticSamplers = 1;
|
||||
desc.pStaticSamplers = &staticSampler;
|
||||
desc.Flags =
|
||||
D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT |
|
||||
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;
|
||||
|
||||
auto blob = g_d3d12_context->SerializeRootSignature(&desc);
|
||||
if (!blob)
|
||||
return false;
|
||||
|
||||
g_pd3dDevice->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&g_pRootSignature));
|
||||
}
|
||||
|
||||
// By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A)
|
||||
// If you would like to use this DX12 sample code but remove this dependency you can:
|
||||
// 1) compile once, save the compiled shader blobs into a file or source code and pass them to CreateVertexShader()/CreatePixelShader() [preferred solution]
|
||||
// 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL.
|
||||
// See https://github.com/ocornut/imgui/pull/638 for sources and details.
|
||||
|
||||
D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc;
|
||||
memset(&psoDesc, 0, sizeof(D3D12_GRAPHICS_PIPELINE_STATE_DESC));
|
||||
psoDesc.NodeMask = 1;
|
||||
psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
|
||||
psoDesc.pRootSignature = g_pRootSignature;
|
||||
psoDesc.SampleMask = UINT_MAX;
|
||||
psoDesc.NumRenderTargets = 1;
|
||||
psoDesc.RTVFormats[0] = g_RTVFormat;
|
||||
psoDesc.SampleDesc.Count = 1;
|
||||
psoDesc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE;
|
||||
|
||||
ID3DBlob* vertexShaderBlob;
|
||||
ID3DBlob* pixelShaderBlob;
|
||||
|
||||
// Create the vertex shader
|
||||
{
|
||||
static const char* vertexShader =
|
||||
"cbuffer vertexBuffer : register(b0) \
|
||||
{\
|
||||
float4x4 ProjectionMatrix; \
|
||||
};\
|
||||
struct VS_INPUT\
|
||||
{\
|
||||
float2 pos : POSITION;\
|
||||
float4 col : COLOR0;\
|
||||
float2 uv : TEXCOORD0;\
|
||||
};\
|
||||
\
|
||||
struct PS_INPUT\
|
||||
{\
|
||||
float4 pos : SV_POSITION;\
|
||||
float4 col : COLOR0;\
|
||||
float2 uv : TEXCOORD0;\
|
||||
};\
|
||||
\
|
||||
PS_INPUT main(VS_INPUT input)\
|
||||
{\
|
||||
PS_INPUT output;\
|
||||
output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
|
||||
output.col = input.col;\
|
||||
output.uv = input.uv;\
|
||||
return output;\
|
||||
}";
|
||||
|
||||
if (FAILED(D3DCompile(vertexShader, strlen(vertexShader), NULL, NULL, NULL, "main", "vs_5_0", 0, 0, &vertexShaderBlob, NULL)))
|
||||
return false; // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
|
||||
psoDesc.VS = { vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize() };
|
||||
|
||||
// Create the input layout
|
||||
static D3D12_INPUT_ELEMENT_DESC local_layout[] =
|
||||
{
|
||||
{ "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)IM_OFFSETOF(ImDrawVert, pos), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
|
||||
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)IM_OFFSETOF(ImDrawVert, uv), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
|
||||
{ "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)IM_OFFSETOF(ImDrawVert, col), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
|
||||
};
|
||||
psoDesc.InputLayout = { local_layout, 3 };
|
||||
}
|
||||
|
||||
// Create the pixel shader
|
||||
{
|
||||
static const char* pixelShader =
|
||||
"struct PS_INPUT\
|
||||
{\
|
||||
float4 pos : SV_POSITION;\
|
||||
float4 col : COLOR0;\
|
||||
float2 uv : TEXCOORD0;\
|
||||
};\
|
||||
SamplerState sampler0 : register(s0);\
|
||||
Texture2D texture0 : register(t0);\
|
||||
\
|
||||
float4 main(PS_INPUT input) : SV_Target\
|
||||
{\
|
||||
float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
|
||||
return out_col; \
|
||||
}";
|
||||
|
||||
if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_5_0", 0, 0, &pixelShaderBlob, NULL)))
|
||||
{
|
||||
vertexShaderBlob->Release();
|
||||
return false; // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
|
||||
}
|
||||
psoDesc.PS = { pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize() };
|
||||
}
|
||||
|
||||
// Create the blending setup
|
||||
{
|
||||
D3D12_BLEND_DESC& desc = psoDesc.BlendState;
|
||||
desc.AlphaToCoverageEnable = false;
|
||||
desc.RenderTarget[0].BlendEnable = true;
|
||||
desc.RenderTarget[0].SrcBlend = D3D12_BLEND_SRC_ALPHA;
|
||||
desc.RenderTarget[0].DestBlend = D3D12_BLEND_INV_SRC_ALPHA;
|
||||
desc.RenderTarget[0].BlendOp = D3D12_BLEND_OP_ADD;
|
||||
desc.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_INV_SRC_ALPHA;
|
||||
desc.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_ZERO;
|
||||
desc.RenderTarget[0].BlendOpAlpha = D3D12_BLEND_OP_ADD;
|
||||
desc.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
|
||||
}
|
||||
|
||||
// Create the rasterizer state
|
||||
{
|
||||
D3D12_RASTERIZER_DESC& desc = psoDesc.RasterizerState;
|
||||
desc.FillMode = D3D12_FILL_MODE_SOLID;
|
||||
desc.CullMode = D3D12_CULL_MODE_NONE;
|
||||
desc.FrontCounterClockwise = FALSE;
|
||||
desc.DepthBias = D3D12_DEFAULT_DEPTH_BIAS;
|
||||
desc.DepthBiasClamp = D3D12_DEFAULT_DEPTH_BIAS_CLAMP;
|
||||
desc.SlopeScaledDepthBias = D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS;
|
||||
desc.DepthClipEnable = true;
|
||||
desc.MultisampleEnable = FALSE;
|
||||
desc.AntialiasedLineEnable = FALSE;
|
||||
desc.ForcedSampleCount = 0;
|
||||
desc.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF;
|
||||
}
|
||||
|
||||
// Create depth-stencil State
|
||||
{
|
||||
D3D12_DEPTH_STENCIL_DESC& desc = psoDesc.DepthStencilState;
|
||||
desc.DepthEnable = false;
|
||||
desc.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL;
|
||||
desc.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS;
|
||||
desc.StencilEnable = false;
|
||||
desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D12_STENCIL_OP_KEEP;
|
||||
desc.FrontFace.StencilFunc = D3D12_COMPARISON_FUNC_ALWAYS;
|
||||
desc.BackFace = desc.FrontFace;
|
||||
}
|
||||
|
||||
HRESULT result_pipeline_state = g_pd3dDevice->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&g_pPipelineState));
|
||||
vertexShaderBlob->Release();
|
||||
pixelShaderBlob->Release();
|
||||
if (result_pipeline_state != S_OK)
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void ImGui_ImplDX12_InvalidateDeviceObjects()
|
||||
{
|
||||
if (!g_pd3dDevice)
|
||||
return;
|
||||
|
||||
SafeRelease(g_pRootSignature);
|
||||
SafeRelease(g_pPipelineState);
|
||||
g_FontTexture.Destroy(true);
|
||||
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
io.Fonts->SetTexID(NULL); // We copied g_pFontTextureView to io.Fonts->TexID so let's clear that as well.
|
||||
|
||||
for (UINT i = 0; i < g_numFramesInFlight; i++)
|
||||
{
|
||||
FrameResources* fr = &g_pFrameResources[i];
|
||||
SafeRelease(fr->IndexBuffer);
|
||||
SafeRelease(fr->VertexBuffer);
|
||||
}
|
||||
}
|
||||
|
||||
bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FORMAT rtv_format)
|
||||
{
|
||||
// Setup backend capabilities flags
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
io.BackendRendererName = "imgui_impl_dx12";
|
||||
io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
|
||||
|
||||
g_pd3dDevice = device;
|
||||
g_RTVFormat = rtv_format;
|
||||
g_pFrameResources = new FrameResources[num_frames_in_flight];
|
||||
g_numFramesInFlight = num_frames_in_flight;
|
||||
g_frameIndex = UINT_MAX;
|
||||
|
||||
// Create buffers with a default size (they will later be grown as needed)
|
||||
for (int i = 0; i < num_frames_in_flight; i++)
|
||||
{
|
||||
FrameResources* fr = &g_pFrameResources[i];
|
||||
fr->IndexBuffer = NULL;
|
||||
fr->VertexBuffer = NULL;
|
||||
fr->IndexBufferSize = 10000;
|
||||
fr->VertexBufferSize = 5000;
|
||||
}
|
||||
|
||||
return ImGui_ImplDX12_CreateDeviceObjects();
|
||||
}
|
||||
|
||||
void ImGui_ImplDX12_Shutdown()
|
||||
{
|
||||
ImGui_ImplDX12_InvalidateDeviceObjects();
|
||||
delete[] g_pFrameResources;
|
||||
g_pFrameResources = NULL;
|
||||
g_pd3dDevice = NULL;
|
||||
g_numFramesInFlight = 0;
|
||||
g_frameIndex = UINT_MAX;
|
||||
}
|
47
src/frontend-common/imgui_impl_dx12.h
Normal file
47
src/frontend-common/imgui_impl_dx12.h
Normal file
@ -0,0 +1,47 @@
|
||||
// dear imgui: Renderer Backend for DirectX12
|
||||
// This needs to be used along with a Platform Backend (e.g. Win32)
|
||||
|
||||
// Implemented features:
|
||||
// [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as ImTextureID. Read the FAQ about ImTextureID!
|
||||
// [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices.
|
||||
|
||||
// Important: to compile on 32-bit systems, this backend requires code to be compiled with '#define ImTextureID ImU64'.
|
||||
// This is because we need ImTextureID to carry a 64-bit value and by default ImTextureID is defined as void*.
|
||||
// This define is set in the example .vcxproj file and need to be replicated in your app or by adding it to your imconfig.h file.
|
||||
|
||||
// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
|
||||
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
|
||||
// Read online: https://github.com/ocornut/imgui/tree/master/docs
|
||||
|
||||
#pragma once
|
||||
#include "imgui.h" // IMGUI_IMPL_API
|
||||
|
||||
#ifdef _MSC_VER
|
||||
#pragma warning (push)
|
||||
#pragma warning (disable: 4471) // a forward declaration of an unscoped enumeration must have an underlying type
|
||||
#endif
|
||||
|
||||
enum DXGI_FORMAT;
|
||||
struct ID3D12Device;
|
||||
struct ID3D12DescriptorHeap;
|
||||
struct ID3D12GraphicsCommandList;
|
||||
struct D3D12_CPU_DESCRIPTOR_HANDLE;
|
||||
struct D3D12_GPU_DESCRIPTOR_HANDLE;
|
||||
|
||||
// cmd_list is the command list that the implementation will use to render imgui draw lists.
|
||||
// Before calling the render function, caller must prepare cmd_list by resetting it and setting the appropriate
|
||||
// render target and descriptor heap that contains font_srv_cpu_desc_handle/font_srv_gpu_desc_handle.
|
||||
// font_srv_cpu_desc_handle and font_srv_gpu_desc_handle are handles to a single SRV descriptor to use for the internal font texture.
|
||||
IMGUI_IMPL_API bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FORMAT rtv_format);
|
||||
IMGUI_IMPL_API void ImGui_ImplDX12_Shutdown();
|
||||
IMGUI_IMPL_API void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandList* graphics_command_list);
|
||||
|
||||
// Use if you want to reset your rendering device without losing Dear ImGui state.
|
||||
IMGUI_IMPL_API void ImGui_ImplDX12_InvalidateDeviceObjects();
|
||||
IMGUI_IMPL_API bool ImGui_ImplDX12_CreateDeviceObjects();
|
||||
IMGUI_IMPL_API bool ImGui_ImplDX12_CreateFontsTexture();
|
||||
|
||||
#ifdef _MSC_VER
|
||||
#pragma warning (pop)
|
||||
#endif
|
||||
|
Reference in New Issue
Block a user