Large diffs are not rendered by default.

@@ -9,90 +9,37 @@
#include <d3dcompiler.h>
#include <dxgi1_5.h>
#include <vector>
#include <wrl/client.h>

#include "Common/Common.h"
#include "Common/CommonTypes.h"
#include "Common/MsgHandler.h"

namespace DX11
{
#define SAFE_RELEASE(x) \
{ \
if (x) \
(x)->Release(); \
(x) = nullptr; \
}
#define SAFE_DELETE(x) \
{ \
delete (x); \
(x) = nullptr; \
}
#define SAFE_DELETE_ARRAY(x) \
{ \
delete[](x); \
(x) = nullptr; \
}
#define CHECK(cond, Message, ...) \
if (!(cond)) \
{ \
PanicAlert("%s failed in %s at line %d: " Message, __func__, __FILE__, __LINE__, __VA_ARGS__); \
}

class DXTexture;
class DXFramebuffer;
namespace DX11
{
using Microsoft::WRL::ComPtr;
class SwapChain;

namespace D3D
{
HRESULT LoadDXGI();
HRESULT LoadD3D();
HRESULT LoadD3DCompiler();
void UnloadDXGI();
void UnloadD3D();
void UnloadD3DCompiler();

D3D_FEATURE_LEVEL GetFeatureLevel(IDXGIAdapter* adapter);
std::vector<DXGI_SAMPLE_DESC> EnumAAModes(IDXGIAdapter* adapter);

HRESULT Create(HWND wnd);
void Close();

extern ID3D11Device* device;
extern ID3D11Device1* device1;
extern ID3D11DeviceContext* context;
extern IDXGISwapChain1* swapchain;

void Reset(HWND new_wnd);
void ResizeSwapChain();
void Present();
extern ComPtr<IDXGIFactory2> dxgi_factory;
extern ComPtr<ID3D11Device> device;
extern ComPtr<ID3D11Device1> device1;
extern ComPtr<ID3D11DeviceContext> context;
extern D3D_FEATURE_LEVEL feature_level;

DXTexture* GetSwapChainTexture();
DXFramebuffer* GetSwapChainFramebuffer();
const char* PixelShaderVersionString();
const char* GeometryShaderVersionString();
const char* VertexShaderVersionString();
const char* ComputeShaderVersionString();
bool BGRATexturesSupported();
bool AllowTearingSupported();
bool Create(u32 adapter_index, bool enable_debug_layer);
void Destroy();

u32 GetMaxTextureSize(D3D_FEATURE_LEVEL feature_level);

HRESULT SetFullscreenState(bool enable_fullscreen);
bool GetFullscreenState();

// This function will assign a name to the given resource.
// The DirectX debug layer will make it easier to identify resources that way,
// e.g. when listing up all resources who have unreleased references.
void SetDebugObjectName(ID3D11DeviceChild* resource, const char* name);
std::string GetDebugObjectName(ID3D11DeviceChild* resource);
// Returns a list of supported AA modes for the current device.
std::vector<u32> GetAAModes(u32 adapter_index);

} // namespace D3D

typedef HRESULT(WINAPI* CREATEDXGIFACTORY)(REFIID, void**);
extern CREATEDXGIFACTORY PCreateDXGIFactory;
typedef HRESULT(WINAPI* D3D11CREATEDEVICE)(IDXGIAdapter*, D3D_DRIVER_TYPE, HMODULE, UINT,
CONST D3D_FEATURE_LEVEL*, UINT, UINT, ID3D11Device**,
D3D_FEATURE_LEVEL*, ID3D11DeviceContext**);

extern pD3DCompile PD3DCompile;

} // namespace DX11
@@ -13,13 +13,14 @@
#include "VideoBackends/D3D/D3DBase.h"
#include "VideoBackends/D3D/D3DState.h"
#include "VideoBackends/D3D/DXTexture.h"
#include "VideoBackends/D3DCommon/Common.h"
#include "VideoCommon/VideoConfig.h"

namespace DX11
{
namespace D3D
{
StateManager* stateman;
std::unique_ptr<StateManager> stateman;

StateManager::StateManager() = default;
StateManager::~StateManager() = default;
@@ -298,27 +299,14 @@ void StateManager::SyncComputeBindings()
}
} // namespace D3D

StateCache::~StateCache()
{
for (auto& it : m_depth)
SAFE_RELEASE(it.second);

for (auto& it : m_raster)
SAFE_RELEASE(it.second);

for (auto& it : m_blend)
SAFE_RELEASE(it.second);

for (auto& it : m_sampler)
SAFE_RELEASE(it.second);
}
StateCache::~StateCache() = default;

ID3D11SamplerState* StateCache::Get(SamplerState state)
{
std::lock_guard<std::mutex> guard(m_lock);
auto it = m_sampler.find(state.hex);
if (it != m_sampler.end())
return it->second;
return it->second.Get();

D3D11_SAMPLER_DESC sampdc = CD3D11_SAMPLER_DESC(CD3D11_DEFAULT());
if (state.mipmap_filter == SamplerState::Filter::Linear)
@@ -358,22 +346,19 @@ ID3D11SamplerState* StateCache::Get(SamplerState state)
sampdc.MaxAnisotropy = 1u << g_ActiveConfig.iMaxAnisotropy;
}

ID3D11SamplerState* res = nullptr;
ComPtr<ID3D11SamplerState> res;
HRESULT hr = D3D::device->CreateSamplerState(&sampdc, &res);
if (FAILED(hr))
PanicAlert("Fail %s %d\n", __FILE__, __LINE__);

D3D::SetDebugObjectName(res, "sampler state used to emulate the GX pipeline");
CHECK(SUCCEEDED(hr), "Creating D3D sampler state failed");
m_sampler.emplace(state.hex, res);
return res;
return res.Get();
}

ID3D11BlendState* StateCache::Get(BlendingState state)
{
std::lock_guard<std::mutex> guard(m_lock);
auto it = m_blend.find(state.hex);
if (it != m_blend.end())
return it->second;
return it->second.Get();

if (state.logicopenable && D3D::device1)
{
@@ -400,7 +385,6 @@ ID3D11BlendState* StateCache::Get(BlendingState state)
HRESULT hr = D3D::device1->CreateBlendState1(&desc, &res);
if (SUCCEEDED(hr))
{
D3D::SetDebugObjectName(res, "blend state used to emulate the GX pipeline");
m_blend.emplace(state.hex, res);
return res;
}
@@ -440,23 +424,19 @@ ID3D11BlendState* StateCache::Get(BlendingState state)
tdesc.BlendOp = state.subtract ? D3D11_BLEND_OP_REV_SUBTRACT : D3D11_BLEND_OP_ADD;
tdesc.BlendOpAlpha = state.subtractAlpha ? D3D11_BLEND_OP_REV_SUBTRACT : D3D11_BLEND_OP_ADD;

ID3D11BlendState* res = nullptr;

ComPtr<ID3D11BlendState> res;
HRESULT hr = D3D::device->CreateBlendState(&desc, &res);
if (FAILED(hr))
PanicAlert("Failed to create blend state at %s %d\n", __FILE__, __LINE__);

D3D::SetDebugObjectName(res, "blend state used to emulate the GX pipeline");
CHECK(SUCCEEDED(hr), "Creating D3D blend state failed");
m_blend.emplace(state.hex, res);
return res;
return res.Get();
}

ID3D11RasterizerState* StateCache::Get(RasterizationState state)
{
std::lock_guard<std::mutex> guard(m_lock);
auto it = m_raster.find(state.hex);
if (it != m_raster.end())
return it->second;
return it->second.Get();

static constexpr std::array<D3D11_CULL_MODE, 4> cull_modes = {
{D3D11_CULL_NONE, D3D11_CULL_BACK, D3D11_CULL_FRONT, D3D11_CULL_BACK}};
@@ -466,22 +446,19 @@ ID3D11RasterizerState* StateCache::Get(RasterizationState state)
desc.CullMode = cull_modes[state.cullmode];
desc.ScissorEnable = TRUE;

ID3D11RasterizerState* res = nullptr;
ComPtr<ID3D11RasterizerState> res;
HRESULT hr = D3D::device->CreateRasterizerState(&desc, &res);
if (FAILED(hr))
PanicAlert("Failed to create rasterizer state at %s %d\n", __FILE__, __LINE__);

D3D::SetDebugObjectName(res, "rasterizer state used to emulate the GX pipeline");
CHECK(SUCCEEDED(hr), "Creating D3D rasterizer state failed");
m_raster.emplace(state.hex, res);
return res;
return res.Get();
}

ID3D11DepthStencilState* StateCache::Get(DepthState state)
{
std::lock_guard<std::mutex> guard(m_lock);
auto it = m_depth.find(state.hex);
if (it != m_depth.end())
return it->second;
return it->second.Get();

D3D11_DEPTH_STENCIL_DESC depthdc = CD3D11_DEPTH_STENCIL_DESC(CD3D11_DEFAULT());

@@ -512,17 +489,11 @@ ID3D11DepthStencilState* StateCache::Get(DepthState state)
depthdc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ZERO;
}

ID3D11DepthStencilState* res = nullptr;

ComPtr<ID3D11DepthStencilState> res;
HRESULT hr = D3D::device->CreateDepthStencilState(&depthdc, &res);
if (SUCCEEDED(hr))
D3D::SetDebugObjectName(res, "depth-stencil state used to emulate the GX pipeline");
else
PanicAlert("Failed to create depth state at %s %d\n", __FILE__, __LINE__);

CHECK(SUCCEEDED(hr), "Creating D3D depth stencil state failed");
m_depth.emplace(state.hex, res);

return res;
return res.Get();
}

D3D11_PRIMITIVE_TOPOLOGY StateCache::GetPrimitiveTopology(PrimitiveType primitive)
@@ -6,6 +6,7 @@

#include <array>
#include <cstddef>
#include <memory>
#include <mutex>
#include <unordered_map>

@@ -34,10 +35,10 @@ class StateCache
static D3D11_PRIMITIVE_TOPOLOGY GetPrimitiveTopology(PrimitiveType primitive);

private:
std::unordered_map<u32, ID3D11DepthStencilState*> m_depth;
std::unordered_map<u32, ID3D11RasterizerState*> m_raster;
std::unordered_map<u32, ID3D11BlendState*> m_blend;
std::unordered_map<SamplerState::StorageType, ID3D11SamplerState*> m_sampler;
std::unordered_map<u32, ComPtr<ID3D11DepthStencilState>> m_depth;
std::unordered_map<u32, ComPtr<ID3D11RasterizerState>> m_raster;
std::unordered_map<u32, ComPtr<ID3D11BlendState>> m_blend;
std::unordered_map<SamplerState::StorageType, ComPtr<ID3D11SamplerState>> m_sampler;
std::mutex m_lock;
};

@@ -296,7 +297,7 @@ class StateManager
ID3D11ComputeShader* m_compute_shader = nullptr;
};

extern StateManager* stateman;
extern std::unique_ptr<StateManager> stateman;

} // namespace D3D

