From c64064024db4ab4ebdd063f0da9f495aa5f36c85 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sat, 10 Oct 2015 16:41:19 +0200 Subject: [PATCH 001/116] Initial vulkan code. This was squashed from nine commits but using old versions of Vulkan. --- Core/Config.h | 4 + Core/Core.cpp | 1 + Core/CoreParameter.h | 2 + GPU/Common/ShaderCommon.h | 1 + GPU/Common/TextureCacheCommon.h | 3 + GPU/GPU.cpp | 4 + GPU/GPU.vcxproj | 19 + GPU/GPU.vcxproj.filters | 19 + GPU/Vulkan/DrawEngineVulkan.cpp | 466 +++++ GPU/Vulkan/DrawEngineVulkan.h | 194 +++ GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp | 543 ++++++ GPU/Vulkan/FragmentShaderGeneratorVulkan.h | 25 + GPU/Vulkan/FramebufferVulkan.cpp | 0 GPU/Vulkan/FramebufferVulkan.h | 107 ++ GPU/Vulkan/GPU_Vulkan.cpp | 116 ++ GPU/Vulkan/GPU_Vulkan.h | 172 ++ GPU/Vulkan/PipelineManagerVulkan.cpp | 221 +++ GPU/Vulkan/PipelineManagerVulkan.h | 106 ++ GPU/Vulkan/ShaderCompiler.cpp | 23 + GPU/Vulkan/ShaderCompiler.h | 27 + GPU/Vulkan/ShaderManagerVulkan.cpp | 612 +++++++ GPU/Vulkan/ShaderManagerVulkan.h | 261 +++ GPU/Vulkan/StateMappingVulkan.cpp | 314 ++++ GPU/Vulkan/TextureCacheVulkan.h | 42 + GPU/Vulkan/VertexShaderGeneratorVulkan.cpp | 618 +++++++ GPU/Vulkan/VertexShaderGeneratorVulkan.h | 5 + GPU/Vulkan/VulkanUtil.h | 5 + UI/EmuScreen.cpp | 15 +- UI/GameSettingsScreen.cpp | 2 +- UI/MiscScreens.cpp | 2 +- Windows/GPU/WindowsVulkanContext.cpp | 107 ++ Windows/GPU/WindowsVulkanContext.h | 36 + Windows/PPSSPP.sln | 101 ++ Windows/PPSSPP.vcxproj | 21 +- Windows/PPSSPP.vcxproj.filters | 2 + Windows/WindowsHost.cpp | 4 + ext/glslang.vcxproj | 11 +- ext/glslang.vcxproj.filters | 15 +- ext/native/math/dataconv.h | 2 +- ext/native/native.vcxproj | 14 +- ext/native/native.vcxproj.filters | 18 +- ext/native/thin3d/VulkanContext.cpp | 1619 ++++++++++++++++++ ext/native/thin3d/VulkanContext.h | 277 +++ ext/native/thin3d/thin3d.cpp | 69 +- ext/native/thin3d/thin3d.h | 17 +- ext/native/thin3d/thin3d_d3d9.cpp | 8 +- ext/native/thin3d/thin3d_gl.cpp | 8 +- ext/native/thin3d/thin3d_vulkan.cpp | 1384 +++++++++++++++ ext/native/thin3d/vulkan_utils.cpp | 173 ++ ext/native/thin3d/vulkan_utils.h | 70 + ext/native/ui/ui_screen.cpp | 4 +- headless/Headless.cpp | 1 + headless/Headless.vcxproj | 10 +- unittest/UnitTest.cpp | 1 + unittest/UnitTests.vcxproj | 10 +- 55 files changed, 7851 insertions(+), 60 deletions(-) create mode 100644 GPU/Vulkan/DrawEngineVulkan.cpp create mode 100644 GPU/Vulkan/DrawEngineVulkan.h create mode 100644 GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp create mode 100644 GPU/Vulkan/FragmentShaderGeneratorVulkan.h create mode 100644 GPU/Vulkan/FramebufferVulkan.cpp create mode 100644 GPU/Vulkan/FramebufferVulkan.h create mode 100644 GPU/Vulkan/GPU_Vulkan.cpp create mode 100644 GPU/Vulkan/GPU_Vulkan.h create mode 100644 GPU/Vulkan/PipelineManagerVulkan.cpp create mode 100644 GPU/Vulkan/PipelineManagerVulkan.h create mode 100644 GPU/Vulkan/ShaderCompiler.cpp create mode 100644 GPU/Vulkan/ShaderCompiler.h create mode 100644 GPU/Vulkan/ShaderManagerVulkan.cpp create mode 100644 GPU/Vulkan/ShaderManagerVulkan.h create mode 100644 GPU/Vulkan/StateMappingVulkan.cpp create mode 100644 GPU/Vulkan/TextureCacheVulkan.h create mode 100644 GPU/Vulkan/VertexShaderGeneratorVulkan.cpp create mode 100644 GPU/Vulkan/VertexShaderGeneratorVulkan.h create mode 100644 GPU/Vulkan/VulkanUtil.h create mode 100644 Windows/GPU/WindowsVulkanContext.cpp create mode 100644 Windows/GPU/WindowsVulkanContext.h create mode 100644 ext/native/thin3d/VulkanContext.cpp create mode 100644 ext/native/thin3d/VulkanContext.h create mode 100644 ext/native/thin3d/thin3d_vulkan.cpp create mode 100644 ext/native/thin3d/vulkan_utils.cpp create mode 100644 ext/native/thin3d/vulkan_utils.h diff --git a/Core/Config.h b/Core/Config.h index df58435160..8618adaa46 100644 --- a/Core/Config.h +++ b/Core/Config.h @@ -50,10 +50,14 @@ enum BufferFilter { enum class GPUBackend { OPENGL = 0, DIRECT3D9 = 1, + DIRECT3D11 = 2, + VULKAN = 3, }; enum { GPU_BACKEND_OPENGL = (int)GPUBackend::OPENGL, GPU_BACKEND_DIRECT3D9 = (int)GPUBackend::DIRECT3D9, + GPU_BACKEND_DIRECT3D11 = (int)GPUBackend::DIRECT3D11, + GPU_BACKEND_VULKAN = (int)GPUBackend::VULKAN, }; enum AudioBackendType { diff --git a/Core/Core.cpp b/Core/Core.cpp index f588b8c38d..508c69ce0d 100644 --- a/Core/Core.cpp +++ b/Core/Core.cpp @@ -34,6 +34,7 @@ #ifdef _WIN32 #include "Windows/GPU/WindowsGLContext.h" #include "Windows/GPU/D3D9Context.h" +#include "Windows/GPU/WindowsVulkanContext.h" #include "Windows/InputDevice.h" #endif diff --git a/Core/CoreParameter.h b/Core/CoreParameter.h index 0b60f84189..1cbe2aab12 100644 --- a/Core/CoreParameter.h +++ b/Core/CoreParameter.h @@ -31,6 +31,8 @@ enum GPUCore { GPU_GLES, GPU_SOFTWARE, GPU_DIRECTX9, + GPU_DIRECTX11, + GPU_VULKAN, }; class FileLoader; diff --git a/GPU/Common/ShaderCommon.h b/GPU/Common/ShaderCommon.h index ef2a05c26b..8d23dfd9a0 100644 --- a/GPU/Common/ShaderCommon.h +++ b/GPU/Common/ShaderCommon.h @@ -22,6 +22,7 @@ enum DebugShaderType { SHADER_TYPE_FRAGMENT = 1, SHADER_TYPE_GEOMETRY = 2, SHADER_TYPE_VERTEXLOADER = 3, // Not really a shader, but might as well re-use this mechanism + SHADER_TYPE_PIPELINE = 4, // Vulkan and DX12 combines a bunch of state into pipeline objects. Might as well make them inspectable. }; enum DebugShaderStringType { diff --git a/GPU/Common/TextureCacheCommon.h b/GPU/Common/TextureCacheCommon.h index 95ff12aa60..664f107ffe 100644 --- a/GPU/Common/TextureCacheCommon.h +++ b/GPU/Common/TextureCacheCommon.h @@ -24,6 +24,9 @@ #include "GPU/Common/GPUDebugInterface.h" #include "Common/MemoryUtil.h" +#include +#include + enum TextureFiltering { TEX_FILTER_AUTO = 1, TEX_FILTER_NEAREST = 2, diff --git a/GPU/GPU.cpp b/GPU/GPU.cpp index 915d953bfb..36e9564291 100644 --- a/GPU/GPU.cpp +++ b/GPU/GPU.cpp @@ -20,6 +20,7 @@ #include "GPU/GPU.h" #include "GPU/GPUInterface.h" #include "GPU/GLES/GLES_GPU.h" +#include "GPU/Vulkan/GPU_Vulkan.h" #include "GPU/Null/NullGpu.h" #include "GPU/Software/SoftGpu.h" @@ -57,6 +58,9 @@ bool GPU_Init(GraphicsContext *ctx) { SetGPU(new DIRECTX9_GPU(ctx)); #endif break; + case GPU_VULKAN: + SetGPU(new GPU_Vulkan()); + break; } return gpu != NULL; diff --git a/GPU/GPU.vcxproj b/GPU/GPU.vcxproj index f089cec7f4..8319755356 100644 --- a/GPU/GPU.vcxproj +++ b/GPU/GPU.vcxproj @@ -244,6 +244,16 @@ + + + + + + + + + + @@ -322,6 +332,15 @@ + + + + + + + + + diff --git a/GPU/GPU.vcxproj.filters b/GPU/GPU.vcxproj.filters index d4bfb7b987..1a1beed97b 100644 --- a/GPU/GPU.vcxproj.filters +++ b/GPU/GPU.vcxproj.filters @@ -201,6 +201,16 @@ Common + + + + + + + + + + @@ -386,5 +396,14 @@ Common + + + + + + + + + \ No newline at end of file diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp new file mode 100644 index 0000000000..3facb84fab --- /dev/null +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -0,0 +1,466 @@ +#include "GPU/Vulkan/DrawEngineVulkan.h" + + +// Copyright (c) 2012- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#include "base/logging.h" +#include "base/timeutil.h" + +#include "Common/MemoryUtil.h" +#include "Core/MemMap.h" +#include "Core/Host.h" +#include "Core/System.h" +#include "Core/Reporting.h" +#include "Core/Config.h" +#include "Core/CoreTiming.h" + +#include "GPU/Math3D.h" +#include "GPU/GPUState.h" +#include "GPU/ge_constants.h" + +#include "GPU/Common/TextureDecoder.h" +#include "GPU/Common/SplineCommon.h" +#include "GPU/Common/TransformCommon.h" +#include "GPU/Common/VertexDecoderCommon.h" +#include "GPU/Common/SoftwareTransformCommon.h" +#include "GPU/Common/DrawEngineCommon.h" +#include "GPU/Vulkan/DrawEngineVulkan.h" +#include "GPU/Vulkan/TextureCacheVulkan.h" +#include "GPU/Vulkan/ShaderManagerVulkan.h" +#include "GPU/Vulkan/PipelineManagerVulkan.h" +#include "GPU/Vulkan/GPU_Vulkan.h" + +const VkPrimitiveTopology prim[8] = { + VK_PRIMITIVE_TOPOLOGY_POINT_LIST, + VK_PRIMITIVE_TOPOLOGY_LINE_LIST, + VK_PRIMITIVE_TOPOLOGY_LINE_STRIP, + VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, + VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP, + VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN, + VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, // Vulkan doesn't do quads. We could do strips with restart-index though. We could also do RECT primitives in the geometry shader. +}; + +enum { + TRANSFORMED_VERTEX_BUFFER_SIZE = VERTEX_BUFFER_MAX * sizeof(TransformedVertex) +}; + +DrawEngineVulkan::DrawEngineVulkan() + : decodedVerts_(0), + prevPrim_(GE_PRIM_INVALID), + lastVType_(-1), + pipelineManager_(nullptr), + textureCache_(nullptr), + framebufferManager_(nullptr), + numDrawCalls(0), + vertexCountInDrawCalls(0), + decodeCounter_(0), + dcid_(0), + fboTexNeedBind_(false), + fboTexBound_(false) { + + memset(&decOptions_, 0, sizeof(decOptions_)); + decOptions_.expandAllUVtoFloat = true; + decOptions_.expandAllWeightsToFloat = true; + decOptions_.expand8BitNormalsToFloat = true; + + // Allocate nicely aligned memory. Maybe graphics drivers will + // appreciate it. + // All this is a LOT of memory, need to see if we can cut down somehow. + decoded = (u8 *)AllocateMemoryPages(DECODED_VERTEX_BUFFER_SIZE); + decIndex = (u16 *)AllocateMemoryPages(DECODED_INDEX_BUFFER_SIZE); + splineBuffer = (u8 *)AllocateMemoryPages(SPLINE_BUFFER_SIZE); + transformed = (TransformedVertex *)AllocateMemoryPages(TRANSFORMED_VERTEX_BUFFER_SIZE); + transformedExpanded = (TransformedVertex *)AllocateMemoryPages(3 * TRANSFORMED_VERTEX_BUFFER_SIZE); + + indexGen.Setup(decIndex); +} + +DrawEngineVulkan::~DrawEngineVulkan() { + FreeMemoryPages(decoded, DECODED_VERTEX_BUFFER_SIZE); + FreeMemoryPages(decIndex, DECODED_INDEX_BUFFER_SIZE); + FreeMemoryPages(splineBuffer, SPLINE_BUFFER_SIZE); + FreeMemoryPages(transformed, TRANSFORMED_VERTEX_BUFFER_SIZE); + FreeMemoryPages(transformedExpanded, 3 * TRANSFORMED_VERTEX_BUFFER_SIZE); +} + +VertexDecoder *DrawEngineVulkan::GetVertexDecoder(u32 vtype) { + auto iter = decoderMap_.find(vtype); + if (iter != decoderMap_.end()) + return iter->second; + VertexDecoder *dec = new VertexDecoder(); + dec->SetVertexType(vtype, decOptions_, decJitCache_); + decoderMap_[vtype] = dec; + return dec; +} + +void DrawEngineVulkan::SetupVertexDecoder(u32 vertType) { + SetupVertexDecoderInternal(vertType); +} + +inline void DrawEngineVulkan::SetupVertexDecoderInternal(u32 vertType) { + // As the decoder depends on the UVGenMode when we use UV prescale, we simply mash it + // into the top of the verttype where there are unused bits. + const u32 vertTypeID = (vertType & 0xFFFFFF) | (gstate.getUVGenMode() << 24); + + // If vtype has changed, setup the vertex decoder. + if (vertTypeID != lastVType_) { + dec_ = GetVertexDecoder(vertTypeID); + lastVType_ = vertTypeID; + } +} + +void DrawEngineVulkan::SubmitPrim(void *verts, void *inds, GEPrimitiveType prim, int vertexCount, u32 vertType, int *bytesRead) { + if (!indexGen.PrimCompatible(prevPrim_, prim) || numDrawCalls >= MAX_DEFERRED_DRAW_CALLS || vertexCountInDrawCalls + vertexCount > VERTEX_BUFFER_MAX) + Flush(cmd_); + + // TODO: Is this the right thing to do? + if (prim == GE_PRIM_KEEP_PREVIOUS) { + prim = prevPrim_ != GE_PRIM_INVALID ? prevPrim_ : GE_PRIM_POINTS; + } else { + prevPrim_ = prim; + } + + SetupVertexDecoderInternal(vertType); + + *bytesRead = vertexCount * dec_->VertexSize(); + + if ((vertexCount < 2 && prim > 0) || (vertexCount < 3 && prim > 2 && prim != GE_PRIM_RECTANGLES)) + return; + + DeferredDrawCall &dc = drawCalls[numDrawCalls]; + dc.verts = verts; + dc.inds = inds; + dc.vertType = vertType; + dc.indexType = (vertType & GE_VTYPE_IDX_MASK) >> GE_VTYPE_IDX_SHIFT; + dc.prim = prim; + dc.vertexCount = vertexCount; + + u32 dhash = dcid_; + dhash ^= (u32)(uintptr_t)verts; + dhash = __rotl(dhash, 13); + dhash ^= (u32)(uintptr_t)inds; + dhash = __rotl(dhash, 13); + dhash ^= (u32)vertType; + dhash = __rotl(dhash, 13); + dhash ^= (u32)vertexCount; + dhash = __rotl(dhash, 13); + dhash ^= (u32)prim; + dcid_ = dhash; + + if (inds) { + GetIndexBounds(inds, vertexCount, vertType, &dc.indexLowerBound, &dc.indexUpperBound); + } else { + dc.indexLowerBound = 0; + dc.indexUpperBound = vertexCount - 1; + } + + numDrawCalls++; + vertexCountInDrawCalls += vertexCount; + + if (g_Config.bSoftwareSkinning && (vertType & GE_VTYPE_WEIGHT_MASK)) { + DecodeVertsStep(); + decodeCounter_++; + } + + if (prim == GE_PRIM_RECTANGLES && (gstate.getTextureAddress(0) & 0x3FFFFFFF) == (gstate.getFrameBufAddress() & 0x3FFFFFFF)) { + // Rendertarget == texture? + if (!g_Config.bDisableSlowFramebufEffects) { + gstate_c.textureChanged |= TEXCHANGE_PARAMSONLY; + Flush(cmd_); + } + } +} + +void DrawEngineVulkan::DecodeVerts() { + for (; decodeCounter_ < numDrawCalls; decodeCounter_++) { + DecodeVertsStep(); + } + // Sanity check + if (indexGen.Prim() < 0) { + ERROR_LOG_REPORT(G3D, "DecodeVerts: Failed to deduce prim: %i", indexGen.Prim()); + // Force to points (0) + indexGen.AddPrim(GE_PRIM_POINTS, 0); + } +} + +void DrawEngineVulkan::DecodeVertsStep() { + const int i = decodeCounter_; + + const DeferredDrawCall &dc = drawCalls[i]; + + indexGen.SetIndex(decodedVerts_); + int indexLowerBound = dc.indexLowerBound, indexUpperBound = dc.indexUpperBound; + + u32 indexType = dc.indexType; + void *inds = dc.inds; + if (indexType == GE_VTYPE_IDX_NONE >> GE_VTYPE_IDX_SHIFT) { + // Decode the verts and apply morphing. Simple. + dec_->DecodeVerts(decoded + decodedVerts_ * (int)dec_->GetDecVtxFmt().stride, + dc.verts, indexLowerBound, indexUpperBound); + decodedVerts_ += indexUpperBound - indexLowerBound + 1; + indexGen.AddPrim(dc.prim, dc.vertexCount); + } else { + // It's fairly common that games issue long sequences of PRIM calls, with differing + // inds pointer but the same base vertex pointer. We'd like to reuse vertices between + // these as much as possible, so we make sure here to combine as many as possible + // into one nice big drawcall, sharing data. + + // 1. Look ahead to find the max index, only looking as "matching" drawcalls. + // Expand the lower and upper bounds as we go. + int lastMatch = i; + const int total = numDrawCalls; + for (int j = i + 1; j < total; ++j) { + if (drawCalls[j].verts != dc.verts) + break; + + indexLowerBound = std::min(indexLowerBound, (int)drawCalls[j].indexLowerBound); + indexUpperBound = std::max(indexUpperBound, (int)drawCalls[j].indexUpperBound); + lastMatch = j; + } + + // 2. Loop through the drawcalls, translating indices as we go. + switch (indexType) { + case GE_VTYPE_IDX_8BIT >> GE_VTYPE_IDX_SHIFT: + for (int j = i; j <= lastMatch; j++) { + indexGen.TranslatePrim(drawCalls[j].prim, drawCalls[j].vertexCount, (const u8 *)drawCalls[j].inds, indexLowerBound); + } + break; + case GE_VTYPE_IDX_16BIT >> GE_VTYPE_IDX_SHIFT: + for (int j = i; j <= lastMatch; j++) { + indexGen.TranslatePrim(drawCalls[j].prim, drawCalls[j].vertexCount, (const u16 *)drawCalls[j].inds, indexLowerBound); + } + break; + } + + const int vertexCount = indexUpperBound - indexLowerBound + 1; + + // This check is a workaround for Pangya Fantasy Golf, which sends bogus index data when switching items in "My Room" sometimes. + if (decodedVerts_ + vertexCount > VERTEX_BUFFER_MAX) { + return; + } + + // 3. Decode that range of vertex data. + dec_->DecodeVerts(decoded + decodedVerts_ * (int)dec_->GetDecVtxFmt().stride, + dc.verts, indexLowerBound, indexUpperBound); + decodedVerts_ += vertexCount; + + // 4. Advance indexgen vertex counter. + indexGen.Advance(vertexCount); + decodeCounter_ = lastMatch; + } +} + +inline u32 ComputeMiniHashRange(const void *ptr, size_t sz) { + // Switch to u32 units. + const u32 *p = (const u32 *)ptr; + sz >>= 2; + + if (sz > 100) { + size_t step = sz / 4; + u32 hash = 0; + for (size_t i = 0; i < sz; i += step) { + hash += DoReliableHash32(p + i, 100, 0x3A44B9C4); + } + return hash; + } else { + return p[0] + p[sz - 1]; + } +} + +// The inline wrapper in the header checks for numDrawCalls == 0 +void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { + gpuStats.numFlushes++; + + // This is not done on every drawcall, we should collect vertex data + // until critical state changes. That's when we draw (flush). + + GEPrimitiveType prim = prevPrim_; + // ApplyDrawState(prim); + + VulkanVertexShader *vshader; + VulkanFragmentShader *fshader; + shaderManager_->GetShaders(prim, lastVType_, &vshader, &fshader); + + if (vshader->UseHWTransform()) { + int vertexCount = 0; + int maxIndex = 0; + bool useElements = true; + + DecodeVerts(); + gpuStats.numUncachedVertsDrawn += indexGen.VertexCount(); + useElements = !indexGen.SeenOnlyPurePrims(); + vertexCount = indexGen.VertexCount(); + maxIndex = indexGen.MaxIndex(); + if (!useElements && indexGen.PureCount()) { + vertexCount = indexGen.PureCount(); + } + prim = indexGen.Prim(); + + VERBOSE_LOG(G3D, "Flush prim %i! %i verts in one go", prim, vertexCount); + bool hasColor = (lastVType_ & GE_VTYPE_COL_MASK) != GE_VTYPE_COL_NONE; + if (gstate.isModeThrough()) { + gstate_c.vertexFullAlpha = gstate_c.vertexFullAlpha && (hasColor || gstate.getMaterialAmbientA() == 255); + } else { + gstate_c.vertexFullAlpha = gstate_c.vertexFullAlpha && ((hasColor && (gstate.materialupdate & 1)) || gstate.getMaterialAmbientA() == 255) && (!gstate.isLightingEnabled() || gstate.getAmbientA() == 255); + } + + VkBuffer buf[1] = {}; + VkDeviceSize offsets[1] = { 0 }; + if (useElements) { + // TODO: Avoid rebinding if the vertex size stays the same by using the offset arguments + vkCmdBindVertexBuffers(cmd_, 0, 1, buf, offsets); + vkCmdBindIndexBuffer(cmd_, buf[0], 0, VK_INDEX_TYPE_UINT16); + vkCmdDrawIndexed(cmd_, maxIndex + 1, 1, 0, 0, 0); + } else { + vkCmdBindVertexBuffers(cmd_, 0, 1, buf, offsets); + vkCmdDraw(cmd_, vertexCount, 1, 0, 0); + } + } else { + DecodeVerts(); + bool hasColor = (lastVType_ & GE_VTYPE_COL_MASK) != GE_VTYPE_COL_NONE; + if (gstate.isModeThrough()) { + gstate_c.vertexFullAlpha = gstate_c.vertexFullAlpha && (hasColor || gstate.getMaterialAmbientA() == 255); + } else { + gstate_c.vertexFullAlpha = gstate_c.vertexFullAlpha && ((hasColor && (gstate.materialupdate & 1)) || gstate.getMaterialAmbientA() == 255) && (!gstate.isLightingEnabled() || gstate.getAmbientA() == 255); + } + + gpuStats.numUncachedVertsDrawn += indexGen.VertexCount(); + prim = indexGen.Prim(); + // Undo the strip optimization, not supported by the SW code yet. + if (prim == GE_PRIM_TRIANGLE_STRIP) + prim = GE_PRIM_TRIANGLES; + VERBOSE_LOG(G3D, "Flush prim %i SW! %i verts in one go", prim, indexGen.VertexCount()); + + int numTrans = 0; + bool drawIndexed = false; + u16 *inds = decIndex; + TransformedVertex *drawBuffer = NULL; + SoftwareTransformResult result; + memset(&result, 0, sizeof(result)); + + int maxIndex = indexGen.MaxIndex(); + SoftwareTransform( + prim, decoded, indexGen.VertexCount(), + dec_->VertexType(), inds, GE_VTYPE_IDX_16BIT, dec_->GetDecVtxFmt(), + maxIndex, framebufferManager_, textureCache_, transformed, transformedExpanded, drawBuffer, numTrans, drawIndexed, &result, 1.0f); + + // ApplyDrawStateLate(); + + if (result.action == SW_DRAW_PRIMITIVES) { + if (result.setStencil) { + // dxstate.stencilFunc.set(D3DCMP_ALWAYS, result.stencilValue, 255); + } + + VkBuffer buf[1] = {}; + VkDeviceSize offsets[1] = { 0 }; + if (drawIndexed) { + // TODO: Have a buffer per frame, use a walking buffer pointer + // TODO: Avoid rebinding if the vertex size stays the same by using the offset arguments + vkCmdBindVertexBuffers(cmd_, 0, 1, buf, offsets); + vkCmdBindIndexBuffer(cmd_, buf[0], 0, VK_INDEX_TYPE_UINT16); + vkCmdDrawIndexed(cmd_, numTrans, 1, 0, 0, 0); + // pD3Ddevice->DrawIndexedPrimitiveUP(glprim[prim], 0, maxIndex, D3DPrimCount(glprim[prim], numTrans), inds, D3DFMT_INDEX16, drawBuffer, sizeof(TransformedVertex)); + } else { + // TODO: Avoid rebinding if the vertex size stays the same by using the offset arguments + vkCmdBindVertexBuffers(cmd_, 0, 1, buf, offsets); + vkCmdDraw(cmd_, numTrans, 1, 0, 0); + // pD3Ddevice->DrawPrimitiveUP(glprim[prim], D3DPrimCount(glprim[prim], numTrans), drawBuffer, sizeof(TransformedVertex)); + } + } else if (result.action == SW_CLEAR) { + // TODO: Support clearing only color and not alpha, or vice versa. This is not supported (probably for good reason) by vkCmdClearColorAttachment + // so we will have to simply draw a rectangle instead. Accordingly, + + int mask = gstate.isClearModeColorMask() ? 1 : 0; + if (gstate.isClearModeAlphaMask()) mask |= 2; + if (gstate.isClearModeDepthMask()) mask |= 4; + + VkClearValue value; + value.color.float32[0] = (result.color & 0xFF) * (1.0f / 255.0f); + value.color.float32[1] = ((result.color >> 8) & 0xFF) * (1.0f / 255.0f); + value.color.float32[2] = ((result.color >> 16) & 0xFF) * (1.0f / 255.0f); + value.color.float32[3] = ((result.color >> 24) & 0xFF) * (1.0f / 255.0f); + value.depthStencil.depth = result.depth; + value.depthStencil.stencil = (result.color >> 24) & 0xFF; + + VkClearRect rect; + rect.baseArrayLayer = 0; + rect.layerCount = 1; + rect.rect.offset.x = 0; + rect.rect.offset.y = 0; + rect.rect.extent.width = gstate_c.curRTRenderWidth; + rect.rect.extent.height = gstate_c.curRTRenderHeight; + + int count = 0; + VkClearAttachment attach[2]; + if (mask & 3) { + attach[count].aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + attach[count].clearValue = value; + attach[count].colorAttachment = 0; + count++; + } + if (mask & 4) { + attach[count].aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; + attach[count].clearValue = value; + attach[count].colorAttachment = 0; + } + vkCmdClearAttachments(cmd_, count, attach, 1, &rect); + + if (mask & 1) { + framebufferManager_->SetColorUpdated(gstate_c.skipDrawReason); + } + if (mask & 4) { + framebufferManager_->SetDepthUpdated(); + } + } + } + + gpuStats.numDrawCalls += numDrawCalls; + gpuStats.numVertsSubmitted += vertexCountInDrawCalls; + + indexGen.Reset(); + decodedVerts_ = 0; + numDrawCalls = 0; + vertexCountInDrawCalls = 0; + decodeCounter_ = 0; + dcid_ = 0; + prevPrim_ = GE_PRIM_INVALID; + gstate_c.vertexFullAlpha = true; + framebufferManager_->SetColorUpdated(gstate_c.skipDrawReason); + + // Now seems as good a time as any to reset the min/max coords, which we may examine later. + gstate_c.vertBounds.minU = 512; + gstate_c.vertBounds.minV = 512; + gstate_c.vertBounds.maxU = 0; + gstate_c.vertBounds.maxV = 0; + + host->GPUNotifyDraw(); +} + +void DrawEngineVulkan::Resized() { + decJitCache_->Clear(); + lastVType_ = -1; + dec_ = NULL; + for (auto iter = decoderMap_.begin(); iter != decoderMap_.end(); iter++) { + delete iter->second; + } + decoderMap_.clear(); +} + +bool DrawEngineVulkan::IsCodePtrVertexDecoder(const u8 *ptr) const { + return decJitCache_->IsInSpace(ptr); +} diff --git a/GPU/Vulkan/DrawEngineVulkan.h b/GPU/Vulkan/DrawEngineVulkan.h new file mode 100644 index 0000000000..a484700443 --- /dev/null +++ b/GPU/Vulkan/DrawEngineVulkan.h @@ -0,0 +1,194 @@ +// Copyright (c) 2015- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#pragma once + +#include "GPU/Common/DrawEngineCommon.h" +// Copyright (c) 2012- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#pragma once + +#include + +#include "GPU/Vulkan/VulkanUtil.h" + +#include "GPU/GPUState.h" +#include "GPU/Common/GPUDebugInterface.h" +#include "GPU/Common/IndexGenerator.h" +#include "GPU/Common/VertexDecoderCommon.h" +#include "GPU/Common/DrawEngineCommon.h" +#include "GPU/Common/GPUStateUtils.h" + +struct DecVtxFormat; +struct UVScale; + +class ShaderManagerVulkan; +class PipelineManagerVulkan; +class TextureCacheVulkan; +class FramebufferManagerVulkan; + +// Avoiding the full include of TextureDecoder.h. +#if (defined(_M_SSE) && defined(_M_X64)) || defined(ARM64) +typedef u64 ReliableHashType; +#else +typedef u32 ReliableHashType; +#endif + +// Handles transform, lighting and drawing. +class DrawEngineVulkan : public DrawEngineCommon { +public: + DrawEngineVulkan(); + virtual ~DrawEngineVulkan(); + + void SubmitPrim(void *verts, void *inds, GEPrimitiveType prim, int vertexCount, u32 vertType, int *bytesRead); + + void SetShaderManager(ShaderManagerVulkan *shaderManager) { + shaderManager_ = shaderManager; + } + void SetPipelineManager(PipelineManagerVulkan *pipelineManager) { + pipelineManager_ = pipelineManager; + } + void SetTextureCache(TextureCacheVulkan *textureCache) { + textureCache_ = textureCache; + } + void SetFramebufferManager(FramebufferManagerVulkan *fbManager) { + framebufferManager_ = fbManager; + } + + void Resized(); // TODO: Call + + void SetupVertexDecoder(u32 vertType); + void SetupVertexDecoderInternal(u32 vertType); + + // This requires a SetupVertexDecoder call first. + int EstimatePerVertexCost() { + // TODO: This is transform cost, also account for rasterization cost somehow... although it probably + // runs in parallel with transform. + + // Also, this is all pure guesswork. If we can find a way to do measurements, that would be great. + + // GTA wants a low value to run smooth, GoW wants a high value (otherwise it thinks things + // went too fast and starts doing all the work over again). + + int cost = 20; + if (gstate.isLightingEnabled()) { + cost += 10; + + for (int i = 0; i < 4; i++) { + if (gstate.isLightChanEnabled(i)) + cost += 10; + } + } + + if (gstate.getUVGenMode() != GE_TEXMAP_TEXTURE_COORDS) { + cost += 20; + } + if (dec_ && dec_->morphcount > 1) { + cost += 5 * dec_->morphcount; + } + + return cost; + } + + // So that this can be inlined + void Flush(VkCommandBuffer cmd) { + if (!numDrawCalls) + return; + DoFlush(cmd); + } + + void FinishDeferred() { + if (!numDrawCalls) + return; + DecodeVerts(); + } + + bool IsCodePtrVertexDecoder(const u8 *ptr) const; + + void DispatchFlush() override { Flush(cmd_); } + void DispatchSubmitPrim(void *verts, void *inds, GEPrimitiveType prim, int vertexCount, u32 vertType, int *bytesRead) override { + SubmitPrim(verts, inds, prim, vertexCount, vertType, bytesRead); + } + + void SetCmdBuffer(VkCommandBuffer cmd) { + cmd_ = cmd; + } + +private: + void DecodeVerts(); + void DecodeVertsStep(); + void DoFlush(VkCommandBuffer cmd); + + VertexDecoder *GetVertexDecoder(u32 vtype); + + // Defer all vertex decoding to a "Flush" (except when software skinning) + struct DeferredDrawCall { + void *verts; + void *inds; + u32 vertType; + u8 indexType; + s8 prim; + u32 vertexCount; + u16 indexLowerBound; + u16 indexUpperBound; + }; + + VkCommandBuffer cmd_; + + // Vertex collector state + IndexGenerator indexGen; + int decodedVerts_; + GEPrimitiveType prevPrim_; + + u32 lastVType_; + + TransformedVertex *transformed; + TransformedVertex *transformedExpanded; + + // Other + ShaderManagerVulkan *shaderManager_; + PipelineManagerVulkan *pipelineManager_; + TextureCacheVulkan *textureCache_; + FramebufferManagerVulkan *framebufferManager_; + + enum { MAX_DEFERRED_DRAW_CALLS = 128 }; + + DeferredDrawCall drawCalls[MAX_DEFERRED_DRAW_CALLS]; + int numDrawCalls; + int vertexCountInDrawCalls; + + int decodeCounter_; + u32 dcid_; + + bool fboTexNeedBind_; + bool fboTexBound_; +}; diff --git a/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp b/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp new file mode 100644 index 0000000000..832f36269c --- /dev/null +++ b/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp @@ -0,0 +1,543 @@ +// Copyright (c) 2012- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#if !defined(USING_GLES2) +// SDL 1.2 on Apple does not have support for OpenGL 3 and hence needs +// special treatment in the shader generator. +#if defined(__APPLE__) +#define FORCE_OPENGL_2_0 +#endif +#endif + +#include +#include + +#include "Common/StringUtils.h" +#include "base/logging.h" +#include "gfx_es2/gpu_features.h" +#include "Core/Reporting.h" +#include "Core/Config.h" +#include "GPU/Common/GPUStateUtils.h" +#include "GPU/Common/ShaderId.h" +#include "GPU/Vulkan/FragmentShaderGeneratorVulkan.h" +#include "GPU/Vulkan/FramebufferVulkan.h" +#include "GPU/Vulkan/PipelineManagerVulkan.h" + +#include "GPU/ge_constants.h" +#include "GPU/GPUState.h" + +#define WRITE p+=sprintf + +// #define DEBUG_SHADER + +// Missing: Z depth range +bool GenerateVulkanGLSLFragmentShader(const ShaderID &id, char *buffer) { + char *p = buffer; + + const char *lastFragData = nullptr; + + WRITE(p, "#version 140\n"); // GLSL ES + WRITE(p, "#extension GL_ARB_separate_shader_objects : enable\n"); + WRITE(p, "#extension GL_ARB_shading_language_420pack : enable\n"); + + // PowerVR needs highp to do the fog in MHU correctly. + // Others don't. + bool highpFog = (gl_extensions.bugs & BUG_PVR_SHADER_PRECISION_BAD) ? true : false; + bool highpTexcoord = highpFog; + + WRITE(p, "precision lowp float;\n"); + + bool lmode = id.Bit(FS_BIT_LMODE); + bool doTexture = id.Bit(FS_BIT_DO_TEXTURE); + bool enableFog = id.Bit(FS_BIT_ENABLE_FOG); + bool enableAlphaTest = id.Bit(FS_BIT_ALPHA_TEST); + + bool alphaTestAgainstZero = id.Bit(FS_BIT_ALPHA_AGAINST_ZERO); + bool enableColorTest = id.Bit(FS_BIT_COLOR_TEST); + bool colorTestAgainstZero = id.Bit(FS_BIT_COLOR_AGAINST_ZERO); + bool enableColorDoubling = id.Bit(FS_BIT_COLOR_DOUBLE); + bool doTextureProjection = id.Bit(FS_BIT_DO_TEXTURE_PROJ); + bool doTextureAlpha = id.Bit(FS_BIT_TEXALPHA); + bool doFlatShading = id.Bit(FS_BIT_FLATSHADE); + + GEComparison alphaTestFunc = (GEComparison)id.Bits(FS_BIT_ALPHA_TEST_FUNC, 3); + GEComparison colorTestFunc = (GEComparison)id.Bits(FS_BIT_COLOR_TEST_FUNC, 2); + bool needShaderTexClamp = id.Bit(FS_BIT_SHADER_TEX_CLAMP); + + GETexFunc texFunc = (GETexFunc)id.Bits(FS_BIT_TEXFUNC, 3); + bool textureAtOffset = id.Bit(FS_BIT_TEXTURE_AT_OFFSET); + + ReplaceBlendType replaceBlend = static_cast(id.Bits(FS_BIT_REPLACE_BLEND, 3)); + ReplaceAlphaType stencilToAlpha = static_cast(id.Bits(FS_BIT_STENCIL_TO_ALPHA, 2)); + + GEBlendSrcFactor replaceBlendFuncA = (GEBlendSrcFactor)id.Bits(FS_BIT_BLENDFUNC_A, 4); + GEBlendDstFactor replaceBlendFuncB = (GEBlendDstFactor)id.Bits(FS_BIT_BLENDFUNC_B, 4); + GEBlendMode replaceBlendEq = (GEBlendMode)id.Bits(FS_BIT_BLENDEQ, 3); + + bool isModeClear = id.Bit(FS_BIT_CLEARMODE); + + const char *shading = doFlatShading ? "flat" : ""; + + if (doTexture) { + WRITE(p, "layout (binding = 1) uniform sampler2D tex;\n"); + } + + if (!isModeClear && replaceBlend > REPLACE_BLEND_STANDARD) { + if (replaceBlend == REPLACE_BLEND_COPY_FBO) { + WRITE(p, "layout (binding = 2) uniform sampler2D fbotex;\n"); + } + if (replaceBlendFuncA == GE_SRCBLEND_FIXA) { + WRITE(p, "uniform vec3 u_blendFixA;\n"); + } + if (replaceBlendFuncB == GE_DSTBLEND_FIXB) { + WRITE(p, "uniform vec3 u_blendFixB;\n"); + } + } + + if (needShaderTexClamp && doTexture) { + WRITE(p, "uniform vec4 u_texclamp;\n"); + if (id.Bit(FS_BIT_TEXTURE_AT_OFFSET)) { + WRITE(p, "uniform vec2 u_texclampoff;\n"); + } + } + + if (enableAlphaTest || enableColorTest) { + WRITE(p, "uniform vec4 u_alphacolorref;\n"); + if (((enableColorTest && !colorTestAgainstZero) || (enableAlphaTest && !alphaTestAgainstZero))) { + WRITE(p, "uniform ivec4 u_alphacolormask;\n"); + } + } + + StencilValueType replaceAlphaWithStencilType = (StencilValueType)id.Bits(FS_BIT_REPLACE_ALPHA_WITH_STENCIL_TYPE, 4); + if (stencilToAlpha && replaceAlphaWithStencilType == STENCIL_VALUE_UNIFORM) { + WRITE(p, "uniform float u_stencilReplaceValue;\n"); + } + if (doTexture && texFunc == GE_TEXFUNC_BLEND) + WRITE(p, "uniform vec3 u_texenv;\n"); + + if (enableFog) { + WRITE(p, "uniform vec3 u_fogcolor;\n"); + } + + WRITE(p, "layout (location = 1) %s in vec4 v_color0;\n", shading); + if (lmode) + WRITE(p, "layout (location = 2) %s in vec3 v_color1;\n", shading); + if (enableFog) { + WRITE(p, "layout (location = 3) %s float v_fogdepth;\n", highpFog ? "highp" : "mediump"); + } + if (doTexture) { + if (doTextureProjection) + WRITE(p, "layout (location = 0) %s vec3 v_texcoord;\n", highpTexcoord ? "highp" : "mediump"); + else + WRITE(p, "layout (location = 0) %s vec2 v_texcoord;\n", highpTexcoord ? "highp" : "mediump"); + } + + if (!g_Config.bFragmentTestCache) { + if (enableAlphaTest && !alphaTestAgainstZero) { + WRITE(p, "int roundAndScaleTo255i(in float x) { return int(floor(x * 255.0 + 0.5)); }\n"); + } + if (enableColorTest && !colorTestAgainstZero) { + WRITE(p, "ivec3 roundAndScaleTo255iv(in vec3 x) { return ivec3(floor(x * 255.0 + 0.5)); }\n"); + } + } + + WRITE(p, "layout (location = 0) out vec4 fragColor0;\n"); + if (stencilToAlpha == REPLACE_ALPHA_DUALSOURCE) { + WRITE(p, "layout (location = 1) out vec4 fragColor1;\n"); + } + + // PowerVR needs a custom modulo function. For some reason, this has far higher precision than the builtin one. + if ((gl_extensions.bugs & BUG_PVR_SHADER_PRECISION_BAD) && needShaderTexClamp) { + WRITE(p, "float mymod(float a, float b) { return a - b * floor(a / b); }\n"); + } + + WRITE(p, "void main() {\n"); + + if (isModeClear) { + // Clear mode does not allow any fancy shading. + WRITE(p, " vec4 v = v_color0;\n"); + } else { + const char *secondary = ""; + // Secondary color for specular on top of texture + if (lmode) { + WRITE(p, " vec4 s = vec4(v_color1, 0.0);\n"); + secondary = " + s"; + } else { + secondary = ""; + } + + if (doTexture) { + const char *texcoord = "v_texcoord"; + // TODO: Not sure the right way to do this for projection. + // This path destroys resolution on older PowerVR no matter what I do, so we disable it on SGX 540 and lesser, and live with the consequences. + if (needShaderTexClamp && !(gl_extensions.bugs & BUG_PVR_SHADER_PRECISION_TERRIBLE)) { + // We may be clamping inside a larger surface (tex = 64x64, buffer=480x272). + // We may also be wrapping in such a surface, or either one in a too-small surface. + // Obviously, clamping to a smaller surface won't work. But better to clamp to something. + std::string ucoord = "v_texcoord.x"; + std::string vcoord = "v_texcoord.y"; + if (doTextureProjection) { + ucoord = "(v_texcoord.x / v_texcoord.z)"; + vcoord = "(v_texcoord.y / v_texcoord.z)"; + } + + std::string modulo = (gl_extensions.bugs & BUG_PVR_SHADER_PRECISION_BAD) ? "mymod" : "mod"; + + if (id.Bit(FS_BIT_CLAMP_S)) { + ucoord = "clamp(" + ucoord + ", u_texclamp.z, u_texclamp.x - u_texclamp.z)"; + } else { + ucoord = modulo + "(" + ucoord + ", u_texclamp.x)"; + } + if (id.Bit(FS_BIT_CLAMP_T)) { + vcoord = "clamp(" + vcoord + ", u_texclamp.w, u_texclamp.y - u_texclamp.w)"; + } else { + vcoord = modulo + "(" + vcoord + ", u_texclamp.y)"; + } + if (textureAtOffset) { + ucoord = "(" + ucoord + " + u_texclampoff.x)"; + vcoord = "(" + vcoord + " + u_texclampoff.y)"; + } + + WRITE(p, " vec2 fixedcoord = vec2(%s, %s);\n", ucoord.c_str(), vcoord.c_str()); + texcoord = "fixedcoord"; + // We already projected it. + doTextureProjection = false; + } + + if (doTextureProjection) { + WRITE(p, " vec4 t = textureProj(tex, %s);\n", texcoord); + } else { + WRITE(p, " vec4 t = texture(tex, %s);\n", texcoord); + } + WRITE(p, " vec4 p = v_color0;\n"); + + if (doTextureAlpha) { // texfmt == RGBA + switch (texFunc) { + case GE_TEXFUNC_MODULATE: + WRITE(p, " vec4 v = p * t%s;\n", secondary); + break; + + case GE_TEXFUNC_DECAL: + WRITE(p, " vec4 v = vec4(mix(p.rgb, t.rgb, t.a), p.a)%s;\n", secondary); + break; + + case GE_TEXFUNC_BLEND: + WRITE(p, " vec4 v = vec4(mix(p.rgb, u_texenv.rgb, t.rgb), p.a * t.a)%s;\n", secondary); + break; + + case GE_TEXFUNC_REPLACE: + WRITE(p, " vec4 v = t%s;\n", secondary); + break; + + case GE_TEXFUNC_ADD: + case GE_TEXFUNC_UNKNOWN1: + case GE_TEXFUNC_UNKNOWN2: + case GE_TEXFUNC_UNKNOWN3: + WRITE(p, " vec4 v = vec4(p.rgb + t.rgb, p.a * t.a)%s;\n", secondary); + break; + default: + WRITE(p, " vec4 v = p;\n"); break; + } + } else { // texfmt == RGB + switch (texFunc) { + case GE_TEXFUNC_MODULATE: + WRITE(p, " vec4 v = vec4(t.rgb * p.rgb, p.a)%s;\n", secondary); + break; + + case GE_TEXFUNC_DECAL: + WRITE(p, " vec4 v = vec4(t.rgb, p.a)%s;\n", secondary); + break; + + case GE_TEXFUNC_BLEND: + WRITE(p, " vec4 v = vec4(mix(p.rgb, u_texenv.rgb, t.rgb), p.a)%s;\n", secondary); + break; + + case GE_TEXFUNC_REPLACE: + WRITE(p, " vec4 v = vec4(t.rgb, p.a)%s;\n", secondary); + break; + + case GE_TEXFUNC_ADD: + case GE_TEXFUNC_UNKNOWN1: + case GE_TEXFUNC_UNKNOWN2: + case GE_TEXFUNC_UNKNOWN3: + WRITE(p, " vec4 v = vec4(p.rgb + t.rgb, p.a)%s;\n", secondary); break; + default: + WRITE(p, " vec4 v = p;\n"); break; + } + } + } else { + // No texture mapping + WRITE(p, " vec4 v = v_color0 %s;\n", secondary); + } + + // Texture access is at half texels [0.5/256, 255.5/256], but colors are normalized [0, 255]. + // So we have to scale to account for the difference. + std::string alphaTestXCoord = "0"; + if (g_Config.bFragmentTestCache) { + if (enableColorTest && !colorTestAgainstZero) { + WRITE(p, " vec4 vScale256 = v * %f + %f;\n", 255.0 / 256.0, 0.5 / 256.0); + alphaTestXCoord = "vScale256.a"; + } else if (enableAlphaTest && !alphaTestAgainstZero) { + char temp[64]; + snprintf(temp, sizeof(temp), "v.a * %f + %f", 255.0 / 256.0, 0.5 / 256.0); + alphaTestXCoord = temp; + } + } + + if (enableAlphaTest) { + if (alphaTestAgainstZero) { + // When testing against 0 (extremely common), we can avoid some math. + // 0.002 is approximately half of 1.0 / 255.0. + if (alphaTestFunc == GE_COMP_NOTEQUAL || alphaTestFunc == GE_COMP_GREATER) { + WRITE(p, " if (v.a < 0.002) discard;\n"); + } else if (alphaTestFunc != GE_COMP_NEVER) { + // Anything else is a test for == 0. Happens sometimes, actually... + WRITE(p, " if (v.a > 0.002) discard;\n"); + } else { + // NEVER has been logged as used by games, although it makes little sense - statically failing. + // Maybe we could discard the drawcall, but it's pretty rare. Let's just statically discard here. + WRITE(p, " discard;\n"); + } + } else if (g_Config.bFragmentTestCache) { + WRITE(p, " float aResult = texture(testtex, vec2(%s, 0)).a;\n", alphaTestXCoord.c_str()); + WRITE(p, " if (aResult < 0.5) discard;\n"); + } else { + const char *alphaTestFuncs[] = { "#", "#", " != ", " == ", " >= ", " > ", " <= ", " < " }; + if (alphaTestFuncs[alphaTestFunc][0] != '#') { + WRITE(p, " if ((roundAndScaleTo255i(v.a) & u_alphacolormask.a) %s int(u_alphacolorref.a)) discard;\n", alphaTestFuncs[alphaTestFunc]); + } else { + // This means NEVER. See above. + WRITE(p, " discard;\n"); + } + } + } + + if (enableColorTest) { + if (colorTestAgainstZero) { + // When testing against 0 (common), we can avoid some math. + // 0.002 is approximately half of 1.0 / 255.0. + if (colorTestFunc == GE_COMP_NOTEQUAL) { + WRITE(p, " if (v.r < 0.002 && v.g < 0.002 && v.b < 0.002) discard;\n"); + } else if (colorTestFunc != GE_COMP_NEVER) { + // Anything else is a test for == 0. + WRITE(p, " if (v.r > 0.002 || v.g > 0.002 || v.b > 0.002) discard;\n"); + } else { + // NEVER has been logged as used by games, although it makes little sense - statically failing. + // Maybe we could discard the drawcall, but it's pretty rare. Let's just statically discard here. + WRITE(p, " discard;\n"); + } + } else if (g_Config.bFragmentTestCache) { + // texelFetch may make more sense, actually, and we should process colors as integers. + WRITE(p, " float rResult = texture(testtex, vec2(vScale256.r, 0)).r;\n"); + WRITE(p, " float gResult = texture(testtex, vec2(vScale256.g, 0)).g;\n"); + WRITE(p, " float bResult = texture(testtex, vec2(vScale256.b, 0)).b;\n"); + if (colorTestFunc == GE_COMP_EQUAL) { + // Equal means all parts must be equal. + WRITE(p, " if (rResult < 0.5 || gResult < 0.5 || bResult < 0.5) discard;\n"); + } else { + // Not equal means any part must be not equal. + WRITE(p, " if (rResult < 0.5 && gResult < 0.5 && bResult < 0.5) discard;\n"); + } + } else { + const char *colorTestFuncs[] = { "#", "#", " != ", " == " }; + if (colorTestFuncs[colorTestFunc][0] != '#') { + // Apparently GLES3 does not support vector bitwise ops. + WRITE(p, " ivec3 v_scaled = roundAndScaleTo255iv(v.rgb);\n"); + const char *maskedFragColor = "ivec3(v_scaled.r & u_alphacolormask.r, v_scaled.g & u_alphacolormask.g, v_scaled.b & u_alphacolormask.b)"; + const char *maskedColorRef = "ivec3(int(u_alphacolorref.r) & u_alphacolormask.r, int(u_alphacolorref.g) & u_alphacolormask.g, int(u_alphacolorref.b) & u_alphacolormask.b)"; + WRITE(p, " if (%s %s %s) discard;\n", maskedFragColor, colorTestFuncs[colorTestFunc], maskedColorRef); + } else { + WRITE(p, " discard;\n"); + } + } + } + + // Color doubling happens after the color test. + if (enableColorDoubling && replaceBlend == REPLACE_BLEND_2X_SRC) { + WRITE(p, " v.rgb = v.rgb * 4.0;\n"); + } else if (enableColorDoubling || replaceBlend == REPLACE_BLEND_2X_SRC) { + WRITE(p, " v.rgb = v.rgb * 2.0;\n"); + } + + if (enableFog) { + WRITE(p, " float fogCoef = clamp(v_fogdepth, 0.0, 1.0);\n"); + WRITE(p, " v = mix(vec4(u_fogcolor, v.a), v, fogCoef);\n"); + // WRITE(p, " v.x = v_depth;\n"); + } + + if (replaceBlend == REPLACE_BLEND_PRE_SRC || replaceBlend == REPLACE_BLEND_PRE_SRC_2X_ALPHA) { + const char *srcFactor = "ERROR"; + switch (replaceBlendFuncA) { + case GE_SRCBLEND_DSTCOLOR: srcFactor = "ERROR"; break; + case GE_SRCBLEND_INVDSTCOLOR: srcFactor = "ERROR"; break; + case GE_SRCBLEND_SRCALPHA: srcFactor = "vec3(v.a)"; break; + case GE_SRCBLEND_INVSRCALPHA: srcFactor = "vec3(1.0 - v.a)"; break; + case GE_SRCBLEND_DSTALPHA: srcFactor = "ERROR"; break; + case GE_SRCBLEND_INVDSTALPHA: srcFactor = "ERROR"; break; + case GE_SRCBLEND_DOUBLESRCALPHA: srcFactor = "vec3(v.a * 2.0)"; break; + case GE_SRCBLEND_DOUBLEINVSRCALPHA: srcFactor = "vec3(1.0 - v.a * 2.0)"; break; + case GE_SRCBLEND_DOUBLEDSTALPHA: srcFactor = "ERROR"; break; + case GE_SRCBLEND_DOUBLEINVDSTALPHA: srcFactor = "ERROR"; break; + case GE_SRCBLEND_FIXA: srcFactor = "u_blendFixA"; break; + } + + WRITE(p, " v.rgb = v.rgb * %s;\n", srcFactor); + } + + if (replaceBlend == REPLACE_BLEND_COPY_FBO) { + WRITE(p, " lowp vec4 destColor = texelFetch(fbotex, ivec2(gl_FragCoord.x, gl_FragCoord.y), 0);\n"); + + const char *srcFactor = "vec3(1.0)"; + const char *dstFactor = "vec3(0.0)"; + + switch (replaceBlendFuncA) { + case GE_SRCBLEND_DSTCOLOR: srcFactor = "destColor.rgb"; break; + case GE_SRCBLEND_INVDSTCOLOR: srcFactor = "(vec3(1.0) - destColor.rgb)"; break; + case GE_SRCBLEND_SRCALPHA: srcFactor = "vec3(v.a)"; break; + case GE_SRCBLEND_INVSRCALPHA: srcFactor = "vec3(1.0 - v.a)"; break; + case GE_SRCBLEND_DSTALPHA: srcFactor = "vec3(destColor.a)"; break; + case GE_SRCBLEND_INVDSTALPHA: srcFactor = "vec3(1.0 - destColor.a)"; break; + case GE_SRCBLEND_DOUBLESRCALPHA: srcFactor = "vec3(v.a * 2.0)"; break; + case GE_SRCBLEND_DOUBLEINVSRCALPHA: srcFactor = "vec3(1.0 - v.a * 2.0)"; break; + case GE_SRCBLEND_DOUBLEDSTALPHA: srcFactor = "vec3(destColor.a * 2.0)"; break; + case GE_SRCBLEND_DOUBLEINVDSTALPHA: srcFactor = "vec3(1.0 - destColor.a * 2.0)"; break; + case GE_SRCBLEND_FIXA: srcFactor = "u_blendFixA"; break; + } + switch (replaceBlendFuncB) { + case GE_DSTBLEND_SRCCOLOR: dstFactor = "v.rgb"; break; + case GE_DSTBLEND_INVSRCCOLOR: dstFactor = "(vec3(1.0) - v.rgb)"; break; + case GE_DSTBLEND_SRCALPHA: dstFactor = "vec3(v.a)"; break; + case GE_DSTBLEND_INVSRCALPHA: dstFactor = "vec3(1.0 - v.a)"; break; + case GE_DSTBLEND_DSTALPHA: dstFactor = "vec3(destColor.a)"; break; + case GE_DSTBLEND_INVDSTALPHA: dstFactor = "vec3(1.0 - destColor.a)"; break; + case GE_DSTBLEND_DOUBLESRCALPHA: dstFactor = "vec3(v.a * 2.0)"; break; + case GE_DSTBLEND_DOUBLEINVSRCALPHA: dstFactor = "vec3(1.0 - v.a * 2.0)"; break; + case GE_DSTBLEND_DOUBLEDSTALPHA: dstFactor = "vec3(destColor.a * 2.0)"; break; + case GE_DSTBLEND_DOUBLEINVDSTALPHA: dstFactor = "vec3(1.0 - destColor.a * 2.0)"; break; + case GE_DSTBLEND_FIXB: dstFactor = "u_blendFixB"; break; + } + + switch (replaceBlendEq) { + case GE_BLENDMODE_MUL_AND_ADD: + WRITE(p, " v.rgb = v.rgb * %s + destColor.rgb * %s;\n", srcFactor, dstFactor); + break; + case GE_BLENDMODE_MUL_AND_SUBTRACT: + WRITE(p, " v.rgb = v.rgb * %s - destColor.rgb * %s;\n", srcFactor, dstFactor); + break; + case GE_BLENDMODE_MUL_AND_SUBTRACT_REVERSE: + WRITE(p, " v.rgb = destColor.rgb * %s - v.rgb * %s;\n", dstFactor, srcFactor); + break; + case GE_BLENDMODE_MIN: + WRITE(p, " v.rgb = min(v.rgb, destColor.rgb);\n"); + break; + case GE_BLENDMODE_MAX: + WRITE(p, " v.rgb = max(v.rgb, destColor.rgb);\n"); + break; + case GE_BLENDMODE_ABSDIFF: + WRITE(p, " v.rgb = abs(v.rgb - destColor.rgb);\n"); + break; + } + } + + if (replaceBlend == REPLACE_BLEND_2X_ALPHA || replaceBlend == REPLACE_BLEND_PRE_SRC_2X_ALPHA) { + WRITE(p, " v.a = v.a * 2.0;\n"); + } + } + + std::string replacedAlpha = "0.0"; + char replacedAlphaTemp[64] = ""; + if (stencilToAlpha != REPLACE_ALPHA_NO) { + switch (replaceAlphaWithStencilType) { + case STENCIL_VALUE_UNIFORM: + replacedAlpha = "u_stencilReplaceValue"; + break; + + case STENCIL_VALUE_ZERO: + replacedAlpha = "0.0"; + break; + + case STENCIL_VALUE_ONE: + case STENCIL_VALUE_INVERT: + // In invert, we subtract by one, but we want to output one here. + replacedAlpha = "1.0"; + break; + + case STENCIL_VALUE_INCR_4: + case STENCIL_VALUE_DECR_4: + // We're adding/subtracting, just by the smallest value in 4-bit. + snprintf(replacedAlphaTemp, sizeof(replacedAlphaTemp), "%f", 1.0 / 15.0); + replacedAlpha = replacedAlphaTemp; + break; + + case STENCIL_VALUE_INCR_8: + case STENCIL_VALUE_DECR_8: + // We're adding/subtracting, just by the smallest value in 8-bit. + snprintf(replacedAlphaTemp, sizeof(replacedAlphaTemp), "%f", 1.0 / 255.0); + replacedAlpha = replacedAlphaTemp; + break; + + case STENCIL_VALUE_KEEP: + // Do nothing. We'll mask out the alpha using color mask. + break; + } + } + + switch (stencilToAlpha) { + case REPLACE_ALPHA_DUALSOURCE: + WRITE(p, " fragColor0 = vec4(v.rgb, %s);\n", replacedAlpha.c_str()); + WRITE(p, " fragColor1 = vec4(0.0, 0.0, 0.0, v.a);\n"); + break; + + case REPLACE_ALPHA_YES: + WRITE(p, " fragColor0 = vec4(v.rgb, %s);\n", replacedAlpha.c_str()); + break; + + case REPLACE_ALPHA_NO: + WRITE(p, " fragColor0 = v;\n"); + break; + + default: + ERROR_LOG(G3D, "Bad stencil-to-alpha type, corrupt ID?"); + return false; + } + + LogicOpReplaceType replaceLogicOpType = (LogicOpReplaceType)id.Bits(FS_BIT_REPLACE_LOGIC_OP_TYPE, 2); + switch (replaceLogicOpType) { + case LOGICOPTYPE_ONE: + WRITE(p, " fragColor0.rgb = vec3(1.0, 1.0, 1.0);\n"); + break; + case LOGICOPTYPE_INVERT: + WRITE(p, " fragColor0.rgb = vec3(1.0, 1.0, 1.0) - fragColor0.rgb;\n"); + break; + case LOGICOPTYPE_NORMAL: + break; + + default: + ERROR_LOG(G3D, "Bad logic op type, corrupt ID?"); + return false; + } + + if (gstate_c.Supports(GPU_ROUND_FRAGMENT_DEPTH_TO_16BIT)) { + WRITE(p, " highp float z = gl_FragCoord.z;\n"); + WRITE(p, " z = (1.0/65535.0) * floor(z * 65535.0);\n"); + WRITE(p, " gl_FragDepth = z;\n"); + } + + WRITE(p, "}\n"); + + return true; +} \ No newline at end of file diff --git a/GPU/Vulkan/FragmentShaderGeneratorVulkan.h b/GPU/Vulkan/FragmentShaderGeneratorVulkan.h new file mode 100644 index 0000000000..666daea965 --- /dev/null +++ b/GPU/Vulkan/FragmentShaderGeneratorVulkan.h @@ -0,0 +1,25 @@ +#pragma once +// Copyright (c) 2012- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#pragma once + +#include "Globals.h" + +struct ShaderID; + +bool GenerateVulkanGLSLFragmentShader(const ShaderID &id, char *buffer); diff --git a/GPU/Vulkan/FramebufferVulkan.cpp b/GPU/Vulkan/FramebufferVulkan.cpp new file mode 100644 index 0000000000..e69de29bb2 diff --git a/GPU/Vulkan/FramebufferVulkan.h b/GPU/Vulkan/FramebufferVulkan.h new file mode 100644 index 0000000000..dc1892bcba --- /dev/null +++ b/GPU/Vulkan/FramebufferVulkan.h @@ -0,0 +1,107 @@ +// Copyright (c) 2015- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#pragma once + +#include "GPU/Common/FramebufferCommon.h" +#include "GPU/Vulkan/VulkanUtil.h" + +class FramebufferManagerVulkan : public FramebufferManagerCommon { +public: + // Subsequent commands will be enqueued on this buffer. + void SetInstance(VkInstance inst) { inst_ = inst; } + void SetCmdBuffer(VkCommandBuffer cmd) { cmd_ = cmd; } + + virtual void ClearBuffer(bool keepState = false) override { + throw std::logic_error("The method or operation is not implemented."); + } + + virtual void RebindFramebuffer() override { + throw std::logic_error("The method or operation is not implemented."); + } + + virtual bool NotifyStencilUpload(u32 addr, int size, bool skipZero = false) override { + throw std::logic_error("The method or operation is not implemented."); + } + + virtual void ReadFramebufferToMemory(VirtualFramebuffer *vfb, bool sync, int x, int y, int w, int h) override { + throw std::logic_error("The method or operation is not implemented."); + } + + virtual void MakePixelTexture(const u8 *srcPixels, GEBufferFormat srcPixelFormat, int srcStride, int width, int height) override { + throw std::logic_error("The method or operation is not implemented."); + } + + virtual void DrawPixels(VirtualFramebuffer *vfb, int dstX, int dstY, const u8 *srcPixels, GEBufferFormat srcPixelFormat, int srcStride, int width, int height) override { + throw std::logic_error("The method or operation is not implemented."); + } + + virtual void DrawFramebufferToOutput(const u8 *srcPixels, GEBufferFormat srcPixelFormat, int srcStride, bool applyPostShader) override { + throw std::logic_error("The method or operation is not implemented."); + } + + virtual void DisableState() override { + throw std::logic_error("The method or operation is not implemented."); + } + + virtual void FlushBeforeCopy() override { + throw std::logic_error("The method or operation is not implemented."); + } + + virtual void DecimateFBOs() override { + throw std::logic_error("The method or operation is not implemented."); + } + + virtual void BlitFramebuffer(VirtualFramebuffer *dst, int dstX, int dstY, VirtualFramebuffer *src, int srcX, int srcY, int w, int h, int bpp) override { + throw std::logic_error("The method or operation is not implemented."); + } + + virtual void DestroyFramebuf(VirtualFramebuffer *vfb) override { + throw std::logic_error("The method or operation is not implemented."); + } + + virtual void ResizeFramebufFBO(VirtualFramebuffer *vfb, u16 w, u16 h, bool force = false) override { + throw std::logic_error("The method or operation is not implemented."); + } + + virtual void NotifyRenderFramebufferCreated(VirtualFramebuffer *vfb) override { + throw std::logic_error("The method or operation is not implemented."); + } + + virtual void NotifyRenderFramebufferSwitched(VirtualFramebuffer *prevVfb, VirtualFramebuffer *vfb, bool isClearingDepth) override { + throw std::logic_error("The method or operation is not implemented."); + } + + virtual void NotifyRenderFramebufferUpdated(VirtualFramebuffer *vfb, bool vfbFormatChanged) override { + throw std::logic_error("The method or operation is not implemented."); + } + + void DownloadFramebufferForClut(u32 fb_address, u32 loadBytes) override { + + } + + bool CreateDownloadTempBuffer(VirtualFramebuffer *nvfb) override { + return false; + } + void UpdateDownloadTempBuffer(VirtualFramebuffer *nvfb) override { + + } + +private: + VkInstance inst_; + VkCommandBuffer cmd_; +}; diff --git a/GPU/Vulkan/GPU_Vulkan.cpp b/GPU/Vulkan/GPU_Vulkan.cpp new file mode 100644 index 0000000000..f58f41230e --- /dev/null +++ b/GPU/Vulkan/GPU_Vulkan.cpp @@ -0,0 +1,116 @@ +// Copyright (c) 2015- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#include "GPU/Vulkan/GPU_Vulkan.h" + +GPU_Vulkan::GPU_Vulkan() { + +} + +GPU_Vulkan::~GPU_Vulkan() { + +} + +void GPU_Vulkan::CheckGPUFeatures() { + +} + +void GPU_Vulkan::ReapplyGfxStateInternal() {} +void GPU_Vulkan::SetDisplayFramebuffer(u32 framebuf, u32 stride, GEBufferFormat format) {} +void GPU_Vulkan::CopyDisplayToOutput() {} +void GPU_Vulkan::BeginFrame() {} +void GPU_Vulkan::UpdateStats() {} +void GPU_Vulkan::InvalidateCache(u32 addr, int size, GPUInvalidationType type) {} +bool GPU_Vulkan::PerformMemoryCopy(u32 dest, u32 src, int size) { return false; } +bool GPU_Vulkan::PerformMemorySet(u32 dest, u8 v, int size) { return false; } +bool GPU_Vulkan::PerformMemoryDownload(u32 dest, int size) { return false; } +bool GPU_Vulkan::PerformMemoryUpload(u32 dest, int size) { return false; } +bool GPU_Vulkan::PerformStencilUpload(u32 dest, int size) { return false; } +void GPU_Vulkan::ClearCacheNextFrame() {} +void GPU_Vulkan::DeviceLost() {} // Only happens on Android. Drop all textures and shaders. + +void GPU_Vulkan::DumpNextFrame() {} + +void GPU_Vulkan::DoState(PointerWrap &p) { + GPUCommon::DoState(p); +} + + +void GPU_Vulkan::DoBlockTransfer(u32 skipDrawReason) { + +} + +void GPU_Vulkan::Resized() {} + +void GPU_Vulkan::ClearShaderCache() {} +bool GPU_Vulkan::FramebufferDirty() { return false; } +bool GPU_Vulkan::FramebufferReallyDirty() { return false; } + +void GPU_Vulkan::FastRunLoop(DisplayList &list) { + +} + +void GPU_Vulkan::ProcessEvent(GPUEvent ev) { + +} + +void GPU_Vulkan::FastLoadBoneMatrix(u32 target) { + +} + +void GPU_Vulkan::FinishDeferred() { + +} + +void GPU_Vulkan::UpdateCmdInfo() { + +} + +void GPU_Vulkan::InitClear() { + +} + +void GPU_Vulkan::Reinitialize() { + +} + +void GPU_Vulkan::PreExecuteOp(u32 op, u32 diff) { + +} + +void GPU_Vulkan::Execute_Generic(u32 op, u32 diff) { + +} + +void GPU_Vulkan::ExecuteOp(u32 op, u32 diff) { + +} + + + +std::vector GPU_Vulkan::DebugGetShaderIDs(DebugShaderType shader) { + std::vector ids; + return ids; +} + +std::string GPU_Vulkan::DebugGetShaderString(std::string id, DebugShaderType shader, DebugShaderStringType stringType) { + return "N/A"; +} + +void GPU_Vulkan::NotifyVideoUpload(u32 addr, int size, int width, int format) { + +} diff --git a/GPU/Vulkan/GPU_Vulkan.h b/GPU/Vulkan/GPU_Vulkan.h new file mode 100644 index 0000000000..69efc4c78f --- /dev/null +++ b/GPU/Vulkan/GPU_Vulkan.h @@ -0,0 +1,172 @@ +// Copyright (c) 2015- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#pragma once + +#include +#include + +#include "GPU/GPUCommon.h" +#include "GPU/Vulkan/FramebufferVulkan.h" +#include "GPU/Vulkan/DrawEngineVulkan.h" +#include "GPU/Vulkan/PipelineManagerVulkan.h" +#include "GPU/Vulkan/TextureCacheVulkan.h" + +class ShaderManager; +class LinkedShader; + +class GPU_Vulkan : public GPUCommon { +public: + GPU_Vulkan(); + ~GPU_Vulkan(); + + // This gets called on startup and when we get back from settings. + void CheckGPUFeatures(); + + void InitClear() override; + void Reinitialize() override; + void PreExecuteOp(u32 op, u32 diff) override; + void Execute_Generic(u32 op, u32 diff); + void ExecuteOp(u32 op, u32 diff) override; + + void ReapplyGfxStateInternal() override; + void SetDisplayFramebuffer(u32 framebuf, u32 stride, GEBufferFormat format) override; + void CopyDisplayToOutput() override; + void BeginFrame() override; + void UpdateStats() override; + void InvalidateCache(u32 addr, int size, GPUInvalidationType type) override; + void NotifyVideoUpload(u32 addr, int size, int width, int format) override; + bool PerformMemoryCopy(u32 dest, u32 src, int size) override; + bool PerformMemorySet(u32 dest, u8 v, int size) override; + bool PerformMemoryDownload(u32 dest, int size) override; + bool PerformMemoryUpload(u32 dest, int size) override; + bool PerformStencilUpload(u32 dest, int size) override; + void ClearCacheNextFrame() override; + void DeviceLost() override; // Only happens on Android. Drop all textures and shaders. + + void DumpNextFrame() override; + void DoState(PointerWrap &p) override; + + // Called by the window system if the window size changed. This will be reflected in PSPCoreParam.pixel*. + void Resized() override; + void ClearShaderCache() override; + bool DecodeTexture(u8 *dest, const GPUgstate &state) override { + return textureCache_.DecodeTexture(dest, state); + } + bool FramebufferDirty() override; + bool FramebufferReallyDirty() override; + + void GetReportingInfo(std::string &primaryInfo, std::string &fullInfo) override { + primaryInfo = reportingPrimaryInfo_; + fullInfo = reportingFullInfo_; + } + + typedef void (GPU_Vulkan::*CmdFunc)(u32 op, u32 diff); + struct CommandInfo { + u8 flags; + GPU_Vulkan::CmdFunc func; + }; + + /* + void Execute_Vaddr(u32 op, u32 diff); + void Execute_Iaddr(u32 op, u32 diff); + void Execute_Prim(u32 op, u32 diff); + void Execute_Bezier(u32 op, u32 diff); + void Execute_Spline(u32 op, u32 diff); + void Execute_BoundingBox(u32 op, u32 diff); + void Execute_VertexType(u32 op, u32 diff); + void Execute_VertexTypeSkinning(u32 op, u32 diff); + void Execute_Region(u32 op, u32 diff); + void Execute_Scissor(u32 op, u32 diff); + void Execute_FramebufType(u32 op, u32 diff); + void Execute_ViewportType(u32 op, u32 diff); + void Execute_ViewportZType(u32 op, u32 diff); + void Execute_TexScaleU(u32 op, u32 diff); + void Execute_TexScaleV(u32 op, u32 diff); + void Execute_TexOffsetU(u32 op, u32 diff); + void Execute_TexOffsetV(u32 op, u32 diff); + void Execute_TexAddr0(u32 op, u32 diff); + void Execute_TexAddrN(u32 op, u32 diff); + void Execute_TexBufw0(u32 op, u32 diff); + void Execute_TexBufwN(u32 op, u32 diff); + void Execute_TexSize0(u32 op, u32 diff); + void Execute_TexSizeN(u32 op, u32 diff); + void Execute_TexFormat(u32 op, u32 diff); + void Execute_TexMapMode(u32 op, u32 diff); + void Execute_TexParamType(u32 op, u32 diff); + void Execute_TexEnvColor(u32 op, u32 diff); + void Execute_TexLevel(u32 op, u32 diff); + void Execute_LoadClut(u32 op, u32 diff); + void Execute_ClutFormat(u32 op, u32 diff); + void Execute_Ambient(u32 op, u32 diff); + void Execute_MaterialDiffuse(u32 op, u32 diff); + void Execute_MaterialEmissive(u32 op, u32 diff); + void Execute_MaterialAmbient(u32 op, u32 diff); + void Execute_MaterialSpecular(u32 op, u32 diff); + void Execute_Light0Param(u32 op, u32 diff); + void Execute_Light1Param(u32 op, u32 diff); + void Execute_Light2Param(u32 op, u32 diff); + void Execute_Light3Param(u32 op, u32 diff); + void Execute_FogColor(u32 op, u32 diff); + void Execute_FogCoef(u32 op, u32 diff); + void Execute_ColorTestMask(u32 op, u32 diff); + void Execute_AlphaTest(u32 op, u32 diff); + void Execute_StencilTest(u32 op, u32 diff); + void Execute_ColorRef(u32 op, u32 diff); + void Execute_WorldMtxNum(u32 op, u32 diff); + void Execute_WorldMtxData(u32 op, u32 diff); + void Execute_ViewMtxNum(u32 op, u32 diff); + void Execute_ViewMtxData(u32 op, u32 diff); + void Execute_ProjMtxNum(u32 op, u32 diff); + void Execute_ProjMtxData(u32 op, u32 diff); + void Execute_TgenMtxNum(u32 op, u32 diff); + void Execute_TgenMtxData(u32 op, u32 diff); + void Execute_BoneMtxNum(u32 op, u32 diff); + void Execute_BoneMtxData(u32 op, u32 diff); + void Execute_BlockTransferStart(u32 op, u32 diff); + */ + + // Using string because it's generic - makes no assumptions on the size of the shader IDs of this backend. + std::vector DebugGetShaderIDs(DebugShaderType shader) override; + std::string DebugGetShaderString(std::string id, DebugShaderType shader, DebugShaderStringType stringType) override; + +protected: + void FastRunLoop(DisplayList &list) override; + void ProcessEvent(GPUEvent ev) override; + void FastLoadBoneMatrix(u32 target) override; + void FinishDeferred() override; + +private: + void DoBlockTransfer(u32 skipDrawReason); + + void UpdateCmdInfo(); + + static CommandInfo cmdInfo_[256]; + + FramebufferManagerVulkan framebufferManager_; + TextureCacheVulkan textureCache_; + // DepalShaderCache depalShaderCache_; + DrawEngineVulkan transformDraw_; + // FragmentTestCache fragmentTestCache_; + PipelineManagerVulkan *pipelineManager_; + + bool resized_; + int lastVsync_; + + std::string reportingPrimaryInfo_; + std::string reportingFullInfo_; +}; diff --git a/GPU/Vulkan/PipelineManagerVulkan.cpp b/GPU/Vulkan/PipelineManagerVulkan.cpp new file mode 100644 index 0000000000..9ef2abce4a --- /dev/null +++ b/GPU/Vulkan/PipelineManagerVulkan.cpp @@ -0,0 +1,221 @@ +#include + +#include "Common/Log.h" +#include "GPU/Vulkan/VulkanUtil.h" +#include "GPU/Vulkan/PipelineManagerVulkan.h" + +struct DeclTypeInfo { + VkFormat type; + const char * name; +}; + +static const DeclTypeInfo VComp[] = { + { VK_FORMAT_UNDEFINED, "NULL" }, // DEC_NONE, + { VK_FORMAT_R32_SFLOAT, "R32_SFLOAT " }, // DEC_FLOAT_1, + { VK_FORMAT_R32G32_SFLOAT, "R32G32_SFLOAT " }, // DEC_FLOAT_2, + { VK_FORMAT_R32G32B32_SFLOAT, "R32G32B32_SFLOAT " }, // DEC_FLOAT_3, + { VK_FORMAT_R32G32B32A32_SFLOAT, "R32G32B32A32_SFLOAT " }, // DEC_FLOAT_4, + + { VK_FORMAT_UNDEFINED, "UNDEFINED" }, // DEC_S8_3, + + { VK_FORMAT_R16G16B16A16_SNORM, "R16G16B16A16_SNORM " }, // DEC_S16_3, + { VK_FORMAT_R8G8B8A8_SNORM, "R8G8B8A8_SNORM " }, // DEC_U8_1, + { VK_FORMAT_R8G8B8A8_SNORM, "R8G8B8A8_SNORM " }, // DEC_U8_2, + { VK_FORMAT_R8G8B8A8_SNORM, "R8G8B8A8_SNORM " }, // DEC_U8_3, + { VK_FORMAT_R8G8B8A8_SNORM, "R8G8B8A8_SNORM " }, // DEC_U8_4, + { VK_FORMAT_R16G16_UNORM, "R16G16_UNORM" }, // DEC_U16_1, + { VK_FORMAT_R16G16_UNORM, "R16G16_UNORM" }, // DEC_U16_2, + { VK_FORMAT_R16G16B16A16_UNORM, "R16G16B16A16_UNORM " }, // DEC_U16_3, + { VK_FORMAT_R16G16B16A16_UNORM, "R16G16B16A16_UNORM " }, // DEC_U16_4, + // Not supported in regular DX9 so faking, will cause graphics bugs until worked around + { VK_FORMAT_R8G8_UINT, "VK_FORMAT_UNDEFINED" }, // DEC_U8A_2, + { VK_FORMAT_R16G16_UINT, "VK_FORMAT_UNDEFINED" }, // DEC_U16A_2, +}; + +void VertexAttribSetup(VkVertexInputAttributeDescription *attr, int fmt, int offset, PspAttributeLocation location) { + attr->location = (uint32_t)location; + attr->binding = 0; + attr->format = VComp[fmt].type; + attr->offset = offset; +} + +// Returns the number of attributes that were set. +// We could cache these AttributeDescription arrays (with pspFmt as the key), but hardly worth bothering +// as we will only call this code when we need to create a new VkPipeline. +int SetupVertexAttribs(VkVertexInputAttributeDescription attrs[], const DecVtxFormat &decFmt) { + int count = 0; + if (decFmt.w0fmt != 0) { + VertexAttribSetup(&attrs[count++], decFmt.w0fmt, decFmt.w0off, PspAttributeLocation::W1); + } + if (decFmt.w1fmt != 0) { + VertexAttribSetup(&attrs[count++], decFmt.w1fmt, decFmt.w1off, PspAttributeLocation::W2); + } + if (decFmt.uvfmt != 0) { + VertexAttribSetup(&attrs[count++], decFmt.uvfmt, decFmt.uvoff, PspAttributeLocation::TEXCOORD); + } + if (decFmt.c0fmt != 0) { + VertexAttribSetup(&attrs[count++], decFmt.c0fmt, decFmt.c0off, PspAttributeLocation::COLOR0); + } + if (decFmt.c1fmt != 0) { + VertexAttribSetup(&attrs[count++], decFmt.c1fmt, decFmt.c1off, PspAttributeLocation::COLOR1); + } + if (decFmt.nrmfmt != 0) { + VertexAttribSetup(&attrs[count++], decFmt.nrmfmt, decFmt.nrmoff, PspAttributeLocation::NORMAL); + } + // Position is always there. + VertexAttribSetup(&attrs[count++], decFmt.posfmt, decFmt.posoff, PspAttributeLocation::POSITION); + return count; +} + +int SetupVertexAttribsPretransformed(VkVertexInputAttributeDescription attrs[]) { + VertexAttribSetup(&attrs[0], DEC_FLOAT_4, 0, PspAttributeLocation::POSITION); + VertexAttribSetup(&attrs[1], DEC_FLOAT_3, 16, PspAttributeLocation::TEXCOORD); + VertexAttribSetup(&attrs[2], DEC_U8_4, 28, PspAttributeLocation::COLOR0); + VertexAttribSetup(&attrs[3], DEC_U8_4, 32, PspAttributeLocation::COLOR1); + return 4; +} + +static VulkanPipeline *CreateVulkanPipeline(VkDevice device, VkPipelineCache pipelineCache, const VulkanPipelineRasterStateKey &key, const DecVtxFormat &vfmt, VkShaderModule vshader, VkShaderModule fshader, bool useHwTransform) { + VkPipelineColorBlendAttachmentState blend0; + blend0.blendEnable = key.blendEnable; + if (key.blendEnable) { + blend0.colorBlendOp = key.blendOpColor; + blend0.alphaBlendOp = key.blendOpAlpha; + blend0.srcColorBlendFactor = key.srcColor; + blend0.srcAlphaBlendFactor = key.srcAlpha; + blend0.dstColorBlendFactor = key.destColor; + blend0.dstAlphaBlendFactor = key.destAlpha; + } + blend0.colorWriteMask = key.colorWriteMask; + + VkPipelineColorBlendStateCreateInfo cbs; + cbs.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; + cbs.pNext = nullptr; + cbs.pAttachments = &blend0; + cbs.attachmentCount = 1; + cbs.logicOpEnable = key.logicOpEnable; + if (key.logicOpEnable) + cbs.logicOp = key.logicOp; + else + cbs.logicOp = VK_LOGIC_OP_COPY; + + VkPipelineDepthStencilStateCreateInfo dss; + dss.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; + dss.depthBoundsTestEnable = false; + dss.stencilTestEnable = key.stencilTestEnable; + if (key.stencilTestEnable) { + dss.front.compareOp = key.stencilCompareOp; + dss.front.passOp = key.stencilPassOp; + dss.front.failOp = key.stencilFailOp; + dss.front.depthFailOp = key.stencilDepthFailOp; + // Back stencil is always the same as front on PSP. + memcpy(&dss.back, &dss.front, sizeof(dss.front)); + } + dss.depthTestEnable = key.depthTestEnable; + if (key.depthTestEnable) { + dss.depthCompareOp = key.depthCompareOp; + dss.depthWriteEnable = key.depthWriteEnable; + } + + VkGraphicsPipelineCreateInfo pipe; + pipe.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; + pipe.pNext = nullptr; + + pipe.pColorBlendState = &cbs; + if (key.depthTestEnable || key.stencilTestEnable) { + pipe.pDepthStencilState = &dss; + } else { + pipe.pDepthStencilState = nullptr; + } + + VkDynamicState dynamicStates[8]; + int numDyn = 0; + if (key.blendEnable) { + dynamicStates[numDyn++] = VK_DYNAMIC_STATE_BLEND_CONSTANTS; + } + dynamicStates[numDyn++] = VK_DYNAMIC_STATE_SCISSOR; + dynamicStates[numDyn++] = VK_DYNAMIC_STATE_VIEWPORT; + if (key.stencilTestEnable) { + dynamicStates[numDyn++] = VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK; + dynamicStates[numDyn++] = VK_DYNAMIC_STATE_STENCIL_REFERENCE; + dynamicStates[numDyn++] = VK_DYNAMIC_STATE_STENCIL_WRITE_MASK; + } + + VkPipelineDynamicStateCreateInfo ds; + ds.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; + ds.pNext = nullptr; + ds.pDynamicStates = dynamicStates; + ds.dynamicStateCount = numDyn; + + pipe.pDynamicState = &ds; + + VkPipelineRasterizationStateCreateInfo rs; + rs.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; + rs.pNext = nullptr; + rs.depthBiasEnable = false; + rs.cullMode = key.cullMode; + rs.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; + rs.lineWidth = 1.0f; + rs.rasterizerDiscardEnable = false; + rs.polygonMode = VK_POLYGON_MODE_FILL; + rs.depthClampEnable = false; + + pipe.pRasterizationState = &rs; + + // We will use dynamic viewport state. + pipe.pViewportState = nullptr; + + VkPipelineShaderStageCreateInfo ss[2]; + ss[0].sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; + ss[0].pNext = nullptr; + ss[0].stage = VK_SHADER_STAGE_VERTEX_BIT; + ss[0].pSpecializationInfo = nullptr; + ss[0].module = vshader; + ss[0].pName = "main"; + ss[0].flags = 0; + ss[1].sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; + ss[1].pNext = nullptr; + ss[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; + ss[1].pSpecializationInfo = nullptr; + ss[1].module = fshader; + ss[1].pName = "main"; + ss[1].flags = 0; + pipe.stageCount = 2; + pipe.pStages = ss; + pipe.basePipelineIndex = 0; + + int vertexStride = 0; + + int offset = 0; + VkVertexInputAttributeDescription attrs[8]; + int attributeCount; + if (useHwTransform) { + attributeCount = SetupVertexAttribs(attrs, vfmt); + } else { + attributeCount = SetupVertexAttribsPretransformed(attrs); + } + + VkVertexInputBindingDescription ibd; + ibd.binding = 0; + ibd.inputRate = VK_VERTEX_INPUT_RATE_VERTEX; + ibd.stride = vertexStride; + + VkPipelineVertexInputStateCreateInfo vis; + vis.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; + vis.pNext = nullptr; + vis.vertexBindingDescriptionCount = 1; + vis.pVertexBindingDescriptions = &ibd; + vis.vertexAttributeDescriptionCount = attributeCount; + vis.pVertexAttributeDescriptions = attrs; + + VkPipeline pipeline; + VkResult result = vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipe, nullptr, &pipeline); + if (result != VK_SUCCESS) { + ERROR_LOG(G3D, "Failed creating graphics pipeline!"); + return nullptr; + } + + VulkanPipeline *vulkanPipeline = new VulkanPipeline(); + vulkanPipeline->pipeline = pipeline; + return vulkanPipeline; +} diff --git a/GPU/Vulkan/PipelineManagerVulkan.h b/GPU/Vulkan/PipelineManagerVulkan.h new file mode 100644 index 0000000000..d28514267e --- /dev/null +++ b/GPU/Vulkan/PipelineManagerVulkan.h @@ -0,0 +1,106 @@ +// Copyright (c) 2015- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#pragma once + +#include "GPU/Common/VertexDecoderCommon.h" +#include "GPU/Common/ShaderId.h" +#include "GPU/Vulkan/VulkanUtil.h" + +// The Descriptor Set used for the majority of PSP rendering looks like this: +// +// * binding 0: Vertex Data (up to 7 locations as defined in PspAttributeLocation) +// * binding 1: Texture Sampler (the PSP texture) +// * binding 2: Secondary texture sampler for shader blending or depal palettes +// * binding 3: Vertex Uniform Buffer +// * binding 4: Fragment Uniform Buffer +// +// All shaders conform to this layout, so they are all compatible with the same descriptor set. +// The format of the various uniform buffers may vary though - vertex shaders that don't skin +// won't get any bone data, etc. + +enum class PspAttributeLocation { + POSITION = 0, + TEXCOORD = 1, + NORMAL = 2, + W1 = 3, + W2 = 4, + COLOR0 = 5, + COLOR1 = 6, + + COUNT +}; + +// Let's pack this tight using bitfields. +// If an enable flag is set to 0, all the data fields for that section should +// also be set to 0. +// ~54 bits. +struct VulkanPipelineRasterStateKey { + // Blend + bool blendEnable : 1; + VkBlendFactor srcColor : 5; + VkBlendFactor destColor : 5; + VkBlendFactor srcAlpha : 5; + VkBlendFactor destAlpha : 5; + VkBlendOp blendOpColor : 3; + VkBlendOp blendOpAlpha : 3; + bool logicOpEnable : 1; + VkLogicOp logicOp : 4; + int colorWriteMask : 4; + + // Depth/Stencil + bool depthTestEnable : 1; + bool depthWriteEnable : 1; + VkCompareOp depthCompareOp : 3; + bool stencilTestEnable : 1; + VkCompareOp stencilCompareOp : 4; + VkStencilOp stencilPassOp : 4; + VkStencilOp stencilFailOp : 4; + VkStencilOp stencilDepthFailOp : 4; + // We'll use dynamic state for writemask, reference and comparemask to start with. + + // Rasterizer + VkCullModeFlagBits cullMode : 2; +}; + +// All the information needed. All PSP rendering (except full screen clears?) will make use of a single +// render pass definition. +struct VulkanPipelineKey { + VulkanPipelineRasterStateKey raster; + int prim; + bool pretransformed; + uint32_t vertType; + ShaderID vShaderId; + ShaderID fShaderId; +}; + +enum { + UB_VS_BASICTRANSFORM = (1 << 0), + UB_VS_BONES = (1 << 1), + UB_VS_LIGHTS = (1 << 2), +}; + +// Simply wraps a Vulkan pipeline, providing some metadata. +struct VulkanPipeline { + VkPipeline pipeline; + int uniformBlocks; // UB_ enum above. +}; + +class PipelineManagerVulkan { +public: + +}; diff --git a/GPU/Vulkan/ShaderCompiler.cpp b/GPU/Vulkan/ShaderCompiler.cpp new file mode 100644 index 0000000000..b644c03db5 --- /dev/null +++ b/GPU/Vulkan/ShaderCompiler.cpp @@ -0,0 +1,23 @@ +// Copyright (c) 2015- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#include "GPU/Vulkan/VulkanUtil.h" +#include "GPU/Vulkan/ShaderCompiler.h" + +bool CompileGLSLVulkan(const char *code, std::vector &spirv, std::string &errorMessage) { + return false; +} diff --git a/GPU/Vulkan/ShaderCompiler.h b/GPU/Vulkan/ShaderCompiler.h new file mode 100644 index 0000000000..8c5121f96f --- /dev/null +++ b/GPU/Vulkan/ShaderCompiler.h @@ -0,0 +1,27 @@ +// Copyright (c) 2015- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#pragma once + +#include +#include "GPU/Vulkan/VulkanUtil.h" + +// Wrapper around the GLSL compiler library. Compiles GLSL into SPIR-V consumable by Vulkan. +bool CompileGLSLVulkan(const char *code, std::vector &spirv, std::string &errorMessage); + +// TODO: Compute shaders + diff --git a/GPU/Vulkan/ShaderManagerVulkan.cpp b/GPU/Vulkan/ShaderManagerVulkan.cpp new file mode 100644 index 0000000000..029e7e9030 --- /dev/null +++ b/GPU/Vulkan/ShaderManagerVulkan.cpp @@ -0,0 +1,612 @@ +// Copyright (c) 2015- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#ifdef _WIN32 +#define SHADERLOG +#endif + +#include + +#include "base/logging.h" +#include "math/lin/matrix4x4.h" +#include "math/math_util.h" +#include "math/dataconv.h" +#include "util/text/utf8.h" +#include "thin3d/vulkan_utils.h" + +#include "Common/Common.h" +#include "Core/Config.h" +#include "Core/Reporting.h" +#include "GPU/Math3D.h" +#include "GPU/GPUState.h" +#include "GPU/ge_constants.h" +#include "GPU/Vulkan/ShaderManagerVulkan.h" +#include "GPU/Vulkan/DrawEngineVulkan.h" +#include "GPU/Vulkan/FramebufferVulkan.h" +#include "GPU/Vulkan/ShaderCompiler.h" +#include "GPU/Vulkan/FragmentShaderGeneratorVulkan.h" +#include "GPU/Vulkan/VertexShaderGeneratorVulkan.h" +#include "UI/OnScreenDisplay.h" + +VulkanFragmentShader::VulkanFragmentShader(VkDevice device, ShaderID id, const char *code, bool useHWTransform) + : device_(device), id_(id), failed_(false), useHWTransform_(useHWTransform), module_(nullptr) { + source_ = code; +#ifdef SHADERLOG + OutputDebugString(ConvertUTF8ToWString(code).c_str()); +#endif + + std::string errorMessage; + std::vector spirv; + bool success = CompileGLSLVulkan(code, spirv, errorMessage); + if (!errorMessage.empty()) { + if (success) { + ERROR_LOG(G3D, "Warnings in shader compilation!"); + } else { + ERROR_LOG(G3D, "Error in shader compilation!"); + } + ERROR_LOG(G3D, "Messages: %s", errorMessage.c_str()); + ERROR_LOG(G3D, "Shader source:\n%s", code); + OutputDebugStringUTF8("Messages:\n"); + OutputDebugStringUTF8(errorMessage.c_str()); + Reporting::ReportMessage("Vulkan error in shader compilation: info: %s / code: %s", errorMessage.c_str(), code); + } else { + success = CreateShaderModule(device_, spirv, &module_); + } + + if (!success) { + failed_ = true; + return; + } else { + DEBUG_LOG(G3D, "Compiled shader:\n%s\n", (const char *)code); + } +} + +VulkanFragmentShader::~VulkanFragmentShader() { + if (module_) { + vkDestroyShaderModule(device_, module_, nullptr); + } +} + +std::string VulkanFragmentShader::GetShaderString(DebugShaderStringType type) const { + switch (type) { + case SHADER_STRING_SOURCE_CODE: + return source_; + case SHADER_STRING_SHORT_DESC: + return FragmentShaderDesc(id_); + default: + return "N/A"; + } +} + +VulkanVertexShader::VulkanVertexShader(VkDevice device, ShaderID id, const char *code, int vertType, bool useHWTransform) + : device_(device), id_(id), failed_(false), useHWTransform_(useHWTransform), module_(nullptr) { + source_ = code; +#ifdef SHADERLOG + OutputDebugString(ConvertUTF8ToWString(code).c_str()); +#endif + std::string errorMessage; + std::vector spirv; + bool success = CompileGLSLVulkan(code, spirv, errorMessage); + if (!errorMessage.empty()) { + if (success) { + ERROR_LOG(G3D, "Warnings in shader compilation!"); + } else { + ERROR_LOG(G3D, "Error in shader compilation!"); + } + ERROR_LOG(G3D, "Messages: %s", errorMessage.c_str()); + ERROR_LOG(G3D, "Shader source:\n%s", code); + OutputDebugStringUTF8("Messages:\n"); + OutputDebugStringUTF8(errorMessage.c_str()); + Reporting::ReportMessage("Vulkan error in shader compilation: info: %s / code: %s", errorMessage.c_str(), code); + } else { + success = CreateShaderModule(device_, spirv, &module_); + } + + if (!success) { + failed_ = true; + module_ = nullptr; + return; + } else { + DEBUG_LOG(G3D, "Compiled shader:\n%s\n", (const char *)code); + } +} + +VulkanVertexShader::~VulkanVertexShader() { + if (module_) { + vkDestroyShaderModule(device_, module_, nullptr); + } +} + +std::string VulkanVertexShader::GetShaderString(DebugShaderStringType type) const { + switch (type) { + case SHADER_STRING_SOURCE_CODE: + return source_; + case SHADER_STRING_SHORT_DESC: + return VertexShaderDesc(id_); + default: + return "N/A"; + } +} + +/* +// Utility +void ShaderManagerVulkan::VSSetMatrix4x3(int creg, const float *m4x3) { + float m4x4[16]; + ConvertMatrix4x3To4x4Transposed(m4x4, m4x3); + pD3Ddevice->SetVertexShaderConstantF(creg, m4x4, 4); +} + +void ShaderManagerVulkan::VSSetMatrix4x3_3(int creg, const float *m4x3) { + float m3x4[16]; + ConvertMatrix4x3To3x4Transposed(m3x4, m4x3); + pD3Ddevice->SetVertexShaderConstantF(creg, m3x4, 3); +} + +void ShaderManagerVulkan::VSSetMatrix(int creg, const float* pMatrix) { + float transp[16]; + Transpose4x4(transp, pMatrix); + pD3Ddevice->SetVertexShaderConstantF(creg, transp, 4); +} +*/ + +// Depth in ogl is between -1;1 we need between 0;1 and optionally reverse it +static void ConvertProjMatrixToVulkan(Matrix4x4 &in, bool invertedX, bool invertedY, bool invertedZ) { + // Half pixel offset hack + float xoff = 0.5f / gstate_c.curRTRenderWidth; + xoff = gstate_c.vpXOffset + (invertedX ? xoff : -xoff); + float yoff = -0.5f / gstate_c.curRTRenderHeight; + yoff = gstate_c.vpYOffset + (invertedY ? yoff : -yoff); + + if (invertedX) + xoff = -xoff; + if (invertedY) + yoff = -yoff; + + in.translateAndScale(Vec3(xoff, yoff, 0.5f), Vec3(gstate_c.vpWidthScale, gstate_c.vpHeightScale, invertedZ ? -0.5 : 0.5f)); +} + +static void ConvertProjMatrixToVulkanThrough(Matrix4x4 &in) { + float xoff = -0.5f / gstate_c.curRTRenderWidth; + float yoff = 0.5f / gstate_c.curRTRenderHeight; + in.translateAndScale(Vec3(xoff, yoff, 0.5f), Vec3(1.0f, 1.0f, 0.5f)); +} + +void ShaderManagerVulkan::PSUpdateUniforms(int dirtyUniforms) { + if (dirtyUniforms & DIRTY_TEXENV) { + Uint8x3ToFloat4(ub_fragment.texEnvColor, gstate.texenvcolor); + } + if (dirtyUniforms & DIRTY_ALPHACOLORREF) { + Uint8x3ToFloat4_Alpha(ub_fragment.alphaColorRef, gstate.getColorTestRef(), (float)gstate.getAlphaTestRef()); + } + if (dirtyUniforms & DIRTY_ALPHACOLORMASK) { + Uint8x3ToFloat4(ub_fragment.colorTestMask, gstate.colortestmask); + } + if (dirtyUniforms & DIRTY_FOGCOLOR) { + Uint8x3ToFloat4(ub_fragment.fogColor, gstate.fogcolor); + } + if (dirtyUniforms & DIRTY_STENCILREPLACEVALUE) { + Uint8x1ToFloat4(ub_fragment.stencilReplace, gstate.getStencilTestRef()); + } + if (dirtyUniforms & DIRTY_SHADERBLEND) { + Uint8x3ToFloat4(ub_fragment.blendFixA, gstate.getFixA()); + Uint8x3ToFloat4(ub_fragment.blendFixB, gstate.getFixB()); + } + if (dirtyUniforms & DIRTY_TEXCLAMP) { + const float invW = 1.0f / (float)gstate_c.curTextureWidth; + const float invH = 1.0f / (float)gstate_c.curTextureHeight; + const int w = gstate.getTextureWidth(0); + const int h = gstate.getTextureHeight(0); + const float widthFactor = (float)w * invW; + const float heightFactor = (float)h * invH; + + // First wrap xy, then half texel xy (for clamp.) + const float texclamp[4] = { + widthFactor, + heightFactor, + invW * 0.5f, + invH * 0.5f, + }; + const float texclampoff[2] = { + gstate_c.curTextureXOffset * invW, + gstate_c.curTextureYOffset * invH, + }; + CopyFloat4(ub_fragment.texClamp, texclamp); + CopyFloat2(ub_fragment.texClampOffset, texclampoff); + } +} + +void ShaderManagerVulkan::VSUpdateUniforms(int dirtyUniforms) { + // Update any dirty uniforms before we draw + if (dirtyUniforms & DIRTY_PROJMATRIX) { + Matrix4x4 flippedMatrix; + memcpy(&flippedMatrix, gstate.projMatrix, 16 * sizeof(float)); + + const bool invertedY = gstate_c.vpHeight < 0; + if (!invertedY) { + flippedMatrix[1] = -flippedMatrix[1]; + flippedMatrix[5] = -flippedMatrix[5]; + flippedMatrix[9] = -flippedMatrix[9]; + flippedMatrix[13] = -flippedMatrix[13]; + } + const bool invertedX = gstate_c.vpWidth < 0; + if (invertedX) { + flippedMatrix[0] = -flippedMatrix[0]; + flippedMatrix[4] = -flippedMatrix[4]; + flippedMatrix[8] = -flippedMatrix[8]; + flippedMatrix[12] = -flippedMatrix[12]; + } + + const bool invertedZ = gstate_c.vpDepthScale < 0; + ConvertProjMatrixToVulkan(flippedMatrix, invertedX, invertedY, invertedZ); + + CopyMatrix4x4(ub_transformCommon.proj, flippedMatrix.getReadPtr()); + } + if (dirtyUniforms & DIRTY_PROJTHROUGHMATRIX) { + Matrix4x4 proj_through; + proj_through.setOrtho(0.0f, gstate_c.curRTWidth, gstate_c.curRTHeight, 0, 0, 1); + ConvertProjMatrixToVulkanThrough(proj_through); + CopyMatrix4x4(ub_transformCommon.proj, proj_through.getReadPtr()); + } + + // Transform + if (dirtyUniforms & DIRTY_WORLDMATRIX) { + ConvertMatrix4x3To4x4(ub_transformCommon.world, gstate.worldMatrix); + } + if (dirtyUniforms & DIRTY_VIEWMATRIX) { + ConvertMatrix4x3To4x4(ub_transformCommon.view, gstate.viewMatrix); + } + if (dirtyUniforms & DIRTY_TEXMATRIX) { + ConvertMatrix4x3To4x4(ub_transformCommon.tex, gstate.tgenMatrix); + } + if (dirtyUniforms & DIRTY_FOGCOEF) { + float fogcoef[2] = { + getFloat24(gstate.fog1), + getFloat24(gstate.fog2), + }; + if (my_isinf(fogcoef[1])) { + // not really sure what a sensible value might be. + fogcoef[1] = fogcoef[1] < 0.0f ? -10000.0f : 10000.0f; + } else if (my_isnan(fogcoef[1])) { + // Workaround for https://github.com/hrydgard/ppsspp/issues/5384#issuecomment-38365988 + // Just put the fog far away at a large finite distance. + // Infinities and NaNs are rather unpredictable in shaders on many GPUs + // so it's best to just make it a sane calculation. + fogcoef[0] = 100000.0f; + fogcoef[1] = 1.0f; + } +#ifndef MOBILE_DEVICE + else if (my_isnanorinf(fogcoef[1]) || my_isnanorinf(fogcoef[0])) { + ERROR_LOG_REPORT_ONCE(fognan, G3D, "Unhandled fog NaN/INF combo: %f %f", fogcoef[0], fogcoef[1]); + } +#endif + CopyFloat2(ub_transformCommon.fogCoef, fogcoef); + } + // TODO: Could even set all bones in one go if they're all dirty. +#ifdef USE_BONE_ARRAY + if (u_bone != 0) { + float allBones[8 * 16]; + + bool allDirty = true; + for (int i = 0; i < numBones; i++) { + if (dirtyUniforms & (DIRTY_BONEMATRIX0 << i)) { + ConvertMatrix4x3To4x4(allBones + 16 * i, gstate.boneMatrix + 12 * i); + } else { + allDirty = false; + } + } + if (allDirty) { + // Set them all with one call + //glUniformMatrix4fv(u_bone, numBones, GL_FALSE, allBones); + } else { + // Set them one by one. Could try to coalesce two in a row etc but too lazy. + for (int i = 0; i < numBones; i++) { + if (dirtyUniforms & (DIRTY_BONEMATRIX0 << i)) { + //glUniformMatrix4fv(u_bone + i, 1, GL_FALSE, allBones + 16 * i); + } + } + } + } +#else + for (int i = 0; i < 8; i++) { + if (dirtyUniforms & (DIRTY_BONEMATRIX0 << i)) { + ConvertMatrix4x3To4x4(ub_bones.bones[i], gstate.boneMatrix + 12 * i); + } + } +#endif + + // Texturing + if (dirtyUniforms & DIRTY_UVSCALEOFFSET) { + const float invW = 1.0f / (float)gstate_c.curTextureWidth; + const float invH = 1.0f / (float)gstate_c.curTextureHeight; + const int w = gstate.getTextureWidth(0); + const int h = gstate.getTextureHeight(0); + const float widthFactor = (float)w * invW; + const float heightFactor = (float)h * invH; + + float uvscaleoff[4]; + switch (gstate.getUVGenMode()) { + case GE_TEXMAP_TEXTURE_COORDS: + // Not sure what GE_TEXMAP_UNKNOWN is, but seen in Riviera. Treating the same as GE_TEXMAP_TEXTURE_COORDS works. + case GE_TEXMAP_UNKNOWN: + uvscaleoff[0] = gstate_c.uv.uScale * widthFactor; + uvscaleoff[1] = gstate_c.uv.vScale * heightFactor; + uvscaleoff[2] = gstate_c.uv.uOff * widthFactor; + uvscaleoff[3] = gstate_c.uv.vOff * heightFactor; + break; + + // These two work the same whether or not we prescale UV. + + case GE_TEXMAP_TEXTURE_MATRIX: + // We cannot bake the UV coord scale factor in here, as we apply a matrix multiplication + // before this is applied, and the matrix multiplication may contain translation. In this case + // the translation will be scaled which breaks faces in Hexyz Force for example. + // So I've gone back to applying the scale factor in the shader. + uvscaleoff[0] = widthFactor; + uvscaleoff[1] = heightFactor; + uvscaleoff[2] = 0.0f; + uvscaleoff[3] = 0.0f; + break; + + case GE_TEXMAP_ENVIRONMENT_MAP: + // In this mode we only use uvscaleoff to scale to the texture size. + uvscaleoff[0] = widthFactor; + uvscaleoff[1] = heightFactor; + uvscaleoff[2] = 0.0f; + uvscaleoff[3] = 0.0f; + break; + + default: + ERROR_LOG_REPORT(G3D, "Unexpected UV gen mode: %d", gstate.getUVGenMode()); + } + CopyFloat4(ub_transformCommon.uvScaleOffset, uvscaleoff); + } + + if (dirtyUniforms & DIRTY_DEPTHRANGE) { + float viewZScale = gstate.getViewportZScale(); + float viewZCenter = gstate.getViewportZCenter(); + + // Given the way we do the rounding, the integer part of the offset is probably mostly irrelevant as we cancel + // it afterwards anyway. + // It seems that we should adjust for D3D projection matrix. We got squashed up to only 0-1, so we divide + // the scale factor by 2, and add an offset. But, this doesn't work! I get near-perfect results not doing it. + // viewZScale *= 2.0f; + + // Need to take the possibly inverted proj matrix into account. + if (gstate_c.vpDepthScale < 0.0) + viewZScale *= -1.0f; + viewZCenter -= 32767.5f; + float viewZInvScale; + if (viewZScale != 0.0) { + viewZInvScale = 1.0f / viewZScale; + } else { + viewZInvScale = 0.0; + } + + float data[4] = { viewZScale, viewZCenter, viewZCenter, viewZInvScale }; + CopyFloat4(ub_transformCommon.depthRange, data); + } + + // Lighting + if (dirtyUniforms & DIRTY_AMBIENT) { + Uint8x3ToFloat4_AlphaUint8(ub_lightGlobal.ambientColor, gstate.ambientcolor, gstate.getAmbientA()); + } + if (dirtyUniforms & DIRTY_MATAMBIENTALPHA) { + // Note - this one is not in lighting but in transformCommon as it has uses beyond lighting + Uint8x3ToFloat4_AlphaUint8(ub_transformCommon.matAmbient, gstate.materialambient, gstate.getMaterialAmbientA()); + } + if (dirtyUniforms & DIRTY_MATDIFFUSE) { + Uint8x3ToFloat4(ub_lightGlobal.materialDiffuse, gstate.materialdiffuse); + } + if (dirtyUniforms & DIRTY_MATEMISSIVE) { + Uint8x3ToFloat4(ub_lightGlobal.materialEmissive, gstate.materialemissive); + } + if (dirtyUniforms & DIRTY_MATSPECULAR) { + Uint8x3ToFloat4_Alpha(ub_lightGlobal.materialEmissive, gstate.materialspecular, getFloat24(gstate.materialspecularcoef)); + } + + for (int i = 0; i < 4; i++) { + if (dirtyUniforms & (DIRTY_LIGHT0 << i)) { + if (gstate.isDirectionalLight(i)) { + // Prenormalize + float x = getFloat24(gstate.lpos[i * 3 + 0]); + float y = getFloat24(gstate.lpos[i * 3 + 1]); + float z = getFloat24(gstate.lpos[i * 3 + 2]); + float len = sqrtf(x*x + y*y + z*z); + if (len == 0.0f) + len = 1.0f; + else + len = 1.0f / len; + float vec[3] = { x * len, y * len, z * len }; + CopyFloat3To4(ub_lights.lpos[i], vec); + } else { + ExpandFloat24x3ToFloat4(ub_lights.lpos[i], &gstate.lpos[i * 3]); + } + ExpandFloat24x3ToFloat4(ub_lights.ldir[i], &gstate.ldir[i * 3]); + ExpandFloat24x3ToFloat4(ub_lights.latt[i], &gstate.latt[i * 3]); + CopyFloat1To4(ub_lights.lightAngle[i], getFloat24(gstate.lcutoff[i])); + CopyFloat1To4(ub_lights.lightSpotCoef[i], getFloat24(gstate.lconv[i])); + Uint8x3ToFloat4(ub_lights.lightAmbient[i], gstate.lcolor[i * 3]); + Uint8x3ToFloat4(ub_lights.lightDiffuse[i], gstate.lcolor[i * 3 + 1]); + Uint8x3ToFloat4(ub_lights.lightSpecular[i], gstate.lcolor[i * 3 + 2]); + } + } +} + +ShaderManagerVulkan::ShaderManagerVulkan(VkDevice device) : device_(device), lastVShader_(nullptr), lastFShader_(nullptr), globalDirty_(0xFFFFFFFF) { + codeBuffer_ = new char[16384]; +} + +ShaderManagerVulkan::~ShaderManagerVulkan() { + delete [] codeBuffer_; +} + +void ShaderManagerVulkan::Clear() { + for (auto iter = fsCache_.begin(); iter != fsCache_.end(); ++iter) { + delete iter->second; + } + for (auto iter = vsCache_.begin(); iter != vsCache_.end(); ++iter) { + delete iter->second; + } + fsCache_.clear(); + vsCache_.clear(); + globalDirty_ = 0xFFFFFFFF; + lastFSID_.clear(); + lastVSID_.clear(); + DirtyShader(); +} + +void ShaderManagerVulkan::ClearCache(bool deleteThem) { + Clear(); +} + + +void ShaderManagerVulkan::DirtyShader() { + // Forget the last shader ID + lastFSID_.clear(); + lastVSID_.clear(); + lastVShader_ = nullptr; + lastFShader_ = nullptr; + globalDirty_ = 0xFFFFFFFF; +} + +void ShaderManagerVulkan::DirtyLastShader() { // disables vertex arrays + lastVShader_ = nullptr; + lastFShader_ = nullptr; +} + + +void ShaderManagerVulkan::GetShaders(int prim, u32 vertType, VulkanVertexShader **vshader, VulkanFragmentShader **fshader) { + bool useHWTransform = CanUseHardwareTransform(prim); + + ShaderID VSID; + ComputeVertexShaderID(&VSID, vertType, useHWTransform); + ShaderID FSID; + ComputeFragmentShaderID(&FSID); + + // Just update uniforms if this is the same shader as last time. + if (lastVShader_ != nullptr && lastFShader_ != nullptr && VSID == lastVSID_ && FSID == lastFSID_) { + if (globalDirty_) { + PSUpdateUniforms(globalDirty_); + VSUpdateUniforms(globalDirty_); + globalDirty_ = 0; + } + *vshader = lastVShader_; + *fshader = lastFShader_; + // Already all set, no need to look up in shader maps. + return; + } + + VSCache::iterator vsIter = vsCache_.find(VSID); + VulkanVertexShader *vs; + if (vsIter == vsCache_.end()) { + // Vertex shader not in cache. Let's compile it. + GenerateVulkanGLSLVertexShader(VSID, codeBuffer_); + vs = new VulkanVertexShader(device_, VSID, codeBuffer_, vertType, useHWTransform); + + if (vs->Failed()) { + ERROR_LOG(HLE, "Shader compilation failed, falling back to software transform"); + osm.Show("hardware transform error - falling back to software", 2.5f, 0xFF3030FF, -1, true); + delete vs; + + ComputeVertexShaderID(&VSID, vertType, false); + + // TODO: Look for existing shader with the appropriate ID, use that instead of generating a new one - however, need to make sure + // that that shader ID is not used when computing the linked shader ID below, because then IDs won't match + // next time and we'll do this over and over... + + // Can still work with software transform. + GenerateVulkanGLSLVertexShader(VSID, codeBuffer_); + vs = new VulkanVertexShader(device_, VSID, codeBuffer_, vertType, false); + } + + vsCache_[VSID] = vs; + } else { + vs = vsIter->second; + } + lastVSID_ = VSID; + + FSCache::iterator fsIter = fsCache_.find(FSID); + VulkanFragmentShader *fs; + if (fsIter == fsCache_.end()) { + // Fragment shader not in cache. Let's compile it. + GenerateVulkanGLSLFragmentShader(FSID, codeBuffer_); + fs = new VulkanFragmentShader(device_, FSID, codeBuffer_, useHWTransform); + fsCache_[FSID] = fs; + } else { + fs = fsIter->second; + } + + lastFSID_ = FSID; + + if (globalDirty_) { + PSUpdateUniforms(globalDirty_); + VSUpdateUniforms(globalDirty_); + globalDirty_ = 0; + } + *vshader = vs; + *fshader = fs; +} + +std::vector ShaderManagerVulkan::DebugGetShaderIDs(DebugShaderType type) { + std::string id; + std::vector ids; + switch (type) { + case SHADER_TYPE_VERTEX: + { + for (auto iter : vsCache_) { + iter.first.ToString(&id); + ids.push_back(id); + } + } + break; + case SHADER_TYPE_FRAGMENT: + { + for (auto iter : fsCache_) { + iter.first.ToString(&id); + ids.push_back(id); + } + } + break; + } + return ids; +} + +std::string ShaderManagerVulkan::DebugGetShaderString(std::string id, DebugShaderType type, DebugShaderStringType stringType) { + ShaderID shaderId; + shaderId.FromString(id); + switch (type) { + case SHADER_TYPE_VERTEX: + { + auto iter = vsCache_.find(shaderId); + if (iter == vsCache_.end()) { + return ""; + } + return iter->second->GetShaderString(stringType); + } + + case SHADER_TYPE_FRAGMENT: + { + auto iter = fsCache_.find(shaderId); + if (iter == fsCache_.end()) { + return ""; + } + return iter->second->GetShaderString(stringType); + } + default: + return "N/A"; + } +} diff --git a/GPU/Vulkan/ShaderManagerVulkan.h b/GPU/Vulkan/ShaderManagerVulkan.h new file mode 100644 index 0000000000..7e099b3416 --- /dev/null +++ b/GPU/Vulkan/ShaderManagerVulkan.h @@ -0,0 +1,261 @@ +#pragma once +// Copyright (c) 2012- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#pragma once + +#include + +#include "base/basictypes.h" +#include "Globals.h" +#include "GPU/Common/ShaderCommon.h" +#include "GPU/Common/ShaderId.h" +#include "GPU/Vulkan/VertexShaderGeneratorVulkan.h" +#include "GPU/Vulkan/FragmentShaderGeneratorVulkan.h" +#include "GPU/Vulkan/VulkanUtil.h" +#include "math/lin/matrix4x4.h" + +void ConvertProjMatrixToVulkan(Matrix4x4 & in); + +// Pretty much full. Will need more bits for more fine grained dirty tracking for lights. +enum { + DIRTY_PROJMATRIX = (1 << 0), + DIRTY_PROJTHROUGHMATRIX = (1 << 1), + DIRTY_FOGCOLOR = (1 << 2), + DIRTY_FOGCOEF = (1 << 3), + DIRTY_TEXENV = (1 << 4), + DIRTY_ALPHACOLORREF = (1 << 5), + DIRTY_STENCILREPLACEVALUE = (1 << 6), + + DIRTY_ALPHACOLORMASK = (1 << 7), + DIRTY_LIGHT0 = (1 << 8), + DIRTY_LIGHT1 = (1 << 9), + DIRTY_LIGHT2 = (1 << 10), + DIRTY_LIGHT3 = (1 << 11), + + DIRTY_MATDIFFUSE = (1 << 12), + DIRTY_MATSPECULAR = (1 << 13), + DIRTY_MATEMISSIVE = (1 << 14), + DIRTY_AMBIENT = (1 << 15), + DIRTY_MATAMBIENTALPHA = (1 << 16), + DIRTY_SHADERBLEND = (1 << 17), // Used only for in-shader blending. + DIRTY_UVSCALEOFFSET = (1 << 18), // this will be dirtied ALL THE TIME... maybe we'll need to do "last value with this shader compares" + DIRTY_TEXCLAMP = (1 << 19), + + DIRTY_DEPTHRANGE = (1 << 20), + + DIRTY_WORLDMATRIX = (1 << 21), + DIRTY_VIEWMATRIX = (1 << 22), // Maybe we'll fold this into projmatrix eventually + DIRTY_TEXMATRIX = (1 << 23), + DIRTY_BONEMATRIX0 = (1 << 24), + DIRTY_BONEMATRIX1 = (1 << 25), + DIRTY_BONEMATRIX2 = (1 << 26), + DIRTY_BONEMATRIX3 = (1 << 27), + DIRTY_BONEMATRIX4 = (1 << 28), + DIRTY_BONEMATRIX5 = (1 << 29), + DIRTY_BONEMATRIX6 = (1 << 30), + DIRTY_BONEMATRIX7 = (1 << 31), + + DIRTY_ALL = 0xFFFFFFFF +}; + +struct UB_VS_TransformCommon { + float proj[16]; + float view[16]; + float world[16]; + float tex[16]; // not that common, may want to break out + float uvScaleOffset[4]; + float depthRange[4]; + float fogCoef[4]; + float matAmbient[4]; +}; + +static const char *ub_vs_transformCommonStr = +R"(matrix4x4 proj; + matrix4x4 view; + matrix4x4 world; + matrix4x4 tex; + vec4 uvScaleOffset; + vec4 depthRange; + vec2 fogCoef; + vec4 matAmbient; +)"; + +struct UB_VS_Lights { + float lpos[4][4]; + float ldir[4][4]; + float latt[4][4]; + float lightAngle[4][4]; // TODO: Merge with lightSpotCoef, use .xy + float lightSpotCoef[4][4]; + float lightAmbient[4][4]; + float lightDiffuse[4][4]; + float lightSpecular[4][4]; +}; + +static const char *ub_vs_lightsStr = +R"(vec3 lpos[4]; + vec3 ldir[4]; + vec3 latt[4]; + float lightAngle[4]; + float lightSpotCoef[4]; + vec3 lightAmbient[4]; + vec3 lightDiffuse[4]; + vec3 lightSpecular[4]; +)"; + +struct UB_VS_LightGlobal { + float ambientColor[4]; + float materialDiffuse[4]; + float materialSpecular[4]; + float materialEmissive[4]; +}; + +static const char *ub_vs_lightsGlobalStr = +R"(vec3 ambientColor; + vec3 materialDiffuse; + vec4 materialSpecular; + vec3 materialEmissive; +)"; + +struct UB_VS_Bones { + float bones[8][16]; +}; + +static const char *ub_vs_bonesStr = +R"(matrix4x4 bone[8]; +)"; + +// Let's not bother splitting this, we'll just upload the lot for every draw call. +struct UB_FS_All { + float fogColor[4]; + float texEnvColor[4]; + float alphaColorRef[4]; + float colorTestMask[4]; + float stencilReplace[4]; // only first float used + float blendFixA[4]; + float blendFixB[4]; + float texClamp[4]; + float texClampOffset[4]; +}; + +static const char *ub_fs_allStr = +R"( + vec3 fogColor; + vec3 texenv; + vec4 alphaColorRef; + vec3 colorTestMask; + float stencilReplace; + vec3 blendFixA; + vec3 blendFixB; + vec4 texClamp; + vec2 texClampOffset; +)"; + +class VulkanFragmentShader { +public: + VulkanFragmentShader(VkDevice device, ShaderID id, const char *code, bool useHWTransform); + ~VulkanFragmentShader(); + + const std::string &source() const { return source_; } + + bool Failed() const { return failed_; } + bool UseHWTransform() const { return useHWTransform_; } + + std::string GetShaderString(DebugShaderStringType type) const; + +protected: + VkShaderModule module_; + + VkDevice device_; + std::string source_; + bool failed_; + bool useHWTransform_; + ShaderID id_; +}; + +class VulkanVertexShader { +public: + VulkanVertexShader(VkDevice device, ShaderID id, const char *code, int vertType, bool useHWTransform); + ~VulkanVertexShader(); + + const std::string &source() const { return source_; } + + bool Failed() const { return failed_; } + bool UseHWTransform() const { return useHWTransform_; } + + std::string GetShaderString(DebugShaderStringType type) const; + +protected: + VkShaderModule module_; + + VkDevice device_; + std::string source_; + bool failed_; + bool useHWTransform_; + ShaderID id_; +}; + +class ShaderManagerVulkan { +public: + ShaderManagerVulkan(VkDevice device); + ~ShaderManagerVulkan(); + + void ClearCache(bool deleteThem); // TODO: deleteThem currently not respected + void GetShaders(int prim, u32 vertType, VulkanVertexShader **vshader, VulkanFragmentShader **fshader); + + void DirtyShader(); + void DirtyUniform(u32 what) { + globalDirty_ |= what; + } + void DirtyLastShader(); + + int NumVertexShaders() const { return (int)vsCache_.size(); } + int NumFragmentShaders() const { return (int)fsCache_.size(); } + + std::vector DebugGetShaderIDs(DebugShaderType type); + std::string DebugGetShaderString(std::string id, DebugShaderType type, DebugShaderStringType stringType); + +private: + void PSUpdateUniforms(int dirtyUniforms); + void VSUpdateUniforms(int dirtyUniforms); + + void Clear(); + + VkDevice device_; + + u32 globalDirty_; + char *codeBuffer_; + + // Uniform block scratchpad. These (the relevant ones) are copied to the current pushbuffer at draw time. + UB_VS_TransformCommon ub_transformCommon; + UB_VS_LightGlobal ub_lightGlobal; + UB_VS_Lights ub_lights; + UB_VS_Bones ub_bones; + UB_FS_All ub_fragment; + + typedef std::map FSCache; + FSCache fsCache_; + + typedef std::map VSCache; + VSCache vsCache_; + + VulkanFragmentShader *lastFShader_; + VulkanVertexShader *lastVShader_; + + ShaderID lastFSID_; + ShaderID lastVSID_; +}; diff --git a/GPU/Vulkan/StateMappingVulkan.cpp b/GPU/Vulkan/StateMappingVulkan.cpp new file mode 100644 index 0000000000..9515c8b088 --- /dev/null +++ b/GPU/Vulkan/StateMappingVulkan.cpp @@ -0,0 +1,314 @@ +// Copyright (c) 2012- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#define VK_PROTOTYPES +#include "ext/vulkan/vulkan.h" + +#include "GPU/Math3D.h" +#include "GPU/GPUState.h" +#include "GPU/ge_constants.h" +#include "GPU/Common/GPUStateUtils.h" +#include "Core/System.h" +#include "Core/Config.h" +#include "Core/Reporting.h" +//#include "GPU/Vulkan/StateMappingVulkan.h" +#include "GPU/Vulkan/GPU_Vulkan.h" +#include "GPU/Vulkan/PipelineManagerVulkan.h" +#include "GPU/Vulkan/TextureCacheVulkan.h" +#include "GPU/Vulkan/FramebufferVulkan.h" +//#include "GPU/Vulkan/PixelShaderGeneratorVulkan.h" + +static const VkBlendFactor vkBlendFactorLookup[(size_t)BlendFactor::COUNT] = { + VK_BLEND_FACTOR_ZERO, + VK_BLEND_FACTOR_ONE, + VK_BLEND_FACTOR_SRC_COLOR, + VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR, + 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, + VK_BLEND_FACTOR_CONSTANT_COLOR, + VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR, + VK_BLEND_FACTOR_CONSTANT_ALPHA, + VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA, + VK_BLEND_FACTOR_SRC1_COLOR, + VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR, + VK_BLEND_FACTOR_MAX_ENUM, +}; + +static const VkBlendOp vkBlendEqLookup[(size_t)BlendEq::COUNT] = { + VK_BLEND_OP_ADD, + VK_BLEND_OP_SUBTRACT, + VK_BLEND_OP_REVERSE_SUBTRACT, + VK_BLEND_OP_MIN, + VK_BLEND_OP_MAX, +}; + +static const VkCullModeFlagBits cullingMode[] = { + VK_CULL_MODE_BACK_BIT, + VK_CULL_MODE_FRONT_BIT, +}; + +static const VkCompareOp compareOps[] = { + VK_COMPARE_OP_NEVER, + VK_COMPARE_OP_ALWAYS, + VK_COMPARE_OP_EQUAL, + VK_COMPARE_OP_NOT_EQUAL, + VK_COMPARE_OP_LESS, + VK_COMPARE_OP_LESS_OR_EQUAL, + VK_COMPARE_OP_GREATER, + VK_COMPARE_OP_GREATER_OR_EQUAL, +}; + +static const VkStencilOp stencilOps[] = { + VK_STENCIL_OP_KEEP, + VK_STENCIL_OP_ZERO, + VK_STENCIL_OP_REPLACE, + VK_STENCIL_OP_INVERT, + VK_STENCIL_OP_INCREMENT_AND_CLAMP, + VK_STENCIL_OP_DECREMENT_AND_CLAMP, + VK_STENCIL_OP_KEEP, // reserved + VK_STENCIL_OP_KEEP, // reserved +}; + +struct VulkanDynamicState { + VkViewport viewport; + VkRect2D scissor; + bool useBlendColor; + uint32_t blendColor; + bool useStencil; + uint8_t stencilRef; + uint8_t stencilWriteMask; + uint8_t stencilCompareMask; +}; + +bool ApplyShaderBlending() { + return false; +} + +void ResetShaderBlending() { + // +} + +// TODO: Do this more progressively. No need to compute the entire state if the entire state hasn't changed. +// In Vulkan, we simply collect all the state together into a "pipeline key" - we don't actually set any state here +// (the caller is responsible for setting the little dynamic state that is supported, dynState). +void ConvertStateToVulkanKey(FramebufferManagerVulkan &fbManager, int prim, VulkanPipelineRasterStateKey &key, VulkanDynamicState &dynState) { + // Unfortunately, this isn't implemented yet. + gstate_c.allowShaderBlend = false; + + // Set blend - unless we need to do it in the shader. + GenericBlendState blendState; + ConvertBlendState(blendState, gstate_c.allowShaderBlend); + + bool useBufferedRendering = g_Config.iRenderingMode != FB_NON_BUFFERED_MODE; + + ViewportAndScissor vpAndScissor; + ConvertViewportAndScissor(useBufferedRendering, + fbManager.GetRenderWidth(), fbManager.GetRenderHeight(), + fbManager.GetTargetBufferWidth(), fbManager.GetTargetBufferHeight(), + vpAndScissor); + + if (blendState.applyShaderBlending) { + if (ApplyShaderBlending()) { + // We may still want to do something about stencil -> alpha. + ApplyStencilReplaceAndLogicOp(blendState.replaceAlphaWithStencil, blendState); + } else { + // Until next time, force it off. + ResetShaderBlending(); + gstate_c.allowShaderBlend = false; + } + } else if (blendState.resetShaderBlending) { + ResetShaderBlending(); + } + + if (blendState.enabled) { + key.blendEnable = true; + key.blendOpColor = vkBlendEqLookup[(size_t)blendState.eqColor]; + key.blendOpAlpha = vkBlendEqLookup[(size_t)blendState.eqAlpha]; + key.srcColor = vkBlendFactorLookup[(size_t)blendState.srcColor]; + key.srcAlpha = vkBlendFactorLookup[(size_t)blendState.srcAlpha]; + key.destColor = vkBlendFactorLookup[(size_t)blendState.dstColor]; + key.destAlpha = vkBlendFactorLookup[(size_t)blendState.dstAlpha]; + if (blendState.dirtyShaderBlend) { + //shaderManager_->DirtyUniform(DIRTY_SHADERBLEND); + } + dynState.useBlendColor = blendState.useBlendColor; + if (blendState.useBlendColor) { + dynState.blendColor = blendState.blendColor; + } + } else { + key.blendEnable = false; + dynState.useBlendColor = false; + } + + dynState.useStencil = false; + + // Set ColorMask/Stencil/Depth + if (gstate.isModeClear()) { + key.cullMode = VK_CULL_MODE_NONE; + + key.depthTestEnable = true; + key.depthCompareOp = VK_COMPARE_OP_ALWAYS; + key.depthWriteEnable = gstate.isClearModeDepthMask(); + if (gstate.isClearModeDepthMask()) { + // framebufferManager_->SetDepthUpdated(); + } + + // Color Test + bool colorMask = gstate.isClearModeColorMask(); + bool alphaMask = gstate.isClearModeAlphaMask(); + key.colorWriteMask = (colorMask ? (VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_A_BIT) : 0) | (alphaMask ? VK_COLOR_COMPONENT_A_BIT : 0); + + // Stencil Test + if (alphaMask) { + key.stencilTestEnable = true; + key.stencilCompareOp = VK_COMPARE_OP_ALWAYS; + key.stencilPassOp = VK_STENCIL_OP_REPLACE; + key.stencilFailOp = VK_STENCIL_OP_REPLACE; + key.stencilDepthFailOp = VK_STENCIL_OP_REPLACE; + // TODO: Are these right? + dynState.useStencil = true; + dynState.stencilRef = 0xFF; + dynState.stencilCompareMask = 0xFF; + dynState.stencilWriteMask = 0xFF; + } else { + key.stencilTestEnable = false; + } + + } else { + // Set cull + bool wantCull = !gstate.isModeThrough() && prim != GE_PRIM_RECTANGLES && gstate.isCullEnabled(); + key.cullMode = wantCull ? (gstate.getCullMode() ? VK_CULL_MODE_FRONT_BIT : VK_CULL_MODE_BACK_BIT) : VK_CULL_MODE_NONE; + + // Depth Test + if (gstate.isDepthTestEnabled()) { + key.depthTestEnable = true; + key.depthCompareOp = compareOps[gstate.getDepthTestFunction()]; + key.depthWriteEnable = gstate.isDepthWriteEnabled(); + if (gstate.isDepthWriteEnabled()) { + // framebufferManager_->SetDepthUpdated(); + } + } else { + key.depthTestEnable = false; + } + + // PSP color/alpha mask is per bit but we can only support per byte. + // But let's do that, at least. And let's try a threshold. + bool rmask = (gstate.pmskc & 0xFF) < 128; + bool gmask = ((gstate.pmskc >> 8) & 0xFF) < 128; + bool bmask = ((gstate.pmskc >> 16) & 0xFF) < 128; + bool amask = (gstate.pmska & 0xFF) < 128; + + u8 abits = (gstate.pmska >> 0) & 0xFF; +#ifndef MOBILE_DEVICE + u8 rbits = (gstate.pmskc >> 0) & 0xFF; + u8 gbits = (gstate.pmskc >> 8) & 0xFF; + u8 bbits = (gstate.pmskc >> 16) & 0xFF; + if ((rbits != 0 && rbits != 0xFF) || (gbits != 0 && gbits != 0xFF) || (bbits != 0 && bbits != 0xFF)) { + WARN_LOG_REPORT_ONCE(rgbmask, G3D, "Unsupported RGB mask: r=%02x g=%02x b=%02x", rbits, gbits, bbits); + } + if (abits != 0 && abits != 0xFF) { + // The stencil part of the mask is supported. + WARN_LOG_REPORT_ONCE(amask, G3D, "Unsupported alpha/stencil mask: %02x", abits); + } +#endif + + // Let's not write to alpha if stencil isn't enabled. + if (!gstate.isStencilTestEnabled()) { + amask = false; + } else { + // If the stencil type is set to KEEP, we shouldn't write to the stencil/alpha channel. + if (ReplaceAlphaWithStencilType() == STENCIL_VALUE_KEEP) { + amask = false; + } + } + + key.colorWriteMask = (rmask ? VK_COLOR_COMPONENT_R_BIT : 0) | (gmask ? VK_COLOR_COMPONENT_G_BIT : 0) | (bmask ? VK_COLOR_COMPONENT_B_BIT : 0) | (amask ? VK_COLOR_COMPONENT_A_BIT : 0); + + // Stencil Test + if (gstate.isStencilTestEnabled()) { + key.stencilTestEnable = true; + key.stencilCompareOp = compareOps[gstate.getStencilTestFunction()]; + dynState.stencilRef = gstate.getStencilTestRef(); + dynState.stencilCompareMask = gstate.getStencilTestMask(); + key.stencilFailOp = stencilOps[gstate.getStencilOpSFail()]; // stencil fail + key.stencilDepthFailOp = stencilOps[gstate.getStencilOpZFail()]; // depth fail + key.stencilPassOp = stencilOps[gstate.getStencilOpZPass()]; // depth pass + dynState.stencilWriteMask = ~abits; + } else { + key.stencilTestEnable = false; + } + } + + VkViewport &vp = dynState.viewport; + vp.x = vpAndScissor.viewportX; + vp.y = vpAndScissor.viewportY; + vp.width = vpAndScissor.viewportW; + vp.height = vpAndScissor.viewportH; + vp.minDepth = vpAndScissor.depthRangeMin; + vp.maxDepth = vpAndScissor.depthRangeMax; + if (vpAndScissor.dirtyProj) { + // shaderManager_->DirtyUniform(DIRTY_PROJMATRIX); + } + + VkRect2D &scissor = dynState.scissor; + scissor.offset.x = vpAndScissor.scissorX; + scissor.offset.y = vpAndScissor.scissorY; + scissor.extent.width = vpAndScissor.scissorW; + scissor.extent.height = vpAndScissor.scissorH; + + float depthMin = vpAndScissor.depthRangeMin; + float depthMax = vpAndScissor.depthRangeMax; + + if (!gstate.isModeThrough()) { + // Direct3D can't handle negative depth ranges, so we fix it in the projection matrix. + if (gstate_c.vpDepthScale != depthMax - depthMin) { + gstate_c.vpDepthScale = depthMax - depthMin; + vpAndScissor.dirtyProj = true; + } + if (depthMin > depthMax) { + std::swap(depthMin, depthMax); + } + if (depthMin < 0.0f) depthMin = 0.0f; + if (depthMax > 1.0f) depthMax = 1.0f; + } +} + +//void DrawEngineVulkan::ApplyDrawStateLate() { + /* + // At this point, we know if the vertices are full alpha or not. + // TODO: Set the nearest/linear here (since we correctly know if alpha/color tests are needed)? + if (!gstate.isModeClear()) { + // TODO: Test texture? + + textureCache_->ApplyTexture(); + + if (fboTexNeedBind_) { + // Note that this is positions, not UVs, that we need the copy from. + framebufferManager_->BindFramebufferColor(1, nullptr, BINDFBCOLOR_MAY_COPY); + // If we are rendering at a higher resolution, linear is probably best for the dest color. + pD3Ddevice->SetSamplerState(1, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); + pD3Ddevice->SetSamplerState(1, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); + fboTexBound_ = true; + fboTexNeedBind_ = false; + } + } + */ +//} diff --git a/GPU/Vulkan/TextureCacheVulkan.h b/GPU/Vulkan/TextureCacheVulkan.h new file mode 100644 index 0000000000..fac5cde8c9 --- /dev/null +++ b/GPU/Vulkan/TextureCacheVulkan.h @@ -0,0 +1,42 @@ +// Copyright (c) 2015- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#pragma once + +#include "GPU/Common/TextureCacheCommon.h" +#include "GPU/GPUState.h" + +class TextureCacheVulkan : public TextureCacheCommon { +public: + bool SetOffsetTexture(u32 offset) override { + return false; + } + bool DecodeTexture(u8 *dest, const GPUgstate &state) { + return false; + } + + bool AttachFramebuffer(TexCacheEntry *entry, u32 address, VirtualFramebuffer *framebuffer, u32 texaddrOffset = 0) override { + return false; + } + void DetachFramebuffer(TexCacheEntry *entry, u32 address, VirtualFramebuffer *framebuffer) override { + + } + + void DownloadFramebufferForClut(u32 clutAddr, u32 bytes) override { + + } +}; diff --git a/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp b/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp new file mode 100644 index 0000000000..f12f104a8e --- /dev/null +++ b/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp @@ -0,0 +1,618 @@ +// Copyright (c) 2012- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#include +#include +#include + +#include "gfx_es2/gpu_features.h" + +#if defined(_WIN32) && defined(_DEBUG) +#include "Common/CommonWindows.h" +#endif + +#include "base/stringutil.h" +#include "GPU/ge_constants.h" +#include "GPU/GPUState.h" +#include "GPU/Common/ShaderId.h" +#include "GPU/Common/VertexDecoderCommon.h" +#include "GPU/Vulkan/VertexShaderGeneratorVulkan.h" +#include "GPU/Vulkan/PipelineManagerVulkan.h" + +// "Varying" layout - must match fragment shader +// color0 = 0 +// color1 = 1 +// texcoord = 2 +// fog = 3 + + + + +// SDL 1.2 on Apple does not have support for OpenGL 3 and hence needs +// special treatment in the shader generator. +#ifdef __APPLE__ +#define FORCE_OPENGL_2_0 +#endif + +#undef WRITE + +#define WRITE p+=sprintf + +static const char * const boneWeightDecl[9] = { + "#ERROR#", + "layout(location = 0) in mediump float w1;\n", + "layout(location = 0) in mediump vec2 w1;\n", + "layout(location = 0) in mediump vec3 w1;\n", + "layout(location = 0) in mediump vec4 w1;\n", + "layout(location = 0) in mediump vec4 w1;\nin mediump float w2;\n", + "layout(location = 0) in mediump vec4 w1;\nin mediump vec2 w2;\n", + "layout(location = 0) in mediump vec4 w1;\nin mediump vec3 w2;\n", + "layout(location = 0) in mediump vec4 w1, w2;\n", +}; + +enum DoLightComputation { + LIGHT_OFF, + LIGHT_SHADE, + LIGHT_FULL, +}; + + +// Depth range and viewport +// +// After the multiplication with the projection matrix, we have a 4D vector in clip space. +// In OpenGL, Z is from -1 to 1, while in D3D, Z is from 0 to 1. +// PSP appears to use the OpenGL convention. As Z is from -1 to 1, and the viewport is represented +// by a center and a scale, to find the final Z value, all we need to do is to multiply by ZScale and +// add ZCenter - these are properly scaled to directly give a Z value in [0, 65535]. +// +// z = vec.z * ViewportZScale + ViewportZCenter; +// +// That will give us the final value between 0 and 65535, which we can simply floor to simulate +// the limited precision of the PSP's depth buffer. Then we convert it back: +// z = floor(z); +// +// vec.z = (z - ViewportZCenter) / ViewportZScale; +// +// Now, the regular machinery will take over and do the calculation again. +// +// All this above is for full transform mode. +// In through mode, the Z coordinate just goes straight through and there is no perspective division. +// We simulate this of course with pretty much an identity matrix. Rounding Z becomes very easy. +// +// TODO: Skip all this if we can actually get a 16-bit depth buffer along with stencil, which +// is a bit of a rare configuration, although quite common on mobile. + +bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { + char *p = buffer; + + // #define USE_FOR_LOOP + + bool highpFog = false; + bool highpTexcoord = false; + + const char *attribute = "in"; + const char *varying = "out"; + + bool isModeThrough = id.Bit(VS_BIT_IS_THROUGH); + bool lmode = id.Bit(VS_BIT_LMODE) && !isModeThrough; // TODO: Different expression than in shaderIDgen + bool doTexture = id.Bit(VS_BIT_DO_TEXTURE); + bool doTextureProjection = id.Bit(VS_BIT_DO_TEXTURE_PROJ); + + GETexMapMode uvGenMode = static_cast(id.Bits(VS_BIT_UVGEN_MODE, 2)); + + // this is only valid for some settings of uvGenMode + GETexProjMapMode uvProjMode = static_cast(id.Bits(VS_BIT_UVPROJ_MODE, 2)); + bool doShadeMapping = uvGenMode == GE_TEXMAP_ENVIRONMENT_MAP; + bool doFlatShading = id.Bit(VS_BIT_FLATSHADE); + + bool useHWTransform = id.Bit(VS_BIT_USE_HW_TRANSFORM); + bool hasColor = id.Bit(VS_BIT_HAS_COLOR) || !useHWTransform; + bool hasNormal = id.Bit(VS_BIT_HAS_NORMAL) && useHWTransform; + bool hasTexcoord = id.Bit(VS_BIT_HAS_TEXCOORD) || !useHWTransform; + bool enableFog = id.Bit(VS_BIT_ENABLE_FOG); + bool throughmode = id.Bit(VS_BIT_IS_THROUGH); + bool flipNormal = id.Bit(VS_BIT_NORM_REVERSE); + int ls0 = id.Bits(VS_BIT_LS0, 2); + int ls1 = id.Bits(VS_BIT_LS1, 2); + bool enableBones = id.Bit(VS_BIT_ENABLE_BONES); + bool enableLighting = id.Bit(VS_BIT_LIGHTING_ENABLE); + int matUpdate = id.Bits(VS_BIT_MATERIAL_UPDATE, 3); + + const char *shading = doFlatShading ? "flat " : ""; + + DoLightComputation doLight[4] = { LIGHT_OFF, LIGHT_OFF, LIGHT_OFF, LIGHT_OFF }; + if (useHWTransform) { + int shadeLight0 = doShadeMapping ? ls0 : -1; + int shadeLight1 = doShadeMapping ? ls1 : -1; + for (int i = 0; i < 4; i++) { + if (i == shadeLight0 || i == shadeLight1) + doLight[i] = LIGHT_SHADE; + if (id.Bit(VS_BIT_LIGHTING_ENABLE) && id.Bit(VS_BIT_LIGHT0_ENABLE + i)) + doLight[i] = LIGHT_FULL; + } + } + + int numBoneWeights = 0; + int boneWeightScale = id.Bits(VS_BIT_WEIGHT_FMTSCALE, 2); + if (enableBones) { + numBoneWeights = 1 + id.Bits(VS_BIT_BONES, 3); + WRITE(p, "%s", boneWeightDecl[numBoneWeights]); + } + int texFmtScale = id.Bits(VS_BIT_TEXCOORD_FMTSCALE, 2); + + if (useHWTransform) + WRITE(p, "layout (location = %d) in vec3 position;\n", PspAttributeLocation::POSITION); + else + WRITE(p, "layout (location = %d) vec4 position;\n", PspAttributeLocation::POSITION); // need to pass the fog coord in w + + if (useHWTransform && hasNormal) + WRITE(p, "layout (location = %d) mediump vec3 normal;\n", PspAttributeLocation::NORMAL); + + if (doTexture && hasTexcoord) { + if (!useHWTransform && doTextureProjection && !throughmode) + WRITE(p, "layout (location = %d) in vec3 texcoord;\n", PspAttributeLocation::TEXCOORD); + else + WRITE(p, "layout (location = %d) in vec2 texcoord;\n", PspAttributeLocation::TEXCOORD); + } + if (hasColor) { + WRITE(p, "layout (location = %d) lowp vec4 color0;\n", PspAttributeLocation::COLOR0); + if (lmode && !useHWTransform) // only software transform supplies color1 as vertex data + WRITE(p, "layout (location = %d) lowp vec3 color1;\n", PspAttributeLocation::COLOR0); + } + + // The uniforms are passed in as three "clumps" that may or may not be present. + // We will memcpy the parts into place in a big buffer so we can be quite dynamic about what parts + // are present and what parts aren't, but we will not be ultra detailed about it. + +// WRITE(p, ) + + + if (isModeThrough) { + WRITE(p, "uniform mat4 u_proj_through;\n"); + } else { + WRITE(p, "uniform mat4 u_proj;\n"); + // Add all the uniforms we'll need to transform properly. + } + + bool prescale = false; + + if (useHWTransform) { + // When transforming by hardware, we need a great deal more uniforms... + WRITE(p, "uniform mat4 u_world;\n"); + WRITE(p, "uniform mat4 u_view;\n"); + if (doTextureProjection) + WRITE(p, "uniform mediump mat4 u_texmtx;\n"); + if (enableBones) { +#ifdef USE_BONE_ARRAY + WRITE(p, "uniform mediump mat4 u_bone[%i];\n", numBoneWeights); +#else + for (int i = 0; i < numBoneWeights; i++) { + WRITE(p, "uniform mat4 u_bone%i;\n", i); + } +#endif + } + if (doTexture && (!prescale || uvGenMode == GE_TEXMAP_ENVIRONMENT_MAP || uvGenMode == GE_TEXMAP_TEXTURE_MATRIX)) { + WRITE(p, "uniform vec4 u_uvscaleoffset;\n"); + } + for (int i = 0; i < 4; i++) { + if (doLight[i] != LIGHT_OFF) { + // This is needed for shade mapping + WRITE(p, "uniform vec3 u_lightpos%i;\n", i); + } + if (doLight[i] == LIGHT_FULL) { + GELightType type = static_cast(id.Bits(VS_BIT_LIGHT0_TYPE + 4 * i, 2)); + GELightComputation comp = static_cast(id.Bits(VS_BIT_LIGHT0_COMP + 4 * i, 2)); + + if (type != GE_LIGHTTYPE_DIRECTIONAL) + WRITE(p, "uniform mediump vec3 u_lightatt%i;\n", i); + + if (type == GE_LIGHTTYPE_SPOT || type == GE_LIGHTTYPE_UNKNOWN) { + WRITE(p, "uniform mediump vec3 u_lightdir%i;\n", i); + WRITE(p, "uniform mediump float u_lightangle%i;\n", i); + WRITE(p, "uniform mediump float u_lightspotCoef%i;\n", i); + } + WRITE(p, "uniform lowp vec3 u_lightambient%i;\n", i); + WRITE(p, "uniform lowp vec3 u_lightdiffuse%i;\n", i); + + if (comp != GE_LIGHTCOMP_ONLYDIFFUSE) { + WRITE(p, "uniform lowp vec3 u_lightspecular%i;\n", i); + } + } + } + if (enableLighting) { + WRITE(p, "uniform lowp vec4 u_ambient;\n"); + if ((matUpdate & 2) == 0 || !hasColor) + WRITE(p, "uniform lowp vec3 u_matdiffuse;\n"); + WRITE(p, "uniform lowp vec4 u_matspecular;\n"); // Specular coef is contained in alpha + WRITE(p, "uniform lowp vec3 u_matemissive;\n"); + } + } + + if (useHWTransform || !hasColor) + WRITE(p, "uniform lowp vec4 u_matambientalpha;\n"); // matambient + matalpha + + if (enableFog) { + WRITE(p, "uniform highp vec2 u_fogcoef;\n"); + } + + if (!isModeThrough && gstate_c.Supports(GPU_ROUND_DEPTH_TO_16BIT)) { + WRITE(p, "uniform highp vec4 u_depthRange;\n"); + } + + WRITE(p, "layout (location = 1) %s out lowp vec4 v_color0;\n", shading); + if (lmode) { + WRITE(p, "layout (location = 2) %s out lowp vec3 v_color1;\n", shading); + } + + if (doTexture) { + if (doTextureProjection) { + WRITE(p, "layout (location = 0) %s out vec3 v_texcoord;\n", highpTexcoord ? "highp" : "mediump"); + } else { + WRITE(p, "layout (location = 0) %s out vec2 v_texcoord;\n", highpTexcoord ? "highp" : "mediump"); + } + } + + if (enableFog) { + // See the fragment shader generator + WRITE(p, "layout (location = 3) %s out float v_fogdepth;\n", highpFog ? "highp" : "mediump"); + } + + // See comment above this function (GenerateVertexShader). + if (!isModeThrough && gstate_c.Supports(GPU_ROUND_DEPTH_TO_16BIT)) { + // Apply the projection and viewport to get the Z buffer value, floor to integer, undo the viewport and projection. + WRITE(p, "\nvec4 depthRoundZVP(vec4 v) {\n"); + WRITE(p, " float z = v.z / v.w;\n"); + WRITE(p, " z = z * u_depthRange.x + u_depthRange.y;\n"); + WRITE(p, " z = floor(z);\n"); + WRITE(p, " z = (z - u_depthRange.z) * u_depthRange.w;\n"); + WRITE(p, " return vec4(v.x, v.y, z * v.w, v.w);\n"); + WRITE(p, "}\n\n"); + } + + WRITE(p, "void main() {\n"); + + if (!useHWTransform) { + // Simple pass-through of vertex data to fragment shader + if (doTexture) { + if (throughmode && doTextureProjection) { + WRITE(p, " v_texcoord = vec3(texcoord, 1.0);\n"); + } else { + WRITE(p, " v_texcoord = texcoord;\n"); + } + } + if (hasColor) { + WRITE(p, " v_color0 = color0;\n"); + if (lmode) + WRITE(p, " v_color1 = color1;\n"); + } else { + WRITE(p, " v_color0 = u_matambientalpha;\n"); + if (lmode) + WRITE(p, " v_color1 = vec3(0.0);\n"); + } + if (enableFog) { + WRITE(p, " v_fogdepth = position.w;\n"); + } + if (isModeThrough) { + WRITE(p, " gl_Position = u_proj_through * vec4(position.xyz, 1.0);\n"); + } else { + // The viewport is used in this case, so need to compensate for that. + if (gstate_c.Supports(GPU_ROUND_DEPTH_TO_16BIT)) { + WRITE(p, " gl_Position = depthRoundZVP(u_proj * vec4(position.xyz, 1.0));\n"); + } else { + WRITE(p, " gl_Position = u_proj * vec4(position.xyz, 1.0);\n"); + } + } + } else { + // Step 1: World Transform / Skinning + if (!enableBones) { + // No skinning, just standard T&L. + WRITE(p, " vec3 worldpos = (u_world * vec4(position.xyz, 1.0)).xyz;\n"); + if (hasNormal) + WRITE(p, " mediump vec3 worldnormal = normalize((u_world * vec4(%snormal, 0.0)).xyz);\n", flipNormal ? "-" : ""); + else + WRITE(p, " mediump vec3 worldnormal = vec3(0.0, 0.0, 1.0);\n"); + } else { + static const char *rescale[4] = { "", " * 1.9921875", " * 1.999969482421875", "" }; // 2*127.5f/128.f, 2*32767.5f/32768.f, 1.0f}; + const char *factor = rescale[boneWeightScale]; + + static const char * const boneWeightAttr[8] = { + "w1.x", "w1.y", "w1.z", "w1.w", + "w2.x", "w2.y", "w2.z", "w2.w", + }; + +#if defined(USE_FOR_LOOP) && defined(USE_BONE_ARRAY) + + // To loop through the weights, we unfortunately need to put them in a float array. + // GLSL ES sucks - no way to directly initialize an array! + switch (numBoneWeights) { + case 1: WRITE(p, " float w[1]; w[0] = w1;\n"); break; + case 2: WRITE(p, " float w[2]; w[0] = w1.x; w[1] = w1.y;\n"); break; + case 3: WRITE(p, " float w[3]; w[0] = w1.x; w[1] = w1.y; w[2] = w1.z;\n"); break; + case 4: WRITE(p, " float w[4]; w[0] = w1.x; w[1] = w1.y; w[2] = w1.z; w[3] = w1.w;\n"); break; + case 5: WRITE(p, " float w[5]; w[0] = w1.x; w[1] = w1.y; w[2] = w1.z; w[3] = w1.w; w[4] = w2;\n"); break; + case 6: WRITE(p, " float w[6]; w[0] = w1.x; w[1] = w1.y; w[2] = w1.z; w[3] = w1.w; w[4] = w2.x; w[5] = w2.y;\n"); break; + case 7: WRITE(p, " float w[7]; w[0] = w1.x; w[1] = w1.y; w[2] = w1.z; w[3] = w1.w; w[4] = w2.x; w[5] = w2.y; w[6] = w2.z;\n"); break; + case 8: WRITE(p, " float w[8]; w[0] = w1.x; w[1] = w1.y; w[2] = w1.z; w[3] = w1.w; w[4] = w2.x; w[5] = w2.y; w[6] = w2.z; w[7] = w2.w;\n"); break; + } + + WRITE(p, " mat4 skinMatrix = w[0] * u_bone[0];\n"); + if (numBoneWeights > 1) { + WRITE(p, " for (int i = 1; i < %i; i++) {\n", numBoneWeights); + WRITE(p, " skinMatrix += w[i] * u_bone[i];\n"); + WRITE(p, " }\n"); + } + +#else + +#ifdef USE_BONE_ARRAY + if (numBoneWeights == 1) + WRITE(p, " mat4 skinMatrix = w1 * u_bone[0]"); + else + WRITE(p, " mat4 skinMatrix = w1.x * u_bone[0]"); + for (int i = 1; i < numBoneWeights; i++) { + const char *weightAttr = boneWeightAttr[i]; + // workaround for "cant do .x of scalar" issue + if (numBoneWeights == 1 && i == 0) weightAttr = "w1"; + if (numBoneWeights == 5 && i == 4) weightAttr = "w2"; + WRITE(p, " + %s * u_bone[%i]", weightAttr, i); + } +#else + // Uncomment this to screw up bone shaders to check the vertex shader software fallback + // WRITE(p, "THIS SHOULD ERROR! #error"); + if (numBoneWeights == 1) + WRITE(p, " mat4 skinMatrix = w1 * u_bone0"); + else + WRITE(p, " mat4 skinMatrix = w1.x * u_bone0"); + for (int i = 1; i < numBoneWeights; i++) { + const char *weightAttr = boneWeightAttr[i]; + // workaround for "cant do .x of scalar" issue + if (numBoneWeights == 1 && i == 0) weightAttr = "w1"; + if (numBoneWeights == 5 && i == 4) weightAttr = "w2"; + WRITE(p, " + %s * u_bone%i", weightAttr, i); + } +#endif + +#endif + + WRITE(p, ";\n"); + + // Trying to simplify this results in bugs in LBP... + WRITE(p, " vec3 skinnedpos = (skinMatrix * vec4(position, 1.0)).xyz %s;\n", factor); + WRITE(p, " vec3 worldpos = (u_world * vec4(skinnedpos, 1.0)).xyz;\n"); + + if (hasNormal) { + WRITE(p, " mediump vec3 skinnednormal = (skinMatrix * vec4(%snormal, 0.0)).xyz %s;\n", flipNormal ? "-" : "", factor); + } else { + WRITE(p, " mediump vec3 skinnednormal = (skinMatrix * vec4(0.0, 0.0, %s1.0, 0.0)).xyz %s;\n", flipNormal ? "-" : "", factor); + } + WRITE(p, " mediump vec3 worldnormal = normalize((u_world * vec4(skinnednormal, 0.0)).xyz);\n"); + } + + WRITE(p, " vec4 viewPos = u_view * vec4(worldpos, 1.0);\n"); + + // Final view and projection transforms. + if (gstate_c.Supports(GPU_ROUND_DEPTH_TO_16BIT)) { + WRITE(p, " gl_Position = depthRoundZVP(u_proj * viewPos);\n"); + } else { + WRITE(p, " gl_Position = u_proj * viewPos;\n"); + } + + // TODO: Declare variables for dots for shade mapping if needed. + + const char *ambientStr = (matUpdate & 1) && hasColor ? "color0" : "u_matambientalpha"; + const char *diffuseStr = (matUpdate & 2) && hasColor ? "color0.rgb" : "u_matdiffuse"; + const char *specularStr = (matUpdate & 4) && hasColor ? "color0.rgb" : "u_matspecular.rgb"; + + bool diffuseIsZero = true; + bool specularIsZero = true; + bool distanceNeeded = false; + + if (enableLighting) { + WRITE(p, " lowp vec4 lightSum0 = u_ambient * %s + vec4(u_matemissive, 0.0);\n", ambientStr); + + for (int i = 0; i < 4; i++) { + GELightType type = static_cast(id.Bits(VS_BIT_LIGHT0_TYPE + 4 * i, 2)); + GELightComputation comp = static_cast(id.Bits(VS_BIT_LIGHT0_COMP + 4 * i, 2)); + if (doLight[i] != LIGHT_FULL) + continue; + diffuseIsZero = false; + if (comp != GE_LIGHTCOMP_ONLYDIFFUSE) + specularIsZero = false; + if (type != GE_LIGHTTYPE_DIRECTIONAL) + distanceNeeded = true; + } + + if (!specularIsZero) { + WRITE(p, " lowp vec3 lightSum1 = vec3(0.0);\n"); + } + if (!diffuseIsZero) { + WRITE(p, " vec3 toLight;\n"); + WRITE(p, " lowp vec3 diffuse;\n"); + } + if (distanceNeeded) { + WRITE(p, " float distance;\n"); + WRITE(p, " lowp float lightScale;\n"); + } + } + + // Calculate lights if needed. If shade mapping is enabled, lights may need to be + // at least partially calculated. + for (int i = 0; i < 4; i++) { + if (doLight[i] != LIGHT_FULL) + continue; + + GELightType type = static_cast(id.Bits(VS_BIT_LIGHT0_TYPE + 4 * i, 2)); + GELightComputation comp = static_cast(id.Bits(VS_BIT_LIGHT0_COMP + 4 * i, 2)); + + if (type == GE_LIGHTTYPE_DIRECTIONAL) { + // We prenormalize light positions for directional lights. + WRITE(p, " toLight = u_lightpos%i;\n", i); + } else { + WRITE(p, " toLight = u_lightpos%i - worldpos;\n", i); + WRITE(p, " distance = length(toLight);\n"); + WRITE(p, " toLight /= distance;\n"); + } + + bool doSpecular = comp != GE_LIGHTCOMP_ONLYDIFFUSE; + bool poweredDiffuse = comp == GE_LIGHTCOMP_BOTHWITHPOWDIFFUSE; + + WRITE(p, " mediump float dot%i = max(dot(toLight, worldnormal), 0.0);\n", i); + if (poweredDiffuse) { + // pow(0.0, 0.0) may be undefined, but the PSP seems to treat it as 1.0. + // Seen in Tales of the World: Radiant Mythology (#2424.) + WRITE(p, " if (dot%i == 0.0 && u_matspecular.a == 0.0) {\n", i); + WRITE(p, " dot%i = 1.0;\n", i); + WRITE(p, " } else {\n"); + WRITE(p, " dot%i = pow(dot%i, u_matspecular.a);\n", i, i); + WRITE(p, " }\n"); + } + + const char *timesLightScale = " * lightScale"; + + // Attenuation + switch (type) { + case GE_LIGHTTYPE_DIRECTIONAL: + timesLightScale = ""; + break; + case GE_LIGHTTYPE_POINT: + WRITE(p, " lightScale = clamp(1.0 / dot(u_lightatt%i, vec3(1.0, distance, distance*distance)), 0.0, 1.0);\n", i); + break; + case GE_LIGHTTYPE_SPOT: + case GE_LIGHTTYPE_UNKNOWN: + WRITE(p, " lowp float angle%i = dot(normalize(u_lightdir%i), toLight);\n", i, i); + WRITE(p, " if (angle%i >= u_lightangle%i) {\n", i, i); + WRITE(p, " lightScale = clamp(1.0 / dot(u_lightatt%i, vec3(1.0, distance, distance*distance)), 0.0, 1.0) * pow(angle%i, u_lightspotCoef%i);\n", i, i, i); + WRITE(p, " } else {\n"); + WRITE(p, " lightScale = 0.0;\n"); + WRITE(p, " }\n"); + break; + default: + // ILLEGAL + break; + } + + WRITE(p, " diffuse = (u_lightdiffuse%i * %s) * dot%i;\n", i, diffuseStr, i); + if (doSpecular) { + WRITE(p, " dot%i = dot(normalize(toLight + vec3(0.0, 0.0, 1.0)), worldnormal);\n", i); + WRITE(p, " if (dot%i > 0.0)\n", i); + WRITE(p, " lightSum1 += u_lightspecular%i * %s * (pow(dot%i, u_matspecular.a) %s);\n", i, specularStr, i, timesLightScale); + } + WRITE(p, " lightSum0.rgb += (u_lightambient%i * %s.rgb + diffuse)%s;\n", i, ambientStr, timesLightScale); + } + + if (enableLighting) { + // Sum up ambient, emissive here. + if (lmode) { + WRITE(p, " v_color0 = clamp(lightSum0, 0.0, 1.0);\n"); + // v_color1 only exists when lmode = 1. + if (specularIsZero) { + WRITE(p, " v_color1 = vec3(0.0);\n"); + } else { + WRITE(p, " v_color1 = clamp(lightSum1, 0.0, 1.0);\n"); + } + } else { + if (specularIsZero) { + WRITE(p, " v_color0 = clamp(lightSum0, 0.0, 1.0);\n"); + } else { + WRITE(p, " v_color0 = clamp(clamp(lightSum0, 0.0, 1.0) + vec4(lightSum1, 0.0), 0.0, 1.0);\n"); + } + } + } else { + // Lighting doesn't affect color. + if (hasColor) { + WRITE(p, " v_color0 = color0;\n"); + } else { + WRITE(p, " v_color0 = u_matambientalpha;\n"); + } + if (lmode) + WRITE(p, " v_color1 = vec3(0.0);\n"); + } + + // Step 3: UV generation + if (doTexture) { + switch (uvGenMode) { + case GE_TEXMAP_TEXTURE_COORDS: // Scale-offset. Easy. + case GE_TEXMAP_UNKNOWN: // Not sure what this is, but Riviera uses it. Treating as coords works. + if (prescale) { + if (hasTexcoord) { + WRITE(p, " v_texcoord = texcoord;\n"); + } else { + WRITE(p, " v_texcoord = vec2(0.0);\n"); + } + } else { + if (hasTexcoord) { + WRITE(p, " v_texcoord = texcoord * u_uvscaleoffset.xy + u_uvscaleoffset.zw;\n"); + } else { + WRITE(p, " v_texcoord = u_uvscaleoffset.zw;\n"); + } + } + break; + + case GE_TEXMAP_TEXTURE_MATRIX: // Projection mapping. + { + std::string temp_tc; + switch (uvProjMode) { + case GE_PROJMAP_POSITION: // Use model space XYZ as source + temp_tc = "vec4(position.xyz, 1.0)"; + break; + case GE_PROJMAP_UV: // Use unscaled UV as source + { + // prescale is false here. + if (hasTexcoord) { + static const char *rescaleuv[4] = { "", " * 1.9921875", " * 1.999969482421875", "" }; // 2*127.5f/128.f, 2*32767.5f/32768.f, 1.0f}; + const char *factor = rescaleuv[texFmtScale]; + temp_tc = StringFromFormat("vec4(texcoord.xy %s, 0.0, 1.0)", factor); + } else { + temp_tc = "vec4(0.0, 0.0, 0.0, 1.0)"; + } + } + break; + case GE_PROJMAP_NORMALIZED_NORMAL: // Use normalized transformed normal as source + if (hasNormal) + temp_tc = flipNormal ? "vec4(normalize(-normal), 1.0)" : "vec4(normalize(normal), 1.0)"; + else + temp_tc = "vec4(0.0, 0.0, 1.0, 1.0)"; + break; + case GE_PROJMAP_NORMAL: // Use non-normalized transformed normal as source + if (hasNormal) + temp_tc = flipNormal ? "vec4(-normal, 1.0)" : "vec4(normal, 1.0)"; + else + temp_tc = "vec4(0.0, 0.0, 1.0, 1.0)"; + break; + } + // Transform by texture matrix. XYZ as we are doing projection mapping. + WRITE(p, " v_texcoord = (u_texmtx * %s).xyz * vec3(u_uvscaleoffset.xy, 1.0);\n", temp_tc.c_str()); + } + break; + + case GE_TEXMAP_ENVIRONMENT_MAP: // Shade mapping - use dots from light sources. + WRITE(p, " v_texcoord = u_uvscaleoffset.xy * vec2(1.0 + dot(normalize(u_lightpos%i), worldnormal), 1.0 + dot(normalize(u_lightpos%i), worldnormal)) * 0.5;\n", ls0, ls1); + break; + + default: + // ILLEGAL + break; + } + } + + // Compute fogdepth + if (enableFog) + WRITE(p, " v_fogdepth = (viewPos.z + u_fogcoef.x) * u_fogcoef.y;\n"); + } + WRITE(p, "}\n"); + return true; +} diff --git a/GPU/Vulkan/VertexShaderGeneratorVulkan.h b/GPU/Vulkan/VertexShaderGeneratorVulkan.h new file mode 100644 index 0000000000..d953fdbd76 --- /dev/null +++ b/GPU/Vulkan/VertexShaderGeneratorVulkan.h @@ -0,0 +1,5 @@ +#pragma once + +#include "GPU/Common/ShaderId.h" + +bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer); \ No newline at end of file diff --git a/GPU/Vulkan/VulkanUtil.h b/GPU/Vulkan/VulkanUtil.h new file mode 100644 index 0000000000..4899ff2b3a --- /dev/null +++ b/GPU/Vulkan/VulkanUtil.h @@ -0,0 +1,5 @@ +#pragma once + +#define VK_PROTOTYPES +#include "ext/vulkan/vulkan.h" + diff --git a/UI/EmuScreen.cpp b/UI/EmuScreen.cpp index a3fc172948..b78068a025 100644 --- a/UI/EmuScreen.cpp +++ b/UI/EmuScreen.cpp @@ -99,8 +99,19 @@ void EmuScreen::bootGame(const std::string &filename) { CoreParameter coreParam; coreParam.cpuCore = g_Config.bJit ? CPU_JIT : CPU_INTERPRETER; coreParam.gpuCore = GPU_GLES; - if (GetGPUBackend() == GPUBackend::DIRECT3D9) { + switch (GetGPUBackend()) { + case GPUBackend::OPENGL: + coreParam.gpuCore = GPU_GLES; + break; + case GPUBackend::DIRECT3D9: coreParam.gpuCore = GPU_DIRECTX9; + break; + case GPUBackend::DIRECT3D11: + coreParam.gpuCore = GPU_DIRECTX11; + break; + case GPUBackend::VULKAN: + coreParam.gpuCore = GPU_VULKAN; + break; } if (g_Config.bSoftwareRendering) { coreParam.gpuCore = GPU_SOFTWARE; @@ -956,6 +967,7 @@ void EmuScreen::render() { } // We have no use for backbuffer depth or stencil, so let tiled renderers discard them after tiling. + /* if (gl_extensions.GLES3 && glInvalidateFramebuffer != nullptr) { GLenum attachments[2] = { GL_DEPTH, GL_STENCIL }; glInvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments); @@ -969,6 +981,7 @@ void EmuScreen::render() { } #endif } + */ } void EmuScreen::deviceLost() { diff --git a/UI/GameSettingsScreen.cpp b/UI/GameSettingsScreen.cpp index 9a7462b496..639dc468ea 100644 --- a/UI/GameSettingsScreen.cpp +++ b/UI/GameSettingsScreen.cpp @@ -136,7 +136,7 @@ void GameSettingsScreen::CreateViews() { graphicsSettings->Add(new ItemHeader(gr->T("Rendering Mode"))); #if defined(_WIN32) - static const char *renderingBackend[] = { "OpenGL", "Direct3D9" }; + static const char *renderingBackend[] = { "OpenGL", "Direct3D 9", "Direct3D 11", "Vulkan" }; PopupMultiChoice *renderingBackendChoice = graphicsSettings->Add(new PopupMultiChoice(&g_Config.iGPUBackend, gr->T("Backend"), renderingBackend, GPU_BACKEND_OPENGL, ARRAY_SIZE(renderingBackend), gr->GetName(), screenManager())); renderingBackendChoice->OnChoice.Handle(this, &GameSettingsScreen::OnRenderingBackend); #endif diff --git a/UI/MiscScreens.cpp b/UI/MiscScreens.cpp index 7925287eda..2ed4aa9f05 100644 --- a/UI/MiscScreens.cpp +++ b/UI/MiscScreens.cpp @@ -383,7 +383,7 @@ void LogoScreen::Next() { void LogoScreen::update(InputState &input_state) { UIScreen::update(input_state); frames_++; - if (frames_ > 180 || input_state.pointer_down[0]) { + if (frames_ > 1800000 || input_state.pointer_down[0]) { Next(); } } diff --git a/Windows/GPU/WindowsVulkanContext.cpp b/Windows/GPU/WindowsVulkanContext.cpp new file mode 100644 index 0000000000..add7bc62f2 --- /dev/null +++ b/Windows/GPU/WindowsVulkanContext.cpp @@ -0,0 +1,107 @@ +// Copyright (c) 2015- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + + +// Initializing a Vulkan context is quite a complex task! +// That's not really a strange thing though - you really do have control over everything, +// and everything needs to be specified. There are no nebulous defaults. + +// We create a swapchain, and two framebuffers that we can point to two of the images +// we got from the swap chain. These will be used as backbuffers. +// +// We also create a depth buffer. The swap chain will not allocate one for us so we need +// to manage the memory for it ourselves. +// The depth buffer will not really be used unless we do "non-buffered" rendering, which will happen +// directly to one of the backbuffers. +// +// Render pass usage +// +// In normal buffered rendering mode, we do not begin the "UI" render pass until after we have rendered +// a frame of PSP graphics. The render pass that we will use then will be the simple "uiPass" that does not +// bother attaching the depth buffer, and discards all input (no need to even bother clearing as we will +// draw over the whole backbuffer anyway). +// +// However, in non-buffered, we will have to use the depth buffer, and we must begin the rendering pass +// before we start rendering PSP graphics, and end it only after we have completed rendering the UI on top. +// We will also use clearing. +// +// So it all turns into a single rendering pass, which might be good for performance on some GPUs, but it +// will complicate things a little. +// +// In a first iteration, we will not distinguish between these two cases - we will always create a depth buffer +// and use the same render pass configuration (clear to black). However, we can later change this so we switch +// to a non-clearing render pass in buffered mode, which might be a tiny bit faster. + +#include +#include + +#define VK_PROTOTYPES + +#include "ext/vulkan/vulkan.h" +#include "ext/native/thin3d/VulkanContext.h" + +#include "thin3d/thin3d.h" +#include "Windows/GPU/WindowsVulkanContext.h" + +const bool g_validate_ = true; +VulkanContext *g_Vulkan; + +bool WindowsVulkanContext::Init(HINSTANCE hInst, HWND hWnd, std::string *error_message) { + *error_message = "N/A"; + + if (g_Vulkan) { + *error_message = "Already initialized"; + return false; + } + + g_Vulkan = new VulkanContext("PPSSPP", 0); + + g_Vulkan->InitObjects(hInst, hWnd, true); + + _CrtCheckMemory(); + return true; +} + +void WindowsVulkanContext::Shutdown() { + g_Vulkan->DestroyObjects(); + delete g_Vulkan; + g_Vulkan = nullptr; +} + +Thin3DContext *WindowsVulkanContext::CreateThin3DContext() { + return T3DCreateVulkanContext(g_Vulkan); +} + +void WindowsVulkanContext::SwapBuffers() { +} + +void WindowsVulkanContext::Resize() { + /* + g_Vulkan->DestroyObjects(); + + g_Vulkan->WaitUntilQueueIdle(); + + g_Vulkan->InitObjects(g_Vulkan) + */ +} + +void WindowsVulkanContext::SwapInterval(int interval) { +} + +Thin3DContext *Vulkan_CreateThin3DContext() { + return T3DCreateVulkanContext(g_Vulkan); +} diff --git a/Windows/GPU/WindowsVulkanContext.h b/Windows/GPU/WindowsVulkanContext.h new file mode 100644 index 0000000000..99e736d01f --- /dev/null +++ b/Windows/GPU/WindowsVulkanContext.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#pragma once + +#include "Common/GraphicsContext.h" +#include "Windows/GPU/WindowsGraphicsContext.h" +#include "thin3d/thin3d.h" + +class WindowsVulkanContext : public WindowsGraphicsContext { +public: + bool Init(HINSTANCE hInst, HWND window, std::string *error_message) override; + void Shutdown() override; + void SwapInterval(int interval) override; + void SwapBuffers() override; + void Resize() override; + + Thin3DContext *CreateThin3DContext() override; +}; + +void Vulkan_BeginSurfaceRender(); +void Vulkan_EndSurfaceRender(); diff --git a/Windows/PPSSPP.sln b/Windows/PPSSPP.sln index 225c2a10bf..ab1953c322 100644 --- a/Windows/PPSSPP.sln +++ b/Windows/PPSSPP.sln @@ -38,6 +38,7 @@ EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "native", "..\ext\native\native.vcxproj", "{C4DF647E-80EA-4111-A0A8-218B1B711E18}" ProjectSection(ProjectDependencies) = postProject {F761046E-6C38-4428-A5F1-38391A37BB34} = {F761046E-6C38-4428-A5F1-38391A37BB34} + {EDFA2E87-8AC1-4853-95D4-D7594FF81947} = {EDFA2E87-8AC1-4853-95D4-D7594FF81947} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "PPSSPPHeadless", "..\headless\Headless.vcxproj", "{EE9BD869-CAA3-447D-8328-294D90DE2C1F}" @@ -75,18 +76,30 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "glslang", "..\ext\glslang.v EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug CRT DLL|Win32 = Debug CRT DLL|Win32 + Debug CRT DLL|x64 = Debug CRT DLL|x64 Debug|Win32 = Debug|Win32 Debug|x64 = Debug|x64 + Release CRT DLL|Win32 = Release CRT DLL|Win32 + Release CRT DLL|x64 = Release CRT DLL|x64 Release|Win32 = Release|Win32 Release|x64 = Release|x64 Tests|Win32 = Tests|Win32 Tests|x64 = Tests|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution + {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Debug CRT DLL|Win32.ActiveCfg = Debug|Win32 + {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Debug CRT DLL|Win32.Build.0 = Debug|Win32 + {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Debug CRT DLL|x64.ActiveCfg = Debug|x64 + {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Debug CRT DLL|x64.Build.0 = Debug|x64 {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Debug|Win32.ActiveCfg = Debug|Win32 {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Debug|Win32.Build.0 = Debug|Win32 {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Debug|x64.ActiveCfg = Debug|x64 {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Debug|x64.Build.0 = Debug|x64 + {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Release CRT DLL|Win32.ActiveCfg = Release|Win32 + {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Release CRT DLL|Win32.Build.0 = Release|Win32 + {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Release CRT DLL|x64.ActiveCfg = Release|x64 + {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Release CRT DLL|x64.Build.0 = Release|x64 {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Release|Win32.ActiveCfg = Release|Win32 {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Release|Win32.Build.0 = Release|Win32 {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Release|x64.ActiveCfg = Release|x64 @@ -95,10 +108,18 @@ Global {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Tests|Win32.Build.0 = Release|Win32 {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Tests|x64.ActiveCfg = Release|x64 {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Tests|x64.Build.0 = Release|x64 + {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Debug CRT DLL|Win32.ActiveCfg = Debug|Win32 + {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Debug CRT DLL|Win32.Build.0 = Debug|Win32 + {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Debug CRT DLL|x64.ActiveCfg = Debug|x64 + {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Debug CRT DLL|x64.Build.0 = Debug|x64 {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Debug|Win32.ActiveCfg = Debug|Win32 {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Debug|Win32.Build.0 = Debug|Win32 {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Debug|x64.ActiveCfg = Debug|x64 {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Debug|x64.Build.0 = Debug|x64 + {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Release CRT DLL|Win32.ActiveCfg = Release|Win32 + {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Release CRT DLL|Win32.Build.0 = Release|Win32 + {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Release CRT DLL|x64.ActiveCfg = Release|x64 + {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Release CRT DLL|x64.Build.0 = Release|x64 {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Release|Win32.ActiveCfg = Release|Win32 {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Release|Win32.Build.0 = Release|Win32 {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Release|x64.ActiveCfg = Release|x64 @@ -107,10 +128,18 @@ Global {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Tests|Win32.Build.0 = Release|Win32 {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Tests|x64.ActiveCfg = Release|x64 {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Tests|x64.Build.0 = Release|x64 + {F761046E-6C38-4428-A5F1-38391A37BB34}.Debug CRT DLL|Win32.ActiveCfg = Debug|Win32 + {F761046E-6C38-4428-A5F1-38391A37BB34}.Debug CRT DLL|Win32.Build.0 = Debug|Win32 + {F761046E-6C38-4428-A5F1-38391A37BB34}.Debug CRT DLL|x64.ActiveCfg = Debug|x64 + {F761046E-6C38-4428-A5F1-38391A37BB34}.Debug CRT DLL|x64.Build.0 = Debug|x64 {F761046E-6C38-4428-A5F1-38391A37BB34}.Debug|Win32.ActiveCfg = Debug|Win32 {F761046E-6C38-4428-A5F1-38391A37BB34}.Debug|Win32.Build.0 = Debug|Win32 {F761046E-6C38-4428-A5F1-38391A37BB34}.Debug|x64.ActiveCfg = Debug|x64 {F761046E-6C38-4428-A5F1-38391A37BB34}.Debug|x64.Build.0 = Debug|x64 + {F761046E-6C38-4428-A5F1-38391A37BB34}.Release CRT DLL|Win32.ActiveCfg = Release|Win32 + {F761046E-6C38-4428-A5F1-38391A37BB34}.Release CRT DLL|Win32.Build.0 = Release|Win32 + {F761046E-6C38-4428-A5F1-38391A37BB34}.Release CRT DLL|x64.ActiveCfg = Release|x64 + {F761046E-6C38-4428-A5F1-38391A37BB34}.Release CRT DLL|x64.Build.0 = Release|x64 {F761046E-6C38-4428-A5F1-38391A37BB34}.Release|Win32.ActiveCfg = Release|Win32 {F761046E-6C38-4428-A5F1-38391A37BB34}.Release|Win32.Build.0 = Release|Win32 {F761046E-6C38-4428-A5F1-38391A37BB34}.Release|x64.ActiveCfg = Release|x64 @@ -119,10 +148,18 @@ Global {F761046E-6C38-4428-A5F1-38391A37BB34}.Tests|Win32.Build.0 = Release|Win32 {F761046E-6C38-4428-A5F1-38391A37BB34}.Tests|x64.ActiveCfg = Release|x64 {F761046E-6C38-4428-A5F1-38391A37BB34}.Tests|x64.Build.0 = Release|x64 + {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Debug CRT DLL|Win32.ActiveCfg = Debug|Win32 + {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Debug CRT DLL|Win32.Build.0 = Debug|Win32 + {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Debug CRT DLL|x64.ActiveCfg = Debug|x64 + {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Debug CRT DLL|x64.Build.0 = Debug|x64 {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Debug|Win32.ActiveCfg = Debug|Win32 {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Debug|Win32.Build.0 = Debug|Win32 {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Debug|x64.ActiveCfg = Debug|x64 {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Debug|x64.Build.0 = Debug|x64 + {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Release CRT DLL|Win32.ActiveCfg = Release|Win32 + {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Release CRT DLL|Win32.Build.0 = Release|Win32 + {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Release CRT DLL|x64.ActiveCfg = Release|x64 + {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Release CRT DLL|x64.Build.0 = Release|x64 {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Release|Win32.ActiveCfg = Release|Win32 {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Release|Win32.Build.0 = Release|Win32 {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Release|x64.ActiveCfg = Release|x64 @@ -131,10 +168,18 @@ Global {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Tests|Win32.Build.0 = Release|Win32 {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Tests|x64.ActiveCfg = Release|x64 {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Tests|x64.Build.0 = Release|x64 + {533F1D30-D04D-47CC-AD71-20F658907E36}.Debug CRT DLL|Win32.ActiveCfg = Debug|Win32 + {533F1D30-D04D-47CC-AD71-20F658907E36}.Debug CRT DLL|Win32.Build.0 = Debug|Win32 + {533F1D30-D04D-47CC-AD71-20F658907E36}.Debug CRT DLL|x64.ActiveCfg = Debug|x64 + {533F1D30-D04D-47CC-AD71-20F658907E36}.Debug CRT DLL|x64.Build.0 = Debug|x64 {533F1D30-D04D-47CC-AD71-20F658907E36}.Debug|Win32.ActiveCfg = Debug|Win32 {533F1D30-D04D-47CC-AD71-20F658907E36}.Debug|Win32.Build.0 = Debug|Win32 {533F1D30-D04D-47CC-AD71-20F658907E36}.Debug|x64.ActiveCfg = Debug|x64 {533F1D30-D04D-47CC-AD71-20F658907E36}.Debug|x64.Build.0 = Debug|x64 + {533F1D30-D04D-47CC-AD71-20F658907E36}.Release CRT DLL|Win32.ActiveCfg = Release|Win32 + {533F1D30-D04D-47CC-AD71-20F658907E36}.Release CRT DLL|Win32.Build.0 = Release|Win32 + {533F1D30-D04D-47CC-AD71-20F658907E36}.Release CRT DLL|x64.ActiveCfg = Release|x64 + {533F1D30-D04D-47CC-AD71-20F658907E36}.Release CRT DLL|x64.Build.0 = Release|x64 {533F1D30-D04D-47CC-AD71-20F658907E36}.Release|Win32.ActiveCfg = Release|Win32 {533F1D30-D04D-47CC-AD71-20F658907E36}.Release|Win32.Build.0 = Release|Win32 {533F1D30-D04D-47CC-AD71-20F658907E36}.Release|x64.ActiveCfg = Release|x64 @@ -143,10 +188,18 @@ Global {533F1D30-D04D-47CC-AD71-20F658907E36}.Tests|Win32.Build.0 = Release|Win32 {533F1D30-D04D-47CC-AD71-20F658907E36}.Tests|x64.ActiveCfg = Release|x64 {533F1D30-D04D-47CC-AD71-20F658907E36}.Tests|x64.Build.0 = Release|x64 + {C4DF647E-80EA-4111-A0A8-218B1B711E18}.Debug CRT DLL|Win32.ActiveCfg = Debug|Win32 + {C4DF647E-80EA-4111-A0A8-218B1B711E18}.Debug CRT DLL|Win32.Build.0 = Debug|Win32 + {C4DF647E-80EA-4111-A0A8-218B1B711E18}.Debug CRT DLL|x64.ActiveCfg = Debug|x64 + {C4DF647E-80EA-4111-A0A8-218B1B711E18}.Debug CRT DLL|x64.Build.0 = Debug|x64 {C4DF647E-80EA-4111-A0A8-218B1B711E18}.Debug|Win32.ActiveCfg = Debug|Win32 {C4DF647E-80EA-4111-A0A8-218B1B711E18}.Debug|Win32.Build.0 = Debug|Win32 {C4DF647E-80EA-4111-A0A8-218B1B711E18}.Debug|x64.ActiveCfg = Debug|x64 {C4DF647E-80EA-4111-A0A8-218B1B711E18}.Debug|x64.Build.0 = Debug|x64 + {C4DF647E-80EA-4111-A0A8-218B1B711E18}.Release CRT DLL|Win32.ActiveCfg = Release|Win32 + {C4DF647E-80EA-4111-A0A8-218B1B711E18}.Release CRT DLL|Win32.Build.0 = Release|Win32 + {C4DF647E-80EA-4111-A0A8-218B1B711E18}.Release CRT DLL|x64.ActiveCfg = Release|x64 + {C4DF647E-80EA-4111-A0A8-218B1B711E18}.Release CRT DLL|x64.Build.0 = Release|x64 {C4DF647E-80EA-4111-A0A8-218B1B711E18}.Release|Win32.ActiveCfg = Release|Win32 {C4DF647E-80EA-4111-A0A8-218B1B711E18}.Release|Win32.Build.0 = Release|Win32 {C4DF647E-80EA-4111-A0A8-218B1B711E18}.Release|x64.ActiveCfg = Release|x64 @@ -155,10 +208,18 @@ Global {C4DF647E-80EA-4111-A0A8-218B1B711E18}.Tests|Win32.Build.0 = Release|Win32 {C4DF647E-80EA-4111-A0A8-218B1B711E18}.Tests|x64.ActiveCfg = Release|x64 {C4DF647E-80EA-4111-A0A8-218B1B711E18}.Tests|x64.Build.0 = Release|x64 + {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Debug CRT DLL|Win32.ActiveCfg = Debug|Win32 + {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Debug CRT DLL|Win32.Build.0 = Debug|Win32 + {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Debug CRT DLL|x64.ActiveCfg = Debug|x64 + {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Debug CRT DLL|x64.Build.0 = Debug|x64 {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Debug|Win32.ActiveCfg = Debug|Win32 {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Debug|Win32.Build.0 = Debug|Win32 {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Debug|x64.ActiveCfg = Debug|x64 {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Debug|x64.Build.0 = Debug|x64 + {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Release CRT DLL|Win32.ActiveCfg = Release|Win32 + {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Release CRT DLL|Win32.Build.0 = Release|Win32 + {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Release CRT DLL|x64.ActiveCfg = Release|x64 + {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Release CRT DLL|x64.Build.0 = Release|x64 {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Release|Win32.ActiveCfg = Release|Win32 {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Release|Win32.Build.0 = Release|Win32 {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Release|x64.ActiveCfg = Release|x64 @@ -167,10 +228,18 @@ Global {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Tests|Win32.Build.0 = Release|Win32 {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Tests|x64.ActiveCfg = Release|x64 {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Tests|x64.Build.0 = Release|x64 + {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Debug CRT DLL|Win32.ActiveCfg = Debug|Win32 + {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Debug CRT DLL|Win32.Build.0 = Debug|Win32 + {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Debug CRT DLL|x64.ActiveCfg = Debug|x64 + {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Debug CRT DLL|x64.Build.0 = Debug|x64 {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Debug|Win32.ActiveCfg = Debug|Win32 {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Debug|Win32.Build.0 = Debug|Win32 {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Debug|x64.ActiveCfg = Debug|x64 {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Debug|x64.Build.0 = Debug|x64 + {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Release CRT DLL|Win32.ActiveCfg = Release|Win32 + {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Release CRT DLL|Win32.Build.0 = Release|Win32 + {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Release CRT DLL|x64.ActiveCfg = Release|x64 + {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Release CRT DLL|x64.Build.0 = Release|x64 {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Release|Win32.ActiveCfg = Release|Win32 {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Release|Win32.Build.0 = Release|Win32 {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Release|x64.ActiveCfg = Release|x64 @@ -179,10 +248,18 @@ Global {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Tests|Win32.Build.0 = Release|Win32 {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Tests|x64.ActiveCfg = Release|x64 {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Tests|x64.Build.0 = Release|x64 + {37CBC214-7CE7-4655-B619-F7CEE16E3313}.Debug CRT DLL|Win32.ActiveCfg = Debug|Win32 + {37CBC214-7CE7-4655-B619-F7CEE16E3313}.Debug CRT DLL|Win32.Build.0 = Debug|Win32 + {37CBC214-7CE7-4655-B619-F7CEE16E3313}.Debug CRT DLL|x64.ActiveCfg = Debug|x64 + {37CBC214-7CE7-4655-B619-F7CEE16E3313}.Debug CRT DLL|x64.Build.0 = Debug|x64 {37CBC214-7CE7-4655-B619-F7CEE16E3313}.Debug|Win32.ActiveCfg = Debug|Win32 {37CBC214-7CE7-4655-B619-F7CEE16E3313}.Debug|Win32.Build.0 = Debug|Win32 {37CBC214-7CE7-4655-B619-F7CEE16E3313}.Debug|x64.ActiveCfg = Debug|x64 {37CBC214-7CE7-4655-B619-F7CEE16E3313}.Debug|x64.Build.0 = Debug|x64 + {37CBC214-7CE7-4655-B619-F7CEE16E3313}.Release CRT DLL|Win32.ActiveCfg = Release|Win32 + {37CBC214-7CE7-4655-B619-F7CEE16E3313}.Release CRT DLL|Win32.Build.0 = Release|Win32 + {37CBC214-7CE7-4655-B619-F7CEE16E3313}.Release CRT DLL|x64.ActiveCfg = Release|x64 + {37CBC214-7CE7-4655-B619-F7CEE16E3313}.Release CRT DLL|x64.Build.0 = Release|x64 {37CBC214-7CE7-4655-B619-F7CEE16E3313}.Release|Win32.ActiveCfg = Release|Win32 {37CBC214-7CE7-4655-B619-F7CEE16E3313}.Release|Win32.Build.0 = Release|Win32 {37CBC214-7CE7-4655-B619-F7CEE16E3313}.Release|x64.ActiveCfg = Release|x64 @@ -191,10 +268,18 @@ Global {37CBC214-7CE7-4655-B619-F7CEE16E3313}.Tests|Win32.Build.0 = Release|Win32 {37CBC214-7CE7-4655-B619-F7CEE16E3313}.Tests|x64.ActiveCfg = Release|x64 {37CBC214-7CE7-4655-B619-F7CEE16E3313}.Tests|x64.Build.0 = Release|x64 + {004B8D11-2BE3-4BD9-AB40-2BE04CF2096F}.Debug CRT DLL|Win32.ActiveCfg = Debug|Win32 + {004B8D11-2BE3-4BD9-AB40-2BE04CF2096F}.Debug CRT DLL|Win32.Build.0 = Debug|Win32 + {004B8D11-2BE3-4BD9-AB40-2BE04CF2096F}.Debug CRT DLL|x64.ActiveCfg = Debug|x64 + {004B8D11-2BE3-4BD9-AB40-2BE04CF2096F}.Debug CRT DLL|x64.Build.0 = Debug|x64 {004B8D11-2BE3-4BD9-AB40-2BE04CF2096F}.Debug|Win32.ActiveCfg = Debug|Win32 {004B8D11-2BE3-4BD9-AB40-2BE04CF2096F}.Debug|Win32.Build.0 = Debug|Win32 {004B8D11-2BE3-4BD9-AB40-2BE04CF2096F}.Debug|x64.ActiveCfg = Debug|x64 {004B8D11-2BE3-4BD9-AB40-2BE04CF2096F}.Debug|x64.Build.0 = Debug|x64 + {004B8D11-2BE3-4BD9-AB40-2BE04CF2096F}.Release CRT DLL|Win32.ActiveCfg = Release|Win32 + {004B8D11-2BE3-4BD9-AB40-2BE04CF2096F}.Release CRT DLL|Win32.Build.0 = Release|Win32 + {004B8D11-2BE3-4BD9-AB40-2BE04CF2096F}.Release CRT DLL|x64.ActiveCfg = Release|x64 + {004B8D11-2BE3-4BD9-AB40-2BE04CF2096F}.Release CRT DLL|x64.Build.0 = Release|x64 {004B8D11-2BE3-4BD9-AB40-2BE04CF2096F}.Release|Win32.ActiveCfg = Release|Win32 {004B8D11-2BE3-4BD9-AB40-2BE04CF2096F}.Release|Win32.Build.0 = Release|Win32 {004B8D11-2BE3-4BD9-AB40-2BE04CF2096F}.Release|x64.ActiveCfg = Release|x64 @@ -203,10 +288,18 @@ Global {004B8D11-2BE3-4BD9-AB40-2BE04CF2096F}.Tests|Win32.Build.0 = Release|Win32 {004B8D11-2BE3-4BD9-AB40-2BE04CF2096F}.Tests|x64.ActiveCfg = Release|x64 {004B8D11-2BE3-4BD9-AB40-2BE04CF2096F}.Tests|x64.Build.0 = Release|x64 + {129E5E2B-39C1-4D84-96FE-DFD22DBB4A25}.Debug CRT DLL|Win32.ActiveCfg = Debug|Win32 + {129E5E2B-39C1-4D84-96FE-DFD22DBB4A25}.Debug CRT DLL|Win32.Build.0 = Debug|Win32 + {129E5E2B-39C1-4D84-96FE-DFD22DBB4A25}.Debug CRT DLL|x64.ActiveCfg = Debug|x64 + {129E5E2B-39C1-4D84-96FE-DFD22DBB4A25}.Debug CRT DLL|x64.Build.0 = Debug|x64 {129E5E2B-39C1-4D84-96FE-DFD22DBB4A25}.Debug|Win32.ActiveCfg = Debug|Win32 {129E5E2B-39C1-4D84-96FE-DFD22DBB4A25}.Debug|Win32.Build.0 = Debug|Win32 {129E5E2B-39C1-4D84-96FE-DFD22DBB4A25}.Debug|x64.ActiveCfg = Debug|x64 {129E5E2B-39C1-4D84-96FE-DFD22DBB4A25}.Debug|x64.Build.0 = Debug|x64 + {129E5E2B-39C1-4D84-96FE-DFD22DBB4A25}.Release CRT DLL|Win32.ActiveCfg = Release|Win32 + {129E5E2B-39C1-4D84-96FE-DFD22DBB4A25}.Release CRT DLL|Win32.Build.0 = Release|Win32 + {129E5E2B-39C1-4D84-96FE-DFD22DBB4A25}.Release CRT DLL|x64.ActiveCfg = Release|x64 + {129E5E2B-39C1-4D84-96FE-DFD22DBB4A25}.Release CRT DLL|x64.Build.0 = Release|x64 {129E5E2B-39C1-4D84-96FE-DFD22DBB4A25}.Release|Win32.ActiveCfg = Release|Win32 {129E5E2B-39C1-4D84-96FE-DFD22DBB4A25}.Release|Win32.Build.0 = Release|Win32 {129E5E2B-39C1-4D84-96FE-DFD22DBB4A25}.Release|x64.ActiveCfg = Release|x64 @@ -215,10 +308,18 @@ Global {129E5E2B-39C1-4D84-96FE-DFD22DBB4A25}.Tests|Win32.Build.0 = Tests|Win32 {129E5E2B-39C1-4D84-96FE-DFD22DBB4A25}.Tests|x64.ActiveCfg = Tests|x64 {129E5E2B-39C1-4D84-96FE-DFD22DBB4A25}.Tests|x64.Build.0 = Tests|x64 + {EDFA2E87-8AC1-4853-95D4-D7594FF81947}.Debug CRT DLL|Win32.ActiveCfg = Debug|Win32 + {EDFA2E87-8AC1-4853-95D4-D7594FF81947}.Debug CRT DLL|Win32.Build.0 = Debug|Win32 + {EDFA2E87-8AC1-4853-95D4-D7594FF81947}.Debug CRT DLL|x64.ActiveCfg = Debug|x64 + {EDFA2E87-8AC1-4853-95D4-D7594FF81947}.Debug CRT DLL|x64.Build.0 = Debug|x64 {EDFA2E87-8AC1-4853-95D4-D7594FF81947}.Debug|Win32.ActiveCfg = Debug|Win32 {EDFA2E87-8AC1-4853-95D4-D7594FF81947}.Debug|Win32.Build.0 = Debug|Win32 {EDFA2E87-8AC1-4853-95D4-D7594FF81947}.Debug|x64.ActiveCfg = Debug|x64 {EDFA2E87-8AC1-4853-95D4-D7594FF81947}.Debug|x64.Build.0 = Debug|x64 + {EDFA2E87-8AC1-4853-95D4-D7594FF81947}.Release CRT DLL|Win32.ActiveCfg = Release|Win32 + {EDFA2E87-8AC1-4853-95D4-D7594FF81947}.Release CRT DLL|Win32.Build.0 = Release|Win32 + {EDFA2E87-8AC1-4853-95D4-D7594FF81947}.Release CRT DLL|x64.ActiveCfg = Release|x64 + {EDFA2E87-8AC1-4853-95D4-D7594FF81947}.Release CRT DLL|x64.Build.0 = Release|x64 {EDFA2E87-8AC1-4853-95D4-D7594FF81947}.Release|Win32.ActiveCfg = Release|Win32 {EDFA2E87-8AC1-4853-95D4-D7594FF81947}.Release|Win32.Build.0 = Release|Win32 {EDFA2E87-8AC1-4853-95D4-D7594FF81947}.Release|x64.ActiveCfg = Release|x64 diff --git a/Windows/PPSSPP.vcxproj b/Windows/PPSSPP.vcxproj index c24357d995..c889776f6c 100644 --- a/Windows/PPSSPP.vcxproj +++ b/Windows/PPSSPP.vcxproj @@ -125,7 +125,7 @@ Use Level3 ProgramDatabase - ../common;..;../ext/native;../ext/native/ext/glew;../ext/zlib + ../ext;../common;..;../ext/native;../ext/native/ext/glew;../ext/zlib stdafx.h;Common/DbgNew.h MultiThreadedDebug StreamingSIMDExtensions2 @@ -135,7 +135,7 @@ Disabled - Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86\lib\avcodec.lib;..\ffmpeg\Windows\x86\lib\avformat.lib;..\ffmpeg\Windows\x86\lib\avutil.lib;..\ffmpeg\Windows\x86\lib\swresample.lib;..\ffmpeg\Windows\x86\lib\swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;dxerr.lib;%(AdditionalDependencies) + ..\ext\vulkan\vulkan-1.lib;Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86\lib\avcodec.lib;..\ffmpeg\Windows\x86\lib\avformat.lib;..\ffmpeg\Windows\x86\lib\avutil.lib;..\ffmpeg\Windows\x86\lib\swresample.lib;..\ffmpeg\Windows\x86\lib\swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;dxerr.lib;%(AdditionalDependencies) true Windows MachineX86 @@ -161,7 +161,7 @@ Use Level3 ProgramDatabase - ../common;..;../ext/native;../ext/native/ext/glew;../ext/zlib + ../ext;../common;..;../ext/native;../ext/native/ext/glew;../ext/zlib stdafx.h;Common/DbgNew.h MultiThreadedDebug false @@ -172,7 +172,7 @@ Disabled - Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86_64\lib\avcodec.lib;..\ffmpeg\Windows\x86_64\lib\avformat.lib;..\ffmpeg\Windows\x86_64\lib\avutil.lib;..\ffmpeg\Windows\x86_64\lib\swresample.lib;..\ffmpeg\Windows\x86_64\lib\swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) + x64\Debug\glslang.lib;..\ext\vulkan\vulkan-1.lib;Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86_64\lib\avcodec.lib;..\ffmpeg\Windows\x86_64\lib\avformat.lib;..\ffmpeg\Windows\x86_64\lib\avutil.lib;..\ffmpeg\Windows\x86_64\lib\swresample.lib;..\ffmpeg\Windows\x86_64\lib\swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) true $(OutDir)$(ProjectName).pdb Windows @@ -201,14 +201,14 @@ Use Level3 ProgramDatabase - ../common;..;../ext/native;../ext/native/ext/glew;../ext/zlib + ../ext;../common;..;../ext/native;../ext/native/ext/glew;../ext/zlib stdafx.h stdafx.h true false - dxerr.lib;Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86\lib\avcodec.lib;..\ffmpeg\Windows\x86\lib\avformat.lib;..\ffmpeg\Windows\x86\lib\avutil.lib;..\ffmpeg\Windows\x86\lib\swresample.lib;..\ffmpeg\Windows\x86\lib\swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) + ..\ext\vulkan\vulkan-1.lib;dxerr.lib;Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86\lib\avcodec.lib;..\ffmpeg\Windows\x86\lib\avformat.lib;..\ffmpeg\Windows\x86\lib\avutil.lib;..\ffmpeg\Windows\x86\lib\swresample.lib;..\ffmpeg\Windows\x86\lib\swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) $(OutDir)$(TargetName)$(TargetExt) %(AdditionalLibraryDirectories) true @@ -246,13 +246,13 @@ Use Level3 ProgramDatabase - ../common;..;../ext/native;../ext/native/ext/glew;../ext/zlib + ../ext;../common;..;../ext/native;../ext/native/ext/glew;../ext/zlib stdafx.h true false - dxerr.lib;Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86_64\lib\avcodec.lib;..\ffmpeg\Windows\x86_64\lib\avformat.lib;..\ffmpeg\Windows\x86_64\lib\avutil.lib;..\ffmpeg\Windows\x86_64\lib\swresample.lib;..\ffmpeg\Windows\x86_64\lib\swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) + ..\ext\vulkan\vulkan-1.lib;dxerr.lib;Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86_64\lib\avcodec.lib;..\ffmpeg\Windows\x86_64\lib\avformat.lib;..\ffmpeg\Windows\x86_64\lib\avutil.lib;..\ffmpeg\Windows\x86_64\lib\swresample.lib;..\ffmpeg\Windows\x86_64\lib\swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) %(AdditionalLibraryDirectories) true Windows @@ -319,6 +319,7 @@ + $(IntDir)%(Filename)2.obj @@ -374,6 +375,7 @@ + @@ -422,6 +424,9 @@ {533f1d30-d04d-47cc-ad71-20f658907e36} + + {edfa2e87-8ac1-4853-95d4-d7594ff81947} + {3baae095-e0ab-4b0e-b5df-ce39c8ae31de} diff --git a/Windows/PPSSPP.vcxproj.filters b/Windows/PPSSPP.vcxproj.filters index 4bf680c53f..a981fe75cb 100644 --- a/Windows/PPSSPP.vcxproj.filters +++ b/Windows/PPSSPP.vcxproj.filters @@ -152,6 +152,7 @@ Windows\System + @@ -278,6 +279,7 @@ Windows\System + diff --git a/Windows/WindowsHost.cpp b/Windows/WindowsHost.cpp index ad9107db8d..b46c16e530 100644 --- a/Windows/WindowsHost.cpp +++ b/Windows/WindowsHost.cpp @@ -43,6 +43,7 @@ #include "Windows/WindowsHost.h" #include "Windows/MainWindow.h" #include "Windows/GPU/WindowsGLContext.h" +#include "Windows/GPU/WindowsVulkanContext.h" #include "Windows/GPU/D3D9Context.h" #include "Windows/Debugger/DebuggerShared.h" @@ -110,6 +111,9 @@ bool WindowsHost::InitGraphics(std::string *error_message, GraphicsContext **ctx case GPU_BACKEND_DIRECT3D9: graphicsContext = new D3D9Context(); break; + case GPU_BACKEND_VULKAN: + graphicsContext = new WindowsVulkanContext(); + break; default: return false; } diff --git a/ext/glslang.vcxproj b/ext/glslang.vcxproj index 53e1c2fee1..b9f4a64d71 100644 --- a/ext/glslang.vcxproj +++ b/ext/glslang.vcxproj @@ -114,6 +114,8 @@ true WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions) glslang/glslang/OSDependent/Windows;glslang/glslang/MachineIndependent + MultiThreaded + false Windows @@ -132,6 +134,8 @@ true NDEBUG;_LIB;%(PreprocessorDefinitions) glslang/glslang/OSDependent/Windows;glslang/glslang/MachineIndependent + MultiThreaded + false Windows @@ -140,13 +144,11 @@ true - - - + @@ -191,6 +193,7 @@ + @@ -202,7 +205,6 @@ - @@ -217,7 +219,6 @@ - diff --git a/ext/glslang.vcxproj.filters b/ext/glslang.vcxproj.filters index bd9df829ce..f1130d7b8d 100644 --- a/ext/glslang.vcxproj.filters +++ b/ext/glslang.vcxproj.filters @@ -1,8 +1,5 @@  - - - {300f8b24-cec5-41dc-bf7f-e60745f3e383} @@ -110,6 +107,9 @@ SPIRV + + glslang + @@ -202,9 +202,6 @@ glslang - - glslang - glslang @@ -212,13 +209,13 @@ glslang + + glslang + glslang - - glslang - \ No newline at end of file diff --git a/ext/native/math/dataconv.h b/ext/native/math/dataconv.h index 046bb63f35..d3d4beefa7 100644 --- a/ext/native/math/dataconv.h +++ b/ext/native/math/dataconv.h @@ -85,4 +85,4 @@ inline void CopyMatrix4x4(float dest[16], const float src[16]) { inline void ExpandFloat24x3ToFloat4(float dest[4], uint32_t src[3]) { uint32_t temp[4] = { src[0] << 8, src[1] << 8, src[2] << 8, 0 }; memcpy(dest, temp, sizeof(float) * 4); -} \ No newline at end of file +} diff --git a/ext/native/native.vcxproj b/ext/native/native.vcxproj index 93d7860e03..238f515b30 100644 --- a/ext/native/native.vcxproj +++ b/ext/native/native.vcxproj @@ -80,7 +80,7 @@ Level3 _CRTDBG_MAP_ALLOC;_CRT_SECURE_NO_WARNINGS;WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions) - ..\..\dx9sdk\Include;..\zlib;..\ext\zlib;..\native;..\RollerballGL;..\native\ext\glew;..\SDL\include;..\native\ext;%(AdditionalIncludeDirectories); + ..\..\ext;..\..;..\..\dx9sdk\Include;..\zlib;..\ext\zlib;..\native;..\RollerballGL;..\native\ext\glew;..\SDL\include;..\native\ext;%(AdditionalIncludeDirectories); ProgramDatabase true false @@ -102,7 +102,7 @@ Level3 _CRTDBG_MAP_ALLOC;_CRT_SECURE_NO_WARNINGS;WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions) - ..\..\dx9sdk\Include;..\zlib;..\ext\zlib;..\native;..\RollerballGL;..\native\ext\glew;..\SDL\include;..\native\ext;%(AdditionalIncludeDirectories); + ..\..\ext;..\..;..\..\dx9sdk\Include;..\zlib;..\ext\zlib;..\native;..\RollerballGL;..\native\ext\glew;..\SDL\include;..\native\ext;%(AdditionalIncludeDirectories); true false false @@ -128,7 +128,7 @@ true true WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions) - ..\..\dx9sdk\Include;..\zlib;..\ext\zlib;..\native;..\RollerballGL;..\native\ext\glew;..\SDL\include;..\native\ext;%(AdditionalIncludeDirectories); + ..\..\ext;..\..;..\..\dx9sdk\Include;..\zlib;..\ext\zlib;..\native;..\RollerballGL;..\native\ext\glew;..\SDL\include;..\native\ext;%(AdditionalIncludeDirectories); StreamingSIMDExtensions2 Fast true @@ -154,7 +154,7 @@ true true WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions) - ..\..\dx9sdk\Include;..\zlib;..\ext\zlib;..\native;..\RollerballGL;..\native\ext\glew;..\SDL\include;..\native\ext;%(AdditionalIncludeDirectories); + ..\..\ext;..\..;..\..\dx9sdk\Include;..\zlib;..\ext\zlib;..\native;..\RollerballGL;..\native\ext\glew;..\SDL\include;..\native\ext;%(AdditionalIncludeDirectories); NotSet Fast true @@ -265,6 +265,8 @@ + + @@ -344,7 +346,6 @@ - @@ -727,6 +728,9 @@ + + + diff --git a/ext/native/native.vcxproj.filters b/ext/native/native.vcxproj.filters index acbf041728..ba91f6e506 100644 --- a/ext/native/native.vcxproj.filters +++ b/ext/native/native.vcxproj.filters @@ -305,9 +305,15 @@ file + + thin3d + math + + thin3d + @@ -502,9 +508,6 @@ ext\libpng17 - - ext\libpng17 - ext\libpng17 @@ -745,6 +748,15 @@ file + + thin3d + + + thin3d + + + thin3d + diff --git a/ext/native/thin3d/VulkanContext.cpp b/ext/native/thin3d/VulkanContext.cpp new file mode 100644 index 0000000000..a324fe7b44 --- /dev/null +++ b/ext/native/thin3d/VulkanContext.cpp @@ -0,0 +1,1619 @@ +#include +#include +#include +#include + +#include "VulkanContext.h" + +#ifdef USE_CRT_DBG +#undef new +#endif + +#include "glslang/SPIRV/GlslangToSpv.h" + +#ifdef USE_CRT_DBG +#define new DBG_NEW +#endif + +#define GET_INSTANCE_PROC_ADDR(inst, entrypoint) \ +{ \ + fp##entrypoint = (PFN_vk##entrypoint) vkGetInstanceProcAddr(inst, "vk"#entrypoint); \ + if (fp##entrypoint == NULL) { \ + std::cout << "vkGetDeviceProcAddr failed to find vk"#entrypoint; \ + exit(-1); \ + } \ +} + +#define GET_DEVICE_PROC_ADDR(dev, entrypoint) \ +{ \ + fp##entrypoint = (PFN_vk##entrypoint) vkGetDeviceProcAddr(dev, "vk"#entrypoint); \ + if (fp##entrypoint == NULL) { \ + std::cout << "vkGetDeviceProcAddr failed to find vk"#entrypoint; \ + exit(-1); \ + } \ +} + +using namespace std; + +VulkanContext::VulkanContext(const char *app_name, uint32_t flags) + : device_(nullptr), + gfx_queue_(nullptr), + connection(nullptr), + gfx_queue_family_index_(-1), + surface(nullptr), + window(nullptr), + prepared(false), + use_staging_buffer_(false), + instance_(nullptr), + width(0), + height(0), + swapchain_format(VK_FORMAT_UNDEFINED), + swapchainImageCount(0), + swap_chain_(nullptr), + cmd_pool_(nullptr), + cmd_(nullptr), + dbgCreateMsgCallback(nullptr), + dbgDestroyMsgCallback(nullptr) +{ + // List extensions to try to enable. + instance_extension_names.push_back(VK_KHR_SURFACE_EXTENSION_NAME); + instance_extension_names.push_back(VK_KHR_WIN32_SURFACE_EXTENSION_NAME); + device_extension_names.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME); + + if (flags & VULKAN_FLAG_VALIDATE) { + instance_layer_names.push_back("VK_LAYER_LUNARG_Threading"); + instance_layer_names.push_back("VK_LAYER_LUNARG_DrawState"); + instance_layer_names.push_back("VK_LAYER_LUNARG_Image"); + instance_layer_names.push_back("VK_LAYER_LUNARG_MemTracker"); + instance_layer_names.push_back("VK_LAYER_LUNARG_ObjectTracker"); + instance_layer_names.push_back("VK_LAYER_LUNARG_ParamChecker"); + + device_layer_names.push_back("VK_LAYER_LUNARG_Threading"); + device_layer_names.push_back("VK_LAYER_LUNARG_DrawState"); + device_layer_names.push_back("VK_LAYER_LUNARG_Image"); + device_layer_names.push_back("VK_LAYER_LUNARG_MemTracker"); + device_layer_names.push_back("VK_LAYER_LUNARG_ObjectTracker"); + device_layer_names.push_back("VK_LAYER_LUNARG_ParamChecker"); + + instance_extension_names.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME); + } + + VkApplicationInfo app_info = {}; + app_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; + app_info.pNext = NULL; + app_info.pApplicationName = app_name; + app_info.applicationVersion = 1; + app_info.pEngineName = app_name; + app_info.engineVersion = 1; + app_info.apiVersion = VK_API_VERSION; + + VkInstanceCreateInfo inst_info = {}; + inst_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; + inst_info.pNext = NULL; + inst_info.flags = 0; + inst_info.pApplicationInfo = &app_info; + inst_info.enabledLayerCount = (uint32_t)instance_layer_names.size(); + inst_info.ppEnabledLayerNames = instance_layer_names.size() ? instance_layer_names.data() : NULL; + inst_info.enabledExtensionCount = (uint32_t)instance_extension_names.size(); + inst_info.ppEnabledExtensionNames = instance_extension_names.data(); + + VkResult res = vkCreateInstance(&inst_info, NULL, &instance_); + assert(res == VK_SUCCESS); + + GET_INSTANCE_PROC_ADDR(instance_, GetPhysicalDeviceSurfaceSupportKHR); + GET_INSTANCE_PROC_ADDR(instance_, GetPhysicalDeviceSurfaceCapabilitiesKHR); + GET_INSTANCE_PROC_ADDR(instance_, GetPhysicalDeviceSurfaceFormatsKHR); + GET_INSTANCE_PROC_ADDR(instance_, GetPhysicalDeviceSurfacePresentModesKHR); + + uint32_t gpu_count = 1; + res = vkEnumeratePhysicalDevices(instance_, &gpu_count, NULL); + assert(gpu_count); + physical_devices_.resize(gpu_count); + res = vkEnumeratePhysicalDevices(instance_, &gpu_count, physical_devices_.data()); + assert(!res); + + init_global_layer_properties(); + init_global_extension_properties(); + + if (!CheckLayers(instance_layer_properties, instance_layer_names)) { + exit(1); + } + + init_device_layer_properties(); + if (!CheckLayers(device_layer_properties, device_layer_names)) { + exit(1); + } +} + +VulkanContext::~VulkanContext() { + vkDestroyInstance(instance_, NULL); +} + +void vk_transition_to_present(VkCommandBuffer cmd, VkImage image) { + VkImageMemoryBarrier prePresentBarrier = {}; + prePresentBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + prePresentBarrier.pNext = NULL; + prePresentBarrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + prePresentBarrier.dstAccessMask = 0; + prePresentBarrier.oldLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + prePresentBarrier.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; + prePresentBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + prePresentBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + prePresentBarrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + prePresentBarrier.subresourceRange.baseMipLevel = 0; + prePresentBarrier.subresourceRange.levelCount = 1; + prePresentBarrier.subresourceRange.baseArrayLayer = 0; + prePresentBarrier.subresourceRange.layerCount = 1; + prePresentBarrier.image = image; + vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + 0, 0, nullptr, 0, nullptr, 1, &prePresentBarrier); +} + +void vk_transition_from_present(VkCommandBuffer cmd, VkImage image) { + VkImageMemoryBarrier prePresentBarrier = {}; + prePresentBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + prePresentBarrier.pNext = NULL; + prePresentBarrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + prePresentBarrier.dstAccessMask = 0; + prePresentBarrier.oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; + prePresentBarrier.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + prePresentBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + prePresentBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + prePresentBarrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + prePresentBarrier.subresourceRange.baseMipLevel = 0; + prePresentBarrier.subresourceRange.levelCount = 1; + prePresentBarrier.subresourceRange.baseArrayLayer = 0; + prePresentBarrier.subresourceRange.layerCount = 1; + prePresentBarrier.image = image; + vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + 0, 0, nullptr, 0, nullptr, 1, &prePresentBarrier); +} + +VkCommandBuffer VulkanContext::BeginSurfaceRenderPass(VkClearValue clear_values[2]) { + VkSemaphoreCreateInfo acquireSemaphoreCreateInfo; + acquireSemaphoreCreateInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; + acquireSemaphoreCreateInfo.pNext = NULL; + acquireSemaphoreCreateInfo.flags = 0; + + VkResult res = vkCreateSemaphore(device_, + &acquireSemaphoreCreateInfo, + NULL, + &acquireSemaphore); + assert(res == VK_SUCCESS); + + // Get the index of the next available swapchain image, and a semaphore to block on. + res = fpAcquireNextImageKHR(device_, swap_chain_, + UINT64_MAX, + acquireSemaphore, + NULL, + ¤t_buffer); + + VkCommandBufferBeginInfo begin; + begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; + begin.pNext = NULL; + begin.flags = 0; + begin.pInheritanceInfo = nullptr; + vkBeginCommandBuffer(cmd_, &begin); + + // TODO: Deal with the VK_SUBOPTIMAL_KHR and VK_ERROR_OUT_OF_DATE_KHR + // return codes + assert(res == VK_SUCCESS); + + vk_transition_from_present(cmd_, swapChainBuffers[current_buffer].image); + + VkRenderPassBeginInfo rp_begin; + rp_begin.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; + rp_begin.pNext = NULL; + rp_begin.renderPass = surface_render_pass_; + rp_begin.framebuffer = framebuffers_[current_buffer]; + rp_begin.renderArea.offset.x = 0; + rp_begin.renderArea.offset.y = 0; + rp_begin.renderArea.extent.width = width; + rp_begin.renderArea.extent.height = height; + rp_begin.clearValueCount = 2; + rp_begin.pClearValues = clear_values; + + vkCmdBeginRenderPass(cmd_, &rp_begin, VK_SUBPASS_CONTENTS_INLINE); + return cmd_; +} + +void VulkanContext::WaitUntilQueueIdle() { + vkQueueWaitIdle(gfx_queue_); +} + +bool VulkanContext::MemoryTypeFromProperties(uint32_t typeBits, VkFlags requirements_mask, uint32_t *typeIndex) { + // Search memtypes to find first index with those properties + for (uint32_t i = 0; i < 32; i++) { + if ((typeBits & 1) == 1) { + // Type is available, does it match user properties? + if ((memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) { + *typeIndex = i; + return true; + } + } + typeBits >>= 1; + } + // No memory types matched, return failure + return false; +} + +// Terrible for performance! +void vk_submit_sync(VkDevice device, VkSemaphore waitForSemaphore, VkQueue queue, VkCommandBuffer cmd) { + const VkCommandBuffer cmd_bufs[] = { cmd }; + + VkFenceCreateInfo fenceInfo; + VkFence drawFence; + fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; + fenceInfo.pNext = NULL; + fenceInfo.flags = 0; + vkCreateFence(device, &fenceInfo, NULL, &drawFence); + + VkSubmitInfo submit_info[1] = {}; + submit_info[0].pNext = NULL; + submit_info[0].sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + submit_info[0].waitSemaphoreCount = waitForSemaphore ? 1 : 0; + submit_info[0].pWaitSemaphores = waitForSemaphore ? &waitForSemaphore : NULL; + submit_info[0].commandBufferCount = 1; + submit_info[0].pCommandBuffers = cmd_bufs; + submit_info[0].signalSemaphoreCount = 0; + submit_info[0].pSignalSemaphores = NULL; + + /* Queue the command buffer for execution */ + VkResult res = vkQueueSubmit(queue, 1, submit_info, drawFence); + assert(res == VK_SUCCESS); + + do { + res = vkWaitForFences(device, 1, &drawFence, VK_TRUE, FENCE_TIMEOUT); + } while (res != VK_SUCCESS && res != VK_TIMEOUT); + + vkDestroyFence(device, drawFence, NULL); +} + +void VulkanContext::BeginInitCommandBuffer() { + VulkanBeginCommandBuffer(cmd_); +} + +void VulkanContext::SubmitInitCommandBufferSync() { + vk_submit_sync(device_, 0, gfx_queue_, cmd_); +} + +void VulkanContext::InitObjects(HINSTANCE hInstance, HWND hWnd, bool depthPresent) { + InitSurfaceAndQueue(hInstance, hWnd); + InitCommandPool(); + + InitCommandBuffer(); + BeginInitCommandBuffer(); + InitSwapchain(); + InitDepthStencilBuffer(); + + InitSurfaceRenderPass(depthPresent, true); + InitFramebuffers(depthPresent); + SubmitInitCommandBufferSync(); +} + +void VulkanContext::DestroyObjects() { + DestroyFramebuffers(); + DestroySurfaceRenderPass(); + DestroyDepthStencilBuffer(); + DestroySwapChain(); + DestroyCommandBuffer(); + DestroyCommandPool(); +} + +void VulkanContext::EndSurfaceRenderPass() { + vkCmdEndRenderPass(cmd_); + + VkResult res = vkEndCommandBuffer(cmd_); + assert(res == VK_SUCCESS); + + vk_transition_to_present(cmd_, swapChainBuffers[current_buffer].image); + + /* Make sure command buffer is finished before presenting */ + vk_submit_sync(device_, acquireSemaphore, gfx_queue_, cmd_); + // At this point we are certain that acquireSemaphore is of no further use and can be destroyed. + + /* Now present the image in the window */ + + VkPresentInfoKHR present; + present.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; + present.pNext = NULL; + present.swapchainCount = 1; + present.pSwapchains = &swap_chain_; + present.pImageIndices = ¤t_buffer; + present.pWaitSemaphores = NULL; + present.waitSemaphoreCount = 0; + present.pResults = NULL; + + res = fpQueuePresentKHR(gfx_queue_, &present); + // TODO: Deal with the VK_SUBOPTIMAL_WSI and VK_ERROR_OUT_OF_DATE_WSI + // return codes + assert(!res); + + vkDestroySemaphore(device_, acquireSemaphore, NULL); +} + +VkResult VulkanContext::init_layer_extension_properties(layer_properties &layer_props) { + VkExtensionProperties *instance_extensions; + uint32_t instance_extension_count; + VkResult res; + char *layer_name = NULL; + + layer_name = layer_props.properties.layerName; + + do { + res = vkEnumerateInstanceExtensionProperties(layer_name, &instance_extension_count, NULL); + if (res) + return res; + + if (instance_extension_count == 0) { + return VK_SUCCESS; + } + + layer_props.extensions.resize(instance_extension_count); + instance_extensions = layer_props.extensions.data(); + res = vkEnumerateInstanceExtensionProperties( + layer_name, + &instance_extension_count, + instance_extensions); + } while (res == VK_INCOMPLETE); + + return res; +} + +VkResult VulkanContext::init_global_extension_properties() { + uint32_t instance_extension_count; + VkResult res; + + do { + res = vkEnumerateInstanceExtensionProperties(NULL, &instance_extension_count, NULL); + if (res) + return res; + + if (instance_extension_count == 0) { + return VK_SUCCESS; + } + + instance_extension_properties.resize(instance_extension_count); + res = vkEnumerateInstanceExtensionProperties( + NULL, + &instance_extension_count, + instance_extension_properties.data()); + } while (res == VK_INCOMPLETE); + + return res; +} + +VkResult VulkanContext::init_global_layer_properties() { + uint32_t instance_layer_count; + VkLayerProperties *vk_props = NULL; + VkResult res; + + /* + * It's possible, though very rare, that the number of + * instance layers could change. For example, installing something + * could include new layers that the loader would pick up + * between the initial query for the count and the + * request for VkLayerProperties. The loader indicates that + * by returning a VK_INCOMPLETE status and will update the + * the count parameter. + * The count parameter will be updated with the number of + * entries loaded into the data pointer - in case the number + * of layers went down or is smaller than the size given. + */ + do { + res = vkEnumerateInstanceLayerProperties(&instance_layer_count, NULL); + if (res) + return res; + + if (instance_layer_count == 0) { + return VK_SUCCESS; + } + + vk_props = (VkLayerProperties *)realloc(vk_props, instance_layer_count * sizeof(VkLayerProperties)); + + res = vkEnumerateInstanceLayerProperties(&instance_layer_count, vk_props); + } while (res == VK_INCOMPLETE); + + // Now gather the extension list for each instance layer. + for (uint32_t i = 0; i < instance_layer_count; i++) { + layer_properties layer_props; + layer_props.properties = vk_props[i]; + res = init_layer_extension_properties(layer_props); + if (res) + return res; + instance_layer_properties.push_back(layer_props); + } + free(vk_props); + + return res; +} + +VkResult VulkanContext::init_device_extension_properties(layer_properties &layer_props) { + VkExtensionProperties *device_extensions; + uint32_t device_extension_count; + VkResult res; + char *layer_name = NULL; + + layer_name = layer_props.properties.layerName; + do { + res = vkEnumerateDeviceExtensionProperties( + physical_devices_[0], + layer_name, &device_extension_count, NULL); + if (res) + return res; + + if (device_extension_count == 0) { + return VK_SUCCESS; + } + + layer_props.extensions.resize(device_extension_count); + device_extensions = layer_props.extensions.data(); + res = vkEnumerateDeviceExtensionProperties( + physical_devices_[0], + layer_name, + &device_extension_count, + device_extensions); + } while (res == VK_INCOMPLETE); + + return res; +} + +/* + * TODO: function description here + */ +VkResult VulkanContext::init_device_layer_properties() { + uint32_t device_layer_count; + VkLayerProperties *vk_props = NULL; + VkResult res; + + /* + * It's possible, though very rare, that the number of + * instance layers could change. For example, installing something + * could include new layers that the loader would pick up + * between the initial query for the count and the + * request for VkLayerProperties. The loader indicates that + * by returning a VK_INCOMPLETE status and will update the + * the count parameter. + * The count parameter will be updated with the number of + * entries loaded into the data pointer - in case the number + * of layers went down or is smaller than the size given. + */ + do { + res = vkEnumerateDeviceLayerProperties(physical_devices_[0], &device_layer_count, NULL); + if (res) + return res; + + if (device_layer_count == 0) { + return VK_SUCCESS; + } + + vk_props = (VkLayerProperties *)realloc(vk_props, device_layer_count * sizeof(VkLayerProperties)); + + res = vkEnumerateDeviceLayerProperties(physical_devices_[0], &device_layer_count, vk_props); + } while (res == VK_INCOMPLETE); + + /* + * Now gather the extension list for each device layer. + */ + for (uint32_t i = 0; i < device_layer_count; i++) { + layer_properties layer_props; + layer_props.properties = vk_props[i]; + res = init_device_extension_properties(layer_props); + if (res) + return res; + device_layer_properties.push_back(layer_props); + } + free(vk_props); + + return res; +} + +/* + * Return 1 (true) if all layer names specified in check_names + * can be found in given layer properties. + */ +VkBool32 CheckLayers(const std::vector &layer_props, const std::vector &layer_names) { + uint32_t check_count = (uint32_t)layer_names.size(); + uint32_t layer_count = (uint32_t)layer_props.size(); + for (uint32_t i = 0; i < check_count; i++) { + VkBool32 found = 0; + for (uint32_t j = 0; j < layer_count; j++) { + if (!strcmp(layer_names[i], layer_props[j].properties.layerName)) { + found = 1; + } + } + if (!found) { + std::cout << "Cannot find layer: " << layer_names[i] << std::endl; + return 0; + } + } + return 1; +} + +VkResult VulkanContext::CreateDevice(int physical_device) { + VkResult res; + VkDeviceQueueCreateInfo queue_info = {}; + + vkGetPhysicalDeviceQueueFamilyProperties(physical_devices_[0], &queue_count, NULL); + assert(queue_count >= 1); + + queue_props.resize(queue_count); + vkGetPhysicalDeviceQueueFamilyProperties(physical_devices_[0], &queue_count, queue_props.data()); + assert(queue_count >= 1); + + bool found = false; + for (int i = 0; i < queue_count; i++) { + if (queue_props[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) { + queue_info.queueFamilyIndex = i; + found = true; + break; + } + } + assert(found); + assert(queue_count >= 1); + + /* This is as good a place as any to do this */ + vkGetPhysicalDeviceMemoryProperties(physical_devices_[0], &memory_properties); + vkGetPhysicalDeviceProperties(physical_devices_[0], &gpu_props); + + float queue_priorities[1] = { 0.0 }; + queue_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; + queue_info.pNext = NULL; + queue_info.queueCount = 1; + queue_info.pQueuePriorities = queue_priorities; + + VkDeviceCreateInfo device_info = {}; + device_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; + device_info.pNext = NULL; + device_info.queueCreateInfoCount = 1; + device_info.pQueueCreateInfos = &queue_info; + device_info.enabledLayerCount = (uint32_t)device_layer_names.size(); + device_info.ppEnabledLayerNames = + device_info.enabledLayerCount ? device_layer_names.data() : NULL; + device_info.enabledExtensionCount = (uint32_t)device_extension_names.size(); + device_info.ppEnabledExtensionNames = + device_info.enabledExtensionCount ? device_extension_names.data() : NULL; + device_info.pEnabledFeatures = NULL; + + res = vkCreateDevice(physical_devices_[0], &device_info, NULL, &device_); + assert(res == VK_SUCCESS); + + GET_DEVICE_PROC_ADDR(device_, CreateSwapchainKHR); + GET_DEVICE_PROC_ADDR(device_, DestroySwapchainKHR); + GET_DEVICE_PROC_ADDR(device_, GetSwapchainImagesKHR); + GET_DEVICE_PROC_ADDR(device_, AcquireNextImageKHR); + GET_DEVICE_PROC_ADDR(device_, QueuePresentKHR); + + return res; +} + +VkResult VulkanContext::InitDebugMsgCallback(PFN_vkDebugReportCallbackEXT dbgFunc) { + VkResult res; + VkDebugReportCallbackEXT msg_callback; + + dbgCreateMsgCallback = (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(instance_, "vkCreateDebugReportCallbackEXT"); + if (!dbgCreateMsgCallback) { + std::cout << "GetInstanceProcAddr: Unable to find vkDbgCreateMsgCallback function." << std::endl; + return VK_ERROR_INITIALIZATION_FAILED; + } + std::cout << "Got dbgCreateMsgCallback function\n"; + + dbgDestroyMsgCallback = (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(instance_, "vkDestroyDebugReportCallbackEXT"); + if (!dbgDestroyMsgCallback) { + std::cout << "GetInstanceProcAddr: Unable to find vkDbgDestroyMsgCallback function." << std::endl; + return VK_ERROR_INITIALIZATION_FAILED; + } + + VkDebugReportCallbackCreateInfoEXT cb; + cb.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT; + cb.pNext = nullptr; + cb.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT; + cb.pfnCallback = dbgFunc; + cb.pUserData = NULL; + res = dbgCreateMsgCallback(instance_, &cb, nullptr, &msg_callback); + switch (res) { + case VK_SUCCESS: + puts("Successfully created message callback object\n"); + msg_callbacks.push_back(msg_callback); + break; + case VK_ERROR_OUT_OF_HOST_MEMORY: + puts("dbgCreateMsgCallback: out of host memory pointer\n"); + return VK_ERROR_INITIALIZATION_FAILED; + break; + default: + puts("dbgCreateMsgCallback: unknown failure\n"); + return VK_ERROR_INITIALIZATION_FAILED; + break; + } + return res; +} + +void VulkanContext::DestroyDebugMsgCallback() { + while (msg_callbacks.size() > 0) { + dbgDestroyMsgCallback(instance_, msg_callbacks.back(), nullptr); + msg_callbacks.pop_back(); + } +} + +void VulkanContext::InitDepthStencilBuffer() { + VkResult U_ASSERT_ONLY res; + bool U_ASSERT_ONLY pass; + VkImageCreateInfo image_info = {}; + const VkFormat depth_format = VK_FORMAT_D16_UNORM; + VkFormatProperties props; + vkGetPhysicalDeviceFormatProperties(physical_devices_[0], depth_format, &props); + if (props.linearTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) { + image_info.tiling = VK_IMAGE_TILING_LINEAR; + } else if (props.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) { + image_info.tiling = VK_IMAGE_TILING_OPTIMAL; + } else { + /* Try other depth formats? */ + std::cout << "VK_FORMAT_D16_UNORM Unsupported.\n"; + exit(-1); + } + + image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; + image_info.pNext = NULL; + image_info.imageType = VK_IMAGE_TYPE_2D; + image_info.format = depth_format; + image_info.extent.width = width; + image_info.extent.height = height; + image_info.extent.depth = 1; + image_info.mipLevels = 1; + image_info.arrayLayers = 1; + image_info.samples = VK_SAMPLE_COUNT_1_BIT; + image_info.queueFamilyIndexCount = 0; + image_info.pQueueFamilyIndices = NULL; + image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + image_info.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; + image_info.flags = 0; + + VkMemoryAllocateInfo mem_alloc = {}; + mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + mem_alloc.pNext = NULL; + mem_alloc.allocationSize = 0; + mem_alloc.memoryTypeIndex = 0; + + VkImageViewCreateInfo view_info = {}; + view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + view_info.pNext = NULL; + view_info.image = VK_NULL_HANDLE; + view_info.format = depth_format; + view_info.components.r = VK_COMPONENT_SWIZZLE_R; + view_info.components.g = VK_COMPONENT_SWIZZLE_G; + view_info.components.b = VK_COMPONENT_SWIZZLE_B; + view_info.components.a = VK_COMPONENT_SWIZZLE_A; + view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT; + view_info.subresourceRange.baseMipLevel = 0; + view_info.subresourceRange.levelCount = 1; + view_info.subresourceRange.baseArrayLayer = 0; + view_info.subresourceRange.layerCount = 1; + view_info.viewType = VK_IMAGE_VIEW_TYPE_2D; + view_info.flags = 0; + + VkMemoryRequirements mem_reqs; + + depth.format = depth_format; + + /* Create image */ + res = vkCreateImage(device_, &image_info, NULL, &depth.image); + assert(res == VK_SUCCESS); + + vkGetImageMemoryRequirements(device_, depth.image, &mem_reqs); + + mem_alloc.allocationSize = mem_reqs.size; + /* Use the memory properties to determine the type of memory required */ + pass = MemoryTypeFromProperties(mem_reqs.memoryTypeBits, + 0, /* No requirements */ + &mem_alloc.memoryTypeIndex); + assert(pass); + + /* Allocate memory */ + res = vkAllocateMemory(device_, &mem_alloc, NULL, &depth.mem); + assert(res == VK_SUCCESS); + + /* Bind memory */ + res = vkBindImageMemory(device_, depth.image, depth.mem, 0); + assert(res == VK_SUCCESS); + + /* Set the image layout to depth stencil optimal */ + TransitionImageLayout(cmd_, depth.image, + VK_IMAGE_ASPECT_DEPTH_BIT, + VK_IMAGE_LAYOUT_UNDEFINED, + VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); + + /* Create image view */ + view_info.image = depth.image; + res = vkCreateImageView(device_, &view_info, NULL, &depth.view); + assert(res == VK_SUCCESS); +} + +void VulkanContext::InitSurfaceAndQueue(HINSTANCE conn, HWND wnd) { + connection = conn; + window = wnd; + + RECT rc; + GetClientRect(wnd, &rc); + width = rc.right - rc.left; + height = rc.bottom - rc.top; + + VkResult U_ASSERT_ONLY res; + +#ifdef _WIN32 + VkWin32SurfaceCreateInfoKHR win32; + win32.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR; + win32.flags = 0; + win32.hwnd = wnd; + win32.hinstance = conn; + res = vkCreateWin32SurfaceKHR(instance_, &win32, nullptr, &surface); + +#else // _WIN32 + res = vkCreateXcbSurfaceKHR(instance_, info.connection, info.window, NULL, &info.surface); +#endif // _WIN32 + + assert(res == VK_SUCCESS); + + // Iterate over each queue to learn whether it supports presenting: + VkBool32* supportsPresent = new VkBool32[queue_count]; + for (uint32_t i = 0; i < queue_count; i++) { + fpGetPhysicalDeviceSurfaceSupportKHR(physical_devices_[0], i, surface, &supportsPresent[i]); + } + + // Search for a graphics queue and a present queue in the array of queue + // families, try to find one that supports both + uint32_t graphicsQueueNodeIndex = UINT32_MAX; + uint32_t presentQueueNodeIndex = UINT32_MAX; + for (uint32_t i = 0; i < queue_count; i++) { + if ((queue_props[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) != 0) { + if (graphicsQueueNodeIndex == UINT32_MAX) { + graphicsQueueNodeIndex = i; + } + + if (supportsPresent[i] == VK_TRUE) { + graphicsQueueNodeIndex = i; + presentQueueNodeIndex = i; + break; + } + } + } + if (presentQueueNodeIndex == UINT32_MAX) { + // If didn't find a queue that supports both graphics and present, then + // find a separate present queue. + for (uint32_t i = 0; i < queue_count; ++i) { + if (supportsPresent[i] == VK_TRUE) { + presentQueueNodeIndex = i; + break; + } + } + } + delete[] supportsPresent; + + // Generate error if could not find both a graphics and a present queue + if (graphicsQueueNodeIndex == UINT32_MAX || presentQueueNodeIndex == UINT32_MAX) { + std::cout << "Could not find a graphics and a present queue\nCould not find a graphics and a present queue\n"; + exit(-1); + } + + gfx_queue_family_index_ = graphicsQueueNodeIndex; + + // Get the list of VkFormats that are supported: + uint32_t formatCount; + res = fpGetPhysicalDeviceSurfaceFormatsKHR(physical_devices_[0], + surface, + &formatCount, NULL); + assert(res == VK_SUCCESS); + VkSurfaceFormatKHR *surfFormats = new VkSurfaceFormatKHR[formatCount]; + res = fpGetPhysicalDeviceSurfaceFormatsKHR(physical_devices_[0], + surface, + &formatCount, surfFormats); + assert(res == VK_SUCCESS); + // If the format list includes just one entry of VK_FORMAT_UNDEFINED, + // the surface has no preferred format. Otherwise, at least one + // supported format will be returned. + if (formatCount == 1 && surfFormats[0].format == VK_FORMAT_UNDEFINED) { + swapchain_format = VK_FORMAT_B8G8R8A8_UNORM; + } else { + assert(formatCount >= 1); + swapchain_format = surfFormats[0].format; + } + delete[] surfFormats; + + vkGetDeviceQueue(device_, gfx_queue_family_index_, 0, &gfx_queue_); +} + +void VulkanContext::InitSwapchain() { + VkResult U_ASSERT_ONLY res; + VkSurfaceCapabilitiesKHR surfCapabilities; + + res = fpGetPhysicalDeviceSurfaceCapabilitiesKHR(physical_devices_[0], + surface, + &surfCapabilities); + assert(res == VK_SUCCESS); + + uint32_t presentModeCount; + res = fpGetPhysicalDeviceSurfacePresentModesKHR(physical_devices_[0], + surface, + &presentModeCount, NULL); + assert(res == VK_SUCCESS); + VkPresentModeKHR *presentModes = + (VkPresentModeKHR *)malloc(presentModeCount * sizeof(VkPresentModeKHR)); + assert(presentModes); + res = fpGetPhysicalDeviceSurfacePresentModesKHR(physical_devices_[0], + surface, + &presentModeCount, presentModes); + assert(res == VK_SUCCESS); + + VkExtent2D swapChainExtent; + // width and height are either both -1, or both not -1. + if (surfCapabilities.currentExtent.width == -1) + { + // If the surface size is undefined, the size is set to + // the size of the images requested. + swapChainExtent.width = width; + swapChainExtent.height = height; + } else + { + // If the surface size is defined, the swap chain size must match + swapChainExtent = surfCapabilities.currentExtent; + } + + // If mailbox mode is available, use it, as is the lowest-latency non- + // tearing mode. If not, try IMMEDIATE which will usually be available, + // and is fastest (though it tears). If not, fall back to FIFO which is + // always available. + VkPresentModeKHR swapchainPresentMode = VK_PRESENT_MODE_FIFO_KHR; + for (size_t i = 0; i < presentModeCount; i++) { + if (presentModes[i] == VK_PRESENT_MODE_MAILBOX_KHR) { + swapchainPresentMode = VK_PRESENT_MODE_MAILBOX_KHR; + break; + } + if ((swapchainPresentMode != VK_PRESENT_MODE_MAILBOX_KHR) && + (presentModes[i] == VK_PRESENT_MODE_IMMEDIATE_KHR)) { + swapchainPresentMode = VK_PRESENT_MODE_IMMEDIATE_KHR; + } + } + + // Determine the number of VkImage's to use in the swap chain (we desire to + // own only 1 image at a time, besides the images being displayed and + // queued for display): + uint32_t desiredNumberOfSwapChainImages = surfCapabilities.minImageCount + 1; + if ((surfCapabilities.maxImageCount > 0) && + (desiredNumberOfSwapChainImages > surfCapabilities.maxImageCount)) + { + // Application must settle for fewer images than desired: + desiredNumberOfSwapChainImages = surfCapabilities.maxImageCount; + } + + VkSurfaceTransformFlagBitsKHR preTransform; + if (surfCapabilities.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR) { + preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; + } else { + preTransform = surfCapabilities.currentTransform; + } + + VkSwapchainCreateInfoKHR swap_chain_info = {}; + swap_chain_info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; + swap_chain_info.pNext = NULL; + swap_chain_info.surface = surface; + swap_chain_info.minImageCount = desiredNumberOfSwapChainImages; + swap_chain_info.imageFormat = swapchain_format; + swap_chain_info.imageExtent.width = swapChainExtent.width; + swap_chain_info.imageExtent.height = swapChainExtent.height; + swap_chain_info.preTransform = preTransform; + swap_chain_info.imageArrayLayers = 1; + swap_chain_info.presentMode = swapchainPresentMode; + swap_chain_info.oldSwapchain = VK_NULL_HANDLE; + swap_chain_info.clipped = true; + swap_chain_info.imageColorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR; + swap_chain_info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; + swap_chain_info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; + swap_chain_info.queueFamilyIndexCount = 0; + swap_chain_info.pQueueFamilyIndices = NULL; + + res = fpCreateSwapchainKHR(device_, &swap_chain_info, NULL, &swap_chain_); + assert(res == VK_SUCCESS); + + res = fpGetSwapchainImagesKHR(device_, swap_chain_, + &swapchainImageCount, NULL); + assert(res == VK_SUCCESS); + + VkImage* swapchainImages = (VkImage*)malloc(swapchainImageCount * sizeof(VkImage)); + assert(swapchainImages); + res = fpGetSwapchainImagesKHR(device_, swap_chain_, &swapchainImageCount, swapchainImages); + assert(res == VK_SUCCESS); + + for (uint32_t i = 0; i < swapchainImageCount; i++) { + swap_chain_buffer sc_buffer; + + VkImageViewCreateInfo color_image_view = {}; + color_image_view.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + color_image_view.pNext = NULL; + color_image_view.format = swapchain_format; + color_image_view.components.r = VK_COMPONENT_SWIZZLE_R; + color_image_view.components.g = VK_COMPONENT_SWIZZLE_G; + color_image_view.components.b = VK_COMPONENT_SWIZZLE_B; + color_image_view.components.a = VK_COMPONENT_SWIZZLE_A; + color_image_view.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + color_image_view.subresourceRange.baseMipLevel = 0; + color_image_view.subresourceRange.levelCount = 1; + color_image_view.subresourceRange.baseArrayLayer = 0; + color_image_view.subresourceRange.layerCount = 1; + color_image_view.viewType = VK_IMAGE_VIEW_TYPE_2D; + color_image_view.flags = 0; + + sc_buffer.image = swapchainImages[i]; + + // TODO: Pre-set them to PRESENT_SRC_KHR, as the first thing we do after acquiring + // in image to render to will be to transition them away from that. + TransitionImageLayout(cmd_, sc_buffer.image, + VK_IMAGE_ASPECT_COLOR_BIT, + VK_IMAGE_LAYOUT_UNDEFINED, + VK_IMAGE_LAYOUT_PRESENT_SRC_KHR); + + color_image_view.image = sc_buffer.image; + + res = vkCreateImageView(device_, + &color_image_view, NULL, &sc_buffer.view); + swapChainBuffers.push_back(sc_buffer); + assert(res == VK_SUCCESS); + } + free(swapchainImages); + + current_buffer = 0; +} + +void VulkanContext::InitSurfaceRenderPass(bool include_depth, bool clear) { + VkResult U_ASSERT_ONLY res; + /* Need attachments for render target and depth buffer */ + VkAttachmentDescription attachments[2]; + attachments[0].format = swapchain_format; + attachments[0].samples = VK_SAMPLE_COUNT_1_BIT; + attachments[0].loadOp = clear?VK_ATTACHMENT_LOAD_OP_CLEAR:VK_ATTACHMENT_LOAD_OP_LOAD; + attachments[0].storeOp = VK_ATTACHMENT_STORE_OP_STORE; + attachments[0].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; + attachments[0].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; + attachments[0].initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + attachments[0].finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + attachments[0].flags = 0; + + if (include_depth) { + attachments[1].format = depth.format; + attachments[1].samples = VK_SAMPLE_COUNT_1_BIT; + attachments[1].loadOp = clear ? VK_ATTACHMENT_LOAD_OP_CLEAR : VK_ATTACHMENT_LOAD_OP_LOAD; + attachments[1].storeOp = VK_ATTACHMENT_STORE_OP_STORE; + attachments[1].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_LOAD; + attachments[1].stencilStoreOp = VK_ATTACHMENT_STORE_OP_STORE; + attachments[1].initialLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; + attachments[1].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; + attachments[1].flags = 0; + } + + VkAttachmentReference color_reference = {}; + color_reference.attachment = 0; + color_reference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + + VkAttachmentReference depth_reference = {}; + depth_reference.attachment = 1; + depth_reference.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; + + VkSubpassDescription subpass = {}; + subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; + subpass.flags = 0; + subpass.inputAttachmentCount = 0; + subpass.pInputAttachments = NULL; + subpass.colorAttachmentCount = 1; + subpass.pColorAttachments = &color_reference; + subpass.pResolveAttachments = NULL; + subpass.pDepthStencilAttachment = include_depth?&depth_reference:NULL; + subpass.preserveAttachmentCount = 0; + subpass.pPreserveAttachments = NULL; + + VkRenderPassCreateInfo rp_info = {}; + rp_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; + rp_info.pNext = NULL; + rp_info.attachmentCount = include_depth ? 2 : 1; + rp_info.pAttachments = attachments; + rp_info.subpassCount = 1; + rp_info.pSubpasses = &subpass; + rp_info.dependencyCount = 0; + rp_info.pDependencies = NULL; + + res = vkCreateRenderPass(device_, &rp_info, NULL, &surface_render_pass_); + assert(res == VK_SUCCESS); +} + +void VulkanContext::InitFramebuffers(bool include_depth) { + VkResult U_ASSERT_ONLY res; + VkImageView attachments[2]; + attachments[1] = depth.view; + + VkFramebufferCreateInfo fb_info = {}; + fb_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; + fb_info.pNext = NULL; + fb_info.renderPass = surface_render_pass_; + fb_info.attachmentCount = include_depth ? 2 : 1; + fb_info.pAttachments = attachments; + fb_info.width = width; + fb_info.height = height; + fb_info.layers = 1; + + framebuffers_.resize(swapchainImageCount); + + for (uint32_t i = 0; i < swapchainImageCount; i++) { + attachments[0] = swapChainBuffers[i].view; + res = vkCreateFramebuffer(device_, &fb_info, NULL, &framebuffers_[i]); + assert(res == VK_SUCCESS); + } +} + +void VulkanContext::InitCommandPool() { + VkResult U_ASSERT_ONLY res; + + VkCommandPoolCreateInfo cmd_pool_info = {}; + cmd_pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; + cmd_pool_info.pNext = NULL; + cmd_pool_info.queueFamilyIndex = gfx_queue_family_index_; + cmd_pool_info.flags = 0; + + res = vkCreateCommandPool(device_, &cmd_pool_info, NULL, &cmd_pool_); + assert(res == VK_SUCCESS); +} + +void VulkanContext::InitCommandBuffer() { + VkResult U_ASSERT_ONLY res; + + VkCommandBufferAllocateInfo cmd = {}; + cmd.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; + cmd.pNext = NULL; + cmd.commandPool = cmd_pool_; + cmd.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; + cmd.commandBufferCount = 1; + + res = vkAllocateCommandBuffers(device_, &cmd, &this->cmd_); + assert(res == VK_SUCCESS); +} + +void VulkanBeginCommandBuffer(VkCommandBuffer cmd) { + VkResult U_ASSERT_ONLY res; + VkCommandBufferBeginInfo cmd_buf_info = {}; + cmd_buf_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; + cmd_buf_info.pNext = NULL; + cmd_buf_info.flags = 0; + cmd_buf_info.pInheritanceInfo = nullptr; + res = vkBeginCommandBuffer(cmd, &cmd_buf_info); + assert(res == VK_SUCCESS); +} + +void VulkanTexture::Create(VulkanContext *vulkan, int w, int h) { + tex_width = w; + tex_height = h; + + bool U_ASSERT_ONLY pass; + + VkFormatProperties formatProps; + vkGetPhysicalDeviceFormatProperties(vulkan->GetPhysicalDevice(), VK_FORMAT_R8G8B8A8_UNORM, &formatProps); + + /* See if we can use a linear tiled image for a texture, if not, we will need a staging image for the texture data */ + needStaging = (!(formatProps.linearTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)) ? true : false; + + VkImageCreateInfo image_create_info = {}; + image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; + image_create_info.pNext = NULL; + image_create_info.imageType = VK_IMAGE_TYPE_2D; + image_create_info.format = VK_FORMAT_R8G8B8A8_UNORM; + image_create_info.extent.width = tex_width; + image_create_info.extent.height = tex_height; + image_create_info.extent.depth = 1; + image_create_info.mipLevels = 1; + image_create_info.arrayLayers = 1; + image_create_info.samples = VK_SAMPLE_COUNT_1_BIT; + image_create_info.tiling = VK_IMAGE_TILING_LINEAR; + image_create_info.usage = needStaging ? VK_IMAGE_USAGE_TRANSFER_SRC_BIT : + VK_IMAGE_USAGE_SAMPLED_BIT; + image_create_info.queueFamilyIndexCount = 0; + image_create_info.pQueueFamilyIndices = NULL; + image_create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + image_create_info.flags = 0; + + VkMemoryAllocateInfo mem_alloc = {}; + mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + mem_alloc.pNext = NULL; + mem_alloc.allocationSize = 0; + mem_alloc.memoryTypeIndex = 0; + + /* Create a mappable image. It will be the texture if linear images are ok to be textures */ + /* or it will be the staging image if they are not. */ + VkResult res = vkCreateImage(vulkan->Device(), &image_create_info, NULL, &mappableImage); + assert(res == VK_SUCCESS); + + vkGetImageMemoryRequirements(vulkan->Device(), mappableImage, &mem_reqs); + assert(res == VK_SUCCESS); + + mem_alloc.allocationSize = mem_reqs.size; + + /* Find the memory type that is host mappable */ + pass = vulkan->MemoryTypeFromProperties(mem_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, &mem_alloc.memoryTypeIndex); + assert(pass); + + res = vkAllocateMemory(vulkan->Device(), &mem_alloc, NULL, &(mappableMemory)); + assert(res == VK_SUCCESS); + + res = vkBindImageMemory(vulkan->Device(), mappableImage, mappableMemory, 0); + assert(res == VK_SUCCESS); +} + +uint8_t *VulkanTexture::Lock(VulkanContext *vulkan, int *rowPitch) { + VkImageSubresource subres = {}; + subres.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + subres.mipLevel = 0; + subres.arrayLayer = 0; + + VkSubresourceLayout layout; + void *data; + + /* Get the subresource layout so we know what the row pitch is */ + vkGetImageSubresourceLayout(vulkan->device_, mappableImage, &subres, &layout); + + VkResult res = vkMapMemory(vulkan->device_, mappableMemory, 0, mem_reqs.size, 0, &data); + assert(res == VK_SUCCESS); + + *rowPitch = (int)layout.rowPitch; + return (uint8_t *)data; +} + +void VulkanTexture::Unlock(VulkanContext *vulkan) { + vkUnmapMemory(vulkan->device_, mappableMemory); + + if (!needStaging) { + /* If we can use the linear tiled image as a texture, just do it */ + image = mappableImage; + mem = mappableMemory; + imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + TransitionImageLayout(vulkan->GetInitCommandBuffer(), image, + VK_IMAGE_ASPECT_COLOR_BIT, + VK_IMAGE_LAYOUT_UNDEFINED, + imageLayout); + } else { + VkImageCreateInfo image_create_info = {}; + image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; + image_create_info.pNext = NULL; + image_create_info.imageType = VK_IMAGE_TYPE_2D; + image_create_info.format = VK_FORMAT_R8G8B8A8_UNORM; + image_create_info.extent.width = tex_width; + image_create_info.extent.height = tex_height; + image_create_info.extent.depth = 1; + image_create_info.mipLevels = 1; + image_create_info.arrayLayers = 1; + image_create_info.samples = VK_SAMPLE_COUNT_1_BIT; + image_create_info.queueFamilyIndexCount = 0; + image_create_info.pQueueFamilyIndices = NULL; + image_create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + image_create_info.flags = 0; + /* The mappable image cannot be our texture, so create an optimally tiled image and blit to it */ + image_create_info.tiling = VK_IMAGE_TILING_OPTIMAL; + image_create_info.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; + + VkResult res = vkCreateImage(vulkan->device_, &image_create_info, NULL, &image); + assert(res == VK_SUCCESS); + + vkGetImageMemoryRequirements(vulkan->device_, image, &mem_reqs); + + VkMemoryAllocateInfo mem_alloc = {}; + mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + mem_alloc.pNext = NULL; + mem_alloc.allocationSize = 0; + mem_alloc.memoryTypeIndex = 0; + mem_alloc.allocationSize = mem_reqs.size; + + /* Find memory type - dont specify any mapping requirements */ + bool pass = vulkan->MemoryTypeFromProperties(mem_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &mem_alloc.memoryTypeIndex); + assert(pass); + + /* allocate memory */ + res = vkAllocateMemory(vulkan->device_, &mem_alloc, NULL, &mem); + assert(res == VK_SUCCESS); + + /* bind memory */ + res = vkBindImageMemory(vulkan->device_, image, mem, 0); + assert(res == VK_SUCCESS); + + /* Since we're going to blit from the mappable image, set its layout to SOURCE_OPTIMAL */ + /* Side effect is that this will create info.cmd */ + TransitionImageLayout(vulkan->GetInitCommandBuffer(), mappableImage, + VK_IMAGE_ASPECT_COLOR_BIT, + VK_IMAGE_LAYOUT_UNDEFINED, + VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); + + /* Since we're going to blit to the texture image, set its layout to DESTINATION_OPTIMAL */ + TransitionImageLayout(vulkan->GetInitCommandBuffer(), image, + VK_IMAGE_ASPECT_COLOR_BIT, + VK_IMAGE_LAYOUT_UNDEFINED, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); + + VkImageCopy copy_region; + copy_region.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + copy_region.srcSubresource.mipLevel = 0; + copy_region.srcSubresource.baseArrayLayer = 0; + copy_region.srcSubresource.layerCount = 1; + copy_region.srcOffset.x = 0; + copy_region.srcOffset.y = 0; + copy_region.srcOffset.z = 0; + copy_region.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + copy_region.dstSubresource.mipLevel = 0; + copy_region.dstSubresource.baseArrayLayer = 0; + copy_region.dstSubresource.layerCount = 1; + copy_region.dstOffset.x = 0; + copy_region.dstOffset.y = 0; + copy_region.dstOffset.z = 0; + copy_region.extent.width = tex_width; + copy_region.extent.height = tex_height; + copy_region.extent.depth = 1; + + VkCommandBufferBeginInfo cmd_buf_info = {}; + cmd_buf_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; + cmd_buf_info.pNext = NULL; + cmd_buf_info.flags = 0; + cmd_buf_info.pInheritanceInfo = nullptr; + + res = vkBeginCommandBuffer(vulkan->cmd_, &cmd_buf_info); + assert(res == VK_SUCCESS); + + /* Put the copy command into the command buffer */ + vkCmdCopyImage(vulkan->cmd_, + mappableImage, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + 1, ©_region); + + res = vkEndCommandBuffer(vulkan->cmd_); + assert(res == VK_SUCCESS); + const VkCommandBuffer cmd_bufs[] = { vulkan->cmd_ }; + VkFence nullFence = VK_NULL_HANDLE; + + VkSubmitInfo submit_info[1] = {}; + submit_info[0].pNext = NULL; + submit_info[0].sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + submit_info[0].waitSemaphoreCount = 0; + submit_info[0].pWaitSemaphores = NULL; + submit_info[0].commandBufferCount = 1; + submit_info[0].pCommandBuffers = cmd_bufs; + submit_info[0].signalSemaphoreCount = 0; + submit_info[0].pSignalSemaphores = NULL; + + // Queue the command buffer for execution. We can't legally delete the staging source + // until this has completed, so let's throw in a fence. Note that this is a huge stall + // that could be avoided with smarter code - for example we can check the fence the next + // time the texture is used and discard the staging image then. + + VkFence fence = vulkan->CreateFence(); + + res = vkQueueSubmit(vulkan->gfx_queue_, 1, submit_info, fence); + assert(res == VK_SUCCESS); + + /* Set the layout for the texture image from DESTINATION_OPTIMAL to SHADER_READ_ONLY */ + imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + TransitionImageLayout(vulkan->GetInitCommandBuffer(), image, + VK_IMAGE_ASPECT_COLOR_BIT, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + imageLayout); + + vulkan->WaitForFence(fence); + + /* Release the resources for the staging image */ + vkFreeMemory(vulkan->device_, mappableMemory, NULL); + vkDestroyImage(vulkan->device_, mappableImage, NULL); + vkDestroyFence(vulkan->device_, fence, NULL); + } + + VkImageViewCreateInfo view_info = {}; + view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + view_info.pNext = NULL; + view_info.image = VK_NULL_HANDLE; + view_info.viewType = VK_IMAGE_VIEW_TYPE_2D; + view_info.format = VK_FORMAT_R8G8B8A8_UNORM; + view_info.components.r = VK_COMPONENT_SWIZZLE_R; + view_info.components.g = VK_COMPONENT_SWIZZLE_G; + view_info.components.b = VK_COMPONENT_SWIZZLE_B; + view_info.components.a = VK_COMPONENT_SWIZZLE_A; + view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + view_info.subresourceRange.baseMipLevel = 0; + view_info.subresourceRange.levelCount = 1; + view_info.subresourceRange.baseArrayLayer = 0; + view_info.subresourceRange.layerCount = 1; + + /* create image view */ + view_info.image = image; + VkResult res = vkCreateImageView(vulkan->device_, &view_info, NULL, &view); + assert(res == VK_SUCCESS); +} + +void VulkanTexture::Destroy(VulkanContext *vulkan) { + vkDestroyImageView(vulkan->device_, view, NULL); + vkDestroyImage(vulkan->device_, image, NULL); + vkFreeMemory(vulkan->device_, mem, NULL); + view = NULL; + image = NULL; + mem = NULL; +} + +VkFence VulkanContext::CreateFence() { + VkFence fence; + VkFenceCreateInfo fenceInfo; + fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; + fenceInfo.pNext = NULL; + fenceInfo.flags = 0; + vkCreateFence(device_, &fenceInfo, NULL, &fence); + return fence; +} + +void VulkanContext::WaitForFence(VkFence fence) { + vkWaitForFences(device_, 1, &fence, true, 0); +} + +void VulkanContext::DestroyCommandBuffer() { + VkCommandBuffer cmd_bufs[1] = { cmd_ }; + vkFreeCommandBuffers(device_, cmd_pool_, 1, cmd_bufs); + cmd_ = nullptr; +} + +void VulkanContext::DestroyCommandPool() { + vkDestroyCommandPool(device_, cmd_pool_, NULL); + cmd_pool_ = nullptr; +} + +void VulkanContext::DestroyDepthStencilBuffer() { + vkDestroyImageView(device_, depth.view, NULL); + vkDestroyImage(device_, depth.image, NULL); + vkFreeMemory(device_, depth.mem, NULL); + depth.view = NULL; + depth.image = NULL; + depth.mem = NULL; +} + +void VulkanContext::DestroySwapChain() { + for (uint32_t i = 0; i < swapchainImageCount; i++) { + vkDestroyImageView(device_, swapChainBuffers[i].view, NULL); + } + fpDestroySwapchainKHR(device_, swap_chain_, NULL); + swap_chain_ = nullptr; + swapChainBuffers.clear(); +} + +void VulkanContext::DestroyFramebuffers() { + for (uint32_t i = 0; i < framebuffers_.size(); i++) { + vkDestroyFramebuffer(device_, framebuffers_[i], NULL); + } + framebuffers_.clear(); +} + +void VulkanContext::DestroySurfaceRenderPass() { + vkDestroyRenderPass(device_, surface_render_pass_, NULL); + surface_render_pass_ = NULL; +} + +void VulkanContext::DestroyDevice() { + vkDestroyDevice(device_, NULL); + device_ = NULL; +} + +void TransitionImageLayout( + VkCommandBuffer cmd, + VkImage image, + VkImageAspectFlags aspectMask, + VkImageLayout old_image_layout, + VkImageLayout new_image_layout) { + /* DEPENDS on info.cmd and info.queue initialized */ + + VkImageMemoryBarrier image_memory_barrier = {}; + image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + image_memory_barrier.pNext = NULL; + image_memory_barrier.srcAccessMask = 0; + image_memory_barrier.dstAccessMask = 0; + image_memory_barrier.oldLayout = old_image_layout; + image_memory_barrier.newLayout = new_image_layout; + image_memory_barrier.image = image; + image_memory_barrier.subresourceRange.aspectMask = aspectMask; + image_memory_barrier.subresourceRange.baseMipLevel = 0; + image_memory_barrier.subresourceRange.levelCount = 1; + image_memory_barrier.subresourceRange.layerCount = 1; + + if (old_image_layout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) { + image_memory_barrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + } + + if (new_image_layout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) { + /* Make sure anything that was copying from this image has completed */ + image_memory_barrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT; + } + + if (new_image_layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) { + /* Make sure any Copy or CPU writes to image are flushed */ + image_memory_barrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT; + image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; + } + + if (new_image_layout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) { + image_memory_barrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT; + } + + if (new_image_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) { + image_memory_barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT; + } + + VkPipelineStageFlags src_stages = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; + VkPipelineStageFlags dest_stages = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; + + vkCmdPipelineBarrier(cmd, src_stages, dest_stages, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier); +} + +void init_resources(TBuiltInResource &Resources) { + Resources.maxLights = 32; + Resources.maxClipPlanes = 6; + Resources.maxTextureUnits = 32; + Resources.maxTextureCoords = 32; + Resources.maxVertexAttribs = 64; + Resources.maxVertexUniformComponents = 4096; + Resources.maxVaryingFloats = 64; + Resources.maxVertexTextureImageUnits = 32; + Resources.maxCombinedTextureImageUnits = 80; + Resources.maxTextureImageUnits = 32; + Resources.maxFragmentUniformComponents = 4096; + Resources.maxDrawBuffers = 32; + Resources.maxVertexUniformVectors = 128; + Resources.maxVaryingVectors = 8; + Resources.maxFragmentUniformVectors = 16; + Resources.maxVertexOutputVectors = 16; + Resources.maxFragmentInputVectors = 15; + Resources.minProgramTexelOffset = -8; + Resources.maxProgramTexelOffset = 7; + Resources.maxClipDistances = 8; + Resources.maxComputeWorkGroupCountX = 65535; + Resources.maxComputeWorkGroupCountY = 65535; + Resources.maxComputeWorkGroupCountZ = 65535; + Resources.maxComputeWorkGroupSizeX = 1024; + Resources.maxComputeWorkGroupSizeY = 1024; + Resources.maxComputeWorkGroupSizeZ = 64; + Resources.maxComputeUniformComponents = 1024; + Resources.maxComputeTextureImageUnits = 16; + Resources.maxComputeImageUniforms = 8; + Resources.maxComputeAtomicCounters = 8; + Resources.maxComputeAtomicCounterBuffers = 1; + Resources.maxVaryingComponents = 60; + Resources.maxVertexOutputComponents = 64; + Resources.maxGeometryInputComponents = 64; + Resources.maxGeometryOutputComponents = 128; + Resources.maxFragmentInputComponents = 128; + Resources.maxImageUnits = 8; + Resources.maxCombinedImageUnitsAndFragmentOutputs = 8; + Resources.maxCombinedShaderOutputResources = 8; + Resources.maxImageSamples = 0; + Resources.maxVertexImageUniforms = 0; + Resources.maxTessControlImageUniforms = 0; + Resources.maxTessEvaluationImageUniforms = 0; + Resources.maxGeometryImageUniforms = 0; + Resources.maxFragmentImageUniforms = 8; + Resources.maxCombinedImageUniforms = 8; + Resources.maxGeometryTextureImageUnits = 16; + Resources.maxGeometryOutputVertices = 256; + Resources.maxGeometryTotalOutputComponents = 1024; + Resources.maxGeometryUniformComponents = 1024; + Resources.maxGeometryVaryingComponents = 64; + Resources.maxTessControlInputComponents = 128; + Resources.maxTessControlOutputComponents = 128; + Resources.maxTessControlTextureImageUnits = 16; + Resources.maxTessControlUniformComponents = 1024; + Resources.maxTessControlTotalOutputComponents = 4096; + Resources.maxTessEvaluationInputComponents = 128; + Resources.maxTessEvaluationOutputComponents = 128; + Resources.maxTessEvaluationTextureImageUnits = 16; + Resources.maxTessEvaluationUniformComponents = 1024; + Resources.maxTessPatchComponents = 120; + Resources.maxPatchVertices = 32; + Resources.maxTessGenLevel = 64; + Resources.maxViewports = 16; + Resources.maxVertexAtomicCounters = 0; + Resources.maxTessControlAtomicCounters = 0; + Resources.maxTessEvaluationAtomicCounters = 0; + Resources.maxGeometryAtomicCounters = 0; + Resources.maxFragmentAtomicCounters = 8; + Resources.maxCombinedAtomicCounters = 8; + Resources.maxAtomicCounterBindings = 1; + Resources.maxVertexAtomicCounterBuffers = 0; + Resources.maxTessControlAtomicCounterBuffers = 0; + Resources.maxTessEvaluationAtomicCounterBuffers = 0; + Resources.maxGeometryAtomicCounterBuffers = 0; + Resources.maxFragmentAtomicCounterBuffers = 1; + Resources.maxCombinedAtomicCounterBuffers = 1; + Resources.maxAtomicCounterBufferSize = 16384; + Resources.maxTransformFeedbackBuffers = 4; + Resources.maxTransformFeedbackInterleavedComponents = 64; + Resources.maxCullDistances = 8; + Resources.maxCombinedClipAndCullDistances = 8; + Resources.maxSamples = 4; + Resources.limits.nonInductiveForLoops = 1; + Resources.limits.whileLoops = 1; + Resources.limits.doWhileLoops = 1; + Resources.limits.generalUniformIndexing = 1; + Resources.limits.generalAttributeMatrixVectorIndexing = 1; + Resources.limits.generalVaryingIndexing = 1; + Resources.limits.generalSamplerIndexing = 1; + Resources.limits.generalVariableIndexing = 1; + Resources.limits.generalConstantMatrixVectorIndexing = 1; +} + +EShLanguage FindLanguage(const VkShaderStageFlagBits shader_type) { + switch (shader_type) { + case VK_SHADER_STAGE_VERTEX_BIT: + return EShLangVertex; + + case VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT: + return EShLangTessControl; + + case VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT: + return EShLangTessEvaluation; + + case VK_SHADER_STAGE_GEOMETRY_BIT: + return EShLangGeometry; + + case VK_SHADER_STAGE_FRAGMENT_BIT: + return EShLangFragment; + + case VK_SHADER_STAGE_COMPUTE_BIT: + return EShLangCompute; + + default: + return EShLangVertex; + } +} + +// +// Compile a given string containing GLSL into SPV for use by VK +// Return value of false means an error was encountered. +// +bool GLSLtoSPV(const VkShaderStageFlagBits shader_type, + const char *pshader, + std::vector &spirv) { + + glslang::TProgram& program = *new glslang::TProgram; + const char *shaderStrings[1]; + TBuiltInResource Resources; + init_resources(Resources); + + // Enable SPIR-V and Vulkan rules when parsing GLSL + EShMessages messages = (EShMessages)(EShMsgSpvRules | EShMsgVulkanRules); + + EShLanguage stage = FindLanguage(shader_type); + glslang::TShader* shader = new glslang::TShader(stage); + + shaderStrings[0] = pshader; + shader->setStrings(shaderStrings, 1); + + if (!shader->parse(&Resources, 100, false, messages)) { + puts(shader->getInfoLog()); + puts(shader->getInfoDebugLog()); + return false; // something didn't work + } + + program.addShader(shader); + + // + // Program-level processing... + // + + if (!program.link(messages)) { + puts(shader->getInfoLog()); + puts(shader->getInfoDebugLog()); + return false; + } + + glslang::GlslangToSpv(*program.getIntermediate(stage), spirv); + + return true; +} + +void init_glslang() { + glslang::InitializeProcess(); +} + +void finalize_glslang() { + glslang::FinalizeProcess(); +} diff --git a/ext/native/thin3d/VulkanContext.h b/ext/native/thin3d/VulkanContext.h new file mode 100644 index 0000000000..e1beaa09ee --- /dev/null +++ b/ext/native/thin3d/VulkanContext.h @@ -0,0 +1,277 @@ +/* + * Vulkan Samples Kit + * + * Copyright (C) 2015 Valve Corporation + * Copyright (C) 2015 Google, Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +#ifndef UTIL_INIT +#define UTIL_INIT + +#include +#include + +#ifdef _WIN32 +#define WIN32_LEAN_AND_MEAN +#define VK_USE_PLATFORM_WIN32_KHR +#define NOMINMAX /* Don't let Windows define min() or max() */ +#define APP_NAME_STR_LEN 80 +#include +#else // _WIN32 +#define VK_USE_PLATFORM_XCB_KHR +#include +#endif // _WIN32 + +#include "ext/vulkan/vulkan.h" +#include "ext/vulkan/vk_sdk_platform.h" + + /* Amount of time, in nanoseconds, to wait for a command buffer to complete */ +#define FENCE_TIMEOUT 10000000000 + +#if defined(NDEBUG) && defined(__GNUC__) +#define U_ASSERT_ONLY __attribute__((unused)) +#else +#define U_ASSERT_ONLY +#endif + +enum { + VULKAN_FLAG_VALIDATE = 1, +}; + +// A layer can expose extensions, keep track of those extensions here. +struct layer_properties { + VkLayerProperties properties; + std::vector extensions; +}; + +// VulkanContext sets up the basics necessary for rendering to a window, including framebuffers etc. +// Optionally, it can create a depth buffer for you as well. +class VulkanContext { +public: + VulkanContext(const char *app_name, uint32_t flags); + ~VulkanContext(); + + VkResult CreateDevice(int physical_device); + + VkDevice Device() { + return device_; + } + + void InitSurfaceAndQueue(HINSTANCE conn, HWND wnd); + void InitSwapchain(); + void InitSurfaceRenderPass(bool include_depth, bool clear); + void InitFramebuffers(bool include_depth); + void InitDepthStencilBuffer(); + void InitCommandPool(); + void InitCommandBuffer(); + + void InitObjects(HINSTANCE hInstance, HWND hWnd, bool depthPresent); + void DestroyObjects(); + + void BeginInitCommandBuffer(); + void SubmitInitCommandBufferSync(); + VkCommandBuffer GetInitCommandBuffer() { + return cmd_; + } + + void DestroySurfaceRenderPass(); + void DestroyFramebuffers(); + void DestroySwapChain(); + void DestroyDepthStencilBuffer(); + void DestroyCommandPool(); + void DestroyCommandBuffer(); + void DestroyDevice(); + + void WaitUntilQueueIdle(); + + // Utility functions for shorter code + VkFence CreateFence(); + void WaitForFence(VkFence fence); + + int GetWidth() { return width; } + int GetHeight() { return height; } + + // The surface render pass is special because it has to acquire the backbuffer, and may thus "block". + // Use the returned command buffer to enqueue commands. Might be a good idea to use secondary cmd buffers. + VkCommandBuffer BeginSurfaceRenderPass(VkClearValue clear_values[2]); + + void EndSurfaceRenderPass(); + + bool MemoryTypeFromProperties(uint32_t typeBits, VkFlags requirements_mask, uint32_t *typeIndex); + + VkResult InitDebugMsgCallback(PFN_vkDebugReportCallbackEXT dbgFunc); + void DestroyDebugMsgCallback(); + + VkSemaphore acquireSemaphore; + + VkRenderPass GetSurfaceRenderPass() { + return surface_render_pass_; + } + + VkPhysicalDevice GetPhysicalDevice() { + return physical_devices_[0]; + } + + VkQueue GetGraphicsQueue() { + return gfx_queue_; + } + + int GetGraphicsQueueFamilyIndex() { + return gfx_queue_family_index_; + } + + VkResult init_global_extension_properties(); + VkResult init_layer_extension_properties(layer_properties &layer_props); + + VkResult init_global_layer_properties(); + + VkResult init_device_extension_properties(layer_properties &layer_props); + VkResult init_device_layer_properties(); + + +#ifdef _WIN32 +#define APP_NAME_STR_LEN 80 + HINSTANCE connection; // hInstance - Windows Instance + char name[APP_NAME_STR_LEN]; // Name to put on the window/icon + HWND window; // hWnd - window handle +#else // _WIN32 + xcb_connection_t *connection; + xcb_screen_t *screen; + xcb_window_t window; + xcb_intern_atom_reply_t *atom_wm_delete_window; +#endif // _WIN32 + + VkCommandPool cmd_pool_; + VkCommandBuffer cmd_; // Buffer for initialization commands + + VkInstance instance_; + VkDevice device_; + VkQueue gfx_queue_; + + VkSurfaceKHR surface; + bool prepared; + bool use_staging_buffer_; + + std::vector instance_layer_names; + std::vector instance_extension_names; + std::vector instance_layer_properties; + std::vector instance_extension_properties; + + std::vector device_layer_names; + std::vector device_extension_names; + std::vector device_layer_properties; + std::vector device_extension_properties; + std::vector physical_devices_; + + uint32_t gfx_queue_family_index_; + VkPhysicalDeviceProperties gpu_props; + std::vector queue_props; + VkPhysicalDeviceMemoryProperties memory_properties; + +private: + struct swap_chain_buffer { + VkImage image; + VkImageView view; + }; + + // Swap chain + int width, height; + VkFormat swapchain_format; + std::vector framebuffers_; + uint32_t swapchainImageCount; + VkSwapchainKHR swap_chain_; + std::vector swapChainBuffers; + + + // Simple loader for the WSI extension. + PFN_vkGetPhysicalDeviceSurfaceSupportKHR fpGetPhysicalDeviceSurfaceSupportKHR; + PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR fpGetPhysicalDeviceSurfaceCapabilitiesKHR; + PFN_vkGetPhysicalDeviceSurfaceFormatsKHR fpGetPhysicalDeviceSurfaceFormatsKHR; + PFN_vkGetPhysicalDeviceSurfacePresentModesKHR fpGetPhysicalDeviceSurfacePresentModesKHR; + PFN_vkCreateSwapchainKHR fpCreateSwapchainKHR; + PFN_vkDestroySwapchainKHR fpDestroySwapchainKHR; + PFN_vkGetSwapchainImagesKHR fpGetSwapchainImagesKHR; + PFN_vkAcquireNextImageKHR fpAcquireNextImageKHR; + PFN_vkQueuePresentKHR fpQueuePresentKHR; + // And the DEBUG_REPORT extension. + PFN_vkCreateDebugReportCallbackEXT dbgCreateMsgCallback; + PFN_vkDestroyDebugReportCallbackEXT dbgDestroyMsgCallback; + std::vector msg_callbacks; + + struct { + VkFormat format; + VkImage image; + VkDeviceMemory mem; + VkImageView view; + } depth; + + VkRenderPass surface_render_pass_; + uint32_t current_buffer; + uint32_t queue_count; +}; + +// Wrapper around what you need to use a texture. +// Not very optimal - if you have many small textures you should use other strategies. +class VulkanTexture { +public: + VkImage image; + VkImageLayout imageLayout; + + VkDeviceMemory mem; + VkImageView view; + + int32_t tex_width, tex_height; + + // Always call Create, Lock, Unlock. Unlock performs the upload if necessary. + + void Create(VulkanContext *vulkan, int w, int h); + uint8_t *Lock(VulkanContext *vulkan, int *rowPitch); + void Unlock(VulkanContext *vulkan); + + void Destroy(VulkanContext *vulkan); + +private: + VkImage mappableImage; + VkDeviceMemory mappableMemory; + VkMemoryRequirements mem_reqs; + bool needStaging; +}; + +VkBool32 CheckLayers(const std::vector &layer_props, const std::vector &layer_names); + +void VulkanBeginCommandBuffer(VkCommandBuffer cmd); + +void vk_submit_sync(VkDevice device, VkSemaphore waitForSemaphore, VkQueue queue, VkCommandBuffer cmd); + +void init_glslang(); +void finalize_glslang(); + +bool GLSLtoSPV(const VkShaderStageFlagBits shader_type, const char *pshader, std::vector &spirv); + +void TransitionImageLayout( + VkCommandBuffer cmd, + VkImage image, + VkImageAspectFlags aspectMask, + VkImageLayout old_image_layout, + VkImageLayout new_image_layout); + +#endif // UTIL_INIT + diff --git a/ext/native/thin3d/thin3d.cpp b/ext/native/thin3d/thin3d.cpp index 78dd46a9d8..cafbf41e25 100644 --- a/ext/native/thin3d/thin3d.cpp +++ b/ext/native/thin3d/thin3d.cpp @@ -7,6 +7,10 @@ #include "file/vfs.h" #include "ext/jpge/jpgd.h" +// ================================== PIXEL/FRAGMENT SHADERS + +// The Vulkan ones can be re-used with modern GL later if desired, as they're just GLSL. + static const char * const glsl_fsTexCol = "#ifdef GL_ES\n" "precision lowp float;\n" @@ -23,6 +27,16 @@ static const char * const hlslFsTexCol = " return input.color * tex2D(Sampler0, input.uv);\n" "}\n"; +static const char * const vulkan_fsTexCol = +"#version 140\n" +"#extension GL_ARB_separate_shader_objects : enable\n" +"#extension GL_ARB_shading_language_420pack : enable\n" +"layout(location = 0) in vec4 oColor0;\n" +"layout(location = 1) in vec2 oTexCoord0;\n" +"layout(location = 0) out vec4 fragColor0\n;" +"layout(binding = 2) uniform sampler2D Sampler0;\n" +"void main() { fragColor0 = texture2D(Sampler0, oTexCoord0) * oColor0; }\n"; + static const char * const glsl_fsCol = "#ifdef GL_ES\n" "precision lowp float;\n" @@ -36,6 +50,18 @@ static const char * const hlslFsCol = " return input.color;\n" "}\n"; +static const char * const vulkan_fsCol = +"#version 140\n" +"#extension GL_ARB_separate_shader_objects : enable\n" +"#extension GL_ARB_shading_language_420pack : enable\n" +"layout(location = 0) in vec4 oColor0;\n" +"layout(location = 0) out vec4 fragColor0\n;" +"void main() { fragColor0 = oColor0; }\n"; + + + +// ================================== VERTEX SHADERS + static const char * const glsl_vsCol = "attribute vec3 Position;\n" "attribute vec4 Color0;\n" @@ -57,6 +83,22 @@ static const char * const hlslVsCol = " return output;\n" "}\n"; +static const char * const vulkan_vsCol = +"#version 140\n" +"#extension GL_ARB_separate_shader_objects : enable\n" +"#extension GL_ARB_shading_language_420pack : enable\n" +"layout (std140, binding = 1) uniform bufferVals {\n" +" mat4 WorldViewProj;\n" +"} myBufferVals;\n" +"layout (location = 0) in vec4 pos;\n" +"layout (location = 1) in vec4 inColor;\n" +"layout (location = 0) out vec4 outColor;\n" +"void main() {\n" +" outColor = inColor;\n" +" gl_Position = myBufferVals.WorldViewProj * pos;\n" +"}\n"; + + static const char * const glsl_vsTexCol = "attribute vec3 Position;\n" "attribute vec4 Color0;\n" @@ -82,6 +124,25 @@ static const char * const hlslVsTexCol = " return output;\n" "}\n"; +static const char * const vulkan_vsTexCol = +"#version 140\n" +"#extension GL_ARB_separate_shader_objects : enable\n" +"#extension GL_ARB_shading_language_420pack : enable\n" +"layout (std140, binding = 1) uniform bufferVals {\n" +" mat4 WorldViewProj;\n" +"} myBufferVals;\n" +"layout (location = 0) in vec4 pos;\n" +"layout (location = 1) in vec4 inColor;\n" +"layout (location = 2) in vec2 inTexCoord;\n" +"layout (location = 0) out vec4 outColor;\n" +"layout (location = 1) out vec2 outTexCoord;\n" +"void main() {\n" +" outColor = inColor;\n" +" outTexCoord = inTexCoord;\n" +" gl_Position = myBufferVals.WorldViewProj * pos;\n" +"}\n"; + + void Thin3DContext::CreatePresets() { // Build prebuilt objects T3DBlendStateDesc off = { false }; @@ -100,11 +161,11 @@ void Thin3DContext::CreatePresets() { sampsPresets_[SAMPS_NEAREST] = CreateSamplerState(nearest); sampsPresets_[SAMPS_LINEAR] = CreateSamplerState(linear); - vsPresets_[VS_TEXTURE_COLOR_2D] = CreateVertexShader(glsl_vsTexCol, hlslVsTexCol); - vsPresets_[VS_COLOR_2D] = CreateVertexShader(glsl_vsCol, hlslVsCol); + vsPresets_[VS_TEXTURE_COLOR_2D] = CreateVertexShader(glsl_vsTexCol, hlslVsTexCol, vulkan_vsTexCol); + vsPresets_[VS_COLOR_2D] = CreateVertexShader(glsl_vsCol, hlslVsCol, vulkan_vsCol); - fsPresets_[FS_TEXTURE_COLOR_2D] = CreateFragmentShader(glsl_fsTexCol, hlslFsTexCol); - fsPresets_[FS_COLOR_2D] = CreateFragmentShader(glsl_fsCol, hlslFsCol); + fsPresets_[FS_TEXTURE_COLOR_2D] = CreateFragmentShader(glsl_fsTexCol, hlslFsTexCol, vulkan_fsTexCol); + fsPresets_[FS_COLOR_2D] = CreateFragmentShader(glsl_fsCol, hlslFsCol, vulkan_fsCol); ssPresets_[SS_TEXTURE_COLOR_2D] = CreateShaderSet(vsPresets_[VS_TEXTURE_COLOR_2D], fsPresets_[FS_TEXTURE_COLOR_2D]); ssPresets_[SS_COLOR_2D] = CreateShaderSet(vsPresets_[VS_COLOR_2D], fsPresets_[FS_COLOR_2D]); diff --git a/ext/native/thin3d/thin3d.h b/ext/native/thin3d/thin3d.h index 1593778d56..131ad0a60e 100644 --- a/ext/native/thin3d/thin3d.h +++ b/ext/native/thin3d/thin3d.h @@ -334,8 +334,8 @@ public: Thin3DShaderSet *GetShaderSetPreset(T3DShaderSetPreset preset) { return ssPresets_[preset]; } // The implementation makes the choice of which shader code to use. - virtual Thin3DShader *CreateVertexShader(const char *glsl_source, const char *hlsl_source) = 0; - virtual Thin3DShader *CreateFragmentShader(const char *glsl_source, const char *hlsl_source) = 0; + virtual Thin3DShader *CreateVertexShader(const char *glsl_source, const char *hlsl_source, const char *vulkan_source) = 0; + virtual Thin3DShader *CreateFragmentShader(const char *glsl_source, const char *hlsl_source, const char *vulkan_source) = 0; // Bound state objects. Too cumbersome to add them all as parameters to Draw. virtual void SetBlendState(Thin3DBlendState *state) = 0; @@ -359,8 +359,15 @@ public: virtual void Draw(T3DPrimitive prim, Thin3DShaderSet *pipeline, Thin3DVertexFormat *format, Thin3DBuffer *vdata, int vertexCount, int offset) = 0; virtual void DrawIndexed(T3DPrimitive prim, Thin3DShaderSet *pipeline, Thin3DVertexFormat *format, Thin3DBuffer *vdata, Thin3DBuffer *idata, int vertexCount, int offset) = 0; virtual void DrawUP(T3DPrimitive prim, Thin3DShaderSet *pipeline, Thin3DVertexFormat *format, const void *vdata, int vertexCount) = 0; + + // Render pass management. Default implementations here. + virtual void Begin(bool clear, uint32_t colorval, float depthVal, int stencilVal) { + Clear(0xF, colorval, depthVal, stencilVal); + } + virtual void End() {} + virtual void Clear(int mask, uint32_t colorval, float depthVal, int stencilVal) = 0; - + // Necessary to correctly flip scissor rectangles etc for OpenGL. void SetTargetSize(int w, int h) { targetWidth_ = w; @@ -393,3 +400,7 @@ struct IDirect3DDevice9Ex; struct IDirect3D9Ex; Thin3DContext *T3DCreateDX9Context(IDirect3D9 *d3d, IDirect3D9Ex *d3dEx, int adapterId, IDirect3DDevice9 *device, IDirect3DDevice9Ex *deviceEx); #endif + +class VulkanContext; + +Thin3DContext *T3DCreateVulkanContext(VulkanContext *context); diff --git a/ext/native/thin3d/thin3d_d3d9.cpp b/ext/native/thin3d/thin3d_d3d9.cpp index d5e1e3edf8..19d373c56f 100644 --- a/ext/native/thin3d/thin3d_d3d9.cpp +++ b/ext/native/thin3d/thin3d_d3d9.cpp @@ -434,8 +434,8 @@ public: Thin3DTexture *CreateTexture() override; Thin3DTexture *CreateTexture(T3DTextureType type, T3DImageFormat format, int width, int height, int depth, int mipLevels) override; - Thin3DShader *CreateVertexShader(const char *glsl_source, const char *hlsl_source) override; - Thin3DShader *CreateFragmentShader(const char *glsl_source, const char *hlsl_source) override; + Thin3DShader *CreateVertexShader(const char *glsl_source, const char *hlsl_source, const char *vulkan_source) override; + Thin3DShader *CreateFragmentShader(const char *glsl_source, const char *hlsl_source, const char *vulkan_source) override; // Bound state objects. Too cumbersome to add them all as parameters to Draw. void SetBlendState(Thin3DBlendState *state) { @@ -502,7 +502,7 @@ Thin3DDX9Context::Thin3DDX9Context(IDirect3D9 *d3d, IDirect3D9Ex *d3dEx, int ada Thin3DDX9Context::~Thin3DDX9Context() { } -Thin3DShader *Thin3DDX9Context::CreateVertexShader(const char *glsl_source, const char *hlsl_source) { +Thin3DShader *Thin3DDX9Context::CreateVertexShader(const char *glsl_source, const char *hlsl_source, const char *vulkan_source) { Thin3DDX9Shader *shader = new Thin3DDX9Shader(false); if (shader->Compile(device_, hlsl_source, "vs_2_0")) { return shader; @@ -512,7 +512,7 @@ Thin3DShader *Thin3DDX9Context::CreateVertexShader(const char *glsl_source, cons } } -Thin3DShader *Thin3DDX9Context::CreateFragmentShader(const char *glsl_source, const char *hlsl_source) { +Thin3DShader *Thin3DDX9Context::CreateFragmentShader(const char *glsl_source, const char *hlsl_source, const char *vulkan_source) { Thin3DDX9Shader *shader = new Thin3DDX9Shader(true); if (shader->Compile(device_, hlsl_source, "ps_2_0")) { return shader; diff --git a/ext/native/thin3d/thin3d_gl.cpp b/ext/native/thin3d/thin3d_gl.cpp index 70453fc322..c04855a2db 100644 --- a/ext/native/thin3d/thin3d_gl.cpp +++ b/ext/native/thin3d/thin3d_gl.cpp @@ -386,8 +386,8 @@ public: } // The implementation makes the choice of which shader code to use. - Thin3DShader *CreateVertexShader(const char *glsl_source, const char *hlsl_source) override; - Thin3DShader *CreateFragmentShader(const char *glsl_source, const char *hlsl_source) override; + Thin3DShader *CreateVertexShader(const char *glsl_source, const char *hlsl_source, const char *vulkan_source) override; + Thin3DShader *CreateFragmentShader(const char *glsl_source, const char *hlsl_source, const char *vulkan_source) override; void SetScissorEnabled(bool enable) override { if (enable) { @@ -737,7 +737,7 @@ void Thin3DGLContext::SetTextures(int start, int count, Thin3DTexture **textures } -Thin3DShader *Thin3DGLContext::CreateVertexShader(const char *glsl_source, const char *hlsl_source) { +Thin3DShader *Thin3DGLContext::CreateVertexShader(const char *glsl_source, const char *hlsl_source, const char *vulkan_source) { Thin3DGLShader *shader = new Thin3DGLShader(false); if (shader->Compile(glsl_source)) { return shader; @@ -747,7 +747,7 @@ Thin3DShader *Thin3DGLContext::CreateVertexShader(const char *glsl_source, const } } -Thin3DShader *Thin3DGLContext::CreateFragmentShader(const char *glsl_source, const char *hlsl_source) { +Thin3DShader *Thin3DGLContext::CreateFragmentShader(const char *glsl_source, const char *hlsl_source, const char *vulkan_source) { Thin3DGLShader *shader = new Thin3DGLShader(true); if (shader->Compile(glsl_source)) { return shader; diff --git a/ext/native/thin3d/thin3d_vulkan.cpp b/ext/native/thin3d/thin3d_vulkan.cpp new file mode 100644 index 0000000000..f9426d61cb --- /dev/null +++ b/ext/native/thin3d/thin3d_vulkan.cpp @@ -0,0 +1,1384 @@ +// Copyright (c) 2015- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#include +#include +#include +#include +#include + +#include "base/logging.h" +#include "base/display.h" +#include "image/zim_load.h" +#include "math/lin/matrix4x4.h" +#include "math/dataconv.h" +#include "thin3d/thin3d.h" +#include "thin3d/vulkan_utils.h" +#include "thin3d/VulkanContext.h" + +// We use a simple descriptor set for all rendering: 1 sampler, 1 texture, 1 UBO binding point. +// binding 0 - vertex data +// binding 1 - uniform data +// binding 2 - sampler + +#define VK_PROTOTYPES +#include "ext/vulkan/vulkan.h" + +// This can actually be replaced with a cast as the values are in the right order. +static const VkCompareOp compToVK[] = { + VK_COMPARE_OP_NEVER, + VK_COMPARE_OP_LESS, + VK_COMPARE_OP_EQUAL, + VK_COMPARE_OP_LESS_OR_EQUAL, + VK_COMPARE_OP_GREATER, + VK_COMPARE_OP_NOT_EQUAL, + VK_COMPARE_OP_GREATER_OR_EQUAL, + VK_COMPARE_OP_ALWAYS +}; + +// So can this. +static const VkBlendOp blendEqToGL[] = { + VK_BLEND_OP_ADD, + VK_BLEND_OP_SUBTRACT, + VK_BLEND_OP_REVERSE_SUBTRACT, +}; + +static const VkBlendFactor blendFactorToVk[] = { + VK_BLEND_FACTOR_ZERO, + VK_BLEND_FACTOR_ONE, + VK_BLEND_FACTOR_SRC_COLOR, + VK_BLEND_FACTOR_SRC_ALPHA, + VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR, + VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, + VK_BLEND_FACTOR_DST_COLOR, + VK_BLEND_FACTOR_DST_ALPHA, + VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR, + VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA, + VK_BLEND_FACTOR_CONSTANT_COLOR, +}; + +static const VkLogicOp logicOpToVK[] = { + VK_LOGIC_OP_CLEAR, + VK_LOGIC_OP_SET, + VK_LOGIC_OP_COPY, + VK_LOGIC_OP_COPY_INVERTED, + VK_LOGIC_OP_NO_OP, + VK_LOGIC_OP_INVERT, + VK_LOGIC_OP_AND, + VK_LOGIC_OP_NAND, + VK_LOGIC_OP_OR, + VK_LOGIC_OP_NOR, + VK_LOGIC_OP_XOR, + VK_LOGIC_OP_EQUIVALENT, + VK_LOGIC_OP_AND_REVERSE, + VK_LOGIC_OP_AND_INVERTED, + VK_LOGIC_OP_OR_REVERSE, + VK_LOGIC_OP_OR_INVERTED, +}; + +static const VkPrimitiveTopology primToVK[] = { + VK_PRIMITIVE_TOPOLOGY_POINT_LIST, + VK_PRIMITIVE_TOPOLOGY_LINE_LIST, + VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, +}; + +static inline void Uint8x4ToFloat4(uint32_t u, float f[4]) { + f[0] = ((u >> 0) & 0xFF) * (1.0f / 255.0f); + f[1] = ((u >> 8) & 0xFF) * (1.0f / 255.0f); + f[2] = ((u >> 16) & 0xFF) * (1.0f / 255.0f); + f[3] = ((u >> 24) & 0xFF) * (1.0f / 255.0f); +} + + +// Use these to push vertex, index and uniform data. +// TODO: Make this dynamically grow by chaining new buffers in the future. +// Until then, we cap at a maximum size. +// We'll have two of these that we alternate between on each frame. +// These will only be used for the "Thin3D" system - the PSP emulation etc will have +// their own similar buffer solutions. +class VulkanPushBuffer { +public: + VulkanPushBuffer(VkDevice device, VulkanDeviceMemoryManager *memMan, size_t size) : offset_(0), size_(size), writePtr_(nullptr) { + VkBufferCreateInfo b; + b.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; + b.pNext = nullptr; + b.size = size; + b.flags = 0; + b.usage = VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; + b.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + b.queueFamilyIndexCount = 0; + b.pQueueFamilyIndices = nullptr; + assert(VK_SUCCESS == vkCreateBuffer(device, &b, nullptr, &buffer_)); + + // Okay, that's the buffer. Now let's allocate some memory for it. + VkMemoryAllocateInfo alloc; + alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + alloc.pNext = nullptr; + memMan->memory_type_from_properties(0xFFFFFFFF, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, &alloc.memoryTypeIndex); + alloc.allocationSize = size; + + assert(VK_SUCCESS == vkAllocateMemory(device, &alloc, nullptr, &deviceMemory_)); + assert(VK_SUCCESS == vkBindBufferMemory(device, buffer_, deviceMemory_, 0)); + } + + void Destroy(VkDevice device) { + vkDestroyBuffer(device, buffer_, nullptr); + vkFreeMemory(device, deviceMemory_, nullptr); + } + + void Reset() { offset_ = 0; } + + void Begin(VkDevice device) { + offset_ = 0; + assert(VK_SUCCESS == vkMapMemory(device, deviceMemory_, 0, size_, 0, (void **)(&writePtr_))); + } + + void End(VkDevice device) { + vkUnmapMemory(device, deviceMemory_); + writePtr_ = nullptr; + } + + + size_t Allocate(size_t numBytes) { + size_t out = offset_; + offset_ += (numBytes + 3) & ~3; // Round up to 4 bytes. + return out; + } + + // TODO: Add alignment support? + // Returns the offset that should be used when binding this buffer to get this data. + size_t Push(const void *data, size_t size) { + size_t off = Allocate(size); + memcpy(writePtr_ + off, data, size); + return off; + } + + size_t PushAligned(const void *data, size_t size, int align) { + offset_ = (offset_ + align - 1) & ~(align - 1); + size_t off = Allocate(size); + memcpy(writePtr_ + off, data, size); + return off; + } + + // "Zero-copy" variant - you can write the data directly as you compute it. + void *Push(size_t size, size_t *bindOffset) { + size_t off = Allocate(size); + *bindOffset = off; + return writePtr_ + off; + } + + VkBuffer GetVkBuffer() const { return buffer_; } + +private: + // TODO: Make it possible to suballocate pushbuffers in a large DeviceMemory block. + VkDeviceMemory deviceMemory_; + VkBuffer buffer_; + size_t offset_; + size_t size_; + uint8_t *writePtr_; +}; + +class Thin3DVKBlendState : public Thin3DBlendState { +public: + bool blendEnabled; + VkBlendOp eqCol, eqAlpha; + VkBlendFactor srcCol, srcAlpha, dstColor, dstAlpha; + bool logicEnabled; + VkLogicOp logicOp; + + void ToVulkan(VkPipelineColorBlendStateCreateInfo *info, VkPipelineColorBlendAttachmentState *attachments) { + memset(info, 0, sizeof(*info)); + info->sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; + info->attachmentCount = 1; + info->logicOp = logicOp; + info->logicOpEnable = logicEnabled; + attachments[0].blendEnable = blendEnabled; + attachments[0].colorBlendOp = eqCol; + attachments[0].alphaBlendOp = eqAlpha; + attachments[0].colorWriteMask = 0xF; + attachments[0].dstAlphaBlendFactor = dstAlpha; + attachments[0].dstColorBlendFactor = dstColor; + attachments[0].srcAlphaBlendFactor = srcAlpha; + attachments[0].srcColorBlendFactor = srcCol; + info->pAttachments = attachments; + } +}; + +class Thin3DVKDepthStencilState : public Thin3DDepthStencilState { +public: + bool depthTestEnabled; + bool depthWriteEnabled; + VkCompareOp depthComp; + + void ToVulkan(VkPipelineDepthStencilStateCreateInfo *info) { + memset(info, 0, sizeof(*info)); + info->sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; + info->depthCompareOp = depthComp; + info->depthTestEnable = depthTestEnabled; + info->depthWriteEnable = depthWriteEnabled; + info->stencilTestEnable = false; + info->depthBoundsTestEnable = false; + } +}; + +// Very simplistic buffer that will simply copy its contents into our "pushbuffer" when it's time to draw, +// to avoid synchronization issues. +class Thin3DVKBuffer : public Thin3DBuffer { +public: + Thin3DVKBuffer(size_t size, uint32_t flags) : dataSize_(size) { + data_ = new uint8_t[size]; + } + ~Thin3DVKBuffer() override { + delete[] data_; + } + + void SetData(const uint8_t *data, size_t size) override { + delete[] data_; + dataSize_ = size; + data_ = new uint8_t[size]; + if (data) { + memcpy(data_, data, size); + } + } + + void SubData(const uint8_t *data, size_t offset, size_t size) override { + memcpy(data_, data_ + offset, size); + } + + size_t GetSize() const { return dataSize_; } + const uint8_t *GetData() const { return data_; } + +private: + uint8_t *data_; + size_t dataSize_; +}; + +// Not registering this as a resource holder, instead ShaderSet is registered. It will +// invoke Compile again to recreate the shader then link them together. +class Thin3DVKShader : public Thin3DShader { +public: + Thin3DVKShader(bool isFragmentShader) : module_(nullptr), ok_(false) { + stage_ = isFragmentShader ? VK_SHADER_STAGE_FRAGMENT_BIT : VK_SHADER_STAGE_VERTEX_BIT; + } + bool Compile(VkDevice device, const char *source); + const std::string &GetSource() const { return source_; } + ~Thin3DVKShader() { + } + VkShaderModule Get() const { return module_; } + +private: + VkShaderModule module_; + VkShaderStageFlagBits stage_; + bool ok_; + std::string source_; // So we can recompile in case of context loss. +}; + +bool Thin3DVKShader::Compile(VkDevice device, const char *source) { + this->source_ = source; + std::vector spirv; + if (!GLSLtoSPV(stage_, source, spirv)) { + return false; + } + + if (!CreateShaderModule(device, spirv, &module_)) { + ok_ = true; + } else { + ok_ = false; + } + + return ok_; +} + + +inline VkFormat ConvertVertexDataTypeToVk(T3DVertexDataType type) { + switch (type) { + case FLOATx2: return VK_FORMAT_R32G32_SFLOAT; + case FLOATx3: return VK_FORMAT_R32G32B32_SFLOAT; + case FLOATx4: return VK_FORMAT_R32G32B32A32_SFLOAT; + case UNORM8x4: return VK_FORMAT_R8G8B8A8_UNORM; + default: return VK_FORMAT_UNDEFINED; + } +} + +class Thin3DVKVertexFormat : public Thin3DVertexFormat { +public: + void ToVulkan(VkPipelineVertexInputStateCreateInfo *info, VkVertexInputAttributeDescription *attrDescs, VkVertexInputBindingDescription *bindDescs) { + memset(info, 0, sizeof(*info)); + info->sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; + int offset = 0; + for (uint32_t i = 0; i < components_.size(); i++) { + attrDescs[i].binding = 0; + attrDescs[i].format = ConvertVertexDataTypeToVk(components_[i].type); + attrDescs[i].location = (int)components_[i].semantic; + attrDescs[i].offset = components_[i].offset; + } + bindDescs[0].binding = 0; + bindDescs[0].inputRate = VK_VERTEX_INPUT_RATE_VERTEX; + bindDescs[0].stride = stride_; + + info->vertexAttributeDescriptionCount = (uint32_t)components_.size(); + info->pVertexAttributeDescriptions = attrDescs; + info->vertexBindingDescriptionCount = 1; + info->pVertexBindingDescriptions = bindDescs; + } + + bool RequiresBuffer() { + return false; + } + + std::vector components_; + int stride_; +}; + +class Thin3DVKShaderSet : public Thin3DShaderSet { +public: + Thin3DVKShaderSet() { + // HACK! Hardcoded + uboSize_ = 16 * sizeof(float); // WorldViewProj + ubo_ = new uint8_t[uboSize_]; + } + ~Thin3DVKShaderSet() { + vshader->Release(); + fshader->Release(); + } + bool Link(); + + // Returns the binding offset. + size_t PushUBO(VulkanPushBuffer *buf) { + return buf->PushAligned(ubo_, uboSize_, 16); + } + + int GetUniformLoc(const char *name); + + void SetVector(const char *name, float *value, int n) override; + void SetMatrix4x4(const char *name, const float value[16]) override; + + Thin3DVKShader *vshader; + Thin3DVKShader *fshader; + +private: + uint8_t *ubo_; + int uboSize_; +}; + +struct PipelineKey { + Thin3DVKDepthStencilState *depthStencil; + Thin3DVKBlendState *blend; + Thin3DVKShaderSet *shaderSet; + VkPrimitiveTopology topology; + T3DCullMode cullMode; + + // etc etc + + bool operator < (const PipelineKey &other) const { + if (depthStencil < other.depthStencil) return true; else if (depthStencil > other.depthStencil) return false; + if (blend < other.blend) return true; else if (blend > other.blend) return false; + if (shaderSet < other.shaderSet) return true; else if (shaderSet > other.shaderSet) return false; + if (topology < other.topology) return true; else if (topology > other.topology) return false; + if (cullMode < other.cullMode) return true; else if (cullMode > other.cullMode) return false; + // etc etc + return false; + } +}; + + + +class Thin3DVKTexture; +class Thin3DVKSamplerState; + +struct DescriptorSetKey { + Thin3DVKTexture *texture_; + Thin3DVertexFormat *vertexFormat_; + Thin3DVKSamplerState *sampler_; + int frame; // 0 or 1 + + bool operator < (const DescriptorSetKey &other) const { + if (texture_ < other.texture_) return true; else if (texture_ > other.texture_) return false; + if (vertexFormat_ < other.vertexFormat_) return true; else if (vertexFormat_ > other.vertexFormat_) return false; + if (sampler_ < other.sampler_) return true; else if (sampler_ > other.sampler_) return false; + return false; + } +}; + +class Thin3DVKContext : public Thin3DContext { +public: + Thin3DVKContext(VulkanContext *vulkan); + virtual ~Thin3DVKContext(); + + Thin3DDepthStencilState *CreateDepthStencilState(bool depthTestEnabled, bool depthWriteEnabled, T3DComparison depthCompare) override; + Thin3DBlendState *CreateBlendState(const T3DBlendStateDesc &desc) override; + Thin3DBuffer *CreateBuffer(size_t size, uint32_t usageFlags) override; + Thin3DShaderSet *CreateShaderSet(Thin3DShader *vshader, Thin3DShader *fshader) override; + Thin3DVertexFormat *CreateVertexFormat(const std::vector &components, int stride, Thin3DShader *vshader) override; + Thin3DSamplerState *CreateSamplerState(const T3DSamplerStateDesc &desc) override; + Thin3DTexture *CreateTexture(T3DTextureType type, T3DImageFormat format, int width, int height, int depth, int mipLevels) override; + Thin3DTexture *CreateTexture() override; + + // Bound state objects + void SetBlendState(Thin3DBlendState *state) override { + Thin3DVKBlendState *s = static_cast(state); + curBlendState_ = s; + } + + // Bound state objects + void SetDepthStencilState(Thin3DDepthStencilState *state) override { + Thin3DVKDepthStencilState *s = static_cast(state); + curDepthStencilState_ = s; + } + + // The implementation makes the choice of which shader code to use. + Thin3DShader *CreateVertexShader(const char *glsl_source, const char *hlsl_source, const char *vulkan_source) override; + Thin3DShader *CreateFragmentShader(const char *glsl_source, const char *hlsl_source, const char *vulkan_source) override; + + void SetScissorEnabled(bool enable) override { + scissorEnabled_ = enable; + scissorDirty_ = true; + } + + void SetScissorRect(int left, int top, int width, int height) override; + + void SetViewports(int count, T3DViewport *viewports) override; + + void SetTextures(int start, int count, Thin3DTexture **textures) override; + + void SetSamplerStates(int start, int count, Thin3DSamplerState **state) override; + + void SetRenderState(T3DRenderState rs, uint32_t value) override; + + // TODO: Add more sophisticated draws. + void Draw(T3DPrimitive prim, Thin3DShaderSet *shaderSet, Thin3DVertexFormat *format, Thin3DBuffer *vdata, int vertexCount, int offset) override; + void DrawIndexed(T3DPrimitive prim, Thin3DShaderSet *shaderSet, Thin3DVertexFormat *format, Thin3DBuffer *vdata, Thin3DBuffer *idata, int vertexCount, int offset) override; + void DrawUP(T3DPrimitive prim, Thin3DShaderSet *shaderSet, Thin3DVertexFormat *format, const void *vdata, int vertexCount) override; + + void Clear(int mask, uint32_t colorval, float depthVal, int stencilVal) override; + + virtual void Begin(bool clear, uint32_t colorval, float depthVal, int stencilVal); + virtual void End(); + + std::string GetInfoString(T3DInfo info) const override { + // TODO: Make these actually query the right information + switch (info) { + case APINAME: + return "Vulkan"; + case VENDORSTRING: return "N/A"; + case VENDOR: return "N/A"; + case RENDERER: return "N/A"; + case SHADELANGVERSION: return "N/A";; + case APIVERSION: return "N/A"; + default: return "?"; + } + } + + VkPipeline GetOrCreatePipeline(); + VkDescriptorSet GetOrCreateDescriptorSet(); + +private: + void ApplyDynamicState(); + void DirtyDynamicState(); + + void BeginInitCommands(); + void EndInitCommands(); + + VulkanContext *vulkan_; + + VulkanDeviceMemoryManager vulkanMem_; + + // These are used to compose the pipeline cache key. + Thin3DVKBlendState *curBlendState_; + Thin3DVKDepthStencilState *curDepthStencilState_; + Thin3DVKShaderSet *curShaderSet_; + VkPrimitiveTopology curPrim_; + Thin3DVKVertexFormat *curVertexFormat_; + T3DCullMode curCullMode_; + + // We keep a pipeline state cache. + std::map pipelines_; + + // Also, a descriptor set state cache. We precompute a descriptor set for every active texture. + // The only difference between descriptor sets will be their textures. And input bindings? Hm + std::map descSets_; + + VkDescriptorPool descriptorPool_; + VkDescriptorSet descriptorSet_; + VkDescriptorSetLayout descriptorSetLayout_; + VkPipelineLayout pipelineLayout_; + VkPipelineCache pipelineCache_; + + VkCommandPool cmdPool_; + VkInstance instance_; + VkPhysicalDevice physicalDevice_; + VkDevice device_; + VkQueue queue_; + VkRenderPass renderPass_; + int queueFamilyIndex_; + + // State to apply at the next draw call if viewportDirty or scissorDirty are true. + bool viewportDirty_; + VkViewport viewport_; + bool scissorDirty_; + VkRect2D scissor_; + bool scissorEnabled_; + + VkRect2D noScissor_; // Simply a scissor covering the screen. + + enum {MAX_BOUND_TEXTURES = 1}; + Thin3DVKTexture *boundTextures_[MAX_BOUND_TEXTURES]; + Thin3DVKSamplerState *boundSamplers_[MAX_BOUND_TEXTURES]; + + // Ephemeral command buffer used for initializing textures, etc. As there can only be one in flight, can cause annoying stalls until I do something better. + VkCommandBuffer initCmd_; + bool hasInitCommands_; + VkFence initFence_; + bool pendingInitFence_; + + // TODO: Transpose this into a struct FrameObject[2]. + + // We write to one, while we wait for the draws from the other to complete. + // Then, at the end of the frame, they switch roles. + // cmdBuf_ for commands, pushBuffer_ for data. cmd_ will often refer to push_. + + VkCommandBuffer cmdBuffer_[2]; + VkCommandBuffer cmd_; // The current one + + VkFence cmdFences_[2]; + VkFence cmdFence_; + + VulkanPushBuffer *pushBuffer_[2]; + int frameNum_; + VulkanPushBuffer *push_; +}; + + +VkFormat FormatToVulkan(T3DImageFormat fmt) { + switch (fmt) { + case RGBA8888: return VK_FORMAT_R8G8B8A8_UNORM; + case RGBA4444: return VK_FORMAT_R4G4B4A4_UNORM_PACK16; + case D24S8: return VK_FORMAT_D24_UNORM_S8_UINT; + case D16: return VK_FORMAT_D16_UNORM; + default: return VK_FORMAT_UNDEFINED; + } +} + +class Thin3DVKSamplerState : public Thin3DSamplerState { +public: + Thin3DVKSamplerState(VulkanContext *vulkan, const T3DSamplerStateDesc &desc) : vulkan_(vulkan) { + VkSamplerCreateInfo s = { VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO }; + s.addressModeU = desc.wrapS ? VK_SAMPLER_ADDRESS_MODE_REPEAT : VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; + s.addressModeV = desc.wrapT ? VK_SAMPLER_ADDRESS_MODE_REPEAT : VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; + s.magFilter = desc.magFilt == T3DTextureFilter::LINEAR ? VK_FILTER_LINEAR : VK_FILTER_NEAREST; + s.minFilter = desc.minFilt == T3DTextureFilter::LINEAR ? VK_FILTER_LINEAR : VK_FILTER_NEAREST; + s.mipmapMode = desc.mipFilt == T3DTextureFilter::LINEAR ? VK_SAMPLER_MIPMAP_MODE_LINEAR : VK_SAMPLER_MIPMAP_MODE_NEAREST; + s.maxLod = 0.0; // TODO: Actually support mipmaps + + VkResult res = vkCreateSampler(vulkan_->Device(), &s, nullptr, &sampler_); + assert(res); + } + ~Thin3DVKSamplerState() { + vkDestroySampler(vulkan_->Device(), sampler_, nullptr); + } + + VkSampler GetSampler() { return sampler_; } + +private: + VulkanContext *vulkan_; + VkSampler sampler_; +}; + +Thin3DSamplerState *Thin3DVKContext::CreateSamplerState(const T3DSamplerStateDesc &desc) { + return new Thin3DVKSamplerState(vulkan_, desc); +} + +void Thin3DVKContext::SetSamplerStates(int start, int count, Thin3DSamplerState **state) { + for (int i = start; i < start + count; i++) { + boundSamplers_[i] = (Thin3DVKSamplerState *)state[i]; + } +} + +enum class TextureState { + UNINITIALIZED, + STAGED, + INITIALIZED, + PENDING_DESTRUCTION, +}; + +class Thin3DVKTexture : public Thin3DTexture { +public: + Thin3DVKTexture(VkDevice device, VulkanDeviceMemoryManager *memMan) : device_(device), memMan_(memMan), state_(TextureState::UNINITIALIZED) { + } + Thin3DVKTexture(VkDevice device, VulkanDeviceMemoryManager *memMan, T3DTextureType type, T3DImageFormat format, int width, int height, int depth, int mipLevels) + : device_(device), memMan_(memMan), format_(format), mipLevels_(mipLevels) { + Create(type, format, width, height, depth, mipLevels); + } + + ~Thin3DVKTexture() { + Destroy(); + } + + bool Create(T3DTextureType type, T3DImageFormat format, int width, int height, int depth, int mipLevels) override { + format_ = format; + mipLevels_ = mipLevels; + width_ = width; + height_ = height; + depth_ = depth; + + // We don't actually do anything here. + return true; + } + + void Destroy() { + } + + void SetImageData(int x, int y, int z, int width, int height, int depth, int level, int stride, const uint8_t *data) override; + + void Upload(VkCommandBuffer cmd); + + void Finalize(int zim_flags) override; + + void AutoGenMipmaps() {} + + bool NeedsUpload(); + + VkImageView GetImageView() { return view_; } + +private: + VulkanDeviceMemoryManager *memMan_; + VkDevice device_; + VulkanImage image_; + VulkanImage staging_; + VkImageView view_; + + int32_t width_, height_, depth_; + int mipLevels_; + + T3DImageFormat format_; + TextureState state_; +}; + +Thin3DVKContext::Thin3DVKContext(VulkanContext *vulkan) + : viewportDirty_(false), scissorDirty_(false) { + device_ = vulkan->Device(); + + noScissor_.offset.x = 0; + noScissor_.offset.y = 0; + noScissor_.extent.width = pixel_xres; + noScissor_.extent.height = pixel_yres; + + memset(boundTextures_, 0, sizeof(boundTextures_)); + CreatePresets(); + + vulkanMem_.Init(vulkan->GetPhysicalDevice()); + + VkCommandPoolCreateInfo p; + p.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; + p.pNext = nullptr; + p.flags = 0; + p.queueFamilyIndex = vulkan->GetGraphicsQueueFamilyIndex(); + VkResult res = vkCreateCommandPool(device_, &p, nullptr, &cmdPool_); + assert(VK_SUCCESS == res); + + VkDescriptorPoolSize dpTypes[3]; + dpTypes[0].descriptorCount = 200; + dpTypes[0].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + dpTypes[1].descriptorCount = 1; + dpTypes[1].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; + dpTypes[2].descriptorCount = 1; + dpTypes[2].type = VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT; + + VkDescriptorPoolCreateInfo dp; + dp.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; + dp.pNext = nullptr; + dp.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT; // We want to individually alloc and free descriptor sets. (do we?) + dp.maxSets = 200; // One set for every texture available... sigh + dp.pPoolSizes = dpTypes; + dp.poolSizeCount = ARRAY_SIZE(dpTypes); + res = vkCreateDescriptorPool(device_, &dp, nullptr, &descriptorPool_); + assert(VK_SUCCESS == res); + pushBuffer_[0] = new VulkanPushBuffer(device_, &vulkanMem_, 1024 * 1024); + pushBuffer_[1] = new VulkanPushBuffer(device_, &vulkanMem_, 1024 * 1024); + + // binding 0 - vertex data + // binding 1 - uniform data + // binding 2 - sampler + // binding 3 - image + VkDescriptorSetLayoutBinding bindings[4]; + bindings[0].descriptorCount = 1; + bindings[0].pImmutableSamplers = nullptr; + bindings[0].descriptorType = VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT; + bindings[0].stageFlags = VK_SHADER_STAGE_VERTEX_BIT; + bindings[1].descriptorCount = 1; + bindings[1].pImmutableSamplers = nullptr; + bindings[1].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; + bindings[1].stageFlags = VK_SHADER_STAGE_VERTEX_BIT; + bindings[2].descriptorCount = 1; + bindings[2].pImmutableSamplers = nullptr; + bindings[2].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + bindings[2].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; + + VkDescriptorSetLayoutCreateInfo dsl; + dsl.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; + dsl.pNext = nullptr; + dsl.bindingCount = 3; + dsl.pBindings = bindings; + res = vkCreateDescriptorSetLayout(device_, &dsl, nullptr, &descriptorSetLayout_); + assert(VK_SUCCESS == res); + + VkPipelineLayoutCreateInfo pl; + pl.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; + pl.pNext = nullptr; + pl.pPushConstantRanges = nullptr; + pl.pushConstantRangeCount = 0; + pl.setLayoutCount = 1; + pl.pSetLayouts = &descriptorSetLayout_; + res = vkCreatePipelineLayout(device_, &pl, nullptr, &pipelineLayout_); + assert(VK_SUCCESS == res); + + VkCommandBufferAllocateInfo cb; + cb.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; + cb.pNext = nullptr; + cb.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; + cb.commandPool = cmdPool_; + cb.commandBufferCount = 1; + res = vkAllocateCommandBuffers(device_, &cb, &cmdBuffer_[0]); + assert(VK_SUCCESS == res); + res = vkAllocateCommandBuffers(device_, &cb, &cmdBuffer_[1]); + assert(VK_SUCCESS == res); + res = vkAllocateCommandBuffers(device_, &cb, &initCmd_); + assert(VK_SUCCESS == res); + hasInitCommands_ = false; + + VkFenceCreateInfo f; + f.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; + f.pNext = nullptr; + f.flags = 0; + res = vkCreateFence(device_, &f, nullptr, &cmdFences_[0]); + assert(VK_SUCCESS == res); + + res = vkCreateFence(device_, &f, nullptr, &cmdFences_[1]); + assert(VK_SUCCESS == res); + // Create as already signalled, so we can wait for it the first time. + // f.flags = VK_FENCE_CREATE_SIGNALED_BIT; + res = vkCreateFence(device_, &f, nullptr, &initFence_); + assert(VK_SUCCESS == res); + pendingInitFence_ = false; + + VkPipelineCacheCreateInfo pc; + pc.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO; + pc.pNext = nullptr; + pc.pInitialData = nullptr; + pc.initialDataSize = 0; + pc.flags = 0; + res = vkCreatePipelineCache(device_, &pc, nullptr, &pipelineCache_); + assert(VK_SUCCESS == res); + push_ = pushBuffer_[0]; + cmd_ = cmdBuffer_[0]; +} + +Thin3DVKContext::~Thin3DVKContext() { + for (auto x : pipelines_) { + vkDestroyPipeline(device_, x.second, nullptr); + } + vkFreeCommandBuffers(device_, cmdPool_, 2, cmdBuffer_); + vkFreeCommandBuffers(device_, cmdPool_, 1, &cmd_); + vkDestroyCommandPool(device_, cmdPool_, nullptr); + // This also destroys all descriptor sets. + vkDestroyDescriptorPool(device_, descriptorPool_, nullptr); + vkDestroyDescriptorSetLayout(device_, descriptorSetLayout_, nullptr); + vkDestroyPipelineLayout(device_, pipelineLayout_, nullptr); + vkDestroyPipelineCache(device_, pipelineCache_, nullptr); +} + +void Thin3DVKContext::Begin(bool clear, uint32_t colorval, float depthVal, int stencilVal) { + VkClearValue clearVal[2]; + Uint8x4ToFloat4(colorval, clearVal[0].color.float32); + clearVal[0].color.float32[2] = 1.0f; + clearVal[1].depthStencil.depth = depthVal; + clearVal[1].depthStencil.stencil = stencilVal; + vulkan_->BeginSurfaceRenderPass(clearVal); + + // Make sure we don't stomp over the old command buffer. + vkWaitForFences(device_, 1, &cmdFence_, true, 0); + push_->Begin(device_); +} + +void Thin3DVKContext::BeginInitCommands() { + assert(!hasInitCommands_); + + // Before we can begin, we must be sure that the command buffer is no longer in use, as we only have a single one for init + // tasks (for now). + + VkCommandBufferBeginInfo begin; + begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; + begin.pNext = nullptr; + begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + begin.pInheritanceInfo = nullptr; + assert(VK_SUCCESS == vkBeginCommandBuffer(initCmd_, &begin)); + hasInitCommands_ = true; +} + +void Thin3DVKContext::EndInitCommands() { + assert(VK_SUCCESS == vkEndCommandBuffer(initCmd_)); +} + +void Thin3DVKContext::End() { + // Stop collecting data in the frame data buffer. + push_->End(device_); + + vkCmdEndRenderPass(cmd_); + VkResult endRes = vkEndCommandBuffer(cmd_); + + if (hasInitCommands_) { + assert(!pendingInitFence_); + EndInitCommands(); + + // Run the texture uploads etc _before_ we execute the ordinary command buffer + pendingInitFence_ = true; + VkSubmitInfo submit = {}; + submit.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + submit.pCommandBuffers = &initCmd_; + submit.commandBufferCount = 1; + assert(VK_SUCCESS == vkQueueSubmit(queue_, 1, &submit, initFence_)); + hasInitCommands_ = false; + } + + if (VK_SUCCESS != endRes) { + ELOG("vkEndCommandBuffer failed"); + vkResetCommandBuffer(cmd_, 0); + } else { + VkSubmitInfo submit = {}; + submit.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + submit.pCommandBuffers = &cmd_; + submit.commandBufferCount = 1; + assert(VK_SUCCESS == vkQueueSubmit(queue_, 1, &submit, cmdFence_)); + } + + frameNum_++; + push_ = pushBuffer_[frameNum_ & 1]; + cmd_ = cmdBuffer_[frameNum_ & 1]; + cmdFence_ = cmdFences_[frameNum_ & 1]; + + DirtyDynamicState(); +} + +VkDescriptorSet Thin3DVKContext::GetOrCreateDescriptorSet() { + DescriptorSetKey key; + key.texture_ = boundTextures_[0]; + key.sampler_ = boundSamplers_[0]; + key.vertexFormat_ = nullptr; + key.frame = frameNum_ & 1; + + auto iter = descSets_.find(key); + if (iter != descSets_.end()) { + return iter->second; + } + + VkDescriptorSet descSet; + VkDescriptorSetAllocateInfo alloc; + alloc.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; + alloc.pNext = nullptr; + alloc.descriptorPool = descriptorPool_; + alloc.pSetLayouts = &descriptorSetLayout_; + alloc.descriptorSetCount = 1; + VkResult res = vkAllocateDescriptorSets(device_, &alloc, &descSet); + assert(VK_SUCCESS == res); + // bindings[0].descriptorType = VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT; + // bindings[1].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; + // bindings[2].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER; + + VkDescriptorBufferInfo bufferDesc; + bufferDesc.buffer = push_->GetVkBuffer(); + bufferDesc.offset = 0; + bufferDesc.range = 16 * 4; + + VkDescriptorImageInfo imageDesc; + imageDesc.imageView = boundTextures_[0]->GetImageView(); + imageDesc.sampler = boundSamplers_[0]->GetSampler(); + imageDesc.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + + VkWriteDescriptorSet writes[2]; + writes[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + writes[0].pNext = nullptr; + writes[0].dstSet = descSet; + writes[0].dstArrayElement = 0; + writes[0].dstBinding = 1; + writes[0].pBufferInfo = &bufferDesc; + writes[0].descriptorCount = 1; + writes[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; + + writes[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + writes[1].pNext = nullptr; + writes[1].dstSet = descSet; + writes[1].dstArrayElement = 0; + writes[1].dstBinding = 2; + writes[1].pImageInfo = &imageDesc; + writes[1].descriptorCount = 1; + writes[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + + vkUpdateDescriptorSets(device_, 2, writes, 0, nullptr); + + descSets_[key] = descSet; + return descSet; +} + +VkPipeline Thin3DVKContext::GetOrCreatePipeline() { + PipelineKey key; + key.blend = curBlendState_; + key.depthStencil = curDepthStencilState_; + key.shaderSet = curShaderSet_; + key.topology = curPrim_; + key.cullMode = curCullMode_; + + auto iter = pipelines_.find(key); + if (iter != pipelines_.end()) { + return iter->second; + } + + VkPipelineShaderStageCreateInfo stages[2]; + stages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + stages[0].pNext = nullptr; + stages[0].pSpecializationInfo = nullptr; + stages[0].stage = VK_SHADER_STAGE_VERTEX_BIT; + stages[0].module = curShaderSet_->vshader->Get(); + stages[0].pName = "main"; + stages[0].flags = 0; + + stages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + stages[1].pNext = nullptr; + stages[1].pSpecializationInfo = nullptr; + stages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; + stages[1].module = curShaderSet_->fshader->Get(); + stages[1].pName = "main"; + stages[1].flags = 0; + + VkPipelineColorBlendStateCreateInfo colorBlend; + VkPipelineColorBlendAttachmentState attachment0; + curBlendState_->ToVulkan(&colorBlend, &attachment0); + + VkPipelineDepthStencilStateCreateInfo depthStencil; + curDepthStencilState_->ToVulkan(&depthStencil); + + VkPipelineVertexInputStateCreateInfo vertex; + VkVertexInputAttributeDescription attrDescs[4]; + VkVertexInputBindingDescription bindDescs[1]; + curVertexFormat_->ToVulkan(&vertex, attrDescs, bindDescs); + + VkPipelineInputAssemblyStateCreateInfo inputAssembly; + inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; + inputAssembly.pNext = nullptr; + inputAssembly.topology = curPrim_; + inputAssembly.primitiveRestartEnable = false; + + VkDynamicState dynamics[] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; + VkPipelineDynamicStateCreateInfo dynamicInfo; + dynamicInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; + dynamicInfo.pNext = nullptr; + dynamicInfo.dynamicStateCount = ARRAY_SIZE(dynamics); + dynamicInfo.pDynamicStates = dynamics; + + VkPipelineRasterizationStateCreateInfo raster; + raster.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; + raster.pNext = nullptr; + switch (curCullMode_) { + case NO_CULL: raster.cullMode = VK_CULL_MODE_NONE; break; + case CW: raster.cullMode = VK_CULL_MODE_BACK_BIT; break; + default: + case CCW: raster.cullMode = VK_CULL_MODE_FRONT_BIT; break; + } + raster.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; + raster.polygonMode = VK_POLYGON_MODE_FILL; + raster.rasterizerDiscardEnable = false; + raster.lineWidth = 1.0f; + raster.depthBiasClamp = 0.0f; + raster.depthBiasEnable = false; + raster.depthClampEnable = false; + raster.depthBiasSlopeFactor = 0.0; + + VkPipelineMultisampleStateCreateInfo ms; + memset(&ms, 0, sizeof(ms)); + ms.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; + ms.pNext = nullptr; + ms.pSampleMask = nullptr; + ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; + + VkPipelineViewportStateCreateInfo vs; + vs.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; + vs.pNext = nullptr; + vs.viewportCount = 1; + vs.scissorCount = 1; + vs.pViewports = nullptr; // dynamic + vs.pScissors = nullptr; // dynamic + + VkGraphicsPipelineCreateInfo info = {}; + info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; + info.pNext = nullptr; + info.flags = 0; + info.stageCount = 2; + info.pStages = stages; + info.pColorBlendState = &colorBlend; + info.pDepthStencilState = &depthStencil; + info.pDynamicState = &dynamicInfo; + info.pInputAssemblyState = &inputAssembly; + info.pTessellationState = nullptr; + info.pMultisampleState = &ms; + info.pVertexInputState = &vertex; + info.pRasterizationState = &raster; + info.pViewportState = &vs; // Must set viewport and scissor counts even if we set the actual state dynamically. + info.layout = pipelineLayout_; + info.subpass = 0; + info.renderPass = renderPass_; + + // OK, need to create a new pipeline. + VkPipeline pipeline; + VkResult result = vkCreateGraphicsPipelines(device_, pipelineCache_, 1, &info, nullptr, &pipeline); + if (result != VK_SUCCESS) { + ELOG("Failed to create graphics pipeline"); + return nullptr; + } + + pipelines_.insert(std::make_pair(key, pipeline)); + return pipeline; +} + +void Thin3DVKContext::SetScissorRect(int left, int top, int width, int height) { + scissor_.offset.x = left; + scissor_.offset.y = top; + scissor_.extent.width = width; + scissor_.extent.height = height; + scissorDirty_ = true; +} + +void Thin3DVKContext::SetViewports(int count, T3DViewport *viewports) { + viewport_.x = viewports[0].TopLeftX; + viewport_.y = viewports[0].TopLeftY; + viewport_.width = viewports[0].Width; + viewport_.height = viewports[0].Height; + viewport_.minDepth = viewports[0].MinDepth; + viewport_.maxDepth = viewports[0].MaxDepth; + viewportDirty_ = true; +} + +void Thin3DVKContext::ApplyDynamicState() { + if (scissorDirty_) { + if (scissorEnabled_) { + vkCmdSetScissor(cmd_, 0, 1, &scissor_); + } else { + vkCmdSetScissor(cmd_, 0, 1, &noScissor_); + } + scissorDirty_ = false; + } + if (viewportDirty_) { + vkCmdSetViewport(cmd_, 0, 1, &viewport_); + viewportDirty_ = false; + } +} + +void Thin3DVKContext::DirtyDynamicState() { + scissorDirty_ = true; + viewportDirty_ = true; +} + +Thin3DVertexFormat *Thin3DVKContext::CreateVertexFormat(const std::vector &components, int stride, Thin3DShader *vshader) { + Thin3DVKVertexFormat *fmt = new Thin3DVKVertexFormat(); + fmt->components_ = components; + fmt->stride_ = stride; + return fmt; +} + +Thin3DTexture *Thin3DVKContext::CreateTexture() { + return new Thin3DVKTexture(device_, &vulkanMem_); +} + +Thin3DTexture *Thin3DVKContext::CreateTexture(T3DTextureType type, T3DImageFormat format, int width, int height, int depth, int mipLevels) { + return new Thin3DVKTexture(device_, &vulkanMem_, type, format, width, height, depth, mipLevels); +} + +void Thin3DVKTexture::SetImageData(int x, int y, int z, int width, int height, int depth, int level, int stride, const uint8_t *data) { + VkFormat vulkanFormat = FormatToVulkan(format_); + + // nVidia and probably many other GPUs can texture _directly_ from a mappable buffer! But let's not rely on that, and it's not quite optimal. + // So we need to do a staging copy. We upload the data to the staging buffer immediately, then we actually do the final copy once it's used the first time + // as we need a command buffer and the architecture of Thin3D doesn't really work the way we want.. + if (!image_.IsValid()) { + staging_.Create2D(device_, memMan_, vulkanFormat, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, VK_IMAGE_USAGE_TRANSFER_SRC_BIT, width, height); + image_.Create2D(device_, memMan_, vulkanFormat, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, (VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT), width, height); + } + + VkImageViewCreateInfo iv; + iv.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + iv.pNext = nullptr; + iv.image = image_.GetImage(); + iv.viewType = VK_IMAGE_VIEW_TYPE_2D; + iv.flags = 0; + iv.format = FormatToVulkan(format_); + iv.components.r = VK_COMPONENT_SWIZZLE_R; + iv.components.g = VK_COMPONENT_SWIZZLE_G; + iv.components.b = VK_COMPONENT_SWIZZLE_B; + iv.components.a = VK_COMPONENT_SWIZZLE_A; + iv.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + iv.subresourceRange.layerCount = 1; + iv.subresourceRange.baseArrayLayer = 0; + iv.subresourceRange.baseMipLevel = 0; + iv.subresourceRange.levelCount = 1; + VkResult res = vkCreateImageView(device_, &iv, nullptr, &view_); + assert(VK_SUCCESS == res); + + // TODO: Support setting only parts of the image efficiently. + staging_.SetImageData2D(device_, data, width, height, stride); + state_ = TextureState::STAGED; +} + +void Thin3DVKTexture::Finalize(int zim_flags) { + // TODO +} + +bool Thin3DVKTexture::NeedsUpload() { + return state_ == TextureState::STAGED; +} + +void Thin3DVKTexture::Upload(VkCommandBuffer cmd) { + if (state_ == TextureState::STAGED) { + // Before we can texture, we need to Copy and ChangeLayout. + VkImageCopy copy_region; + copy_region.srcSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }; + copy_region.srcOffset = { 0, 0, 0 }; + copy_region.dstSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }; + copy_region.dstOffset = { 0, 0, 0 }; + copy_region.extent = { (uint32_t)width_, (uint32_t)height_, 1 }; + vkCmdCopyImage(cmd, staging_.GetImage(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, image_.GetImage(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©_region); + image_.ChangeLayout(cmd, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); + // From this point on, the image can be used for texturing. + // Even before this function call (but after SetImageData), the image object can be referenced in a descriptor set. + state_ = TextureState::INITIALIZED; + } +} + +static bool isPowerOf2(int n) { + return n == 1 || (n & (n - 1)) == 0; +} + +Thin3DDepthStencilState *Thin3DVKContext::CreateDepthStencilState(bool depthTestEnabled, bool depthWriteEnabled, T3DComparison depthCompare) { + Thin3DVKDepthStencilState *ds = new Thin3DVKDepthStencilState(); + ds->depthTestEnabled = depthTestEnabled; + ds->depthWriteEnabled = depthWriteEnabled; + ds->depthComp = compToVK[depthCompare]; + return ds; +} + +Thin3DBlendState *Thin3DVKContext::CreateBlendState(const T3DBlendStateDesc &desc) { + Thin3DVKBlendState *bs = new Thin3DVKBlendState(); + bs->blendEnabled = desc.enabled; + bs->eqCol = blendEqToGL[desc.eqCol]; + bs->srcCol = blendFactorToVk[desc.srcCol]; + bs->dstColor = blendFactorToVk[desc.dstCol]; + bs->eqAlpha = blendEqToGL[desc.eqAlpha]; + bs->srcAlpha = blendFactorToVk[desc.srcAlpha]; + bs->dstAlpha = blendFactorToVk[desc.dstAlpha]; + bs->logicEnabled = desc.logicEnabled; + bs->logicOp = logicOpToVK[desc.logicOp]; + return bs; +} + +Thin3DBuffer *Thin3DVKContext::CreateBuffer(size_t size, uint32_t usageFlags) { + return new Thin3DVKBuffer(size, usageFlags); +} + +Thin3DShaderSet *Thin3DVKContext::CreateShaderSet(Thin3DShader *vshader, Thin3DShader *fshader) { + if (!vshader || !fshader) { + ELOG("ShaderSet requires both a valid vertex and a fragment shader: %p %p", vshader, fshader); + return NULL; + } + Thin3DVKShaderSet *shaderSet = new Thin3DVKShaderSet(); + vshader->AddRef(); + fshader->AddRef(); + shaderSet->vshader = static_cast(vshader); + shaderSet->fshader = static_cast(fshader); + if (shaderSet->Link()) { + return shaderSet; + } else { + delete shaderSet; + return NULL; + } +} + +void Thin3DVKContext::SetTextures(int start, int count, Thin3DTexture **textures) { + for (int i = start; i < start + count; i++) { + boundTextures_[i] = static_cast(textures[i]); + // Bind simply copies the texture to VRAM if needed. + if (boundTextures_[i]->NeedsUpload()) { + if (!hasInitCommands_) { + BeginInitCommands(); + } + boundTextures_[i]->Upload(initCmd_); + } + } +} + +Thin3DShader *Thin3DVKContext::CreateVertexShader(const char *glsl_source, const char *hlsl_source, const char *vulkan_source) { + Thin3DVKShader *shader = new Thin3DVKShader(false); + if (shader->Compile(device_, vulkan_source)) { + return shader; + } else { + shader->Release(); + return nullptr; + } +} + +Thin3DShader *Thin3DVKContext::CreateFragmentShader(const char *glsl_source, const char *hlsl_source, const char *vulkan_source) { + Thin3DVKShader *shader = new Thin3DVKShader(true); + if (shader->Compile(device_, vulkan_source)) { + return shader; + } else { + shader->Release(); + return nullptr; + } +} + +bool Thin3DVKShaderSet::Link() { + // There is no link step. However, we will create and cache Pipeline objects in the device context. + return true; +} + +int Thin3DVKShaderSet::GetUniformLoc(const char *name) { + int loc = -1; + + // HACK! As we only use one uniform we hardcode it. + if (!strcmp(name, "WorldViewProj")) { + return 0; + } + + /* + auto iter = uniforms_.find(name); + if (iter != uniforms_.end()) { + loc = iter->second.loc_; + } else { + loc = glGetUniformLocation(program_, name); + UniformInfo info; + info.loc_ = loc; + uniforms_[name] = info; + }*/ + + return loc; +} + +void Thin3DVKShaderSet::SetVector(const char *name, float *value, int n) { + // TODO: Implement +} + +void Thin3DVKShaderSet::SetMatrix4x4(const char *name, const float value[16]) { + int loc = GetUniformLoc(name); + if (loc != -1) { + memcpy(ubo_ + loc, value, 16 * sizeof(float)); + } +} + +void Thin3DVKContext::SetRenderState(T3DRenderState rs, uint32_t value) { + switch (rs) { + case T3DRenderState::CULL_MODE: + curCullMode_ = (T3DCullMode)value; + break; + } +} + +void Thin3DVKContext::Draw(T3DPrimitive prim, Thin3DShaderSet *shaderSet, Thin3DVertexFormat *format, Thin3DBuffer *vdata, int vertexCount, int offset) { + ApplyDynamicState(); + + curPrim_ = primToVK[prim]; + curShaderSet_ = (Thin3DVKShaderSet *)shaderSet; + curVertexFormat_ = (Thin3DVKVertexFormat *)format; + Thin3DVKBuffer *vbuf = static_cast(vdata); + + uint32_t ubo_offset = (uint32_t)curShaderSet_->PushUBO(push_); + size_t vbBindOffset = push_->Push(vbuf->GetData(), vbuf->GetSize()); + + VkPipeline pipeline = GetOrCreatePipeline(); + vkCmdBindPipeline(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); + VkDescriptorSet descSet = GetOrCreateDescriptorSet(); + vkCmdBindDescriptorSets(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout_, 0, 1, &descSet, 1, &ubo_offset); + VkBuffer buffers[1] = { push_->GetVkBuffer() }; + VkDeviceSize offsets[1] = { vbBindOffset }; + vkCmdBindVertexBuffers(cmd_, 0, 1, buffers, offsets); + vkCmdDraw(cmd_, vertexCount, 1, offset, 0); +} + +void Thin3DVKContext::DrawIndexed(T3DPrimitive prim, Thin3DShaderSet *shaderSet, Thin3DVertexFormat *format, Thin3DBuffer *vdata, Thin3DBuffer *idata, int vertexCount, int offset) { + ApplyDynamicState(); + + curPrim_ = primToVK[prim]; + curShaderSet_ = (Thin3DVKShaderSet *)shaderSet; + curVertexFormat_ = (Thin3DVKVertexFormat *)format; + + Thin3DVKBuffer *ibuf = (Thin3DVKBuffer *)idata; + Thin3DVKBuffer *vbuf = (Thin3DVKBuffer *)vdata; + + uint32_t ubo_offset = (uint32_t)curShaderSet_->PushUBO(push_); + size_t vbBindOffset = push_->Push(vbuf->GetData(), vbuf->GetSize()); + size_t ibBindOffset = push_->Push(ibuf->GetData(), ibuf->GetSize()); + + VkPipeline pipeline = GetOrCreatePipeline(); + vkCmdBindPipeline(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); + + VkDescriptorSet descSet = GetOrCreateDescriptorSet(); + vkCmdBindDescriptorSets(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout_, 0, 1, &descSet, 1, &ubo_offset); + + VkBuffer buffers[1] = { push_->GetVkBuffer() }; + VkDeviceSize offsets[1] = { vbBindOffset }; + vkCmdBindVertexBuffers(cmd_, 0, 1, buffers, offsets); + + vkCmdBindIndexBuffer(cmd_, push_->GetVkBuffer(), ibBindOffset, VK_INDEX_TYPE_UINT16); + vkCmdDrawIndexed(cmd_, vertexCount, 1, 0, offset, 0); +} + +void Thin3DVKContext::DrawUP(T3DPrimitive prim, Thin3DShaderSet *shaderSet, Thin3DVertexFormat *format, const void *vdata, int vertexCount) { + ApplyDynamicState(); + + curPrim_ = primToVK[prim]; + curShaderSet_ = (Thin3DVKShaderSet *)shaderSet; + curVertexFormat_ = (Thin3DVKVertexFormat *)format; + + uint32_t ubo_offset = (uint32_t)curShaderSet_->PushUBO(push_); + size_t vbBindOffset = push_->Push(vdata, vertexCount * curVertexFormat_->stride_); + + VkPipeline pipeline = GetOrCreatePipeline(); + vkCmdBindPipeline(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); + + VkDescriptorSet descSet = GetOrCreateDescriptorSet(); + vkCmdBindDescriptorSets(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout_, 0, 1, &descSet, 1, &ubo_offset); + + VkBuffer buffers[1] = { push_->GetVkBuffer() }; + VkDeviceSize offsets[1] = { vbBindOffset }; + vkCmdBindVertexBuffers(cmd_, 0, 1, buffers, offsets); + vkCmdDraw(cmd_, vertexCount, 1, 0, 0); +} + +void Thin3DVKContext::Clear(int mask, uint32_t colorval, float depthVal, int stencilVal) { + if (mask & T3DClear::COLOR) { + VkClearColorValue col; + Uint8x4ToFloat4(colorval, col.float32); + + /* + VkRect3D rect; + rect.extent.width = + vkCmdClearColorAttachment(cmdBuf_, 0, imageLayout_, &col, 1, nullptr); + */ + } + if (mask & T3DClear::DEPTH | T3DClear::STENCIL) { + + } +} + +Thin3DContext *T3DCreateVulkanContext(VulkanContext *vulkan) { + return new Thin3DVKContext(vulkan); +} \ No newline at end of file diff --git a/ext/native/thin3d/vulkan_utils.cpp b/ext/native/thin3d/vulkan_utils.cpp new file mode 100644 index 0000000000..264602a5b4 --- /dev/null +++ b/ext/native/thin3d/vulkan_utils.cpp @@ -0,0 +1,173 @@ +// Copyright (c) 2015- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#ifdef _WIN32 +#define WIN32_LEAN_AND_MEAN +#include +#undef min +#undef max + +#endif + +#include +#include +#include + +#ifdef USE_CRT_DBG +#undef new +#endif + +#include "ext/glslang/SPIRV/GlslangToSpv.h" +#include "ext/glslang/SPIRV/disassemble.h" + +#ifdef USE_CRT_DBG +#define new DBG_NEW +#endif + +#include "thin3d/vulkan_utils.h" + +void VulkanDeviceMemoryManager::Init(VkPhysicalDevice gpu) { + // Get Memory information and properties + vkGetPhysicalDeviceMemoryProperties(gpu, &memory_properties_); +} + +VkResult VulkanDeviceMemoryManager::memory_type_from_properties(uint32_t typeBits, VkFlags requirements_mask, uint32_t *typeIndex) { + // Search memtypes to find first index with those properties + for (uint32_t i = 0; i < 32; i++) { + if ((typeBits & 1) == 1) { + // Type is available, does it match user properties? + if ((memory_properties_.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) { + *typeIndex = i; + return VK_SUCCESS; + } + } + typeBits >>= 1; + } + // No memory types matched, return failure + return VK_ERROR_FORMAT_NOT_SUPPORTED; +} + +void VulkanImage::Create2D(VkDevice device, VulkanDeviceMemoryManager *memMan, VkFormat format, VkFlags required_props, VkImageUsageFlags usage, int width, int height) { + width_ = width; + height_ = height; + + VkImageCreateInfo i; + i.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; + i.pNext = NULL; + i.imageType = VK_IMAGE_TYPE_2D; + i.format = format; + i.extent = { (uint32_t)width, (uint32_t)height, 1 }; + i.mipLevels = 1; + i.arrayLayers = 1; + i.samples = VK_SAMPLE_COUNT_1_BIT; + i.tiling = VK_IMAGE_TILING_LINEAR; + i.usage = usage; + i.flags = 0; + i.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + i.queueFamilyIndexCount = 0; + i.pQueueFamilyIndices = nullptr; + i.initialLayout = VK_IMAGE_LAYOUT_GENERAL; + + VkMemoryRequirements mem_reqs; + + VkResult err = vkCreateImage(device, &i, nullptr, &image_); + assert(!err); + + vkGetImageMemoryRequirements(device, image_, &mem_reqs); + + mem_alloc_.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + mem_alloc_.pNext = NULL; + mem_alloc_.allocationSize = mem_reqs.size; + mem_alloc_.memoryTypeIndex = 0; + + err = memMan->memory_type_from_properties(mem_reqs.memoryTypeBits, required_props, &mem_alloc_.memoryTypeIndex); + assert(!err); + + err = vkAllocateMemory(device, &mem_alloc_, nullptr, &memory_); + assert(!err); + + err = vkBindImageMemory(device, image_, memory_, 0); // at offset 0. +} + +void VulkanImage::SetImageData2D(VkDevice device, const uint8_t *data, int width, int height, int pitch) { + VkImageSubresource subres; + subres.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + subres.mipLevel = 0; + subres.arrayLayer = 0; + + VkSubresourceLayout layout; + void *destData; + vkGetImageSubresourceLayout(device, image_, &subres, &layout); + + VkResult err = vkMapMemory(device, memory_, 0, mem_alloc_.allocationSize, 0, &destData); + assert(!err); + + uint8_t *writePtr = (uint8_t *)destData + layout.offset; + int bpp = 4; // TODO + for (int y = 0; y < height; y++) { + memcpy(writePtr + y * layout.rowPitch, data + y * pitch, bpp * width); + } + + vkUnmapMemory(device, memory_); +} + + +void VulkanImage::ChangeLayout(VkCommandBuffer cmd, VkImageAspectFlags aspectMask, VkImageLayout old_image_layout, VkImageLayout new_image_layout) { + VkImageMemoryBarrier image_memory_barrier; + image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + image_memory_barrier.pNext = NULL; + image_memory_barrier.dstAccessMask = 0; + image_memory_barrier.srcAccessMask = 0; + image_memory_barrier.oldLayout = old_image_layout; + image_memory_barrier.newLayout = new_image_layout; + image_memory_barrier.image = image_; + image_memory_barrier.subresourceRange.aspectMask = aspectMask; + image_memory_barrier.subresourceRange.layerCount = 1; + image_memory_barrier.subresourceRange.baseArrayLayer = 0; + image_memory_barrier.subresourceRange.baseMipLevel = 0; + image_memory_barrier.subresourceRange.levelCount = 1; + + if (new_image_layout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) { + /* Make sure anything that was copying from this image has completed */ + image_memory_barrier.srcAccessMask = VK_ACCESS_MEMORY_READ_BIT; + } + + if (new_image_layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) { + /* Make sure any Copy or CPU writes to image are flushed */ + image_memory_barrier.dstAccessMask = VK_ACCESS_HOST_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT; + } + + VkPipelineStageFlags src_stages = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; + VkPipelineStageFlags dest_stages = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; + vkCmdPipelineBarrier(cmd, src_stages, dest_stages, false, 0, nullptr, 0, nullptr, 1, &image_memory_barrier); +} + + +bool CreateShaderModule(VkDevice device, const std::vector &spirv, VkShaderModule *shaderModule) { + VkShaderModuleCreateInfo sm; + sm.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; + sm.pNext = nullptr; + sm.pCode = spirv.data(); + sm.codeSize = spirv.size() * sizeof(uint32_t); + sm.flags = 0; + VkResult result = vkCreateShaderModule(device, &sm, NULL, shaderModule); + if (result != VK_SUCCESS) { + return false; + } else { + return true; + } +} diff --git a/ext/native/thin3d/vulkan_utils.h b/ext/native/thin3d/vulkan_utils.h new file mode 100644 index 0000000000..a2dd321843 --- /dev/null +++ b/ext/native/thin3d/vulkan_utils.h @@ -0,0 +1,70 @@ +// Copyright (c) 2015- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#pragma once + +#include + +#define VK_PROTOTYPES +#include "ext/vulkan/vulkan.h" + +// +class VulkanDeviceMemoryManager { +public: + VulkanDeviceMemoryManager() {} + void Init(VkPhysicalDevice gpu); + + VkResult memory_type_from_properties(uint32_t typeBits, VkFlags requirements_mask, uint32_t *typeIndex); + +private: + VkPhysicalDeviceMemoryProperties memory_properties_; +}; + + +// Utility class to handle images without going insane. +// Allocates its own memory. +class VulkanImage { +public: + VulkanImage() : image_(nullptr), memory_(nullptr) {} + + bool IsValid() const { return image_ != nullptr; } + // This can be done completely unsynchronized. + void Create2D(VkDevice device, VulkanDeviceMemoryManager *memMan, VkFormat format, VkFlags required_props, VkImageUsageFlags usage, int width, int height); + + // This can only be used if you pass in VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT in required_props in Create2D. + void SetImageData2D(VkDevice device, const uint8_t *data, int width, int height, int pitch); + void ChangeLayout(VkCommandBuffer cmd, VkImageAspectFlags aspectMask, VkImageLayout old_image_layout, VkImageLayout new_image_layout); + VkImage GetImage() const { + return image_; + } + +private: + VkMemoryAllocateInfo mem_alloc_; + VkImage image_; + VkDeviceMemory memory_; + int width_; + int height_; +}; + + +class Thin3DPipelineCache { + +}; + +bool GLSLtoSPV(const VkShaderStageFlagBits shader_type, const char *pshader, std::vector &spirv); + +bool CreateShaderModule(VkDevice device, const std::vector &spirv, VkShaderModule *shaderModule); diff --git a/ext/native/ui/ui_screen.cpp b/ext/native/ui/ui_screen.cpp index 172b357273..acad8fbaca 100644 --- a/ext/native/ui/ui_screen.cpp +++ b/ext/native/ui/ui_screen.cpp @@ -58,7 +58,7 @@ void UIScreen::update(InputState &input) { void UIScreen::preRender() { Thin3DContext *thin3d = screenManager()->getThin3DContext(); - thin3d->Clear(T3DClear::COLOR | T3DClear::DEPTH | T3DClear::STENCIL, 0xFF000000, 0.0f, 0); + thin3d->Begin(true, 0xFF000000, 0.0f, 0); T3DViewport viewport; viewport.TopLeftX = 0; @@ -72,6 +72,8 @@ void UIScreen::preRender() { } void UIScreen::postRender() { + Thin3DContext *thin3d = screenManager()->getThin3DContext(); + thin3d->End(); } void UIScreen::render() { diff --git a/headless/Headless.cpp b/headless/Headless.cpp index 36c8ffa865..eba3ffca29 100644 --- a/headless/Headless.cpp +++ b/headless/Headless.cpp @@ -71,6 +71,7 @@ struct InputState; void D3D9_SwapBuffers() { } void GL_SwapBuffers() { } void GL_SwapInterval(int) { } +void Vulkan_SwapBuffers() {} void NativeUpdate(InputState &input_state) { } void NativeRender(GraphicsContext *graphicsContext) { } void NativeResized() { } diff --git a/headless/Headless.vcxproj b/headless/Headless.vcxproj index 0ed50f1a78..2225af37cf 100644 --- a/headless/Headless.vcxproj +++ b/headless/Headless.vcxproj @@ -106,7 +106,7 @@ Console true - Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86\lib\avcodec.lib;..\ffmpeg\Windows\x86\lib\avformat.lib;..\ffmpeg\Windows\x86\lib\avutil.lib;..\ffmpeg\Windows\x86\lib\swresample.lib;..\ffmpeg\Windows\x86\lib\swscale.lib;comctl32.lib;xinput.lib;d3d9.lib;d3dx9d.lib;dxguid.lib;%(AdditionalDependencies) + ..\ext\vulkan\vulkan-1.lib;Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86\lib\avcodec.lib;..\ffmpeg\Windows\x86\lib\avformat.lib;..\ffmpeg\Windows\x86\lib\avutil.lib;..\ffmpeg\Windows\x86\lib\swresample.lib;..\ffmpeg\Windows\x86\lib\swscale.lib;comctl32.lib;xinput.lib;d3d9.lib;d3dx9d.lib;dxguid.lib;%(AdditionalDependencies) 0x00400000 false true @@ -138,7 +138,7 @@ Console true - Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86_64\lib\avcodec.lib;..\ffmpeg\Windows\x86_64\lib\avformat.lib;..\ffmpeg\Windows\x86_64\lib\avutil.lib;..\ffmpeg\Windows\x86_64\lib\swresample.lib;..\ffmpeg\Windows\x86_64\lib\swscale.lib;comctl32.lib;d3d9.lib;d3dx9d.lib;dxguid.lib;%(AdditionalDependencies) + ..\Windows\x64\Debug\glslang.lib;..\ext\vulkan\vulkan-1.lib;Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86_64\lib\avcodec.lib;..\ffmpeg\Windows\x86_64\lib\avformat.lib;..\ffmpeg\Windows\x86_64\lib\avutil.lib;..\ffmpeg\Windows\x86_64\lib\swresample.lib;..\ffmpeg\Windows\x86_64\lib\swscale.lib;comctl32.lib;d3d9.lib;d3dx9d.lib;dxguid.lib;%(AdditionalDependencies) 0x00400000 false true @@ -173,7 +173,7 @@ true true true - Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86\lib\avcodec.lib;..\ffmpeg\Windows\x86\lib\avformat.lib;..\ffmpeg\Windows\x86\lib\avutil.lib;..\ffmpeg\Windows\x86\lib\swresample.lib;..\ffmpeg\Windows\x86\lib\swscale.lib;comctl32.lib;d3d9.lib;d3dx9.lib;dxguid.lib;%(AdditionalDependencies) + ..\ext\vulkan\vulkan-1.lib;Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86\lib\avcodec.lib;..\ffmpeg\Windows\x86\lib\avformat.lib;..\ffmpeg\Windows\x86\lib\avutil.lib;..\ffmpeg\Windows\x86\lib\swresample.lib;..\ffmpeg\Windows\x86\lib\swscale.lib;comctl32.lib;d3d9.lib;d3dx9.lib;dxguid.lib;%(AdditionalDependencies) 0x00400000 false true @@ -209,7 +209,7 @@ true true true - Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86_64\lib\avcodec.lib;..\ffmpeg\Windows\x86_64\lib\avformat.lib;..\ffmpeg\Windows\x86_64\lib\avutil.lib;..\ffmpeg\Windows\x86_64\lib\swresample.lib;..\ffmpeg\Windows\x86_64\lib\swscale.lib;comctl32.lib;d3d9.lib;d3dx9.lib;dxguid.lib;%(AdditionalDependencies) + ..\ext\vulkan\vulkan-1.lib;Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86_64\lib\avcodec.lib;..\ffmpeg\Windows\x86_64\lib\avformat.lib;..\ffmpeg\Windows\x86_64\lib\avutil.lib;..\ffmpeg\Windows\x86_64\lib\swresample.lib;..\ffmpeg\Windows\x86_64\lib\swscale.lib;comctl32.lib;d3d9.lib;d3dx9.lib;dxguid.lib;%(AdditionalDependencies) 0x00400000 false true @@ -269,4 +269,4 @@ - \ No newline at end of file + diff --git a/unittest/UnitTest.cpp b/unittest/UnitTest.cpp index e020d61191..3c8d6ccd40 100644 --- a/unittest/UnitTest.cpp +++ b/unittest/UnitTest.cpp @@ -54,6 +54,7 @@ std::string System_GetProperty(SystemProperty prop) { return ""; } int System_GetPropertyInt(SystemProperty prop) { return -1; } void NativeMessageReceived(const char *message, const char *value) {} void GL_SwapInterval(int) {} +void Vulkan_SwapBuffers() {} #ifndef M_PI_2 #define M_PI_2 1.57079632679489661923 diff --git a/unittest/UnitTests.vcxproj b/unittest/UnitTests.vcxproj index 9f396c145a..212bd576fd 100644 --- a/unittest/UnitTests.vcxproj +++ b/unittest/UnitTests.vcxproj @@ -100,7 +100,7 @@ Console true - Ws2_32.lib;winmm.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;opengl32.lib;dsound.lib;glu32.lib;avcodec.lib;avformat.lib;avutil.lib;swresample.lib;swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) + ..\ext\vulkan\vulkan-1.lib;Ws2_32.lib;winmm.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;opengl32.lib;dsound.lib;glu32.lib;avcodec.lib;avformat.lib;avutil.lib;swresample.lib;swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) /ignore:4049 /ignore:4217 %(AdditionalOptions) ..\ffmpeg\Windows\x86\lib @@ -123,7 +123,7 @@ Console true - Ws2_32.lib;winmm.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;opengl32.lib;dsound.lib;glu32.lib;avcodec.lib;avformat.lib;avutil.lib;swresample.lib;swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) + ..\Windows\x64\Debug\glslang.lib;..\ext\vulkan\vulkan-1.lib;Ws2_32.lib;winmm.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;opengl32.lib;dsound.lib;glu32.lib;avcodec.lib;avformat.lib;avutil.lib;swresample.lib;swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) /ignore:4049 /ignore:4217 %(AdditionalOptions) ..\ffmpeg\Windows\x86_64\lib @@ -149,7 +149,7 @@ true true true - Ws2_32.lib;winmm.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;opengl32.lib;dsound.lib;glu32.lib;avcodec.lib;avformat.lib;avutil.lib;swresample.lib;swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) + ..\ext\vulkan\vulkan-1.lib;Ws2_32.lib;winmm.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;opengl32.lib;dsound.lib;glu32.lib;avcodec.lib;avformat.lib;avutil.lib;swresample.lib;swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) /ignore:4049 /ignore:4217 %(AdditionalOptions) ..\ffmpeg\Windows\x86\lib @@ -174,7 +174,7 @@ true true true - Ws2_32.lib;winmm.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;opengl32.lib;dsound.lib;glu32.lib;avcodec.lib;avformat.lib;avutil.lib;swresample.lib;swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) + ..\ext\vulkan\vulkan-1.lib;Ws2_32.lib;winmm.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;opengl32.lib;dsound.lib;glu32.lib;avcodec.lib;avformat.lib;avutil.lib;swresample.lib;swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) /ignore:4049 /ignore:4217 %(AdditionalOptions) ..\ffmpeg\Windows\x86_64\lib @@ -219,4 +219,4 @@ - \ No newline at end of file + From eedd81988c92d8adfbe9856cf7fbd38b31df0950 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Wed, 6 Jan 2016 12:52:08 +0100 Subject: [PATCH 002/116] Implement a trivial SPIR-V disassembler, just for fun --- Common/Common.vcxproj | 2 + Common/Common.vcxproj.filters | 11 +- Common/Vulkan/SPIRVDisasm.cpp | 616 ++++++++++++++++++++++++++++ Common/Vulkan/SPIRVDisasm.h | 9 + ext/native/thin3d/thin3d_vulkan.cpp | 15 +- 5 files changed, 650 insertions(+), 3 deletions(-) create mode 100644 Common/Vulkan/SPIRVDisasm.cpp create mode 100644 Common/Vulkan/SPIRVDisasm.h diff --git a/Common/Common.vcxproj b/Common/Common.vcxproj index 91be776722..48727fc670 100644 --- a/Common/Common.vcxproj +++ b/Common/Common.vcxproj @@ -239,6 +239,7 @@ + @@ -307,6 +308,7 @@ + diff --git a/Common/Common.vcxproj.filters b/Common/Common.vcxproj.filters index cc8b91d6ad..62356cf7e1 100644 --- a/Common/Common.vcxproj.filters +++ b/Common/Common.vcxproj.filters @@ -58,6 +58,9 @@ + + Vulkan + @@ -103,6 +106,9 @@ GL\GLInterface + + Vulkan + @@ -117,5 +123,8 @@ {2c723cf4-75b6-406a-90c0-ebb7a13ba476} + + {c14d66ef-5f7c-4565-975a-72774e7ccfb9} + - \ No newline at end of file + diff --git a/Common/Vulkan/SPIRVDisasm.cpp b/Common/Vulkan/SPIRVDisasm.cpp new file mode 100644 index 0000000000..85bcde7485 --- /dev/null +++ b/Common/Vulkan/SPIRVDisasm.cpp @@ -0,0 +1,616 @@ +#include + +#include "Common/StringUtils.h" +#include "Common/Vulkan/SPIRVDisasm.h" +#include "ext/vulkan/spirv.hpp" + +#define WRITE p+=sprintf + +struct SpirvID { + std::string name; + int opcode; +}; + +struct OpInfo { + const char *name; + const char *extra; +}; + +static const char *executionModelNames[] = { + "Vertex", // 0, + "TessellationControl", // 1, + "TessellationEvaluation", // 2, + "Geometry", // 3, + "Fragment", // 4, + "GLCompute", // 5, + "Kernel", // 6, +}; + +static const char *storageClassNames[] = { + "UniformConstant", + "Input", + "Uniform", + "Output", + "Workgroup", + "CrossWorkgroup", + "Private", + "Function", + "Generic", + "PushConstant", + "AtomicCounter", + "Image", +}; + +static const char *decorationNames[] = { + "RelaxedPrecision", // 0, + "SpecId", // 1, + "Block", // 2, + "BufferBlock", // 3, + "RowMajor", // 4, + "ColMajor", // 5, + "ArrayStride", // 6, + "MatrixStride", // 7, + "GLSLShared", // 8, + "GLSLPacked", // 9, + "CPacked", // 10, + "BuiltIn", // 11, + nullptr, // 12 + "NoPerspective", // 13, + "Flat", // 14, + "Patch", // 15, + "Centroid", // 16, + "Sample", // 17, + "Invariant", // 18, + "Restrict", // 19, + "Aliased", // 20, + "Volatile", // 21, + "Constant", // 22, + "Coherent", // 23, + "NonWritable", // 24, + "NonReadable", // 25, + "Uniform", // 26, + nullptr, // 27 + "SaturatedConversion", // 28, + "Stream", // 29, + "Location", // 30, + "Component", // 31, + "Index", // 32, + "Binding", // 33, + "DescriptorSet", // 34, + "Offset", // 35, + "XfbBuffer", // 36, + "XfbStride", // 37, + "FuncParamAttr", // 38, + "FPRoundingMode", // 39, + "FPFastMathMode", // 40, + "LinkageAttributes", // 41, + "NoContraction", // 42, + "InputAttachmentIndex", // 43, + "Alignment", // 44, +}; + +static const OpInfo opInfo[] = { + {"Nop"}, // 0, + {"Undef"}, // 1, + {"SourceContinued"}, // 2, + {"Source"}, // 3, + {"SourceExtension"}, // 4, + {"Name"}, // 5, + {"MemberName"}, // 6, + {"String"}, // 7, + {"Line"}, // 8, + {nullptr}, // 9 + {"Extension"}, // 10, + {"ExtInstImport"}, // 11, + {"ExtInst"}, // 12, + {nullptr}, // 13 + {"MemoryModel"}, // 14, + {"EntryPoint"}, // 15, + {"ExecutionMode"}, // 16, + {"Capability"}, // 17, + {nullptr}, // 18 + {"TypeVoid"}, // 19, + {"TypeBool"}, // 20, + {"TypeInt"}, // 21, + {"TypeFloat"}, // 22, + {"TypeVector"}, // 23, + {"TypeMatrix"}, // 24, + {"TypeImage"}, // 25, + {"TypeSampler"}, // 26, + {"TypeSampledImage"}, // 27, + {"TypeArray"}, // 28, + {"TypeRuntimeArray"}, // 29, + {"TypeStruct"}, // 30, + {"TypeOpaque"}, // 31, + {"TypePointer"}, // 32, + {"TypeFunction"}, // 33, + {"TypeEvent"}, // 34, + {"TypeDeviceEvent"}, // 35, + {"TypeReserveId"}, // 36, + {"TypeQueue"}, // 37, + {"TypePipe"}, // 38, + {"TypeForwardPointer"}, // 39, + {nullptr}, // 40 + {"ConstantTrue"}, // 41, + {"ConstantFalse"}, // 42, + {"Constant"}, // 43, + {"ConstantComposite"}, // 44, + {"ConstantSampler"}, // 45, + {"ConstantNull"}, // 46, + {nullptr}, // 47 + {"SpecConstantTrue"}, // 48, + {"SpecConstantFalse"}, // 49, + {"SpecConstant"}, // 50, + {"SpecConstantComposite"}, // 51, + {"SpecConstantOp"}, // 52, + {nullptr}, // 53 + {"Function"}, // 54, + {"FunctionParameter"}, // 55, + {"FunctionEnd"}, // 56, + {"FunctionCall"}, // 57, + {nullptr}, // 58 + {"Variable"}, // 59, + {"ImageTexelPointer"}, // 60, + {"Load"}, // 61, + {"Store"}, // 62, + {"CopyMemory"}, // 63, + {"CopyMemorySized"}, // 64, + {"AccessChain"}, // 65, + {"InBoundsAccessChain"}, // 66, + {"PtrAccessChain"}, // 67, + {"ArrayLength"}, // 68, + {"GenericPtrMemSemantics"}, // 69, + {"InBoundsPtrAccessChain"}, // 70, + {"Decorate"}, // 71, + {"MemberDecorate"}, // 72, + {"DecorationGroup"}, // 73, + {"GroupDecorate"}, // 74, + {"GroupMemberDecorate"}, // 75, + {nullptr}, // 76 + {"VectorExtractDynamic"}, // 77, + {"VectorInsertDynamic"}, // 78, + {"VectorShuffle"}, // 79, + {"CompositeConstruct"}, // 80, + {"CompositeExtract"}, // 81, + {"CompositeInsert"}, // 82, + {"CopyObject"}, // 83, + {"Transpose"}, // 84, + {nullptr}, // 85 + {"SampledImage"}, // 86, + {"ImageSampleImplicitLod"}, // 87, + {"ImageSampleExplicitLod"}, // 88, + {"ImageSampleDrefImplicitLod"}, // 89, + {"ImageSampleDrefExplicitLod"}, // 90, + {"ImageSampleProjImplicitLod"}, // 91, + {"ImageSampleProjExplicitLod"}, // 92, + {"ImageSampleProjDrefImplicitLod"}, // 93, + {"ImageSampleProjDrefExplicitLod"}, // 94, + {"ImageFetch"}, // 95, + {"ImageGather"}, // 96, + {"ImageDrefGather"}, // 97, + {"ImageRead"}, // 98, + {"ImageWrite"}, // 99, + {"Image"}, // 100, + {"ImageQueryFormat"}, // 101, + {"ImageQueryOrder"}, // 102, + {"ImageQuerySizeLod"}, // 103, + {"ImageQuerySize"}, // 104, + {"ImageQueryLod"}, // 105, + {"ImageQueryLevels"}, // 106, + {"ImageQuerySamples"}, // 107, + {nullptr}, // 108 + {"ConvertFToU"}, // 109, + {"ConvertFToS"}, // 110, + {"ConvertSToF"}, // 111, + {"ConvertUToF"}, // 112, + {"UConvert"}, // 113, + {"SConvert"}, // 114, + {"FConvert"}, // 115, + {"QuantizeToF16"}, // 116, + {"ConvertPtrToU"}, // 117, + {"SatConvertSToU"}, // 118, + {"SatConvertUToS"}, // 119, + {"ConvertUToPtr"}, // 120, + {"PtrCastToGeneric"}, // 121, + {"GenericCastToPtr"}, // 122, + {"GenericCastToPtrExplicit"}, // 123, + {"Bitcast"}, // 124, + {nullptr}, // 125 + {"SNegate"}, // 126, + {"FNegate"}, // 127, + {"IAdd"}, // 128, + {"FAdd", "+"}, // 129, + {"ISub"}, // 130, + {"FSub", "-"}, // 131, + {"IMul"}, // 132, + {"FMul", "*"}, // 133, + {"UDiv"}, // 134, + {"SDiv"}, // 135, + {"FDiv", "/"}, // 136, + {"UMod"}, // 137, + {"SRem"}, // 138, + {"SMod"}, // 139, + {"FRem"}, // 140, + {"FMod", "%"}, // 141, + {"VectorTimesScalar"}, // 142, + {"MatrixTimesScalar"}, // 143, + {"VectorTimesMatrix"}, // 144, + {"MatrixTimesVector"}, // 145, + {"MatrixTimesMatrix"}, // 146, + {"OuterProduct"}, // 147, + {"Dot", " dot "}, // 148, + {"IAddCarry"}, // 149, + {"ISubBorrow"}, // 150, + {"UMulExtended"}, // 151, + {"SMulExtended"}, // 152, + {nullptr}, // 153 + {"Any"}, // 154, + {"All"}, // 155, + {"IsNan"}, // 156, + {"IsInf"}, // 157, + {"IsFinite"}, // 158, + {"IsNormal"}, // 159, + {"SignBitSet"}, // 160, + {"LessOrGreater"}, // 161, + {"Ordered"}, // 162, + {"Unordered"}, // 163, + {"LogicalEqual"}, // 164, + {"LogicalNotEqual"}, // 165, + {"LogicalOr"}, // 166, + {"LogicalAnd"}, // 167, + {"LogicalNot"}, // 168, + {"Select"}, // 169, + {"IEqual"}, // 170, + {"INotEqual"}, // 171, + {"UGreaterThan"}, // 172, + {"SGreaterThan"}, // 173, + {"UGreaterThanEqual"}, // 174, + {"SGreaterThanEqual"}, // 175, + {"ULessThan"}, // 176, + {"SLessThan"}, // 177, + {"ULessThanEqual"}, // 178, + {"SLessThanEqual"}, // 179, + {"FOrdEqual", "=="}, // 180, + {"FUnordEqual", "=="}, // 181, + {"FOrdNotEqual", "!="}, // 182, + {"FUnordNotEqual", "!="}, // 183, + {"FOrdLessThan"}, // 184, + {"FUnordLessThan"}, // 185, + {"FOrdGreaterThan"}, // 186, + {"FUnordGreaterThan"}, // 187, + {"FOrdLessThanEqual"}, // 188, + {"FUnordLessThanEqual"}, // 189, + {"FOrdGreaterThanEqual"}, // 190, + {"FUnordGreaterThanEqual"}, // 191, + { nullptr }, // 192 + { nullptr }, // 193 + {"ShiftRightLogical"}, // 194, + {"ShiftRightArithmetic"}, // 195, + {"ShiftLeftLogical"}, // 196, + {"BitwiseOr", "|"}, // 197, + {"BitwiseXor", "^"}, // 198, + {"BitwiseAnd", "&"}, // 199, + {"Not", "~"}, // 200, + {"BitFieldInsert"}, // 201, + {"BitFieldSExtract"}, // 202, + {"BitFieldUExtract"}, // 203, + {"BitReverse"}, // 204, + {"BitCount"}, // 205, + {nullptr}, + {"DPdx"}, // 207, + {"DPdy"}, // 208, + {"Fwidth"}, // 209, + {"DPdxFine"}, // 210, + {"DPdyFine"}, // 211, + {"FwidthFine"}, // 212, + {"DPdxCoarse"}, // 213, + {"DPdyCoarse"}, // 214, + {"FwidthCoarse"}, // 215, + {nullptr}, // 216 + {nullptr}, // 217 + {"EmitVertex"}, // 218, + {"EndPrimitive"}, // 219, + {"EmitStreamVertex"}, // 220, + {"EndStreamPrimitive"}, // 221, + {nullptr}, // 222 + {nullptr}, // 223 + {"ControlBarrier"}, // 224, + {"MemoryBarrier"}, // 225, + {nullptr}, // 226 + {"AtomicLoad"}, // 227, + {"AtomicStore"}, // 228, + {"AtomicExchange"}, // 229, + {"AtomicCompareExchange"}, // 230, + {"AtomicCompareExchangeWeak"}, // 231, + {"AtomicIIncrement"}, // 232, + {"AtomicIDecrement"}, // 233, + {"AtomicIAdd"}, // 234, + {"AtomicISub"}, // 235, + {"AtomicSMin"}, // 236, + {"AtomicUMin"}, // 237, + {"AtomicSMax"}, // 238, + {"AtomicUMax"}, // 239, + {"AtomicAnd"}, // 240, + {"AtomicOr"}, // 241, + {"AtomicXor"}, // 242, + { nullptr }, // 243, + { nullptr }, // 244, + {"Phi"}, // 245, + {"LoopMerge"}, // 246, + {"SelectionMerge"}, // 247, + {"Label"}, // 248, + {"Branch"}, // 249, + {"BranchConditional"}, // 250, + {"Switch"}, // 251, + {"Kill"}, // 252, + {"Return"}, // 253, + {"ReturnValue"}, // 254, + {"Unreachable"}, // 255, + {"LifetimeStart"}, // 256, + {"LifetimeStop"}, // 257, + { nullptr }, + {"GroupAsyncCopy"}, // 259, + {"GroupWaitEvents"}, // 260, + {"GroupAll"}, // 261, + {"GroupAny"}, // 262, + {"GroupBroadcast"}, // 263, + {"GroupIAdd"}, // 264, + {"GroupFAdd"}, // 265, + {"GroupFMin"}, // 266, + {"GroupUMin"}, // 267, + {"GroupSMin"}, // 268, + {"GroupFMax"}, // 269, + {"GroupUMax"}, // 270, + {"GroupSMax"}, // 271, + {nullptr}, // 272 + {nullptr}, // 273 + {"ReadPipe"}, // 274, + {"WritePipe"}, // 275, + {"ReservedReadPipe"}, // 276, + {"ReservedWritePipe"}, // 277, + {"ReserveReadPipePackets"}, // 278, + {"ReserveWritePipePackets"}, // 279, + {"CommitReadPipe"}, // 280, + {"CommitWritePipe"}, // 281, + {"IsValidReserveId"}, // 282, + {"GetNumPipePackets"}, // 283, + {"GetMaxPipePackets"}, // 284, + {"GroupReserveReadPipePackets"}, // 285, + {"GroupReserveWritePipePackets"}, // 286, + {"GroupCommitReadPipe"}, // 287, + {"GroupCommitWritePipe"}, // 288, + { nullptr }, // 289 + { nullptr }, // 290 + {"EnqueueMarker"}, // 291, + {"EnqueueKernel"}, // 292, + {"GetKernelNDrangeSubGroupCount"}, // 293, + {"GetKernelNDrangeMaxSubGroupSize"}, // 294, + {"GetKernelWorkGroupSize"}, // 295, + {"GetKernelPreferredWorkGroupSizeMultiple"}, // 296, + {"RetainEvent"}, // 297, + {"ReleaseEvent"}, // 298, + {"CreateUserEvent"}, // 299, + {"IsValidEvent"}, // 300, + {"SetUserEventStatus"}, // 301, + {"CaptureEventProfilingInfo"}, // 302, + {"GetDefaultQueue"}, // 303, + {"BuildNDRange"}, // 304, + {"ImageSparseSampleImplicitLod"}, // 305, + {"ImageSparseSampleExplicitLod"}, // 306, + {"ImageSparseSampleDrefImplicitLod"}, // 307, + {"ImageSparseSampleDrefExplicitLod"}, // 308, + {"ImageSparseSampleProjImplicitLod"}, // 309, + {"ImageSparseSampleProjExplicitLod"}, // 310, + {"ImageSparseSampleProjDrefImplicitLod"}, // 311, + {"ImageSparseSampleProjDrefExplicitLod"}, // 312, + {"ImageSparseFetch"}, // 313, + {"ImageSparseGather"}, // 314, + {"ImageSparseDrefGather"}, // 315, + {"ImageSparseTexelsResident"}, // 316, + {"NoLine"}, // 317, + {"AtomicFlagTestAndSet"}, // 318, + {"AtomicFlagClear"}, // 319, +}; + +static std::string ReadSpirvString(const std::vector &spirv, int offset, int *outOffset = nullptr) { + bool done = false; + std::string temp; + while (!done) { + uint32_t data = spirv[offset++]; + for (int i = 0; i < 4; i++) { + char c = (char)(data & 0xff); + if (!c) { + done = true; + break; + } + temp.push_back(data); + data >>= 8; + } + if (offset == (int)spirv.size()) + break; + } + if (outOffset) + *outOffset = offset; + return temp; +} + +bool DisassembleSPIRV(std::vector spirv, std::string *output) { + if (spirv.size() < 10) { + *output = "Too small"; + return false; + } + uint32_t magic = spirv[0]; + uint32_t version = spirv[1]; + uint32_t generator = spirv[2]; + + int bound = (int)spirv[3]; // Max ID used in file. + // spirv[4] is reserved for schema. + std::vector ids; + ids.resize(bound); + for (int i = 0; i < bound; i++) { + ids[i].name = StringFromFormat("%%%d", i); + } + + if (magic != 0x07230203) { + *output = "Not SPIRV"; + return false; + } + + int indent = 0; + + char *buffer = new char[1024 * 1024]; + char *p = buffer; + + WRITE(p, "// ======= SPIR-V version %08x =======\n// Max ID: %d\n", version, bound); // GLSL ES + + int i = 5; + while (i < (int)spirv.size()) { + uint32_t d = spirv[i]; + int wordCount = d >> 16; + int opcode = d & 0xFFFF; + const OpInfo &op = opInfo[opcode]; + int target = (i < (int)spirv.size() - 1) ? spirv[(i + 1)] : 0; // Not always, but used often enough that we get it here. + int source, source2, resType; + std::string name; + switch (opcode) { + case spv::OpTypeVoid: + case spv::OpTypeBool: + case spv::OpTypeInt: + case spv::OpTypeFloat: + case spv::OpTypeMatrix: + case spv::OpTypeImage: + case spv::OpTypeSampler: + case spv::OpTypeSampledImage: + case spv::OpTypeRuntimeArray: + case spv::OpTypeOpaque: + case spv::OpTypePointer: + case spv::OpTypeFunction: + case spv::OpTypeEvent: + case spv::OpTypeDeviceEvent: + case spv::OpTypeReserveId: + case spv::OpTypeQueue: + case spv::OpTypePipe: + case spv::OpTypeForwardPointer: + ids[target].name = op.name + 4; // Remove "Type" + ids[target].opcode = opcode; + break; + case spv::OpTypeVector: + source = spirv[i + 2]; + source2 = spirv[i + 3]; + ids[target].name = ids[source].name + StringFromFormat("%d", source2); break; + break; + case spv::OpTypeArray: + source = spirv[i + 2]; + source2 = spirv[i + 3]; + ids[target].name = ids[source].name + "[" + ids[source2].name + "]"; break; + break; + case spv::OpTypeStruct: + { + ids[target].name = "struct" + ids[target].name; + WRITE(p, "struct {\n"); + if (wordCount == 3) { + source = spirv[i + 2]; + WRITE(p, " %s\n", ids[source].name.c_str()); + } else { + int numMembers = (wordCount - 2) / 2; + for (int m = 0; m < numMembers; m++) { + int id = spirv[i + 2 + m]; + int type = spirv[i + 2 + m + numMembers]; + WRITE(p, " %s %s;\n", ids[type].name.c_str(), ids[id].name.c_str()); + } + } + WRITE(p, "};\n"); + } + break; + case spv::OpVariable: + resType = spirv[i + 1]; + target = spirv[i + 2]; + source = spirv[i + 3]; + source2 = spirv[i + 4]; + ids[target].name = storageClassNames[source]; + break; + case spv::OpDecorate: + source = spirv[i + 2]; + ids[target].name += std::string("[") + decorationNames[source] + "]"; + break; + case spv::OpName: + ids[target].name = ReadSpirvString(spirv, i + 2); + // WRITE(p, "Name %d: '%s'\n", target, ids[target].name.c_str()); + break; + case spv::OpMemberName: + break; + case spv::OpStore: + source = spirv[i + 2]; + WRITE(p, "Store(%s, %s)\n", ids[target].name.c_str(), ids[source].name.c_str()); + break; + case spv::OpLoad: + resType = spirv[i + 1]; + target = spirv[i + 2]; + source = spirv[i + 3]; + WRITE(p, "%s (%s) := Load(%s)\n", ids[target].name.c_str(), ids[resType].name.c_str(), ids[source].name.c_str()); + break; + case spv::OpFAdd: + case spv::OpFMul: + case spv::OpFDiv: + case spv::OpFSub: + resType = spirv[i + 2]; + source = spirv[i + 3]; + source2 = spirv[i + 4]; + WRITE(p, "%s (%s) := %s %s %s\n", ids[target].name.c_str(), ids[resType].name.c_str(), ids[source].name.c_str(), op.extra, ids[source2].name.c_str()); + break; + + case spv::OpCapability: + case spv::OpMemoryModel: + case spv::OpExtInstImport: + case spv::OpExecutionMode: + case spv::OpGroupAsyncCopy: + case spv::OpSource: + case spv::OpExtension: + // hide these for now + break; + + case spv::OpEntryPoint: + source = spirv[i + 1]; + source2 = spirv[i + 2]; + name = ReadSpirvString(spirv, i + 3); + WRITE(p, "EntryPoint %s: '%s' %s : %s\n", executionModelNames[target], ids[source].name.c_str(), ids[source2].name.c_str(), name.c_str()); + break; + + case spv::OpFunction: + resType = spirv[i + 1]; + target = spirv[i + 2]; + source = spirv[i + 3]; + ids[target].name = ids[resType].name + "()"; + WRITE(p, "Function %s {\n", ids[target].name.c_str()); + break; + + case spv::OpLabel: + WRITE(p, "label %s:\n", ids[target].name.c_str()); + break; + + case spv::OpReturnValue: + WRITE(p, "return %s\n", ids[target].name.c_str()); + break; + + case spv::OpReturn: + WRITE(p, "return\n"); + break; + + case spv::OpFunctionEnd: + WRITE(p, "}\n"); + break; + + case spv::OpSourceExtension: + break; + + default: + WRITE(p, "%s (%d data words)\n", op.name, wordCount - 1); + break; + } + i += wordCount; + } + + *output = buffer; + delete[] buffer; + return true; +} \ No newline at end of file diff --git a/Common/Vulkan/SPIRVDisasm.h b/Common/Vulkan/SPIRVDisasm.h new file mode 100644 index 0000000000..199f5048fb --- /dev/null +++ b/Common/Vulkan/SPIRVDisasm.h @@ -0,0 +1,9 @@ +#pragma once + +#include +#include +#include + +// Mostly just a toy to understand SPIR-V better. + +bool DisassembleSPIRV(std::vector spirv, std::string *output); \ No newline at end of file diff --git a/ext/native/thin3d/thin3d_vulkan.cpp b/ext/native/thin3d/thin3d_vulkan.cpp index f9426d61cb..d6be27a68c 100644 --- a/ext/native/thin3d/thin3d_vulkan.cpp +++ b/ext/native/thin3d/thin3d_vulkan.cpp @@ -21,6 +21,8 @@ #include #include +#include "Common/Vulkan/SPIRVDisasm.h" + #include "base/logging.h" #include "base/display.h" #include "image/zim_load.h" @@ -294,7 +296,16 @@ bool Thin3DVKShader::Compile(VkDevice device, const char *source) { return false; } - if (!CreateShaderModule(device, spirv, &module_)) { + // Just for kicks, sanity check the SPIR-V. The disasm isn't perfect + // but gives you some idea of what's going on. +#if 0 + std::string disasm; + if (DisassembleSPIRV(spirv, &disasm)) { + OutputDebugStringA(disasm.c_str()); + } +#endif + + if (vulkan->CreateShaderModule(spirv, &module_)) { ok_ = true; } else { ok_ = false; @@ -1381,4 +1392,4 @@ void Thin3DVKContext::Clear(int mask, uint32_t colorval, float depthVal, int ste Thin3DContext *T3DCreateVulkanContext(VulkanContext *vulkan) { return new Thin3DVKContext(vulkan); -} \ No newline at end of file +} From 2a449f78bbefe8d8217edc4f9bc7bcf6b116b614 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 20 Dec 2015 23:39:03 +0100 Subject: [PATCH 003/116] More vulkan fixing --- Common/Common.vcxproj | 3 ++- Core/Core.vcxproj | 4 +-- GPU/GPU.vcxproj | 4 +-- UI/UI.vcxproj | 4 +-- Windows/GPU/WindowsVulkanContext.cpp | 17 +++++++++--- Windows/GPU/WindowsVulkanContext.h | 2 -- Windows/PPSSPP.vcxproj | 13 +++++----- Windows/WindowsHost.cpp | 4 ++- ext/libarmips.vcxproj | 5 ++-- ext/libkirk/libkirk.vcxproj | 4 +-- ext/native/native.vcxproj | 5 ++-- ext/native/thin3d/VulkanContext.cpp | 29 +++++++++++---------- ext/native/thin3d/VulkanContext.h | 4 +-- ext/native/thin3d/thin3d_vulkan.cpp | 39 ++++++++++++++++++---------- ext/native/thin3d/vulkan_utils.cpp | 1 - ext/zlib/zlib.vcxproj | 4 +-- headless/Headless.vcxproj | 4 +-- unittest/UnitTests.vcxproj | 12 ++++----- 18 files changed, 91 insertions(+), 67 deletions(-) diff --git a/Common/Common.vcxproj b/Common/Common.vcxproj index 48727fc670..c8fc1adc26 100644 --- a/Common/Common.vcxproj +++ b/Common/Common.vcxproj @@ -170,6 +170,7 @@ true false MultiThreaded + true Windows @@ -323,4 +324,4 @@ - \ No newline at end of file + diff --git a/Core/Core.vcxproj b/Core/Core.vcxproj index 09b1d79cfc..514cf98e74 100644 --- a/Core/Core.vcxproj +++ b/Core/Core.vcxproj @@ -45,7 +45,6 @@ StaticLibrary false - false Unicode v140_xp @@ -158,6 +157,7 @@ USING_WIN_UI;_CRT_SECURE_NO_WARNINGS;USE_FFMPEG;WIN32;_ARCH_64=1;_M_X64=1;_LIB;NDEBUG;_UNICODE;UNICODE;%(PreprocessorDefinitions) false MultiThreaded + true true @@ -737,4 +737,4 @@ - \ No newline at end of file + diff --git a/GPU/GPU.vcxproj b/GPU/GPU.vcxproj index 8319755356..8ac43081a1 100644 --- a/GPU/GPU.vcxproj +++ b/GPU/GPU.vcxproj @@ -45,7 +45,6 @@ StaticLibrary false - false Unicode v140_xp @@ -168,6 +167,7 @@ false USING_WIN_UI;_CRT_SECURE_NO_WARNINGS;WIN32;_ARCH_64=1;_M_X64=1;_LIB;NDEBUG;_UNICODE;UNICODE;%(PreprocessorDefinitions) MultiThreaded + true true @@ -350,4 +350,4 @@ - \ No newline at end of file + diff --git a/UI/UI.vcxproj b/UI/UI.vcxproj index 5886b99bfb..596eba30a8 100644 --- a/UI/UI.vcxproj +++ b/UI/UI.vcxproj @@ -104,7 +104,6 @@ StaticLibrary false v140_xp - false Unicode @@ -212,6 +211,7 @@ true false MultiThreaded + true Windows @@ -227,4 +227,4 @@ - \ No newline at end of file + diff --git a/Windows/GPU/WindowsVulkanContext.cpp b/Windows/GPU/WindowsVulkanContext.cpp index add7bc62f2..b19be7a81e 100644 --- a/Windows/GPU/WindowsVulkanContext.cpp +++ b/Windows/GPU/WindowsVulkanContext.cpp @@ -73,10 +73,17 @@ bool WindowsVulkanContext::Init(HINSTANCE hInst, HWND hWnd, std::string *error_m g_Vulkan->InitObjects(hInst, hWnd, true); _CrtCheckMemory(); + + VkClearValue clearVal[2]; + memset(clearVal, 0, sizeof(clearVal)); + clearVal[0].color.float32[0] = 0.5f; + g_Vulkan->BeginSurfaceRenderPass(clearVal); return true; } void WindowsVulkanContext::Shutdown() { + g_Vulkan->EndSurfaceRenderPass(); + g_Vulkan->DestroyObjects(); delete g_Vulkan; g_Vulkan = nullptr; @@ -87,6 +94,12 @@ Thin3DContext *WindowsVulkanContext::CreateThin3DContext() { } void WindowsVulkanContext::SwapBuffers() { + g_Vulkan->EndSurfaceRenderPass(); + + VkClearValue clearVal[2]; + memset(clearVal, 0, sizeof(clearVal)); + clearVal[0].color.float32[0] = 0.5f; + g_Vulkan->BeginSurfaceRenderPass(clearVal); } void WindowsVulkanContext::Resize() { @@ -101,7 +114,3 @@ void WindowsVulkanContext::Resize() { void WindowsVulkanContext::SwapInterval(int interval) { } - -Thin3DContext *Vulkan_CreateThin3DContext() { - return T3DCreateVulkanContext(g_Vulkan); -} diff --git a/Windows/GPU/WindowsVulkanContext.h b/Windows/GPU/WindowsVulkanContext.h index 99e736d01f..5fc24a8669 100644 --- a/Windows/GPU/WindowsVulkanContext.h +++ b/Windows/GPU/WindowsVulkanContext.h @@ -32,5 +32,3 @@ public: Thin3DContext *CreateThin3DContext() override; }; -void Vulkan_BeginSurfaceRender(); -void Vulkan_EndSurfaceRender(); diff --git a/Windows/PPSSPP.vcxproj b/Windows/PPSSPP.vcxproj index c889776f6c..8fdfd0717d 100644 --- a/Windows/PPSSPP.vcxproj +++ b/Windows/PPSSPP.vcxproj @@ -39,7 +39,6 @@ Application Unicode - false v140_xp @@ -135,7 +134,7 @@ Disabled - ..\ext\vulkan\vulkan-1.lib;Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86\lib\avcodec.lib;..\ffmpeg\Windows\x86\lib\avformat.lib;..\ffmpeg\Windows\x86\lib\avutil.lib;..\ffmpeg\Windows\x86\lib\swresample.lib;..\ffmpeg\Windows\x86\lib\swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;dxerr.lib;%(AdditionalDependencies) + ..\ext\vulkan\vulkan-1.lib;Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86\lib\avcodec.lib;..\ffmpeg\Windows\x86\lib\avformat.lib;..\ffmpeg\Windows\x86\lib\avutil.lib;..\ffmpeg\Windows\x86\lib\swresample.lib;..\ffmpeg\Windows\x86\lib\swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) true Windows MachineX86 @@ -175,11 +174,10 @@ x64\Debug\glslang.lib;..\ext\vulkan\vulkan-1.lib;Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86_64\lib\avcodec.lib;..\ffmpeg\Windows\x86_64\lib\avformat.lib;..\ffmpeg\Windows\x86_64\lib\avutil.lib;..\ffmpeg\Windows\x86_64\lib\swresample.lib;..\ffmpeg\Windows\x86_64\lib\swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) true $(OutDir)$(ProjectName).pdb - Windows - MachineX64 true NotSet /ignore:4049 /ignore:4217 %(AdditionalOptions) + Windows ../Windows/git-version-gen.cmd @@ -208,7 +206,7 @@ false - ..\ext\vulkan\vulkan-1.lib;dxerr.lib;Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86\lib\avcodec.lib;..\ffmpeg\Windows\x86\lib\avformat.lib;..\ffmpeg\Windows\x86\lib\avutil.lib;..\ffmpeg\Windows\x86\lib\swresample.lib;..\ffmpeg\Windows\x86\lib\swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) + ..\ext\vulkan\vulkan-1.lib;Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86\lib\avcodec.lib;..\ffmpeg\Windows\x86\lib\avformat.lib;..\ffmpeg\Windows\x86\lib\avutil.lib;..\ffmpeg\Windows\x86\lib\swresample.lib;..\ffmpeg\Windows\x86\lib\swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) $(OutDir)$(TargetName)$(TargetExt) %(AdditionalLibraryDirectories) true @@ -252,7 +250,7 @@ false - ..\ext\vulkan\vulkan-1.lib;dxerr.lib;Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86_64\lib\avcodec.lib;..\ffmpeg\Windows\x86_64\lib\avformat.lib;..\ffmpeg\Windows\x86_64\lib\avutil.lib;..\ffmpeg\Windows\x86_64\lib\swresample.lib;..\ffmpeg\Windows\x86_64\lib\swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) + ..\ext\vulkan\vulkan-1.lib;Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86_64\lib\avcodec.lib;..\ffmpeg\Windows\x86_64\lib\avformat.lib;..\ffmpeg\Windows\x86_64\lib\avutil.lib;..\ffmpeg\Windows\x86_64\lib\swresample.lib;..\ffmpeg\Windows\x86_64\lib\swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) %(AdditionalLibraryDirectories) true Windows @@ -260,6 +258,7 @@ true MachineX64 /ignore:4049 /ignore:4217 %(AdditionalOptions) + true ../Windows/git-version-gen.cmd @@ -454,4 +453,4 @@ - \ No newline at end of file + diff --git a/Windows/WindowsHost.cpp b/Windows/WindowsHost.cpp index b46c16e530..06f78162d6 100644 --- a/Windows/WindowsHost.cpp +++ b/Windows/WindowsHost.cpp @@ -69,7 +69,9 @@ static BOOL PostDialogMessage(Dialog *dialog, UINT message, WPARAM wParam = 0, L } WindowsHost::WindowsHost(HINSTANCE hInstance, HWND mainWindow, HWND displayWindow) - : gfx_(nullptr), hInstance_(hInstance), mainWindow_(mainWindow), displayWindow_(displayWindow) + : gfx_(nullptr), hInstance_(hInstance), + mainWindow_(mainWindow), + displayWindow_(displayWindow) { mouseDeltaX = 0; mouseDeltaY = 0; diff --git a/ext/libarmips.vcxproj b/ext/libarmips.vcxproj index f4f042f231..22bc0bba00 100644 --- a/ext/libarmips.vcxproj +++ b/ext/libarmips.vcxproj @@ -67,7 +67,6 @@ StaticLibrary false v140_xp - false Unicode @@ -221,6 +220,8 @@ WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions) MultiThreaded armips + false + true Windows @@ -333,4 +334,4 @@ - \ No newline at end of file + diff --git a/ext/libkirk/libkirk.vcxproj b/ext/libkirk/libkirk.vcxproj index 661bf7f609..cdc3e4f739 100644 --- a/ext/libkirk/libkirk.vcxproj +++ b/ext/libkirk/libkirk.vcxproj @@ -46,7 +46,6 @@ StaticLibrary false v140_xp - false Unicode @@ -129,6 +128,7 @@ true false MultiThreaded + true true @@ -156,4 +156,4 @@ - \ No newline at end of file + diff --git a/ext/native/native.vcxproj b/ext/native/native.vcxproj index 238f515b30..62927609fd 100644 --- a/ext/native/native.vcxproj +++ b/ext/native/native.vcxproj @@ -46,7 +46,6 @@ StaticLibrary false - false Unicode v140_xp @@ -160,6 +159,8 @@ true false MultiThreaded + false + true Windows @@ -749,4 +750,4 @@ - \ No newline at end of file + diff --git a/ext/native/thin3d/VulkanContext.cpp b/ext/native/thin3d/VulkanContext.cpp index a324fe7b44..cb94b93283 100644 --- a/ext/native/thin3d/VulkanContext.cpp +++ b/ext/native/thin3d/VulkanContext.cpp @@ -9,7 +9,10 @@ #undef new #endif +#pragma warning(push) +#pragma warning(disable:4996) #include "glslang/SPIRV/GlslangToSpv.h" +#pragma warning(pop) #ifdef USE_CRT_DBG #define new DBG_NEW @@ -61,19 +64,19 @@ VulkanContext::VulkanContext(const char *app_name, uint32_t flags) device_extension_names.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME); if (flags & VULKAN_FLAG_VALIDATE) { - instance_layer_names.push_back("VK_LAYER_LUNARG_Threading"); - instance_layer_names.push_back("VK_LAYER_LUNARG_DrawState"); - instance_layer_names.push_back("VK_LAYER_LUNARG_Image"); - instance_layer_names.push_back("VK_LAYER_LUNARG_MemTracker"); - instance_layer_names.push_back("VK_LAYER_LUNARG_ObjectTracker"); - instance_layer_names.push_back("VK_LAYER_LUNARG_ParamChecker"); + instance_layer_names.push_back("VK_LAYER_LUNARG_threading"); + instance_layer_names.push_back("VK_LAYER_LUNARG_draw_state"); + instance_layer_names.push_back("VK_LAYER_LUNARG_image"); + instance_layer_names.push_back("VK_LAYER_LUNARG_mem_tracker"); + instance_layer_names.push_back("VK_LAYER_LUNARG_object_tracker"); + instance_layer_names.push_back("VK_LAYER_LUNARG_param_checker"); - device_layer_names.push_back("VK_LAYER_LUNARG_Threading"); - device_layer_names.push_back("VK_LAYER_LUNARG_DrawState"); - device_layer_names.push_back("VK_LAYER_LUNARG_Image"); - device_layer_names.push_back("VK_LAYER_LUNARG_MemTracker"); - device_layer_names.push_back("VK_LAYER_LUNARG_ObjectTracker"); - device_layer_names.push_back("VK_LAYER_LUNARG_ParamChecker"); + device_layer_names.push_back("VK_LAYER_LUNARG_threading"); + device_layer_names.push_back("VK_LAYER_LUNARG_draw_state"); + device_layer_names.push_back("VK_LAYER_LUNARG_image"); + device_layer_names.push_back("VK_LAYER_LUNARG_mem_tracker"); + device_layer_names.push_back("VK_LAYER_LUNARG_object_tracker"); + device_layer_names.push_back("VK_LAYER_LUNARG_param_checker"); instance_extension_names.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME); } @@ -542,7 +545,7 @@ VkResult VulkanContext::CreateDevice(int physical_device) { assert(queue_count >= 1); bool found = false; - for (int i = 0; i < queue_count; i++) { + for (int i = 0; i < (int)queue_count; i++) { if (queue_props[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) { queue_info.queueFamilyIndex = i; found = true; diff --git a/ext/native/thin3d/VulkanContext.h b/ext/native/thin3d/VulkanContext.h index e1beaa09ee..c6fe04afc1 100644 --- a/ext/native/thin3d/VulkanContext.h +++ b/ext/native/thin3d/VulkanContext.h @@ -40,8 +40,8 @@ #include #endif // _WIN32 -#include "ext/vulkan/vulkan.h" -#include "ext/vulkan/vk_sdk_platform.h" +#include "vulkan/vulkan.h" +#include "vulkan/vk_sdk_platform.h" /* Amount of time, in nanoseconds, to wait for a command buffer to complete */ #define FENCE_TIMEOUT 10000000000 diff --git a/ext/native/thin3d/thin3d_vulkan.cpp b/ext/native/thin3d/thin3d_vulkan.cpp index d6be27a68c..3a2a2adb3e 100644 --- a/ext/native/thin3d/thin3d_vulkan.cpp +++ b/ext/native/thin3d/thin3d_vulkan.cpp @@ -124,7 +124,8 @@ public: b.sharingMode = VK_SHARING_MODE_EXCLUSIVE; b.queueFamilyIndexCount = 0; b.pQueueFamilyIndices = nullptr; - assert(VK_SUCCESS == vkCreateBuffer(device, &b, nullptr, &buffer_)); + VkResult res = vkCreateBuffer(device, &b, nullptr, &buffer_); + assert(VK_SUCCESS == res); // Okay, that's the buffer. Now let's allocate some memory for it. VkMemoryAllocateInfo alloc; @@ -133,8 +134,10 @@ public: memMan->memory_type_from_properties(0xFFFFFFFF, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, &alloc.memoryTypeIndex); alloc.allocationSize = size; - assert(VK_SUCCESS == vkAllocateMemory(device, &alloc, nullptr, &deviceMemory_)); - assert(VK_SUCCESS == vkBindBufferMemory(device, buffer_, deviceMemory_, 0)); + res = vkAllocateMemory(device, &alloc, nullptr, &deviceMemory_); + assert(VK_SUCCESS == res); + res = vkBindBufferMemory(device, buffer_, deviceMemory_, 0); + assert(VK_SUCCESS == res); } void Destroy(VkDevice device) { @@ -146,7 +149,8 @@ public: void Begin(VkDevice device) { offset_ = 0; - assert(VK_SUCCESS == vkMapMemory(device, deviceMemory_, 0, size_, 0, (void **)(&writePtr_))); + VkResult res = vkMapMemory(device, deviceMemory_, 0, size_, 0, (void **)(&writePtr_)); + assert(VK_SUCCESS == res); } void End(VkDevice device) { @@ -273,7 +277,7 @@ private: // invoke Compile again to recreate the shader then link them together. class Thin3DVKShader : public Thin3DShader { public: - Thin3DVKShader(bool isFragmentShader) : module_(nullptr), ok_(false) { + Thin3DVKShader(VulkanContext *vulkan, bool isFragmentShader) : vulkan_(vulkan), module_(nullptr), ok_(false) { stage_ = isFragmentShader ? VK_SHADER_STAGE_FRAGMENT_BIT : VK_SHADER_STAGE_VERTEX_BIT; } bool Compile(VkDevice device, const char *source); @@ -283,6 +287,7 @@ public: VkShaderModule Get() const { return module_; } private: + VulkanContext *vulkan_; VkShaderModule module_; VkShaderStageFlagBits stage_; bool ok_; @@ -305,7 +310,7 @@ bool Thin3DVKShader::Compile(VkDevice device, const char *source) { } #endif - if (vulkan->CreateShaderModule(spirv, &module_)) { + if (CreateShaderModule(device, spirv, &module_)) { ok_ = true; } else { ok_ = false; @@ -596,7 +601,7 @@ public: s.maxLod = 0.0; // TODO: Actually support mipmaps VkResult res = vkCreateSampler(vulkan_->Device(), &s, nullptr, &sampler_); - assert(res); + assert(VK_SUCCESS == res); } ~Thin3DVKSamplerState() { vkDestroySampler(vulkan_->Device(), sampler_, nullptr); @@ -781,7 +786,7 @@ Thin3DVKContext::Thin3DVKContext(VulkanContext *vulkan) res = vkCreateFence(device_, &f, nullptr, &cmdFences_[1]); assert(VK_SUCCESS == res); // Create as already signalled, so we can wait for it the first time. - // f.flags = VK_FENCE_CREATE_SIGNALED_BIT; + f.flags = VK_FENCE_CREATE_SIGNALED_BIT; res = vkCreateFence(device_, &f, nullptr, &initFence_); assert(VK_SUCCESS == res); pendingInitFence_ = false; @@ -794,6 +799,7 @@ Thin3DVKContext::Thin3DVKContext(VulkanContext *vulkan) pc.flags = 0; res = vkCreatePipelineCache(device_, &pc, nullptr, &pipelineCache_); assert(VK_SUCCESS == res); + push_ = pushBuffer_[0]; cmd_ = cmdBuffer_[0]; } @@ -836,12 +842,14 @@ void Thin3DVKContext::BeginInitCommands() { begin.pNext = nullptr; begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; begin.pInheritanceInfo = nullptr; - assert(VK_SUCCESS == vkBeginCommandBuffer(initCmd_, &begin)); + VkResult res = vkBeginCommandBuffer(initCmd_, &begin); + assert(VK_SUCCESS == res); hasInitCommands_ = true; } void Thin3DVKContext::EndInitCommands() { - assert(VK_SUCCESS == vkEndCommandBuffer(initCmd_)); + VkResult res = vkEndCommandBuffer(initCmd_); + assert(VK_SUCCESS == res); } void Thin3DVKContext::End() { @@ -861,7 +869,8 @@ void Thin3DVKContext::End() { submit.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submit.pCommandBuffers = &initCmd_; submit.commandBufferCount = 1; - assert(VK_SUCCESS == vkQueueSubmit(queue_, 1, &submit, initFence_)); + VkResult res = vkQueueSubmit(queue_, 1, &submit, initFence_); + assert(VK_SUCCESS == res); hasInitCommands_ = false; } @@ -873,7 +882,8 @@ void Thin3DVKContext::End() { submit.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submit.pCommandBuffers = &cmd_; submit.commandBufferCount = 1; - assert(VK_SUCCESS == vkQueueSubmit(queue_, 1, &submit, cmdFence_)); + VkResult res = vkQueueSubmit(queue_, 1, &submit, cmdFence_); + assert(VK_SUCCESS == res); } frameNum_++; @@ -905,6 +915,7 @@ VkDescriptorSet Thin3DVKContext::GetOrCreateDescriptorSet() { alloc.descriptorSetCount = 1; VkResult res = vkAllocateDescriptorSets(device_, &alloc, &descSet); assert(VK_SUCCESS == res); + // bindings[0].descriptorType = VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT; // bindings[1].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; // bindings[2].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER; @@ -1238,7 +1249,7 @@ void Thin3DVKContext::SetTextures(int start, int count, Thin3DTexture **textures } Thin3DShader *Thin3DVKContext::CreateVertexShader(const char *glsl_source, const char *hlsl_source, const char *vulkan_source) { - Thin3DVKShader *shader = new Thin3DVKShader(false); + Thin3DVKShader *shader = new Thin3DVKShader(vulkan_, false); if (shader->Compile(device_, vulkan_source)) { return shader; } else { @@ -1248,7 +1259,7 @@ Thin3DShader *Thin3DVKContext::CreateVertexShader(const char *glsl_source, const } Thin3DShader *Thin3DVKContext::CreateFragmentShader(const char *glsl_source, const char *hlsl_source, const char *vulkan_source) { - Thin3DVKShader *shader = new Thin3DVKShader(true); + Thin3DVKShader *shader = new Thin3DVKShader(vulkan_, true); if (shader->Compile(device_, vulkan_source)) { return shader; } else { diff --git a/ext/native/thin3d/vulkan_utils.cpp b/ext/native/thin3d/vulkan_utils.cpp index 264602a5b4..9af64294b9 100644 --- a/ext/native/thin3d/vulkan_utils.cpp +++ b/ext/native/thin3d/vulkan_utils.cpp @@ -156,7 +156,6 @@ void VulkanImage::ChangeLayout(VkCommandBuffer cmd, VkImageAspectFlags aspectMas vkCmdPipelineBarrier(cmd, src_stages, dest_stages, false, 0, nullptr, 0, nullptr, 1, &image_memory_barrier); } - bool CreateShaderModule(VkDevice device, const std::vector &spirv, VkShaderModule *shaderModule) { VkShaderModuleCreateInfo sm; sm.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; diff --git a/ext/zlib/zlib.vcxproj b/ext/zlib/zlib.vcxproj index 9a194bdff4..30bcd6ee0f 100644 --- a/ext/zlib/zlib.vcxproj +++ b/ext/zlib/zlib.vcxproj @@ -76,7 +76,6 @@ StaticLibrary false - false Unicode v140_xp @@ -183,6 +182,7 @@ true false MultiThreaded + true Windows @@ -194,4 +194,4 @@ - \ No newline at end of file + diff --git a/headless/Headless.vcxproj b/headless/Headless.vcxproj index 2225af37cf..d155cb76af 100644 --- a/headless/Headless.vcxproj +++ b/headless/Headless.vcxproj @@ -47,7 +47,6 @@ Application false - false Unicode v140_xp @@ -138,7 +137,7 @@ Console true - ..\Windows\x64\Debug\glslang.lib;..\ext\vulkan\vulkan-1.lib;Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86_64\lib\avcodec.lib;..\ffmpeg\Windows\x86_64\lib\avformat.lib;..\ffmpeg\Windows\x86_64\lib\avutil.lib;..\ffmpeg\Windows\x86_64\lib\swresample.lib;..\ffmpeg\Windows\x86_64\lib\swscale.lib;comctl32.lib;d3d9.lib;d3dx9d.lib;dxguid.lib;%(AdditionalDependencies) + ..\ext\vulkan\vulkan-1.lib;Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86_64\lib\avcodec.lib;..\ffmpeg\Windows\x86_64\lib\avformat.lib;..\ffmpeg\Windows\x86_64\lib\avutil.lib;..\ffmpeg\Windows\x86_64\lib\swresample.lib;..\ffmpeg\Windows\x86_64\lib\swscale.lib;comctl32.lib;d3d9.lib;d3dx9d.lib;dxguid.lib;%(AdditionalDependencies) 0x00400000 false true @@ -203,6 +202,7 @@ true false MultiThreaded + true Console diff --git a/unittest/UnitTests.vcxproj b/unittest/UnitTests.vcxproj index 212bd576fd..cc55ecec4a 100644 --- a/unittest/UnitTests.vcxproj +++ b/unittest/UnitTests.vcxproj @@ -48,7 +48,6 @@ Application false v140_xp - false Unicode @@ -88,8 +87,8 @@ Level3 - _CRTDBG_MAP_ALLOC;USING_WIN_UI;GLEW_STATIC;_CRT_SECURE_NO_WARNINGS;WIN32;_DEBUG;_ARCH_32=1;_WINDOWS;_UNICODE;UNICODE;%(PreprocessorDefinitions) - ../common;..;../ext/native;../ext/native/ext/glew;../ext/zlib + _CRTDBG_MAP_ALLOC;USING_WIN_UI;USING_WIN_UI;GLEW_STATIC;_CRT_SECURE_NO_WARNINGS;WIN32;_DEBUG;_ARCH_32=1;_WINDOWS;_UNICODE;UNICODE;%(PreprocessorDefinitions) + ../ext;../common;..;../ext/native;../ext/native/ext/glew;../ext/zlib true false false @@ -111,7 +110,7 @@ Level3 _CRTDBG_MAP_ALLOC;USING_WIN_UI;GLEW_STATIC;_CRT_SECURE_NO_WARNINGS;WIN32;_DEBUG;_ARCH_64=1;_WINDOWS;_UNICODE;UNICODE;%(PreprocessorDefinitions) - ../common;..;../ext/native;../ext/native/ext/glew;../ext/zlib + ../ext;../common;..;../ext/native;../ext/native/ext/glew;../ext/zlib true false false @@ -137,7 +136,7 @@ true true USING_WIN_UI;GLEW_STATIC;_CRT_SECURE_NO_WARNINGS;WIN32;NDEBUG;_ARCH_32=1;_WINDOWS;_UNICODE;UNICODE;%(PreprocessorDefinitions) - ../common;..;../ext/native;../ext/native/ext/glew;../ext/zlib + ../ext;../common;..;../ext/native;../ext/native/ext/glew;../ext/zlib false Speed true @@ -163,11 +162,12 @@ true true USING_WIN_UI;GLEW_STATIC;_CRT_SECURE_NO_WARNINGS;WIN32;NDEBUG;_ARCH_64=1;_WINDOWS;_UNICODE;UNICODE;%(PreprocessorDefinitions) - ../common;..;../ext/native;../ext/native/ext/glew;../ext/zlib + ../ext;../common;..;../ext/native;../ext/native/ext/glew;../ext/zlib false true false MultiThreaded + true Console From 847cab231fc4445938c303c8bf551f9245ce8974 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Thu, 31 Dec 2015 00:30:36 +0100 Subject: [PATCH 004/116] Fixes in VulkanContext --- ext/native/thin3d/VulkanContext.cpp | 18 +++++++++++++----- ext/native/thin3d/VulkanContext.h | 1 + 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/ext/native/thin3d/VulkanContext.cpp b/ext/native/thin3d/VulkanContext.cpp index cb94b93283..6a60bc0f22 100644 --- a/ext/native/thin3d/VulkanContext.cpp +++ b/ext/native/thin3d/VulkanContext.cpp @@ -55,8 +55,10 @@ VulkanContext::VulkanContext(const char *app_name, uint32_t flags) swap_chain_(nullptr), cmd_pool_(nullptr), cmd_(nullptr), + cmdInitActive_(false), dbgCreateMsgCallback(nullptr), - dbgDestroyMsgCallback(nullptr) + dbgDestroyMsgCallback(nullptr), + queue_count(0) { // List extensions to try to enable. instance_extension_names.push_back(VK_KHR_SURFACE_EXTENSION_NAME); @@ -273,11 +275,17 @@ void vk_submit_sync(VkDevice device, VkSemaphore waitForSemaphore, VkQueue queue } void VulkanContext::BeginInitCommandBuffer() { + assert(!cmdInitActive_); VulkanBeginCommandBuffer(cmd_); + cmdInitActive_ = true; } void VulkanContext::SubmitInitCommandBufferSync() { - vk_submit_sync(device_, 0, gfx_queue_, cmd_); + if (cmdInitActive_) { + vkEndCommandBuffer(cmd_); + vk_submit_sync(device_, 0, gfx_queue_, cmd_); + cmdInitActive_ = false; + } } void VulkanContext::InitObjects(HINSTANCE hInstance, HWND hWnd, bool depthPresent) { @@ -306,11 +314,11 @@ void VulkanContext::DestroyObjects() { void VulkanContext::EndSurfaceRenderPass() { vkCmdEndRenderPass(cmd_); + vk_transition_to_present(cmd_, swapChainBuffers[current_buffer].image); + VkResult res = vkEndCommandBuffer(cmd_); assert(res == VK_SUCCESS); - vk_transition_to_present(cmd_, swapChainBuffers[current_buffer].image); - /* Make sure command buffer is finished before presenting */ vk_submit_sync(device_, acquireSemaphore, gfx_queue_, cmd_); // At this point we are certain that acquireSemaphore is of no further use and can be destroyed. @@ -1056,7 +1064,7 @@ void VulkanContext::InitCommandPool() { cmd_pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; cmd_pool_info.pNext = NULL; cmd_pool_info.queueFamilyIndex = gfx_queue_family_index_; - cmd_pool_info.flags = 0; + cmd_pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT | VK_COMMAND_POOL_CREATE_TRANSIENT_BIT; res = vkCreateCommandPool(device_, &cmd_pool_info, NULL, &cmd_pool_); assert(res == VK_SUCCESS); diff --git a/ext/native/thin3d/VulkanContext.h b/ext/native/thin3d/VulkanContext.h index c6fe04afc1..ad382958fa 100644 --- a/ext/native/thin3d/VulkanContext.h +++ b/ext/native/thin3d/VulkanContext.h @@ -161,6 +161,7 @@ public: VkCommandPool cmd_pool_; VkCommandBuffer cmd_; // Buffer for initialization commands + bool cmdInitActive_; VkInstance instance_; VkDevice device_; From 2a71e164f5cfd24aebc4eccac180f9ec0e4e69ac Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Thu, 31 Dec 2015 00:30:52 +0100 Subject: [PATCH 005/116] Enable vulkan validation --- Common/Vulkan/SPIRVDisasm.h | 3 +- Windows/GPU/WindowsVulkanContext.cpp | 78 ++++++++++++++++++++++++++-- Windows/PPSSPP.vcxproj | 2 +- 3 files changed, 77 insertions(+), 6 deletions(-) diff --git a/Common/Vulkan/SPIRVDisasm.h b/Common/Vulkan/SPIRVDisasm.h index 199f5048fb..d5d036fbb4 100644 --- a/Common/Vulkan/SPIRVDisasm.h +++ b/Common/Vulkan/SPIRVDisasm.h @@ -4,6 +4,7 @@ #include #include -// Mostly just a toy to understand SPIR-V better. +// Mostly just a toy to understand SPIR-V better. Not an accurate SPIR-V disassembler, +// and the result will not reassemble. bool DisassembleSPIRV(std::vector spirv, std::string *output); \ No newline at end of file diff --git a/Windows/GPU/WindowsVulkanContext.cpp b/Windows/GPU/WindowsVulkanContext.cpp index b19be7a81e..0f37bb0d96 100644 --- a/Windows/GPU/WindowsVulkanContext.cpp +++ b/Windows/GPU/WindowsVulkanContext.cpp @@ -48,8 +48,7 @@ #include #include - -#define VK_PROTOTYPES +#include #include "ext/vulkan/vulkan.h" #include "ext/native/thin3d/VulkanContext.h" @@ -60,6 +59,74 @@ const bool g_validate_ = true; VulkanContext *g_Vulkan; +const char *ObjTypeToString(VkDebugReportObjectTypeEXT type) { + switch (type) { + case VK_DEBUG_REPORT_OBJECT_TYPE_INSTANCE_EXT: return "Instance"; + case VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT: return "PhysicalDevice"; + case VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT: return "Device"; + case VK_DEBUG_REPORT_OBJECT_TYPE_QUEUE_EXT: return "Queue"; + case VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT: return "CommandBuffer"; + case VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT: return "DeviceMemory"; + case VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT: return "Buffer"; + case VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_VIEW_EXT: return "BufferView"; + case VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT: return "Image"; + case VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_VIEW_EXT: return "ImageView"; + case VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT: return "ShaderModule"; + case VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT: return "Pipeline"; + case VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_LAYOUT_EXT: return "PipelineLayout"; + case VK_DEBUG_REPORT_OBJECT_TYPE_SAMPLER_EXT: return "Sampler"; + case VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT: return "DescriptorSet"; + case VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT_EXT: return "DescriptorSetLayout"; + case VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_POOL_EXT: return "DescriptorPool"; + case VK_DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT: return "Fence"; + case VK_DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT: return "Semaphore"; + case VK_DEBUG_REPORT_OBJECT_TYPE_EVENT_EXT: return "Event"; + case VK_DEBUG_REPORT_OBJECT_TYPE_QUERY_POOL_EXT: return "QueryPool"; + case VK_DEBUG_REPORT_OBJECT_TYPE_FRAMEBUFFER_EXT: return "Framebuffer"; + case VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT: return "RenderPass"; + case VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_CACHE_EXT: return "PipelineCache"; + case VK_DEBUG_REPORT_OBJECT_TYPE_SURFACE_KHR_EXT: return "SurfaceKHR"; + case VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT: return "SwapChainKHR"; + case VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_POOL_EXT: return "CommandPool"; + default: return "Unknown"; + } +} + +static VkBool32 Vulkan_Dbg(VkDebugReportFlagsEXT msgFlags, VkDebugReportObjectTypeEXT objType, uint64_t srcObject, size_t location, int32_t msgCode, const char* pLayerPrefix, const char* pMsg, void *pUserData) { + std::ostringstream message; + + if (msgFlags & VK_DEBUG_REPORT_ERROR_BIT_EXT) { + message << "ERROR: "; + } else if (msgFlags & VK_DEBUG_REPORT_WARNING_BIT_EXT) { + message << "WARNING: "; + } else if (msgFlags & VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT) { + message << "PERFORMANCE WARNING: "; + } else if (msgFlags & VK_DEBUG_REPORT_INFORMATION_BIT_EXT) { + message << "INFO: "; + } else if (msgFlags & VK_DEBUG_REPORT_DEBUG_BIT_EXT) { + message << "DEBUG: "; + } + message << "[" << pLayerPrefix << "] " << ObjTypeToString(objType) << " Code " << msgCode << " : " << pMsg; + +#ifdef _WIN32 + OutputDebugStringA(message.str().c_str()); + OutputDebugStringA("\n"); + if (msgFlags & VK_DEBUG_REPORT_ERROR_BIT_EXT) { + // MessageBox(NULL, message.str().c_str(), "Alert", MB_OK); + } else { + } +#else + std::cout << message << std::endl; +#endif + + // false indicates that layer should not bail-out of an + // API call that had validation failures. This may mean that the + // app dies inside the driver due to invalid parameter(s). + // That's what would happen without validation layers, so we'll + // keep that behavior here. + return false; +} + bool WindowsVulkanContext::Init(HINSTANCE hInst, HWND hWnd, std::string *error_message) { *error_message = "N/A"; @@ -68,8 +135,9 @@ bool WindowsVulkanContext::Init(HINSTANCE hInst, HWND hWnd, std::string *error_m return false; } - g_Vulkan = new VulkanContext("PPSSPP", 0); - + g_Vulkan = new VulkanContext("PPSSPP", VULKAN_FLAG_VALIDATE); + g_Vulkan->CreateDevice(0); + g_Vulkan->InitDebugMsgCallback(Vulkan_Dbg); g_Vulkan->InitObjects(hInst, hWnd, true); _CrtCheckMemory(); @@ -85,6 +153,8 @@ void WindowsVulkanContext::Shutdown() { g_Vulkan->EndSurfaceRenderPass(); g_Vulkan->DestroyObjects(); + g_Vulkan->DestroyDebugMsgCallback(); + g_Vulkan->DestroyDevice(); delete g_Vulkan; g_Vulkan = nullptr; } diff --git a/Windows/PPSSPP.vcxproj b/Windows/PPSSPP.vcxproj index 8fdfd0717d..845e7baf7f 100644 --- a/Windows/PPSSPP.vcxproj +++ b/Windows/PPSSPP.vcxproj @@ -171,7 +171,7 @@ Disabled - x64\Debug\glslang.lib;..\ext\vulkan\vulkan-1.lib;Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86_64\lib\avcodec.lib;..\ffmpeg\Windows\x86_64\lib\avformat.lib;..\ffmpeg\Windows\x86_64\lib\avutil.lib;..\ffmpeg\Windows\x86_64\lib\swresample.lib;..\ffmpeg\Windows\x86_64\lib\swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) + ..\ext\vulkan\vulkan-1.lib;Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86_64\lib\avcodec.lib;..\ffmpeg\Windows\x86_64\lib\avformat.lib;..\ffmpeg\Windows\x86_64\lib\avutil.lib;..\ffmpeg\Windows\x86_64\lib\swresample.lib;..\ffmpeg\Windows\x86_64\lib\swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) true $(OutDir)$(ProjectName).pdb true From 73d6d2dc72edf232e3ccb6ee65989a6d6c70ead6 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Thu, 31 Dec 2015 01:07:06 +0100 Subject: [PATCH 006/116] More vulkan in thin3d --- GPU/GPU.vcxproj | 8 +++--- Windows/GPU/WindowsVulkanContext.cpp | 4 +++ ext/native/thin3d/VulkanContext.cpp | 41 +++++++++++++++++++++++++--- ext/native/thin3d/VulkanContext.h | 7 ++++- ext/native/thin3d/thin3d_vulkan.cpp | 30 ++++++++++---------- ext/native/thin3d/vulkan_utils.cpp | 27 ++---------------- ext/native/thin3d/vulkan_utils.h | 15 ++-------- headless/Headless.vcxproj | 5 +++- 8 files changed, 74 insertions(+), 63 deletions(-) diff --git a/GPU/GPU.vcxproj b/GPU/GPU.vcxproj index 8ac43081a1..97caad8963 100644 --- a/GPU/GPU.vcxproj +++ b/GPU/GPU.vcxproj @@ -83,7 +83,7 @@ Level3 - ../common;..;../ext/native;../ext/native/ext/glew; + ../common;..;../ext;../ext/native;../ext/native/ext/glew; _CRTDBG_MAP_ALLOC;USING_WIN_UI;_CRT_SECURE_NO_WARNINGS;WIN32;_ARCH_32=1;_M_IX86=1;_DEBUG;_LIB;_UNICODE;UNICODE;%(PreprocessorDefinitions) StreamingSIMDExtensions2 Fast @@ -105,7 +105,7 @@ Level3 - ../common;..;../ext/native;../ext/native/ext/glew; + ../common;..;../ext;../ext/native;../ext/native/ext/glew; NotSet Fast false @@ -131,7 +131,7 @@ MaxSpeed true true - ../common;..;../ext/native;../ext/native/ext/glew; + ../common;..;../ext;../ext/native;../ext/native/ext/glew; false StreamingSIMDExtensions2 Fast @@ -157,7 +157,7 @@ MaxSpeed true true - ../common;..;../ext/native;../ext/native/ext/glew; + ../common;..;../ext;../ext/native;../ext/native/ext/glew; false NotSet Fast diff --git a/Windows/GPU/WindowsVulkanContext.cpp b/Windows/GPU/WindowsVulkanContext.cpp index 0f37bb0d96..77cc2fc877 100644 --- a/Windows/GPU/WindowsVulkanContext.cpp +++ b/Windows/GPU/WindowsVulkanContext.cpp @@ -135,6 +135,8 @@ bool WindowsVulkanContext::Init(HINSTANCE hInst, HWND hWnd, std::string *error_m return false; } + init_glslang(); + g_Vulkan = new VulkanContext("PPSSPP", VULKAN_FLAG_VALIDATE); g_Vulkan->CreateDevice(0); g_Vulkan->InitDebugMsgCallback(Vulkan_Dbg); @@ -157,6 +159,8 @@ void WindowsVulkanContext::Shutdown() { g_Vulkan->DestroyDevice(); delete g_Vulkan; g_Vulkan = nullptr; + + finalize_glslang(); } Thin3DContext *WindowsVulkanContext::CreateThin3DContext() { diff --git a/ext/native/thin3d/VulkanContext.cpp b/ext/native/thin3d/VulkanContext.cpp index 6a60bc0f22..d5189dd71b 100644 --- a/ext/native/thin3d/VulkanContext.cpp +++ b/ext/native/thin3d/VulkanContext.cpp @@ -1134,10 +1134,10 @@ void VulkanTexture::Create(VulkanContext *vulkan, int w, int h) { /* Create a mappable image. It will be the texture if linear images are ok to be textures */ /* or it will be the staging image if they are not. */ - VkResult res = vkCreateImage(vulkan->Device(), &image_create_info, NULL, &mappableImage); + VkResult res = vkCreateImage(vulkan->GetDevice(), &image_create_info, NULL, &mappableImage); assert(res == VK_SUCCESS); - vkGetImageMemoryRequirements(vulkan->Device(), mappableImage, &mem_reqs); + vkGetImageMemoryRequirements(vulkan->GetDevice(), mappableImage, &mem_reqs); assert(res == VK_SUCCESS); mem_alloc.allocationSize = mem_reqs.size; @@ -1146,10 +1146,10 @@ void VulkanTexture::Create(VulkanContext *vulkan, int w, int h) { pass = vulkan->MemoryTypeFromProperties(mem_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, &mem_alloc.memoryTypeIndex); assert(pass); - res = vkAllocateMemory(vulkan->Device(), &mem_alloc, NULL, &(mappableMemory)); + res = vkAllocateMemory(vulkan->GetDevice(), &mem_alloc, NULL, &(mappableMemory)); assert(res == VK_SUCCESS); - res = vkBindImageMemory(vulkan->Device(), mappableImage, mappableMemory, 0); + res = vkBindImageMemory(vulkan->GetDevice(), mappableImage, mappableMemory, 0); assert(res == VK_SUCCESS); } @@ -1628,3 +1628,36 @@ void init_glslang() { void finalize_glslang() { glslang::FinalizeProcess(); } + +const char *VulkanResultToString(VkResult res) { + switch (res) { + case VK_NOT_READY: return "VK_NOT_READY"; + case VK_TIMEOUT: return "VK_TIMEOUT"; + case VK_EVENT_SET: return "VK_EVENT_SET"; + case VK_EVENT_RESET: return "VK_EVENT_RESET"; + case VK_INCOMPLETE: return "VK_INCOMPLETE"; + case VK_ERROR_OUT_OF_HOST_MEMORY: return "VK_ERROR_OUT_OF_HOST_MEMORY"; + case VK_ERROR_OUT_OF_DEVICE_MEMORY: return "VK_ERROR_OUT_OF_DEVICE_MEMORY"; + case VK_ERROR_INITIALIZATION_FAILED: return "VK_ERROR_INITIALIZATION_FAILED"; + case VK_ERROR_DEVICE_LOST: return "VK_ERROR_DEVICE_LOST"; + case VK_ERROR_MEMORY_MAP_FAILED: return "VK_ERROR_MEMORY_MAP_FAILED"; + case VK_ERROR_LAYER_NOT_PRESENT: return "VK_ERROR_LAYER_NOT_PRESENT"; + case VK_ERROR_EXTENSION_NOT_PRESENT: return "VK_ERROR_EXTENSION_NOT_PRESENT"; + case VK_ERROR_FEATURE_NOT_PRESENT: return "VK_ERROR_FEATURE_NOT_PRESENT"; + case VK_ERROR_INCOMPATIBLE_DRIVER: return "VK_ERROR_INCOMPATIBLE_DRIVER"; + case VK_ERROR_TOO_MANY_OBJECTS: return "VK_ERROR_TOO_MANY_OBJECTS"; + case VK_ERROR_FORMAT_NOT_SUPPORTED: return "VK_ERROR_FORMAT_NOT_SUPPORTED"; + case VK_ERROR_SURFACE_LOST_KHR: return "VK_ERROR_SURFACE_LOST_KHR"; + case VK_SUBOPTIMAL_KHR: return "VK_SUBOPTIMAL_KHR"; + case VK_ERROR_OUT_OF_DATE_KHR: return "VK_ERROR_OUT_OF_DATE_KHR"; + case VK_ERROR_INCOMPATIBLE_DISPLAY_KHR: return "VK_ERROR_INCOMPATIBLE_DISPLAY_KHR"; + case VK_ERROR_NATIVE_WINDOW_IN_USE_KHR: return "VK_ERROR_NATIVE_WINDOW_IN_USE_KHR"; + default: + return "Unknown"; + } +} + +void VulkanAssertImpl(VkResult check, const char *function, const char *file, int line) { + const char *error = "(none)"; + +} diff --git a/ext/native/thin3d/VulkanContext.h b/ext/native/thin3d/VulkanContext.h index ad382958fa..71aa2a4379 100644 --- a/ext/native/thin3d/VulkanContext.h +++ b/ext/native/thin3d/VulkanContext.h @@ -71,7 +71,7 @@ public: VkResult CreateDevice(int physical_device); - VkDevice Device() { + VkDevice GetDevice() { return device_; } @@ -274,5 +274,10 @@ void TransitionImageLayout( VkImageLayout old_image_layout, VkImageLayout new_image_layout); +void VulkanAssertImpl(VkResult check, const char *function, const char *file, int line); + +// DO NOT call vulkan functions within this! Instead, store the result in a variable and check that. +#define VulkanAssert(x) if ((x) != VK_SUCCESS) VulkanAssertImpl((x), __FUNCTION__, __FILE__, __LINE__); + #endif // UTIL_INIT diff --git a/ext/native/thin3d/thin3d_vulkan.cpp b/ext/native/thin3d/thin3d_vulkan.cpp index 3a2a2adb3e..3502331495 100644 --- a/ext/native/thin3d/thin3d_vulkan.cpp +++ b/ext/native/thin3d/thin3d_vulkan.cpp @@ -114,7 +114,7 @@ static inline void Uint8x4ToFloat4(uint32_t u, float f[4]) { // their own similar buffer solutions. class VulkanPushBuffer { public: - VulkanPushBuffer(VkDevice device, VulkanDeviceMemoryManager *memMan, size_t size) : offset_(0), size_(size), writePtr_(nullptr) { + VulkanPushBuffer(VkDevice device, VulkanContext *vulkan, size_t size) : offset_(0), size_(size), writePtr_(nullptr) { VkBufferCreateInfo b; b.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; b.pNext = nullptr; @@ -131,7 +131,7 @@ public: VkMemoryAllocateInfo alloc; alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; alloc.pNext = nullptr; - memMan->memory_type_from_properties(0xFFFFFFFF, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, &alloc.memoryTypeIndex); + vulkan->MemoryTypeFromProperties(0xFFFFFFFF, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, &alloc.memoryTypeIndex); alloc.allocationSize = size; res = vkAllocateMemory(device, &alloc, nullptr, &deviceMemory_); @@ -511,8 +511,6 @@ private: VulkanContext *vulkan_; - VulkanDeviceMemoryManager vulkanMem_; - // These are used to compose the pipeline cache key. Thin3DVKBlendState *curBlendState_; Thin3DVKDepthStencilState *curDepthStencilState_; @@ -633,10 +631,10 @@ enum class TextureState { class Thin3DVKTexture : public Thin3DTexture { public: - Thin3DVKTexture(VkDevice device, VulkanDeviceMemoryManager *memMan) : device_(device), memMan_(memMan), state_(TextureState::UNINITIALIZED) { + Thin3DVKTexture(VulkanContext *vulkan) : vulkan_(vulkan), state_(TextureState::UNINITIALIZED) { } - Thin3DVKTexture(VkDevice device, VulkanDeviceMemoryManager *memMan, T3DTextureType type, T3DImageFormat format, int width, int height, int depth, int mipLevels) - : device_(device), memMan_(memMan), format_(format), mipLevels_(mipLevels) { + Thin3DVKTexture(VulkanContext *vulkan, T3DTextureType type, T3DImageFormat format, int width, int height, int depth, int mipLevels) + : vulkan_(vulkan), format_(format), mipLevels_(mipLevels) { Create(type, format, width, height, depth, mipLevels); } @@ -671,7 +669,7 @@ public: VkImageView GetImageView() { return view_; } private: - VulkanDeviceMemoryManager *memMan_; + VulkanContext *vulkan_; VkDevice device_; VulkanImage image_; VulkanImage staging_; @@ -685,8 +683,8 @@ private: }; Thin3DVKContext::Thin3DVKContext(VulkanContext *vulkan) - : viewportDirty_(false), scissorDirty_(false) { - device_ = vulkan->Device(); + : viewportDirty_(false), scissorDirty_(false), vulkan_(vulkan) { + device_ = vulkan->GetDevice(); noScissor_.offset.x = 0; noScissor_.offset.y = 0; @@ -723,8 +721,8 @@ Thin3DVKContext::Thin3DVKContext(VulkanContext *vulkan) dp.poolSizeCount = ARRAY_SIZE(dpTypes); res = vkCreateDescriptorPool(device_, &dp, nullptr, &descriptorPool_); assert(VK_SUCCESS == res); - pushBuffer_[0] = new VulkanPushBuffer(device_, &vulkanMem_, 1024 * 1024); - pushBuffer_[1] = new VulkanPushBuffer(device_, &vulkanMem_, 1024 * 1024); + pushBuffer_[0] = new VulkanPushBuffer(device_, vulkan_, 1024 * 1024); + pushBuffer_[1] = new VulkanPushBuffer(device_, vulkan_, 1024 * 1024); // binding 0 - vertex data // binding 1 - uniform data @@ -1120,11 +1118,11 @@ Thin3DVertexFormat *Thin3DVKContext::CreateVertexFormat(const std::vector>= 1; - } - // No memory types matched, return failure - return VK_ERROR_FORMAT_NOT_SUPPORTED; -} - -void VulkanImage::Create2D(VkDevice device, VulkanDeviceMemoryManager *memMan, VkFormat format, VkFlags required_props, VkImageUsageFlags usage, int width, int height) { +void VulkanImage::Create2D(VkDevice device, VulkanContext *vulkan, VkFormat format, VkFlags required_props, VkImageUsageFlags usage, int width, int height) { width_ = width; height_ = height; @@ -94,8 +73,8 @@ void VulkanImage::Create2D(VkDevice device, VulkanDeviceMemoryManager *memMan, V mem_alloc_.allocationSize = mem_reqs.size; mem_alloc_.memoryTypeIndex = 0; - err = memMan->memory_type_from_properties(mem_reqs.memoryTypeBits, required_props, &mem_alloc_.memoryTypeIndex); - assert(!err); + bool res = vulkan->MemoryTypeFromProperties(mem_reqs.memoryTypeBits, required_props, &mem_alloc_.memoryTypeIndex); + assert(res); err = vkAllocateMemory(device, &mem_alloc_, nullptr, &memory_); assert(!err); diff --git a/ext/native/thin3d/vulkan_utils.h b/ext/native/thin3d/vulkan_utils.h index a2dd321843..7a0266fe20 100644 --- a/ext/native/thin3d/vulkan_utils.h +++ b/ext/native/thin3d/vulkan_utils.h @@ -21,18 +21,7 @@ #define VK_PROTOTYPES #include "ext/vulkan/vulkan.h" - -// -class VulkanDeviceMemoryManager { -public: - VulkanDeviceMemoryManager() {} - void Init(VkPhysicalDevice gpu); - - VkResult memory_type_from_properties(uint32_t typeBits, VkFlags requirements_mask, uint32_t *typeIndex); - -private: - VkPhysicalDeviceMemoryProperties memory_properties_; -}; +#include "VulkanContext.h" // Utility class to handle images without going insane. @@ -43,7 +32,7 @@ public: bool IsValid() const { return image_ != nullptr; } // This can be done completely unsynchronized. - void Create2D(VkDevice device, VulkanDeviceMemoryManager *memMan, VkFormat format, VkFlags required_props, VkImageUsageFlags usage, int width, int height); + void Create2D(VkDevice device, VulkanContext *vulkan, VkFormat format, VkFlags required_props, VkImageUsageFlags usage, int width, int height); // This can only be used if you pass in VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT in required_props in Create2D. void SetImageData2D(VkDevice device, const uint8_t *data, int width, int height, int pitch); diff --git a/headless/Headless.vcxproj b/headless/Headless.vcxproj index d155cb76af..2e84a6801e 100644 --- a/headless/Headless.vcxproj +++ b/headless/Headless.vcxproj @@ -246,6 +246,9 @@ {533f1d30-d04d-47cc-ad71-20f658907e36} + + {edfa2e87-8ac1-4853-95d4-d7594ff81947} + {3baae095-e0ab-4b0e-b5df-ce39c8ae31de} @@ -269,4 +272,4 @@ - + \ No newline at end of file From 83a5313a063bb7f5a93e3349342e0a9f5464363e Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Thu, 31 Dec 2015 01:33:23 +0100 Subject: [PATCH 007/116] More fixes --- ext/native/thin3d/thin3d.cpp | 2 +- ext/native/thin3d/thin3d_vulkan.cpp | 20 ++++++++++++-------- ext/native/thin3d/vulkan_utils.cpp | 3 ++- ext/native/thin3d/vulkan_utils.h | 2 +- 4 files changed, 16 insertions(+), 11 deletions(-) diff --git a/ext/native/thin3d/thin3d.cpp b/ext/native/thin3d/thin3d.cpp index cafbf41e25..1fb65b34e4 100644 --- a/ext/native/thin3d/thin3d.cpp +++ b/ext/native/thin3d/thin3d.cpp @@ -35,7 +35,7 @@ static const char * const vulkan_fsTexCol = "layout(location = 1) in vec2 oTexCoord0;\n" "layout(location = 0) out vec4 fragColor0\n;" "layout(binding = 2) uniform sampler2D Sampler0;\n" -"void main() { fragColor0 = texture2D(Sampler0, oTexCoord0) * oColor0; }\n"; +"void main() { fragColor0 = texture(Sampler0, oTexCoord0) * oColor0; }\n"; static const char * const glsl_fsCol = "#ifdef GL_ES\n" diff --git a/ext/native/thin3d/thin3d_vulkan.cpp b/ext/native/thin3d/thin3d_vulkan.cpp index 3502331495..e6c96ba840 100644 --- a/ext/native/thin3d/thin3d_vulkan.cpp +++ b/ext/native/thin3d/thin3d_vulkan.cpp @@ -114,7 +114,7 @@ static inline void Uint8x4ToFloat4(uint32_t u, float f[4]) { // their own similar buffer solutions. class VulkanPushBuffer { public: - VulkanPushBuffer(VkDevice device, VulkanContext *vulkan, size_t size) : offset_(0), size_(size), writePtr_(nullptr) { + VulkanPushBuffer(VkDevice device, VulkanContext *vulkan, size_t size) : offset_(0), size_(size), writePtr_(nullptr), deviceMemory_(nullptr) { VkBufferCreateInfo b; b.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; b.pNext = nullptr; @@ -670,7 +670,6 @@ public: private: VulkanContext *vulkan_; - VkDevice device_; VulkanImage image_; VulkanImage staging_; VkImageView view_; @@ -699,7 +698,7 @@ Thin3DVKContext::Thin3DVKContext(VulkanContext *vulkan) VkCommandPoolCreateInfo p; p.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; p.pNext = nullptr; - p.flags = 0; + p.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; p.queueFamilyIndex = vulkan->GetGraphicsQueueFamilyIndex(); VkResult res = vkCreateCommandPool(device_, &p, nullptr, &cmdPool_); assert(VK_SUCCESS == res); @@ -733,14 +732,17 @@ Thin3DVKContext::Thin3DVKContext(VulkanContext *vulkan) bindings[0].pImmutableSamplers = nullptr; bindings[0].descriptorType = VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT; bindings[0].stageFlags = VK_SHADER_STAGE_VERTEX_BIT; + bindings[0].binding = 0; bindings[1].descriptorCount = 1; bindings[1].pImmutableSamplers = nullptr; bindings[1].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; bindings[1].stageFlags = VK_SHADER_STAGE_VERTEX_BIT; + bindings[1].binding = 1; bindings[2].descriptorCount = 1; bindings[2].pImmutableSamplers = nullptr; bindings[2].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; bindings[2].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; + bindings[2].binding = 2; VkDescriptorSetLayoutCreateInfo dsl; dsl.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; @@ -781,10 +783,10 @@ Thin3DVKContext::Thin3DVKContext(VulkanContext *vulkan) res = vkCreateFence(device_, &f, nullptr, &cmdFences_[0]); assert(VK_SUCCESS == res); + f.flags = VK_FENCE_CREATE_SIGNALED_BIT; res = vkCreateFence(device_, &f, nullptr, &cmdFences_[1]); assert(VK_SUCCESS == res); // Create as already signalled, so we can wait for it the first time. - f.flags = VK_FENCE_CREATE_SIGNALED_BIT; res = vkCreateFence(device_, &f, nullptr, &initFence_); assert(VK_SUCCESS == res); pendingInitFence_ = false; @@ -800,6 +802,7 @@ Thin3DVKContext::Thin3DVKContext(VulkanContext *vulkan) push_ = pushBuffer_[0]; cmd_ = cmdBuffer_[0]; + cmdFence_ = cmdFences_[0]; } Thin3DVKContext::~Thin3DVKContext() { @@ -929,6 +932,7 @@ VkDescriptorSet Thin3DVKContext::GetOrCreateDescriptorSet() { imageDesc.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; VkWriteDescriptorSet writes[2]; + memset(writes, 0, sizeof(writes)); writes[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; writes[0].pNext = nullptr; writes[0].dstSet = descSet; @@ -1132,8 +1136,8 @@ void Thin3DVKTexture::SetImageData(int x, int y, int z, int width, int height, i // So we need to do a staging copy. We upload the data to the staging buffer immediately, then we actually do the final copy once it's used the first time // as we need a command buffer and the architecture of Thin3D doesn't really work the way we want.. if (!image_.IsValid()) { - staging_.Create2D(device_, vulkan_, vulkanFormat, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, VK_IMAGE_USAGE_TRANSFER_SRC_BIT, width, height); - image_.Create2D(device_, vulkan_, vulkanFormat, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, (VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT), width, height); + staging_.Create2D(vulkan_, vulkanFormat, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, VK_IMAGE_USAGE_TRANSFER_SRC_BIT, width, height); + image_.Create2D(vulkan_, vulkanFormat, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, (VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT), width, height); } VkImageViewCreateInfo iv; @@ -1152,11 +1156,11 @@ void Thin3DVKTexture::SetImageData(int x, int y, int z, int width, int height, i iv.subresourceRange.baseArrayLayer = 0; iv.subresourceRange.baseMipLevel = 0; iv.subresourceRange.levelCount = 1; - VkResult res = vkCreateImageView(device_, &iv, nullptr, &view_); + VkResult res = vkCreateImageView(vulkan_->GetDevice(), &iv, nullptr, &view_); assert(VK_SUCCESS == res); // TODO: Support setting only parts of the image efficiently. - staging_.SetImageData2D(device_, data, width, height, stride); + staging_.SetImageData2D(vulkan_->GetDevice(), data, width, height, stride); state_ = TextureState::STAGED; } diff --git a/ext/native/thin3d/vulkan_utils.cpp b/ext/native/thin3d/vulkan_utils.cpp index 44155f68d0..a94fd2955e 100644 --- a/ext/native/thin3d/vulkan_utils.cpp +++ b/ext/native/thin3d/vulkan_utils.cpp @@ -40,7 +40,8 @@ #include "thin3d/vulkan_utils.h" -void VulkanImage::Create2D(VkDevice device, VulkanContext *vulkan, VkFormat format, VkFlags required_props, VkImageUsageFlags usage, int width, int height) { +void VulkanImage::Create2D(VulkanContext *vulkan, VkFormat format, VkFlags required_props, VkImageUsageFlags usage, int width, int height) { + VkDevice device = vulkan->GetDevice(); width_ = width; height_ = height; diff --git a/ext/native/thin3d/vulkan_utils.h b/ext/native/thin3d/vulkan_utils.h index 7a0266fe20..9c194a78c3 100644 --- a/ext/native/thin3d/vulkan_utils.h +++ b/ext/native/thin3d/vulkan_utils.h @@ -32,7 +32,7 @@ public: bool IsValid() const { return image_ != nullptr; } // This can be done completely unsynchronized. - void Create2D(VkDevice device, VulkanContext *vulkan, VkFormat format, VkFlags required_props, VkImageUsageFlags usage, int width, int height); + void Create2D(VulkanContext *vulkan, VkFormat format, VkFlags required_props, VkImageUsageFlags usage, int width, int height); // This can only be used if you pass in VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT in required_props in Create2D. void SetImageData2D(VkDevice device, const uint8_t *data, int width, int height, int pitch); From 129c706cfc764f4a29449d5a1e8cda1df9753d88 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Thu, 31 Dec 2015 14:05:48 +0100 Subject: [PATCH 008/116] Just some work on the shader generators --- GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp | 57 +++-- GPU/Vulkan/VertexShaderGeneratorVulkan.cpp | 211 +++++++------------ 2 files changed, 99 insertions(+), 169 deletions(-) diff --git a/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp b/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp index 832f36269c..8a1a5d1e60 100644 --- a/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp +++ b/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp @@ -44,6 +44,29 @@ // #define DEBUG_SHADER +// TODO: Which binding number? +static const char *vulkan_uniform_buffer = R"( +layout(set=0, binding=3) uniform constants { + // Blend function replacement + vec3 u_blendFixA; + vec3 u_blendFixB; + + // Texture clamp emulation + vec4 u_texclamp; + vec2 u_texclampoff; + + // Alpha/Color test emulation + vec4 u_alphacolorref; + ivec4 u_alphacolormask; + + // Stencil replacement + float u_stencilReplaceValue; + vec3 u_texenv; + + vec3 u_fogcolor; +)"; + + // Missing: Z depth range bool GenerateVulkanGLSLFragmentShader(const ShaderID &id, char *buffer) { char *p = buffer; @@ -87,11 +110,14 @@ bool GenerateVulkanGLSLFragmentShader(const ShaderID &id, char *buffer) { GEBlendSrcFactor replaceBlendFuncA = (GEBlendSrcFactor)id.Bits(FS_BIT_BLENDFUNC_A, 4); GEBlendDstFactor replaceBlendFuncB = (GEBlendDstFactor)id.Bits(FS_BIT_BLENDFUNC_B, 4); GEBlendMode replaceBlendEq = (GEBlendMode)id.Bits(FS_BIT_BLENDEQ, 3); + StencilValueType replaceAlphaWithStencilType = (StencilValueType)id.Bits(FS_BIT_REPLACE_ALPHA_WITH_STENCIL_TYPE, 4); bool isModeClear = id.Bit(FS_BIT_CLEARMODE); const char *shading = doFlatShading ? "flat" : ""; + WRITE(p, "%s\n", vulkan_uniform_buffer); + if (doTexture) { WRITE(p, "layout (binding = 1) uniform sampler2D tex;\n"); } @@ -100,37 +126,6 @@ bool GenerateVulkanGLSLFragmentShader(const ShaderID &id, char *buffer) { if (replaceBlend == REPLACE_BLEND_COPY_FBO) { WRITE(p, "layout (binding = 2) uniform sampler2D fbotex;\n"); } - if (replaceBlendFuncA == GE_SRCBLEND_FIXA) { - WRITE(p, "uniform vec3 u_blendFixA;\n"); - } - if (replaceBlendFuncB == GE_DSTBLEND_FIXB) { - WRITE(p, "uniform vec3 u_blendFixB;\n"); - } - } - - if (needShaderTexClamp && doTexture) { - WRITE(p, "uniform vec4 u_texclamp;\n"); - if (id.Bit(FS_BIT_TEXTURE_AT_OFFSET)) { - WRITE(p, "uniform vec2 u_texclampoff;\n"); - } - } - - if (enableAlphaTest || enableColorTest) { - WRITE(p, "uniform vec4 u_alphacolorref;\n"); - if (((enableColorTest && !colorTestAgainstZero) || (enableAlphaTest && !alphaTestAgainstZero))) { - WRITE(p, "uniform ivec4 u_alphacolormask;\n"); - } - } - - StencilValueType replaceAlphaWithStencilType = (StencilValueType)id.Bits(FS_BIT_REPLACE_ALPHA_WITH_STENCIL_TYPE, 4); - if (stencilToAlpha && replaceAlphaWithStencilType == STENCIL_VALUE_UNIFORM) { - WRITE(p, "uniform float u_stencilReplaceValue;\n"); - } - if (doTexture && texFunc == GE_TEXFUNC_BLEND) - WRITE(p, "uniform vec3 u_texenv;\n"); - - if (enableFog) { - WRITE(p, "uniform vec3 u_fogcolor;\n"); } WRITE(p, "layout (location = 1) %s in vec4 v_color0;\n", shading); diff --git a/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp b/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp index f12f104a8e..c1ef4ddc8a 100644 --- a/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp +++ b/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp @@ -71,6 +71,41 @@ enum DoLightComputation { }; +const char *vulkan_base_uniforms = R"( +layout(set=0, binding=4) uniform base { + mat4 proj; + mat4 world; + mat4 view; + mat4 texmtx; + vec4 uvscaleoffset; + vec2 fogcoef; + vec4 depthRange; + vec4 matambientalpha; +}; +)"; + +const char *vulkan_light_uniforms = R"( +layout(set=0, binding=5) uniform light { + vec4 ambient; + vec3 matdiffuse; + vec4 matspecular; + vec3 matemissive; + vec3 pos[4]; + // TODO: Make lighttype/comp uniforms too + vec3 att[4]; + vec3 dir[4]; + float angle[4]; + float spotCoef[4]; + vec3 ambient[4]; + vec3 diffuse[4]; + vec3 specular[4]; +)"; + +const char *vulkan_bone_uniforms = R"( +layout(set=0, binding=6) uniform bone { + mat4 m[8]; +)"; + // Depth range and viewport // // After the multiplication with the projection matrix, we have a 4D vector in clip space. @@ -178,81 +213,15 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { // We will memcpy the parts into place in a big buffer so we can be quite dynamic about what parts // are present and what parts aren't, but we will not be ultra detailed about it. -// WRITE(p, ) + WRITE(p, "%s", vulkan_base_uniforms); + if (enableLighting) + WRITE(p, "%s", vulkan_light_uniforms); + if (enableBones) + WRITE(p, "%s", vulkan_bone_uniforms); - if (isModeThrough) { - WRITE(p, "uniform mat4 u_proj_through;\n"); - } else { - WRITE(p, "uniform mat4 u_proj;\n"); - // Add all the uniforms we'll need to transform properly. - } - bool prescale = false; - if (useHWTransform) { - // When transforming by hardware, we need a great deal more uniforms... - WRITE(p, "uniform mat4 u_world;\n"); - WRITE(p, "uniform mat4 u_view;\n"); - if (doTextureProjection) - WRITE(p, "uniform mediump mat4 u_texmtx;\n"); - if (enableBones) { -#ifdef USE_BONE_ARRAY - WRITE(p, "uniform mediump mat4 u_bone[%i];\n", numBoneWeights); -#else - for (int i = 0; i < numBoneWeights; i++) { - WRITE(p, "uniform mat4 u_bone%i;\n", i); - } -#endif - } - if (doTexture && (!prescale || uvGenMode == GE_TEXMAP_ENVIRONMENT_MAP || uvGenMode == GE_TEXMAP_TEXTURE_MATRIX)) { - WRITE(p, "uniform vec4 u_uvscaleoffset;\n"); - } - for (int i = 0; i < 4; i++) { - if (doLight[i] != LIGHT_OFF) { - // This is needed for shade mapping - WRITE(p, "uniform vec3 u_lightpos%i;\n", i); - } - if (doLight[i] == LIGHT_FULL) { - GELightType type = static_cast(id.Bits(VS_BIT_LIGHT0_TYPE + 4 * i, 2)); - GELightComputation comp = static_cast(id.Bits(VS_BIT_LIGHT0_COMP + 4 * i, 2)); - - if (type != GE_LIGHTTYPE_DIRECTIONAL) - WRITE(p, "uniform mediump vec3 u_lightatt%i;\n", i); - - if (type == GE_LIGHTTYPE_SPOT || type == GE_LIGHTTYPE_UNKNOWN) { - WRITE(p, "uniform mediump vec3 u_lightdir%i;\n", i); - WRITE(p, "uniform mediump float u_lightangle%i;\n", i); - WRITE(p, "uniform mediump float u_lightspotCoef%i;\n", i); - } - WRITE(p, "uniform lowp vec3 u_lightambient%i;\n", i); - WRITE(p, "uniform lowp vec3 u_lightdiffuse%i;\n", i); - - if (comp != GE_LIGHTCOMP_ONLYDIFFUSE) { - WRITE(p, "uniform lowp vec3 u_lightspecular%i;\n", i); - } - } - } - if (enableLighting) { - WRITE(p, "uniform lowp vec4 u_ambient;\n"); - if ((matUpdate & 2) == 0 || !hasColor) - WRITE(p, "uniform lowp vec3 u_matdiffuse;\n"); - WRITE(p, "uniform lowp vec4 u_matspecular;\n"); // Specular coef is contained in alpha - WRITE(p, "uniform lowp vec3 u_matemissive;\n"); - } - } - - if (useHWTransform || !hasColor) - WRITE(p, "uniform lowp vec4 u_matambientalpha;\n"); // matambient + matalpha - - if (enableFog) { - WRITE(p, "uniform highp vec2 u_fogcoef;\n"); - } - - if (!isModeThrough && gstate_c.Supports(GPU_ROUND_DEPTH_TO_16BIT)) { - WRITE(p, "uniform highp vec4 u_depthRange;\n"); - } - WRITE(p, "layout (location = 1) %s out lowp vec4 v_color0;\n", shading); if (lmode) { WRITE(p, "layout (location = 2) %s out lowp vec3 v_color1;\n", shading); @@ -276,9 +245,9 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { // Apply the projection and viewport to get the Z buffer value, floor to integer, undo the viewport and projection. WRITE(p, "\nvec4 depthRoundZVP(vec4 v) {\n"); WRITE(p, " float z = v.z / v.w;\n"); - WRITE(p, " z = z * u_depthRange.x + u_depthRange.y;\n"); + WRITE(p, " z = z * base.depthRange.x + base.depthRange.y;\n"); WRITE(p, " z = floor(z);\n"); - WRITE(p, " z = (z - u_depthRange.z) * u_depthRange.w;\n"); + WRITE(p, " z = (z - base.depthRange.z) * base.depthRange.w;\n"); WRITE(p, " return vec4(v.x, v.y, z * v.w, v.w);\n"); WRITE(p, "}\n\n"); } @@ -299,7 +268,7 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { if (lmode) WRITE(p, " v_color1 = color1;\n"); } else { - WRITE(p, " v_color0 = u_matambientalpha;\n"); + WRITE(p, " v_color0 = base.matambientalpha;\n"); if (lmode) WRITE(p, " v_color1 = vec3(0.0);\n"); } @@ -307,22 +276,22 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { WRITE(p, " v_fogdepth = position.w;\n"); } if (isModeThrough) { - WRITE(p, " gl_Position = u_proj_through * vec4(position.xyz, 1.0);\n"); + WRITE(p, " gl_Position = base.proj * vec4(position.xyz, 1.0);\n"); } else { // The viewport is used in this case, so need to compensate for that. if (gstate_c.Supports(GPU_ROUND_DEPTH_TO_16BIT)) { - WRITE(p, " gl_Position = depthRoundZVP(u_proj * vec4(position.xyz, 1.0));\n"); + WRITE(p, " gl_Position = depthRoundZVP(base.proj * vec4(position.xyz, 1.0));\n"); } else { - WRITE(p, " gl_Position = u_proj * vec4(position.xyz, 1.0);\n"); + WRITE(p, " gl_Position = base.proj * vec4(position.xyz, 1.0);\n"); } } } else { // Step 1: World Transform / Skinning if (!enableBones) { // No skinning, just standard T&L. - WRITE(p, " vec3 worldpos = (u_world * vec4(position.xyz, 1.0)).xyz;\n"); + WRITE(p, " vec3 worldpos = (base.world * vec4(position.xyz, 1.0)).xyz;\n"); if (hasNormal) - WRITE(p, " mediump vec3 worldnormal = normalize((u_world * vec4(%snormal, 0.0)).xyz);\n", flipNormal ? "-" : ""); + WRITE(p, " mediump vec3 worldnormal = normalize((base.world * vec4(%snormal, 0.0)).xyz);\n", flipNormal ? "-" : ""); else WRITE(p, " mediump vec3 worldnormal = vec3(0.0, 0.0, 1.0);\n"); } else { @@ -334,8 +303,6 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { "w2.x", "w2.y", "w2.z", "w2.w", }; -#if defined(USE_FOR_LOOP) && defined(USE_BONE_ARRAY) - // To loop through the weights, we unfortunately need to put them in a float array. // GLSL ES sucks - no way to directly initialize an array! switch (numBoneWeights) { @@ -349,80 +316,48 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { case 8: WRITE(p, " float w[8]; w[0] = w1.x; w[1] = w1.y; w[2] = w1.z; w[3] = w1.w; w[4] = w2.x; w[5] = w2.y; w[6] = w2.z; w[7] = w2.w;\n"); break; } - WRITE(p, " mat4 skinMatrix = w[0] * u_bone[0];\n"); + WRITE(p, " mat4 skinMatrix = w[0] * bone.m[0];\n"); if (numBoneWeights > 1) { WRITE(p, " for (int i = 1; i < %i; i++) {\n", numBoneWeights); - WRITE(p, " skinMatrix += w[i] * u_bone[i];\n"); + WRITE(p, " skinMatrix += w[i] * bone.m[i];\n"); WRITE(p, " }\n"); } -#else - -#ifdef USE_BONE_ARRAY - if (numBoneWeights == 1) - WRITE(p, " mat4 skinMatrix = w1 * u_bone[0]"); - else - WRITE(p, " mat4 skinMatrix = w1.x * u_bone[0]"); - for (int i = 1; i < numBoneWeights; i++) { - const char *weightAttr = boneWeightAttr[i]; - // workaround for "cant do .x of scalar" issue - if (numBoneWeights == 1 && i == 0) weightAttr = "w1"; - if (numBoneWeights == 5 && i == 4) weightAttr = "w2"; - WRITE(p, " + %s * u_bone[%i]", weightAttr, i); - } -#else - // Uncomment this to screw up bone shaders to check the vertex shader software fallback - // WRITE(p, "THIS SHOULD ERROR! #error"); - if (numBoneWeights == 1) - WRITE(p, " mat4 skinMatrix = w1 * u_bone0"); - else - WRITE(p, " mat4 skinMatrix = w1.x * u_bone0"); - for (int i = 1; i < numBoneWeights; i++) { - const char *weightAttr = boneWeightAttr[i]; - // workaround for "cant do .x of scalar" issue - if (numBoneWeights == 1 && i == 0) weightAttr = "w1"; - if (numBoneWeights == 5 && i == 4) weightAttr = "w2"; - WRITE(p, " + %s * u_bone%i", weightAttr, i); - } -#endif - -#endif - WRITE(p, ";\n"); // Trying to simplify this results in bugs in LBP... WRITE(p, " vec3 skinnedpos = (skinMatrix * vec4(position, 1.0)).xyz %s;\n", factor); - WRITE(p, " vec3 worldpos = (u_world * vec4(skinnedpos, 1.0)).xyz;\n"); + WRITE(p, " vec3 worldpos = (base.world * vec4(skinnedpos, 1.0)).xyz;\n"); if (hasNormal) { WRITE(p, " mediump vec3 skinnednormal = (skinMatrix * vec4(%snormal, 0.0)).xyz %s;\n", flipNormal ? "-" : "", factor); } else { WRITE(p, " mediump vec3 skinnednormal = (skinMatrix * vec4(0.0, 0.0, %s1.0, 0.0)).xyz %s;\n", flipNormal ? "-" : "", factor); } - WRITE(p, " mediump vec3 worldnormal = normalize((u_world * vec4(skinnednormal, 0.0)).xyz);\n"); + WRITE(p, " mediump vec3 worldnormal = normalize((base.world * vec4(skinnednormal, 0.0)).xyz);\n"); } - WRITE(p, " vec4 viewPos = u_view * vec4(worldpos, 1.0);\n"); + WRITE(p, " vec4 viewPos = base.view * vec4(worldpos, 1.0);\n"); // Final view and projection transforms. if (gstate_c.Supports(GPU_ROUND_DEPTH_TO_16BIT)) { - WRITE(p, " gl_Position = depthRoundZVP(u_proj * viewPos);\n"); + WRITE(p, " gl_Position = depthRoundZVP(base.proj * viewPos);\n"); } else { - WRITE(p, " gl_Position = u_proj * viewPos;\n"); + WRITE(p, " gl_Position = base.proj * viewPos;\n"); } // TODO: Declare variables for dots for shade mapping if needed. - const char *ambientStr = (matUpdate & 1) && hasColor ? "color0" : "u_matambientalpha"; - const char *diffuseStr = (matUpdate & 2) && hasColor ? "color0.rgb" : "u_matdiffuse"; - const char *specularStr = (matUpdate & 4) && hasColor ? "color0.rgb" : "u_matspecular.rgb"; + const char *ambientStr = (matUpdate & 1) && hasColor ? "color0" : "base.matambientalpha"; + const char *diffuseStr = (matUpdate & 2) && hasColor ? "color0.rgb" : "light.matdiffuse"; + const char *specularStr = (matUpdate & 4) && hasColor ? "color0.rgb" : "light.matspecular.rgb"; bool diffuseIsZero = true; bool specularIsZero = true; bool distanceNeeded = false; if (enableLighting) { - WRITE(p, " lowp vec4 lightSum0 = u_ambient * %s + vec4(u_matemissive, 0.0);\n", ambientStr); + WRITE(p, " lowp vec4 lightSum0 = light.ambient * %s + vec4(light.matemissive, 0.0);\n", ambientStr); for (int i = 0; i < 4; i++) { GELightType type = static_cast(id.Bits(VS_BIT_LIGHT0_TYPE + 4 * i, 2)); @@ -460,9 +395,9 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { if (type == GE_LIGHTTYPE_DIRECTIONAL) { // We prenormalize light positions for directional lights. - WRITE(p, " toLight = u_lightpos%i;\n", i); + WRITE(p, " toLight = light.pos[%i];\n", i); } else { - WRITE(p, " toLight = u_lightpos%i - worldpos;\n", i); + WRITE(p, " toLight = light.pos[%i] - worldpos;\n", i); WRITE(p, " distance = length(toLight);\n"); WRITE(p, " toLight /= distance;\n"); } @@ -477,7 +412,7 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { WRITE(p, " if (dot%i == 0.0 && u_matspecular.a == 0.0) {\n", i); WRITE(p, " dot%i = 1.0;\n", i); WRITE(p, " } else {\n"); - WRITE(p, " dot%i = pow(dot%i, u_matspecular.a);\n", i, i); + WRITE(p, " dot%i = pow(dot[%i], u_matspecular.a);\n", i, i); WRITE(p, " }\n"); } @@ -489,13 +424,13 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { timesLightScale = ""; break; case GE_LIGHTTYPE_POINT: - WRITE(p, " lightScale = clamp(1.0 / dot(u_lightatt%i, vec3(1.0, distance, distance*distance)), 0.0, 1.0);\n", i); + WRITE(p, " lightScale = clamp(1.0 / dot(light.att[%i], vec3(1.0, distance, distance*distance)), 0.0, 1.0);\n", i); break; case GE_LIGHTTYPE_SPOT: case GE_LIGHTTYPE_UNKNOWN: - WRITE(p, " lowp float angle%i = dot(normalize(u_lightdir%i), toLight);\n", i, i); - WRITE(p, " if (angle%i >= u_lightangle%i) {\n", i, i); - WRITE(p, " lightScale = clamp(1.0 / dot(u_lightatt%i, vec3(1.0, distance, distance*distance)), 0.0, 1.0) * pow(angle%i, u_lightspotCoef%i);\n", i, i, i); + WRITE(p, " lowp float angle%i = dot(normalize(light.dir[%i]), toLight);\n", i, i); + WRITE(p, " if (angle[%i] >= light.angle[%i]) {\n", i, i); + WRITE(p, " lightScale = clamp(1.0 / dot(light.att[%i], vec3(1.0, distance, distance*distance)), 0.0, 1.0) * pow(angle[%i], light.spotCoef[%i]);\n", i, i, i); WRITE(p, " } else {\n"); WRITE(p, " lightScale = 0.0;\n"); WRITE(p, " }\n"); @@ -505,13 +440,13 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { break; } - WRITE(p, " diffuse = (u_lightdiffuse%i * %s) * dot%i;\n", i, diffuseStr, i); + WRITE(p, " diffuse = (light.diffuse[%i] * %s) * dot[%i];\n", i, diffuseStr, i); if (doSpecular) { - WRITE(p, " dot%i = dot(normalize(toLight + vec3(0.0, 0.0, 1.0)), worldnormal);\n", i); - WRITE(p, " if (dot%i > 0.0)\n", i); - WRITE(p, " lightSum1 += u_lightspecular%i * %s * (pow(dot%i, u_matspecular.a) %s);\n", i, specularStr, i, timesLightScale); + WRITE(p, " dot[%i] = dot(normalize(toLight + vec3(0.0, 0.0, 1.0)), worldnormal);\n", i); + WRITE(p, " if (dot[%i] > 0.0)\n", i); + WRITE(p, " lightSum1 += light.specular[%i] * %s * (pow(dot[%i], u_matspecular.a) %s);\n", i, specularStr, i, timesLightScale); } - WRITE(p, " lightSum0.rgb += (u_lightambient%i * %s.rgb + diffuse)%s;\n", i, ambientStr, timesLightScale); + WRITE(p, " lightSum0.rgb += (light.ambient[%i] * %s.rgb + diffuse)%s;\n", i, ambientStr, timesLightScale); } if (enableLighting) { @@ -595,12 +530,12 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { break; } // Transform by texture matrix. XYZ as we are doing projection mapping. - WRITE(p, " v_texcoord = (u_texmtx * %s).xyz * vec3(u_uvscaleoffset.xy, 1.0);\n", temp_tc.c_str()); + WRITE(p, " v_texcoord = (base.texmtx * %s).xyz * vec3(base.uvscaleoffset.xy, 1.0);\n", temp_tc.c_str()); } break; case GE_TEXMAP_ENVIRONMENT_MAP: // Shade mapping - use dots from light sources. - WRITE(p, " v_texcoord = u_uvscaleoffset.xy * vec2(1.0 + dot(normalize(u_lightpos%i), worldnormal), 1.0 + dot(normalize(u_lightpos%i), worldnormal)) * 0.5;\n", ls0, ls1); + WRITE(p, " v_texcoord = base.uvscaleoffset.xy * vec2(1.0 + dot(normalize(light.pos[%i]), worldnormal), 1.0 + dot(normalize(light.pos[%i]), worldnormal)) * 0.5;\n", ls0, ls1); break; default: From 4ddca8607f642656265da98685f071051605bc07 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Thu, 31 Dec 2015 14:06:18 +0100 Subject: [PATCH 009/116] Further vulkan stuff --- Windows/GPU/WindowsVulkanContext.cpp | 37 +++++++++++++++---- ext/native/thin3d/VulkanContext.cpp | 54 +++++++++++++++------------- ext/native/thin3d/VulkanContext.h | 2 +- headless/Headless.vcxproj | 2 +- unittest/UnitTests.vcxproj | 5 ++- 5 files changed, 65 insertions(+), 35 deletions(-) diff --git a/Windows/GPU/WindowsVulkanContext.cpp b/Windows/GPU/WindowsVulkanContext.cpp index 77cc2fc877..855824ec2f 100644 --- a/Windows/GPU/WindowsVulkanContext.cpp +++ b/Windows/GPU/WindowsVulkanContext.cpp @@ -56,8 +56,15 @@ #include "thin3d/thin3d.h" #include "Windows/GPU/WindowsVulkanContext.h" -const bool g_validate_ = true; -VulkanContext *g_Vulkan; +static const bool g_validate_ = true; +static VulkanContext *g_Vulkan; + +struct VulkanLogOptions { + bool breakOnWarning; + bool breakOnError; + bool msgBoxOnError; +}; +static VulkanLogOptions g_LogOptions; const char *ObjTypeToString(VkDebugReportObjectTypeEXT type) { switch (type) { @@ -92,7 +99,8 @@ const char *ObjTypeToString(VkDebugReportObjectTypeEXT type) { } } -static VkBool32 Vulkan_Dbg(VkDebugReportFlagsEXT msgFlags, VkDebugReportObjectTypeEXT objType, uint64_t srcObject, size_t location, int32_t msgCode, const char* pLayerPrefix, const char* pMsg, void *pUserData) { +static VkBool32 VKAPI_CALL Vulkan_Dbg(VkDebugReportFlagsEXT msgFlags, VkDebugReportObjectTypeEXT objType, uint64_t srcObject, size_t location, int32_t msgCode, const char* pLayerPrefix, const char* pMsg, void *pUserData) { + VulkanLogOptions *options = (VulkanLogOptions *)pUserData; std::ostringstream message; if (msgFlags & VK_DEBUG_REPORT_ERROR_BIT_EXT) { @@ -112,8 +120,16 @@ static VkBool32 Vulkan_Dbg(VkDebugReportFlagsEXT msgFlags, VkDebugReportObjectTy OutputDebugStringA(message.str().c_str()); OutputDebugStringA("\n"); if (msgFlags & VK_DEBUG_REPORT_ERROR_BIT_EXT) { - // MessageBox(NULL, message.str().c_str(), "Alert", MB_OK); - } else { + if (options->breakOnError) { + DebugBreak(); + } + if (options->msgBoxOnError) { + MessageBoxA(NULL, message.str().c_str(), "Alert", MB_OK); + } + } else if (msgFlags & VK_DEBUG_REPORT_WARNING_BIT_EXT) { + if (options->breakOnWarning) { + DebugBreak(); + } } #else std::cout << message << std::endl; @@ -137,9 +153,16 @@ bool WindowsVulkanContext::Init(HINSTANCE hInst, HWND hWnd, std::string *error_m init_glslang(); - g_Vulkan = new VulkanContext("PPSSPP", VULKAN_FLAG_VALIDATE); + g_LogOptions.breakOnError = true; + g_LogOptions.breakOnWarning = true; + g_LogOptions.msgBoxOnError = false; + + g_Vulkan = new VulkanContext("PPSSPP", g_validate_ ? VULKAN_FLAG_VALIDATE : 0); g_Vulkan->CreateDevice(0); - g_Vulkan->InitDebugMsgCallback(Vulkan_Dbg); + if (g_validate_) { + int bits = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT; + g_Vulkan->InitDebugMsgCallback(Vulkan_Dbg, bits, &g_LogOptions); + } g_Vulkan->InitObjects(hInst, hWnd, true); _CrtCheckMemory(); diff --git a/ext/native/thin3d/VulkanContext.cpp b/ext/native/thin3d/VulkanContext.cpp index d5189dd71b..9cdc7c2315 100644 --- a/ext/native/thin3d/VulkanContext.cpp +++ b/ext/native/thin3d/VulkanContext.cpp @@ -155,23 +155,23 @@ void vk_transition_to_present(VkCommandBuffer cmd, VkImage image) { } void vk_transition_from_present(VkCommandBuffer cmd, VkImage image) { - VkImageMemoryBarrier prePresentBarrier = {}; - prePresentBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - prePresentBarrier.pNext = NULL; - prePresentBarrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; - prePresentBarrier.dstAccessMask = 0; - prePresentBarrier.oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; - prePresentBarrier.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; - prePresentBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - prePresentBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - prePresentBarrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - prePresentBarrier.subresourceRange.baseMipLevel = 0; - prePresentBarrier.subresourceRange.levelCount = 1; - prePresentBarrier.subresourceRange.baseArrayLayer = 0; - prePresentBarrier.subresourceRange.layerCount = 1; - prePresentBarrier.image = image; + VkImageMemoryBarrier postPresentBarrier = {}; + postPresentBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + postPresentBarrier.pNext = NULL; + postPresentBarrier.srcAccessMask = 0; + postPresentBarrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + postPresentBarrier.oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; + postPresentBarrier.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + postPresentBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + postPresentBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + postPresentBarrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + postPresentBarrier.subresourceRange.baseMipLevel = 0; + postPresentBarrier.subresourceRange.levelCount = 1; + postPresentBarrier.subresourceRange.baseArrayLayer = 0; + postPresentBarrier.subresourceRange.layerCount = 1; + postPresentBarrier.image = image; vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, - 0, 0, nullptr, 0, nullptr, 1, &prePresentBarrier); + 0, 0, nullptr, 0, nullptr, 1, &postPresentBarrier); } VkCommandBuffer VulkanContext::BeginSurfaceRenderPass(VkClearValue clear_values[2]) { @@ -193,6 +193,10 @@ VkCommandBuffer VulkanContext::BeginSurfaceRenderPass(VkClearValue clear_values[ NULL, ¤t_buffer); + // TODO: Deal with the VK_SUBOPTIMAL_KHR and VK_ERROR_OUT_OF_DATE_KHR + // return codes + assert(res == VK_SUCCESS); + VkCommandBufferBeginInfo begin; begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; begin.pNext = NULL; @@ -200,10 +204,6 @@ VkCommandBuffer VulkanContext::BeginSurfaceRenderPass(VkClearValue clear_values[ begin.pInheritanceInfo = nullptr; vkBeginCommandBuffer(cmd_, &begin); - // TODO: Deal with the VK_SUBOPTIMAL_KHR and VK_ERROR_OUT_OF_DATE_KHR - // return codes - assert(res == VK_SUCCESS); - vk_transition_from_present(cmd_, swapChainBuffers[current_buffer].image); VkRenderPassBeginInfo rp_begin; @@ -598,7 +598,7 @@ VkResult VulkanContext::CreateDevice(int physical_device) { return res; } -VkResult VulkanContext::InitDebugMsgCallback(PFN_vkDebugReportCallbackEXT dbgFunc) { +VkResult VulkanContext::InitDebugMsgCallback(PFN_vkDebugReportCallbackEXT dbgFunc, int bits, void *userdata) { VkResult res; VkDebugReportCallbackEXT msg_callback; @@ -618,9 +618,9 @@ VkResult VulkanContext::InitDebugMsgCallback(PFN_vkDebugReportCallbackEXT dbgFun VkDebugReportCallbackCreateInfoEXT cb; cb.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT; cb.pNext = nullptr; - cb.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT; + cb.flags = bits; cb.pfnCallback = dbgFunc; - cb.pUserData = NULL; + cb.pUserData = userdata; res = dbgCreateMsgCallback(instance_, &cb, nullptr, &msg_callback); switch (res) { case VK_SUCCESS: @@ -1427,6 +1427,10 @@ void TransitionImageLayout( image_memory_barrier.subresourceRange.levelCount = 1; image_memory_barrier.subresourceRange.layerCount = 1; + if (old_image_layout == VK_IMAGE_LAYOUT_PRESENT_SRC_KHR) { + image_memory_barrier.srcAccessMask = VK_ACCESS_MEMORY_READ_BIT; + } + if (old_image_layout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) { image_memory_barrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; } @@ -1443,11 +1447,11 @@ void TransitionImageLayout( } if (new_image_layout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) { - image_memory_barrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT; + image_memory_barrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_READ_BIT; } if (new_image_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) { - image_memory_barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT; + image_memory_barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT; } VkPipelineStageFlags src_stages = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; diff --git a/ext/native/thin3d/VulkanContext.h b/ext/native/thin3d/VulkanContext.h index 71aa2a4379..b661b225ae 100644 --- a/ext/native/thin3d/VulkanContext.h +++ b/ext/native/thin3d/VulkanContext.h @@ -117,7 +117,7 @@ public: bool MemoryTypeFromProperties(uint32_t typeBits, VkFlags requirements_mask, uint32_t *typeIndex); - VkResult InitDebugMsgCallback(PFN_vkDebugReportCallbackEXT dbgFunc); + VkResult InitDebugMsgCallback(PFN_vkDebugReportCallbackEXT dbgFunc, int bits, void *userdata = nullptr); void DestroyDebugMsgCallback(); VkSemaphore acquireSemaphore; diff --git a/headless/Headless.vcxproj b/headless/Headless.vcxproj index 2e84a6801e..5711fc1184 100644 --- a/headless/Headless.vcxproj +++ b/headless/Headless.vcxproj @@ -272,4 +272,4 @@ - \ No newline at end of file + diff --git a/unittest/UnitTests.vcxproj b/unittest/UnitTests.vcxproj index cc55ecec4a..8a37770f7c 100644 --- a/unittest/UnitTests.vcxproj +++ b/unittest/UnitTests.vcxproj @@ -195,6 +195,9 @@ {533f1d30-d04d-47cc-ad71-20f658907e36} + + {edfa2e87-8ac1-4853-95d4-d7594ff81947} + {3baae095-e0ab-4b0e-b5df-ce39c8ae31de} @@ -219,4 +222,4 @@ - + \ No newline at end of file From cfbecf5071da42df65f6d85eb02786fdffda7029 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sat, 2 Jan 2016 02:08:05 +0100 Subject: [PATCH 010/116] More progress --- GPU/GPU.vcxproj | 2 - GPU/GPU.vcxproj.filters | 2 - GPU/Vulkan/ShaderCompiler.cpp | 23 -- GPU/Vulkan/ShaderCompiler.h | 27 --- GPU/Vulkan/ShaderManagerVulkan.cpp | 41 +--- GPU/Vulkan/ShaderManagerVulkan.h | 27 +-- GPU/Vulkan/StateMappingVulkan.cpp | 22 +- GPU/Vulkan/VertexShaderGeneratorVulkan.cpp | 58 +---- GPU/Vulkan/VulkanUtil.h | 1 + Windows/GPU/WindowsVulkanContext.cpp | 14 +- Windows/WindowsHost.cpp | 1 + ext/native/thin3d/VulkanContext.cpp | 249 ++++++++++++--------- ext/native/thin3d/VulkanContext.h | 49 ++-- ext/native/thin3d/thin3d.cpp | 6 +- ext/native/thin3d/thin3d_vulkan.cpp | 197 +++++++--------- ext/native/thin3d/vulkan_utils.cpp | 19 +- ext/native/thin3d/vulkan_utils.h | 6 +- unittest/UnitTests.vcxproj | 2 +- 18 files changed, 320 insertions(+), 426 deletions(-) delete mode 100644 GPU/Vulkan/ShaderCompiler.cpp delete mode 100644 GPU/Vulkan/ShaderCompiler.h diff --git a/GPU/GPU.vcxproj b/GPU/GPU.vcxproj index 97caad8963..99093aaf4b 100644 --- a/GPU/GPU.vcxproj +++ b/GPU/GPU.vcxproj @@ -249,7 +249,6 @@ - @@ -337,7 +336,6 @@ - diff --git a/GPU/GPU.vcxproj.filters b/GPU/GPU.vcxproj.filters index 1a1beed97b..9ad5e7fe0c 100644 --- a/GPU/GPU.vcxproj.filters +++ b/GPU/GPU.vcxproj.filters @@ -210,7 +210,6 @@ - @@ -404,6 +403,5 @@ - \ No newline at end of file diff --git a/GPU/Vulkan/ShaderCompiler.cpp b/GPU/Vulkan/ShaderCompiler.cpp deleted file mode 100644 index b644c03db5..0000000000 --- a/GPU/Vulkan/ShaderCompiler.cpp +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) 2015- PPSSPP Project. - -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, version 2.0 or later versions. - -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License 2.0 for more details. - -// A copy of the GPL 2.0 should have been included with the program. -// If not, see http://www.gnu.org/licenses/ - -// Official git repository and contact information can be found at -// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. - -#include "GPU/Vulkan/VulkanUtil.h" -#include "GPU/Vulkan/ShaderCompiler.h" - -bool CompileGLSLVulkan(const char *code, std::vector &spirv, std::string &errorMessage) { - return false; -} diff --git a/GPU/Vulkan/ShaderCompiler.h b/GPU/Vulkan/ShaderCompiler.h deleted file mode 100644 index 8c5121f96f..0000000000 --- a/GPU/Vulkan/ShaderCompiler.h +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) 2015- PPSSPP Project. - -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, version 2.0 or later versions. - -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License 2.0 for more details. - -// A copy of the GPL 2.0 should have been included with the program. -// If not, see http://www.gnu.org/licenses/ - -// Official git repository and contact information can be found at -// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. - -#pragma once - -#include -#include "GPU/Vulkan/VulkanUtil.h" - -// Wrapper around the GLSL compiler library. Compiles GLSL into SPIR-V consumable by Vulkan. -bool CompileGLSLVulkan(const char *code, std::vector &spirv, std::string &errorMessage); - -// TODO: Compute shaders - diff --git a/GPU/Vulkan/ShaderManagerVulkan.cpp b/GPU/Vulkan/ShaderManagerVulkan.cpp index 029e7e9030..1efb3e925a 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.cpp +++ b/GPU/Vulkan/ShaderManagerVulkan.cpp @@ -37,7 +37,6 @@ #include "GPU/Vulkan/ShaderManagerVulkan.h" #include "GPU/Vulkan/DrawEngineVulkan.h" #include "GPU/Vulkan/FramebufferVulkan.h" -#include "GPU/Vulkan/ShaderCompiler.h" #include "GPU/Vulkan/FragmentShaderGeneratorVulkan.h" #include "GPU/Vulkan/VertexShaderGeneratorVulkan.h" #include "UI/OnScreenDisplay.h" @@ -51,7 +50,8 @@ VulkanFragmentShader::VulkanFragmentShader(VkDevice device, ShaderID id, const c std::string errorMessage; std::vector spirv; - bool success = CompileGLSLVulkan(code, spirv, errorMessage); + + bool success = GLSLtoSPV(VK_SHADER_STAGE_FRAGMENT_BIT, code, spirv, &errorMessage); if (!errorMessage.empty()) { if (success) { ERROR_LOG(G3D, "Warnings in shader compilation!"); @@ -100,7 +100,7 @@ VulkanVertexShader::VulkanVertexShader(VkDevice device, ShaderID id, const char #endif std::string errorMessage; std::vector spirv; - bool success = CompileGLSLVulkan(code, spirv, errorMessage); + bool success = GLSLtoSPV(VK_SHADER_STAGE_VERTEX_BIT, code, spirv, &errorMessage); if (!errorMessage.empty()) { if (success) { ERROR_LOG(G3D, "Warnings in shader compilation!"); @@ -142,33 +142,12 @@ std::string VulkanVertexShader::GetShaderString(DebugShaderStringType type) cons } } -/* -// Utility -void ShaderManagerVulkan::VSSetMatrix4x3(int creg, const float *m4x3) { - float m4x4[16]; - ConvertMatrix4x3To4x4Transposed(m4x4, m4x3); - pD3Ddevice->SetVertexShaderConstantF(creg, m4x4, 4); -} - -void ShaderManagerVulkan::VSSetMatrix4x3_3(int creg, const float *m4x3) { - float m3x4[16]; - ConvertMatrix4x3To3x4Transposed(m3x4, m4x3); - pD3Ddevice->SetVertexShaderConstantF(creg, m3x4, 3); -} - -void ShaderManagerVulkan::VSSetMatrix(int creg, const float* pMatrix) { - float transp[16]; - Transpose4x4(transp, pMatrix); - pD3Ddevice->SetVertexShaderConstantF(creg, transp, 4); -} -*/ - // Depth in ogl is between -1;1 we need between 0;1 and optionally reverse it static void ConvertProjMatrixToVulkan(Matrix4x4 &in, bool invertedX, bool invertedY, bool invertedZ) { // Half pixel offset hack float xoff = 0.5f / gstate_c.curRTRenderWidth; xoff = gstate_c.vpXOffset + (invertedX ? xoff : -xoff); - float yoff = -0.5f / gstate_c.curRTRenderHeight; + float yoff = 0.5f / gstate_c.curRTRenderHeight; yoff = gstate_c.vpYOffset + (invertedY ? yoff : -yoff); if (invertedX) @@ -180,9 +159,7 @@ static void ConvertProjMatrixToVulkan(Matrix4x4 &in, bool invertedX, bool invert } static void ConvertProjMatrixToVulkanThrough(Matrix4x4 &in) { - float xoff = -0.5f / gstate_c.curRTRenderWidth; - float yoff = 0.5f / gstate_c.curRTRenderHeight; - in.translateAndScale(Vec3(xoff, yoff, 0.5f), Vec3(1.0f, 1.0f, 0.5f)); + in.translateAndScale(Vec3(0.0f, 0.0f, 0.5f), Vec3(1.0f, 1.0f, 0.5f)); } void ShaderManagerVulkan::PSUpdateUniforms(int dirtyUniforms) { @@ -402,20 +379,20 @@ void ShaderManagerVulkan::VSUpdateUniforms(int dirtyUniforms) { // Lighting if (dirtyUniforms & DIRTY_AMBIENT) { - Uint8x3ToFloat4_AlphaUint8(ub_lightGlobal.ambientColor, gstate.ambientcolor, gstate.getAmbientA()); + Uint8x3ToFloat4_AlphaUint8(ub_lights.ambientColor, gstate.ambientcolor, gstate.getAmbientA()); } if (dirtyUniforms & DIRTY_MATAMBIENTALPHA) { // Note - this one is not in lighting but in transformCommon as it has uses beyond lighting Uint8x3ToFloat4_AlphaUint8(ub_transformCommon.matAmbient, gstate.materialambient, gstate.getMaterialAmbientA()); } if (dirtyUniforms & DIRTY_MATDIFFUSE) { - Uint8x3ToFloat4(ub_lightGlobal.materialDiffuse, gstate.materialdiffuse); + Uint8x3ToFloat4(ub_lights.materialDiffuse, gstate.materialdiffuse); } if (dirtyUniforms & DIRTY_MATEMISSIVE) { - Uint8x3ToFloat4(ub_lightGlobal.materialEmissive, gstate.materialemissive); + Uint8x3ToFloat4(ub_lights.materialEmissive, gstate.materialemissive); } if (dirtyUniforms & DIRTY_MATSPECULAR) { - Uint8x3ToFloat4_Alpha(ub_lightGlobal.materialEmissive, gstate.materialspecular, getFloat24(gstate.materialspecularcoef)); + Uint8x3ToFloat4_Alpha(ub_lights.materialEmissive, gstate.materialspecular, getFloat24(gstate.materialspecularcoef)); } for (int i = 0; i < 4; i++) { diff --git a/GPU/Vulkan/ShaderManagerVulkan.h b/GPU/Vulkan/ShaderManagerVulkan.h index 7e099b3416..00b6103bd7 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.h +++ b/GPU/Vulkan/ShaderManagerVulkan.h @@ -96,6 +96,10 @@ R"(matrix4x4 proj; )"; struct UB_VS_Lights { + float ambientColor[4]; + float materialDiffuse[4]; + float materialSpecular[4]; + float materialEmissive[4]; float lpos[4][4]; float ldir[4][4]; float latt[4][4]; @@ -107,7 +111,11 @@ struct UB_VS_Lights { }; static const char *ub_vs_lightsStr = -R"(vec3 lpos[4]; +R"(vec3 ambientColor; + vec3 materialDiffuse; + vec4 materialSpecular; + vec3 materialEmissive; + vec3 lpos[4]; vec3 ldir[4]; vec3 latt[4]; float lightAngle[4]; @@ -117,26 +125,12 @@ R"(vec3 lpos[4]; vec3 lightSpecular[4]; )"; -struct UB_VS_LightGlobal { - float ambientColor[4]; - float materialDiffuse[4]; - float materialSpecular[4]; - float materialEmissive[4]; -}; - -static const char *ub_vs_lightsGlobalStr = -R"(vec3 ambientColor; - vec3 materialDiffuse; - vec4 materialSpecular; - vec3 materialEmissive; -)"; - struct UB_VS_Bones { float bones[8][16]; }; static const char *ub_vs_bonesStr = -R"(matrix4x4 bone[8]; +R"(matrix4x4 m[8]; )"; // Let's not bother splitting this, we'll just upload the lot for every draw call. @@ -242,7 +236,6 @@ private: // Uniform block scratchpad. These (the relevant ones) are copied to the current pushbuffer at draw time. UB_VS_TransformCommon ub_transformCommon; - UB_VS_LightGlobal ub_lightGlobal; UB_VS_Lights ub_lights; UB_VS_Bones ub_bones; UB_FS_All ub_fragment; diff --git a/GPU/Vulkan/StateMappingVulkan.cpp b/GPU/Vulkan/StateMappingVulkan.cpp index 9515c8b088..ce7c1122e1 100644 --- a/GPU/Vulkan/StateMappingVulkan.cpp +++ b/GPU/Vulkan/StateMappingVulkan.cpp @@ -176,22 +176,24 @@ void ConvertStateToVulkanKey(FramebufferManagerVulkan &fbManager, int prim, Vulk bool alphaMask = gstate.isClearModeAlphaMask(); key.colorWriteMask = (colorMask ? (VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_A_BIT) : 0) | (alphaMask ? VK_COLOR_COMPONENT_A_BIT : 0); + GenericStencilFuncState stencilState; + ConvertStencilFuncState(stencilState); + // Stencil Test - if (alphaMask) { + if (stencilState.enabled) { key.stencilTestEnable = true; - key.stencilCompareOp = VK_COMPARE_OP_ALWAYS; - key.stencilPassOp = VK_STENCIL_OP_REPLACE; - key.stencilFailOp = VK_STENCIL_OP_REPLACE; - key.stencilDepthFailOp = VK_STENCIL_OP_REPLACE; - // TODO: Are these right? + key.stencilCompareOp = compareOps[stencilState.testFunc]; + key.stencilPassOp = stencilOps[stencilState.zPass]; + key.stencilFailOp = stencilOps[stencilState.sFail]; + key.stencilDepthFailOp = stencilOps[stencilState.zFail]; dynState.useStencil = true; - dynState.stencilRef = 0xFF; - dynState.stencilCompareMask = 0xFF; - dynState.stencilWriteMask = 0xFF; + dynState.stencilRef = stencilState.testRef; + dynState.stencilCompareMask = stencilState.testMask; + dynState.stencilWriteMask = stencilState.writeMask; } else { key.stencilTestEnable = false; + dynState.useStencil = false; } - } else { // Set cull bool wantCull = !gstate.isModeThrough() && prim != GE_PRIM_RECTANGLES && gstate.isCullEnabled(); diff --git a/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp b/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp index c1ef4ddc8a..5d6c5197b8 100644 --- a/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp +++ b/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp @@ -32,6 +32,7 @@ #include "GPU/Common/VertexDecoderCommon.h" #include "GPU/Vulkan/VertexShaderGeneratorVulkan.h" #include "GPU/Vulkan/PipelineManagerVulkan.h" +#include "GPU/Vulkan/ShaderManagerVulkan.h" // "Varying" layout - must match fragment shader // color0 = 0 @@ -70,42 +71,6 @@ enum DoLightComputation { LIGHT_FULL, }; - -const char *vulkan_base_uniforms = R"( -layout(set=0, binding=4) uniform base { - mat4 proj; - mat4 world; - mat4 view; - mat4 texmtx; - vec4 uvscaleoffset; - vec2 fogcoef; - vec4 depthRange; - vec4 matambientalpha; -}; -)"; - -const char *vulkan_light_uniforms = R"( -layout(set=0, binding=5) uniform light { - vec4 ambient; - vec3 matdiffuse; - vec4 matspecular; - vec3 matemissive; - vec3 pos[4]; - // TODO: Make lighttype/comp uniforms too - vec3 att[4]; - vec3 dir[4]; - float angle[4]; - float spotCoef[4]; - vec3 ambient[4]; - vec3 diffuse[4]; - vec3 specular[4]; -)"; - -const char *vulkan_bone_uniforms = R"( -layout(set=0, binding=6) uniform bone { - mat4 m[8]; -)"; - // Depth range and viewport // // After the multiplication with the projection matrix, we have a 4D vector in clip space. @@ -213,12 +178,11 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { // We will memcpy the parts into place in a big buffer so we can be quite dynamic about what parts // are present and what parts aren't, but we will not be ultra detailed about it. - WRITE(p, "%s", vulkan_base_uniforms); + WRITE(p, "layout (binding=3) uniform base {\n%s\n}\n", ub_vs_transformCommonStr); if (enableLighting) - WRITE(p, "%s", vulkan_light_uniforms); + WRITE(p, "layout (binding=4) uniform light {\n%s\n}\n", ub_vs_lightsStr); if (enableBones) - WRITE(p, "%s", vulkan_bone_uniforms); - + WRITE(p, "layout (binding=5) uniform bone {\n%s\n}\n", ub_vs_bonesStr); bool prescale = false; @@ -409,10 +373,10 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { if (poweredDiffuse) { // pow(0.0, 0.0) may be undefined, but the PSP seems to treat it as 1.0. // Seen in Tales of the World: Radiant Mythology (#2424.) - WRITE(p, " if (dot%i == 0.0 && u_matspecular.a == 0.0) {\n", i); + WRITE(p, " if (dot%i == 0.0 && light.matspecular.a == 0.0) {\n", i); WRITE(p, " dot%i = 1.0;\n", i); WRITE(p, " } else {\n"); - WRITE(p, " dot%i = pow(dot[%i], u_matspecular.a);\n", i, i); + WRITE(p, " dot%i = pow(dot[%i], light.matspecular.a);\n", i, i); WRITE(p, " }\n"); } @@ -444,7 +408,7 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { if (doSpecular) { WRITE(p, " dot[%i] = dot(normalize(toLight + vec3(0.0, 0.0, 1.0)), worldnormal);\n", i); WRITE(p, " if (dot[%i] > 0.0)\n", i); - WRITE(p, " lightSum1 += light.specular[%i] * %s * (pow(dot[%i], u_matspecular.a) %s);\n", i, specularStr, i, timesLightScale); + WRITE(p, " lightSum1 += light.specular[%i] * %s * (pow(dot[%i], light.matspecular.a) %s);\n", i, specularStr, i, timesLightScale); } WRITE(p, " lightSum0.rgb += (light.ambient[%i] * %s.rgb + diffuse)%s;\n", i, ambientStr, timesLightScale); } @@ -471,7 +435,7 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { if (hasColor) { WRITE(p, " v_color0 = color0;\n"); } else { - WRITE(p, " v_color0 = u_matambientalpha;\n"); + WRITE(p, " v_color0 = base.matambientalpha;\n"); } if (lmode) WRITE(p, " v_color1 = vec3(0.0);\n"); @@ -490,9 +454,9 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { } } else { if (hasTexcoord) { - WRITE(p, " v_texcoord = texcoord * u_uvscaleoffset.xy + u_uvscaleoffset.zw;\n"); + WRITE(p, " v_texcoord = texcoord * base.uvscaleoffset.xy + base.uvscaleoffset.zw;\n"); } else { - WRITE(p, " v_texcoord = u_uvscaleoffset.zw;\n"); + WRITE(p, " v_texcoord = base.uvscaleoffset.zw;\n"); } } break; @@ -546,7 +510,7 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { // Compute fogdepth if (enableFog) - WRITE(p, " v_fogdepth = (viewPos.z + u_fogcoef.x) * u_fogcoef.y;\n"); + WRITE(p, " v_fogdepth = (viewPos.z + base.fogcoef.x) * base.fogcoef.y;\n"); } WRITE(p, "}\n"); return true; diff --git a/GPU/Vulkan/VulkanUtil.h b/GPU/Vulkan/VulkanUtil.h index 4899ff2b3a..4b0ebdbda3 100644 --- a/GPU/Vulkan/VulkanUtil.h +++ b/GPU/Vulkan/VulkanUtil.h @@ -2,4 +2,5 @@ #define VK_PROTOTYPES #include "ext/vulkan/vulkan.h" +#include "thin3d/vulkan_utils.h" diff --git a/Windows/GPU/WindowsVulkanContext.cpp b/Windows/GPU/WindowsVulkanContext.cpp index 855824ec2f..eb0af1f2c3 100644 --- a/Windows/GPU/WindowsVulkanContext.cpp +++ b/Windows/GPU/WindowsVulkanContext.cpp @@ -100,7 +100,7 @@ const char *ObjTypeToString(VkDebugReportObjectTypeEXT type) { } static VkBool32 VKAPI_CALL Vulkan_Dbg(VkDebugReportFlagsEXT msgFlags, VkDebugReportObjectTypeEXT objType, uint64_t srcObject, size_t location, int32_t msgCode, const char* pLayerPrefix, const char* pMsg, void *pUserData) { - VulkanLogOptions *options = (VulkanLogOptions *)pUserData; + const VulkanLogOptions *options = (const VulkanLogOptions *)pUserData; std::ostringstream message; if (msgFlags & VK_DEBUG_REPORT_ERROR_BIT_EXT) { @@ -167,16 +167,10 @@ bool WindowsVulkanContext::Init(HINSTANCE hInst, HWND hWnd, std::string *error_m _CrtCheckMemory(); - VkClearValue clearVal[2]; - memset(clearVal, 0, sizeof(clearVal)); - clearVal[0].color.float32[0] = 0.5f; - g_Vulkan->BeginSurfaceRenderPass(clearVal); return true; } void WindowsVulkanContext::Shutdown() { - g_Vulkan->EndSurfaceRenderPass(); - g_Vulkan->DestroyObjects(); g_Vulkan->DestroyDebugMsgCallback(); g_Vulkan->DestroyDevice(); @@ -191,12 +185,6 @@ Thin3DContext *WindowsVulkanContext::CreateThin3DContext() { } void WindowsVulkanContext::SwapBuffers() { - g_Vulkan->EndSurfaceRenderPass(); - - VkClearValue clearVal[2]; - memset(clearVal, 0, sizeof(clearVal)); - clearVal[0].color.float32[0] = 0.5f; - g_Vulkan->BeginSurfaceRenderPass(clearVal); } void WindowsVulkanContext::Resize() { diff --git a/Windows/WindowsHost.cpp b/Windows/WindowsHost.cpp index 06f78162d6..5a6e50a097 100644 --- a/Windows/WindowsHost.cpp +++ b/Windows/WindowsHost.cpp @@ -187,6 +187,7 @@ void WindowsHost::SetDebugMode(bool mode) { } void WindowsHost::PollControllers(InputState &input_state) { + return; bool doPad = true; for (auto iter = this->input.begin(); iter != this->input.end(); iter++) { diff --git a/ext/native/thin3d/VulkanContext.cpp b/ext/native/thin3d/VulkanContext.cpp index 9cdc7c2315..98eef940cd 100644 --- a/ext/native/thin3d/VulkanContext.cpp +++ b/ext/native/thin3d/VulkanContext.cpp @@ -42,7 +42,7 @@ VulkanContext::VulkanContext(const char *app_name, uint32_t flags) : device_(nullptr), gfx_queue_(nullptr), connection(nullptr), - gfx_queue_family_index_(-1), + graphics_queue_family_index_(-1), surface(nullptr), window(nullptr), prepared(false), @@ -50,6 +50,7 @@ VulkanContext::VulkanContext(const char *app_name, uint32_t flags) instance_(nullptr), width(0), height(0), + flags_(flags), swapchain_format(VK_FORMAT_UNDEFINED), swapchainImageCount(0), swap_chain_(nullptr), @@ -58,7 +59,8 @@ VulkanContext::VulkanContext(const char *app_name, uint32_t flags) cmdInitActive_(false), dbgCreateMsgCallback(nullptr), dbgDestroyMsgCallback(nullptr), - queue_count(0) + queue_count(0), + curFrame_(0) { // List extensions to try to enable. instance_extension_names.push_back(VK_KHR_SURFACE_EXTENSION_NAME); @@ -117,14 +119,14 @@ VulkanContext::VulkanContext(const char *app_name, uint32_t flags) res = vkEnumeratePhysicalDevices(instance_, &gpu_count, physical_devices_.data()); assert(!res); - init_global_layer_properties(); - init_global_extension_properties(); + InitGlobalLayerProperties(); + InitGlobalExtensionProperties(); if (!CheckLayers(instance_layer_properties, instance_layer_names)) { exit(1); } - init_device_layer_properties(); + InitDeviceLayerProperties(); if (!CheckLayers(device_layer_properties, device_layer_names)) { exit(1); } @@ -134,7 +136,7 @@ VulkanContext::~VulkanContext() { vkDestroyInstance(instance_, NULL); } -void vk_transition_to_present(VkCommandBuffer cmd, VkImage image) { +void TransitionToPresent(VkCommandBuffer cmd, VkImage image) { VkImageMemoryBarrier prePresentBarrier = {}; prePresentBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; prePresentBarrier.pNext = NULL; @@ -154,45 +156,39 @@ void vk_transition_to_present(VkCommandBuffer cmd, VkImage image) { 0, 0, nullptr, 0, nullptr, 1, &prePresentBarrier); } -void vk_transition_from_present(VkCommandBuffer cmd, VkImage image) { - VkImageMemoryBarrier postPresentBarrier = {}; - postPresentBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - postPresentBarrier.pNext = NULL; - postPresentBarrier.srcAccessMask = 0; - postPresentBarrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; - postPresentBarrier.oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; - postPresentBarrier.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; - postPresentBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - postPresentBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - postPresentBarrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - postPresentBarrier.subresourceRange.baseMipLevel = 0; - postPresentBarrier.subresourceRange.levelCount = 1; - postPresentBarrier.subresourceRange.baseArrayLayer = 0; - postPresentBarrier.subresourceRange.layerCount = 1; - postPresentBarrier.image = image; +void TransitionFromPresent(VkCommandBuffer cmd, VkImage image) { + VkImageMemoryBarrier prePresentBarrier = {}; + prePresentBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + prePresentBarrier.pNext = NULL; + prePresentBarrier.srcAccessMask = 0; + prePresentBarrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + prePresentBarrier.oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; + prePresentBarrier.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + prePresentBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + prePresentBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + prePresentBarrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + prePresentBarrier.subresourceRange.baseMipLevel = 0; + prePresentBarrier.subresourceRange.levelCount = 1; + prePresentBarrier.subresourceRange.baseArrayLayer = 0; + prePresentBarrier.subresourceRange.layerCount = 1; + prePresentBarrier.image = image; vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, - 0, 0, nullptr, 0, nullptr, 1, &postPresentBarrier); + 0, 0, nullptr, 0, nullptr, 1, &prePresentBarrier); } VkCommandBuffer VulkanContext::BeginSurfaceRenderPass(VkClearValue clear_values[2]) { - VkSemaphoreCreateInfo acquireSemaphoreCreateInfo; - acquireSemaphoreCreateInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; - acquireSemaphoreCreateInfo.pNext = NULL; - acquireSemaphoreCreateInfo.flags = 0; + FrameData *frame = &frame_[curFrame_]; - VkResult res = vkCreateSemaphore(device_, - &acquireSemaphoreCreateInfo, - NULL, - &acquireSemaphore); - assert(res == VK_SUCCESS); + // Make sure the command buffer from the frame before the previous has been fully executed. + WaitAndResetFence(frame->fence); - // Get the index of the next available swapchain image, and a semaphore to block on. - res = fpAcquireNextImageKHR(device_, swap_chain_, + // Get the index of the next available swapchain image, and a semaphore to block command buffer execution on. + // Now, I wonder if we should do this early in the frame or late? + VkResult res = fpAcquireNextImageKHR(device_, swap_chain_, UINT64_MAX, acquireSemaphore, NULL, ¤t_buffer); - // TODO: Deal with the VK_SUBOPTIMAL_KHR and VK_ERROR_OUT_OF_DATE_KHR // return codes assert(res == VK_SUCCESS); @@ -202,9 +198,9 @@ VkCommandBuffer VulkanContext::BeginSurfaceRenderPass(VkClearValue clear_values[ begin.pNext = NULL; begin.flags = 0; begin.pInheritanceInfo = nullptr; - vkBeginCommandBuffer(cmd_, &begin); + res = vkBeginCommandBuffer(cmd_, &begin); - vk_transition_from_present(cmd_, swapChainBuffers[current_buffer].image); + TransitionFromPresent(frame->cmdBuf, swapChainBuffers[current_buffer].image); VkRenderPassBeginInfo rp_begin; rp_begin.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; @@ -218,8 +214,8 @@ VkCommandBuffer VulkanContext::BeginSurfaceRenderPass(VkClearValue clear_values[ rp_begin.clearValueCount = 2; rp_begin.pClearValues = clear_values; - vkCmdBeginRenderPass(cmd_, &rp_begin, VK_SUBPASS_CONTENTS_INLINE); - return cmd_; + vkCmdBeginRenderPass(frame->cmdBuf, &rp_begin, VK_SUBPASS_CONTENTS_INLINE); + return frame->cmdBuf; } void VulkanContext::WaitUntilQueueIdle() { @@ -274,6 +270,47 @@ void vk_submit_sync(VkDevice device, VkSemaphore waitForSemaphore, VkQueue queue vkDestroyFence(device, drawFence, NULL); } +void VulkanContext::EndSurfaceRenderPass() { + FrameData *frame = &frame_[curFrame_]; + vkCmdEndRenderPass(frame->cmdBuf); + + TransitionToPresent(frame->cmdBuf, swapChainBuffers[current_buffer].image); + + VkResult res = vkEndCommandBuffer(frame->cmdBuf); + assert(res == VK_SUCCESS); + + VkSubmitInfo submit_info = {}; + submit_info.pNext = NULL; + submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + submit_info.waitSemaphoreCount = 1; + submit_info.pWaitSemaphores = &acquireSemaphore; + submit_info.commandBufferCount = 1; + submit_info.pCommandBuffers = &frame->cmdBuf; + submit_info.signalSemaphoreCount = 0; + submit_info.pSignalSemaphores = NULL; + res = vkQueueSubmit(gfx_queue_, 1, &submit_info, frame->fence); + assert(res == VK_SUCCESS); + + // At this point we are certain that acquireSemaphore is of no further use and can be destroyed. + + VkPresentInfoKHR present; + present.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; + present.pNext = NULL; + present.swapchainCount = 1; + present.pSwapchains = &swap_chain_; + present.pImageIndices = ¤t_buffer; + present.pWaitSemaphores = NULL; + present.waitSemaphoreCount = 0; + present.pResults = NULL; + + res = fpQueuePresentKHR(gfx_queue_, &present); + // TODO: Deal with the VK_SUBOPTIMAL_WSI and VK_ERROR_OUT_OF_DATE_WSI + // return codes + assert(!res); + + curFrame_ ^= 1; +} + void VulkanContext::BeginInitCommandBuffer() { assert(!cmdInitActive_); VulkanBeginCommandBuffer(cmd_); @@ -300,9 +337,33 @@ void VulkanContext::InitObjects(HINSTANCE hInstance, HWND hWnd, bool depthPresen InitSurfaceRenderPass(depthPresent, true); InitFramebuffers(depthPresent); SubmitInitCommandBufferSync(); + + // Create frame data + + VkCommandBufferAllocateInfo cmd = {}; + cmd.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; + cmd.pNext = NULL; + cmd.commandPool = cmd_pool_; + cmd.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; + cmd.commandBufferCount = 2; + + VkCommandBuffer cmdBuf[2]; + VkResult res = vkAllocateCommandBuffers(device_, &cmd, cmdBuf); + assert(res == VK_SUCCESS); + + frame_[0].cmdBuf = cmdBuf[0]; + frame_[0].fence = CreateFence(true); // So it can be instantly waited on + frame_[1].cmdBuf = cmdBuf[1]; + frame_[1].fence = CreateFence(true); } void VulkanContext::DestroyObjects() { + VkCommandBuffer cmdBuf[2] = { frame_[0].cmdBuf, frame_[1].cmdBuf }; + + vkFreeCommandBuffers(device_, cmd_pool_, 2, cmdBuf); + vkDestroyFence(device_, frame_[0].fence, nullptr); + vkDestroyFence(device_, frame_[1].fence, nullptr); + DestroyFramebuffers(); DestroySurfaceRenderPass(); DestroyDepthStencilBuffer(); @@ -311,39 +372,7 @@ void VulkanContext::DestroyObjects() { DestroyCommandPool(); } -void VulkanContext::EndSurfaceRenderPass() { - vkCmdEndRenderPass(cmd_); - - vk_transition_to_present(cmd_, swapChainBuffers[current_buffer].image); - - VkResult res = vkEndCommandBuffer(cmd_); - assert(res == VK_SUCCESS); - - /* Make sure command buffer is finished before presenting */ - vk_submit_sync(device_, acquireSemaphore, gfx_queue_, cmd_); - // At this point we are certain that acquireSemaphore is of no further use and can be destroyed. - - /* Now present the image in the window */ - - VkPresentInfoKHR present; - present.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; - present.pNext = NULL; - present.swapchainCount = 1; - present.pSwapchains = &swap_chain_; - present.pImageIndices = ¤t_buffer; - present.pWaitSemaphores = NULL; - present.waitSemaphoreCount = 0; - present.pResults = NULL; - - res = fpQueuePresentKHR(gfx_queue_, &present); - // TODO: Deal with the VK_SUBOPTIMAL_WSI and VK_ERROR_OUT_OF_DATE_WSI - // return codes - assert(!res); - - vkDestroySemaphore(device_, acquireSemaphore, NULL); -} - -VkResult VulkanContext::init_layer_extension_properties(layer_properties &layer_props) { +VkResult VulkanContext::InitLayerExtensionProperties(layer_properties &layer_props) { VkExtensionProperties *instance_extensions; uint32_t instance_extension_count; VkResult res; @@ -371,7 +400,7 @@ VkResult VulkanContext::init_layer_extension_properties(layer_properties &layer_ return res; } -VkResult VulkanContext::init_global_extension_properties() { +VkResult VulkanContext::InitGlobalExtensionProperties() { uint32_t instance_extension_count; VkResult res; @@ -394,7 +423,7 @@ VkResult VulkanContext::init_global_extension_properties() { return res; } -VkResult VulkanContext::init_global_layer_properties() { +VkResult VulkanContext::InitGlobalLayerProperties() { uint32_t instance_layer_count; VkLayerProperties *vk_props = NULL; VkResult res; @@ -429,7 +458,7 @@ VkResult VulkanContext::init_global_layer_properties() { for (uint32_t i = 0; i < instance_layer_count; i++) { layer_properties layer_props; layer_props.properties = vk_props[i]; - res = init_layer_extension_properties(layer_props); + res = InitLayerExtensionProperties(layer_props); if (res) return res; instance_layer_properties.push_back(layer_props); @@ -439,7 +468,7 @@ VkResult VulkanContext::init_global_layer_properties() { return res; } -VkResult VulkanContext::init_device_extension_properties(layer_properties &layer_props) { +VkResult VulkanContext::InitDeviceExtensionProperties(layer_properties &layer_props) { VkExtensionProperties *device_extensions; uint32_t device_extension_count; VkResult res; @@ -469,10 +498,7 @@ VkResult VulkanContext::init_device_extension_properties(layer_properties &layer return res; } -/* - * TODO: function description here - */ -VkResult VulkanContext::init_device_layer_properties() { +VkResult VulkanContext::InitDeviceLayerProperties() { uint32_t device_layer_count; VkLayerProperties *vk_props = NULL; VkResult res; @@ -509,7 +535,7 @@ VkResult VulkanContext::init_device_layer_properties() { for (uint32_t i = 0; i < device_layer_count; i++) { layer_properties layer_props; layer_props.properties = vk_props[i]; - res = init_device_extension_properties(layer_props); + res = InitDeviceExtensionProperties(layer_props); if (res) return res; device_layer_properties.push_back(layer_props); @@ -607,7 +633,6 @@ VkResult VulkanContext::InitDebugMsgCallback(PFN_vkDebugReportCallbackEXT dbgFun std::cout << "GetInstanceProcAddr: Unable to find vkDbgCreateMsgCallback function." << std::endl; return VK_ERROR_INITIALIZATION_FAILED; } - std::cout << "Got dbgCreateMsgCallback function\n"; dbgDestroyMsgCallback = (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(instance_, "vkDestroyDebugReportCallbackEXT"); if (!dbgDestroyMsgCallback) { @@ -624,7 +649,6 @@ VkResult VulkanContext::InitDebugMsgCallback(PFN_vkDebugReportCallbackEXT dbgFun res = dbgCreateMsgCallback(instance_, &cb, nullptr, &msg_callback); switch (res) { case VK_SUCCESS: - puts("Successfully created message callback object\n"); msg_callbacks.push_back(msg_callback); break; case VK_ERROR_OUT_OF_HOST_MEMORY: @@ -805,7 +829,7 @@ void VulkanContext::InitSurfaceAndQueue(HINSTANCE conn, HWND wnd) { exit(-1); } - gfx_queue_family_index_ = graphicsQueueNodeIndex; + graphics_queue_family_index_ = graphicsQueueNodeIndex; // Get the list of VkFormats that are supported: uint32_t formatCount; @@ -829,7 +853,18 @@ void VulkanContext::InitSurfaceAndQueue(HINSTANCE conn, HWND wnd) { } delete[] surfFormats; - vkGetDeviceQueue(device_, gfx_queue_family_index_, 0, &gfx_queue_); + vkGetDeviceQueue(device_, graphics_queue_family_index_, 0, &gfx_queue_); + + VkSemaphoreCreateInfo acquireSemaphoreCreateInfo; + acquireSemaphoreCreateInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; + acquireSemaphoreCreateInfo.pNext = NULL; + acquireSemaphoreCreateInfo.flags = 0; + + res = vkCreateSemaphore(device_, + &acquireSemaphoreCreateInfo, + NULL, + &acquireSemaphore); + assert(res == VK_SUCCESS); } void VulkanContext::InitSwapchain() { @@ -874,13 +909,13 @@ void VulkanContext::InitSwapchain() { // always available. VkPresentModeKHR swapchainPresentMode = VK_PRESENT_MODE_FIFO_KHR; for (size_t i = 0; i < presentModeCount; i++) { - if (presentModes[i] == VK_PRESENT_MODE_MAILBOX_KHR) { + if ((flags_ & VULKAN_FLAG_PRESENT_MAILBOX) && presentModes[i] == VK_PRESENT_MODE_MAILBOX_KHR) { swapchainPresentMode = VK_PRESENT_MODE_MAILBOX_KHR; break; } - if ((swapchainPresentMode != VK_PRESENT_MODE_MAILBOX_KHR) && - (presentModes[i] == VK_PRESENT_MODE_IMMEDIATE_KHR)) { + if ((flags_ & VULKAN_FLAG_PRESENT_IMMEDIATE) && presentModes[i] == VK_PRESENT_MODE_IMMEDIATE_KHR) { swapchainPresentMode = VK_PRESENT_MODE_IMMEDIATE_KHR; + break; } } @@ -1063,7 +1098,7 @@ void VulkanContext::InitCommandPool() { VkCommandPoolCreateInfo cmd_pool_info = {}; cmd_pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; cmd_pool_info.pNext = NULL; - cmd_pool_info.queueFamilyIndex = gfx_queue_family_index_; + cmd_pool_info.queueFamilyIndex = graphics_queue_family_index_; cmd_pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT | VK_COMMAND_POOL_CREATE_TRANSIENT_BIT; res = vkCreateCommandPool(device_, &cmd_pool_info, NULL, &cmd_pool_); @@ -1295,7 +1330,7 @@ void VulkanTexture::Unlock(VulkanContext *vulkan) { // that could be avoided with smarter code - for example we can check the fence the next // time the texture is used and discard the staging image then. - VkFence fence = vulkan->CreateFence(); + VkFence fence = vulkan->CreateFence(false); res = vkQueueSubmit(vulkan->gfx_queue_, 1, submit_info, fence); assert(res == VK_SUCCESS); @@ -1307,7 +1342,7 @@ void VulkanTexture::Unlock(VulkanContext *vulkan) { VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, imageLayout); - vulkan->WaitForFence(fence); + vulkan->WaitAndResetFence(fence); /* Release the resources for the staging image */ vkFreeMemory(vulkan->device_, mappableMemory, NULL); @@ -1346,18 +1381,21 @@ void VulkanTexture::Destroy(VulkanContext *vulkan) { mem = NULL; } -VkFence VulkanContext::CreateFence() { +VkFence VulkanContext::CreateFence(bool presignalled) { VkFence fence; VkFenceCreateInfo fenceInfo; fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; fenceInfo.pNext = NULL; - fenceInfo.flags = 0; + fenceInfo.flags = presignalled ? VK_FENCE_CREATE_SIGNALED_BIT : 0; vkCreateFence(device_, &fenceInfo, NULL, &fence); return fence; } -void VulkanContext::WaitForFence(VkFence fence) { - vkWaitForFences(device_, 1, &fence, true, 0); +void VulkanContext::WaitAndResetFence(VkFence fence) { + VkResult res = vkWaitForFences(device_, 1, &fence, true, UINT64_MAX); + assert(!res); + res = vkResetFences(device_, 1, &fence); + assert(!res); } void VulkanContext::DestroyCommandBuffer() { @@ -1387,6 +1425,7 @@ void VulkanContext::DestroySwapChain() { fpDestroySwapchainKHR(device_, swap_chain_, NULL); swap_chain_ = nullptr; swapChainBuffers.clear(); + vkDestroySemaphore(device_, acquireSemaphore, NULL); } void VulkanContext::DestroyFramebuffers() { @@ -1426,7 +1465,6 @@ void TransitionImageLayout( image_memory_barrier.subresourceRange.baseMipLevel = 0; image_memory_barrier.subresourceRange.levelCount = 1; image_memory_barrier.subresourceRange.layerCount = 1; - if (old_image_layout == VK_IMAGE_LAYOUT_PRESENT_SRC_KHR) { image_memory_barrier.srcAccessMask = VK_ACCESS_MEMORY_READ_BIT; } @@ -1442,7 +1480,9 @@ void TransitionImageLayout( if (new_image_layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) { /* Make sure any Copy or CPU writes to image are flushed */ - image_memory_barrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT; + if (old_image_layout != VK_IMAGE_LAYOUT_UNDEFINED) { + image_memory_barrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT; + } image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; } @@ -1580,13 +1620,11 @@ EShLanguage FindLanguage(const VkShaderStageFlagBits shader_type) { } } -// // Compile a given string containing GLSL into SPV for use by VK // Return value of false means an error was encountered. -// bool GLSLtoSPV(const VkShaderStageFlagBits shader_type, const char *pshader, - std::vector &spirv) { + std::vector &spirv, std::string *errorMessage) { glslang::TProgram& program = *new glslang::TProgram; const char *shaderStrings[1]; @@ -1605,6 +1643,10 @@ bool GLSLtoSPV(const VkShaderStageFlagBits shader_type, if (!shader->parse(&Resources, 100, false, messages)) { puts(shader->getInfoLog()); puts(shader->getInfoDebugLog()); + if (errorMessage) { + *errorMessage = shader->getInfoLog(); + (*errorMessage) += shader->getInfoDebugLog(); + } return false; // something didn't work } @@ -1617,11 +1659,15 @@ bool GLSLtoSPV(const VkShaderStageFlagBits shader_type, if (!program.link(messages)) { puts(shader->getInfoLog()); puts(shader->getInfoDebugLog()); + if (errorMessage) { + *errorMessage = shader->getInfoLog(); + (*errorMessage) += shader->getInfoDebugLog(); + } return false; } + // Can't fail, parsing worked, "linking" worked. glslang::GlslangToSpv(*program.getIntermediate(stage), spirv); - return true; } @@ -1663,5 +1709,4 @@ const char *VulkanResultToString(VkResult res) { void VulkanAssertImpl(VkResult check, const char *function, const char *file, int line) { const char *error = "(none)"; - } diff --git a/ext/native/thin3d/VulkanContext.h b/ext/native/thin3d/VulkanContext.h index b661b225ae..7eaba87e59 100644 --- a/ext/native/thin3d/VulkanContext.h +++ b/ext/native/thin3d/VulkanContext.h @@ -54,6 +54,8 @@ enum { VULKAN_FLAG_VALIDATE = 1, + VULKAN_FLAG_PRESENT_MAILBOX = 2, + VULKAN_FLAG_PRESENT_IMMEDIATE = 4, }; // A layer can expose extensions, keep track of those extensions here. @@ -103,8 +105,8 @@ public: void WaitUntilQueueIdle(); // Utility functions for shorter code - VkFence CreateFence(); - void WaitForFence(VkFence fence); + VkFence CreateFence(bool presignalled); + void WaitAndResetFence(VkFence fence); int GetWidth() { return width; } int GetHeight() { return height; } @@ -120,32 +122,33 @@ public: VkResult InitDebugMsgCallback(PFN_vkDebugReportCallbackEXT dbgFunc, int bits, void *userdata = nullptr); void DestroyDebugMsgCallback(); - VkSemaphore acquireSemaphore; - - VkRenderPass GetSurfaceRenderPass() { + VkRenderPass GetSurfaceRenderPass() const { return surface_render_pass_; } - VkPhysicalDevice GetPhysicalDevice() { + VkPhysicalDevice GetPhysicalDevice() const { return physical_devices_[0]; } - VkQueue GetGraphicsQueue() { + VkQueue GetGraphicsQueue() const { return gfx_queue_; } - int GetGraphicsQueueFamilyIndex() { - return gfx_queue_family_index_; + int GetGraphicsQueueFamilyIndex() const { + return graphics_queue_family_index_; } - VkResult init_global_extension_properties(); - VkResult init_layer_extension_properties(layer_properties &layer_props); - VkResult init_global_layer_properties(); + VkResult InitGlobalExtensionProperties(); + VkResult InitLayerExtensionProperties(layer_properties &layer_props); - VkResult init_device_extension_properties(layer_properties &layer_props); - VkResult init_device_layer_properties(); + VkResult InitGlobalLayerProperties(); + VkResult InitDeviceExtensionProperties(layer_properties &layer_props); + VkResult InitDeviceLayerProperties(); + + + VkSemaphore acquireSemaphore; #ifdef _WIN32 #define APP_NAME_STR_LEN 80 @@ -182,7 +185,7 @@ public: std::vector device_extension_properties; std::vector physical_devices_; - uint32_t gfx_queue_family_index_; + uint32_t graphics_queue_family_index_; VkPhysicalDeviceProperties gpu_props; std::vector queue_props; VkPhysicalDeviceMemoryProperties memory_properties; @@ -195,12 +198,21 @@ private: // Swap chain int width, height; + int flags_; VkFormat swapchain_format; std::vector framebuffers_; uint32_t swapchainImageCount; VkSwapchainKHR swap_chain_; std::vector swapChainBuffers; + // Manages flipping command buffers for the backbuffer render pass. + // It is recommended to do the same for other rendering passes. + struct FrameData { + VkFence fence; + VkCommandBuffer cmdBuf; + }; + FrameData frame_[2]; + int curFrame_; // Simple loader for the WSI extension. PFN_vkGetPhysicalDeviceSurfaceSupportKHR fpGetPhysicalDeviceSurfaceSupportKHR; @@ -265,7 +277,7 @@ void vk_submit_sync(VkDevice device, VkSemaphore waitForSemaphore, VkQueue queue void init_glslang(); void finalize_glslang(); -bool GLSLtoSPV(const VkShaderStageFlagBits shader_type, const char *pshader, std::vector &spirv); +bool GLSLtoSPV(const VkShaderStageFlagBits shader_type, const char *pshader, std::vector &spirv, std::string *errorMessage = nullptr); void TransitionImageLayout( VkCommandBuffer cmd, @@ -274,10 +286,5 @@ void TransitionImageLayout( VkImageLayout old_image_layout, VkImageLayout new_image_layout); -void VulkanAssertImpl(VkResult check, const char *function, const char *file, int line); - -// DO NOT call vulkan functions within this! Instead, store the result in a variable and check that. -#define VulkanAssert(x) if ((x) != VK_SUCCESS) VulkanAssertImpl((x), __FUNCTION__, __FILE__, __LINE__); - #endif // UTIL_INIT diff --git a/ext/native/thin3d/thin3d.cpp b/ext/native/thin3d/thin3d.cpp index 1fb65b34e4..d72e72f9a9 100644 --- a/ext/native/thin3d/thin3d.cpp +++ b/ext/native/thin3d/thin3d.cpp @@ -34,7 +34,7 @@ static const char * const vulkan_fsTexCol = "layout(location = 0) in vec4 oColor0;\n" "layout(location = 1) in vec2 oTexCoord0;\n" "layout(location = 0) out vec4 fragColor0\n;" -"layout(binding = 2) uniform sampler2D Sampler0;\n" +"layout(set = 0, binding = 1) uniform sampler2D Sampler0;\n" "void main() { fragColor0 = texture(Sampler0, oTexCoord0) * oColor0; }\n"; static const char * const glsl_fsCol = @@ -87,7 +87,7 @@ static const char * const vulkan_vsCol = "#version 140\n" "#extension GL_ARB_separate_shader_objects : enable\n" "#extension GL_ARB_shading_language_420pack : enable\n" -"layout (std140, binding = 1) uniform bufferVals {\n" +"layout (std140, set = 0, binding = 0) uniform bufferVals {\n" " mat4 WorldViewProj;\n" "} myBufferVals;\n" "layout (location = 0) in vec4 pos;\n" @@ -128,7 +128,7 @@ static const char * const vulkan_vsTexCol = "#version 140\n" "#extension GL_ARB_separate_shader_objects : enable\n" "#extension GL_ARB_shading_language_420pack : enable\n" -"layout (std140, binding = 1) uniform bufferVals {\n" +"layout (std140, set = 0, binding = 0) uniform bufferVals {\n" " mat4 WorldViewProj;\n" "} myBufferVals;\n" "layout (location = 0) in vec4 pos;\n" diff --git a/ext/native/thin3d/thin3d_vulkan.cpp b/ext/native/thin3d/thin3d_vulkan.cpp index e6c96ba840..b421af57e4 100644 --- a/ext/native/thin3d/thin3d_vulkan.cpp +++ b/ext/native/thin3d/thin3d_vulkan.cpp @@ -33,9 +33,10 @@ #include "thin3d/VulkanContext.h" // We use a simple descriptor set for all rendering: 1 sampler, 1 texture, 1 UBO binding point. -// binding 0 - vertex data -// binding 1 - uniform data -// binding 2 - sampler +// binding 0 - uniform data +// binding 1 - sampler +// +// Vertex data lives in a separate namespace (location = 0, 1, etc) #define VK_PROTOTYPES #include "ext/vulkan/vulkan.h" @@ -383,6 +384,10 @@ public: void SetVector(const char *name, float *value, int n) override; void SetMatrix4x4(const char *name, const float value[16]) override; + int GetUBOSize() const { + return uboSize_; + } + Thin3DVKShader *vshader; Thin3DVKShader *fshader; @@ -426,6 +431,7 @@ struct DescriptorSetKey { if (texture_ < other.texture_) return true; else if (texture_ > other.texture_) return false; if (vertexFormat_ < other.vertexFormat_) return true; else if (vertexFormat_ > other.vertexFormat_) return false; if (sampler_ < other.sampler_) return true; else if (sampler_ > other.sampler_) return false; + if (frame < other.frame) return true; else if (frame > other.frame) return false; return false; } }; @@ -507,7 +513,6 @@ private: void DirtyDynamicState(); void BeginInitCommands(); - void EndInitCommands(); VulkanContext *vulkan_; @@ -527,17 +532,13 @@ private: std::map descSets_; VkDescriptorPool descriptorPool_; - VkDescriptorSet descriptorSet_; VkDescriptorSetLayout descriptorSetLayout_; VkPipelineLayout pipelineLayout_; VkPipelineCache pipelineCache_; VkCommandPool cmdPool_; - VkInstance instance_; - VkPhysicalDevice physicalDevice_; VkDevice device_; VkQueue queue_; - VkRenderPass renderPass_; int queueFamilyIndex_; // State to apply at the next draw call if viewportDirty or scissorDirty are true. @@ -557,20 +558,11 @@ private: VkCommandBuffer initCmd_; bool hasInitCommands_; VkFence initFence_; - bool pendingInitFence_; // TODO: Transpose this into a struct FrameObject[2]. - // We write to one, while we wait for the draws from the other to complete. - // Then, at the end of the frame, they switch roles. - // cmdBuf_ for commands, pushBuffer_ for data. cmd_ will often refer to push_. - - VkCommandBuffer cmdBuffer_[2]; VkCommandBuffer cmd_; // The current one - VkFence cmdFences_[2]; - VkFence cmdFence_; - VulkanPushBuffer *pushBuffer_[2]; int frameNum_; VulkanPushBuffer *push_; @@ -674,7 +666,6 @@ private: VulkanImage staging_; VkImageView view_; - int32_t width_, height_, depth_; int mipLevels_; T3DImageFormat format_; @@ -682,14 +673,22 @@ private: }; Thin3DVKContext::Thin3DVKContext(VulkanContext *vulkan) - : viewportDirty_(false), scissorDirty_(false), vulkan_(vulkan) { + : viewportDirty_(false), scissorDirty_(false), vulkan_(vulkan), frameNum_(0) { device_ = vulkan->GetDevice(); + queue_ = vulkan->GetGraphicsQueue(); + queueFamilyIndex_ = vulkan->GetGraphicsQueueFamilyIndex(); noScissor_.offset.x = 0; noScissor_.offset.y = 0; noScissor_.extent.width = pixel_xres; noScissor_.extent.height = pixel_yres; - + scissor_ = noScissor_; + viewport_.x = 0; + viewport_.y = 0; + viewport_.width = pixel_xres; + viewport_.height = pixel_yres; + viewport_.minDepth = 0.0f; + viewport_.maxDepth = 0.0f; memset(boundTextures_, 0, sizeof(boundTextures_)); CreatePresets(); @@ -703,18 +702,16 @@ Thin3DVKContext::Thin3DVKContext(VulkanContext *vulkan) VkResult res = vkCreateCommandPool(device_, &p, nullptr, &cmdPool_); assert(VK_SUCCESS == res); - VkDescriptorPoolSize dpTypes[3]; + VkDescriptorPoolSize dpTypes[2]; dpTypes[0].descriptorCount = 200; dpTypes[0].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; - dpTypes[1].descriptorCount = 1; + dpTypes[1].descriptorCount = 2; dpTypes[1].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; - dpTypes[2].descriptorCount = 1; - dpTypes[2].type = VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT; VkDescriptorPoolCreateInfo dp; dp.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; dp.pNext = nullptr; - dp.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT; // We want to individually alloc and free descriptor sets. (do we?) + dp.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT; // We want to individually alloc and free descriptor sets. (do we? or one per "frame"?) dp.maxSets = 200; // One set for every texture available... sigh dp.pPoolSizes = dpTypes; dp.poolSizeCount = ARRAY_SIZE(dpTypes); @@ -723,31 +720,25 @@ Thin3DVKContext::Thin3DVKContext(VulkanContext *vulkan) pushBuffer_[0] = new VulkanPushBuffer(device_, vulkan_, 1024 * 1024); pushBuffer_[1] = new VulkanPushBuffer(device_, vulkan_, 1024 * 1024); - // binding 0 - vertex data - // binding 1 - uniform data - // binding 2 - sampler - // binding 3 - image - VkDescriptorSetLayoutBinding bindings[4]; + // binding 0 - uniform data + // binding 1 - sampler + // binding 2 - image + VkDescriptorSetLayoutBinding bindings[2]; bindings[0].descriptorCount = 1; bindings[0].pImmutableSamplers = nullptr; - bindings[0].descriptorType = VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT; + bindings[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; bindings[0].stageFlags = VK_SHADER_STAGE_VERTEX_BIT; bindings[0].binding = 0; bindings[1].descriptorCount = 1; bindings[1].pImmutableSamplers = nullptr; - bindings[1].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; - bindings[1].stageFlags = VK_SHADER_STAGE_VERTEX_BIT; + bindings[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + bindings[1].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; bindings[1].binding = 1; - bindings[2].descriptorCount = 1; - bindings[2].pImmutableSamplers = nullptr; - bindings[2].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; - bindings[2].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; - bindings[2].binding = 2; VkDescriptorSetLayoutCreateInfo dsl; dsl.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; dsl.pNext = nullptr; - dsl.bindingCount = 3; + dsl.bindingCount = 2; dsl.pBindings = bindings; res = vkCreateDescriptorSetLayout(device_, &dsl, nullptr, &descriptorSetLayout_); assert(VK_SUCCESS == res); @@ -768,10 +759,6 @@ Thin3DVKContext::Thin3DVKContext(VulkanContext *vulkan) cb.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; cb.commandPool = cmdPool_; cb.commandBufferCount = 1; - res = vkAllocateCommandBuffers(device_, &cb, &cmdBuffer_[0]); - assert(VK_SUCCESS == res); - res = vkAllocateCommandBuffers(device_, &cb, &cmdBuffer_[1]); - assert(VK_SUCCESS == res); res = vkAllocateCommandBuffers(device_, &cb, &initCmd_); assert(VK_SUCCESS == res); hasInitCommands_ = false; @@ -780,16 +767,7 @@ Thin3DVKContext::Thin3DVKContext(VulkanContext *vulkan) f.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; f.pNext = nullptr; f.flags = 0; - res = vkCreateFence(device_, &f, nullptr, &cmdFences_[0]); - assert(VK_SUCCESS == res); - - f.flags = VK_FENCE_CREATE_SIGNALED_BIT; - res = vkCreateFence(device_, &f, nullptr, &cmdFences_[1]); - assert(VK_SUCCESS == res); - // Create as already signalled, so we can wait for it the first time. - res = vkCreateFence(device_, &f, nullptr, &initFence_); - assert(VK_SUCCESS == res); - pendingInitFence_ = false; + vkCreateFence(device_, &f, nullptr, &initFence_); VkPipelineCacheCreateInfo pc; pc.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO; @@ -799,18 +777,12 @@ Thin3DVKContext::Thin3DVKContext(VulkanContext *vulkan) pc.flags = 0; res = vkCreatePipelineCache(device_, &pc, nullptr, &pipelineCache_); assert(VK_SUCCESS == res); - - push_ = pushBuffer_[0]; - cmd_ = cmdBuffer_[0]; - cmdFence_ = cmdFences_[0]; } Thin3DVKContext::~Thin3DVKContext() { for (auto x : pipelines_) { vkDestroyPipeline(device_, x.second, nullptr); } - vkFreeCommandBuffers(device_, cmdPool_, 2, cmdBuffer_); - vkFreeCommandBuffers(device_, cmdPool_, 1, &cmd_); vkDestroyCommandPool(device_, cmdPool_, nullptr); // This also destroys all descriptor sets. vkDestroyDescriptorPool(device_, descriptorPool_, nullptr); @@ -820,24 +792,28 @@ Thin3DVKContext::~Thin3DVKContext() { } void Thin3DVKContext::Begin(bool clear, uint32_t colorval, float depthVal, int stencilVal) { - VkClearValue clearVal[2]; + VkClearValue clearVal[2] = {}; Uint8x4ToFloat4(colorval, clearVal[0].color.float32); - clearVal[0].color.float32[2] = 1.0f; + + if (frameNum_ & 1) + clearVal[0].color.float32[2] = 1.0f; clearVal[1].depthStencil.depth = depthVal; clearVal[1].depthStencil.stencil = stencilVal; - vulkan_->BeginSurfaceRenderPass(clearVal); - // Make sure we don't stomp over the old command buffer. - vkWaitForFences(device_, 1, &cmdFence_, true, 0); + cmd_ = vulkan_->BeginSurfaceRenderPass(clearVal); + + push_ = pushBuffer_[frameNum_ & 1]; + + // OK, we now know that nothing is reading from this frame's data pushbuffer, + // and that the command buffer can be safely reset and reused. So let's do that. push_->Begin(device_); + scissorDirty_ = true; + viewportDirty_ = true; } void Thin3DVKContext::BeginInitCommands() { assert(!hasInitCommands_); - // Before we can begin, we must be sure that the command buffer is no longer in use, as we only have a single one for init - // tasks (for now). - VkCommandBufferBeginInfo begin; begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; begin.pNext = nullptr; @@ -848,49 +824,34 @@ void Thin3DVKContext::BeginInitCommands() { hasInitCommands_ = true; } -void Thin3DVKContext::EndInitCommands() { - VkResult res = vkEndCommandBuffer(initCmd_); - assert(VK_SUCCESS == res); -} - void Thin3DVKContext::End() { // Stop collecting data in the frame data buffer. push_->End(device_); - vkCmdEndRenderPass(cmd_); - VkResult endRes = vkEndCommandBuffer(cmd_); - + // IF something needs to be uploaded etc, sneak it in before we actually run the main command buffer. if (hasInitCommands_) { - assert(!pendingInitFence_); - EndInitCommands(); + VkResult res = vkEndCommandBuffer(initCmd_); + assert(VK_SUCCESS == res); // Run the texture uploads etc _before_ we execute the ordinary command buffer - pendingInitFence_ = true; VkSubmitInfo submit = {}; submit.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submit.pCommandBuffers = &initCmd_; submit.commandBufferCount = 1; - VkResult res = vkQueueSubmit(queue_, 1, &submit, initFence_); + res = vkQueueSubmit(queue_, 1, &submit, initFence_); assert(VK_SUCCESS == res); + // Before we can begin, we must be sure that the command buffer is no longer in use, as we only have a single one for init + // tasks (for now). + vulkan_->WaitAndResetFence(initFence_); hasInitCommands_ = false; + // Init cmd buffer is again available for writing. } - if (VK_SUCCESS != endRes) { - ELOG("vkEndCommandBuffer failed"); - vkResetCommandBuffer(cmd_, 0); - } else { - VkSubmitInfo submit = {}; - submit.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; - submit.pCommandBuffers = &cmd_; - submit.commandBufferCount = 1; - VkResult res = vkQueueSubmit(queue_, 1, &submit, cmdFence_); - assert(VK_SUCCESS == res); - } + vulkan_->EndSurfaceRenderPass(); frameNum_++; - push_ = pushBuffer_[frameNum_ & 1]; - cmd_ = cmdBuffer_[frameNum_ & 1]; - cmdFence_ = cmdFences_[frameNum_ & 1]; + cmd_ = nullptr; // will be set on the next begin + push_ = nullptr; DirtyDynamicState(); } @@ -917,14 +878,13 @@ VkDescriptorSet Thin3DVKContext::GetOrCreateDescriptorSet() { VkResult res = vkAllocateDescriptorSets(device_, &alloc, &descSet); assert(VK_SUCCESS == res); - // bindings[0].descriptorType = VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT; - // bindings[1].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; - // bindings[2].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER; + // bindings[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; + // bindings[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; VkDescriptorBufferInfo bufferDesc; bufferDesc.buffer = push_->GetVkBuffer(); bufferDesc.offset = 0; - bufferDesc.range = 16 * 4; + bufferDesc.range = curShaderSet_->GetUBOSize(); VkDescriptorImageInfo imageDesc; imageDesc.imageView = boundTextures_[0]->GetImageView(); @@ -937,7 +897,7 @@ VkDescriptorSet Thin3DVKContext::GetOrCreateDescriptorSet() { writes[0].pNext = nullptr; writes[0].dstSet = descSet; writes[0].dstArrayElement = 0; - writes[0].dstBinding = 1; + writes[0].dstBinding = 0; writes[0].pBufferInfo = &bufferDesc; writes[0].descriptorCount = 1; writes[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; @@ -946,7 +906,7 @@ VkDescriptorSet Thin3DVKContext::GetOrCreateDescriptorSet() { writes[1].pNext = nullptr; writes[1].dstSet = descSet; writes[1].dstArrayElement = 0; - writes[1].dstBinding = 2; + writes[1].dstBinding = 1; writes[1].pImageInfo = &imageDesc; writes[1].descriptorCount = 1; writes[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; @@ -1062,7 +1022,7 @@ VkPipeline Thin3DVKContext::GetOrCreatePipeline() { info.pViewportState = &vs; // Must set viewport and scissor counts even if we set the actual state dynamically. info.layout = pipelineLayout_; info.subpass = 0; - info.renderPass = renderPass_; + info.renderPass = vulkan_->GetSurfaceRenderPass(); // OK, need to create a new pipeline. VkPipeline pipeline; @@ -1136,8 +1096,8 @@ void Thin3DVKTexture::SetImageData(int x, int y, int z, int width, int height, i // So we need to do a staging copy. We upload the data to the staging buffer immediately, then we actually do the final copy once it's used the first time // as we need a command buffer and the architecture of Thin3D doesn't really work the way we want.. if (!image_.IsValid()) { - staging_.Create2D(vulkan_, vulkanFormat, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, VK_IMAGE_USAGE_TRANSFER_SRC_BIT, width, height); - image_.Create2D(vulkan_, vulkanFormat, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, (VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT), width, height); + staging_.Create2D(vulkan_, vulkanFormat, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, VK_IMAGE_TILING_LINEAR, VK_IMAGE_USAGE_TRANSFER_SRC_BIT, width, height); + image_.Create2D(vulkan_, vulkanFormat, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VK_IMAGE_TILING_OPTIMAL, (VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT), width, height); } VkImageViewCreateInfo iv; @@ -1162,6 +1122,8 @@ void Thin3DVKTexture::SetImageData(int x, int y, int z, int width, int height, i // TODO: Support setting only parts of the image efficiently. staging_.SetImageData2D(vulkan_->GetDevice(), data, width, height, stride); state_ = TextureState::STAGED; + width_ = width; + height_ = height; } void Thin3DVKTexture::Finalize(int zim_flags) { @@ -1173,20 +1135,23 @@ bool Thin3DVKTexture::NeedsUpload() { } void Thin3DVKTexture::Upload(VkCommandBuffer cmd) { - if (state_ == TextureState::STAGED) { - // Before we can texture, we need to Copy and ChangeLayout. - VkImageCopy copy_region; - copy_region.srcSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }; - copy_region.srcOffset = { 0, 0, 0 }; - copy_region.dstSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }; - copy_region.dstOffset = { 0, 0, 0 }; - copy_region.extent = { (uint32_t)width_, (uint32_t)height_, 1 }; - vkCmdCopyImage(cmd, staging_.GetImage(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, image_.GetImage(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©_region); - image_.ChangeLayout(cmd, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); - // From this point on, the image can be used for texturing. - // Even before this function call (but after SetImageData), the image object can be referenced in a descriptor set. - state_ = TextureState::INITIALIZED; + if (state_ != TextureState::STAGED) { + return; } + + // Before we can texture, we need to Copy and ChangeLayout. + VkImageCopy copy_region; + copy_region.srcSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }; + copy_region.srcOffset = { 0, 0, 0 }; + copy_region.dstSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }; + copy_region.dstOffset = { 0, 0, 0 }; + copy_region.extent = { (uint32_t)width_, (uint32_t)height_, 1 }; + vkCmdCopyImage(cmd, staging_.GetImage(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, image_.GetImage(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©_region); + image_.ChangeLayout(cmd, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); + // From this point on, the image can be used for texturing. + // Even before this function call (but after SetImageData), the image object can be referenced in a descriptor set. Better make sure that the image is uploaded + // before it's actually used though... + state_ = TextureState::INITIALIZED; } static bool isPowerOf2(int n) { @@ -1317,6 +1282,7 @@ void Thin3DVKContext::SetRenderState(T3DRenderState rs, uint32_t value) { } void Thin3DVKContext::Draw(T3DPrimitive prim, Thin3DShaderSet *shaderSet, Thin3DVertexFormat *format, Thin3DBuffer *vdata, int vertexCount, int offset) { + return; ApplyDynamicState(); curPrim_ = primToVK[prim]; @@ -1338,6 +1304,7 @@ void Thin3DVKContext::Draw(T3DPrimitive prim, Thin3DShaderSet *shaderSet, Thin3D } void Thin3DVKContext::DrawIndexed(T3DPrimitive prim, Thin3DShaderSet *shaderSet, Thin3DVertexFormat *format, Thin3DBuffer *vdata, Thin3DBuffer *idata, int vertexCount, int offset) { + return; ApplyDynamicState(); curPrim_ = primToVK[prim]; diff --git a/ext/native/thin3d/vulkan_utils.cpp b/ext/native/thin3d/vulkan_utils.cpp index a94fd2955e..800f0ccf1c 100644 --- a/ext/native/thin3d/vulkan_utils.cpp +++ b/ext/native/thin3d/vulkan_utils.cpp @@ -40,12 +40,12 @@ #include "thin3d/vulkan_utils.h" -void VulkanImage::Create2D(VulkanContext *vulkan, VkFormat format, VkFlags required_props, VkImageUsageFlags usage, int width, int height) { +void VulkanImage::Create2D(VulkanContext *vulkan, VkFormat format, VkFlags required_props, VkImageTiling tiling, VkImageUsageFlags usage, int width, int height) { VkDevice device = vulkan->GetDevice(); width_ = width; height_ = height; - VkImageCreateInfo i; + VkImageCreateInfo i = {}; i.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; i.pNext = NULL; i.imageType = VK_IMAGE_TYPE_2D; @@ -54,13 +54,13 @@ void VulkanImage::Create2D(VulkanContext *vulkan, VkFormat format, VkFlags requi i.mipLevels = 1; i.arrayLayers = 1; i.samples = VK_SAMPLE_COUNT_1_BIT; - i.tiling = VK_IMAGE_TILING_LINEAR; + i.tiling = tiling; i.usage = usage; i.flags = 0; i.sharingMode = VK_SHARING_MODE_EXCLUSIVE; i.queueFamilyIndexCount = 0; i.pQueueFamilyIndices = nullptr; - i.initialLayout = VK_IMAGE_LAYOUT_GENERAL; + i.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; VkMemoryRequirements mem_reqs; @@ -81,6 +81,7 @@ void VulkanImage::Create2D(VulkanContext *vulkan, VkFormat format, VkFlags requi assert(!err); err = vkBindImageMemory(device, image_, memory_, 0); // at offset 0. + assert(!err); } void VulkanImage::SetImageData2D(VkDevice device, const uint8_t *data, int width, int height, int pitch) { @@ -121,14 +122,18 @@ void VulkanImage::ChangeLayout(VkCommandBuffer cmd, VkImageAspectFlags aspectMas image_memory_barrier.subresourceRange.baseMipLevel = 0; image_memory_barrier.subresourceRange.levelCount = 1; + if (old_image_layout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) { + image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + } + if (new_image_layout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) { - /* Make sure anything that was copying from this image has completed */ + // Make sure anything that was copying from this image has completed image_memory_barrier.srcAccessMask = VK_ACCESS_MEMORY_READ_BIT; } if (new_image_layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) { - /* Make sure any Copy or CPU writes to image are flushed */ - image_memory_barrier.dstAccessMask = VK_ACCESS_HOST_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT; + // Make sure any Copy or CPU writes to image are flushed + image_memory_barrier.dstAccessMask = VK_ACCESS_HOST_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_SHADER_READ_BIT; } VkPipelineStageFlags src_stages = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; diff --git a/ext/native/thin3d/vulkan_utils.h b/ext/native/thin3d/vulkan_utils.h index 9c194a78c3..278abdb4a2 100644 --- a/ext/native/thin3d/vulkan_utils.h +++ b/ext/native/thin3d/vulkan_utils.h @@ -23,7 +23,7 @@ #include "ext/vulkan/vulkan.h" #include "VulkanContext.h" - +class VulkanContext; // Utility class to handle images without going insane. // Allocates its own memory. class VulkanImage { @@ -32,7 +32,7 @@ public: bool IsValid() const { return image_ != nullptr; } // This can be done completely unsynchronized. - void Create2D(VulkanContext *vulkan, VkFormat format, VkFlags required_props, VkImageUsageFlags usage, int width, int height); + void Create2D(VulkanContext *vulkan, VkFormat format, VkFlags required_props, VkImageTiling tiling, VkImageUsageFlags usage, int width, int height); // This can only be used if you pass in VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT in required_props in Create2D. void SetImageData2D(VkDevice device, const uint8_t *data, int width, int height, int pitch); @@ -54,6 +54,4 @@ class Thin3DPipelineCache { }; -bool GLSLtoSPV(const VkShaderStageFlagBits shader_type, const char *pshader, std::vector &spirv); - bool CreateShaderModule(VkDevice device, const std::vector &spirv, VkShaderModule *shaderModule); diff --git a/unittest/UnitTests.vcxproj b/unittest/UnitTests.vcxproj index 8a37770f7c..43cbbea96b 100644 --- a/unittest/UnitTests.vcxproj +++ b/unittest/UnitTests.vcxproj @@ -222,4 +222,4 @@ - \ No newline at end of file + From e89a7f0c676aba12a87b75d6bbd3e7c448692151 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 3 Jan 2016 00:46:41 +0100 Subject: [PATCH 011/116] Update VulkanContext --- GPU/Common/TextureCacheCommon.h | 3 - GPU/GPU.vcxproj | 1 + GPU/GPU.vcxproj.filters | 1 + GPU/Vulkan/TextureCacheVulkan.cpp | 9 + GPU/Vulkan/TextureCacheVulkan.h | 8 +- ext/native/thin3d/VulkanContext.cpp | 287 ++++++++++------------------ ext/native/thin3d/VulkanContext.h | 64 +++++-- ext/native/thin3d/thin3d_vulkan.cpp | 70 +------ 8 files changed, 174 insertions(+), 269 deletions(-) create mode 100644 GPU/Vulkan/TextureCacheVulkan.cpp diff --git a/GPU/Common/TextureCacheCommon.h b/GPU/Common/TextureCacheCommon.h index 664f107ffe..95ff12aa60 100644 --- a/GPU/Common/TextureCacheCommon.h +++ b/GPU/Common/TextureCacheCommon.h @@ -24,9 +24,6 @@ #include "GPU/Common/GPUDebugInterface.h" #include "Common/MemoryUtil.h" -#include -#include - enum TextureFiltering { TEX_FILTER_AUTO = 1, TEX_FILTER_NEAREST = 2, diff --git a/GPU/GPU.vcxproj b/GPU/GPU.vcxproj index 99093aaf4b..09c17b003a 100644 --- a/GPU/GPU.vcxproj +++ b/GPU/GPU.vcxproj @@ -338,6 +338,7 @@ + diff --git a/GPU/GPU.vcxproj.filters b/GPU/GPU.vcxproj.filters index 9ad5e7fe0c..4fe276f335 100644 --- a/GPU/GPU.vcxproj.filters +++ b/GPU/GPU.vcxproj.filters @@ -403,5 +403,6 @@ + \ No newline at end of file diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp new file mode 100644 index 0000000000..d9bbf8e6b1 --- /dev/null +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -0,0 +1,9 @@ +#include "GPU/Vulkan/TextureCacheVulkan.h" + +bool TextureCacheVulkan::AttachFramebuffer(TexCacheEntry *entry, u32 address, VirtualFramebuffer *framebuffer, u32 texaddrOffset) { + return false; +} + +void TextureCacheVulkan::DetachFramebuffer(TexCacheEntry *entry, u32 address, VirtualFramebuffer *framebuffer) { + +} diff --git a/GPU/Vulkan/TextureCacheVulkan.h b/GPU/Vulkan/TextureCacheVulkan.h index fac5cde8c9..64f2c5bbd1 100644 --- a/GPU/Vulkan/TextureCacheVulkan.h +++ b/GPU/Vulkan/TextureCacheVulkan.h @@ -29,12 +29,8 @@ public: return false; } - bool AttachFramebuffer(TexCacheEntry *entry, u32 address, VirtualFramebuffer *framebuffer, u32 texaddrOffset = 0) override { - return false; - } - void DetachFramebuffer(TexCacheEntry *entry, u32 address, VirtualFramebuffer *framebuffer) override { - - } + bool AttachFramebuffer(TexCacheEntry *entry, u32 address, VirtualFramebuffer *framebuffer, u32 texaddrOffset = 0) override; + void DetachFramebuffer(TexCacheEntry *entry, u32 address, VirtualFramebuffer *framebuffer) override; void DownloadFramebufferForClut(u32 clutAddr, u32 bytes) override { diff --git a/ext/native/thin3d/VulkanContext.cpp b/ext/native/thin3d/VulkanContext.cpp index 98eef940cd..0b0556dc4a 100644 --- a/ext/native/thin3d/VulkanContext.cpp +++ b/ext/native/thin3d/VulkanContext.cpp @@ -55,8 +55,6 @@ VulkanContext::VulkanContext(const char *app_name, uint32_t flags) swapchainImageCount(0), swap_chain_(nullptr), cmd_pool_(nullptr), - cmd_(nullptr), - cmdInitActive_(false), dbgCreateMsgCallback(nullptr), dbgDestroyMsgCallback(nullptr), queue_count(0), @@ -176,12 +174,24 @@ void TransitionFromPresent(VkCommandBuffer cmd, VkImage image) { 0, 0, nullptr, 0, nullptr, 1, &prePresentBarrier); } +VkCommandBuffer VulkanContext::GetInitCommandBuffer() { + FrameData *frame = &frame_[curFrame_]; + if (!frame->hasInitCommands) { + VulkanBeginCommandBuffer(frame->cmdInit); + frame->hasInitCommands = true; + } + return frame_[curFrame_].cmdInit; +} + VkCommandBuffer VulkanContext::BeginSurfaceRenderPass(VkClearValue clear_values[2]) { FrameData *frame = &frame_[curFrame_]; // Make sure the command buffer from the frame before the previous has been fully executed. WaitAndResetFence(frame->fence); + // Process pending deletes. + frame->deleteList.PerformDeletes(device_); + // Get the index of the next available swapchain image, and a semaphore to block command buffer execution on. // Now, I wonder if we should do this early in the frame or late? VkResult res = fpAcquireNextImageKHR(device_, swap_chain_, @@ -198,7 +208,7 @@ VkCommandBuffer VulkanContext::BeginSurfaceRenderPass(VkClearValue clear_values[ begin.pNext = NULL; begin.flags = 0; begin.pInheritanceInfo = nullptr; - res = vkBeginCommandBuffer(cmd_, &begin); + res = vkBeginCommandBuffer(frame->cmdBuf, &begin); TransitionFromPresent(frame->cmdBuf, swapChainBuffers[current_buffer].image); @@ -219,6 +229,7 @@ VkCommandBuffer VulkanContext::BeginSurfaceRenderPass(VkClearValue clear_values[ } void VulkanContext::WaitUntilQueueIdle() { + // Should almost never be used vkQueueWaitIdle(gfx_queue_); } @@ -238,38 +249,6 @@ bool VulkanContext::MemoryTypeFromProperties(uint32_t typeBits, VkFlags requirem return false; } -// Terrible for performance! -void vk_submit_sync(VkDevice device, VkSemaphore waitForSemaphore, VkQueue queue, VkCommandBuffer cmd) { - const VkCommandBuffer cmd_bufs[] = { cmd }; - - VkFenceCreateInfo fenceInfo; - VkFence drawFence; - fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; - fenceInfo.pNext = NULL; - fenceInfo.flags = 0; - vkCreateFence(device, &fenceInfo, NULL, &drawFence); - - VkSubmitInfo submit_info[1] = {}; - submit_info[0].pNext = NULL; - submit_info[0].sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; - submit_info[0].waitSemaphoreCount = waitForSemaphore ? 1 : 0; - submit_info[0].pWaitSemaphores = waitForSemaphore ? &waitForSemaphore : NULL; - submit_info[0].commandBufferCount = 1; - submit_info[0].pCommandBuffers = cmd_bufs; - submit_info[0].signalSemaphoreCount = 0; - submit_info[0].pSignalSemaphores = NULL; - - /* Queue the command buffer for execution */ - VkResult res = vkQueueSubmit(queue, 1, submit_info, drawFence); - assert(res == VK_SUCCESS); - - do { - res = vkWaitForFences(device, 1, &drawFence, VK_TRUE, FENCE_TIMEOUT); - } while (res != VK_SUCCESS && res != VK_TIMEOUT); - - vkDestroyFence(device, drawFence, NULL); -} - void VulkanContext::EndSurfaceRenderPass() { FrameData *frame = &frame_[curFrame_]; vkCmdEndRenderPass(frame->cmdBuf); @@ -279,19 +258,27 @@ void VulkanContext::EndSurfaceRenderPass() { VkResult res = vkEndCommandBuffer(frame->cmdBuf); assert(res == VK_SUCCESS); - VkSubmitInfo submit_info = {}; - submit_info.pNext = NULL; - submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; - submit_info.waitSemaphoreCount = 1; - submit_info.pWaitSemaphores = &acquireSemaphore; - submit_info.commandBufferCount = 1; - submit_info.pCommandBuffers = &frame->cmdBuf; - submit_info.signalSemaphoreCount = 0; - submit_info.pSignalSemaphores = NULL; - res = vkQueueSubmit(gfx_queue_, 1, &submit_info, frame->fence); - assert(res == VK_SUCCESS); + int numCmdBufs = 0; + VkCommandBuffer cmdBufs[2]; - // At this point we are certain that acquireSemaphore is of no further use and can be destroyed. + if (frame->hasInitCommands) { + vkEndCommandBuffer(frame->cmdInit); + cmdBufs[numCmdBufs++] = frame->cmdInit; + frame->hasInitCommands = false; + } + cmdBufs[numCmdBufs++] = frame->cmdBuf; + + VkSubmitInfo submit_info[1] = {}; + submit_info[0].pNext = NULL; + submit_info[0].sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + submit_info[0].waitSemaphoreCount = 1; + submit_info[0].pWaitSemaphores = &acquireSemaphore; + submit_info[0].commandBufferCount = numCmdBufs; + submit_info[0].pCommandBuffers = cmdBufs; + submit_info[0].signalSemaphoreCount = 0; + submit_info[0].pSignalSemaphores = NULL; + res = vkQueueSubmit(gfx_queue_, 1, submit_info, frame->fence); + assert(res == VK_SUCCESS); VkPresentInfoKHR present; present.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; @@ -308,59 +295,59 @@ void VulkanContext::EndSurfaceRenderPass() { // return codes assert(!res); + frame->deleteList.Ingest(globalDeleteList_); curFrame_ ^= 1; } -void VulkanContext::BeginInitCommandBuffer() { - assert(!cmdInitActive_); - VulkanBeginCommandBuffer(cmd_); - cmdInitActive_ = true; -} - -void VulkanContext::SubmitInitCommandBufferSync() { - if (cmdInitActive_) { - vkEndCommandBuffer(cmd_); - vk_submit_sync(device_, 0, gfx_queue_, cmd_); - cmdInitActive_ = false; - } +void VulkanBeginCommandBuffer(VkCommandBuffer cmd) { + VkResult U_ASSERT_ONLY res; + VkCommandBufferBeginInfo cmd_buf_info = {}; + cmd_buf_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; + cmd_buf_info.pNext = NULL; + cmd_buf_info.pInheritanceInfo = nullptr; + cmd_buf_info.flags = 0; + res = vkBeginCommandBuffer(cmd, &cmd_buf_info); + assert(res == VK_SUCCESS); } void VulkanContext::InitObjects(HINSTANCE hInstance, HWND hWnd, bool depthPresent) { InitSurfaceAndQueue(hInstance, hWnd); InitCommandPool(); - InitCommandBuffer(); - BeginInitCommandBuffer(); - InitSwapchain(); - InitDepthStencilBuffer(); - - InitSurfaceRenderPass(depthPresent, true); - InitFramebuffers(depthPresent); - SubmitInitCommandBufferSync(); - // Create frame data - VkCommandBufferAllocateInfo cmd = {}; - cmd.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; - cmd.pNext = NULL; - cmd.commandPool = cmd_pool_; - cmd.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; - cmd.commandBufferCount = 2; + VkCommandBufferAllocateInfo cmd_alloc = {}; + cmd_alloc.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; + cmd_alloc.pNext = NULL; + cmd_alloc.commandPool = cmd_pool_; + cmd_alloc.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; + cmd_alloc.commandBufferCount = 4; - VkCommandBuffer cmdBuf[2]; - VkResult res = vkAllocateCommandBuffers(device_, &cmd, cmdBuf); + VkCommandBuffer cmdBuf[4]; + VkResult res = vkAllocateCommandBuffers(device_, &cmd_alloc, cmdBuf); assert(res == VK_SUCCESS); frame_[0].cmdBuf = cmdBuf[0]; + frame_[0].cmdInit = cmdBuf[1]; frame_[0].fence = CreateFence(true); // So it can be instantly waited on - frame_[1].cmdBuf = cmdBuf[1]; + frame_[1].cmdBuf = cmdBuf[2]; + frame_[1].cmdInit = cmdBuf[3]; frame_[1].fence = CreateFence(true); + + VkCommandBuffer cmd = GetInitCommandBuffer(); + InitSwapchain(cmd); + InitDepthStencilBuffer(cmd); + + InitSurfaceRenderPass(depthPresent, true); + InitFramebuffers(depthPresent); + + // The init command buffer will be executed as part of the first frame. } void VulkanContext::DestroyObjects() { - VkCommandBuffer cmdBuf[2] = { frame_[0].cmdBuf, frame_[1].cmdBuf }; + VkCommandBuffer cmdBuf[4] = { frame_[0].cmdBuf, frame_[0].cmdInit, frame_[1].cmdBuf, frame_[1].cmdInit}; - vkFreeCommandBuffers(device_, cmd_pool_, 2, cmdBuf); + vkFreeCommandBuffers(device_, cmd_pool_, sizeof(cmdBuf)/sizeof(cmdBuf[0]), cmdBuf); vkDestroyFence(device_, frame_[0].fence, nullptr); vkDestroyFence(device_, frame_[1].fence, nullptr); @@ -368,7 +355,6 @@ void VulkanContext::DestroyObjects() { DestroySurfaceRenderPass(); DestroyDepthStencilBuffer(); DestroySwapChain(); - DestroyCommandBuffer(); DestroyCommandPool(); } @@ -498,6 +484,9 @@ VkResult VulkanContext::InitDeviceExtensionProperties(layer_properties &layer_pr return res; } +/* + * TODO: function description here + */ VkResult VulkanContext::InitDeviceLayerProperties() { uint32_t device_layer_count; VkLayerProperties *vk_props = NULL; @@ -670,7 +659,7 @@ void VulkanContext::DestroyDebugMsgCallback() { } } -void VulkanContext::InitDepthStencilBuffer() { +void VulkanContext::InitDepthStencilBuffer(VkCommandBuffer cmd) { VkResult U_ASSERT_ONLY res; bool U_ASSERT_ONLY pass; VkImageCreateInfo image_info = {}; @@ -752,7 +741,7 @@ void VulkanContext::InitDepthStencilBuffer() { assert(res == VK_SUCCESS); /* Set the image layout to depth stencil optimal */ - TransitionImageLayout(cmd_, depth.image, + TransitionImageLayout(cmd, depth.image, VK_IMAGE_ASPECT_DEPTH_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); @@ -867,7 +856,7 @@ void VulkanContext::InitSurfaceAndQueue(HINSTANCE conn, HWND wnd) { assert(res == VK_SUCCESS); } -void VulkanContext::InitSwapchain() { +void VulkanContext::InitSwapchain(VkCommandBuffer cmd) { VkResult U_ASSERT_ONLY res; VkSurfaceCapabilitiesKHR surfCapabilities; @@ -991,7 +980,7 @@ void VulkanContext::InitSwapchain() { // TODO: Pre-set them to PRESENT_SRC_KHR, as the first thing we do after acquiring // in image to render to will be to transition them away from that. - TransitionImageLayout(cmd_, sc_buffer.image, + TransitionImageLayout(cmd, sc_buffer.image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR); @@ -1105,31 +1094,6 @@ void VulkanContext::InitCommandPool() { assert(res == VK_SUCCESS); } -void VulkanContext::InitCommandBuffer() { - VkResult U_ASSERT_ONLY res; - - VkCommandBufferAllocateInfo cmd = {}; - cmd.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; - cmd.pNext = NULL; - cmd.commandPool = cmd_pool_; - cmd.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; - cmd.commandBufferCount = 1; - - res = vkAllocateCommandBuffers(device_, &cmd, &this->cmd_); - assert(res == VK_SUCCESS); -} - -void VulkanBeginCommandBuffer(VkCommandBuffer cmd) { - VkResult U_ASSERT_ONLY res; - VkCommandBufferBeginInfo cmd_buf_info = {}; - cmd_buf_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; - cmd_buf_info.pNext = NULL; - cmd_buf_info.flags = 0; - cmd_buf_info.pInheritanceInfo = nullptr; - res = vkBeginCommandBuffer(cmd, &cmd_buf_info); - assert(res == VK_SUCCESS); -} - void VulkanTexture::Create(VulkanContext *vulkan, int w, int h) { tex_width = w; tex_height = h; @@ -1139,7 +1103,7 @@ void VulkanTexture::Create(VulkanContext *vulkan, int w, int h) { VkFormatProperties formatProps; vkGetPhysicalDeviceFormatProperties(vulkan->GetPhysicalDevice(), VK_FORMAT_R8G8B8A8_UNORM, &formatProps); - /* See if we can use a linear tiled image for a texture, if not, we will need a staging image for the texture data */ + // See if we can use a linear tiled image for a texture, if not, we will need a staging image for the texture data needStaging = (!(formatProps.linearTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)) ? true : false; VkImageCreateInfo image_create_info = {}; @@ -1154,8 +1118,7 @@ void VulkanTexture::Create(VulkanContext *vulkan, int w, int h) { image_create_info.arrayLayers = 1; image_create_info.samples = VK_SAMPLE_COUNT_1_BIT; image_create_info.tiling = VK_IMAGE_TILING_LINEAR; - image_create_info.usage = needStaging ? VK_IMAGE_USAGE_TRANSFER_SRC_BIT : - VK_IMAGE_USAGE_SAMPLED_BIT; + image_create_info.usage = needStaging ? VK_IMAGE_USAGE_TRANSFER_SRC_BIT : VK_IMAGE_USAGE_SAMPLED_BIT; image_create_info.queueFamilyIndexCount = 0; image_create_info.pQueueFamilyIndices = NULL; image_create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; @@ -1198,9 +1161,9 @@ uint8_t *VulkanTexture::Lock(VulkanContext *vulkan, int *rowPitch) { void *data; /* Get the subresource layout so we know what the row pitch is */ - vkGetImageSubresourceLayout(vulkan->device_, mappableImage, &subres, &layout); + vkGetImageSubresourceLayout(vulkan->GetDevice(), mappableImage, &subres, &layout); - VkResult res = vkMapMemory(vulkan->device_, mappableMemory, 0, mem_reqs.size, 0, &data); + VkResult res = vkMapMemory(vulkan->GetDevice(), mappableMemory, 0, mem_reqs.size, 0, &data); assert(res == VK_SUCCESS); *rowPitch = (int)layout.rowPitch; @@ -1208,17 +1171,16 @@ uint8_t *VulkanTexture::Lock(VulkanContext *vulkan, int *rowPitch) { } void VulkanTexture::Unlock(VulkanContext *vulkan) { - vkUnmapMemory(vulkan->device_, mappableMemory); + vkUnmapMemory(vulkan->GetDevice(), mappableMemory); + + VkCommandBuffer cmd = vulkan->GetInitCommandBuffer(); if (!needStaging) { /* If we can use the linear tiled image as a texture, just do it */ image = mappableImage; mem = mappableMemory; imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - TransitionImageLayout(vulkan->GetInitCommandBuffer(), image, - VK_IMAGE_ASPECT_COLOR_BIT, - VK_IMAGE_LAYOUT_UNDEFINED, - imageLayout); + TransitionImageLayout(cmd, image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED, imageLayout); } else { VkImageCreateInfo image_create_info = {}; image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; @@ -1235,14 +1197,15 @@ void VulkanTexture::Unlock(VulkanContext *vulkan) { image_create_info.pQueueFamilyIndices = NULL; image_create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; image_create_info.flags = 0; - /* The mappable image cannot be our texture, so create an optimally tiled image and blit to it */ + // The mappable image cannot be our texture, so create an optimally tiled image and blit to it image_create_info.tiling = VK_IMAGE_TILING_OPTIMAL; image_create_info.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; + image_create_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; - VkResult res = vkCreateImage(vulkan->device_, &image_create_info, NULL, &image); + VkResult res = vkCreateImage(vulkan->GetDevice(), &image_create_info, NULL, &image); assert(res == VK_SUCCESS); - vkGetImageMemoryRequirements(vulkan->device_, image, &mem_reqs); + vkGetImageMemoryRequirements(vulkan->GetDevice(), image, &mem_reqs); VkMemoryAllocateInfo mem_alloc = {}; mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; @@ -1256,22 +1219,22 @@ void VulkanTexture::Unlock(VulkanContext *vulkan) { assert(pass); /* allocate memory */ - res = vkAllocateMemory(vulkan->device_, &mem_alloc, NULL, &mem); + res = vkAllocateMemory(vulkan->GetDevice(), &mem_alloc, NULL, &mem); assert(res == VK_SUCCESS); /* bind memory */ - res = vkBindImageMemory(vulkan->device_, image, mem, 0); + res = vkBindImageMemory(vulkan->GetDevice(), image, mem, 0); assert(res == VK_SUCCESS); /* Since we're going to blit from the mappable image, set its layout to SOURCE_OPTIMAL */ /* Side effect is that this will create info.cmd */ - TransitionImageLayout(vulkan->GetInitCommandBuffer(), mappableImage, + TransitionImageLayout(cmd, mappableImage, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); /* Since we're going to blit to the texture image, set its layout to DESTINATION_OPTIMAL */ - TransitionImageLayout(vulkan->GetInitCommandBuffer(), image, + TransitionImageLayout(cmd, image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); @@ -1295,59 +1258,23 @@ void VulkanTexture::Unlock(VulkanContext *vulkan) { copy_region.extent.height = tex_height; copy_region.extent.depth = 1; - VkCommandBufferBeginInfo cmd_buf_info = {}; - cmd_buf_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; - cmd_buf_info.pNext = NULL; - cmd_buf_info.flags = 0; - cmd_buf_info.pInheritanceInfo = nullptr; - - res = vkBeginCommandBuffer(vulkan->cmd_, &cmd_buf_info); - assert(res == VK_SUCCESS); - - /* Put the copy command into the command buffer */ - vkCmdCopyImage(vulkan->cmd_, + // Put the copy command into the command buffer + vkCmdCopyImage(cmd, mappableImage, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©_region); - res = vkEndCommandBuffer(vulkan->cmd_); - assert(res == VK_SUCCESS); - const VkCommandBuffer cmd_bufs[] = { vulkan->cmd_ }; - VkFence nullFence = VK_NULL_HANDLE; - - VkSubmitInfo submit_info[1] = {}; - submit_info[0].pNext = NULL; - submit_info[0].sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; - submit_info[0].waitSemaphoreCount = 0; - submit_info[0].pWaitSemaphores = NULL; - submit_info[0].commandBufferCount = 1; - submit_info[0].pCommandBuffers = cmd_bufs; - submit_info[0].signalSemaphoreCount = 0; - submit_info[0].pSignalSemaphores = NULL; - - // Queue the command buffer for execution. We can't legally delete the staging source - // until this has completed, so let's throw in a fence. Note that this is a huge stall - // that could be avoided with smarter code - for example we can check the fence the next - // time the texture is used and discard the staging image then. - - VkFence fence = vulkan->CreateFence(false); - - res = vkQueueSubmit(vulkan->gfx_queue_, 1, submit_info, fence); assert(res == VK_SUCCESS); /* Set the layout for the texture image from DESTINATION_OPTIMAL to SHADER_READ_ONLY */ imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - TransitionImageLayout(vulkan->GetInitCommandBuffer(), image, + TransitionImageLayout(cmd, image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, imageLayout); - vulkan->WaitAndResetFence(fence); - - /* Release the resources for the staging image */ - vkFreeMemory(vulkan->device_, mappableMemory, NULL); - vkDestroyImage(vulkan->device_, mappableImage, NULL); - vkDestroyFence(vulkan->device_, fence, NULL); + vulkan->QueueDelete(mappableMemory); + vulkan->QueueDelete(mappableImage); } VkImageViewCreateInfo view_info = {}; @@ -1368,14 +1295,14 @@ void VulkanTexture::Unlock(VulkanContext *vulkan) { /* create image view */ view_info.image = image; - VkResult res = vkCreateImageView(vulkan->device_, &view_info, NULL, &view); + VkResult res = vkCreateImageView(vulkan->GetDevice(), &view_info, NULL, &view); assert(res == VK_SUCCESS); } void VulkanTexture::Destroy(VulkanContext *vulkan) { - vkDestroyImageView(vulkan->device_, view, NULL); - vkDestroyImage(vulkan->device_, image, NULL); - vkFreeMemory(vulkan->device_, mem, NULL); + vkDestroyImageView(vulkan->GetDevice(), view, NULL); + vkDestroyImage(vulkan->GetDevice(), image, NULL); + vkFreeMemory(vulkan->GetDevice(), mem, NULL); view = NULL; image = NULL; mem = NULL; @@ -1392,16 +1319,8 @@ VkFence VulkanContext::CreateFence(bool presignalled) { } void VulkanContext::WaitAndResetFence(VkFence fence) { - VkResult res = vkWaitForFences(device_, 1, &fence, true, UINT64_MAX); - assert(!res); - res = vkResetFences(device_, 1, &fence); - assert(!res); -} - -void VulkanContext::DestroyCommandBuffer() { - VkCommandBuffer cmd_bufs[1] = { cmd_ }; - vkFreeCommandBuffers(device_, cmd_pool_, 1, cmd_bufs); - cmd_ = nullptr; + vkWaitForFences(device_, 1, &fence, true, UINT64_MAX); + vkResetFences(device_, 1, &fence); } void VulkanContext::DestroyCommandPool() { @@ -1473,9 +1392,13 @@ void TransitionImageLayout( image_memory_barrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; } + if (new_image_layout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL) { + image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; + } + if (new_image_layout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) { /* Make sure anything that was copying from this image has completed */ - image_memory_barrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT; + image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT|VK_ACCESS_MEMORY_READ_BIT; } if (new_image_layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) { diff --git a/ext/native/thin3d/VulkanContext.h b/ext/native/thin3d/VulkanContext.h index 7eaba87e59..fcf4e84862 100644 --- a/ext/native/thin3d/VulkanContext.h +++ b/ext/native/thin3d/VulkanContext.h @@ -64,6 +64,34 @@ struct layer_properties { std::vector extensions; }; +class VulkanDeleteList { +public: + void QueueDelete(VkImage image) { images_.push_back(image); } + void QueueDelete(VkDeviceMemory deviceMemory) { memory_.push_back(deviceMemory); } + + void Ingest(VulkanDeleteList &del) { + images_ = del.images_; + memory_ = del.memory_; + del.images_.clear(); + del.memory_.clear(); + } + + void PerformDeletes(VkDevice device) { + for (auto &mem : memory_) { + vkFreeMemory(device, mem, nullptr); + } + memory_.clear(); + for (auto &image : images_) { + vkDestroyImage(device, image, nullptr); + } + images_.clear(); + } + +private: + std::vector images_; + std::vector memory_; +}; + // VulkanContext sets up the basics necessary for rendering to a window, including framebuffers etc. // Optionally, it can create a depth buffer for you as well. class VulkanContext { @@ -77,29 +105,28 @@ public: return device_; } + template + void QueueDelete(T mem) { + globalDeleteList_.QueueDelete(mem); + } + void InitSurfaceAndQueue(HINSTANCE conn, HWND wnd); - void InitSwapchain(); + void InitSwapchain(VkCommandBuffer cmd); void InitSurfaceRenderPass(bool include_depth, bool clear); void InitFramebuffers(bool include_depth); - void InitDepthStencilBuffer(); + void InitDepthStencilBuffer(VkCommandBuffer cmd); void InitCommandPool(); - void InitCommandBuffer(); void InitObjects(HINSTANCE hInstance, HWND hWnd, bool depthPresent); void DestroyObjects(); - void BeginInitCommandBuffer(); - void SubmitInitCommandBufferSync(); - VkCommandBuffer GetInitCommandBuffer() { - return cmd_; - } + VkCommandBuffer GetInitCommandBuffer(); void DestroySurfaceRenderPass(); void DestroyFramebuffers(); void DestroySwapChain(); void DestroyDepthStencilBuffer(); void DestroyCommandPool(); - void DestroyCommandBuffer(); void DestroyDevice(); void WaitUntilQueueIdle(); @@ -147,7 +174,7 @@ public: VkResult InitDeviceExtensionProperties(layer_properties &layer_props); VkResult InitDeviceLayerProperties(); - +private: VkSemaphore acquireSemaphore; #ifdef _WIN32 @@ -162,9 +189,8 @@ public: xcb_intern_atom_reply_t *atom_wm_delete_window; #endif // _WIN32 + // TODO: Move to frame data VkCommandPool cmd_pool_; - VkCommandBuffer cmd_; // Buffer for initialization commands - bool cmdInitActive_; VkInstance instance_; VkDevice device_; @@ -190,7 +216,6 @@ public: std::vector queue_props; VkPhysicalDeviceMemoryProperties memory_properties; -private: struct swap_chain_buffer { VkImage image; VkImageView view; @@ -208,12 +233,23 @@ private: // Manages flipping command buffers for the backbuffer render pass. // It is recommended to do the same for other rendering passes. struct FrameData { + FrameData() : fence(nullptr), hasInitCommands(false), cmdInit(nullptr), cmdBuf(nullptr) {} + VkFence fence; + bool hasInitCommands; + VkCommandBuffer cmdInit; VkCommandBuffer cmdBuf; + + VulkanDeleteList deleteList; }; + FrameData frame_[2]; int curFrame_; + // At the end of the frame, this is copied into the frame's delete list, so it can be processed + // the next time the frame comes around again. + VulkanDeleteList globalDeleteList_; + // Simple loader for the WSI extension. PFN_vkGetPhysicalDeviceSurfaceSupportKHR fpGetPhysicalDeviceSurfaceSupportKHR; PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR fpGetPhysicalDeviceSurfaceCapabilitiesKHR; @@ -272,8 +308,6 @@ VkBool32 CheckLayers(const std::vector &layer_props, const std void VulkanBeginCommandBuffer(VkCommandBuffer cmd); -void vk_submit_sync(VkDevice device, VkSemaphore waitForSemaphore, VkQueue queue, VkCommandBuffer cmd); - void init_glslang(); void finalize_glslang(); diff --git a/ext/native/thin3d/thin3d_vulkan.cpp b/ext/native/thin3d/thin3d_vulkan.cpp index b421af57e4..8b55ce6bd3 100644 --- a/ext/native/thin3d/thin3d_vulkan.cpp +++ b/ext/native/thin3d/thin3d_vulkan.cpp @@ -351,6 +351,7 @@ public: info->pVertexAttributeDescriptions = attrDescs; info->vertexBindingDescriptionCount = 1; info->pVertexBindingDescriptions = bindDescs; + info->flags = 0; } bool RequiresBuffer() { @@ -512,8 +513,6 @@ private: void ApplyDynamicState(); void DirtyDynamicState(); - void BeginInitCommands(); - VulkanContext *vulkan_; // These are used to compose the pipeline cache key. @@ -554,15 +553,7 @@ private: Thin3DVKTexture *boundTextures_[MAX_BOUND_TEXTURES]; Thin3DVKSamplerState *boundSamplers_[MAX_BOUND_TEXTURES]; - // Ephemeral command buffer used for initializing textures, etc. As there can only be one in flight, can cause annoying stalls until I do something better. - VkCommandBuffer initCmd_; - bool hasInitCommands_; - VkFence initFence_; - - // TODO: Transpose this into a struct FrameObject[2]. - VkCommandBuffer cmd_; // The current one - VulkanPushBuffer *pushBuffer_[2]; int frameNum_; VulkanPushBuffer *push_; @@ -753,22 +744,6 @@ Thin3DVKContext::Thin3DVKContext(VulkanContext *vulkan) res = vkCreatePipelineLayout(device_, &pl, nullptr, &pipelineLayout_); assert(VK_SUCCESS == res); - VkCommandBufferAllocateInfo cb; - cb.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; - cb.pNext = nullptr; - cb.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; - cb.commandPool = cmdPool_; - cb.commandBufferCount = 1; - res = vkAllocateCommandBuffers(device_, &cb, &initCmd_); - assert(VK_SUCCESS == res); - hasInitCommands_ = false; - - VkFenceCreateInfo f; - f.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; - f.pNext = nullptr; - f.flags = 0; - vkCreateFence(device_, &f, nullptr, &initFence_); - VkPipelineCacheCreateInfo pc; pc.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO; pc.pNext = nullptr; @@ -811,42 +786,9 @@ void Thin3DVKContext::Begin(bool clear, uint32_t colorval, float depthVal, int s viewportDirty_ = true; } -void Thin3DVKContext::BeginInitCommands() { - assert(!hasInitCommands_); - - VkCommandBufferBeginInfo begin; - begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; - begin.pNext = nullptr; - begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; - begin.pInheritanceInfo = nullptr; - VkResult res = vkBeginCommandBuffer(initCmd_, &begin); - assert(VK_SUCCESS == res); - hasInitCommands_ = true; -} - void Thin3DVKContext::End() { // Stop collecting data in the frame data buffer. push_->End(device_); - - // IF something needs to be uploaded etc, sneak it in before we actually run the main command buffer. - if (hasInitCommands_) { - VkResult res = vkEndCommandBuffer(initCmd_); - assert(VK_SUCCESS == res); - - // Run the texture uploads etc _before_ we execute the ordinary command buffer - VkSubmitInfo submit = {}; - submit.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; - submit.pCommandBuffers = &initCmd_; - submit.commandBufferCount = 1; - res = vkQueueSubmit(queue_, 1, &submit, initFence_); - assert(VK_SUCCESS == res); - // Before we can begin, we must be sure that the command buffer is no longer in use, as we only have a single one for init - // tasks (for now). - vulkan_->WaitAndResetFence(initFence_); - hasInitCommands_ = false; - // Init cmd buffer is again available for writing. - } - vulkan_->EndSurfaceRenderPass(); frameNum_++; @@ -899,6 +841,8 @@ VkDescriptorSet Thin3DVKContext::GetOrCreateDescriptorSet() { writes[0].dstArrayElement = 0; writes[0].dstBinding = 0; writes[0].pBufferInfo = &bufferDesc; + writes[0].pImageInfo = nullptr; + writes[0].pTexelBufferView = nullptr; writes[0].descriptorCount = 1; writes[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; @@ -907,7 +851,9 @@ VkDescriptorSet Thin3DVKContext::GetOrCreateDescriptorSet() { writes[1].dstSet = descSet; writes[1].dstArrayElement = 0; writes[1].dstBinding = 1; + writes[1].pBufferInfo = nullptr; writes[1].pImageInfo = &imageDesc; + writes[1].pTexelBufferView = nullptr; writes[1].descriptorCount = 1; writes[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; @@ -1207,10 +1153,8 @@ void Thin3DVKContext::SetTextures(int start, int count, Thin3DTexture **textures boundTextures_[i] = static_cast(textures[i]); // Bind simply copies the texture to VRAM if needed. if (boundTextures_[i]->NeedsUpload()) { - if (!hasInitCommands_) { - BeginInitCommands(); - } - boundTextures_[i]->Upload(initCmd_); + VkCommandBuffer cmd = vulkan_->GetInitCommandBuffer(); + boundTextures_[i]->Upload(cmd); } } } From d7e8f8433ffc34e69d53073c9f00ddcdd5113d12 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 3 Jan 2016 12:37:05 +0100 Subject: [PATCH 012/116] Support multiple texture formats --- UI/NativeApp.cpp | 10 +- ext/native/thin3d/VulkanContext.cpp | 14 +-- ext/native/thin3d/VulkanContext.h | 8 +- ext/native/thin3d/thin3d_vulkan.cpp | 148 +++++++++------------------- 4 files changed, 67 insertions(+), 113 deletions(-) diff --git a/UI/NativeApp.cpp b/UI/NativeApp.cpp index d481fb3429..c2a80b3e32 100644 --- a/UI/NativeApp.cpp +++ b/UI/NativeApp.cpp @@ -698,13 +698,19 @@ void NativeRender(GraphicsContext *graphicsContext) { // Apply the UIContext bounds as a 2D transformation matrix. Matrix4x4 ortho; - if (GetGPUBackend() == GPUBackend::DIRECT3D9) { + switch (GetGPUBackend()) { + case GPUBackend::VULKAN: + ortho.setOrthoD3D(0.0f, xres, 0, yres, -1.0f, 1.0f); + break; + case GPUBackend::DIRECT3D9: ortho.setOrthoD3D(0.0f, xres, yres, 0.0f, -1.0f, 1.0f); Matrix4x4 translation; translation.setTranslation(Vec3(-0.5f, -0.5f, 0.0f)); ortho = translation * ortho; - } else { + break; + case GPUBackend::OPENGL: ortho.setOrtho(0.0f, xres, yres, 0.0f, -1.0f, 1.0f); + break; } ui_draw2d.SetDrawMatrix(ortho); diff --git a/ext/native/thin3d/VulkanContext.cpp b/ext/native/thin3d/VulkanContext.cpp index 0b0556dc4a..925637ab18 100644 --- a/ext/native/thin3d/VulkanContext.cpp +++ b/ext/native/thin3d/VulkanContext.cpp @@ -1094,23 +1094,25 @@ void VulkanContext::InitCommandPool() { assert(res == VK_SUCCESS); } -void VulkanTexture::Create(VulkanContext *vulkan, int w, int h) { +void VulkanTexture::Create(VulkanContext *vulkan, int w, int h, VkFormat format) { tex_width = w; tex_height = h; + format_ = format; bool U_ASSERT_ONLY pass; VkFormatProperties formatProps; - vkGetPhysicalDeviceFormatProperties(vulkan->GetPhysicalDevice(), VK_FORMAT_R8G8B8A8_UNORM, &formatProps); + vkGetPhysicalDeviceFormatProperties(vulkan->GetPhysicalDevice(), format, &formatProps); - // See if we can use a linear tiled image for a texture, if not, we will need a staging image for the texture data + // See if we can use a linear tiled image for a texture, if not, we will need a staging image for the texture data. + // Linear tiling is usually only supported for 2D non-array textures. needStaging = (!(formatProps.linearTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)) ? true : false; VkImageCreateInfo image_create_info = {}; image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; image_create_info.pNext = NULL; image_create_info.imageType = VK_IMAGE_TYPE_2D; - image_create_info.format = VK_FORMAT_R8G8B8A8_UNORM; + image_create_info.format = format; image_create_info.extent.width = tex_width; image_create_info.extent.height = tex_height; image_create_info.extent.depth = 1; @@ -1186,7 +1188,7 @@ void VulkanTexture::Unlock(VulkanContext *vulkan) { image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; image_create_info.pNext = NULL; image_create_info.imageType = VK_IMAGE_TYPE_2D; - image_create_info.format = VK_FORMAT_R8G8B8A8_UNORM; + image_create_info.format = format_; image_create_info.extent.width = tex_width; image_create_info.extent.height = tex_height; image_create_info.extent.depth = 1; @@ -1282,7 +1284,7 @@ void VulkanTexture::Unlock(VulkanContext *vulkan) { view_info.pNext = NULL; view_info.image = VK_NULL_HANDLE; view_info.viewType = VK_IMAGE_VIEW_TYPE_2D; - view_info.format = VK_FORMAT_R8G8B8A8_UNORM; + view_info.format = format_; view_info.components.r = VK_COMPONENT_SWIZZLE_R; view_info.components.g = VK_COMPONENT_SWIZZLE_G; view_info.components.b = VK_COMPONENT_SWIZZLE_B; diff --git a/ext/native/thin3d/VulkanContext.h b/ext/native/thin3d/VulkanContext.h index fcf4e84862..83c7b3315f 100644 --- a/ext/native/thin3d/VulkanContext.h +++ b/ext/native/thin3d/VulkanContext.h @@ -165,6 +165,9 @@ public: return graphics_queue_family_index_; } + const VkPhysicalDeviceProperties &GetPhysicalDeviceProperties() { + return gpu_props; + } VkResult InitGlobalExtensionProperties(); VkResult InitLayerExtensionProperties(layer_properties &layer_props); @@ -178,9 +181,7 @@ private: VkSemaphore acquireSemaphore; #ifdef _WIN32 -#define APP_NAME_STR_LEN 80 HINSTANCE connection; // hInstance - Windows Instance - char name[APP_NAME_STR_LEN]; // Name to put on the window/icon HWND window; // hWnd - window handle #else // _WIN32 xcb_connection_t *connection; @@ -291,13 +292,14 @@ public: // Always call Create, Lock, Unlock. Unlock performs the upload if necessary. - void Create(VulkanContext *vulkan, int w, int h); + void Create(VulkanContext *vulkan, int w, int h, VkFormat format); uint8_t *Lock(VulkanContext *vulkan, int *rowPitch); void Unlock(VulkanContext *vulkan); void Destroy(VulkanContext *vulkan); private: + VkFormat format_; VkImage mappableImage; VkDeviceMemory mappableMemory; VkMemoryRequirements mem_reqs; diff --git a/ext/native/thin3d/thin3d_vulkan.cpp b/ext/native/thin3d/thin3d_vulkan.cpp index 8b55ce6bd3..abf347af40 100644 --- a/ext/native/thin3d/thin3d_vulkan.cpp +++ b/ext/native/thin3d/thin3d_vulkan.cpp @@ -376,8 +376,8 @@ public: bool Link(); // Returns the binding offset. - size_t PushUBO(VulkanPushBuffer *buf) { - return buf->PushAligned(ubo_, uboSize_, 16); + size_t PushUBO(VulkanPushBuffer *buf, VulkanContext *vulkan) { + return buf->PushAligned(ubo_, uboSize_, vulkan->GetPhysicalDeviceProperties().limits.minUniformBufferOffsetAlignment); } int GetUniformLoc(const char *name); @@ -430,7 +430,6 @@ struct DescriptorSetKey { bool operator < (const DescriptorSetKey &other) const { if (texture_ < other.texture_) return true; else if (texture_ > other.texture_) return false; - if (vertexFormat_ < other.vertexFormat_) return true; else if (vertexFormat_ > other.vertexFormat_) return false; if (sampler_ < other.sampler_) return true; else if (sampler_ > other.sampler_) return false; if (frame < other.frame) return true; else if (frame > other.frame) return false; return false; @@ -554,18 +553,24 @@ private: Thin3DVKSamplerState *boundSamplers_[MAX_BOUND_TEXTURES]; VkCommandBuffer cmd_; // The current one - VulkanPushBuffer *pushBuffer_[2]; + + struct FrameData { + VulkanPushBuffer *pushBuffer; + }; + + FrameData frame_[2]; + int frameNum_; VulkanPushBuffer *push_; }; -VkFormat FormatToVulkan(T3DImageFormat fmt) { +VkFormat FormatToVulkan(T3DImageFormat fmt, int *bpp) { switch (fmt) { - case RGBA8888: return VK_FORMAT_R8G8B8A8_UNORM; - case RGBA4444: return VK_FORMAT_R4G4B4A4_UNORM_PACK16; - case D24S8: return VK_FORMAT_D24_UNORM_S8_UINT; - case D16: return VK_FORMAT_D16_UNORM; + case RGBA8888: *bpp = 32; return VK_FORMAT_R8G8B8A8_UNORM; + case RGBA4444: *bpp = 16; return VK_FORMAT_R4G4B4A4_UNORM_PACK16; + case D24S8: *bpp = 32; return VK_FORMAT_D24_UNORM_S8_UINT; + case D16: *bpp = 16; return VK_FORMAT_D16_UNORM; default: return VK_FORMAT_UNDEFINED; } } @@ -581,11 +586,11 @@ public: s.mipmapMode = desc.mipFilt == T3DTextureFilter::LINEAR ? VK_SAMPLER_MIPMAP_MODE_LINEAR : VK_SAMPLER_MIPMAP_MODE_NEAREST; s.maxLod = 0.0; // TODO: Actually support mipmaps - VkResult res = vkCreateSampler(vulkan_->Device(), &s, nullptr, &sampler_); + VkResult res = vkCreateSampler(vulkan_->GetDevice(), &s, nullptr, &sampler_); assert(VK_SUCCESS == res); } ~Thin3DVKSamplerState() { - vkDestroySampler(vulkan_->Device(), sampler_, nullptr); + vkDestroySampler(vulkan_->GetDevice(), sampler_, nullptr); } VkSampler GetSampler() { return sampler_; } @@ -614,7 +619,7 @@ enum class TextureState { class Thin3DVKTexture : public Thin3DTexture { public: - Thin3DVKTexture(VulkanContext *vulkan) : vulkan_(vulkan), state_(TextureState::UNINITIALIZED) { + Thin3DVKTexture(VulkanContext *vulkan) : vulkan_(vulkan), vkTex_(nullptr) { } Thin3DVKTexture(VulkanContext *vulkan, T3DTextureType type, T3DImageFormat format, int width, int height, int depth, int mipLevels) : vulkan_(vulkan), format_(format), mipLevels_(mipLevels) { @@ -631,36 +636,31 @@ public: width_ = width; height_ = height; depth_ = depth; - + vkTex_ = new VulkanTexture(); // We don't actually do anything here. return true; } void Destroy() { + vkTex_->Destroy(vulkan_); + delete vkTex_; } void SetImageData(int x, int y, int z, int width, int height, int depth, int level, int stride, const uint8_t *data) override; - void Upload(VkCommandBuffer cmd); - void Finalize(int zim_flags) override; void AutoGenMipmaps() {} - bool NeedsUpload(); - - VkImageView GetImageView() { return view_; } + VkImageView GetImageView() { return vkTex_->view; } private: VulkanContext *vulkan_; - VulkanImage image_; - VulkanImage staging_; - VkImageView view_; + VulkanTexture *vkTex_; int mipLevels_; T3DImageFormat format_; - TextureState state_; }; Thin3DVKContext::Thin3DVKContext(VulkanContext *vulkan) @@ -683,8 +683,6 @@ Thin3DVKContext::Thin3DVKContext(VulkanContext *vulkan) memset(boundTextures_, 0, sizeof(boundTextures_)); CreatePresets(); - vulkanMem_.Init(vulkan->GetPhysicalDevice()); - VkCommandPoolCreateInfo p; p.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; p.pNext = nullptr; @@ -695,9 +693,9 @@ Thin3DVKContext::Thin3DVKContext(VulkanContext *vulkan) VkDescriptorPoolSize dpTypes[2]; dpTypes[0].descriptorCount = 200; - dpTypes[0].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; - dpTypes[1].descriptorCount = 2; - dpTypes[1].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; + dpTypes[0].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; + dpTypes[1].descriptorCount = 200; + dpTypes[1].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; VkDescriptorPoolCreateInfo dp; dp.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; @@ -708,8 +706,9 @@ Thin3DVKContext::Thin3DVKContext(VulkanContext *vulkan) dp.poolSizeCount = ARRAY_SIZE(dpTypes); res = vkCreateDescriptorPool(device_, &dp, nullptr, &descriptorPool_); assert(VK_SUCCESS == res); - pushBuffer_[0] = new VulkanPushBuffer(device_, vulkan_, 1024 * 1024); - pushBuffer_[1] = new VulkanPushBuffer(device_, vulkan_, 1024 * 1024); + + frame_[0].pushBuffer = new VulkanPushBuffer(device_, vulkan_, 1024 * 1024); + frame_[1].pushBuffer = new VulkanPushBuffer(device_, vulkan_, 1024 * 1024); // binding 0 - uniform data // binding 1 - sampler @@ -777,17 +776,16 @@ void Thin3DVKContext::Begin(bool clear, uint32_t colorval, float depthVal, int s cmd_ = vulkan_->BeginSurfaceRenderPass(clearVal); - push_ = pushBuffer_[frameNum_ & 1]; + push_ = frame_[frameNum_ & 1].pushBuffer; // OK, we now know that nothing is reading from this frame's data pushbuffer, - // and that the command buffer can be safely reset and reused. So let's do that. push_->Begin(device_); scissorDirty_ = true; viewportDirty_ = true; } void Thin3DVKContext::End() { - // Stop collecting data in the frame data buffer. + // Stop collecting data in the frame's data pushbuffer. push_->End(device_); vulkan_->EndSurfaceRenderPass(); @@ -817,6 +815,7 @@ VkDescriptorSet Thin3DVKContext::GetOrCreateDescriptorSet() { alloc.descriptorPool = descriptorPool_; alloc.pSetLayouts = &descriptorSetLayout_; alloc.descriptorSetCount = 1; + // OutputDebugStringA("Allocated a desc set!\n"); VkResult res = vkAllocateDescriptorSets(device_, &alloc, &descSet); assert(VK_SUCCESS == res); @@ -1036,70 +1035,22 @@ Thin3DTexture *Thin3DVKContext::CreateTexture(T3DTextureType type, T3DImageForma } void Thin3DVKTexture::SetImageData(int x, int y, int z, int width, int height, int depth, int level, int stride, const uint8_t *data) { - VkFormat vulkanFormat = FormatToVulkan(format_); - - // nVidia and probably many other GPUs can texture _directly_ from a mappable buffer! But let's not rely on that, and it's not quite optimal. - // So we need to do a staging copy. We upload the data to the staging buffer immediately, then we actually do the final copy once it's used the first time - // as we need a command buffer and the architecture of Thin3D doesn't really work the way we want.. - if (!image_.IsValid()) { - staging_.Create2D(vulkan_, vulkanFormat, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, VK_IMAGE_TILING_LINEAR, VK_IMAGE_USAGE_TRANSFER_SRC_BIT, width, height); - image_.Create2D(vulkan_, vulkanFormat, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VK_IMAGE_TILING_OPTIMAL, (VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT), width, height); + int bpp; + VkFormat vulkanFormat = FormatToVulkan(format_, &bpp); + int bytesPerPixel = bpp / 8; + vkTex_->Create(vulkan_, width, height, vulkanFormat); + int rowPitch; + uint8_t *dstData = vkTex_->Lock(vulkan_, &rowPitch); + for (int y = 0; y < height; y++) { + memcpy(dstData + rowPitch * y, data + stride * y, width * bytesPerPixel); } - - VkImageViewCreateInfo iv; - iv.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; - iv.pNext = nullptr; - iv.image = image_.GetImage(); - iv.viewType = VK_IMAGE_VIEW_TYPE_2D; - iv.flags = 0; - iv.format = FormatToVulkan(format_); - iv.components.r = VK_COMPONENT_SWIZZLE_R; - iv.components.g = VK_COMPONENT_SWIZZLE_G; - iv.components.b = VK_COMPONENT_SWIZZLE_B; - iv.components.a = VK_COMPONENT_SWIZZLE_A; - iv.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - iv.subresourceRange.layerCount = 1; - iv.subresourceRange.baseArrayLayer = 0; - iv.subresourceRange.baseMipLevel = 0; - iv.subresourceRange.levelCount = 1; - VkResult res = vkCreateImageView(vulkan_->GetDevice(), &iv, nullptr, &view_); - assert(VK_SUCCESS == res); - - // TODO: Support setting only parts of the image efficiently. - staging_.SetImageData2D(vulkan_->GetDevice(), data, width, height, stride); - state_ = TextureState::STAGED; - width_ = width; - height_ = height; + vkTex_->Unlock(vulkan_); } void Thin3DVKTexture::Finalize(int zim_flags) { // TODO } -bool Thin3DVKTexture::NeedsUpload() { - return state_ == TextureState::STAGED; -} - -void Thin3DVKTexture::Upload(VkCommandBuffer cmd) { - if (state_ != TextureState::STAGED) { - return; - } - - // Before we can texture, we need to Copy and ChangeLayout. - VkImageCopy copy_region; - copy_region.srcSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }; - copy_region.srcOffset = { 0, 0, 0 }; - copy_region.dstSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }; - copy_region.dstOffset = { 0, 0, 0 }; - copy_region.extent = { (uint32_t)width_, (uint32_t)height_, 1 }; - vkCmdCopyImage(cmd, staging_.GetImage(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, image_.GetImage(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©_region); - image_.ChangeLayout(cmd, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); - // From this point on, the image can be used for texturing. - // Even before this function call (but after SetImageData), the image object can be referenced in a descriptor set. Better make sure that the image is uploaded - // before it's actually used though... - state_ = TextureState::INITIALIZED; -} - static bool isPowerOf2(int n) { return n == 1 || (n & (n - 1)) == 0; } @@ -1151,11 +1102,6 @@ Thin3DShaderSet *Thin3DVKContext::CreateShaderSet(Thin3DShader *vshader, Thin3DS void Thin3DVKContext::SetTextures(int start, int count, Thin3DTexture **textures) { for (int i = start; i < start + count; i++) { boundTextures_[i] = static_cast(textures[i]); - // Bind simply copies the texture to VRAM if needed. - if (boundTextures_[i]->NeedsUpload()) { - VkCommandBuffer cmd = vulkan_->GetInitCommandBuffer(); - boundTextures_[i]->Upload(cmd); - } } } @@ -1226,7 +1172,6 @@ void Thin3DVKContext::SetRenderState(T3DRenderState rs, uint32_t value) { } void Thin3DVKContext::Draw(T3DPrimitive prim, Thin3DShaderSet *shaderSet, Thin3DVertexFormat *format, Thin3DBuffer *vdata, int vertexCount, int offset) { - return; ApplyDynamicState(); curPrim_ = primToVK[prim]; @@ -1234,7 +1179,7 @@ void Thin3DVKContext::Draw(T3DPrimitive prim, Thin3DShaderSet *shaderSet, Thin3D curVertexFormat_ = (Thin3DVKVertexFormat *)format; Thin3DVKBuffer *vbuf = static_cast(vdata); - uint32_t ubo_offset = (uint32_t)curShaderSet_->PushUBO(push_); + uint32_t ubo_offset = (uint32_t)curShaderSet_->PushUBO(push_, vulkan_); size_t vbBindOffset = push_->Push(vbuf->GetData(), vbuf->GetSize()); VkPipeline pipeline = GetOrCreatePipeline(); @@ -1248,7 +1193,6 @@ void Thin3DVKContext::Draw(T3DPrimitive prim, Thin3DShaderSet *shaderSet, Thin3D } void Thin3DVKContext::DrawIndexed(T3DPrimitive prim, Thin3DShaderSet *shaderSet, Thin3DVertexFormat *format, Thin3DBuffer *vdata, Thin3DBuffer *idata, int vertexCount, int offset) { - return; ApplyDynamicState(); curPrim_ = primToVK[prim]; @@ -1258,7 +1202,7 @@ void Thin3DVKContext::DrawIndexed(T3DPrimitive prim, Thin3DShaderSet *shaderSet, Thin3DVKBuffer *ibuf = (Thin3DVKBuffer *)idata; Thin3DVKBuffer *vbuf = (Thin3DVKBuffer *)vdata; - uint32_t ubo_offset = (uint32_t)curShaderSet_->PushUBO(push_); + uint32_t ubo_offset = (uint32_t)curShaderSet_->PushUBO(push_, vulkan_); size_t vbBindOffset = push_->Push(vbuf->GetData(), vbuf->GetSize()); size_t ibBindOffset = push_->Push(ibuf->GetData(), ibuf->GetSize()); @@ -1283,18 +1227,18 @@ void Thin3DVKContext::DrawUP(T3DPrimitive prim, Thin3DShaderSet *shaderSet, Thin curShaderSet_ = (Thin3DVKShaderSet *)shaderSet; curVertexFormat_ = (Thin3DVKVertexFormat *)format; - uint32_t ubo_offset = (uint32_t)curShaderSet_->PushUBO(push_); size_t vbBindOffset = push_->Push(vdata, vertexCount * curVertexFormat_->stride_); + uint32_t ubo_offset = (uint32_t)curShaderSet_->PushUBO(push_, vulkan_); VkPipeline pipeline = GetOrCreatePipeline(); vkCmdBindPipeline(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); - VkDescriptorSet descSet = GetOrCreateDescriptorSet(); - vkCmdBindDescriptorSets(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout_, 0, 1, &descSet, 1, &ubo_offset); - VkBuffer buffers[1] = { push_->GetVkBuffer() }; VkDeviceSize offsets[1] = { vbBindOffset }; vkCmdBindVertexBuffers(cmd_, 0, 1, buffers, offsets); + + VkDescriptorSet descSet = GetOrCreateDescriptorSet(); + vkCmdBindDescriptorSets(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout_, 0, 1, &descSet, 1, &ubo_offset); vkCmdDraw(cmd_, vertexCount, 1, 0, 0); } From 776439d706d19bf0b26877e75066a004be3f5d8e Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 3 Jan 2016 13:27:19 +0100 Subject: [PATCH 013/116] Per-frame descriptor pools. Safe-delete more types. --- ext/native/thin3d/VulkanContext.cpp | 11 ++-- ext/native/thin3d/VulkanContext.h | 34 +++++++++--- ext/native/thin3d/thin3d_vulkan.cpp | 82 ++++++++++++++--------------- 3 files changed, 74 insertions(+), 53 deletions(-) diff --git a/ext/native/thin3d/VulkanContext.cpp b/ext/native/thin3d/VulkanContext.cpp index 925637ab18..c0af2c5f7e 100644 --- a/ext/native/thin3d/VulkanContext.cpp +++ b/ext/native/thin3d/VulkanContext.cpp @@ -67,14 +67,14 @@ VulkanContext::VulkanContext(const char *app_name, uint32_t flags) if (flags & VULKAN_FLAG_VALIDATE) { instance_layer_names.push_back("VK_LAYER_LUNARG_threading"); - instance_layer_names.push_back("VK_LAYER_LUNARG_draw_state"); + // instance_layer_names.push_back("VK_LAYER_LUNARG_draw_state"); instance_layer_names.push_back("VK_LAYER_LUNARG_image"); instance_layer_names.push_back("VK_LAYER_LUNARG_mem_tracker"); instance_layer_names.push_back("VK_LAYER_LUNARG_object_tracker"); instance_layer_names.push_back("VK_LAYER_LUNARG_param_checker"); device_layer_names.push_back("VK_LAYER_LUNARG_threading"); - device_layer_names.push_back("VK_LAYER_LUNARG_draw_state"); + // device_layer_names.push_back("VK_LAYER_LUNARG_draw_state"); device_layer_names.push_back("VK_LAYER_LUNARG_image"); device_layer_names.push_back("VK_LAYER_LUNARG_mem_tracker"); device_layer_names.push_back("VK_LAYER_LUNARG_object_tracker"); @@ -1302,9 +1302,10 @@ void VulkanTexture::Unlock(VulkanContext *vulkan) { } void VulkanTexture::Destroy(VulkanContext *vulkan) { - vkDestroyImageView(vulkan->GetDevice(), view, NULL); - vkDestroyImage(vulkan->GetDevice(), image, NULL); - vkFreeMemory(vulkan->GetDevice(), mem, NULL); + vulkan->QueueDelete(view); + vulkan->QueueDelete(image); + vulkan->QueueDelete(mem); + view = NULL; image = NULL; mem = NULL; diff --git a/ext/native/thin3d/VulkanContext.h b/ext/native/thin3d/VulkanContext.h index 83c7b3315f..bb412c5ea5 100644 --- a/ext/native/thin3d/VulkanContext.h +++ b/ext/native/thin3d/VulkanContext.h @@ -64,31 +64,51 @@ struct layer_properties { std::vector extensions; }; +// This is a bit repetitive... class VulkanDeleteList { public: + void QueueDelete(VkBuffer buffer) { buffers_.push_back(buffer); } + void QueueDelete(VkBufferView bufferView) { bufferViews_.push_back(bufferView); } void QueueDelete(VkImage image) { images_.push_back(image); } + void QueueDelete(VkImageView imageView) { imageViews_.push_back(imageView); } void QueueDelete(VkDeviceMemory deviceMemory) { memory_.push_back(deviceMemory); } void Ingest(VulkanDeleteList &del) { - images_ = del.images_; - memory_ = del.memory_; - del.images_.clear(); - del.memory_.clear(); + buffers_ = std::move(del.buffers_); + bufferViews_ = std::move(del.bufferViews_); + images_ = std::move(del.images_); + imageViews_ = std::move(del.imageViews_); + memory_ = std::move(del.memory_); } void PerformDeletes(VkDevice device) { - for (auto &mem : memory_) { - vkFreeMemory(device, mem, nullptr); + for (auto &buf : buffers_) { + vkDestroyBuffer(device, buf, nullptr); } - memory_.clear(); + buffers_.clear(); + for (auto &bufView : bufferViews_) { + vkDestroyBufferView(device, bufView, nullptr); + } + bufferViews_.clear(); for (auto &image : images_) { vkDestroyImage(device, image, nullptr); } images_.clear(); + for (auto &imageView : imageViews_) { + vkDestroyImageView(device, imageView, nullptr); + } + imageViews_.clear(); + for (auto &mem : memory_) { + vkFreeMemory(device, mem, nullptr); + } + memory_.clear(); } private: + std::vector buffers_; + std::vector bufferViews_; std::vector images_; + std::vector imageViews_; std::vector memory_; }; diff --git a/ext/native/thin3d/thin3d_vulkan.cpp b/ext/native/thin3d/thin3d_vulkan.cpp index abf347af40..5e35eddcb8 100644 --- a/ext/native/thin3d/thin3d_vulkan.cpp +++ b/ext/native/thin3d/thin3d_vulkan.cpp @@ -141,9 +141,9 @@ public: assert(VK_SUCCESS == res); } - void Destroy(VkDevice device) { - vkDestroyBuffer(device, buffer_, nullptr); - vkFreeMemory(device, deviceMemory_, nullptr); + void Destroy(VulkanContext *vulkan) { + vulkan->QueueDelete(buffer_); + vulkan->QueueDelete(deviceMemory_); } void Reset() { offset_ = 0; } @@ -424,14 +424,13 @@ class Thin3DVKSamplerState; struct DescriptorSetKey { Thin3DVKTexture *texture_; - Thin3DVertexFormat *vertexFormat_; Thin3DVKSamplerState *sampler_; - int frame; // 0 or 1 + VulkanPushBuffer *buffer_; bool operator < (const DescriptorSetKey &other) const { if (texture_ < other.texture_) return true; else if (texture_ > other.texture_) return false; if (sampler_ < other.sampler_) return true; else if (sampler_ > other.sampler_) return false; - if (frame < other.frame) return true; else if (frame > other.frame) return false; + if (buffer_ < other.buffer_) return true; else if (buffer_ > other.buffer_) return false; return false; } }; @@ -525,11 +524,6 @@ private: // We keep a pipeline state cache. std::map pipelines_; - // Also, a descriptor set state cache. We precompute a descriptor set for every active texture. - // The only difference between descriptor sets will be their textures. And input bindings? Hm - std::map descSets_; - - VkDescriptorPool descriptorPool_; VkDescriptorSetLayout descriptorSetLayout_; VkPipelineLayout pipelineLayout_; VkPipelineCache pipelineCache_; @@ -556,6 +550,11 @@ private: struct FrameData { VulkanPushBuffer *pushBuffer; + + // Per-frame descriptor set cache. As it's per frame and reset every frame, we don't need to + // worry about invalidating descriptors pointing to deleted textures. + std::map descSets_; + VkDescriptorPool descriptorPool; }; FrameData frame_[2]; @@ -564,7 +563,6 @@ private: VulkanPushBuffer *push_; }; - VkFormat FormatToVulkan(T3DImageFormat fmt, int *bpp) { switch (fmt) { case RGBA8888: *bpp = 32; return VK_FORMAT_R8G8B8A8_UNORM; @@ -621,6 +619,7 @@ class Thin3DVKTexture : public Thin3DTexture { public: Thin3DVKTexture(VulkanContext *vulkan) : vulkan_(vulkan), vkTex_(nullptr) { } + Thin3DVKTexture(VulkanContext *vulkan, T3DTextureType type, T3DImageFormat format, int width, int height, int depth, int mipLevels) : vulkan_(vulkan), format_(format), mipLevels_(mipLevels) { Create(type, format, width, height, depth, mipLevels); @@ -631,6 +630,7 @@ public: } bool Create(T3DTextureType type, T3DImageFormat format, int width, int height, int depth, int mipLevels) override { + ILOG("texture created: %p", this); format_ = format; mipLevels_ = mipLevels; width_ = width; @@ -641,20 +641,19 @@ public: return true; } - void Destroy() { - vkTex_->Destroy(vulkan_); - delete vkTex_; - } - void SetImageData(int x, int y, int z, int width, int height, int depth, int level, int stride, const uint8_t *data) override; - void Finalize(int zim_flags) override; - void AutoGenMipmaps() {} VkImageView GetImageView() { return vkTex_->view; } private: + void Destroy() { + ILOG("texture destroyed: %p", this); + vkTex_->Destroy(vulkan_); + delete vkTex_; + } + VulkanContext *vulkan_; VulkanTexture *vkTex_; @@ -700,11 +699,13 @@ Thin3DVKContext::Thin3DVKContext(VulkanContext *vulkan) VkDescriptorPoolCreateInfo dp; dp.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; dp.pNext = nullptr; - dp.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT; // We want to individually alloc and free descriptor sets. (do we? or one per "frame"?) - dp.maxSets = 200; // One set for every texture available... sigh + dp.flags = 0; // Don't want to mess around with individually freeing these, let's go dynamic each frame. + dp.maxSets = 200; // 200 textures per frame should be enough for the UI... dp.pPoolSizes = dpTypes; dp.poolSizeCount = ARRAY_SIZE(dpTypes); - res = vkCreateDescriptorPool(device_, &dp, nullptr, &descriptorPool_); + res = vkCreateDescriptorPool(device_, &dp, nullptr, &frame_[0].descriptorPool); + assert(VK_SUCCESS == res); + res = vkCreateDescriptorPool(device_, &dp, nullptr, &frame_[1].descriptorPool); assert(VK_SUCCESS == res); frame_[0].pushBuffer = new VulkanPushBuffer(device_, vulkan_, 1024 * 1024); @@ -759,7 +760,9 @@ Thin3DVKContext::~Thin3DVKContext() { } vkDestroyCommandPool(device_, cmdPool_, nullptr); // This also destroys all descriptor sets. - vkDestroyDescriptorPool(device_, descriptorPool_, nullptr); + for (int i = 0; i < 2; i++) { + vkDestroyDescriptorPool(device_, frame_[i].descriptorPool, nullptr); + } vkDestroyDescriptorSetLayout(device_, descriptorSetLayout_, nullptr); vkDestroyPipelineLayout(device_, pipelineLayout_, nullptr); vkDestroyPipelineCache(device_, pipelineCache_, nullptr); @@ -776,10 +779,16 @@ void Thin3DVKContext::Begin(bool clear, uint32_t colorval, float depthVal, int s cmd_ = vulkan_->BeginSurfaceRenderPass(clearVal); - push_ = frame_[frameNum_ & 1].pushBuffer; + FrameData *frame = &frame_[frameNum_ & 1]; + push_ = frame->pushBuffer; // OK, we now know that nothing is reading from this frame's data pushbuffer, push_->Begin(device_); + + frame->descSets_.clear(); + VkResult result = vkResetDescriptorPool(device_, frame->descriptorPool, 0); + assert(result == VK_SUCCESS); + scissorDirty_ = true; viewportDirty_ = true; } @@ -798,13 +807,15 @@ void Thin3DVKContext::End() { VkDescriptorSet Thin3DVKContext::GetOrCreateDescriptorSet() { DescriptorSetKey key; + + FrameData *frame = &frame_[frameNum_ & 1]; + key.texture_ = boundTextures_[0]; key.sampler_ = boundSamplers_[0]; - key.vertexFormat_ = nullptr; - key.frame = frameNum_ & 1; + key.buffer_ = push_; // Not currently strictly necessary as a single frame always uses a specific push buffer - auto iter = descSets_.find(key); - if (iter != descSets_.end()) { + auto iter = frame->descSets_.find(key); + if (iter != frame->descSets_.end()) { return iter->second; } @@ -812,7 +823,7 @@ VkDescriptorSet Thin3DVKContext::GetOrCreateDescriptorSet() { VkDescriptorSetAllocateInfo alloc; alloc.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; alloc.pNext = nullptr; - alloc.descriptorPool = descriptorPool_; + alloc.descriptorPool = frame->descriptorPool; alloc.pSetLayouts = &descriptorSetLayout_; alloc.descriptorSetCount = 1; // OutputDebugStringA("Allocated a desc set!\n"); @@ -858,7 +869,7 @@ VkDescriptorSet Thin3DVKContext::GetOrCreateDescriptorSet() { vkUpdateDescriptorSets(device_, 2, writes, 0, nullptr); - descSets_[key] = descSet; + frame->descSets_[key] = descSet; return descSet; } @@ -1138,17 +1149,6 @@ int Thin3DVKShaderSet::GetUniformLoc(const char *name) { return 0; } - /* - auto iter = uniforms_.find(name); - if (iter != uniforms_.end()) { - loc = iter->second.loc_; - } else { - loc = glGetUniformLocation(program_, name); - UniformInfo info; - info.loc_ = loc; - uniforms_[name] = info; - }*/ - return loc; } From 56e358aa24c2063b1a4a3199a37124c0d93d0d82 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 3 Jan 2016 14:00:05 +0100 Subject: [PATCH 014/116] Show Vulkan information in system information. --- UI/DevScreens.cpp | 8 +++++ UI/MiscScreens.cpp | 2 +- ext/native/thin3d/VulkanContext.cpp | 25 +++++++++++++++- ext/native/thin3d/VulkanContext.h | 6 ++++ ext/native/thin3d/thin3d_vulkan.cpp | 46 +++++++++++++++++++++++++---- 5 files changed, 79 insertions(+), 8 deletions(-) diff --git a/UI/DevScreens.cpp b/UI/DevScreens.cpp index 38afafa231..e25c8ad982 100644 --- a/UI/DevScreens.cpp +++ b/UI/DevScreens.cpp @@ -466,6 +466,14 @@ void SystemInfoScreen::CreateViews() { eglExtensions->Add(new TextView(exts[i]))->SetFocusable(true); } } + } else if (g_Config.iGPUBackend == GPU_BACKEND_VULKAN) { + tabHolder->AddTab("Vulkan Features", oglExtensionsScroll); + + oglExtensions->Add(new ItemHeader("Vulkan Features")); + std::vector features = thin3d->GetFeatureList(); + for (auto &feature : features) { + oglExtensions->Add(new TextView(feature))->SetFocusable(true); + } } } diff --git a/UI/MiscScreens.cpp b/UI/MiscScreens.cpp index 2ed4aa9f05..7925287eda 100644 --- a/UI/MiscScreens.cpp +++ b/UI/MiscScreens.cpp @@ -383,7 +383,7 @@ void LogoScreen::Next() { void LogoScreen::update(InputState &input_state) { UIScreen::update(input_state); frames_++; - if (frames_ > 1800000 || input_state.pointer_down[0]) { + if (frames_ > 180 || input_state.pointer_down[0]) { Next(); } } diff --git a/ext/native/thin3d/VulkanContext.cpp b/ext/native/thin3d/VulkanContext.cpp index c0af2c5f7e..809a0f9abd 100644 --- a/ext/native/thin3d/VulkanContext.cpp +++ b/ext/native/thin3d/VulkanContext.cpp @@ -65,6 +65,7 @@ VulkanContext::VulkanContext(const char *app_name, uint32_t flags) instance_extension_names.push_back(VK_KHR_WIN32_SURFACE_EXTENSION_NAME); device_extension_names.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME); + // DrawState validation is broken, hangs on vkResetDescriptorPool. if (flags & VULKAN_FLAG_VALIDATE) { instance_layer_names.push_back("VK_LAYER_LUNARG_threading"); // instance_layer_names.push_back("VK_LAYER_LUNARG_draw_state"); @@ -588,6 +589,28 @@ VkResult VulkanContext::CreateDevice(int physical_device) { queue_info.queueCount = 1; queue_info.pQueuePriorities = queue_priorities; + + // Optional features + vkGetPhysicalDeviceFeatures(physical_devices_[0], &featuresAvailable_); + memset(&featuresEnabled_, 0, sizeof(featuresEnabled_)); + + // Enable a few safe ones if they are available. + if (featuresAvailable_.dualSrcBlend) { + featuresEnabled_.dualSrcBlend = true; + } + if (featuresAvailable_.largePoints) { + featuresEnabled_.largePoints = true; + } + if (featuresAvailable_.wideLines) { + featuresEnabled_.wideLines = true; + } + if (featuresAvailable_.geometryShader) { + featuresEnabled_.geometryShader = true; + } + if (featuresAvailable_.logicOp) { + featuresEnabled_.logicOp = true; + } + VkDeviceCreateInfo device_info = {}; device_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; device_info.pNext = NULL; @@ -599,7 +622,7 @@ VkResult VulkanContext::CreateDevice(int physical_device) { device_info.enabledExtensionCount = (uint32_t)device_extension_names.size(); device_info.ppEnabledExtensionNames = device_info.enabledExtensionCount ? device_extension_names.data() : NULL; - device_info.pEnabledFeatures = NULL; + device_info.pEnabledFeatures = &featuresEnabled_; res = vkCreateDevice(physical_devices_[0], &device_info, NULL, &device_); assert(res == VK_SUCCESS); diff --git a/ext/native/thin3d/VulkanContext.h b/ext/native/thin3d/VulkanContext.h index bb412c5ea5..f43ba208d6 100644 --- a/ext/native/thin3d/VulkanContext.h +++ b/ext/native/thin3d/VulkanContext.h @@ -197,6 +197,9 @@ public: VkResult InitDeviceExtensionProperties(layer_properties &layer_props); VkResult InitDeviceLayerProperties(); + const VkPhysicalDeviceFeatures &GetFeaturesAvailable() const { return featuresAvailable_; } + const VkPhysicalDeviceFeatures &GetFeaturesEnabled() const { return featuresEnabled_; } + private: VkSemaphore acquireSemaphore; @@ -296,6 +299,9 @@ private: VkRenderPass surface_render_pass_; uint32_t current_buffer; uint32_t queue_count; + + VkPhysicalDeviceFeatures featuresAvailable_; + VkPhysicalDeviceFeatures featuresEnabled_; }; // Wrapper around what you need to use a texture. diff --git a/ext/native/thin3d/thin3d_vulkan.cpp b/ext/native/thin3d/thin3d_vulkan.cpp index 5e35eddcb8..80dc0f4485 100644 --- a/ext/native/thin3d/thin3d_vulkan.cpp +++ b/ext/native/thin3d/thin3d_vulkan.cpp @@ -25,6 +25,7 @@ #include "base/logging.h" #include "base/display.h" +#include "base/stringutil.h" #include "image/zim_load.h" #include "math/lin/matrix4x4.h" #include "math/dataconv.h" @@ -493,13 +494,16 @@ public: std::string GetInfoString(T3DInfo info) const override { // TODO: Make these actually query the right information switch (info) { - case APINAME: - return "Vulkan"; - case VENDORSTRING: return "N/A"; - case VENDOR: return "N/A"; - case RENDERER: return "N/A"; + case APINAME: return "Vulkan"; + case VENDORSTRING: return vulkan_->GetPhysicalDeviceProperties().deviceName; + case VENDOR: return StringFromFormat("%08x", vulkan_->GetPhysicalDeviceProperties().vendorID); + case RENDERER: return StringFromFormat("%08x", vulkan_->GetPhysicalDeviceProperties().driverVersion); case SHADELANGVERSION: return "N/A";; - case APIVERSION: return "N/A"; + case APIVERSION: + { + uint32_t ver = vulkan_->GetPhysicalDeviceProperties().apiVersion; + return StringFromFormat("%d.%d.%d", ver >> 22, (ver >> 12) & 0x3ff, ver & 0xfff); + } default: return "?"; } } @@ -507,6 +511,8 @@ public: VkPipeline GetOrCreatePipeline(); VkDescriptorSet GetOrCreateDescriptorSet(); + std::vector GetFeatureList() override; + private: void ApplyDynamicState(); void DirtyDynamicState(); @@ -1261,3 +1267,31 @@ void Thin3DVKContext::Clear(int mask, uint32_t colorval, float depthVal, int ste Thin3DContext *T3DCreateVulkanContext(VulkanContext *vulkan) { return new Thin3DVKContext(vulkan); } + +void AddFeature(std::vector &features, const char *name, VkBool32 available, VkBool32 enabled) { + char buf[512]; + snprintf(buf, sizeof(buf), "%s: Available: %d Enabled: %d", name, (int)available, (int)enabled); + features.push_back(buf); +} + +std::vector Thin3DVKContext::GetFeatureList() { + const VkPhysicalDeviceFeatures &available = vulkan_->GetFeaturesAvailable(); + const VkPhysicalDeviceFeatures &enabled = vulkan_->GetFeaturesEnabled(); + std::vector features; + AddFeature(features, "dualSrcBlend", available.dualSrcBlend, enabled.dualSrcBlend); + AddFeature(features, "logicOp", available.logicOp, enabled.logicOp); + AddFeature(features, "geometryShader", available.geometryShader, enabled.geometryShader); + AddFeature(features, "depthBounds", available.depthBounds, enabled.depthBounds); + AddFeature(features, "depthClamp", available.depthClamp, enabled.depthClamp); + AddFeature(features, "fillModeNonSolid", available.fillModeNonSolid, enabled.fillModeNonSolid); + AddFeature(features, "largePoints", available.largePoints, enabled.largePoints); + AddFeature(features, "wideLines", available.wideLines, enabled.wideLines); + AddFeature(features, "pipelineStatisticsQuery", available.pipelineStatisticsQuery, enabled.pipelineStatisticsQuery); + AddFeature(features, "samplerAnisotropy", available.samplerAnisotropy, enabled.samplerAnisotropy); + AddFeature(features, "textureCompressionBC", available.textureCompressionBC, enabled.textureCompressionBC); + AddFeature(features, "textureCompressionETC2", available.textureCompressionETC2, enabled.textureCompressionETC2); + AddFeature(features, "textureCompressionASTC_LDR", available.textureCompressionASTC_LDR, enabled.textureCompressionASTC_LDR); + AddFeature(features, "shaderClipDistance", available.shaderClipDistance, enabled.shaderClipDistance); + AddFeature(features, "shaderCullDistance", available.shaderCullDistance, enabled.shaderCullDistance); + return features; +} From 5216a245901e221ee0e41f065412b5cd1c68071b Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 3 Jan 2016 18:31:03 +0100 Subject: [PATCH 015/116] Back to work on the PSP renderer --- GPU/GPU.cpp | 2 +- GPU/Vulkan/DrawEngineVulkan.cpp | 130 ++++++++++++++++++- GPU/Vulkan/DrawEngineVulkan.h | 58 ++++++--- GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp | 39 +----- GPU/Vulkan/GPU_Vulkan.cpp | 2 +- GPU/Vulkan/GPU_Vulkan.h | 2 +- GPU/Vulkan/PipelineManagerVulkan.cpp | 72 +++++++--- GPU/Vulkan/PipelineManagerVulkan.h | 39 ++++-- GPU/Vulkan/ShaderManagerVulkan.h | 19 ++- GPU/Vulkan/VertexShaderGeneratorVulkan.cpp | 2 +- ext/native/thin3d/VulkanContext.cpp | 13 ++ ext/native/thin3d/VulkanContext.h | 100 ++++++++++++++ ext/native/thin3d/thin3d_vulkan.cpp | 108 +-------------- 13 files changed, 385 insertions(+), 201 deletions(-) diff --git a/GPU/GPU.cpp b/GPU/GPU.cpp index 36e9564291..5088b1108c 100644 --- a/GPU/GPU.cpp +++ b/GPU/GPU.cpp @@ -59,7 +59,7 @@ bool GPU_Init(GraphicsContext *ctx) { #endif break; case GPU_VULKAN: - SetGPU(new GPU_Vulkan()); + SetGPU(new GPU_Vulkan(nullptr)); break; } diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index 3facb84fab..e5e7e4a966 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -18,6 +18,8 @@ // Official git repository and contact information can be found at // https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. +#include + #include "base/logging.h" #include "base/timeutil.h" @@ -59,8 +61,10 @@ enum { TRANSFORMED_VERTEX_BUFFER_SIZE = VERTEX_BUFFER_MAX * sizeof(TransformedVertex) }; -DrawEngineVulkan::DrawEngineVulkan() - : decodedVerts_(0), +DrawEngineVulkan::DrawEngineVulkan(VulkanContext *vulkan) + : + vulkan_(vulkan), + decodedVerts_(0), prevPrim_(GE_PRIM_INVALID), lastVType_(-1), pipelineManager_(nullptr), @@ -71,7 +75,8 @@ DrawEngineVulkan::DrawEngineVulkan() decodeCounter_(0), dcid_(0), fboTexNeedBind_(false), - fboTexBound_(false) { + fboTexBound_(false), + curFrame_(0) { memset(&decOptions_, 0, sizeof(decOptions_)); decOptions_.expandAllUVtoFloat = true; @@ -88,6 +93,82 @@ DrawEngineVulkan::DrawEngineVulkan() transformedExpanded = (TransformedVertex *)AllocateMemoryPages(3 * TRANSFORMED_VERTEX_BUFFER_SIZE); indexGen.Setup(decIndex); + + VkDescriptorSetLayoutBinding bindings[5]; + bindings[0].descriptorCount = 1; + bindings[0].pImmutableSamplers = nullptr; + bindings[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + bindings[0].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; + bindings[0].binding = 1; + bindings[1].descriptorCount = 1; + bindings[1].pImmutableSamplers = nullptr; + bindings[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + bindings[1].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; + bindings[1].binding = 1; + bindings[2].descriptorCount = 1; + bindings[2].pImmutableSamplers = nullptr; + bindings[2].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; + bindings[2].stageFlags = VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT; + bindings[2].binding = 2; + bindings[3].descriptorCount = 1; + bindings[3].pImmutableSamplers = nullptr; + bindings[3].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; + bindings[3].stageFlags = VK_SHADER_STAGE_VERTEX_BIT; + bindings[3].binding = 3; + bindings[4].descriptorCount = 1; + bindings[4].pImmutableSamplers = nullptr; + bindings[4].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; + bindings[4].stageFlags = VK_SHADER_STAGE_VERTEX_BIT; + bindings[4].binding = 3; + + VkDevice device = vulkan_->GetDevice(); + + VkDescriptorSetLayoutCreateInfo dsl; + dsl.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; + dsl.pNext = nullptr; + dsl.bindingCount = 5; + dsl.pBindings = bindings; + VkResult res = vkCreateDescriptorSetLayout(device, &dsl, nullptr, &descriptorSetLayout_); + + VkDescriptorPoolSize dpTypes[2]; + dpTypes[0].descriptorCount = 200; + dpTypes[0].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; + dpTypes[1].descriptorCount = 200; + dpTypes[1].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + + VkDescriptorPoolCreateInfo dp; + dp.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; + dp.pNext = nullptr; + dp.flags = 0; // Don't want to mess around with individually freeing these, let's go dynamic each frame. + dp.maxSets = 200; // 200 textures per frame should be enough for the UI... + dp.pPoolSizes = dpTypes; + dp.poolSizeCount = ARRAY_SIZE(dpTypes); + res = vkCreateDescriptorPool(device, &dp, nullptr, &frame_[0].descPool); + assert(VK_SUCCESS == res); + res = vkCreateDescriptorPool(device, &dp, nullptr, &frame_[1].descPool); + assert(VK_SUCCESS == res); + + // We are going to use one-shot descriptors in the initial implementation. Might look into caching them + // if creating and updating them turns out to be expensive. + for (int i = 0; i < 2; i++) { + VkResult res = vkCreateDescriptorPool(vulkan_->GetDevice(), &dp, nullptr, &frame_[i].descPool); + assert(VK_SUCCESS == res); + } + + VkPipelineLayoutCreateInfo pl; + pl.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; + pl.pNext = nullptr; + pl.pPushConstantRanges = nullptr; + pl.pushConstantRangeCount = 0; + pl.setLayoutCount = 1; + pl.pSetLayouts = &descriptorSetLayout_; + res = vkCreatePipelineLayout(device, &pl, nullptr, &pipelineLayout_); + + assert(VK_SUCCESS == res); +} + +void DrawEngineVulkan::EndFrame() { + curFrame_++; } DrawEngineVulkan::~DrawEngineVulkan() { @@ -282,12 +363,32 @@ inline u32 ComputeMiniHashRange(const void *ptr, size_t sz) { } } +/* +struct DescriptorSetKey { + void *texture_; + void *secondaryTexture_; + + bool operator < (const DescriptorSetKey &other) const { + if (texture_ < other.texture_) return true; else if (texture_ > other.texture_) return false; + if (secondaryTexture_ < other.secondaryTexture_) return true; else if (secondaryTexture_ > other.secondaryTexture_) return false; + return false; + } +}; +*/ + +VkDescriptorSet DrawEngineVulkan::GetDescriptorSet() { + return nullptr; +} + // The inline wrapper in the header checks for numDrawCalls == 0 void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { gpuStats.numFlushes++; + FrameData *frame = &frame_[curFrame_ & 1]; + // This is not done on every drawcall, we should collect vertex data // until critical state changes. That's when we draw (flush). + VkDescriptorSet ds = GetDescriptorSet(); GEPrimitiveType prim = prevPrim_; // ApplyDrawState(prim); @@ -296,6 +397,13 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { VulkanFragmentShader *fshader; shaderManager_->GetShaders(prim, lastVType_, &vshader, &fshader); + uint32_t baseUBOOffset = 0; + uint32_t lightUBOOffset = 0; + uint32_t boneUBOOffset = 0; + + uint32_t ibOffset = 0; + uint32_t vbOffset = 0; + if (vshader->UseHWTransform()) { int vertexCount = 0; int maxIndex = 0; @@ -319,12 +427,20 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { gstate_c.vertexFullAlpha = gstate_c.vertexFullAlpha && ((hasColor && (gstate.materialupdate & 1)) || gstate.getMaterialAmbientA() == 255) && (!gstate.isLightingEnabled() || gstate.getAmbientA() == 255); } - VkBuffer buf[1] = {}; - VkDeviceSize offsets[1] = { 0 }; + VkBuffer buf[1] = {frame->pushData->GetVkBuffer()}; + uint32_t dynamicUBOOffsets[3] = { + baseUBOOffset, lightUBOOffset, boneUBOOffset, + }; + vkCmdBindDescriptorSets(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout_, 0, 1, &ds, 3, dynamicUBOOffsets); + + ibOffset = (uint32_t)(frame->pushData->Push(decIndex, 2 * indexGen.VertexCount())); + // vbOffset = frame->pushData->Push(decoded, ) + + VkDeviceSize offsets[1] = { vbOffset }; if (useElements) { // TODO: Avoid rebinding if the vertex size stays the same by using the offset arguments vkCmdBindVertexBuffers(cmd_, 0, 1, buf, offsets); - vkCmdBindIndexBuffer(cmd_, buf[0], 0, VK_INDEX_TYPE_UINT16); + vkCmdBindIndexBuffer(cmd_, buf[0], ibOffset, VK_INDEX_TYPE_UINT16); vkCmdDrawIndexed(cmd_, maxIndex + 1, 1, 0, 0, 0); } else { vkCmdBindVertexBuffers(cmd_, 0, 1, buf, offsets); @@ -383,7 +499,7 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { } } else if (result.action == SW_CLEAR) { // TODO: Support clearing only color and not alpha, or vice versa. This is not supported (probably for good reason) by vkCmdClearColorAttachment - // so we will have to simply draw a rectangle instead. Accordingly, + // so we will have to simply draw a rectangle instead. int mask = gstate.isClearModeColorMask() ? 1 : 0; if (gstate.isClearModeAlphaMask()) mask |= 2; diff --git a/GPU/Vulkan/DrawEngineVulkan.h b/GPU/Vulkan/DrawEngineVulkan.h index a484700443..ebb81dadc9 100644 --- a/GPU/Vulkan/DrawEngineVulkan.h +++ b/GPU/Vulkan/DrawEngineVulkan.h @@ -17,25 +17,18 @@ #pragma once -#include "GPU/Common/DrawEngineCommon.h" -// Copyright (c) 2012- PPSSPP Project. +// The Descriptor Set used for the majority of PSP rendering looks like this: +// +// * binding 0: Texture/Sampler (the PSP texture) +// * binding 1: Secondary texture sampler for shader blending or depal palettes +// * binding 2: Base Uniform Buffer (includes fragment state) +// * binding 3: Light uniform buffer +// * binding 4: Bone uniform buffer +// +// All shaders conform to this layout, so they are all compatible with the same descriptor set. +// The format of the various uniform buffers may vary though - vertex shaders that don't skin +// won't get any bone data, etc. -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, version 2.0 or later versions. - -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License 2.0 for more details. - -// A copy of the GPL 2.0 should have been included with the program. -// If not, see http://www.gnu.org/licenses/ - -// Official git repository and contact information can be found at -// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. - -#pragma once #include @@ -66,7 +59,7 @@ typedef u32 ReliableHashType; // Handles transform, lighting and drawing. class DrawEngineVulkan : public DrawEngineCommon { public: - DrawEngineVulkan(); + DrawEngineVulkan(VulkanContext *vulkan); virtual ~DrawEngineVulkan(); void SubmitPrim(void *verts, void *inds, GEPrimitiveType prim, int vertexCount, u32 vertType, int *bytesRead); @@ -143,13 +136,36 @@ public: cmd_ = cmd; } + VkPipelineLayout GetPipelineLayout() const { + return pipelineLayout_; + } + + void EndFrame(); + private: void DecodeVerts(); void DecodeVertsStep(); void DoFlush(VkCommandBuffer cmd); + VkDescriptorSet GetDescriptorSet(); + VertexDecoder *GetVertexDecoder(u32 vtype); + VulkanContext *vulkan_; + + // We use a single descriptor set layout for all PSP draws. + VkDescriptorSetLayout descriptorSetLayout_; + VkPipelineLayout pipelineLayout_; + + // We alternate between these. + struct FrameData { + VkDescriptorPool descPool; + VulkanPushBuffer *pushData; + }; + + int curFrame_; + FrameData frame_[2]; + // Defer all vertex decoding to a "Flush" (except when software skinning) struct DeferredDrawCall { void *verts; @@ -162,6 +178,10 @@ private: u16 indexUpperBound; }; + // This is always set to the current main command buffer of the VulkanContext. + // In the future, we may support flushing mid-frame and more fine grained command buffer usage, + // but for now, let's just submit a whole frame at a time. This is not compatible with some games + // that do mid frame read-backs. VkCommandBuffer cmd_; // Vertex collector state diff --git a/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp b/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp index 8a1a5d1e60..7be678c0b4 100644 --- a/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp +++ b/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp @@ -35,6 +35,7 @@ #include "GPU/Common/ShaderId.h" #include "GPU/Vulkan/FragmentShaderGeneratorVulkan.h" #include "GPU/Vulkan/FramebufferVulkan.h" +#include "GPU/Vulkan/ShaderManagerVulkan.h" #include "GPU/Vulkan/PipelineManagerVulkan.h" #include "GPU/ge_constants.h" @@ -42,31 +43,6 @@ #define WRITE p+=sprintf -// #define DEBUG_SHADER - -// TODO: Which binding number? -static const char *vulkan_uniform_buffer = R"( -layout(set=0, binding=3) uniform constants { - // Blend function replacement - vec3 u_blendFixA; - vec3 u_blendFixB; - - // Texture clamp emulation - vec4 u_texclamp; - vec2 u_texclampoff; - - // Alpha/Color test emulation - vec4 u_alphacolorref; - ivec4 u_alphacolormask; - - // Stencil replacement - float u_stencilReplaceValue; - vec3 u_texenv; - - vec3 u_fogcolor; -)"; - - // Missing: Z depth range bool GenerateVulkanGLSLFragmentShader(const ShaderID &id, char *buffer) { char *p = buffer; @@ -116,15 +92,14 @@ bool GenerateVulkanGLSLFragmentShader(const ShaderID &id, char *buffer) { const char *shading = doFlatShading ? "flat" : ""; - WRITE(p, "%s\n", vulkan_uniform_buffer); - + WRITE(p, "layout (binding = 2) uniform %s\n", ub_baseStr); if (doTexture) { - WRITE(p, "layout (binding = 1) uniform sampler2D tex;\n"); + WRITE(p, "layout (binding = 0) uniform sampler2D tex;\n"); } if (!isModeClear && replaceBlend > REPLACE_BLEND_STANDARD) { if (replaceBlend == REPLACE_BLEND_COPY_FBO) { - WRITE(p, "layout (binding = 2) uniform sampler2D fbotex;\n"); + WRITE(p, "layout (binding = 1) uniform sampler2D fbotex;\n"); } } @@ -132,13 +107,13 @@ bool GenerateVulkanGLSLFragmentShader(const ShaderID &id, char *buffer) { if (lmode) WRITE(p, "layout (location = 2) %s in vec3 v_color1;\n", shading); if (enableFog) { - WRITE(p, "layout (location = 3) %s float v_fogdepth;\n", highpFog ? "highp" : "mediump"); + WRITE(p, "layout (location = 3) %s in float v_fogdepth;\n", highpFog ? "highp" : "mediump"); } if (doTexture) { if (doTextureProjection) - WRITE(p, "layout (location = 0) %s vec3 v_texcoord;\n", highpTexcoord ? "highp" : "mediump"); + WRITE(p, "layout (location = 0) %s in vec3 v_texcoord;\n", highpTexcoord ? "highp" : "mediump"); else - WRITE(p, "layout (location = 0) %s vec2 v_texcoord;\n", highpTexcoord ? "highp" : "mediump"); + WRITE(p, "layout (location = 0) %s in vec2 v_texcoord;\n", highpTexcoord ? "highp" : "mediump"); } if (!g_Config.bFragmentTestCache) { diff --git a/GPU/Vulkan/GPU_Vulkan.cpp b/GPU/Vulkan/GPU_Vulkan.cpp index f58f41230e..0bfb67d41c 100644 --- a/GPU/Vulkan/GPU_Vulkan.cpp +++ b/GPU/Vulkan/GPU_Vulkan.cpp @@ -17,7 +17,7 @@ #include "GPU/Vulkan/GPU_Vulkan.h" -GPU_Vulkan::GPU_Vulkan() { +GPU_Vulkan::GPU_Vulkan(VulkanContext *vulkan) : transformDraw_(vulkan) { } diff --git a/GPU/Vulkan/GPU_Vulkan.h b/GPU/Vulkan/GPU_Vulkan.h index 69efc4c78f..e691cbbb61 100644 --- a/GPU/Vulkan/GPU_Vulkan.h +++ b/GPU/Vulkan/GPU_Vulkan.h @@ -31,7 +31,7 @@ class LinkedShader; class GPU_Vulkan : public GPUCommon { public: - GPU_Vulkan(); + GPU_Vulkan(VulkanContext *vulkan); ~GPU_Vulkan(); // This gets called on startup and when we get back from settings. diff --git a/GPU/Vulkan/PipelineManagerVulkan.cpp b/GPU/Vulkan/PipelineManagerVulkan.cpp index 9ef2abce4a..58920f4fcc 100644 --- a/GPU/Vulkan/PipelineManagerVulkan.cpp +++ b/GPU/Vulkan/PipelineManagerVulkan.cpp @@ -3,6 +3,15 @@ #include "Common/Log.h" #include "GPU/Vulkan/VulkanUtil.h" #include "GPU/Vulkan/PipelineManagerVulkan.h" +#include "thin3d/VulkanContext.h" + +PipelineManagerVulkan::PipelineManagerVulkan(VulkanContext *vulkan) : vulkan_(vulkan) { + pipelineCache_ = vulkan->CreatePipelineCache(); +} + +PipelineManagerVulkan::~PipelineManagerVulkan() { + vkDestroyPipelineCache(vulkan_->GetDevice(), pipelineCache_, nullptr); +} struct DeclTypeInfo { VkFormat type; @@ -87,7 +96,7 @@ static VulkanPipeline *CreateVulkanPipeline(VkDevice device, VkPipelineCache pip blend0.dstAlphaBlendFactor = key.destAlpha; } blend0.colorWriteMask = key.colorWriteMask; - + VkPipelineColorBlendStateCreateInfo cbs; cbs.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; cbs.pNext = nullptr; @@ -117,17 +126,6 @@ static VulkanPipeline *CreateVulkanPipeline(VkDevice device, VkPipelineCache pip dss.depthWriteEnable = key.depthWriteEnable; } - VkGraphicsPipelineCreateInfo pipe; - pipe.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; - pipe.pNext = nullptr; - - pipe.pColorBlendState = &cbs; - if (key.depthTestEnable || key.stencilTestEnable) { - pipe.pDepthStencilState = &dss; - } else { - pipe.pDepthStencilState = nullptr; - } - VkDynamicState dynamicStates[8]; int numDyn = 0; if (key.blendEnable) { @@ -147,8 +145,6 @@ static VulkanPipeline *CreateVulkanPipeline(VkDevice device, VkPipelineCache pip ds.pDynamicStates = dynamicStates; ds.dynamicStateCount = numDyn; - pipe.pDynamicState = &ds; - VkPipelineRasterizationStateCreateInfo rs; rs.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; rs.pNext = nullptr; @@ -160,10 +156,12 @@ static VulkanPipeline *CreateVulkanPipeline(VkDevice device, VkPipelineCache pip rs.polygonMode = VK_POLYGON_MODE_FILL; rs.depthClampEnable = false; - pipe.pRasterizationState = &rs; - - // We will use dynamic viewport state. - pipe.pViewportState = nullptr; + VkPipelineMultisampleStateCreateInfo ms; + memset(&ms, 0, sizeof(ms)); + ms.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; + ms.pNext = nullptr; + ms.pSampleMask = nullptr; + ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; VkPipelineShaderStageCreateInfo ss[2]; ss[0].sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; @@ -180,9 +178,12 @@ static VulkanPipeline *CreateVulkanPipeline(VkDevice device, VkPipelineCache pip ss[1].module = fshader; ss[1].pName = "main"; ss[1].flags = 0; - pipe.stageCount = 2; - pipe.pStages = ss; - pipe.basePipelineIndex = 0; + + VkPipelineInputAssemblyStateCreateInfo inputAssembly; + inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; + inputAssembly.pNext = nullptr; + inputAssembly.topology = key.topology; + inputAssembly.primitiveRestartEnable = false; int vertexStride = 0; @@ -208,6 +209,35 @@ static VulkanPipeline *CreateVulkanPipeline(VkDevice device, VkPipelineCache pip vis.vertexAttributeDescriptionCount = attributeCount; vis.pVertexAttributeDescriptions = attrs; + VkPipelineViewportStateCreateInfo vs; + vs.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; + vs.pNext = nullptr; + vs.viewportCount = 1; + vs.scissorCount = 1; + vs.pViewports = nullptr; // dynamic + vs.pScissors = nullptr; // dynamic + + VkGraphicsPipelineCreateInfo pipe; + pipe.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; + pipe.pNext = nullptr; + pipe.stageCount = 2; + pipe.pStages = ss; + pipe.basePipelineIndex = 0; + + pipe.pColorBlendState = &cbs; + if (key.depthTestEnable || key.stencilTestEnable) { + pipe.pDepthStencilState = &dss; + } else { + pipe.pDepthStencilState = nullptr; + } + pipe.pRasterizationState = &rs; + + // We will use dynamic viewport state. + pipe.pViewportState = &vs; + pipe.pDynamicState = &ds; + pipe.pInputAssemblyState = &inputAssembly; + pipe.pMultisampleState = &ms; + VkPipeline pipeline; VkResult result = vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipe, nullptr, &pipeline); if (result != VK_SUCCESS) { diff --git a/GPU/Vulkan/PipelineManagerVulkan.h b/GPU/Vulkan/PipelineManagerVulkan.h index d28514267e..b31a097539 100644 --- a/GPU/Vulkan/PipelineManagerVulkan.h +++ b/GPU/Vulkan/PipelineManagerVulkan.h @@ -17,22 +17,13 @@ #pragma once +#include + #include "GPU/Common/VertexDecoderCommon.h" #include "GPU/Common/ShaderId.h" #include "GPU/Vulkan/VulkanUtil.h" -// The Descriptor Set used for the majority of PSP rendering looks like this: -// -// * binding 0: Vertex Data (up to 7 locations as defined in PspAttributeLocation) -// * binding 1: Texture Sampler (the PSP texture) -// * binding 2: Secondary texture sampler for shader blending or depal palettes -// * binding 3: Vertex Uniform Buffer -// * binding 4: Fragment Uniform Buffer -// -// All shaders conform to this layout, so they are all compatible with the same descriptor set. -// The format of the various uniform buffers may vary though - vertex shaders that don't skin -// won't get any bone data, etc. - +// PSP vertex format. enum class PspAttributeLocation { POSITION = 0, TEXCOORD = 1, @@ -71,10 +62,16 @@ struct VulkanPipelineRasterStateKey { VkStencilOp stencilPassOp : 4; VkStencilOp stencilFailOp : 4; VkStencilOp stencilDepthFailOp : 4; - // We'll use dynamic state for writemask, reference and comparemask to start with. + // We'll use dynamic state for writemask, reference and comparemask to start with, + // and viewport/scissor. // Rasterizer VkCullModeFlagBits cullMode : 2; + VkPrimitiveTopology topology : 4; + + bool operator < (const VulkanPipelineRasterStateKey &other) const { + return memcmp(this, &other, sizeof(*this)) < 0; + } }; // All the information needed. All PSP rendering (except full screen clears?) will make use of a single @@ -86,6 +83,16 @@ struct VulkanPipelineKey { uint32_t vertType; ShaderID vShaderId; ShaderID fShaderId; + + bool operator < (const VulkanPipelineKey &other) const { + if (raster < other.raster) return true; else if (other.raster < raster) return false; + if (prim < other.prim) return true; else if (other.prim < prim) return false; + if (pretransformed < other.pretransformed) return true; else if (other.pretransformed < pretransformed) return false; + if (vertType < other.vertType) return true; else if (other.vertType < vertType) return false; + if (vShaderId < other.vShaderId) return true; else if (other.vShaderId < vShaderId) return false; + if (fShaderId < other.fShaderId) return true; else if (other.fShaderId < fShaderId) return false; + return false; + } }; enum { @@ -102,5 +109,11 @@ struct VulkanPipeline { class PipelineManagerVulkan { public: + PipelineManagerVulkan(VulkanContext *ctx); + ~PipelineManagerVulkan(); +private: + std::map pipelines_; + VkPipelineCache pipelineCache_; + VulkanContext *vulkan_; }; diff --git a/GPU/Vulkan/ShaderManagerVulkan.h b/GPU/Vulkan/ShaderManagerVulkan.h index 00b6103bd7..ef7bdda917 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.h +++ b/GPU/Vulkan/ShaderManagerVulkan.h @@ -84,7 +84,7 @@ struct UB_VS_TransformCommon { float matAmbient[4]; }; -static const char *ub_vs_transformCommonStr = +static const char *ub_baseStr = R"(matrix4x4 proj; matrix4x4 view; matrix4x4 world; @@ -93,6 +93,23 @@ R"(matrix4x4 proj; vec4 depthRange; vec2 fogCoef; vec4 matAmbient; + // Blend function replacement + vec3 u_blendFixA; + vec3 u_blendFixB; + + // Texture clamp emulation + vec4 u_texclamp; + vec2 u_texclampoff; + + // Alpha/Color test emulation + vec4 u_alphacolorref; + ivec4 u_alphacolormask; + + // Stencil replacement + float u_stencilReplaceValue; + vec3 u_texenv; + + vec3 u_fogcolor; )"; struct UB_VS_Lights { diff --git a/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp b/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp index 5d6c5197b8..d76ce47ed1 100644 --- a/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp +++ b/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp @@ -178,7 +178,7 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { // We will memcpy the parts into place in a big buffer so we can be quite dynamic about what parts // are present and what parts aren't, but we will not be ultra detailed about it. - WRITE(p, "layout (binding=3) uniform base {\n%s\n}\n", ub_vs_transformCommonStr); + WRITE(p, "layout (binding=3) uniform base {\n%s\n}\n", ub_baseStr); if (enableLighting) WRITE(p, "layout (binding=4) uniform light {\n%s\n}\n", ub_vs_lightsStr); if (enableBones) diff --git a/ext/native/thin3d/VulkanContext.cpp b/ext/native/thin3d/VulkanContext.cpp index 809a0f9abd..0af8e5ddd8 100644 --- a/ext/native/thin3d/VulkanContext.cpp +++ b/ext/native/thin3d/VulkanContext.cpp @@ -1390,6 +1390,19 @@ void VulkanContext::DestroyDevice() { device_ = NULL; } +VkPipelineCache VulkanContext::CreatePipelineCache() { + VkPipelineCache cache; + VkPipelineCacheCreateInfo pc; + pc.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO; + pc.pNext = nullptr; + pc.pInitialData = nullptr; + pc.initialDataSize = 0; + pc.flags = 0; + VkResult res = vkCreatePipelineCache(device_, &pc, nullptr, &cache); + assert(VK_SUCCESS == res); + return cache; +} + void TransitionImageLayout( VkCommandBuffer cmd, VkImage image, diff --git a/ext/native/thin3d/VulkanContext.h b/ext/native/thin3d/VulkanContext.h index f43ba208d6..876d20c213 100644 --- a/ext/native/thin3d/VulkanContext.h +++ b/ext/native/thin3d/VulkanContext.h @@ -26,6 +26,7 @@ #ifndef UTIL_INIT #define UTIL_INIT +#include #include #include @@ -130,6 +131,9 @@ public: globalDeleteList_.QueueDelete(mem); } + + VkPipelineCache CreatePipelineCache(); + void InitSurfaceAndQueue(HINSTANCE conn, HWND wnd); void InitSwapchain(VkCommandBuffer cmd); void InitSurfaceRenderPass(bool include_depth, bool clear); @@ -306,6 +310,7 @@ private: // Wrapper around what you need to use a texture. // Not very optimal - if you have many small textures you should use other strategies. +// Only supports simple 2D textures for now. Mipmap support will be added later. class VulkanTexture { public: VkImage image; @@ -332,6 +337,101 @@ private: bool needStaging; }; +// Use these to push vertex, index and uniform data. +// TODO: Make it possible to suballocate pushbuffers from a large DeviceMemory block. +// TODO: Make this dynamically grow by chaining new buffers in the future. +// Until then, we cap at a maximum size. +// We'll have two of these that we alternate between on each frame. +// These will only be used for the "Thin3D" system - the PSP emulation etc will have +// their own similar buffer solutions. +class VulkanPushBuffer { +public: + VulkanPushBuffer(VulkanContext *vulkan, size_t size) : offset_(0), size_(size), writePtr_(nullptr), deviceMemory_(nullptr) { + VkDevice device = vulkan->GetDevice(); + + VkBufferCreateInfo b; + b.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; + b.pNext = nullptr; + b.size = size; + b.flags = 0; + b.usage = VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; + b.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + b.queueFamilyIndexCount = 0; + b.pQueueFamilyIndices = nullptr; + VkResult res = vkCreateBuffer(device, &b, nullptr, &buffer_); + assert(VK_SUCCESS == res); + + // Okay, that's the buffer. Now let's allocate some memory for it. + VkMemoryAllocateInfo alloc; + alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + alloc.pNext = nullptr; + vulkan->MemoryTypeFromProperties(0xFFFFFFFF, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, &alloc.memoryTypeIndex); + alloc.allocationSize = size; + + res = vkAllocateMemory(device, &alloc, nullptr, &deviceMemory_); + assert(VK_SUCCESS == res); + res = vkBindBufferMemory(device, buffer_, deviceMemory_, 0); + assert(VK_SUCCESS == res); + } + + void Destroy(VulkanContext *vulkan) { + vulkan->QueueDelete(buffer_); + vulkan->QueueDelete(deviceMemory_); + } + + void Reset() { offset_ = 0; } + + void Begin(VkDevice device) { + offset_ = 0; + VkResult res = vkMapMemory(device, deviceMemory_, 0, size_, 0, (void **)(&writePtr_)); + assert(VK_SUCCESS == res); + } + + void End(VkDevice device) { + vkUnmapMemory(device, deviceMemory_); + writePtr_ = nullptr; + } + + + size_t Allocate(size_t numBytes) { + size_t out = offset_; + offset_ += (numBytes + 3) & ~3; // Round up to 4 bytes. + return out; + } + + // TODO: Add alignment support? + // Returns the offset that should be used when binding this buffer to get this data. + size_t Push(const void *data, size_t size) { + size_t off = Allocate(size); + memcpy(writePtr_ + off, data, size); + return off; + } + + size_t PushAligned(const void *data, size_t size, int align) { + offset_ = (offset_ + align - 1) & ~(align - 1); + size_t off = Allocate(size); + memcpy(writePtr_ + off, data, size); + return off; + } + + // "Zero-copy" variant - you can write the data directly as you compute it. + void *Push(size_t size, size_t *bindOffset) { + size_t off = Allocate(size); + *bindOffset = off; + return writePtr_ + off; + } + + VkBuffer GetVkBuffer() const { return buffer_; } + +private: + VkDeviceMemory deviceMemory_; + VkBuffer buffer_; + size_t offset_; + size_t size_; + uint8_t *writePtr_; +}; + + VkBool32 CheckLayers(const std::vector &layer_props, const std::vector &layer_names); void VulkanBeginCommandBuffer(VkCommandBuffer cmd); diff --git a/ext/native/thin3d/thin3d_vulkan.cpp b/ext/native/thin3d/thin3d_vulkan.cpp index 80dc0f4485..d2aa8faab8 100644 --- a/ext/native/thin3d/thin3d_vulkan.cpp +++ b/ext/native/thin3d/thin3d_vulkan.cpp @@ -108,98 +108,6 @@ static inline void Uint8x4ToFloat4(uint32_t u, float f[4]) { } -// Use these to push vertex, index and uniform data. -// TODO: Make this dynamically grow by chaining new buffers in the future. -// Until then, we cap at a maximum size. -// We'll have two of these that we alternate between on each frame. -// These will only be used for the "Thin3D" system - the PSP emulation etc will have -// their own similar buffer solutions. -class VulkanPushBuffer { -public: - VulkanPushBuffer(VkDevice device, VulkanContext *vulkan, size_t size) : offset_(0), size_(size), writePtr_(nullptr), deviceMemory_(nullptr) { - VkBufferCreateInfo b; - b.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; - b.pNext = nullptr; - b.size = size; - b.flags = 0; - b.usage = VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; - b.sharingMode = VK_SHARING_MODE_EXCLUSIVE; - b.queueFamilyIndexCount = 0; - b.pQueueFamilyIndices = nullptr; - VkResult res = vkCreateBuffer(device, &b, nullptr, &buffer_); - assert(VK_SUCCESS == res); - - // Okay, that's the buffer. Now let's allocate some memory for it. - VkMemoryAllocateInfo alloc; - alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; - alloc.pNext = nullptr; - vulkan->MemoryTypeFromProperties(0xFFFFFFFF, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, &alloc.memoryTypeIndex); - alloc.allocationSize = size; - - res = vkAllocateMemory(device, &alloc, nullptr, &deviceMemory_); - assert(VK_SUCCESS == res); - res = vkBindBufferMemory(device, buffer_, deviceMemory_, 0); - assert(VK_SUCCESS == res); - } - - void Destroy(VulkanContext *vulkan) { - vulkan->QueueDelete(buffer_); - vulkan->QueueDelete(deviceMemory_); - } - - void Reset() { offset_ = 0; } - - void Begin(VkDevice device) { - offset_ = 0; - VkResult res = vkMapMemory(device, deviceMemory_, 0, size_, 0, (void **)(&writePtr_)); - assert(VK_SUCCESS == res); - } - - void End(VkDevice device) { - vkUnmapMemory(device, deviceMemory_); - writePtr_ = nullptr; - } - - - size_t Allocate(size_t numBytes) { - size_t out = offset_; - offset_ += (numBytes + 3) & ~3; // Round up to 4 bytes. - return out; - } - - // TODO: Add alignment support? - // Returns the offset that should be used when binding this buffer to get this data. - size_t Push(const void *data, size_t size) { - size_t off = Allocate(size); - memcpy(writePtr_ + off, data, size); - return off; - } - - size_t PushAligned(const void *data, size_t size, int align) { - offset_ = (offset_ + align - 1) & ~(align - 1); - size_t off = Allocate(size); - memcpy(writePtr_ + off, data, size); - return off; - } - - // "Zero-copy" variant - you can write the data directly as you compute it. - void *Push(size_t size, size_t *bindOffset) { - size_t off = Allocate(size); - *bindOffset = off; - return writePtr_ + off; - } - - VkBuffer GetVkBuffer() const { return buffer_; } - -private: - // TODO: Make it possible to suballocate pushbuffers in a large DeviceMemory block. - VkDeviceMemory deviceMemory_; - VkBuffer buffer_; - size_t offset_; - size_t size_; - uint8_t *writePtr_; -}; - class Thin3DVKBlendState : public Thin3DBlendState { public: bool blendEnabled; @@ -714,12 +622,11 @@ Thin3DVKContext::Thin3DVKContext(VulkanContext *vulkan) res = vkCreateDescriptorPool(device_, &dp, nullptr, &frame_[1].descriptorPool); assert(VK_SUCCESS == res); - frame_[0].pushBuffer = new VulkanPushBuffer(device_, vulkan_, 1024 * 1024); - frame_[1].pushBuffer = new VulkanPushBuffer(device_, vulkan_, 1024 * 1024); + frame_[0].pushBuffer = new VulkanPushBuffer(vulkan_, 1024 * 1024); + frame_[1].pushBuffer = new VulkanPushBuffer(vulkan_, 1024 * 1024); // binding 0 - uniform data - // binding 1 - sampler - // binding 2 - image + // binding 1 - combined sampler/image VkDescriptorSetLayoutBinding bindings[2]; bindings[0].descriptorCount = 1; bindings[0].pImmutableSamplers = nullptr; @@ -750,14 +657,7 @@ Thin3DVKContext::Thin3DVKContext(VulkanContext *vulkan) res = vkCreatePipelineLayout(device_, &pl, nullptr, &pipelineLayout_); assert(VK_SUCCESS == res); - VkPipelineCacheCreateInfo pc; - pc.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO; - pc.pNext = nullptr; - pc.pInitialData = nullptr; - pc.initialDataSize = 0; - pc.flags = 0; - res = vkCreatePipelineCache(device_, &pc, nullptr, &pipelineCache_); - assert(VK_SUCCESS == res); + pipelineCache_ = vulkan_->CreatePipelineCache(); } Thin3DVKContext::~Thin3DVKContext() { From cfcfd406fc21c164f46afcd09685197f6456b3c8 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 3 Jan 2016 23:09:37 +0100 Subject: [PATCH 016/116] Start porting TextureCache. Lots of stubbing going on. --- GPU/Common/DepalettizeShaderCommon.cpp | 5 +- GPU/Common/DepalettizeShaderCommon.h | 1 + GPU/Common/FramebufferCommon.h | 3 + GPU/Common/TextureCacheCommon.h | 3 + GPU/GPU.vcxproj | 3 + GPU/GPU.vcxproj.filters | 3 + GPU/Vulkan/DepalettizeShaderVulkan.h | 61 + GPU/Vulkan/DrawEngineVulkan.cpp | 4 +- GPU/Vulkan/FramebufferVulkan.cpp | 24 + GPU/Vulkan/FramebufferVulkan.h | 9 + GPU/Vulkan/GPU_Vulkan.cpp | 2 +- GPU/Vulkan/GPU_Vulkan.h | 2 +- GPU/Vulkan/TextureCacheVulkan.cpp | 1779 +++++++++++++++++++++++- GPU/Vulkan/TextureCacheVulkan.h | 116 +- GPU/Vulkan/TextureScalerVulkan.cpp | 62 + GPU/Vulkan/TextureScalerVulkan.h | 27 + ext/native/thin3d/VulkanContext.cpp | 19 + ext/native/thin3d/VulkanContext.h | 18 + 18 files changed, 2128 insertions(+), 13 deletions(-) create mode 100644 GPU/Vulkan/DepalettizeShaderVulkan.h create mode 100644 GPU/Vulkan/TextureScalerVulkan.cpp create mode 100644 GPU/Vulkan/TextureScalerVulkan.h diff --git a/GPU/Common/DepalettizeShaderCommon.cpp b/GPU/Common/DepalettizeShaderCommon.cpp index 721fdf18a3..2a250a21de 100644 --- a/GPU/Common/DepalettizeShaderCommon.cpp +++ b/GPU/Common/DepalettizeShaderCommon.cpp @@ -27,7 +27,7 @@ #define WRITE p+=sprintf // Uses integer instructions available since OpenGL 3.0. Suitable for ES 3.0 as well. -void GenerateDepalShader300(char *buffer, GEBufferFormat pixelFormat) { +void GenerateDepalShader300(char *buffer, GEBufferFormat pixelFormat, ShaderLanguage language) { char *p = buffer; if (gl_extensions.IsGLES) { WRITE(p, "#version 300 es\n"); @@ -250,7 +250,8 @@ void GenerateDepalShader(char *buffer, GEBufferFormat pixelFormat, ShaderLanguag GenerateDepalShaderFloat(buffer, pixelFormat, language); break; case GLSL_300: - GenerateDepalShader300(buffer, pixelFormat); + case GLSL_VULKAN: + GenerateDepalShader300(buffer, pixelFormat, language); break; case HLSL_DX9: GenerateDepalShaderFloat(buffer, pixelFormat, language); diff --git a/GPU/Common/DepalettizeShaderCommon.h b/GPU/Common/DepalettizeShaderCommon.h index 57a87c889c..c49a65cdbf 100644 --- a/GPU/Common/DepalettizeShaderCommon.h +++ b/GPU/Common/DepalettizeShaderCommon.h @@ -22,6 +22,7 @@ enum ShaderLanguage { GLSL_140, GLSL_300, + GLSL_VULKAN, HLSL_DX9, }; diff --git a/GPU/Common/FramebufferCommon.h b/GPU/Common/FramebufferCommon.h index e236a64f6d..f9ebd1e3ad 100644 --- a/GPU/Common/FramebufferCommon.h +++ b/GPU/Common/FramebufferCommon.h @@ -51,6 +51,8 @@ namespace DX9 { struct FBO_DX9; } +class VulkanFramebuffer; + struct VirtualFramebuffer { int last_frame_used; int last_frame_attached; @@ -90,6 +92,7 @@ struct VirtualFramebuffer { union { FBO *fbo; DX9::FBO_DX9 *fbo_dx9; + VulkanFramebuffer *fbo_vk; }; u16 drawnWidth; diff --git a/GPU/Common/TextureCacheCommon.h b/GPU/Common/TextureCacheCommon.h index 95ff12aa60..c5da7b3af3 100644 --- a/GPU/Common/TextureCacheCommon.h +++ b/GPU/Common/TextureCacheCommon.h @@ -39,6 +39,8 @@ enum FramebufferNotification { struct VirtualFramebuffer; +class CachedTextureVulkan; + class TextureCacheCommon { public: TextureCacheCommon(); @@ -96,6 +98,7 @@ public: union { u32 textureName; void *texturePtr; + CachedTextureVulkan *vkTex; }; int invalidHint; u32 fullhash; diff --git a/GPU/GPU.vcxproj b/GPU/GPU.vcxproj index 09c17b003a..9904be92b8 100644 --- a/GPU/GPU.vcxproj +++ b/GPU/GPU.vcxproj @@ -244,6 +244,7 @@ + @@ -251,6 +252,7 @@ + @@ -339,6 +341,7 @@ + diff --git a/GPU/GPU.vcxproj.filters b/GPU/GPU.vcxproj.filters index 4fe276f335..c48c83ecf7 100644 --- a/GPU/GPU.vcxproj.filters +++ b/GPU/GPU.vcxproj.filters @@ -210,6 +210,8 @@ + + @@ -404,5 +406,6 @@ + \ No newline at end of file diff --git a/GPU/Vulkan/DepalettizeShaderVulkan.h b/GPU/Vulkan/DepalettizeShaderVulkan.h new file mode 100644 index 0000000000..ccee8ed7e9 --- /dev/null +++ b/GPU/Vulkan/DepalettizeShaderVulkan.h @@ -0,0 +1,61 @@ +#pragma once +// Copyright (c) 2014- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#include + +#include "Common/CommonTypes.h" +#include "GPU/ge_constants.h" + +class DepalShader { +public: + /* + GLuint program; + GLuint fragShader; + GLint a_position; + GLint a_texcoord0; + */ +}; + +class DepalTexture { +public: + int texture; + int lastFrame; +}; + +// Caches both shaders and palette textures. +// Could even avoid bothering with palette texture and just use uniform data... +class DepalShaderCacheVulkan { +public: + DepalShaderCacheVulkan(); + ~DepalShaderCacheVulkan(); + + // This also uploads the palette and binds the correct texture. + DepalShader *GetDepalettizeShader(GEPaletteFormat clutFormat, GEBufferFormat pixelFormat); + VulkanTexture *GetClutTexture(GEPaletteFormat clutFormat, const u32 clutHash, u32 *rawClut); + void Clear(); + void Decimate(); + +private: + u32 GenerateShaderID(GEPaletteFormat clutFormat, GEBufferFormat pixelFormat); + bool CreateVertexShader(); + + // GLuint vertexShader_; + std::map cache_; + std::map texCache_; +}; + diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index e5e7e4a966..f090bd602c 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -433,8 +433,8 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { }; vkCmdBindDescriptorSets(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout_, 0, 1, &ds, 3, dynamicUBOOffsets); - ibOffset = (uint32_t)(frame->pushData->Push(decIndex, 2 * indexGen.VertexCount())); - // vbOffset = frame->pushData->Push(decoded, ) + ibOffset = (uint32_t)frame->pushData->Push(decIndex, 2 * indexGen.VertexCount()); + vbOffset = (uint32_t)frame->pushData->Push(decoded, vertexCount * dec_->GetDecVtxFmt().stride); VkDeviceSize offsets[1] = { vbOffset }; if (useElements) { diff --git a/GPU/Vulkan/FramebufferVulkan.cpp b/GPU/Vulkan/FramebufferVulkan.cpp index e69de29bb2..f6fa0ee164 100644 --- a/GPU/Vulkan/FramebufferVulkan.cpp +++ b/GPU/Vulkan/FramebufferVulkan.cpp @@ -0,0 +1,24 @@ +// Copyright (c) 2015- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#pragma once + +#include "GPU/Vulkan/FramebufferVulkan.h" + +VulkanFramebuffer *FramebufferManagerVulkan::GetTempFBO(int width, int height, VulkanFBOColorDepth colorDepth) { + return nullptr; +} diff --git a/GPU/Vulkan/FramebufferVulkan.h b/GPU/Vulkan/FramebufferVulkan.h index dc1892bcba..a45a93a400 100644 --- a/GPU/Vulkan/FramebufferVulkan.h +++ b/GPU/Vulkan/FramebufferVulkan.h @@ -20,6 +20,14 @@ #include "GPU/Common/FramebufferCommon.h" #include "GPU/Vulkan/VulkanUtil.h" +// TODO: WTF? +enum VulkanFBOColorDepth { + VK_FBO_8888, + VK_FBO_565, + VK_FBO_4444, + VK_FBO_5551, +}; + class FramebufferManagerVulkan : public FramebufferManagerCommon { public: // Subsequent commands will be enqueued on this buffer. @@ -29,6 +37,7 @@ public: virtual void ClearBuffer(bool keepState = false) override { throw std::logic_error("The method or operation is not implemented."); } + VulkanFramebuffer *GetTempFBO(int width, int height, VulkanFBOColorDepth colorDepth); virtual void RebindFramebuffer() override { throw std::logic_error("The method or operation is not implemented."); diff --git a/GPU/Vulkan/GPU_Vulkan.cpp b/GPU/Vulkan/GPU_Vulkan.cpp index 0bfb67d41c..b7834de1ca 100644 --- a/GPU/Vulkan/GPU_Vulkan.cpp +++ b/GPU/Vulkan/GPU_Vulkan.cpp @@ -17,7 +17,7 @@ #include "GPU/Vulkan/GPU_Vulkan.h" -GPU_Vulkan::GPU_Vulkan(VulkanContext *vulkan) : transformDraw_(vulkan) { +GPU_Vulkan::GPU_Vulkan(VulkanContext *vulkan) : transformDraw_(vulkan), textureCache_(vulkan) { } diff --git a/GPU/Vulkan/GPU_Vulkan.h b/GPU/Vulkan/GPU_Vulkan.h index e691cbbb61..6f63b3c807 100644 --- a/GPU/Vulkan/GPU_Vulkan.h +++ b/GPU/Vulkan/GPU_Vulkan.h @@ -65,7 +65,7 @@ public: void Resized() override; void ClearShaderCache() override; bool DecodeTexture(u8 *dest, const GPUgstate &state) override { - return textureCache_.DecodeTexture(dest, state); + return false; } bool FramebufferDirty() override; bool FramebufferReallyDirty() override; diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index d9bbf8e6b1..f70fd39522 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -1,9 +1,1786 @@ +// Copyright (c) 2012- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#include +#include + +#include "ext/xxhash.h" +#include "i18n/i18n.h" +#include "math/math_util.h" +#include "profiler/profiler.h" +#include "thin3d/VulkanContext.h" +#include "Common/ColorConv.h" +#include "Core/Config.h" +#include "Core/Host.h" +#include "Core/MemMap.h" +#include "Core/Reporting.h" +#include "Core/System.h" +#include "GPU/ge_constants.h" +#include "GPU/GPUState.h" #include "GPU/Vulkan/TextureCacheVulkan.h" +#include "GPU/Vulkan/FramebufferVulkan.h" +#include "GPU/Vulkan/FragmentShaderGeneratorVulkan.h" +#include "GPU/Vulkan/DepalettizeShaderVulkan.h" +#include "GPU/Vulkan/ShaderManagerVulkan.h" +#include "GPU/Vulkan/DrawEngineVulkan.h" +#include "GPU/Common/TextureDecoder.h" +#include "UI/OnScreenDisplay.h" + +#ifdef _M_SSE +#include +#endif + +// If a texture hasn't been seen for this many frames, get rid of it. +#define TEXTURE_KILL_AGE 200 +#define TEXTURE_KILL_AGE_LOWMEM 60 +// Not used in lowmem mode. +#define TEXTURE_SECOND_KILL_AGE 100 + +// Try to be prime to other decimation intervals. +#define TEXCACHE_DECIMATION_INTERVAL 13 + +// Changes more frequent than this will be considered "frequent" and prevent texture scaling. +#define TEXCACHE_FRAME_CHANGE_FREQUENT 6 +// Note: only used when hash backoff is disabled. +#define TEXCACHE_FRAME_CHANGE_FREQUENT_REGAIN_TRUST 33 + +#define TEXCACHE_NAME_CACHE_SIZE 16 + +#define TEXCACHE_MAX_TEXELS_SCALED (256*256) // Per frame + +#define TEXCACHE_MIN_PRESSURE 16 * 1024 * 1024 // Total in GL +#define TEXCACHE_SECOND_MIN_PRESSURE 4 * 1024 * 1024 + +// Hack! +extern int g_iNumVideos; + +// texturePtr points to these. +class CachedTextureVulkan { +public: + VkImageView imageView; +}; + + +TextureCacheVulkan::TextureCacheVulkan(VulkanContext *vulkan) : vulkan_(vulkan), cacheSizeEstimate_(0), secondCacheSizeEstimate_(0), clearCacheNextFrame_(false), lowMemoryMode_(false), clutBuf_(NULL), texelsScaledThisFrame_(0) { + timesInvalidatedAllThisFrame_ = 0; + lastBoundTexture = nullptr; + decimationCounter_ = TEXCACHE_DECIMATION_INTERVAL; + + SetupTextureDecoder(); + + nextTexture_ = nullptr; +} + +TextureCacheVulkan::~TextureCacheVulkan() { + Clear(true); +} + +static u32 EstimateTexMemoryUsage(const TextureCacheVulkan::TexCacheEntry *entry) { + const u16 dim = entry->dim; + const u8 dimW = ((dim >> 0) & 0xf); + const u8 dimH = ((dim >> 8) & 0xf); + + u32 pixelSize = 2; + switch (entry->format) { + case GE_TFMT_CLUT4: + case GE_TFMT_CLUT8: + case GE_TFMT_CLUT16: + case GE_TFMT_CLUT32: + // We assume cluts always point to 8888 for simplicity. + pixelSize = 4; + break; + case GE_TFMT_4444: + case GE_TFMT_5551: + case GE_TFMT_5650: + break; + + case GE_TFMT_8888: + case GE_TFMT_DXT1: + case GE_TFMT_DXT3: + case GE_TFMT_DXT5: + default: + pixelSize = 4; + break; + } + + // This in other words multiplies by w and h. + return pixelSize << (dimW + dimH); +} + +void TextureCacheVulkan::Clear(bool delete_them) { + lastBoundTexture = nullptr; + if (delete_them) { + for (TexCache::iterator iter = cache.begin(); iter != cache.end(); ++iter) { + DEBUG_LOG(G3D, "Deleting texture %p", iter->second.vkTex); + delete iter->second.vkTex; + } + for (TexCache::iterator iter = secondCache.begin(); iter != secondCache.end(); ++iter) { + DEBUG_LOG(G3D, "Deleting texture %p", iter->second.vkTex); + delete iter->second.vkTex; + } + } + if (cache.size() + secondCache.size()) { + INFO_LOG(G3D, "Texture cached cleared from %i textures", (int)(cache.size() + secondCache.size())); + cache.clear(); + secondCache.clear(); + cacheSizeEstimate_ = 0; + secondCacheSizeEstimate_ = 0; + } + fbTexInfo_.clear(); +} + +void TextureCacheVulkan::DeleteTexture(TexCache::iterator it) { + delete it->second.vkTex; + auto fbInfo = fbTexInfo_.find(it->second.addr); + if (fbInfo != fbTexInfo_.end()) { + fbTexInfo_.erase(fbInfo); + } + + cacheSizeEstimate_ -= EstimateTexMemoryUsage(&it->second); + cache.erase(it); +} + +// Removes old textures. +void TextureCacheVulkan::Decimate() { + if (--decimationCounter_ <= 0) { + decimationCounter_ = TEXCACHE_DECIMATION_INTERVAL; + } else { + return; + } + + if (cacheSizeEstimate_ >= TEXCACHE_MIN_PRESSURE) { + const u32 had = cacheSizeEstimate_; + + lastBoundTexture = nullptr; + int killAge = lowMemoryMode_ ? TEXTURE_KILL_AGE_LOWMEM : TEXTURE_KILL_AGE; + for (TexCache::iterator iter = cache.begin(); iter != cache.end(); ) { + if (iter->second.lastFrame + killAge < gpuStats.numFlips) { + DeleteTexture(iter++); + } else { + ++iter; + } + } + + VERBOSE_LOG(G3D, "Decimated texture cache, saved %d estimated bytes - now %d bytes", had - cacheSizeEstimate_, cacheSizeEstimate_); + } + + if (g_Config.bTextureSecondaryCache && secondCacheSizeEstimate_ >= TEXCACHE_SECOND_MIN_PRESSURE) { + const u32 had = secondCacheSizeEstimate_; + + for (TexCache::iterator iter = secondCache.begin(); iter != secondCache.end(); ) { + // In low memory mode, we kill them all. + if (lowMemoryMode_ || iter->second.lastFrame + TEXTURE_SECOND_KILL_AGE < gpuStats.numFlips) { + delete iter->second.vkTex; + secondCacheSizeEstimate_ -= EstimateTexMemoryUsage(&iter->second); + secondCache.erase(iter++); + } else { + ++iter; + } + } + + VERBOSE_LOG(G3D, "Decimated second texture cache, saved %d estimated bytes - now %d bytes", had - secondCacheSizeEstimate_, secondCacheSizeEstimate_); + } +} + +void TextureCacheVulkan::Invalidate(u32 addr, int size, GPUInvalidationType type) { + // If we're hashing every use, without backoff, then this isn't needed. + if (!g_Config.bTextureBackoffCache) { + return; + } + + addr &= 0x3FFFFFFF; + const u32 addr_end = addr + size; + + // They could invalidate inside the texture, let's just give a bit of leeway. + const int LARGEST_TEXTURE_SIZE = 512 * 512 * 4; + const u64 startKey = (u64)(addr - LARGEST_TEXTURE_SIZE) << 32; + u64 endKey = (u64)(addr + size + LARGEST_TEXTURE_SIZE) << 32; + if (endKey < startKey) { + endKey = (u64)-1; + } + + for (TexCache::iterator iter = cache.lower_bound(startKey), end = cache.upper_bound(endKey); iter != end; ++iter) { + u32 texAddr = iter->second.addr; + u32 texEnd = iter->second.addr + iter->second.sizeInRAM; + + if (texAddr < addr_end && addr < texEnd) { + if (iter->second.GetHashStatus() == TexCacheEntry::STATUS_RELIABLE) { + iter->second.SetHashStatus(TexCacheEntry::STATUS_HASHING); + } + if (type != GPU_INVALIDATE_ALL) { + gpuStats.numTextureInvalidations++; + // Start it over from 0 (unless it's safe.) + iter->second.numFrames = type == GPU_INVALIDATE_SAFE ? 256 : 0; + if (type == GPU_INVALIDATE_SAFE) { + u32 diff = gpuStats.numFlips - iter->second.lastFrame; + // We still need to mark if the texture is frequently changing, even if it's safely changing. + if (diff < TEXCACHE_FRAME_CHANGE_FREQUENT) { + iter->second.status |= TexCacheEntry::STATUS_CHANGE_FREQUENT; + } + } + iter->second.framesUntilNextFullHash = 0; + } else if (!iter->second.framebuffer) { + iter->second.invalidHint++; + } + } + } +} + +void TextureCacheVulkan::InvalidateAll(GPUInvalidationType /*unused*/) { + // If we're hashing every use, without backoff, then this isn't needed. + if (!g_Config.bTextureBackoffCache) { + return; + } + + if (timesInvalidatedAllThisFrame_ > 5) { + return; + } + timesInvalidatedAllThisFrame_++; + + for (TexCache::iterator iter = cache.begin(), end = cache.end(); iter != end; ++iter) { + if (iter->second.GetHashStatus() == TexCacheEntry::STATUS_RELIABLE) { + iter->second.SetHashStatus(TexCacheEntry::STATUS_HASHING); + } + if (!iter->second.framebuffer) { + iter->second.invalidHint++; + } + } +} + +void TextureCacheVulkan::ClearNextFrame() { + clearCacheNextFrame_ = true; +} + + +void TextureCacheVulkan::AttachFramebufferValid(TexCacheEntry *entry, VirtualFramebuffer *framebuffer, const AttachedFramebufferInfo &fbInfo) { + const bool hasInvalidFramebuffer = entry->framebuffer == nullptr || entry->invalidHint == -1; + const bool hasOlderFramebuffer = entry->framebuffer != nullptr && entry->framebuffer->last_frame_render < framebuffer->last_frame_render; + bool hasFartherFramebuffer = false; + if (!hasInvalidFramebuffer && !hasOlderFramebuffer) { + // If it's valid, but the offset is greater, then we still win. + if (fbTexInfo_[entry->addr].yOffset == fbInfo.yOffset) + hasFartherFramebuffer = fbTexInfo_[entry->addr].xOffset > fbInfo.xOffset; + else + hasFartherFramebuffer = fbTexInfo_[entry->addr].yOffset > fbInfo.yOffset; + } + if (hasInvalidFramebuffer || hasOlderFramebuffer || hasFartherFramebuffer) { + if (entry->framebuffer == nullptr) { + cacheSizeEstimate_ -= EstimateTexMemoryUsage(entry); + } + entry->framebuffer = framebuffer; + entry->invalidHint = 0; + entry->status &= ~TextureCacheVulkan::TexCacheEntry::STATUS_DEPALETTIZE; + entry->maxLevel = 0; + fbTexInfo_[entry->addr] = fbInfo; + framebuffer->last_frame_attached = gpuStats.numFlips; + host->GPUNotifyTextureAttachment(entry->addr); + } else if (entry->framebuffer == framebuffer) { + framebuffer->last_frame_attached = gpuStats.numFlips; + } +} + +void TextureCacheVulkan::AttachFramebufferInvalid(TexCacheEntry *entry, VirtualFramebuffer *framebuffer, const AttachedFramebufferInfo &fbInfo) { + if (entry->framebuffer == nullptr || entry->framebuffer == framebuffer) { + if (entry->framebuffer == nullptr) { + cacheSizeEstimate_ -= EstimateTexMemoryUsage(entry); + } + entry->framebuffer = framebuffer; + entry->invalidHint = -1; + entry->status &= ~TextureCacheVulkan::TexCacheEntry::STATUS_DEPALETTIZE; + entry->maxLevel = 0; + fbTexInfo_[entry->addr] = fbInfo; + host->GPUNotifyTextureAttachment(entry->addr); + } +} bool TextureCacheVulkan::AttachFramebuffer(TexCacheEntry *entry, u32 address, VirtualFramebuffer *framebuffer, u32 texaddrOffset) { + static const u32 MAX_SUBAREA_Y_OFFSET_SAFE = 32; + + AttachedFramebufferInfo fbInfo = { 0 }; + + const u64 mirrorMask = 0x00600000; + // Must be in VRAM so | 0x04000000 it is. Also, ignore memory mirrors. + const u32 addr = (address | 0x04000000) & 0x3FFFFFFF & ~mirrorMask; + const u32 texaddr = ((entry->addr + texaddrOffset) & ~mirrorMask); + const bool noOffset = texaddr == addr; + const bool exactMatch = noOffset && entry->format < 4; + const u32 h = 1 << ((entry->dim >> 8) & 0xf); + // 512 on a 272 framebuffer is sane, so let's be lenient. + const u32 minSubareaHeight = h / 4; + + // If they match exactly, it's non-CLUT and from the top left. + if (exactMatch) { + // Apply to non-buffered and buffered mode only. + if (!(g_Config.iRenderingMode == FB_NON_BUFFERED_MODE || g_Config.iRenderingMode == FB_BUFFERED_MODE)) + return false; + + DEBUG_LOG(G3D, "Render to texture detected at %08x!", address); + if (framebuffer->fb_stride != entry->bufw) { + WARN_LOG_REPORT_ONCE(diffStrides1, G3D, "Render to texture with different strides %d != %d", entry->bufw, framebuffer->fb_stride); + } + if (entry->format != (GETextureFormat)framebuffer->format) { + WARN_LOG_REPORT_ONCE(diffFormat1, G3D, "Render to texture with different formats %d != %d", entry->format, framebuffer->format); + // Let's avoid using it when we know the format is wrong. May be a video/etc. updating memory. + // However, some games use a different format to clear the buffer. + if (framebuffer->last_frame_attached + 1 < gpuStats.numFlips) { + DetachFramebuffer(entry, address, framebuffer); + } + } else { + AttachFramebufferValid(entry, framebuffer, fbInfo); + return true; + } + } else { + // Apply to buffered mode only. + if (!(g_Config.iRenderingMode == FB_BUFFERED_MODE)) + return false; + + const bool clutFormat = + (framebuffer->format == GE_FORMAT_8888 && entry->format == GE_TFMT_CLUT32) || + (framebuffer->format != GE_FORMAT_8888 && entry->format == GE_TFMT_CLUT16); + + const u32 bitOffset = (texaddr - addr) * 8; + const u32 pixelOffset = bitOffset / std::max(1U, (u32)textureBitsPerPixel[entry->format]); + fbInfo.yOffset = entry->bufw == 0 ? 0 : pixelOffset / entry->bufw; + fbInfo.xOffset = entry->bufw == 0 ? 0 : pixelOffset % entry->bufw; + + if (framebuffer->fb_stride != entry->bufw) { + if (noOffset) { + WARN_LOG_REPORT_ONCE(diffStrides2, G3D, "Render to texture using CLUT with different strides %d != %d", entry->bufw, framebuffer->fb_stride); + } else { + // Assume any render-to-tex with different bufw + offset is a render from ram. + DetachFramebuffer(entry, address, framebuffer); + return false; + } + } + + if (fbInfo.yOffset + minSubareaHeight >= framebuffer->height) { + // Can't be inside the framebuffer then, ram. Detach to be safe. + DetachFramebuffer(entry, address, framebuffer); + return false; + } + // Trying to play it safe. Below 0x04110000 is almost always framebuffers. + // TODO: Maybe we can reduce this check and find a better way above 0x04110000? + if (fbInfo.yOffset > MAX_SUBAREA_Y_OFFSET_SAFE && addr > 0x04110000) { + WARN_LOG_REPORT_ONCE(subareaIgnored, G3D, "Ignoring possible render to texture at %08x +%dx%d / %dx%d", address, fbInfo.xOffset, fbInfo.yOffset, framebuffer->width, framebuffer->height); + DetachFramebuffer(entry, address, framebuffer); + return false; + } + + // Check for CLUT. The framebuffer is always RGB, but it can be interpreted as a CLUT texture. + // 3rd Birthday (and a bunch of other games) render to a 16 bit clut texture. + if (clutFormat) { + if (!noOffset) { + WARN_LOG_REPORT_ONCE(subareaClut, G3D, "Render to texture using CLUT with offset at %08x +%dx%d", address, fbInfo.xOffset, fbInfo.yOffset); + } + AttachFramebufferValid(entry, framebuffer, fbInfo); + entry->status |= TexCacheEntry::STATUS_DEPALETTIZE; + // We'll validate it compiles later. + return true; + } else if (entry->format == GE_TFMT_CLUT8 || entry->format == GE_TFMT_CLUT4) { + ERROR_LOG_REPORT_ONCE(fourEightBit, G3D, "4 and 8-bit CLUT format not supported for framebuffers"); + } + + // This is either normal or we failed to generate a shader to depalettize + if (framebuffer->format == entry->format || clutFormat) { + if (framebuffer->format != entry->format) { + WARN_LOG_REPORT_ONCE(diffFormat2, G3D, "Render to texture with different formats %d != %d at %08x", entry->format, framebuffer->format, address); + AttachFramebufferValid(entry, framebuffer, fbInfo); + return true; + } else { + WARN_LOG_REPORT_ONCE(subarea, G3D, "Render to area containing texture at %08x +%dx%d", address, fbInfo.xOffset, fbInfo.yOffset); + // If "AttachFramebufferValid" , God of War Ghost of Sparta/Chains of Olympus will be missing special effect. + AttachFramebufferInvalid(entry, framebuffer, fbInfo); + return true; + } + } else { + WARN_LOG_REPORT_ONCE(diffFormat2, G3D, "Render to texture with incompatible formats %d != %d at %08x", entry->format, framebuffer->format, address); + } + } + return false; } -void TextureCacheVulkan::DetachFramebuffer(TexCacheEntry *entry, u32 address, VirtualFramebuffer *framebuffer) { +inline void TextureCacheVulkan::DetachFramebuffer(TexCacheEntry *entry, u32 address, VirtualFramebuffer *framebuffer) { + if (entry->framebuffer == framebuffer) { + cacheSizeEstimate_ += EstimateTexMemoryUsage(entry); + entry->framebuffer = 0; + host->GPUNotifyTextureAttachment(entry->addr); + } +} +void *TextureCacheVulkan::ReadIndexedTex(int level, const u8 *texptr, int bytesPerIndex, VkFormat dstFmt, int bufw) { + int w = gstate.getTextureWidth(level); + int h = gstate.getTextureHeight(level); + int length = bufw * h; + void *buf = NULL; + switch (gstate.getClutPaletteFormat()) { + case GE_CMODE_16BIT_BGR5650: + case GE_CMODE_16BIT_ABGR5551: + case GE_CMODE_16BIT_ABGR4444: + { + tmpTexBuf16.resize(std::max(bufw, w) * h); + tmpTexBufRearrange.resize(std::max(bufw, w) * h); + const u16 *clut = GetCurrentClut(); + if (!gstate.isTextureSwizzled()) { + switch (bytesPerIndex) { + case 1: + DeIndexTexture(tmpTexBuf16.data(), (const u8 *)texptr, length, clut); + break; + + case 2: + DeIndexTexture(tmpTexBuf16.data(), (const u16_le *)texptr, length, clut); + break; + + case 4: + DeIndexTexture(tmpTexBuf16.data(), (const u32_le *)texptr, length, clut); + break; + } + } else { + tmpTexBuf32.resize(std::max(bufw, w) * h); + UnswizzleFromMem(texptr, bufw, h, bytesPerIndex); + switch (bytesPerIndex) { + case 1: + DeIndexTexture(tmpTexBuf16.data(), (u8 *)tmpTexBuf32.data(), length, clut); + break; + + case 2: + DeIndexTexture(tmpTexBuf16.data(), (u16 *)tmpTexBuf32.data(), length, clut); + break; + + case 4: + DeIndexTexture(tmpTexBuf16.data(), (u32 *)tmpTexBuf32.data(), length, clut); + break; + } + } + buf = tmpTexBuf16.data(); + } + break; + + case GE_CMODE_32BIT_ABGR8888: + { + tmpTexBuf32.resize(std::max(bufw, w) * h); + tmpTexBufRearrange.resize(std::max(bufw, w) * h); + const u32 *clut = GetCurrentClut(); + if (!gstate.isTextureSwizzled()) { + switch (bytesPerIndex) { + case 1: + DeIndexTexture(tmpTexBuf32.data(), (const u8 *)texptr, length, clut); + break; + + case 2: + DeIndexTexture(tmpTexBuf32.data(), (const u16_le *)texptr, length, clut); + break; + + case 4: + DeIndexTexture(tmpTexBuf32.data(), (const u32_le *)texptr, length, clut); + break; + } + buf = tmpTexBuf32.data(); + } else { + UnswizzleFromMem(texptr, bufw, h, bytesPerIndex); + // Since we had to unswizzle to tmpTexBuf32, let's output to tmpTexBuf16. + tmpTexBuf16.resize(std::max(bufw, w) * h * 2); + u32 *dest32 = (u32 *)tmpTexBuf16.data(); + switch (bytesPerIndex) { + case 1: + DeIndexTexture(dest32, (u8 *)tmpTexBuf32.data(), length, clut); + buf = dest32; + break; + + case 2: + DeIndexTexture(dest32, (u16 *)tmpTexBuf32.data(), length, clut); + buf = dest32; + break; + + case 4: + // TODO: If a game actually uses this mode, check if using dest32 or tmpTexBuf32 is faster. + DeIndexTexture(tmpTexBuf32.data(), tmpTexBuf32.data(), length, clut); + buf = tmpTexBuf32.data(); + break; + } + } + } + break; + + default: + ERROR_LOG_REPORT(G3D, "Unhandled clut texture mode %d!!!", (gstate.clutformat & 3)); + break; + } + + return buf; +} + +VkFormat getClutDestFormatVulkan(GEPaletteFormat format) { + switch (format) { + case GE_CMODE_16BIT_ABGR4444: + return VK_FORMAT_B4G4R4A4_UNORM_PACK16; + case GE_CMODE_16BIT_ABGR5551: + return VK_FORMAT_A1R5G5B5_UNORM_PACK16; + case GE_CMODE_16BIT_BGR5650: + return VK_FORMAT_R5G6B5_UNORM_PACK16; + case GE_CMODE_32BIT_ABGR8888: + return VK_FORMAT_R8G8B8A8_UNORM; + } + return VK_FORMAT_UNDEFINED; +} + +static const u8 texByteAlignMap[] = { 2, 2, 2, 4 }; + +static const VkFilter MagFiltVK[2] = { + VK_FILTER_NEAREST, + VK_FILTER_LINEAR +}; + + +struct SamplerCacheKey { + bool minFilt : 1; + bool mipFilt : 1; + bool magFilt : 1; + bool sClamp : 1; + bool tClamp : 1; + int lodBias : 4; + int maxLevel : 4; + + bool operator < (const SamplerCacheKey &other) const { + return memcmp(this, &other, sizeof(*this)) < 0; + } +}; + +// This should not have to be done per texture! OpenGL is silly yo +void TextureCacheVulkan::UpdateSamplingParams(TexCacheEntry &entry, bool force) { + // TODO: Make GetSamplingParams write SamplerCacheKey directly + int minFilt; + int magFilt; + bool sClamp; + bool tClamp; + float lodBias; + GetSamplingParams(minFilt, magFilt, sClamp, tClamp, lodBias, entry.maxLevel); + + SamplerCacheKey key; + key.minFilt = minFilt & 1; + key.mipFilt = (minFilt >> 2) & 1; + key.magFilt = magFilt & 1; + key.sClamp = sClamp; + key.tClamp = tClamp; + /* + if (entry.maxLevel != 0) { + if (force || entry.lodBias != lodBias) { + if (gstate_c.Supports(GPU_SUPPORTS_TEXTURE_LOD_CONTROL)) { + GETexLevelMode mode = gstate.getTexLevelMode(); + switch (mode) { + case GE_TEXLEVEL_MODE_AUTO: + // TODO + break; + case GE_TEXLEVEL_MODE_CONST: + // Sigh, LOD_BIAS is not even in ES 3.0.. + break; + case GE_TEXLEVEL_MODE_SLOPE: + // TODO + break; + } + } + entry.lodBias = lodBias; + } + } + */ + + if (entry.framebuffer) { + WARN_LOG_REPORT_ONCE(wrongFramebufAttach, G3D, "Framebuffer still attached in UpdateSamplingParams()?"); + } +} + +void TextureCacheVulkan::SetFramebufferSamplingParams(u16 bufferWidth, u16 bufferHeight, SamplerCacheKey &key) { + int minFilt; + int magFilt; + bool sClamp; + bool tClamp; + float lodBias; + GetSamplingParams(minFilt, magFilt, sClamp, tClamp, lodBias, 0); + + key.minFilt = minFilt & 1; + key.mipFilt = 0; + key.magFilt = magFilt & 1; + key.sClamp = sClamp; + key.tClamp = tClamp; + + // Often the framebuffer will not match the texture size. We'll wrap/clamp in the shader in that case. + // This happens whether we have OES_texture_npot or not. + int w = gstate.getTextureWidth(0); + int h = gstate.getTextureHeight(0); + if (w != bufferWidth || h != bufferHeight) { + key.sClamp = true; + key.tClamp = true; + } +} + +static void ConvertColors(void *dstBuf, const void *srcBuf, VkFormat dstFmt, int numPixels) { + const u32 *src = (const u32 *)srcBuf; + u32 *dst = (u32 *)dstBuf; + switch (dstFmt) { + case VK_FORMAT_B4G4R4A4_UNORM_PACK16: + ConvertRGBA4444ToABGR4444((u16 *)dst, (const u16 *)src, numPixels); + break; + // Final Fantasy 2 uses this heavily in animated textures. + case VK_FORMAT_A1R5G5B5_UNORM_PACK16: + ConvertRGBA5551ToABGR1555((u16 *)dst, (const u16 *)src, numPixels); + break; + case VK_FORMAT_R5G6B5_UNORM_PACK16: + ConvertRGB565ToBGR565((u16 *)dst, (const u16 *)src, numPixels); + break; + default: + // No need to convert RGBA8888, right order already + if (dst != src) + memcpy(dst, src, numPixels * sizeof(u32)); + break; + } +} + +void TextureCacheVulkan::StartFrame() { + lastBoundTexture = nullptr; + timesInvalidatedAllThisFrame_ = 0; + + if (texelsScaledThisFrame_) { + // INFO_LOG(G3D, "Scaled %i texels", texelsScaledThisFrame_); + } + texelsScaledThisFrame_ = 0; + if (clearCacheNextFrame_) { + Clear(true); + clearCacheNextFrame_ = false; + } else { + Decimate(); + } +} + +static inline u32 MiniHash(const u32 *ptr) { + return ptr[0]; +} + +static inline u32 QuickTexHash(u32 addr, int bufw, int w, int h, GETextureFormat format, TextureCacheVulkan::TexCacheEntry *entry) { + if (h == 512 && entry->maxSeenV < 512 && entry->maxSeenV != 0) { + h = (int)entry->maxSeenV; + } + + const u32 sizeInRAM = (textureBitsPerPixel[format] * bufw * h) / 8; + const u32 *checkp = (const u32 *)Memory::GetPointer(addr); + + return DoQuickTexHash(checkp, sizeInRAM); +} + +void TextureCacheVulkan::UpdateCurrentClut(GEPaletteFormat clutFormat, u32 clutBase, bool clutIndexIsSimple) { + const u32 clutBaseBytes = clutFormat == GE_CMODE_32BIT_ABGR8888 ? (clutBase * sizeof(u32)) : (clutBase * sizeof(u16)); + // Technically, these extra bytes weren't loaded, but hopefully it was loaded earlier. + // If not, we're going to hash random data, which hopefully doesn't cause a performance issue. + // + // TODO: Actually, this seems like a hack. The game can upload part of a CLUT and reference other data. + // clutTotalBytes_ is the last amount uploaded. We should hash clutMaxBytes_, but this will often hash + // unrelated old entries for small palettes. + // Adding clutBaseBytes may just be mitigating this for some usage patterns. + const u32 clutExtendedBytes = std::min(clutTotalBytes_ + clutBaseBytes, clutMaxBytes_); + + clutHash_ = DoReliableHash32((const char *)clutBufRaw_, clutExtendedBytes, 0xC0108888); + + // Avoid a copy when we don't need to convert colors. + if (clutFormat != GE_CMODE_32BIT_ABGR8888) { + const int numColors = clutFormat == GE_CMODE_32BIT_ABGR8888 ? (clutMaxBytes_ / sizeof(u32)) : (clutMaxBytes_ / sizeof(u16)); + ConvertColors(clutBufConverted_, clutBufRaw_, getClutDestFormatVulkan(clutFormat), numColors); + clutBuf_ = clutBufConverted_; + } else { + clutBuf_ = clutBufRaw_; + } + + // Special optimization: fonts typically draw clut4 with just alpha values in a single color. + clutAlphaLinear_ = false; + clutAlphaLinearColor_ = 0; + if (clutFormat == GE_CMODE_16BIT_ABGR4444 && clutIndexIsSimple) { + const u16_le *clut = GetCurrentClut(); + clutAlphaLinear_ = true; + clutAlphaLinearColor_ = clut[15] & 0xFFF0; + for (int i = 0; i < 16; ++i) { + u16 step = clutAlphaLinearColor_ | i; + if (clut[i] != step) { + clutAlphaLinear_ = false; + break; + } + } + } + + clutLastFormat_ = gstate.clutformat; +} + +template +inline const T *TextureCacheVulkan::GetCurrentClut() { + return (const T *)clutBuf_; +} + +inline u32 TextureCacheVulkan::GetCurrentClutHash() { + return clutHash_; +} + +// #define DEBUG_TEXTURES + +#ifdef DEBUG_TEXTURES +bool SetDebugTexture() { + static const int highlightFrames = 30; + + static int numTextures = 0; + static int lastFrames = 0; + static int mostTextures = 1; + + if (lastFrames != gpuStats.numFlips) { + mostTextures = std::max(mostTextures, numTextures); + numTextures = 0; + lastFrames = gpuStats.numFlips; + } + + static GLuint solidTexture = 0; + + bool changed = false; + if (((gpuStats.numFlips / highlightFrames) % mostTextures) == numTextures) { + if (gpuStats.numFlips % highlightFrames == 0) { + NOTICE_LOG(G3D, "Highlighting texture # %d / %d", numTextures, mostTextures); + } + static const u32 solidTextureData[] = { 0x99AA99FF }; + + if (solidTexture == 0) { + glGenTextures(1, &solidTexture); + glBindTexture(GL_TEXTURE_2D, solidTexture); + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + glPixelStorei(GL_PACK_ALIGNMENT, 1); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, solidTextureData); + } else { + glBindTexture(GL_TEXTURE_2D, solidTexture); + } + changed = true; + } + + ++numTextures; + return changed; +} +#endif + +void TextureCacheVulkan::SetTextureFramebuffer(TexCacheEntry *entry, VirtualFramebuffer *framebuffer) { + _dbg_assert_msg_(G3D, framebuffer != nullptr, "Framebuffer must not be null."); + + framebuffer->usageFlags |= FB_USAGE_TEXTURE; + bool useBufferedRendering = g_Config.iRenderingMode != FB_NON_BUFFERED_MODE; + if (useBufferedRendering) { + const GEPaletteFormat clutFormat = gstate.getClutPaletteFormat(); + DepalShader *depal = nullptr; + if ((entry->status & TexCacheEntry::STATUS_DEPALETTIZE) && !g_Config.bDisableSlowFramebufEffects) { + // depal = depalShaderCache_->GetDepalettizeShader(clutFormat, framebuffer->drawnFormat); + } + if (depal) { + const u32 bytesPerColor = clutFormat == GE_CMODE_32BIT_ABGR8888 ? sizeof(u32) : sizeof(u16); + const u32 clutTotalColors = clutMaxBytes_ / bytesPerColor; + + TexCacheEntry::Status alphaStatus = CheckAlpha(clutBuf_, getClutDestFormatVulkan(clutFormat), clutTotalColors, clutTotalColors, 1); + gstate_c.textureFullAlpha = alphaStatus == TexCacheEntry::STATUS_ALPHA_FULL; + gstate_c.textureSimpleAlpha = alphaStatus == TexCacheEntry::STATUS_ALPHA_SIMPLE; + } else { + entry->status &= ~TexCacheEntry::STATUS_DEPALETTIZE; + + gstate_c.textureFullAlpha = gstate.getTextureFormat() == GE_TFMT_5650; + gstate_c.textureSimpleAlpha = gstate_c.textureFullAlpha; + } + + // Keep the framebuffer alive. + framebuffer->last_frame_used = gpuStats.numFlips; + + // We need to force it, since we may have set it on a texture before attaching. + gstate_c.curTextureWidth = framebuffer->bufferWidth; + gstate_c.curTextureHeight = framebuffer->bufferHeight; + gstate_c.curTextureXOffset = fbTexInfo_[entry->addr].xOffset; + gstate_c.curTextureYOffset = fbTexInfo_[entry->addr].yOffset; + gstate_c.needShaderTexClamp = gstate_c.curTextureWidth != (u32)gstate.getTextureWidth(0) || gstate_c.curTextureHeight != (u32)gstate.getTextureHeight(0); + if (gstate_c.curTextureXOffset != 0 || gstate_c.curTextureYOffset != 0) { + gstate_c.needShaderTexClamp = true; + } + + nextTexture_ = entry; + } else { + if (framebuffer->fbo_vk) { + delete framebuffer->fbo_vk; + framebuffer->fbo_vk = 0; + } + gstate_c.needShaderTexClamp = false; + } +} + +void TextureCacheVulkan::ApplyTexture(VkImageView &imageView, VkSampler &sampler) { + if (nextTexture_ == nullptr) { + return; + } + VkCommandBuffer cmd = nullptr; + if (nextTexture_->framebuffer) { + ApplyTextureFramebuffer(cmd, nextTexture_, nextTexture_->framebuffer, imageView, sampler); + } else { + // If the texture is >= 512 pixels tall... + if (nextTexture_->dim >= 0x900) { + // Texture scale/offset and gen modes don't apply in through. + // So we can optimize how much of the texture we look at. + if (gstate.isModeThrough()) { + if (nextTexture_->maxSeenV == 0 && gstate_c.vertBounds.maxV > 0) { + // Let's not hash less than 272, we might use more later and have to rehash. 272 is very common. + nextTexture_->maxSeenV = std::max((u16)272, gstate_c.vertBounds.maxV); + } else if (gstate_c.vertBounds.maxV > nextTexture_->maxSeenV) { + // The max height changed, so we're better off hashing the entire thing. + nextTexture_->maxSeenV = 512; + nextTexture_->status |= TexCacheEntry::STATUS_FREE_CHANGE; + } + } else { + // Otherwise, we need to reset to ensure we use the whole thing. + // Can't tell how much is used. + // TODO: We could tell for texcoord UV gen, and apply scale to max? + nextTexture_->maxSeenV = 512; + } + } + + + // if (nextTexture_->textureName != lastBoundTexture) { + // nextTexture_->vkTex-> + // + + lastBoundTexture = nextTexture_->vkTex; + UpdateSamplingParams(*nextTexture_, false); + } + + nextTexture_ = nullptr; +} + +void TextureCacheVulkan::ApplyTextureFramebuffer(VkCommandBuffer cmd, TexCacheEntry *entry, VirtualFramebuffer *framebuffer, VkImageView &imageView, VkSampler &sampler) { + DepalShader *depal = nullptr; + const GEPaletteFormat clutFormat = gstate.getClutPaletteFormat(); + if ((entry->status & TexCacheEntry::STATUS_DEPALETTIZE) && !g_Config.bDisableSlowFramebufEffects) { + // depal = depalShaderCache_->GetDepalettizeShader(clutFormat, framebuffer->drawnFormat); + } + if (depal) { + // VulkanTexture *clutTexture = depalShaderCache_->GetClutTexture(clutFormat, clutHash_, clutBuf_); + VulkanFramebuffer *depalFBO = framebufferManager_->GetTempFBO(framebuffer->renderWidth, framebuffer->renderHeight, VK_FBO_8888); + + depalFBO->BeginPass(cmd); + + struct Pos { + Pos(float x_, float y_, float z_) : x(x_), y(y_), z(z_) { + } + float x; + float y; + float z; + }; + struct UV { + UV(float u_, float v_) : u(u_), v(v_) { + } + float u; + float v; + }; + + Pos pos[4] = { + { -1, -1, -1 }, + { 1, -1, -1 }, + { 1, 1, -1 }, + { -1, 1, -1 }, + }; + UV uv[4] = { + { 0, 0 }, + { 1, 0 }, + { 1, 1 }, + { 0, 1 }, + }; + static const int indices[4] = { 0, 1, 3, 2 }; + + // If min is not < max, then we don't have values (wasn't set during decode.) + if (gstate_c.vertBounds.minV < gstate_c.vertBounds.maxV) { + const float invWidth = 1.0f / (float)framebuffer->bufferWidth; + const float invHeight = 1.0f / (float)framebuffer->bufferHeight; + // Inverse of half = double. + const float invHalfWidth = invWidth * 2.0f; + const float invHalfHeight = invHeight * 2.0f; + + const int u1 = gstate_c.vertBounds.minU + gstate_c.curTextureXOffset; + const int v1 = gstate_c.vertBounds.minV + gstate_c.curTextureYOffset; + const int u2 = gstate_c.vertBounds.maxU + gstate_c.curTextureXOffset; + const int v2 = gstate_c.vertBounds.maxV + gstate_c.curTextureYOffset; + + const float left = u1 * invHalfWidth - 1.0f; + const float right = u2 * invHalfWidth - 1.0f; + const float top = v1 * invHalfHeight - 1.0f; + const float bottom = v2 * invHalfHeight - 1.0f; + // Points are: BL, BR, TR, TL. + pos[0] = Pos(left, bottom, -1.0f); + pos[1] = Pos(right, bottom, -1.0f); + pos[2] = Pos(right, top, -1.0f); + pos[3] = Pos(left, top, -1.0f); + + // And also the UVs, same order. + const float uvleft = u1 * invWidth; + const float uvright = u2 * invWidth; + const float uvtop = v1 * invHeight; + const float uvbottom = v2 * invHeight; + uv[0] = UV(uvleft, uvbottom); + uv[1] = UV(uvright, uvbottom); + uv[2] = UV(uvright, uvtop); + uv[3] = UV(uvleft, uvtop); + } + + shaderManager_->DirtyLastShader(); + + /* + glUseProgram(depal->program); + + // Restore will rebind all of the state below. + if (gstate_c.Supports(GPU_SUPPORTS_VAO)) { + transformDraw_->BindBuffer(pos, sizeof(pos), uv, sizeof(uv)); + transformDraw_->BindElementBuffer(indices, sizeof(indices)); + } else { + glBindBuffer(GL_ARRAY_BUFFER, 0); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); + } + glEnableVertexAttribArray(depal->a_position); + glEnableVertexAttribArray(depal->a_texcoord0); + + glActiveTexture(GL_TEXTURE3); + glBindTexture(GL_TEXTURE_2D, clutTexture); + glActiveTexture(GL_TEXTURE0); + + framebufferManager_->BindFramebufferColor(GL_TEXTURE0, gstate.getFrameBufRawAddress(), framebuffer, BINDFBCOLOR_SKIP_COPY); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + + glstate.blend.force(false); + glstate.colorMask.force(true, true, true, true); + glstate.scissorTest.force(false); + glstate.cullFace.force(false); + glstate.depthTest.force(false); + glstate.stencilTest.force(false); +#if !defined(USING_GLES2) + glstate.colorLogicOp.force(false); +#endif + glViewport(0, 0, framebuffer->renderWidth, framebuffer->renderHeight); + + if (gstate_c.Supports(GPU_SUPPORTS_VAO)) { + glVertexAttribPointer(depal->a_position, 3, GL_FLOAT, GL_FALSE, 12, 0); + glVertexAttribPointer(depal->a_texcoord0, 2, GL_FLOAT, GL_FALSE, 8, (void *)sizeof(pos)); + glDrawElements(GL_TRIANGLE_STRIP, 4, GL_UNSIGNED_BYTE, 0); + } else { + glVertexAttribPointer(depal->a_position, 3, GL_FLOAT, GL_FALSE, 12, pos); + glVertexAttribPointer(depal->a_texcoord0, 2, GL_FLOAT, GL_FALSE, 8, uv); + glDrawElements(GL_TRIANGLE_STRIP, 4, GL_UNSIGNED_BYTE, indices); + } + glDisableVertexAttribArray(depal->a_position); + glDisableVertexAttribArray(depal->a_texcoord0); + */ + depalFBO->EndPass(cmd); + depalFBO->TransitionToTexture(cmd); + imageView = depalFBO->GetColorImageView(); + } + + /* + imageView = depalFBO->GetColorImageView(); + + SamplerCacheKey samplerKey; + framebufferManager_->RebindFramebuffer(); + SetFramebufferSamplingParams(framebuffer->bufferWidth, framebuffer->bufferHeight, samplerKey); + sampler = GetOrCreateSampler(samplerKey); + */ + lastBoundTexture = nullptr; +} + +bool TextureCacheVulkan::SetOffsetTexture(u32 offset) { + if (g_Config.iRenderingMode != FB_BUFFERED_MODE) { + return false; + } + u32 texaddr = gstate.getTextureAddress(0); + if (!Memory::IsValidAddress(texaddr) || !Memory::IsValidAddress(texaddr + offset)) { + return false; + } + + const u16 dim = gstate.getTextureDimension(0); + u64 cachekey = ((u64)(texaddr & 0x3FFFFFFF) << 32) | dim; + TexCache::iterator iter = cache.find(cachekey); + if (iter == cache.end()) { + return false; + } + TexCacheEntry *entry = &iter->second; + + bool success = false; + for (size_t i = 0, n = fbCache_.size(); i < n; ++i) { + auto framebuffer = fbCache_[i]; + if (AttachFramebuffer(entry, framebuffer->fb_address, framebuffer, offset)) { + success = true; + } + } + + if (success && entry->framebuffer) { + // This will not apply the texture immediately. + SetTextureFramebuffer(entry, entry->framebuffer); + entry->lastFrame = gpuStats.numFlips; + return true; + } + + return false; +} + +void TextureCacheVulkan::SetTexture(VkCommandBuffer cmd, VkImageView &imageView) { +#ifdef DEBUG_TEXTURES + if (SetDebugTexture()) { + // A different texture was bound, let's rebind next time. + lastBoundTexture = nullptr; + return; + } +#endif + + u32 texaddr = gstate.getTextureAddress(0); + if (!Memory::IsValidAddress(texaddr)) { + // Bind a null texture and return. + lastBoundTexture = nullptr; + return; + } + + const u16 dim = gstate.getTextureDimension(0); + int w = gstate.getTextureWidth(0); + int h = gstate.getTextureHeight(0); + + GETextureFormat format = gstate.getTextureFormat(); + if (format >= 11) { + ERROR_LOG_REPORT(G3D, "Unknown texture format %i", format); + // TODO: Better assumption? + format = GE_TFMT_5650; + } + bool hasClut = gstate.isTextureFormatIndexed(); + + // Ignore uncached/kernel when caching. + u64 cachekey = ((u64)(texaddr & 0x3FFFFFFF) << 32) | dim; + u32 cluthash; + if (hasClut) { + if (clutLastFormat_ != gstate.clutformat) { + // We update here because the clut format can be specified after the load. + UpdateCurrentClut(gstate.getClutPaletteFormat(), gstate.getClutIndexStartPos(), gstate.isClutIndexSimple()); + } + cluthash = GetCurrentClutHash() ^ gstate.clutformat; + cachekey ^= cluthash; + } else { + cluthash = 0; + } + + int bufw = GetTextureBufw(0, texaddr, format); + u8 maxLevel = gstate.getTextureMaxLevel(); + + u32 texhash = MiniHash((const u32 *)Memory::GetPointerUnchecked(texaddr)); + u32 fullhash = 0; + + TexCache::iterator iter = cache.find(cachekey); + TexCacheEntry *entry = NULL; + gstate_c.needShaderTexClamp = false; + gstate_c.skipDrawReason &= ~SKIPDRAW_BAD_FB_TEXTURE; + bool replaceImages = false; + + if (iter != cache.end()) { + entry = &iter->second; + // Validate the texture still matches the cache entry. + bool match = entry->Matches(dim, format, maxLevel); + const char *reason = "different params"; + + // Check for FBO - slow! + if (entry->framebuffer) { + if (match) { + if (hasClut && clutRenderAddress_ != 0xFFFFFFFF) { + WARN_LOG_REPORT_ONCE(clutAndTexRender, G3D, "Using rendered texture with rendered CLUT: texfmt=%d, clutfmt=%d", gstate.getTextureFormat(), gstate.getClutPaletteFormat()); + } + + SetTextureFramebuffer(entry, entry->framebuffer); + entry->lastFrame = gpuStats.numFlips; + return; + } else { + // Make sure we re-evaluate framebuffers. + DetachFramebuffer(entry, texaddr, entry->framebuffer); + reason = "detached framebuf"; + match = false; + } + } + + bool rehash = entry->GetHashStatus() == TexCacheEntry::STATUS_UNRELIABLE; + bool doDelete = true; + + // First let's see if another texture with the same address had a hashfail. + if (entry->status & TexCacheEntry::STATUS_CLUT_RECHECK) { + // Always rehash in this case, if one changed the rest all probably did. + rehash = true; + entry->status &= ~TexCacheEntry::STATUS_CLUT_RECHECK; + } else if ((gstate_c.textureChanged & TEXCHANGE_UPDATED) == 0) { + // Okay, just some parameter change - the data didn't change, no need to rehash. + rehash = false; + } + + if (match) { + if (entry->lastFrame != gpuStats.numFlips) { + u32 diff = gpuStats.numFlips - entry->lastFrame; + entry->numFrames++; + + if (entry->framesUntilNextFullHash < diff) { + // Exponential backoff up to 512 frames. Textures are often reused. + if (entry->numFrames > 32) { + // Also, try to add some "randomness" to avoid rehashing several textures the same frame. + entry->framesUntilNextFullHash = std::min(512, entry->numFrames) + (entry->textureName & 15); + } else { + entry->framesUntilNextFullHash = entry->numFrames; + } + rehash = true; + } else { + entry->framesUntilNextFullHash -= diff; + } + } + + // If it's not huge or has been invalidated many times, recheck the whole texture. + if (entry->invalidHint > 180 || (entry->invalidHint > 15 && (dim >> 8) < 9 && (dim & 0xF) < 9)) { + entry->invalidHint = 0; + rehash = true; + } + + bool hashFail = false; + if (texhash != entry->hash) { + fullhash = QuickTexHash(texaddr, bufw, w, h, format, entry); + hashFail = true; + rehash = false; + } + + if (rehash && entry->GetHashStatus() != TexCacheEntry::STATUS_RELIABLE) { + fullhash = QuickTexHash(texaddr, bufw, w, h, format, entry); + if (fullhash != entry->fullhash) { + hashFail = true; + } else { + if (g_Config.bTextureBackoffCache) { + if (entry->GetHashStatus() != TexCacheEntry::STATUS_HASHING && entry->numFrames > TexCacheEntry::FRAMES_REGAIN_TRUST) { + // Reset to STATUS_HASHING. + entry->SetHashStatus(TexCacheEntry::STATUS_HASHING); + entry->status &= ~TexCacheEntry::STATUS_CHANGE_FREQUENT; + } + } else if (entry->numFrames > TEXCACHE_FRAME_CHANGE_FREQUENT_REGAIN_TRUST) { + entry->status &= ~TexCacheEntry::STATUS_CHANGE_FREQUENT; + } + } + } + + if (hashFail) { + match = false; + reason = "hash fail"; + entry->status |= TexCacheEntry::STATUS_UNRELIABLE; + if (entry->numFrames < TEXCACHE_FRAME_CHANGE_FREQUENT) { + if (entry->status & TexCacheEntry::STATUS_FREE_CHANGE) { + entry->status &= ~TexCacheEntry::STATUS_FREE_CHANGE; + } else { + entry->status |= TexCacheEntry::STATUS_CHANGE_FREQUENT; + } + } + entry->numFrames = 0; + + // Don't give up just yet. Let's try the secondary cache if it's been invalidated before. + // If it's failed a bunch of times, then the second cache is just wasting time and VRAM. + if (g_Config.bTextureSecondaryCache) { + if (entry->numInvalidated > 2 && entry->numInvalidated < 128 && !lowMemoryMode_) { + u64 secondKey = fullhash | (u64)cluthash << 32; + TexCache::iterator secondIter = secondCache.find(secondKey); + if (secondIter != secondCache.end()) { + TexCacheEntry *secondEntry = &secondIter->second; + if (secondEntry->Matches(dim, format, maxLevel)) { + // Reset the numInvalidated value lower, we got a match. + if (entry->numInvalidated > 8) { + --entry->numInvalidated; + } + entry = secondEntry; + match = true; + } + } else { + secondKey = entry->fullhash | ((u64)entry->cluthash << 32); + secondCacheSizeEstimate_ += EstimateTexMemoryUsage(entry); + secondCache[secondKey] = *entry; + doDelete = false; + } + } + } + } + } + + if (match && (entry->status & TexCacheEntry::STATUS_TO_SCALE) && g_Config.iTexScalingLevel != 1 && texelsScaledThisFrame_ < TEXCACHE_MAX_TEXELS_SCALED) { + if ((entry->status & TexCacheEntry::STATUS_CHANGE_FREQUENT) == 0) { + // INFO_LOG(G3D, "Reloading texture to do the scaling we skipped.."); + match = false; + reason = "scaling"; + } + } + + if (match) { + // TODO: Mark the entry reliable if it's been safe for long enough? + //got one! + entry->lastFrame = gpuStats.numFlips; + if (entry->vkTex != lastBoundTexture) { + gstate_c.textureFullAlpha = entry->GetAlphaStatus() == TexCacheEntry::STATUS_ALPHA_FULL; + gstate_c.textureSimpleAlpha = entry->GetAlphaStatus() != TexCacheEntry::STATUS_ALPHA_UNKNOWN; + } + nextTexture_ = entry; + VERBOSE_LOG(G3D, "Texture at %08x Found in Cache, applying", texaddr); + return; //Done! + } else { + cacheSizeEstimate_ -= EstimateTexMemoryUsage(entry); + entry->numInvalidated++; + gpuStats.numTextureInvalidations++; + DEBUG_LOG(G3D, "Texture different or overwritten, reloading at %08x: %s", texaddr, reason); + if (doDelete) { + if (entry->maxLevel == maxLevel && entry->dim == gstate.getTextureDimension(0) && entry->format == format && g_Config.iTexScalingLevel == 1) { + // Actually, if size and number of levels match, let's try to avoid deleting and recreating. + // Instead, let's use glTexSubImage to replace the images. + replaceImages = true; + } else { + if (entry->vkTex == lastBoundTexture) { + lastBoundTexture = nullptr; + } + delete entry->vkTex; + } + } + // Clear the reliable bit if set. + if (entry->GetHashStatus() == TexCacheEntry::STATUS_RELIABLE) { + entry->SetHashStatus(TexCacheEntry::STATUS_HASHING); + } + + // Also, mark any textures with the same address but different clut. They need rechecking. + if (cluthash != 0) { + const u64 cachekeyMin = (u64)(texaddr & 0x3FFFFFFF) << 32; + const u64 cachekeyMax = cachekeyMin + (1ULL << 32); + for (auto it = cache.lower_bound(cachekeyMin), end = cache.upper_bound(cachekeyMax); it != end; ++it) { + if (it->second.cluthash != cluthash) { + it->second.status |= TexCacheEntry::STATUS_CLUT_RECHECK; + } + } + } + } + } else { + VERBOSE_LOG(G3D, "No texture in cache, decoding..."); + TexCacheEntry entryNew = { 0 }; + cache[cachekey] = entryNew; + + if (hasClut && clutRenderAddress_ != 0xFFFFFFFF) { + WARN_LOG_REPORT_ONCE(clutUseRender, G3D, "Using texture with rendered CLUT: texfmt=%d, clutfmt=%d", gstate.getTextureFormat(), gstate.getClutPaletteFormat()); + } + + entry = &cache[cachekey]; + if (g_Config.bTextureBackoffCache) { + entry->status = TexCacheEntry::STATUS_HASHING; + } else { + entry->status = TexCacheEntry::STATUS_UNRELIABLE; + } + } + + if ((bufw == 0 || (gstate.texbufwidth[0] & 0xf800) != 0) && texaddr >= PSP_GetKernelMemoryEnd()) { + ERROR_LOG_REPORT(G3D, "Texture with unexpected bufw (full=%d)", gstate.texbufwidth[0] & 0xffff); + // Proceeding here can cause a crash. + return; + } + + // We have to decode it, let's setup the cache entry first. + entry->addr = texaddr; + entry->hash = texhash; + entry->format = format; + entry->lastFrame = gpuStats.numFlips; + entry->framebuffer = 0; + entry->maxLevel = maxLevel; + entry->lodBias = 0.0f; + + entry->dim = gstate.getTextureDimension(0); + entry->bufw = bufw; + + // This would overestimate the size in many case so we underestimate instead + // to avoid excessive clearing caused by cache invalidations. + entry->sizeInRAM = (textureBitsPerPixel[format] * bufw * h / 2) / 8; + + entry->fullhash = fullhash == 0 ? QuickTexHash(texaddr, bufw, w, h, format, entry) : fullhash; + entry->cluthash = cluthash; + + entry->status &= ~TexCacheEntry::STATUS_ALPHA_MASK; + + gstate_c.curTextureWidth = w; + gstate_c.curTextureHeight = h; + + // For the estimate, we assume cluts always point to 8888 for simplicity. + cacheSizeEstimate_ += EstimateTexMemoryUsage(entry); + + entry->vkTex = new CachedTextureVulkan(); + + // Before we go reading the texture from memory, let's check for render-to-texture. + for (size_t i = 0, n = fbCache_.size(); i < n; ++i) { + auto framebuffer = fbCache_[i]; + AttachFramebuffer(entry, framebuffer->fb_address, framebuffer); + } + + // If we ended up with a framebuffer, attach it - no texture decoding needed. + if (entry->framebuffer) { + SetTextureFramebuffer(entry, entry->framebuffer); + entry->lastFrame = gpuStats.numFlips; + return; + } + + lastBoundTexture = entry->vkTex; + + // Adjust maxLevel to actually present levels.. + bool badMipSizes = false; + for (u32 i = 0; i <= maxLevel; i++) { + // If encountering levels pointing to nothing, adjust max level. + u32 levelTexaddr = gstate.getTextureAddress(i); + if (!Memory::IsValidAddress(levelTexaddr)) { + maxLevel = i - 1; + break; + } + + if (i > 0 && gstate_c.Supports(GPU_SUPPORTS_TEXTURE_LOD_CONTROL)) { + int tw = gstate.getTextureWidth(i); + int th = gstate.getTextureHeight(i); + if (tw != 1 && tw != (gstate.getTextureWidth(i - 1) >> 1)) + badMipSizes = true; + else if (th != 1 && th != (gstate.getTextureHeight(i - 1) >> 1)) + badMipSizes = true; + } + } + + // In addition, simply don't load more than level 0 if g_Config.bMipMap is false. + if (!g_Config.bMipMap) { + maxLevel = 0; + } + + // If GLES3 is available, we can preallocate the storage, which makes texture loading more efficient. + VkFormat dstFmt = GetDestFormat(format, gstate.getClutPaletteFormat()); + + int scaleFactor; + // Auto-texture scale upto 5x rendering resolution + if (g_Config.iTexScalingLevel == 0) { + scaleFactor = g_Config.iInternalResolution; + if (scaleFactor == 0) { + scaleFactor = (PSP_CoreParameter().renderWidth + 479) / 480; + } + + // Mobile devices don't get the higher scale factors, too expensive. Very rough way to decide though... + if (!gstate_c.Supports(GPU_IS_MOBILE)) { + bool supportNpot = gstate_c.Supports(GPU_SUPPORTS_OES_TEXTURE_NPOT); + scaleFactor = std::min(supportNpot ? 5 : 4, scaleFactor); + if (!supportNpot && scaleFactor == 3) { + scaleFactor = 2; + } + } else { + scaleFactor = std::min(gstate_c.Supports(GPU_SUPPORTS_OES_TEXTURE_NPOT) ? 3 : 2, scaleFactor); + } + } else { + scaleFactor = g_Config.iTexScalingLevel; + } + + // Rachet down scale factor in low-memory mode. + if (lowMemoryMode_) { + // Keep it even, though, just in case of npot troubles. + scaleFactor = scaleFactor > 4 ? 4 : (scaleFactor > 2 ? 2 : 1); + } + + // Don't scale the PPGe texture. + if (entry->addr > 0x05000000 && entry->addr < 0x08800000) + scaleFactor = 1; + if ((entry->status & TexCacheEntry::STATUS_CHANGE_FREQUENT) != 0) { + // Remember for later that we /wanted/ to scale this texture. + entry->status |= TexCacheEntry::STATUS_TO_SCALE; + scaleFactor = 1; + } + + if (scaleFactor != 1) { + if (texelsScaledThisFrame_ >= TEXCACHE_MAX_TEXELS_SCALED) { + entry->status |= TexCacheEntry::STATUS_TO_SCALE; + scaleFactor = 1; + } else { + entry->status &= ~TexCacheEntry::STATUS_TO_SCALE; + texelsScaledThisFrame_ += w * h; + } + } + + // GLES2 doesn't have support for a "Max lod" which is critical as PSP games often + // don't specify mips all the way down. As a result, we either need to manually generate + // the bottom few levels or rely on OpenGL's autogen mipmaps instead, which might not + // be as good quality as the game's own (might even be better in some cases though). + + // Always load base level texture here + LoadTextureLevel(*entry, 0, replaceImages, scaleFactor, dstFmt); + + // Mipmapping only enable when texture scaling disable + /* + if (maxLevel > 0 && scaleFactor == 1) { + if (gstate_c.Supports(GPU_SUPPORTS_TEXTURE_LOD_CONTROL)) { + if (badMipSizes) { + // WARN_LOG(G3D, "Bad mipmap for texture sized %dx%dx%d - autogenerating", w, h, (int)format); + glGenerateMipmap(GL_TEXTURE_2D); + } else { + for (int i = 1; i <= maxLevel; i++) { + LoadTextureLevel(*entry, i, replaceImages, scaleFactor, dstFmt); + } + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, maxLevel); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_LOD, (float)maxLevel); + } + } else { + glGenerateMipmap(GL_TEXTURE_2D); + } + } else if (gstate_c.Supports(GPU_SUPPORTS_TEXTURE_LOD_CONTROL)) { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0); + } + */ + gstate_c.textureFullAlpha = entry->GetAlphaStatus() == TexCacheEntry::STATUS_ALPHA_FULL; + gstate_c.textureSimpleAlpha = entry->GetAlphaStatus() != TexCacheEntry::STATUS_ALPHA_UNKNOWN; + + // This will rebind it, but that's okay. + nextTexture_ = entry; + UpdateSamplingParams(*entry, true); + + // entry->vkTex->imageView = CreateImageView + + imageView = entry->vkTex->imageView; +} + +VkFormat TextureCacheVulkan::GetDestFormat(GETextureFormat format, GEPaletteFormat clutFormat) const { + switch (format) { + case GE_TFMT_CLUT4: + case GE_TFMT_CLUT8: + case GE_TFMT_CLUT16: + case GE_TFMT_CLUT32: + return getClutDestFormatVulkan(clutFormat); + case GE_TFMT_4444: + return VK_FORMAT_B4G4R4A4_UNORM_PACK16; + case GE_TFMT_5551: + return VK_FORMAT_A1R5G5B5_UNORM_PACK16; + case GE_TFMT_5650: + return VK_FORMAT_R5G6B5_UNORM_PACK16; + case GE_TFMT_8888: + case GE_TFMT_DXT1: + case GE_TFMT_DXT3: + case GE_TFMT_DXT5: + default: + return VK_FORMAT_R8G8B8A8_UNORM; + } +} + +void *TextureCacheVulkan::DecodeTextureLevel(GETextureFormat format, GEPaletteFormat clutformat, int level, u32 &texByteAlign, VkFormat dstFmt, int scaleFactor, int *bufwout) { + void *finalBuf = NULL; + + u32 texaddr = gstate.getTextureAddress(level); + bool swizzled = gstate.isTextureSwizzled(); + if ((texaddr & 0x00600000) != 0 && Memory::IsVRAMAddress(texaddr)) { + // This means it's in a mirror, possibly a swizzled mirror. Let's report. + WARN_LOG_REPORT_ONCE(texmirror, G3D, "Decoding texture from VRAM mirror at %08x swizzle=%d", texaddr, swizzled ? 1 : 0); + if ((texaddr & 0x00200000) == 0x00200000) { + // Technically 2 and 6 are slightly different, but this is better than nothing probably. + swizzled = !swizzled; + } + // Note that (texaddr & 0x00600000) == 0x00600000 is very likely to be depth texturing. + } + + int bufw = GetTextureBufw(level, texaddr, format); + if (bufwout) + *bufwout = bufw; + int w = gstate.getTextureWidth(level); + int h = gstate.getTextureHeight(level); + const u8 *texptr = Memory::GetPointer(texaddr); + + switch (format) { + case GE_TFMT_CLUT4: + { + const bool mipmapShareClut = gstate.isClutSharedForMipmaps(); + const int clutSharingOffset = mipmapShareClut ? 0 : level * 16; + + switch (clutformat) { + case GE_CMODE_16BIT_BGR5650: + case GE_CMODE_16BIT_ABGR5551: + case GE_CMODE_16BIT_ABGR4444: + { + tmpTexBuf16.resize(std::max(bufw, w) * h); + tmpTexBufRearrange.resize(std::max(bufw, w) * h); + const u16 *clut = GetCurrentClut() + clutSharingOffset; + texByteAlign = 2; + if (!swizzled) { + if (clutAlphaLinear_ && mipmapShareClut) { + DeIndexTexture4Optimal(tmpTexBuf16.data(), texptr, bufw * h, clutAlphaLinearColor_); + } else { + DeIndexTexture4(tmpTexBuf16.data(), texptr, bufw * h, clut); + } + } else { + tmpTexBuf32.resize(std::max(bufw, w) * h); + UnswizzleFromMem(texptr, bufw, h, 0); + if (clutAlphaLinear_ && mipmapShareClut) { + DeIndexTexture4Optimal(tmpTexBuf16.data(), (const u8 *)tmpTexBuf32.data(), bufw * h, clutAlphaLinearColor_); + } else { + DeIndexTexture4(tmpTexBuf16.data(), (const u8 *)tmpTexBuf32.data(), bufw * h, clut); + } + } + finalBuf = tmpTexBuf16.data(); + } + break; + + case GE_CMODE_32BIT_ABGR8888: + { + tmpTexBuf32.resize(std::max(bufw, w) * h); + tmpTexBufRearrange.resize(std::max(bufw, w) * h); + const u32 *clut = GetCurrentClut() + clutSharingOffset; + if (!swizzled) { + DeIndexTexture4(tmpTexBuf32.data(), texptr, bufw * h, clut); + finalBuf = tmpTexBuf32.data(); + } else { + UnswizzleFromMem(texptr, bufw, h, 0); + // Let's reuse tmpTexBuf16, just need double the space. + tmpTexBuf16.resize(std::max(bufw, w) * h * 2); + DeIndexTexture4((u32 *)tmpTexBuf16.data(), (u8 *)tmpTexBuf32.data(), bufw * h, clut); + finalBuf = tmpTexBuf16.data(); + } + } + break; + + default: + ERROR_LOG_REPORT(G3D, "Unknown CLUT4 texture mode %d", gstate.getClutPaletteFormat()); + return NULL; + } + } + break; + + case GE_TFMT_CLUT8: + texByteAlign = texByteAlignMap[gstate.getClutPaletteFormat()]; + finalBuf = ReadIndexedTex(level, texptr, 1, dstFmt, bufw); + break; + + case GE_TFMT_CLUT16: + texByteAlign = texByteAlignMap[gstate.getClutPaletteFormat()]; + finalBuf = ReadIndexedTex(level, texptr, 2, dstFmt, bufw); + break; + + case GE_TFMT_CLUT32: + texByteAlign = texByteAlignMap[gstate.getClutPaletteFormat()]; + finalBuf = ReadIndexedTex(level, texptr, 4, dstFmt, bufw); + break; + + case GE_TFMT_4444: + case GE_TFMT_5551: + case GE_TFMT_5650: + texByteAlign = 2; + + if (!swizzled) { + int len = std::max(bufw, w) * h; + tmpTexBuf16.resize(len); + tmpTexBufRearrange.resize(len); + finalBuf = tmpTexBuf16.data(); + ConvertColors(finalBuf, texptr, dstFmt, bufw * h); + } else { + tmpTexBuf32.resize(std::max(bufw, w) * h); + finalBuf = UnswizzleFromMem(texptr, bufw, h, 2); + ConvertColors(finalBuf, finalBuf, dstFmt, bufw * h); + } + break; + + case GE_TFMT_8888: + if (!swizzled) { + // Special case: if we don't need to deal with packing, we don't need to copy. + if ((scaleFactor == 1 && gstate_c.Supports(GPU_SUPPORTS_UNPACK_SUBIMAGE)) || w == bufw) { + finalBuf = (void *)texptr; + } else { + tmpTexBuf32.resize(std::max(bufw, w) * h); + tmpTexBufRearrange.resize(std::max(bufw, w) * h); + finalBuf = tmpTexBuf32.data(); + ConvertColors(finalBuf, texptr, dstFmt, bufw * h); + } + } else { + tmpTexBuf32.resize(std::max(bufw, w) * h); + finalBuf = UnswizzleFromMem(texptr, bufw, h, 4); + ConvertColors(finalBuf, finalBuf, dstFmt, bufw * h); + } + break; + + case GE_TFMT_DXT1: + { + int minw = std::min(bufw, w); + tmpTexBuf32.resize(std::max(bufw, w) * h); + tmpTexBufRearrange.resize(std::max(bufw, w) * h); + u32 *dst = tmpTexBuf32.data(); + DXT1Block *src = (DXT1Block*)texptr; + + for (int y = 0; y < h; y += 4) { + u32 blockIndex = (y / 4) * (bufw / 4); + for (int x = 0; x < minw; x += 4) { + DecodeDXT1Block(dst + bufw * y + x, src + blockIndex, bufw); + blockIndex++; + } + } + finalBuf = tmpTexBuf32.data(); + ConvertColors(finalBuf, finalBuf, dstFmt, bufw * h); + w = (w + 3) & ~3; + } + break; + + case GE_TFMT_DXT3: + { + int minw = std::min(bufw, w); + tmpTexBuf32.resize(std::max(bufw, w) * h); + tmpTexBufRearrange.resize(std::max(bufw, w) * h); + u32 *dst = tmpTexBuf32.data(); + DXT3Block *src = (DXT3Block*)texptr; + + for (int y = 0; y < h; y += 4) { + u32 blockIndex = (y / 4) * (bufw / 4); + for (int x = 0; x < minw; x += 4) { + DecodeDXT3Block(dst + bufw * y + x, src + blockIndex, bufw); + blockIndex++; + } + } + w = (w + 3) & ~3; + finalBuf = tmpTexBuf32.data(); + ConvertColors(finalBuf, finalBuf, dstFmt, bufw * h); + } + break; + + case GE_TFMT_DXT5: + { + int minw = std::min(bufw, w); + tmpTexBuf32.resize(std::max(bufw, w) * h); + tmpTexBufRearrange.resize(std::max(bufw, w) * h); + u32 *dst = tmpTexBuf32.data(); + DXT5Block *src = (DXT5Block*)texptr; + + for (int y = 0; y < h; y += 4) { + u32 blockIndex = (y / 4) * (bufw / 4); + for (int x = 0; x < minw; x += 4) { + DecodeDXT5Block(dst + bufw * y + x, src + blockIndex, bufw); + blockIndex++; + } + } + w = (w + 3) & ~3; + finalBuf = tmpTexBuf32.data(); + ConvertColors(finalBuf, finalBuf, dstFmt, bufw * h); + } + break; + + default: + ERROR_LOG_REPORT(G3D, "Unknown Texture Format %d!!!", format); + return NULL; + } + + if (!finalBuf) { + ERROR_LOG_REPORT(G3D, "NO finalbuf! Will crash!"); + } + + if (!(scaleFactor == 1 && gstate_c.Supports(GPU_SUPPORTS_UNPACK_SUBIMAGE)) && w != bufw) { + int pixelSize; + switch (dstFmt) { + case VK_FORMAT_R4G4B4A4_UNORM_PACK16: + case VK_FORMAT_R5G6B5_UNORM_PACK16: + case VK_FORMAT_A1R5G5B5_UNORM_PACK16: + pixelSize = 2; + break; + default: + pixelSize = 4; + break; + } + + // Need to rearrange the buffer to simulate GL_UNPACK_ROW_LENGTH etc. + finalBuf = RearrangeBuf(finalBuf, bufw * pixelSize, w * pixelSize, h); + } + + return finalBuf; +} + +TextureCacheVulkan::TexCacheEntry::Status TextureCacheVulkan::CheckAlpha(const u32 *pixelData, VkFormat dstFmt, int stride, int w, int h) { + CheckAlphaResult res; + switch (dstFmt) { + case VK_FORMAT_R4G4B4A4_UNORM_PACK16: + res = CheckAlphaABGR4444Basic(pixelData, stride, w, h); + break; + case VK_FORMAT_A1R5G5B5_UNORM_PACK16: + res = CheckAlphaABGR1555Basic(pixelData, stride, w, h); + break; + case VK_FORMAT_R5G6B5_UNORM_PACK16: + // Never has any alpha. + res = CHECKALPHA_FULL; + break; + default: + res = CheckAlphaRGBA8888Basic(pixelData, stride, w, h); + break; + } + + return (TexCacheEntry::Status)res; +} + +void TextureCacheVulkan::LoadTextureLevel(TexCacheEntry &entry, int level, bool replaceImages, int scaleFactor, VkFormat dstFmt) { + int w = gstate.getTextureWidth(level); + int h = gstate.getTextureHeight(level); + u32 *pixelData; + { + PROFILE_THIS_SCOPE("decodetex"); + + // TODO: only do this once + u32 texByteAlign = 1; + + GEPaletteFormat clutformat = gstate.getClutPaletteFormat(); + int bufw; + void *finalBuf = DecodeTextureLevel(GETextureFormat(entry.format), clutformat, level, texByteAlign, dstFmt, scaleFactor, &bufw); + if (finalBuf == NULL) { + return; + } + + gpuStats.numTexturesDecoded++; + + pixelData = (u32 *)finalBuf; + if (scaleFactor > 1) { + u32 fmt = dstFmt; + scaler.Scale(pixelData, fmt, w, h, scaleFactor); + dstFmt = (VkFormat)fmt; + } + + if ((entry.status & TexCacheEntry::STATUS_CHANGE_FREQUENT) == 0) { + TexCacheEntry::Status alphaStatus = CheckAlpha(pixelData, dstFmt, bufw, w, h); + entry.SetAlphaStatus(alphaStatus, level); + } else { + entry.SetAlphaStatus(TexCacheEntry::STATUS_ALPHA_UNKNOWN); + } + } + + /* + GLuint components = dstFmt == GL_UNSIGNED_SHORT_5_6_5 ? GL_RGB : GL_RGBA; + + GLuint components2 = components; + + if (replaceImages) { + PROFILE_THIS_SCOPE("repltex"); + glTexSubImage2D(GL_TEXTURE_2D, level, 0, 0, w, h, components2, dstFmt, pixelData); + } else { + PROFILE_THIS_SCOPE("loadtex"); + glTexImage2D(GL_TEXTURE_2D, level, components, w, h, 0, components2, dstFmt, pixelData); + if (!lowMemoryMode_) { + GLenum err = glGetError(); + if (err == GL_OUT_OF_MEMORY) { + WARN_LOG_REPORT(G3D, "Texture cache ran out of GPU memory; switching to low memory mode"); + lowMemoryMode_ = true; + decimationCounter_ = 0; + Decimate(); + // Try again, now that we've cleared out textures in lowMemoryMode_. + glTexImage2D(GL_TEXTURE_2D, level, components, w, h, 0, components2, dstFmt, pixelData); + + I18NCategory *err = GetI18NCategory("Error"); + if (scaleFactor > 1) { + osm.Show(err->T("Warning: Video memory FULL, reducing upscaling and switching to slow caching mode"), 2.0f); + } else { + osm.Show(err->T("Warning: Video memory FULL, switching to slow caching mode"), 2.0f); + } + } else if (err != GL_NO_ERROR) { + // We checked the err anyway, might as well log if there is one. + WARN_LOG(G3D, "Got an error in texture upload: %08x", err); + } + } + } + */ } diff --git a/GPU/Vulkan/TextureCacheVulkan.h b/GPU/Vulkan/TextureCacheVulkan.h index 64f2c5bbd1..49edc5222d 100644 --- a/GPU/Vulkan/TextureCacheVulkan.h +++ b/GPU/Vulkan/TextureCacheVulkan.h @@ -17,22 +17,126 @@ #pragma once -#include "GPU/Common/TextureCacheCommon.h" +#include + +#include "Globals.h" +#include "GPU/GPUInterface.h" #include "GPU/GPUState.h" +#include "GPU/Vulkan/TextureScalerVulkan.h" +#include "GPU/Common/TextureCacheCommon.h" + +struct VirtualFramebuffer; +class FramebufferManagerVulkan; +class DepalShaderCacheVulkan; +class ShaderManagerVulkan; +class DrawEngineVulkan; + +class VulkanContext; +struct SamplerCacheKey; class TextureCacheVulkan : public TextureCacheCommon { public: - bool SetOffsetTexture(u32 offset) override { - return false; + TextureCacheVulkan(VulkanContext *vulkan); + ~TextureCacheVulkan(); + + void SetTexture(VkCommandBuffer cmd, VkImageView &imageView); + virtual bool SetOffsetTexture(u32 offset) override; + + void Clear(bool delete_them); + void StartFrame(); + void Invalidate(u32 addr, int size, GPUInvalidationType type); + void InvalidateAll(GPUInvalidationType type); + void ClearNextFrame(); + + void SetFramebufferManager(FramebufferManagerVulkan *fbManager) { + framebufferManager_ = fbManager; } + void SetDepalShaderCache(DepalShaderCacheVulkan *dpCache) { + depalShaderCache_ = dpCache; + } + void SetShaderManager(ShaderManagerVulkan *sm) { + shaderManager_ = sm; + } + void SetTransformDrawEngine(DrawEngineVulkan *td) { + transformDraw_ = td; + } + + size_t NumLoadedTextures() const { + return cache.size(); + } + + void ForgetLastTexture() { + lastBoundTexture = nullptr; + gstate_c.textureChanged |= TEXCHANGE_PARAMSONLY; + } + + void ApplyTexture(VkImageView &imageView, VkSampler &sampler); + bool DecodeTexture(u8 *dest, const GPUgstate &state) { return false; } - bool AttachFramebuffer(TexCacheEntry *entry, u32 address, VirtualFramebuffer *framebuffer, u32 texaddrOffset = 0) override; - void DetachFramebuffer(TexCacheEntry *entry, u32 address, VirtualFramebuffer *framebuffer) override; - void DownloadFramebufferForClut(u32 clutAddr, u32 bytes) override { } + +private: + void Decimate(); // Run this once per frame to get rid of old textures. + void DeleteTexture(TexCache::iterator it); + void *ReadIndexedTex(int level, const u8 *texptr, int bytesPerIndex, VkFormat dstFmt, int bufw); + void UpdateSamplingParams(TexCacheEntry &entry, bool force); + void LoadTextureLevel(TexCacheEntry &entry, int level, bool replaceImages, int scaleFactor, VkFormat dstFmt); + VkFormat GetDestFormat(GETextureFormat format, GEPaletteFormat clutFormat) const; + void *DecodeTextureLevel(GETextureFormat format, GEPaletteFormat clutformat, int level, u32 &texByteAlign, VkFormat dstFmt, int scaleFactor, int *bufw = 0); + TexCacheEntry::Status CheckAlpha(const u32 *pixelData, VkFormat dstFmt, int stride, int w, int h); + template + const T *GetCurrentClut(); + u32 GetCurrentClutHash(); + void UpdateCurrentClut(GEPaletteFormat clutFormat, u32 clutBase, bool clutIndexIsSimple); + bool AttachFramebuffer(TexCacheEntry *entry, u32 address, VirtualFramebuffer *framebuffer, u32 texaddrOffset = 0) override; + void DetachFramebuffer(TexCacheEntry *entry, u32 address, VirtualFramebuffer *framebuffer) override; + void SetTextureFramebuffer(TexCacheEntry *entry, VirtualFramebuffer *framebuffer); + void ApplyTextureFramebuffer(VkCommandBuffer cmd, TexCacheEntry *entry, VirtualFramebuffer *framebuffer, VkImageView &image, VkSampler &sampler); + void SetFramebufferSamplingParams(u16 bufferWidth, u16 bufferHeight, SamplerCacheKey &key); + + VulkanContext *vulkan_; + + TexCache secondCache; + std::vector nameCache_; + u32 cacheSizeEstimate_; + u32 secondCacheSizeEstimate_; + + // Separate to keep main texture cache size down. + struct AttachedFramebufferInfo { + u32 xOffset; + u32 yOffset; + }; + std::map fbTexInfo_; + void AttachFramebufferValid(TexCacheEntry *entry, VirtualFramebuffer *framebuffer, const AttachedFramebufferInfo &fbInfo); + void AttachFramebufferInvalid(TexCacheEntry *entry, VirtualFramebuffer *framebuffer, const AttachedFramebufferInfo &fbInfo); + + bool clearCacheNextFrame_; + bool lowMemoryMode_; + + TextureScalerVulkan scaler; + + u32 *clutBuf_; + u32 clutHash_; + // True if the clut is just alpha values in the same order (RGBA4444-bit only.) + bool clutAlphaLinear_; + u16 clutAlphaLinearColor_; + + CachedTextureVulkan *lastBoundTexture; + float maxAnisotropyLevel; + + int decimationCounter_; + int texelsScaledThisFrame_; + int timesInvalidatedAllThisFrame_; + + FramebufferManagerVulkan *framebufferManager_; + DepalShaderCacheVulkan *depalShaderCache_; + ShaderManagerVulkan *shaderManager_; + DrawEngineVulkan *transformDraw_; }; + +VkFormat getClutDestFormatVulkan(GEPaletteFormat format); diff --git a/GPU/Vulkan/TextureScalerVulkan.cpp b/GPU/Vulkan/TextureScalerVulkan.cpp new file mode 100644 index 0000000000..267538846c --- /dev/null +++ b/GPU/Vulkan/TextureScalerVulkan.cpp @@ -0,0 +1,62 @@ +// Copyright (c) 2012- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#if _MSC_VER == 1700 +// Has to be included before TextureScaler.h, else we get those std::bind errors in VS2012.. +#include "../native/base/basictypes.h" +#endif + +#include +#include "gfx/gl_common.h" + +#include "GPU/Common/TextureScalerCommon.h" +#include "GPU/Vulkan/TextureScalerVulkan.h" +#include "Common/ColorConv.h" +#include "Common/Log.h" +#include "Common/ThreadPools.h" + +int TextureScalerVulkan::BytesPerPixel(u32 format) { + return (format == GL_UNSIGNED_BYTE) ? 4 : 2; +} + +u32 TextureScalerVulkan::Get8888Format() { + return GL_UNSIGNED_BYTE; +} + +void TextureScalerVulkan::ConvertTo8888(u32 format, u32* source, u32* &dest, int width, int height) { + switch (format) { + case GL_UNSIGNED_BYTE: + dest = source; // already fine + break; + + case GL_UNSIGNED_SHORT_4_4_4_4: + GlobalThreadPool::Loop(std::bind(&convert4444_gl, (u16*)source, dest, width, placeholder::_1, placeholder::_2), 0, height); + break; + + case GL_UNSIGNED_SHORT_5_6_5: + GlobalThreadPool::Loop(std::bind(&convert565_gl, (u16*)source, dest, width, placeholder::_1, placeholder::_2), 0, height); + break; + + case GL_UNSIGNED_SHORT_5_5_5_1: + GlobalThreadPool::Loop(std::bind(&convert5551_gl, (u16*)source, dest, width, placeholder::_1, placeholder::_2), 0, height); + break; + + default: + dest = source; + ERROR_LOG(G3D, "iXBRZTexScaling: unsupported texture format"); + } +} diff --git a/GPU/Vulkan/TextureScalerVulkan.h b/GPU/Vulkan/TextureScalerVulkan.h new file mode 100644 index 0000000000..abb4dc4960 --- /dev/null +++ b/GPU/Vulkan/TextureScalerVulkan.h @@ -0,0 +1,27 @@ +// Copyright (c) 2012- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#pragma once + +#include "Common/CommonTypes.h" +#include "GPU/Common/TextureScalerCommon.h" + +class TextureScalerVulkan : public TextureScaler { + void ConvertTo8888(u32 format, u32* source, u32* &dest, int width, int height) override; + int BytesPerPixel(u32 format) override; + u32 Get8888Format() override; +}; diff --git a/ext/native/thin3d/VulkanContext.cpp b/ext/native/thin3d/VulkanContext.cpp index 0af8e5ddd8..f94aa06273 100644 --- a/ext/native/thin3d/VulkanContext.cpp +++ b/ext/native/thin3d/VulkanContext.cpp @@ -1672,3 +1672,22 @@ const char *VulkanResultToString(VkResult res) { void VulkanAssertImpl(VkResult check, const char *function, const char *file, int line) { const char *error = "(none)"; } + +void VulkanFramebuffer::Create(VulkanContext *vulkan, int w, int h, VkFormat format) { + +} +// void TransitionToImage() + +void VulkanFramebuffer::BeginPass(VkCommandBuffer cmd) { + +} +void VulkanFramebuffer::EndPass(VkCommandBuffer cmd) { + +} +void VulkanFramebuffer::TransitionToTexture(VkCommandBuffer cmd) { + +} + +VkImageView VulkanFramebuffer::GetColorImageView() { + return nullptr; +} diff --git a/ext/native/thin3d/VulkanContext.h b/ext/native/thin3d/VulkanContext.h index 876d20c213..cd6fefdd32 100644 --- a/ext/native/thin3d/VulkanContext.h +++ b/ext/native/thin3d/VulkanContext.h @@ -337,6 +337,24 @@ private: bool needStaging; }; +// Placeholder + +class VulkanFramebuffer { +public: + void Create(VulkanContext *vulkan, int w, int h, VkFormat format); + // void TransitionToImage() + + void BeginPass(VkCommandBuffer cmd); + void EndPass(VkCommandBuffer cmd); + void TransitionToTexture(VkCommandBuffer cmd); + + VkImageView GetColorImageView(); + +private: + VkImage image_; + VkFramebuffer framebuffer_; +}; + // Use these to push vertex, index and uniform data. // TODO: Make it possible to suballocate pushbuffers from a large DeviceMemory block. // TODO: Make this dynamically grow by chaining new buffers in the future. From 4063f7e0db232188370625524be57b039e1a84d5 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Tue, 5 Jan 2016 21:18:43 +0100 Subject: [PATCH 017/116] Fill out GPU_Vulkan.cpp with what's mostly a copy of GLES_GPU.cpp --- Common/GraphicsContext.h | 3 + Core/System.cpp | 3 + GPU/GPU.cpp | 5 +- GPU/GPU.vcxproj | 1 + GPU/GPU.vcxproj.filters | 1 + GPU/GPUState.h | 1 + GPU/Vulkan/DepalettizeShaderVulkan.cpp | 47 + GPU/Vulkan/DepalettizeShaderVulkan.h | 15 +- GPU/Vulkan/FramebufferVulkan.cpp | 26 + GPU/Vulkan/FramebufferVulkan.h | 14 + GPU/Vulkan/GPU_Vulkan.cpp | 2207 +++++++++++++++++++++++- GPU/Vulkan/GPU_Vulkan.h | 36 +- GPU/Vulkan/PipelineManagerVulkan.h | 2 + GPU/Vulkan/ShaderManagerVulkan.cpp | 40 +- GPU/Vulkan/ShaderManagerVulkan.h | 16 +- GPU/Vulkan/TextureCacheVulkan.cpp | 4 +- Windows/GPU/WindowsVulkanContext.cpp | 5 + Windows/GPU/WindowsVulkanContext.h | 2 + ext/native/thin3d/VulkanContext.cpp | 22 +- ext/native/thin3d/VulkanContext.h | 9 + ext/native/thin3d/thin3d_vulkan.cpp | 17 +- ext/native/thin3d/vulkan_utils.cpp | 15 - ext/native/thin3d/vulkan_utils.h | 1 - 23 files changed, 2345 insertions(+), 147 deletions(-) create mode 100644 GPU/Vulkan/DepalettizeShaderVulkan.cpp diff --git a/Common/GraphicsContext.h b/Common/GraphicsContext.h index 9ed4f21d77..f0f419cb1e 100644 --- a/Common/GraphicsContext.h +++ b/Common/GraphicsContext.h @@ -22,6 +22,9 @@ public: virtual void Resize() = 0; + // Needs casting to the appropriate type, unfortunately. Should find a better solution.. + virtual void *GetAPIContext() { return nullptr; } + virtual Thin3DContext *CreateThin3DContext() = 0; }; diff --git a/Core/System.cpp b/Core/System.cpp index 0df10e3d91..bc7e20b8b3 100644 --- a/Core/System.cpp +++ b/Core/System.cpp @@ -386,7 +386,10 @@ bool PSP_InitStart(const CoreParameter &coreParam, std::string *error_string) { #else INFO_LOG(BOOT, "PPSSPP %s", PPSSPP_GIT_VERSION); #endif + + GraphicsContext *temp = coreParameter.graphicsContext; coreParameter = coreParam; + coreParameter.graphicsContext = temp; coreParameter.errorString = ""; pspIsIniting = true; diff --git a/GPU/GPU.cpp b/GPU/GPU.cpp index 5088b1108c..dc1b9b9e3c 100644 --- a/GPU/GPU.cpp +++ b/GPU/GPU.cpp @@ -15,6 +15,7 @@ // Official git repository and contact information can be found at // https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. +#include "Common/GraphicsContext.h" #include "Core/Core.h" #include "GPU/GPU.h" @@ -59,7 +60,9 @@ bool GPU_Init(GraphicsContext *ctx) { #endif break; case GPU_VULKAN: - SetGPU(new GPU_Vulkan(nullptr)); + { + SetGPU(new GPU_Vulkan(ctx)); + } break; } diff --git a/GPU/GPU.vcxproj b/GPU/GPU.vcxproj index 9904be92b8..2cbf6a85d7 100644 --- a/GPU/GPU.vcxproj +++ b/GPU/GPU.vcxproj @@ -333,6 +333,7 @@ + diff --git a/GPU/GPU.vcxproj.filters b/GPU/GPU.vcxproj.filters index c48c83ecf7..7b13b92862 100644 --- a/GPU/GPU.vcxproj.filters +++ b/GPU/GPU.vcxproj.filters @@ -407,5 +407,6 @@ + \ No newline at end of file diff --git a/GPU/GPUState.h b/GPU/GPUState.h index 59671d1dd4..bd0c853095 100644 --- a/GPU/GPUState.h +++ b/GPU/GPUState.h @@ -456,6 +456,7 @@ enum { GPU_SUPPORTS_BLEND_MINMAX = FLAG_BIT(4), GPU_SUPPORTS_LOGIC_OP = FLAG_BIT(5), GPU_USE_DEPTH_RANGE_HACK = FLAG_BIT(6), + GPU_SUPPORTS_WIDE_LINES = FLAG_BIT(7), GPU_SUPPORTS_ACCURATE_DEPTH = FLAG_BIT(17), GPU_SUPPORTS_VAO = FLAG_BIT(18), GPU_SUPPORTS_ANY_COPY_IMAGE = FLAG_BIT(19), diff --git a/GPU/Vulkan/DepalettizeShaderVulkan.cpp b/GPU/Vulkan/DepalettizeShaderVulkan.cpp new file mode 100644 index 0000000000..2de073cabe --- /dev/null +++ b/GPU/Vulkan/DepalettizeShaderVulkan.cpp @@ -0,0 +1,47 @@ +// Copyright (c) 2014- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY{} without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + + +#include "GPU/Vulkan/DepalettizeShaderVulkan.h" + +DepalShaderCacheVulkan::DepalShaderCacheVulkan() { + +} + +DepalShaderCacheVulkan::~DepalShaderCacheVulkan() { + +} + +DepalShaderVulkan *DepalShaderCacheVulkan::GetDepalettizeShader(GEPaletteFormat clutFormat, GEBufferFormat pixelFormat) { + return nullptr; +} + +VulkanTexture *DepalShaderCacheVulkan::GetClutTexture(GEPaletteFormat clutFormat, const u32 clutHash, u32 *rawClut) { + return nullptr; +} + +void DepalShaderCacheVulkan::Clear() {} + +void DepalShaderCacheVulkan::Decimate() {} + +u32 DepalShaderCacheVulkan::GenerateShaderID(GEPaletteFormat clutFormat, GEBufferFormat pixelFormat) { + return 0; +} + +bool DepalShaderCacheVulkan::CreateVertexShader() { + return false; +} diff --git a/GPU/Vulkan/DepalettizeShaderVulkan.h b/GPU/Vulkan/DepalettizeShaderVulkan.h index ccee8ed7e9..63faa1c8b6 100644 --- a/GPU/Vulkan/DepalettizeShaderVulkan.h +++ b/GPU/Vulkan/DepalettizeShaderVulkan.h @@ -1,4 +1,3 @@ -#pragma once // Copyright (c) 2014- PPSSPP Project. // This program is free software: you can redistribute it and/or modify @@ -16,12 +15,14 @@ // Official git repository and contact information can be found at // https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. +#pragma once + #include #include "Common/CommonTypes.h" #include "GPU/ge_constants.h" -class DepalShader { +class DepalShaderVulkan { public: /* GLuint program; @@ -31,12 +32,14 @@ public: */ }; -class DepalTexture { +class DepalTextureVulkan { public: int texture; int lastFrame; }; +class VulkanTexture; + // Caches both shaders and palette textures. // Could even avoid bothering with palette texture and just use uniform data... class DepalShaderCacheVulkan { @@ -45,7 +48,7 @@ public: ~DepalShaderCacheVulkan(); // This also uploads the palette and binds the correct texture. - DepalShader *GetDepalettizeShader(GEPaletteFormat clutFormat, GEBufferFormat pixelFormat); + DepalShaderVulkan *GetDepalettizeShader(GEPaletteFormat clutFormat, GEBufferFormat pixelFormat); VulkanTexture *GetClutTexture(GEPaletteFormat clutFormat, const u32 clutHash, u32 *rawClut); void Clear(); void Decimate(); @@ -55,7 +58,7 @@ private: bool CreateVertexShader(); // GLuint vertexShader_; - std::map cache_; - std::map texCache_; + std::map cache_; + std::map texCache_; }; diff --git a/GPU/Vulkan/FramebufferVulkan.cpp b/GPU/Vulkan/FramebufferVulkan.cpp index f6fa0ee164..24f4c8cbd7 100644 --- a/GPU/Vulkan/FramebufferVulkan.cpp +++ b/GPU/Vulkan/FramebufferVulkan.cpp @@ -17,8 +17,34 @@ #pragma once +#include "GPU/GPUInterface.h" #include "GPU/Vulkan/FramebufferVulkan.h" + VulkanFramebuffer *FramebufferManagerVulkan::GetTempFBO(int width, int height, VulkanFBOColorDepth colorDepth) { return nullptr; } + +void FramebufferManagerVulkan::DestroyAllFBOs() { + +} + +void FramebufferManagerVulkan::Resized() { + +} + +void FramebufferManagerVulkan::DeviceLost() { + +} + +void FramebufferManagerVulkan::CopyDisplayToOutput() { + +} + +void FramebufferManagerVulkan::EndFrame() { + +} + +std::vector FramebufferManagerVulkan::GetFramebufferList() { + return std::vector(); +} diff --git a/GPU/Vulkan/FramebufferVulkan.h b/GPU/Vulkan/FramebufferVulkan.h index a45a93a400..f8a8b6f521 100644 --- a/GPU/Vulkan/FramebufferVulkan.h +++ b/GPU/Vulkan/FramebufferVulkan.h @@ -18,6 +18,7 @@ #pragma once #include "GPU/Common/FramebufferCommon.h" +#include "GPU/GPUInterface.h" #include "GPU/Vulkan/VulkanUtil.h" // TODO: WTF? @@ -28,6 +29,8 @@ enum VulkanFBOColorDepth { VK_FBO_5551, }; +class TextureCacheVulkan; + class FramebufferManagerVulkan : public FramebufferManagerCommon { public: // Subsequent commands will be enqueued on this buffer. @@ -37,6 +40,7 @@ public: virtual void ClearBuffer(bool keepState = false) override { throw std::logic_error("The method or operation is not implemented."); } + void SetTextureCache(TextureCacheVulkan *texCache) { texCache_ = texCache; } VulkanFramebuffer *GetTempFBO(int width, int height, VulkanFBOColorDepth colorDepth); virtual void RebindFramebuffer() override { @@ -109,8 +113,18 @@ public: void UpdateDownloadTempBuffer(VirtualFramebuffer *nvfb) override { } + void DestroyAllFBOs(); + void Resized(); + void DeviceLost(); + + void CopyDisplayToOutput(); + void EndFrame(); + + std::vector GetFramebufferList(); private: VkInstance inst_; VkCommandBuffer cmd_; + + TextureCacheVulkan *texCache_; }; diff --git a/GPU/Vulkan/GPU_Vulkan.cpp b/GPU/Vulkan/GPU_Vulkan.cpp index b7834de1ca..5980c49220 100644 --- a/GPU/Vulkan/GPU_Vulkan.cpp +++ b/GPU/Vulkan/GPU_Vulkan.cpp @@ -15,100 +15,2181 @@ // Official git repository and contact information can be found at // https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. +#include "base/logging.h" +#include "profiler/profiler.h" + +#include "Common/ChunkFile.h" +#include "Common/GraphicsContext.h" + +#include "Core/Config.h" +#include "Core/Debugger/Breakpoints.h" +#include "Core/MemMapHelpers.h" +#include "Core/Host.h" +#include "Core/Config.h" +#include "Core/Reporting.h" +#include "Core/System.h" + +#include "GPU/GPUState.h" +#include "GPU/ge_constants.h" +#include "GPU/GeDisasm.h" +#include "GPU/Common/FramebufferCommon.h" + +#include "GPU/Vulkan/ShaderManagerVulkan.h" #include "GPU/Vulkan/GPU_Vulkan.h" +#include "GPU/Vulkan/FramebufferVulkan.h" +#include "GPU/Vulkan/DrawEngineVulkan.h" +#include "GPU/Vulkan/TextureCacheVulkan.h" -GPU_Vulkan::GPU_Vulkan(VulkanContext *vulkan) : transformDraw_(vulkan), textureCache_(vulkan) { +#include "Core/MIPS/MIPS.h" +#include "Core/HLE/sceKernelThread.h" +#include "Core/HLE/sceKernelInterrupt.h" +#include "Core/HLE/sceGe.h" +enum { + FLAG_FLUSHBEFORE = 1, + FLAG_FLUSHBEFOREONCHANGE = 2, + FLAG_EXECUTE = 4, // needs to actually be executed. unused for now. + FLAG_EXECUTEONCHANGE = 8, + FLAG_ANY_EXECUTE = 4 | 8, + FLAG_READS_PC = 16, + FLAG_WRITES_PC = 32, + FLAG_DIRTYONCHANGE = 64, +}; + +struct CommandTableEntry { + u8 cmd; + u8 flags; + u64 dirtyFlags; + GPU_Vulkan::CmdFunc func; +}; + +GPU_Vulkan::CommandInfo GPU_Vulkan::cmdInfo_[256]; + +// This table gets crunched into a faster form by init. +// TODO: Share this table between the backends. Will have to make another indirection for the function pointers though.. +static const CommandTableEntry commandTable[] = { + // Changes that dirty the framebuffer + { GE_CMD_FRAMEBUFPTR, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_FramebufType }, + { GE_CMD_FRAMEBUFWIDTH, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_FramebufType }, + { GE_CMD_FRAMEBUFPIXFORMAT, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_FramebufType }, + { GE_CMD_ZBUFPTR, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_ZBUFWIDTH, FLAG_FLUSHBEFOREONCHANGE }, + + // Changes that dirty uniforms + { GE_CMD_FOGCOLOR, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_FOGCOLOR, &GPU_Vulkan::Execute_FogColor }, + { GE_CMD_FOG1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_FOGCOEF, &GPU_Vulkan::Execute_FogCoef }, + { GE_CMD_FOG2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_FOGCOEF, &GPU_Vulkan::Execute_FogCoef }, + + // Should these maybe flush? + { GE_CMD_MINZ, FLAG_FLUSHBEFOREONCHANGE, DIRTY_DEPTHRANGE }, + { GE_CMD_MAXZ, FLAG_FLUSHBEFOREONCHANGE, DIRTY_DEPTHRANGE }, + + // Changes that dirty texture scaling. + { GE_CMD_TEXMAPMODE, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_UVSCALEOFFSET, &GPU_Vulkan::Execute_TexMapMode }, + { GE_CMD_TEXSCALEU, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_UVSCALEOFFSET, &GPU_Vulkan::Execute_TexScaleU }, + { GE_CMD_TEXSCALEV, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_UVSCALEOFFSET, &GPU_Vulkan::Execute_TexScaleV }, + { GE_CMD_TEXOFFSETU, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_UVSCALEOFFSET, &GPU_Vulkan::Execute_TexOffsetU }, + { GE_CMD_TEXOFFSETV, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_UVSCALEOFFSET, &GPU_Vulkan::Execute_TexOffsetV }, + + // Changes that dirty the current texture. Really should be possible to avoid executing these if we compile + // by adding some more flags. + { GE_CMD_TEXSIZE0, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTE, 0, &GPU_Vulkan::Execute_TexSize0 }, + { GE_CMD_TEXSIZE1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexSizeN }, + { GE_CMD_TEXSIZE2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexSizeN }, + { GE_CMD_TEXSIZE3, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexSizeN }, + { GE_CMD_TEXSIZE4, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexSizeN }, + { GE_CMD_TEXSIZE5, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexSizeN }, + { GE_CMD_TEXSIZE6, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexSizeN }, + { GE_CMD_TEXSIZE7, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexSizeN }, + { GE_CMD_TEXFORMAT, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexFormat }, + { GE_CMD_TEXLEVEL, FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexLevel }, + { GE_CMD_TEXADDR0, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexAddr0 }, + { GE_CMD_TEXADDR1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexAddrN }, + { GE_CMD_TEXADDR2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexAddrN }, + { GE_CMD_TEXADDR3, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexAddrN }, + { GE_CMD_TEXADDR4, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexAddrN }, + { GE_CMD_TEXADDR5, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexAddrN }, + { GE_CMD_TEXADDR6, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexAddrN }, + { GE_CMD_TEXADDR7, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexAddrN }, + { GE_CMD_TEXBUFWIDTH0, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexBufw0 }, + { GE_CMD_TEXBUFWIDTH1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexBufwN }, + { GE_CMD_TEXBUFWIDTH2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexBufwN }, + { GE_CMD_TEXBUFWIDTH3, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexBufwN }, + { GE_CMD_TEXBUFWIDTH4, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexBufwN }, + { GE_CMD_TEXBUFWIDTH5, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexBufwN }, + { GE_CMD_TEXBUFWIDTH6, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexBufwN }, + { GE_CMD_TEXBUFWIDTH7, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexBufwN }, + // These must flush on change, so that LoadClut doesn't have to always flush. + { GE_CMD_CLUTADDR, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_CLUTADDRUPPER, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_CLUTFORMAT, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_ClutFormat }, + + // These affect the fragment shader so need flushing. + { GE_CMD_CLEARMODE, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_TEXTUREMAPENABLE, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_FOGENABLE, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_TEXMODE, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexParamType }, + { GE_CMD_TEXSHADELS, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_SHADEMODE, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_TEXFUNC, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_COLORTEST, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_ALPHATESTENABLE, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_COLORTESTENABLE, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_COLORTESTMASK, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_ALPHACOLORMASK, &GPU_Vulkan::Execute_ColorTestMask }, + + // These change the vertex shader so need flushing. + { GE_CMD_REVERSENORMAL, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_LIGHTINGENABLE, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_LIGHTENABLE0, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_LIGHTENABLE1, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_LIGHTENABLE2, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_LIGHTENABLE3, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_LIGHTTYPE0, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_LIGHTTYPE1, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_LIGHTTYPE2, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_LIGHTTYPE3, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_MATERIALUPDATE, FLAG_FLUSHBEFOREONCHANGE }, + + // This changes both shaders so need flushing. + { GE_CMD_LIGHTMODE, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_TEXFILTER, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexParamType }, + { GE_CMD_TEXWRAP, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_TexParamType }, + + // Uniform changes + { GE_CMD_ALPHATEST, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_ALPHACOLORREF | DIRTY_ALPHACOLORMASK, &GPU_Vulkan::Execute_AlphaTest }, + { GE_CMD_COLORREF, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_ColorRef }, + { GE_CMD_TEXENVCOLOR, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_TEXENV, &GPU_Vulkan::Execute_TexEnvColor }, + + // Simple render state changes. Handled in StateMapping.cpp. + { GE_CMD_OFFSETX, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_OFFSETY, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_CULL, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_CULLFACEENABLE, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_DITHERENABLE, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_STENCILOP, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_STENCILTEST, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_STENCILREPLACEVALUE, &GPU_Vulkan::Execute_StencilTest }, + { GE_CMD_STENCILTESTENABLE, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_ALPHABLENDENABLE, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_BLENDMODE, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_BLENDFIXEDA, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_BLENDFIXEDB, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_MASKRGB, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_MASKALPHA, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_ZTEST, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_ZTESTENABLE, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_ZWRITEDISABLE, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_LOGICOP, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_LOGICOPENABLE, FLAG_FLUSHBEFOREONCHANGE }, + + // Can probably ignore this one as we don't support AA lines. + { GE_CMD_ANTIALIASENABLE, FLAG_FLUSHBEFOREONCHANGE }, + + // Morph weights. TODO: Remove precomputation? + { GE_CMD_MORPHWEIGHT0, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE }, + { GE_CMD_MORPHWEIGHT1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE }, + { GE_CMD_MORPHWEIGHT2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE }, + { GE_CMD_MORPHWEIGHT3, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE }, + { GE_CMD_MORPHWEIGHT4, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE }, + { GE_CMD_MORPHWEIGHT5, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE }, + { GE_CMD_MORPHWEIGHT6, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE }, + { GE_CMD_MORPHWEIGHT7, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE }, + + // Control spline/bezier patches. Don't really require flushing as such, but meh. + { GE_CMD_PATCHDIVISION, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_PATCHPRIMITIVE, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_PATCHFACING, FLAG_FLUSHBEFOREONCHANGE }, + { GE_CMD_PATCHCULLENABLE, FLAG_FLUSHBEFOREONCHANGE }, + + // Viewport. + { GE_CMD_VIEWPORTXSCALE, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_ViewportType }, + { GE_CMD_VIEWPORTYSCALE, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_ViewportType }, + { GE_CMD_VIEWPORTXCENTER, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_ViewportType }, + { GE_CMD_VIEWPORTYCENTER, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_ViewportType }, + { GE_CMD_VIEWPORTZSCALE, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_DEPTHRANGE, &GPU_Vulkan::Execute_ViewportZType }, + { GE_CMD_VIEWPORTZCENTER, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_DEPTHRANGE, &GPU_Vulkan::Execute_ViewportZType }, + + // Region + { GE_CMD_REGION1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_Region }, + { GE_CMD_REGION2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_Region }, + + // Scissor + { GE_CMD_SCISSOR1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_Scissor }, + { GE_CMD_SCISSOR2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_Scissor }, + + // These dirty various vertex shader uniforms. Could embed information about that in this table and call dirtyuniform directly, hm... + { GE_CMD_AMBIENTCOLOR, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_AMBIENT, &GPU_Vulkan::Execute_Ambient }, + { GE_CMD_AMBIENTALPHA, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_AMBIENT, &GPU_Vulkan::Execute_Ambient }, + { GE_CMD_MATERIALDIFFUSE, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_MATDIFFUSE, &GPU_Vulkan::Execute_MaterialDiffuse }, + { GE_CMD_MATERIALEMISSIVE, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_MATEMISSIVE, &GPU_Vulkan::Execute_MaterialEmissive }, + { GE_CMD_MATERIALAMBIENT, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_MATAMBIENTALPHA, &GPU_Vulkan::Execute_MaterialAmbient }, + { GE_CMD_MATERIALALPHA, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_MATAMBIENTALPHA, &GPU_Vulkan::Execute_MaterialAmbient }, + { GE_CMD_MATERIALSPECULAR, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_MATSPECULAR, &GPU_Vulkan::Execute_MaterialSpecular }, + { GE_CMD_MATERIALSPECULARCOEF, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_MATSPECULAR, &GPU_Vulkan::Execute_MaterialSpecular }, + + // These dirty uniforms, which could be table-ized to avoid execute. + { GE_CMD_LX0, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT0, &GPU_Vulkan::Execute_Light0Param }, + { GE_CMD_LY0, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT0, &GPU_Vulkan::Execute_Light0Param }, + { GE_CMD_LZ0, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT0, &GPU_Vulkan::Execute_Light0Param }, + { GE_CMD_LX1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT1, &GPU_Vulkan::Execute_Light1Param }, + { GE_CMD_LY1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT1, &GPU_Vulkan::Execute_Light1Param }, + { GE_CMD_LZ1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT1, &GPU_Vulkan::Execute_Light1Param }, + { GE_CMD_LX2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT2, &GPU_Vulkan::Execute_Light2Param }, + { GE_CMD_LY2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT2, &GPU_Vulkan::Execute_Light2Param }, + { GE_CMD_LZ2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT2, &GPU_Vulkan::Execute_Light2Param }, + { GE_CMD_LX3, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT3, &GPU_Vulkan::Execute_Light3Param }, + { GE_CMD_LY3, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT3, &GPU_Vulkan::Execute_Light3Param }, + { GE_CMD_LZ3, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT3, &GPU_Vulkan::Execute_Light3Param }, + + { GE_CMD_LDX0, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT0, &GPU_Vulkan::Execute_Light0Param }, + { GE_CMD_LDY0, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT0, &GPU_Vulkan::Execute_Light0Param }, + { GE_CMD_LDZ0, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT0, &GPU_Vulkan::Execute_Light0Param }, + { GE_CMD_LDX1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT1, &GPU_Vulkan::Execute_Light1Param }, + { GE_CMD_LDY1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT1, &GPU_Vulkan::Execute_Light1Param }, + { GE_CMD_LDZ1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT1, &GPU_Vulkan::Execute_Light1Param }, + { GE_CMD_LDX2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT2, &GPU_Vulkan::Execute_Light2Param }, + { GE_CMD_LDY2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT2, &GPU_Vulkan::Execute_Light2Param }, + { GE_CMD_LDZ2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT2, &GPU_Vulkan::Execute_Light2Param }, + { GE_CMD_LDX3, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT3, &GPU_Vulkan::Execute_Light3Param }, + { GE_CMD_LDY3, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT3, &GPU_Vulkan::Execute_Light3Param }, + { GE_CMD_LDZ3, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT3, &GPU_Vulkan::Execute_Light3Param }, + + { GE_CMD_LKA0, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT0, &GPU_Vulkan::Execute_Light0Param }, + { GE_CMD_LKB0, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT0, &GPU_Vulkan::Execute_Light0Param }, + { GE_CMD_LKC0, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT0, &GPU_Vulkan::Execute_Light0Param }, + { GE_CMD_LKA1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT1, &GPU_Vulkan::Execute_Light1Param }, + { GE_CMD_LKB1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT1, &GPU_Vulkan::Execute_Light1Param }, + { GE_CMD_LKC1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT1, &GPU_Vulkan::Execute_Light1Param }, + { GE_CMD_LKA2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT2, &GPU_Vulkan::Execute_Light2Param }, + { GE_CMD_LKB2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT2, &GPU_Vulkan::Execute_Light2Param }, + { GE_CMD_LKC2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT2, &GPU_Vulkan::Execute_Light2Param }, + { GE_CMD_LKA3, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT3, &GPU_Vulkan::Execute_Light3Param }, + { GE_CMD_LKB3, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT3, &GPU_Vulkan::Execute_Light3Param }, + { GE_CMD_LKC3, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT3, &GPU_Vulkan::Execute_Light3Param }, + + { GE_CMD_LKS0, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT0, &GPU_Vulkan::Execute_Light0Param }, + { GE_CMD_LKS1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT1, &GPU_Vulkan::Execute_Light1Param }, + { GE_CMD_LKS2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT2, &GPU_Vulkan::Execute_Light2Param }, + { GE_CMD_LKS3, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT3, &GPU_Vulkan::Execute_Light3Param }, + + { GE_CMD_LKO0, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT0, &GPU_Vulkan::Execute_Light0Param }, + { GE_CMD_LKO1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT1, &GPU_Vulkan::Execute_Light1Param }, + { GE_CMD_LKO2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT2, &GPU_Vulkan::Execute_Light2Param }, + { GE_CMD_LKO3, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT3, &GPU_Vulkan::Execute_Light3Param }, + + { GE_CMD_LAC0, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT0, &GPU_Vulkan::Execute_Light0Param }, + { GE_CMD_LDC0, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT0, &GPU_Vulkan::Execute_Light0Param }, + { GE_CMD_LSC0, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT0, &GPU_Vulkan::Execute_Light0Param }, + { GE_CMD_LAC1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT1, &GPU_Vulkan::Execute_Light1Param }, + { GE_CMD_LDC1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT1, &GPU_Vulkan::Execute_Light1Param }, + { GE_CMD_LSC1, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT1, &GPU_Vulkan::Execute_Light1Param }, + { GE_CMD_LAC2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT2, &GPU_Vulkan::Execute_Light2Param }, + { GE_CMD_LDC2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT2, &GPU_Vulkan::Execute_Light2Param }, + { GE_CMD_LSC2, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT2, &GPU_Vulkan::Execute_Light2Param }, + { GE_CMD_LAC3, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT3, &GPU_Vulkan::Execute_Light3Param }, + { GE_CMD_LDC3, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT3, &GPU_Vulkan::Execute_Light3Param }, + { GE_CMD_LSC3, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_LIGHT3, &GPU_Vulkan::Execute_Light3Param }, + + // Ignored commands + { GE_CMD_CLIPENABLE, 0 }, + { GE_CMD_TEXFLUSH, 0 }, + { GE_CMD_TEXLODSLOPE, 0 }, + { GE_CMD_TEXSYNC, 0 }, + + // These are just nop or part of other later commands. + { GE_CMD_NOP, 0 }, + { GE_CMD_BASE, 0 }, + { GE_CMD_TRANSFERSRC, 0 }, + { GE_CMD_TRANSFERSRCW, 0 }, + { GE_CMD_TRANSFERDST, 0 }, + { GE_CMD_TRANSFERDSTW, 0 }, + { GE_CMD_TRANSFERSRCPOS, 0 }, + { GE_CMD_TRANSFERDSTPOS, 0 }, + { GE_CMD_TRANSFERSIZE, 0 }, + + // From Common. No flushing but definitely need execute. + { GE_CMD_OFFSETADDR, FLAG_EXECUTE, 0, &GPUCommon::Execute_OffsetAddr }, + { GE_CMD_ORIGIN, FLAG_EXECUTE | FLAG_READS_PC, 0, &GPUCommon::Execute_Origin }, // Really? + { GE_CMD_PRIM, FLAG_EXECUTE, 0, &GPU_Vulkan::Execute_Prim }, + { GE_CMD_JUMP, FLAG_EXECUTE | FLAG_READS_PC | FLAG_WRITES_PC, 0, &GPUCommon::Execute_Jump }, + { GE_CMD_CALL, FLAG_EXECUTE | FLAG_READS_PC | FLAG_WRITES_PC, 0, &GPUCommon::Execute_Call }, + { GE_CMD_RET, FLAG_EXECUTE | FLAG_READS_PC | FLAG_WRITES_PC, 0, &GPUCommon::Execute_Ret }, + { GE_CMD_END, FLAG_FLUSHBEFORE | FLAG_EXECUTE | FLAG_READS_PC | FLAG_WRITES_PC, 0, &GPUCommon::Execute_End }, // Flush? + { GE_CMD_VADDR, FLAG_EXECUTE, 0, &GPU_Vulkan::Execute_Vaddr }, + { GE_CMD_IADDR, FLAG_EXECUTE, 0, &GPU_Vulkan::Execute_Iaddr }, + { GE_CMD_BJUMP, FLAG_EXECUTE | FLAG_READS_PC | FLAG_WRITES_PC, 0, &GPUCommon::Execute_BJump }, // EXECUTE + { GE_CMD_BOUNDINGBOX, FLAG_EXECUTE, 0, &GPU_Vulkan::Execute_BoundingBox }, // + FLUSHBEFORE when we implement... or not, do we need to? + + // Changing the vertex type requires us to flush. + { GE_CMD_VERTEXTYPE, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_VertexType }, + + { GE_CMD_BEZIER, FLAG_FLUSHBEFORE | FLAG_EXECUTE, 0, &GPU_Vulkan::Execute_Bezier }, + { GE_CMD_SPLINE, FLAG_FLUSHBEFORE | FLAG_EXECUTE, 0, &GPU_Vulkan::Execute_Spline }, + + // These two are actually processed in CMD_END. + { GE_CMD_SIGNAL, FLAG_FLUSHBEFORE }, + { GE_CMD_FINISH, FLAG_FLUSHBEFORE }, + + // Changes that trigger data copies. Only flushing on change for LOADCLUT must be a bit of a hack... + { GE_CMD_LOADCLUT, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTE, 0, &GPU_Vulkan::Execute_LoadClut }, + { GE_CMD_TRANSFERSTART, FLAG_FLUSHBEFORE | FLAG_EXECUTE | FLAG_READS_PC, 0, &GPU_Vulkan::Execute_BlockTransferStart }, + + // We don't use the dither table. + { GE_CMD_DITH0 }, + { GE_CMD_DITH1 }, + { GE_CMD_DITH2 }, + { GE_CMD_DITH3 }, + + // These handle their own flushing. + { GE_CMD_WORLDMATRIXNUMBER, FLAG_EXECUTE | FLAG_READS_PC | FLAG_WRITES_PC, 0, &GPU_Vulkan::Execute_WorldMtxNum }, + { GE_CMD_WORLDMATRIXDATA, FLAG_EXECUTE, 0, &GPU_Vulkan::Execute_WorldMtxData }, + { GE_CMD_VIEWMATRIXNUMBER, FLAG_EXECUTE | FLAG_READS_PC | FLAG_WRITES_PC, 0, &GPU_Vulkan::Execute_ViewMtxNum }, + { GE_CMD_VIEWMATRIXDATA, FLAG_EXECUTE, 0, &GPU_Vulkan::Execute_ViewMtxData }, + { GE_CMD_PROJMATRIXNUMBER, FLAG_EXECUTE | FLAG_READS_PC | FLAG_WRITES_PC, 0, &GPU_Vulkan::Execute_ProjMtxNum }, + { GE_CMD_PROJMATRIXDATA, FLAG_EXECUTE, 0, &GPU_Vulkan::Execute_ProjMtxData }, + { GE_CMD_TGENMATRIXNUMBER, FLAG_EXECUTE | FLAG_READS_PC | FLAG_WRITES_PC, 0, &GPU_Vulkan::Execute_TgenMtxNum }, + { GE_CMD_TGENMATRIXDATA, FLAG_EXECUTE, 0, &GPU_Vulkan::Execute_TgenMtxData }, + { GE_CMD_BONEMATRIXNUMBER, FLAG_EXECUTE | FLAG_READS_PC | FLAG_WRITES_PC, 0, &GPU_Vulkan::Execute_BoneMtxNum }, + { GE_CMD_BONEMATRIXDATA, FLAG_EXECUTE, 0, &GPU_Vulkan::Execute_BoneMtxData }, + + // Vertex Screen/Texture/Color + { GE_CMD_VSCX, FLAG_EXECUTE }, + { GE_CMD_VSCY, FLAG_EXECUTE }, + { GE_CMD_VSCZ, FLAG_EXECUTE }, + { GE_CMD_VTCS, FLAG_EXECUTE }, + { GE_CMD_VTCT, FLAG_EXECUTE }, + { GE_CMD_VTCQ, FLAG_EXECUTE }, + { GE_CMD_VCV, FLAG_EXECUTE }, + { GE_CMD_VAP, FLAG_EXECUTE }, + { GE_CMD_VFC, FLAG_EXECUTE }, + { GE_CMD_VSCV, FLAG_EXECUTE }, + + // "Missing" commands (gaps in the sequence) + { GE_CMD_UNKNOWN_03, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_0D, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_11, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_29, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_34, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_35, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_39, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_4E, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_4F, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_52, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_59, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_5A, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_B6, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_B7, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_D1, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_ED, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_EF, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_FA, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_FB, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_FC, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_FD, FLAG_EXECUTE }, + { GE_CMD_UNKNOWN_FE, FLAG_EXECUTE }, + // Appears to be debugging related or something? Hit a lot in GoW. + { GE_CMD_UNKNOWN_FF, 0 }, +}; + +GPU_Vulkan::GPU_Vulkan(GraphicsContext *ctx) + : vulkan_((VulkanContext *)ctx->GetAPIContext()), + drawEngine_(vulkan_), + textureCache_(vulkan_), + resized_(false), + gfxCtx_(ctx) { + UpdateVsyncInterval(true); + CheckGPUFeatures(); + + shaderManager_ = new ShaderManagerVulkan(vulkan_); + drawEngine_.SetShaderManager(shaderManager_); + drawEngine_.SetTextureCache(&textureCache_); + drawEngine_.SetFramebufferManager(&framebufferManager_); + framebufferManager_.Init(); + framebufferManager_.SetTextureCache(&textureCache_); + textureCache_.SetFramebufferManager(&framebufferManager_); + textureCache_.SetDepalShaderCache(&depalShaderCache_); + textureCache_.SetShaderManager(shaderManager_); + textureCache_.SetTransformDrawEngine(&drawEngine_); + + // Sanity check gstate + if ((int *)&gstate.transferstart - (int *)&gstate != 0xEA) { + ERROR_LOG(G3D, "gstate has drifted out of sync!"); + } + + // Sanity check cmdInfo_ table - no dupes please + std::set dupeCheck; + memset(cmdInfo_, 0, sizeof(cmdInfo_)); + for (size_t i = 0; i < ARRAY_SIZE(commandTable); i++) { + const u8 cmd = commandTable[i].cmd; + if (dupeCheck.find(cmd) != dupeCheck.end()) { + ERROR_LOG(G3D, "Command table Dupe: %02x (%i)", (int)cmd, (int)cmd); + } else { + dupeCheck.insert(cmd); + } + cmdInfo_[cmd].flags |= commandTable[i].flags; + cmdInfo_[cmd].func = commandTable[i].func; + if (!cmdInfo_[cmd].func) { + cmdInfo_[cmd].func = &GPU_Vulkan::Execute_Generic; + } + } + // Find commands missing from the table. + for (int i = 0; i < 0xEF; i++) { + if (dupeCheck.find((u8)i) == dupeCheck.end()) { + ERROR_LOG(G3D, "Command missing from table: %02x (%i)", i, i); + } + } + + // No need to flush before the tex scale/offset commands if we are baking + // the tex scale/offset into the vertices anyway. + + UpdateCmdInfo(); + + BuildReportingInfo(); + // Update again after init to be sure of any silly driver problems. + UpdateVsyncInterval(true); } GPU_Vulkan::~GPU_Vulkan() { + framebufferManager_.DestroyAllFBOs(); + shaderManager_->ClearCache(true); + depalShaderCache_.Clear(); + delete shaderManager_; + shaderManager_ = nullptr; +#ifdef _WIN32 + gfxCtx_->SwapInterval(0); +#endif } void GPU_Vulkan::CheckGPUFeatures() { - -} - -void GPU_Vulkan::ReapplyGfxStateInternal() {} -void GPU_Vulkan::SetDisplayFramebuffer(u32 framebuf, u32 stride, GEBufferFormat format) {} -void GPU_Vulkan::CopyDisplayToOutput() {} -void GPU_Vulkan::BeginFrame() {} -void GPU_Vulkan::UpdateStats() {} -void GPU_Vulkan::InvalidateCache(u32 addr, int size, GPUInvalidationType type) {} -bool GPU_Vulkan::PerformMemoryCopy(u32 dest, u32 src, int size) { return false; } -bool GPU_Vulkan::PerformMemorySet(u32 dest, u8 v, int size) { return false; } -bool GPU_Vulkan::PerformMemoryDownload(u32 dest, int size) { return false; } -bool GPU_Vulkan::PerformMemoryUpload(u32 dest, int size) { return false; } -bool GPU_Vulkan::PerformStencilUpload(u32 dest, int size) { return false; } -void GPU_Vulkan::ClearCacheNextFrame() {} -void GPU_Vulkan::DeviceLost() {} // Only happens on Android. Drop all textures and shaders. - -void GPU_Vulkan::DumpNextFrame() {} - -void GPU_Vulkan::DoState(PointerWrap &p) { - GPUCommon::DoState(p); + gstate_c.featureFlags = 0; + if (vulkan_->GetFeaturesEnabled().wideLines) { + gstate_c.featureFlags |= GPU_SUPPORTS_WIDE_LINES; + } + if (vulkan_->GetFeaturesEnabled().dualSrcBlend) { + gstate_c.featureFlags |= GPU_SUPPORTS_DUALSOURCE_BLEND; + } + if (vulkan_->GetFeaturesEnabled().logicOp) { + gstate_c.featureFlags |= GPU_SUPPORTS_LOGIC_OP; + } } -void GPU_Vulkan::DoBlockTransfer(u32 skipDrawReason) { - -} - -void GPU_Vulkan::Resized() {} - -void GPU_Vulkan::ClearShaderCache() {} -bool GPU_Vulkan::FramebufferDirty() { return false; } -bool GPU_Vulkan::FramebufferReallyDirty() { return false; } - -void GPU_Vulkan::FastRunLoop(DisplayList &list) { - -} - -void GPU_Vulkan::ProcessEvent(GPUEvent ev) { - -} - -void GPU_Vulkan::FastLoadBoneMatrix(u32 target) { - -} - -void GPU_Vulkan::FinishDeferred() { - -} - -void GPU_Vulkan::UpdateCmdInfo() { +// Needs to be called on GPU thread, not reporting thread. +// TODO +void GPU_Vulkan::BuildReportingInfo() { + char temp[16384]; + snprintf(temp, sizeof(temp), "Vulkan"); + reportingPrimaryInfo_ = "VulkanVendor"; + reportingFullInfo_ = temp; + Reporting::UpdateConfig(); } void GPU_Vulkan::InitClear() { - + ScheduleEvent(GPU_EVENT_INIT_CLEAR); } void GPU_Vulkan::Reinitialize() { + GPUCommon::Reinitialize(); + ScheduleEvent(GPU_EVENT_REINITIALIZE); +} +void GPU_Vulkan::ReinitializeInternal() { + textureCache_.Clear(true); + depalShaderCache_.Clear(); + framebufferManager_.DestroyAllFBOs(); + framebufferManager_.Resized(); +} + +void GPU_Vulkan::InitClearInternal() { + bool useNonBufferedRendering = g_Config.iRenderingMode == FB_NON_BUFFERED_MODE; + if (useNonBufferedRendering) { + /* + glstate.depthWrite.set(GL_TRUE); + glstate.colorMask.set(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); + glClearColor(0, 0, 0, 1); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); + */ + } +} + +void GPU_Vulkan::DumpNextFrame() { + dumpNextFrame_ = true; +} + +void GPU_Vulkan::BeginFrame() { + ScheduleEvent(GPU_EVENT_BEGIN_FRAME); +} + +void GPU_Vulkan::UpdateVsyncInterval(bool force) { + // TODO +} + +void GPU_Vulkan::UpdateCmdInfo() { + if (g_Config.bPrescaleUV) { + cmdInfo_[GE_CMD_TEXSCALEU].flags &= ~FLAG_FLUSHBEFOREONCHANGE; + cmdInfo_[GE_CMD_TEXSCALEV].flags &= ~FLAG_FLUSHBEFOREONCHANGE; + cmdInfo_[GE_CMD_TEXOFFSETU].flags &= ~FLAG_FLUSHBEFOREONCHANGE; + cmdInfo_[GE_CMD_TEXOFFSETV].flags &= ~FLAG_FLUSHBEFOREONCHANGE; + } else { + cmdInfo_[GE_CMD_TEXSCALEU].flags |= FLAG_FLUSHBEFOREONCHANGE; + cmdInfo_[GE_CMD_TEXSCALEV].flags |= FLAG_FLUSHBEFOREONCHANGE; + cmdInfo_[GE_CMD_TEXOFFSETU].flags |= FLAG_FLUSHBEFOREONCHANGE; + cmdInfo_[GE_CMD_TEXOFFSETV].flags |= FLAG_FLUSHBEFOREONCHANGE; + } + + if (g_Config.bSoftwareSkinning) { + cmdInfo_[GE_CMD_VERTEXTYPE].flags &= ~FLAG_FLUSHBEFOREONCHANGE; + cmdInfo_[GE_CMD_VERTEXTYPE].func = &GPU_Vulkan::Execute_VertexTypeSkinning; + } else { + cmdInfo_[GE_CMD_VERTEXTYPE].flags |= FLAG_FLUSHBEFOREONCHANGE; + cmdInfo_[GE_CMD_VERTEXTYPE].func = &GPU_Vulkan::Execute_VertexType; + } +} + +void GPU_Vulkan::ReapplyGfxStateInternal() { + GPUCommon::ReapplyGfxStateInternal(); +} + +void GPU_Vulkan::BeginFrameInternal() { + if (resized_) { + CheckGPUFeatures(); + UpdateCmdInfo(); + drawEngine_.Resized(); + } + UpdateVsyncInterval(resized_); + resized_ = false; + + textureCache_.StartFrame(); + depalShaderCache_.Decimate(); + + if (dumpNextFrame_) { + NOTICE_LOG(G3D, "DUMPING THIS FRAME"); + dumpThisFrame_ = true; + dumpNextFrame_ = false; + } else if (dumpThisFrame_) { + dumpThisFrame_ = false; + } + shaderManager_->DirtyShader(); + + // Not sure if this is really needed. + shaderManager_->DirtyUniform(DIRTY_ALL); + + framebufferManager_.BeginFrame(); +} + +void GPU_Vulkan::SetDisplayFramebuffer(u32 framebuf, u32 stride, GEBufferFormat format) { + host->GPUNotifyDisplay(framebuf, stride, format); + framebufferManager_.SetDisplayFramebuffer(framebuf, stride, format); +} + +bool GPU_Vulkan::FramebufferDirty() { + if (ThreadEnabled()) { + // Allow it to process fully before deciding if it's dirty. + SyncThread(); + } + + VirtualFramebuffer *vfb = framebufferManager_.GetDisplayVFB(); + if (vfb) { + bool dirty = vfb->dirtyAfterDisplay; + vfb->dirtyAfterDisplay = false; + return dirty; + } + return true; +} + +bool GPU_Vulkan::FramebufferReallyDirty() { + if (ThreadEnabled()) { + // Allow it to process fully before deciding if it's dirty. + SyncThread(); + } + + VirtualFramebuffer *vfb = framebufferManager_.GetDisplayVFB(); + if (vfb) { + bool dirty = vfb->reallyDirtyAfterDisplay; + vfb->reallyDirtyAfterDisplay = false; + return dirty; + } + return true; +} + +void GPU_Vulkan::CopyDisplayToOutput() { + ScheduleEvent(GPU_EVENT_COPY_DISPLAY_TO_OUTPUT); +} + +void GPU_Vulkan::CopyDisplayToOutputInternal() { + // Flush anything left over. + framebufferManager_.RebindFramebuffer(); + drawEngine_.Flush(curCmd_); + + shaderManager_->DirtyLastShader(); + + framebufferManager_.CopyDisplayToOutput(); + framebufferManager_.EndFrame(); + + gstate_c.textureChanged = TEXCHANGE_UPDATED; +} + +// Maybe should write this in ASM... +void GPU_Vulkan::FastRunLoop(DisplayList &list) { + PROFILE_THIS_SCOPE("gpuloop"); + const CommandInfo *cmdInfo = cmdInfo_; + int dc = downcount; + for (; dc > 0; --dc) { + // We know that display list PCs have the upper nibble == 0 - no need to mask the pointer + const u32 op = *(const u32 *)(Memory::base + list.pc); + const u32 cmd = op >> 24; + const CommandInfo info = cmdInfo[cmd]; + const u8 cmdFlags = info.flags; // If we stashed the cmdFlags in the top bits of the cmdmem, we could get away with one table lookup instead of two + const u32 diff = op ^ gstate.cmdmem[cmd]; + // Inlined CheckFlushOp here to get rid of the dumpThisFrame_ check. + if ((cmdFlags & FLAG_FLUSHBEFORE) || (diff && (cmdFlags & FLAG_FLUSHBEFOREONCHANGE))) { + drawEngine_.Flush(curCmd_); + } + gstate.cmdmem[cmd] = op; // TODO: no need to write if diff==0... + if ((cmdFlags & FLAG_EXECUTE) || (diff && (cmdFlags & FLAG_EXECUTEONCHANGE))) { + downcount = dc; + (this->*info.func)(op, diff); + dc = downcount; + } + list.pc += 4; + } + downcount = 0; +} + +void GPU_Vulkan::FinishDeferred() { + // This finishes reading any vertex data that is pending. + drawEngine_.FinishDeferred(); +} + +void GPU_Vulkan::ProcessEvent(GPUEvent ev) { + switch (ev.type) { + case GPU_EVENT_INIT_CLEAR: + InitClearInternal(); + break; + + case GPU_EVENT_BEGIN_FRAME: + BeginFrameInternal(); + break; + + case GPU_EVENT_COPY_DISPLAY_TO_OUTPUT: + CopyDisplayToOutputInternal(); + break; + + case GPU_EVENT_INVALIDATE_CACHE: + InvalidateCacheInternal(ev.invalidate_cache.addr, ev.invalidate_cache.size, ev.invalidate_cache.type); + break; + + case GPU_EVENT_FB_MEMCPY: + PerformMemoryCopyInternal(ev.fb_memcpy.dst, ev.fb_memcpy.src, ev.fb_memcpy.size); + break; + + case GPU_EVENT_FB_MEMSET: + PerformMemorySetInternal(ev.fb_memset.dst, ev.fb_memset.v, ev.fb_memset.size); + break; + + case GPU_EVENT_FB_STENCIL_UPLOAD: + PerformStencilUploadInternal(ev.fb_stencil_upload.dst, ev.fb_stencil_upload.size); + break; + + case GPU_EVENT_REINITIALIZE: + ReinitializeInternal(); + break; + + default: + GPUCommon::ProcessEvent(ev); + } +} + +inline void GPU_Vulkan::CheckFlushOp(int cmd, u32 diff) { + const u8 cmdFlags = cmdInfo_[cmd].flags; + if ((cmdFlags & FLAG_FLUSHBEFORE) || (diff && (cmdFlags & FLAG_FLUSHBEFOREONCHANGE))) { + if (dumpThisFrame_) { + NOTICE_LOG(G3D, "================ FLUSH ================"); + } + drawEngine_.Flush(curCmd_); + } } void GPU_Vulkan::PreExecuteOp(u32 op, u32 diff) { - -} - -void GPU_Vulkan::Execute_Generic(u32 op, u32 diff) { - + CheckFlushOp(op >> 24, diff); } void GPU_Vulkan::ExecuteOp(u32 op, u32 diff) { - + const u8 cmd = op >> 24; + const CommandInfo info = cmdInfo_[cmd]; + const u8 cmdFlags = info.flags; + if ((cmdFlags & FLAG_EXECUTE) || (diff && (cmdFlags & FLAG_EXECUTEONCHANGE))) { + (this->*info.func)(op, diff); + } } - - -std::vector GPU_Vulkan::DebugGetShaderIDs(DebugShaderType shader) { - std::vector ids; - return ids; +void GPU_Vulkan::Execute_Vaddr(u32 op, u32 diff) { + gstate_c.vertexAddr = gstate_c.getRelativeAddress(op & 0x00FFFFFF); } -std::string GPU_Vulkan::DebugGetShaderString(std::string id, DebugShaderType shader, DebugShaderStringType stringType) { - return "N/A"; +void GPU_Vulkan::Execute_Iaddr(u32 op, u32 diff) { + gstate_c.indexAddr = gstate_c.getRelativeAddress(op & 0x00FFFFFF); +} + +void GPU_Vulkan::Execute_Prim(u32 op, u32 diff) { + // This drives all drawing. All other state we just buffer up, then we apply it only + // when it's time to draw. As most PSP games set state redundantly ALL THE TIME, this is a huge optimization. + + u32 data = op & 0xFFFFFF; + u32 count = data & 0xFFFF; + GEPrimitiveType prim = static_cast(data >> 16); + + if (count == 0) + return; + + // Discard AA lines as we can't do anything that makes sense with these anyway. The SW plugin might, though. + + if (gstate.isAntiAliasEnabled()) { + // Discard AA lines in DOA + if (prim == GE_PRIM_LINE_STRIP) + return; + // Discard AA lines in Summon Night 5 + if ((prim == GE_PRIM_LINES) && gstate.isSkinningEnabled()) + return; + } + + // This also makes skipping drawing very effective. + framebufferManager_.SetRenderFrameBuffer(gstate_c.framebufChanged, gstate_c.skipDrawReason); + if (gstate_c.skipDrawReason & (SKIPDRAW_SKIPFRAME | SKIPDRAW_NON_DISPLAYED_FB)) { + drawEngine_.SetupVertexDecoder(gstate.vertType); + // Rough estimate, not sure what's correct. + int vertexCost = drawEngine_.EstimatePerVertexCost(); + cyclesExecuted += vertexCost * count; + return; + } + + if (!Memory::IsValidAddress(gstate_c.vertexAddr)) { + ERROR_LOG_REPORT(G3D, "Bad vertex address %08x!", gstate_c.vertexAddr); + return; + } + + void *verts = Memory::GetPointerUnchecked(gstate_c.vertexAddr); + void *inds = 0; + if ((gstate.vertType & GE_VTYPE_IDX_MASK) != GE_VTYPE_IDX_NONE) { + if (!Memory::IsValidAddress(gstate_c.indexAddr)) { + ERROR_LOG_REPORT(G3D, "Bad index address %08x!", gstate_c.indexAddr); + return; + } + inds = Memory::GetPointerUnchecked(gstate_c.indexAddr); + } + +#ifndef MOBILE_DEVICE + if (prim > GE_PRIM_RECTANGLES) { + ERROR_LOG_REPORT_ONCE(reportPrim, G3D, "Unexpected prim type: %d", prim); + } +#endif + + int bytesRead = 0; + drawEngine_.SubmitPrim(verts, inds, prim, count, gstate.vertType, &bytesRead); + + int vertexCost = drawEngine_.EstimatePerVertexCost(); + gpuStats.vertexGPUCycles += vertexCost * count; + cyclesExecuted += vertexCost * count; + + // After drawing, we advance the vertexAddr (when non indexed) or indexAddr (when indexed). + // Some games rely on this, they don't bother reloading VADDR and IADDR. + // The VADDR/IADDR registers are NOT updated. + if (inds) { + int indexSize = 1; + if ((gstate.vertType & GE_VTYPE_IDX_MASK) == GE_VTYPE_IDX_16BIT) + indexSize = 2; + gstate_c.indexAddr += count * indexSize; + } else { + gstate_c.vertexAddr += bytesRead; + } +} + +void GPU_Vulkan::Execute_VertexType(u32 op, u32 diff) { + if (diff & (GE_VTYPE_TC_MASK | GE_VTYPE_THROUGH_MASK)) { + shaderManager_->DirtyUniform(DIRTY_UVSCALEOFFSET); + } +} + +void GPU_Vulkan::Execute_VertexTypeSkinning(u32 op, u32 diff) { + // Don't flush when weight count changes, unless morph is enabled. + if ((diff & ~GE_VTYPE_WEIGHTCOUNT_MASK) || (op & GE_VTYPE_MORPHCOUNT_MASK) != 0) { + // Restore and flush + gstate.vertType ^= diff; + Flush(); + gstate.vertType ^= diff; + if (diff & (GE_VTYPE_TC_MASK | GE_VTYPE_THROUGH_MASK)) + shaderManager_->DirtyUniform(DIRTY_UVSCALEOFFSET); + // In this case, we may be doing weights and morphs. + // Update any bone matrix uniforms so it uses them correctly. + if ((op & GE_VTYPE_MORPHCOUNT_MASK) != 0) { + shaderManager_->DirtyUniform(gstate_c.deferredVertTypeDirty); + gstate_c.deferredVertTypeDirty = 0; + } + } +} + +void GPU_Vulkan::Execute_Bezier(u32 op, u32 diff) { + // This also make skipping drawing very effective. + framebufferManager_.SetRenderFrameBuffer(gstate_c.framebufChanged, gstate_c.skipDrawReason); + if (gstate_c.skipDrawReason & (SKIPDRAW_SKIPFRAME | SKIPDRAW_NON_DISPLAYED_FB)) { + // TODO: Should this eat some cycles? Probably yes. Not sure if important. + return; + } + + if (!Memory::IsValidAddress(gstate_c.vertexAddr)) { + ERROR_LOG_REPORT(G3D, "Bad vertex address %08x!", gstate_c.vertexAddr); + return; + } + + void *control_points = Memory::GetPointerUnchecked(gstate_c.vertexAddr); + void *indices = NULL; + if ((gstate.vertType & GE_VTYPE_IDX_MASK) != GE_VTYPE_IDX_NONE) { + if (!Memory::IsValidAddress(gstate_c.indexAddr)) { + ERROR_LOG_REPORT(G3D, "Bad index address %08x!", gstate_c.indexAddr); + return; + } + indices = Memory::GetPointerUnchecked(gstate_c.indexAddr); + } + + if (gstate.getPatchPrimitiveType() == GE_PATCHPRIM_UNKNOWN) { + ERROR_LOG_REPORT(G3D, "Unsupported patch primitive %x", gstate.getPatchPrimitiveType()); + return; + } + + if (gstate.vertType & GE_VTYPE_MORPHCOUNT_MASK) { + DEBUG_LOG_REPORT(G3D, "Bezier + morph: %i", (gstate.vertType & GE_VTYPE_MORPHCOUNT_MASK) >> GE_VTYPE_MORPHCOUNT_SHIFT); + } + if (vertTypeIsSkinningEnabled(gstate.vertType)) { + DEBUG_LOG_REPORT(G3D, "Bezier + skinning: %i", vertTypeGetNumBoneWeights(gstate.vertType)); + } + + GEPatchPrimType patchPrim = gstate.getPatchPrimitiveType(); + int bz_ucount = op & 0xFF; + int bz_vcount = (op >> 8) & 0xFF; + bool computeNormals = gstate.isLightingEnabled(); + bool patchFacing = gstate.patchfacing & 1; + drawEngine_.SubmitBezier(control_points, indices, gstate.getPatchDivisionU(), gstate.getPatchDivisionV(), bz_ucount, bz_vcount, patchPrim, computeNormals, patchFacing, gstate.vertType); +} + +void GPU_Vulkan::Execute_Spline(u32 op, u32 diff) { + // This also make skipping drawing very effective. + framebufferManager_.SetRenderFrameBuffer(gstate_c.framebufChanged, gstate_c.skipDrawReason); + if (gstate_c.skipDrawReason & (SKIPDRAW_SKIPFRAME | SKIPDRAW_NON_DISPLAYED_FB)) { + // TODO: Should this eat some cycles? Probably yes. Not sure if important. + return; + } + + if (!Memory::IsValidAddress(gstate_c.vertexAddr)) { + ERROR_LOG_REPORT(G3D, "Bad vertex address %08x!", gstate_c.vertexAddr); + return; + } + + void *control_points = Memory::GetPointerUnchecked(gstate_c.vertexAddr); + void *indices = NULL; + if ((gstate.vertType & GE_VTYPE_IDX_MASK) != GE_VTYPE_IDX_NONE) { + if (!Memory::IsValidAddress(gstate_c.indexAddr)) { + ERROR_LOG_REPORT(G3D, "Bad index address %08x!", gstate_c.indexAddr); + return; + } + indices = Memory::GetPointerUnchecked(gstate_c.indexAddr); + } + + if (gstate.getPatchPrimitiveType() == GE_PATCHPRIM_UNKNOWN) { + ERROR_LOG_REPORT(G3D, "Unsupported patch primitive %x", gstate.getPatchPrimitiveType()); + return; + } + + if (gstate.vertType & GE_VTYPE_MORPHCOUNT_MASK) { + DEBUG_LOG_REPORT(G3D, "Spline + morph: %i", (gstate.vertType & GE_VTYPE_MORPHCOUNT_MASK) >> GE_VTYPE_MORPHCOUNT_SHIFT); + } + if (vertTypeIsSkinningEnabled(gstate.vertType)) { + DEBUG_LOG_REPORT(G3D, "Spline + skinning: %i", vertTypeGetNumBoneWeights(gstate.vertType)); + } + + int sp_ucount = op & 0xFF; + int sp_vcount = (op >> 8) & 0xFF; + int sp_utype = (op >> 16) & 0x3; + int sp_vtype = (op >> 18) & 0x3; + GEPatchPrimType patchPrim = gstate.getPatchPrimitiveType(); + bool computeNormals = gstate.isLightingEnabled(); + bool patchFacing = gstate.patchfacing & 1; + u32 vertType = gstate.vertType; + drawEngine_.SubmitSpline(control_points, indices, gstate.getPatchDivisionU(), gstate.getPatchDivisionV(), sp_ucount, sp_vcount, sp_utype, sp_vtype, patchPrim, computeNormals, patchFacing, vertType); +} + +void GPU_Vulkan::Execute_BoundingBox(u32 op, u32 diff) { + // Just resetting, nothing to bound. + const u32 data = op & 0x00FFFFFF; + if (data == 0) { + // TODO: Should this set the bboxResult? Let's set it true for now. + currentList->bboxResult = true; + return; + } + if (((data & 7) == 0) && data <= 64) { // Sanity check + void *control_points = Memory::GetPointer(gstate_c.vertexAddr); + if (gstate.vertType & GE_VTYPE_IDX_MASK) { + ERROR_LOG_REPORT_ONCE(boundingbox, G3D, "Indexed bounding box data not supported."); + // Data seems invalid. Let's assume the box test passed. + currentList->bboxResult = true; + return; + } + + // Test if the bounding box is within the drawing region. + currentList->bboxResult = drawEngine_.TestBoundingBox(control_points, data, gstate.vertType); + } else { + ERROR_LOG_REPORT_ONCE(boundingbox, G3D, "Bad bounding box data: %06x", data); + // Data seems invalid. Let's assume the box test passed. + currentList->bboxResult = true; + } +} + +void GPU_Vulkan::Execute_Region(u32 op, u32 diff) { + gstate_c.framebufChanged = true; + gstate_c.textureChanged |= TEXCHANGE_PARAMSONLY; +} + +void GPU_Vulkan::Execute_Scissor(u32 op, u32 diff) { + gstate_c.framebufChanged = true; + gstate_c.textureChanged |= TEXCHANGE_PARAMSONLY; +} + +void GPU_Vulkan::Execute_FramebufType(u32 op, u32 diff) { + gstate_c.framebufChanged = true; + gstate_c.textureChanged |= TEXCHANGE_PARAMSONLY; +} + +void GPU_Vulkan::Execute_ViewportType(u32 op, u32 diff) { + gstate_c.framebufChanged = true; + gstate_c.textureChanged |= TEXCHANGE_PARAMSONLY; +} + +void GPU_Vulkan::Execute_ViewportZType(u32 op, u32 diff) { + gstate_c.framebufChanged = true; + gstate_c.textureChanged |= TEXCHANGE_PARAMSONLY; + shaderManager_->DirtyUniform(DIRTY_DEPTHRANGE); +} + +void GPU_Vulkan::Execute_TexScaleU(u32 op, u32 diff) { + gstate_c.uv.uScale = getFloat24(op); + shaderManager_->DirtyUniform(DIRTY_UVSCALEOFFSET); +} + +void GPU_Vulkan::Execute_TexScaleV(u32 op, u32 diff) { + gstate_c.uv.vScale = getFloat24(op); + shaderManager_->DirtyUniform(DIRTY_UVSCALEOFFSET); +} + +void GPU_Vulkan::Execute_TexOffsetU(u32 op, u32 diff) { + gstate_c.uv.uOff = getFloat24(op); + shaderManager_->DirtyUniform(DIRTY_UVSCALEOFFSET); +} + +void GPU_Vulkan::Execute_TexOffsetV(u32 op, u32 diff) { + gstate_c.uv.vOff = getFloat24(op); + shaderManager_->DirtyUniform(DIRTY_UVSCALEOFFSET); +} + +void GPU_Vulkan::Execute_TexAddr0(u32 op, u32 diff) { + gstate_c.textureChanged = TEXCHANGE_UPDATED; + shaderManager_->DirtyUniform(DIRTY_UVSCALEOFFSET); +} + +void GPU_Vulkan::Execute_TexAddrN(u32 op, u32 diff) { + gstate_c.textureChanged |= TEXCHANGE_PARAMSONLY; +} + +void GPU_Vulkan::Execute_TexBufw0(u32 op, u32 diff) { + gstate_c.textureChanged = TEXCHANGE_UPDATED; +} + +void GPU_Vulkan::Execute_TexBufwN(u32 op, u32 diff) { + gstate_c.textureChanged |= TEXCHANGE_PARAMSONLY; +} + +void GPU_Vulkan::Execute_TexSize0(u32 op, u32 diff) { + // Render to texture may have overridden the width/height. + // Don't reset it unless the size is different / the texture has changed. + if (diff || gstate_c.textureChanged != TEXCHANGE_UNCHANGED) { + gstate_c.curTextureWidth = gstate.getTextureWidth(0); + gstate_c.curTextureHeight = gstate.getTextureHeight(0); + shaderManager_->DirtyUniform(DIRTY_UVSCALEOFFSET); + // We will need to reset the texture now. + gstate_c.textureChanged |= TEXCHANGE_PARAMSONLY; + } +} + +void GPU_Vulkan::Execute_TexSizeN(u32 op, u32 diff) { + gstate_c.textureChanged |= TEXCHANGE_PARAMSONLY; +} + +void GPU_Vulkan::Execute_TexFormat(u32 op, u32 diff) { + gstate_c.textureChanged = TEXCHANGE_UPDATED; +} + +void GPU_Vulkan::Execute_TexMapMode(u32 op, u32 diff) { + shaderManager_->DirtyUniform(DIRTY_UVSCALEOFFSET); +} + +void GPU_Vulkan::Execute_TexParamType(u32 op, u32 diff) { + gstate_c.textureChanged |= TEXCHANGE_PARAMSONLY; +} + +void GPU_Vulkan::Execute_TexEnvColor(u32 op, u32 diff) { + shaderManager_->DirtyUniform(DIRTY_TEXENV); +} + +void GPU_Vulkan::Execute_TexLevel(u32 op, u32 diff) { + // I had hoped that this would let us avoid excessively flushing in Gran Turismo, but not so, + // as the game switches rapidly between modes 0 and 1. + /* + if (gstate.getTexLevelMode() == GE_TEXLEVEL_MODE_CONST) { + gstate.texlevel ^= diff; + Flush(); + gstate.texlevel ^= diff; + } + */ + gstate_c.textureChanged |= TEXCHANGE_PARAMSONLY; +} + +void GPU_Vulkan::Execute_LoadClut(u32 op, u32 diff) { + gstate_c.textureChanged |= TEXCHANGE_PARAMSONLY; + textureCache_.LoadClut(gstate.getClutAddress(), gstate.getClutLoadBytes()); + // This could be used to "dirty" textures with clut. +} + +void GPU_Vulkan::Execute_ClutFormat(u32 op, u32 diff) { + gstate_c.textureChanged |= TEXCHANGE_PARAMSONLY; + // This could be used to "dirty" textures with clut. +} + +void GPU_Vulkan::Execute_Ambient(u32 op, u32 diff) { + shaderManager_->DirtyUniform(DIRTY_AMBIENT); +} + +void GPU_Vulkan::Execute_MaterialDiffuse(u32 op, u32 diff) { + shaderManager_->DirtyUniform(DIRTY_MATDIFFUSE); +} + +void GPU_Vulkan::Execute_MaterialEmissive(u32 op, u32 diff) { + shaderManager_->DirtyUniform(DIRTY_MATEMISSIVE); +} + +void GPU_Vulkan::Execute_MaterialAmbient(u32 op, u32 diff) { + shaderManager_->DirtyUniform(DIRTY_MATAMBIENTALPHA); +} + +void GPU_Vulkan::Execute_MaterialSpecular(u32 op, u32 diff) { + shaderManager_->DirtyUniform(DIRTY_MATSPECULAR); +} + +void GPU_Vulkan::Execute_Light0Param(u32 op, u32 diff) { + shaderManager_->DirtyUniform(DIRTY_LIGHT0); +} + +void GPU_Vulkan::Execute_Light1Param(u32 op, u32 diff) { + shaderManager_->DirtyUniform(DIRTY_LIGHT1); +} + +void GPU_Vulkan::Execute_Light2Param(u32 op, u32 diff) { + shaderManager_->DirtyUniform(DIRTY_LIGHT2); +} + +void GPU_Vulkan::Execute_Light3Param(u32 op, u32 diff) { + shaderManager_->DirtyUniform(DIRTY_LIGHT3); +} + +void GPU_Vulkan::Execute_FogColor(u32 op, u32 diff) { + shaderManager_->DirtyUniform(DIRTY_FOGCOLOR); +} + +void GPU_Vulkan::Execute_FogCoef(u32 op, u32 diff) { + shaderManager_->DirtyUniform(DIRTY_FOGCOEF); +} + +void GPU_Vulkan::Execute_ColorTestMask(u32 op, u32 diff) { + shaderManager_->DirtyUniform(DIRTY_ALPHACOLORMASK); +} + +void GPU_Vulkan::Execute_AlphaTest(u32 op, u32 diff) { + shaderManager_->DirtyUniform(DIRTY_ALPHACOLORREF); + shaderManager_->DirtyUniform(DIRTY_ALPHACOLORMASK); +} + +void GPU_Vulkan::Execute_StencilTest(u32 op, u32 diff) { + shaderManager_->DirtyUniform(DIRTY_STENCILREPLACEVALUE); +} + +void GPU_Vulkan::Execute_ColorRef(u32 op, u32 diff) { + shaderManager_->DirtyUniform(DIRTY_ALPHACOLORREF); +} + +void GPU_Vulkan::Execute_WorldMtxNum(u32 op, u32 diff) { + // This is almost always followed by GE_CMD_WORLDMATRIXDATA. + const u32_le *src = (const u32_le *)Memory::GetPointerUnchecked(currentList->pc + 4); + u32 *dst = (u32 *)(gstate.worldMatrix + (op & 0xF)); + const int end = 12 - (op & 0xF); + int i = 0; + + while ((src[i] >> 24) == GE_CMD_WORLDMATRIXDATA) { + const u32 newVal = src[i] << 8; + if (dst[i] != newVal) { + Flush(); + dst[i] = newVal; + shaderManager_->DirtyUniform(DIRTY_WORLDMATRIX); + } + if (++i >= end) { + break; + } + } + + const int count = i; + gstate.worldmtxnum = (GE_CMD_WORLDMATRIXNUMBER << 24) | ((op + count) & 0xF); + + // Skip over the loaded data, it's done now. + UpdatePC(currentList->pc, currentList->pc + count * 4); + currentList->pc += count * 4; +} + +void GPU_Vulkan::Execute_WorldMtxData(u32 op, u32 diff) { + // Note: it's uncommon to get here now, see above. + int num = gstate.worldmtxnum & 0xF; + u32 newVal = op << 8; + if (num < 12 && newVal != ((const u32 *)gstate.worldMatrix)[num]) { + Flush(); + ((u32 *)gstate.worldMatrix)[num] = newVal; + shaderManager_->DirtyUniform(DIRTY_WORLDMATRIX); + } + num++; + gstate.worldmtxnum = (GE_CMD_WORLDMATRIXNUMBER << 24) | (num & 0xF); +} + +void GPU_Vulkan::Execute_ViewMtxNum(u32 op, u32 diff) { + // This is almost always followed by GE_CMD_VIEWMATRIXDATA. + const u32_le *src = (const u32_le *)Memory::GetPointerUnchecked(currentList->pc + 4); + u32 *dst = (u32 *)(gstate.viewMatrix + (op & 0xF)); + const int end = 12 - (op & 0xF); + int i = 0; + + while ((src[i] >> 24) == GE_CMD_VIEWMATRIXDATA) { + const u32 newVal = src[i] << 8; + if (dst[i] != newVal) { + Flush(); + dst[i] = newVal; + shaderManager_->DirtyUniform(DIRTY_VIEWMATRIX); + } + if (++i >= end) { + break; + } + } + + const int count = i; + gstate.viewmtxnum = (GE_CMD_VIEWMATRIXNUMBER << 24) | ((op + count) & 0xF); + + // Skip over the loaded data, it's done now. + UpdatePC(currentList->pc, currentList->pc + count * 4); + currentList->pc += count * 4; +} + +void GPU_Vulkan::Execute_ViewMtxData(u32 op, u32 diff) { + // Note: it's uncommon to get here now, see above. + int num = gstate.viewmtxnum & 0xF; + u32 newVal = op << 8; + if (num < 12 && newVal != ((const u32 *)gstate.viewMatrix)[num]) { + Flush(); + ((u32 *)gstate.viewMatrix)[num] = newVal; + shaderManager_->DirtyUniform(DIRTY_VIEWMATRIX); + } + num++; + gstate.viewmtxnum = (GE_CMD_VIEWMATRIXNUMBER << 24) | (num & 0xF); +} + +void GPU_Vulkan::Execute_ProjMtxNum(u32 op, u32 diff) { + // This is almost always followed by GE_CMD_PROJMATRIXDATA. + const u32_le *src = (const u32_le *)Memory::GetPointerUnchecked(currentList->pc + 4); + u32 *dst = (u32 *)(gstate.projMatrix + (op & 0xF)); + const int end = 16 - (op & 0xF); + int i = 0; + + while ((src[i] >> 24) == GE_CMD_PROJMATRIXDATA) { + const u32 newVal = src[i] << 8; + if (dst[i] != newVal) { + Flush(); + dst[i] = newVal; + shaderManager_->DirtyUniform(DIRTY_PROJMATRIX); + } + if (++i >= end) { + break; + } + } + + const int count = i; + gstate.projmtxnum = (GE_CMD_PROJMATRIXNUMBER << 24) | ((op + count) & 0xF); + + // Skip over the loaded data, it's done now. + UpdatePC(currentList->pc, currentList->pc + count * 4); + currentList->pc += count * 4; +} + +void GPU_Vulkan::Execute_ProjMtxData(u32 op, u32 diff) { + // Note: it's uncommon to get here now, see above. + int num = gstate.projmtxnum & 0xF; + u32 newVal = op << 8; + if (newVal != ((const u32 *)gstate.projMatrix)[num]) { + Flush(); + ((u32 *)gstate.projMatrix)[num] = newVal; + shaderManager_->DirtyUniform(DIRTY_PROJMATRIX); + } + num++; + gstate.projmtxnum = (GE_CMD_PROJMATRIXNUMBER << 24) | (num & 0xF); +} + +void GPU_Vulkan::Execute_TgenMtxNum(u32 op, u32 diff) { + // This is almost always followed by GE_CMD_TGENMATRIXDATA. + const u32_le *src = (const u32_le *)Memory::GetPointerUnchecked(currentList->pc + 4); + u32 *dst = (u32 *)(gstate.tgenMatrix + (op & 0xF)); + const int end = 12 - (op & 0xF); + int i = 0; + + while ((src[i] >> 24) == GE_CMD_TGENMATRIXDATA) { + const u32 newVal = src[i] << 8; + if (dst[i] != newVal) { + Flush(); + dst[i] = newVal; + shaderManager_->DirtyUniform(DIRTY_TEXMATRIX); + } + if (++i >= end) { + break; + } + } + + const int count = i; + gstate.texmtxnum = (GE_CMD_TGENMATRIXNUMBER << 24) | ((op + count) & 0xF); + + // Skip over the loaded data, it's done now. + UpdatePC(currentList->pc, currentList->pc + count * 4); + currentList->pc += count * 4; +} + +void GPU_Vulkan::Execute_TgenMtxData(u32 op, u32 diff) { + // Note: it's uncommon to get here now, see above. + int num = gstate.texmtxnum & 0xF; + u32 newVal = op << 8; + if (num < 12 && newVal != ((const u32 *)gstate.tgenMatrix)[num]) { + Flush(); + ((u32 *)gstate.tgenMatrix)[num] = newVal; + shaderManager_->DirtyUniform(DIRTY_TEXMATRIX); + } + num++; + gstate.texmtxnum = (GE_CMD_TGENMATRIXNUMBER << 24) | (num & 0xF); +} + +void GPU_Vulkan::Execute_BoneMtxNum(u32 op, u32 diff) { + // This is almost always followed by GE_CMD_BONEMATRIXDATA. + const u32_le *src = (const u32_le *)Memory::GetPointerUnchecked(currentList->pc + 4); + u32 *dst = (u32 *)(gstate.boneMatrix + (op & 0x7F)); + const int end = 12 * 8 - (op & 0x7F); + int i = 0; + + // If we can't use software skinning, we have to flush and dirty. + if (!g_Config.bSoftwareSkinning || (gstate.vertType & GE_VTYPE_MORPHCOUNT_MASK) != 0) { + while ((src[i] >> 24) == GE_CMD_BONEMATRIXDATA) { + const u32 newVal = src[i] << 8; + if (dst[i] != newVal) { + Flush(); + dst[i] = newVal; + } + if (++i >= end) { + break; + } + } + + const int numPlusCount = (op & 0x7F) + i; + for (int num = op & 0x7F; num < numPlusCount; num += 12) { + shaderManager_->DirtyUniform(DIRTY_BONEMATRIX0 << (num / 12)); + } + } else { + while ((src[i] >> 24) == GE_CMD_BONEMATRIXDATA) { + dst[i] = src[i] << 8; + if (++i >= end) { + break; + } + } + + const int numPlusCount = (op & 0x7F) + i; + for (int num = op & 0x7F; num < numPlusCount; num += 12) { + gstate_c.deferredVertTypeDirty |= DIRTY_BONEMATRIX0 << (num / 12); + } + } + + const int count = i; + gstate.boneMatrixNumber = (GE_CMD_BONEMATRIXNUMBER << 24) | ((op + count) & 0x7F); + + // Skip over the loaded data, it's done now. + UpdatePC(currentList->pc, currentList->pc + count * 4); + currentList->pc += count * 4; +} + +void GPU_Vulkan::Execute_BoneMtxData(u32 op, u32 diff) { + // Note: it's uncommon to get here now, see above. + int num = gstate.boneMatrixNumber & 0x7F; + u32 newVal = op << 8; + if (num < 96 && newVal != ((const u32 *)gstate.boneMatrix)[num]) { + // Bone matrices should NOT flush when software skinning is enabled! + if (!g_Config.bSoftwareSkinning || (gstate.vertType & GE_VTYPE_MORPHCOUNT_MASK) != 0) { + Flush(); + shaderManager_->DirtyUniform(DIRTY_BONEMATRIX0 << (num / 12)); + } else { + gstate_c.deferredVertTypeDirty |= DIRTY_BONEMATRIX0 << (num / 12); + } + ((u32 *)gstate.boneMatrix)[num] = newVal; + } + num++; + gstate.boneMatrixNumber = (GE_CMD_BONEMATRIXNUMBER << 24) | (num & 0x7F); +} + +void GPU_Vulkan::Execute_BlockTransferStart(u32 op, u32 diff) { + // TODO: Here we should check if the transfer overlaps a framebuffer or any textures, + // and take appropriate action. This is a block transfer between RAM and VRAM, or vice versa. + // Can we skip this on SkipDraw? + DoBlockTransfer(gstate_c.skipDrawReason); + + // Fixes Gran Turismo's funky text issue, since it overwrites the current texture. + gstate_c.textureChanged = TEXCHANGE_UPDATED; +} + +void GPU_Vulkan::Execute_Generic(u32 op, u32 diff) { + u32 cmd = op >> 24; + u32 data = op & 0xFFFFFF; + + // Handle control and drawing commands here directly. The others we delegate. + switch (cmd) { + case GE_CMD_BASE: + break; + + case GE_CMD_VADDR: + Execute_Vaddr(op, diff); + break; + + case GE_CMD_IADDR: + Execute_Iaddr(op, diff); + break; + + case GE_CMD_PRIM: + Execute_Prim(op, diff); + break; + + // The arrow and other rotary items in Puzbob are bezier patches, strangely enough. + case GE_CMD_BEZIER: + Execute_Bezier(op, diff); + break; + + case GE_CMD_SPLINE: + Execute_Spline(op, diff); + break; + + case GE_CMD_BOUNDINGBOX: + Execute_BoundingBox(op, diff); + break; + + case GE_CMD_VERTEXTYPE: + Execute_VertexType(op, diff); + break; + + case GE_CMD_REGION1: + case GE_CMD_REGION2: + Execute_Region(op, diff); + break; + + case GE_CMD_CLIPENABLE: + //we always clip, this is opengl + break; + + case GE_CMD_CULLFACEENABLE: + case GE_CMD_CULL: + break; + + case GE_CMD_TEXTUREMAPENABLE: + // Don't need to dirty the texture here, already dirtied at list start/etc. + break; + + case GE_CMD_LIGHTINGENABLE: + break; + + case GE_CMD_FOGCOLOR: + Execute_FogColor(op, diff); + break; + + case GE_CMD_FOG1: + case GE_CMD_FOG2: + Execute_FogCoef(op, diff); + break; + + case GE_CMD_FOGENABLE: + break; + + case GE_CMD_DITHERENABLE: + break; + + case GE_CMD_OFFSETX: + break; + + case GE_CMD_OFFSETY: + break; + + case GE_CMD_TEXSCALEU: + Execute_TexScaleU(op, diff); + break; + + case GE_CMD_TEXSCALEV: + Execute_TexScaleV(op, diff); + break; + + case GE_CMD_TEXOFFSETU: + Execute_TexOffsetU(op, diff); + break; + + case GE_CMD_TEXOFFSETV: + Execute_TexOffsetV(op, diff); + break; + + case GE_CMD_SCISSOR1: + case GE_CMD_SCISSOR2: + Execute_Scissor(op, diff); + break; + + /// + case GE_CMD_MINZ: + case GE_CMD_MAXZ: + break; + + case GE_CMD_FRAMEBUFPTR: + case GE_CMD_FRAMEBUFWIDTH: + case GE_CMD_FRAMEBUFPIXFORMAT: + Execute_FramebufType(op, diff); + break; + + case GE_CMD_TEXADDR0: + Execute_TexAddr0(op, diff); + break; + + case GE_CMD_TEXADDR1: + case GE_CMD_TEXADDR2: + case GE_CMD_TEXADDR3: + case GE_CMD_TEXADDR4: + case GE_CMD_TEXADDR5: + case GE_CMD_TEXADDR6: + case GE_CMD_TEXADDR7: + Execute_TexAddrN(op, diff); + break; + + case GE_CMD_TEXBUFWIDTH0: + Execute_TexBufw0(op, diff); + break; + + case GE_CMD_TEXBUFWIDTH1: + case GE_CMD_TEXBUFWIDTH2: + case GE_CMD_TEXBUFWIDTH3: + case GE_CMD_TEXBUFWIDTH4: + case GE_CMD_TEXBUFWIDTH5: + case GE_CMD_TEXBUFWIDTH6: + case GE_CMD_TEXBUFWIDTH7: + Execute_TexBufwN(op, diff); + break; + + case GE_CMD_CLUTFORMAT: + Execute_ClutFormat(op, diff); + break; + + case GE_CMD_CLUTADDR: + case GE_CMD_CLUTADDRUPPER: + // Hm, LOADCLUT actually changes the CLUT so no need to dirty here. + break; + + case GE_CMD_LOADCLUT: + Execute_LoadClut(op, diff); + break; + + case GE_CMD_TEXMAPMODE: + Execute_TexMapMode(op, diff); + break; + + case GE_CMD_TEXSHADELS: + break; + + case GE_CMD_TRANSFERSRC: + case GE_CMD_TRANSFERSRCW: + case GE_CMD_TRANSFERDST: + case GE_CMD_TRANSFERDSTW: + case GE_CMD_TRANSFERSRCPOS: + case GE_CMD_TRANSFERDSTPOS: + break; + + case GE_CMD_TRANSFERSIZE: + break; + + case GE_CMD_TRANSFERSTART: // Orphis calls this TRXKICK + Execute_BlockTransferStart(op, diff); + break; + + case GE_CMD_TEXSIZE0: + Execute_TexSize0(op, diff); + break; + + case GE_CMD_TEXSIZE1: + case GE_CMD_TEXSIZE2: + case GE_CMD_TEXSIZE3: + case GE_CMD_TEXSIZE4: + case GE_CMD_TEXSIZE5: + case GE_CMD_TEXSIZE6: + case GE_CMD_TEXSIZE7: + Execute_TexSizeN(op, diff); + break; + + case GE_CMD_ZBUFPTR: + case GE_CMD_ZBUFWIDTH: + break; + + case GE_CMD_AMBIENTCOLOR: + case GE_CMD_AMBIENTALPHA: + Execute_Ambient(op, diff); + break; + + case GE_CMD_MATERIALDIFFUSE: + Execute_MaterialDiffuse(op, diff); + break; + + case GE_CMD_MATERIALEMISSIVE: + Execute_MaterialEmissive(op, diff); + break; + + case GE_CMD_MATERIALAMBIENT: + case GE_CMD_MATERIALALPHA: + Execute_MaterialAmbient(op, diff); + break; + + case GE_CMD_MATERIALSPECULAR: + case GE_CMD_MATERIALSPECULARCOEF: + Execute_MaterialSpecular(op, diff); + break; + + case GE_CMD_LIGHTTYPE0: + case GE_CMD_LIGHTTYPE1: + case GE_CMD_LIGHTTYPE2: + case GE_CMD_LIGHTTYPE3: + break; + + case GE_CMD_LX0:case GE_CMD_LY0:case GE_CMD_LZ0: + case GE_CMD_LDX0:case GE_CMD_LDY0:case GE_CMD_LDZ0: + case GE_CMD_LKA0:case GE_CMD_LKB0:case GE_CMD_LKC0: + case GE_CMD_LKS0: // spot coef ("conv") + case GE_CMD_LKO0: // light angle ("cutoff") + case GE_CMD_LAC0: + case GE_CMD_LDC0: + case GE_CMD_LSC0: + Execute_Light0Param(op, diff); + break; + case GE_CMD_LX1:case GE_CMD_LY1:case GE_CMD_LZ1: + case GE_CMD_LDX1:case GE_CMD_LDY1:case GE_CMD_LDZ1: + case GE_CMD_LKA1:case GE_CMD_LKB1:case GE_CMD_LKC1: + case GE_CMD_LKS1: + case GE_CMD_LKO1: + case GE_CMD_LAC1: + case GE_CMD_LDC1: + case GE_CMD_LSC1: + Execute_Light1Param(op, diff); + break; + case GE_CMD_LX2:case GE_CMD_LY2:case GE_CMD_LZ2: + case GE_CMD_LDX2:case GE_CMD_LDY2:case GE_CMD_LDZ2: + case GE_CMD_LKA2:case GE_CMD_LKB2:case GE_CMD_LKC2: + case GE_CMD_LKS2: + case GE_CMD_LKO2: + case GE_CMD_LAC2: + case GE_CMD_LDC2: + case GE_CMD_LSC2: + Execute_Light2Param(op, diff); + break; + case GE_CMD_LX3:case GE_CMD_LY3:case GE_CMD_LZ3: + case GE_CMD_LDX3:case GE_CMD_LDY3:case GE_CMD_LDZ3: + case GE_CMD_LKA3:case GE_CMD_LKB3:case GE_CMD_LKC3: + case GE_CMD_LKS3: + case GE_CMD_LKO3: + case GE_CMD_LAC3: + case GE_CMD_LDC3: + case GE_CMD_LSC3: + Execute_Light3Param(op, diff); + break; + + case GE_CMD_VIEWPORTXSCALE: + case GE_CMD_VIEWPORTYSCALE: + case GE_CMD_VIEWPORTXCENTER: + case GE_CMD_VIEWPORTYCENTER: + case GE_CMD_VIEWPORTZSCALE: + case GE_CMD_VIEWPORTZCENTER: + Execute_ViewportType(op, diff); + break; + + case GE_CMD_LIGHTENABLE0: + case GE_CMD_LIGHTENABLE1: + case GE_CMD_LIGHTENABLE2: + case GE_CMD_LIGHTENABLE3: + break; + + case GE_CMD_SHADEMODE: + break; + + case GE_CMD_PATCHDIVISION: + case GE_CMD_PATCHPRIMITIVE: + case GE_CMD_PATCHFACING: + break; + + + case GE_CMD_MATERIALUPDATE: + break; + + ////////////////////////////////////////////////////////////////// + // CLEARING + ////////////////////////////////////////////////////////////////// + case GE_CMD_CLEARMODE: + break; + + ////////////////////////////////////////////////////////////////// + // ALPHA BLENDING + ////////////////////////////////////////////////////////////////// + case GE_CMD_ALPHABLENDENABLE: + case GE_CMD_BLENDMODE: + break; + + case GE_CMD_BLENDFIXEDA: + case GE_CMD_BLENDFIXEDB: + break; + + case GE_CMD_ALPHATESTENABLE: + case GE_CMD_COLORTESTENABLE: + // They are done in the fragment shader. + break; + + case GE_CMD_COLORTEST: + break; + + case GE_CMD_COLORTESTMASK: + Execute_ColorTestMask(op, diff); + break; + + case GE_CMD_ALPHATEST: + Execute_AlphaTest(op, diff); + break; + + case GE_CMD_COLORREF: + Execute_ColorRef(op, diff); + break; + + case GE_CMD_TEXENVCOLOR: + Execute_TexEnvColor(op, diff); + break; + + case GE_CMD_TEXFUNC: + case GE_CMD_TEXFLUSH: + break; + + case GE_CMD_TEXFORMAT: + Execute_TexFormat(op, diff); + break; + + case GE_CMD_TEXMODE: + case GE_CMD_TEXFILTER: + case GE_CMD_TEXWRAP: + Execute_TexParamType(op, diff); + break; + + ////////////////////////////////////////////////////////////////// + // DEPTH TESTING + ////////////////////////////////////////////////////////////////// + + case GE_CMD_ZTESTENABLE: + case GE_CMD_ZTEST: + case GE_CMD_ZWRITEDISABLE: + break; + + case GE_CMD_MORPHWEIGHT0: + case GE_CMD_MORPHWEIGHT1: + case GE_CMD_MORPHWEIGHT2: + case GE_CMD_MORPHWEIGHT3: + case GE_CMD_MORPHWEIGHT4: + case GE_CMD_MORPHWEIGHT5: + case GE_CMD_MORPHWEIGHT6: + case GE_CMD_MORPHWEIGHT7: + gstate_c.morphWeights[cmd - GE_CMD_MORPHWEIGHT0] = getFloat24(data); + break; + + case GE_CMD_DITH0: + case GE_CMD_DITH1: + case GE_CMD_DITH2: + case GE_CMD_DITH3: + break; + + case GE_CMD_WORLDMATRIXNUMBER: + Execute_WorldMtxNum(op, diff); + break; + + case GE_CMD_WORLDMATRIXDATA: + Execute_WorldMtxData(op, diff); + break; + + case GE_CMD_VIEWMATRIXNUMBER: + Execute_ViewMtxNum(op, diff); + break; + + case GE_CMD_VIEWMATRIXDATA: + Execute_ViewMtxData(op, diff); + break; + + case GE_CMD_PROJMATRIXNUMBER: + Execute_ProjMtxNum(op, diff); + break; + + case GE_CMD_PROJMATRIXDATA: + Execute_ProjMtxData(op, diff); + break; + + case GE_CMD_TGENMATRIXNUMBER: + Execute_TgenMtxNum(op, diff); + break; + + case GE_CMD_TGENMATRIXDATA: + Execute_TgenMtxData(op, diff); + break; + + case GE_CMD_BONEMATRIXNUMBER: + Execute_BoneMtxNum(op, diff); + break; + + case GE_CMD_BONEMATRIXDATA: + Execute_BoneMtxData(op, diff); + break; + +#ifndef MOBILE_DEVICE + case GE_CMD_ANTIALIASENABLE: + if (data != 0) + WARN_LOG_REPORT_ONCE(antiAlias, G3D, "Unsupported antialias enabled: %06x", data); + break; + + case GE_CMD_TEXLODSLOPE: + if (data != 0) + WARN_LOG_REPORT_ONCE(texLodSlope, G3D, "Unsupported texture lod slope: %06x", data); + break; +#endif + + case GE_CMD_TEXLEVEL: + Execute_TexLevel(op, diff); + break; + + ////////////////////////////////////////////////////////////////// + // STENCIL TESTING + ////////////////////////////////////////////////////////////////// + + case GE_CMD_STENCILTEST: + Execute_StencilTest(op, diff); + break; + + case GE_CMD_STENCILTESTENABLE: + case GE_CMD_STENCILOP: + break; + + case GE_CMD_MASKRGB: + case GE_CMD_MASKALPHA: + break; + + case GE_CMD_REVERSENORMAL: + break; + + case GE_CMD_VSCX: + if (data != 0) + WARN_LOG_REPORT_ONCE(vscx, G3D, "Unsupported Vertex Screen Coordinate X : %06x", data); + break; + + case GE_CMD_VSCY: + if (data != 0) + WARN_LOG_REPORT_ONCE(vscy, G3D, "Unsupported Vertex Screen Coordinate Y : %06x", data); + break; + + case GE_CMD_VSCZ: + if (data != 0) + WARN_LOG_REPORT_ONCE(vscz, G3D, "Unsupported Vertex Screen Coordinate Z : %06x", data); + break; + + case GE_CMD_VTCS: + if (data != 0) + WARN_LOG_REPORT_ONCE(vtcs, G3D, "Unsupported Vertex Texture Coordinate S : %06x", data); + break; + + case GE_CMD_VTCT: + if (data != 0) + WARN_LOG_REPORT_ONCE(vtct, G3D, "Unsupported Vertex Texture Coordinate T : %06x", data); + break; + + case GE_CMD_VTCQ: + if (data != 0) + WARN_LOG_REPORT_ONCE(vtcq, G3D, "Unsupported Vertex Texture Coordinate Q : %06x", data); + break; + + case GE_CMD_VCV: + if (data != 0) + WARN_LOG_REPORT_ONCE(vcv, G3D, "Unsupported Vertex Color Value : %06x", data); + break; + + case GE_CMD_VAP: + if (data != 0) + WARN_LOG_REPORT_ONCE(vap, G3D, "Unsupported Vertex Alpha and Primitive : %06x", data); + break; + + case GE_CMD_VFC: + if (data != 0) + WARN_LOG_REPORT_ONCE(vfc, G3D, "Unsupported Vertex Fog Coefficient : %06x", data); + break; + + case GE_CMD_VSCV: + if (data != 0) + WARN_LOG_REPORT_ONCE(vscv, G3D, "Unsupported Vertex Secondary Color Value : %06x", data); + break; + + + case GE_CMD_UNKNOWN_03: + case GE_CMD_UNKNOWN_0D: + case GE_CMD_UNKNOWN_11: + case GE_CMD_UNKNOWN_29: + case GE_CMD_UNKNOWN_34: + case GE_CMD_UNKNOWN_35: + case GE_CMD_UNKNOWN_39: + case GE_CMD_UNKNOWN_4E: + case GE_CMD_UNKNOWN_4F: + case GE_CMD_UNKNOWN_52: + case GE_CMD_UNKNOWN_59: + case GE_CMD_UNKNOWN_5A: + case GE_CMD_UNKNOWN_B6: + case GE_CMD_UNKNOWN_B7: + case GE_CMD_UNKNOWN_D1: + case GE_CMD_UNKNOWN_ED: + case GE_CMD_UNKNOWN_EF: + case GE_CMD_UNKNOWN_FA: + case GE_CMD_UNKNOWN_FB: + case GE_CMD_UNKNOWN_FC: + case GE_CMD_UNKNOWN_FD: + case GE_CMD_UNKNOWN_FE: + if (data != 0) + WARN_LOG_REPORT_ONCE(unknowncmd, G3D, "Unknown GE command : %08x ", op); + break; + case GE_CMD_UNKNOWN_FF: + // This is hit in quite a few games, supposedly it is a no-op. + // Might be used for debugging or something? + break; + + default: + GPUCommon::ExecuteOp(op, diff); + break; + } +} + +void GPU_Vulkan::FastLoadBoneMatrix(u32 target) { + const int num = gstate.boneMatrixNumber & 0x7F; + const int mtxNum = num / 12; + uint32_t uniformsToDirty = DIRTY_BONEMATRIX0 << mtxNum; + if ((num - 12 * mtxNum) != 0) { + uniformsToDirty |= DIRTY_BONEMATRIX0 << ((mtxNum + 1) & 7); + } + + if (!g_Config.bSoftwareSkinning || (gstate.vertType & GE_VTYPE_MORPHCOUNT_MASK) != 0) { + Flush(); + shaderManager_->DirtyUniform(uniformsToDirty); + } else { + gstate_c.deferredVertTypeDirty |= uniformsToDirty; + } + gstate.FastLoadBoneMatrix(target); +} + +void GPU_Vulkan::DeviceLost() { + // TODO +} + +void GPU_Vulkan::UpdateStats() { + gpuStats.numVertexShaders = shaderManager_->GetNumVertexShaders(); + gpuStats.numFragmentShaders = shaderManager_->GetNumFragmentShaders(); + gpuStats.numShaders = pipelineManager_->GetNumPipelines(); + gpuStats.numTextures = (int)textureCache_.NumLoadedTextures(); + gpuStats.numFBOs = (int)framebufferManager_.NumVFBs(); +} + +void GPU_Vulkan::DoBlockTransfer(u32 skipDrawReason) { + // TODO: This is used a lot to copy data around between render targets and textures, + // and also to quickly load textures from RAM to VRAM. So we should do checks like the following: + // * Does dstBasePtr point to an existing texture? If so maybe reload it immediately. + // + // * Does srcBasePtr point to a render target, and dstBasePtr to a texture? If so + // either copy between rt and texture or reassign the texture to point to the render target + // + // etc.... + + u32 srcBasePtr = gstate.getTransferSrcAddress(); + u32 srcStride = gstate.getTransferSrcStride(); + + u32 dstBasePtr = gstate.getTransferDstAddress(); + u32 dstStride = gstate.getTransferDstStride(); + + int srcX = gstate.getTransferSrcX(); + int srcY = gstate.getTransferSrcY(); + + int dstX = gstate.getTransferDstX(); + int dstY = gstate.getTransferDstY(); + + int width = gstate.getTransferWidth(); + int height = gstate.getTransferHeight(); + + int bpp = gstate.getTransferBpp(); + + DEBUG_LOG(G3D, "Block transfer: %08x/%x -> %08x/%x, %ix%ix%i (%i,%i)->(%i,%i)", srcBasePtr, srcStride, dstBasePtr, dstStride, width, height, bpp, srcX, srcY, dstX, dstY); + + if (!Memory::IsValidAddress(srcBasePtr)) { + ERROR_LOG_REPORT(G3D, "BlockTransfer: Bad source transfer address %08x!", srcBasePtr); + return; + } + + if (!Memory::IsValidAddress(dstBasePtr)) { + ERROR_LOG_REPORT(G3D, "BlockTransfer: Bad destination transfer address %08x!", dstBasePtr); + return; + } + + // Check that the last address of both source and dest are valid addresses + + u32 srcLastAddr = srcBasePtr + ((srcY + height - 1) * srcStride + (srcX + width - 1)) * bpp; + u32 dstLastAddr = dstBasePtr + ((dstY + height - 1) * dstStride + (dstX + width - 1)) * bpp; + + if (!Memory::IsValidAddress(srcLastAddr)) { + ERROR_LOG_REPORT(G3D, "Bottom-right corner of source of block transfer is at an invalid address: %08x", srcLastAddr); + return; + } + if (!Memory::IsValidAddress(dstLastAddr)) { + ERROR_LOG_REPORT(G3D, "Bottom-right corner of destination of block transfer is at an invalid address: %08x", srcLastAddr); + return; + } + + // Tell the framebuffer manager to take action if possible. If it does the entire thing, let's just return. + if (!framebufferManager_.NotifyBlockTransferBefore(dstBasePtr, dstStride, dstX, dstY, srcBasePtr, srcStride, srcX, srcY, width, height, bpp, skipDrawReason)) { + // Do the copy! (Hm, if we detect a drawn video frame (see below) then we could maybe skip this?) + // Can use GetPointerUnchecked because we checked the addresses above. We could also avoid them + // entirely by walking a couple of pointers... + if (srcStride == dstStride && (u32)width == srcStride) { + // Common case in God of War, let's do it all in one chunk. + u32 srcLineStartAddr = srcBasePtr + (srcY * srcStride + srcX) * bpp; + u32 dstLineStartAddr = dstBasePtr + (dstY * dstStride + dstX) * bpp; + const u8 *src = Memory::GetPointerUnchecked(srcLineStartAddr); + u8 *dst = Memory::GetPointerUnchecked(dstLineStartAddr); + memcpy(dst, src, width * height * bpp); + } else { + for (int y = 0; y < height; y++) { + u32 srcLineStartAddr = srcBasePtr + ((y + srcY) * srcStride + srcX) * bpp; + u32 dstLineStartAddr = dstBasePtr + ((y + dstY) * dstStride + dstX) * bpp; + + const u8 *src = Memory::GetPointerUnchecked(srcLineStartAddr); + u8 *dst = Memory::GetPointerUnchecked(dstLineStartAddr); + memcpy(dst, src, width * bpp); + } + } + + textureCache_.Invalidate(dstBasePtr + (dstY * dstStride + dstX) * bpp, height * dstStride * bpp, GPU_INVALIDATE_HINT); + framebufferManager_.NotifyBlockTransferAfter(dstBasePtr, dstStride, dstX, dstY, srcBasePtr, srcStride, srcX, srcY, width, height, bpp, skipDrawReason); + } + +#ifndef MOBILE_DEVICE + CBreakPoints::ExecMemCheck(srcBasePtr + (srcY * srcStride + srcX) * bpp, false, height * srcStride * bpp, currentMIPS->pc); + CBreakPoints::ExecMemCheck(dstBasePtr + (srcY * dstStride + srcX) * bpp, true, height * dstStride * bpp, currentMIPS->pc); +#endif + + // TODO: Correct timing appears to be 1.9, but erring a bit low since some of our other timing is inaccurate. + cyclesExecuted += ((height * width * bpp) * 16) / 10; +} + +void GPU_Vulkan::InvalidateCache(u32 addr, int size, GPUInvalidationType type) { + GPUEvent ev(GPU_EVENT_INVALIDATE_CACHE); + ev.invalidate_cache.addr = addr; + ev.invalidate_cache.size = size; + ev.invalidate_cache.type = type; + ScheduleEvent(ev); +} + +void GPU_Vulkan::InvalidateCacheInternal(u32 addr, int size, GPUInvalidationType type) { + if (size > 0) + textureCache_.Invalidate(addr, size, type); + else + textureCache_.InvalidateAll(type); + + if (type != GPU_INVALIDATE_ALL && framebufferManager_.MayIntersectFramebuffer(addr)) { + // If we're doing block transfers, we shouldn't need this, and it'll only confuse us. + // Vempire invalidates (with writeback) after drawing, but before blitting. + if (!g_Config.bBlockTransferGPU || type == GPU_INVALIDATE_SAFE) { + framebufferManager_.UpdateFromMemory(addr, size, type == GPU_INVALIDATE_SAFE); + } + } +} + +void GPU_Vulkan::PerformMemoryCopyInternal(u32 dest, u32 src, int size) { + if (!framebufferManager_.NotifyFramebufferCopy(src, dest, size, false, gstate_c.skipDrawReason)) { + // We use a little hack for Download/Upload using a VRAM mirror. + // Since they're identical we don't need to copy. + if (!Memory::IsVRAMAddress(dest) || (dest ^ 0x00400000) != src) { + Memory::Memcpy(dest, src, size); + } + } + InvalidateCache(dest, size, GPU_INVALIDATE_HINT); +} + +void GPU_Vulkan::PerformMemorySetInternal(u32 dest, u8 v, int size) { + if (!framebufferManager_.NotifyFramebufferCopy(dest, dest, size, true, gstate_c.skipDrawReason)) { + InvalidateCache(dest, size, GPU_INVALIDATE_HINT); + } +} + +void GPU_Vulkan::PerformStencilUploadInternal(u32 dest, int size) { + framebufferManager_.NotifyStencilUpload(dest, size); +} + +bool GPU_Vulkan::PerformMemoryCopy(u32 dest, u32 src, int size) { + // Track stray copies of a framebuffer in RAM. MotoGP does this. + if (framebufferManager_.MayIntersectFramebuffer(src) || framebufferManager_.MayIntersectFramebuffer(dest)) { + if (IsOnSeparateCPUThread()) { + GPUEvent ev(GPU_EVENT_FB_MEMCPY); + ev.fb_memcpy.dst = dest; + ev.fb_memcpy.src = src; + ev.fb_memcpy.size = size; + ScheduleEvent(ev); + + // This is a memcpy, so we need to wait for it to complete. + SyncThread(); + } else { + PerformMemoryCopyInternal(dest, src, size); + } + return true; + } + + InvalidateCache(dest, size, GPU_INVALIDATE_HINT); + return false; +} + +bool GPU_Vulkan::PerformMemorySet(u32 dest, u8 v, int size) { + // This may indicate a memset, usually to 0, of a framebuffer. + if (framebufferManager_.MayIntersectFramebuffer(dest)) { + Memory::Memset(dest, v, size); + + if (IsOnSeparateCPUThread()) { + GPUEvent ev(GPU_EVENT_FB_MEMSET); + ev.fb_memset.dst = dest; + ev.fb_memset.v = v; + ev.fb_memset.size = size; + ScheduleEvent(ev); + + // We don't need to wait for the framebuffer to be updated. + } else { + PerformMemorySetInternal(dest, v, size); + } + return true; + } + + // Or perhaps a texture, let's invalidate. + InvalidateCache(dest, size, GPU_INVALIDATE_HINT); + return false; +} + +bool GPU_Vulkan::PerformMemoryDownload(u32 dest, int size) { + // Cheat a bit to force a download of the framebuffer. + // VRAM + 0x00400000 is simply a VRAM mirror. + if (Memory::IsVRAMAddress(dest)) { + return PerformMemoryCopy(dest ^ 0x00400000, dest, size); + } + return false; +} + +bool GPU_Vulkan::PerformMemoryUpload(u32 dest, int size) { + // Cheat a bit to force an upload of the framebuffer. + // VRAM + 0x00400000 is simply a VRAM mirror. + if (Memory::IsVRAMAddress(dest)) { + return PerformMemoryCopy(dest, dest ^ 0x00400000, size); + } + return false; +} + +bool GPU_Vulkan::PerformStencilUpload(u32 dest, int size) { + if (framebufferManager_.MayIntersectFramebuffer(dest)) { + if (IsOnSeparateCPUThread()) { + GPUEvent ev(GPU_EVENT_FB_STENCIL_UPLOAD); + ev.fb_stencil_upload.dst = dest; + ev.fb_stencil_upload.size = size; + ScheduleEvent(ev); + } else { + PerformStencilUploadInternal(dest, size); + } + return true; + } + return false; +} + +void GPU_Vulkan::ClearCacheNextFrame() { + textureCache_.ClearNextFrame(); +} + +void GPU_Vulkan::Resized() { + resized_ = true; + framebufferManager_.Resized(); +} + +void GPU_Vulkan::ClearShaderCache() { + shaderManager_->ClearCache(true); +} + +std::vector GPU_Vulkan::GetFramebufferList() { + return framebufferManager_.GetFramebufferList(); +} + +void GPU_Vulkan::DoState(PointerWrap &p) { + GPUCommon::DoState(p); + + // TODO: Some of these things may not be necessary. + // None of these are necessary when saving. + // In Freeze-Frame mode, we don't want to do any of this. + if (p.mode == p.MODE_READ && !PSP_CoreParameter().frozen) { + textureCache_.Clear(true); + depalShaderCache_.Clear(); + + gstate_c.textureChanged = TEXCHANGE_UPDATED; + framebufferManager_.DestroyAllFBOs(); + shaderManager_->ClearCache(true); + } +} + +bool GPU_Vulkan::GetCurrentSimpleVertices(int count, std::vector &vertices, std::vector &indices) { + return drawEngine_.GetCurrentSimpleVertices(count, vertices, indices); +} + +bool GPU_Vulkan::DescribeCodePtr(const u8 *ptr, std::string &name) { + if (drawEngine_.IsCodePtrVertexDecoder(ptr)) { + name = "VertexDecoderJit"; + return true; + } + return false; +} + +std::vector GPU_Vulkan::DebugGetShaderIDs(DebugShaderType type) { + if (type == SHADER_TYPE_VERTEXLOADER) { + return drawEngine_.DebugGetVertexLoaderIDs(); + } else { + return shaderManager_->DebugGetShaderIDs(type); + } +} + +std::string GPU_Vulkan::DebugGetShaderString(std::string id, DebugShaderType type, DebugShaderStringType stringType) { + if (type == SHADER_TYPE_VERTEXLOADER) { + return drawEngine_.DebugGetVertexLoaderString(id, stringType); + } else { + return shaderManager_->DebugGetShaderString(id, type, stringType); + } } void GPU_Vulkan::NotifyVideoUpload(u32 addr, int size, int width, int format) { diff --git a/GPU/Vulkan/GPU_Vulkan.h b/GPU/Vulkan/GPU_Vulkan.h index 6f63b3c807..f5813a1435 100644 --- a/GPU/Vulkan/GPU_Vulkan.h +++ b/GPU/Vulkan/GPU_Vulkan.h @@ -25,13 +25,14 @@ #include "GPU/Vulkan/DrawEngineVulkan.h" #include "GPU/Vulkan/PipelineManagerVulkan.h" #include "GPU/Vulkan/TextureCacheVulkan.h" +#include "GPU/Vulkan/DepalettizeShaderVulkan.h" class ShaderManager; class LinkedShader; class GPU_Vulkan : public GPUCommon { public: - GPU_Vulkan(VulkanContext *vulkan); + GPU_Vulkan(GraphicsContext *ctx); ~GPU_Vulkan(); // This gets called on startup and when we get back from settings. @@ -81,7 +82,6 @@ public: GPU_Vulkan::CmdFunc func; }; - /* void Execute_Vaddr(u32 op, u32 diff); void Execute_Iaddr(u32 op, u32 diff); void Execute_Prim(u32 op, u32 diff); @@ -138,11 +138,13 @@ public: void Execute_BoneMtxNum(u32 op, u32 diff); void Execute_BoneMtxData(u32 op, u32 diff); void Execute_BlockTransferStart(u32 op, u32 diff); - */ // Using string because it's generic - makes no assumptions on the size of the shader IDs of this backend. std::vector DebugGetShaderIDs(DebugShaderType shader) override; std::string DebugGetShaderString(std::string id, DebugShaderType shader, DebugShaderStringType stringType) override; + std::vector GetFramebufferList(); + bool GetCurrentSimpleVertices(int count, std::vector &vertices, std::vector &indices); + bool DescribeCodePtr(const u8 *ptr, std::string &name); protected: void FastRunLoop(DisplayList &list) override; @@ -151,21 +153,41 @@ protected: void FinishDeferred() override; private: + void Flush() { + drawEngine_.Flush(nullptr); + } void DoBlockTransfer(u32 skipDrawReason); - + void CheckFlushOp(int cmd, u32 diff); + void BuildReportingInfo(); + void InitClearInternal(); + void BeginFrameInternal(); + void CopyDisplayToOutputInternal(); + void PerformMemoryCopyInternal(u32 dest, u32 src, int size); + void PerformMemorySetInternal(u32 dest, u8 v, int size); + void PerformStencilUploadInternal(u32 dest, int size); + void InvalidateCacheInternal(u32 addr, int size, GPUInvalidationType type); + void ReinitializeInternal(); + inline void UpdateVsyncInterval(bool force); void UpdateCmdInfo(); static CommandInfo cmdInfo_[256]; + GraphicsContext *gfxCtx_; + VulkanContext *vulkan_; FramebufferManagerVulkan framebufferManager_; TextureCacheVulkan textureCache_; - // DepalShaderCache depalShaderCache_; - DrawEngineVulkan transformDraw_; - // FragmentTestCache fragmentTestCache_; + DepalShaderCacheVulkan depalShaderCache_; + DrawEngineVulkan drawEngine_; + + // Manages shaders and UBO data + ShaderManagerVulkan *shaderManager_; + + // Manages state and pipeline objects PipelineManagerVulkan *pipelineManager_; bool resized_; int lastVsync_; + VkCommandBuffer curCmd_; std::string reportingPrimaryInfo_; std::string reportingFullInfo_; diff --git a/GPU/Vulkan/PipelineManagerVulkan.h b/GPU/Vulkan/PipelineManagerVulkan.h index b31a097539..0f0ed070c1 100644 --- a/GPU/Vulkan/PipelineManagerVulkan.h +++ b/GPU/Vulkan/PipelineManagerVulkan.h @@ -112,6 +112,8 @@ public: PipelineManagerVulkan(VulkanContext *ctx); ~PipelineManagerVulkan(); + int GetNumPipelines() const { return 0; } + private: std::map pipelines_; VkPipelineCache pipelineCache_; diff --git a/GPU/Vulkan/ShaderManagerVulkan.cpp b/GPU/Vulkan/ShaderManagerVulkan.cpp index 1efb3e925a..a03a5429be 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.cpp +++ b/GPU/Vulkan/ShaderManagerVulkan.cpp @@ -41,8 +41,8 @@ #include "GPU/Vulkan/VertexShaderGeneratorVulkan.h" #include "UI/OnScreenDisplay.h" -VulkanFragmentShader::VulkanFragmentShader(VkDevice device, ShaderID id, const char *code, bool useHWTransform) - : device_(device), id_(id), failed_(false), useHWTransform_(useHWTransform), module_(nullptr) { +VulkanFragmentShader::VulkanFragmentShader(VulkanContext *vulkan, ShaderID id, const char *code, bool useHWTransform) + : vulkan_(vulkan), id_(id), failed_(false), useHWTransform_(useHWTransform), module_(nullptr) { source_ = code; #ifdef SHADERLOG OutputDebugString(ConvertUTF8ToWString(code).c_str()); @@ -64,7 +64,7 @@ VulkanFragmentShader::VulkanFragmentShader(VkDevice device, ShaderID id, const c OutputDebugStringUTF8(errorMessage.c_str()); Reporting::ReportMessage("Vulkan error in shader compilation: info: %s / code: %s", errorMessage.c_str(), code); } else { - success = CreateShaderModule(device_, spirv, &module_); + success = vulkan_->CreateShaderModule(spirv, &module_); } if (!success) { @@ -77,7 +77,7 @@ VulkanFragmentShader::VulkanFragmentShader(VkDevice device, ShaderID id, const c VulkanFragmentShader::~VulkanFragmentShader() { if (module_) { - vkDestroyShaderModule(device_, module_, nullptr); + vulkan_->QueueDelete(module_); } } @@ -92,8 +92,8 @@ std::string VulkanFragmentShader::GetShaderString(DebugShaderStringType type) co } } -VulkanVertexShader::VulkanVertexShader(VkDevice device, ShaderID id, const char *code, int vertType, bool useHWTransform) - : device_(device), id_(id), failed_(false), useHWTransform_(useHWTransform), module_(nullptr) { +VulkanVertexShader::VulkanVertexShader(VulkanContext *vulkan, ShaderID id, const char *code, int vertType, bool useHWTransform) + : vulkan_(vulkan), id_(id), failed_(false), useHWTransform_(useHWTransform), module_(nullptr) { source_ = code; #ifdef SHADERLOG OutputDebugString(ConvertUTF8ToWString(code).c_str()); @@ -113,7 +113,7 @@ VulkanVertexShader::VulkanVertexShader(VkDevice device, ShaderID id, const char OutputDebugStringUTF8(errorMessage.c_str()); Reporting::ReportMessage("Vulkan error in shader compilation: info: %s / code: %s", errorMessage.c_str(), code); } else { - success = CreateShaderModule(device_, spirv, &module_); + success = vulkan_->CreateShaderModule(spirv, &module_); } if (!success) { @@ -127,7 +127,7 @@ VulkanVertexShader::VulkanVertexShader(VkDevice device, ShaderID id, const char VulkanVertexShader::~VulkanVertexShader() { if (module_) { - vkDestroyShaderModule(device_, module_, nullptr); + vulkan_->QueueDelete(module_); } } @@ -423,7 +423,8 @@ void ShaderManagerVulkan::VSUpdateUniforms(int dirtyUniforms) { } } -ShaderManagerVulkan::ShaderManagerVulkan(VkDevice device) : device_(device), lastVShader_(nullptr), lastFShader_(nullptr), globalDirty_(0xFFFFFFFF) { +ShaderManagerVulkan::ShaderManagerVulkan(VulkanContext *vulkan) + : vulkan_(vulkan), lastVShader_(nullptr), lastFShader_(nullptr), globalDirty_(0xFFFFFFFF) { codeBuffer_ = new char[16384]; } @@ -492,24 +493,7 @@ void ShaderManagerVulkan::GetShaders(int prim, u32 vertType, VulkanVertexShader if (vsIter == vsCache_.end()) { // Vertex shader not in cache. Let's compile it. GenerateVulkanGLSLVertexShader(VSID, codeBuffer_); - vs = new VulkanVertexShader(device_, VSID, codeBuffer_, vertType, useHWTransform); - - if (vs->Failed()) { - ERROR_LOG(HLE, "Shader compilation failed, falling back to software transform"); - osm.Show("hardware transform error - falling back to software", 2.5f, 0xFF3030FF, -1, true); - delete vs; - - ComputeVertexShaderID(&VSID, vertType, false); - - // TODO: Look for existing shader with the appropriate ID, use that instead of generating a new one - however, need to make sure - // that that shader ID is not used when computing the linked shader ID below, because then IDs won't match - // next time and we'll do this over and over... - - // Can still work with software transform. - GenerateVulkanGLSLVertexShader(VSID, codeBuffer_); - vs = new VulkanVertexShader(device_, VSID, codeBuffer_, vertType, false); - } - + vs = new VulkanVertexShader(vulkan_, VSID, codeBuffer_, vertType, useHWTransform); vsCache_[VSID] = vs; } else { vs = vsIter->second; @@ -521,7 +505,7 @@ void ShaderManagerVulkan::GetShaders(int prim, u32 vertType, VulkanVertexShader if (fsIter == fsCache_.end()) { // Fragment shader not in cache. Let's compile it. GenerateVulkanGLSLFragmentShader(FSID, codeBuffer_); - fs = new VulkanFragmentShader(device_, FSID, codeBuffer_, useHWTransform); + fs = new VulkanFragmentShader(vulkan_, FSID, codeBuffer_, useHWTransform); fsCache_[FSID] = fs; } else { fs = fsIter->second; diff --git a/GPU/Vulkan/ShaderManagerVulkan.h b/GPU/Vulkan/ShaderManagerVulkan.h index ef7bdda917..75c8daae4b 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.h +++ b/GPU/Vulkan/ShaderManagerVulkan.h @@ -178,7 +178,7 @@ R"( class VulkanFragmentShader { public: - VulkanFragmentShader(VkDevice device, ShaderID id, const char *code, bool useHWTransform); + VulkanFragmentShader(VulkanContext *vulkan, ShaderID id, const char *code, bool useHWTransform); ~VulkanFragmentShader(); const std::string &source() const { return source_; } @@ -191,7 +191,7 @@ public: protected: VkShaderModule module_; - VkDevice device_; + VulkanContext *vulkan_; std::string source_; bool failed_; bool useHWTransform_; @@ -200,7 +200,7 @@ protected: class VulkanVertexShader { public: - VulkanVertexShader(VkDevice device, ShaderID id, const char *code, int vertType, bool useHWTransform); + VulkanVertexShader(VulkanContext *vulkan, ShaderID id, const char *code, int vertType, bool useHWTransform); ~VulkanVertexShader(); const std::string &source() const { return source_; } @@ -213,7 +213,7 @@ public: protected: VkShaderModule module_; - VkDevice device_; + VulkanContext *vulkan_; std::string source_; bool failed_; bool useHWTransform_; @@ -222,7 +222,7 @@ protected: class ShaderManagerVulkan { public: - ShaderManagerVulkan(VkDevice device); + ShaderManagerVulkan(VulkanContext *vulkan); ~ShaderManagerVulkan(); void ClearCache(bool deleteThem); // TODO: deleteThem currently not respected @@ -234,8 +234,8 @@ public: } void DirtyLastShader(); - int NumVertexShaders() const { return (int)vsCache_.size(); } - int NumFragmentShaders() const { return (int)fsCache_.size(); } + int GetNumVertexShaders() const { return (int)vsCache_.size(); } + int GetNumFragmentShaders() const { return (int)fsCache_.size(); } std::vector DebugGetShaderIDs(DebugShaderType type); std::string DebugGetShaderString(std::string id, DebugShaderType type, DebugShaderStringType stringType); @@ -246,7 +246,7 @@ private: void Clear(); - VkDevice device_; + VulkanContext *vulkan_; u32 globalDirty_; char *codeBuffer_; diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index f70fd39522..606213b80e 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -779,7 +779,7 @@ void TextureCacheVulkan::SetTextureFramebuffer(TexCacheEntry *entry, VirtualFram bool useBufferedRendering = g_Config.iRenderingMode != FB_NON_BUFFERED_MODE; if (useBufferedRendering) { const GEPaletteFormat clutFormat = gstate.getClutPaletteFormat(); - DepalShader *depal = nullptr; + DepalShaderVulkan *depal = nullptr; if ((entry->status & TexCacheEntry::STATUS_DEPALETTIZE) && !g_Config.bDisableSlowFramebufEffects) { // depal = depalShaderCache_->GetDepalettizeShader(clutFormat, framebuffer->drawnFormat); } @@ -862,7 +862,7 @@ void TextureCacheVulkan::ApplyTexture(VkImageView &imageView, VkSampler &sampler } void TextureCacheVulkan::ApplyTextureFramebuffer(VkCommandBuffer cmd, TexCacheEntry *entry, VirtualFramebuffer *framebuffer, VkImageView &imageView, VkSampler &sampler) { - DepalShader *depal = nullptr; + DepalShaderVulkan *depal = nullptr; const GEPaletteFormat clutFormat = gstate.getClutPaletteFormat(); if ((entry->status & TexCacheEntry::STATUS_DEPALETTIZE) && !g_Config.bDisableSlowFramebufEffects) { // depal = depalShaderCache_->GetDepalettizeShader(clutFormat, framebuffer->drawnFormat); diff --git a/Windows/GPU/WindowsVulkanContext.cpp b/Windows/GPU/WindowsVulkanContext.cpp index eb0af1f2c3..f9e3a7fc44 100644 --- a/Windows/GPU/WindowsVulkanContext.cpp +++ b/Windows/GPU/WindowsVulkanContext.cpp @@ -171,6 +171,7 @@ bool WindowsVulkanContext::Init(HINSTANCE hInst, HWND hWnd, std::string *error_m } void WindowsVulkanContext::Shutdown() { + g_Vulkan->WaitUntilQueueIdle(); g_Vulkan->DestroyObjects(); g_Vulkan->DestroyDebugMsgCallback(); g_Vulkan->DestroyDevice(); @@ -199,3 +200,7 @@ void WindowsVulkanContext::Resize() { void WindowsVulkanContext::SwapInterval(int interval) { } + +void *WindowsVulkanContext::GetAPIContext() { + return g_Vulkan; +} diff --git a/Windows/GPU/WindowsVulkanContext.h b/Windows/GPU/WindowsVulkanContext.h index 5fc24a8669..0aad7d92c3 100644 --- a/Windows/GPU/WindowsVulkanContext.h +++ b/Windows/GPU/WindowsVulkanContext.h @@ -29,6 +29,8 @@ public: void SwapBuffers() override; void Resize() override; + void *GetAPIContext(); + Thin3DContext *CreateThin3DContext() override; }; diff --git a/ext/native/thin3d/VulkanContext.cpp b/ext/native/thin3d/VulkanContext.cpp index f94aa06273..9291b7d0b9 100644 --- a/ext/native/thin3d/VulkanContext.cpp +++ b/ext/native/thin3d/VulkanContext.cpp @@ -1403,14 +1403,22 @@ VkPipelineCache VulkanContext::CreatePipelineCache() { return cache; } -void TransitionImageLayout( - VkCommandBuffer cmd, - VkImage image, - VkImageAspectFlags aspectMask, - VkImageLayout old_image_layout, - VkImageLayout new_image_layout) { - /* DEPENDS on info.cmd and info.queue initialized */ +bool VulkanContext::CreateShaderModule(const std::vector &spirv, VkShaderModule *shaderModule) { + VkShaderModuleCreateInfo sm; + sm.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; + sm.pNext = nullptr; + sm.pCode = spirv.data(); + sm.codeSize = spirv.size() * sizeof(uint32_t); + sm.flags = 0; + VkResult result = vkCreateShaderModule(device_, &sm, NULL, shaderModule); + if (result != VK_SUCCESS) { + return false; + } else { + return true; + } +} +void TransitionImageLayout(VkCommandBuffer cmd, VkImage image, VkImageAspectFlags aspectMask, VkImageLayout old_image_layout, VkImageLayout new_image_layout) { VkImageMemoryBarrier image_memory_barrier = {}; image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; image_memory_barrier.pNext = NULL; diff --git a/ext/native/thin3d/VulkanContext.h b/ext/native/thin3d/VulkanContext.h index cd6fefdd32..70541de5b8 100644 --- a/ext/native/thin3d/VulkanContext.h +++ b/ext/native/thin3d/VulkanContext.h @@ -68,6 +68,7 @@ struct layer_properties { // This is a bit repetitive... class VulkanDeleteList { public: + void QueueDelete(VkShaderModule module) { modules_.push_back(module); } void QueueDelete(VkBuffer buffer) { buffers_.push_back(buffer); } void QueueDelete(VkBufferView bufferView) { bufferViews_.push_back(bufferView); } void QueueDelete(VkImage image) { images_.push_back(image); } @@ -75,6 +76,7 @@ public: void QueueDelete(VkDeviceMemory deviceMemory) { memory_.push_back(deviceMemory); } void Ingest(VulkanDeleteList &del) { + modules_ = std::move(del.modules_); buffers_ = std::move(del.buffers_); bufferViews_ = std::move(del.bufferViews_); images_ = std::move(del.images_); @@ -83,6 +85,10 @@ public: } void PerformDeletes(VkDevice device) { + for (auto &module : modules_) { + vkDestroyShaderModule(device, module, nullptr); + } + modules_.clear(); for (auto &buf : buffers_) { vkDestroyBuffer(device, buf, nullptr); } @@ -106,6 +112,7 @@ public: } private: + std::vector modules_; std::vector buffers_; std::vector bufferViews_; std::vector images_; @@ -157,6 +164,8 @@ public: // Utility functions for shorter code VkFence CreateFence(bool presignalled); + bool CreateShaderModule(const std::vector &spirv, VkShaderModule *shaderModule); + void WaitAndResetFence(VkFence fence); int GetWidth() { return width; } diff --git a/ext/native/thin3d/thin3d_vulkan.cpp b/ext/native/thin3d/thin3d_vulkan.cpp index d2aa8faab8..fbdfc80e57 100644 --- a/ext/native/thin3d/thin3d_vulkan.cpp +++ b/ext/native/thin3d/thin3d_vulkan.cpp @@ -187,24 +187,23 @@ private: // invoke Compile again to recreate the shader then link them together. class Thin3DVKShader : public Thin3DShader { public: - Thin3DVKShader(VulkanContext *vulkan, bool isFragmentShader) : vulkan_(vulkan), module_(nullptr), ok_(false) { + Thin3DVKShader(bool isFragmentShader) : module_(nullptr), ok_(false) { stage_ = isFragmentShader ? VK_SHADER_STAGE_FRAGMENT_BIT : VK_SHADER_STAGE_VERTEX_BIT; } - bool Compile(VkDevice device, const char *source); + bool Compile(VulkanContext *vulkan, const char *source); const std::string &GetSource() const { return source_; } ~Thin3DVKShader() { } VkShaderModule Get() const { return module_; } private: - VulkanContext *vulkan_; VkShaderModule module_; VkShaderStageFlagBits stage_; bool ok_; std::string source_; // So we can recompile in case of context loss. }; -bool Thin3DVKShader::Compile(VkDevice device, const char *source) { +bool Thin3DVKShader::Compile(VulkanContext *vulkan, const char *source) { this->source_ = source; std::vector spirv; if (!GLSLtoSPV(stage_, source, spirv)) { @@ -220,7 +219,7 @@ bool Thin3DVKShader::Compile(VkDevice device, const char *source) { } #endif - if (CreateShaderModule(device, spirv, &module_)) { + if (vulkan->CreateShaderModule(spirv, &module_)) { ok_ = true; } else { ok_ = false; @@ -1023,8 +1022,8 @@ void Thin3DVKContext::SetTextures(int start, int count, Thin3DTexture **textures } Thin3DShader *Thin3DVKContext::CreateVertexShader(const char *glsl_source, const char *hlsl_source, const char *vulkan_source) { - Thin3DVKShader *shader = new Thin3DVKShader(vulkan_, false); - if (shader->Compile(device_, vulkan_source)) { + Thin3DVKShader *shader = new Thin3DVKShader(false); + if (shader->Compile(vulkan_, vulkan_source)) { return shader; } else { shader->Release(); @@ -1033,8 +1032,8 @@ Thin3DShader *Thin3DVKContext::CreateVertexShader(const char *glsl_source, const } Thin3DShader *Thin3DVKContext::CreateFragmentShader(const char *glsl_source, const char *hlsl_source, const char *vulkan_source) { - Thin3DVKShader *shader = new Thin3DVKShader(vulkan_, true); - if (shader->Compile(device_, vulkan_source)) { + Thin3DVKShader *shader = new Thin3DVKShader(true); + if (shader->Compile(vulkan_, vulkan_source)) { return shader; } else { shader->Release(); diff --git a/ext/native/thin3d/vulkan_utils.cpp b/ext/native/thin3d/vulkan_utils.cpp index 800f0ccf1c..ec46b011a9 100644 --- a/ext/native/thin3d/vulkan_utils.cpp +++ b/ext/native/thin3d/vulkan_utils.cpp @@ -140,18 +140,3 @@ void VulkanImage::ChangeLayout(VkCommandBuffer cmd, VkImageAspectFlags aspectMas VkPipelineStageFlags dest_stages = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; vkCmdPipelineBarrier(cmd, src_stages, dest_stages, false, 0, nullptr, 0, nullptr, 1, &image_memory_barrier); } - -bool CreateShaderModule(VkDevice device, const std::vector &spirv, VkShaderModule *shaderModule) { - VkShaderModuleCreateInfo sm; - sm.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; - sm.pNext = nullptr; - sm.pCode = spirv.data(); - sm.codeSize = spirv.size() * sizeof(uint32_t); - sm.flags = 0; - VkResult result = vkCreateShaderModule(device, &sm, NULL, shaderModule); - if (result != VK_SUCCESS) { - return false; - } else { - return true; - } -} diff --git a/ext/native/thin3d/vulkan_utils.h b/ext/native/thin3d/vulkan_utils.h index 278abdb4a2..a6fb88aaae 100644 --- a/ext/native/thin3d/vulkan_utils.h +++ b/ext/native/thin3d/vulkan_utils.h @@ -54,4 +54,3 @@ class Thin3DPipelineCache { }; -bool CreateShaderModule(VkDevice device, const std::vector &spirv, VkShaderModule *shaderModule); From 3701e2eca3a0698de01201b5a166ca1232976cfa Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Tue, 5 Jan 2016 22:55:47 +0100 Subject: [PATCH 018/116] Reaches the first clear --- GPU/GPU.cpp | 2 -- GPU/Vulkan/DrawEngineVulkan.cpp | 14 ------------- GPU/Vulkan/DrawEngineVulkan.h | 1 - GPU/Vulkan/FramebufferVulkan.cpp | 24 ++++++++++++++++++++++ GPU/Vulkan/FramebufferVulkan.h | 34 +++++++++++--------------------- GPU/Vulkan/GPU_Vulkan.cpp | 3 ++- 6 files changed, 38 insertions(+), 40 deletions(-) diff --git a/GPU/GPU.cpp b/GPU/GPU.cpp index dc1b9b9e3c..0c509df0c7 100644 --- a/GPU/GPU.cpp +++ b/GPU/GPU.cpp @@ -60,9 +60,7 @@ bool GPU_Init(GraphicsContext *ctx) { #endif break; case GPU_VULKAN: - { SetGPU(new GPU_Vulkan(ctx)); - } break; } diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index f090bd602c..72e2aba8a7 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -73,7 +73,6 @@ DrawEngineVulkan::DrawEngineVulkan(VulkanContext *vulkan) numDrawCalls(0), vertexCountInDrawCalls(0), decodeCounter_(0), - dcid_(0), fboTexNeedBind_(false), fboTexBound_(false), curFrame_(0) { @@ -231,18 +230,6 @@ void DrawEngineVulkan::SubmitPrim(void *verts, void *inds, GEPrimitiveType prim, dc.prim = prim; dc.vertexCount = vertexCount; - u32 dhash = dcid_; - dhash ^= (u32)(uintptr_t)verts; - dhash = __rotl(dhash, 13); - dhash ^= (u32)(uintptr_t)inds; - dhash = __rotl(dhash, 13); - dhash ^= (u32)vertType; - dhash = __rotl(dhash, 13); - dhash ^= (u32)vertexCount; - dhash = __rotl(dhash, 13); - dhash ^= (u32)prim; - dcid_ = dhash; - if (inds) { GetIndexBounds(inds, vertexCount, vertType, &dc.indexLowerBound, &dc.indexUpperBound); } else { @@ -553,7 +540,6 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { numDrawCalls = 0; vertexCountInDrawCalls = 0; decodeCounter_ = 0; - dcid_ = 0; prevPrim_ = GE_PRIM_INVALID; gstate_c.vertexFullAlpha = true; framebufferManager_->SetColorUpdated(gstate_c.skipDrawReason); diff --git a/GPU/Vulkan/DrawEngineVulkan.h b/GPU/Vulkan/DrawEngineVulkan.h index ebb81dadc9..05f3911cb8 100644 --- a/GPU/Vulkan/DrawEngineVulkan.h +++ b/GPU/Vulkan/DrawEngineVulkan.h @@ -207,7 +207,6 @@ private: int vertexCountInDrawCalls; int decodeCounter_; - u32 dcid_; bool fboTexNeedBind_; bool fboTexBound_; diff --git a/GPU/Vulkan/FramebufferVulkan.cpp b/GPU/Vulkan/FramebufferVulkan.cpp index 24f4c8cbd7..b26ab43b12 100644 --- a/GPU/Vulkan/FramebufferVulkan.cpp +++ b/GPU/Vulkan/FramebufferVulkan.cpp @@ -18,7 +18,10 @@ #pragma once #include "GPU/GPUInterface.h" +#include "GPU/GPUState.h" #include "GPU/Vulkan/FramebufferVulkan.h" +#include "GPU/Vulkan/DrawEngineVulkan.h" + VulkanFramebuffer *FramebufferManagerVulkan::GetTempFBO(int width, int height, VulkanFBOColorDepth colorDepth) { @@ -41,10 +44,31 @@ void FramebufferManagerVulkan::CopyDisplayToOutput() { } +void FramebufferManagerVulkan::DecimateFBOs() { + +} + void FramebufferManagerVulkan::EndFrame() { } +void FramebufferManagerVulkan::DrawPixels(VirtualFramebuffer *vfb, int dstX, int dstY, const u8 *srcPixels, GEBufferFormat srcPixelFormat, int srcStride, int width, int height) { + // So: Allocate a temporary texture from a (very small) pool, upload content directly into it, schedule a transition + // into the init command buffer, alloc and create an appropriate descriptor set, then bind and draw. no need for uniforms. +} + + +void FramebufferManagerVulkan::FlushBeforeCopy() { + // Flush anything not yet drawn before blitting, downloading, or uploading. + // This might be a stalled list, or unflushed before a block transfer, etc. + + // TODO: It's really bad that we are calling SetRenderFramebuffer here with + // all the irrelevant state checking it'll use to decide what to do. Should + // do something more focused here. + SetRenderFrameBuffer(gstate_c.framebufChanged, gstate_c.skipDrawReason); + drawEngine_->Flush(nullptr); +} + std::vector FramebufferManagerVulkan::GetFramebufferList() { return std::vector(); } diff --git a/GPU/Vulkan/FramebufferVulkan.h b/GPU/Vulkan/FramebufferVulkan.h index f8a8b6f521..a30a097e70 100644 --- a/GPU/Vulkan/FramebufferVulkan.h +++ b/GPU/Vulkan/FramebufferVulkan.h @@ -30,25 +30,26 @@ enum VulkanFBOColorDepth { }; class TextureCacheVulkan; +class DrawEngineVulkan; +class VulkanContext; class FramebufferManagerVulkan : public FramebufferManagerCommon { public: + FramebufferManagerVulkan(VulkanContext *vulkan) : vulkan_(vulkan) {} // Subsequent commands will be enqueued on this buffer. - void SetInstance(VkInstance inst) { inst_ = inst; } void SetCmdBuffer(VkCommandBuffer cmd) { cmd_ = cmd; } virtual void ClearBuffer(bool keepState = false) override { throw std::logic_error("The method or operation is not implemented."); } void SetTextureCache(TextureCacheVulkan *texCache) { texCache_ = texCache; } + void SetDrawEngine(DrawEngineVulkan *drawEngine) { drawEngine_ = drawEngine; } VulkanFramebuffer *GetTempFBO(int width, int height, VulkanFBOColorDepth colorDepth); - virtual void RebindFramebuffer() override { - throw std::logic_error("The method or operation is not implemented."); - } + void RebindFramebuffer() override { } // This makes little sense with Vulkan's model. - virtual bool NotifyStencilUpload(u32 addr, int size, bool skipZero = false) override { - throw std::logic_error("The method or operation is not implemented."); + bool NotifyStencilUpload(u32 addr, int size, bool skipZero = false) override { + return false; } virtual void ReadFramebufferToMemory(VirtualFramebuffer *vfb, bool sync, int x, int y, int w, int h) override { @@ -56,28 +57,20 @@ public: } virtual void MakePixelTexture(const u8 *srcPixels, GEBufferFormat srcPixelFormat, int srcStride, int width, int height) override { - throw std::logic_error("The method or operation is not implemented."); } - virtual void DrawPixels(VirtualFramebuffer *vfb, int dstX, int dstY, const u8 *srcPixels, GEBufferFormat srcPixelFormat, int srcStride, int width, int height) override { - throw std::logic_error("The method or operation is not implemented."); - } + void DrawPixels(VirtualFramebuffer *vfb, int dstX, int dstY, const u8 *srcPixels, GEBufferFormat srcPixelFormat, int srcStride, int width, int height) override; virtual void DrawFramebufferToOutput(const u8 *srcPixels, GEBufferFormat srcPixelFormat, int srcStride, bool applyPostShader) override { throw std::logic_error("The method or operation is not implemented."); } virtual void DisableState() override { - throw std::logic_error("The method or operation is not implemented."); } - virtual void FlushBeforeCopy() override { - throw std::logic_error("The method or operation is not implemented."); - } + virtual void FlushBeforeCopy() override; - virtual void DecimateFBOs() override { - throw std::logic_error("The method or operation is not implemented."); - } + void DecimateFBOs() override; virtual void BlitFramebuffer(VirtualFramebuffer *dst, int dstX, int dstY, VirtualFramebuffer *src, int srcX, int srcY, int w, int h, int bpp) override { throw std::logic_error("The method or operation is not implemented."); @@ -88,19 +81,15 @@ public: } virtual void ResizeFramebufFBO(VirtualFramebuffer *vfb, u16 w, u16 h, bool force = false) override { - throw std::logic_error("The method or operation is not implemented."); } virtual void NotifyRenderFramebufferCreated(VirtualFramebuffer *vfb) override { - throw std::logic_error("The method or operation is not implemented."); } virtual void NotifyRenderFramebufferSwitched(VirtualFramebuffer *prevVfb, VirtualFramebuffer *vfb, bool isClearingDepth) override { - throw std::logic_error("The method or operation is not implemented."); } virtual void NotifyRenderFramebufferUpdated(VirtualFramebuffer *vfb, bool vfbFormatChanged) override { - throw std::logic_error("The method or operation is not implemented."); } void DownloadFramebufferForClut(u32 fb_address, u32 loadBytes) override { @@ -123,8 +112,9 @@ public: std::vector GetFramebufferList(); private: - VkInstance inst_; + VulkanContext *vulkan_; VkCommandBuffer cmd_; TextureCacheVulkan *texCache_; + DrawEngineVulkan *drawEngine_; }; diff --git a/GPU/Vulkan/GPU_Vulkan.cpp b/GPU/Vulkan/GPU_Vulkan.cpp index 5980c49220..77ce919ac5 100644 --- a/GPU/Vulkan/GPU_Vulkan.cpp +++ b/GPU/Vulkan/GPU_Vulkan.cpp @@ -394,6 +394,7 @@ GPU_Vulkan::GPU_Vulkan(GraphicsContext *ctx) : vulkan_((VulkanContext *)ctx->GetAPIContext()), drawEngine_(vulkan_), textureCache_(vulkan_), + framebufferManager_(vulkan_), resized_(false), gfxCtx_(ctx) { UpdateVsyncInterval(true); @@ -405,6 +406,7 @@ GPU_Vulkan::GPU_Vulkan(GraphicsContext *ctx) drawEngine_.SetFramebufferManager(&framebufferManager_); framebufferManager_.Init(); framebufferManager_.SetTextureCache(&textureCache_); + framebufferManager_.SetDrawEngine(&drawEngine_); textureCache_.SetFramebufferManager(&framebufferManager_); textureCache_.SetDepalShaderCache(&depalShaderCache_); textureCache_.SetShaderManager(shaderManager_); @@ -619,7 +621,6 @@ void GPU_Vulkan::CopyDisplayToOutput() { void GPU_Vulkan::CopyDisplayToOutputInternal() { // Flush anything left over. - framebufferManager_.RebindFramebuffer(); drawEngine_.Flush(curCmd_); shaderManager_->DirtyLastShader(); From 49f1e702c93f06f0f83644bbf9226b5a46685826 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Tue, 5 Jan 2016 23:37:18 +0100 Subject: [PATCH 019/116] Okay, reached the shader generators --- GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp | 32 ++++++++++---------- GPU/Vulkan/GPU_Vulkan.cpp | 5 +++ GPU/Vulkan/GPU_Vulkan.h | 2 +- GPU/Vulkan/ShaderManagerVulkan.h | 30 +++++++----------- 4 files changed, 33 insertions(+), 36 deletions(-) diff --git a/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp b/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp index 7be678c0b4..cd670ca0ad 100644 --- a/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp +++ b/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp @@ -168,18 +168,18 @@ bool GenerateVulkanGLSLFragmentShader(const ShaderID &id, char *buffer) { std::string modulo = (gl_extensions.bugs & BUG_PVR_SHADER_PRECISION_BAD) ? "mymod" : "mod"; if (id.Bit(FS_BIT_CLAMP_S)) { - ucoord = "clamp(" + ucoord + ", u_texclamp.z, u_texclamp.x - u_texclamp.z)"; + ucoord = "clamp(" + ucoord + ", base.texclamp.z, base.texclamp.x - base.texclamp.z)"; } else { - ucoord = modulo + "(" + ucoord + ", u_texclamp.x)"; + ucoord = modulo + "(" + ucoord + ", base.texclamp.x)"; } if (id.Bit(FS_BIT_CLAMP_T)) { - vcoord = "clamp(" + vcoord + ", u_texclamp.w, u_texclamp.y - u_texclamp.w)"; + vcoord = "clamp(" + vcoord + ", base.texclamp.w, base.texclamp.y - base.texclamp.w)"; } else { - vcoord = modulo + "(" + vcoord + ", u_texclamp.y)"; + vcoord = modulo + "(" + vcoord + ", base.texclamp.y)"; } if (textureAtOffset) { - ucoord = "(" + ucoord + " + u_texclampoff.x)"; - vcoord = "(" + vcoord + " + u_texclampoff.y)"; + ucoord = "(" + ucoord + " + base.texclampoff.x)"; + vcoord = "(" + vcoord + " + base.texclampoff.y)"; } WRITE(p, " vec2 fixedcoord = vec2(%s, %s);\n", ucoord.c_str(), vcoord.c_str()); @@ -206,7 +206,7 @@ bool GenerateVulkanGLSLFragmentShader(const ShaderID &id, char *buffer) { break; case GE_TEXFUNC_BLEND: - WRITE(p, " vec4 v = vec4(mix(p.rgb, u_texenv.rgb, t.rgb), p.a * t.a)%s;\n", secondary); + WRITE(p, " vec4 v = vec4(mix(p.rgb, base.texenv.rgb, t.rgb), p.a * t.a)%s;\n", secondary); break; case GE_TEXFUNC_REPLACE: @@ -233,7 +233,7 @@ bool GenerateVulkanGLSLFragmentShader(const ShaderID &id, char *buffer) { break; case GE_TEXFUNC_BLEND: - WRITE(p, " vec4 v = vec4(mix(p.rgb, u_texenv.rgb, t.rgb), p.a)%s;\n", secondary); + WRITE(p, " vec4 v = vec4(mix(p.rgb, base.texenv.rgb, t.rgb), p.a)%s;\n", secondary); break; case GE_TEXFUNC_REPLACE: @@ -288,7 +288,7 @@ bool GenerateVulkanGLSLFragmentShader(const ShaderID &id, char *buffer) { } else { const char *alphaTestFuncs[] = { "#", "#", " != ", " == ", " >= ", " > ", " <= ", " < " }; if (alphaTestFuncs[alphaTestFunc][0] != '#') { - WRITE(p, " if ((roundAndScaleTo255i(v.a) & u_alphacolormask.a) %s int(u_alphacolorref.a)) discard;\n", alphaTestFuncs[alphaTestFunc]); + WRITE(p, " if ((roundAndScaleTo255i(v.a) & base.alphacolormask.a) %s int(base.alphacolorref.a)) discard;\n", alphaTestFuncs[alphaTestFunc]); } else { // This means NEVER. See above. WRITE(p, " discard;\n"); @@ -327,8 +327,8 @@ bool GenerateVulkanGLSLFragmentShader(const ShaderID &id, char *buffer) { if (colorTestFuncs[colorTestFunc][0] != '#') { // Apparently GLES3 does not support vector bitwise ops. WRITE(p, " ivec3 v_scaled = roundAndScaleTo255iv(v.rgb);\n"); - const char *maskedFragColor = "ivec3(v_scaled.r & u_alphacolormask.r, v_scaled.g & u_alphacolormask.g, v_scaled.b & u_alphacolormask.b)"; - const char *maskedColorRef = "ivec3(int(u_alphacolorref.r) & u_alphacolormask.r, int(u_alphacolorref.g) & u_alphacolormask.g, int(u_alphacolorref.b) & u_alphacolormask.b)"; + const char *maskedFragColor = "ivec3(v_scaled.r & base.alphacolormask.r, v_scaled.g & base.alphacolormask.g, v_scaled.b & base.alphacolormask.b)"; + const char *maskedColorRef = "ivec3(int(base.alphacolorref.r) & base.alphacolormask.r, int(base.alphacolorref.g) & base.alphacolormask.g, int(base.alphacolorref.b) & base.alphacolormask.b)"; WRITE(p, " if (%s %s %s) discard;\n", maskedFragColor, colorTestFuncs[colorTestFunc], maskedColorRef); } else { WRITE(p, " discard;\n"); @@ -345,7 +345,7 @@ bool GenerateVulkanGLSLFragmentShader(const ShaderID &id, char *buffer) { if (enableFog) { WRITE(p, " float fogCoef = clamp(v_fogdepth, 0.0, 1.0);\n"); - WRITE(p, " v = mix(vec4(u_fogcolor, v.a), v, fogCoef);\n"); + WRITE(p, " v = mix(vec4(base.fogcolor, v.a), v, fogCoef);\n"); // WRITE(p, " v.x = v_depth;\n"); } @@ -362,7 +362,7 @@ bool GenerateVulkanGLSLFragmentShader(const ShaderID &id, char *buffer) { case GE_SRCBLEND_DOUBLEINVSRCALPHA: srcFactor = "vec3(1.0 - v.a * 2.0)"; break; case GE_SRCBLEND_DOUBLEDSTALPHA: srcFactor = "ERROR"; break; case GE_SRCBLEND_DOUBLEINVDSTALPHA: srcFactor = "ERROR"; break; - case GE_SRCBLEND_FIXA: srcFactor = "u_blendFixA"; break; + case GE_SRCBLEND_FIXA: srcFactor = "base.blendFixA"; break; } WRITE(p, " v.rgb = v.rgb * %s;\n", srcFactor); @@ -385,7 +385,7 @@ bool GenerateVulkanGLSLFragmentShader(const ShaderID &id, char *buffer) { case GE_SRCBLEND_DOUBLEINVSRCALPHA: srcFactor = "vec3(1.0 - v.a * 2.0)"; break; case GE_SRCBLEND_DOUBLEDSTALPHA: srcFactor = "vec3(destColor.a * 2.0)"; break; case GE_SRCBLEND_DOUBLEINVDSTALPHA: srcFactor = "vec3(1.0 - destColor.a * 2.0)"; break; - case GE_SRCBLEND_FIXA: srcFactor = "u_blendFixA"; break; + case GE_SRCBLEND_FIXA: srcFactor = "base.blendFixA"; break; } switch (replaceBlendFuncB) { case GE_DSTBLEND_SRCCOLOR: dstFactor = "v.rgb"; break; @@ -398,7 +398,7 @@ bool GenerateVulkanGLSLFragmentShader(const ShaderID &id, char *buffer) { case GE_DSTBLEND_DOUBLEINVSRCALPHA: dstFactor = "vec3(1.0 - v.a * 2.0)"; break; case GE_DSTBLEND_DOUBLEDSTALPHA: dstFactor = "vec3(destColor.a * 2.0)"; break; case GE_DSTBLEND_DOUBLEINVDSTALPHA: dstFactor = "vec3(1.0 - destColor.a * 2.0)"; break; - case GE_DSTBLEND_FIXB: dstFactor = "u_blendFixB"; break; + case GE_DSTBLEND_FIXB: dstFactor = "base.blendFixB"; break; } switch (replaceBlendEq) { @@ -433,7 +433,7 @@ bool GenerateVulkanGLSLFragmentShader(const ShaderID &id, char *buffer) { if (stencilToAlpha != REPLACE_ALPHA_NO) { switch (replaceAlphaWithStencilType) { case STENCIL_VALUE_UNIFORM: - replacedAlpha = "u_stencilReplaceValue"; + replacedAlpha = "base.stencilReplaceValue"; break; case STENCIL_VALUE_ZERO: diff --git a/GPU/Vulkan/GPU_Vulkan.cpp b/GPU/Vulkan/GPU_Vulkan.cpp index 77ce919ac5..25bee1aba9 100644 --- a/GPU/Vulkan/GPU_Vulkan.cpp +++ b/GPU/Vulkan/GPU_Vulkan.cpp @@ -578,6 +578,11 @@ void GPU_Vulkan::BeginFrameInternal() { shaderManager_->DirtyUniform(DIRTY_ALL); framebufferManager_.BeginFrame(); + + if (g_Config.iRenderingMode == FB_NON_BUFFERED_MODE) { + // Draw everything directly to the backbuffer. + drawEngine_.SetCmdBuffer(vulkan_->GetSurfaceCommandBuffer()); + } } void GPU_Vulkan::SetDisplayFramebuffer(u32 framebuf, u32 stride, GEBufferFormat format) { diff --git a/GPU/Vulkan/GPU_Vulkan.h b/GPU/Vulkan/GPU_Vulkan.h index f5813a1435..e292a567b7 100644 --- a/GPU/Vulkan/GPU_Vulkan.h +++ b/GPU/Vulkan/GPU_Vulkan.h @@ -146,6 +146,7 @@ public: bool GetCurrentSimpleVertices(int count, std::vector &vertices, std::vector &indices); bool DescribeCodePtr(const u8 *ptr, std::string &name); + protected: void FastRunLoop(DisplayList &list) override; void ProcessEvent(GPUEvent ev) override; @@ -169,7 +170,6 @@ private: void ReinitializeInternal(); inline void UpdateVsyncInterval(bool force); void UpdateCmdInfo(); - static CommandInfo cmdInfo_[256]; GraphicsContext *gfxCtx_; diff --git a/GPU/Vulkan/ShaderManagerVulkan.h b/GPU/Vulkan/ShaderManagerVulkan.h index 75c8daae4b..4bdc3951e1 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.h +++ b/GPU/Vulkan/ShaderManagerVulkan.h @@ -89,27 +89,19 @@ R"(matrix4x4 proj; matrix4x4 view; matrix4x4 world; matrix4x4 tex; - vec4 uvScaleOffset; + vec4 uvScaleOffset; vec4 depthRange; vec2 fogCoef; - vec4 matAmbient; - // Blend function replacement - vec3 u_blendFixA; - vec3 u_blendFixB; - - // Texture clamp emulation - vec4 u_texclamp; - vec2 u_texclampoff; - - // Alpha/Color test emulation - vec4 u_alphacolorref; - ivec4 u_alphacolormask; - - // Stencil replacement - float u_stencilReplaceValue; - vec3 u_texenv; - - vec3 u_fogcolor; + vec4 matAmbient; + vec3 blendFixA; // Blend func replace + vec3 blendFixB; + vec4 texclamp; // Texture clamp emu + vec2 texclampoff; + vec4 alphacolorref; // Alpha/Color test + ivec4 alphacolormask; + float stencilReplaceValue; // Stencil replacement + vec3 texenv; + vec3 fogcolor; )"; struct UB_VS_Lights { From 906b259a8582018efaa1e2b20b58f6b9898133ba Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Wed, 6 Jan 2016 00:38:45 +0100 Subject: [PATCH 020/116] First PSP shaders actually compile --- GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp | 2 +- GPU/Vulkan/ShaderManagerVulkan.cpp | 48 ++++++----- GPU/Vulkan/ShaderManagerVulkan.h | 58 +++++-------- GPU/Vulkan/VertexShaderGeneratorVulkan.cpp | 88 ++++++++++---------- ext/native/thin3d/VulkanContext.cpp | 82 ++++++++++-------- ext/native/thin3d/VulkanContext.h | 21 +++-- 6 files changed, 155 insertions(+), 144 deletions(-) diff --git a/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp b/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp index cd670ca0ad..56c3ad5947 100644 --- a/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp +++ b/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp @@ -92,7 +92,7 @@ bool GenerateVulkanGLSLFragmentShader(const ShaderID &id, char *buffer) { const char *shading = doFlatShading ? "flat" : ""; - WRITE(p, "layout (binding = 2) uniform %s\n", ub_baseStr); + WRITE(p, "layout (std140, set = 0, binding = 3) uniform baseUBO {\n%s} base;\n", ub_baseStr); if (doTexture) { WRITE(p, "layout (binding = 0) uniform sampler2D tex;\n"); } diff --git a/GPU/Vulkan/ShaderManagerVulkan.cpp b/GPU/Vulkan/ShaderManagerVulkan.cpp index a03a5429be..88fc61fcfb 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.cpp +++ b/GPU/Vulkan/ShaderManagerVulkan.cpp @@ -44,9 +44,6 @@ VulkanFragmentShader::VulkanFragmentShader(VulkanContext *vulkan, ShaderID id, const char *code, bool useHWTransform) : vulkan_(vulkan), id_(id), failed_(false), useHWTransform_(useHWTransform), module_(nullptr) { source_ = code; -#ifdef SHADERLOG - OutputDebugString(ConvertUTF8ToWString(code).c_str()); -#endif std::string errorMessage; std::vector spirv; @@ -60,11 +57,16 @@ VulkanFragmentShader::VulkanFragmentShader(VulkanContext *vulkan, ShaderID id, c } ERROR_LOG(G3D, "Messages: %s", errorMessage.c_str()); ERROR_LOG(G3D, "Shader source:\n%s", code); - OutputDebugStringUTF8("Messages:\n"); - OutputDebugStringUTF8(errorMessage.c_str()); + OutputDebugStringA("Messages:\n"); + OutputDebugStringA(errorMessage.c_str()); + OutputDebugStringA(code); Reporting::ReportMessage("Vulkan error in shader compilation: info: %s / code: %s", errorMessage.c_str(), code); } else { success = vulkan_->CreateShaderModule(spirv, &module_); +#ifdef SHADERLOG + OutputDebugStringA(code); + OutputDebugStringA("OK"); +#endif } if (!success) { @@ -164,23 +166,23 @@ static void ConvertProjMatrixToVulkanThrough(Matrix4x4 &in) { void ShaderManagerVulkan::PSUpdateUniforms(int dirtyUniforms) { if (dirtyUniforms & DIRTY_TEXENV) { - Uint8x3ToFloat4(ub_fragment.texEnvColor, gstate.texenvcolor); + Uint8x3ToFloat4(ub_base.texEnvColor, gstate.texenvcolor); } if (dirtyUniforms & DIRTY_ALPHACOLORREF) { - Uint8x3ToFloat4_Alpha(ub_fragment.alphaColorRef, gstate.getColorTestRef(), (float)gstate.getAlphaTestRef()); + Uint8x3ToFloat4_Alpha(ub_base.alphaColorRef, gstate.getColorTestRef(), (float)gstate.getAlphaTestRef()); } if (dirtyUniforms & DIRTY_ALPHACOLORMASK) { - Uint8x3ToFloat4(ub_fragment.colorTestMask, gstate.colortestmask); + Uint8x3ToFloat4(ub_base.colorTestMask, gstate.colortestmask); } if (dirtyUniforms & DIRTY_FOGCOLOR) { - Uint8x3ToFloat4(ub_fragment.fogColor, gstate.fogcolor); + Uint8x3ToFloat4(ub_base.fogColor, gstate.fogcolor); } if (dirtyUniforms & DIRTY_STENCILREPLACEVALUE) { - Uint8x1ToFloat4(ub_fragment.stencilReplace, gstate.getStencilTestRef()); + Uint8x1ToFloat4(ub_base.stencilReplace, gstate.getStencilTestRef()); } if (dirtyUniforms & DIRTY_SHADERBLEND) { - Uint8x3ToFloat4(ub_fragment.blendFixA, gstate.getFixA()); - Uint8x3ToFloat4(ub_fragment.blendFixB, gstate.getFixB()); + Uint8x3ToFloat4(ub_base.blendFixA, gstate.getFixA()); + Uint8x3ToFloat4(ub_base.blendFixB, gstate.getFixB()); } if (dirtyUniforms & DIRTY_TEXCLAMP) { const float invW = 1.0f / (float)gstate_c.curTextureWidth; @@ -201,8 +203,8 @@ void ShaderManagerVulkan::PSUpdateUniforms(int dirtyUniforms) { gstate_c.curTextureXOffset * invW, gstate_c.curTextureYOffset * invH, }; - CopyFloat4(ub_fragment.texClamp, texclamp); - CopyFloat2(ub_fragment.texClampOffset, texclampoff); + CopyFloat4(ub_base.texClamp, texclamp); + CopyFloat2(ub_base.texClampOffset, texclampoff); } } @@ -230,24 +232,24 @@ void ShaderManagerVulkan::VSUpdateUniforms(int dirtyUniforms) { const bool invertedZ = gstate_c.vpDepthScale < 0; ConvertProjMatrixToVulkan(flippedMatrix, invertedX, invertedY, invertedZ); - CopyMatrix4x4(ub_transformCommon.proj, flippedMatrix.getReadPtr()); + CopyMatrix4x4(ub_base.proj, flippedMatrix.getReadPtr()); } if (dirtyUniforms & DIRTY_PROJTHROUGHMATRIX) { Matrix4x4 proj_through; proj_through.setOrtho(0.0f, gstate_c.curRTWidth, gstate_c.curRTHeight, 0, 0, 1); ConvertProjMatrixToVulkanThrough(proj_through); - CopyMatrix4x4(ub_transformCommon.proj, proj_through.getReadPtr()); + CopyMatrix4x4(ub_base.proj, proj_through.getReadPtr()); } // Transform if (dirtyUniforms & DIRTY_WORLDMATRIX) { - ConvertMatrix4x3To4x4(ub_transformCommon.world, gstate.worldMatrix); + ConvertMatrix4x3To4x4(ub_base.world, gstate.worldMatrix); } if (dirtyUniforms & DIRTY_VIEWMATRIX) { - ConvertMatrix4x3To4x4(ub_transformCommon.view, gstate.viewMatrix); + ConvertMatrix4x3To4x4(ub_base.view, gstate.viewMatrix); } if (dirtyUniforms & DIRTY_TEXMATRIX) { - ConvertMatrix4x3To4x4(ub_transformCommon.tex, gstate.tgenMatrix); + ConvertMatrix4x3To4x4(ub_base.tex, gstate.tgenMatrix); } if (dirtyUniforms & DIRTY_FOGCOEF) { float fogcoef[2] = { @@ -270,7 +272,7 @@ void ShaderManagerVulkan::VSUpdateUniforms(int dirtyUniforms) { ERROR_LOG_REPORT_ONCE(fognan, G3D, "Unhandled fog NaN/INF combo: %f %f", fogcoef[0], fogcoef[1]); } #endif - CopyFloat2(ub_transformCommon.fogCoef, fogcoef); + CopyFloat2(ub_base.fogCoef, fogcoef); } // TODO: Could even set all bones in one go if they're all dirty. #ifdef USE_BONE_ARRAY @@ -349,7 +351,7 @@ void ShaderManagerVulkan::VSUpdateUniforms(int dirtyUniforms) { default: ERROR_LOG_REPORT(G3D, "Unexpected UV gen mode: %d", gstate.getUVGenMode()); } - CopyFloat4(ub_transformCommon.uvScaleOffset, uvscaleoff); + CopyFloat4(ub_base.uvScaleOffset, uvscaleoff); } if (dirtyUniforms & DIRTY_DEPTHRANGE) { @@ -374,7 +376,7 @@ void ShaderManagerVulkan::VSUpdateUniforms(int dirtyUniforms) { } float data[4] = { viewZScale, viewZCenter, viewZCenter, viewZInvScale }; - CopyFloat4(ub_transformCommon.depthRange, data); + CopyFloat4(ub_base.depthRange, data); } // Lighting @@ -383,7 +385,7 @@ void ShaderManagerVulkan::VSUpdateUniforms(int dirtyUniforms) { } if (dirtyUniforms & DIRTY_MATAMBIENTALPHA) { // Note - this one is not in lighting but in transformCommon as it has uses beyond lighting - Uint8x3ToFloat4_AlphaUint8(ub_transformCommon.matAmbient, gstate.materialambient, gstate.getMaterialAmbientA()); + Uint8x3ToFloat4_AlphaUint8(ub_base.matAmbient, gstate.materialambient, gstate.getMaterialAmbientA()); } if (dirtyUniforms & DIRTY_MATDIFFUSE) { Uint8x3ToFloat4(ub_lights.materialDiffuse, gstate.materialdiffuse); diff --git a/GPU/Vulkan/ShaderManagerVulkan.h b/GPU/Vulkan/ShaderManagerVulkan.h index 4bdc3951e1..5394c761ea 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.h +++ b/GPU/Vulkan/ShaderManagerVulkan.h @@ -82,24 +82,34 @@ struct UB_VS_TransformCommon { float depthRange[4]; float fogCoef[4]; float matAmbient[4]; + // Fragment data + float fogColor[4]; + float texEnvColor[4]; + float alphaColorRef[4]; + float colorTestMask[4]; + float stencilReplace[4]; // only first float used + float blendFixA[4]; + float blendFixB[4]; + float texClamp[4]; + float texClampOffset[4]; }; static const char *ub_baseStr = -R"(matrix4x4 proj; - matrix4x4 view; - matrix4x4 world; - matrix4x4 tex; +R"( mat4 proj_mtx; + mat4 view_mtx; + mat4 world_mtx; + mat4 tex_mtx; vec4 uvScaleOffset; vec4 depthRange; vec2 fogCoef; vec4 matAmbient; - vec3 blendFixA; // Blend func replace + vec3 blendFixA; vec3 blendFixB; - vec4 texclamp; // Texture clamp emu + vec4 texclamp; vec2 texclampoff; - vec4 alphacolorref; // Alpha/Color test + vec4 alphacolorref; ivec4 alphacolormask; - float stencilReplaceValue; // Stencil replacement + float stencilReplaceValue; vec3 texenv; vec3 fogcolor; )"; @@ -120,7 +130,7 @@ struct UB_VS_Lights { }; static const char *ub_vs_lightsStr = -R"(vec3 ambientColor; +R"( vec3 ambientColor; vec3 materialDiffuse; vec4 materialSpecular; vec3 materialEmissive; @@ -139,34 +149,9 @@ struct UB_VS_Bones { }; static const char *ub_vs_bonesStr = -R"(matrix4x4 m[8]; +R"(mat4 m[8]; )"; -// Let's not bother splitting this, we'll just upload the lot for every draw call. -struct UB_FS_All { - float fogColor[4]; - float texEnvColor[4]; - float alphaColorRef[4]; - float colorTestMask[4]; - float stencilReplace[4]; // only first float used - float blendFixA[4]; - float blendFixB[4]; - float texClamp[4]; - float texClampOffset[4]; -}; - -static const char *ub_fs_allStr = -R"( - vec3 fogColor; - vec3 texenv; - vec4 alphaColorRef; - vec3 colorTestMask; - float stencilReplace; - vec3 blendFixA; - vec3 blendFixB; - vec4 texClamp; - vec2 texClampOffset; -)"; class VulkanFragmentShader { public: @@ -244,10 +229,9 @@ private: char *codeBuffer_; // Uniform block scratchpad. These (the relevant ones) are copied to the current pushbuffer at draw time. - UB_VS_TransformCommon ub_transformCommon; + UB_VS_TransformCommon ub_base; UB_VS_Lights ub_lights; UB_VS_Bones ub_bones; - UB_FS_All ub_fragment; typedef std::map FSCache; FSCache fsCache_; diff --git a/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp b/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp index d76ce47ed1..7cb9e1e0b7 100644 --- a/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp +++ b/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp @@ -55,14 +55,14 @@ static const char * const boneWeightDecl[9] = { "#ERROR#", - "layout(location = 0) in mediump float w1;\n", - "layout(location = 0) in mediump vec2 w1;\n", - "layout(location = 0) in mediump vec3 w1;\n", - "layout(location = 0) in mediump vec4 w1;\n", - "layout(location = 0) in mediump vec4 w1;\nin mediump float w2;\n", - "layout(location = 0) in mediump vec4 w1;\nin mediump vec2 w2;\n", - "layout(location = 0) in mediump vec4 w1;\nin mediump vec3 w2;\n", - "layout(location = 0) in mediump vec4 w1, w2;\n", + "layout(location = 0) in float w1;\n", + "layout(location = 0) in vec2 w1;\n", + "layout(location = 0) in vec3 w1;\n", + "layout(location = 0) in vec4 w1;\n", + "layout(location = 0) in vec4 w1;\nin float w2;\n", + "layout(location = 0) in vec4 w1;\nin vec2 w2;\n", + "layout(location = 0) in vec4 w1;\nin vec3 w2;\n", + "layout(location = 0) in vec4 w1, w2;\n", }; enum DoLightComputation { @@ -101,12 +101,13 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { // #define USE_FOR_LOOP + WRITE(p, "#version 140\n"); // GLSL ES + WRITE(p, "#extension GL_ARB_separate_shader_objects : enable\n"); + WRITE(p, "#extension GL_ARB_shading_language_420pack : enable\n"); + bool highpFog = false; bool highpTexcoord = false; - const char *attribute = "in"; - const char *varying = "out"; - bool isModeThrough = id.Bit(VS_BIT_IS_THROUGH); bool lmode = id.Bit(VS_BIT_LMODE) && !isModeThrough; // TODO: Different expression than in shaderIDgen bool doTexture = id.Bit(VS_BIT_DO_TEXTURE); @@ -132,6 +133,17 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { bool enableLighting = id.Bit(VS_BIT_LIGHTING_ENABLE); int matUpdate = id.Bits(VS_BIT_MATERIAL_UPDATE, 3); + // The uniforms are passed in as three "clumps" that may or may not be present. + // We will memcpy the parts into place in a big buffer so we can be quite dynamic about what parts + // are present and what parts aren't, but we will not be ultra detailed about it. + + WRITE(p, "\n"); + WRITE(p, "layout (std140, set = 0, binding = 3) uniform baseVars {\n%s\n} base;\n", ub_baseStr); + if (enableLighting) + WRITE(p, "layout (std140, set = 0, binding = 4) uniform lightVars {\n%s\n} light;\n", ub_vs_lightsStr); + if (enableBones) + WRITE(p, "layout (std140, set = 0, binding = 5) uniform boneVars {\n%s\n} bone;\n", ub_vs_bonesStr); + const char *shading = doFlatShading ? "flat " : ""; DoLightComputation doLight[4] = { LIGHT_OFF, LIGHT_OFF, LIGHT_OFF, LIGHT_OFF }; @@ -157,10 +169,10 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { if (useHWTransform) WRITE(p, "layout (location = %d) in vec3 position;\n", PspAttributeLocation::POSITION); else - WRITE(p, "layout (location = %d) vec4 position;\n", PspAttributeLocation::POSITION); // need to pass the fog coord in w + WRITE(p, "layout (location = %d) in vec4 position;\n", PspAttributeLocation::POSITION); // need to pass the fog coord in w if (useHWTransform && hasNormal) - WRITE(p, "layout (location = %d) mediump vec3 normal;\n", PspAttributeLocation::NORMAL); + WRITE(p, "layout (location = %d) in vec3 normal;\n", PspAttributeLocation::NORMAL); if (doTexture && hasTexcoord) { if (!useHWTransform && doTextureProjection && !throughmode) @@ -169,39 +181,29 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { WRITE(p, "layout (location = %d) in vec2 texcoord;\n", PspAttributeLocation::TEXCOORD); } if (hasColor) { - WRITE(p, "layout (location = %d) lowp vec4 color0;\n", PspAttributeLocation::COLOR0); + WRITE(p, "layout (location = %d) in vec4 color0;\n", PspAttributeLocation::COLOR0); if (lmode && !useHWTransform) // only software transform supplies color1 as vertex data - WRITE(p, "layout (location = %d) lowp vec3 color1;\n", PspAttributeLocation::COLOR0); + WRITE(p, "layout (location = %d) in vec3 color1;\n", PspAttributeLocation::COLOR0); } - // The uniforms are passed in as three "clumps" that may or may not be present. - // We will memcpy the parts into place in a big buffer so we can be quite dynamic about what parts - // are present and what parts aren't, but we will not be ultra detailed about it. - - WRITE(p, "layout (binding=3) uniform base {\n%s\n}\n", ub_baseStr); - if (enableLighting) - WRITE(p, "layout (binding=4) uniform light {\n%s\n}\n", ub_vs_lightsStr); - if (enableBones) - WRITE(p, "layout (binding=5) uniform bone {\n%s\n}\n", ub_vs_bonesStr); - bool prescale = false; - WRITE(p, "layout (location = 1) %s out lowp vec4 v_color0;\n", shading); + WRITE(p, "layout (location = 1) %sout vec4 v_color0;\n", shading); if (lmode) { - WRITE(p, "layout (location = 2) %s out lowp vec3 v_color1;\n", shading); + WRITE(p, "layout (location = 2) %sout vec3 v_color1;\n", shading); } if (doTexture) { if (doTextureProjection) { - WRITE(p, "layout (location = 0) %s out vec3 v_texcoord;\n", highpTexcoord ? "highp" : "mediump"); + WRITE(p, "layout (location = 0) out vec3 v_texcoord;\n"); } else { - WRITE(p, "layout (location = 0) %s out vec2 v_texcoord;\n", highpTexcoord ? "highp" : "mediump"); + WRITE(p, "layout (location = 0) out vec2 v_texcoord;\n"); } } if (enableFog) { // See the fragment shader generator - WRITE(p, "layout (location = 3) %s out float v_fogdepth;\n", highpFog ? "highp" : "mediump"); + WRITE(p, "layout (location = 3) out float v_fogdepth;\n"); } // See comment above this function (GenerateVertexShader). @@ -240,22 +242,22 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { WRITE(p, " v_fogdepth = position.w;\n"); } if (isModeThrough) { - WRITE(p, " gl_Position = base.proj * vec4(position.xyz, 1.0);\n"); + WRITE(p, " gl_Position = base.proj_mtx * vec4(position.xyz, 1.0);\n"); } else { // The viewport is used in this case, so need to compensate for that. if (gstate_c.Supports(GPU_ROUND_DEPTH_TO_16BIT)) { - WRITE(p, " gl_Position = depthRoundZVP(base.proj * vec4(position.xyz, 1.0));\n"); + WRITE(p, " gl_Position = depthRoundZVP(base.proj_mtx * vec4(position.xyz, 1.0));\n"); } else { - WRITE(p, " gl_Position = base.proj * vec4(position.xyz, 1.0);\n"); + WRITE(p, " gl_Position = base.proj_mtx * vec4(position.xyz, 1.0);\n"); } } } else { // Step 1: World Transform / Skinning if (!enableBones) { // No skinning, just standard T&L. - WRITE(p, " vec3 worldpos = (base.world * vec4(position.xyz, 1.0)).xyz;\n"); + WRITE(p, " vec3 worldpos = (base.world_mtx * vec4(position.xyz, 1.0)).xyz;\n"); if (hasNormal) - WRITE(p, " mediump vec3 worldnormal = normalize((base.world * vec4(%snormal, 0.0)).xyz);\n", flipNormal ? "-" : ""); + WRITE(p, " mediump vec3 worldnormal = normalize((base.world_mtx * vec4(%snormal, 0.0)).xyz);\n", flipNormal ? "-" : ""); else WRITE(p, " mediump vec3 worldnormal = vec3(0.0, 0.0, 1.0);\n"); } else { @@ -291,17 +293,17 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { // Trying to simplify this results in bugs in LBP... WRITE(p, " vec3 skinnedpos = (skinMatrix * vec4(position, 1.0)).xyz %s;\n", factor); - WRITE(p, " vec3 worldpos = (base.world * vec4(skinnedpos, 1.0)).xyz;\n"); + WRITE(p, " vec3 worldpos = (base.world_mtx * vec4(skinnedpos, 1.0)).xyz;\n"); if (hasNormal) { WRITE(p, " mediump vec3 skinnednormal = (skinMatrix * vec4(%snormal, 0.0)).xyz %s;\n", flipNormal ? "-" : "", factor); } else { WRITE(p, " mediump vec3 skinnednormal = (skinMatrix * vec4(0.0, 0.0, %s1.0, 0.0)).xyz %s;\n", flipNormal ? "-" : "", factor); } - WRITE(p, " mediump vec3 worldnormal = normalize((base.world * vec4(skinnednormal, 0.0)).xyz);\n"); + WRITE(p, " mediump vec3 worldnormal = normalize((base.world_mtx * vec4(skinnednormal, 0.0)).xyz);\n"); } - WRITE(p, " vec4 viewPos = base.view * vec4(worldpos, 1.0);\n"); + WRITE(p, " vec4 viewPos = base.view_mtx * vec4(worldpos, 1.0);\n"); // Final view and projection transforms. if (gstate_c.Supports(GPU_ROUND_DEPTH_TO_16BIT)) { @@ -321,7 +323,7 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { bool distanceNeeded = false; if (enableLighting) { - WRITE(p, " lowp vec4 lightSum0 = light.ambient * %s + vec4(light.matemissive, 0.0);\n", ambientStr); + WRITE(p, " vec4 lightSum0 = light.ambient * %s + vec4(light.matemissive, 0.0);\n", ambientStr); for (int i = 0; i < 4; i++) { GELightType type = static_cast(id.Bits(VS_BIT_LIGHT0_TYPE + 4 * i, 2)); @@ -336,15 +338,15 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { } if (!specularIsZero) { - WRITE(p, " lowp vec3 lightSum1 = vec3(0.0);\n"); + WRITE(p, " vec3 lightSum1 = vec3(0.0);\n"); } if (!diffuseIsZero) { WRITE(p, " vec3 toLight;\n"); - WRITE(p, " lowp vec3 diffuse;\n"); + WRITE(p, " vec3 diffuse;\n"); } if (distanceNeeded) { WRITE(p, " float distance;\n"); - WRITE(p, " lowp float lightScale;\n"); + WRITE(p, " float lightScale;\n"); } } @@ -392,7 +394,7 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { break; case GE_LIGHTTYPE_SPOT: case GE_LIGHTTYPE_UNKNOWN: - WRITE(p, " lowp float angle%i = dot(normalize(light.dir[%i]), toLight);\n", i, i); + WRITE(p, " float angle%i = dot(normalize(light.dir[%i]), toLight);\n", i, i); WRITE(p, " if (angle[%i] >= light.angle[%i]) {\n", i, i); WRITE(p, " lightScale = clamp(1.0 / dot(light.att[%i], vec3(1.0, distance, distance*distance)), 0.0, 1.0) * pow(angle[%i], light.spotCoef[%i]);\n", i, i, i); WRITE(p, " } else {\n"); diff --git a/ext/native/thin3d/VulkanContext.cpp b/ext/native/thin3d/VulkanContext.cpp index 9291b7d0b9..c0c5b504a9 100644 --- a/ext/native/thin3d/VulkanContext.cpp +++ b/ext/native/thin3d/VulkanContext.cpp @@ -184,17 +184,15 @@ VkCommandBuffer VulkanContext::GetInitCommandBuffer() { return frame_[curFrame_].cmdInit; } +void VulkanContext::QueueBeforeSurfaceRender(VkCommandBuffer cmd) { + cmdQueue_.push_back(cmd); +} + VkCommandBuffer VulkanContext::BeginSurfaceRenderPass(VkClearValue clear_values[2]) { FrameData *frame = &frame_[curFrame_]; - // Make sure the command buffer from the frame before the previous has been fully executed. - WaitAndResetFence(frame->fence); - - // Process pending deletes. - frame->deleteList.PerformDeletes(device_); - // Get the index of the next available swapchain image, and a semaphore to block command buffer execution on. - // Now, I wonder if we should do this early in the frame or late? + // Now, I wonder if we should do this early in the frame or late? Right now we do it early, which should be fine. VkResult res = fpAcquireNextImageKHR(device_, swap_chain_, UINT64_MAX, acquireSemaphore, @@ -204,6 +202,12 @@ VkCommandBuffer VulkanContext::BeginSurfaceRenderPass(VkClearValue clear_values[ // return codes assert(res == VK_SUCCESS); + // Make sure the very last command buffer from the frame before the previous has been fully executed. + WaitAndResetFence(frame->fence); + + // Process pending deletes. + frame->deleteList.PerformDeletes(device_); + VkCommandBufferBeginInfo begin; begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; begin.pNext = NULL; @@ -225,31 +229,13 @@ VkCommandBuffer VulkanContext::BeginSurfaceRenderPass(VkClearValue clear_values[ rp_begin.clearValueCount = 2; rp_begin.pClearValues = clear_values; + // We don't really need to record this at this point in time, but hey, at some point we'll start this + // pass anyway so might as well do it now (although you can imagine getting away with just a stretchblt and not + // even starting a final render pass if there's nothing to overlay... hm. Uncommon though on mobile). vkCmdBeginRenderPass(frame->cmdBuf, &rp_begin, VK_SUBPASS_CONTENTS_INLINE); return frame->cmdBuf; } -void VulkanContext::WaitUntilQueueIdle() { - // Should almost never be used - vkQueueWaitIdle(gfx_queue_); -} - -bool VulkanContext::MemoryTypeFromProperties(uint32_t typeBits, VkFlags requirements_mask, uint32_t *typeIndex) { - // Search memtypes to find first index with those properties - for (uint32_t i = 0; i < 32; i++) { - if ((typeBits & 1) == 1) { - // Type is available, does it match user properties? - if ((memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) { - *typeIndex = i; - return true; - } - } - typeBits >>= 1; - } - // No memory types matched, return failure - return false; -} - void VulkanContext::EndSurfaceRenderPass() { FrameData *frame = &frame_[curFrame_]; vkCmdEndRenderPass(frame->cmdBuf); @@ -259,23 +245,30 @@ void VulkanContext::EndSurfaceRenderPass() { VkResult res = vkEndCommandBuffer(frame->cmdBuf); assert(res == VK_SUCCESS); - int numCmdBufs = 0; - VkCommandBuffer cmdBufs[2]; + // So the sequence will be, cmdInit, [cmdQueue_], frame->cmdBuf. + // This way we bunch up all the initialization needed for the frame, we render to + // other buffers before the back buffer, and then last we render to the backbuffer. + int numCmdBufs = 0; + std::vector cmdBufs; if (frame->hasInitCommands) { vkEndCommandBuffer(frame->cmdInit); - cmdBufs[numCmdBufs++] = frame->cmdInit; + cmdBufs.push_back(frame->cmdInit); frame->hasInitCommands = false; } - cmdBufs[numCmdBufs++] = frame->cmdBuf; + for (auto cmd : cmdQueue_) { + cmdBufs.push_back(cmd); + } + cmdQueue_.clear(); + cmdBufs.push_back(frame->cmdBuf); VkSubmitInfo submit_info[1] = {}; submit_info[0].pNext = NULL; submit_info[0].sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submit_info[0].waitSemaphoreCount = 1; submit_info[0].pWaitSemaphores = &acquireSemaphore; - submit_info[0].commandBufferCount = numCmdBufs; - submit_info[0].pCommandBuffers = cmdBufs; + submit_info[0].commandBufferCount = (uint32_t)cmdBufs.size(); + submit_info[0].pCommandBuffers = cmdBufs.data(); submit_info[0].signalSemaphoreCount = 0; submit_info[0].pSignalSemaphores = NULL; res = vkQueueSubmit(gfx_queue_, 1, submit_info, frame->fence); @@ -300,6 +293,27 @@ void VulkanContext::EndSurfaceRenderPass() { curFrame_ ^= 1; } +void VulkanContext::WaitUntilQueueIdle() { + // Should almost never be used + vkQueueWaitIdle(gfx_queue_); +} + +bool VulkanContext::MemoryTypeFromProperties(uint32_t typeBits, VkFlags requirements_mask, uint32_t *typeIndex) { + // Search memtypes to find first index with those properties + for (uint32_t i = 0; i < 32; i++) { + if ((typeBits & 1) == 1) { + // Type is available, does it match user properties? + if ((memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) { + *typeIndex = i; + return true; + } + } + typeBits >>= 1; + } + // No memory types matched, return failure + return false; +} + void VulkanBeginCommandBuffer(VkCommandBuffer cmd) { VkResult U_ASSERT_ONLY res; VkCommandBufferBeginInfo cmd_buf_info = {}; diff --git a/ext/native/thin3d/VulkanContext.h b/ext/native/thin3d/VulkanContext.h index 70541de5b8..2f47eeb394 100644 --- a/ext/native/thin3d/VulkanContext.h +++ b/ext/native/thin3d/VulkanContext.h @@ -138,7 +138,6 @@ public: globalDeleteList_.QueueDelete(mem); } - VkPipelineCache CreatePipelineCache(); void InitSurfaceAndQueue(HINSTANCE conn, HWND wnd); @@ -151,8 +150,6 @@ public: void InitObjects(HINSTANCE hInstance, HWND hWnd, bool depthPresent); void DestroyObjects(); - VkCommandBuffer GetInitCommandBuffer(); - void DestroySurfaceRenderPass(); void DestroyFramebuffers(); void DestroySwapChain(); @@ -171,12 +168,22 @@ public: int GetWidth() { return width; } int GetHeight() { return height; } - // The surface render pass is special because it has to acquire the backbuffer, and may thus "block". - // Use the returned command buffer to enqueue commands. Might be a good idea to use secondary cmd buffers. - VkCommandBuffer BeginSurfaceRenderPass(VkClearValue clear_values[2]); + VkCommandBuffer GetInitCommandBuffer(); + // This must only be accessed between BeginSurfaceRenderPass and EndSurfaceRenderPass. + VkCommandBuffer GetSurfaceCommandBuffer() { + return frame_[curFrame_ & 1].cmdBuf; + } + + // The surface render pass is special because it has to acquire the backbuffer, and may thus "block". + // Use the returned command buffer to enqueue commands that render to the backbuffer. + // To render to other buffers first, you can submit additional commandbuffers using QueueBeforeSurfaceRender(cmd). + VkCommandBuffer BeginSurfaceRenderPass(VkClearValue clear_values[2]); + // May eventually need the ability to break and resume the backbuffer render pass in a few rare cases. void EndSurfaceRenderPass(); + void QueueBeforeSurfaceRender(VkCommandBuffer cmd); + bool MemoryTypeFromProperties(uint32_t typeBits, VkFlags requirements_mask, uint32_t *typeIndex); VkResult InitDebugMsgCallback(PFN_vkDebugReportCallbackEXT dbgFunc, int bits, void *userdata = nullptr); @@ -315,6 +322,8 @@ private: VkPhysicalDeviceFeatures featuresAvailable_; VkPhysicalDeviceFeatures featuresEnabled_; + + std::vector cmdQueue_; }; // Wrapper around what you need to use a texture. From ddb36a35a08af849e04f7602044082d2baa0c4e8 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Wed, 6 Jan 2016 12:52:42 +0100 Subject: [PATCH 021/116] Some descriptor binding fixes --- GPU/Vulkan/DrawEngineVulkan.cpp | 37 +++++++++++--------- GPU/Vulkan/DrawEngineVulkan.h | 19 ++++++++-- GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp | 2 +- GPU/Vulkan/VertexShaderGeneratorVulkan.cpp | 6 ++-- ext/native/thin3d/VulkanContext.h | 7 ++-- 5 files changed, 47 insertions(+), 24 deletions(-) diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index 72e2aba8a7..aa09c7511d 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -93,12 +93,13 @@ DrawEngineVulkan::DrawEngineVulkan(VulkanContext *vulkan) indexGen.Setup(decIndex); + // All resources we need for PSP drawing. Usually only bindings 0 and 2-4 are populated. VkDescriptorSetLayoutBinding bindings[5]; bindings[0].descriptorCount = 1; bindings[0].pImmutableSamplers = nullptr; bindings[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; bindings[0].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; - bindings[0].binding = 1; + bindings[0].binding = 0; bindings[1].descriptorCount = 1; bindings[1].pImmutableSamplers = nullptr; bindings[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; @@ -118,7 +119,7 @@ DrawEngineVulkan::DrawEngineVulkan(VulkanContext *vulkan) bindings[4].pImmutableSamplers = nullptr; bindings[4].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; bindings[4].stageFlags = VK_SHADER_STAGE_VERTEX_BIT; - bindings[4].binding = 3; + bindings[4].binding = 4; VkDevice device = vulkan_->GetDevice(); @@ -152,6 +153,7 @@ DrawEngineVulkan::DrawEngineVulkan(VulkanContext *vulkan) for (int i = 0; i < 2; i++) { VkResult res = vkCreateDescriptorPool(vulkan_->GetDevice(), &dp, nullptr, &frame_[i].descPool); assert(VK_SUCCESS == res); + frame_[i].pushData = new VulkanPushBuffer(vulkan_, 4 * 1024 * 1024); // TODO: Do something more dynamic } VkPipelineLayoutCreateInfo pl; @@ -166,6 +168,12 @@ DrawEngineVulkan::DrawEngineVulkan(VulkanContext *vulkan) assert(VK_SUCCESS == res); } +void DrawEngineVulkan::BeginFrame() { + FrameData *frame = &frame_[curFrame_ & 1]; + vkResetDescriptorPool(vulkan_->GetDevice(), frame->descPool, 0); + frame->pushData->Reset(); +} + void DrawEngineVulkan::EndFrame() { curFrame_++; } @@ -176,6 +184,11 @@ DrawEngineVulkan::~DrawEngineVulkan() { FreeMemoryPages(splineBuffer, SPLINE_BUFFER_SIZE); FreeMemoryPages(transformed, TRANSFORMED_VERTEX_BUFFER_SIZE); FreeMemoryPages(transformedExpanded, 3 * TRANSFORMED_VERTEX_BUFFER_SIZE); + + for (int i = 0; i < 2; i++) { + vulkan_->QueueDelete(frame_[i].descPool); + delete frame_[i].pushData; + } } VertexDecoder *DrawEngineVulkan::GetVertexDecoder(u32 vtype) { @@ -350,20 +363,11 @@ inline u32 ComputeMiniHashRange(const void *ptr, size_t sz) { } } -/* -struct DescriptorSetKey { - void *texture_; - void *secondaryTexture_; - - bool operator < (const DescriptorSetKey &other) const { - if (texture_ < other.texture_) return true; else if (texture_ > other.texture_) return false; - if (secondaryTexture_ < other.secondaryTexture_) return true; else if (secondaryTexture_ > other.secondaryTexture_) return false; - return false; - } -}; -*/ +VkDescriptorSet DrawEngineVulkan::GetDescriptorSet(CachedTextureVulkan *texture) { + DescriptorSetKey key; + key.texture_ = texture; + key.secondaryTexture_ = nullptr; -VkDescriptorSet DrawEngineVulkan::GetDescriptorSet() { return nullptr; } @@ -373,9 +377,10 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { FrameData *frame = &frame_[curFrame_ & 1]; + CachedTextureVulkan *tex = nullptr; // This is not done on every drawcall, we should collect vertex data // until critical state changes. That's when we draw (flush). - VkDescriptorSet ds = GetDescriptorSet(); + VkDescriptorSet ds = GetDescriptorSet(tex); GEPrimitiveType prim = prevPrim_; // ApplyDrawState(prim); diff --git a/GPU/Vulkan/DrawEngineVulkan.h b/GPU/Vulkan/DrawEngineVulkan.h index 05f3911cb8..b14bd52477 100644 --- a/GPU/Vulkan/DrawEngineVulkan.h +++ b/GPU/Vulkan/DrawEngineVulkan.h @@ -29,7 +29,7 @@ // The format of the various uniform buffers may vary though - vertex shaders that don't skin // won't get any bone data, etc. - +#include #include #include "GPU/Vulkan/VulkanUtil.h" @@ -48,6 +48,7 @@ class ShaderManagerVulkan; class PipelineManagerVulkan; class TextureCacheVulkan; class FramebufferManagerVulkan; +class CachedTextureVulkan; // Avoiding the full include of TextureDecoder.h. #if (defined(_M_SSE) && defined(_M_X64)) || defined(ARM64) @@ -140,6 +141,7 @@ public: return pipelineLayout_; } + void BeginFrame(); void EndFrame(); private: @@ -147,7 +149,7 @@ private: void DecodeVertsStep(); void DoFlush(VkCommandBuffer cmd); - VkDescriptorSet GetDescriptorSet(); + VkDescriptorSet GetDescriptorSet(CachedTextureVulkan *texture); VertexDecoder *GetVertexDecoder(u32 vtype); @@ -157,10 +159,23 @@ private: VkDescriptorSetLayout descriptorSetLayout_; VkPipelineLayout pipelineLayout_; + struct DescriptorSetKey { + void *texture_; + void *secondaryTexture_; + + bool operator < (const DescriptorSetKey &other) const { + if (texture_ < other.texture_) return true; else if (texture_ > other.texture_) return false; + if (secondaryTexture_ < other.secondaryTexture_) return true; else if (secondaryTexture_ > other.secondaryTexture_) return false; + return false; + } + }; + // We alternate between these. struct FrameData { VkDescriptorPool descPool; VulkanPushBuffer *pushData; + // We do rolling allocation and reset instead of caching across frames. That we might do later. + std::map descSets; }; int curFrame_; diff --git a/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp b/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp index 56c3ad5947..c42b1bbc82 100644 --- a/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp +++ b/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp @@ -92,7 +92,7 @@ bool GenerateVulkanGLSLFragmentShader(const ShaderID &id, char *buffer) { const char *shading = doFlatShading ? "flat" : ""; - WRITE(p, "layout (std140, set = 0, binding = 3) uniform baseUBO {\n%s} base;\n", ub_baseStr); + WRITE(p, "layout (std140, set = 0, binding = 2) uniform baseUBO {\n%s} base;\n", ub_baseStr); if (doTexture) { WRITE(p, "layout (binding = 0) uniform sampler2D tex;\n"); } diff --git a/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp b/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp index 7cb9e1e0b7..dc308e344f 100644 --- a/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp +++ b/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp @@ -138,11 +138,11 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { // are present and what parts aren't, but we will not be ultra detailed about it. WRITE(p, "\n"); - WRITE(p, "layout (std140, set = 0, binding = 3) uniform baseVars {\n%s\n} base;\n", ub_baseStr); + WRITE(p, "layout (std140, set = 0, binding = 2) uniform baseVars {\n%s\n} base;\n", ub_baseStr); if (enableLighting) - WRITE(p, "layout (std140, set = 0, binding = 4) uniform lightVars {\n%s\n} light;\n", ub_vs_lightsStr); + WRITE(p, "layout (std140, set = 0, binding = 3) uniform lightVars {\n%s\n} light;\n", ub_vs_lightsStr); if (enableBones) - WRITE(p, "layout (std140, set = 0, binding = 5) uniform boneVars {\n%s\n} bone;\n", ub_vs_bonesStr); + WRITE(p, "layout (std140, set = 0, binding = 4) uniform boneVars {\n%s\n} bone;\n", ub_vs_bonesStr); const char *shading = doFlatShading ? "flat " : ""; diff --git a/ext/native/thin3d/VulkanContext.h b/ext/native/thin3d/VulkanContext.h index 2f47eeb394..df3fc7d4a7 100644 --- a/ext/native/thin3d/VulkanContext.h +++ b/ext/native/thin3d/VulkanContext.h @@ -68,6 +68,7 @@ struct layer_properties { // This is a bit repetitive... class VulkanDeleteList { public: + void QueueDelete(VkDescriptorPool pool) { descPools_.push_back(pool); } void QueueDelete(VkShaderModule module) { modules_.push_back(module); } void QueueDelete(VkBuffer buffer) { buffers_.push_back(buffer); } void QueueDelete(VkBufferView bufferView) { bufferViews_.push_back(bufferView); } @@ -76,6 +77,7 @@ public: void QueueDelete(VkDeviceMemory deviceMemory) { memory_.push_back(deviceMemory); } void Ingest(VulkanDeleteList &del) { + descPools_ = std::move(del.descPools_); modules_ = std::move(del.modules_); buffers_ = std::move(del.buffers_); bufferViews_ = std::move(del.bufferViews_); @@ -85,8 +87,8 @@ public: } void PerformDeletes(VkDevice device) { - for (auto &module : modules_) { - vkDestroyShaderModule(device, module, nullptr); + for (auto &descPool : descPools_) { + vkDestroyDescriptorPool(device, descPool, nullptr); } modules_.clear(); for (auto &buf : buffers_) { @@ -112,6 +114,7 @@ public: } private: + std::vector descPools_; std::vector modules_; std::vector buffers_; std::vector bufferViews_; From 01e3fbae95f835a57b08aa732c0292b9d640592a Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Wed, 6 Jan 2016 23:08:26 +0100 Subject: [PATCH 022/116] Fix clearing bug, add FIFO_RELAXED flag, etc --- Core/System.h | 2 ++ GPU/Vulkan/DrawEngineVulkan.cpp | 33 +++++++++++++++---------- GPU/Vulkan/FramebufferVulkan.cpp | 17 +++++++++++++ GPU/Vulkan/FramebufferVulkan.h | 20 ++++++--------- GPU/Vulkan/GPU_Vulkan.cpp | 3 +++ GPU/Vulkan/ShaderManagerVulkan.cpp | 38 ++++++++++++++++------------- GPU/Vulkan/StateMappingVulkan.cpp | 18 ++++++-------- GPU/Vulkan/TextureCacheVulkan.cpp | 4 +++ GPU/Vulkan/TextureCacheVulkan.h | 9 ++----- UI/EmuScreen.cpp | 1 + UI/NativeApp.cpp | 1 + ext/native/thin3d/VulkanContext.cpp | 22 ++++++++--------- ext/native/thin3d/VulkanContext.h | 1 + 13 files changed, 97 insertions(+), 72 deletions(-) diff --git a/Core/System.h b/Core/System.h index 7749d893bc..4ff1767d87 100644 --- a/Core/System.h +++ b/Core/System.h @@ -68,6 +68,8 @@ void PSP_BeginHostFrame(); void PSP_EndHostFrame(); void PSP_RunLoopUntil(u64 globalticks); void PSP_RunLoopFor(int cycles); +void PSP_BeginFrame(); +void PSP_EndFrame(); void Audio_Init(); diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index aa09c7511d..56298b7a04 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -171,10 +171,13 @@ DrawEngineVulkan::DrawEngineVulkan(VulkanContext *vulkan) void DrawEngineVulkan::BeginFrame() { FrameData *frame = &frame_[curFrame_ & 1]; vkResetDescriptorPool(vulkan_->GetDevice(), frame->descPool, 0); + frame->pushData->Begin(vulkan_->GetDevice()); frame->pushData->Reset(); } void DrawEngineVulkan::EndFrame() { + FrameData *frame = &frame_[curFrame_ & 1]; + frame->pushData->End(vulkan_->GetDevice()); curFrame_++; } @@ -471,16 +474,20 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { if (result.action == SW_DRAW_PRIMITIVES) { if (result.setStencil) { - // dxstate.stencilFunc.set(D3DCMP_ALWAYS, result.stencilValue, 255); + // hey, dynamic state! + vkCmdSetStencilReference(cmd_, VK_STENCIL_FRONT_AND_BACK, result.stencilValue); } - VkBuffer buf[1] = {}; - VkDeviceSize offsets[1] = { 0 }; + ibOffset = (uint32_t)frame->pushData->Push(decIndex, 2 * indexGen.VertexCount()); + vbOffset = (uint32_t)frame->pushData->Push(decoded, numTrans * dec_->GetDecVtxFmt().stride); + + VkBuffer buf[1] = { frame->pushData->GetVkBuffer() }; + VkDeviceSize offsets[1] = { vbOffset }; if (drawIndexed) { // TODO: Have a buffer per frame, use a walking buffer pointer // TODO: Avoid rebinding if the vertex size stays the same by using the offset arguments vkCmdBindVertexBuffers(cmd_, 0, 1, buf, offsets); - vkCmdBindIndexBuffer(cmd_, buf[0], 0, VK_INDEX_TYPE_UINT16); + vkCmdBindIndexBuffer(cmd_, buf[0], ibOffset, VK_INDEX_TYPE_UINT16); vkCmdDrawIndexed(cmd_, numTrans, 1, 0, 0, 0); // pD3Ddevice->DrawIndexedPrimitiveUP(glprim[prim], 0, maxIndex, D3DPrimCount(glprim[prim], numTrans), inds, D3DFMT_INDEX16, drawBuffer, sizeof(TransformedVertex)); } else { @@ -497,13 +504,13 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { if (gstate.isClearModeAlphaMask()) mask |= 2; if (gstate.isClearModeDepthMask()) mask |= 4; - VkClearValue value; - value.color.float32[0] = (result.color & 0xFF) * (1.0f / 255.0f); - value.color.float32[1] = ((result.color >> 8) & 0xFF) * (1.0f / 255.0f); - value.color.float32[2] = ((result.color >> 16) & 0xFF) * (1.0f / 255.0f); - value.color.float32[3] = ((result.color >> 24) & 0xFF) * (1.0f / 255.0f); - value.depthStencil.depth = result.depth; - value.depthStencil.stencil = (result.color >> 24) & 0xFF; + VkClearValue colorValue, depthValue; + colorValue.color.float32[0] = (result.color & 0xFF) * (1.0f / 255.0f); + colorValue.color.float32[1] = ((result.color >> 8) & 0xFF) * (1.0f / 255.0f); + colorValue.color.float32[2] = ((result.color >> 16) & 0xFF) * (1.0f / 255.0f); + colorValue.color.float32[3] = ((result.color >> 24) & 0xFF) * (1.0f / 255.0f); + depthValue.depthStencil.depth = result.depth; + depthValue.depthStencil.stencil = (result.color >> 24) & 0xFF; VkClearRect rect; rect.baseArrayLayer = 0; @@ -517,13 +524,13 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { VkClearAttachment attach[2]; if (mask & 3) { attach[count].aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - attach[count].clearValue = value; + attach[count].clearValue = colorValue; attach[count].colorAttachment = 0; count++; } if (mask & 4) { attach[count].aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; - attach[count].clearValue = value; + attach[count].clearValue = depthValue; attach[count].colorAttachment = 0; } vkCmdClearAttachments(cmd_, count, attach, 1, &rect); diff --git a/GPU/Vulkan/FramebufferVulkan.cpp b/GPU/Vulkan/FramebufferVulkan.cpp index b26ab43b12..378e4921fe 100644 --- a/GPU/Vulkan/FramebufferVulkan.cpp +++ b/GPU/Vulkan/FramebufferVulkan.cpp @@ -69,6 +69,23 @@ void FramebufferManagerVulkan::FlushBeforeCopy() { drawEngine_->Flush(nullptr); } +void FramebufferManagerVulkan::ReadFramebufferToMemory(VirtualFramebuffer *vfb, bool sync, int x, int y, int w, int h) { + +} + +void FramebufferManagerVulkan::DownloadFramebufferForClut(u32 fb_address, u32 loadBytes) { + +} + +bool FramebufferManagerVulkan::CreateDownloadTempBuffer(VirtualFramebuffer *nvfb) { + return false; +} + +void FramebufferManagerVulkan::UpdateDownloadTempBuffer(VirtualFramebuffer *nvfb) { + +} + + std::vector FramebufferManagerVulkan::GetFramebufferList() { return std::vector(); } diff --git a/GPU/Vulkan/FramebufferVulkan.h b/GPU/Vulkan/FramebufferVulkan.h index a30a097e70..075e2c435c 100644 --- a/GPU/Vulkan/FramebufferVulkan.h +++ b/GPU/Vulkan/FramebufferVulkan.h @@ -52,9 +52,9 @@ public: return false; } - virtual void ReadFramebufferToMemory(VirtualFramebuffer *vfb, bool sync, int x, int y, int w, int h) override { - throw std::logic_error("The method or operation is not implemented."); - } + void ReadFramebufferToMemory(VirtualFramebuffer *vfb, bool sync, int x, int y, int w, int h) override; + void DownloadFramebufferForClut(u32 fb_address, u32 loadBytes) override; + virtual void MakePixelTexture(const u8 *srcPixels, GEBufferFormat srcPixelFormat, int srcStride, int width, int height) override { } @@ -92,16 +92,6 @@ public: virtual void NotifyRenderFramebufferUpdated(VirtualFramebuffer *vfb, bool vfbFormatChanged) override { } - void DownloadFramebufferForClut(u32 fb_address, u32 loadBytes) override { - - } - - bool CreateDownloadTempBuffer(VirtualFramebuffer *nvfb) override { - return false; - } - void UpdateDownloadTempBuffer(VirtualFramebuffer *nvfb) override { - - } void DestroyAllFBOs(); void Resized(); void DeviceLost(); @@ -111,6 +101,10 @@ public: std::vector GetFramebufferList(); +protected: + bool CreateDownloadTempBuffer(VirtualFramebuffer *nvfb) override; + void UpdateDownloadTempBuffer(VirtualFramebuffer *nvfb) override; + private: VulkanContext *vulkan_; VkCommandBuffer cmd_; diff --git a/GPU/Vulkan/GPU_Vulkan.cpp b/GPU/Vulkan/GPU_Vulkan.cpp index 25bee1aba9..d9d4d116dd 100644 --- a/GPU/Vulkan/GPU_Vulkan.cpp +++ b/GPU/Vulkan/GPU_Vulkan.cpp @@ -578,6 +578,7 @@ void GPU_Vulkan::BeginFrameInternal() { shaderManager_->DirtyUniform(DIRTY_ALL); framebufferManager_.BeginFrame(); + drawEngine_.BeginFrame(); if (g_Config.iRenderingMode == FB_NON_BUFFERED_MODE) { // Draw everything directly to the backbuffer. @@ -627,12 +628,14 @@ void GPU_Vulkan::CopyDisplayToOutput() { void GPU_Vulkan::CopyDisplayToOutputInternal() { // Flush anything left over. drawEngine_.Flush(curCmd_); + drawEngine_.EndFrame(); shaderManager_->DirtyLastShader(); framebufferManager_.CopyDisplayToOutput(); framebufferManager_.EndFrame(); + gstate_c.textureChanged = TEXCHANGE_UPDATED; } diff --git a/GPU/Vulkan/ShaderManagerVulkan.cpp b/GPU/Vulkan/ShaderManagerVulkan.cpp index 88fc61fcfb..24fc019713 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.cpp +++ b/GPU/Vulkan/ShaderManagerVulkan.cpp @@ -144,8 +144,7 @@ std::string VulkanVertexShader::GetShaderString(DebugShaderStringType type) cons } } -// Depth in ogl is between -1;1 we need between 0;1 and optionally reverse it -static void ConvertProjMatrixToVulkan(Matrix4x4 &in, bool invertedX, bool invertedY, bool invertedZ) { +static void ConvertProjMatrixToVulkan(Matrix4x4 &in, bool invertedX, bool invertedY) { // Half pixel offset hack float xoff = 0.5f / gstate_c.curRTRenderWidth; xoff = gstate_c.vpXOffset + (invertedX ? xoff : -xoff); @@ -157,7 +156,9 @@ static void ConvertProjMatrixToVulkan(Matrix4x4 &in, bool invertedX, bool invert if (invertedY) yoff = -yoff; - in.translateAndScale(Vec3(xoff, yoff, 0.5f), Vec3(gstate_c.vpWidthScale, gstate_c.vpHeightScale, invertedZ ? -0.5 : 0.5f)); + const Vec3 trans(xoff, yoff, gstate_c.vpZOffset + 0.5f); + const Vec3 scale(gstate_c.vpWidthScale, gstate_c.vpHeightScale, gstate_c.vpDepthScale * 0.5f); + in.translateAndScale(trans, scale); } static void ConvertProjMatrixToVulkanThrough(Matrix4x4 &in) { @@ -228,9 +229,8 @@ void ShaderManagerVulkan::VSUpdateUniforms(int dirtyUniforms) { flippedMatrix[8] = -flippedMatrix[8]; flippedMatrix[12] = -flippedMatrix[12]; } - - const bool invertedZ = gstate_c.vpDepthScale < 0; - ConvertProjMatrixToVulkan(flippedMatrix, invertedX, invertedY, invertedZ); + + ConvertProjMatrixToVulkan(flippedMatrix, invertedX, invertedY); CopyMatrix4x4(ub_base.proj, flippedMatrix.getReadPtr()); } @@ -357,18 +357,22 @@ void ShaderManagerVulkan::VSUpdateUniforms(int dirtyUniforms) { if (dirtyUniforms & DIRTY_DEPTHRANGE) { float viewZScale = gstate.getViewportZScale(); float viewZCenter = gstate.getViewportZCenter(); - - // Given the way we do the rounding, the integer part of the offset is probably mostly irrelevant as we cancel - // it afterwards anyway. - // It seems that we should adjust for D3D projection matrix. We got squashed up to only 0-1, so we divide - // the scale factor by 2, and add an offset. But, this doesn't work! I get near-perfect results not doing it. - // viewZScale *= 2.0f; - - // Need to take the possibly inverted proj matrix into account. - if (gstate_c.vpDepthScale < 0.0) - viewZScale *= -1.0f; - viewZCenter -= 32767.5f; float viewZInvScale; + + // We had to scale and translate Z to account for our clamped Z range. + // Therefore, we also need to reverse this to round properly. + // + // Example: scale = 65535.0, center = 0.0 + // Resulting range = -65535 to 65535, clamped to [0, 65535] + // gstate_c.vpDepthScale = 2.0f + // gstate_c.vpZOffset = -1.0f + // + // The projection already accounts for those, so we need to reverse them. + // + // Additionally, D3D9 uses a range from [0, 1]. We double and move the center. + viewZScale *= (1.0f / gstate_c.vpDepthScale) * 2.0f; + viewZCenter -= 65535.0f * gstate_c.vpZOffset + 32768.5f; + if (viewZScale != 0.0) { viewZInvScale = 1.0f / viewZScale; } else { diff --git a/GPU/Vulkan/StateMappingVulkan.cpp b/GPU/Vulkan/StateMappingVulkan.cpp index ce7c1122e1..5d5960a4ae 100644 --- a/GPU/Vulkan/StateMappingVulkan.cpp +++ b/GPU/Vulkan/StateMappingVulkan.cpp @@ -279,17 +279,13 @@ void ConvertStateToVulkanKey(FramebufferManagerVulkan &fbManager, int prim, Vulk float depthMin = vpAndScissor.depthRangeMin; float depthMax = vpAndScissor.depthRangeMax; - if (!gstate.isModeThrough()) { - // Direct3D can't handle negative depth ranges, so we fix it in the projection matrix. - if (gstate_c.vpDepthScale != depthMax - depthMin) { - gstate_c.vpDepthScale = depthMax - depthMin; - vpAndScissor.dirtyProj = true; - } - if (depthMin > depthMax) { - std::swap(depthMin, depthMax); - } - if (depthMin < 0.0f) depthMin = 0.0f; - if (depthMax > 1.0f) depthMax = 1.0f; + if (depthMin < 0.0f) depthMin = 0.0f; + if (depthMax > 1.0f) depthMax = 1.0f; + if (vpAndScissor.dirtyProj) { + // shaderManager_->DirtyUniform(DIRTY_PROJMATRIX); + } + if (vpAndScissor.dirtyDepth) { + // shaderManager_->DirtyUniform(DIRTY_DEPTHRANGE); } } diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index 606213b80e..6c10005fba 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -89,6 +89,10 @@ TextureCacheVulkan::~TextureCacheVulkan() { Clear(true); } +void TextureCacheVulkan::DownloadFramebufferForClut(u32 clutAddr, u32 bytes) { + +} + static u32 EstimateTexMemoryUsage(const TextureCacheVulkan::TexCacheEntry *entry) { const u16 dim = entry->dim; const u8 dimW = ((dim >> 0) & 0xf); diff --git a/GPU/Vulkan/TextureCacheVulkan.h b/GPU/Vulkan/TextureCacheVulkan.h index 49edc5222d..cb75f1d4ba 100644 --- a/GPU/Vulkan/TextureCacheVulkan.h +++ b/GPU/Vulkan/TextureCacheVulkan.h @@ -72,13 +72,8 @@ public: void ApplyTexture(VkImageView &imageView, VkSampler &sampler); - bool DecodeTexture(u8 *dest, const GPUgstate &state) { - return false; - } - - void DownloadFramebufferForClut(u32 clutAddr, u32 bytes) override { - - } +protected: + void DownloadFramebufferForClut(u32 clutAddr, u32 bytes); private: void Decimate(); // Run this once per frame to get rid of old textures. diff --git a/UI/EmuScreen.cpp b/UI/EmuScreen.cpp index b78068a025..7b00528dc9 100644 --- a/UI/EmuScreen.cpp +++ b/UI/EmuScreen.cpp @@ -908,6 +908,7 @@ void EmuScreen::render() { while (coreState == CORE_RUNNING) { PSP_RunLoopFor(blockTicks); } + // Hopefully coreState is now CORE_NEXTFRAME if (coreState == CORE_NEXTFRAME) { // set back to running for the next frame diff --git a/UI/NativeApp.cpp b/UI/NativeApp.cpp index c2a80b3e32..a0cea8fc27 100644 --- a/UI/NativeApp.cpp +++ b/UI/NativeApp.cpp @@ -703,6 +703,7 @@ void NativeRender(GraphicsContext *graphicsContext) { ortho.setOrthoD3D(0.0f, xres, 0, yres, -1.0f, 1.0f); break; case GPUBackend::DIRECT3D9: + case GPUBackend::DIRECT3D11: ortho.setOrthoD3D(0.0f, xres, yres, 0.0f, -1.0f, 1.0f); Matrix4x4 translation; translation.setTranslation(Vec3(-0.5f, -0.5f, 0.0f)); diff --git a/ext/native/thin3d/VulkanContext.cpp b/ext/native/thin3d/VulkanContext.cpp index c0c5b504a9..4bfa3d1797 100644 --- a/ext/native/thin3d/VulkanContext.cpp +++ b/ext/native/thin3d/VulkanContext.cpp @@ -194,10 +194,8 @@ VkCommandBuffer VulkanContext::BeginSurfaceRenderPass(VkClearValue clear_values[ // Get the index of the next available swapchain image, and a semaphore to block command buffer execution on. // Now, I wonder if we should do this early in the frame or late? Right now we do it early, which should be fine. VkResult res = fpAcquireNextImageKHR(device_, swap_chain_, - UINT64_MAX, - acquireSemaphore, - NULL, - ¤t_buffer); + UINT64_MAX, acquireSemaphore, NULL, ¤t_buffer); + // TODO: Deal with the VK_SUBOPTIMAL_KHR and VK_ERROR_OUT_OF_DATE_KHR // return codes assert(res == VK_SUCCESS); @@ -917,28 +915,30 @@ void VulkanContext::InitSwapchain(VkCommandBuffer cmd) { VkExtent2D swapChainExtent; // width and height are either both -1, or both not -1. - if (surfCapabilities.currentExtent.width == -1) - { + if (surfCapabilities.currentExtent.width == -1) { // If the surface size is undefined, the size is set to // the size of the images requested. swapChainExtent.width = width; swapChainExtent.height = height; - } else - { + } else { // If the surface size is defined, the swap chain size must match swapChainExtent = surfCapabilities.currentExtent; } // If mailbox mode is available, use it, as is the lowest-latency non- - // tearing mode. If not, try IMMEDIATE which will usually be available, - // and is fastest (though it tears). If not, fall back to FIFO which is - // always available. + // tearing mode. If not, try FIFO_RELAXED, and if not that, try IMMEDIATE + // which will usually be available, and is fastest (though it tears). + // If not, fall back to FIFO which is always available. VkPresentModeKHR swapchainPresentMode = VK_PRESENT_MODE_FIFO_KHR; for (size_t i = 0; i < presentModeCount; i++) { if ((flags_ & VULKAN_FLAG_PRESENT_MAILBOX) && presentModes[i] == VK_PRESENT_MODE_MAILBOX_KHR) { swapchainPresentMode = VK_PRESENT_MODE_MAILBOX_KHR; break; } + if ((flags_ & VULKAN_FLAG_PRESENT_FIFO_RELAXED) && presentModes[i] == VK_PRESENT_MODE_FIFO_RELAXED_KHR) { + swapchainPresentMode = VK_PRESENT_MODE_FIFO_RELAXED_KHR; + break; + } if ((flags_ & VULKAN_FLAG_PRESENT_IMMEDIATE) && presentModes[i] == VK_PRESENT_MODE_IMMEDIATE_KHR) { swapchainPresentMode = VK_PRESENT_MODE_IMMEDIATE_KHR; break; diff --git a/ext/native/thin3d/VulkanContext.h b/ext/native/thin3d/VulkanContext.h index df3fc7d4a7..e6f9993c65 100644 --- a/ext/native/thin3d/VulkanContext.h +++ b/ext/native/thin3d/VulkanContext.h @@ -57,6 +57,7 @@ enum { VULKAN_FLAG_VALIDATE = 1, VULKAN_FLAG_PRESENT_MAILBOX = 2, VULKAN_FLAG_PRESENT_IMMEDIATE = 4, + VULKAN_FLAG_PRESENT_FIFO_RELAXED = 8, }; // A layer can expose extensions, keep track of those extensions here. From 668830365d940aa3a8fd7fd474a99c78c55cb2a8 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Fri, 8 Jan 2016 01:05:52 +0100 Subject: [PATCH 023/116] Begin/End frame fixes --- GPU/Vulkan/GPU_Vulkan.cpp | 69 ++++++++++++++++++++------------------- GPU/Vulkan/GPU_Vulkan.h | 4 +++ 2 files changed, 40 insertions(+), 33 deletions(-) diff --git a/GPU/Vulkan/GPU_Vulkan.cpp b/GPU/Vulkan/GPU_Vulkan.cpp index d9d4d116dd..eb196c53cc 100644 --- a/GPU/Vulkan/GPU_Vulkan.cpp +++ b/GPU/Vulkan/GPU_Vulkan.cpp @@ -475,6 +475,42 @@ void GPU_Vulkan::CheckGPUFeatures() { } } +void GPU_Vulkan::BeginHostFrame() { + if (g_Config.iRenderingMode == FB_NON_BUFFERED_MODE) { + // Draw everything directly to the backbuffer. + drawEngine_.SetCmdBuffer(vulkan_->GetSurfaceCommandBuffer()); + } + drawEngine_.BeginFrame(); + + if (resized_) { + CheckGPUFeatures(); + UpdateCmdInfo(); + drawEngine_.Resized(); + } + resized_ = false; + + textureCache_.StartFrame(); + depalShaderCache_.Decimate(); + + if (dumpNextFrame_) { + NOTICE_LOG(G3D, "DUMPING THIS FRAME"); + dumpThisFrame_ = true; + dumpNextFrame_ = false; + } else if (dumpThisFrame_) { + dumpThisFrame_ = false; + } + shaderManager_->DirtyShader(); + + // Not sure if this is really needed. + shaderManager_->DirtyUniform(DIRTY_ALL); + + framebufferManager_.BeginFrame(); +} + +void GPU_Vulkan::EndHostFrame() { + drawEngine_.EndFrame(); + framebufferManager_.EndFrame(); +} // Needs to be called on GPU thread, not reporting thread. // TODO @@ -554,36 +590,6 @@ void GPU_Vulkan::ReapplyGfxStateInternal() { } void GPU_Vulkan::BeginFrameInternal() { - if (resized_) { - CheckGPUFeatures(); - UpdateCmdInfo(); - drawEngine_.Resized(); - } - UpdateVsyncInterval(resized_); - resized_ = false; - - textureCache_.StartFrame(); - depalShaderCache_.Decimate(); - - if (dumpNextFrame_) { - NOTICE_LOG(G3D, "DUMPING THIS FRAME"); - dumpThisFrame_ = true; - dumpNextFrame_ = false; - } else if (dumpThisFrame_) { - dumpThisFrame_ = false; - } - shaderManager_->DirtyShader(); - - // Not sure if this is really needed. - shaderManager_->DirtyUniform(DIRTY_ALL); - - framebufferManager_.BeginFrame(); - drawEngine_.BeginFrame(); - - if (g_Config.iRenderingMode == FB_NON_BUFFERED_MODE) { - // Draw everything directly to the backbuffer. - drawEngine_.SetCmdBuffer(vulkan_->GetSurfaceCommandBuffer()); - } } void GPU_Vulkan::SetDisplayFramebuffer(u32 framebuf, u32 stride, GEBufferFormat format) { @@ -628,13 +634,10 @@ void GPU_Vulkan::CopyDisplayToOutput() { void GPU_Vulkan::CopyDisplayToOutputInternal() { // Flush anything left over. drawEngine_.Flush(curCmd_); - drawEngine_.EndFrame(); shaderManager_->DirtyLastShader(); framebufferManager_.CopyDisplayToOutput(); - framebufferManager_.EndFrame(); - gstate_c.textureChanged = TEXCHANGE_UPDATED; } diff --git a/GPU/Vulkan/GPU_Vulkan.h b/GPU/Vulkan/GPU_Vulkan.h index e292a567b7..c88f9931d2 100644 --- a/GPU/Vulkan/GPU_Vulkan.h +++ b/GPU/Vulkan/GPU_Vulkan.h @@ -38,6 +38,10 @@ public: // This gets called on startup and when we get back from settings. void CheckGPUFeatures(); + // These are where we can reset command buffers etc. + void BeginHostFrame(); + void EndHostFrame(); + void InitClear() override; void Reinitialize() override; void PreExecuteOp(u32 op, u32 diff) override; From 28ae840abe020fbe2311034f146866d727ce2b6c Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sat, 9 Jan 2016 01:23:32 +0100 Subject: [PATCH 024/116] Pipelines, samplers, description sets, oh my --- GPU/Common/TextureCacheCommon.h | 2 +- GPU/GLES/StateMapping.cpp | 2 +- GPU/GPU.vcxproj | 1 + GPU/GPU.vcxproj.filters | 1 + GPU/Vulkan/DrawEngineVulkan.cpp | 102 +++++++++++-- GPU/Vulkan/DrawEngineVulkan.h | 6 +- GPU/Vulkan/GPU_Vulkan.cpp | 4 +- GPU/Vulkan/PipelineManagerVulkan.cpp | 81 ++++++++--- GPU/Vulkan/PipelineManagerVulkan.h | 56 ++------ GPU/Vulkan/ShaderManagerVulkan.cpp | 160 +++++++++++---------- GPU/Vulkan/ShaderManagerVulkan.h | 56 +++++--- GPU/Vulkan/StateMappingVulkan.cpp | 11 -- GPU/Vulkan/StateMappingVulkan.h | 62 ++++++++ GPU/Vulkan/TextureCacheVulkan.cpp | 57 +++++--- GPU/Vulkan/TextureCacheVulkan.h | 29 +++- GPU/Vulkan/VertexShaderGeneratorVulkan.cpp | 19 +-- ext/native/thin3d/VulkanContext.cpp | 2 +- ext/native/thin3d/VulkanContext.h | 13 +- ext/native/thin3d/vulkan_utils.h | 9 +- 19 files changed, 451 insertions(+), 222 deletions(-) create mode 100644 GPU/Vulkan/StateMappingVulkan.h diff --git a/GPU/Common/TextureCacheCommon.h b/GPU/Common/TextureCacheCommon.h index c5da7b3af3..9b24211d9e 100644 --- a/GPU/Common/TextureCacheCommon.h +++ b/GPU/Common/TextureCacheCommon.h @@ -107,7 +107,7 @@ public: u16 maxSeenV; // Cache the current filter settings so we can avoid setting it again. - // (OpenGL madness where filter settings are attached to each texture). + // (OpenGL madness where filter settings are attached to each texture. Unused in Vulkan). u8 magFilt; u8 minFilt; bool sClamp; diff --git a/GPU/GLES/StateMapping.cpp b/GPU/GLES/StateMapping.cpp index e693bd3768..1993d88d60 100644 --- a/GPU/GLES/StateMapping.cpp +++ b/GPU/GLES/StateMapping.cpp @@ -152,7 +152,7 @@ inline void TransformDrawEngine::ResetShaderBlending() { } void TransformDrawEngine::ApplyDrawState(int prim) { - // TODO: All this setup is soon so expensive that we'll need dirty flags, or simply do it in the command writes where we detect dirty by xoring. Silly to do all this work on every drawcall. + // TODO: All this setup is so expensive that we'll need dirty flags, or simply do it in the command writes where we detect dirty by xoring. Silly to do all this work on every drawcall. if (gstate_c.textureChanged != TEXCHANGE_UNCHANGED && !gstate.isModeClear() && gstate.isTextureMapEnabled()) { textureCache_->SetTexture(); diff --git a/GPU/GPU.vcxproj b/GPU/GPU.vcxproj index 2cbf6a85d7..1f21022378 100644 --- a/GPU/GPU.vcxproj +++ b/GPU/GPU.vcxproj @@ -251,6 +251,7 @@ + diff --git a/GPU/GPU.vcxproj.filters b/GPU/GPU.vcxproj.filters index 7b13b92862..771443b91c 100644 --- a/GPU/GPU.vcxproj.filters +++ b/GPU/GPU.vcxproj.filters @@ -212,6 +212,7 @@ + diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index 56298b7a04..b7b5c59b15 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -164,7 +164,17 @@ DrawEngineVulkan::DrawEngineVulkan(VulkanContext *vulkan) pl.setLayoutCount = 1; pl.pSetLayouts = &descriptorSetLayout_; res = vkCreatePipelineLayout(device, &pl, nullptr, &pipelineLayout_); + assert(VK_SUCCESS == res); + VkSamplerCreateInfo samp = {}; + samp.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; + samp.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; + samp.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; + samp.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; + samp.flags = 0; + samp.magFilter = VK_FILTER_LINEAR; + samp.minFilter = VK_FILTER_LINEAR; + res = vkCreateSampler(device, &samp, nullptr, &depalSampler_); assert(VK_SUCCESS == res); } @@ -192,6 +202,7 @@ DrawEngineVulkan::~DrawEngineVulkan() { vulkan_->QueueDelete(frame_[i].descPool); delete frame_[i].pushData; } + vulkan_->QueueDelete(depalSampler_); } VertexDecoder *DrawEngineVulkan::GetVertexDecoder(u32 vtype) { @@ -366,24 +377,48 @@ inline u32 ComputeMiniHashRange(const void *ptr, size_t sz) { } } -VkDescriptorSet DrawEngineVulkan::GetDescriptorSet(CachedTextureVulkan *texture) { +VkDescriptorSet DrawEngineVulkan::GetDescriptorSet(CachedTextureVulkan *texture, VkSampler sampler) { DescriptorSetKey key; key.texture_ = texture; + key.sampler_ = sampler; key.secondaryTexture_ = nullptr; + FrameData *frame = &frame_[curFrame_ & 1]; + auto iter = frame->descSets.find(key); + if (iter != frame->descSets.end()) { + return iter->second; + } + + // Didn't find one in the frame cache, let's make a new one. + + VkDescriptorSet desc; + // We just don't write to the slots we don't care about. + VkWriteDescriptorSet writes[2]; + memset(writes, 0, sizeof(writes)); + // Main texture + VkDescriptorImageInfo tex; + + // tex.imageView = texture->imageView; + tex.sampler = sampler; + writes[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + writes[0].dstBinding = 0; + writes[0].pImageInfo = &tex; + + vkUpdateDescriptorSets(vulkan_->GetDevice(), 2, writes, 0, nullptr); + + frame->descSets[key] = desc; return nullptr; } -// The inline wrapper in the header checks for numDrawCalls == 0 +// The inline wrapper in the header checks for numDrawCalls == 0d void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { gpuStats.numFlushes++; FrameData *frame = &frame_[curFrame_ & 1]; - CachedTextureVulkan *tex = nullptr; - // This is not done on every drawcall, we should collect vertex data - // until critical state changes. That's when we draw (flush). - VkDescriptorSet ds = GetDescriptorSet(tex); +// CachedTextureVulkan *tex = textureCache_->ApplyTexture(); +// VkDescriptorSet ds = GetDescriptorSet(tex); + VkDescriptorSet ds; GEPrimitiveType prim = prevPrim_; // ApplyDrawState(prim); @@ -422,6 +457,29 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { gstate_c.vertexFullAlpha = gstate_c.vertexFullAlpha && ((hasColor && (gstate.materialupdate & 1)) || gstate.getMaterialAmbientA() == 255) && (!gstate.isLightingEnabled() || gstate.getAmbientA() == 255); } + VulkanPipelineRasterStateKey pipelineKey; + VulkanDynamicState dynState; + ConvertStateToVulkanKey(*framebufferManager_, prim, pipelineKey, dynState); + // TODO: Dirty-flag these. + vkCmdSetScissor(cmd_, 0, 1, &dynState.scissor); + vkCmdSetViewport(cmd_, 0, 1, &dynState.viewport); + vkCmdSetStencilReference(cmd_, VK_STENCIL_FRONT_AND_BACK, dynState.stencilRef); + vkCmdSetStencilWriteMask(cmd_, VK_STENCIL_FRONT_AND_BACK, dynState.stencilWriteMask); + vkCmdSetStencilCompareMask(cmd_, VK_STENCIL_FRONT_AND_BACK, dynState.stencilCompareMask); + // vkCmdSetBlendConstants(cmd_, dynState.blendColor); + VulkanPipeline *pipeline = pipelineManager_->GetOrCreatePipeline(pipelineLayout_, pipelineKey, dec_, vshader->GetModule(), fshader->GetModule(), true); + vkCmdBindPipeline(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline->pipeline); // TODO: Avoid if same as last draw. + + if (pipeline->uniformBlocks & UB_VS_FS_BASE) { + baseUBOOffset = shaderManager_->PushBaseBuffer(frame->pushData); + } + if (pipeline->uniformBlocks & UB_VS_LIGHTS) { + lightUBOOffset = shaderManager_->PushLightBuffer(frame->pushData); + } + if (pipeline->uniformBlocks & UB_VS_BONES) { + boneUBOOffset = shaderManager_->PushBoneBuffer(frame->pushData); + } + VkBuffer buf[1] = {frame->pushData->GetVkBuffer()}; uint32_t dynamicUBOOffsets[3] = { baseUBOOffset, lightUBOOffset, boneUBOOffset, @@ -433,7 +491,8 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { VkDeviceSize offsets[1] = { vbOffset }; if (useElements) { - // TODO: Avoid rebinding if the vertex size stays the same by using the offset arguments + // TODO: Avoid rebinding vertex/index buffers if the vertex size stays the same by using the offset arguments + // Might want to separate vertices out into a different push buffer in that case. vkCmdBindVertexBuffers(cmd_, 0, 1, buf, offsets); vkCmdBindIndexBuffer(cmd_, buf[0], ibOffset, VK_INDEX_TYPE_UINT16); vkCmdDrawIndexed(cmd_, maxIndex + 1, 1, 0, 0, 0); @@ -470,14 +529,37 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { dec_->VertexType(), inds, GE_VTYPE_IDX_16BIT, dec_->GetDecVtxFmt(), maxIndex, framebufferManager_, textureCache_, transformed, transformedExpanded, drawBuffer, numTrans, drawIndexed, &result, 1.0f); - // ApplyDrawStateLate(); - if (result.action == SW_DRAW_PRIMITIVES) { + VulkanPipelineRasterStateKey pipelineKey; + VulkanDynamicState dynState; + ConvertStateToVulkanKey(*framebufferManager_, prim, pipelineKey, dynState); + // TODO: Dirty-flag these. + vkCmdSetScissor(cmd_, 0, 1, &dynState.scissor); + vkCmdSetViewport(cmd_, 0, 1, &dynState.viewport); + if (dynState.useStencil) { + vkCmdSetStencilWriteMask(cmd_, VK_STENCIL_FRONT_AND_BACK, dynState.stencilWriteMask); + vkCmdSetStencilCompareMask(cmd_, VK_STENCIL_FRONT_AND_BACK, dynState.stencilCompareMask); + } if (result.setStencil) { // hey, dynamic state! vkCmdSetStencilReference(cmd_, VK_STENCIL_FRONT_AND_BACK, result.stencilValue); + } else if (dynState.useStencil) { + vkCmdSetStencilReference(cmd_, VK_STENCIL_FRONT_AND_BACK, dynState.stencilRef); } + // vkCmdSetBlendConstants(cmd_, dynState.blendColor); + VulkanPipeline *pipeline = pipelineManager_->GetOrCreatePipeline(pipelineLayout_, pipelineKey, dec_, vshader->GetModule(), fshader->GetModule(), false); + vkCmdBindPipeline(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline->pipeline); // TODO: Avoid if same as last draw. + + if (pipeline->uniformBlocks & UB_VS_FS_BASE) { + baseUBOOffset = shaderManager_->PushBaseBuffer(frame->pushData); + } + + uint32_t dynamicUBOOffsets[3] = { + baseUBOOffset, lightUBOOffset, boneUBOOffset, + }; + vkCmdBindDescriptorSets(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout_, 0, 1, &ds, 3, dynamicUBOOffsets); + ibOffset = (uint32_t)frame->pushData->Push(decIndex, 2 * indexGen.VertexCount()); vbOffset = (uint32_t)frame->pushData->Push(decoded, numTrans * dec_->GetDecVtxFmt().stride); @@ -489,12 +571,10 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { vkCmdBindVertexBuffers(cmd_, 0, 1, buf, offsets); vkCmdBindIndexBuffer(cmd_, buf[0], ibOffset, VK_INDEX_TYPE_UINT16); vkCmdDrawIndexed(cmd_, numTrans, 1, 0, 0, 0); - // pD3Ddevice->DrawIndexedPrimitiveUP(glprim[prim], 0, maxIndex, D3DPrimCount(glprim[prim], numTrans), inds, D3DFMT_INDEX16, drawBuffer, sizeof(TransformedVertex)); } else { // TODO: Avoid rebinding if the vertex size stays the same by using the offset arguments vkCmdBindVertexBuffers(cmd_, 0, 1, buf, offsets); vkCmdDraw(cmd_, numTrans, 1, 0, 0); - // pD3Ddevice->DrawPrimitiveUP(glprim[prim], D3DPrimCount(glprim[prim], numTrans), drawBuffer, sizeof(TransformedVertex)); } } else if (result.action == SW_CLEAR) { // TODO: Support clearing only color and not alpha, or vice versa. This is not supported (probably for good reason) by vkCmdClearColorAttachment diff --git a/GPU/Vulkan/DrawEngineVulkan.h b/GPU/Vulkan/DrawEngineVulkan.h index b14bd52477..e51c141842 100644 --- a/GPU/Vulkan/DrawEngineVulkan.h +++ b/GPU/Vulkan/DrawEngineVulkan.h @@ -149,7 +149,7 @@ private: void DecodeVertsStep(); void DoFlush(VkCommandBuffer cmd); - VkDescriptorSet GetDescriptorSet(CachedTextureVulkan *texture); + VkDescriptorSet GetDescriptorSet(CachedTextureVulkan *texture, VkSampler sampler); VertexDecoder *GetVertexDecoder(u32 vtype); @@ -162,9 +162,11 @@ private: struct DescriptorSetKey { void *texture_; void *secondaryTexture_; + VkSampler sampler_; bool operator < (const DescriptorSetKey &other) const { if (texture_ < other.texture_) return true; else if (texture_ > other.texture_) return false; + if (sampler_ < other.sampler_) return true; else if (sampler_ > other.sampler_) return false; if (secondaryTexture_ < other.secondaryTexture_) return true; else if (secondaryTexture_ > other.secondaryTexture_) return false; return false; } @@ -215,6 +217,8 @@ private: TextureCacheVulkan *textureCache_; FramebufferManagerVulkan *framebufferManager_; + VkSampler depalSampler_; + enum { MAX_DEFERRED_DRAW_CALLS = 128 }; DeferredDrawCall drawCalls[MAX_DEFERRED_DRAW_CALLS]; diff --git a/GPU/Vulkan/GPU_Vulkan.cpp b/GPU/Vulkan/GPU_Vulkan.cpp index eb196c53cc..c49fa09d5d 100644 --- a/GPU/Vulkan/GPU_Vulkan.cpp +++ b/GPU/Vulkan/GPU_Vulkan.cpp @@ -401,9 +401,11 @@ GPU_Vulkan::GPU_Vulkan(GraphicsContext *ctx) CheckGPUFeatures(); shaderManager_ = new ShaderManagerVulkan(vulkan_); - drawEngine_.SetShaderManager(shaderManager_); + pipelineManager_ = new PipelineManagerVulkan(vulkan_); drawEngine_.SetTextureCache(&textureCache_); drawEngine_.SetFramebufferManager(&framebufferManager_); + drawEngine_.SetShaderManager(shaderManager_); + drawEngine_.SetPipelineManager(pipelineManager_); framebufferManager_.Init(); framebufferManager_.SetTextureCache(&textureCache_); framebufferManager_.SetDrawEngine(&drawEngine_); diff --git a/GPU/Vulkan/PipelineManagerVulkan.cpp b/GPU/Vulkan/PipelineManagerVulkan.cpp index 58920f4fcc..9b77ac4b86 100644 --- a/GPU/Vulkan/PipelineManagerVulkan.cpp +++ b/GPU/Vulkan/PipelineManagerVulkan.cpp @@ -3,6 +3,7 @@ #include "Common/Log.h" #include "GPU/Vulkan/VulkanUtil.h" #include "GPU/Vulkan/PipelineManagerVulkan.h" +// #include "GPU/Vulkan/" #include "thin3d/VulkanContext.h" PipelineManagerVulkan::PipelineManagerVulkan(VulkanContext *vulkan) : vulkan_(vulkan) { @@ -10,7 +11,14 @@ PipelineManagerVulkan::PipelineManagerVulkan(VulkanContext *vulkan) : vulkan_(vu } PipelineManagerVulkan::~PipelineManagerVulkan() { + // This should kill off all the shaders at once. + // This could also be an opportunity to store the whole cache to disk. Will need to also + // store the keys. vkDestroyPipelineCache(vulkan_->GetDevice(), pipelineCache_, nullptr); + for (auto iter : pipelines_) { + delete iter.second; + } + pipelines_.clear(); } struct DeclTypeInfo { @@ -84,45 +92,47 @@ int SetupVertexAttribsPretransformed(VkVertexInputAttributeDescription attrs[]) return 4; } -static VulkanPipeline *CreateVulkanPipeline(VkDevice device, VkPipelineCache pipelineCache, const VulkanPipelineRasterStateKey &key, const DecVtxFormat &vfmt, VkShaderModule vshader, VkShaderModule fshader, bool useHwTransform) { +static VulkanPipeline *CreateVulkanPipeline(VkDevice device, VkPipelineCache pipelineCache, VkPipelineLayout layout, VkRenderPass renderPass, const VulkanPipelineRasterStateKey &key, const VertexDecoder *vtxDec, VkShaderModule vshader, VkShaderModule fshader, bool useHwTransform) { VkPipelineColorBlendAttachmentState blend0; blend0.blendEnable = key.blendEnable; if (key.blendEnable) { - blend0.colorBlendOp = key.blendOpColor; - blend0.alphaBlendOp = key.blendOpAlpha; - blend0.srcColorBlendFactor = key.srcColor; - blend0.srcAlphaBlendFactor = key.srcAlpha; - blend0.dstColorBlendFactor = key.destColor; - blend0.dstAlphaBlendFactor = key.destAlpha; + blend0.colorBlendOp = (VkBlendOp)key.blendOpColor; + blend0.alphaBlendOp = (VkBlendOp)key.blendOpAlpha; + blend0.srcColorBlendFactor = (VkBlendFactor)key.srcColor; + blend0.srcAlphaBlendFactor = (VkBlendFactor)key.srcAlpha; + blend0.dstColorBlendFactor = (VkBlendFactor)key.destColor; + blend0.dstAlphaBlendFactor = (VkBlendFactor)key.destAlpha; } blend0.colorWriteMask = key.colorWriteMask; VkPipelineColorBlendStateCreateInfo cbs; cbs.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; cbs.pNext = nullptr; + cbs.flags = 0; cbs.pAttachments = &blend0; cbs.attachmentCount = 1; cbs.logicOpEnable = key.logicOpEnable; if (key.logicOpEnable) - cbs.logicOp = key.logicOp; + cbs.logicOp = (VkLogicOp)key.logicOp; else cbs.logicOp = VK_LOGIC_OP_COPY; - VkPipelineDepthStencilStateCreateInfo dss; + VkPipelineDepthStencilStateCreateInfo dss = { }; dss.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; + dss.pNext = nullptr; dss.depthBoundsTestEnable = false; dss.stencilTestEnable = key.stencilTestEnable; if (key.stencilTestEnable) { - dss.front.compareOp = key.stencilCompareOp; - dss.front.passOp = key.stencilPassOp; - dss.front.failOp = key.stencilFailOp; - dss.front.depthFailOp = key.stencilDepthFailOp; + dss.front.compareOp = (VkCompareOp)key.stencilCompareOp; + dss.front.passOp = (VkStencilOp)key.stencilPassOp; + dss.front.failOp = (VkStencilOp)key.stencilFailOp; + dss.front.depthFailOp = (VkStencilOp)key.stencilDepthFailOp; // Back stencil is always the same as front on PSP. memcpy(&dss.back, &dss.front, sizeof(dss.front)); } dss.depthTestEnable = key.depthTestEnable; if (key.depthTestEnable) { - dss.depthCompareOp = key.depthCompareOp; + dss.depthCompareOp = (VkCompareOp)key.depthCompareOp; dss.depthWriteEnable = key.depthWriteEnable; } @@ -142,12 +152,14 @@ static VulkanPipeline *CreateVulkanPipeline(VkDevice device, VkPipelineCache pip VkPipelineDynamicStateCreateInfo ds; ds.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; ds.pNext = nullptr; + ds.flags = 0; ds.pDynamicStates = dynamicStates; ds.dynamicStateCount = numDyn; VkPipelineRasterizationStateCreateInfo rs; rs.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; rs.pNext = nullptr; + rs.flags = 0; rs.depthBiasEnable = false; rs.cullMode = key.cullMode; rs.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; @@ -164,14 +176,14 @@ static VulkanPipeline *CreateVulkanPipeline(VkDevice device, VkPipelineCache pip ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; VkPipelineShaderStageCreateInfo ss[2]; - ss[0].sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; + ss[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; ss[0].pNext = nullptr; ss[0].stage = VK_SHADER_STAGE_VERTEX_BIT; ss[0].pSpecializationInfo = nullptr; ss[0].module = vshader; ss[0].pName = "main"; ss[0].flags = 0; - ss[1].sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; + ss[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; ss[1].pNext = nullptr; ss[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; ss[1].pSpecializationInfo = nullptr; @@ -182,7 +194,8 @@ static VulkanPipeline *CreateVulkanPipeline(VkDevice device, VkPipelineCache pip VkPipelineInputAssemblyStateCreateInfo inputAssembly; inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; inputAssembly.pNext = nullptr; - inputAssembly.topology = key.topology; + inputAssembly.flags = 0; + inputAssembly.topology = (VkPrimitiveTopology)key.topology; inputAssembly.primitiveRestartEnable = false; int vertexStride = 0; @@ -191,9 +204,11 @@ static VulkanPipeline *CreateVulkanPipeline(VkDevice device, VkPipelineCache pip VkVertexInputAttributeDescription attrs[8]; int attributeCount; if (useHwTransform) { - attributeCount = SetupVertexAttribs(attrs, vfmt); + attributeCount = SetupVertexAttribs(attrs, vtxDec->decFmt); + vertexStride = vtxDec->decFmt.stride; } else { attributeCount = SetupVertexAttribsPretransformed(attrs); + vertexStride = 36; } VkVertexInputBindingDescription ibd; @@ -204,6 +219,7 @@ static VulkanPipeline *CreateVulkanPipeline(VkDevice device, VkPipelineCache pip VkPipelineVertexInputStateCreateInfo vis; vis.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; vis.pNext = nullptr; + vis.flags = 0; vis.vertexBindingDescriptionCount = 1; vis.pVertexBindingDescriptions = &ibd; vis.vertexAttributeDescriptionCount = attributeCount; @@ -212,6 +228,7 @@ static VulkanPipeline *CreateVulkanPipeline(VkDevice device, VkPipelineCache pip VkPipelineViewportStateCreateInfo vs; vs.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; vs.pNext = nullptr; + vs.flags = 0; vs.viewportCount = 1; vs.scissorCount = 1; vs.pViewports = nullptr; // dynamic @@ -220,6 +237,7 @@ static VulkanPipeline *CreateVulkanPipeline(VkDevice device, VkPipelineCache pip VkGraphicsPipelineCreateInfo pipe; pipe.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; pipe.pNext = nullptr; + pipe.flags = 0; pipe.stageCount = 2; pipe.pStages = ss; pipe.basePipelineIndex = 0; @@ -233,10 +251,17 @@ static VulkanPipeline *CreateVulkanPipeline(VkDevice device, VkPipelineCache pip pipe.pRasterizationState = &rs; // We will use dynamic viewport state. + pipe.pVertexInputState = &vis; pipe.pViewportState = &vs; + pipe.pTessellationState = nullptr; pipe.pDynamicState = &ds; pipe.pInputAssemblyState = &inputAssembly; pipe.pMultisampleState = &ms; + pipe.layout = layout; + pipe.basePipelineHandle = nullptr; + pipe.basePipelineIndex = 0; + pipe.renderPass = renderPass; + pipe.subpass = 0; VkPipeline pipeline; VkResult result = vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipe, nullptr, &pipeline); @@ -247,5 +272,25 @@ static VulkanPipeline *CreateVulkanPipeline(VkDevice device, VkPipelineCache pip VulkanPipeline *vulkanPipeline = new VulkanPipeline(); vulkanPipeline->pipeline = pipeline; + vulkanPipeline->uniformBlocks = UB_VS_FS_BASE; + if (useHwTransform) { + // TODO: Remove BONES and LIGHTS when those aren't used. + vulkanPipeline->uniformBlocks |= UB_VS_BONES | UB_VS_LIGHTS; + } return vulkanPipeline; } + +VulkanPipeline *PipelineManagerVulkan::GetOrCreatePipeline(VkPipelineLayout layout, const VulkanPipelineRasterStateKey &rasterKey, const VertexDecoder *vtxDec, VkShaderModule vShader, VkShaderModule fShader, bool useHwTransform) { + VulkanPipelineKey key; + key.raster = rasterKey; + auto iter = pipelines_.find(key); + if (iter != pipelines_.end()) { + return iter->second; + } + + VulkanPipeline *pipeline = CreateVulkanPipeline( + vulkan_->GetDevice(), pipelineCache_, layout, vulkan_->GetSurfaceRenderPass(), + rasterKey, vtxDec, vShader, fShader, useHwTransform); + pipelines_[key] = pipeline; + return pipeline; +} diff --git a/GPU/Vulkan/PipelineManagerVulkan.h b/GPU/Vulkan/PipelineManagerVulkan.h index 0f0ed070c1..0805425fb2 100644 --- a/GPU/Vulkan/PipelineManagerVulkan.h +++ b/GPU/Vulkan/PipelineManagerVulkan.h @@ -22,6 +22,7 @@ #include "GPU/Common/VertexDecoderCommon.h" #include "GPU/Common/ShaderId.h" #include "GPU/Vulkan/VulkanUtil.h" +#include "GPU/Vulkan/StateMappingVulkan.h" // PSP vertex format. enum class PspAttributeLocation { @@ -36,67 +37,29 @@ enum class PspAttributeLocation { COUNT }; -// Let's pack this tight using bitfields. -// If an enable flag is set to 0, all the data fields for that section should -// also be set to 0. -// ~54 bits. -struct VulkanPipelineRasterStateKey { - // Blend - bool blendEnable : 1; - VkBlendFactor srcColor : 5; - VkBlendFactor destColor : 5; - VkBlendFactor srcAlpha : 5; - VkBlendFactor destAlpha : 5; - VkBlendOp blendOpColor : 3; - VkBlendOp blendOpAlpha : 3; - bool logicOpEnable : 1; - VkLogicOp logicOp : 4; - int colorWriteMask : 4; - - // Depth/Stencil - bool depthTestEnable : 1; - bool depthWriteEnable : 1; - VkCompareOp depthCompareOp : 3; - bool stencilTestEnable : 1; - VkCompareOp stencilCompareOp : 4; - VkStencilOp stencilPassOp : 4; - VkStencilOp stencilFailOp : 4; - VkStencilOp stencilDepthFailOp : 4; - // We'll use dynamic state for writemask, reference and comparemask to start with, - // and viewport/scissor. - - // Rasterizer - VkCullModeFlagBits cullMode : 2; - VkPrimitiveTopology topology : 4; - - bool operator < (const VulkanPipelineRasterStateKey &other) const { - return memcmp(this, &other, sizeof(*this)) < 0; - } -}; - // All the information needed. All PSP rendering (except full screen clears?) will make use of a single // render pass definition. struct VulkanPipelineKey { VulkanPipelineRasterStateKey raster; int prim; bool pretransformed; - uint32_t vertType; - ShaderID vShaderId; - ShaderID fShaderId; + const VertexDecoder *vtxDec; + VkShaderModule vShader; + VkShaderModule fShader; bool operator < (const VulkanPipelineKey &other) const { if (raster < other.raster) return true; else if (other.raster < raster) return false; if (prim < other.prim) return true; else if (other.prim < prim) return false; if (pretransformed < other.pretransformed) return true; else if (other.pretransformed < pretransformed) return false; - if (vertType < other.vertType) return true; else if (other.vertType < vertType) return false; - if (vShaderId < other.vShaderId) return true; else if (other.vShaderId < vShaderId) return false; - if (fShaderId < other.fShaderId) return true; else if (other.fShaderId < fShaderId) return false; + if (vtxDec < other.vtxDec) return true; else if (other.vtxDec < vtxDec) return false; + if (vShader < other.vShader) return true; else if (other.vShader < vShader) return false; + if (fShader < other.fShader) return true; else if (other.fShader < fShader) return false; return false; } }; enum { - UB_VS_BASICTRANSFORM = (1 << 0), + UB_VS_FS_BASE = (1 << 0), UB_VS_BONES = (1 << 1), UB_VS_LIGHTS = (1 << 2), }; @@ -112,10 +75,11 @@ public: PipelineManagerVulkan(VulkanContext *ctx); ~PipelineManagerVulkan(); + VulkanPipeline *GetOrCreatePipeline(VkPipelineLayout layout, const VulkanPipelineRasterStateKey &rasterKey, const VertexDecoder *vtxDec, VkShaderModule vShader, VkShaderModule fShader, bool useHwTransform); int GetNumPipelines() const { return 0; } private: - std::map pipelines_; + std::map pipelines_; VkPipelineCache pipelineCache_; VulkanContext *vulkan_; }; diff --git a/GPU/Vulkan/ShaderManagerVulkan.cpp b/GPU/Vulkan/ShaderManagerVulkan.cpp index 24fc019713..4b1de3306f 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.cpp +++ b/GPU/Vulkan/ShaderManagerVulkan.cpp @@ -47,6 +47,9 @@ VulkanFragmentShader::VulkanFragmentShader(VulkanContext *vulkan, ShaderID id, c std::string errorMessage; std::vector spirv; +#ifdef SHADERLOG + OutputDebugStringA(code); +#endif bool success = GLSLtoSPV(VK_SHADER_STAGE_FRAGMENT_BIT, code, spirv, &errorMessage); if (!errorMessage.empty()) { @@ -64,7 +67,6 @@ VulkanFragmentShader::VulkanFragmentShader(VulkanContext *vulkan, ShaderID id, c } else { success = vulkan_->CreateShaderModule(spirv, &module_); #ifdef SHADERLOG - OutputDebugStringA(code); OutputDebugStringA("OK"); #endif } @@ -97,11 +99,11 @@ std::string VulkanFragmentShader::GetShaderString(DebugShaderStringType type) co VulkanVertexShader::VulkanVertexShader(VulkanContext *vulkan, ShaderID id, const char *code, int vertType, bool useHWTransform) : vulkan_(vulkan), id_(id), failed_(false), useHWTransform_(useHWTransform), module_(nullptr) { source_ = code; -#ifdef SHADERLOG - OutputDebugString(ConvertUTF8ToWString(code).c_str()); -#endif std::string errorMessage; std::vector spirv; +#ifdef SHADERLOG + OutputDebugStringA(code); +#endif bool success = GLSLtoSPV(VK_SHADER_STAGE_VERTEX_BIT, code, spirv, &errorMessage); if (!errorMessage.empty()) { if (success) { @@ -116,6 +118,9 @@ VulkanVertexShader::VulkanVertexShader(VulkanContext *vulkan, ShaderID id, const Reporting::ReportMessage("Vulkan error in shader compilation: info: %s / code: %s", errorMessage.c_str(), code); } else { success = vulkan_->CreateShaderModule(spirv, &module_); +#ifdef SHADERLOG + OutputDebugStringA("OK"); +#endif } if (!success) { @@ -165,7 +170,37 @@ static void ConvertProjMatrixToVulkanThrough(Matrix4x4 &in) { in.translateAndScale(Vec3(0.0f, 0.0f, 0.5f), Vec3(1.0f, 1.0f, 0.5f)); } -void ShaderManagerVulkan::PSUpdateUniforms(int dirtyUniforms) { + +ShaderManagerVulkan::ShaderManagerVulkan(VulkanContext *vulkan) + : vulkan_(vulkan), lastVShader_(nullptr), lastFShader_(nullptr), globalDirty_(0xFFFFFFFF) { + codeBuffer_ = new char[16384]; + uboAlignment_ = vulkan_->GetPhysicalDeviceProperties().limits.minUniformBufferOffsetAlignment; +} + +ShaderManagerVulkan::~ShaderManagerVulkan() { + delete[] codeBuffer_; +} + +uint32_t ShaderManagerVulkan::PushBaseBuffer(VulkanPushBuffer *dest) { + if (globalDirty_ & DIRTY_BASE_UNIFORMS) + BaseUpdateUniforms(globalDirty_); + return dest->PushAligned(&ub_base, sizeof(ub_base), uboAlignment_); +} + +uint32_t ShaderManagerVulkan::PushLightBuffer(VulkanPushBuffer *dest) { + if (globalDirty_ & DIRTY_BASE_UNIFORMS) + BaseUpdateUniforms(globalDirty_); + return dest->PushAligned(&ub_lights, sizeof(ub_lights), uboAlignment_); +} + +// TODO: Only push half the bone buffer if we only have four bones. +uint32_t ShaderManagerVulkan::PushBoneBuffer(VulkanPushBuffer *dest) { + if (globalDirty_ & DIRTY_BASE_UNIFORMS) + BaseUpdateUniforms(globalDirty_); + return dest->PushAligned(&ub_bones, sizeof(ub_bones), uboAlignment_); +} + +void ShaderManagerVulkan::BaseUpdateUniforms(int dirtyUniforms) { if (dirtyUniforms & DIRTY_TEXENV) { Uint8x3ToFloat4(ub_base.texEnvColor, gstate.texenvcolor); } @@ -207,38 +242,36 @@ void ShaderManagerVulkan::PSUpdateUniforms(int dirtyUniforms) { CopyFloat4(ub_base.texClamp, texclamp); CopyFloat2(ub_base.texClampOffset, texclampoff); } -} -void ShaderManagerVulkan::VSUpdateUniforms(int dirtyUniforms) { // Update any dirty uniforms before we draw if (dirtyUniforms & DIRTY_PROJMATRIX) { - Matrix4x4 flippedMatrix; - memcpy(&flippedMatrix, gstate.projMatrix, 16 * sizeof(float)); + if (gstate.isModeThrough()) { + Matrix4x4 proj_through; + proj_through.setOrtho(0.0f, gstate_c.curRTWidth, gstate_c.curRTHeight, 0, 0, 1); + ConvertProjMatrixToVulkanThrough(proj_through); + CopyMatrix4x4(ub_base.proj, proj_through.getReadPtr()); + } else { + Matrix4x4 flippedMatrix; + memcpy(&flippedMatrix, gstate.projMatrix, 16 * sizeof(float)); - const bool invertedY = gstate_c.vpHeight < 0; - if (!invertedY) { - flippedMatrix[1] = -flippedMatrix[1]; - flippedMatrix[5] = -flippedMatrix[5]; - flippedMatrix[9] = -flippedMatrix[9]; - flippedMatrix[13] = -flippedMatrix[13]; + const bool invertedY = gstate_c.vpHeight < 0; + if (!invertedY) { + flippedMatrix[1] = -flippedMatrix[1]; + flippedMatrix[5] = -flippedMatrix[5]; + flippedMatrix[9] = -flippedMatrix[9]; + flippedMatrix[13] = -flippedMatrix[13]; + } + const bool invertedX = gstate_c.vpWidth < 0; + if (invertedX) { + flippedMatrix[0] = -flippedMatrix[0]; + flippedMatrix[4] = -flippedMatrix[4]; + flippedMatrix[8] = -flippedMatrix[8]; + flippedMatrix[12] = -flippedMatrix[12]; + } + + ConvertProjMatrixToVulkan(flippedMatrix, invertedX, invertedY); + CopyMatrix4x4(ub_base.proj, flippedMatrix.getReadPtr()); } - const bool invertedX = gstate_c.vpWidth < 0; - if (invertedX) { - flippedMatrix[0] = -flippedMatrix[0]; - flippedMatrix[4] = -flippedMatrix[4]; - flippedMatrix[8] = -flippedMatrix[8]; - flippedMatrix[12] = -flippedMatrix[12]; - } - - ConvertProjMatrixToVulkan(flippedMatrix, invertedX, invertedY); - - CopyMatrix4x4(ub_base.proj, flippedMatrix.getReadPtr()); - } - if (dirtyUniforms & DIRTY_PROJTHROUGHMATRIX) { - Matrix4x4 proj_through; - proj_through.setOrtho(0.0f, gstate_c.curRTWidth, gstate_c.curRTHeight, 0, 0, 1); - ConvertProjMatrixToVulkanThrough(proj_through); - CopyMatrix4x4(ub_base.proj, proj_through.getReadPtr()); } // Transform @@ -274,38 +307,6 @@ void ShaderManagerVulkan::VSUpdateUniforms(int dirtyUniforms) { #endif CopyFloat2(ub_base.fogCoef, fogcoef); } - // TODO: Could even set all bones in one go if they're all dirty. -#ifdef USE_BONE_ARRAY - if (u_bone != 0) { - float allBones[8 * 16]; - - bool allDirty = true; - for (int i = 0; i < numBones; i++) { - if (dirtyUniforms & (DIRTY_BONEMATRIX0 << i)) { - ConvertMatrix4x3To4x4(allBones + 16 * i, gstate.boneMatrix + 12 * i); - } else { - allDirty = false; - } - } - if (allDirty) { - // Set them all with one call - //glUniformMatrix4fv(u_bone, numBones, GL_FALSE, allBones); - } else { - // Set them one by one. Could try to coalesce two in a row etc but too lazy. - for (int i = 0; i < numBones; i++) { - if (dirtyUniforms & (DIRTY_BONEMATRIX0 << i)) { - //glUniformMatrix4fv(u_bone + i, 1, GL_FALSE, allBones + 16 * i); - } - } - } - } -#else - for (int i = 0; i < 8; i++) { - if (dirtyUniforms & (DIRTY_BONEMATRIX0 << i)) { - ConvertMatrix4x3To4x4(ub_bones.bones[i], gstate.boneMatrix + 12 * i); - } - } -#endif // Texturing if (dirtyUniforms & DIRTY_UVSCALEOFFSET) { @@ -327,7 +328,7 @@ void ShaderManagerVulkan::VSUpdateUniforms(int dirtyUniforms) { uvscaleoff[3] = gstate_c.uv.vOff * heightFactor; break; - // These two work the same whether or not we prescale UV. + // These two work the same whether or not we prescale UV. case GE_TEXMAP_TEXTURE_MATRIX: // We cannot bake the UV coord scale factor in here, as we apply a matrix multiplication @@ -350,11 +351,11 @@ void ShaderManagerVulkan::VSUpdateUniforms(int dirtyUniforms) { default: ERROR_LOG_REPORT(G3D, "Unexpected UV gen mode: %d", gstate.getUVGenMode()); - } + } CopyFloat4(ub_base.uvScaleOffset, uvscaleoff); } - if (dirtyUniforms & DIRTY_DEPTHRANGE) { + if (dirtyUniforms & DIRTY_DEPTHRANGE) { float viewZScale = gstate.getViewportZScale(); float viewZCenter = gstate.getViewportZCenter(); float viewZInvScale; @@ -382,7 +383,9 @@ void ShaderManagerVulkan::VSUpdateUniforms(int dirtyUniforms) { float data[4] = { viewZScale, viewZCenter, viewZCenter, viewZInvScale }; CopyFloat4(ub_base.depthRange, data); } +} +void ShaderManagerVulkan::LightUpdateUniforms(int dirtyUniforms) { // Lighting if (dirtyUniforms & DIRTY_AMBIENT) { Uint8x3ToFloat4_AlphaUint8(ub_lights.ambientColor, gstate.ambientcolor, gstate.getAmbientA()); @@ -429,13 +432,12 @@ void ShaderManagerVulkan::VSUpdateUniforms(int dirtyUniforms) { } } -ShaderManagerVulkan::ShaderManagerVulkan(VulkanContext *vulkan) - : vulkan_(vulkan), lastVShader_(nullptr), lastFShader_(nullptr), globalDirty_(0xFFFFFFFF) { - codeBuffer_ = new char[16384]; -} - -ShaderManagerVulkan::~ShaderManagerVulkan() { - delete [] codeBuffer_; +void ShaderManagerVulkan::BoneUpdateUniforms(int dirtyUniforms) { + for (int i = 0; i < 8; i++) { + if (dirtyUniforms & (DIRTY_BONEMATRIX0 << i)) { + ConvertMatrix4x3To4x4(ub_bones.bones[i], gstate.boneMatrix + 12 * i); + } + } } void ShaderManagerVulkan::Clear() { @@ -484,8 +486,9 @@ void ShaderManagerVulkan::GetShaders(int prim, u32 vertType, VulkanVertexShader // Just update uniforms if this is the same shader as last time. if (lastVShader_ != nullptr && lastFShader_ != nullptr && VSID == lastVSID_ && FSID == lastFSID_) { if (globalDirty_) { - PSUpdateUniforms(globalDirty_); - VSUpdateUniforms(globalDirty_); + BaseUpdateUniforms(globalDirty_); + LightUpdateUniforms(globalDirty_); + BoneUpdateUniforms(globalDirty_); globalDirty_ = 0; } *vshader = lastVShader_; @@ -520,8 +523,9 @@ void ShaderManagerVulkan::GetShaders(int prim, u32 vertType, VulkanVertexShader lastFSID_ = FSID; if (globalDirty_) { - PSUpdateUniforms(globalDirty_); - VSUpdateUniforms(globalDirty_); + BaseUpdateUniforms(globalDirty_); + LightUpdateUniforms(globalDirty_); + BoneUpdateUniforms(globalDirty_); globalDirty_ = 0; } *vshader = vs; diff --git a/GPU/Vulkan/ShaderManagerVulkan.h b/GPU/Vulkan/ShaderManagerVulkan.h index 5394c761ea..af96ca5b54 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.h +++ b/GPU/Vulkan/ShaderManagerVulkan.h @@ -34,7 +34,6 @@ void ConvertProjMatrixToVulkan(Matrix4x4 & in); // Pretty much full. Will need more bits for more fine grained dirty tracking for lights. enum { DIRTY_PROJMATRIX = (1 << 0), - DIRTY_PROJTHROUGHMATRIX = (1 << 1), DIRTY_FOGCOLOR = (1 << 2), DIRTY_FOGCOEF = (1 << 3), DIRTY_TEXENV = (1 << 4), @@ -70,6 +69,15 @@ enum { DIRTY_BONEMATRIX6 = (1 << 30), DIRTY_BONEMATRIX7 = (1 << 31), + DIRTY_BASE_UNIFORMS = + DIRTY_WORLDMATRIX | DIRTY_VIEWMATRIX | DIRTY_TEXMATRIX | DIRTY_ALPHACOLORREF | + DIRTY_PROJMATRIX | DIRTY_FOGCOLOR | DIRTY_FOGCOEF | DIRTY_TEXENV | DIRTY_STENCILREPLACEVALUE | + DIRTY_ALPHACOLORMASK | DIRTY_SHADERBLEND | DIRTY_UVSCALEOFFSET | DIRTY_TEXCLAMP | DIRTY_DEPTHRANGE | DIRTY_MATAMBIENTALPHA, + DIRTY_LIGHT_UNIFORMS = + DIRTY_LIGHT0 | DIRTY_LIGHT1 | DIRTY_LIGHT2 | DIRTY_LIGHT3 | + DIRTY_MATDIFFUSE | DIRTY_MATSPECULAR | DIRTY_MATEMISSIVE | DIRTY_AMBIENT, + DIRTY_BONE_UNIFORMS = 0xFF000000, + DIRTY_ALL = 0xFFFFFFFF }; @@ -102,7 +110,7 @@ R"( mat4 proj_mtx; vec4 uvScaleOffset; vec4 depthRange; vec2 fogCoef; - vec4 matAmbient; + vec4 matambientalpha; vec3 blendFixA; vec3 blendFixB; vec4 texclamp; @@ -130,18 +138,18 @@ struct UB_VS_Lights { }; static const char *ub_vs_lightsStr = -R"( vec3 ambientColor; - vec3 materialDiffuse; - vec4 materialSpecular; - vec3 materialEmissive; - vec3 lpos[4]; - vec3 ldir[4]; - vec3 latt[4]; - float lightAngle[4]; - float lightSpotCoef[4]; - vec3 lightAmbient[4]; - vec3 lightDiffuse[4]; - vec3 lightSpecular[4]; +R"(vec4 globalAmbient; + vec3 matdiffuse; + vec4 matspecular; + vec3 matemissive; + vec3 pos[4]; + vec3 dir[4]; + vec3 att[4]; + float angle[4]; + float spotCoef[4]; + vec3 ambient[4]; + vec3 diffuse[4]; + vec3 specular[4]; )"; struct UB_VS_Bones { @@ -164,6 +172,7 @@ public: bool UseHWTransform() const { return useHWTransform_; } std::string GetShaderString(DebugShaderStringType type) const; + VkShaderModule GetModule() const { return module_; } protected: VkShaderModule module_; @@ -186,6 +195,7 @@ public: bool UseHWTransform() const { return useHWTransform_; } std::string GetShaderString(DebugShaderStringType type) const; + VkShaderModule GetModule() const { return module_; } protected: VkShaderModule module_; @@ -217,15 +227,27 @@ public: std::vector DebugGetShaderIDs(DebugShaderType type); std::string DebugGetShaderString(std::string id, DebugShaderType type, DebugShaderStringType stringType); + // TODO: Avoid copying these buffers if same as last draw, can still point to it assuming we're still in the same pushbuffer. + // Applies dirty changes and copies the buffer. + bool IsBaseDirty() { return true; } + bool IsLightDirty() { return true; } + bool IsBoneDirty() { return true; } + + uint32_t PushBaseBuffer(VulkanPushBuffer *dest); + uint32_t PushLightBuffer(VulkanPushBuffer *dest); + uint32_t PushBoneBuffer(VulkanPushBuffer *dest); + private: - void PSUpdateUniforms(int dirtyUniforms); - void VSUpdateUniforms(int dirtyUniforms); + void BaseUpdateUniforms(int dirtyUniforms); + void LightUpdateUniforms(int dirtyUniforms); + void BoneUpdateUniforms(int dirtyUniforms); void Clear(); VulkanContext *vulkan_; - u32 globalDirty_; + uint32_t globalDirty_; + uint32_t uboAlignment_; char *codeBuffer_; // Uniform block scratchpad. These (the relevant ones) are copied to the current pushbuffer at draw time. diff --git a/GPU/Vulkan/StateMappingVulkan.cpp b/GPU/Vulkan/StateMappingVulkan.cpp index 5d5960a4ae..18e0a2e14b 100644 --- a/GPU/Vulkan/StateMappingVulkan.cpp +++ b/GPU/Vulkan/StateMappingVulkan.cpp @@ -87,17 +87,6 @@ static const VkStencilOp stencilOps[] = { VK_STENCIL_OP_KEEP, // reserved }; -struct VulkanDynamicState { - VkViewport viewport; - VkRect2D scissor; - bool useBlendColor; - uint32_t blendColor; - bool useStencil; - uint8_t stencilRef; - uint8_t stencilWriteMask; - uint8_t stencilCompareMask; -}; - bool ApplyShaderBlending() { return false; } diff --git a/GPU/Vulkan/StateMappingVulkan.h b/GPU/Vulkan/StateMappingVulkan.h new file mode 100644 index 0000000000..fe0abe9386 --- /dev/null +++ b/GPU/Vulkan/StateMappingVulkan.h @@ -0,0 +1,62 @@ +#pragma once + +#define VK_PROTOTYPES +#include "ext/vulkan/vulkan.h" + +#include + +class FramebufferManagerVulkan; + +struct VulkanDynamicState { + VkViewport viewport; + VkRect2D scissor; + bool useBlendColor; + uint32_t blendColor; + bool useStencil; + uint8_t stencilRef; + uint8_t stencilWriteMask; + uint8_t stencilCompareMask; +}; + +// Let's pack this tight using bitfields. +// If an enable flag is set to 0, all the data fields for that section should +// also be set to 0. +// ~54 bits. +// Can't use enums unfortunately, they end up signed and breaking values above half their ranges. +struct VulkanPipelineRasterStateKey { + // Blend + bool blendEnable : 1; + unsigned int srcColor : 5; // VkBlendFactor + unsigned int destColor : 5; // VkBlendFactor + unsigned int srcAlpha : 5; // VkBlendFactor + unsigned int destAlpha : 5; // VkBlendFactor + unsigned int blendOpColor : 3; // VkBlendOp + unsigned int blendOpAlpha : 3; // VkBlendOp + bool logicOpEnable : 1; + unsigned int logicOp : 4; // VkLogicOp + int colorWriteMask : 4; + + // Depth/Stencil + bool depthTestEnable : 1; + bool depthWriteEnable : 1; + unsigned int depthCompareOp : 3; // VkCompareOp + bool stencilTestEnable : 1; + unsigned int stencilCompareOp : 4; // VkCompareOp + unsigned int stencilPassOp : 4; // VkStencilOp + unsigned int stencilFailOp : 4; //VkStencilOp + unsigned int stencilDepthFailOp : 4; // VkStencilOp + + // We'll use dynamic state for writemask, reference and comparemask to start with, + // and viewport/scissor. + + // Rasterizer + unsigned int cullMode : 2; // VkCullModeFlagBits + unsigned int topology : 4; // VkPrimitiveTopology + + bool operator < (const VulkanPipelineRasterStateKey &other) const { + return memcmp(this, &other, sizeof(*this)) < 0; + } +}; + + +void ConvertStateToVulkanKey(FramebufferManagerVulkan &fbManager, int prim, VulkanPipelineRasterStateKey &key, VulkanDynamicState &dynState); diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index 6c10005fba..14cb54700f 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -74,8 +74,44 @@ public: VkImageView imageView; }; +SamplerCache::~SamplerCache() { + for (auto iter : cache_) { + vulkan_->QueueDelete(iter.second); + } +} -TextureCacheVulkan::TextureCacheVulkan(VulkanContext *vulkan) : vulkan_(vulkan), cacheSizeEstimate_(0), secondCacheSizeEstimate_(0), clearCacheNextFrame_(false), lowMemoryMode_(false), clutBuf_(NULL), texelsScaledThisFrame_(0) { +VkSampler SamplerCache::GetOrCreateSampler(const SamplerCacheKey &key) { + auto iter = cache_.find(key); + if (iter != cache_.end()) { + return iter->second; + } + + VkSamplerCreateInfo samp; + samp.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; + samp.pNext = nullptr; + samp.addressModeU = key.sClamp ? VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE : VK_SAMPLER_ADDRESS_MODE_REPEAT; + samp.addressModeV = key.tClamp ? VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE : VK_SAMPLER_ADDRESS_MODE_REPEAT; + samp.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT; + samp.borderColor = VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK; + samp.compareEnable = false; + samp.flags = 0; + samp.magFilter = (key.magFilt & 1) ? VK_FILTER_LINEAR : VK_FILTER_NEAREST; + samp.minFilter = key.minFilt ? VK_FILTER_LINEAR : VK_FILTER_NEAREST; // TODO: Aniso + samp.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; // key.4) ? ((key.magFilt & 2) ? VK_SAMPLER_MIPMAP_MODE_LINEAR : VK_SAMPLER_MIPMAP_MODE_NEAREST) : VK_SAMPLER_MIPMAP_MODE_BASE; + samp.maxAnisotropy = 1.0f; + samp.maxLod = 1000.0f; + samp.minLod = 0.0f; + samp.unnormalizedCoordinates = false; + samp.mipLodBias = 0.0f; + + VkSampler sampler; + VkResult res = vkCreateSampler(vulkan_->GetDevice(), &samp, nullptr, &sampler); + + cache_[key] = sampler; + return sampler; +} + +TextureCacheVulkan::TextureCacheVulkan(VulkanContext *vulkan) : vulkan_(vulkan), samplerCache_(vulkan), cacheSizeEstimate_(0), secondCacheSizeEstimate_(0), clearCacheNextFrame_(false), lowMemoryMode_(false), clutBuf_(NULL), texelsScaledThisFrame_(0) { timesInvalidatedAllThisFrame_ = 0; lastBoundTexture = nullptr; decimationCounter_ = TEXCACHE_DECIMATION_INTERVAL; @@ -549,21 +585,6 @@ static const VkFilter MagFiltVK[2] = { VK_FILTER_LINEAR }; - -struct SamplerCacheKey { - bool minFilt : 1; - bool mipFilt : 1; - bool magFilt : 1; - bool sClamp : 1; - bool tClamp : 1; - int lodBias : 4; - int maxLevel : 4; - - bool operator < (const SamplerCacheKey &other) const { - return memcmp(this, &other, sizeof(*this)) < 0; - } -}; - // This should not have to be done per texture! OpenGL is silly yo void TextureCacheVulkan::UpdateSamplingParams(TexCacheEntry &entry, bool force) { // TODO: Make GetSamplingParams write SamplerCacheKey directly @@ -854,6 +875,10 @@ void TextureCacheVulkan::ApplyTexture(VkImageView &imageView, VkSampler &sampler } + imageView = nextTexture_->vkTex->imageView; + + SamplerCacheKey key; + sampler = samplerCache_.GetOrCreateSampler(key); // if (nextTexture_->textureName != lastBoundTexture) { // nextTexture_->vkTex-> // diff --git a/GPU/Vulkan/TextureCacheVulkan.h b/GPU/Vulkan/TextureCacheVulkan.h index cb75f1d4ba..809ef6cc55 100644 --- a/GPU/Vulkan/TextureCacheVulkan.h +++ b/GPU/Vulkan/TextureCacheVulkan.h @@ -32,7 +32,32 @@ class ShaderManagerVulkan; class DrawEngineVulkan; class VulkanContext; -struct SamplerCacheKey; + +struct SamplerCacheKey { + bool minFilt : 1; + bool mipFilt : 1; + bool magFilt : 1; + bool sClamp : 1; + bool tClamp : 1; + int lodBias : 4; + int maxLevel : 4; + + bool operator < (const SamplerCacheKey &other) const { + return memcmp(this, &other, sizeof(*this)) < 0; + } +}; + + +class SamplerCache { +public: + SamplerCache(VulkanContext *vulkan) : vulkan_(vulkan) {} + ~SamplerCache(); + VkSampler GetOrCreateSampler(const SamplerCacheKey &key); +private: + VulkanContext *vulkan_; + std::map cache_; +}; + class TextureCacheVulkan : public TextureCacheCommon { public: @@ -113,6 +138,8 @@ private: bool clearCacheNextFrame_; bool lowMemoryMode_; + SamplerCache samplerCache_; + TextureScalerVulkan scaler; u32 *clutBuf_; diff --git a/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp b/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp index dc308e344f..4eac7a04ef 100644 --- a/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp +++ b/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp @@ -307,9 +307,9 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { // Final view and projection transforms. if (gstate_c.Supports(GPU_ROUND_DEPTH_TO_16BIT)) { - WRITE(p, " gl_Position = depthRoundZVP(base.proj * viewPos);\n"); + WRITE(p, " gl_Position = depthRoundZVP(base.proj_mtx * viewPos);\n"); } else { - WRITE(p, " gl_Position = base.proj * viewPos;\n"); + WRITE(p, " gl_Position = base.proj_mtx * viewPos;\n"); } // TODO: Declare variables for dots for shade mapping if needed. @@ -323,7 +323,7 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { bool distanceNeeded = false; if (enableLighting) { - WRITE(p, " vec4 lightSum0 = light.ambient * %s + vec4(light.matemissive, 0.0);\n", ambientStr); + WRITE(p, " vec4 lightSum0 = light.globalAmbient * %s + vec4(light.matemissive, 0.0);\n", ambientStr); for (int i = 0; i < 4; i++) { GELightType type = static_cast(id.Bits(VS_BIT_LIGHT0_TYPE + 4 * i, 2)); @@ -378,7 +378,7 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { WRITE(p, " if (dot%i == 0.0 && light.matspecular.a == 0.0) {\n", i); WRITE(p, " dot%i = 1.0;\n", i); WRITE(p, " } else {\n"); - WRITE(p, " dot%i = pow(dot[%i], light.matspecular.a);\n", i, i); + WRITE(p, " dot%i = pow(dot%i, light.matspecular.a);\n", i, i); WRITE(p, " }\n"); } @@ -406,11 +406,11 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { break; } - WRITE(p, " diffuse = (light.diffuse[%i] * %s) * dot[%i];\n", i, diffuseStr, i); + WRITE(p, " diffuse = (light.diffuse[%i] * %s) * dot%i;\n", i, diffuseStr, i); if (doSpecular) { - WRITE(p, " dot[%i] = dot(normalize(toLight + vec3(0.0, 0.0, 1.0)), worldnormal);\n", i); - WRITE(p, " if (dot[%i] > 0.0)\n", i); - WRITE(p, " lightSum1 += light.specular[%i] * %s * (pow(dot[%i], light.matspecular.a) %s);\n", i, specularStr, i, timesLightScale); + WRITE(p, " dot%i = dot(normalize(toLight + vec3(0.0, 0.0, 1.0)), worldnormal);\n", i); + WRITE(p, " if (dot%i > 0.0)\n", i); + WRITE(p, " lightSum1 += light.specular[%i] * %s * (pow(dot%i, light.matspecular.a) %s);\n", i, specularStr, i, timesLightScale); } WRITE(p, " lightSum0.rgb += (light.ambient[%i] * %s.rgb + diffuse)%s;\n", i, ambientStr, timesLightScale); } @@ -439,8 +439,9 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { } else { WRITE(p, " v_color0 = base.matambientalpha;\n"); } - if (lmode) + if (lmode) { WRITE(p, " v_color1 = vec3(0.0);\n"); + } } // Step 3: UV generation diff --git a/ext/native/thin3d/VulkanContext.cpp b/ext/native/thin3d/VulkanContext.cpp index 4bfa3d1797..434628f54c 100644 --- a/ext/native/thin3d/VulkanContext.cpp +++ b/ext/native/thin3d/VulkanContext.cpp @@ -287,7 +287,7 @@ void VulkanContext::EndSurfaceRenderPass() { // return codes assert(!res); - frame->deleteList.Ingest(globalDeleteList_); + frame->deleteList.Take(globalDeleteList_); curFrame_ ^= 1; } diff --git a/ext/native/thin3d/VulkanContext.h b/ext/native/thin3d/VulkanContext.h index e6f9993c65..71b6f63440 100644 --- a/ext/native/thin3d/VulkanContext.h +++ b/ext/native/thin3d/VulkanContext.h @@ -76,8 +76,9 @@ public: void QueueDelete(VkImage image) { images_.push_back(image); } void QueueDelete(VkImageView imageView) { imageViews_.push_back(imageView); } void QueueDelete(VkDeviceMemory deviceMemory) { memory_.push_back(deviceMemory); } + void QueueDelete(VkSampler sampler) { samplers_.push_back(sampler); } - void Ingest(VulkanDeleteList &del) { + void Take(VulkanDeleteList &del) { descPools_ = std::move(del.descPools_); modules_ = std::move(del.modules_); buffers_ = std::move(del.buffers_); @@ -85,6 +86,7 @@ public: images_ = std::move(del.images_); imageViews_ = std::move(del.imageViews_); memory_ = std::move(del.memory_); + samplers_ = std::move(del.samplers_); } void PerformDeletes(VkDevice device) { @@ -112,6 +114,10 @@ public: vkFreeMemory(device, mem, nullptr); } memory_.clear(); + for (auto &sampler : samplers_) { + vkDestroySampler(device, sampler, nullptr); + } + samplers_.clear(); } private: @@ -122,6 +128,7 @@ private: std::vector images_; std::vector imageViews_; std::vector memory_; + std::vector samplers_; }; // VulkanContext sets up the basics necessary for rendering to a window, including framebuffers etc. @@ -447,11 +454,11 @@ public: return off; } - size_t PushAligned(const void *data, size_t size, int align) { + uint32_t PushAligned(const void *data, size_t size, int align) { offset_ = (offset_ + align - 1) & ~(align - 1); size_t off = Allocate(size); memcpy(writePtr_ + off, data, size); - return off; + return (uint32_t)off; } // "Zero-copy" variant - you can write the data directly as you compute it. diff --git a/ext/native/thin3d/vulkan_utils.h b/ext/native/thin3d/vulkan_utils.h index a6fb88aaae..d9daa4c998 100644 --- a/ext/native/thin3d/vulkan_utils.h +++ b/ext/native/thin3d/vulkan_utils.h @@ -24,8 +24,9 @@ #include "VulkanContext.h" class VulkanContext; + // Utility class to handle images without going insane. -// Allocates its own memory. +// Allocates its own memory. class VulkanImage { public: VulkanImage() : image_(nullptr), memory_(nullptr) {} @@ -48,9 +49,3 @@ private: int width_; int height_; }; - - -class Thin3DPipelineCache { - -}; - From d67d187b728dd383b6cb85e57f36e3e4dee9a1c4 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sat, 9 Jan 2016 11:07:14 +0100 Subject: [PATCH 025/116] Get untextured drawing working! (at least cube.elf) --- GPU/Vulkan/DrawEngineVulkan.cpp | 119 +++++++++++++++++++-------- GPU/Vulkan/DrawEngineVulkan.h | 3 +- GPU/Vulkan/PipelineManagerVulkan.cpp | 4 + GPU/Vulkan/PipelineManagerVulkan.h | 10 +-- GPU/Vulkan/ShaderManagerVulkan.cpp | 6 +- GPU/Vulkan/ShaderManagerVulkan.h | 8 +- GPU/Vulkan/StateMappingVulkan.cpp | 3 + GPU/Vulkan/TextureCacheVulkan.cpp | 6 -- GPU/Vulkan/TextureCacheVulkan.h | 7 ++ ext/native/thin3d/VulkanContext.h | 9 +- 10 files changed, 113 insertions(+), 62 deletions(-) diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index b7b5c59b15..5a09088aa6 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -1,6 +1,3 @@ -#include "GPU/Vulkan/DrawEngineVulkan.h" - - // Copyright (c) 2012- PPSSPP Project. // This program is free software: you can redistribute it and/or modify @@ -47,6 +44,14 @@ #include "GPU/Vulkan/PipelineManagerVulkan.h" #include "GPU/Vulkan/GPU_Vulkan.h" +enum { + DRAW_BINDING_TEXTURE = 0, + DRAW_BINDING_2ND_TEXTURE = 1, + DRAW_BINDING_DYNUBO_BASE = 2, + DRAW_BINDING_DYNUBO_LIGHT = 3, + DRAW_BINDING_DYNUBO_BONE = 4, +}; + const VkPrimitiveTopology prim[8] = { VK_PRIMITIVE_TOPOLOGY_POINT_LIST, VK_PRIMITIVE_TOPOLOGY_LINE_LIST, @@ -99,27 +104,27 @@ DrawEngineVulkan::DrawEngineVulkan(VulkanContext *vulkan) bindings[0].pImmutableSamplers = nullptr; bindings[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; bindings[0].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; - bindings[0].binding = 0; + bindings[0].binding = DRAW_BINDING_TEXTURE; bindings[1].descriptorCount = 1; bindings[1].pImmutableSamplers = nullptr; bindings[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; bindings[1].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; - bindings[1].binding = 1; + bindings[1].binding = DRAW_BINDING_2ND_TEXTURE; bindings[2].descriptorCount = 1; bindings[2].pImmutableSamplers = nullptr; bindings[2].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; bindings[2].stageFlags = VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT; - bindings[2].binding = 2; + bindings[2].binding = DRAW_BINDING_DYNUBO_BASE; bindings[3].descriptorCount = 1; bindings[3].pImmutableSamplers = nullptr; bindings[3].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; bindings[3].stageFlags = VK_SHADER_STAGE_VERTEX_BIT; - bindings[3].binding = 3; + bindings[3].binding = DRAW_BINDING_DYNUBO_LIGHT; bindings[4].descriptorCount = 1; bindings[4].pImmutableSamplers = nullptr; bindings[4].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; bindings[4].stageFlags = VK_SHADER_STAGE_VERTEX_BIT; - bindings[4].binding = 4; + bindings[4].binding = DRAW_BINDING_DYNUBO_BONE; VkDevice device = vulkan_->GetDevice(); @@ -131,7 +136,7 @@ DrawEngineVulkan::DrawEngineVulkan(VulkanContext *vulkan) VkResult res = vkCreateDescriptorSetLayout(device, &dsl, nullptr, &descriptorSetLayout_); VkDescriptorPoolSize dpTypes[2]; - dpTypes[0].descriptorCount = 200; + dpTypes[0].descriptorCount = 800; dpTypes[0].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; dpTypes[1].descriptorCount = 200; dpTypes[1].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; @@ -139,8 +144,8 @@ DrawEngineVulkan::DrawEngineVulkan(VulkanContext *vulkan) VkDescriptorPoolCreateInfo dp; dp.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; dp.pNext = nullptr; - dp.flags = 0; // Don't want to mess around with individually freeing these, let's go dynamic each frame. - dp.maxSets = 200; // 200 textures per frame should be enough for the UI... + dp.flags = 0; // Don't want to mess around with individually freeing these, let's go fixed each frame and zap the whole array. Might try the dynamic approach later. + dp.maxSets = 1000; dp.pPoolSizes = dpTypes; dp.poolSizeCount = ARRAY_SIZE(dpTypes); res = vkCreateDescriptorPool(device, &dp, nullptr, &frame_[0].descPool); @@ -167,6 +172,8 @@ DrawEngineVulkan::DrawEngineVulkan(VulkanContext *vulkan) assert(VK_SUCCESS == res); VkSamplerCreateInfo samp = {}; + samp.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; + samp.pNext = nullptr; samp.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; samp.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; samp.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; @@ -377,13 +384,14 @@ inline u32 ComputeMiniHashRange(const void *ptr, size_t sz) { } } -VkDescriptorSet DrawEngineVulkan::GetDescriptorSet(CachedTextureVulkan *texture, VkSampler sampler) { +VkDescriptorSet DrawEngineVulkan::GetDescriptorSet(CachedTextureVulkan *texture, VkSampler sampler, VkBuffer dynamicUbo) { DescriptorSetKey key; key.texture_ = texture; key.sampler_ = sampler; key.secondaryTexture_ = nullptr; - FrameData *frame = &frame_[curFrame_ & 1]; + key.buffer_ = dynamicUbo; + FrameData *frame = &frame_[curFrame_ & 1]; auto iter = frame->descSets.find(key); if (iter != frame->descSets.end()) { return iter->second; @@ -392,22 +400,59 @@ VkDescriptorSet DrawEngineVulkan::GetDescriptorSet(CachedTextureVulkan *texture, // Didn't find one in the frame cache, let's make a new one. VkDescriptorSet desc; + VkDescriptorSetAllocateInfo descAlloc; + descAlloc.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; + descAlloc.pNext = nullptr; + descAlloc.pSetLayouts = &descriptorSetLayout_; + descAlloc.descriptorPool = frame->descPool; + descAlloc.descriptorSetCount = 1; + vkAllocateDescriptorSets(vulkan_->GetDevice(), &descAlloc, &desc); + // We just don't write to the slots we don't care about. - VkWriteDescriptorSet writes[2]; + VkWriteDescriptorSet writes[4]; memset(writes, 0, sizeof(writes)); // Main texture - VkDescriptorImageInfo tex; + int n = 0; + if (texture) { + VkDescriptorImageInfo tex; + tex.imageLayout = texture->imageLayout; + tex.imageView = texture->imageView; + tex.sampler = sampler; + writes[n].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + writes[n].pNext = nullptr; + writes[n].dstBinding = DRAW_BINDING_TEXTURE; + writes[n].pImageInfo = &tex; + writes[n].descriptorCount = 1; + writes[n].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + writes[n].dstSet = desc; + n++; + } - // tex.imageView = texture->imageView; - tex.sampler = sampler; - writes[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - writes[0].dstBinding = 0; - writes[0].pImageInfo = &tex; - - vkUpdateDescriptorSets(vulkan_->GetDevice(), 2, writes, 0, nullptr); + // Skipping 2nd texture for now. + // Uniform buffer objects + VkDescriptorBufferInfo buf[3]; + buf[0].buffer = dynamicUbo; + buf[0].offset = 0; + buf[0].range = sizeof(UB_VS_FS_Base); + buf[1].buffer = dynamicUbo; + buf[1].offset = 0; + buf[1].range = sizeof(UB_VS_Lights); + buf[2].buffer = dynamicUbo; + buf[2].offset = 0; + buf[2].range = sizeof(UB_VS_Bones); + writes[n].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + writes[n].pNext = nullptr; + writes[n].dstBinding = DRAW_BINDING_DYNUBO_BASE; + writes[n].pBufferInfo = &buf[0]; + writes[n].dstSet = desc; + writes[n].descriptorCount = 3; + writes[n].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; + n++; + + vkUpdateDescriptorSets(vulkan_->GetDevice(), n, writes, 0, nullptr); frame->descSets[key] = desc; - return nullptr; + return desc; } // The inline wrapper in the header checks for numDrawCalls == 0d @@ -416,16 +461,19 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { FrameData *frame = &frame_[curFrame_ & 1]; -// CachedTextureVulkan *tex = textureCache_->ApplyTexture(); -// VkDescriptorSet ds = GetDescriptorSet(tex); - VkDescriptorSet ds; + // Note than when we implement overflow in pushbuffer, we need to make sure to overflow here, not between + // the three ubo pushes. The reason is that the three UBOs must be in the same buffer as that's how we + // designed the descriptor set. + + // CachedTextureVulkan *tex = textureCache_->ApplyTexture(); + VkDescriptorSet ds = GetDescriptorSet(nullptr, nullptr, frame->pushData->GetVkBuffer()); GEPrimitiveType prim = prevPrim_; - // ApplyDrawState(prim); + + bool useHWTransform = CanUseHardwareTransform(prim); VulkanVertexShader *vshader; VulkanFragmentShader *fshader; - shaderManager_->GetShaders(prim, lastVType_, &vshader, &fshader); uint32_t baseUBOOffset = 0; uint32_t lightUBOOffset = 0; @@ -434,7 +482,7 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { uint32_t ibOffset = 0; uint32_t vbOffset = 0; - if (vshader->UseHWTransform()) { + if (useHWTransform) { int vertexCount = 0; int maxIndex = 0; bool useElements = true; @@ -449,7 +497,6 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { } prim = indexGen.Prim(); - VERBOSE_LOG(G3D, "Flush prim %i! %i verts in one go", prim, vertexCount); bool hasColor = (lastVType_ & GE_VTYPE_COL_MASK) != GE_VTYPE_COL_NONE; if (gstate.isModeThrough()) { gstate_c.vertexFullAlpha = gstate_c.vertexFullAlpha && (hasColor || gstate.getMaterialAmbientA() == 255); @@ -467,6 +514,7 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { vkCmdSetStencilWriteMask(cmd_, VK_STENCIL_FRONT_AND_BACK, dynState.stencilWriteMask); vkCmdSetStencilCompareMask(cmd_, VK_STENCIL_FRONT_AND_BACK, dynState.stencilCompareMask); // vkCmdSetBlendConstants(cmd_, dynState.blendColor); + shaderManager_->GetShaders(prim, lastVType_, &vshader, &fshader, useHWTransform); VulkanPipeline *pipeline = pipelineManager_->GetOrCreatePipeline(pipelineLayout_, pipelineKey, dec_, vshader->GetModule(), fshader->GetModule(), true); vkCmdBindPipeline(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline->pipeline); // TODO: Avoid if same as last draw. @@ -481,21 +529,21 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { } VkBuffer buf[1] = {frame->pushData->GetVkBuffer()}; - uint32_t dynamicUBOOffsets[3] = { + const uint32_t dynamicUBOOffsets[3] = { baseUBOOffset, lightUBOOffset, boneUBOOffset, }; vkCmdBindDescriptorSets(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout_, 0, 1, &ds, 3, dynamicUBOOffsets); - ibOffset = (uint32_t)frame->pushData->Push(decIndex, 2 * indexGen.VertexCount()); vbOffset = (uint32_t)frame->pushData->Push(decoded, vertexCount * dec_->GetDecVtxFmt().stride); VkDeviceSize offsets[1] = { vbOffset }; if (useElements) { + ibOffset = (uint32_t)frame->pushData->Push(decIndex, 2 * indexGen.VertexCount()); // TODO: Avoid rebinding vertex/index buffers if the vertex size stays the same by using the offset arguments // Might want to separate vertices out into a different push buffer in that case. vkCmdBindVertexBuffers(cmd_, 0, 1, buf, offsets); vkCmdBindIndexBuffer(cmd_, buf[0], ibOffset, VK_INDEX_TYPE_UINT16); - vkCmdDrawIndexed(cmd_, maxIndex + 1, 1, 0, 0, 0); + vkCmdDrawIndexed(cmd_, maxIndex, 1, 0, 0, 0); } else { vkCmdBindVertexBuffers(cmd_, 0, 1, buf, offsets); vkCmdDraw(cmd_, vertexCount, 1, 0, 0); @@ -548,6 +596,7 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { } // vkCmdSetBlendConstants(cmd_, dynState.blendColor); + shaderManager_->GetShaders(prim, lastVType_, &vshader, &fshader, useHWTransform); VulkanPipeline *pipeline = pipelineManager_->GetOrCreatePipeline(pipelineLayout_, pipelineKey, dec_, vshader->GetModule(), fshader->GetModule(), false); vkCmdBindPipeline(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline->pipeline); // TODO: Avoid if same as last draw. @@ -555,17 +604,17 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { baseUBOOffset = shaderManager_->PushBaseBuffer(frame->pushData); } - uint32_t dynamicUBOOffsets[3] = { + const uint32_t dynamicUBOOffsets[3] = { baseUBOOffset, lightUBOOffset, boneUBOOffset, }; vkCmdBindDescriptorSets(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout_, 0, 1, &ds, 3, dynamicUBOOffsets); - ibOffset = (uint32_t)frame->pushData->Push(decIndex, 2 * indexGen.VertexCount()); vbOffset = (uint32_t)frame->pushData->Push(decoded, numTrans * dec_->GetDecVtxFmt().stride); VkBuffer buf[1] = { frame->pushData->GetVkBuffer() }; VkDeviceSize offsets[1] = { vbOffset }; if (drawIndexed) { + ibOffset = (uint32_t)frame->pushData->Push(decIndex, 2 * indexGen.VertexCount()); // TODO: Have a buffer per frame, use a walking buffer pointer // TODO: Avoid rebinding if the vertex size stays the same by using the offset arguments vkCmdBindVertexBuffers(cmd_, 0, 1, buf, offsets); diff --git a/GPU/Vulkan/DrawEngineVulkan.h b/GPU/Vulkan/DrawEngineVulkan.h index e51c141842..936d8840ff 100644 --- a/GPU/Vulkan/DrawEngineVulkan.h +++ b/GPU/Vulkan/DrawEngineVulkan.h @@ -149,7 +149,7 @@ private: void DecodeVertsStep(); void DoFlush(VkCommandBuffer cmd); - VkDescriptorSet GetDescriptorSet(CachedTextureVulkan *texture, VkSampler sampler); + VkDescriptorSet GetDescriptorSet(CachedTextureVulkan *texture, VkSampler sampler, VkBuffer dynamicUbo); VertexDecoder *GetVertexDecoder(u32 vtype); @@ -163,6 +163,7 @@ private: void *texture_; void *secondaryTexture_; VkSampler sampler_; + VkBuffer buffer_; // All three UBO slots will be set to this. bool operator < (const DescriptorSetKey &other) const { if (texture_ < other.texture_) return true; else if (texture_ > other.texture_) return false; diff --git a/GPU/Vulkan/PipelineManagerVulkan.cpp b/GPU/Vulkan/PipelineManagerVulkan.cpp index 9b77ac4b86..e7c97a0c92 100644 --- a/GPU/Vulkan/PipelineManagerVulkan.cpp +++ b/GPU/Vulkan/PipelineManagerVulkan.cpp @@ -283,6 +283,10 @@ static VulkanPipeline *CreateVulkanPipeline(VkDevice device, VkPipelineCache pip VulkanPipeline *PipelineManagerVulkan::GetOrCreatePipeline(VkPipelineLayout layout, const VulkanPipelineRasterStateKey &rasterKey, const VertexDecoder *vtxDec, VkShaderModule vShader, VkShaderModule fShader, bool useHwTransform) { VulkanPipelineKey key; key.raster = rasterKey; + key.useHWTransform = useHwTransform; + key.vShader = vShader; + key.fShader = fShader; + key.vtxDec = vtxDec; auto iter = pipelines_.find(key); if (iter != pipelines_.end()) { return iter->second; diff --git a/GPU/Vulkan/PipelineManagerVulkan.h b/GPU/Vulkan/PipelineManagerVulkan.h index 0805425fb2..3d86e50427 100644 --- a/GPU/Vulkan/PipelineManagerVulkan.h +++ b/GPU/Vulkan/PipelineManagerVulkan.h @@ -37,20 +37,16 @@ enum class PspAttributeLocation { COUNT }; -// All the information needed. All PSP rendering (except full screen clears?) will make use of a single -// render pass definition. struct VulkanPipelineKey { - VulkanPipelineRasterStateKey raster; - int prim; - bool pretransformed; + VulkanPipelineRasterStateKey raster; // prim is included here + bool useHWTransform; const VertexDecoder *vtxDec; VkShaderModule vShader; VkShaderModule fShader; bool operator < (const VulkanPipelineKey &other) const { if (raster < other.raster) return true; else if (other.raster < raster) return false; - if (prim < other.prim) return true; else if (other.prim < prim) return false; - if (pretransformed < other.pretransformed) return true; else if (other.pretransformed < pretransformed) return false; + if (useHWTransform < other.useHWTransform) return true; else if (other.useHWTransform < useHWTransform) return false; if (vtxDec < other.vtxDec) return true; else if (other.vtxDec < vtxDec) return false; if (vShader < other.vShader) return true; else if (other.vShader < vShader) return false; if (fShader < other.fShader) return true; else if (other.fShader < fShader) return false; diff --git a/GPU/Vulkan/ShaderManagerVulkan.cpp b/GPU/Vulkan/ShaderManagerVulkan.cpp index 4b1de3306f..a3dda8833b 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.cpp +++ b/GPU/Vulkan/ShaderManagerVulkan.cpp @@ -351,7 +351,7 @@ void ShaderManagerVulkan::BaseUpdateUniforms(int dirtyUniforms) { default: ERROR_LOG_REPORT(G3D, "Unexpected UV gen mode: %d", gstate.getUVGenMode()); - } + } CopyFloat4(ub_base.uvScaleOffset, uvscaleoff); } @@ -475,9 +475,7 @@ void ShaderManagerVulkan::DirtyLastShader() { // disables vertex arrays } -void ShaderManagerVulkan::GetShaders(int prim, u32 vertType, VulkanVertexShader **vshader, VulkanFragmentShader **fshader) { - bool useHWTransform = CanUseHardwareTransform(prim); - +void ShaderManagerVulkan::GetShaders(int prim, u32 vertType, VulkanVertexShader **vshader, VulkanFragmentShader **fshader, bool useHWTransform) { ShaderID VSID; ComputeVertexShaderID(&VSID, vertType, useHWTransform); ShaderID FSID; diff --git a/GPU/Vulkan/ShaderManagerVulkan.h b/GPU/Vulkan/ShaderManagerVulkan.h index af96ca5b54..f1991426cb 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.h +++ b/GPU/Vulkan/ShaderManagerVulkan.h @@ -81,7 +81,7 @@ enum { DIRTY_ALL = 0xFFFFFFFF }; -struct UB_VS_TransformCommon { +struct UB_VS_FS_Base { float proj[16]; float view[16]; float world[16]; @@ -107,7 +107,7 @@ R"( mat4 proj_mtx; mat4 view_mtx; mat4 world_mtx; mat4 tex_mtx; - vec4 uvScaleOffset; + vec4 uvscaleoffset; vec4 depthRange; vec2 fogCoef; vec4 matambientalpha; @@ -213,7 +213,7 @@ public: ~ShaderManagerVulkan(); void ClearCache(bool deleteThem); // TODO: deleteThem currently not respected - void GetShaders(int prim, u32 vertType, VulkanVertexShader **vshader, VulkanFragmentShader **fshader); + void GetShaders(int prim, u32 vertType, VulkanVertexShader **vshader, VulkanFragmentShader **fshader, bool useHWTransform); void DirtyShader(); void DirtyUniform(u32 what) { @@ -251,7 +251,7 @@ private: char *codeBuffer_; // Uniform block scratchpad. These (the relevant ones) are copied to the current pushbuffer at draw time. - UB_VS_TransformCommon ub_base; + UB_VS_FS_Base ub_base; UB_VS_Lights ub_lights; UB_VS_Bones ub_bones; diff --git a/GPU/Vulkan/StateMappingVulkan.cpp b/GPU/Vulkan/StateMappingVulkan.cpp index 18e0a2e14b..acd959c8e2 100644 --- a/GPU/Vulkan/StateMappingVulkan.cpp +++ b/GPU/Vulkan/StateMappingVulkan.cpp @@ -188,6 +188,9 @@ void ConvertStateToVulkanKey(FramebufferManagerVulkan &fbManager, int prim, Vulk bool wantCull = !gstate.isModeThrough() && prim != GE_PRIM_RECTANGLES && gstate.isCullEnabled(); key.cullMode = wantCull ? (gstate.getCullMode() ? VK_CULL_MODE_FRONT_BIT : VK_CULL_MODE_BACK_BIT) : VK_CULL_MODE_NONE; + // TODO: Remove (For debugging) + key.cullMode = VK_CULL_MODE_NONE; + // Depth Test if (gstate.isDepthTestEnabled()) { key.depthTestEnable = true; diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index 14cb54700f..4e52597a67 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -68,12 +68,6 @@ // Hack! extern int g_iNumVideos; -// texturePtr points to these. -class CachedTextureVulkan { -public: - VkImageView imageView; -}; - SamplerCache::~SamplerCache() { for (auto iter : cache_) { vulkan_->QueueDelete(iter.second); diff --git a/GPU/Vulkan/TextureCacheVulkan.h b/GPU/Vulkan/TextureCacheVulkan.h index 809ef6cc55..f4f94d6918 100644 --- a/GPU/Vulkan/TextureCacheVulkan.h +++ b/GPU/Vulkan/TextureCacheVulkan.h @@ -47,12 +47,19 @@ struct SamplerCacheKey { } }; +// texturePtr points to these. +class CachedTextureVulkan { +public: + VkImageView imageView; + VkImageLayout imageLayout; +}; class SamplerCache { public: SamplerCache(VulkanContext *vulkan) : vulkan_(vulkan) {} ~SamplerCache(); VkSampler GetOrCreateSampler(const SamplerCacheKey &key); + private: VulkanContext *vulkan_; std::map cache_; diff --git a/ext/native/thin3d/VulkanContext.h b/ext/native/thin3d/VulkanContext.h index 71b6f63440..da3fbf06fe 100644 --- a/ext/native/thin3d/VulkanContext.h +++ b/ext/native/thin3d/VulkanContext.h @@ -384,13 +384,12 @@ private: VkFramebuffer framebuffer_; }; -// Use these to push vertex, index and uniform data. +// Use these to push vertex, index and uniform data. Generally you'll have two of these +// and alternate on each frame. // TODO: Make it possible to suballocate pushbuffers from a large DeviceMemory block. -// TODO: Make this dynamically grow by chaining new buffers in the future. -// Until then, we cap at a maximum size. // We'll have two of these that we alternate between on each frame. -// These will only be used for the "Thin3D" system - the PSP emulation etc will have -// their own similar buffer solutions. +// TODO: Make this auto-grow and shrink. Need to be careful about returning and using the new +// buffer handle on overflow. class VulkanPushBuffer { public: VulkanPushBuffer(VulkanContext *vulkan, size_t size) : offset_(0), size_(size), writePtr_(nullptr), deviceMemory_(nullptr) { From 6141c3651b4bac9eec8cda9ce2288e1c8fd8dde9 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sat, 9 Jan 2016 12:17:02 +0100 Subject: [PATCH 026/116] Separate uniform updates from shader updates --- GPU/Vulkan/DrawEngineVulkan.cpp | 2 ++ GPU/Vulkan/ShaderManagerVulkan.cpp | 20 ++++++++------------ GPU/Vulkan/ShaderManagerVulkan.h | 27 +++++++++++++++------------ 3 files changed, 25 insertions(+), 24 deletions(-) diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index 5a09088aa6..72d7de2b34 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -514,6 +514,7 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { vkCmdSetStencilWriteMask(cmd_, VK_STENCIL_FRONT_AND_BACK, dynState.stencilWriteMask); vkCmdSetStencilCompareMask(cmd_, VK_STENCIL_FRONT_AND_BACK, dynState.stencilCompareMask); // vkCmdSetBlendConstants(cmd_, dynState.blendColor); + shaderManager_->UpdateUniforms(); shaderManager_->GetShaders(prim, lastVType_, &vshader, &fshader, useHWTransform); VulkanPipeline *pipeline = pipelineManager_->GetOrCreatePipeline(pipelineLayout_, pipelineKey, dec_, vshader->GetModule(), fshader->GetModule(), true); vkCmdBindPipeline(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline->pipeline); // TODO: Avoid if same as last draw. @@ -596,6 +597,7 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { } // vkCmdSetBlendConstants(cmd_, dynState.blendColor); + shaderManager_->UpdateUniforms(); shaderManager_->GetShaders(prim, lastVType_, &vshader, &fshader, useHWTransform); VulkanPipeline *pipeline = pipelineManager_->GetOrCreatePipeline(pipelineLayout_, pipelineKey, dec_, vshader->GetModule(), fshader->GetModule(), false); vkCmdBindPipeline(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline->pipeline); // TODO: Avoid if same as last draw. diff --git a/GPU/Vulkan/ShaderManagerVulkan.cpp b/GPU/Vulkan/ShaderManagerVulkan.cpp index a3dda8833b..0ab32e7f0d 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.cpp +++ b/GPU/Vulkan/ShaderManagerVulkan.cpp @@ -474,6 +474,14 @@ void ShaderManagerVulkan::DirtyLastShader() { // disables vertex arrays lastFShader_ = nullptr; } +void ShaderManagerVulkan::UpdateUniforms() { + if (globalDirty_) { + BaseUpdateUniforms(globalDirty_); + LightUpdateUniforms(globalDirty_); + BoneUpdateUniforms(globalDirty_); + globalDirty_ = 0; + } +} void ShaderManagerVulkan::GetShaders(int prim, u32 vertType, VulkanVertexShader **vshader, VulkanFragmentShader **fshader, bool useHWTransform) { ShaderID VSID; @@ -483,12 +491,6 @@ void ShaderManagerVulkan::GetShaders(int prim, u32 vertType, VulkanVertexShader // Just update uniforms if this is the same shader as last time. if (lastVShader_ != nullptr && lastFShader_ != nullptr && VSID == lastVSID_ && FSID == lastFSID_) { - if (globalDirty_) { - BaseUpdateUniforms(globalDirty_); - LightUpdateUniforms(globalDirty_); - BoneUpdateUniforms(globalDirty_); - globalDirty_ = 0; - } *vshader = lastVShader_; *fshader = lastFShader_; // Already all set, no need to look up in shader maps. @@ -520,12 +522,6 @@ void ShaderManagerVulkan::GetShaders(int prim, u32 vertType, VulkanVertexShader lastFSID_ = FSID; - if (globalDirty_) { - BaseUpdateUniforms(globalDirty_); - LightUpdateUniforms(globalDirty_); - BoneUpdateUniforms(globalDirty_); - globalDirty_ = 0; - } *vshader = vs; *fshader = fs; } diff --git a/GPU/Vulkan/ShaderManagerVulkan.h b/GPU/Vulkan/ShaderManagerVulkan.h index f1991426cb..7e297598bf 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.h +++ b/GPU/Vulkan/ShaderManagerVulkan.h @@ -216,9 +216,6 @@ public: void GetShaders(int prim, u32 vertType, VulkanVertexShader **vshader, VulkanFragmentShader **fshader, bool useHWTransform); void DirtyShader(); - void DirtyUniform(u32 what) { - globalDirty_ |= what; - } void DirtyLastShader(); int GetNumVertexShaders() const { return (int)vsCache_.size(); } @@ -227,6 +224,12 @@ public: std::vector DebugGetShaderIDs(DebugShaderType type); std::string DebugGetShaderString(std::string id, DebugShaderType type, DebugShaderStringType stringType); + void UpdateUniforms(); + + void DirtyUniform(u32 what) { + globalDirty_ |= what; + } + // TODO: Avoid copying these buffers if same as last draw, can still point to it assuming we're still in the same pushbuffer. // Applies dirty changes and copies the buffer. bool IsBaseDirty() { return true; } @@ -246,21 +249,21 @@ private: VulkanContext *vulkan_; - uint32_t globalDirty_; - uint32_t uboAlignment_; - char *codeBuffer_; - - // Uniform block scratchpad. These (the relevant ones) are copied to the current pushbuffer at draw time. - UB_VS_FS_Base ub_base; - UB_VS_Lights ub_lights; - UB_VS_Bones ub_bones; - typedef std::map FSCache; FSCache fsCache_; typedef std::map VSCache; VSCache vsCache_; + char *codeBuffer_; + + uint32_t globalDirty_; + uint32_t uboAlignment_; + // Uniform block scratchpad. These (the relevant ones) are copied to the current pushbuffer at draw time. + UB_VS_FS_Base ub_base; + UB_VS_Lights ub_lights; + UB_VS_Bones ub_bones; + VulkanFragmentShader *lastFShader_; VulkanVertexShader *lastVShader_; From 6b8c0045612dfa23058fd5ecd1a9c0dd25228ab4 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sat, 9 Jan 2016 12:37:05 +0100 Subject: [PATCH 027/116] Fix indexed drawing, flip rendering the right side up, enable culling --- GPU/Vulkan/DrawEngineVulkan.cpp | 2 +- GPU/Vulkan/GPU_Vulkan.cpp | 3 +-- GPU/Vulkan/ShaderManagerVulkan.cpp | 15 ++++----------- GPU/Vulkan/StateMappingVulkan.cpp | 3 --- GPU/Vulkan/TextureCacheVulkan.cpp | 2 +- 5 files changed, 7 insertions(+), 18 deletions(-) diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index 72d7de2b34..f1523df757 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -544,7 +544,7 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { // Might want to separate vertices out into a different push buffer in that case. vkCmdBindVertexBuffers(cmd_, 0, 1, buf, offsets); vkCmdBindIndexBuffer(cmd_, buf[0], ibOffset, VK_INDEX_TYPE_UINT16); - vkCmdDrawIndexed(cmd_, maxIndex, 1, 0, 0, 0); + vkCmdDrawIndexed(cmd_, indexGen.VertexCount(), 1, 0, 0, 0); } else { vkCmdBindVertexBuffers(cmd_, 0, 1, buf, offsets); vkCmdDraw(cmd_, vertexCount, 1, 0, 0); diff --git a/GPU/Vulkan/GPU_Vulkan.cpp b/GPU/Vulkan/GPU_Vulkan.cpp index c49fa09d5d..29e9d6f547 100644 --- a/GPU/Vulkan/GPU_Vulkan.cpp +++ b/GPU/Vulkan/GPU_Vulkan.cpp @@ -501,9 +501,8 @@ void GPU_Vulkan::BeginHostFrame() { } else if (dumpThisFrame_) { dumpThisFrame_ = false; } - shaderManager_->DirtyShader(); - // Not sure if this is really needed. + shaderManager_->DirtyShader(); shaderManager_->DirtyUniform(DIRTY_ALL); framebufferManager_.BeginFrame(); diff --git a/GPU/Vulkan/ShaderManagerVulkan.cpp b/GPU/Vulkan/ShaderManagerVulkan.cpp index 0ab32e7f0d..a51fedd901 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.cpp +++ b/GPU/Vulkan/ShaderManagerVulkan.cpp @@ -182,21 +182,15 @@ ShaderManagerVulkan::~ShaderManagerVulkan() { } uint32_t ShaderManagerVulkan::PushBaseBuffer(VulkanPushBuffer *dest) { - if (globalDirty_ & DIRTY_BASE_UNIFORMS) - BaseUpdateUniforms(globalDirty_); return dest->PushAligned(&ub_base, sizeof(ub_base), uboAlignment_); } uint32_t ShaderManagerVulkan::PushLightBuffer(VulkanPushBuffer *dest) { - if (globalDirty_ & DIRTY_BASE_UNIFORMS) - BaseUpdateUniforms(globalDirty_); return dest->PushAligned(&ub_lights, sizeof(ub_lights), uboAlignment_); } // TODO: Only push half the bone buffer if we only have four bones. uint32_t ShaderManagerVulkan::PushBoneBuffer(VulkanPushBuffer *dest) { - if (globalDirty_ & DIRTY_BASE_UNIFORMS) - BaseUpdateUniforms(globalDirty_); return dest->PushAligned(&ub_bones, sizeof(ub_bones), uboAlignment_); } @@ -255,7 +249,7 @@ void ShaderManagerVulkan::BaseUpdateUniforms(int dirtyUniforms) { memcpy(&flippedMatrix, gstate.projMatrix, 16 * sizeof(float)); const bool invertedY = gstate_c.vpHeight < 0; - if (!invertedY) { + if (invertedY) { flippedMatrix[1] = -flippedMatrix[1]; flippedMatrix[5] = -flippedMatrix[5]; flippedMatrix[9] = -flippedMatrix[9]; @@ -401,7 +395,7 @@ void ShaderManagerVulkan::LightUpdateUniforms(int dirtyUniforms) { Uint8x3ToFloat4(ub_lights.materialEmissive, gstate.materialemissive); } if (dirtyUniforms & DIRTY_MATSPECULAR) { - Uint8x3ToFloat4_Alpha(ub_lights.materialEmissive, gstate.materialspecular, getFloat24(gstate.materialspecularcoef)); + Uint8x3ToFloat4_Alpha(ub_lights.materialSpecular, gstate.materialspecular, getFloat24(gstate.materialspecularcoef)); } for (int i = 0; i < 4; i++) { @@ -449,10 +443,10 @@ void ShaderManagerVulkan::Clear() { } fsCache_.clear(); vsCache_.clear(); - globalDirty_ = 0xFFFFFFFF; lastFSID_.clear(); lastVSID_.clear(); DirtyShader(); + DirtyUniform(0xFFFFFFFF); } void ShaderManagerVulkan::ClearCache(bool deleteThem) { @@ -466,7 +460,6 @@ void ShaderManagerVulkan::DirtyShader() { lastVSID_.clear(); lastVShader_ = nullptr; lastFShader_ = nullptr; - globalDirty_ = 0xFFFFFFFF; } void ShaderManagerVulkan::DirtyLastShader() { // disables vertex arrays @@ -485,8 +478,8 @@ void ShaderManagerVulkan::UpdateUniforms() { void ShaderManagerVulkan::GetShaders(int prim, u32 vertType, VulkanVertexShader **vshader, VulkanFragmentShader **fshader, bool useHWTransform) { ShaderID VSID; - ComputeVertexShaderID(&VSID, vertType, useHWTransform); ShaderID FSID; + ComputeVertexShaderID(&VSID, vertType, useHWTransform); ComputeFragmentShaderID(&FSID); // Just update uniforms if this is the same shader as last time. diff --git a/GPU/Vulkan/StateMappingVulkan.cpp b/GPU/Vulkan/StateMappingVulkan.cpp index acd959c8e2..18e0a2e14b 100644 --- a/GPU/Vulkan/StateMappingVulkan.cpp +++ b/GPU/Vulkan/StateMappingVulkan.cpp @@ -188,9 +188,6 @@ void ConvertStateToVulkanKey(FramebufferManagerVulkan &fbManager, int prim, Vulk bool wantCull = !gstate.isModeThrough() && prim != GE_PRIM_RECTANGLES && gstate.isCullEnabled(); key.cullMode = wantCull ? (gstate.getCullMode() ? VK_CULL_MODE_FRONT_BIT : VK_CULL_MODE_BACK_BIT) : VK_CULL_MODE_NONE; - // TODO: Remove (For debugging) - key.cullMode = VK_CULL_MODE_NONE; - // Depth Test if (gstate.isDepthTestEnabled()) { key.depthTestEnable = true; diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index 4e52597a67..ecc44dcf3a 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -93,7 +93,7 @@ VkSampler SamplerCache::GetOrCreateSampler(const SamplerCacheKey &key) { samp.minFilter = key.minFilt ? VK_FILTER_LINEAR : VK_FILTER_NEAREST; // TODO: Aniso samp.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; // key.4) ? ((key.magFilt & 2) ? VK_SAMPLER_MIPMAP_MODE_LINEAR : VK_SAMPLER_MIPMAP_MODE_NEAREST) : VK_SAMPLER_MIPMAP_MODE_BASE; samp.maxAnisotropy = 1.0f; - samp.maxLod = 1000.0f; + samp.maxLod = 0.0f; // 1000.0f; samp.minLod = 0.0f; samp.unnormalizedCoordinates = false; samp.mipLodBias = 0.0f; From ec6bc4a5f673b4eee87e1951d0dbdef46bccd1e4 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sat, 9 Jan 2016 13:31:36 +0100 Subject: [PATCH 028/116] Vertex format fixes. Flip through drawing the right way up. --- GPU/Vulkan/DrawEngineVulkan.cpp | 2 +- GPU/Vulkan/PipelineManagerVulkan.cpp | 12 ++++++------ GPU/Vulkan/ShaderManagerVulkan.cpp | 3 +-- GPU/Vulkan/StateMappingVulkan.cpp | 1 + 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index f1523df757..d81848880e 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -611,7 +611,7 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { }; vkCmdBindDescriptorSets(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout_, 0, 1, &ds, 3, dynamicUBOOffsets); - vbOffset = (uint32_t)frame->pushData->Push(decoded, numTrans * dec_->GetDecVtxFmt().stride); + vbOffset = (uint32_t)frame->pushData->Push(drawBuffer, numTrans * sizeof(TransformedVertex)); VkBuffer buf[1] = { frame->pushData->GetVkBuffer() }; VkDeviceSize offsets[1] = { vbOffset }; diff --git a/GPU/Vulkan/PipelineManagerVulkan.cpp b/GPU/Vulkan/PipelineManagerVulkan.cpp index e7c97a0c92..28883b7ab3 100644 --- a/GPU/Vulkan/PipelineManagerVulkan.cpp +++ b/GPU/Vulkan/PipelineManagerVulkan.cpp @@ -33,13 +33,13 @@ static const DeclTypeInfo VComp[] = { { VK_FORMAT_R32G32B32_SFLOAT, "R32G32B32_SFLOAT " }, // DEC_FLOAT_3, { VK_FORMAT_R32G32B32A32_SFLOAT, "R32G32B32A32_SFLOAT " }, // DEC_FLOAT_4, - { VK_FORMAT_UNDEFINED, "UNDEFINED" }, // DEC_S8_3, - + { VK_FORMAT_R8G8B8A8_SNORM, "UNDEFINED" }, // DEC_S8_3, { VK_FORMAT_R16G16B16A16_SNORM, "R16G16B16A16_SNORM " }, // DEC_S16_3, - { VK_FORMAT_R8G8B8A8_SNORM, "R8G8B8A8_SNORM " }, // DEC_U8_1, - { VK_FORMAT_R8G8B8A8_SNORM, "R8G8B8A8_SNORM " }, // DEC_U8_2, - { VK_FORMAT_R8G8B8A8_SNORM, "R8G8B8A8_SNORM " }, // DEC_U8_3, - { VK_FORMAT_R8G8B8A8_SNORM, "R8G8B8A8_SNORM " }, // DEC_U8_4, + + { VK_FORMAT_R8G8B8A8_UNORM, "R8G8B8A8_UNORM " }, // DEC_U8_1, + { VK_FORMAT_R8G8B8A8_UNORM, "R8G8B8A8_UNORM " }, // DEC_U8_2, + { VK_FORMAT_R8G8B8A8_UNORM, "R8G8B8A8_UNORM " }, // DEC_U8_3, + { VK_FORMAT_R8G8B8A8_UNORM, "R8G8B8A8_UNORM " }, // DEC_U8_4, { VK_FORMAT_R16G16_UNORM, "R16G16_UNORM" }, // DEC_U16_1, { VK_FORMAT_R16G16_UNORM, "R16G16_UNORM" }, // DEC_U16_2, { VK_FORMAT_R16G16B16A16_UNORM, "R16G16B16A16_UNORM " }, // DEC_U16_3, diff --git a/GPU/Vulkan/ShaderManagerVulkan.cpp b/GPU/Vulkan/ShaderManagerVulkan.cpp index a51fedd901..a9808b584f 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.cpp +++ b/GPU/Vulkan/ShaderManagerVulkan.cpp @@ -241,7 +241,7 @@ void ShaderManagerVulkan::BaseUpdateUniforms(int dirtyUniforms) { if (dirtyUniforms & DIRTY_PROJMATRIX) { if (gstate.isModeThrough()) { Matrix4x4 proj_through; - proj_through.setOrtho(0.0f, gstate_c.curRTWidth, gstate_c.curRTHeight, 0, 0, 1); + proj_through.setOrtho(0.0f, gstate_c.curRTWidth, 0, gstate_c.curRTHeight, 0, 1); ConvertProjMatrixToVulkanThrough(proj_through); CopyMatrix4x4(ub_base.proj, proj_through.getReadPtr()); } else { @@ -262,7 +262,6 @@ void ShaderManagerVulkan::BaseUpdateUniforms(int dirtyUniforms) { flippedMatrix[8] = -flippedMatrix[8]; flippedMatrix[12] = -flippedMatrix[12]; } - ConvertProjMatrixToVulkan(flippedMatrix, invertedX, invertedY); CopyMatrix4x4(ub_base.proj, flippedMatrix.getReadPtr()); } diff --git a/GPU/Vulkan/StateMappingVulkan.cpp b/GPU/Vulkan/StateMappingVulkan.cpp index 18e0a2e14b..6af78f6c6e 100644 --- a/GPU/Vulkan/StateMappingVulkan.cpp +++ b/GPU/Vulkan/StateMappingVulkan.cpp @@ -32,6 +32,7 @@ #include "GPU/Vulkan/FramebufferVulkan.h" //#include "GPU/Vulkan/PixelShaderGeneratorVulkan.h" +// These tables all fit into u8s. static const VkBlendFactor vkBlendFactorLookup[(size_t)BlendFactor::COUNT] = { VK_BLEND_FACTOR_ZERO, VK_BLEND_FACTOR_ONE, From 4e6a9b81080d2dd6b5dfe28ece24d1afb164a003 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sat, 9 Jan 2016 13:47:48 +0100 Subject: [PATCH 029/116] Fix indexed through-mode drawing --- GPU/Vulkan/DrawEngineVulkan.cpp | 3 ++- ext/native/thin3d/VulkanContext.h | 5 ++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index d81848880e..bc240fa2b3 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -475,6 +475,7 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { VulkanVertexShader *vshader; VulkanFragmentShader *fshader; + // TODO: Keep these between calls if not dirty. uint32_t baseUBOOffset = 0; uint32_t lightUBOOffset = 0; uint32_t boneUBOOffset = 0; @@ -616,7 +617,7 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { VkBuffer buf[1] = { frame->pushData->GetVkBuffer() }; VkDeviceSize offsets[1] = { vbOffset }; if (drawIndexed) { - ibOffset = (uint32_t)frame->pushData->Push(decIndex, 2 * indexGen.VertexCount()); + ibOffset = (uint32_t)frame->pushData->Push(inds, 2 * numTrans); // TODO: Have a buffer per frame, use a walking buffer pointer // TODO: Avoid rebinding if the vertex size stays the same by using the offset arguments vkCmdBindVertexBuffers(cmd_, 0, 1, buf, offsets); diff --git a/ext/native/thin3d/VulkanContext.h b/ext/native/thin3d/VulkanContext.h index da3fbf06fe..dbaa56d0bd 100644 --- a/ext/native/thin3d/VulkanContext.h +++ b/ext/native/thin3d/VulkanContext.h @@ -438,10 +438,13 @@ public: writePtr_ = nullptr; } - size_t Allocate(size_t numBytes) { size_t out = offset_; offset_ += (numBytes + 3) & ~3; // Round up to 4 bytes. + if (offset_ >= size_) { + // For now + DebugBreak(); + } return out; } From 9e34d7d625dc033b0d50c0afe2607e4b64862c5d Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sat, 9 Jan 2016 13:52:27 +0100 Subject: [PATCH 030/116] Remove remains of FragmentTestCache from Vulkan backend --- GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp | 37 +++----------------- ext/native/thin3d/VulkanContext.h | 2 +- 2 files changed, 6 insertions(+), 33 deletions(-) diff --git a/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp b/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp index c42b1bbc82..b6dd01c96e 100644 --- a/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp +++ b/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp @@ -116,13 +116,11 @@ bool GenerateVulkanGLSLFragmentShader(const ShaderID &id, char *buffer) { WRITE(p, "layout (location = 0) %s in vec2 v_texcoord;\n", highpTexcoord ? "highp" : "mediump"); } - if (!g_Config.bFragmentTestCache) { - if (enableAlphaTest && !alphaTestAgainstZero) { - WRITE(p, "int roundAndScaleTo255i(in float x) { return int(floor(x * 255.0 + 0.5)); }\n"); - } - if (enableColorTest && !colorTestAgainstZero) { - WRITE(p, "ivec3 roundAndScaleTo255iv(in vec3 x) { return ivec3(floor(x * 255.0 + 0.5)); }\n"); - } + if (enableAlphaTest && !alphaTestAgainstZero) { + WRITE(p, "int roundAndScaleTo255i(in float x) { return int(floor(x * 255.0 + 0.5)); }\n"); + } + if (enableColorTest && !colorTestAgainstZero) { + WRITE(p, "ivec3 roundAndScaleTo255iv(in vec3 x) { return ivec3(floor(x * 255.0 + 0.5)); }\n"); } WRITE(p, "layout (location = 0) out vec4 fragColor0;\n"); @@ -257,16 +255,6 @@ bool GenerateVulkanGLSLFragmentShader(const ShaderID &id, char *buffer) { // Texture access is at half texels [0.5/256, 255.5/256], but colors are normalized [0, 255]. // So we have to scale to account for the difference. std::string alphaTestXCoord = "0"; - if (g_Config.bFragmentTestCache) { - if (enableColorTest && !colorTestAgainstZero) { - WRITE(p, " vec4 vScale256 = v * %f + %f;\n", 255.0 / 256.0, 0.5 / 256.0); - alphaTestXCoord = "vScale256.a"; - } else if (enableAlphaTest && !alphaTestAgainstZero) { - char temp[64]; - snprintf(temp, sizeof(temp), "v.a * %f + %f", 255.0 / 256.0, 0.5 / 256.0); - alphaTestXCoord = temp; - } - } if (enableAlphaTest) { if (alphaTestAgainstZero) { @@ -282,9 +270,6 @@ bool GenerateVulkanGLSLFragmentShader(const ShaderID &id, char *buffer) { // Maybe we could discard the drawcall, but it's pretty rare. Let's just statically discard here. WRITE(p, " discard;\n"); } - } else if (g_Config.bFragmentTestCache) { - WRITE(p, " float aResult = texture(testtex, vec2(%s, 0)).a;\n", alphaTestXCoord.c_str()); - WRITE(p, " if (aResult < 0.5) discard;\n"); } else { const char *alphaTestFuncs[] = { "#", "#", " != ", " == ", " >= ", " > ", " <= ", " < " }; if (alphaTestFuncs[alphaTestFunc][0] != '#') { @@ -310,18 +295,6 @@ bool GenerateVulkanGLSLFragmentShader(const ShaderID &id, char *buffer) { // Maybe we could discard the drawcall, but it's pretty rare. Let's just statically discard here. WRITE(p, " discard;\n"); } - } else if (g_Config.bFragmentTestCache) { - // texelFetch may make more sense, actually, and we should process colors as integers. - WRITE(p, " float rResult = texture(testtex, vec2(vScale256.r, 0)).r;\n"); - WRITE(p, " float gResult = texture(testtex, vec2(vScale256.g, 0)).g;\n"); - WRITE(p, " float bResult = texture(testtex, vec2(vScale256.b, 0)).b;\n"); - if (colorTestFunc == GE_COMP_EQUAL) { - // Equal means all parts must be equal. - WRITE(p, " if (rResult < 0.5 || gResult < 0.5 || bResult < 0.5) discard;\n"); - } else { - // Not equal means any part must be not equal. - WRITE(p, " if (rResult < 0.5 && gResult < 0.5 && bResult < 0.5) discard;\n"); - } } else { const char *colorTestFuncs[] = { "#", "#", " != ", " == " }; if (colorTestFuncs[colorTestFunc][0] != '#') { diff --git a/ext/native/thin3d/VulkanContext.h b/ext/native/thin3d/VulkanContext.h index dbaa56d0bd..fa35bb33fc 100644 --- a/ext/native/thin3d/VulkanContext.h +++ b/ext/native/thin3d/VulkanContext.h @@ -442,7 +442,7 @@ public: size_t out = offset_; offset_ += (numBytes + 3) & ~3; // Round up to 4 bytes. if (offset_ >= size_) { - // For now + // For now. 4MB is not enough for God of War but lets start with smaller games :P DebugBreak(); } return out; From 7eeba080c72ca14d92fff66c9d9196b55feaa50f Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sat, 9 Jan 2016 17:12:37 +0100 Subject: [PATCH 031/116] Fix primitive topology. Crashfix. --- GPU/Vulkan/DrawEngineVulkan.cpp | 10 ---------- GPU/Vulkan/StateMappingVulkan.cpp | 13 +++++++++++++ ext/native/thin3d/thin3d_vulkan.cpp | 6 ++++-- 3 files changed, 17 insertions(+), 12 deletions(-) diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index bc240fa2b3..90e1e2d580 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -52,16 +52,6 @@ enum { DRAW_BINDING_DYNUBO_BONE = 4, }; -const VkPrimitiveTopology prim[8] = { - VK_PRIMITIVE_TOPOLOGY_POINT_LIST, - VK_PRIMITIVE_TOPOLOGY_LINE_LIST, - VK_PRIMITIVE_TOPOLOGY_LINE_STRIP, - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP, - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN, - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, // Vulkan doesn't do quads. We could do strips with restart-index though. We could also do RECT primitives in the geometry shader. -}; - enum { TRANSFORMED_VERTEX_BUFFER_SIZE = VERTEX_BUFFER_MAX * sizeof(TransformedVertex) }; diff --git a/GPU/Vulkan/StateMappingVulkan.cpp b/GPU/Vulkan/StateMappingVulkan.cpp index 6af78f6c6e..8c2a56c187 100644 --- a/GPU/Vulkan/StateMappingVulkan.cpp +++ b/GPU/Vulkan/StateMappingVulkan.cpp @@ -88,6 +88,17 @@ static const VkStencilOp stencilOps[] = { VK_STENCIL_OP_KEEP, // reserved }; +const VkPrimitiveTopology primToVulkan[8] = { + VK_PRIMITIVE_TOPOLOGY_POINT_LIST, + VK_PRIMITIVE_TOPOLOGY_LINE_LIST, + VK_PRIMITIVE_TOPOLOGY_LINE_STRIP, + VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, + VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP, + VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN, + VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, // Vulkan doesn't do quads. We could do strips with restart-index though. We could also do RECT primitives in the geometry shader. +}; + + bool ApplyShaderBlending() { return false; } @@ -249,6 +260,8 @@ void ConvertStateToVulkanKey(FramebufferManagerVulkan &fbManager, int prim, Vulk } } + key.topology = primToVulkan[prim]; + VkViewport &vp = dynState.viewport; vp.x = vpAndScissor.viewportX; vp.y = vpAndScissor.viewportY; diff --git a/ext/native/thin3d/thin3d_vulkan.cpp b/ext/native/thin3d/thin3d_vulkan.cpp index fbdfc80e57..6a4fc56cad 100644 --- a/ext/native/thin3d/thin3d_vulkan.cpp +++ b/ext/native/thin3d/thin3d_vulkan.cpp @@ -563,8 +563,10 @@ public: private: void Destroy() { ILOG("texture destroyed: %p", this); - vkTex_->Destroy(vulkan_); - delete vkTex_; + if (vkTex_) { + vkTex_->Destroy(vulkan_); + delete vkTex_; + } } VulkanContext *vulkan_; From dced84c9fcb913a5e2d0130b8f3c6db198297609 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sat, 9 Jan 2016 21:19:18 +0100 Subject: [PATCH 032/116] Work on texture support, cube.elf works correctly. Delete unused code. --- GPU/Directx9/TextureCacheDX9.cpp | 1 + GPU/Vulkan/DrawEngineVulkan.cpp | 30 ++++-- GPU/Vulkan/DrawEngineVulkan.h | 17 +-- GPU/Vulkan/GPU_Vulkan.cpp | 10 ++ GPU/Vulkan/PipelineManagerVulkan.cpp | 44 ++++++++ GPU/Vulkan/PipelineManagerVulkan.h | 12 +++ GPU/Vulkan/ShaderManagerVulkan.cpp | 2 +- GPU/Vulkan/ShaderManagerVulkan.h | 4 + GPU/Vulkan/TextureCacheVulkan.cpp | 151 +++++++++++++++------------ GPU/Vulkan/TextureCacheVulkan.h | 40 ++++--- GPU/Vulkan/VulkanUtil.h | 1 - ext/native/native.vcxproj | 2 - ext/native/native.vcxproj.filters | 6 -- ext/native/thin3d/VulkanContext.cpp | 2 +- ext/native/thin3d/VulkanContext.h | 7 +- ext/native/thin3d/thin3d_vulkan.cpp | 5 +- ext/native/thin3d/vulkan_utils.h | 51 --------- 17 files changed, 225 insertions(+), 160 deletions(-) delete mode 100644 ext/native/thin3d/vulkan_utils.h diff --git a/GPU/Directx9/TextureCacheDX9.cpp b/GPU/Directx9/TextureCacheDX9.cpp index c8f2d67084..17eabe5ecc 100644 --- a/GPU/Directx9/TextureCacheDX9.cpp +++ b/GPU/Directx9/TextureCacheDX9.cpp @@ -1639,6 +1639,7 @@ TextureCacheDX9::TexCacheEntry::Status TextureCacheDX9::CheckAlpha(const u32 *pi return (TexCacheEntry::Status)res; } +// TODO: xoffset and yoffset are unused - bug? static inline void copyTexture(int xoffset, int yoffset, int w, int h, int pitch, int srcfmt, int fmt, void * pSrc, void * pDst) { int y; switch(fmt) { diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index 90e1e2d580..84cbed6e6c 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -374,11 +374,11 @@ inline u32 ComputeMiniHashRange(const void *ptr, size_t sz) { } } -VkDescriptorSet DrawEngineVulkan::GetDescriptorSet(CachedTextureVulkan *texture, VkSampler sampler, VkBuffer dynamicUbo) { +VkDescriptorSet DrawEngineVulkan::GetDescriptorSet(VkImageView imageView, VkSampler sampler, VkBuffer dynamicUbo) { DescriptorSetKey key; - key.texture_ = texture; + key.imageView_= imageView; key.sampler_ = sampler; - key.secondaryTexture_ = nullptr; + key.secondaryImageView_ = nullptr; key.buffer_ = dynamicUbo; FrameData *frame = &frame_[curFrame_ & 1]; @@ -403,10 +403,11 @@ VkDescriptorSet DrawEngineVulkan::GetDescriptorSet(CachedTextureVulkan *texture, memset(writes, 0, sizeof(writes)); // Main texture int n = 0; - if (texture) { + if (imageView) { VkDescriptorImageInfo tex; - tex.imageLayout = texture->imageLayout; - tex.imageView = texture->imageView; + // TODO: Also support LAYOUT_GENERAL to be able to texture from framebuffers without transitioning them? + tex.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + tex.imageView = imageView; tex.sampler = sampler; writes[n].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; writes[n].pNext = nullptr; @@ -455,8 +456,21 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { // the three ubo pushes. The reason is that the three UBOs must be in the same buffer as that's how we // designed the descriptor set. - // CachedTextureVulkan *tex = textureCache_->ApplyTexture(); - VkDescriptorSet ds = GetDescriptorSet(nullptr, nullptr, frame->pushData->GetVkBuffer()); + VkImageView imageView = nullptr; + VkSampler sampler = nullptr; + + if (gstate_c.textureChanged != TEXCHANGE_UNCHANGED && !gstate.isModeClear() && gstate.isTextureMapEnabled()) { + textureCache_->SetTexture(); + gstate_c.textureChanged = TEXCHANGE_UNCHANGED; + if (gstate_c.needShaderTexClamp) { + // We will rarely need to set this, so let's do it every time on use rather than in runloop. + // Most of the time non-framebuffer textures will be used which can be clamped themselves. + shaderManager_->DirtyUniform(DIRTY_TEXCLAMP); + } + textureCache_->ApplyTexture(imageView, sampler); + } + + VkDescriptorSet ds = GetDescriptorSet(imageView, sampler, frame->pushData->GetVkBuffer()); GEPrimitiveType prim = prevPrim_; diff --git a/GPU/Vulkan/DrawEngineVulkan.h b/GPU/Vulkan/DrawEngineVulkan.h index 936d8840ff..0622b0d3fe 100644 --- a/GPU/Vulkan/DrawEngineVulkan.h +++ b/GPU/Vulkan/DrawEngineVulkan.h @@ -57,6 +57,9 @@ typedef u64 ReliableHashType; typedef u32 ReliableHashType; #endif +class VulkanContext; +class VulkanPushBuffer; + // Handles transform, lighting and drawing. class DrawEngineVulkan : public DrawEngineCommon { public: @@ -149,7 +152,7 @@ private: void DecodeVertsStep(); void DoFlush(VkCommandBuffer cmd); - VkDescriptorSet GetDescriptorSet(CachedTextureVulkan *texture, VkSampler sampler, VkBuffer dynamicUbo); + VkDescriptorSet GetDescriptorSet(VkImageView imageView, VkSampler sampler, VkBuffer dynamicUbo); VertexDecoder *GetVertexDecoder(u32 vtype); @@ -160,15 +163,17 @@ private: VkPipelineLayout pipelineLayout_; struct DescriptorSetKey { - void *texture_; - void *secondaryTexture_; + VkImageView imageView_; + VkImageView secondaryImageView_; VkSampler sampler_; - VkBuffer buffer_; // All three UBO slots will be set to this. + VkBuffer buffer_; // All three UBO slots will be set to this. This will usually be identical + // for all draws in a frame, except when the buffer has to grow. bool operator < (const DescriptorSetKey &other) const { - if (texture_ < other.texture_) return true; else if (texture_ > other.texture_) return false; + if (imageView_ < other.imageView_) return true; else if (imageView_ > other.imageView_) return false; if (sampler_ < other.sampler_) return true; else if (sampler_ > other.sampler_) return false; - if (secondaryTexture_ < other.secondaryTexture_) return true; else if (secondaryTexture_ > other.secondaryTexture_) return false; + if (secondaryImageView_ < other.secondaryImageView_) return true; else if (secondaryImageView_ > other.secondaryImageView_) return false; + if (buffer_ < other.buffer_) return true; else if (buffer_ > other.buffer_) return false; return false; } }; diff --git a/GPU/Vulkan/GPU_Vulkan.cpp b/GPU/Vulkan/GPU_Vulkan.cpp index 29e9d6f547..2410bb1322 100644 --- a/GPU/Vulkan/GPU_Vulkan.cpp +++ b/GPU/Vulkan/GPU_Vulkan.cpp @@ -475,6 +475,12 @@ void GPU_Vulkan::CheckGPUFeatures() { if (vulkan_->GetFeaturesEnabled().logicOp) { gstate_c.featureFlags |= GPU_SUPPORTS_LOGIC_OP; } + // Mandatory features on Vulkan, which may be checked in "centralized" code + gstate_c.featureFlags |= GPU_SUPPORTS_TEXTURE_LOD_CONTROL; + gstate_c.featureFlags |= GPU_SUPPORTS_FBO; + gstate_c.featureFlags |= GPU_SUPPORTS_BLEND_MINMAX; + gstate_c.featureFlags |= GPU_SUPPORTS_ANY_COPY_IMAGE; + gstate_c.featureFlags |= GPU_SUPPORTS_OES_TEXTURE_NPOT; } void GPU_Vulkan::BeginHostFrame() { @@ -2192,6 +2198,8 @@ bool GPU_Vulkan::DescribeCodePtr(const u8 *ptr, std::string &name) { std::vector GPU_Vulkan::DebugGetShaderIDs(DebugShaderType type) { if (type == SHADER_TYPE_VERTEXLOADER) { return drawEngine_.DebugGetVertexLoaderIDs(); + } else if (type == SHADER_TYPE_PIPELINE) { + return pipelineManager_->DebugGetObjectIDs(type); } else { return shaderManager_->DebugGetShaderIDs(type); } @@ -2200,6 +2208,8 @@ std::vector GPU_Vulkan::DebugGetShaderIDs(DebugShaderType type) { std::string GPU_Vulkan::DebugGetShaderString(std::string id, DebugShaderType type, DebugShaderStringType stringType) { if (type == SHADER_TYPE_VERTEXLOADER) { return drawEngine_.DebugGetVertexLoaderString(id, stringType); + } else if (type == SHADER_TYPE_PIPELINE) { + return pipelineManager_->DebugGetObjectString(id, type, stringType); } else { return shaderManager_->DebugGetShaderString(id, type, stringType); } diff --git a/GPU/Vulkan/PipelineManagerVulkan.cpp b/GPU/Vulkan/PipelineManagerVulkan.cpp index 28883b7ab3..b8751455d9 100644 --- a/GPU/Vulkan/PipelineManagerVulkan.cpp +++ b/GPU/Vulkan/PipelineManagerVulkan.cpp @@ -1,6 +1,7 @@ #include #include "Common/Log.h" +#include "Common/StringUtils.h" #include "GPU/Vulkan/VulkanUtil.h" #include "GPU/Vulkan/PipelineManagerVulkan.h" // #include "GPU/Vulkan/" @@ -298,3 +299,46 @@ VulkanPipeline *PipelineManagerVulkan::GetOrCreatePipeline(VkPipelineLayout layo pipelines_[key] = pipeline; return pipeline; } + +std::vector PipelineManagerVulkan::DebugGetObjectIDs(DebugShaderType type) { + std::string id; + std::vector ids; + switch (type) { + case SHADER_TYPE_PIPELINE: + { + for (auto iter : pipelines_) { + iter.first.ToString(&id); + ids.push_back(id); + } + } + break; + } + return ids; +} + +std::string PipelineManagerVulkan::DebugGetObjectString(std::string id, DebugShaderType type, DebugShaderStringType stringType) { + if (type != SHADER_TYPE_PIPELINE) + return "N/A"; + + VulkanPipelineKey shaderId; + shaderId.FromString(id); + + auto iter = pipelines_.find(shaderId); + if (iter == pipelines_.end()) { + return ""; + } + + switch (stringType) { + case SHADER_STRING_SHORT_DESC: + { + return StringFromFormat("%p", &iter->second); + } + + case SHADER_STRING_SOURCE_CODE: + { + return "N/A"; + } + default: + return "N/A"; + } +} diff --git a/GPU/Vulkan/PipelineManagerVulkan.h b/GPU/Vulkan/PipelineManagerVulkan.h index 3d86e50427..8d9e8d8761 100644 --- a/GPU/Vulkan/PipelineManagerVulkan.h +++ b/GPU/Vulkan/PipelineManagerVulkan.h @@ -52,6 +52,13 @@ struct VulkanPipelineKey { if (fShader < other.fShader) return true; else if (other.fShader < fShader) return false; return false; } + void ToString(std::string *str) const { + str->resize(sizeof(*this)); + memcpy(&(*str)[0], this, sizeof(*this)); + } + void FromString(const std::string &str) { + memcpy(this, &str[0], sizeof(*this)); + } }; enum { @@ -66,6 +73,8 @@ struct VulkanPipeline { int uniformBlocks; // UB_ enum above. }; +class VulkanContext; + class PipelineManagerVulkan { public: PipelineManagerVulkan(VulkanContext *ctx); @@ -74,6 +83,9 @@ public: VulkanPipeline *GetOrCreatePipeline(VkPipelineLayout layout, const VulkanPipelineRasterStateKey &rasterKey, const VertexDecoder *vtxDec, VkShaderModule vShader, VkShaderModule fShader, bool useHwTransform); int GetNumPipelines() const { return 0; } + std::string DebugGetObjectString(std::string id, DebugShaderType type, DebugShaderStringType stringType); + std::vector DebugGetObjectIDs(DebugShaderType type); + private: std::map pipelines_; VkPipelineCache pipelineCache_; diff --git a/GPU/Vulkan/ShaderManagerVulkan.cpp b/GPU/Vulkan/ShaderManagerVulkan.cpp index a9808b584f..dfa435dc32 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.cpp +++ b/GPU/Vulkan/ShaderManagerVulkan.cpp @@ -26,7 +26,7 @@ #include "math/math_util.h" #include "math/dataconv.h" #include "util/text/utf8.h" -#include "thin3d/vulkan_utils.h" +#include "thin3d/VulkanContext.h" #include "Common/Common.h" #include "Core/Config.h" diff --git a/GPU/Vulkan/ShaderManagerVulkan.h b/GPU/Vulkan/ShaderManagerVulkan.h index 7e297598bf..82b0d0e600 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.h +++ b/GPU/Vulkan/ShaderManagerVulkan.h @@ -160,6 +160,8 @@ static const char *ub_vs_bonesStr = R"(mat4 m[8]; )"; +class VulkanContext; +class VulkanPushBuffer; class VulkanFragmentShader { public: @@ -207,6 +209,8 @@ protected: ShaderID id_; }; +class VulkanPushBuffer; + class ShaderManagerVulkan { public: ShaderManagerVulkan(VulkanContext *vulkan); diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index ecc44dcf3a..b988398a3f 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -65,6 +65,11 @@ #define TEXCACHE_MIN_PRESSURE 16 * 1024 * 1024 // Total in GL #define TEXCACHE_SECOND_MIN_PRESSURE 4 * 1024 * 1024 +#define VULKAN_4444_FORMAT VK_FORMAT_R4G4B4A4_UNORM_PACK16 +#define VULKAN_1555_FORMAT VK_FORMAT_A1R5G5B5_UNORM_PACK16 +#define VULKAN_565_FORMAT VK_FORMAT_R5G6B5_UNORM_PACK16 +#define VULKAN_8888_FORMAT VK_FORMAT_R8G8B8A8_UNORM + // Hack! extern int g_iNumVideos; @@ -80,7 +85,7 @@ VkSampler SamplerCache::GetOrCreateSampler(const SamplerCacheKey &key) { return iter->second; } - VkSamplerCreateInfo samp; + VkSamplerCreateInfo samp = {}; samp.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; samp.pNext = nullptr; samp.addressModeU = key.sClamp ? VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE : VK_SAMPLER_ADDRESS_MODE_REPEAT; @@ -88,6 +93,7 @@ VkSampler SamplerCache::GetOrCreateSampler(const SamplerCacheKey &key) { samp.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT; samp.borderColor = VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK; samp.compareEnable = false; + samp.compareOp = VK_COMPARE_OP_ALWAYS; samp.flags = 0; samp.magFilter = (key.magFilt & 1) ? VK_FILTER_LINEAR : VK_FILTER_NEAREST; samp.minFilter = key.minFilt ? VK_FILTER_LINEAR : VK_FILTER_NEAREST; // TODO: Aniso @@ -100,7 +106,7 @@ VkSampler SamplerCache::GetOrCreateSampler(const SamplerCacheKey &key) { VkSampler sampler; VkResult res = vkCreateSampler(vulkan_->GetDevice(), &samp, nullptr, &sampler); - + assert(res == VK_SUCCESS); cache_[key] = sampler; return sampler; } @@ -561,13 +567,13 @@ void *TextureCacheVulkan::ReadIndexedTex(int level, const u8 *texptr, int bytesP VkFormat getClutDestFormatVulkan(GEPaletteFormat format) { switch (format) { case GE_CMODE_16BIT_ABGR4444: - return VK_FORMAT_B4G4R4A4_UNORM_PACK16; + return VULKAN_4444_FORMAT; case GE_CMODE_16BIT_ABGR5551: - return VK_FORMAT_A1R5G5B5_UNORM_PACK16; + return VULKAN_1555_FORMAT; case GE_CMODE_16BIT_BGR5650: - return VK_FORMAT_R5G6B5_UNORM_PACK16; + return VULKAN_565_FORMAT; case GE_CMODE_32BIT_ABGR8888: - return VK_FORMAT_R8G8B8A8_UNORM; + return VULKAN_8888_FORMAT; } return VK_FORMAT_UNDEFINED; } @@ -579,8 +585,7 @@ static const VkFilter MagFiltVK[2] = { VK_FILTER_LINEAR }; -// This should not have to be done per texture! OpenGL is silly yo -void TextureCacheVulkan::UpdateSamplingParams(TexCacheEntry &entry, bool force) { +void TextureCacheVulkan::UpdateSamplingParams(TexCacheEntry &entry, SamplerCacheKey &key) { // TODO: Make GetSamplingParams write SamplerCacheKey directly int minFilt; int magFilt; @@ -588,10 +593,9 @@ void TextureCacheVulkan::UpdateSamplingParams(TexCacheEntry &entry, bool force) bool tClamp; float lodBias; GetSamplingParams(minFilt, magFilt, sClamp, tClamp, lodBias, entry.maxLevel); - - SamplerCacheKey key; key.minFilt = minFilt & 1; - key.mipFilt = (minFilt >> 2) & 1; + key.mipEnable = (minFilt >> 2) & 1; + key.mipFilt = (minFilt >> 1) & 1; key.magFilt = magFilt & 1; key.sClamp = sClamp; key.tClamp = tClamp; @@ -650,14 +654,14 @@ static void ConvertColors(void *dstBuf, const void *srcBuf, VkFormat dstFmt, int const u32 *src = (const u32 *)srcBuf; u32 *dst = (u32 *)dstBuf; switch (dstFmt) { - case VK_FORMAT_B4G4R4A4_UNORM_PACK16: + case VULKAN_4444_FORMAT: ConvertRGBA4444ToABGR4444((u16 *)dst, (const u16 *)src, numPixels); break; // Final Fantasy 2 uses this heavily in animated textures. - case VK_FORMAT_A1R5G5B5_UNORM_PACK16: + case VULKAN_1555_FORMAT: ConvertRGBA5551ToABGR1555((u16 *)dst, (const u16 *)src, numPixels); break; - case VK_FORMAT_R5G6B5_UNORM_PACK16: + case VULKAN_565_FORMAT: ConvertRGB565ToBGR565((u16 *)dst, (const u16 *)src, numPixels); break; default: @@ -841,6 +845,8 @@ void TextureCacheVulkan::SetTextureFramebuffer(TexCacheEntry *entry, VirtualFram void TextureCacheVulkan::ApplyTexture(VkImageView &imageView, VkSampler &sampler) { if (nextTexture_ == nullptr) { + imageView = nullptr; + sampler = nullptr; return; } VkCommandBuffer cmd = nullptr; @@ -867,18 +873,14 @@ void TextureCacheVulkan::ApplyTexture(VkImageView &imageView, VkSampler &sampler nextTexture_->maxSeenV = 512; } } - - imageView = nextTexture_->vkTex->imageView; + imageView = nextTexture_->vkTex->texture_->GetImageView(); SamplerCacheKey key; + UpdateSamplingParams(*nextTexture_, key); sampler = samplerCache_.GetOrCreateSampler(key); - // if (nextTexture_->textureName != lastBoundTexture) { - // nextTexture_->vkTex-> - // lastBoundTexture = nextTexture_->vkTex; - UpdateSamplingParams(*nextTexture_, false); } nextTexture_ = nullptr; @@ -1018,6 +1020,12 @@ void TextureCacheVulkan::ApplyTextureFramebuffer(VkCommandBuffer cmd, TexCacheEn SetFramebufferSamplingParams(framebuffer->bufferWidth, framebuffer->bufferHeight, samplerKey); sampler = GetOrCreateSampler(samplerKey); */ + + SamplerCacheKey key; + UpdateSamplingParams(*nextTexture_, key); + key.mipEnable = false; + sampler = samplerCache_.GetOrCreateSampler(key); + lastBoundTexture = nullptr; } @@ -1056,7 +1064,7 @@ bool TextureCacheVulkan::SetOffsetTexture(u32 offset) { return false; } -void TextureCacheVulkan::SetTexture(VkCommandBuffer cmd, VkImageView &imageView) { +void TextureCacheVulkan::SetTexture() { #ifdef DEBUG_TEXTURES if (SetDebugTexture()) { // A different texture was bound, let's rebind next time. @@ -1075,6 +1083,9 @@ void TextureCacheVulkan::SetTexture(VkCommandBuffer cmd, VkImageView &imageView) const u16 dim = gstate.getTextureDimension(0); int w = gstate.getTextureWidth(0); int h = gstate.getTextureHeight(0); + if (texaddr == 0x04000000 && w == 2 && h == 2) { + // Nonsense bootup texture. Discard. + } GETextureFormat format = gstate.getTextureFormat(); if (format >= 11) { @@ -1308,6 +1319,7 @@ void TextureCacheVulkan::SetTexture(VkCommandBuffer cmd, VkImageView &imageView) if ((bufw == 0 || (gstate.texbufwidth[0] & 0xf800) != 0) && texaddr >= PSP_GetKernelMemoryEnd()) { ERROR_LOG_REPORT(G3D, "Texture with unexpected bufw (full=%d)", gstate.texbufwidth[0] & 0xffff); // Proceeding here can cause a crash. + nextTexture_ = nullptr; return; } @@ -1338,8 +1350,6 @@ void TextureCacheVulkan::SetTexture(VkCommandBuffer cmd, VkImageView &imageView) // For the estimate, we assume cluts always point to 8888 for simplicity. cacheSizeEstimate_ += EstimateTexMemoryUsage(entry); - entry->vkTex = new CachedTextureVulkan(); - // Before we go reading the texture from memory, let's check for render-to-texture. for (size_t i = 0, n = fbCache_.size(); i < n; ++i) { auto framebuffer = fbCache_[i]; @@ -1353,6 +1363,8 @@ void TextureCacheVulkan::SetTexture(VkCommandBuffer cmd, VkImageView &imageView) return; } + entry->vkTex = new CachedTextureVulkan(); + lastBoundTexture = entry->vkTex; // Adjust maxLevel to actually present levels.. @@ -1430,6 +1442,11 @@ void TextureCacheVulkan::SetTexture(VkCommandBuffer cmd, VkImageView &imageView) } } + // Ready or not, here I go... + entry->vkTex->texture_ = new VulkanTexture(); + VulkanTexture *image = entry->vkTex->texture_; + image->Create(vulkan_, w, h, dstFmt); + // GLES2 doesn't have support for a "Max lod" which is critical as PSP games often // don't specify mips all the way down. As a result, we either need to manually generate // the bottom few levels or rely on OpenGL's autogen mipmaps instead, which might not @@ -1462,13 +1479,8 @@ void TextureCacheVulkan::SetTexture(VkCommandBuffer cmd, VkImageView &imageView) gstate_c.textureFullAlpha = entry->GetAlphaStatus() == TexCacheEntry::STATUS_ALPHA_FULL; gstate_c.textureSimpleAlpha = entry->GetAlphaStatus() != TexCacheEntry::STATUS_ALPHA_UNKNOWN; - // This will rebind it, but that's okay. + // TODO: Refactor away nextTexture_. Not needed on Vulkan. nextTexture_ = entry; - UpdateSamplingParams(*entry, true); - - // entry->vkTex->imageView = CreateImageView - - imageView = entry->vkTex->imageView; } VkFormat TextureCacheVulkan::GetDestFormat(GETextureFormat format, GEPaletteFormat clutFormat) const { @@ -1479,11 +1491,11 @@ VkFormat TextureCacheVulkan::GetDestFormat(GETextureFormat format, GEPaletteForm case GE_TFMT_CLUT32: return getClutDestFormatVulkan(clutFormat); case GE_TFMT_4444: - return VK_FORMAT_B4G4R4A4_UNORM_PACK16; + return VULKAN_4444_FORMAT; case GE_TFMT_5551: - return VK_FORMAT_A1R5G5B5_UNORM_PACK16; + return VULKAN_1555_FORMAT; case GE_TFMT_5650: - return VK_FORMAT_R5G6B5_UNORM_PACK16; + return VULKAN_565_FORMAT; case GE_TFMT_8888: case GE_TFMT_DXT1: case GE_TFMT_DXT3: @@ -1739,9 +1751,12 @@ TextureCacheVulkan::TexCacheEntry::Status TextureCacheVulkan::CheckAlpha(const u } void TextureCacheVulkan::LoadTextureLevel(TexCacheEntry &entry, int level, bool replaceImages, int scaleFactor, VkFormat dstFmt) { + CachedTextureVulkan *tex = entry.vkTex; int w = gstate.getTextureWidth(level); int h = gstate.getTextureHeight(level); u32 *pixelData; + int decPitch; + int rowBytes; { PROFILE_THIS_SCOPE("decodetex"); @@ -1754,7 +1769,8 @@ void TextureCacheVulkan::LoadTextureLevel(TexCacheEntry &entry, int level, bool if (finalBuf == NULL) { return; } - + decPitch = w * (dstFmt == VULKAN_8888_FORMAT ? 4 : 2); + rowBytes = decPitch; gpuStats.numTexturesDecoded++; pixelData = (u32 *)finalBuf; @@ -1772,38 +1788,43 @@ void TextureCacheVulkan::LoadTextureLevel(TexCacheEntry &entry, int level, bool } } - /* - GLuint components = dstFmt == GL_UNSIGNED_SHORT_5_6_5 ? GL_RGB : GL_RGBA; - - GLuint components2 = components; - if (replaceImages) { - PROFILE_THIS_SCOPE("repltex"); - glTexSubImage2D(GL_TEXTURE_2D, level, 0, 0, w, h, components2, dstFmt, pixelData); - } else { - PROFILE_THIS_SCOPE("loadtex"); - glTexImage2D(GL_TEXTURE_2D, level, components, w, h, 0, components2, dstFmt, pixelData); - if (!lowMemoryMode_) { - GLenum err = glGetError(); - if (err == GL_OUT_OF_MEMORY) { - WARN_LOG_REPORT(G3D, "Texture cache ran out of GPU memory; switching to low memory mode"); - lowMemoryMode_ = true; - decimationCounter_ = 0; - Decimate(); - // Try again, now that we've cleared out textures in lowMemoryMode_. - glTexImage2D(GL_TEXTURE_2D, level, components, w, h, 0, components2, dstFmt, pixelData); - - I18NCategory *err = GetI18NCategory("Error"); - if (scaleFactor > 1) { - osm.Show(err->T("Warning: Video memory FULL, reducing upscaling and switching to slow caching mode"), 2.0f); - } else { - osm.Show(err->T("Warning: Video memory FULL, switching to slow caching mode"), 2.0f); - } - } else if (err != GL_NO_ERROR) { - // We checked the err anyway, might as well log if there is one. - WARN_LOG(G3D, "Got an error in texture upload: %08x", err); - } - } + // TODO: No support for texture shadows + DebugBreak(); } - */ + + PROFILE_THIS_SCOPE("loadtex"); + + // Upload the texture data. TODO: Decode directly into this buffer. + int rowPitch; + uint8_t *writePtr = entry.vkTex->texture_->Lock(vulkan_, level, &rowPitch); + for (int y = 0; y < h; y++) { + memcpy(writePtr + rowPitch * y, (const uint8_t *)pixelData + decPitch * y, rowBytes); + } + entry.vkTex->texture_->Unlock(vulkan_); + + /* + if (!lowMemoryMode_) { + GLenum err = glGetError(); + if (err == GL_OUT_OF_MEMORY) { + WARN_LOG_REPORT(G3D, "Texture cache ran out of GPU memory; switching to low memory mode"); + lowMemoryMode_ = true; + decimationCounter_ = 0; + Decimate(); + // TODO: We need to stall the GPU here and wipe things out of memory. + + // Try again, now that we've cleared out textures in lowMemoryMode_. + glTexImage2D(GL_TEXTURE_2D, level, components, w, h, 0, components2, dstFmt, pixelData); + + I18NCategory *err = GetI18NCategory("Error"); + if (scaleFactor > 1) { + osm.Show(err->T("Warning: Video memory FULL, reducing upscaling and switching to slow caching mode"), 2.0f); + } else { + osm.Show(err->T("Warning: Video memory FULL, switching to slow caching mode"), 2.0f); + } + } else if (err != GL_NO_ERROR) { + // We checked the err anyway, might as well log if there is one. + WARN_LOG(G3D, "Got an error in texture upload: %08x", err); + } + }*/ } diff --git a/GPU/Vulkan/TextureCacheVulkan.h b/GPU/Vulkan/TextureCacheVulkan.h index f4f94d6918..dd70514c3f 100644 --- a/GPU/Vulkan/TextureCacheVulkan.h +++ b/GPU/Vulkan/TextureCacheVulkan.h @@ -22,6 +22,7 @@ #include "Globals.h" #include "GPU/GPUInterface.h" #include "GPU/GPUState.h" +#include "thin3d/VulkanContext.h" #include "GPU/Vulkan/TextureScalerVulkan.h" #include "GPU/Common/TextureCacheCommon.h" @@ -32,26 +33,39 @@ class ShaderManagerVulkan; class DrawEngineVulkan; class VulkanContext; +class VulkanImage; struct SamplerCacheKey { - bool minFilt : 1; - bool mipFilt : 1; - bool magFilt : 1; - bool sClamp : 1; - bool tClamp : 1; - int lodBias : 4; - int maxLevel : 4; + SamplerCacheKey() : fullKey(0) {} + + union { + u32 fullKey; + struct { + bool mipEnable : 1; + bool minFilt : 1; + bool mipFilt : 1; + bool magFilt : 1; + bool sClamp : 1; + bool tClamp : 1; + int lodBias : 4; + int maxLevel : 4; + }; + }; bool operator < (const SamplerCacheKey &other) const { - return memcmp(this, &other, sizeof(*this)) < 0; + return fullKey < other.fullKey; } }; -// texturePtr points to these. class CachedTextureVulkan { public: - VkImageView imageView; - VkImageLayout imageLayout; + CachedTextureVulkan() : texture_(nullptr) { + } + ~CachedTextureVulkan() { + delete texture_; + } + // TODO: Switch away from VulkanImage to some kind of smart suballocating texture pool. + VulkanTexture *texture_; }; class SamplerCache { @@ -71,7 +85,7 @@ public: TextureCacheVulkan(VulkanContext *vulkan); ~TextureCacheVulkan(); - void SetTexture(VkCommandBuffer cmd, VkImageView &imageView); + void SetTexture(); virtual bool SetOffsetTexture(u32 offset) override; void Clear(bool delete_them); @@ -111,7 +125,7 @@ private: void Decimate(); // Run this once per frame to get rid of old textures. void DeleteTexture(TexCache::iterator it); void *ReadIndexedTex(int level, const u8 *texptr, int bytesPerIndex, VkFormat dstFmt, int bufw); - void UpdateSamplingParams(TexCacheEntry &entry, bool force); + void UpdateSamplingParams(TexCacheEntry &entry, SamplerCacheKey &key); void LoadTextureLevel(TexCacheEntry &entry, int level, bool replaceImages, int scaleFactor, VkFormat dstFmt); VkFormat GetDestFormat(GETextureFormat format, GEPaletteFormat clutFormat) const; void *DecodeTextureLevel(GETextureFormat format, GEPaletteFormat clutformat, int level, u32 &texByteAlign, VkFormat dstFmt, int scaleFactor, int *bufw = 0); diff --git a/GPU/Vulkan/VulkanUtil.h b/GPU/Vulkan/VulkanUtil.h index 4b0ebdbda3..4899ff2b3a 100644 --- a/GPU/Vulkan/VulkanUtil.h +++ b/GPU/Vulkan/VulkanUtil.h @@ -2,5 +2,4 @@ #define VK_PROTOTYPES #include "ext/vulkan/vulkan.h" -#include "thin3d/vulkan_utils.h" diff --git a/ext/native/native.vcxproj b/ext/native/native.vcxproj index 62927609fd..9557ba566e 100644 --- a/ext/native/native.vcxproj +++ b/ext/native/native.vcxproj @@ -267,7 +267,6 @@ - @@ -731,7 +730,6 @@ - diff --git a/ext/native/native.vcxproj.filters b/ext/native/native.vcxproj.filters index ba91f6e506..a278eba455 100644 --- a/ext/native/native.vcxproj.filters +++ b/ext/native/native.vcxproj.filters @@ -305,9 +305,6 @@ file - - thin3d - math @@ -748,9 +745,6 @@ file - - thin3d - thin3d diff --git a/ext/native/thin3d/VulkanContext.cpp b/ext/native/thin3d/VulkanContext.cpp index 434628f54c..a1f3272547 100644 --- a/ext/native/thin3d/VulkanContext.cpp +++ b/ext/native/thin3d/VulkanContext.cpp @@ -1190,7 +1190,7 @@ void VulkanTexture::Create(VulkanContext *vulkan, int w, int h, VkFormat format) assert(res == VK_SUCCESS); } -uint8_t *VulkanTexture::Lock(VulkanContext *vulkan, int *rowPitch) { +uint8_t *VulkanTexture::Lock(VulkanContext *vulkan, int level, int *rowPitch) { VkImageSubresource subres = {}; subres.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; subres.mipLevel = 0; diff --git a/ext/native/thin3d/VulkanContext.h b/ext/native/thin3d/VulkanContext.h index fa35bb33fc..b9e754f7ce 100644 --- a/ext/native/thin3d/VulkanContext.h +++ b/ext/native/thin3d/VulkanContext.h @@ -348,17 +348,18 @@ public: VkDeviceMemory mem; VkImageView view; - int32_t tex_width, tex_height; - // Always call Create, Lock, Unlock. Unlock performs the upload if necessary. void Create(VulkanContext *vulkan, int w, int h, VkFormat format); - uint8_t *Lock(VulkanContext *vulkan, int *rowPitch); + uint8_t *Lock(VulkanContext *vulkan, int level, int *rowPitch); void Unlock(VulkanContext *vulkan); void Destroy(VulkanContext *vulkan); + VkImageView GetImageView() const { return view; } + private: + int32_t tex_width, tex_height; VkFormat format_; VkImage mappableImage; VkDeviceMemory mappableMemory; diff --git a/ext/native/thin3d/thin3d_vulkan.cpp b/ext/native/thin3d/thin3d_vulkan.cpp index 6a4fc56cad..b04c10e348 100644 --- a/ext/native/thin3d/thin3d_vulkan.cpp +++ b/ext/native/thin3d/thin3d_vulkan.cpp @@ -30,7 +30,6 @@ #include "math/lin/matrix4x4.h" #include "math/dataconv.h" #include "thin3d/thin3d.h" -#include "thin3d/vulkan_utils.h" #include "thin3d/VulkanContext.h" // We use a simple descriptor set for all rendering: 1 sampler, 1 texture, 1 UBO binding point. @@ -558,7 +557,7 @@ public: void Finalize(int zim_flags) override; void AutoGenMipmaps() {} - VkImageView GetImageView() { return vkTex_->view; } + VkImageView GetImageView() { return vkTex_->GetImageView(); } private: void Destroy() { @@ -958,7 +957,7 @@ void Thin3DVKTexture::SetImageData(int x, int y, int z, int width, int height, i int bytesPerPixel = bpp / 8; vkTex_->Create(vulkan_, width, height, vulkanFormat); int rowPitch; - uint8_t *dstData = vkTex_->Lock(vulkan_, &rowPitch); + uint8_t *dstData = vkTex_->Lock(vulkan_, 0, &rowPitch); for (int y = 0; y < height; y++) { memcpy(dstData + rowPitch * y, data + stride * y, width * bytesPerPixel); } diff --git a/ext/native/thin3d/vulkan_utils.h b/ext/native/thin3d/vulkan_utils.h deleted file mode 100644 index d9daa4c998..0000000000 --- a/ext/native/thin3d/vulkan_utils.h +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) 2015- PPSSPP Project. - -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, version 2.0 or later versions. - -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License 2.0 for more details. - -// A copy of the GPL 2.0 should have been included with the program. -// If not, see http://www.gnu.org/licenses/ - -// Official git repository and contact information can be found at -// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. - -#pragma once - -#include - -#define VK_PROTOTYPES -#include "ext/vulkan/vulkan.h" -#include "VulkanContext.h" - -class VulkanContext; - -// Utility class to handle images without going insane. -// Allocates its own memory. -class VulkanImage { -public: - VulkanImage() : image_(nullptr), memory_(nullptr) {} - - bool IsValid() const { return image_ != nullptr; } - // This can be done completely unsynchronized. - void Create2D(VulkanContext *vulkan, VkFormat format, VkFlags required_props, VkImageTiling tiling, VkImageUsageFlags usage, int width, int height); - - // This can only be used if you pass in VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT in required_props in Create2D. - void SetImageData2D(VkDevice device, const uint8_t *data, int width, int height, int pitch); - void ChangeLayout(VkCommandBuffer cmd, VkImageAspectFlags aspectMask, VkImageLayout old_image_layout, VkImageLayout new_image_layout); - VkImage GetImage() const { - return image_; - } - -private: - VkMemoryAllocateInfo mem_alloc_; - VkImage image_; - VkDeviceMemory memory_; - int width_; - int height_; -}; From 78d5fff2fe87e8d9ecd6a99e7c6d5f6dcffe40e4 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sat, 9 Jan 2016 21:54:57 +0100 Subject: [PATCH 033/116] More texture work --- GPU/Vulkan/GPU_Vulkan.cpp | 2 +- GPU/Vulkan/ShaderManagerVulkan.h | 3 ++- GPU/Vulkan/TextureCacheVulkan.cpp | 22 ++++++++++++++-------- 3 files changed, 17 insertions(+), 10 deletions(-) diff --git a/GPU/Vulkan/GPU_Vulkan.cpp b/GPU/Vulkan/GPU_Vulkan.cpp index 2410bb1322..426b004252 100644 --- a/GPU/Vulkan/GPU_Vulkan.cpp +++ b/GPU/Vulkan/GPU_Vulkan.cpp @@ -320,7 +320,7 @@ static const CommandTableEntry commandTable[] = { { GE_CMD_BOUNDINGBOX, FLAG_EXECUTE, 0, &GPU_Vulkan::Execute_BoundingBox }, // + FLUSHBEFORE when we implement... or not, do we need to? // Changing the vertex type requires us to flush. - { GE_CMD_VERTEXTYPE, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_VertexType }, + { GE_CMD_VERTEXTYPE, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_PROJMATRIX, &GPU_Vulkan::Execute_VertexType }, { GE_CMD_BEZIER, FLAG_FLUSHBEFORE | FLAG_EXECUTE, 0, &GPU_Vulkan::Execute_Bezier }, { GE_CMD_SPLINE, FLAG_FLUSHBEFORE | FLAG_EXECUTE, 0, &GPU_Vulkan::Execute_Spline }, diff --git a/GPU/Vulkan/ShaderManagerVulkan.h b/GPU/Vulkan/ShaderManagerVulkan.h index 82b0d0e600..0c3eb7385a 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.h +++ b/GPU/Vulkan/ShaderManagerVulkan.h @@ -34,6 +34,7 @@ void ConvertProjMatrixToVulkan(Matrix4x4 & in); // Pretty much full. Will need more bits for more fine grained dirty tracking for lights. enum { DIRTY_PROJMATRIX = (1 << 0), + // 1 << 1 is free DIRTY_FOGCOLOR = (1 << 2), DIRTY_FOGCOEF = (1 << 3), DIRTY_TEXENV = (1 << 4), @@ -58,7 +59,7 @@ enum { DIRTY_DEPTHRANGE = (1 << 20), DIRTY_WORLDMATRIX = (1 << 21), - DIRTY_VIEWMATRIX = (1 << 22), // Maybe we'll fold this into projmatrix eventually + DIRTY_VIEWMATRIX = (1 << 22), DIRTY_TEXMATRIX = (1 << 23), DIRTY_BONEMATRIX0 = (1 << 24), DIRTY_BONEMATRIX1 = (1 << 25), diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index b988398a3f..900f169890 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -1281,6 +1281,7 @@ void TextureCacheVulkan::SetTexture() { lastBoundTexture = nullptr; } delete entry->vkTex; + entry->vkTex = nullptr; } } // Clear the reliable bit if set. @@ -1363,10 +1364,6 @@ void TextureCacheVulkan::SetTexture() { return; } - entry->vkTex = new CachedTextureVulkan(); - - lastBoundTexture = entry->vkTex; - // Adjust maxLevel to actually present levels.. bool badMipSizes = false; for (u32 i = 0; i <= maxLevel; i++) { @@ -1443,9 +1440,17 @@ void TextureCacheVulkan::SetTexture() { } // Ready or not, here I go... - entry->vkTex->texture_ = new VulkanTexture(); - VulkanTexture *image = entry->vkTex->texture_; - image->Create(vulkan_, w, h, dstFmt); + if (replaceImages) { + if (!entry->vkTex) { + DebugBreak(); + } + } else { + entry->vkTex = new CachedTextureVulkan(); + entry->vkTex->texture_ = new VulkanTexture(); + VulkanTexture *image = entry->vkTex->texture_; + image->Create(vulkan_, w, h, dstFmt); + } + lastBoundTexture = entry->vkTex; // GLES2 doesn't have support for a "Max lod" which is critical as PSP games often // don't specify mips all the way down. As a result, we either need to manually generate @@ -1453,6 +1458,7 @@ void TextureCacheVulkan::SetTexture() { // be as good quality as the game's own (might even be better in some cases though). // Always load base level texture here + LoadTextureLevel(*entry, 0, replaceImages, scaleFactor, dstFmt); // Mipmapping only enable when texture scaling disable @@ -1790,7 +1796,7 @@ void TextureCacheVulkan::LoadTextureLevel(TexCacheEntry &entry, int level, bool if (replaceImages) { // TODO: No support for texture shadows - DebugBreak(); + // DebugBreak(); } PROFILE_THIS_SCOPE("loadtex"); From 87b743e92259ca74f82cb082bace3c447bb47a84 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sat, 9 Jan 2016 22:14:19 +0100 Subject: [PATCH 034/116] Fix issues with texture replacement --- GPU/Vulkan/DrawEngineVulkan.cpp | 9 +++-- ext/native/thin3d/VulkanContext.cpp | 61 ++++++++++++++++++++--------- ext/native/thin3d/VulkanContext.h | 20 ++++++---- 3 files changed, 62 insertions(+), 28 deletions(-) diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index 84cbed6e6c..ee56b0a9bf 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -178,6 +178,7 @@ DrawEngineVulkan::DrawEngineVulkan(VulkanContext *vulkan) void DrawEngineVulkan::BeginFrame() { FrameData *frame = &frame_[curFrame_ & 1]; vkResetDescriptorPool(vulkan_->GetDevice(), frame->descPool, 0); + frame->descSets.clear(); frame->pushData->Begin(vulkan_->GetDevice()); frame->pushData->Reset(); } @@ -376,7 +377,7 @@ inline u32 ComputeMiniHashRange(const void *ptr, size_t sz) { VkDescriptorSet DrawEngineVulkan::GetDescriptorSet(VkImageView imageView, VkSampler sampler, VkBuffer dynamicUbo) { DescriptorSetKey key; - key.imageView_= imageView; + key.imageView_ = imageView; key.sampler_ = sampler; key.secondaryImageView_ = nullptr; key.buffer_ = dynamicUbo; @@ -387,7 +388,8 @@ VkDescriptorSet DrawEngineVulkan::GetDescriptorSet(VkImageView imageView, VkSamp return iter->second; } - // Didn't find one in the frame cache, let's make a new one. + // Didn't find one in the frame descriptor set cache, let's make a new one. + // We wipe the cache on every frame. VkDescriptorSet desc; VkDescriptorSetAllocateInfo descAlloc; @@ -396,7 +398,8 @@ VkDescriptorSet DrawEngineVulkan::GetDescriptorSet(VkImageView imageView, VkSamp descAlloc.pSetLayouts = &descriptorSetLayout_; descAlloc.descriptorPool = frame->descPool; descAlloc.descriptorSetCount = 1; - vkAllocateDescriptorSets(vulkan_->GetDevice(), &descAlloc, &desc); + VkResult result = vkAllocateDescriptorSets(vulkan_->GetDevice(), &descAlloc, &desc); + assert(result == VK_SUCCESS); // We just don't write to the slots we don't care about. VkWriteDescriptorSet writes[4]; diff --git a/ext/native/thin3d/VulkanContext.cpp b/ext/native/thin3d/VulkanContext.cpp index a1f3272547..c254cd930a 100644 --- a/ext/native/thin3d/VulkanContext.cpp +++ b/ext/native/thin3d/VulkanContext.cpp @@ -1131,25 +1131,41 @@ void VulkanContext::InitCommandPool() { assert(res == VK_SUCCESS); } -void VulkanTexture::Create(VulkanContext *vulkan, int w, int h, VkFormat format) { +VkResult VulkanTexture::Create(VulkanContext *vulkan, int w, int h, VkFormat format) { tex_width = w; tex_height = h; format_ = format; - bool U_ASSERT_ONLY pass; - VkFormatProperties formatProps; vkGetPhysicalDeviceFormatProperties(vulkan->GetPhysicalDevice(), format, &formatProps); // See if we can use a linear tiled image for a texture, if not, we will need a staging image for the texture data. // Linear tiling is usually only supported for 2D non-array textures. - needStaging = (!(formatProps.linearTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)) ? true : false; + // needStaging = (!(formatProps.linearTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)) ? true : false; + // Always stage. + needStaging = true; + + return VK_SUCCESS; +} + +void VulkanTexture::CreateMappableImage(VulkanContext *vulkan) { + // If we already have a mappableImage, forget it. + if (mappableImage) { + vulkan->QueueDelete(mappableImage); + mappableImage = nullptr; + } + if (mappableMemory) { + vulkan->QueueDelete(mappableMemory); + mappableMemory = nullptr; + } + + bool U_ASSERT_ONLY pass; VkImageCreateInfo image_create_info = {}; image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; image_create_info.pNext = NULL; image_create_info.imageType = VK_IMAGE_TYPE_2D; - image_create_info.format = format; + image_create_info.format = format_; image_create_info.extent.width = tex_width; image_create_info.extent.height = tex_height; image_create_info.extent.depth = 1; @@ -1169,8 +1185,8 @@ void VulkanTexture::Create(VulkanContext *vulkan, int w, int h, VkFormat format) mem_alloc.allocationSize = 0; mem_alloc.memoryTypeIndex = 0; - /* Create a mappable image. It will be the texture if linear images are ok to be textures */ - /* or it will be the staging image if they are not. */ + // Create a mappable image. It will be the texture if linear images are ok to be textures + // or it will be the staging image if they are not. VkResult res = vkCreateImage(vulkan->GetDevice(), &image_create_info, NULL, &mappableImage); assert(res == VK_SUCCESS); @@ -1179,7 +1195,7 @@ void VulkanTexture::Create(VulkanContext *vulkan, int w, int h, VkFormat format) mem_alloc.allocationSize = mem_reqs.size; - /* Find the memory type that is host mappable */ + // Find the memory type that is host mappable. pass = vulkan->MemoryTypeFromProperties(mem_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, &mem_alloc.memoryTypeIndex); assert(pass); @@ -1191,6 +1207,8 @@ void VulkanTexture::Create(VulkanContext *vulkan, int w, int h, VkFormat format) } uint8_t *VulkanTexture::Lock(VulkanContext *vulkan, int level, int *rowPitch) { + CreateMappableImage(vulkan); + VkImageSubresource subres = {}; subres.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; subres.mipLevel = 0; @@ -1199,10 +1217,9 @@ uint8_t *VulkanTexture::Lock(VulkanContext *vulkan, int level, int *rowPitch) { VkSubresourceLayout layout; void *data; - /* Get the subresource layout so we know what the row pitch is */ + // Get the subresource layout so we know what the row pitch is vkGetImageSubresourceLayout(vulkan->GetDevice(), mappableImage, &subres, &layout); - - VkResult res = vkMapMemory(vulkan->GetDevice(), mappableMemory, 0, mem_reqs.size, 0, &data); + VkResult res = vkMapMemory(vulkan->GetDevice(), mappableMemory, layout.offset, layout.size, 0, &data); assert(res == VK_SUCCESS); *rowPitch = (int)layout.rowPitch; @@ -1214,6 +1231,15 @@ void VulkanTexture::Unlock(VulkanContext *vulkan) { VkCommandBuffer cmd = vulkan->GetInitCommandBuffer(); + // if we already have an image, queue it for destruction and forget it. + if (image) { + vulkan->QueueDelete(image); + image = nullptr; + } + if (view) { + vulkan->QueueDelete(view); + view = nullptr; + } if (!needStaging) { /* If we can use the linear tiled image as a texture, just do it */ image = mappableImage; @@ -1253,26 +1279,23 @@ void VulkanTexture::Unlock(VulkanContext *vulkan) { mem_alloc.memoryTypeIndex = 0; mem_alloc.allocationSize = mem_reqs.size; - /* Find memory type - dont specify any mapping requirements */ + // Find memory type - don't specify any mapping requirements bool pass = vulkan->MemoryTypeFromProperties(mem_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &mem_alloc.memoryTypeIndex); assert(pass); - /* allocate memory */ res = vkAllocateMemory(vulkan->GetDevice(), &mem_alloc, NULL, &mem); assert(res == VK_SUCCESS); - /* bind memory */ res = vkBindImageMemory(vulkan->GetDevice(), image, mem, 0); assert(res == VK_SUCCESS); - /* Since we're going to blit from the mappable image, set its layout to SOURCE_OPTIMAL */ - /* Side effect is that this will create info.cmd */ + // Since we're going to blit from the mappable image, set its layout to SOURCE_OPTIMAL TransitionImageLayout(cmd, mappableImage, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); - /* Since we're going to blit to the texture image, set its layout to DESTINATION_OPTIMAL */ + // Since we're going to blit to the texture image, set its layout to DESTINATION_OPTIMAL TransitionImageLayout(cmd, image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED, @@ -1305,7 +1328,7 @@ void VulkanTexture::Unlock(VulkanContext *vulkan) { assert(res == VK_SUCCESS); - /* Set the layout for the texture image from DESTINATION_OPTIMAL to SHADER_READ_ONLY */ + // Set the layout for the texture image from DESTINATION_OPTIMAL to SHADER_READ_ONLY imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; TransitionImageLayout(cmd, image, VK_IMAGE_ASPECT_COLOR_BIT, @@ -1314,6 +1337,8 @@ void VulkanTexture::Unlock(VulkanContext *vulkan) { vulkan->QueueDelete(mappableMemory); vulkan->QueueDelete(mappableImage); + mappableImage = nullptr; + mappableMemory = nullptr; } VkImageViewCreateInfo view_info = {}; diff --git a/ext/native/thin3d/VulkanContext.h b/ext/native/thin3d/VulkanContext.h index b9e754f7ce..51093503e2 100644 --- a/ext/native/thin3d/VulkanContext.h +++ b/ext/native/thin3d/VulkanContext.h @@ -342,15 +342,15 @@ private: // Only supports simple 2D textures for now. Mipmap support will be added later. class VulkanTexture { public: - VkImage image; - VkImageLayout imageLayout; - - VkDeviceMemory mem; - VkImageView view; - + VulkanTexture() + : image(nullptr), mem(nullptr), view(nullptr), tex_width(0), tex_height(0), format_(VK_FORMAT_UNDEFINED), + mappableImage(nullptr), mappableMemory(nullptr) { + } // Always call Create, Lock, Unlock. Unlock performs the upload if necessary. + // Can later Lock and Unlock again. This cannot change the format. Create cannot + // be called a second time without recreating the texture object. - void Create(VulkanContext *vulkan, int w, int h, VkFormat format); + VkResult Create(VulkanContext *vulkan, int w, int h, VkFormat format); uint8_t *Lock(VulkanContext *vulkan, int level, int *rowPitch); void Unlock(VulkanContext *vulkan); @@ -359,6 +359,12 @@ public: VkImageView GetImageView() const { return view; } private: + void CreateMappableImage(VulkanContext *vulkan); + + VkImage image; + VkImageLayout imageLayout; + VkDeviceMemory mem; + VkImageView view; int32_t tex_width, tex_height; VkFormat format_; VkImage mappableImage; From b51b38f97c104eef48909abe4858897157a414b9 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sat, 9 Jan 2016 23:27:13 +0100 Subject: [PATCH 035/116] Switch to "Mailbox" frame submission if available, lets us go beyond 60hz for unthrottle --- Windows/GPU/WindowsVulkanContext.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Windows/GPU/WindowsVulkanContext.cpp b/Windows/GPU/WindowsVulkanContext.cpp index f9e3a7fc44..1e36cff290 100644 --- a/Windows/GPU/WindowsVulkanContext.cpp +++ b/Windows/GPU/WindowsVulkanContext.cpp @@ -157,7 +157,7 @@ bool WindowsVulkanContext::Init(HINSTANCE hInst, HWND hWnd, std::string *error_m g_LogOptions.breakOnWarning = true; g_LogOptions.msgBoxOnError = false; - g_Vulkan = new VulkanContext("PPSSPP", g_validate_ ? VULKAN_FLAG_VALIDATE : 0); + g_Vulkan = new VulkanContext("PPSSPP", (g_validate_ ? VULKAN_FLAG_VALIDATE : 0) | VULKAN_FLAG_PRESENT_MAILBOX); g_Vulkan->CreateDevice(0); if (g_validate_) { int bits = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT; From 29341e53a58290c3830248f4315dcd05a05a63e5 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sat, 9 Jan 2016 23:27:53 +0100 Subject: [PATCH 036/116] Assorted fixes and cleanups. --- GPU/Vulkan/DrawEngineVulkan.cpp | 45 ++++++++++++---------- GPU/Vulkan/PipelineManagerVulkan.cpp | 6 +-- GPU/Vulkan/ShaderManagerVulkan.cpp | 3 ++ GPU/Vulkan/ShaderManagerVulkan.h | 2 +- GPU/Vulkan/StateMappingVulkan.cpp | 13 ++++--- GPU/Vulkan/StateMappingVulkan.h | 4 +- GPU/Vulkan/TextureCacheVulkan.cpp | 33 ++++------------ GPU/Vulkan/VertexShaderGeneratorVulkan.cpp | 20 +++++----- ext/native/thin3d/VulkanContext.cpp | 1 - ext/native/thin3d/VulkanContext.h | 4 +- 10 files changed, 62 insertions(+), 69 deletions(-) diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index ee56b0a9bf..139eac9296 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -19,6 +19,7 @@ #include "base/logging.h" #include "base/timeutil.h" +#include "math/dataconv.h" #include "Common/MemoryUtil.h" #include "Core/MemMap.h" @@ -148,7 +149,7 @@ DrawEngineVulkan::DrawEngineVulkan(VulkanContext *vulkan) for (int i = 0; i < 2; i++) { VkResult res = vkCreateDescriptorPool(vulkan_->GetDevice(), &dp, nullptr, &frame_[i].descPool); assert(VK_SUCCESS == res); - frame_[i].pushData = new VulkanPushBuffer(vulkan_, 4 * 1024 * 1024); // TODO: Do something more dynamic + frame_[i].pushData = new VulkanPushBuffer(vulkan_, 32 * 1024 * 1024); // TODO: Do something more dynamic } VkPipelineLayoutCreateInfo pl; @@ -175,20 +176,6 @@ DrawEngineVulkan::DrawEngineVulkan(VulkanContext *vulkan) assert(VK_SUCCESS == res); } -void DrawEngineVulkan::BeginFrame() { - FrameData *frame = &frame_[curFrame_ & 1]; - vkResetDescriptorPool(vulkan_->GetDevice(), frame->descPool, 0); - frame->descSets.clear(); - frame->pushData->Begin(vulkan_->GetDevice()); - frame->pushData->Reset(); -} - -void DrawEngineVulkan::EndFrame() { - FrameData *frame = &frame_[curFrame_ & 1]; - frame->pushData->End(vulkan_->GetDevice()); - curFrame_++; -} - DrawEngineVulkan::~DrawEngineVulkan() { FreeMemoryPages(decoded, DECODED_VERTEX_BUFFER_SIZE); FreeMemoryPages(decIndex, DECODED_INDEX_BUFFER_SIZE); @@ -203,6 +190,20 @@ DrawEngineVulkan::~DrawEngineVulkan() { vulkan_->QueueDelete(depalSampler_); } +void DrawEngineVulkan::BeginFrame() { + FrameData *frame = &frame_[curFrame_ & 1]; + vkResetDescriptorPool(vulkan_->GetDevice(), frame->descPool, 0); + frame->descSets.clear(); + frame->pushData->Begin(vulkan_->GetDevice()); + frame->pushData->Reset(); +} + +void DrawEngineVulkan::EndFrame() { + FrameData *frame = &frame_[curFrame_ & 1]; + frame->pushData->End(vulkan_->GetDevice()); + curFrame_++; +} + VertexDecoder *DrawEngineVulkan::GetVertexDecoder(u32 vtype) { auto iter = decoderMap_.find(vtype); if (iter != decoderMap_.end()) @@ -402,7 +403,7 @@ VkDescriptorSet DrawEngineVulkan::GetDescriptorSet(VkImageView imageView, VkSamp assert(result == VK_SUCCESS); // We just don't write to the slots we don't care about. - VkWriteDescriptorSet writes[4]; + VkWriteDescriptorSet writes[2]; memset(writes, 0, sizeof(writes)); // Main texture int n = 0; @@ -514,14 +515,16 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { VulkanPipelineRasterStateKey pipelineKey; VulkanDynamicState dynState; - ConvertStateToVulkanKey(*framebufferManager_, prim, pipelineKey, dynState); + ConvertStateToVulkanKey(*framebufferManager_, shaderManager_, prim, pipelineKey, dynState); // TODO: Dirty-flag these. vkCmdSetScissor(cmd_, 0, 1, &dynState.scissor); vkCmdSetViewport(cmd_, 0, 1, &dynState.viewport); vkCmdSetStencilReference(cmd_, VK_STENCIL_FRONT_AND_BACK, dynState.stencilRef); vkCmdSetStencilWriteMask(cmd_, VK_STENCIL_FRONT_AND_BACK, dynState.stencilWriteMask); vkCmdSetStencilCompareMask(cmd_, VK_STENCIL_FRONT_AND_BACK, dynState.stencilCompareMask); - // vkCmdSetBlendConstants(cmd_, dynState.blendColor); + float bc[4]; + Uint8x4ToFloat4(bc, dynState.blendColor); + vkCmdSetBlendConstants(cmd_, bc); shaderManager_->UpdateUniforms(); shaderManager_->GetShaders(prim, lastVType_, &vshader, &fshader, useHWTransform); VulkanPipeline *pipeline = pipelineManager_->GetOrCreatePipeline(pipelineLayout_, pipelineKey, dec_, vshader->GetModule(), fshader->GetModule(), true); @@ -589,7 +592,7 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { if (result.action == SW_DRAW_PRIMITIVES) { VulkanPipelineRasterStateKey pipelineKey; VulkanDynamicState dynState; - ConvertStateToVulkanKey(*framebufferManager_, prim, pipelineKey, dynState); + ConvertStateToVulkanKey(*framebufferManager_, shaderManager_, prim, pipelineKey, dynState); // TODO: Dirty-flag these. vkCmdSetScissor(cmd_, 0, 1, &dynState.scissor); vkCmdSetViewport(cmd_, 0, 1, &dynState.viewport); @@ -604,7 +607,9 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { vkCmdSetStencilReference(cmd_, VK_STENCIL_FRONT_AND_BACK, dynState.stencilRef); } - // vkCmdSetBlendConstants(cmd_, dynState.blendColor); + float bc[4]; + Uint8x4ToFloat4(bc, dynState.blendColor); + vkCmdSetBlendConstants(cmd_, bc); shaderManager_->UpdateUniforms(); shaderManager_->GetShaders(prim, lastVType_, &vshader, &fshader, useHWTransform); VulkanPipeline *pipeline = pipelineManager_->GetOrCreatePipeline(pipelineLayout_, pipelineKey, dec_, vshader->GetModule(), fshader->GetModule(), false); diff --git a/GPU/Vulkan/PipelineManagerVulkan.cpp b/GPU/Vulkan/PipelineManagerVulkan.cpp index b8751455d9..89034ff8e4 100644 --- a/GPU/Vulkan/PipelineManagerVulkan.cpp +++ b/GPU/Vulkan/PipelineManagerVulkan.cpp @@ -34,7 +34,7 @@ static const DeclTypeInfo VComp[] = { { VK_FORMAT_R32G32B32_SFLOAT, "R32G32B32_SFLOAT " }, // DEC_FLOAT_3, { VK_FORMAT_R32G32B32A32_SFLOAT, "R32G32B32A32_SFLOAT " }, // DEC_FLOAT_4, - { VK_FORMAT_R8G8B8A8_SNORM, "UNDEFINED" }, // DEC_S8_3, + { VK_FORMAT_R8G8B8A8_SNORM, "R8G8B8A8_SNORM" }, // DEC_S8_3, { VK_FORMAT_R16G16B16A16_SNORM, "R16G16B16A16_SNORM " }, // DEC_S16_3, { VK_FORMAT_R8G8B8A8_UNORM, "R8G8B8A8_UNORM " }, // DEC_U8_1, @@ -46,8 +46,8 @@ static const DeclTypeInfo VComp[] = { { VK_FORMAT_R16G16B16A16_UNORM, "R16G16B16A16_UNORM " }, // DEC_U16_3, { VK_FORMAT_R16G16B16A16_UNORM, "R16G16B16A16_UNORM " }, // DEC_U16_4, // Not supported in regular DX9 so faking, will cause graphics bugs until worked around - { VK_FORMAT_R8G8_UINT, "VK_FORMAT_UNDEFINED" }, // DEC_U8A_2, - { VK_FORMAT_R16G16_UINT, "VK_FORMAT_UNDEFINED" }, // DEC_U16A_2, + { VK_FORMAT_R8G8_UINT, "R8G8_UINT" }, // DEC_U8A_2, + { VK_FORMAT_R16G16_UINT, "R16G16_UINT" }, // DEC_U16A_2, }; void VertexAttribSetup(VkVertexInputAttributeDescription *attr, int fmt, int offset, PspAttributeLocation location) { diff --git a/GPU/Vulkan/ShaderManagerVulkan.cpp b/GPU/Vulkan/ShaderManagerVulkan.cpp index dfa435dc32..50c95843a1 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.cpp +++ b/GPU/Vulkan/ShaderManagerVulkan.cpp @@ -514,6 +514,9 @@ void ShaderManagerVulkan::GetShaders(int prim, u32 vertType, VulkanVertexShader lastFSID_ = FSID; + lastVShader_ = vs; + lastFShader_ = fs; + *vshader = vs; *fshader = fs; } diff --git a/GPU/Vulkan/ShaderManagerVulkan.h b/GPU/Vulkan/ShaderManagerVulkan.h index 0c3eb7385a..14fd1b32a0 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.h +++ b/GPU/Vulkan/ShaderManagerVulkan.h @@ -110,7 +110,7 @@ R"( mat4 proj_mtx; mat4 tex_mtx; vec4 uvscaleoffset; vec4 depthRange; - vec2 fogCoef; + vec2 fogcoef; vec4 matambientalpha; vec3 blendFixA; vec3 blendFixB; diff --git a/GPU/Vulkan/StateMappingVulkan.cpp b/GPU/Vulkan/StateMappingVulkan.cpp index 8c2a56c187..6fb68e0eec 100644 --- a/GPU/Vulkan/StateMappingVulkan.cpp +++ b/GPU/Vulkan/StateMappingVulkan.cpp @@ -30,6 +30,7 @@ #include "GPU/Vulkan/PipelineManagerVulkan.h" #include "GPU/Vulkan/TextureCacheVulkan.h" #include "GPU/Vulkan/FramebufferVulkan.h" +#include "GPU/Vulkan/ShaderManagerVulkan.h" //#include "GPU/Vulkan/PixelShaderGeneratorVulkan.h" // These tables all fit into u8s. @@ -110,7 +111,9 @@ void ResetShaderBlending() { // TODO: Do this more progressively. No need to compute the entire state if the entire state hasn't changed. // In Vulkan, we simply collect all the state together into a "pipeline key" - we don't actually set any state here // (the caller is responsible for setting the little dynamic state that is supported, dynState). -void ConvertStateToVulkanKey(FramebufferManagerVulkan &fbManager, int prim, VulkanPipelineRasterStateKey &key, VulkanDynamicState &dynState) { +void ConvertStateToVulkanKey(FramebufferManagerVulkan &fbManager, ShaderManagerVulkan *shaderManager, int prim, VulkanPipelineRasterStateKey &key, VulkanDynamicState &dynState) { + memset(&key, 0, sizeof(key)); + memset(&dynState, 0, sizeof(dynState)); // Unfortunately, this isn't implemented yet. gstate_c.allowShaderBlend = false; @@ -148,7 +151,7 @@ void ConvertStateToVulkanKey(FramebufferManagerVulkan &fbManager, int prim, Vulk key.destColor = vkBlendFactorLookup[(size_t)blendState.dstColor]; key.destAlpha = vkBlendFactorLookup[(size_t)blendState.dstAlpha]; if (blendState.dirtyShaderBlend) { - //shaderManager_->DirtyUniform(DIRTY_SHADERBLEND); + shaderManager->DirtyUniform(DIRTY_SHADERBLEND); } dynState.useBlendColor = blendState.useBlendColor; if (blendState.useBlendColor) { @@ -270,7 +273,7 @@ void ConvertStateToVulkanKey(FramebufferManagerVulkan &fbManager, int prim, Vulk vp.minDepth = vpAndScissor.depthRangeMin; vp.maxDepth = vpAndScissor.depthRangeMax; if (vpAndScissor.dirtyProj) { - // shaderManager_->DirtyUniform(DIRTY_PROJMATRIX); + shaderManager->DirtyUniform(DIRTY_PROJMATRIX); } VkRect2D &scissor = dynState.scissor; @@ -285,10 +288,10 @@ void ConvertStateToVulkanKey(FramebufferManagerVulkan &fbManager, int prim, Vulk if (depthMin < 0.0f) depthMin = 0.0f; if (depthMax > 1.0f) depthMax = 1.0f; if (vpAndScissor.dirtyProj) { - // shaderManager_->DirtyUniform(DIRTY_PROJMATRIX); + shaderManager->DirtyUniform(DIRTY_PROJMATRIX); } if (vpAndScissor.dirtyDepth) { - // shaderManager_->DirtyUniform(DIRTY_DEPTHRANGE); + shaderManager->DirtyUniform(DIRTY_DEPTHRANGE); } } diff --git a/GPU/Vulkan/StateMappingVulkan.h b/GPU/Vulkan/StateMappingVulkan.h index fe0abe9386..f0ee8bd715 100644 --- a/GPU/Vulkan/StateMappingVulkan.h +++ b/GPU/Vulkan/StateMappingVulkan.h @@ -58,5 +58,5 @@ struct VulkanPipelineRasterStateKey { } }; - -void ConvertStateToVulkanKey(FramebufferManagerVulkan &fbManager, int prim, VulkanPipelineRasterStateKey &key, VulkanDynamicState &dynState); +class ShaderManagerVulkan; +void ConvertStateToVulkanKey(FramebufferManagerVulkan &fbManager, ShaderManagerVulkan *shaderManager, int prim, VulkanPipelineRasterStateKey &key, VulkanDynamicState &dynState); diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index 900f169890..7ec887c1ce 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -66,7 +66,7 @@ #define TEXCACHE_SECOND_MIN_PRESSURE 4 * 1024 * 1024 #define VULKAN_4444_FORMAT VK_FORMAT_R4G4B4A4_UNORM_PACK16 -#define VULKAN_1555_FORMAT VK_FORMAT_A1R5G5B5_UNORM_PACK16 +#define VULKAN_1555_FORMAT VK_FORMAT_R5G5B5A1_UNORM_PACK16 // TODO: Switch to the one that matches the PSP better. #define VULKAN_565_FORMAT VK_FORMAT_R5G6B5_UNORM_PACK16 #define VULKAN_8888_FORMAT VK_FORMAT_R8G8B8A8_UNORM @@ -1507,7 +1507,7 @@ VkFormat TextureCacheVulkan::GetDestFormat(GETextureFormat format, GEPaletteForm case GE_TFMT_DXT3: case GE_TFMT_DXT5: default: - return VK_FORMAT_R8G8B8A8_UNORM; + return VULKAN_8888_FORMAT; } } @@ -1628,7 +1628,7 @@ void *TextureCacheVulkan::DecodeTextureLevel(GETextureFormat format, GEPaletteFo case GE_TFMT_8888: if (!swizzled) { // Special case: if we don't need to deal with packing, we don't need to copy. - if ((scaleFactor == 1 && gstate_c.Supports(GPU_SUPPORTS_UNPACK_SUBIMAGE)) || w == bufw) { + if (scaleFactor == 1 || w == bufw) { finalBuf = (void *)texptr; } else { tmpTexBuf32.resize(std::max(bufw, w) * h); @@ -1715,36 +1715,19 @@ void *TextureCacheVulkan::DecodeTextureLevel(GETextureFormat format, GEPaletteFo ERROR_LOG_REPORT(G3D, "NO finalbuf! Will crash!"); } - if (!(scaleFactor == 1 && gstate_c.Supports(GPU_SUPPORTS_UNPACK_SUBIMAGE)) && w != bufw) { - int pixelSize; - switch (dstFmt) { - case VK_FORMAT_R4G4B4A4_UNORM_PACK16: - case VK_FORMAT_R5G6B5_UNORM_PACK16: - case VK_FORMAT_A1R5G5B5_UNORM_PACK16: - pixelSize = 2; - break; - default: - pixelSize = 4; - break; - } - - // Need to rearrange the buffer to simulate GL_UNPACK_ROW_LENGTH etc. - finalBuf = RearrangeBuf(finalBuf, bufw * pixelSize, w * pixelSize, h); - } - return finalBuf; } TextureCacheVulkan::TexCacheEntry::Status TextureCacheVulkan::CheckAlpha(const u32 *pixelData, VkFormat dstFmt, int stride, int w, int h) { CheckAlphaResult res; switch (dstFmt) { - case VK_FORMAT_R4G4B4A4_UNORM_PACK16: + case VULKAN_4444_FORMAT: res = CheckAlphaABGR4444Basic(pixelData, stride, w, h); break; - case VK_FORMAT_A1R5G5B5_UNORM_PACK16: + case VULKAN_1555_FORMAT: res = CheckAlphaABGR1555Basic(pixelData, stride, w, h); break; - case VK_FORMAT_R5G6B5_UNORM_PACK16: + case VULKAN_565_FORMAT: // Never has any alpha. res = CHECKALPHA_FULL; break; @@ -1775,8 +1758,8 @@ void TextureCacheVulkan::LoadTextureLevel(TexCacheEntry &entry, int level, bool if (finalBuf == NULL) { return; } - decPitch = w * (dstFmt == VULKAN_8888_FORMAT ? 4 : 2); - rowBytes = decPitch; + decPitch = bufw * (dstFmt == VULKAN_8888_FORMAT ? 4 : 2); + rowBytes = w * (dstFmt == VULKAN_8888_FORMAT ? 4 : 2); gpuStats.numTexturesDecoded++; pixelData = (u32 *)finalBuf; diff --git a/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp b/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp index 4eac7a04ef..ea35594545 100644 --- a/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp +++ b/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp @@ -55,14 +55,14 @@ static const char * const boneWeightDecl[9] = { "#ERROR#", - "layout(location = 0) in float w1;\n", - "layout(location = 0) in vec2 w1;\n", - "layout(location = 0) in vec3 w1;\n", - "layout(location = 0) in vec4 w1;\n", - "layout(location = 0) in vec4 w1;\nin float w2;\n", - "layout(location = 0) in vec4 w1;\nin vec2 w2;\n", - "layout(location = 0) in vec4 w1;\nin vec3 w2;\n", - "layout(location = 0) in vec4 w1, w2;\n", + "layout(location = 3) in float w1;\n", + "layout(location = 3) in vec2 w1;\n", + "layout(location = 3) in vec3 w1;\n", + "layout(location = 3) in vec4 w1;\n", + "layout(location = 3) in vec4 w1;\nlayout(location = 4) in float w2;\n", + "layout(location = 3) in vec4 w1;\nlayout(location = 4) in vec2 w2;\n", + "layout(location = 3) in vec4 w1;\nlayout(location = 4) in vec3 w2;\n", + "layout(location = 3) in vec4 w1;\nlayout(location = 4) in vec4 w2;\n", }; enum DoLightComputation { @@ -139,7 +139,7 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { WRITE(p, "\n"); WRITE(p, "layout (std140, set = 0, binding = 2) uniform baseVars {\n%s\n} base;\n", ub_baseStr); - if (enableLighting) + if (enableLighting || doShadeMapping) WRITE(p, "layout (std140, set = 0, binding = 3) uniform lightVars {\n%s\n} light;\n", ub_vs_lightsStr); if (enableBones) WRITE(p, "layout (std140, set = 0, binding = 4) uniform boneVars {\n%s\n} bone;\n", ub_vs_bonesStr); @@ -497,7 +497,7 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { break; } // Transform by texture matrix. XYZ as we are doing projection mapping. - WRITE(p, " v_texcoord = (base.texmtx * %s).xyz * vec3(base.uvscaleoffset.xy, 1.0);\n", temp_tc.c_str()); + WRITE(p, " v_texcoord = (base.tex_mtx * %s).xyz * vec3(base.uvscaleoffset.xy, 1.0);\n", temp_tc.c_str()); } break; diff --git a/ext/native/thin3d/VulkanContext.cpp b/ext/native/thin3d/VulkanContext.cpp index c254cd930a..e29c1f4bd3 100644 --- a/ext/native/thin3d/VulkanContext.cpp +++ b/ext/native/thin3d/VulkanContext.cpp @@ -1275,7 +1275,6 @@ void VulkanTexture::Unlock(VulkanContext *vulkan) { VkMemoryAllocateInfo mem_alloc = {}; mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; mem_alloc.pNext = NULL; - mem_alloc.allocationSize = 0; mem_alloc.memoryTypeIndex = 0; mem_alloc.allocationSize = mem_reqs.size; diff --git a/ext/native/thin3d/VulkanContext.h b/ext/native/thin3d/VulkanContext.h index 51093503e2..4115e8435e 100644 --- a/ext/native/thin3d/VulkanContext.h +++ b/ext/native/thin3d/VulkanContext.h @@ -343,8 +343,8 @@ private: class VulkanTexture { public: VulkanTexture() - : image(nullptr), mem(nullptr), view(nullptr), tex_width(0), tex_height(0), format_(VK_FORMAT_UNDEFINED), - mappableImage(nullptr), mappableMemory(nullptr) { + : image(nullptr), imageLayout(VK_IMAGE_LAYOUT_UNDEFINED), mem(nullptr), view(nullptr), tex_width(0), tex_height(0), format_(VK_FORMAT_UNDEFINED), + mappableImage(nullptr), mappableMemory(nullptr), needStaging(false) { } // Always call Create, Lock, Unlock. Unlock performs the upload if necessary. // Can later Lock and Unlock again. This cannot change the format. Create cannot From 3bf88d7475dce6136308d7a07f4d2bd76e4cac30 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 10 Jan 2016 11:41:46 +0100 Subject: [PATCH 037/116] Plug the texture memory leak --- GPU/Vulkan/ShaderManagerVulkan.h | 18 ++--- GPU/Vulkan/StateMappingVulkan.cpp | 3 + GPU/Vulkan/TextureCacheVulkan.cpp | 9 +-- GPU/Vulkan/VertexShaderGeneratorVulkan.cpp | 6 +- ext/native/thin3d/VulkanContext.cpp | 84 +++++++++++++--------- ext/native/thin3d/VulkanContext.h | 21 +++--- ext/native/thin3d/thin3d_vulkan.cpp | 10 +-- 7 files changed, 88 insertions(+), 63 deletions(-) diff --git a/GPU/Vulkan/ShaderManagerVulkan.h b/GPU/Vulkan/ShaderManagerVulkan.h index 14fd1b32a0..078230f0ba 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.h +++ b/GPU/Vulkan/ShaderManagerVulkan.h @@ -104,7 +104,7 @@ struct UB_VS_FS_Base { }; static const char *ub_baseStr = -R"( mat4 proj_mtx; +R"( mat4 proj_mtx; mat4 view_mtx; mat4 world_mtx; mat4 tex_mtx; @@ -139,15 +139,15 @@ struct UB_VS_Lights { }; static const char *ub_vs_lightsStr = -R"(vec4 globalAmbient; +R"( vec4 globalAmbient; vec3 matdiffuse; - vec4 matspecular; - vec3 matemissive; - vec3 pos[4]; - vec3 dir[4]; - vec3 att[4]; + vec4 matspecular; + vec3 matemissive; + vec3 pos[4]; + vec3 dir[4]; + vec3 att[4]; float angle[4]; - float spotCoef[4]; + float spotCoef[4]; vec3 ambient[4]; vec3 diffuse[4]; vec3 specular[4]; @@ -158,7 +158,7 @@ struct UB_VS_Bones { }; static const char *ub_vs_bonesStr = -R"(mat4 m[8]; +R"( mat4 m[8]; )"; class VulkanContext; diff --git a/GPU/Vulkan/StateMappingVulkan.cpp b/GPU/Vulkan/StateMappingVulkan.cpp index 6fb68e0eec..c2ea8a2e21 100644 --- a/GPU/Vulkan/StateMappingVulkan.cpp +++ b/GPU/Vulkan/StateMappingVulkan.cpp @@ -202,6 +202,7 @@ void ConvertStateToVulkanKey(FramebufferManagerVulkan &fbManager, ShaderManagerV // Set cull bool wantCull = !gstate.isModeThrough() && prim != GE_PRIM_RECTANGLES && gstate.isCullEnabled(); key.cullMode = wantCull ? (gstate.getCullMode() ? VK_CULL_MODE_FRONT_BIT : VK_CULL_MODE_BACK_BIT) : VK_CULL_MODE_NONE; + key.cullMode = VK_CULL_MODE_NONE; // Depth Test if (gstate.isDepthTestEnabled()) { @@ -213,6 +214,8 @@ void ConvertStateToVulkanKey(FramebufferManagerVulkan &fbManager, ShaderManagerV } } else { key.depthTestEnable = false; + key.depthWriteEnable = false; + key.depthCompareOp = VK_COMPARE_OP_ALWAYS; } // PSP color/alpha mask is per bit but we can only support per byte. diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index 7ec887c1ce..0349ebc481 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -1446,9 +1446,10 @@ void TextureCacheVulkan::SetTexture() { } } else { entry->vkTex = new CachedTextureVulkan(); - entry->vkTex->texture_ = new VulkanTexture(); + entry->vkTex->texture_ = new VulkanTexture(vulkan_); VulkanTexture *image = entry->vkTex->texture_; - image->Create(vulkan_, w, h, dstFmt); + VkResult res = image->Create(w, h, dstFmt); + assert(res == VK_SUCCESS); } lastBoundTexture = entry->vkTex; @@ -1786,11 +1787,11 @@ void TextureCacheVulkan::LoadTextureLevel(TexCacheEntry &entry, int level, bool // Upload the texture data. TODO: Decode directly into this buffer. int rowPitch; - uint8_t *writePtr = entry.vkTex->texture_->Lock(vulkan_, level, &rowPitch); + uint8_t *writePtr = entry.vkTex->texture_->Lock(level, &rowPitch); for (int y = 0; y < h; y++) { memcpy(writePtr + rowPitch * y, (const uint8_t *)pixelData + decPitch * y, rowBytes); } - entry.vkTex->texture_->Unlock(vulkan_); + entry.vkTex->texture_->Unlock(); /* if (!lowMemoryMode_) { diff --git a/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp b/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp index ea35594545..0adf5d5ddd 100644 --- a/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp +++ b/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp @@ -138,11 +138,11 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { // are present and what parts aren't, but we will not be ultra detailed about it. WRITE(p, "\n"); - WRITE(p, "layout (std140, set = 0, binding = 2) uniform baseVars {\n%s\n} base;\n", ub_baseStr); + WRITE(p, "layout (std140, set = 0, binding = 2) uniform baseVars {\n%s} base;\n", ub_baseStr); if (enableLighting || doShadeMapping) - WRITE(p, "layout (std140, set = 0, binding = 3) uniform lightVars {\n%s\n} light;\n", ub_vs_lightsStr); + WRITE(p, "layout (std140, set = 0, binding = 3) uniform lightVars {\n%s} light;\n", ub_vs_lightsStr); if (enableBones) - WRITE(p, "layout (std140, set = 0, binding = 4) uniform boneVars {\n%s\n} bone;\n", ub_vs_bonesStr); + WRITE(p, "layout (std140, set = 0, binding = 4) uniform boneVars {\n%s} bone;\n", ub_vs_bonesStr); const char *shading = doFlatShading ? "flat " : ""; diff --git a/ext/native/thin3d/VulkanContext.cpp b/ext/native/thin3d/VulkanContext.cpp index e29c1f4bd3..75bcdc3663 100644 --- a/ext/native/thin3d/VulkanContext.cpp +++ b/ext/native/thin3d/VulkanContext.cpp @@ -1131,13 +1131,13 @@ void VulkanContext::InitCommandPool() { assert(res == VK_SUCCESS); } -VkResult VulkanTexture::Create(VulkanContext *vulkan, int w, int h, VkFormat format) { +VkResult VulkanTexture::Create(int w, int h, VkFormat format) { tex_width = w; tex_height = h; format_ = format; VkFormatProperties formatProps; - vkGetPhysicalDeviceFormatProperties(vulkan->GetPhysicalDevice(), format, &formatProps); + vkGetPhysicalDeviceFormatProperties(vulkan_->GetPhysicalDevice(), format, &formatProps); // See if we can use a linear tiled image for a texture, if not, we will need a staging image for the texture data. // Linear tiling is usually only supported for 2D non-array textures. @@ -1148,14 +1148,14 @@ VkResult VulkanTexture::Create(VulkanContext *vulkan, int w, int h, VkFormat for return VK_SUCCESS; } -void VulkanTexture::CreateMappableImage(VulkanContext *vulkan) { +void VulkanTexture::CreateMappableImage() { // If we already have a mappableImage, forget it. if (mappableImage) { - vulkan->QueueDelete(mappableImage); + vulkan_->QueueDelete(mappableImage); mappableImage = nullptr; } if (mappableMemory) { - vulkan->QueueDelete(mappableMemory); + vulkan_->QueueDelete(mappableMemory); mappableMemory = nullptr; } @@ -1187,27 +1187,27 @@ void VulkanTexture::CreateMappableImage(VulkanContext *vulkan) { // Create a mappable image. It will be the texture if linear images are ok to be textures // or it will be the staging image if they are not. - VkResult res = vkCreateImage(vulkan->GetDevice(), &image_create_info, NULL, &mappableImage); + VkResult res = vkCreateImage(vulkan_->GetDevice(), &image_create_info, NULL, &mappableImage); assert(res == VK_SUCCESS); - vkGetImageMemoryRequirements(vulkan->GetDevice(), mappableImage, &mem_reqs); + vkGetImageMemoryRequirements(vulkan_->GetDevice(), mappableImage, &mem_reqs); assert(res == VK_SUCCESS); mem_alloc.allocationSize = mem_reqs.size; // Find the memory type that is host mappable. - pass = vulkan->MemoryTypeFromProperties(mem_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, &mem_alloc.memoryTypeIndex); + pass = vulkan_->MemoryTypeFromProperties(mem_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, &mem_alloc.memoryTypeIndex); assert(pass); - res = vkAllocateMemory(vulkan->GetDevice(), &mem_alloc, NULL, &(mappableMemory)); + res = vkAllocateMemory(vulkan_->GetDevice(), &mem_alloc, NULL, &(mappableMemory)); assert(res == VK_SUCCESS); - res = vkBindImageMemory(vulkan->GetDevice(), mappableImage, mappableMemory, 0); + res = vkBindImageMemory(vulkan_->GetDevice(), mappableImage, mappableMemory, 0); assert(res == VK_SUCCESS); } -uint8_t *VulkanTexture::Lock(VulkanContext *vulkan, int level, int *rowPitch) { - CreateMappableImage(vulkan); +uint8_t *VulkanTexture::Lock(int level, int *rowPitch) { + CreateMappableImage(); VkImageSubresource subres = {}; subres.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; @@ -1218,28 +1218,32 @@ uint8_t *VulkanTexture::Lock(VulkanContext *vulkan, int level, int *rowPitch) { void *data; // Get the subresource layout so we know what the row pitch is - vkGetImageSubresourceLayout(vulkan->GetDevice(), mappableImage, &subres, &layout); - VkResult res = vkMapMemory(vulkan->GetDevice(), mappableMemory, layout.offset, layout.size, 0, &data); + vkGetImageSubresourceLayout(vulkan_->GetDevice(), mappableImage, &subres, &layout); + VkResult res = vkMapMemory(vulkan_->GetDevice(), mappableMemory, layout.offset, layout.size, 0, &data); assert(res == VK_SUCCESS); *rowPitch = (int)layout.rowPitch; return (uint8_t *)data; } -void VulkanTexture::Unlock(VulkanContext *vulkan) { - vkUnmapMemory(vulkan->GetDevice(), mappableMemory); +void VulkanTexture::Unlock() { + vkUnmapMemory(vulkan_->GetDevice(), mappableMemory); - VkCommandBuffer cmd = vulkan->GetInitCommandBuffer(); + VkCommandBuffer cmd = vulkan_->GetInitCommandBuffer(); // if we already have an image, queue it for destruction and forget it. if (image) { - vulkan->QueueDelete(image); + vulkan_->QueueDelete(image); image = nullptr; } if (view) { - vulkan->QueueDelete(view); + vulkan_->QueueDelete(view); view = nullptr; } + if (mem) { + vulkan_->QueueDelete(mem); + mem = nullptr; + } if (!needStaging) { /* If we can use the linear tiled image as a texture, just do it */ image = mappableImage; @@ -1267,10 +1271,10 @@ void VulkanTexture::Unlock(VulkanContext *vulkan) { image_create_info.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; image_create_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; - VkResult res = vkCreateImage(vulkan->GetDevice(), &image_create_info, NULL, &image); + VkResult res = vkCreateImage(vulkan_->GetDevice(), &image_create_info, NULL, &image); assert(res == VK_SUCCESS); - vkGetImageMemoryRequirements(vulkan->GetDevice(), image, &mem_reqs); + vkGetImageMemoryRequirements(vulkan_->GetDevice(), image, &mem_reqs); VkMemoryAllocateInfo mem_alloc = {}; mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; @@ -1279,13 +1283,13 @@ void VulkanTexture::Unlock(VulkanContext *vulkan) { mem_alloc.allocationSize = mem_reqs.size; // Find memory type - don't specify any mapping requirements - bool pass = vulkan->MemoryTypeFromProperties(mem_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &mem_alloc.memoryTypeIndex); + bool pass = vulkan_->MemoryTypeFromProperties(mem_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &mem_alloc.memoryTypeIndex); assert(pass); - res = vkAllocateMemory(vulkan->GetDevice(), &mem_alloc, NULL, &mem); + res = vkAllocateMemory(vulkan_->GetDevice(), &mem_alloc, NULL, &mem); assert(res == VK_SUCCESS); - res = vkBindImageMemory(vulkan->GetDevice(), image, mem, 0); + res = vkBindImageMemory(vulkan_->GetDevice(), image, mem, 0); assert(res == VK_SUCCESS); // Since we're going to blit from the mappable image, set its layout to SOURCE_OPTIMAL @@ -1334,8 +1338,8 @@ void VulkanTexture::Unlock(VulkanContext *vulkan) { VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, imageLayout); - vulkan->QueueDelete(mappableMemory); - vulkan->QueueDelete(mappableImage); + vulkan_->QueueDelete(mappableMemory); + vulkan_->QueueDelete(mappableImage); mappableImage = nullptr; mappableMemory = nullptr; } @@ -1358,18 +1362,30 @@ void VulkanTexture::Unlock(VulkanContext *vulkan) { /* create image view */ view_info.image = image; - VkResult res = vkCreateImageView(vulkan->GetDevice(), &view_info, NULL, &view); + VkResult res = vkCreateImageView(vulkan_->GetDevice(), &view_info, NULL, &view); assert(res == VK_SUCCESS); } -void VulkanTexture::Destroy(VulkanContext *vulkan) { - vulkan->QueueDelete(view); - vulkan->QueueDelete(image); - vulkan->QueueDelete(mem); +void VulkanTexture::Destroy() { + if (view) { + vulkan_->QueueDelete(view); + } + if (image) { + vulkan_->QueueDelete(image); + if (mappableImage == image) { + mappableImage = nullptr; + } + } + if (mem) { + vulkan_->QueueDelete(mem); + if (mappableMemory == mem) { + mappableMemory = nullptr; + } + } - view = NULL; - image = NULL; - mem = NULL; + view = nullptr; + image = nullptr; + mem = nullptr; } VkFence VulkanContext::CreateFence(bool presignalled) { diff --git a/ext/native/thin3d/VulkanContext.h b/ext/native/thin3d/VulkanContext.h index 4115e8435e..7568368d64 100644 --- a/ext/native/thin3d/VulkanContext.h +++ b/ext/native/thin3d/VulkanContext.h @@ -342,25 +342,30 @@ private: // Only supports simple 2D textures for now. Mipmap support will be added later. class VulkanTexture { public: - VulkanTexture() - : image(nullptr), imageLayout(VK_IMAGE_LAYOUT_UNDEFINED), mem(nullptr), view(nullptr), tex_width(0), tex_height(0), format_(VK_FORMAT_UNDEFINED), + VulkanTexture(VulkanContext *vulkan) + : vulkan_(vulkan), image(nullptr), imageLayout(VK_IMAGE_LAYOUT_UNDEFINED), mem(nullptr), view(nullptr), tex_width(0), tex_height(0), format_(VK_FORMAT_UNDEFINED), mappableImage(nullptr), mappableMemory(nullptr), needStaging(false) { } + ~VulkanTexture() { + Destroy(); + } // Always call Create, Lock, Unlock. Unlock performs the upload if necessary. // Can later Lock and Unlock again. This cannot change the format. Create cannot - // be called a second time without recreating the texture object. + // be called a second time without recreating the texture object until Destroy has + // been called. - VkResult Create(VulkanContext *vulkan, int w, int h, VkFormat format); - uint8_t *Lock(VulkanContext *vulkan, int level, int *rowPitch); - void Unlock(VulkanContext *vulkan); + VkResult Create(int w, int h, VkFormat format); + uint8_t *Lock(int level, int *rowPitch); + void Unlock(); - void Destroy(VulkanContext *vulkan); + void Destroy(); VkImageView GetImageView() const { return view; } private: - void CreateMappableImage(VulkanContext *vulkan); + void CreateMappableImage(); + VulkanContext *vulkan_; VkImage image; VkImageLayout imageLayout; VkDeviceMemory mem; diff --git a/ext/native/thin3d/thin3d_vulkan.cpp b/ext/native/thin3d/thin3d_vulkan.cpp index b04c10e348..5fc81cb708 100644 --- a/ext/native/thin3d/thin3d_vulkan.cpp +++ b/ext/native/thin3d/thin3d_vulkan.cpp @@ -548,7 +548,7 @@ public: width_ = width; height_ = height; depth_ = depth; - vkTex_ = new VulkanTexture(); + vkTex_ = new VulkanTexture(vulkan_); // We don't actually do anything here. return true; } @@ -563,7 +563,7 @@ private: void Destroy() { ILOG("texture destroyed: %p", this); if (vkTex_) { - vkTex_->Destroy(vulkan_); + vkTex_->Destroy(); delete vkTex_; } } @@ -955,13 +955,13 @@ void Thin3DVKTexture::SetImageData(int x, int y, int z, int width, int height, i int bpp; VkFormat vulkanFormat = FormatToVulkan(format_, &bpp); int bytesPerPixel = bpp / 8; - vkTex_->Create(vulkan_, width, height, vulkanFormat); + vkTex_->Create(width, height, vulkanFormat); int rowPitch; - uint8_t *dstData = vkTex_->Lock(vulkan_, 0, &rowPitch); + uint8_t *dstData = vkTex_->Lock(0, &rowPitch); for (int y = 0; y < height; y++) { memcpy(dstData + rowPitch * y, data + stride * y, width * bytesPerPixel); } - vkTex_->Unlock(vulkan_); + vkTex_->Unlock(); } void Thin3DVKTexture::Finalize(int zim_flags) { From 4c281f16acd74d1fd8baf11f1441a5bcdfa4bda5 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 10 Jan 2016 12:27:45 +0100 Subject: [PATCH 038/116] Fix mixup with fragment shader ubo variables --- GPU/Vulkan/DrawEngineVulkan.cpp | 1 + GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp | 14 +++----------- GPU/Vulkan/ShaderManagerVulkan.cpp | 2 +- GPU/Vulkan/ShaderManagerVulkan.h | 12 ++++++------ GPU/Vulkan/TextureCacheVulkan.cpp | 6 ++++-- ext/native/thin3d/thin3d_vulkan.cpp | 6 ++++++ 6 files changed, 21 insertions(+), 20 deletions(-) diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index 139eac9296..e49888fd83 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -713,6 +713,7 @@ void DrawEngineVulkan::Resized() { decJitCache_->Clear(); lastVType_ = -1; dec_ = NULL; + // TODO: We must also wipe pipelines. for (auto iter = decoderMap_.begin(); iter != decoderMap_.end(); iter++) { delete iter->second; } diff --git a/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp b/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp index b6dd01c96e..ef3389112f 100644 --- a/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp +++ b/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp @@ -53,13 +53,6 @@ bool GenerateVulkanGLSLFragmentShader(const ShaderID &id, char *buffer) { WRITE(p, "#extension GL_ARB_separate_shader_objects : enable\n"); WRITE(p, "#extension GL_ARB_shading_language_420pack : enable\n"); - // PowerVR needs highp to do the fog in MHU correctly. - // Others don't. - bool highpFog = (gl_extensions.bugs & BUG_PVR_SHADER_PRECISION_BAD) ? true : false; - bool highpTexcoord = highpFog; - - WRITE(p, "precision lowp float;\n"); - bool lmode = id.Bit(FS_BIT_LMODE); bool doTexture = id.Bit(FS_BIT_DO_TEXTURE); bool enableFog = id.Bit(FS_BIT_ENABLE_FOG); @@ -107,13 +100,13 @@ bool GenerateVulkanGLSLFragmentShader(const ShaderID &id, char *buffer) { if (lmode) WRITE(p, "layout (location = 2) %s in vec3 v_color1;\n", shading); if (enableFog) { - WRITE(p, "layout (location = 3) %s in float v_fogdepth;\n", highpFog ? "highp" : "mediump"); + WRITE(p, "layout (location = 3) in float v_fogdepth;\n"); } if (doTexture) { if (doTextureProjection) - WRITE(p, "layout (location = 0) %s in vec3 v_texcoord;\n", highpTexcoord ? "highp" : "mediump"); + WRITE(p, "layout (location = 0) in vec3 v_texcoord;\n"); else - WRITE(p, "layout (location = 0) %s in vec2 v_texcoord;\n", highpTexcoord ? "highp" : "mediump"); + WRITE(p, "layout (location = 0) in vec2 v_texcoord;\n"); } if (enableAlphaTest && !alphaTestAgainstZero) { @@ -134,7 +127,6 @@ bool GenerateVulkanGLSLFragmentShader(const ShaderID &id, char *buffer) { } WRITE(p, "void main() {\n"); - if (isModeClear) { // Clear mode does not allow any fancy shading. WRITE(p, " vec4 v = v_color0;\n"); diff --git a/GPU/Vulkan/ShaderManagerVulkan.cpp b/GPU/Vulkan/ShaderManagerVulkan.cpp index 50c95843a1..c85336868f 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.cpp +++ b/GPU/Vulkan/ShaderManagerVulkan.cpp @@ -202,7 +202,7 @@ void ShaderManagerVulkan::BaseUpdateUniforms(int dirtyUniforms) { Uint8x3ToFloat4_Alpha(ub_base.alphaColorRef, gstate.getColorTestRef(), (float)gstate.getAlphaTestRef()); } if (dirtyUniforms & DIRTY_ALPHACOLORMASK) { - Uint8x3ToFloat4(ub_base.colorTestMask, gstate.colortestmask); + Uint8x3ToInt4(ub_base.colorTestMask, gstate.colortestmask); } if (dirtyUniforms & DIRTY_FOGCOLOR) { Uint8x3ToFloat4(ub_base.fogColor, gstate.fogcolor); diff --git a/GPU/Vulkan/ShaderManagerVulkan.h b/GPU/Vulkan/ShaderManagerVulkan.h index 078230f0ba..2042d4ec95 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.h +++ b/GPU/Vulkan/ShaderManagerVulkan.h @@ -95,7 +95,7 @@ struct UB_VS_FS_Base { float fogColor[4]; float texEnvColor[4]; float alphaColorRef[4]; - float colorTestMask[4]; + int colorTestMask[4]; float stencilReplace[4]; // only first float used float blendFixA[4]; float blendFixB[4]; @@ -112,15 +112,15 @@ R"( mat4 proj_mtx; vec4 depthRange; vec2 fogcoef; vec4 matambientalpha; + vec3 fogcolor; + vec3 texenv; + vec4 alphacolorref; + ivec4 alphacolormask; + float stencilReplaceValue; vec3 blendFixA; vec3 blendFixB; vec4 texclamp; vec2 texclampoff; - vec4 alphacolorref; - ivec4 alphacolormask; - float stencilReplaceValue; - vec3 texenv; - vec3 fogcolor; )"; struct UB_VS_Lights { diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index 0349ebc481..43c2da5f3e 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -1750,12 +1750,12 @@ void TextureCacheVulkan::LoadTextureLevel(TexCacheEntry &entry, int level, bool { PROFILE_THIS_SCOPE("decodetex"); - // TODO: only do this once u32 texByteAlign = 1; + GETextureFormat tfmt = (GETextureFormat)entry.format; GEPaletteFormat clutformat = gstate.getClutPaletteFormat(); int bufw; - void *finalBuf = DecodeTextureLevel(GETextureFormat(entry.format), clutformat, level, texByteAlign, dstFmt, scaleFactor, &bufw); + void *finalBuf = DecodeTextureLevel(tfmt, clutformat, level, texByteAlign, dstFmt, scaleFactor, &bufw); if (finalBuf == NULL) { return; } @@ -1790,6 +1790,8 @@ void TextureCacheVulkan::LoadTextureLevel(TexCacheEntry &entry, int level, bool uint8_t *writePtr = entry.vkTex->texture_->Lock(level, &rowPitch); for (int y = 0; y < h; y++) { memcpy(writePtr + rowPitch * y, (const uint8_t *)pixelData + decPitch * y, rowBytes); + // uncomment to make all textures white for debugging + //memset(writePtr + rowPitch * y, 0xff, rowBytes); } entry.vkTex->texture_->Unlock(); diff --git a/ext/native/thin3d/thin3d_vulkan.cpp b/ext/native/thin3d/thin3d_vulkan.cpp index 5fc81cb708..89d6b5097e 100644 --- a/ext/native/thin3d/thin3d_vulkan.cpp +++ b/ext/native/thin3d/thin3d_vulkan.cpp @@ -1193,5 +1193,11 @@ std::vector Thin3DVKContext::GetFeatureList() { AddFeature(features, "textureCompressionASTC_LDR", available.textureCompressionASTC_LDR, enabled.textureCompressionASTC_LDR); AddFeature(features, "shaderClipDistance", available.shaderClipDistance, enabled.shaderClipDistance); AddFeature(features, "shaderCullDistance", available.shaderCullDistance, enabled.shaderCullDistance); + + // Also list texture formats and their properties. + for (int i = VK_FORMAT_BEGIN_RANGE; i <= VK_FORMAT_END_RANGE; i++) { + // TODO + } + return features; } From 52e7f06908c8f1168fc20236caaeeb71ecfc91d8 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 10 Jan 2016 13:08:19 +0100 Subject: [PATCH 039/116] Add Vulkan to Win32 menu. disable gfx logging in debug by default. --- Windows/MainWindowMenu.cpp | 33 ++++++++++++++++++++++++++++----- Windows/ppsspp.rc | 1 + Windows/resource.h | 1 + 3 files changed, 30 insertions(+), 5 deletions(-) diff --git a/Windows/MainWindowMenu.cpp b/Windows/MainWindowMenu.cpp index b2cd04a898..a78d3b784f 100644 --- a/Windows/MainWindowMenu.cpp +++ b/Windows/MainWindowMenu.cpp @@ -701,6 +701,12 @@ namespace MainWindow { PostMessage(MainWindow::GetHWND(), WM_CLOSE, 0, 0); break; + case ID_OPTIONS_VULKAN: + g_Config.iGPUBackend = GPU_BACKEND_VULKAN; + g_Config.bRestartRequired = true; + PostMessage(MainWindow::GetHWND(), WM_CLOSE, 0, 0); + break; + case ID_OPTIONS_NONBUFFEREDRENDERING: setRenderingMode(FB_NON_BUFFERED_MODE); break; case ID_OPTIONS_BUFFEREDRENDERING: setRenderingMode(FB_BUFFERED_MODE); break; case ID_OPTIONS_READFBOTOMEMORYCPU: setRenderingMode(FB_READFBOMEMORY_CPU); break; @@ -1144,14 +1150,31 @@ namespace MainWindow { CheckMenuItem(menu, savestateSlot[i], MF_BYCOMMAND | ((i == g_Config.iCurrentStateSlot) ? MF_CHECKED : MF_UNCHECKED)); } - if (g_Config.iGPUBackend == GPU_BACKEND_DIRECT3D9) { + switch (g_Config.iGPUBackend) { + case GPU_BACKEND_DIRECT3D9: EnableMenuItem(menu, ID_OPTIONS_DIRECT3D9, MF_GRAYED); - CheckMenuItem(menu, ID_OPTIONS_DIRECT3D9, MF_CHECKED); EnableMenuItem(menu, ID_OPTIONS_OPENGL, MF_ENABLED); - } else { - EnableMenuItem(menu, ID_OPTIONS_OPENGL, MF_GRAYED); - CheckMenuItem(menu, ID_OPTIONS_OPENGL, MF_CHECKED); + EnableMenuItem(menu, ID_OPTIONS_VULKAN, MF_ENABLED); + CheckMenuItem(menu, ID_OPTIONS_DIRECT3D9, MF_CHECKED); + CheckMenuItem(menu, ID_OPTIONS_OPENGL, MF_UNCHECKED); + CheckMenuItem(menu, ID_OPTIONS_VULKAN, MF_UNCHECKED); + break; + case GPU_BACKEND_OPENGL: EnableMenuItem(menu, ID_OPTIONS_DIRECT3D9, MF_ENABLED); + EnableMenuItem(menu, ID_OPTIONS_OPENGL, MF_GRAYED); + EnableMenuItem(menu, ID_OPTIONS_VULKAN, MF_ENABLED); + CheckMenuItem(menu, ID_OPTIONS_DIRECT3D9, MF_UNCHECKED); + CheckMenuItem(menu, ID_OPTIONS_OPENGL, MF_CHECKED); + CheckMenuItem(menu, ID_OPTIONS_VULKAN, MF_UNCHECKED); + break; + case GPU_BACKEND_VULKAN: + EnableMenuItem(menu, ID_OPTIONS_DIRECT3D9, MF_ENABLED); + EnableMenuItem(menu, ID_OPTIONS_OPENGL, MF_ENABLED); + EnableMenuItem(menu, ID_OPTIONS_VULKAN, MF_GRAYED); + CheckMenuItem(menu, ID_OPTIONS_DIRECT3D9, MF_UNCHECKED); + CheckMenuItem(menu, ID_OPTIONS_OPENGL, MF_UNCHECKED); + CheckMenuItem(menu, ID_OPTIONS_VULKAN, MF_CHECKED); + break; } UpdateDynamicMenuCheckmarks(menu); diff --git a/Windows/ppsspp.rc b/Windows/ppsspp.rc index 9f2f7040b3..01baf572a8 100644 --- a/Windows/ppsspp.rc +++ b/Windows/ppsspp.rc @@ -481,6 +481,7 @@ BEGIN BEGIN MENUITEM "Direct3D9" ID_OPTIONS_DIRECT3D9 MENUITEM "OpenGL" ID_OPTIONS_OPENGL + MENUITEM "Vulkan" ID_OPTIONS_VULKAN END POPUP "Rendering Mode" diff --git a/Windows/resource.h b/Windows/resource.h index 675dcd39bd..bdb6137da2 100644 --- a/Windows/resource.h +++ b/Windows/resource.h @@ -323,6 +323,7 @@ #define ID_EMULATION_ROTATION_H_R 40158 #define ID_EMULATION_ROTATION_V_R 40159 #define ID_OPTIONS_DISPLAY_LAYOUT 40160 +#define ID_OPTIONS_VULKAN 40161 // Dummy option to let the buffered rendering hotkey cycle through all the options. #define ID_OPTIONS_BUFFEREDRENDERINGDUMMY 40500 From 55ef97639a9aac45ef4e0fe8ff20d278aa2afea4 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 10 Jan 2016 13:08:54 +0100 Subject: [PATCH 040/116] More zero-initialization. Fix scope issue, MSVC's optimizer was aggressive enough that this was a problem. Fixes textures in release mode. --- GPU/Vulkan/DrawEngineVulkan.cpp | 6 +++--- GPU/Vulkan/ShaderManagerVulkan.cpp | 3 +++ GPU/Vulkan/TextureCacheVulkan.cpp | 7 +++++-- GPU/Vulkan/TextureCacheVulkan.h | 1 - ext/native/thin3d/VulkanContext.h | 6 +++--- 5 files changed, 14 insertions(+), 9 deletions(-) diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index e49888fd83..cfd9b11564 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -394,6 +394,7 @@ VkDescriptorSet DrawEngineVulkan::GetDescriptorSet(VkImageView imageView, VkSamp VkDescriptorSet desc; VkDescriptorSetAllocateInfo descAlloc; + VkDescriptorImageInfo tex; descAlloc.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; descAlloc.pNext = nullptr; descAlloc.pSetLayouts = &descriptorSetLayout_; @@ -408,7 +409,6 @@ VkDescriptorSet DrawEngineVulkan::GetDescriptorSet(VkImageView imageView, VkSamp // Main texture int n = 0; if (imageView) { - VkDescriptorImageInfo tex; // TODO: Also support LAYOUT_GENERAL to be able to texture from framebuffers without transitioning them? tex.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; tex.imageView = imageView; @@ -480,8 +480,8 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { bool useHWTransform = CanUseHardwareTransform(prim); - VulkanVertexShader *vshader; - VulkanFragmentShader *fshader; + VulkanVertexShader *vshader = nullptr; + VulkanFragmentShader *fshader = nullptr; // TODO: Keep these between calls if not dirty. uint32_t baseUBOOffset = 0; diff --git a/GPU/Vulkan/ShaderManagerVulkan.cpp b/GPU/Vulkan/ShaderManagerVulkan.cpp index c85336868f..d8e390aebf 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.cpp +++ b/GPU/Vulkan/ShaderManagerVulkan.cpp @@ -175,6 +175,9 @@ ShaderManagerVulkan::ShaderManagerVulkan(VulkanContext *vulkan) : vulkan_(vulkan), lastVShader_(nullptr), lastFShader_(nullptr), globalDirty_(0xFFFFFFFF) { codeBuffer_ = new char[16384]; uboAlignment_ = vulkan_->GetPhysicalDeviceProperties().limits.minUniformBufferOffsetAlignment; + memset(&ub_base, 0, sizeof(ub_base)); + memset(&ub_lights, 0, sizeof(ub_lights)); + memset(&ub_bones, 0, sizeof(ub_bones)); } ShaderManagerVulkan::~ShaderManagerVulkan() { diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index 43c2da5f3e..c3f88db497 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -95,7 +95,7 @@ VkSampler SamplerCache::GetOrCreateSampler(const SamplerCacheKey &key) { samp.compareEnable = false; samp.compareOp = VK_COMPARE_OP_ALWAYS; samp.flags = 0; - samp.magFilter = (key.magFilt & 1) ? VK_FILTER_LINEAR : VK_FILTER_NEAREST; + samp.magFilter = key.magFilt ? VK_FILTER_LINEAR : VK_FILTER_NEAREST; samp.minFilter = key.minFilt ? VK_FILTER_LINEAR : VK_FILTER_NEAREST; // TODO: Aniso samp.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; // key.4) ? ((key.magFilt & 2) ? VK_SAMPLER_MIPMAP_MODE_LINEAR : VK_SAMPLER_MIPMAP_MODE_NEAREST) : VK_SAMPLER_MIPMAP_MODE_BASE; samp.maxAnisotropy = 1.0f; @@ -111,7 +111,10 @@ VkSampler SamplerCache::GetOrCreateSampler(const SamplerCacheKey &key) { return sampler; } -TextureCacheVulkan::TextureCacheVulkan(VulkanContext *vulkan) : vulkan_(vulkan), samplerCache_(vulkan), cacheSizeEstimate_(0), secondCacheSizeEstimate_(0), clearCacheNextFrame_(false), lowMemoryMode_(false), clutBuf_(NULL), texelsScaledThisFrame_(0) { +TextureCacheVulkan::TextureCacheVulkan(VulkanContext *vulkan) + : vulkan_(vulkan), samplerCache_(vulkan), cacheSizeEstimate_(0), secondCacheSizeEstimate_(0), + clearCacheNextFrame_(false), lowMemoryMode_(false), clutBuf_(NULL), texelsScaledThisFrame_(0), + clutAlphaLinear_(false) { timesInvalidatedAllThisFrame_ = 0; lastBoundTexture = nullptr; decimationCounter_ = TEXCACHE_DECIMATION_INTERVAL; diff --git a/GPU/Vulkan/TextureCacheVulkan.h b/GPU/Vulkan/TextureCacheVulkan.h index dd70514c3f..46bd17688e 100644 --- a/GPU/Vulkan/TextureCacheVulkan.h +++ b/GPU/Vulkan/TextureCacheVulkan.h @@ -170,7 +170,6 @@ private: u16 clutAlphaLinearColor_; CachedTextureVulkan *lastBoundTexture; - float maxAnisotropyLevel; int decimationCounter_; int texelsScaledThisFrame_; diff --git a/ext/native/thin3d/VulkanContext.h b/ext/native/thin3d/VulkanContext.h index 7568368d64..920aecaa9b 100644 --- a/ext/native/thin3d/VulkanContext.h +++ b/ext/native/thin3d/VulkanContext.h @@ -345,6 +345,7 @@ public: VulkanTexture(VulkanContext *vulkan) : vulkan_(vulkan), image(nullptr), imageLayout(VK_IMAGE_LAYOUT_UNDEFINED), mem(nullptr), view(nullptr), tex_width(0), tex_height(0), format_(VK_FORMAT_UNDEFINED), mappableImage(nullptr), mappableMemory(nullptr), needStaging(false) { + memset(&mem_reqs, 0, sizeof(mem_reqs)); } ~VulkanTexture() { Destroy(); @@ -383,7 +384,6 @@ private: class VulkanFramebuffer { public: void Create(VulkanContext *vulkan, int w, int h, VkFormat format); - // void TransitionToImage() void BeginPass(VkCommandBuffer cmd); void EndPass(VkCommandBuffer cmd); @@ -407,7 +407,7 @@ public: VulkanPushBuffer(VulkanContext *vulkan, size_t size) : offset_(0), size_(size), writePtr_(nullptr), deviceMemory_(nullptr) { VkDevice device = vulkan->GetDevice(); - VkBufferCreateInfo b; + VkBufferCreateInfo b = {}; b.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; b.pNext = nullptr; b.size = size; @@ -420,7 +420,7 @@ public: assert(VK_SUCCESS == res); // Okay, that's the buffer. Now let's allocate some memory for it. - VkMemoryAllocateInfo alloc; + VkMemoryAllocateInfo alloc = {}; alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; alloc.pNext = nullptr; vulkan->MemoryTypeFromProperties(0xFFFFFFFF, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, &alloc.memoryTypeIndex); From 2e998891a4f336da8726e074795da07a142a9cf7 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 10 Jan 2016 13:47:56 +0100 Subject: [PATCH 041/116] The settings to the vertex decoder must match the implementation.. Fixes some character scale issues. --- GPU/Vulkan/DrawEngineVulkan.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index cfd9b11564..1388fea7bb 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -74,9 +74,9 @@ DrawEngineVulkan::DrawEngineVulkan(VulkanContext *vulkan) curFrame_(0) { memset(&decOptions_, 0, sizeof(decOptions_)); - decOptions_.expandAllUVtoFloat = true; - decOptions_.expandAllWeightsToFloat = true; - decOptions_.expand8BitNormalsToFloat = true; + decOptions_.expandAllUVtoFloat = false; + decOptions_.expandAllWeightsToFloat = false; + decOptions_.expand8BitNormalsToFloat = false; // Allocate nicely aligned memory. Maybe graphics drivers will // appreciate it. @@ -125,6 +125,7 @@ DrawEngineVulkan::DrawEngineVulkan(VulkanContext *vulkan) dsl.bindingCount = 5; dsl.pBindings = bindings; VkResult res = vkCreateDescriptorSetLayout(device, &dsl, nullptr, &descriptorSetLayout_); + assert(VK_SUCCESS == res); VkDescriptorPoolSize dpTypes[2]; dpTypes[0].descriptorCount = 800; From 3284899844854569858e1ac6177d987f5fa5b2c0 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 10 Jan 2016 14:24:10 +0100 Subject: [PATCH 042/116] More clearing fixes. Also fix some memory leaks. --- GPU/Vulkan/DrawEngineVulkan.cpp | 1 + GPU/Vulkan/FramebufferVulkan.cpp | 1896 +++++++++++++++++++++++++- GPU/Vulkan/FramebufferVulkan.h | 207 ++- GPU/Vulkan/GPU_Vulkan.cpp | 70 +- GPU/Vulkan/GPU_Vulkan.h | 6 +- GPU/Vulkan/PipelineManagerVulkan.cpp | 4 + GPU/Vulkan/PipelineManagerVulkan.h | 4 +- GPU/Vulkan/ShaderManagerVulkan.cpp | 10 +- GPU/Vulkan/ShaderManagerVulkan.h | 3 +- ext/native/thin3d/VulkanContext.cpp | 36 +- ext/native/thin3d/thin3d_vulkan.cpp | 3 + ext/vulkan/vk_sdk_platform.h | 2 + 12 files changed, 2093 insertions(+), 149 deletions(-) diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index 1388fea7bb..bdfa8612f3 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -43,6 +43,7 @@ #include "GPU/Vulkan/TextureCacheVulkan.h" #include "GPU/Vulkan/ShaderManagerVulkan.h" #include "GPU/Vulkan/PipelineManagerVulkan.h" +#include "GPU/Vulkan/FramebufferVulkan.h" #include "GPU/Vulkan/GPU_Vulkan.h" enum { diff --git a/GPU/Vulkan/FramebufferVulkan.cpp b/GPU/Vulkan/FramebufferVulkan.cpp index 378e4921fe..76c621c6f2 100644 --- a/GPU/Vulkan/FramebufferVulkan.cpp +++ b/GPU/Vulkan/FramebufferVulkan.cpp @@ -17,46 +17,1818 @@ #pragma once +#include +#include + +#include "profiler/profiler.h" + +#include "base/timeutil.h" +#include "math/lin/matrix4x4.h" +#include "thin3d/VulkanContext.h" + +#include "Common/ColorConv.h" +#include "Core/Host.h" +#include "Core/MemMap.h" +#include "Core/Config.h" +#include "Core/System.h" +#include "Core/Reporting.h" +#include "Core/HLE/sceDisplay.h" +#include "GPU/ge_constants.h" +#include "GPU/GPUState.h" + +#include "GPU/Common/PostShader.h" +#include "GPU/Common/TextureDecoder.h" +#include "GPU/Common/FramebufferCommon.h" +#include "GPU/Debugger/Stepping.h" + #include "GPU/GPUInterface.h" #include "GPU/GPUState.h" #include "GPU/Vulkan/FramebufferVulkan.h" #include "GPU/Vulkan/DrawEngineVulkan.h" +#include "GPU/Vulkan/TextureCacheVulkan.h" +#include "GPU/Vulkan/ShaderManagerVulkan.h" + +#include "UI/OnScreenDisplay.h" + +extern int g_iNumVideos; +static const char tex_fs[] = +"layout (binding = 0) uniform sampler2D sampler0;\n" +"layout (location = 0) in vec2 v_texcoord0;\n" +"void main() {\n" +" gl_FragColor = texture2D(sampler0, v_texcoord0);\n" +"}\n"; -VulkanFramebuffer *FramebufferManagerVulkan::GetTempFBO(int width, int height, VulkanFBOColorDepth colorDepth) { - return nullptr; +static const char basic_vs[] = +"layout (location = 0) in vec4 a_position;\n" +"layout (location = 1) in attribute vec2 a_texcoord0;\n" +"layout (location = 0) out vec2 v_texcoord0;\n" +"void main() {\n" +" v_texcoord0 = a_texcoord0;\n" +" gl_Position = a_position;\n" +"}\n"; + +void ConvertFromRGBA8888_Vulkan(u8 *dst, const u8 *src, u32 dstStride, u32 srcStride, u32 width, u32 height, GEBufferFormat format); + +void FramebufferManagerVulkan::ClearBuffer(bool keepState) { + // keepState is irrelevant. + if (!currentRenderVfb_) { + return; + } + VkClearAttachment clear[2]; + memset(clear, 0, sizeof(clear)); + clear[0].aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + clear[1].aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; + VkClearRect rc; + rc.baseArrayLayer = 0; + rc.layerCount = 1; + rc.rect.offset.x = 0; + rc.rect.offset.y = 0; + rc.rect.extent.width = currentRenderVfb_->bufferWidth; + rc.rect.extent.height = currentRenderVfb_->bufferHeight; + vkCmdClearAttachments(curCmd_, 2, clear, 1, &rc); } -void FramebufferManagerVulkan::DestroyAllFBOs() { - +void FramebufferManagerVulkan::DisableState() { } -void FramebufferManagerVulkan::Resized() { +void FramebufferManagerVulkan::SetNumExtraFBOs(int num) { + /* + for (size_t i = 0; i < extraFBOs_.size(); i++) { + fbo_destroy(extraFBOs_[i]); + } + extraFBOs_.clear(); + for (int i = 0; i < num; i++) { + // No depth/stencil for post processing + FBO *fbo_vk = fbo_create(renderWidth_, renderHeight_, 1, false, FBO_8888); + extraFBOs_.push_back(fbo_vk); + // The new FBO is still bound after creation, but let's bind it anyway. + fbo_bind_as_render_target(fbo_vk); + ClearBuffer(); + } + + currentRenderVfb_ = 0; + fbo_unbind(); + */ } -void FramebufferManagerVulkan::DeviceLost() { +void FramebufferManagerVulkan::CompileDraw2DProgram() { + /* + if (!draw2dprogram_) { + std::string errorString; + draw2dprogram_ = glsl_create_source(basic_vs, tex_fs, &errorString); + if (!draw2dprogram_) { + ERROR_LOG_REPORT(G3D, "Failed to compile draw2dprogram! This shouldn't happen.\n%s", errorString.c_str()); + } else { + glsl_bind(draw2dprogram_); + glUniform1i(draw2dprogram_->sampler0, 0); + } + plainColorProgram_ = glsl_create_source(color_vs, color_fs, &errorString); + if (!plainColorProgram_) { + ERROR_LOG_REPORT(G3D, "Failed to compile plainColorProgram! This shouldn't happen.\n%s", errorString.c_str()); + } else { + glsl_bind(plainColorProgram_); + plainColorLoc_ = glsl_uniform_loc(plainColorProgram_, "u_color"); + } + + SetNumExtraFBOs(0); + const ShaderInfo *shaderInfo = 0; + if (g_Config.sPostShaderName != "Off") { + shaderInfo = GetPostShaderInfo(g_Config.sPostShaderName); + } + + if (shaderInfo) { + postShaderAtOutputResolution_ = shaderInfo->outputResolution; + postShaderProgram_ = glsl_create(shaderInfo->vertexShaderFile.c_str(), shaderInfo->fragmentShaderFile.c_str(), &errorString); + if (!postShaderProgram_) { + // DO NOT turn this into a report, as it will pollute our logs with all kinds of + // user shader experiments. + ERROR_LOG(G3D, "Failed to build post-processing program from %s and %s!\n%s", shaderInfo->vertexShaderFile.c_str(), shaderInfo->fragmentShaderFile.c_str(), errorString.c_str()); + // let's show the first line of the error string as an OSM. + std::set blacklistedLines; + // These aren't useful to show, skip to the first interesting line. + blacklistedLines.insert("Fragment shader failed to compile with the following errors:"); + blacklistedLines.insert("Vertex shader failed to compile with the following errors:"); + blacklistedLines.insert("Compile failed."); + blacklistedLines.insert(""); + + std::string firstLine; + size_t start = 0; + for (size_t i = 0; i < errorString.size(); i++) { + if (errorString[i] == '\n') { + firstLine = errorString.substr(start, i - start); + if (blacklistedLines.find(firstLine) == blacklistedLines.end()) { + break; + } + start = i + 1; + firstLine.clear(); + } + } + if (!firstLine.empty()) { + osm.Show("Post-shader error: " + firstLine + "...", 10.0f, 0xFF3090FF); + } else { + osm.Show("Post-shader error, see log for details", 10.0f, 0xFF3090FF); + } + usePostShader_ = false; + } else { + glsl_bind(postShaderProgram_); + glUniform1i(postShaderProgram_->sampler0, 0); + SetNumExtraFBOs(1); + deltaLoc_ = glsl_uniform_loc(postShaderProgram_, "u_texelDelta"); + pixelDeltaLoc_ = glsl_uniform_loc(postShaderProgram_, "u_pixelDelta"); + timeLoc_ = glsl_uniform_loc(postShaderProgram_, "u_time"); + usePostShader_ = true; + } + } else { + postShaderProgram_ = nullptr; + usePostShader_ = false; + } + + glsl_unbind(); + } + */ } -void FramebufferManagerVulkan::CopyDisplayToOutput() { +void FramebufferManagerVulkan::UpdatePostShaderUniforms(int bufferWidth, int bufferHeight, int renderWidth, int renderHeight) { + float u_delta = 1.0f / renderWidth; + float v_delta = 1.0f / renderHeight; + float u_pixel_delta = u_delta; + float v_pixel_delta = v_delta; + if (postShaderAtOutputResolution_) { + float x, y, w, h; + CenterDisplayOutputRect(&x, &y, &w, &h, 480.0f, 272.0f, (float)pixelWidth_, (float)pixelHeight_, ROTATION_LOCKED_HORIZONTAL); + u_pixel_delta = (1.0f / w) * (480.0f / bufferWidth); + v_pixel_delta = (1.0f / h) * (272.0f / bufferHeight); + } + postUniforms_.texelDelta[0] = u_delta; + postUniforms_.texelDelta[1] = v_delta; + postUniforms_.pixelDelta[0] = u_pixel_delta; + postUniforms_.pixelDelta[1] = v_pixel_delta; + int flipCount = __DisplayGetFlipCount(); + int vCount = __DisplayGetVCount(); + float time[4] = { time_now(), (vCount % 60) * 1.0f / 60.0f, (float)vCount, (float)(flipCount % 60) }; + memcpy(postUniforms_.time, time, 4 * sizeof(float)); } -void FramebufferManagerVulkan::DecimateFBOs() { - +void FramebufferManagerVulkan::DestroyDraw2DProgram() { + /* + if (draw2dprogram_) { + glsl_destroy(draw2dprogram_); + draw2dprogram_ = nullptr; + } + if (postShaderProgram_) { + glsl_destroy(postShaderProgram_); + postShaderProgram_ = nullptr; + } + */ } -void FramebufferManagerVulkan::EndFrame() { +FramebufferManagerVulkan::FramebufferManagerVulkan(VulkanContext *vulkan) : + vulkan_(vulkan), + drawPixelsTex_(0), + drawPixelsTexFormat_(GE_FORMAT_INVALID), + convBuf_(nullptr), + textureCache_(nullptr), + shaderManager_(nullptr), + resized_(false), + pixelBufObj_(nullptr), + currentPBO_(0) { +} +FramebufferManagerVulkan::~FramebufferManagerVulkan() { + /* + if (drawPixelsTex_) + glDeleteTextures(1, &drawPixelsTex_); + DestroyDraw2DProgram(); + if (stencilUploadProgram_) { + glsl_destroy(stencilUploadProgram_); + } + SetNumExtraFBOs(0); + + for (auto it = tempFBOs_.begin(), end = tempFBOs_.end(); it != end; ++it) { + fbo_destroy(it->second.fbo_vk); + } + + delete[] pixelBufObj_; + delete[] convBuf_; + */ +} + +void FramebufferManagerVulkan::Init() { + FramebufferManagerCommon::Init(); + // Workaround for upscaling shaders where we force x1 resolution without saving it + resized_ = true; + CompileDraw2DProgram(); +} + +void FramebufferManagerVulkan::MakePixelTexture(const u8 *srcPixels, GEBufferFormat srcPixelFormat, int srcStride, int width, int height) { + /* + if (drawPixelsTex_ && (drawPixelsTexFormat_ != srcPixelFormat || drawPixelsTexW_ != width || drawPixelsTexH_ != height)) { + glDeleteTextures(1, &drawPixelsTex_); + drawPixelsTex_ = 0; + } + + if (!drawPixelsTex_) { + drawPixelsTex_ = textureCache_->AllocTextureName(); + drawPixelsTexW_ = width; + drawPixelsTexH_ = height; + + // Initialize backbuffer texture for DrawPixels + glBindTexture(GL_TEXTURE_2D, drawPixelsTex_); + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); + drawPixelsTexFormat_ = srcPixelFormat; + } else { + glBindTexture(GL_TEXTURE_2D, drawPixelsTex_); + } + + // TODO: We can just change the texture format and flip some bits around instead of this. + // Could share code with the texture cache perhaps. + bool useConvBuf = false; + if (srcPixelFormat != GE_FORMAT_8888 || srcStride != width) { + useConvBuf = true; + u32 neededSize = width * height * 4; + if (!convBuf_ || convBufSize_ < neededSize) { + delete[] convBuf_; + convBuf_ = new u8[neededSize]; + convBufSize_ = neededSize; + } + for (int y = 0; y < height; y++) { + switch (srcPixelFormat) { + case GE_FORMAT_565: + { + const u16 *src = (const u16 *)srcPixels + srcStride * y; + u8 *dst = convBuf_ + 4 * width * y; + ConvertRGBA565ToRGBA8888((u32 *)dst, src, width); + } + break; + + case GE_FORMAT_5551: + { + const u16 *src = (const u16 *)srcPixels + srcStride * y; + u8 *dst = convBuf_ + 4 * width * y; + ConvertRGBA5551ToRGBA8888((u32 *)dst, src, width); + } + break; + + case GE_FORMAT_4444: + { + const u16 *src = (const u16 *)srcPixels + srcStride * y; + u8 *dst = convBuf_ + 4 * width * y; + ConvertRGBA4444ToRGBA8888((u32 *)dst, src, width); + } + break; + + case GE_FORMAT_8888: + { + const u8 *src = srcPixels + srcStride * 4 * y; + u8 *dst = convBuf_ + 4 * width * y; + memcpy(dst, src, 4 * width); + } + break; + + case GE_FORMAT_INVALID: + _dbg_assert_msg_(G3D, false, "Invalid pixelFormat passed to DrawPixels()."); + break; + } + } + } + glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, useConvBuf ? convBuf_ : srcPixels); + */ } void FramebufferManagerVulkan::DrawPixels(VirtualFramebuffer *vfb, int dstX, int dstY, const u8 *srcPixels, GEBufferFormat srcPixelFormat, int srcStride, int width, int height) { - // So: Allocate a temporary texture from a (very small) pool, upload content directly into it, schedule a transition - // into the init command buffer, alloc and create an appropriate descriptor set, then bind and draw. no need for uniforms. + /* + float v0 = 0.0f, v1 = 1.0f; + if (useBufferedRendering_ && vfb && vfb->fbo_vk) { + fbo_bind_as_render_target(vfb->fbo_vk); + glViewport(0, 0, vfb->renderWidth, vfb->renderHeight); + } else { + // We are drawing to the back buffer so need to flip. + v0 = 1.0f; + v1 = 0.0f; + float x, y, w, h; + CenterDisplayOutputRect(&x, &y, &w, &h, 480.0f, 272.0f, (float)pixelWidth_, (float)pixelHeight_, ROTATION_LOCKED_HORIZONTAL); + glViewport(x, y, w, h); + } + + MakePixelTexture(srcPixels, srcPixelFormat, srcStride, width, height); + + DrawActiveTexture(0, dstX, dstY, width, height, vfb->bufferWidth, vfb->bufferHeight, 0.0f, v0, 1.0f, v1, nullptr, ROTATION_LOCKED_HORIZONTAL); + textureCache_->ForgetLastTexture(); + */ } +void FramebufferManagerVulkan::DrawFramebufferToOutput(const u8 *srcPixels, GEBufferFormat srcPixelFormat, int srcStride, bool applyPostShader) { + /* + MakePixelTexture(srcPixels, srcPixelFormat, srcStride, 512, 272); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, g_Config.iTexFiltering == TEX_FILTER_NEAREST ? GL_NEAREST : GL_LINEAR); + + struct CardboardSettings cardboardSettings; + GetCardboardSettings(&cardboardSettings); + + // This might draw directly at the backbuffer (if so, applyPostShader is set) so if there's a post shader, we need to apply it here. + // Should try to unify this path with the regular path somehow, but this simple solution works for most of the post shaders + // (it always runs at output resolution so FXAA may look odd). + float x, y, w, h; + int uvRotation = (g_Config.iRenderingMode != FB_NON_BUFFERED_MODE) ? g_Config.iInternalScreenRotation : ROTATION_LOCKED_HORIZONTAL; + CenterDisplayOutputRect(&x, &y, &w, &h, 480.0f, 272.0f, (float)pixelWidth_, (float)pixelHeight_, uvRotation); + if (applyPostShader) { + // Make sure we've compiled the shader. + if (!postShaderProgram_) { + CompileDraw2DProgram(); + } + // Might've changed if the shader was just changed to Off. + if (usePostShader_) { + glsl_bind(postShaderProgram_); + UpdatePostShaderUniforms(480, 272, renderWidth_, renderHeight_); + } + } + float u0 = 0.0f, u1 = 480.0f / 512.0f; + float v0 = 0.0f, v1 = 1.0f; + + // We are drawing directly to the back buffer. + std::swap(v0, v1); + + if (cardboardSettings.enabled) { + // Left Eye Image + glstate.viewport.set(cardboardSettings.leftEyeXPosition, cardboardSettings.screenYPosition, cardboardSettings.screenWidth, cardboardSettings.screenHeight); + if (applyPostShader && usePostShader_ && useBufferedRendering_) { + DrawActiveTexture(0, x, y, w, h, (float)pixelWidth_, (float)pixelHeight_, u0, v0, u1, v1, postShaderProgram_, ROTATION_LOCKED_HORIZONTAL); + } else { + DrawActiveTexture(0, x, y, w, h, (float)pixelWidth_, (float)pixelHeight_, u0, v0, u1, v1, nullptr, ROTATION_LOCKED_HORIZONTAL); + } + + // Right Eye Image + glstate.viewport.set(cardboardSettings.rightEyeXPosition, cardboardSettings.screenYPosition, cardboardSettings.screenWidth, cardboardSettings.screenHeight); + if (applyPostShader && usePostShader_ && useBufferedRendering_) { + DrawActiveTexture(0, x, y, w, h, (float)pixelWidth_, (float)pixelHeight_, u0, v0, u1, v1, postShaderProgram_, ROTATION_LOCKED_HORIZONTAL); + } else { + DrawActiveTexture(0, x, y, w, h, (float)pixelWidth_, (float)pixelHeight_, u0, v0, u1, v1, nullptr, ROTATION_LOCKED_HORIZONTAL); + } + } else { + // Fullscreen Image + glstate.viewport.set(0, 0, pixelWidth_, pixelHeight_); + if (applyPostShader && usePostShader_ && useBufferedRendering_) { + DrawActiveTexture(0, x, y, w, h, (float)pixelWidth_, (float)pixelHeight_, u0, v0, u1, v1, postShaderProgram_, uvRotation); + } else { + DrawActiveTexture(0, x, y, w, h, (float)pixelWidth_, (float)pixelHeight_, u0, v0, u1, v1, nullptr, uvRotation); + } + } + */ +} + +// x, y, w, h are relative coordinates against destW/destH, which is not very intuitive. +void FramebufferManagerVulkan::DrawActiveTexture(VulkanTexture *texture, float x, float y, float w, float h, float destW, float destH, float u0, float v0, float u1, float v1, VkPipeline pipeline, int uvRotation) { + /* + float texCoords[8] = { + u0,v0, + u1,v0, + u1,v1, + u0,v1, + }; + + static const GLubyte indices[4] = { 0,1,3,2 }; + + if (uvRotation != ROTATION_LOCKED_HORIZONTAL) { + float temp[8]; + int rotation = 0; + switch (uvRotation) { + case ROTATION_LOCKED_HORIZONTAL180: rotation = 4; break; + case ROTATION_LOCKED_VERTICAL: rotation = 2; break; + case ROTATION_LOCKED_VERTICAL180: rotation = 6; break; + } + for (int i = 0; i < 8; i++) { + temp[i] = texCoords[(i + rotation) & 7]; + } + memcpy(texCoords, temp, sizeof(temp)); + } + + if (texture) { + // Previously had NVDrawTexture fallback here but wasn't worth it. + glBindTexture(GL_TEXTURE_2D, texture); + } + + float pos[12] = { + x,y,0, + x + w,y,0, + x + w,y + h,0, + x,y + h,0 + }; + + float invDestW = 1.0f / (destW * 0.5f); + float invDestH = 1.0f / (destH * 0.5f); + for (int i = 0; i < 4; i++) { + pos[i * 3] = pos[i * 3] * invDestW - 1.0f; + pos[i * 3 + 1] = pos[i * 3 + 1] * invDestH - 1.0f; + } + + if (!program) { + if (!draw2dprogram_) { + CompileDraw2DProgram(); + } + + program = draw2dprogram_; + } + + // Upscaling postshaders doesn't look well with linear + if (postShaderIsUpscalingFilter_) { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + } else { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, g_Config.iBufFilter == SCALE_NEAREST ? GL_NEAREST : GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, g_Config.iBufFilter == SCALE_NEAREST ? GL_NEAREST : GL_LINEAR); + } + + if (program != postShaderProgram_) { + shaderManager_->DirtyLastShader(); // dirty lastShader_ + glsl_bind(program); + } + + glEnableVertexAttribArray(program->a_position); + glEnableVertexAttribArray(program->a_texcoord0); + if (gstate_c.Supports(GPU_SUPPORTS_VAO)) { + transformDraw_->BindBuffer(pos, sizeof(pos), texCoords, sizeof(texCoords)); + transformDraw_->BindElementBuffer(indices, sizeof(indices)); + glVertexAttribPointer(program->a_position, 3, GL_FLOAT, GL_FALSE, 12, 0); + glVertexAttribPointer(program->a_texcoord0, 2, GL_FLOAT, GL_FALSE, 8, (void *)sizeof(pos)); + glDrawElements(GL_TRIANGLE_STRIP, 4, GL_UNSIGNED_BYTE, 0); + } else { + glstate.arrayBuffer.unbind(); + glstate.elementArrayBuffer.unbind(); + glVertexAttribPointer(program->a_position, 3, GL_FLOAT, GL_FALSE, 12, pos); + glVertexAttribPointer(program->a_texcoord0, 2, GL_FLOAT, GL_FALSE, 8, texCoords); + glDrawElements(GL_TRIANGLE_STRIP, 4, GL_UNSIGNED_BYTE, indices); + } + glDisableVertexAttribArray(program->a_position); + glDisableVertexAttribArray(program->a_texcoord0); + + glsl_unbind(); + */ +} + +void FramebufferManagerVulkan::DestroyFramebuf(VirtualFramebuffer *v) { + textureCache_->NotifyFramebuffer(v->fb_address, v, NOTIFY_FB_DESTROYED); + if (v->fbo_vk) { + delete v->fbo_vk; + v->fbo_vk = 0; + } + + // Wipe some pointers + if (currentRenderVfb_ == v) + currentRenderVfb_ = 0; + if (displayFramebuf_ == v) + displayFramebuf_ = 0; + if (prevDisplayFramebuf_ == v) + prevDisplayFramebuf_ = 0; + if (prevPrevDisplayFramebuf_ == v) + prevPrevDisplayFramebuf_ = 0; + + delete v; +} + +void FramebufferManagerVulkan::RebindFramebuffer() { + /* + if (currentRenderVfb_ && currentRenderVfb_->fbo_vk) { + ImagcurrentRenderVfb_->fbo_vk->GetColorImageView(); + } else { + fbo_unbind(); + } + if (g_Config.iRenderingMode == FB_NON_BUFFERED_MODE) + glstate.viewport.restore(); + */ +} + +void FramebufferManagerVulkan::ResizeFramebufFBO(VirtualFramebuffer *vfb, u16 w, u16 h, bool force) { + VirtualFramebuffer old = *vfb; + + if (force) { + vfb->bufferWidth = w; + vfb->bufferHeight = h; + } else { + if (vfb->bufferWidth >= w && vfb->bufferHeight >= h) { + return; + } + + // In case it gets thin and wide, don't resize down either side. + vfb->bufferWidth = std::max(vfb->bufferWidth, w); + vfb->bufferHeight = std::max(vfb->bufferHeight, h); + } + + SetRenderSize(vfb); + + bool trueColor = g_Config.bTrueColor; + if (hackForce04154000Download_ && vfb->fb_address == 0x00154000) { + trueColor = true; + } + + if (trueColor) { + vfb->colorDepth = VK_FBO_8888; + } else { + switch (vfb->format) { + case GE_FORMAT_4444: + vfb->colorDepth = VK_FBO_4444; + break; + case GE_FORMAT_5551: + vfb->colorDepth = VK_FBO_5551; + break; + case GE_FORMAT_565: + vfb->colorDepth = VK_FBO_565; + break; + case GE_FORMAT_8888: + default: + vfb->colorDepth = VK_FBO_8888; + break; + } + } + + textureCache_->ForgetLastTexture(); + + if (!useBufferedRendering_) { + if (vfb->fbo_vk) { + delete vfb->fbo_vk; + vfb->fbo_vk = 0; + } + return; + } + + vfb->fbo_vk = new VulkanFramebuffer(); + // bo_create(vfb->renderWidth, vfb->renderHeight, 1, true, (FBOColorDepth)vfb->colorDepth); + if (old.fbo_vk) { + INFO_LOG(SCEGE, "Resizing FBO for %08x : %i x %i x %i", vfb->fb_address, w, h, vfb->format); + if (vfb->fbo_vk) { + /// fbo_bind_as_render_target(vfb->fbo_vk); + ClearBuffer(); + if (!g_Config.bDisableSlowFramebufEffects) { + BlitFramebuffer(vfb, 0, 0, &old, 0, 0, std::min(vfb->bufferWidth, vfb->width), std::min(vfb->height, vfb->bufferHeight), 0); + } + } + delete old.fbo_vk; + if (vfb->fbo_vk) { + // fbo_bind_as_render_target(vfb->fbo_vk); + } + } + + if (!vfb->fbo_vk) { + ERROR_LOG(SCEGE, "Error creating FBO! %i x %i", vfb->renderWidth, vfb->renderHeight); + } +} + +void FramebufferManagerVulkan::NotifyRenderFramebufferCreated(VirtualFramebuffer *vfb) { + if (!useBufferedRendering_) { + // Let's ignore rendering to targets that have not (yet) been displayed. + gstate_c.skipDrawReason |= SKIPDRAW_NON_DISPLAYED_FB; + } + + textureCache_->NotifyFramebuffer(vfb->fb_address, vfb, NOTIFY_FB_CREATED); + + // Some AMD drivers crash if we don't clear the buffer first? + /* + glDisable(GL_DITHER); // why? + ClearBuffer(); + */ + + // ugly... + if ((gstate_c.curRTWidth != vfb->width || gstate_c.curRTHeight != vfb->height) && shaderManager_) { + shaderManager_->DirtyUniform(DIRTY_PROJMATRIX); + } +} + +void FramebufferManagerVulkan::NotifyRenderFramebufferSwitched(VirtualFramebuffer *prevVfb, VirtualFramebuffer *vfb, bool isClearingDepth) { + if (ShouldDownloadFramebuffer(vfb) && !vfb->memoryUpdated) { + ReadFramebufferToMemory(vfb, true, 0, 0, vfb->width, vfb->height); + } + textureCache_->ForgetLastTexture(); + + if (useBufferedRendering_) { + if (vfb->fbo_vk) { + // vfb->fbo_vk->GetColorImageView(); + } + } else { + if (vfb->fbo_vk) { + // wtf? This should only happen very briefly when toggling bBufferedRendering + textureCache_->NotifyFramebuffer(vfb->fb_address, vfb, NOTIFY_FB_DESTROYED); + delete vfb->fbo_vk; + vfb->fbo_vk = nullptr; + } + + // Let's ignore rendering to targets that have not (yet) been displayed. + if (vfb->usageFlags & FB_USAGE_DISPLAYED_FRAMEBUFFER) { + gstate_c.skipDrawReason &= ~SKIPDRAW_NON_DISPLAYED_FB; + } else { + gstate_c.skipDrawReason |= SKIPDRAW_NON_DISPLAYED_FB; + } + } + textureCache_->NotifyFramebuffer(vfb->fb_address, vfb, NOTIFY_FB_UPDATED); + + // Copy depth pixel value from the read framebuffer to the draw framebuffer + if (prevVfb && !g_Config.bDisableSlowFramebufEffects) { + if (!prevVfb->fbo_vk || !vfb->fbo_vk || !useBufferedRendering_ || !prevVfb->depthUpdated || isClearingDepth) { + // If depth wasn't updated, then we're at least "two degrees" away from the data. + // This is an optimization: it probably doesn't need to be copied in this case. + } else { + BlitFramebufferDepth(prevVfb, vfb); + } + } + if (vfb->drawnFormat != vfb->format) { + // TODO: Might ultimately combine this with the resize step in DoSetRenderFrameBuffer(). + ReformatFramebufferFrom(vfb, vfb->drawnFormat); + } + + // ugly... + if ((gstate_c.curRTWidth != vfb->width || gstate_c.curRTHeight != vfb->height) && shaderManager_) { + shaderManager_->DirtyUniform(DIRTY_PROJMATRIX); + } +} + +void FramebufferManagerVulkan::NotifyRenderFramebufferUpdated(VirtualFramebuffer *vfb, bool vfbFormatChanged) { + if (vfbFormatChanged) { + textureCache_->NotifyFramebuffer(vfb->fb_address, vfb, NOTIFY_FB_UPDATED); + if (vfb->drawnFormat != vfb->format) { + ReformatFramebufferFrom(vfb, vfb->drawnFormat); + } + } + + // ugly... + if ((gstate_c.curRTWidth != vfb->width || gstate_c.curRTHeight != vfb->height) && shaderManager_) { + shaderManager_->DirtyUniform(DIRTY_PROJMATRIX); + } +} + +bool FramebufferManagerVulkan::NotifyStencilUpload(u32 addr, int size, bool skipZero) { + // In Vulkan we should be able to simply copy the stencil data directly to a stencil buffer without + // messing about with bitplane textures and the like. + return false; +} + + +int FramebufferManagerVulkan::GetLineWidth() { + if (g_Config.iInternalResolution == 0) { + return std::max(1, (int)(renderWidth_ / 480)); + } else { + return g_Config.iInternalResolution; + } +} + +void FramebufferManagerVulkan::ReformatFramebufferFrom(VirtualFramebuffer *vfb, GEBufferFormat old) { + if (!useBufferedRendering_ || !vfb->fbo_vk) { + return; + } + /* + fbo_bind_as_render_target(vfb->fbo); + + // Technically, we should at this point re-interpret the bytes of the old format to the new. + // That might get tricky, and could cause unnecessary slowness in some games. + // For now, we just clear alpha/stencil from 565, which fixes shadow issues in Kingdom Hearts. + // (it uses 565 to write zeros to the buffer, than 4444 to actually render the shadow.) + // + // The best way to do this may ultimately be to create a new FBO (combine with any resize?) + // and blit with a shader to that, then replace the FBO on vfb. Stencil would still be complex + // to exactly reproduce in 4444 and 8888 formats. + + if (old == GE_FORMAT_565) { + glstate.scissorTest.disable(); + glstate.depthWrite.set(GL_FALSE); + glstate.colorMask.set(false, false, false, true); + glstate.stencilFunc.set(GL_ALWAYS, 0, 0); + glstate.stencilMask.set(0xFF); + glClearColor(0.0f, 0.0f, 0.0f, 0.0f); + glClearStencil(0); + glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); + } + + RebindFramebuffer(); + */ +} + +void FramebufferManagerVulkan::BlitFramebufferDepth(VirtualFramebuffer *src, VirtualFramebuffer *dst) { + /* + if (src->z_address == dst->z_address && + src->z_stride != 0 && dst->z_stride != 0 && + src->renderWidth == dst->renderWidth && + src->renderHeight == dst->renderHeight) { + + if (gstate_c.Supports(GPU_SUPPORTS_ARB_FRAMEBUFFER_BLIT | GPU_SUPPORTS_NV_FRAMEBUFFER_BLIT)) { + // Only use NV if ARB isn't supported. + bool useNV = !gstate_c.Supports(GPU_SUPPORTS_ARB_FRAMEBUFFER_BLIT); + + // Let's only do this if not clearing depth. + fbo_bind_for_read(src->fbo); + glstate.scissorTest.force(false); + + if (useNV) { +#if defined(USING_GLES2) && defined(ANDROID) // We only support this extension on Android, it's not even available on PC. + glBlitFramebufferNV(0, 0, src->renderWidth, src->renderHeight, 0, 0, dst->renderWidth, dst->renderHeight, GL_DEPTH_BUFFER_BIT, GL_NEAREST); +#endif // defined(USING_GLES2) && defined(ANDROID) + } else { + glBlitFramebuffer(0, 0, src->renderWidth, src->renderHeight, 0, 0, dst->renderWidth, dst->renderHeight, GL_DEPTH_BUFFER_BIT, GL_NEAREST); + } + // If we set dst->depthUpdated here, our optimization above would be pointless. + + glstate.scissorTest.restore(); + } + }*/ +} + +VulkanFramebuffer *FramebufferManagerVulkan::GetTempFBO(u16 w, u16 h, VulkanFBOColorDepth depth) { + u64 key = ((u64)depth << 32) | ((u32)w << 16) | h; + auto it = tempFBOs_.find(key); + if (it != tempFBOs_.end()) { + it->second.last_frame_used = gpuStats.numFlips; + return it->second.fbo_vk; + } + + textureCache_->ForgetLastTexture(); + // FBO *fbo_vk = fbo_create(w, h, 1, false, depth); + VulkanFramebuffer *fbo_vk = new VulkanFramebuffer(); + if (!fbo_vk) + return nullptr; + // fbo_bind_as_render_target(fbo_vk); + // fbo_vk->GetColorImageView() + // ClearBuffer(true); + const TempFBO info = { fbo_vk, gpuStats.numFlips }; + tempFBOs_[key] = info; + return fbo_vk; +} + +void FramebufferManagerVulkan::BindFramebufferColor(int stage, u32 fbRawAddress, VirtualFramebuffer *framebuffer, int flags) { + if (framebuffer == NULL) { + framebuffer = currentRenderVfb_; + } + + /* + if (stage != GL_TEXTURE0) { + glActiveTexture(stage); + } + + if (!framebuffer->fbo_vk || !useBufferedRendering_) { + glBindTexture(GL_TEXTURE_2D, 0); + glActiveTexture(GL_TEXTURE0); + gstate_c.skipDrawReason |= SKIPDRAW_BAD_FB_TEXTURE; + return; + } + + // currentRenderVfb_ will always be set when this is called, except from the GE debugger. + // Let's just not bother with the copy in that case. + bool skipCopy = (flags & BINDFBCOLOR_MAY_COPY) == 0; + if (GPUStepping::IsStepping() || g_Config.bDisableSlowFramebufEffects) { + skipCopy = true; + } + if (!skipCopy && currentRenderVfb_ && framebuffer->fb_address == fbRawAddress) { + // TODO: Maybe merge with bvfbs_? Not sure if those could be packing, and they're created at a different size. + fbo_vk *renderCopy = GetTempFBO(framebuffer->renderWidth, framebuffer->renderHeight, (FBOColorDepth)framebuffer->colorDepth); + if (renderCopy) { + VirtualFramebuffer copyInfo = *framebuffer; + copyInfo.fbo_vk = renderCopy; + + int x = 0; + int y = 0; + int w = framebuffer->drawnWidth; + int h = framebuffer->drawnHeight; + + // If max is not > min, we probably could not detect it. Skip. + // See the vertex decoder, where this is updated. + if ((flags & BINDFBCOLOR_MAY_COPY_WITH_UV) == BINDFBCOLOR_MAY_COPY_WITH_UV && gstate_c.vertBounds.maxU > gstate_c.vertBounds.minU) { + x = gstate_c.vertBounds.minU; + y = gstate_c.vertBounds.minV; + w = gstate_c.vertBounds.maxU - x; + h = gstate_c.vertBounds.maxV - y; + + // If we bound a framebuffer, apply the byte offset as pixels to the copy too. + if (flags & BINDFBCOLOR_APPLY_TEX_OFFSET) { + x += gstate_c.curTextureXOffset; + y += gstate_c.curTextureYOffset; + } + } + + BlitFramebuffer(©Info, x, y, framebuffer, x, y, w, h, 0); + + fbo_bind_color_as_texture(renderCopy, 0); + } else { + fbo_bind_color_as_texture(framebuffer->fbo_vk, 0); + } + } else { + fbo_bind_color_as_texture(framebuffer->fbo_vk, 0); + } + + if (stage != GL_TEXTURE0) { + glActiveTexture(stage); + } + */ +} + +struct CardboardSettings * FramebufferManagerVulkan::GetCardboardSettings(struct CardboardSettings * cardboardSettings) { + if (cardboardSettings) { + // Calculate Cardboard Settings + float cardboardScreenScale = g_Config.iCardboardScreenSize / 100.0f; + float cardboardScreenWidth = pixelWidth_ / 2.0f * cardboardScreenScale; + float cardboardScreenHeight = pixelHeight_ / 2.0f * cardboardScreenScale; + float cardboardMaxXShift = (pixelWidth_ / 2.0f - cardboardScreenWidth) / 2.0f; + float cardboardUserXShift = g_Config.iCardboardXShift / 100.0f * cardboardMaxXShift; + float cardboardLeftEyeX = cardboardMaxXShift + cardboardUserXShift; + float cardboardRightEyeX = pixelWidth_ / 2.0f + cardboardMaxXShift - cardboardUserXShift; + float cardboardMaxYShift = pixelHeight_ / 2.0f - cardboardScreenHeight / 2.0f; + float cardboardUserYShift = g_Config.iCardboardYShift / 100.0f * cardboardMaxYShift; + float cardboardScreenY = cardboardMaxYShift + cardboardUserYShift; + + // Copy current Settings into Structure + cardboardSettings->enabled = g_Config.bEnableCardboard; + cardboardSettings->leftEyeXPosition = cardboardLeftEyeX; + cardboardSettings->rightEyeXPosition = cardboardRightEyeX; + cardboardSettings->screenYPosition = cardboardScreenY; + cardboardSettings->screenWidth = cardboardScreenWidth; + cardboardSettings->screenHeight = cardboardScreenHeight; + } + + return cardboardSettings; +} + +void FramebufferManagerVulkan::CopyDisplayToOutput() { + // This is where we should collect all the renderpasses from this frame, + // sort them in order according to texturing dependencies, and enqueue + // them on the Vulkan context. + + // Then, we will simply perform a blit of the currently displayed framebuffer to the backbuffer. + // If there's no extra graphics to draw like framerate counters or controls, + // then in theory, we can even avoid starting up a render pass at all for the backbuffer (!). not sure if that + // is worth the needed refactoring trouble though. + + // fbo_unbind(); + // glstate.viewport.set(0, 0, pixelWidth_, pixelHeight_); + + currentRenderVfb_ = 0; + + if (useBufferedRendering_) { + // TODO: Clear here. Although it will be done through the surface pass instead.. + } + + if (displayFramebufPtr_ == 0) { + DEBUG_LOG(SCEGE, "Display disabled, displaying only black"); + // No framebuffer to display! Clear to black. + ClearBuffer(); + return; + } + + u32 offsetX = 0; + u32 offsetY = 0; + + struct CardboardSettings cardboardSettings; + GetCardboardSettings(&cardboardSettings); + + VirtualFramebuffer *vfb = GetVFBAt(displayFramebufPtr_); + if (!vfb) { + // Let's search for a framebuf within this range. + const u32 addr = (displayFramebufPtr_ & 0x03FFFFFF) | 0x04000000; + for (size_t i = 0; i < vfbs_.size(); ++i) { + VirtualFramebuffer *v = vfbs_[i]; + const u32 v_addr = (v->fb_address & 0x03FFFFFF) | 0x04000000; + const u32 v_size = FramebufferByteSize(v); + if (addr >= v_addr && addr < v_addr + v_size) { + const u32 dstBpp = v->format == GE_FORMAT_8888 ? 4 : 2; + const u32 v_offsetX = ((addr - v_addr) / dstBpp) % v->fb_stride; + const u32 v_offsetY = ((addr - v_addr) / dstBpp) / v->fb_stride; + // We have enough space there for the display, right? + if (v_offsetX + 480 > (u32)v->fb_stride || v->bufferHeight < v_offsetY + 272) { + continue; + } + // Check for the closest one. + if (offsetY == 0 || offsetY > v_offsetY) { + offsetX = v_offsetX; + offsetY = v_offsetY; + vfb = v; + } + } + } + + if (vfb) { + // Okay, we found one above. + INFO_LOG_REPORT_ONCE(displayoffset, HLE, "Rendering from framebuf with offset %08x -> %08x+%dx%d", addr, vfb->fb_address, offsetX, offsetY); + } + } + + if (vfb && vfb->format != displayFormat_) { + if (vfb->last_frame_render + FBO_OLD_AGE < gpuStats.numFlips) { + // The game probably switched formats on us. + vfb->format = displayFormat_; + } else { + vfb = 0; + } + } + + if (!vfb) { + if (Memory::IsValidAddress(displayFramebufPtr_)) { + // The game is displaying something directly from RAM. In GTA, it's decoded video. + + // First check that it's not a known RAM copy of a VRAM framebuffer though, as in MotoGP + for (auto iter = knownFramebufferRAMCopies_.begin(); iter != knownFramebufferRAMCopies_.end(); ++iter) { + if (iter->second == displayFramebufPtr_) { + vfb = GetVFBAt(iter->first); + } + } + + if (!vfb) { + // Just a pointer to plain memory to draw. We should create a framebuffer, then draw to it. + DrawFramebufferToOutput(Memory::GetPointer(displayFramebufPtr_), displayFormat_, displayStride_, true); + return; + } + } else { + DEBUG_LOG(SCEGE, "Found no FBO to display! displayFBPtr = %08x", displayFramebufPtr_); + // No framebuffer to display! Clear to black. + ClearBuffer(); + return; + } + } + + vfb->usageFlags |= FB_USAGE_DISPLAYED_FRAMEBUFFER; + vfb->last_frame_displayed = gpuStats.numFlips; + vfb->dirtyAfterDisplay = false; + vfb->reallyDirtyAfterDisplay = false; + + if (prevDisplayFramebuf_ != displayFramebuf_) { + prevPrevDisplayFramebuf_ = prevDisplayFramebuf_; + } + if (displayFramebuf_ != vfb) { + prevDisplayFramebuf_ = displayFramebuf_; + } + displayFramebuf_ = vfb; + + if (vfb->fbo_vk) { + DEBUG_LOG(SCEGE, "Displaying FBO %08x", vfb->fb_address); + + // We should not be in a renderpass here so can just copy. + + /* + GLuint colorTexture = fbo_get_color_texture(vfb->fbo_vk); + + int uvRotation = (g_Config.iRenderingMode != FB_NON_BUFFERED_MODE) ? g_Config.iInternalScreenRotation : ROTATION_LOCKED_HORIZONTAL; + + // Output coordinates + float x, y, w, h; + CenterDisplayOutputRect(&x, &y, &w, &h, 480.0f, 272.0f, (float)pixelWidth_, (float)pixelHeight_, uvRotation); + + // TODO ES3: Use glInvalidateFramebuffer to discard depth/stencil data at the end of frame. + + float u0 = offsetX / (float)vfb->bufferWidth; + float v0 = offsetY / (float)vfb->bufferHeight; + float u1 = (480.0f + offsetX) / (float)vfb->bufferWidth; + float v1 = (272.0f + offsetY) / (float)vfb->bufferHeight; + + if (!usePostShader_) { + // We are doing the DrawActiveTexture call directly to the backbuffer here. Hence, we must + // flip V. + std::swap(v0, v1); + if (cardboardSettings.enabled) { + // Left Eye Image + glstate.viewport.set(cardboardSettings.leftEyeXPosition, cardboardSettings.screenYPosition, cardboardSettings.screenWidth, cardboardSettings.screenHeight); + DrawActiveTexture(colorTexture, x, y, w, h, (float)pixelWidth_, (float)pixelHeight_, u0, v0, u1, v1, nullptr, ROTATION_LOCKED_HORIZONTAL); + + // Right Eye Image + glstate.viewport.set(cardboardSettings.rightEyeXPosition, cardboardSettings.screenYPosition, cardboardSettings.screenWidth, cardboardSettings.screenHeight); + DrawActiveTexture(colorTexture, x, y, w, h, (float)pixelWidth_, (float)pixelHeight_, u0, v0, u1, v1, nullptr, ROTATION_LOCKED_HORIZONTAL); + } else { + // Fullscreen Image + glstate.viewport.set(0, 0, pixelWidth_, pixelHeight_); + DrawActiveTexture(colorTexture, x, y, w, h, (float)pixelWidth_, (float)pixelHeight_, u0, v0, u1, v1, nullptr, uvRotation); + } + } else if (usePostShader_ && extraFBOs_.size() == 1 && !postShaderAtOutputResolution_) { + // An additional pass, post-processing shader to the extra FBO. + fbo_bind_as_render_target(extraFBOs_[0]); + int fbo_w, fbo_h; + fbo_get_dimensions(extraFBOs_[0], &fbo_w, &fbo_h); + glstate.viewport.set(0, 0, fbo_w, fbo_h); + shaderManager_->DirtyLastShader(); // dirty lastShader_ + glsl_bind(postShaderProgram_); + UpdatePostShaderUniforms(vfb->bufferWidth, vfb->bufferHeight, renderWidth_, renderHeight_); + DrawActiveTexture(colorTexture, 0, 0, fbo_w, fbo_h, fbo_w, fbo_h, 0.0f, 0.0f, 1.0f, 1.0f, postShaderProgram_, ROTATION_LOCKED_HORIZONTAL); + + fbo_unbind(); + + // Use the extra FBO, with applied post-processing shader, as a texture. + // fbo_bind_color_as_texture(extraFBOs_[0], 0); + if (extraFBOs_.size() == 0) { + ERROR_LOG(G3D, "WTF?"); + return; + } + colorTexture = fbo_get_color_texture(extraFBOs_[0]); + + // We are doing the DrawActiveTexture call directly to the backbuffer after here. Hence, we must + // flip V. + std::swap(v0, v1); + + if (g_Config.bEnableCardboard) { + // Left Eye Image + glstate.viewport.set(cardboardSettings.leftEyeXPosition, cardboardSettings.screenYPosition, cardboardSettings.screenWidth, cardboardSettings.screenHeight); + DrawActiveTexture(colorTexture, x, y, w, h, (float)pixelWidth_, (float)pixelHeight_, u0, v0, u1, v1, nullptr, ROTATION_LOCKED_HORIZONTAL); + + // Right Eye Image + glstate.viewport.set(cardboardSettings.rightEyeXPosition, cardboardSettings.screenYPosition, cardboardSettings.screenWidth, cardboardSettings.screenHeight); + DrawActiveTexture(colorTexture, x, y, w, h, (float)pixelWidth_, (float)pixelHeight_, u0, v0, u1, v1, nullptr, ROTATION_LOCKED_HORIZONTAL); + } else { + // Fullscreen Image + glstate.viewport.set(0, 0, pixelWidth_, pixelHeight_); + DrawActiveTexture(colorTexture, x, y, w, h, (float)pixelWidth_, (float)pixelHeight_, u0, v0, u1, v1, nullptr, uvRotation); + } + + if (gl_extensions.GLES3 && glInvalidateFramebuffer != nullptr) { + fbo_bind_as_render_target(extraFBOs_[0]); + GLenum attachments[3] = { GL_COLOR_ATTACHMENT0, GL_DEPTH_ATTACHMENT, GL_STENCIL_ATTACHMENT }; + glInvalidateFramebuffer(GL_FRAMEBUFFER, 3, attachments); + } + } else { + // We are doing the DrawActiveTexture call directly to the backbuffer here. Hence, we must + // flip V. + std::swap(v0, v1); + + shaderManager_->DirtyLastShader(); // dirty lastShader_ + glsl_bind(postShaderProgram_); + UpdatePostShaderUniforms(vfb->bufferWidth, vfb->bufferHeight, vfb->renderWidth, vfb->renderHeight); + if (g_Config.bEnableCardboard) { + // Left Eye Image + glstate.viewport.set(cardboardSettings.leftEyeXPosition, cardboardSettings.screenYPosition, cardboardSettings.screenWidth, cardboardSettings.screenHeight); + DrawActiveTexture(colorTexture, x, y, w, h, (float)pixelWidth_, (float)pixelHeight_, u0, v0, u1, v1, nullptr, ROTATION_LOCKED_HORIZONTAL); + + // Right Eye Image + glstate.viewport.set(cardboardSettings.rightEyeXPosition, cardboardSettings.screenYPosition, cardboardSettings.screenWidth, cardboardSettings.screenHeight); + DrawActiveTexture(colorTexture, x, y, w, h, (float)pixelWidth_, (float)pixelHeight_, u0, v0, u1, v1, nullptr, ROTATION_LOCKED_HORIZONTAL); + } else { + // Fullscreen Image + glstate.viewport.set(0, 0, pixelWidth_, pixelHeight_); + DrawActiveTexture(colorTexture, x, y, w, h, (float)pixelWidth_, (float)pixelHeight_, u0, v0, u1, v1, postShaderProgram_, uvRotation); + } + } + + glBindTexture(GL_TEXTURE_2D, 0); + */ + } +} + +void FramebufferManagerVulkan::ReadFramebufferToMemory(VirtualFramebuffer *vfb, bool sync, int x, int y, int w, int h) { + PROFILE_THIS_SCOPE("gpu-readback"); + if (sync) { + // flush async just in case when we go for synchronous update + // Doesn't actually pack when sent a null argument. + PackFramebufferAsync_(nullptr); + } + + if (vfb) { + // We'll pseudo-blit framebuffers here to get a resized version of vfb. + VirtualFramebuffer *nvfb = FindDownloadTempBuffer(vfb); + OptimizeDownloadRange(vfb, x, y, w, h); + BlitFramebuffer(nvfb, x, y, vfb, x, y, w, h, 0); + + // PackFramebufferSync_() - Synchronous pixel data transfer using glReadPixels + // PackFramebufferAsync_() - Asynchronous pixel data transfer using glReadPixels with PBOs + + // TODO: Can we fall back to sync without these? + if (!sync) { + PackFramebufferAsync_(nvfb); + } else { + PackFramebufferSync_(nvfb, x, y, w, h); + } + + textureCache_->ForgetLastTexture(); + RebindFramebuffer(); + } +} + +void FramebufferManagerVulkan::DownloadFramebufferForClut(u32 fb_address, u32 loadBytes) { + PROFILE_THIS_SCOPE("gpu-readback"); + // Flush async just in case. + PackFramebufferAsync_(nullptr); + + VirtualFramebuffer *vfb = GetVFBAt(fb_address); + if (vfb && vfb->fb_stride != 0) { + const u32 bpp = vfb->drawnFormat == GE_FORMAT_8888 ? 4 : 2; + int x = 0; + int y = 0; + int pixels = loadBytes / bpp; + // The height will be 1 for each stride or part thereof. + int w = std::min(pixels % vfb->fb_stride, (int)vfb->width); + int h = std::min((pixels + vfb->fb_stride - 1) / vfb->fb_stride, (int)vfb->height); + + // No need to download if we already have it. + if (!vfb->memoryUpdated && vfb->clutUpdatedBytes < loadBytes) { + // We intentionally don't call OptimizeDownloadRange() here - we don't want to over download. + // CLUT framebuffers are often incorrectly estimated in size. + if (x == 0 && y == 0 && w == vfb->width && h == vfb->height) { + vfb->memoryUpdated = true; + } + vfb->clutUpdatedBytes = loadBytes; + + // We'll pseudo-blit framebuffers here to get a resized version of vfb. + VirtualFramebuffer *nvfb = FindDownloadTempBuffer(vfb); + BlitFramebuffer(nvfb, x, y, vfb, x, y, w, h, 0); + + PackFramebufferSync_(nvfb, x, y, w, h); + + textureCache_->ForgetLastTexture(); + RebindFramebuffer(); + } + } +} + +bool FramebufferManagerVulkan::CreateDownloadTempBuffer(VirtualFramebuffer *nvfb) { + // When updating VRAM, it need to be exact format. + if (!gstate_c.Supports(GPU_PREFER_CPU_DOWNLOAD)) { + switch (nvfb->format) { + case GE_FORMAT_4444: + nvfb->colorDepth = VK_FBO_4444; + break; + case GE_FORMAT_5551: + nvfb->colorDepth = VK_FBO_5551; + break; + case GE_FORMAT_565: + nvfb->colorDepth = VK_FBO_565; + break; + case GE_FORMAT_8888: + default: + nvfb->colorDepth = VK_FBO_8888; + break; + } + } + + /* + nvfb->fbo = fbo_create(nvfb->width, nvfb->height, 1, false, (FBOColorDepth)nvfb->colorDepth); + if (!(nvfb->fbo)) { + ERROR_LOG(SCEGE, "Error creating FBO! %i x %i", nvfb->renderWidth, nvfb->renderHeight); + return false; + } + + fbo_bind_as_render_target(nvfb->fbo); + ClearBuffer(); + glDisable(GL_DITHER); + */ + return true; +} + +void FramebufferManagerVulkan::UpdateDownloadTempBuffer(VirtualFramebuffer *nvfb) { + _assert_msg_(G3D, nvfb->fbo, "Expecting a valid nvfb in UpdateDownloadTempBuffer"); + + // Discard the previous contents of this buffer where possible. + /* + if (gl_extensions.GLES3 && glInvalidateFramebuffer != nullptr) { + fbo_bind_as_render_target(nvfb->fbo); + GLenum attachments[3] = { GL_COLOR_ATTACHMENT0, GL_STENCIL_ATTACHMENT, GL_DEPTH_ATTACHMENT }; + glInvalidateFramebuffer(GL_FRAMEBUFFER, 3, attachments); + } else if (gl_extensions.IsGLES) { + fbo_bind_as_render_target(nvfb->fbo); + ClearBuffer(); + } + */ +} + +void FramebufferManagerVulkan::BlitFramebuffer(VirtualFramebuffer *dst, int dstX, int dstY, VirtualFramebuffer *src, int srcX, int srcY, int w, int h, int bpp) { + /* + if (!dst->fbo || !src->fbo || !useBufferedRendering_) { + // This can happen if they recently switched from non-buffered. + fbo_unbind(); + return; + } + + bool useBlit = gstate_c.Supports(GPU_SUPPORTS_ARB_FRAMEBUFFER_BLIT | GPU_SUPPORTS_NV_FRAMEBUFFER_BLIT); + bool useNV = useBlit && !gstate_c.Supports(GPU_SUPPORTS_ARB_FRAMEBUFFER_BLIT); + + float srcXFactor = useBlit ? (float)src->renderWidth / (float)src->bufferWidth : 1.0f; + float srcYFactor = useBlit ? (float)src->renderHeight / (float)src->bufferHeight : 1.0f; + const int srcBpp = src->format == GE_FORMAT_8888 ? 4 : 2; + if (srcBpp != bpp && bpp != 0) { + srcXFactor = (srcXFactor * bpp) / srcBpp; + } + int srcX1 = srcX * srcXFactor; + int srcX2 = (srcX + w) * srcXFactor; + int srcY1 = srcY * srcYFactor; + int srcY2 = (srcY + h) * srcYFactor; + + float dstXFactor = useBlit ? (float)dst->renderWidth / (float)dst->bufferWidth : 1.0f; + float dstYFactor = useBlit ? (float)dst->renderHeight / (float)dst->bufferHeight : 1.0f; + const int dstBpp = dst->format == GE_FORMAT_8888 ? 4 : 2; + if (dstBpp != bpp && bpp != 0) { + dstXFactor = (dstXFactor * bpp) / dstBpp; + } + int dstX1 = dstX * dstXFactor; + int dstX2 = (dstX + w) * dstXFactor; + int dstY1 = dstY * dstYFactor; + int dstY2 = (dstY + h) * dstYFactor; + + if (src == dst && srcX == dstX && srcY == dstY) { + // Let's just skip a copy where the destination is equal to the source. + WARN_LOG_REPORT_ONCE(blitSame, G3D, "Skipped blit with equal dst and src"); + return; + } + + if (gstate_c.Supports(GPU_SUPPORTS_ANY_COPY_IMAGE)) { + // glBlitFramebuffer can clip, but glCopyImageSubData is more restricted. + // In case the src goes outside, we just skip the optimization in that case. + const bool sameSize = dstX2 - dstX1 == srcX2 - srcX1 && dstY2 - dstY1 == srcY2 - srcY1; + const bool sameDepth = dst->colorDepth == src->colorDepth; + const bool srcInsideBounds = srcX2 <= src->renderWidth && srcY2 <= src->renderHeight; + const bool dstInsideBounds = dstX2 <= dst->renderWidth && dstY2 <= dst->renderHeight; + const bool xOverlap = src == dst && srcX2 > dstX1 && srcX1 < dstX2; + const bool yOverlap = src == dst && srcY2 > dstY1 && srcY1 < dstY2; + if (sameSize && sameDepth && srcInsideBounds && dstInsideBounds && !(xOverlap && yOverlap)) { +#if defined(USING_GLES2) +#ifndef IOS + glCopyImageSubDataOES( + fbo_get_color_texture(src->fbo), GL_TEXTURE_2D, 0, srcX1, srcY1, 0, + fbo_get_color_texture(dst->fbo), GL_TEXTURE_2D, 0, dstX1, dstY1, 0, + dstX2 - dstX1, dstY2 - dstY1, 1); + return; +#endif +#else + if (gl_extensions.ARB_copy_image) { + glCopyImageSubData( + fbo_get_color_texture(src->fbo), GL_TEXTURE_2D, 0, srcX1, srcY1, 0, + fbo_get_color_texture(dst->fbo), GL_TEXTURE_2D, 0, dstX1, dstY1, 0, + dstX2 - dstX1, dstY2 - dstY1, 1); + return; + } else if (gl_extensions.NV_copy_image) { + // Older, pre GL 4.x NVIDIA cards. + glCopyImageSubDataNV( + fbo_get_color_texture(src->fbo), GL_TEXTURE_2D, 0, srcX1, srcY1, 0, + fbo_get_color_texture(dst->fbo), GL_TEXTURE_2D, 0, dstX1, dstY1, 0, + dstX2 - dstX1, dstY2 - dstY1, 1); + return; + } +#endif + } + } + + fbo_bind_as_render_target(dst->fbo); + glstate.scissorTest.force(false); + + if (useBlit) { + fbo_bind_for_read(src->fbo); + if (!useNV) { + glBlitFramebuffer(srcX1, srcY1, srcX2, srcY2, dstX1, dstY1, dstX2, dstY2, GL_COLOR_BUFFER_BIT, GL_NEAREST); + } else { +#if defined(USING_GLES2) && defined(ANDROID) // We only support this extension on Android, it's not even available on PC. + glBlitFramebufferNV(srcX1, srcY1, srcX2, srcY2, dstX1, dstY1, dstX2, dstY2, GL_COLOR_BUFFER_BIT, GL_NEAREST); +#endif // defined(USING_GLES2) && defined(ANDROID) + } + + fbo_unbind_read(); + } else { + fbo_bind_color_as_texture(src->fbo, 0); + + // Make sure our 2D drawing program is ready. Compiles only if not already compiled. + CompileDraw2DProgram(); + + glstate.viewport.force(0, 0, dst->renderWidth, dst->renderHeight); + glstate.blend.force(false); + glstate.cullFace.force(false); + glstate.depthTest.force(false); + glstate.stencilTest.force(false); +#if !defined(USING_GLES2) + glstate.colorLogicOp.force(false); +#endif + glstate.colorMask.force(true, true, true, true); + glstate.stencilMask.force(0xFF); + + // The first four coordinates are relative to the 6th and 7th arguments of DrawActiveTexture. + // Should maybe revamp that interface. + float srcW = src->bufferWidth; + float srcH = src->bufferHeight; + DrawActiveTexture(0, dstX1, dstY1, w * dstXFactor, h, dst->bufferWidth, dst->bufferHeight, srcX1 / srcW, srcY1 / srcH, srcX2 / srcW, srcY2 / srcH, draw2dprogram_, ROTATION_LOCKED_HORIZONTAL); + glBindTexture(GL_TEXTURE_2D, 0); + textureCache_->ForgetLastTexture(); + glstate.viewport.restore(); + glstate.blend.restore(); + glstate.cullFace.restore(); + glstate.depthTest.restore(); + glstate.stencilTest.restore(); +#if !defined(USING_GLES2) + glstate.colorLogicOp.restore(); +#endif + glstate.colorMask.restore(); + glstate.stencilMask.restore(); + } + + glstate.scissorTest.restore(); + */ +} + +// TODO: SSE/NEON +// Could also make C fake-simd for 64-bit, two 8888 pixels fit in a register :) +void ConvertFromRGBA8888_Vulkan(u8 *dst, const u8 *src, u32 dstStride, u32 srcStride, u32 width, u32 height, GEBufferFormat format) { + // Must skip stride in the cases below. Some games pack data into the cracks, like MotoGP. + const u32 *src32 = (const u32 *)src; + + if (format == GE_FORMAT_8888) { + u32 *dst32 = (u32 *)dst; + if (src == dst) { + return; + } else { + // Here let's assume they don't intersect + for (u32 y = 0; y < height; ++y) { + memcpy(dst32, src32, width * 4); + src32 += srcStride; + dst32 += dstStride; + } + } + } else { + // But here it shouldn't matter if they do intersect + u16 *dst16 = (u16 *)dst; + switch (format) { + case GE_FORMAT_565: // BGR 565 + for (u32 y = 0; y < height; ++y) { + ConvertRGBA8888ToRGB565(dst16, src32, width); + src32 += srcStride; + dst16 += dstStride; + } + break; + case GE_FORMAT_5551: // ABGR 1555 + for (u32 y = 0; y < height; ++y) { + ConvertBGRA8888ToRGBA5551(dst16, src32, width); + src32 += srcStride; + dst16 += dstStride; + } + break; + case GE_FORMAT_4444: // ABGR 4444 + for (u32 y = 0; y < height; ++y) { + ConvertRGBA8888ToRGBA4444(dst16, src32, width); + src32 += srcStride; + dst16 += dstStride; + } + break; + case GE_FORMAT_8888: + case GE_FORMAT_INVALID: + // Not possible. + break; + } + } +} + +#ifdef DEBUG_READ_PIXELS +// TODO: Make more generic. +static void LogReadPixelsError(GLenum error) { + switch (error) { + case GL_NO_ERROR: + break; + case GL_INVALID_ENUM: + ERROR_LOG(SCEGE, "glReadPixels: GL_INVALID_ENUM"); + break; + case GL_INVALID_VALUE: + ERROR_LOG(SCEGE, "glReadPixels: GL_INVALID_VALUE"); + break; + case GL_INVALID_OPERATION: + ERROR_LOG(SCEGE, "glReadPixels: GL_INVALID_OPERATION"); + break; + case GL_INVALID_FRAMEBUFFER_OPERATION: + ERROR_LOG(SCEGE, "glReadPixels: GL_INVALID_FRAMEBUFFER_OPERATION"); + break; + case GL_OUT_OF_MEMORY: + ERROR_LOG(SCEGE, "glReadPixels: GL_OUT_OF_MEMORY"); + break; +#ifndef USING_GLES2 + case GL_STACK_UNDERFLOW: + ERROR_LOG(SCEGE, "glReadPixels: GL_STACK_UNDERFLOW"); + break; + case GL_STACK_OVERFLOW: + ERROR_LOG(SCEGE, "glReadPixels: GL_STACK_OVERFLOW"); + break; +#endif + default: + ERROR_LOG(SCEGE, "glReadPixels: %08x", error); + break; + } +} +#endif + +void FramebufferManagerVulkan::PackFramebufferAsync_(VirtualFramebuffer *vfb) { + /* + const int MAX_PBO = 2; + GLubyte *packed = 0; + bool unbind = false; + const u8 nextPBO = (currentPBO_ + 1) % MAX_PBO; + const bool useCPU = gstate_c.Supports(GPU_PREFER_CPU_DOWNLOAD); + + // We'll prepare two PBOs to switch between readying and reading + if (!pixelBufObj_) { + if (!vfb) { + // This call is just to flush the buffers. We don't have any yet, + // so there's nothing to do. + return; + } + + GLuint pbos[MAX_PBO]; + glGenBuffers(MAX_PBO, pbos); + + pixelBufObj_ = new AsyncPBO[MAX_PBO]; + for (int i = 0; i < MAX_PBO; i++) { + pixelBufObj_[i].handle = pbos[i]; + pixelBufObj_[i].maxSize = 0; + pixelBufObj_[i].reading = false; + } + } + + // Receive previously requested data from a PBO + AsyncPBO &pbo = pixelBufObj_[nextPBO]; + if (pbo.reading) { + glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo.handle); +#ifdef USING_GLES2 + // Not on desktop GL 2.x... + packed = (GLubyte *)glMapBufferRange(GL_PIXEL_PACK_BUFFER, 0, pbo.size, GL_MAP_READ_BIT); +#else + packed = (GLubyte *)glMapBuffer(GL_PIXEL_PACK_BUFFER, GL_READ_ONLY); +#endif + + if (packed) { + DEBUG_LOG(SCEGE, "Reading PBO to memory , bufSize = %u, packed = %p, fb_address = %08x, stride = %u, pbo = %u", + pbo.size, packed, pbo.fb_address, pbo.stride, nextPBO); + + if (useCPU || (UseBGRA8888() && pbo.format == GE_FORMAT_8888)) { + u8 *dst = Memory::GetPointer(pbo.fb_address); + ConvertFromRGBA8888(dst, packed, pbo.stride, pbo.stride, pbo.stride, pbo.height, pbo.format); + } else { + // We don't need to convert, GPU already did (or should have) + Memory::MemcpyUnchecked(pbo.fb_address, packed, pbo.size); + } + + pbo.reading = false; + } + + glUnmapBuffer(GL_PIXEL_PACK_BUFFER); + unbind = true; + } + + // Order packing/readback of the framebuffer + if (vfb) { + int pixelType, pixelSize, pixelFormat, align; + + bool reverseOrder = gstate_c.Supports(GPU_PREFER_REVERSE_COLOR_ORDER); + switch (vfb->format) { + // GL_UNSIGNED_INT_8_8_8_8 returns A B G R (little-endian, tested in Nvidia card/x86 PC) + // GL_UNSIGNED_BYTE returns R G B A in consecutive bytes ("big-endian"/not treated as 32-bit value) + // We want R G B A, so we use *_REV for 16-bit formats and GL_UNSIGNED_BYTE for 32-bit + case GE_FORMAT_4444: // 16 bit RGBA +#ifdef USING_GLES2 + pixelType = GL_UNSIGNED_SHORT_4_4_4_4; +#else + pixelType = (reverseOrder ? GL_UNSIGNED_SHORT_4_4_4_4_REV : GL_UNSIGNED_SHORT_4_4_4_4); +#endif + pixelFormat = GL_RGBA; + pixelSize = 2; + align = 2; + break; + case GE_FORMAT_5551: // 16 bit RGBA +#ifdef USING_GLES2 + pixelType = GL_UNSIGNED_SHORT_5_5_5_1; +#else + pixelType = (reverseOrder ? GL_UNSIGNED_SHORT_1_5_5_5_REV : GL_UNSIGNED_SHORT_5_5_5_1); +#endif + pixelFormat = GL_RGBA; + pixelSize = 2; + align = 2; + break; + case GE_FORMAT_565: // 16 bit RGB +#ifdef USING_GLES2 + pixelType = GL_UNSIGNED_SHORT_5_6_5; +#else + pixelType = (reverseOrder ? GL_UNSIGNED_SHORT_5_6_5_REV : GL_UNSIGNED_SHORT_5_6_5); +#endif + pixelFormat = GL_RGB; + pixelSize = 2; + align = 2; + break; + case GE_FORMAT_8888: // 32 bit RGBA + default: + pixelType = GL_UNSIGNED_BYTE; + pixelFormat = UseBGRA8888() ? GL_BGRA_EXT : GL_RGBA; + pixelSize = 4; + align = 4; + break; + } + + // If using the CPU, we need 4 bytes per pixel always. + u32 bufSize = vfb->fb_stride * vfb->height * (useCPU ? 4 : pixelSize); + u32 fb_address = (0x04000000) | vfb->fb_address; + + if (vfb->fbo) { + fbo_bind_for_read(vfb->fbo); + } else { + ERROR_LOG_REPORT_ONCE(vfbfbozero, SCEGE, "PackFramebufferAsync_: vfb->fbo == 0"); + fbo_unbind_read(); + return; + } + + GLenum fbStatus; + fbStatus = (GLenum)fbo_check_framebuffer_status(vfb->fbo); + + if (fbStatus != GL_FRAMEBUFFER_COMPLETE) { + ERROR_LOG(SCEGE, "Incomplete source framebuffer, aborting read"); + fbo_unbind_read(); + return; + } + + glBindBuffer(GL_PIXEL_PACK_BUFFER, pixelBufObj_[currentPBO_].handle); + + if (pixelBufObj_[currentPBO_].maxSize < bufSize) { + // We reserve a buffer big enough to fit all those pixels + glBufferData(GL_PIXEL_PACK_BUFFER, bufSize, NULL, GL_DYNAMIC_READ); + pixelBufObj_[currentPBO_].maxSize = bufSize; + } + + if (useCPU) { + // If converting pixel formats on the CPU we'll always request RGBA8888 + glPixelStorei(GL_PACK_ALIGNMENT, 4); + SafeGLReadPixels(0, 0, vfb->fb_stride, vfb->height, UseBGRA8888() ? GL_BGRA_EXT : GL_RGBA, GL_UNSIGNED_BYTE, 0); + } else { + // Otherwise we'll directly request the format we need and let the GPU sort it out + glPixelStorei(GL_PACK_ALIGNMENT, align); + SafeGLReadPixels(0, 0, vfb->fb_stride, vfb->height, pixelFormat, pixelType, 0); + } + + fbo_unbind_read(); + unbind = true; + + pixelBufObj_[currentPBO_].fb_address = fb_address; + pixelBufObj_[currentPBO_].size = bufSize; + pixelBufObj_[currentPBO_].stride = vfb->fb_stride; + pixelBufObj_[currentPBO_].height = vfb->height; + pixelBufObj_[currentPBO_].format = vfb->format; + pixelBufObj_[currentPBO_].reading = true; + } + + currentPBO_ = nextPBO; + + if (unbind) { + glBindBuffer(GL_PIXEL_PACK_BUFFER, 0); + } + */ +} + +void FramebufferManagerVulkan::PackFramebufferSync_(VirtualFramebuffer *vfb, int x, int y, int w, int h) { + /* + if (vfb->fbo) { + fbo_bind_for_read(vfb->fbo); + } else { + ERROR_LOG_REPORT_ONCE(vfbfbozero, SCEGE, "PackFramebufferSync_: vfb->fbo == 0"); + fbo_unbind_read(); + return; + } + + // Pixel size always 4 here because we always request RGBA8888 + size_t bufSize = vfb->fb_stride * std::max(vfb->height, (u16)h) * 4; + u32 fb_address = (0x04000000) | vfb->fb_address; + + GLubyte *packed = 0; + + bool convert = vfb->format != GE_FORMAT_8888 || UseBGRA8888(); + const int dstBpp = vfb->format == GE_FORMAT_8888 ? 4 : 2; + const int packWidth = x + w < vfb->width ? x + w : vfb->width; + + if (!convert) { + packed = (GLubyte *)Memory::GetPointer(fb_address); + } else { // End result may be 16-bit but we are reading 32-bit, so there may not be enough space at fb_address + u32 neededSize = (u32)bufSize * sizeof(GLubyte); + if (!convBuf_ || convBufSize_ < neededSize) { + delete[] convBuf_; + convBuf_ = new u8[neededSize]; + convBufSize_ = neededSize; + } + packed = convBuf_; + } + + if (packed) { + DEBUG_LOG(SCEGE, "Reading framebuffer to mem, bufSize = %u, packed = %p, fb_address = %08x", + (u32)bufSize, packed, fb_address); + + glPixelStorei(GL_PACK_ALIGNMENT, 4); + GLenum glfmt = GL_RGBA; + if (UseBGRA8888()) { + glfmt = GL_BGRA_EXT; + } + + int byteOffset = y * vfb->fb_stride * 4; + SafeGLReadPixels(0, y, h == 1 ? packWidth : vfb->fb_stride, h, glfmt, GL_UNSIGNED_BYTE, packed + byteOffset); + + if (convert) { + int dstByteOffset = y * vfb->fb_stride * dstBpp; + ConvertFromRGBA8888(Memory::GetPointer(fb_address + dstByteOffset), packed + byteOffset, vfb->fb_stride, vfb->fb_stride, packWidth, h, vfb->format); + } + } + + if (gl_extensions.GLES3 && glInvalidateFramebuffer != nullptr) { +#ifdef USING_GLES2 + // GLES3 doesn't support using GL_READ_FRAMEBUFFER here. + fbo_bind_as_render_target(vfb->fbo); + const GLenum target = GL_FRAMEBUFFER; +#else + const GLenum target = GL_READ_FRAMEBUFFER; +#endif + GLenum attachments[3] = { GL_COLOR_ATTACHMENT0, GL_DEPTH_ATTACHMENT, GL_STENCIL_ATTACHMENT }; + glInvalidateFramebuffer(target, 3, attachments); + } + + fbo_unbind_read(); + */ +} + +#ifdef _WIN32 +void ShowScreenResolution(); +#endif + +void FramebufferManagerVulkan::EndFrame() { + if (resized_) { + // TODO: Only do this if the new size actually changed the renderwidth/height. + DestroyAllFBOs(); + + // Probably not necessary + //glstate.viewport.set(0, 0, PSP_CoreParameter().pixelWidth, PSP_CoreParameter().pixelHeight); + + // Check if postprocessing shader is doing upscaling as it requires native resolution + const ShaderInfo *shaderInfo = 0; + if (g_Config.sPostShaderName != "Off") { + shaderInfo = GetPostShaderInfo(g_Config.sPostShaderName); + } + + postShaderIsUpscalingFilter_ = shaderInfo ? shaderInfo->isUpscalingFilter : false; + + // Actually, auto mode should be more granular... + // Round up to a zoom factor for the render size. + int zoom = g_Config.iInternalResolution; + if (zoom == 0) { // auto mode + // Use the longest dimension + if (!g_Config.IsPortrait()) { + zoom = (PSP_CoreParameter().pixelWidth + 479) / 480; + } else { + zoom = (PSP_CoreParameter().pixelHeight + 479) / 480; + } + } + if (zoom <= 1 || postShaderIsUpscalingFilter_) + zoom = 1; + + if (g_Config.IsPortrait()) { + PSP_CoreParameter().renderWidth = 272 * zoom; + PSP_CoreParameter().renderHeight = 480 * zoom; + } else { + PSP_CoreParameter().renderWidth = 480 * zoom; + PSP_CoreParameter().renderHeight = 272 * zoom; + } + + UpdateSize(); + + resized_ = false; +#ifdef _WIN32 + // Seems related - if you're ok with numbers all the time, show some more :) + if (g_Config.iShowFPSCounter != 0) { + ShowScreenResolution(); + } +#endif + ClearBuffer(); + DestroyDraw2DProgram(); + } + + // We flush to memory last requested framebuffer, if any. + // Only do this in the read-framebuffer modes. + if (updateVRAM_) + PackFramebufferAsync_(nullptr); +} + +void FramebufferManagerVulkan::DeviceLost() { + DestroyAllFBOs(); + DestroyDraw2DProgram(); + resized_ = false; +} + +std::vector FramebufferManagerVulkan::GetFramebufferList() { + std::vector list; + + for (size_t i = 0; i < vfbs_.size(); ++i) { + VirtualFramebuffer *vfb = vfbs_[i]; + + FramebufferInfo info; + info.fb_address = vfb->fb_address; + info.z_address = vfb->z_address; + info.format = vfb->format; + info.width = vfb->width; + info.height = vfb->height; + info.fbo = vfb->fbo; + list.push_back(info); + } + + return list; +} + +void FramebufferManagerVulkan::DecimateFBOs() { + currentRenderVfb_ = 0; + + for (size_t i = 0; i < vfbs_.size(); ++i) { + VirtualFramebuffer *vfb = vfbs_[i]; + int age = frameLastFramebufUsed_ - std::max(vfb->last_frame_render, vfb->last_frame_used); + + if (ShouldDownloadFramebuffer(vfb) && age == 0 && !vfb->memoryUpdated) { + bool sync = true; + ReadFramebufferToMemory(vfb, sync, 0, 0, vfb->width, vfb->height); + } + + // Let's also "decimate" the usageFlags. + UpdateFramebufUsage(vfb); + + if (vfb != displayFramebuf_ && vfb != prevDisplayFramebuf_ && vfb != prevPrevDisplayFramebuf_) { + if (age > FBO_OLD_AGE) { + INFO_LOG(SCEGE, "Decimating FBO for %08x (%i x %i x %i), age %i", vfb->fb_address, vfb->width, vfb->height, vfb->format, age); + DestroyFramebuf(vfb); + vfbs_.erase(vfbs_.begin() + i--); + } + } + } + + for (auto it = tempFBOs_.begin(); it != tempFBOs_.end(); ) { + int age = frameLastFramebufUsed_ - it->second.last_frame_used; + if (age > FBO_OLD_AGE) { + delete it->second.fbo_vk; + tempFBOs_.erase(it++); + } else { + ++it; + } + } + + // Do the same for ReadFramebuffersToMemory's VFBs + for (size_t i = 0; i < bvfbs_.size(); ++i) { + VirtualFramebuffer *vfb = bvfbs_[i]; + int age = frameLastFramebufUsed_ - vfb->last_frame_render; + if (age > FBO_OLD_AGE) { + INFO_LOG(SCEGE, "Decimating FBO for %08x (%i x %i x %i), age %i", vfb->fb_address, vfb->width, vfb->height, vfb->format, age); + DestroyFramebuf(vfb); + bvfbs_.erase(bvfbs_.begin() + i--); + } + } +} + +void FramebufferManagerVulkan::DestroyAllFBOs() { + currentRenderVfb_ = 0; + displayFramebuf_ = 0; + prevDisplayFramebuf_ = 0; + prevPrevDisplayFramebuf_ = 0; + + for (size_t i = 0; i < vfbs_.size(); ++i) { + VirtualFramebuffer *vfb = vfbs_[i]; + INFO_LOG(SCEGE, "Destroying FBO for %08x : %i x %i x %i", vfb->fb_address, vfb->width, vfb->height, vfb->format); + DestroyFramebuf(vfb); + } + vfbs_.clear(); + + for (size_t i = 0; i < bvfbs_.size(); ++i) { + VirtualFramebuffer *vfb = bvfbs_[i]; + DestroyFramebuf(vfb); + } + bvfbs_.clear(); + + for (auto it = tempFBOs_.begin(), end = tempFBOs_.end(); it != end; ++it) { + delete it->second.fbo_vk; + } + tempFBOs_.clear(); +} void FramebufferManagerVulkan::FlushBeforeCopy() { // Flush anything not yet drawn before blitting, downloading, or uploading. @@ -66,26 +1838,108 @@ void FramebufferManagerVulkan::FlushBeforeCopy() { // all the irrelevant state checking it'll use to decide what to do. Should // do something more focused here. SetRenderFrameBuffer(gstate_c.framebufChanged, gstate_c.skipDrawReason); - drawEngine_->Flush(nullptr); + transformDraw_->Flush(curCmd_); } -void FramebufferManagerVulkan::ReadFramebufferToMemory(VirtualFramebuffer *vfb, bool sync, int x, int y, int w, int h) { - +void FramebufferManagerVulkan::Resized() { + resized_ = true; } -void FramebufferManagerVulkan::DownloadFramebufferForClut(u32 fb_address, u32 loadBytes) { +bool FramebufferManagerVulkan::GetFramebuffer(u32 fb_address, int fb_stride, GEBufferFormat format, GPUDebugBuffer &buffer) { + // TODO: Doing this synchronously will require stalling the pipeline. Maybe better + // to do it callback-style? +/* + VirtualFramebuffer *vfb = currentRenderVfb_; + if (!vfb) { + vfb = GetVFBAt(fb_address); + } -} + if (!vfb) { + // If there's no vfb and we're drawing there, must be memory? + buffer = GPUDebugBuffer(Memory::GetPointer(fb_address | 0x04000000), fb_stride, 512, format); + return true; + } -bool FramebufferManagerVulkan::CreateDownloadTempBuffer(VirtualFramebuffer *nvfb) { + buffer.Allocate(vfb->renderWidth, vfb->renderHeight, GE_FORMAT_8888, false, true); + if (vfb->fbo_vk) + fbo_bind_for_read(vfb->fbo_vk); + if (gl_extensions.GLES3 || !gl_extensions.IsGLES) + glReadBuffer(GL_COLOR_ATTACHMENT0); + + glPixelStorei(GL_PACK_ALIGNMENT, 4); + SafeGLReadPixels(0, 0, vfb->renderWidth, vfb->renderHeight, GL_RGBA, GL_UNSIGNED_BYTE, buffer.GetData()); + */ return false; } -void FramebufferManagerVulkan::UpdateDownloadTempBuffer(VirtualFramebuffer *nvfb) { +bool FramebufferManagerVulkan::GetDisplayFramebuffer(GPUDebugBuffer &buffer) { + // TODO: Doing this synchronously will require stalling the pipeline. Maybe better + // to do it callback-style? + /* + fbo_unbind_read(); + int pw = PSP_CoreParameter().pixelWidth; + int ph = PSP_CoreParameter().pixelHeight; + + // The backbuffer is flipped. + buffer.Allocate(pw, ph, GPU_DBG_FORMAT_888_RGB, true); + glPixelStorei(GL_PACK_ALIGNMENT, 1); + SafeGLReadPixels(0, 0, pw, ph, GL_RGB, GL_UNSIGNED_BYTE, buffer.GetData()); + */ + return false; } +bool FramebufferManagerVulkan::GetDepthbuffer(u32 fb_address, int fb_stride, u32 z_address, int z_stride, GPUDebugBuffer &buffer) { + // TODO: Doing this synchronously will require stalling the pipeline. Maybe better + // to do it callback-style? + /* + VirtualFramebuffer *vfb = currentRenderVfb_; + if (!vfb) { + vfb = GetVFBAt(fb_address); + } -std::vector FramebufferManagerVulkan::GetFramebufferList() { - return std::vector(); + if (!vfb) { + // If there's no vfb and we're drawing there, must be memory? + buffer = GPUDebugBuffer(Memory::GetPointer(z_address | 0x04000000), z_stride, 512, GPU_DBG_FORMAT_16BIT); + return true; + } + + buffer.Allocate(vfb->renderWidth, vfb->renderHeight, GPU_DBG_FORMAT_FLOAT, false); + if (vfb->fbo_vk) + fbo_bind_for_read(vfb->fbo_vk); + if (gl_extensions.GLES3 || !gl_extensions.IsGLES) + glReadBuffer(GL_COLOR_ATTACHMENT0); + glPixelStorei(GL_PACK_ALIGNMENT, 4); + SafeGLReadPixels(0, 0, vfb->renderWidth, vfb->renderHeight, GL_DEPTH_COMPONENT, GL_FLOAT, buffer.GetData()); + */ + return false; +} + +bool FramebufferManagerVulkan::GetStencilbuffer(u32 fb_address, int fb_stride, GPUDebugBuffer &buffer) { + // TODO: Doing this synchronously will require stalling the pipeline. Maybe better + // to do it callback-style? + /* + VirtualFramebuffer *vfb = currentRenderVfb_; + if (!vfb) { + vfb = GetVFBAt(fb_address); + } + + if (!vfb) { + // If there's no vfb and we're drawing there, must be memory? + // TODO: Actually get the stencil. + buffer = GPUDebugBuffer(Memory::GetPointer(fb_address | 0x04000000), fb_stride, 512, GPU_DBG_FORMAT_8888); + return true; + } + + buffer.Allocate(vfb->renderWidth, vfb->renderHeight, GPU_DBG_FORMAT_8BIT, false); + if (vfb->fbo_vk) + fbo_bind_for_read(vfb->fbo_vk); + if (gl_extensions.GLES3 || !gl_extensions.IsGLES) + glReadBuffer(GL_COLOR_ATTACHMENT0); + glPixelStorei(GL_PACK_ALIGNMENT, 2); + SafeGLReadPixels(0, 0, vfb->renderWidth, vfb->renderHeight, GL_STENCIL_INDEX, GL_UNSIGNED_BYTE, buffer.GetData()); + + return true; + */ + return false; } diff --git a/GPU/Vulkan/FramebufferVulkan.h b/GPU/Vulkan/FramebufferVulkan.h index 075e2c435c..2bd75f9cc7 100644 --- a/GPU/Vulkan/FramebufferVulkan.h +++ b/GPU/Vulkan/FramebufferVulkan.h @@ -17,8 +17,10 @@ #pragma once +#include "GPU/Vulkan/VulkanUtil.h" #include "GPU/Common/FramebufferCommon.h" #include "GPU/GPUInterface.h" +#include "GPU/Common/GPUDebugInterface.h" #include "GPU/Vulkan/VulkanUtil.h" // TODO: WTF? @@ -32,83 +34,164 @@ enum VulkanFBOColorDepth { class TextureCacheVulkan; class DrawEngineVulkan; class VulkanContext; +class ShaderManagerVulkan; +class VulkanTexture; +class VulkanFramebuffer; + +struct PostShaderUniforms { + float texelDelta[2]; float pad[2]; + float pixelDelta[2]; float pad0[2]; + float time[4]; +}; +// Simple struct for asynchronous PBO readbacks +// TODO: Probably will need a complete redesign. +struct AsyncPBOVulkan { + // handle; + u32 maxSize; + + u32 fb_address; + u32 stride; + u32 height; + u32 size; + GEBufferFormat format; + bool reading; +}; + +struct CardboardSettings { + bool enabled; + float leftEyeXPosition; + float rightEyeXPosition; + float screenYPosition; + float screenWidth; + float screenHeight; +}; class FramebufferManagerVulkan : public FramebufferManagerCommon { public: - FramebufferManagerVulkan(VulkanContext *vulkan) : vulkan_(vulkan) {} - // Subsequent commands will be enqueued on this buffer. - void SetCmdBuffer(VkCommandBuffer cmd) { cmd_ = cmd; } - - virtual void ClearBuffer(bool keepState = false) override { - throw std::logic_error("The method or operation is not implemented."); + FramebufferManagerVulkan(VulkanContext *vulkan); + ~FramebufferManagerVulkan(); + + void SetTextureCache(TextureCacheVulkan *tc) { + textureCache_ = tc; } - void SetTextureCache(TextureCacheVulkan *texCache) { texCache_ = texCache; } - void SetDrawEngine(DrawEngineVulkan *drawEngine) { drawEngine_ = drawEngine; } - VulkanFramebuffer *GetTempFBO(int width, int height, VulkanFBOColorDepth colorDepth); - - void RebindFramebuffer() override { } // This makes little sense with Vulkan's model. - - bool NotifyStencilUpload(u32 addr, int size, bool skipZero = false) override { - return false; + void SetShaderManager(ShaderManagerVulkan *sm) { + shaderManager_ = sm; + } + void SetDrawEngine(DrawEngineVulkan *td) { + transformDraw_ = td; } + void MakePixelTexture(const u8 *srcPixels, GEBufferFormat srcPixelFormat, int srcStride, int width, int height) override; + void DrawPixels(VirtualFramebuffer *vfb, int dstX, int dstY, const u8 *srcPixels, GEBufferFormat srcPixelFormat, int srcStride, int width, int height) override; + void DrawFramebufferToOutput(const u8 *srcPixels, GEBufferFormat srcPixelFormat, int srcStride, bool applyPostShader) override; + + // If texture != 0, will bind it. + // x,y,w,h are relative to destW, destH which fill out the target completely. + void DrawActiveTexture(VulkanTexture *texture, float x, float y, float w, float h, float destW, float destH, float u0, float v0, float u1, float v1, VkPipeline pipeline, int uvRotation); + + void DestroyAllFBOs(); + + virtual void Init() override; + void EndFrame(); + void Resized(); + void DeviceLost(); + void CopyDisplayToOutput(); + int GetLineWidth(); + void ReformatFramebufferFrom(VirtualFramebuffer *vfb, GEBufferFormat old); + + void BlitFramebufferDepth(VirtualFramebuffer *src, VirtualFramebuffer *dst); + + // For use when texturing from a framebuffer. May create a duplicate if target. + void BindFramebufferColor(int stage, u32 fbRawAddress, VirtualFramebuffer *framebuffer, int flags); + + // Reads a rectangular subregion of a framebuffer to the right position in its backing memory. void ReadFramebufferToMemory(VirtualFramebuffer *vfb, bool sync, int x, int y, int w, int h) override; void DownloadFramebufferForClut(u32 fb_address, u32 loadBytes) override; - - virtual void MakePixelTexture(const u8 *srcPixels, GEBufferFormat srcPixelFormat, int srcStride, int width, int height) override { - } - - void DrawPixels(VirtualFramebuffer *vfb, int dstX, int dstY, const u8 *srcPixels, GEBufferFormat srcPixelFormat, int srcStride, int width, int height) override; - - virtual void DrawFramebufferToOutput(const u8 *srcPixels, GEBufferFormat srcPixelFormat, int srcStride, bool applyPostShader) override { - throw std::logic_error("The method or operation is not implemented."); - } - - virtual void DisableState() override { - } - - virtual void FlushBeforeCopy() override; - - void DecimateFBOs() override; - - virtual void BlitFramebuffer(VirtualFramebuffer *dst, int dstX, int dstY, VirtualFramebuffer *src, int srcX, int srcY, int w, int h, int bpp) override { - throw std::logic_error("The method or operation is not implemented."); - } - - virtual void DestroyFramebuf(VirtualFramebuffer *vfb) override { - throw std::logic_error("The method or operation is not implemented."); - } - - virtual void ResizeFramebufFBO(VirtualFramebuffer *vfb, u16 w, u16 h, bool force = false) override { - } - - virtual void NotifyRenderFramebufferCreated(VirtualFramebuffer *vfb) override { - } - - virtual void NotifyRenderFramebufferSwitched(VirtualFramebuffer *prevVfb, VirtualFramebuffer *vfb, bool isClearingDepth) override { - } - - virtual void NotifyRenderFramebufferUpdated(VirtualFramebuffer *vfb, bool vfbFormatChanged) override { - } - - void DestroyAllFBOs(); - void Resized(); - void DeviceLost(); - - void CopyDisplayToOutput(); - void EndFrame(); - std::vector GetFramebufferList(); + bool NotifyStencilUpload(u32 addr, int size, bool skipZero = false) override; + + void DestroyFramebuf(VirtualFramebuffer *vfb) override; + void ResizeFramebufFBO(VirtualFramebuffer *vfb, u16 w, u16 h, bool force = false) override; + + bool GetFramebuffer(u32 fb_address, int fb_stride, GEBufferFormat format, GPUDebugBuffer &buffer); + bool GetDepthbuffer(u32 fb_address, int fb_stride, u32 z_address, int z_stride, GPUDebugBuffer &buffer); + bool GetStencilbuffer(u32 fb_address, int fb_stride, GPUDebugBuffer &buffer); + static bool GetDisplayFramebuffer(GPUDebugBuffer &buffer); + + virtual void RebindFramebuffer() override; + + VulkanFramebuffer *GetTempFBO(u16 w, u16 h, VulkanFBOColorDepth depth = VK_FBO_8888); + + // Cardboard Settings Calculator + struct CardboardSettings * GetCardboardSettings(struct CardboardSettings * cardboardSettings); + protected: - bool CreateDownloadTempBuffer(VirtualFramebuffer *nvfb) override; - void UpdateDownloadTempBuffer(VirtualFramebuffer *nvfb) override; + virtual void DisableState() override; + virtual void ClearBuffer(bool keepState = false); + virtual void FlushBeforeCopy() override; + virtual void DecimateFBOs() override; + + // Used by ReadFramebufferToMemory and later framebuffer block copies + virtual void BlitFramebuffer(VirtualFramebuffer *dst, int dstX, int dstY, VirtualFramebuffer *src, int srcX, int srcY, int w, int h, int bpp) override; + + virtual void NotifyRenderFramebufferCreated(VirtualFramebuffer *vfb) override; + virtual void NotifyRenderFramebufferSwitched(VirtualFramebuffer *prevVfb, VirtualFramebuffer *vfb, bool isClearingDepth) override; + virtual void NotifyRenderFramebufferUpdated(VirtualFramebuffer *vfb, bool vfbFormatChanged) override; + virtual bool CreateDownloadTempBuffer(VirtualFramebuffer *nvfb) override; + virtual void UpdateDownloadTempBuffer(VirtualFramebuffer *nvfb) override; + private: + void UpdatePostShaderUniforms(int bufferWidth, int bufferHeight, int renderWidth, int renderHeight); + void CompileDraw2DProgram(); + void DestroyDraw2DProgram(); + + void SetNumExtraFBOs(int num); + + void PackFramebufferAsync_(VirtualFramebuffer *vfb); // Not used under ES currently + void PackFramebufferSync_(VirtualFramebuffer *vfb, int x, int y, int w, int h); + VulkanContext *vulkan_; - VkCommandBuffer cmd_; + + // The command buffer of the current framebuffer pass being rendered to. + // One framebuffer can be used as a texturing source at multiple times in a frame, + // but then the contents have to be copied out into a new texture every time. + VkCommandBuffer curCmd_; - TextureCacheVulkan *texCache_; DrawEngineVulkan *drawEngine_; + + // Used by DrawPixels + VulkanTexture *drawPixelsTex_; + GEBufferFormat drawPixelsTexFormat_; + + int drawPixelsTexW_; + int drawPixelsTexH_; + + u8 *convBuf_; + u32 convBufSize_; + + TextureCacheVulkan *textureCache_; + ShaderManagerVulkan *shaderManager_; + DrawEngineVulkan *transformDraw_; + + // Used by post-processing shader + std::vector extraFBOs_; + + bool resized_; + + struct TempFBO { + VulkanFramebuffer *fbo_vk; + int last_frame_used; + }; + + std::map tempFBOs_; + + // Not used under ES currently. + AsyncPBOVulkan *pixelBufObj_; //this isn't that large + u8 currentPBO_; + + // This gets copied to the current frame's push buffer as needed. + PostShaderUniforms postUniforms_; }; diff --git a/GPU/Vulkan/GPU_Vulkan.cpp b/GPU/Vulkan/GPU_Vulkan.cpp index 426b004252..96b3a99a81 100644 --- a/GPU/Vulkan/GPU_Vulkan.cpp +++ b/GPU/Vulkan/GPU_Vulkan.cpp @@ -394,7 +394,6 @@ GPU_Vulkan::GPU_Vulkan(GraphicsContext *ctx) : vulkan_((VulkanContext *)ctx->GetAPIContext()), drawEngine_(vulkan_), textureCache_(vulkan_), - framebufferManager_(vulkan_), resized_(false), gfxCtx_(ctx) { UpdateVsyncInterval(true); @@ -402,14 +401,15 @@ GPU_Vulkan::GPU_Vulkan(GraphicsContext *ctx) shaderManager_ = new ShaderManagerVulkan(vulkan_); pipelineManager_ = new PipelineManagerVulkan(vulkan_); + framebufferManager_ = new FramebufferManagerVulkan(vulkan_), drawEngine_.SetTextureCache(&textureCache_); - drawEngine_.SetFramebufferManager(&framebufferManager_); + drawEngine_.SetFramebufferManager(framebufferManager_); drawEngine_.SetShaderManager(shaderManager_); drawEngine_.SetPipelineManager(pipelineManager_); - framebufferManager_.Init(); - framebufferManager_.SetTextureCache(&textureCache_); - framebufferManager_.SetDrawEngine(&drawEngine_); - textureCache_.SetFramebufferManager(&framebufferManager_); + framebufferManager_->Init(); + framebufferManager_->SetTextureCache(&textureCache_); + framebufferManager_->SetDrawEngine(&drawEngine_); + textureCache_.SetFramebufferManager(framebufferManager_); textureCache_.SetDepalShaderCache(&depalShaderCache_); textureCache_.SetShaderManager(shaderManager_); textureCache_.SetTransformDrawEngine(&drawEngine_); @@ -453,8 +453,7 @@ GPU_Vulkan::GPU_Vulkan(GraphicsContext *ctx) } GPU_Vulkan::~GPU_Vulkan() { - framebufferManager_.DestroyAllFBOs(); - shaderManager_->ClearCache(true); + framebufferManager_->DestroyAllFBOs(); depalShaderCache_.Clear(); delete shaderManager_; shaderManager_ = nullptr; @@ -511,12 +510,12 @@ void GPU_Vulkan::BeginHostFrame() { shaderManager_->DirtyShader(); shaderManager_->DirtyUniform(DIRTY_ALL); - framebufferManager_.BeginFrame(); + framebufferManager_->BeginFrame(); } void GPU_Vulkan::EndHostFrame() { drawEngine_.EndFrame(); - framebufferManager_.EndFrame(); + framebufferManager_->EndFrame(); } // Needs to be called on GPU thread, not reporting thread. @@ -542,8 +541,8 @@ void GPU_Vulkan::Reinitialize() { void GPU_Vulkan::ReinitializeInternal() { textureCache_.Clear(true); depalShaderCache_.Clear(); - framebufferManager_.DestroyAllFBOs(); - framebufferManager_.Resized(); + framebufferManager_->DestroyAllFBOs(); + framebufferManager_->Resized(); } void GPU_Vulkan::InitClearInternal() { @@ -601,7 +600,7 @@ void GPU_Vulkan::BeginFrameInternal() { void GPU_Vulkan::SetDisplayFramebuffer(u32 framebuf, u32 stride, GEBufferFormat format) { host->GPUNotifyDisplay(framebuf, stride, format); - framebufferManager_.SetDisplayFramebuffer(framebuf, stride, format); + framebufferManager_->SetDisplayFramebuffer(framebuf, stride, format); } bool GPU_Vulkan::FramebufferDirty() { @@ -610,7 +609,7 @@ bool GPU_Vulkan::FramebufferDirty() { SyncThread(); } - VirtualFramebuffer *vfb = framebufferManager_.GetDisplayVFB(); + VirtualFramebuffer *vfb = framebufferManager_->GetDisplayVFB(); if (vfb) { bool dirty = vfb->dirtyAfterDisplay; vfb->dirtyAfterDisplay = false; @@ -625,7 +624,7 @@ bool GPU_Vulkan::FramebufferReallyDirty() { SyncThread(); } - VirtualFramebuffer *vfb = framebufferManager_.GetDisplayVFB(); + VirtualFramebuffer *vfb = framebufferManager_->GetDisplayVFB(); if (vfb) { bool dirty = vfb->reallyDirtyAfterDisplay; vfb->reallyDirtyAfterDisplay = false; @@ -644,7 +643,7 @@ void GPU_Vulkan::CopyDisplayToOutputInternal() { shaderManager_->DirtyLastShader(); - framebufferManager_.CopyDisplayToOutput(); + framebufferManager_->CopyDisplayToOutput(); gstate_c.textureChanged = TEXCHANGE_UPDATED; } @@ -774,7 +773,7 @@ void GPU_Vulkan::Execute_Prim(u32 op, u32 diff) { } // This also makes skipping drawing very effective. - framebufferManager_.SetRenderFrameBuffer(gstate_c.framebufChanged, gstate_c.skipDrawReason); + framebufferManager_->SetRenderFrameBuffer(gstate_c.framebufChanged, gstate_c.skipDrawReason); if (gstate_c.skipDrawReason & (SKIPDRAW_SKIPFRAME | SKIPDRAW_NON_DISPLAYED_FB)) { drawEngine_.SetupVertexDecoder(gstate.vertType); // Rough estimate, not sure what's correct. @@ -850,7 +849,7 @@ void GPU_Vulkan::Execute_VertexTypeSkinning(u32 op, u32 diff) { void GPU_Vulkan::Execute_Bezier(u32 op, u32 diff) { // This also make skipping drawing very effective. - framebufferManager_.SetRenderFrameBuffer(gstate_c.framebufChanged, gstate_c.skipDrawReason); + framebufferManager_->SetRenderFrameBuffer(gstate_c.framebufChanged, gstate_c.skipDrawReason); if (gstate_c.skipDrawReason & (SKIPDRAW_SKIPFRAME | SKIPDRAW_NON_DISPLAYED_FB)) { // TODO: Should this eat some cycles? Probably yes. Not sure if important. return; @@ -893,7 +892,7 @@ void GPU_Vulkan::Execute_Bezier(u32 op, u32 diff) { void GPU_Vulkan::Execute_Spline(u32 op, u32 diff) { // This also make skipping drawing very effective. - framebufferManager_.SetRenderFrameBuffer(gstate_c.framebufChanged, gstate_c.skipDrawReason); + framebufferManager_->SetRenderFrameBuffer(gstate_c.framebufChanged, gstate_c.skipDrawReason); if (gstate_c.skipDrawReason & (SKIPDRAW_SKIPFRAME | SKIPDRAW_NON_DISPLAYED_FB)) { // TODO: Should this eat some cycles? Probably yes. Not sure if important. return; @@ -1935,7 +1934,7 @@ void GPU_Vulkan::UpdateStats() { gpuStats.numFragmentShaders = shaderManager_->GetNumFragmentShaders(); gpuStats.numShaders = pipelineManager_->GetNumPipelines(); gpuStats.numTextures = (int)textureCache_.NumLoadedTextures(); - gpuStats.numFBOs = (int)framebufferManager_.NumVFBs(); + gpuStats.numFBOs = (int)framebufferManager_->NumVFBs(); } void GPU_Vulkan::DoBlockTransfer(u32 skipDrawReason) { @@ -1992,7 +1991,7 @@ void GPU_Vulkan::DoBlockTransfer(u32 skipDrawReason) { } // Tell the framebuffer manager to take action if possible. If it does the entire thing, let's just return. - if (!framebufferManager_.NotifyBlockTransferBefore(dstBasePtr, dstStride, dstX, dstY, srcBasePtr, srcStride, srcX, srcY, width, height, bpp, skipDrawReason)) { + if (!framebufferManager_->NotifyBlockTransferBefore(dstBasePtr, dstStride, dstX, dstY, srcBasePtr, srcStride, srcX, srcY, width, height, bpp, skipDrawReason)) { // Do the copy! (Hm, if we detect a drawn video frame (see below) then we could maybe skip this?) // Can use GetPointerUnchecked because we checked the addresses above. We could also avoid them // entirely by walking a couple of pointers... @@ -2015,7 +2014,7 @@ void GPU_Vulkan::DoBlockTransfer(u32 skipDrawReason) { } textureCache_.Invalidate(dstBasePtr + (dstY * dstStride + dstX) * bpp, height * dstStride * bpp, GPU_INVALIDATE_HINT); - framebufferManager_.NotifyBlockTransferAfter(dstBasePtr, dstStride, dstX, dstY, srcBasePtr, srcStride, srcX, srcY, width, height, bpp, skipDrawReason); + framebufferManager_->NotifyBlockTransferAfter(dstBasePtr, dstStride, dstX, dstY, srcBasePtr, srcStride, srcX, srcY, width, height, bpp, skipDrawReason); } #ifndef MOBILE_DEVICE @@ -2041,17 +2040,17 @@ void GPU_Vulkan::InvalidateCacheInternal(u32 addr, int size, GPUInvalidationType else textureCache_.InvalidateAll(type); - if (type != GPU_INVALIDATE_ALL && framebufferManager_.MayIntersectFramebuffer(addr)) { + if (type != GPU_INVALIDATE_ALL && framebufferManager_->MayIntersectFramebuffer(addr)) { // If we're doing block transfers, we shouldn't need this, and it'll only confuse us. // Vempire invalidates (with writeback) after drawing, but before blitting. if (!g_Config.bBlockTransferGPU || type == GPU_INVALIDATE_SAFE) { - framebufferManager_.UpdateFromMemory(addr, size, type == GPU_INVALIDATE_SAFE); + framebufferManager_->UpdateFromMemory(addr, size, type == GPU_INVALIDATE_SAFE); } } } void GPU_Vulkan::PerformMemoryCopyInternal(u32 dest, u32 src, int size) { - if (!framebufferManager_.NotifyFramebufferCopy(src, dest, size, false, gstate_c.skipDrawReason)) { + if (!framebufferManager_->NotifyFramebufferCopy(src, dest, size, false, gstate_c.skipDrawReason)) { // We use a little hack for Download/Upload using a VRAM mirror. // Since they're identical we don't need to copy. if (!Memory::IsVRAMAddress(dest) || (dest ^ 0x00400000) != src) { @@ -2062,18 +2061,18 @@ void GPU_Vulkan::PerformMemoryCopyInternal(u32 dest, u32 src, int size) { } void GPU_Vulkan::PerformMemorySetInternal(u32 dest, u8 v, int size) { - if (!framebufferManager_.NotifyFramebufferCopy(dest, dest, size, true, gstate_c.skipDrawReason)) { + if (!framebufferManager_->NotifyFramebufferCopy(dest, dest, size, true, gstate_c.skipDrawReason)) { InvalidateCache(dest, size, GPU_INVALIDATE_HINT); } } void GPU_Vulkan::PerformStencilUploadInternal(u32 dest, int size) { - framebufferManager_.NotifyStencilUpload(dest, size); + framebufferManager_->NotifyStencilUpload(dest, size); } bool GPU_Vulkan::PerformMemoryCopy(u32 dest, u32 src, int size) { // Track stray copies of a framebuffer in RAM. MotoGP does this. - if (framebufferManager_.MayIntersectFramebuffer(src) || framebufferManager_.MayIntersectFramebuffer(dest)) { + if (framebufferManager_->MayIntersectFramebuffer(src) || framebufferManager_->MayIntersectFramebuffer(dest)) { if (IsOnSeparateCPUThread()) { GPUEvent ev(GPU_EVENT_FB_MEMCPY); ev.fb_memcpy.dst = dest; @@ -2095,7 +2094,7 @@ bool GPU_Vulkan::PerformMemoryCopy(u32 dest, u32 src, int size) { bool GPU_Vulkan::PerformMemorySet(u32 dest, u8 v, int size) { // This may indicate a memset, usually to 0, of a framebuffer. - if (framebufferManager_.MayIntersectFramebuffer(dest)) { + if (framebufferManager_->MayIntersectFramebuffer(dest)) { Memory::Memset(dest, v, size); if (IsOnSeparateCPUThread()) { @@ -2136,7 +2135,7 @@ bool GPU_Vulkan::PerformMemoryUpload(u32 dest, int size) { } bool GPU_Vulkan::PerformStencilUpload(u32 dest, int size) { - if (framebufferManager_.MayIntersectFramebuffer(dest)) { + if (framebufferManager_->MayIntersectFramebuffer(dest)) { if (IsOnSeparateCPUThread()) { GPUEvent ev(GPU_EVENT_FB_STENCIL_UPLOAD); ev.fb_stencil_upload.dst = dest; @@ -2156,15 +2155,15 @@ void GPU_Vulkan::ClearCacheNextFrame() { void GPU_Vulkan::Resized() { resized_ = true; - framebufferManager_.Resized(); + framebufferManager_->Resized(); } void GPU_Vulkan::ClearShaderCache() { - shaderManager_->ClearCache(true); + // TODO } std::vector GPU_Vulkan::GetFramebufferList() { - return framebufferManager_.GetFramebufferList(); + return framebufferManager_->GetFramebufferList(); } void GPU_Vulkan::DoState(PointerWrap &p) { @@ -2178,8 +2177,9 @@ void GPU_Vulkan::DoState(PointerWrap &p) { depalShaderCache_.Clear(); gstate_c.textureChanged = TEXCHANGE_UPDATED; - framebufferManager_.DestroyAllFBOs(); - shaderManager_->ClearCache(true); + framebufferManager_->DestroyAllFBOs(); + shaderManager_->ClearShaders(); + pipelineManager_->Clear(); } } diff --git a/GPU/Vulkan/GPU_Vulkan.h b/GPU/Vulkan/GPU_Vulkan.h index c88f9931d2..1890017e5c 100644 --- a/GPU/Vulkan/GPU_Vulkan.h +++ b/GPU/Vulkan/GPU_Vulkan.h @@ -21,13 +21,13 @@ #include #include "GPU/GPUCommon.h" -#include "GPU/Vulkan/FramebufferVulkan.h" #include "GPU/Vulkan/DrawEngineVulkan.h" #include "GPU/Vulkan/PipelineManagerVulkan.h" #include "GPU/Vulkan/TextureCacheVulkan.h" #include "GPU/Vulkan/DepalettizeShaderVulkan.h" -class ShaderManager; +class FramebufferManagerVulkan; +class ShaderManagerVulkan; class LinkedShader; class GPU_Vulkan : public GPUCommon { @@ -178,7 +178,7 @@ private: GraphicsContext *gfxCtx_; VulkanContext *vulkan_; - FramebufferManagerVulkan framebufferManager_; + FramebufferManagerVulkan *framebufferManager_; TextureCacheVulkan textureCache_; DepalShaderCacheVulkan depalShaderCache_; DrawEngineVulkan drawEngine_; diff --git a/GPU/Vulkan/PipelineManagerVulkan.cpp b/GPU/Vulkan/PipelineManagerVulkan.cpp index 89034ff8e4..2721adad09 100644 --- a/GPU/Vulkan/PipelineManagerVulkan.cpp +++ b/GPU/Vulkan/PipelineManagerVulkan.cpp @@ -12,6 +12,10 @@ PipelineManagerVulkan::PipelineManagerVulkan(VulkanContext *vulkan) : vulkan_(vu } PipelineManagerVulkan::~PipelineManagerVulkan() { + Clear(); +} + +void PipelineManagerVulkan::Clear() { // This should kill off all the shaders at once. // This could also be an opportunity to store the whole cache to disk. Will need to also // store the keys. diff --git a/GPU/Vulkan/PipelineManagerVulkan.h b/GPU/Vulkan/PipelineManagerVulkan.h index 8d9e8d8761..951cd6f348 100644 --- a/GPU/Vulkan/PipelineManagerVulkan.h +++ b/GPU/Vulkan/PipelineManagerVulkan.h @@ -81,7 +81,9 @@ public: ~PipelineManagerVulkan(); VulkanPipeline *GetOrCreatePipeline(VkPipelineLayout layout, const VulkanPipelineRasterStateKey &rasterKey, const VertexDecoder *vtxDec, VkShaderModule vShader, VkShaderModule fShader, bool useHwTransform); - int GetNumPipelines() const { return 0; } + int GetNumPipelines() const { return (int)pipelines_.size(); } + + void Clear(); std::string DebugGetObjectString(std::string id, DebugShaderType type, DebugShaderStringType stringType); std::vector DebugGetObjectIDs(DebugShaderType type); diff --git a/GPU/Vulkan/ShaderManagerVulkan.cpp b/GPU/Vulkan/ShaderManagerVulkan.cpp index d8e390aebf..0bf47a6743 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.cpp +++ b/GPU/Vulkan/ShaderManagerVulkan.cpp @@ -181,6 +181,7 @@ ShaderManagerVulkan::ShaderManagerVulkan(VulkanContext *vulkan) } ShaderManagerVulkan::~ShaderManagerVulkan() { + ClearShaders(); delete[] codeBuffer_; } @@ -447,15 +448,14 @@ void ShaderManagerVulkan::Clear() { vsCache_.clear(); lastFSID_.clear(); lastVSID_.clear(); +} + +void ShaderManagerVulkan::ClearShaders() { + Clear(); DirtyShader(); DirtyUniform(0xFFFFFFFF); } -void ShaderManagerVulkan::ClearCache(bool deleteThem) { - Clear(); -} - - void ShaderManagerVulkan::DirtyShader() { // Forget the last shader ID lastFSID_.clear(); diff --git a/GPU/Vulkan/ShaderManagerVulkan.h b/GPU/Vulkan/ShaderManagerVulkan.h index 2042d4ec95..7c21609583 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.h +++ b/GPU/Vulkan/ShaderManagerVulkan.h @@ -217,9 +217,8 @@ public: ShaderManagerVulkan(VulkanContext *vulkan); ~ShaderManagerVulkan(); - void ClearCache(bool deleteThem); // TODO: deleteThem currently not respected void GetShaders(int prim, u32 vertType, VulkanVertexShader **vshader, VulkanFragmentShader **fshader, bool useHWTransform); - + void ClearShaders(); void DirtyShader(); void DirtyLastShader(); diff --git a/ext/native/thin3d/VulkanContext.cpp b/ext/native/thin3d/VulkanContext.cpp index 75bcdc3663..02ab4899a0 100644 --- a/ext/native/thin3d/VulkanContext.cpp +++ b/ext/native/thin3d/VulkanContext.cpp @@ -905,8 +905,7 @@ void VulkanContext::InitSwapchain(VkCommandBuffer cmd) { surface, &presentModeCount, NULL); assert(res == VK_SUCCESS); - VkPresentModeKHR *presentModes = - (VkPresentModeKHR *)malloc(presentModeCount * sizeof(VkPresentModeKHR)); + VkPresentModeKHR *presentModes = new VkPresentModeKHR[presentModeCount]; assert(presentModes); res = fpGetPhysicalDeviceSurfacePresentModesKHR(physical_devices_[0], surface, @@ -944,7 +943,7 @@ void VulkanContext::InitSwapchain(VkCommandBuffer cmd) { break; } } - + delete[] presentModes; // Determine the number of VkImage's to use in the swap chain (we desire to // own only 1 image at a time, besides the images being displayed and // queued for display): @@ -1650,7 +1649,7 @@ bool GLSLtoSPV(const VkShaderStageFlagBits shader_type, const char *pshader, std::vector &spirv, std::string *errorMessage) { - glslang::TProgram& program = *new glslang::TProgram; + glslang::TProgram program; const char *shaderStrings[1]; TBuiltInResource Resources; init_resources(Resources); @@ -1659,33 +1658,30 @@ bool GLSLtoSPV(const VkShaderStageFlagBits shader_type, EShMessages messages = (EShMessages)(EShMsgSpvRules | EShMsgVulkanRules); EShLanguage stage = FindLanguage(shader_type); - glslang::TShader* shader = new glslang::TShader(stage); + glslang::TShader shader(stage); shaderStrings[0] = pshader; - shader->setStrings(shaderStrings, 1); + shader.setStrings(shaderStrings, 1); - if (!shader->parse(&Resources, 100, false, messages)) { - puts(shader->getInfoLog()); - puts(shader->getInfoDebugLog()); + if (!shader.parse(&Resources, 100, false, messages)) { + puts(shader.getInfoLog()); + puts(shader.getInfoDebugLog()); if (errorMessage) { - *errorMessage = shader->getInfoLog(); - (*errorMessage) += shader->getInfoDebugLog(); + *errorMessage = shader.getInfoLog(); + (*errorMessage) += shader.getInfoDebugLog(); } return false; // something didn't work } - program.addShader(shader); - - // - // Program-level processing... - // + // Note that program does not take ownership of &shader, so this is fine. + program.addShader(&shader); if (!program.link(messages)) { - puts(shader->getInfoLog()); - puts(shader->getInfoDebugLog()); + puts(shader.getInfoLog()); + puts(shader.getInfoDebugLog()); if (errorMessage) { - *errorMessage = shader->getInfoLog(); - (*errorMessage) += shader->getInfoDebugLog(); + *errorMessage = shader.getInfoLog(); + (*errorMessage) += shader.getInfoDebugLog(); } return false; } diff --git a/ext/native/thin3d/thin3d_vulkan.cpp b/ext/native/thin3d/thin3d_vulkan.cpp index 89d6b5097e..52252b0236 100644 --- a/ext/native/thin3d/thin3d_vulkan.cpp +++ b/ext/native/thin3d/thin3d_vulkan.cpp @@ -279,6 +279,7 @@ public: ~Thin3DVKShaderSet() { vshader->Release(); fshader->Release(); + delete[] ubo_; } bool Link(); @@ -667,7 +668,9 @@ Thin3DVKContext::~Thin3DVKContext() { vkDestroyCommandPool(device_, cmdPool_, nullptr); // This also destroys all descriptor sets. for (int i = 0; i < 2; i++) { + frame_[i].descSets_.clear(); vkDestroyDescriptorPool(device_, frame_[i].descriptorPool, nullptr); + delete frame_[i].pushBuffer; } vkDestroyDescriptorSetLayout(device_, descriptorSetLayout_, nullptr); vkDestroyPipelineLayout(device_, pipelineLayout_, nullptr); diff --git a/ext/vulkan/vk_sdk_platform.h b/ext/vulkan/vk_sdk_platform.h index f79396bac1..6450895df2 100644 --- a/ext/vulkan/vk_sdk_platform.h +++ b/ext/vulkan/vk_sdk_platform.h @@ -46,7 +46,9 @@ #define snprintf _snprintf #endif +#ifndef strdup #define strdup _strdup +#endif #endif // _WIN32 From 02d164887263c3e4d18a9603dfe713345441a073 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 10 Jan 2016 16:55:18 +0100 Subject: [PATCH 043/116] Delete pipeline caches asynchronously too --- GPU/Vulkan/PipelineManagerVulkan.cpp | 2 +- ext/native/thin3d/VulkanContext.h | 17 ++++++++++++----- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/GPU/Vulkan/PipelineManagerVulkan.cpp b/GPU/Vulkan/PipelineManagerVulkan.cpp index 2721adad09..f3275566cd 100644 --- a/GPU/Vulkan/PipelineManagerVulkan.cpp +++ b/GPU/Vulkan/PipelineManagerVulkan.cpp @@ -19,7 +19,7 @@ void PipelineManagerVulkan::Clear() { // This should kill off all the shaders at once. // This could also be an opportunity to store the whole cache to disk. Will need to also // store the keys. - vkDestroyPipelineCache(vulkan_->GetDevice(), pipelineCache_, nullptr); + vulkan_->QueueDelete(pipelineCache_); for (auto iter : pipelines_) { delete iter.second; } diff --git a/ext/native/thin3d/VulkanContext.h b/ext/native/thin3d/VulkanContext.h index 920aecaa9b..4588e57cd0 100644 --- a/ext/native/thin3d/VulkanContext.h +++ b/ext/native/thin3d/VulkanContext.h @@ -75,8 +75,9 @@ public: void QueueDelete(VkBufferView bufferView) { bufferViews_.push_back(bufferView); } void QueueDelete(VkImage image) { images_.push_back(image); } void QueueDelete(VkImageView imageView) { imageViews_.push_back(imageView); } - void QueueDelete(VkDeviceMemory deviceMemory) { memory_.push_back(deviceMemory); } + void QueueDelete(VkDeviceMemory deviceMemory) { deviceMemory_.push_back(deviceMemory); } void QueueDelete(VkSampler sampler) { samplers_.push_back(sampler); } + void QueueDelete(VkPipelineCache pipelineCache) { pipelineCaches_.push_back(pipelineCache); } void Take(VulkanDeleteList &del) { descPools_ = std::move(del.descPools_); @@ -85,8 +86,9 @@ public: bufferViews_ = std::move(del.bufferViews_); images_ = std::move(del.images_); imageViews_ = std::move(del.imageViews_); - memory_ = std::move(del.memory_); + deviceMemory_ = std::move(del.deviceMemory_); samplers_ = std::move(del.samplers_); + pipelineCaches_ = std::move(del.pipelineCaches_); } void PerformDeletes(VkDevice device) { @@ -110,14 +112,18 @@ public: vkDestroyImageView(device, imageView, nullptr); } imageViews_.clear(); - for (auto &mem : memory_) { + for (auto &mem : deviceMemory_) { vkFreeMemory(device, mem, nullptr); } - memory_.clear(); + deviceMemory_.clear(); for (auto &sampler : samplers_) { vkDestroySampler(device, sampler, nullptr); } samplers_.clear(); + for (auto &pcache : pipelineCaches_) { + vkDestroyPipelineCache(device, pcache, nullptr); + } + pipelineCaches_.clear(); } private: @@ -127,8 +133,9 @@ private: std::vector bufferViews_; std::vector images_; std::vector imageViews_; - std::vector memory_; + std::vector deviceMemory_; std::vector samplers_; + std::vector pipelineCaches_; }; // VulkanContext sets up the basics necessary for rendering to a window, including framebuffers etc. From 4b978b1fd3c7ca1e36a52889aaae5b86d761f286 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 10 Jan 2016 23:41:19 +0100 Subject: [PATCH 044/116] Crashfix, fix left-behind culling disabling --- GPU/Vulkan/PipelineManagerVulkan.cpp | 2 +- GPU/Vulkan/StateMappingVulkan.cpp | 4 ---- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/GPU/Vulkan/PipelineManagerVulkan.cpp b/GPU/Vulkan/PipelineManagerVulkan.cpp index f3275566cd..d704d172db 100644 --- a/GPU/Vulkan/PipelineManagerVulkan.cpp +++ b/GPU/Vulkan/PipelineManagerVulkan.cpp @@ -13,13 +13,13 @@ PipelineManagerVulkan::PipelineManagerVulkan(VulkanContext *vulkan) : vulkan_(vu PipelineManagerVulkan::~PipelineManagerVulkan() { Clear(); + vulkan_->QueueDelete(pipelineCache_); } void PipelineManagerVulkan::Clear() { // This should kill off all the shaders at once. // This could also be an opportunity to store the whole cache to disk. Will need to also // store the keys. - vulkan_->QueueDelete(pipelineCache_); for (auto iter : pipelines_) { delete iter.second; } diff --git a/GPU/Vulkan/StateMappingVulkan.cpp b/GPU/Vulkan/StateMappingVulkan.cpp index c2ea8a2e21..60e8a0bdac 100644 --- a/GPU/Vulkan/StateMappingVulkan.cpp +++ b/GPU/Vulkan/StateMappingVulkan.cpp @@ -202,7 +202,6 @@ void ConvertStateToVulkanKey(FramebufferManagerVulkan &fbManager, ShaderManagerV // Set cull bool wantCull = !gstate.isModeThrough() && prim != GE_PRIM_RECTANGLES && gstate.isCullEnabled(); key.cullMode = wantCull ? (gstate.getCullMode() ? VK_CULL_MODE_FRONT_BIT : VK_CULL_MODE_BACK_BIT) : VK_CULL_MODE_NONE; - key.cullMode = VK_CULL_MODE_NONE; // Depth Test if (gstate.isDepthTestEnabled()) { @@ -290,9 +289,6 @@ void ConvertStateToVulkanKey(FramebufferManagerVulkan &fbManager, ShaderManagerV if (depthMin < 0.0f) depthMin = 0.0f; if (depthMax > 1.0f) depthMax = 1.0f; - if (vpAndScissor.dirtyProj) { - shaderManager->DirtyUniform(DIRTY_PROJMATRIX); - } if (vpAndScissor.dirtyDepth) { shaderManager->DirtyUniform(DIRTY_DEPTHRANGE); } From d5f685ce05cbca165adbbe9daab805482e663fae Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 10 Jan 2016 23:42:09 +0100 Subject: [PATCH 045/116] WIP trying to fix drawing issues --- GPU/Vulkan/DrawEngineVulkan.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index bdfa8612f3..7a4edb7909 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -626,18 +626,19 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { }; vkCmdBindDescriptorSets(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout_, 0, 1, &ds, 3, dynamicUBOOffsets); - vbOffset = (uint32_t)frame->pushData->Push(drawBuffer, numTrans * sizeof(TransformedVertex)); - VkBuffer buf[1] = { frame->pushData->GetVkBuffer() }; - VkDeviceSize offsets[1] = { vbOffset }; if (drawIndexed) { - ibOffset = (uint32_t)frame->pushData->Push(inds, 2 * numTrans); + vbOffset = (uint32_t)frame->pushData->PushAligned(drawBuffer, maxIndex * sizeof(TransformedVertex), 16); + ibOffset = (uint32_t)frame->pushData->PushAligned(inds, sizeof(short) * numTrans, 16); + VkDeviceSize offsets[1] = { vbOffset }; // TODO: Have a buffer per frame, use a walking buffer pointer // TODO: Avoid rebinding if the vertex size stays the same by using the offset arguments vkCmdBindVertexBuffers(cmd_, 0, 1, buf, offsets); vkCmdBindIndexBuffer(cmd_, buf[0], ibOffset, VK_INDEX_TYPE_UINT16); vkCmdDrawIndexed(cmd_, numTrans, 1, 0, 0, 0); } else { + vbOffset = (uint32_t)frame->pushData->PushAligned(drawBuffer, numTrans * sizeof(TransformedVertex), 16); + VkDeviceSize offsets[1] = { vbOffset }; // TODO: Avoid rebinding if the vertex size stays the same by using the offset arguments vkCmdBindVertexBuffers(cmd_, 0, 1, buf, offsets); vkCmdDraw(cmd_, numTrans, 1, 0, 0); From 5b70957b1f283771d2a5e6064a0cb0d9f6dfe6e5 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Tue, 19 Jan 2016 18:41:45 +0100 Subject: [PATCH 046/116] Expose another couple of vulkan device features. --- GPU/Vulkan/GPU_Vulkan.cpp | 8 ++++---- GPU/Vulkan/GPU_Vulkan.h | 2 +- ext/native/thin3d/VulkanContext.cpp | 6 ++++++ ext/native/thin3d/thin3d_vulkan.cpp | 2 ++ 4 files changed, 13 insertions(+), 5 deletions(-) diff --git a/GPU/Vulkan/GPU_Vulkan.cpp b/GPU/Vulkan/GPU_Vulkan.cpp index 96b3a99a81..b465cc357b 100644 --- a/GPU/Vulkan/GPU_Vulkan.cpp +++ b/GPU/Vulkan/GPU_Vulkan.cpp @@ -2116,6 +2116,10 @@ bool GPU_Vulkan::PerformMemorySet(u32 dest, u8 v, int size) { return false; } +void GPU_Vulkan::NotifyVideoUpload(u32 addr, int size, int width, int format) { + +} + bool GPU_Vulkan::PerformMemoryDownload(u32 dest, int size) { // Cheat a bit to force a download of the framebuffer. // VRAM + 0x00400000 is simply a VRAM mirror. @@ -2214,7 +2218,3 @@ std::string GPU_Vulkan::DebugGetShaderString(std::string id, DebugShaderType typ return shaderManager_->DebugGetShaderString(id, type, stringType); } } - -void GPU_Vulkan::NotifyVideoUpload(u32 addr, int size, int width, int format) { - -} diff --git a/GPU/Vulkan/GPU_Vulkan.h b/GPU/Vulkan/GPU_Vulkan.h index 1890017e5c..45d60b43bf 100644 --- a/GPU/Vulkan/GPU_Vulkan.h +++ b/GPU/Vulkan/GPU_Vulkan.h @@ -51,10 +51,10 @@ public: void ReapplyGfxStateInternal() override; void SetDisplayFramebuffer(u32 framebuf, u32 stride, GEBufferFormat format) override; void CopyDisplayToOutput() override; + void NotifyVideoUpload(u32 addr, int size, int width, int format) override; void BeginFrame() override; void UpdateStats() override; void InvalidateCache(u32 addr, int size, GPUInvalidationType type) override; - void NotifyVideoUpload(u32 addr, int size, int width, int format) override; bool PerformMemoryCopy(u32 dest, u32 src, int size) override; bool PerformMemorySet(u32 dest, u8 v, int size) override; bool PerformMemoryDownload(u32 dest, int size) override; diff --git a/ext/native/thin3d/VulkanContext.cpp b/ext/native/thin3d/VulkanContext.cpp index 02ab4899a0..923ddfb857 100644 --- a/ext/native/thin3d/VulkanContext.cpp +++ b/ext/native/thin3d/VulkanContext.cpp @@ -622,6 +622,12 @@ VkResult VulkanContext::CreateDevice(int physical_device) { if (featuresAvailable_.logicOp) { featuresEnabled_.logicOp = true; } + if (featuresAvailable_.depthClamp) { + featuresEnabled_.depthClamp = true; + } + if (featuresAvailable_.depthBounds) { + featuresEnabled_.depthBounds = true; + } VkDeviceCreateInfo device_info = {}; device_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; diff --git a/ext/native/thin3d/thin3d_vulkan.cpp b/ext/native/thin3d/thin3d_vulkan.cpp index 52252b0236..c91d9e7c3e 100644 --- a/ext/native/thin3d/thin3d_vulkan.cpp +++ b/ext/native/thin3d/thin3d_vulkan.cpp @@ -1196,6 +1196,8 @@ std::vector Thin3DVKContext::GetFeatureList() { AddFeature(features, "textureCompressionASTC_LDR", available.textureCompressionASTC_LDR, enabled.textureCompressionASTC_LDR); AddFeature(features, "shaderClipDistance", available.shaderClipDistance, enabled.shaderClipDistance); AddFeature(features, "shaderCullDistance", available.shaderCullDistance, enabled.shaderCullDistance); + AddFeature(features, "occlusionQueryPrecise", available.occlusionQueryPrecise, enabled.occlusionQueryPrecise); + AddFeature(features, "multiDrawIndirect", available.multiDrawIndirect, enabled.multiDrawIndirect); // Also list texture formats and their properties. for (int i = VK_FORMAT_BEGIN_RANGE; i <= VK_FORMAT_END_RANGE; i++) { From ca63cca9a27d9fa371c03401594f3fbbddf14acc Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 24 Jan 2016 11:22:06 +0100 Subject: [PATCH 047/116] WIP: Start work on getting the Vulkan code to compile for Android --- GPU/GPU.cpp | 2 ++ Windows/GPU/WindowsVulkanContext.cpp | 3 ++- android/jni/Android.mk | 2 ++ android/jni/Locals.mk | 1 + ext/native/thin3d/VulkanContext.cpp | 37 +++++++++++++++++++++------- ext/native/thin3d/VulkanContext.h | 25 +++++++++++++++---- 6 files changed, 55 insertions(+), 15 deletions(-) diff --git a/GPU/GPU.cpp b/GPU/GPU.cpp index 0c509df0c7..5365e7dd42 100644 --- a/GPU/GPU.cpp +++ b/GPU/GPU.cpp @@ -59,6 +59,8 @@ bool GPU_Init(GraphicsContext *ctx) { SetGPU(new DIRECTX9_GPU(ctx)); #endif break; + case GPU_DIRECTX11: + return nullptr; case GPU_VULKAN: SetGPU(new GPU_Vulkan(ctx)); break; diff --git a/Windows/GPU/WindowsVulkanContext.cpp b/Windows/GPU/WindowsVulkanContext.cpp index 1e36cff290..b6462aa651 100644 --- a/Windows/GPU/WindowsVulkanContext.cpp +++ b/Windows/GPU/WindowsVulkanContext.cpp @@ -163,7 +163,8 @@ bool WindowsVulkanContext::Init(HINSTANCE hInst, HWND hWnd, std::string *error_m int bits = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT; g_Vulkan->InitDebugMsgCallback(Vulkan_Dbg, bits, &g_LogOptions); } - g_Vulkan->InitObjects(hInst, hWnd, true); + g_Vulkan->InitSurfaceWin32(hInst, hWnd); + g_Vulkan->InitObjects(true); _CrtCheckMemory(); diff --git a/android/jni/Android.mk b/android/jni/Android.mk index 365b03b47f..32c9b991ee 100644 --- a/android/jni/Android.mk +++ b/android/jni/Android.mk @@ -209,6 +209,8 @@ EXEC_AND_LIB_FILES := \ $(SRC)/GPU/GLES/FragmentShaderGenerator.cpp.arm \ $(SRC)/GPU/GLES/FragmentTestCache.cpp.arm \ $(SRC)/GPU/GLES/TextureScaler.cpp \ + $(SRC)/GPU/Vulkan/FramebufferVulkan.cpp \ + $(SRC)/GPU/Vulkan/GPU_Vulkan.cpp \ $(SRC)/GPU/Null/NullGpu.cpp \ $(SRC)/GPU/Software/Clipper.cpp \ $(SRC)/GPU/Software/Lighting.cpp \ diff --git a/android/jni/Locals.mk b/android/jni/Locals.mk index 327f81c1b4..67c19581f7 100644 --- a/android/jni/Locals.mk +++ b/android/jni/Locals.mk @@ -8,6 +8,7 @@ LOCAL_CPPFLAGS := -fno-exceptions -std=gnu++11 -fno-rtti -Wno-reorder -Wno-liter LOCAL_C_INCLUDES := \ $(LOCAL_PATH)/../../Common \ $(LOCAL_PATH)/../.. \ + $(LOCAL_PATH)/../../ext \ $(LOCAL_PATH)/$(NATIVE)/base \ $(LOCAL_PATH)/$(NATIVE)/ext \ $(LOCAL_PATH)/$(NATIVE)/ext/libzip \ diff --git a/ext/native/thin3d/VulkanContext.cpp b/ext/native/thin3d/VulkanContext.cpp index 923ddfb857..4d47968627 100644 --- a/ext/native/thin3d/VulkanContext.cpp +++ b/ext/native/thin3d/VulkanContext.cpp @@ -323,8 +323,8 @@ void VulkanBeginCommandBuffer(VkCommandBuffer cmd) { assert(res == VK_SUCCESS); } -void VulkanContext::InitObjects(HINSTANCE hInstance, HWND hWnd, bool depthPresent) { - InitSurfaceAndQueue(hInstance, hWnd); +void VulkanContext::InitObjects(bool depthPresent) { + InitQueue(); InitCommandPool(); // Create frame data @@ -793,7 +793,8 @@ void VulkanContext::InitDepthStencilBuffer(VkCommandBuffer cmd) { assert(res == VK_SUCCESS); } -void VulkanContext::InitSurfaceAndQueue(HINSTANCE conn, HWND wnd) { +#ifdef _WIN32 +void VulkanContext::InitSurfaceWin32(HINSTANCE conn, HWND wnd) { connection = conn; window = wnd; @@ -804,20 +805,38 @@ void VulkanContext::InitSurfaceAndQueue(HINSTANCE conn, HWND wnd) { VkResult U_ASSERT_ONLY res; -#ifdef _WIN32 VkWin32SurfaceCreateInfoKHR win32; win32.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR; + win32.pNext = nullptr; win32.flags = 0; win32.hwnd = wnd; win32.hinstance = conn; res = vkCreateWin32SurfaceKHR(instance_, &win32, nullptr, &surface); -#else // _WIN32 - res = vkCreateXcbSurfaceKHR(instance_, info.connection, info.window, NULL, &info.surface); -#endif // _WIN32 - assert(res == VK_SUCCESS); +} +#elif defined(ANDROID) +void VulkanContext::InitSurfaceAndroid(ANativeWindow *native_window, int width, int height) { + connection = conn; + window = wnd; + VkResult U_ASSERT_ONLY res; + + VkAndroidSurfaceCreateInfoKHR android; + android.sType = VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR; + android.flags = 0; + android.window = native_window; + android.pNext = nullptr; + res = vkCreateAndroidSurfaceKHR(instance_, &android, nullptr, &surface); + + this->width = width; + this->height = height; + assert(res == VK_SUCCESS); +} + +#endif + +void VulkanContext::InitQueue() { // Iterate over each queue to learn whether it supports presenting: VkBool32* supportsPresent = new VkBool32[queue_count]; for (uint32_t i = 0; i < queue_count; i++) { @@ -863,7 +882,7 @@ void VulkanContext::InitSurfaceAndQueue(HINSTANCE conn, HWND wnd) { // Get the list of VkFormats that are supported: uint32_t formatCount; - res = fpGetPhysicalDeviceSurfaceFormatsKHR(physical_devices_[0], + VkResult res = fpGetPhysicalDeviceSurfaceFormatsKHR(physical_devices_[0], surface, &formatCount, NULL); assert(res == VK_SUCCESS); diff --git a/ext/native/thin3d/VulkanContext.h b/ext/native/thin3d/VulkanContext.h index 4588e57cd0..5d9d733359 100644 --- a/ext/native/thin3d/VulkanContext.h +++ b/ext/native/thin3d/VulkanContext.h @@ -36,7 +36,10 @@ #define NOMINMAX /* Don't let Windows define min() or max() */ #define APP_NAME_STR_LEN 80 #include -#else // _WIN32 +#elif defined(ANDROID) // _WIN32 +#include +#define VK_USE_PLATFORM_ANDROID_KHR +#else #define VK_USE_PLATFORM_XCB_KHR #include #endif // _WIN32 @@ -158,14 +161,22 @@ public: VkPipelineCache CreatePipelineCache(); - void InitSurfaceAndQueue(HINSTANCE conn, HWND wnd); +#ifdef _WIN32 + void InitSurfaceWin32(HINSTANCE conn, HWND wnd); +#elif ANDROID + void InitSurfaceAndroid(ANativeWindow *native_window, int width, int height); +#else + //void InitSurfaceAndQueueXcb(); +#error Vulkan not supported on this platform +#endif + void InitQueue(); + void InitObjects(bool depthPresent); void InitSwapchain(VkCommandBuffer cmd); void InitSurfaceRenderPass(bool include_depth, bool clear); void InitFramebuffers(bool include_depth); void InitDepthStencilBuffer(VkCommandBuffer cmd); void InitCommandPool(); - void InitObjects(HINSTANCE hInstance, HWND hWnd, bool depthPresent); void DestroyObjects(); void DestroySurfaceRenderPass(); @@ -244,7 +255,9 @@ private: #ifdef _WIN32 HINSTANCE connection; // hInstance - Windows Instance HWND window; // hWnd - window handle -#else // _WIN32 +#elif ANDROID // _WIN32 + ANativeWindow *native_window; +#else xcb_connection_t *connection; xcb_screen_t *screen; xcb_window_t window; @@ -295,7 +308,7 @@ private: // Manages flipping command buffers for the backbuffer render pass. // It is recommended to do the same for other rendering passes. struct FrameData { - FrameData() : fence(nullptr), hasInitCommands(false), cmdInit(nullptr), cmdBuf(nullptr) {} + FrameData() : hasInitCommands(false), cmdInit(nullptr), cmdBuf(nullptr) {} VkFence fence; bool hasInitCommands; @@ -462,7 +475,9 @@ public: offset_ += (numBytes + 3) & ~3; // Round up to 4 bytes. if (offset_ >= size_) { // For now. 4MB is not enough for God of War but lets start with smaller games :P +#ifdef _WIN32 DebugBreak(); +#endif } return out; } From 5f71b5b3ec251b90fcc4e34e5c59a571d49ed845 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 24 Jan 2016 12:19:04 +0100 Subject: [PATCH 048/116] Android: Vulkan builds but doesn't link as we have no link library. --- GPU/Vulkan/ShaderManagerVulkan.cpp | 2 ++ GPU/Vulkan/TextureCacheVulkan.cpp | 2 +- android/jni/Android.mk | 21 +++++++++++++++++++-- 3 files changed, 22 insertions(+), 3 deletions(-) diff --git a/GPU/Vulkan/ShaderManagerVulkan.cpp b/GPU/Vulkan/ShaderManagerVulkan.cpp index 0bf47a6743..36de452533 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.cpp +++ b/GPU/Vulkan/ShaderManagerVulkan.cpp @@ -60,9 +60,11 @@ VulkanFragmentShader::VulkanFragmentShader(VulkanContext *vulkan, ShaderID id, c } ERROR_LOG(G3D, "Messages: %s", errorMessage.c_str()); ERROR_LOG(G3D, "Shader source:\n%s", code); +#ifdef SHADERLOG OutputDebugStringA("Messages:\n"); OutputDebugStringA(errorMessage.c_str()); OutputDebugStringA(code); +#endif Reporting::ReportMessage("Vulkan error in shader compilation: info: %s / code: %s", errorMessage.c_str(), code); } else { success = vulkan_->CreateShaderModule(spirv, &module_); diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index c3f88db497..8bfc89f90e 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -1445,7 +1445,7 @@ void TextureCacheVulkan::SetTexture() { // Ready or not, here I go... if (replaceImages) { if (!entry->vkTex) { - DebugBreak(); + Crash(); } } else { entry->vkTex = new CachedTextureVulkan(); diff --git a/android/jni/Android.mk b/android/jni/Android.mk index 32c9b991ee..04ad94d17f 100644 --- a/android/jni/Android.mk +++ b/android/jni/Android.mk @@ -124,9 +124,28 @@ EGL_FILES := \ $(SRC)/Common/GL/GLInterface/EGLAndroid.cpp \ $(SRC)/Common/GL/GLInterface/GLInterface.cpp +# Only build Vulkan on ARM64 for now. +ifeq ($(TARGET_ARCH_ABI),arm64-v8a) +VULKAN_FILES := \ + $(SRC)/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp \ + $(SRC)/GPU/Vulkan/DrawEngineVulkan.cpp \ + $(SRC)/GPU/Vulkan/FramebufferVulkan.cpp \ + $(SRC)/GPU/Vulkan/GPU_Vulkan.cpp \ + $(SRC)/GPU/Vulkan/PipelineManagerVulkan.cpp \ + $(SRC)/GPU/Vulkan/ShaderManagerVulkan.cpp \ + $(SRC)/GPU/Vulkan/StateMappingVulkan.cpp \ + $(SRC)/GPU/Vulkan/TextureCacheVulkan.cpp \ + $(SRC)/GPU/Vulkan/TextureScalerVulkan.cpp \ + $(SRC)/GPU/Vulkan/DepalettizeShaderVulkan.cpp \ + $(SRC)/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp +else +VULKAN_FILES := +endif + EXEC_AND_LIB_FILES := \ $(ARCH_FILES) \ $(EGL_FILES) \ + $(VULKAN_FILES) \ TestRunner.cpp \ $(SRC)/Core/MIPS/MIPS.cpp.arm \ $(SRC)/Core/MIPS/MIPSAnalyst.cpp \ @@ -209,8 +228,6 @@ EXEC_AND_LIB_FILES := \ $(SRC)/GPU/GLES/FragmentShaderGenerator.cpp.arm \ $(SRC)/GPU/GLES/FragmentTestCache.cpp.arm \ $(SRC)/GPU/GLES/TextureScaler.cpp \ - $(SRC)/GPU/Vulkan/FramebufferVulkan.cpp \ - $(SRC)/GPU/Vulkan/GPU_Vulkan.cpp \ $(SRC)/GPU/Null/NullGpu.cpp \ $(SRC)/GPU/Software/Clipper.cpp \ $(SRC)/GPU/Software/Lighting.cpp \ From 1677697735393b761ba3e6620dad5939632e3424 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 24 Jan 2016 17:30:26 +0100 Subject: [PATCH 049/116] Vulkan: Don't try to overlap proj with proj_through, will need a different approach. Also, assorted bugfixes. --- GPU/Vulkan/DrawEngineVulkan.cpp | 13 +++++++++---- GPU/Vulkan/GPU_Vulkan.cpp | 2 +- GPU/Vulkan/PipelineManagerVulkan.cpp | 9 +++++---- GPU/Vulkan/PipelineManagerVulkan.h | 4 +++- GPU/Vulkan/ShaderManagerVulkan.cpp | 2 +- GPU/Vulkan/ShaderManagerVulkan.h | 7 +++++-- GPU/Vulkan/StateMappingVulkan.cpp | 4 ++-- GPU/Vulkan/StateMappingVulkan.h | 2 +- GPU/Vulkan/VertexShaderGeneratorVulkan.cpp | 2 +- 9 files changed, 28 insertions(+), 17 deletions(-) diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index 7a4edb7909..b0fcdd2bb2 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -494,6 +494,8 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { uint32_t vbOffset = 0; if (useHWTransform) { + // We don't detect clears in this path, so here we can switch framebuffers if necessary. + int vertexCount = 0; int maxIndex = 0; bool useElements = true; @@ -529,7 +531,7 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { vkCmdSetBlendConstants(cmd_, bc); shaderManager_->UpdateUniforms(); shaderManager_->GetShaders(prim, lastVType_, &vshader, &fshader, useHWTransform); - VulkanPipeline *pipeline = pipelineManager_->GetOrCreatePipeline(pipelineLayout_, pipelineKey, dec_, vshader->GetModule(), fshader->GetModule(), true); + VulkanPipeline *pipeline = pipelineManager_->GetOrCreatePipeline(pipelineLayout_, pipelineKey, dec_, vshader, fshader, true); vkCmdBindPipeline(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline->pipeline); // TODO: Avoid if same as last draw. if (pipeline->uniformBlocks & UB_VS_FS_BASE) { @@ -548,11 +550,11 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { }; vkCmdBindDescriptorSets(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout_, 0, 1, &ds, 3, dynamicUBOOffsets); - vbOffset = (uint32_t)frame->pushData->Push(decoded, vertexCount * dec_->GetDecVtxFmt().stride); + vbOffset = (uint32_t)frame->pushData->PushAligned(decoded, vertexCount * dec_->GetDecVtxFmt().stride, 16); VkDeviceSize offsets[1] = { vbOffset }; if (useElements) { - ibOffset = (uint32_t)frame->pushData->Push(decIndex, 2 * indexGen.VertexCount()); + ibOffset = (uint32_t)frame->pushData->PushAligned(decIndex, 2 * indexGen.VertexCount(), 16); // TODO: Avoid rebinding vertex/index buffers if the vertex size stays the same by using the offset arguments // Might want to separate vertices out into a different push buffer in that case. vkCmdBindVertexBuffers(cmd_, 0, 1, buf, offsets); @@ -591,6 +593,9 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { dec_->VertexType(), inds, GE_VTYPE_IDX_16BIT, dec_->GetDecVtxFmt(), maxIndex, framebufferManager_, textureCache_, transformed, transformedExpanded, drawBuffer, numTrans, drawIndexed, &result, 1.0f); + // Only here, where we know whether to clear or to draw primitives, should we actually set the current framebuffer! Because that gives use the opportunity + // to use a "pre-clear" render pass, for high efficiency on tilers. + if (result.action == SW_DRAW_PRIMITIVES) { VulkanPipelineRasterStateKey pipelineKey; VulkanDynamicState dynState; @@ -614,7 +619,7 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { vkCmdSetBlendConstants(cmd_, bc); shaderManager_->UpdateUniforms(); shaderManager_->GetShaders(prim, lastVType_, &vshader, &fshader, useHWTransform); - VulkanPipeline *pipeline = pipelineManager_->GetOrCreatePipeline(pipelineLayout_, pipelineKey, dec_, vshader->GetModule(), fshader->GetModule(), false); + VulkanPipeline *pipeline = pipelineManager_->GetOrCreatePipeline(pipelineLayout_, pipelineKey, dec_, vshader, fshader, false); vkCmdBindPipeline(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline->pipeline); // TODO: Avoid if same as last draw. if (pipeline->uniformBlocks & UB_VS_FS_BASE) { diff --git a/GPU/Vulkan/GPU_Vulkan.cpp b/GPU/Vulkan/GPU_Vulkan.cpp index b465cc357b..3fdf78ba9c 100644 --- a/GPU/Vulkan/GPU_Vulkan.cpp +++ b/GPU/Vulkan/GPU_Vulkan.cpp @@ -320,7 +320,7 @@ static const CommandTableEntry commandTable[] = { { GE_CMD_BOUNDINGBOX, FLAG_EXECUTE, 0, &GPU_Vulkan::Execute_BoundingBox }, // + FLUSHBEFORE when we implement... or not, do we need to? // Changing the vertex type requires us to flush. - { GE_CMD_VERTEXTYPE, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, DIRTY_PROJMATRIX, &GPU_Vulkan::Execute_VertexType }, + { GE_CMD_VERTEXTYPE, FLAG_FLUSHBEFOREONCHANGE | FLAG_EXECUTEONCHANGE, 0, &GPU_Vulkan::Execute_VertexType }, { GE_CMD_BEZIER, FLAG_FLUSHBEFORE | FLAG_EXECUTE, 0, &GPU_Vulkan::Execute_Bezier }, { GE_CMD_SPLINE, FLAG_FLUSHBEFORE | FLAG_EXECUTE, 0, &GPU_Vulkan::Execute_Spline }, diff --git a/GPU/Vulkan/PipelineManagerVulkan.cpp b/GPU/Vulkan/PipelineManagerVulkan.cpp index d704d172db..a092fb31d2 100644 --- a/GPU/Vulkan/PipelineManagerVulkan.cpp +++ b/GPU/Vulkan/PipelineManagerVulkan.cpp @@ -4,6 +4,7 @@ #include "Common/StringUtils.h" #include "GPU/Vulkan/VulkanUtil.h" #include "GPU/Vulkan/PipelineManagerVulkan.h" +#include "GPU/Vulkan/ShaderManagerVulkan.h" // #include "GPU/Vulkan/" #include "thin3d/VulkanContext.h" @@ -285,12 +286,12 @@ static VulkanPipeline *CreateVulkanPipeline(VkDevice device, VkPipelineCache pip return vulkanPipeline; } -VulkanPipeline *PipelineManagerVulkan::GetOrCreatePipeline(VkPipelineLayout layout, const VulkanPipelineRasterStateKey &rasterKey, const VertexDecoder *vtxDec, VkShaderModule vShader, VkShaderModule fShader, bool useHwTransform) { +VulkanPipeline *PipelineManagerVulkan::GetOrCreatePipeline(VkPipelineLayout layout, const VulkanPipelineRasterStateKey &rasterKey, const VertexDecoder *vtxDec, VulkanVertexShader *vs, VulkanFragmentShader *fs, bool useHwTransform) { VulkanPipelineKey key; key.raster = rasterKey; key.useHWTransform = useHwTransform; - key.vShader = vShader; - key.fShader = fShader; + key.vShader = vs->GetModule(); + key.fShader = fs->GetModule(); key.vtxDec = vtxDec; auto iter = pipelines_.find(key); if (iter != pipelines_.end()) { @@ -299,7 +300,7 @@ VulkanPipeline *PipelineManagerVulkan::GetOrCreatePipeline(VkPipelineLayout layo VulkanPipeline *pipeline = CreateVulkanPipeline( vulkan_->GetDevice(), pipelineCache_, layout, vulkan_->GetSurfaceRenderPass(), - rasterKey, vtxDec, vShader, fShader, useHwTransform); + rasterKey, vtxDec, key.vShader, key.fShader, useHwTransform); pipelines_[key] = pipeline; return pipeline; } diff --git a/GPU/Vulkan/PipelineManagerVulkan.h b/GPU/Vulkan/PipelineManagerVulkan.h index 951cd6f348..1d6bd6178d 100644 --- a/GPU/Vulkan/PipelineManagerVulkan.h +++ b/GPU/Vulkan/PipelineManagerVulkan.h @@ -74,13 +74,15 @@ struct VulkanPipeline { }; class VulkanContext; +class VulkanVertexShader; +class VulkanFragmentShader; class PipelineManagerVulkan { public: PipelineManagerVulkan(VulkanContext *ctx); ~PipelineManagerVulkan(); - VulkanPipeline *GetOrCreatePipeline(VkPipelineLayout layout, const VulkanPipelineRasterStateKey &rasterKey, const VertexDecoder *vtxDec, VkShaderModule vShader, VkShaderModule fShader, bool useHwTransform); + VulkanPipeline *GetOrCreatePipeline(VkPipelineLayout layout, const VulkanPipelineRasterStateKey &rasterKey, const VertexDecoder *vtxDec, VulkanVertexShader *vs, VulkanFragmentShader *fs, bool useHwTransform); int GetNumPipelines() const { return (int)pipelines_.size(); } void Clear(); diff --git a/GPU/Vulkan/ShaderManagerVulkan.cpp b/GPU/Vulkan/ShaderManagerVulkan.cpp index 36de452533..3a0230d53d 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.cpp +++ b/GPU/Vulkan/ShaderManagerVulkan.cpp @@ -249,7 +249,7 @@ void ShaderManagerVulkan::BaseUpdateUniforms(int dirtyUniforms) { Matrix4x4 proj_through; proj_through.setOrtho(0.0f, gstate_c.curRTWidth, 0, gstate_c.curRTHeight, 0, 1); ConvertProjMatrixToVulkanThrough(proj_through); - CopyMatrix4x4(ub_base.proj, proj_through.getReadPtr()); + CopyMatrix4x4(ub_base.proj_through, proj_through.getReadPtr()); } else { Matrix4x4 flippedMatrix; memcpy(&flippedMatrix, gstate.projMatrix, 16 * sizeof(float)); diff --git a/GPU/Vulkan/ShaderManagerVulkan.h b/GPU/Vulkan/ShaderManagerVulkan.h index 7c21609583..d374862c41 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.h +++ b/GPU/Vulkan/ShaderManagerVulkan.h @@ -34,7 +34,7 @@ void ConvertProjMatrixToVulkan(Matrix4x4 & in); // Pretty much full. Will need more bits for more fine grained dirty tracking for lights. enum { DIRTY_PROJMATRIX = (1 << 0), - // 1 << 1 is free + DIRTY_PROJTHROUGHMATRIX = (1 << 1), DIRTY_FOGCOLOR = (1 << 2), DIRTY_FOGCOEF = (1 << 3), DIRTY_TEXENV = (1 << 4), @@ -82,8 +82,10 @@ enum { DIRTY_ALL = 0xFFFFFFFF }; +// TODO: Split into two structs, one for software transform and one for hardware transform, to save space. struct UB_VS_FS_Base { float proj[16]; + float proj_through[16]; float view[16]; float world[16]; float tex[16]; // not that common, may want to break out @@ -104,7 +106,8 @@ struct UB_VS_FS_Base { }; static const char *ub_baseStr = -R"( mat4 proj_mtx; +R"( mat4 proj_mtx; + mat4 proj_through_mtx; mat4 view_mtx; mat4 world_mtx; mat4 tex_mtx; diff --git a/GPU/Vulkan/StateMappingVulkan.cpp b/GPU/Vulkan/StateMappingVulkan.cpp index 60e8a0bdac..0a095d6345 100644 --- a/GPU/Vulkan/StateMappingVulkan.cpp +++ b/GPU/Vulkan/StateMappingVulkan.cpp @@ -172,13 +172,13 @@ void ConvertStateToVulkanKey(FramebufferManagerVulkan &fbManager, ShaderManagerV key.depthCompareOp = VK_COMPARE_OP_ALWAYS; key.depthWriteEnable = gstate.isClearModeDepthMask(); if (gstate.isClearModeDepthMask()) { - // framebufferManager_->SetDepthUpdated(); + fbManager.SetDepthUpdated(); } // Color Test bool colorMask = gstate.isClearModeColorMask(); bool alphaMask = gstate.isClearModeAlphaMask(); - key.colorWriteMask = (colorMask ? (VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_A_BIT) : 0) | (alphaMask ? VK_COLOR_COMPONENT_A_BIT : 0); + key.colorWriteMask = (colorMask ? (VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT) : 0) | (alphaMask ? VK_COLOR_COMPONENT_A_BIT : 0); GenericStencilFuncState stencilState; ConvertStencilFuncState(stencilState); diff --git a/GPU/Vulkan/StateMappingVulkan.h b/GPU/Vulkan/StateMappingVulkan.h index f0ee8bd715..76495e5593 100644 --- a/GPU/Vulkan/StateMappingVulkan.h +++ b/GPU/Vulkan/StateMappingVulkan.h @@ -34,7 +34,7 @@ struct VulkanPipelineRasterStateKey { unsigned int blendOpAlpha : 3; // VkBlendOp bool logicOpEnable : 1; unsigned int logicOp : 4; // VkLogicOp - int colorWriteMask : 4; + unsigned int colorWriteMask : 4; // Depth/Stencil bool depthTestEnable : 1; diff --git a/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp b/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp index 0adf5d5ddd..749a512e36 100644 --- a/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp +++ b/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp @@ -242,7 +242,7 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { WRITE(p, " v_fogdepth = position.w;\n"); } if (isModeThrough) { - WRITE(p, " gl_Position = base.proj_mtx * vec4(position.xyz, 1.0);\n"); + WRITE(p, " gl_Position = base.proj_through_mtx * vec4(position.xyz, 1.0);\n"); } else { // The viewport is used in this case, so need to compensate for that. if (gstate_c.Supports(GPU_ROUND_DEPTH_TO_16BIT)) { From 432f276bec802d690e2766806776c635fe67ae01 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Mon, 25 Jan 2016 00:58:47 +0100 Subject: [PATCH 050/116] Cleanups. Don't loop over bones in vshader, causes trouble --- GPU/Vulkan/DrawEngineVulkan.cpp | 28 +++++++++++----------- GPU/Vulkan/StateMappingVulkan.h | 1 - GPU/Vulkan/VertexShaderGeneratorVulkan.cpp | 21 ++++------------ GPU/Vulkan/VulkanUtil.h | 1 - UI/NativeApp.cpp | 4 +++- ext/native/thin3d/VulkanContext.h | 2 +- 6 files changed, 22 insertions(+), 35 deletions(-) diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index b0fcdd2bb2..af495f53ff 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -141,10 +141,6 @@ DrawEngineVulkan::DrawEngineVulkan(VulkanContext *vulkan) dp.maxSets = 1000; dp.pPoolSizes = dpTypes; dp.poolSizeCount = ARRAY_SIZE(dpTypes); - res = vkCreateDescriptorPool(device, &dp, nullptr, &frame_[0].descPool); - assert(VK_SUCCESS == res); - res = vkCreateDescriptorPool(device, &dp, nullptr, &frame_[1].descPool); - assert(VK_SUCCESS == res); // We are going to use one-shot descriptors in the initial implementation. Might look into caching them // if creating and updating them turns out to be expensive. @@ -161,6 +157,7 @@ DrawEngineVulkan::DrawEngineVulkan(VulkanContext *vulkan) pl.pushConstantRangeCount = 0; pl.setLayoutCount = 1; pl.pSetLayouts = &descriptorSetLayout_; + pl.flags = 0; res = vkCreatePipelineLayout(device, &pl, nullptr, &pipelineLayout_); assert(VK_SUCCESS == res); @@ -406,7 +403,7 @@ VkDescriptorSet DrawEngineVulkan::GetDescriptorSet(VkImageView imageView, VkSamp assert(result == VK_SUCCESS); // We just don't write to the slots we don't care about. - VkWriteDescriptorSet writes[2]; + VkWriteDescriptorSet writes[4]; memset(writes, 0, sizeof(writes)); // Main texture int n = 0; @@ -437,14 +434,16 @@ VkDescriptorSet DrawEngineVulkan::GetDescriptorSet(VkImageView imageView, VkSamp buf[2].buffer = dynamicUbo; buf[2].offset = 0; buf[2].range = sizeof(UB_VS_Bones); - writes[n].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - writes[n].pNext = nullptr; - writes[n].dstBinding = DRAW_BINDING_DYNUBO_BASE; - writes[n].pBufferInfo = &buf[0]; - writes[n].dstSet = desc; - writes[n].descriptorCount = 3; - writes[n].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; - n++; + for (int i = 0; i < 3; i++) { + writes[n].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + writes[n].pNext = nullptr; + writes[n].dstBinding = DRAW_BINDING_DYNUBO_BASE + i; + writes[n].pBufferInfo = &buf[i]; + writes[n].dstSet = desc; + writes[n].descriptorCount = 1; + writes[n].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; + n++; + } vkUpdateDescriptorSets(vulkan_->GetDevice(), n, writes, 0, nullptr); @@ -550,7 +549,8 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { }; vkCmdBindDescriptorSets(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout_, 0, 1, &ds, 3, dynamicUBOOffsets); - vbOffset = (uint32_t)frame->pushData->PushAligned(decoded, vertexCount * dec_->GetDecVtxFmt().stride, 16); + int stride = dec_->GetDecVtxFmt().stride; + vbOffset = (uint32_t)frame->pushData->PushAligned(decoded, vertexCount * stride, 16); VkDeviceSize offsets[1] = { vbOffset }; if (useElements) { diff --git a/GPU/Vulkan/StateMappingVulkan.h b/GPU/Vulkan/StateMappingVulkan.h index 76495e5593..3275fc268b 100644 --- a/GPU/Vulkan/StateMappingVulkan.h +++ b/GPU/Vulkan/StateMappingVulkan.h @@ -1,6 +1,5 @@ #pragma once -#define VK_PROTOTYPES #include "ext/vulkan/vulkan.h" #include diff --git a/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp b/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp index 749a512e36..83ad78d3f9 100644 --- a/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp +++ b/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp @@ -269,24 +269,11 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { "w2.x", "w2.y", "w2.z", "w2.w", }; - // To loop through the weights, we unfortunately need to put them in a float array. - // GLSL ES sucks - no way to directly initialize an array! - switch (numBoneWeights) { - case 1: WRITE(p, " float w[1]; w[0] = w1;\n"); break; - case 2: WRITE(p, " float w[2]; w[0] = w1.x; w[1] = w1.y;\n"); break; - case 3: WRITE(p, " float w[3]; w[0] = w1.x; w[1] = w1.y; w[2] = w1.z;\n"); break; - case 4: WRITE(p, " float w[4]; w[0] = w1.x; w[1] = w1.y; w[2] = w1.z; w[3] = w1.w;\n"); break; - case 5: WRITE(p, " float w[5]; w[0] = w1.x; w[1] = w1.y; w[2] = w1.z; w[3] = w1.w; w[4] = w2;\n"); break; - case 6: WRITE(p, " float w[6]; w[0] = w1.x; w[1] = w1.y; w[2] = w1.z; w[3] = w1.w; w[4] = w2.x; w[5] = w2.y;\n"); break; - case 7: WRITE(p, " float w[7]; w[0] = w1.x; w[1] = w1.y; w[2] = w1.z; w[3] = w1.w; w[4] = w2.x; w[5] = w2.y; w[6] = w2.z;\n"); break; - case 8: WRITE(p, " float w[8]; w[0] = w1.x; w[1] = w1.y; w[2] = w1.z; w[3] = w1.w; w[4] = w2.x; w[5] = w2.y; w[6] = w2.z; w[7] = w2.w;\n"); break; - } - - WRITE(p, " mat4 skinMatrix = w[0] * bone.m[0];\n"); + WRITE(p, " mat4 skinMatrix = w1.x * bone.m[0];\n"); if (numBoneWeights > 1) { - WRITE(p, " for (int i = 1; i < %i; i++) {\n", numBoneWeights); - WRITE(p, " skinMatrix += w[i] * bone.m[i];\n"); - WRITE(p, " }\n"); + for (int i = 1; i < numBoneWeights; i++) { + WRITE(p, " skinMatrix += %s * bone.m[%i];\n", boneWeightAttr[i], i); + } } WRITE(p, ";\n"); diff --git a/GPU/Vulkan/VulkanUtil.h b/GPU/Vulkan/VulkanUtil.h index 4899ff2b3a..f0c8496d91 100644 --- a/GPU/Vulkan/VulkanUtil.h +++ b/GPU/Vulkan/VulkanUtil.h @@ -1,5 +1,4 @@ #pragma once -#define VK_PROTOTYPES #include "ext/vulkan/vulkan.h" diff --git a/UI/NativeApp.cpp b/UI/NativeApp.cpp index a0cea8fc27..90d5044df5 100644 --- a/UI/NativeApp.cpp +++ b/UI/NativeApp.cpp @@ -722,7 +722,9 @@ void NativeRender(GraphicsContext *graphicsContext) { screenManager->getUIContext()->Text()->OncePerFrame(); } - DrawDownloadsOverlay(*screenManager->getUIContext()); + // At this point, the vulkan context has been "ended" already, no more drawing can be done in this frame. + // TODO: Integrate the download overlay with the screen system + // DrawDownloadsOverlay(*screenManager->getUIContext()); if (g_TakeScreenshot) { TakeScreenshot(); diff --git a/ext/native/thin3d/VulkanContext.h b/ext/native/thin3d/VulkanContext.h index 5d9d733359..c721ac4925 100644 --- a/ext/native/thin3d/VulkanContext.h +++ b/ext/native/thin3d/VulkanContext.h @@ -474,7 +474,7 @@ public: size_t out = offset_; offset_ += (numBytes + 3) & ~3; // Round up to 4 bytes. if (offset_ >= size_) { - // For now. 4MB is not enough for God of War but lets start with smaller games :P + // TODO: Allocate a second buffer, then combine them on the next frame. #ifdef _WIN32 DebugBreak(); #endif From 5a72564583da6edd01ce7621e897f4f32c09a1cb Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Thu, 28 Jan 2016 23:44:05 +0100 Subject: [PATCH 051/116] Cleanup --- GPU/Vulkan/PipelineManagerVulkan.cpp | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/GPU/Vulkan/PipelineManagerVulkan.cpp b/GPU/Vulkan/PipelineManagerVulkan.cpp index a092fb31d2..155a65be91 100644 --- a/GPU/Vulkan/PipelineManagerVulkan.cpp +++ b/GPU/Vulkan/PipelineManagerVulkan.cpp @@ -98,7 +98,7 @@ int SetupVertexAttribsPretransformed(VkVertexInputAttributeDescription attrs[]) return 4; } -static VulkanPipeline *CreateVulkanPipeline(VkDevice device, VkPipelineCache pipelineCache, VkPipelineLayout layout, VkRenderPass renderPass, const VulkanPipelineRasterStateKey &key, const VertexDecoder *vtxDec, VkShaderModule vshader, VkShaderModule fshader, bool useHwTransform) { +static VulkanPipeline *CreateVulkanPipeline(VkDevice device, VkPipelineCache pipelineCache, VkPipelineLayout layout, VkRenderPass renderPass, const VulkanPipelineRasterStateKey &key, const VertexDecoder *vtxDec, VulkanVertexShader *vs, VulkanFragmentShader *fs, bool useHwTransform) { VkPipelineColorBlendAttachmentState blend0; blend0.blendEnable = key.blendEnable; if (key.blendEnable) { @@ -186,14 +186,14 @@ static VulkanPipeline *CreateVulkanPipeline(VkDevice device, VkPipelineCache pip ss[0].pNext = nullptr; ss[0].stage = VK_SHADER_STAGE_VERTEX_BIT; ss[0].pSpecializationInfo = nullptr; - ss[0].module = vshader; + ss[0].module = vs->GetModule(); ss[0].pName = "main"; ss[0].flags = 0; ss[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; ss[1].pNext = nullptr; ss[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; ss[1].pSpecializationInfo = nullptr; - ss[1].module = fshader; + ss[1].module = fs->GetModule(); ss[1].pName = "main"; ss[1].flags = 0; @@ -231,14 +231,14 @@ static VulkanPipeline *CreateVulkanPipeline(VkDevice device, VkPipelineCache pip vis.vertexAttributeDescriptionCount = attributeCount; vis.pVertexAttributeDescriptions = attrs; - VkPipelineViewportStateCreateInfo vs; - vs.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; - vs.pNext = nullptr; - vs.flags = 0; - vs.viewportCount = 1; - vs.scissorCount = 1; - vs.pViewports = nullptr; // dynamic - vs.pScissors = nullptr; // dynamic + VkPipelineViewportStateCreateInfo views; + views.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; + views.pNext = nullptr; + views.flags = 0; + views.viewportCount = 1; + views.scissorCount = 1; + views.pViewports = nullptr; // dynamic + views.pScissors = nullptr; // dynamic VkGraphicsPipelineCreateInfo pipe; pipe.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; @@ -258,7 +258,7 @@ static VulkanPipeline *CreateVulkanPipeline(VkDevice device, VkPipelineCache pip // We will use dynamic viewport state. pipe.pVertexInputState = &vis; - pipe.pViewportState = &vs; + pipe.pViewportState = &views; pipe.pTessellationState = nullptr; pipe.pDynamicState = &ds; pipe.pInputAssemblyState = &inputAssembly; @@ -300,7 +300,7 @@ VulkanPipeline *PipelineManagerVulkan::GetOrCreatePipeline(VkPipelineLayout layo VulkanPipeline *pipeline = CreateVulkanPipeline( vulkan_->GetDevice(), pipelineCache_, layout, vulkan_->GetSurfaceRenderPass(), - rasterKey, vtxDec, key.vShader, key.fShader, useHwTransform); + rasterKey, vtxDec, vs, fs, useHwTransform); pipelines_[key] = pipeline; return pipeline; } From 2481714a8e35b7fae0ca799d64edbd4beacf2297 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 21 Feb 2016 18:05:01 +0100 Subject: [PATCH 052/116] Load Vulkan dynamically. Fix Android build (though - Vulkan is not working on Android yet) --- Common/Common.vcxproj | 4 +- Common/Common.vcxproj.filters | 8 +- Common/Vulkan/VulkanLoader.cpp | 393 +++++++++++++++++++++ Common/Vulkan/VulkanLoader.h | 198 +++++++++++ GPU/Vulkan/DrawEngineVulkan.cpp | 10 +- GPU/Vulkan/FramebufferVulkan.cpp | 2 - GPU/Vulkan/FramebufferVulkan.h | 2 +- GPU/Vulkan/PipelineManagerVulkan.cpp | 8 +- GPU/Vulkan/ShaderManagerVulkan.cpp | 16 +- GPU/Vulkan/StateMappingVulkan.cpp | 3 +- GPU/Vulkan/StateMappingVulkan.h | 2 +- GPU/Vulkan/TextureCacheVulkan.cpp | 6 +- GPU/Vulkan/VertexShaderGeneratorVulkan.cpp | 1 + GPU/Vulkan/VulkanUtil.h | 2 +- Windows/GPU/WindowsVulkanContext.cpp | 2 +- android/jni/Android.mk | 8 +- android/jni/Locals.mk | 2 +- ext/native/Android.mk | 4 +- ext/native/thin3d/VulkanContext.cpp | 175 ++++----- ext/native/thin3d/VulkanContext.h | 51 +-- ext/native/thin3d/thin3d_vulkan.cpp | 7 +- 21 files changed, 733 insertions(+), 171 deletions(-) create mode 100644 Common/Vulkan/VulkanLoader.cpp create mode 100644 Common/Vulkan/VulkanLoader.h diff --git a/Common/Common.vcxproj b/Common/Common.vcxproj index c8fc1adc26..59f1e261fc 100644 --- a/Common/Common.vcxproj +++ b/Common/Common.vcxproj @@ -241,6 +241,7 @@ + @@ -310,6 +311,7 @@ + @@ -324,4 +326,4 @@ - + \ No newline at end of file diff --git a/Common/Common.vcxproj.filters b/Common/Common.vcxproj.filters index 62356cf7e1..8f32f6e506 100644 --- a/Common/Common.vcxproj.filters +++ b/Common/Common.vcxproj.filters @@ -61,6 +61,9 @@ Vulkan + + Vulkan + @@ -109,6 +112,9 @@ Vulkan + + Vulkan + @@ -127,4 +133,4 @@ {c14d66ef-5f7c-4565-975a-72774e7ccfb9} - + \ No newline at end of file diff --git a/Common/Vulkan/VulkanLoader.cpp b/Common/Vulkan/VulkanLoader.cpp new file mode 100644 index 0000000000..7b6b143510 --- /dev/null +++ b/Common/Vulkan/VulkanLoader.cpp @@ -0,0 +1,393 @@ +// Copyright (c) 2016- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#include "Common/Vulkan/VulkanLoader.h" + +#ifndef _WIN32 +#include +#endif + + +PFN_vkCreateInstance vkCreateInstance; +PFN_vkDestroyInstance vkDestroyInstance; +PFN_vkEnumeratePhysicalDevices vkEnumeratePhysicalDevices; +PFN_vkGetPhysicalDeviceFeatures vkGetPhysicalDeviceFeatures; +PFN_vkGetPhysicalDeviceFormatProperties vkGetPhysicalDeviceFormatProperties; +PFN_vkGetPhysicalDeviceImageFormatProperties vkGetPhysicalDeviceImageFormatProperties; +PFN_vkGetPhysicalDeviceProperties vkGetPhysicalDeviceProperties; +PFN_vkGetPhysicalDeviceQueueFamilyProperties vkGetPhysicalDeviceQueueFamilyProperties; +PFN_vkGetPhysicalDeviceMemoryProperties vkGetPhysicalDeviceMemoryProperties; +PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr; +PFN_vkGetDeviceProcAddr vkGetDeviceProcAddr; +PFN_vkCreateDevice vkCreateDevice; +PFN_vkDestroyDevice vkDestroyDevice; +PFN_vkEnumerateInstanceExtensionProperties vkEnumerateInstanceExtensionProperties; +PFN_vkEnumerateDeviceExtensionProperties vkEnumerateDeviceExtensionProperties; +PFN_vkEnumerateInstanceLayerProperties vkEnumerateInstanceLayerProperties; +PFN_vkEnumerateDeviceLayerProperties vkEnumerateDeviceLayerProperties; +PFN_vkGetDeviceQueue vkGetDeviceQueue; +PFN_vkQueueSubmit vkQueueSubmit; +PFN_vkQueueWaitIdle vkQueueWaitIdle; +PFN_vkDeviceWaitIdle vkDeviceWaitIdle; +PFN_vkAllocateMemory vkAllocateMemory; +PFN_vkFreeMemory vkFreeMemory; +PFN_vkMapMemory vkMapMemory; +PFN_vkUnmapMemory vkUnmapMemory; +PFN_vkFlushMappedMemoryRanges vkFlushMappedMemoryRanges; +PFN_vkInvalidateMappedMemoryRanges vkInvalidateMappedMemoryRanges; +PFN_vkGetDeviceMemoryCommitment vkGetDeviceMemoryCommitment; +PFN_vkBindBufferMemory vkBindBufferMemory; +PFN_vkBindImageMemory vkBindImageMemory; +PFN_vkGetBufferMemoryRequirements vkGetBufferMemoryRequirements; +PFN_vkGetImageMemoryRequirements vkGetImageMemoryRequirements; +PFN_vkGetImageSparseMemoryRequirements vkGetImageSparseMemoryRequirements; +PFN_vkGetPhysicalDeviceSparseImageFormatProperties vkGetPhysicalDeviceSparseImageFormatProperties; +PFN_vkQueueBindSparse vkQueueBindSparse; +PFN_vkCreateFence vkCreateFence; +PFN_vkDestroyFence vkDestroyFence; +PFN_vkResetFences vkResetFences; +PFN_vkGetFenceStatus vkGetFenceStatus; +PFN_vkWaitForFences vkWaitForFences; +PFN_vkCreateSemaphore vkCreateSemaphore; +PFN_vkDestroySemaphore vkDestroySemaphore; +PFN_vkCreateEvent vkCreateEvent; +PFN_vkDestroyEvent vkDestroyEvent; +PFN_vkGetEventStatus vkGetEventStatus; +PFN_vkSetEvent vkSetEvent; +PFN_vkResetEvent vkResetEvent; +PFN_vkCreateQueryPool vkCreateQueryPool; +PFN_vkDestroyQueryPool vkDestroyQueryPool; +PFN_vkGetQueryPoolResults vkGetQueryPoolResults; +PFN_vkCreateBuffer vkCreateBuffer; +PFN_vkDestroyBuffer vkDestroyBuffer; +PFN_vkCreateBufferView vkCreateBufferView; +PFN_vkDestroyBufferView vkDestroyBufferView; +PFN_vkCreateImage vkCreateImage; +PFN_vkDestroyImage vkDestroyImage; +PFN_vkGetImageSubresourceLayout vkGetImageSubresourceLayout; +PFN_vkCreateImageView vkCreateImageView; +PFN_vkDestroyImageView vkDestroyImageView; +PFN_vkCreateShaderModule vkCreateShaderModule; +PFN_vkDestroyShaderModule vkDestroyShaderModule; +PFN_vkCreatePipelineCache vkCreatePipelineCache; +PFN_vkDestroyPipelineCache vkDestroyPipelineCache; +PFN_vkGetPipelineCacheData vkGetPipelineCacheData; +PFN_vkMergePipelineCaches vkMergePipelineCaches; +PFN_vkCreateGraphicsPipelines vkCreateGraphicsPipelines; +PFN_vkCreateComputePipelines vkCreateComputePipelines; +PFN_vkDestroyPipeline vkDestroyPipeline; +PFN_vkCreatePipelineLayout vkCreatePipelineLayout; +PFN_vkDestroyPipelineLayout vkDestroyPipelineLayout; +PFN_vkCreateSampler vkCreateSampler; +PFN_vkDestroySampler vkDestroySampler; +PFN_vkCreateDescriptorSetLayout vkCreateDescriptorSetLayout; +PFN_vkDestroyDescriptorSetLayout vkDestroyDescriptorSetLayout; +PFN_vkCreateDescriptorPool vkCreateDescriptorPool; +PFN_vkDestroyDescriptorPool vkDestroyDescriptorPool; +PFN_vkResetDescriptorPool vkResetDescriptorPool; +PFN_vkAllocateDescriptorSets vkAllocateDescriptorSets; +PFN_vkFreeDescriptorSets vkFreeDescriptorSets; +PFN_vkUpdateDescriptorSets vkUpdateDescriptorSets; +PFN_vkCreateFramebuffer vkCreateFramebuffer; +PFN_vkDestroyFramebuffer vkDestroyFramebuffer; +PFN_vkCreateRenderPass vkCreateRenderPass; +PFN_vkDestroyRenderPass vkDestroyRenderPass; +PFN_vkGetRenderAreaGranularity vkGetRenderAreaGranularity; +PFN_vkCreateCommandPool vkCreateCommandPool; +PFN_vkDestroyCommandPool vkDestroyCommandPool; +PFN_vkResetCommandPool vkResetCommandPool; +PFN_vkAllocateCommandBuffers vkAllocateCommandBuffers; +PFN_vkFreeCommandBuffers vkFreeCommandBuffers; +PFN_vkBeginCommandBuffer vkBeginCommandBuffer; +PFN_vkEndCommandBuffer vkEndCommandBuffer; +PFN_vkResetCommandBuffer vkResetCommandBuffer; +PFN_vkCmdBindPipeline vkCmdBindPipeline; +PFN_vkCmdSetViewport vkCmdSetViewport; +PFN_vkCmdSetScissor vkCmdSetScissor; +PFN_vkCmdSetLineWidth vkCmdSetLineWidth; +PFN_vkCmdSetDepthBias vkCmdSetDepthBias; +PFN_vkCmdSetBlendConstants vkCmdSetBlendConstants; +PFN_vkCmdSetDepthBounds vkCmdSetDepthBounds; +PFN_vkCmdSetStencilCompareMask vkCmdSetStencilCompareMask; +PFN_vkCmdSetStencilWriteMask vkCmdSetStencilWriteMask; +PFN_vkCmdSetStencilReference vkCmdSetStencilReference; +PFN_vkCmdBindDescriptorSets vkCmdBindDescriptorSets; +PFN_vkCmdBindIndexBuffer vkCmdBindIndexBuffer; +PFN_vkCmdBindVertexBuffers vkCmdBindVertexBuffers; +PFN_vkCmdDraw vkCmdDraw; +PFN_vkCmdDrawIndexed vkCmdDrawIndexed; +PFN_vkCmdDrawIndirect vkCmdDrawIndirect; +PFN_vkCmdDrawIndexedIndirect vkCmdDrawIndexedIndirect; +PFN_vkCmdDispatch vkCmdDispatch; +PFN_vkCmdDispatchIndirect vkCmdDispatchIndirect; +PFN_vkCmdCopyBuffer vkCmdCopyBuffer; +PFN_vkCmdCopyImage vkCmdCopyImage; +PFN_vkCmdBlitImage vkCmdBlitImage; +PFN_vkCmdCopyBufferToImage vkCmdCopyBufferToImage; +PFN_vkCmdCopyImageToBuffer vkCmdCopyImageToBuffer; +PFN_vkCmdUpdateBuffer vkCmdUpdateBuffer; +PFN_vkCmdFillBuffer vkCmdFillBuffer; +PFN_vkCmdClearColorImage vkCmdClearColorImage; +PFN_vkCmdClearDepthStencilImage vkCmdClearDepthStencilImage; +PFN_vkCmdClearAttachments vkCmdClearAttachments; +PFN_vkCmdResolveImage vkCmdResolveImage; +PFN_vkCmdSetEvent vkCmdSetEvent; +PFN_vkCmdResetEvent vkCmdResetEvent; +PFN_vkCmdWaitEvents vkCmdWaitEvents; +PFN_vkCmdPipelineBarrier vkCmdPipelineBarrier; +PFN_vkCmdBeginQuery vkCmdBeginQuery; +PFN_vkCmdEndQuery vkCmdEndQuery; +PFN_vkCmdResetQueryPool vkCmdResetQueryPool; +PFN_vkCmdWriteTimestamp vkCmdWriteTimestamp; +PFN_vkCmdCopyQueryPoolResults vkCmdCopyQueryPoolResults; +PFN_vkCmdPushConstants vkCmdPushConstants; +PFN_vkCmdBeginRenderPass vkCmdBeginRenderPass; +PFN_vkCmdNextSubpass vkCmdNextSubpass; +PFN_vkCmdEndRenderPass vkCmdEndRenderPass; +PFN_vkCmdExecuteCommands vkCmdExecuteCommands; + +#ifdef ANDROID +PFN_vkCreateAndroidSurfaceKHR vkCreateAndroidSurfaceKHR; +#elif defined(_WIN32) +PFN_vkCreateWin32SurfaceKHR vkCreateWin32SurfaceKHR; +#endif + +PFN_vkDestroySurfaceKHR vkDestroySurfaceKHR; + +// WSI extension. +PFN_vkGetPhysicalDeviceSurfaceSupportKHR vkGetPhysicalDeviceSurfaceSupportKHR; +PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR vkGetPhysicalDeviceSurfaceCapabilitiesKHR; +PFN_vkGetPhysicalDeviceSurfaceFormatsKHR vkGetPhysicalDeviceSurfaceFormatsKHR; +PFN_vkGetPhysicalDeviceSurfacePresentModesKHR vkGetPhysicalDeviceSurfacePresentModesKHR; +PFN_vkCreateSwapchainKHR vkCreateSwapchainKHR; +PFN_vkDestroySwapchainKHR vkDestroySwapchainKHR; +PFN_vkGetSwapchainImagesKHR vkGetSwapchainImagesKHR; +PFN_vkAcquireNextImageKHR vkAcquireNextImageKHR; +PFN_vkQueuePresentKHR vkQueuePresentKHR; + +// And the DEBUG_REPORT extension. +PFN_vkCreateDebugReportCallbackEXT vkCreateDebugReportCallbackEXT; +PFN_vkDestroyDebugReportCallbackEXT vkDestroyDebugReportCallbackEXT; + +#ifdef _WIN32 +static HINSTANCE vulkanLibrary; +#define dlsym(x, y) GetProcAddress(x, y) +#else +static void *vulkanLibrary; +#endif + +bool VulkanLoad() { + +#ifndef _WIN32 + vulkanLibrary = dlopen("libvulkan.sh", RTLD_NOW | RTLD_LOCAL); + if (!vulkanLibrary) { + return false; + } +#else + // LoadLibrary etc + vulkanLibrary = LoadLibrary(L"vulkan-1.dll"); +#endif + + vkCreateInstance = (PFN_vkCreateInstance)dlsym(vulkanLibrary, "vkCreateInstance"); + vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)dlsym(vulkanLibrary, "vkGetInstanceProcAddr"); + vkGetDeviceProcAddr = (PFN_vkGetDeviceProcAddr)dlsym(vulkanLibrary, "vkGetDeviceProcAddr"); + + // Why do we need to load these separately? + vkEnumerateInstanceExtensionProperties = (PFN_vkEnumerateInstanceExtensionProperties)dlsym(vulkanLibrary, "vkEnumerateInstanceExtensionProperties"); + vkEnumerateInstanceLayerProperties = (PFN_vkEnumerateInstanceLayerProperties)dlsym(vulkanLibrary, "vkEnumerateInstanceLayerProperties"); + return true; +} + +void VulkanLoadInstanceFunctions(VkInstance instance) { + // OK, let's use the above functions to get the rest. + vkDestroyInstance = (PFN_vkDestroyInstance)vkGetInstanceProcAddr(instance, "vkDestroyInstance"); + vkEnumeratePhysicalDevices = (PFN_vkEnumeratePhysicalDevices)vkGetInstanceProcAddr(instance, "vkEnumeratePhysicalDevices"); + vkGetPhysicalDeviceFeatures = (PFN_vkGetPhysicalDeviceFeatures)vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceFeatures"); + vkGetPhysicalDeviceFormatProperties = (PFN_vkGetPhysicalDeviceFormatProperties)vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceFormatProperties"); + vkGetPhysicalDeviceImageFormatProperties = (PFN_vkGetPhysicalDeviceImageFormatProperties)vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceImageFormatProperties"); + vkGetPhysicalDeviceProperties = (PFN_vkGetPhysicalDeviceProperties)vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceProperties"); + vkGetPhysicalDeviceQueueFamilyProperties = (PFN_vkGetPhysicalDeviceQueueFamilyProperties)vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceQueueFamilyProperties"); + vkGetPhysicalDeviceMemoryProperties = (PFN_vkGetPhysicalDeviceMemoryProperties)vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceMemoryProperties"); + vkCreateDevice = (PFN_vkCreateDevice)vkGetInstanceProcAddr(instance, "vkCreateDevice"); + vkDestroyDevice = (PFN_vkDestroyDevice)vkGetInstanceProcAddr(instance, "vkDestroyDevice"); + vkEnumerateDeviceExtensionProperties = (PFN_vkEnumerateDeviceExtensionProperties)vkGetInstanceProcAddr(instance, "vkEnumerateDeviceExtensionProperties"); + vkEnumerateDeviceLayerProperties = (PFN_vkEnumerateDeviceLayerProperties)vkGetInstanceProcAddr(instance, "vkEnumerateDeviceLayerProperties"); + vkGetDeviceQueue = (PFN_vkGetDeviceQueue)vkGetInstanceProcAddr(instance, "vkGetDeviceQueue"); + vkQueueSubmit = (PFN_vkQueueSubmit)vkGetInstanceProcAddr(instance, "vkQueueSubmit"); + vkQueueWaitIdle = (PFN_vkQueueWaitIdle)vkGetInstanceProcAddr(instance, "vkQueueWaitIdle"); + vkDeviceWaitIdle = (PFN_vkDeviceWaitIdle)vkGetInstanceProcAddr(instance, "vkDeviceWaitIdle"); + vkAllocateMemory = (PFN_vkAllocateMemory)vkGetInstanceProcAddr(instance, "vkAllocateMemory"); + vkFreeMemory = (PFN_vkFreeMemory)vkGetInstanceProcAddr(instance, "vkFreeMemory"); + vkMapMemory = (PFN_vkMapMemory)vkGetInstanceProcAddr(instance, "vkMapMemory"); + vkUnmapMemory = (PFN_vkUnmapMemory)vkGetInstanceProcAddr(instance, "vkUnmapMemory"); + vkFlushMappedMemoryRanges = (PFN_vkFlushMappedMemoryRanges)vkGetInstanceProcAddr(instance, "vkFlushMappedMemoryRanges"); + vkInvalidateMappedMemoryRanges = (PFN_vkInvalidateMappedMemoryRanges)vkGetInstanceProcAddr(instance, "vkInvalidateMappedMemoryRanges"); + vkGetDeviceMemoryCommitment = (PFN_vkGetDeviceMemoryCommitment)vkGetInstanceProcAddr(instance, "vkGetDeviceMemoryCommitment"); + vkBindBufferMemory = (PFN_vkBindBufferMemory)vkGetInstanceProcAddr(instance, "vkBindBufferMemory"); + vkBindImageMemory = (PFN_vkBindImageMemory)vkGetInstanceProcAddr(instance, "vkBindImageMemory"); + vkGetBufferMemoryRequirements = (PFN_vkGetBufferMemoryRequirements)vkGetInstanceProcAddr(instance, "vkGetBufferMemoryRequirements"); + vkGetImageMemoryRequirements = (PFN_vkGetImageMemoryRequirements)vkGetInstanceProcAddr(instance, "vkGetImageMemoryRequirements"); + vkGetImageSparseMemoryRequirements = (PFN_vkGetImageSparseMemoryRequirements)vkGetInstanceProcAddr(instance, "vkGetImageSparseMemoryRequirements"); + vkGetPhysicalDeviceSparseImageFormatProperties = (PFN_vkGetPhysicalDeviceSparseImageFormatProperties)vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceSparseImageFormatProperties"); + vkQueueBindSparse = (PFN_vkQueueBindSparse)vkGetInstanceProcAddr(instance, "vkQueueBindSparse"); + vkCreateFence = (PFN_vkCreateFence)vkGetInstanceProcAddr(instance, "vkCreateFence"); + vkDestroyFence = (PFN_vkDestroyFence)vkGetInstanceProcAddr(instance, "vkDestroyFence"); + vkResetFences = (PFN_vkResetFences)vkGetInstanceProcAddr(instance, "vkResetFences"); + vkGetFenceStatus = (PFN_vkGetFenceStatus)vkGetInstanceProcAddr(instance, "vkGetFenceStatus"); + vkWaitForFences = (PFN_vkWaitForFences)vkGetInstanceProcAddr(instance, "vkWaitForFences"); + vkCreateSemaphore = (PFN_vkCreateSemaphore)vkGetInstanceProcAddr(instance, "vkCreateSemaphore"); + vkDestroySemaphore = (PFN_vkDestroySemaphore)vkGetInstanceProcAddr(instance, "vkDestroySemaphore"); + vkCreateEvent = (PFN_vkCreateEvent)vkGetInstanceProcAddr(instance, "vkCreateEvent"); + vkDestroyEvent = (PFN_vkDestroyEvent)vkGetInstanceProcAddr(instance, "vkDestroyEvent"); + vkGetEventStatus = (PFN_vkGetEventStatus)vkGetInstanceProcAddr(instance, "vkGetEventStatus"); + vkSetEvent = (PFN_vkSetEvent)vkGetInstanceProcAddr(instance, "vkSetEvent"); + vkResetEvent = (PFN_vkResetEvent)vkGetInstanceProcAddr(instance, "vkResetEvent"); + vkCreateQueryPool = (PFN_vkCreateQueryPool)vkGetInstanceProcAddr(instance, "vkCreateQueryPool"); + vkDestroyQueryPool = (PFN_vkDestroyQueryPool)vkGetInstanceProcAddr(instance, "vkDestroyQueryPool"); + vkGetQueryPoolResults = (PFN_vkGetQueryPoolResults)vkGetInstanceProcAddr(instance, "vkGetQueryPoolResults"); + vkCreateBuffer = (PFN_vkCreateBuffer)vkGetInstanceProcAddr(instance, "vkCreateBuffer"); + vkDestroyBuffer = (PFN_vkDestroyBuffer)vkGetInstanceProcAddr(instance, "vkDestroyBuffer"); + vkCreateBufferView = (PFN_vkCreateBufferView)vkGetInstanceProcAddr(instance, "vkCreateBufferView"); + vkDestroyBufferView = (PFN_vkDestroyBufferView)vkGetInstanceProcAddr(instance, "vkDestroyBufferView"); + vkCreateImage = (PFN_vkCreateImage)vkGetInstanceProcAddr(instance, "vkCreateImage"); + vkDestroyImage = (PFN_vkDestroyImage)vkGetInstanceProcAddr(instance, "vkDestroyImage"); + vkGetImageSubresourceLayout = (PFN_vkGetImageSubresourceLayout)vkGetInstanceProcAddr(instance, "vkGetImageSubresourceLayout"); + vkCreateImageView = (PFN_vkCreateImageView)vkGetInstanceProcAddr(instance, "vkCreateImageView"); + vkDestroyImageView = (PFN_vkDestroyImageView)vkGetInstanceProcAddr(instance, "vkDestroyImageView"); + vkCreateShaderModule = (PFN_vkCreateShaderModule)vkGetInstanceProcAddr(instance, "vkCreateShaderModule"); + vkDestroyShaderModule = (PFN_vkDestroyShaderModule)vkGetInstanceProcAddr(instance, "vkDestroyShaderModule"); + vkCreatePipelineCache = (PFN_vkCreatePipelineCache)vkGetInstanceProcAddr(instance, "vkCreatePipelineCache"); + vkDestroyPipelineCache = (PFN_vkDestroyPipelineCache)vkGetInstanceProcAddr(instance, "vkDestroyPipelineCache"); + vkGetPipelineCacheData = (PFN_vkGetPipelineCacheData)vkGetInstanceProcAddr(instance, "vkGetPipelineCacheData"); + vkMergePipelineCaches = (PFN_vkMergePipelineCaches)vkGetInstanceProcAddr(instance, "vkMergePipelineCaches"); + vkCreateGraphicsPipelines = (PFN_vkCreateGraphicsPipelines)vkGetInstanceProcAddr(instance, "vkCreateGraphicsPipelines"); + vkCreateComputePipelines = (PFN_vkCreateComputePipelines)vkGetInstanceProcAddr(instance, "vkCreateComputePipelines"); + vkDestroyPipeline = (PFN_vkDestroyPipeline)vkGetInstanceProcAddr(instance, "vkDestroyPipeline"); + vkCreatePipelineLayout = (PFN_vkCreatePipelineLayout)vkGetInstanceProcAddr(instance, "vkCreatePipelineLayout"); + vkDestroyPipelineLayout = (PFN_vkDestroyPipelineLayout)vkGetInstanceProcAddr(instance, "vkDestroyPipelineLayout"); + vkCreateSampler = (PFN_vkCreateSampler)vkGetInstanceProcAddr(instance, "vkCreateSampler"); + vkDestroySampler = (PFN_vkDestroySampler)vkGetInstanceProcAddr(instance, "vkDestroySampler"); + vkCreateDescriptorSetLayout = (PFN_vkCreateDescriptorSetLayout)vkGetInstanceProcAddr(instance, "vkCreateDescriptorSetLayout"); + vkDestroyDescriptorSetLayout = (PFN_vkDestroyDescriptorSetLayout)vkGetInstanceProcAddr(instance, "vkDestroyDescriptorSetLayout"); + vkCreateDescriptorPool = (PFN_vkCreateDescriptorPool)vkGetInstanceProcAddr(instance, "vkCreateDescriptorPool"); + vkDestroyDescriptorPool = (PFN_vkDestroyDescriptorPool)vkGetInstanceProcAddr(instance, "vkDestroyDescriptorPool"); + vkResetDescriptorPool = (PFN_vkResetDescriptorPool)vkGetInstanceProcAddr(instance, "vkResetDescriptorPool"); + vkAllocateDescriptorSets = (PFN_vkAllocateDescriptorSets)vkGetInstanceProcAddr(instance, "vkAllocateDescriptorSets"); + vkFreeDescriptorSets = (PFN_vkFreeDescriptorSets)vkGetInstanceProcAddr(instance, "vkFreeDescriptorSets"); + vkUpdateDescriptorSets = (PFN_vkUpdateDescriptorSets)vkGetInstanceProcAddr(instance, "vkUpdateDescriptorSets"); + vkCreateFramebuffer = (PFN_vkCreateFramebuffer)vkGetInstanceProcAddr(instance, "vkCreateFramebuffer"); + vkDestroyFramebuffer = (PFN_vkDestroyFramebuffer)vkGetInstanceProcAddr(instance, "vkDestroyFramebuffer"); + vkCreateRenderPass = (PFN_vkCreateRenderPass)vkGetInstanceProcAddr(instance, "vkCreateRenderPass"); + vkDestroyRenderPass = (PFN_vkDestroyRenderPass)vkGetInstanceProcAddr(instance, "vkDestroyRenderPass"); + vkGetRenderAreaGranularity = (PFN_vkGetRenderAreaGranularity)vkGetInstanceProcAddr(instance, "vkGetRenderAreaGranularity"); + vkCreateCommandPool = (PFN_vkCreateCommandPool)vkGetInstanceProcAddr(instance, "vkCreateCommandPool"); + vkDestroyCommandPool = (PFN_vkDestroyCommandPool)vkGetInstanceProcAddr(instance, "vkDestroyCommandPool"); + vkResetCommandPool = (PFN_vkResetCommandPool)vkGetInstanceProcAddr(instance, "vkResetCommandPool"); + vkAllocateCommandBuffers = (PFN_vkAllocateCommandBuffers)vkGetInstanceProcAddr(instance, "vkAllocateCommandBuffers"); + vkFreeCommandBuffers = (PFN_vkFreeCommandBuffers)vkGetInstanceProcAddr(instance, "vkFreeCommandBuffers"); + vkBeginCommandBuffer = (PFN_vkBeginCommandBuffer)vkGetInstanceProcAddr(instance, "vkBeginCommandBuffer"); + vkEndCommandBuffer = (PFN_vkEndCommandBuffer)vkGetInstanceProcAddr(instance, "vkEndCommandBuffer"); + vkResetCommandBuffer = (PFN_vkResetCommandBuffer)vkGetInstanceProcAddr(instance, "vkResetCommandBuffer"); + vkCmdBindPipeline = (PFN_vkCmdBindPipeline)vkGetInstanceProcAddr(instance, "vkCmdBindPipeline"); + vkCmdSetViewport = (PFN_vkCmdSetViewport)vkGetInstanceProcAddr(instance, "vkCmdSetViewport"); + vkCmdSetScissor = (PFN_vkCmdSetScissor)vkGetInstanceProcAddr(instance, "vkCmdSetScissor"); + vkCmdSetLineWidth = (PFN_vkCmdSetLineWidth)vkGetInstanceProcAddr(instance, "vkCmdSetLineWidth"); + vkCmdSetDepthBias = (PFN_vkCmdSetDepthBias)vkGetInstanceProcAddr(instance, "vkCmdSetDepthBias"); + vkCmdSetBlendConstants = (PFN_vkCmdSetBlendConstants)vkGetInstanceProcAddr(instance, "vkCmdSetBlendConstants"); + vkCmdSetDepthBounds = (PFN_vkCmdSetDepthBounds)vkGetInstanceProcAddr(instance, "vkCmdSetDepthBounds"); + vkCmdSetStencilCompareMask = (PFN_vkCmdSetStencilCompareMask)vkGetInstanceProcAddr(instance, "vkCmdSetStencilCompareMask"); + vkCmdSetStencilWriteMask = (PFN_vkCmdSetStencilWriteMask)vkGetInstanceProcAddr(instance, "vkCmdSetStencilWriteMask"); + vkCmdSetStencilReference = (PFN_vkCmdSetStencilReference)vkGetInstanceProcAddr(instance, "vkCmdSetStencilReference"); + vkCmdBindDescriptorSets = (PFN_vkCmdBindDescriptorSets)vkGetInstanceProcAddr(instance, "vkCmdBindDescriptorSets"); + vkCmdBindIndexBuffer = (PFN_vkCmdBindIndexBuffer)vkGetInstanceProcAddr(instance, "vkCmdBindIndexBuffer"); + vkCmdBindVertexBuffers = (PFN_vkCmdBindVertexBuffers)vkGetInstanceProcAddr(instance, "vkCmdBindVertexBuffers"); + vkCmdDraw = (PFN_vkCmdDraw)vkGetInstanceProcAddr(instance, "vkCmdDraw"); + vkCmdDrawIndexed = (PFN_vkCmdDrawIndexed)vkGetInstanceProcAddr(instance, "vkCmdDrawIndexed"); + vkCmdDrawIndirect = (PFN_vkCmdDrawIndirect)vkGetInstanceProcAddr(instance, "vkCmdDrawIndirect"); + vkCmdDrawIndexedIndirect = (PFN_vkCmdDrawIndexedIndirect)vkGetInstanceProcAddr(instance, "vkCmdDrawIndexedIndirect"); + vkCmdDispatch = (PFN_vkCmdDispatch)vkGetInstanceProcAddr(instance, "vkCmdDispatch"); + vkCmdDispatchIndirect = (PFN_vkCmdDispatchIndirect)vkGetInstanceProcAddr(instance, "vkCmdDispatchIndirect"); + vkCmdCopyBuffer = (PFN_vkCmdCopyBuffer)vkGetInstanceProcAddr(instance, "vkCmdCopyBuffer"); + vkCmdCopyImage = (PFN_vkCmdCopyImage)vkGetInstanceProcAddr(instance, "vkCmdCopyImage"); + vkCmdBlitImage = (PFN_vkCmdBlitImage)vkGetInstanceProcAddr(instance, "vkCmdBlitImage"); + vkCmdCopyBufferToImage = (PFN_vkCmdCopyBufferToImage)vkGetInstanceProcAddr(instance, "vkCmdCopyBufferToImage"); + vkCmdCopyImageToBuffer = (PFN_vkCmdCopyImageToBuffer)vkGetInstanceProcAddr(instance, "vkCmdCopyImageToBuffer"); + vkCmdUpdateBuffer = (PFN_vkCmdUpdateBuffer)vkGetInstanceProcAddr(instance, "vkCmdUpdateBuffer"); + vkCmdFillBuffer = (PFN_vkCmdFillBuffer)vkGetInstanceProcAddr(instance, "vkCmdFillBuffer"); + vkCmdClearColorImage = (PFN_vkCmdClearColorImage)vkGetInstanceProcAddr(instance, "vkCmdClearColorImage"); + vkCmdClearDepthStencilImage = (PFN_vkCmdClearDepthStencilImage)vkGetInstanceProcAddr(instance, "vkCmdClearDepthStencilImage"); + vkCmdClearAttachments = (PFN_vkCmdClearAttachments)vkGetInstanceProcAddr(instance, "vkCmdClearAttachments"); + vkCmdResolveImage = (PFN_vkCmdResolveImage)vkGetInstanceProcAddr(instance, "vkCmdResolveImage"); + vkCmdSetEvent = (PFN_vkCmdSetEvent)vkGetInstanceProcAddr(instance, "vkCmdSetEvent"); + vkCmdResetEvent = (PFN_vkCmdResetEvent)vkGetInstanceProcAddr(instance, "vkCmdResetEvent"); + vkCmdWaitEvents = (PFN_vkCmdWaitEvents)vkGetInstanceProcAddr(instance, "vkCmdWaitEvents"); + vkCmdPipelineBarrier = (PFN_vkCmdPipelineBarrier)vkGetInstanceProcAddr(instance, "vkCmdPipelineBarrier"); + vkCmdBeginQuery = (PFN_vkCmdBeginQuery)vkGetInstanceProcAddr(instance, "vkCmdBeginQuery"); + vkCmdEndQuery = (PFN_vkCmdEndQuery)vkGetInstanceProcAddr(instance, "vkCmdEndQuery"); + vkCmdResetQueryPool = (PFN_vkCmdResetQueryPool)vkGetInstanceProcAddr(instance, "vkCmdResetQueryPool"); + vkCmdWriteTimestamp = (PFN_vkCmdWriteTimestamp)vkGetInstanceProcAddr(instance, "vkCmdWriteTimestamp"); + vkCmdCopyQueryPoolResults = (PFN_vkCmdCopyQueryPoolResults)vkGetInstanceProcAddr(instance, "vkCmdCopyQueryPoolResults"); + vkCmdPushConstants = (PFN_vkCmdPushConstants)vkGetInstanceProcAddr(instance, "vkCmdPushConstants"); + vkCmdBeginRenderPass = (PFN_vkCmdBeginRenderPass)vkGetInstanceProcAddr(instance, "vkCmdBeginRenderPass"); + vkCmdNextSubpass = (PFN_vkCmdNextSubpass)vkGetInstanceProcAddr(instance, "vkCmdNextSubpass"); + vkCmdEndRenderPass = (PFN_vkCmdEndRenderPass)vkGetInstanceProcAddr(instance, "vkCmdEndRenderPass"); + vkCmdExecuteCommands = (PFN_vkCmdExecuteCommands)vkGetInstanceProcAddr(instance, "vkCmdExecuteCommands"); + + vkGetPhysicalDeviceSurfaceSupportKHR = (PFN_vkGetPhysicalDeviceSurfaceSupportKHR)vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceSurfaceSupportKHR"); + vkGetPhysicalDeviceSurfaceCapabilitiesKHR = (PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR)vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceSurfaceCapabilitiesKHR"); + vkGetPhysicalDeviceSurfaceFormatsKHR = (PFN_vkGetPhysicalDeviceSurfaceFormatsKHR)vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceSurfaceFormatsKHR"); + vkGetPhysicalDeviceSurfacePresentModesKHR = (PFN_vkGetPhysicalDeviceSurfacePresentModesKHR)vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceSurfacePresentModesKHR"); + + vkCreateSwapchainKHR = (PFN_vkCreateSwapchainKHR)vkGetInstanceProcAddr(instance, "vkCreateSwapchainKHR"); + vkDestroySwapchainKHR = (PFN_vkDestroySwapchainKHR)vkGetInstanceProcAddr(instance, "vkDestroySwapchainKHR"); + vkGetSwapchainImagesKHR = (PFN_vkGetSwapchainImagesKHR)vkGetInstanceProcAddr(instance, "vkGetSwapchainImagesKHR"); + vkAcquireNextImageKHR = (PFN_vkAcquireNextImageKHR)vkGetInstanceProcAddr(instance, "vkAcquireNextImageKHR"); + vkQueuePresentKHR = (PFN_vkQueuePresentKHR)vkGetInstanceProcAddr(instance, "vkQueuePresentKHR"); + +#ifdef _WIN32 + vkCreateWin32SurfaceKHR = (PFN_vkCreateWin32SurfaceKHR)vkGetInstanceProcAddr(instance, "vkCreateWin32SurfaceKHR"); +#elif defined(ANDROID) + vkCreateAndroidSurfaceKHR = (PFN_vkCreateAndroidSurfaceKHR)vkGetInstanceProcAddr(instance, "vkCreateAndroidSurfaceKHR"); +#endif + + vkCreateDebugReportCallbackEXT = (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(instance, "vkCreateDebugReportCallbackEXT"); + vkDestroyDebugReportCallbackEXT = (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(instance, "vkDestroyDebugReportCallbackEXT"); +} + +// On some implementations, loading functions (that have Device as their first parameter) via vkGetDeviceProcAddr may +// increase performance - but then these function pointers will only work on that specific device. Thus, this loader is not very +// good for multi-device. +void VulkanLoadDeviceFunctions(VkDevice device) { + // TODO: Move more functions VulkanLoadInstanceFunctions to here. + vkCreateSwapchainKHR = (PFN_vkCreateSwapchainKHR)vkGetDeviceProcAddr(device, "vkCreateSwapchainKHR"); + vkDestroySwapchainKHR = (PFN_vkDestroySwapchainKHR)vkGetDeviceProcAddr(device, "vkDestroySwapchainKHR"); + vkGetSwapchainImagesKHR = (PFN_vkGetSwapchainImagesKHR)vkGetDeviceProcAddr(device, "vkGetSwapchainImagesKHR"); + vkAcquireNextImageKHR = (PFN_vkAcquireNextImageKHR)vkGetDeviceProcAddr(device, "vkAcquireNextImageKHR"); + vkQueuePresentKHR = (PFN_vkQueuePresentKHR)vkGetDeviceProcAddr(device, "vkQueuePresentKHR"); +} + +void VulkanFree() { +#ifdef _WIN32 + if (vulkanLibrary) { + FreeLibrary(vulkanLibrary); + } +#else + if (vulkanLibrary) { + dlclose(vulkanLibrary); + } +#endif +} diff --git a/Common/Vulkan/VulkanLoader.h b/Common/Vulkan/VulkanLoader.h new file mode 100644 index 0000000000..5c36804596 --- /dev/null +++ b/Common/Vulkan/VulkanLoader.h @@ -0,0 +1,198 @@ +// Copyright (c) 2016- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#pragma once + +#ifdef ANDROID +#define VK_USE_PLATFORM_ANDROID_KHR +#elif defined(_WIN32) +#define VK_USE_PLATFORM_WIN32_KHR +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#endif + +#define VK_NO_PROTOTYPES + +#include "ext/vulkan/vulkan.h" + +extern PFN_vkCreateInstance vkCreateInstance; +extern PFN_vkDestroyInstance vkDestroyInstance; +extern PFN_vkEnumeratePhysicalDevices vkEnumeratePhysicalDevices; +extern PFN_vkGetPhysicalDeviceFeatures vkGetPhysicalDeviceFeatures; +extern PFN_vkGetPhysicalDeviceFormatProperties vkGetPhysicalDeviceFormatProperties; +extern PFN_vkGetPhysicalDeviceImageFormatProperties vkGetPhysicalDeviceImageFormatProperties; +extern PFN_vkGetPhysicalDeviceProperties vkGetPhysicalDeviceProperties; +extern PFN_vkGetPhysicalDeviceQueueFamilyProperties vkGetPhysicalDeviceQueueFamilyProperties; +extern PFN_vkGetPhysicalDeviceMemoryProperties vkGetPhysicalDeviceMemoryProperties; +extern PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr; +extern PFN_vkGetDeviceProcAddr vkGetDeviceProcAddr; +extern PFN_vkCreateDevice vkCreateDevice; +extern PFN_vkDestroyDevice vkDestroyDevice; +extern PFN_vkEnumerateInstanceExtensionProperties vkEnumerateInstanceExtensionProperties; +extern PFN_vkEnumerateDeviceExtensionProperties vkEnumerateDeviceExtensionProperties; +extern PFN_vkEnumerateInstanceLayerProperties vkEnumerateInstanceLayerProperties; +extern PFN_vkEnumerateDeviceLayerProperties vkEnumerateDeviceLayerProperties; +extern PFN_vkGetDeviceQueue vkGetDeviceQueue; +extern PFN_vkQueueSubmit vkQueueSubmit; +extern PFN_vkQueueWaitIdle vkQueueWaitIdle; +extern PFN_vkDeviceWaitIdle vkDeviceWaitIdle; +extern PFN_vkAllocateMemory vkAllocateMemory; +extern PFN_vkFreeMemory vkFreeMemory; +extern PFN_vkMapMemory vkMapMemory; +extern PFN_vkUnmapMemory vkUnmapMemory; +extern PFN_vkFlushMappedMemoryRanges vkFlushMappedMemoryRanges; +extern PFN_vkInvalidateMappedMemoryRanges vkInvalidateMappedMemoryRanges; +extern PFN_vkGetDeviceMemoryCommitment vkGetDeviceMemoryCommitment; +extern PFN_vkBindBufferMemory vkBindBufferMemory; +extern PFN_vkBindImageMemory vkBindImageMemory; +extern PFN_vkGetBufferMemoryRequirements vkGetBufferMemoryRequirements; +extern PFN_vkGetImageMemoryRequirements vkGetImageMemoryRequirements; +extern PFN_vkGetImageSparseMemoryRequirements vkGetImageSparseMemoryRequirements; +extern PFN_vkGetPhysicalDeviceSparseImageFormatProperties vkGetPhysicalDeviceSparseImageFormatProperties; +extern PFN_vkQueueBindSparse vkQueueBindSparse; +extern PFN_vkCreateFence vkCreateFence; +extern PFN_vkDestroyFence vkDestroyFence; +extern PFN_vkResetFences vkResetFences; +extern PFN_vkGetFenceStatus vkGetFenceStatus; +extern PFN_vkWaitForFences vkWaitForFences; +extern PFN_vkCreateSemaphore vkCreateSemaphore; +extern PFN_vkDestroySemaphore vkDestroySemaphore; +extern PFN_vkCreateEvent vkCreateEvent; +extern PFN_vkDestroyEvent vkDestroyEvent; +extern PFN_vkGetEventStatus vkGetEventStatus; +extern PFN_vkSetEvent vkSetEvent; +extern PFN_vkResetEvent vkResetEvent; +extern PFN_vkCreateQueryPool vkCreateQueryPool; +extern PFN_vkDestroyQueryPool vkDestroyQueryPool; +extern PFN_vkGetQueryPoolResults vkGetQueryPoolResults; +extern PFN_vkCreateBuffer vkCreateBuffer; +extern PFN_vkDestroyBuffer vkDestroyBuffer; +extern PFN_vkCreateBufferView vkCreateBufferView; +extern PFN_vkDestroyBufferView vkDestroyBufferView; +extern PFN_vkCreateImage vkCreateImage; +extern PFN_vkDestroyImage vkDestroyImage; +extern PFN_vkGetImageSubresourceLayout vkGetImageSubresourceLayout; +extern PFN_vkCreateImageView vkCreateImageView; +extern PFN_vkDestroyImageView vkDestroyImageView; +extern PFN_vkCreateShaderModule vkCreateShaderModule; +extern PFN_vkDestroyShaderModule vkDestroyShaderModule; +extern PFN_vkCreatePipelineCache vkCreatePipelineCache; +extern PFN_vkDestroyPipelineCache vkDestroyPipelineCache; +extern PFN_vkGetPipelineCacheData vkGetPipelineCacheData; +extern PFN_vkMergePipelineCaches vkMergePipelineCaches; +extern PFN_vkCreateGraphicsPipelines vkCreateGraphicsPipelines; +extern PFN_vkCreateComputePipelines vkCreateComputePipelines; +extern PFN_vkDestroyPipeline vkDestroyPipeline; +extern PFN_vkCreatePipelineLayout vkCreatePipelineLayout; +extern PFN_vkDestroyPipelineLayout vkDestroyPipelineLayout; +extern PFN_vkCreateSampler vkCreateSampler; +extern PFN_vkDestroySampler vkDestroySampler; +extern PFN_vkCreateDescriptorSetLayout vkCreateDescriptorSetLayout; +extern PFN_vkDestroyDescriptorSetLayout vkDestroyDescriptorSetLayout; +extern PFN_vkCreateDescriptorPool vkCreateDescriptorPool; +extern PFN_vkDestroyDescriptorPool vkDestroyDescriptorPool; +extern PFN_vkResetDescriptorPool vkResetDescriptorPool; +extern PFN_vkAllocateDescriptorSets vkAllocateDescriptorSets; +extern PFN_vkFreeDescriptorSets vkFreeDescriptorSets; +extern PFN_vkUpdateDescriptorSets vkUpdateDescriptorSets; +extern PFN_vkCreateFramebuffer vkCreateFramebuffer; +extern PFN_vkDestroyFramebuffer vkDestroyFramebuffer; +extern PFN_vkCreateRenderPass vkCreateRenderPass; +extern PFN_vkDestroyRenderPass vkDestroyRenderPass; +extern PFN_vkGetRenderAreaGranularity vkGetRenderAreaGranularity; +extern PFN_vkCreateCommandPool vkCreateCommandPool; +extern PFN_vkDestroyCommandPool vkDestroyCommandPool; +extern PFN_vkResetCommandPool vkResetCommandPool; +extern PFN_vkAllocateCommandBuffers vkAllocateCommandBuffers; +extern PFN_vkFreeCommandBuffers vkFreeCommandBuffers; +extern PFN_vkBeginCommandBuffer vkBeginCommandBuffer; +extern PFN_vkEndCommandBuffer vkEndCommandBuffer; +extern PFN_vkResetCommandBuffer vkResetCommandBuffer; +extern PFN_vkCmdBindPipeline vkCmdBindPipeline; +extern PFN_vkCmdSetViewport vkCmdSetViewport; +extern PFN_vkCmdSetScissor vkCmdSetScissor; +extern PFN_vkCmdSetLineWidth vkCmdSetLineWidth; +extern PFN_vkCmdSetDepthBias vkCmdSetDepthBias; +extern PFN_vkCmdSetBlendConstants vkCmdSetBlendConstants; +extern PFN_vkCmdSetDepthBounds vkCmdSetDepthBounds; +extern PFN_vkCmdSetStencilCompareMask vkCmdSetStencilCompareMask; +extern PFN_vkCmdSetStencilWriteMask vkCmdSetStencilWriteMask; +extern PFN_vkCmdSetStencilReference vkCmdSetStencilReference; +extern PFN_vkCmdBindDescriptorSets vkCmdBindDescriptorSets; +extern PFN_vkCmdBindIndexBuffer vkCmdBindIndexBuffer; +extern PFN_vkCmdBindVertexBuffers vkCmdBindVertexBuffers; +extern PFN_vkCmdDraw vkCmdDraw; +extern PFN_vkCmdDrawIndexed vkCmdDrawIndexed; +extern PFN_vkCmdDrawIndirect vkCmdDrawIndirect; +extern PFN_vkCmdDrawIndexedIndirect vkCmdDrawIndexedIndirect; +extern PFN_vkCmdDispatch vkCmdDispatch; +extern PFN_vkCmdDispatchIndirect vkCmdDispatchIndirect; +extern PFN_vkCmdCopyBuffer vkCmdCopyBuffer; +extern PFN_vkCmdCopyImage vkCmdCopyImage; +extern PFN_vkCmdBlitImage vkCmdBlitImage; +extern PFN_vkCmdCopyBufferToImage vkCmdCopyBufferToImage; +extern PFN_vkCmdCopyImageToBuffer vkCmdCopyImageToBuffer; +extern PFN_vkCmdUpdateBuffer vkCmdUpdateBuffer; +extern PFN_vkCmdFillBuffer vkCmdFillBuffer; +extern PFN_vkCmdClearColorImage vkCmdClearColorImage; +extern PFN_vkCmdClearDepthStencilImage vkCmdClearDepthStencilImage; +extern PFN_vkCmdClearAttachments vkCmdClearAttachments; +extern PFN_vkCmdResolveImage vkCmdResolveImage; +extern PFN_vkCmdSetEvent vkCmdSetEvent; +extern PFN_vkCmdResetEvent vkCmdResetEvent; +extern PFN_vkCmdWaitEvents vkCmdWaitEvents; +extern PFN_vkCmdPipelineBarrier vkCmdPipelineBarrier; +extern PFN_vkCmdBeginQuery vkCmdBeginQuery; +extern PFN_vkCmdEndQuery vkCmdEndQuery; +extern PFN_vkCmdResetQueryPool vkCmdResetQueryPool; +extern PFN_vkCmdWriteTimestamp vkCmdWriteTimestamp; +extern PFN_vkCmdCopyQueryPoolResults vkCmdCopyQueryPoolResults; +extern PFN_vkCmdPushConstants vkCmdPushConstants; +extern PFN_vkCmdBeginRenderPass vkCmdBeginRenderPass; +extern PFN_vkCmdNextSubpass vkCmdNextSubpass; +extern PFN_vkCmdEndRenderPass vkCmdEndRenderPass; +extern PFN_vkCmdExecuteCommands vkCmdExecuteCommands; + +#ifdef ANDROID +extern PFN_vkCreateAndroidSurfaceKHR vkCreateAndroidSurfaceKHR; +#elif defined(_WIN32) +extern PFN_vkCreateWin32SurfaceKHR vkCreateWin32SurfaceKHR; +#endif + +extern PFN_vkDestroySurfaceKHR vkDestroySurfaceKHR; + +// Simple loader for the WSI extension. +extern PFN_vkGetPhysicalDeviceSurfaceSupportKHR vkGetPhysicalDeviceSurfaceSupportKHR; +extern PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR vkGetPhysicalDeviceSurfaceCapabilitiesKHR; +extern PFN_vkGetPhysicalDeviceSurfaceFormatsKHR vkGetPhysicalDeviceSurfaceFormatsKHR; +extern PFN_vkGetPhysicalDeviceSurfacePresentModesKHR vkGetPhysicalDeviceSurfacePresentModesKHR; + +extern PFN_vkCreateSwapchainKHR vkCreateSwapchainKHR; +extern PFN_vkDestroySwapchainKHR vkDestroySwapchainKHR; +extern PFN_vkGetSwapchainImagesKHR vkGetSwapchainImagesKHR; +extern PFN_vkAcquireNextImageKHR vkAcquireNextImageKHR; +extern PFN_vkQueuePresentKHR vkQueuePresentKHR; + +// And the DEBUG_REPORT extension. +extern PFN_vkCreateDebugReportCallbackEXT vkCreateDebugReportCallbackEXT; +extern PFN_vkDestroyDebugReportCallbackEXT vkDestroyDebugReportCallbackEXT; + +bool VulkanLoad(); +void VulkanLoadInstanceFunctions(VkInstance instance); +void VulkanLoadDeviceFunctions(VkDevice device); +void VulkanFree(); + diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index af495f53ff..c12f8d9390 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -183,10 +183,10 @@ DrawEngineVulkan::~DrawEngineVulkan() { FreeMemoryPages(transformedExpanded, 3 * TRANSFORMED_VERTEX_BUFFER_SIZE); for (int i = 0; i < 2; i++) { - vulkan_->QueueDelete(frame_[i].descPool); + vulkan_->Delete().QueueDeleteDescriptorPool(frame_[i].descPool); delete frame_[i].pushData; } - vulkan_->QueueDelete(depalSampler_); + vulkan_->Delete().QueueDeleteSampler(depalSampler_); } void DrawEngineVulkan::BeginFrame() { @@ -379,7 +379,7 @@ VkDescriptorSet DrawEngineVulkan::GetDescriptorSet(VkImageView imageView, VkSamp DescriptorSetKey key; key.imageView_ = imageView; key.sampler_ = sampler; - key.secondaryImageView_ = nullptr; + key.secondaryImageView_ = VK_NULL_HANDLE; key.buffer_ = dynamicUbo; FrameData *frame = &frame_[curFrame_ & 1]; @@ -461,8 +461,8 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { // the three ubo pushes. The reason is that the three UBOs must be in the same buffer as that's how we // designed the descriptor set. - VkImageView imageView = nullptr; - VkSampler sampler = nullptr; + VkImageView imageView = VK_NULL_HANDLE; + VkSampler sampler = VK_NULL_HANDLE; if (gstate_c.textureChanged != TEXCHANGE_UNCHANGED && !gstate.isModeClear() && gstate.isTextureMapEnabled()) { textureCache_->SetTexture(); diff --git a/GPU/Vulkan/FramebufferVulkan.cpp b/GPU/Vulkan/FramebufferVulkan.cpp index 76c621c6f2..ae5c1ca13e 100644 --- a/GPU/Vulkan/FramebufferVulkan.cpp +++ b/GPU/Vulkan/FramebufferVulkan.cpp @@ -15,8 +15,6 @@ // Official git repository and contact information can be found at // https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. -#pragma once - #include #include diff --git a/GPU/Vulkan/FramebufferVulkan.h b/GPU/Vulkan/FramebufferVulkan.h index 2bd75f9cc7..510714458e 100644 --- a/GPU/Vulkan/FramebufferVulkan.h +++ b/GPU/Vulkan/FramebufferVulkan.h @@ -17,7 +17,7 @@ #pragma once -#include "GPU/Vulkan/VulkanUtil.h" +#include "Common/Vulkan/VulkanLoader.h" #include "GPU/Common/FramebufferCommon.h" #include "GPU/GPUInterface.h" #include "GPU/Common/GPUDebugInterface.h" diff --git a/GPU/Vulkan/PipelineManagerVulkan.cpp b/GPU/Vulkan/PipelineManagerVulkan.cpp index 155a65be91..a666094708 100644 --- a/GPU/Vulkan/PipelineManagerVulkan.cpp +++ b/GPU/Vulkan/PipelineManagerVulkan.cpp @@ -14,7 +14,7 @@ PipelineManagerVulkan::PipelineManagerVulkan(VulkanContext *vulkan) : vulkan_(vu PipelineManagerVulkan::~PipelineManagerVulkan() { Clear(); - vulkan_->QueueDelete(pipelineCache_); + vulkan_->Delete().QueueDeletePipelineCache(pipelineCache_); } void PipelineManagerVulkan::Clear() { @@ -29,7 +29,7 @@ void PipelineManagerVulkan::Clear() { struct DeclTypeInfo { VkFormat type; - const char * name; + const char *name; }; static const DeclTypeInfo VComp[] = { @@ -264,7 +264,7 @@ static VulkanPipeline *CreateVulkanPipeline(VkDevice device, VkPipelineCache pip pipe.pInputAssemblyState = &inputAssembly; pipe.pMultisampleState = &ms; pipe.layout = layout; - pipe.basePipelineHandle = nullptr; + pipe.basePipelineHandle = VK_NULL_HANDLE; pipe.basePipelineIndex = 0; pipe.renderPass = renderPass; pipe.subpass = 0; @@ -317,6 +317,8 @@ std::vector PipelineManagerVulkan::DebugGetObjectIDs(DebugShaderTyp } } break; + default: + break; } return ids; } diff --git a/GPU/Vulkan/ShaderManagerVulkan.cpp b/GPU/Vulkan/ShaderManagerVulkan.cpp index 3a0230d53d..691b8667ef 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.cpp +++ b/GPU/Vulkan/ShaderManagerVulkan.cpp @@ -42,7 +42,7 @@ #include "UI/OnScreenDisplay.h" VulkanFragmentShader::VulkanFragmentShader(VulkanContext *vulkan, ShaderID id, const char *code, bool useHWTransform) - : vulkan_(vulkan), id_(id), failed_(false), useHWTransform_(useHWTransform), module_(nullptr) { + : vulkan_(vulkan), id_(id), failed_(false), useHWTransform_(useHWTransform), module_(0) { source_ = code; std::string errorMessage; @@ -83,7 +83,7 @@ VulkanFragmentShader::VulkanFragmentShader(VulkanContext *vulkan, ShaderID id, c VulkanFragmentShader::~VulkanFragmentShader() { if (module_) { - vulkan_->QueueDelete(module_); + vulkan_->Delete().QueueDeleteShaderModule(module_); } } @@ -99,7 +99,7 @@ std::string VulkanFragmentShader::GetShaderString(DebugShaderStringType type) co } VulkanVertexShader::VulkanVertexShader(VulkanContext *vulkan, ShaderID id, const char *code, int vertType, bool useHWTransform) - : vulkan_(vulkan), id_(id), failed_(false), useHWTransform_(useHWTransform), module_(nullptr) { + : vulkan_(vulkan), id_(id), failed_(false), useHWTransform_(useHWTransform), module_(VK_NULL_HANDLE) { source_ = code; std::string errorMessage; std::vector spirv; @@ -127,7 +127,7 @@ VulkanVertexShader::VulkanVertexShader(VulkanContext *vulkan, ShaderID id, const if (!success) { failed_ = true; - module_ = nullptr; + module_ = VK_NULL_HANDLE; return; } else { DEBUG_LOG(G3D, "Compiled shader:\n%s\n", (const char *)code); @@ -136,7 +136,7 @@ VulkanVertexShader::VulkanVertexShader(VulkanContext *vulkan, ShaderID id, const VulkanVertexShader::~VulkanVertexShader() { if (module_) { - vulkan_->QueueDelete(module_); + vulkan_->Delete().QueueDeleteShaderModule(module_); } } @@ -536,16 +536,18 @@ std::vector ShaderManagerVulkan::DebugGetShaderIDs(DebugShaderType iter.first.ToString(&id); ids.push_back(id); } + break; } - break; case SHADER_TYPE_FRAGMENT: { for (auto iter : fsCache_) { iter.first.ToString(&id); ids.push_back(id); } + break; } - break; + default: + break; } return ids; } diff --git a/GPU/Vulkan/StateMappingVulkan.cpp b/GPU/Vulkan/StateMappingVulkan.cpp index 0a095d6345..488439999f 100644 --- a/GPU/Vulkan/StateMappingVulkan.cpp +++ b/GPU/Vulkan/StateMappingVulkan.cpp @@ -15,8 +15,7 @@ // Official git repository and contact information can be found at // https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. -#define VK_PROTOTYPES -#include "ext/vulkan/vulkan.h" +#include "Common/Vulkan/VulkanLoader.h" #include "GPU/Math3D.h" #include "GPU/GPUState.h" diff --git a/GPU/Vulkan/StateMappingVulkan.h b/GPU/Vulkan/StateMappingVulkan.h index 3275fc268b..8bb8aa0a07 100644 --- a/GPU/Vulkan/StateMappingVulkan.h +++ b/GPU/Vulkan/StateMappingVulkan.h @@ -1,6 +1,6 @@ #pragma once -#include "ext/vulkan/vulkan.h" +#include "Common/Vulkan/VulkanLoader.h" #include diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index 8bfc89f90e..a38835dff6 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -75,7 +75,7 @@ extern int g_iNumVideos; SamplerCache::~SamplerCache() { for (auto iter : cache_) { - vulkan_->QueueDelete(iter.second); + vulkan_->Delete().QueueDeleteSampler(iter.second); } } @@ -848,8 +848,8 @@ void TextureCacheVulkan::SetTextureFramebuffer(TexCacheEntry *entry, VirtualFram void TextureCacheVulkan::ApplyTexture(VkImageView &imageView, VkSampler &sampler) { if (nextTexture_ == nullptr) { - imageView = nullptr; - sampler = nullptr; + imageView = VK_NULL_HANDLE; + sampler = VK_NULL_HANDLE; return; } VkCommandBuffer cmd = nullptr; diff --git a/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp b/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp index 83ad78d3f9..152a274ee4 100644 --- a/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp +++ b/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp @@ -26,6 +26,7 @@ #endif #include "base/stringutil.h" +#include "Common/Vulkan/VulkanLoader.h" #include "GPU/ge_constants.h" #include "GPU/GPUState.h" #include "GPU/Common/ShaderId.h" diff --git a/GPU/Vulkan/VulkanUtil.h b/GPU/Vulkan/VulkanUtil.h index f0c8496d91..fe41a2b8e0 100644 --- a/GPU/Vulkan/VulkanUtil.h +++ b/GPU/Vulkan/VulkanUtil.h @@ -1,4 +1,4 @@ #pragma once -#include "ext/vulkan/vulkan.h" +#include "Common/Vulkan/VulkanLoader.h" diff --git a/Windows/GPU/WindowsVulkanContext.cpp b/Windows/GPU/WindowsVulkanContext.cpp index b6462aa651..b30f7788e8 100644 --- a/Windows/GPU/WindowsVulkanContext.cpp +++ b/Windows/GPU/WindowsVulkanContext.cpp @@ -50,7 +50,7 @@ #include #include -#include "ext/vulkan/vulkan.h" +#include "Common/Vulkan/VulkanLoader.h" #include "ext/native/thin3d/VulkanContext.h" #include "thin3d/thin3d.h" diff --git a/android/jni/Android.mk b/android/jni/Android.mk index 04ad94d17f..fc6cd779ec 100644 --- a/android/jni/Android.mk +++ b/android/jni/Android.mk @@ -124,9 +124,8 @@ EGL_FILES := \ $(SRC)/Common/GL/GLInterface/EGLAndroid.cpp \ $(SRC)/Common/GL/GLInterface/GLInterface.cpp -# Only build Vulkan on ARM64 for now. -ifeq ($(TARGET_ARCH_ABI),arm64-v8a) VULKAN_FILES := \ + $(SRC)/Common/Vulkan/VulkanLoader.cpp \ $(SRC)/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp \ $(SRC)/GPU/Vulkan/DrawEngineVulkan.cpp \ $(SRC)/GPU/Vulkan/FramebufferVulkan.cpp \ @@ -138,9 +137,7 @@ VULKAN_FILES := \ $(SRC)/GPU/Vulkan/TextureScalerVulkan.cpp \ $(SRC)/GPU/Vulkan/DepalettizeShaderVulkan.cpp \ $(SRC)/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp -else -VULKAN_FILES := -endif +#endif EXEC_AND_LIB_FILES := \ $(ARCH_FILES) \ @@ -511,6 +508,7 @@ endif $(call import-module,libzip) $(call import-module,native) +$(call import-module,glslang) ifeq ($(ANDROID_NDK_PROFILER),1) $(call import-module,android-ndk-profiler) diff --git a/android/jni/Locals.mk b/android/jni/Locals.mk index 67c19581f7..bc8dea52b8 100644 --- a/android/jni/Locals.mk +++ b/android/jni/Locals.mk @@ -15,7 +15,7 @@ LOCAL_C_INCLUDES := \ $(LOCAL_PATH)/$(NATIVE) \ $(LOCAL_PATH) -LOCAL_STATIC_LIBRARIES := native libzip +LOCAL_STATIC_LIBRARIES := native libzip glslang LOCAL_LDLIBS := -lz -landroid -lGLESv2 -lOpenSLES -lEGL -ldl -llog # ifeq ($(TARGET_ARCH_ABI),armeabi-v7a) diff --git a/ext/native/Android.mk b/ext/native/Android.mk index 28542deac3..9ac0f5f8db 100644 --- a/ext/native/Android.mk +++ b/ext/native/Android.mk @@ -81,6 +81,8 @@ LOCAL_SRC_FILES :=\ image/png_load.cpp \ thin3d/thin3d.cpp \ thin3d/thin3d_gl.cpp \ + thin3d/thin3d_vulkan.cpp \ + thin3d/VulkanContext.cpp \ ui/view.cpp \ ui/viewgroup.cpp \ ui/ui.cpp \ @@ -94,7 +96,7 @@ LOCAL_SRC_FILES :=\ LOCAL_CFLAGS := -O3 -DUSING_GLES2 -fsigned-char -fno-strict-aliasing -Wall -Wno-multichar -D__STDC_CONSTANT_MACROS LOCAL_CPPFLAGS := -fno-exceptions -std=gnu++11 -fno-rtti -Wno-reorder -LOCAL_C_INCLUDES := $(LOCAL_PATH)/ext $(LOCAL_PATH)/ext/libzip +LOCAL_C_INCLUDES := $(LOCAL_PATH)/ext $(LOCAL_PATH)/ext/libzip .. #Portable native and separate code on android in future is easy you needs add files #by ($(target_arch_ABI),arquitecture (armeabi-v7a , armeabi , x86 , MIPS) diff --git a/ext/native/thin3d/VulkanContext.cpp b/ext/native/thin3d/VulkanContext.cpp index 4d47968627..d0634669a9 100644 --- a/ext/native/thin3d/VulkanContext.cpp +++ b/ext/native/thin3d/VulkanContext.cpp @@ -1,4 +1,6 @@ +#define __STDC_LIMIT_MACROS #include +#include #include #include #include @@ -9,73 +11,70 @@ #undef new #endif +#ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4996) -#include "glslang/SPIRV/GlslangToSpv.h" +#endif + +#include "ext/glslang/SPIRV/GlslangToSpv.h" + +#ifdef _MSC_VER #pragma warning(pop) +#endif #ifdef USE_CRT_DBG #define new DBG_NEW #endif -#define GET_INSTANCE_PROC_ADDR(inst, entrypoint) \ -{ \ - fp##entrypoint = (PFN_vk##entrypoint) vkGetInstanceProcAddr(inst, "vk"#entrypoint); \ - if (fp##entrypoint == NULL) { \ - std::cout << "vkGetDeviceProcAddr failed to find vk"#entrypoint; \ - exit(-1); \ - } \ -} - -#define GET_DEVICE_PROC_ADDR(dev, entrypoint) \ -{ \ - fp##entrypoint = (PFN_vk##entrypoint) vkGetDeviceProcAddr(dev, "vk"#entrypoint); \ - if (fp##entrypoint == NULL) { \ - std::cout << "vkGetDeviceProcAddr failed to find vk"#entrypoint; \ - exit(-1); \ - } \ -} - using namespace std; VulkanContext::VulkanContext(const char *app_name, uint32_t flags) : device_(nullptr), - gfx_queue_(nullptr), + gfx_queue_(VK_NULL_HANDLE), +#ifdef _WIN32 connection(nullptr), - graphics_queue_family_index_(-1), - surface(nullptr), window(nullptr), +#elif defined(ANDROID) + native_window(nullptr), +#endif + graphics_queue_family_index_(-1), + surface(VK_NULL_HANDLE), prepared(false), use_staging_buffer_(false), - instance_(nullptr), + instance_(VK_NULL_HANDLE), width(0), height(0), flags_(flags), swapchain_format(VK_FORMAT_UNDEFINED), swapchainImageCount(0), - swap_chain_(nullptr), - cmd_pool_(nullptr), - dbgCreateMsgCallback(nullptr), - dbgDestroyMsgCallback(nullptr), + swap_chain_(VK_NULL_HANDLE), + cmd_pool_(VK_NULL_HANDLE), queue_count(0), curFrame_(0) { + if (!VulkanLoad()) { + // No DLL? + return; + } // List extensions to try to enable. instance_extension_names.push_back(VK_KHR_SURFACE_EXTENSION_NAME); +#ifdef _WIN32 instance_extension_names.push_back(VK_KHR_WIN32_SURFACE_EXTENSION_NAME); +#elif defined(ANDROID) + instance_extension_names.push_back(VK_KHR_ANDROID_SURFACE_EXTENSION_NAME); +#endif device_extension_names.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME); - // DrawState validation is broken, hangs on vkResetDescriptorPool. if (flags & VULKAN_FLAG_VALIDATE) { instance_layer_names.push_back("VK_LAYER_LUNARG_threading"); - // instance_layer_names.push_back("VK_LAYER_LUNARG_draw_state"); + instance_layer_names.push_back("VK_LAYER_LUNARG_draw_state"); instance_layer_names.push_back("VK_LAYER_LUNARG_image"); instance_layer_names.push_back("VK_LAYER_LUNARG_mem_tracker"); instance_layer_names.push_back("VK_LAYER_LUNARG_object_tracker"); instance_layer_names.push_back("VK_LAYER_LUNARG_param_checker"); device_layer_names.push_back("VK_LAYER_LUNARG_threading"); - // device_layer_names.push_back("VK_LAYER_LUNARG_draw_state"); + device_layer_names.push_back("VK_LAYER_LUNARG_draw_state"); device_layer_names.push_back("VK_LAYER_LUNARG_image"); device_layer_names.push_back("VK_LAYER_LUNARG_mem_tracker"); device_layer_names.push_back("VK_LAYER_LUNARG_object_tracker"); @@ -106,10 +105,7 @@ VulkanContext::VulkanContext(const char *app_name, uint32_t flags) VkResult res = vkCreateInstance(&inst_info, NULL, &instance_); assert(res == VK_SUCCESS); - GET_INSTANCE_PROC_ADDR(instance_, GetPhysicalDeviceSurfaceSupportKHR); - GET_INSTANCE_PROC_ADDR(instance_, GetPhysicalDeviceSurfaceCapabilitiesKHR); - GET_INSTANCE_PROC_ADDR(instance_, GetPhysicalDeviceSurfaceFormatsKHR); - GET_INSTANCE_PROC_ADDR(instance_, GetPhysicalDeviceSurfacePresentModesKHR); + VulkanLoadInstanceFunctions(instance_); uint32_t gpu_count = 1; res = vkEnumeratePhysicalDevices(instance_, &gpu_count, NULL); @@ -133,6 +129,7 @@ VulkanContext::VulkanContext(const char *app_name, uint32_t flags) VulkanContext::~VulkanContext() { vkDestroyInstance(instance_, NULL); + VulkanFree(); } void TransitionToPresent(VkCommandBuffer cmd, VkImage image) { @@ -193,8 +190,7 @@ VkCommandBuffer VulkanContext::BeginSurfaceRenderPass(VkClearValue clear_values[ // Get the index of the next available swapchain image, and a semaphore to block command buffer execution on. // Now, I wonder if we should do this early in the frame or late? Right now we do it early, which should be fine. - VkResult res = fpAcquireNextImageKHR(device_, swap_chain_, - UINT64_MAX, acquireSemaphore, NULL, ¤t_buffer); + VkResult res = vkAcquireNextImageKHR(device_, swap_chain_, UINT64_MAX, acquireSemaphore, NULL, ¤t_buffer); // TODO: Deal with the VK_SUBOPTIMAL_KHR and VK_ERROR_OUT_OF_DATE_KHR // return codes @@ -282,7 +278,7 @@ void VulkanContext::EndSurfaceRenderPass() { present.waitSemaphoreCount = 0; present.pResults = NULL; - res = fpQueuePresentKHR(gfx_queue_, &present); + res = vkQueuePresentKHR(gfx_queue_, &present); // TODO: Deal with the VK_SUBOPTIMAL_WSI and VK_ERROR_OUT_OF_DATE_WSI // return codes assert(!res); @@ -645,11 +641,7 @@ VkResult VulkanContext::CreateDevice(int physical_device) { res = vkCreateDevice(physical_devices_[0], &device_info, NULL, &device_); assert(res == VK_SUCCESS); - GET_DEVICE_PROC_ADDR(device_, CreateSwapchainKHR); - GET_DEVICE_PROC_ADDR(device_, DestroySwapchainKHR); - GET_DEVICE_PROC_ADDR(device_, GetSwapchainImagesKHR); - GET_DEVICE_PROC_ADDR(device_, AcquireNextImageKHR); - GET_DEVICE_PROC_ADDR(device_, QueuePresentKHR); + VulkanLoadDeviceFunctions(device_); return res; } @@ -658,25 +650,13 @@ VkResult VulkanContext::InitDebugMsgCallback(PFN_vkDebugReportCallbackEXT dbgFun VkResult res; VkDebugReportCallbackEXT msg_callback; - dbgCreateMsgCallback = (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(instance_, "vkCreateDebugReportCallbackEXT"); - if (!dbgCreateMsgCallback) { - std::cout << "GetInstanceProcAddr: Unable to find vkDbgCreateMsgCallback function." << std::endl; - return VK_ERROR_INITIALIZATION_FAILED; - } - - dbgDestroyMsgCallback = (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(instance_, "vkDestroyDebugReportCallbackEXT"); - if (!dbgDestroyMsgCallback) { - std::cout << "GetInstanceProcAddr: Unable to find vkDbgDestroyMsgCallback function." << std::endl; - return VK_ERROR_INITIALIZATION_FAILED; - } - VkDebugReportCallbackCreateInfoEXT cb; cb.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT; cb.pNext = nullptr; cb.flags = bits; cb.pfnCallback = dbgFunc; cb.pUserData = userdata; - res = dbgCreateMsgCallback(instance_, &cb, nullptr, &msg_callback); + res = vkCreateDebugReportCallbackEXT(instance_, &cb, nullptr, &msg_callback); switch (res) { case VK_SUCCESS: msg_callbacks.push_back(msg_callback); @@ -695,7 +675,7 @@ VkResult VulkanContext::InitDebugMsgCallback(PFN_vkDebugReportCallbackEXT dbgFun void VulkanContext::DestroyDebugMsgCallback() { while (msg_callbacks.size() > 0) { - dbgDestroyMsgCallback(instance_, msg_callbacks.back(), nullptr); + vkDestroyDebugReportCallbackEXT(instance_, msg_callbacks.back(), nullptr); msg_callbacks.pop_back(); } } @@ -816,9 +796,8 @@ void VulkanContext::InitSurfaceWin32(HINSTANCE conn, HWND wnd) { assert(res == VK_SUCCESS); } #elif defined(ANDROID) -void VulkanContext::InitSurfaceAndroid(ANativeWindow *native_window, int width, int height) { - connection = conn; - window = wnd; +void VulkanContext::InitSurfaceAndroid(ANativeWindow *wnd, int width, int height) { + native_window = wnd; VkResult U_ASSERT_ONLY res; @@ -840,7 +819,7 @@ void VulkanContext::InitQueue() { // Iterate over each queue to learn whether it supports presenting: VkBool32* supportsPresent = new VkBool32[queue_count]; for (uint32_t i = 0; i < queue_count; i++) { - fpGetPhysicalDeviceSurfaceSupportKHR(physical_devices_[0], i, surface, &supportsPresent[i]); + vkGetPhysicalDeviceSurfaceSupportKHR(physical_devices_[0], i, surface, &supportsPresent[i]); } // Search for a graphics queue and a present queue in the array of queue @@ -882,12 +861,12 @@ void VulkanContext::InitQueue() { // Get the list of VkFormats that are supported: uint32_t formatCount; - VkResult res = fpGetPhysicalDeviceSurfaceFormatsKHR(physical_devices_[0], + VkResult res = vkGetPhysicalDeviceSurfaceFormatsKHR(physical_devices_[0], surface, &formatCount, NULL); assert(res == VK_SUCCESS); VkSurfaceFormatKHR *surfFormats = new VkSurfaceFormatKHR[formatCount]; - res = fpGetPhysicalDeviceSurfaceFormatsKHR(physical_devices_[0], + res = vkGetPhysicalDeviceSurfaceFormatsKHR(physical_devices_[0], surface, &formatCount, surfFormats); assert(res == VK_SUCCESS); @@ -920,26 +899,26 @@ void VulkanContext::InitSwapchain(VkCommandBuffer cmd) { VkResult U_ASSERT_ONLY res; VkSurfaceCapabilitiesKHR surfCapabilities; - res = fpGetPhysicalDeviceSurfaceCapabilitiesKHR(physical_devices_[0], + res = vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physical_devices_[0], surface, &surfCapabilities); assert(res == VK_SUCCESS); uint32_t presentModeCount; - res = fpGetPhysicalDeviceSurfacePresentModesKHR(physical_devices_[0], + res = vkGetPhysicalDeviceSurfacePresentModesKHR(physical_devices_[0], surface, &presentModeCount, NULL); assert(res == VK_SUCCESS); VkPresentModeKHR *presentModes = new VkPresentModeKHR[presentModeCount]; assert(presentModes); - res = fpGetPhysicalDeviceSurfacePresentModesKHR(physical_devices_[0], + res = vkGetPhysicalDeviceSurfacePresentModesKHR(physical_devices_[0], surface, &presentModeCount, presentModes); assert(res == VK_SUCCESS); VkExtent2D swapChainExtent; // width and height are either both -1, or both not -1. - if (surfCapabilities.currentExtent.width == -1) { + if (surfCapabilities.currentExtent.width == (uint32_t)-1) { // If the surface size is undefined, the size is set to // the size of the images requested. swapChainExtent.width = width; @@ -1006,16 +985,16 @@ void VulkanContext::InitSwapchain(VkCommandBuffer cmd) { swap_chain_info.queueFamilyIndexCount = 0; swap_chain_info.pQueueFamilyIndices = NULL; - res = fpCreateSwapchainKHR(device_, &swap_chain_info, NULL, &swap_chain_); + res = vkCreateSwapchainKHR(device_, &swap_chain_info, NULL, &swap_chain_); assert(res == VK_SUCCESS); - res = fpGetSwapchainImagesKHR(device_, swap_chain_, + res = vkGetSwapchainImagesKHR(device_, swap_chain_, &swapchainImageCount, NULL); assert(res == VK_SUCCESS); VkImage* swapchainImages = (VkImage*)malloc(swapchainImageCount * sizeof(VkImage)); assert(swapchainImages); - res = fpGetSwapchainImagesKHR(device_, swap_chain_, &swapchainImageCount, swapchainImages); + res = vkGetSwapchainImagesKHR(device_, swap_chain_, &swapchainImageCount, swapchainImages); assert(res == VK_SUCCESS); for (uint32_t i = 0; i < swapchainImageCount; i++) { @@ -1175,12 +1154,12 @@ VkResult VulkanTexture::Create(int w, int h, VkFormat format) { void VulkanTexture::CreateMappableImage() { // If we already have a mappableImage, forget it. if (mappableImage) { - vulkan_->QueueDelete(mappableImage); - mappableImage = nullptr; + vulkan_->Delete().QueueDeleteImage(mappableImage); + mappableImage = VK_NULL_HANDLE; } if (mappableMemory) { - vulkan_->QueueDelete(mappableMemory); - mappableMemory = nullptr; + vulkan_->Delete().QueueDeleteDeviceMemory(mappableMemory); + mappableMemory = VK_NULL_HANDLE; } bool U_ASSERT_ONLY pass; @@ -1257,16 +1236,16 @@ void VulkanTexture::Unlock() { // if we already have an image, queue it for destruction and forget it. if (image) { - vulkan_->QueueDelete(image); - image = nullptr; + vulkan_->Delete().QueueDeleteImage(image); + image = VK_NULL_HANDLE; } if (view) { - vulkan_->QueueDelete(view); - view = nullptr; + vulkan_->Delete().QueueDeleteImageView(view); + view = VK_NULL_HANDLE; } if (mem) { - vulkan_->QueueDelete(mem); - mem = nullptr; + vulkan_->Delete().QueueDeleteDeviceMemory(mem); + mem = VK_NULL_HANDLE; } if (!needStaging) { /* If we can use the linear tiled image as a texture, just do it */ @@ -1362,10 +1341,10 @@ void VulkanTexture::Unlock() { VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, imageLayout); - vulkan_->QueueDelete(mappableMemory); - vulkan_->QueueDelete(mappableImage); - mappableImage = nullptr; - mappableMemory = nullptr; + vulkan_->Delete().QueueDeleteDeviceMemory(mappableMemory); + vulkan_->Delete().QueueDeleteImage(mappableImage); + mappableImage = VK_NULL_HANDLE; + mappableMemory = VK_NULL_HANDLE; } VkImageViewCreateInfo view_info = {}; @@ -1392,24 +1371,24 @@ void VulkanTexture::Unlock() { void VulkanTexture::Destroy() { if (view) { - vulkan_->QueueDelete(view); + vulkan_->Delete().QueueDeleteImageView(view); } if (image) { - vulkan_->QueueDelete(image); + vulkan_->Delete().QueueDeleteImage(image); if (mappableImage == image) { - mappableImage = nullptr; + mappableImage = VK_NULL_HANDLE; } } if (mem) { - vulkan_->QueueDelete(mem); + vulkan_->Delete().QueueDeleteDeviceMemory(mem); if (mappableMemory == mem) { - mappableMemory = nullptr; + mappableMemory = VK_NULL_HANDLE; } } - view = nullptr; - image = nullptr; - mem = nullptr; + view = VK_NULL_HANDLE; + image = VK_NULL_HANDLE; + mem = VK_NULL_HANDLE; } VkFence VulkanContext::CreateFence(bool presignalled) { @@ -1429,24 +1408,24 @@ void VulkanContext::WaitAndResetFence(VkFence fence) { void VulkanContext::DestroyCommandPool() { vkDestroyCommandPool(device_, cmd_pool_, NULL); - cmd_pool_ = nullptr; + cmd_pool_ = VK_NULL_HANDLE; } void VulkanContext::DestroyDepthStencilBuffer() { vkDestroyImageView(device_, depth.view, NULL); vkDestroyImage(device_, depth.image, NULL); vkFreeMemory(device_, depth.mem, NULL); - depth.view = NULL; - depth.image = NULL; - depth.mem = NULL; + depth.view = VK_NULL_HANDLE; + depth.image = VK_NULL_HANDLE; + depth.mem = VK_NULL_HANDLE; } void VulkanContext::DestroySwapChain() { for (uint32_t i = 0; i < swapchainImageCount; i++) { vkDestroyImageView(device_, swapChainBuffers[i].view, NULL); } - fpDestroySwapchainKHR(device_, swap_chain_, NULL); - swap_chain_ = nullptr; + vkDestroySwapchainKHR(device_, swap_chain_, NULL); + swap_chain_ = VK_NULL_HANDLE; swapChainBuffers.clear(); vkDestroySemaphore(device_, acquireSemaphore, NULL); } @@ -1772,5 +1751,5 @@ void VulkanFramebuffer::TransitionToTexture(VkCommandBuffer cmd) { } VkImageView VulkanFramebuffer::GetColorImageView() { - return nullptr; + return VK_NULL_HANDLE; } diff --git a/ext/native/thin3d/VulkanContext.h b/ext/native/thin3d/VulkanContext.h index c721ac4925..1b7ac7ce9c 100644 --- a/ext/native/thin3d/VulkanContext.h +++ b/ext/native/thin3d/VulkanContext.h @@ -44,8 +44,7 @@ #include #endif // _WIN32 -#include "vulkan/vulkan.h" -#include "vulkan/vk_sdk_platform.h" +#include "Common/Vulkan/VulkanLoader.h" /* Amount of time, in nanoseconds, to wait for a command buffer to complete */ #define FENCE_TIMEOUT 10000000000 @@ -72,15 +71,15 @@ struct layer_properties { // This is a bit repetitive... class VulkanDeleteList { public: - void QueueDelete(VkDescriptorPool pool) { descPools_.push_back(pool); } - void QueueDelete(VkShaderModule module) { modules_.push_back(module); } - void QueueDelete(VkBuffer buffer) { buffers_.push_back(buffer); } - void QueueDelete(VkBufferView bufferView) { bufferViews_.push_back(bufferView); } - void QueueDelete(VkImage image) { images_.push_back(image); } - void QueueDelete(VkImageView imageView) { imageViews_.push_back(imageView); } - void QueueDelete(VkDeviceMemory deviceMemory) { deviceMemory_.push_back(deviceMemory); } - void QueueDelete(VkSampler sampler) { samplers_.push_back(sampler); } - void QueueDelete(VkPipelineCache pipelineCache) { pipelineCaches_.push_back(pipelineCache); } + void QueueDeleteDescriptorPool(VkDescriptorPool pool) { descPools_.push_back(pool); } + void QueueDeleteShaderModule(VkShaderModule module) { modules_.push_back(module); } + void QueueDeleteBuffer(VkBuffer buffer) { buffers_.push_back(buffer); } + void QueueDeleteBufferView(VkBufferView bufferView) { bufferViews_.push_back(bufferView); } + void QueueDeleteImage(VkImage image) { images_.push_back(image); } + void QueueDeleteImageView(VkImageView imageView) { imageViews_.push_back(imageView); } + void QueueDeleteDeviceMemory(VkDeviceMemory deviceMemory) { deviceMemory_.push_back(deviceMemory); } + void QueueDeleteSampler(VkSampler sampler) { samplers_.push_back(sampler); } + void QueueDeletePipelineCache(VkPipelineCache pipelineCache) { pipelineCaches_.push_back(pipelineCache); } void Take(VulkanDeleteList &del) { descPools_ = std::move(del.descPools_); @@ -154,10 +153,7 @@ public: return device_; } - template - void QueueDelete(T mem) { - globalDeleteList_.QueueDelete(mem); - } + VulkanDeleteList &Delete() { return globalDeleteList_; } VkPipelineCache CreatePipelineCache(); @@ -254,7 +250,7 @@ private: #ifdef _WIN32 HINSTANCE connection; // hInstance - Windows Instance - HWND window; // hWnd - window handle + HWND window; // hWnd - window handle #elif ANDROID // _WIN32 ANativeWindow *native_window; #else @@ -325,19 +321,6 @@ private: // the next time the frame comes around again. VulkanDeleteList globalDeleteList_; - // Simple loader for the WSI extension. - PFN_vkGetPhysicalDeviceSurfaceSupportKHR fpGetPhysicalDeviceSurfaceSupportKHR; - PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR fpGetPhysicalDeviceSurfaceCapabilitiesKHR; - PFN_vkGetPhysicalDeviceSurfaceFormatsKHR fpGetPhysicalDeviceSurfaceFormatsKHR; - PFN_vkGetPhysicalDeviceSurfacePresentModesKHR fpGetPhysicalDeviceSurfacePresentModesKHR; - PFN_vkCreateSwapchainKHR fpCreateSwapchainKHR; - PFN_vkDestroySwapchainKHR fpDestroySwapchainKHR; - PFN_vkGetSwapchainImagesKHR fpGetSwapchainImagesKHR; - PFN_vkAcquireNextImageKHR fpAcquireNextImageKHR; - PFN_vkQueuePresentKHR fpQueuePresentKHR; - // And the DEBUG_REPORT extension. - PFN_vkCreateDebugReportCallbackEXT dbgCreateMsgCallback; - PFN_vkDestroyDebugReportCallbackEXT dbgDestroyMsgCallback; std::vector msg_callbacks; struct { @@ -363,8 +346,8 @@ private: class VulkanTexture { public: VulkanTexture(VulkanContext *vulkan) - : vulkan_(vulkan), image(nullptr), imageLayout(VK_IMAGE_LAYOUT_UNDEFINED), mem(nullptr), view(nullptr), tex_width(0), tex_height(0), format_(VK_FORMAT_UNDEFINED), - mappableImage(nullptr), mappableMemory(nullptr), needStaging(false) { + : vulkan_(vulkan), image(0), imageLayout(VK_IMAGE_LAYOUT_UNDEFINED), mem(0), view(0), tex_width(0), tex_height(0), format_(VK_FORMAT_UNDEFINED), + mappableImage(0), mappableMemory(0), needStaging(false) { memset(&mem_reqs, 0, sizeof(mem_reqs)); } ~VulkanTexture() { @@ -424,7 +407,7 @@ private: // buffer handle on overflow. class VulkanPushBuffer { public: - VulkanPushBuffer(VulkanContext *vulkan, size_t size) : offset_(0), size_(size), writePtr_(nullptr), deviceMemory_(nullptr) { + VulkanPushBuffer(VulkanContext *vulkan, size_t size) : offset_(0), size_(size), writePtr_(nullptr), deviceMemory_(0) { VkDevice device = vulkan->GetDevice(); VkBufferCreateInfo b = {}; @@ -453,8 +436,8 @@ public: } void Destroy(VulkanContext *vulkan) { - vulkan->QueueDelete(buffer_); - vulkan->QueueDelete(deviceMemory_); + vulkan->Delete().QueueDeleteBuffer(buffer_); + vulkan->Delete().QueueDeleteDeviceMemory(deviceMemory_); } void Reset() { offset_ = 0; } diff --git a/ext/native/thin3d/thin3d_vulkan.cpp b/ext/native/thin3d/thin3d_vulkan.cpp index c91d9e7c3e..660c12c918 100644 --- a/ext/native/thin3d/thin3d_vulkan.cpp +++ b/ext/native/thin3d/thin3d_vulkan.cpp @@ -38,8 +38,7 @@ // // Vertex data lives in a separate namespace (location = 0, 1, etc) -#define VK_PROTOTYPES -#include "ext/vulkan/vulkan.h" +#include "Common/Vulkan/VulkanLoader.h" // This can actually be replaced with a cast as the values are in the right order. static const VkCompareOp compToVK[] = { @@ -186,7 +185,7 @@ private: // invoke Compile again to recreate the shader then link them together. class Thin3DVKShader : public Thin3DShader { public: - Thin3DVKShader(bool isFragmentShader) : module_(nullptr), ok_(false) { + Thin3DVKShader(bool isFragmentShader) : module_(VK_NULL_HANDLE), ok_(false) { stage_ = isFragmentShader ? VK_SHADER_STAGE_FRAGMENT_BIT : VK_SHADER_STAGE_VERTEX_BIT; } bool Compile(VulkanContext *vulkan, const char *source); @@ -894,7 +893,7 @@ VkPipeline Thin3DVKContext::GetOrCreatePipeline() { VkResult result = vkCreateGraphicsPipelines(device_, pipelineCache_, 1, &info, nullptr, &pipeline); if (result != VK_SUCCESS) { ELOG("Failed to create graphics pipeline"); - return nullptr; + return VK_NULL_HANDLE; } pipelines_.insert(std::make_pair(key, pipeline)); From 45cf39909199babc3e153982c37592818e8dd445 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 21 Feb 2016 19:20:46 +0100 Subject: [PATCH 053/116] Remove remains of xcb support. Will add back later. --- ext/native/thin3d/VulkanContext.h | 8 -------- 1 file changed, 8 deletions(-) diff --git a/ext/native/thin3d/VulkanContext.h b/ext/native/thin3d/VulkanContext.h index 1b7ac7ce9c..18522117de 100644 --- a/ext/native/thin3d/VulkanContext.h +++ b/ext/native/thin3d/VulkanContext.h @@ -161,9 +161,6 @@ public: void InitSurfaceWin32(HINSTANCE conn, HWND wnd); #elif ANDROID void InitSurfaceAndroid(ANativeWindow *native_window, int width, int height); -#else - //void InitSurfaceAndQueueXcb(); -#error Vulkan not supported on this platform #endif void InitQueue(); void InitObjects(bool depthPresent); @@ -253,11 +250,6 @@ private: HWND window; // hWnd - window handle #elif ANDROID // _WIN32 ANativeWindow *native_window; -#else - xcb_connection_t *connection; - xcb_screen_t *screen; - xcb_window_t window; - xcb_intern_atom_reply_t *atom_wm_delete_window; #endif // _WIN32 // TODO: Move to frame data From c8e06675bb78817ea92231e1476704b92d54abd5 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 21 Feb 2016 19:23:31 +0100 Subject: [PATCH 054/116] Possible buildfix --- ext/native/thin3d/VulkanContext.h | 1 + 1 file changed, 1 insertion(+) diff --git a/ext/native/thin3d/VulkanContext.h b/ext/native/thin3d/VulkanContext.h index 18522117de..e1c428e433 100644 --- a/ext/native/thin3d/VulkanContext.h +++ b/ext/native/thin3d/VulkanContext.h @@ -29,6 +29,7 @@ #include #include #include +#include #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN From d325aa2b3094a0ae4bcb8362d4efd2da4ca23f66 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 21 Feb 2016 20:21:24 +0100 Subject: [PATCH 055/116] Hook up Vulkan on Android, no idea if it works. Move VulkanContext to Common. --- Common/Common.vcxproj | 2 + Common/Common.vcxproj.filters | 6 + .../Vulkan}/VulkanContext.cpp | 0 .../thin3d => Common/Vulkan}/VulkanContext.h | 0 GPU/Vulkan/FramebufferVulkan.cpp | 2 +- GPU/Vulkan/PipelineManagerVulkan.cpp | 3 +- GPU/Vulkan/ShaderManagerVulkan.cpp | 3 +- GPU/Vulkan/TextureCacheVulkan.cpp | 2 +- GPU/Vulkan/TextureCacheVulkan.h | 2 +- Windows/GPU/WindowsVulkanContext.cpp | 2 +- android/jni/Android.mk | 1 + android/jni/app-android.cpp | 160 +++++++++++++++++- ext/native/Android.mk | 1 - ext/native/native.vcxproj | 4 +- ext/native/native.vcxproj.filters | 6 - ext/native/thin3d/thin3d_vulkan.cpp | 2 +- 16 files changed, 174 insertions(+), 22 deletions(-) rename {ext/native/thin3d => Common/Vulkan}/VulkanContext.cpp (100%) rename {ext/native/thin3d => Common/Vulkan}/VulkanContext.h (100%) diff --git a/Common/Common.vcxproj b/Common/Common.vcxproj index 59f1e261fc..e11012bc8f 100644 --- a/Common/Common.vcxproj +++ b/Common/Common.vcxproj @@ -241,6 +241,7 @@ + @@ -311,6 +312,7 @@ + diff --git a/Common/Common.vcxproj.filters b/Common/Common.vcxproj.filters index 8f32f6e506..e5bc85c777 100644 --- a/Common/Common.vcxproj.filters +++ b/Common/Common.vcxproj.filters @@ -64,6 +64,9 @@ Vulkan + + Vulkan + @@ -115,6 +118,9 @@ Vulkan + + Vulkan + diff --git a/ext/native/thin3d/VulkanContext.cpp b/Common/Vulkan/VulkanContext.cpp similarity index 100% rename from ext/native/thin3d/VulkanContext.cpp rename to Common/Vulkan/VulkanContext.cpp diff --git a/ext/native/thin3d/VulkanContext.h b/Common/Vulkan/VulkanContext.h similarity index 100% rename from ext/native/thin3d/VulkanContext.h rename to Common/Vulkan/VulkanContext.h diff --git a/GPU/Vulkan/FramebufferVulkan.cpp b/GPU/Vulkan/FramebufferVulkan.cpp index ae5c1ca13e..14f17ba6a8 100644 --- a/GPU/Vulkan/FramebufferVulkan.cpp +++ b/GPU/Vulkan/FramebufferVulkan.cpp @@ -22,8 +22,8 @@ #include "base/timeutil.h" #include "math/lin/matrix4x4.h" -#include "thin3d/VulkanContext.h" +#include "Common/Vulkan/VulkanContext.h" #include "Common/ColorConv.h" #include "Core/Host.h" #include "Core/MemMap.h" diff --git a/GPU/Vulkan/PipelineManagerVulkan.cpp b/GPU/Vulkan/PipelineManagerVulkan.cpp index a666094708..06e6733d8e 100644 --- a/GPU/Vulkan/PipelineManagerVulkan.cpp +++ b/GPU/Vulkan/PipelineManagerVulkan.cpp @@ -2,11 +2,10 @@ #include "Common/Log.h" #include "Common/StringUtils.h" +#include "Common/Vulkan/VulkanContext.h" #include "GPU/Vulkan/VulkanUtil.h" #include "GPU/Vulkan/PipelineManagerVulkan.h" #include "GPU/Vulkan/ShaderManagerVulkan.h" -// #include "GPU/Vulkan/" -#include "thin3d/VulkanContext.h" PipelineManagerVulkan::PipelineManagerVulkan(VulkanContext *vulkan) : vulkan_(vulkan) { pipelineCache_ = vulkan->CreatePipelineCache(); diff --git a/GPU/Vulkan/ShaderManagerVulkan.cpp b/GPU/Vulkan/ShaderManagerVulkan.cpp index 691b8667ef..4f062f4e6e 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.cpp +++ b/GPU/Vulkan/ShaderManagerVulkan.cpp @@ -26,8 +26,7 @@ #include "math/math_util.h" #include "math/dataconv.h" #include "util/text/utf8.h" -#include "thin3d/VulkanContext.h" - +#include "Common/Vulkan/VulkanContext.h" #include "Common/Common.h" #include "Core/Config.h" #include "Core/Reporting.h" diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index a38835dff6..bd730d7495 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -22,7 +22,7 @@ #include "i18n/i18n.h" #include "math/math_util.h" #include "profiler/profiler.h" -#include "thin3d/VulkanContext.h" +#include "Common/Vulkan/VulkanContext.h" #include "Common/ColorConv.h" #include "Core/Config.h" #include "Core/Host.h" diff --git a/GPU/Vulkan/TextureCacheVulkan.h b/GPU/Vulkan/TextureCacheVulkan.h index 46bd17688e..17eaabf863 100644 --- a/GPU/Vulkan/TextureCacheVulkan.h +++ b/GPU/Vulkan/TextureCacheVulkan.h @@ -22,7 +22,7 @@ #include "Globals.h" #include "GPU/GPUInterface.h" #include "GPU/GPUState.h" -#include "thin3d/VulkanContext.h" +#include "Common/Vulkan/VulkanContext.h" #include "GPU/Vulkan/TextureScalerVulkan.h" #include "GPU/Common/TextureCacheCommon.h" diff --git a/Windows/GPU/WindowsVulkanContext.cpp b/Windows/GPU/WindowsVulkanContext.cpp index b30f7788e8..95160d7e16 100644 --- a/Windows/GPU/WindowsVulkanContext.cpp +++ b/Windows/GPU/WindowsVulkanContext.cpp @@ -51,7 +51,7 @@ #include #include "Common/Vulkan/VulkanLoader.h" -#include "ext/native/thin3d/VulkanContext.h" +#include "Common/Vulkan/VulkanContext.h" #include "thin3d/thin3d.h" #include "Windows/GPU/WindowsVulkanContext.h" diff --git a/android/jni/Android.mk b/android/jni/Android.mk index fc6cd779ec..c752482e2d 100644 --- a/android/jni/Android.mk +++ b/android/jni/Android.mk @@ -126,6 +126,7 @@ EGL_FILES := \ VULKAN_FILES := \ $(SRC)/Common/Vulkan/VulkanLoader.cpp \ + $(SRC)/Common/Vulkan/VulkanContext.cpp \ $(SRC)/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp \ $(SRC)/GPU/Vulkan/DrawEngineVulkan.cpp \ $(SRC)/GPU/Vulkan/FramebufferVulkan.cpp \ diff --git a/android/jni/app-android.cpp b/android/jni/app-android.cpp index aa66e7923b..23b84a452f 100644 --- a/android/jni/app-android.cpp +++ b/android/jni/app-android.cpp @@ -4,6 +4,9 @@ // It calls a set of methods defined in NativeApp.h. These should be implemented // by your game or app. + +#include +#include #include #include #include @@ -30,8 +33,12 @@ #include "gfx/gl_common.h" #include "gfx_es2/gpu_features.h" +#include "thin3d/thin3d.h" +#include "Core/Config.cpp" #include "Common/GraphicsContext.h" #include "Common/GL/GLInterfaceBase.h" +#include "Common/Vulkan/VulkanLoader.h" +#include "Common/Vulkan/VulkanContext.h" #include "UI/GameInfoCache.h" #include "app-android.h" @@ -56,7 +63,12 @@ struct FrameCommand { std::string params; }; -class AndroidEGLGraphicsContext : public GraphicsContext { +class AndroidGraphicsContext : public GraphicsContext { +public: + virtual bool Init(ANativeWindow *wnd, int desiredBackbufferSizeX, int desiredBackbufferSizeY, int backbufferFormat, int androidVersion) = 0; +}; + +class AndroidEGLGraphicsContext : public AndroidGraphicsContext { public: AndroidEGLGraphicsContext() : wnd_(nullptr), gl(nullptr) {} bool Init(ANativeWindow *wnd, int desiredBackbufferSizeX, int desiredBackbufferSizeY, int backbufferFormat, int androidVersion); @@ -137,6 +149,140 @@ public: }; +static const bool g_validate_ = true; +static VulkanContext *g_Vulkan; + +class AndroidVulkanContext : public AndroidGraphicsContext { +public: + AndroidVulkanContext() {} + bool Init(ANativeWindow *wnd, int desiredBackbufferSizeX, int desiredBackbufferSizeY, int backbufferFormat, int androidVersion) override; + void Shutdown() override; + void SwapInterval(int interval) override; + void SwapBuffers() override; + void Resize() override; + + void *GetAPIContext() { return g_Vulkan; } + + Thin3DContext *CreateThin3DContext() override { + return T3DCreateVulkanContext(g_Vulkan); + } +}; + +struct VulkanLogOptions { + bool breakOnWarning; + bool breakOnError; + bool msgBoxOnError; +}; +static VulkanLogOptions g_LogOptions; + +const char *ObjTypeToString(VkDebugReportObjectTypeEXT type) { + switch (type) { + case VK_DEBUG_REPORT_OBJECT_TYPE_INSTANCE_EXT: return "Instance"; + case VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT: return "PhysicalDevice"; + case VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT: return "Device"; + case VK_DEBUG_REPORT_OBJECT_TYPE_QUEUE_EXT: return "Queue"; + case VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT: return "CommandBuffer"; + case VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT: return "DeviceMemory"; + case VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT: return "Buffer"; + case VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_VIEW_EXT: return "BufferView"; + case VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT: return "Image"; + case VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_VIEW_EXT: return "ImageView"; + case VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT: return "ShaderModule"; + case VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT: return "Pipeline"; + case VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_LAYOUT_EXT: return "PipelineLayout"; + case VK_DEBUG_REPORT_OBJECT_TYPE_SAMPLER_EXT: return "Sampler"; + case VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT: return "DescriptorSet"; + case VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT_EXT: return "DescriptorSetLayout"; + case VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_POOL_EXT: return "DescriptorPool"; + case VK_DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT: return "Fence"; + case VK_DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT: return "Semaphore"; + case VK_DEBUG_REPORT_OBJECT_TYPE_EVENT_EXT: return "Event"; + case VK_DEBUG_REPORT_OBJECT_TYPE_QUERY_POOL_EXT: return "QueryPool"; + case VK_DEBUG_REPORT_OBJECT_TYPE_FRAMEBUFFER_EXT: return "Framebuffer"; + case VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT: return "RenderPass"; + case VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_CACHE_EXT: return "PipelineCache"; + case VK_DEBUG_REPORT_OBJECT_TYPE_SURFACE_KHR_EXT: return "SurfaceKHR"; + case VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT: return "SwapChainKHR"; + case VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_POOL_EXT: return "CommandPool"; + default: return "Unknown"; + } +} + +static VkBool32 VKAPI_CALL Vulkan_Dbg(VkDebugReportFlagsEXT msgFlags, VkDebugReportObjectTypeEXT objType, uint64_t srcObject, size_t location, int32_t msgCode, const char* pLayerPrefix, const char* pMsg, void *pUserData) { + const VulkanLogOptions *options = (const VulkanLogOptions *)pUserData; + int loglevel = ANDROID_LOG_INFO; + if (msgFlags & VK_DEBUG_REPORT_ERROR_BIT_EXT) { + loglevel = ANDROID_LOG_ERROR; + } else if (msgFlags & VK_DEBUG_REPORT_WARNING_BIT_EXT) { + loglevel = ANDROID_LOG_WARN; + } else if (msgFlags & VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT) { + loglevel = ANDROID_LOG_WARN; + } else if (msgFlags & VK_DEBUG_REPORT_INFORMATION_BIT_EXT) { + loglevel = ANDROID_LOG_WARN; + } else if (msgFlags & VK_DEBUG_REPORT_DEBUG_BIT_EXT) { + loglevel = ANDROID_LOG_WARN; + } + + __android_log_print(loglevel, APP_NAME, "[%s] %s Code %d : %s", pLayerPrefix, ObjTypeToString(objType), msgCode, pMsg); + + // false indicates that layer should not bail-out of an + // API call that had validation failures. This may mean that the + // app dies inside the driver due to invalid parameter(s). + // That's what would happen without validation layers, so we'll + // keep that behavior here. + return false; +} + +bool AndroidVulkanContext::Init(ANativeWindow *wnd, int desiredBackbufferSizeX, int desiredBackbufferSizeY, int backbufferFormat, int androidVersion) { + if (g_Vulkan) { + return false; + } + + init_glslang(); + + g_LogOptions.breakOnError = true; + g_LogOptions.breakOnWarning = true; + g_LogOptions.msgBoxOnError = false; + + g_Vulkan = new VulkanContext("PPSSPP", (g_validate_ ? VULKAN_FLAG_VALIDATE : 0) | VULKAN_FLAG_PRESENT_MAILBOX); + g_Vulkan->CreateDevice(0); + if (g_validate_) { + int bits = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT; + g_Vulkan->InitDebugMsgCallback(Vulkan_Dbg, bits, &g_LogOptions); + } + g_Vulkan->InitSurfaceAndroid(wnd, desiredBackbufferSizeX, desiredBackbufferSizeY); + g_Vulkan->InitObjects(true); + + return true; +} + +void AndroidVulkanContext::Shutdown() { + g_Vulkan->WaitUntilQueueIdle(); + g_Vulkan->DestroyObjects(); + g_Vulkan->DestroyDebugMsgCallback(); + g_Vulkan->DestroyDevice(); + delete g_Vulkan; + g_Vulkan = nullptr; + + finalize_glslang(); +} + +void AndroidVulkanContext::SwapBuffers() { +} + +void AndroidVulkanContext::Resize() { + /* + g_Vulkan->DestroyObjects(); + + g_Vulkan->WaitUntilQueueIdle(); + + g_Vulkan->InitObjects(g_Vulkan) + */ +} + +void AndroidVulkanContext::SwapInterval(int interval) { +} + static recursive_mutex frameCommandLock; static std::queue frameCommands; @@ -827,8 +973,16 @@ extern "C" bool JNICALL Java_org_ppsspp_ppsspp_NativeActivity_runEGLRenderLoop(J ELOG("Error: Surface is null."); return false; } + + bool vulkan = g_Config.iGPUBackend == GPU_BACKEND_VULKAN; + + AndroidGraphicsContext *graphicsContext; + if (vulkan) { + graphicsContext = new AndroidVulkanContext(); + } else { + graphicsContext = new AndroidEGLGraphicsContext(); + } - AndroidEGLGraphicsContext *graphicsContext = new AndroidEGLGraphicsContext(); if (!graphicsContext->Init(wnd, desiredBackbufferSizeX, desiredBackbufferSizeY, backbuffer_format, androidVersion)) { ELOG("Failed to initialize graphics context."); delete graphicsContext; @@ -883,7 +1037,7 @@ extern "C" bool JNICALL Java_org_ppsspp_ppsspp_NativeActivity_runEGLRenderLoop(J renderer_inited = false; graphicsContext->Shutdown(); - + delete graphicsContext; renderLoopRunning = false; WLOG("Render loop function exited."); return true; diff --git a/ext/native/Android.mk b/ext/native/Android.mk index 9ac0f5f8db..1f3eea6530 100644 --- a/ext/native/Android.mk +++ b/ext/native/Android.mk @@ -82,7 +82,6 @@ LOCAL_SRC_FILES :=\ thin3d/thin3d.cpp \ thin3d/thin3d_gl.cpp \ thin3d/thin3d_vulkan.cpp \ - thin3d/VulkanContext.cpp \ ui/view.cpp \ ui/viewgroup.cpp \ ui/ui.cpp \ diff --git a/ext/native/native.vcxproj b/ext/native/native.vcxproj index 9557ba566e..f750063f7c 100644 --- a/ext/native/native.vcxproj +++ b/ext/native/native.vcxproj @@ -266,7 +266,6 @@ - @@ -729,7 +728,6 @@ - @@ -748,4 +746,4 @@ - + \ No newline at end of file diff --git a/ext/native/native.vcxproj.filters b/ext/native/native.vcxproj.filters index a278eba455..269ac5835d 100644 --- a/ext/native/native.vcxproj.filters +++ b/ext/native/native.vcxproj.filters @@ -308,9 +308,6 @@ math - - thin3d - @@ -748,9 +745,6 @@ thin3d - - thin3d - diff --git a/ext/native/thin3d/thin3d_vulkan.cpp b/ext/native/thin3d/thin3d_vulkan.cpp index 660c12c918..bf8d412fcc 100644 --- a/ext/native/thin3d/thin3d_vulkan.cpp +++ b/ext/native/thin3d/thin3d_vulkan.cpp @@ -30,7 +30,7 @@ #include "math/lin/matrix4x4.h" #include "math/dataconv.h" #include "thin3d/thin3d.h" -#include "thin3d/VulkanContext.h" +#include "Common/Vulkan/VulkanContext.h" // We use a simple descriptor set for all rendering: 1 sampler, 1 texture, 1 UBO binding point. // binding 0 - uniform data From 96273c661650dc594978fafc3c6a33510742302e Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 21 Feb 2016 22:12:19 +0100 Subject: [PATCH 056/116] Turn off Vulkan in CMake-based and Qt-based builds, for now --- CMakeLists.txt | 3 +++ GPU/GPU.cpp | 4 ++++ Qt/Common.pro | 1 + Qt/Settings.pri | 2 +- 4 files changed, 9 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index f4185d47ac..e6f437726e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -6,6 +6,9 @@ set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_SOURCE_DIR}/CMakeTests) add_definitions(-DPPSSPP) +# None of these platforms support Vulkan yet. +add_definitions(-DNO_VULKAN) + if(CMAKE_SIZEOF_VOID_P EQUAL 8) set(_ARCH_64 1) add_definitions(-D_ARCH_64=1) diff --git a/GPU/GPU.cpp b/GPU/GPU.cpp index 5365e7dd42..eb02c65748 100644 --- a/GPU/GPU.cpp +++ b/GPU/GPU.cpp @@ -21,7 +21,9 @@ #include "GPU/GPU.h" #include "GPU/GPUInterface.h" #include "GPU/GLES/GLES_GPU.h" +#ifndef NO_VULKAN #include "GPU/Vulkan/GPU_Vulkan.h" +#endif #include "GPU/Null/NullGpu.h" #include "GPU/Software/SoftGpu.h" @@ -61,9 +63,11 @@ bool GPU_Init(GraphicsContext *ctx) { break; case GPU_DIRECTX11: return nullptr; +#ifndef NO_VULKAN case GPU_VULKAN: SetGPU(new GPU_Vulkan(ctx)); break; +#endif } return gpu != NULL; diff --git a/Qt/Common.pro b/Qt/Common.pro index 3a9b41a5ec..6aa505554d 100644 --- a/Qt/Common.pro +++ b/Qt/Common.pro @@ -72,4 +72,5 @@ HEADERS += $$P/Common/ChunkFile.h \ $$P/Common/Crypto/*.h INCLUDEPATH += $$P/ext/native +INCLUDEPATH += $$P/ext diff --git a/Qt/Settings.pri b/Qt/Settings.pri index be855dfa00..83405099dc 100644 --- a/Qt/Settings.pri +++ b/Qt/Settings.pri @@ -1,5 +1,5 @@ VERSION = 1.2.2.0 -DEFINES += USING_QT_UI USE_FFMPEG +DEFINES += USING_QT_UI USE_FFMPEG NO_VULKAN exists( /usr/include/snappy-c.h ) { DEFINES += SHARED_SNAPPY From e97a6c6f77ba2af1753117d4086091489e2f8807 Mon Sep 17 00:00:00 2001 From: Scott Mansell Date: Mon, 22 Feb 2016 17:57:44 +1300 Subject: [PATCH 057/116] VulkanLoader: Load vkDestroySurfaceKHR --- Common/Vulkan/VulkanLoader.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Common/Vulkan/VulkanLoader.cpp b/Common/Vulkan/VulkanLoader.cpp index 7b6b143510..abd32d091f 100644 --- a/Common/Vulkan/VulkanLoader.cpp +++ b/Common/Vulkan/VulkanLoader.cpp @@ -364,6 +364,8 @@ void VulkanLoadInstanceFunctions(VkInstance instance) { vkCreateAndroidSurfaceKHR = (PFN_vkCreateAndroidSurfaceKHR)vkGetInstanceProcAddr(instance, "vkCreateAndroidSurfaceKHR"); #endif + vkDestroySurfaceKHR = (PFN_vkDestroySurfaceKHR)vkGetInstanceProcAddr(instance, "vkDestroySurfaceKHR"); + vkCreateDebugReportCallbackEXT = (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(instance, "vkCreateDebugReportCallbackEXT"); vkDestroyDebugReportCallbackEXT = (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(instance, "vkDestroyDebugReportCallbackEXT"); } From 77420f799ee7769f682c82d283442712e63ab74b Mon Sep 17 00:00:00 2001 From: Scott Mansell Date: Mon, 22 Feb 2016 17:59:58 +1300 Subject: [PATCH 058/116] VulkanLoader: Detect loader failure on windows. --- Common/Vulkan/VulkanLoader.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Common/Vulkan/VulkanLoader.cpp b/Common/Vulkan/VulkanLoader.cpp index abd32d091f..96cd171eda 100644 --- a/Common/Vulkan/VulkanLoader.cpp +++ b/Common/Vulkan/VulkanLoader.cpp @@ -194,13 +194,13 @@ bool VulkanLoad() { #ifndef _WIN32 vulkanLibrary = dlopen("libvulkan.sh", RTLD_NOW | RTLD_LOCAL); - if (!vulkanLibrary) { - return false; - } #else // LoadLibrary etc vulkanLibrary = LoadLibrary(L"vulkan-1.dll"); #endif + if (!vulkanLibrary) { + return false; + } vkCreateInstance = (PFN_vkCreateInstance)dlsym(vulkanLibrary, "vkCreateInstance"); vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)dlsym(vulkanLibrary, "vkGetInstanceProcAddr"); From 78b878222f92dd747293e3b2257184d1e05e5aff Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Thu, 25 Feb 2016 15:41:45 +0100 Subject: [PATCH 059/116] Show backend chooser on Android so we can choose Vulkan. --- UI/GameSettingsScreen.cpp | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/UI/GameSettingsScreen.cpp b/UI/GameSettingsScreen.cpp index 639dc468ea..2eae30fd1a 100644 --- a/UI/GameSettingsScreen.cpp +++ b/UI/GameSettingsScreen.cpp @@ -135,10 +135,18 @@ void GameSettingsScreen::CreateViews() { tabHolder->AddTab(ms->T("Graphics"), graphicsSettingsScroll); graphicsSettings->Add(new ItemHeader(gr->T("Rendering Mode"))); -#if defined(_WIN32) static const char *renderingBackend[] = { "OpenGL", "Direct3D 9", "Direct3D 11", "Vulkan" }; PopupMultiChoice *renderingBackendChoice = graphicsSettings->Add(new PopupMultiChoice(&g_Config.iGPUBackend, gr->T("Backend"), renderingBackend, GPU_BACKEND_OPENGL, ARRAY_SIZE(renderingBackend), gr->GetName(), screenManager())); renderingBackendChoice->OnChoice.Handle(this, &GameSettingsScreen::OnRenderingBackend); +#if !defined(_WIN32) + renderingBackendChoice->HideChoice(1); // D3D9 + renderingBackendChoice->HideChoice(2); // D3D11 +#else + renderingBackendChoice->HideChoice(2); // D3D11 +#endif +#if !defined(ANDROID) && !defined(_WIN32) + // TODO: Add dynamic runtime check for Vulkan support on Android + renderingBackendChoice->HideChoice(3); #endif static const char *renderingMode[] = { "Non-Buffered Rendering", "Buffered Rendering", "Read Framebuffers To Memory (CPU)", "Read Framebuffers To Memory (GPU)"}; PopupMultiChoice *renderingModeChoice = graphicsSettings->Add(new PopupMultiChoice(&g_Config.iRenderingMode, gr->T("Mode"), renderingMode, 0, ARRAY_SIZE(renderingMode), gr->GetName(), screenManager())); From 9c457da4c9bbea395759c14939d8666149855405 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Thu, 25 Feb 2016 18:52:33 +0100 Subject: [PATCH 060/116] Gets the Vulkan backend running, but not drawing correctly, on Android. Not sure what's wrong, I get a yellow flashing screen. --- Common/Vulkan/VulkanContext.cpp | 131 ++++++----- Common/Vulkan/VulkanContext.h | 16 +- Common/Vulkan/VulkanLoader.cpp | 340 ++++++++++++++-------------- android/jni/app-android.cpp | 18 +- ext/native/thin3d/thin3d_vulkan.cpp | 2 +- 5 files changed, 275 insertions(+), 232 deletions(-) diff --git a/Common/Vulkan/VulkanContext.cpp b/Common/Vulkan/VulkanContext.cpp index d0634669a9..371bb94966 100644 --- a/Common/Vulkan/VulkanContext.cpp +++ b/Common/Vulkan/VulkanContext.cpp @@ -38,7 +38,7 @@ VulkanContext::VulkanContext(const char *app_name, uint32_t flags) native_window(nullptr), #endif graphics_queue_family_index_(-1), - surface(VK_NULL_HANDLE), + surface_(VK_NULL_HANDLE), prepared(false), use_staging_buffer_(false), instance_(VK_NULL_HANDLE), @@ -53,6 +53,7 @@ VulkanContext::VulkanContext(const char *app_name, uint32_t flags) curFrame_(0) { if (!VulkanLoad()) { + ELOG("Failed to load vulkan"); // No DLL? return; } @@ -90,8 +91,12 @@ VulkanContext::VulkanContext(const char *app_name, uint32_t flags) app_info.applicationVersion = 1; app_info.pEngineName = app_name; app_info.engineVersion = 1; +#ifdef ANDROID + // For some strange reason, the Shield TV wants 1.0.2, not 1.0.3. + app_info.apiVersion = VK_MAKE_VERSION(1, 0, 2); +#else app_info.apiVersion = VK_API_VERSION; - +#endif VkInstanceCreateInfo inst_info = {}; inst_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; inst_info.pNext = NULL; @@ -103,6 +108,9 @@ VulkanContext::VulkanContext(const char *app_name, uint32_t flags) inst_info.ppEnabledExtensionNames = instance_extension_names.data(); VkResult res = vkCreateInstance(&inst_info, NULL, &instance_); + if (res != VK_SUCCESS) { + ELOG("Failed to create instance: %d", res); + } assert(res == VK_SUCCESS); VulkanLoadInstanceFunctions(instance_); @@ -118,11 +126,13 @@ VulkanContext::VulkanContext(const char *app_name, uint32_t flags) InitGlobalExtensionProperties(); if (!CheckLayers(instance_layer_properties, instance_layer_names)) { + ELOG("CheckLayers failed"); exit(1); } InitDeviceLayerProperties(); if (!CheckLayers(device_layer_properties, device_layer_names)) { + ELOG("CheckLayers failed (2)"); exit(1); } } @@ -587,7 +597,7 @@ VkResult VulkanContext::CreateDevice(int physical_device) { assert(found); assert(queue_count >= 1); - /* This is as good a place as any to do this */ + // This is as good a place as any to do this vkGetPhysicalDeviceMemoryProperties(physical_devices_[0], &memory_properties); vkGetPhysicalDeviceProperties(physical_devices_[0], &gpu_props); @@ -597,7 +607,6 @@ VkResult VulkanContext::CreateDevice(int physical_device) { queue_info.queueCount = 1; queue_info.pQueuePriorities = queue_priorities; - // Optional features vkGetPhysicalDeviceFeatures(physical_devices_[0], &featuresAvailable_); memset(&featuresEnabled_, 0, sizeof(featuresEnabled_)); @@ -650,7 +659,13 @@ VkResult VulkanContext::InitDebugMsgCallback(PFN_vkDebugReportCallbackEXT dbgFun VkResult res; VkDebugReportCallbackEXT msg_callback; - VkDebugReportCallbackCreateInfoEXT cb; + if (!(flags_ & VULKAN_FLAG_VALIDATE)) { + WLOG("Not registering debug report callback - extension not enabled!"); + return VK_SUCCESS; + } + ILOG("Registering debug report callback"); + + VkDebugReportCallbackCreateInfoEXT cb = {}; cb.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT; cb.pNext = nullptr; cb.flags = bits; @@ -662,13 +677,9 @@ VkResult VulkanContext::InitDebugMsgCallback(PFN_vkDebugReportCallbackEXT dbgFun msg_callbacks.push_back(msg_callback); break; case VK_ERROR_OUT_OF_HOST_MEMORY: - puts("dbgCreateMsgCallback: out of host memory pointer\n"); return VK_ERROR_INITIALIZATION_FAILED; - break; default: - puts("dbgCreateMsgCallback: unknown failure\n"); return VK_ERROR_INITIALIZATION_FAILED; - break; } return res; } @@ -684,13 +695,14 @@ void VulkanContext::InitDepthStencilBuffer(VkCommandBuffer cmd) { VkResult U_ASSERT_ONLY res; bool U_ASSERT_ONLY pass; VkImageCreateInfo image_info = {}; - const VkFormat depth_format = VK_FORMAT_D16_UNORM; + const VkFormat depth_format = VK_FORMAT_D16_UNORM; + // const VkFormat depth_format = VK_FORMAT_D24_UNORM_S8_UINT; VkFormatProperties props; vkGetPhysicalDeviceFormatProperties(physical_devices_[0], depth_format, &props); - if (props.linearTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) { - image_info.tiling = VK_IMAGE_TILING_LINEAR; - } else if (props.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) { + if (props.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) { image_info.tiling = VK_IMAGE_TILING_OPTIMAL; + } else if (props.linearTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) { + image_info.tiling = VK_IMAGE_TILING_LINEAR; } else { /* Try other depth formats? */ std::cout << "VK_FORMAT_D16_UNORM Unsupported.\n"; @@ -719,23 +731,6 @@ void VulkanContext::InitDepthStencilBuffer(VkCommandBuffer cmd) { mem_alloc.allocationSize = 0; mem_alloc.memoryTypeIndex = 0; - VkImageViewCreateInfo view_info = {}; - view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; - view_info.pNext = NULL; - view_info.image = VK_NULL_HANDLE; - view_info.format = depth_format; - view_info.components.r = VK_COMPONENT_SWIZZLE_R; - view_info.components.g = VK_COMPONENT_SWIZZLE_G; - view_info.components.b = VK_COMPONENT_SWIZZLE_B; - view_info.components.a = VK_COMPONENT_SWIZZLE_A; - view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT; - view_info.subresourceRange.baseMipLevel = 0; - view_info.subresourceRange.levelCount = 1; - view_info.subresourceRange.baseArrayLayer = 0; - view_info.subresourceRange.layerCount = 1; - view_info.viewType = VK_IMAGE_VIEW_TYPE_2D; - view_info.flags = 0; - VkMemoryRequirements mem_reqs; depth.format = depth_format; @@ -768,7 +763,23 @@ void VulkanContext::InitDepthStencilBuffer(VkCommandBuffer cmd) { VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); /* Create image view */ + VkImageViewCreateInfo view_info = {}; + view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + view_info.pNext = NULL; view_info.image = depth.image; + view_info.format = depth_format; + view_info.components.r = VK_COMPONENT_SWIZZLE_R; + view_info.components.g = VK_COMPONENT_SWIZZLE_G; + view_info.components.b = VK_COMPONENT_SWIZZLE_B; + view_info.components.a = VK_COMPONENT_SWIZZLE_A; + view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; + view_info.subresourceRange.baseMipLevel = 0; + view_info.subresourceRange.levelCount = 1; + view_info.subresourceRange.baseArrayLayer = 0; + view_info.subresourceRange.layerCount = 1; + view_info.viewType = VK_IMAGE_VIEW_TYPE_2D; + view_info.flags = 0; + res = vkCreateImageView(device_, &view_info, NULL, &depth.view); assert(res == VK_SUCCESS); } @@ -791,7 +802,7 @@ void VulkanContext::InitSurfaceWin32(HINSTANCE conn, HWND wnd) { win32.flags = 0; win32.hwnd = wnd; win32.hinstance = conn; - res = vkCreateWin32SurfaceKHR(instance_, &win32, nullptr, &surface); + res = vkCreateWin32SurfaceKHR(instance_, &win32, nullptr, &surface_); assert(res == VK_SUCCESS); } @@ -803,14 +814,14 @@ void VulkanContext::InitSurfaceAndroid(ANativeWindow *wnd, int width, int height VkAndroidSurfaceCreateInfoKHR android; android.sType = VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR; + android.pNext = nullptr; android.flags = 0; android.window = native_window; - android.pNext = nullptr; - res = vkCreateAndroidSurfaceKHR(instance_, &android, nullptr, &surface); + res = vkCreateAndroidSurfaceKHR(instance_, &android, nullptr, &surface_); + assert(res == VK_SUCCESS); this->width = width; this->height = height; - assert(res == VK_SUCCESS); } #endif @@ -819,7 +830,7 @@ void VulkanContext::InitQueue() { // Iterate over each queue to learn whether it supports presenting: VkBool32* supportsPresent = new VkBool32[queue_count]; for (uint32_t i = 0; i < queue_count; i++) { - vkGetPhysicalDeviceSurfaceSupportKHR(physical_devices_[0], i, surface, &supportsPresent[i]); + vkGetPhysicalDeviceSurfaceSupportKHR(physical_devices_[0], i, surface_, &supportsPresent[i]); } // Search for a graphics queue and a present queue in the array of queue @@ -853,7 +864,7 @@ void VulkanContext::InitQueue() { // Generate error if could not find both a graphics and a present queue if (graphicsQueueNodeIndex == UINT32_MAX || presentQueueNodeIndex == UINT32_MAX) { - std::cout << "Could not find a graphics and a present queue\nCould not find a graphics and a present queue\n"; + std::cout << "Could not find a graphics and a present queue"; exit(-1); } @@ -861,27 +872,26 @@ void VulkanContext::InitQueue() { // Get the list of VkFormats that are supported: uint32_t formatCount; - VkResult res = vkGetPhysicalDeviceSurfaceFormatsKHR(physical_devices_[0], - surface, - &formatCount, NULL); + VkResult res = vkGetPhysicalDeviceSurfaceFormatsKHR(physical_devices_[0], surface_, &formatCount, NULL); assert(res == VK_SUCCESS); VkSurfaceFormatKHR *surfFormats = new VkSurfaceFormatKHR[formatCount]; - res = vkGetPhysicalDeviceSurfaceFormatsKHR(physical_devices_[0], - surface, - &formatCount, surfFormats); + res = vkGetPhysicalDeviceSurfaceFormatsKHR(physical_devices_[0], surface_, &formatCount, surfFormats); assert(res == VK_SUCCESS); // If the format list includes just one entry of VK_FORMAT_UNDEFINED, // the surface has no preferred format. Otherwise, at least one // supported format will be returned. if (formatCount == 1 && surfFormats[0].format == VK_FORMAT_UNDEFINED) { + ILOG("swapchain_format: Falling back to B8G8R8A8_UNORM"); swapchain_format = VK_FORMAT_B8G8R8A8_UNORM; } else { assert(formatCount >= 1); swapchain_format = surfFormats[0].format; + ILOG("swapchain_format: %d (/%d)", swapchain_format, formatCount); } delete[] surfFormats; vkGetDeviceQueue(device_, graphics_queue_family_index_, 0, &gfx_queue_); + ILOG("gfx_queue_: %p", gfx_queue_); VkSemaphoreCreateInfo acquireSemaphoreCreateInfo; acquireSemaphoreCreateInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; @@ -899,21 +909,15 @@ void VulkanContext::InitSwapchain(VkCommandBuffer cmd) { VkResult U_ASSERT_ONLY res; VkSurfaceCapabilitiesKHR surfCapabilities; - res = vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physical_devices_[0], - surface, - &surfCapabilities); + res = vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physical_devices_[0], surface_, &surfCapabilities); assert(res == VK_SUCCESS); uint32_t presentModeCount; - res = vkGetPhysicalDeviceSurfacePresentModesKHR(physical_devices_[0], - surface, - &presentModeCount, NULL); + res = vkGetPhysicalDeviceSurfacePresentModesKHR(physical_devices_[0], surface_, &presentModeCount, NULL); assert(res == VK_SUCCESS); VkPresentModeKHR *presentModes = new VkPresentModeKHR[presentModeCount]; assert(presentModes); - res = vkGetPhysicalDeviceSurfacePresentModesKHR(physical_devices_[0], - surface, - &presentModeCount, presentModes); + res = vkGetPhysicalDeviceSurfacePresentModesKHR(physical_devices_[0], surface_, &presentModeCount, presentModes); assert(res == VK_SUCCESS); VkExtent2D swapChainExtent; @@ -921,6 +925,7 @@ void VulkanContext::InitSwapchain(VkCommandBuffer cmd) { if (surfCapabilities.currentExtent.width == (uint32_t)-1) { // If the surface size is undefined, the size is set to // the size of the images requested. + ILOG("initSwapchain: %dx%d", width, height); swapChainExtent.width = width; swapChainExtent.height = height; } else { @@ -928,12 +933,17 @@ void VulkanContext::InitSwapchain(VkCommandBuffer cmd) { swapChainExtent = surfCapabilities.currentExtent; } - // If mailbox mode is available, use it, as is the lowest-latency non- - // tearing mode. If not, try FIFO_RELAXED, and if not that, try IMMEDIATE - // which will usually be available, and is fastest (though it tears). - // If not, fall back to FIFO which is always available. - VkPresentModeKHR swapchainPresentMode = VK_PRESENT_MODE_FIFO_KHR; + // TODO: Find a better way to specify the prioritized present mode while being able + // to fall back in a sensible way. + VkPresentModeKHR swapchainPresentMode = VK_PRESENT_MODE_MAX_ENUM; for (size_t i = 0; i < presentModeCount; i++) { + ILOG("Supported present mode: %d", presentModes[i]); + } + for (size_t i = 0; i < presentModeCount; i++) { + if (swapchainPresentMode == VK_PRESENT_MODE_MAX_ENUM) { + // Default to the first present mode from the list. + swapchainPresentMode = presentModes[i]; + } if ((flags_ & VULKAN_FLAG_PRESENT_MAILBOX) && presentModes[i] == VK_PRESENT_MODE_MAILBOX_KHR) { swapchainPresentMode = VK_PRESENT_MODE_MAILBOX_KHR; break; @@ -947,11 +957,17 @@ void VulkanContext::InitSwapchain(VkCommandBuffer cmd) { break; } } +#ifdef ANDROID + // HACK + swapchainPresentMode = VK_PRESENT_MODE_FIFO_KHR; +#endif + ILOG("Chosen present mode: %d", swapchainPresentMode); delete[] presentModes; // Determine the number of VkImage's to use in the swap chain (we desire to // own only 1 image at a time, besides the images being displayed and // queued for display): uint32_t desiredNumberOfSwapChainImages = surfCapabilities.minImageCount + 1; + ILOG("numSwapChainImages: %d", desiredNumberOfSwapChainImages); if ((surfCapabilities.maxImageCount > 0) && (desiredNumberOfSwapChainImages > surfCapabilities.maxImageCount)) { @@ -969,7 +985,7 @@ void VulkanContext::InitSwapchain(VkCommandBuffer cmd) { VkSwapchainCreateInfoKHR swap_chain_info = {}; swap_chain_info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; swap_chain_info.pNext = NULL; - swap_chain_info.surface = surface; + swap_chain_info.surface = surface_; swap_chain_info.minImageCount = desiredNumberOfSwapChainImages; swap_chain_info.imageFormat = swapchain_format; swap_chain_info.imageExtent.width = swapChainExtent.width; @@ -1102,6 +1118,7 @@ void VulkanContext::InitFramebuffers(bool include_depth) { VkImageView attachments[2]; attachments[1] = depth.view; + ILOG("InitFramebuffers: %dx%d", width, height); VkFramebufferCreateInfo fb_info = {}; fb_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; fb_info.pNext = NULL; diff --git a/Common/Vulkan/VulkanContext.h b/Common/Vulkan/VulkanContext.h index e1c428e433..1ef29e4203 100644 --- a/Common/Vulkan/VulkanContext.h +++ b/Common/Vulkan/VulkanContext.h @@ -26,11 +26,16 @@ #ifndef UTIL_INIT #define UTIL_INIT +#ifdef ANDROID +#undef NDEBUG // asserts +#endif #include #include #include #include +#include "base/logging.h" + #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN #define VK_USE_PLATFORM_WIN32_KHR @@ -150,9 +155,8 @@ public: VkResult CreateDevice(int physical_device); - VkDevice GetDevice() { - return device_; - } + VkDevice GetDevice() { return device_; } + VkInstance GetInstance() { return instance_; } VulkanDeleteList &Delete() { return globalDeleteList_; } @@ -216,8 +220,8 @@ public: return surface_render_pass_; } - VkPhysicalDevice GetPhysicalDevice() const { - return physical_devices_[0]; + VkPhysicalDevice GetPhysicalDevice(int n = 0) const { + return physical_devices_[n]; } VkQueue GetGraphicsQueue() const { @@ -260,7 +264,7 @@ private: VkDevice device_; VkQueue gfx_queue_; - VkSurfaceKHR surface; + VkSurfaceKHR surface_; bool prepared; bool use_staging_buffer_; diff --git a/Common/Vulkan/VulkanLoader.cpp b/Common/Vulkan/VulkanLoader.cpp index 96cd171eda..559a7bec88 100644 --- a/Common/Vulkan/VulkanLoader.cpp +++ b/Common/Vulkan/VulkanLoader.cpp @@ -16,6 +16,7 @@ // https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. #include "Common/Vulkan/VulkanLoader.h" +#include "base/logging.h" #ifndef _WIN32 #include @@ -190,196 +191,203 @@ static HINSTANCE vulkanLibrary; static void *vulkanLibrary; #endif -bool VulkanLoad() { +#define LOAD_INSTANCE_FUNC(instance, x) x = (PFN_ ## x)vkGetInstanceProcAddr(instance, #x); if (!x) {ILOG("Missing (instance): %s", #x);} +#define LOAD_DEVICE_FUNC(instance, x) x = (PFN_ ## x)vkGetDeviceProcAddr(instance, #x); if (!x) {ILOG("Missing (device): %s", #x);} +#define LOAD_GLOBAL_FUNC(x) x = (PFN_ ## x)dlsym(vulkanLibrary, #x); if (!x) {ILOG("Missing (global): %s", #x);} + +bool VulkanLoad() { #ifndef _WIN32 - vulkanLibrary = dlopen("libvulkan.sh", RTLD_NOW | RTLD_LOCAL); + vulkanLibrary = dlopen("libvulkan.so", RTLD_NOW | RTLD_LOCAL); #else - // LoadLibrary etc + // LoadLibrary etc vulkanLibrary = LoadLibrary(L"vulkan-1.dll"); #endif - if (!vulkanLibrary) { - return false; - } + if (!vulkanLibrary) { + return false; + } - vkCreateInstance = (PFN_vkCreateInstance)dlsym(vulkanLibrary, "vkCreateInstance"); - vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)dlsym(vulkanLibrary, "vkGetInstanceProcAddr"); - vkGetDeviceProcAddr = (PFN_vkGetDeviceProcAddr)dlsym(vulkanLibrary, "vkGetDeviceProcAddr"); + LOAD_GLOBAL_FUNC(vkCreateInstance); + LOAD_GLOBAL_FUNC(vkGetInstanceProcAddr); + LOAD_GLOBAL_FUNC(vkGetDeviceProcAddr); - // Why do we need to load these separately? - vkEnumerateInstanceExtensionProperties = (PFN_vkEnumerateInstanceExtensionProperties)dlsym(vulkanLibrary, "vkEnumerateInstanceExtensionProperties"); - vkEnumerateInstanceLayerProperties = (PFN_vkEnumerateInstanceLayerProperties)dlsym(vulkanLibrary, "vkEnumerateInstanceLayerProperties"); - return true; + LOAD_GLOBAL_FUNC(vkEnumerateInstanceExtensionProperties); + LOAD_GLOBAL_FUNC(vkEnumerateInstanceLayerProperties); + + WLOG("Vulkan base functions loaded."); + return true; } void VulkanLoadInstanceFunctions(VkInstance instance) { - // OK, let's use the above functions to get the rest. - vkDestroyInstance = (PFN_vkDestroyInstance)vkGetInstanceProcAddr(instance, "vkDestroyInstance"); - vkEnumeratePhysicalDevices = (PFN_vkEnumeratePhysicalDevices)vkGetInstanceProcAddr(instance, "vkEnumeratePhysicalDevices"); - vkGetPhysicalDeviceFeatures = (PFN_vkGetPhysicalDeviceFeatures)vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceFeatures"); - vkGetPhysicalDeviceFormatProperties = (PFN_vkGetPhysicalDeviceFormatProperties)vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceFormatProperties"); - vkGetPhysicalDeviceImageFormatProperties = (PFN_vkGetPhysicalDeviceImageFormatProperties)vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceImageFormatProperties"); - vkGetPhysicalDeviceProperties = (PFN_vkGetPhysicalDeviceProperties)vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceProperties"); - vkGetPhysicalDeviceQueueFamilyProperties = (PFN_vkGetPhysicalDeviceQueueFamilyProperties)vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceQueueFamilyProperties"); - vkGetPhysicalDeviceMemoryProperties = (PFN_vkGetPhysicalDeviceMemoryProperties)vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceMemoryProperties"); - vkCreateDevice = (PFN_vkCreateDevice)vkGetInstanceProcAddr(instance, "vkCreateDevice"); - vkDestroyDevice = (PFN_vkDestroyDevice)vkGetInstanceProcAddr(instance, "vkDestroyDevice"); - vkEnumerateDeviceExtensionProperties = (PFN_vkEnumerateDeviceExtensionProperties)vkGetInstanceProcAddr(instance, "vkEnumerateDeviceExtensionProperties"); - vkEnumerateDeviceLayerProperties = (PFN_vkEnumerateDeviceLayerProperties)vkGetInstanceProcAddr(instance, "vkEnumerateDeviceLayerProperties"); - vkGetDeviceQueue = (PFN_vkGetDeviceQueue)vkGetInstanceProcAddr(instance, "vkGetDeviceQueue"); - vkQueueSubmit = (PFN_vkQueueSubmit)vkGetInstanceProcAddr(instance, "vkQueueSubmit"); - vkQueueWaitIdle = (PFN_vkQueueWaitIdle)vkGetInstanceProcAddr(instance, "vkQueueWaitIdle"); - vkDeviceWaitIdle = (PFN_vkDeviceWaitIdle)vkGetInstanceProcAddr(instance, "vkDeviceWaitIdle"); - vkAllocateMemory = (PFN_vkAllocateMemory)vkGetInstanceProcAddr(instance, "vkAllocateMemory"); - vkFreeMemory = (PFN_vkFreeMemory)vkGetInstanceProcAddr(instance, "vkFreeMemory"); - vkMapMemory = (PFN_vkMapMemory)vkGetInstanceProcAddr(instance, "vkMapMemory"); - vkUnmapMemory = (PFN_vkUnmapMemory)vkGetInstanceProcAddr(instance, "vkUnmapMemory"); - vkFlushMappedMemoryRanges = (PFN_vkFlushMappedMemoryRanges)vkGetInstanceProcAddr(instance, "vkFlushMappedMemoryRanges"); - vkInvalidateMappedMemoryRanges = (PFN_vkInvalidateMappedMemoryRanges)vkGetInstanceProcAddr(instance, "vkInvalidateMappedMemoryRanges"); - vkGetDeviceMemoryCommitment = (PFN_vkGetDeviceMemoryCommitment)vkGetInstanceProcAddr(instance, "vkGetDeviceMemoryCommitment"); - vkBindBufferMemory = (PFN_vkBindBufferMemory)vkGetInstanceProcAddr(instance, "vkBindBufferMemory"); - vkBindImageMemory = (PFN_vkBindImageMemory)vkGetInstanceProcAddr(instance, "vkBindImageMemory"); - vkGetBufferMemoryRequirements = (PFN_vkGetBufferMemoryRequirements)vkGetInstanceProcAddr(instance, "vkGetBufferMemoryRequirements"); - vkGetImageMemoryRequirements = (PFN_vkGetImageMemoryRequirements)vkGetInstanceProcAddr(instance, "vkGetImageMemoryRequirements"); - vkGetImageSparseMemoryRequirements = (PFN_vkGetImageSparseMemoryRequirements)vkGetInstanceProcAddr(instance, "vkGetImageSparseMemoryRequirements"); - vkGetPhysicalDeviceSparseImageFormatProperties = (PFN_vkGetPhysicalDeviceSparseImageFormatProperties)vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceSparseImageFormatProperties"); - vkQueueBindSparse = (PFN_vkQueueBindSparse)vkGetInstanceProcAddr(instance, "vkQueueBindSparse"); - vkCreateFence = (PFN_vkCreateFence)vkGetInstanceProcAddr(instance, "vkCreateFence"); - vkDestroyFence = (PFN_vkDestroyFence)vkGetInstanceProcAddr(instance, "vkDestroyFence"); - vkResetFences = (PFN_vkResetFences)vkGetInstanceProcAddr(instance, "vkResetFences"); - vkGetFenceStatus = (PFN_vkGetFenceStatus)vkGetInstanceProcAddr(instance, "vkGetFenceStatus"); - vkWaitForFences = (PFN_vkWaitForFences)vkGetInstanceProcAddr(instance, "vkWaitForFences"); - vkCreateSemaphore = (PFN_vkCreateSemaphore)vkGetInstanceProcAddr(instance, "vkCreateSemaphore"); - vkDestroySemaphore = (PFN_vkDestroySemaphore)vkGetInstanceProcAddr(instance, "vkDestroySemaphore"); - vkCreateEvent = (PFN_vkCreateEvent)vkGetInstanceProcAddr(instance, "vkCreateEvent"); - vkDestroyEvent = (PFN_vkDestroyEvent)vkGetInstanceProcAddr(instance, "vkDestroyEvent"); - vkGetEventStatus = (PFN_vkGetEventStatus)vkGetInstanceProcAddr(instance, "vkGetEventStatus"); - vkSetEvent = (PFN_vkSetEvent)vkGetInstanceProcAddr(instance, "vkSetEvent"); - vkResetEvent = (PFN_vkResetEvent)vkGetInstanceProcAddr(instance, "vkResetEvent"); - vkCreateQueryPool = (PFN_vkCreateQueryPool)vkGetInstanceProcAddr(instance, "vkCreateQueryPool"); - vkDestroyQueryPool = (PFN_vkDestroyQueryPool)vkGetInstanceProcAddr(instance, "vkDestroyQueryPool"); - vkGetQueryPoolResults = (PFN_vkGetQueryPoolResults)vkGetInstanceProcAddr(instance, "vkGetQueryPoolResults"); - vkCreateBuffer = (PFN_vkCreateBuffer)vkGetInstanceProcAddr(instance, "vkCreateBuffer"); - vkDestroyBuffer = (PFN_vkDestroyBuffer)vkGetInstanceProcAddr(instance, "vkDestroyBuffer"); - vkCreateBufferView = (PFN_vkCreateBufferView)vkGetInstanceProcAddr(instance, "vkCreateBufferView"); - vkDestroyBufferView = (PFN_vkDestroyBufferView)vkGetInstanceProcAddr(instance, "vkDestroyBufferView"); - vkCreateImage = (PFN_vkCreateImage)vkGetInstanceProcAddr(instance, "vkCreateImage"); - vkDestroyImage = (PFN_vkDestroyImage)vkGetInstanceProcAddr(instance, "vkDestroyImage"); - vkGetImageSubresourceLayout = (PFN_vkGetImageSubresourceLayout)vkGetInstanceProcAddr(instance, "vkGetImageSubresourceLayout"); - vkCreateImageView = (PFN_vkCreateImageView)vkGetInstanceProcAddr(instance, "vkCreateImageView"); - vkDestroyImageView = (PFN_vkDestroyImageView)vkGetInstanceProcAddr(instance, "vkDestroyImageView"); - vkCreateShaderModule = (PFN_vkCreateShaderModule)vkGetInstanceProcAddr(instance, "vkCreateShaderModule"); - vkDestroyShaderModule = (PFN_vkDestroyShaderModule)vkGetInstanceProcAddr(instance, "vkDestroyShaderModule"); - vkCreatePipelineCache = (PFN_vkCreatePipelineCache)vkGetInstanceProcAddr(instance, "vkCreatePipelineCache"); - vkDestroyPipelineCache = (PFN_vkDestroyPipelineCache)vkGetInstanceProcAddr(instance, "vkDestroyPipelineCache"); - vkGetPipelineCacheData = (PFN_vkGetPipelineCacheData)vkGetInstanceProcAddr(instance, "vkGetPipelineCacheData"); - vkMergePipelineCaches = (PFN_vkMergePipelineCaches)vkGetInstanceProcAddr(instance, "vkMergePipelineCaches"); - vkCreateGraphicsPipelines = (PFN_vkCreateGraphicsPipelines)vkGetInstanceProcAddr(instance, "vkCreateGraphicsPipelines"); - vkCreateComputePipelines = (PFN_vkCreateComputePipelines)vkGetInstanceProcAddr(instance, "vkCreateComputePipelines"); - vkDestroyPipeline = (PFN_vkDestroyPipeline)vkGetInstanceProcAddr(instance, "vkDestroyPipeline"); - vkCreatePipelineLayout = (PFN_vkCreatePipelineLayout)vkGetInstanceProcAddr(instance, "vkCreatePipelineLayout"); - vkDestroyPipelineLayout = (PFN_vkDestroyPipelineLayout)vkGetInstanceProcAddr(instance, "vkDestroyPipelineLayout"); - vkCreateSampler = (PFN_vkCreateSampler)vkGetInstanceProcAddr(instance, "vkCreateSampler"); - vkDestroySampler = (PFN_vkDestroySampler)vkGetInstanceProcAddr(instance, "vkDestroySampler"); - vkCreateDescriptorSetLayout = (PFN_vkCreateDescriptorSetLayout)vkGetInstanceProcAddr(instance, "vkCreateDescriptorSetLayout"); - vkDestroyDescriptorSetLayout = (PFN_vkDestroyDescriptorSetLayout)vkGetInstanceProcAddr(instance, "vkDestroyDescriptorSetLayout"); - vkCreateDescriptorPool = (PFN_vkCreateDescriptorPool)vkGetInstanceProcAddr(instance, "vkCreateDescriptorPool"); - vkDestroyDescriptorPool = (PFN_vkDestroyDescriptorPool)vkGetInstanceProcAddr(instance, "vkDestroyDescriptorPool"); - vkResetDescriptorPool = (PFN_vkResetDescriptorPool)vkGetInstanceProcAddr(instance, "vkResetDescriptorPool"); - vkAllocateDescriptorSets = (PFN_vkAllocateDescriptorSets)vkGetInstanceProcAddr(instance, "vkAllocateDescriptorSets"); - vkFreeDescriptorSets = (PFN_vkFreeDescriptorSets)vkGetInstanceProcAddr(instance, "vkFreeDescriptorSets"); - vkUpdateDescriptorSets = (PFN_vkUpdateDescriptorSets)vkGetInstanceProcAddr(instance, "vkUpdateDescriptorSets"); - vkCreateFramebuffer = (PFN_vkCreateFramebuffer)vkGetInstanceProcAddr(instance, "vkCreateFramebuffer"); - vkDestroyFramebuffer = (PFN_vkDestroyFramebuffer)vkGetInstanceProcAddr(instance, "vkDestroyFramebuffer"); - vkCreateRenderPass = (PFN_vkCreateRenderPass)vkGetInstanceProcAddr(instance, "vkCreateRenderPass"); - vkDestroyRenderPass = (PFN_vkDestroyRenderPass)vkGetInstanceProcAddr(instance, "vkDestroyRenderPass"); - vkGetRenderAreaGranularity = (PFN_vkGetRenderAreaGranularity)vkGetInstanceProcAddr(instance, "vkGetRenderAreaGranularity"); - vkCreateCommandPool = (PFN_vkCreateCommandPool)vkGetInstanceProcAddr(instance, "vkCreateCommandPool"); - vkDestroyCommandPool = (PFN_vkDestroyCommandPool)vkGetInstanceProcAddr(instance, "vkDestroyCommandPool"); - vkResetCommandPool = (PFN_vkResetCommandPool)vkGetInstanceProcAddr(instance, "vkResetCommandPool"); - vkAllocateCommandBuffers = (PFN_vkAllocateCommandBuffers)vkGetInstanceProcAddr(instance, "vkAllocateCommandBuffers"); - vkFreeCommandBuffers = (PFN_vkFreeCommandBuffers)vkGetInstanceProcAddr(instance, "vkFreeCommandBuffers"); - vkBeginCommandBuffer = (PFN_vkBeginCommandBuffer)vkGetInstanceProcAddr(instance, "vkBeginCommandBuffer"); - vkEndCommandBuffer = (PFN_vkEndCommandBuffer)vkGetInstanceProcAddr(instance, "vkEndCommandBuffer"); - vkResetCommandBuffer = (PFN_vkResetCommandBuffer)vkGetInstanceProcAddr(instance, "vkResetCommandBuffer"); - vkCmdBindPipeline = (PFN_vkCmdBindPipeline)vkGetInstanceProcAddr(instance, "vkCmdBindPipeline"); - vkCmdSetViewport = (PFN_vkCmdSetViewport)vkGetInstanceProcAddr(instance, "vkCmdSetViewport"); - vkCmdSetScissor = (PFN_vkCmdSetScissor)vkGetInstanceProcAddr(instance, "vkCmdSetScissor"); - vkCmdSetLineWidth = (PFN_vkCmdSetLineWidth)vkGetInstanceProcAddr(instance, "vkCmdSetLineWidth"); - vkCmdSetDepthBias = (PFN_vkCmdSetDepthBias)vkGetInstanceProcAddr(instance, "vkCmdSetDepthBias"); - vkCmdSetBlendConstants = (PFN_vkCmdSetBlendConstants)vkGetInstanceProcAddr(instance, "vkCmdSetBlendConstants"); - vkCmdSetDepthBounds = (PFN_vkCmdSetDepthBounds)vkGetInstanceProcAddr(instance, "vkCmdSetDepthBounds"); - vkCmdSetStencilCompareMask = (PFN_vkCmdSetStencilCompareMask)vkGetInstanceProcAddr(instance, "vkCmdSetStencilCompareMask"); - vkCmdSetStencilWriteMask = (PFN_vkCmdSetStencilWriteMask)vkGetInstanceProcAddr(instance, "vkCmdSetStencilWriteMask"); - vkCmdSetStencilReference = (PFN_vkCmdSetStencilReference)vkGetInstanceProcAddr(instance, "vkCmdSetStencilReference"); - vkCmdBindDescriptorSets = (PFN_vkCmdBindDescriptorSets)vkGetInstanceProcAddr(instance, "vkCmdBindDescriptorSets"); - vkCmdBindIndexBuffer = (PFN_vkCmdBindIndexBuffer)vkGetInstanceProcAddr(instance, "vkCmdBindIndexBuffer"); - vkCmdBindVertexBuffers = (PFN_vkCmdBindVertexBuffers)vkGetInstanceProcAddr(instance, "vkCmdBindVertexBuffers"); - vkCmdDraw = (PFN_vkCmdDraw)vkGetInstanceProcAddr(instance, "vkCmdDraw"); - vkCmdDrawIndexed = (PFN_vkCmdDrawIndexed)vkGetInstanceProcAddr(instance, "vkCmdDrawIndexed"); - vkCmdDrawIndirect = (PFN_vkCmdDrawIndirect)vkGetInstanceProcAddr(instance, "vkCmdDrawIndirect"); - vkCmdDrawIndexedIndirect = (PFN_vkCmdDrawIndexedIndirect)vkGetInstanceProcAddr(instance, "vkCmdDrawIndexedIndirect"); - vkCmdDispatch = (PFN_vkCmdDispatch)vkGetInstanceProcAddr(instance, "vkCmdDispatch"); - vkCmdDispatchIndirect = (PFN_vkCmdDispatchIndirect)vkGetInstanceProcAddr(instance, "vkCmdDispatchIndirect"); - vkCmdCopyBuffer = (PFN_vkCmdCopyBuffer)vkGetInstanceProcAddr(instance, "vkCmdCopyBuffer"); - vkCmdCopyImage = (PFN_vkCmdCopyImage)vkGetInstanceProcAddr(instance, "vkCmdCopyImage"); - vkCmdBlitImage = (PFN_vkCmdBlitImage)vkGetInstanceProcAddr(instance, "vkCmdBlitImage"); - vkCmdCopyBufferToImage = (PFN_vkCmdCopyBufferToImage)vkGetInstanceProcAddr(instance, "vkCmdCopyBufferToImage"); - vkCmdCopyImageToBuffer = (PFN_vkCmdCopyImageToBuffer)vkGetInstanceProcAddr(instance, "vkCmdCopyImageToBuffer"); - vkCmdUpdateBuffer = (PFN_vkCmdUpdateBuffer)vkGetInstanceProcAddr(instance, "vkCmdUpdateBuffer"); - vkCmdFillBuffer = (PFN_vkCmdFillBuffer)vkGetInstanceProcAddr(instance, "vkCmdFillBuffer"); - vkCmdClearColorImage = (PFN_vkCmdClearColorImage)vkGetInstanceProcAddr(instance, "vkCmdClearColorImage"); - vkCmdClearDepthStencilImage = (PFN_vkCmdClearDepthStencilImage)vkGetInstanceProcAddr(instance, "vkCmdClearDepthStencilImage"); - vkCmdClearAttachments = (PFN_vkCmdClearAttachments)vkGetInstanceProcAddr(instance, "vkCmdClearAttachments"); - vkCmdResolveImage = (PFN_vkCmdResolveImage)vkGetInstanceProcAddr(instance, "vkCmdResolveImage"); - vkCmdSetEvent = (PFN_vkCmdSetEvent)vkGetInstanceProcAddr(instance, "vkCmdSetEvent"); - vkCmdResetEvent = (PFN_vkCmdResetEvent)vkGetInstanceProcAddr(instance, "vkCmdResetEvent"); - vkCmdWaitEvents = (PFN_vkCmdWaitEvents)vkGetInstanceProcAddr(instance, "vkCmdWaitEvents"); - vkCmdPipelineBarrier = (PFN_vkCmdPipelineBarrier)vkGetInstanceProcAddr(instance, "vkCmdPipelineBarrier"); - vkCmdBeginQuery = (PFN_vkCmdBeginQuery)vkGetInstanceProcAddr(instance, "vkCmdBeginQuery"); - vkCmdEndQuery = (PFN_vkCmdEndQuery)vkGetInstanceProcAddr(instance, "vkCmdEndQuery"); - vkCmdResetQueryPool = (PFN_vkCmdResetQueryPool)vkGetInstanceProcAddr(instance, "vkCmdResetQueryPool"); - vkCmdWriteTimestamp = (PFN_vkCmdWriteTimestamp)vkGetInstanceProcAddr(instance, "vkCmdWriteTimestamp"); - vkCmdCopyQueryPoolResults = (PFN_vkCmdCopyQueryPoolResults)vkGetInstanceProcAddr(instance, "vkCmdCopyQueryPoolResults"); - vkCmdPushConstants = (PFN_vkCmdPushConstants)vkGetInstanceProcAddr(instance, "vkCmdPushConstants"); - vkCmdBeginRenderPass = (PFN_vkCmdBeginRenderPass)vkGetInstanceProcAddr(instance, "vkCmdBeginRenderPass"); - vkCmdNextSubpass = (PFN_vkCmdNextSubpass)vkGetInstanceProcAddr(instance, "vkCmdNextSubpass"); - vkCmdEndRenderPass = (PFN_vkCmdEndRenderPass)vkGetInstanceProcAddr(instance, "vkCmdEndRenderPass"); - vkCmdExecuteCommands = (PFN_vkCmdExecuteCommands)vkGetInstanceProcAddr(instance, "vkCmdExecuteCommands"); + // OK, let's use the above functions to get the rest. + LOAD_INSTANCE_FUNC(instance, vkDestroyInstance); + LOAD_INSTANCE_FUNC(instance, vkEnumeratePhysicalDevices); + LOAD_INSTANCE_FUNC(instance, vkGetPhysicalDeviceFeatures); + LOAD_INSTANCE_FUNC(instance, vkGetPhysicalDeviceFormatProperties); + LOAD_INSTANCE_FUNC(instance, vkGetPhysicalDeviceImageFormatProperties); + LOAD_INSTANCE_FUNC(instance, vkGetPhysicalDeviceProperties); + LOAD_INSTANCE_FUNC(instance, vkGetPhysicalDeviceQueueFamilyProperties); + LOAD_INSTANCE_FUNC(instance, vkGetPhysicalDeviceMemoryProperties); + LOAD_INSTANCE_FUNC(instance, vkCreateDevice); + LOAD_INSTANCE_FUNC(instance, vkDestroyDevice); + LOAD_INSTANCE_FUNC(instance, vkEnumerateDeviceExtensionProperties); + LOAD_INSTANCE_FUNC(instance, vkEnumerateDeviceLayerProperties); + LOAD_INSTANCE_FUNC(instance, vkGetDeviceQueue); + LOAD_INSTANCE_FUNC(instance, vkQueueSubmit); + LOAD_INSTANCE_FUNC(instance, vkQueueWaitIdle); + LOAD_INSTANCE_FUNC(instance, vkDeviceWaitIdle); + LOAD_INSTANCE_FUNC(instance, vkAllocateMemory); + LOAD_INSTANCE_FUNC(instance, vkFreeMemory); + LOAD_INSTANCE_FUNC(instance, vkMapMemory); + LOAD_INSTANCE_FUNC(instance, vkUnmapMemory); + LOAD_INSTANCE_FUNC(instance, vkFlushMappedMemoryRanges); + LOAD_INSTANCE_FUNC(instance, vkInvalidateMappedMemoryRanges); + LOAD_INSTANCE_FUNC(instance, vkGetDeviceMemoryCommitment); + LOAD_INSTANCE_FUNC(instance, vkBindBufferMemory); + LOAD_INSTANCE_FUNC(instance, vkBindImageMemory); + LOAD_INSTANCE_FUNC(instance, vkGetBufferMemoryRequirements); + LOAD_INSTANCE_FUNC(instance, vkGetImageMemoryRequirements); + LOAD_INSTANCE_FUNC(instance, vkGetImageSparseMemoryRequirements); + LOAD_INSTANCE_FUNC(instance, vkGetPhysicalDeviceSparseImageFormatProperties); + LOAD_INSTANCE_FUNC(instance, vkQueueBindSparse); + LOAD_INSTANCE_FUNC(instance, vkCreateFence); + LOAD_INSTANCE_FUNC(instance, vkDestroyFence); + LOAD_INSTANCE_FUNC(instance, vkResetFences); + LOAD_INSTANCE_FUNC(instance, vkGetFenceStatus); + LOAD_INSTANCE_FUNC(instance, vkWaitForFences); + LOAD_INSTANCE_FUNC(instance, vkCreateSemaphore); + LOAD_INSTANCE_FUNC(instance, vkDestroySemaphore); + LOAD_INSTANCE_FUNC(instance, vkCreateEvent); + LOAD_INSTANCE_FUNC(instance, vkDestroyEvent); + LOAD_INSTANCE_FUNC(instance, vkGetEventStatus); + LOAD_INSTANCE_FUNC(instance, vkSetEvent); + LOAD_INSTANCE_FUNC(instance, vkResetEvent); + LOAD_INSTANCE_FUNC(instance, vkCreateQueryPool); + LOAD_INSTANCE_FUNC(instance, vkDestroyQueryPool); + LOAD_INSTANCE_FUNC(instance, vkGetQueryPoolResults); + LOAD_INSTANCE_FUNC(instance, vkCreateBuffer); + LOAD_INSTANCE_FUNC(instance, vkDestroyBuffer); + LOAD_INSTANCE_FUNC(instance, vkCreateBufferView); + LOAD_INSTANCE_FUNC(instance, vkDestroyBufferView); + LOAD_INSTANCE_FUNC(instance, vkCreateImage); + LOAD_INSTANCE_FUNC(instance, vkDestroyImage); + LOAD_INSTANCE_FUNC(instance, vkGetImageSubresourceLayout); + LOAD_INSTANCE_FUNC(instance, vkCreateImageView); + LOAD_INSTANCE_FUNC(instance, vkDestroyImageView); + LOAD_INSTANCE_FUNC(instance, vkCreateShaderModule); + LOAD_INSTANCE_FUNC(instance, vkDestroyShaderModule); + LOAD_INSTANCE_FUNC(instance, vkCreatePipelineCache); + LOAD_INSTANCE_FUNC(instance, vkDestroyPipelineCache); + LOAD_INSTANCE_FUNC(instance, vkGetPipelineCacheData); + LOAD_INSTANCE_FUNC(instance, vkMergePipelineCaches); + LOAD_INSTANCE_FUNC(instance, vkCreateGraphicsPipelines); + LOAD_INSTANCE_FUNC(instance, vkCreateComputePipelines); + LOAD_INSTANCE_FUNC(instance, vkDestroyPipeline); + LOAD_INSTANCE_FUNC(instance, vkCreatePipelineLayout); + LOAD_INSTANCE_FUNC(instance, vkDestroyPipelineLayout); + LOAD_INSTANCE_FUNC(instance, vkCreateSampler); + LOAD_INSTANCE_FUNC(instance, vkDestroySampler); + LOAD_INSTANCE_FUNC(instance, vkCreateDescriptorSetLayout); + LOAD_INSTANCE_FUNC(instance, vkDestroyDescriptorSetLayout); + LOAD_INSTANCE_FUNC(instance, vkCreateDescriptorPool); + LOAD_INSTANCE_FUNC(instance, vkDestroyDescriptorPool); + LOAD_INSTANCE_FUNC(instance, vkResetDescriptorPool); + LOAD_INSTANCE_FUNC(instance, vkAllocateDescriptorSets); + LOAD_INSTANCE_FUNC(instance, vkFreeDescriptorSets); + LOAD_INSTANCE_FUNC(instance, vkUpdateDescriptorSets); + LOAD_INSTANCE_FUNC(instance, vkCreateFramebuffer); + LOAD_INSTANCE_FUNC(instance, vkDestroyFramebuffer); + LOAD_INSTANCE_FUNC(instance, vkCreateRenderPass); + LOAD_INSTANCE_FUNC(instance, vkDestroyRenderPass); + LOAD_INSTANCE_FUNC(instance, vkGetRenderAreaGranularity); + LOAD_INSTANCE_FUNC(instance, vkCreateCommandPool); + LOAD_INSTANCE_FUNC(instance, vkDestroyCommandPool); + LOAD_INSTANCE_FUNC(instance, vkResetCommandPool); + LOAD_INSTANCE_FUNC(instance, vkAllocateCommandBuffers); + LOAD_INSTANCE_FUNC(instance, vkFreeCommandBuffers); + LOAD_INSTANCE_FUNC(instance, vkBeginCommandBuffer); + LOAD_INSTANCE_FUNC(instance, vkEndCommandBuffer); + LOAD_INSTANCE_FUNC(instance, vkResetCommandBuffer); + LOAD_INSTANCE_FUNC(instance, vkCmdBindPipeline); + LOAD_INSTANCE_FUNC(instance, vkCmdSetViewport); + LOAD_INSTANCE_FUNC(instance, vkCmdSetScissor); + LOAD_INSTANCE_FUNC(instance, vkCmdSetLineWidth); + LOAD_INSTANCE_FUNC(instance, vkCmdSetDepthBias); + LOAD_INSTANCE_FUNC(instance, vkCmdSetBlendConstants); + LOAD_INSTANCE_FUNC(instance, vkCmdSetDepthBounds); + LOAD_INSTANCE_FUNC(instance, vkCmdSetStencilCompareMask); + LOAD_INSTANCE_FUNC(instance, vkCmdSetStencilWriteMask); + LOAD_INSTANCE_FUNC(instance, vkCmdSetStencilReference); + LOAD_INSTANCE_FUNC(instance, vkCmdBindDescriptorSets); + LOAD_INSTANCE_FUNC(instance, vkCmdBindIndexBuffer); + LOAD_INSTANCE_FUNC(instance, vkCmdBindVertexBuffers); + LOAD_INSTANCE_FUNC(instance, vkCmdDraw); + LOAD_INSTANCE_FUNC(instance, vkCmdDrawIndexed); + LOAD_INSTANCE_FUNC(instance, vkCmdDrawIndirect); + LOAD_INSTANCE_FUNC(instance, vkCmdDrawIndexedIndirect); + LOAD_INSTANCE_FUNC(instance, vkCmdDispatch); + LOAD_INSTANCE_FUNC(instance, vkCmdDispatchIndirect); + LOAD_INSTANCE_FUNC(instance, vkCmdCopyBuffer); + LOAD_INSTANCE_FUNC(instance, vkCmdCopyImage); + LOAD_INSTANCE_FUNC(instance, vkCmdBlitImage); + LOAD_INSTANCE_FUNC(instance, vkCmdCopyBufferToImage); + LOAD_INSTANCE_FUNC(instance, vkCmdCopyImageToBuffer); + LOAD_INSTANCE_FUNC(instance, vkCmdUpdateBuffer); + LOAD_INSTANCE_FUNC(instance, vkCmdFillBuffer); + LOAD_INSTANCE_FUNC(instance, vkCmdClearColorImage); + LOAD_INSTANCE_FUNC(instance, vkCmdClearDepthStencilImage); + LOAD_INSTANCE_FUNC(instance, vkCmdClearAttachments); + LOAD_INSTANCE_FUNC(instance, vkCmdResolveImage); + LOAD_INSTANCE_FUNC(instance, vkCmdSetEvent); + LOAD_INSTANCE_FUNC(instance, vkCmdResetEvent); + LOAD_INSTANCE_FUNC(instance, vkCmdWaitEvents); + LOAD_INSTANCE_FUNC(instance, vkCmdPipelineBarrier); + LOAD_INSTANCE_FUNC(instance, vkCmdBeginQuery); + LOAD_INSTANCE_FUNC(instance, vkCmdEndQuery); + LOAD_INSTANCE_FUNC(instance, vkCmdResetQueryPool); + LOAD_INSTANCE_FUNC(instance, vkCmdWriteTimestamp); + LOAD_INSTANCE_FUNC(instance, vkCmdCopyQueryPoolResults); + LOAD_INSTANCE_FUNC(instance, vkCmdPushConstants); + LOAD_INSTANCE_FUNC(instance, vkCmdBeginRenderPass); + LOAD_INSTANCE_FUNC(instance, vkCmdNextSubpass); + LOAD_INSTANCE_FUNC(instance, vkCmdEndRenderPass); + LOAD_INSTANCE_FUNC(instance, vkCmdExecuteCommands); - vkGetPhysicalDeviceSurfaceSupportKHR = (PFN_vkGetPhysicalDeviceSurfaceSupportKHR)vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceSurfaceSupportKHR"); - vkGetPhysicalDeviceSurfaceCapabilitiesKHR = (PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR)vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceSurfaceCapabilitiesKHR"); - vkGetPhysicalDeviceSurfaceFormatsKHR = (PFN_vkGetPhysicalDeviceSurfaceFormatsKHR)vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceSurfaceFormatsKHR"); - vkGetPhysicalDeviceSurfacePresentModesKHR = (PFN_vkGetPhysicalDeviceSurfacePresentModesKHR)vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceSurfacePresentModesKHR"); + LOAD_INSTANCE_FUNC(instance, vkGetPhysicalDeviceSurfaceSupportKHR); + LOAD_INSTANCE_FUNC(instance, vkGetPhysicalDeviceSurfaceCapabilitiesKHR); + LOAD_INSTANCE_FUNC(instance, vkGetPhysicalDeviceSurfaceFormatsKHR); + LOAD_INSTANCE_FUNC(instance, vkGetPhysicalDeviceSurfacePresentModesKHR); - vkCreateSwapchainKHR = (PFN_vkCreateSwapchainKHR)vkGetInstanceProcAddr(instance, "vkCreateSwapchainKHR"); - vkDestroySwapchainKHR = (PFN_vkDestroySwapchainKHR)vkGetInstanceProcAddr(instance, "vkDestroySwapchainKHR"); - vkGetSwapchainImagesKHR = (PFN_vkGetSwapchainImagesKHR)vkGetInstanceProcAddr(instance, "vkGetSwapchainImagesKHR"); - vkAcquireNextImageKHR = (PFN_vkAcquireNextImageKHR)vkGetInstanceProcAddr(instance, "vkAcquireNextImageKHR"); - vkQueuePresentKHR = (PFN_vkQueuePresentKHR)vkGetInstanceProcAddr(instance, "vkQueuePresentKHR"); + LOAD_INSTANCE_FUNC(instance, vkCreateSwapchainKHR); + LOAD_INSTANCE_FUNC(instance, vkDestroySwapchainKHR); + LOAD_INSTANCE_FUNC(instance, vkGetSwapchainImagesKHR); + LOAD_INSTANCE_FUNC(instance, vkAcquireNextImageKHR); + LOAD_INSTANCE_FUNC(instance, vkQueuePresentKHR); #ifdef _WIN32 - vkCreateWin32SurfaceKHR = (PFN_vkCreateWin32SurfaceKHR)vkGetInstanceProcAddr(instance, "vkCreateWin32SurfaceKHR"); + LOAD_INSTANCE_FUNC(instance, vkCreateWin32SurfaceKHR); #elif defined(ANDROID) - vkCreateAndroidSurfaceKHR = (PFN_vkCreateAndroidSurfaceKHR)vkGetInstanceProcAddr(instance, "vkCreateAndroidSurfaceKHR"); + LOAD_INSTANCE_FUNC(instance, vkCreateAndroidSurfaceKHR); #endif - vkDestroySurfaceKHR = (PFN_vkDestroySurfaceKHR)vkGetInstanceProcAddr(instance, "vkDestroySurfaceKHR"); + LOAD_INSTANCE_FUNC(instance, vkDestroySurfaceKHR); - vkCreateDebugReportCallbackEXT = (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(instance, "vkCreateDebugReportCallbackEXT"); - vkDestroyDebugReportCallbackEXT = (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(instance, "vkDestroyDebugReportCallbackEXT"); + LOAD_INSTANCE_FUNC(instance, vkCreateDebugReportCallbackEXT); + LOAD_INSTANCE_FUNC(instance, vkDestroyDebugReportCallbackEXT); + WLOG("Vulkan instance functions loaded."); } // On some implementations, loading functions (that have Device as their first parameter) via vkGetDeviceProcAddr may // increase performance - but then these function pointers will only work on that specific device. Thus, this loader is not very // good for multi-device. void VulkanLoadDeviceFunctions(VkDevice device) { - // TODO: Move more functions VulkanLoadInstanceFunctions to here. - vkCreateSwapchainKHR = (PFN_vkCreateSwapchainKHR)vkGetDeviceProcAddr(device, "vkCreateSwapchainKHR"); - vkDestroySwapchainKHR = (PFN_vkDestroySwapchainKHR)vkGetDeviceProcAddr(device, "vkDestroySwapchainKHR"); - vkGetSwapchainImagesKHR = (PFN_vkGetSwapchainImagesKHR)vkGetDeviceProcAddr(device, "vkGetSwapchainImagesKHR"); - vkAcquireNextImageKHR = (PFN_vkAcquireNextImageKHR)vkGetDeviceProcAddr(device, "vkAcquireNextImageKHR"); - vkQueuePresentKHR = (PFN_vkQueuePresentKHR)vkGetDeviceProcAddr(device, "vkQueuePresentKHR"); + WLOG("Vulkan device functions loaded."); + // TODO: Move more functions VulkanLoadInstanceFunctions to here. + LOAD_DEVICE_FUNC(device, vkCreateSwapchainKHR); + LOAD_DEVICE_FUNC(device, vkDestroySwapchainKHR); + LOAD_DEVICE_FUNC(device, vkGetSwapchainImagesKHR); + LOAD_DEVICE_FUNC(device, vkAcquireNextImageKHR); + LOAD_DEVICE_FUNC(device, vkQueuePresentKHR); } void VulkanFree() { diff --git a/android/jni/app-android.cpp b/android/jni/app-android.cpp index 23b84a452f..73e0db30ff 100644 --- a/android/jni/app-android.cpp +++ b/android/jni/app-android.cpp @@ -244,13 +244,27 @@ bool AndroidVulkanContext::Init(ANativeWindow *wnd, int desiredBackbufferSizeX, g_LogOptions.breakOnWarning = true; g_LogOptions.msgBoxOnError = false; - g_Vulkan = new VulkanContext("PPSSPP", (g_validate_ ? VULKAN_FLAG_VALIDATE : 0) | VULKAN_FLAG_PRESENT_MAILBOX); + ILOG("Creating vulkan context"); + g_Vulkan = new VulkanContext("PPSSPP", VULKAN_FLAG_PRESENT_MAILBOX | VULKAN_FLAG_PRESENT_FIFO_RELAXED); + if (!g_Vulkan->GetInstance()) { + ELOG("Failed to create vulkan context"); + return false; + } + + ILOG("Creating vulkan device"); g_Vulkan->CreateDevice(0); + int width = desiredBackbufferSizeX; + int height = desiredBackbufferSizeY; + if (!width || !height) { + width = pixel_xres; + height = pixel_yres; + } + ILOG("InitSurfaceAndroid: width=%d height=%d", width, height); + g_Vulkan->InitSurfaceAndroid(wnd, width, height); if (g_validate_) { int bits = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT; g_Vulkan->InitDebugMsgCallback(Vulkan_Dbg, bits, &g_LogOptions); } - g_Vulkan->InitSurfaceAndroid(wnd, desiredBackbufferSizeX, desiredBackbufferSizeY); g_Vulkan->InitObjects(true); return true; diff --git a/ext/native/thin3d/thin3d_vulkan.cpp b/ext/native/thin3d/thin3d_vulkan.cpp index bf8d412fcc..63c967c2d5 100644 --- a/ext/native/thin3d/thin3d_vulkan.cpp +++ b/ext/native/thin3d/thin3d_vulkan.cpp @@ -1161,7 +1161,7 @@ void Thin3DVKContext::Clear(int mask, uint32_t colorval, float depthVal, int ste vkCmdClearColorAttachment(cmdBuf_, 0, imageLayout_, &col, 1, nullptr); */ } - if (mask & T3DClear::DEPTH | T3DClear::STENCIL) { + if (mask & (T3DClear::DEPTH | T3DClear::STENCIL)) { } } From b06cf4e68846b45cd83f4be5c72873090ce9be15 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 28 Feb 2016 00:34:50 +0100 Subject: [PATCH 061/116] Re-fix depth buffer initialization --- Common/Vulkan/VulkanContext.cpp | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/Common/Vulkan/VulkanContext.cpp b/Common/Vulkan/VulkanContext.cpp index 371bb94966..a6cc02c50e 100644 --- a/Common/Vulkan/VulkanContext.cpp +++ b/Common/Vulkan/VulkanContext.cpp @@ -695,8 +695,12 @@ void VulkanContext::InitDepthStencilBuffer(VkCommandBuffer cmd) { VkResult U_ASSERT_ONLY res; bool U_ASSERT_ONLY pass; VkImageCreateInfo image_info = {}; - const VkFormat depth_format = VK_FORMAT_D16_UNORM; - // const VkFormat depth_format = VK_FORMAT_D24_UNORM_S8_UINT; + // const VkFormat depth_format = VK_FORMAT_D16_UNORM; + // int aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT; + + const VkFormat depth_format = VK_FORMAT_D24_UNORM_S8_UINT; + int aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; + VkFormatProperties props; vkGetPhysicalDeviceFormatProperties(physical_devices_[0], depth_format, &props); if (props.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) { @@ -772,7 +776,7 @@ void VulkanContext::InitDepthStencilBuffer(VkCommandBuffer cmd) { view_info.components.g = VK_COMPONENT_SWIZZLE_G; view_info.components.b = VK_COMPONENT_SWIZZLE_B; view_info.components.a = VK_COMPONENT_SWIZZLE_A; - view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; + view_info.subresourceRange.aspectMask = aspectMask; view_info.subresourceRange.baseMipLevel = 0; view_info.subresourceRange.levelCount = 1; view_info.subresourceRange.baseArrayLayer = 0; From 8950509bc5a81ff4b33976bccfdbc43161e0c49c Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 28 Feb 2016 13:27:35 +0100 Subject: [PATCH 062/116] Buildfix (glslang project settings /MT) --- ext/glslang.vcxproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ext/glslang.vcxproj b/ext/glslang.vcxproj index b9f4a64d71..ad64018836 100644 --- a/ext/glslang.vcxproj +++ b/ext/glslang.vcxproj @@ -223,4 +223,4 @@ - \ No newline at end of file + From 432fbe30d1513a4cefd18057ec45a65732880893 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sat, 5 Mar 2016 01:00:59 +0100 Subject: [PATCH 063/116] Vulkan: We're doing dual src blending wrong (GLSL part, not sure how to do it right) so disable it. --- Common/Vulkan/VulkanContext.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Common/Vulkan/VulkanContext.cpp b/Common/Vulkan/VulkanContext.cpp index a6cc02c50e..378958a1b8 100644 --- a/Common/Vulkan/VulkanContext.cpp +++ b/Common/Vulkan/VulkanContext.cpp @@ -613,7 +613,7 @@ VkResult VulkanContext::CreateDevice(int physical_device) { // Enable a few safe ones if they are available. if (featuresAvailable_.dualSrcBlend) { - featuresEnabled_.dualSrcBlend = true; + // featuresEnabled_.dualSrcBlend = true; } if (featuresAvailable_.largePoints) { featuresEnabled_.largePoints = true; From 76d8a87b2f3486f432acc2d47518d93c54349dc4 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 6 Mar 2016 12:00:57 +0100 Subject: [PATCH 064/116] Vulkan: Attempt at fixing dual source blending. Should work but doesn't. --- GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp | 13 ++++++++----- GPU/Vulkan/PipelineManagerVulkan.cpp | 15 ++++++++------- GPU/Vulkan/TextureCacheVulkan.cpp | 2 ++ GPU/Vulkan/VertexShaderGeneratorVulkan.cpp | 17 ++++++++++------- Windows/GPU/WindowsVulkanContext.cpp | 5 ++--- 5 files changed, 30 insertions(+), 22 deletions(-) diff --git a/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp b/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp index ef3389112f..07adad893f 100644 --- a/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp +++ b/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp @@ -41,6 +41,11 @@ #include "GPU/ge_constants.h" #include "GPU/GPUState.h" +static const char *vulkan_glsl_preamble = + "#version 400\n" + "#extension GL_ARB_separate_shader_objects : enable\n" + "#extension GL_ARB_shading_language_420pack : enable\n\n"; + #define WRITE p+=sprintf // Missing: Z depth range @@ -49,9 +54,7 @@ bool GenerateVulkanGLSLFragmentShader(const ShaderID &id, char *buffer) { const char *lastFragData = nullptr; - WRITE(p, "#version 140\n"); // GLSL ES - WRITE(p, "#extension GL_ARB_separate_shader_objects : enable\n"); - WRITE(p, "#extension GL_ARB_shading_language_420pack : enable\n"); + WRITE(p, "%s", vulkan_glsl_preamble); bool lmode = id.Bit(FS_BIT_LMODE); bool doTexture = id.Bit(FS_BIT_DO_TEXTURE); @@ -116,9 +119,9 @@ bool GenerateVulkanGLSLFragmentShader(const ShaderID &id, char *buffer) { WRITE(p, "ivec3 roundAndScaleTo255iv(in vec3 x) { return ivec3(floor(x * 255.0 + 0.5)); }\n"); } - WRITE(p, "layout (location = 0) out vec4 fragColor0;\n"); + WRITE(p, "layout (location = 0, index = 0) out vec4 fragColor0;\n"); if (stencilToAlpha == REPLACE_ALPHA_DUALSOURCE) { - WRITE(p, "layout (location = 1) out vec4 fragColor1;\n"); + WRITE(p, "layout (location = 0, index = 1) out vec4 fragColor1;\n"); } // PowerVR needs a custom modulo function. For some reason, this has far higher precision than the builtin one. diff --git a/GPU/Vulkan/PipelineManagerVulkan.cpp b/GPU/Vulkan/PipelineManagerVulkan.cpp index 06e6733d8e..4102af0d53 100644 --- a/GPU/Vulkan/PipelineManagerVulkan.cpp +++ b/GPU/Vulkan/PipelineManagerVulkan.cpp @@ -89,12 +89,13 @@ int SetupVertexAttribs(VkVertexInputAttributeDescription attrs[], const DecVtxFo return count; } -int SetupVertexAttribsPretransformed(VkVertexInputAttributeDescription attrs[]) { - VertexAttribSetup(&attrs[0], DEC_FLOAT_4, 0, PspAttributeLocation::POSITION); - VertexAttribSetup(&attrs[1], DEC_FLOAT_3, 16, PspAttributeLocation::TEXCOORD); - VertexAttribSetup(&attrs[2], DEC_U8_4, 28, PspAttributeLocation::COLOR0); - VertexAttribSetup(&attrs[3], DEC_U8_4, 32, PspAttributeLocation::COLOR1); - return 4; +int SetupVertexAttribsPretransformed(VkVertexInputAttributeDescription attrs[], const DecVtxFormat &decFmt) { + int count = 0; + VertexAttribSetup(&attrs[count++], DEC_FLOAT_4, 0, PspAttributeLocation::POSITION); + VertexAttribSetup(&attrs[count++], DEC_FLOAT_3, 16, PspAttributeLocation::TEXCOORD); + VertexAttribSetup(&attrs[count++], DEC_U8_4, 28, PspAttributeLocation::COLOR0); + VertexAttribSetup(&attrs[count++], DEC_U8_4, 32, PspAttributeLocation::COLOR1); + return count; } static VulkanPipeline *CreateVulkanPipeline(VkDevice device, VkPipelineCache pipelineCache, VkPipelineLayout layout, VkRenderPass renderPass, const VulkanPipelineRasterStateKey &key, const VertexDecoder *vtxDec, VulkanVertexShader *vs, VulkanFragmentShader *fs, bool useHwTransform) { @@ -212,7 +213,7 @@ static VulkanPipeline *CreateVulkanPipeline(VkDevice device, VkPipelineCache pip attributeCount = SetupVertexAttribs(attrs, vtxDec->decFmt); vertexStride = vtxDec->decFmt.stride; } else { - attributeCount = SetupVertexAttribsPretransformed(attrs); + attributeCount = SetupVertexAttribsPretransformed(attrs, vtxDec->decFmt); vertexStride = 36; } diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index bd730d7495..c4695fb6bb 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -1266,6 +1266,8 @@ void TextureCacheVulkan::SetTexture() { gstate_c.textureFullAlpha = entry->GetAlphaStatus() == TexCacheEntry::STATUS_ALPHA_FULL; gstate_c.textureSimpleAlpha = entry->GetAlphaStatus() != TexCacheEntry::STATUS_ALPHA_UNKNOWN; } + gstate_c.curTextureWidth = w; + gstate_c.curTextureHeight = h; nextTexture_ = entry; VERBOSE_LOG(G3D, "Texture at %08x Found in Cache, applying", texaddr); return; //Done! diff --git a/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp b/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp index 152a274ee4..15aa010fbb 100644 --- a/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp +++ b/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp @@ -35,6 +35,11 @@ #include "GPU/Vulkan/PipelineManagerVulkan.h" #include "GPU/Vulkan/ShaderManagerVulkan.h" +static const char *vulkan_glsl_preamble = +"#version 400\n" +"#extension GL_ARB_separate_shader_objects : enable\n" +"#extension GL_ARB_shading_language_420pack : enable\n\n"; + // "Varying" layout - must match fragment shader // color0 = 0 // color1 = 1 @@ -102,9 +107,7 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { // #define USE_FOR_LOOP - WRITE(p, "#version 140\n"); // GLSL ES - WRITE(p, "#extension GL_ARB_separate_shader_objects : enable\n"); - WRITE(p, "#extension GL_ARB_shading_language_420pack : enable\n"); + WRITE(p, "%s", vulkan_glsl_preamble); bool highpFog = false; bool highpTexcoord = false; @@ -184,7 +187,7 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { if (hasColor) { WRITE(p, "layout (location = %d) in vec4 color0;\n", PspAttributeLocation::COLOR0); if (lmode && !useHWTransform) // only software transform supplies color1 as vertex data - WRITE(p, "layout (location = %d) in vec3 color1;\n", PspAttributeLocation::COLOR0); + WRITE(p, "layout (location = %d) in vec3 color1;\n", PspAttributeLocation::COLOR1); } bool prescale = false; @@ -302,9 +305,9 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { // TODO: Declare variables for dots for shade mapping if needed. - const char *ambientStr = (matUpdate & 1) && hasColor ? "color0" : "base.matambientalpha"; - const char *diffuseStr = (matUpdate & 2) && hasColor ? "color0.rgb" : "light.matdiffuse"; - const char *specularStr = (matUpdate & 4) && hasColor ? "color0.rgb" : "light.matspecular.rgb"; + const char *ambientStr = ((matUpdate & 1) && hasColor) ? "color0" : "base.matambientalpha"; + const char *diffuseStr = ((matUpdate & 2) && hasColor) ? "color0.rgb" : "light.matdiffuse"; + const char *specularStr = ((matUpdate & 4) && hasColor) ? "color0.rgb" : "light.matspecular.rgb"; bool diffuseIsZero = true; bool specularIsZero = true; diff --git a/Windows/GPU/WindowsVulkanContext.cpp b/Windows/GPU/WindowsVulkanContext.cpp index 95160d7e16..fd87b1be7a 100644 --- a/Windows/GPU/WindowsVulkanContext.cpp +++ b/Windows/GPU/WindowsVulkanContext.cpp @@ -114,11 +114,10 @@ static VkBool32 VKAPI_CALL Vulkan_Dbg(VkDebugReportFlagsEXT msgFlags, VkDebugRep } else if (msgFlags & VK_DEBUG_REPORT_DEBUG_BIT_EXT) { message << "DEBUG: "; } - message << "[" << pLayerPrefix << "] " << ObjTypeToString(objType) << " Code " << msgCode << " : " << pMsg; + message << "[" << pLayerPrefix << "] " << ObjTypeToString(objType) << " Code " << msgCode << " : " << pMsg << "\n"; #ifdef _WIN32 OutputDebugStringA(message.str().c_str()); - OutputDebugStringA("\n"); if (msgFlags & VK_DEBUG_REPORT_ERROR_BIT_EXT) { if (options->breakOnError) { DebugBreak(); @@ -132,7 +131,7 @@ static VkBool32 VKAPI_CALL Vulkan_Dbg(VkDebugReportFlagsEXT msgFlags, VkDebugRep } } #else - std::cout << message << std::endl; + std::cout << message; #endif // false indicates that layer should not bail-out of an From 22f47d37879e57c1ff5d0551ed6b0d9035246d09 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 6 Mar 2016 23:29:52 +0100 Subject: [PATCH 065/116] Remove redundant configuration, remove temp hack --- Windows/PPSSPP.sln | 100 ---------------------------------------- Windows/WindowsHost.cpp | 1 - 2 files changed, 101 deletions(-) diff --git a/Windows/PPSSPP.sln b/Windows/PPSSPP.sln index ab1953c322..6454a20c83 100644 --- a/Windows/PPSSPP.sln +++ b/Windows/PPSSPP.sln @@ -76,30 +76,18 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "glslang", "..\ext\glslang.v EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug CRT DLL|Win32 = Debug CRT DLL|Win32 - Debug CRT DLL|x64 = Debug CRT DLL|x64 Debug|Win32 = Debug|Win32 Debug|x64 = Debug|x64 - Release CRT DLL|Win32 = Release CRT DLL|Win32 - Release CRT DLL|x64 = Release CRT DLL|x64 Release|Win32 = Release|Win32 Release|x64 = Release|x64 Tests|Win32 = Tests|Win32 Tests|x64 = Tests|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Debug CRT DLL|Win32.ActiveCfg = Debug|Win32 - {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Debug CRT DLL|Win32.Build.0 = Debug|Win32 - {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Debug CRT DLL|x64.ActiveCfg = Debug|x64 - {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Debug CRT DLL|x64.Build.0 = Debug|x64 {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Debug|Win32.ActiveCfg = Debug|Win32 {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Debug|Win32.Build.0 = Debug|Win32 {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Debug|x64.ActiveCfg = Debug|x64 {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Debug|x64.Build.0 = Debug|x64 - {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Release CRT DLL|Win32.ActiveCfg = Release|Win32 - {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Release CRT DLL|Win32.Build.0 = Release|Win32 - {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Release CRT DLL|x64.ActiveCfg = Release|x64 - {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Release CRT DLL|x64.Build.0 = Release|x64 {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Release|Win32.ActiveCfg = Release|Win32 {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Release|Win32.Build.0 = Release|Win32 {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Release|x64.ActiveCfg = Release|x64 @@ -108,18 +96,10 @@ Global {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Tests|Win32.Build.0 = Release|Win32 {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Tests|x64.ActiveCfg = Release|x64 {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Tests|x64.Build.0 = Release|x64 - {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Debug CRT DLL|Win32.ActiveCfg = Debug|Win32 - {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Debug CRT DLL|Win32.Build.0 = Debug|Win32 - {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Debug CRT DLL|x64.ActiveCfg = Debug|x64 - {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Debug CRT DLL|x64.Build.0 = Debug|x64 {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Debug|Win32.ActiveCfg = Debug|Win32 {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Debug|Win32.Build.0 = Debug|Win32 {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Debug|x64.ActiveCfg = Debug|x64 {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Debug|x64.Build.0 = Debug|x64 - {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Release CRT DLL|Win32.ActiveCfg = Release|Win32 - {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Release CRT DLL|Win32.Build.0 = Release|Win32 - {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Release CRT DLL|x64.ActiveCfg = Release|x64 - {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Release CRT DLL|x64.Build.0 = Release|x64 {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Release|Win32.ActiveCfg = Release|Win32 {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Release|Win32.Build.0 = Release|Win32 {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Release|x64.ActiveCfg = Release|x64 @@ -128,18 +108,10 @@ Global {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Tests|Win32.Build.0 = Release|Win32 {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Tests|x64.ActiveCfg = Release|x64 {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Tests|x64.Build.0 = Release|x64 - {F761046E-6C38-4428-A5F1-38391A37BB34}.Debug CRT DLL|Win32.ActiveCfg = Debug|Win32 - {F761046E-6C38-4428-A5F1-38391A37BB34}.Debug CRT DLL|Win32.Build.0 = Debug|Win32 - {F761046E-6C38-4428-A5F1-38391A37BB34}.Debug CRT DLL|x64.ActiveCfg = Debug|x64 - {F761046E-6C38-4428-A5F1-38391A37BB34}.Debug CRT DLL|x64.Build.0 = Debug|x64 {F761046E-6C38-4428-A5F1-38391A37BB34}.Debug|Win32.ActiveCfg = Debug|Win32 {F761046E-6C38-4428-A5F1-38391A37BB34}.Debug|Win32.Build.0 = Debug|Win32 {F761046E-6C38-4428-A5F1-38391A37BB34}.Debug|x64.ActiveCfg = Debug|x64 {F761046E-6C38-4428-A5F1-38391A37BB34}.Debug|x64.Build.0 = Debug|x64 - {F761046E-6C38-4428-A5F1-38391A37BB34}.Release CRT DLL|Win32.ActiveCfg = Release|Win32 - {F761046E-6C38-4428-A5F1-38391A37BB34}.Release CRT DLL|Win32.Build.0 = Release|Win32 - {F761046E-6C38-4428-A5F1-38391A37BB34}.Release CRT DLL|x64.ActiveCfg = Release|x64 - {F761046E-6C38-4428-A5F1-38391A37BB34}.Release CRT DLL|x64.Build.0 = Release|x64 {F761046E-6C38-4428-A5F1-38391A37BB34}.Release|Win32.ActiveCfg = Release|Win32 {F761046E-6C38-4428-A5F1-38391A37BB34}.Release|Win32.Build.0 = Release|Win32 {F761046E-6C38-4428-A5F1-38391A37BB34}.Release|x64.ActiveCfg = Release|x64 @@ -148,18 +120,10 @@ Global {F761046E-6C38-4428-A5F1-38391A37BB34}.Tests|Win32.Build.0 = Release|Win32 {F761046E-6C38-4428-A5F1-38391A37BB34}.Tests|x64.ActiveCfg = Release|x64 {F761046E-6C38-4428-A5F1-38391A37BB34}.Tests|x64.Build.0 = Release|x64 - {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Debug CRT DLL|Win32.ActiveCfg = Debug|Win32 - {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Debug CRT DLL|Win32.Build.0 = Debug|Win32 - {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Debug CRT DLL|x64.ActiveCfg = Debug|x64 - {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Debug CRT DLL|x64.Build.0 = Debug|x64 {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Debug|Win32.ActiveCfg = Debug|Win32 {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Debug|Win32.Build.0 = Debug|Win32 {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Debug|x64.ActiveCfg = Debug|x64 {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Debug|x64.Build.0 = Debug|x64 - {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Release CRT DLL|Win32.ActiveCfg = Release|Win32 - {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Release CRT DLL|Win32.Build.0 = Release|Win32 - {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Release CRT DLL|x64.ActiveCfg = Release|x64 - {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Release CRT DLL|x64.Build.0 = Release|x64 {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Release|Win32.ActiveCfg = Release|Win32 {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Release|Win32.Build.0 = Release|Win32 {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Release|x64.ActiveCfg = Release|x64 @@ -168,18 +132,10 @@ Global {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Tests|Win32.Build.0 = Release|Win32 {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Tests|x64.ActiveCfg = Release|x64 {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Tests|x64.Build.0 = Release|x64 - {533F1D30-D04D-47CC-AD71-20F658907E36}.Debug CRT DLL|Win32.ActiveCfg = Debug|Win32 - {533F1D30-D04D-47CC-AD71-20F658907E36}.Debug CRT DLL|Win32.Build.0 = Debug|Win32 - {533F1D30-D04D-47CC-AD71-20F658907E36}.Debug CRT DLL|x64.ActiveCfg = Debug|x64 - {533F1D30-D04D-47CC-AD71-20F658907E36}.Debug CRT DLL|x64.Build.0 = Debug|x64 {533F1D30-D04D-47CC-AD71-20F658907E36}.Debug|Win32.ActiveCfg = Debug|Win32 {533F1D30-D04D-47CC-AD71-20F658907E36}.Debug|Win32.Build.0 = Debug|Win32 {533F1D30-D04D-47CC-AD71-20F658907E36}.Debug|x64.ActiveCfg = Debug|x64 {533F1D30-D04D-47CC-AD71-20F658907E36}.Debug|x64.Build.0 = Debug|x64 - {533F1D30-D04D-47CC-AD71-20F658907E36}.Release CRT DLL|Win32.ActiveCfg = Release|Win32 - {533F1D30-D04D-47CC-AD71-20F658907E36}.Release CRT DLL|Win32.Build.0 = Release|Win32 - {533F1D30-D04D-47CC-AD71-20F658907E36}.Release CRT DLL|x64.ActiveCfg = Release|x64 - {533F1D30-D04D-47CC-AD71-20F658907E36}.Release CRT DLL|x64.Build.0 = Release|x64 {533F1D30-D04D-47CC-AD71-20F658907E36}.Release|Win32.ActiveCfg = Release|Win32 {533F1D30-D04D-47CC-AD71-20F658907E36}.Release|Win32.Build.0 = Release|Win32 {533F1D30-D04D-47CC-AD71-20F658907E36}.Release|x64.ActiveCfg = Release|x64 @@ -188,18 +144,10 @@ Global {533F1D30-D04D-47CC-AD71-20F658907E36}.Tests|Win32.Build.0 = Release|Win32 {533F1D30-D04D-47CC-AD71-20F658907E36}.Tests|x64.ActiveCfg = Release|x64 {533F1D30-D04D-47CC-AD71-20F658907E36}.Tests|x64.Build.0 = Release|x64 - {C4DF647E-80EA-4111-A0A8-218B1B711E18}.Debug CRT DLL|Win32.ActiveCfg = Debug|Win32 - {C4DF647E-80EA-4111-A0A8-218B1B711E18}.Debug CRT DLL|Win32.Build.0 = Debug|Win32 - {C4DF647E-80EA-4111-A0A8-218B1B711E18}.Debug CRT DLL|x64.ActiveCfg = Debug|x64 - {C4DF647E-80EA-4111-A0A8-218B1B711E18}.Debug CRT DLL|x64.Build.0 = Debug|x64 {C4DF647E-80EA-4111-A0A8-218B1B711E18}.Debug|Win32.ActiveCfg = Debug|Win32 {C4DF647E-80EA-4111-A0A8-218B1B711E18}.Debug|Win32.Build.0 = Debug|Win32 {C4DF647E-80EA-4111-A0A8-218B1B711E18}.Debug|x64.ActiveCfg = Debug|x64 {C4DF647E-80EA-4111-A0A8-218B1B711E18}.Debug|x64.Build.0 = Debug|x64 - {C4DF647E-80EA-4111-A0A8-218B1B711E18}.Release CRT DLL|Win32.ActiveCfg = Release|Win32 - {C4DF647E-80EA-4111-A0A8-218B1B711E18}.Release CRT DLL|Win32.Build.0 = Release|Win32 - {C4DF647E-80EA-4111-A0A8-218B1B711E18}.Release CRT DLL|x64.ActiveCfg = Release|x64 - {C4DF647E-80EA-4111-A0A8-218B1B711E18}.Release CRT DLL|x64.Build.0 = Release|x64 {C4DF647E-80EA-4111-A0A8-218B1B711E18}.Release|Win32.ActiveCfg = Release|Win32 {C4DF647E-80EA-4111-A0A8-218B1B711E18}.Release|Win32.Build.0 = Release|Win32 {C4DF647E-80EA-4111-A0A8-218B1B711E18}.Release|x64.ActiveCfg = Release|x64 @@ -208,18 +156,10 @@ Global {C4DF647E-80EA-4111-A0A8-218B1B711E18}.Tests|Win32.Build.0 = Release|Win32 {C4DF647E-80EA-4111-A0A8-218B1B711E18}.Tests|x64.ActiveCfg = Release|x64 {C4DF647E-80EA-4111-A0A8-218B1B711E18}.Tests|x64.Build.0 = Release|x64 - {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Debug CRT DLL|Win32.ActiveCfg = Debug|Win32 - {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Debug CRT DLL|Win32.Build.0 = Debug|Win32 - {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Debug CRT DLL|x64.ActiveCfg = Debug|x64 - {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Debug CRT DLL|x64.Build.0 = Debug|x64 {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Debug|Win32.ActiveCfg = Debug|Win32 {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Debug|Win32.Build.0 = Debug|Win32 {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Debug|x64.ActiveCfg = Debug|x64 {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Debug|x64.Build.0 = Debug|x64 - {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Release CRT DLL|Win32.ActiveCfg = Release|Win32 - {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Release CRT DLL|Win32.Build.0 = Release|Win32 - {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Release CRT DLL|x64.ActiveCfg = Release|x64 - {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Release CRT DLL|x64.Build.0 = Release|x64 {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Release|Win32.ActiveCfg = Release|Win32 {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Release|Win32.Build.0 = Release|Win32 {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Release|x64.ActiveCfg = Release|x64 @@ -228,18 +168,10 @@ Global {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Tests|Win32.Build.0 = Release|Win32 {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Tests|x64.ActiveCfg = Release|x64 {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Tests|x64.Build.0 = Release|x64 - {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Debug CRT DLL|Win32.ActiveCfg = Debug|Win32 - {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Debug CRT DLL|Win32.Build.0 = Debug|Win32 - {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Debug CRT DLL|x64.ActiveCfg = Debug|x64 - {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Debug CRT DLL|x64.Build.0 = Debug|x64 {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Debug|Win32.ActiveCfg = Debug|Win32 {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Debug|Win32.Build.0 = Debug|Win32 {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Debug|x64.ActiveCfg = Debug|x64 {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Debug|x64.Build.0 = Debug|x64 - {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Release CRT DLL|Win32.ActiveCfg = Release|Win32 - {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Release CRT DLL|Win32.Build.0 = Release|Win32 - {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Release CRT DLL|x64.ActiveCfg = Release|x64 - {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Release CRT DLL|x64.Build.0 = Release|x64 {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Release|Win32.ActiveCfg = Release|Win32 {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Release|Win32.Build.0 = Release|Win32 {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Release|x64.ActiveCfg = Release|x64 @@ -248,18 +180,10 @@ Global {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Tests|Win32.Build.0 = Release|Win32 {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Tests|x64.ActiveCfg = Release|x64 {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Tests|x64.Build.0 = Release|x64 - {37CBC214-7CE7-4655-B619-F7CEE16E3313}.Debug CRT DLL|Win32.ActiveCfg = Debug|Win32 - {37CBC214-7CE7-4655-B619-F7CEE16E3313}.Debug CRT DLL|Win32.Build.0 = Debug|Win32 - {37CBC214-7CE7-4655-B619-F7CEE16E3313}.Debug CRT DLL|x64.ActiveCfg = Debug|x64 - {37CBC214-7CE7-4655-B619-F7CEE16E3313}.Debug CRT DLL|x64.Build.0 = Debug|x64 {37CBC214-7CE7-4655-B619-F7CEE16E3313}.Debug|Win32.ActiveCfg = Debug|Win32 {37CBC214-7CE7-4655-B619-F7CEE16E3313}.Debug|Win32.Build.0 = Debug|Win32 {37CBC214-7CE7-4655-B619-F7CEE16E3313}.Debug|x64.ActiveCfg = Debug|x64 {37CBC214-7CE7-4655-B619-F7CEE16E3313}.Debug|x64.Build.0 = Debug|x64 - {37CBC214-7CE7-4655-B619-F7CEE16E3313}.Release CRT DLL|Win32.ActiveCfg = Release|Win32 - {37CBC214-7CE7-4655-B619-F7CEE16E3313}.Release CRT DLL|Win32.Build.0 = Release|Win32 - {37CBC214-7CE7-4655-B619-F7CEE16E3313}.Release CRT DLL|x64.ActiveCfg = Release|x64 - {37CBC214-7CE7-4655-B619-F7CEE16E3313}.Release CRT DLL|x64.Build.0 = Release|x64 {37CBC214-7CE7-4655-B619-F7CEE16E3313}.Release|Win32.ActiveCfg = Release|Win32 {37CBC214-7CE7-4655-B619-F7CEE16E3313}.Release|Win32.Build.0 = Release|Win32 {37CBC214-7CE7-4655-B619-F7CEE16E3313}.Release|x64.ActiveCfg = Release|x64 @@ -268,18 +192,10 @@ Global {37CBC214-7CE7-4655-B619-F7CEE16E3313}.Tests|Win32.Build.0 = Release|Win32 {37CBC214-7CE7-4655-B619-F7CEE16E3313}.Tests|x64.ActiveCfg = Release|x64 {37CBC214-7CE7-4655-B619-F7CEE16E3313}.Tests|x64.Build.0 = Release|x64 - {004B8D11-2BE3-4BD9-AB40-2BE04CF2096F}.Debug CRT DLL|Win32.ActiveCfg = Debug|Win32 - {004B8D11-2BE3-4BD9-AB40-2BE04CF2096F}.Debug CRT DLL|Win32.Build.0 = Debug|Win32 - {004B8D11-2BE3-4BD9-AB40-2BE04CF2096F}.Debug CRT DLL|x64.ActiveCfg = Debug|x64 - {004B8D11-2BE3-4BD9-AB40-2BE04CF2096F}.Debug CRT DLL|x64.Build.0 = Debug|x64 {004B8D11-2BE3-4BD9-AB40-2BE04CF2096F}.Debug|Win32.ActiveCfg = Debug|Win32 {004B8D11-2BE3-4BD9-AB40-2BE04CF2096F}.Debug|Win32.Build.0 = Debug|Win32 {004B8D11-2BE3-4BD9-AB40-2BE04CF2096F}.Debug|x64.ActiveCfg = Debug|x64 {004B8D11-2BE3-4BD9-AB40-2BE04CF2096F}.Debug|x64.Build.0 = Debug|x64 - {004B8D11-2BE3-4BD9-AB40-2BE04CF2096F}.Release CRT DLL|Win32.ActiveCfg = Release|Win32 - {004B8D11-2BE3-4BD9-AB40-2BE04CF2096F}.Release CRT DLL|Win32.Build.0 = Release|Win32 - {004B8D11-2BE3-4BD9-AB40-2BE04CF2096F}.Release CRT DLL|x64.ActiveCfg = Release|x64 - {004B8D11-2BE3-4BD9-AB40-2BE04CF2096F}.Release CRT DLL|x64.Build.0 = Release|x64 {004B8D11-2BE3-4BD9-AB40-2BE04CF2096F}.Release|Win32.ActiveCfg = Release|Win32 {004B8D11-2BE3-4BD9-AB40-2BE04CF2096F}.Release|Win32.Build.0 = Release|Win32 {004B8D11-2BE3-4BD9-AB40-2BE04CF2096F}.Release|x64.ActiveCfg = Release|x64 @@ -288,18 +204,10 @@ Global {004B8D11-2BE3-4BD9-AB40-2BE04CF2096F}.Tests|Win32.Build.0 = Release|Win32 {004B8D11-2BE3-4BD9-AB40-2BE04CF2096F}.Tests|x64.ActiveCfg = Release|x64 {004B8D11-2BE3-4BD9-AB40-2BE04CF2096F}.Tests|x64.Build.0 = Release|x64 - {129E5E2B-39C1-4D84-96FE-DFD22DBB4A25}.Debug CRT DLL|Win32.ActiveCfg = Debug|Win32 - {129E5E2B-39C1-4D84-96FE-DFD22DBB4A25}.Debug CRT DLL|Win32.Build.0 = Debug|Win32 - {129E5E2B-39C1-4D84-96FE-DFD22DBB4A25}.Debug CRT DLL|x64.ActiveCfg = Debug|x64 - {129E5E2B-39C1-4D84-96FE-DFD22DBB4A25}.Debug CRT DLL|x64.Build.0 = Debug|x64 {129E5E2B-39C1-4D84-96FE-DFD22DBB4A25}.Debug|Win32.ActiveCfg = Debug|Win32 {129E5E2B-39C1-4D84-96FE-DFD22DBB4A25}.Debug|Win32.Build.0 = Debug|Win32 {129E5E2B-39C1-4D84-96FE-DFD22DBB4A25}.Debug|x64.ActiveCfg = Debug|x64 {129E5E2B-39C1-4D84-96FE-DFD22DBB4A25}.Debug|x64.Build.0 = Debug|x64 - {129E5E2B-39C1-4D84-96FE-DFD22DBB4A25}.Release CRT DLL|Win32.ActiveCfg = Release|Win32 - {129E5E2B-39C1-4D84-96FE-DFD22DBB4A25}.Release CRT DLL|Win32.Build.0 = Release|Win32 - {129E5E2B-39C1-4D84-96FE-DFD22DBB4A25}.Release CRT DLL|x64.ActiveCfg = Release|x64 - {129E5E2B-39C1-4D84-96FE-DFD22DBB4A25}.Release CRT DLL|x64.Build.0 = Release|x64 {129E5E2B-39C1-4D84-96FE-DFD22DBB4A25}.Release|Win32.ActiveCfg = Release|Win32 {129E5E2B-39C1-4D84-96FE-DFD22DBB4A25}.Release|Win32.Build.0 = Release|Win32 {129E5E2B-39C1-4D84-96FE-DFD22DBB4A25}.Release|x64.ActiveCfg = Release|x64 @@ -308,18 +216,10 @@ Global {129E5E2B-39C1-4D84-96FE-DFD22DBB4A25}.Tests|Win32.Build.0 = Tests|Win32 {129E5E2B-39C1-4D84-96FE-DFD22DBB4A25}.Tests|x64.ActiveCfg = Tests|x64 {129E5E2B-39C1-4D84-96FE-DFD22DBB4A25}.Tests|x64.Build.0 = Tests|x64 - {EDFA2E87-8AC1-4853-95D4-D7594FF81947}.Debug CRT DLL|Win32.ActiveCfg = Debug|Win32 - {EDFA2E87-8AC1-4853-95D4-D7594FF81947}.Debug CRT DLL|Win32.Build.0 = Debug|Win32 - {EDFA2E87-8AC1-4853-95D4-D7594FF81947}.Debug CRT DLL|x64.ActiveCfg = Debug|x64 - {EDFA2E87-8AC1-4853-95D4-D7594FF81947}.Debug CRT DLL|x64.Build.0 = Debug|x64 {EDFA2E87-8AC1-4853-95D4-D7594FF81947}.Debug|Win32.ActiveCfg = Debug|Win32 {EDFA2E87-8AC1-4853-95D4-D7594FF81947}.Debug|Win32.Build.0 = Debug|Win32 {EDFA2E87-8AC1-4853-95D4-D7594FF81947}.Debug|x64.ActiveCfg = Debug|x64 {EDFA2E87-8AC1-4853-95D4-D7594FF81947}.Debug|x64.Build.0 = Debug|x64 - {EDFA2E87-8AC1-4853-95D4-D7594FF81947}.Release CRT DLL|Win32.ActiveCfg = Release|Win32 - {EDFA2E87-8AC1-4853-95D4-D7594FF81947}.Release CRT DLL|Win32.Build.0 = Release|Win32 - {EDFA2E87-8AC1-4853-95D4-D7594FF81947}.Release CRT DLL|x64.ActiveCfg = Release|x64 - {EDFA2E87-8AC1-4853-95D4-D7594FF81947}.Release CRT DLL|x64.Build.0 = Release|x64 {EDFA2E87-8AC1-4853-95D4-D7594FF81947}.Release|Win32.ActiveCfg = Release|Win32 {EDFA2E87-8AC1-4853-95D4-D7594FF81947}.Release|Win32.Build.0 = Release|Win32 {EDFA2E87-8AC1-4853-95D4-D7594FF81947}.Release|x64.ActiveCfg = Release|x64 diff --git a/Windows/WindowsHost.cpp b/Windows/WindowsHost.cpp index 5a6e50a097..06f78162d6 100644 --- a/Windows/WindowsHost.cpp +++ b/Windows/WindowsHost.cpp @@ -187,7 +187,6 @@ void WindowsHost::SetDebugMode(bool mode) { } void WindowsHost::PollControllers(InputState &input_state) { - return; bool doPad = true; for (auto iter = this->input.begin(); iter != this->input.end(); iter++) { From 2d548d64dad9d1924524896d9f58ba8d6e6ad252 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sat, 12 Mar 2016 09:19:19 -0800 Subject: [PATCH 066/116] Move Vulkan code into a filter. --- GPU/GPU.vcxproj.filters | 95 +++++++++++++++++++++++++++++++---------- 1 file changed, 72 insertions(+), 23 deletions(-) diff --git a/GPU/GPU.vcxproj.filters b/GPU/GPU.vcxproj.filters index 771443b91c..21183c6e72 100644 --- a/GPU/GPU.vcxproj.filters +++ b/GPU/GPU.vcxproj.filters @@ -22,6 +22,9 @@ {0cbddc00-4aa3-41d0-bed2-a454d37f838e} + + {3c621896-140c-4c8b-8e4d-a478bfdeca8a} + @@ -201,18 +204,42 @@ Common - - - - - - - - - - - - + + Vulkan + + + Vulkan + + + Vulkan + + + Vulkan + + + Vulkan + + + Vulkan + + + Vulkan + + + Vulkan + + + Vulkan + + + Vulkan + + + Vulkan + + + Vulkan + @@ -398,16 +425,38 @@ Common - - - - - - - - - - - + + Vulkan + + + Vulkan + + + Vulkan + + + Vulkan + + + Vulkan + + + Vulkan + + + Vulkan + + + Vulkan + + + Vulkan + + + Vulkan + + + Vulkan + \ No newline at end of file From 323130eb862af82d09e0cd4943255b7b3a111172 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sat, 12 Mar 2016 09:21:13 -0800 Subject: [PATCH 067/116] Don't crash as hard on shader compile error. --- GPU/Vulkan/DrawEngineVulkan.cpp | 8 ++++++++ GPU/Vulkan/PipelineManagerVulkan.cpp | 5 +++++ 2 files changed, 13 insertions(+) diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index c12f8d9390..b1a4d14144 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -531,6 +531,10 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { shaderManager_->UpdateUniforms(); shaderManager_->GetShaders(prim, lastVType_, &vshader, &fshader, useHWTransform); VulkanPipeline *pipeline = pipelineManager_->GetOrCreatePipeline(pipelineLayout_, pipelineKey, dec_, vshader, fshader, true); + if (!pipeline) { + // Already logged, let's bail out. + return; + } vkCmdBindPipeline(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline->pipeline); // TODO: Avoid if same as last draw. if (pipeline->uniformBlocks & UB_VS_FS_BASE) { @@ -620,6 +624,10 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { shaderManager_->UpdateUniforms(); shaderManager_->GetShaders(prim, lastVType_, &vshader, &fshader, useHWTransform); VulkanPipeline *pipeline = pipelineManager_->GetOrCreatePipeline(pipelineLayout_, pipelineKey, dec_, vshader, fshader, false); + if (!pipeline) { + // Already logged, let's bail out. + return; + } vkCmdBindPipeline(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline->pipeline); // TODO: Avoid if same as last draw. if (pipeline->uniformBlocks & UB_VS_FS_BASE) { diff --git a/GPU/Vulkan/PipelineManagerVulkan.cpp b/GPU/Vulkan/PipelineManagerVulkan.cpp index 4102af0d53..ef51bf6e9e 100644 --- a/GPU/Vulkan/PipelineManagerVulkan.cpp +++ b/GPU/Vulkan/PipelineManagerVulkan.cpp @@ -197,6 +197,11 @@ static VulkanPipeline *CreateVulkanPipeline(VkDevice device, VkPipelineCache pip ss[1].pName = "main"; ss[1].flags = 0; + if (!ss[0].module || !ss[1].module) { + ERROR_LOG(G3D, "Failed creating graphics pipeline - bad shaders"); + return nullptr; + } + VkPipelineInputAssemblyStateCreateInfo inputAssembly; inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; inputAssembly.pNext = nullptr; From ba7deb7c9aff89a2fdc95ff473dd3fd17972a1e4 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sat, 12 Mar 2016 09:36:59 -0800 Subject: [PATCH 068/116] Fix GE debugger preview in non-buffered. --- GPU/GLES/Framebuffer.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GPU/GLES/Framebuffer.cpp b/GPU/GLES/Framebuffer.cpp index 6ef3bf0ffe..b33e886bb1 100644 --- a/GPU/GLES/Framebuffer.cpp +++ b/GPU/GLES/Framebuffer.cpp @@ -1987,7 +1987,7 @@ bool FramebufferManager::GetFramebuffer(u32 fb_address, int fb_stride, GEBufferF return true; } - buffer.Allocate(vfb->renderWidth, vfb->renderHeight, GE_FORMAT_8888, false, true); + buffer.Allocate(vfb->renderWidth, vfb->renderHeight, GE_FORMAT_8888, !useBufferedRendering_, true); if (vfb->fbo) fbo_bind_for_read(vfb->fbo); if (gl_extensions.GLES3 || !gl_extensions.IsGLES) From 8efbcf8d4240f9deef877a0078425d4dfaf7a13a Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sat, 12 Mar 2016 13:37:08 -0800 Subject: [PATCH 069/116] Use draws for alpha/stencil only clear in Vulkan. --- GPU/Common/SoftwareTransformCommon.cpp | 23 ++++++++++++++++------- GPU/Common/SoftwareTransformCommon.h | 13 +++++++++++-- GPU/Directx9/TransformPipelineDX9.cpp | 13 +++++++++++-- GPU/GLES/TransformPipeline.cpp | 14 ++++++++++++-- GPU/Vulkan/DrawEngineVulkan.cpp | 18 ++++++++++++++---- 5 files changed, 64 insertions(+), 17 deletions(-) diff --git a/GPU/Common/SoftwareTransformCommon.cpp b/GPU/Common/SoftwareTransformCommon.cpp index 00a05dc4a0..1ba4bfc3de 100644 --- a/GPU/Common/SoftwareTransformCommon.cpp +++ b/GPU/Common/SoftwareTransformCommon.cpp @@ -129,8 +129,14 @@ static bool IsReallyAClear(const TransformedVertex *transformed, int numVerts) { } void SoftwareTransform( - int prim, u8 *decoded, int vertexCount, u32 vertType, u16 *&inds, int indexType, - const DecVtxFormat &decVtxFormat, int &maxIndex, FramebufferManagerCommon *fbman, TextureCacheCommon *texCache, TransformedVertex *transformed, TransformedVertex *transformedExpanded, TransformedVertex *&drawBuffer, int &numTrans, bool &drawIndexed, SoftwareTransformResult *result, float ySign) { + int prim, int vertexCount, u32 vertType, u16 *&inds, int indexType, + const DecVtxFormat &decVtxFormat, int &maxIndex, TransformedVertex *&drawBuffer, int &numTrans, bool &drawIndexed, const SoftwareTransformParams *params, SoftwareTransformResult *result) { + u8 *decoded = params->decoded; + FramebufferManagerCommon *fbman = params->fbman; + TextureCacheCommon *texCache = params->texCache; + TransformedVertex *transformed = params->transformed; + TransformedVertex *transformedExpanded = params->transformedExpanded; + float ySign = 1.0f; bool throughmode = (vertType & GE_VTYPE_THROUGH_MASK) != 0; bool lmode = gstate.isUsingSecondaryColor() && gstate.isLightingEnabled(); @@ -406,11 +412,14 @@ void SoftwareTransform( // Experiment: Disable on PowerVR (see issue #6290) // TODO: This bleeds outside the play area in non-buffered mode. Big deal? Probably not. if (maxIndex > 1 && gstate.isModeClear() && prim == GE_PRIM_RECTANGLES && IsReallyAClear(transformed, maxIndex) && gl_extensions.gpuVendor != GPU_VENDOR_POWERVR) { // && g_Config.iRenderingMode != FB_NON_BUFFERED_MODE) { - result->color = transformed[1].color0_32; - // Need to rescale from a [0, 1] float. This is the final transformed value. - result->depth = ToScaledDepth((s16)(int)(transformed[1].z * 65535.0f)); - result->action = SW_CLEAR; - return; + bool separateAlphaClear = gstate.isClearModeColorMask() != gstate.isClearModeAlphaMask(); + if (params->allowSeparateAlphaClear || !separateAlphaClear) { + result->color = transformed[1].color0_32; + // Need to rescale from a [0, 1] float. This is the final transformed value. + result->depth = ToScaledDepth((s16)(int)(transformed[1].z * 65535.0f)); + result->action = SW_CLEAR; + return; + } } // This means we're using a framebuffer (and one that isn't big enough.) diff --git a/GPU/Common/SoftwareTransformCommon.h b/GPU/Common/SoftwareTransformCommon.h index 581bfbfbd5..9ae3bd2697 100644 --- a/GPU/Common/SoftwareTransformCommon.h +++ b/GPU/Common/SoftwareTransformCommon.h @@ -38,5 +38,14 @@ struct SoftwareTransformResult { u8 stencilValue; }; -void SoftwareTransform(int prim, u8 *decoded, int vertexCount, u32 vertexType, u16 *&inds, int indexType, const DecVtxFormat &decVtxFormat, int &maxIndex, FramebufferManagerCommon *fbman, TextureCacheCommon *texCache, TransformedVertex *transformed, TransformedVertex *transformedExpanded, TransformedVertex *&drawBuffer, - int &numTrans, bool &drawIndexed, SoftwareTransformResult *result, float ySign); +struct SoftwareTransformParams { + u8 *decoded; + TransformedVertex *transformed; + TransformedVertex *transformedExpanded; + FramebufferManagerCommon *fbman; + TextureCacheCommon *texCache; + bool allowSeparateAlphaClear; +}; + +void SoftwareTransform(int prim, int vertexCount, u32 vertexType, u16 *&inds, int indexType, const DecVtxFormat &decVtxFormat, int &maxIndex, TransformedVertex *&drawBuffer, + int &numTrans, bool &drawIndexed, const SoftwareTransformParams *params, SoftwareTransformResult *result); diff --git a/GPU/Directx9/TransformPipelineDX9.cpp b/GPU/Directx9/TransformPipelineDX9.cpp index 19f894c7b8..5e9f9d6596 100644 --- a/GPU/Directx9/TransformPipelineDX9.cpp +++ b/GPU/Directx9/TransformPipelineDX9.cpp @@ -828,11 +828,20 @@ rotateVBO: SoftwareTransformResult result; memset(&result, 0, sizeof(result)); + SoftwareTransformParams params; + memset(¶ms, 0, sizeof(params)); + params.decoded = decoded; + params.transformed = transformed; + params.transformedExpanded = transformedExpanded; + params.fbman = framebufferManager_; + params.texCache = textureCache_; + params.allowSeparateAlphaClear = true; + int maxIndex = indexGen.MaxIndex(); SoftwareTransform( - prim, decoded, indexGen.VertexCount(), + prim, indexGen.VertexCount(), dec_->VertexType(), inds, GE_VTYPE_IDX_16BIT, dec_->GetDecVtxFmt(), - maxIndex, framebufferManager_, textureCache_, transformed, transformedExpanded, drawBuffer, numTrans, drawIndexed, &result, 1.0f); + maxIndex, drawBuffer, numTrans, drawIndexed, ¶ms, &result); ApplyDrawStateLate(); vshader = shaderManager_->ApplyShader(prim, lastVType_); diff --git a/GPU/GLES/TransformPipeline.cpp b/GPU/GLES/TransformPipeline.cpp index b23d5239bc..edd8a8657a 100644 --- a/GPU/GLES/TransformPipeline.cpp +++ b/GPU/GLES/TransformPipeline.cpp @@ -890,11 +890,21 @@ rotateVBO: SoftwareTransformResult result; memset(&result, 0, sizeof(result)); + // TODO: Keep this static? Faster than repopulating? + SoftwareTransformParams params; + memset(¶ms, 0, sizeof(params)); + params.decoded = decoded; + params.transformed = transformed; + params.transformedExpanded = transformedExpanded; + params.fbman = framebufferManager_; + params.texCache = textureCache_; + params.allowSeparateAlphaClear = true; + int maxIndex = indexGen.MaxIndex(); SoftwareTransform( - prim, decoded, indexGen.VertexCount(), + prim, indexGen.VertexCount(), dec_->VertexType(), inds, GE_VTYPE_IDX_16BIT, dec_->GetDecVtxFmt(), - maxIndex, framebufferManager_, textureCache_, transformed, transformedExpanded, drawBuffer, numTrans, drawIndexed, &result, 1.0); + maxIndex, drawBuffer, numTrans, drawIndexed, ¶ms, &result); ApplyDrawStateLate(); LinkedShader *program = shaderManager_->ApplyFragmentShader(vsid, vshader, lastVType_, prim); diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index b1a4d14144..4d42ef4dff 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -591,11 +591,20 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { SoftwareTransformResult result; memset(&result, 0, sizeof(result)); + SoftwareTransformParams params; + memset(¶ms, 0, sizeof(params)); + params.decoded = decoded; + params.transformed = transformed; + params.transformedExpanded = transformedExpanded; + params.fbman = framebufferManager_; + params.texCache = textureCache_; + params.allowSeparateAlphaClear = false; + int maxIndex = indexGen.MaxIndex(); SoftwareTransform( - prim, decoded, indexGen.VertexCount(), + prim, indexGen.VertexCount(), dec_->VertexType(), inds, GE_VTYPE_IDX_16BIT, dec_->GetDecVtxFmt(), - maxIndex, framebufferManager_, textureCache_, transformed, transformedExpanded, drawBuffer, numTrans, drawIndexed, &result, 1.0f); + maxIndex, drawBuffer, numTrans, drawIndexed, ¶ms, &result); // Only here, where we know whether to clear or to draw primitives, should we actually set the current framebuffer! Because that gives use the opportunity // to use a "pre-clear" render pass, for high efficiency on tilers. @@ -657,8 +666,9 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { vkCmdDraw(cmd_, numTrans, 1, 0, 0); } } else if (result.action == SW_CLEAR) { - // TODO: Support clearing only color and not alpha, or vice versa. This is not supported (probably for good reason) by vkCmdClearColorAttachment - // so we will have to simply draw a rectangle instead. + // Note: we won't get here if the clear is alpha but not color, or color but not alpha. + // A rectangle will be used instead. + // TODO: If this is the first clear in a frame, translate to a cleared attachment load instead. int mask = gstate.isClearModeColorMask() ? 1 : 0; if (gstate.isClearModeAlphaMask()) mask |= 2; From c92790c5a8b9d7c4080100c44918061f850392fc Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sat, 12 Mar 2016 14:03:26 -0800 Subject: [PATCH 070/116] Specify a useful app version when loading Vulkan. --- Common/Vulkan/VulkanContext.cpp | 5 +++-- Common/Vulkan/VulkanContext.h | 2 +- Windows/GPU/WindowsVulkanContext.cpp | 6 +++++- android/jni/app-android.cpp | 3 ++- ext/native/util/text/parsers.cpp | 5 +++++ ext/native/util/text/parsers.h | 1 + 6 files changed, 17 insertions(+), 5 deletions(-) diff --git a/Common/Vulkan/VulkanContext.cpp b/Common/Vulkan/VulkanContext.cpp index 378958a1b8..879ae8953f 100644 --- a/Common/Vulkan/VulkanContext.cpp +++ b/Common/Vulkan/VulkanContext.cpp @@ -28,7 +28,7 @@ using namespace std; -VulkanContext::VulkanContext(const char *app_name, uint32_t flags) +VulkanContext::VulkanContext(const char *app_name, int app_ver, uint32_t flags) : device_(nullptr), gfx_queue_(VK_NULL_HANDLE), #ifdef _WIN32 @@ -88,8 +88,9 @@ VulkanContext::VulkanContext(const char *app_name, uint32_t flags) app_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; app_info.pNext = NULL; app_info.pApplicationName = app_name; - app_info.applicationVersion = 1; + app_info.applicationVersion = app_ver; app_info.pEngineName = app_name; + // Let's increment this when we make major engine/context changes. app_info.engineVersion = 1; #ifdef ANDROID // For some strange reason, the Shield TV wants 1.0.2, not 1.0.3. diff --git a/Common/Vulkan/VulkanContext.h b/Common/Vulkan/VulkanContext.h index 1ef29e4203..1c2b6f31d3 100644 --- a/Common/Vulkan/VulkanContext.h +++ b/Common/Vulkan/VulkanContext.h @@ -150,7 +150,7 @@ private: // Optionally, it can create a depth buffer for you as well. class VulkanContext { public: - VulkanContext(const char *app_name, uint32_t flags); + VulkanContext(const char *app_name, int app_ver, uint32_t flags); ~VulkanContext(); VkResult CreateDevice(int physical_device); diff --git a/Windows/GPU/WindowsVulkanContext.cpp b/Windows/GPU/WindowsVulkanContext.cpp index fd87b1be7a..3a7f3a63a7 100644 --- a/Windows/GPU/WindowsVulkanContext.cpp +++ b/Windows/GPU/WindowsVulkanContext.cpp @@ -54,8 +54,11 @@ #include "Common/Vulkan/VulkanContext.h" #include "thin3d/thin3d.h" +#include "util/text/parsers.h" #include "Windows/GPU/WindowsVulkanContext.h" +extern const char *PPSSPP_GIT_VERSION; + static const bool g_validate_ = true; static VulkanContext *g_Vulkan; @@ -156,7 +159,8 @@ bool WindowsVulkanContext::Init(HINSTANCE hInst, HWND hWnd, std::string *error_m g_LogOptions.breakOnWarning = true; g_LogOptions.msgBoxOnError = false; - g_Vulkan = new VulkanContext("PPSSPP", (g_validate_ ? VULKAN_FLAG_VALIDATE : 0) | VULKAN_FLAG_PRESENT_MAILBOX); + Version gitVer(PPSSPP_GIT_VERSION); + g_Vulkan = new VulkanContext("PPSSPP", gitVer.ToInteger(), (g_validate_ ? VULKAN_FLAG_VALIDATE : 0) | VULKAN_FLAG_PRESENT_MAILBOX); g_Vulkan->CreateDevice(0); if (g_validate_) { int bits = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT; diff --git a/android/jni/app-android.cpp b/android/jni/app-android.cpp index 73e0db30ff..52426ed1ec 100644 --- a/android/jni/app-android.cpp +++ b/android/jni/app-android.cpp @@ -245,7 +245,8 @@ bool AndroidVulkanContext::Init(ANativeWindow *wnd, int desiredBackbufferSizeX, g_LogOptions.msgBoxOnError = false; ILOG("Creating vulkan context"); - g_Vulkan = new VulkanContext("PPSSPP", VULKAN_FLAG_PRESENT_MAILBOX | VULKAN_FLAG_PRESENT_FIFO_RELAXED); + Version gitVer(PPSSPP_GIT_VERSION); + g_Vulkan = new VulkanContext("PPSSPP", gitVer.ToInteger(), VULKAN_FLAG_PRESENT_MAILBOX | VULKAN_FLAG_PRESENT_FIFO_RELAXED); if (!g_Vulkan->GetInstance()) { ELOG("Failed to create vulkan context"); return false; diff --git a/ext/native/util/text/parsers.cpp b/ext/native/util/text/parsers.cpp index 748a292a50..ea53d43d6f 100644 --- a/ext/native/util/text/parsers.cpp +++ b/ext/native/util/text/parsers.cpp @@ -22,6 +22,11 @@ std::string Version::ToString() const { return std::string(temp); } +int Version::ToInteger() const { + // This allows for ~2000 major versions, ~100 minor versions, and ~10000 sub versions. + return major * 1000000 + minor * 10000 + sub; +} + bool ParseMacAddress(std::string str, uint8_t macAddr[6]) { int mac[6]; if (6 != sscanf(str.c_str(), "%02x:%02x:%02x:%02x:%02x:%02x", &mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5])) { diff --git a/ext/native/util/text/parsers.h b/ext/native/util/text/parsers.h index 7f763cf9b8..fbf2c36d99 100644 --- a/ext/native/util/text/parsers.h +++ b/ext/native/util/text/parsers.h @@ -48,6 +48,7 @@ struct Version { } std::string ToString() const; + int ToInteger() const; private: bool ParseVersionString(std::string str); }; From 6e2e0bfa33e023b302671e94a638977e6ce4f3e3 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 13 Mar 2016 15:26:32 +0100 Subject: [PATCH 071/116] Should not specify the Vulkan patch version when requesting Vulkan 1.0. --- Common/Vulkan/VulkanContext.cpp | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/Common/Vulkan/VulkanContext.cpp b/Common/Vulkan/VulkanContext.cpp index 879ae8953f..d6f17920fe 100644 --- a/Common/Vulkan/VulkanContext.cpp +++ b/Common/Vulkan/VulkanContext.cpp @@ -92,12 +92,7 @@ VulkanContext::VulkanContext(const char *app_name, int app_ver, uint32_t flags) app_info.pEngineName = app_name; // Let's increment this when we make major engine/context changes. app_info.engineVersion = 1; -#ifdef ANDROID - // For some strange reason, the Shield TV wants 1.0.2, not 1.0.3. - app_info.apiVersion = VK_MAKE_VERSION(1, 0, 2); -#else - app_info.apiVersion = VK_API_VERSION; -#endif + app_info.apiVersion = VK_MAKE_VERSION(1, 0, 0); VkInstanceCreateInfo inst_info = {}; inst_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; inst_info.pNext = NULL; From b7b0b59e9ab1a4b7b0103d85c328b1e98819e71c Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 13 Mar 2016 15:42:10 +0100 Subject: [PATCH 072/116] Update Vulkan headers to 1.0.5. Remove references to vulkan-1.lib as we load dynamically. --- Windows/PPSSPP.vcxproj | 8 +-- ext/vulkan/icd-spv.h | 35 +++++----- ext/vulkan/vk_debug_marker_layer.h | 44 ------------- ext/vulkan/vk_icd.h | 13 +++- ext/vulkan/vk_layer.h | 15 ++++- ext/vulkan/vk_lunarg_debug_marker.h | 98 ---------------------------- ext/vulkan/vk_platform.h | 2 +- ext/vulkan/vk_sdk_platform.h | 2 - ext/vulkan/vulkan-1.lib | Bin 35956 -> 0 bytes ext/vulkan/vulkan.h | 34 ++++++---- headless/Headless.vcxproj | 8 +-- unittest/UnitTests.vcxproj | 8 +-- 12 files changed, 79 insertions(+), 188 deletions(-) delete mode 100644 ext/vulkan/vk_debug_marker_layer.h delete mode 100644 ext/vulkan/vk_lunarg_debug_marker.h delete mode 100644 ext/vulkan/vulkan-1.lib diff --git a/Windows/PPSSPP.vcxproj b/Windows/PPSSPP.vcxproj index 845e7baf7f..4a61e38dd2 100644 --- a/Windows/PPSSPP.vcxproj +++ b/Windows/PPSSPP.vcxproj @@ -134,7 +134,7 @@ Disabled - ..\ext\vulkan\vulkan-1.lib;Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86\lib\avcodec.lib;..\ffmpeg\Windows\x86\lib\avformat.lib;..\ffmpeg\Windows\x86\lib\avutil.lib;..\ffmpeg\Windows\x86\lib\swresample.lib;..\ffmpeg\Windows\x86\lib\swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) + Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86\lib\avcodec.lib;..\ffmpeg\Windows\x86\lib\avformat.lib;..\ffmpeg\Windows\x86\lib\avutil.lib;..\ffmpeg\Windows\x86\lib\swresample.lib;..\ffmpeg\Windows\x86\lib\swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) true Windows MachineX86 @@ -171,7 +171,7 @@ Disabled - ..\ext\vulkan\vulkan-1.lib;Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86_64\lib\avcodec.lib;..\ffmpeg\Windows\x86_64\lib\avformat.lib;..\ffmpeg\Windows\x86_64\lib\avutil.lib;..\ffmpeg\Windows\x86_64\lib\swresample.lib;..\ffmpeg\Windows\x86_64\lib\swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) + Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86_64\lib\avcodec.lib;..\ffmpeg\Windows\x86_64\lib\avformat.lib;..\ffmpeg\Windows\x86_64\lib\avutil.lib;..\ffmpeg\Windows\x86_64\lib\swresample.lib;..\ffmpeg\Windows\x86_64\lib\swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) true $(OutDir)$(ProjectName).pdb true @@ -206,7 +206,7 @@ false - ..\ext\vulkan\vulkan-1.lib;Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86\lib\avcodec.lib;..\ffmpeg\Windows\x86\lib\avformat.lib;..\ffmpeg\Windows\x86\lib\avutil.lib;..\ffmpeg\Windows\x86\lib\swresample.lib;..\ffmpeg\Windows\x86\lib\swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) + Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86\lib\avcodec.lib;..\ffmpeg\Windows\x86\lib\avformat.lib;..\ffmpeg\Windows\x86\lib\avutil.lib;..\ffmpeg\Windows\x86\lib\swresample.lib;..\ffmpeg\Windows\x86\lib\swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) $(OutDir)$(TargetName)$(TargetExt) %(AdditionalLibraryDirectories) true @@ -250,7 +250,7 @@ false - ..\ext\vulkan\vulkan-1.lib;Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86_64\lib\avcodec.lib;..\ffmpeg\Windows\x86_64\lib\avformat.lib;..\ffmpeg\Windows\x86_64\lib\avutil.lib;..\ffmpeg\Windows\x86_64\lib\swresample.lib;..\ffmpeg\Windows\x86_64\lib\swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) + Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86_64\lib\avcodec.lib;..\ffmpeg\Windows\x86_64\lib\avformat.lib;..\ffmpeg\Windows\x86_64\lib\avutil.lib;..\ffmpeg\Windows\x86_64\lib\swresample.lib;..\ffmpeg\Windows\x86_64\lib\swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) %(AdditionalLibraryDirectories) true Windows diff --git a/ext/vulkan/icd-spv.h b/ext/vulkan/icd-spv.h index b6640a4b3d..3019a1d2ca 100644 --- a/ext/vulkan/icd-spv.h +++ b/ext/vulkan/icd-spv.h @@ -1,28 +1,27 @@ /* + * Copyright (c) 2015-2016 Valve Corporation + * Copyright (c) 2015-2016 LunarG, Inc. * - * Copyright (C) 2015-2016 Valve Corporation - * Copyright (C) 2015-2016 LunarG, Inc. + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and/or associated documentation files (the "Materials"), to + * deal in the Materials without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Materials, and to permit persons to whom the Materials are + * furnished to do so, subject to the following conditions: * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and associated documentation files (the "Software"), - * to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, - * and/or sell copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following conditions: + * The above copyright notice(s) and this permission notice shall be included in + * all copies or substantial portions of the Materials. * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE + * USE OR OTHER DEALINGS IN THE MATERIALS. * * Author: Cody Northrop - * */ #ifndef ICD_SPV_H diff --git a/ext/vulkan/vk_debug_marker_layer.h b/ext/vulkan/vk_debug_marker_layer.h deleted file mode 100644 index e882b02b48..0000000000 --- a/ext/vulkan/vk_debug_marker_layer.h +++ /dev/null @@ -1,44 +0,0 @@ -// -// File: vk_debug_marker_layer.h -// -/* - * Copyright (c) 2015-2016 The Khronos Group Inc. - * Copyright (c) 2015-2016 Valve Corporation - * Copyright (c) 2015-2016 LunarG, Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and/or associated documentation files (the "Materials"), to - * deal in the Materials without restriction, including without limitation the - * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or - * sell copies of the Materials, and to permit persons to whom the Materials are - * furnished to do so, subject to the following conditions: - * - * The above copyright notice(s) and this permission notice shall be included in - * all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE - * USE OR OTHER DEALINGS IN THE MATERIALS. - * - * Authors: - * Jon Ashburn - * Courtney Goeltzenleuchter - */ - -#pragma once - -#include "vulkan.h" -#include "vk_lunarg_debug_marker.h" -#include "vk_layer.h" - -typedef struct VkLayerDebugMarkerDispatchTable_ { - PFN_vkCmdDbgMarkerBegin CmdDbgMarkerBegin; - PFN_vkCmdDbgMarkerEnd CmdDbgMarkerEnd; - PFN_vkDbgSetObjectTag DbgSetObjectTag; - PFN_vkDbgSetObjectName DbgSetObjectName; -} VkLayerDebugMarkerDispatchTable; diff --git a/ext/vulkan/vk_icd.h b/ext/vulkan/vk_icd.h index 60b29e037b..fdb1e6e433 100644 --- a/ext/vulkan/vk_icd.h +++ b/ext/vulkan/vk_icd.h @@ -30,7 +30,7 @@ #ifndef VKICD_H #define VKICD_H -#include "vk_platform.h" +#include "vulkan.h" /* * The ICD must reserve space for a pointer for the loader's dispatch @@ -65,6 +65,7 @@ typedef enum _VkIcdWsiPlatform { VK_ICD_WSI_PLATFORM_WIN32, VK_ICD_WSI_PLATFORM_XCB, VK_ICD_WSI_PLATFORM_XLIB, + VK_ICD_WSI_PLATFORM_DISPLAY } VkIcdWsiPlatform; typedef struct _VkIcdSurfaceBase { @@ -111,4 +112,14 @@ typedef struct _VkIcdSurfaceXlib { } VkIcdSurfaceXlib; #endif // VK_USE_PLATFORM_XLIB_KHR +typedef struct _VkIcdSurfaceDisplay { + VkIcdSurfaceBase base; + VkDisplayModeKHR displayMode; + uint32_t planeIndex; + uint32_t planeStackIndex; + VkSurfaceTransformFlagBitsKHR transform; + float globalAlpha; + VkDisplayPlaneAlphaFlagBitsKHR alphaMode; + VkExtent2D imageExtent; +} VkIcdSurfaceDisplay; #endif // VKICD_H diff --git a/ext/vulkan/vk_layer.h b/ext/vulkan/vk_layer.h index 2487043401..95d8802553 100644 --- a/ext/vulkan/vk_layer.h +++ b/ext/vulkan/vk_layer.h @@ -34,7 +34,6 @@ #pragma once #include "vulkan.h" -#include "vk_lunarg_debug_marker.h" #if defined(__GNUC__) && __GNUC__ >= 4 #define VK_LAYER_EXPORT __attribute__((visibility("default"))) #elif defined(__SUNPRO_C) && (__SUNPRO_C >= 0x590) @@ -226,6 +225,20 @@ typedef struct VkLayerInstanceDispatchTable_ { #ifdef VK_USE_PLATFORM_ANDROID_KHR PFN_vkCreateAndroidSurfaceKHR CreateAndroidSurfaceKHR; #endif + PFN_vkGetPhysicalDeviceDisplayPropertiesKHR + GetPhysicalDeviceDisplayPropertiesKHR; + PFN_vkGetPhysicalDeviceDisplayPlanePropertiesKHR + GetPhysicalDeviceDisplayPlanePropertiesKHR; + PFN_vkGetDisplayPlaneSupportedDisplaysKHR + GetDisplayPlaneSupportedDisplaysKHR; + PFN_vkGetDisplayModePropertiesKHR + GetDisplayModePropertiesKHR; + PFN_vkCreateDisplayModeKHR + CreateDisplayModeKHR; + PFN_vkGetDisplayPlaneCapabilitiesKHR + GetDisplayPlaneCapabilitiesKHR; + PFN_vkCreateDisplayPlaneSurfaceKHR + CreateDisplayPlaneSurfaceKHR; } VkLayerInstanceDispatchTable; // LL node for tree of dbg callback functions diff --git a/ext/vulkan/vk_lunarg_debug_marker.h b/ext/vulkan/vk_lunarg_debug_marker.h deleted file mode 100644 index edff2b9eee..0000000000 --- a/ext/vulkan/vk_lunarg_debug_marker.h +++ /dev/null @@ -1,98 +0,0 @@ -// -// File: vk_lunarg_debug_marker.h -// -/* - * Copyright (c) 2015-2016 The Khronos Group Inc. - * Copyright (c) 2015-2016 Valve Corporation - * Copyright (c) 2015-2016 LunarG, Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and/or associated documentation files (the "Materials"), to - * deal in the Materials without restriction, including without limitation the - * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or - * sell copies of the Materials, and to permit persons to whom the Materials are - * furnished to do so, subject to the following conditions: - * - * The above copyright notice(s) and this permission notice shall be included in - * all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE - * USE OR OTHER DEALINGS IN THE MATERIALS. - * - * Authors: - * Jon Ashburn - * Courtney Goeltzenleuchter - */ - -#ifndef __VK_DEBUG_MARKER_H__ -#define __VK_DEBUG_MARKER_H__ - -#include "vulkan.h" - -#define VK_DEBUG_MARKER_EXTENSION_NUMBER 6 -#define VK_DEBUG_MARKER_EXTENSION_REVISION 1 -#ifdef __cplusplus -extern "C" { -#endif // __cplusplus - -/* -*************************************************************************************************** -* DebugMarker Vulkan Extension API -*************************************************************************************************** -*/ - -#define DEBUG_MARKER_EXTENSION_NAME "VK_LUNARG_DEBUG_MARKER" - -// ------------------------------------------------------------------------------------------------ -// Enumerations - -#define VK_DEBUG_MARKER_ENUM_EXTEND(type, id) \ - ((type)(VK_DEBUG_MARKER_EXTENSION_NUMBER * -1000 + (id))) - -#define VK_OBJECT_INFO_TYPE_DBG_OBJECT_TAG \ - VK_DEBUG_MARKER_ENUM_EXTEND(VkDbgObjectInfoType, 0) -#define VK_OBJECT_INFO_TYPE_DBG_OBJECT_NAME \ - VK_DEBUG_MARKER_ENUM_EXTEND(VkDbgObjectInfoType, 1) - -// ------------------------------------------------------------------------------------------------ -// API functions - -typedef void(VKAPI_PTR *PFN_vkCmdDbgMarkerBegin)(VkCommandBuffer commandBuffer, - const char *pMarker); -typedef void(VKAPI_PTR *PFN_vkCmdDbgMarkerEnd)(VkCommandBuffer commandBuffer); -typedef VkResult(VKAPI_PTR *PFN_vkDbgSetObjectTag)( - VkDevice device, VkDebugReportObjectTypeEXT objType, uint64_t object, - size_t tagSize, const void *pTag); -typedef VkResult(VKAPI_PTR *PFN_vkDbgSetObjectName)( - VkDevice device, VkDebugReportObjectTypeEXT objType, uint64_t object, - size_t nameSize, const char *pName); - -#ifndef VK_NO_PROTOTYPES - -// DebugMarker extension entrypoints -VKAPI_ATTR void VKAPI_CALL -vkCmdDbgMarkerBegin(VkCommandBuffer commandBuffer, const char *pMarker); - -VKAPI_ATTR void VKAPI_CALL vkCmdDbgMarkerEnd(VkCommandBuffer commandBuffer); - -VKAPI_ATTR VkResult VKAPI_CALL -vkDbgSetObjectTag(VkDevice device, VkDebugReportObjectTypeEXT objType, - uint64_t object, size_t tagSize, const void *pTag); - -VKAPI_ATTR VkResult VKAPI_CALL -vkDbgSetObjectName(VkDevice device, VkDebugReportObjectTypeEXT objType, - uint64_t object, size_t nameSize, const char *pName); - -#endif // VK_NO_PROTOTYPES - -#ifdef __cplusplus -} // extern "C" -#endif // __cplusplus - -#endif // __VK_DEBUG_MARKER_H__ diff --git a/ext/vulkan/vk_platform.h b/ext/vulkan/vk_platform.h index a53e725a9a..075a18cab3 100644 --- a/ext/vulkan/vk_platform.h +++ b/ext/vulkan/vk_platform.h @@ -2,7 +2,7 @@ // File: vk_platform.h // /* -** Copyright (c) 2014-2015 The Khronos Group Inc. +** Copyright (c) 2014-2016 The Khronos Group Inc. ** ** Permission is hereby granted, free of charge, to any person obtaining a ** copy of this software and/or associated documentation files (the diff --git a/ext/vulkan/vk_sdk_platform.h b/ext/vulkan/vk_sdk_platform.h index 6450895df2..f79396bac1 100644 --- a/ext/vulkan/vk_sdk_platform.h +++ b/ext/vulkan/vk_sdk_platform.h @@ -46,9 +46,7 @@ #define snprintf _snprintf #endif -#ifndef strdup #define strdup _strdup -#endif #endif // _WIN32 diff --git a/ext/vulkan/vulkan-1.lib b/ext/vulkan/vulkan-1.lib deleted file mode 100644 index fa61ca91d0a395242f09364a15d41bb811b00de4..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 35956 zcmeHQON?Ac)jl{O81pg?gkVhKfN>rq#&%|G2l9g-W5*MZ?a9pek>|KQeaF*wPxrW| zd+bT#JRQezOb8)76d@J}MJ!k$gd&7c#DWD2^a~*rA^v}XSRhu21ws*m|EtHTd+Of0 z<-WO--9OTCcbz&_Up-DePSvUQO?THiQ!`&)@rAYi-==}V!NINDHg4SN^EcYywyhfn z%-3Tph~9Gt(apa6r8^h8~5SqUTXAMHkl@n*TYGqI-X2=q$>i z=()EIy||u8(V6QEJ@*9opv9wx_FX2@^e=pZ&i>KRV=oaYdVIN|ryeI#bm1*SQ^$!E z&7zEoE{z#_Y%S7(E?;A4W*d>B(|b00#8xxyM|6pAPjn; zYv|rB=s(a|GW6mr=r_>RZw$>|LVZ9d9x!xz74iq2f7#HnpP(H;C;w#Vg{zS-X!uP- zXV905_N_M5y$!ksx(EzK2L=p1f_Oy_p?-=Ue9O=Sz}9pfJ{7%f=%JrN4)pL3EN#Fi zX#a?%U*Z#V0P%{(|7~bunn=;1dksze4q?zZbV(EN#zCWhHgw;wh!h>X-q3wx2!qBp z8+zm-$_+ZQ+|a>)LJl-~($K;42!rl_-Oz(g)C+VJc`AAYvWkuXPtgeC6dn4Rq5IK3 ziYBKGjUgXJM-Lks`2*xZM-~hnUQeXyTlfTZesAcR*N7B7jdE&2|2++QW|g7FY9dAR zdksAYIYq-GhMossQRA|qXE83GT{Ag3ynpoI*u><}?(tn?!=n=i$0iqg%~Q439h+!! z^1z{yk-P*w$s$HzV(*~?`zD8WOzc3C#_ZhW!l_-Iq}EM_Tl3voYbv1}gXM;j`EIAZ zC39&TOqa z+G)=voo=Hbm#j=-Zo{*+6Um;e_`<1N!NP)t`Nqp9VheM)ub1?aJ+;|Jb5V!~N){F@ z%y)k>+wNQ;%bbkJjkN`Zn%YsXcc21jtQ=RQFuLN)XLu}aG}lBry|qD>u{!F6{4h&7 zwd9iRKHE)N^Nn`PYt6pIa(No;E96)#l*^CHI8s|oI`Q&lMRIu=*sPcsr(prk2YqP- zv|5?Yl?;~C(c``2vyCorFKYX&D!0DU-KjFPzFSSZ+tN*`C4#WK{$IF^Z z2Fs0GIW(C2%5k~{8ASv*-jof!jCHo%ZX$~;hb3(hrD%@DvM9Ne18A?w<15GI6b97{ zPFDyUWEl(Rg#0i|$(#;1k~5jyG>c`u9ISAj$I>QeJ-l3|Cd3jpEsJzHQfgdJ!~G9+Ty5#k@F| zy~pJgCbQATT+(c`l3lf_nRKlATuxyz{747lvpEgg){7Xbb!+IVAe+T*v9Q$}NIo|CFnMKOL#EQNDD*eA9z(uBDPPM2v5AZ0l$>9?~}tRS1yWb$%} z!hB9;vK+6?&NUOYv-ZO*W%EeIG7Oe8sS!EVY0P!o9ZY1d9K~^*+GZL~9*N}iSp;t? zOmo$2PLs>lCJOU8m7an#IofqD!{rpbc}%0xHcDp-A~>DeQ0CGEm@I#2PVM({DS~WH zW7=&`r#71$*PAt`2a?Cq$XnU)GRi5kWU{=;eJp8VRvN9%r{hGhSk~q(VqDgO$I_S( z40i{PA25(xy=JY`=q{r8g;AW=luB)9YpuGcD3Zt0wp=pG6-+W&Uh9X9u*xA>EXxXD z68*=q83gCm@L0DInii&3D8afCd=<`)w9w$7R$=|x`jQ!WcgjQb+z~8 zxl`#|h9e{~P}Gt**Y2pr6@rrC%Z*Pp=I7gb9@AnR_N7L!b{%QdyE87kl;cYdC3D@G zosF7STAgFc@g;XQq2RmP`UFgmYg5h)+fQTiYWG_8Z2pGlOON9;VXDzYpTOvVMK^!S z6+aLaOnU^QBbYLc2&NlLV8O9TU>epGCXEp3RL|xnAlttgekRp0=7_USe{2%T%*Y?c zfgC5WO{lHs+hd30F$Yg6J9ap5-)t+0F%__nfDZQyQEue%cb;C}h&y zC)z?b&(5ULvJ>rWL4CGJW7ae&?s0_Vo<_4N&T8QWUO z4lWTEQap?AtaUmKvx%H_Q#&(-yk2v(32Bu`ElegXq_EZq85a@~y3EcLHF;%tLRwF8 z6OCEyUa;9U(ixtRR?6zKMyA&GRXr4n5h+J;T9;V|e3p>aEg?2GW*Jn?A(%q`KytPV zgLBUAqGs!oA>`0nA_JYP&yuodlPQ=ncB!`=y*tBXdAko9?{%hYQ^~%)V`#@bkENBt z=H1@dbmP4_wV0daeF$ACzg@Mt+VKWvCS1 zrIKbPIcKwP9Y0f>o0_RLTBf=ICd+g0_z6N>PJs?_+3UF`t$u*dsdh~1Ls+GdI*}<@ zh|4K3yn2bPrjgEaSkhGQNTYS53Nd`^{9ES-S`taWiO6W7C-czNHEP0n}ZJGi;O zG(_~q9-_b9L-cAw^j3@Ld$B$~>n;-ge4gk>xGnFTC3^cgqV+ElU3UiFCHQ_6d0gH{^e@mK5&zO- zM9UwC=fhJd!v%OCOd-!%+*spAeJ$dy!R_(38KS?RMp=OUV_^RnSieC0UtS>k>on2# z=THXRn7=iNa^eUaDRP@=(~uYz-Je@Tkb_8qWrJCNc0<&`4Vs*fcz@Rzl^f{ z1ZDUW%5XJg-yB9gQUBGb^KEFeSI|ZS2M~S)cn_i64gL_b4*1BjbO`@N2|hY|k=@D~uj{xH$EK)*+uz4i?9d>Zuw zt-|-!4U`{!y&U~If;#R+|6c}g4chdM_rODmmeDuqA-az~NsrK4x{02p7w8lra3xKFVbatlrGUTbdjE-=jaKVri4z=lT@cEnxT`_ zpyRYiPtyh3Lfhzm+Cv9ugg!zW=w_Or-SkEJFS?p`&|bQe4%5AKJAH*-p>NYxx{Ds5 zgS4Mk(ii9!Iz(ThFVlPJ9@8tb&x}GL!6@838O4rgg^l5sS#%MKt zhHj(})5mEe-A13Kb#ymHYLUT0tM6&(YWDW%@e3MBkxZG)PD3Rl0#bMMJcn zzD3v3C+HYGNTalwZlz7MhQ{gh|KC!5x71be`gkW^Bs?$2)`Wty5SP?m$zu6R4;bg2 z7Ye7g7l@oHa>k*oMPnFb(;z~xV;R1(NrT(f>{gD!RRZKyP+}Vkn~lv_R~Z|{o9isU z(8dj$WXg&uFe|cVk0`m0id!+MWhv7+E?a<^NMplW&>U~0o7v>bBQNb#UCK^Ux2<-oYm_`=%ubK@Jc4A(g-Wcc#xHWMWcI6o?D z7;!9mP+inyl*!|IO=e?4>SUwvVb@(xVREr~jd3EL%2=+iGnVNq4Ku|ZRi>K0T3GqK zUT_4vs%CQG-ggRP<(cnmOeQj;GB!4^Gd3ciG&UxyHO$Vb4M&9ZhU3z+noM1tHLtAi zG*0!9nzOVM9ka23S-r@plXGV@UUVT3#WWA=(rZM~TAu4+PK*a{UwN|d6?64Zq|!C% zO3rkVo3+SwtcuEPA#pAtx165a7`FjrOe2}Js_CuQT~5Mzx#nV^c)fIbMwWV)6qoOeFn~w3CpCbki=M z-itUh^JcvUgn*kGb#v$`(YZm^tMpxXt8uLWbilD4S)5R{0=8F?jE`sJ;PiT*q zo3`~9KRj{EC~q~_5m-DzE4_~Mmut<^Q%E|OV*U4pLVnFrmlRbK>Gl~qG)R4Cyc()2 z3_b}+tAQfP2-`bB2M93H7jlk9j*6v~!KL(%0)kgJhKZE9as&*2C(L^db4R6sePiDU z`WLaedqXXhHSJSo-l#Wm&Tu#2`8!)DrW+%b(m`juJE`0#)G^Lr_d>&LWE-w`SC2S# zVQ%om-F!Zc&vC}M&eJ!;4J&igrJ2I?)?sOMYX)}_o7;w&zxfm6MT_XLYZFr&@KUo{ zOF>sN1~s#d$(;8`@qI|l*yA**;mjO1nO*pbo+YW7oJo@!$QH$&x0~wh9Mbqw4Y)>xAQ^G0VKX z8Ot$llgaimG%n9>MkX4d?4 zH^Qz9(aNbIYO88_ekWRH+AFrRa(vlaF4A_F4Re3lAa@uCg(2w*%pGH8WX~{*%|@4o z`v#q5WthXgm0`Q?vV7TJmgRMr<)uBw4AEuG^81XrsR8K9==L|};x+RENVrb&pUk&Yq$339hbk#XjVGl z?HZ%GylCivHEP6jtc6q3kU=QyZ0{Q{#jof2S^b83v#C5vuJj8e19xq+zeRFvMg786 z^z8?KdHBP)>0b_K2=%w24*&fV>)?}M{&wO64jkU!c3Qb}gL)HMTeq1bK87#90sYA` zuEOVb+W4lG+hWSWX4E)7m$e;qzMDzN^0v%1Yf#*RFgYnE$P#5Q)!oi>vlG zraJBU_H=jcEn~N?9T`3V&y4(^5>_Qq1WykAZ6*GFul^=sP>LydMWeXq7XOF-^BNPl^IMqihq;($Ns6j2;L6q-!k|=;MX7C(JlGX zY0KupO+s6iX>Iu#%4NzM))u(ocz;4$?&JuiEw6LHekyHI`7XT{^wYDS26Ew#SFDhl z($6T{ye&V<{ucZ*G2Di4+Sww2JVPvhDQ+Gl`vwMGlL-pGdZ znz*l4-5l1RwLpBYL2P7??kd%gr_f9dZv@^o4o_^&y&9F*)q%Uh^;0w4`!rtW)KONh z{K$y(-*OL4TBH(Ec4lAw=YCtwAOD|2{od~o(S@-=v844}AyIL5==`u`)x2KqtDX_P z`G7>^!vYVXyxt6M3G2-|wCe{YUgjjZN?#5X%&TjF`5}jy9#dDrime+TW~}@fxP)9% zt@((DDc=l9NU1{oXw8-at+^E~y3#`o9N$ae(shl^J0Eq(;&Px8T1;D4<zt!(nL0@tZZMH1uMtR(4CJ<%)GfTVasby!HoVX z;9keL>3vTntk^8@i7Zxn4^#sfZ2Q{;mhhjbgclou zpBH$}JEIcXmV*7nEf|5fOSFLRhXgLIqmiA(9eG^gSn_V6Zpfnwua!!u1#PTO+rA)B zQ^vCpd6XQv5o=Rwgk-28GL(BLIRYHtegm)T5?LNa-i4v^z zsEDlg134_?B2x)3(wc(;&$}3vfTgu1cHX_kN6dI=N!Zfu8d-(63e@yC(cJb{!Hk{K zYztxvZzTy_x{YHRdzXi7T%jab*_Ms1#9tIxOR*Biu)ZX)tPhv0R_Qj3%`uqh83fA6>v!)60&l6#Okz8l-2%_~TFS;O z--D6X+#}IaN6u<^ku!{YB%bFbDj`ejO9XMRMD*N-DPbdq@3t?GwiL5zq#s8lV&QhNwB|(malb^2ZQM%tCPaKtKfz4a#nibgl>K6Dui51wqmBosk(vEppMVq&>h_RL& zmxzH)R9URp4Z=hYD?jW@<3-k|Lmpmm6IEI(W9My$B_401s?MX49n_H!USQi+x=kbV z+R+eZXxmo4WeeuDwHSl*_>KN1fr%|$s zrTa0WH#Loxe^*rnZ)-vAlw<#Ki|761M)0v!l@e?zm}57f1XH0BrLEl=?-pZA_ z?xXWNvZZfUlNc-DBBV-{d_81g4l1nNqBDy)Yq=3VArhPKt1islK%~aD)o=8jL$HpJ9UG5 zt@(ik30b<=V;0}DjA>5ZvcGUwt$ibBo97uf^xF{CYFn@t-i}^i45j z0|hhQCxLxIV~d})kU*vTG^R(-8>Gk?y^!L`AN;6< z7xRC)l;ZLKC|?b$V6UX!?Y@{|g^wA_YfHhHQ17lUYc%c1?>%Strc*D_&q#>fO?@?o zSl!1iHXdF|@zO(=JY?xsjh(uDEyY}lJJW)hRK1ydIYr{%pQ)yq1-f!Qu)eOba9;H; p*Xb3FplSAN4_1%H@Ff|gzjA|w1&jp_gDkIbJ|{2%w;g*X5J diff --git a/ext/vulkan/vulkan.h b/ext/vulkan/vulkan.h index cd6a71ac1a..f57c4d9368 100644 --- a/ext/vulkan/vulkan.h +++ b/ext/vulkan/vulkan.h @@ -1,5 +1,5 @@ -#ifndef __vulkan_h_ -#define __vulkan_h_ 1 +#ifndef VULKAN_H_ +#define VULKAN_H_ 1 #ifdef __cplusplus extern "C" { @@ -41,7 +41,7 @@ extern "C" { (((major) << 22) | ((minor) << 12) | (patch)) // Vulkan API version supported by this file -#define VK_API_VERSION VK_MAKE_VERSION(1, 0, 3) +#define VK_API_VERSION VK_MAKE_VERSION(1, 0, 5) #define VK_VERSION_MAJOR(version) ((uint32_t)(version) >> 22) #define VK_VERSION_MINOR(version) (((uint32_t)(version) >> 12) & 0x3ff) @@ -142,6 +142,7 @@ typedef enum VkResult { VK_ERROR_OUT_OF_DATE_KHR = -1000001004, VK_ERROR_INCOMPATIBLE_DISPLAY_KHR = -1000003001, VK_ERROR_VALIDATION_FAILED_EXT = -1000011001, + VK_ERROR_INVALID_SHADER_NV = -1000012000, VK_RESULT_BEGIN_RANGE = VK_ERROR_FORMAT_NOT_SUPPORTED, VK_RESULT_END_RANGE = VK_INCOMPLETE, VK_RESULT_RANGE_SIZE = (VK_INCOMPLETE - VK_ERROR_FORMAT_NOT_SUPPORTED + 1), @@ -209,7 +210,7 @@ typedef enum VkStructureType { VK_STRUCTURE_TYPE_MIR_SURFACE_CREATE_INFO_KHR = 1000007000, VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR = 1000008000, VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR = 1000009000, - VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT = 1000011000, + VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT = 1000011000, VK_STRUCTURE_TYPE_BEGIN_RANGE = VK_STRUCTURE_TYPE_APPLICATION_INFO, VK_STRUCTURE_TYPE_END_RANGE = VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO, VK_STRUCTURE_TYPE_RANGE_SIZE = (VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO - VK_STRUCTURE_TYPE_APPLICATION_INFO + 1), @@ -701,8 +702,8 @@ typedef enum VkSamplerAddressMode { VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER = 3, VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE = 4, VK_SAMPLER_ADDRESS_MODE_BEGIN_RANGE = VK_SAMPLER_ADDRESS_MODE_REPEAT, - VK_SAMPLER_ADDRESS_MODE_END_RANGE = VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE, - VK_SAMPLER_ADDRESS_MODE_RANGE_SIZE = (VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE - VK_SAMPLER_ADDRESS_MODE_REPEAT + 1), + VK_SAMPLER_ADDRESS_MODE_END_RANGE = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER, + VK_SAMPLER_ADDRESS_MODE_RANGE_SIZE = (VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER - VK_SAMPLER_ADDRESS_MODE_REPEAT + 1), VK_SAMPLER_ADDRESS_MODE_MAX_ENUM = 0x7FFFFFFF } VkSamplerAddressMode; @@ -979,7 +980,7 @@ typedef enum VkShaderStageFlagBits { VK_SHADER_STAGE_GEOMETRY_BIT = 0x00000008, VK_SHADER_STAGE_FRAGMENT_BIT = 0x00000010, VK_SHADER_STAGE_COMPUTE_BIT = 0x00000020, - VK_SHADER_STAGE_ALL_GRAPHICS = 0x1F, + VK_SHADER_STAGE_ALL_GRAPHICS = 0x0000001F, VK_SHADER_STAGE_ALL = 0x7FFFFFFF, } VkShaderStageFlagBits; typedef VkFlags VkPipelineVertexInputStateCreateFlags; @@ -992,7 +993,7 @@ typedef enum VkCullModeFlagBits { VK_CULL_MODE_NONE = 0, VK_CULL_MODE_FRONT_BIT = 0x00000001, VK_CULL_MODE_BACK_BIT = 0x00000002, - VK_CULL_MODE_FRONT_AND_BACK = 0x3, + VK_CULL_MODE_FRONT_AND_BACK = 0x00000003, } VkCullModeFlagBits; typedef VkFlags VkCullModeFlags; typedef VkFlags VkPipelineMultisampleStateCreateFlags; @@ -1083,7 +1084,7 @@ typedef VkFlags VkCommandBufferResetFlags; typedef enum VkStencilFaceFlagBits { VK_STENCIL_FACE_FRONT_BIT = 0x00000001, VK_STENCIL_FACE_BACK_BIT = 0x00000002, - VK_STENCIL_FRONT_AND_BACK = 0x3, + VK_STENCIL_FRONT_AND_BACK = 0x00000003, } VkStencilFaceFlagBits; typedef VkFlags VkStencilFaceFlags; @@ -3326,8 +3327,8 @@ typedef enum VkDisplayPlaneAlphaFlagBitsKHR { VK_DISPLAY_PLANE_ALPHA_PER_PIXEL_BIT_KHR = 0x00000004, VK_DISPLAY_PLANE_ALPHA_PER_PIXEL_PREMULTIPLIED_BIT_KHR = 0x00000008, } VkDisplayPlaneAlphaFlagBitsKHR; -typedef VkFlags VkDisplayModeCreateFlagsKHR; typedef VkFlags VkDisplayPlaneAlphaFlagsKHR; +typedef VkFlags VkDisplayModeCreateFlagsKHR; typedef VkFlags VkDisplaySurfaceCreateFlagsKHR; typedef struct VkDisplayPropertiesKHR { @@ -3667,11 +3668,17 @@ VKAPI_ATTR VkBool32 VKAPI_CALL vkGetPhysicalDeviceWin32PresentationSupportKHR( #endif #endif /* VK_USE_PLATFORM_WIN32_KHR */ +#define VK_KHR_sampler_mirror_clamp_to_edge 1 +#define VK_KHR_SAMPLER_MIRROR_CLAMP_TO_EDGE_SPEC_VERSION 1 +#define VK_KHR_SAMPLER_MIRROR_CLAMP_TO_EDGE_EXTENSION_NAME "VK_KHR_sampler_mirror_clamp_to_edge" + + #define VK_EXT_debug_report 1 VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkDebugReportCallbackEXT) -#define VK_EXT_DEBUG_REPORT_SPEC_VERSION 1 +#define VK_EXT_DEBUG_REPORT_SPEC_VERSION 2 #define VK_EXT_DEBUG_REPORT_EXTENSION_NAME "VK_EXT_debug_report" +#define VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT typedef enum VkDebugReportObjectTypeEXT { @@ -3768,6 +3775,11 @@ VKAPI_ATTR void VKAPI_CALL vkDebugReportMessageEXT( const char* pMessage); #endif +#define VK_NV_glsl_shader 1 +#define VK_NV_GLSL_SHADER_SPEC_VERSION 1 +#define VK_NV_GLSL_SHADER_EXTENSION_NAME "VK_NV_glsl_shader" + + #ifdef __cplusplus } #endif diff --git a/headless/Headless.vcxproj b/headless/Headless.vcxproj index 5711fc1184..cdf062c374 100644 --- a/headless/Headless.vcxproj +++ b/headless/Headless.vcxproj @@ -105,7 +105,7 @@ Console true - ..\ext\vulkan\vulkan-1.lib;Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86\lib\avcodec.lib;..\ffmpeg\Windows\x86\lib\avformat.lib;..\ffmpeg\Windows\x86\lib\avutil.lib;..\ffmpeg\Windows\x86\lib\swresample.lib;..\ffmpeg\Windows\x86\lib\swscale.lib;comctl32.lib;xinput.lib;d3d9.lib;d3dx9d.lib;dxguid.lib;%(AdditionalDependencies) + Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86\lib\avcodec.lib;..\ffmpeg\Windows\x86\lib\avformat.lib;..\ffmpeg\Windows\x86\lib\avutil.lib;..\ffmpeg\Windows\x86\lib\swresample.lib;..\ffmpeg\Windows\x86\lib\swscale.lib;comctl32.lib;xinput.lib;d3d9.lib;d3dx9d.lib;dxguid.lib;%(AdditionalDependencies) 0x00400000 false true @@ -137,7 +137,7 @@ Console true - ..\ext\vulkan\vulkan-1.lib;Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86_64\lib\avcodec.lib;..\ffmpeg\Windows\x86_64\lib\avformat.lib;..\ffmpeg\Windows\x86_64\lib\avutil.lib;..\ffmpeg\Windows\x86_64\lib\swresample.lib;..\ffmpeg\Windows\x86_64\lib\swscale.lib;comctl32.lib;d3d9.lib;d3dx9d.lib;dxguid.lib;%(AdditionalDependencies) + Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86_64\lib\avcodec.lib;..\ffmpeg\Windows\x86_64\lib\avformat.lib;..\ffmpeg\Windows\x86_64\lib\avutil.lib;..\ffmpeg\Windows\x86_64\lib\swresample.lib;..\ffmpeg\Windows\x86_64\lib\swscale.lib;comctl32.lib;d3d9.lib;d3dx9d.lib;dxguid.lib;%(AdditionalDependencies) 0x00400000 false true @@ -172,7 +172,7 @@ true true true - ..\ext\vulkan\vulkan-1.lib;Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86\lib\avcodec.lib;..\ffmpeg\Windows\x86\lib\avformat.lib;..\ffmpeg\Windows\x86\lib\avutil.lib;..\ffmpeg\Windows\x86\lib\swresample.lib;..\ffmpeg\Windows\x86\lib\swscale.lib;comctl32.lib;d3d9.lib;d3dx9.lib;dxguid.lib;%(AdditionalDependencies) + Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86\lib\avcodec.lib;..\ffmpeg\Windows\x86\lib\avformat.lib;..\ffmpeg\Windows\x86\lib\avutil.lib;..\ffmpeg\Windows\x86\lib\swresample.lib;..\ffmpeg\Windows\x86\lib\swscale.lib;comctl32.lib;d3d9.lib;d3dx9.lib;dxguid.lib;%(AdditionalDependencies) 0x00400000 false true @@ -209,7 +209,7 @@ true true true - ..\ext\vulkan\vulkan-1.lib;Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86_64\lib\avcodec.lib;..\ffmpeg\Windows\x86_64\lib\avformat.lib;..\ffmpeg\Windows\x86_64\lib\avutil.lib;..\ffmpeg\Windows\x86_64\lib\swresample.lib;..\ffmpeg\Windows\x86_64\lib\swscale.lib;comctl32.lib;d3d9.lib;d3dx9.lib;dxguid.lib;%(AdditionalDependencies) + Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;..\ffmpeg\Windows\x86_64\lib\avcodec.lib;..\ffmpeg\Windows\x86_64\lib\avformat.lib;..\ffmpeg\Windows\x86_64\lib\avutil.lib;..\ffmpeg\Windows\x86_64\lib\swresample.lib;..\ffmpeg\Windows\x86_64\lib\swscale.lib;comctl32.lib;d3d9.lib;d3dx9.lib;dxguid.lib;%(AdditionalDependencies) 0x00400000 false true diff --git a/unittest/UnitTests.vcxproj b/unittest/UnitTests.vcxproj index 43cbbea96b..0ea78b3d12 100644 --- a/unittest/UnitTests.vcxproj +++ b/unittest/UnitTests.vcxproj @@ -99,7 +99,7 @@ Console true - ..\ext\vulkan\vulkan-1.lib;Ws2_32.lib;winmm.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;opengl32.lib;dsound.lib;glu32.lib;avcodec.lib;avformat.lib;avutil.lib;swresample.lib;swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) + Ws2_32.lib;winmm.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;opengl32.lib;dsound.lib;glu32.lib;avcodec.lib;avformat.lib;avutil.lib;swresample.lib;swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) /ignore:4049 /ignore:4217 %(AdditionalOptions) ..\ffmpeg\Windows\x86\lib @@ -122,7 +122,7 @@ Console true - ..\Windows\x64\Debug\glslang.lib;..\ext\vulkan\vulkan-1.lib;Ws2_32.lib;winmm.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;opengl32.lib;dsound.lib;glu32.lib;avcodec.lib;avformat.lib;avutil.lib;swresample.lib;swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) + Ws2_32.lib;winmm.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;opengl32.lib;dsound.lib;glu32.lib;avcodec.lib;avformat.lib;avutil.lib;swresample.lib;swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) /ignore:4049 /ignore:4217 %(AdditionalOptions) ..\ffmpeg\Windows\x86_64\lib @@ -148,7 +148,7 @@ true true true - ..\ext\vulkan\vulkan-1.lib;Ws2_32.lib;winmm.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;opengl32.lib;dsound.lib;glu32.lib;avcodec.lib;avformat.lib;avutil.lib;swresample.lib;swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) + Ws2_32.lib;winmm.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;opengl32.lib;dsound.lib;glu32.lib;avcodec.lib;avformat.lib;avutil.lib;swresample.lib;swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) /ignore:4049 /ignore:4217 %(AdditionalOptions) ..\ffmpeg\Windows\x86\lib @@ -174,7 +174,7 @@ true true true - ..\ext\vulkan\vulkan-1.lib;Ws2_32.lib;winmm.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;opengl32.lib;dsound.lib;glu32.lib;avcodec.lib;avformat.lib;avutil.lib;swresample.lib;swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) + Ws2_32.lib;winmm.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;opengl32.lib;dsound.lib;glu32.lib;avcodec.lib;avformat.lib;avutil.lib;swresample.lib;swscale.lib;comctl32.lib;d3d9.lib;dxguid.lib;%(AdditionalDependencies) /ignore:4049 /ignore:4217 %(AdditionalOptions) ..\ffmpeg\Windows\x86_64\lib From 5ca012e83de57356712d9b405cac63fbd30e1a80 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 13 Mar 2016 16:22:46 +0100 Subject: [PATCH 073/116] Fix a bunch of new vulkan validation layer failures. --- Common/Vulkan/VulkanContext.cpp | 74 ++++++++++++++++++---------- Common/Vulkan/VulkanContext.h | 6 +-- Windows/GPU/WindowsVulkanContext.cpp | 2 +- 3 files changed, 51 insertions(+), 31 deletions(-) diff --git a/Common/Vulkan/VulkanContext.cpp b/Common/Vulkan/VulkanContext.cpp index d6f17920fe..21ed7c4a22 100644 --- a/Common/Vulkan/VulkanContext.cpp +++ b/Common/Vulkan/VulkanContext.cpp @@ -5,6 +5,7 @@ #include #include +#include "base/basictypes.h" #include "VulkanContext.h" #ifdef USE_CRT_DBG @@ -28,6 +29,18 @@ using namespace std; +static const char *validationLayers[] = { + "VK_LAYER_LUNARG_standard_validation", + /* + "VK_LAYER_GOOGLE_threading", + "VK_LAYER_LUNARG_draw_state", + "VK_LAYER_LUNARG_image", + "VK_LAYER_LUNARG_mem_tracker", + "VK_LAYER_LUNARG_object_tracker", + "VK_LAYER_LUNARG_param_checker", + */ +}; + VulkanContext::VulkanContext(const char *app_name, int app_ver, uint32_t flags) : device_(nullptr), gfx_queue_(VK_NULL_HANDLE), @@ -67,20 +80,10 @@ VulkanContext::VulkanContext(const char *app_name, int app_ver, uint32_t flags) device_extension_names.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME); if (flags & VULKAN_FLAG_VALIDATE) { - instance_layer_names.push_back("VK_LAYER_LUNARG_threading"); - instance_layer_names.push_back("VK_LAYER_LUNARG_draw_state"); - instance_layer_names.push_back("VK_LAYER_LUNARG_image"); - instance_layer_names.push_back("VK_LAYER_LUNARG_mem_tracker"); - instance_layer_names.push_back("VK_LAYER_LUNARG_object_tracker"); - instance_layer_names.push_back("VK_LAYER_LUNARG_param_checker"); - - device_layer_names.push_back("VK_LAYER_LUNARG_threading"); - device_layer_names.push_back("VK_LAYER_LUNARG_draw_state"); - device_layer_names.push_back("VK_LAYER_LUNARG_image"); - device_layer_names.push_back("VK_LAYER_LUNARG_mem_tracker"); - device_layer_names.push_back("VK_LAYER_LUNARG_object_tracker"); - device_layer_names.push_back("VK_LAYER_LUNARG_param_checker"); - + for (int i = 0; i < ARRAY_SIZE(validationLayers); i++) { + instance_layer_names.push_back(validationLayers[i]); + device_layer_names.push_back(validationLayers[i]); + } instance_extension_names.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME); } @@ -92,7 +95,9 @@ VulkanContext::VulkanContext(const char *app_name, int app_ver, uint32_t flags) app_info.pEngineName = app_name; // Let's increment this when we make major engine/context changes. app_info.engineVersion = 1; + // Don't specify the API patch version. app_info.apiVersion = VK_MAKE_VERSION(1, 0, 0); + VkInstanceCreateInfo inst_info = {}; inst_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; inst_info.pNext = NULL; @@ -101,11 +106,19 @@ VulkanContext::VulkanContext(const char *app_name, int app_ver, uint32_t flags) inst_info.enabledLayerCount = (uint32_t)instance_layer_names.size(); inst_info.ppEnabledLayerNames = instance_layer_names.size() ? instance_layer_names.data() : NULL; inst_info.enabledExtensionCount = (uint32_t)instance_extension_names.size(); - inst_info.ppEnabledExtensionNames = instance_extension_names.data(); + inst_info.ppEnabledExtensionNames = instance_extension_names.size() ? instance_extension_names.data() : NULL; VkResult res = vkCreateInstance(&inst_info, NULL, &instance_); if (res != VK_SUCCESS) { ELOG("Failed to create instance: %d", res); + if (res == VK_ERROR_LAYER_NOT_PRESENT) { + // Drop the validation layers and try again. + instance_layer_names.clear(); + device_layer_names.clear(); + inst_info.enabledLayerCount = 0; + inst_info.ppEnabledLayerNames = NULL; + res = vkCreateInstance(&inst_info, NULL, &instance_); + } } assert(res == VK_SUCCESS); @@ -267,6 +280,8 @@ void VulkanContext::EndSurfaceRenderPass() { submit_info[0].sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submit_info[0].waitSemaphoreCount = 1; submit_info[0].pWaitSemaphores = &acquireSemaphore; + VkPipelineStageFlags waitStage[1] = { VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT }; + submit_info[0].pWaitDstStageMask = waitStage; submit_info[0].commandBufferCount = (uint32_t)cmdBufs.size(); submit_info[0].pCommandBuffers = cmdBufs.data(); submit_info[0].signalSemaphoreCount = 0; @@ -758,7 +773,7 @@ void VulkanContext::InitDepthStencilBuffer(VkCommandBuffer cmd) { /* Set the image layout to depth stencil optimal */ TransitionImageLayout(cmd, depth.image, - VK_IMAGE_ASPECT_DEPTH_BIT, + aspectMask, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); @@ -1000,6 +1015,7 @@ void VulkanContext::InitSwapchain(VkCommandBuffer cmd) { swap_chain_info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; swap_chain_info.queueFamilyIndexCount = 0; swap_chain_info.pQueueFamilyIndices = NULL; + swap_chain_info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; res = vkCreateSwapchainKHR(device_, &swap_chain_info, NULL, &swap_chain_); assert(res == VK_SUCCESS); @@ -1198,6 +1214,7 @@ void VulkanTexture::CreateMappableImage() { image_create_info.pQueueFamilyIndices = NULL; image_create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; image_create_info.flags = 0; + image_create_info.initialLayout = VK_IMAGE_LAYOUT_PREINITIALIZED; VkMemoryAllocateInfo mem_alloc = {}; mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; @@ -1219,7 +1236,7 @@ void VulkanTexture::CreateMappableImage() { pass = vulkan_->MemoryTypeFromProperties(mem_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, &mem_alloc.memoryTypeIndex); assert(pass); - res = vkAllocateMemory(vulkan_->GetDevice(), &mem_alloc, NULL, &(mappableMemory)); + res = vkAllocateMemory(vulkan_->GetDevice(), &mem_alloc, NULL, &mappableMemory); assert(res == VK_SUCCESS); res = vkBindImageMemory(vulkan_->GetDevice(), mappableImage, mappableMemory, 0); @@ -1265,11 +1282,13 @@ void VulkanTexture::Unlock() { mem = VK_NULL_HANDLE; } if (!needStaging) { - /* If we can use the linear tiled image as a texture, just do it */ + // If we can use the linear tiled image as a texture, just do it image = mappableImage; mem = mappableMemory; - imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - TransitionImageLayout(cmd, image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED, imageLayout); + TransitionImageLayout(cmd, image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_PREINITIALIZED, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); + // Make sure we don't accidentally delete the main image. + mappableImage = VK_NULL_HANDLE; + mappableMemory = VK_NULL_HANDLE; } else { VkImageCreateInfo image_create_info = {}; image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; @@ -1315,10 +1334,9 @@ void VulkanTexture::Unlock() { // Since we're going to blit from the mappable image, set its layout to SOURCE_OPTIMAL TransitionImageLayout(cmd, mappableImage, VK_IMAGE_ASPECT_COLOR_BIT, - VK_IMAGE_LAYOUT_UNDEFINED, + VK_IMAGE_LAYOUT_PREINITIALIZED, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); - // Since we're going to blit to the texture image, set its layout to DESTINATION_OPTIMAL TransitionImageLayout(cmd, image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED, @@ -1352,14 +1370,15 @@ void VulkanTexture::Unlock() { assert(res == VK_SUCCESS); // Set the layout for the texture image from DESTINATION_OPTIMAL to SHADER_READ_ONLY - imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; TransitionImageLayout(cmd, image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - imageLayout); + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); - vulkan_->Delete().QueueDeleteDeviceMemory(mappableMemory); + // Then drop the temporary mappable image - although should not be necessary... vulkan_->Delete().QueueDeleteImage(mappableImage); + vulkan_->Delete().QueueDeleteDeviceMemory(mappableMemory); + mappableImage = VK_NULL_HANDLE; mappableMemory = VK_NULL_HANDLE; } @@ -1379,8 +1398,6 @@ void VulkanTexture::Unlock() { view_info.subresourceRange.levelCount = 1; view_info.subresourceRange.baseArrayLayer = 0; view_info.subresourceRange.layerCount = 1; - - /* create image view */ view_info.image = image; VkResult res = vkCreateImageView(vulkan_->GetDevice(), &view_info, NULL, &view); assert(res == VK_SUCCESS); @@ -1514,6 +1531,9 @@ void TransitionImageLayout(VkCommandBuffer cmd, VkImage image, VkImageAspectFlag } if (new_image_layout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL) { + if (old_image_layout == VK_IMAGE_LAYOUT_PREINITIALIZED) { + image_memory_barrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; + } image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; } diff --git a/Common/Vulkan/VulkanContext.h b/Common/Vulkan/VulkanContext.h index 1c2b6f31d3..14779e3168 100644 --- a/Common/Vulkan/VulkanContext.h +++ b/Common/Vulkan/VulkanContext.h @@ -343,8 +343,9 @@ private: class VulkanTexture { public: VulkanTexture(VulkanContext *vulkan) - : vulkan_(vulkan), image(0), imageLayout(VK_IMAGE_LAYOUT_UNDEFINED), mem(0), view(0), tex_width(0), tex_height(0), format_(VK_FORMAT_UNDEFINED), - mappableImage(0), mappableMemory(0), needStaging(false) { + : vulkan_(vulkan), image(VK_NULL_HANDLE), mem(VK_NULL_HANDLE), view(VK_NULL_HANDLE), + tex_width(0), tex_height(0), format_(VK_FORMAT_UNDEFINED), + mappableImage(VK_NULL_HANDLE), mappableMemory(VK_NULL_HANDLE), needStaging(false) { memset(&mem_reqs, 0, sizeof(mem_reqs)); } ~VulkanTexture() { @@ -368,7 +369,6 @@ private: VulkanContext *vulkan_; VkImage image; - VkImageLayout imageLayout; VkDeviceMemory mem; VkImageView view; int32_t tex_width, tex_height; diff --git a/Windows/GPU/WindowsVulkanContext.cpp b/Windows/GPU/WindowsVulkanContext.cpp index 3a7f3a63a7..999b0031c4 100644 --- a/Windows/GPU/WindowsVulkanContext.cpp +++ b/Windows/GPU/WindowsVulkanContext.cpp @@ -98,7 +98,7 @@ const char *ObjTypeToString(VkDebugReportObjectTypeEXT type) { case VK_DEBUG_REPORT_OBJECT_TYPE_SURFACE_KHR_EXT: return "SurfaceKHR"; case VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT: return "SwapChainKHR"; case VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_POOL_EXT: return "CommandPool"; - default: return "Unknown"; + default: return ""; } } From 79fd828d16e1590175fbad0a8cf4edcd2459f65a Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 13 Mar 2016 16:32:07 +0100 Subject: [PATCH 074/116] Work around what seems like a validation layer bug (trigger by scrolling around the UI a bit) --- Windows/GPU/WindowsVulkanContext.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Windows/GPU/WindowsVulkanContext.cpp b/Windows/GPU/WindowsVulkanContext.cpp index 999b0031c4..57b43f96d8 100644 --- a/Windows/GPU/WindowsVulkanContext.cpp +++ b/Windows/GPU/WindowsVulkanContext.cpp @@ -119,6 +119,10 @@ static VkBool32 VKAPI_CALL Vulkan_Dbg(VkDebugReportFlagsEXT msgFlags, VkDebugRep } message << "[" << pLayerPrefix << "] " << ObjTypeToString(objType) << " Code " << msgCode << " : " << pMsg << "\n"; + // Getting some bizarre false positive for mapping image memory. + if (msgCode == 6) + return false; + #ifdef _WIN32 OutputDebugStringA(message.str().c_str()); if (msgFlags & VK_DEBUG_REPORT_ERROR_BIT_EXT) { From 575cc890b7cef575edc864264dc4e120a2b82a67 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 13 Mar 2016 17:05:03 +0100 Subject: [PATCH 075/116] Turn off annoying "debug flicker" I used to see if we were swapping buffers properly early on Also minor logging changes, refine the false-positive debug layer check --- Common/Vulkan/VulkanContext.cpp | 6 +++++- Windows/GPU/WindowsVulkanContext.cpp | 5 +++-- ext/native/thin3d/thin3d_vulkan.cpp | 6 ++++-- 3 files changed, 12 insertions(+), 5 deletions(-) diff --git a/Common/Vulkan/VulkanContext.cpp b/Common/Vulkan/VulkanContext.cpp index 21ed7c4a22..7f9f10d537 100644 --- a/Common/Vulkan/VulkanContext.cpp +++ b/Common/Vulkan/VulkanContext.cpp @@ -110,14 +110,18 @@ VulkanContext::VulkanContext(const char *app_name, int app_ver, uint32_t flags) VkResult res = vkCreateInstance(&inst_info, NULL, &instance_); if (res != VK_SUCCESS) { - ELOG("Failed to create instance: %d", res); if (res == VK_ERROR_LAYER_NOT_PRESENT) { + WLOG("Validation on but layers not available - dropping layers"); // Drop the validation layers and try again. instance_layer_names.clear(); device_layer_names.clear(); inst_info.enabledLayerCount = 0; inst_info.ppEnabledLayerNames = NULL; res = vkCreateInstance(&inst_info, NULL, &instance_); + if (res != VK_SUCCESS) + ELOG("Failed to create instance even without validation: %d", res); + } else { + ELOG("Failed to create instance : %d", res); } } assert(res == VK_SUCCESS); diff --git a/Windows/GPU/WindowsVulkanContext.cpp b/Windows/GPU/WindowsVulkanContext.cpp index 57b43f96d8..5d9e0b79c4 100644 --- a/Windows/GPU/WindowsVulkanContext.cpp +++ b/Windows/GPU/WindowsVulkanContext.cpp @@ -119,8 +119,9 @@ static VkBool32 VKAPI_CALL Vulkan_Dbg(VkDebugReportFlagsEXT msgFlags, VkDebugRep } message << "[" << pLayerPrefix << "] " << ObjTypeToString(objType) << " Code " << msgCode << " : " << pMsg << "\n"; - // Getting some bizarre false positive for mapping image memory. - if (msgCode == 6) + // Getting some bizarre false positives for mapping image memory. + // https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers/issues/121 + if (msgCode == 6 && !memcmp(pMsg, "Cannot map", 10)) return false; #ifdef _WIN32 diff --git a/ext/native/thin3d/thin3d_vulkan.cpp b/ext/native/thin3d/thin3d_vulkan.cpp index 63c967c2d5..f547e58cb0 100644 --- a/ext/native/thin3d/thin3d_vulkan.cpp +++ b/ext/native/thin3d/thin3d_vulkan.cpp @@ -680,8 +680,10 @@ void Thin3DVKContext::Begin(bool clear, uint32_t colorval, float depthVal, int s VkClearValue clearVal[2] = {}; Uint8x4ToFloat4(colorval, clearVal[0].color.float32); - if (frameNum_ & 1) - clearVal[0].color.float32[2] = 1.0f; + // // Debug flicker - used to see if we swap at all. no longer necessary + // if (frameNum_ & 1) + // clearVal[0].color.float32[2] = 1.0f; + clearVal[1].depthStencil.depth = depthVal; clearVal[1].depthStencil.stencil = stencilVal; From b0098f79616bb5a624418c414064acb5f0881dfe Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 13 Mar 2016 17:20:04 +0100 Subject: [PATCH 076/116] Replace ugly workaround with VK_LAYER_LUNARG_unique_objects which prevents handle reuse. See https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers/issues/121 --- Common/Vulkan/VulkanContext.cpp | 1 + Windows/GPU/WindowsVulkanContext.cpp | 5 ----- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/Common/Vulkan/VulkanContext.cpp b/Common/Vulkan/VulkanContext.cpp index 7f9f10d537..3f7314dd20 100644 --- a/Common/Vulkan/VulkanContext.cpp +++ b/Common/Vulkan/VulkanContext.cpp @@ -30,6 +30,7 @@ using namespace std; static const char *validationLayers[] = { + "VK_LAYER_LUNARG_unique_objects", "VK_LAYER_LUNARG_standard_validation", /* "VK_LAYER_GOOGLE_threading", diff --git a/Windows/GPU/WindowsVulkanContext.cpp b/Windows/GPU/WindowsVulkanContext.cpp index 5d9e0b79c4..999b0031c4 100644 --- a/Windows/GPU/WindowsVulkanContext.cpp +++ b/Windows/GPU/WindowsVulkanContext.cpp @@ -119,11 +119,6 @@ static VkBool32 VKAPI_CALL Vulkan_Dbg(VkDebugReportFlagsEXT msgFlags, VkDebugRep } message << "[" << pLayerPrefix << "] " << ObjTypeToString(objType) << " Code " << msgCode << " : " << pMsg << "\n"; - // Getting some bizarre false positives for mapping image memory. - // https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers/issues/121 - if (msgCode == 6 && !memcmp(pMsg, "Cannot map", 10)) - return false; - #ifdef _WIN32 OutputDebugStringA(message.str().c_str()); if (msgFlags & VK_DEBUG_REPORT_ERROR_BIT_EXT) { From fe270c592ad6648eb31b122002ae913447744bd8 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 13 Mar 2016 17:43:50 +0100 Subject: [PATCH 077/116] Typo fix --- Common/Vulkan/VulkanContext.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Common/Vulkan/VulkanContext.cpp b/Common/Vulkan/VulkanContext.cpp index 3f7314dd20..d95167843f 100644 --- a/Common/Vulkan/VulkanContext.cpp +++ b/Common/Vulkan/VulkanContext.cpp @@ -30,7 +30,7 @@ using namespace std; static const char *validationLayers[] = { - "VK_LAYER_LUNARG_unique_objects", + "VK_LAYER_GOOGLE_unique_objects", "VK_LAYER_LUNARG_standard_validation", /* "VK_LAYER_GOOGLE_threading", From 76b17a4912c131c475fefe7490949a5b73c34704 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 13 Mar 2016 17:44:38 +0100 Subject: [PATCH 078/116] Revert "Replace ugly workaround with VK_LAYER_LUNARG_unique_objects which prevents handle reuse." This reverts commit 6342c07a19d5ab410cbc233a570488214923a9f8. --- Windows/GPU/WindowsVulkanContext.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Windows/GPU/WindowsVulkanContext.cpp b/Windows/GPU/WindowsVulkanContext.cpp index 999b0031c4..5d9e0b79c4 100644 --- a/Windows/GPU/WindowsVulkanContext.cpp +++ b/Windows/GPU/WindowsVulkanContext.cpp @@ -119,6 +119,11 @@ static VkBool32 VKAPI_CALL Vulkan_Dbg(VkDebugReportFlagsEXT msgFlags, VkDebugRep } message << "[" << pLayerPrefix << "] " << ObjTypeToString(objType) << " Code " << msgCode << " : " << pMsg << "\n"; + // Getting some bizarre false positives for mapping image memory. + // https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers/issues/121 + if (msgCode == 6 && !memcmp(pMsg, "Cannot map", 10)) + return false; + #ifdef _WIN32 OutputDebugStringA(message.str().c_str()); if (msgFlags & VK_DEBUG_REPORT_ERROR_BIT_EXT) { From 82205a46609ab0ff66c3c90ba79ff3e94a7867d2 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sun, 13 Mar 2016 09:33:39 -0700 Subject: [PATCH 079/116] Handle Vulkan init errors more gracefully. --- Common/Vulkan/VulkanContext.cpp | 94 ++++++++++++++++------------ Common/Vulkan/VulkanContext.h | 3 + Windows/EmuThread.cpp | 5 ++ Windows/GPU/WindowsVulkanContext.cpp | 5 +- android/jni/app-android.cpp | 4 +- 5 files changed, 70 insertions(+), 41 deletions(-) diff --git a/Common/Vulkan/VulkanContext.cpp b/Common/Vulkan/VulkanContext.cpp index d95167843f..52a5a3b769 100644 --- a/Common/Vulkan/VulkanContext.cpp +++ b/Common/Vulkan/VulkanContext.cpp @@ -67,7 +67,7 @@ VulkanContext::VulkanContext(const char *app_name, int app_ver, uint32_t flags) curFrame_(0) { if (!VulkanLoad()) { - ELOG("Failed to load vulkan"); + init_error_ = "Failed to load Vulkan driver library"; // No DLL? return; } @@ -125,7 +125,10 @@ VulkanContext::VulkanContext(const char *app_name, int app_ver, uint32_t flags) ELOG("Failed to create instance : %d", res); } } - assert(res == VK_SUCCESS); + if (res != VK_SUCCESS) { + init_error_ = "Failed to create Vulkan instance"; + return; + } VulkanLoadInstanceFunctions(instance_); @@ -134,20 +137,25 @@ VulkanContext::VulkanContext(const char *app_name, int app_ver, uint32_t flags) assert(gpu_count); physical_devices_.resize(gpu_count); res = vkEnumeratePhysicalDevices(instance_, &gpu_count, physical_devices_.data()); - assert(!res); + if (res != VK_SUCCESS) { + init_error_ = "Failed to enumerate physical devices"; + return; + } InitGlobalLayerProperties(); InitGlobalExtensionProperties(); if (!CheckLayers(instance_layer_properties, instance_layer_names)) { ELOG("CheckLayers failed"); - exit(1); + init_error_ = "Failed to validate instance layers"; + return; } InitDeviceLayerProperties(); if (!CheckLayers(device_layer_properties, device_layer_names)) { ELOG("CheckLayers failed (2)"); - exit(1); + init_error_ = "Failed to validate device layers"; + return; } } @@ -592,36 +600,41 @@ VkBool32 CheckLayers(const std::vector &layer_props, const std } VkResult VulkanContext::CreateDevice(int physical_device) { - VkResult res; - VkDeviceQueueCreateInfo queue_info = {}; + VkResult res; + VkDeviceQueueCreateInfo queue_info = {}; - vkGetPhysicalDeviceQueueFamilyProperties(physical_devices_[0], &queue_count, NULL); - assert(queue_count >= 1); + if (!init_error_.empty()) { + ELOG("Vulkan init failed: %s", init_error_.c_str()); + return VK_ERROR_INITIALIZATION_FAILED; + } - queue_props.resize(queue_count); - vkGetPhysicalDeviceQueueFamilyProperties(physical_devices_[0], &queue_count, queue_props.data()); - assert(queue_count >= 1); + vkGetPhysicalDeviceQueueFamilyProperties(physical_devices_[0], &queue_count, nullptr); + assert(queue_count >= 1); - bool found = false; - for (int i = 0; i < (int)queue_count; i++) { + queue_props.resize(queue_count); + vkGetPhysicalDeviceQueueFamilyProperties(physical_devices_[0], &queue_count, queue_props.data()); + assert(queue_count >= 1); + + bool found = false; + for (int i = 0; i < (int)queue_count; i++) { if (queue_props[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) { queue_info.queueFamilyIndex = i; found = true; break; } - } - assert(found); - assert(queue_count >= 1); + } + assert(found); + assert(queue_count >= 1); - // This is as good a place as any to do this - vkGetPhysicalDeviceMemoryProperties(physical_devices_[0], &memory_properties); - vkGetPhysicalDeviceProperties(physical_devices_[0], &gpu_props); + // This is as good a place as any to do this + vkGetPhysicalDeviceMemoryProperties(physical_devices_[0], &memory_properties); + vkGetPhysicalDeviceProperties(physical_devices_[0], &gpu_props); - float queue_priorities[1] = { 0.0 }; - queue_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; - queue_info.pNext = NULL; - queue_info.queueCount = 1; - queue_info.pQueuePriorities = queue_priorities; + float queue_priorities[1] = { 0.0 }; + queue_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; + queue_info.pNext = nullptr; + queue_info.queueCount = 1; + queue_info.pQueuePriorities = queue_priorities; // Optional features vkGetPhysicalDeviceFeatures(physical_devices_[0], &featuresAvailable_); @@ -650,25 +663,28 @@ VkResult VulkanContext::CreateDevice(int physical_device) { featuresEnabled_.depthBounds = true; } - VkDeviceCreateInfo device_info = {}; - device_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; - device_info.pNext = NULL; - device_info.queueCreateInfoCount = 1; - device_info.pQueueCreateInfos = &queue_info; - device_info.enabledLayerCount = (uint32_t)device_layer_names.size(); - device_info.ppEnabledLayerNames = + VkDeviceCreateInfo device_info = {}; + device_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; + device_info.pNext = NULL; + device_info.queueCreateInfoCount = 1; + device_info.pQueueCreateInfos = &queue_info; + device_info.enabledLayerCount = (uint32_t)device_layer_names.size(); + device_info.ppEnabledLayerNames = device_info.enabledLayerCount ? device_layer_names.data() : NULL; - device_info.enabledExtensionCount = (uint32_t)device_extension_names.size(); - device_info.ppEnabledExtensionNames = + device_info.enabledExtensionCount = (uint32_t)device_extension_names.size(); + device_info.ppEnabledExtensionNames = device_info.enabledExtensionCount ? device_extension_names.data() : NULL; device_info.pEnabledFeatures = &featuresEnabled_; - res = vkCreateDevice(physical_devices_[0], &device_info, NULL, &device_); - assert(res == VK_SUCCESS); + res = vkCreateDevice(physical_devices_[0], &device_info, NULL, &device_); + if (res != VK_SUCCESS) { + init_error_ = "Unable to create Vulkan device"; + ELOG("Unable to create Vulkan device"); + } else { + VulkanLoadDeviceFunctions(device_); + } - VulkanLoadDeviceFunctions(device_); - - return res; + return res; } VkResult VulkanContext::InitDebugMsgCallback(PFN_vkDebugReportCallbackEXT dbgFunc, int bits, void *userdata) { diff --git a/Common/Vulkan/VulkanContext.h b/Common/Vulkan/VulkanContext.h index 14779e3168..5ffa6c2e45 100644 --- a/Common/Vulkan/VulkanContext.h +++ b/Common/Vulkan/VulkanContext.h @@ -155,6 +155,8 @@ public: VkResult CreateDevice(int physical_device); + const std::string &InitError() { return init_error_; } + VkDevice GetDevice() { return device_; } VkInstance GetInstance() { return instance_; } @@ -268,6 +270,7 @@ private: bool prepared; bool use_staging_buffer_; + std::string init_error_; std::vector instance_layer_names; std::vector instance_extension_names; std::vector instance_layer_properties; diff --git a/Windows/EmuThread.cpp b/Windows/EmuThread.cpp index 753b8cf5f7..abe0797908 100644 --- a/Windows/EmuThread.cpp +++ b/Windows/EmuThread.cpp @@ -128,6 +128,7 @@ unsigned int WINAPI TheThread(void *) I18NCategory *err = GetI18NCategory("Error"); Reporting::ReportMessage("Graphics init error: %s", error_string.c_str()); + const char *defaultErrorVulkan = "Failed initializing graphics. Try upgrading your graphics drivers.\n\nWould you like to try switching to OpenGL?\n\nError message:"; const char *defaultErrorOpenGL = "Failed initializing graphics. Try upgrading your graphics drivers.\n\nWould you like to try switching to DirectX 9?\n\nError message:"; const char *defaultErrorDirect3D9 = "Failed initializing graphics. Try upgrading your graphics drivers and directx 9 runtime.\n\nWould you like to try switching to OpenGL?\n\nError message:"; const char *genericError; @@ -137,6 +138,10 @@ unsigned int WINAPI TheThread(void *) nextBackend = GPU_BACKEND_OPENGL; genericError = err->T("GenericDirect3D9Error", defaultErrorDirect3D9); break; + case GPU_BACKEND_VULKAN: + nextBackend = GPU_BACKEND_OPENGL; + genericError = err->T("GenericVulkanError", defaultErrorDirect3D9); + break; case GPU_BACKEND_OPENGL: default: nextBackend = GPU_BACKEND_DIRECT3D9; diff --git a/Windows/GPU/WindowsVulkanContext.cpp b/Windows/GPU/WindowsVulkanContext.cpp index 5d9e0b79c4..32f8b46676 100644 --- a/Windows/GPU/WindowsVulkanContext.cpp +++ b/Windows/GPU/WindowsVulkanContext.cpp @@ -166,7 +166,10 @@ bool WindowsVulkanContext::Init(HINSTANCE hInst, HWND hWnd, std::string *error_m Version gitVer(PPSSPP_GIT_VERSION); g_Vulkan = new VulkanContext("PPSSPP", gitVer.ToInteger(), (g_validate_ ? VULKAN_FLAG_VALIDATE : 0) | VULKAN_FLAG_PRESENT_MAILBOX); - g_Vulkan->CreateDevice(0); + if (g_Vulkan->CreateDevice(0) != VK_SUCCESS) { + *error_message = g_Vulkan->InitError(); + return false; + } if (g_validate_) { int bits = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT; g_Vulkan->InitDebugMsgCallback(Vulkan_Dbg, bits, &g_LogOptions); diff --git a/android/jni/app-android.cpp b/android/jni/app-android.cpp index 52426ed1ec..853fb3673c 100644 --- a/android/jni/app-android.cpp +++ b/android/jni/app-android.cpp @@ -253,7 +253,9 @@ bool AndroidVulkanContext::Init(ANativeWindow *wnd, int desiredBackbufferSizeX, } ILOG("Creating vulkan device"); - g_Vulkan->CreateDevice(0); + if (g_Vulkan->CreateDevice(0) != VK_SUCCESS) { + return false; + } int width = desiredBackbufferSizeX; int height = desiredBackbufferSizeY; if (!width || !height) { From 0b7e43d05c8ed4d96c43e32a33bf86ce0a4102d4 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sun, 13 Mar 2016 10:38:38 -0700 Subject: [PATCH 080/116] Allow the graphicsContext to be overridden. This is useful when coming from, for example, headless. --- Core/System.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Core/System.cpp b/Core/System.cpp index bc7e20b8b3..110f88f04f 100644 --- a/Core/System.cpp +++ b/Core/System.cpp @@ -389,7 +389,9 @@ bool PSP_InitStart(const CoreParameter &coreParam, std::string *error_string) { GraphicsContext *temp = coreParameter.graphicsContext; coreParameter = coreParam; - coreParameter.graphicsContext = temp; + if (coreParameter.graphicsContext == nullptr) { + coreParameter.graphicsContext = temp; + } coreParameter.errorString = ""; pspIsIniting = true; From c770349475ba67296037d9b7660d83f4f251ea36 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sun, 13 Mar 2016 11:23:46 -0700 Subject: [PATCH 081/116] Switch headless to using graphics contexts. Vulkan doesn't work yet, needs some thin3d for the command buffer? --- Windows/WindowsHost.cpp | 4 +- headless/Headless.cpp | 10 +-- headless/Headless.vcxproj | 8 ++- headless/Headless.vcxproj.filters | 27 ++++++-- headless/StubHost.h | 3 + headless/WindowsHeadlessHost.cpp | 101 +++++++++++++--------------- headless/WindowsHeadlessHost.h | 2 +- headless/WindowsHeadlessHostDx9.cpp | 101 ---------------------------- headless/WindowsHeadlessHostDx9.h | 39 ----------- 9 files changed, 83 insertions(+), 212 deletions(-) delete mode 100644 headless/WindowsHeadlessHostDx9.cpp delete mode 100644 headless/WindowsHeadlessHostDx9.h diff --git a/Windows/WindowsHost.cpp b/Windows/WindowsHost.cpp index 06f78162d6..9121e630b4 100644 --- a/Windows/WindowsHost.cpp +++ b/Windows/WindowsHost.cpp @@ -114,8 +114,8 @@ bool WindowsHost::InitGraphics(std::string *error_message, GraphicsContext **ctx graphicsContext = new D3D9Context(); break; case GPU_BACKEND_VULKAN: - graphicsContext = new WindowsVulkanContext(); - break; + graphicsContext = new WindowsVulkanContext(); + break; default: return false; } diff --git a/headless/Headless.cpp b/headless/Headless.cpp index eba3ffca29..630c1bd39b 100644 --- a/headless/Headless.cpp +++ b/headless/Headless.cpp @@ -25,9 +25,7 @@ #include "Compare.h" #include "StubHost.h" #ifdef _WIN32 -#include "Windows/GPU/WindowsGLContext.h" #include "WindowsHeadlessHost.h" -#include "WindowsHeadlessHostDx9.h" #endif // https://github.com/richq/android-ndk-profiler @@ -120,10 +118,6 @@ static HeadlessHost *getHost(GPUCore gpuCore) { switch (gpuCore) { case GPU_NULL: return new HeadlessHost(); -#ifdef _WIN32 - case GPU_DIRECTX9: - return new WindowsHeadlessHostDx9(); -#endif #ifdef HEADLESSHOST_CLASS default: return new HEADLESSHOST_CLASS(); @@ -258,6 +252,8 @@ int main(int argc, const char* argv[]) gpuCore = GPU_SOFTWARE; else if (!strcasecmp(gpuName, "directx9")) gpuCore = GPU_DIRECTX9; + else if (!strcasecmp(gpuName, "vulkan")) + gpuCore = GPU_VULKAN; else if (!strcasecmp(gpuName, "null")) gpuCore = GPU_NULL; else @@ -295,10 +291,10 @@ int main(int argc, const char* argv[]) return printUsage(argv[0], argc <= 1 ? NULL : "No executables specified"); HeadlessHost *headlessHost = getHost(gpuCore); + headlessHost->SetGraphicsCore(gpuCore); host = headlessHost; std::string error_string; - GraphicsContext *graphicsContext; bool glWorking = host->InitGraphics(&error_string, &graphicsContext); diff --git a/headless/Headless.vcxproj b/headless/Headless.vcxproj index cdf062c374..c1ae2d41fa 100644 --- a/headless/Headless.vcxproj +++ b/headless/Headless.vcxproj @@ -225,6 +225,10 @@ + + + + NotUsing @@ -233,7 +237,6 @@ NotUsing - @@ -267,9 +270,8 @@ - - + \ No newline at end of file diff --git a/headless/Headless.vcxproj.filters b/headless/Headless.vcxproj.filters index fd3ee83d54..d699015802 100644 --- a/headless/Headless.vcxproj.filters +++ b/headless/Headless.vcxproj.filters @@ -2,11 +2,24 @@ - - + + Windows + + + Windows + + + Windows + + + Windows + + + Windows + @@ -14,9 +27,15 @@ - - + + Windows + + + + + {28215e85-3e11-4a8a-8b4d-3e355b85a542} + \ No newline at end of file diff --git a/headless/StubHost.h b/headless/StubHost.h index d12ca57099..78e9b1a15f 100644 --- a/headless/StubHost.h +++ b/headless/StubHost.h @@ -17,6 +17,7 @@ #pragma once +#include "Core/CoreParameter.h" #include "Core/Host.h" #include "Core/Debugger/SymbolMap.h" @@ -30,6 +31,7 @@ public: void SetDebugMode(bool mode) { } + void SetGraphicsCore(GPUCore core) { gpuCore_ = core; } bool InitGraphics(std::string *error_message, GraphicsContext **ctx) override {return false;} void ShutdownGraphics() override {} @@ -70,4 +72,5 @@ public: protected: std::string debugOutputBuffer_; + GPUCore gpuCore_; }; \ No newline at end of file diff --git a/headless/WindowsHeadlessHost.cpp b/headless/WindowsHeadlessHost.cpp index e2e776f21c..55a9b39de5 100644 --- a/headless/WindowsHeadlessHost.cpp +++ b/headless/WindowsHeadlessHost.cpp @@ -28,6 +28,8 @@ #include "GPU/Common/GPUDebugInterface.h" #include "GPU/GPUState.h" #include "Windows/GPU/WindowsGLContext.h" +#include "Windows/GPU/D3D9Context.h" +#include "Windows/GPU/WindowsVulkanContext.h" #include "base/logging.h" #include "gfx/gl_common.h" @@ -141,79 +143,68 @@ void WindowsHeadlessHost::SetComparisonScreenshot(const std::string &filename) comparisonScreenshot = filename; } -bool WindowsHeadlessHost::InitGraphics(std::string *error_message, GraphicsContext **graphicsContext) -{ +bool WindowsHeadlessHost::InitGraphics(std::string *error_message, GraphicsContext **ctx) { hWnd = CreateHiddenWindow(); - if (WINDOW_VISIBLE) - { + if (WINDOW_VISIBLE) { ShowWindow(hWnd, TRUE); SetFocus(hWnd); } - int pixelFormat; + WindowsGraphicsContext *graphicsContext = nullptr; + switch (gpuCore_) { + case GPU_NULL: + case GPU_GLES: + case GPU_SOFTWARE: + graphicsContext = new WindowsGLContext(); + break; - static PIXELFORMATDESCRIPTOR pfd = {0}; - pfd.nSize = sizeof(pfd); - pfd.nVersion = 1; - pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; - pfd.iPixelType = PFD_TYPE_RGBA; - pfd.cColorBits = 32; - pfd.cDepthBits = 16; - pfd.iLayerType = PFD_MAIN_PLANE; + case GPU_DIRECTX9: + graphicsContext = new D3D9Context(); + break; -#define ENFORCE(x, msg) { if (!(x)) { fprintf(stderr, msg); *error_message = msg; return false; } } + case GPU_DIRECTX11: + return false; - ENFORCE(hDC = GetDC(hWnd), "Unable to create DC."); - ENFORCE(pixelFormat = ChoosePixelFormat(hDC, &pfd), "Unable to match pixel format."); - ENFORCE(SetPixelFormat(hDC, pixelFormat, &pfd), "Unable to set pixel format."); - ENFORCE(hRC = wglCreateContext(hDC), "Unable to create GL context."); - ENFORCE(wglMakeCurrent(hDC, hRC), "Unable to activate GL context."); + case GPU_VULKAN: + graphicsContext = new WindowsVulkanContext(); + break; + } - // GL_SwapInterval(0); + if (graphicsContext->Init(NULL, hWnd, error_message)) { + *ctx = graphicsContext; + gfx_ = graphicsContext; + } else { + delete graphicsContext; + *ctx = nullptr; + gfx_ = nullptr; + return false; + } - glewInit(); - CheckGLExtensions(); + if (gpuCore_ == GPU_GLES) { + // TODO: Do we need to do this here? + CheckGLExtensions(); + } LoadNativeAssets(); - *graphicsContext = new DummyGraphicsContext(); - return ResizeGL(); + return true; } -void WindowsHeadlessHost::ShutdownGraphics() -{ - if (hRC) { - wglMakeCurrent(NULL, NULL); - wglDeleteContext(hRC); - hRC = NULL; - } - - if (hDC) - ReleaseDC(hWnd, hDC); - hDC = NULL; +void WindowsHeadlessHost::ShutdownGraphics() { + gfx_->Shutdown(); + delete gfx_; + gfx_ = nullptr; DestroyWindow(hWnd); hWnd = NULL; } -bool WindowsHeadlessHost::ResizeGL() -{ - if (!hWnd) - return false; - - RECT rc; - GetWindowRect(hWnd, &rc); - - glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - glOrtho(0.0f, WINDOW_WIDTH, WINDOW_HEIGHT, 0.0f, -1.0f, 1.0f); - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - return true; -} - -void WindowsHeadlessHost::SwapBuffers() -{ - ::SwapBuffers(hDC); +void WindowsHeadlessHost::SwapBuffers() { + if (gpuCore_ == GPU_DIRECTX9) { + MSG msg; + PeekMessage(&msg, NULL, 0, 0, PM_REMOVE); + TranslateMessage(&msg); + DispatchMessage(&msg); + } + gfx_->SwapBuffers(); } diff --git a/headless/WindowsHeadlessHost.h b/headless/WindowsHeadlessHost.h index 7e968fb9fb..088e7935da 100644 --- a/headless/WindowsHeadlessHost.h +++ b/headless/WindowsHeadlessHost.h @@ -38,12 +38,12 @@ public: virtual void SetComparisonScreenshot(const std::string &filename) override; protected: - virtual bool ResizeGL(); void LoadNativeAssets(); void SendOrCollectDebugOutput(const std::string &output); HWND hWnd; HDC hDC; HGLRC hRC; + GraphicsContext *gfx_; std::string comparisonScreenshot; }; \ No newline at end of file diff --git a/headless/WindowsHeadlessHostDx9.cpp b/headless/WindowsHeadlessHostDx9.cpp deleted file mode 100644 index b110d69a7a..0000000000 --- a/headless/WindowsHeadlessHostDx9.cpp +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright (c) 2012- PPSSPP Project. - -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, version 2.0 or later versions. - -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License 2.0 for more details. - -// A copy of the GPL 2.0 should have been included with the program. -// If not, see http://www.gnu.org/licenses/ - -// Official git repository and contact information can be found at -// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. - -#include "WindowsHeadlessHostDx9.h" -#include "Compare.h" - -#include -#include "Common/CommonWindows.h" -#include - -#include "base/logging.h" -#include "thin3d/d3dx9_loader.h" -#include "GPU/Directx9/helper/global.h" -#include "GPU/Directx9/helper/dx_fbo.h" -#include "file/vfs.h" -#include "file/zip_read.h" - -const bool WINDOW_VISIBLE = false; -const int WINDOW_WIDTH = 480; -const int WINDOW_HEIGHT = 272; - -HWND DxCreateWindow() { - static WNDCLASSEX wndClass = { - sizeof(WNDCLASSEX), - CS_HREDRAW | CS_VREDRAW | CS_OWNDC, - DefWindowProc, - 0, - 0, - NULL, - NULL, - LoadCursor(NULL, IDC_ARROW), - (HBRUSH) GetStockObject(BLACK_BRUSH), - NULL, - _T("PPSSPPHeadless"), - NULL, - }; - RegisterClassEx(&wndClass); - - RECT wr = {0, 0, WINDOW_WIDTH, WINDOW_HEIGHT}; // set the size, but not the position - AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE); // adjust the size - - DWORD style = WS_OVERLAPPEDWINDOW | (WINDOW_VISIBLE ? WS_VISIBLE : 0); - return CreateWindowEx(0, _T("PPSSPPHeadless"), _T("PPSSPPHeadless"), style, CW_USEDEFAULT, CW_USEDEFAULT, wr.right - wr.left, wr.bottom - wr.top, NULL, NULL, NULL, NULL); -} - -bool WindowsHeadlessHostDx9::InitGraphics(std::string *error_message, GraphicsContext **graphicsContext) { - *graphicsContext = nullptr; - LoadD3DX9Dynamic(); - hWnd = DxCreateWindow(); - - if (WINDOW_VISIBLE) { - ShowWindow(hWnd, TRUE); - SetFocus(hWnd); - } - - DX9::DirectxInit(hWnd); - - LoadNativeAssets(); - - DX9::pD3Ddevice->BeginScene(); - - return true; -} - -void WindowsHeadlessHostDx9::ShutdownGraphics() { - DX9::DestroyShaders(); - DX9::fbo_shutdown(); - DX9::pD3Ddevice->EndScene(); - DX9::pD3Ddevice->Release(); - DX9::pD3Ddevice = NULL; - hWnd = NULL; -} - -bool WindowsHeadlessHostDx9::ResizeGL() { - return true; -} - -void WindowsHeadlessHostDx9::SwapBuffers() { - MSG msg; - PeekMessage(&msg, NULL, 0, 0, PM_REMOVE); - TranslateMessage(&msg); - DispatchMessage(&msg); - - DX9::pD3Ddevice->EndScene(); - DX9::pD3Ddevice->Present(0, 0, 0, 0); - DX9::pD3Ddevice->BeginScene(); -} diff --git a/headless/WindowsHeadlessHostDx9.h b/headless/WindowsHeadlessHostDx9.h deleted file mode 100644 index 29966ec756..0000000000 --- a/headless/WindowsHeadlessHostDx9.h +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) 2012- PPSSPP Project. - -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, version 2.0 or later versions. - -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License 2.0 for more details. - -// A copy of the GPL 2.0 should have been included with the program. -// If not, see http://www.gnu.org/licenses/ - -// Official git repository and contact information can be found at -// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. - -#pragma once - -#include "StubHost.h" -#include "WindowsHeadlessHost.h" - -#undef HEADLESSHOST_CLASS -#define HEADLESSHOST_CLASS WindowsHeadlessHost - -#include "Common/CommonWindows.h" - -// TODO: Get rid of this junk -class WindowsHeadlessHostDx9 : public WindowsHeadlessHost -{ -public: - bool InitGraphics(std::string *error_message, GraphicsContext **graphicsContext) override; - void ShutdownGraphics() override; - - void SwapBuffers() override; - -private: - bool ResizeGL() override; -}; \ No newline at end of file From 5cee8856eadec6b4922e2877fbae47aa6b9670a9 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Mon, 14 Mar 2016 00:52:09 +0100 Subject: [PATCH 082/116] Fix UV scale for some vertex formats (like GL). Separate updates of PROJ and PROJTHROUGH matrices. --- GPU/Common/ShaderId.cpp | 2 +- GPU/Directx9/VertexShaderGeneratorDX9.cpp | 1 - GPU/Vulkan/DrawEngineVulkan.cpp | 2 +- GPU/Vulkan/ShaderManagerVulkan.cpp | 57 ++++++++++++----------- 4 files changed, 32 insertions(+), 30 deletions(-) diff --git a/GPU/Common/ShaderId.cpp b/GPU/Common/ShaderId.cpp index 1bf7cb7a1a..98d55089bf 100644 --- a/GPU/Common/ShaderId.cpp +++ b/GPU/Common/ShaderId.cpp @@ -122,7 +122,7 @@ void ComputeVertexShaderID(ShaderID *id_out, u32 vertType, bool useHWTransform) if (doTextureProjection && gstate.getUVProjMode() == GE_PROJMAP_UV) { id.SetBits(VS_BIT_TEXCOORD_FMTSCALE, 2, (vertType & GE_VTYPE_TC_MASK) >> GE_VTYPE_TC_SHIFT); // two bits } else { - id.SetBits(VS_BIT_TEXCOORD_FMTSCALE, 2, 3); + id.SetBits(VS_BIT_TEXCOORD_FMTSCALE, 2, 3); // float - no scaling } } diff --git a/GPU/Directx9/VertexShaderGeneratorDX9.cpp b/GPU/Directx9/VertexShaderGeneratorDX9.cpp index d464e59ab1..905c84722c 100644 --- a/GPU/Directx9/VertexShaderGeneratorDX9.cpp +++ b/GPU/Directx9/VertexShaderGeneratorDX9.cpp @@ -102,7 +102,6 @@ void GenerateVertexShaderDX9(const ShaderID &id, char *buffer) { if (enableBones) { numBoneWeights = 1 + id.Bits(VS_BIT_BONES, 3); } - int texFmtScale = id.Bits(VS_BIT_TEXCOORD_FMTSCALE, 2); WRITE(p, "#pragma warning( disable : 3571 )\n"); diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index 4d42ef4dff..248e2cdbe8 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -75,7 +75,7 @@ DrawEngineVulkan::DrawEngineVulkan(VulkanContext *vulkan) curFrame_(0) { memset(&decOptions_, 0, sizeof(decOptions_)); - decOptions_.expandAllUVtoFloat = false; + decOptions_.expandAllUVtoFloat = false; // this may be a good idea though. decOptions_.expandAllWeightsToFloat = false; decOptions_.expand8BitNormalsToFloat = false; diff --git a/GPU/Vulkan/ShaderManagerVulkan.cpp b/GPU/Vulkan/ShaderManagerVulkan.cpp index 4f062f4e6e..97c0bbc47e 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.cpp +++ b/GPU/Vulkan/ShaderManagerVulkan.cpp @@ -242,34 +242,33 @@ void ShaderManagerVulkan::BaseUpdateUniforms(int dirtyUniforms) { CopyFloat2(ub_base.texClampOffset, texclampoff); } - // Update any dirty uniforms before we draw if (dirtyUniforms & DIRTY_PROJMATRIX) { - if (gstate.isModeThrough()) { - Matrix4x4 proj_through; - proj_through.setOrtho(0.0f, gstate_c.curRTWidth, 0, gstate_c.curRTHeight, 0, 1); - ConvertProjMatrixToVulkanThrough(proj_through); - CopyMatrix4x4(ub_base.proj_through, proj_through.getReadPtr()); - } else { - Matrix4x4 flippedMatrix; - memcpy(&flippedMatrix, gstate.projMatrix, 16 * sizeof(float)); + Matrix4x4 flippedMatrix; + memcpy(&flippedMatrix, gstate.projMatrix, 16 * sizeof(float)); - const bool invertedY = gstate_c.vpHeight < 0; - if (invertedY) { - flippedMatrix[1] = -flippedMatrix[1]; - flippedMatrix[5] = -flippedMatrix[5]; - flippedMatrix[9] = -flippedMatrix[9]; - flippedMatrix[13] = -flippedMatrix[13]; - } - const bool invertedX = gstate_c.vpWidth < 0; - if (invertedX) { - flippedMatrix[0] = -flippedMatrix[0]; - flippedMatrix[4] = -flippedMatrix[4]; - flippedMatrix[8] = -flippedMatrix[8]; - flippedMatrix[12] = -flippedMatrix[12]; - } - ConvertProjMatrixToVulkan(flippedMatrix, invertedX, invertedY); - CopyMatrix4x4(ub_base.proj, flippedMatrix.getReadPtr()); + const bool invertedY = gstate_c.vpHeight < 0; + if (invertedY) { + flippedMatrix[1] = -flippedMatrix[1]; + flippedMatrix[5] = -flippedMatrix[5]; + flippedMatrix[9] = -flippedMatrix[9]; + flippedMatrix[13] = -flippedMatrix[13]; } + const bool invertedX = gstate_c.vpWidth < 0; + if (invertedX) { + flippedMatrix[0] = -flippedMatrix[0]; + flippedMatrix[4] = -flippedMatrix[4]; + flippedMatrix[8] = -flippedMatrix[8]; + flippedMatrix[12] = -flippedMatrix[12]; + } + ConvertProjMatrixToVulkan(flippedMatrix, invertedX, invertedY); + CopyMatrix4x4(ub_base.proj, flippedMatrix.getReadPtr()); + } + + if (dirtyUniforms & DIRTY_PROJTHROUGHMATRIX) { + Matrix4x4 proj_through; + proj_through.setOrtho(0.0f, gstate_c.curRTWidth, 0, gstate_c.curRTHeight, 0, 1); + ConvertProjMatrixToVulkanThrough(proj_through); + CopyMatrix4x4(ub_base.proj_through, proj_through.getReadPtr()); } // Transform @@ -315,13 +314,17 @@ void ShaderManagerVulkan::BaseUpdateUniforms(int dirtyUniforms) { const float widthFactor = (float)w * invW; const float heightFactor = (float)h * invH; + static const float rescale[4] = { 1.0f, 2 * 127.5f / 128.f, 2 * 32767.5f / 32768.f, 1.0f }; + const float factor = rescale[(gstate.vertType & GE_VTYPE_TC_MASK) >> GE_VTYPE_TC_SHIFT]; + float uvscaleoff[4]; + switch (gstate.getUVGenMode()) { case GE_TEXMAP_TEXTURE_COORDS: // Not sure what GE_TEXMAP_UNKNOWN is, but seen in Riviera. Treating the same as GE_TEXMAP_TEXTURE_COORDS works. case GE_TEXMAP_UNKNOWN: - uvscaleoff[0] = gstate_c.uv.uScale * widthFactor; - uvscaleoff[1] = gstate_c.uv.vScale * heightFactor; + uvscaleoff[0] = gstate_c.uv.uScale * factor * widthFactor; + uvscaleoff[1] = gstate_c.uv.vScale * factor * heightFactor; uvscaleoff[2] = gstate_c.uv.uOff * widthFactor; uvscaleoff[3] = gstate_c.uv.vOff * heightFactor; break; From 1f1e679aa039e2023cfdda564df75bc2f8eb1fff Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Mon, 14 Mar 2016 00:53:36 +0100 Subject: [PATCH 083/116] Silence another validation warning --- Windows/GPU/WindowsVulkanContext.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Windows/GPU/WindowsVulkanContext.cpp b/Windows/GPU/WindowsVulkanContext.cpp index 32f8b46676..3fcfbbf182 100644 --- a/Windows/GPU/WindowsVulkanContext.cpp +++ b/Windows/GPU/WindowsVulkanContext.cpp @@ -121,7 +121,7 @@ static VkBool32 VKAPI_CALL Vulkan_Dbg(VkDebugReportFlagsEXT msgFlags, VkDebugRep // Getting some bizarre false positives for mapping image memory. // https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers/issues/121 - if (msgCode == 6 && !memcmp(pMsg, "Cannot map", 10)) + if (msgCode == 6 && (!memcmp(pMsg, "Cannot map", 10) || !memcmp(pMsg, "Cannot sub", 10))) return false; #ifdef _WIN32 From 3e268e4d373c73ce29b024c5be43dd107a61d34e Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Mon, 14 Mar 2016 00:53:57 +0100 Subject: [PATCH 084/116] Mem leak fixes, cleanups --- GPU/Vulkan/GPU_Vulkan.cpp | 7 ++--- GPU/Vulkan/PipelineManagerVulkan.cpp | 41 ++++++++-------------------- GPU/Vulkan/StateMappingVulkan.h | 1 + GPU/Vulkan/TextureCacheVulkan.cpp | 11 ++------ 4 files changed, 16 insertions(+), 44 deletions(-) diff --git a/GPU/Vulkan/GPU_Vulkan.cpp b/GPU/Vulkan/GPU_Vulkan.cpp index 3fdf78ba9c..f4982fc894 100644 --- a/GPU/Vulkan/GPU_Vulkan.cpp +++ b/GPU/Vulkan/GPU_Vulkan.cpp @@ -455,12 +455,9 @@ GPU_Vulkan::GPU_Vulkan(GraphicsContext *ctx) GPU_Vulkan::~GPU_Vulkan() { framebufferManager_->DestroyAllFBOs(); depalShaderCache_.Clear(); + delete framebufferManager_; + delete pipelineManager_; delete shaderManager_; - shaderManager_ = nullptr; - -#ifdef _WIN32 - gfxCtx_->SwapInterval(0); -#endif } void GPU_Vulkan::CheckGPUFeatures() { diff --git a/GPU/Vulkan/PipelineManagerVulkan.cpp b/GPU/Vulkan/PipelineManagerVulkan.cpp index ef51bf6e9e..13f228b142 100644 --- a/GPU/Vulkan/PipelineManagerVulkan.cpp +++ b/GPU/Vulkan/PipelineManagerVulkan.cpp @@ -99,7 +99,7 @@ int SetupVertexAttribsPretransformed(VkVertexInputAttributeDescription attrs[], } static VulkanPipeline *CreateVulkanPipeline(VkDevice device, VkPipelineCache pipelineCache, VkPipelineLayout layout, VkRenderPass renderPass, const VulkanPipelineRasterStateKey &key, const VertexDecoder *vtxDec, VulkanVertexShader *vs, VulkanFragmentShader *fs, bool useHwTransform) { - VkPipelineColorBlendAttachmentState blend0; + VkPipelineColorBlendAttachmentState blend0 = {}; blend0.blendEnable = key.blendEnable; if (key.blendEnable) { blend0.colorBlendOp = (VkBlendOp)key.blendOpColor; @@ -110,10 +110,8 @@ static VulkanPipeline *CreateVulkanPipeline(VkDevice device, VkPipelineCache pip blend0.dstAlphaBlendFactor = (VkBlendFactor)key.destAlpha; } blend0.colorWriteMask = key.colorWriteMask; - - VkPipelineColorBlendStateCreateInfo cbs; - cbs.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; - cbs.pNext = nullptr; + + VkPipelineColorBlendStateCreateInfo cbs = { VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO }; cbs.flags = 0; cbs.pAttachments = &blend0; cbs.attachmentCount = 1; @@ -123,9 +121,7 @@ static VulkanPipeline *CreateVulkanPipeline(VkDevice device, VkPipelineCache pip else cbs.logicOp = VK_LOGIC_OP_COPY; - VkPipelineDepthStencilStateCreateInfo dss = { }; - dss.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; - dss.pNext = nullptr; + VkPipelineDepthStencilStateCreateInfo dss = { VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO }; dss.depthBoundsTestEnable = false; dss.stencilTestEnable = key.stencilTestEnable; if (key.stencilTestEnable) { @@ -155,16 +151,12 @@ static VulkanPipeline *CreateVulkanPipeline(VkDevice device, VkPipelineCache pip dynamicStates[numDyn++] = VK_DYNAMIC_STATE_STENCIL_WRITE_MASK; } - VkPipelineDynamicStateCreateInfo ds; - ds.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; - ds.pNext = nullptr; + VkPipelineDynamicStateCreateInfo ds = { VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO }; ds.flags = 0; ds.pDynamicStates = dynamicStates; ds.dynamicStateCount = numDyn; - VkPipelineRasterizationStateCreateInfo rs; - rs.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; - rs.pNext = nullptr; + VkPipelineRasterizationStateCreateInfo rs = { VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO }; rs.flags = 0; rs.depthBiasEnable = false; rs.cullMode = key.cullMode; @@ -174,10 +166,7 @@ static VulkanPipeline *CreateVulkanPipeline(VkDevice device, VkPipelineCache pip rs.polygonMode = VK_POLYGON_MODE_FILL; rs.depthClampEnable = false; - VkPipelineMultisampleStateCreateInfo ms; - memset(&ms, 0, sizeof(ms)); - ms.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; - ms.pNext = nullptr; + VkPipelineMultisampleStateCreateInfo ms = { VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO }; ms.pSampleMask = nullptr; ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; @@ -202,9 +191,7 @@ static VulkanPipeline *CreateVulkanPipeline(VkDevice device, VkPipelineCache pip return nullptr; } - VkPipelineInputAssemblyStateCreateInfo inputAssembly; - inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; - inputAssembly.pNext = nullptr; + VkPipelineInputAssemblyStateCreateInfo inputAssembly = { VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO }; inputAssembly.flags = 0; inputAssembly.topology = (VkPrimitiveTopology)key.topology; inputAssembly.primitiveRestartEnable = false; @@ -227,27 +214,21 @@ static VulkanPipeline *CreateVulkanPipeline(VkDevice device, VkPipelineCache pip ibd.inputRate = VK_VERTEX_INPUT_RATE_VERTEX; ibd.stride = vertexStride; - VkPipelineVertexInputStateCreateInfo vis; - vis.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; - vis.pNext = nullptr; + VkPipelineVertexInputStateCreateInfo vis = { VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO }; vis.flags = 0; vis.vertexBindingDescriptionCount = 1; vis.pVertexBindingDescriptions = &ibd; vis.vertexAttributeDescriptionCount = attributeCount; vis.pVertexAttributeDescriptions = attrs; - VkPipelineViewportStateCreateInfo views; - views.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; - views.pNext = nullptr; + VkPipelineViewportStateCreateInfo views = { VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO }; views.flags = 0; views.viewportCount = 1; views.scissorCount = 1; views.pViewports = nullptr; // dynamic views.pScissors = nullptr; // dynamic - VkGraphicsPipelineCreateInfo pipe; - pipe.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; - pipe.pNext = nullptr; + VkGraphicsPipelineCreateInfo pipe = { VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO }; pipe.flags = 0; pipe.stageCount = 2; pipe.pStages = ss; diff --git a/GPU/Vulkan/StateMappingVulkan.h b/GPU/Vulkan/StateMappingVulkan.h index 8bb8aa0a07..0f907bc649 100644 --- a/GPU/Vulkan/StateMappingVulkan.h +++ b/GPU/Vulkan/StateMappingVulkan.h @@ -29,6 +29,7 @@ struct VulkanPipelineRasterStateKey { unsigned int destColor : 5; // VkBlendFactor unsigned int srcAlpha : 5; // VkBlendFactor unsigned int destAlpha : 5; // VkBlendFactor + // bool useBlendConstant : 1; // sacrifice a bit to cheaply check if we need to update the blend color unsigned int blendOpColor : 3; // VkBlendOp unsigned int blendOpAlpha : 3; // VkBlendOp bool logicOpEnable : 1; diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index c4695fb6bb..25a3cfc1a7 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -1266,8 +1266,6 @@ void TextureCacheVulkan::SetTexture() { gstate_c.textureFullAlpha = entry->GetAlphaStatus() == TexCacheEntry::STATUS_ALPHA_FULL; gstate_c.textureSimpleAlpha = entry->GetAlphaStatus() != TexCacheEntry::STATUS_ALPHA_UNKNOWN; } - gstate_c.curTextureWidth = w; - gstate_c.curTextureHeight = h; nextTexture_ = entry; VERBOSE_LOG(G3D, "Texture at %08x Found in Cache, applying", texaddr); return; //Done! @@ -1458,13 +1456,8 @@ void TextureCacheVulkan::SetTexture() { } lastBoundTexture = entry->vkTex; - // GLES2 doesn't have support for a "Max lod" which is critical as PSP games often - // don't specify mips all the way down. As a result, we either need to manually generate - // the bottom few levels or rely on OpenGL's autogen mipmaps instead, which might not - // be as good quality as the game's own (might even be better in some cases though). - - // Always load base level texture here - + // In Vulkan, fortunately, we have full control over mipmapping. + // For now, we only load the base texture. More to come. LoadTextureLevel(*entry, 0, replaceImages, scaleFactor, dstFmt); // Mipmapping only enable when texture scaling disable From 242daae00a010b2fc82b90e15987cdd808a4ca8b Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sun, 13 Mar 2016 18:41:26 -0700 Subject: [PATCH 085/116] Disable last texture reuse for now. This will be slower, but otherwise a lot of textures are missing in various games, like Final Fantasy 4. Better to get all the bugs out first and then start optimizing. Note: there is still missing drawing in Final Fantasy 4, but only text after this change. --- GPU/Vulkan/DrawEngineVulkan.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index 248e2cdbe8..089f8d267f 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -464,7 +464,9 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { VkImageView imageView = VK_NULL_HANDLE; VkSampler sampler = VK_NULL_HANDLE; - if (gstate_c.textureChanged != TEXCHANGE_UNCHANGED && !gstate.isModeClear() && gstate.isTextureMapEnabled()) { + // TODO: The descriptor set seems to be unbinding the texture when not specified. Cache it or the imageView instead? + // TODO: Add this back when fixed: gstate_c.textureChanged != TEXCHANGE_UNCHANGED && + if (!gstate.isModeClear() && gstate.isTextureMapEnabled()) { textureCache_->SetTexture(); gstate_c.textureChanged = TEXCHANGE_UNCHANGED; if (gstate_c.needShaderTexClamp) { From 00d617c9d51866850d7716b4c8ccee0ea899204d Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Mon, 14 Mar 2016 01:46:54 +0100 Subject: [PATCH 086/116] Fix bug where we sometimes pushed too much vertex data. Doesn't seem to fix much though... --- GPU/Vulkan/DrawEngineVulkan.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index 089f8d267f..665c0b0f96 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -556,7 +556,7 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { vkCmdBindDescriptorSets(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout_, 0, 1, &ds, 3, dynamicUBOOffsets); int stride = dec_->GetDecVtxFmt().stride; - vbOffset = (uint32_t)frame->pushData->PushAligned(decoded, vertexCount * stride, 16); + vbOffset = (uint32_t)frame->pushData->PushAligned(decoded, indexGen.MaxIndex() * stride, 16); VkDeviceSize offsets[1] = { vbOffset }; if (useElements) { @@ -565,7 +565,7 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { // Might want to separate vertices out into a different push buffer in that case. vkCmdBindVertexBuffers(cmd_, 0, 1, buf, offsets); vkCmdBindIndexBuffer(cmd_, buf[0], ibOffset, VK_INDEX_TYPE_UINT16); - vkCmdDrawIndexed(cmd_, indexGen.VertexCount(), 1, 0, 0, 0); + vkCmdDrawIndexed(cmd_, vertexCount, 1, 0, 0, 0); } else { vkCmdBindVertexBuffers(cmd_, 0, 1, buf, offsets); vkCmdDraw(cmd_, vertexCount, 1, 0, 0); From 1970d3865059647585bd0a46c7e761d76a4d8a2d Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Mon, 14 Mar 2016 18:57:21 +0100 Subject: [PATCH 087/116] Enable the Unpack Subimage path on DX9 (maybe should just remove the check) --- GPU/Directx9/GPU_DX9.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/GPU/Directx9/GPU_DX9.cpp b/GPU/Directx9/GPU_DX9.cpp index a21f0a703e..3734b4c9df 100644 --- a/GPU/Directx9/GPU_DX9.cpp +++ b/GPU/Directx9/GPU_DX9.cpp @@ -480,6 +480,7 @@ void DIRECTX9_GPU::CheckGPUFeatures() { features |= GPU_SUPPORTS_TEXTURE_LOD_CONTROL; features |= GPU_PREFER_CPU_DOWNLOAD; features |= GPU_SUPPORTS_ACCURATE_DEPTH; + features |= GPU_SUPPORTS_UNPACK_SUBIMAGE; if (!g_Config.bHighQualityDepth) { features |= GPU_SCALE_DEPTH_FROM_24BIT_TO_16BIT; From 697f3a8f94211f003bf07725e1d4e33d14f584ea Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Mon, 14 Mar 2016 20:00:38 +0100 Subject: [PATCH 088/116] Matrix depth fix. Still have depth issues though. --- GPU/Vulkan/ShaderManagerVulkan.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GPU/Vulkan/ShaderManagerVulkan.cpp b/GPU/Vulkan/ShaderManagerVulkan.cpp index 97c0bbc47e..ee78c43901 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.cpp +++ b/GPU/Vulkan/ShaderManagerVulkan.cpp @@ -162,7 +162,7 @@ static void ConvertProjMatrixToVulkan(Matrix4x4 &in, bool invertedX, bool invert if (invertedY) yoff = -yoff; - const Vec3 trans(xoff, yoff, gstate_c.vpZOffset + 0.5f); + const Vec3 trans(xoff, yoff, gstate_c.vpZOffset * 0.5f + 0.5f); const Vec3 scale(gstate_c.vpWidthScale, gstate_c.vpHeightScale, gstate_c.vpDepthScale * 0.5f); in.translateAndScale(trans, scale); } From c2775d4dfa253b5c293a681dea60627112b613c3 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Mon, 14 Mar 2016 22:07:37 +0100 Subject: [PATCH 089/116] Default validation on in Debug and off in Release --- Windows/GPU/WindowsVulkanContext.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Windows/GPU/WindowsVulkanContext.cpp b/Windows/GPU/WindowsVulkanContext.cpp index 3fcfbbf182..3088e4aca7 100644 --- a/Windows/GPU/WindowsVulkanContext.cpp +++ b/Windows/GPU/WindowsVulkanContext.cpp @@ -59,7 +59,12 @@ extern const char *PPSSPP_GIT_VERSION; +#ifdef _DEBUG static const bool g_validate_ = true; +#else +static const bool g_validate_ = false; +#endif + static VulkanContext *g_Vulkan; struct VulkanLogOptions { From 5ea01ffff68deefe09fc6dbda72edd4dcb1c5d57 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Mon, 14 Mar 2016 23:24:19 +0100 Subject: [PATCH 090/116] Add a secondary way to upload textures - through buffers. --- Common/Vulkan/VulkanContext.cpp | 122 +++++++++++++++++++++++++++--- Common/Vulkan/VulkanContext.h | 12 ++- GPU/Vulkan/TextureCacheVulkan.cpp | 4 +- 3 files changed, 122 insertions(+), 16 deletions(-) diff --git a/Common/Vulkan/VulkanContext.cpp b/Common/Vulkan/VulkanContext.cpp index 52a5a3b769..2b15f90f2e 100644 --- a/Common/Vulkan/VulkanContext.cpp +++ b/Common/Vulkan/VulkanContext.cpp @@ -1290,18 +1290,7 @@ void VulkanTexture::Unlock() { VkCommandBuffer cmd = vulkan_->GetInitCommandBuffer(); // if we already have an image, queue it for destruction and forget it. - if (image) { - vulkan_->Delete().QueueDeleteImage(image); - image = VK_NULL_HANDLE; - } - if (view) { - vulkan_->Delete().QueueDeleteImageView(view); - view = VK_NULL_HANDLE; - } - if (mem) { - vulkan_->Delete().QueueDeleteDeviceMemory(mem); - mem = VK_NULL_HANDLE; - } + Wipe(); if (!needStaging) { // If we can use the linear tiled image as a texture, just do it image = mappableImage; @@ -1424,6 +1413,115 @@ void VulkanTexture::Unlock() { assert(res == VK_SUCCESS); } +void VulkanTexture::Wipe() { + if (image) { + vulkan_->Delete().QueueDeleteImage(image); + image = VK_NULL_HANDLE; + } + if (view) { + vulkan_->Delete().QueueDeleteImageView(view); + view = VK_NULL_HANDLE; + } + if (mem) { + vulkan_->Delete().QueueDeleteDeviceMemory(mem); + mem = VK_NULL_HANDLE; + } +} + +void VulkanTexture::CreateDirect(int w, int h, int numMips, VkFormat format) { + Wipe(); + + VkCommandBuffer cmd = vulkan_->GetInitCommandBuffer(); + + tex_width = w; + tex_height = h; + numMips_ = numMips; + + VkImageCreateInfo image_create_info = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO }; + image_create_info.imageType = VK_IMAGE_TYPE_2D; + image_create_info.format = format_; + image_create_info.extent.width = tex_width; + image_create_info.extent.height = tex_height; + image_create_info.extent.depth = 1; + image_create_info.mipLevels = numMips; + image_create_info.arrayLayers = 1; + image_create_info.samples = VK_SAMPLE_COUNT_1_BIT; + image_create_info.flags = 0; + image_create_info.tiling = VK_IMAGE_TILING_OPTIMAL; + image_create_info.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; + image_create_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + VkResult res = vkCreateImage(vulkan_->GetDevice(), &image_create_info, NULL, &image); + assert(res == VK_SUCCESS); + + vkGetImageMemoryRequirements(vulkan_->GetDevice(), image, &mem_reqs); + VkMemoryAllocateInfo mem_alloc = {}; + mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + mem_alloc.pNext = NULL; + mem_alloc.memoryTypeIndex = 0; + mem_alloc.allocationSize = mem_reqs.size; + + // Find memory type - don't specify any mapping requirements + bool pass = vulkan_->MemoryTypeFromProperties(mem_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &mem_alloc.memoryTypeIndex); + assert(pass); + + res = vkAllocateMemory(vulkan_->GetDevice(), &mem_alloc, NULL, &mem); + assert(res == VK_SUCCESS); + + res = vkBindImageMemory(vulkan_->GetDevice(), image, mem, 0); + assert(res == VK_SUCCESS); + + // Since we're going to blit to the target, set its layout to TRANSFER_DST + TransitionImageLayout(cmd, image, + VK_IMAGE_ASPECT_COLOR_BIT, + VK_IMAGE_LAYOUT_UNDEFINED, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); + + // Create the view while we're at it. + VkImageViewCreateInfo view_info = {}; + view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + view_info.pNext = NULL; + view_info.image = VK_NULL_HANDLE; + view_info.viewType = VK_IMAGE_VIEW_TYPE_2D; + view_info.format = format_; + view_info.components.r = VK_COMPONENT_SWIZZLE_R; + view_info.components.g = VK_COMPONENT_SWIZZLE_G; + view_info.components.b = VK_COMPONENT_SWIZZLE_B; + view_info.components.a = VK_COMPONENT_SWIZZLE_A; + view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + view_info.subresourceRange.baseMipLevel = 0; + view_info.subresourceRange.levelCount = numMips; + view_info.subresourceRange.baseArrayLayer = 0; + view_info.subresourceRange.layerCount = 1; + view_info.image = image; + res = vkCreateImageView(vulkan_->GetDevice(), &view_info, NULL, &view); + assert(res == VK_SUCCESS); +} + +void VulkanTexture::UploadMip(int mip, VkBuffer buffer, size_t offset, size_t stride) { + VkBufferImageCopy copy_region = {}; + copy_region.bufferOffset = offset; + copy_region.bufferRowLength = (uint32_t)stride; + copy_region.bufferImageHeight = tex_height; + copy_region.imageExtent.width = tex_width; + copy_region.imageExtent.height = tex_height; + copy_region.imageExtent.depth = 1; + copy_region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + copy_region.imageSubresource.mipLevel = mip; + copy_region.imageSubresource.baseArrayLayer = 0; + copy_region.imageSubresource.layerCount = 1; + + VkCommandBuffer cmd = vulkan_->GetInitCommandBuffer(); + vkCmdCopyBufferToImage(cmd, buffer, image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©_region); +} + +void VulkanTexture::EndCreate() { + VkCommandBuffer cmd = vulkan_->GetInitCommandBuffer(); + TransitionImageLayout(cmd, image, + VK_IMAGE_ASPECT_COLOR_BIT, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); +} + void VulkanTexture::Destroy() { if (view) { vulkan_->Delete().QueueDeleteImageView(view); diff --git a/Common/Vulkan/VulkanContext.h b/Common/Vulkan/VulkanContext.h index 5ffa6c2e45..ba905279c4 100644 --- a/Common/Vulkan/VulkanContext.h +++ b/Common/Vulkan/VulkanContext.h @@ -354,27 +354,33 @@ public: ~VulkanTexture() { Destroy(); } + + // Simple usage - no cleverness, no mipmaps. // Always call Create, Lock, Unlock. Unlock performs the upload if necessary. // Can later Lock and Unlock again. This cannot change the format. Create cannot // be called a second time without recreating the texture object until Destroy has // been called. - VkResult Create(int w, int h, VkFormat format); uint8_t *Lock(int level, int *rowPitch); void Unlock(); + // Fast uploads from buffer. Mipmaps supported. + void CreateDirect(int w, int h, int numMips, VkFormat format); + void UploadMip(int mip, VkBuffer buffer, size_t offset, size_t stride); + void EndCreate(); + void Destroy(); VkImageView GetImageView() const { return view; } private: void CreateMappableImage(); - + void Wipe(); VulkanContext *vulkan_; VkImage image; VkDeviceMemory mem; VkImageView view; - int32_t tex_width, tex_height; + int32_t tex_width, tex_height, numMips_; VkFormat format_; VkImage mappableImage; VkDeviceMemory mappableMemory; diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index 25a3cfc1a7..2768c7d12b 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -65,8 +65,10 @@ #define TEXCACHE_MIN_PRESSURE 16 * 1024 * 1024 // Total in GL #define TEXCACHE_SECOND_MIN_PRESSURE 4 * 1024 * 1024 +// TODO: Except for color swizzle, exact matches are available. +// So we can get rid of the conversion functions entirely. #define VULKAN_4444_FORMAT VK_FORMAT_R4G4B4A4_UNORM_PACK16 -#define VULKAN_1555_FORMAT VK_FORMAT_R5G5B5A1_UNORM_PACK16 // TODO: Switch to the one that matches the PSP better. +#define VULKAN_1555_FORMAT VK_FORMAT_A1R5G5B5_UNORM_PACK16 // TODO: Switch to the one that matches the PSP better. #define VULKAN_565_FORMAT VK_FORMAT_R5G6B5_UNORM_PACK16 #define VULKAN_8888_FORMAT VK_FORMAT_R8G8B8A8_UNORM From 8a62724316cd9a1e0f4709770e32774fafc5523a Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Mon, 14 Mar 2016 23:25:00 +0100 Subject: [PATCH 091/116] Upload PSP textures through a push buffer instead of image copy. More flexible. --- Common/Vulkan/VulkanContext.cpp | 5 +++-- Common/Vulkan/VulkanContext.h | 8 +++----- GPU/Vulkan/DrawEngineVulkan.cpp | 2 +- GPU/Vulkan/TextureCacheVulkan.cpp | 23 ++++++++++++----------- GPU/Vulkan/TextureCacheVulkan.h | 4 ++-- 5 files changed, 21 insertions(+), 21 deletions(-) diff --git a/Common/Vulkan/VulkanContext.cpp b/Common/Vulkan/VulkanContext.cpp index 2b15f90f2e..3d91d00aab 100644 --- a/Common/Vulkan/VulkanContext.cpp +++ b/Common/Vulkan/VulkanContext.cpp @@ -1436,6 +1436,7 @@ void VulkanTexture::CreateDirect(int w, int h, int numMips, VkFormat format) { tex_width = w; tex_height = h; numMips_ = numMips; + format_ = format; VkImageCreateInfo image_create_info = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO }; image_create_info.imageType = VK_IMAGE_TYPE_2D; @@ -1497,10 +1498,10 @@ void VulkanTexture::CreateDirect(int w, int h, int numMips, VkFormat format) { assert(res == VK_SUCCESS); } -void VulkanTexture::UploadMip(int mip, VkBuffer buffer, size_t offset, size_t stride) { +void VulkanTexture::UploadMip(int mip, VkBuffer buffer, size_t offset, size_t rowLength) { VkBufferImageCopy copy_region = {}; copy_region.bufferOffset = offset; - copy_region.bufferRowLength = (uint32_t)stride; + copy_region.bufferRowLength = (uint32_t)rowLength; copy_region.bufferImageHeight = tex_height; copy_region.imageExtent.width = tex_width; copy_region.imageExtent.height = tex_height; diff --git a/Common/Vulkan/VulkanContext.h b/Common/Vulkan/VulkanContext.h index ba905279c4..c60e305e8b 100644 --- a/Common/Vulkan/VulkanContext.h +++ b/Common/Vulkan/VulkanContext.h @@ -366,7 +366,7 @@ public: // Fast uploads from buffer. Mipmaps supported. void CreateDirect(int w, int h, int numMips, VkFormat format); - void UploadMip(int mip, VkBuffer buffer, size_t offset, size_t stride); + void UploadMip(int mip, VkBuffer buffer, size_t offset, size_t rowLength); // rowLength is in pixels void EndCreate(); void Destroy(); @@ -416,12 +416,10 @@ public: VulkanPushBuffer(VulkanContext *vulkan, size_t size) : offset_(0), size_(size), writePtr_(nullptr), deviceMemory_(0) { VkDevice device = vulkan->GetDevice(); - VkBufferCreateInfo b = {}; - b.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; - b.pNext = nullptr; + VkBufferCreateInfo b = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; b.size = size; b.flags = 0; - b.usage = VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; + b.usage = VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT; b.sharingMode = VK_SHARING_MODE_EXCLUSIVE; b.queueFamilyIndexCount = 0; b.pQueueFamilyIndices = nullptr; diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index 665c0b0f96..dd015a8d8d 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -467,7 +467,7 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { // TODO: The descriptor set seems to be unbinding the texture when not specified. Cache it or the imageView instead? // TODO: Add this back when fixed: gstate_c.textureChanged != TEXCHANGE_UNCHANGED && if (!gstate.isModeClear() && gstate.isTextureMapEnabled()) { - textureCache_->SetTexture(); + textureCache_->SetTexture(frame->pushData); gstate_c.textureChanged = TEXCHANGE_UNCHANGED; if (gstate_c.needShaderTexClamp) { // We will rarely need to set this, so let's do it every time on use rather than in runloop. diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index 2768c7d12b..c9a710a102 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -1069,7 +1069,7 @@ bool TextureCacheVulkan::SetOffsetTexture(u32 offset) { return false; } -void TextureCacheVulkan::SetTexture() { +void TextureCacheVulkan::SetTexture(VulkanPushBuffer *uploadBuffer) { #ifdef DEBUG_TEXTURES if (SetDebugTexture()) { // A different texture was bound, let's rebind next time. @@ -1453,14 +1453,21 @@ void TextureCacheVulkan::SetTexture() { entry->vkTex = new CachedTextureVulkan(); entry->vkTex->texture_ = new VulkanTexture(vulkan_); VulkanTexture *image = entry->vkTex->texture_; - VkResult res = image->Create(w, h, dstFmt); - assert(res == VK_SUCCESS); + image->CreateDirect(w, h, 1, dstFmt); } lastBoundTexture = entry->vkTex; // In Vulkan, fortunately, we have full control over mipmapping. // For now, we only load the base texture. More to come. - LoadTextureLevel(*entry, 0, replaceImages, scaleFactor, dstFmt); + + // Upload the texture data. + int bpp = dstFmt == VULKAN_8888_FORMAT ? 4 : 2; + int stride = (w * bpp + 15) & ~15; + int size = stride * h; + size_t bufferOffset; + void *data = uploadBuffer->Push(size, &bufferOffset); + LoadTextureLevel(*entry, (uint8_t *)data, stride, 0, replaceImages, scaleFactor, dstFmt); + entry->vkTex->texture_->UploadMip(0, uploadBuffer->GetVkBuffer(), bufferOffset, stride / bpp); // Mipmapping only enable when texture scaling disable /* @@ -1740,7 +1747,7 @@ TextureCacheVulkan::TexCacheEntry::Status TextureCacheVulkan::CheckAlpha(const u return (TexCacheEntry::Status)res; } -void TextureCacheVulkan::LoadTextureLevel(TexCacheEntry &entry, int level, bool replaceImages, int scaleFactor, VkFormat dstFmt) { +void TextureCacheVulkan::LoadTextureLevel(TexCacheEntry &entry, uint8_t *writePtr, int rowPitch, int level, bool replaceImages, int scaleFactor, VkFormat dstFmt) { CachedTextureVulkan *tex = entry.vkTex; int w = gstate.getTextureWidth(level); int h = gstate.getTextureHeight(level); @@ -1751,7 +1758,6 @@ void TextureCacheVulkan::LoadTextureLevel(TexCacheEntry &entry, int level, bool PROFILE_THIS_SCOPE("decodetex"); u32 texByteAlign = 1; - GETextureFormat tfmt = (GETextureFormat)entry.format; GEPaletteFormat clutformat = gstate.getClutPaletteFormat(); int bufw; @@ -1784,16 +1790,11 @@ void TextureCacheVulkan::LoadTextureLevel(TexCacheEntry &entry, int level, bool } PROFILE_THIS_SCOPE("loadtex"); - - // Upload the texture data. TODO: Decode directly into this buffer. - int rowPitch; - uint8_t *writePtr = entry.vkTex->texture_->Lock(level, &rowPitch); for (int y = 0; y < h; y++) { memcpy(writePtr + rowPitch * y, (const uint8_t *)pixelData + decPitch * y, rowBytes); // uncomment to make all textures white for debugging //memset(writePtr + rowPitch * y, 0xff, rowBytes); } - entry.vkTex->texture_->Unlock(); /* if (!lowMemoryMode_) { diff --git a/GPU/Vulkan/TextureCacheVulkan.h b/GPU/Vulkan/TextureCacheVulkan.h index 17eaabf863..0d732f480d 100644 --- a/GPU/Vulkan/TextureCacheVulkan.h +++ b/GPU/Vulkan/TextureCacheVulkan.h @@ -85,7 +85,7 @@ public: TextureCacheVulkan(VulkanContext *vulkan); ~TextureCacheVulkan(); - void SetTexture(); + void SetTexture(VulkanPushBuffer *uploadBuffer); virtual bool SetOffsetTexture(u32 offset) override; void Clear(bool delete_them); @@ -126,7 +126,7 @@ private: void DeleteTexture(TexCache::iterator it); void *ReadIndexedTex(int level, const u8 *texptr, int bytesPerIndex, VkFormat dstFmt, int bufw); void UpdateSamplingParams(TexCacheEntry &entry, SamplerCacheKey &key); - void LoadTextureLevel(TexCacheEntry &entry, int level, bool replaceImages, int scaleFactor, VkFormat dstFmt); + void LoadTextureLevel(TexCacheEntry &entry, uint8_t *writePtr, int rowPitch, int level, bool replaceImages, int scaleFactor, VkFormat dstFmt); VkFormat GetDestFormat(GETextureFormat format, GEPaletteFormat clutFormat) const; void *DecodeTextureLevel(GETextureFormat format, GEPaletteFormat clutformat, int level, u32 &texByteAlign, VkFormat dstFmt, int scaleFactor, int *bufw = 0); TexCacheEntry::Status CheckAlpha(const u32 *pixelData, VkFormat dstFmt, int stride, int w, int h); From 84e649f74ba900f30e38f6e075be8b029ce09e9f Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Tue, 15 Mar 2016 00:37:14 +0100 Subject: [PATCH 092/116] Vulkan: Enable mipmapping --- Common/Vulkan/VulkanContext.cpp | 12 +++--- Common/Vulkan/VulkanContext.h | 6 +-- GPU/Vulkan/TextureCacheVulkan.cpp | 72 +++++++++++++------------------ 3 files changed, 38 insertions(+), 52 deletions(-) diff --git a/Common/Vulkan/VulkanContext.cpp b/Common/Vulkan/VulkanContext.cpp index 3d91d00aab..ac601ccd30 100644 --- a/Common/Vulkan/VulkanContext.cpp +++ b/Common/Vulkan/VulkanContext.cpp @@ -1455,9 +1455,7 @@ void VulkanTexture::CreateDirect(int w, int h, int numMips, VkFormat format) { assert(res == VK_SUCCESS); vkGetImageMemoryRequirements(vulkan_->GetDevice(), image, &mem_reqs); - VkMemoryAllocateInfo mem_alloc = {}; - mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; - mem_alloc.pNext = NULL; + VkMemoryAllocateInfo mem_alloc = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO }; mem_alloc.memoryTypeIndex = 0; mem_alloc.allocationSize = mem_reqs.size; @@ -1498,13 +1496,13 @@ void VulkanTexture::CreateDirect(int w, int h, int numMips, VkFormat format) { assert(res == VK_SUCCESS); } -void VulkanTexture::UploadMip(int mip, VkBuffer buffer, size_t offset, size_t rowLength) { +void VulkanTexture::UploadMip(int mip, int mipWidth, int mipHeight, VkBuffer buffer, size_t offset, size_t rowLength) { VkBufferImageCopy copy_region = {}; copy_region.bufferOffset = offset; copy_region.bufferRowLength = (uint32_t)rowLength; - copy_region.bufferImageHeight = tex_height; - copy_region.imageExtent.width = tex_width; - copy_region.imageExtent.height = tex_height; + copy_region.bufferImageHeight = 0; // 2D + copy_region.imageExtent.width = mipWidth; + copy_region.imageExtent.height = mipHeight; copy_region.imageExtent.depth = 1; copy_region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; copy_region.imageSubresource.mipLevel = mip; diff --git a/Common/Vulkan/VulkanContext.h b/Common/Vulkan/VulkanContext.h index c60e305e8b..d4acf04953 100644 --- a/Common/Vulkan/VulkanContext.h +++ b/Common/Vulkan/VulkanContext.h @@ -347,7 +347,7 @@ class VulkanTexture { public: VulkanTexture(VulkanContext *vulkan) : vulkan_(vulkan), image(VK_NULL_HANDLE), mem(VK_NULL_HANDLE), view(VK_NULL_HANDLE), - tex_width(0), tex_height(0), format_(VK_FORMAT_UNDEFINED), + tex_width(0), tex_height(0), numMips_(1), format_(VK_FORMAT_UNDEFINED), mappableImage(VK_NULL_HANDLE), mappableMemory(VK_NULL_HANDLE), needStaging(false) { memset(&mem_reqs, 0, sizeof(mem_reqs)); } @@ -366,9 +366,9 @@ public: // Fast uploads from buffer. Mipmaps supported. void CreateDirect(int w, int h, int numMips, VkFormat format); - void UploadMip(int mip, VkBuffer buffer, size_t offset, size_t rowLength); // rowLength is in pixels + void UploadMip(int mip, int mipWidth, int mipHeight, VkBuffer buffer, size_t offset, size_t rowLength); // rowLength is in pixels void EndCreate(); - + int GetNumMips() const { return numMips_; } void Destroy(); VkImageView GetImageView() const { return view; } diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index c9a710a102..b19f921718 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -87,23 +87,28 @@ VkSampler SamplerCache::GetOrCreateSampler(const SamplerCacheKey &key) { return iter->second; } - VkSamplerCreateInfo samp = {}; - samp.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; - samp.pNext = nullptr; + VkSamplerCreateInfo samp = { VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO }; samp.addressModeU = key.sClamp ? VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE : VK_SAMPLER_ADDRESS_MODE_REPEAT; samp.addressModeV = key.tClamp ? VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE : VK_SAMPLER_ADDRESS_MODE_REPEAT; samp.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT; samp.borderColor = VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK; - samp.compareEnable = false; samp.compareOp = VK_COMPARE_OP_ALWAYS; samp.flags = 0; samp.magFilter = key.magFilt ? VK_FILTER_LINEAR : VK_FILTER_NEAREST; - samp.minFilter = key.minFilt ? VK_FILTER_LINEAR : VK_FILTER_NEAREST; // TODO: Aniso - samp.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; // key.4) ? ((key.magFilt & 2) ? VK_SAMPLER_MIPMAP_MODE_LINEAR : VK_SAMPLER_MIPMAP_MODE_NEAREST) : VK_SAMPLER_MIPMAP_MODE_BASE; + samp.minFilter = key.minFilt ? VK_FILTER_LINEAR : VK_FILTER_NEAREST; + samp.mipmapMode = key.mipFilt ? VK_SAMPLER_MIPMAP_MODE_LINEAR : VK_SAMPLER_MIPMAP_MODE_NEAREST; + + // TODO: Need to check for device support before enabling aniso + /* + if (g_Config.iAnisotropyLevel > 1) { + samp.maxAnisotropy = g_Config.iAnisotropyLevel; + samp.anisotropyEnable = true; + } + */ samp.maxAnisotropy = 1.0f; - samp.maxLod = 0.0f; // 1000.0f; + samp.anisotropyEnable = false; + samp.maxLod = key.maxLevel; samp.minLod = 0.0f; - samp.unnormalizedCoordinates = false; samp.mipLodBias = 0.0f; VkSampler sampler; @@ -604,6 +609,7 @@ void TextureCacheVulkan::UpdateSamplingParams(TexCacheEntry &entry, SamplerCache key.magFilt = magFilt & 1; key.sClamp = sClamp; key.tClamp = tClamp; + key.maxLevel = entry.vkTex->texture_->GetNumMips() - 1; /* if (entry.maxLevel != 0) { if (force || entry.lodBias != lodBias) { @@ -1390,10 +1396,13 @@ void TextureCacheVulkan::SetTexture(VulkanPushBuffer *uploadBuffer) { } // In addition, simply don't load more than level 0 if g_Config.bMipMap is false. - if (!g_Config.bMipMap) { + if (!g_Config.bMipMap || badMipSizes) { maxLevel = 0; } + // Disable mipmapping. Something is wrong. + // maxLevel = 0; + // If GLES3 is available, we can preallocate the storage, which makes texture loading more efficient. VkFormat dstFmt = GetDestFormat(format, gstate.getClutPaletteFormat()); @@ -1453,47 +1462,26 @@ void TextureCacheVulkan::SetTexture(VulkanPushBuffer *uploadBuffer) { entry->vkTex = new CachedTextureVulkan(); entry->vkTex->texture_ = new VulkanTexture(vulkan_); VulkanTexture *image = entry->vkTex->texture_; - image->CreateDirect(w, h, 1, dstFmt); + image->CreateDirect(w, h, maxLevel + 1, dstFmt); } lastBoundTexture = entry->vkTex; - // In Vulkan, fortunately, we have full control over mipmapping. - // For now, we only load the base texture. More to come. - // Upload the texture data. - int bpp = dstFmt == VULKAN_8888_FORMAT ? 4 : 2; - int stride = (w * bpp + 15) & ~15; - int size = stride * h; - size_t bufferOffset; - void *data = uploadBuffer->Push(size, &bufferOffset); - LoadTextureLevel(*entry, (uint8_t *)data, stride, 0, replaceImages, scaleFactor, dstFmt); - entry->vkTex->texture_->UploadMip(0, uploadBuffer->GetVkBuffer(), bufferOffset, stride / bpp); - - // Mipmapping only enable when texture scaling disable - /* - if (maxLevel > 0 && scaleFactor == 1) { - if (gstate_c.Supports(GPU_SUPPORTS_TEXTURE_LOD_CONTROL)) { - if (badMipSizes) { - // WARN_LOG(G3D, "Bad mipmap for texture sized %dx%dx%d - autogenerating", w, h, (int)format); - glGenerateMipmap(GL_TEXTURE_2D); - } else { - for (int i = 1; i <= maxLevel; i++) { - LoadTextureLevel(*entry, i, replaceImages, scaleFactor, dstFmt); - } - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, maxLevel); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_LOD, (float)maxLevel); - } - } else { - glGenerateMipmap(GL_TEXTURE_2D); - } - } else if (gstate_c.Supports(GPU_SUPPORTS_TEXTURE_LOD_CONTROL)) { - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0); + for (int i = 0; i <= maxLevel; i++) { + int mipWidth = gstate.getTextureWidth(i); + int mipHeight = gstate.getTextureHeight(i); + int bpp = dstFmt == VULKAN_8888_FORMAT ? 4 : 2; + int stride = (mipWidth * bpp + 15) & ~15; + int size = stride * mipHeight; + size_t bufferOffset; + void *data = uploadBuffer->Push(size, &bufferOffset); + LoadTextureLevel(*entry, (uint8_t *)data, stride, i, replaceImages, scaleFactor, dstFmt); + entry->vkTex->texture_->UploadMip(i, mipWidth, mipHeight, uploadBuffer->GetVkBuffer(), bufferOffset, stride / bpp); } - */ + gstate_c.textureFullAlpha = entry->GetAlphaStatus() == TexCacheEntry::STATUS_ALPHA_FULL; gstate_c.textureSimpleAlpha = entry->GetAlphaStatus() != TexCacheEntry::STATUS_ALPHA_UNKNOWN; - // TODO: Refactor away nextTexture_. Not needed on Vulkan. nextTexture_ = entry; } From e45c24b75f039b1599441d754f0e21a25687b55c Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Tue, 15 Mar 2016 00:50:36 +0100 Subject: [PATCH 093/116] Show how much pushbuffer space is used each frame. Optimizing this number (by avoiding redundant UBO uploads etc) will probably help performance. --- Common/Vulkan/VulkanContext.h | 4 ++++ Core/HLE/sceDisplay.cpp | 6 ++++-- GPU/GPU.h | 1 + GPU/Vulkan/DrawEngineVulkan.cpp | 2 +- 4 files changed, 10 insertions(+), 3 deletions(-) diff --git a/Common/Vulkan/VulkanContext.h b/Common/Vulkan/VulkanContext.h index d4acf04953..3a4982175b 100644 --- a/Common/Vulkan/VulkanContext.h +++ b/Common/Vulkan/VulkanContext.h @@ -484,6 +484,10 @@ public: return (uint32_t)off; } + size_t GetOffset() const { + return offset_; + } + // "Zero-copy" variant - you can write the data directly as you compute it. void *Push(size_t size, size_t *bindOffset) { size_t off = Allocate(size); diff --git a/Core/HLE/sceDisplay.cpp b/Core/HLE/sceDisplay.cpp index 878303a2f0..a364cddbf4 100644 --- a/Core/HLE/sceDisplay.cpp +++ b/Core/HLE/sceDisplay.cpp @@ -439,7 +439,8 @@ void __DisplayGetDebugStats(char stats[], size_t bufsize) { "Texture invalidations: %i\n" "Vertex shaders loaded: %i\n" "Fragment shaders loaded: %i\n" - "Combined shaders loaded: %i\n", + "Combined shaders loaded: %i\n" + "Pushbuffer space used: %i\n", gpuStats.numVBlanks, gpuStats.msProcessingDisplayLists * 1000.0f, kernelStats.msInSyscalls * 1000.0f, @@ -463,7 +464,8 @@ void __DisplayGetDebugStats(char stats[], size_t bufsize) { gpuStats.numTextureInvalidations, gpuStats.numVertexShaders, gpuStats.numFragmentShaders, - gpuStats.numShaders + gpuStats.numShaders, + gpuStats.pushSpaceUsed ); stats[bufsize - 1] = '\0'; gpuStats.ResetFrame(); diff --git a/GPU/GPU.h b/GPU/GPU.h index d036d3ebea..6eb2c88c84 100644 --- a/GPU/GPU.h +++ b/GPU/GPU.h @@ -89,6 +89,7 @@ struct GPUStatistics { int vertexGPUCycles; int otherGPUCycles; int gpuCommandsAtCallLevel[4]; + int pushSpaceUsed; // Total statistics, updated by the GPU core in UpdateStats int numVBlanks; diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index dd015a8d8d..3100bee0d9 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -194,11 +194,11 @@ void DrawEngineVulkan::BeginFrame() { vkResetDescriptorPool(vulkan_->GetDevice(), frame->descPool, 0); frame->descSets.clear(); frame->pushData->Begin(vulkan_->GetDevice()); - frame->pushData->Reset(); } void DrawEngineVulkan::EndFrame() { FrameData *frame = &frame_[curFrame_ & 1]; + gpuStats.pushSpaceUsed = frame->pushData->GetOffset(); frame->pushData->End(vulkan_->GetDevice()); curFrame_++; } From a995dd2ff4f0b441b77f3ae87e794725f20c59e6 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Thu, 17 Mar 2016 00:04:23 +0100 Subject: [PATCH 094/116] Get rid of strange offset in Vulkan matrix converter --- GPU/Common/GPUStateUtils.cpp | 42 ++++++++++++++++-------------- GPU/Common/VertexDecoderCommon.cpp | 2 +- GPU/GPUState.h | 1 + GPU/Vulkan/GPU_Vulkan.cpp | 1 + GPU/Vulkan/ShaderManagerVulkan.cpp | 13 +-------- 5 files changed, 26 insertions(+), 33 deletions(-) diff --git a/GPU/Common/GPUStateUtils.cpp b/GPU/Common/GPUStateUtils.cpp index 88d45eb6b1..54120aa7ec 100644 --- a/GPU/Common/GPUStateUtils.cpp +++ b/GPU/Common/GPUStateUtils.cpp @@ -640,31 +640,33 @@ void ConvertViewportAndScissor(bool useBufferedRendering, float renderWidth, flo float hScale = 1.0f; float yOffset = 0.0f; - // If we're within the bounds, we want clipping the viewport way. So leave it be. - if (left < 0.0f || right > renderWidth) { - float overageLeft = std::max(-left, 0.0f); - float overageRight = std::max(right - renderWidth, 0.0f); - // Our center drifted by the difference in overages. - float drift = overageRight - overageLeft; + if (!gstate_c.Supports(GPU_SUPPORTS_LARGE_VIEWPORTS)) { + // If we're within the bounds, we want clipping the viewport way. So leave it be. + if (left < 0.0f || right > renderWidth) { + float overageLeft = std::max(-left, 0.0f); + float overageRight = std::max(right - renderWidth, 0.0f); + // Our center drifted by the difference in overages. + float drift = overageRight - overageLeft; - left += overageLeft; - right -= overageRight; + left += overageLeft; + right -= overageRight; - wScale = vpWidth / (right - left); - xOffset = drift / (right - left); - } + wScale = vpWidth / (right - left); + xOffset = drift / (right - left); + } - if (top < 0.0f || bottom > renderHeight) { - float overageTop = std::max(-top, 0.0f); - float overageBottom = std::max(bottom - renderHeight, 0.0f); - // Our center drifted by the difference in overages. - float drift = overageBottom - overageTop; + if (top < 0.0f || bottom > renderHeight) { + float overageTop = std::max(-top, 0.0f); + float overageBottom = std::max(bottom - renderHeight, 0.0f); + // Our center drifted by the difference in overages. + float drift = overageBottom - overageTop; - top += overageTop; - bottom -= overageBottom; + top += overageTop; + bottom -= overageBottom; - hScale = vpHeight / (bottom - top); - yOffset = drift / (bottom - top); + hScale = vpHeight / (bottom - top); + yOffset = drift / (bottom - top); + } } out.viewportX = left + displayOffsetX; diff --git a/GPU/Common/VertexDecoderCommon.cpp b/GPU/Common/VertexDecoderCommon.cpp index 101e3295b0..9a3ec013b3 100644 --- a/GPU/Common/VertexDecoderCommon.cpp +++ b/GPU/Common/VertexDecoderCommon.cpp @@ -1118,7 +1118,7 @@ int VertexDecoder::ToString(char *output) const { if (tc) output += sprintf(output, "T: %s ", tcnames[tc]); if (weighttype) - output += sprintf(output, "W: %s (%ix)", weightnames[weighttype], nweights); + output += sprintf(output, "W: %s (%ix) ", weightnames[weighttype], nweights); if (idx) output += sprintf(output, "I: %s ", idxnames[idx]); if (morphcount > 1) diff --git a/GPU/GPUState.h b/GPU/GPUState.h index bd0c853095..16c4edf5a3 100644 --- a/GPU/GPUState.h +++ b/GPU/GPUState.h @@ -457,6 +457,7 @@ enum { GPU_SUPPORTS_LOGIC_OP = FLAG_BIT(5), GPU_USE_DEPTH_RANGE_HACK = FLAG_BIT(6), GPU_SUPPORTS_WIDE_LINES = FLAG_BIT(7), + GPU_SUPPORTS_LARGE_VIEWPORTS = FLAG_BIT(16), GPU_SUPPORTS_ACCURATE_DEPTH = FLAG_BIT(17), GPU_SUPPORTS_VAO = FLAG_BIT(18), GPU_SUPPORTS_ANY_COPY_IMAGE = FLAG_BIT(19), diff --git a/GPU/Vulkan/GPU_Vulkan.cpp b/GPU/Vulkan/GPU_Vulkan.cpp index f4982fc894..f29f47baae 100644 --- a/GPU/Vulkan/GPU_Vulkan.cpp +++ b/GPU/Vulkan/GPU_Vulkan.cpp @@ -477,6 +477,7 @@ void GPU_Vulkan::CheckGPUFeatures() { gstate_c.featureFlags |= GPU_SUPPORTS_BLEND_MINMAX; gstate_c.featureFlags |= GPU_SUPPORTS_ANY_COPY_IMAGE; gstate_c.featureFlags |= GPU_SUPPORTS_OES_TEXTURE_NPOT; + gstate_c.featureFlags |= GPU_SUPPORTS_LARGE_VIEWPORTS; } void GPU_Vulkan::BeginHostFrame() { diff --git a/GPU/Vulkan/ShaderManagerVulkan.cpp b/GPU/Vulkan/ShaderManagerVulkan.cpp index ee78c43901..c68ec22867 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.cpp +++ b/GPU/Vulkan/ShaderManagerVulkan.cpp @@ -151,18 +151,7 @@ std::string VulkanVertexShader::GetShaderString(DebugShaderStringType type) cons } static void ConvertProjMatrixToVulkan(Matrix4x4 &in, bool invertedX, bool invertedY) { - // Half pixel offset hack - float xoff = 0.5f / gstate_c.curRTRenderWidth; - xoff = gstate_c.vpXOffset + (invertedX ? xoff : -xoff); - float yoff = 0.5f / gstate_c.curRTRenderHeight; - yoff = gstate_c.vpYOffset + (invertedY ? yoff : -yoff); - - if (invertedX) - xoff = -xoff; - if (invertedY) - yoff = -yoff; - - const Vec3 trans(xoff, yoff, gstate_c.vpZOffset * 0.5f + 0.5f); + const Vec3 trans(0, 0, gstate_c.vpZOffset * 0.5f + 0.5f); const Vec3 scale(gstate_c.vpWidthScale, gstate_c.vpHeightScale, gstate_c.vpDepthScale * 0.5f); in.translateAndScale(trans, scale); } From f289e8485d8c066fe338e4f9da315e28814aa2b8 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Wed, 16 Mar 2016 21:59:37 -0700 Subject: [PATCH 095/116] Vulkan: Make sure depth==stencil when clearing. We have to clear both at the same time. I think it makes sense to consider this part of the "separate alpha" flag, since alpha has to match both color and depth. --- GPU/Common/SoftwareTransformCommon.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/GPU/Common/SoftwareTransformCommon.cpp b/GPU/Common/SoftwareTransformCommon.cpp index 1ba4bfc3de..669e4924d2 100644 --- a/GPU/Common/SoftwareTransformCommon.cpp +++ b/GPU/Common/SoftwareTransformCommon.cpp @@ -412,8 +412,10 @@ void SoftwareTransform( // Experiment: Disable on PowerVR (see issue #6290) // TODO: This bleeds outside the play area in non-buffered mode. Big deal? Probably not. if (maxIndex > 1 && gstate.isModeClear() && prim == GE_PRIM_RECTANGLES && IsReallyAClear(transformed, maxIndex) && gl_extensions.gpuVendor != GPU_VENDOR_POWERVR) { // && g_Config.iRenderingMode != FB_NON_BUFFERED_MODE) { - bool separateAlphaClear = gstate.isClearModeColorMask() != gstate.isClearModeAlphaMask(); - if (params->allowSeparateAlphaClear || !separateAlphaClear) { + // If alpha is not allowed to be separate, it must match for both depth/stencil and color. Vulkan requires this. + bool alphaMatchesColor = gstate.isClearModeColorMask() == gstate.isClearModeAlphaMask(); + bool depthMatchesStencil = gstate.isClearModeAlphaMask() == gstate.isClearModeDepthMask(); + if (params->allowSeparateAlphaClear || (alphaMatchesColor && depthMatchesStencil)) { result->color = transformed[1].color0_32; // Need to rescale from a [0, 1] float. This is the final transformed value. result->depth = ToScaledDepth((s16)(int)(transformed[1].z * 65535.0f)); From dad64b39b6ee64c02bfd093270f4d130676ae462 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Wed, 16 Mar 2016 22:01:15 -0700 Subject: [PATCH 096/116] Vulkan: Properly set the alpha test ref. It's definitely not a float, oops. --- GPU/Vulkan/DrawEngineVulkan.cpp | 2 +- GPU/Vulkan/ShaderManagerVulkan.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index 3100bee0d9..0f36f232a1 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -198,7 +198,7 @@ void DrawEngineVulkan::BeginFrame() { void DrawEngineVulkan::EndFrame() { FrameData *frame = &frame_[curFrame_ & 1]; - gpuStats.pushSpaceUsed = frame->pushData->GetOffset(); + gpuStats.pushSpaceUsed = (int)frame->pushData->GetOffset(); frame->pushData->End(vulkan_->GetDevice()); curFrame_++; } diff --git a/GPU/Vulkan/ShaderManagerVulkan.cpp b/GPU/Vulkan/ShaderManagerVulkan.cpp index c68ec22867..e5aa18906a 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.cpp +++ b/GPU/Vulkan/ShaderManagerVulkan.cpp @@ -193,7 +193,7 @@ void ShaderManagerVulkan::BaseUpdateUniforms(int dirtyUniforms) { Uint8x3ToFloat4(ub_base.texEnvColor, gstate.texenvcolor); } if (dirtyUniforms & DIRTY_ALPHACOLORREF) { - Uint8x3ToFloat4_Alpha(ub_base.alphaColorRef, gstate.getColorTestRef(), (float)gstate.getAlphaTestRef()); + Uint8x3ToFloat4_AlphaUint8(ub_base.alphaColorRef, gstate.getColorTestRef(), gstate.getAlphaTestRef()); } if (dirtyUniforms & DIRTY_ALPHACOLORMASK) { Uint8x3ToInt4(ub_base.colorTestMask, gstate.colortestmask); From baa7132a89586a42c8b78e46fa9eb7654c511368 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Wed, 16 Mar 2016 22:51:18 -0700 Subject: [PATCH 097/116] Vulkan: Simplify color testing. --- GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp | 7 ++----- GPU/Vulkan/ShaderManagerVulkan.cpp | 4 ++-- GPU/Vulkan/ShaderManagerVulkan.h | 4 ++-- ext/native/math/dataconv.h | 7 +++++++ 4 files changed, 13 insertions(+), 9 deletions(-) diff --git a/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp b/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp index 07adad893f..cf8a1aa513 100644 --- a/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp +++ b/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp @@ -268,7 +268,7 @@ bool GenerateVulkanGLSLFragmentShader(const ShaderID &id, char *buffer) { } else { const char *alphaTestFuncs[] = { "#", "#", " != ", " == ", " >= ", " > ", " <= ", " < " }; if (alphaTestFuncs[alphaTestFunc][0] != '#') { - WRITE(p, " if ((roundAndScaleTo255i(v.a) & base.alphacolormask.a) %s int(base.alphacolorref.a)) discard;\n", alphaTestFuncs[alphaTestFunc]); + WRITE(p, " if ((roundAndScaleTo255i(v.a) & base.alphacolormask.a) %s base.alphacolorref.a) discard;\n", alphaTestFuncs[alphaTestFunc]); } else { // This means NEVER. See above. WRITE(p, " discard;\n"); @@ -293,11 +293,8 @@ bool GenerateVulkanGLSLFragmentShader(const ShaderID &id, char *buffer) { } else { const char *colorTestFuncs[] = { "#", "#", " != ", " == " }; if (colorTestFuncs[colorTestFunc][0] != '#') { - // Apparently GLES3 does not support vector bitwise ops. WRITE(p, " ivec3 v_scaled = roundAndScaleTo255iv(v.rgb);\n"); - const char *maskedFragColor = "ivec3(v_scaled.r & base.alphacolormask.r, v_scaled.g & base.alphacolormask.g, v_scaled.b & base.alphacolormask.b)"; - const char *maskedColorRef = "ivec3(int(base.alphacolorref.r) & base.alphacolormask.r, int(base.alphacolorref.g) & base.alphacolormask.g, int(base.alphacolorref.b) & base.alphacolormask.b)"; - WRITE(p, " if (%s %s %s) discard;\n", maskedFragColor, colorTestFuncs[colorTestFunc], maskedColorRef); + WRITE(p, " if ((v_scaled & base.alphacolormask.rgb) %s (base.alphacolorref.rgb & base.alphacolormask.rgb)) discard;\n", colorTestFuncs[colorTestFunc]); } else { WRITE(p, " discard;\n"); } diff --git a/GPU/Vulkan/ShaderManagerVulkan.cpp b/GPU/Vulkan/ShaderManagerVulkan.cpp index e5aa18906a..6bdd619bee 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.cpp +++ b/GPU/Vulkan/ShaderManagerVulkan.cpp @@ -193,10 +193,10 @@ void ShaderManagerVulkan::BaseUpdateUniforms(int dirtyUniforms) { Uint8x3ToFloat4(ub_base.texEnvColor, gstate.texenvcolor); } if (dirtyUniforms & DIRTY_ALPHACOLORREF) { - Uint8x3ToFloat4_AlphaUint8(ub_base.alphaColorRef, gstate.getColorTestRef(), gstate.getAlphaTestRef()); + Uint8x3ToInt4_Alpha(ub_base.alphaColorRef, gstate.getColorTestRef(), gstate.getAlphaTestRef() & gstate.getAlphaTestMask()); } if (dirtyUniforms & DIRTY_ALPHACOLORMASK) { - Uint8x3ToInt4(ub_base.colorTestMask, gstate.colortestmask); + Uint8x3ToInt4_Alpha(ub_base.colorTestMask, gstate.getColorTestMask(), gstate.getAlphaTestMask()); } if (dirtyUniforms & DIRTY_FOGCOLOR) { Uint8x3ToFloat4(ub_base.fogColor, gstate.fogcolor); diff --git a/GPU/Vulkan/ShaderManagerVulkan.h b/GPU/Vulkan/ShaderManagerVulkan.h index d374862c41..bcdc0eaa64 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.h +++ b/GPU/Vulkan/ShaderManagerVulkan.h @@ -96,7 +96,7 @@ struct UB_VS_FS_Base { // Fragment data float fogColor[4]; float texEnvColor[4]; - float alphaColorRef[4]; + int alphaColorRef[4]; int colorTestMask[4]; float stencilReplace[4]; // only first float used float blendFixA[4]; @@ -117,7 +117,7 @@ R"( mat4 proj_mtx; vec4 matambientalpha; vec3 fogcolor; vec3 texenv; - vec4 alphacolorref; + ivec4 alphacolorref; ivec4 alphacolormask; float stencilReplaceValue; vec3 blendFixA; diff --git a/ext/native/math/dataconv.h b/ext/native/math/dataconv.h index d3d4beefa7..c2b540b003 100644 --- a/ext/native/math/dataconv.h +++ b/ext/native/math/dataconv.h @@ -29,6 +29,13 @@ inline void Uint8x3ToInt4(int i[4], uint32_t u) { i[3] = 0; } +inline void Uint8x3ToInt4_Alpha(int i[4], uint32_t u, uint8_t alpha) { + i[0] = ((u >> 0) & 0xFF); + i[1] = ((u >> 8) & 0xFF); + i[2] = ((u >> 16) & 0xFF); + i[3] = alpha; +} + inline void Uint8x3ToFloat4_Alpha(float f[4], uint32_t u, float alpha) { f[0] = ((u >> 0) & 0xFF) * (1.0f / 255.0f); f[1] = ((u >> 8) & 0xFF) * (1.0f / 255.0f); From 3744008d1fef08a7c666fcd36afbc5d0da348460 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Wed, 16 Mar 2016 23:32:48 -0700 Subject: [PATCH 098/116] Correct the 5551 format for now. Otherwise we get wrong colors - also we are still converting colors. --- GPU/Vulkan/TextureCacheVulkan.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index b19f921718..0cef7827de 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -68,7 +68,7 @@ // TODO: Except for color swizzle, exact matches are available. // So we can get rid of the conversion functions entirely. #define VULKAN_4444_FORMAT VK_FORMAT_R4G4B4A4_UNORM_PACK16 -#define VULKAN_1555_FORMAT VK_FORMAT_A1R5G5B5_UNORM_PACK16 // TODO: Switch to the one that matches the PSP better. +#define VULKAN_1555_FORMAT VK_FORMAT_R5G5B5A1_UNORM_PACK16 #define VULKAN_565_FORMAT VK_FORMAT_R5G6B5_UNORM_PACK16 #define VULKAN_8888_FORMAT VK_FORMAT_R8G8B8A8_UNORM From da5037032893deb8ce145cf218ddd68f1e627183 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Thu, 17 Mar 2016 11:56:43 +0100 Subject: [PATCH 099/116] Split out VulkanTexture from VulkanContext.cpp/h into VulkanImage.cpp/h --- Common/Common.vcxproj | 2 + Common/Common.vcxproj.filters | 6 + Common/Vulkan/VulkanContext.cpp | 378 +--------------------------- Common/Vulkan/VulkanContext.h | 80 +----- Common/Vulkan/VulkanImage.cpp | 356 ++++++++++++++++++++++++++ Common/Vulkan/VulkanImage.h | 50 ++++ GPU/Common/FramebufferCommon.h | 5 +- GPU/Common/VertexDecoderCommon.h | 3 +- GPU/GPU.vcxproj | 3 +- GPU/GPU.vcxproj.filters | 1 + GPU/Vulkan/FramebufferVulkan.cpp | 8 +- GPU/Vulkan/FramebufferVulkan.h | 6 +- GPU/Vulkan/ShaderManagerVulkan.h | 3 +- GPU/Vulkan/TextureCacheVulkan.cpp | 19 +- GPU/Vulkan/TextureCacheVulkan.h | 7 +- GPU/Vulkan/VulkanUtil.cpp | 45 ++++ GPU/Vulkan/VulkanUtil.h | 44 ++++ android/jni/Android.mk | 4 +- ext/native/thin3d/thin3d_vulkan.cpp | 2 + 19 files changed, 549 insertions(+), 473 deletions(-) create mode 100644 Common/Vulkan/VulkanImage.cpp create mode 100644 Common/Vulkan/VulkanImage.h create mode 100644 GPU/Vulkan/VulkanUtil.cpp diff --git a/Common/Common.vcxproj b/Common/Common.vcxproj index e11012bc8f..b8e484321f 100644 --- a/Common/Common.vcxproj +++ b/Common/Common.vcxproj @@ -242,6 +242,7 @@ + @@ -313,6 +314,7 @@ + diff --git a/Common/Common.vcxproj.filters b/Common/Common.vcxproj.filters index e5bc85c777..351cfd7608 100644 --- a/Common/Common.vcxproj.filters +++ b/Common/Common.vcxproj.filters @@ -67,6 +67,9 @@ Vulkan + + Vulkan + @@ -121,6 +124,9 @@ Vulkan + + Vulkan + diff --git a/Common/Vulkan/VulkanContext.cpp b/Common/Vulkan/VulkanContext.cpp index ac601ccd30..048f8f66ed 100644 --- a/Common/Vulkan/VulkanContext.cpp +++ b/Common/Vulkan/VulkanContext.cpp @@ -42,6 +42,8 @@ static const char *validationLayers[] = { */ }; +static VkBool32 CheckLayers(const std::vector &layer_props, const std::vector &layer_names); + VulkanContext::VulkanContext(const char *app_name, int app_ver, uint32_t flags) : device_(nullptr), gfx_queue_(VK_NULL_HANDLE), @@ -581,7 +583,7 @@ VkResult VulkanContext::InitDeviceLayerProperties() { * Return 1 (true) if all layer names specified in check_names * can be found in given layer properties. */ -VkBool32 CheckLayers(const std::vector &layer_props, const std::vector &layer_names) { +static VkBool32 CheckLayers(const std::vector &layer_props, const std::vector &layer_names) { uint32_t check_count = (uint32_t)layer_names.size(); uint32_t layer_count = (uint32_t)layer_props.size(); for (uint32_t i = 0; i < check_count; i++) { @@ -1188,361 +1190,6 @@ void VulkanContext::InitCommandPool() { assert(res == VK_SUCCESS); } -VkResult VulkanTexture::Create(int w, int h, VkFormat format) { - tex_width = w; - tex_height = h; - format_ = format; - - VkFormatProperties formatProps; - vkGetPhysicalDeviceFormatProperties(vulkan_->GetPhysicalDevice(), format, &formatProps); - - // See if we can use a linear tiled image for a texture, if not, we will need a staging image for the texture data. - // Linear tiling is usually only supported for 2D non-array textures. - // needStaging = (!(formatProps.linearTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)) ? true : false; - // Always stage. - needStaging = true; - - return VK_SUCCESS; -} - -void VulkanTexture::CreateMappableImage() { - // If we already have a mappableImage, forget it. - if (mappableImage) { - vulkan_->Delete().QueueDeleteImage(mappableImage); - mappableImage = VK_NULL_HANDLE; - } - if (mappableMemory) { - vulkan_->Delete().QueueDeleteDeviceMemory(mappableMemory); - mappableMemory = VK_NULL_HANDLE; - } - - bool U_ASSERT_ONLY pass; - - VkImageCreateInfo image_create_info = {}; - image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; - image_create_info.pNext = NULL; - image_create_info.imageType = VK_IMAGE_TYPE_2D; - image_create_info.format = format_; - image_create_info.extent.width = tex_width; - image_create_info.extent.height = tex_height; - image_create_info.extent.depth = 1; - image_create_info.mipLevels = 1; - image_create_info.arrayLayers = 1; - image_create_info.samples = VK_SAMPLE_COUNT_1_BIT; - image_create_info.tiling = VK_IMAGE_TILING_LINEAR; - image_create_info.usage = needStaging ? VK_IMAGE_USAGE_TRANSFER_SRC_BIT : VK_IMAGE_USAGE_SAMPLED_BIT; - image_create_info.queueFamilyIndexCount = 0; - image_create_info.pQueueFamilyIndices = NULL; - image_create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; - image_create_info.flags = 0; - image_create_info.initialLayout = VK_IMAGE_LAYOUT_PREINITIALIZED; - - VkMemoryAllocateInfo mem_alloc = {}; - mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; - mem_alloc.pNext = NULL; - mem_alloc.allocationSize = 0; - mem_alloc.memoryTypeIndex = 0; - - // Create a mappable image. It will be the texture if linear images are ok to be textures - // or it will be the staging image if they are not. - VkResult res = vkCreateImage(vulkan_->GetDevice(), &image_create_info, NULL, &mappableImage); - assert(res == VK_SUCCESS); - - vkGetImageMemoryRequirements(vulkan_->GetDevice(), mappableImage, &mem_reqs); - assert(res == VK_SUCCESS); - - mem_alloc.allocationSize = mem_reqs.size; - - // Find the memory type that is host mappable. - pass = vulkan_->MemoryTypeFromProperties(mem_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, &mem_alloc.memoryTypeIndex); - assert(pass); - - res = vkAllocateMemory(vulkan_->GetDevice(), &mem_alloc, NULL, &mappableMemory); - assert(res == VK_SUCCESS); - - res = vkBindImageMemory(vulkan_->GetDevice(), mappableImage, mappableMemory, 0); - assert(res == VK_SUCCESS); -} - -uint8_t *VulkanTexture::Lock(int level, int *rowPitch) { - CreateMappableImage(); - - VkImageSubresource subres = {}; - subres.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - subres.mipLevel = 0; - subres.arrayLayer = 0; - - VkSubresourceLayout layout; - void *data; - - // Get the subresource layout so we know what the row pitch is - vkGetImageSubresourceLayout(vulkan_->GetDevice(), mappableImage, &subres, &layout); - VkResult res = vkMapMemory(vulkan_->GetDevice(), mappableMemory, layout.offset, layout.size, 0, &data); - assert(res == VK_SUCCESS); - - *rowPitch = (int)layout.rowPitch; - return (uint8_t *)data; -} - -void VulkanTexture::Unlock() { - vkUnmapMemory(vulkan_->GetDevice(), mappableMemory); - - VkCommandBuffer cmd = vulkan_->GetInitCommandBuffer(); - - // if we already have an image, queue it for destruction and forget it. - Wipe(); - if (!needStaging) { - // If we can use the linear tiled image as a texture, just do it - image = mappableImage; - mem = mappableMemory; - TransitionImageLayout(cmd, image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_PREINITIALIZED, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); - // Make sure we don't accidentally delete the main image. - mappableImage = VK_NULL_HANDLE; - mappableMemory = VK_NULL_HANDLE; - } else { - VkImageCreateInfo image_create_info = {}; - image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; - image_create_info.pNext = NULL; - image_create_info.imageType = VK_IMAGE_TYPE_2D; - image_create_info.format = format_; - image_create_info.extent.width = tex_width; - image_create_info.extent.height = tex_height; - image_create_info.extent.depth = 1; - image_create_info.mipLevels = 1; - image_create_info.arrayLayers = 1; - image_create_info.samples = VK_SAMPLE_COUNT_1_BIT; - image_create_info.queueFamilyIndexCount = 0; - image_create_info.pQueueFamilyIndices = NULL; - image_create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; - image_create_info.flags = 0; - // The mappable image cannot be our texture, so create an optimally tiled image and blit to it - image_create_info.tiling = VK_IMAGE_TILING_OPTIMAL; - image_create_info.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; - image_create_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; - - VkResult res = vkCreateImage(vulkan_->GetDevice(), &image_create_info, NULL, &image); - assert(res == VK_SUCCESS); - - vkGetImageMemoryRequirements(vulkan_->GetDevice(), image, &mem_reqs); - - VkMemoryAllocateInfo mem_alloc = {}; - mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; - mem_alloc.pNext = NULL; - mem_alloc.memoryTypeIndex = 0; - mem_alloc.allocationSize = mem_reqs.size; - - // Find memory type - don't specify any mapping requirements - bool pass = vulkan_->MemoryTypeFromProperties(mem_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &mem_alloc.memoryTypeIndex); - assert(pass); - - res = vkAllocateMemory(vulkan_->GetDevice(), &mem_alloc, NULL, &mem); - assert(res == VK_SUCCESS); - - res = vkBindImageMemory(vulkan_->GetDevice(), image, mem, 0); - assert(res == VK_SUCCESS); - - // Since we're going to blit from the mappable image, set its layout to SOURCE_OPTIMAL - TransitionImageLayout(cmd, mappableImage, - VK_IMAGE_ASPECT_COLOR_BIT, - VK_IMAGE_LAYOUT_PREINITIALIZED, - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); - - TransitionImageLayout(cmd, image, - VK_IMAGE_ASPECT_COLOR_BIT, - VK_IMAGE_LAYOUT_UNDEFINED, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); - - VkImageCopy copy_region; - copy_region.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - copy_region.srcSubresource.mipLevel = 0; - copy_region.srcSubresource.baseArrayLayer = 0; - copy_region.srcSubresource.layerCount = 1; - copy_region.srcOffset.x = 0; - copy_region.srcOffset.y = 0; - copy_region.srcOffset.z = 0; - copy_region.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - copy_region.dstSubresource.mipLevel = 0; - copy_region.dstSubresource.baseArrayLayer = 0; - copy_region.dstSubresource.layerCount = 1; - copy_region.dstOffset.x = 0; - copy_region.dstOffset.y = 0; - copy_region.dstOffset.z = 0; - copy_region.extent.width = tex_width; - copy_region.extent.height = tex_height; - copy_region.extent.depth = 1; - - // Put the copy command into the command buffer - vkCmdCopyImage(cmd, - mappableImage, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - 1, ©_region); - - assert(res == VK_SUCCESS); - - // Set the layout for the texture image from DESTINATION_OPTIMAL to SHADER_READ_ONLY - TransitionImageLayout(cmd, image, - VK_IMAGE_ASPECT_COLOR_BIT, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); - - // Then drop the temporary mappable image - although should not be necessary... - vulkan_->Delete().QueueDeleteImage(mappableImage); - vulkan_->Delete().QueueDeleteDeviceMemory(mappableMemory); - - mappableImage = VK_NULL_HANDLE; - mappableMemory = VK_NULL_HANDLE; - } - - VkImageViewCreateInfo view_info = {}; - view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; - view_info.pNext = NULL; - view_info.image = VK_NULL_HANDLE; - view_info.viewType = VK_IMAGE_VIEW_TYPE_2D; - view_info.format = format_; - view_info.components.r = VK_COMPONENT_SWIZZLE_R; - view_info.components.g = VK_COMPONENT_SWIZZLE_G; - view_info.components.b = VK_COMPONENT_SWIZZLE_B; - view_info.components.a = VK_COMPONENT_SWIZZLE_A; - view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - view_info.subresourceRange.baseMipLevel = 0; - view_info.subresourceRange.levelCount = 1; - view_info.subresourceRange.baseArrayLayer = 0; - view_info.subresourceRange.layerCount = 1; - view_info.image = image; - VkResult res = vkCreateImageView(vulkan_->GetDevice(), &view_info, NULL, &view); - assert(res == VK_SUCCESS); -} - -void VulkanTexture::Wipe() { - if (image) { - vulkan_->Delete().QueueDeleteImage(image); - image = VK_NULL_HANDLE; - } - if (view) { - vulkan_->Delete().QueueDeleteImageView(view); - view = VK_NULL_HANDLE; - } - if (mem) { - vulkan_->Delete().QueueDeleteDeviceMemory(mem); - mem = VK_NULL_HANDLE; - } -} - -void VulkanTexture::CreateDirect(int w, int h, int numMips, VkFormat format) { - Wipe(); - - VkCommandBuffer cmd = vulkan_->GetInitCommandBuffer(); - - tex_width = w; - tex_height = h; - numMips_ = numMips; - format_ = format; - - VkImageCreateInfo image_create_info = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO }; - image_create_info.imageType = VK_IMAGE_TYPE_2D; - image_create_info.format = format_; - image_create_info.extent.width = tex_width; - image_create_info.extent.height = tex_height; - image_create_info.extent.depth = 1; - image_create_info.mipLevels = numMips; - image_create_info.arrayLayers = 1; - image_create_info.samples = VK_SAMPLE_COUNT_1_BIT; - image_create_info.flags = 0; - image_create_info.tiling = VK_IMAGE_TILING_OPTIMAL; - image_create_info.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; - image_create_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; - VkResult res = vkCreateImage(vulkan_->GetDevice(), &image_create_info, NULL, &image); - assert(res == VK_SUCCESS); - - vkGetImageMemoryRequirements(vulkan_->GetDevice(), image, &mem_reqs); - VkMemoryAllocateInfo mem_alloc = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO }; - mem_alloc.memoryTypeIndex = 0; - mem_alloc.allocationSize = mem_reqs.size; - - // Find memory type - don't specify any mapping requirements - bool pass = vulkan_->MemoryTypeFromProperties(mem_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &mem_alloc.memoryTypeIndex); - assert(pass); - - res = vkAllocateMemory(vulkan_->GetDevice(), &mem_alloc, NULL, &mem); - assert(res == VK_SUCCESS); - - res = vkBindImageMemory(vulkan_->GetDevice(), image, mem, 0); - assert(res == VK_SUCCESS); - - // Since we're going to blit to the target, set its layout to TRANSFER_DST - TransitionImageLayout(cmd, image, - VK_IMAGE_ASPECT_COLOR_BIT, - VK_IMAGE_LAYOUT_UNDEFINED, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); - - // Create the view while we're at it. - VkImageViewCreateInfo view_info = {}; - view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; - view_info.pNext = NULL; - view_info.image = VK_NULL_HANDLE; - view_info.viewType = VK_IMAGE_VIEW_TYPE_2D; - view_info.format = format_; - view_info.components.r = VK_COMPONENT_SWIZZLE_R; - view_info.components.g = VK_COMPONENT_SWIZZLE_G; - view_info.components.b = VK_COMPONENT_SWIZZLE_B; - view_info.components.a = VK_COMPONENT_SWIZZLE_A; - view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - view_info.subresourceRange.baseMipLevel = 0; - view_info.subresourceRange.levelCount = numMips; - view_info.subresourceRange.baseArrayLayer = 0; - view_info.subresourceRange.layerCount = 1; - view_info.image = image; - res = vkCreateImageView(vulkan_->GetDevice(), &view_info, NULL, &view); - assert(res == VK_SUCCESS); -} - -void VulkanTexture::UploadMip(int mip, int mipWidth, int mipHeight, VkBuffer buffer, size_t offset, size_t rowLength) { - VkBufferImageCopy copy_region = {}; - copy_region.bufferOffset = offset; - copy_region.bufferRowLength = (uint32_t)rowLength; - copy_region.bufferImageHeight = 0; // 2D - copy_region.imageExtent.width = mipWidth; - copy_region.imageExtent.height = mipHeight; - copy_region.imageExtent.depth = 1; - copy_region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - copy_region.imageSubresource.mipLevel = mip; - copy_region.imageSubresource.baseArrayLayer = 0; - copy_region.imageSubresource.layerCount = 1; - - VkCommandBuffer cmd = vulkan_->GetInitCommandBuffer(); - vkCmdCopyBufferToImage(cmd, buffer, image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©_region); -} - -void VulkanTexture::EndCreate() { - VkCommandBuffer cmd = vulkan_->GetInitCommandBuffer(); - TransitionImageLayout(cmd, image, - VK_IMAGE_ASPECT_COLOR_BIT, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); -} - -void VulkanTexture::Destroy() { - if (view) { - vulkan_->Delete().QueueDeleteImageView(view); - } - if (image) { - vulkan_->Delete().QueueDeleteImage(image); - if (mappableImage == image) { - mappableImage = VK_NULL_HANDLE; - } - } - if (mem) { - vulkan_->Delete().QueueDeleteDeviceMemory(mem); - if (mappableMemory == mem) { - mappableMemory = VK_NULL_HANDLE; - } - } - - view = VK_NULL_HANDLE; - image = VK_NULL_HANDLE; - mem = VK_NULL_HANDLE; -} - VkFence VulkanContext::CreateFence(bool presignalled) { VkFence fence; VkFenceCreateInfo fenceInfo; @@ -1889,22 +1536,3 @@ const char *VulkanResultToString(VkResult res) { void VulkanAssertImpl(VkResult check, const char *function, const char *file, int line) { const char *error = "(none)"; } - -void VulkanFramebuffer::Create(VulkanContext *vulkan, int w, int h, VkFormat format) { - -} -// void TransitionToImage() - -void VulkanFramebuffer::BeginPass(VkCommandBuffer cmd) { - -} -void VulkanFramebuffer::EndPass(VkCommandBuffer cmd) { - -} -void VulkanFramebuffer::TransitionToTexture(VkCommandBuffer cmd) { - -} - -VkImageView VulkanFramebuffer::GetColorImageView() { - return VK_NULL_HANDLE; -} diff --git a/Common/Vulkan/VulkanContext.h b/Common/Vulkan/VulkanContext.h index 3a4982175b..e6eda63762 100644 --- a/Common/Vulkan/VulkanContext.h +++ b/Common/Vulkan/VulkanContext.h @@ -340,71 +340,6 @@ private: std::vector cmdQueue_; }; -// Wrapper around what you need to use a texture. -// Not very optimal - if you have many small textures you should use other strategies. -// Only supports simple 2D textures for now. Mipmap support will be added later. -class VulkanTexture { -public: - VulkanTexture(VulkanContext *vulkan) - : vulkan_(vulkan), image(VK_NULL_HANDLE), mem(VK_NULL_HANDLE), view(VK_NULL_HANDLE), - tex_width(0), tex_height(0), numMips_(1), format_(VK_FORMAT_UNDEFINED), - mappableImage(VK_NULL_HANDLE), mappableMemory(VK_NULL_HANDLE), needStaging(false) { - memset(&mem_reqs, 0, sizeof(mem_reqs)); - } - ~VulkanTexture() { - Destroy(); - } - - // Simple usage - no cleverness, no mipmaps. - // Always call Create, Lock, Unlock. Unlock performs the upload if necessary. - // Can later Lock and Unlock again. This cannot change the format. Create cannot - // be called a second time without recreating the texture object until Destroy has - // been called. - VkResult Create(int w, int h, VkFormat format); - uint8_t *Lock(int level, int *rowPitch); - void Unlock(); - - // Fast uploads from buffer. Mipmaps supported. - void CreateDirect(int w, int h, int numMips, VkFormat format); - void UploadMip(int mip, int mipWidth, int mipHeight, VkBuffer buffer, size_t offset, size_t rowLength); // rowLength is in pixels - void EndCreate(); - int GetNumMips() const { return numMips_; } - void Destroy(); - - VkImageView GetImageView() const { return view; } - -private: - void CreateMappableImage(); - void Wipe(); - VulkanContext *vulkan_; - VkImage image; - VkDeviceMemory mem; - VkImageView view; - int32_t tex_width, tex_height, numMips_; - VkFormat format_; - VkImage mappableImage; - VkDeviceMemory mappableMemory; - VkMemoryRequirements mem_reqs; - bool needStaging; -}; - -// Placeholder - -class VulkanFramebuffer { -public: - void Create(VulkanContext *vulkan, int w, int h, VkFormat format); - - void BeginPass(VkCommandBuffer cmd); - void EndPass(VkCommandBuffer cmd); - void TransitionToTexture(VkCommandBuffer cmd); - - VkImageView GetColorImageView(); - -private: - VkImage image_; - VkFramebuffer framebuffer_; -}; - // Use these to push vertex, index and uniform data. Generally you'll have two of these // and alternate on each frame. // TODO: Make it possible to suballocate pushbuffers from a large DeviceMemory block. @@ -505,16 +440,8 @@ private: uint8_t *writePtr_; }; - -VkBool32 CheckLayers(const std::vector &layer_props, const std::vector &layer_names); - +// Stand-alone utility functions void VulkanBeginCommandBuffer(VkCommandBuffer cmd); - -void init_glslang(); -void finalize_glslang(); - -bool GLSLtoSPV(const VkShaderStageFlagBits shader_type, const char *pshader, std::vector &spirv, std::string *errorMessage = nullptr); - void TransitionImageLayout( VkCommandBuffer cmd, VkImage image, @@ -522,5 +449,10 @@ void TransitionImageLayout( VkImageLayout old_image_layout, VkImageLayout new_image_layout); +// GLSL compiler +void init_glslang(); +void finalize_glslang(); +bool GLSLtoSPV(const VkShaderStageFlagBits shader_type, const char *pshader, std::vector &spirv, std::string *errorMessage = nullptr); + #endif // UTIL_INIT diff --git a/Common/Vulkan/VulkanImage.cpp b/Common/Vulkan/VulkanImage.cpp new file mode 100644 index 0000000000..c2cd59e6c5 --- /dev/null +++ b/Common/Vulkan/VulkanImage.cpp @@ -0,0 +1,356 @@ +#include "Common/Vulkan/VulkanImage.h" + +VkResult VulkanTexture::Create(int w, int h, VkFormat format) { + tex_width = w; + tex_height = h; + format_ = format; + + VkFormatProperties formatProps; + vkGetPhysicalDeviceFormatProperties(vulkan_->GetPhysicalDevice(), format, &formatProps); + + // See if we can use a linear tiled image for a texture, if not, we will need a staging image for the texture data. + // Linear tiling is usually only supported for 2D non-array textures. + // needStaging = (!(formatProps.linearTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)) ? true : false; + // Always stage. + needStaging = true; + + return VK_SUCCESS; +} + +void VulkanTexture::CreateMappableImage() { + // If we already have a mappableImage, forget it. + if (mappableImage) { + vulkan_->Delete().QueueDeleteImage(mappableImage); + mappableImage = VK_NULL_HANDLE; + } + if (mappableMemory) { + vulkan_->Delete().QueueDeleteDeviceMemory(mappableMemory); + mappableMemory = VK_NULL_HANDLE; + } + + bool U_ASSERT_ONLY pass; + + VkImageCreateInfo image_create_info = {}; + image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; + image_create_info.pNext = NULL; + image_create_info.imageType = VK_IMAGE_TYPE_2D; + image_create_info.format = format_; + image_create_info.extent.width = tex_width; + image_create_info.extent.height = tex_height; + image_create_info.extent.depth = 1; + image_create_info.mipLevels = 1; + image_create_info.arrayLayers = 1; + image_create_info.samples = VK_SAMPLE_COUNT_1_BIT; + image_create_info.tiling = VK_IMAGE_TILING_LINEAR; + image_create_info.usage = needStaging ? VK_IMAGE_USAGE_TRANSFER_SRC_BIT : VK_IMAGE_USAGE_SAMPLED_BIT; + image_create_info.queueFamilyIndexCount = 0; + image_create_info.pQueueFamilyIndices = NULL; + image_create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + image_create_info.flags = 0; + image_create_info.initialLayout = VK_IMAGE_LAYOUT_PREINITIALIZED; + + VkMemoryAllocateInfo mem_alloc = {}; + mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + mem_alloc.pNext = NULL; + mem_alloc.allocationSize = 0; + mem_alloc.memoryTypeIndex = 0; + + // Create a mappable image. It will be the texture if linear images are ok to be textures + // or it will be the staging image if they are not. + VkResult res = vkCreateImage(vulkan_->GetDevice(), &image_create_info, NULL, &mappableImage); + assert(res == VK_SUCCESS); + + vkGetImageMemoryRequirements(vulkan_->GetDevice(), mappableImage, &mem_reqs); + assert(res == VK_SUCCESS); + + mem_alloc.allocationSize = mem_reqs.size; + + // Find the memory type that is host mappable. + pass = vulkan_->MemoryTypeFromProperties(mem_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, &mem_alloc.memoryTypeIndex); + assert(pass); + + res = vkAllocateMemory(vulkan_->GetDevice(), &mem_alloc, NULL, &mappableMemory); + assert(res == VK_SUCCESS); + + res = vkBindImageMemory(vulkan_->GetDevice(), mappableImage, mappableMemory, 0); + assert(res == VK_SUCCESS); +} + +uint8_t *VulkanTexture::Lock(int level, int *rowPitch) { + CreateMappableImage(); + + VkImageSubresource subres = {}; + subres.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + subres.mipLevel = 0; + subres.arrayLayer = 0; + + VkSubresourceLayout layout; + void *data; + + // Get the subresource layout so we know what the row pitch is + vkGetImageSubresourceLayout(vulkan_->GetDevice(), mappableImage, &subres, &layout); + VkResult res = vkMapMemory(vulkan_->GetDevice(), mappableMemory, layout.offset, layout.size, 0, &data); + assert(res == VK_SUCCESS); + + *rowPitch = (int)layout.rowPitch; + return (uint8_t *)data; +} + +void VulkanTexture::Unlock() { + vkUnmapMemory(vulkan_->GetDevice(), mappableMemory); + + VkCommandBuffer cmd = vulkan_->GetInitCommandBuffer(); + + // if we already have an image, queue it for destruction and forget it. + Wipe(); + if (!needStaging) { + // If we can use the linear tiled image as a texture, just do it + image = mappableImage; + mem = mappableMemory; + TransitionImageLayout(cmd, image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_PREINITIALIZED, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); + // Make sure we don't accidentally delete the main image. + mappableImage = VK_NULL_HANDLE; + mappableMemory = VK_NULL_HANDLE; + } else { + VkImageCreateInfo image_create_info = {}; + image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; + image_create_info.pNext = NULL; + image_create_info.imageType = VK_IMAGE_TYPE_2D; + image_create_info.format = format_; + image_create_info.extent.width = tex_width; + image_create_info.extent.height = tex_height; + image_create_info.extent.depth = 1; + image_create_info.mipLevels = 1; + image_create_info.arrayLayers = 1; + image_create_info.samples = VK_SAMPLE_COUNT_1_BIT; + image_create_info.queueFamilyIndexCount = 0; + image_create_info.pQueueFamilyIndices = NULL; + image_create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + image_create_info.flags = 0; + // The mappable image cannot be our texture, so create an optimally tiled image and blit to it + image_create_info.tiling = VK_IMAGE_TILING_OPTIMAL; + image_create_info.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; + image_create_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + + VkResult res = vkCreateImage(vulkan_->GetDevice(), &image_create_info, NULL, &image); + assert(res == VK_SUCCESS); + + vkGetImageMemoryRequirements(vulkan_->GetDevice(), image, &mem_reqs); + + VkMemoryAllocateInfo mem_alloc = {}; + mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + mem_alloc.pNext = NULL; + mem_alloc.memoryTypeIndex = 0; + mem_alloc.allocationSize = mem_reqs.size; + + // Find memory type - don't specify any mapping requirements + bool pass = vulkan_->MemoryTypeFromProperties(mem_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &mem_alloc.memoryTypeIndex); + assert(pass); + + res = vkAllocateMemory(vulkan_->GetDevice(), &mem_alloc, NULL, &mem); + assert(res == VK_SUCCESS); + + res = vkBindImageMemory(vulkan_->GetDevice(), image, mem, 0); + assert(res == VK_SUCCESS); + + // Since we're going to blit from the mappable image, set its layout to SOURCE_OPTIMAL + TransitionImageLayout(cmd, mappableImage, + VK_IMAGE_ASPECT_COLOR_BIT, + VK_IMAGE_LAYOUT_PREINITIALIZED, + VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); + + TransitionImageLayout(cmd, image, + VK_IMAGE_ASPECT_COLOR_BIT, + VK_IMAGE_LAYOUT_UNDEFINED, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); + + VkImageCopy copy_region; + copy_region.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + copy_region.srcSubresource.mipLevel = 0; + copy_region.srcSubresource.baseArrayLayer = 0; + copy_region.srcSubresource.layerCount = 1; + copy_region.srcOffset.x = 0; + copy_region.srcOffset.y = 0; + copy_region.srcOffset.z = 0; + copy_region.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + copy_region.dstSubresource.mipLevel = 0; + copy_region.dstSubresource.baseArrayLayer = 0; + copy_region.dstSubresource.layerCount = 1; + copy_region.dstOffset.x = 0; + copy_region.dstOffset.y = 0; + copy_region.dstOffset.z = 0; + copy_region.extent.width = tex_width; + copy_region.extent.height = tex_height; + copy_region.extent.depth = 1; + + // Put the copy command into the command buffer + vkCmdCopyImage(cmd, + mappableImage, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + 1, ©_region); + + assert(res == VK_SUCCESS); + + // Set the layout for the texture image from DESTINATION_OPTIMAL to SHADER_READ_ONLY + TransitionImageLayout(cmd, image, + VK_IMAGE_ASPECT_COLOR_BIT, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); + + // Then drop the temporary mappable image - although should not be necessary... + vulkan_->Delete().QueueDeleteImage(mappableImage); + vulkan_->Delete().QueueDeleteDeviceMemory(mappableMemory); + + mappableImage = VK_NULL_HANDLE; + mappableMemory = VK_NULL_HANDLE; + } + + VkImageViewCreateInfo view_info = {}; + view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + view_info.pNext = NULL; + view_info.image = VK_NULL_HANDLE; + view_info.viewType = VK_IMAGE_VIEW_TYPE_2D; + view_info.format = format_; + view_info.components.r = VK_COMPONENT_SWIZZLE_R; + view_info.components.g = VK_COMPONENT_SWIZZLE_G; + view_info.components.b = VK_COMPONENT_SWIZZLE_B; + view_info.components.a = VK_COMPONENT_SWIZZLE_A; + view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + view_info.subresourceRange.baseMipLevel = 0; + view_info.subresourceRange.levelCount = 1; + view_info.subresourceRange.baseArrayLayer = 0; + view_info.subresourceRange.layerCount = 1; + view_info.image = image; + VkResult res = vkCreateImageView(vulkan_->GetDevice(), &view_info, NULL, &view); + assert(res == VK_SUCCESS); +} + +void VulkanTexture::Wipe() { + if (image) { + vulkan_->Delete().QueueDeleteImage(image); + image = VK_NULL_HANDLE; + } + if (view) { + vulkan_->Delete().QueueDeleteImageView(view); + view = VK_NULL_HANDLE; + } + if (mem) { + vulkan_->Delete().QueueDeleteDeviceMemory(mem); + mem = VK_NULL_HANDLE; + } +} + +void VulkanTexture::CreateDirect(int w, int h, int numMips, VkFormat format, VkImageUsageFlags usage) { + Wipe(); + + VkCommandBuffer cmd = vulkan_->GetInitCommandBuffer(); + + tex_width = w; + tex_height = h; + numMips_ = numMips; + format_ = format; + + VkImageCreateInfo image_create_info = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO }; + image_create_info.imageType = VK_IMAGE_TYPE_2D; + image_create_info.format = format_; + image_create_info.extent.width = tex_width; + image_create_info.extent.height = tex_height; + image_create_info.extent.depth = 1; + image_create_info.mipLevels = numMips; + image_create_info.arrayLayers = 1; + image_create_info.samples = VK_SAMPLE_COUNT_1_BIT; + image_create_info.flags = 0; + image_create_info.tiling = VK_IMAGE_TILING_OPTIMAL; + image_create_info.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; + image_create_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + VkResult res = vkCreateImage(vulkan_->GetDevice(), &image_create_info, NULL, &image); + assert(res == VK_SUCCESS); + + vkGetImageMemoryRequirements(vulkan_->GetDevice(), image, &mem_reqs); + VkMemoryAllocateInfo mem_alloc = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO }; + mem_alloc.memoryTypeIndex = 0; + mem_alloc.allocationSize = mem_reqs.size; + + // Find memory type - don't specify any mapping requirements + bool pass = vulkan_->MemoryTypeFromProperties(mem_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &mem_alloc.memoryTypeIndex); + assert(pass); + + res = vkAllocateMemory(vulkan_->GetDevice(), &mem_alloc, NULL, &mem); + assert(res == VK_SUCCESS); + + res = vkBindImageMemory(vulkan_->GetDevice(), image, mem, 0); + assert(res == VK_SUCCESS); + + // Since we're going to blit to the target, set its layout to TRANSFER_DST + TransitionImageLayout(cmd, image, + VK_IMAGE_ASPECT_COLOR_BIT, + VK_IMAGE_LAYOUT_UNDEFINED, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); + + // Create the view while we're at it. + VkImageViewCreateInfo view_info = {}; + view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + view_info.pNext = NULL; + view_info.image = VK_NULL_HANDLE; + view_info.viewType = VK_IMAGE_VIEW_TYPE_2D; + view_info.format = format_; + view_info.components.r = VK_COMPONENT_SWIZZLE_R; + view_info.components.g = VK_COMPONENT_SWIZZLE_G; + view_info.components.b = VK_COMPONENT_SWIZZLE_B; + view_info.components.a = VK_COMPONENT_SWIZZLE_A; + view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + view_info.subresourceRange.baseMipLevel = 0; + view_info.subresourceRange.levelCount = numMips; + view_info.subresourceRange.baseArrayLayer = 0; + view_info.subresourceRange.layerCount = 1; + view_info.image = image; + res = vkCreateImageView(vulkan_->GetDevice(), &view_info, NULL, &view); + assert(res == VK_SUCCESS); +} + +void VulkanTexture::UploadMip(int mip, int mipWidth, int mipHeight, VkBuffer buffer, size_t offset, size_t rowLength) { + VkBufferImageCopy copy_region = {}; + copy_region.bufferOffset = offset; + copy_region.bufferRowLength = (uint32_t)rowLength; + copy_region.bufferImageHeight = 0; // 2D + copy_region.imageExtent.width = mipWidth; + copy_region.imageExtent.height = mipHeight; + copy_region.imageExtent.depth = 1; + copy_region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + copy_region.imageSubresource.mipLevel = mip; + copy_region.imageSubresource.baseArrayLayer = 0; + copy_region.imageSubresource.layerCount = 1; + + VkCommandBuffer cmd = vulkan_->GetInitCommandBuffer(); + vkCmdCopyBufferToImage(cmd, buffer, image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©_region); +} + +void VulkanTexture::EndCreate() { + VkCommandBuffer cmd = vulkan_->GetInitCommandBuffer(); + TransitionImageLayout(cmd, image, + VK_IMAGE_ASPECT_COLOR_BIT, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); +} + +void VulkanTexture::Destroy() { + if (view) { + vulkan_->Delete().QueueDeleteImageView(view); + } + if (image) { + vulkan_->Delete().QueueDeleteImage(image); + if (mappableImage == image) { + mappableImage = VK_NULL_HANDLE; + } + } + if (mem) { + vulkan_->Delete().QueueDeleteDeviceMemory(mem); + if (mappableMemory == mem) { + mappableMemory = VK_NULL_HANDLE; + } + } + + view = VK_NULL_HANDLE; + image = VK_NULL_HANDLE; + mem = VK_NULL_HANDLE; +} diff --git a/Common/Vulkan/VulkanImage.h b/Common/Vulkan/VulkanImage.h new file mode 100644 index 0000000000..482f52f98c --- /dev/null +++ b/Common/Vulkan/VulkanImage.h @@ -0,0 +1,50 @@ +#pragma once + +#include "Common/Vulkan/VulkanContext.h" + +// Wrapper around what you need to use a texture. +// Not very optimal - if you have many small textures you should use other strategies. +class VulkanTexture { +public: + VulkanTexture(VulkanContext *vulkan) + : vulkan_(vulkan), image(VK_NULL_HANDLE), mem(VK_NULL_HANDLE), view(VK_NULL_HANDLE), + tex_width(0), tex_height(0), numMips_(1), format_(VK_FORMAT_UNDEFINED), + mappableImage(VK_NULL_HANDLE), mappableMemory(VK_NULL_HANDLE), needStaging(false) { + memset(&mem_reqs, 0, sizeof(mem_reqs)); + } + ~VulkanTexture() { + Destroy(); + } + + // Simple usage - no cleverness, no mipmaps. + // Always call Create, Lock, Unlock. Unlock performs the upload if necessary. + // Can later Lock and Unlock again. This cannot change the format. Create cannot + // be called a second time without recreating the texture object until Destroy has + // been called. + VkResult Create(int w, int h, VkFormat format); + uint8_t *Lock(int level, int *rowPitch); + void Unlock(); + + // Fast uploads from buffer. Mipmaps supported. Usage must at least include VK_IMAGE_USAGE_TRANSFER_DST_BIT in order to use UploadMip. + void CreateDirect(int w, int h, int numMips, VkFormat format, VkImageUsageFlags usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT); + void UploadMip(int mip, int mipWidth, int mipHeight, VkBuffer buffer, size_t offset, size_t rowLength); // rowLength is in pixels + void EndCreate(); + int GetNumMips() const { return numMips_; } + void Destroy(); + + VkImageView GetImageView() const { return view; } + +private: + void CreateMappableImage(); + void Wipe(); + VulkanContext *vulkan_; + VkImage image; + VkDeviceMemory mem; + VkImageView view; + int32_t tex_width, tex_height, numMips_; + VkFormat format_; + VkImage mappableImage; + VkDeviceMemory mappableMemory; + VkMemoryRequirements mem_reqs; + bool needStaging; +}; diff --git a/GPU/Common/FramebufferCommon.h b/GPU/Common/FramebufferCommon.h index f9ebd1e3ad..4456e3461c 100644 --- a/GPU/Common/FramebufferCommon.h +++ b/GPU/Common/FramebufferCommon.h @@ -51,7 +51,7 @@ namespace DX9 { struct FBO_DX9; } -class VulkanFramebuffer; +class VulkanFBO; struct VirtualFramebuffer { int last_frame_used; @@ -87,12 +87,13 @@ struct VirtualFramebuffer { int lastFrameNewSize; GEBufferFormat format; // virtual, right now they are all RGBA8888 + // TODO: Handle fbo and colorDepth better. u8 colorDepth; union { FBO *fbo; DX9::FBO_DX9 *fbo_dx9; - VulkanFramebuffer *fbo_vk; + VulkanFBO *fbo_vk; }; u16 drawnWidth; diff --git a/GPU/Common/VertexDecoderCommon.h b/GPU/Common/VertexDecoderCommon.h index 69dbe4da53..14ed122bae 100644 --- a/GPU/Common/VertexDecoderCommon.h +++ b/GPU/Common/VertexDecoderCommon.h @@ -106,8 +106,7 @@ inline int RoundUp4(int x) { } // Reads decoded vertex formats in a convenient way. For software transform and debugging. -class VertexReader -{ +class VertexReader { public: VertexReader(u8 *base, const DecVtxFormat &decFmt, int vtype) : base_(base), data_(base), decFmt_(decFmt), vtype_(vtype) {} diff --git a/GPU/GPU.vcxproj b/GPU/GPU.vcxproj index 1f21022378..cfb441cc35 100644 --- a/GPU/GPU.vcxproj +++ b/GPU/GPU.vcxproj @@ -345,6 +345,7 @@ + @@ -354,4 +355,4 @@ - + \ No newline at end of file diff --git a/GPU/GPU.vcxproj.filters b/GPU/GPU.vcxproj.filters index 21183c6e72..7558d33b67 100644 --- a/GPU/GPU.vcxproj.filters +++ b/GPU/GPU.vcxproj.filters @@ -458,5 +458,6 @@ Vulkan + \ No newline at end of file diff --git a/GPU/Vulkan/FramebufferVulkan.cpp b/GPU/Vulkan/FramebufferVulkan.cpp index 14f17ba6a8..74c1c94ec0 100644 --- a/GPU/Vulkan/FramebufferVulkan.cpp +++ b/GPU/Vulkan/FramebufferVulkan.cpp @@ -41,10 +41,12 @@ #include "GPU/GPUInterface.h" #include "GPU/GPUState.h" +#include "Common/Vulkan/VulkanImage.h" #include "GPU/Vulkan/FramebufferVulkan.h" #include "GPU/Vulkan/DrawEngineVulkan.h" #include "GPU/Vulkan/TextureCacheVulkan.h" #include "GPU/Vulkan/ShaderManagerVulkan.h" +#include "GPU/Vulkan/VulkanUtil.h" #include "UI/OnScreenDisplay.h" @@ -599,7 +601,7 @@ void FramebufferManagerVulkan::ResizeFramebufFBO(VirtualFramebuffer *vfb, u16 w, return; } - vfb->fbo_vk = new VulkanFramebuffer(); + vfb->fbo_vk = new VulkanFBO(); // bo_create(vfb->renderWidth, vfb->renderHeight, 1, true, (FBOColorDepth)vfb->colorDepth); if (old.fbo_vk) { INFO_LOG(SCEGE, "Resizing FBO for %08x : %i x %i x %i", vfb->fb_address, w, h, vfb->format); @@ -777,7 +779,7 @@ void FramebufferManagerVulkan::BlitFramebufferDepth(VirtualFramebuffer *src, Vir }*/ } -VulkanFramebuffer *FramebufferManagerVulkan::GetTempFBO(u16 w, u16 h, VulkanFBOColorDepth depth) { +VulkanFBO *FramebufferManagerVulkan::GetTempFBO(u16 w, u16 h, VulkanFBOColorDepth depth) { u64 key = ((u64)depth << 32) | ((u32)w << 16) | h; auto it = tempFBOs_.find(key); if (it != tempFBOs_.end()) { @@ -787,7 +789,7 @@ VulkanFramebuffer *FramebufferManagerVulkan::GetTempFBO(u16 w, u16 h, VulkanFBOC textureCache_->ForgetLastTexture(); // FBO *fbo_vk = fbo_create(w, h, 1, false, depth); - VulkanFramebuffer *fbo_vk = new VulkanFramebuffer(); + VulkanFBO *fbo_vk = new VulkanFBO(); if (!fbo_vk) return nullptr; // fbo_bind_as_render_target(fbo_vk); diff --git a/GPU/Vulkan/FramebufferVulkan.h b/GPU/Vulkan/FramebufferVulkan.h index 510714458e..0b93fabef0 100644 --- a/GPU/Vulkan/FramebufferVulkan.h +++ b/GPU/Vulkan/FramebufferVulkan.h @@ -36,13 +36,13 @@ class DrawEngineVulkan; class VulkanContext; class ShaderManagerVulkan; class VulkanTexture; -class VulkanFramebuffer; struct PostShaderUniforms { float texelDelta[2]; float pad[2]; float pixelDelta[2]; float pad0[2]; float time[4]; }; + // Simple struct for asynchronous PBO readbacks // TODO: Probably will need a complete redesign. struct AsyncPBOVulkan { @@ -122,7 +122,7 @@ public: virtual void RebindFramebuffer() override; - VulkanFramebuffer *GetTempFBO(u16 w, u16 h, VulkanFBOColorDepth depth = VK_FBO_8888); + VulkanFBO *GetTempFBO(u16 w, u16 h, VulkanFBOColorDepth depth = VK_FBO_8888); // Cardboard Settings Calculator struct CardboardSettings * GetCardboardSettings(struct CardboardSettings * cardboardSettings); @@ -182,7 +182,7 @@ private: bool resized_; struct TempFBO { - VulkanFramebuffer *fbo_vk; + VulkanFBO *fbo_vk; int last_frame_used; }; diff --git a/GPU/Vulkan/ShaderManagerVulkan.h b/GPU/Vulkan/ShaderManagerVulkan.h index bcdc0eaa64..e6672b4fcc 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.h +++ b/GPU/Vulkan/ShaderManagerVulkan.h @@ -1,5 +1,4 @@ -#pragma once -// Copyright (c) 2012- PPSSPP Project. +// Copyright (c) 2016- PPSSPP Project. // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index 0cef7827de..655a12c05d 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -22,13 +22,16 @@ #include "i18n/i18n.h" #include "math/math_util.h" #include "profiler/profiler.h" -#include "Common/Vulkan/VulkanContext.h" #include "Common/ColorConv.h" #include "Core/Config.h" #include "Core/Host.h" #include "Core/MemMap.h" #include "Core/Reporting.h" #include "Core/System.h" + +#include "Common/Vulkan/VulkanContext.h" +#include "Common/Vulkan/VulkanImage.h" + #include "GPU/ge_constants.h" #include "GPU/GPUState.h" #include "GPU/Vulkan/TextureCacheVulkan.h" @@ -81,6 +84,10 @@ SamplerCache::~SamplerCache() { } } +CachedTextureVulkan::~CachedTextureVulkan() { + delete texture_; +} + VkSampler SamplerCache::GetOrCreateSampler(const SamplerCacheKey &key) { auto iter = cache_.find(key); if (iter != cache_.end()) { @@ -905,9 +912,9 @@ void TextureCacheVulkan::ApplyTextureFramebuffer(VkCommandBuffer cmd, TexCacheEn } if (depal) { // VulkanTexture *clutTexture = depalShaderCache_->GetClutTexture(clutFormat, clutHash_, clutBuf_); - VulkanFramebuffer *depalFBO = framebufferManager_->GetTempFBO(framebuffer->renderWidth, framebuffer->renderHeight, VK_FBO_8888); + VulkanFBO *depalFBO = framebufferManager_->GetTempFBO(framebuffer->renderWidth, framebuffer->renderHeight, VK_FBO_8888); - depalFBO->BeginPass(cmd); + //depalFBO->BeginPass(cmd); struct Pos { Pos(float x_, float y_, float z_) : x(x_), y(y_), z(z_) { @@ -1018,9 +1025,9 @@ void TextureCacheVulkan::ApplyTextureFramebuffer(VkCommandBuffer cmd, TexCacheEn glDisableVertexAttribArray(depal->a_position); glDisableVertexAttribArray(depal->a_texcoord0); */ - depalFBO->EndPass(cmd); - depalFBO->TransitionToTexture(cmd); - imageView = depalFBO->GetColorImageView(); + //depalFBO->EndPass(cmd); + //depalFBO->TransitionToTexture(cmd); + //imageView = depalFBO->GetColorImageView(); } /* diff --git a/GPU/Vulkan/TextureCacheVulkan.h b/GPU/Vulkan/TextureCacheVulkan.h index 0d732f480d..0d256ba3a9 100644 --- a/GPU/Vulkan/TextureCacheVulkan.h +++ b/GPU/Vulkan/TextureCacheVulkan.h @@ -33,7 +33,7 @@ class ShaderManagerVulkan; class DrawEngineVulkan; class VulkanContext; -class VulkanImage; +class VulkanTexture; struct SamplerCacheKey { SamplerCacheKey() : fullKey(0) {} @@ -61,9 +61,8 @@ class CachedTextureVulkan { public: CachedTextureVulkan() : texture_(nullptr) { } - ~CachedTextureVulkan() { - delete texture_; - } + ~CachedTextureVulkan(); + // TODO: Switch away from VulkanImage to some kind of smart suballocating texture pool. VulkanTexture *texture_; }; diff --git a/GPU/Vulkan/VulkanUtil.cpp b/GPU/Vulkan/VulkanUtil.cpp new file mode 100644 index 0000000000..a8a39ccdd9 --- /dev/null +++ b/GPU/Vulkan/VulkanUtil.cpp @@ -0,0 +1,45 @@ +// Copyright (c) 2016- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#include "GPU/Vulkan/VulkanUtil.h" + +VulkanFBO::VulkanFBO() : color_(nullptr), depthStencil_(nullptr) {} + +VulkanFBO::~VulkanFBO() { + delete color_; + delete depthStencil_; +} + +void VulkanFBO::Create(VulkanContext *vulkan, VkRenderPass rp_compatible, int width, int height, VkFormat color_Format) { + color_ = new VulkanTexture(vulkan); + VkImageCreateFlags flags = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT; + color_->CreateDirect(width, height, 1, VK_FORMAT_R8G8B8A8_UNORM, flags | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT); + depthStencil_->CreateDirect(width, height, 1, VK_FORMAT_D24_UNORM_S8_UINT, flags | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT); + + VkImageView views[2] = { color_->GetImageView(), depthStencil_->GetImageView() }; + + VkFramebufferCreateInfo fb = { VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO }; + fb.pAttachments = views; + fb.attachmentCount = 2; + fb.flags = 0; + fb.renderPass = rp_compatible; + fb.width = width; + fb.height = height; + fb.layers = 1; + + vkCreateFramebuffer(vulkan->GetDevice(), &fb, nullptr, &framebuffer_); +} diff --git a/GPU/Vulkan/VulkanUtil.h b/GPU/Vulkan/VulkanUtil.h index fe41a2b8e0..61a4160359 100644 --- a/GPU/Vulkan/VulkanUtil.h +++ b/GPU/Vulkan/VulkanUtil.h @@ -1,4 +1,48 @@ +// Copyright (c) 2016- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + #pragma once #include "Common/Vulkan/VulkanLoader.h" +#include "Common/Vulkan/VulkanImage.h" +// Vulkan doesn't really have the concept of an FBO that owns the images, +// but it does have the concept of a framebuffer as a set of attachments. +// VulkanFBO is an approximation of the FBO concept the other backends use +// to make things as similar as possible without being suboptimal. +// +class VulkanFBO { +public: + VulkanFBO(); + ~VulkanFBO(); + + // Depth-format is chosen automatically depending on hardware support. + // Color format will be 32-bit RGBA. + void Create(VulkanContext *vulkan, VkRenderPass rp_compatible, int width, int height, VkFormat colorFormat); + + VulkanTexture *GetColor() { return color_; } + VulkanTexture *GetDepthStencil() { return depthStencil_; } + + VkFramebuffer GetFramebuffer() { return framebuffer_; } + +private: + VulkanTexture *color_; + VulkanTexture *depthStencil_; + + // This point specifically to color and depth. + VkFramebuffer framebuffer_; +}; \ No newline at end of file diff --git a/android/jni/Android.mk b/android/jni/Android.mk index c752482e2d..45d2f9e0f7 100644 --- a/android/jni/Android.mk +++ b/android/jni/Android.mk @@ -127,6 +127,7 @@ EGL_FILES := \ VULKAN_FILES := \ $(SRC)/Common/Vulkan/VulkanLoader.cpp \ $(SRC)/Common/Vulkan/VulkanContext.cpp \ + $(SRC)/Common/Vulkan/VulkanImage.cpp \ $(SRC)/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp \ $(SRC)/GPU/Vulkan/DrawEngineVulkan.cpp \ $(SRC)/GPU/Vulkan/FramebufferVulkan.cpp \ @@ -137,7 +138,8 @@ VULKAN_FILES := \ $(SRC)/GPU/Vulkan/TextureCacheVulkan.cpp \ $(SRC)/GPU/Vulkan/TextureScalerVulkan.cpp \ $(SRC)/GPU/Vulkan/DepalettizeShaderVulkan.cpp \ - $(SRC)/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp + $(SRC)/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp \ + $(SRC)/GPU/Vulkan/VulkanUtil.cpp #endif EXEC_AND_LIB_FILES := \ diff --git a/ext/native/thin3d/thin3d_vulkan.cpp b/ext/native/thin3d/thin3d_vulkan.cpp index f547e58cb0..6a9585c538 100644 --- a/ext/native/thin3d/thin3d_vulkan.cpp +++ b/ext/native/thin3d/thin3d_vulkan.cpp @@ -30,7 +30,9 @@ #include "math/lin/matrix4x4.h" #include "math/dataconv.h" #include "thin3d/thin3d.h" + #include "Common/Vulkan/VulkanContext.h" +#include "Common/Vulkan/VulkanImage.h" // We use a simple descriptor set for all rendering: 1 sampler, 1 texture, 1 UBO binding point. // binding 0 - uniform data From 82f3df1e06e1a0b3819198cb2973b0805356b5d3 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Thu, 17 Mar 2016 21:59:16 -0700 Subject: [PATCH 100/116] Vulkan: Initial support for aniso filtering. --- Common/Vulkan/VulkanContext.cpp | 3 +++ GPU/GPUState.h | 1 + GPU/Vulkan/GPU_Vulkan.cpp | 3 +++ GPU/Vulkan/TextureCacheVulkan.cpp | 11 +++++------ 4 files changed, 12 insertions(+), 6 deletions(-) diff --git a/Common/Vulkan/VulkanContext.cpp b/Common/Vulkan/VulkanContext.cpp index 048f8f66ed..2643ae9ca7 100644 --- a/Common/Vulkan/VulkanContext.cpp +++ b/Common/Vulkan/VulkanContext.cpp @@ -664,6 +664,9 @@ VkResult VulkanContext::CreateDevice(int physical_device) { if (featuresAvailable_.depthBounds) { featuresEnabled_.depthBounds = true; } + if (featuresAvailable_.samplerAnisotropy) { + featuresEnabled_.samplerAnisotropy = true; + } VkDeviceCreateInfo device_info = {}; device_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; diff --git a/GPU/GPUState.h b/GPU/GPUState.h index 16c4edf5a3..5d4c3f006e 100644 --- a/GPU/GPUState.h +++ b/GPU/GPUState.h @@ -457,6 +457,7 @@ enum { GPU_SUPPORTS_LOGIC_OP = FLAG_BIT(5), GPU_USE_DEPTH_RANGE_HACK = FLAG_BIT(6), GPU_SUPPORTS_WIDE_LINES = FLAG_BIT(7), + GPU_SUPPORTS_ANISOTROPY = FLAG_BIT(8), GPU_SUPPORTS_LARGE_VIEWPORTS = FLAG_BIT(16), GPU_SUPPORTS_ACCURATE_DEPTH = FLAG_BIT(17), GPU_SUPPORTS_VAO = FLAG_BIT(18), diff --git a/GPU/Vulkan/GPU_Vulkan.cpp b/GPU/Vulkan/GPU_Vulkan.cpp index f29f47baae..808a94616e 100644 --- a/GPU/Vulkan/GPU_Vulkan.cpp +++ b/GPU/Vulkan/GPU_Vulkan.cpp @@ -471,6 +471,9 @@ void GPU_Vulkan::CheckGPUFeatures() { if (vulkan_->GetFeaturesEnabled().logicOp) { gstate_c.featureFlags |= GPU_SUPPORTS_LOGIC_OP; } + if (vulkan_->GetFeaturesEnabled().samplerAnisotropy) { + gstate_c.featureFlags |= GPU_SUPPORTS_ANISOTROPY; + } // Mandatory features on Vulkan, which may be checked in "centralized" code gstate_c.featureFlags |= GPU_SUPPORTS_TEXTURE_LOD_CONTROL; gstate_c.featureFlags |= GPU_SUPPORTS_FBO; diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index 655a12c05d..190b2d4de1 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -105,15 +105,14 @@ VkSampler SamplerCache::GetOrCreateSampler(const SamplerCacheKey &key) { samp.minFilter = key.minFilt ? VK_FILTER_LINEAR : VK_FILTER_NEAREST; samp.mipmapMode = key.mipFilt ? VK_SAMPLER_MIPMAP_MODE_LINEAR : VK_SAMPLER_MIPMAP_MODE_NEAREST; - // TODO: Need to check for device support before enabling aniso - /* - if (g_Config.iAnisotropyLevel > 1) { + if (gstate_c.Supports(GPU_SUPPORTS_ANISOTROPY) && g_Config.iAnisotropyLevel > 0) { samp.maxAnisotropy = g_Config.iAnisotropyLevel; samp.anisotropyEnable = true; + } else { + samp.maxAnisotropy = 1.0f; + samp.anisotropyEnable = false; } - */ - samp.maxAnisotropy = 1.0f; - samp.anisotropyEnable = false; + samp.maxLod = key.maxLevel; samp.minLod = 0.0f; samp.mipLodBias = 0.0f; From add506a0d381524076e47a7899a104d6b7645286 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Thu, 17 Mar 2016 21:56:04 -0700 Subject: [PATCH 101/116] Cleanup differences in aniso handling. Some places were not handling it as a power of two. --- Core/Config.cpp | 5 +++-- GPU/Directx9/GPU_DX9.cpp | 17 +++++++++++++++++ GPU/Directx9/TextureCacheDX9.cpp | 9 ++++++--- GPU/GLES/GLES_GPU.cpp | 2 ++ GPU/GLES/TextureCache.cpp | 8 +++++--- GPU/Vulkan/TextureCacheVulkan.cpp | 3 ++- headless/Headless.cpp | 2 +- 7 files changed, 36 insertions(+), 10 deletions(-) diff --git a/Core/Config.cpp b/Core/Config.cpp index 895d05a1b2..76ab8b3bc0 100644 --- a/Core/Config.cpp +++ b/Core/Config.cpp @@ -454,11 +454,11 @@ static ConfigSetting graphicsSettings[] = { #endif ReportedConfigSetting("ForceMaxEmulatedFPS", &g_Config.iForceMaxEmulatedFPS, 60, true, true), - // TODO: Hm, on fast mobile GPUs we should definitely default to at least 4... + // TODO: Hm, on fast mobile GPUs we should definitely default to at least 4 (setting = 2)... #ifdef MOBILE_DEVICE ConfigSetting("AnisotropyLevel", &g_Config.iAnisotropyLevel, 0, true, true), #else - ConfigSetting("AnisotropyLevel", &g_Config.iAnisotropyLevel, 8, true, true), + ConfigSetting("AnisotropyLevel", &g_Config.iAnisotropyLevel, 4, true, true), #endif ReportedConfigSetting("VertexCache", &g_Config.bVertexCache, true, true, true), ReportedConfigSetting("TextureBackoffCache", &g_Config.bTextureBackoffCache, false, true, true), @@ -862,6 +862,7 @@ void Config::Load(const char *iniFileName, const char *controllerIniFilename) { vPinnedPaths.push_back(it->second); } + // This caps the exponent 4 (so 16x.) if (iAnisotropyLevel > 4) { iAnisotropyLevel = 4; } diff --git a/GPU/Directx9/GPU_DX9.cpp b/GPU/Directx9/GPU_DX9.cpp index 3734b4c9df..7481c508d8 100644 --- a/GPU/Directx9/GPU_DX9.cpp +++ b/GPU/Directx9/GPU_DX9.cpp @@ -482,6 +482,23 @@ void DIRECTX9_GPU::CheckGPUFeatures() { features |= GPU_SUPPORTS_ACCURATE_DEPTH; features |= GPU_SUPPORTS_UNPACK_SUBIMAGE; + D3DCAPS9 caps; + ZeroMemory(&caps, sizeof(caps)); + HRESULT result = 0; + if (pD3DdeviceEx) { + result = pD3DdeviceEx->GetDeviceCaps(&caps); + } else { + result = pD3Ddevice->GetDeviceCaps(&caps); + } + if (FAILED(result)) { + WARN_LOG_REPORT(G3D, "Direct3D9: Failed to get the device caps!"); + } else { + if ((caps.RasterCaps & D3DPRASTERCAPS_ANISOTROPY) != 0 && caps.MaxAnisotropy > 1) + features |= GPU_SUPPORTS_ANISOTROPY; + if ((caps.TextureCaps & (D3DPTEXTURECAPS_NONPOW2CONDITIONAL | D3DPTEXTURECAPS_POW2)) == 0) + features |= GPU_SUPPORTS_OES_TEXTURE_NPOT; + } + if (!g_Config.bHighQualityDepth) { features |= GPU_SCALE_DEPTH_FROM_24BIT_TO_16BIT; } else if (PSP_CoreParameter().compat.flags().PixelDepthRounding) { diff --git a/GPU/Directx9/TextureCacheDX9.cpp b/GPU/Directx9/TextureCacheDX9.cpp index 17eabe5ecc..e772734e6d 100644 --- a/GPU/Directx9/TextureCacheDX9.cpp +++ b/GPU/Directx9/TextureCacheDX9.cpp @@ -603,7 +603,7 @@ void TextureCacheDX9::UpdateSamplingParams(TexCacheEntry &entry, bool force) { D3DTEXTUREFILTERTYPE mipf = (D3DTEXTUREFILTERTYPE)MipFilt[minFilt]; D3DTEXTUREFILTERTYPE magf = (D3DTEXTUREFILTERTYPE)MagFilt[magFilt]; - if (g_Config.iAnisotropyLevel > 0 && minf == D3DTEXF_LINEAR) { + if (gstate_c.Supports(GPU_SUPPORTS_ANISOTROPY) && g_Config.iAnisotropyLevel > 0 && minf == D3DTEXF_LINEAR) { minf = D3DTEXF_ANISOTROPIC; } @@ -653,8 +653,11 @@ void TextureCacheDX9::StartFrame() { Decimate(); } - DWORD anisotropyLevel = (DWORD)g_Config.iAnisotropyLevel > maxAnisotropyLevel ? maxAnisotropyLevel : g_Config.iAnisotropyLevel; - pD3Ddevice->SetSamplerState(0, D3DSAMP_MAXANISOTROPY, anisotropyLevel); + if (gstate_c.Supports(GPU_SUPPORTS_ANISOTROPY)) { + DWORD aniso = 1 << g_Config.iAnisotropyLevel; + DWORD anisotropyLevel = aniso > maxAnisotropyLevel ? maxAnisotropyLevel : aniso; + pD3Ddevice->SetSamplerState(0, D3DSAMP_MAXANISOTROPY, anisotropyLevel); + } } diff --git a/GPU/GLES/GLES_GPU.cpp b/GPU/GLES/GLES_GPU.cpp index 9efdeb0b8d..c6ee431456 100644 --- a/GPU/GLES/GLES_GPU.cpp +++ b/GPU/GLES/GLES_GPU.cpp @@ -565,6 +565,8 @@ void GLES_GPU::CheckGPUFeatures() { if (gl_extensions.GLES3 || !gl_extensions.IsGLES) features |= GPU_SUPPORTS_TEXTURE_LOD_CONTROL; + features |= GPU_SUPPORTS_ANISOTROPY; + // If we already have a 16-bit depth buffer, we don't need to round. if (fbo_standard_z_depth() > 16) { if (!g_Config.bHighQualityDepth && (features & GPU_SUPPORTS_ACCURATE_DEPTH) != 0) { diff --git a/GPU/GLES/TextureCache.cpp b/GPU/GLES/TextureCache.cpp index c799e02c85..5c096af52d 100644 --- a/GPU/GLES/TextureCache.cpp +++ b/GPU/GLES/TextureCache.cpp @@ -1485,9 +1485,11 @@ void TextureCache::SetTexture(bool force) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0); } - int aniso = 1 << g_Config.iAnisotropyLevel; - float anisotropyLevel = (float) aniso > maxAnisotropyLevel ? maxAnisotropyLevel : (float) aniso; - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, anisotropyLevel); + if (gstate_c.Supports(GPU_SUPPORTS_ANISOTROPY)) { + int aniso = 1 << g_Config.iAnisotropyLevel; + float anisotropyLevel = (float) aniso > maxAnisotropyLevel ? maxAnisotropyLevel : (float) aniso; + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, anisotropyLevel); + } gstate_c.textureFullAlpha = entry->GetAlphaStatus() == TexCacheEntry::STATUS_ALPHA_FULL; gstate_c.textureSimpleAlpha = entry->GetAlphaStatus() != TexCacheEntry::STATUS_ALPHA_UNKNOWN; diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index 190b2d4de1..dc34d05abf 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -106,7 +106,8 @@ VkSampler SamplerCache::GetOrCreateSampler(const SamplerCacheKey &key) { samp.mipmapMode = key.mipFilt ? VK_SAMPLER_MIPMAP_MODE_LINEAR : VK_SAMPLER_MIPMAP_MODE_NEAREST; if (gstate_c.Supports(GPU_SUPPORTS_ANISOTROPY) && g_Config.iAnisotropyLevel > 0) { - samp.maxAnisotropy = g_Config.iAnisotropyLevel; + // Docs say the min of this value and the supported max are used. + samp.maxAnisotropy = 1 << g_Config.iAnisotropyLevel; samp.anisotropyEnable = true; } else { samp.maxAnisotropy = 1.0f; diff --git a/headless/Headless.cpp b/headless/Headless.cpp index 630c1bd39b..a0a56ac585 100644 --- a/headless/Headless.cpp +++ b/headless/Headless.cpp @@ -337,7 +337,7 @@ int main(int argc, const char* argv[]) #ifdef USING_GLES2 g_Config.iAnisotropyLevel = 0; #else - g_Config.iAnisotropyLevel = 8; + g_Config.iAnisotropyLevel = 4; #endif g_Config.bVertexCache = true; g_Config.bTrueColor = true; From 966cb89d41657ec990c1c6d40170eb63b2afb835 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sat, 19 Mar 2016 01:57:13 +0100 Subject: [PATCH 102/116] Vulkan: Fix our use of dual source blending, re-enable if available. --- Common/Vulkan/VulkanContext.cpp | 2 +- GPU/Vulkan/StateMappingVulkan.cpp | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Common/Vulkan/VulkanContext.cpp b/Common/Vulkan/VulkanContext.cpp index 2643ae9ca7..f0d0de5107 100644 --- a/Common/Vulkan/VulkanContext.cpp +++ b/Common/Vulkan/VulkanContext.cpp @@ -644,7 +644,7 @@ VkResult VulkanContext::CreateDevice(int physical_device) { // Enable a few safe ones if they are available. if (featuresAvailable_.dualSrcBlend) { - // featuresEnabled_.dualSrcBlend = true; + featuresEnabled_.dualSrcBlend = true; } if (featuresAvailable_.largePoints) { featuresEnabled_.largePoints = true; diff --git a/GPU/Vulkan/StateMappingVulkan.cpp b/GPU/Vulkan/StateMappingVulkan.cpp index 488439999f..05f40f5dc0 100644 --- a/GPU/Vulkan/StateMappingVulkan.cpp +++ b/GPU/Vulkan/StateMappingVulkan.cpp @@ -48,8 +48,8 @@ static const VkBlendFactor vkBlendFactorLookup[(size_t)BlendFactor::COUNT] = { VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR, VK_BLEND_FACTOR_CONSTANT_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA, - VK_BLEND_FACTOR_SRC1_COLOR, - VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR, + VK_BLEND_FACTOR_SRC1_ALPHA, + VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA, VK_BLEND_FACTOR_MAX_ENUM, }; From f7113bb2e31dbf6b9faca1f0be7ab74b28cfa480 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sat, 19 Mar 2016 11:47:58 +0100 Subject: [PATCH 103/116] Use separate pushbuffers for UBO/Index/Vertex. This will make decoding directly into the pushbuffers easier, plus other benefits later. (For example, we'll often be able to avoid rebinding the vertex and index buffers at new offsets by just keep counting upwards between draws, if the vertex format is the same but other state changed) --- Core/HLE/sceDisplay.cpp | 6 ++-- GPU/GPU.h | 4 ++- GPU/Vulkan/DrawEngineVulkan.cpp | 61 +++++++++++++++++++-------------- GPU/Vulkan/DrawEngineVulkan.h | 4 ++- 4 files changed, 46 insertions(+), 29 deletions(-) diff --git a/Core/HLE/sceDisplay.cpp b/Core/HLE/sceDisplay.cpp index a364cddbf4..b1fdb606bf 100644 --- a/Core/HLE/sceDisplay.cpp +++ b/Core/HLE/sceDisplay.cpp @@ -440,7 +440,7 @@ void __DisplayGetDebugStats(char stats[], size_t bufsize) { "Vertex shaders loaded: %i\n" "Fragment shaders loaded: %i\n" "Combined shaders loaded: %i\n" - "Pushbuffer space used: %i\n", + "Pushbuffer space used: UBO %d, Vtx %d, Idx %d\n", gpuStats.numVBlanks, gpuStats.msProcessingDisplayLists * 1000.0f, kernelStats.msInSyscalls * 1000.0f, @@ -465,7 +465,9 @@ void __DisplayGetDebugStats(char stats[], size_t bufsize) { gpuStats.numVertexShaders, gpuStats.numFragmentShaders, gpuStats.numShaders, - gpuStats.pushSpaceUsed + gpuStats.pushUBOSpaceUsed, + gpuStats.pushVertexSpaceUsed, + gpuStats.pushIndexSpaceUsed ); stats[bufsize - 1] = '\0'; gpuStats.ResetFrame(); diff --git a/GPU/GPU.h b/GPU/GPU.h index 6eb2c88c84..55c5aaf566 100644 --- a/GPU/GPU.h +++ b/GPU/GPU.h @@ -89,7 +89,9 @@ struct GPUStatistics { int vertexGPUCycles; int otherGPUCycles; int gpuCommandsAtCallLevel[4]; - int pushSpaceUsed; + int pushUBOSpaceUsed; + int pushVertexSpaceUsed; + int pushIndexSpaceUsed; // Total statistics, updated by the GPU core in UpdateStats int numVBlanks; diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index 0f36f232a1..f756364f23 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -147,7 +147,9 @@ DrawEngineVulkan::DrawEngineVulkan(VulkanContext *vulkan) for (int i = 0; i < 2; i++) { VkResult res = vkCreateDescriptorPool(vulkan_->GetDevice(), &dp, nullptr, &frame_[i].descPool); assert(VK_SUCCESS == res); - frame_[i].pushData = new VulkanPushBuffer(vulkan_, 32 * 1024 * 1024); // TODO: Do something more dynamic + frame_[i].pushUBO = new VulkanPushBuffer(vulkan_, 16 * 1024 * 1024); // TODO: Do something more dynamic + frame_[i].pushVertex = new VulkanPushBuffer(vulkan_, 8 * 1024 * 1024); // TODO: Do something more dynamic + frame_[i].pushIndex = new VulkanPushBuffer(vulkan_, 2 * 1024 * 1024); // TODO: Do something more dynamic } VkPipelineLayoutCreateInfo pl; @@ -184,7 +186,9 @@ DrawEngineVulkan::~DrawEngineVulkan() { for (int i = 0; i < 2; i++) { vulkan_->Delete().QueueDeleteDescriptorPool(frame_[i].descPool); - delete frame_[i].pushData; + delete frame_[i].pushUBO; + delete frame_[i].pushVertex; + delete frame_[i].pushIndex; } vulkan_->Delete().QueueDeleteSampler(depalSampler_); } @@ -193,13 +197,19 @@ void DrawEngineVulkan::BeginFrame() { FrameData *frame = &frame_[curFrame_ & 1]; vkResetDescriptorPool(vulkan_->GetDevice(), frame->descPool, 0); frame->descSets.clear(); - frame->pushData->Begin(vulkan_->GetDevice()); + frame->pushUBO->Begin(vulkan_->GetDevice()); + frame->pushVertex->Begin(vulkan_->GetDevice()); + frame->pushIndex->Begin(vulkan_->GetDevice()); } void DrawEngineVulkan::EndFrame() { FrameData *frame = &frame_[curFrame_ & 1]; - gpuStats.pushSpaceUsed = (int)frame->pushData->GetOffset(); - frame->pushData->End(vulkan_->GetDevice()); + gpuStats.pushUBOSpaceUsed = (int)frame->pushUBO->GetOffset(); + gpuStats.pushVertexSpaceUsed = (int)frame->pushVertex->GetOffset(); + gpuStats.pushIndexSpaceUsed = (int)frame->pushIndex->GetOffset(); + frame->pushUBO->End(vulkan_->GetDevice()); + frame->pushVertex->End(vulkan_->GetDevice()); + frame->pushIndex->End(vulkan_->GetDevice()); curFrame_++; } @@ -243,7 +253,6 @@ void DrawEngineVulkan::SubmitPrim(void *verts, void *inds, GEPrimitiveType prim, SetupVertexDecoderInternal(vertType); *bytesRead = vertexCount * dec_->VertexSize(); - if ((vertexCount < 2 && prim > 0) || (vertexCount < 3 && prim > 2 && prim != GE_PRIM_RECTANGLES)) return; @@ -467,7 +476,7 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { // TODO: The descriptor set seems to be unbinding the texture when not specified. Cache it or the imageView instead? // TODO: Add this back when fixed: gstate_c.textureChanged != TEXCHANGE_UNCHANGED && if (!gstate.isModeClear() && gstate.isTextureMapEnabled()) { - textureCache_->SetTexture(frame->pushData); + textureCache_->SetTexture(frame->pushUBO); gstate_c.textureChanged = TEXCHANGE_UNCHANGED; if (gstate_c.needShaderTexClamp) { // We will rarely need to set this, so let's do it every time on use rather than in runloop. @@ -477,7 +486,7 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { textureCache_->ApplyTexture(imageView, sampler); } - VkDescriptorSet ds = GetDescriptorSet(imageView, sampler, frame->pushData->GetVkBuffer()); + VkDescriptorSet ds = GetDescriptorSet(imageView, sampler, frame->pushUBO->GetVkBuffer()); GEPrimitiveType prim = prevPrim_; @@ -540,34 +549,35 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { vkCmdBindPipeline(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline->pipeline); // TODO: Avoid if same as last draw. if (pipeline->uniformBlocks & UB_VS_FS_BASE) { - baseUBOOffset = shaderManager_->PushBaseBuffer(frame->pushData); + baseUBOOffset = shaderManager_->PushBaseBuffer(frame->pushUBO); } if (pipeline->uniformBlocks & UB_VS_LIGHTS) { - lightUBOOffset = shaderManager_->PushLightBuffer(frame->pushData); + lightUBOOffset = shaderManager_->PushLightBuffer(frame->pushUBO); } if (pipeline->uniformBlocks & UB_VS_BONES) { - boneUBOOffset = shaderManager_->PushBoneBuffer(frame->pushData); + boneUBOOffset = shaderManager_->PushBoneBuffer(frame->pushUBO); } - VkBuffer buf[1] = {frame->pushData->GetVkBuffer()}; + VkBuffer vbuf[1] = { frame->pushVertex->GetVkBuffer() }; + VkBuffer ibuf = { frame->pushIndex->GetVkBuffer() }; const uint32_t dynamicUBOOffsets[3] = { baseUBOOffset, lightUBOOffset, boneUBOOffset, }; vkCmdBindDescriptorSets(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout_, 0, 1, &ds, 3, dynamicUBOOffsets); int stride = dec_->GetDecVtxFmt().stride; - vbOffset = (uint32_t)frame->pushData->PushAligned(decoded, indexGen.MaxIndex() * stride, 16); + vbOffset = (uint32_t)frame->pushVertex->PushAligned(decoded, indexGen.MaxIndex() * stride, 16); VkDeviceSize offsets[1] = { vbOffset }; if (useElements) { - ibOffset = (uint32_t)frame->pushData->PushAligned(decIndex, 2 * indexGen.VertexCount(), 16); + ibOffset = (uint32_t)frame->pushIndex->PushAligned(decIndex, 2 * indexGen.VertexCount(), 16); // TODO: Avoid rebinding vertex/index buffers if the vertex size stays the same by using the offset arguments // Might want to separate vertices out into a different push buffer in that case. - vkCmdBindVertexBuffers(cmd_, 0, 1, buf, offsets); - vkCmdBindIndexBuffer(cmd_, buf[0], ibOffset, VK_INDEX_TYPE_UINT16); + vkCmdBindVertexBuffers(cmd_, 0, 1, vbuf, offsets); + vkCmdBindIndexBuffer(cmd_, ibuf, ibOffset, VK_INDEX_TYPE_UINT16); vkCmdDrawIndexed(cmd_, vertexCount, 1, 0, 0, 0); } else { - vkCmdBindVertexBuffers(cmd_, 0, 1, buf, offsets); + vkCmdBindVertexBuffers(cmd_, 0, 1, vbuf, offsets); vkCmdDraw(cmd_, vertexCount, 1, 0, 0); } } else { @@ -642,7 +652,7 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { vkCmdBindPipeline(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline->pipeline); // TODO: Avoid if same as last draw. if (pipeline->uniformBlocks & UB_VS_FS_BASE) { - baseUBOOffset = shaderManager_->PushBaseBuffer(frame->pushData); + baseUBOOffset = shaderManager_->PushBaseBuffer(frame->pushUBO); } const uint32_t dynamicUBOOffsets[3] = { @@ -650,21 +660,22 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { }; vkCmdBindDescriptorSets(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout_, 0, 1, &ds, 3, dynamicUBOOffsets); - VkBuffer buf[1] = { frame->pushData->GetVkBuffer() }; + VkBuffer vbuf[1] = { frame->pushVertex->GetVkBuffer() }; + VkBuffer ibuf = { frame->pushIndex->GetVkBuffer() }; if (drawIndexed) { - vbOffset = (uint32_t)frame->pushData->PushAligned(drawBuffer, maxIndex * sizeof(TransformedVertex), 16); - ibOffset = (uint32_t)frame->pushData->PushAligned(inds, sizeof(short) * numTrans, 16); + vbOffset = (uint32_t)frame->pushVertex->PushAligned(drawBuffer, maxIndex * sizeof(TransformedVertex), 16); + ibOffset = (uint32_t)frame->pushIndex->PushAligned(inds, sizeof(short) * numTrans, 16); VkDeviceSize offsets[1] = { vbOffset }; // TODO: Have a buffer per frame, use a walking buffer pointer // TODO: Avoid rebinding if the vertex size stays the same by using the offset arguments - vkCmdBindVertexBuffers(cmd_, 0, 1, buf, offsets); - vkCmdBindIndexBuffer(cmd_, buf[0], ibOffset, VK_INDEX_TYPE_UINT16); + vkCmdBindVertexBuffers(cmd_, 0, 1, vbuf, offsets); + vkCmdBindIndexBuffer(cmd_, ibuf, ibOffset, VK_INDEX_TYPE_UINT16); vkCmdDrawIndexed(cmd_, numTrans, 1, 0, 0, 0); } else { - vbOffset = (uint32_t)frame->pushData->PushAligned(drawBuffer, numTrans * sizeof(TransformedVertex), 16); + vbOffset = (uint32_t)frame->pushVertex->PushAligned(drawBuffer, numTrans * sizeof(TransformedVertex), 16); VkDeviceSize offsets[1] = { vbOffset }; // TODO: Avoid rebinding if the vertex size stays the same by using the offset arguments - vkCmdBindVertexBuffers(cmd_, 0, 1, buf, offsets); + vkCmdBindVertexBuffers(cmd_, 0, 1, vbuf, offsets); vkCmdDraw(cmd_, numTrans, 1, 0, 0); } } else if (result.action == SW_CLEAR) { diff --git a/GPU/Vulkan/DrawEngineVulkan.h b/GPU/Vulkan/DrawEngineVulkan.h index 0622b0d3fe..0e8339c1a1 100644 --- a/GPU/Vulkan/DrawEngineVulkan.h +++ b/GPU/Vulkan/DrawEngineVulkan.h @@ -181,7 +181,9 @@ private: // We alternate between these. struct FrameData { VkDescriptorPool descPool; - VulkanPushBuffer *pushData; + VulkanPushBuffer *pushUBO; + VulkanPushBuffer *pushVertex; + VulkanPushBuffer *pushIndex; // We do rolling allocation and reset instead of caching across frames. That we might do later. std::map descSets; }; From 5d56537a169b5f61c1bea7f2455de51d6ad46b78 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 20 Mar 2016 09:35:10 +0100 Subject: [PATCH 104/116] Move VulkanPushBuffer into VulkanMemory.h --- Common/Common.vcxproj | 2 + Common/Common.vcxproj.filters | 6 ++ Common/Vulkan/VulkanContext.h | 136 ++-------------------------- Common/Vulkan/VulkanMemory.cpp | 47 ++++++++++ Common/Vulkan/VulkanMemory.h | 93 +++++++++++++++++++ GPU/Vulkan/DrawEngineVulkan.cpp | 3 + GPU/Vulkan/ShaderManagerVulkan.cpp | 1 + GPU/Vulkan/TextureCacheVulkan.cpp | 1 + GPU/Vulkan/TextureCacheVulkan.h | 1 + android/jni/Android.mk | 1 + ext/native/thin3d/thin3d_vulkan.cpp | 1 + 11 files changed, 166 insertions(+), 126 deletions(-) create mode 100644 Common/Vulkan/VulkanMemory.cpp create mode 100644 Common/Vulkan/VulkanMemory.h diff --git a/Common/Common.vcxproj b/Common/Common.vcxproj index b8e484321f..2fb7c33a0b 100644 --- a/Common/Common.vcxproj +++ b/Common/Common.vcxproj @@ -244,6 +244,7 @@ + @@ -316,6 +317,7 @@ + diff --git a/Common/Common.vcxproj.filters b/Common/Common.vcxproj.filters index 351cfd7608..1dcbacabe5 100644 --- a/Common/Common.vcxproj.filters +++ b/Common/Common.vcxproj.filters @@ -70,6 +70,9 @@ Vulkan + + Vulkan + @@ -127,6 +130,9 @@ Vulkan + + Vulkan + diff --git a/Common/Vulkan/VulkanContext.h b/Common/Vulkan/VulkanContext.h index e6eda63762..8671f2c246 100644 --- a/Common/Vulkan/VulkanContext.h +++ b/Common/Vulkan/VulkanContext.h @@ -1,28 +1,3 @@ -/* - * Vulkan Samples Kit - * - * Copyright (C) 2015 Valve Corporation - * Copyright (C) 2015 Google, Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and associated documentation files (the "Software"), - * to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, - * and/or sell copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - */ - #ifndef UTIL_INIT #define UTIL_INIT @@ -52,7 +27,7 @@ #include "Common/Vulkan/VulkanLoader.h" - /* Amount of time, in nanoseconds, to wait for a command buffer to complete */ +// Amount of time, in nanoseconds, to wait for a command buffer to complete #define FENCE_TIMEOUT 10000000000 #if defined(NDEBUG) && defined(__GNUC__) @@ -88,6 +63,15 @@ public: void QueueDeletePipelineCache(VkPipelineCache pipelineCache) { pipelineCaches_.push_back(pipelineCache); } void Take(VulkanDeleteList &del) { + assert(descPools_.size() == 0); + assert(modules_.size() == 0); + assert(buffers_.size() == 0); + assert(bufferViews_.size() == 0); + assert(images_.size() == 0); + assert(imageViews_.size() == 0); + assert(deviceMemory_.size() == 0); + assert(samplers_.size() == 0); + assert(pipelineCaches_.size() == 0); descPools_ = std::move(del.descPools_); modules_ = std::move(del.modules_); buffers_ = std::move(del.buffers_); @@ -340,106 +324,6 @@ private: std::vector cmdQueue_; }; -// Use these to push vertex, index and uniform data. Generally you'll have two of these -// and alternate on each frame. -// TODO: Make it possible to suballocate pushbuffers from a large DeviceMemory block. -// We'll have two of these that we alternate between on each frame. -// TODO: Make this auto-grow and shrink. Need to be careful about returning and using the new -// buffer handle on overflow. -class VulkanPushBuffer { -public: - VulkanPushBuffer(VulkanContext *vulkan, size_t size) : offset_(0), size_(size), writePtr_(nullptr), deviceMemory_(0) { - VkDevice device = vulkan->GetDevice(); - - VkBufferCreateInfo b = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; - b.size = size; - b.flags = 0; - b.usage = VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT; - b.sharingMode = VK_SHARING_MODE_EXCLUSIVE; - b.queueFamilyIndexCount = 0; - b.pQueueFamilyIndices = nullptr; - VkResult res = vkCreateBuffer(device, &b, nullptr, &buffer_); - assert(VK_SUCCESS == res); - - // Okay, that's the buffer. Now let's allocate some memory for it. - VkMemoryAllocateInfo alloc = {}; - alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; - alloc.pNext = nullptr; - vulkan->MemoryTypeFromProperties(0xFFFFFFFF, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, &alloc.memoryTypeIndex); - alloc.allocationSize = size; - - res = vkAllocateMemory(device, &alloc, nullptr, &deviceMemory_); - assert(VK_SUCCESS == res); - res = vkBindBufferMemory(device, buffer_, deviceMemory_, 0); - assert(VK_SUCCESS == res); - } - - void Destroy(VulkanContext *vulkan) { - vulkan->Delete().QueueDeleteBuffer(buffer_); - vulkan->Delete().QueueDeleteDeviceMemory(deviceMemory_); - } - - void Reset() { offset_ = 0; } - - void Begin(VkDevice device) { - offset_ = 0; - VkResult res = vkMapMemory(device, deviceMemory_, 0, size_, 0, (void **)(&writePtr_)); - assert(VK_SUCCESS == res); - } - - void End(VkDevice device) { - vkUnmapMemory(device, deviceMemory_); - writePtr_ = nullptr; - } - - size_t Allocate(size_t numBytes) { - size_t out = offset_; - offset_ += (numBytes + 3) & ~3; // Round up to 4 bytes. - if (offset_ >= size_) { - // TODO: Allocate a second buffer, then combine them on the next frame. -#ifdef _WIN32 - DebugBreak(); -#endif - } - return out; - } - - // TODO: Add alignment support? - // Returns the offset that should be used when binding this buffer to get this data. - size_t Push(const void *data, size_t size) { - size_t off = Allocate(size); - memcpy(writePtr_ + off, data, size); - return off; - } - - uint32_t PushAligned(const void *data, size_t size, int align) { - offset_ = (offset_ + align - 1) & ~(align - 1); - size_t off = Allocate(size); - memcpy(writePtr_ + off, data, size); - return (uint32_t)off; - } - - size_t GetOffset() const { - return offset_; - } - - // "Zero-copy" variant - you can write the data directly as you compute it. - void *Push(size_t size, size_t *bindOffset) { - size_t off = Allocate(size); - *bindOffset = off; - return writePtr_ + off; - } - - VkBuffer GetVkBuffer() const { return buffer_; } - -private: - VkDeviceMemory deviceMemory_; - VkBuffer buffer_; - size_t offset_; - size_t size_; - uint8_t *writePtr_; -}; - // Stand-alone utility functions void VulkanBeginCommandBuffer(VkCommandBuffer cmd); void TransitionImageLayout( diff --git a/Common/Vulkan/VulkanMemory.cpp b/Common/Vulkan/VulkanMemory.cpp new file mode 100644 index 0000000000..2ffcc15ed8 --- /dev/null +++ b/Common/Vulkan/VulkanMemory.cpp @@ -0,0 +1,47 @@ +// Copyright (c) 2016- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +// Additionally, Common/Vulkan/* , including this file, are also licensed +// under the public domain. + +#include "Common/Vulkan/VulkanMemory.h" + +VulkanPushBuffer::VulkanPushBuffer(VulkanContext *vulkan, size_t size) : offset_(0), size_(size), writePtr_(nullptr), deviceMemory_(0) { + VkDevice device = vulkan->GetDevice(); + + VkBufferCreateInfo b = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; + b.size = size; + b.flags = 0; + b.usage = VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT; + b.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + b.queueFamilyIndexCount = 0; + b.pQueueFamilyIndices = nullptr; + VkResult res = vkCreateBuffer(device, &b, nullptr, &buffer_); + assert(VK_SUCCESS == res); + + // Okay, that's the buffer. Now let's allocate some memory for it. + VkMemoryAllocateInfo alloc = {}; + alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + alloc.pNext = nullptr; + vulkan->MemoryTypeFromProperties(0xFFFFFFFF, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, &alloc.memoryTypeIndex); + alloc.allocationSize = size; + + res = vkAllocateMemory(device, &alloc, nullptr, &deviceMemory_); + assert(VK_SUCCESS == res); + res = vkBindBufferMemory(device, buffer_, deviceMemory_, 0); + assert(VK_SUCCESS == res); +} diff --git a/Common/Vulkan/VulkanMemory.h b/Common/Vulkan/VulkanMemory.h new file mode 100644 index 0000000000..eb0ab011c0 --- /dev/null +++ b/Common/Vulkan/VulkanMemory.h @@ -0,0 +1,93 @@ +#pragma once + +#include "Common/Vulkan/VulkanContext.h" + +// VulkanMemory +// +// Vulkan memory management utils. + +// VulkanPushBuffer +// Simple incrementing allocator. +// Use these to push vertex, index and uniform data. Generally you'll have two of these +// and alternate on each frame. Make sure not to reset until the fence from the last time you used it +// has completed. +// +// TODO: Make it possible to suballocate pushbuffers from a large DeviceMemory block. +// TODO: Make this auto-grow and shrink. Need to be careful about returning and using the new +// buffer handle on overflow. +class VulkanPushBuffer { +public: + VulkanPushBuffer(VulkanContext *vulkan, size_t size); + + ~VulkanPushBuffer() { + assert(buffer_ == VK_NULL_HANDLE); + assert(deviceMemory_ == VK_NULL_HANDLE); + } + + void Destroy(VulkanContext *vulkan) { + vulkan->Delete().QueueDeleteBuffer(buffer_); + vulkan->Delete().QueueDeleteDeviceMemory(deviceMemory_); + buffer_ = VK_NULL_HANDLE; + deviceMemory_ = VK_NULL_HANDLE; + } + + void Reset() { offset_ = 0; } + + void Begin(VkDevice device) { + offset_ = 0; + VkResult res = vkMapMemory(device, deviceMemory_, 0, size_, 0, (void **)(&writePtr_)); + assert(VK_SUCCESS == res); + } + + void End(VkDevice device) { + vkUnmapMemory(device, deviceMemory_); + writePtr_ = nullptr; + } + + size_t Allocate(size_t numBytes) { + size_t out = offset_; + offset_ += (numBytes + 3) & ~3; // Round up to 4 bytes. + if (offset_ >= size_) { + // TODO: Allocate a second buffer, then combine them on the next frame. +#ifdef _WIN32 + DebugBreak(); +#endif + } + return out; + } + + // TODO: Add alignment support? + // Returns the offset that should be used when binding this buffer to get this data. + size_t Push(const void *data, size_t size) { + size_t off = Allocate(size); + memcpy(writePtr_ + off, data, size); + return off; + } + + uint32_t PushAligned(const void *data, size_t size, int align) { + offset_ = (offset_ + align - 1) & ~(align - 1); + size_t off = Allocate(size); + memcpy(writePtr_ + off, data, size); + return (uint32_t)off; + } + + size_t GetOffset() const { + return offset_; + } + + // "Zero-copy" variant - you can write the data directly as you compute it. + void *Push(size_t size, size_t *bindOffset) { + size_t off = Allocate(size); + *bindOffset = off; + return writePtr_ + off; + } + + VkBuffer GetVkBuffer() const { return buffer_; } + +private: + VkDeviceMemory deviceMemory_; + VkBuffer buffer_; + size_t offset_; + size_t size_; + uint8_t *writePtr_; +}; diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index f756364f23..673fdb4f51 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -33,6 +33,9 @@ #include "GPU/GPUState.h" #include "GPU/ge_constants.h" +#include "Common/Vulkan/VulkanContext.h" +#include "Common/Vulkan/VulkanMemory.h" + #include "GPU/Common/TextureDecoder.h" #include "GPU/Common/SplineCommon.h" #include "GPU/Common/TransformCommon.h" diff --git a/GPU/Vulkan/ShaderManagerVulkan.cpp b/GPU/Vulkan/ShaderManagerVulkan.cpp index 6bdd619bee..13972b6c92 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.cpp +++ b/GPU/Vulkan/ShaderManagerVulkan.cpp @@ -27,6 +27,7 @@ #include "math/dataconv.h" #include "util/text/utf8.h" #include "Common/Vulkan/VulkanContext.h" +#include "Common/Vulkan/VulkanMemory.h" #include "Common/Common.h" #include "Core/Config.h" #include "Core/Reporting.h" diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index dc34d05abf..4d5eb0003e 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -31,6 +31,7 @@ #include "Common/Vulkan/VulkanContext.h" #include "Common/Vulkan/VulkanImage.h" +#include "Common/Vulkan/VulkanMemory.h" #include "GPU/ge_constants.h" #include "GPU/GPUState.h" diff --git a/GPU/Vulkan/TextureCacheVulkan.h b/GPU/Vulkan/TextureCacheVulkan.h index 0d256ba3a9..8a4998aa32 100644 --- a/GPU/Vulkan/TextureCacheVulkan.h +++ b/GPU/Vulkan/TextureCacheVulkan.h @@ -34,6 +34,7 @@ class DrawEngineVulkan; class VulkanContext; class VulkanTexture; +class VulkanPushBuffer; struct SamplerCacheKey { SamplerCacheKey() : fullKey(0) {} diff --git a/android/jni/Android.mk b/android/jni/Android.mk index 45d2f9e0f7..3e8e1ddc40 100644 --- a/android/jni/Android.mk +++ b/android/jni/Android.mk @@ -128,6 +128,7 @@ VULKAN_FILES := \ $(SRC)/Common/Vulkan/VulkanLoader.cpp \ $(SRC)/Common/Vulkan/VulkanContext.cpp \ $(SRC)/Common/Vulkan/VulkanImage.cpp \ + $(SRC)/Common/Vulkan/VulkanMemory.cpp \ $(SRC)/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp \ $(SRC)/GPU/Vulkan/DrawEngineVulkan.cpp \ $(SRC)/GPU/Vulkan/FramebufferVulkan.cpp \ diff --git a/ext/native/thin3d/thin3d_vulkan.cpp b/ext/native/thin3d/thin3d_vulkan.cpp index 6a9585c538..9d1397a787 100644 --- a/ext/native/thin3d/thin3d_vulkan.cpp +++ b/ext/native/thin3d/thin3d_vulkan.cpp @@ -33,6 +33,7 @@ #include "Common/Vulkan/VulkanContext.h" #include "Common/Vulkan/VulkanImage.h" +#include "Common/Vulkan/VulkanMemory.h" // We use a simple descriptor set for all rendering: 1 sampler, 1 texture, 1 UBO binding point. // binding 0 - uniform data From 2c61b1e763b8da2bf56495c8532cf9cc8b1f2f59 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 20 Mar 2016 09:52:13 +0100 Subject: [PATCH 105/116] Change the VulkanPushBuffer API to allow for adding support for dynamic growth --- Common/Vulkan/VulkanMemory.h | 19 +++++---- GPU/Vulkan/DrawEngineVulkan.cpp | 66 ++++++++++++++++++----------- GPU/Vulkan/DrawEngineVulkan.h | 8 ++-- GPU/Vulkan/ShaderManagerVulkan.cpp | 12 +++--- GPU/Vulkan/ShaderManagerVulkan.h | 6 +-- GPU/Vulkan/TextureCacheVulkan.cpp | 5 ++- UI/EmuScreen.cpp | 2 +- ext/native/thin3d/thin3d_vulkan.cpp | 50 ++++++++++++---------- 8 files changed, 98 insertions(+), 70 deletions(-) diff --git a/Common/Vulkan/VulkanMemory.h b/Common/Vulkan/VulkanMemory.h index eb0ab011c0..f8855bf762 100644 --- a/Common/Vulkan/VulkanMemory.h +++ b/Common/Vulkan/VulkanMemory.h @@ -44,7 +44,9 @@ public: writePtr_ = nullptr; } - size_t Allocate(size_t numBytes) { + // When using the returned memory, make sure to bind the returned vkbuf. + // This will later allow for handling overflow correctly. + size_t Allocate(size_t numBytes, VkBuffer *vkbuf) { size_t out = offset_; offset_ += (numBytes + 3) & ~3; // Round up to 4 bytes. if (offset_ >= size_) { @@ -53,20 +55,21 @@ public: DebugBreak(); #endif } + *vkbuf = buffer_; return out; } // TODO: Add alignment support? // Returns the offset that should be used when binding this buffer to get this data. - size_t Push(const void *data, size_t size) { - size_t off = Allocate(size); + size_t Push(const void *data, size_t size, VkBuffer *vkbuf) { + size_t off = Allocate(size, vkbuf); memcpy(writePtr_ + off, data, size); return off; } - uint32_t PushAligned(const void *data, size_t size, int align) { + uint32_t PushAligned(const void *data, size_t size, int align, VkBuffer *vkbuf) { offset_ = (offset_ + align - 1) & ~(align - 1); - size_t off = Allocate(size); + size_t off = Allocate(size, vkbuf); memcpy(writePtr_ + off, data, size); return (uint32_t)off; } @@ -76,14 +79,12 @@ public: } // "Zero-copy" variant - you can write the data directly as you compute it. - void *Push(size_t size, size_t *bindOffset) { - size_t off = Allocate(size); + void *Push(size_t size, size_t *bindOffset, VkBuffer *vkbuf) { + size_t off = Allocate(size, vkbuf); *bindOffset = off; return writePtr_ + off; } - VkBuffer GetVkBuffer() const { return buffer_; } - private: VkDeviceMemory deviceMemory_; VkBuffer buffer_; diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index 673fdb4f51..ff0036eb86 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -189,6 +189,9 @@ DrawEngineVulkan::~DrawEngineVulkan() { for (int i = 0; i < 2; i++) { vulkan_->Delete().QueueDeleteDescriptorPool(frame_[i].descPool); + frame_[i].pushUBO->Destroy(vulkan_); + frame_[i].pushVertex->Destroy(vulkan_); + frame_[i].pushIndex->Destroy(vulkan_); delete frame_[i].pushUBO; delete frame_[i].pushVertex; delete frame_[i].pushIndex; @@ -200,6 +203,15 @@ void DrawEngineVulkan::BeginFrame() { FrameData *frame = &frame_[curFrame_ & 1]; vkResetDescriptorPool(vulkan_->GetDevice(), frame->descPool, 0); frame->descSets.clear(); + + // First reset all buffers, then begin. This is so that Reset can free memory and Begin can allocate it, + // if growing the buffer is needed. Doing it this way will reduce fragmentation if more than one buffer + // needs to grow in the same frame. The state where many buffers are reset can also be used to + // defragment memory. + frame->pushUBO->Reset(); + frame->pushVertex->Reset(); + frame->pushIndex->Reset(); + frame->pushUBO->Begin(vulkan_->GetDevice()); frame->pushVertex->Begin(vulkan_->GetDevice()); frame->pushIndex->Begin(vulkan_->GetDevice()); @@ -387,12 +399,14 @@ inline u32 ComputeMiniHashRange(const void *ptr, size_t sz) { } } -VkDescriptorSet DrawEngineVulkan::GetDescriptorSet(VkImageView imageView, VkSampler sampler, VkBuffer dynamicUbo) { +VkDescriptorSet DrawEngineVulkan::GetDescriptorSet(VkImageView imageView, VkSampler sampler, VkBuffer base, VkBuffer light, VkBuffer bone) { DescriptorSetKey key; key.imageView_ = imageView; key.sampler_ = sampler; key.secondaryImageView_ = VK_NULL_HANDLE; - key.buffer_ = dynamicUbo; + key.base_ = base; + key.light_ = light; + key.bone_ = bone; FrameData *frame = &frame_[curFrame_ & 1]; auto iter = frame->descSets.find(key); @@ -437,13 +451,13 @@ VkDescriptorSet DrawEngineVulkan::GetDescriptorSet(VkImageView imageView, VkSamp // Skipping 2nd texture for now. // Uniform buffer objects VkDescriptorBufferInfo buf[3]; - buf[0].buffer = dynamicUbo; + buf[0].buffer = base; buf[0].offset = 0; buf[0].range = sizeof(UB_VS_FS_Base); - buf[1].buffer = dynamicUbo; + buf[1].buffer = light; buf[1].offset = 0; buf[1].range = sizeof(UB_VS_Lights); - buf[2].buffer = dynamicUbo; + buf[2].buffer = bone; buf[2].offset = 0; buf[2].range = sizeof(UB_VS_Bones); for (int i = 0; i < 3; i++) { @@ -489,8 +503,6 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { textureCache_->ApplyTexture(imageView, sampler); } - VkDescriptorSet ds = GetDescriptorSet(imageView, sampler, frame->pushUBO->GetVkBuffer()); - GEPrimitiveType prim = prevPrim_; bool useHWTransform = CanUseHardwareTransform(prim); @@ -551,36 +563,40 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { } vkCmdBindPipeline(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline->pipeline); // TODO: Avoid if same as last draw. + // TODO: Make only one allocation so all three end up in the same buffer. + VkBuffer baseBuf, lightBuf, boneBuf; if (pipeline->uniformBlocks & UB_VS_FS_BASE) { - baseUBOOffset = shaderManager_->PushBaseBuffer(frame->pushUBO); + baseUBOOffset = shaderManager_->PushBaseBuffer(frame->pushUBO, &baseBuf); } if (pipeline->uniformBlocks & UB_VS_LIGHTS) { - lightUBOOffset = shaderManager_->PushLightBuffer(frame->pushUBO); + lightUBOOffset = shaderManager_->PushLightBuffer(frame->pushUBO, &lightBuf); } if (pipeline->uniformBlocks & UB_VS_BONES) { - boneUBOOffset = shaderManager_->PushBoneBuffer(frame->pushUBO); + boneUBOOffset = shaderManager_->PushBoneBuffer(frame->pushUBO, &boneBuf); } - VkBuffer vbuf[1] = { frame->pushVertex->GetVkBuffer() }; - VkBuffer ibuf = { frame->pushIndex->GetVkBuffer() }; + VkDescriptorSet ds = GetDescriptorSet(imageView, sampler, baseBuf, lightBuf, boneBuf); + const uint32_t dynamicUBOOffsets[3] = { baseUBOOffset, lightUBOOffset, boneUBOOffset, }; vkCmdBindDescriptorSets(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout_, 0, 1, &ds, 3, dynamicUBOOffsets); int stride = dec_->GetDecVtxFmt().stride; - vbOffset = (uint32_t)frame->pushVertex->PushAligned(decoded, indexGen.MaxIndex() * stride, 16); + VkBuffer vbuf; + vbOffset = (uint32_t)frame->pushVertex->PushAligned(decoded, indexGen.MaxIndex() * stride, 16, &vbuf); VkDeviceSize offsets[1] = { vbOffset }; if (useElements) { - ibOffset = (uint32_t)frame->pushIndex->PushAligned(decIndex, 2 * indexGen.VertexCount(), 16); + VkBuffer ibuf; + ibOffset = (uint32_t)frame->pushIndex->PushAligned(decIndex, 2 * indexGen.VertexCount(), 16, &ibuf); // TODO: Avoid rebinding vertex/index buffers if the vertex size stays the same by using the offset arguments // Might want to separate vertices out into a different push buffer in that case. - vkCmdBindVertexBuffers(cmd_, 0, 1, vbuf, offsets); + vkCmdBindVertexBuffers(cmd_, 0, 1, &vbuf, offsets); vkCmdBindIndexBuffer(cmd_, ibuf, ibOffset, VK_INDEX_TYPE_UINT16); vkCmdDrawIndexed(cmd_, vertexCount, 1, 0, 0, 0); } else { - vkCmdBindVertexBuffers(cmd_, 0, 1, vbuf, offsets); + vkCmdBindVertexBuffers(cmd_, 0, 1, &vbuf, offsets); vkCmdDraw(cmd_, vertexCount, 1, 0, 0); } } else { @@ -654,31 +670,33 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { } vkCmdBindPipeline(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline->pipeline); // TODO: Avoid if same as last draw. + VkBuffer uboBuf; if (pipeline->uniformBlocks & UB_VS_FS_BASE) { - baseUBOOffset = shaderManager_->PushBaseBuffer(frame->pushUBO); + baseUBOOffset = shaderManager_->PushBaseBuffer(frame->pushUBO, &uboBuf); } + VkDescriptorSet ds = GetDescriptorSet(imageView, sampler, uboBuf, uboBuf, uboBuf); const uint32_t dynamicUBOOffsets[3] = { baseUBOOffset, lightUBOOffset, boneUBOOffset, }; vkCmdBindDescriptorSets(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout_, 0, 1, &ds, 3, dynamicUBOOffsets); - VkBuffer vbuf[1] = { frame->pushVertex->GetVkBuffer() }; - VkBuffer ibuf = { frame->pushIndex->GetVkBuffer() }; if (drawIndexed) { - vbOffset = (uint32_t)frame->pushVertex->PushAligned(drawBuffer, maxIndex * sizeof(TransformedVertex), 16); - ibOffset = (uint32_t)frame->pushIndex->PushAligned(inds, sizeof(short) * numTrans, 16); + VkBuffer vbuf, ibuf; + vbOffset = (uint32_t)frame->pushVertex->PushAligned(drawBuffer, maxIndex * sizeof(TransformedVertex), 16, &vbuf); + ibOffset = (uint32_t)frame->pushIndex->PushAligned(inds, sizeof(short) * numTrans, 16, &ibuf); VkDeviceSize offsets[1] = { vbOffset }; // TODO: Have a buffer per frame, use a walking buffer pointer // TODO: Avoid rebinding if the vertex size stays the same by using the offset arguments - vkCmdBindVertexBuffers(cmd_, 0, 1, vbuf, offsets); + vkCmdBindVertexBuffers(cmd_, 0, 1, &vbuf, offsets); vkCmdBindIndexBuffer(cmd_, ibuf, ibOffset, VK_INDEX_TYPE_UINT16); vkCmdDrawIndexed(cmd_, numTrans, 1, 0, 0, 0); } else { - vbOffset = (uint32_t)frame->pushVertex->PushAligned(drawBuffer, numTrans * sizeof(TransformedVertex), 16); + VkBuffer vbuf; + vbOffset = (uint32_t)frame->pushVertex->PushAligned(drawBuffer, numTrans * sizeof(TransformedVertex), 16, &vbuf); VkDeviceSize offsets[1] = { vbOffset }; // TODO: Avoid rebinding if the vertex size stays the same by using the offset arguments - vkCmdBindVertexBuffers(cmd_, 0, 1, vbuf, offsets); + vkCmdBindVertexBuffers(cmd_, 0, 1, &vbuf, offsets); vkCmdDraw(cmd_, numTrans, 1, 0, 0); } } else if (result.action == SW_CLEAR) { diff --git a/GPU/Vulkan/DrawEngineVulkan.h b/GPU/Vulkan/DrawEngineVulkan.h index 0e8339c1a1..ef7eecf5b9 100644 --- a/GPU/Vulkan/DrawEngineVulkan.h +++ b/GPU/Vulkan/DrawEngineVulkan.h @@ -152,7 +152,7 @@ private: void DecodeVertsStep(); void DoFlush(VkCommandBuffer cmd); - VkDescriptorSet GetDescriptorSet(VkImageView imageView, VkSampler sampler, VkBuffer dynamicUbo); + VkDescriptorSet GetDescriptorSet(VkImageView imageView, VkSampler sampler, VkBuffer base, VkBuffer light, VkBuffer bone); VertexDecoder *GetVertexDecoder(u32 vtype); @@ -166,14 +166,16 @@ private: VkImageView imageView_; VkImageView secondaryImageView_; VkSampler sampler_; - VkBuffer buffer_; // All three UBO slots will be set to this. This will usually be identical + VkBuffer base_, light_, bone_; // All three UBO slots will be set to this. This will usually be identical // for all draws in a frame, except when the buffer has to grow. bool operator < (const DescriptorSetKey &other) const { if (imageView_ < other.imageView_) return true; else if (imageView_ > other.imageView_) return false; if (sampler_ < other.sampler_) return true; else if (sampler_ > other.sampler_) return false; if (secondaryImageView_ < other.secondaryImageView_) return true; else if (secondaryImageView_ > other.secondaryImageView_) return false; - if (buffer_ < other.buffer_) return true; else if (buffer_ > other.buffer_) return false; + if (base_ < other.base_) return true; else if (base_ > other.base_) return false; + if (light_ < other.light_) return true; else if (light_ > other.light_) return false; + if (bone_ < other.bone_) return true; else if (bone_ > other.bone_) return false; return false; } }; diff --git a/GPU/Vulkan/ShaderManagerVulkan.cpp b/GPU/Vulkan/ShaderManagerVulkan.cpp index 13972b6c92..a5b865d656 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.cpp +++ b/GPU/Vulkan/ShaderManagerVulkan.cpp @@ -176,17 +176,17 @@ ShaderManagerVulkan::~ShaderManagerVulkan() { delete[] codeBuffer_; } -uint32_t ShaderManagerVulkan::PushBaseBuffer(VulkanPushBuffer *dest) { - return dest->PushAligned(&ub_base, sizeof(ub_base), uboAlignment_); +uint32_t ShaderManagerVulkan::PushBaseBuffer(VulkanPushBuffer *dest, VkBuffer *buf) { + return dest->PushAligned(&ub_base, sizeof(ub_base), uboAlignment_, buf); } -uint32_t ShaderManagerVulkan::PushLightBuffer(VulkanPushBuffer *dest) { - return dest->PushAligned(&ub_lights, sizeof(ub_lights), uboAlignment_); +uint32_t ShaderManagerVulkan::PushLightBuffer(VulkanPushBuffer *dest, VkBuffer *buf) { + return dest->PushAligned(&ub_lights, sizeof(ub_lights), uboAlignment_, buf); } // TODO: Only push half the bone buffer if we only have four bones. -uint32_t ShaderManagerVulkan::PushBoneBuffer(VulkanPushBuffer *dest) { - return dest->PushAligned(&ub_bones, sizeof(ub_bones), uboAlignment_); +uint32_t ShaderManagerVulkan::PushBoneBuffer(VulkanPushBuffer *dest, VkBuffer *buf) { + return dest->PushAligned(&ub_bones, sizeof(ub_bones), uboAlignment_, buf); } void ShaderManagerVulkan::BaseUpdateUniforms(int dirtyUniforms) { diff --git a/GPU/Vulkan/ShaderManagerVulkan.h b/GPU/Vulkan/ShaderManagerVulkan.h index e6672b4fcc..bba2e878a5 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.h +++ b/GPU/Vulkan/ShaderManagerVulkan.h @@ -242,9 +242,9 @@ public: bool IsLightDirty() { return true; } bool IsBoneDirty() { return true; } - uint32_t PushBaseBuffer(VulkanPushBuffer *dest); - uint32_t PushLightBuffer(VulkanPushBuffer *dest); - uint32_t PushBoneBuffer(VulkanPushBuffer *dest); + uint32_t PushBaseBuffer(VulkanPushBuffer *dest, VkBuffer *buf); + uint32_t PushLightBuffer(VulkanPushBuffer *dest, VkBuffer *buf); + uint32_t PushBoneBuffer(VulkanPushBuffer *dest, VkBuffer *buf); private: void BaseUpdateUniforms(int dirtyUniforms); diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index 4d5eb0003e..86e0f4a991 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -1482,9 +1482,10 @@ void TextureCacheVulkan::SetTexture(VulkanPushBuffer *uploadBuffer) { int stride = (mipWidth * bpp + 15) & ~15; int size = stride * mipHeight; size_t bufferOffset; - void *data = uploadBuffer->Push(size, &bufferOffset); + VkBuffer texBuf; + void *data = uploadBuffer->Push(size, &bufferOffset, &texBuf); LoadTextureLevel(*entry, (uint8_t *)data, stride, i, replaceImages, scaleFactor, dstFmt); - entry->vkTex->texture_->UploadMip(i, mipWidth, mipHeight, uploadBuffer->GetVkBuffer(), bufferOffset, stride / bpp); + entry->vkTex->texture_->UploadMip(i, mipWidth, mipHeight, texBuf, bufferOffset, stride / bpp); } gstate_c.textureFullAlpha = entry->GetAlphaStatus() == TexCacheEntry::STATUS_ALPHA_FULL; diff --git a/UI/EmuScreen.cpp b/UI/EmuScreen.cpp index 7b00528dc9..d89ab487f4 100644 --- a/UI/EmuScreen.cpp +++ b/UI/EmuScreen.cpp @@ -702,7 +702,7 @@ void EmuScreen::update(InputState &input) { UIScreen::update(input); - // Simply forcibily update to the current screen size every frame. Doesn't cost much. + // Simply forcibly update to the current screen size every frame. Doesn't cost much. // If bounds is set to be smaller than the actual pixel resolution of the display, respect that. // TODO: Should be able to use g_dpi_scale here instead. Might want to store the dpi scale in the UI context too. const Bounds &bounds = screenManager()->getUIContext()->GetBounds(); diff --git a/ext/native/thin3d/thin3d_vulkan.cpp b/ext/native/thin3d/thin3d_vulkan.cpp index 9d1397a787..eec08f88e4 100644 --- a/ext/native/thin3d/thin3d_vulkan.cpp +++ b/ext/native/thin3d/thin3d_vulkan.cpp @@ -285,9 +285,9 @@ public: } bool Link(); - // Returns the binding offset. - size_t PushUBO(VulkanPushBuffer *buf, VulkanContext *vulkan) { - return buf->PushAligned(ubo_, uboSize_, vulkan->GetPhysicalDeviceProperties().limits.minUniformBufferOffsetAlignment); + // Returns the binding offset, and the VkBuffer to bind. + size_t PushUBO(VulkanPushBuffer *buf, VulkanContext *vulkan, VkBuffer *vkbuf) { + return buf->PushAligned(ubo_, uboSize_, vulkan->GetPhysicalDeviceProperties().limits.minUniformBufferOffsetAlignment, vkbuf); } int GetUniformLoc(const char *name); @@ -335,7 +335,7 @@ class Thin3DVKSamplerState; struct DescriptorSetKey { Thin3DVKTexture *texture_; Thin3DVKSamplerState *sampler_; - VulkanPushBuffer *buffer_; + VkBuffer buffer_; bool operator < (const DescriptorSetKey &other) const { if (texture_ < other.texture_) return true; else if (texture_ > other.texture_) return false; @@ -418,7 +418,7 @@ public: } VkPipeline GetOrCreatePipeline(); - VkDescriptorSet GetOrCreateDescriptorSet(); + VkDescriptorSet GetOrCreateDescriptorSet(VkBuffer buffer); std::vector GetFeatureList() override; @@ -672,6 +672,7 @@ Thin3DVKContext::~Thin3DVKContext() { for (int i = 0; i < 2; i++) { frame_[i].descSets_.clear(); vkDestroyDescriptorPool(device_, frame_[i].descriptorPool, nullptr); + frame_[i].pushBuffer->Destroy(vulkan_); delete frame_[i].pushBuffer; } vkDestroyDescriptorSetLayout(device_, descriptorSetLayout_, nullptr); @@ -696,6 +697,7 @@ void Thin3DVKContext::Begin(bool clear, uint32_t colorval, float depthVal, int s push_ = frame->pushBuffer; // OK, we now know that nothing is reading from this frame's data pushbuffer, + push_->Reset(); push_->Begin(device_); frame->descSets_.clear(); @@ -718,14 +720,14 @@ void Thin3DVKContext::End() { DirtyDynamicState(); } -VkDescriptorSet Thin3DVKContext::GetOrCreateDescriptorSet() { +VkDescriptorSet Thin3DVKContext::GetOrCreateDescriptorSet(VkBuffer buf) { DescriptorSetKey key; FrameData *frame = &frame_[frameNum_ & 1]; key.texture_ = boundTextures_[0]; key.sampler_ = boundSamplers_[0]; - key.buffer_ = push_; // Not currently strictly necessary as a single frame always uses a specific push buffer + key.buffer_ = buf; auto iter = frame->descSets_.find(key); if (iter != frame->descSets_.end()) { @@ -747,7 +749,7 @@ VkDescriptorSet Thin3DVKContext::GetOrCreateDescriptorSet() { // bindings[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; VkDescriptorBufferInfo bufferDesc; - bufferDesc.buffer = push_->GetVkBuffer(); + bufferDesc.buffer = buf; bufferDesc.offset = 0; bufferDesc.range = curShaderSet_->GetUBOSize(); @@ -1092,14 +1094,16 @@ void Thin3DVKContext::Draw(T3DPrimitive prim, Thin3DShaderSet *shaderSet, Thin3D curVertexFormat_ = (Thin3DVKVertexFormat *)format; Thin3DVKBuffer *vbuf = static_cast(vdata); - uint32_t ubo_offset = (uint32_t)curShaderSet_->PushUBO(push_, vulkan_); - size_t vbBindOffset = push_->Push(vbuf->GetData(), vbuf->GetSize()); + VkBuffer vulkanVbuf; + VkBuffer vulkanUBObuf; + uint32_t ubo_offset = (uint32_t)curShaderSet_->PushUBO(push_, vulkan_, &vulkanVbuf); + size_t vbBindOffset = push_->Push(vbuf->GetData(), vbuf->GetSize(), &vulkanUBObuf); VkPipeline pipeline = GetOrCreatePipeline(); vkCmdBindPipeline(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); - VkDescriptorSet descSet = GetOrCreateDescriptorSet(); + VkDescriptorSet descSet = GetOrCreateDescriptorSet(vulkanUBObuf); vkCmdBindDescriptorSets(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout_, 0, 1, &descSet, 1, &ubo_offset); - VkBuffer buffers[1] = { push_->GetVkBuffer() }; + VkBuffer buffers[1] = { vulkanVbuf }; VkDeviceSize offsets[1] = { vbBindOffset }; vkCmdBindVertexBuffers(cmd_, 0, 1, buffers, offsets); vkCmdDraw(cmd_, vertexCount, 1, offset, 0); @@ -1115,21 +1119,22 @@ void Thin3DVKContext::DrawIndexed(T3DPrimitive prim, Thin3DShaderSet *shaderSet, Thin3DVKBuffer *ibuf = (Thin3DVKBuffer *)idata; Thin3DVKBuffer *vbuf = (Thin3DVKBuffer *)vdata; - uint32_t ubo_offset = (uint32_t)curShaderSet_->PushUBO(push_, vulkan_); - size_t vbBindOffset = push_->Push(vbuf->GetData(), vbuf->GetSize()); - size_t ibBindOffset = push_->Push(ibuf->GetData(), ibuf->GetSize()); + VkBuffer vulkanVbuf, vulkanIbuf, vulkanUBObuf; + uint32_t ubo_offset = (uint32_t)curShaderSet_->PushUBO(push_, vulkan_, &vulkanUBObuf); + size_t vbBindOffset = push_->Push(vbuf->GetData(), vbuf->GetSize(), &vulkanVbuf); + size_t ibBindOffset = push_->Push(ibuf->GetData(), ibuf->GetSize(), &vulkanIbuf); VkPipeline pipeline = GetOrCreatePipeline(); vkCmdBindPipeline(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); - VkDescriptorSet descSet = GetOrCreateDescriptorSet(); + VkDescriptorSet descSet = GetOrCreateDescriptorSet(vulkanUBObuf); vkCmdBindDescriptorSets(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout_, 0, 1, &descSet, 1, &ubo_offset); - VkBuffer buffers[1] = { push_->GetVkBuffer() }; + VkBuffer buffers[1] = { vulkanVbuf }; VkDeviceSize offsets[1] = { vbBindOffset }; vkCmdBindVertexBuffers(cmd_, 0, 1, buffers, offsets); - vkCmdBindIndexBuffer(cmd_, push_->GetVkBuffer(), ibBindOffset, VK_INDEX_TYPE_UINT16); + vkCmdBindIndexBuffer(cmd_, vulkanIbuf, ibBindOffset, VK_INDEX_TYPE_UINT16); vkCmdDrawIndexed(cmd_, vertexCount, 1, 0, offset, 0); } @@ -1140,17 +1145,18 @@ void Thin3DVKContext::DrawUP(T3DPrimitive prim, Thin3DShaderSet *shaderSet, Thin curShaderSet_ = (Thin3DVKShaderSet *)shaderSet; curVertexFormat_ = (Thin3DVKVertexFormat *)format; - size_t vbBindOffset = push_->Push(vdata, vertexCount * curVertexFormat_->stride_); - uint32_t ubo_offset = (uint32_t)curShaderSet_->PushUBO(push_, vulkan_); + VkBuffer vulkanVbuf, vulkanUBObuf; + size_t vbBindOffset = push_->Push(vdata, vertexCount * curVertexFormat_->stride_, &vulkanVbuf); + uint32_t ubo_offset = (uint32_t)curShaderSet_->PushUBO(push_, vulkan_, &vulkanUBObuf); VkPipeline pipeline = GetOrCreatePipeline(); vkCmdBindPipeline(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); - VkBuffer buffers[1] = { push_->GetVkBuffer() }; + VkBuffer buffers[1] = { vulkanVbuf }; VkDeviceSize offsets[1] = { vbBindOffset }; vkCmdBindVertexBuffers(cmd_, 0, 1, buffers, offsets); - VkDescriptorSet descSet = GetOrCreateDescriptorSet(); + VkDescriptorSet descSet = GetOrCreateDescriptorSet(vulkanUBObuf); vkCmdBindDescriptorSets(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout_, 0, 1, &descSet, 1, &ubo_offset); vkCmdDraw(cmd_, vertexCount, 1, 0, 0); } From 8e9acff6aa0442e5e38f4f5d3d7deb4c054fcac4 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 20 Mar 2016 14:33:37 +0100 Subject: [PATCH 106/116] Always specify depthstencil state in pipelines. Turns out it's only OK to leave out if rendering only to color, otherwise behaviour is undefined - which means it may still be enabled. --- GPU/Vulkan/PipelineManagerVulkan.cpp | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/GPU/Vulkan/PipelineManagerVulkan.cpp b/GPU/Vulkan/PipelineManagerVulkan.cpp index 13f228b142..9f9fd679f2 100644 --- a/GPU/Vulkan/PipelineManagerVulkan.cpp +++ b/GPU/Vulkan/PipelineManagerVulkan.cpp @@ -49,7 +49,7 @@ static const DeclTypeInfo VComp[] = { { VK_FORMAT_R16G16_UNORM, "R16G16_UNORM" }, // DEC_U16_2, { VK_FORMAT_R16G16B16A16_UNORM, "R16G16B16A16_UNORM " }, // DEC_U16_3, { VK_FORMAT_R16G16B16A16_UNORM, "R16G16B16A16_UNORM " }, // DEC_U16_4, - // Not supported in regular DX9 so faking, will cause graphics bugs until worked around + { VK_FORMAT_R8G8_UINT, "R8G8_UINT" }, // DEC_U8A_2, { VK_FORMAT_R16G16_UINT, "R16G16_UINT" }, // DEC_U16A_2, }; @@ -235,11 +235,7 @@ static VulkanPipeline *CreateVulkanPipeline(VkDevice device, VkPipelineCache pip pipe.basePipelineIndex = 0; pipe.pColorBlendState = &cbs; - if (key.depthTestEnable || key.stencilTestEnable) { - pipe.pDepthStencilState = &dss; - } else { - pipe.pDepthStencilState = nullptr; - } + pipe.pDepthStencilState = &dss; pipe.pRasterizationState = &rs; // We will use dynamic viewport state. @@ -278,7 +274,7 @@ VulkanPipeline *PipelineManagerVulkan::GetOrCreatePipeline(VkPipelineLayout layo key.useHWTransform = useHwTransform; key.vShader = vs->GetModule(); key.fShader = fs->GetModule(); - key.vtxDec = vtxDec; + key.vtxDec = useHwTransform ? vtxDec : nullptr; auto iter = pipelines_.find(key); if (iter != pipelines_.end()) { return iter->second; From 5d45413dabe051f38c0a07232b672a2fe3501988 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 20 Mar 2016 14:50:58 +0100 Subject: [PATCH 107/116] Fix a resource leak. Request COHERENT memory for pushbuffers. --- Common/Vulkan/VulkanContext.h | 4 ++++ Common/Vulkan/VulkanMemory.cpp | 3 ++- Common/Vulkan/VulkanMemory.h | 7 +++++++ 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/Common/Vulkan/VulkanContext.h b/Common/Vulkan/VulkanContext.h index 8671f2c246..bc3a7d6d1b 100644 --- a/Common/Vulkan/VulkanContext.h +++ b/Common/Vulkan/VulkanContext.h @@ -87,6 +87,10 @@ public: for (auto &descPool : descPools_) { vkDestroyDescriptorPool(device, descPool, nullptr); } + descPools_.clear(); + for (auto &module : modules_) { + vkDestroyShaderModule(device, module, nullptr); + } modules_.clear(); for (auto &buf : buffers_) { vkDestroyBuffer(device, buf, nullptr); diff --git a/Common/Vulkan/VulkanMemory.cpp b/Common/Vulkan/VulkanMemory.cpp index 2ffcc15ed8..2daf1d5bfb 100644 --- a/Common/Vulkan/VulkanMemory.cpp +++ b/Common/Vulkan/VulkanMemory.cpp @@ -37,7 +37,8 @@ VulkanPushBuffer::VulkanPushBuffer(VulkanContext *vulkan, size_t size) : offset_ VkMemoryAllocateInfo alloc = {}; alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; alloc.pNext = nullptr; - vulkan->MemoryTypeFromProperties(0xFFFFFFFF, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, &alloc.memoryTypeIndex); + + vulkan->MemoryTypeFromProperties(0xFFFFFFFF, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &alloc.memoryTypeIndex); alloc.allocationSize = size; res = vkAllocateMemory(device, &alloc, nullptr, &deviceMemory_); diff --git a/Common/Vulkan/VulkanMemory.h b/Common/Vulkan/VulkanMemory.h index f8855bf762..ff0f7d6519 100644 --- a/Common/Vulkan/VulkanMemory.h +++ b/Common/Vulkan/VulkanMemory.h @@ -40,6 +40,13 @@ public: } void End(VkDevice device) { + /* + VkMappedMemoryRange range = { VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE }; + range.offset = 0; + range.size = offset_; + range.memory = deviceMemory_; + vkFlushMappedMemoryRanges(device, 1, &range); + */ vkUnmapMemory(device, deviceMemory_); writePtr_ = nullptr; } From 18d78f9a35326cec1707a2c1b3413a21b87550ed Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 20 Mar 2016 14:54:21 +0100 Subject: [PATCH 108/116] Minor optimizations --- GPU/Vulkan/ShaderManagerVulkan.cpp | 7 +++---- GPU/Vulkan/ShaderManagerVulkan.h | 2 +- GPU/Vulkan/StateMappingVulkan.h | 17 +++++++++-------- GPU/Vulkan/VertexShaderGeneratorVulkan.cpp | 3 ++- ext/native/math/lin/matrix4x4.cpp | 17 +++++++++++++++-- ext/native/math/lin/matrix4x4.h | 1 + 6 files changed, 31 insertions(+), 16 deletions(-) diff --git a/GPU/Vulkan/ShaderManagerVulkan.cpp b/GPU/Vulkan/ShaderManagerVulkan.cpp index a5b865d656..abeefea128 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.cpp +++ b/GPU/Vulkan/ShaderManagerVulkan.cpp @@ -69,7 +69,7 @@ VulkanFragmentShader::VulkanFragmentShader(VulkanContext *vulkan, ShaderID id, c } else { success = vulkan_->CreateShaderModule(spirv, &module_); #ifdef SHADERLOG - OutputDebugStringA("OK"); + OutputDebugStringA("OK\n"); #endif } @@ -121,7 +121,7 @@ VulkanVertexShader::VulkanVertexShader(VulkanContext *vulkan, ShaderID id, const } else { success = vulkan_->CreateShaderModule(spirv, &module_); #ifdef SHADERLOG - OutputDebugStringA("OK"); + OutputDebugStringA("OK\n"); #endif } @@ -256,8 +256,7 @@ void ShaderManagerVulkan::BaseUpdateUniforms(int dirtyUniforms) { if (dirtyUniforms & DIRTY_PROJTHROUGHMATRIX) { Matrix4x4 proj_through; - proj_through.setOrtho(0.0f, gstate_c.curRTWidth, 0, gstate_c.curRTHeight, 0, 1); - ConvertProjMatrixToVulkanThrough(proj_through); + proj_through.setOrthoVulkan(0.0f, gstate_c.curRTWidth, 0, gstate_c.curRTHeight, 0, 1); CopyMatrix4x4(ub_base.proj_through, proj_through.getReadPtr()); } diff --git a/GPU/Vulkan/ShaderManagerVulkan.h b/GPU/Vulkan/ShaderManagerVulkan.h index bba2e878a5..2cf794da7b 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.h +++ b/GPU/Vulkan/ShaderManagerVulkan.h @@ -70,7 +70,7 @@ enum { DIRTY_BONEMATRIX7 = (1 << 31), DIRTY_BASE_UNIFORMS = - DIRTY_WORLDMATRIX | DIRTY_VIEWMATRIX | DIRTY_TEXMATRIX | DIRTY_ALPHACOLORREF | + DIRTY_WORLDMATRIX | DIRTY_PROJTHROUGHMATRIX | DIRTY_VIEWMATRIX | DIRTY_TEXMATRIX | DIRTY_ALPHACOLORREF | DIRTY_PROJMATRIX | DIRTY_FOGCOLOR | DIRTY_FOGCOEF | DIRTY_TEXENV | DIRTY_STENCILREPLACEVALUE | DIRTY_ALPHACOLORMASK | DIRTY_SHADERBLEND | DIRTY_UVSCALEOFFSET | DIRTY_TEXCLAMP | DIRTY_DEPTHRANGE | DIRTY_MATAMBIENTALPHA, DIRTY_LIGHT_UNIFORMS = diff --git a/GPU/Vulkan/StateMappingVulkan.h b/GPU/Vulkan/StateMappingVulkan.h index 0f907bc649..e4b67a3b57 100644 --- a/GPU/Vulkan/StateMappingVulkan.h +++ b/GPU/Vulkan/StateMappingVulkan.h @@ -24,7 +24,7 @@ struct VulkanDynamicState { // Can't use enums unfortunately, they end up signed and breaking values above half their ranges. struct VulkanPipelineRasterStateKey { // Blend - bool blendEnable : 1; + unsigned int blendEnable : 1; unsigned int srcColor : 5; // VkBlendFactor unsigned int destColor : 5; // VkBlendFactor unsigned int srcAlpha : 5; // VkBlendFactor @@ -32,18 +32,18 @@ struct VulkanPipelineRasterStateKey { // bool useBlendConstant : 1; // sacrifice a bit to cheaply check if we need to update the blend color unsigned int blendOpColor : 3; // VkBlendOp unsigned int blendOpAlpha : 3; // VkBlendOp - bool logicOpEnable : 1; + unsigned int logicOpEnable : 1; unsigned int logicOp : 4; // VkLogicOp unsigned int colorWriteMask : 4; // Depth/Stencil - bool depthTestEnable : 1; - bool depthWriteEnable : 1; + unsigned int depthTestEnable : 1; + unsigned int depthWriteEnable : 1; unsigned int depthCompareOp : 3; // VkCompareOp - bool stencilTestEnable : 1; - unsigned int stencilCompareOp : 4; // VkCompareOp + unsigned int stencilTestEnable : 1; + unsigned int stencilCompareOp : 3; // VkCompareOp unsigned int stencilPassOp : 4; // VkStencilOp - unsigned int stencilFailOp : 4; //VkStencilOp + unsigned int stencilFailOp : 4; // VkStencilOp unsigned int stencilDepthFailOp : 4; // VkStencilOp // We'll use dynamic state for writemask, reference and comparemask to start with, @@ -54,7 +54,8 @@ struct VulkanPipelineRasterStateKey { unsigned int topology : 4; // VkPrimitiveTopology bool operator < (const VulkanPipelineRasterStateKey &other) const { - return memcmp(this, &other, sizeof(*this)) < 0; + size_t size = sizeof(VulkanPipelineRasterStateKey); + return memcmp(this, &other, size) < 0; } }; diff --git a/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp b/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp index 15aa010fbb..a4a0ede14a 100644 --- a/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp +++ b/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp @@ -173,7 +173,8 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { if (useHWTransform) WRITE(p, "layout (location = %d) in vec3 position;\n", PspAttributeLocation::POSITION); else - WRITE(p, "layout (location = %d) in vec4 position;\n", PspAttributeLocation::POSITION); // need to pass the fog coord in w + // we pass the fog coord in w + WRITE(p, "layout (location = %d) in vec4 position;\n", PspAttributeLocation::POSITION); if (useHWTransform && hasNormal) WRITE(p, "layout (location = %d) in vec3 normal;\n", PspAttributeLocation::NORMAL); diff --git a/ext/native/math/lin/matrix4x4.cpp b/ext/native/math/lin/matrix4x4.cpp index d90dc957ab..703ed366c3 100644 --- a/ext/native/math/lin/matrix4x4.cpp +++ b/ext/native/math/lin/matrix4x4.cpp @@ -203,23 +203,36 @@ void Matrix4x4::setProjectionD3D(float near_plane, float far_plane, float fov_ho } void Matrix4x4::setOrtho(float left, float right, float bottom, float top, float near, float far) { - setIdentity(); + empty(); xx = 2.0f / (right - left); yy = 2.0f / (top - bottom); zz = 2.0f / (far - near); wx = -(right + left) / (right - left); wy = -(top + bottom) / (top - bottom); wz = -(far + near) / (far - near); + ww = 1.0f; } void Matrix4x4::setOrthoD3D(float left, float right, float bottom, float top, float near, float far) { - setIdentity(); + empty(); xx = 2.0f / (right - left); yy = 2.0f / (top - bottom); zz = 1.0f / (far - near); wx = -(right + left) / (right - left); wy = -(top + bottom) / (top - bottom); wz = -near / (far - near); + ww = 1.0f; +} + +void Matrix4x4::setOrthoVulkan(float left, float right, float top, float bottom, float near, float far) { + empty(); + xx = 2.0f / (right - left); + yy = 2.0f / (bottom - top); + zz = 1.0f / (far - near); + wx = -(right + left) / (right - left); + wy = -(top + bottom) / (bottom - top); + wz = -near / (far - near); + ww = 1.0f; } void Matrix4x4::setProjectionInf(const float near_plane, const float fov_horiz, const float aspect) { diff --git a/ext/native/math/lin/matrix4x4.h b/ext/native/math/lin/matrix4x4.h index d56906d1f2..3b52e4ecd7 100644 --- a/ext/native/math/lin/matrix4x4.h +++ b/ext/native/math/lin/matrix4x4.h @@ -120,6 +120,7 @@ public: void setProjectionInf(float near_plane, float fov_horiz, float aspect = 0.75f); void setOrtho(float left, float right, float bottom, float top, float near, float far); void setOrthoD3D(float left, float right, float bottom, float top, float near, float far); + void setOrthoVulkan(float left, float right, float top, float bottom, float near, float far); void setShadow(float Lx, float Ly, float Lz, float Lw) { float Pa=0; float Pb=1; From d0659f0debcdc231332f4cf4828d0d768499ac96 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 20 Mar 2016 15:08:26 +0100 Subject: [PATCH 109/116] No need to align vertex/index data. Will only be harmful for an upcoming optimization. --- GPU/Vulkan/DrawEngineVulkan.cpp | 11 +++++------ Windows/GPU/WindowsVulkanContext.cpp | 2 +- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index ff0036eb86..91ad7f9afc 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -584,14 +584,13 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { int stride = dec_->GetDecVtxFmt().stride; VkBuffer vbuf; - vbOffset = (uint32_t)frame->pushVertex->PushAligned(decoded, indexGen.MaxIndex() * stride, 16, &vbuf); + vbOffset = (uint32_t)frame->pushVertex->Push(decoded, indexGen.MaxIndex() * stride, &vbuf); VkDeviceSize offsets[1] = { vbOffset }; if (useElements) { VkBuffer ibuf; - ibOffset = (uint32_t)frame->pushIndex->PushAligned(decIndex, 2 * indexGen.VertexCount(), 16, &ibuf); + ibOffset = (uint32_t)frame->pushIndex->Push(decIndex, 2 * indexGen.VertexCount(), &ibuf); // TODO: Avoid rebinding vertex/index buffers if the vertex size stays the same by using the offset arguments - // Might want to separate vertices out into a different push buffer in that case. vkCmdBindVertexBuffers(cmd_, 0, 1, &vbuf, offsets); vkCmdBindIndexBuffer(cmd_, ibuf, ibOffset, VK_INDEX_TYPE_UINT16); vkCmdDrawIndexed(cmd_, vertexCount, 1, 0, 0, 0); @@ -683,8 +682,8 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { if (drawIndexed) { VkBuffer vbuf, ibuf; - vbOffset = (uint32_t)frame->pushVertex->PushAligned(drawBuffer, maxIndex * sizeof(TransformedVertex), 16, &vbuf); - ibOffset = (uint32_t)frame->pushIndex->PushAligned(inds, sizeof(short) * numTrans, 16, &ibuf); + vbOffset = (uint32_t)frame->pushVertex->Push(drawBuffer, maxIndex * sizeof(TransformedVertex), &vbuf); + ibOffset = (uint32_t)frame->pushIndex->Push(inds, sizeof(short) * numTrans, &ibuf); VkDeviceSize offsets[1] = { vbOffset }; // TODO: Have a buffer per frame, use a walking buffer pointer // TODO: Avoid rebinding if the vertex size stays the same by using the offset arguments @@ -693,7 +692,7 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { vkCmdDrawIndexed(cmd_, numTrans, 1, 0, 0, 0); } else { VkBuffer vbuf; - vbOffset = (uint32_t)frame->pushVertex->PushAligned(drawBuffer, numTrans * sizeof(TransformedVertex), 16, &vbuf); + vbOffset = (uint32_t)frame->pushVertex->Push(drawBuffer, numTrans * sizeof(TransformedVertex), &vbuf); VkDeviceSize offsets[1] = { vbOffset }; // TODO: Avoid rebinding if the vertex size stays the same by using the offset arguments vkCmdBindVertexBuffers(cmd_, 0, 1, &vbuf, offsets); diff --git a/Windows/GPU/WindowsVulkanContext.cpp b/Windows/GPU/WindowsVulkanContext.cpp index 3088e4aca7..88cb6173c5 100644 --- a/Windows/GPU/WindowsVulkanContext.cpp +++ b/Windows/GPU/WindowsVulkanContext.cpp @@ -190,8 +190,8 @@ bool WindowsVulkanContext::Init(HINSTANCE hInst, HWND hWnd, std::string *error_m void WindowsVulkanContext::Shutdown() { g_Vulkan->WaitUntilQueueIdle(); g_Vulkan->DestroyObjects(); - g_Vulkan->DestroyDebugMsgCallback(); g_Vulkan->DestroyDevice(); + g_Vulkan->DestroyDebugMsgCallback(); delete g_Vulkan; g_Vulkan = nullptr; From d7ffc39d2acc565296f8720adefa538efc697703 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 20 Mar 2016 15:46:41 +0100 Subject: [PATCH 110/116] Vulkan: Remove support for software skinning to reduce complexity --- GPU/Vulkan/DrawEngineVulkan.cpp | 25 ++++------ GPU/Vulkan/DrawEngineVulkan.h | 4 +- GPU/Vulkan/GPU_Vulkan.cpp | 84 +++++++-------------------------- 3 files changed, 30 insertions(+), 83 deletions(-) diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index 91ad7f9afc..8f1b71a3df 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -66,7 +66,7 @@ DrawEngineVulkan::DrawEngineVulkan(VulkanContext *vulkan) vulkan_(vulkan), decodedVerts_(0), prevPrim_(GE_PRIM_INVALID), - lastVType_(-1), + lastVTypeID_(-1), pipelineManager_(nullptr), textureCache_(nullptr), framebufferManager_(nullptr), @@ -248,9 +248,9 @@ inline void DrawEngineVulkan::SetupVertexDecoderInternal(u32 vertType) { const u32 vertTypeID = (vertType & 0xFFFFFF) | (gstate.getUVGenMode() << 24); // If vtype has changed, setup the vertex decoder. - if (vertTypeID != lastVType_) { + if (vertTypeID != lastVTypeID_) { dec_ = GetVertexDecoder(vertTypeID); - lastVType_ = vertTypeID; + lastVTypeID_ = vertTypeID; } } @@ -289,11 +289,6 @@ void DrawEngineVulkan::SubmitPrim(void *verts, void *inds, GEPrimitiveType prim, numDrawCalls++; vertexCountInDrawCalls += vertexCount; - if (g_Config.bSoftwareSkinning && (vertType & GE_VTYPE_WEIGHT_MASK)) { - DecodeVertsStep(); - decodeCounter_++; - } - if (prim == GE_PRIM_RECTANGLES && (gstate.getTextureAddress(0) & 0x3FFFFFFF) == (gstate.getFrameBufAddress() & 0x3FFFFFFF)) { // Rendertarget == texture? if (!g_Config.bDisableSlowFramebufEffects) { @@ -305,7 +300,7 @@ void DrawEngineVulkan::SubmitPrim(void *verts, void *inds, GEPrimitiveType prim, void DrawEngineVulkan::DecodeVerts() { for (; decodeCounter_ < numDrawCalls; decodeCounter_++) { - DecodeVertsStep(); + DecodeVertsStep(decoded); } // Sanity check if (indexGen.Prim() < 0) { @@ -315,7 +310,7 @@ void DrawEngineVulkan::DecodeVerts() { } } -void DrawEngineVulkan::DecodeVertsStep() { +void DrawEngineVulkan::DecodeVertsStep(u8 *decoded) { const int i = decodeCounter_; const DeferredDrawCall &dc = drawCalls[i]; @@ -535,7 +530,7 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { } prim = indexGen.Prim(); - bool hasColor = (lastVType_ & GE_VTYPE_COL_MASK) != GE_VTYPE_COL_NONE; + bool hasColor = (lastVTypeID_ & GE_VTYPE_COL_MASK) != GE_VTYPE_COL_NONE; if (gstate.isModeThrough()) { gstate_c.vertexFullAlpha = gstate_c.vertexFullAlpha && (hasColor || gstate.getMaterialAmbientA() == 255); } else { @@ -555,7 +550,7 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { Uint8x4ToFloat4(bc, dynState.blendColor); vkCmdSetBlendConstants(cmd_, bc); shaderManager_->UpdateUniforms(); - shaderManager_->GetShaders(prim, lastVType_, &vshader, &fshader, useHWTransform); + shaderManager_->GetShaders(prim, lastVTypeID_, &vshader, &fshader, useHWTransform); VulkanPipeline *pipeline = pipelineManager_->GetOrCreatePipeline(pipelineLayout_, pipelineKey, dec_, vshader, fshader, true); if (!pipeline) { // Already logged, let's bail out. @@ -600,7 +595,7 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { } } else { DecodeVerts(); - bool hasColor = (lastVType_ & GE_VTYPE_COL_MASK) != GE_VTYPE_COL_NONE; + bool hasColor = (lastVTypeID_ & GE_VTYPE_COL_MASK) != GE_VTYPE_COL_NONE; if (gstate.isModeThrough()) { gstate_c.vertexFullAlpha = gstate_c.vertexFullAlpha && (hasColor || gstate.getMaterialAmbientA() == 255); } else { @@ -661,7 +656,7 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { Uint8x4ToFloat4(bc, dynState.blendColor); vkCmdSetBlendConstants(cmd_, bc); shaderManager_->UpdateUniforms(); - shaderManager_->GetShaders(prim, lastVType_, &vshader, &fshader, useHWTransform); + shaderManager_->GetShaders(prim, lastVTypeID_, &vshader, &fshader, useHWTransform); VulkanPipeline *pipeline = pipelineManager_->GetOrCreatePipeline(pipelineLayout_, pipelineKey, dec_, vshader, fshader, false); if (!pipeline) { // Already logged, let's bail out. @@ -770,7 +765,7 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { void DrawEngineVulkan::Resized() { decJitCache_->Clear(); - lastVType_ = -1; + lastVTypeID_ = -1; dec_ = NULL; // TODO: We must also wipe pipelines. for (auto iter = decoderMap_.begin(); iter != decoderMap_.end(); iter++) { diff --git a/GPU/Vulkan/DrawEngineVulkan.h b/GPU/Vulkan/DrawEngineVulkan.h index ef7eecf5b9..edffc85522 100644 --- a/GPU/Vulkan/DrawEngineVulkan.h +++ b/GPU/Vulkan/DrawEngineVulkan.h @@ -149,7 +149,7 @@ public: private: void DecodeVerts(); - void DecodeVertsStep(); + void DecodeVertsStep(u8 *decoded); void DoFlush(VkCommandBuffer cmd); VkDescriptorSet GetDescriptorSet(VkImageView imageView, VkSampler sampler, VkBuffer base, VkBuffer light, VkBuffer bone); @@ -216,7 +216,7 @@ private: int decodedVerts_; GEPrimitiveType prevPrim_; - u32 lastVType_; + u32 lastVTypeID_; TransformedVertex *transformed; TransformedVertex *transformedExpanded; diff --git a/GPU/Vulkan/GPU_Vulkan.cpp b/GPU/Vulkan/GPU_Vulkan.cpp index 808a94616e..de84577aad 100644 --- a/GPU/Vulkan/GPU_Vulkan.cpp +++ b/GPU/Vulkan/GPU_Vulkan.cpp @@ -583,13 +583,8 @@ void GPU_Vulkan::UpdateCmdInfo() { cmdInfo_[GE_CMD_TEXOFFSETV].flags |= FLAG_FLUSHBEFOREONCHANGE; } - if (g_Config.bSoftwareSkinning) { - cmdInfo_[GE_CMD_VERTEXTYPE].flags &= ~FLAG_FLUSHBEFOREONCHANGE; - cmdInfo_[GE_CMD_VERTEXTYPE].func = &GPU_Vulkan::Execute_VertexTypeSkinning; - } else { - cmdInfo_[GE_CMD_VERTEXTYPE].flags |= FLAG_FLUSHBEFOREONCHANGE; - cmdInfo_[GE_CMD_VERTEXTYPE].func = &GPU_Vulkan::Execute_VertexType; - } + cmdInfo_[GE_CMD_VERTEXTYPE].flags |= FLAG_FLUSHBEFOREONCHANGE; + cmdInfo_[GE_CMD_VERTEXTYPE].func = &GPU_Vulkan::Execute_VertexType; } void GPU_Vulkan::ReapplyGfxStateInternal() { @@ -830,24 +825,6 @@ void GPU_Vulkan::Execute_VertexType(u32 op, u32 diff) { } } -void GPU_Vulkan::Execute_VertexTypeSkinning(u32 op, u32 diff) { - // Don't flush when weight count changes, unless morph is enabled. - if ((diff & ~GE_VTYPE_WEIGHTCOUNT_MASK) || (op & GE_VTYPE_MORPHCOUNT_MASK) != 0) { - // Restore and flush - gstate.vertType ^= diff; - Flush(); - gstate.vertType ^= diff; - if (diff & (GE_VTYPE_TC_MASK | GE_VTYPE_THROUGH_MASK)) - shaderManager_->DirtyUniform(DIRTY_UVSCALEOFFSET); - // In this case, we may be doing weights and morphs. - // Update any bone matrix uniforms so it uses them correctly. - if ((op & GE_VTYPE_MORPHCOUNT_MASK) != 0) { - shaderManager_->DirtyUniform(gstate_c.deferredVertTypeDirty); - gstate_c.deferredVertTypeDirty = 0; - } - } -} - void GPU_Vulkan::Execute_Bezier(u32 op, u32 diff) { // This also make skipping drawing very effective. framebufferManager_->SetRenderFrameBuffer(gstate_c.framebufChanged, gstate_c.skipDrawReason); @@ -1310,35 +1287,20 @@ void GPU_Vulkan::Execute_BoneMtxNum(u32 op, u32 diff) { const int end = 12 * 8 - (op & 0x7F); int i = 0; - // If we can't use software skinning, we have to flush and dirty. - if (!g_Config.bSoftwareSkinning || (gstate.vertType & GE_VTYPE_MORPHCOUNT_MASK) != 0) { - while ((src[i] >> 24) == GE_CMD_BONEMATRIXDATA) { - const u32 newVal = src[i] << 8; - if (dst[i] != newVal) { - Flush(); - dst[i] = newVal; - } - if (++i >= end) { - break; - } + while ((src[i] >> 24) == GE_CMD_BONEMATRIXDATA) { + const u32 newVal = src[i] << 8; + if (dst[i] != newVal) { + Flush(); + dst[i] = newVal; } + if (++i >= end) { + break; + } + } - const int numPlusCount = (op & 0x7F) + i; - for (int num = op & 0x7F; num < numPlusCount; num += 12) { - shaderManager_->DirtyUniform(DIRTY_BONEMATRIX0 << (num / 12)); - } - } else { - while ((src[i] >> 24) == GE_CMD_BONEMATRIXDATA) { - dst[i] = src[i] << 8; - if (++i >= end) { - break; - } - } - - const int numPlusCount = (op & 0x7F) + i; - for (int num = op & 0x7F; num < numPlusCount; num += 12) { - gstate_c.deferredVertTypeDirty |= DIRTY_BONEMATRIX0 << (num / 12); - } + const int numPlusCount = (op & 0x7F) + i; + for (int num = op & 0x7F; num < numPlusCount; num += 12) { + shaderManager_->DirtyUniform(DIRTY_BONEMATRIX0 << (num / 12)); } const int count = i; @@ -1354,13 +1316,8 @@ void GPU_Vulkan::Execute_BoneMtxData(u32 op, u32 diff) { int num = gstate.boneMatrixNumber & 0x7F; u32 newVal = op << 8; if (num < 96 && newVal != ((const u32 *)gstate.boneMatrix)[num]) { - // Bone matrices should NOT flush when software skinning is enabled! - if (!g_Config.bSoftwareSkinning || (gstate.vertType & GE_VTYPE_MORPHCOUNT_MASK) != 0) { - Flush(); - shaderManager_->DirtyUniform(DIRTY_BONEMATRIX0 << (num / 12)); - } else { - gstate_c.deferredVertTypeDirty |= DIRTY_BONEMATRIX0 << (num / 12); - } + Flush(); + shaderManager_->DirtyUniform(DIRTY_BONEMATRIX0 << (num / 12)); ((u32 *)gstate.boneMatrix)[num] = newVal; } num++; @@ -1916,13 +1873,8 @@ void GPU_Vulkan::FastLoadBoneMatrix(u32 target) { if ((num - 12 * mtxNum) != 0) { uniformsToDirty |= DIRTY_BONEMATRIX0 << ((mtxNum + 1) & 7); } - - if (!g_Config.bSoftwareSkinning || (gstate.vertType & GE_VTYPE_MORPHCOUNT_MASK) != 0) { - Flush(); - shaderManager_->DirtyUniform(uniformsToDirty); - } else { - gstate_c.deferredVertTypeDirty |= uniformsToDirty; - } + Flush(); + shaderManager_->DirtyUniform(uniformsToDirty); gstate.FastLoadBoneMatrix(target); } From 5d19f3dfb84a00decaed617ae766e870dfb0d129 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 20 Mar 2016 16:06:11 +0100 Subject: [PATCH 111/116] Decode vertex data directly into the vertex pushbuffer, saving a memcpy. --- Common/Vulkan/VulkanContext.cpp | 2 +- Common/Vulkan/VulkanImage.cpp | 2 +- Common/Vulkan/VulkanImage.h | 2 +- Common/Vulkan/VulkanMemory.h | 4 +- GPU/Vulkan/DrawEngineVulkan.cpp | 164 ++++++++++++++++-------------- GPU/Vulkan/DrawEngineVulkan.h | 12 +-- GPU/Vulkan/GPU_Vulkan.cpp | 2 - GPU/Vulkan/TextureCacheVulkan.cpp | 2 +- 8 files changed, 93 insertions(+), 97 deletions(-) diff --git a/Common/Vulkan/VulkanContext.cpp b/Common/Vulkan/VulkanContext.cpp index f0d0de5107..5fb745b513 100644 --- a/Common/Vulkan/VulkanContext.cpp +++ b/Common/Vulkan/VulkanContext.cpp @@ -31,7 +31,7 @@ using namespace std; static const char *validationLayers[] = { "VK_LAYER_GOOGLE_unique_objects", - "VK_LAYER_LUNARG_standard_validation", + //"VK_LAYER_LUNARG_standard_validation", /* "VK_LAYER_GOOGLE_threading", "VK_LAYER_LUNARG_draw_state", diff --git a/Common/Vulkan/VulkanImage.cpp b/Common/Vulkan/VulkanImage.cpp index c2cd59e6c5..01ad9e3db4 100644 --- a/Common/Vulkan/VulkanImage.cpp +++ b/Common/Vulkan/VulkanImage.cpp @@ -308,7 +308,7 @@ void VulkanTexture::CreateDirect(int w, int h, int numMips, VkFormat format, VkI assert(res == VK_SUCCESS); } -void VulkanTexture::UploadMip(int mip, int mipWidth, int mipHeight, VkBuffer buffer, size_t offset, size_t rowLength) { +void VulkanTexture::UploadMip(int mip, int mipWidth, int mipHeight, VkBuffer buffer, uint32_t offset, size_t rowLength) { VkBufferImageCopy copy_region = {}; copy_region.bufferOffset = offset; copy_region.bufferRowLength = (uint32_t)rowLength; diff --git a/Common/Vulkan/VulkanImage.h b/Common/Vulkan/VulkanImage.h index 482f52f98c..fe2dbe6dbd 100644 --- a/Common/Vulkan/VulkanImage.h +++ b/Common/Vulkan/VulkanImage.h @@ -27,7 +27,7 @@ public: // Fast uploads from buffer. Mipmaps supported. Usage must at least include VK_IMAGE_USAGE_TRANSFER_DST_BIT in order to use UploadMip. void CreateDirect(int w, int h, int numMips, VkFormat format, VkImageUsageFlags usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT); - void UploadMip(int mip, int mipWidth, int mipHeight, VkBuffer buffer, size_t offset, size_t rowLength); // rowLength is in pixels + void UploadMip(int mip, int mipWidth, int mipHeight, VkBuffer buffer, uint32_t offset, size_t rowLength); // rowLength is in pixels void EndCreate(); int GetNumMips() const { return numMips_; } void Destroy(); diff --git a/Common/Vulkan/VulkanMemory.h b/Common/Vulkan/VulkanMemory.h index ff0f7d6519..4d35fd8c6a 100644 --- a/Common/Vulkan/VulkanMemory.h +++ b/Common/Vulkan/VulkanMemory.h @@ -86,9 +86,9 @@ public: } // "Zero-copy" variant - you can write the data directly as you compute it. - void *Push(size_t size, size_t *bindOffset, VkBuffer *vkbuf) { + void *Push(size_t size, uint32_t *bindOffset, VkBuffer *vkbuf) { size_t off = Allocate(size, vkbuf); - *bindOffset = off; + *bindOffset = (uint32_t)off; return writePtr_ + off; } diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index 8f1b71a3df..14f4287ba8 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -64,7 +64,6 @@ enum { DrawEngineVulkan::DrawEngineVulkan(VulkanContext *vulkan) : vulkan_(vulkan), - decodedVerts_(0), prevPrim_(GE_PRIM_INVALID), lastVTypeID_(-1), pipelineManager_(nullptr), @@ -72,7 +71,6 @@ DrawEngineVulkan::DrawEngineVulkan(VulkanContext *vulkan) framebufferManager_(nullptr), numDrawCalls(0), vertexCountInDrawCalls(0), - decodeCounter_(0), fboTexNeedBind_(false), fboTexBound_(false), curFrame_(0) { @@ -298,9 +296,87 @@ void DrawEngineVulkan::SubmitPrim(void *verts, void *inds, GEPrimitiveType prim, } } -void DrawEngineVulkan::DecodeVerts() { - for (; decodeCounter_ < numDrawCalls; decodeCounter_++) { - DecodeVertsStep(decoded); +void DrawEngineVulkan::DecodeVerts(VulkanPushBuffer *push, uint32_t *bindOffset, VkBuffer *vkbuf) { + int decodedVerts = 0; + + u8 *dest = decoded; + + // Figure out how much pushbuffer space we need to allocate. + if (push) { + int vertsToDecode = 0; + for (int i = 0; i < numDrawCalls; i++) { + const DeferredDrawCall &dc = drawCalls[i]; + if (dc.indexType == GE_VTYPE_IDX_NONE >> GE_VTYPE_IDX_SHIFT) { + vertsToDecode += dc.indexUpperBound - dc.indexLowerBound + 1; + } else { + vertsToDecode += dc.vertexCount; + } + } + dest = (u8 *)push->Push(vertsToDecode * dec_->GetDecVtxFmt().stride, bindOffset, vkbuf); + } + + for (int i = 0; i < numDrawCalls; i++) { + const DeferredDrawCall &dc = drawCalls[i]; + + indexGen.SetIndex(decodedVerts); + int indexLowerBound = dc.indexLowerBound, indexUpperBound = dc.indexUpperBound; + + void *inds = dc.inds; + if (dc.indexType == GE_VTYPE_IDX_NONE >> GE_VTYPE_IDX_SHIFT) { + // Decode the verts and apply morphing. Simple. + dec_->DecodeVerts(dest + decodedVerts * (int)dec_->GetDecVtxFmt().stride, + dc.verts, indexLowerBound, indexUpperBound); + decodedVerts += indexUpperBound - indexLowerBound + 1; + indexGen.AddPrim(dc.prim, dc.vertexCount); + } else { + // It's fairly common that games issue long sequences of PRIM calls, with differing + // inds pointer but the same base vertex pointer. We'd like to reuse vertices between + // these as much as possible, so we make sure here to combine as many as possible + // into one nice big drawcall, sharing data. + + // 1. Look ahead to find the max index, only looking as "matching" drawcalls. + // Expand the lower and upper bounds as we go. + int lastMatch = i; + const int total = numDrawCalls; + for (int j = i + 1; j < total; ++j) { + if (drawCalls[j].verts != dc.verts) + break; + + indexLowerBound = std::min(indexLowerBound, (int)drawCalls[j].indexLowerBound); + indexUpperBound = std::max(indexUpperBound, (int)drawCalls[j].indexUpperBound); + lastMatch = j; + } + + // 2. Loop through the drawcalls, translating indices as we go. + switch (dc.indexType) { + case GE_VTYPE_IDX_8BIT >> GE_VTYPE_IDX_SHIFT: + for (int j = i; j <= lastMatch; j++) { + indexGen.TranslatePrim(drawCalls[j].prim, drawCalls[j].vertexCount, (const u8 *)drawCalls[j].inds, indexLowerBound); + } + break; + case GE_VTYPE_IDX_16BIT >> GE_VTYPE_IDX_SHIFT: + for (int j = i; j <= lastMatch; j++) { + indexGen.TranslatePrim(drawCalls[j].prim, drawCalls[j].vertexCount, (const u16 *)drawCalls[j].inds, indexLowerBound); + } + break; + } + + const int vertexCount = indexUpperBound - indexLowerBound + 1; + + // This check is a workaround for Pangya Fantasy Golf, which sends bogus index data when switching items in "My Room" sometimes. + if (decodedVerts + vertexCount > VERTEX_BUFFER_MAX) { + return; + } + + // 3. Decode that range of vertex data. + dec_->DecodeVerts(dest + decodedVerts * (int)dec_->GetDecVtxFmt().stride, + dc.verts, indexLowerBound, indexUpperBound); + decodedVerts += vertexCount; + + // 4. Advance indexgen vertex counter. + indexGen.Advance(vertexCount); + i = lastMatch; + } } // Sanity check if (indexGen.Prim() < 0) { @@ -310,73 +386,6 @@ void DrawEngineVulkan::DecodeVerts() { } } -void DrawEngineVulkan::DecodeVertsStep(u8 *decoded) { - const int i = decodeCounter_; - - const DeferredDrawCall &dc = drawCalls[i]; - - indexGen.SetIndex(decodedVerts_); - int indexLowerBound = dc.indexLowerBound, indexUpperBound = dc.indexUpperBound; - - u32 indexType = dc.indexType; - void *inds = dc.inds; - if (indexType == GE_VTYPE_IDX_NONE >> GE_VTYPE_IDX_SHIFT) { - // Decode the verts and apply morphing. Simple. - dec_->DecodeVerts(decoded + decodedVerts_ * (int)dec_->GetDecVtxFmt().stride, - dc.verts, indexLowerBound, indexUpperBound); - decodedVerts_ += indexUpperBound - indexLowerBound + 1; - indexGen.AddPrim(dc.prim, dc.vertexCount); - } else { - // It's fairly common that games issue long sequences of PRIM calls, with differing - // inds pointer but the same base vertex pointer. We'd like to reuse vertices between - // these as much as possible, so we make sure here to combine as many as possible - // into one nice big drawcall, sharing data. - - // 1. Look ahead to find the max index, only looking as "matching" drawcalls. - // Expand the lower and upper bounds as we go. - int lastMatch = i; - const int total = numDrawCalls; - for (int j = i + 1; j < total; ++j) { - if (drawCalls[j].verts != dc.verts) - break; - - indexLowerBound = std::min(indexLowerBound, (int)drawCalls[j].indexLowerBound); - indexUpperBound = std::max(indexUpperBound, (int)drawCalls[j].indexUpperBound); - lastMatch = j; - } - - // 2. Loop through the drawcalls, translating indices as we go. - switch (indexType) { - case GE_VTYPE_IDX_8BIT >> GE_VTYPE_IDX_SHIFT: - for (int j = i; j <= lastMatch; j++) { - indexGen.TranslatePrim(drawCalls[j].prim, drawCalls[j].vertexCount, (const u8 *)drawCalls[j].inds, indexLowerBound); - } - break; - case GE_VTYPE_IDX_16BIT >> GE_VTYPE_IDX_SHIFT: - for (int j = i; j <= lastMatch; j++) { - indexGen.TranslatePrim(drawCalls[j].prim, drawCalls[j].vertexCount, (const u16 *)drawCalls[j].inds, indexLowerBound); - } - break; - } - - const int vertexCount = indexUpperBound - indexLowerBound + 1; - - // This check is a workaround for Pangya Fantasy Golf, which sends bogus index data when switching items in "My Room" sometimes. - if (decodedVerts_ + vertexCount > VERTEX_BUFFER_MAX) { - return; - } - - // 3. Decode that range of vertex data. - dec_->DecodeVerts(decoded + decodedVerts_ * (int)dec_->GetDecVtxFmt().stride, - dc.verts, indexLowerBound, indexUpperBound); - decodedVerts_ += vertexCount; - - // 4. Advance indexgen vertex counter. - indexGen.Advance(vertexCount); - decodeCounter_ = lastMatch; - } -} - inline u32 ComputeMiniHashRange(const void *ptr, size_t sz) { // Switch to u32 units. const u32 *p = (const u32 *)ptr; @@ -520,7 +529,9 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { int maxIndex = 0; bool useElements = true; - DecodeVerts(); + // Decode directly into the pushbuffer + VkBuffer vbuf; + DecodeVerts(frame->pushVertex, &vbOffset, &vbuf); gpuStats.numUncachedVertsDrawn += indexGen.VertexCount(); useElements = !indexGen.SeenOnlyPurePrims(); vertexCount = indexGen.VertexCount(); @@ -578,8 +589,6 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { vkCmdBindDescriptorSets(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout_, 0, 1, &ds, 3, dynamicUBOOffsets); int stride = dec_->GetDecVtxFmt().stride; - VkBuffer vbuf; - vbOffset = (uint32_t)frame->pushVertex->Push(decoded, indexGen.MaxIndex() * stride, &vbuf); VkDeviceSize offsets[1] = { vbOffset }; if (useElements) { @@ -594,7 +603,8 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { vkCmdDraw(cmd_, vertexCount, 1, 0, 0); } } else { - DecodeVerts(); + // Decode to "decoded" + DecodeVerts(nullptr, nullptr, nullptr); bool hasColor = (lastVTypeID_ & GE_VTYPE_COL_MASK) != GE_VTYPE_COL_NONE; if (gstate.isModeThrough()) { gstate_c.vertexFullAlpha = gstate_c.vertexFullAlpha && (hasColor || gstate.getMaterialAmbientA() == 255); @@ -746,10 +756,8 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { gpuStats.numVertsSubmitted += vertexCountInDrawCalls; indexGen.Reset(); - decodedVerts_ = 0; numDrawCalls = 0; vertexCountInDrawCalls = 0; - decodeCounter_ = 0; prevPrim_ = GE_PRIM_INVALID; gstate_c.vertexFullAlpha = true; framebufferManager_->SetColorUpdated(gstate_c.skipDrawReason); diff --git a/GPU/Vulkan/DrawEngineVulkan.h b/GPU/Vulkan/DrawEngineVulkan.h index edffc85522..62a266a187 100644 --- a/GPU/Vulkan/DrawEngineVulkan.h +++ b/GPU/Vulkan/DrawEngineVulkan.h @@ -123,12 +123,6 @@ public: DoFlush(cmd); } - void FinishDeferred() { - if (!numDrawCalls) - return; - DecodeVerts(); - } - bool IsCodePtrVertexDecoder(const u8 *ptr) const; void DispatchFlush() override { Flush(cmd_); } @@ -148,8 +142,7 @@ public: void EndFrame(); private: - void DecodeVerts(); - void DecodeVertsStep(u8 *decoded); + void DecodeVerts(VulkanPushBuffer *push, uint32_t *bindOffset, VkBuffer *vkbuf); void DoFlush(VkCommandBuffer cmd); VkDescriptorSet GetDescriptorSet(VkImageView imageView, VkSampler sampler, VkBuffer base, VkBuffer light, VkBuffer bone); @@ -213,7 +206,6 @@ private: // Vertex collector state IndexGenerator indexGen; - int decodedVerts_; GEPrimitiveType prevPrim_; u32 lastVTypeID_; @@ -235,8 +227,6 @@ private: int numDrawCalls; int vertexCountInDrawCalls; - int decodeCounter_; - bool fboTexNeedBind_; bool fboTexBound_; }; diff --git a/GPU/Vulkan/GPU_Vulkan.cpp b/GPU/Vulkan/GPU_Vulkan.cpp index de84577aad..a7c345bb6b 100644 --- a/GPU/Vulkan/GPU_Vulkan.cpp +++ b/GPU/Vulkan/GPU_Vulkan.cpp @@ -672,8 +672,6 @@ void GPU_Vulkan::FastRunLoop(DisplayList &list) { } void GPU_Vulkan::FinishDeferred() { - // This finishes reading any vertex data that is pending. - drawEngine_.FinishDeferred(); } void GPU_Vulkan::ProcessEvent(GPUEvent ev) { diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index 86e0f4a991..b21c252491 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -1481,7 +1481,7 @@ void TextureCacheVulkan::SetTexture(VulkanPushBuffer *uploadBuffer) { int bpp = dstFmt == VULKAN_8888_FORMAT ? 4 : 2; int stride = (mipWidth * bpp + 15) & ~15; int size = stride * mipHeight; - size_t bufferOffset; + uint32_t bufferOffset; VkBuffer texBuf; void *data = uploadBuffer->Push(size, &bufferOffset, &texBuf); LoadTextureLevel(*entry, (uint8_t *)data, stride, i, replaceImages, scaleFactor, dstFmt); From 0b1cfaf751bb97f40af1ba8060c51afd6d8eb212 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 20 Mar 2016 16:33:34 +0100 Subject: [PATCH 112/116] Be more economical with UBO pushbuffer space by reusing the last data when possible. --- Common/Vulkan/VulkanMemory.h | 1 + GPU/Common/GPUStateUtils.cpp | 1 + GPU/Vulkan/DrawEngineVulkan.cpp | 84 ++++++++++++++-------- GPU/Vulkan/DrawEngineVulkan.h | 8 +++ GPU/Vulkan/PipelineManagerVulkan.cpp | 12 +++- GPU/Vulkan/ShaderManagerVulkan.cpp | 21 +++--- GPU/Vulkan/ShaderManagerVulkan.h | 11 ++- GPU/Vulkan/VertexShaderGeneratorVulkan.cpp | 4 +- GPU/Vulkan/VertexShaderGeneratorVulkan.h | 2 +- 9 files changed, 98 insertions(+), 46 deletions(-) diff --git a/Common/Vulkan/VulkanMemory.h b/Common/Vulkan/VulkanMemory.h index 4d35fd8c6a..8ea4cb08db 100644 --- a/Common/Vulkan/VulkanMemory.h +++ b/Common/Vulkan/VulkanMemory.h @@ -56,6 +56,7 @@ public: size_t Allocate(size_t numBytes, VkBuffer *vkbuf) { size_t out = offset_; offset_ += (numBytes + 3) & ~3; // Round up to 4 bytes. + if (offset_ >= size_) { // TODO: Allocate a second buffer, then combine them on the next frame. #ifdef _WIN32 diff --git a/GPU/Common/GPUStateUtils.cpp b/GPU/Common/GPUStateUtils.cpp index 54120aa7ec..0762ddd4f0 100644 --- a/GPU/Common/GPUStateUtils.cpp +++ b/GPU/Common/GPUStateUtils.cpp @@ -544,6 +544,7 @@ float FromScaledDepth(float z) { void ConvertViewportAndScissor(bool useBufferedRendering, float renderWidth, float renderHeight, int bufferWidth, int bufferHeight, ViewportAndScissor &out) { bool throughmode = gstate.isModeThrough(); out.dirtyProj = false; + out.dirtyDepth = false; float renderWidthFactor, renderHeightFactor; float renderX = 0.0f, renderY = 0.0f; diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index 14f4287ba8..173bbfc38b 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -130,7 +130,7 @@ DrawEngineVulkan::DrawEngineVulkan(VulkanContext *vulkan) assert(VK_SUCCESS == res); VkDescriptorPoolSize dpTypes[2]; - dpTypes[0].descriptorCount = 800; + dpTypes[0].descriptorCount = 2048; dpTypes[0].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; dpTypes[1].descriptorCount = 200; dpTypes[1].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; @@ -213,6 +213,8 @@ void DrawEngineVulkan::BeginFrame() { frame->pushUBO->Begin(vulkan_->GetDevice()); frame->pushVertex->Begin(vulkan_->GetDevice()); frame->pushIndex->Begin(vulkan_->GetDevice()); + + DirtyAllUBOs(); } void DrawEngineVulkan::EndFrame() { @@ -411,6 +413,9 @@ VkDescriptorSet DrawEngineVulkan::GetDescriptorSet(VkImageView imageView, VkSamp key.base_ = base; key.light_ = light; key.bone_ = bone; + assert(base != VK_NULL_HANDLE); + assert(light != VK_NULL_HANDLE); + assert(bone != VK_NULL_HANDLE); FrameData *frame = &frame_[curFrame_ & 1]; auto iter = frame->descSets.find(key); @@ -455,19 +460,24 @@ VkDescriptorSet DrawEngineVulkan::GetDescriptorSet(VkImageView imageView, VkSamp // Skipping 2nd texture for now. // Uniform buffer objects VkDescriptorBufferInfo buf[3]; - buf[0].buffer = base; - buf[0].offset = 0; - buf[0].range = sizeof(UB_VS_FS_Base); - buf[1].buffer = light; - buf[1].offset = 0; - buf[1].range = sizeof(UB_VS_Lights); - buf[2].buffer = bone; - buf[2].offset = 0; - buf[2].range = sizeof(UB_VS_Bones); - for (int i = 0; i < 3; i++) { + int count = 0; + buf[count].buffer = base; + buf[count].offset = 0; + buf[count].range = sizeof(UB_VS_FS_Base); + count++; + buf[count].buffer = light; + buf[count].offset = 0; + buf[count].range = sizeof(UB_VS_Lights); + count++; + buf[count].buffer = bone; + buf[count].offset = 0; + buf[count].range = sizeof(UB_VS_Bones); + count++; + for (int i = 0; i < count; i++) { writes[n].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; writes[n].pNext = nullptr; writes[n].dstBinding = DRAW_BINDING_DYNUBO_BASE + i; + writes[n].dstArrayElement = 0; writes[n].pBufferInfo = &buf[i]; writes[n].dstSet = desc; writes[n].descriptorCount = 1; @@ -481,6 +491,16 @@ VkDescriptorSet DrawEngineVulkan::GetDescriptorSet(VkImageView imageView, VkSamp return desc; } +void DrawEngineVulkan::DirtyAllUBOs() { + baseUBOOffset = 0; + lightUBOOffset = 0; + boneUBOOffset = 0; + baseBuf = VK_NULL_HANDLE; + lightBuf = VK_NULL_HANDLE; + boneBuf = VK_NULL_HANDLE; + dirtyUniforms_ = DIRTY_BASE_UNIFORMS | DIRTY_LIGHT_UNIFORMS | DIRTY_BONE_UNIFORMS; +} + // The inline wrapper in the header checks for numDrawCalls == 0d void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { gpuStats.numFlushes++; @@ -514,11 +534,6 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { VulkanVertexShader *vshader = nullptr; VulkanFragmentShader *fshader = nullptr; - // TODO: Keep these between calls if not dirty. - uint32_t baseUBOOffset = 0; - uint32_t lightUBOOffset = 0; - uint32_t boneUBOOffset = 0; - uint32_t ibOffset = 0; uint32_t vbOffset = 0; @@ -560,7 +575,9 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { float bc[4]; Uint8x4ToFloat4(bc, dynState.blendColor); vkCmdSetBlendConstants(cmd_, bc); - shaderManager_->UpdateUniforms(); + + dirtyUniforms_ |= shaderManager_->UpdateUniforms(); + shaderManager_->GetShaders(prim, lastVTypeID_, &vshader, &fshader, useHWTransform); VulkanPipeline *pipeline = pipelineManager_->GetOrCreatePipeline(pipelineLayout_, pipelineKey, dec_, vshader, fshader, true); if (!pipeline) { @@ -569,16 +586,17 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { } vkCmdBindPipeline(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline->pipeline); // TODO: Avoid if same as last draw. - // TODO: Make only one allocation so all three end up in the same buffer. - VkBuffer baseBuf, lightBuf, boneBuf; - if (pipeline->uniformBlocks & UB_VS_FS_BASE) { + if ((dirtyUniforms_ & DIRTY_BASE_UNIFORMS) || baseBuf == VK_NULL_HANDLE) { baseUBOOffset = shaderManager_->PushBaseBuffer(frame->pushUBO, &baseBuf); + dirtyUniforms_ &= ~DIRTY_BASE_UNIFORMS; } - if (pipeline->uniformBlocks & UB_VS_LIGHTS) { + if ((dirtyUniforms_ & DIRTY_LIGHT_UNIFORMS) || lightBuf == VK_NULL_HANDLE) { lightUBOOffset = shaderManager_->PushLightBuffer(frame->pushUBO, &lightBuf); + dirtyUniforms_ &= ~DIRTY_LIGHT_UNIFORMS; } - if (pipeline->uniformBlocks & UB_VS_BONES) { + if ((dirtyUniforms_ & DIRTY_BONE_UNIFORMS) || boneBuf == VK_NULL_HANDLE) { boneUBOOffset = shaderManager_->PushBoneBuffer(frame->pushUBO, &boneBuf); + dirtyUniforms_ &= ~DIRTY_BONE_UNIFORMS; } VkDescriptorSet ds = GetDescriptorSet(imageView, sampler, baseBuf, lightBuf, boneBuf); @@ -656,7 +674,6 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { vkCmdSetStencilCompareMask(cmd_, VK_STENCIL_FRONT_AND_BACK, dynState.stencilCompareMask); } if (result.setStencil) { - // hey, dynamic state! vkCmdSetStencilReference(cmd_, VK_STENCIL_FRONT_AND_BACK, result.stencilValue); } else if (dynState.useStencil) { vkCmdSetStencilReference(cmd_, VK_STENCIL_FRONT_AND_BACK, dynState.stencilRef); @@ -665,7 +682,8 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { float bc[4]; Uint8x4ToFloat4(bc, dynState.blendColor); vkCmdSetBlendConstants(cmd_, bc); - shaderManager_->UpdateUniforms(); + dirtyUniforms_ |= shaderManager_->UpdateUniforms(); + shaderManager_->GetShaders(prim, lastVTypeID_, &vshader, &fshader, useHWTransform); VulkanPipeline *pipeline = pipelineManager_->GetOrCreatePipeline(pipelineLayout_, pipelineKey, dec_, vshader, fshader, false); if (!pipeline) { @@ -674,12 +692,21 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { } vkCmdBindPipeline(cmd_, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline->pipeline); // TODO: Avoid if same as last draw. - VkBuffer uboBuf; - if (pipeline->uniformBlocks & UB_VS_FS_BASE) { - baseUBOOffset = shaderManager_->PushBaseBuffer(frame->pushUBO, &uboBuf); + if ((dirtyUniforms_ & DIRTY_BASE_UNIFORMS) || baseBuf == VK_NULL_HANDLE) { + baseUBOOffset = shaderManager_->PushBaseBuffer(frame->pushUBO, &baseBuf); + dirtyUniforms_ &= ~DIRTY_BASE_UNIFORMS; + } + // Even if the first draw is through-mode, make sure we at least have one copy of these uniforms buffered + if ((dirtyUniforms_ & DIRTY_LIGHT_UNIFORMS) || lightBuf == VK_NULL_HANDLE) { + lightUBOOffset = shaderManager_->PushLightBuffer(frame->pushUBO, &lightBuf); + dirtyUniforms_ &= ~DIRTY_LIGHT_UNIFORMS; + } + if ((dirtyUniforms_ & DIRTY_BONE_UNIFORMS) || boneBuf == VK_NULL_HANDLE) { + boneUBOOffset = shaderManager_->PushBoneBuffer(frame->pushUBO, &boneBuf); + dirtyUniforms_ &= ~DIRTY_BONE_UNIFORMS; } - VkDescriptorSet ds = GetDescriptorSet(imageView, sampler, uboBuf, uboBuf, uboBuf); + VkDescriptorSet ds = GetDescriptorSet(imageView, sampler, baseBuf, lightBuf, boneBuf); const uint32_t dynamicUBOOffsets[3] = { baseUBOOffset, lightUBOOffset, boneUBOOffset, }; @@ -690,7 +717,6 @@ void DrawEngineVulkan::DoFlush(VkCommandBuffer cmd) { vbOffset = (uint32_t)frame->pushVertex->Push(drawBuffer, maxIndex * sizeof(TransformedVertex), &vbuf); ibOffset = (uint32_t)frame->pushIndex->Push(inds, sizeof(short) * numTrans, &ibuf); VkDeviceSize offsets[1] = { vbOffset }; - // TODO: Have a buffer per frame, use a walking buffer pointer // TODO: Avoid rebinding if the vertex size stays the same by using the offset arguments vkCmdBindVertexBuffers(cmd_, 0, 1, &vbuf, offsets); vkCmdBindIndexBuffer(cmd_, ibuf, ibOffset, VK_INDEX_TYPE_UINT16); diff --git a/GPU/Vulkan/DrawEngineVulkan.h b/GPU/Vulkan/DrawEngineVulkan.h index 62a266a187..afe1a8d606 100644 --- a/GPU/Vulkan/DrawEngineVulkan.h +++ b/GPU/Vulkan/DrawEngineVulkan.h @@ -141,6 +141,8 @@ public: void BeginFrame(); void EndFrame(); + void DirtyAllUBOs(); + private: void DecodeVerts(VulkanPushBuffer *push, uint32_t *bindOffset, VkBuffer *vkbuf); void DoFlush(VkCommandBuffer cmd); @@ -223,6 +225,12 @@ private: enum { MAX_DEFERRED_DRAW_CALLS = 128 }; + uint32_t dirtyUniforms_; + uint32_t baseUBOOffset; + uint32_t lightUBOOffset; + uint32_t boneUBOOffset; + VkBuffer baseBuf, lightBuf, boneBuf; + DeferredDrawCall drawCalls[MAX_DEFERRED_DRAW_CALLS]; int numDrawCalls; int vertexCountInDrawCalls; diff --git a/GPU/Vulkan/PipelineManagerVulkan.cpp b/GPU/Vulkan/PipelineManagerVulkan.cpp index 9f9fd679f2..9a9998b6b8 100644 --- a/GPU/Vulkan/PipelineManagerVulkan.cpp +++ b/GPU/Vulkan/PipelineManagerVulkan.cpp @@ -98,7 +98,9 @@ int SetupVertexAttribsPretransformed(VkVertexInputAttributeDescription attrs[], return count; } -static VulkanPipeline *CreateVulkanPipeline(VkDevice device, VkPipelineCache pipelineCache, VkPipelineLayout layout, VkRenderPass renderPass, const VulkanPipelineRasterStateKey &key, const VertexDecoder *vtxDec, VulkanVertexShader *vs, VulkanFragmentShader *fs, bool useHwTransform) { +static VulkanPipeline *CreateVulkanPipeline(VkDevice device, VkPipelineCache pipelineCache, + VkPipelineLayout layout, VkRenderPass renderPass, const VulkanPipelineRasterStateKey &key, + const VertexDecoder *vtxDec, VulkanVertexShader *vs, VulkanFragmentShader *fs, bool useHwTransform) { VkPipelineColorBlendAttachmentState blend0 = {}; blend0.blendEnable = key.blendEnable; if (key.blendEnable) { @@ -262,8 +264,12 @@ static VulkanPipeline *CreateVulkanPipeline(VkDevice device, VkPipelineCache pip vulkanPipeline->pipeline = pipeline; vulkanPipeline->uniformBlocks = UB_VS_FS_BASE; if (useHwTransform) { - // TODO: Remove BONES and LIGHTS when those aren't used. - vulkanPipeline->uniformBlocks |= UB_VS_BONES | UB_VS_LIGHTS; + if (vs->HasLights()) { + vulkanPipeline->uniformBlocks |= UB_VS_LIGHTS; + } + if (vs->HasBones()) { + vulkanPipeline->uniformBlocks |= UB_VS_BONES; + } } return vulkanPipeline; } diff --git a/GPU/Vulkan/ShaderManagerVulkan.cpp b/GPU/Vulkan/ShaderManagerVulkan.cpp index abeefea128..48c8e1172c 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.cpp +++ b/GPU/Vulkan/ShaderManagerVulkan.cpp @@ -98,8 +98,8 @@ std::string VulkanFragmentShader::GetShaderString(DebugShaderStringType type) co } } -VulkanVertexShader::VulkanVertexShader(VulkanContext *vulkan, ShaderID id, const char *code, int vertType, bool useHWTransform) - : vulkan_(vulkan), id_(id), failed_(false), useHWTransform_(useHWTransform), module_(VK_NULL_HANDLE) { +VulkanVertexShader::VulkanVertexShader(VulkanContext *vulkan, ShaderID id, const char *code, int vertType, bool useHWTransform, bool usesLighting) + : vulkan_(vulkan), id_(id), failed_(false), useHWTransform_(useHWTransform), module_(VK_NULL_HANDLE), usesLighting_(usesLighting) { source_ = code; std::string errorMessage; std::vector spirv; @@ -462,13 +462,15 @@ void ShaderManagerVulkan::DirtyLastShader() { // disables vertex arrays lastFShader_ = nullptr; } -void ShaderManagerVulkan::UpdateUniforms() { +uint32_t ShaderManagerVulkan::UpdateUniforms() { + uint32_t dirty = globalDirty_; if (globalDirty_) { - BaseUpdateUniforms(globalDirty_); - LightUpdateUniforms(globalDirty_); - BoneUpdateUniforms(globalDirty_); - globalDirty_ = 0; + BaseUpdateUniforms(dirty); + LightUpdateUniforms(dirty); + BoneUpdateUniforms(dirty); } + globalDirty_ = 0; + return dirty; } void ShaderManagerVulkan::GetShaders(int prim, u32 vertType, VulkanVertexShader **vshader, VulkanFragmentShader **fshader, bool useHWTransform) { @@ -489,8 +491,9 @@ void ShaderManagerVulkan::GetShaders(int prim, u32 vertType, VulkanVertexShader VulkanVertexShader *vs; if (vsIter == vsCache_.end()) { // Vertex shader not in cache. Let's compile it. - GenerateVulkanGLSLVertexShader(VSID, codeBuffer_); - vs = new VulkanVertexShader(vulkan_, VSID, codeBuffer_, vertType, useHWTransform); + bool usesLighting; + GenerateVulkanGLSLVertexShader(VSID, codeBuffer_, &usesLighting); + vs = new VulkanVertexShader(vulkan_, VSID, codeBuffer_, vertType, useHWTransform, usesLighting); vsCache_[VSID] = vs; } else { vs = vsIter->second; diff --git a/GPU/Vulkan/ShaderManagerVulkan.h b/GPU/Vulkan/ShaderManagerVulkan.h index 2cf794da7b..6184b2910b 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.h +++ b/GPU/Vulkan/ShaderManagerVulkan.h @@ -191,13 +191,19 @@ protected: class VulkanVertexShader { public: - VulkanVertexShader(VulkanContext *vulkan, ShaderID id, const char *code, int vertType, bool useHWTransform); + VulkanVertexShader(VulkanContext *vulkan, ShaderID id, const char *code, int vertType, bool useHWTransform, bool usesLighting); ~VulkanVertexShader(); const std::string &source() const { return source_; } bool Failed() const { return failed_; } bool UseHWTransform() const { return useHWTransform_; } + bool HasBones() const { + return id_.Bit(VS_BIT_ENABLE_BONES); + } + bool HasLights() const { + return usesLighting_; + } std::string GetShaderString(DebugShaderStringType type) const; VkShaderModule GetModule() const { return module_; } @@ -209,6 +215,7 @@ protected: std::string source_; bool failed_; bool useHWTransform_; + bool usesLighting_; ShaderID id_; }; @@ -230,7 +237,7 @@ public: std::vector DebugGetShaderIDs(DebugShaderType type); std::string DebugGetShaderString(std::string id, DebugShaderType type, DebugShaderStringType stringType); - void UpdateUniforms(); + uint32_t UpdateUniforms(); void DirtyUniform(u32 what) { globalDirty_ |= what; diff --git a/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp b/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp index a4a0ede14a..1880c74f73 100644 --- a/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp +++ b/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp @@ -102,7 +102,7 @@ enum DoLightComputation { // TODO: Skip all this if we can actually get a 16-bit depth buffer along with stencil, which // is a bit of a rare configuration, although quite common on mobile. -bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { +bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer, bool *usesLighting) { char *p = buffer; // #define USE_FOR_LOOP @@ -140,7 +140,7 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer) { // The uniforms are passed in as three "clumps" that may or may not be present. // We will memcpy the parts into place in a big buffer so we can be quite dynamic about what parts // are present and what parts aren't, but we will not be ultra detailed about it. - + *usesLighting = enableLighting || doShadeMapping; WRITE(p, "\n"); WRITE(p, "layout (std140, set = 0, binding = 2) uniform baseVars {\n%s} base;\n", ub_baseStr); if (enableLighting || doShadeMapping) diff --git a/GPU/Vulkan/VertexShaderGeneratorVulkan.h b/GPU/Vulkan/VertexShaderGeneratorVulkan.h index d953fdbd76..4f3a97bb32 100644 --- a/GPU/Vulkan/VertexShaderGeneratorVulkan.h +++ b/GPU/Vulkan/VertexShaderGeneratorVulkan.h @@ -2,4 +2,4 @@ #include "GPU/Common/ShaderId.h" -bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer); \ No newline at end of file +bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer, bool *usesLighting); \ No newline at end of file From 29bc07eb0acf3fdf0289f7f1d07cd156a3085924 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 20 Mar 2016 20:04:49 +0100 Subject: [PATCH 113/116] SoftGPU with Vulkan runs but displays black --- Core/CoreParameter.h | 4 +++- Core/System.cpp | 2 +- GPU/GPU.cpp | 5 +++-- GPU/GPU.h | 4 +++- GPU/Software/SoftGpu.cpp | 10 ++-------- GPU/Software/SoftGpu.h | 7 ++++++- UI/EmuScreen.cpp | 1 + ext/native/thin3d/thin3d_vulkan.cpp | 2 ++ 8 files changed, 21 insertions(+), 14 deletions(-) diff --git a/Core/CoreParameter.h b/Core/CoreParameter.h index 1cbe2aab12..e19984a171 100644 --- a/Core/CoreParameter.h +++ b/Core/CoreParameter.h @@ -38,14 +38,16 @@ enum GPUCore { class FileLoader; class GraphicsContext; +class Thin3DContext; // PSP_CoreParameter() struct CoreParameter { - CoreParameter() : collectEmuLog(0), unthrottle(false), fpsLimit(0), updateRecent(true), freezeNext(false), frozen(false), mountIsoLoader(nullptr) {} + CoreParameter() : thin3d(nullptr), collectEmuLog(0), unthrottle(false), fpsLimit(0), updateRecent(true), freezeNext(false), frozen(false), mountIsoLoader(nullptr) {} CPUCore cpuCore; GPUCore gpuCore; GraphicsContext *graphicsContext; // TODO: Find a better place. + Thin3DContext *thin3d; bool enableSound; // there aren't multiple sound cores. std::string fileToStart; diff --git a/Core/System.cpp b/Core/System.cpp index 110f88f04f..d1613cc617 100644 --- a/Core/System.cpp +++ b/Core/System.cpp @@ -425,7 +425,7 @@ bool PSP_InitUpdate(std::string *error_string) { bool success = coreParameter.fileToStart != ""; *error_string = coreParameter.errorString; if (success) { - success = GPU_Init(coreParameter.graphicsContext); + success = GPU_Init(coreParameter.graphicsContext, coreParameter.thin3d); if (!success) { PSP_Shutdown(); *error_string = "Unable to initialize rendering engine."; diff --git a/GPU/GPU.cpp b/GPU/GPU.cpp index eb02c65748..f5bec931d5 100644 --- a/GPU/GPU.cpp +++ b/GPU/GPU.cpp @@ -45,7 +45,8 @@ static void SetGPU(T *obj) { #ifdef USE_CRT_DBG #undef new #endif -bool GPU_Init(GraphicsContext *ctx) { + +bool GPU_Init(GraphicsContext *ctx, Thin3DContext *thin3d) { switch (PSP_CoreParameter().gpuCore) { case GPU_NULL: SetGPU(new NullGPU()); @@ -54,7 +55,7 @@ bool GPU_Init(GraphicsContext *ctx) { SetGPU(new GLES_GPU(ctx)); break; case GPU_SOFTWARE: - SetGPU(new SoftGPU(ctx)); + SetGPU(new SoftGPU(ctx, thin3d)); break; case GPU_DIRECTX9: #if defined(_WIN32) diff --git a/GPU/GPU.h b/GPU/GPU.h index 55c5aaf566..6989ba4d18 100644 --- a/GPU/GPU.h +++ b/GPU/GPU.h @@ -107,5 +107,7 @@ extern GPUStatistics gpuStats; extern GPUInterface *gpu; extern GPUDebugInterface *gpuDebug; -bool GPU_Init(GraphicsContext *ctx); +class Thin3DContext; + +bool GPU_Init(GraphicsContext *ctx, Thin3DContext *thin3d); void GPU_Shutdown(); diff --git a/GPU/Software/SoftGpu.cpp b/GPU/Software/SoftGpu.cpp index d14d7872e3..c9e44c2cbe 100644 --- a/GPU/Software/SoftGpu.cpp +++ b/GPU/Software/SoftGpu.cpp @@ -42,18 +42,14 @@ FormatBuffer fb; FormatBuffer depthbuf; u32 clut[4096]; -static Thin3DContext *thin3d = nullptr; -static Thin3DTexture *fbTex = nullptr; static Thin3DVertexFormat *vformat = nullptr; static Thin3DDepthStencilState *depth = nullptr; static Thin3DBuffer *vdata = nullptr; static Thin3DBuffer *idata = nullptr; -static std::vector fbTexBuffer; -SoftGPU::SoftGPU(GraphicsContext *gfxCtx) - : gfxCtx_(gfxCtx) +SoftGPU::SoftGPU(GraphicsContext *gfxCtx, Thin3DContext *_thin3D) + : gfxCtx_(gfxCtx), thin3d(_thin3D) { - thin3d = gfxCtx_->CreateThin3DContext(); fbTex = thin3d->CreateTexture(LINEAR2D, RGBA8888, 480, 272, 1, 1); std::vector components; @@ -87,8 +83,6 @@ SoftGPU::~SoftGPU() { vformat = nullptr; fbTex->Release(); fbTex = nullptr; - thin3d->Release(); - thin3d = nullptr; } void SoftGPU::SetDisplayFramebuffer(u32 framebuf, u32 stride, GEBufferFormat format) { diff --git a/GPU/Software/SoftGpu.h b/GPU/Software/SoftGpu.h index 423b4f22d3..481fd4ae6b 100644 --- a/GPU/Software/SoftGpu.h +++ b/GPU/Software/SoftGpu.h @@ -45,10 +45,12 @@ typedef struct { } FormatBuffer; class ShaderManager; +class Thin3DContext; +class Thin3DTexture; class SoftGPU : public GPUCommon { public: - SoftGPU(GraphicsContext *gfxCtx); + SoftGPU(GraphicsContext *gfxCtx, Thin3DContext *_thin3D); ~SoftGPU(); void InitClear() override {} void ExecuteOp(u32 op, u32 diff) override; @@ -102,4 +104,7 @@ private: GEBufferFormat displayFormat_; GraphicsContext *gfxCtx_; + Thin3DTexture *fbTex; + Thin3DContext *thin3d; + std::vector fbTexBuffer; }; diff --git a/UI/EmuScreen.cpp b/UI/EmuScreen.cpp index d89ab487f4..735612fd90 100644 --- a/UI/EmuScreen.cpp +++ b/UI/EmuScreen.cpp @@ -118,6 +118,7 @@ void EmuScreen::bootGame(const std::string &filename) { } // Preserve the existing graphics context. coreParam.graphicsContext = PSP_CoreParameter().graphicsContext; + coreParam.thin3d = screenManager()->getThin3DContext(); coreParam.enableSound = g_Config.bEnableSound; coreParam.fileToStart = filename; coreParam.mountIso = ""; diff --git a/ext/native/thin3d/thin3d_vulkan.cpp b/ext/native/thin3d/thin3d_vulkan.cpp index eec08f88e4..95d863c63c 100644 --- a/ext/native/thin3d/thin3d_vulkan.cpp +++ b/ext/native/thin3d/thin3d_vulkan.cpp @@ -704,6 +704,8 @@ void Thin3DVKContext::Begin(bool clear, uint32_t colorval, float depthVal, int s VkResult result = vkResetDescriptorPool(device_, frame->descriptorPool, 0); assert(result == VK_SUCCESS); + noScissor_.extent.width = pixel_xres; + noScissor_.extent.height = pixel_yres; scissorDirty_ = true; viewportDirty_ = true; } From c33c3cf3d4a3503d445017e01cf04fb3a8672807 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 20 Mar 2016 20:26:52 +0100 Subject: [PATCH 114/116] Vulkan: Add ugly temporary warning about buffered rendering not working --- UI/EmuScreen.cpp | 14 ++++++++++++++ UI/GameSettingsScreen.cpp | 2 +- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/UI/EmuScreen.cpp b/UI/EmuScreen.cpp index 735612fd90..dc20fe1c32 100644 --- a/UI/EmuScreen.cpp +++ b/UI/EmuScreen.cpp @@ -66,6 +66,10 @@ #include "UI/InstallZipScreen.h" #include "UI/ProfilerDraw.h" +#ifdef _WIN32 +#include "Windows/MainWindow.h" +#endif + EmuScreen::EmuScreen(const std::string &filename) : bootPending_(true), gamePath_(filename), invalid_(true), quit_(false), pauseTrigger_(false), saveStatePreviewShownTime_(0.0), saveStatePreview_(nullptr) { memset(axisState_, 0, sizeof(axisState_)); @@ -111,6 +115,16 @@ void EmuScreen::bootGame(const std::string &filename) { break; case GPUBackend::VULKAN: coreParam.gpuCore = GPU_VULKAN; + if (g_Config.iRenderingMode != FB_NON_BUFFERED_MODE) { +#ifdef _WIN32 + if (IDYES == MessageBox(MainWindow::GetHWND(), L"The Vulkan backend is not yet compatible with buffered rendering. Switch to non-buffered (WARNING: This will cause glitches with the other backends unless you switch back)", L"Vulkan Experimental Support", MB_ICONINFORMATION | MB_YESNO)) { + g_Config.iRenderingMode = FB_NON_BUFFERED_MODE; + } else { + errorMessage_ = "Non-buffered rendering required for Vulkan"; + return; + } +#endif + } break; } if (g_Config.bSoftwareRendering) { diff --git a/UI/GameSettingsScreen.cpp b/UI/GameSettingsScreen.cpp index 2eae30fd1a..348076e221 100644 --- a/UI/GameSettingsScreen.cpp +++ b/UI/GameSettingsScreen.cpp @@ -135,7 +135,7 @@ void GameSettingsScreen::CreateViews() { tabHolder->AddTab(ms->T("Graphics"), graphicsSettingsScroll); graphicsSettings->Add(new ItemHeader(gr->T("Rendering Mode"))); - static const char *renderingBackend[] = { "OpenGL", "Direct3D 9", "Direct3D 11", "Vulkan" }; + static const char *renderingBackend[] = { "OpenGL", "Direct3D 9", "Direct3D 11", "Vulkan (experimental)" }; PopupMultiChoice *renderingBackendChoice = graphicsSettings->Add(new PopupMultiChoice(&g_Config.iGPUBackend, gr->T("Backend"), renderingBackend, GPU_BACKEND_OPENGL, ARRAY_SIZE(renderingBackend), gr->GetName(), screenManager())); renderingBackendChoice->OnChoice.Handle(this, &GameSettingsScreen::OnRenderingBackend); #if !defined(_WIN32) From 827481d41d03f317fb489dae354581fc2be31f59 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 20 Mar 2016 20:53:46 +0100 Subject: [PATCH 115/116] Combined two uniforms to get the base UBO down to 512b, in order to not waste space (nVidia needs 256-byte alignment) --- GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp | 2 +- GPU/Vulkan/ShaderManagerVulkan.cpp | 30 +++++++++++--------- GPU/Vulkan/ShaderManagerVulkan.h | 9 +++--- GPU/Vulkan/VertexShaderGeneratorVulkan.cpp | 2 +- 4 files changed, 24 insertions(+), 19 deletions(-) diff --git a/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp b/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp index cf8a1aa513..05d479e6c8 100644 --- a/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp +++ b/GPU/Vulkan/FragmentShaderGeneratorVulkan.cpp @@ -398,7 +398,7 @@ bool GenerateVulkanGLSLFragmentShader(const ShaderID &id, char *buffer) { if (stencilToAlpha != REPLACE_ALPHA_NO) { switch (replaceAlphaWithStencilType) { case STENCIL_VALUE_UNIFORM: - replacedAlpha = "base.stencilReplaceValue"; + replacedAlpha = "base.fogcoef_stencilreplace.z"; break; case STENCIL_VALUE_ZERO: diff --git a/GPU/Vulkan/ShaderManagerVulkan.cpp b/GPU/Vulkan/ShaderManagerVulkan.cpp index 48c8e1172c..3fee8bd807 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.cpp +++ b/GPU/Vulkan/ShaderManagerVulkan.cpp @@ -169,6 +169,10 @@ ShaderManagerVulkan::ShaderManagerVulkan(VulkanContext *vulkan) memset(&ub_base, 0, sizeof(ub_base)); memset(&ub_lights, 0, sizeof(ub_lights)); memset(&ub_bones, 0, sizeof(ub_bones)); + + ILOG("sizeof(ub_base): %d", (int)sizeof(ub_base)); + ILOG("sizeof(ub_lights): %d", (int)sizeof(ub_lights)); + ILOG("sizeof(ub_bones): %d", (int)sizeof(ub_bones)); } ShaderManagerVulkan::~ShaderManagerVulkan() { @@ -202,9 +206,6 @@ void ShaderManagerVulkan::BaseUpdateUniforms(int dirtyUniforms) { if (dirtyUniforms & DIRTY_FOGCOLOR) { Uint8x3ToFloat4(ub_base.fogColor, gstate.fogcolor); } - if (dirtyUniforms & DIRTY_STENCILREPLACEVALUE) { - Uint8x1ToFloat4(ub_base.stencilReplace, gstate.getStencilTestRef()); - } if (dirtyUniforms & DIRTY_SHADERBLEND) { Uint8x3ToFloat4(ub_base.blendFixA, gstate.getFixA()); Uint8x3ToFloat4(ub_base.blendFixB, gstate.getFixB()); @@ -270,28 +271,31 @@ void ShaderManagerVulkan::BaseUpdateUniforms(int dirtyUniforms) { if (dirtyUniforms & DIRTY_TEXMATRIX) { ConvertMatrix4x3To4x4(ub_base.tex, gstate.tgenMatrix); } - if (dirtyUniforms & DIRTY_FOGCOEF) { - float fogcoef[2] = { + + // Combined two small uniforms + if (dirtyUniforms & (DIRTY_FOGCOEF | DIRTY_STENCILREPLACEVALUE)) { + float fogcoef_stencil[3] = { getFloat24(gstate.fog1), getFloat24(gstate.fog2), + (float)gstate.getStencilTestRef() }; - if (my_isinf(fogcoef[1])) { + if (my_isinf(fogcoef_stencil[1])) { // not really sure what a sensible value might be. - fogcoef[1] = fogcoef[1] < 0.0f ? -10000.0f : 10000.0f; - } else if (my_isnan(fogcoef[1])) { + fogcoef_stencil[1] = fogcoef_stencil[1] < 0.0f ? -10000.0f : 10000.0f; + } else if (my_isnan(fogcoef_stencil[1])) { // Workaround for https://github.com/hrydgard/ppsspp/issues/5384#issuecomment-38365988 // Just put the fog far away at a large finite distance. // Infinities and NaNs are rather unpredictable in shaders on many GPUs // so it's best to just make it a sane calculation. - fogcoef[0] = 100000.0f; - fogcoef[1] = 1.0f; + fogcoef_stencil[0] = 100000.0f; + fogcoef_stencil[1] = 1.0f; } #ifndef MOBILE_DEVICE - else if (my_isnanorinf(fogcoef[1]) || my_isnanorinf(fogcoef[0])) { - ERROR_LOG_REPORT_ONCE(fognan, G3D, "Unhandled fog NaN/INF combo: %f %f", fogcoef[0], fogcoef[1]); + else if (my_isnanorinf(fogcoef_stencil[1]) || my_isnanorinf(fogcoef_stencil[0])) { + ERROR_LOG_REPORT_ONCE(fognan, G3D, "Unhandled fog NaN/INF combo: %f %f", fogcoef_stencil[0], fogcoef_stencil[1]); } #endif - CopyFloat2(ub_base.fogCoef, fogcoef); + CopyFloat3(ub_base.fogCoef_stencil, fogcoef_stencil); } // Texturing diff --git a/GPU/Vulkan/ShaderManagerVulkan.h b/GPU/Vulkan/ShaderManagerVulkan.h index 6184b2910b..50f8e4388b 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.h +++ b/GPU/Vulkan/ShaderManagerVulkan.h @@ -82,6 +82,8 @@ enum { }; // TODO: Split into two structs, one for software transform and one for hardware transform, to save space. +// This is just a bit too big to fit in 512 bytes... +// 512 bytes. Probably can't get to 256 (nVidia's UBO alignment). struct UB_VS_FS_Base { float proj[16]; float proj_through[16]; @@ -90,14 +92,13 @@ struct UB_VS_FS_Base { float tex[16]; // not that common, may want to break out float uvScaleOffset[4]; float depthRange[4]; - float fogCoef[4]; + float fogCoef_stencil[4]; float matAmbient[4]; // Fragment data float fogColor[4]; float texEnvColor[4]; int alphaColorRef[4]; int colorTestMask[4]; - float stencilReplace[4]; // only first float used float blendFixA[4]; float blendFixB[4]; float texClamp[4]; @@ -112,19 +113,19 @@ R"( mat4 proj_mtx; mat4 tex_mtx; vec4 uvscaleoffset; vec4 depthRange; - vec2 fogcoef; + vec3 fogcoef_stencilreplace; vec4 matambientalpha; vec3 fogcolor; vec3 texenv; ivec4 alphacolorref; ivec4 alphacolormask; - float stencilReplaceValue; vec3 blendFixA; vec3 blendFixB; vec4 texclamp; vec2 texclampoff; )"; +// 576 bytes. Can we get down to 512? struct UB_VS_Lights { float ambientColor[4]; float materialDiffuse[4]; diff --git a/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp b/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp index 1880c74f73..6417060276 100644 --- a/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp +++ b/GPU/Vulkan/VertexShaderGeneratorVulkan.cpp @@ -505,7 +505,7 @@ bool GenerateVulkanGLSLVertexShader(const ShaderID &id, char *buffer, bool *uses // Compute fogdepth if (enableFog) - WRITE(p, " v_fogdepth = (viewPos.z + base.fogcoef.x) * base.fogcoef.y;\n"); + WRITE(p, " v_fogdepth = (viewPos.z + base.fogcoef_stencilreplace.x) * base.fogcoef_stencilreplace.y;\n"); } WRITE(p, "}\n"); return true; From 0e199272ed6a19b74c1d9889cd3091afda5ea598 Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 20 Mar 2016 20:56:33 +0100 Subject: [PATCH 116/116] Buildfix to last commit, add a comment --- GPU/Vulkan/ShaderManagerVulkan.h | 4 +++- ext/native/math/dataconv.h | 4 ++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/GPU/Vulkan/ShaderManagerVulkan.h b/GPU/Vulkan/ShaderManagerVulkan.h index 50f8e4388b..ad7b3c5ef5 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.h +++ b/GPU/Vulkan/ShaderManagerVulkan.h @@ -82,7 +82,6 @@ enum { }; // TODO: Split into two structs, one for software transform and one for hardware transform, to save space. -// This is just a bit too big to fit in 512 bytes... // 512 bytes. Probably can't get to 256 (nVidia's UBO alignment). struct UB_VS_FS_Base { float proj[16]; @@ -156,6 +155,9 @@ R"( vec4 globalAmbient; vec3 specular[4]; )"; +// With some cleverness, we could get away with uploading just half this when only the four first +// bones are being used. This is 512b, 256b would be great. +// Could also move to 4x3 matrices - would let us fit 5 bones into 256b. struct UB_VS_Bones { float bones[8][16]; }; diff --git a/ext/native/math/dataconv.h b/ext/native/math/dataconv.h index c2b540b003..46ea8b84be 100644 --- a/ext/native/math/dataconv.h +++ b/ext/native/math/dataconv.h @@ -63,6 +63,10 @@ inline void CopyFloat2(float dest[2], const float src[2]) { memcpy(dest, src, sizeof(float) * 2); } +inline void CopyFloat3(float dest[3], const float src[3]) { + memcpy(dest, src, sizeof(float) * 3); +} + inline void CopyFloat1To4(float dest[4], const float src) { dest[0] = src; dest[1] = 0.0f;