summaryrefslogtreecommitdiff
path: root/Source/Core/VideoBackends/Vulkan
diff options
context:
space:
mode:
authorTilka <tilkax@gmail.com>2019-02-26 04:21:05 +0000
committerGitHub <noreply@github.com>2019-02-26 04:21:05 +0000
commit6ce7f44b8a0bb3b95d3f12ebffbef7a71a443fdd (patch)
tree98380ce3a3284c52597a6fba86589c847219ecd5 /Source/Core/VideoBackends/Vulkan
parent19673ce79af814ca3b77d7f8ea60458e564bfa51 (diff)
parentf039149198657c1891e1c6462ed30c31ed4b8486 (diff)
Merge pull request #7753 from stenzek/videocommon-all-the-things
Move a significant amount of video backend logic to VideoCommon
Diffstat (limited to 'Source/Core/VideoBackends/Vulkan')
-rw-r--r--Source/Core/VideoBackends/Vulkan/BoundingBox.cpp21
-rw-r--r--Source/Core/VideoBackends/Vulkan/BoundingBox.h3
-rw-r--r--Source/Core/VideoBackends/Vulkan/CMakeLists.txt7
-rw-r--r--Source/Core/VideoBackends/Vulkan/CommandBufferManager.cpp140
-rw-r--r--Source/Core/VideoBackends/Vulkan/CommandBufferManager.h63
-rw-r--r--Source/Core/VideoBackends/Vulkan/Constants.h87
-rw-r--r--Source/Core/VideoBackends/Vulkan/FramebufferManager.cpp1198
-rw-r--r--Source/Core/VideoBackends/Vulkan/FramebufferManager.h161
-rw-r--r--Source/Core/VideoBackends/Vulkan/ObjectCache.cpp357
-rw-r--r--Source/Core/VideoBackends/Vulkan/ObjectCache.h49
-rw-r--r--Source/Core/VideoBackends/Vulkan/PerfQuery.cpp56
-rw-r--r--Source/Core/VideoBackends/Vulkan/PerfQuery.h6
-rw-r--r--Source/Core/VideoBackends/Vulkan/PostProcessing.cpp316
-rw-r--r--Source/Core/VideoBackends/Vulkan/PostProcessing.h44
-rw-r--r--Source/Core/VideoBackends/Vulkan/Renderer.cpp527
-rw-r--r--Source/Core/VideoBackends/Vulkan/Renderer.h45
-rw-r--r--Source/Core/VideoBackends/Vulkan/ShaderCache.cpp859
-rw-r--r--Source/Core/VideoBackends/Vulkan/ShaderCache.h145
-rw-r--r--Source/Core/VideoBackends/Vulkan/ShaderCompiler.cpp10
-rw-r--r--Source/Core/VideoBackends/Vulkan/StagingBuffer.cpp35
-rw-r--r--Source/Core/VideoBackends/Vulkan/StagingBuffer.h9
-rw-r--r--Source/Core/VideoBackends/Vulkan/StateTracker.cpp805
-rw-r--r--Source/Core/VideoBackends/Vulkan/StateTracker.h158
-rw-r--r--Source/Core/VideoBackends/Vulkan/StreamBuffer.cpp124
-rw-r--r--Source/Core/VideoBackends/Vulkan/StreamBuffer.h33
-rw-r--r--Source/Core/VideoBackends/Vulkan/SwapChain.cpp98
-rw-r--r--Source/Core/VideoBackends/Vulkan/SwapChain.h27
-rw-r--r--Source/Core/VideoBackends/Vulkan/Texture2D.cpp404
-rw-r--r--Source/Core/VideoBackends/Vulkan/Texture2D.h79
-rw-r--r--Source/Core/VideoBackends/Vulkan/TextureCache.cpp316
-rw-r--r--Source/Core/VideoBackends/Vulkan/TextureCache.h65
-rw-r--r--Source/Core/VideoBackends/Vulkan/TextureConverter.cpp634
-rw-r--r--Source/Core/VideoBackends/Vulkan/TextureConverter.h109
-rw-r--r--Source/Core/VideoBackends/Vulkan/Util.cpp925
-rw-r--r--Source/Core/VideoBackends/Vulkan/Util.h235
-rw-r--r--Source/Core/VideoBackends/Vulkan/VKPipeline.cpp363
-rw-r--r--Source/Core/VideoBackends/Vulkan/VKShader.cpp43
-rw-r--r--Source/Core/VideoBackends/Vulkan/VKTexture.cpp812
-rw-r--r--Source/Core/VideoBackends/Vulkan/VKTexture.h76
-rw-r--r--Source/Core/VideoBackends/Vulkan/VertexFormat.cpp48
-rw-r--r--Source/Core/VideoBackends/Vulkan/VertexFormat.h4
-rw-r--r--Source/Core/VideoBackends/Vulkan/VertexManager.cpp352
-rw-r--r--Source/Core/VideoBackends/Vulkan/VertexManager.h37
-rw-r--r--Source/Core/VideoBackends/Vulkan/Vulkan.vcxproj14
-rw-r--r--Source/Core/VideoBackends/Vulkan/VulkanContext.cpp28
-rw-r--r--Source/Core/VideoBackends/Vulkan/VulkanContext.h4
-rw-r--r--Source/Core/VideoBackends/Vulkan/main.cpp54
47 files changed, 2486 insertions, 7499 deletions
diff --git a/Source/Core/VideoBackends/Vulkan/BoundingBox.cpp b/Source/Core/VideoBackends/Vulkan/BoundingBox.cpp
index 169404d7ca..9e7da60249 100644
--- a/Source/Core/VideoBackends/Vulkan/BoundingBox.cpp
+++ b/Source/Core/VideoBackends/Vulkan/BoundingBox.cpp
@@ -13,7 +13,6 @@
#include "VideoBackends/Vulkan/Renderer.h"
#include "VideoBackends/Vulkan/StagingBuffer.h"
#include "VideoBackends/Vulkan/StateTracker.h"
-#include "VideoBackends/Vulkan/Util.h"
#include "VideoBackends/Vulkan/VulkanContext.h"
namespace Vulkan
@@ -33,7 +32,7 @@ BoundingBox::~BoundingBox()
bool BoundingBox::Initialize()
{
- if (!g_vulkan_context->SupportsBoundingBox())
+ if (!g_ActiveConfig.backend_info.bSupportsBBox)
{
WARN_LOG(VIDEO, "Vulkan: Bounding box is unsupported by your device.");
return true;
@@ -45,6 +44,8 @@ bool BoundingBox::Initialize()
if (!CreateReadbackBuffer())
return false;
+ // Bind bounding box to state tracker
+ StateTracker::GetInstance()->SetSSBO(m_gpu_buffer, 0, BUFFER_SIZE);
return true;
}
@@ -79,7 +80,7 @@ void BoundingBox::Flush()
StateTracker::GetInstance()->EndRenderPass();
// Ensure GPU buffer is in a state where it can be transferred to.
- Util::BufferMemoryBarrier(
+ StagingBuffer::BufferMemoryBarrier(
g_command_buffer_mgr->GetCurrentCommandBuffer(), m_gpu_buffer,
VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, 0,
BUFFER_SIZE, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
@@ -95,7 +96,7 @@ void BoundingBox::Flush()
// Restore fragment shader access to the buffer.
if (updated_buffer)
{
- Util::BufferMemoryBarrier(
+ StagingBuffer::BufferMemoryBarrier(
g_command_buffer_mgr->GetCurrentCommandBuffer(), m_gpu_buffer, VK_ACCESS_TRANSFER_WRITE_BIT,
VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT, 0, BUFFER_SIZE,
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT);
@@ -219,7 +220,7 @@ void BoundingBox::Readback()
StateTracker::GetInstance()->EndRenderPass();
// Ensure all writes are completed to the GPU buffer prior to the transfer.
- Util::BufferMemoryBarrier(
+ StagingBuffer::BufferMemoryBarrier(
g_command_buffer_mgr->GetCurrentCommandBuffer(), m_gpu_buffer,
VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT, 0,
BUFFER_SIZE, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
@@ -233,15 +234,15 @@ void BoundingBox::Readback()
m_readback_buffer->GetBuffer(), 1, &region);
// Restore GPU buffer access.
- Util::BufferMemoryBarrier(g_command_buffer_mgr->GetCurrentCommandBuffer(), m_gpu_buffer,
- VK_ACCESS_TRANSFER_READ_BIT,
- VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT, 0, BUFFER_SIZE,
- VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT);
+ StagingBuffer::BufferMemoryBarrier(
+ g_command_buffer_mgr->GetCurrentCommandBuffer(), m_gpu_buffer, VK_ACCESS_TRANSFER_READ_BIT,
+ VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT, 0, BUFFER_SIZE,
+ VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT);
m_readback_buffer->FlushGPUCache(g_command_buffer_mgr->GetCurrentCommandBuffer(),
VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
// Wait until these commands complete.
- Util::ExecuteCurrentCommandsAndRestoreState(false, true);
+ Renderer::GetInstance()->ExecuteCommandBuffer(false, true);
// Cache is now valid.
m_readback_buffer->InvalidateCPUCache();
diff --git a/Source/Core/VideoBackends/Vulkan/BoundingBox.h b/Source/Core/VideoBackends/Vulkan/BoundingBox.h
index 872f49aa31..e5fda1066a 100644
--- a/Source/Core/VideoBackends/Vulkan/BoundingBox.h
+++ b/Source/Core/VideoBackends/Vulkan/BoundingBox.h
@@ -24,9 +24,6 @@ public:
bool Initialize();
- VkBuffer GetGPUBuffer() const { return m_gpu_buffer; }
- VkDeviceSize GetGPUBufferOffset() const { return 0; }
- VkDeviceSize GetGPUBufferSize() const { return BUFFER_SIZE; }
s32 Get(size_t index);
void Set(size_t index, s32 value);
diff --git a/Source/Core/VideoBackends/Vulkan/CMakeLists.txt b/Source/Core/VideoBackends/Vulkan/CMakeLists.txt
index 5746cd1aaa..014a3378c8 100644
--- a/Source/Core/VideoBackends/Vulkan/CMakeLists.txt
+++ b/Source/Core/VideoBackends/Vulkan/CMakeLists.txt
@@ -1,21 +1,14 @@
add_library(videovulkan
BoundingBox.cpp
CommandBufferManager.cpp
- FramebufferManager.cpp
ObjectCache.cpp
PerfQuery.cpp
- PostProcessing.cpp
Renderer.cpp
- ShaderCache.cpp
ShaderCompiler.cpp
StateTracker.cpp
StagingBuffer.cpp
StreamBuffer.cpp
SwapChain.cpp
- Texture2D.cpp
- TextureCache.cpp
- TextureConverter.cpp
- Util.cpp
VertexFormat.cpp
VertexManager.cpp
VKPipeline.cpp
diff --git a/Source/Core/VideoBackends/Vulkan/CommandBufferManager.cpp b/Source/Core/VideoBackends/Vulkan/CommandBufferManager.cpp
index ea07d47a53..1f2fcd01c7 100644
--- a/Source/Core/VideoBackends/Vulkan/CommandBufferManager.cpp
+++ b/Source/Core/VideoBackends/Vulkan/CommandBufferManager.cpp
@@ -44,12 +44,16 @@ bool CommandBufferManager::Initialize()
bool CommandBufferManager::CreateCommandBuffers()
{
+ static constexpr VkSemaphoreCreateInfo semaphore_create_info = {
+ VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, nullptr, 0};
+
VkDevice device = g_vulkan_context->GetDevice();
VkResult res;
for (FrameResources& resources : m_frame_resources)
{
resources.init_command_buffer_used = false;
+ resources.semaphore_used = false;
resources.needs_fence_wait = false;
VkCommandPoolCreateInfo pool_info = {VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, nullptr, 0,
@@ -83,6 +87,13 @@ bool CommandBufferManager::CreateCommandBuffers()
return false;
}
+ res = vkCreateSemaphore(device, &semaphore_create_info, nullptr, &resources.semaphore);
+ if (res != VK_SUCCESS)
+ {
+ LOG_VULKAN_ERROR(res, "vkCreateSemaphore failed: ");
+ return false;
+ }
+
// TODO: A better way to choose the number of descriptors.
VkDescriptorPoolSize pool_sizes[] = {{VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 500000},
{VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 500000},
@@ -105,9 +116,16 @@ bool CommandBufferManager::CreateCommandBuffers()
}
}
+ res = vkCreateSemaphore(device, &semaphore_create_info, nullptr, &m_present_semaphore);
+ if (res != VK_SUCCESS)
+ {
+ LOG_VULKAN_ERROR(res, "vkCreateSemaphore failed: ");
+ return false;
+ }
+
// Activate the first command buffer. ActivateCommandBuffer moves forward, so start with the last
- m_current_frame = m_frame_resources.size() - 1;
- ActivateCommandBuffer();
+ m_current_frame = static_cast<u32>(m_frame_resources.size()) - 1;
+ BeginCommandBuffer();
return true;
}
@@ -122,28 +140,23 @@ void CommandBufferManager::DestroyCommandBuffers()
// We destroy the command pool first, to avoid any warnings from the validation layers about
// objects which are pending destruction being in-use.
if (resources.command_pool != VK_NULL_HANDLE)
- {
vkDestroyCommandPool(device, resources.command_pool, nullptr);
- resources.command_pool = VK_NULL_HANDLE;
- }
// Destroy any pending objects.
for (auto& it : resources.cleanup_resources)
it();
- resources.cleanup_resources.clear();
+
+ if (resources.semaphore != VK_NULL_HANDLE)
+ vkDestroySemaphore(device, resources.semaphore, nullptr);
if (resources.fence != VK_NULL_HANDLE)
- {
vkDestroyFence(device, resources.fence, nullptr);
- resources.fence = VK_NULL_HANDLE;
- }
if (resources.descriptor_pool != VK_NULL_HANDLE)
- {
vkDestroyDescriptorPool(device, resources.descriptor_pool, nullptr);
- resources.descriptor_pool = VK_NULL_HANDLE;
- }
}
+
+ vkDestroySemaphore(device, m_present_semaphore, nullptr);
}
VkDescriptorSet CommandBufferManager::AllocateDescriptorSet(VkDescriptorSetLayout set_layout)
@@ -183,22 +196,14 @@ bool CommandBufferManager::CreateSubmitThread()
m_pending_submits.pop_front();
}
- SubmitCommandBuffer(submit.index, submit.wait_semaphore, submit.signal_semaphore,
- submit.present_swap_chain, submit.present_image_index);
+ SubmitCommandBuffer(submit.command_buffer_index, submit.present_swap_chain,
+ submit.present_image_index);
});
});
return true;
}
-void CommandBufferManager::PrepareToSubmitCommandBuffer()
-{
- // Grab the semaphore before submitting command buffer either on-thread or off-thread.
- // This prevents a race from occurring where a second command buffer is executed
- // before the worker thread has woken and executed the first one yet.
- m_submit_semaphore.Wait();
-}
-
void CommandBufferManager::WaitForWorkerThreadIdle()
{
// Drain the semaphore, then allow another request in the future.
@@ -215,8 +220,8 @@ void CommandBufferManager::WaitForGPUIdle()
void CommandBufferManager::WaitForFence(VkFence fence)
{
// Find the command buffer that this fence corresponds to.
- size_t command_buffer_index = 0;
- for (; command_buffer_index < m_frame_resources.size(); command_buffer_index++)
+ u32 command_buffer_index = 0;
+ for (; command_buffer_index < static_cast<u32>(m_frame_resources.size()); command_buffer_index++)
{
if (m_frame_resources[command_buffer_index].fence == fence)
break;
@@ -227,6 +232,9 @@ void CommandBufferManager::WaitForFence(VkFence fence)
if (!m_frame_resources[command_buffer_index].needs_fence_wait)
return;
+ // Ensure this command buffer has been submitted.
+ WaitForWorkerThreadIdle();
+
// Wait for this command buffer to be completed.
VkResult res =
vkWaitForFences(g_vulkan_context->GetDevice(), 1,
@@ -240,19 +248,11 @@ void CommandBufferManager::WaitForFence(VkFence fence)
}
void CommandBufferManager::SubmitCommandBuffer(bool submit_on_worker_thread,
- VkSemaphore wait_semaphore,
- VkSemaphore signal_semaphore,
VkSwapchainKHR present_swap_chain,
uint32_t present_image_index)
{
- FrameResources& resources = m_frame_resources[m_current_frame];
-
- // Fire fence tracking callbacks. This can't happen on the worker thread.
- // We invoke these before submitting so that any last-minute commands can be added.
- for (const auto& iter : m_fence_point_callbacks)
- iter.second.first(resources.command_buffers[1], resources.fence);
-
// End the current command buffer.
+ FrameResources& resources = m_frame_resources[m_current_frame];
for (VkCommandBuffer command_buffer : resources.command_buffers)
{
VkResult res = vkEndCommandBuffer(command_buffer);
@@ -266,14 +266,18 @@ void CommandBufferManager::SubmitCommandBuffer(bool submit_on_worker_thread,
// This command buffer now has commands, so can't be re-used without waiting.
resources.needs_fence_wait = true;
+ // Grab the semaphore before submitting command buffer either on-thread or off-thread.
+ // This prevents a race from occurring where a second command buffer is executed
+ // before the worker thread has woken and executed the first one yet.
+ m_submit_semaphore.Wait();
+
// Submitting off-thread?
if (m_use_threaded_submission && submit_on_worker_thread)
{
// Push to the pending submit queue.
{
std::lock_guard<std::mutex> guard(m_pending_submit_lock);
- m_pending_submits.push_back({m_current_frame, wait_semaphore, signal_semaphore,
- present_swap_chain, present_image_index});
+ m_pending_submits.push_back({present_swap_chain, present_image_index, m_current_frame});
}
// Wake up the worker thread for a single iteration.
@@ -282,17 +286,18 @@ void CommandBufferManager::SubmitCommandBuffer(bool submit_on_worker_thread,
else
{
// Pass through to normal submission path.
- SubmitCommandBuffer(m_current_frame, wait_semaphore, signal_semaphore, present_swap_chain,
- present_image_index);
+ SubmitCommandBuffer(m_current_frame, present_swap_chain, present_image_index);
}
+
+ // Switch to next cmdbuffer.
+ BeginCommandBuffer();
}
-void CommandBufferManager::SubmitCommandBuffer(size_t index, VkSemaphore wait_semaphore,
- VkSemaphore signal_semaphore,
+void CommandBufferManager::SubmitCommandBuffer(u32 command_buffer_index,
VkSwapchainKHR present_swap_chain,
- uint32_t present_image_index)
+ u32 present_image_index)
{
- FrameResources& resources = m_frame_resources[index];
+ FrameResources& resources = m_frame_resources[command_buffer_index];
// This may be executed on the worker thread, so don't modify any state of the manager class.
uint32_t wait_bits = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
@@ -307,22 +312,22 @@ void CommandBufferManager::SubmitCommandBuffer(size_t index, VkSemaphore wait_se
nullptr};
// If the init command buffer did not have any commands recorded, don't submit it.
- if (!m_frame_resources[index].init_command_buffer_used)
+ if (!resources.init_command_buffer_used)
{
submit_info.commandBufferCount = 1;
- submit_info.pCommandBuffers = &m_frame_resources[index].command_buffers[1];
+ submit_info.pCommandBuffers = &resources.command_buffers[1];
}
- if (wait_semaphore != VK_NULL_HANDLE)
+ if (resources.semaphore_used != VK_NULL_HANDLE)
{
- submit_info.pWaitSemaphores = &wait_semaphore;
+ submit_info.pWaitSemaphores = &resources.semaphore;
submit_info.waitSemaphoreCount = 1;
}
- if (signal_semaphore != VK_NULL_HANDLE)
+ if (present_swap_chain != VK_NULL_HANDLE)
{
submit_info.signalSemaphoreCount = 1;
- submit_info.pSignalSemaphores = &signal_semaphore;
+ submit_info.pSignalSemaphores = &m_present_semaphore;
}
VkResult res =
@@ -337,11 +342,10 @@ void CommandBufferManager::SubmitCommandBuffer(size_t index, VkSemaphore wait_se
if (present_swap_chain != VK_NULL_HANDLE)
{
// Should have a signal semaphore.
- ASSERT(signal_semaphore != VK_NULL_HANDLE);
VkPresentInfoKHR present_info = {VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
nullptr,
1,
- &signal_semaphore,
+ &m_present_semaphore,
1,
&present_swap_chain,
&present_image_index,
@@ -361,15 +365,15 @@ void CommandBufferManager::SubmitCommandBuffer(size_t index, VkSemaphore wait_se
m_submit_semaphore.Post();
}
-void CommandBufferManager::OnCommandBufferExecuted(size_t index)
+void CommandBufferManager::OnCommandBufferExecuted(u32 index)
{
FrameResources& resources = m_frame_resources[index];
// Fire fence tracking callbacks.
- for (auto iter = m_fence_point_callbacks.begin(); iter != m_fence_point_callbacks.end();)
+ for (auto iter = m_fence_callbacks.begin(); iter != m_fence_callbacks.end();)
{
auto backup_iter = iter++;
- backup_iter->second.second(resources.fence);
+ backup_iter->second(resources.fence);
}
// Clean up all objects pending destruction on this command buffer
@@ -378,7 +382,7 @@ void CommandBufferManager::OnCommandBufferExecuted(size_t index)
resources.cleanup_resources.clear();
}
-void CommandBufferManager::ActivateCommandBuffer()
+void CommandBufferManager::BeginCommandBuffer()
{
// Move to the next command buffer.
m_current_frame = (m_current_frame + 1) % NUM_COMMAND_BUFFERS;
@@ -422,19 +426,7 @@ void CommandBufferManager::ActivateCommandBuffer()
// Reset upload command buffer state
resources.init_command_buffer_used = false;
-}
-
-void CommandBufferManager::ExecuteCommandBuffer(bool submit_off_thread, bool wait_for_completion)
-{
- VkFence pending_fence = GetCurrentCommandBufferFence();
-
- // If we're waiting for completion, don't bother waking the worker thread.
- PrepareToSubmitCommandBuffer();
- SubmitCommandBuffer((submit_off_thread && wait_for_completion));
- ActivateCommandBuffer();
-
- if (wait_for_completion)
- WaitForFence(pending_fence);
+ resources.semaphore_used = false;
}
void CommandBufferManager::DeferBufferDestruction(VkBuffer object)
@@ -479,20 +471,18 @@ void CommandBufferManager::DeferImageViewDestruction(VkImageView object)
[object]() { vkDestroyImageView(g_vulkan_context->GetDevice(), object, nullptr); });
}
-void CommandBufferManager::AddFencePointCallback(
- const void* key, const CommandBufferQueuedCallback& queued_callback,
- const CommandBufferExecutedCallback& executed_callback)
+void CommandBufferManager::AddFenceSignaledCallback(const void* key, FenceSignaledCallback callback)
{
// Shouldn't be adding twice.
- ASSERT(m_fence_point_callbacks.find(key) == m_fence_point_callbacks.end());
- m_fence_point_callbacks.emplace(key, std::make_pair(queued_callback, executed_callback));
+ ASSERT(m_fence_callbacks.find(key) == m_fence_callbacks.end());
+ m_fence_callbacks.emplace(key, std::move(callback));
}
-void CommandBufferManager::RemoveFencePointCallback(const void* key)
+void CommandBufferManager::RemoveFenceSignaledCallback(const void* key)
{
- auto iter = m_fence_point_callbacks.find(key);
- ASSERT(iter != m_fence_point_callbacks.end());
- m_fence_point_callbacks.erase(iter);
+ auto iter = m_fence_callbacks.find(key);
+ ASSERT(iter != m_fence_callbacks.end());
+ m_fence_callbacks.erase(iter);
}
std::unique_ptr<CommandBufferManager> g_command_buffer_mgr;
diff --git a/Source/Core/VideoBackends/Vulkan/CommandBufferManager.h b/Source/Core/VideoBackends/Vulkan/CommandBufferManager.h
index 9cefe100d7..9cfc50e287 100644
--- a/Source/Core/VideoBackends/Vulkan/CommandBufferManager.h
+++ b/Source/Core/VideoBackends/Vulkan/CommandBufferManager.h
@@ -22,7 +22,6 @@
#include "VideoCommon/VideoCommon.h"
#include "VideoBackends/Vulkan/Constants.h"
-#include "VideoBackends/Vulkan/Util.h"
namespace Vulkan
{
@@ -55,8 +54,14 @@ public:
// Gets the fence that will be signaled when the currently executing command buffer is
// queued and executed. Do not wait for this fence before the buffer is executed.
VkFence GetCurrentCommandBufferFence() const { return m_frame_resources[m_current_frame].fence; }
- // Ensure the worker thread has submitted the previous frame's command buffer.
- void PrepareToSubmitCommandBuffer();
+
+ // Returns the semaphore for the current command buffer, which can be used to ensure the
+ // swap chain image is ready before the command buffer executes.
+ VkSemaphore GetCurrentCommandBufferSemaphore()
+ {
+ m_frame_resources[m_current_frame].semaphore_used = true;
+ return m_frame_resources[m_current_frame].semaphore;
+ }
// Ensure that the worker thread has submitted any previous command buffers and is idle.
void WaitForWorkerThreadIdle();
@@ -70,17 +75,12 @@ public:
void WaitForFence(VkFence fence);
void SubmitCommandBuffer(bool submit_on_worker_thread,
- VkSemaphore wait_semaphore = VK_NULL_HANDLE,
- VkSemaphore signal_semaphore = VK_NULL_HANDLE,
VkSwapchainKHR present_swap_chain = VK_NULL_HANDLE,
uint32_t present_image_index = 0xFFFFFFFF);
- void ActivateCommandBuffer();
-
- void ExecuteCommandBuffer(bool submit_off_thread, bool wait_for_completion);
-
// Was the last present submitted to the queue a failure? If so, we must recreate our swapchain.
bool CheckLastPresentFail() { return m_present_failed_flag.TestAndClear(); }
+
// Schedule a vulkan resource for destruction later on. This will occur when the command buffer
// is next re-used, and the GPU has finished working with the specified resource.
void DeferBufferDestruction(VkBuffer object);
@@ -93,13 +93,9 @@ public:
// Instruct the manager to fire the specified callback when a fence is flagged to be signaled.
// This happens when command buffers are executed, and can be tested if signaled, which means
// that all commands up to the point when the callback was fired have completed.
- using CommandBufferQueuedCallback = std::function<void(VkCommandBuffer, VkFence)>;
- using CommandBufferExecutedCallback = std::function<void(VkFence)>;
-
- void AddFencePointCallback(const void* key, const CommandBufferQueuedCallback& queued_callback,
- const CommandBufferExecutedCallback& executed_callback);
-
- void RemoveFencePointCallback(const void* key);
+ using FenceSignaledCallback = std::function<void(VkFence)>;
+ void AddFenceSignaledCallback(const void* key, FenceSignaledCallback callback);
+ void RemoveFenceSignaledCallback(const void* key);
private:
bool CreateCommandBuffers();
@@ -107,30 +103,32 @@ private:
bool CreateSubmitThread();
- void SubmitCommandBuffer(size_t index, VkSemaphore wait_semaphore, VkSemaphore signal_semaphore,
- VkSwapchainKHR present_swap_chain, uint32_t present_image_index);
+ void SubmitCommandBuffer(u32 command_buffer_index, VkSwapchainKHR present_swap_chain,
+ u32 present_image_index);
+ void BeginCommandBuffer();
- void OnCommandBufferExecuted(size_t index);
+ void OnCommandBufferExecuted(u32 index);
struct FrameResources
{
// [0] - Init (upload) command buffer, [1] - draw command buffer
- VkCommandPool command_pool;
- std::array<VkCommandBuffer, 2> command_buffers;
- VkDescriptorPool descriptor_pool;
- VkFence fence;
- bool init_command_buffer_used;
- bool needs_fence_wait;
+ VkCommandPool command_pool = VK_NULL_HANDLE;
+ std::array<VkCommandBuffer, 2> command_buffers = {};
+ VkDescriptorPool descriptor_pool = VK_NULL_HANDLE;
+ VkFence fence = VK_NULL_HANDLE;
+ VkSemaphore semaphore = VK_NULL_HANDLE;
+ bool init_command_buffer_used = false;
+ bool semaphore_used = false;
+ bool needs_fence_wait = false;
std::vector<std::function<void()>> cleanup_resources;
};
- std::array<FrameResources, NUM_COMMAND_BUFFERS> m_frame_resources = {};
- size_t m_current_frame;
+ std::array<FrameResources, NUM_COMMAND_BUFFERS> m_frame_resources;
+ u32 m_current_frame;
// callbacks when a fence point is set
- std::map<const void*, std::pair<CommandBufferQueuedCallback, CommandBufferExecutedCallback>>
- m_fence_point_callbacks;
+ std::map<const void*, FenceSignaledCallback> m_fence_callbacks;
// Threaded command buffer execution
// Semaphore determines when a command buffer can be queued
@@ -139,12 +137,11 @@ private:
std::unique_ptr<Common::BlockingLoop> m_submit_loop;
struct PendingCommandBufferSubmit
{
- size_t index;
- VkSemaphore wait_semaphore;
- VkSemaphore signal_semaphore;
VkSwapchainKHR present_swap_chain;
- uint32_t present_image_index;
+ u32 present_image_index;
+ u32 command_buffer_index;
};
+ VkSemaphore m_present_semaphore = VK_NULL_HANDLE;
std::deque<PendingCommandBufferSubmit> m_pending_submits;
std::mutex m_pending_submit_lock;
Common::Flag m_present_failed_flag;
diff --git a/Source/Core/VideoBackends/Vulkan/Constants.h b/Source/Core/VideoBackends/Vulkan/Constants.h
index f2af115b2a..816af86bc5 100644
--- a/Source/Core/VideoBackends/Vulkan/Constants.h
+++ b/Source/Core/VideoBackends/Vulkan/Constants.h
@@ -26,39 +26,29 @@ enum STAGING_BUFFER_TYPE
// Descriptor set layouts
enum DESCRIPTOR_SET_LAYOUT
{
- DESCRIPTOR_SET_LAYOUT_SINGLE_UNIFORM_BUFFER,
- DESCRIPTOR_SET_LAYOUT_PER_STAGE_UNIFORM_BUFFERS,
- DESCRIPTOR_SET_LAYOUT_PIXEL_SHADER_SAMPLERS,
- DESCRIPTOR_SET_LAYOUT_SHADER_STORAGE_BUFFERS,
- DESCRIPTOR_SET_LAYOUT_TEXEL_BUFFERS,
+ DESCRIPTOR_SET_LAYOUT_STANDARD_UNIFORM_BUFFERS,
+ DESCRIPTOR_SET_LAYOUT_STANDARD_SAMPLERS,
+ DESCRIPTOR_SET_LAYOUT_STANDARD_SHADER_STORAGE_BUFFERS,
+ DESCRIPTOR_SET_LAYOUT_UTILITY_UNIFORM_BUFFER,
+ DESCRIPTOR_SET_LAYOUT_UTILITY_SAMPLERS,
DESCRIPTOR_SET_LAYOUT_COMPUTE,
NUM_DESCRIPTOR_SET_LAYOUTS
};
-// Descriptor set bind points
-enum DESCRIPTOR_SET_BIND_POINT
-{
- DESCRIPTOR_SET_BIND_POINT_UNIFORM_BUFFERS,
- DESCRIPTOR_SET_BIND_POINT_PIXEL_SHADER_SAMPLERS,
- DESCRIPTOR_SET_BIND_POINT_STORAGE_OR_TEXEL_BUFFER,
- NUM_DESCRIPTOR_SET_BIND_POINTS
-};
-
// We use four pipeline layouts:
// - Standard
-// - Per-stage UBO (VS/GS/PS, VS constants accessible from PS)
-// - 8 combined image samplers (accessible from PS)
-// - 1 SSBO accessible from PS if supported
-// - Push Constant
-// - Same as standard, plus 128 bytes of push constants, accessible from all stages.
-// - Texture Decoding
-// - Same as push constant, plus a single texel buffer accessible from PS.
+// - Per-stage UBO (VS/GS/PS, VS constants accessible from PS) [set=0, binding=0-2]
+// - 8 combined image samplers (accessible from PS) [set=1, binding=0-7]
+// - 1 SSBO accessible from PS if supported [set=2, binding=0]
+// - Utility
+// - 1 combined UBO, accessible from VS/GS/PS [set=0, binding=0]
+// - 8 combined image samplers (accessible from PS) [set=1, binding=0-7]
+// - 1 texel buffer (accessible from PS) [set=1, binding=8]
// - Compute
// - 1 uniform buffer [set=0, binding=0]
-// - 4 combined image samplers [set=0, binding=1-4]
-// - 1 texel buffer [set=0, binding=5]
-// - 1 storage image [set=0, binding=6]
-// - 128 bytes of push constants
+// - 2 combined image samplers [set=0, binding=1-2]
+// - 2 texel buffers [set=0, binding=3-4]
+// - 1 storage image [set=0, binding=5]
//
// All four pipeline layout share the first two descriptor sets (uniform buffers, PS samplers).
// The third descriptor set (see bind points above) is used for storage or texel buffers.
@@ -66,8 +56,6 @@ enum DESCRIPTOR_SET_BIND_POINT
enum PIPELINE_LAYOUT
{
PIPELINE_LAYOUT_STANDARD,
- PIPELINE_LAYOUT_PUSH_CONSTANT,
- PIPELINE_LAYOUT_TEXTURE_CONVERSION,
PIPELINE_LAYOUT_UTILITY,
PIPELINE_LAYOUT_COMPUTE,
NUM_PIPELINE_LAYOUTS
@@ -83,53 +71,22 @@ enum UNIFORM_BUFFER_DESCRIPTOR_SET_BINDING
};
// Maximum number of attributes per vertex (we don't have any more than this?)
-constexpr size_t MAX_VERTEX_ATTRIBUTES = 16;
+constexpr u32 MAX_VERTEX_ATTRIBUTES = 16;
// Number of pixel shader texture slots
-constexpr size_t NUM_PIXEL_SHADER_SAMPLERS = 8;
-
-// Total number of binding points in the pipeline layout
-constexpr size_t TOTAL_PIPELINE_BINDING_POINTS =
- NUM_UBO_DESCRIPTOR_SET_BINDINGS + NUM_PIXEL_SHADER_SAMPLERS + 1;
+constexpr u32 NUM_PIXEL_SHADER_SAMPLERS = 8;
+constexpr u32 NUM_COMPUTE_SHADER_SAMPLERS = 2;
-// Format of EFB textures
-constexpr VkFormat EFB_COLOR_TEXTURE_FORMAT = VK_FORMAT_R8G8B8A8_UNORM;
-constexpr VkFormat EFB_DEPTH_TEXTURE_FORMAT = VK_FORMAT_D32_SFLOAT;
-constexpr VkFormat EFB_DEPTH_AS_COLOR_TEXTURE_FORMAT = VK_FORMAT_R32_SFLOAT;
-
-// Format of texturecache textures
-constexpr VkFormat TEXTURECACHE_TEXTURE_FORMAT = VK_FORMAT_R8G8B8A8_UNORM;
+// Number of texel buffer binding points.
+constexpr u32 NUM_COMPUTE_TEXEL_BUFFERS = 2;
// Textures that don't fit into this buffer will be uploaded with a separate buffer (see below).
-constexpr size_t INITIAL_TEXTURE_UPLOAD_BUFFER_SIZE = 16 * 1024 * 1024;
-constexpr size_t MAXIMUM_TEXTURE_UPLOAD_BUFFER_SIZE = 64 * 1024 * 1024;
+constexpr u32 TEXTURE_UPLOAD_BUFFER_SIZE = 32 * 1024 * 1024;
// Textures greater than 1024*1024 will be put in staging textures that are released after
// execution instead. A 2048x2048 texture is 16MB, and we'd only fit four of these in our
// streaming buffer and be blocking frequently. Games are unlikely to have textures this
// large anyway, so it's only really an issue for HD texture packs, and memory is not
// a limiting factor in these scenarios anyway.
-constexpr size_t STAGING_TEXTURE_UPLOAD_THRESHOLD = 1024 * 1024 * 8;
-
-// Streaming uniform buffer size
-constexpr size_t INITIAL_UNIFORM_STREAM_BUFFER_SIZE = 16 * 1024 * 1024;
-constexpr size_t MAXIMUM_UNIFORM_STREAM_BUFFER_SIZE = 32 * 1024 * 1024;
-
-// Texel buffer size for palette and texture decoding.
-constexpr size_t TEXTURE_CONVERSION_TEXEL_BUFFER_SIZE = 8 * 1024 * 1024;
-
-// Push constant buffer size for utility shaders
-constexpr u32 PUSH_CONSTANT_BUFFER_SIZE = 128;
-
-// Minimum number of draw calls per command buffer when attempting to preempt a readback operation.
-constexpr u32 MINIMUM_DRAW_CALLS_PER_COMMAND_BUFFER_FOR_READBACK = 10;
-
-// Multisampling state info that we don't expose in VideoCommon.
-union MultisamplingState
-{
- BitField<0, 5, u32> samples; // 1-16
- BitField<5, 1, u32> per_sample_shading; // SSAA
- u32 hex;
-};
-
+constexpr u32 STAGING_TEXTURE_UPLOAD_THRESHOLD = 1024 * 1024 * 4;
} // namespace Vulkan
diff --git a/Source/Core/VideoBackends/Vulkan/FramebufferManager.cpp b/Source/Core/VideoBackends/Vulkan/FramebufferManager.cpp
deleted file mode 100644
index cd1fbd9c82..0000000000
--- a/Source/Core/VideoBackends/Vulkan/FramebufferManager.cpp
+++ /dev/null
@@ -1,1198 +0,0 @@
-// Copyright 2016 Dolphin Emulator Project
-// Licensed under GPLv2+
-// Refer to the license.txt file included.
-
-#include "VideoBackends/Vulkan/FramebufferManager.h"
-
-#include <algorithm>
-#include <cstddef>
-
-#include "Common/Assert.h"
-#include "Common/CommonFuncs.h"
-#include "Common/Logging/Log.h"
-#include "Common/MsgHandler.h"
-
-#include "Core/HW/Memmap.h"
-
-#include "VideoBackends/Vulkan/CommandBufferManager.h"
-#include "VideoBackends/Vulkan/ObjectCache.h"
-#include "VideoBackends/Vulkan/StateTracker.h"
-#include "VideoBackends/Vulkan/StreamBuffer.h"
-#include "VideoBackends/Vulkan/Texture2D.h"
-#include "VideoBackends/Vulkan/Util.h"
-#include "VideoBackends/Vulkan/VKTexture.h"
-#include "VideoBackends/Vulkan/VertexFormat.h"
-#include "VideoBackends/Vulkan/VulkanContext.h"
-
-#include "VideoCommon/RenderBase.h"
-#include "VideoCommon/VideoConfig.h"
-
-namespace Vulkan
-{
-// Maximum number of pixels poked in one batch * 6
-constexpr size_t MAX_POKE_VERTICES = 8192;
-constexpr size_t POKE_VERTEX_BUFFER_SIZE = 8 * 1024 * 1024;
-
-FramebufferManager::FramebufferManager()
-{
-}
-
-FramebufferManager::~FramebufferManager()
-{
- DestroyEFBFramebuffer();
-
- DestroyConversionShaders();
-
- DestroyReadbackFramebuffer();
- DestroyReadbackTextures();
- DestroyReadbackShaders();
-
- DestroyPokeVertexBuffer();
- DestroyPokeShaders();
-}
-
-FramebufferManager* FramebufferManager::GetInstance()
-{
- return static_cast<FramebufferManager*>(g_framebuffer_manager.get());
-}
-
-u32 FramebufferManager::GetEFBWidth() const
-{
- return m_efb_color_texture->GetWidth();
-}
-
-u32 FramebufferManager::GetEFBHeight() const
-{
- return m_efb_color_texture->GetHeight();
-}
-
-u32 FramebufferManager::GetEFBLayers() const
-{
- return m_efb_color_texture->GetLayers();
-}
-
-VkSampleCountFlagBits FramebufferManager::GetEFBSamples() const
-{
- return m_efb_color_texture->GetSamples();
-}
-
-MultisamplingState FramebufferManager::GetEFBMultisamplingState() const
-{
- MultisamplingState ms = {};
- ms.per_sample_shading = g_ActiveConfig.MultisamplingEnabled() && g_ActiveConfig.bSSAA;
- ms.samples = static_cast<u32>(GetEFBSamples());
- return ms;
-}
-
-bool FramebufferManager::Initialize()
-{
- if (!CreateEFBRenderPasses())
- {
- PanicAlert("Failed to create EFB render pass");
- return false;
- }
- if (!CreateEFBFramebuffer())
- {
- PanicAlert("Failed to create EFB textures");
- return false;
- }
-
- if (!CompileConversionShaders())
- {
- PanicAlert("Failed to compile EFB shaders");
- return false;
- }
-
- if (!CreateReadbackRenderPasses())
- {
- PanicAlert("Failed to create readback render passes");
- return false;
- }
- if (!CompileReadbackShaders())
- {
- PanicAlert("Failed to compile readback shaders");
- return false;
- }
- if (!CreateReadbackTextures())
- {
- PanicAlert("Failed to create readback textures");
- return false;
- }
- if (!CreateReadbackFramebuffer())
- {
- PanicAlert("Failed to create readback framebuffer");
- return false;
- }
-
- CreatePokeVertexFormat();
- if (!CreatePokeVertexBuffer())
- {
- PanicAlert("Failed to create poke vertex buffer");
- return false;
- }
-
- if (!CompilePokeShaders())
- {
- PanicAlert("Failed to compile poke shaders");
- return false;
- }
-
- return true;
-}
-
-bool FramebufferManager::CreateEFBRenderPasses()
-{
- m_efb_load_render_pass = g_object_cache->GetRenderPass(
- EFB_COLOR_TEXTURE_FORMAT, Util::GetVkFormatForHostTextureFormat(GetEFBDepthFormat()),
- g_ActiveConfig.iMultisamples, VK_ATTACHMENT_LOAD_OP_LOAD);
- m_efb_clear_render_pass = g_object_cache->GetRenderPass(
- EFB_COLOR_TEXTURE_FORMAT, Util::GetVkFormatForHostTextureFormat(GetEFBDepthFormat()),
- g_ActiveConfig.iMultisamples, VK_ATTACHMENT_LOAD_OP_CLEAR);
- m_depth_resolve_render_pass = g_object_cache->GetRenderPass(
- EFB_DEPTH_AS_COLOR_TEXTURE_FORMAT, VK_FORMAT_UNDEFINED, 1, VK_ATTACHMENT_LOAD_OP_DONT_CARE);
- return m_efb_load_render_pass != VK_NULL_HANDLE && m_efb_clear_render_pass != VK_NULL_HANDLE &&
- m_depth_resolve_render_pass != VK_NULL_HANDLE;
-}
-
-bool FramebufferManager::CreateEFBFramebuffer()
-{
- u32 efb_width = static_cast<u32>(std::max(g_renderer->GetTargetWidth(), 1));
- u32 efb_height = static_cast<u32>(std::max(g_renderer->GetTargetHeight(), 1));
- u32 efb_layers = (g_ActiveConfig.stereo_mode != StereoMode::Off) ? 2 : 1;
- VkSampleCountFlagBits efb_samples =
- static_cast<VkSampleCountFlagBits>(g_ActiveConfig.iMultisamples);
- INFO_LOG(VIDEO, "EFB size: %ux%ux%u", efb_width, efb_height, efb_layers);
-
- // Update the static variable in the base class. Why does this even exist?
- FramebufferManagerBase::m_EFBLayers = efb_layers;
-
- // Allocate EFB render targets
- m_efb_color_texture =
- Texture2D::Create(efb_width, efb_height, 1, efb_layers, EFB_COLOR_TEXTURE_FORMAT, efb_samples,
- VK_IMAGE_VIEW_TYPE_2D_ARRAY, VK_IMAGE_TILING_OPTIMAL,
- VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT |
- VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT);
-
- // We need a second texture to swap with for changing pixel formats
- m_efb_convert_color_texture =
- Texture2D::Create(efb_width, efb_height, 1, efb_layers, EFB_COLOR_TEXTURE_FORMAT, efb_samples,
- VK_IMAGE_VIEW_TYPE_2D_ARRAY, VK_IMAGE_TILING_OPTIMAL,
- VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT |
- VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT);
-
- m_efb_depth_texture = Texture2D::Create(
- efb_width, efb_height, 1, efb_layers,
- Util::GetVkFormatForHostTextureFormat(GetEFBDepthFormat()), efb_samples,
- VK_IMAGE_VIEW_TYPE_2D_ARRAY, VK_IMAGE_TILING_OPTIMAL,
- VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT |
- VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT);
-
- if (!m_efb_color_texture || !m_efb_convert_color_texture || !m_efb_depth_texture)
- return false;
-
- // Create resolved textures if MSAA is on
- if (g_ActiveConfig.MultisamplingEnabled())
- {
- m_efb_resolve_color_texture = Texture2D::Create(
- efb_width, efb_height, 1, efb_layers, EFB_COLOR_TEXTURE_FORMAT, VK_SAMPLE_COUNT_1_BIT,
- VK_IMAGE_VIEW_TYPE_2D_ARRAY, VK_IMAGE_TILING_OPTIMAL,
- VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT |
- VK_IMAGE_USAGE_SAMPLED_BIT);
-
- m_efb_resolve_depth_texture = Texture2D::Create(
- efb_width, efb_height, 1, efb_layers, EFB_DEPTH_AS_COLOR_TEXTURE_FORMAT,
- VK_SAMPLE_COUNT_1_BIT, VK_IMAGE_VIEW_TYPE_2D_ARRAY, VK_IMAGE_TILING_OPTIMAL,
- VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
- VK_IMAGE_USAGE_SAMPLED_BIT);
-
- if (!m_efb_resolve_color_texture || !m_efb_resolve_depth_texture)
- return false;
-
- VkImageView attachment = m_efb_resolve_depth_texture->GetView();
- VkFramebufferCreateInfo framebuffer_info = {VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO,
- nullptr,
- 0,
- m_depth_resolve_render_pass,
- 1,
- &attachment,
- efb_width,
- efb_height,
- efb_layers};
-
- VkResult res = vkCreateFramebuffer(g_vulkan_context->GetDevice(), &framebuffer_info, nullptr,
- &m_depth_resolve_framebuffer);
- if (res != VK_SUCCESS)
- {
- LOG_VULKAN_ERROR(res, "vkCreateFramebuffer failed: ");
- return false;
- }
- }
-
- VkImageView framebuffer_attachments[] = {
- m_efb_color_texture->GetView(),
- m_efb_depth_texture->GetView(),
- };
-
- VkFramebufferCreateInfo framebuffer_info = {VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO,
- nullptr,
- 0,
- m_efb_load_render_pass,
- static_cast<u32>(ArraySize(framebuffer_attachments)),
- framebuffer_attachments,
- efb_width,
- efb_height,
- efb_layers};
-
- VkResult res = vkCreateFramebuffer(g_vulkan_context->GetDevice(), &framebuffer_info, nullptr,
- &m_efb_framebuffer);
- if (res != VK_SUCCESS)
- {
- LOG_VULKAN_ERROR(res, "vkCreateFramebuffer failed: ");
- return false;
- }
-
- // Create second framebuffer for format conversions
- framebuffer_attachments[0] = m_efb_convert_color_texture->GetView();
- res = vkCreateFramebuffer(g_vulkan_context->GetDevice(), &framebuffer_info, nullptr,
- &m_efb_convert_framebuffer);
- if (res != VK_SUCCESS)
- {
- LOG_VULKAN_ERROR(res, "vkCreateFramebuffer failed: ");
- return false;
- }
-
- // Transition to state that can be used to clear
- m_efb_color_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
- m_efb_convert_color_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
- m_efb_depth_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
-
- // Clear the contents of the buffers.
- static const VkClearColorValue clear_color = {{0.0f, 0.0f, 0.0f, 0.0f}};
- static const VkClearDepthStencilValue clear_depth = {0.0f, 0};
- VkImageSubresourceRange clear_color_range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, efb_layers};
- VkImageSubresourceRange clear_depth_range = {VK_IMAGE_ASPECT_DEPTH_BIT, 0, 1, 0, efb_layers};
- vkCmdClearColorImage(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- m_efb_color_texture->GetImage(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
- &clear_color, 1, &clear_color_range);
- vkCmdClearColorImage(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- m_efb_convert_color_texture->GetImage(),
- VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &clear_color, 1, &clear_color_range);
- vkCmdClearDepthStencilImage(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- m_efb_depth_texture->GetImage(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
- &clear_depth, 1, &clear_depth_range);
-
- // Transition to color attachment state ready for rendering.
- m_efb_color_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
- m_efb_depth_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
-
- return true;
-}
-
-void FramebufferManager::DestroyEFBFramebuffer()
-{
- if (m_efb_framebuffer != VK_NULL_HANDLE)
- {
- vkDestroyFramebuffer(g_vulkan_context->GetDevice(), m_efb_framebuffer, nullptr);
- m_efb_framebuffer = VK_NULL_HANDLE;
- }
-
- if (m_efb_convert_framebuffer != VK_NULL_HANDLE)
- {
- vkDestroyFramebuffer(g_vulkan_context->GetDevice(), m_efb_convert_framebuffer, nullptr);
- m_efb_convert_framebuffer = VK_NULL_HANDLE;
- }
-
- if (m_depth_resolve_framebuffer != VK_NULL_HANDLE)
- {
- vkDestroyFramebuffer(g_vulkan_context->GetDevice(), m_depth_resolve_framebuffer, nullptr);
- m_depth_resolve_framebuffer = VK_NULL_HANDLE;
- }
-
- m_efb_color_texture.reset();
- m_efb_convert_color_texture.reset();
- m_efb_depth_texture.reset();
- m_efb_resolve_color_texture.reset();
- m_efb_resolve_depth_texture.reset();
-}
-
-void FramebufferManager::RecreateEFBFramebuffer()
-{
- DestroyEFBFramebuffer();
-
- if (!CreateEFBRenderPasses())
- PanicAlert("Failed to create EFB render pass");
-
- if (!CreateEFBFramebuffer())
- PanicAlert("Failed to create EFB textures");
-}
-
-void FramebufferManager::RecompileShaders()
-{
- DestroyConversionShaders();
-
- if (!CompileConversionShaders())
- PanicAlert("Failed to compile EFB shaders");
-
- DestroyReadbackShaders();
- if (!CompileReadbackShaders())
- PanicAlert("Failed to compile readback shaders");
-}
-
-void FramebufferManager::ReinterpretPixelData(int convtype)
-{
- VkShaderModule pixel_shader = VK_NULL_HANDLE;
- if (convtype == 0)
- {
- pixel_shader = m_ps_rgb8_to_rgba6;
- }
- else if (convtype == 2)
- {
- pixel_shader = m_ps_rgba6_to_rgb8;
- }
- else
- {
- ERROR_LOG(VIDEO, "Unhandled reinterpret pixel data %d", convtype);
- return;
- }
-
- // Transition EFB color buffer to shader resource, and the convert buffer to color attachment.
- m_efb_color_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
- m_efb_convert_color_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
-
- UtilityShaderDraw draw(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- g_object_cache->GetPipelineLayout(PIPELINE_LAYOUT_STANDARD),
- m_efb_load_render_pass, g_shader_cache->GetScreenQuadVertexShader(),
- g_shader_cache->GetScreenQuadGeometryShader(), pixel_shader);
-
- VkRect2D region = {{0, 0}, {GetEFBWidth(), GetEFBHeight()}};
- draw.SetMultisamplingState(GetEFBMultisamplingState());
- draw.BeginRenderPass(m_efb_convert_framebuffer, region);
- draw.SetPSSampler(0, m_efb_color_texture->GetView(), g_object_cache->GetPointSampler());
- draw.SetViewportAndScissor(0, 0, GetEFBWidth(), GetEFBHeight());
- draw.DrawWithoutVertexBuffer(4);
- draw.EndRenderPass();
-
- // Swap EFB texture pointers
- std::swap(m_efb_color_texture, m_efb_convert_color_texture);
- std::swap(m_efb_framebuffer, m_efb_convert_framebuffer);
-}
-
-Texture2D* FramebufferManager::ResolveEFBColorTexture(const VkRect2D& region)
-{
- // Return the normal EFB texture if multisampling is off.
- if (GetEFBSamples() == VK_SAMPLE_COUNT_1_BIT)
- return m_efb_color_texture.get();
-
- // Can't resolve within a render pass.
- StateTracker::GetInstance()->EndRenderPass();
-
- // It's not valid to resolve out-of-bounds coordinates.
- // Ensuring the region is within the image is the caller's responsibility.
- ASSERT(region.offset.x >= 0 && region.offset.y >= 0 &&
- (static_cast<u32>(region.offset.x) + region.extent.width) <= GetEFBWidth() &&
- (static_cast<u32>(region.offset.y) + region.extent.height) <= GetEFBHeight());
-
- // Resolving is considered to be a transfer operation.
- m_efb_color_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
- m_efb_resolve_color_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
-
- // Resolve to our already-created texture.
- VkImageResolve resolve = {
- {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, GetEFBLayers()}, // VkImageSubresourceLayers srcSubresource
- {region.offset.x, region.offset.y, 0}, // VkOffset3D srcOffset
- {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, GetEFBLayers()}, // VkImageSubresourceLayers dstSubresource
- {region.offset.x, region.offset.y, 0}, // VkOffset3D dstOffset
- {region.extent.width, region.extent.height, GetEFBLayers()} // VkExtent3D extent
- };
- vkCmdResolveImage(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- m_efb_color_texture->GetImage(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
- m_efb_resolve_color_texture->GetImage(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
- 1, &resolve);
-
- // Restore MSAA texture ready for rendering again
- m_efb_color_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
- return m_efb_resolve_color_texture.get();
-}
-
-Texture2D* FramebufferManager::ResolveEFBDepthTexture(const VkRect2D& region)
-{
- // Return the normal EFB texture if multisampling is off.
- if (GetEFBSamples() == VK_SAMPLE_COUNT_1_BIT)
- return m_efb_depth_texture.get();
-
- // Can't resolve within a render pass.
- StateTracker::GetInstance()->EndRenderPass();
-
- m_efb_depth_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
- m_efb_resolve_depth_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
-
- // Draw using resolve shader to write the minimum depth of all samples to the resolve texture.
- UtilityShaderDraw draw(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- g_object_cache->GetPipelineLayout(PIPELINE_LAYOUT_STANDARD),
- m_depth_resolve_render_pass, g_shader_cache->GetScreenQuadVertexShader(),
- g_shader_cache->GetScreenQuadGeometryShader(), m_ps_depth_resolve);
- draw.BeginRenderPass(m_depth_resolve_framebuffer, region);
- draw.SetPSSampler(0, m_efb_depth_texture->GetView(), g_object_cache->GetPointSampler());
- draw.SetViewportAndScissor(region.offset.x, region.offset.y, region.extent.width,
- region.extent.height);
- draw.DrawWithoutVertexBuffer(4);
- draw.EndRenderPass();
-
- // Restore MSAA texture ready for rendering again
- m_efb_depth_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
-
- return m_efb_resolve_depth_texture.get();
-}
-
-bool FramebufferManager::CompileConversionShaders()
-{
- static const char RGB8_TO_RGBA6_SHADER_SOURCE[] = R"(
- #if MSAA_ENABLED
- SAMPLER_BINDING(0) uniform sampler2DMSArray samp0;
- #else
- SAMPLER_BINDING(0) uniform sampler2DArray samp0;
- #endif
- layout(location = 0) in vec3 uv0;
- layout(location = 0) out vec4 ocol0;
-
- void main()
- {
- int layer = 0;
- #if EFB_LAYERS > 1
- layer = int(uv0.z);
- #endif
-
- ivec3 coords = ivec3(gl_FragCoord.xy, layer);
-
- vec4 val;
- #if !MSAA_ENABLED
- // No MSAA - just load the first (and only) sample
- val = texelFetch(samp0, coords, 0);
- #elif SSAA_ENABLED
- // Sample shading, shader runs once per sample
- val = texelFetch(samp0, coords, gl_SampleID);
- #else
- // MSAA without sample shading, average out all samples.
- val = vec4(0, 0, 0, 0);
- for (int i = 0; i < MSAA_SAMPLES; i++)
- val += texelFetch(samp0, coords, i);
- val /= float(MSAA_SAMPLES);
- #endif
-
- ivec4 src8 = ivec4(round(val * 255.f));
- ivec4 dst6;
- dst6.r = src8.r >> 2;
- dst6.g = ((src8.r & 0x3) << 4) | (src8.g >> 4);
- dst6.b = ((src8.g & 0xF) << 2) | (src8.b >> 6);
- dst6.a = src8.b & 0x3F;
-
- ocol0 = float4(dst6) / 63.f;
- }
- )";
-
- static const char RGBA6_TO_RGB8_SHADER_SOURCE[] = R"(
- #if MSAA_ENABLED
- SAMPLER_BINDING(0) uniform sampler2DMSArray samp0;
- #else
- SAMPLER_BINDING(0) uniform sampler2DArray samp0;
- #endif
- layout(location = 0) in vec3 uv0;
- layout(location = 0) out vec4 ocol0;
-
- void main()
- {
- int layer = 0;
- #if EFB_LAYERS > 1
- layer = int(uv0.z);
- #endif
-
- ivec3 coords = ivec3(gl_FragCoord.xy, layer);
-
- vec4 val;
- #if !MSAA_ENABLED
- // No MSAA - just load the first (and only) sample
- val = texelFetch(samp0, coords, 0);
- #elif SSAA_ENABLED
- // Sample shading, shader runs once per sample
- val = texelFetch(samp0, coords, gl_SampleID);
- #else
- // MSAA without sample shading, average out all samples.
- val = vec4(0, 0, 0, 0);
- for (int i = 0; i < MSAA_SAMPLES; i++)
- val += texelFetch(samp0, coords, i);
- val /= float(MSAA_SAMPLES);
- #endif
-
- ivec4 src6 = ivec4(round(val * 63.f));
- ivec4 dst8;
- dst8.r = (src6.r << 2) | (src6.g >> 4);
- dst8.g = ((src6.g & 0xF) << 4) | (src6.b >> 2);
- dst8.b = ((src6.b & 0x3) << 6) | src6.a;
- dst8.a = 255;
-
- ocol0 = float4(dst8) / 255.f;
- }
- )";
-
- static const char DEPTH_RESOLVE_SHADER_SOURCE[] = R"(
- SAMPLER_BINDING(0) uniform sampler2DMSArray samp0;
- layout(location = 0) in vec3 uv0;
- layout(location = 0) out float ocol0;
-
- void main()
- {
- int layer = 0;
- #if EFB_LAYERS > 1
- layer = int(uv0.z);
- #endif
-
- // gl_FragCoord is in window coordinates, and we're rendering to
- // the same rectangle in the resolve texture.
- ivec3 coords = ivec3(gl_FragCoord.xy, layer);
-
- // Take the minimum of all depth samples.
- ocol0 = texelFetch(samp0, coords, 0).r;
- for (int i = 1; i < MSAA_SAMPLES; i++)
- ocol0 = min(ocol0, texelFetch(samp0, coords, i).r);
- }
- )";
-
- std::string header = g_shader_cache->GetUtilityShaderHeader();
- DestroyConversionShaders();
-
- m_ps_rgb8_to_rgba6 = Util::CompileAndCreateFragmentShader(header + RGB8_TO_RGBA6_SHADER_SOURCE);
- m_ps_rgba6_to_rgb8 = Util::CompileAndCreateFragmentShader(header + RGBA6_TO_RGB8_SHADER_SOURCE);
- if (GetEFBSamples() != VK_SAMPLE_COUNT_1_BIT)
- m_ps_depth_resolve = Util::CompileAndCreateFragmentShader(header + DEPTH_RESOLVE_SHADER_SOURCE);
-
- return (m_ps_rgba6_to_rgb8 != VK_NULL_HANDLE && m_ps_rgb8_to_rgba6 != VK_NULL_HANDLE &&
- (GetEFBSamples() == VK_SAMPLE_COUNT_1_BIT || m_ps_depth_resolve != VK_NULL_HANDLE));
-}
-
-void FramebufferManager::DestroyConversionShaders()
-{
- auto DestroyShader = [this](VkShaderModule& shader) {
- if (shader != VK_NULL_HANDLE)
- {
- vkDestroyShaderModule(g_vulkan_context->GetDevice(), shader, nullptr);
- shader = VK_NULL_HANDLE;
- }
- };
-
- DestroyShader(m_ps_rgb8_to_rgba6);
- DestroyShader(m_ps_rgba6_to_rgb8);
- DestroyShader(m_ps_depth_resolve);
-}
-
-u32 FramebufferManager::PeekEFBColor(u32 x, u32 y)
-{
- if (!m_color_readback_texture_valid && !PopulateColorReadbackTexture())
- return 0;
-
- u32 value;
- m_color_readback_texture->ReadTexel(x, y, &value);
- return value;
-}
-
-bool FramebufferManager::PopulateColorReadbackTexture()
-{
- // Can't be in our normal render pass.
- StateTracker::GetInstance()->EndRenderPass();
- StateTracker::GetInstance()->OnCPUEFBAccess();
-
- // Issue a copy from framebuffer -> copy texture if we have >1xIR or MSAA on.
- VkRect2D src_region = {{0, 0}, {GetEFBWidth(), GetEFBHeight()}};
- Texture2D* src_texture = m_efb_color_texture.get();
- if (GetEFBSamples() > 1)
- src_texture = ResolveEFBColorTexture(src_region);
-
- if (GetEFBWidth() != EFB_WIDTH || GetEFBHeight() != EFB_HEIGHT)
- {
- // Transition EFB to shader read before drawing.
- src_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
- m_color_copy_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
-
- UtilityShaderDraw draw(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- g_object_cache->GetPipelineLayout(PIPELINE_LAYOUT_STANDARD),
- m_copy_color_render_pass, g_shader_cache->GetScreenQuadVertexShader(),
- VK_NULL_HANDLE, m_copy_color_shader);
-
- VkRect2D rect = {{0, 0}, {EFB_WIDTH, EFB_HEIGHT}};
- draw.BeginRenderPass(m_color_copy_framebuffer, rect);
- draw.SetPSSampler(0, src_texture->GetView(), g_object_cache->GetPointSampler());
- draw.SetViewportAndScissor(0, 0, EFB_WIDTH, EFB_HEIGHT);
- draw.DrawWithoutVertexBuffer(4);
- draw.EndRenderPass();
-
- // Restore EFB to color attachment, since we're done with it.
- if (src_texture == m_efb_color_texture.get())
- {
- src_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
- }
-
- // Use this as a source texture now.
- src_texture = m_color_copy_texture.get();
- }
-
- // Copy from EFB or copy texture to staging texture.
- src_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
- static_cast<VKStagingTexture*>(m_color_readback_texture.get())
- ->CopyFromTexture(src_texture, m_color_readback_texture->GetConfig().GetRect(), 0, 0,
- m_color_readback_texture->GetConfig().GetRect());
-
- // Restore original layout if we used the EFB as a source.
- if (src_texture == m_efb_color_texture.get())
- {
- src_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
- }
-
- // Wait until the copy is complete.
- m_color_readback_texture->Flush();
- m_color_readback_texture_valid = true;
- return true;
-}
-
-float FramebufferManager::PeekEFBDepth(u32 x, u32 y)
-{
- if (!m_depth_readback_texture_valid && !PopulateDepthReadbackTexture())
- return 0.0f;
-
- float value;
- m_depth_readback_texture->ReadTexel(x, y, &value);
- return value;
-}
-
-bool FramebufferManager::PopulateDepthReadbackTexture()
-{
- // Can't be in our normal render pass.
- StateTracker::GetInstance()->EndRenderPass();
- StateTracker::GetInstance()->OnCPUEFBAccess();
-
- // Issue a copy from framebuffer -> copy texture if we have >1xIR or MSAA on.
- VkRect2D src_region = {{0, 0}, {GetEFBWidth(), GetEFBHeight()}};
- Texture2D* src_texture = m_efb_depth_texture.get();
- if (GetEFBSamples() > 1)
- {
- // EFB depth resolves are written out as color textures
- src_texture = ResolveEFBDepthTexture(src_region);
- }
- if (GetEFBWidth() != EFB_WIDTH || GetEFBHeight() != EFB_HEIGHT)
- {
- // Transition EFB to shader read before drawing.
- src_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
- m_depth_copy_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
-
- UtilityShaderDraw draw(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- g_object_cache->GetPipelineLayout(PIPELINE_LAYOUT_STANDARD),
- m_copy_depth_render_pass, g_shader_cache->GetScreenQuadVertexShader(),
- VK_NULL_HANDLE, m_copy_depth_shader);
-
- VkRect2D rect = {{0, 0}, {EFB_WIDTH, EFB_HEIGHT}};
- draw.BeginRenderPass(m_depth_copy_framebuffer, rect);
- draw.SetPSSampler(0, src_texture->GetView(), g_object_cache->GetPointSampler());
- draw.SetViewportAndScissor(0, 0, EFB_WIDTH, EFB_HEIGHT);
- draw.DrawWithoutVertexBuffer(4);
- draw.EndRenderPass();
-
- // Restore EFB to depth attachment, since we're done with it.
- if (src_texture == m_efb_depth_texture.get())
- {
- src_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
- }
-
- // Use this as a source texture now.
- src_texture = m_depth_copy_texture.get();
- }
-
- // Copy from EFB or copy texture to staging texture.
- src_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
- static_cast<VKStagingTexture*>(m_depth_readback_texture.get())
- ->CopyFromTexture(src_texture, m_depth_readback_texture->GetConfig().GetRect(), 0, 0,
- m_depth_readback_texture->GetConfig().GetRect());
-
- // Restore original layout if we used the EFB as a source.
- if (src_texture == m_efb_depth_texture.get())
- {
- src_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
- }
-
- // Wait until the copy is complete.
- m_depth_readback_texture->Flush();
- m_depth_readback_texture_valid = true;
- return true;
-}
-
-void FramebufferManager::InvalidatePeekCache()
-{
- m_color_readback_texture_valid = false;
- m_depth_readback_texture_valid = false;
-}
-
-bool FramebufferManager::CreateReadbackRenderPasses()
-{
- m_copy_color_render_pass = g_object_cache->GetRenderPass(
- EFB_COLOR_TEXTURE_FORMAT, VK_FORMAT_UNDEFINED, 1, VK_ATTACHMENT_LOAD_OP_DONT_CARE);
- m_copy_depth_render_pass = g_object_cache->GetRenderPass(
- EFB_DEPTH_AS_COLOR_TEXTURE_FORMAT, VK_FORMAT_UNDEFINED, 1, VK_ATTACHMENT_LOAD_OP_DONT_CARE);
- if (m_copy_color_render_pass == VK_NULL_HANDLE || m_copy_depth_render_pass == VK_NULL_HANDLE)
- return false;
-
- // Some devices don't support point sizes >1 (e.g. Adreno).
- // If we can't use a point size above our maximum IR, use triangles instead.
- // This means a 6x increase in the size of the vertices, though.
- if (!g_vulkan_context->GetDeviceFeatures().largePoints ||
- g_vulkan_context->GetDeviceLimits().pointSizeGranularity > 1 ||
- g_vulkan_context->GetDeviceLimits().pointSizeRange[0] > 1 ||
- g_vulkan_context->GetDeviceLimits().pointSizeRange[1] < 16)
- {
- m_poke_primitive = PrimitiveType::TriangleStrip;
- }
- else
- {
- // Points should be okay.
- m_poke_primitive = PrimitiveType::Points;
- }
-
- return true;
-}
-
-bool FramebufferManager::CompileReadbackShaders()
-{
- std::string source;
-
- // TODO: Use input attachment here instead?
- // TODO: MSAA resolve in shader.
- static const char COPY_COLOR_SHADER_SOURCE[] = R"(
- SAMPLER_BINDING(0) uniform sampler2DArray samp0;
- layout(location = 0) in vec3 uv0;
- layout(location = 0) out vec4 ocol0;
- void main()
- {
- ocol0 = texture(samp0, uv0);
- }
- )";
-
- static const char COPY_DEPTH_SHADER_SOURCE[] = R"(
- SAMPLER_BINDING(0) uniform sampler2DArray samp0;
- layout(location = 0) in vec3 uv0;
- layout(location = 0) out float ocol0;
- void main()
- {
- ocol0 = texture(samp0, uv0).r;
- }
- )";
-
- source = g_shader_cache->GetUtilityShaderHeader() + COPY_COLOR_SHADER_SOURCE;
- m_copy_color_shader = Util::CompileAndCreateFragmentShader(source);
-
- source = g_shader_cache->GetUtilityShaderHeader() + COPY_DEPTH_SHADER_SOURCE;
- m_copy_depth_shader = Util::CompileAndCreateFragmentShader(source);
-
- return m_copy_color_shader != VK_NULL_HANDLE && m_copy_depth_shader != VK_NULL_HANDLE;
-}
-
-void FramebufferManager::DestroyReadbackShaders()
-{
- if (m_copy_color_shader != VK_NULL_HANDLE)
- {
- vkDestroyShaderModule(g_vulkan_context->GetDevice(), m_copy_color_shader, nullptr);
- m_copy_color_shader = VK_NULL_HANDLE;
- }
- if (m_copy_depth_shader != VK_NULL_HANDLE)
- {
- vkDestroyShaderModule(g_vulkan_context->GetDevice(), m_copy_depth_shader, nullptr);
- m_copy_depth_shader = VK_NULL_HANDLE;
- }
-}
-
-bool FramebufferManager::CreateReadbackTextures()
-{
- m_color_copy_texture =
- Texture2D::Create(EFB_WIDTH, EFB_HEIGHT, 1, 1, EFB_COLOR_TEXTURE_FORMAT,
- VK_SAMPLE_COUNT_1_BIT, VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_TILING_OPTIMAL,
- VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT |
- VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT);
-
- m_depth_copy_texture =
- Texture2D::Create(EFB_WIDTH, EFB_HEIGHT, 1, 1, EFB_DEPTH_AS_COLOR_TEXTURE_FORMAT,
- VK_SAMPLE_COUNT_1_BIT, VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_TILING_OPTIMAL,
- VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT |
- VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT);
-
- if (!m_color_copy_texture || !m_depth_copy_texture)
- {
- ERROR_LOG(VIDEO, "Failed to create EFB copy textures");
- return false;
- }
-
- TextureConfig readback_texture_config(EFB_WIDTH, EFB_HEIGHT, 1, 1, 1,
- AbstractTextureFormat::RGBA8, false);
- m_color_readback_texture =
- g_renderer->CreateStagingTexture(StagingTextureType::Mutable, readback_texture_config);
- m_depth_readback_texture =
- g_renderer->CreateStagingTexture(StagingTextureType::Mutable, readback_texture_config);
- if (!m_color_readback_texture || !m_depth_readback_texture)
- {
- ERROR_LOG(VIDEO, "Failed to create EFB readback textures");
- return false;
- }
-
- return true;
-}
-
-void FramebufferManager::DestroyReadbackTextures()
-{
- m_color_copy_texture.reset();
- m_color_readback_texture.reset();
- m_color_readback_texture_valid = false;
- m_depth_copy_texture.reset();
- m_depth_readback_texture.reset();
- m_depth_readback_texture_valid = false;
-}
-
-bool FramebufferManager::CreateReadbackFramebuffer()
-{
- VkImageView framebuffer_attachment = m_color_copy_texture->GetView();
- VkFramebufferCreateInfo framebuffer_info = {
- VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, // VkStructureType sType
- nullptr, // const void* pNext
- 0, // VkFramebufferCreateFlags flags
- m_copy_color_render_pass, // VkRenderPass renderPass
- 1, // uint32_t attachmentCount
- &framebuffer_attachment, // const VkImageView* pAttachments
- EFB_WIDTH, // uint32_t width
- EFB_HEIGHT, // uint32_t height
- 1 // uint32_t layers
- };
- VkResult res = vkCreateFramebuffer(g_vulkan_context->GetDevice(), &framebuffer_info, nullptr,
- &m_color_copy_framebuffer);
- if (res != VK_SUCCESS)
- {
- LOG_VULKAN_ERROR(res, "vkCreateFramebuffer failed: ");
- return false;
- }
-
- // Swap for depth
- framebuffer_info.renderPass = m_copy_depth_render_pass;
- framebuffer_attachment = m_depth_copy_texture->GetView();
- res = vkCreateFramebuffer(g_vulkan_context->GetDevice(), &framebuffer_info, nullptr,
- &m_depth_copy_framebuffer);
- if (res != VK_SUCCESS)
- {
- LOG_VULKAN_ERROR(res, "vkCreateFramebuffer failed: ");
- return false;
- }
-
- return true;
-}
-
-void FramebufferManager::DestroyReadbackFramebuffer()
-{
- if (m_color_copy_framebuffer != VK_NULL_HANDLE)
- {
- vkDestroyFramebuffer(g_vulkan_context->GetDevice(), m_color_copy_framebuffer, nullptr);
- m_color_copy_framebuffer = VK_NULL_HANDLE;
- }
- if (m_depth_copy_framebuffer != VK_NULL_HANDLE)
- {
- vkDestroyFramebuffer(g_vulkan_context->GetDevice(), m_depth_copy_framebuffer, nullptr);
- m_depth_copy_framebuffer = VK_NULL_HANDLE;
- }
-}
-
-void FramebufferManager::PokeEFBColor(u32 x, u32 y, u32 color)
-{
- // Flush if we exceeded the number of vertices per batch.
- if ((m_color_poke_vertices.size() + 6) > MAX_POKE_VERTICES)
- FlushEFBPokes();
-
- CreatePokeVertices(&m_color_poke_vertices, x, y, 0.0f, color);
-
- // Update the peek cache if it's valid, since we know the color of the pixel now.
- if (m_color_readback_texture_valid)
- m_color_readback_texture->WriteTexel(x, y, &color);
-}
-
-void FramebufferManager::PokeEFBDepth(u32 x, u32 y, float depth)
-{
- // Flush if we exceeded the number of vertices per batch.
- if ((m_color_poke_vertices.size() + 6) > MAX_POKE_VERTICES)
- FlushEFBPokes();
-
- CreatePokeVertices(&m_depth_poke_vertices, x, y, depth, 0);
-
- // Update the peek cache if it's valid, since we know the color of the pixel now.
- if (m_depth_readback_texture_valid)
- m_depth_readback_texture->WriteTexel(x, y, &depth);
-}
-
-void FramebufferManager::CreatePokeVertices(std::vector<EFBPokeVertex>* destination_list, u32 x,
- u32 y, float z, u32 color)
-{
- if (m_poke_primitive == PrimitiveType::Points)
- {
- // GPU will expand the point to a quad.
- float cs_x = float(x) * 2.0f / EFB_WIDTH - 1.0f;
- float cs_y = float(y) * 2.0f / EFB_HEIGHT - 1.0f;
- float point_size = GetEFBWidth() / static_cast<float>(EFB_WIDTH);
- destination_list->push_back({{cs_x, cs_y, z, point_size}, color});
- return;
- }
-
- // Some devices don't support point sizes >1 (e.g. Adreno).
- // Generate quad from the single point (clip-space coordinates).
- float x1 = float(x) * 2.0f / EFB_WIDTH - 1.0f;
- float y1 = float(y) * 2.0f / EFB_HEIGHT - 1.0f;
- float x2 = float(x + 1) * 2.0f / EFB_WIDTH - 1.0f;
- float y2 = float(y + 1) * 2.0f / EFB_HEIGHT - 1.0f;
- destination_list->push_back({{x1, y1, z, 1.0f}, color});
- destination_list->push_back({{x2, y1, z, 1.0f}, color});
- destination_list->push_back({{x1, y2, z, 1.0f}, color});
- destination_list->push_back({{x1, y2, z, 1.0f}, color});
- destination_list->push_back({{x2, y1, z, 1.0f}, color});
- destination_list->push_back({{x2, y2, z, 1.0f}, color});
-}
-
-void FramebufferManager::FlushEFBPokes()
-{
- if (!m_color_poke_vertices.empty())
- {
- DrawPokeVertices(m_color_poke_vertices.data(), m_color_poke_vertices.size(), true, false);
- m_color_poke_vertices.clear();
- }
-
- if (!m_depth_poke_vertices.empty())
- {
- DrawPokeVertices(m_depth_poke_vertices.data(), m_depth_poke_vertices.size(), false, true);
- m_depth_poke_vertices.clear();
- }
-}
-
-void FramebufferManager::DrawPokeVertices(const EFBPokeVertex* vertices, size_t vertex_count,
- bool write_color, bool write_depth)
-{
- // Relatively simple since we don't have any bindings.
- VkCommandBuffer command_buffer = g_command_buffer_mgr->GetCurrentCommandBuffer();
-
- // We don't use the utility shader in order to keep the vertices compact.
- PipelineInfo pipeline_info = {};
- pipeline_info.vertex_format = m_poke_vertex_format.get();
- pipeline_info.pipeline_layout = g_object_cache->GetPipelineLayout(PIPELINE_LAYOUT_STANDARD);
- pipeline_info.vs = m_poke_vertex_shader;
- pipeline_info.gs = (GetEFBLayers() > 1) ? m_poke_geometry_shader : VK_NULL_HANDLE;
- pipeline_info.ps = m_poke_fragment_shader;
- pipeline_info.render_pass = m_efb_load_render_pass;
- pipeline_info.rasterization_state.hex = RenderState::GetNoCullRasterizationState().hex;
- pipeline_info.rasterization_state.primitive = m_poke_primitive;
- pipeline_info.multisampling_state.hex = GetEFBMultisamplingState().hex;
- pipeline_info.depth_state.hex = RenderState::GetNoDepthTestingDepthStencilState().hex;
- pipeline_info.blend_state.hex = RenderState::GetNoBlendingBlendState().hex;
- pipeline_info.blend_state.colorupdate = write_color;
- pipeline_info.blend_state.alphaupdate = write_color;
- if (write_depth)
- {
- pipeline_info.depth_state.testenable = true;
- pipeline_info.depth_state.updateenable = true;
- pipeline_info.depth_state.func = ZMode::ALWAYS;
- }
-
- VkPipeline pipeline = g_shader_cache->GetPipeline(pipeline_info);
- if (pipeline == VK_NULL_HANDLE)
- {
- PanicAlert("Failed to get pipeline for EFB poke draw");
- return;
- }
-
- // Populate vertex buffer.
- size_t vertices_size = sizeof(EFBPokeVertex) * m_color_poke_vertices.size();
- if (!m_poke_vertex_stream_buffer->ReserveMemory(vertices_size, sizeof(EfbPokeData), true, true,
- false))
- {
- // Kick a command buffer first.
- WARN_LOG(VIDEO, "Kicking command buffer due to no EFB poke space.");
- Util::ExecuteCurrentCommandsAndRestoreState(false);
- command_buffer = g_command_buffer_mgr->GetCurrentCommandBuffer();
-
- if (!m_poke_vertex_stream_buffer->ReserveMemory(vertices_size, sizeof(EfbPokeData), true, true,
- false))
- {
- PanicAlert("Failed to get space for EFB poke vertices");
- return;
- }
- }
- VkBuffer vb_buffer = m_poke_vertex_stream_buffer->GetBuffer();
- VkDeviceSize vb_offset = m_poke_vertex_stream_buffer->GetCurrentOffset();
- memcpy(m_poke_vertex_stream_buffer->GetCurrentHostPointer(), vertices, vertices_size);
- m_poke_vertex_stream_buffer->CommitMemory(vertices_size);
-
- // Set up state.
- StateTracker::GetInstance()->EndClearRenderPass();
- StateTracker::GetInstance()->BeginRenderPass();
- StateTracker::GetInstance()->SetPendingRebind();
- Util::SetViewportAndScissor(command_buffer, 0, 0, GetEFBWidth(), GetEFBHeight());
- vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
- vkCmdBindVertexBuffers(command_buffer, 0, 1, &vb_buffer, &vb_offset);
- vkCmdDraw(command_buffer, static_cast<u32>(vertex_count), 1, 0, 0);
-}
-
-void FramebufferManager::CreatePokeVertexFormat()
-{
- PortableVertexDeclaration vtx_decl = {};
- vtx_decl.position.enable = true;
- vtx_decl.position.type = VAR_FLOAT;
- vtx_decl.position.components = 4;
- vtx_decl.position.integer = false;
- vtx_decl.position.offset = offsetof(EFBPokeVertex, position);
- vtx_decl.colors[0].enable = true;
- vtx_decl.colors[0].type = VAR_UNSIGNED_BYTE;
- vtx_decl.colors[0].components = 4;
- vtx_decl.colors[0].integer = false;
- vtx_decl.colors[0].offset = offsetof(EFBPokeVertex, color);
- vtx_decl.stride = sizeof(EFBPokeVertex);
-
- m_poke_vertex_format = std::make_unique<VertexFormat>(vtx_decl);
-}
-
-bool FramebufferManager::CreatePokeVertexBuffer()
-{
- m_poke_vertex_stream_buffer = StreamBuffer::Create(
- VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, POKE_VERTEX_BUFFER_SIZE, POKE_VERTEX_BUFFER_SIZE);
- if (!m_poke_vertex_stream_buffer)
- {
- ERROR_LOG(VIDEO, "Failed to create EFB poke vertex buffer");
- return false;
- }
-
- return true;
-}
-
-void FramebufferManager::DestroyPokeVertexBuffer()
-{
- m_poke_vertex_stream_buffer.reset();
-}
-
-bool FramebufferManager::CompilePokeShaders()
-{
- static const char POKE_VERTEX_SHADER_SOURCE[] = R"(
- layout(location = 0) in vec4 ipos;
- layout(location = 5) in vec4 icol0;
-
- layout(location = 0) out vec4 col0;
-
- void main()
- {
- gl_Position = vec4(ipos.xyz, 1.0f);
- #if USE_POINT_SIZE
- gl_PointSize = ipos.w;
- #endif
- col0 = icol0;
- }
-
- )";
-
- static const char POKE_GEOMETRY_SHADER_SOURCE[] = R"(
- layout(triangles) in;
- layout(triangle_strip, max_vertices = EFB_LAYERS * 3) out;
-
- VARYING_LOCATION(0) in VertexData
- {
- vec4 col0;
- } in_data[];
-
- VARYING_LOCATION(0) out VertexData
- {
- vec4 col0;
- } out_data;
-
- void main()
- {
- for (int j = 0; j < EFB_LAYERS; j++)
- {
- for (int i = 0; i < 3; i++)
- {
- gl_Layer = j;
- gl_Position = gl_in[i].gl_Position;
- out_data.col0 = in_data[i].col0;
- EmitVertex();
- }
- EndPrimitive();
- }
- }
- )";
-
- static const char POKE_PIXEL_SHADER_SOURCE[] = R"(
- layout(location = 0) in vec4 col0;
- layout(location = 0) out vec4 ocol0;
- void main()
- {
- ocol0 = col0;
- }
- )";
-
- std::string source = g_shader_cache->GetUtilityShaderHeader();
- if (m_poke_primitive == PrimitiveType::Points)
- source += "#define USE_POINT_SIZE 1\n";
- source += POKE_VERTEX_SHADER_SOURCE;
- m_poke_vertex_shader = Util::CompileAndCreateVertexShader(source);
- if (m_poke_vertex_shader == VK_NULL_HANDLE)
- return false;
-
- if (g_vulkan_context->SupportsGeometryShaders())
- {
- source = g_shader_cache->GetUtilityShaderHeader() + POKE_GEOMETRY_SHADER_SOURCE;
- m_poke_geometry_shader = Util::CompileAndCreateGeometryShader(source);
- if (m_poke_geometry_shader == VK_NULL_HANDLE)
- return false;
- }
-
- source = g_shader_cache->GetUtilityShaderHeader() + POKE_PIXEL_SHADER_SOURCE;
- m_poke_fragment_shader = Util::CompileAndCreateFragmentShader(source);
- if (m_poke_fragment_shader == VK_NULL_HANDLE)
- return false;
-
- return true;
-}
-
-void FramebufferManager::DestroyPokeShaders()
-{
- if (m_poke_vertex_shader != VK_NULL_HANDLE)
- {
- vkDestroyShaderModule(g_vulkan_context->GetDevice(), m_poke_vertex_shader, nullptr);
- m_poke_vertex_shader = VK_NULL_HANDLE;
- }
- if (m_poke_geometry_shader != VK_NULL_HANDLE)
- {
- vkDestroyShaderModule(g_vulkan_context->GetDevice(), m_poke_geometry_shader, nullptr);
- m_poke_geometry_shader = VK_NULL_HANDLE;
- }
- if (m_poke_fragment_shader != VK_NULL_HANDLE)
- {
- vkDestroyShaderModule(g_vulkan_context->GetDevice(), m_poke_fragment_shader, nullptr);
- m_poke_vertex_shader = VK_NULL_HANDLE;
- }
-}
-
-} // namespace Vulkan
diff --git a/Source/Core/VideoBackends/Vulkan/FramebufferManager.h b/Source/Core/VideoBackends/Vulkan/FramebufferManager.h
deleted file mode 100644
index f037564e1c..0000000000
--- a/Source/Core/VideoBackends/Vulkan/FramebufferManager.h
+++ /dev/null
@@ -1,161 +0,0 @@
-// Copyright 2016 Dolphin Emulator Project
-// Licensed under GPLv2+
-// Refer to the license.txt file included.
-
-#pragma once
-
-#include <memory>
-#include <utility>
-
-#include "Common/CommonTypes.h"
-#include "VideoBackends/Vulkan/Constants.h"
-#include "VideoBackends/Vulkan/TextureCache.h"
-#include "VideoCommon/FramebufferManagerBase.h"
-#include "VideoCommon/RenderState.h"
-
-class AbstractStagingTexture;
-
-namespace Vulkan
-{
-class StateTracker;
-class StreamBuffer;
-class Texture2D;
-class VertexFormat;
-class VKTexture;
-class XFBSource;
-
-class FramebufferManager : public FramebufferManagerBase
-{
-public:
- FramebufferManager();
- ~FramebufferManager();
-
- static FramebufferManager* GetInstance();
-
- bool Initialize();
-
- VkRenderPass GetEFBLoadRenderPass() const { return m_efb_load_render_pass; }
- VkRenderPass GetEFBClearRenderPass() const { return m_efb_clear_render_pass; }
- Texture2D* GetEFBColorTexture() const { return m_efb_color_texture.get(); }
- Texture2D* GetEFBDepthTexture() const { return m_efb_depth_texture.get(); }
- VkFramebuffer GetEFBFramebuffer() const { return m_efb_framebuffer; }
- u32 GetEFBWidth() const;
- u32 GetEFBHeight() const;
- u32 GetEFBLayers() const;
- VkSampleCountFlagBits GetEFBSamples() const;
- MultisamplingState GetEFBMultisamplingState() const;
-
- void RecreateEFBFramebuffer();
-
- // Recompile shaders, use when MSAA mode changes.
- void RecompileShaders();
-
- // Reinterpret pixel format of EFB color texture.
- // Assumes no render pass is currently in progress.
- // Swaps EFB framebuffers, so re-bind afterwards.
- void ReinterpretPixelData(int convtype);
-
- // This render pass can be used for other readback operations.
- VkRenderPass GetColorCopyForReadbackRenderPass() const { return m_copy_color_render_pass; }
- // Resolve color/depth textures to a non-msaa texture, and return it.
- Texture2D* ResolveEFBColorTexture(const VkRect2D& region);
- Texture2D* ResolveEFBDepthTexture(const VkRect2D& region);
-
- // Returns the texture that the EFB color texture is resolved to when multisampling is enabled.
- // Ensure ResolveEFBColorTexture is called before this method.
- Texture2D* GetResolvedEFBColorTexture() const { return m_efb_resolve_color_texture.get(); }
- // Reads a framebuffer value back from the GPU. This may block if the cache is not current.
- u32 PeekEFBColor(u32 x, u32 y);
- float PeekEFBDepth(u32 x, u32 y);
- void InvalidatePeekCache();
-
- // Writes a value to the framebuffer. This will never block, and writes will be batched.
- void PokeEFBColor(u32 x, u32 y, u32 color);
- void PokeEFBDepth(u32 x, u32 y, float depth);
- void FlushEFBPokes();
-
-private:
- struct EFBPokeVertex
- {
- float position[4];
- u32 color;
- };
-
- bool CreateEFBRenderPasses();
- bool CreateEFBFramebuffer();
- void DestroyEFBFramebuffer();
-
- bool CompileConversionShaders();
- void DestroyConversionShaders();
-
- bool CreateReadbackRenderPasses();
- bool CompileReadbackShaders();
- void DestroyReadbackShaders();
- bool CreateReadbackTextures();
- void DestroyReadbackTextures();
- bool CreateReadbackFramebuffer();
- void DestroyReadbackFramebuffer();
-
- void CreatePokeVertexFormat();
- bool CreatePokeVertexBuffer();
- void DestroyPokeVertexBuffer();
- bool CompilePokeShaders();
- void DestroyPokeShaders();
-
- bool PopulateColorReadbackTexture();
- bool PopulateDepthReadbackTexture();
-
- void CreatePokeVertices(std::vector<EFBPokeVertex>* destination_list, u32 x, u32 y, float z,
- u32 color);
-
- void DrawPokeVertices(const EFBPokeVertex* vertices, size_t vertex_count, bool write_color,
- bool write_depth);
-
- VkRenderPass m_efb_load_render_pass = VK_NULL_HANDLE;
- VkRenderPass m_efb_clear_render_pass = VK_NULL_HANDLE;
- VkRenderPass m_depth_resolve_render_pass = VK_NULL_HANDLE;
-
- std::unique_ptr<Texture2D> m_efb_color_texture;
- std::unique_ptr<Texture2D> m_efb_convert_color_texture;
- std::unique_ptr<Texture2D> m_efb_depth_texture;
- std::unique_ptr<Texture2D> m_efb_resolve_color_texture;
- std::unique_ptr<Texture2D> m_efb_resolve_depth_texture;
- VkFramebuffer m_efb_framebuffer = VK_NULL_HANDLE;
- VkFramebuffer m_efb_convert_framebuffer = VK_NULL_HANDLE;
- VkFramebuffer m_depth_resolve_framebuffer = VK_NULL_HANDLE;
-
- // Format conversion shaders
- VkShaderModule m_ps_rgb8_to_rgba6 = VK_NULL_HANDLE;
- VkShaderModule m_ps_rgba6_to_rgb8 = VK_NULL_HANDLE;
- VkShaderModule m_ps_depth_resolve = VK_NULL_HANDLE;
-
- // EFB readback texture
- std::unique_ptr<Texture2D> m_color_copy_texture;
- std::unique_ptr<Texture2D> m_depth_copy_texture;
- VkFramebuffer m_color_copy_framebuffer = VK_NULL_HANDLE;
- VkFramebuffer m_depth_copy_framebuffer = VK_NULL_HANDLE;
-
- // CPU-side EFB readback texture
- std::unique_ptr<AbstractStagingTexture> m_color_readback_texture;
- std::unique_ptr<AbstractStagingTexture> m_depth_readback_texture;
- bool m_color_readback_texture_valid = false;
- bool m_depth_readback_texture_valid = false;
-
- // EFB poke drawing setup
- std::unique_ptr<VertexFormat> m_poke_vertex_format;
- std::unique_ptr<StreamBuffer> m_poke_vertex_stream_buffer;
- std::vector<EFBPokeVertex> m_color_poke_vertices;
- std::vector<EFBPokeVertex> m_depth_poke_vertices;
- PrimitiveType m_poke_primitive = PrimitiveType::TriangleStrip;
-
- VkRenderPass m_copy_color_render_pass = VK_NULL_HANDLE;
- VkRenderPass m_copy_depth_render_pass = VK_NULL_HANDLE;
- VkShaderModule m_copy_color_shader = VK_NULL_HANDLE;
- VkShaderModule m_copy_depth_shader = VK_NULL_HANDLE;
-
- VkShaderModule m_poke_vertex_shader = VK_NULL_HANDLE;
- VkShaderModule m_poke_geometry_shader = VK_NULL_HANDLE;
- VkShaderModule m_poke_fragment_shader = VK_NULL_HANDLE;
-};
-
-} // namespace Vulkan
diff --git a/Source/Core/VideoBackends/Vulkan/ObjectCache.cpp b/Source/Core/VideoBackends/Vulkan/ObjectCache.cpp
index 1de68b8349..59690118aa 100644
--- a/Source/Core/VideoBackends/Vulkan/ObjectCache.cpp
+++ b/Source/Core/VideoBackends/Vulkan/ObjectCache.cpp
@@ -19,7 +19,7 @@
#include "VideoBackends/Vulkan/CommandBufferManager.h"
#include "VideoBackends/Vulkan/ShaderCompiler.h"
#include "VideoBackends/Vulkan/StreamBuffer.h"
-#include "VideoBackends/Vulkan/Util.h"
+#include "VideoBackends/Vulkan/VKTexture.h"
#include "VideoBackends/Vulkan/VertexFormat.h"
#include "VideoBackends/Vulkan/VulkanContext.h"
#include "VideoCommon/Statistics.h"
@@ -28,16 +28,16 @@ namespace Vulkan
{
std::unique_ptr<ObjectCache> g_object_cache;
-ObjectCache::ObjectCache()
-{
-}
+ObjectCache::ObjectCache() = default;
ObjectCache::~ObjectCache()
{
+ DestroyPipelineCache();
DestroySamplers();
DestroyPipelineLayouts();
DestroyDescriptorSetLayouts();
DestroyRenderPassCache();
+ m_dummy_texture.reset();
}
bool ObjectCache::Initialize()
@@ -48,44 +48,37 @@ bool ObjectCache::Initialize()
if (!CreatePipelineLayouts())
return false;
- if (!CreateUtilityShaderVertexFormat())
- return false;
-
if (!CreateStaticSamplers())
return false;
m_texture_upload_buffer =
- StreamBuffer::Create(VK_BUFFER_USAGE_TRANSFER_SRC_BIT, INITIAL_TEXTURE_UPLOAD_BUFFER_SIZE,
- MAXIMUM_TEXTURE_UPLOAD_BUFFER_SIZE);
+ StreamBuffer::Create(VK_BUFFER_USAGE_TRANSFER_SRC_BIT, TEXTURE_UPLOAD_BUFFER_SIZE);
if (!m_texture_upload_buffer)
{
PanicAlert("Failed to create texture upload buffer");
return false;
}
- m_utility_shader_vertex_buffer =
- StreamBuffer::Create(VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, 1024 * 1024, 4 * 1024 * 1024);
- m_utility_shader_uniform_buffer =
- StreamBuffer::Create(VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, 1024, 4 * 1024 * 1024);
- if (!m_utility_shader_vertex_buffer || !m_utility_shader_uniform_buffer)
- return false;
-
- m_dummy_texture = Texture2D::Create(1, 1, 1, 1, VK_FORMAT_R8G8B8A8_UNORM, VK_SAMPLE_COUNT_1_BIT,
- VK_IMAGE_VIEW_TYPE_2D_ARRAY, VK_IMAGE_TILING_OPTIMAL,
- VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT);
- m_dummy_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentInitCommandBuffer(),
- VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
- VkClearColorValue clear_color = {};
- VkImageSubresourceRange clear_range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
- vkCmdClearColorImage(g_command_buffer_mgr->GetCurrentInitCommandBuffer(),
- m_dummy_texture->GetImage(), m_dummy_texture->GetLayout(), &clear_color, 1,
- &clear_range);
- m_dummy_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentInitCommandBuffer(),
- VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
+ if (g_ActiveConfig.bShaderCache)
+ {
+ if (!LoadPipelineCache())
+ return false;
+ }
+ else
+ {
+ if (!CreatePipelineCache())
+ return false;
+ }
return true;
}
+void ObjectCache::Shutdown()
+{
+ if (g_ActiveConfig.bShaderCache && m_pipeline_cache != VK_NULL_HANDLE)
+ SavePipelineCache();
+}
+
void ObjectCache::ClearSamplerCache()
{
for (const auto& it : m_sampler_cache)
@@ -115,13 +108,9 @@ void ObjectCache::DestroySamplers()
bool ObjectCache::CreateDescriptorSetLayouts()
{
- static const VkDescriptorSetLayoutBinding single_ubo_set_bindings[] = {
- 0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1,
- VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_GEOMETRY_BIT | VK_SHADER_STAGE_FRAGMENT_BIT};
-
// The geometry shader buffer must be last in this binding set, as we don't include it
// if geometry shaders are not supported by the device. See the decrement below.
- static const VkDescriptorSetLayoutBinding per_stage_ubo_set_bindings[] = {
+ static const VkDescriptorSetLayoutBinding standard_ubo_bindings[] = {
{UBO_DESCRIPTOR_SET_BINDING_PS, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1,
VK_SHADER_STAGE_FRAGMENT_BIT},
{UBO_DESCRIPTOR_SET_BINDING_VS, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1,
@@ -129,45 +118,56 @@ bool ObjectCache::CreateDescriptorSetLayouts()
{UBO_DESCRIPTOR_SET_BINDING_GS, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1,
VK_SHADER_STAGE_GEOMETRY_BIT}};
- static const VkDescriptorSetLayoutBinding sampler_set_bindings[] = {
+ static const VkDescriptorSetLayoutBinding standard_sampler_bindings[] = {
{0, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, static_cast<u32>(NUM_PIXEL_SHADER_SAMPLERS),
VK_SHADER_STAGE_FRAGMENT_BIT}};
- static const VkDescriptorSetLayoutBinding ssbo_set_bindings[] = {
+ static const VkDescriptorSetLayoutBinding standard_ssbo_bindings[] = {
{0, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_FRAGMENT_BIT}};
- static const VkDescriptorSetLayoutBinding texel_buffer_set_bindings[] = {
- {0, VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, 1, VK_SHADER_STAGE_FRAGMENT_BIT},
+ static const VkDescriptorSetLayoutBinding utility_ubo_bindings[] = {
+ 0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1,
+ VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_GEOMETRY_BIT | VK_SHADER_STAGE_FRAGMENT_BIT};
+
+ // Utility samplers aren't dynamically indexed.
+ static const VkDescriptorSetLayoutBinding utility_sampler_bindings[] = {
+ {0, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT},
+ {1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT},
+ {2, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT},
+ {3, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT},
+ {4, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT},
+ {5, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT},
+ {6, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT},
+ {7, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT},
+ {8, VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, 1, VK_SHADER_STAGE_FRAGMENT_BIT},
};
static const VkDescriptorSetLayoutBinding compute_set_bindings[] = {
{0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1, VK_SHADER_STAGE_COMPUTE_BIT},
{1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT},
{2, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT},
- {3, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT},
- {4, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT},
- {5, VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT},
- {6, VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT},
- {7, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, VK_SHADER_STAGE_COMPUTE_BIT},
+ {3, VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT},
+ {4, VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT},
+ {5, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, VK_SHADER_STAGE_COMPUTE_BIT},
};
VkDescriptorSetLayoutCreateInfo create_infos[NUM_DESCRIPTOR_SET_LAYOUTS] = {
{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, nullptr, 0,
- static_cast<u32>(ArraySize(single_ubo_set_bindings)), single_ubo_set_bindings},
+ static_cast<u32>(ArraySize(standard_ubo_bindings)), standard_ubo_bindings},
{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, nullptr, 0,
- static_cast<u32>(ArraySize(per_stage_ubo_set_bindings)), per_stage_ubo_set_bindings},
+ static_cast<u32>(ArraySize(standard_sampler_bindings)), standard_sampler_bindings},
{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, nullptr, 0,
- static_cast<u32>(ArraySize(sampler_set_bindings)), sampler_set_bindings},
+ static_cast<u32>(ArraySize(standard_ssbo_bindings)), standard_ssbo_bindings},
{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, nullptr, 0,
- static_cast<u32>(ArraySize(ssbo_set_bindings)), ssbo_set_bindings},
+ static_cast<u32>(ArraySize(utility_ubo_bindings)), utility_ubo_bindings},
{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, nullptr, 0,
- static_cast<u32>(ArraySize(texel_buffer_set_bindings)), texel_buffer_set_bindings},
+ static_cast<u32>(ArraySize(utility_sampler_bindings)), utility_sampler_bindings},
{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, nullptr, 0,
static_cast<u32>(ArraySize(compute_set_bindings)), compute_set_bindings}};
// Don't set the GS bit if geometry shaders aren't available.
- if (!g_vulkan_context->SupportsGeometryShaders())
- create_infos[DESCRIPTOR_SET_LAYOUT_PER_STAGE_UNIFORM_BUFFERS].bindingCount--;
+ if (!g_ActiveConfig.backend_info.bSupportsGeometryShaders)
+ create_infos[DESCRIPTOR_SET_LAYOUT_STANDARD_UNIFORM_BUFFERS].bindingCount--;
for (size_t i = 0; i < NUM_DESCRIPTOR_SET_LAYOUTS; i++)
{
@@ -199,22 +199,15 @@ bool ObjectCache::CreatePipelineLayouts()
// Descriptor sets for each pipeline layout.
// In the standard set, the SSBO must be the last descriptor, as we do not include it
// when fragment stores and atomics are not supported by the device.
- VkDescriptorSetLayout standard_sets[] = {
- m_descriptor_set_layouts[DESCRIPTOR_SET_LAYOUT_PER_STAGE_UNIFORM_BUFFERS],
- m_descriptor_set_layouts[DESCRIPTOR_SET_LAYOUT_PIXEL_SHADER_SAMPLERS],
- m_descriptor_set_layouts[DESCRIPTOR_SET_LAYOUT_SHADER_STORAGE_BUFFERS]};
- VkDescriptorSetLayout texture_conversion_sets[] = {
- m_descriptor_set_layouts[DESCRIPTOR_SET_LAYOUT_PER_STAGE_UNIFORM_BUFFERS],
- m_descriptor_set_layouts[DESCRIPTOR_SET_LAYOUT_PIXEL_SHADER_SAMPLERS],
- m_descriptor_set_layouts[DESCRIPTOR_SET_LAYOUT_TEXEL_BUFFERS]};
- VkDescriptorSetLayout utility_sets[] = {
- m_descriptor_set_layouts[DESCRIPTOR_SET_LAYOUT_SINGLE_UNIFORM_BUFFER],
- m_descriptor_set_layouts[DESCRIPTOR_SET_LAYOUT_PIXEL_SHADER_SAMPLERS]};
- VkDescriptorSetLayout compute_sets[] = {m_descriptor_set_layouts[DESCRIPTOR_SET_LAYOUT_COMPUTE]};
- VkPushConstantRange push_constant_range = {
- VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, PUSH_CONSTANT_BUFFER_SIZE};
- VkPushConstantRange compute_push_constant_range = {VK_SHADER_STAGE_COMPUTE_BIT, 0,
- PUSH_CONSTANT_BUFFER_SIZE};
+ const VkDescriptorSetLayout standard_sets[] = {
+ m_descriptor_set_layouts[DESCRIPTOR_SET_LAYOUT_STANDARD_UNIFORM_BUFFERS],
+ m_descriptor_set_layouts[DESCRIPTOR_SET_LAYOUT_STANDARD_SAMPLERS],
+ m_descriptor_set_layouts[DESCRIPTOR_SET_LAYOUT_STANDARD_SHADER_STORAGE_BUFFERS]};
+ const VkDescriptorSetLayout utility_sets[] = {
+ m_descriptor_set_layouts[DESCRIPTOR_SET_LAYOUT_UTILITY_UNIFORM_BUFFER],
+ m_descriptor_set_layouts[DESCRIPTOR_SET_LAYOUT_UTILITY_SAMPLERS]};
+ const VkDescriptorSetLayout compute_sets[] = {
+ m_descriptor_set_layouts[DESCRIPTOR_SET_LAYOUT_COMPUTE]};
// Info for each pipeline layout
VkPipelineLayoutCreateInfo pipeline_layout_info[NUM_PIPELINE_LAYOUTS] = {
@@ -222,25 +215,16 @@ bool ObjectCache::CreatePipelineLayouts()
{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, nullptr, 0,
static_cast<u32>(ArraySize(standard_sets)), standard_sets, 0, nullptr},
- // Push Constant
- {VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, nullptr, 0,
- static_cast<u32>(ArraySize(standard_sets)), standard_sets, 1, &push_constant_range},
-
- // Texture Conversion
- {VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, nullptr, 0,
- static_cast<u32>(ArraySize(texture_conversion_sets)), texture_conversion_sets, 1,
- &push_constant_range},
-
- // Texture Conversion
+ // Utility
{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, nullptr, 0,
static_cast<u32>(ArraySize(utility_sets)), utility_sets, 0, nullptr},
// Compute
{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, nullptr, 0,
- static_cast<u32>(ArraySize(compute_sets)), compute_sets, 1, &compute_push_constant_range}};
+ static_cast<u32>(ArraySize(compute_sets)), compute_sets, 0, nullptr}};
// If bounding box is unsupported, don't bother with the SSBO descriptor set.
- if (!g_vulkan_context->SupportsBoundingBox())
+ if (!g_ActiveConfig.backend_info.bSupportsBBox)
pipeline_layout_info[PIPELINE_LAYOUT_STANDARD].setLayoutCount--;
for (size_t i = 0; i < NUM_PIPELINE_LAYOUTS; i++)
@@ -265,30 +249,6 @@ void ObjectCache::DestroyPipelineLayouts()
}
}
-bool ObjectCache::CreateUtilityShaderVertexFormat()
-{
- PortableVertexDeclaration vtx_decl = {};
- vtx_decl.position.enable = true;
- vtx_decl.position.type = VAR_FLOAT;
- vtx_decl.position.components = 4;
- vtx_decl.position.integer = false;
- vtx_decl.position.offset = offsetof(UtilityShaderVertex, Position);
- vtx_decl.texcoords[0].enable = true;
- vtx_decl.texcoords[0].type = VAR_FLOAT;
- vtx_decl.texcoords[0].components = 4;
- vtx_decl.texcoords[0].integer = false;
- vtx_decl.texcoords[0].offset = offsetof(UtilityShaderVertex, TexCoord);
- vtx_decl.colors[0].enable = true;
- vtx_decl.colors[0].type = VAR_UNSIGNED_BYTE;
- vtx_decl.colors[0].components = 4;
- vtx_decl.colors[0].integer = false;
- vtx_decl.colors[0].offset = offsetof(UtilityShaderVertex, Color);
- vtx_decl.stride = sizeof(UtilityShaderVertex);
-
- m_utility_shader_vertex_format = std::make_unique<VertexFormat>(vtx_decl);
- return true;
-}
-
bool ObjectCache::CreateStaticSamplers()
{
VkSamplerCreateInfo create_info = {
@@ -472,4 +432,199 @@ void ObjectCache::DestroyRenderPassCache()
vkDestroyRenderPass(g_vulkan_context->GetDevice(), it.second, nullptr);
m_render_pass_cache.clear();
}
+
+class PipelineCacheReadCallback : public LinearDiskCacheReader<u32, u8>
+{
+public:
+ PipelineCacheReadCallback(std::vector<u8>* data) : m_data(data) {}
+ void Read(const u32& key, const u8* value, u32 value_size) override
+ {
+ m_data->resize(value_size);
+ if (value_size > 0)
+ memcpy(m_data->data(), value, value_size);
+ }
+
+private:
+ std::vector<u8>* m_data;
+};
+
+class PipelineCacheReadIgnoreCallback : public LinearDiskCacheReader<u32, u8>
+{
+public:
+ void Read(const u32& key, const u8* value, u32 value_size) override {}
+};
+
+bool ObjectCache::CreatePipelineCache()
+{
+ // Vulkan pipeline caches can be shared between games for shader compile time reduction.
+ // This assumes that drivers don't create all pipelines in the cache on load time, only
+ // when a lookup occurs that matches a pipeline (or pipeline data) in the cache.
+ m_pipeline_cache_filename = GetDiskShaderCacheFileName(APIType::Vulkan, "Pipeline", false, true);
+
+ VkPipelineCacheCreateInfo info = {
+ VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, // VkStructureType sType
+ nullptr, // const void* pNext
+ 0, // VkPipelineCacheCreateFlags flags
+ 0, // size_t initialDataSize
+ nullptr // const void* pInitialData
+ };
+
+ VkResult res =
+ vkCreatePipelineCache(g_vulkan_context->GetDevice(), &info, nullptr, &m_pipeline_cache);
+ if (res == VK_SUCCESS)
+ return true;
+
+ LOG_VULKAN_ERROR(res, "vkCreatePipelineCache failed: ");
+ return false;
+}
+
+bool ObjectCache::LoadPipelineCache()
+{
+ // We have to keep the pipeline cache file name around since when we save it
+ // we delete the old one, by which time the game's unique ID is already cleared.
+ m_pipeline_cache_filename = GetDiskShaderCacheFileName(APIType::Vulkan, "Pipeline", false, true);
+
+ std::vector<u8> disk_data;
+ LinearDiskCache<u32, u8> disk_cache;
+ PipelineCacheReadCallback read_callback(&disk_data);
+ if (disk_cache.OpenAndRead(m_pipeline_cache_filename, read_callback) != 1)
+ disk_data.clear();
+
+ if (!disk_data.empty() && !ValidatePipelineCache(disk_data.data(), disk_data.size()))
+ {
+ // Don't use this data. In fact, we should delete it to prevent it from being used next time.
+ File::Delete(m_pipeline_cache_filename);
+ return CreatePipelineCache();
+ }
+
+ VkPipelineCacheCreateInfo info = {
+ VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, // VkStructureType sType
+ nullptr, // const void* pNext
+ 0, // VkPipelineCacheCreateFlags flags
+ disk_data.size(), // size_t initialDataSize
+ disk_data.data() // const void* pInitialData
+ };
+
+ VkResult res =
+ vkCreatePipelineCache(g_vulkan_context->GetDevice(), &info, nullptr, &m_pipeline_cache);
+ if (res == VK_SUCCESS)
+ return true;
+
+ // Failed to create pipeline cache, try with it empty.
+ LOG_VULKAN_ERROR(res, "vkCreatePipelineCache failed, trying empty cache: ");
+ return CreatePipelineCache();
+}
+
+// Based on Vulkan 1.0 specification,
+// Table 9.1. Layout for pipeline cache header version VK_PIPELINE_CACHE_HEADER_VERSION_ONE
+// NOTE: This data is assumed to be in little-endian format.
+#pragma pack(push, 4)
+struct VK_PIPELINE_CACHE_HEADER
+{
+ u32 header_length;
+ u32 header_version;
+ u32 vendor_id;
+ u32 device_id;
+ u8 uuid[VK_UUID_SIZE];
+};
+#pragma pack(pop)
+static_assert(std::is_trivially_copyable<VK_PIPELINE_CACHE_HEADER>::value,
+ "VK_PIPELINE_CACHE_HEADER must be trivially copyable");
+
+bool ObjectCache::ValidatePipelineCache(const u8* data, size_t data_length)
+{
+ if (data_length < sizeof(VK_PIPELINE_CACHE_HEADER))
+ {
+ ERROR_LOG(VIDEO, "Pipeline cache failed validation: Invalid header");
+ return false;
+ }
+
+ VK_PIPELINE_CACHE_HEADER header;
+ std::memcpy(&header, data, sizeof(header));
+ if (header.header_length < sizeof(VK_PIPELINE_CACHE_HEADER))
+ {
+ ERROR_LOG(VIDEO, "Pipeline cache failed validation: Invalid header length");
+ return false;
+ }
+
+ if (header.header_version != VK_PIPELINE_CACHE_HEADER_VERSION_ONE)
+ {
+ ERROR_LOG(VIDEO, "Pipeline cache failed validation: Invalid header version");
+ return false;
+ }
+
+ if (header.vendor_id != g_vulkan_context->GetDeviceProperties().vendorID)
+ {
+ ERROR_LOG(VIDEO,
+ "Pipeline cache failed validation: Incorrect vendor ID (file: 0x%X, device: 0x%X)",
+ header.vendor_id, g_vulkan_context->GetDeviceProperties().vendorID);
+ return false;
+ }
+
+ if (header.device_id != g_vulkan_context->GetDeviceProperties().deviceID)
+ {
+ ERROR_LOG(VIDEO,
+ "Pipeline cache failed validation: Incorrect device ID (file: 0x%X, device: 0x%X)",
+ header.device_id, g_vulkan_context->GetDeviceProperties().deviceID);
+ return false;
+ }
+
+ if (std::memcmp(header.uuid, g_vulkan_context->GetDeviceProperties().pipelineCacheUUID,
+ VK_UUID_SIZE) != 0)
+ {
+ ERROR_LOG(VIDEO, "Pipeline cache failed validation: Incorrect UUID");
+ return false;
+ }
+
+ return true;
+}
+
+void ObjectCache::DestroyPipelineCache()
+{
+ vkDestroyPipelineCache(g_vulkan_context->GetDevice(), m_pipeline_cache, nullptr);
+ m_pipeline_cache = VK_NULL_HANDLE;
+}
+
+void ObjectCache::SavePipelineCache()
+{
+ size_t data_size;
+ VkResult res =
+ vkGetPipelineCacheData(g_vulkan_context->GetDevice(), m_pipeline_cache, &data_size, nullptr);
+ if (res != VK_SUCCESS)
+ {
+ LOG_VULKAN_ERROR(res, "vkGetPipelineCacheData failed: ");
+ return;
+ }
+
+ std::vector<u8> data(data_size);
+ res = vkGetPipelineCacheData(g_vulkan_context->GetDevice(), m_pipeline_cache, &data_size,
+ data.data());
+ if (res != VK_SUCCESS)
+ {
+ LOG_VULKAN_ERROR(res, "vkGetPipelineCacheData failed: ");
+ return;
+ }
+
+ // Delete the old cache and re-create.
+ File::Delete(m_pipeline_cache_filename);
+
+ // We write a single key of 1, with the entire pipeline cache data.
+ // Not ideal, but our disk cache class does not support just writing a single blob
+ // of data without specifying a key.
+ LinearDiskCache<u32, u8> disk_cache;
+ PipelineCacheReadIgnoreCallback callback;
+ disk_cache.OpenAndRead(m_pipeline_cache_filename, callback);
+ disk_cache.Append(1, data.data(), static_cast<u32>(data.size()));
+ disk_cache.Close();
+}
+
+void ObjectCache::ReloadPipelineCache()
+{
+ SavePipelineCache();
+
+ if (g_ActiveConfig.bShaderCache)
+ LoadPipelineCache();
+ else
+ CreatePipelineCache();
}
+} // namespace Vulkan
diff --git a/Source/Core/VideoBackends/Vulkan/ObjectCache.h b/Source/Core/VideoBackends/Vulkan/ObjectCache.h
index c3502f7c66..794c52c0f0 100644
--- a/Source/Core/VideoBackends/Vulkan/ObjectCache.h
+++ b/Source/Core/VideoBackends/Vulkan/ObjectCache.h
@@ -16,7 +16,6 @@
#include "Common/LinearDiskCache.h"
#include "VideoBackends/Vulkan/Constants.h"
-#include "VideoBackends/Vulkan/Texture2D.h"
#include "VideoCommon/GeometryShaderGen.h"
#include "VideoCommon/PixelShaderGen.h"
@@ -27,6 +26,7 @@ namespace Vulkan
{
class CommandBufferManager;
class VertexFormat;
+class VKTexture;
class StreamBuffer;
class ObjectCache
@@ -35,29 +35,23 @@ public:
ObjectCache();
~ObjectCache();
+ // Perform at startup, create descriptor layouts, compiles all static shaders.
+ bool Initialize();
+ void Shutdown();
+
// Descriptor set layout accessor. Used for allocating descriptor sets.
VkDescriptorSetLayout GetDescriptorSetLayout(DESCRIPTOR_SET_LAYOUT layout) const
{
return m_descriptor_set_layouts[layout];
}
+
// Pipeline layout accessor. Used to fill in required field in PipelineInfo.
VkPipelineLayout GetPipelineLayout(PIPELINE_LAYOUT layout) const
{
return m_pipeline_layouts[layout];
}
- // Shared utility shader resources
- VertexFormat* GetUtilityShaderVertexFormat() const
- {
- return m_utility_shader_vertex_format.get();
- }
- StreamBuffer* GetUtilityShaderVertexBuffer() const
- {
- return m_utility_shader_vertex_buffer.get();
- }
- StreamBuffer* GetUtilityShaderUniformBuffer() const
- {
- return m_utility_shader_uniform_buffer.get();
- }
+
+ // Staging buffer for textures.
StreamBuffer* GetTextureUploadBuffer() const { return m_texture_upload_buffer.get(); }
// Static samplers
@@ -65,36 +59,39 @@ public:
VkSampler GetLinearSampler() const { return m_linear_sampler; }
VkSampler GetSampler(const SamplerState& info);
- // Dummy image for samplers that are unbound
- Texture2D* GetDummyImage() const { return m_dummy_texture.get(); }
- VkImageView GetDummyImageView() const { return m_dummy_texture->GetView(); }
// Render pass cache.
VkRenderPass GetRenderPass(VkFormat color_format, VkFormat depth_format, u32 multisamples,
VkAttachmentLoadOp load_op);
- // Perform at startup, create descriptor layouts, compiles all static shaders.
- bool Initialize();
+ // Pipeline cache. Used when creating pipelines for drivers to store compiled programs.
+ VkPipelineCache GetPipelineCache() const { return m_pipeline_cache; }
// Clear sampler cache, use when anisotropy mode changes
// WARNING: Ensure none of the objects from here are in use when calling
void ClearSamplerCache();
+ // Saves the pipeline cache to disk. Call when shutting down.
+ void SavePipelineCache();
+
+ // Reload pipeline cache. Call when host config changes.
+ void ReloadPipelineCache();
+
private:
bool CreateDescriptorSetLayouts();
void DestroyDescriptorSetLayouts();
bool CreatePipelineLayouts();
void DestroyPipelineLayouts();
- bool CreateUtilityShaderVertexFormat();
bool CreateStaticSamplers();
void DestroySamplers();
void DestroyRenderPassCache();
+ bool CreatePipelineCache();
+ bool LoadPipelineCache();
+ bool ValidatePipelineCache(const u8* data, size_t data_length);
+ void DestroyPipelineCache();
std::array<VkDescriptorSetLayout, NUM_DESCRIPTOR_SET_LAYOUTS> m_descriptor_set_layouts = {};
std::array<VkPipelineLayout, NUM_PIPELINE_LAYOUTS> m_pipeline_layouts = {};
- std::unique_ptr<VertexFormat> m_utility_shader_vertex_format;
- std::unique_ptr<StreamBuffer> m_utility_shader_vertex_buffer;
- std::unique_ptr<StreamBuffer> m_utility_shader_uniform_buffer;
std::unique_ptr<StreamBuffer> m_texture_upload_buffer;
VkSampler m_point_sampler = VK_NULL_HANDLE;
@@ -103,11 +100,15 @@ private:
std::map<SamplerState, VkSampler> m_sampler_cache;
// Dummy image for samplers that are unbound
- std::unique_ptr<Texture2D> m_dummy_texture;
+ std::unique_ptr<VKTexture> m_dummy_texture;
// Render pass cache
using RenderPassCacheKey = std::tuple<VkFormat, VkFormat, u32, VkAttachmentLoadOp>;
std::map<RenderPassCacheKey, VkRenderPass> m_render_pass_cache;
+
+ // pipeline cache
+ VkPipelineCache m_pipeline_cache = VK_NULL_HANDLE;
+ std::string m_pipeline_cache_filename;
};
extern std::unique_ptr<ObjectCache> g_object_cache;
diff --git a/Source/Core/VideoBackends/Vulkan/PerfQuery.cpp b/Source/Core/VideoBackends/Vulkan/PerfQuery.cpp
index 25334e3eb4..3a84f2e571 100644
--- a/Source/Core/VideoBackends/Vulkan/PerfQuery.cpp
+++ b/Source/Core/VideoBackends/Vulkan/PerfQuery.cpp
@@ -13,20 +13,18 @@
#include "Common/MsgHandler.h"
#include "VideoBackends/Vulkan/CommandBufferManager.h"
+#include "VideoBackends/Vulkan/Renderer.h"
#include "VideoBackends/Vulkan/StagingBuffer.h"
#include "VideoBackends/Vulkan/StateTracker.h"
-#include "VideoBackends/Vulkan/Util.h"
#include "VideoBackends/Vulkan/VulkanContext.h"
namespace Vulkan
{
-PerfQuery::PerfQuery()
-{
-}
+PerfQuery::PerfQuery() = default;
PerfQuery::~PerfQuery()
{
- g_command_buffer_mgr->RemoveFencePointCallback(this);
+ g_command_buffer_mgr->RemoveFenceSignaledCallback(this);
if (m_query_pool != VK_NULL_HANDLE)
vkDestroyQueryPool(g_vulkan_context->GetDevice(), m_query_pool, nullptr);
@@ -51,11 +49,8 @@ bool PerfQuery::Initialize()
return false;
}
- g_command_buffer_mgr->AddFencePointCallback(
- this,
- std::bind(&PerfQuery::OnCommandBufferQueued, this, std::placeholders::_1,
- std::placeholders::_2),
- std::bind(&PerfQuery::OnCommandBufferExecuted, this, std::placeholders::_1));
+ g_command_buffer_mgr->AddFenceSignaledCallback(
+ this, std::bind(&PerfQuery::OnFenceSignaled, this, std::placeholders::_1));
return true;
}
@@ -92,9 +87,6 @@ void PerfQuery::EnableQuery(PerfQueryGroup type)
// TODO: Is this needed?
StateTracker::GetInstance()->BeginRenderPass();
vkCmdBeginQuery(g_command_buffer_mgr->GetCurrentCommandBuffer(), m_query_pool, index, flags);
-
- // Prevent background command buffer submission while the query is active.
- StateTracker::GetInstance()->SetBackgroundCommandBufferExecution(false);
}
}
@@ -105,8 +97,6 @@ void PerfQuery::DisableQuery(PerfQueryGroup type)
// DisableQuery should be called for each EnableQuery, so subtract one to get the previous one.
u32 index = (m_query_read_pos + m_query_count - 1) % PERF_QUERY_BUFFER_SIZE;
vkCmdEndQuery(g_command_buffer_mgr->GetCurrentCommandBuffer(), m_query_pool, index);
- StateTracker::GetInstance()->SetBackgroundCommandBufferExecution(true);
- DEBUG_LOG(VIDEO, "end query %u", index);
}
}
@@ -198,40 +188,42 @@ bool PerfQuery::CreateReadbackBuffer()
return true;
}
-void PerfQuery::QueueCopyQueryResults(VkCommandBuffer command_buffer, VkFence fence,
- u32 start_index, u32 query_count)
+void PerfQuery::QueueCopyQueryResults(u32 start_index, u32 query_count)
{
DEBUG_LOG(VIDEO, "queue copy of queries %u-%u", start_index, start_index + query_count - 1);
// Transition buffer for GPU write
// TODO: Is this needed?
- m_readback_buffer->PrepareForGPUWrite(command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT,
+ m_readback_buffer->PrepareForGPUWrite(g_command_buffer_mgr->GetCurrentCommandBuffer(),
+ VK_ACCESS_TRANSFER_WRITE_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT);
// Copy from queries -> buffer
- vkCmdCopyQueryPoolResults(command_buffer, m_query_pool, start_index, query_count,
- m_readback_buffer->GetBuffer(), start_index * sizeof(PerfQueryDataType),
- sizeof(PerfQueryDataType), VK_QUERY_RESULT_WAIT_BIT);
+ vkCmdCopyQueryPoolResults(g_command_buffer_mgr->GetCurrentCommandBuffer(), m_query_pool,
+ start_index, query_count, m_readback_buffer->GetBuffer(),
+ start_index * sizeof(PerfQueryDataType), sizeof(PerfQueryDataType),
+ VK_QUERY_RESULT_WAIT_BIT);
// Prepare for host readback
- m_readback_buffer->FlushGPUCache(command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT,
- VK_PIPELINE_STAGE_TRANSFER_BIT);
+ m_readback_buffer->FlushGPUCache(g_command_buffer_mgr->GetCurrentCommandBuffer(),
+ VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
// Reset queries so they're ready to use again
- vkCmdResetQueryPool(command_buffer, m_query_pool, start_index, query_count);
+ vkCmdResetQueryPool(g_command_buffer_mgr->GetCurrentCommandBuffer(), m_query_pool, start_index,
+ query_count);
// Flag all queries as available, but with a fence that has to be completed first
for (u32 i = 0; i < query_count; i++)
{
u32 index = start_index + i;
ActiveQuery& entry = m_query_buffer[index];
- entry.pending_fence = fence;
+ entry.pending_fence = g_command_buffer_mgr->GetCurrentCommandBufferFence();
entry.available = true;
entry.active = false;
}
}
-void PerfQuery::OnCommandBufferQueued(VkCommandBuffer command_buffer, VkFence fence)
+void PerfQuery::FlushQueries()
{
// Flag all pending queries that aren't available as available after execution.
u32 copy_start_index = 0;
@@ -254,7 +246,7 @@ void PerfQuery::OnCommandBufferQueued(VkCommandBuffer command_buffer, VkFence fe
ASSERT(entry.active);
if (index < copy_start_index)
{
- QueueCopyQueryResults(command_buffer, fence, copy_start_index, copy_count);
+ QueueCopyQueryResults(copy_start_index, copy_count);
copy_start_index = index;
copy_count = 0;
}
@@ -266,10 +258,10 @@ void PerfQuery::OnCommandBufferQueued(VkCommandBuffer command_buffer, VkFence fe
}
if (copy_count > 0)
- QueueCopyQueryResults(command_buffer, fence, copy_start_index, copy_count);
+ QueueCopyQueryResults(copy_start_index, copy_count);
}
-void PerfQuery::OnCommandBufferExecuted(VkFence fence)
+void PerfQuery::OnFenceSignaled(VkFence fence)
{
// Need to save these since ProcessResults will modify them.
u32 query_read_pos = m_query_read_pos;
@@ -350,7 +342,7 @@ void PerfQuery::NonBlockingPartialFlush()
// Submit a command buffer in the background if the front query is not bound to one.
// Ideally this will complete before the buffer fills.
if (m_query_buffer[m_query_read_pos].pending_fence == VK_NULL_HANDLE)
- Util::ExecuteCurrentCommandsAndRestoreState(true, false);
+ Renderer::GetInstance()->ExecuteCommandBuffer(true, false);
}
void PerfQuery::BlockingPartialFlush()
@@ -364,7 +356,7 @@ void PerfQuery::BlockingPartialFlush()
{
// This will callback OnCommandBufferQueued which will set the fence on the entry.
// We wait for completion, which will also call OnCommandBufferExecuted, and clear the fence.
- Util::ExecuteCurrentCommandsAndRestoreState(false, true);
+ Renderer::GetInstance()->ExecuteCommandBuffer(false, true);
}
else
{
@@ -373,4 +365,4 @@ void PerfQuery::BlockingPartialFlush()
g_command_buffer_mgr->WaitForFence(entry.pending_fence);
}
}
-}
+} // namespace Vulkan
diff --git a/Source/Core/VideoBackends/Vulkan/PerfQuery.h b/Source/Core/VideoBackends/Vulkan/PerfQuery.h
index c5f5d13e90..47ccf22a66 100644
--- a/Source/Core/VideoBackends/Vulkan/PerfQuery.h
+++ b/Source/Core/VideoBackends/Vulkan/PerfQuery.h
@@ -24,6 +24,7 @@ public:
static PerfQuery* GetInstance();
bool Initialize();
+ void FlushQueries();
void EnableQuery(PerfQueryGroup type) override;
void DisableQuery(PerfQueryGroup type) override;
@@ -43,12 +44,11 @@ private:
bool CreateQueryPool();
bool CreateReadbackBuffer();
- void QueueCopyQueryResults(VkCommandBuffer command_buffer, VkFence fence, u32 start_index,
- u32 query_count);
+ void QueueCopyQueryResults(u32 start_index, u32 query_count);
void ProcessResults(u32 start_index, u32 query_count);
void OnCommandBufferQueued(VkCommandBuffer command_buffer, VkFence fence);
- void OnCommandBufferExecuted(VkFence fence);
+ void OnFenceSignaled(VkFence fence);
void NonBlockingPartialFlush();
void BlockingPartialFlush();
diff --git a/Source/Core/VideoBackends/Vulkan/PostProcessing.cpp b/Source/Core/VideoBackends/Vulkan/PostProcessing.cpp
deleted file mode 100644
index 57dbd3e391..0000000000
--- a/Source/Core/VideoBackends/Vulkan/PostProcessing.cpp
+++ /dev/null
@@ -1,316 +0,0 @@
-// Copyright 2017 Dolphin Emulator Project
-// Licensed under GPLv2+
-// Refer to the license.txt file included.
-
-#include "VideoBackends/Vulkan/PostProcessing.h"
-#include <sstream>
-
-#include "Common/Assert.h"
-#include "Common/StringUtil.h"
-
-#include "VideoBackends/Vulkan/CommandBufferManager.h"
-#include "VideoBackends/Vulkan/ObjectCache.h"
-#include "VideoBackends/Vulkan/ShaderCache.h"
-#include "VideoBackends/Vulkan/Texture2D.h"
-#include "VideoBackends/Vulkan/Util.h"
-#include "VideoBackends/Vulkan/VulkanContext.h"
-
-#include "VideoCommon/VideoCommon.h"
-#include "VideoCommon/VideoConfig.h"
-
-namespace Vulkan
-{
-VulkanPostProcessing::~VulkanPostProcessing()
-{
- if (m_default_fragment_shader != VK_NULL_HANDLE)
- vkDestroyShaderModule(g_vulkan_context->GetDevice(), m_default_fragment_shader, nullptr);
- if (m_fragment_shader != VK_NULL_HANDLE)
- vkDestroyShaderModule(g_vulkan_context->GetDevice(), m_fragment_shader, nullptr);
-}
-
-bool VulkanPostProcessing::Initialize()
-{
- if (!CompileDefaultShader())
- return false;
-
- RecompileShader();
- return true;
-}
-
-void VulkanPostProcessing::BlitFromTexture(const TargetRectangle& dst, const TargetRectangle& src,
- const Texture2D* src_tex, int src_layer,
- VkRenderPass render_pass)
-{
- // If the source layer is negative we simply copy all available layers.
- VkShaderModule geometry_shader =
- src_layer < 0 ? g_shader_cache->GetPassthroughGeometryShader() : VK_NULL_HANDLE;
- VkShaderModule fragment_shader =
- m_fragment_shader != VK_NULL_HANDLE ? m_fragment_shader : m_default_fragment_shader;
- UtilityShaderDraw draw(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- g_object_cache->GetPipelineLayout(PIPELINE_LAYOUT_STANDARD), render_pass,
- g_shader_cache->GetPassthroughVertexShader(), geometry_shader,
- fragment_shader);
-
- // Source is always bound.
- draw.SetPSSampler(0, src_tex->GetView(), g_object_cache->GetLinearSampler());
-
- // No need to allocate uniforms for the default shader.
- // The config will also still contain the invalid shader at this point.
- if (fragment_shader != m_default_fragment_shader)
- {
- size_t uniforms_size = CalculateUniformsSize();
- u8* uniforms = draw.AllocatePSUniforms(uniforms_size);
- FillUniformBuffer(uniforms, src, src_tex, src_layer);
- draw.CommitPSUniforms(uniforms_size);
- }
-
- draw.DrawQuad(dst.left, dst.top, dst.GetWidth(), dst.GetHeight(), src.left, src.top, src_layer,
- src.GetWidth(), src.GetHeight(), static_cast<int>(src_tex->GetWidth()),
- static_cast<int>(src_tex->GetHeight()));
-}
-
-struct BuiltinUniforms
-{
- float resolution[4];
- float src_rect[4];
- u32 time;
- u32 unused[3];
-};
-
-size_t VulkanPostProcessing::CalculateUniformsSize() const
-{
- // Allocate a vec4 for each uniform to simplify allocation.
- return sizeof(BuiltinUniforms) + m_config.GetOptions().size() * sizeof(float) * 4;
-}
-
-void VulkanPostProcessing::FillUniformBuffer(u8* buf, const TargetRectangle& src,
- const Texture2D* src_tex, int src_layer)
-{
- float src_width_float = static_cast<float>(src_tex->GetWidth());
- float src_height_float = static_cast<float>(src_tex->GetHeight());
- BuiltinUniforms builtin_uniforms = {
- {src_width_float, src_height_float, 1.0f / src_width_float, 1.0f / src_height_float},
- {static_cast<float>(src.left) / src_width_float,
- static_cast<float>(src.top) / src_height_float,
- static_cast<float>(src.GetWidth()) / src_width_float,
- static_cast<float>(src.GetHeight()) / src_height_float},
- static_cast<u32>(m_timer.GetTimeElapsed())};
-
- std::memcpy(buf, &builtin_uniforms, sizeof(builtin_uniforms));
- buf += sizeof(builtin_uniforms);
-
- for (const auto& it : m_config.GetOptions())
- {
- union
- {
- u32 as_bool[4];
- s32 as_int[4];
- float as_float[4];
- } value = {};
-
- switch (it.second.m_type)
- {
- case PostProcessingShaderConfiguration::ConfigurationOption::OptionType::OPTION_BOOL:
- value.as_bool[0] = it.second.m_bool_value ? 1 : 0;
- break;
-
- case PostProcessingShaderConfiguration::ConfigurationOption::OptionType::OPTION_INTEGER:
- ASSERT(it.second.m_integer_values.size() < 4);
- std::copy_n(it.second.m_integer_values.begin(), it.second.m_integer_values.size(),
- value.as_int);
- break;
-
- case PostProcessingShaderConfiguration::ConfigurationOption::OptionType::OPTION_FLOAT:
- ASSERT(it.second.m_float_values.size() < 4);
- std::copy_n(it.second.m_float_values.begin(), it.second.m_float_values.size(),
- value.as_float);
- break;
- }
-
- std::memcpy(buf, &value, sizeof(value));
- buf += sizeof(value);
- }
-}
-
-constexpr char DEFAULT_FRAGMENT_SHADER_SOURCE[] = R"(
- layout(set = 1, binding = 0) uniform sampler2DArray samp0;
-
- layout(location = 0) in float3 uv0;
- layout(location = 1) in float4 col0;
- layout(location = 0) out float4 ocol0;
-
- void main()
- {
- ocol0 = float4(texture(samp0, uv0).xyz, 1.0);
- }
-)";
-
-constexpr char POSTPROCESSING_SHADER_HEADER[] = R"(
- SAMPLER_BINDING(0) uniform sampler2DArray samp0;
- SAMPLER_BINDING(1) uniform sampler2DArray samp1;
-
- layout(location = 0) in float3 uv0;
- layout(location = 1) in float4 col0;
- layout(location = 0) out float4 ocol0;
-
- // Interfacing functions
- // The EFB may have a zero alpha value, which we don't want to write to the frame dump, so set it to one here.
- float4 Sample()
- {
- return float4(texture(samp0, uv0).xyz, 1.0);
- }
-
- float4 SampleLocation(float2 location)
- {
- return float4(texture(samp0, float3(location, uv0.z)).xyz, 1.0);
- }
-
- float4 SampleLayer(int layer)
- {
- return float4(texture(samp0, float3(uv0.xy, float(layer))).xyz, 1.0);
- }
-
- #define SampleOffset(offset) float4(textureOffset(samp0, uv0, offset).xyz, 1.0)
-
- float2 GetResolution()
- {
- return options.resolution.xy;
- }
-
- float2 GetInvResolution()
- {
- return options.resolution.zw;
- }
-
- float2 GetCoordinates()
- {
- return uv0.xy;
- }
-
- uint GetTime()
- {
- return options.time;
- }
-
- void SetOutput(float4 color)
- {
- ocol0 = color;
- }
-
- #define GetOption(x) (options.x)
- #define OptionEnabled(x) (options.x != 0)
-
- // Workaround because there is no getter function for src rect/layer.
- float4 src_rect = options.src_rect;
- int layer = int(uv0.z);
-)";
-
-void VulkanPostProcessing::UpdateConfig()
-{
- if (m_config.GetShader() == g_ActiveConfig.sPostProcessingShader)
- return;
-
- RecompileShader();
-}
-
-bool VulkanPostProcessing::CompileDefaultShader()
-{
- m_default_fragment_shader = Util::CompileAndCreateFragmentShader(DEFAULT_FRAGMENT_SHADER_SOURCE);
- if (m_default_fragment_shader == VK_NULL_HANDLE)
- {
- PanicAlert("Failed to compile default post-processing shader.");
- return false;
- }
-
- return true;
-}
-
-bool VulkanPostProcessing::RecompileShader()
-{
- // As a driver can return the same new module pointer when destroying a shader and re-compiling,
- // we need to wipe out the pipeline cache, otherwise we risk using old pipelines with old shaders.
- // We can't just clear a single pipeline, because we don't know which render pass is going to be
- // used here either.
- if (m_fragment_shader != VK_NULL_HANDLE)
- {
- g_command_buffer_mgr->WaitForGPUIdle();
- g_shader_cache->ClearPipelineCache();
- vkDestroyShaderModule(g_vulkan_context->GetDevice(), m_fragment_shader, nullptr);
- m_fragment_shader = VK_NULL_HANDLE;
- }
-
- // If post-processing is disabled, just use the default shader.
- // This way we don't need to allocate uniforms.
- if (g_ActiveConfig.sPostProcessingShader.empty())
- return true;
-
- // Generate GLSL and compile the new shader.
- std::string main_code = m_config.LoadShader();
- std::string options_code = GetGLSLUniformBlock();
- std::string code = options_code + POSTPROCESSING_SHADER_HEADER + main_code;
- m_fragment_shader = Util::CompileAndCreateFragmentShader(code);
- if (m_fragment_shader == VK_NULL_HANDLE)
- {
- // BlitFromTexture will use the default shader as a fallback.
- PanicAlert("Failed to compile post-processing shader %s", m_config.GetShader().c_str());
- return false;
- }
-
- return true;
-}
-
-std::string VulkanPostProcessing::GetGLSLUniformBlock() const
-{
- std::stringstream ss;
- u32 unused_counter = 1;
- ss << "UBO_BINDING(std140, 1) uniform PSBlock {\n";
-
- // Builtin uniforms
- ss << " float4 resolution;\n";
- ss << " float4 src_rect;\n";
- ss << " uint time;\n";
- for (u32 i = 0; i < 3; i++)
- ss << " uint unused" << unused_counter++ << ";\n\n";
-
- // Custom options/uniforms
- for (const auto& it : m_config.GetOptions())
- {
- if (it.second.m_type ==
- PostProcessingShaderConfiguration::ConfigurationOption::OptionType::OPTION_BOOL)
- {
- ss << StringFromFormat(" int %s;\n", it.first.c_str());
- for (u32 i = 0; i < 3; i++)
- ss << " int unused" << unused_counter++ << ";\n";
- }
- else if (it.second.m_type ==
- PostProcessingShaderConfiguration::ConfigurationOption::OptionType::OPTION_INTEGER)
- {
- u32 count = static_cast<u32>(it.second.m_integer_values.size());
- if (count == 1)
- ss << StringFromFormat(" int %s;\n", it.first.c_str());
- else
- ss << StringFromFormat(" int%u %s;\n", count, it.first.c_str());
-
- for (u32 i = count; i < 4; i++)
- ss << " int unused" << unused_counter++ << ";\n";
- }
- else if (it.second.m_type ==
- PostProcessingShaderConfiguration::ConfigurationOption::OptionType::OPTION_FLOAT)
- {
- u32 count = static_cast<u32>(it.second.m_float_values.size());
- if (count == 1)
- ss << StringFromFormat(" float %s;\n", it.first.c_str());
- else
- ss << StringFromFormat(" float%u %s;\n", count, it.first.c_str());
-
- for (u32 i = count; i < 4; i++)
- ss << " float unused" << unused_counter++ << ";\n";
- }
- }
-
- ss << "} options;\n\n";
-
- return ss.str();
-}
-
-} // namespace Vulkan
diff --git a/Source/Core/VideoBackends/Vulkan/PostProcessing.h b/Source/Core/VideoBackends/Vulkan/PostProcessing.h
deleted file mode 100644
index e9c18b9d2d..0000000000
--- a/Source/Core/VideoBackends/Vulkan/PostProcessing.h
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright 2017 Dolphin Emulator Project
-// Licensed under GPLv2+
-// Refer to the license.txt file included.
-
-#pragma once
-
-#include <string>
-
-#include "VideoBackends/Vulkan/VulkanContext.h"
-
-#include "VideoCommon/PostProcessing.h"
-#include "VideoCommon/VideoCommon.h"
-
-namespace Vulkan
-{
-class Texture2D;
-
-class VulkanPostProcessing : public PostProcessingShaderImplementation
-{
-public:
- VulkanPostProcessing() = default;
- ~VulkanPostProcessing();
-
- bool Initialize();
-
- void BlitFromTexture(const TargetRectangle& dst, const TargetRectangle& src,
- const Texture2D* src_tex, int src_layer, VkRenderPass render_pass);
-
- void UpdateConfig();
-
-private:
- size_t CalculateUniformsSize() const;
- void FillUniformBuffer(u8* buf, const TargetRectangle& src, const Texture2D* src_tex,
- int src_layer);
-
- bool CompileDefaultShader();
- bool RecompileShader();
- std::string GetGLSLUniformBlock() const;
-
- VkShaderModule m_fragment_shader = VK_NULL_HANDLE;
- VkShaderModule m_default_fragment_shader = VK_NULL_HANDLE;
-};
-
-} // namespace
diff --git a/Source/Core/VideoBackends/Vulkan/Renderer.cpp b/Source/Core/VideoBackends/Vulkan/Renderer.cpp
index a3085aa486..0254f128a8 100644
--- a/Source/Core/VideoBackends/Vulkan/Renderer.cpp
+++ b/Source/Core/VideoBackends/Vulkan/Renderer.cpp
@@ -18,27 +18,22 @@
#include "VideoBackends/Vulkan/BoundingBox.h"
#include "VideoBackends/Vulkan/CommandBufferManager.h"
-#include "VideoBackends/Vulkan/FramebufferManager.h"
#include "VideoBackends/Vulkan/ObjectCache.h"
-#include "VideoBackends/Vulkan/PostProcessing.h"
+#include "VideoBackends/Vulkan/PerfQuery.h"
#include "VideoBackends/Vulkan/Renderer.h"
#include "VideoBackends/Vulkan/StateTracker.h"
#include "VideoBackends/Vulkan/StreamBuffer.h"
#include "VideoBackends/Vulkan/SwapChain.h"
-#include "VideoBackends/Vulkan/TextureCache.h"
-#include "VideoBackends/Vulkan/Util.h"
#include "VideoBackends/Vulkan/VKPipeline.h"
#include "VideoBackends/Vulkan/VKShader.h"
#include "VideoBackends/Vulkan/VKTexture.h"
+#include "VideoBackends/Vulkan/VertexFormat.h"
#include "VideoBackends/Vulkan/VulkanContext.h"
-#include "VideoCommon/BPFunctions.h"
-#include "VideoCommon/BPMemory.h"
#include "VideoCommon/DriverDetails.h"
-#include "VideoCommon/OnScreenDisplay.h"
-#include "VideoCommon/PixelEngine.h"
+#include "VideoCommon/FramebufferManager.h"
#include "VideoCommon/RenderState.h"
-#include "VideoCommon/TextureCacheBase.h"
+#include "VideoCommon/VertexManagerBase.h"
#include "VideoCommon/VideoBackendBase.h"
#include "VideoCommon/VideoCommon.h"
#include "VideoCommon/VideoConfig.h"
@@ -59,11 +54,6 @@ Renderer::Renderer(std::unique_ptr<SwapChain> swap_chain, float backbuffer_scale
Renderer::~Renderer() = default;
-Renderer* Renderer::GetInstance()
-{
- return static_cast<Renderer*>(g_renderer.get());
-}
-
bool Renderer::IsHeadless() const
{
return m_swap_chain == nullptr;
@@ -74,8 +64,6 @@ bool Renderer::Initialize()
if (!::Renderer::Initialize())
return false;
- BindEFBToStateTracker();
-
m_bounding_box = std::make_unique<BoundingBox>();
if (!m_bounding_box->Initialize())
{
@@ -83,34 +71,16 @@ bool Renderer::Initialize()
return false;
}
- if (g_vulkan_context->SupportsBoundingBox())
- {
- // Bind bounding box to state tracker
- StateTracker::GetInstance()->SetBBoxBuffer(m_bounding_box->GetGPUBuffer(),
- m_bounding_box->GetGPUBufferOffset(),
- m_bounding_box->GetGPUBufferSize());
- }
-
- // Initialize post processing.
- m_post_processor = std::make_unique<VulkanPostProcessing>();
- if (!static_cast<VulkanPostProcessing*>(m_post_processor.get())->Initialize())
- {
- PanicAlert("failed to initialize post processor.");
- return false;
- }
-
// Various initialization routines will have executed commands on the command buffer.
// Execute what we have done before beginning the first frame.
- g_command_buffer_mgr->PrepareToSubmitCommandBuffer();
- g_command_buffer_mgr->SubmitCommandBuffer(false);
- BeginFrame();
-
+ ExecuteCommandBuffer(true, false);
return true;
}
void Renderer::Shutdown()
{
::Renderer::Shutdown();
+ m_swap_chain.reset();
}
std::unique_ptr<AbstractTexture> Renderer::CreateTexture(const TextureConfig& config)
@@ -136,17 +106,22 @@ std::unique_ptr<AbstractShader> Renderer::CreateShaderFromBinary(ShaderStage sta
return VKShader::CreateFromBinary(stage, data, length);
}
+std::unique_ptr<NativeVertexFormat>
+Renderer::CreateNativeVertexFormat(const PortableVertexDeclaration& vtx_decl)
+{
+ return std::make_unique<VertexFormat>(vtx_decl);
+}
+
std::unique_ptr<AbstractPipeline> Renderer::CreatePipeline(const AbstractPipelineConfig& config)
{
return VKPipeline::Create(config);
}
-std::unique_ptr<AbstractFramebuffer>
-Renderer::CreateFramebuffer(const AbstractTexture* color_attachment,
- const AbstractTexture* depth_attachment)
+std::unique_ptr<AbstractFramebuffer> Renderer::CreateFramebuffer(AbstractTexture* color_attachment,
+ AbstractTexture* depth_attachment)
{
- return VKFramebuffer::Create(static_cast<const VKTexture*>(color_attachment),
- static_cast<const VKTexture*>(depth_attachment));
+ return VKFramebuffer::Create(static_cast<VKTexture*>(color_attachment),
+ static_cast<VKTexture*>(depth_attachment));
}
void Renderer::SetPipeline(const AbstractPipeline* pipeline)
@@ -154,90 +129,6 @@ void Renderer::SetPipeline(const AbstractPipeline* pipeline)
StateTracker::GetInstance()->SetPipeline(static_cast<const VKPipeline*>(pipeline));
}
-u32 Renderer::AccessEFB(EFBAccessType type, u32 x, u32 y, u32 poke_data)
-{
- if (type == EFBAccessType::PeekColor)
- {
- u32 color = FramebufferManager::GetInstance()->PeekEFBColor(x, y);
-
- // a little-endian value is expected to be returned
- color = ((color & 0xFF00FF00) | ((color >> 16) & 0xFF) | ((color << 16) & 0xFF0000));
-
- // check what to do with the alpha channel (GX_PokeAlphaRead)
- PixelEngine::UPEAlphaReadReg alpha_read_mode = PixelEngine::GetAlphaReadMode();
-
- if (bpmem.zcontrol.pixel_format == PEControl::RGBA6_Z24)
- {
- color = RGBA8ToRGBA6ToRGBA8(color);
- }
- else if (bpmem.zcontrol.pixel_format == PEControl::RGB565_Z16)
- {
- color = RGBA8ToRGB565ToRGBA8(color);
- }
- if (bpmem.zcontrol.pixel_format != PEControl::RGBA6_Z24)
- {
- color |= 0xFF000000;
- }
-
- if (alpha_read_mode.ReadMode == 2)
- {
- return color; // GX_READ_NONE
- }
- else if (alpha_read_mode.ReadMode == 1)
- {
- return color | 0xFF000000; // GX_READ_FF
- }
- else /*if(alpha_read_mode.ReadMode == 0)*/
- {
- return color & 0x00FFFFFF; // GX_READ_00
- }
- }
- else // if (type == EFBAccessType::PeekZ)
- {
- // Depth buffer is inverted for improved precision near far plane
- float depth = 1.0f - FramebufferManager::GetInstance()->PeekEFBDepth(x, y);
- u32 ret = 0;
-
- if (bpmem.zcontrol.pixel_format == PEControl::RGB565_Z16)
- {
- // if Z is in 16 bit format you must return a 16 bit integer
- ret = MathUtil::Clamp<u32>(static_cast<u32>(depth * 65536.0f), 0, 0xFFFF);
- }
- else
- {
- ret = MathUtil::Clamp<u32>(static_cast<u32>(depth * 16777216.0f), 0, 0xFFFFFF);
- }
-
- return ret;
- }
-}
-
-void Renderer::PokeEFB(EFBAccessType type, const EfbPokeData* points, size_t num_points)
-{
- if (type == EFBAccessType::PokeColor)
- {
- for (size_t i = 0; i < num_points; i++)
- {
- // Convert to expected format (BGRA->RGBA)
- // TODO: Check alpha, depending on mode?
- const EfbPokeData& point = points[i];
- u32 color = ((point.data & 0xFF00FF00) | ((point.data >> 16) & 0xFF) |
- ((point.data << 16) & 0xFF0000));
- FramebufferManager::GetInstance()->PokeEFBColor(point.x, point.y, color);
- }
- }
- else // if (type == EFBAccessType::PokeZ)
- {
- for (size_t i = 0; i < num_points; i++)
- {
- // Convert to floating-point depth.
- const EfbPokeData& point = points[i];
- float depth = (1.0f - float(point.data & 0xFFFFFF) / 16777216.0f);
- FramebufferManager::GetInstance()->PokeEFBDepth(point.x, point.y, depth);
- }
- }
-}
-
u16 Renderer::BBoxRead(int index)
{
s32 value = m_bounding_box->Get(static_cast<size_t>(index));
@@ -285,31 +176,18 @@ void Renderer::BBoxWrite(int index, u16 value)
m_bounding_box->Set(static_cast<size_t>(index), scaled_value);
}
-TargetRectangle Renderer::ConvertEFBRectangle(const EFBRectangle& rc)
+void Renderer::BBoxFlush()
{
- TargetRectangle result;
- result.left = EFBToScaledX(rc.left);
- result.top = EFBToScaledY(rc.top);
- result.right = EFBToScaledX(rc.right);
- result.bottom = EFBToScaledY(rc.bottom);
- return result;
-}
-
-void Renderer::BeginFrame()
-{
- // Activate a new command list, and restore state ready for the next draw
- g_command_buffer_mgr->ActivateCommandBuffer();
-
- // Ensure that the state tracker rebinds everything, and allocates a new set
- // of descriptors out of the next pool.
- StateTracker::GetInstance()->InvalidateDescriptorSets();
- StateTracker::GetInstance()->InvalidateConstants();
- StateTracker::GetInstance()->SetPendingRebind();
+ m_bounding_box->Flush();
+ m_bounding_box->Invalidate();
}
void Renderer::ClearScreen(const EFBRectangle& rc, bool color_enable, bool alpha_enable,
bool z_enable, u32 color, u32 z)
{
+ g_framebuffer_manager->FlushEFBPokes();
+ g_framebuffer_manager->InvalidatePeekCache();
+
// Native -> EFB coordinates
TargetRectangle target_rc = Renderer::ConvertEFBRectangle(rc);
@@ -340,7 +218,9 @@ void Renderer::ClearScreen(const EFBRectangle& rc, bool color_enable, bool alpha
clear_color_value.color.float32[1] = static_cast<float>((color >> 8) & 0xFF) / 255.0f;
clear_color_value.color.float32[2] = static_cast<float>((color >> 0) & 0xFF) / 255.0f;
clear_color_value.color.float32[3] = static_cast<float>((color >> 24) & 0xFF) / 255.0f;
- clear_depth_value.depthStencil.depth = (1.0f - (static_cast<float>(z & 0xFFFFFF) / 16777216.0f));
+ clear_depth_value.depthStencil.depth = static_cast<float>(z & 0xFFFFFF) / 16777216.0f;
+ if (!g_ActiveConfig.backend_info.bSupportsReversedDepthRange)
+ clear_depth_value.depthStencil.depth = 1.0f - clear_depth_value.depthStencil.depth;
// If we're not in a render pass (start of the frame), we can use a clear render pass
// to discard the data, rather than loading and then clearing.
@@ -396,7 +276,7 @@ void Renderer::ClearScreen(const EFBRectangle& rc, bool color_enable, bool alpha
}
if (num_clear_attachments > 0)
{
- VkClearRect vk_rect = {target_vk_rc, 0, FramebufferManager::GetInstance()->GetEFBLayers()};
+ VkClearRect vk_rect = {target_vk_rc, 0, g_framebuffer_manager->GetEFBLayers()};
if (!StateTracker::GetInstance()->IsWithinRenderArea(
target_vk_rc.offset.x, target_vk_rc.offset.y, target_vk_rc.extent.width,
target_vk_rc.extent.height))
@@ -414,57 +294,17 @@ void Renderer::ClearScreen(const EFBRectangle& rc, bool color_enable, bool alpha
if (!color_enable && !alpha_enable && !z_enable)
return;
- // Clearing must occur within a render pass.
- if (!StateTracker::GetInstance()->IsWithinRenderArea(target_vk_rc.offset.x, target_vk_rc.offset.y,
- target_vk_rc.extent.width,
- target_vk_rc.extent.height))
- {
- StateTracker::GetInstance()->EndClearRenderPass();
- }
- StateTracker::GetInstance()->BeginRenderPass();
- StateTracker::GetInstance()->SetPendingRebind();
-
- // Mask away the appropriate colors and use a shader
- BlendingState blend_state = RenderState::GetNoBlendingBlendState();
- blend_state.colorupdate = color_enable;
- blend_state.alphaupdate = alpha_enable;
-
- DepthState depth_state = RenderState::GetNoDepthTestingDepthStencilState();
- depth_state.testenable = z_enable;
- depth_state.updateenable = z_enable;
- depth_state.func = ZMode::ALWAYS;
-
- // No need to start a new render pass, but we do need to restore viewport state
- UtilityShaderDraw draw(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- g_object_cache->GetPipelineLayout(PIPELINE_LAYOUT_STANDARD),
- FramebufferManager::GetInstance()->GetEFBLoadRenderPass(),
- g_shader_cache->GetPassthroughVertexShader(),
- g_shader_cache->GetPassthroughGeometryShader(),
- g_shader_cache->GetClearFragmentShader());
-
- draw.SetMultisamplingState(FramebufferManager::GetInstance()->GetEFBMultisamplingState());
- draw.SetDepthState(depth_state);
- draw.SetBlendState(blend_state);
-
- draw.DrawColoredQuad(target_rc.left, target_rc.top, target_rc.GetWidth(), target_rc.GetHeight(),
- clear_color_value.color.float32[0], clear_color_value.color.float32[1],
- clear_color_value.color.float32[2], clear_color_value.color.float32[3],
- clear_depth_value.depthStencil.depth);
+ g_framebuffer_manager->ClearEFB(rc, color_enable, alpha_enable, z_enable, color, z);
}
-void Renderer::ReinterpretPixelData(unsigned int convtype)
+void Renderer::Flush()
{
- StateTracker::GetInstance()->EndRenderPass();
- StateTracker::GetInstance()->SetPendingRebind();
- FramebufferManager::GetInstance()->ReinterpretPixelData(convtype);
-
- // EFB framebuffer has now changed, so update accordingly.
- BindEFBToStateTracker();
+ ExecuteCommandBuffer(true, false);
}
-void Renderer::Flush()
+void Renderer::WaitForGPUIdle()
{
- Util::ExecuteCurrentCommandsAndRestoreState(true, false);
+ ExecuteCommandBuffer(false, true);
}
void Renderer::BindBackbuffer(const ClearColor& clear_color)
@@ -475,35 +315,13 @@ void Renderer::BindBackbuffer(const ClearColor& clear_color)
CheckForSurfaceChange();
CheckForSurfaceResize();
- // Ensure the worker thread is not still submitting a previous command buffer.
- // In other words, the last frame has been submitted (otherwise the next call would
- // be a race, as the image may not have been consumed yet).
- g_command_buffer_mgr->PrepareToSubmitCommandBuffer();
-
- VkResult res;
- if (!g_command_buffer_mgr->CheckLastPresentFail())
- {
- // Grab the next image from the swap chain in preparation for drawing the window.
- res = m_swap_chain->AcquireNextImage();
- }
- else
- {
- // If the last present failed, we need to recreate the swap chain.
- res = VK_ERROR_OUT_OF_DATE_KHR;
- }
-
+ VkResult res = g_command_buffer_mgr->CheckLastPresentFail() ? VK_ERROR_OUT_OF_DATE_KHR :
+ m_swap_chain->AcquireNextImage();
if (res == VK_SUBOPTIMAL_KHR || res == VK_ERROR_OUT_OF_DATE_KHR)
{
- // There's an issue here. We can't resize the swap chain while the GPU is still busy with it,
- // but calling WaitForGPUIdle would create a deadlock as PrepareToSubmitCommandBuffer has been
- // called by SwapImpl. WaitForGPUIdle waits on the semaphore, which PrepareToSubmitCommandBuffer
- // has already done, so it blocks indefinitely. To work around this, we submit the current
- // command buffer, resize the swap chain (which calls WaitForGPUIdle), and then finally call
- // PrepareToSubmitCommandBuffer to return to the state that the caller expects.
- g_command_buffer_mgr->SubmitCommandBuffer(false);
+ // Execute cmdbuffer before resizing, as the last frame could still be presenting.
+ ExecuteCommandBuffer(false, true);
m_swap_chain->ResizeSwapChain();
- BeginFrame();
- g_command_buffer_mgr->PrepareToSubmitCommandBuffer();
res = m_swap_chain->AcquireNextImage();
}
if (res != VK_SUCCESS)
@@ -512,30 +330,18 @@ void Renderer::BindBackbuffer(const ClearColor& clear_color)
// Transition from undefined (or present src, but it can be substituted) to
// color attachment ready for writing. These transitions must occur outside
// a render pass, unless the render pass declares a self-dependency.
- Texture2D* backbuffer = m_swap_chain->GetCurrentTexture();
- backbuffer->OverrideImageLayout(VK_IMAGE_LAYOUT_UNDEFINED);
- backbuffer->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
- m_current_framebuffer = nullptr;
- m_current_framebuffer_width = backbuffer->GetWidth();
- m_current_framebuffer_height = backbuffer->GetHeight();
-
- // Draw to the backbuffer.
- VkRect2D region = {{0, 0}, {backbuffer->GetWidth(), backbuffer->GetHeight()}};
- StateTracker::GetInstance()->SetRenderPass(m_swap_chain->GetLoadRenderPass(),
- m_swap_chain->GetClearRenderPass());
- StateTracker::GetInstance()->SetFramebuffer(m_swap_chain->GetCurrentFramebuffer(), region);
-
- // Begin render pass for rendering to the swap chain.
- VkClearValue clear_value = {{{0.0f, 0.0f, 0.0f, 1.0f}}};
- StateTracker::GetInstance()->BeginClearRenderPass(region, &clear_value, 1);
+ m_swap_chain->GetCurrentTexture()->OverrideImageLayout(VK_IMAGE_LAYOUT_UNDEFINED);
+ m_swap_chain->GetCurrentTexture()->TransitionToLayout(
+ g_command_buffer_mgr->GetCurrentCommandBuffer(), VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
+ SetAndClearFramebuffer(m_swap_chain->GetCurrentFramebuffer(),
+ ClearColor{{0.0f, 0.0f, 0.0f, 1.0f}});
}
void Renderer::PresentBackbuffer()
{
// End drawing to backbuffer
StateTracker::GetInstance()->EndRenderPass();
- StateTracker::GetInstance()->OnEndFrame();
+ PerfQuery::GetInstance()->FlushQueries();
// Transition the backbuffer to PRESENT_SRC to ensure all commands drawing
// to it have finished before present.
@@ -546,47 +352,25 @@ void Renderer::PresentBackbuffer()
// Because this final command buffer is rendering to the swap chain, we need to wait for
// the available semaphore to be signaled before executing the buffer. This final submission
// can happen off-thread in the background while we're preparing the next frame.
- g_command_buffer_mgr->SubmitCommandBuffer(true, m_swap_chain->GetImageAvailableSemaphore(),
- m_swap_chain->GetRenderingFinishedSemaphore(),
- m_swap_chain->GetSwapChain(),
+ g_command_buffer_mgr->SubmitCommandBuffer(true, m_swap_chain->GetSwapChain(),
m_swap_chain->GetCurrentImageIndex());
- BeginFrame();
+
+ // New cmdbuffer, so invalidate state.
+ StateTracker::GetInstance()->InvalidateCachedState();
}
-void Renderer::RenderXFBToScreen(const AbstractTexture* texture, const EFBRectangle& rc)
+void Renderer::ExecuteCommandBuffer(bool submit_off_thread, bool wait_for_completion)
{
- const TargetRectangle target_rc = GetTargetRectangle();
+ StateTracker::GetInstance()->EndRenderPass();
+ PerfQuery::GetInstance()->FlushQueries();
- VulkanPostProcessing* post_processor = static_cast<VulkanPostProcessing*>(m_post_processor.get());
- if (g_ActiveConfig.stereo_mode == StereoMode::SBS ||
- g_ActiveConfig.stereo_mode == StereoMode::TAB)
- {
- TargetRectangle left_rect;
- TargetRectangle right_rect;
- std::tie(left_rect, right_rect) = ConvertStereoRectangle(target_rc);
-
- post_processor->BlitFromTexture(left_rect, rc,
- static_cast<const VKTexture*>(texture)->GetRawTexIdentifier(),
- 0, m_swap_chain->GetLoadRenderPass());
- post_processor->BlitFromTexture(right_rect, rc,
- static_cast<const VKTexture*>(texture)->GetRawTexIdentifier(),
- 1, m_swap_chain->GetLoadRenderPass());
- }
- else if (g_ActiveConfig.stereo_mode == StereoMode::QuadBuffer)
- {
- post_processor->BlitFromTexture(target_rc, rc,
- static_cast<const VKTexture*>(texture)->GetRawTexIdentifier(),
- -1, m_swap_chain->GetLoadRenderPass());
- }
- else
- {
- post_processor->BlitFromTexture(target_rc, rc,
- static_cast<const VKTexture*>(texture)->GetRawTexIdentifier(),
- 0, m_swap_chain->GetLoadRenderPass());
- }
+ // If we're waiting for completion, don't bother waking the worker thread.
+ const VkFence pending_fence = g_command_buffer_mgr->GetCurrentCommandBufferFence();
+ g_command_buffer_mgr->SubmitCommandBuffer(submit_off_thread && wait_for_completion);
+ if (wait_for_completion)
+ g_command_buffer_mgr->WaitForFence(pending_fence);
- // The post-processor uses the old-style Vulkan draws, which mess with the tracked state.
- StateTracker::GetInstance()->SetPendingRebind();
+ StateTracker::GetInstance()->InvalidateCachedState();
}
void Renderer::CheckForSurfaceChange()
@@ -595,8 +379,7 @@ void Renderer::CheckForSurfaceChange()
return;
// Submit the current draws up until rendering the XFB.
- g_command_buffer_mgr->ExecuteCommandBuffer(false, false);
- g_command_buffer_mgr->WaitForGPUIdle();
+ ExecuteCommandBuffer(false, true);
// Clear the present failed flag, since we don't want to resize after recreating.
g_command_buffer_mgr->CheckLastPresentFail();
@@ -624,8 +407,7 @@ void Renderer::CheckForSurfaceResize()
}
// Wait for the GPU to catch up since we're going to destroy the swap chain.
- g_command_buffer_mgr->ExecuteCommandBuffer(false, false);
- g_command_buffer_mgr->WaitForGPUIdle();
+ ExecuteCommandBuffer(false, true);
// Clear the present failed flag, since we don't want to resize after recreating.
g_command_buffer_mgr->CheckLastPresentFail();
@@ -637,45 +419,29 @@ void Renderer::CheckForSurfaceResize()
void Renderer::OnConfigChanged(u32 bits)
{
- // Update texture cache settings with any changed options.
- TextureCache::GetInstance()->OnConfigChanged(g_ActiveConfig);
-
- // Handle settings that can cause the EFB framebuffer to change.
- if (bits & CONFIG_CHANGE_BIT_TARGET_SIZE)
- RecreateEFBFramebuffer();
-
- // MSAA samples changed, we need to recreate the EFB render pass.
- // If the stereoscopy mode changed, we need to recreate the buffers as well.
- // SSAA changed on/off, we have to recompile shaders.
- // Changing stereoscopy from off<->on also requires shaders to be recompiled.
- if (bits & (CONFIG_CHANGE_BIT_HOST_CONFIG | CONFIG_CHANGE_BIT_MULTISAMPLES))
- {
- RecreateEFBFramebuffer();
- FramebufferManager::GetInstance()->RecompileShaders();
- g_shader_cache->ReloadPipelineCache();
- g_shader_cache->RecompileSharedShaders();
- }
+ if (bits & CONFIG_CHANGE_BIT_HOST_CONFIG)
+ g_object_cache->ReloadPipelineCache();
// For vsync, we need to change the present mode, which means recreating the swap chain.
if (m_swap_chain && bits & CONFIG_CHANGE_BIT_VSYNC)
{
- g_command_buffer_mgr->WaitForGPUIdle();
+ ExecuteCommandBuffer(false, true);
m_swap_chain->SetVSync(g_ActiveConfig.bVSyncActive);
}
// For quad-buffered stereo we need to change the layer count, so recreate the swap chain.
if (m_swap_chain && bits & CONFIG_CHANGE_BIT_STEREO_MODE)
{
- g_command_buffer_mgr->WaitForGPUIdle();
+ ExecuteCommandBuffer(false, true);
m_swap_chain->RecreateSwapChain();
}
// Wipe sampler cache if force texture filtering or anisotropy changes.
if (bits & (CONFIG_CHANGE_BIT_ANISOTROPY | CONFIG_CHANGE_BIT_FORCE_TEXTURE_FILTERING))
+ {
+ ExecuteCommandBuffer(false, true);
ResetSamplerStates();
-
- // Check for a changed post-processing shader and recompile if needed.
- static_cast<VulkanPostProcessing*>(m_post_processor.get())->UpdateConfig();
+ }
}
void Renderer::OnSwapChainResized()
@@ -684,103 +450,55 @@ void Renderer::OnSwapChainResized()
m_backbuffer_height = m_swap_chain->GetHeight();
}
-void Renderer::BindEFBToStateTracker()
-{
- // Update framebuffer in state tracker
- VkRect2D framebuffer_size = {{0, 0},
- {FramebufferManager::GetInstance()->GetEFBWidth(),
- FramebufferManager::GetInstance()->GetEFBHeight()}};
- StateTracker::GetInstance()->SetRenderPass(
- FramebufferManager::GetInstance()->GetEFBLoadRenderPass(),
- FramebufferManager::GetInstance()->GetEFBClearRenderPass());
- StateTracker::GetInstance()->SetFramebuffer(
- FramebufferManager::GetInstance()->GetEFBFramebuffer(), framebuffer_size);
- m_current_framebuffer = nullptr;
- m_current_framebuffer_width = FramebufferManager::GetInstance()->GetEFBWidth();
- m_current_framebuffer_height = FramebufferManager::GetInstance()->GetEFBHeight();
-}
-
-void Renderer::RecreateEFBFramebuffer()
-{
- // Ensure the GPU is finished with the current EFB textures.
- g_command_buffer_mgr->WaitForGPUIdle();
- FramebufferManager::GetInstance()->RecreateEFBFramebuffer();
- BindEFBToStateTracker();
-
- // Viewport and scissor rect have to be reset since they will be scaled differently.
- BPFunctions::SetViewport();
- BPFunctions::SetScissor();
-}
-
-void Renderer::ApplyState()
+void Renderer::BindFramebuffer(VKFramebuffer* fb)
{
-}
-
-void Renderer::ResetAPIState()
-{
- // End the EFB render pass if active
StateTracker::GetInstance()->EndRenderPass();
-}
-
-void Renderer::RestoreAPIState()
-{
- StateTracker::GetInstance()->EndRenderPass();
- if (m_current_framebuffer)
- static_cast<const VKFramebuffer*>(m_current_framebuffer)->TransitionForSample();
-
- BindEFBToStateTracker();
- BPFunctions::SetViewport();
- BPFunctions::SetScissor();
-
- // Instruct the state tracker to re-bind everything before the next draw
- StateTracker::GetInstance()->SetPendingRebind();
-}
-void Renderer::BindFramebuffer(const VKFramebuffer* fb)
-{
- const VkRect2D render_area = {static_cast<int>(fb->GetWidth()),
- static_cast<int>(fb->GetHeight())};
-
- StateTracker::GetInstance()->EndRenderPass();
- if (m_current_framebuffer)
- static_cast<const VKFramebuffer*>(m_current_framebuffer)->TransitionForSample();
+ // Shouldn't be bound as a texture.
+ if (fb->GetColorAttachment())
+ {
+ StateTracker::GetInstance()->UnbindTexture(
+ static_cast<VKTexture*>(fb->GetColorAttachment())->GetView());
+ }
+ if (fb->GetDepthAttachment())
+ {
+ StateTracker::GetInstance()->UnbindTexture(
+ static_cast<VKTexture*>(fb->GetDepthAttachment())->GetView());
+ }
fb->TransitionForRender();
- StateTracker::GetInstance()->SetFramebuffer(fb->GetFB(), render_area);
- StateTracker::GetInstance()->SetRenderPass(fb->GetLoadRenderPass(), fb->GetClearRenderPass());
+ StateTracker::GetInstance()->SetFramebuffer(fb);
m_current_framebuffer = fb;
- m_current_framebuffer_width = fb->GetWidth();
- m_current_framebuffer_height = fb->GetHeight();
}
-void Renderer::SetFramebuffer(const AbstractFramebuffer* framebuffer)
+void Renderer::SetFramebuffer(AbstractFramebuffer* framebuffer)
{
- const VKFramebuffer* vkfb = static_cast<const VKFramebuffer*>(framebuffer);
+ if (m_current_framebuffer == framebuffer)
+ return;
+
+ VKFramebuffer* vkfb = static_cast<VKFramebuffer*>(framebuffer);
BindFramebuffer(vkfb);
- StateTracker::GetInstance()->BeginRenderPass();
}
-void Renderer::SetAndDiscardFramebuffer(const AbstractFramebuffer* framebuffer)
+void Renderer::SetAndDiscardFramebuffer(AbstractFramebuffer* framebuffer)
{
- const VKFramebuffer* vkfb = static_cast<const VKFramebuffer*>(framebuffer);
+ if (m_current_framebuffer == framebuffer)
+ return;
+
+ VKFramebuffer* vkfb = static_cast<VKFramebuffer*>(framebuffer);
BindFramebuffer(vkfb);
// If we're discarding, begin the discard pass, then switch to a load pass.
// This way if the command buffer is flushed, we don't start another discard pass.
- StateTracker::GetInstance()->SetRenderPass(vkfb->GetDiscardRenderPass(),
- vkfb->GetClearRenderPass());
- StateTracker::GetInstance()->BeginRenderPass();
- StateTracker::GetInstance()->SetRenderPass(vkfb->GetLoadRenderPass(), vkfb->GetClearRenderPass());
+ StateTracker::GetInstance()->BeginDiscardRenderPass();
}
-void Renderer::SetAndClearFramebuffer(const AbstractFramebuffer* framebuffer,
+void Renderer::SetAndClearFramebuffer(AbstractFramebuffer* framebuffer,
const ClearColor& color_value, float depth_value)
{
- const VKFramebuffer* vkfb = static_cast<const VKFramebuffer*>(framebuffer);
+ VKFramebuffer* vkfb = static_cast<VKFramebuffer*>(framebuffer);
BindFramebuffer(vkfb);
- const VkRect2D render_area = {static_cast<int>(vkfb->GetWidth()),
- static_cast<int>(vkfb->GetHeight())};
std::array<VkClearValue, 2> clear_values;
u32 num_clear_values = 0;
if (vkfb->GetColorFormat() != AbstractTextureFormat::Undefined)
@@ -795,7 +513,7 @@ void Renderer::SetAndClearFramebuffer(const AbstractFramebuffer* framebuffer,
clear_values[num_clear_values].depthStencil.stencil = 0;
num_clear_values++;
}
- StateTracker::GetInstance()->BeginClearRenderPass(render_area, clear_values.data(),
+ StateTracker::GetInstance()->BeginClearRenderPass(vkfb->GetRect(), clear_values.data(),
num_clear_values);
}
@@ -803,9 +521,27 @@ void Renderer::SetTexture(u32 index, const AbstractTexture* texture)
{
// Texture should always be in SHADER_READ_ONLY layout prior to use.
// This is so we don't need to transition during render passes.
- auto* tex = texture ? static_cast<const VKTexture*>(texture)->GetRawTexIdentifier() : nullptr;
- DEBUG_ASSERT(!tex || tex->GetLayout() == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
- StateTracker::GetInstance()->SetTexture(index, tex ? tex->GetView() : VK_NULL_HANDLE);
+ const VKTexture* tex = static_cast<const VKTexture*>(texture);
+ if (tex)
+ {
+ if (tex->GetLayout() != VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL)
+ {
+ if (StateTracker::GetInstance()->InRenderPass())
+ {
+ WARN_LOG(VIDEO, "Transitioning image in render pass in Renderer::SetTexture()");
+ StateTracker::GetInstance()->EndRenderPass();
+ }
+
+ tex->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
+ VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
+ }
+
+ StateTracker::GetInstance()->SetTexture(index, tex->GetView());
+ }
+ else
+ {
+ StateTracker::GetInstance()->SetTexture(0, VK_NULL_HANDLE);
+ }
}
void Renderer::SetSamplerState(u32 index, const SamplerState& state)
@@ -826,10 +562,27 @@ void Renderer::SetSamplerState(u32 index, const SamplerState& state)
m_sampler_states[index].hex = state.hex;
}
+void Renderer::SetComputeImageTexture(AbstractTexture* texture, bool read, bool write)
+{
+ VKTexture* vk_texture = static_cast<VKTexture*>(texture);
+ if (vk_texture)
+ {
+ StateTracker::GetInstance()->EndRenderPass();
+ StateTracker::GetInstance()->SetImageTexture(vk_texture->GetView());
+ vk_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
+ read ? (write ? VKTexture::ComputeImageLayout::ReadWrite :
+ VKTexture::ComputeImageLayout::ReadOnly) :
+ VKTexture::ComputeImageLayout::WriteOnly);
+ }
+ else
+ {
+ StateTracker::GetInstance()->SetImageTexture(VK_NULL_HANDLE);
+ }
+}
+
void Renderer::UnbindTexture(const AbstractTexture* texture)
{
- StateTracker::GetInstance()->UnbindTexture(
- static_cast<const VKTexture*>(texture)->GetRawTexIdentifier()->GetView());
+ StateTracker::GetInstance()->UnbindTexture(static_cast<const VKTexture*>(texture)->GetView());
}
void Renderer::ResetSamplerStates()
@@ -839,7 +592,7 @@ void Renderer::ResetSamplerStates()
g_command_buffer_mgr->WaitForGPUIdle();
// Invalidate all sampler states, next draw will re-initialize them.
- for (size_t i = 0; i < m_sampler_states.size(); i++)
+ for (u32 i = 0; i < m_sampler_states.size(); i++)
{
m_sampler_states[i].hex = RenderState::GetPointSamplerState().hex;
StateTracker::GetInstance()->SetSampler(i, g_object_cache->GetPointSampler());
@@ -849,10 +602,6 @@ void Renderer::ResetSamplerStates()
g_object_cache->ClearSamplerCache();
}
-void Renderer::SetInterlacingMode()
-{
-}
-
void Renderer::SetScissorRect(const MathUtil::Rectangle<int>& rc)
{
VkRect2D scissor = {{rc.left, rc.top},
@@ -863,14 +612,13 @@ void Renderer::SetScissorRect(const MathUtil::Rectangle<int>& rc)
void Renderer::SetViewport(float x, float y, float width, float height, float near_depth,
float far_depth)
{
- VkViewport viewport = {x, y, std::max(width, 1.0f), std::max(height, 1.0f),
- near_depth, far_depth};
+ VkViewport viewport = {x, y, width, height, near_depth, far_depth};
StateTracker::GetInstance()->SetViewport(viewport);
}
void Renderer::Draw(u32 base_vertex, u32 num_vertices)
{
- if (StateTracker::GetInstance()->Bind())
+ if (!StateTracker::GetInstance()->Bind())
return;
vkCmdDraw(g_command_buffer_mgr->GetCurrentCommandBuffer(), num_vertices, 1, base_vertex, 0);
@@ -884,4 +632,13 @@ void Renderer::DrawIndexed(u32 base_index, u32 num_indices, u32 base_vertex)
vkCmdDrawIndexed(g_command_buffer_mgr->GetCurrentCommandBuffer(), num_indices, 1, base_index,
base_vertex, 0);
}
+
+void Renderer::DispatchComputeShader(const AbstractShader* shader, u32 groups_x, u32 groups_y,
+ u32 groups_z)
+{
+ StateTracker::GetInstance()->SetComputeShader(static_cast<const VKShader*>(shader));
+ if (StateTracker::GetInstance()->BindCompute())
+ vkCmdDispatch(g_command_buffer_mgr->GetCurrentCommandBuffer(), groups_x, groups_y, groups_z);
+}
+
} // namespace Vulkan
diff --git a/Source/Core/VideoBackends/Vulkan/Renderer.h b/Source/Core/VideoBackends/Vulkan/Renderer.h
index 43e97279f0..2b3390b263 100644
--- a/Source/Core/VideoBackends/Vulkan/Renderer.h
+++ b/Source/Core/VideoBackends/Vulkan/Renderer.h
@@ -17,10 +17,8 @@ struct XFBSourceBase;
namespace Vulkan
{
class BoundingBox;
-class FramebufferManager;
class SwapChain;
class StagingTexture2D;
-class Texture2D;
class VKFramebuffer;
class VKPipeline;
class VKTexture;
@@ -31,7 +29,7 @@ public:
Renderer(std::unique_ptr<SwapChain> swap_chain, float backbuffer_scale);
~Renderer() override;
- static Renderer* GetInstance();
+ static Renderer* GetInstance() { return static_cast<Renderer*>(g_renderer.get()); }
bool IsHeadless() const override;
@@ -42,67 +40,60 @@ public:
std::unique_ptr<AbstractStagingTexture>
CreateStagingTexture(StagingTextureType type, const TextureConfig& config) override;
std::unique_ptr<AbstractFramebuffer>
- CreateFramebuffer(const AbstractTexture* color_attachment,
- const AbstractTexture* depth_attachment) override;
+ CreateFramebuffer(AbstractTexture* color_attachment, AbstractTexture* depth_attachment) override;
std::unique_ptr<AbstractShader> CreateShaderFromSource(ShaderStage stage, const char* source,
size_t length) override;
std::unique_ptr<AbstractShader> CreateShaderFromBinary(ShaderStage stage, const void* data,
size_t length) override;
+ std::unique_ptr<NativeVertexFormat>
+ CreateNativeVertexFormat(const PortableVertexDeclaration& vtx_decl) override;
std::unique_ptr<AbstractPipeline> CreatePipeline(const AbstractPipelineConfig& config) override;
SwapChain* GetSwapChain() const { return m_swap_chain.get(); }
BoundingBox* GetBoundingBox() const { return m_bounding_box.get(); }
- u32 AccessEFB(EFBAccessType type, u32 x, u32 y, u32 poke_data) override;
- void PokeEFB(EFBAccessType type, const EfbPokeData* points, size_t num_points) override;
u16 BBoxRead(int index) override;
void BBoxWrite(int index, u16 value) override;
- TargetRectangle ConvertEFBRectangle(const EFBRectangle& rc) override;
+ void BBoxFlush() override;
void Flush() override;
- void RenderXFBToScreen(const AbstractTexture* texture, const EFBRectangle& rc) override;
+ void WaitForGPUIdle() override;
void OnConfigChanged(u32 bits) override;
void ClearScreen(const EFBRectangle& rc, bool color_enable, bool alpha_enable, bool z_enable,
u32 color, u32 z) override;
- void ReinterpretPixelData(unsigned int convtype) override;
-
- void ApplyState() override;
-
- void ResetAPIState() override;
- void RestoreAPIState() override;
-
void SetPipeline(const AbstractPipeline* pipeline) override;
- void SetFramebuffer(const AbstractFramebuffer* framebuffer) override;
- void SetAndDiscardFramebuffer(const AbstractFramebuffer* framebuffer) override;
- void SetAndClearFramebuffer(const AbstractFramebuffer* framebuffer,
- const ClearColor& color_value = {},
+ void SetFramebuffer(AbstractFramebuffer* framebuffer) override;
+ void SetAndDiscardFramebuffer(AbstractFramebuffer* framebuffer) override;
+ void SetAndClearFramebuffer(AbstractFramebuffer* framebuffer, const ClearColor& color_value = {},
float depth_value = 0.0f) override;
void SetScissorRect(const MathUtil::Rectangle<int>& rc) override;
void SetTexture(u32 index, const AbstractTexture* texture) override;
void SetSamplerState(u32 index, const SamplerState& state) override;
+ void SetComputeImageTexture(AbstractTexture* texture, bool read, bool write) override;
void UnbindTexture(const AbstractTexture* texture) override;
- void SetInterlacingMode() override;
void SetViewport(float x, float y, float width, float height, float near_depth,
float far_depth) override;
void Draw(u32 base_vertex, u32 num_vertices) override;
void DrawIndexed(u32 base_index, u32 num_indices, u32 base_vertex) override;
+ void DispatchComputeShader(const AbstractShader* shader, u32 groups_x, u32 groups_y,
+ u32 groups_z) override;
void BindBackbuffer(const ClearColor& clear_color = {}) override;
void PresentBackbuffer() override;
-private:
- void BeginFrame();
+ // Completes the current render pass, executes the command buffer, and restores state ready for
+ // next render. Use when you want to kick the current buffer to make room for new data.
+ void ExecuteCommandBuffer(bool execute_off_thread, bool wait_for_completion = false);
+private:
void CheckForSurfaceChange();
void CheckForSurfaceResize();
void ResetSamplerStates();
void OnSwapChainResized();
- void BindEFBToStateTracker();
- void RecreateEFBFramebuffer();
- void BindFramebuffer(const VKFramebuffer* fb);
+ void BindFramebuffer(VKFramebuffer* fb);
std::unique_ptr<SwapChain> m_swap_chain;
std::unique_ptr<BoundingBox> m_bounding_box;
@@ -110,4 +101,4 @@ private:
// Keep a copy of sampler states to avoid cache lookups every draw
std::array<SamplerState, NUM_PIXEL_SHADER_SAMPLERS> m_sampler_states = {};
};
-}
+} // namespace Vulkan
diff --git a/Source/Core/VideoBackends/Vulkan/ShaderCache.cpp b/Source/Core/VideoBackends/Vulkan/ShaderCache.cpp
deleted file mode 100644
index 33181e920c..0000000000
--- a/Source/Core/VideoBackends/Vulkan/ShaderCache.cpp
+++ /dev/null
@@ -1,859 +0,0 @@
-// Copyright 2016 Dolphin Emulator Project
-// Licensed under GPLv2+
-// Refer to the license.txt file included.
-
-#include "VideoBackends/Vulkan/ShaderCache.h"
-
-#include <algorithm>
-#include <sstream>
-#include <type_traits>
-#include <xxhash.h>
-
-#include "Common/Assert.h"
-#include "Common/CommonFuncs.h"
-#include "Common/LinearDiskCache.h"
-#include "Common/MsgHandler.h"
-
-#include "Core/ConfigManager.h"
-#include "Core/Host.h"
-
-#include "VideoBackends/Vulkan/FramebufferManager.h"
-#include "VideoBackends/Vulkan/ShaderCompiler.h"
-#include "VideoBackends/Vulkan/StreamBuffer.h"
-#include "VideoBackends/Vulkan/Util.h"
-#include "VideoBackends/Vulkan/VertexFormat.h"
-#include "VideoBackends/Vulkan/VulkanContext.h"
-#include "VideoCommon/Statistics.h"
-
-namespace Vulkan
-{
-std::unique_ptr<ShaderCache> g_shader_cache;
-
-ShaderCache::ShaderCache()
-{
-}
-
-ShaderCache::~ShaderCache()
-{
- DestroyPipelineCache();
- DestroySharedShaders();
-}
-
-bool ShaderCache::Initialize()
-{
- if (g_ActiveConfig.bShaderCache)
- {
- if (!LoadPipelineCache())
- return false;
- }
- else
- {
- if (!CreatePipelineCache())
- return false;
- }
-
- if (!CompileSharedShaders())
- return false;
-
- return true;
-}
-
-void ShaderCache::Shutdown()
-{
- if (g_ActiveConfig.bShaderCache && m_pipeline_cache != VK_NULL_HANDLE)
- SavePipelineCache();
-}
-
-static bool IsStripPrimitiveTopology(VkPrimitiveTopology topology)
-{
- return topology == VK_PRIMITIVE_TOPOLOGY_LINE_STRIP ||
- topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP ||
- topology == VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY ||
- topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY;
-}
-
-static VkPipelineRasterizationStateCreateInfo
-GetVulkanRasterizationState(const RasterizationState& state)
-{
- static constexpr std::array<VkCullModeFlags, 4> cull_modes = {
- {VK_CULL_MODE_NONE, VK_CULL_MODE_BACK_BIT, VK_CULL_MODE_FRONT_BIT,
- VK_CULL_MODE_FRONT_AND_BACK}};
-
- bool depth_clamp = g_ActiveConfig.backend_info.bSupportsDepthClamp;
-
- return {
- VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO, // VkStructureType sType
- nullptr, // const void* pNext
- 0, // VkPipelineRasterizationStateCreateFlags flags
- depth_clamp, // VkBool32 depthClampEnable
- VK_FALSE, // VkBool32 rasterizerDiscardEnable
- VK_POLYGON_MODE_FILL, // VkPolygonMode polygonMode
- cull_modes[state.cullmode], // VkCullModeFlags cullMode
- VK_FRONT_FACE_CLOCKWISE, // VkFrontFace frontFace
- VK_FALSE, // VkBool32 depthBiasEnable
- 0.0f, // float depthBiasConstantFactor
- 0.0f, // float depthBiasClamp
- 0.0f, // float depthBiasSlopeFactor
- 1.0f // float lineWidth
- };
-}
-
-static VkPipelineMultisampleStateCreateInfo
-GetVulkanMultisampleState(const MultisamplingState& state)
-{
- return {
- VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO, // VkStructureType sType
- nullptr, // const void* pNext
- 0, // VkPipelineMultisampleStateCreateFlags flags
- static_cast<VkSampleCountFlagBits>(
- state.samples.Value()), // VkSampleCountFlagBits rasterizationSamples
- state.per_sample_shading, // VkBool32 sampleShadingEnable
- 1.0f, // float minSampleShading
- nullptr, // const VkSampleMask* pSampleMask;
- VK_FALSE, // VkBool32 alphaToCoverageEnable
- VK_FALSE // VkBool32 alphaToOneEnable
- };
-}
-
-static VkPipelineDepthStencilStateCreateInfo GetVulkanDepthStencilState(const DepthState& state)
-{
- // Less/greater are swapped due to inverted depth.
- static constexpr std::array<VkCompareOp, 8> funcs = {
- {VK_COMPARE_OP_NEVER, VK_COMPARE_OP_GREATER, VK_COMPARE_OP_EQUAL,
- VK_COMPARE_OP_GREATER_OR_EQUAL, VK_COMPARE_OP_LESS, VK_COMPARE_OP_NOT_EQUAL,
- VK_COMPARE_OP_LESS_OR_EQUAL, VK_COMPARE_OP_ALWAYS}};
-
- return {
- VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO, // VkStructureType sType
- nullptr, // const void* pNext
- 0, // VkPipelineDepthStencilStateCreateFlags flags
- state.testenable, // VkBool32 depthTestEnable
- state.updateenable, // VkBool32 depthWriteEnable
- funcs[state.func], // VkCompareOp depthCompareOp
- VK_FALSE, // VkBool32 depthBoundsTestEnable
- VK_FALSE, // VkBool32 stencilTestEnable
- {}, // VkStencilOpState front
- {}, // VkStencilOpState back
- 0.0f, // float minDepthBounds
- 1.0f // float maxDepthBounds
- };
-}
-
-static VkPipelineColorBlendAttachmentState GetVulkanAttachmentBlendState(const BlendingState& state)
-{
- VkPipelineColorBlendAttachmentState vk_state = {};
- vk_state.blendEnable = static_cast<VkBool32>(state.blendenable);
- vk_state.colorBlendOp = state.subtract ? VK_BLEND_OP_REVERSE_SUBTRACT : VK_BLEND_OP_ADD;
- vk_state.alphaBlendOp = state.subtractAlpha ? VK_BLEND_OP_REVERSE_SUBTRACT : VK_BLEND_OP_ADD;
-
- if (state.usedualsrc && g_vulkan_context->SupportsDualSourceBlend())
- {
- static constexpr std::array<VkBlendFactor, 8> src_factors = {
- {VK_BLEND_FACTOR_ZERO, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_DST_COLOR,
- VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR, VK_BLEND_FACTOR_SRC1_ALPHA,
- VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA, VK_BLEND_FACTOR_DST_ALPHA,
- VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA}};
- static constexpr std::array<VkBlendFactor, 8> dst_factors = {
- {VK_BLEND_FACTOR_ZERO, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_SRC_COLOR,
- VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR, VK_BLEND_FACTOR_SRC1_ALPHA,
- VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA, VK_BLEND_FACTOR_DST_ALPHA,
- VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA}};
-
- vk_state.srcColorBlendFactor = src_factors[state.srcfactor];
- vk_state.srcAlphaBlendFactor = src_factors[state.srcfactoralpha];
- vk_state.dstColorBlendFactor = dst_factors[state.dstfactor];
- vk_state.dstAlphaBlendFactor = dst_factors[state.dstfactoralpha];
- }
- else
- {
- static constexpr std::array<VkBlendFactor, 8> src_factors = {
- {VK_BLEND_FACTOR_ZERO, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_DST_COLOR,
- VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR, VK_BLEND_FACTOR_SRC_ALPHA,
- VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, VK_BLEND_FACTOR_DST_ALPHA,
- VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA}};
-
- static constexpr std::array<VkBlendFactor, 8> dst_factors = {
- {VK_BLEND_FACTOR_ZERO, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_SRC_COLOR,
- VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR, VK_BLEND_FACTOR_SRC_ALPHA,
- VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, VK_BLEND_FACTOR_DST_ALPHA,
- VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA}};
-
- vk_state.srcColorBlendFactor = src_factors[state.srcfactor];
- vk_state.srcAlphaBlendFactor = src_factors[state.srcfactoralpha];
- vk_state.dstColorBlendFactor = dst_factors[state.dstfactor];
- vk_state.dstAlphaBlendFactor = dst_factors[state.dstfactoralpha];
- }
-
- if (state.colorupdate)
- {
- vk_state.colorWriteMask =
- VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT;
- }
- else
- {
- vk_state.colorWriteMask = 0;
- }
-
- if (state.alphaupdate)
- vk_state.colorWriteMask |= VK_COLOR_COMPONENT_A_BIT;
-
- return vk_state;
-}
-
-static VkPipelineColorBlendStateCreateInfo
-GetVulkanColorBlendState(const BlendingState& state,
- const VkPipelineColorBlendAttachmentState* attachments,
- uint32_t num_attachments)
-{
- static constexpr std::array<VkLogicOp, 16> vk_logic_ops = {
- {VK_LOGIC_OP_CLEAR, VK_LOGIC_OP_AND, VK_LOGIC_OP_AND_REVERSE, VK_LOGIC_OP_COPY,
- VK_LOGIC_OP_AND_INVERTED, VK_LOGIC_OP_NO_OP, VK_LOGIC_OP_XOR, VK_LOGIC_OP_OR,
- VK_LOGIC_OP_NOR, VK_LOGIC_OP_EQUIVALENT, VK_LOGIC_OP_INVERT, VK_LOGIC_OP_OR_REVERSE,
- VK_LOGIC_OP_COPY_INVERTED, VK_LOGIC_OP_OR_INVERTED, VK_LOGIC_OP_NAND, VK_LOGIC_OP_SET}};
-
- VkBool32 vk_logic_op_enable = static_cast<VkBool32>(state.logicopenable);
- if (vk_logic_op_enable && !g_vulkan_context->SupportsLogicOps())
- {
- // At the time of writing, Adreno and Mali drivers didn't support logic ops.
- // The "emulation" through blending path has been removed, so just disable it completely.
- // These drivers don't support dual-source blend either, so issues are to be expected.
- vk_logic_op_enable = VK_FALSE;
- }
-
- VkLogicOp vk_logic_op = vk_logic_op_enable ? vk_logic_ops[state.logicmode] : VK_LOGIC_OP_CLEAR;
-
- VkPipelineColorBlendStateCreateInfo vk_state = {
- VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, // VkStructureType sType
- nullptr, // const void* pNext
- 0, // VkPipelineColorBlendStateCreateFlags flags
- vk_logic_op_enable, // VkBool32 logicOpEnable
- vk_logic_op, // VkLogicOp logicOp
- num_attachments, // uint32_t attachmentCount
- attachments, // const VkPipelineColorBlendAttachmentState* pAttachments
- {1.0f, 1.0f, 1.0f, 1.0f} // float blendConstants[4]
- };
-
- return vk_state;
-}
-
-VkPipeline ShaderCache::CreatePipeline(const PipelineInfo& info)
-{
- // Declare descriptors for empty vertex buffers/attributes
- static const VkPipelineVertexInputStateCreateInfo empty_vertex_input_state = {
- VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO, // VkStructureType sType
- nullptr, // const void* pNext
- 0, // VkPipelineVertexInputStateCreateFlags flags
- 0, // uint32_t vertexBindingDescriptionCount
- nullptr, // const VkVertexInputBindingDescription* pVertexBindingDescriptions
- 0, // uint32_t vertexAttributeDescriptionCount
- nullptr // const VkVertexInputAttributeDescription* pVertexAttributeDescriptions
- };
-
- // Vertex inputs
- const VkPipelineVertexInputStateCreateInfo& vertex_input_state =
- info.vertex_format ? info.vertex_format->GetVertexInputStateInfo() : empty_vertex_input_state;
-
- // Input assembly
- static constexpr std::array<VkPrimitiveTopology, 4> vk_primitive_topologies = {
- {VK_PRIMITIVE_TOPOLOGY_POINT_LIST, VK_PRIMITIVE_TOPOLOGY_LINE_LIST,
- VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP}};
- VkPipelineInputAssemblyStateCreateInfo input_assembly_state = {
- VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO, nullptr, 0,
- vk_primitive_topologies[static_cast<u32>(info.rasterization_state.primitive.Value())],
- VK_FALSE};
-
- // See Vulkan spec, section 19:
- // If topology is VK_PRIMITIVE_TOPOLOGY_POINT_LIST, VK_PRIMITIVE_TOPOLOGY_LINE_LIST,
- // VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY,
- // VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY or VK_PRIMITIVE_TOPOLOGY_PATCH_LIST,
- // primitiveRestartEnable must be VK_FALSE
- if (g_ActiveConfig.backend_info.bSupportsPrimitiveRestart &&
- IsStripPrimitiveTopology(input_assembly_state.topology))
- {
- input_assembly_state.primitiveRestartEnable = VK_TRUE;
- }
-
- // Shaders to stages
- VkPipelineShaderStageCreateInfo shader_stages[3];
- uint32_t num_shader_stages = 0;
- if (info.vs != VK_NULL_HANDLE)
- {
- shader_stages[num_shader_stages++] = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
- nullptr,
- 0,
- VK_SHADER_STAGE_VERTEX_BIT,
- info.vs,
- "main"};
- }
- if (info.gs != VK_NULL_HANDLE)
- {
- shader_stages[num_shader_stages++] = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
- nullptr,
- 0,
- VK_SHADER_STAGE_GEOMETRY_BIT,
- info.gs,
- "main"};
- }
- if (info.ps != VK_NULL_HANDLE)
- {
- shader_stages[num_shader_stages++] = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
- nullptr,
- 0,
- VK_SHADER_STAGE_FRAGMENT_BIT,
- info.ps,
- "main"};
- }
-
- // Fill in Vulkan descriptor structs from our state structures.
- VkPipelineRasterizationStateCreateInfo rasterization_state =
- GetVulkanRasterizationState(info.rasterization_state);
- VkPipelineMultisampleStateCreateInfo multisample_state =
- GetVulkanMultisampleState(info.multisampling_state);
- VkPipelineDepthStencilStateCreateInfo depth_stencil_state =
- GetVulkanDepthStencilState(info.depth_state);
- VkPipelineColorBlendAttachmentState blend_attachment_state =
- GetVulkanAttachmentBlendState(info.blend_state);
- VkPipelineColorBlendStateCreateInfo blend_state =
- GetVulkanColorBlendState(info.blend_state, &blend_attachment_state, 1);
-
- // This viewport isn't used, but needs to be specified anyway.
- static const VkViewport viewport = {0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f};
- static const VkRect2D scissor = {{0, 0}, {1, 1}};
- static const VkPipelineViewportStateCreateInfo viewport_state = {
- VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO,
- nullptr,
- 0, // VkPipelineViewportStateCreateFlags flags;
- 1, // uint32_t viewportCount
- &viewport, // const VkViewport* pViewports
- 1, // uint32_t scissorCount
- &scissor // const VkRect2D* pScissors
- };
-
- // Set viewport and scissor dynamic state so we can change it elsewhere.
- static const VkDynamicState dynamic_states[] = {VK_DYNAMIC_STATE_VIEWPORT,
- VK_DYNAMIC_STATE_SCISSOR};
- static const VkPipelineDynamicStateCreateInfo dynamic_state = {
- VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO, nullptr,
- 0, // VkPipelineDynamicStateCreateFlags flags
- static_cast<u32>(ArraySize(dynamic_states)), // uint32_t dynamicStateCount
- dynamic_states // const VkDynamicState* pDynamicStates
- };
-
- // Combine to full pipeline info structure.
- VkGraphicsPipelineCreateInfo pipeline_info = {
- VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO,
- nullptr, // VkStructureType sType
- 0, // VkPipelineCreateFlags flags
- num_shader_stages, // uint32_t stageCount
- shader_stages, // const VkPipelineShaderStageCreateInfo* pStages
- &vertex_input_state, // const VkPipelineVertexInputStateCreateInfo* pVertexInputState
- &input_assembly_state, // const VkPipelineInputAssemblyStateCreateInfo* pInputAssemblyState
- nullptr, // const VkPipelineTessellationStateCreateInfo* pTessellationState
- &viewport_state, // const VkPipelineViewportStateCreateInfo* pViewportState
- &rasterization_state, // const VkPipelineRasterizationStateCreateInfo* pRasterizationState
- &multisample_state, // const VkPipelineMultisampleStateCreateInfo* pMultisampleState
- &depth_stencil_state, // const VkPipelineDepthStencilStateCreateInfo* pDepthStencilState
- &blend_state, // const VkPipelineColorBlendStateCreateInfo* pColorBlendState
- &dynamic_state, // const VkPipelineDynamicStateCreateInfo* pDynamicState
- info.pipeline_layout, // VkPipelineLayout layout
- info.render_pass, // VkRenderPass renderPass
- 0, // uint32_t subpass
- VK_NULL_HANDLE, // VkPipeline basePipelineHandle
- -1 // int32_t basePipelineIndex
- };
-
- VkPipeline pipeline;
- VkResult res = vkCreateGraphicsPipelines(g_vulkan_context->GetDevice(), m_pipeline_cache, 1,
- &pipeline_info, nullptr, &pipeline);
- if (res != VK_SUCCESS)
- {
- LOG_VULKAN_ERROR(res, "vkCreateGraphicsPipelines failed: ");
- return VK_NULL_HANDLE;
- }
-
- return pipeline;
-}
-
-VkPipeline ShaderCache::GetPipeline(const PipelineInfo& info)
-{
- auto iter = m_pipeline_objects.find(info);
- if (iter != m_pipeline_objects.end())
- return iter->second;
-
- VkPipeline pipeline = CreatePipeline(info);
- m_pipeline_objects.emplace(info, pipeline);
- return pipeline;
-}
-
-VkPipeline ShaderCache::CreateComputePipeline(const ComputePipelineInfo& info)
-{
- VkComputePipelineCreateInfo pipeline_info = {VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO,
- nullptr,
- 0,
- {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
- nullptr, 0, VK_SHADER_STAGE_COMPUTE_BIT, info.cs,
- "main", nullptr},
- info.pipeline_layout,
- VK_NULL_HANDLE,
- -1};
-
- VkPipeline pipeline;
- VkResult res = vkCreateComputePipelines(g_vulkan_context->GetDevice(), VK_NULL_HANDLE, 1,
- &pipeline_info, nullptr, &pipeline);
- if (res != VK_SUCCESS)
- {
- LOG_VULKAN_ERROR(res, "vkCreateComputePipelines failed: ");
- return VK_NULL_HANDLE;
- }
-
- return pipeline;
-}
-
-VkPipeline ShaderCache::GetComputePipeline(const ComputePipelineInfo& info)
-{
- auto iter = m_compute_pipeline_objects.find(info);
- if (iter != m_compute_pipeline_objects.end())
- return iter->second;
-
- VkPipeline pipeline = CreateComputePipeline(info);
- m_compute_pipeline_objects.emplace(info, pipeline);
- return pipeline;
-}
-
-void ShaderCache::ClearPipelineCache()
-{
- for (const auto& it : m_pipeline_objects)
- {
- if (it.second != VK_NULL_HANDLE)
- vkDestroyPipeline(g_vulkan_context->GetDevice(), it.second, nullptr);
- }
- m_pipeline_objects.clear();
-
- for (const auto& it : m_compute_pipeline_objects)
- {
- if (it.second != VK_NULL_HANDLE)
- vkDestroyPipeline(g_vulkan_context->GetDevice(), it.second, nullptr);
- }
- m_compute_pipeline_objects.clear();
-}
-
-class PipelineCacheReadCallback : public LinearDiskCacheReader<u32, u8>
-{
-public:
- PipelineCacheReadCallback(std::vector<u8>* data) : m_data(data) {}
- void Read(const u32& key, const u8* value, u32 value_size) override
- {
- m_data->resize(value_size);
- if (value_size > 0)
- memcpy(m_data->data(), value, value_size);
- }
-
-private:
- std::vector<u8>* m_data;
-};
-
-class PipelineCacheReadIgnoreCallback : public LinearDiskCacheReader<u32, u8>
-{
-public:
- void Read(const u32& key, const u8* value, u32 value_size) override {}
-};
-
-bool ShaderCache::CreatePipelineCache()
-{
- // Vulkan pipeline caches can be shared between games for shader compile time reduction.
- // This assumes that drivers don't create all pipelines in the cache on load time, only
- // when a lookup occurs that matches a pipeline (or pipeline data) in the cache.
- m_pipeline_cache_filename = GetDiskShaderCacheFileName(APIType::Vulkan, "Pipeline", false, true);
-
- VkPipelineCacheCreateInfo info = {
- VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, // VkStructureType sType
- nullptr, // const void* pNext
- 0, // VkPipelineCacheCreateFlags flags
- 0, // size_t initialDataSize
- nullptr // const void* pInitialData
- };
-
- VkResult res =
- vkCreatePipelineCache(g_vulkan_context->GetDevice(), &info, nullptr, &m_pipeline_cache);
- if (res == VK_SUCCESS)
- return true;
-
- LOG_VULKAN_ERROR(res, "vkCreatePipelineCache failed: ");
- return false;
-}
-
-bool ShaderCache::LoadPipelineCache()
-{
- // We have to keep the pipeline cache file name around since when we save it
- // we delete the old one, by which time the game's unique ID is already cleared.
- m_pipeline_cache_filename = GetDiskShaderCacheFileName(APIType::Vulkan, "Pipeline", false, true);
-
- std::vector<u8> disk_data;
- LinearDiskCache<u32, u8> disk_cache;
- PipelineCacheReadCallback read_callback(&disk_data);
- if (disk_cache.OpenAndRead(m_pipeline_cache_filename, read_callback) != 1)
- disk_data.clear();
-
- if (!disk_data.empty() && !ValidatePipelineCache(disk_data.data(), disk_data.size()))
- {
- // Don't use this data. In fact, we should delete it to prevent it from being used next time.
- File::Delete(m_pipeline_cache_filename);
- return CreatePipelineCache();
- }
-
- VkPipelineCacheCreateInfo info = {
- VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, // VkStructureType sType
- nullptr, // const void* pNext
- 0, // VkPipelineCacheCreateFlags flags
- disk_data.size(), // size_t initialDataSize
- disk_data.data() // const void* pInitialData
- };
-
- VkResult res =
- vkCreatePipelineCache(g_vulkan_context->GetDevice(), &info, nullptr, &m_pipeline_cache);
- if (res == VK_SUCCESS)
- return true;
-
- // Failed to create pipeline cache, try with it empty.
- LOG_VULKAN_ERROR(res, "vkCreatePipelineCache failed, trying empty cache: ");
- return CreatePipelineCache();
-}
-
-// Based on Vulkan 1.0 specification,
-// Table 9.1. Layout for pipeline cache header version VK_PIPELINE_CACHE_HEADER_VERSION_ONE
-// NOTE: This data is assumed to be in little-endian format.
-#pragma pack(push, 4)
-struct VK_PIPELINE_CACHE_HEADER
-{
- u32 header_length;
- u32 header_version;
- u32 vendor_id;
- u32 device_id;
- u8 uuid[VK_UUID_SIZE];
-};
-#pragma pack(pop)
-static_assert(std::is_trivially_copyable<VK_PIPELINE_CACHE_HEADER>::value,
- "VK_PIPELINE_CACHE_HEADER must be trivially copyable");
-
-bool ShaderCache::ValidatePipelineCache(const u8* data, size_t data_length)
-{
- if (data_length < sizeof(VK_PIPELINE_CACHE_HEADER))
- {
- ERROR_LOG(VIDEO, "Pipeline cache failed validation: Invalid header");
- return false;
- }
-
- VK_PIPELINE_CACHE_HEADER header;
- std::memcpy(&header, data, sizeof(header));
- if (header.header_length < sizeof(VK_PIPELINE_CACHE_HEADER))
- {
- ERROR_LOG(VIDEO, "Pipeline cache failed validation: Invalid header length");
- return false;
- }
-
- if (header.header_version != VK_PIPELINE_CACHE_HEADER_VERSION_ONE)
- {
- ERROR_LOG(VIDEO, "Pipeline cache failed validation: Invalid header version");
- return false;
- }
-
- if (header.vendor_id != g_vulkan_context->GetDeviceProperties().vendorID)
- {
- ERROR_LOG(VIDEO,
- "Pipeline cache failed validation: Incorrect vendor ID (file: 0x%X, device: 0x%X)",
- header.vendor_id, g_vulkan_context->GetDeviceProperties().vendorID);
- return false;
- }
-
- if (header.device_id != g_vulkan_context->GetDeviceProperties().deviceID)
- {
- ERROR_LOG(VIDEO,
- "Pipeline cache failed validation: Incorrect device ID (file: 0x%X, device: 0x%X)",
- header.device_id, g_vulkan_context->GetDeviceProperties().deviceID);
- return false;
- }
-
- if (std::memcmp(header.uuid, g_vulkan_context->GetDeviceProperties().pipelineCacheUUID,
- VK_UUID_SIZE) != 0)
- {
- ERROR_LOG(VIDEO, "Pipeline cache failed validation: Incorrect UUID");
- return false;
- }
-
- return true;
-}
-
-void ShaderCache::DestroyPipelineCache()
-{
- ClearPipelineCache();
- vkDestroyPipelineCache(g_vulkan_context->GetDevice(), m_pipeline_cache, nullptr);
- m_pipeline_cache = VK_NULL_HANDLE;
-}
-
-void ShaderCache::SavePipelineCache()
-{
- size_t data_size;
- VkResult res =
- vkGetPipelineCacheData(g_vulkan_context->GetDevice(), m_pipeline_cache, &data_size, nullptr);
- if (res != VK_SUCCESS)
- {
- LOG_VULKAN_ERROR(res, "vkGetPipelineCacheData failed: ");
- return;
- }
-
- std::vector<u8> data(data_size);
- res = vkGetPipelineCacheData(g_vulkan_context->GetDevice(), m_pipeline_cache, &data_size,
- data.data());
- if (res != VK_SUCCESS)
- {
- LOG_VULKAN_ERROR(res, "vkGetPipelineCacheData failed: ");
- return;
- }
-
- // Delete the old cache and re-create.
- File::Delete(m_pipeline_cache_filename);
-
- // We write a single key of 1, with the entire pipeline cache data.
- // Not ideal, but our disk cache class does not support just writing a single blob
- // of data without specifying a key.
- LinearDiskCache<u32, u8> disk_cache;
- PipelineCacheReadIgnoreCallback callback;
- disk_cache.OpenAndRead(m_pipeline_cache_filename, callback);
- disk_cache.Append(1, data.data(), static_cast<u32>(data.size()));
- disk_cache.Close();
-}
-
-void ShaderCache::RecompileSharedShaders()
-{
- DestroySharedShaders();
- if (!CompileSharedShaders())
- PanicAlert("Failed to recompile shared shaders.");
-}
-
-void ShaderCache::ReloadPipelineCache()
-{
- SavePipelineCache();
- DestroyPipelineCache();
-
- if (g_ActiveConfig.bShaderCache)
- LoadPipelineCache();
- else
- CreatePipelineCache();
-}
-
-std::string ShaderCache::GetUtilityShaderHeader() const
-{
- std::stringstream ss;
- if (g_ActiveConfig.iMultisamples > 1)
- {
- ss << "#define MSAA_ENABLED 1" << std::endl;
- ss << "#define MSAA_SAMPLES " << g_ActiveConfig.iMultisamples << std::endl;
- if (g_ActiveConfig.bSSAA)
- ss << "#define SSAA_ENABLED 1" << std::endl;
- }
-
- u32 efb_layers = (g_ActiveConfig.stereo_mode != StereoMode::Off) ? 2 : 1;
- ss << "#define EFB_LAYERS " << efb_layers << std::endl;
-
- return ss.str();
-}
-
-std::size_t PipelineInfoHash::operator()(const PipelineInfo& key) const
-{
- return static_cast<std::size_t>(XXH64(&key, sizeof(key), 0));
-}
-
-bool operator==(const PipelineInfo& lhs, const PipelineInfo& rhs)
-{
- return std::memcmp(&lhs, &rhs, sizeof(lhs)) == 0;
-}
-
-bool operator!=(const PipelineInfo& lhs, const PipelineInfo& rhs)
-{
- return !operator==(lhs, rhs);
-}
-
-bool operator<(const PipelineInfo& lhs, const PipelineInfo& rhs)
-{
- return std::memcmp(&lhs, &rhs, sizeof(lhs)) < 0;
-}
-
-bool operator>(const PipelineInfo& lhs, const PipelineInfo& rhs)
-{
- return std::memcmp(&lhs, &rhs, sizeof(lhs)) > 0;
-}
-
-std::size_t ComputePipelineInfoHash::operator()(const ComputePipelineInfo& key) const
-{
- return static_cast<std::size_t>(XXH64(&key, sizeof(key), 0));
-}
-
-bool operator==(const ComputePipelineInfo& lhs, const ComputePipelineInfo& rhs)
-{
- return std::memcmp(&lhs, &rhs, sizeof(lhs)) == 0;
-}
-
-bool operator!=(const ComputePipelineInfo& lhs, const ComputePipelineInfo& rhs)
-{
- return !operator==(lhs, rhs);
-}
-
-bool operator<(const ComputePipelineInfo& lhs, const ComputePipelineInfo& rhs)
-{
- return std::memcmp(&lhs, &rhs, sizeof(lhs)) < 0;
-}
-
-bool operator>(const ComputePipelineInfo& lhs, const ComputePipelineInfo& rhs)
-{
- return std::memcmp(&lhs, &rhs, sizeof(lhs)) > 0;
-}
-
-bool ShaderCache::CompileSharedShaders()
-{
- static const char PASSTHROUGH_VERTEX_SHADER_SOURCE[] = R"(
- layout(location = 0) in vec4 ipos;
- layout(location = 5) in vec4 icol0;
- layout(location = 8) in vec3 itex0;
-
- layout(location = 0) out vec3 uv0;
- layout(location = 1) out vec4 col0;
-
- void main()
- {
- gl_Position = ipos;
- uv0 = itex0;
- col0 = icol0;
- }
- )";
-
- static const char PASSTHROUGH_GEOMETRY_SHADER_SOURCE[] = R"(
- layout(triangles) in;
- layout(triangle_strip, max_vertices = EFB_LAYERS * 3) out;
-
- layout(location = 0) in vec3 in_uv0[];
- layout(location = 1) in vec4 in_col0[];
-
- layout(location = 0) out vec3 out_uv0;
- layout(location = 1) out vec4 out_col0;
-
- void main()
- {
- for (int j = 0; j < EFB_LAYERS; j++)
- {
- for (int i = 0; i < 3; i++)
- {
- gl_Layer = j;
- gl_Position = gl_in[i].gl_Position;
- out_uv0 = vec3(in_uv0[i].xy, float(j));
- out_col0 = in_col0[i];
- EmitVertex();
- }
- EndPrimitive();
- }
- }
- )";
-
- static const char SCREEN_QUAD_VERTEX_SHADER_SOURCE[] = R"(
- layout(location = 0) out vec3 uv0;
-
- void main()
- {
- /*
- * id &1 &2 clamp(*2-1)
- * 0 0,0 0,0 -1,-1 TL
- * 1 1,0 1,0 1,-1 TR
- * 2 0,2 0,1 -1,1 BL
- * 3 1,2 1,1 1,1 BR
- */
- vec2 rawpos = vec2(float(gl_VertexID & 1), clamp(float(gl_VertexID & 2), 0.0f, 1.0f));
- gl_Position = vec4(rawpos * 2.0f - 1.0f, 0.0f, 1.0f);
- uv0 = vec3(rawpos, 0.0f);
- }
- )";
-
- static const char SCREEN_QUAD_GEOMETRY_SHADER_SOURCE[] = R"(
- layout(triangles) in;
- layout(triangle_strip, max_vertices = EFB_LAYERS * 3) out;
-
- layout(location = 0) in vec3 in_uv0[];
-
- layout(location = 0) out vec3 out_uv0;
-
- void main()
- {
- for (int j = 0; j < EFB_LAYERS; j++)
- {
- for (int i = 0; i < 3; i++)
- {
- gl_Layer = j;
- gl_Position = gl_in[i].gl_Position;
- out_uv0 = vec3(in_uv0[i].xy, float(j));
- EmitVertex();
- }
- EndPrimitive();
- }
- }
- )";
-
- static const char CLEAR_FRAGMENT_SHADER_SOURCE[] = R"(
- layout(location = 0) in float3 uv0;
- layout(location = 1) in float4 col0;
- layout(location = 0) out float4 ocol0;
-
- void main()
- {
- ocol0 = col0;
- }
-
- )";
-
- const std::string header = GetUtilityShaderHeader();
-
- m_screen_quad_vertex_shader =
- Util::CompileAndCreateVertexShader(header + SCREEN_QUAD_VERTEX_SHADER_SOURCE);
- m_passthrough_vertex_shader =
- Util::CompileAndCreateVertexShader(header + PASSTHROUGH_VERTEX_SHADER_SOURCE);
- if (m_screen_quad_vertex_shader == VK_NULL_HANDLE ||
- m_passthrough_vertex_shader == VK_NULL_HANDLE)
- {
- return false;
- }
-
- if (g_ActiveConfig.stereo_mode != StereoMode::Off && g_vulkan_context->SupportsGeometryShaders())
- {
- m_screen_quad_geometry_shader =
- Util::CompileAndCreateGeometryShader(header + SCREEN_QUAD_GEOMETRY_SHADER_SOURCE);
- m_passthrough_geometry_shader =
- Util::CompileAndCreateGeometryShader(header + PASSTHROUGH_GEOMETRY_SHADER_SOURCE);
- if (m_screen_quad_geometry_shader == VK_NULL_HANDLE ||
- m_passthrough_geometry_shader == VK_NULL_HANDLE)
- {
- return false;
- }
- }
-
- m_clear_fragment_shader =
- Util::CompileAndCreateFragmentShader(header + CLEAR_FRAGMENT_SHADER_SOURCE);
- if (m_clear_fragment_shader == VK_NULL_HANDLE)
- return false;
-
- return true;
-}
-
-void ShaderCache::DestroySharedShaders()
-{
- auto DestroyShader = [this](VkShaderModule& shader) {
- if (shader != VK_NULL_HANDLE)
- {
- vkDestroyShaderModule(g_vulkan_context->GetDevice(), shader, nullptr);
- shader = VK_NULL_HANDLE;
- }
- };
-
- DestroyShader(m_screen_quad_vertex_shader);
- DestroyShader(m_passthrough_vertex_shader);
- DestroyShader(m_screen_quad_geometry_shader);
- DestroyShader(m_passthrough_geometry_shader);
- DestroyShader(m_clear_fragment_shader);
-}
-} // namespace Vulkan
diff --git a/Source/Core/VideoBackends/Vulkan/ShaderCache.h b/Source/Core/VideoBackends/Vulkan/ShaderCache.h
deleted file mode 100644
index 51060358e2..0000000000
--- a/Source/Core/VideoBackends/Vulkan/ShaderCache.h
+++ /dev/null
@@ -1,145 +0,0 @@
-// Copyright 2016 Dolphin Emulator Project
-// Licensed under GPLv2+
-// Refer to the license.txt file included.
-
-#pragma once
-
-#include <array>
-#include <cstddef>
-#include <map>
-#include <memory>
-#include <string>
-#include <unordered_map>
-#include <utility>
-
-#include "Common/CommonTypes.h"
-#include "Common/LinearDiskCache.h"
-
-#include "VideoBackends/Vulkan/Constants.h"
-#include "VideoBackends/Vulkan/ObjectCache.h"
-#include "VideoBackends/Vulkan/ShaderCompiler.h"
-
-#include "VideoCommon/RenderState.h"
-
-namespace Vulkan
-{
-class CommandBufferManager;
-class VertexFormat;
-class StreamBuffer;
-
-struct PipelineInfo
-{
- // These are packed in descending order of size, to avoid any padding so that the structure
- // can be copied/compared as a single block of memory. 64-bit pointer size is assumed.
- const VertexFormat* vertex_format;
- VkPipelineLayout pipeline_layout;
- VkShaderModule vs;
- VkShaderModule gs;
- VkShaderModule ps;
- VkRenderPass render_pass;
- BlendingState blend_state;
- RasterizationState rasterization_state;
- DepthState depth_state;
- MultisamplingState multisampling_state;
-};
-
-struct PipelineInfoHash
-{
- std::size_t operator()(const PipelineInfo& key) const;
-};
-
-bool operator==(const PipelineInfo& lhs, const PipelineInfo& rhs);
-bool operator!=(const PipelineInfo& lhs, const PipelineInfo& rhs);
-bool operator<(const PipelineInfo& lhs, const PipelineInfo& rhs);
-bool operator>(const PipelineInfo& lhs, const PipelineInfo& rhs);
-
-struct ComputePipelineInfo
-{
- VkPipelineLayout pipeline_layout;
- VkShaderModule cs;
-};
-
-struct ComputePipelineInfoHash
-{
- std::size_t operator()(const ComputePipelineInfo& key) const;
-};
-
-bool operator==(const ComputePipelineInfo& lhs, const ComputePipelineInfo& rhs);
-bool operator!=(const ComputePipelineInfo& lhs, const ComputePipelineInfo& rhs);
-bool operator<(const ComputePipelineInfo& lhs, const ComputePipelineInfo& rhs);
-bool operator>(const ComputePipelineInfo& lhs, const ComputePipelineInfo& rhs);
-
-class ShaderCache
-{
-public:
- ShaderCache();
- ~ShaderCache();
-
- // Get utility shader header based on current config.
- std::string GetUtilityShaderHeader() const;
-
- // Perform at startup, create descriptor layouts, compiles all static shaders.
- bool Initialize();
- void Shutdown();
-
- // Creates a pipeline for the specified description. The resulting pipeline, if successful
- // is not stored anywhere, this is left up to the caller.
- VkPipeline CreatePipeline(const PipelineInfo& info);
-
- // Find a pipeline by the specified description, if not found, attempts to create it.
- VkPipeline GetPipeline(const PipelineInfo& info);
-
- // Creates a compute pipeline, and does not track the handle.
- VkPipeline CreateComputePipeline(const ComputePipelineInfo& info);
-
- // Find a pipeline by the specified description, if not found, attempts to create it
- VkPipeline GetComputePipeline(const ComputePipelineInfo& info);
-
- // Clears our pipeline cache of all objects. This is necessary when recompiling shaders,
- // as drivers are free to return the same pointer again, which means that we may end up using
- // and old pipeline object if they are not cleared first. Some stutter may be experienced
- // while our cache is rebuilt on use, but the pipeline cache object should mitigate this.
- // NOTE: Ensure that none of these objects are in use before calling.
- void ClearPipelineCache();
-
- // Saves the pipeline cache to disk. Call when shutting down.
- void SavePipelineCache();
-
- // Recompile shared shaders, call when stereo mode changes.
- void RecompileSharedShaders();
-
- // Reload pipeline cache. This will destroy all pipelines.
- void ReloadPipelineCache();
-
- // Shared shader accessors
- VkShaderModule GetScreenQuadVertexShader() const { return m_screen_quad_vertex_shader; }
- VkShaderModule GetPassthroughVertexShader() const { return m_passthrough_vertex_shader; }
- VkShaderModule GetScreenQuadGeometryShader() const { return m_screen_quad_geometry_shader; }
- VkShaderModule GetPassthroughGeometryShader() const { return m_passthrough_geometry_shader; }
- VkShaderModule GetClearFragmentShader() const { return m_clear_fragment_shader; }
-
-private:
- bool CreatePipelineCache();
- bool LoadPipelineCache();
- bool ValidatePipelineCache(const u8* data, size_t data_length);
- void DestroyPipelineCache();
- bool CompileSharedShaders();
- void DestroySharedShaders();
-
- std::unordered_map<PipelineInfo, VkPipeline, PipelineInfoHash> m_pipeline_objects;
- std::unordered_map<ComputePipelineInfo, VkPipeline, ComputePipelineInfoHash>
- m_compute_pipeline_objects;
- VkPipelineCache m_pipeline_cache = VK_NULL_HANDLE;
- std::string m_pipeline_cache_filename;
-
- // Utility/shared shaders
- VkShaderModule m_screen_quad_vertex_shader = VK_NULL_HANDLE;
- VkShaderModule m_passthrough_vertex_shader = VK_NULL_HANDLE;
- VkShaderModule m_screen_quad_geometry_shader = VK_NULL_HANDLE;
- VkShaderModule m_passthrough_geometry_shader = VK_NULL_HANDLE;
- VkShaderModule m_clear_fragment_shader = VK_NULL_HANDLE;
-};
-
-extern std::unique_ptr<ShaderCache> g_shader_cache;
-
-} // namespace Vulkan
diff --git a/Source/Core/VideoBackends/Vulkan/ShaderCompiler.cpp b/Source/Core/VideoBackends/Vulkan/ShaderCompiler.cpp
index d430c8bab9..abe6df2653 100644
--- a/Source/Core/VideoBackends/Vulkan/ShaderCompiler.cpp
+++ b/Source/Core/VideoBackends/Vulkan/ShaderCompiler.cpp
@@ -53,12 +53,13 @@ static const char SHADER_HEADER[] = R"(
#define FRAGMENT_OUTPUT_LOCATION_INDEXED(x, y) layout(location = x, index = y)
#define UBO_BINDING(packing, x) layout(packing, set = 0, binding = (x - 1))
#define SAMPLER_BINDING(x) layout(set = 1, binding = x)
+ #define TEXEL_BUFFER_BINDING(x) layout(set = 1, binding = (x + 8))
#define SSBO_BINDING(x) layout(set = 2, binding = x)
- #define TEXEL_BUFFER_BINDING(x) layout(set = 2, binding = x)
#define VARYING_LOCATION(x) layout(location = x)
#define FORCE_EARLY_Z layout(early_fragment_tests) in
// hlsl to glsl function translation
+ #define API_VULKAN 1
#define float2 vec2
#define float3 vec3
#define float4 vec4
@@ -79,12 +80,13 @@ static const char COMPUTE_SHADER_HEADER[] = R"(
// Target GLSL 4.5.
#version 450 core
// All resources are packed into one descriptor set for compute.
- #define UBO_BINDING(packing, x) layout(packing, set = 0, binding = (0 + x))
+ #define UBO_BINDING(packing, x) layout(packing, set = 0, binding = (x - 1))
#define SAMPLER_BINDING(x) layout(set = 0, binding = (1 + x))
- #define TEXEL_BUFFER_BINDING(x) layout(set = 0, binding = (5 + x))
- #define IMAGE_BINDING(format, x) layout(format, set = 0, binding = (7 + x))
+ #define TEXEL_BUFFER_BINDING(x) layout(set = 0, binding = (3 + x))
+ #define IMAGE_BINDING(format, x) layout(format, set = 0, binding = (5 + x))
// hlsl to glsl function translation
+ #define API_VULKAN 1
#define float2 vec2
#define float3 vec3
#define float4 vec4
diff --git a/Source/Core/VideoBackends/Vulkan/StagingBuffer.cpp b/Source/Core/VideoBackends/Vulkan/StagingBuffer.cpp
index 7a2c238489..50d7c2f16a 100644
--- a/Source/Core/VideoBackends/Vulkan/StagingBuffer.cpp
+++ b/Source/Core/VideoBackends/Vulkan/StagingBuffer.cpp
@@ -9,7 +9,6 @@
#include "VideoBackends/Vulkan/CommandBufferManager.h"
#include "VideoBackends/Vulkan/StagingBuffer.h"
-#include "VideoBackends/Vulkan/Util.h"
#include "VideoBackends/Vulkan/VulkanContext.h"
namespace Vulkan
@@ -30,6 +29,28 @@ StagingBuffer::~StagingBuffer()
g_command_buffer_mgr->DeferBufferDestruction(m_buffer);
}
+void StagingBuffer::BufferMemoryBarrier(VkCommandBuffer command_buffer, VkBuffer buffer,
+ VkAccessFlags src_access_mask,
+ VkAccessFlags dst_access_mask, VkDeviceSize offset,
+ VkDeviceSize size, VkPipelineStageFlags src_stage_mask,
+ VkPipelineStageFlags dst_stage_mask)
+{
+ VkBufferMemoryBarrier buffer_info = {
+ VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, // VkStructureType sType
+ nullptr, // const void* pNext
+ src_access_mask, // VkAccessFlags srcAccessMask
+ dst_access_mask, // VkAccessFlags dstAccessMask
+ VK_QUEUE_FAMILY_IGNORED, // uint32_t srcQueueFamilyIndex
+ VK_QUEUE_FAMILY_IGNORED, // uint32_t dstQueueFamilyIndex
+ buffer, // VkBuffer buffer
+ offset, // VkDeviceSize offset
+ size // VkDeviceSize size
+ };
+
+ vkCmdPipelineBarrier(command_buffer, src_stage_mask, dst_stage_mask, 0, 0, nullptr, 1,
+ &buffer_info, 0, nullptr);
+}
+
bool StagingBuffer::Map(VkDeviceSize offset, VkDeviceSize size)
{
m_map_offset = offset;
@@ -84,8 +105,8 @@ void StagingBuffer::InvalidateGPUCache(VkCommandBuffer command_buffer,
return;
ASSERT((offset + size) <= m_size || (offset < m_size && size == VK_WHOLE_SIZE));
- Util::BufferMemoryBarrier(command_buffer, m_buffer, VK_ACCESS_HOST_WRITE_BIT, dest_access_flags,
- offset, size, VK_PIPELINE_STAGE_HOST_BIT, dest_pipeline_stage);
+ BufferMemoryBarrier(command_buffer, m_buffer, VK_ACCESS_HOST_WRITE_BIT, dest_access_flags, offset,
+ size, VK_PIPELINE_STAGE_HOST_BIT, dest_pipeline_stage);
}
void StagingBuffer::PrepareForGPUWrite(VkCommandBuffer command_buffer,
@@ -97,8 +118,8 @@ void StagingBuffer::PrepareForGPUWrite(VkCommandBuffer command_buffer,
return;
ASSERT((offset + size) <= m_size || (offset < m_size && size == VK_WHOLE_SIZE));
- Util::BufferMemoryBarrier(command_buffer, m_buffer, 0, dst_access_flags, offset, size,
- VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, dst_pipeline_stage);
+ BufferMemoryBarrier(command_buffer, m_buffer, 0, dst_access_flags, offset, size,
+ VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, dst_pipeline_stage);
}
void StagingBuffer::FlushGPUCache(VkCommandBuffer command_buffer, VkAccessFlagBits src_access_flags,
@@ -109,8 +130,8 @@ void StagingBuffer::FlushGPUCache(VkCommandBuffer command_buffer, VkAccessFlagBi
return;
ASSERT((offset + size) <= m_size || (offset < m_size && size == VK_WHOLE_SIZE));
- Util::BufferMemoryBarrier(command_buffer, m_buffer, src_access_flags, VK_ACCESS_HOST_READ_BIT,
- offset, size, src_pipeline_stage, VK_PIPELINE_STAGE_HOST_BIT);
+ BufferMemoryBarrier(command_buffer, m_buffer, src_access_flags, VK_ACCESS_HOST_READ_BIT, offset,
+ size, src_pipeline_stage, VK_PIPELINE_STAGE_HOST_BIT);
}
void StagingBuffer::InvalidateCPUCache(VkDeviceSize offset, VkDeviceSize size)
diff --git a/Source/Core/VideoBackends/Vulkan/StagingBuffer.h b/Source/Core/VideoBackends/Vulkan/StagingBuffer.h
index 2ecb21cb22..bf2f9fb2e5 100644
--- a/Source/Core/VideoBackends/Vulkan/StagingBuffer.h
+++ b/Source/Core/VideoBackends/Vulkan/StagingBuffer.h
@@ -63,6 +63,13 @@ public:
static bool AllocateBuffer(STAGING_BUFFER_TYPE type, VkDeviceSize size, VkBufferUsageFlags usage,
VkBuffer* out_buffer, VkDeviceMemory* out_memory, bool* out_coherent);
+ // Wrapper for creating an barrier on a buffer
+ static void BufferMemoryBarrier(VkCommandBuffer command_buffer, VkBuffer buffer,
+ VkAccessFlags src_access_mask, VkAccessFlags dst_access_mask,
+ VkDeviceSize offset, VkDeviceSize size,
+ VkPipelineStageFlags src_stage_mask,
+ VkPipelineStageFlags dst_stage_mask);
+
protected:
STAGING_BUFFER_TYPE m_type;
VkBuffer m_buffer;
@@ -74,4 +81,4 @@ protected:
VkDeviceSize m_map_offset = 0;
VkDeviceSize m_map_size = 0;
};
-}
+} // namespace Vulkan
diff --git a/Source/Core/VideoBackends/Vulkan/StateTracker.cpp b/Source/Core/VideoBackends/Vulkan/StateTracker.cpp
index 089b385ffe..6bb1b8981d 100644
--- a/Source/Core/VideoBackends/Vulkan/StateTracker.cpp
+++ b/Source/Core/VideoBackends/Vulkan/StateTracker.cpp
@@ -4,32 +4,25 @@
#include "VideoBackends/Vulkan/StateTracker.h"
-#include <cstring>
-
-#include "Common/Align.h"
#include "Common/Assert.h"
#include "VideoBackends/Vulkan/CommandBufferManager.h"
-#include "VideoBackends/Vulkan/Constants.h"
#include "VideoBackends/Vulkan/ObjectCache.h"
-#include "VideoBackends/Vulkan/ShaderCache.h"
-#include "VideoBackends/Vulkan/StreamBuffer.h"
-#include "VideoBackends/Vulkan/Util.h"
+#include "VideoBackends/Vulkan/Renderer.h"
#include "VideoBackends/Vulkan/VKPipeline.h"
+#include "VideoBackends/Vulkan/VKShader.h"
+#include "VideoBackends/Vulkan/VKTexture.h"
#include "VideoBackends/Vulkan/VertexFormat.h"
#include "VideoBackends/Vulkan/VulkanContext.h"
-#include "VideoCommon/GeometryShaderManager.h"
-#include "VideoCommon/PixelShaderManager.h"
-#include "VideoCommon/Statistics.h"
-#include "VideoCommon/VertexLoaderManager.h"
-#include "VideoCommon/VertexShaderManager.h"
-#include "VideoCommon/VideoConfig.h"
-
namespace Vulkan
{
static std::unique_ptr<StateTracker> s_state_tracker;
+StateTracker::StateTracker() = default;
+
+StateTracker::~StateTracker() = default;
+
StateTracker* StateTracker::GetInstance()
{
return s_state_tracker.get();
@@ -49,46 +42,37 @@ bool StateTracker::CreateInstance()
void StateTracker::DestroyInstance()
{
+ if (!s_state_tracker)
+ return;
+
+ // When the dummy texture is destroyed, it unbinds itself, then references itself.
+ // Clear everything out so this doesn't happen.
+ for (auto& it : s_state_tracker->m_bindings.samplers)
+ it.imageView = VK_NULL_HANDLE;
+ s_state_tracker->m_bindings.image_texture.imageView = VK_NULL_HANDLE;
+ s_state_tracker->m_dummy_texture.reset();
+
s_state_tracker.reset();
}
bool StateTracker::Initialize()
{
+ // Create a dummy texture which can be used in place of a real binding.
+ m_dummy_texture =
+ VKTexture::Create(TextureConfig(1, 1, 1, 1, 1, AbstractTextureFormat::RGBA8, 0));
+ if (!m_dummy_texture)
+ return false;
+
// Initialize all samplers to point by default
for (size_t i = 0; i < NUM_PIXEL_SHADER_SAMPLERS; i++)
{
- m_bindings.ps_samplers[i].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
- m_bindings.ps_samplers[i].imageView = g_object_cache->GetDummyImageView();
- m_bindings.ps_samplers[i].sampler = g_object_cache->GetPointSampler();
+ m_bindings.samplers[i].imageLayout = VK_IMAGE_LAYOUT_UNDEFINED;
+ m_bindings.samplers[i].imageView = m_dummy_texture->GetView();
+ m_bindings.samplers[i].sampler = g_object_cache->GetPointSampler();
}
- // Create the streaming uniform buffer
- m_uniform_stream_buffer =
- StreamBuffer::Create(VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, INITIAL_UNIFORM_STREAM_BUFFER_SIZE,
- MAXIMUM_UNIFORM_STREAM_BUFFER_SIZE);
- if (!m_uniform_stream_buffer)
- {
- PanicAlert("Failed to create uniform stream buffer");
- return false;
- }
-
- // The validation layer complains if max(offsets) + max(ubo_ranges) >= ubo_size.
- // To work around this we reserve the maximum buffer size at all times, but only commit
- // as many bytes as we use.
- m_uniform_buffer_reserve_size = sizeof(PixelShaderConstants);
- m_uniform_buffer_reserve_size = Common::AlignUp(m_uniform_buffer_reserve_size,
- g_vulkan_context->GetUniformBufferAlignment()) +
- sizeof(VertexShaderConstants);
- m_uniform_buffer_reserve_size = Common::AlignUp(m_uniform_buffer_reserve_size,
- g_vulkan_context->GetUniformBufferAlignment()) +
- sizeof(GeometryShaderConstants);
-
// Default dirty flags include all descriptors
- InvalidateDescriptorSets();
- SetPendingRebind();
-
- // Set default constants
- UploadAllConstants();
+ InvalidateCachedState();
return true;
}
@@ -113,20 +97,11 @@ void StateTracker::SetIndexBuffer(VkBuffer buffer, VkDeviceSize offset, VkIndexT
m_dirty_flags |= DIRTY_FLAG_INDEX_BUFFER;
}
-void StateTracker::SetRenderPass(VkRenderPass load_render_pass, VkRenderPass clear_render_pass)
-{
- // Should not be changed within a render pass.
- ASSERT(!InRenderPass());
- m_load_render_pass = load_render_pass;
- m_clear_render_pass = clear_render_pass;
-}
-
-void StateTracker::SetFramebuffer(VkFramebuffer framebuffer, const VkRect2D& render_area)
+void StateTracker::SetFramebuffer(VKFramebuffer* framebuffer)
{
// Should not be changed within a render pass.
ASSERT(!InRenderPass());
m_framebuffer = framebuffer;
- m_framebuffer_size = render_area;
}
void StateTracker::SetPipeline(const VKPipeline* pipeline)
@@ -134,278 +109,177 @@ void StateTracker::SetPipeline(const VKPipeline* pipeline)
if (m_pipeline == pipeline)
return;
+ // If the usage changes, we need to re-bind everything, as the layout is different.
const bool new_usage =
pipeline && (!m_pipeline || m_pipeline->GetUsage() != pipeline->GetUsage());
m_pipeline = pipeline;
m_dirty_flags |= DIRTY_FLAG_PIPELINE;
if (new_usage)
- m_dirty_flags |= DIRTY_FLAG_ALL_DESCRIPTOR_SETS;
+ m_dirty_flags |= DIRTY_FLAG_DESCRIPTOR_SETS;
}
-void StateTracker::UpdateVertexShaderConstants()
+void StateTracker::SetComputeShader(const VKShader* shader)
{
- if (!VertexShaderManager::dirty || !ReserveConstantStorage())
+ if (m_compute_shader == shader)
return;
- // Buffer allocation changed?
- if (m_uniform_stream_buffer->GetBuffer() !=
- m_bindings.uniform_buffer_bindings[UBO_DESCRIPTOR_SET_BINDING_VS].buffer)
- {
- m_bindings.uniform_buffer_bindings[UBO_DESCRIPTOR_SET_BINDING_VS].buffer =
- m_uniform_stream_buffer->GetBuffer();
- m_dirty_flags |= DIRTY_FLAG_VS_UBO;
- }
-
- m_bindings.uniform_buffer_offsets[UBO_DESCRIPTOR_SET_BINDING_VS] =
- static_cast<uint32_t>(m_uniform_stream_buffer->GetCurrentOffset());
- m_dirty_flags |= DIRTY_FLAG_DYNAMIC_OFFSETS;
-
- memcpy(m_uniform_stream_buffer->GetCurrentHostPointer(), &VertexShaderManager::constants,
- sizeof(VertexShaderConstants));
- ADDSTAT(stats.thisFrame.bytesUniformStreamed, sizeof(VertexShaderConstants));
- m_uniform_stream_buffer->CommitMemory(sizeof(VertexShaderConstants));
- VertexShaderManager::dirty = false;
+ m_compute_shader = shader;
+ m_dirty_flags |= DIRTY_FLAG_COMPUTE_SHADER;
}
-void StateTracker::UpdateGeometryShaderConstants()
+void StateTracker::SetGXUniformBuffer(u32 index, VkBuffer buffer, u32 offset, u32 size)
{
- if (!GeometryShaderManager::dirty || !ReserveConstantStorage())
- return;
-
- // Buffer allocation changed?
- if (m_uniform_stream_buffer->GetBuffer() !=
- m_bindings.uniform_buffer_bindings[UBO_DESCRIPTOR_SET_BINDING_GS].buffer)
+ auto& binding = m_bindings.gx_ubo_bindings[index];
+ if (binding.buffer != buffer || binding.range != size)
{
- m_bindings.uniform_buffer_bindings[UBO_DESCRIPTOR_SET_BINDING_GS].buffer =
- m_uniform_stream_buffer->GetBuffer();
- m_dirty_flags |= DIRTY_FLAG_GS_UBO;
+ binding.buffer = buffer;
+ binding.range = size;
+ m_dirty_flags |= DIRTY_FLAG_GX_UBOS;
}
- m_bindings.uniform_buffer_offsets[UBO_DESCRIPTOR_SET_BINDING_GS] =
- static_cast<uint32_t>(m_uniform_stream_buffer->GetCurrentOffset());
- m_dirty_flags |= DIRTY_FLAG_DYNAMIC_OFFSETS;
-
- memcpy(m_uniform_stream_buffer->GetCurrentHostPointer(), &GeometryShaderManager::constants,
- sizeof(GeometryShaderConstants));
- ADDSTAT(stats.thisFrame.bytesUniformStreamed, sizeof(GeometryShaderConstants));
- m_uniform_stream_buffer->CommitMemory(sizeof(GeometryShaderConstants));
- GeometryShaderManager::dirty = false;
-}
-
-void StateTracker::UpdatePixelShaderConstants()
-{
- if (!PixelShaderManager::dirty || !ReserveConstantStorage())
- return;
-
- // Buffer allocation changed?
- if (m_uniform_stream_buffer->GetBuffer() !=
- m_bindings.uniform_buffer_bindings[UBO_DESCRIPTOR_SET_BINDING_PS].buffer)
+ if (m_bindings.gx_ubo_offsets[index] != offset)
{
- m_bindings.uniform_buffer_bindings[UBO_DESCRIPTOR_SET_BINDING_PS].buffer =
- m_uniform_stream_buffer->GetBuffer();
- m_dirty_flags |= DIRTY_FLAG_PS_UBO;
+ m_bindings.gx_ubo_offsets[index] = offset;
+ m_dirty_flags |= DIRTY_FLAG_GX_UBO_OFFSETS;
}
-
- m_bindings.uniform_buffer_offsets[UBO_DESCRIPTOR_SET_BINDING_PS] =
- static_cast<uint32_t>(m_uniform_stream_buffer->GetCurrentOffset());
- m_dirty_flags |= DIRTY_FLAG_DYNAMIC_OFFSETS;
-
- memcpy(m_uniform_stream_buffer->GetCurrentHostPointer(), &PixelShaderManager::constants,
- sizeof(PixelShaderConstants));
- ADDSTAT(stats.thisFrame.bytesUniformStreamed, sizeof(PixelShaderConstants));
- m_uniform_stream_buffer->CommitMemory(sizeof(PixelShaderConstants));
- PixelShaderManager::dirty = false;
}
-void StateTracker::UpdateConstants(const void* data, u32 data_size)
+void StateTracker::SetUtilityUniformBuffer(VkBuffer buffer, u32 offset, u32 size)
{
- if (!m_uniform_stream_buffer->ReserveMemory(
- data_size, g_vulkan_context->GetUniformBufferAlignment(), true, true, false))
+ auto& binding = m_bindings.utility_ubo_binding;
+ if (binding.buffer != buffer || binding.range != size)
{
- WARN_LOG(VIDEO, "Executing command buffer while waiting for ext space in uniform buffer");
- Util::ExecuteCurrentCommandsAndRestoreState(false);
+ binding.buffer = buffer;
+ binding.range = size;
+ m_dirty_flags |= DIRTY_FLAG_UTILITY_UBO;
}
- for (u32 binding = 0; binding < NUM_UBO_DESCRIPTOR_SET_BINDINGS; binding++)
+ if (m_bindings.utility_ubo_offset != offset)
{
- if (m_bindings.uniform_buffer_bindings[binding].buffer != m_uniform_stream_buffer->GetBuffer())
- {
- m_bindings.uniform_buffer_bindings[binding].buffer = m_uniform_stream_buffer->GetBuffer();
- m_dirty_flags |= DIRTY_FLAG_VS_UBO << binding;
- }
- m_bindings.uniform_buffer_offsets[binding] =
- static_cast<uint32_t>(m_uniform_stream_buffer->GetCurrentOffset());
+ m_bindings.utility_ubo_offset = offset;
+ m_dirty_flags |= DIRTY_FLAG_UTILITY_UBO_OFFSET | DIRTY_FLAG_COMPUTE_DESCRIPTOR_SET;
}
- m_dirty_flags |= DIRTY_FLAG_DYNAMIC_OFFSETS;
-
- std::memcpy(m_uniform_stream_buffer->GetCurrentHostPointer(), data, data_size);
- ADDSTAT(stats.thisFrame.bytesUniformStreamed, data_size);
- m_uniform_stream_buffer->CommitMemory(data_size);
-
- // Cached data is now out-of-sync.
- VertexShaderManager::dirty = true;
- GeometryShaderManager::dirty = true;
- PixelShaderManager::dirty = true;
}
-bool StateTracker::ReserveConstantStorage()
+void StateTracker::SetTexture(u32 index, VkImageView view)
{
- // Since we invalidate all constants on command buffer execution, it doesn't matter if this
- // causes the stream buffer to be resized.
- if (m_uniform_stream_buffer->ReserveMemory(m_uniform_buffer_reserve_size,
- g_vulkan_context->GetUniformBufferAlignment(), true,
- true, false))
- {
- return true;
- }
-
- // The only places that call constant updates are safe to have state restored.
- WARN_LOG(VIDEO, "Executing command buffer while waiting for space in uniform buffer");
- Util::ExecuteCurrentCommandsAndRestoreState(false);
+ if (m_bindings.samplers[index].imageView == view)
+ return;
- // Since we are on a new command buffer, all constants have been invalidated, and we need
- // to reupload them. We may as well do this now, since we're issuing a draw anyway.
- UploadAllConstants();
- return false;
+ m_bindings.samplers[index].imageView = view;
+ m_bindings.samplers[index].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
+ m_dirty_flags |=
+ DIRTY_FLAG_GX_SAMPLERS | DIRTY_FLAG_UTILITY_BINDINGS | DIRTY_FLAG_COMPUTE_BINDINGS;
}
-void StateTracker::UploadAllConstants()
+void StateTracker::SetSampler(u32 index, VkSampler sampler)
{
- // We are free to re-use parts of the buffer now since we're uploading all constants.
- size_t ub_alignment = g_vulkan_context->GetUniformBufferAlignment();
- size_t pixel_constants_offset = 0;
- size_t vertex_constants_offset =
- Common::AlignUp(pixel_constants_offset + sizeof(PixelShaderConstants), ub_alignment);
- size_t geometry_constants_offset =
- Common::AlignUp(vertex_constants_offset + sizeof(VertexShaderConstants), ub_alignment);
- size_t allocation_size = geometry_constants_offset + sizeof(GeometryShaderConstants);
-
- // Allocate everything at once.
- // We should only be here if the buffer was full and a command buffer was submitted anyway.
- if (!m_uniform_stream_buffer->ReserveMemory(allocation_size, ub_alignment, true, true, false))
- {
- PanicAlert("Failed to allocate space for constants in streaming buffer");
+ if (m_bindings.samplers[index].sampler == sampler)
return;
- }
-
- // Update bindings
- for (size_t i = 0; i < NUM_UBO_DESCRIPTOR_SET_BINDINGS; i++)
- {
- m_bindings.uniform_buffer_bindings[i].buffer = m_uniform_stream_buffer->GetBuffer();
- m_bindings.uniform_buffer_bindings[i].offset = 0;
- }
- m_bindings.uniform_buffer_bindings[UBO_DESCRIPTOR_SET_BINDING_PS].range =
- sizeof(PixelShaderConstants);
- m_bindings.uniform_buffer_bindings[UBO_DESCRIPTOR_SET_BINDING_VS].range =
- sizeof(VertexShaderConstants);
- m_bindings.uniform_buffer_bindings[UBO_DESCRIPTOR_SET_BINDING_GS].range =
- sizeof(GeometryShaderConstants);
-
- // Update dynamic offsets
- m_bindings.uniform_buffer_offsets[UBO_DESCRIPTOR_SET_BINDING_PS] =
- static_cast<uint32_t>(m_uniform_stream_buffer->GetCurrentOffset() + pixel_constants_offset);
-
- m_bindings.uniform_buffer_offsets[UBO_DESCRIPTOR_SET_BINDING_VS] =
- static_cast<uint32_t>(m_uniform_stream_buffer->GetCurrentOffset() + vertex_constants_offset);
-
- m_bindings.uniform_buffer_offsets[UBO_DESCRIPTOR_SET_BINDING_GS] = static_cast<uint32_t>(
- m_uniform_stream_buffer->GetCurrentOffset() + geometry_constants_offset);
-
- m_dirty_flags |= DIRTY_FLAG_ALL_DESCRIPTOR_SETS | DIRTY_FLAG_DYNAMIC_OFFSETS | DIRTY_FLAG_VS_UBO |
- DIRTY_FLAG_GS_UBO | DIRTY_FLAG_PS_UBO;
-
- // Copy the actual data in
- memcpy(m_uniform_stream_buffer->GetCurrentHostPointer() + pixel_constants_offset,
- &PixelShaderManager::constants, sizeof(PixelShaderConstants));
- memcpy(m_uniform_stream_buffer->GetCurrentHostPointer() + vertex_constants_offset,
- &VertexShaderManager::constants, sizeof(VertexShaderConstants));
- memcpy(m_uniform_stream_buffer->GetCurrentHostPointer() + geometry_constants_offset,
- &GeometryShaderManager::constants, sizeof(GeometryShaderConstants));
- // Finally, flush buffer memory after copying
- m_uniform_stream_buffer->CommitMemory(allocation_size);
-
- // Clear dirty flags
- VertexShaderManager::dirty = false;
- GeometryShaderManager::dirty = false;
- PixelShaderManager::dirty = false;
+ m_bindings.samplers[index].sampler = sampler;
+ m_dirty_flags |=
+ DIRTY_FLAG_GX_SAMPLERS | DIRTY_FLAG_UTILITY_BINDINGS | DIRTY_FLAG_COMPUTE_BINDINGS;
}
-void StateTracker::SetTexture(size_t index, VkImageView view)
+void StateTracker::SetSSBO(VkBuffer buffer, VkDeviceSize offset, VkDeviceSize range)
{
- if (m_bindings.ps_samplers[index].imageView == view)
+ if (m_bindings.ssbo.buffer == buffer && m_bindings.ssbo.offset == offset &&
+ m_bindings.ssbo.range == range)
+ {
return;
+ }
- m_bindings.ps_samplers[index].imageView = view;
- m_bindings.ps_samplers[index].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
- m_dirty_flags |= DIRTY_FLAG_PS_SAMPLERS;
+ m_bindings.ssbo.buffer = buffer;
+ m_bindings.ssbo.offset = offset;
+ m_bindings.ssbo.range = range;
+ m_dirty_flags |= DIRTY_FLAG_GX_SSBO;
}
-void StateTracker::SetSampler(size_t index, VkSampler sampler)
+void StateTracker::SetTexelBuffer(u32 index, VkBufferView view)
{
- if (m_bindings.ps_samplers[index].sampler == sampler)
+ if (m_bindings.texel_buffers[index] == view)
return;
- m_bindings.ps_samplers[index].sampler = sampler;
- m_dirty_flags |= DIRTY_FLAG_PS_SAMPLERS;
+ m_bindings.texel_buffers[index] = view;
+ m_dirty_flags |= DIRTY_FLAG_UTILITY_BINDINGS | DIRTY_FLAG_COMPUTE_BINDINGS;
}
-void StateTracker::SetBBoxBuffer(VkBuffer buffer, VkDeviceSize offset, VkDeviceSize range)
+void StateTracker::SetImageTexture(VkImageView view)
{
- if (m_bindings.ps_ssbo.buffer == buffer && m_bindings.ps_ssbo.offset == offset &&
- m_bindings.ps_ssbo.range == range)
- {
+ if (m_bindings.image_texture.imageView == view)
return;
- }
- m_bindings.ps_ssbo.buffer = buffer;
- m_bindings.ps_ssbo.offset = offset;
- m_bindings.ps_ssbo.range = range;
- m_dirty_flags |= DIRTY_FLAG_PS_SSBO;
+ m_bindings.image_texture.imageView = view;
+ m_bindings.image_texture.imageLayout = VK_IMAGE_LAYOUT_GENERAL;
+ m_dirty_flags |= DIRTY_FLAG_COMPUTE_BINDINGS;
}
void StateTracker::UnbindTexture(VkImageView view)
{
- for (VkDescriptorImageInfo& it : m_bindings.ps_samplers)
+ for (VkDescriptorImageInfo& it : m_bindings.samplers)
{
if (it.imageView == view)
- it.imageView = g_object_cache->GetDummyImageView();
+ {
+ it.imageView = m_dummy_texture->GetView();
+ it.imageLayout = VK_IMAGE_LAYOUT_UNDEFINED;
+ }
}
-}
-void StateTracker::InvalidateDescriptorSets()
-{
- m_descriptor_sets.fill(VK_NULL_HANDLE);
- m_dirty_flags |= DIRTY_FLAG_ALL_DESCRIPTOR_SETS;
+ if (m_bindings.image_texture.imageView == view)
+ {
+ m_bindings.image_texture.imageView = m_dummy_texture->GetView();
+ m_bindings.image_texture.imageLayout = VK_IMAGE_LAYOUT_UNDEFINED;
+ }
}
-void StateTracker::InvalidateConstants()
+void StateTracker::InvalidateCachedState()
{
- VertexShaderManager::dirty = true;
- GeometryShaderManager::dirty = true;
- PixelShaderManager::dirty = true;
+ m_gx_descriptor_sets.fill(VK_NULL_HANDLE);
+ m_utility_descriptor_sets.fill(VK_NULL_HANDLE);
+ m_compute_descriptor_set = VK_NULL_HANDLE;
+ m_dirty_flags |= DIRTY_FLAG_ALL_DESCRIPTORS | DIRTY_FLAG_VIEWPORT | DIRTY_FLAG_SCISSOR |
+ DIRTY_FLAG_PIPELINE | DIRTY_FLAG_COMPUTE_SHADER | DIRTY_FLAG_DESCRIPTOR_SETS |
+ DIRTY_FLAG_COMPUTE_DESCRIPTOR_SET;
+ if (m_vertex_buffer != VK_NULL_HANDLE)
+ m_dirty_flags |= DIRTY_FLAG_VERTEX_BUFFER;
+ if (m_index_buffer != VK_NULL_HANDLE)
+ m_dirty_flags |= DIRTY_FLAG_INDEX_BUFFER;
}
-void StateTracker::SetPendingRebind()
+void StateTracker::BeginRenderPass()
{
- m_dirty_flags |= DIRTY_FLAG_DYNAMIC_OFFSETS | DIRTY_FLAG_DESCRIPTOR_SET_BINDING |
- DIRTY_FLAG_VERTEX_BUFFER | DIRTY_FLAG_INDEX_BUFFER | DIRTY_FLAG_VIEWPORT |
- DIRTY_FLAG_SCISSOR | DIRTY_FLAG_PIPELINE;
+ if (InRenderPass())
+ return;
+
+ m_current_render_pass = m_framebuffer->GetLoadRenderPass();
+ m_framebuffer_render_area = m_framebuffer->GetRect();
+
+ VkRenderPassBeginInfo begin_info = {VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO,
+ nullptr,
+ m_current_render_pass,
+ m_framebuffer->GetFB(),
+ m_framebuffer_render_area,
+ 0,
+ nullptr};
+
+ vkCmdBeginRenderPass(g_command_buffer_mgr->GetCurrentCommandBuffer(), &begin_info,
+ VK_SUBPASS_CONTENTS_INLINE);
}
-void StateTracker::BeginRenderPass()
+void StateTracker::BeginDiscardRenderPass()
{
if (InRenderPass())
return;
- m_current_render_pass = m_load_render_pass;
- m_framebuffer_render_area = m_framebuffer_size;
+ m_current_render_pass = m_framebuffer->GetDiscardRenderPass();
+ m_framebuffer_render_area = m_framebuffer->GetRect();
VkRenderPassBeginInfo begin_info = {VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO,
nullptr,
m_current_render_pass,
- m_framebuffer,
+ m_framebuffer->GetFB(),
m_framebuffer_render_area,
0,
nullptr};
@@ -428,13 +302,13 @@ void StateTracker::BeginClearRenderPass(const VkRect2D& area, const VkClearValue
{
ASSERT(!InRenderPass());
- m_current_render_pass = m_clear_render_pass;
+ m_current_render_pass = m_framebuffer->GetClearRenderPass();
m_framebuffer_render_area = area;
VkRenderPassBeginInfo begin_info = {VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO,
nullptr,
m_current_render_pass,
- m_framebuffer,
+ m_framebuffer->GetFB(),
m_framebuffer_render_area,
num_clear_values,
clear_values};
@@ -461,22 +335,22 @@ void StateTracker::SetScissor(const VkRect2D& scissor)
m_dirty_flags |= DIRTY_FLAG_SCISSOR;
}
-bool StateTracker::Bind(bool rebind_all /*= false*/)
+bool StateTracker::Bind()
{
// Must have a pipeline.
if (!m_pipeline)
return false;
// Check the render area if we were in a clear pass.
- if (m_current_render_pass == m_clear_render_pass && !IsViewportWithinRenderArea())
+ if (m_current_render_pass == m_framebuffer->GetClearRenderPass() && !IsViewportWithinRenderArea())
EndRenderPass();
// Get a new descriptor set if any parts have changed
- if (m_dirty_flags & DIRTY_FLAG_ALL_DESCRIPTOR_SETS && !UpdateDescriptorSet())
+ if (!UpdateDescriptorSet())
{
// We can fail to allocate descriptors if we exhaust the pool for this command buffer.
WARN_LOG(VIDEO, "Failed to get a descriptor set, executing buffer");
- Util::ExecuteCurrentCommandsAndRestoreState(false, false);
+ Renderer::GetInstance()->ExecuteCommandBuffer(false, false);
if (!UpdateDescriptorSet())
{
// Something strange going on.
@@ -490,151 +364,57 @@ bool StateTracker::Bind(bool rebind_all /*= false*/)
BeginRenderPass();
// Re-bind parts of the pipeline
- VkCommandBuffer command_buffer = g_command_buffer_mgr->GetCurrentCommandBuffer();
- if (m_dirty_flags & DIRTY_FLAG_VERTEX_BUFFER || rebind_all)
+ const VkCommandBuffer command_buffer = g_command_buffer_mgr->GetCurrentCommandBuffer();
+ if (m_dirty_flags & DIRTY_FLAG_VERTEX_BUFFER)
vkCmdBindVertexBuffers(command_buffer, 0, 1, &m_vertex_buffer, &m_vertex_buffer_offset);
- if (m_dirty_flags & DIRTY_FLAG_INDEX_BUFFER || rebind_all)
+ if (m_dirty_flags & DIRTY_FLAG_INDEX_BUFFER)
vkCmdBindIndexBuffer(command_buffer, m_index_buffer, m_index_buffer_offset, m_index_type);
- if (m_dirty_flags & DIRTY_FLAG_PIPELINE || rebind_all)
+ if (m_dirty_flags & DIRTY_FLAG_PIPELINE)
vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, m_pipeline->GetVkPipeline());
- if (m_dirty_flags & DIRTY_FLAG_DESCRIPTOR_SET_BINDING || rebind_all)
- {
- vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS,
- m_pipeline->GetVkPipelineLayout(), 0, m_num_active_descriptor_sets,
- m_descriptor_sets.data(), m_num_dynamic_offsets,
- m_bindings.uniform_buffer_offsets.data());
- }
- else if (m_dirty_flags & DIRTY_FLAG_DYNAMIC_OFFSETS)
- {
- vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS,
- m_pipeline->GetVkPipelineLayout(),
- DESCRIPTOR_SET_BIND_POINT_UNIFORM_BUFFERS, 1,
- &m_descriptor_sets[DESCRIPTOR_SET_BIND_POINT_UNIFORM_BUFFERS],
- m_num_dynamic_offsets, m_bindings.uniform_buffer_offsets.data());
- }
-
- if (m_dirty_flags & DIRTY_FLAG_VIEWPORT || rebind_all)
+ if (m_dirty_flags & DIRTY_FLAG_VIEWPORT)
vkCmdSetViewport(command_buffer, 0, 1, &m_viewport);
- if (m_dirty_flags & DIRTY_FLAG_SCISSOR || rebind_all)
+ if (m_dirty_flags & DIRTY_FLAG_SCISSOR)
vkCmdSetScissor(command_buffer, 0, 1, &m_scissor);
- m_dirty_flags = 0;
+ m_dirty_flags &= ~(DIRTY_FLAG_VERTEX_BUFFER | DIRTY_FLAG_INDEX_BUFFER | DIRTY_FLAG_PIPELINE |
+ DIRTY_FLAG_VIEWPORT | DIRTY_FLAG_SCISSOR);
return true;
}
-void StateTracker::OnDraw()
+bool StateTracker::BindCompute()
{
- m_draw_counter++;
-
- // If we didn't have any CPU access last frame, do nothing.
- if (m_scheduled_command_buffer_kicks.empty() || !m_allow_background_execution)
- return;
-
- // Check if this draw is scheduled to kick a command buffer.
- // The draw counters will always be sorted so a binary search is possible here.
- if (std::binary_search(m_scheduled_command_buffer_kicks.begin(),
- m_scheduled_command_buffer_kicks.end(), m_draw_counter))
- {
- // Kick a command buffer on the background thread.
- Util::ExecuteCurrentCommandsAndRestoreState(true);
- }
-}
-
-void StateTracker::OnCPUEFBAccess()
-{
- // Check this isn't another access without any draws inbetween.
- if (!m_cpu_accesses_this_frame.empty() && m_cpu_accesses_this_frame.back() == m_draw_counter)
- return;
+ if (!m_compute_shader)
+ return false;
- // Store the current draw counter for scheduling in OnEndFrame.
- m_cpu_accesses_this_frame.emplace_back(m_draw_counter);
-}
+ // Can't kick compute in a render pass.
+ if (InRenderPass())
+ EndRenderPass();
-void StateTracker::OnEFBCopyToRAM()
-{
- // If we're not deferring, try to preempt it next frame.
- if (!g_ActiveConfig.bDeferEFBCopies)
+ const VkCommandBuffer command_buffer = g_command_buffer_mgr->GetCurrentCommandBuffer();
+ if (m_dirty_flags & DIRTY_FLAG_COMPUTE_SHADER)
{
- OnCPUEFBAccess();
- return;
+ vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE,
+ m_compute_shader->GetComputePipeline());
}
- // Otherwise, only execute if we have at least 10 objects between us and the last copy.
- const u32 diff = m_draw_counter - m_last_efb_copy_draw_counter;
- m_last_efb_copy_draw_counter = m_draw_counter;
- if (diff < MINIMUM_DRAW_CALLS_PER_COMMAND_BUFFER_FOR_READBACK)
- return;
-
- Util::ExecuteCurrentCommandsAndRestoreState(true);
-}
-
-void StateTracker::OnEndFrame()
-{
- m_draw_counter = 0;
- m_last_efb_copy_draw_counter = 0;
- m_scheduled_command_buffer_kicks.clear();
-
- // If we have no CPU access at all, leave everything in the one command buffer for maximum
- // parallelism between CPU/GPU, at the cost of slightly higher latency.
- if (m_cpu_accesses_this_frame.empty())
- return;
-
- // In order to reduce CPU readback latency, we want to kick a command buffer roughly halfway
- // between the draw counters that invoked the readback, or every 250 draws, whichever is smaller.
- if (g_ActiveConfig.iCommandBufferExecuteInterval > 0)
+ if (!UpdateComputeDescriptorSet())
{
- u32 last_draw_counter = 0;
- u32 interval = static_cast<u32>(g_ActiveConfig.iCommandBufferExecuteInterval);
- for (u32 draw_counter : m_cpu_accesses_this_frame)
+ WARN_LOG(VIDEO, "Failed to get a compute descriptor set, executing buffer");
+ Renderer::GetInstance()->ExecuteCommandBuffer(false, false);
+ if (!UpdateComputeDescriptorSet())
{
- // We don't want to waste executing command buffers for only a few draws, so set a minimum.
- // Leave last_draw_counter as-is, so we get the correct number of draws between submissions.
- u32 draw_count = draw_counter - last_draw_counter;
- if (draw_count < MINIMUM_DRAW_CALLS_PER_COMMAND_BUFFER_FOR_READBACK)
- continue;
-
- if (draw_count <= interval)
- {
- u32 mid_point = draw_count / 2;
- m_scheduled_command_buffer_kicks.emplace_back(last_draw_counter + mid_point);
- }
- else
- {
- u32 counter = interval;
- while (counter < draw_count)
- {
- m_scheduled_command_buffer_kicks.emplace_back(last_draw_counter + counter);
- counter += interval;
- }
- }
-
- last_draw_counter = draw_counter;
+ // Something strange going on.
+ ERROR_LOG(VIDEO, "Failed to get descriptor set, skipping dispatch");
+ return false;
}
}
-#if 0
- {
- std::stringstream ss;
- std::for_each(m_cpu_accesses_this_frame.begin(), m_cpu_accesses_this_frame.end(), [&ss](u32 idx) { ss << idx << ","; });
- WARN_LOG(VIDEO, "CPU EFB accesses in last frame: %s", ss.str().c_str());
- }
- {
- std::stringstream ss;
- std::for_each(m_scheduled_command_buffer_kicks.begin(), m_scheduled_command_buffer_kicks.end(), [&ss](u32 idx) { ss << idx << ","; });
- WARN_LOG(VIDEO, "Scheduled command buffer kicks: %s", ss.str().c_str());
- }
-#endif
-
- m_cpu_accesses_this_frame.clear();
-}
-
-void StateTracker::SetBackgroundCommandBufferExecution(bool enabled)
-{
- m_allow_background_execution = enabled;
+ m_dirty_flags &= ~DIRTY_FLAG_COMPUTE_SHADER;
+ return true;
}
bool StateTracker::IsWithinRenderArea(s32 x, s32 y, u32 width, u32 height) const
@@ -661,7 +441,7 @@ bool StateTracker::IsViewportWithinRenderArea() const
void StateTracker::EndClearRenderPass()
{
- if (m_current_render_pass != m_clear_render_pass)
+ if (m_current_render_pass != m_framebuffer->GetClearRenderPass())
return;
// End clear render pass. Bind() will call BeginRenderPass() which
@@ -685,135 +465,244 @@ bool StateTracker::UpdateGXDescriptorSet()
std::array<VkWriteDescriptorSet, MAX_DESCRIPTOR_WRITES> writes;
u32 num_writes = 0;
- if (m_dirty_flags & (DIRTY_FLAG_VS_UBO | DIRTY_FLAG_GS_UBO | DIRTY_FLAG_PS_UBO) ||
- m_descriptor_sets[DESCRIPTOR_SET_BIND_POINT_UNIFORM_BUFFERS] == VK_NULL_HANDLE)
+ if (m_dirty_flags & DIRTY_FLAG_GX_UBOS || m_gx_descriptor_sets[0] == VK_NULL_HANDLE)
{
- VkDescriptorSetLayout layout =
- g_object_cache->GetDescriptorSetLayout(DESCRIPTOR_SET_LAYOUT_PER_STAGE_UNIFORM_BUFFERS);
- VkDescriptorSet set = g_command_buffer_mgr->AllocateDescriptorSet(layout);
- if (set == VK_NULL_HANDLE)
+ m_gx_descriptor_sets[0] = g_command_buffer_mgr->AllocateDescriptorSet(
+ g_object_cache->GetDescriptorSetLayout(DESCRIPTOR_SET_LAYOUT_STANDARD_UNIFORM_BUFFERS));
+ if (m_gx_descriptor_sets[0] == VK_NULL_HANDLE)
return false;
for (size_t i = 0; i < NUM_UBO_DESCRIPTOR_SET_BINDINGS; i++)
{
- if (i == UBO_DESCRIPTOR_SET_BINDING_GS && !g_vulkan_context->SupportsGeometryShaders())
+ if (i == UBO_DESCRIPTOR_SET_BINDING_GS &&
+ !g_ActiveConfig.backend_info.bSupportsGeometryShaders)
+ {
continue;
+ }
writes[num_writes++] = {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
nullptr,
- set,
+ m_gx_descriptor_sets[0],
static_cast<uint32_t>(i),
0,
1,
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC,
nullptr,
- &m_bindings.uniform_buffer_bindings[i],
+ &m_bindings.gx_ubo_bindings[i],
nullptr};
}
- m_descriptor_sets[DESCRIPTOR_SET_BIND_POINT_UNIFORM_BUFFERS] = set;
- m_dirty_flags |= DIRTY_FLAG_DESCRIPTOR_SET_BINDING;
+ m_dirty_flags = (m_dirty_flags & ~DIRTY_FLAG_GX_UBOS) | DIRTY_FLAG_DESCRIPTOR_SETS;
}
- if (m_dirty_flags & DIRTY_FLAG_PS_SAMPLERS ||
- m_descriptor_sets[DESCRIPTOR_SET_BIND_POINT_PIXEL_SHADER_SAMPLERS] == VK_NULL_HANDLE)
+ if (m_dirty_flags & DIRTY_FLAG_GX_SAMPLERS || m_gx_descriptor_sets[1] == VK_NULL_HANDLE)
{
- VkDescriptorSetLayout layout =
- g_object_cache->GetDescriptorSetLayout(DESCRIPTOR_SET_LAYOUT_PIXEL_SHADER_SAMPLERS);
- VkDescriptorSet set = g_command_buffer_mgr->AllocateDescriptorSet(layout);
- if (set == VK_NULL_HANDLE)
+ m_gx_descriptor_sets[1] = g_command_buffer_mgr->AllocateDescriptorSet(
+ g_object_cache->GetDescriptorSetLayout(DESCRIPTOR_SET_LAYOUT_STANDARD_SAMPLERS));
+ if (m_gx_descriptor_sets[1] == VK_NULL_HANDLE)
return false;
writes[num_writes++] = {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
nullptr,
- set,
+ m_gx_descriptor_sets[1],
0,
0,
static_cast<u32>(NUM_PIXEL_SHADER_SAMPLERS),
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
- m_bindings.ps_samplers.data(),
+ m_bindings.samplers.data(),
nullptr,
nullptr};
-
- m_descriptor_sets[DESCRIPTOR_SET_BIND_POINT_PIXEL_SHADER_SAMPLERS] = set;
- m_dirty_flags |= DIRTY_FLAG_DESCRIPTOR_SET_BINDING;
+ m_dirty_flags = (m_dirty_flags & ~DIRTY_FLAG_GX_SAMPLERS) | DIRTY_FLAG_DESCRIPTOR_SETS;
}
- if (g_vulkan_context->SupportsBoundingBox() &&
- (m_dirty_flags & DIRTY_FLAG_PS_SSBO ||
- m_descriptor_sets[DESCRIPTOR_SET_BIND_POINT_STORAGE_OR_TEXEL_BUFFER] == VK_NULL_HANDLE))
+ if (g_ActiveConfig.backend_info.bSupportsBBox &&
+ (m_dirty_flags & DIRTY_FLAG_GX_SSBO || m_gx_descriptor_sets[2] == VK_NULL_HANDLE))
{
- VkDescriptorSetLayout layout =
- g_object_cache->GetDescriptorSetLayout(DESCRIPTOR_SET_LAYOUT_SHADER_STORAGE_BUFFERS);
- VkDescriptorSet set = g_command_buffer_mgr->AllocateDescriptorSet(layout);
- if (set == VK_NULL_HANDLE)
+ m_gx_descriptor_sets[2] =
+ g_command_buffer_mgr->AllocateDescriptorSet(g_object_cache->GetDescriptorSetLayout(
+ DESCRIPTOR_SET_LAYOUT_STANDARD_SHADER_STORAGE_BUFFERS));
+ if (m_gx_descriptor_sets[2] == VK_NULL_HANDLE)
return false;
- writes[num_writes++] = {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
- nullptr,
- set,
- 0,
- 0,
- 1,
- VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
- nullptr,
- &m_bindings.ps_ssbo,
- nullptr};
-
- m_descriptor_sets[DESCRIPTOR_SET_BIND_POINT_STORAGE_OR_TEXEL_BUFFER] = set;
- m_dirty_flags |= DIRTY_FLAG_DESCRIPTOR_SET_BINDING;
+ writes[num_writes++] = {
+ VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, nullptr, m_gx_descriptor_sets[2], 0, 0, 1,
+ VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, nullptr, &m_bindings.ssbo, nullptr};
+ m_dirty_flags = (m_dirty_flags & ~DIRTY_FLAG_GX_SSBO) | DIRTY_FLAG_DESCRIPTOR_SETS;
}
if (num_writes > 0)
vkUpdateDescriptorSets(g_vulkan_context->GetDevice(), num_writes, writes.data(), 0, nullptr);
- m_num_active_descriptor_sets = g_vulkan_context->SupportsBoundingBox() ?
- NUM_GX_DRAW_DESCRIPTOR_SETS_SSBO :
- NUM_GX_DRAW_DESCRIPTOR_SETS;
- m_num_dynamic_offsets = NUM_UBO_DESCRIPTOR_SET_BINDINGS;
+ if (m_dirty_flags & DIRTY_FLAG_DESCRIPTOR_SETS)
+ {
+ vkCmdBindDescriptorSets(g_command_buffer_mgr->GetCurrentCommandBuffer(),
+ VK_PIPELINE_BIND_POINT_GRAPHICS, m_pipeline->GetVkPipelineLayout(), 0,
+ g_ActiveConfig.backend_info.bSupportsBBox ?
+ NUM_GX_DESCRIPTOR_SETS :
+ (NUM_GX_DESCRIPTOR_SETS - 1),
+ m_gx_descriptor_sets.data(), NUM_UBO_DESCRIPTOR_SET_BINDINGS,
+ m_bindings.gx_ubo_offsets.data());
+ m_dirty_flags &= ~(DIRTY_FLAG_DESCRIPTOR_SETS | DIRTY_FLAG_GX_UBO_OFFSETS);
+ }
+ else if (m_dirty_flags & DIRTY_FLAG_GX_UBO_OFFSETS)
+ {
+ vkCmdBindDescriptorSets(g_command_buffer_mgr->GetCurrentCommandBuffer(),
+ VK_PIPELINE_BIND_POINT_GRAPHICS, m_pipeline->GetVkPipelineLayout(), 0,
+ 1, m_gx_descriptor_sets.data(), NUM_UBO_DESCRIPTOR_SET_BINDINGS,
+ m_bindings.gx_ubo_offsets.data());
+ m_dirty_flags &= ~DIRTY_FLAG_GX_UBO_OFFSETS;
+ }
+
return true;
}
bool StateTracker::UpdateUtilityDescriptorSet()
{
+ // Max number of updates - UBO, Samplers, TexelBuffer
+ std::array<VkWriteDescriptorSet, 3> dswrites;
+ u32 writes = 0;
+
// Allocate descriptor sets.
- m_descriptor_sets[0] = g_command_buffer_mgr->AllocateDescriptorSet(
- g_object_cache->GetDescriptorSetLayout(DESCRIPTOR_SET_LAYOUT_SINGLE_UNIFORM_BUFFER));
- m_descriptor_sets[1] = g_command_buffer_mgr->AllocateDescriptorSet(
- g_object_cache->GetDescriptorSetLayout(DESCRIPTOR_SET_LAYOUT_PIXEL_SHADER_SAMPLERS));
- if (m_descriptor_sets[0] == VK_NULL_HANDLE || m_descriptor_sets[1] == VK_NULL_HANDLE)
+ if (m_dirty_flags & DIRTY_FLAG_UTILITY_UBO || m_utility_descriptor_sets[0] == VK_NULL_HANDLE)
{
- return false;
+ m_utility_descriptor_sets[0] = g_command_buffer_mgr->AllocateDescriptorSet(
+ g_object_cache->GetDescriptorSetLayout(DESCRIPTOR_SET_LAYOUT_UTILITY_UNIFORM_BUFFER));
+ if (!m_utility_descriptor_sets[0])
+ return false;
+
+ dswrites[writes++] = {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
+ nullptr,
+ m_utility_descriptor_sets[0],
+ 0,
+ 0,
+ 1,
+ VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC,
+ nullptr,
+ &m_bindings.utility_ubo_binding,
+ nullptr};
+
+ m_dirty_flags = (m_dirty_flags & ~DIRTY_FLAG_UTILITY_UBO) | DIRTY_FLAG_DESCRIPTOR_SETS;
+ }
+
+ if (m_dirty_flags & DIRTY_FLAG_UTILITY_BINDINGS || m_utility_descriptor_sets[1] == VK_NULL_HANDLE)
+ {
+ m_utility_descriptor_sets[1] = g_command_buffer_mgr->AllocateDescriptorSet(
+ g_object_cache->GetDescriptorSetLayout(DESCRIPTOR_SET_LAYOUT_UTILITY_SAMPLERS));
+ if (!m_utility_descriptor_sets[1])
+ return false;
+
+ dswrites[writes++] = {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
+ nullptr,
+ m_utility_descriptor_sets[1],
+ 0,
+ 0,
+ NUM_PIXEL_SHADER_SAMPLERS,
+ VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
+ m_bindings.samplers.data(),
+ nullptr,
+ nullptr};
+ dswrites[writes++] = {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
+ nullptr,
+ m_utility_descriptor_sets[1],
+ 8,
+ 0,
+ 1,
+ VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER,
+ nullptr,
+ nullptr,
+ m_bindings.texel_buffers.data()};
+
+ m_dirty_flags = (m_dirty_flags & ~DIRTY_FLAG_UTILITY_BINDINGS) | DIRTY_FLAG_DESCRIPTOR_SETS;
+ }
+
+ if (writes > 0)
+ vkUpdateDescriptorSets(g_vulkan_context->GetDevice(), writes, dswrites.data(), 0, nullptr);
+
+ if (m_dirty_flags & DIRTY_FLAG_DESCRIPTOR_SETS)
+ {
+ vkCmdBindDescriptorSets(g_command_buffer_mgr->GetCurrentCommandBuffer(),
+ VK_PIPELINE_BIND_POINT_GRAPHICS, m_pipeline->GetVkPipelineLayout(), 0,
+ NUM_UTILITY_DESCRIPTOR_SETS, m_utility_descriptor_sets.data(), 1,
+ &m_bindings.utility_ubo_offset);
+ m_dirty_flags &= ~(DIRTY_FLAG_DESCRIPTOR_SETS | DIRTY_FLAG_UTILITY_UBO_OFFSET);
+ }
+ else if (m_dirty_flags & DIRTY_FLAG_UTILITY_UBO_OFFSET)
+ {
+ vkCmdBindDescriptorSets(g_command_buffer_mgr->GetCurrentCommandBuffer(),
+ VK_PIPELINE_BIND_POINT_GRAPHICS, m_pipeline->GetVkPipelineLayout(), 0,
+ 1, m_utility_descriptor_sets.data(), 1, &m_bindings.utility_ubo_offset);
+ m_dirty_flags &= ~(DIRTY_FLAG_DESCRIPTOR_SETS | DIRTY_FLAG_UTILITY_UBO_OFFSET);
+ }
+
+ return true;
+}
+
+bool StateTracker::UpdateComputeDescriptorSet()
+{
+ // Max number of updates - UBO, Samplers, TexelBuffer, Image
+ std::array<VkWriteDescriptorSet, 4> dswrites;
+
+ // Allocate descriptor sets.
+ if (m_dirty_flags & DIRTY_FLAG_COMPUTE_BINDINGS)
+ {
+ m_compute_descriptor_set = g_command_buffer_mgr->AllocateDescriptorSet(
+ g_object_cache->GetDescriptorSetLayout(DESCRIPTOR_SET_LAYOUT_COMPUTE));
+ dswrites[0] = {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
+ nullptr,
+ m_compute_descriptor_set,
+ 0,
+ 0,
+ 1,
+ VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC,
+ nullptr,
+ &m_bindings.utility_ubo_binding,
+ nullptr};
+ dswrites[1] = {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
+ nullptr,
+ m_compute_descriptor_set,
+ 1,
+ 0,
+ NUM_COMPUTE_SHADER_SAMPLERS,
+ VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
+ m_bindings.samplers.data(),
+ nullptr,
+ nullptr};
+ dswrites[2] = {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
+ nullptr,
+ m_compute_descriptor_set,
+ 3,
+ 0,
+ NUM_COMPUTE_TEXEL_BUFFERS,
+ VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER,
+ nullptr,
+ nullptr,
+ m_bindings.texel_buffers.data()};
+ dswrites[3] = {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
+ nullptr,
+ m_compute_descriptor_set,
+ 5,
+ 0,
+ 1,
+ VK_DESCRIPTOR_TYPE_STORAGE_IMAGE,
+ &m_bindings.image_texture,
+ nullptr,
+ nullptr};
+
+ vkUpdateDescriptorSets(g_vulkan_context->GetDevice(), static_cast<uint32_t>(dswrites.size()),
+ dswrites.data(), 0, nullptr);
+ m_dirty_flags =
+ (m_dirty_flags & ~DIRTY_FLAG_COMPUTE_BINDINGS) | DIRTY_FLAG_COMPUTE_DESCRIPTOR_SET;
+ }
+
+ if (m_dirty_flags & DIRTY_FLAG_COMPUTE_DESCRIPTOR_SET)
+ {
+ vkCmdBindDescriptorSets(g_command_buffer_mgr->GetCurrentCommandBuffer(),
+ VK_PIPELINE_BIND_POINT_COMPUTE,
+ g_object_cache->GetPipelineLayout(PIPELINE_LAYOUT_COMPUTE), 0, 1,
+ &m_compute_descriptor_set, 1, &m_bindings.utility_ubo_offset);
+ m_dirty_flags &= ~DIRTY_FLAG_COMPUTE_DESCRIPTOR_SET;
}
- // Build UBO descriptor set.
- std::array<VkWriteDescriptorSet, 2> dswrites;
- dswrites[0] = {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
- nullptr,
- m_descriptor_sets[0],
- 0,
- 0,
- 1,
- VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC,
- nullptr,
- &m_bindings.uniform_buffer_bindings[UBO_DESCRIPTOR_SET_BINDING_VS],
- nullptr};
- dswrites[1] = {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
- nullptr,
- m_descriptor_sets[1],
- 0,
- 0,
- NUM_PIXEL_SHADER_SAMPLERS,
- VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
- m_bindings.ps_samplers.data(),
- nullptr,
- nullptr};
-
- vkUpdateDescriptorSets(g_vulkan_context->GetDevice(), static_cast<uint32_t>(dswrites.size()),
- dswrites.data(), 0, nullptr);
- m_num_active_descriptor_sets = NUM_UTILITY_DRAW_DESCRIPTOR_SETS;
- m_num_dynamic_offsets = 1;
- m_dirty_flags |= DIRTY_FLAG_DESCRIPTOR_SET_BINDING;
return true;
}
diff --git a/Source/Core/VideoBackends/Vulkan/StateTracker.h b/Source/Core/VideoBackends/Vulkan/StateTracker.h
index f4cbc8e180..10e804d69f 100644
--- a/Source/Core/VideoBackends/Vulkan/StateTracker.h
+++ b/Source/Core/VideoBackends/Vulkan/StateTracker.h
@@ -10,64 +10,53 @@
#include "Common/CommonTypes.h"
#include "VideoBackends/Vulkan/Constants.h"
-#include "VideoBackends/Vulkan/ShaderCache.h"
-#include "VideoCommon/NativeVertexFormat.h"
#include "VideoCommon/RenderBase.h"
namespace Vulkan
{
+class VKFramebuffer;
+class VKShader;
class VKPipeline;
+class VKTexture;
class StreamBuffer;
class VertexFormat;
class StateTracker
{
public:
- StateTracker() = default;
- ~StateTracker() = default;
+ StateTracker();
+ ~StateTracker();
static StateTracker* GetInstance();
static bool CreateInstance();
static void DestroyInstance();
- VkFramebuffer GetFramebuffer() const { return m_framebuffer; }
+ VKFramebuffer* GetFramebuffer() const { return m_framebuffer; }
const VKPipeline* GetPipeline() const { return m_pipeline; }
void SetVertexBuffer(VkBuffer buffer, VkDeviceSize offset);
void SetIndexBuffer(VkBuffer buffer, VkDeviceSize offset, VkIndexType type);
-
- void SetRenderPass(VkRenderPass load_render_pass, VkRenderPass clear_render_pass);
- void SetFramebuffer(VkFramebuffer framebuffer, const VkRect2D& render_area);
+ void SetFramebuffer(VKFramebuffer* framebuffer);
void SetPipeline(const VKPipeline* pipeline);
-
- void UpdateVertexShaderConstants();
- void UpdateGeometryShaderConstants();
- void UpdatePixelShaderConstants();
-
- // Updates constants from external data, e.g. utility draws.
- void UpdateConstants(const void* data, u32 data_size);
-
- void SetTexture(size_t index, VkImageView view);
- void SetSampler(size_t index, VkSampler sampler);
-
- void SetBBoxBuffer(VkBuffer buffer, VkDeviceSize offset, VkDeviceSize range);
+ void SetComputeShader(const VKShader* shader);
+ void SetGXUniformBuffer(u32 index, VkBuffer buffer, u32 offset, u32 size);
+ void SetUtilityUniformBuffer(VkBuffer buffer, u32 offset, u32 size);
+ void SetTexture(u32 index, VkImageView view);
+ void SetSampler(u32 index, VkSampler sampler);
+ void SetSSBO(VkBuffer buffer, VkDeviceSize offset, VkDeviceSize range);
+ void SetTexelBuffer(u32 index, VkBufferView view);
+ void SetImageTexture(VkImageView view);
void UnbindTexture(VkImageView view);
- // When executing a command buffer, we want to recreate the descriptor set, as it will
- // now be in a different pool for the new command buffer.
- void InvalidateDescriptorSets();
-
- // Same with the uniforms, as the current storage will belong to the previous command buffer.
- void InvalidateConstants();
-
// Set dirty flags on everything to force re-bind at next draw time.
- void SetPendingRebind();
+ void InvalidateCachedState();
// Ends a render pass if we're currently in one.
// When Bind() is next called, the pass will be restarted.
// Calling this function is allowed even if a pass has not begun.
bool InRenderPass() const { return m_current_render_pass != VK_NULL_HANDLE; }
void BeginRenderPass();
+ void BeginDiscardRenderPass();
void EndRenderPass();
// Ends the current render pass if it was a clear render pass.
@@ -78,53 +67,48 @@ public:
void SetViewport(const VkViewport& viewport);
void SetScissor(const VkRect2D& scissor);
- bool Bind(bool rebind_all = false);
-
- // CPU Access Tracking
- // Call after a draw call is made.
- void OnDraw();
+ // Binds all dirty state to the commmand buffer.
+ // If this returns false, you should not issue the draw.
+ bool Bind();
- // Call after CPU access is requested.
- void OnCPUEFBAccess();
-
- // Call after an EFB copy to RAM. If true, the current command buffer should be executed.
- void OnEFBCopyToRAM();
-
- // Call at the end of a frame.
- void OnEndFrame();
-
- // Prevent/allow background command buffer execution.
- // Use when queries are active.
- void SetBackgroundCommandBufferExecution(bool enabled);
+ // Binds all dirty compute state to the command buffer.
+ // If this returns false, you should not dispatch the shader.
+ bool BindCompute();
+ // Returns true if the specified rectangle is inside the current render area (used for clears).
bool IsWithinRenderArea(s32 x, s32 y, u32 width, u32 height) const;
private:
// Number of descriptor sets for game draws.
enum
{
- NUM_GX_DRAW_DESCRIPTOR_SETS = DESCRIPTOR_SET_BIND_POINT_PIXEL_SHADER_SAMPLERS + 1,
- NUM_GX_DRAW_DESCRIPTOR_SETS_SSBO = DESCRIPTOR_SET_BIND_POINT_STORAGE_OR_TEXEL_BUFFER + 1,
- NUM_UTILITY_DRAW_DESCRIPTOR_SETS = 2
+ NUM_GX_DESCRIPTOR_SETS = 3,
+ NUM_UTILITY_DESCRIPTOR_SETS = 2,
+ NUM_COMPUTE_DESCRIPTOR_SETS = 1
};
- enum DITRY_FLAG : u32
+ enum DIRTY_FLAG : u32
{
- DIRTY_FLAG_VS_UBO = (1 << 0),
- DIRTY_FLAG_GS_UBO = (1 << 1),
- DIRTY_FLAG_PS_UBO = (1 << 2),
- DIRTY_FLAG_PS_SAMPLERS = (1 << 3),
- DIRTY_FLAG_PS_SSBO = (1 << 4),
- DIRTY_FLAG_DYNAMIC_OFFSETS = (1 << 5),
- DIRTY_FLAG_VERTEX_BUFFER = (1 << 6),
- DIRTY_FLAG_INDEX_BUFFER = (1 << 7),
- DIRTY_FLAG_VIEWPORT = (1 << 8),
- DIRTY_FLAG_SCISSOR = (1 << 9),
- DIRTY_FLAG_PIPELINE = (1 << 10),
- DIRTY_FLAG_DESCRIPTOR_SET_BINDING = (1 << 11),
-
- DIRTY_FLAG_ALL_DESCRIPTOR_SETS = DIRTY_FLAG_VS_UBO | DIRTY_FLAG_GS_UBO | DIRTY_FLAG_PS_UBO |
- DIRTY_FLAG_PS_SAMPLERS | DIRTY_FLAG_PS_SSBO
+ DIRTY_FLAG_GX_UBOS = (1 << 0),
+ DIRTY_FLAG_GX_UBO_OFFSETS = (1 << 1),
+ DIRTY_FLAG_GX_SAMPLERS = (1 << 4),
+ DIRTY_FLAG_GX_SSBO = (1 << 5),
+ DIRTY_FLAG_UTILITY_UBO = (1 << 2),
+ DIRTY_FLAG_UTILITY_UBO_OFFSET = (1 << 3),
+ DIRTY_FLAG_UTILITY_BINDINGS = (1 << 6),
+ DIRTY_FLAG_COMPUTE_BINDINGS = (1 << 7),
+ DIRTY_FLAG_VERTEX_BUFFER = (1 << 8),
+ DIRTY_FLAG_INDEX_BUFFER = (1 << 9),
+ DIRTY_FLAG_VIEWPORT = (1 << 10),
+ DIRTY_FLAG_SCISSOR = (1 << 11),
+ DIRTY_FLAG_PIPELINE = (1 << 12),
+ DIRTY_FLAG_COMPUTE_SHADER = (1 << 13),
+ DIRTY_FLAG_DESCRIPTOR_SETS = (1 << 14),
+ DIRTY_FLAG_COMPUTE_DESCRIPTOR_SET = (1 << 15),
+
+ DIRTY_FLAG_ALL_DESCRIPTORS = DIRTY_FLAG_GX_UBOS | DIRTY_FLAG_UTILITY_UBO |
+ DIRTY_FLAG_GX_SAMPLERS | DIRTY_FLAG_GX_SSBO |
+ DIRTY_FLAG_UTILITY_BINDINGS | DIRTY_FLAG_COMPUTE_BINDINGS
};
bool Initialize();
@@ -136,12 +120,7 @@ private:
bool UpdateDescriptorSet();
bool UpdateGXDescriptorSet();
bool UpdateUtilityDescriptorSet();
-
- // Allocates storage in the uniform buffer of the specified size. If this storage cannot be
- // allocated immediately, the current command buffer will be submitted and all stage's
- // constants will be re-uploaded. false will be returned in this case, otherwise true.
- bool ReserveConstantStorage();
- void UploadAllConstants();
+ bool UpdateComputeDescriptorSet();
// Which bindings/state has to be updated before the next draw.
u32 m_dirty_flags = 0;
@@ -155,42 +134,33 @@ private:
// pipeline state
const VKPipeline* m_pipeline = nullptr;
+ const VKShader* m_compute_shader = nullptr;
// shader bindings
- std::array<VkDescriptorSet, NUM_DESCRIPTOR_SET_BIND_POINTS> m_descriptor_sets = {};
struct
{
- std::array<VkDescriptorBufferInfo, NUM_UBO_DESCRIPTOR_SET_BINDINGS> uniform_buffer_bindings =
- {};
- std::array<uint32_t, NUM_UBO_DESCRIPTOR_SET_BINDINGS> uniform_buffer_offsets = {};
-
- std::array<VkDescriptorImageInfo, NUM_PIXEL_SHADER_SAMPLERS> ps_samplers = {};
-
- VkDescriptorBufferInfo ps_ssbo = {};
- } m_bindings;
- size_t m_uniform_buffer_reserve_size = 0;
- u32 m_num_active_descriptor_sets = 0;
- u32 m_num_dynamic_offsets = 0;
+ std::array<VkDescriptorBufferInfo, NUM_UBO_DESCRIPTOR_SET_BINDINGS> gx_ubo_bindings;
+ std::array<u32, NUM_UBO_DESCRIPTOR_SET_BINDINGS> gx_ubo_offsets;
+ VkDescriptorBufferInfo utility_ubo_binding;
+ u32 utility_ubo_offset;
+ std::array<VkDescriptorImageInfo, NUM_PIXEL_SHADER_SAMPLERS> samplers;
+ std::array<VkBufferView, NUM_COMPUTE_TEXEL_BUFFERS> texel_buffers;
+ VkDescriptorBufferInfo ssbo;
+ VkDescriptorImageInfo image_texture;
+ } m_bindings = {};
+ std::array<VkDescriptorSet, NUM_GX_DESCRIPTOR_SETS> m_gx_descriptor_sets = {};
+ std::array<VkDescriptorSet, NUM_UTILITY_DESCRIPTOR_SETS> m_utility_descriptor_sets = {};
+ VkDescriptorSet m_compute_descriptor_set = VK_NULL_HANDLE;
// rasterization
VkViewport m_viewport = {0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f};
VkRect2D m_scissor = {{0, 0}, {1, 1}};
// uniform buffers
- std::unique_ptr<StreamBuffer> m_uniform_stream_buffer;
+ std::unique_ptr<VKTexture> m_dummy_texture;
- VkFramebuffer m_framebuffer = VK_NULL_HANDLE;
- VkRenderPass m_load_render_pass = VK_NULL_HANDLE;
- VkRenderPass m_clear_render_pass = VK_NULL_HANDLE;
+ VKFramebuffer* m_framebuffer = nullptr;
VkRenderPass m_current_render_pass = VK_NULL_HANDLE;
- VkRect2D m_framebuffer_size = {};
VkRect2D m_framebuffer_render_area = {};
-
- // CPU access tracking
- u32 m_draw_counter = 0;
- u32 m_last_efb_copy_draw_counter = 0;
- std::vector<u32> m_cpu_accesses_this_frame;
- std::vector<u32> m_scheduled_command_buffer_kicks;
- bool m_allow_background_execution = true;
};
} // namespace Vulkan
diff --git a/Source/Core/VideoBackends/Vulkan/StreamBuffer.cpp b/Source/Core/VideoBackends/Vulkan/StreamBuffer.cpp
index cb8e660af2..ea610f09cf 100644
--- a/Source/Core/VideoBackends/Vulkan/StreamBuffer.cpp
+++ b/Source/Core/VideoBackends/Vulkan/StreamBuffer.cpp
@@ -8,29 +8,24 @@
#include <cstdint>
#include <functional>
+#include "Common/Align.h"
#include "Common/Assert.h"
#include "Common/MsgHandler.h"
#include "VideoBackends/Vulkan/CommandBufferManager.h"
-#include "VideoBackends/Vulkan/Util.h"
#include "VideoBackends/Vulkan/VulkanContext.h"
namespace Vulkan
{
-StreamBuffer::StreamBuffer(VkBufferUsageFlags usage, size_t max_size)
- : m_usage(usage), m_maximum_size(max_size)
+StreamBuffer::StreamBuffer(VkBufferUsageFlags usage, u32 size) : m_usage(usage), m_size(size)
{
- // Add a callback that fires on fence point creation and signal
- g_command_buffer_mgr->AddFencePointCallback(
- this,
- std::bind(&StreamBuffer::OnCommandBufferQueued, this, std::placeholders::_1,
- std::placeholders::_2),
- std::bind(&StreamBuffer::OnCommandBufferExecuted, this, std::placeholders::_1));
+ g_command_buffer_mgr->AddFenceSignaledCallback(
+ this, std::bind(&StreamBuffer::OnFenceSignaled, this, std::placeholders::_1));
}
StreamBuffer::~StreamBuffer()
{
- g_command_buffer_mgr->RemoveFencePointCallback(this);
+ g_command_buffer_mgr->RemoveFenceSignaledCallback(this);
if (m_host_pointer)
vkUnmapMemory(g_vulkan_context->GetDevice(), m_memory);
@@ -41,24 +36,23 @@ StreamBuffer::~StreamBuffer()
g_command_buffer_mgr->DeferDeviceMemoryDestruction(m_memory);
}
-std::unique_ptr<StreamBuffer> StreamBuffer::Create(VkBufferUsageFlags usage, size_t initial_size,
- size_t max_size)
+std::unique_ptr<StreamBuffer> StreamBuffer::Create(VkBufferUsageFlags usage, u32 size)
{
- std::unique_ptr<StreamBuffer> buffer = std::make_unique<StreamBuffer>(usage, max_size);
- if (!buffer->ResizeBuffer(initial_size))
+ std::unique_ptr<StreamBuffer> buffer = std::make_unique<StreamBuffer>(usage, size);
+ if (!buffer->AllocateBuffer())
return nullptr;
return buffer;
}
-bool StreamBuffer::ResizeBuffer(size_t size)
+bool StreamBuffer::AllocateBuffer()
{
// Create the buffer descriptor
VkBufferCreateInfo buffer_create_info = {
VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, // VkStructureType sType
nullptr, // const void* pNext
0, // VkBufferCreateFlags flags
- static_cast<VkDeviceSize>(size), // VkDeviceSize size
+ static_cast<VkDeviceSize>(m_size), // VkDeviceSize size
m_usage, // VkBufferUsageFlags usage
VK_SHARING_MODE_EXCLUSIVE, // VkSharingMode sharingMode
0, // uint32_t queueFamilyIndexCount
@@ -110,7 +104,7 @@ bool StreamBuffer::ResizeBuffer(size_t size)
// Map this buffer into user-space
void* mapped_ptr = nullptr;
- res = vkMapMemory(g_vulkan_context->GetDevice(), memory, 0, size, 0, &mapped_ptr);
+ res = vkMapMemory(g_vulkan_context->GetDevice(), memory, 0, m_size, 0, &mapped_ptr);
if (res != VK_SUCCESS)
{
LOG_VULKAN_ERROR(res, "vkMapMemory failed: ");
@@ -133,36 +127,34 @@ bool StreamBuffer::ResizeBuffer(size_t size)
m_buffer = buffer;
m_memory = memory;
m_host_pointer = reinterpret_cast<u8*>(mapped_ptr);
- m_current_size = size;
m_current_offset = 0;
m_current_gpu_position = 0;
m_tracked_fences.clear();
return true;
}
-bool StreamBuffer::ReserveMemory(size_t num_bytes, size_t alignment, bool allow_reuse /* = true */,
- bool allow_growth /* = true */,
- bool reallocate_if_full /* = false */)
+bool StreamBuffer::ReserveMemory(u32 num_bytes, u32 alignment)
{
- size_t required_bytes = num_bytes + alignment;
+ const u32 required_bytes = num_bytes + alignment;
// Check for sane allocations
- if (required_bytes > m_maximum_size)
+ if (required_bytes > m_size)
{
PanicAlert("Attempting to allocate %u bytes from a %u byte stream buffer",
- static_cast<uint32_t>(num_bytes), static_cast<uint32_t>(m_maximum_size));
+ static_cast<uint32_t>(num_bytes), static_cast<uint32_t>(m_size));
return false;
}
// Is the GPU behind or up to date with our current offset?
+ UpdateCurrentFencePosition();
if (m_current_offset >= m_current_gpu_position)
{
- size_t remaining_bytes = m_current_size - m_current_offset;
+ const u32 remaining_bytes = m_size - m_current_offset;
if (required_bytes <= remaining_bytes)
{
// Place at the current position, after the GPU position.
- m_current_offset = Util::AlignBufferOffset(m_current_offset, alignment);
+ m_current_offset = Common::AlignUp(m_current_offset, alignment);
m_last_allocation_size = num_bytes;
return true;
}
@@ -171,7 +163,7 @@ bool StreamBuffer::ReserveMemory(size_t num_bytes, size_t alignment, bool allow_
// We use < here because we don't want to have the case of m_current_offset ==
// m_current_gpu_position. That would mean the code above would assume the
// GPU has caught up to us, which it hasn't.
- if (allow_reuse && required_bytes < m_current_gpu_position)
+ if (required_bytes < m_current_gpu_position)
{
// Reset offset to zero, since we're allocating behind the gpu now
m_current_offset = 0;
@@ -184,56 +176,35 @@ bool StreamBuffer::ReserveMemory(size_t num_bytes, size_t alignment, bool allow_
if (m_current_offset < m_current_gpu_position)
{
// We have from m_current_offset..m_current_gpu_position space to use.
- size_t remaining_bytes = m_current_gpu_position - m_current_offset;
+ const u32 remaining_bytes = m_current_gpu_position - m_current_offset;
if (required_bytes < remaining_bytes)
{
// Place at the current position, since this is still behind the GPU.
- m_current_offset = Util::AlignBufferOffset(m_current_offset, alignment);
+ m_current_offset = Common::AlignUp(m_current_offset, alignment);
m_last_allocation_size = num_bytes;
return true;
}
}
- // Try to grow the buffer up to the maximum size before waiting.
- // Double each time until the maximum size is reached.
- if (allow_growth && m_current_size < m_maximum_size)
- {
- size_t new_size = std::min(std::max(num_bytes, m_current_size * 2), m_maximum_size);
- if (ResizeBuffer(new_size))
- {
- // Allocating from the start of the buffer.
- m_last_allocation_size = new_size;
- return true;
- }
- }
-
// Can we find a fence to wait on that will give us enough memory?
- if (allow_reuse && WaitForClearSpace(required_bytes))
+ if (WaitForClearSpace(required_bytes))
{
ASSERT(m_current_offset == m_current_gpu_position ||
(m_current_offset + required_bytes) < m_current_gpu_position);
- m_current_offset = Util::AlignBufferOffset(m_current_offset, alignment);
- m_last_allocation_size = num_bytes;
- return true;
- }
-
- // If we are not allowed to execute in our current state (e.g. in the middle of a render pass),
- // as a last resort, reallocate the buffer. This will incur a performance hit and is not
- // encouraged.
- if (reallocate_if_full && ResizeBuffer(m_current_size))
- {
+ m_current_offset = Common::AlignUp(m_current_offset, alignment);
m_last_allocation_size = num_bytes;
return true;
}
- // We tried everything we could, and still couldn't get anything. If we're not at a point
- // where the state is known and can be resumed, this is probably a fatal error.
+ // We tried everything we could, and still couldn't get anything. This means that too much space
+ // in the buffer is being used by the command buffer currently being recorded. Therefore, the
+ // only option is to execute it, and wait until it's done.
return false;
}
-void StreamBuffer::CommitMemory(size_t final_num_bytes)
+void StreamBuffer::CommitMemory(u32 final_num_bytes)
{
- ASSERT((m_current_offset + final_num_bytes) <= m_current_size);
+ ASSERT((m_current_offset + final_num_bytes) <= m_size);
ASSERT(final_num_bytes <= m_last_allocation_size);
// For non-coherent mappings, flush the memory range
@@ -247,23 +218,25 @@ void StreamBuffer::CommitMemory(size_t final_num_bytes)
m_current_offset += final_num_bytes;
}
-void StreamBuffer::OnCommandBufferQueued(VkCommandBuffer command_buffer, VkFence fence)
+void StreamBuffer::UpdateCurrentFencePosition()
{
// Don't create a tracking entry if the GPU is caught up with the buffer.
if (m_current_offset == m_current_gpu_position)
return;
// Has the offset changed since the last fence?
- if (!m_tracked_fences.empty() && m_tracked_fences.back().second == m_current_offset)
+ const VkFence fence = g_command_buffer_mgr->GetCurrentCommandBufferFence();
+ if (!m_tracked_fences.empty() && m_tracked_fences.back().first == fence)
{
- // No need to track the new fence, the old one is sufficient.
+ // Still haven't executed a command buffer, so just update the offset.
+ m_tracked_fences.back().second = m_current_offset;
return;
}
m_tracked_fences.emplace_back(fence, m_current_offset);
}
-void StreamBuffer::OnCommandBufferExecuted(VkFence fence)
+void StreamBuffer::OnFenceSignaled(VkFence fence)
{
// Locate the entry for this fence (if any, we may have been forced to wait already)
auto iter = std::find_if(m_tracked_fences.begin(), m_tracked_fences.end(),
@@ -279,10 +252,9 @@ void StreamBuffer::OnCommandBufferExecuted(VkFence fence)
}
}
-bool StreamBuffer::WaitForClearSpace(size_t num_bytes)
+bool StreamBuffer::WaitForClearSpace(u32 num_bytes)
{
- size_t new_offset = 0;
- size_t new_gpu_position = 0;
+ u32 new_offset = 0;
auto iter = m_tracked_fences.begin();
for (; iter != m_tracked_fences.end(); iter++)
{
@@ -290,12 +262,11 @@ bool StreamBuffer::WaitForClearSpace(size_t num_bytes)
// This is the "last resort" case, where a command buffer execution has been forced
// after no additional data has been written to it, so we can assume that after the
// fence has been signaled the entire buffer is now consumed.
- size_t gpu_position = iter->second;
+ u32 gpu_position = iter->second;
if (m_current_offset == gpu_position)
{
// Start at the start of the buffer again.
new_offset = 0;
- new_gpu_position = 0;
break;
}
@@ -308,7 +279,6 @@ bool StreamBuffer::WaitForClearSpace(size_t num_bytes)
if (gpu_position > num_bytes)
{
new_offset = 0;
- new_gpu_position = gpu_position;
break;
}
}
@@ -317,31 +287,27 @@ bool StreamBuffer::WaitForClearSpace(size_t num_bytes)
// We're currently allocating behind the GPU. This would give us between the current
// offset and the GPU position worth of space to work with. Again, > because we can't
// align the GPU position with the buffer offset.
- size_t available_space_inbetween = gpu_position - m_current_offset;
+ u32 available_space_inbetween = gpu_position - m_current_offset;
if (available_space_inbetween > num_bytes)
{
// Leave the offset as-is, but update the GPU position.
new_offset = m_current_offset;
- new_gpu_position = gpu_position;
break;
}
}
}
// Did any fences satisfy this condition?
- if (iter == m_tracked_fences.end())
+ // Has the command buffer been executed yet? If not, the caller should execute it.
+ if (iter == m_tracked_fences.end() ||
+ iter->first == g_command_buffer_mgr->GetCurrentCommandBufferFence())
+ {
return false;
+ }
- // Wait until this fence is signaled.
- VkResult res =
- vkWaitForFences(g_vulkan_context->GetDevice(), 1, &iter->first, VK_TRUE, UINT64_MAX);
- if (res != VK_SUCCESS)
- LOG_VULKAN_ERROR(res, "vkWaitForFences failed: ");
-
- // Update GPU position, and remove all fences up to (and including) this fence.
+ // Wait until this fence is signaled. This will fire the callback, updating the GPU position.
+ g_command_buffer_mgr->WaitForFence(iter->first);
m_current_offset = new_offset;
- m_current_gpu_position = new_gpu_position;
- m_tracked_fences.erase(m_tracked_fences.begin(), ++iter);
return true;
}
diff --git a/Source/Core/VideoBackends/Vulkan/StreamBuffer.h b/Source/Core/VideoBackends/Vulkan/StreamBuffer.h
index ce1b02164f..b52ce6cd35 100644
--- a/Source/Core/VideoBackends/Vulkan/StreamBuffer.h
+++ b/Source/Core/VideoBackends/Vulkan/StreamBuffer.h
@@ -17,43 +17,40 @@ namespace Vulkan
class StreamBuffer
{
public:
- StreamBuffer(VkBufferUsageFlags usage, size_t max_size);
+ StreamBuffer(VkBufferUsageFlags usage, u32 size);
~StreamBuffer();
VkBuffer GetBuffer() const { return m_buffer; }
VkDeviceMemory GetDeviceMemory() const { return m_memory; }
u8* GetHostPointer() const { return m_host_pointer; }
u8* GetCurrentHostPointer() const { return m_host_pointer + m_current_offset; }
- size_t GetCurrentSize() const { return m_current_size; }
- size_t GetCurrentOffset() const { return m_current_offset; }
- bool ReserveMemory(size_t num_bytes, size_t alignment, bool allow_reuse = true,
- bool allow_growth = true, bool reallocate_if_full = false);
- void CommitMemory(size_t final_num_bytes);
+ u32 GetCurrentSize() const { return m_size; }
+ u32 GetCurrentOffset() const { return m_current_offset; }
+ bool ReserveMemory(u32 num_bytes, u32 alignment);
+ void CommitMemory(u32 final_num_bytes);
- static std::unique_ptr<StreamBuffer> Create(VkBufferUsageFlags usage, size_t initial_size,
- size_t max_size);
+ static std::unique_ptr<StreamBuffer> Create(VkBufferUsageFlags usage, u32 size);
private:
- bool ResizeBuffer(size_t size);
- void OnCommandBufferQueued(VkCommandBuffer command_buffer, VkFence fence);
- void OnCommandBufferExecuted(VkFence fence);
+ bool AllocateBuffer();
+ void UpdateCurrentFencePosition();
+ void OnFenceSignaled(VkFence fence);
// Waits for as many fences as needed to allocate num_bytes bytes from the buffer.
- bool WaitForClearSpace(size_t num_bytes);
+ bool WaitForClearSpace(u32 num_bytes);
VkBufferUsageFlags m_usage;
- size_t m_current_size = 0;
- size_t m_maximum_size;
- size_t m_current_offset = 0;
- size_t m_current_gpu_position = 0;
- size_t m_last_allocation_size = 0;
+ u32 m_size;
+ u32 m_current_offset = 0;
+ u32 m_current_gpu_position = 0;
+ u32 m_last_allocation_size = 0;
VkBuffer m_buffer = VK_NULL_HANDLE;
VkDeviceMemory m_memory = VK_NULL_HANDLE;
u8* m_host_pointer = nullptr;
// List of fences and the corresponding positions in the buffer
- std::deque<std::pair<VkFence, size_t>> m_tracked_fences;
+ std::deque<std::pair<VkFence, u32>> m_tracked_fences;
bool m_coherent_mapping = false;
};
diff --git a/Source/Core/VideoBackends/Vulkan/SwapChain.cpp b/Source/Core/VideoBackends/Vulkan/SwapChain.cpp
index 94cd0ade67..ee53005b93 100644
--- a/Source/Core/VideoBackends/Vulkan/SwapChain.cpp
+++ b/Source/Core/VideoBackends/Vulkan/SwapChain.cpp
@@ -13,6 +13,8 @@
#include "Common/MsgHandler.h"
#include "VideoBackends/Vulkan/CommandBufferManager.h"
+#include "VideoBackends/Vulkan/ObjectCache.h"
+#include "VideoBackends/Vulkan/VKTexture.h"
#include "VideoBackends/Vulkan/VulkanContext.h"
#include "VideoCommon/RenderBase.h"
@@ -32,7 +34,6 @@ SwapChain::~SwapChain()
DestroySwapChainImages();
DestroySwapChain();
DestroySurface();
- DestroySemaphores();
}
VkSurfaceKHR SwapChain::CreateVulkanSurface(VkInstance instance, const WindowSystemInfo& wsi)
@@ -130,53 +131,12 @@ std::unique_ptr<SwapChain> SwapChain::Create(const WindowSystemInfo& wsi, VkSurf
bool vsync)
{
std::unique_ptr<SwapChain> swap_chain = std::make_unique<SwapChain>(wsi, surface, vsync);
- if (!swap_chain->CreateSemaphores() || !swap_chain->CreateSwapChain() ||
- !swap_chain->SetupSwapChainImages())
- {
+ if (!swap_chain->CreateSwapChain() || !swap_chain->SetupSwapChainImages())
return nullptr;
- }
return swap_chain;
}
-bool SwapChain::CreateSemaphores()
-{
- // Create two semaphores, one that is triggered when the swapchain buffer is ready, another after
- // submit and before present
- VkSemaphoreCreateInfo semaphore_info = {
- VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, // VkStructureType sType
- nullptr, // const void* pNext
- 0 // VkSemaphoreCreateFlags flags
- };
-
- VkResult res;
- if ((res = vkCreateSemaphore(g_vulkan_context->GetDevice(), &semaphore_info, nullptr,
- &m_image_available_semaphore)) != VK_SUCCESS ||
- (res = vkCreateSemaphore(g_vulkan_context->GetDevice(), &semaphore_info, nullptr,
- &m_rendering_finished_semaphore)) != VK_SUCCESS)
- {
- LOG_VULKAN_ERROR(res, "vkCreateSemaphore failed: ");
- return false;
- }
-
- return true;
-}
-
-void SwapChain::DestroySemaphores()
-{
- if (m_image_available_semaphore)
- {
- vkDestroySemaphore(g_vulkan_context->GetDevice(), m_image_available_semaphore, nullptr);
- m_image_available_semaphore = VK_NULL_HANDLE;
- }
-
- if (m_rendering_finished_semaphore)
- {
- vkDestroySemaphore(g_vulkan_context->GetDevice(), m_rendering_finished_semaphore, nullptr);
- m_rendering_finished_semaphore = VK_NULL_HANDLE;
- }
-}
-
bool SwapChain::SelectSurfaceFormat()
{
u32 format_count;
@@ -207,7 +167,7 @@ bool SwapChain::SelectSurfaceFormat()
// Some drivers seem to return a SRGB format here (Intel Mesa).
// This results in gamma correction when presenting to the screen, which we don't want.
// Use a linear format instead, if this is the case.
- VkFormat format = Util::GetLinearFormat(surface_format.format);
+ VkFormat format = VKTexture::GetLinearFormat(surface_format.format);
if (format == VK_FORMAT_R8G8B8A8_UNORM)
m_texture_format = AbstractTextureFormat::RGBA8;
else if (format == VK_FORMAT_B8G8R8A8_UNORM)
@@ -399,11 +359,13 @@ bool SwapChain::SetupSwapChainImages()
images.data());
ASSERT(res == VK_SUCCESS);
- m_render_pass = g_object_cache->GetRenderPass(m_surface_format.format, VK_FORMAT_UNDEFINED, 1,
- VK_ATTACHMENT_LOAD_OP_LOAD);
- m_clear_render_pass = g_object_cache->GetRenderPass(m_surface_format.format, VK_FORMAT_UNDEFINED,
- 1, VK_ATTACHMENT_LOAD_OP_CLEAR);
- if (m_render_pass == VK_NULL_HANDLE || m_clear_render_pass == VK_NULL_HANDLE)
+ const TextureConfig texture_config(TextureConfig(
+ m_width, m_height, 1, m_layers, 1, m_texture_format, AbstractTextureFlag_RenderTarget));
+ const VkRenderPass load_render_pass = g_object_cache->GetRenderPass(
+ m_surface_format.format, VK_FORMAT_UNDEFINED, 1, VK_ATTACHMENT_LOAD_OP_LOAD);
+ const VkRenderPass clear_render_pass = g_object_cache->GetRenderPass(
+ m_surface_format.format, VK_FORMAT_UNDEFINED, 1, VK_ATTACHMENT_LOAD_OP_CLEAR);
+ if (load_render_pass == VK_NULL_HANDLE || clear_render_pass == VK_NULL_HANDLE)
{
PanicAlert("Failed to get swap chain render passes.");
return false;
@@ -416,26 +378,17 @@ bool SwapChain::SetupSwapChainImages()
image.image = images[i];
// Create texture object, which creates a view of the backbuffer
- image.texture = Texture2D::CreateFromExistingImage(
- m_width, m_height, 1, 1, m_surface_format.format, VK_SAMPLE_COUNT_1_BIT,
- VK_IMAGE_VIEW_TYPE_2D, image.image);
-
- VkImageView view = image.texture->GetView();
- VkFramebufferCreateInfo framebuffer_info = {VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO,
- nullptr,
- 0,
- m_render_pass,
- 1,
- &view,
- m_width,
- m_height,
- m_layers};
-
- res = vkCreateFramebuffer(g_vulkan_context->GetDevice(), &framebuffer_info, nullptr,
- &image.framebuffer);
- if (res != VK_SUCCESS)
+ image.texture =
+ VKTexture::CreateAdopted(texture_config, image.image,
+ m_layers > 1 ? VK_IMAGE_VIEW_TYPE_2D_ARRAY : VK_IMAGE_VIEW_TYPE_2D,
+ VK_IMAGE_LAYOUT_UNDEFINED);
+ if (!image.texture)
+ return false;
+
+ image.framebuffer = VKFramebuffer::Create(image.texture.get(), nullptr);
+ if (!image.framebuffer)
{
- LOG_VULKAN_ERROR(res, "vkCreateFramebuffer failed: ");
+ image.texture.reset();
return false;
}
@@ -447,10 +400,11 @@ bool SwapChain::SetupSwapChainImages()
void SwapChain::DestroySwapChainImages()
{
- for (const auto& it : m_swap_chain_images)
+ for (auto& it : m_swap_chain_images)
{
// Images themselves are cleaned up by the swap chain object
- vkDestroyFramebuffer(g_vulkan_context->GetDevice(), it.framebuffer, nullptr);
+ it.framebuffer.reset();
+ it.texture.reset();
}
m_swap_chain_images.clear();
}
@@ -467,8 +421,8 @@ void SwapChain::DestroySwapChain()
VkResult SwapChain::AcquireNextImage()
{
VkResult res = vkAcquireNextImageKHR(g_vulkan_context->GetDevice(), m_swap_chain, UINT64_MAX,
- m_image_available_semaphore, VK_NULL_HANDLE,
- &m_current_swap_chain_image_index);
+ g_command_buffer_mgr->GetCurrentCommandBufferSemaphore(),
+ VK_NULL_HANDLE, &m_current_swap_chain_image_index);
if (res != VK_SUCCESS && res != VK_ERROR_OUT_OF_DATE_KHR && res != VK_SUBOPTIMAL_KHR)
LOG_VULKAN_ERROR(res, "vkAcquireNextImageKHR failed: ");
diff --git a/Source/Core/VideoBackends/Vulkan/SwapChain.h b/Source/Core/VideoBackends/Vulkan/SwapChain.h
index 0687249acd..4359f4663c 100644
--- a/Source/Core/VideoBackends/Vulkan/SwapChain.h
+++ b/Source/Core/VideoBackends/Vulkan/SwapChain.h
@@ -10,13 +10,14 @@
#include "Common/CommonTypes.h"
#include "Common/WindowSystemInfo.h"
#include "VideoBackends/Vulkan/Constants.h"
-#include "VideoBackends/Vulkan/Texture2D.h"
#include "VideoCommon/TextureConfig.h"
namespace Vulkan
{
class CommandBufferManager;
class ObjectCache;
+class VKTexture;
+class VKFramebuffer;
class SwapChain
{
@@ -44,19 +45,14 @@ public:
{
return m_swap_chain_images[m_current_swap_chain_image_index].image;
}
- Texture2D* GetCurrentTexture() const
+ VKTexture* GetCurrentTexture() const
{
return m_swap_chain_images[m_current_swap_chain_image_index].texture.get();
}
- VkFramebuffer GetCurrentFramebuffer() const
+ VKFramebuffer* GetCurrentFramebuffer() const
{
- return m_swap_chain_images[m_current_swap_chain_image_index].framebuffer;
+ return m_swap_chain_images[m_current_swap_chain_image_index].framebuffer.get();
}
- VkRenderPass GetLoadRenderPass() const { return m_render_pass; }
- VkRenderPass GetClearRenderPass() const { return m_clear_render_pass; }
- VkSemaphore GetImageAvailableSemaphore() const { return m_image_available_semaphore; }
- VkSemaphore GetRenderingFinishedSemaphore() const { return m_rendering_finished_semaphore; }
-
VkResult AcquireNextImage();
bool RecreateSurface(void* native_handle);
@@ -67,9 +63,6 @@ public:
bool SetVSync(bool enabled);
private:
- bool CreateSemaphores();
- void DestroySemaphores();
-
bool SelectSurfaceFormat();
bool SelectPresentMode();
@@ -84,8 +77,8 @@ private:
struct SwapChainImage
{
VkImage image;
- std::unique_ptr<Texture2D> texture;
- VkFramebuffer framebuffer;
+ std::unique_ptr<VKTexture> texture;
+ std::unique_ptr<VKFramebuffer> framebuffer;
};
WindowSystemInfo m_wsi;
@@ -99,12 +92,6 @@ private:
std::vector<SwapChainImage> m_swap_chain_images;
u32 m_current_swap_chain_image_index = 0;
- VkSemaphore m_image_available_semaphore = VK_NULL_HANDLE;
- VkSemaphore m_rendering_finished_semaphore = VK_NULL_HANDLE;
-
- VkRenderPass m_render_pass = VK_NULL_HANDLE;
- VkRenderPass m_clear_render_pass = VK_NULL_HANDLE;
-
u32 m_width = 0;
u32 m_height = 0;
u32 m_layers = 0;
diff --git a/Source/Core/VideoBackends/Vulkan/Texture2D.cpp b/Source/Core/VideoBackends/Vulkan/Texture2D.cpp
deleted file mode 100644
index 96bfba6538..0000000000
--- a/Source/Core/VideoBackends/Vulkan/Texture2D.cpp
+++ /dev/null
@@ -1,404 +0,0 @@
-// Copyright 2016 Dolphin Emulator Project
-// Licensed under GPLv2+
-// Refer to the license.txt file included.
-
-#include <algorithm>
-
-#include "Common/Assert.h"
-#include "VideoBackends/Vulkan/CommandBufferManager.h"
-#include "VideoBackends/Vulkan/Texture2D.h"
-#include "VideoBackends/Vulkan/VulkanContext.h"
-
-namespace Vulkan
-{
-Texture2D::Texture2D(u32 width, u32 height, u32 levels, u32 layers, VkFormat format,
- VkSampleCountFlagBits samples, VkImageViewType view_type, VkImage image,
- VkDeviceMemory device_memory, VkImageView view)
- : m_width(width), m_height(height), m_levels(levels), m_layers(layers), m_format(format),
- m_samples(samples), m_view_type(view_type), m_image(image), m_device_memory(device_memory),
- m_view(view)
-{
-}
-
-Texture2D::~Texture2D()
-{
- g_command_buffer_mgr->DeferImageViewDestruction(m_view);
-
- // If we don't have device memory allocated, the image is not owned by us (e.g. swapchain)
- if (m_device_memory != VK_NULL_HANDLE)
- {
- g_command_buffer_mgr->DeferImageDestruction(m_image);
- g_command_buffer_mgr->DeferDeviceMemoryDestruction(m_device_memory);
- }
-}
-
-std::unique_ptr<Texture2D> Texture2D::Create(u32 width, u32 height, u32 levels, u32 layers,
- VkFormat format, VkSampleCountFlagBits samples,
- VkImageViewType view_type, VkImageTiling tiling,
- VkImageUsageFlags usage)
-{
- VkImageCreateInfo image_info = {VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
- nullptr,
- 0,
- VK_IMAGE_TYPE_2D,
- format,
- {width, height, 1},
- levels,
- layers,
- samples,
- tiling,
- usage,
- VK_SHARING_MODE_EXCLUSIVE,
- 0,
- nullptr,
- VK_IMAGE_LAYOUT_UNDEFINED};
-
- VkImage image = VK_NULL_HANDLE;
- VkResult res = vkCreateImage(g_vulkan_context->GetDevice(), &image_info, nullptr, &image);
- if (res != VK_SUCCESS)
- {
- LOG_VULKAN_ERROR(res, "vkCreateImage failed: ");
- return nullptr;
- }
-
- // Allocate memory to back this texture, we want device local memory in this case
- VkMemoryRequirements memory_requirements;
- vkGetImageMemoryRequirements(g_vulkan_context->GetDevice(), image, &memory_requirements);
-
- VkMemoryAllocateInfo memory_info = {
- VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, nullptr, memory_requirements.size,
- g_vulkan_context->GetMemoryType(memory_requirements.memoryTypeBits,
- VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)};
-
- VkDeviceMemory device_memory;
- res = vkAllocateMemory(g_vulkan_context->GetDevice(), &memory_info, nullptr, &device_memory);
- if (res != VK_SUCCESS)
- {
- LOG_VULKAN_ERROR(res, "vkAllocateMemory failed: ");
- vkDestroyImage(g_vulkan_context->GetDevice(), image, nullptr);
- return nullptr;
- }
-
- res = vkBindImageMemory(g_vulkan_context->GetDevice(), image, device_memory, 0);
- if (res != VK_SUCCESS)
- {
- LOG_VULKAN_ERROR(res, "vkBindImageMemory failed: ");
- vkDestroyImage(g_vulkan_context->GetDevice(), image, nullptr);
- vkFreeMemory(g_vulkan_context->GetDevice(), device_memory, nullptr);
- return nullptr;
- }
-
- VkImageViewCreateInfo view_info = {
- VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
- nullptr,
- 0,
- image,
- view_type,
- format,
- {VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY,
- VK_COMPONENT_SWIZZLE_IDENTITY},
- {Util::IsDepthFormat(format) ? static_cast<VkImageAspectFlags>(VK_IMAGE_ASPECT_DEPTH_BIT) :
- static_cast<VkImageAspectFlags>(VK_IMAGE_ASPECT_COLOR_BIT),
- 0, levels, 0, layers}};
-
- VkImageView view = VK_NULL_HANDLE;
- res = vkCreateImageView(g_vulkan_context->GetDevice(), &view_info, nullptr, &view);
- if (res != VK_SUCCESS)
- {
- LOG_VULKAN_ERROR(res, "vkCreateImageView failed: ");
- vkDestroyImage(g_vulkan_context->GetDevice(), image, nullptr);
- vkFreeMemory(g_vulkan_context->GetDevice(), device_memory, nullptr);
- return nullptr;
- }
-
- return std::make_unique<Texture2D>(width, height, levels, layers, format, samples, view_type,
- image, device_memory, view);
-}
-
-std::unique_ptr<Texture2D> Texture2D::CreateFromExistingImage(u32 width, u32 height, u32 levels,
- u32 layers, VkFormat format,
- VkSampleCountFlagBits samples,
- VkImageViewType view_type,
- VkImage existing_image)
-{
- // Only need to create the image view, this is mainly for swap chains.
- VkImageViewCreateInfo view_info = {
- VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
- nullptr,
- 0,
- existing_image,
- view_type,
- format,
- {VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY,
- VK_COMPONENT_SWIZZLE_IDENTITY},
- {Util::IsDepthFormat(format) ? static_cast<VkImageAspectFlags>(VK_IMAGE_ASPECT_DEPTH_BIT) :
- static_cast<VkImageAspectFlags>(VK_IMAGE_ASPECT_COLOR_BIT),
- 0, levels, 0, layers}};
-
- // Memory is managed by the owner of the image.
- VkDeviceMemory memory = VK_NULL_HANDLE;
- VkImageView view = VK_NULL_HANDLE;
- VkResult res = vkCreateImageView(g_vulkan_context->GetDevice(), &view_info, nullptr, &view);
- if (res != VK_SUCCESS)
- {
- LOG_VULKAN_ERROR(res, "vkCreateImageView failed: ");
- return nullptr;
- }
-
- return std::make_unique<Texture2D>(width, height, levels, layers, format, samples, view_type,
- existing_image, memory, view);
-}
-
-void Texture2D::OverrideImageLayout(VkImageLayout new_layout)
-{
- m_layout = new_layout;
-}
-
-void Texture2D::TransitionToLayout(VkCommandBuffer command_buffer, VkImageLayout new_layout)
-{
- if (m_layout == new_layout)
- return;
-
- VkImageMemoryBarrier barrier = {
- VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, // VkStructureType sType
- nullptr, // const void* pNext
- 0, // VkAccessFlags srcAccessMask
- 0, // VkAccessFlags dstAccessMask
- m_layout, // VkImageLayout oldLayout
- new_layout, // VkImageLayout newLayout
- VK_QUEUE_FAMILY_IGNORED, // uint32_t srcQueueFamilyIndex
- VK_QUEUE_FAMILY_IGNORED, // uint32_t dstQueueFamilyIndex
- m_image, // VkImage image
- {Util::GetImageAspectForFormat(m_format), 0, m_levels, 0,
- m_layers} // VkImageSubresourceRange subresourceRange
- };
-
- // srcStageMask -> Stages that must complete before the barrier
- // dstStageMask -> Stages that must wait for after the barrier before beginning
- VkPipelineStageFlags srcStageMask, dstStageMask;
- switch (m_layout)
- {
- case VK_IMAGE_LAYOUT_UNDEFINED:
- // Layout undefined therefore contents undefined, and we don't care what happens to it.
- barrier.srcAccessMask = 0;
- srcStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
- break;
-
- case VK_IMAGE_LAYOUT_PREINITIALIZED:
- // Image has been pre-initialized by the host, so ensure all writes have completed.
- barrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
- srcStageMask = VK_PIPELINE_STAGE_HOST_BIT;
- break;
-
- case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
- // Image was being used as a color attachment, so ensure all writes have completed.
- barrier.srcAccessMask =
- VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
- srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
- break;
-
- case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
- // Image was being used as a depthstencil attachment, so ensure all writes have completed.
- barrier.srcAccessMask =
- VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
- srcStageMask =
- VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
- break;
-
- case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
- // Image was being used as a shader resource, make sure all reads have finished.
- barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT;
- srcStageMask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
- break;
-
- case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:
- // Image was being used as a copy source, ensure all reads have finished.
- barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
- srcStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT;
- break;
-
- case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:
- // Image was being used as a copy destination, ensure all writes have finished.
- barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
- srcStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT;
- break;
-
- default:
- srcStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
- break;
- }
-
- switch (new_layout)
- {
- case VK_IMAGE_LAYOUT_UNDEFINED:
- barrier.dstAccessMask = 0;
- dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
- break;
-
- case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
- barrier.dstAccessMask =
- VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
- dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
- break;
-
- case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
- barrier.dstAccessMask =
- VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
- dstStageMask =
- VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
- break;
-
- case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
- barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
- dstStageMask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
- break;
-
- case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:
- barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
- dstStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT;
- break;
-
- case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:
- barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
- dstStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT;
- break;
-
- case VK_IMAGE_LAYOUT_PRESENT_SRC_KHR:
- srcStageMask = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
- dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
- break;
-
- default:
- dstStageMask = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
- break;
- }
-
- // If we were using a compute layout, the stages need to reflect that
- switch (m_compute_layout)
- {
- case ComputeImageLayout::Undefined:
- break;
- case ComputeImageLayout::ReadOnly:
- barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT;
- srcStageMask = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
- break;
- case ComputeImageLayout::WriteOnly:
- barrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
- srcStageMask = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
- break;
- case ComputeImageLayout::ReadWrite:
- barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
- srcStageMask = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
- break;
- }
- m_compute_layout = ComputeImageLayout::Undefined;
-
- vkCmdPipelineBarrier(command_buffer, srcStageMask, dstStageMask, 0, 0, nullptr, 0, nullptr, 1,
- &barrier);
-
- m_layout = new_layout;
-}
-
-void Texture2D::TransitionToLayout(VkCommandBuffer command_buffer, ComputeImageLayout new_layout)
-{
- ASSERT(new_layout != ComputeImageLayout::Undefined);
- if (m_compute_layout == new_layout)
- return;
-
- VkImageMemoryBarrier barrier = {
- VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, // VkStructureType sType
- nullptr, // const void* pNext
- 0, // VkAccessFlags srcAccessMask
- 0, // VkAccessFlags dstAccessMask
- m_layout, // VkImageLayout oldLayout
- VK_IMAGE_LAYOUT_GENERAL, // VkImageLayout newLayout
- VK_QUEUE_FAMILY_IGNORED, // uint32_t srcQueueFamilyIndex
- VK_QUEUE_FAMILY_IGNORED, // uint32_t dstQueueFamilyIndex
- m_image, // VkImage image
- {Util::GetImageAspectForFormat(m_format), 0, m_levels, 0,
- m_layers} // VkImageSubresourceRange subresourceRange
- };
-
- VkPipelineStageFlags srcStageMask, dstStageMask;
- switch (m_layout)
- {
- case VK_IMAGE_LAYOUT_UNDEFINED:
- // Layout undefined therefore contents undefined, and we don't care what happens to it.
- barrier.srcAccessMask = 0;
- srcStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
- break;
-
- case VK_IMAGE_LAYOUT_PREINITIALIZED:
- // Image has been pre-initialized by the host, so ensure all writes have completed.
- barrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
- srcStageMask = VK_PIPELINE_STAGE_HOST_BIT;
- break;
-
- case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
- // Image was being used as a color attachment, so ensure all writes have completed.
- barrier.srcAccessMask =
- VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
- srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
- break;
-
- case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
- // Image was being used as a depthstencil attachment, so ensure all writes have completed.
- barrier.srcAccessMask =
- VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
- srcStageMask =
- VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
- break;
-
- case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
- // Image was being used as a shader resource, make sure all reads have finished.
- barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT;
- srcStageMask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
- break;
-
- case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:
- // Image was being used as a copy source, ensure all reads have finished.
- barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
- srcStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT;
- break;
-
- case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:
- // Image was being used as a copy destination, ensure all writes have finished.
- barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
- srcStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT;
- break;
-
- default:
- srcStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
- break;
- }
-
- switch (new_layout)
- {
- case ComputeImageLayout::ReadOnly:
- barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
- barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
- dstStageMask = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
- break;
- case ComputeImageLayout::WriteOnly:
- barrier.dstAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
- barrier.newLayout = VK_IMAGE_LAYOUT_GENERAL;
- dstStageMask = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
- break;
- case ComputeImageLayout::ReadWrite:
- barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
- barrier.newLayout = VK_IMAGE_LAYOUT_GENERAL;
- dstStageMask = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
- break;
- default:
- dstStageMask = 0;
- break;
- }
-
- m_layout = barrier.newLayout;
- m_compute_layout = new_layout;
-
- vkCmdPipelineBarrier(command_buffer, srcStageMask, dstStageMask, 0, 0, nullptr, 0, nullptr, 1,
- &barrier);
-}
-
-} // namespace Vulkan
diff --git a/Source/Core/VideoBackends/Vulkan/Texture2D.h b/Source/Core/VideoBackends/Vulkan/Texture2D.h
deleted file mode 100644
index 3fce48d758..0000000000
--- a/Source/Core/VideoBackends/Vulkan/Texture2D.h
+++ /dev/null
@@ -1,79 +0,0 @@
-// Copyright 2016 Dolphin Emulator Project
-// Licensed under GPLv2+
-// Refer to the license.txt file included.
-
-#pragma once
-
-#include <memory>
-
-#include "Common/CommonTypes.h"
-#include "VideoBackends/Vulkan/Constants.h"
-
-namespace Vulkan
-{
-class CommandBufferManager;
-class ObjectCache;
-
-class Texture2D
-{
-public:
- // Custom image layouts, mainly used for switching to/from compute
- enum class ComputeImageLayout
- {
- Undefined,
- ReadOnly,
- WriteOnly,
- ReadWrite
- };
-
- Texture2D(u32 width, u32 height, u32 levels, u32 layers, VkFormat format,
- VkSampleCountFlagBits samples, VkImageViewType view_type, VkImage image,
- VkDeviceMemory device_memory, VkImageView view);
- ~Texture2D();
-
- static std::unique_ptr<Texture2D> Create(u32 width, u32 height, u32 levels, u32 layers,
- VkFormat format, VkSampleCountFlagBits samples,
- VkImageViewType view_type, VkImageTiling tiling,
- VkImageUsageFlags usage);
-
- static std::unique_ptr<Texture2D> CreateFromExistingImage(u32 width, u32 height, u32 levels,
- u32 layers, VkFormat format,
- VkSampleCountFlagBits samples,
- VkImageViewType view_type,
- VkImage existing_image);
-
- u32 GetWidth() const { return m_width; }
- u32 GetHeight() const { return m_height; }
- u32 GetLevels() const { return m_levels; }
- u32 GetLayers() const { return m_layers; }
- VkFormat GetFormat() const { return m_format; }
- VkSampleCountFlagBits GetSamples() const { return m_samples; }
- VkImageLayout GetLayout() const { return m_layout; }
- VkImageViewType GetViewType() const { return m_view_type; }
- VkImage GetImage() const { return m_image; }
- VkDeviceMemory GetDeviceMemory() const { return m_device_memory; }
- VkImageView GetView() const { return m_view; }
- // Used when the render pass is changing the image layout, or to force it to
- // VK_IMAGE_LAYOUT_UNDEFINED, if the existing contents of the image is
- // irrelevant and will not be loaded.
- void OverrideImageLayout(VkImageLayout new_layout);
-
- void TransitionToLayout(VkCommandBuffer command_buffer, VkImageLayout new_layout);
- void TransitionToLayout(VkCommandBuffer command_buffer, ComputeImageLayout new_layout);
-
-private:
- u32 m_width;
- u32 m_height;
- u32 m_levels;
- u32 m_layers;
- VkFormat m_format;
- VkSampleCountFlagBits m_samples;
- VkImageViewType m_view_type;
- VkImageLayout m_layout = VK_IMAGE_LAYOUT_UNDEFINED;
- ComputeImageLayout m_compute_layout = ComputeImageLayout::Undefined;
-
- VkImage m_image;
- VkDeviceMemory m_device_memory;
- VkImageView m_view;
-};
-}
diff --git a/Source/Core/VideoBackends/Vulkan/TextureCache.cpp b/Source/Core/VideoBackends/Vulkan/TextureCache.cpp
deleted file mode 100644
index 3f26b28a7c..0000000000
--- a/Source/Core/VideoBackends/Vulkan/TextureCache.cpp
+++ /dev/null
@@ -1,316 +0,0 @@
-// Copyright 2016 Dolphin Emulator Project
-// Licensed under GPLv2+
-// Refer to the license.txt file included.
-
-#include "VideoBackends/Vulkan/TextureCache.h"
-
-#include <algorithm>
-#include <cstring>
-#include <string>
-#include <vector>
-
-#include "Common/Assert.h"
-#include "Common/CommonFuncs.h"
-#include "Common/Logging/Log.h"
-#include "Common/MsgHandler.h"
-
-#include "VideoBackends/Vulkan/CommandBufferManager.h"
-#include "VideoBackends/Vulkan/FramebufferManager.h"
-#include "VideoBackends/Vulkan/ObjectCache.h"
-#include "VideoBackends/Vulkan/Renderer.h"
-#include "VideoBackends/Vulkan/StateTracker.h"
-#include "VideoBackends/Vulkan/StreamBuffer.h"
-#include "VideoBackends/Vulkan/Texture2D.h"
-#include "VideoBackends/Vulkan/TextureConverter.h"
-#include "VideoBackends/Vulkan/Util.h"
-#include "VideoBackends/Vulkan/VKTexture.h"
-#include "VideoBackends/Vulkan/VulkanContext.h"
-
-#include "VideoCommon/ImageWrite.h"
-#include "VideoCommon/TextureConfig.h"
-
-namespace Vulkan
-{
-TextureCache::TextureCache()
-{
-}
-
-TextureCache::~TextureCache()
-{
- TextureCache::DeleteShaders();
-}
-
-VkShaderModule TextureCache::GetCopyShader() const
-{
- return m_copy_shader;
-}
-
-TextureCache* TextureCache::GetInstance()
-{
- return static_cast<TextureCache*>(g_texture_cache.get());
-}
-
-bool TextureCache::Initialize()
-{
- m_texture_converter = std::make_unique<TextureConverter>();
- if (!m_texture_converter->Initialize())
- {
- PanicAlert("Failed to initialize texture converter");
- return false;
- }
-
- if (!CompileShaders())
- {
- PanicAlert("Failed to compile one or more shaders");
- return false;
- }
-
- return true;
-}
-
-void TextureCache::ConvertTexture(TCacheEntry* destination, TCacheEntry* source,
- const void* palette, TLUTFormat format)
-{
- m_texture_converter->ConvertTexture(destination, source, palette, format);
-
- // Ensure both textures remain in the SHADER_READ_ONLY layout so they can be bound.
- static_cast<VKTexture*>(source->texture.get())
- ->GetRawTexIdentifier()
- ->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
- static_cast<VKTexture*>(destination->texture.get())
- ->GetRawTexIdentifier()
- ->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
-}
-
-void TextureCache::CopyEFB(AbstractStagingTexture* dst, const EFBCopyParams& params,
- u32 native_width, u32 bytes_per_row, u32 num_blocks_y, u32 memory_stride,
- const EFBRectangle& src_rect, bool scale_by_half, float y_scale,
- float gamma, bool clamp_top, bool clamp_bottom,
- const CopyFilterCoefficientArray& filter_coefficients)
-{
- // Flush EFB pokes first, as they're expected to be included.
- FramebufferManager::GetInstance()->FlushEFBPokes();
-
- // MSAA case where we need to resolve first.
- // An out-of-bounds source region is valid here, and fine for the draw (since it is converted
- // to texture coordinates), but it's not valid to resolve an out-of-range rectangle.
- TargetRectangle scaled_src_rect = g_renderer->ConvertEFBRectangle(src_rect);
- VkRect2D region = {{scaled_src_rect.left, scaled_src_rect.top},
- {static_cast<u32>(scaled_src_rect.GetWidth()),
- static_cast<u32>(scaled_src_rect.GetHeight())}};
- region = Util::ClampRect2D(region, FramebufferManager::GetInstance()->GetEFBWidth(),
- FramebufferManager::GetInstance()->GetEFBHeight());
- Texture2D* src_texture;
- if (params.depth)
- src_texture = FramebufferManager::GetInstance()->ResolveEFBDepthTexture(region);
- else
- src_texture = FramebufferManager::GetInstance()->ResolveEFBColorTexture(region);
-
- // End render pass before barrier (since we have no self-dependencies).
- // The barrier has to happen after the render pass, not inside it, as we are going to be
- // reading from the texture immediately afterwards.
- StateTracker::GetInstance()->EndRenderPass();
-
- // Transition to shader resource before reading.
- VkImageLayout original_layout = src_texture->GetLayout();
- src_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
-
- m_texture_converter->EncodeTextureToMemory(
- src_texture->GetView(), dst, params, native_width, bytes_per_row, num_blocks_y, memory_stride,
- src_rect, scale_by_half, y_scale, gamma, clamp_top, clamp_bottom, filter_coefficients);
-
- // Transition back to original state
- src_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(), original_layout);
-
- StateTracker::GetInstance()->OnEFBCopyToRAM();
-}
-
-bool TextureCache::SupportsGPUTextureDecode(TextureFormat format, TLUTFormat palette_format)
-{
- return m_texture_converter->SupportsTextureDecoding(format, palette_format);
-}
-
-void TextureCache::DecodeTextureOnGPU(TCacheEntry* entry, u32 dst_level, const u8* data,
- size_t data_size, TextureFormat format, u32 width, u32 height,
- u32 aligned_width, u32 aligned_height, u32 row_stride,
- const u8* palette, TLUTFormat palette_format)
-{
- // Group compute shader dispatches together in the init command buffer. That way we don't have to
- // pay a penalty for switching from graphics->compute, or end/restart our render pass.
- VkCommandBuffer command_buffer = g_command_buffer_mgr->GetCurrentInitCommandBuffer();
- m_texture_converter->DecodeTexture(command_buffer, entry, dst_level, data, data_size, format,
- width, height, aligned_width, aligned_height, row_stride,
- palette, palette_format);
-
- // Last mip level? Ensure the texture is ready for use.
- if (dst_level == (entry->GetNumLevels() - 1))
- {
- static_cast<VKTexture*>(entry->texture.get())
- ->GetRawTexIdentifier()
- ->TransitionToLayout(command_buffer, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
- }
-}
-
-bool TextureCache::CompileShaders()
-{
- static const char COPY_SHADER_SOURCE[] = R"(
- layout(set = 1, binding = 0) uniform sampler2DArray samp0;
-
- layout(location = 0) in float3 uv0;
- layout(location = 1) in float4 col0;
- layout(location = 0) out float4 ocol0;
-
- void main()
- {
- ocol0 = texture(samp0, uv0);
- }
- )";
-
- std::string header = g_shader_cache->GetUtilityShaderHeader();
- std::string source = header + COPY_SHADER_SOURCE;
-
- m_copy_shader = Util::CompileAndCreateFragmentShader(source);
-
- return m_copy_shader != VK_NULL_HANDLE;
-}
-
-void TextureCache::DeleteShaders()
-{
- // It is safe to destroy shader modules after they are consumed by creating a pipeline.
- // Therefore, no matter where this function is called from, it won't cause an issue due to
- // pending commands, although at the time of writing should only be called at the end of
- // a frame. See Vulkan spec, section 2.3.1. Object Lifetime.
- if (m_copy_shader != VK_NULL_HANDLE)
- {
- vkDestroyShaderModule(g_vulkan_context->GetDevice(), m_copy_shader, nullptr);
- m_copy_shader = VK_NULL_HANDLE;
- }
-
- for (auto& shader : m_efb_copy_to_tex_shaders)
- {
- vkDestroyShaderModule(g_vulkan_context->GetDevice(), shader.second, nullptr);
- }
- m_efb_copy_to_tex_shaders.clear();
-}
-
-void TextureCache::CopyEFBToCacheEntry(TCacheEntry* entry, bool is_depth_copy,
- const EFBRectangle& src_rect, bool scale_by_half,
- EFBCopyFormat dst_format, bool is_intensity, float gamma,
- bool clamp_top, bool clamp_bottom,
- const CopyFilterCoefficientArray& filter_coefficients)
-{
- VKTexture* texture = static_cast<VKTexture*>(entry->texture.get());
-
- // A better way of doing this would be nice.
- FramebufferManager* framebuffer_mgr =
- static_cast<FramebufferManager*>(g_framebuffer_manager.get());
- TargetRectangle scaled_src_rect = g_renderer->ConvertEFBRectangle(src_rect);
-
- // Flush EFB pokes first, as they're expected to be included.
- framebuffer_mgr->FlushEFBPokes();
-
- // Has to be flagged as a render target.
- ASSERT(texture->GetFramebuffer() != VK_NULL_HANDLE);
-
- // Can't be done in a render pass, since we're doing our own render pass!
- VkCommandBuffer command_buffer = g_command_buffer_mgr->GetCurrentCommandBuffer();
- StateTracker::GetInstance()->EndRenderPass();
-
- // Fill uniform buffer.
- struct PixelUniforms
- {
- float filter_coefficients[3];
- float gamma_rcp;
- float clamp_top;
- float clamp_bottom;
- float pixel_height;
- u32 padding;
- };
- PixelUniforms uniforms;
- for (size_t i = 0; i < filter_coefficients.size(); i++)
- uniforms.filter_coefficients[i] = filter_coefficients[i];
- uniforms.gamma_rcp = 1.0f / gamma;
- uniforms.clamp_top = clamp_top ? src_rect.top / float(EFB_HEIGHT) : 0.0f;
- uniforms.clamp_bottom = clamp_bottom ? src_rect.bottom / float(EFB_HEIGHT) : 1.0f;
- uniforms.pixel_height =
- g_ActiveConfig.bCopyEFBScaled ? 1.0f / g_renderer->GetTargetHeight() : 1.0f / EFB_HEIGHT;
- uniforms.padding = 0;
-
- // Transition EFB to shader resource before binding.
- // An out-of-bounds source region is valid here, and fine for the draw (since it is converted
- // to texture coordinates), but it's not valid to resolve an out-of-range rectangle.
- VkRect2D region = {{scaled_src_rect.left, scaled_src_rect.top},
- {static_cast<u32>(scaled_src_rect.GetWidth()),
- static_cast<u32>(scaled_src_rect.GetHeight())}};
- region = Util::ClampRect2D(region, FramebufferManager::GetInstance()->GetEFBWidth(),
- FramebufferManager::GetInstance()->GetEFBHeight());
- Texture2D* src_texture;
- if (is_depth_copy)
- src_texture = FramebufferManager::GetInstance()->ResolveEFBDepthTexture(region);
- else
- src_texture = FramebufferManager::GetInstance()->ResolveEFBColorTexture(region);
-
- VkSampler src_sampler =
- scale_by_half ? g_object_cache->GetLinearSampler() : g_object_cache->GetPointSampler();
- VkImageLayout original_layout = src_texture->GetLayout();
- src_texture->TransitionToLayout(command_buffer, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
- texture->GetRawTexIdentifier()->TransitionToLayout(command_buffer,
- VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
-
- auto uid = TextureConversionShaderGen::GetShaderUid(dst_format, is_depth_copy, is_intensity,
- scale_by_half,
- NeedsCopyFilterInShader(filter_coefficients));
-
- auto it = m_efb_copy_to_tex_shaders.emplace(uid, VkShaderModule(VK_NULL_HANDLE));
- VkShaderModule& shader = it.first->second;
- bool created = it.second;
-
- if (created)
- {
- std::string source = g_shader_cache->GetUtilityShaderHeader();
- source +=
- TextureConversionShaderGen::GenerateShader(APIType::Vulkan, uid.GetUidData()).GetBuffer();
-
- shader = Util::CompileAndCreateFragmentShader(source);
- }
-
- VkRenderPass render_pass = g_object_cache->GetRenderPass(
- texture->GetRawTexIdentifier()->GetFormat(), VK_FORMAT_UNDEFINED,
- texture->GetRawTexIdentifier()->GetSamples(), VK_ATTACHMENT_LOAD_OP_DONT_CARE);
-
- UtilityShaderDraw draw(command_buffer,
- g_object_cache->GetPipelineLayout(PIPELINE_LAYOUT_STANDARD), render_pass,
- g_shader_cache->GetPassthroughVertexShader(),
- g_shader_cache->GetPassthroughGeometryShader(), shader);
-
- u8* ubo_ptr = draw.AllocatePSUniforms(sizeof(PixelUniforms));
- std::memcpy(ubo_ptr, &uniforms, sizeof(PixelUniforms));
- draw.CommitPSUniforms(sizeof(PixelUniforms));
-
- draw.SetPSSampler(0, src_texture->GetView(), src_sampler);
-
- VkRect2D dest_region = {{0, 0}, {texture->GetConfig().width, texture->GetConfig().height}};
-
- draw.BeginRenderPass(texture->GetFramebuffer(), dest_region);
-
- draw.DrawQuad(0, 0, texture->GetConfig().width, texture->GetConfig().height, scaled_src_rect.left,
- scaled_src_rect.top, 0, scaled_src_rect.GetWidth(), scaled_src_rect.GetHeight(),
- framebuffer_mgr->GetEFBWidth(), framebuffer_mgr->GetEFBHeight());
-
- draw.EndRenderPass();
-
- // We touched everything, so put it back.
- StateTracker::GetInstance()->SetPendingRebind();
-
- // Transition the EFB back to its original layout.
- src_texture->TransitionToLayout(command_buffer, original_layout);
-
- // Ensure texture is in SHADER_READ_ONLY layout, ready for usage.
- texture->GetRawTexIdentifier()->TransitionToLayout(command_buffer,
- VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
-}
-
-} // namespace Vulkan
diff --git a/Source/Core/VideoBackends/Vulkan/TextureCache.h b/Source/Core/VideoBackends/Vulkan/TextureCache.h
deleted file mode 100644
index 35b3b6c360..0000000000
--- a/Source/Core/VideoBackends/Vulkan/TextureCache.h
+++ /dev/null
@@ -1,65 +0,0 @@
-// Copyright 2016 Dolphin Emulator Project
-// Licensed under GPLv2+
-// Refer to the license.txt file included.
-
-#pragma once
-
-#include <map>
-#include <memory>
-
-#include "Common/CommonTypes.h"
-#include "VideoBackends/Vulkan/StreamBuffer.h"
-#include "VideoCommon/TextureCacheBase.h"
-#include "VideoCommon/TextureConverterShaderGen.h"
-
-namespace Vulkan
-{
-class TextureConverter;
-class StateTracker;
-class Texture2D;
-class VKTexture;
-
-class TextureCache : public TextureCacheBase
-{
-public:
- TextureCache();
- ~TextureCache();
-
- static TextureCache* GetInstance();
-
- TextureConverter* GetTextureConverter() const { return m_texture_converter.get(); }
- bool Initialize();
-
- bool CompileShaders() override;
- void DeleteShaders() override;
-
- void ConvertTexture(TCacheEntry* destination, TCacheEntry* source, const void* palette,
- TLUTFormat format) override;
-
- void CopyEFB(AbstractStagingTexture* dst, const EFBCopyParams& params, u32 native_width,
- u32 bytes_per_row, u32 num_blocks_y, u32 memory_stride, const EFBRectangle& src_rect,
- bool scale_by_half, float y_scale, float gamma, bool clamp_top, bool clamp_bottom,
- const CopyFilterCoefficientArray& filter_coefficients) override;
-
- bool SupportsGPUTextureDecode(TextureFormat format, TLUTFormat palette_format) override;
-
- void DecodeTextureOnGPU(TCacheEntry* entry, u32 dst_level, const u8* data, size_t data_size,
- TextureFormat format, u32 width, u32 height, u32 aligned_width,
- u32 aligned_height, u32 row_stride, const u8* palette,
- TLUTFormat palette_format) override;
-
- VkShaderModule GetCopyShader() const;
-
-private:
- void CopyEFBToCacheEntry(TCacheEntry* entry, bool is_depth_copy, const EFBRectangle& src_rect,
- bool scale_by_half, EFBCopyFormat dst_format, bool is_intensity,
- float gamma, bool clamp_top, bool clamp_bottom,
- const CopyFilterCoefficientArray& filter_coefficients) override;
-
- std::unique_ptr<TextureConverter> m_texture_converter;
-
- VkShaderModule m_copy_shader = VK_NULL_HANDLE;
- std::map<TextureConversionShaderGen::TCShaderUid, VkShaderModule> m_efb_copy_to_tex_shaders;
-};
-
-} // namespace Vulkan
diff --git a/Source/Core/VideoBackends/Vulkan/TextureConverter.cpp b/Source/Core/VideoBackends/Vulkan/TextureConverter.cpp
deleted file mode 100644
index c5acdc8e7f..0000000000
--- a/Source/Core/VideoBackends/Vulkan/TextureConverter.cpp
+++ /dev/null
@@ -1,634 +0,0 @@
-// Copyright 2016 Dolphin Emulator Project
-// Licensed under GPLv2+
-// Refer to the license.txt file included.
-
-#include "VideoBackends/Vulkan/TextureConverter.h"
-
-#include <algorithm>
-#include <array>
-#include <cstddef>
-#include <cstring>
-#include <string>
-
-#include "Common/Assert.h"
-#include "Common/CommonFuncs.h"
-#include "Common/CommonTypes.h"
-#include "Common/Logging/Log.h"
-#include "Common/MsgHandler.h"
-
-#include "VideoBackends/Vulkan/CommandBufferManager.h"
-#include "VideoBackends/Vulkan/FramebufferManager.h"
-#include "VideoBackends/Vulkan/ObjectCache.h"
-#include "VideoBackends/Vulkan/StateTracker.h"
-#include "VideoBackends/Vulkan/StreamBuffer.h"
-#include "VideoBackends/Vulkan/Texture2D.h"
-#include "VideoBackends/Vulkan/Util.h"
-#include "VideoBackends/Vulkan/VKTexture.h"
-#include "VideoBackends/Vulkan/VulkanContext.h"
-
-#include "VideoCommon/TextureConversionShader.h"
-#include "VideoCommon/TextureDecoder.h"
-#include "VideoCommon/VideoConfig.h"
-
-namespace Vulkan
-{
-namespace
-{
-struct EFBEncodeParams
-{
- std::array<s32, 4> position_uniform;
- float y_scale;
- float gamma_rcp;
- float clamp_top;
- float clamp_bottom;
- float filter_coefficients[3];
- u32 padding;
-};
-} // namespace
-TextureConverter::TextureConverter()
-{
-}
-
-TextureConverter::~TextureConverter()
-{
- for (const auto& it : m_palette_conversion_shaders)
- {
- if (it != VK_NULL_HANDLE)
- vkDestroyShaderModule(g_vulkan_context->GetDevice(), it, nullptr);
- }
-
- if (m_texel_buffer_view_r8_uint != VK_NULL_HANDLE)
- vkDestroyBufferView(g_vulkan_context->GetDevice(), m_texel_buffer_view_r8_uint, nullptr);
- if (m_texel_buffer_view_r16_uint != VK_NULL_HANDLE)
- vkDestroyBufferView(g_vulkan_context->GetDevice(), m_texel_buffer_view_r16_uint, nullptr);
- if (m_texel_buffer_view_r32g32_uint != VK_NULL_HANDLE)
- vkDestroyBufferView(g_vulkan_context->GetDevice(), m_texel_buffer_view_r32g32_uint, nullptr);
- if (m_texel_buffer_view_rgba8_unorm != VK_NULL_HANDLE)
- vkDestroyBufferView(g_vulkan_context->GetDevice(), m_texel_buffer_view_rgba8_unorm, nullptr);
- if (m_texel_buffer_view_rgba8_uint != VK_NULL_HANDLE)
- vkDestroyBufferView(g_vulkan_context->GetDevice(), m_texel_buffer_view_rgba8_uint, nullptr);
-
- for (auto& it : m_encoding_shaders)
- vkDestroyShaderModule(g_vulkan_context->GetDevice(), it.second, nullptr);
-
- for (const auto& it : m_decoding_pipelines)
- {
- if (it.second.compute_shader != VK_NULL_HANDLE)
- vkDestroyShaderModule(g_vulkan_context->GetDevice(), it.second.compute_shader, nullptr);
- }
-}
-
-bool TextureConverter::Initialize()
-{
- if (!CreateTexelBuffer())
- {
- PanicAlert("Failed to create uniform buffer");
- return false;
- }
-
- if (!CompilePaletteConversionShaders())
- {
- PanicAlert("Failed to compile palette conversion shaders");
- return false;
- }
-
- if (!CreateEncodingTexture())
- {
- PanicAlert("Failed to create encoding texture");
- return false;
- }
-
- if (!CreateDecodingTexture())
- {
- PanicAlert("Failed to create decoding texture");
- return false;
- }
-
- return true;
-}
-
-bool TextureConverter::ReserveTexelBufferStorage(size_t size, size_t alignment)
-{
- // Enforce the minimum alignment for texture buffers on the device.
- size_t actual_alignment =
- std::max(static_cast<size_t>(g_vulkan_context->GetTexelBufferAlignment()), alignment);
- if (m_texel_buffer->ReserveMemory(size, actual_alignment))
- return true;
-
- WARN_LOG(VIDEO, "Executing command list while waiting for space in palette buffer");
- Util::ExecuteCurrentCommandsAndRestoreState(false);
-
- // This next call should never fail, since a command buffer is now in-flight and we can
- // wait on the fence for the GPU to finish. If this returns false, it's probably because
- // the device has been lost, which is fatal anyway.
- if (!m_texel_buffer->ReserveMemory(size, actual_alignment))
- {
- PanicAlert("Failed to allocate space for texture conversion");
- return false;
- }
-
- return true;
-}
-
-VkCommandBuffer
-TextureConverter::GetCommandBufferForTextureConversion(const TextureCache::TCacheEntry* src_entry)
-{
- // EFB copies can be used as paletted textures as well. For these, we can't assume them to be
- // contain the correct data before the frame begins (when the init command buffer is executed),
- // so we must convert them at the appropriate time, during the drawing command buffer.
- if (src_entry->IsCopy())
- {
- StateTracker::GetInstance()->EndRenderPass();
- StateTracker::GetInstance()->SetPendingRebind();
- return g_command_buffer_mgr->GetCurrentCommandBuffer();
- }
- else
- {
- // Use initialization command buffer and perform conversion before the drawing commands.
- return g_command_buffer_mgr->GetCurrentInitCommandBuffer();
- }
-}
-
-void TextureConverter::ConvertTexture(TextureCacheBase::TCacheEntry* dst_entry,
- TextureCacheBase::TCacheEntry* src_entry, const void* palette,
- TLUTFormat palette_format)
-{
- struct PSUniformBlock
- {
- float multiplier;
- int texel_buffer_offset;
- int pad[2];
- };
-
- VKTexture* source_texture = static_cast<VKTexture*>(src_entry->texture.get());
- VKTexture* destination_texture = static_cast<VKTexture*>(dst_entry->texture.get());
-
- ASSERT(static_cast<size_t>(palette_format) < NUM_PALETTE_CONVERSION_SHADERS);
- ASSERT(destination_texture->GetConfig().rendertarget);
-
- // We want to align to 2 bytes (R16) or the device's texel buffer alignment, whichever is greater.
- size_t palette_size = src_entry->format == TextureFormat::I4 ? 32 : 512;
- if (!ReserveTexelBufferStorage(palette_size, sizeof(u16)))
- return;
-
- // Copy in palette to texel buffer.
- u32 palette_offset = static_cast<u32>(m_texel_buffer->GetCurrentOffset());
- memcpy(m_texel_buffer->GetCurrentHostPointer(), palette, palette_size);
- m_texel_buffer->CommitMemory(palette_size);
-
- VkCommandBuffer command_buffer = GetCommandBufferForTextureConversion(src_entry);
- source_texture->GetRawTexIdentifier()->TransitionToLayout(
- command_buffer, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
- destination_texture->GetRawTexIdentifier()->TransitionToLayout(
- command_buffer, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
-
- // Bind and draw to the destination.
- VkRenderPass render_pass = g_object_cache->GetRenderPass(
- destination_texture->GetRawTexIdentifier()->GetFormat(), VK_FORMAT_UNDEFINED,
- destination_texture->GetRawTexIdentifier()->GetSamples(), VK_ATTACHMENT_LOAD_OP_DONT_CARE);
- UtilityShaderDraw draw(command_buffer,
- g_object_cache->GetPipelineLayout(PIPELINE_LAYOUT_TEXTURE_CONVERSION),
- render_pass, g_shader_cache->GetScreenQuadVertexShader(), VK_NULL_HANDLE,
- m_palette_conversion_shaders[static_cast<int>(palette_format)]);
-
- VkRect2D region = {{0, 0}, {dst_entry->GetWidth(), dst_entry->GetHeight()}};
- draw.BeginRenderPass(destination_texture->GetFramebuffer(), region);
-
- PSUniformBlock uniforms = {};
- uniforms.multiplier = src_entry->format == TextureFormat::I4 ? 15.0f : 255.0f;
- uniforms.texel_buffer_offset = static_cast<int>(palette_offset / sizeof(u16));
- draw.SetPushConstants(&uniforms, sizeof(uniforms));
- draw.SetPSSampler(0, source_texture->GetRawTexIdentifier()->GetView(),
- g_object_cache->GetPointSampler());
- draw.SetPSTexelBuffer(m_texel_buffer_view_r16_uint);
- draw.SetViewportAndScissor(0, 0, dst_entry->GetWidth(), dst_entry->GetHeight());
- draw.DrawWithoutVertexBuffer(4);
- draw.EndRenderPass();
-}
-
-void TextureConverter::EncodeTextureToMemory(
- VkImageView src_texture, AbstractStagingTexture* dest, const EFBCopyParams& params,
- u32 native_width, u32 bytes_per_row, u32 num_blocks_y, u32 memory_stride,
- const EFBRectangle& src_rect, bool scale_by_half, float y_scale, float gamma, bool clamp_top,
- bool clamp_bottom, const TextureCacheBase::CopyFilterCoefficientArray& filter_coefficients)
-{
- VkShaderModule shader = GetEncodingShader(params);
- if (shader == VK_NULL_HANDLE)
- {
- ERROR_LOG(VIDEO, "Missing encoding fragment shader for format %u->%u",
- static_cast<unsigned>(params.efb_format), static_cast<unsigned>(params.copy_format));
- return;
- }
-
- // Can't do our own draw within a render pass.
- StateTracker::GetInstance()->EndRenderPass();
-
- static_cast<VKTexture*>(m_encoding_render_texture.get())
- ->GetRawTexIdentifier()
- ->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
-
- VkRenderPass render_pass = g_object_cache->GetRenderPass(
- Util::GetVkFormatForHostTextureFormat(m_encoding_render_texture->GetConfig().format),
- VK_FORMAT_UNDEFINED, 1, VK_ATTACHMENT_LOAD_OP_DONT_CARE);
- UtilityShaderDraw draw(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- g_object_cache->GetPipelineLayout(PIPELINE_LAYOUT_PUSH_CONSTANT),
- render_pass, g_shader_cache->GetScreenQuadVertexShader(), VK_NULL_HANDLE,
- shader);
-
- // Uniform - int4 of left,top,native_width,scale
- EFBEncodeParams encoder_params;
- encoder_params.position_uniform[0] = src_rect.left;
- encoder_params.position_uniform[1] = src_rect.top;
- encoder_params.position_uniform[2] = static_cast<s32>(native_width);
- encoder_params.position_uniform[3] = scale_by_half ? 2 : 1;
- encoder_params.y_scale = y_scale;
- encoder_params.gamma_rcp = 1.0f / gamma;
- encoder_params.clamp_top = clamp_top ? src_rect.top / float(EFB_HEIGHT) : 0.0f;
- encoder_params.clamp_bottom = clamp_bottom ? src_rect.bottom / float(EFB_HEIGHT) : 1.0f;
- for (size_t i = 0; i < filter_coefficients.size(); i++)
- encoder_params.filter_coefficients[i] = filter_coefficients[i];
- u8* ubo_ptr = draw.AllocatePSUniforms(sizeof(EFBEncodeParams));
- std::memcpy(ubo_ptr, &encoder_params, sizeof(EFBEncodeParams));
- draw.CommitPSUniforms(sizeof(EFBEncodeParams));
-
- // We also linear filtering for both box filtering and downsampling higher resolutions to 1x
- // TODO: This only produces perfect downsampling for 2x IR, other resolutions will need more
- // complex down filtering to average all pixels and produce the correct result.
- bool linear_filter =
- (scale_by_half && !params.depth) || g_renderer->GetEFBScale() != 1 || y_scale > 1.0f;
- draw.SetPSSampler(0, src_texture,
- linear_filter ? g_object_cache->GetLinearSampler() :
- g_object_cache->GetPointSampler());
-
- u32 render_width = bytes_per_row / sizeof(u32);
- u32 render_height = num_blocks_y;
- Util::SetViewportAndScissor(g_command_buffer_mgr->GetCurrentCommandBuffer(), 0, 0, render_width,
- render_height);
-
- VkRect2D render_region = {{0, 0}, {render_width, render_height}};
- draw.BeginRenderPass(static_cast<VKTexture*>(m_encoding_render_texture.get())->GetFramebuffer(),
- render_region);
- draw.DrawWithoutVertexBuffer(4);
- draw.EndRenderPass();
-
- MathUtil::Rectangle<int> copy_rect(0, 0, render_width, render_height);
- dest->CopyFromTexture(m_encoding_render_texture.get(), copy_rect, 0, 0, copy_rect);
-}
-
-bool TextureConverter::SupportsTextureDecoding(TextureFormat format, TLUTFormat palette_format)
-{
- auto key = std::make_pair(format, palette_format);
- auto iter = m_decoding_pipelines.find(key);
- if (iter != m_decoding_pipelines.end())
- return iter->second.valid;
-
- TextureDecodingPipeline pipeline;
- pipeline.base_info = TextureConversionShaderTiled::GetDecodingShaderInfo(format);
- pipeline.compute_shader = VK_NULL_HANDLE;
- pipeline.valid = false;
-
- if (!pipeline.base_info)
- {
- m_decoding_pipelines.emplace(key, pipeline);
- return false;
- }
-
- std::string shader_source =
- TextureConversionShaderTiled::GenerateDecodingShader(format, palette_format, APIType::Vulkan);
-
- pipeline.compute_shader = Util::CompileAndCreateComputeShader(shader_source);
- if (pipeline.compute_shader == VK_NULL_HANDLE)
- {
- m_decoding_pipelines.emplace(key, pipeline);
- return false;
- }
-
- pipeline.valid = true;
- m_decoding_pipelines.emplace(key, pipeline);
- return true;
-}
-
-void TextureConverter::DecodeTexture(VkCommandBuffer command_buffer,
- TextureCache::TCacheEntry* entry, u32 dst_level,
- const u8* data, size_t data_size, TextureFormat format,
- u32 width, u32 height, u32 aligned_width, u32 aligned_height,
- u32 row_stride, const u8* palette, TLUTFormat palette_format)
-{
- VKTexture* destination_texture = static_cast<VKTexture*>(entry->texture.get());
- auto key = std::make_pair(format, palette_format);
- auto iter = m_decoding_pipelines.find(key);
- if (iter == m_decoding_pipelines.end())
- return;
-
- struct PushConstants
- {
- u32 dst_size[2];
- u32 src_size[2];
- u32 src_offset;
- u32 src_row_stride;
- u32 palette_offset;
- };
-
- // Copy to GPU-visible buffer, aligned to the data type
- auto info = iter->second;
- u32 bytes_per_buffer_elem =
- TextureConversionShaderTiled::GetBytesPerBufferElement(info.base_info->buffer_format);
-
- // Calculate total data size, including palette.
- // Only copy palette if it is required.
- u32 total_upload_size = static_cast<u32>(data_size);
- u32 palette_size = iter->second.base_info->palette_size;
- u32 palette_offset = total_upload_size;
- bool has_palette = palette_size > 0;
- if (has_palette)
- {
- // Align to u16.
- if ((total_upload_size % sizeof(u16)) != 0)
- {
- total_upload_size++;
- palette_offset++;
- }
-
- total_upload_size += palette_size;
- }
-
- // Allocate space for upload, if it fails, execute the buffer.
- if (!m_texel_buffer->ReserveMemory(total_upload_size, bytes_per_buffer_elem))
- {
- Util::ExecuteCurrentCommandsAndRestoreState(true, false);
- if (!m_texel_buffer->ReserveMemory(total_upload_size, bytes_per_buffer_elem))
- PanicAlert("Failed to reserve memory for encoded texture upload");
- }
-
- // Copy/commit upload buffer.
- u32 texel_buffer_offset = static_cast<u32>(m_texel_buffer->GetCurrentOffset());
-
- Util::BufferMemoryBarrier(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- m_texel_buffer->GetBuffer(), VK_ACCESS_SHADER_READ_BIT,
- VK_ACCESS_HOST_WRITE_BIT, texel_buffer_offset, total_upload_size,
- VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_HOST_BIT);
-
- std::memcpy(m_texel_buffer->GetCurrentHostPointer(), data, data_size);
- if (has_palette)
- std::memcpy(m_texel_buffer->GetCurrentHostPointer() + palette_offset, palette, palette_size);
- m_texel_buffer->CommitMemory(total_upload_size);
-
- Util::BufferMemoryBarrier(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- m_texel_buffer->GetBuffer(), VK_ACCESS_HOST_WRITE_BIT,
- VK_ACCESS_SHADER_READ_BIT, texel_buffer_offset, total_upload_size,
- VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
-
- // Determine uniforms.
- PushConstants constants = {
- {width, height},
- {aligned_width, aligned_height},
- texel_buffer_offset / bytes_per_buffer_elem,
- row_stride / bytes_per_buffer_elem,
- static_cast<u32>((texel_buffer_offset + palette_offset) / sizeof(u16))};
-
- // Determine view to use for texel buffers.
- VkBufferView data_view = VK_NULL_HANDLE;
- switch (iter->second.base_info->buffer_format)
- {
- case TextureConversionShaderTiled::BUFFER_FORMAT_R8_UINT:
- data_view = m_texel_buffer_view_r8_uint;
- break;
- case TextureConversionShaderTiled::BUFFER_FORMAT_R16_UINT:
- data_view = m_texel_buffer_view_r16_uint;
- break;
- case TextureConversionShaderTiled::BUFFER_FORMAT_R32G32_UINT:
- data_view = m_texel_buffer_view_r32g32_uint;
- break;
- case TextureConversionShaderTiled::BUFFER_FORMAT_RGBA8_UINT:
- data_view = m_texel_buffer_view_rgba8_uint;
- break;
- default:
- break;
- }
-
- // Dispatch compute to temporary texture.
- ComputeShaderDispatcher dispatcher(command_buffer,
- g_object_cache->GetPipelineLayout(PIPELINE_LAYOUT_COMPUTE),
- iter->second.compute_shader);
- m_decoding_texture->TransitionToLayout(command_buffer, Texture2D::ComputeImageLayout::WriteOnly);
- dispatcher.SetPushConstants(&constants, sizeof(constants));
- dispatcher.SetStorageImage(m_decoding_texture->GetView(), m_decoding_texture->GetLayout());
- dispatcher.SetTexelBuffer(0, data_view);
- if (has_palette)
- dispatcher.SetTexelBuffer(1, m_texel_buffer_view_r16_uint);
- auto groups = TextureConversionShaderTiled::GetDispatchCount(iter->second.base_info,
- aligned_width, aligned_height);
- dispatcher.Dispatch(groups.first, groups.second, 1);
-
- // Copy from temporary texture to final destination.
- Texture2D* vulkan_tex_identifier = destination_texture->GetRawTexIdentifier();
- m_decoding_texture->TransitionToLayout(command_buffer, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
- vulkan_tex_identifier->TransitionToLayout(command_buffer, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
- VkImageCopy image_copy = {{VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
- {0, 0, 0},
- {VK_IMAGE_ASPECT_COLOR_BIT, dst_level, 0, 1},
- {0, 0, 0},
- {width, height, 1}};
- vkCmdCopyImage(command_buffer, m_decoding_texture->GetImage(),
- VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, vulkan_tex_identifier->GetImage(),
- VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &image_copy);
-}
-
-bool TextureConverter::CreateTexelBuffer()
-{
- // Prefer an 8MB buffer if possible, but use less if the device doesn't support this.
- // This buffer is potentially going to be addressed as R8s in the future, so we assume
- // that one element is one byte.
- m_texel_buffer_size =
- std::min(TEXTURE_CONVERSION_TEXEL_BUFFER_SIZE,
- static_cast<size_t>(g_vulkan_context->GetDeviceLimits().maxTexelBufferElements));
-
- m_texel_buffer = StreamBuffer::Create(VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT,
- m_texel_buffer_size, m_texel_buffer_size);
- if (!m_texel_buffer)
- return false;
-
- // Create views of the formats that we will be using.
- m_texel_buffer_view_r8_uint = CreateTexelBufferView(VK_FORMAT_R8_UINT);
- m_texel_buffer_view_r16_uint = CreateTexelBufferView(VK_FORMAT_R16_UINT);
- m_texel_buffer_view_r32g32_uint = CreateTexelBufferView(VK_FORMAT_R32G32_UINT);
- m_texel_buffer_view_rgba8_unorm = CreateTexelBufferView(VK_FORMAT_R8G8B8A8_UNORM);
- m_texel_buffer_view_rgba8_uint = CreateTexelBufferView(VK_FORMAT_R8G8B8A8_UINT);
- return m_texel_buffer_view_r8_uint != VK_NULL_HANDLE &&
- m_texel_buffer_view_r16_uint != VK_NULL_HANDLE &&
- m_texel_buffer_view_r32g32_uint != VK_NULL_HANDLE &&
- m_texel_buffer_view_rgba8_unorm != VK_NULL_HANDLE &&
- m_texel_buffer_view_rgba8_uint != VK_NULL_HANDLE;
-}
-
-VkBufferView TextureConverter::CreateTexelBufferView(VkFormat format) const
-{
- // Create a view of the whole buffer, we'll offset our texel load into it
- VkBufferViewCreateInfo view_info = {
- VK_STRUCTURE_TYPE_BUFFER_VIEW_CREATE_INFO, // VkStructureType sType
- nullptr, // const void* pNext
- 0, // VkBufferViewCreateFlags flags
- m_texel_buffer->GetBuffer(), // VkBuffer buffer
- format, // VkFormat format
- 0, // VkDeviceSize offset
- m_texel_buffer_size // VkDeviceSize range
- };
-
- VkBufferView view;
- VkResult res = vkCreateBufferView(g_vulkan_context->GetDevice(), &view_info, nullptr, &view);
- if (res != VK_SUCCESS)
- {
- LOG_VULKAN_ERROR(res, "vkCreateBufferView failed: ");
- return VK_NULL_HANDLE;
- }
-
- return view;
-}
-
-bool TextureConverter::CompilePaletteConversionShaders()
-{
- static const char PALETTE_CONVERSION_FRAGMENT_SHADER_SOURCE[] = R"(
- layout(std140, push_constant) uniform PCBlock
- {
- float multiplier;
- int texture_buffer_offset;
- } PC;
-
- SAMPLER_BINDING(0) uniform sampler2DArray samp0;
- TEXEL_BUFFER_BINDING(0) uniform usamplerBuffer samp1;
-
- layout(location = 0) in vec3 f_uv0;
- layout(location = 0) out vec4 ocol0;
-
- int Convert3To8(int v)
- {
- // Swizzle bits: 00000123 -> 12312312
- return (v << 5) | (v << 2) | (v >> 1);
- }
- int Convert4To8(int v)
- {
- // Swizzle bits: 00001234 -> 12341234
- return (v << 4) | v;
- }
- int Convert5To8(int v)
- {
- // Swizzle bits: 00012345 -> 12345123
- return (v << 3) | (v >> 2);
- }
- int Convert6To8(int v)
- {
- // Swizzle bits: 00123456 -> 12345612
- return (v << 2) | (v >> 4);
- }
- float4 DecodePixel_RGB5A3(int val)
- {
- int r,g,b,a;
- if ((val&0x8000) > 0)
- {
- r=Convert5To8((val>>10) & 0x1f);
- g=Convert5To8((val>>5 ) & 0x1f);
- b=Convert5To8((val ) & 0x1f);
- a=0xFF;
- }
- else
- {
- a=Convert3To8((val>>12) & 0x7);
- r=Convert4To8((val>>8 ) & 0xf);
- g=Convert4To8((val>>4 ) & 0xf);
- b=Convert4To8((val ) & 0xf);
- }
- return float4(r, g, b, a) / 255.0;
- }
- float4 DecodePixel_RGB565(int val)
- {
- int r, g, b, a;
- r = Convert5To8((val >> 11) & 0x1f);
- g = Convert6To8((val >> 5) & 0x3f);
- b = Convert5To8((val) & 0x1f);
- a = 0xFF;
- return float4(r, g, b, a) / 255.0;
- }
- float4 DecodePixel_IA8(int val)
- {
- int i = val & 0xFF;
- int a = val >> 8;
- return float4(i, i, i, a) / 255.0;
- }
- void main()
- {
- int src = int(round(texture(samp0, f_uv0).r * PC.multiplier));
- src = int(texelFetch(samp1, src + PC.texture_buffer_offset).r);
- src = ((src << 8) & 0xFF00) | (src >> 8);
- ocol0 = DECODE(src);
- }
-
- )";
-
- std::string palette_ia8_program = StringFromFormat("%s\n%s", "#define DECODE DecodePixel_IA8",
- PALETTE_CONVERSION_FRAGMENT_SHADER_SOURCE);
- std::string palette_rgb565_program = StringFromFormat(
- "%s\n%s", "#define DECODE DecodePixel_RGB565", PALETTE_CONVERSION_FRAGMENT_SHADER_SOURCE);
- std::string palette_rgb5a3_program = StringFromFormat(
- "%s\n%s", "#define DECODE DecodePixel_RGB5A3", PALETTE_CONVERSION_FRAGMENT_SHADER_SOURCE);
-
- m_palette_conversion_shaders[static_cast<int>(TLUTFormat::IA8)] =
- Util::CompileAndCreateFragmentShader(palette_ia8_program);
- m_palette_conversion_shaders[static_cast<int>(TLUTFormat::RGB565)] =
- Util::CompileAndCreateFragmentShader(palette_rgb565_program);
- m_palette_conversion_shaders[static_cast<int>(TLUTFormat::RGB5A3)] =
- Util::CompileAndCreateFragmentShader(palette_rgb5a3_program);
-
- return m_palette_conversion_shaders[static_cast<int>(TLUTFormat::IA8)] != VK_NULL_HANDLE &&
- m_palette_conversion_shaders[static_cast<int>(TLUTFormat::RGB565)] != VK_NULL_HANDLE &&
- m_palette_conversion_shaders[static_cast<int>(TLUTFormat::RGB5A3)] != VK_NULL_HANDLE;
-}
-
-VkShaderModule TextureConverter::CompileEncodingShader(const EFBCopyParams& params)
-{
- const char* shader =
- TextureConversionShaderTiled::GenerateEncodingShader(params, APIType::Vulkan);
- VkShaderModule module = Util::CompileAndCreateFragmentShader(shader);
- if (module == VK_NULL_HANDLE)
- PanicAlert("Failed to compile texture encoding shader.");
-
- return module;
-}
-
-VkShaderModule TextureConverter::GetEncodingShader(const EFBCopyParams& params)
-{
- auto iter = m_encoding_shaders.find(params);
- if (iter != m_encoding_shaders.end())
- return iter->second;
-
- VkShaderModule shader = CompileEncodingShader(params);
- m_encoding_shaders.emplace(params, shader);
- return shader;
-}
-
-bool TextureConverter::CreateEncodingTexture()
-{
- m_encoding_render_texture = g_renderer->CreateTexture(TextureCache::GetEncodingTextureConfig());
- return m_encoding_render_texture != nullptr;
-}
-
-bool TextureConverter::CreateDecodingTexture()
-{
- m_decoding_texture = Texture2D::Create(
- DECODING_TEXTURE_WIDTH, DECODING_TEXTURE_HEIGHT, 1, 1, VK_FORMAT_R8G8B8A8_UNORM,
- VK_SAMPLE_COUNT_1_BIT, VK_IMAGE_VIEW_TYPE_2D_ARRAY, VK_IMAGE_TILING_OPTIMAL,
- VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT |
- VK_IMAGE_USAGE_TRANSFER_SRC_BIT);
- if (!m_decoding_texture)
- return false;
-
- VkClearColorValue clear_value = {{0.0f, 0.0f, 0.0f, 1.0f}};
- VkImageSubresourceRange clear_range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
- m_decoding_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentInitCommandBuffer(),
- VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
- vkCmdClearColorImage(g_command_buffer_mgr->GetCurrentInitCommandBuffer(),
- m_decoding_texture->GetImage(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
- &clear_value, 1, &clear_range);
- return true;
-}
-} // namespace Vulkan
diff --git a/Source/Core/VideoBackends/Vulkan/TextureConverter.h b/Source/Core/VideoBackends/Vulkan/TextureConverter.h
deleted file mode 100644
index 9c035296b2..0000000000
--- a/Source/Core/VideoBackends/Vulkan/TextureConverter.h
+++ /dev/null
@@ -1,109 +0,0 @@
-// Copyright 2016 Dolphin Emulator Project
-// Licensed under GPLv2+
-// Refer to the license.txt file included.
-
-#pragma once
-
-#include <array>
-#include <map>
-#include <memory>
-#include <utility>
-
-#include "Common/CommonTypes.h"
-#include "VideoBackends/Vulkan/StreamBuffer.h"
-#include "VideoBackends/Vulkan/TextureCache.h"
-#include "VideoCommon/TextureConversionShader.h"
-#include "VideoCommon/TextureDecoder.h"
-#include "VideoCommon/VideoCommon.h"
-
-class AbstractTexture;
-class AbstractStagingTexture;
-
-namespace Vulkan
-{
-class Texture2D;
-class VKTexture;
-
-class TextureConverter
-{
-public:
- TextureConverter();
- ~TextureConverter();
-
- bool Initialize();
-
- // Applies palette to dst_entry, using indices from src_entry.
- void ConvertTexture(TextureCacheBase::TCacheEntry* dst_entry,
- TextureCache::TCacheEntry* src_entry, const void* palette,
- TLUTFormat palette_format);
-
- // Uses an encoding shader to copy src_texture to dest.
- void EncodeTextureToMemory(
- VkImageView src_texture, AbstractStagingTexture* dest, const EFBCopyParams& params,
- u32 native_width, u32 bytes_per_row, u32 num_blocks_y, u32 memory_stride,
- const EFBRectangle& src_rect, bool scale_by_half, float y_scale, float gamma, bool clamp_top,
- bool clamp_bottom, const TextureCacheBase::CopyFilterCoefficientArray& filter_coefficients);
-
- bool SupportsTextureDecoding(TextureFormat format, TLUTFormat palette_format);
- void DecodeTexture(VkCommandBuffer command_buffer, TextureCache::TCacheEntry* entry,
- u32 dst_level, const u8* data, size_t data_size, TextureFormat format,
- u32 width, u32 height, u32 aligned_width, u32 aligned_height, u32 row_stride,
- const u8* palette, TLUTFormat palette_format);
-
-private:
- static const size_t NUM_PALETTE_CONVERSION_SHADERS = 3;
-
- // Maximum size of a texture based on BP registers.
- static const u32 DECODING_TEXTURE_WIDTH = 1024;
- static const u32 DECODING_TEXTURE_HEIGHT = 1024;
-
- bool CreateTexelBuffer();
- VkBufferView CreateTexelBufferView(VkFormat format) const;
-
- bool CompilePaletteConversionShaders();
-
- VkShaderModule CompileEncodingShader(const EFBCopyParams& params);
- VkShaderModule GetEncodingShader(const EFBCopyParams& params);
-
- bool CreateEncodingTexture();
- bool CreateDecodingTexture();
-
- // Allocates storage in the texel command buffer of the specified size.
- // If the buffer does not have enough space, executes the current command buffer and tries again.
- // If this is done, g_command_buffer_mgr->GetCurrentCommandBuffer() will return a different value,
- // so it always should be re-obtained after calling this method.
- // Once the data copy is done, call m_texel_buffer->CommitMemory(size).
- bool ReserveTexelBufferStorage(size_t size, size_t alignment);
-
- // Returns the command buffer that the texture conversion should occur in for the given texture.
- // This can be the initialization/copy command buffer, or the drawing command buffer.
- VkCommandBuffer GetCommandBufferForTextureConversion(const TextureCache::TCacheEntry* src_entry);
-
- // Shared between conversion types
- std::unique_ptr<StreamBuffer> m_texel_buffer;
- VkBufferView m_texel_buffer_view_r8_uint = VK_NULL_HANDLE;
- VkBufferView m_texel_buffer_view_r16_uint = VK_NULL_HANDLE;
- VkBufferView m_texel_buffer_view_r32g32_uint = VK_NULL_HANDLE;
- VkBufferView m_texel_buffer_view_rgba8_uint = VK_NULL_HANDLE;
- VkBufferView m_texel_buffer_view_rgba8_unorm = VK_NULL_HANDLE;
- size_t m_texel_buffer_size = 0;
-
- // Palette conversion - taking an indexed texture and applying palette
- std::array<VkShaderModule, NUM_PALETTE_CONVERSION_SHADERS> m_palette_conversion_shaders = {};
-
- // Texture encoding - RGBA8->GX format in memory
- std::map<EFBCopyParams, VkShaderModule> m_encoding_shaders;
- std::unique_ptr<AbstractTexture> m_encoding_render_texture;
-
- // Texture decoding - GX format in memory->RGBA8
- struct TextureDecodingPipeline
- {
- const TextureConversionShaderTiled::DecodingShaderInfo* base_info;
- VkShaderModule compute_shader;
- bool valid;
- };
- std::map<std::pair<TextureFormat, TLUTFormat>, TextureDecodingPipeline> m_decoding_pipelines;
- std::unique_ptr<Texture2D> m_decoding_texture;
-};
-
-} // namespace Vulkan
diff --git a/Source/Core/VideoBackends/Vulkan/Util.cpp b/Source/Core/VideoBackends/Vulkan/Util.cpp
deleted file mode 100644
index 35c9bcfbaf..0000000000
--- a/Source/Core/VideoBackends/Vulkan/Util.cpp
+++ /dev/null
@@ -1,925 +0,0 @@
-// Copyright 2016 Dolphin Emulator Project
-// Licensed under GPLv2+
-// Refer to the license.txt file included.
-
-#include "VideoBackends/Vulkan/Util.h"
-
-#include "Common/Align.h"
-#include "Common/Assert.h"
-#include "Common/CommonFuncs.h"
-#include "Common/MathUtil.h"
-#include "Common/MsgHandler.h"
-
-#include "VideoBackends/Vulkan/CommandBufferManager.h"
-#include "VideoBackends/Vulkan/ObjectCache.h"
-#include "VideoBackends/Vulkan/ShaderCache.h"
-#include "VideoBackends/Vulkan/ShaderCompiler.h"
-#include "VideoBackends/Vulkan/StateTracker.h"
-#include "VideoBackends/Vulkan/StreamBuffer.h"
-#include "VideoBackends/Vulkan/VulkanContext.h"
-
-namespace Vulkan
-{
-namespace Util
-{
-size_t AlignBufferOffset(size_t offset, size_t alignment)
-{
- // Assume an offset of zero is already aligned to a value larger than alignment.
- if (offset == 0)
- return 0;
-
- return Common::AlignUp(offset, alignment);
-}
-
-u32 MakeRGBA8Color(float r, float g, float b, float a)
-{
- return (static_cast<u32>(MathUtil::Clamp(static_cast<int>(r * 255.0f), 0, 255)) << 0) |
- (static_cast<u32>(MathUtil::Clamp(static_cast<int>(g * 255.0f), 0, 255)) << 8) |
- (static_cast<u32>(MathUtil::Clamp(static_cast<int>(b * 255.0f), 0, 255)) << 16) |
- (static_cast<u32>(MathUtil::Clamp(static_cast<int>(a * 255.0f), 0, 255)) << 24);
-}
-
-bool IsDepthFormat(VkFormat format)
-{
- switch (format)
- {
- case VK_FORMAT_D16_UNORM:
- case VK_FORMAT_D16_UNORM_S8_UINT:
- case VK_FORMAT_D24_UNORM_S8_UINT:
- case VK_FORMAT_D32_SFLOAT:
- case VK_FORMAT_D32_SFLOAT_S8_UINT:
- return true;
- default:
- return false;
- }
-}
-
-bool IsCompressedFormat(VkFormat format)
-{
- switch (format)
- {
- case VK_FORMAT_BC1_RGBA_UNORM_BLOCK:
- case VK_FORMAT_BC2_UNORM_BLOCK:
- case VK_FORMAT_BC3_UNORM_BLOCK:
- case VK_FORMAT_BC7_UNORM_BLOCK:
- return true;
-
- default:
- return false;
- }
-}
-
-VkFormat GetLinearFormat(VkFormat format)
-{
- switch (format)
- {
- case VK_FORMAT_R8_SRGB:
- return VK_FORMAT_R8_UNORM;
- case VK_FORMAT_R8G8_SRGB:
- return VK_FORMAT_R8G8_UNORM;
- case VK_FORMAT_R8G8B8_SRGB:
- return VK_FORMAT_R8G8B8_UNORM;
- case VK_FORMAT_R8G8B8A8_SRGB:
- return VK_FORMAT_R8G8B8A8_UNORM;
- case VK_FORMAT_B8G8R8_SRGB:
- return VK_FORMAT_B8G8R8_UNORM;
- case VK_FORMAT_B8G8R8A8_SRGB:
- return VK_FORMAT_B8G8R8A8_UNORM;
- default:
- return format;
- }
-}
-
-VkFormat GetVkFormatForHostTextureFormat(AbstractTextureFormat format)
-{
- switch (format)
- {
- case AbstractTextureFormat::DXT1:
- return VK_FORMAT_BC1_RGBA_UNORM_BLOCK;
-
- case AbstractTextureFormat::DXT3:
- return VK_FORMAT_BC2_UNORM_BLOCK;
-
- case AbstractTextureFormat::DXT5:
- return VK_FORMAT_BC3_UNORM_BLOCK;
-
- case AbstractTextureFormat::BPTC:
- return VK_FORMAT_BC7_UNORM_BLOCK;
-
- case AbstractTextureFormat::RGBA8:
- return VK_FORMAT_R8G8B8A8_UNORM;
-
- case AbstractTextureFormat::BGRA8:
- return VK_FORMAT_B8G8R8A8_UNORM;
-
- case AbstractTextureFormat::R16:
- return VK_FORMAT_R16_UNORM;
-
- case AbstractTextureFormat::D16:
- return VK_FORMAT_D16_UNORM;
-
- case AbstractTextureFormat::D24_S8:
- return VK_FORMAT_D24_UNORM_S8_UINT;
-
- case AbstractTextureFormat::R32F:
- return VK_FORMAT_R32_SFLOAT;
-
- case AbstractTextureFormat::D32F:
- return VK_FORMAT_D32_SFLOAT;
-
- case AbstractTextureFormat::D32F_S8:
- return VK_FORMAT_D32_SFLOAT_S8_UINT;
-
- case AbstractTextureFormat::Undefined:
- return VK_FORMAT_UNDEFINED;
-
- default:
- PanicAlert("Unhandled texture format.");
- return VK_FORMAT_R8G8B8A8_UNORM;
- }
-}
-
-VkImageAspectFlags GetImageAspectForFormat(VkFormat format)
-{
- switch (format)
- {
- case VK_FORMAT_D16_UNORM_S8_UINT:
- case VK_FORMAT_D24_UNORM_S8_UINT:
- case VK_FORMAT_D32_SFLOAT_S8_UINT:
- return VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;
-
- case VK_FORMAT_D16_UNORM:
- case VK_FORMAT_D32_SFLOAT:
- return VK_IMAGE_ASPECT_DEPTH_BIT;
-
- default:
- return VK_IMAGE_ASPECT_COLOR_BIT;
- }
-}
-
-u32 GetTexelSize(VkFormat format)
-{
- // Only contains pixel formats we use.
- switch (format)
- {
- case VK_FORMAT_R32_SFLOAT:
- return 4;
-
- case VK_FORMAT_D32_SFLOAT:
- return 4;
-
- case VK_FORMAT_R8G8B8A8_UNORM:
- return 4;
-
- case VK_FORMAT_B8G8R8A8_UNORM:
- return 4;
-
- case VK_FORMAT_BC1_RGBA_UNORM_BLOCK:
- return 8;
-
- case VK_FORMAT_BC2_UNORM_BLOCK:
- case VK_FORMAT_BC3_UNORM_BLOCK:
- case VK_FORMAT_BC7_UNORM_BLOCK:
- return 16;
-
- default:
- PanicAlert("Unhandled pixel format");
- return 1;
- }
-}
-
-u32 GetBlockSize(VkFormat format)
-{
- switch (format)
- {
- case VK_FORMAT_BC1_RGBA_UNORM_BLOCK:
- case VK_FORMAT_BC2_UNORM_BLOCK:
- case VK_FORMAT_BC3_UNORM_BLOCK:
- case VK_FORMAT_BC7_UNORM_BLOCK:
- return 4;
-
- default:
- return 1;
- }
-}
-
-VkRect2D ClampRect2D(const VkRect2D& rect, u32 width, u32 height)
-{
- VkRect2D out;
- out.offset.x = MathUtil::Clamp(rect.offset.x, 0, static_cast<int32_t>(width - 1));
- out.offset.y = MathUtil::Clamp(rect.offset.y, 0, static_cast<int32_t>(height - 1));
- out.extent.width = std::min(rect.extent.width, width - static_cast<uint32_t>(rect.offset.x));
- out.extent.height = std::min(rect.extent.height, height - static_cast<uint32_t>(rect.offset.y));
- return out;
-}
-
-VkBlendFactor GetAlphaBlendFactor(VkBlendFactor factor)
-{
- switch (factor)
- {
- case VK_BLEND_FACTOR_SRC_COLOR:
- return VK_BLEND_FACTOR_SRC_ALPHA;
- case VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR:
- return VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
- case VK_BLEND_FACTOR_DST_COLOR:
- return VK_BLEND_FACTOR_DST_ALPHA;
- case VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR:
- return VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA;
- default:
- return factor;
- }
-}
-
-void SetViewportAndScissor(VkCommandBuffer command_buffer, int x, int y, int width, int height,
- float min_depth /*= 0.0f*/, float max_depth /*= 1.0f*/)
-{
- VkViewport viewport = {static_cast<float>(x),
- static_cast<float>(y),
- static_cast<float>(width),
- static_cast<float>(height),
- min_depth,
- max_depth};
-
- VkRect2D scissor = {{x, y}, {static_cast<uint32_t>(width), static_cast<uint32_t>(height)}};
-
- vkCmdSetViewport(command_buffer, 0, 1, &viewport);
- vkCmdSetScissor(command_buffer, 0, 1, &scissor);
-}
-
-void BufferMemoryBarrier(VkCommandBuffer command_buffer, VkBuffer buffer,
- VkAccessFlags src_access_mask, VkAccessFlags dst_access_mask,
- VkDeviceSize offset, VkDeviceSize size,
- VkPipelineStageFlags src_stage_mask, VkPipelineStageFlags dst_stage_mask)
-{
- VkBufferMemoryBarrier buffer_info = {
- VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, // VkStructureType sType
- nullptr, // const void* pNext
- src_access_mask, // VkAccessFlags srcAccessMask
- dst_access_mask, // VkAccessFlags dstAccessMask
- VK_QUEUE_FAMILY_IGNORED, // uint32_t srcQueueFamilyIndex
- VK_QUEUE_FAMILY_IGNORED, // uint32_t dstQueueFamilyIndex
- buffer, // VkBuffer buffer
- offset, // VkDeviceSize offset
- size // VkDeviceSize size
- };
-
- vkCmdPipelineBarrier(command_buffer, src_stage_mask, dst_stage_mask, 0, 0, nullptr, 1,
- &buffer_info, 0, nullptr);
-}
-
-void ExecuteCurrentCommandsAndRestoreState(bool execute_off_thread, bool wait_for_completion)
-{
- StateTracker::GetInstance()->EndRenderPass();
- g_command_buffer_mgr->ExecuteCommandBuffer(execute_off_thread, wait_for_completion);
- StateTracker::GetInstance()->InvalidateDescriptorSets();
- StateTracker::GetInstance()->InvalidateConstants();
- StateTracker::GetInstance()->SetPendingRebind();
-}
-
-VkShaderModule CreateShaderModule(const u32* spv, size_t spv_word_count)
-{
- VkShaderModuleCreateInfo info = {};
- info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
- info.codeSize = spv_word_count * sizeof(u32);
- info.pCode = spv;
-
- VkShaderModule module;
- VkResult res = vkCreateShaderModule(g_vulkan_context->GetDevice(), &info, nullptr, &module);
- if (res != VK_SUCCESS)
- {
- LOG_VULKAN_ERROR(res, "vkCreateShaderModule failed: ");
- return VK_NULL_HANDLE;
- }
-
- return module;
-}
-
-VkShaderModule CompileAndCreateVertexShader(const std::string& source_code)
-{
- ShaderCompiler::SPIRVCodeVector code;
- if (!ShaderCompiler::CompileVertexShader(&code, source_code.c_str(), source_code.length()))
- return VK_NULL_HANDLE;
-
- return CreateShaderModule(code.data(), code.size());
-}
-
-VkShaderModule CompileAndCreateGeometryShader(const std::string& source_code)
-{
- ShaderCompiler::SPIRVCodeVector code;
- if (!ShaderCompiler::CompileGeometryShader(&code, source_code.c_str(), source_code.length()))
- return VK_NULL_HANDLE;
-
- return CreateShaderModule(code.data(), code.size());
-}
-
-VkShaderModule CompileAndCreateFragmentShader(const std::string& source_code)
-{
- ShaderCompiler::SPIRVCodeVector code;
- if (!ShaderCompiler::CompileFragmentShader(&code, source_code.c_str(), source_code.length()))
- return VK_NULL_HANDLE;
-
- return CreateShaderModule(code.data(), code.size());
-}
-
-VkShaderModule CompileAndCreateComputeShader(const std::string& source_code)
-{
- ShaderCompiler::SPIRVCodeVector code;
- if (!ShaderCompiler::CompileComputeShader(&code, source_code.c_str(), source_code.length()))
- return VK_NULL_HANDLE;
-
- return CreateShaderModule(code.data(), code.size());
-}
-
-} // namespace Util
-
-UtilityShaderDraw::UtilityShaderDraw(VkCommandBuffer command_buffer,
- VkPipelineLayout pipeline_layout, VkRenderPass render_pass,
- VkShaderModule vertex_shader, VkShaderModule geometry_shader,
- VkShaderModule pixel_shader, PrimitiveType primitive)
- : m_command_buffer(command_buffer)
-{
- // Populate minimal pipeline state
- m_pipeline_info.vertex_format = g_object_cache->GetUtilityShaderVertexFormat();
- m_pipeline_info.pipeline_layout = pipeline_layout;
- m_pipeline_info.render_pass = render_pass;
- m_pipeline_info.vs = vertex_shader;
- m_pipeline_info.gs = geometry_shader;
- m_pipeline_info.ps = pixel_shader;
- m_pipeline_info.rasterization_state.hex = RenderState::GetNoCullRasterizationState().hex;
- m_pipeline_info.rasterization_state.primitive = primitive;
- m_pipeline_info.depth_state.hex = RenderState::GetNoDepthTestingDepthStencilState().hex;
- m_pipeline_info.blend_state.hex = RenderState::GetNoBlendingBlendState().hex;
- m_pipeline_info.multisampling_state.per_sample_shading = false;
- m_pipeline_info.multisampling_state.samples = 1;
-}
-
-UtilityShaderVertex* UtilityShaderDraw::ReserveVertices(size_t count)
-{
- if (!g_object_cache->GetUtilityShaderVertexBuffer()->ReserveMemory(
- sizeof(UtilityShaderVertex) * count, sizeof(UtilityShaderVertex), true, true, true))
- PanicAlert("Failed to allocate space for vertices in backend shader");
-
- m_vertex_buffer = g_object_cache->GetUtilityShaderVertexBuffer()->GetBuffer();
- m_vertex_buffer_offset = g_object_cache->GetUtilityShaderVertexBuffer()->GetCurrentOffset();
-
- return reinterpret_cast<UtilityShaderVertex*>(
- g_object_cache->GetUtilityShaderVertexBuffer()->GetCurrentHostPointer());
-}
-
-void UtilityShaderDraw::CommitVertices(size_t count)
-{
- g_object_cache->GetUtilityShaderVertexBuffer()->CommitMemory(sizeof(UtilityShaderVertex) * count);
- m_vertex_count = static_cast<uint32_t>(count);
-}
-
-void UtilityShaderDraw::UploadVertices(UtilityShaderVertex* vertices, size_t count)
-{
- UtilityShaderVertex* upload_vertices = ReserveVertices(count);
- memcpy(upload_vertices, vertices, sizeof(UtilityShaderVertex) * count);
- CommitVertices(count);
-}
-
-u8* UtilityShaderDraw::AllocateVSUniforms(size_t size)
-{
- if (!g_object_cache->GetUtilityShaderUniformBuffer()->ReserveMemory(
- size, g_vulkan_context->GetUniformBufferAlignment(), true, true, true))
- PanicAlert("Failed to allocate util uniforms");
-
- return g_object_cache->GetUtilityShaderUniformBuffer()->GetCurrentHostPointer();
-}
-
-void UtilityShaderDraw::CommitVSUniforms(size_t size)
-{
- m_vs_uniform_buffer.buffer = g_object_cache->GetUtilityShaderUniformBuffer()->GetBuffer();
- m_vs_uniform_buffer.offset = 0;
- m_vs_uniform_buffer.range = size;
- m_ubo_offsets[UBO_DESCRIPTOR_SET_BINDING_VS] =
- static_cast<uint32_t>(g_object_cache->GetUtilityShaderUniformBuffer()->GetCurrentOffset());
-
- g_object_cache->GetUtilityShaderUniformBuffer()->CommitMemory(size);
-}
-
-u8* UtilityShaderDraw::AllocatePSUniforms(size_t size)
-{
- if (!g_object_cache->GetUtilityShaderUniformBuffer()->ReserveMemory(
- size, g_vulkan_context->GetUniformBufferAlignment(), true, true, true))
- PanicAlert("Failed to allocate util uniforms");
-
- return g_object_cache->GetUtilityShaderUniformBuffer()->GetCurrentHostPointer();
-}
-
-void UtilityShaderDraw::CommitPSUniforms(size_t size)
-{
- m_ps_uniform_buffer.buffer = g_object_cache->GetUtilityShaderUniformBuffer()->GetBuffer();
- m_ps_uniform_buffer.offset = 0;
- m_ps_uniform_buffer.range = size;
- m_ubo_offsets[UBO_DESCRIPTOR_SET_BINDING_PS] =
- static_cast<uint32_t>(g_object_cache->GetUtilityShaderUniformBuffer()->GetCurrentOffset());
-
- g_object_cache->GetUtilityShaderUniformBuffer()->CommitMemory(size);
-}
-
-void UtilityShaderDraw::SetPushConstants(const void* data, size_t data_size)
-{
- ASSERT(static_cast<u32>(data_size) < PUSH_CONSTANT_BUFFER_SIZE);
-
- vkCmdPushConstants(m_command_buffer, m_pipeline_info.pipeline_layout,
- VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0,
- static_cast<u32>(data_size), data);
-}
-
-void UtilityShaderDraw::SetPSSampler(size_t index, VkImageView view, VkSampler sampler)
-{
- m_ps_samplers[index].sampler = sampler;
- m_ps_samplers[index].imageView = view;
- m_ps_samplers[index].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
-}
-
-void UtilityShaderDraw::SetPSTexelBuffer(VkBufferView view)
-{
- // Should only be used with the texture conversion pipeline layout.
- ASSERT(m_pipeline_info.pipeline_layout ==
- g_object_cache->GetPipelineLayout(PIPELINE_LAYOUT_TEXTURE_CONVERSION));
-
- m_ps_texel_buffer = view;
-}
-
-void UtilityShaderDraw::SetRasterizationState(const RasterizationState& state)
-{
- m_pipeline_info.rasterization_state.hex = state.hex;
-}
-
-void UtilityShaderDraw::SetMultisamplingState(const MultisamplingState& state)
-{
- m_pipeline_info.multisampling_state.hex = state.hex;
-}
-
-void UtilityShaderDraw::SetDepthState(const DepthState& state)
-{
- m_pipeline_info.depth_state.hex = state.hex;
-}
-
-void UtilityShaderDraw::SetBlendState(const BlendingState& state)
-{
- m_pipeline_info.blend_state.hex = state.hex;
-}
-
-void UtilityShaderDraw::BeginRenderPass(VkFramebuffer framebuffer, const VkRect2D& region,
- const VkClearValue* clear_value)
-{
- VkRenderPassBeginInfo begin_info = {VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO,
- nullptr,
- m_pipeline_info.render_pass,
- framebuffer,
- region,
- clear_value ? 1u : 0u,
- clear_value};
-
- vkCmdBeginRenderPass(m_command_buffer, &begin_info, VK_SUBPASS_CONTENTS_INLINE);
-}
-
-void UtilityShaderDraw::EndRenderPass()
-{
- vkCmdEndRenderPass(m_command_buffer);
-}
-
-void UtilityShaderDraw::Draw()
-{
- BindVertexBuffer();
- BindDescriptors();
- if (!BindPipeline())
- return;
-
- vkCmdDraw(m_command_buffer, m_vertex_count, 1, 0, 0);
-}
-
-void UtilityShaderDraw::DrawQuad(int x, int y, int width, int height, float z)
-{
- UtilityShaderVertex vertices[4];
- vertices[0].SetPosition(-1.0f, 1.0f, z);
- vertices[0].SetTextureCoordinates(0.0f, 1.0f);
- vertices[0].SetColor(1.0f, 1.0f, 1.0f, 1.0f);
- vertices[1].SetPosition(1.0f, 1.0f, z);
- vertices[1].SetTextureCoordinates(1.0f, 1.0f);
- vertices[1].SetColor(1.0f, 1.0f, 1.0f, 1.0f);
- vertices[2].SetPosition(-1.0f, -1.0f, z);
- vertices[2].SetTextureCoordinates(0.0f, 0.0f);
- vertices[2].SetColor(1.0f, 1.0f, 1.0f, 1.0f);
- vertices[3].SetPosition(1.0f, -1.0f, z);
- vertices[3].SetTextureCoordinates(1.0f, 0.0f);
- vertices[3].SetColor(1.0f, 1.0f, 1.0f, 1.0f);
-
- Util::SetViewportAndScissor(m_command_buffer, x, y, width, height);
- UploadVertices(vertices, ArraySize(vertices));
- Draw();
-}
-
-void UtilityShaderDraw::DrawQuad(int dst_x, int dst_y, int dst_width, int dst_height, int src_x,
- int src_y, int src_layer, int src_width, int src_height,
- int src_full_width, int src_full_height, float z)
-{
- float u0 = float(src_x) / float(src_full_width);
- float v0 = float(src_y) / float(src_full_height);
- float u1 = float(src_x + src_width) / float(src_full_width);
- float v1 = float(src_y + src_height) / float(src_full_height);
- float w = static_cast<float>(src_layer);
-
- UtilityShaderVertex vertices[4];
- vertices[0].SetPosition(-1.0f, 1.0f, z);
- vertices[0].SetTextureCoordinates(u0, v1, w);
- vertices[0].SetColor(1.0f, 1.0f, 1.0f, 1.0f);
- vertices[1].SetPosition(1.0f, 1.0f, z);
- vertices[1].SetTextureCoordinates(u1, v1, w);
- vertices[1].SetColor(1.0f, 1.0f, 1.0f, 1.0f);
- vertices[2].SetPosition(-1.0f, -1.0f, z);
- vertices[2].SetTextureCoordinates(u0, v0, w);
- vertices[2].SetColor(1.0f, 1.0f, 1.0f, 1.0f);
- vertices[3].SetPosition(1.0f, -1.0f, z);
- vertices[3].SetTextureCoordinates(u1, v0, w);
- vertices[3].SetColor(1.0f, 1.0f, 1.0f, 1.0f);
-
- Util::SetViewportAndScissor(m_command_buffer, dst_x, dst_y, dst_width, dst_height);
- UploadVertices(vertices, ArraySize(vertices));
- Draw();
-}
-
-void UtilityShaderDraw::DrawColoredQuad(int x, int y, int width, int height, float r, float g,
- float b, float a, float z)
-{
- return DrawColoredQuad(x, y, width, height, Util::MakeRGBA8Color(r, g, b, a), z);
-}
-
-void UtilityShaderDraw::DrawColoredQuad(int x, int y, int width, int height, u32 color, float z)
-{
- UtilityShaderVertex vertices[4];
- vertices[0].SetPosition(-1.0f, 1.0f, z);
- vertices[0].SetTextureCoordinates(0.0f, 1.0f);
- vertices[0].SetColor(color);
- vertices[1].SetPosition(1.0f, 1.0f, z);
- vertices[1].SetTextureCoordinates(1.0f, 1.0f);
- vertices[1].SetColor(color);
- vertices[2].SetPosition(-1.0f, -1.0f, z);
- vertices[2].SetTextureCoordinates(0.0f, 0.0f);
- vertices[2].SetColor(color);
- vertices[3].SetPosition(1.0f, -1.0f, z);
- vertices[3].SetTextureCoordinates(1.0f, 0.0f);
- vertices[3].SetColor(color);
-
- Util::SetViewportAndScissor(m_command_buffer, x, y, width, height);
- UploadVertices(vertices, ArraySize(vertices));
- Draw();
-}
-
-void UtilityShaderDraw::SetViewportAndScissor(int x, int y, int width, int height)
-{
- Util::SetViewportAndScissor(m_command_buffer, x, y, width, height, 0.0f, 1.0f);
-}
-
-void UtilityShaderDraw::DrawWithoutVertexBuffer(u32 vertex_count)
-{
- m_pipeline_info.vertex_format = nullptr;
-
- BindDescriptors();
- if (!BindPipeline())
- return;
-
- vkCmdDraw(m_command_buffer, vertex_count, 1, 0, 0);
-}
-
-void UtilityShaderDraw::BindVertexBuffer()
-{
- vkCmdBindVertexBuffers(m_command_buffer, 0, 1, &m_vertex_buffer, &m_vertex_buffer_offset);
-}
-
-void UtilityShaderDraw::BindDescriptors()
-{
- // TODO: This method is a mess, clean it up
- std::array<VkDescriptorSet, NUM_DESCRIPTOR_SET_BIND_POINTS> bind_descriptor_sets = {};
- std::array<VkWriteDescriptorSet, NUM_UBO_DESCRIPTOR_SET_BINDINGS + 1> set_writes = {};
- uint32_t num_set_writes = 0;
-
- VkDescriptorBufferInfo dummy_uniform_buffer = {
- g_object_cache->GetUtilityShaderUniformBuffer()->GetBuffer(), 0, 1};
-
- // uniform buffers
- if (m_vs_uniform_buffer.buffer != VK_NULL_HANDLE || m_ps_uniform_buffer.buffer != VK_NULL_HANDLE)
- {
- VkDescriptorSet set = g_command_buffer_mgr->AllocateDescriptorSet(
- g_object_cache->GetDescriptorSetLayout(DESCRIPTOR_SET_LAYOUT_PER_STAGE_UNIFORM_BUFFERS));
- if (set == VK_NULL_HANDLE)
- PanicAlert("Failed to allocate descriptor set for utility draw");
-
- set_writes[num_set_writes++] = {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
- nullptr,
- set,
- UBO_DESCRIPTOR_SET_BINDING_VS,
- 0,
- 1,
- VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC,
- nullptr,
- (m_vs_uniform_buffer.buffer != VK_NULL_HANDLE) ?
- &m_vs_uniform_buffer :
- &dummy_uniform_buffer,
- nullptr};
-
- if (g_vulkan_context->SupportsGeometryShaders())
- {
- set_writes[num_set_writes++] = {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
- nullptr,
- set,
- UBO_DESCRIPTOR_SET_BINDING_GS,
- 0,
- 1,
- VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC,
- nullptr,
- &dummy_uniform_buffer,
- nullptr};
- }
-
- set_writes[num_set_writes++] = {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
- nullptr,
- set,
- UBO_DESCRIPTOR_SET_BINDING_PS,
- 0,
- 1,
- VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC,
- nullptr,
- (m_ps_uniform_buffer.buffer != VK_NULL_HANDLE) ?
- &m_ps_uniform_buffer :
- &dummy_uniform_buffer,
- nullptr};
-
- bind_descriptor_sets[DESCRIPTOR_SET_BIND_POINT_UNIFORM_BUFFERS] = set;
- }
-
- // PS samplers
- size_t first_active_sampler;
- for (first_active_sampler = 0; first_active_sampler < NUM_PIXEL_SHADER_SAMPLERS;
- first_active_sampler++)
- {
- if (m_ps_samplers[first_active_sampler].imageView != VK_NULL_HANDLE &&
- m_ps_samplers[first_active_sampler].sampler != VK_NULL_HANDLE)
- {
- break;
- }
- }
-
- // Check if we have any at all, skip the binding process entirely if we don't
- if (first_active_sampler != NUM_PIXEL_SHADER_SAMPLERS)
- {
- // We need to fill it with non-empty images.
- for (size_t i = 0; i < NUM_PIXEL_SHADER_SAMPLERS; i++)
- {
- if (m_ps_samplers[i].imageView == VK_NULL_HANDLE)
- {
- m_ps_samplers[i].imageView = g_object_cache->GetDummyImageView();
- m_ps_samplers[i].sampler = g_object_cache->GetPointSampler();
- }
- }
-
- // Allocate a new descriptor set
- VkDescriptorSet set = g_command_buffer_mgr->AllocateDescriptorSet(
- g_object_cache->GetDescriptorSetLayout(DESCRIPTOR_SET_LAYOUT_PIXEL_SHADER_SAMPLERS));
- if (set == VK_NULL_HANDLE)
- PanicAlert("Failed to allocate descriptor set for utility draw");
-
- set_writes[num_set_writes++] = {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
- nullptr,
- set,
- 0,
- 0,
- static_cast<u32>(NUM_PIXEL_SHADER_SAMPLERS),
- VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
- m_ps_samplers.data(),
- nullptr,
- nullptr};
-
- bind_descriptor_sets[DESCRIPTOR_SET_BIND_POINT_PIXEL_SHADER_SAMPLERS] = set;
- }
-
- vkUpdateDescriptorSets(g_vulkan_context->GetDevice(), num_set_writes, set_writes.data(), 0,
- nullptr);
-
- if (m_ps_texel_buffer != VK_NULL_HANDLE)
- {
- // TODO: Handle case where this fails.
- // This'll only be when we do over say, 1024 allocations per frame, which shouldn't happen.
- // TODO: Execute the command buffer, reset render passes and then try again.
- VkDescriptorSet set = g_command_buffer_mgr->AllocateDescriptorSet(
- g_object_cache->GetDescriptorSetLayout(DESCRIPTOR_SET_LAYOUT_TEXEL_BUFFERS));
- if (set == VK_NULL_HANDLE)
- {
- PanicAlert("Failed to allocate texel buffer descriptor set for utility draw");
- return;
- }
-
- VkWriteDescriptorSet set_write = {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
- nullptr,
- set,
- 0,
- 0,
- 1,
- VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER,
- nullptr,
- nullptr,
- &m_ps_texel_buffer};
- vkUpdateDescriptorSets(g_vulkan_context->GetDevice(), 1, &set_write, 0, nullptr);
- bind_descriptor_sets[DESCRIPTOR_SET_BIND_POINT_STORAGE_OR_TEXEL_BUFFER] = set;
- }
-
- // Fast path when there are no gaps in the set bindings
- u32 bind_point_index;
- for (bind_point_index = 0; bind_point_index < NUM_DESCRIPTOR_SET_BIND_POINTS; bind_point_index++)
- {
- if (bind_descriptor_sets[bind_point_index] == VK_NULL_HANDLE)
- break;
- }
- if (bind_point_index > 0)
- {
- // Bind the contiguous sets, any others after any gaps will be handled below
- vkCmdBindDescriptorSets(m_command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS,
- m_pipeline_info.pipeline_layout, 0, bind_point_index,
- &bind_descriptor_sets[0], NUM_UBO_DESCRIPTOR_SET_BINDINGS,
- m_ubo_offsets.data());
- }
-
- // Handle any remaining sets
- for (u32 i = bind_point_index; i < NUM_DESCRIPTOR_SET_BIND_POINTS; i++)
- {
- if (bind_descriptor_sets[i] == VK_NULL_HANDLE)
- continue;
-
- // No need to worry about dynamic offsets here, since #0 will always be bound above.
- vkCmdBindDescriptorSets(m_command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS,
- m_pipeline_info.pipeline_layout, i, 1, &bind_descriptor_sets[i], 0,
- nullptr);
- }
-}
-
-bool UtilityShaderDraw::BindPipeline()
-{
- VkPipeline pipeline = g_shader_cache->GetPipeline(m_pipeline_info);
- if (pipeline == VK_NULL_HANDLE)
- {
- PanicAlert("Failed to get pipeline for backend shader draw");
- return false;
- }
-
- vkCmdBindPipeline(m_command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
- return true;
-}
-
-ComputeShaderDispatcher::ComputeShaderDispatcher(VkCommandBuffer command_buffer,
- VkPipelineLayout pipeline_layout,
- VkShaderModule compute_shader)
- : m_command_buffer(command_buffer)
-{
- // Populate minimal pipeline state
- m_pipeline_info.pipeline_layout = pipeline_layout;
- m_pipeline_info.cs = compute_shader;
-}
-
-u8* ComputeShaderDispatcher::AllocateUniformBuffer(size_t size)
-{
- if (!g_object_cache->GetUtilityShaderUniformBuffer()->ReserveMemory(
- size, g_vulkan_context->GetUniformBufferAlignment(), true, true, true))
- PanicAlert("Failed to allocate util uniforms");
-
- return g_object_cache->GetUtilityShaderUniformBuffer()->GetCurrentHostPointer();
-}
-
-void ComputeShaderDispatcher::CommitUniformBuffer(size_t size)
-{
- m_uniform_buffer.buffer = g_object_cache->GetUtilityShaderUniformBuffer()->GetBuffer();
- m_uniform_buffer.offset = 0;
- m_uniform_buffer.range = size;
- m_uniform_buffer_offset =
- static_cast<u32>(g_object_cache->GetUtilityShaderUniformBuffer()->GetCurrentOffset());
-
- g_object_cache->GetUtilityShaderUniformBuffer()->CommitMemory(size);
-}
-
-void ComputeShaderDispatcher::SetPushConstants(const void* data, size_t data_size)
-{
- ASSERT(static_cast<u32>(data_size) < PUSH_CONSTANT_BUFFER_SIZE);
-
- vkCmdPushConstants(m_command_buffer, m_pipeline_info.pipeline_layout, VK_SHADER_STAGE_COMPUTE_BIT,
- 0, static_cast<u32>(data_size), data);
-}
-
-void ComputeShaderDispatcher::SetSampler(size_t index, VkImageView view, VkSampler sampler)
-{
- m_samplers[index].sampler = sampler;
- m_samplers[index].imageView = view;
- m_samplers[index].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
-}
-
-void ComputeShaderDispatcher::SetStorageImage(VkImageView view, VkImageLayout image_layout)
-{
- m_storage_image.sampler = VK_NULL_HANDLE;
- m_storage_image.imageView = view;
- m_storage_image.imageLayout = image_layout;
-}
-
-void ComputeShaderDispatcher::SetTexelBuffer(size_t index, VkBufferView view)
-{
- m_texel_buffers[index] = view;
-}
-
-void ComputeShaderDispatcher::Dispatch(u32 groups_x, u32 groups_y, u32 groups_z)
-{
- BindDescriptors();
- if (!BindPipeline())
- return;
-
- vkCmdDispatch(m_command_buffer, groups_x, groups_y, groups_z);
-}
-
-void ComputeShaderDispatcher::BindDescriptors()
-{
- VkDescriptorSet set = g_command_buffer_mgr->AllocateDescriptorSet(
- g_object_cache->GetDescriptorSetLayout(DESCRIPTOR_SET_LAYOUT_COMPUTE));
- if (set == VK_NULL_HANDLE)
- {
- PanicAlert("Failed to allocate descriptor set for compute dispatch");
- return;
- }
-
- // Reserve enough descriptors to write every binding.
- std::array<VkWriteDescriptorSet, 7> set_writes = {};
- u32 num_set_writes = 0;
-
- if (m_uniform_buffer.buffer != VK_NULL_HANDLE)
- {
- set_writes[num_set_writes++] = {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
- nullptr,
- set,
- 0,
- 0,
- 1,
- VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC,
- nullptr,
- &m_uniform_buffer,
- nullptr};
- }
-
- // Samplers
- for (size_t i = 0; i < m_samplers.size(); i++)
- {
- const VkDescriptorImageInfo& info = m_samplers[i];
- if (info.imageView != VK_NULL_HANDLE && info.sampler != VK_NULL_HANDLE)
- {
- set_writes[num_set_writes++] = {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
- nullptr,
- set,
- static_cast<u32>(1 + i),
- 0,
- 1,
- VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
- &info,
- nullptr,
- nullptr};
- }
- }
-
- for (size_t i = 0; i < m_texel_buffers.size(); i++)
- {
- if (m_texel_buffers[i] != VK_NULL_HANDLE)
- {
- set_writes[num_set_writes++] = {
- VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, nullptr, set, 5 + static_cast<u32>(i), 0, 1,
- VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, nullptr, nullptr, &m_texel_buffers[i]};
- }
- }
-
- if (m_storage_image.imageView != VK_NULL_HANDLE)
- {
- set_writes[num_set_writes++] = {
- VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, nullptr, set, 7, 0, 1,
- VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, &m_storage_image, nullptr, nullptr};
- }
-
- if (num_set_writes > 0)
- {
- vkUpdateDescriptorSets(g_vulkan_context->GetDevice(), num_set_writes, set_writes.data(), 0,
- nullptr);
- }
-
- vkCmdBindDescriptorSets(m_command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE,
- m_pipeline_info.pipeline_layout, 0, 1, &set, 1, &m_uniform_buffer_offset);
-}
-
-bool ComputeShaderDispatcher::BindPipeline()
-{
- VkPipeline pipeline = g_shader_cache->GetComputePipeline(m_pipeline_info);
- if (pipeline == VK_NULL_HANDLE)
- {
- PanicAlert("Failed to get pipeline for backend compute dispatch");
- return false;
- }
-
- vkCmdBindPipeline(m_command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline);
- return true;
-}
-
-} // namespace Vulkan
diff --git a/Source/Core/VideoBackends/Vulkan/Util.h b/Source/Core/VideoBackends/Vulkan/Util.h
deleted file mode 100644
index ced63ef06b..0000000000
--- a/Source/Core/VideoBackends/Vulkan/Util.h
+++ /dev/null
@@ -1,235 +0,0 @@
-// Copyright 2016 Dolphin Emulator Project
-// Licensed under GPLv2+
-// Refer to the license.txt file included.
-
-#pragma once
-
-#include <array>
-#include <cstddef>
-
-#include "Common/CommonTypes.h"
-#include "VideoBackends/Vulkan/Constants.h"
-#include "VideoBackends/Vulkan/ObjectCache.h"
-#include "VideoBackends/Vulkan/ShaderCache.h"
-#include "VideoCommon/RenderState.h"
-#include "VideoCommon/TextureConfig.h"
-
-namespace Vulkan
-{
-class CommandBufferManager;
-class StateTracker;
-
-namespace Util
-{
-size_t AlignBufferOffset(size_t offset, size_t alignment);
-
-u32 MakeRGBA8Color(float r, float g, float b, float a);
-
-bool IsDepthFormat(VkFormat format);
-bool IsCompressedFormat(VkFormat format);
-VkFormat GetLinearFormat(VkFormat format);
-VkFormat GetVkFormatForHostTextureFormat(AbstractTextureFormat format);
-VkImageAspectFlags GetImageAspectForFormat(VkFormat format);
-u32 GetTexelSize(VkFormat format);
-u32 GetBlockSize(VkFormat format);
-
-// Clamps a VkRect2D to the specified dimensions.
-VkRect2D ClampRect2D(const VkRect2D& rect, u32 width, u32 height);
-
-// Map {SRC,DST}_COLOR to {SRC,DST}_ALPHA
-VkBlendFactor GetAlphaBlendFactor(VkBlendFactor factor);
-
-// Combines viewport and scissor updates
-void SetViewportAndScissor(VkCommandBuffer command_buffer, int x, int y, int width, int height,
- float min_depth = 0.0f, float max_depth = 1.0f);
-
-// Wrapper for creating an barrier on a buffer
-void BufferMemoryBarrier(VkCommandBuffer command_buffer, VkBuffer buffer,
- VkAccessFlags src_access_mask, VkAccessFlags dst_access_mask,
- VkDeviceSize offset, VkDeviceSize size,
- VkPipelineStageFlags src_stage_mask, VkPipelineStageFlags dst_stage_mask);
-
-// Completes the current render pass, executes the command buffer, and restores state ready for next
-// render. Use when you want to kick the current buffer to make room for new data.
-void ExecuteCurrentCommandsAndRestoreState(bool execute_off_thread,
- bool wait_for_completion = false);
-
-// Create a shader module from the specified SPIR-V.
-VkShaderModule CreateShaderModule(const u32* spv, size_t spv_word_count);
-
-// Compile a vertex shader and create a shader module, discarding the intermediate SPIR-V.
-VkShaderModule CompileAndCreateVertexShader(const std::string& source_code);
-
-// Compile a geometry shader and create a shader module, discarding the intermediate SPIR-V.
-VkShaderModule CompileAndCreateGeometryShader(const std::string& source_code);
-
-// Compile a fragment shader and create a shader module, discarding the intermediate SPIR-V.
-VkShaderModule CompileAndCreateFragmentShader(const std::string& source_code);
-
-// Compile a compute shader and create a shader module, discarding the intermediate SPIR-V.
-VkShaderModule CompileAndCreateComputeShader(const std::string& source_code);
-}
-
-// Utility shader vertex format
-#pragma pack(push, 1)
-struct UtilityShaderVertex
-{
- float Position[4];
- float TexCoord[4];
- u32 Color;
-
- void SetPosition(float x, float y)
- {
- Position[0] = x;
- Position[1] = y;
- Position[2] = 0.0f;
- Position[3] = 1.0f;
- }
- void SetPosition(float x, float y, float z)
- {
- Position[0] = x;
- Position[1] = y;
- Position[2] = z;
- Position[3] = 1.0f;
- }
- void SetTextureCoordinates(float u, float v)
- {
- TexCoord[0] = u;
- TexCoord[1] = v;
- TexCoord[2] = 0.0f;
- TexCoord[3] = 0.0f;
- }
- void SetTextureCoordinates(float u, float v, float w)
- {
- TexCoord[0] = u;
- TexCoord[1] = v;
- TexCoord[2] = w;
- TexCoord[3] = 0.0f;
- }
- void SetTextureCoordinates(float u, float v, float w, float x)
- {
- TexCoord[0] = u;
- TexCoord[1] = v;
- TexCoord[2] = w;
- TexCoord[3] = x;
- }
- void SetColor(u32 color) { Color = color; }
- void SetColor(float r, float g, float b) { Color = Util::MakeRGBA8Color(r, g, b, 1.0f); }
- void SetColor(float r, float g, float b, float a) { Color = Util::MakeRGBA8Color(r, g, b, a); }
-};
-#pragma pack(pop)
-
-class UtilityShaderDraw
-{
-public:
- UtilityShaderDraw(VkCommandBuffer command_buffer, VkPipelineLayout pipeline_layout,
- VkRenderPass render_pass, VkShaderModule vertex_shader,
- VkShaderModule geometry_shader, VkShaderModule pixel_shader,
- PrimitiveType primitive = PrimitiveType::TriangleStrip);
-
- UtilityShaderVertex* ReserveVertices(size_t count);
- void CommitVertices(size_t count);
-
- void UploadVertices(UtilityShaderVertex* vertices, size_t count);
-
- u8* AllocateVSUniforms(size_t size);
- void CommitVSUniforms(size_t size);
-
- u8* AllocatePSUniforms(size_t size);
- void CommitPSUniforms(size_t size);
-
- void SetPushConstants(const void* data, size_t data_size);
-
- void SetPSSampler(size_t index, VkImageView view, VkSampler sampler);
-
- void SetPSTexelBuffer(VkBufferView view);
-
- void SetRasterizationState(const RasterizationState& state);
- void SetMultisamplingState(const MultisamplingState& state);
- void SetDepthState(const DepthState& state);
- void SetBlendState(const BlendingState& state);
-
- void BeginRenderPass(VkFramebuffer framebuffer, const VkRect2D& region,
- const VkClearValue* clear_value = nullptr);
- void EndRenderPass();
-
- void Draw();
-
- // NOTE: These methods alter the viewport state of the command buffer.
-
- // Sets texture coordinates to 0..1
- void DrawQuad(int x, int y, int width, int height, float z = 0.0f);
-
- // Sets texture coordinates to the specified range
- void DrawQuad(int dst_x, int dst_y, int dst_width, int dst_height, int src_x, int src_y,
- int src_layer, int src_width, int src_height, int src_full_width,
- int src_full_height, float z = 0.0f);
-
- void DrawColoredQuad(int x, int y, int width, int height, u32 color, float z = 0.0f);
-
- void DrawColoredQuad(int x, int y, int width, int height, float r, float g, float b, float a,
- float z = 0.0f);
-
- // Draw without a vertex buffer. Assumes viewport has been initialized separately.
- void SetViewportAndScissor(int x, int y, int width, int height);
- void DrawWithoutVertexBuffer(u32 vertex_count);
-
-private:
- void BindVertexBuffer();
- void BindDescriptors();
- bool BindPipeline();
-
- VkCommandBuffer m_command_buffer = VK_NULL_HANDLE;
- VkBuffer m_vertex_buffer = VK_NULL_HANDLE;
- VkDeviceSize m_vertex_buffer_offset = 0;
- uint32_t m_vertex_count = 0;
-
- VkDescriptorBufferInfo m_vs_uniform_buffer = {};
- VkDescriptorBufferInfo m_ps_uniform_buffer = {};
- std::array<uint32_t, NUM_UBO_DESCRIPTOR_SET_BINDINGS> m_ubo_offsets = {};
-
- std::array<VkDescriptorImageInfo, NUM_PIXEL_SHADER_SAMPLERS> m_ps_samplers = {};
-
- VkBufferView m_ps_texel_buffer = VK_NULL_HANDLE;
-
- PipelineInfo m_pipeline_info = {};
-};
-
-class ComputeShaderDispatcher
-{
-public:
- ComputeShaderDispatcher(VkCommandBuffer command_buffer, VkPipelineLayout pipeline_layout,
- VkShaderModule compute_shader);
-
- u8* AllocateUniformBuffer(size_t size);
- void CommitUniformBuffer(size_t size);
-
- void SetPushConstants(const void* data, size_t data_size);
-
- void SetSampler(size_t index, VkImageView view, VkSampler sampler);
-
- void SetTexelBuffer(size_t index, VkBufferView view);
-
- void SetStorageImage(VkImageView view, VkImageLayout image_layout);
-
- void Dispatch(u32 groups_x, u32 groups_y, u32 groups_z);
-
-private:
- void BindDescriptors();
- bool BindPipeline();
-
- VkCommandBuffer m_command_buffer = VK_NULL_HANDLE;
-
- VkDescriptorBufferInfo m_uniform_buffer = {};
- u32 m_uniform_buffer_offset = 0;
-
- std::array<VkDescriptorImageInfo, 4> m_samplers = {};
-
- std::array<VkBufferView, 2> m_texel_buffers = {};
-
- VkDescriptorImageInfo m_storage_image = {};
-
- ComputePipelineInfo m_pipeline_info = {};
-};
-
-} // namespace Vulkan
diff --git a/Source/Core/VideoBackends/Vulkan/VKPipeline.cpp b/Source/Core/VideoBackends/Vulkan/VKPipeline.cpp
index fa513cef7d..8ff1a30009 100644
--- a/Source/Core/VideoBackends/Vulkan/VKPipeline.cpp
+++ b/Source/Core/VideoBackends/Vulkan/VKPipeline.cpp
@@ -6,9 +6,9 @@
#include "Common/MsgHandler.h"
#include "VideoBackends/Vulkan/ObjectCache.h"
-#include "VideoBackends/Vulkan/Util.h"
#include "VideoBackends/Vulkan/VKPipeline.h"
#include "VideoBackends/Vulkan/VKShader.h"
+#include "VideoBackends/Vulkan/VKTexture.h"
#include "VideoBackends/Vulkan/VertexFormat.h"
#include "VideoBackends/Vulkan/VulkanContext.h"
@@ -25,14 +25,213 @@ VKPipeline::~VKPipeline()
vkDestroyPipeline(g_vulkan_context->GetDevice(), m_pipeline, nullptr);
}
+static bool IsStripPrimitiveTopology(VkPrimitiveTopology topology)
+{
+ return topology == VK_PRIMITIVE_TOPOLOGY_LINE_STRIP ||
+ topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP ||
+ topology == VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY ||
+ topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY;
+}
+
+static VkPipelineRasterizationStateCreateInfo
+GetVulkanRasterizationState(const RasterizationState& state)
+{
+ static constexpr std::array<VkCullModeFlags, 4> cull_modes = {
+ {VK_CULL_MODE_NONE, VK_CULL_MODE_BACK_BIT, VK_CULL_MODE_FRONT_BIT,
+ VK_CULL_MODE_FRONT_AND_BACK}};
+
+ bool depth_clamp = g_ActiveConfig.backend_info.bSupportsDepthClamp;
+
+ return {
+ VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO, // VkStructureType sType
+ nullptr, // const void* pNext
+ 0, // VkPipelineRasterizationStateCreateFlags flags
+ depth_clamp, // VkBool32 depthClampEnable
+ VK_FALSE, // VkBool32 rasterizerDiscardEnable
+ VK_POLYGON_MODE_FILL, // VkPolygonMode polygonMode
+ cull_modes[state.cullmode], // VkCullModeFlags cullMode
+ VK_FRONT_FACE_CLOCKWISE, // VkFrontFace frontFace
+ VK_FALSE, // VkBool32 depthBiasEnable
+ 0.0f, // float depthBiasConstantFactor
+ 0.0f, // float depthBiasClamp
+ 0.0f, // float depthBiasSlopeFactor
+ 1.0f // float lineWidth
+ };
+}
+
+static VkPipelineMultisampleStateCreateInfo GetVulkanMultisampleState(const FramebufferState& state)
+{
+ return {
+ VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO, // VkStructureType sType
+ nullptr, // const void* pNext
+ 0, // VkPipelineMultisampleStateCreateFlags flags
+ static_cast<VkSampleCountFlagBits>(
+ state.samples.Value()), // VkSampleCountFlagBits rasterizationSamples
+ state.per_sample_shading, // VkBool32 sampleShadingEnable
+ 1.0f, // float minSampleShading
+ nullptr, // const VkSampleMask* pSampleMask;
+ VK_FALSE, // VkBool32 alphaToCoverageEnable
+ VK_FALSE // VkBool32 alphaToOneEnable
+ };
+}
+
+static VkPipelineDepthStencilStateCreateInfo GetVulkanDepthStencilState(const DepthState& state)
+{
+ // Less/greater are swapped due to inverted depth.
+ VkCompareOp compare_op;
+ bool inverted_depth = !g_ActiveConfig.backend_info.bSupportsReversedDepthRange;
+ switch (state.func)
+ {
+ case ZMode::NEVER:
+ compare_op = VK_COMPARE_OP_NEVER;
+ break;
+ case ZMode::LESS:
+ compare_op = inverted_depth ? VK_COMPARE_OP_GREATER : VK_COMPARE_OP_LESS;
+ break;
+ case ZMode::EQUAL:
+ compare_op = VK_COMPARE_OP_EQUAL;
+ break;
+ case ZMode::LEQUAL:
+ compare_op = inverted_depth ? VK_COMPARE_OP_GREATER_OR_EQUAL : VK_COMPARE_OP_LESS_OR_EQUAL;
+ break;
+ case ZMode::GREATER:
+ compare_op = inverted_depth ? VK_COMPARE_OP_LESS : VK_COMPARE_OP_GREATER;
+ break;
+ case ZMode::NEQUAL:
+ compare_op = VK_COMPARE_OP_NOT_EQUAL;
+ break;
+ case ZMode::GEQUAL:
+ compare_op = inverted_depth ? VK_COMPARE_OP_LESS_OR_EQUAL : VK_COMPARE_OP_GREATER_OR_EQUAL;
+ break;
+ case ZMode::ALWAYS:
+ compare_op = VK_COMPARE_OP_ALWAYS;
+ break;
+ default:
+ compare_op = VK_COMPARE_OP_ALWAYS;
+ break;
+ }
+
+ return {
+ VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO, // VkStructureType sType
+ nullptr, // const void* pNext
+ 0, // VkPipelineDepthStencilStateCreateFlags flags
+ state.testenable, // VkBool32 depthTestEnable
+ state.updateenable, // VkBool32 depthWriteEnable
+ compare_op, // VkCompareOp depthCompareOp
+ VK_FALSE, // VkBool32 depthBoundsTestEnable
+ VK_FALSE, // VkBool32 stencilTestEnable
+ {}, // VkStencilOpState front
+ {}, // VkStencilOpState back
+ 0.0f, // float minDepthBounds
+ 1.0f // float maxDepthBounds
+ };
+}
+
+static VkPipelineColorBlendAttachmentState GetVulkanAttachmentBlendState(const BlendingState& state)
+{
+ VkPipelineColorBlendAttachmentState vk_state = {};
+ vk_state.blendEnable = static_cast<VkBool32>(state.blendenable);
+ vk_state.colorBlendOp = state.subtract ? VK_BLEND_OP_REVERSE_SUBTRACT : VK_BLEND_OP_ADD;
+ vk_state.alphaBlendOp = state.subtractAlpha ? VK_BLEND_OP_REVERSE_SUBTRACT : VK_BLEND_OP_ADD;
+
+ if (state.usedualsrc && g_ActiveConfig.backend_info.bSupportsDualSourceBlend)
+ {
+ static constexpr std::array<VkBlendFactor, 8> src_factors = {
+ {VK_BLEND_FACTOR_ZERO, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_DST_COLOR,
+ VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR, VK_BLEND_FACTOR_SRC1_ALPHA,
+ VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA, VK_BLEND_FACTOR_DST_ALPHA,
+ VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA}};
+ static constexpr std::array<VkBlendFactor, 8> dst_factors = {
+ {VK_BLEND_FACTOR_ZERO, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_SRC_COLOR,
+ VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR, VK_BLEND_FACTOR_SRC1_ALPHA,
+ VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA, VK_BLEND_FACTOR_DST_ALPHA,
+ VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA}};
+
+ vk_state.srcColorBlendFactor = src_factors[state.srcfactor];
+ vk_state.srcAlphaBlendFactor = src_factors[state.srcfactoralpha];
+ vk_state.dstColorBlendFactor = dst_factors[state.dstfactor];
+ vk_state.dstAlphaBlendFactor = dst_factors[state.dstfactoralpha];
+ }
+ else
+ {
+ static constexpr std::array<VkBlendFactor, 8> src_factors = {
+ {VK_BLEND_FACTOR_ZERO, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_DST_COLOR,
+ VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR, VK_BLEND_FACTOR_SRC_ALPHA,
+ VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, VK_BLEND_FACTOR_DST_ALPHA,
+ VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA}};
+
+ static constexpr std::array<VkBlendFactor, 8> dst_factors = {
+ {VK_BLEND_FACTOR_ZERO, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_SRC_COLOR,
+ VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR, VK_BLEND_FACTOR_SRC_ALPHA,
+ VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, VK_BLEND_FACTOR_DST_ALPHA,
+ VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA}};
+
+ vk_state.srcColorBlendFactor = src_factors[state.srcfactor];
+ vk_state.srcAlphaBlendFactor = src_factors[state.srcfactoralpha];
+ vk_state.dstColorBlendFactor = dst_factors[state.dstfactor];
+ vk_state.dstAlphaBlendFactor = dst_factors[state.dstfactoralpha];
+ }
+
+ if (state.colorupdate)
+ {
+ vk_state.colorWriteMask =
+ VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT;
+ }
+ else
+ {
+ vk_state.colorWriteMask = 0;
+ }
+
+ if (state.alphaupdate)
+ vk_state.colorWriteMask |= VK_COLOR_COMPONENT_A_BIT;
+
+ return vk_state;
+}
+
+static VkPipelineColorBlendStateCreateInfo
+GetVulkanColorBlendState(const BlendingState& state,
+ const VkPipelineColorBlendAttachmentState* attachments,
+ uint32_t num_attachments)
+{
+ static constexpr std::array<VkLogicOp, 16> vk_logic_ops = {
+ {VK_LOGIC_OP_CLEAR, VK_LOGIC_OP_AND, VK_LOGIC_OP_AND_REVERSE, VK_LOGIC_OP_COPY,
+ VK_LOGIC_OP_AND_INVERTED, VK_LOGIC_OP_NO_OP, VK_LOGIC_OP_XOR, VK_LOGIC_OP_OR,
+ VK_LOGIC_OP_NOR, VK_LOGIC_OP_EQUIVALENT, VK_LOGIC_OP_INVERT, VK_LOGIC_OP_OR_REVERSE,
+ VK_LOGIC_OP_COPY_INVERTED, VK_LOGIC_OP_OR_INVERTED, VK_LOGIC_OP_NAND, VK_LOGIC_OP_SET}};
+
+ VkBool32 vk_logic_op_enable = static_cast<VkBool32>(state.logicopenable);
+ if (vk_logic_op_enable && !g_ActiveConfig.backend_info.bSupportsLogicOp)
+ {
+ // At the time of writing, Adreno and Mali drivers didn't support logic ops.
+ // The "emulation" through blending path has been removed, so just disable it completely.
+ // These drivers don't support dual-source blend either, so issues are to be expected.
+ vk_logic_op_enable = VK_FALSE;
+ }
+
+ VkLogicOp vk_logic_op = vk_logic_op_enable ? vk_logic_ops[state.logicmode] : VK_LOGIC_OP_CLEAR;
+
+ VkPipelineColorBlendStateCreateInfo vk_state = {
+ VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, // VkStructureType sType
+ nullptr, // const void* pNext
+ 0, // VkPipelineColorBlendStateCreateFlags flags
+ vk_logic_op_enable, // VkBool32 logicOpEnable
+ vk_logic_op, // VkLogicOp logicOp
+ num_attachments, // uint32_t attachmentCount
+ attachments, // const VkPipelineColorBlendAttachmentState* pAttachments
+ {1.0f, 1.0f, 1.0f, 1.0f} // float blendConstants[4]
+ };
+
+ return vk_state;
+}
+
std::unique_ptr<VKPipeline> VKPipeline::Create(const AbstractPipelineConfig& config)
{
DEBUG_ASSERT(config.vertex_shader && config.pixel_shader);
// Get render pass for config.
VkRenderPass render_pass = g_object_cache->GetRenderPass(
- Util::GetVkFormatForHostTextureFormat(config.framebuffer_state.color_texture_format),
- Util::GetVkFormatForHostTextureFormat(config.framebuffer_state.depth_texture_format),
+ VKTexture::GetVkFormatForHostTextureFormat(config.framebuffer_state.color_texture_format),
+ VKTexture::GetVkFormatForHostTextureFormat(config.framebuffer_state.depth_texture_format),
config.framebuffer_state.samples, VK_ATTACHMENT_LOAD_OP_LOAD);
// Get pipeline layout.
@@ -50,26 +249,144 @@ std::unique_ptr<VKPipeline> VKPipeline::Create(const AbstractPipelineConfig& con
return nullptr;
}
- // TODO: Move ShaderCache stuff to here.
- PipelineInfo pinfo;
- pinfo.vertex_format = static_cast<const VertexFormat*>(config.vertex_format);
- pinfo.pipeline_layout = pipeline_layout;
- pinfo.vs = static_cast<const VKShader*>(config.vertex_shader)->GetShaderModule();
- pinfo.ps = static_cast<const VKShader*>(config.pixel_shader)->GetShaderModule();
- pinfo.gs = config.geometry_shader ?
- static_cast<const VKShader*>(config.geometry_shader)->GetShaderModule() :
- VK_NULL_HANDLE;
- pinfo.render_pass = render_pass;
- pinfo.rasterization_state.hex = config.rasterization_state.hex;
- pinfo.depth_state.hex = config.depth_state.hex;
- pinfo.blend_state.hex = config.blending_state.hex;
- pinfo.multisampling_state.hex = 0;
- pinfo.multisampling_state.samples = config.framebuffer_state.samples;
- pinfo.multisampling_state.per_sample_shading = config.framebuffer_state.per_sample_shading;
-
- VkPipeline pipeline = g_shader_cache->CreatePipeline(pinfo);
- if (pipeline == VK_NULL_HANDLE)
- return nullptr;
+ // Declare descriptors for empty vertex buffers/attributes
+ static const VkPipelineVertexInputStateCreateInfo empty_vertex_input_state = {
+ VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO, // VkStructureType sType
+ nullptr, // const void* pNext
+ 0, // VkPipelineVertexInputStateCreateFlags flags
+ 0, // uint32_t vertexBindingDescriptionCount
+ nullptr, // const VkVertexInputBindingDescription* pVertexBindingDescriptions
+ 0, // uint32_t vertexAttributeDescriptionCount
+ nullptr // const VkVertexInputAttributeDescription* pVertexAttributeDescriptions
+ };
+
+ // Vertex inputs
+ const VkPipelineVertexInputStateCreateInfo& vertex_input_state =
+ config.vertex_format ?
+ static_cast<const VertexFormat*>(config.vertex_format)->GetVertexInputStateInfo() :
+ empty_vertex_input_state;
+
+ // Input assembly
+ static constexpr std::array<VkPrimitiveTopology, 4> vk_primitive_topologies = {
+ {VK_PRIMITIVE_TOPOLOGY_POINT_LIST, VK_PRIMITIVE_TOPOLOGY_LINE_LIST,
+ VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP}};
+ VkPipelineInputAssemblyStateCreateInfo input_assembly_state = {
+ VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO, nullptr, 0,
+ vk_primitive_topologies[static_cast<u32>(config.rasterization_state.primitive.Value())],
+ VK_FALSE};
+
+ // See Vulkan spec, section 19:
+ // If topology is VK_PRIMITIVE_TOPOLOGY_POINT_LIST, VK_PRIMITIVE_TOPOLOGY_LINE_LIST,
+ // VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY,
+ // VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY or VK_PRIMITIVE_TOPOLOGY_PATCH_LIST,
+ // primitiveRestartEnable must be VK_FALSE
+ if (g_ActiveConfig.backend_info.bSupportsPrimitiveRestart &&
+ IsStripPrimitiveTopology(input_assembly_state.topology))
+ {
+ input_assembly_state.primitiveRestartEnable = VK_TRUE;
+ }
+
+ // Shaders to stages
+ VkPipelineShaderStageCreateInfo shader_stages[3];
+ uint32_t num_shader_stages = 0;
+ if (config.vertex_shader)
+ {
+ shader_stages[num_shader_stages++] = {
+ VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
+ nullptr,
+ 0,
+ VK_SHADER_STAGE_VERTEX_BIT,
+ static_cast<const VKShader*>(config.vertex_shader)->GetShaderModule(),
+ "main"};
+ }
+ if (config.geometry_shader)
+ {
+ shader_stages[num_shader_stages++] = {
+ VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
+ nullptr,
+ 0,
+ VK_SHADER_STAGE_GEOMETRY_BIT,
+ static_cast<const VKShader*>(config.geometry_shader)->GetShaderModule(),
+ "main"};
+ }
+ if (config.pixel_shader)
+ {
+ shader_stages[num_shader_stages++] = {
+ VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
+ nullptr,
+ 0,
+ VK_SHADER_STAGE_FRAGMENT_BIT,
+ static_cast<const VKShader*>(config.pixel_shader)->GetShaderModule(),
+ "main"};
+ }
+
+ // Fill in Vulkan descriptor structs from our state structures.
+ VkPipelineRasterizationStateCreateInfo rasterization_state =
+ GetVulkanRasterizationState(config.rasterization_state);
+ VkPipelineMultisampleStateCreateInfo multisample_state =
+ GetVulkanMultisampleState(config.framebuffer_state);
+ VkPipelineDepthStencilStateCreateInfo depth_stencil_state =
+ GetVulkanDepthStencilState(config.depth_state);
+ VkPipelineColorBlendAttachmentState blend_attachment_state =
+ GetVulkanAttachmentBlendState(config.blending_state);
+ VkPipelineColorBlendStateCreateInfo blend_state =
+ GetVulkanColorBlendState(config.blending_state, &blend_attachment_state, 1);
+
+ // This viewport isn't used, but needs to be specified anyway.
+ static const VkViewport viewport = {0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f};
+ static const VkRect2D scissor = {{0, 0}, {1, 1}};
+ static const VkPipelineViewportStateCreateInfo viewport_state = {
+ VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO,
+ nullptr,
+ 0, // VkPipelineViewportStateCreateFlags flags;
+ 1, // uint32_t viewportCount
+ &viewport, // const VkViewport* pViewports
+ 1, // uint32_t scissorCount
+ &scissor // const VkRect2D* pScissors
+ };
+
+ // Set viewport and scissor dynamic state so we can change it elsewhere.
+ static const VkDynamicState dynamic_states[] = {VK_DYNAMIC_STATE_VIEWPORT,
+ VK_DYNAMIC_STATE_SCISSOR};
+ static const VkPipelineDynamicStateCreateInfo dynamic_state = {
+ VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO, nullptr,
+ 0, // VkPipelineDynamicStateCreateFlags flags
+ static_cast<u32>(ArraySize(dynamic_states)), // uint32_t dynamicStateCount
+ dynamic_states // const VkDynamicState* pDynamicStates
+ };
+
+ // Combine to full pipeline info structure.
+ VkGraphicsPipelineCreateInfo pipeline_info = {
+ VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO,
+ nullptr, // VkStructureType sType
+ 0, // VkPipelineCreateFlags flags
+ num_shader_stages, // uint32_t stageCount
+ shader_stages, // const VkPipelineShaderStageCreateInfo* pStages
+ &vertex_input_state, // const VkPipelineVertexInputStateCreateInfo* pVertexInputState
+ &input_assembly_state, // const VkPipelineInputAssemblyStateCreateInfo* pInputAssemblyState
+ nullptr, // const VkPipelineTessellationStateCreateInfo* pTessellationState
+ &viewport_state, // const VkPipelineViewportStateCreateInfo* pViewportState
+ &rasterization_state, // const VkPipelineRasterizationStateCreateInfo* pRasterizationState
+ &multisample_state, // const VkPipelineMultisampleStateCreateInfo* pMultisampleState
+ &depth_stencil_state, // const VkPipelineDepthStencilStateCreateInfo* pDepthStencilState
+ &blend_state, // const VkPipelineColorBlendStateCreateInfo* pColorBlendState
+ &dynamic_state, // const VkPipelineDynamicStateCreateInfo* pDynamicState
+ pipeline_layout, // VkPipelineLayout layout
+ render_pass, // VkRenderPass renderPass
+ 0, // uint32_t subpass
+ VK_NULL_HANDLE, // VkPipeline basePipelineHandle
+ -1 // int32_t basePipelineIndex
+ };
+
+ VkPipeline pipeline;
+ VkResult res =
+ vkCreateGraphicsPipelines(g_vulkan_context->GetDevice(), g_object_cache->GetPipelineCache(),
+ 1, &pipeline_info, nullptr, &pipeline);
+ if (res != VK_SUCCESS)
+ {
+ LOG_VULKAN_ERROR(res, "vkCreateGraphicsPipelines failed: ");
+ return VK_NULL_HANDLE;
+ }
return std::make_unique<VKPipeline>(pipeline, pipeline_layout, config.usage);
}
diff --git a/Source/Core/VideoBackends/Vulkan/VKShader.cpp b/Source/Core/VideoBackends/Vulkan/VKShader.cpp
index 5b44ed99a4..1a95a9c1f8 100644
--- a/Source/Core/VideoBackends/Vulkan/VKShader.cpp
+++ b/Source/Core/VideoBackends/Vulkan/VKShader.cpp
@@ -5,8 +5,8 @@
#include "Common/Align.h"
#include "Common/Assert.h"
+#include "VideoBackends/Vulkan/ObjectCache.h"
#include "VideoBackends/Vulkan/ShaderCompiler.h"
-#include "VideoBackends/Vulkan/Util.h"
#include "VideoBackends/Vulkan/VKShader.h"
#include "VideoBackends/Vulkan/VulkanContext.h"
@@ -48,26 +48,47 @@ AbstractShader::BinaryData VKShader::GetBinary() const
static std::unique_ptr<VKShader> CreateShaderObject(ShaderStage stage,
ShaderCompiler::SPIRVCodeVector spv)
{
- VkShaderModule mod = Util::CreateShaderModule(spv.data(), spv.size());
- if (mod == VK_NULL_HANDLE)
- return nullptr;
+ VkShaderModuleCreateInfo info = {};
+ info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
+ info.codeSize = spv.size() * sizeof(u32);
+ info.pCode = spv.data();
+
+ VkShaderModule mod;
+ VkResult res = vkCreateShaderModule(g_vulkan_context->GetDevice(), &info, nullptr, &mod);
+ if (res != VK_SUCCESS)
+ {
+ LOG_VULKAN_ERROR(res, "vkCreateShaderModule failed: ");
+ return VK_NULL_HANDLE;
+ }
// If it's a graphics shader, we defer pipeline creation.
if (stage != ShaderStage::Compute)
return std::make_unique<VKShader>(stage, std::move(spv), mod);
// If it's a compute shader, we create the pipeline straight away.
- ComputePipelineInfo pinfo;
- pinfo.pipeline_layout = g_object_cache->GetPipelineLayout(PIPELINE_LAYOUT_COMPUTE);
- pinfo.cs = mod;
- VkPipeline pipeline = g_shader_cache->CreateComputePipeline(pinfo);
- if (pipeline == VK_NULL_HANDLE)
+ const VkComputePipelineCreateInfo pipeline_info = {
+ VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO,
+ nullptr,
+ 0,
+ {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, nullptr, 0, VK_SHADER_STAGE_COMPUTE_BIT,
+ mod, "main", nullptr},
+ g_object_cache->GetPipelineLayout(PIPELINE_LAYOUT_COMPUTE),
+ VK_NULL_HANDLE,
+ -1};
+
+ VkPipeline pipeline;
+ res = vkCreateComputePipelines(g_vulkan_context->GetDevice(), g_object_cache->GetPipelineCache(),
+ 1, &pipeline_info, nullptr, &pipeline);
+
+ // Shader module is no longer needed, now it is compiled to a pipeline.
+ vkDestroyShaderModule(g_vulkan_context->GetDevice(), mod, nullptr);
+
+ if (res != VK_SUCCESS)
{
- vkDestroyShaderModule(g_vulkan_context->GetDevice(), mod, nullptr);
+ LOG_VULKAN_ERROR(res, "vkCreateComputePipelines failed: ");
return nullptr;
}
- // Shader module is no longer needed, now it is compiled to a pipeline.
return std::make_unique<VKShader>(std::move(spv), pipeline);
}
diff --git a/Source/Core/VideoBackends/Vulkan/VKTexture.cpp b/Source/Core/VideoBackends/Vulkan/VKTexture.cpp
index 929307edb3..a19e169412 100644
--- a/Source/Core/VideoBackends/Vulkan/VKTexture.cpp
+++ b/Source/Core/VideoBackends/Vulkan/VKTexture.cpp
@@ -13,23 +13,35 @@
#include "Common/MsgHandler.h"
#include "VideoBackends/Vulkan/CommandBufferManager.h"
-#include "VideoBackends/Vulkan/FramebufferManager.h"
+#include "VideoBackends/Vulkan/ObjectCache.h"
+#include "VideoBackends/Vulkan/Renderer.h"
#include "VideoBackends/Vulkan/StagingBuffer.h"
#include "VideoBackends/Vulkan/StateTracker.h"
-#include "VideoBackends/Vulkan/Texture2D.h"
-#include "VideoBackends/Vulkan/Util.h"
+#include "VideoBackends/Vulkan/StreamBuffer.h"
#include "VideoBackends/Vulkan/VKTexture.h"
#include "VideoBackends/Vulkan/VulkanContext.h"
-#include "VideoCommon/ImageWrite.h"
-#include "VideoCommon/TextureConfig.h"
-
namespace Vulkan
{
-VKTexture::VKTexture(const TextureConfig& tex_config, std::unique_ptr<Texture2D> texture,
- VkFramebuffer framebuffer)
- : AbstractTexture(tex_config), m_texture(std::move(texture)), m_framebuffer(framebuffer)
+VKTexture::VKTexture(const TextureConfig& tex_config, VkDeviceMemory device_memory, VkImage image,
+ VkImageLayout layout /* = VK_IMAGE_LAYOUT_UNDEFINED */,
+ ComputeImageLayout compute_layout /* = ComputeImageLayout::Undefined */)
+ : AbstractTexture(tex_config), m_device_memory(device_memory), m_image(image), m_layout(layout),
+ m_compute_layout(compute_layout)
+{
+}
+
+VKTexture::~VKTexture()
{
+ StateTracker::GetInstance()->UnbindTexture(m_view);
+ g_command_buffer_mgr->DeferImageViewDestruction(m_view);
+
+ // If we don't have device memory allocated, the image is not owned by us (e.g. swapchain)
+ if (m_device_memory != VK_NULL_HANDLE)
+ {
+ g_command_buffer_mgr->DeferImageDestruction(m_image);
+ g_command_buffer_mgr->DeferDeviceMemoryDestruction(m_device_memory);
+ }
}
std::unique_ptr<VKTexture> VKTexture::Create(const TextureConfig& tex_config)
@@ -37,91 +49,192 @@ std::unique_ptr<VKTexture> VKTexture::Create(const TextureConfig& tex_config)
// Determine image usage, we need to flag as an attachment if it can be used as a rendertarget.
VkImageUsageFlags usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT |
VK_IMAGE_USAGE_SAMPLED_BIT;
- if (tex_config.rendertarget)
- usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
+ if (tex_config.IsRenderTarget())
+ {
+ usage |= IsDepthFormat(tex_config.format) ? VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT :
+ VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
+ }
+ if (tex_config.IsComputeImage())
+ usage |= VK_IMAGE_USAGE_STORAGE_BIT;
+
+ VkImageCreateInfo image_info = {VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
+ nullptr,
+ 0,
+ VK_IMAGE_TYPE_2D,
+ GetVkFormatForHostTextureFormat(tex_config.format),
+ {tex_config.width, tex_config.height, 1},
+ tex_config.levels,
+ tex_config.layers,
+ static_cast<VkSampleCountFlagBits>(tex_config.samples),
+ VK_IMAGE_TILING_OPTIMAL,
+ usage,
+ VK_SHARING_MODE_EXCLUSIVE,
+ 0,
+ nullptr,
+ VK_IMAGE_LAYOUT_UNDEFINED};
+
+ VkImage image = VK_NULL_HANDLE;
+ VkResult res = vkCreateImage(g_vulkan_context->GetDevice(), &image_info, nullptr, &image);
+ if (res != VK_SUCCESS)
+ {
+ LOG_VULKAN_ERROR(res, "vkCreateImage failed: ");
+ return nullptr;
+ }
+
+ // Allocate memory to back this texture, we want device local memory in this case
+ VkMemoryRequirements memory_requirements;
+ vkGetImageMemoryRequirements(g_vulkan_context->GetDevice(), image, &memory_requirements);
- // Allocate texture object
- VkFormat vk_format = Util::GetVkFormatForHostTextureFormat(tex_config.format);
- auto texture =
- Texture2D::Create(tex_config.width, tex_config.height, tex_config.levels, tex_config.layers,
- vk_format, static_cast<VkSampleCountFlagBits>(tex_config.samples),
- VK_IMAGE_VIEW_TYPE_2D_ARRAY, VK_IMAGE_TILING_OPTIMAL, usage);
+ VkMemoryAllocateInfo memory_info = {
+ VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, nullptr, memory_requirements.size,
+ g_vulkan_context->GetMemoryType(memory_requirements.memoryTypeBits,
+ VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)};
- if (!texture)
+ VkDeviceMemory device_memory;
+ res = vkAllocateMemory(g_vulkan_context->GetDevice(), &memory_info, nullptr, &device_memory);
+ if (res != VK_SUCCESS)
{
+ LOG_VULKAN_ERROR(res, "vkAllocateMemory failed: ");
+ vkDestroyImage(g_vulkan_context->GetDevice(), image, nullptr);
return nullptr;
}
- // If this is a render target (for efb copies), allocate a framebuffer
- VkFramebuffer framebuffer = VK_NULL_HANDLE;
- if (tex_config.rendertarget)
+ res = vkBindImageMemory(g_vulkan_context->GetDevice(), image, device_memory, 0);
+ if (res != VK_SUCCESS)
{
- VkImageView framebuffer_attachments[] = {texture->GetView()};
- VkRenderPass render_pass =
- g_object_cache->GetRenderPass(texture->GetFormat(), VK_FORMAT_UNDEFINED, tex_config.samples,
- VK_ATTACHMENT_LOAD_OP_DONT_CARE);
- VkFramebufferCreateInfo framebuffer_info = {
- VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO,
- nullptr,
- 0,
- render_pass,
- static_cast<u32>(ArraySize(framebuffer_attachments)),
- framebuffer_attachments,
- texture->GetWidth(),
- texture->GetHeight(),
- texture->GetLayers()};
-
- VkResult res = vkCreateFramebuffer(g_vulkan_context->GetDevice(), &framebuffer_info, nullptr,
- &framebuffer);
- if (res != VK_SUCCESS)
- {
- LOG_VULKAN_ERROR(res, "vkCreateFramebuffer failed: ");
- return nullptr;
- }
+ LOG_VULKAN_ERROR(res, "vkBindImageMemory failed: ");
+ vkDestroyImage(g_vulkan_context->GetDevice(), image, nullptr);
+ vkFreeMemory(g_vulkan_context->GetDevice(), device_memory, nullptr);
+ return nullptr;
+ }
- if (!IsDepthFormat(tex_config.format))
- {
- // Clear render targets before use to prevent reading uninitialized memory.
- VkClearColorValue clear_value = {{0.0f, 0.0f, 0.0f, 1.0f}};
- VkImageSubresourceRange clear_range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, tex_config.levels, 0,
- tex_config.layers};
- texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentInitCommandBuffer(),
- VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
- vkCmdClearColorImage(g_command_buffer_mgr->GetCurrentInitCommandBuffer(), texture->GetImage(),
- texture->GetLayout(), &clear_value, 1, &clear_range);
- }
- else
- {
- // Clear render targets before use to prevent reading uninitialized memory.
- VkClearDepthStencilValue clear_value = {0.0f, 0};
- VkImageSubresourceRange clear_range = {Util::GetImageAspectForFormat(vk_format), 0,
- tex_config.levels, 0, tex_config.layers};
- texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentInitCommandBuffer(),
- VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
- vkCmdClearDepthStencilImage(g_command_buffer_mgr->GetCurrentInitCommandBuffer(),
- texture->GetImage(), texture->GetLayout(), &clear_value, 1,
- &clear_range);
- }
+ std::unique_ptr<VKTexture> texture = std::make_unique<VKTexture>(
+ tex_config, device_memory, image, VK_IMAGE_LAYOUT_UNDEFINED, ComputeImageLayout::Undefined);
+ if (!texture->CreateView(VK_IMAGE_VIEW_TYPE_2D_ARRAY))
+ return nullptr;
+
+ return texture;
+}
+
+std::unique_ptr<VKTexture> VKTexture::CreateAdopted(const TextureConfig& tex_config, VkImage image,
+ VkImageViewType view_type, VkImageLayout layout)
+{
+ std::unique_ptr<VKTexture> texture = std::make_unique<VKTexture>(
+ tex_config, nullptr, image, layout, ComputeImageLayout::Undefined);
+ if (!texture->CreateView(VK_IMAGE_VIEW_TYPE_2D_ARRAY))
+ return nullptr;
+
+ return texture;
+}
+
+bool VKTexture::CreateView(VkImageViewType type)
+{
+ VkImageViewCreateInfo view_info = {
+ VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
+ nullptr,
+ 0,
+ m_image,
+ type,
+ GetVkFormat(),
+ {VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY,
+ VK_COMPONENT_SWIZZLE_IDENTITY},
+ {GetImageAspectForFormat(GetFormat()), 0, GetLevels(), 0, GetLayers()}};
+
+ VkResult res = vkCreateImageView(g_vulkan_context->GetDevice(), &view_info, nullptr, &m_view);
+ if (res != VK_SUCCESS)
+ {
+ LOG_VULKAN_ERROR(res, "vkCreateImageView failed: ");
+ return false;
}
- return std::unique_ptr<VKTexture>(new VKTexture(tex_config, std::move(texture), framebuffer));
+ return true;
}
-VKTexture::~VKTexture()
+VkFormat VKTexture::GetLinearFormat(VkFormat format)
{
- // Texture is automatically cleaned up, however, we don't want to leave it bound.
- g_renderer->UnbindTexture(this);
- if (m_framebuffer != VK_NULL_HANDLE)
- g_command_buffer_mgr->DeferFramebufferDestruction(m_framebuffer);
+ switch (format)
+ {
+ case VK_FORMAT_R8_SRGB:
+ return VK_FORMAT_R8_UNORM;
+ case VK_FORMAT_R8G8_SRGB:
+ return VK_FORMAT_R8G8_UNORM;
+ case VK_FORMAT_R8G8B8_SRGB:
+ return VK_FORMAT_R8G8B8_UNORM;
+ case VK_FORMAT_R8G8B8A8_SRGB:
+ return VK_FORMAT_R8G8B8A8_UNORM;
+ case VK_FORMAT_B8G8R8_SRGB:
+ return VK_FORMAT_B8G8R8_UNORM;
+ case VK_FORMAT_B8G8R8A8_SRGB:
+ return VK_FORMAT_B8G8R8A8_UNORM;
+ default:
+ return format;
+ }
}
-Texture2D* VKTexture::GetRawTexIdentifier() const
+VkFormat VKTexture::GetVkFormatForHostTextureFormat(AbstractTextureFormat format)
{
- return m_texture.get();
+ switch (format)
+ {
+ case AbstractTextureFormat::DXT1:
+ return VK_FORMAT_BC1_RGBA_UNORM_BLOCK;
+
+ case AbstractTextureFormat::DXT3:
+ return VK_FORMAT_BC2_UNORM_BLOCK;
+
+ case AbstractTextureFormat::DXT5:
+ return VK_FORMAT_BC3_UNORM_BLOCK;
+
+ case AbstractTextureFormat::BPTC:
+ return VK_FORMAT_BC7_UNORM_BLOCK;
+
+ case AbstractTextureFormat::RGBA8:
+ return VK_FORMAT_R8G8B8A8_UNORM;
+
+ case AbstractTextureFormat::BGRA8:
+ return VK_FORMAT_B8G8R8A8_UNORM;
+
+ case AbstractTextureFormat::R16:
+ return VK_FORMAT_R16_UNORM;
+
+ case AbstractTextureFormat::D16:
+ return VK_FORMAT_D16_UNORM;
+
+ case AbstractTextureFormat::D24_S8:
+ return VK_FORMAT_D24_UNORM_S8_UINT;
+
+ case AbstractTextureFormat::R32F:
+ return VK_FORMAT_R32_SFLOAT;
+
+ case AbstractTextureFormat::D32F:
+ return VK_FORMAT_D32_SFLOAT;
+
+ case AbstractTextureFormat::D32F_S8:
+ return VK_FORMAT_D32_SFLOAT_S8_UINT;
+
+ case AbstractTextureFormat::Undefined:
+ return VK_FORMAT_UNDEFINED;
+
+ default:
+ PanicAlert("Unhandled texture format.");
+ return VK_FORMAT_R8G8B8A8_UNORM;
+ }
}
-VkFramebuffer VKTexture::GetFramebuffer() const
+
+VkImageAspectFlags VKTexture::GetImageAspectForFormat(AbstractTextureFormat format)
{
- return m_framebuffer;
+ switch (format)
+ {
+ case AbstractTextureFormat::D24_S8:
+ case AbstractTextureFormat::D32F_S8:
+ return VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;
+
+ case AbstractTextureFormat::D16:
+ case AbstractTextureFormat::D32F:
+ return VK_IMAGE_ASPECT_DEPTH_BIT;
+
+ default:
+ return VK_IMAGE_ASPECT_COLOR_BIT;
+ }
}
void VKTexture::CopyRectangleFromTexture(const AbstractTexture* src,
@@ -129,7 +242,7 @@ void VKTexture::CopyRectangleFromTexture(const AbstractTexture* src,
u32 src_level, const MathUtil::Rectangle<int>& dst_rect,
u32 dst_layer, u32 dst_level)
{
- Texture2D* src_texture = static_cast<const VKTexture*>(src)->GetRawTexIdentifier();
+ const VKTexture* src_texture = static_cast<const VKTexture*>(src);
ASSERT_MSG(VIDEO,
static_cast<u32>(src_rect.GetWidth()) <= src_texture->GetWidth() &&
@@ -151,67 +264,18 @@ void VKTexture::CopyRectangleFromTexture(const AbstractTexture* src,
// Must be called outside of a render pass.
StateTracker::GetInstance()->EndRenderPass();
+ const VkImageLayout old_src_layout = src_texture->GetLayout();
src_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
- m_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
+ TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
+ VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
- vkCmdCopyImage(g_command_buffer_mgr->GetCurrentCommandBuffer(), src_texture->GetImage(),
- VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, m_texture->GetImage(),
+ vkCmdCopyImage(g_command_buffer_mgr->GetCurrentCommandBuffer(), src_texture->m_image,
+ VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, m_image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &image_copy);
- // Ensure both textures remain in the SHADER_READ_ONLY layout so they can be bound.
- src_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
- m_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
-}
-
-void VKTexture::ScaleRectangleFromTexture(const AbstractTexture* source,
- const MathUtil::Rectangle<int>& src_rect,
- const MathUtil::Rectangle<int>& dst_rect)
-{
- Texture2D* src_texture = static_cast<const VKTexture*>(source)->GetRawTexIdentifier();
-
- // Can't do this within a game render pass.
- StateTracker::GetInstance()->EndRenderPass();
- StateTracker::GetInstance()->SetPendingRebind();
-
- // Can't render to a non-rendertarget (no framebuffer).
- ASSERT_MSG(VIDEO, m_config.rendertarget,
- "Destination texture for partial copy is not a rendertarget");
-
- // Render pass expects dst_texture to be in COLOR_ATTACHMENT_OPTIMAL state.
- // src_texture should already be in SHADER_READ_ONLY state, but transition in case (XFB).
- src_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
- m_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
-
- VkRenderPass render_pass = g_object_cache->GetRenderPass(
- m_texture->GetFormat(), VK_FORMAT_UNDEFINED, 1, VK_ATTACHMENT_LOAD_OP_DONT_CARE);
- UtilityShaderDraw draw(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- g_object_cache->GetPipelineLayout(PIPELINE_LAYOUT_STANDARD), render_pass,
- g_shader_cache->GetPassthroughVertexShader(),
- g_shader_cache->GetPassthroughGeometryShader(),
- TextureCache::GetInstance()->GetCopyShader());
-
- VkRect2D region = {
- {dst_rect.left, dst_rect.top},
- {static_cast<u32>(dst_rect.GetWidth()), static_cast<u32>(dst_rect.GetHeight())}};
- draw.BeginRenderPass(m_framebuffer, region);
- draw.SetPSSampler(0, src_texture->GetView(), g_object_cache->GetLinearSampler());
- draw.DrawQuad(dst_rect.left, dst_rect.top, dst_rect.GetWidth(), dst_rect.GetHeight(),
- src_rect.left, src_rect.top, 0, src_rect.GetWidth(), src_rect.GetHeight(),
- static_cast<int>(src_texture->GetWidth()),
- static_cast<int>(src_texture->GetHeight()));
- draw.EndRenderPass();
-
- // Ensure both textures remain in the SHADER_READ_ONLY layout so they can be bound.
- src_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
- m_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
+ // Only restore the source layout. Destination is restored by FinishedRendering().
+ src_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(), old_src_layout);
}
void VKTexture::ResolveFromTexture(const AbstractTexture* src, const MathUtil::Rectangle<int>& rect,
@@ -225,11 +289,11 @@ void VKTexture::ResolveFromTexture(const AbstractTexture* src, const MathUtil::R
// Resolving is considered to be a transfer operation.
StateTracker::GetInstance()->EndRenderPass();
- VkImageLayout old_src_layout = srcentry->m_texture->GetLayout();
- srcentry->m_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
- m_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
+ VkImageLayout old_src_layout = srcentry->m_layout;
+ srcentry->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
+ VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
+ TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
+ VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
VkImageResolve resolve = {
{VK_IMAGE_ASPECT_COLOR_BIT, level, layer, 1}, // srcSubresource
@@ -238,23 +302,18 @@ void VKTexture::ResolveFromTexture(const AbstractTexture* src, const MathUtil::R
{rect.left, rect.top, 0}, // dstOffset
{static_cast<u32>(rect.GetWidth()), static_cast<u32>(rect.GetHeight()), 1} // extent
};
- vkCmdResolveImage(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- srcentry->m_texture->GetImage(), srcentry->m_texture->GetLayout(),
- m_texture->GetImage(), m_texture->GetLayout(), 1, &resolve);
-
- // Restore old source texture layout. Destination is assumed to be bound as a shader resource.
- srcentry->m_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- old_src_layout);
- m_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
+ vkCmdResolveImage(g_command_buffer_mgr->GetCurrentCommandBuffer(), srcentry->m_image,
+ srcentry->m_layout, m_image, m_layout, 1, &resolve);
+
+ srcentry->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(), old_src_layout);
}
void VKTexture::Load(u32 level, u32 width, u32 height, u32 row_length, const u8* buffer,
size_t buffer_size)
{
// Can't copy data larger than the texture extents.
- width = std::max(1u, std::min(width, m_texture->GetWidth() >> level));
- height = std::max(1u, std::min(height, m_texture->GetHeight() >> level));
+ width = std::max(1u, std::min(width, GetWidth() >> level));
+ height = std::max(1u, std::min(height, GetHeight() >> level));
// We don't care about the existing contents of the texture, so we could the image layout to
// VK_IMAGE_LAYOUT_UNDEFINED here. However, under section 2.2.1, Queue Operation of the Vulkan
@@ -272,30 +331,29 @@ void VKTexture::Load(u32 level, u32 width, u32 height, u32 row_length, const u8*
// When the last mip level is uploaded, we transition to SHADER_READ_ONLY, ready for use. This is
// because we can't transition in a render pass, and we don't necessarily know when this texture
// is going to be used.
- m_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentInitCommandBuffer(),
- VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
+ TransitionToLayout(g_command_buffer_mgr->GetCurrentInitCommandBuffer(),
+ VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
// For unaligned textures, we can save some memory in the transfer buffer by skipping the rows
// that lie outside of the texture's dimensions.
- u32 upload_alignment = static_cast<u32>(g_vulkan_context->GetBufferImageGranularity());
- u32 block_size = Util::GetBlockSize(m_texture->GetFormat());
- u32 num_rows = Common::AlignUp(height, block_size) / block_size;
- size_t source_pitch = CalculateStrideForFormat(m_config.format, row_length);
- size_t upload_size = source_pitch * num_rows;
+ const u32 upload_alignment = static_cast<u32>(g_vulkan_context->GetBufferImageGranularity());
+ const u32 block_size = GetBlockSizeForFormat(GetFormat());
+ const u32 num_rows = Common::AlignUp(height, block_size) / block_size;
+ const u32 source_pitch = CalculateStrideForFormat(m_config.format, row_length);
+ const u32 upload_size = source_pitch * num_rows;
std::unique_ptr<StagingBuffer> temp_buffer;
VkBuffer upload_buffer;
VkDeviceSize upload_buffer_offset;
// Does this texture data fit within the streaming buffer?
- if (upload_size <= STAGING_TEXTURE_UPLOAD_THRESHOLD &&
- upload_size <= MAXIMUM_TEXTURE_UPLOAD_BUFFER_SIZE)
+ if (upload_size <= STAGING_TEXTURE_UPLOAD_THRESHOLD)
{
StreamBuffer* stream_buffer = g_object_cache->GetTextureUploadBuffer();
if (!stream_buffer->ReserveMemory(upload_size, upload_alignment))
{
// Execute the command buffer first.
WARN_LOG(VIDEO, "Executing command list while waiting for space in texture upload buffer");
- Util::ExecuteCurrentCommandsAndRestoreState(false);
+ Renderer::GetInstance()->ExecuteCommandBuffer(false);
// Try allocating again. This may cause a fence wait.
if (!stream_buffer->ReserveMemory(upload_size, upload_alignment))
@@ -334,17 +392,282 @@ void VKTexture::Load(u32 level, u32 width, u32 height, u32 row_length, const u8*
{width, height, 1} // VkExtent3D imageExtent
};
vkCmdCopyBufferToImage(g_command_buffer_mgr->GetCurrentInitCommandBuffer(), upload_buffer,
- m_texture->GetImage(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1,
- &image_copy);
+ m_image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &image_copy);
- // Last mip level? We shouldn't be doing any further uploads now, so transition for rendering.
+ // Preemptively transition to shader read only after uploading the last mip level, as we're
+ // likely finished with writes to this texture for now. We can't do this in common with a
+ // FinishedRendering() call because the upload happens in the init command buffer, and we
+ // don't want to interrupt the render pass with calls which were executed ages before.
if (level == (m_config.levels - 1))
{
- m_texture->TransitionToLayout(g_command_buffer_mgr->GetCurrentInitCommandBuffer(),
- VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
+ TransitionToLayout(g_command_buffer_mgr->GetCurrentInitCommandBuffer(),
+ VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
}
}
+void VKTexture::FinishedRendering()
+{
+ if (m_layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL)
+ return;
+
+ StateTracker::GetInstance()->EndRenderPass();
+ TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
+ VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
+}
+
+void VKTexture::OverrideImageLayout(VkImageLayout new_layout)
+{
+ m_layout = new_layout;
+}
+
+void VKTexture::TransitionToLayout(VkCommandBuffer command_buffer, VkImageLayout new_layout) const
+{
+ if (m_layout == new_layout)
+ return;
+
+ VkImageMemoryBarrier barrier = {
+ VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, // VkStructureType sType
+ nullptr, // const void* pNext
+ 0, // VkAccessFlags srcAccessMask
+ 0, // VkAccessFlags dstAccessMask
+ m_layout, // VkImageLayout oldLayout
+ new_layout, // VkImageLayout newLayout
+ VK_QUEUE_FAMILY_IGNORED, // uint32_t srcQueueFamilyIndex
+ VK_QUEUE_FAMILY_IGNORED, // uint32_t dstQueueFamilyIndex
+ m_image, // VkImage image
+ {GetImageAspectForFormat(GetFormat()), 0, GetLevels(), 0,
+ GetLayers()} // VkImageSubresourceRange subresourceRange
+ };
+
+ // srcStageMask -> Stages that must complete before the barrier
+ // dstStageMask -> Stages that must wait for after the barrier before beginning
+ VkPipelineStageFlags srcStageMask, dstStageMask;
+ switch (m_layout)
+ {
+ case VK_IMAGE_LAYOUT_UNDEFINED:
+ // Layout undefined therefore contents undefined, and we don't care what happens to it.
+ barrier.srcAccessMask = 0;
+ srcStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
+ break;
+
+ case VK_IMAGE_LAYOUT_PREINITIALIZED:
+ // Image has been pre-initialized by the host, so ensure all writes have completed.
+ barrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
+ srcStageMask = VK_PIPELINE_STAGE_HOST_BIT;
+ break;
+
+ case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
+ // Image was being used as a color attachment, so ensure all writes have completed.
+ barrier.srcAccessMask =
+ VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
+ srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
+ break;
+
+ case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
+ // Image was being used as a depthstencil attachment, so ensure all writes have completed.
+ barrier.srcAccessMask =
+ VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
+ srcStageMask =
+ VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
+ break;
+
+ case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
+ // Image was being used as a shader resource, make sure all reads have finished.
+ barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT;
+ srcStageMask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
+ break;
+
+ case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:
+ // Image was being used as a copy source, ensure all reads have finished.
+ barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
+ srcStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT;
+ break;
+
+ case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:
+ // Image was being used as a copy destination, ensure all writes have finished.
+ barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
+ srcStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT;
+ break;
+
+ default:
+ srcStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
+ break;
+ }
+
+ switch (new_layout)
+ {
+ case VK_IMAGE_LAYOUT_UNDEFINED:
+ barrier.dstAccessMask = 0;
+ dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
+ break;
+
+ case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
+ barrier.dstAccessMask =
+ VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
+ dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
+ break;
+
+ case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
+ barrier.dstAccessMask =
+ VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
+ dstStageMask =
+ VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
+ break;
+
+ case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
+ barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
+ dstStageMask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
+ break;
+
+ case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:
+ barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
+ dstStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT;
+ break;
+
+ case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:
+ barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
+ dstStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT;
+ break;
+
+ case VK_IMAGE_LAYOUT_PRESENT_SRC_KHR:
+ srcStageMask = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
+ dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
+ break;
+
+ default:
+ dstStageMask = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
+ break;
+ }
+
+ // If we were using a compute layout, the stages need to reflect that
+ switch (m_compute_layout)
+ {
+ case ComputeImageLayout::Undefined:
+ break;
+ case ComputeImageLayout::ReadOnly:
+ barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT;
+ srcStageMask = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
+ break;
+ case ComputeImageLayout::WriteOnly:
+ barrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
+ srcStageMask = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
+ break;
+ case ComputeImageLayout::ReadWrite:
+ barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
+ srcStageMask = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
+ break;
+ }
+ m_compute_layout = ComputeImageLayout::Undefined;
+
+ vkCmdPipelineBarrier(command_buffer, srcStageMask, dstStageMask, 0, 0, nullptr, 0, nullptr, 1,
+ &barrier);
+
+ m_layout = new_layout;
+}
+
+void VKTexture::TransitionToLayout(VkCommandBuffer command_buffer,
+ ComputeImageLayout new_layout) const
+{
+ ASSERT(new_layout != ComputeImageLayout::Undefined);
+ if (m_compute_layout == new_layout)
+ return;
+
+ VkImageMemoryBarrier barrier = {
+ VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, // VkStructureType sType
+ nullptr, // const void* pNext
+ 0, // VkAccessFlags srcAccessMask
+ 0, // VkAccessFlags dstAccessMask
+ m_layout, // VkImageLayout oldLayout
+ VK_IMAGE_LAYOUT_GENERAL, // VkImageLayout newLayout
+ VK_QUEUE_FAMILY_IGNORED, // uint32_t srcQueueFamilyIndex
+ VK_QUEUE_FAMILY_IGNORED, // uint32_t dstQueueFamilyIndex
+ m_image, // VkImage image
+ {GetImageAspectForFormat(GetFormat()), 0, GetLevels(), 0,
+ GetLayers()} // VkImageSubresourceRange subresourceRange
+ };
+
+ VkPipelineStageFlags srcStageMask, dstStageMask;
+ switch (m_layout)
+ {
+ case VK_IMAGE_LAYOUT_UNDEFINED:
+ // Layout undefined therefore contents undefined, and we don't care what happens to it.
+ barrier.srcAccessMask = 0;
+ srcStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
+ break;
+
+ case VK_IMAGE_LAYOUT_PREINITIALIZED:
+ // Image has been pre-initialized by the host, so ensure all writes have completed.
+ barrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
+ srcStageMask = VK_PIPELINE_STAGE_HOST_BIT;
+ break;
+
+ case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
+ // Image was being used as a color attachment, so ensure all writes have completed.
+ barrier.srcAccessMask =
+ VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
+ srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
+ break;
+
+ case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
+ // Image was being used as a depthstencil attachment, so ensure all writes have completed.
+ barrier.srcAccessMask =
+ VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
+ srcStageMask =
+ VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
+ break;
+
+ case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
+ // Image was being used as a shader resource, make sure all reads have finished.
+ barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT;
+ srcStageMask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
+ break;
+
+ case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:
+ // Image was being used as a copy source, ensure all reads have finished.
+ barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
+ srcStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT;
+ break;
+
+ case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:
+ // Image was being used as a copy destination, ensure all writes have finished.
+ barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
+ srcStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT;
+ break;
+
+ default:
+ srcStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
+ break;
+ }
+
+ switch (new_layout)
+ {
+ case ComputeImageLayout::ReadOnly:
+ barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
+ barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
+ dstStageMask = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
+ break;
+ case ComputeImageLayout::WriteOnly:
+ barrier.dstAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
+ barrier.newLayout = VK_IMAGE_LAYOUT_GENERAL;
+ dstStageMask = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
+ break;
+ case ComputeImageLayout::ReadWrite:
+ barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
+ barrier.newLayout = VK_IMAGE_LAYOUT_GENERAL;
+ dstStageMask = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
+ break;
+ default:
+ dstStageMask = 0;
+ break;
+ }
+
+ m_layout = barrier.newLayout;
+ m_compute_layout = new_layout;
+
+ vkCmdPipelineBarrier(command_buffer, srcStageMask, dstStageMask, 0, 0, nullptr, 0, nullptr, 1,
+ &barrier);
+}
+
VKStagingTexture::VKStagingTexture(StagingTextureType type, const TextureConfig& config,
std::unique_ptr<StagingBuffer> buffer)
: AbstractStagingTexture(type, config), m_staging_buffer(std::move(buffer))
@@ -407,38 +730,32 @@ void VKStagingTexture::CopyFromTexture(const AbstractTexture* src,
const MathUtil::Rectangle<int>& src_rect, u32 src_layer,
u32 src_level, const MathUtil::Rectangle<int>& dst_rect)
{
+ const VKTexture* src_tex = static_cast<const VKTexture*>(src);
ASSERT(m_type == StagingTextureType::Readback || m_type == StagingTextureType::Mutable);
ASSERT(src_rect.GetWidth() == dst_rect.GetWidth() &&
src_rect.GetHeight() == dst_rect.GetHeight());
- ASSERT(src_rect.left >= 0 && static_cast<u32>(src_rect.right) <= src->GetConfig().width &&
- src_rect.top >= 0 && static_cast<u32>(src_rect.bottom) <= src->GetConfig().height);
+ ASSERT(src_rect.left >= 0 && static_cast<u32>(src_rect.right) <= src_tex->GetWidth() &&
+ src_rect.top >= 0 && static_cast<u32>(src_rect.bottom) <= src_tex->GetHeight());
ASSERT(dst_rect.left >= 0 && static_cast<u32>(dst_rect.right) <= m_config.width &&
dst_rect.top >= 0 && static_cast<u32>(dst_rect.bottom) <= m_config.height);
- Texture2D* src_tex = static_cast<const VKTexture*>(src)->GetRawTexIdentifier();
- CopyFromTexture(src_tex, src_rect, src_layer, src_level, dst_rect);
-}
-
-void VKStagingTexture::CopyFromTexture(Texture2D* src, const MathUtil::Rectangle<int>& src_rect,
- u32 src_layer, u32 src_level,
- const MathUtil::Rectangle<int>& dst_rect)
-{
if (m_needs_flush)
{
// Drop copy before reusing it.
- g_command_buffer_mgr->RemoveFencePointCallback(this);
+ g_command_buffer_mgr->RemoveFenceSignaledCallback(this);
m_flush_fence = VK_NULL_HANDLE;
m_needs_flush = false;
}
- VkImageLayout old_layout = src->GetLayout();
- src->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
- VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
+ StateTracker::GetInstance()->EndRenderPass();
+
+ VkImageLayout old_layout = src_tex->GetLayout();
+ src_tex->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
+ VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
// Issue the image->buffer copy, but delay it for now.
VkBufferImageCopy image_copy = {};
- VkImageAspectFlags aspect =
- Util::IsDepthFormat(src->GetFormat()) ? VK_IMAGE_ASPECT_DEPTH_BIT : VK_IMAGE_ASPECT_COLOR_BIT;
+ const VkImageAspectFlags aspect = VKTexture::GetImageAspectForFormat(src_tex->GetFormat());
image_copy.bufferOffset =
static_cast<VkDeviceSize>(static_cast<size_t>(dst_rect.top) * m_config.GetStride() +
static_cast<size_t>(dst_rect.left) * m_texel_size);
@@ -448,58 +765,51 @@ void VKStagingTexture::CopyFromTexture(Texture2D* src, const MathUtil::Rectangle
image_copy.imageOffset = {src_rect.left, src_rect.top, 0};
image_copy.imageExtent = {static_cast<u32>(src_rect.GetWidth()),
static_cast<u32>(src_rect.GetHeight()), 1u};
- vkCmdCopyImageToBuffer(g_command_buffer_mgr->GetCurrentCommandBuffer(), src->GetImage(),
+ vkCmdCopyImageToBuffer(g_command_buffer_mgr->GetCurrentCommandBuffer(), src_tex->GetImage(),
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, m_staging_buffer->GetBuffer(), 1,
&image_copy);
// Restore old source texture layout.
- src->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(), old_layout);
+ src_tex->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(), old_layout);
m_needs_flush = true;
- g_command_buffer_mgr->AddFencePointCallback(this,
- [this](VkCommandBuffer buf, VkFence fence) {
- ASSERT(m_needs_flush);
- if (m_flush_fence != VK_NULL_HANDLE)
- return;
-
- m_flush_fence = fence;
- },
- [this](VkFence fence) {
- if (m_flush_fence != fence)
- return;
-
- m_flush_fence = VK_NULL_HANDLE;
- m_needs_flush = false;
- g_command_buffer_mgr->RemoveFencePointCallback(
- this);
- m_staging_buffer->InvalidateCPUCache();
- });
+ m_flush_fence = g_command_buffer_mgr->GetCurrentCommandBufferFence();
+ g_command_buffer_mgr->AddFenceSignaledCallback(this, [this](VkFence fence) {
+ if (m_flush_fence != fence)
+ return;
+
+ m_flush_fence = VK_NULL_HANDLE;
+ m_needs_flush = false;
+ g_command_buffer_mgr->RemoveFenceSignaledCallback(this);
+ m_staging_buffer->InvalidateCPUCache();
+ });
}
void VKStagingTexture::CopyToTexture(const MathUtil::Rectangle<int>& src_rect, AbstractTexture* dst,
const MathUtil::Rectangle<int>& dst_rect, u32 dst_layer,
u32 dst_level)
{
+ const VKTexture* dst_tex = static_cast<const VKTexture*>(dst);
ASSERT(m_type == StagingTextureType::Upload || m_type == StagingTextureType::Mutable);
ASSERT(src_rect.GetWidth() == dst_rect.GetWidth() &&
src_rect.GetHeight() == dst_rect.GetHeight());
ASSERT(src_rect.left >= 0 && static_cast<u32>(src_rect.right) <= m_config.width &&
src_rect.top >= 0 && static_cast<u32>(src_rect.bottom) <= m_config.height);
- ASSERT(dst_rect.left >= 0 && static_cast<u32>(dst_rect.right) <= dst->GetConfig().width &&
- dst_rect.top >= 0 && static_cast<u32>(dst_rect.bottom) <= dst->GetConfig().height);
+ ASSERT(dst_rect.left >= 0 && static_cast<u32>(dst_rect.right) <= dst_tex->GetWidth() &&
+ dst_rect.top >= 0 && static_cast<u32>(dst_rect.bottom) <= dst_tex->GetHeight());
if (m_needs_flush)
{
// Drop copy before reusing it.
- g_command_buffer_mgr->RemoveFencePointCallback(this);
+ g_command_buffer_mgr->RemoveFenceSignaledCallback(this);
m_flush_fence = VK_NULL_HANDLE;
m_needs_flush = false;
}
// Flush caches before copying.
m_staging_buffer->FlushCPUCache();
+ StateTracker::GetInstance()->EndRenderPass();
- Texture2D* dst_tex = static_cast<const VKTexture*>(dst)->GetRawTexIdentifier();
VkImageLayout old_layout = dst_tex->GetLayout();
dst_tex->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
@@ -523,23 +833,15 @@ void VKStagingTexture::CopyToTexture(const MathUtil::Rectangle<int>& src_rect, A
dst_tex->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(), old_layout);
m_needs_flush = true;
- g_command_buffer_mgr->AddFencePointCallback(this,
- [this](VkCommandBuffer buf, VkFence fence) {
- ASSERT(m_needs_flush);
- if (m_flush_fence != VK_NULL_HANDLE)
- return;
-
- m_flush_fence = fence;
- },
- [this](VkFence fence) {
- if (m_flush_fence != fence)
- return;
-
- m_flush_fence = VK_NULL_HANDLE;
- m_needs_flush = false;
- g_command_buffer_mgr->RemoveFencePointCallback(
- this);
- });
+ m_flush_fence = g_command_buffer_mgr->GetCurrentCommandBufferFence();
+ g_command_buffer_mgr->AddFenceSignaledCallback(this, [this](VkFence fence) {
+ if (m_flush_fence != fence)
+ return;
+
+ m_flush_fence = VK_NULL_HANDLE;
+ m_needs_flush = false;
+ g_command_buffer_mgr->RemoveFenceSignaledCallback(this);
+ });
}
bool VKStagingTexture::Map()
@@ -559,19 +861,19 @@ void VKStagingTexture::Flush()
return;
// Either of the below two calls will cause the callback to fire.
- g_command_buffer_mgr->RemoveFencePointCallback(this);
- if (m_flush_fence != VK_NULL_HANDLE)
+ g_command_buffer_mgr->RemoveFenceSignaledCallback(this);
+ if (m_flush_fence == g_command_buffer_mgr->GetCurrentCommandBufferFence())
{
- // WaitForFence should fire the callback.
- g_command_buffer_mgr->WaitForFence(m_flush_fence);
- m_flush_fence = VK_NULL_HANDLE;
+ // The readback is in the current command buffer, and we must execute it.
+ Renderer::GetInstance()->ExecuteCommandBuffer(false, true);
}
else
{
- // We don't have a fence, and are pending. That means the readback is in the current
- // command buffer, and must execute it to populate the staging texture.
- Util::ExecuteCurrentCommandsAndRestoreState(false, true);
+ // WaitForFence should fire the callback.
+ g_command_buffer_mgr->WaitForFence(m_flush_fence);
}
+
+ DEBUG_ASSERT(m_flush_fence == VK_NULL_HANDLE);
m_needs_flush = false;
// For readback textures, invalidate the CPU cache as there is new data there.
@@ -579,16 +881,16 @@ void VKStagingTexture::Flush()
m_staging_buffer->InvalidateCPUCache();
}
-VKFramebuffer::VKFramebuffer(const VKTexture* color_attachment, const VKTexture* depth_attachment,
- u32 width, u32 height, u32 layers, u32 samples, VkFramebuffer fb,
+VKFramebuffer::VKFramebuffer(VKTexture* color_attachment, VKTexture* depth_attachment, u32 width,
+ u32 height, u32 layers, u32 samples, VkFramebuffer fb,
VkRenderPass load_render_pass, VkRenderPass discard_render_pass,
VkRenderPass clear_render_pass)
: AbstractFramebuffer(
+ color_attachment, depth_attachment,
color_attachment ? color_attachment->GetFormat() : AbstractTextureFormat::Undefined,
depth_attachment ? depth_attachment->GetFormat() : AbstractTextureFormat::Undefined,
width, height, layers, samples),
- m_color_attachment(color_attachment), m_depth_attachment(depth_attachment), m_fb(fb),
- m_load_render_pass(load_render_pass), m_discard_render_pass(discard_render_pass),
+ m_fb(fb), m_load_render_pass(load_render_pass), m_discard_render_pass(discard_render_pass),
m_clear_render_pass(clear_render_pass)
{
}
@@ -598,16 +900,16 @@ VKFramebuffer::~VKFramebuffer()
g_command_buffer_mgr->DeferFramebufferDestruction(m_fb);
}
-std::unique_ptr<VKFramebuffer> VKFramebuffer::Create(const VKTexture* color_attachment,
- const VKTexture* depth_attachment)
+std::unique_ptr<VKFramebuffer> VKFramebuffer::Create(VKTexture* color_attachment,
+ VKTexture* depth_attachment)
{
if (!ValidateConfig(color_attachment, depth_attachment))
return nullptr;
const VkFormat vk_color_format =
- color_attachment ? color_attachment->GetRawTexIdentifier()->GetFormat() : VK_FORMAT_UNDEFINED;
+ color_attachment ? color_attachment->GetVkFormat() : VK_FORMAT_UNDEFINED;
const VkFormat vk_depth_format =
- depth_attachment ? depth_attachment->GetRawTexIdentifier()->GetFormat() : VK_FORMAT_UNDEFINED;
+ depth_attachment ? depth_attachment->GetVkFormat() : VK_FORMAT_UNDEFINED;
const VKTexture* either_attachment = color_attachment ? color_attachment : depth_attachment;
const u32 width = either_attachment->GetWidth();
const u32 height = either_attachment->GetHeight();
@@ -618,10 +920,10 @@ std::unique_ptr<VKFramebuffer> VKFramebuffer::Create(const VKTexture* color_atta
u32 num_attachments = 0;
if (color_attachment)
- attachment_views[num_attachments++] = color_attachment->GetRawTexIdentifier()->GetView();
+ attachment_views[num_attachments++] = color_attachment->GetView();
if (depth_attachment)
- attachment_views[num_attachments++] = depth_attachment->GetRawTexIdentifier()->GetView();
+ attachment_views[num_attachments++] = depth_attachment->GetView();
VkRenderPass load_render_pass = g_object_cache->GetRenderPass(
vk_color_format, vk_depth_format, samples, VK_ATTACHMENT_LOAD_OP_LOAD);
@@ -659,38 +961,20 @@ std::unique_ptr<VKFramebuffer> VKFramebuffer::Create(const VKTexture* color_atta
clear_render_pass);
}
-void VKFramebuffer::TransitionForRender() const
-{
- if (m_color_attachment)
- {
- m_color_attachment->GetRawTexIdentifier()->TransitionToLayout(
- g_command_buffer_mgr->GetCurrentCommandBuffer(), VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
- }
-
- if (m_depth_attachment)
- {
- m_depth_attachment->GetRawTexIdentifier()->TransitionToLayout(
- g_command_buffer_mgr->GetCurrentCommandBuffer(),
- VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
- }
-}
-
-void VKFramebuffer::TransitionForSample() const
+void VKFramebuffer::TransitionForRender()
{
- if (StateTracker::GetInstance()->GetFramebuffer() == m_fb)
- StateTracker::GetInstance()->EndRenderPass();
-
if (m_color_attachment)
{
- m_color_attachment->GetRawTexIdentifier()->TransitionToLayout(
- g_command_buffer_mgr->GetCurrentCommandBuffer(), VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
+ static_cast<VKTexture*>(m_color_attachment)
+ ->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
+ VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
}
if (m_depth_attachment)
{
- m_depth_attachment->GetRawTexIdentifier()->TransitionToLayout(
- g_command_buffer_mgr->GetCurrentCommandBuffer(), VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
+ static_cast<VKTexture*>(m_depth_attachment)
+ ->TransitionToLayout(g_command_buffer_mgr->GetCurrentCommandBuffer(),
+ VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
}
}
-
} // namespace Vulkan
diff --git a/Source/Core/VideoBackends/Vulkan/VKTexture.h b/Source/Core/VideoBackends/Vulkan/VKTexture.h
index 3a5c8cadc8..bab11ec108 100644
--- a/Source/Core/VideoBackends/Vulkan/VKTexture.h
+++ b/Source/Core/VideoBackends/Vulkan/VKTexture.h
@@ -5,8 +5,8 @@
#pragma once
#include <memory>
-#include <vulkan/vulkan.h>
+#include "VideoBackends/Vulkan/VulkanLoader.h"
#include "VideoCommon/AbstractFramebuffer.h"
#include "VideoCommon/AbstractStagingTexture.h"
#include "VideoCommon/AbstractTexture.h"
@@ -19,33 +19,64 @@ class Texture2D;
class VKTexture final : public AbstractTexture
{
public:
+ // Custom image layouts, mainly used for switching to/from compute
+ enum class ComputeImageLayout
+ {
+ Undefined,
+ ReadOnly,
+ WriteOnly,
+ ReadWrite
+ };
+
VKTexture() = delete;
+ VKTexture(const TextureConfig& tex_config, VkDeviceMemory device_memory, VkImage image,
+ VkImageLayout layout = VK_IMAGE_LAYOUT_UNDEFINED,
+ ComputeImageLayout compute_layout = ComputeImageLayout::Undefined);
~VKTexture();
+ static VkFormat GetLinearFormat(VkFormat format);
+ static VkFormat GetVkFormatForHostTextureFormat(AbstractTextureFormat format);
+ static VkImageAspectFlags GetImageAspectForFormat(AbstractTextureFormat format);
+
void CopyRectangleFromTexture(const AbstractTexture* src,
const MathUtil::Rectangle<int>& src_rect, u32 src_layer,
u32 src_level, const MathUtil::Rectangle<int>& dst_rect,
u32 dst_layer, u32 dst_level) override;
- void ScaleRectangleFromTexture(const AbstractTexture* source,
- const MathUtil::Rectangle<int>& src_rect,
- const MathUtil::Rectangle<int>& dst_rect) override;
void ResolveFromTexture(const AbstractTexture* src, const MathUtil::Rectangle<int>& rect,
u32 layer, u32 level) override;
-
void Load(u32 level, u32 width, u32 height, u32 row_length, const u8* buffer,
size_t buffer_size) override;
+ void FinishedRendering() override;
- Texture2D* GetRawTexIdentifier() const;
- VkFramebuffer GetFramebuffer() const;
+ VkImage GetImage() const { return m_image; }
+ VkDeviceMemory GetDeviceMemory() const { return m_device_memory; }
+ VkImageView GetView() const { return m_view; }
+ VkImageLayout GetLayout() const { return m_layout; }
+ VkFormat GetVkFormat() const { return GetVkFormatForHostTextureFormat(m_config.format); }
+ bool IsAdopted() const { return m_device_memory != nullptr; }
static std::unique_ptr<VKTexture> Create(const TextureConfig& tex_config);
+ static std::unique_ptr<VKTexture>
+ CreateAdopted(const TextureConfig& tex_config, VkImage image,
+ VkImageViewType view_type = VK_IMAGE_VIEW_TYPE_2D_ARRAY,
+ VkImageLayout layout = VK_IMAGE_LAYOUT_UNDEFINED);
+
+ // Used when the render pass is changing the image layout, or to force it to
+ // VK_IMAGE_LAYOUT_UNDEFINED, if the existing contents of the image is
+ // irrelevant and will not be loaded.
+ void OverrideImageLayout(VkImageLayout new_layout);
+
+ void TransitionToLayout(VkCommandBuffer command_buffer, VkImageLayout new_layout) const;
+ void TransitionToLayout(VkCommandBuffer command_buffer, ComputeImageLayout new_layout) const;
private:
- VKTexture(const TextureConfig& tex_config, std::unique_ptr<Texture2D> texture,
- VkFramebuffer framebuffer);
+ bool CreateView(VkImageViewType type);
- std::unique_ptr<Texture2D> m_texture;
- VkFramebuffer m_framebuffer;
+ VkDeviceMemory m_device_memory;
+ VkImage m_image;
+ VkImageView m_view = VK_NULL_HANDLE;
+ mutable VkImageLayout m_layout = VK_IMAGE_LAYOUT_UNDEFINED;
+ mutable ComputeImageLayout m_compute_layout = ComputeImageLayout::Undefined;
};
class VKStagingTexture final : public AbstractStagingTexture
@@ -65,11 +96,6 @@ public:
void Unmap() override;
void Flush() override;
- // This overload is provided for compatibility as we dropped StagingTexture2D.
- // For now, FramebufferManager relies on them. But we can drop it once we move that to common.
- void CopyFromTexture(Texture2D* src, const MathUtil::Rectangle<int>& src_rect, u32 src_layer,
- u32 src_level, const MathUtil::Rectangle<int>& dst_rect);
-
static std::unique_ptr<VKStagingTexture> Create(StagingTextureType type,
const TextureConfig& config);
@@ -84,25 +110,23 @@ private:
class VKFramebuffer final : public AbstractFramebuffer
{
public:
- VKFramebuffer(const VKTexture* color_attachment, const VKTexture* depth_attachment, u32 width,
- u32 height, u32 layers, u32 samples, VkFramebuffer fb,
- VkRenderPass load_render_pass, VkRenderPass discard_render_pass,
- VkRenderPass clear_render_pass);
+ VKFramebuffer(VKTexture* color_attachment, VKTexture* depth_attachment, u32 width, u32 height,
+ u32 layers, u32 samples, VkFramebuffer fb, VkRenderPass load_render_pass,
+ VkRenderPass discard_render_pass, VkRenderPass clear_render_pass);
~VKFramebuffer() override;
VkFramebuffer GetFB() const { return m_fb; }
+ VkRect2D GetRect() const { return VkRect2D{{0, 0}, {m_width, m_height}}; }
+
VkRenderPass GetLoadRenderPass() const { return m_load_render_pass; }
VkRenderPass GetDiscardRenderPass() const { return m_discard_render_pass; }
VkRenderPass GetClearRenderPass() const { return m_clear_render_pass; }
- void TransitionForRender() const;
- void TransitionForSample() const;
+ void TransitionForRender();
- static std::unique_ptr<VKFramebuffer> Create(const VKTexture* color_attachments,
- const VKTexture* depth_attachment);
+ static std::unique_ptr<VKFramebuffer> Create(VKTexture* color_attachments,
+ VKTexture* depth_attachment);
protected:
- const VKTexture* m_color_attachment;
- const VKTexture* m_depth_attachment;
VkFramebuffer m_fb;
VkRenderPass m_load_render_pass;
VkRenderPass m_discard_render_pass;
diff --git a/Source/Core/VideoBackends/Vulkan/VertexFormat.cpp b/Source/Core/VideoBackends/Vulkan/VertexFormat.cpp
index 3ea824e530..5d8006c2c0 100644
--- a/Source/Core/VideoBackends/Vulkan/VertexFormat.cpp
+++ b/Source/Core/VideoBackends/Vulkan/VertexFormat.cpp
@@ -46,9 +46,8 @@ static VkFormat VarToVkFormat(VarType t, uint32_t components, bool integer)
return integer ? integer_type_lookup[t][components - 1] : float_type_lookup[t][components - 1];
}
-VertexFormat::VertexFormat(const PortableVertexDeclaration& in_vtx_decl)
+VertexFormat::VertexFormat(const PortableVertexDeclaration& vtx_decl) : NativeVertexFormat(vtx_decl)
{
- vtx_decl = in_vtx_decl;
MapAttributes();
SetupInputState();
}
@@ -62,50 +61,49 @@ void VertexFormat::MapAttributes()
{
m_num_attributes = 0;
- if (vtx_decl.position.enable)
- AddAttribute(SHADER_POSITION_ATTRIB, 0,
- VarToVkFormat(vtx_decl.position.type, vtx_decl.position.components,
- vtx_decl.position.integer),
- vtx_decl.position.offset);
+ if (m_decl.position.enable)
+ AddAttribute(
+ SHADER_POSITION_ATTRIB, 0,
+ VarToVkFormat(m_decl.position.type, m_decl.position.components, m_decl.position.integer),
+ m_decl.position.offset);
for (uint32_t i = 0; i < 3; i++)
{
- if (vtx_decl.normals[i].enable)
+ if (m_decl.normals[i].enable)
AddAttribute(SHADER_NORM0_ATTRIB + i, 0,
- VarToVkFormat(vtx_decl.normals[i].type, vtx_decl.normals[i].components,
- vtx_decl.normals[i].integer),
- vtx_decl.normals[i].offset);
+ VarToVkFormat(m_decl.normals[i].type, m_decl.normals[i].components,
+ m_decl.normals[i].integer),
+ m_decl.normals[i].offset);
}
for (uint32_t i = 0; i < 2; i++)
{
- if (vtx_decl.colors[i].enable)
+ if (m_decl.colors[i].enable)
AddAttribute(SHADER_COLOR0_ATTRIB + i, 0,
- VarToVkFormat(vtx_decl.colors[i].type, vtx_decl.colors[i].components,
- vtx_decl.colors[i].integer),
- vtx_decl.colors[i].offset);
+ VarToVkFormat(m_decl.colors[i].type, m_decl.colors[i].components,
+ m_decl.colors[i].integer),
+ m_decl.colors[i].offset);
}
for (uint32_t i = 0; i < 8; i++)
{
- if (vtx_decl.texcoords[i].enable)
+ if (m_decl.texcoords[i].enable)
AddAttribute(SHADER_TEXTURE0_ATTRIB + i, 0,
- VarToVkFormat(vtx_decl.texcoords[i].type, vtx_decl.texcoords[i].components,
- vtx_decl.texcoords[i].integer),
- vtx_decl.texcoords[i].offset);
+ VarToVkFormat(m_decl.texcoords[i].type, m_decl.texcoords[i].components,
+ m_decl.texcoords[i].integer),
+ m_decl.texcoords[i].offset);
}
- if (vtx_decl.posmtx.enable)
- AddAttribute(
- SHADER_POSMTX_ATTRIB, 0,
- VarToVkFormat(vtx_decl.posmtx.type, vtx_decl.posmtx.components, vtx_decl.posmtx.integer),
- vtx_decl.posmtx.offset);
+ if (m_decl.posmtx.enable)
+ AddAttribute(SHADER_POSMTX_ATTRIB, 0,
+ VarToVkFormat(m_decl.posmtx.type, m_decl.posmtx.components, m_decl.posmtx.integer),
+ m_decl.posmtx.offset);
}
void VertexFormat::SetupInputState()
{
m_binding_description.binding = 0;
- m_binding_description.stride = vtx_decl.stride;
+ m_binding_description.stride = m_decl.stride;
m_binding_description.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
m_input_state_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
diff --git a/Source/Core/VideoBackends/Vulkan/VertexFormat.h b/Source/Core/VideoBackends/Vulkan/VertexFormat.h
index 9b5810ced7..617967202b 100644
--- a/Source/Core/VideoBackends/Vulkan/VertexFormat.h
+++ b/Source/Core/VideoBackends/Vulkan/VertexFormat.h
@@ -14,7 +14,7 @@ namespace Vulkan
class VertexFormat : public ::NativeVertexFormat
{
public:
- VertexFormat(const PortableVertexDeclaration& in_vtx_decl);
+ VertexFormat(const PortableVertexDeclaration& vtx_decl);
// Passed to pipeline state creation
const VkPipelineVertexInputStateCreateInfo& GetVertexInputStateInfo() const;
@@ -35,4 +35,4 @@ private:
uint32_t m_num_attributes = 0;
};
-}
+} // namespace Vulkan
diff --git a/Source/Core/VideoBackends/Vulkan/VertexManager.cpp b/Source/Core/VideoBackends/Vulkan/VertexManager.cpp
index bd0ab0b54d..7fcbf84013 100644
--- a/Source/Core/VideoBackends/Vulkan/VertexManager.cpp
+++ b/Source/Core/VideoBackends/Vulkan/VertexManager.cpp
@@ -4,87 +4,140 @@
#include "VideoBackends/Vulkan/VertexManager.h"
+#include "Common/Align.h"
#include "Common/CommonTypes.h"
#include "Common/Logging/Log.h"
#include "Common/MsgHandler.h"
-#include "VideoBackends/Vulkan/BoundingBox.h"
#include "VideoBackends/Vulkan/CommandBufferManager.h"
-#include "VideoBackends/Vulkan/FramebufferManager.h"
#include "VideoBackends/Vulkan/Renderer.h"
#include "VideoBackends/Vulkan/StateTracker.h"
#include "VideoBackends/Vulkan/StreamBuffer.h"
-#include "VideoBackends/Vulkan/Util.h"
#include "VideoBackends/Vulkan/VertexFormat.h"
#include "VideoBackends/Vulkan/VulkanContext.h"
-#include "VideoCommon/BoundingBox.h"
+#include "VideoCommon/GeometryShaderManager.h"
#include "VideoCommon/IndexGenerator.h"
+#include "VideoCommon/PixelShaderManager.h"
#include "VideoCommon/Statistics.h"
#include "VideoCommon/VertexLoaderManager.h"
+#include "VideoCommon/VertexShaderManager.h"
#include "VideoCommon/VideoConfig.h"
namespace Vulkan
{
-// TODO: Clean up this mess
-constexpr size_t INITIAL_VERTEX_BUFFER_SIZE = VertexManager::MAXVBUFFERSIZE * 2;
-constexpr size_t MAX_VERTEX_BUFFER_SIZE = VertexManager::MAXVBUFFERSIZE * 16;
-constexpr size_t INITIAL_INDEX_BUFFER_SIZE = VertexManager::MAXIBUFFERSIZE * sizeof(u16) * 2;
-constexpr size_t MAX_INDEX_BUFFER_SIZE = VertexManager::MAXIBUFFERSIZE * sizeof(u16) * 16;
-
-VertexManager::VertexManager()
- : m_cpu_vertex_buffer(MAXVBUFFERSIZE), m_cpu_index_buffer(MAXIBUFFERSIZE)
+static VkBufferView CreateTexelBufferView(VkBuffer buffer, VkFormat vk_format)
{
-}
+ // Create a view of the whole buffer, we'll offset our texel load into it
+ VkBufferViewCreateInfo view_info = {
+ VK_STRUCTURE_TYPE_BUFFER_VIEW_CREATE_INFO, // VkStructureType sType
+ nullptr, // const void* pNext
+ 0, // VkBufferViewCreateFlags flags
+ buffer, // VkBuffer buffer
+ vk_format, // VkFormat format
+ 0, // VkDeviceSize offset
+ VK_WHOLE_SIZE // VkDeviceSize range
+ };
-VertexManager::~VertexManager()
-{
+ VkBufferView view;
+ VkResult res = vkCreateBufferView(g_vulkan_context->GetDevice(), &view_info, nullptr, &view);
+ if (res != VK_SUCCESS)
+ {
+ LOG_VULKAN_ERROR(res, "vkCreateBufferView failed: ");
+ return VK_NULL_HANDLE;
+ }
+
+ return view;
}
-VertexManager* VertexManager::GetInstance()
+VertexManager::VertexManager() = default;
+
+VertexManager::~VertexManager()
{
- return static_cast<VertexManager*>(g_vertex_manager.get());
+ DestroyTexelBufferViews();
}
bool VertexManager::Initialize()
{
- m_vertex_stream_buffer = StreamBuffer::Create(VK_BUFFER_USAGE_VERTEX_BUFFER_BIT,
- INITIAL_VERTEX_BUFFER_SIZE, MAX_VERTEX_BUFFER_SIZE);
+ m_vertex_stream_buffer =
+ StreamBuffer::Create(VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VERTEX_STREAM_BUFFER_SIZE * 4);
+ m_index_stream_buffer =
+ StreamBuffer::Create(VK_BUFFER_USAGE_INDEX_BUFFER_BIT, INDEX_STREAM_BUFFER_SIZE * 4);
+ m_uniform_stream_buffer =
+ StreamBuffer::Create(VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, UNIFORM_STREAM_BUFFER_SIZE * 4);
+ if (!m_vertex_stream_buffer || !m_index_stream_buffer || !m_uniform_stream_buffer)
+ {
+ PanicAlert("Failed to allocate streaming buffers");
+ return false;
+ }
- m_index_stream_buffer = StreamBuffer::Create(VK_BUFFER_USAGE_INDEX_BUFFER_BIT,
- INITIAL_INDEX_BUFFER_SIZE, MAX_INDEX_BUFFER_SIZE);
+ // The validation layer complains if max(offsets) + max(ubo_ranges) >= ubo_size.
+ // To work around this we reserve the maximum buffer size at all times, but only commit
+ // as many bytes as we use.
+ m_uniform_buffer_reserve_size = sizeof(PixelShaderConstants);
+ m_uniform_buffer_reserve_size = Common::AlignUp(m_uniform_buffer_reserve_size,
+ g_vulkan_context->GetUniformBufferAlignment()) +
+ sizeof(VertexShaderConstants);
+ m_uniform_buffer_reserve_size = Common::AlignUp(m_uniform_buffer_reserve_size,
+ g_vulkan_context->GetUniformBufferAlignment()) +
+ sizeof(GeometryShaderConstants);
- if (!m_vertex_stream_buffer || !m_index_stream_buffer)
+ // Prefer an 8MB buffer if possible, but use less if the device doesn't support this.
+ // This buffer is potentially going to be addressed as R8s in the future, so we assume
+ // that one element is one byte. This doesn't use min() because of a NDK compiler bug..
+ const u32 texel_buffer_size =
+ TEXEL_STREAM_BUFFER_SIZE > g_vulkan_context->GetDeviceLimits().maxTexelBufferElements ?
+ g_vulkan_context->GetDeviceLimits().maxTexelBufferElements :
+ TEXEL_STREAM_BUFFER_SIZE;
+ m_texel_stream_buffer =
+ StreamBuffer::Create(VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT, texel_buffer_size);
+ if (!m_texel_stream_buffer)
{
- PanicAlert("Failed to allocate streaming buffers");
+ PanicAlert("Failed to allocate streaming texel buffer");
return false;
}
- return true;
-}
+ static constexpr std::array<std::pair<TexelBufferFormat, VkFormat>, NUM_TEXEL_BUFFER_FORMATS>
+ format_mapping = {{
+ {TEXEL_BUFFER_FORMAT_R8_UINT, VK_FORMAT_R8_UINT},
+ {TEXEL_BUFFER_FORMAT_R16_UINT, VK_FORMAT_R16_UINT},
+ {TEXEL_BUFFER_FORMAT_RGBA8_UINT, VK_FORMAT_R8G8B8A8_UNORM},
+ {TEXEL_BUFFER_FORMAT_R32G32_UINT, VK_FORMAT_R32G32_UINT},
+ }};
+ for (const auto& it : format_mapping)
+ {
+ if ((m_texel_buffer_views[it.first] = CreateTexelBufferView(m_texel_stream_buffer->GetBuffer(),
+ it.second)) == VK_NULL_HANDLE)
+ {
+ PanicAlert("Failed to create texel buffer view");
+ return false;
+ }
+ }
-std::unique_ptr<NativeVertexFormat>
-VertexManager::CreateNativeVertexFormat(const PortableVertexDeclaration& vtx_decl)
-{
- return std::make_unique<VertexFormat>(vtx_decl);
-}
+ // Bind the buffers to all the known spots even if it's not used, to keep the driver happy.
+ UploadAllConstants();
+ StateTracker::GetInstance()->SetUtilityUniformBuffer(m_uniform_stream_buffer->GetBuffer(), 0,
+ sizeof(VertexShaderConstants));
+ for (u32 i = 0; i < NUM_COMPUTE_TEXEL_BUFFERS; i++)
+ {
+ StateTracker::GetInstance()->SetTexelBuffer(i,
+ m_texel_buffer_views[TEXEL_BUFFER_FORMAT_R8_UINT]);
+ }
-void VertexManager::UploadUtilityUniforms(const void* uniforms, u32 uniforms_size)
-{
- StateTracker::GetInstance()->UpdateConstants(uniforms, uniforms_size);
+ return true;
}
-void VertexManager::ResetBuffer(u32 vertex_stride, bool cull_all)
+void VertexManager::DestroyTexelBufferViews()
{
- if (cull_all)
+ for (VkBufferView view : m_texel_buffer_views)
{
- // Not drawing on the gpu, so store in a heap buffer instead
- m_cur_buffer_pointer = m_base_buffer_pointer = m_cpu_vertex_buffer.data();
- m_end_buffer_pointer = m_base_buffer_pointer + m_cpu_vertex_buffer.size();
- IndexGenerator::Start(m_cpu_index_buffer.data());
- return;
+ if (view != VK_NULL_HANDLE)
+ vkDestroyBufferView(g_vulkan_context->GetDevice(), view, nullptr);
}
+}
+void VertexManager::ResetBuffer(u32 vertex_stride)
+{
// Attempt to allocate from buffers
bool has_vbuffer_allocation =
m_vertex_stream_buffer->ReserveMemory(MAXVBUFFERSIZE, vertex_stride);
@@ -94,7 +147,7 @@ void VertexManager::ResetBuffer(u32 vertex_stride, bool cull_all)
{
// Flush any pending commands first, so that we can wait on the fences
WARN_LOG(VIDEO, "Executing command list while waiting for space in vertex/index buffer");
- Util::ExecuteCurrentCommandsAndRestoreState(false);
+ Renderer::GetInstance()->ExecuteCommandBuffer(false);
// Attempt to allocate again, this may cause a fence wait
if (!has_vbuffer_allocation)
@@ -122,10 +175,8 @@ void VertexManager::CommitBuffer(u32 num_vertices, u32 vertex_stride, u32 num_in
const u32 index_data_size = num_indices * sizeof(u16);
*out_base_vertex =
- vertex_stride > 0 ?
- static_cast<u32>(m_vertex_stream_buffer->GetCurrentOffset() / vertex_stride) :
- 0;
- *out_base_index = static_cast<u32>(m_index_stream_buffer->GetCurrentOffset() / sizeof(u16));
+ vertex_stride > 0 ? (m_vertex_stream_buffer->GetCurrentOffset() / vertex_stride) : 0;
+ *out_base_index = m_index_stream_buffer->GetCurrentOffset() / sizeof(u16);
m_vertex_stream_buffer->CommitMemory(vertex_data_size);
m_index_stream_buffer->CommitMemory(index_data_size);
@@ -138,43 +189,206 @@ void VertexManager::CommitBuffer(u32 num_vertices, u32 vertex_stride, u32 num_in
VK_INDEX_TYPE_UINT16);
}
-void VertexManager::UploadConstants()
+void VertexManager::UploadUniforms()
+{
+ UpdateVertexShaderConstants();
+ UpdateGeometryShaderConstants();
+ UpdatePixelShaderConstants();
+}
+
+void VertexManager::UpdateVertexShaderConstants()
+{
+ if (!VertexShaderManager::dirty || !ReserveConstantStorage())
+ return;
+
+ StateTracker::GetInstance()->SetGXUniformBuffer(
+ UBO_DESCRIPTOR_SET_BINDING_VS, m_uniform_stream_buffer->GetBuffer(),
+ m_uniform_stream_buffer->GetCurrentOffset(), sizeof(VertexShaderConstants));
+ std::memcpy(m_uniform_stream_buffer->GetCurrentHostPointer(), &VertexShaderManager::constants,
+ sizeof(VertexShaderConstants));
+ m_uniform_stream_buffer->CommitMemory(sizeof(VertexShaderConstants));
+ ADDSTAT(stats.thisFrame.bytesUniformStreamed, sizeof(VertexShaderConstants));
+ VertexShaderManager::dirty = false;
+}
+
+void VertexManager::UpdateGeometryShaderConstants()
+{
+ if (!GeometryShaderManager::dirty || !ReserveConstantStorage())
+ return;
+
+ StateTracker::GetInstance()->SetGXUniformBuffer(
+ UBO_DESCRIPTOR_SET_BINDING_GS, m_uniform_stream_buffer->GetBuffer(),
+ m_uniform_stream_buffer->GetCurrentOffset(), sizeof(GeometryShaderConstants));
+ std::memcpy(m_uniform_stream_buffer->GetCurrentHostPointer(), &GeometryShaderManager::constants,
+ sizeof(GeometryShaderConstants));
+ m_uniform_stream_buffer->CommitMemory(sizeof(GeometryShaderConstants));
+ ADDSTAT(stats.thisFrame.bytesUniformStreamed, sizeof(GeometryShaderConstants));
+ GeometryShaderManager::dirty = false;
+}
+
+void VertexManager::UpdatePixelShaderConstants()
+{
+ if (!PixelShaderManager::dirty || !ReserveConstantStorage())
+ return;
+
+ StateTracker::GetInstance()->SetGXUniformBuffer(
+ UBO_DESCRIPTOR_SET_BINDING_PS, m_uniform_stream_buffer->GetBuffer(),
+ m_uniform_stream_buffer->GetCurrentOffset(), sizeof(PixelShaderConstants));
+ std::memcpy(m_uniform_stream_buffer->GetCurrentHostPointer(), &PixelShaderManager::constants,
+ sizeof(PixelShaderConstants));
+ m_uniform_stream_buffer->CommitMemory(sizeof(PixelShaderConstants));
+ ADDSTAT(stats.thisFrame.bytesUniformStreamed, sizeof(PixelShaderConstants));
+ PixelShaderManager::dirty = false;
+}
+
+bool VertexManager::ReserveConstantStorage()
{
- StateTracker::GetInstance()->UpdateVertexShaderConstants();
- StateTracker::GetInstance()->UpdateGeometryShaderConstants();
- StateTracker::GetInstance()->UpdatePixelShaderConstants();
+ if (m_uniform_stream_buffer->ReserveMemory(m_uniform_buffer_reserve_size,
+ g_vulkan_context->GetUniformBufferAlignment()))
+ {
+ return true;
+ }
+
+ // The only places that call constant updates are safe to have state restored.
+ WARN_LOG(VIDEO, "Executing command buffer while waiting for space in uniform buffer");
+ Renderer::GetInstance()->ExecuteCommandBuffer(false);
+
+ // Since we are on a new command buffer, all constants have been invalidated, and we need
+ // to reupload them. We may as well do this now, since we're issuing a draw anyway.
+ UploadAllConstants();
+ return false;
}
-void VertexManager::DrawCurrentBatch(u32 base_index, u32 num_indices, u32 base_vertex)
+void VertexManager::UploadAllConstants()
{
- // Flush all EFB pokes and invalidate the peek cache.
- FramebufferManager::GetInstance()->InvalidatePeekCache();
- FramebufferManager::GetInstance()->FlushEFBPokes();
+ // We are free to re-use parts of the buffer now since we're uploading all constants.
+ const u32 ub_alignment = static_cast<u32>(g_vulkan_context->GetUniformBufferAlignment());
+ const u32 pixel_constants_offset = 0;
+ const u32 vertex_constants_offset =
+ Common::AlignUp(pixel_constants_offset + sizeof(PixelShaderConstants), ub_alignment);
+ const u32 geometry_constants_offset =
+ Common::AlignUp(vertex_constants_offset + sizeof(VertexShaderConstants), ub_alignment);
+ const u32 allocation_size = geometry_constants_offset + sizeof(GeometryShaderConstants);
- // If bounding box is enabled, we need to flush any changes first, then invalidate what we have.
- if (g_vulkan_context->SupportsBoundingBox())
+ // Allocate everything at once.
+ // We should only be here if the buffer was full and a command buffer was submitted anyway.
+ if (!m_uniform_stream_buffer->ReserveMemory(allocation_size, ub_alignment))
{
- BoundingBox* bounding_box = Renderer::GetInstance()->GetBoundingBox();
- bool bounding_box_enabled = (::BoundingBox::active && g_ActiveConfig.bBBoxEnable);
- if (bounding_box_enabled)
- {
- bounding_box->Flush();
- bounding_box->Invalidate();
- }
+ PanicAlert("Failed to allocate space for constants in streaming buffer");
+ return;
}
- // Bind all pending state to the command buffer
- if (StateTracker::GetInstance()->Bind())
+ // Update bindings
+ StateTracker::GetInstance()->SetGXUniformBuffer(
+ UBO_DESCRIPTOR_SET_BINDING_PS, m_uniform_stream_buffer->GetBuffer(),
+ m_uniform_stream_buffer->GetCurrentOffset() + pixel_constants_offset,
+ sizeof(PixelShaderConstants));
+ StateTracker::GetInstance()->SetGXUniformBuffer(
+ UBO_DESCRIPTOR_SET_BINDING_VS, m_uniform_stream_buffer->GetBuffer(),
+ m_uniform_stream_buffer->GetCurrentOffset() + vertex_constants_offset,
+ sizeof(VertexShaderConstants));
+ StateTracker::GetInstance()->SetGXUniformBuffer(
+ UBO_DESCRIPTOR_SET_BINDING_GS, m_uniform_stream_buffer->GetBuffer(),
+ m_uniform_stream_buffer->GetCurrentOffset() + geometry_constants_offset,
+ sizeof(GeometryShaderConstants));
+
+ // Copy the actual data in
+ std::memcpy(m_uniform_stream_buffer->GetCurrentHostPointer() + pixel_constants_offset,
+ &PixelShaderManager::constants, sizeof(PixelShaderConstants));
+ std::memcpy(m_uniform_stream_buffer->GetCurrentHostPointer() + vertex_constants_offset,
+ &VertexShaderManager::constants, sizeof(VertexShaderConstants));
+ std::memcpy(m_uniform_stream_buffer->GetCurrentHostPointer() + geometry_constants_offset,
+ &GeometryShaderManager::constants, sizeof(GeometryShaderConstants));
+
+ // Finally, flush buffer memory after copying
+ m_uniform_stream_buffer->CommitMemory(allocation_size);
+ ADDSTAT(stats.thisFrame.bytesUniformStreamed, allocation_size);
+
+ // Clear dirty flags
+ VertexShaderManager::dirty = false;
+ GeometryShaderManager::dirty = false;
+ PixelShaderManager::dirty = false;
+}
+
+void VertexManager::UploadUtilityUniforms(const void* data, u32 data_size)
+{
+ InvalidateConstants();
+ if (!m_uniform_stream_buffer->ReserveMemory(data_size,
+ g_vulkan_context->GetUniformBufferAlignment()))
{
- vkCmdDrawIndexed(g_command_buffer_mgr->GetCurrentCommandBuffer(), num_indices, 1, base_index,
- base_vertex, 0);
+ WARN_LOG(VIDEO, "Executing command buffer while waiting for ext space in uniform buffer");
+ Renderer::GetInstance()->ExecuteCommandBuffer(false);
}
- else
+
+ StateTracker::GetInstance()->SetUtilityUniformBuffer(
+ m_uniform_stream_buffer->GetBuffer(), m_uniform_stream_buffer->GetCurrentOffset(), data_size);
+ std::memcpy(m_uniform_stream_buffer->GetCurrentHostPointer(), data, data_size);
+ m_uniform_stream_buffer->CommitMemory(data_size);
+ ADDSTAT(stats.thisFrame.bytesUniformStreamed, data_size);
+}
+
+bool VertexManager::UploadTexelBuffer(const void* data, u32 data_size, TexelBufferFormat format,
+ u32* out_offset)
+{
+ if (data_size > m_texel_stream_buffer->GetCurrentSize())
+ return false;
+
+ const u32 elem_size = GetTexelBufferElementSize(format);
+ if (!m_texel_stream_buffer->ReserveMemory(data_size, elem_size))
{
- WARN_LOG(VIDEO, "Skipped draw of %u indices", num_indices);
+ // Try submitting cmdbuffer.
+ WARN_LOG(VIDEO, "Submitting command buffer while waiting for space in texel buffer");
+ Renderer::GetInstance()->ExecuteCommandBuffer(false, false);
+ if (!m_texel_stream_buffer->ReserveMemory(data_size, elem_size))
+ {
+ PanicAlert("Failed to allocate %u bytes from texel buffer", data_size);
+ return false;
+ }
}
- StateTracker::GetInstance()->OnDraw();
+ std::memcpy(m_texel_stream_buffer->GetCurrentHostPointer(), data, data_size);
+ *out_offset = static_cast<u32>(m_texel_stream_buffer->GetCurrentOffset()) / elem_size;
+ m_texel_stream_buffer->CommitMemory(data_size);
+ ADDSTAT(stats.thisFrame.bytesUniformStreamed, data_size);
+ StateTracker::GetInstance()->SetTexelBuffer(0, m_texel_buffer_views[format]);
+ return true;
}
+bool VertexManager::UploadTexelBuffer(const void* data, u32 data_size, TexelBufferFormat format,
+ u32* out_offset, const void* palette_data, u32 palette_size,
+ TexelBufferFormat palette_format, u32* out_palette_offset)
+{
+ const u32 elem_size = GetTexelBufferElementSize(format);
+ const u32 palette_elem_size = GetTexelBufferElementSize(palette_format);
+ const u32 reserve_size = data_size + palette_size + palette_elem_size;
+ if (reserve_size > m_texel_stream_buffer->GetCurrentSize())
+ return false;
+
+ if (!m_texel_stream_buffer->ReserveMemory(reserve_size, elem_size))
+ {
+ // Try submitting cmdbuffer.
+ WARN_LOG(VIDEO, "Submitting command buffer while waiting for space in texel buffer");
+ Renderer::GetInstance()->ExecuteCommandBuffer(false, false);
+ if (!m_texel_stream_buffer->ReserveMemory(reserve_size, elem_size))
+ {
+ PanicAlert("Failed to allocate %u bytes from texel buffer", reserve_size);
+ return false;
+ }
+ }
+
+ const u32 palette_byte_offset = Common::AlignUp(data_size, palette_elem_size);
+ std::memcpy(m_texel_stream_buffer->GetCurrentHostPointer(), data, data_size);
+ std::memcpy(m_texel_stream_buffer->GetCurrentHostPointer() + palette_byte_offset, palette_data,
+ palette_size);
+ *out_offset = static_cast<u32>(m_texel_stream_buffer->GetCurrentOffset()) / elem_size;
+ *out_palette_offset =
+ (static_cast<u32>(m_texel_stream_buffer->GetCurrentOffset()) + palette_byte_offset) /
+ palette_elem_size;
+
+ m_texel_stream_buffer->CommitMemory(palette_byte_offset + palette_size);
+ ADDSTAT(stats.thisFrame.bytesUniformStreamed, palette_byte_offset + palette_size);
+ StateTracker::GetInstance()->SetTexelBuffer(0, m_texel_buffer_views[format]);
+ StateTracker::GetInstance()->SetTexelBuffer(1, m_texel_buffer_views[palette_format]);
+ return true;
+}
} // namespace Vulkan
diff --git a/Source/Core/VideoBackends/Vulkan/VertexManager.h b/Source/Core/VideoBackends/Vulkan/VertexManager.h
index 65c31e11f4..0a71903c83 100644
--- a/Source/Core/VideoBackends/Vulkan/VertexManager.h
+++ b/Source/Core/VideoBackends/Vulkan/VertexManager.h
@@ -8,6 +8,7 @@
#include <vector>
#include "Common/CommonTypes.h"
+#include "VideoBackends/Vulkan/VulkanLoader.h"
#include "VideoCommon/VertexManagerBase.h"
namespace Vulkan
@@ -20,26 +21,38 @@ public:
VertexManager();
~VertexManager();
- static VertexManager* GetInstance();
-
- bool Initialize();
-
- std::unique_ptr<NativeVertexFormat>
- CreateNativeVertexFormat(const PortableVertexDeclaration& vtx_decl) override;
+ bool Initialize() override;
void UploadUtilityUniforms(const void* uniforms, u32 uniforms_size) override;
+ bool UploadTexelBuffer(const void* data, u32 data_size, TexelBufferFormat format,
+ u32* out_offset) override;
+ bool UploadTexelBuffer(const void* data, u32 data_size, TexelBufferFormat format, u32* out_offset,
+ const void* palette_data, u32 palette_size,
+ TexelBufferFormat palette_format, u32* out_palette_offset) override;
protected:
- void ResetBuffer(u32 vertex_stride, bool cull_all) override;
+ void ResetBuffer(u32 vertex_stride) override;
void CommitBuffer(u32 num_vertices, u32 vertex_stride, u32 num_indices, u32* out_base_vertex,
u32* out_base_index) override;
- void UploadConstants() override;
- void DrawCurrentBatch(u32 base_index, u32 num_indices, u32 base_vertex) override;
+ void UploadUniforms() override;
+
+ void DestroyTexelBufferViews();
+
+ void UpdateVertexShaderConstants();
+ void UpdateGeometryShaderConstants();
+ void UpdatePixelShaderConstants();
- std::vector<u8> m_cpu_vertex_buffer;
- std::vector<u16> m_cpu_index_buffer;
+ // Allocates storage in the uniform buffer of the specified size. If this storage cannot be
+ // allocated immediately, the current command buffer will be submitted and all stage's
+ // constants will be re-uploaded. false will be returned in this case, otherwise true.
+ bool ReserveConstantStorage();
+ void UploadAllConstants();
std::unique_ptr<StreamBuffer> m_vertex_stream_buffer;
std::unique_ptr<StreamBuffer> m_index_stream_buffer;
+ std::unique_ptr<StreamBuffer> m_uniform_stream_buffer;
+ std::unique_ptr<StreamBuffer> m_texel_stream_buffer;
+ std::array<VkBufferView, NUM_TEXEL_BUFFER_FORMATS> m_texel_buffer_views = {};
+ u32 m_uniform_buffer_reserve_size = 0;
};
-}
+} // namespace Vulkan
diff --git a/Source/Core/VideoBackends/Vulkan/Vulkan.vcxproj b/Source/Core/VideoBackends/Vulkan/Vulkan.vcxproj
index 5b465ff733..fab11bab7e 100644
--- a/Source/Core/VideoBackends/Vulkan/Vulkan.vcxproj
+++ b/Source/Core/VideoBackends/Vulkan/Vulkan.vcxproj
@@ -38,14 +38,9 @@
<ItemGroup>
<ClCompile Include="BoundingBox.cpp" />
<ClCompile Include="CommandBufferManager.cpp" />
- <ClCompile Include="FramebufferManager.cpp" />
<ClCompile Include="main.cpp" />
- <ClCompile Include="PostProcessing.cpp" />
- <ClCompile Include="ShaderCache.cpp" />
- <ClCompile Include="TextureConverter.cpp" />
<ClCompile Include="PerfQuery.cpp" />
<ClCompile Include="StagingBuffer.cpp" />
- <ClCompile Include="Util.cpp" />
<ClCompile Include="VertexFormat.cpp" />
<ClCompile Include="ObjectCache.cpp" />
<ClCompile Include="Renderer.cpp" />
@@ -53,8 +48,6 @@
<ClCompile Include="StateTracker.cpp" />
<ClCompile Include="StreamBuffer.cpp" />
<ClCompile Include="SwapChain.cpp" />
- <ClCompile Include="Texture2D.cpp" />
- <ClCompile Include="TextureCache.cpp" />
<ClCompile Include="VertexManager.cpp" />
<ClCompile Include="VKPipeline.cpp" />
<ClCompile Include="VKShader.cpp" />
@@ -65,13 +58,8 @@
<ItemGroup>
<ClInclude Include="BoundingBox.h" />
<ClInclude Include="CommandBufferManager.h" />
- <ClInclude Include="FramebufferManager.h" />
<ClInclude Include="Constants.h" />
- <ClInclude Include="PostProcessing.h" />
- <ClInclude Include="ShaderCache.h" />
- <ClInclude Include="TextureConverter.h" />
<ClInclude Include="StagingBuffer.h" />
- <ClInclude Include="Util.h" />
<ClInclude Include="VertexFormat.h" />
<ClInclude Include="PerfQuery.h" />
<ClInclude Include="ObjectCache.h" />
@@ -80,8 +68,6 @@
<ClInclude Include="StateTracker.h" />
<ClInclude Include="StreamBuffer.h" />
<ClInclude Include="SwapChain.h" />
- <ClInclude Include="Texture2D.h" />
- <ClInclude Include="TextureCache.h" />
<ClInclude Include="VertexManager.h" />
<ClInclude Include="VideoBackend.h" />
<ClInclude Include="VKPipeline.h" />
diff --git a/Source/Core/VideoBackends/Vulkan/VulkanContext.cpp b/Source/Core/VideoBackends/Vulkan/VulkanContext.cpp
index 4eaea78865..72f929af1c 100644
--- a/Source/Core/VideoBackends/Vulkan/VulkanContext.cpp
+++ b/Source/Core/VideoBackends/Vulkan/VulkanContext.cpp
@@ -255,6 +255,7 @@ void VulkanContext::PopulateBackendInfo(VideoConfig* config)
config->backend_info.bSupportsDynamicSamplerIndexing = true; // Assumed support.
config->backend_info.bSupportsPostProcessing = true; // Assumed support.
config->backend_info.bSupportsBackgroundCompiling = true; // Assumed support.
+ config->backend_info.bSupportsCopyToVram = true; // Assumed support.
config->backend_info.bSupportsDualSourceBlend = false; // Dependent on features.
config->backend_info.bSupportsGeometryShaders = false; // Dependent on features.
config->backend_info.bSupportsGSInstancing = false; // Dependent on features.
@@ -264,10 +265,10 @@ void VulkanContext::PopulateBackendInfo(VideoConfig* config)
config->backend_info.bSupportsDepthClamp = false; // Dependent on features.
config->backend_info.bSupportsST3CTextures = false; // Dependent on features.
config->backend_info.bSupportsBPTCTextures = false; // Dependent on features.
+ config->backend_info.bSupportsLogicOp = false; // Dependent on features.
+ config->backend_info.bSupportsLargePoints = false; // Dependent on features.
config->backend_info.bSupportsReversedDepthRange = false; // No support yet due to driver bugs.
- config->backend_info.bSupportsLogicOp = false; // Dependent on features.
- config->backend_info.bSupportsCopyToVram = true; // Assumed support.
- config->backend_info.bSupportsFramebufferFetch = false;
+ config->backend_info.bSupportsFramebufferFetch = false; // No support.
}
void VulkanContext::PopulateBackendInfoAdapters(VideoConfig* config, const GPUList& gpu_list)
@@ -286,6 +287,7 @@ void VulkanContext::PopulateBackendInfoFeatures(VideoConfig* config, VkPhysicalD
const VkPhysicalDeviceFeatures& features)
{
config->backend_info.MaxTextureSize = properties.limits.maxImageDimension2D;
+ config->backend_info.bUsesLowerLeftOrigin = false;
config->backend_info.bSupportsDualSourceBlend = (features.dualSrcBlend == VK_TRUE);
config->backend_info.bSupportsGeometryShaders = (features.geometryShader == VK_TRUE);
config->backend_info.bSupportsGSInstancing = (features.geometryShader == VK_TRUE);
@@ -311,6 +313,13 @@ void VulkanContext::PopulateBackendInfoFeatures(VideoConfig* config, VkPhysicalD
config->backend_info.bSupportsST3CTextures = supports_bc;
config->backend_info.bSupportsBPTCTextures = supports_bc;
+ // Some devices don't support point sizes >1 (e.g. Adreno).
+ // If we can't use a point size above our maximum IR, use triangles instead for EFB pokes.
+ // This means a 6x increase in the size of the vertices, though.
+ config->backend_info.bSupportsLargePoints = features.largePoints &&
+ properties.limits.pointSizeRange[0] <= 1.0f &&
+ properties.limits.pointSizeRange[1] >= 16;
+
// Our usage of primitive restart appears to be broken on AMD's binary drivers.
// Seems to be fine on GCN Gen 1-2, unconfirmed on GCN Gen 3, causes driver resets on GCN Gen 4.
if (DriverDetails::HasBug(DriverDetails::BUG_PRIMITIVE_RESTART))
@@ -323,11 +332,11 @@ void VulkanContext::PopulateBackendInfoMultisampleModes(
// Query image support for the EFB texture formats.
VkImageFormatProperties efb_color_properties = {};
vkGetPhysicalDeviceImageFormatProperties(
- gpu, EFB_COLOR_TEXTURE_FORMAT, VK_IMAGE_TYPE_2D, VK_IMAGE_TILING_OPTIMAL,
+ gpu, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_TYPE_2D, VK_IMAGE_TILING_OPTIMAL,
VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, 0, &efb_color_properties);
VkImageFormatProperties efb_depth_properties = {};
vkGetPhysicalDeviceImageFormatProperties(
- gpu, EFB_DEPTH_TEXTURE_FORMAT, VK_IMAGE_TYPE_2D, VK_IMAGE_TILING_OPTIMAL,
+ gpu, VK_FORMAT_D32_SFLOAT, VK_IMAGE_TYPE_2D, VK_IMAGE_TILING_OPTIMAL,
VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, 0, &efb_depth_properties);
// We can only support MSAA if it's supported on our render target formats.
@@ -456,15 +465,6 @@ bool VulkanContext::SelectDeviceFeatures()
if (!available_features.occlusionQueryPrecise)
WARN_LOG(VIDEO, "Vulkan: Missing precise occlusion queries. Perf queries will be inaccurate.");
- // Check push constant size.
- if (properties.limits.maxPushConstantsSize < static_cast<u32>(PUSH_CONSTANT_BUFFER_SIZE))
- {
- PanicAlert("Vulkan: Push contant buffer size %u is below minimum %u.",
- properties.limits.maxPushConstantsSize, static_cast<u32>(PUSH_CONSTANT_BUFFER_SIZE));
-
- return false;
- }
-
// Enable the features we use.
m_device_features.dualSrcBlend = available_features.dualSrcBlend;
m_device_features.geometryShader = available_features.geometryShader;
diff --git a/Source/Core/VideoBackends/Vulkan/VulkanContext.h b/Source/Core/VideoBackends/Vulkan/VulkanContext.h
index 6b254e24c0..3f4492bc4a 100644
--- a/Source/Core/VideoBackends/Vulkan/VulkanContext.h
+++ b/Source/Core/VideoBackends/Vulkan/VulkanContext.h
@@ -76,10 +76,6 @@ public:
{
return m_device_features.samplerAnisotropy == VK_TRUE;
}
- bool SupportsGeometryShaders() const { return m_device_features.geometryShader == VK_TRUE; }
- bool SupportsDualSourceBlend() const { return m_device_features.dualSrcBlend == VK_TRUE; }
- bool SupportsLogicOps() const { return m_device_features.logicOp == VK_TRUE; }
- bool SupportsBoundingBox() const { return m_device_features.fragmentStoresAndAtomics == VK_TRUE; }
bool SupportsPreciseOcclusionQueries() const
{
return m_device_features.occlusionQueryPrecise == VK_TRUE;
diff --git a/Source/Core/VideoBackends/Vulkan/main.cpp b/Source/Core/VideoBackends/Vulkan/main.cpp
index 8055aab178..911f8d1991 100644
--- a/Source/Core/VideoBackends/Vulkan/main.cpp
+++ b/Source/Core/VideoBackends/Vulkan/main.cpp
@@ -9,18 +9,17 @@
#include "VideoBackends/Vulkan/CommandBufferManager.h"
#include "VideoBackends/Vulkan/Constants.h"
-#include "VideoBackends/Vulkan/FramebufferManager.h"
#include "VideoBackends/Vulkan/ObjectCache.h"
#include "VideoBackends/Vulkan/PerfQuery.h"
#include "VideoBackends/Vulkan/Renderer.h"
#include "VideoBackends/Vulkan/StateTracker.h"
#include "VideoBackends/Vulkan/SwapChain.h"
-#include "VideoBackends/Vulkan/TextureCache.h"
#include "VideoBackends/Vulkan/VertexManager.h"
#include "VideoBackends/Vulkan/VideoBackend.h"
#include "VideoBackends/Vulkan/VulkanContext.h"
-#include "VideoCommon/OnScreenDisplay.h"
+#include "VideoCommon/FramebufferManager.h"
+#include "VideoCommon/TextureCacheBase.h"
#include "VideoCommon/VideoBackendBase.h"
#include "VideoCommon/VideoConfig.h"
@@ -200,10 +199,9 @@ bool VideoBackend::Initialize(const WindowSystemInfo& wsi)
return false;
}
- // Remaining classes are also dependent on object/shader cache.
+ // Remaining classes are also dependent on object cache.
g_object_cache = std::make_unique<ObjectCache>();
- g_shader_cache = std::make_unique<ShaderCache>();
- if (!g_object_cache->Initialize() || !g_shader_cache->Initialize())
+ if (!g_object_cache->Initialize())
{
PanicAlert("Failed to initialize Vulkan object cache.");
Shutdown();
@@ -223,29 +221,31 @@ bool VideoBackend::Initialize(const WindowSystemInfo& wsi)
}
}
+ if (!StateTracker::CreateInstance())
+ {
+ PanicAlert("Failed to create state tracker");
+ Shutdown();
+ return false;
+ }
+
// Create main wrapper instances.
- g_framebuffer_manager = std::make_unique<FramebufferManager>();
g_renderer = std::make_unique<Renderer>(std::move(swap_chain), wsi.render_surface_scale);
g_vertex_manager = std::make_unique<VertexManager>();
- g_texture_cache = std::make_unique<TextureCache>();
- ::g_shader_cache = std::make_unique<VideoCommon::ShaderCache>();
+ g_shader_cache = std::make_unique<VideoCommon::ShaderCache>();
+ g_framebuffer_manager = std::make_unique<FramebufferManager>();
+ g_texture_cache = std::make_unique<TextureCacheBase>();
g_perf_query = std::make_unique<PerfQuery>();
- // Invoke init methods on main wrapper classes.
- // These have to be done before the others because the destructors
- // for the remaining classes may call methods on these.
- if (!StateTracker::CreateInstance() || !FramebufferManager::GetInstance()->Initialize() ||
- !Renderer::GetInstance()->Initialize() || !VertexManager::GetInstance()->Initialize() ||
- !TextureCache::GetInstance()->Initialize() || !PerfQuery::GetInstance()->Initialize() ||
- !::g_shader_cache->Initialize())
+ if (!g_vertex_manager->Initialize() || !g_shader_cache->Initialize() ||
+ !g_renderer->Initialize() || !g_framebuffer_manager->Initialize() ||
+ !g_texture_cache->Initialize() || !PerfQuery::GetInstance()->Initialize())
{
- PanicAlert("Failed to initialize Vulkan classes.");
+ PanicAlert("Failed to initialize renderer classes");
Shutdown();
return false;
}
- // Display the name so the user knows which device was actually created.
- INFO_LOG(VIDEO, "Vulkan Device: %s", g_vulkan_context->GetDeviceProperties().deviceName);
+ g_shader_cache->InitializeShaderCache();
return true;
}
@@ -254,23 +254,23 @@ void VideoBackend::Shutdown()
if (g_command_buffer_mgr)
g_command_buffer_mgr->WaitForGPUIdle();
- if (::g_shader_cache)
- ::g_shader_cache->Shutdown();
+ if (g_shader_cache)
+ g_shader_cache->Shutdown();
+
+ if (g_object_cache)
+ g_object_cache->Shutdown();
if (g_renderer)
g_renderer->Shutdown();
g_perf_query.reset();
- ::g_shader_cache.reset();
g_texture_cache.reset();
- g_vertex_manager.reset();
- g_renderer.reset();
g_framebuffer_manager.reset();
- StateTracker::DestroyInstance();
- if (g_shader_cache)
- g_shader_cache->Shutdown();
g_shader_cache.reset();
+ g_vertex_manager.reset();
+ g_renderer.reset();
g_object_cache.reset();
+ StateTracker::DestroyInstance();
g_command_buffer_mgr.reset();
g_vulkan_context.reset();
ShutdownShared();