@@ -28,39 +28,9 @@ DXPipeline::DXPipeline(ID3D11InputLayout* input_layout, ID3D11VertexShader* vert
m_rasterizer_state(rasterizer_state), m_depth_state(depth_state), m_blend_state(blend_state),
m_primitive_topology(primitive_topology), m_use_logic_op(use_logic_op)
{
if (m_input_layout)
m_input_layout->AddRef();
if (m_vertex_shader)
m_vertex_shader->AddRef();
if (m_geometry_shader)
m_geometry_shader->AddRef();
if (m_pixel_shader)
m_pixel_shader->AddRef();
if (m_rasterizer_state)
m_rasterizer_state->AddRef();
if (m_depth_state)
m_depth_state->AddRef();
if (m_blend_state)
m_blend_state->AddRef();
}

DXPipeline::~DXPipeline()
{
if (m_input_layout)
m_input_layout->Release();
if (m_vertex_shader)
m_vertex_shader->Release();
if (m_geometry_shader)
m_geometry_shader->Release();
if (m_pixel_shader)
m_pixel_shader->Release();
if (m_rasterizer_state)
m_rasterizer_state->Release();
if (m_depth_state)
m_depth_state->Release();
if (m_blend_state)
m_blend_state->Release();
}
DXPipeline::~DXPipeline() = default;

std::unique_ptr<DXPipeline> DXPipeline::Create(const AbstractPipelineConfig& config)
{
@@ -71,12 +41,7 @@ std::unique_ptr<DXPipeline> DXPipeline::Create(const AbstractPipelineConfig& con
D3D11_PRIMITIVE_TOPOLOGY primitive_topology =
StateCache::GetPrimitiveTopology(config.rasterization_state.primitive);
if (!rasterizer_state || !depth_state || !blend_state)
{
SAFE_RELEASE(rasterizer_state);
SAFE_RELEASE(depth_state);
SAFE_RELEASE(blend_state);
return nullptr;
}

const DXShader* vertex_shader = static_cast<const DXShader*>(config.vertex_shader);
const DXShader* geometry_shader = static_cast<const DXShader*>(config.geometry_shader);
@@ -20,27 +20,27 @@ class DXPipeline final : public AbstractPipeline
bool use_logic_op);
~DXPipeline() override;

ID3D11InputLayout* GetInputLayout() const { return m_input_layout; }
ID3D11VertexShader* GetVertexShader() const { return m_vertex_shader; }
ID3D11GeometryShader* GetGeometryShader() const { return m_geometry_shader; }
ID3D11PixelShader* GetPixelShader() const { return m_pixel_shader; }
ID3D11RasterizerState* GetRasterizerState() const { return m_rasterizer_state; }
ID3D11DepthStencilState* GetDepthState() const { return m_depth_state; }
ID3D11BlendState* GetBlendState() const { return m_blend_state; }
ID3D11InputLayout* GetInputLayout() const { return m_input_layout.Get(); }
ID3D11VertexShader* GetVertexShader() const { return m_vertex_shader.Get(); }
ID3D11GeometryShader* GetGeometryShader() const { return m_geometry_shader.Get(); }
ID3D11PixelShader* GetPixelShader() const { return m_pixel_shader.Get(); }
ID3D11RasterizerState* GetRasterizerState() const { return m_rasterizer_state.Get(); }
ID3D11DepthStencilState* GetDepthState() const { return m_depth_state.Get(); }
ID3D11BlendState* GetBlendState() const { return m_blend_state.Get(); }
D3D11_PRIMITIVE_TOPOLOGY GetPrimitiveTopology() const { return m_primitive_topology; }
bool HasGeometryShader() const { return m_geometry_shader != nullptr; }
bool UseLogicOp() const { return m_use_logic_op; }

static std::unique_ptr<DXPipeline> Create(const AbstractPipelineConfig& config);

private:
ID3D11InputLayout* m_input_layout;
ID3D11VertexShader* m_vertex_shader;
ID3D11GeometryShader* m_geometry_shader;
ID3D11PixelShader* m_pixel_shader;
ID3D11RasterizerState* m_rasterizer_state;
ID3D11DepthStencilState* m_depth_state;
ID3D11BlendState* m_blend_state;
ComPtr<ID3D11InputLayout> m_input_layout;
ComPtr<ID3D11VertexShader> m_vertex_shader;
ComPtr<ID3D11GeometryShader> m_geometry_shader;
ComPtr<ID3D11PixelShader> m_pixel_shader;
ComPtr<ID3D11RasterizerState> m_rasterizer_state;
ComPtr<ID3D11DepthStencilState> m_depth_state;
ComPtr<ID3D11BlendState> m_blend_state;
D3D11_PRIMITIVE_TOPOLOGY m_primitive_topology;
bool m_use_logic_op;
};
@@ -2,62 +2,41 @@
// Licensed under GPLv2+
// Refer to the license.txt file included.

#include <fstream>

#include "VideoBackends/D3D/DXShader.h"
#include "Common/Assert.h"
#include "Common/FileUtil.h"
#include "Common/Logging/Log.h"
#include "Common/MsgHandler.h"
#include "Common/StringUtil.h"

#include "VideoBackends/D3D/D3DBase.h"
#include "VideoBackends/D3D/DXShader.h"
#include "VideoCommon/VideoConfig.h"

namespace DX11
{
DXShader::DXShader(ShaderStage stage, BinaryData bytecode, ID3D11DeviceChild* shader)
: AbstractShader(stage), m_bytecode(bytecode), m_shader(shader)
: D3DCommon::Shader(stage, std::move(bytecode)), m_shader(shader)
{
}

DXShader::~DXShader()
{
m_shader->Release();
}
DXShader::~DXShader() = default;

ID3D11VertexShader* DXShader::GetD3DVertexShader() const
{
DEBUG_ASSERT(m_stage == ShaderStage::Vertex);
return static_cast<ID3D11VertexShader*>(m_shader);
return static_cast<ID3D11VertexShader*>(m_shader.Get());
}

ID3D11GeometryShader* DXShader::GetD3DGeometryShader() const
{
DEBUG_ASSERT(m_stage == ShaderStage::Geometry);
return static_cast<ID3D11GeometryShader*>(m_shader);
return static_cast<ID3D11GeometryShader*>(m_shader.Get());
}

ID3D11PixelShader* DXShader::GetD3DPixelShader() const
{
DEBUG_ASSERT(m_stage == ShaderStage::Pixel);
return static_cast<ID3D11PixelShader*>(m_shader);
return static_cast<ID3D11PixelShader*>(m_shader.Get());
}

ID3D11ComputeShader* DXShader::GetD3DComputeShader() const
{
DEBUG_ASSERT(m_stage == ShaderStage::Compute);
return static_cast<ID3D11ComputeShader*>(m_shader);
}

bool DXShader::HasBinary() const
{
return true;
}

AbstractShader::BinaryData DXShader::GetBinary() const
{
return m_bytecode;
return static_cast<ID3D11ComputeShader*>(m_shader.Get());
}

std::unique_ptr<DXShader> DXShader::CreateFromBytecode(ShaderStage stage, BinaryData bytecode)
@@ -66,48 +45,48 @@ std::unique_ptr<DXShader> DXShader::CreateFromBytecode(ShaderStage stage, Binary
{
case ShaderStage::Vertex:
{
ID3D11VertexShader* vs;
ComPtr<ID3D11VertexShader> vs;
HRESULT hr = D3D::device->CreateVertexShader(bytecode.data(), bytecode.size(), nullptr, &vs);
CHECK(SUCCEEDED(hr), "Create vertex shader");
if (FAILED(hr))
return nullptr;

return std::make_unique<DXShader>(ShaderStage::Vertex, std::move(bytecode), vs);
return std::make_unique<DXShader>(ShaderStage::Vertex, std::move(bytecode), vs.Get());
}

case ShaderStage::Geometry:
{
ID3D11GeometryShader* gs;
ComPtr<ID3D11GeometryShader> gs;
HRESULT hr = D3D::device->CreateGeometryShader(bytecode.data(), bytecode.size(), nullptr, &gs);
CHECK(SUCCEEDED(hr), "Create geometry shader");
if (FAILED(hr))
return nullptr;

return std::make_unique<DXShader>(ShaderStage::Geometry, std::move(bytecode), gs);
return std::make_unique<DXShader>(ShaderStage::Geometry, std::move(bytecode), gs.Get());
}
break;

case ShaderStage::Pixel:
{
ID3D11PixelShader* ps;
ComPtr<ID3D11PixelShader> ps;
HRESULT hr = D3D::device->CreatePixelShader(bytecode.data(), bytecode.size(), nullptr, &ps);
CHECK(SUCCEEDED(hr), "Create pixel shader");
if (FAILED(hr))
return nullptr;

return std::make_unique<DXShader>(ShaderStage::Pixel, std::move(bytecode), ps);
return std::make_unique<DXShader>(ShaderStage::Pixel, std::move(bytecode), ps.Get());
}
break;

case ShaderStage::Compute:
{
ID3D11ComputeShader* cs;
ComPtr<ID3D11ComputeShader> cs;
HRESULT hr = D3D::device->CreateComputeShader(bytecode.data(), bytecode.size(), nullptr, &cs);
CHECK(SUCCEEDED(hr), "Create compute shader");
if (FAILED(hr))
return nullptr;

return std::make_unique<DXShader>(ShaderStage::Compute, std::move(bytecode), cs);
return std::make_unique<DXShader>(ShaderStage::Compute, std::move(bytecode), cs.Get());
}
break;

@@ -117,86 +96,4 @@ std::unique_ptr<DXShader> DXShader::CreateFromBytecode(ShaderStage stage, Binary

return nullptr;
}

static const char* GetCompileTarget(ShaderStage stage)
{
switch (stage)
{
case ShaderStage::Vertex:
return D3D::VertexShaderVersionString();
case ShaderStage::Geometry:
return D3D::GeometryShaderVersionString();
case ShaderStage::Pixel:
return D3D::PixelShaderVersionString();
case ShaderStage::Compute:
return D3D::ComputeShaderVersionString();
default:
return "";
}
}

bool DXShader::CompileShader(BinaryData* out_bytecode, ShaderStage stage, const char* source,
size_t length)
{
static constexpr D3D_SHADER_MACRO macros[] = {{"API_D3D", "1"}, {nullptr, nullptr}};
const UINT flags = g_ActiveConfig.bEnableValidationLayer ?
(D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION) :
(D3DCOMPILE_OPTIMIZATION_LEVEL3 | D3DCOMPILE_SKIP_VALIDATION);
const char* target = GetCompileTarget(stage);

ID3DBlob* code = nullptr;
ID3DBlob* errors = nullptr;
HRESULT hr = PD3DCompile(source, length, nullptr, macros, nullptr, "main", target, flags, 0,
&code, &errors);
if (FAILED(hr))
{
static int num_failures = 0;
std::string filename = StringFromFormat(
"%sbad_%s_%04i.txt", File::GetUserPath(D_DUMP_IDX).c_str(), target, num_failures++);
std::ofstream file;
File::OpenFStream(file, filename, std::ios_base::out);
file.write(source, length);
file << "\n";
file.write(static_cast<const char*>(errors->GetBufferPointer()), errors->GetBufferSize());
file.close();

PanicAlert("Failed to compile %s:\nDebug info (%s):\n%s", filename.c_str(), target,
static_cast<const char*>(errors->GetBufferPointer()));
errors->Release();
return false;
}

if (errors && errors->GetBufferSize() > 0)
{
WARN_LOG(VIDEO, "%s compilation succeeded with warnings:\n%s", target,
static_cast<const char*>(errors->GetBufferPointer()));
}
SAFE_RELEASE(errors);

out_bytecode->resize(code->GetBufferSize());
std::memcpy(out_bytecode->data(), code->GetBufferPointer(), code->GetBufferSize());
code->Release();
return true;
}

std::unique_ptr<DXShader> DXShader::CreateFromSource(ShaderStage stage, const char* source,
size_t length)
{
BinaryData bytecode;
if (!CompileShader(&bytecode, stage, source, length))
return nullptr;

return CreateFromBytecode(stage, std::move(bytecode));
}

std::unique_ptr<DXShader> DXShader::CreateFromBinary(ShaderStage stage, const void* data,
size_t length)
{
if (length == 0)
return nullptr;

BinaryData bytecode(length);
std::memcpy(bytecode.data(), data, length);
return CreateFromBytecode(stage, std::move(bytecode));
}
} // namespace DX11
@@ -3,14 +3,14 @@
// Refer to the license.txt file included.

#pragma once
#include <d3d11.h>
#include <memory>

#include "VideoCommon/AbstractShader.h"
#include "VideoBackends/D3D/D3DBase.h"
#include "VideoBackends/D3DCommon/Shader.h"

namespace DX11
{
class DXShader final : public AbstractShader
class DXShader final : public D3DCommon::Shader
{
public:
DXShader(ShaderStage stage, BinaryData bytecode, ID3D11DeviceChild* shader);
@@ -23,22 +23,10 @@ class DXShader final : public AbstractShader
ID3D11PixelShader* GetD3DPixelShader() const;
ID3D11ComputeShader* GetD3DComputeShader() const;

bool HasBinary() const override;
BinaryData GetBinary() const override;

// Creates a new shader object.
static std::unique_ptr<DXShader> CreateFromBytecode(ShaderStage stage, BinaryData bytecode);
static bool CompileShader(BinaryData* out_bytecode, ShaderStage stage, const char* source,
size_t length);

static std::unique_ptr<DXShader> CreateFromBinary(ShaderStage stage, const void* data,
size_t length);
static std::unique_ptr<DXShader> CreateFromSource(ShaderStage stage, const char* source,
size_t length);

private:
ID3D11DeviceChild* m_shader;
BinaryData m_bytecode;
ComPtr<ID3D11DeviceChild> m_shader;
};

} // namespace DX11

Large diffs are not rendered by default.

@@ -17,11 +17,10 @@ namespace DX11
class DXTexture final : public AbstractTexture
{
public:
explicit DXTexture(const TextureConfig& tex_config, ID3D11Texture2D* d3d_texture,
ID3D11ShaderResourceView* d3d_srv, ID3D11UnorderedAccessView* d3d_uav);
~DXTexture();

static std::unique_ptr<DXTexture> Create(const TextureConfig& config);
static std::unique_ptr<DXTexture> CreateAdopted(ID3D11Texture2D* texture);

void CopyRectangleFromTexture(const AbstractTexture* src,
const MathUtil::Rectangle<int>& src_rect, u32 src_layer,
@@ -32,14 +31,19 @@ class DXTexture final : public AbstractTexture
void Load(u32 level, u32 width, u32 height, u32 row_length, const u8* buffer,
size_t buffer_size) override;

ID3D11Texture2D* GetD3DTexture() const { return m_d3d_texture; }
ID3D11ShaderResourceView* GetD3DSRV() const { return m_d3d_srv; }
ID3D11UnorderedAccessView* GetD3DUAV() const { return m_d3d_uav; }
ID3D11Texture2D* GetD3DTexture() const { return m_texture.Get(); }
ID3D11ShaderResourceView* GetD3DSRV() const { return m_srv.Get(); }
ID3D11UnorderedAccessView* GetD3DUAV() const { return m_uav.Get(); }

private:
ID3D11Texture2D* m_d3d_texture;
ID3D11ShaderResourceView* m_d3d_srv;
ID3D11UnorderedAccessView* m_d3d_uav;
DXTexture(const TextureConfig& config, ID3D11Texture2D* texture);

bool CreateSRV();
bool CreateUAV();

ComPtr<ID3D11Texture2D> m_texture;
ComPtr<ID3D11ShaderResourceView> m_srv;
ComPtr<ID3D11UnorderedAccessView> m_uav;
};

class DXStagingTexture final : public AbstractStagingTexture
@@ -65,7 +69,7 @@ class DXStagingTexture final : public AbstractStagingTexture
private:
DXStagingTexture(StagingTextureType type, const TextureConfig& config, ID3D11Texture2D* tex);

ID3D11Texture2D* m_tex = nullptr;
ComPtr<ID3D11Texture2D> m_tex = nullptr;
};

class DXFramebuffer final : public AbstractFramebuffer
@@ -77,17 +81,17 @@ class DXFramebuffer final : public AbstractFramebuffer
ID3D11RenderTargetView* integer_rtv, ID3D11DepthStencilView* dsv);
~DXFramebuffer() override;

ID3D11RenderTargetView* const* GetRTVArray() const { return &m_rtv; }
ID3D11RenderTargetView* const* GetIntegerRTVArray() const { return &m_integer_rtv; }
ID3D11RenderTargetView* const* GetRTVArray() const { return m_rtv.GetAddressOf(); }
ID3D11RenderTargetView* const* GetIntegerRTVArray() const { return m_integer_rtv.GetAddressOf(); }
UINT GetNumRTVs() const { return m_rtv ? 1 : 0; }
ID3D11DepthStencilView* GetDSV() const { return m_dsv; }
ID3D11DepthStencilView* GetDSV() const { return m_dsv.Get(); }
static std::unique_ptr<DXFramebuffer> Create(DXTexture* color_attachment,
DXTexture* depth_attachment);

protected:
ID3D11RenderTargetView* m_rtv;
ID3D11RenderTargetView* m_integer_rtv;
ID3D11DepthStencilView* m_dsv;
ComPtr<ID3D11RenderTargetView> m_rtv;
ComPtr<ID3D11RenderTargetView> m_integer_rtv;
ComPtr<ID3D11DepthStencilView> m_dsv;
};

} // namespace DX11
@@ -147,7 +147,8 @@ D3DVertexFormat::D3DVertexFormat(const PortableVertexDeclaration& vtx_decl)
D3DVertexFormat::~D3DVertexFormat()
{
ID3D11InputLayout* layout = m_layout.load();
SAFE_RELEASE(layout);
if (layout)
layout->Release();
}

ID3D11InputLayout* D3DVertexFormat::GetInputLayout(const void* vs_bytecode, size_t vs_bytecode_size)
@@ -160,16 +161,16 @@ ID3D11InputLayout* D3DVertexFormat::GetInputLayout(const void* vs_bytecode, size

HRESULT hr = D3D::device->CreateInputLayout(m_elems.data(), m_num_elems, vs_bytecode,
vs_bytecode_size, &layout);
if (FAILED(hr))
PanicAlert("Failed to create input layout, %s %d\n", __FILE__, __LINE__);
DX11::D3D::SetDebugObjectName(m_layout, "input layout used to emulate the GX pipeline");
CHECK(SUCCEEDED(hr), "Failed to create input layout");

// This method can be called from multiple threads, so ensure that only one thread sets the
// cached input layout pointer. If another thread beats this thread, use the existing layout.
ID3D11InputLayout* expected = nullptr;
if (!m_layout.compare_exchange_strong(expected, layout))
{
SAFE_RELEASE(layout);
if (layout)
layout->Release();

layout = expected;
}

@@ -22,14 +22,7 @@ PerfQuery::PerfQuery() : m_query_read_pos()
ResetQuery();
}

PerfQuery::~PerfQuery()
{
for (ActiveQuery& entry : m_query_buffer)
{
// TODO: EndQuery?
entry.query->Release();
}
}
PerfQuery::~PerfQuery() = default;

void PerfQuery::EnableQuery(PerfQueryGroup type)
{
@@ -49,7 +42,7 @@ void PerfQuery::EnableQuery(PerfQueryGroup type)
{
auto& entry = m_query_buffer[(m_query_read_pos + m_query_count) % m_query_buffer.size()];

D3D::context->Begin(entry.query);
D3D::context->Begin(entry.query.Get());
entry.query_type = type;

++m_query_count;
@@ -63,7 +56,7 @@ void PerfQuery::DisableQuery(PerfQueryGroup type)
{
auto& entry = m_query_buffer[(m_query_read_pos + m_query_count + m_query_buffer.size() - 1) %
m_query_buffer.size()];
D3D::context->End(entry.query);
D3D::context->End(entry.query.Get());
}
}

@@ -98,7 +91,7 @@ void PerfQuery::FlushOne()
while (hr != S_OK)
{
// TODO: Might cause us to be stuck in an infinite loop!
hr = D3D::context->GetData(entry.query, &result, sizeof(result), 0);
hr = D3D::context->GetData(entry.query.Get(), &result, sizeof(result), 0);
}

// NOTE: Reported pixel metrics should be referenced to native resolution
@@ -125,8 +118,8 @@ void PerfQuery::WeakFlush()
auto& entry = m_query_buffer[m_query_read_pos];

UINT64 result = 0;
HRESULT hr =
D3D::context->GetData(entry.query, &result, sizeof(result), D3D11_ASYNC_GETDATA_DONOTFLUSH);
HRESULT hr = D3D::context->GetData(entry.query.Get(), &result, sizeof(result),
D3D11_ASYNC_GETDATA_DONOTFLUSH);

if (hr == S_OK)
{
@@ -149,4 +142,4 @@ bool PerfQuery::IsFlushed() const
return 0 == m_query_count;
}

} // namespace
} // namespace DX11
@@ -5,8 +5,7 @@
#pragma once

#include <array>
#include <d3d11.h>

#include "VideoBackends/D3D/D3DBase.h"
#include "VideoCommon/PerfQueryBase.h"

namespace DX11
@@ -27,7 +26,7 @@ class PerfQuery : public PerfQueryBase
private:
struct ActiveQuery
{
ID3D11Query* query;
ComPtr<ID3D11Query> query;
PerfQueryGroup query_type;
};

@@ -43,4 +42,4 @@ class PerfQuery : public PerfQueryBase
int m_query_read_pos;
};

} // namespace
} // namespace DX11
@@ -26,6 +26,7 @@
#include "VideoBackends/D3D/DXPipeline.h"
#include "VideoBackends/D3D/DXShader.h"
#include "VideoBackends/D3D/DXTexture.h"
#include "VideoBackends/D3D/SwapChain.h"

#include "VideoCommon/BPFunctions.h"
#include "VideoCommon/FramebufferManager.h"
@@ -48,11 +49,12 @@ typedef struct _Nv_Stereo_Image_Header

#define NVSTEREO_IMAGE_SIGNATURE 0x4433564e

Renderer::Renderer(int backbuffer_width, int backbuffer_height, float backbuffer_scale)
: ::Renderer(backbuffer_width, backbuffer_height, backbuffer_scale,
AbstractTextureFormat::RGBA8)
Renderer::Renderer(std::unique_ptr<SwapChain> swap_chain, float backbuffer_scale)
: ::Renderer(swap_chain ? swap_chain->GetWidth() : 0, swap_chain ? swap_chain->GetHeight() : 0,
backbuffer_scale,
swap_chain ? swap_chain->GetFormat() : AbstractTextureFormat::Undefined),
m_swap_chain(std::move(swap_chain))
{
m_last_fullscreen_state = D3D::GetFullscreenState();
}

Renderer::~Renderer() = default;
@@ -82,17 +84,13 @@ void Renderer::Create3DVisionTexture(int width, int height)
ID3D11Texture2D* texture;
HRESULT hr = D3D::device->CreateTexture2D(&texture_desc, &sys_data, &texture);
CHECK(SUCCEEDED(hr), "Create 3D Vision Texture");
m_3d_vision_texture = std::make_unique<DXTexture>(TextureConfig(width * 2, height + 1, 1, 1, 1,
AbstractTextureFormat::RGBA8,
AbstractTextureFlag_RenderTarget),
texture, nullptr, nullptr);
m_3d_vision_framebuffer =
DXFramebuffer::Create(static_cast<DXTexture*>(m_3d_vision_texture.get()), nullptr);
m_3d_vision_texture = DXTexture::CreateAdopted(texture);
m_3d_vision_framebuffer = DXFramebuffer::Create(m_3d_vision_texture.get(), nullptr);
}

bool Renderer::IsHeadless() const
{
return D3D::swapchain == nullptr;
return !m_swap_chain;
}

std::unique_ptr<AbstractTexture> Renderer::CreateTexture(const TextureConfig& config)
@@ -116,13 +114,17 @@ std::unique_ptr<AbstractFramebuffer> Renderer::CreateFramebuffer(AbstractTexture
std::unique_ptr<AbstractShader> Renderer::CreateShaderFromSource(ShaderStage stage,
const char* source, size_t length)
{
return DXShader::CreateFromSource(stage, source, length);
DXShader::BinaryData bytecode;
if (!DXShader::CompileShader(D3D::feature_level, &bytecode, stage, source, length))
return nullptr;

return DXShader::CreateFromBytecode(stage, std::move(bytecode));
}

std::unique_ptr<AbstractShader> Renderer::CreateShaderFromBinary(ShaderStage stage,
const void* data, size_t length)
{
return DXShader::CreateFromBinary(stage, data, length);
return DXShader::CreateFromBytecode(stage, DXShader::CreateByteCode(data, length));
}

std::unique_ptr<AbstractPipeline> Renderer::CreatePipeline(const AbstractPipelineConfig& config)
@@ -196,64 +198,44 @@ void Renderer::DispatchComputeShader(const AbstractShader* shader, u32 groups_x,

void Renderer::BindBackbuffer(const ClearColor& clear_color)
{
CheckForSurfaceChange();
CheckForSurfaceResize();
SetAndClearFramebuffer(D3D::GetSwapChainFramebuffer(), clear_color);
CheckForSwapChainChanges();
SetAndClearFramebuffer(m_swap_chain->GetFramebuffer(), clear_color);
}

void Renderer::PresentBackbuffer()
{
D3D::Present();
m_swap_chain->Present();
}

void Renderer::OnConfigChanged(u32 bits)
{
// Quad-buffer changes require swap chain recreation.
if (bits & CONFIG_CHANGE_BIT_STEREO_MODE && m_swap_chain)
m_swap_chain->SetStereo(SwapChain::WantsStereo());
}

void Renderer::CheckForSurfaceChange()
{
if (!m_surface_changed.TestAndClear())
return;

m_3d_vision_framebuffer.reset();
m_3d_vision_texture.reset();

D3D::Reset(reinterpret_cast<HWND>(m_new_surface_handle));
m_new_surface_handle = nullptr;

UpdateBackbufferSize();
}

void Renderer::CheckForSurfaceResize()
void Renderer::CheckForSwapChainChanges()
{
const bool fullscreen_state = D3D::GetFullscreenState();
const bool exclusive_fullscreen_changed = fullscreen_state != m_last_fullscreen_state;
if (!m_surface_resized.TestAndClear() && !exclusive_fullscreen_changed)
const bool surface_changed = m_surface_changed.TestAndClear();
const bool surface_resized =
m_surface_resized.TestAndClear() || m_swap_chain->CheckForFullscreenChange();
if (!surface_changed && !surface_resized)
return;

m_3d_vision_framebuffer.reset();
m_3d_vision_texture.reset();

m_last_fullscreen_state = fullscreen_state;
if (D3D::swapchain)
D3D::ResizeSwapChain();
UpdateBackbufferSize();
}

void Renderer::UpdateBackbufferSize()
{
if (D3D::swapchain)
if (surface_changed)
{
DXGI_SWAP_CHAIN_DESC1 desc = {};
D3D::swapchain->GetDesc1(&desc);
m_backbuffer_width = std::max(desc.Width, 1u);
m_backbuffer_height = std::max(desc.Height, 1u);
m_swap_chain->ChangeSurface(m_new_surface_handle);
m_new_surface_handle = nullptr;
}
else
{
m_backbuffer_width = 1;
m_backbuffer_height = 1;
m_swap_chain->ResizeSwapChain();
}

m_backbuffer_width = m_swap_chain->GetWidth();
m_backbuffer_height = m_swap_chain->GetHeight();
m_3d_vision_framebuffer.reset();
m_3d_vision_texture.reset();
}

void Renderer::SetFramebuffer(AbstractFramebuffer* framebuffer)
@@ -363,22 +345,23 @@ void Renderer::RenderXFBToScreen(const AbstractTexture* texture, const EFBRectan

// Copy the left eye to the backbuffer, if Nvidia 3D Vision is enabled it should
// recognize the signature and automatically include the right eye frame.
const CD3D11_BOX box(0, 0, 0, m_backbuffer_width, m_backbuffer_height, 1);
D3D::context->CopySubresourceRegion(D3D::GetSwapChainTexture()->GetD3DTexture(), 0, 0, 0, 0,
const CD3D11_BOX box(0, 0, 0, m_swap_chain->GetWidth(), m_swap_chain->GetHeight(), 1);
D3D::context->CopySubresourceRegion(m_swap_chain->GetTexture()->GetD3DTexture(), 0, 0, 0, 0,
m_3d_vision_texture->GetD3DTexture(), 0, &box);

// Restore render target to backbuffer
SetFramebuffer(D3D::GetSwapChainFramebuffer());
SetFramebuffer(m_swap_chain->GetFramebuffer());
}

void Renderer::SetFullscreen(bool enable_fullscreen)
{
D3D::SetFullscreenState(enable_fullscreen);
if (m_swap_chain)
m_swap_chain->SetFullscreen(enable_fullscreen);
}

bool Renderer::IsFullscreen() const
{
return D3D::GetFullscreenState();
return m_swap_chain && m_swap_chain->GetFullscreen();
}

} // namespace DX11
@@ -11,13 +11,14 @@

namespace DX11
{
class SwapChain;
class DXTexture;
class DXFramebuffer;

class Renderer : public ::Renderer
{
public:
Renderer(int backbuffer_width, int backbuffer_height, float backbuffer_scale);
Renderer(std::unique_ptr<SwapChain> swap_chain, float backbuffer_scale);
~Renderer() override;

StateCache& GetStateCache() { return m_state_cache; }
@@ -69,15 +70,12 @@ class Renderer : public ::Renderer

private:
void Create3DVisionTexture(int width, int height);
void CheckForSurfaceChange();
void CheckForSurfaceResize();
void UpdateBackbufferSize();
void CheckForSwapChainChanges();

StateCache m_state_cache;

std::unique_ptr<SwapChain> m_swap_chain;
std::unique_ptr<DXTexture> m_3d_vision_texture;
std::unique_ptr<DXFramebuffer> m_3d_vision_framebuffer;

bool m_last_fullscreen_state = false;
};
} // namespace DX11
@@ -0,0 +1,52 @@
// Copyright 2019 Dolphin Emulator Project
// Licensed under GPLv2+
// Refer to the license.txt file included.

#include "VideoBackends/D3D/SwapChain.h"
#include "VideoBackends/D3D/DXTexture.h"

namespace DX11
{
SwapChain::SwapChain(const WindowSystemInfo& wsi, IDXGIFactory2* dxgi_factory,
ID3D11Device* d3d_device)
: D3DCommon::SwapChain(wsi, dxgi_factory, d3d_device)
{
}

SwapChain::~SwapChain() = default;

std::unique_ptr<SwapChain> SwapChain::Create(const WindowSystemInfo& wsi)
{
std::unique_ptr<SwapChain> swap_chain =
std::make_unique<SwapChain>(wsi, D3D::dxgi_factory.Get(), D3D::device.Get());
if (!swap_chain->CreateSwapChain(WantsStereo()))
return nullptr;

return swap_chain;
}

bool SwapChain::CreateSwapChainBuffers()
{
ComPtr<ID3D11Texture2D> texture;
HRESULT hr = m_swap_chain->GetBuffer(0, IID_PPV_ARGS(&texture));
CHECK(SUCCEEDED(hr), "Get swap chain buffer");
if (FAILED(hr))
return false;

m_texture = DXTexture::CreateAdopted(texture.Get());
if (!m_texture)
return false;

m_framebuffer = DXFramebuffer::Create(m_texture.get(), nullptr);
if (!m_framebuffer)
return false;

return true;
}

void SwapChain::DestroySwapChainBuffers()
{
m_framebuffer.reset();
m_texture.reset();
}
} // namespace DX11
@@ -0,0 +1,44 @@
// Copyright 2019 Dolphin Emulator Project
// Licensed under GPLv2+
// Refer to the license.txt file included.

#pragma once

#include <d3d11.h>
#include <dxgi.h>
#include <memory>
#include <vector>

#include "Common/CommonTypes.h"
#include "Common/WindowSystemInfo.h"
#include "VideoBackends/D3D/D3DBase.h"
#include "VideoBackends/D3DCommon/SwapChain.h"
#include "VideoCommon/TextureConfig.h"

namespace DX11
{
class DXTexture;
class DXFramebuffer;

class SwapChain : public D3DCommon::SwapChain
{
public:
SwapChain(const WindowSystemInfo& wsi, IDXGIFactory2* dxgi_factory, ID3D11Device* d3d_device);
~SwapChain();

static std::unique_ptr<SwapChain> Create(const WindowSystemInfo& wsi);

DXTexture* GetTexture() const { return m_texture.get(); }
DXFramebuffer* GetFramebuffer() const { return m_framebuffer.get(); }

protected:
bool CreateSwapChainBuffers() override;
void DestroySwapChainBuffers() override;

private:
// The runtime takes care of renaming the buffers.
std::unique_ptr<DXTexture> m_texture;
std::unique_ptr<DXFramebuffer> m_framebuffer;
};

} // namespace DX11
@@ -14,6 +14,7 @@
#include "VideoBackends/D3D/D3DBase.h"
#include "VideoBackends/D3D/D3DState.h"
#include "VideoBackends/D3D/Render.h"
#include "VideoBackends/D3DCommon/Common.h"

#include "VideoCommon/BoundingBox.h"
#include "VideoCommon/GeometryShaderManager.h"
@@ -27,15 +28,18 @@

namespace DX11
{
static ID3D11Buffer* AllocateConstantBuffer(u32 size)
static ComPtr<ID3D11Buffer> AllocateConstantBuffer(u32 size)
{
const u32 cbsize = Common::AlignUp(size, 16u); // must be a multiple of 16
const CD3D11_BUFFER_DESC cbdesc(cbsize, D3D11_BIND_CONSTANT_BUFFER, D3D11_USAGE_DYNAMIC,
D3D11_CPU_ACCESS_WRITE);
ID3D11Buffer* cbuf;
ComPtr<ID3D11Buffer> cbuf;
const HRESULT hr = D3D::device->CreateBuffer(&cbdesc, nullptr, &cbuf);
CHECK(hr == S_OK, "shader constant buffer (size=%u)", cbsize);
D3D::SetDebugObjectName(cbuf, "constant buffer used to emulate the GX pipeline");
CHECK(SUCCEEDED(hr), "shader constant buffer (size=%u)", cbsize);
if (FAILED(hr))
return nullptr;

D3DCommon::SetDebugObjectName(cbuf.Get(), "constant buffer");
return cbuf;
}

@@ -49,10 +53,10 @@ static void UpdateConstantBuffer(ID3D11Buffer* const buffer, const void* data, u
ADDSTAT(stats.thisFrame.bytesUniformStreamed, data_size);
}

static ID3D11ShaderResourceView*
static ComPtr<ID3D11ShaderResourceView>
CreateTexelBufferView(ID3D11Buffer* buffer, TexelBufferFormat format, DXGI_FORMAT srv_format)
{
ID3D11ShaderResourceView* srv;
ComPtr<ID3D11ShaderResourceView> srv;
CD3D11_SHADER_RESOURCE_VIEW_DESC srv_desc(buffer, srv_format, 0,
VertexManager::TEXEL_STREAM_BUFFER_SIZE /
VertexManager::GetTexelBufferElementSize(format));
@@ -63,17 +67,7 @@ CreateTexelBufferView(ID3D11Buffer* buffer, TexelBufferFormat format, DXGI_FORMA

VertexManager::VertexManager() = default;

VertexManager::~VertexManager()
{
for (auto& srv_ptr : m_texel_buffer_views)
SAFE_RELEASE(srv_ptr);
SAFE_RELEASE(m_texel_buffer);
SAFE_RELEASE(m_pixel_constant_buffer);
SAFE_RELEASE(m_geometry_constant_buffer);
SAFE_RELEASE(m_vertex_constant_buffer);
for (auto& buffer : m_buffers)
SAFE_RELEASE(buffer);
}
VertexManager::~VertexManager() = default;

bool VertexManager::Initialize()
{
@@ -88,7 +82,8 @@ bool VertexManager::Initialize()
{
CHECK(SUCCEEDED(D3D::device->CreateBuffer(&bufdesc, nullptr, &m_buffers[i])),
"Failed to create buffer.");
D3D::SetDebugObjectName(m_buffers[i], "Buffer of VertexManager");
if (m_buffers[i])
D3DCommon::SetDebugObjectName(m_buffers[i].Get(), "Buffer of VertexManager");
}

m_vertex_constant_buffer = AllocateConstantBuffer(sizeof(VertexShaderConstants));
@@ -113,7 +108,8 @@ bool VertexManager::Initialize()
}};
for (const auto& it : format_mapping)
{
m_texel_buffer_views[it.first] = CreateTexelBufferView(m_texel_buffer, it.first, it.second);
m_texel_buffer_views[it.first] =
CreateTexelBufferView(m_texel_buffer.Get(), it.first, it.second);
if (!m_texel_buffer_views[it.first])
return false;
}
@@ -125,18 +121,18 @@ void VertexManager::UploadUtilityUniforms(const void* uniforms, u32 uniforms_siz
{
// Just use the one buffer for all three.
InvalidateConstants();
UpdateConstantBuffer(m_vertex_constant_buffer, uniforms, uniforms_size);
D3D::stateman->SetVertexConstants(m_vertex_constant_buffer);
D3D::stateman->SetGeometryConstants(m_vertex_constant_buffer);
D3D::stateman->SetPixelConstants(m_vertex_constant_buffer);
UpdateConstantBuffer(m_vertex_constant_buffer.Get(), uniforms, uniforms_size);
D3D::stateman->SetVertexConstants(m_vertex_constant_buffer.Get());
D3D::stateman->SetGeometryConstants(m_vertex_constant_buffer.Get());
D3D::stateman->SetPixelConstants(m_vertex_constant_buffer.Get());
}

bool VertexManager::MapTexelBuffer(u32 required_size, D3D11_MAPPED_SUBRESOURCE& sr)
{
if ((m_texel_buffer_offset + required_size) > TEXEL_STREAM_BUFFER_SIZE)
{
// Restart buffer.
HRESULT hr = D3D::context->Map(m_texel_buffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &sr);
HRESULT hr = D3D::context->Map(m_texel_buffer.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &sr);
CHECK(SUCCEEDED(hr), "Map texel buffer");
if (FAILED(hr))
return false;
@@ -146,7 +142,7 @@ bool VertexManager::MapTexelBuffer(u32 required_size, D3D11_MAPPED_SUBRESOURCE&
else
{
// Don't overwrite the earlier-used space.
HRESULT hr = D3D::context->Map(m_texel_buffer, 0, D3D11_MAP_WRITE_NO_OVERWRITE, 0, &sr);
HRESULT hr = D3D::context->Map(m_texel_buffer.Get(), 0, D3D11_MAP_WRITE_NO_OVERWRITE, 0, &sr);
CHECK(SUCCEEDED(hr), "Map texel buffer");
if (FAILED(hr))
return false;
@@ -173,8 +169,8 @@ bool VertexManager::UploadTexelBuffer(const void* data, u32 data_size, TexelBuff
ADDSTAT(stats.thisFrame.bytesUniformStreamed, data_size);
m_texel_buffer_offset += data_size;

D3D::context->Unmap(m_texel_buffer, 0);
D3D::stateman->SetTexture(0, m_texel_buffer_views[static_cast<size_t>(format)]);
D3D::context->Unmap(m_texel_buffer.Get(), 0);
D3D::stateman->SetTexture(0, m_texel_buffer_views[static_cast<size_t>(format)].Get());
return true;
}

@@ -203,9 +199,9 @@ bool VertexManager::UploadTexelBuffer(const void* data, u32 data_size, TexelBuff
*out_palette_offset = (m_texel_buffer_offset + palette_byte_offset) / palette_elem_size;
m_texel_buffer_offset += palette_byte_offset + palette_size;

D3D::context->Unmap(m_texel_buffer, 0);
D3D::stateman->SetTexture(0, m_texel_buffer_views[static_cast<size_t>(format)]);
D3D::stateman->SetTexture(1, m_texel_buffer_views[static_cast<size_t>(palette_format)]);
D3D::context->Unmap(m_texel_buffer.Get(), 0);
D3D::stateman->SetTexture(0, m_texel_buffer_views[static_cast<size_t>(format)].Get());
D3D::stateman->SetTexture(1, m_texel_buffer_views[static_cast<size_t>(palette_format)].Get());
return true;
}

@@ -245,48 +241,48 @@ void VertexManager::CommitBuffer(u32 num_vertices, u32 vertex_stride, u32 num_in
*out_base_vertex = vertex_stride > 0 ? (cursor / vertex_stride) : 0;
*out_base_index = (cursor + vertexBufferSize) / sizeof(u16);

D3D::context->Map(m_buffers[m_current_buffer], 0, MapType, 0, &map);
D3D::context->Map(m_buffers[m_current_buffer].Get(), 0, MapType, 0, &map);
u8* mappedData = reinterpret_cast<u8*>(map.pData);
if (vertexBufferSize > 0)
std::memcpy(mappedData + cursor, m_base_buffer_pointer, vertexBufferSize);
if (indexBufferSize > 0)
std::memcpy(mappedData + cursor + vertexBufferSize, m_cpu_index_buffer.data(), indexBufferSize);
D3D::context->Unmap(m_buffers[m_current_buffer], 0);
D3D::context->Unmap(m_buffers[m_current_buffer].Get(), 0);

m_buffer_cursor = cursor + totalBufferSize;

ADDSTAT(stats.thisFrame.bytesVertexStreamed, vertexBufferSize);
ADDSTAT(stats.thisFrame.bytesIndexStreamed, indexBufferSize);

D3D::stateman->SetVertexBuffer(m_buffers[m_current_buffer], vertex_stride, 0);
D3D::stateman->SetIndexBuffer(m_buffers[m_current_buffer]);
D3D::stateman->SetVertexBuffer(m_buffers[m_current_buffer].Get(), vertex_stride, 0);
D3D::stateman->SetIndexBuffer(m_buffers[m_current_buffer].Get());
}

void VertexManager::UploadUniforms()
{
if (VertexShaderManager::dirty)
{
UpdateConstantBuffer(m_vertex_constant_buffer, &VertexShaderManager::constants,
UpdateConstantBuffer(m_vertex_constant_buffer.Get(), &VertexShaderManager::constants,
sizeof(VertexShaderConstants));
VertexShaderManager::dirty = false;
}
if (GeometryShaderManager::dirty)
{
UpdateConstantBuffer(m_geometry_constant_buffer, &GeometryShaderManager::constants,
UpdateConstantBuffer(m_geometry_constant_buffer.Get(), &GeometryShaderManager::constants,
sizeof(GeometryShaderConstants));
GeometryShaderManager::dirty = false;
}
if (PixelShaderManager::dirty)
{
UpdateConstantBuffer(m_pixel_constant_buffer, &PixelShaderManager::constants,
UpdateConstantBuffer(m_pixel_constant_buffer.Get(), &PixelShaderManager::constants,
sizeof(PixelShaderConstants));
PixelShaderManager::dirty = false;
}

D3D::stateman->SetPixelConstants(m_pixel_constant_buffer, g_ActiveConfig.bEnablePixelLighting ?
m_vertex_constant_buffer :
nullptr);
D3D::stateman->SetVertexConstants(m_vertex_constant_buffer);
D3D::stateman->SetGeometryConstants(m_geometry_constant_buffer);
D3D::stateman->SetPixelConstants(
m_pixel_constant_buffer.Get(),
g_ActiveConfig.bEnablePixelLighting ? m_vertex_constant_buffer.Get() : nullptr);
D3D::stateman->SetVertexConstants(m_vertex_constant_buffer.Get());
D3D::stateman->SetGeometryConstants(m_geometry_constant_buffer.Get());
}
} // namespace DX11
@@ -4,18 +4,15 @@

#pragma once

#include <d3d11.h>

#include <array>
#include <atomic>
#include <memory>
#include <vector>

#include "VideoBackends/D3D/D3DBase.h"
#include "VideoCommon/NativeVertexFormat.h"
#include "VideoCommon/VertexManagerBase.h"

struct ID3D11Buffer;

namespace DX11
{
class D3DVertexFormat : public NativeVertexFormat
@@ -60,16 +57,16 @@ class VertexManager : public VertexManagerBase

bool MapTexelBuffer(u32 required_size, D3D11_MAPPED_SUBRESOURCE& sr);

ID3D11Buffer* m_buffers[BUFFER_COUNT] = {};
ComPtr<ID3D11Buffer> m_buffers[BUFFER_COUNT] = {};
u32 m_current_buffer = 0;
u32 m_buffer_cursor = 0;

ID3D11Buffer* m_vertex_constant_buffer = nullptr;
ID3D11Buffer* m_geometry_constant_buffer = nullptr;
ID3D11Buffer* m_pixel_constant_buffer = nullptr;
ComPtr<ID3D11Buffer> m_vertex_constant_buffer = nullptr;
ComPtr<ID3D11Buffer> m_geometry_constant_buffer = nullptr;
ComPtr<ID3D11Buffer> m_pixel_constant_buffer = nullptr;

ID3D11Buffer* m_texel_buffer = nullptr;
std::array<ID3D11ShaderResourceView*, NUM_TEXEL_BUFFER_FORMATS> m_texel_buffer_views;
ComPtr<ID3D11Buffer> m_texel_buffer = nullptr;
std::array<ComPtr<ID3D11ShaderResourceView>, NUM_TEXEL_BUFFER_FORMATS> m_texel_buffer_views;
u32 m_texel_buffer_offset = 0;
};

@@ -11,12 +11,16 @@ namespace DX11
{
class VideoBackend : public VideoBackendBase
{
public:
bool Initialize(const WindowSystemInfo& wsi) override;
void Shutdown() override;

std::string GetName() const override;
std::string GetDisplayName() const override;

void InitBackendInfo() override;

private:
void FillBackendInfo();
};
} // namespace DX11
@@ -14,8 +14,10 @@
#include "VideoBackends/D3D/D3DBase.h"
#include "VideoBackends/D3D/PerfQuery.h"
#include "VideoBackends/D3D/Render.h"
#include "VideoBackends/D3D/SwapChain.h"
#include "VideoBackends/D3D/VertexManager.h"
#include "VideoBackends/D3D/VideoBackend.h"
#include "VideoBackends/D3DCommon/Common.h"

#include "VideoCommon/FramebufferManager.h"
#include "VideoCommon/ShaderCache.h"
@@ -37,15 +39,15 @@ std::string VideoBackend::GetDisplayName() const

void VideoBackend::InitBackendInfo()
{
HRESULT hr = DX11::D3D::LoadDXGI();
if (SUCCEEDED(hr))
hr = DX11::D3D::LoadD3D();
if (FAILED(hr))
{
DX11::D3D::UnloadDXGI();
if (!D3DCommon::LoadLibraries())
return;
}

FillBackendInfo();
D3DCommon::UnloadLibraries();
}

void VideoBackend::FillBackendInfo()
{
g_Config.backend_info.api_type = APIType::D3D;
g_Config.backend_info.MaxTextureSize = D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION;
g_Config.backend_info.bUsesLowerLeftOrigin = false;
@@ -73,82 +75,36 @@ void VideoBackend::InitBackendInfo()
g_Config.backend_info.bSupportsBPTCTextures = false;
g_Config.backend_info.bSupportsFramebufferFetch = false;
g_Config.backend_info.bSupportsBackgroundCompiling = true;

IDXGIFactory2* factory;
IDXGIAdapter* ad;
hr = DX11::PCreateDXGIFactory(__uuidof(IDXGIFactory2), (void**)&factory);
if (FAILED(hr))
PanicAlert("Failed to create IDXGIFactory object");

// adapters
g_Config.backend_info.Adapters.clear();
g_Config.backend_info.AAModes.clear();
while (factory->EnumAdapters((UINT)g_Config.backend_info.Adapters.size(), &ad) !=
DXGI_ERROR_NOT_FOUND)
{
const size_t adapter_index = g_Config.backend_info.Adapters.size();

DXGI_ADAPTER_DESC desc;
ad->GetDesc(&desc);

// TODO: These don't get updated on adapter change, yet
if (adapter_index == g_Config.iAdapter)
{
std::vector<DXGI_SAMPLE_DESC> modes = DX11::D3D::EnumAAModes(ad);
// First iteration will be 1. This equals no AA.
for (unsigned int i = 0; i < modes.size(); ++i)
{
g_Config.backend_info.AAModes.push_back(modes[i].Count);
}

D3D_FEATURE_LEVEL feature_level = D3D::GetFeatureLevel(ad);
bool shader_model_5_supported = feature_level >= D3D_FEATURE_LEVEL_11_0;
g_Config.backend_info.MaxTextureSize = D3D::GetMaxTextureSize(feature_level);

// Requires the earlydepthstencil attribute (only available in shader model 5)
g_Config.backend_info.bSupportsEarlyZ = shader_model_5_supported;

// Requires full UAV functionality (only available in shader model 5)
g_Config.backend_info.bSupportsBBox =
g_Config.backend_info.bSupportsFragmentStoresAndAtomics = shader_model_5_supported;

// Requires the instance attribute (only available in shader model 5)
g_Config.backend_info.bSupportsGSInstancing = shader_model_5_supported;

// Sample shading requires shader model 5
g_Config.backend_info.bSupportsSSAA = shader_model_5_supported;
}
g_Config.backend_info.Adapters.push_back(UTF16ToUTF8(desc.Description));
ad->Release();
}
factory->Release();

DX11::D3D::UnloadDXGI();
DX11::D3D::UnloadD3D();
g_Config.backend_info.bSupportsST3CTextures = true;
g_Config.backend_info.bSupportsBPTCTextures = true;
g_Config.backend_info.bSupportsEarlyZ = true;
g_Config.backend_info.bSupportsBBox = true;
g_Config.backend_info.bSupportsFragmentStoresAndAtomics = true;
g_Config.backend_info.bSupportsGSInstancing = true;
g_Config.backend_info.bSupportsSSAA = true;

g_Config.backend_info.Adapters = D3DCommon::GetAdapterNames();
g_Config.backend_info.AAModes = D3D::GetAAModes(g_Config.iAdapter);
}

bool VideoBackend::Initialize(const WindowSystemInfo& wsi)
{
if (!D3D::Create(g_Config.iAdapter, g_Config.bEnableValidationLayer))
return false;

FillBackendInfo();
InitializeShared();

if (FAILED(D3D::Create(reinterpret_cast<HWND>(wsi.render_surface))))
std::unique_ptr<SwapChain> swap_chain;
if (wsi.render_surface && !(swap_chain = SwapChain::Create(wsi)))
{
PanicAlert("Failed to create D3D device.");
PanicAlertT("Failed to create D3D swap chain");
ShutdownShared();
D3D::Destroy();
return false;
}

int backbuffer_width = 1, backbuffer_height = 1;
if (D3D::swapchain)
{
DXGI_SWAP_CHAIN_DESC1 desc = {};
D3D::swapchain->GetDesc1(&desc);
backbuffer_width = std::max(desc.Width, 1u);
backbuffer_height = std::max(desc.Height, 1u);
}

// internal interfaces
g_renderer =
std::make_unique<Renderer>(backbuffer_width, backbuffer_height, wsi.render_surface_scale);
g_renderer = std::make_unique<Renderer>(std::move(swap_chain), wsi.render_surface_scale);
g_vertex_manager = std::make_unique<VertexManager>();
g_shader_cache = std::make_unique<VideoCommon::ShaderCache>();
g_framebuffer_manager = std::make_unique<FramebufferManager>();
@@ -158,6 +114,7 @@ bool VideoBackend::Initialize(const WindowSystemInfo& wsi)
!g_shader_cache->Initialize() || !g_framebuffer_manager->Initialize() ||
!g_texture_cache->Initialize())
{
Shutdown();
return false;
}

@@ -181,7 +138,6 @@ void VideoBackend::Shutdown()
g_renderer.reset();

ShutdownShared();

D3D::Close();
D3D::Destroy();
}
} // namespace DX11
@@ -0,0 +1,15 @@
add_library(videod3dcommon
Common.cpp
Common.h
Shader.cpp
Shader.h
SwapChain.cpp
SwapChain.h
)

target_link_libraries(videod3dcommon
PUBLIC
common
videocommon
videod3dcommon
)
@@ -0,0 +1,320 @@
// Copyright 2019 Dolphin Emulator Project
// Licensed under GPLv2+
// Refer to the license.txt file included.

#include <d3d11.h>
#include <d3d12.h>
#include <dxgi1_3.h>
#include <wrl/client.h>

#include "Common/Assert.h"
#include "Common/DynamicLibrary.h"
#include "Common/MsgHandler.h"
#include "Common/StringUtil.h"
#include "VideoBackends/D3DCommon/Common.h"
#include "VideoCommon/TextureConfig.h"
#include "VideoCommon/VideoConfig.h"

namespace D3DCommon
{
pD3DCompile d3d_compile;

static Common::DynamicLibrary s_dxgi_library;
static Common::DynamicLibrary s_d3dcompiler_library;
static bool s_libraries_loaded = false;

static HRESULT (*create_dxgi_factory)(REFIID riid, _COM_Outptr_ void** ppFactory);
static HRESULT (*create_dxgi_factory2)(UINT Flags, REFIID riid, void** ppFactory);

bool LoadLibraries()
{
if (s_libraries_loaded)
return true;

if (!s_dxgi_library.Open("dxgi.dll"))
{
PanicAlertT("Failed to load dxgi.dll");
return false;
}

if (!s_d3dcompiler_library.Open(D3DCOMPILER_DLL_A))
{
PanicAlertT("Failed to load %s. If you are using Windows 7, try installing the "
"KB4019990 update package.",
D3DCOMPILER_DLL_A);
s_dxgi_library.Close();
return false;
}

// Required symbols.
if (!s_d3dcompiler_library.GetSymbol("D3DCompile", &d3d_compile) ||
!s_dxgi_library.GetSymbol("CreateDXGIFactory", &create_dxgi_factory))
{
PanicAlertT("Failed to find one or more D3D symbols");
s_d3dcompiler_library.Close();
s_dxgi_library.Close();
return false;
}

// Optional symbols.
s_dxgi_library.GetSymbol("CreateDXGIFactory2", &create_dxgi_factory2);
s_libraries_loaded = true;
return true;
}

void UnloadLibraries()
{
create_dxgi_factory = nullptr;
create_dxgi_factory2 = nullptr;
d3d_compile = nullptr;
s_d3dcompiler_library.Close();
s_dxgi_library.Close();
s_libraries_loaded = false;
}

IDXGIFactory2* CreateDXGIFactory(bool debug_device)
{
IDXGIFactory2* factory;

// Use Win8.1 version if available.
if (create_dxgi_factory2 &&
SUCCEEDED(create_dxgi_factory2(debug_device ? DXGI_CREATE_FACTORY_DEBUG : 0,
IID_PPV_ARGS(&factory))))
{
return factory;
}

// Fallback to original version, without debug support.
HRESULT hr = create_dxgi_factory(IID_PPV_ARGS(&factory));
if (FAILED(hr))
{
PanicAlert("CreateDXGIFactory() failed with HRESULT %08X", hr);
return nullptr;
}

return factory;
}

std::vector<std::string> GetAdapterNames()
{
Microsoft::WRL::ComPtr<IDXGIFactory> factory;
HRESULT hr = create_dxgi_factory(IID_PPV_ARGS(&factory));
if (!SUCCEEDED(hr))
return {};

std::vector<std::string> adapters;
IDXGIAdapter* adapter;
while (factory->EnumAdapters(static_cast<UINT>(adapters.size()), &adapter) !=
DXGI_ERROR_NOT_FOUND)
{
std::string name;
DXGI_ADAPTER_DESC desc;
if (SUCCEEDED(adapter->GetDesc(&desc)))
name = UTF16ToUTF8(desc.Description);

adapters.push_back(std::move(name));
}

return adapters;
}

DXGI_FORMAT GetDXGIFormatForAbstractFormat(AbstractTextureFormat format, bool typeless)
{
switch (format)
{
case AbstractTextureFormat::DXT1:
return DXGI_FORMAT_BC1_UNORM;
case AbstractTextureFormat::DXT3:
return DXGI_FORMAT_BC2_UNORM;
case AbstractTextureFormat::DXT5:
return DXGI_FORMAT_BC3_UNORM;
case AbstractTextureFormat::BPTC:
return DXGI_FORMAT_BC7_UNORM;
case AbstractTextureFormat::RGBA8:
return typeless ? DXGI_FORMAT_R8G8B8A8_TYPELESS : DXGI_FORMAT_R8G8B8A8_UNORM;
case AbstractTextureFormat::BGRA8:
return typeless ? DXGI_FORMAT_B8G8R8A8_TYPELESS : DXGI_FORMAT_B8G8R8A8_UNORM;
case AbstractTextureFormat::R16:
return typeless ? DXGI_FORMAT_R16_TYPELESS : DXGI_FORMAT_R16_UNORM;
case AbstractTextureFormat::R32F:
return typeless ? DXGI_FORMAT_R32_TYPELESS : DXGI_FORMAT_R32_FLOAT;
case AbstractTextureFormat::D16:
return DXGI_FORMAT_R16_TYPELESS;
case AbstractTextureFormat::D24_S8:
return DXGI_FORMAT_R24G8_TYPELESS;
case AbstractTextureFormat::D32F:
return DXGI_FORMAT_R32_TYPELESS;
case AbstractTextureFormat::D32F_S8:
return DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS;
default:
PanicAlert("Unhandled texture format.");
return DXGI_FORMAT_R8G8B8A8_UNORM;
}
}
DXGI_FORMAT GetSRVFormatForAbstractFormat(AbstractTextureFormat format)
{
switch (format)
{
case AbstractTextureFormat::DXT1:
return DXGI_FORMAT_BC1_UNORM;
case AbstractTextureFormat::DXT3:
return DXGI_FORMAT_BC2_UNORM;
case AbstractTextureFormat::DXT5:
return DXGI_FORMAT_BC3_UNORM;
case AbstractTextureFormat::BPTC:
return DXGI_FORMAT_BC7_UNORM;
case AbstractTextureFormat::RGBA8:
return DXGI_FORMAT_R8G8B8A8_UNORM;
case AbstractTextureFormat::BGRA8:
return DXGI_FORMAT_B8G8R8A8_UNORM;
case AbstractTextureFormat::R16:
return DXGI_FORMAT_R16_UNORM;
case AbstractTextureFormat::R32F:
return DXGI_FORMAT_R32_FLOAT;
case AbstractTextureFormat::D16:
return DXGI_FORMAT_R16_UNORM;
case AbstractTextureFormat::D24_S8:
return DXGI_FORMAT_R24_UNORM_X8_TYPELESS;
case AbstractTextureFormat::D32F:
return DXGI_FORMAT_R32_FLOAT;
case AbstractTextureFormat::D32F_S8:
return DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS;
default:
PanicAlert("Unhandled SRV format");
return DXGI_FORMAT_UNKNOWN;
}
}

DXGI_FORMAT GetRTVFormatForAbstractFormat(AbstractTextureFormat format, bool integer)
{
switch (format)
{
case AbstractTextureFormat::RGBA8:
return integer ? DXGI_FORMAT_R8G8B8A8_UINT : DXGI_FORMAT_R8G8B8A8_UNORM;
case AbstractTextureFormat::BGRA8:
return DXGI_FORMAT_B8G8R8A8_UNORM;
case AbstractTextureFormat::R16:
return integer ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R16_UNORM;
case AbstractTextureFormat::R32F:
return DXGI_FORMAT_R32_FLOAT;
default:
PanicAlert("Unhandled RTV format");
return DXGI_FORMAT_UNKNOWN;
}
}
DXGI_FORMAT GetDSVFormatForAbstractFormat(AbstractTextureFormat format)
{
switch (format)
{
case AbstractTextureFormat::D16:
return DXGI_FORMAT_D16_UNORM;
case AbstractTextureFormat::D24_S8:
return DXGI_FORMAT_D24_UNORM_S8_UINT;
case AbstractTextureFormat::D32F:
return DXGI_FORMAT_D32_FLOAT;
case AbstractTextureFormat::D32F_S8:
return DXGI_FORMAT_D32_FLOAT_S8X24_UINT;
default:
PanicAlert("Unhandled DSV format");
return DXGI_FORMAT_UNKNOWN;
}
}

AbstractTextureFormat GetAbstractFormatForDXGIFormat(DXGI_FORMAT format)
{
switch (format)
{
case DXGI_FORMAT_R8G8B8A8_UINT:
case DXGI_FORMAT_R8G8B8A8_UNORM:
case DXGI_FORMAT_R8G8B8A8_TYPELESS:
return AbstractTextureFormat::RGBA8;

case DXGI_FORMAT_B8G8R8A8_UNORM:
case DXGI_FORMAT_B8G8R8A8_TYPELESS:
return AbstractTextureFormat::BGRA8;

case DXGI_FORMAT_R16_UINT:
case DXGI_FORMAT_R16_UNORM:
case DXGI_FORMAT_R16_TYPELESS:
return AbstractTextureFormat::R16;

case DXGI_FORMAT_R32_FLOAT:
case DXGI_FORMAT_R32_TYPELESS:
return AbstractTextureFormat::R32F;

case DXGI_FORMAT_D16_UNORM:
return AbstractTextureFormat::D16;

case DXGI_FORMAT_D24_UNORM_S8_UINT:
return AbstractTextureFormat::D24_S8;

case DXGI_FORMAT_D32_FLOAT:
return AbstractTextureFormat::D32F;

case DXGI_FORMAT_D32_FLOAT_S8X24_UINT:
return AbstractTextureFormat::D32F_S8;

case DXGI_FORMAT_BC1_UNORM:
return AbstractTextureFormat::DXT1;
case DXGI_FORMAT_BC2_UNORM:
return AbstractTextureFormat::DXT3;
case DXGI_FORMAT_BC3_UNORM:
return AbstractTextureFormat::DXT5;
case DXGI_FORMAT_BC7_UNORM:
return AbstractTextureFormat::BPTC;

default:
return AbstractTextureFormat::Undefined;
}
}

void SetDebugObjectName(IUnknown* resource, const char* format, ...)
{
if (!g_ActiveConfig.bEnableValidationLayer)
return;

std::va_list ap;
va_start(ap, format);
std::string name = StringFromFormatV(format, ap);
va_end(ap);

Microsoft::WRL::ComPtr<ID3D11DeviceChild> child11;
Microsoft::WRL::ComPtr<ID3D12DeviceChild> child12;
if (SUCCEEDED(resource->QueryInterface(IID_PPV_ARGS(&child11))))
{
child11->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(name.length()),
name.c_str());
}
else if (SUCCEEDED(resource->QueryInterface(IID_PPV_ARGS(&child12))))
{
child12->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(name.length()),
name.c_str());
}
}

std::string GetDebugObjectName(IUnknown* resource)
{
if (!g_ActiveConfig.bEnableValidationLayer)
return {};

std::string name;
UINT size = 0;

Microsoft::WRL::ComPtr<ID3D11DeviceChild> child11;
Microsoft::WRL::ComPtr<ID3D12DeviceChild> child12;
if (SUCCEEDED(resource->QueryInterface(IID_PPV_ARGS(&child11))))
{
child11->GetPrivateData(WKPDID_D3DDebugObjectName, &size, nullptr);
name.resize(size);
child11->GetPrivateData(WKPDID_D3DDebugObjectName, &size, name.data());
}
else if (SUCCEEDED(resource->QueryInterface(IID_PPV_ARGS(&child12))))
{
child12->GetPrivateData(WKPDID_D3DDebugObjectName, &size, nullptr);
name.resize(size);
child12->GetPrivateData(WKPDID_D3DDebugObjectName, &size, name.data());
}

return name;
}
} // namespace D3DCommon
@@ -0,0 +1,46 @@
// Copyright 2019 Dolphin Emulator Project
// Licensed under GPLv2+
// Refer to the license.txt file included.

#pragma once

#include <d3dcompiler.h>
#include <dxgiformat.h>
#include <string>
#include <vector>

#include "Common/CommonTypes.h"
#include "VideoCommon/VideoCommon.h"

struct IDXGIFactory2;

enum class AbstractTextureFormat : u32;

namespace D3DCommon
{
// Loading dxgi.dll and d3dcompiler.dll
bool LoadLibraries();
void UnloadLibraries();

// Returns a list of D3D device names.
std::vector<std::string> GetAdapterNames();

// Helper function which creates a DXGI factory.
IDXGIFactory2* CreateDXGIFactory(bool debug_device);

// Globally-accessible D3DCompiler function.
extern pD3DCompile d3d_compile;

// Helpers for texture format conversion.
DXGI_FORMAT GetDXGIFormatForAbstractFormat(AbstractTextureFormat format, bool typeless);
DXGI_FORMAT GetSRVFormatForAbstractFormat(AbstractTextureFormat format);
DXGI_FORMAT GetRTVFormatForAbstractFormat(AbstractTextureFormat format, bool integer);
DXGI_FORMAT GetDSVFormatForAbstractFormat(AbstractTextureFormat format);
AbstractTextureFormat GetAbstractFormatForDXGIFormat(DXGI_FORMAT format);

// This function will assign a name to the given resource.
// The DirectX debug layer will make it easier to identify resources that way,
// e.g. when listing up all resources who have unreleased references.
void SetDebugObjectName(IUnknown* resource, const char* format, ...);
std::string GetDebugObjectName(IUnknown* resource);
} // namespace D3DCommon
@@ -0,0 +1,68 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{DEA96CF2-F237-4A1A-B32F-C916769EFB50}</ProjectGuid>
<WindowsTargetPlatformVersion>10.0.17134.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<PlatformToolset>v141</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)'=='Debug'" Label="Configuration">
<UseDebugLibraries>true</UseDebugLibraries>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)'=='Release'" Label="Configuration">
<UseDebugLibraries>false</UseDebugLibraries>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="..\..\..\VSProps\Base.props" />
<Import Project="..\..\..\VSProps\PCHUse.props" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<ForcedIncludeFiles />
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<ForcedIncludeFiles />
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="Common.cpp" />
<ClCompile Include="Shader.cpp" />
<ClCompile Include="SwapChain.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="Common.h" />
<ClInclude Include="Shader.h" />
<ClInclude Include="SwapChain.h" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="$(CoreDir)VideoCommon\VideoCommon.vcxproj">
<Project>{3de9ee35-3e91-4f27-a014-2866ad8c3fe3}</Project>
</ProjectReference>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<ClCompile Include="SwapChain.cpp" />
<ClCompile Include="Common.cpp" />
<ClCompile Include="Shader.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="SwapChain.h" />
<ClInclude Include="Common.h" />
<ClInclude Include="Shader.h" />
</ItemGroup>
</Project>
@@ -0,0 +1,145 @@
// Copyright 2019 Dolphin Emulator Project
// Licensed under GPLv2+
// Refer to the license.txt file included.

#include <fstream>
#include <wrl/client.h>

#include "Common/Assert.h"
#include "Common/FileUtil.h"
#include "Common/Logging/Log.h"
#include "Common/MsgHandler.h"
#include "Common/StringUtil.h"

#include "VideoBackends/D3DCommon/Shader.h"
#include "VideoCommon/VideoConfig.h"

namespace D3DCommon
{
Shader::Shader(ShaderStage stage, BinaryData bytecode)
: AbstractShader(stage), m_bytecode(std::move(bytecode))
{
}

Shader::~Shader() = default;

bool Shader::HasBinary() const
{
return true;
}

AbstractShader::BinaryData Shader::GetBinary() const
{
return m_bytecode;
}

static const char* GetCompileTarget(D3D_FEATURE_LEVEL feature_level, ShaderStage stage)
{
switch (stage)
{
case ShaderStage::Vertex:
{
switch (feature_level)
{
case D3D_FEATURE_LEVEL_10_0:
return "vs_4_0";
case D3D_FEATURE_LEVEL_10_1:
return "vs_4_1";
default:
return "vs_5_0";
}
}

case ShaderStage::Geometry:
{
switch (feature_level)
{
case D3D_FEATURE_LEVEL_10_0:
return "gs_4_0";
case D3D_FEATURE_LEVEL_10_1:
return "gs_4_1";
default:
return "gs_5_0";
}
}

case ShaderStage::Pixel:
{
switch (feature_level)
{
case D3D_FEATURE_LEVEL_10_0:
return "ps_4_0";
case D3D_FEATURE_LEVEL_10_1:
return "ps_4_1";
default:
return "ps_5_0";
}
}

case ShaderStage::Compute:
{
switch (feature_level)
{
case D3D_FEATURE_LEVEL_10_0:
case D3D_FEATURE_LEVEL_10_1:
return "";

default:
return "cs_5_0";
}
}

default:
return "";
}
}

bool Shader::CompileShader(D3D_FEATURE_LEVEL feature_level, BinaryData* out_bytecode,
ShaderStage stage, const char* source, size_t length)
{
static constexpr D3D_SHADER_MACRO macros[] = {{"API_D3D", "1"}, {nullptr, nullptr}};
const UINT flags = g_ActiveConfig.bEnableValidationLayer ?
(D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION) :
(D3DCOMPILE_OPTIMIZATION_LEVEL3 | D3DCOMPILE_SKIP_VALIDATION);
const char* target = GetCompileTarget(feature_level, stage);

Microsoft::WRL::ComPtr<ID3DBlob> code;
Microsoft::WRL::ComPtr<ID3DBlob> errors;
HRESULT hr = d3d_compile(source, length, nullptr, macros, nullptr, "main", target, flags, 0,
&code, &errors);
if (FAILED(hr))
{
static int num_failures = 0;
std::string filename = StringFromFormat(
"%sbad_%s_%04i.txt", File::GetUserPath(D_DUMP_IDX).c_str(), target, num_failures++);
std::ofstream file;
File::OpenFStream(file, filename, std::ios_base::out);
file.write(source, length);
file << "\n";
file.write(static_cast<const char*>(errors->GetBufferPointer()), errors->GetBufferSize());
file.close();

PanicAlert("Failed to compile %s:\nDebug info (%s):\n%s", filename.c_str(), target,
static_cast<const char*>(errors->GetBufferPointer()));
return false;
}

if (errors && errors->GetBufferSize() > 0)
{
WARN_LOG(VIDEO, "%s compilation succeeded with warnings:\n%s", target,
static_cast<const char*>(errors->GetBufferPointer()));
}

out_bytecode->resize(code->GetBufferSize());
std::memcpy(out_bytecode->data(), code->GetBufferPointer(), code->GetBufferSize());
return true;
}

AbstractShader::BinaryData Shader::CreateByteCode(const void* data, size_t length)
{
BinaryData bytecode(length);
std::memcpy(bytecode.data(), data, length);
return bytecode;
}

} // namespace D3DCommon
@@ -0,0 +1,33 @@
// Copyright 2019 Dolphin Emulator Project
// Licensed under GPLv2+
// Refer to the license.txt file included.

#pragma once
#include <memory>
#include "VideoBackends/D3DCommon/Common.h"
#include "VideoCommon/AbstractShader.h"

namespace D3DCommon
{
class Shader : public AbstractShader
{
public:
virtual ~Shader() override;

const BinaryData& GetByteCode() const { return m_bytecode; }

bool HasBinary() const override;
BinaryData GetBinary() const override;

static bool CompileShader(D3D_FEATURE_LEVEL feature_level, BinaryData* out_bytecode,
ShaderStage stage, const char* source, size_t length);

static BinaryData CreateByteCode(const void* data, size_t length);

protected:
Shader(ShaderStage stage, BinaryData bytecode);

BinaryData m_bytecode;
};

} // namespace D3DCommon
@@ -0,0 +1,232 @@
// Copyright 2019 Dolphin Emulator Project
// Licensed under GPLv2+
// Refer to the license.txt file included.

#include "VideoBackends/D3DCommon/SwapChain.h"

#include <algorithm>
#include <cstdint>

#include "Common/Assert.h"
#include "Common/CommonFuncs.h"
#include "Common/Logging/Log.h"
#include "Common/MsgHandler.h"
#include "VideoCommon/VideoConfig.h"

static bool IsTearingSupported(IDXGIFactory2* dxgi_factory)
{
Microsoft::WRL::ComPtr<IDXGIFactory5> factory5;
if (FAILED(dxgi_factory->QueryInterface(IID_PPV_ARGS(&factory5))))
return false;

UINT allow_tearing = 0;
return SUCCEEDED(factory5->CheckFeatureSupport(DXGI_FEATURE_PRESENT_ALLOW_TEARING, &allow_tearing,
sizeof(allow_tearing))) &&
allow_tearing != 0;
}

static bool GetFullscreenState(IDXGISwapChain1* swap_chain)
{
BOOL fs = FALSE;
return SUCCEEDED(swap_chain->GetFullscreenState(&fs, nullptr)) && fs;
}

namespace D3DCommon
{
SwapChain::SwapChain(const WindowSystemInfo& wsi, IDXGIFactory2* dxgi_factory, IUnknown* d3d_device)
: m_wsi(wsi), m_dxgi_factory(dxgi_factory), m_d3d_device(d3d_device),
m_allow_tearing_supported(IsTearingSupported(dxgi_factory))
{
}

SwapChain::~SwapChain()
{
// Can't destroy swap chain while it's fullscreen.
if (m_swap_chain && GetFullscreenState(m_swap_chain.Get()))
m_swap_chain->SetFullscreenState(FALSE, nullptr);
}

bool SwapChain::WantsStereo()
{
return g_ActiveConfig.stereo_mode == StereoMode::QuadBuffer;
}

u32 SwapChain::GetSwapChainFlags() const
{
// This flag is necessary if we want to use a flip-model swapchain without locking the framerate
return m_allow_tearing_supported ? DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING : 0;
}

bool SwapChain::CreateSwapChain(bool stereo)
{
RECT client_rc;
if (GetClientRect(static_cast<HWND>(m_wsi.render_surface), &client_rc))
{
m_width = client_rc.right - client_rc.left;
m_height = client_rc.bottom - client_rc.top;
}

DXGI_SWAP_CHAIN_DESC1 swap_chain_desc = {};
swap_chain_desc.Width = m_width;
swap_chain_desc.Height = m_height;
swap_chain_desc.BufferCount = SWAP_CHAIN_BUFFER_COUNT;
swap_chain_desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swap_chain_desc.SampleDesc.Count = 1;
swap_chain_desc.SampleDesc.Quality = 0;
swap_chain_desc.Format = GetDXGIFormatForAbstractFormat(m_texture_format, false);
swap_chain_desc.Scaling = DXGI_SCALING_STRETCH;
swap_chain_desc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
swap_chain_desc.Stereo = stereo;
swap_chain_desc.Flags = GetSwapChainFlags();

HRESULT hr = m_dxgi_factory->CreateSwapChainForHwnd(
m_d3d_device.Get(), static_cast<HWND>(m_wsi.render_surface), &swap_chain_desc, nullptr,
nullptr, &m_swap_chain);
if (FAILED(hr))
{
// Flip-model discard swapchains aren't supported on Windows 8, so here we fall back to
// a sequential swapchain
swap_chain_desc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;
hr = m_dxgi_factory->CreateSwapChainForHwnd(m_d3d_device.Get(),
static_cast<HWND>(m_wsi.render_surface),
&swap_chain_desc, nullptr, nullptr, &m_swap_chain);
}

if (FAILED(hr))
{
// Flip-model swapchains aren't supported on Windows 7, so here we fall back to a legacy
// BitBlt-model swapchain
swap_chain_desc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
hr = m_dxgi_factory->CreateSwapChainForHwnd(m_d3d_device.Get(),
static_cast<HWND>(m_wsi.render_surface),
&swap_chain_desc, nullptr, nullptr, &m_swap_chain);
}

if (FAILED(hr))
{
PanicAlert("Failed to create swap chain with HRESULT %08X", hr);
return false;
}

// We handle fullscreen ourselves.
hr = m_dxgi_factory->MakeWindowAssociation(static_cast<HWND>(m_wsi.render_surface),
DXGI_MWA_NO_WINDOW_CHANGES | DXGI_MWA_NO_ALT_ENTER);
if (FAILED(hr))
WARN_LOG(VIDEO, "MakeWindowAssociation() failed with HRESULT %08X", hr);

m_stereo = stereo;
if (!CreateSwapChainBuffers())
{
PanicAlert("Failed to create swap chain buffers");
DestroySwapChainBuffers();
m_swap_chain.Reset();
return false;
}

return true;
}

void SwapChain::DestroySwapChain()
{
DestroySwapChainBuffers();

// Can't destroy swap chain while it's fullscreen.
if (m_swap_chain && GetFullscreenState(m_swap_chain.Get()))
m_swap_chain->SetFullscreenState(FALSE, nullptr);

m_swap_chain.Reset();
}

bool SwapChain::ResizeSwapChain()
{
DestroySwapChainBuffers();

HRESULT hr = m_swap_chain->ResizeBuffers(SWAP_CHAIN_BUFFER_COUNT, 0, 0,
GetDXGIFormatForAbstractFormat(m_texture_format, false),
GetSwapChainFlags());
if (FAILED(hr))
WARN_LOG(VIDEO, "ResizeBuffers() failed with HRESULT %08X", hr);

DXGI_SWAP_CHAIN_DESC1 desc;
if (SUCCEEDED(m_swap_chain->GetDesc1(&desc)))
{
m_width = desc.Width;
m_height = desc.Height;
}

return CreateSwapChainBuffers();
}

void SwapChain::SetStereo(bool stereo)
{
if (m_stereo == stereo)
return;

DestroySwapChain();
if (!CreateSwapChain(stereo))
{
PanicAlert("Failed to switch swap chain stereo mode");
CreateSwapChain(false);
}
}

bool SwapChain::GetFullscreen() const
{
return GetFullscreenState(m_swap_chain.Get());
}

void SwapChain::SetFullscreen(bool request)
{
m_swap_chain->SetFullscreenState(request, nullptr);
}

bool SwapChain::CheckForFullscreenChange()
{
if (m_fullscreen_request != m_has_fullscreen)
{
HRESULT hr = m_swap_chain->SetFullscreenState(m_fullscreen_request, nullptr);
if (SUCCEEDED(hr))
{
m_has_fullscreen = m_fullscreen_request;
return true;
}
}

const bool new_fullscreen_state = GetFullscreenState(m_swap_chain.Get());
if (new_fullscreen_state != m_has_fullscreen)
{
m_has_fullscreen = new_fullscreen_state;
m_fullscreen_request = new_fullscreen_state;
return true;
}

return false;
}

bool SwapChain::Present()
{
// When using sync interval 0, it is recommended to always pass the tearing flag when it is
// supported, even when presenting in windowed mode. However, this flag cannot be used if the app
// is in fullscreen mode as a result of calling SetFullscreenState.
UINT present_flags = 0;
if (m_allow_tearing_supported && !g_ActiveConfig.bVSyncActive && !m_has_fullscreen)
present_flags |= DXGI_PRESENT_ALLOW_TEARING;

HRESULT hr = m_swap_chain->Present(static_cast<UINT>(g_ActiveConfig.bVSyncActive), present_flags);
if (FAILED(hr))
{
WARN_LOG(VIDEO, "Swap chain present failed with HRESULT %08X", hr);
return false;
}

return true;
}

bool SwapChain::ChangeSurface(void* native_handle)
{
DestroySwapChain();
m_wsi.render_surface = native_handle;
return CreateSwapChain(m_stereo);
}

} // namespace D3DCommon
@@ -0,0 +1,74 @@
// Copyright 2019 Dolphin Emulator Project
// Licensed under GPLv2+
// Refer to the license.txt file included.

#pragma once

#include <dxgi1_5.h>
#include <wrl/client.h>

#include "Common/CommonTypes.h"
#include "Common/WindowSystemInfo.h"
#include "VideoBackends/D3DCommon/Common.h"
#include "VideoCommon/TextureConfig.h"

namespace D3DCommon
{
class SwapChain
{
public:
SwapChain(const WindowSystemInfo& wsi, IDXGIFactory2* dxgi_factory, IUnknown* d3d_device);
virtual ~SwapChain();

// Sufficient buffers for triple buffering.
static const u32 SWAP_CHAIN_BUFFER_COUNT = 3;

// Returns true if the stereo mode is quad-buffering.
static bool WantsStereo();

IDXGISwapChain1* GetDXGISwapChain() const { return m_swap_chain.Get(); }
AbstractTextureFormat GetFormat() const { return m_texture_format; }
u32 GetWidth() const { return m_width; }
u32 GetHeight() const { return m_height; }
u32 GetLayers() const { return m_stereo ? 2u : 1u; }
bool IsStereoEnabled() const { return m_stereo; }
bool HasExclusiveFullscreen() const { return m_has_fullscreen; }

// Mode switches.
bool GetFullscreen() const;
void SetFullscreen(bool request);

// Checks for loss of exclusive fullscreen.
bool CheckForFullscreenChange();

// Presents the swap chain to the screen.
virtual bool Present();

bool ChangeSurface(void* native_handle);
bool ResizeSwapChain();
void SetStereo(bool stereo);

protected:
u32 GetSwapChainFlags() const;
bool CreateSwapChain(bool stereo);
void DestroySwapChain();

virtual bool CreateSwapChainBuffers() = 0;
virtual void DestroySwapChainBuffers() = 0;

WindowSystemInfo m_wsi;
Microsoft::WRL::ComPtr<IDXGIFactory2> m_dxgi_factory;
Microsoft::WRL::ComPtr<IDXGISwapChain1> m_swap_chain;
Microsoft::WRL::ComPtr<IUnknown> m_d3d_device;
AbstractTextureFormat m_texture_format = AbstractTextureFormat::RGBA8;

u32 m_width = 1;
u32 m_height = 1;

bool m_stereo = false;
bool m_allow_tearing_supported = false;
bool m_has_fullscreen = false;
bool m_fullscreen_request = false;
};

} // namespace D3DCommon
@@ -39,8 +39,6 @@

namespace OGL
{
static constexpr u32 UBO_LENGTH = 32 * 1024 * 1024;

u32 ProgramShaderCache::s_ubo_buffer_size;
s32 ProgramShaderCache::s_ubo_align;
GLuint ProgramShaderCache::s_attributeless_VBO = 0;
@@ -497,7 +495,7 @@ void ProgramShaderCache::Init()
// We multiply by *4*4 because we need to get down to basic machine units.
// So multiply by four to get how many floats we have from vec4s
// Then once more to get bytes
s_buffer = StreamBuffer::Create(GL_UNIFORM_BUFFER, UBO_LENGTH);
s_buffer = StreamBuffer::Create(GL_UNIFORM_BUFFER, VertexManagerBase::UNIFORM_STREAM_BUFFER_SIZE);

CreateHeader();
CreateAttributelessVAO();
@@ -135,6 +135,8 @@ bool VideoBackend::InitializeGLExtensions(GLContext* context)

bool VideoBackend::FillBackendInfo()
{
InitBackendInfo();

// check for the max vertex attributes
GLint numvertexattribs = 0;
glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &numvertexattribs);
@@ -162,17 +164,16 @@ bool VideoBackend::FillBackendInfo()

bool VideoBackend::Initialize(const WindowSystemInfo& wsi)
{
InitializeShared();

std::unique_ptr<GLContext> main_gl_context =
GLContext::Create(wsi, g_ActiveConfig.stereo_mode == StereoMode::QuadBuffer, true, false,
GLContext::Create(wsi, g_Config.stereo_mode == StereoMode::QuadBuffer, true, false,
Config::Get(Config::GFX_PREFER_GLES));
if (!main_gl_context)
return false;

if (!InitializeGLExtensions(main_gl_context.get()) || !FillBackendInfo())
return false;

InitializeShared();
g_renderer = std::make_unique<Renderer>(std::move(main_gl_context), wsi.render_surface_scale);
ProgramShaderCache::Init();
g_vertex_manager = std::make_unique<VertexManager>();
@@ -7,18 +7,13 @@
#include <cstdlib>

#include "Common/CommonFuncs.h"
#include "Common/DynamicLibrary.h"
#include "Common/FileUtil.h"
#include "Common/Logging/Log.h"
#include "Common/StringUtil.h"

#include "VideoBackends/Vulkan/VulkanLoader.h"

#if defined(_WIN32)
#include <Windows.h>
#else
#include <dlfcn.h>
#endif

#define VULKAN_MODULE_ENTRY_POINT(name, required) PFN_##name name;
#define VULKAN_INSTANCE_ENTRY_POINT(name, required) PFN_##name name;
#define VULKAN_DEVICE_ENTRY_POINT(name, required) PFN_##name name;
@@ -40,145 +35,56 @@ static void ResetVulkanLibraryFunctionPointers()
#undef VULKAN_MODULE_ENTRY_POINT
}

#if defined(_WIN32)

static HMODULE vulkan_module;
static std::atomic_int vulkan_module_ref_count = {0};

bool LoadVulkanLibrary()
{
// Not thread safe if a second thread calls the loader whilst the first is still in-progress.
if (vulkan_module)
{
vulkan_module_ref_count++;
return true;
}

vulkan_module = LoadLibraryA("vulkan-1.dll");
if (!vulkan_module)
{
ERROR_LOG(VIDEO, "Failed to load vulkan-1.dll");
return false;
}

bool required_functions_missing = false;
auto LoadFunction = [&](FARPROC* func_ptr, const char* name, bool is_required) {
*func_ptr = GetProcAddress(vulkan_module, name);
if (!(*func_ptr) && is_required)
{
ERROR_LOG(VIDEO, "Vulkan: Failed to load required module function %s", name);
required_functions_missing = true;
}
};

#define VULKAN_MODULE_ENTRY_POINT(name, required) \
LoadFunction(reinterpret_cast<FARPROC*>(&name), #name, required);
#include "VideoBackends/Vulkan/VulkanEntryPoints.inl"
#undef VULKAN_MODULE_ENTRY_POINT

if (required_functions_missing)
{
ResetVulkanLibraryFunctionPointers();
FreeLibrary(vulkan_module);
vulkan_module = nullptr;
return false;
}

vulkan_module_ref_count++;
return true;
}

void UnloadVulkanLibrary()
{
if ((--vulkan_module_ref_count) > 0)
return;

ResetVulkanLibraryFunctionPointers();
FreeLibrary(vulkan_module);
vulkan_module = nullptr;
}

#else

static void* vulkan_module;
static std::atomic_int vulkan_module_ref_count = {0};
static Common::DynamicLibrary s_vulkan_module;

bool LoadVulkanLibrary()
static std::string GetVulkanLibraryFilename()
{
// Not thread safe if a second thread calls the loader whilst the first is still in-progress.
if (vulkan_module)
{
vulkan_module_ref_count++;
return true;
}

#if defined(__APPLE__)
#ifdef __APPLE__
// Check if a path to a specific Vulkan library has been specified.
char* libvulkan_env = getenv("LIBVULKAN_PATH");
if (libvulkan_env)
vulkan_module = dlopen(libvulkan_env, RTLD_NOW);
if (!vulkan_module)
{
// Use the libvulkan.dylib from the application bundle.
std::string path = File::GetBundleDirectory() + "/Contents/Frameworks/libvulkan.dylib";
vulkan_module = dlopen(path.c_str(), RTLD_NOW);
}
return std::string(libvulkan_env);

// Use the libvulkan.dylib from the application bundle.
return File::GetBundleDirectory() + "/Contents/Frameworks/libvulkan.dylib";
#else
// Names of libraries to search. Desktop should use libvulkan.so.1 or libvulkan.so.
static const char* search_lib_names[] = {"libvulkan.so.1", "libvulkan.so"};
for (size_t i = 0; i < ArraySize(search_lib_names); i++)
{
vulkan_module = dlopen(search_lib_names[i], RTLD_NOW);
if (vulkan_module)
break;
}
return Common::DynamicLibrary::GetVersionedFilename("vulkan", 1);
#endif
}

if (!vulkan_module)
bool LoadVulkanLibrary()
{
if (!s_vulkan_module.IsOpen())
{
ERROR_LOG(VIDEO, "Failed to load or locate libvulkan.so");
return false;
}

bool required_functions_missing = false;
auto LoadFunction = [&](void** func_ptr, const char* name, bool is_required) {
*func_ptr = dlsym(vulkan_module, name);
if (!(*func_ptr) && is_required)
const std::string filename = GetVulkanLibraryFilename();
if (!s_vulkan_module.Open(filename.c_str()))
{
ERROR_LOG(VIDEO, "Vulkan: Failed to load required module function %s", name);
required_functions_missing = true;
ERROR_LOG(VIDEO, "Failed to load %s", filename.c_str());
return false;
}
};
}

#define VULKAN_MODULE_ENTRY_POINT(name, required) \
LoadFunction(reinterpret_cast<void**>(&name), #name, required);
if (!s_vulkan_module.GetSymbol(#name, &name) && required) \
{ \
ERROR_LOG(VIDEO, "Vulkan: Failed to load required module function %s", #name); \
ResetVulkanLibraryFunctionPointers(); \
s_vulkan_module.Close(); \
return false; \
}
#include "VideoBackends/Vulkan/VulkanEntryPoints.inl"
#undef VULKAN_MODULE_ENTRY_POINT

if (required_functions_missing)
{
ResetVulkanLibraryFunctionPointers();
dlclose(vulkan_module);
vulkan_module = nullptr;
return false;
}

vulkan_module_ref_count++;
return true;
}

void UnloadVulkanLibrary()
{
if ((--vulkan_module_ref_count) > 0)
return;

ResetVulkanLibraryFunctionPointers();
dlclose(vulkan_module);
vulkan_module = nullptr;
s_vulkan_module.Close();
if (!s_vulkan_module.IsOpen())
ResetVulkanLibraryFunctionPointers();
}

#endif

bool LoadVulkanInstanceFunctions(VkInstance instance)
{
bool required_functions_missing = false;
@@ -151,6 +151,11 @@ std::unique_ptr<AbstractShader> Renderer::CreateShaderFromSource(ShaderStage sta
return CreateShaderFromSource(stage, source.c_str(), source.size());
}

bool Renderer::EFBHasAlphaChannel() const
{
return m_prev_efb_format == PEControl::RGBA6_Z24;
}

void Renderer::ClearScreen(const EFBRectangle& rc, bool colorEnable, bool alphaEnable, bool zEnable,
u32 color, u32 z)
{
@@ -224,6 +224,7 @@ class Renderer

PEControl::PixelFormat GetPrevPixelFormat() const { return m_prev_efb_format; }
void StorePixelFormat(PEControl::PixelFormat new_format) { m_prev_efb_format = new_format; }
bool EFBHasAlphaChannel() const;
VideoCommon::PostProcessing* GetPostProcessor() const { return m_post_processor.get(); }
// Final surface changing
// This is called when the surface is resized (WX) or the window changes (Android).
@@ -966,10 +966,16 @@ void ShaderCache::QueueUberShaderPipelines()
config.vs_uid = vs_uid;
config.gs_uid = gs_uid;
config.ps_uid = ps_uid;
config.rasterization_state =
RenderState::GetCullBackFaceRasterizationState(PrimitiveType::TriangleStrip);
config.rasterization_state = RenderState::GetCullBackFaceRasterizationState(
static_cast<PrimitiveType>(gs_uid.GetUidData()->primitive_type));
config.depth_state = RenderState::GetNoDepthTestingDepthState();
config.blending_state = RenderState::GetNoBlendingBlendState();
if (ps_uid.GetUidData()->uint_output)
{
// uint_output is only ever enabled when logic ops are enabled.
config.blending_state.logicopenable = true;
config.blending_state.logicmode = BlendMode::AND;
}

auto iter = m_gx_uber_pipeline_cache.find(config);
if (iter != m_gx_uber_pipeline_cache.end())
@@ -986,13 +992,15 @@ void ShaderCache::QueueUberShaderPipelines()
if (vuid.GetUidData()->num_texgens != puid.GetUidData()->num_texgens)
return;

UberShader::PixelShaderUid cleared_puid = puid;
UberShader::ClearUnusedPixelShaderUidBits(m_api_type, m_host_config, &cleared_puid);
EnumerateGeometryShaderUids([&](const GeometryShaderUid& guid) {
if (guid.GetUidData()->numTexGens != vuid.GetUidData()->num_texgens ||
(!guid.GetUidData()->IsPassthrough() && !m_host_config.backend_geometry_shaders))
{
return;
}
QueueDummyPipeline(vuid, guid, puid);
QueueDummyPipeline(vuid, guid, cleared_puid);
});
});
});
@@ -54,9 +54,9 @@ class VertexManagerBase

// Streaming buffer sizes.
// Texel buffer will fit the maximum size of an encoded GX texture. 1024x1024, RGBA8 = 4MB.
static constexpr u32 VERTEX_STREAM_BUFFER_SIZE = 40 * 1024 * 1024;
static constexpr u32 INDEX_STREAM_BUFFER_SIZE = 4 * 1024 * 1024;
static constexpr u32 UNIFORM_STREAM_BUFFER_SIZE = 16 * 1024 * 1024;
static constexpr u32 VERTEX_STREAM_BUFFER_SIZE = 48 * 1024 * 1024;
static constexpr u32 INDEX_STREAM_BUFFER_SIZE = 8 * 1024 * 1024;
static constexpr u32 UNIFORM_STREAM_BUFFER_SIZE = 32 * 1024 * 1024;
static constexpr u32 TEXEL_STREAM_BUFFER_SIZE = 16 * 1024 * 1024;

VertexManagerBase();
@@ -294,6 +294,7 @@ void VideoBackendBase::InitializeShared()
GeometryShaderManager::Init();
PixelShaderManager::Init();

g_Config.VerifyValidity();
UpdateActiveConfig();
}

@@ -93,6 +93,8 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "imgui", "..\Externals\imgui
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "UpdaterCommon", "Core\UpdaterCommon\UpdaterCommon.vcxproj", "{B001D13E-7EAB-4689-842D-801E5ACFFAC5}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "D3DCommon", "Core\VideoBackends\D3DCommon\D3DCommon.vcxproj", "{DEA96CF2-F237-4A1A-B32F-C916769EFB50}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
@@ -353,6 +355,12 @@ Global
{B001D13E-7EAB-4689-842D-801E5ACFFAC5}.Release|x64.ActiveCfg = Release|x64
{B001D13E-7EAB-4689-842D-801E5ACFFAC5}.Release|x64.Build.0 = Release|x64
{B001D13E-7EAB-4689-842D-801E5ACFFAC5}.Release|x86.ActiveCfg = Release|x64
{DEA96CF2-F237-4A1A-B32F-C916769EFB50}.Debug|x64.ActiveCfg = Debug|x64
{DEA96CF2-F237-4A1A-B32F-C916769EFB50}.Debug|x64.Build.0 = Debug|x64
{DEA96CF2-F237-4A1A-B32F-C916769EFB50}.Debug|x86.ActiveCfg = Debug|x64
{DEA96CF2-F237-4A1A-B32F-C916769EFB50}.Release|x64.ActiveCfg = Release|x64
{DEA96CF2-F237-4A1A-B32F-C916769EFB50}.Release|x64.Build.0 = Release|x64
{DEA96CF2-F237-4A1A-B32F-C916769EFB50}.Release|x86.ActiveCfg = Release|x64
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -394,6 +402,7 @@ Global
{4482FD2A-EC43-3FFB-AC20-2E5C54B05EAD} = {87ADDFF9-5768-4DA2-A33B-2477593D6677}
{23114507-079A-4418-9707-CFA81A03CA99} = {87ADDFF9-5768-4DA2-A33B-2477593D6677}
{4C3B2264-EA73-4A7B-9CFE-65B0FD635EBB} = {87ADDFF9-5768-4DA2-A33B-2477593D6677}
{DEA96CF2-F237-4A1A-B32F-C916769EFB50} = {AAD1BCD6-9804-44A5-A5FC-4782EA00E9D4}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {710976F2-1BC7-4F2A-B32D-5DD2BBCB44E1}