diff --git a/CMakeLists.txt b/CMakeLists.txt index bc62b35ff5..bc81d9be2b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1594,6 +1594,8 @@ set(GPU_SOURCES GPU/Debugger/Breakpoints.h GPU/Debugger/Debugger.cpp GPU/Debugger/Debugger.h + GPU/Debugger/GECommandTable.cpp + GPU/Debugger/GECommandTable.h GPU/Debugger/Playback.cpp GPU/Debugger/Playback.h GPU/Debugger/Record.cpp diff --git a/Common/Common.vcxproj b/Common/Common.vcxproj index b176b3d040..2895cdc837 100644 --- a/Common/Common.vcxproj +++ b/Common/Common.vcxproj @@ -988,9 +988,6 @@ {f761046e-6c38-4428-a5f1-38391a37bb34} - - - diff --git a/Common/Common.vcxproj.filters b/Common/Common.vcxproj.filters index 2261dddd4d..ff9fd9eaa6 100644 --- a/Common/Common.vcxproj.filters +++ b/Common/Common.vcxproj.filters @@ -901,9 +901,4 @@ ext\libpng17 - - - Math\lin - - \ No newline at end of file diff --git a/Common/Data/Collections/Hashmaps.h b/Common/Data/Collections/Hashmaps.h index 4c6664277c..8368c83db5 100644 --- a/Common/Data/Collections/Hashmaps.h +++ b/Common/Data/Collections/Hashmaps.h @@ -127,6 +127,16 @@ public: } } + template + inline void IterateMut(T func) { + for (size_t i = 0; i < map.size(); i++) { + if (state[i] == BucketState::TAKEN) { + func(map[i].key, map[i].value); + } + } + } + + // Note! Does NOT delete any pointed-to data (in case you stored pointers in the map). void Clear() { memset(state.data(), (int)BucketState::FREE, state.size()); count_ = 0; diff --git a/Common/Data/Collections/TinySet.h b/Common/Data/Collections/TinySet.h index 5c8c8e78e6..1b9933e186 100644 --- a/Common/Data/Collections/TinySet.h +++ b/Common/Data/Collections/TinySet.h @@ -99,6 +99,13 @@ struct TinySet { return slowLookup_->size() + MaxFastSize; } } + T &operator[] (size_t index) { + if (index < MaxFastSize) { + return fastLookup_[index]; + } else { + return (*slowLookup_)[index - MaxFastSize]; + } + } const T &operator[] (size_t index) const { if (index < MaxFastSize) { return fastLookup_[index]; diff --git a/Common/GPU/D3D11/thin3d_d3d11.cpp b/Common/GPU/D3D11/thin3d_d3d11.cpp index 0464235eb5..2bce9ebaff 100644 --- a/Common/GPU/D3D11/thin3d_d3d11.cpp +++ b/Common/GPU/D3D11/thin3d_d3d11.cpp @@ -82,9 +82,9 @@ public: SamplerState *CreateSamplerState(const SamplerStateDesc &desc) override; RasterState *CreateRasterState(const RasterStateDesc &desc) override; Buffer *CreateBuffer(size_t size, uint32_t usageFlags) override; - Pipeline *CreateGraphicsPipeline(const PipelineDesc &desc) override; + Pipeline *CreateGraphicsPipeline(const PipelineDesc &desc, const char *tag) override; Texture *CreateTexture(const TextureDesc &desc) override; - ShaderModule *CreateShaderModule(ShaderStage stage, ShaderLanguage language, const uint8_t *data, size_t dataSize, const std::string &tag) override; + ShaderModule *CreateShaderModule(ShaderStage stage, ShaderLanguage language, const uint8_t *data, size_t dataSize, const char *tag) override; Framebuffer *CreateFramebuffer(const FramebufferDesc &desc) override; void UpdateBuffer(Buffer *buffer, const uint8_t *data, size_t offset, size_t size, UpdateBufferFlags flags) override; @@ -920,7 +920,7 @@ Texture *D3D11DrawContext::CreateTexture(const TextureDesc &desc) { return tex; } -ShaderModule *D3D11DrawContext::CreateShaderModule(ShaderStage stage, ShaderLanguage language, const uint8_t *data, size_t dataSize, const std::string &tag) { +ShaderModule *D3D11DrawContext::CreateShaderModule(ShaderStage stage, ShaderLanguage language, const uint8_t *data, size_t dataSize, const char *tag) { if (language != ShaderLanguage::HLSL_D3D11) { ERROR_LOG(G3D, "Unsupported shader language"); return nullptr; @@ -965,7 +965,7 @@ ShaderModule *D3D11DrawContext::CreateShaderModule(ShaderStage stage, ShaderLang } if (errorMsgs) { errors = std::string((const char *)errorMsgs->GetBufferPointer(), errorMsgs->GetBufferSize()); - ERROR_LOG(G3D, "Failed compiling:\n%s\n%s", data, errors.c_str()); + ERROR_LOG(G3D, "Failed compiling %s:\n%s\n%s", tag, data, errors.c_str()); errorMsgs->Release(); } @@ -1003,7 +1003,7 @@ ShaderModule *D3D11DrawContext::CreateShaderModule(ShaderStage stage, ShaderLang return nullptr; } -Pipeline *D3D11DrawContext::CreateGraphicsPipeline(const PipelineDesc &desc) { +Pipeline *D3D11DrawContext::CreateGraphicsPipeline(const PipelineDesc &desc, const char *tag) { D3D11Pipeline *dPipeline = new D3D11Pipeline(); dPipeline->blend = (D3D11BlendState *)desc.blend; dPipeline->depthStencil = (D3D11DepthStencilState *)desc.depthStencil; diff --git a/Common/GPU/D3D9/thin3d_d3d9.cpp b/Common/GPU/D3D9/thin3d_d3d9.cpp index dc72ed898d..8554961119 100644 --- a/Common/GPU/D3D9/thin3d_d3d9.cpp +++ b/Common/GPU/D3D9/thin3d_d3d9.cpp @@ -489,13 +489,13 @@ public: } uint32_t GetDataFormatSupport(DataFormat fmt) const override; - ShaderModule *CreateShaderModule(ShaderStage stage, ShaderLanguage language, const uint8_t *data, size_t dataSize, const std::string &tag) override; + ShaderModule *CreateShaderModule(ShaderStage stage, ShaderLanguage language, const uint8_t *data, size_t dataSize, const char *tag) override; DepthStencilState *CreateDepthStencilState(const DepthStencilStateDesc &desc) override; BlendState *CreateBlendState(const BlendStateDesc &desc) override; SamplerState *CreateSamplerState(const SamplerStateDesc &desc) override; RasterState *CreateRasterState(const RasterStateDesc &desc) override; Buffer *CreateBuffer(size_t size, uint32_t usageFlags) override; - Pipeline *CreateGraphicsPipeline(const PipelineDesc &desc) override; + Pipeline *CreateGraphicsPipeline(const PipelineDesc &desc, const char *tag) override; InputLayout *CreateInputLayout(const InputLayoutDesc &desc) override; Texture *CreateTexture(const TextureDesc &desc) override; @@ -692,7 +692,7 @@ D3D9Context::D3D9Context(IDirect3D9 *d3d, IDirect3D9Ex *d3dEx, int adapterId, ID D3D9Context::~D3D9Context() { } -ShaderModule *D3D9Context::CreateShaderModule(ShaderStage stage, ShaderLanguage language, const uint8_t *data, size_t size, const std::string &tag) { +ShaderModule *D3D9Context::CreateShaderModule(ShaderStage stage, ShaderLanguage language, const uint8_t *data, size_t size, const char *tag) { D3D9ShaderModule *shader = new D3D9ShaderModule(stage, tag); if (shader->Compile(device_, data, size)) { return shader; @@ -702,15 +702,15 @@ ShaderModule *D3D9Context::CreateShaderModule(ShaderStage stage, ShaderLanguage } } -Pipeline *D3D9Context::CreateGraphicsPipeline(const PipelineDesc &desc) { +Pipeline *D3D9Context::CreateGraphicsPipeline(const PipelineDesc &desc, const char *tag) { if (!desc.shaders.size()) { - ERROR_LOG(G3D, "Pipeline requires at least one shader"); + ERROR_LOG(G3D, "Pipeline %s requires at least one shader", tag); return NULL; } D3D9Pipeline *pipeline = new D3D9Pipeline(); for (auto iter : desc.shaders) { if (!iter) { - ERROR_LOG(G3D, "NULL shader passed to CreateGraphicsPipeline"); + ERROR_LOG(G3D, "NULL shader passed to CreateGraphicsPipeline(%s)", tag); delete pipeline; return NULL; } diff --git a/Common/GPU/OpenGL/thin3d_gl.cpp b/Common/GPU/OpenGL/thin3d_gl.cpp index 5283b064ec..1d2e5822e2 100644 --- a/Common/GPU/OpenGL/thin3d_gl.cpp +++ b/Common/GPU/OpenGL/thin3d_gl.cpp @@ -336,9 +336,9 @@ public: BlendState *CreateBlendState(const BlendStateDesc &desc) override; SamplerState *CreateSamplerState(const SamplerStateDesc &desc) override; RasterState *CreateRasterState(const RasterStateDesc &desc) override; - Pipeline *CreateGraphicsPipeline(const PipelineDesc &desc) override; + Pipeline *CreateGraphicsPipeline(const PipelineDesc &desc, const char *tag) override; InputLayout *CreateInputLayout(const InputLayoutDesc &desc) override; - ShaderModule *CreateShaderModule(ShaderStage stage, ShaderLanguage language, const uint8_t *data, size_t dataSize, const std::string &tag) override; + ShaderModule *CreateShaderModule(ShaderStage stage, ShaderLanguage language, const uint8_t *data, size_t dataSize, const char *tag) override; Texture *CreateTexture(const TextureDesc &desc) override; Buffer *CreateBuffer(size_t size, uint32_t usageFlags) override; @@ -1079,7 +1079,7 @@ void OpenGLContext::UpdateBuffer(Buffer *buffer, const uint8_t *data, size_t off renderManager_.BufferSubdata(buf->buffer_, offset, size, dataCopy); } -Pipeline *OpenGLContext::CreateGraphicsPipeline(const PipelineDesc &desc) { +Pipeline *OpenGLContext::CreateGraphicsPipeline(const PipelineDesc &desc, const char *tag) { if (!desc.shaders.size()) { ERROR_LOG(G3D, "Pipeline requires at least one shader"); return nullptr; @@ -1099,7 +1099,7 @@ Pipeline *OpenGLContext::CreateGraphicsPipeline(const PipelineDesc &desc) { iter->AddRef(); pipeline->shaders.push_back(static_cast(iter)); } else { - ERROR_LOG(G3D, "ERROR: Tried to create graphics pipeline with a null shader module"); + ERROR_LOG(G3D, "ERROR: Tried to create graphics pipeline %s with a null shader module", tag); delete pipeline; return nullptr; } @@ -1118,7 +1118,7 @@ Pipeline *OpenGLContext::CreateGraphicsPipeline(const PipelineDesc &desc) { pipeline->inputLayout = (OpenGLInputLayout *)desc.inputLayout; return pipeline; } else { - ERROR_LOG(G3D, "Failed to create pipeline - shaders failed to link"); + ERROR_LOG(G3D, "Failed to create pipeline %s - shaders failed to link", tag); delete pipeline; return nullptr; } @@ -1163,7 +1163,7 @@ void OpenGLContext::ApplySamplers() { } } -ShaderModule *OpenGLContext::CreateShaderModule(ShaderStage stage, ShaderLanguage language, const uint8_t *data, size_t dataSize, const std::string &tag) { +ShaderModule *OpenGLContext::CreateShaderModule(ShaderStage stage, ShaderLanguage language, const uint8_t *data, size_t dataSize, const char *tag) { OpenGLShaderModule *shader = new OpenGLShaderModule(&renderManager_, stage, tag); if (shader->Compile(&renderManager_, language, data, dataSize)) { return shader; diff --git a/Common/GPU/ShaderWriter.cpp b/Common/GPU/ShaderWriter.cpp index 0332e4d346..b260d05fc9 100644 --- a/Common/GPU/ShaderWriter.cpp +++ b/Common/GPU/ShaderWriter.cpp @@ -24,6 +24,7 @@ const char * const hlsl_preamble_fs = "#define vec4 float4\n" "#define uvec3 uint3\n" "#define uvec4 uint4\n" +"#define ivec2 int2\n" "#define ivec3 int3\n" "#define ivec4 int4\n" "#define mat4 float4x4\n" @@ -424,6 +425,40 @@ ShaderWriter &ShaderWriter::SampleTexture2D(const char *sampName, const char *uv return *this; } +ShaderWriter &ShaderWriter::SampleTexture2DOffset(const char *sampName, const char *uv, int offX, int offY) { + switch (lang_.shaderLanguage) { + case HLSL_D3D11: + F("%s.Sample(%sSamp, %s, int2(%d, %d))", sampName, sampName, uv, offX, offY); + break; + case HLSL_D3D9: + // Not supported, we do a normal sample here to not crash or something + F("tex2D(%s, %s)", sampName, uv); + break; + default: + // Note: we ignore the sampler. make sure you bound samplers to the textures correctly. + F("%sOffset(%s, %s, ivec2(%d, %d))", lang_.texture, sampName, uv, offX, offY); + break; + } + return *this; +} + +ShaderWriter &ShaderWriter::LoadTexture2D(const char *sampName, const char *uv, int level) { + switch (lang_.shaderLanguage) { + case HLSL_D3D11: + F("%s.Load(ivec3(%s, %d))", sampName, uv, level); + break; + case HLSL_D3D9: + // Not supported, we return a bad value + C("float4(1.0, 0.0, 1.0, 1.0)"); + break; + default: + // Note: we ignore the sampler. make sure you bound samplers to the textures correctly. + F("texelFetch(%s, %s, %d)", sampName, uv, level); + break; + } + return *this; +} + ShaderWriter &ShaderWriter::GetTextureSize(const char *szVariable, const char *texName) { switch (lang_.shaderLanguage) { case HLSL_D3D11: diff --git a/Common/GPU/ShaderWriter.h b/Common/GPU/ShaderWriter.h index 7464ebc652..f6a04c828b 100644 --- a/Common/GPU/ShaderWriter.h +++ b/Common/GPU/ShaderWriter.h @@ -78,6 +78,8 @@ public: void ConstFloat(const char *name, float value); ShaderWriter &SampleTexture2D(const char *texName, const char *uv); + ShaderWriter &SampleTexture2DOffset(const char *texName, const char *uv, int offX, int offY); + ShaderWriter &LoadTexture2D(const char *texName, const char *integer_uv, int level); ShaderWriter &GetTextureSize(const char *szVariable, const char *texName); // Simple shaders with no special tricks. diff --git a/Common/GPU/Vulkan/VulkanContext.cpp b/Common/GPU/Vulkan/VulkanContext.cpp index 63351eaf45..55edc0f31f 100644 --- a/Common/GPU/Vulkan/VulkanContext.cpp +++ b/Common/GPU/Vulkan/VulkanContext.cpp @@ -1196,12 +1196,15 @@ void VulkanContext::DestroyDevice() { device_ = nullptr; } -bool VulkanContext::CreateShaderModule(const std::vector &spirv, VkShaderModule *shaderModule) { +bool VulkanContext::CreateShaderModule(const std::vector &spirv, VkShaderModule *shaderModule, const char *tag) { VkShaderModuleCreateInfo sm{ VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO }; sm.pCode = spirv.data(); sm.codeSize = spirv.size() * sizeof(uint32_t); sm.flags = 0; VkResult result = vkCreateShaderModule(device_, &sm, nullptr, shaderModule); + if (tag) { + SetDebugName(*shaderModule, VK_OBJECT_TYPE_SHADER_MODULE, tag); + } if (result != VK_SUCCESS) { return false; } else { diff --git a/Common/GPU/Vulkan/VulkanContext.h b/Common/GPU/Vulkan/VulkanContext.h index b5750c77ab..87a73a59fc 100644 --- a/Common/GPU/Vulkan/VulkanContext.h +++ b/Common/GPU/Vulkan/VulkanContext.h @@ -201,7 +201,7 @@ public: // Utility functions for shorter code VkFence CreateFence(bool presignalled); - bool CreateShaderModule(const std::vector &spirv, VkShaderModule *shaderModule); + bool CreateShaderModule(const std::vector &spirv, VkShaderModule *shaderModule, const char *tag); int GetBackbufferWidth() { return (int)swapChainExtent_.width; } int GetBackbufferHeight() { return (int)swapChainExtent_.height; } diff --git a/Common/GPU/Vulkan/VulkanImage.cpp b/Common/GPU/Vulkan/VulkanImage.cpp index c013f5d9ee..72eb339c12 100644 --- a/Common/GPU/Vulkan/VulkanImage.cpp +++ b/Common/GPU/Vulkan/VulkanImage.cpp @@ -36,6 +36,10 @@ bool VulkanTexture::CreateDirect(VkCommandBuffer cmd, int w, int h, int depth, i ERROR_LOG(G3D, "Can't create a zero-size VulkanTexture"); return false; } + if (w > 4096 || h > 4096) { + ERROR_LOG(G3D, "Can't create a texture this large"); + return false; + } Wipe(); diff --git a/Common/GPU/Vulkan/VulkanMemory.cpp b/Common/GPU/Vulkan/VulkanMemory.cpp index a7a5277efa..8206c80c91 100644 --- a/Common/GPU/Vulkan/VulkanMemory.cpp +++ b/Common/GPU/Vulkan/VulkanMemory.cpp @@ -59,6 +59,8 @@ bool VulkanPushBuffer::AddBuffer() { return false; } + vulkan_->SetDebugName(info.buffer, VK_OBJECT_TYPE_BUFFER, name_); + buffers_.push_back(info); buf_ = buffers_.size() - 1; return true; @@ -222,5 +224,9 @@ VkResult VulkanDescSetPool::Recreate(bool grow) { info_.pPoolSizes = &sizes_[0]; info_.poolSizeCount = (uint32_t)sizes_.size(); - return vkCreateDescriptorPool(vulkan_->GetDevice(), &info_, nullptr, &descPool_); + VkResult result = vkCreateDescriptorPool(vulkan_->GetDevice(), &info_, nullptr, &descPool_); + if (result == VK_SUCCESS) { + vulkan_->SetDebugName(descPool_, VK_OBJECT_TYPE_DESCRIPTOR_POOL, tag_); + } + return result; } diff --git a/Common/GPU/Vulkan/VulkanMemory.h b/Common/GPU/Vulkan/VulkanMemory.h index 82ef924390..79a71d4ce6 100644 --- a/Common/GPU/Vulkan/VulkanMemory.h +++ b/Common/GPU/Vulkan/VulkanMemory.h @@ -143,8 +143,7 @@ private: // Only appropriate for use in a per-frame pool. class VulkanDescSetPool { public: - VulkanDescSetPool(const char *tag, bool grow) : tag_(tag), grow_(grow) { - } + VulkanDescSetPool(const char *tag, bool grow) : tag_(tag), grow_(grow) {} ~VulkanDescSetPool(); // Must call this before use: defines how to clear cache of ANY returned values from Allocate(). diff --git a/Common/GPU/Vulkan/VulkanQueueRunner.cpp b/Common/GPU/Vulkan/VulkanQueueRunner.cpp index 9b7ae11ea5..10a88e623a 100644 --- a/Common/GPU/Vulkan/VulkanQueueRunner.cpp +++ b/Common/GPU/Vulkan/VulkanQueueRunner.cpp @@ -27,13 +27,26 @@ static void MergeRenderAreaRectInto(VkRect2D *dest, VkRect2D &src) { } } +// We need to take the "max" of the features used in the two render passes. +RenderPassType MergeRPTypes(RenderPassType a, RenderPassType b) { + // Either both are backbuffer type, or neither are. + _dbg_assert_((a == RP_TYPE_BACKBUFFER) == (b == RP_TYPE_BACKBUFFER)); + if (a == b) { + // Trivial merging case. + return a; + } + // More cases to be added later. + return a; +} + void VulkanQueueRunner::CreateDeviceObjects() { INFO_LOG(G3D, "VulkanQueueRunner::CreateDeviceObjects"); - InitBackbufferRenderPass(); - RPKey key{ VKRRenderPassLoadAction::CLEAR, VKRRenderPassLoadAction::CLEAR, VKRRenderPassLoadAction::CLEAR, - VKRRenderPassStoreAction::STORE, VKRRenderPassStoreAction::DONT_CARE, VKRRenderPassStoreAction::DONT_CARE }; - framebufferRenderPass_ = GetRenderPass(key); + RPKey key{ + VKRRenderPassLoadAction::CLEAR, VKRRenderPassLoadAction::CLEAR, VKRRenderPassLoadAction::CLEAR, + VKRRenderPassStoreAction::STORE, VKRRenderPassStoreAction::DONT_CARE, VKRRenderPassStoreAction::DONT_CARE, + }; + compatibleRenderPass_ = GetRenderPass(key); #if 0 // Just to check whether it makes sense to split some of these. drawidx is way bigger than the others... @@ -117,78 +130,12 @@ void VulkanQueueRunner::DestroyDeviceObjects() { } readbackBufferSize_ = 0; - renderPasses_.Iterate([&](const RPKey &rpkey, VkRenderPass rp) { - _assert_(rp != VK_NULL_HANDLE); - vulkan_->Delete().QueueDeleteRenderPass(rp); + renderPasses_.IterateMut([&](const RPKey &rpkey, VKRRenderPass *rp) { + _assert_(rp); + rp->Destroy(vulkan_); + delete rp; }); renderPasses_.Clear(); - - _assert_(backbufferRenderPass_ != VK_NULL_HANDLE); - vulkan_->Delete().QueueDeleteRenderPass(backbufferRenderPass_); - backbufferRenderPass_ = VK_NULL_HANDLE; -} - -void VulkanQueueRunner::InitBackbufferRenderPass() { - VkAttachmentDescription attachments[2]; - attachments[0].format = vulkan_->GetSwapchainFormat(); - attachments[0].samples = VK_SAMPLE_COUNT_1_BIT; - attachments[0].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; - 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_UNDEFINED; // We don't want to preserve the backbuffer between frames so we really don't care. - attachments[0].finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; // We only render once to the backbuffer per frame so we can do this here. - attachments[0].flags = 0; - - attachments[1].format = vulkan_->GetDeviceInfo().preferredDepthStencilFormat; // must use this same format later for the back depth buffer. - attachments[1].samples = VK_SAMPLE_COUNT_1_BIT; - attachments[1].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; - attachments[1].storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; // Don't care about storing backbuffer Z - we clear it anyway. - attachments[1].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; - attachments[1].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; - 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 = attachments[1].finalLayout; - - VkSubpassDescription subpass{}; - subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; - subpass.flags = 0; - subpass.inputAttachmentCount = 0; - subpass.pInputAttachments = nullptr; - subpass.colorAttachmentCount = 1; - subpass.pColorAttachments = &color_reference; - subpass.pResolveAttachments = nullptr; - subpass.pDepthStencilAttachment = &depth_reference; - subpass.preserveAttachmentCount = 0; - subpass.pPreserveAttachments = nullptr; - - // For the built-in layout transitions. - VkSubpassDependency dep{}; - dep.srcSubpass = VK_SUBPASS_EXTERNAL; - dep.dstSubpass = 0; - dep.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; - dep.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; - dep.srcAccessMask = 0; - dep.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; - - VkRenderPassCreateInfo rp_info{ VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO }; - rp_info.attachmentCount = 2; - rp_info.pAttachments = attachments; - rp_info.subpassCount = 1; - rp_info.pSubpasses = &subpass; - rp_info.dependencyCount = 1; - rp_info.pDependencies = &dep; - - VkResult res = vkCreateRenderPass(vulkan_->GetDevice(), &rp_info, nullptr, &backbufferRenderPass_); - _assert_(res == VK_SUCCESS); } static VkAttachmentLoadOp ConvertLoadAction(VKRRenderPassLoadAction action) { @@ -208,24 +155,19 @@ static VkAttachmentStoreOp ConvertStoreAction(VKRRenderPassStoreAction action) { return VK_ATTACHMENT_STORE_OP_DONT_CARE; // avoid compiler warning } -VkRenderPass VulkanQueueRunner::GetRenderPass(const RPKey &key) { - auto pass = renderPasses_.Get(key); - if (pass) { - return pass; - } - +VkRenderPass CreateRP(VulkanContext *vulkan, const RPKey &key, RenderPassType rpType) { VkAttachmentDescription attachments[2] = {}; - attachments[0].format = VK_FORMAT_R8G8B8A8_UNORM; + attachments[0].format = rpType == RP_TYPE_BACKBUFFER ? vulkan->GetSwapchainFormat() : VK_FORMAT_R8G8B8A8_UNORM; attachments[0].samples = VK_SAMPLE_COUNT_1_BIT; attachments[0].loadOp = ConvertLoadAction(key.colorLoadAction); attachments[0].storeOp = ConvertStoreAction(key.colorStoreAction); 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].initialLayout = rpType == RP_TYPE_BACKBUFFER ? VK_IMAGE_LAYOUT_UNDEFINED : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + attachments[0].finalLayout = rpType == RP_TYPE_BACKBUFFER ? VK_IMAGE_LAYOUT_PRESENT_SRC_KHR : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; attachments[0].flags = 0; - attachments[1].format = vulkan_->GetDeviceInfo().preferredDepthStencilFormat; + attachments[1].format = vulkan->GetDeviceInfo().preferredDepthStencilFormat; attachments[1].samples = VK_SAMPLE_COUNT_1_BIT; attachments[1].loadOp = ConvertLoadAction(key.depthLoadAction); attachments[1].storeOp = ConvertStoreAction(key.depthStoreAction); @@ -255,15 +197,51 @@ VkRenderPass VulkanQueueRunner::GetRenderPass(const RPKey &key) { subpass.preserveAttachmentCount = 0; subpass.pPreserveAttachments = nullptr; + // Not sure if this is really necessary. + VkSubpassDependency dep{}; + dep.srcSubpass = VK_SUBPASS_EXTERNAL; + dep.dstSubpass = 0; + dep.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + dep.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + dep.srcAccessMask = 0; + dep.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + VkRenderPassCreateInfo rp{ VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO }; rp.attachmentCount = 2; rp.pAttachments = attachments; rp.subpassCount = 1; rp.pSubpasses = &subpass; + if (rpType == RP_TYPE_BACKBUFFER) { + rp.dependencyCount = 1; + rp.pDependencies = &dep; + } - VkResult res = vkCreateRenderPass(vulkan_->GetDevice(), &rp, nullptr, &pass); + VkRenderPass pass; + VkResult res = vkCreateRenderPass(vulkan->GetDevice(), &rp, nullptr, &pass); _assert_(res == VK_SUCCESS); _assert_(pass != VK_NULL_HANDLE); + return pass; +} + +VkRenderPass VKRRenderPass::Get(VulkanContext *vulkan, RenderPassType rpType) { + // When we create a render pass, we create all "types" of it immediately, + // practical later when referring to it. Could change to on-demand if it feels motivated + // but I think the render pass objects are cheap. + if (!pass[(int)rpType]) { + pass[(int)rpType] = CreateRP(vulkan, key_, (RenderPassType)rpType); + } + return pass[(int)rpType]; +} + +// Self-dependency: https://github.com/gpuweb/gpuweb/issues/442#issuecomment-547604827 +// Also see https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#synchronization-pipeline-barriers-subpass-self-dependencies +VKRRenderPass *VulkanQueueRunner::GetRenderPass(const RPKey &key) { + auto foundPass = renderPasses_.Get(key); + if (foundPass) { + return foundPass; + } + + VKRRenderPass *pass = new VKRRenderPass(key); renderPasses_.Insert(key, pass); return pass; } @@ -272,7 +250,8 @@ void VulkanQueueRunner::PreprocessSteps(std::vector &steps) { // Optimizes renderpasses, then sequences them. // Planned optimizations: // * Create copies of render target that are rendered to multiple times and textured from in sequence, and push those render passes - // as early as possible in the frame (Wipeout billboards). + // as early as possible in the frame (Wipeout billboards). This will require taking over more of descriptor management so we can + // substitute descriptors, alternatively using texture array layers creatively. for (int j = 0; j < (int)steps.size(); j++) { if (steps[j]->stepType == VKRStepType::RENDER && @@ -312,7 +291,7 @@ void VulkanQueueRunner::PreprocessSteps(std::vector &steps) { steps[i]->render.clearStencil = steps[j]->render.clearStencil; } MergeRenderAreaRectInto(&steps[i]->render.renderArea, steps[j]->render.renderArea); - + steps[i]->render.renderPassType = MergeRPTypes(steps[i]->render.renderPassType, steps[j]->render.renderPassType); // Cheaply skip the first step. steps[j]->stepType = VKRStepType::RENDER_SKIP; break; @@ -645,17 +624,23 @@ std::string VulkanQueueRunner::StepToString(const VKRStep &step) const { int h = step.render.framebuffer ? step.render.framebuffer->height : vulkan_->GetBackbufferHeight(); int actual_w = step.render.renderArea.extent.width; int actual_h = step.render.renderArea.extent.height; - snprintf(buffer, sizeof(buffer), "RENDER %s (draws: %d, %dx%d/%dx%d, fb: %p, )", step.tag, step.render.numDraws, actual_w, actual_h, w, h, step.render.framebuffer); + const char *renderCmd; + switch (step.render.renderPassType) { + case RP_TYPE_BACKBUFFER: renderCmd = "BACKBUF"; break; + case RP_TYPE_COLOR_DEPTH: renderCmd = "RENDER"; break; + default: renderCmd = "N/A"; + } + snprintf(buffer, sizeof(buffer), "%s %s (draws: %d, %dx%d/%dx%d, fb: %p, )", renderCmd, step.tag, step.render.numDraws, actual_w, actual_h, w, h, step.render.framebuffer); break; } case VKRStepType::COPY: - snprintf(buffer, sizeof(buffer), "COPY '%s' %s -> %s (%dx%d, %s)", step.tag, step.copy.src->tag.c_str(), step.copy.dst->tag.c_str(), step.copy.srcRect.extent.width, step.copy.srcRect.extent.height, AspectToString(step.copy.aspectMask)); + snprintf(buffer, sizeof(buffer), "COPY '%s' %s -> %s (%dx%d, %s)", step.tag, step.copy.src->Tag(), step.copy.dst->Tag(), step.copy.srcRect.extent.width, step.copy.srcRect.extent.height, AspectToString(step.copy.aspectMask)); break; case VKRStepType::BLIT: - snprintf(buffer, sizeof(buffer), "BLIT '%s' %s -> %s (%dx%d->%dx%d, %s)", step.tag, step.copy.src->tag.c_str(), step.copy.dst->tag.c_str(), step.blit.srcRect.extent.width, step.blit.srcRect.extent.height, step.blit.dstRect.extent.width, step.blit.dstRect.extent.height, AspectToString(step.blit.aspectMask)); + snprintf(buffer, sizeof(buffer), "BLIT '%s' %s -> %s (%dx%d->%dx%d, %s)", step.tag, step.copy.src->Tag(), step.copy.dst->Tag(), step.blit.srcRect.extent.width, step.blit.srcRect.extent.height, step.blit.dstRect.extent.width, step.blit.dstRect.extent.height, AspectToString(step.blit.aspectMask)); break; case VKRStepType::READBACK: - snprintf(buffer, sizeof(buffer), "READBACK '%s' %s (%dx%d, %s)", step.tag, step.readback.src->tag.c_str(), step.readback.srcRect.extent.width, step.readback.srcRect.extent.height, AspectToString(step.readback.aspectMask)); + snprintf(buffer, sizeof(buffer), "READBACK '%s' %s (%dx%d, %s)", step.tag, step.readback.src->Tag(), step.readback.srcRect.extent.width, step.readback.srcRect.extent.height, AspectToString(step.readback.aspectMask)); break; case VKRStepType::READBACK_IMAGE: snprintf(buffer, sizeof(buffer), "READBACK_IMAGE '%s' (%dx%d)", step.tag, step.readback_image.srcRect.extent.width, step.readback_image.srcRect.extent.height); @@ -692,6 +677,8 @@ void VulkanQueueRunner::ApplyRenderPassMerge(std::vector &steps) { // So we don't consider it for other things, maybe doesn't matter. src->dependencies.clear(); src->stepType = VKRStepType::RENDER_SKIP; + dst->render.pipelineFlags |= src->render.pipelineFlags; + dst->render.renderPassType = MergeRPTypes(dst->render.renderPassType, src->render.renderPassType); }; auto renderHasClear = [](const VKRStep *step) { const auto &r = step->render; @@ -814,14 +801,14 @@ const char *ImageLayoutToString(VkImageLayout layout) { void VulkanQueueRunner::LogRenderPass(const VKRStep &pass, bool verbose) { const auto &r = pass.render; - const char *framebuf = r.framebuffer ? r.framebuffer->tag.c_str() : "backbuffer"; + const char *framebuf = r.framebuffer ? r.framebuffer->Tag() : "backbuffer"; int w = r.framebuffer ? r.framebuffer->width : vulkan_->GetBackbufferWidth(); int h = r.framebuffer ? r.framebuffer->height : vulkan_->GetBackbufferHeight(); INFO_LOG(G3D, "RENDER %s Begin(%s, draws: %d, %dx%d, %s, %s, %s)", pass.tag, framebuf, r.numDraws, w, h, RenderPassActionName(r.colorLoad), RenderPassActionName(r.depthLoad), RenderPassActionName(r.stencilLoad)); // TODO: Log these in detail. for (int i = 0; i < (int)pass.preTransitions.size(); i++) { - INFO_LOG(G3D, " PRETRANSITION: %s %s -> %s", pass.preTransitions[i].fb->tag.c_str(), AspectToString(pass.preTransitions[i].aspect), ImageLayoutToString(pass.preTransitions[i].targetLayout)); + INFO_LOG(G3D, " PRETRANSITION: %s %s -> %s", pass.preTransitions[i].fb->Tag(), AspectToString(pass.preTransitions[i].aspect), ImageLayoutToString(pass.preTransitions[i].targetLayout)); } if (verbose) { @@ -830,9 +817,6 @@ void VulkanQueueRunner::LogRenderPass(const VKRStep &pass, bool verbose) { case VKRRenderCommand::REMOVED: INFO_LOG(G3D, " (Removed)"); break; - case VKRRenderCommand::BIND_PIPELINE: - INFO_LOG(G3D, " BindPipeline(%x)", (int)(intptr_t)cmd.pipeline.pipeline); - break; case VKRRenderCommand::BIND_GRAPHICS_PIPELINE: INFO_LOG(G3D, " BindGraphicsPipeline(%x)", (int)(intptr_t)cmd.graphics_pipeline.pipeline); break; @@ -1137,7 +1121,7 @@ void VulkanQueueRunner::PerformRenderPass(const VKRStep &step, VkCommandBuffer c // This reads the layout of the color and depth images, and chooses a render pass using them that // will transition to the desired final layout. // NOTE: Flushes recordBarrier_. - PerformBindFramebufferAsRenderTarget(step, cmd); + VKRRenderPass *renderPass = PerformBindFramebufferAsRenderTarget(step, cmd); int curWidth = step.render.framebuffer ? step.render.framebuffer->width : vulkan_->GetBackbufferWidth(); int curHeight = step.render.framebuffer ? step.render.framebuffer->height : vulkan_->GetBackbufferHeight(); @@ -1159,29 +1143,28 @@ void VulkanQueueRunner::PerformRenderPass(const VKRStep &step, VkCommandBuffer c int lastStencilCompareMask = -1; int lastStencilReference = -1; + const RenderPassType rpType = step.render.renderPassType; + for (const auto &c : commands) { switch (c.cmd) { case VKRRenderCommand::REMOVED: break; - // Still here to support binding of non-async pipelines. - case VKRRenderCommand::BIND_PIPELINE: - { - VkPipeline pipeline = c.pipeline.pipeline; - vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); - pipelineLayout = c.pipeline.pipelineLayout; - // Reset dynamic state so it gets refreshed with the new pipeline. - lastStencilWriteMask = -1; - lastStencilCompareMask = -1; - lastStencilReference = -1; - break; - } - case VKRRenderCommand::BIND_GRAPHICS_PIPELINE: { VKRGraphicsPipeline *graphicsPipeline = c.graphics_pipeline.pipeline; if (graphicsPipeline != lastGraphicsPipeline) { - VkPipeline pipeline = graphicsPipeline->pipeline->BlockUntilReady(); + if (!graphicsPipeline->pipeline[rpType]) { + // NOTE: If render steps got merged, it can happen that, as they ended during recording, + // they didn't know their final render pass type so they created the wrong pipelines in EndCurRenderStep(). + // Unfortunately I don't know if we can fix it in any more sensible place than here. + // Maybe a middle pass. But let's try to just block and compile here for now, this doesn't + // happen all that much. + graphicsPipeline->pipeline[rpType] = Promise::CreateEmpty(); + graphicsPipeline->Create(vulkan_, renderPass->Get(vulkan_, rpType), rpType); + } + + VkPipeline pipeline = graphicsPipeline->pipeline[rpType]->BlockUntilReady(); if (pipeline != VK_NULL_HANDLE) { vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); pipelineLayout = c.pipeline.pipelineLayout; @@ -1337,8 +1320,8 @@ void VulkanQueueRunner::PerformRenderPass(const VKRStep &step, VkCommandBuffer c } } -void VulkanQueueRunner::PerformBindFramebufferAsRenderTarget(const VKRStep &step, VkCommandBuffer cmd) { - VkRenderPass renderPass; +VKRRenderPass *VulkanQueueRunner::PerformBindFramebufferAsRenderTarget(const VKRStep &step, VkCommandBuffer cmd) { + VKRRenderPass *renderPass; int numClearVals = 0; VkClearValue clearVal[2]{}; VkFramebuffer framebuf; @@ -1348,8 +1331,14 @@ void VulkanQueueRunner::PerformBindFramebufferAsRenderTarget(const VKRStep &step _dbg_assert_(step.render.finalColorLayout != VK_IMAGE_LAYOUT_UNDEFINED); _dbg_assert_(step.render.finalDepthStencilLayout != VK_IMAGE_LAYOUT_UNDEFINED); + RPKey key{ + step.render.colorLoad, step.render.depthLoad, step.render.stencilLoad, + step.render.colorStore, step.render.depthStore, step.render.stencilStore, + }; + renderPass = GetRenderPass(key); + VKRFramebuffer *fb = step.render.framebuffer; - framebuf = fb->framebuf; + framebuf = fb->Get(renderPass, step.render.renderPassType); w = fb->width; h = fb->height; @@ -1371,12 +1360,6 @@ void VulkanQueueRunner::PerformBindFramebufferAsRenderTarget(const VKRStep &step TransitionToOptimal(cmd, fb->color.image, fb->color.layout, fb->depth.image, fb->depth.layout, &recordBarrier_); - RPKey key{ - step.render.colorLoad, step.render.depthLoad, step.render.stencilLoad, - step.render.colorStore, step.render.depthStore, step.render.stencilStore, - }; - renderPass = GetRenderPass(key); - // The transition from the optimal format happens after EndRenderPass, now that we don't // do it as part of the renderpass itself anymore. @@ -1390,12 +1373,18 @@ void VulkanQueueRunner::PerformBindFramebufferAsRenderTarget(const VKRStep &step numClearVals = 2; } } else { + RPKey key{ + VKRRenderPassLoadAction::CLEAR, VKRRenderPassLoadAction::CLEAR, VKRRenderPassLoadAction::CLEAR, + VKRRenderPassStoreAction::STORE, VKRRenderPassStoreAction::DONT_CARE, VKRRenderPassStoreAction::DONT_CARE, + }; + renderPass = GetRenderPass(key); + framebuf = backbuffer_; // Raw, rotated backbuffer size. w = vulkan_->GetBackbufferWidth(); h = vulkan_->GetBackbufferHeight(); - renderPass = GetBackbufferRenderPass(); + Uint8x4ToFloat4(clearVal[0].color.float32, step.render.clearColor); numClearVals = 2; // We don't bother with a depth buffer here. clearVal[1].depthStencil.depth = 0.0f; @@ -1403,7 +1392,7 @@ void VulkanQueueRunner::PerformBindFramebufferAsRenderTarget(const VKRStep &step } VkRenderPassBeginInfo rp_begin = { VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO }; - rp_begin.renderPass = renderPass; + rp_begin.renderPass = renderPass->Get(vulkan_, step.render.renderPassType); rp_begin.framebuffer = framebuf; VkRect2D rc = step.render.renderArea; @@ -1424,6 +1413,8 @@ void VulkanQueueRunner::PerformBindFramebufferAsRenderTarget(const VKRStep &step rp_begin.clearValueCount = numClearVals; rp_begin.pClearValues = numClearVals ? clearVal : nullptr; vkCmdBeginRenderPass(cmd, &rp_begin, VK_SUBPASS_CONTENTS_INLINE); + + return renderPass; } void VulkanQueueRunner::PerformCopy(const VKRStep &step, VkCommandBuffer cmd) { diff --git a/Common/GPU/Vulkan/VulkanQueueRunner.h b/Common/GPU/Vulkan/VulkanQueueRunner.h index ce6dc9f5eb..adb9e7d96e 100644 --- a/Common/GPU/Vulkan/VulkanQueueRunner.h +++ b/Common/GPU/Vulkan/VulkanQueueRunner.h @@ -26,7 +26,6 @@ enum { enum class VKRRenderCommand : uint8_t { REMOVED, - BIND_PIPELINE, // raw pipeline BIND_GRAPHICS_PIPELINE, // async BIND_COMPUTE_PIPELINE, // async STENCIL, @@ -47,6 +46,14 @@ enum PipelineFlags { PIPELINE_FLAG_USES_DEPTH_STENCIL = (1 << 4), // Reads or writes the depth buffer. }; +// Pipelines need to be created for the right type of render pass. +enum RenderPassType { + RP_TYPE_BACKBUFFER, + RP_TYPE_COLOR_DEPTH, + // Later will add pure-color render passes. + RP_TYPE_COUNT, +}; + struct VkRenderData { VKRRenderCommand cmd; union { @@ -147,6 +154,8 @@ struct QueueProfileContext { double cpuEndTime; }; +class VKRRenderPass; + struct VKRStep { VKRStep(VKRStepType _type) : stepType(_type) {} ~VKRStep() {} @@ -159,6 +168,7 @@ struct VKRStep { union { struct { VKRFramebuffer *framebuffer; + // TODO: Look these up through renderPass? VKRRenderPassLoadAction colorLoad; VKRRenderPassLoadAction depthLoad; VKRRenderPassLoadAction stencilLoad; @@ -175,6 +185,9 @@ struct VKRStep { VkImageLayout finalDepthStencilLayout; u32 pipelineFlags; VkRect2D renderArea; + // Render pass type. Deduced after finishing recording the pass, from the used pipelines. + // NOTE: Storing the render pass here doesn't do much good, we change the compatible parameters (load/store ops) during step optimization. + RenderPassType renderPassType; } render; struct { VKRFramebuffer *src; @@ -204,9 +217,38 @@ struct VKRStep { }; }; +struct RPKey { + // Only render-pass-compatibility-volatile things can be here. + VKRRenderPassLoadAction colorLoadAction; + VKRRenderPassLoadAction depthLoadAction; + VKRRenderPassLoadAction stencilLoadAction; + VKRRenderPassStoreAction colorStoreAction; + VKRRenderPassStoreAction depthStoreAction; + VKRRenderPassStoreAction stencilStoreAction; +}; + +class VKRRenderPass { +public: + VKRRenderPass(const RPKey &key) : key_(key) {} + + VkRenderPass Get(VulkanContext *vulkan, RenderPassType rpType); + void Destroy(VulkanContext *vulkan) { + for (int i = 0; i < RP_TYPE_COUNT; i++) { + if (pass[i]) { + vulkan->Delete().QueueDeleteRenderPass(pass[i]); + } + } + } + +private: + VkRenderPass pass[RP_TYPE_COUNT]{}; + RPKey key_; +}; + class VulkanQueueRunner { public: VulkanQueueRunner(VulkanContext *vulkan) : vulkan_(vulkan), renderPasses_(16) {} + void SetBackbuffer(VkFramebuffer fb, VkImage img) { backbuffer_ = fb; backbufferImage_ = img; @@ -221,14 +263,10 @@ public: void CreateDeviceObjects(); void DestroyDeviceObjects(); - VkRenderPass GetBackbufferRenderPass() const { - return backbufferRenderPass_; - } - // Get a render pass that's compatible with all our framebuffers. // Note that it's precached, cannot look up in the map as this might be on another thread. - VkRenderPass GetFramebufferRenderPass() const { - return framebufferRenderPass_; + VKRRenderPass *GetCompatibleRenderPass() const { + return compatibleRenderPass_; } inline int RPIndex(VKRRenderPassLoadAction color, VKRRenderPassLoadAction depth) { @@ -237,20 +275,11 @@ public: void CopyReadbackBuffer(int width, int height, Draw::DataFormat srcFormat, Draw::DataFormat destFormat, int pixelStride, uint8_t *pixels); - struct RPKey { - VKRRenderPassLoadAction colorLoadAction; - VKRRenderPassLoadAction depthLoadAction; - VKRRenderPassLoadAction stencilLoadAction; - VKRRenderPassStoreAction colorStoreAction; - VKRRenderPassStoreAction depthStoreAction; - VKRRenderPassStoreAction stencilStoreAction; - }; + VKRRenderPass *GetRenderPass(const RPKey &key); - VkRenderPass GetRenderPass(const RPKey &key); - - bool GetRenderPassKey(VkRenderPass passToFind, RPKey *outKey) const { + bool GetRenderPassKey(VKRRenderPass *passToFind, RPKey *outKey) const { bool found = false; - renderPasses_.Iterate([passToFind, &found, outKey](const RPKey &rpkey, VkRenderPass pass) { + renderPasses_.Iterate([passToFind, &found, outKey](const RPKey &rpkey, const VKRRenderPass *pass) { if (pass == passToFind) { found = true; *outKey = rpkey; @@ -273,9 +302,7 @@ public: } private: - void InitBackbufferRenderPass(); - - void PerformBindFramebufferAsRenderTarget(const VKRStep &pass, VkCommandBuffer cmd); + VKRRenderPass *PerformBindFramebufferAsRenderTarget(const VKRStep &pass, VkCommandBuffer cmd); void PerformRenderPass(const VKRStep &pass, VkCommandBuffer cmd); void PerformCopy(const VKRStep &pass, VkCommandBuffer cmd); void PerformBlit(const VKRStep &pass, VkCommandBuffer cmd); @@ -302,14 +329,12 @@ private: VkFramebuffer backbuffer_ = VK_NULL_HANDLE; VkImage backbufferImage_ = VK_NULL_HANDLE; - VkRenderPass backbufferRenderPass_ = VK_NULL_HANDLE; - - // The "Compatible" render pass. Used when creating pipelines that render to "normal" framebuffers. - VkRenderPass framebufferRenderPass_ = VK_NULL_HANDLE; + // The "Compatible" render pass. Should be able to get rid of this soon. + VKRRenderPass *compatibleRenderPass_ = nullptr; // Renderpasses, all combinations of preserving or clearing or dont-care-ing fb contents. - // TODO: Create these on demand. - DenseHashMap renderPasses_; + // Each VKRRenderPass contains all compatibility classes (which attachments they have, etc). + DenseHashMap renderPasses_; // Readback buffer. Currently we only support synchronous readback, so we only really need one. // We size it generously. diff --git a/Common/GPU/Vulkan/VulkanRenderManager.cpp b/Common/GPU/Vulkan/VulkanRenderManager.cpp index a4e14a1b8d..10cc890009 100644 --- a/Common/GPU/Vulkan/VulkanRenderManager.cpp +++ b/Common/GPU/Vulkan/VulkanRenderManager.cpp @@ -25,12 +25,8 @@ using namespace PPSSPP_VK; -bool VKRGraphicsPipeline::Create(VulkanContext *vulkan) { - if (!desc) { - // Already failed to create this one. - return false; - } - +// renderPass is an example of the "compatibility class" or RenderPassType type. +bool VKRGraphicsPipeline::Create(VulkanContext *vulkan, VkRenderPass compatibleRenderPass, RenderPassType rpType) { // Fill in the last part of the desc since now it's time to block. VkShaderModule vs = desc->vertexShader->BlockUntilReady(); VkShaderModule fs = desc->fragmentShader->BlockUntilReady(); @@ -55,12 +51,30 @@ bool VKRGraphicsPipeline::Create(VulkanContext *vulkan) { ss[1].pName = "main"; ss[1].flags = 0; - desc->pipe.pStages = ss; - desc->pipe.stageCount = 2; + VkGraphicsPipelineCreateInfo pipe{ VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO }; + pipe.pStages = ss; + pipe.stageCount = 2; + pipe.renderPass = compatibleRenderPass; + pipe.basePipelineIndex = 0; + pipe.pColorBlendState = &desc->cbs; + pipe.pDepthStencilState = &desc->dss; + pipe.pRasterizationState = &desc->rs; + + // We will use dynamic viewport state. + pipe.pVertexInputState = &desc->vis; + pipe.pViewportState = &desc->views; + pipe.pTessellationState = nullptr; + pipe.pDynamicState = &desc->ds; + pipe.pInputAssemblyState = &desc->inputAssembly; + pipe.pMultisampleState = &desc->ms; + pipe.layout = desc->pipelineLayout; + pipe.basePipelineHandle = VK_NULL_HANDLE; + pipe.basePipelineIndex = 0; + pipe.subpass = 0; double start = time_now_d(); VkPipeline vkpipeline; - VkResult result = vkCreateGraphicsPipelines(vulkan->GetDevice(), desc->pipelineCache, 1, &desc->pipe, nullptr, &vkpipeline); + VkResult result = vkCreateGraphicsPipelines(vulkan->GetDevice(), desc->pipelineCache, 1, &pipe, nullptr, &vkpipeline); INFO_LOG(G3D, "Pipeline creation time: %0.2f ms", (time_now_d() - start) * 1000.0); @@ -70,24 +84,46 @@ bool VKRGraphicsPipeline::Create(VulkanContext *vulkan) { // Would really like to log more here, we could probably attach more info to desc. // // At least create a null placeholder to avoid creating over and over if something is broken. - pipeline->Post(VK_NULL_HANDLE); + pipeline[rpType]->Post(VK_NULL_HANDLE); success = false; } else if (result != VK_SUCCESS) { - pipeline->Post(VK_NULL_HANDLE); + pipeline[rpType]->Post(VK_NULL_HANDLE); ERROR_LOG(G3D, "Failed creating graphics pipeline! result='%s'", VulkanResultToString(result)); success = false; } else { - pipeline->Post(vkpipeline); + // Success! + if (!tag.empty()) { + vulkan->SetDebugName(vkpipeline, VK_OBJECT_TYPE_PIPELINE, tag.c_str()); + } + pipeline[rpType]->Post(vkpipeline); } - // Having the desc stick around can be useful for debugging. -#ifndef _DEBUG - delete desc; - desc = nullptr; -#endif return success; } +void VKRGraphicsPipeline::QueueForDeletion(VulkanContext *vulkan) { + for (int i = 0; i < RP_TYPE_COUNT; i++) { + if (!pipeline[i]) + continue; + VkPipeline pipeline = this->pipeline[i]->BlockUntilReady(); + vulkan->Delete().QueueDeletePipeline(pipeline); + } + vulkan->Delete().QueueCallback([](void *p) { + VKRGraphicsPipeline *pipeline = (VKRGraphicsPipeline *)p; + delete pipeline; + }, this); +} + +u32 VKRGraphicsPipeline::GetVariantsBitmask() const { + u32 bitmask = 0; + for (int i = 0; i < RP_TYPE_COUNT; i++) { + if (pipeline[i]) { + bitmask |= 1 << i; + } + } + return bitmask; +} + bool VKRComputePipeline::Create(VulkanContext *vulkan) { if (!desc) { // Already failed to create this one. @@ -110,17 +146,25 @@ bool VKRComputePipeline::Create(VulkanContext *vulkan) { return success; } -VKRFramebuffer::VKRFramebuffer(VulkanContext *vk, VkCommandBuffer initCmd, VkRenderPass renderPass, int _width, int _height, const char *tag) : vulkan_(vk) { +VKRFramebuffer::VKRFramebuffer(VulkanContext *vk, VkCommandBuffer initCmd, VKRRenderPass *compatibleRenderPass, int _width, int _height, const char *tag) : vulkan_(vk), tag_(tag) { width = _width; height = _height; CreateImage(vulkan_, initCmd, color, width, height, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, true, tag); CreateImage(vulkan_, initCmd, depth, width, height, vulkan_->GetDeviceInfo().preferredDepthStencilFormat, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, false, tag); + // We create the actual framebuffer objects on demand, because some combinations might not make sense. +} + +VkFramebuffer VKRFramebuffer::Get(VKRRenderPass *compatibleRenderPass, RenderPassType renderPassType) { + if (framebuf[(int)renderPassType]) { + return framebuf[(int)renderPassType]; + } + VkFramebufferCreateInfo fbci{ VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO }; VkImageView views[2]{}; - fbci.renderPass = renderPass; + fbci.renderPass = compatibleRenderPass->Get(vulkan_, renderPassType); fbci.attachmentCount = 2; fbci.pAttachments = views; views[0] = color.imageView; @@ -129,15 +173,16 @@ VKRFramebuffer::VKRFramebuffer(VulkanContext *vk, VkCommandBuffer initCmd, VkRen fbci.height = height; fbci.layers = 1; - VkResult res = vkCreateFramebuffer(vulkan_->GetDevice(), &fbci, nullptr, &framebuf); + VkResult res = vkCreateFramebuffer(vulkan_->GetDevice(), &fbci, nullptr, &framebuf[(int)renderPassType]); _assert_(res == VK_SUCCESS); - if (tag && vk->Extensions().EXT_debug_utils) { - vk->SetDebugName(color.image, VK_OBJECT_TYPE_IMAGE, StringFromFormat("fb_color_%s", tag).c_str()); - vk->SetDebugName(depth.image, VK_OBJECT_TYPE_IMAGE, StringFromFormat("fb_depth_%s", tag).c_str()); - vk->SetDebugName(framebuf, VK_OBJECT_TYPE_FRAMEBUFFER, StringFromFormat("fb_%s", tag).c_str()); - this->tag = tag; + if (!tag_.empty() && vulkan_->Extensions().EXT_debug_utils) { + vulkan_->SetDebugName(color.image, VK_OBJECT_TYPE_IMAGE, StringFromFormat("fb_color_%s", tag_.c_str()).c_str()); + vulkan_->SetDebugName(depth.image, VK_OBJECT_TYPE_IMAGE, StringFromFormat("fb_depth_%s", tag_.c_str()).c_str()); + vulkan_->SetDebugName(framebuf[(int)renderPassType], VK_OBJECT_TYPE_FRAMEBUFFER, StringFromFormat("fb_%s", tag_.c_str()).c_str()); } + + return framebuf[(int)renderPassType]; } VKRFramebuffer::~VKRFramebuffer() { @@ -155,8 +200,10 @@ VKRFramebuffer::~VKRFramebuffer() { } if (depth.depthSampleView) vulkan_->Delete().QueueDeleteImageView(depth.depthSampleView); - if (framebuf) - vulkan_->Delete().QueueDeleteFramebuffer(framebuf); + for (auto &fb : framebuf) { + if (fb) + vulkan_->Delete().QueueDeleteFramebuffer(fb); + } } void CreateImage(VulkanContext *vulkan, VkCommandBuffer cmd, VKRImage &img, int width, int height, VkFormat format, VkImageLayout initialLayout, bool color, const char *tag) { @@ -493,7 +540,7 @@ void VulkanRenderManager::CompileThreadFunc() { for (auto &entry : toCompile) { switch (entry.type) { case CompileQueueEntry::Type::GRAPHICS: - entry.graphics->Create(vulkan_); + entry.graphics->Create(vulkan_, entry.compatibleRenderPass, entry.renderPassType); break; case CompileQueueEntry::Type::COMPUTE: entry.compute->Create(vulkan_); @@ -506,6 +553,7 @@ void VulkanRenderManager::CompileThreadFunc() { void VulkanRenderManager::DrainCompileQueue() { std::unique_lock lock(compileMutex_); + compileCond_.notify_all(); while (!compileQueue_.empty()) { queueRunner_.WaitForCompileNotification(); } @@ -576,7 +624,9 @@ void VulkanRenderManager::BeginFrame(bool enableProfiling, bool enableLogProfile VLOG("PUSH: Fencing %d", curFrame); - vkWaitForFences(device, 1, &frameData.fence, true, UINT64_MAX); + if (vkWaitForFences(device, 1, &frameData.fence, true, UINT64_MAX) == VK_ERROR_DEVICE_LOST) { + _assert_msg_(false, "Device lost in vkWaitForFences"); + } vkResetFences(device, 1, &frameData.fence); // Can't set this until after the fence. @@ -663,24 +713,98 @@ VkCommandBuffer VulkanRenderManager::GetInitCmd() { return frameData_[curFrame].initCmd; } +VKRGraphicsPipeline *VulkanRenderManager::CreateGraphicsPipeline(VKRGraphicsPipelineDesc *desc, uint32_t variantBitmask, const char *tag) { + VKRGraphicsPipeline *pipeline = new VKRGraphicsPipeline(); + _dbg_assert_(desc->vertexShader); + _dbg_assert_(desc->fragmentShader); + pipeline->desc = desc; + pipeline->tag = tag; + if (curRenderStep_) { + // The common case + pipelinesToCheck_.push_back(pipeline); + } else { + if (!variantBitmask) { + WARN_LOG(G3D, "WARNING: Will not compile any variants of pipeline, not in renderpass and empty variantBitmask"); + } + // Presumably we're in initialization, loading the shader cache. + // Look at variantBitmask to see what variants we should queue up. + RPKey key{ + VKRRenderPassLoadAction::CLEAR, VKRRenderPassLoadAction::CLEAR, VKRRenderPassLoadAction::CLEAR, + VKRRenderPassStoreAction::STORE, VKRRenderPassStoreAction::DONT_CARE, VKRRenderPassStoreAction::DONT_CARE, + }; + VKRRenderPass *compatibleRenderPass = queueRunner_.GetRenderPass(key); + compileMutex_.lock(); + bool needsCompile = false; + for (int i = 0; i < RP_TYPE_COUNT; i++) { + if (!(variantBitmask & (1 << i))) + continue; + RenderPassType rpType = (RenderPassType)i; + pipeline->pipeline[rpType] = Promise::CreateEmpty(); + compileQueue_.push_back(CompileQueueEntry(pipeline, compatibleRenderPass->Get(vulkan_, rpType), rpType)); + needsCompile = true; + } + if (needsCompile) + compileCond_.notify_one(); + compileMutex_.unlock(); + } + return pipeline; +} + +VKRComputePipeline *VulkanRenderManager::CreateComputePipeline(VKRComputePipelineDesc *desc) { + VKRComputePipeline *pipeline = new VKRComputePipeline(); + pipeline->desc = desc; + compileMutex_.lock(); + compileQueue_.push_back(CompileQueueEntry(pipeline)); + compileCond_.notify_one(); + compileMutex_.unlock(); + return pipeline; +} + void VulkanRenderManager::EndCurRenderStep() { + if (!curRenderStep_) + return; + + RPKey key{ + curRenderStep_->render.colorLoad, curRenderStep_->render.depthLoad, curRenderStep_->render.stencilLoad, + curRenderStep_->render.colorStore, curRenderStep_->render.depthStore, curRenderStep_->render.stencilStore, + }; + RenderPassType rpType = RP_TYPE_COLOR_DEPTH; + curRenderStep_->render.pipelineFlags = curPipelineFlags_; + if (!curRenderStep_->render.framebuffer) { + rpType = RP_TYPE_BACKBUFFER; + } + + VKRRenderPass *renderPass = queueRunner_.GetRenderPass(key); + curRenderStep_->render.renderPassType = rpType; + // Save the accumulated pipeline flags so we can use that to configure the render pass. // We'll often be able to avoid loading/saving the depth/stencil buffer. - if (curRenderStep_) { - curRenderStep_->render.pipelineFlags = curPipelineFlags_; - // We don't do this optimization for very small targets, probably not worth it. - if (!curRenderArea_.Empty() && (curWidth_ > 32 && curHeight_ > 32)) { - curRenderStep_->render.renderArea = curRenderArea_.ToVkRect2D(); - } else { - curRenderStep_->render.renderArea.offset = {}; - curRenderStep_->render.renderArea.extent = { (uint32_t)curWidth_, (uint32_t)curHeight_ }; + compileMutex_.lock(); + bool needsCompile = false; + for (VKRGraphicsPipeline *pipeline : pipelinesToCheck_) { + if (!pipeline->pipeline[rpType]) { + pipeline->pipeline[rpType] = Promise::CreateEmpty(); + compileQueue_.push_back(CompileQueueEntry(pipeline, renderPass->Get(vulkan_, rpType), rpType)); + needsCompile = true; } - curRenderArea_.Reset(); - - // We no longer have a current render step. - curRenderStep_ = nullptr; - curPipelineFlags_ = 0; } + if (needsCompile) + compileCond_.notify_one(); + compileMutex_.unlock(); + pipelinesToCheck_.clear(); + + // We don't do this optimization for very small targets, probably not worth it. + if (!curRenderArea_.Empty() && (curWidth_ > 32 && curHeight_ > 32)) { + curRenderStep_->render.renderArea = curRenderArea_.ToVkRect2D(); + } else { + curRenderStep_->render.renderArea.offset = {}; + curRenderStep_->render.renderArea.extent = { (uint32_t)curWidth_, (uint32_t)curHeight_ }; + } + curRenderArea_.Reset(); + + // We no longer have a current render step. + curRenderStep_ = nullptr; + curPipelineFlags_ = 0; } void VulkanRenderManager::BindFramebufferAsRenderTarget(VKRFramebuffer *fb, VKRRenderPassLoadAction color, VKRRenderPassLoadAction depth, VKRRenderPassLoadAction stencil, uint32_t clearColor, float clearDepth, uint8_t clearStencil, const char *tag) { @@ -907,9 +1031,8 @@ bool VulkanRenderManager::InitBackbufferFramebuffers(int width, int height) { // We share the same depth buffer but have multiple color buffers, see the loop below. VkImageView attachments[2] = { VK_NULL_HANDLE, depth_.view }; - VLOG("InitFramebuffers: %dx%d", width, height); VkFramebufferCreateInfo fb_info = { VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO }; - fb_info.renderPass = queueRunner_.GetBackbufferRenderPass(); + fb_info.renderPass = queueRunner_.GetCompatibleRenderPass()->Get(vulkan_, RP_TYPE_BACKBUFFER); fb_info.attachmentCount = 2; fb_info.pAttachments = attachments; fb_info.width = width; @@ -1017,7 +1140,6 @@ static void CleanupRenderCommands(std::vector *cmds) { case VKRRenderCommand::REMOVED: continue; - case VKRRenderCommand::BIND_PIPELINE: case VKRRenderCommand::VIEWPORT: case VKRRenderCommand::SCISSOR: case VKRRenderCommand::BLEND: diff --git a/Common/GPU/Vulkan/VulkanRenderManager.h b/Common/GPU/Vulkan/VulkanRenderManager.h index 67dff36880..4cc7aafdfc 100644 --- a/Common/GPU/Vulkan/VulkanRenderManager.h +++ b/Common/GPU/Vulkan/VulkanRenderManager.h @@ -43,17 +43,26 @@ void CreateImage(VulkanContext *vulkan, VkCommandBuffer cmd, VKRImage &img, int class VKRFramebuffer { public: - VKRFramebuffer(VulkanContext *vk, VkCommandBuffer initCmd, VkRenderPass renderPass, int _width, int _height, const char *tag); + VKRFramebuffer(VulkanContext *vk, VkCommandBuffer initCmd, VKRRenderPass *compatibleRenderPass, int _width, int _height, const char *tag); ~VKRFramebuffer(); - VkFramebuffer framebuf = VK_NULL_HANDLE; - VKRImage color{}; - VKRImage depth{}; + VkFramebuffer Get(VKRRenderPass *compatibleRenderPass, RenderPassType rpType); + int width = 0; int height = 0; + VKRImage color{}; + VKRImage depth{}; + const char *Tag() const { + return tag_.c_str(); + } + + // TODO: Hide. VulkanContext *vulkan_; - std::string tag; +private: + VkFramebuffer framebuf[RP_TYPE_COUNT]{}; + + std::string tag_; }; enum class VKRRunType { @@ -124,15 +133,20 @@ struct VKRGraphicsPipelineDesc { VkPipelineMultisampleStateCreateInfo ms{ VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO }; // Replaced the ShaderStageInfo with promises here so we can wait for compiles to finish. - Promise *vertexShader; - Promise *fragmentShader; + Promise *vertexShader = nullptr; + Promise *fragmentShader = nullptr; VkPipelineInputAssemblyStateCreateInfo inputAssembly{ VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO }; VkVertexInputAttributeDescription attrs[8]{}; VkVertexInputBindingDescription ibd{}; VkPipelineVertexInputStateCreateInfo vis{ VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO }; VkPipelineViewportStateCreateInfo views{ VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO }; - VkGraphicsPipelineCreateInfo pipe{ VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO }; + + VkPipelineLayout pipelineLayout = VK_NULL_HANDLE; + + // Does not include the render pass type, it's passed in separately since the + // desc is persistent. + RPKey rpKey{}; }; // All the data needed to create a compute pipeline. @@ -141,19 +155,18 @@ struct VKRComputePipelineDesc { VkComputePipelineCreateInfo pipe{ VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO }; }; -// Wrapped pipeline. +// Wrapped pipeline. Doesn't own desc. struct VKRGraphicsPipeline { - VKRGraphicsPipeline() { - pipeline = Promise::CreateEmpty(); - } - ~VKRGraphicsPipeline() { - delete desc; - } + bool Create(VulkanContext *vulkan, VkRenderPass compatibleRenderPass, RenderPassType rpType); - VKRGraphicsPipelineDesc *desc = nullptr; - Promise *pipeline; + // This deletes the whole VKRGraphicsPipeline, you must remove your last pointer to it when doing this. + void QueueForDeletion(VulkanContext *vulkan); - bool Create(VulkanContext *vulkan); + u32 GetVariantsBitmask() const; + + VKRGraphicsPipelineDesc *desc = nullptr; // not owned! + Promise *pipeline[RP_TYPE_COUNT]{}; + std::string tag; }; struct VKRComputePipeline { @@ -170,13 +183,16 @@ struct VKRComputePipeline { }; struct CompileQueueEntry { - CompileQueueEntry(VKRGraphicsPipeline *p) : type(Type::GRAPHICS), graphics(p) {} - CompileQueueEntry(VKRComputePipeline *p) : type(Type::COMPUTE), compute(p) {} + CompileQueueEntry(VKRGraphicsPipeline *p, VkRenderPass _compatibleRenderPass, RenderPassType _renderPassType) + : type(Type::GRAPHICS), graphics(p), compatibleRenderPass(_compatibleRenderPass), renderPassType(_renderPassType) {} + CompileQueueEntry(VKRComputePipeline *p) : type(Type::COMPUTE), compute(p), renderPassType(RP_TYPE_COLOR_DEPTH) {} enum class Type { GRAPHICS, COMPUTE, }; Type type; + VkRenderPass compatibleRenderPass; + RenderPassType renderPassType; VKRGraphicsPipeline *graphics = nullptr; VKRComputePipeline *compute = nullptr; }; @@ -228,40 +244,23 @@ public: // Deferred creation, like in GL. Unlike GL though, the purpose is to allow background creation and avoiding // stalling the emulation thread as much as possible. - VKRGraphicsPipeline *CreateGraphicsPipeline(VKRGraphicsPipelineDesc *desc) { - VKRGraphicsPipeline *pipeline = new VKRGraphicsPipeline(); - pipeline->desc = desc; + // We delay creating pipelines until the end of the current render pass, so we can create the right type immediately. + // Unless a variantBitmask is passed in, in which case we can just go ahead. + // WARNING: desc must stick around during the lifetime of the pipeline! It's not enough to build it on the stack and drop it. + VKRGraphicsPipeline *CreateGraphicsPipeline(VKRGraphicsPipelineDesc *desc, uint32_t variantBitmask, const char *tag); + VKRComputePipeline *CreateComputePipeline(VKRComputePipelineDesc *desc); + + void NudgeCompilerThread() { compileMutex_.lock(); - compileQueue_.push_back(CompileQueueEntry(pipeline)); compileCond_.notify_one(); compileMutex_.unlock(); - return pipeline; - } - - VKRComputePipeline *CreateComputePipeline(VKRComputePipelineDesc *desc) { - VKRComputePipeline *pipeline = new VKRComputePipeline(); - pipeline->desc = desc; - compileMutex_.lock(); - compileQueue_.push_back(CompileQueueEntry(pipeline)); - compileCond_.notify_one(); - compileMutex_.unlock(); - return pipeline; - } - - void BindPipeline(VkPipeline pipeline, PipelineFlags flags, VkPipelineLayout pipelineLayout) { - _dbg_assert_(curRenderStep_ && curRenderStep_->stepType == VKRStepType::RENDER); - _dbg_assert_(pipeline != VK_NULL_HANDLE); - VkRenderData data{ VKRRenderCommand::BIND_PIPELINE }; - data.pipeline.pipeline = pipeline; - data.pipeline.pipelineLayout = pipelineLayout; - curPipelineFlags_ |= flags; - curRenderStep_->commands.push_back(data); } void BindPipeline(VKRGraphicsPipeline *pipeline, PipelineFlags flags, VkPipelineLayout pipelineLayout) { _dbg_assert_(curRenderStep_ && curRenderStep_->stepType == VKRStepType::RENDER); _dbg_assert_(pipeline != nullptr); VkRenderData data{ VKRRenderCommand::BIND_GRAPHICS_PIPELINE }; + pipelinesToCheck_.push_back(pipeline); data.graphics_pipeline.pipeline = pipeline; data.graphics_pipeline.pipelineLayout = pipelineLayout; curPipelineFlags_ |= flags; @@ -431,20 +430,6 @@ public: VkCommandBuffer GetInitCmd(); - VkRenderPass GetBackbufferRenderPass() { - return queueRunner_.GetBackbufferRenderPass(); - } - VkRenderPass GetFramebufferRenderPass() { - return queueRunner_.GetFramebufferRenderPass(); - } - VkRenderPass GetCompatibleRenderPass() { - if (curRenderStep_ && curRenderStep_->render.framebuffer != nullptr) { - return queueRunner_.GetFramebufferRenderPass(); - } else { - return queueRunner_.GetBackbufferRenderPass(); - } - } - // Gets a frame-unique ID of the current step being recorded. Can be used to figure out // when the current step has changed, which means the caller will need to re-record its state. int GetCurrentStepId() const { @@ -581,6 +566,9 @@ private: std::mutex compileMutex_; std::vector compileQueue_; + // pipelines to check and possibly create at the end of the current render pass. + std::vector pipelinesToCheck_; + // Swap chain management struct SwapchainImageData { VkImage image; diff --git a/Common/GPU/Vulkan/thin3d_vulkan.cpp b/Common/GPU/Vulkan/thin3d_vulkan.cpp index 8a1112d446..bb206fd1cb 100644 --- a/Common/GPU/Vulkan/thin3d_vulkan.cpp +++ b/Common/GPU/Vulkan/thin3d_vulkan.cpp @@ -31,6 +31,7 @@ #include "Common/GPU/Vulkan/VulkanContext.h" #include "Common/GPU/Vulkan/VulkanImage.h" #include "Common/GPU/Vulkan/VulkanMemory.h" +#include "Common/Thread/Promise.h" #include "Core/Config.h" @@ -192,6 +193,7 @@ public: const std::string &GetSource() const { return source_; } ~VKShaderModule() { if (module_) { + DEBUG_LOG(G3D, "Queueing %s (shmodule %p) for release", tag_.c_str(), module_); vulkan_->Delete().QueueDeleteShaderModule(module_); } } @@ -217,7 +219,7 @@ bool VKShaderModule::Compile(VulkanContext *vulkan, ShaderLanguage language, con std::vector spirv; std::string errorMessage; if (!GLSLtoSPV(vkstage_, source_.c_str(), GLSLVariant::VULKAN, spirv, &errorMessage)) { - WARN_LOG(G3D, "Shader compile to module failed: %s", errorMessage.c_str()); + WARN_LOG(G3D, "Shader compile to module failed (%s): %s", tag_.c_str(), errorMessage.c_str()); return false; } @@ -230,10 +232,10 @@ bool VKShaderModule::Compile(VulkanContext *vulkan, ShaderLanguage language, con } #endif - if (vulkan->CreateShaderModule(spirv, &module_)) { + if (vulkan->CreateShaderModule(spirv, &module_, vkstage_ == VK_SHADER_STAGE_VERTEX_BIT ? "thin3d_vs" : "thin3d_fs")) { ok_ = true; } else { - WARN_LOG(G3D, "vkCreateShaderModule failed"); + WARN_LOG(G3D, "vkCreateShaderModule failed (%s)", tag_.c_str()); ok_ = false; } return ok_; @@ -248,13 +250,18 @@ public: class VKPipeline : public Pipeline { public: - VKPipeline(VulkanContext *vulkan, size_t size, PipelineFlags _flags) : flags(_flags), vulkan_(vulkan) { + VKPipeline(VulkanContext *vulkan, size_t size, PipelineFlags _flags, const char *tag) : vulkan_(vulkan), flags(_flags), tag_(tag) { uboSize_ = (int)size; ubo_ = new uint8_t[uboSize_]; } ~VKPipeline() { - vulkan_->Delete().QueueDeletePipeline(backbufferPipeline); - vulkan_->Delete().QueueDeletePipeline(framebufferPipeline); + DEBUG_LOG(G3D, "Queueing %s (pipeline) for release", tag_.c_str()); + if (pipeline) { + pipeline->QueueForDeletion(vulkan_); + } + for (auto dep : deps) { + dep->Release(); + } delete[] ubo_; } @@ -272,10 +279,12 @@ public: return uboSize_; } - VkPipeline backbufferPipeline = VK_NULL_HANDLE; - VkPipeline framebufferPipeline = VK_NULL_HANDLE; - + VKRGraphicsPipeline *pipeline = nullptr; + VKRGraphicsPipelineDesc vkrDesc; PipelineFlags flags; + + std::vector deps; + int stride[4]{}; int dynamicUniformSize = 0; @@ -285,6 +294,7 @@ private: VulkanContext *vulkan_; uint8_t *ubo_; int uboSize_; + std::string tag_; }; class VKTexture; @@ -374,8 +384,8 @@ public: InputLayout *CreateInputLayout(const InputLayoutDesc &desc) override; SamplerState *CreateSamplerState(const SamplerStateDesc &desc) override; RasterState *CreateRasterState(const RasterStateDesc &desc) override; - Pipeline *CreateGraphicsPipeline(const PipelineDesc &desc) override; - ShaderModule *CreateShaderModule(ShaderStage stage, ShaderLanguage language, const uint8_t *data, size_t dataSize, const std::string &tag) override; + Pipeline *CreateGraphicsPipeline(const PipelineDesc &desc, const char *tag) override; + ShaderModule *CreateShaderModule(ShaderStage stage, ShaderLanguage language, const uint8_t *data, size_t dataSize, const char *tag) override; Texture *CreateTexture(const TextureDesc &desc) override; Buffer *CreateBuffer(size_t size, uint32_t usageFlags) override; @@ -429,7 +439,7 @@ public: void DrawIndexed(int vertexCount, int offset) override; void DrawUP(const void *vdata, int vertexCount) override; - void BindCompatiblePipeline(); + void BindCurrentPipeline(); void ApplyDynamicState(); void Clear(int mask, uint32_t colorval, float depthVal, int stencilVal) override; @@ -466,13 +476,6 @@ public: switch (obj) { case NativeObject::CONTEXT: return (uint64_t)vulkan_; - case NativeObject::FRAMEBUFFER_RENDERPASS: - // Return a representative renderpass. - return (uint64_t)renderManager_.GetFramebufferRenderPass(); - case NativeObject::BACKBUFFER_RENDERPASS: - return (uint64_t)renderManager_.GetBackbufferRenderPass(); - case NativeObject::COMPATIBLE_RENDERPASS: - return (uint64_t)renderManager_.GetCompatibleRenderPass(); case NativeObject::INIT_COMMANDBUFFER: return (uint64_t)renderManager_.GetInitCmd(); case NativeObject::BOUND_TEXTURE0_IMAGEVIEW: @@ -893,6 +896,8 @@ VKContext::VKContext(VulkanContext *vulkan, bool splitSubmit) VkResult res = vkCreateDescriptorSetLayout(device_, &dsl, nullptr, &descriptorSetLayout_); _assert_(VK_SUCCESS == res); + vulkan_->SetDebugName(descriptorSetLayout_, VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT, "thin3d_d_layout"); + VkPipelineLayoutCreateInfo pl = { VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO }; pl.pPushConstantRanges = nullptr; pl.pushConstantRangeCount = 0; @@ -901,6 +906,8 @@ VKContext::VKContext(VulkanContext *vulkan, bool splitSubmit) res = vkCreatePipelineLayout(device_, &pl, nullptr, &pipelineLayout_); _assert_(VK_SUCCESS == res); + vulkan_->SetDebugName(pipelineLayout_, VK_OBJECT_TYPE_PIPELINE_LAYOUT, "thin3d_p_layout"); + VkPipelineCacheCreateInfo pc{ VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO }; res = vkCreatePipelineCache(vulkan_->GetDevice(), &pc, nullptr, &pipelineCache_); _assert_(VK_SUCCESS == res); @@ -1036,7 +1043,7 @@ VkDescriptorSet VKContext::GetOrCreateDescriptorSet(VkBuffer buf) { return descSet; } -Pipeline *VKContext::CreateGraphicsPipeline(const PipelineDesc &desc) { +Pipeline *VKContext::CreateGraphicsPipeline(const PipelineDesc &desc, const char *tag) { VKInputLayout *input = (VKInputLayout *)desc.inputLayout; VKBlendState *blend = (VKBlendState *)desc.blend; VKDepthStencilState *depth = (VKDepthStencilState *)desc.depthStencil; @@ -1047,7 +1054,26 @@ Pipeline *VKContext::CreateGraphicsPipeline(const PipelineDesc &desc) { pipelineFlags |= PIPELINE_FLAG_USES_DEPTH_STENCIL; } - VKPipeline *pipeline = new VKPipeline(vulkan_, desc.uniformDesc ? desc.uniformDesc->uniformBufferSize : 16 * sizeof(float), (PipelineFlags)pipelineFlags); + VKPipeline *pipeline = new VKPipeline(vulkan_, desc.uniformDesc ? desc.uniformDesc->uniformBufferSize : 16 * sizeof(float), (PipelineFlags)pipelineFlags, tag); + + VKRGraphicsPipelineDesc &gDesc = pipeline->vkrDesc; + + std::vector stages; + stages.resize(desc.shaders.size()); + + for (auto &iter : desc.shaders) { + VKShaderModule *vkshader = (VKShaderModule *)iter; + vkshader->AddRef(); + pipeline->deps.push_back(vkshader); + if (vkshader->GetStage() == ShaderStage::Vertex) { + gDesc.vertexShader = Promise::AlreadyDone(vkshader->Get()); + } else if (vkshader->GetStage() == ShaderStage::Fragment) { + gDesc.fragmentShader = Promise::AlreadyDone(vkshader->Get()); + } else { + ERROR_LOG(G3D, "Bad stage"); + return nullptr; + } + } if (input) { for (int i = 0; i < (int)input->bindings.size(); i++) { @@ -1056,84 +1082,51 @@ Pipeline *VKContext::CreateGraphicsPipeline(const PipelineDesc &desc) { } else { pipeline->stride[0] = 0; } + _dbg_assert_(input->bindings.size() == 1); + _dbg_assert_((int)input->attributes.size() == (int)input->visc.vertexAttributeDescriptionCount); - std::vector stages; - stages.resize(desc.shaders.size()); - int i = 0; - for (auto &iter : desc.shaders) { - VKShaderModule *vkshader = (VKShaderModule *)iter; - if (!vkshader) { - ERROR_LOG(G3D, "CreateGraphicsPipeline got passed a null shader"); - return nullptr; - } - VkPipelineShaderStageCreateInfo &stage = stages[i++]; - stage.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; - stage.pNext = nullptr; - stage.pSpecializationInfo = nullptr; - stage.stage = StageToVulkan(vkshader->GetStage()); - stage.module = vkshader->Get(); - stage.pName = "main"; - stage.flags = 0; + gDesc.ibd = input->bindings[0]; + for (int i = 0; i < input->attributes.size(); i++) { + gDesc.attrs[i] = input->attributes[i]; } + gDesc.vis.vertexAttributeDescriptionCount = input->visc.vertexAttributeDescriptionCount; + gDesc.vis.vertexBindingDescriptionCount = input->visc.vertexBindingDescriptionCount; + gDesc.vis.pVertexBindingDescriptions = &gDesc.ibd; + gDesc.vis.pVertexAttributeDescriptions = gDesc.attrs; - VkPipelineInputAssemblyStateCreateInfo inputAssembly = { VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO }; - inputAssembly.topology = primToVK[(int)desc.prim]; - inputAssembly.primitiveRestartEnable = false; + gDesc.blend0 = blend->attachments[0]; + gDesc.cbs = blend->info; + gDesc.cbs.pAttachments = &gDesc.blend0; + + gDesc.dss = depth->info; + + raster->ToVulkan(&gDesc.rs); + + // Copy bindings from input layout. + gDesc.inputAssembly.topology = primToVK[(int)desc.prim]; // We treat the three stencil states as a unit in other places, so let's do that here too. - VkDynamicState dynamics[] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK, VK_DYNAMIC_STATE_STENCIL_REFERENCE, VK_DYNAMIC_STATE_STENCIL_WRITE_MASK }; - VkPipelineDynamicStateCreateInfo dynamicInfo = { VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO }; - dynamicInfo.dynamicStateCount = depth->info.stencilTestEnable ? ARRAY_SIZE(dynamics) : 2; - dynamicInfo.pDynamicStates = dynamics; + const VkDynamicState dynamics[] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK, VK_DYNAMIC_STATE_STENCIL_REFERENCE, VK_DYNAMIC_STATE_STENCIL_WRITE_MASK }; + gDesc.ds.dynamicStateCount = depth->info.stencilTestEnable ? ARRAY_SIZE(dynamics) : 2; + for (size_t i = 0; i < gDesc.ds.dynamicStateCount; i++) { + gDesc.dynamicStates[i] = dynamics[i]; + } + gDesc.ds.pDynamicStates = gDesc.dynamicStates; - VkPipelineMultisampleStateCreateInfo ms{ VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO }; - ms.pSampleMask = nullptr; - ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; + gDesc.ms.pSampleMask = nullptr; + gDesc.ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; - VkPipelineViewportStateCreateInfo vs{ VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO }; - vs.viewportCount = 1; - vs.scissorCount = 1; - vs.pViewports = nullptr; // dynamic - vs.pScissors = nullptr; // dynamic + gDesc.views.viewportCount = 1; + gDesc.views.scissorCount = 1; + gDesc.views.pViewports = nullptr; // dynamic + gDesc.views.pScissors = nullptr; // dynamic + + gDesc.pipelineLayout = pipelineLayout_; VkPipelineRasterizationStateCreateInfo rs{ VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO }; - raster->ToVulkan(&rs); + raster->ToVulkan(&gDesc.rs); - VkPipelineVertexInputStateCreateInfo emptyVisc{ VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO }; - - VkGraphicsPipelineCreateInfo createInfo[2]{}; - for (auto &info : createInfo) { - info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; - info.flags = 0; - info.stageCount = (uint32_t)stages.size(); - info.pStages = stages.data(); - info.pColorBlendState = &blend->info; - info.pDepthStencilState = &depth->info; - info.pDynamicState = &dynamicInfo; - info.pInputAssemblyState = &inputAssembly; - info.pTessellationState = nullptr; - info.pMultisampleState = &ms; - info.pVertexInputState = input ? &input->visc : &emptyVisc; - info.pRasterizationState = &rs; - info.pViewportState = &vs; // Must set viewport and scissor counts even if we set the actual state dynamically. - info.layout = pipelineLayout_; - info.subpass = 0; - } - - createInfo[0].renderPass = renderManager_.GetBackbufferRenderPass(); - createInfo[1].renderPass = renderManager_.GetFramebufferRenderPass(); - - // OK, need to create new pipelines. - VkPipeline pipelines[2]{}; - VkResult result = vkCreateGraphicsPipelines(device_, pipelineCache_, 2, createInfo, nullptr, pipelines); - if (result != VK_SUCCESS) { - ERROR_LOG(G3D, "Failed to create graphics pipeline"); - delete pipeline; - return nullptr; - } - - pipeline->backbufferPipeline = pipelines[0]; - pipeline->framebufferPipeline = pipelines[1]; + pipeline->pipeline = renderManager_.CreateGraphicsPipeline(&gDesc, 1 << RP_TYPE_BACKBUFFER, tag ? tag : "thin3d"); if (desc.uniformDesc) { pipeline->dynamicUniformSize = (int)desc.uniformDesc->uniformBufferSize; @@ -1291,12 +1284,12 @@ void VKContext::BindTextures(int start, int count, Texture **textures) { } } -ShaderModule *VKContext::CreateShaderModule(ShaderStage stage, ShaderLanguage language, const uint8_t *data, size_t size, const std::string &tag) { +ShaderModule *VKContext::CreateShaderModule(ShaderStage stage, ShaderLanguage language, const uint8_t *data, size_t size, const char *tag) { VKShaderModule *shader = new VKShaderModule(stage, tag); if (shader->Compile(vulkan_, language, data, size)) { return shader; } else { - ERROR_LOG(G3D, "Failed to compile shader:\n%s", (const char *)LineNumberString((const char *)data).c_str()); + ERROR_LOG(G3D, "Failed to compile shader %s:\n%s", tag, (const char *)LineNumberString((const char *)data).c_str()); shader->Release(); return nullptr; } @@ -1338,7 +1331,7 @@ void VKContext::Draw(int vertexCount, int offset) { return; } - BindCompatiblePipeline(); + BindCurrentPipeline(); ApplyDynamicState(); renderManager_.Draw(descSet, 1, &ubo_offset, vulkanVbuf, (int)vbBindOffset + curVBufferOffsets_[0], vertexCount, offset); } @@ -1358,7 +1351,7 @@ void VKContext::DrawIndexed(int vertexCount, int offset) { return; } - BindCompatiblePipeline(); + BindCurrentPipeline(); ApplyDynamicState(); renderManager_.DrawIndexed(descSet, 1, &ubo_offset, vulkanVbuf, (int)vbBindOffset + curVBufferOffsets_[0], vulkanIbuf, (int)ibBindOffset + offset * sizeof(uint32_t), vertexCount, 1, VK_INDEX_TYPE_UINT16); } @@ -1374,18 +1367,13 @@ void VKContext::DrawUP(const void *vdata, int vertexCount) { return; } - BindCompatiblePipeline(); + BindCurrentPipeline(); ApplyDynamicState(); renderManager_.Draw(descSet, 1, &ubo_offset, vulkanVbuf, (int)vbBindOffset + curVBufferOffsets_[0], vertexCount); } -void VKContext::BindCompatiblePipeline() { - VkRenderPass renderPass = renderManager_.GetCompatibleRenderPass(); - if (renderPass == renderManager_.GetBackbufferRenderPass()) { - renderManager_.BindPipeline(curPipeline_->backbufferPipeline, curPipeline_->flags, pipelineLayout_); - } else { - renderManager_.BindPipeline(curPipeline_->framebufferPipeline, curPipeline_->flags, pipelineLayout_); - } +void VKContext::BindCurrentPipeline() { + renderManager_.BindPipeline(curPipeline_->pipeline, curPipeline_->flags, pipelineLayout_); } void VKContext::Clear(int clearMask, uint32_t colorval, float depthVal, int stencilVal) { @@ -1497,7 +1485,7 @@ Framebuffer *VKContext::CreateFramebuffer(const FramebufferDesc &desc) { VkCommandBuffer cmd = renderManager_.GetInitCmd(); // TODO: We always create with depth here, even when it's not needed (such as color temp FBOs). // Should optimize those away. - VKRFramebuffer *vkrfb = new VKRFramebuffer(vulkan_, cmd, renderManager_.GetFramebufferRenderPass(), desc.width, desc.height, desc.tag); + VKRFramebuffer *vkrfb = new VKRFramebuffer(vulkan_, cmd, renderManager_.GetQueueRunner()->GetCompatibleRenderPass(), desc.width, desc.height, desc.tag); return new VKFramebuffer(vkrfb); } diff --git a/Common/GPU/thin3d.h b/Common/GPU/thin3d.h index 21d605b6cd..6196f494f9 100644 --- a/Common/GPU/thin3d.h +++ b/Common/GPU/thin3d.h @@ -239,9 +239,6 @@ enum class NativeObject { BACKBUFFER_COLOR_TEX, BACKBUFFER_DEPTH_TEX, FEATURE_LEVEL, - COMPATIBLE_RENDERPASS, - BACKBUFFER_RENDERPASS, - FRAMEBUFFER_RENDERPASS, INIT_COMMANDBUFFER, BOUND_TEXTURE0_IMAGEVIEW, BOUND_TEXTURE1_IMAGEVIEW, @@ -619,8 +616,8 @@ public: virtual RasterState *CreateRasterState(const RasterStateDesc &desc) = 0; // virtual ComputePipeline CreateComputePipeline(const ComputePipelineDesc &desc) = 0 virtual InputLayout *CreateInputLayout(const InputLayoutDesc &desc) = 0; - virtual ShaderModule *CreateShaderModule(ShaderStage stage, ShaderLanguage language, const uint8_t *data, size_t dataSize, const std::string &tag = "thin3d") = 0; - virtual Pipeline *CreateGraphicsPipeline(const PipelineDesc &desc) = 0; + virtual ShaderModule *CreateShaderModule(ShaderStage stage, ShaderLanguage language, const uint8_t *data, size_t dataSize, const char *tag = "thin3d") = 0; + virtual Pipeline *CreateGraphicsPipeline(const PipelineDesc &desc, const char *tag) = 0; // Note that these DO NOT AddRef so you must not ->Release presets unless you manually AddRef them. ShaderModule *GetVshaderPreset(VertexShaderPreset preset) { return vsPresets_[preset]; } diff --git a/Common/Math/expression_parser.cpp b/Common/Math/expression_parser.cpp index 1b9ed7ba90..970c9c4a20 100644 --- a/Common/Math/expression_parser.cpp +++ b/Common/Math/expression_parser.cpp @@ -580,8 +580,7 @@ bool parsePostfixExpression(PostfixExpression& exp, IExpressionFunctions* funcs, return true; } -bool parseExpression(char* exp, IExpressionFunctions* funcs, uint32_t& dest) -{ +bool parseExpression(const char *exp, IExpressionFunctions *funcs, uint32_t &dest) { PostfixExpression postfix; if (initPostfixExpression(exp,funcs,postfix) == false) return false; return parsePostfixExpression(postfix,funcs,dest); diff --git a/Common/Thread/Promise.h b/Common/Thread/Promise.h index 4145b4b6c1..6fae6d7a2b 100644 --- a/Common/Thread/Promise.h +++ b/Common/Thread/Promise.h @@ -79,6 +79,7 @@ public: // Returns T if the data is ready, nullptr if it's not. T Poll() { + _dbg_assert_(this != nullptr); std::lock_guard guard(readyMutex_); if (ready_) { return data_; @@ -95,6 +96,7 @@ public: } T BlockUntilReady() { + _dbg_assert_(this != nullptr); std::lock_guard guard(readyMutex_); if (ready_) { return data_; diff --git a/Common/VR/PPSSPPVR.cpp b/Common/VR/PPSSPPVR.cpp index 6a5ac4c0d5..71b4919bf1 100644 --- a/Common/VR/PPSSPPVR.cpp +++ b/Common/VR/PPSSPPVR.cpp @@ -96,7 +96,7 @@ bool IsVRBuild() { return true; } -void InitVROnAndroid(void* vm, void* activity, int version, char* name) { +void InitVROnAndroid(void* vm, void* activity, int version, const char* name) { ovrJava java; java.Vm = (JavaVM*)vm; java.ActivityObject = (jobject)activity; diff --git a/Common/VR/PPSSPPVR.h b/Common/VR/PPSSPPVR.h index dde26bf72a..e7151130ea 100644 --- a/Common/VR/PPSSPPVR.h +++ b/Common/VR/PPSSPPVR.h @@ -7,7 +7,7 @@ // VR app flow integration bool IsVRBuild(); -void InitVROnAndroid(void* vm, void* activity, int version, char* name); +void InitVROnAndroid(void* vm, void* activity, int version, const char* name); void EnterVR(bool firstStart); void GetVRResolutionPerEye(int* width, int* height); void UpdateVRInput(bool(*NativeKey)(const KeyInput &key), bool(*NativeTouch)(const TouchInput &touch), bool haptics, float dp_xscale, float dp_yscale); @@ -30,7 +30,7 @@ void UpdateVRView(float* leftEye, float* rightEye); // VR app flow integration inline bool IsVRBuild() { return false; } -inline void InitVROnAndroid(void* vm, void* activity, int version, char* name) {} +inline void InitVROnAndroid(void* vm, void* activity, int version, const char* name) {} inline void EnterVR(bool firstTime) {} inline void GetVRResolutionPerEye(int* width, int* height) {} inline void UpdateVRInput(bool(*NativeKey)(const KeyInput &key), bool(*NativeTouch)(const TouchInput &touch), bool haptics, float dp_xscale, float dp_yscale) {} diff --git a/Core/Compatibility.cpp b/Core/Compatibility.cpp index f3970fac65..75c0623ead 100644 --- a/Core/Compatibility.cpp +++ b/Core/Compatibility.cpp @@ -107,6 +107,7 @@ void Compatibility::CheckSettings(IniFile &iniFile, const std::string &gameID) { CheckSetting(iniFile, gameID, "DeswizzleDepth", &flags_.DeswizzleDepth); CheckSetting(iniFile, gameID, "SplitFramebufferMargin", &flags_.SplitFramebufferMargin); CheckSetting(iniFile, gameID, "ForceLowerResolutionForEffectsOn", &flags_.ForceLowerResolutionForEffectsOn); + CheckSetting(iniFile, gameID, "AllowDownloadCLUT", &flags_.AllowDownloadCLUT); } void Compatibility::CheckSetting(IniFile &iniFile, const std::string &gameID, const char *option, bool *flag) { diff --git a/Core/Compatibility.h b/Core/Compatibility.h index 83ba931fd4..04f3ab22b7 100644 --- a/Core/Compatibility.h +++ b/Core/Compatibility.h @@ -88,6 +88,7 @@ struct CompatFlags { bool DeswizzleDepth; bool SplitFramebufferMargin; bool ForceLowerResolutionForEffectsOn; + bool AllowDownloadCLUT; }; struct VRCompat { diff --git a/Core/HLE/sceAtrac.cpp b/Core/HLE/sceAtrac.cpp index b22c439bc1..f336d8713b 100644 --- a/Core/HLE/sceAtrac.cpp +++ b/Core/HLE/sceAtrac.cpp @@ -116,6 +116,8 @@ const int PSP_ATRAC_LOOP_STREAM_DATA_IS_ON_MEMORY = -3; const u32 ATRAC3_MAX_SAMPLES = 0x400; const u32 ATRAC3PLUS_MAX_SAMPLES = 0x800; +const size_t overAllocBytes = 16384; + static const int atracDecodeDelay = 2300; #ifdef USE_FFMPEG @@ -264,7 +266,8 @@ struct Atrac { if (p.mode == p.MODE_READ) { if (dataBuf_) delete [] dataBuf_; - dataBuf_ = new u8[first_.filesize]; + dataBuf_ = new u8[first_.filesize + overAllocBytes]; + memset(dataBuf_, 0, first_.filesize + overAllocBytes); } DoArray(p, dataBuf_, first_.filesize); } @@ -453,7 +456,7 @@ struct Atrac { #else // Future versions may add other things to free, but avcodec_free_context didn't exist yet here. // Some old versions crash when we try to free extradata and subtitle_header, so let's not. A minor - // leak is better than a segfualt. + // leak is better than a segfault. // av_freep(&codecCtx_->extradata); // av_freep(&codecCtx_->subtitle_header); avcodec_close(codecCtx_); @@ -1948,7 +1951,11 @@ static int _AtracSetData(Atrac *atrac, u32 buffer, u32 readSize, u32 bufferSize, const char *codecName = atrac->codecType_ == PSP_MODE_AT_3 ? "atrac3" : "atrac3+"; const char *channelName = atrac->channels_ == 1 ? "mono" : "stereo"; - atrac->dataBuf_ = new u8[atrac->first_.filesize]; + // Over-allocate databuf to prevent going off the end if the bitstream is bad or if there are + // bugs in the decoder. This happens, see issue #15788. Arbitrary, but let's make it a whole page on the popular + // architecture that has the largest pages (M1). + atrac->dataBuf_ = new u8[atrac->first_.filesize + overAllocBytes]; + memset(atrac->dataBuf_, 0, atrac->first_.filesize + overAllocBytes); if (!atrac->ignoreDataBuf_) { u32 copybytes = std::min(bufferSize, atrac->first_.filesize); Memory::Memcpy(atrac->dataBuf_, buffer, copybytes, "AtracSetData"); @@ -2455,7 +2462,9 @@ static int sceAtracLowLevelInitDecoder(int atracID, u32 paramsAddr) { atrac->first_.size = 0; atrac->first_.filesize = atrac->bytesPerFrame_; atrac->bufferState_ = ATRAC_STATUS_LOW_LEVEL; - atrac->dataBuf_ = new u8[atrac->first_.filesize]; + + atrac->dataBuf_ = new u8[atrac->first_.filesize + overAllocBytes]; + memset(atrac->dataBuf_, 0, atrac->first_.filesize + overAllocBytes); atrac->currentSample_ = 0; int ret = __AtracSetContext(atrac); diff --git a/Core/HLE/sceGe.cpp b/Core/HLE/sceGe.cpp index 46230373d2..81667a448e 100644 --- a/Core/HLE/sceGe.cpp +++ b/Core/HLE/sceGe.cpp @@ -565,8 +565,32 @@ static int sceGeGetMtx(int type, u32 matrixPtr) { static u32 sceGeGetCmd(int cmd) { if (cmd >= 0 && cmd < (int)ARRAY_SIZE(gstate.cmdmem)) { - // Does not mask away the high bits. - return hleLogSuccessInfoX(SCEGE, gstate.cmdmem[cmd]); + // Does not mask away the high bits. But matrix regs don't read back. + u32 val = gstate.cmdmem[cmd]; + switch (cmd) { + case GE_CMD_BONEMATRIXDATA: + case GE_CMD_WORLDMATRIXDATA: + case GE_CMD_VIEWMATRIXDATA: + case GE_CMD_PROJMATRIXDATA: + case GE_CMD_TGENMATRIXDATA: + val &= 0xFF000000; + break; + + case GE_CMD_BONEMATRIXNUMBER: + val &= 0xFF00007F; + break; + + case GE_CMD_WORLDMATRIXNUMBER: + case GE_CMD_VIEWMATRIXNUMBER: + case GE_CMD_PROJMATRIXNUMBER: + case GE_CMD_TGENMATRIXNUMBER: + val &= 0xFF00000F; + break; + + default: + break; + } + return hleLogSuccessInfoX(SCEGE, val); } return hleLogError(SCEGE, SCE_KERNEL_ERROR_INVALID_INDEX); } diff --git a/GPU/Common/Draw2D.cpp b/GPU/Common/Draw2D.cpp index cd54704e9a..ff7aab3169 100644 --- a/GPU/Common/Draw2D.cpp +++ b/GPU/Common/Draw2D.cpp @@ -64,6 +64,7 @@ Draw2DPipelineInfo GenerateDraw2DCopyColorFs(ShaderWriter &writer) { writer.EndFSMain("outColor", FSFLAG_NONE); return Draw2DPipelineInfo{ + "draw2d_copy_color", RASTER_COLOR, RASTER_COLOR, }; @@ -77,6 +78,7 @@ Draw2DPipelineInfo GenerateDraw2DCopyDepthFs(ShaderWriter &writer) { writer.EndFSMain("outColor", FSFLAG_WRITEDEPTH); return Draw2DPipelineInfo{ + "draw2d_copy_depth", RASTER_DEPTH, RASTER_DEPTH, }; @@ -95,6 +97,7 @@ Draw2DPipelineInfo GenerateDraw2D565ToDepthFs(ShaderWriter &writer) { writer.EndFSMain("outColor", FSFLAG_WRITEDEPTH); return Draw2DPipelineInfo{ + "draw2d_565_to_depth", RASTER_COLOR, RASTER_DEPTH, }; @@ -119,6 +122,7 @@ Draw2DPipelineInfo GenerateDraw2D565ToDepthDeswizzleFs(ShaderWriter &writer) { writer.EndFSMain("outColor", FSFLAG_WRITEDEPTH); return Draw2DPipelineInfo{ + "draw2d_565_to_depth_deswizzle", RASTER_COLOR, RASTER_DEPTH }; @@ -198,7 +202,7 @@ Draw2DPipeline *Draw2D::Create2DPipeline(std::functionCreateShaderModule(ShaderStage::Fragment, shaderLanguageDesc.shaderLanguage, (const uint8_t *)fsCode, strlen(fsCode), "draw2d_fs"); + ShaderModule *fs = draw_->CreateShaderModule(ShaderStage::Fragment, shaderLanguageDesc.shaderLanguage, (const uint8_t *)fsCode, strlen(fsCode), info.tag); _assert_(fs); @@ -237,7 +241,7 @@ Draw2DPipeline *Draw2D::Create2DPipeline(std::functionCreateGraphicsPipeline(pipelineDesc); + Draw::Pipeline *pipeline = draw_->CreateGraphicsPipeline(pipelineDesc, info.tag); fs->Release(); diff --git a/GPU/Common/Draw2D.h b/GPU/Common/Draw2D.h index 2df15581b0..d44f7ff613 100644 --- a/GPU/Common/Draw2D.h +++ b/GPU/Common/Draw2D.h @@ -31,6 +31,7 @@ inline RasterChannel Draw2DSourceChannel(Draw2DShader shader) { } struct Draw2DPipelineInfo { + const char *tag; RasterChannel readChannel; RasterChannel writeChannel; Slice samplers; diff --git a/GPU/Common/FragmentShaderGenerator.cpp b/GPU/Common/FragmentShaderGenerator.cpp index 42205de0e7..fe3d685f28 100644 --- a/GPU/Common/FragmentShaderGenerator.cpp +++ b/GPU/Common/FragmentShaderGenerator.cpp @@ -36,8 +36,11 @@ #define WRITE(p, ...) p.F(__VA_ARGS__) -bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLanguageDesc &compat, Draw::Bugs bugs, uint64_t *uniformMask, std::string *errorString) { +bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLanguageDesc &compat, Draw::Bugs bugs, uint64_t *uniformMask, FragmentShaderFlags *fragmentShaderFlags, std::string *errorString) { *uniformMask = 0; + if (fragmentShaderFlags) { + *fragmentShaderFlags = (FragmentShaderFlags)0; + } errorString->clear(); bool highpFog = false; @@ -89,8 +92,14 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu bool flatBug = bugs.Has(Draw::Bugs::BROKEN_FLAT_IN_SHADER) && g_Config.bVendorBugChecksEnabled; bool doFlatShading = id.Bit(FS_BIT_FLATSHADE) && !flatBug; - bool shaderDepal = id.Bit(FS_BIT_SHADER_DEPAL) && !texture3D; // combination with texture3D not supported. Enforced elsewhere too. - bool smoothedDepal = id.Bit(FS_BIT_SHADER_SMOOTHED_DEPAL); + ShaderDepalMode shaderDepalMode = (ShaderDepalMode)id.Bits(FS_BIT_SHADER_DEPAL_MODE, 2); + if (texture3D) { + shaderDepalMode = ShaderDepalMode::OFF; + } + if (!compat.bitwiseOps && shaderDepalMode != ShaderDepalMode::OFF) { + *errorString = "depal requires bitwise ops"; + return false; + } bool bgraTexture = id.Bit(FS_BIT_BGRA_TEXTURE); bool colorWriteMask = id.Bit(FS_BIT_COLOR_WRITEMASK) && compat.bitwiseOps; @@ -131,7 +140,7 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu bool needFragCoord = readFramebuffer || gstate_c.Supports(GPU_ROUND_FRAGMENT_DEPTH_TO_16BIT); bool writeDepth = gstate_c.Supports(GPU_ROUND_FRAGMENT_DEPTH_TO_16BIT); - if (shaderDepal && !doTexture) { + if (shaderDepalMode != ShaderDepalMode::OFF && !doTexture) { *errorString = "depal requires a texture"; return false; } @@ -150,7 +159,7 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu WRITE(p, "layout (binding = 1) uniform sampler2D fbotex;\n"); } - if (shaderDepal) { + if (shaderDepalMode != ShaderDepalMode::OFF) { WRITE(p, "layout (binding = 2) uniform sampler2D pal;\n"); } @@ -218,7 +227,7 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu WRITE(p, "float u_mipBias : register(c%i);\n", CONST_PS_MIPBIAS); } } else { - WRITE(p, "SamplerState samp : register(s0);\n"); + WRITE(p, "SamplerState texSamp : register(s0);\n"); if (texture3D) { WRITE(p, "Texture3D tex : register(t0);\n"); } else { @@ -228,11 +237,14 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu // No sampler required, we Load WRITE(p, "Texture2D fbotex : register(t1);\n"); } - WRITE(p, "cbuffer base : register(b0) {\n%s};\n", ub_baseStr); - if (shaderDepal) { + if (shaderDepalMode != ShaderDepalMode::OFF) { + WRITE(p, "SamplerState palSamp : register(s3);\n"); + WRITE(p, "Texture2D pal : register(t3);\n"); WRITE(p, "float2 textureSize(Texture2D tex, int mip) { float2 size; tex.GetDimensions(size.x, size.y); return size; }\n"); } + + WRITE(p, "cbuffer base : register(b0) {\n%s};\n", ub_baseStr); } if (enableAlphaTest) { @@ -293,7 +305,7 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu WRITE(p, "};\n"); } } else if (ShaderLanguageIsOpenGL(compat.shaderLanguage)) { - if ((shaderDepal || colorWriteMask) && gl_extensions.IsGLES) { + if ((shaderDepalMode != ShaderDepalMode::OFF || colorWriteMask) && gl_extensions.IsGLES) { WRITE(p, "precision highp int;\n"); } @@ -344,7 +356,7 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu } } - if (shaderDepal) { + if (shaderDepalMode != ShaderDepalMode::OFF) { WRITE(p, "uniform sampler2D pal;\n"); WRITE(p, "uniform uint u_depal_mask_shift_off_fmt;\n"); *uniformMask |= DIRTY_DEPAL; @@ -554,19 +566,20 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu doTextureProjection = false; } - if (!shaderDepal) { + switch (shaderDepalMode) { + case ShaderDepalMode::OFF: if (compat.shaderLanguage == HLSL_D3D11) { if (texture3D) { if (doTextureProjection) { - WRITE(p, " vec4 t = tex.Sample(samp, vec3(v_texcoord.xy / v_texcoord.z, u_mipBias))%s;\n", bgraTexture ? ".bgra" : ""); + WRITE(p, " vec4 t = tex.Sample(texSamp, vec3(v_texcoord.xy / v_texcoord.z, u_mipBias))%s;\n", bgraTexture ? ".bgra" : ""); } else { - WRITE(p, " vec4 t = tex.Sample(samp, vec3(%s.xy, u_mipBias))%s;\n", texcoord, bgraTexture ? ".bgra" : ""); + WRITE(p, " vec4 t = tex.Sample(texSamp, vec3(%s.xy, u_mipBias))%s;\n", texcoord, bgraTexture ? ".bgra" : ""); } } else { if (doTextureProjection) { - WRITE(p, " vec4 t = tex.Sample(samp, v_texcoord.xy / v_texcoord.z)%s;\n", bgraTexture ? ".bgra" : ""); + WRITE(p, " vec4 t = tex.Sample(texSamp, v_texcoord.xy / v_texcoord.z)%s;\n", bgraTexture ? ".bgra" : ""); } else { - WRITE(p, " vec4 t = tex.Sample(samp, %s.xy)%s;\n", texcoord, bgraTexture ? ".bgra" : ""); + WRITE(p, " vec4 t = tex.Sample(texSamp, %s.xy)%s;\n", texcoord, bgraTexture ? ".bgra" : ""); } } } else if (compat.shaderLanguage == HLSL_D3D9) { @@ -600,34 +613,36 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu } } } - } else if (shaderDepal && smoothedDepal) { + break; + case ShaderDepalMode::SMOOTHED: // Specific mode for Test Drive. Fixes the banding. if (doTextureProjection) { // We don't use textureProj because we need better control and it's probably not much of a savings anyway. // However it is good for precision on older hardware like PowerVR. - WRITE(p, " vec2 uv = %s.xy/%s.z;\n vec2 uv_round;\n", texcoord, texcoord); + p.F(" vec2 uv = %s.xy/%s.z;\n vec2 uv_round;\n", texcoord, texcoord); } else { - WRITE(p, " vec2 uv = %s.xy;\n vec2 uv_round;\n", texcoord); + p.F(" vec2 uv = %s.xy;\n vec2 uv_round;\n", texcoord); } // Restrictions on this are checked before setting the smoothed flag. // Only RGB565 and RGBA5551 are supported, and only the specific shifts hitting the // channels directly. // Also, since we know the CLUT is smooth, we do not need to do the bilinear filter manually, we can just // lookup with the filtered value once. - WRITE(p, " vec4 t = %s(tex, %s.xy);\n", compat.texture, texcoord); - WRITE(p, " uint depalShift = (u_depal_mask_shift_off_fmt >> 8) & 0xFFU;\n"); - WRITE(p, " uint depalFmt = (u_depal_mask_shift_off_fmt >> 24) & 0x3U;\n"); - WRITE(p, " float index0 = t.r;\n"); - WRITE(p, " float factor = 31.0 / 256.0;\n"); - WRITE(p, " if (depalFmt == 0u) {\n"); // yes, different versions of Test Drive use different formats. Could do compile time by adding more compat flags but meh. - WRITE(p, " if (depalShift == 5u) { index0 = t.g; factor = 63.0 / 256.0; }\n"); - WRITE(p, " else if (depalShift == 11u) { index0 = t.b; }\n"); - WRITE(p, " } else {\n"); - WRITE(p, " if (depalShift == 5u) { index0 = t.g; }\n"); - WRITE(p, " else if (depalShift == 10u) { index0 = t.b; }\n"); - WRITE(p, " }\n"); - WRITE(p, " t = %s(pal, vec2(index0 * factor, 0.0));\n", compat.texture); - } else { + p.F(" vec4 t = ").SampleTexture2D("tex", "uv").C(";\n"); + p.C(" uint depalShift = (u_depal_mask_shift_off_fmt >> 8) & 0xFFU;\n"); + p.C(" uint depalFmt = (u_depal_mask_shift_off_fmt >> 24) & 0x3U;\n"); + p.C(" float index0 = t.r;\n"); + p.C(" float factor = 31.0 / 256.0;\n"); + p.C(" if (depalFmt == 0u) {\n"); // yes, different versions of Test Drive use different formats. Could do compile time by adding more compat flags but meh. + p.C(" if (depalShift == 5u) { index0 = t.g; factor = 63.0 / 256.0; }\n"); + p.C(" else if (depalShift == 11u) { index0 = t.b; }\n"); + p.C(" } else {\n"); + p.C(" if (depalShift == 5u) { index0 = t.g; }\n"); + p.C(" else if (depalShift == 10u) { index0 = t.b; }\n"); + p.C(" }\n"); + p.F(" t = ").SampleTexture2D("pal", "vec2(index0 * factor, 0.0)").C(";\n"); + break; + case ShaderDepalMode::NORMAL: if (doTextureProjection) { // We don't use textureProj because we need better control and it's probably not much of a savings anyway. // However it is good for precision on older hardware like PowerVR. @@ -645,10 +660,10 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu WRITE(p, " } else {\n"); WRITE(p, " uv_round = uv;\n"); WRITE(p, " }\n"); - WRITE(p, " highp vec4 t = %s(tex, uv_round);\n", compat.texture); - WRITE(p, " highp vec4 t1 = %sOffset(tex, uv_round, ivec2(1, 0));\n", compat.texture); - WRITE(p, " highp vec4 t2 = %sOffset(tex, uv_round, ivec2(0, 1));\n", compat.texture); - WRITE(p, " highp vec4 t3 = %sOffset(tex, uv_round, ivec2(1, 1));\n", compat.texture); + p.C(" highp vec4 t = ").SampleTexture2D("tex", "uv_round").C(";\n"); + p.C(" highp vec4 t1 = ").SampleTexture2DOffset("tex", "uv_round", 1, 0).C(";\n"); + p.C(" highp vec4 t2 = ").SampleTexture2DOffset("tex", "uv_round", 0, 1).C(";\n"); + p.C(" highp vec4 t3 = ").SampleTexture2DOffset("tex", "uv_round", 1, 1).C(";\n"); WRITE(p, " uint depalMask = (u_depal_mask_shift_off_fmt & 0xFFU);\n"); WRITE(p, " uint depalShift = (u_depal_mask_shift_off_fmt >> 8) & 0xFFU;\n"); WRITE(p, " uint depalOffset = ((u_depal_mask_shift_off_fmt >> 16) & 0xFFU) << 4;\n"); @@ -705,18 +720,23 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu WRITE(p, " break;\n"); WRITE(p, " };\n"); WRITE(p, " index0 = ((index0 >> depalShift) & depalMask) | depalOffset;\n"); - WRITE(p, " t = texelFetch(pal, ivec2(index0, 0), 0);\n"); + p.C(" t = ").LoadTexture2D("pal", "ivec2(index0, 0)", 0).C(";\n"); WRITE(p, " if (bilinear && !(index0 == index1 && index1 == index2 && index2 == index3)) {\n"); WRITE(p, " index1 = ((index1 >> depalShift) & depalMask) | depalOffset;\n"); WRITE(p, " index2 = ((index2 >> depalShift) & depalMask) | depalOffset;\n"); WRITE(p, " index3 = ((index3 >> depalShift) & depalMask) | depalOffset;\n"); - WRITE(p, " t1 = texelFetch(pal, ivec2(index1, 0), 0);\n"); - WRITE(p, " t2 = texelFetch(pal, ivec2(index2, 0), 0);\n"); - WRITE(p, " t3 = texelFetch(pal, ivec2(index3, 0), 0);\n"); + p.C(" t1 = ").LoadTexture2D("pal", "ivec2(index1, 0)", 0).C(";\n"); + p.C(" t2 = ").LoadTexture2D("pal", "ivec2(index2, 0)", 0).C(";\n"); + p.C(" t3 = ").LoadTexture2D("pal", "ivec2(index3, 0)", 0).C(";\n"); WRITE(p, " t = mix(t, t1, fraction.x);\n"); WRITE(p, " t2 = mix(t2, t3, fraction.x);\n"); WRITE(p, " t = mix(t, t2, fraction.y);\n"); WRITE(p, " }\n"); + break; + case ShaderDepalMode::CLUT8_8888: + // Not yet implemented. + WRITE(p, " vec4 t = vec4(0.0, 0.0, 0.0, 0.0);\n"); + break; } if (texFunc != GE_TEXFUNC_REPLACE || !doTextureAlpha) diff --git a/GPU/Common/FragmentShaderGenerator.h b/GPU/Common/FragmentShaderGenerator.h index b459543a50..85c651cf8b 100644 --- a/GPU/Common/FragmentShaderGenerator.h +++ b/GPU/Common/FragmentShaderGenerator.h @@ -17,6 +17,7 @@ #pragma once +#include "Common/Common.h" #include "Common/GPU/Shader.h" #include "Common/GPU/thin3d.h" @@ -39,4 +40,10 @@ struct FShaderID; // For stencil upload #define CONST_PS_STENCILVALUE 11 -bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLanguageDesc &compat, Draw::Bugs bugs, uint64_t *uniformMask, std::string *errorString); +// Can technically be deduced from the fragment shader ID, but this is safer. +enum class FragmentShaderFlags : u32 { + FS_FLAG_INPUT_ATTACHMENT = 1, +}; +ENUM_CLASS_BITOPS(FragmentShaderFlags); + +bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLanguageDesc &compat, Draw::Bugs bugs, uint64_t *uniformMask, FragmentShaderFlags *fragmentShaderFlags, std::string *errorString); diff --git a/GPU/Common/FramebufferManagerCommon.cpp b/GPU/Common/FramebufferManagerCommon.cpp index d907f1ac2f..e4ecfb4192 100644 --- a/GPU/Common/FramebufferManagerCommon.cpp +++ b/GPU/Common/FramebufferManagerCommon.cpp @@ -810,7 +810,7 @@ void FramebufferManagerCommon::CopyToColorFromOverlappingFramebuffers(VirtualFra } } - if (dst != currentRenderVfb_ && tookActions) { + if (currentRenderVfb_ && dst != currentRenderVfb_ && tookActions) { // Will probably just change the name of the current renderpass, since one was started by the reinterpret itself. draw_->BindFramebufferAsRenderTarget(currentRenderVfb_->fbo, { Draw::RPAction::KEEP, Draw::RPAction::KEEP, Draw::RPAction::KEEP }, "After Reinterpret"); } @@ -2552,6 +2552,11 @@ void FramebufferManagerCommon::DownloadFramebufferForClut(u32 fb_address, u32 lo 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); + if (w == 0 || h > 1) { + // Exactly aligned, or more than one row. + w = std::min(vfb->fb_stride, vfb->width); + } + // We might still have a pending draw to the fb in question, flush if so. FlushBeforeCopy(); diff --git a/GPU/Common/FramebufferManagerCommon.h b/GPU/Common/FramebufferManagerCommon.h index e4e2b86cf6..b54cc0611d 100644 --- a/GPU/Common/FramebufferManagerCommon.h +++ b/GPU/Common/FramebufferManagerCommon.h @@ -148,6 +148,7 @@ struct VirtualFramebuffer { // Convenience methods inline int WidthInBytes() const { return width * BufferFormatBytesPerPixel(fb_format); } + inline int BufferWidthInBytes() const { return bufferWidth * BufferFormatBytesPerPixel(fb_format); } inline int FbStrideInBytes() const { return fb_stride * BufferFormatBytesPerPixel(fb_format); } inline int ZStrideInBytes() const { return z_stride * 2; } }; diff --git a/GPU/Common/GPUDebugInterface.cpp b/GPU/Common/GPUDebugInterface.cpp index e4ce10ea44..1f7d04369e 100644 --- a/GPU/Common/GPUDebugInterface.cpp +++ b/GPU/Common/GPUDebugInterface.cpp @@ -15,7 +15,942 @@ // Official git repository and contact information can be found at // https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. -#include "GPUDebugInterface.h" +#include "Common/Log.h" +#include "Common/Math/expression_parser.h" +#include "Core/Debugger/SymbolMap.h" +#include "GPU/Common/GPUDebugInterface.h" +#include "GPU/Debugger/GECommandTable.h" +#include "GPU/GPUState.h" + +enum class GEReferenceIndex : uint32_t { + VADDR = 0x100, + IADDR, + OFFSET, + PC, + STALL, + BFLAG, + OP, + DATA, + CLUTADDR, + TRANSFERSRC, + TRANSFERDST, + + TEXADDR0, + TEXADDR1, + TEXADDR2, + TEXADDR3, + TEXADDR4, + TEXADDR5, + TEXADDR6, + TEXADDR7, + + BONE_MATRIX = 0x200, + WORLD_MATRIX = 0x260, + VIEW_MATRIX = 0x26C, + PROJ_MATRIX = 0x278, + TGEN_MATRIX = 0x288, + MATRIX_END = 0x294, + + FIELD_START = 0x1000, + FIELD_END = 0xFF000, +}; +ENUM_CLASS_BITOPS(GEReferenceIndex); + +struct ReferenceName { + GEReferenceIndex index; + const char *name; +}; + +static constexpr ReferenceName referenceNames[] = { + { GEReferenceIndex::VADDR, "vaddr" }, + { GEReferenceIndex::IADDR, "iaddr" }, + { GEReferenceIndex::OFFSET, "offset" }, + { GEReferenceIndex::PC, "pc" }, + { GEReferenceIndex::STALL, "stall" }, + { GEReferenceIndex::BFLAG, "bflag" }, + { GEReferenceIndex::BFLAG, "boundflag" }, + { GEReferenceIndex::OP, "op" }, + { GEReferenceIndex::DATA, "data" }, + { GEReferenceIndex::CLUTADDR, "clutaddr" }, + { GEReferenceIndex::TRANSFERSRC, "transfersrc" }, + { GEReferenceIndex::TRANSFERDST, "transferdst" }, + { GEReferenceIndex::TEXADDR0, "texaddr0" }, + { GEReferenceIndex::TEXADDR1, "texaddr1" }, + { GEReferenceIndex::TEXADDR2, "texaddr2" }, + { GEReferenceIndex::TEXADDR3, "texaddr3" }, + { GEReferenceIndex::TEXADDR4, "texaddr4" }, + { GEReferenceIndex::TEXADDR5, "texaddr5" }, + { GEReferenceIndex::TEXADDR6, "texaddr6" }, + { GEReferenceIndex::TEXADDR7, "texaddr7" }, +}; + +enum class GECmdField : uint8_t { + DATA, // Alias for the entire data. + LOW_FLAG, + LOW_U2, + LOW_U4, + LOW_U7, + LOW_U8, + LOW_U10, + LOW_U10_P1, + LOW_U11, + LOW_U16, + MID_U8, + MID_U10, // At 10, 10 bits. + MID_U10_P1, // At 10, 10 bits (add 1 to value.) + TOP_U8, + FLAG_AFTER_1, // At 1, 1 bit. + FLAG_AFTER_2, // At 2, 1 bit. + FLAG_AFTER_8, // At 8, 1 bit. + FLAG_AFTER_9, // At 9, 1 bit. + FLAG_AFTER_10, // At 10, 1 bit. + FLAG_AFTER_11, // At 11, 1 bit. + FLAG_AFTER_16, // At 16, 1 bit. + FLAG_AFTER_17, // At 17, 1 bit. + FLAG_AFTER_18, // At 18, 1 bit. + FLAG_AFTER_19, // At 19, 1 bit. + FLAG_AFTER_20, // At 20, 1 bit. + FLAG_AFTER_21, // At 21, 1 bit. + FLAG_AFTER_22, // At 22, 1 bit. + FLAG_AFTER_23, // At 23, 1 bit. + U2_AFTER_8, // At 8, 2 bits. + U3_AFTER_16, // At 16, 3 bits. + U12_AFTER_4, // At 4, 12 bits. + PRIM_TYPE, // At 16, 3 bits. + SIGNAL_TYPE, // At 16, 8 bits. + VTYPE_TC, // At 0, 2 bits. + VTYPE_COL, // At 2, 3 bits. + VTYPE_NRM, // At 5, 2 bits. + VTYPE_POS, // At 7, 2 bits. + VTYPE_WEIGHTTYPE, // At 9, 2 bits. + VTYPE_INDEX, // At 11, 2 bits. + VTYPE_WEIGHTCOUNT, // At 14, 3 bits. + VTYPE_MORPHCOUNT, // At 18, 3 bits. + PATCH_PRIM_TYPE, // At 0, 2 bits. + LIGHT_COMP, // At 0, 2 bits. + LIGHT_TYPE, // At 8, 2 bits. + LIGHT_TYPE_SPECULAR, // 1 if comp is 1 (but not 3.) + HIGH_ADDR, // At 16, 8 bits moved left to top 8 bits. + TEX_W, // At 0, 4 bits - 1 to this power. + TEX_H, // At 8, 4 bits - 1 to this power. + UVGEN_TYPE, // At 0, 2 bits. + UVGEN_PROJ, // At 8, 2 bits. + TEX_FORMAT, // At 0, 4 bits. + TEX_MINFILTER, // At 0, 3 bits. + TEX_MAGFILTER, // At 8, 1 bit. + TEX_LEVEL_MODE, // At 0, 2 bits. + LOW_U12_4_FLOAT, // At 0, 12.4 converted to float. + HIGH_S4_4_FLOAT, // At 16, s.3.4 converted to float. + TEX_FUNC, // At 0, 3 bits. + CLUT_BYTES, // At 0, 6 bits, multiplied by 8. + CLUT_FORMAT, // At 0, 2 bits. + CLUT_SHIFT, // At 2, 5 bits. + CLUT_OFFSET, // At 16, 5 bits, multiplied by 16. + COMPARE_FUNC2, // At 0, 2 bits. + COMPARE_FUNC3, // At 0, 3 bits. + STENCIL_OP_AT_0, // At 0, 3 bits. + STENCIL_OP_AT_8, // At 8, 3 bits. + STENCIL_OP_AT_16, // At 16, 3 bits. + BLEND_SRC, // At 0, 4 bits. + BLEND_DST, // At 4, 4 bits. + BLEND_EQUATION, // At 8, 3 bits. + LOGIC_OP, // At 0, 4 bits. +}; + +struct FieldName { + GECmdFormat fmt; + GECmdField field; + const char *name; +}; + +static constexpr FieldName fieldNames[] = { + { GECmdFormat::PRIM, GECmdField::LOW_U16, "count" }, + { GECmdFormat::PRIM, GECmdField::PRIM_TYPE, "type" }, + { GECmdFormat::BEZIER, GECmdField::LOW_U8, "ucount" }, + { GECmdFormat::BEZIER, GECmdField::LOW_U8, "u" }, + { GECmdFormat::BEZIER, GECmdField::MID_U8, "vcount" }, + { GECmdFormat::BEZIER, GECmdField::MID_U8, "v" }, + { GECmdFormat::SPLINE, GECmdField::LOW_U8, "ucount" }, + { GECmdFormat::SPLINE, GECmdField::LOW_U8, "u" }, + { GECmdFormat::SPLINE, GECmdField::MID_U8, "vcount" }, + { GECmdFormat::SPLINE, GECmdField::MID_U8, "v" }, + { GECmdFormat::SPLINE, GECmdField::FLAG_AFTER_16, "ufirstopen" }, + { GECmdFormat::SPLINE, GECmdField::FLAG_AFTER_17, "ulastopen" }, + { GECmdFormat::SPLINE, GECmdField::FLAG_AFTER_18, "vfirstopen" }, + { GECmdFormat::SPLINE, GECmdField::FLAG_AFTER_19, "vlastopen" }, + { GECmdFormat::SIGNAL, GECmdField::LOW_U16, "data" }, + { GECmdFormat::SIGNAL, GECmdField::SIGNAL_TYPE, "type" }, + { GECmdFormat::VERTEX_TYPE, GECmdField::VTYPE_TC, "texcoord" }, + { GECmdFormat::VERTEX_TYPE, GECmdField::VTYPE_TC, "tc" }, + { GECmdFormat::VERTEX_TYPE, GECmdField::VTYPE_COL, "col" }, + { GECmdFormat::VERTEX_TYPE, GECmdField::VTYPE_COL, "color" }, + { GECmdFormat::VERTEX_TYPE, GECmdField::VTYPE_NRM, "normal" }, + { GECmdFormat::VERTEX_TYPE, GECmdField::VTYPE_POS, "pos" }, + { GECmdFormat::VERTEX_TYPE, GECmdField::VTYPE_POS, "position" }, + { GECmdFormat::VERTEX_TYPE, GECmdField::VTYPE_WEIGHTTYPE, "weighttype" }, + { GECmdFormat::VERTEX_TYPE, GECmdField::VTYPE_WEIGHTTYPE, "weight" }, + { GECmdFormat::VERTEX_TYPE, GECmdField::VTYPE_INDEX, "index" }, + { GECmdFormat::VERTEX_TYPE, GECmdField::VTYPE_WEIGHTCOUNT, "weightcount" }, + { GECmdFormat::VERTEX_TYPE, GECmdField::VTYPE_MORPHCOUNT, "morphcount" }, + { GECmdFormat::VERTEX_TYPE, GECmdField::FLAG_AFTER_23, "through" }, + { GECmdFormat::VERTEX_TYPE, GECmdField::FLAG_AFTER_23, "throughmode" }, + { GECmdFormat::X10_Y10, GECmdField::LOW_U10, "x" }, + { GECmdFormat::X10_Y10, GECmdField::MID_U10, "y" }, + { GECmdFormat::X10_Y10, GECmdField::LOW_U10_P1, "w" }, + { GECmdFormat::X10_Y10, GECmdField::MID_U10_P1, "h" }, + { GECmdFormat::FLAG, GECmdField::LOW_FLAG, "flag" }, + { GECmdFormat::BONE_NUM, GECmdField::LOW_U7, "num" }, + { GECmdFormat::MATRIX_NUM, GECmdField::LOW_U4, "num" }, + { GECmdFormat::FLOAT, GECmdField::DATA, "data" }, + { GECmdFormat::PATCH_DIVISION, GECmdField::LOW_U8, "u" }, + { GECmdFormat::PATCH_DIVISION, GECmdField::MID_U8, "v" }, + { GECmdFormat::PATCH_PRIM, GECmdField::PATCH_PRIM_TYPE, "type" }, + { GECmdFormat::SUBPIXEL_COORD, GECmdField::LOW_U4, "frac" }, + { GECmdFormat::SUBPIXEL_COORD, GECmdField::LOW_U4, "sub" }, + { GECmdFormat::SUBPIXEL_COORD, GECmdField::LOW_U4, "subpixels" }, + { GECmdFormat::SUBPIXEL_COORD, GECmdField::U12_AFTER_4, "int" }, + { GECmdFormat::SUBPIXEL_COORD, GECmdField::U12_AFTER_4, "integer" }, + { GECmdFormat::SUBPIXEL_COORD, GECmdField::LOW_U12_4_FLOAT, "pixels" }, + { GECmdFormat::MATERIAL_UPDATE, GECmdField::LOW_FLAG, "ambient" }, + { GECmdFormat::MATERIAL_UPDATE, GECmdField::FLAG_AFTER_1, "diffuse" }, + { GECmdFormat::MATERIAL_UPDATE, GECmdField::FLAG_AFTER_2, "specular" }, + { GECmdFormat::RGB, GECmdField::LOW_U8, "r" }, + { GECmdFormat::RGB, GECmdField::LOW_U8, "red" }, + { GECmdFormat::RGB, GECmdField::MID_U8, "g" }, + { GECmdFormat::RGB, GECmdField::MID_U8, "green" }, + { GECmdFormat::RGB, GECmdField::TOP_U8, "b" }, + { GECmdFormat::RGB, GECmdField::TOP_U8, "blue" }, + { GECmdFormat::LIGHT_TYPE, GECmdField::LIGHT_COMP, "computation" }, + { GECmdFormat::LIGHT_TYPE, GECmdField::LIGHT_TYPE, "type" }, + { GECmdFormat::LIGHT_TYPE, GECmdField::LIGHT_TYPE_SPECULAR, "specular" }, + { GECmdFormat::STRIDE, GECmdField::LOW_U11, "stride" }, + { GECmdFormat::STRIDE_HIGH_ADDR, GECmdField::HIGH_ADDR, "highaddr" }, + { GECmdFormat::HIGH_ADDR, GECmdField::HIGH_ADDR, "highaddr" }, + { GECmdFormat::HIGH_ADDR_ONLY, GECmdField::HIGH_ADDR, "highaddr" }, + { GECmdFormat::TEX_SIZE, GECmdField::TEX_W, "w" }, + { GECmdFormat::TEX_SIZE, GECmdField::TEX_W, "width" }, + { GECmdFormat::TEX_SIZE, GECmdField::TEX_H, "h" }, + { GECmdFormat::TEX_SIZE, GECmdField::TEX_H, "height" }, + { GECmdFormat::TEX_MAP_MODE, GECmdField::UVGEN_TYPE, "type" }, + { GECmdFormat::TEX_MAP_MODE, GECmdField::UVGEN_TYPE, "uv" }, + { GECmdFormat::TEX_MAP_MODE, GECmdField::UVGEN_PROJ, "proj" }, + { GECmdFormat::TEX_MAP_MODE, GECmdField::UVGEN_PROJ, "factor" }, + { GECmdFormat::TEX_LIGHT_SRC, GECmdField::LOW_U2, "u" }, + { GECmdFormat::TEX_LIGHT_SRC, GECmdField::U2_AFTER_8, "v" }, + { GECmdFormat::TEX_MODE, GECmdField::LOW_FLAG, "swizzle" }, + { GECmdFormat::TEX_MODE, GECmdField::FLAG_AFTER_8, "separateclut" }, + { GECmdFormat::TEX_MODE, GECmdField::FLAG_AFTER_8, "separate" }, + { GECmdFormat::TEX_MODE, GECmdField::U3_AFTER_16, "maxlevel" }, + { GECmdFormat::TEX_MODE, GECmdField::U3_AFTER_16, "level" }, + { GECmdFormat::TEX_FORMAT, GECmdField::TEX_FORMAT, "format" }, + { GECmdFormat::TEX_FORMAT, GECmdField::TEX_FORMAT, "fmt" }, + { GECmdFormat::TEX_FORMAT, GECmdField::FLAG_AFTER_2, "indexed" }, + { GECmdFormat::TEX_FILTER, GECmdField::TEX_MINFILTER, "min" }, + { GECmdFormat::TEX_FILTER, GECmdField::TEX_MINFILTER, "minify" }, + { GECmdFormat::TEX_FILTER, GECmdField::TEX_MAGFILTER, "mag" }, + { GECmdFormat::TEX_FILTER, GECmdField::TEX_MAGFILTER, "magnify" }, + { GECmdFormat::TEX_CLAMP, GECmdField::LOW_FLAG, "s" }, + { GECmdFormat::TEX_CLAMP, GECmdField::FLAG_AFTER_8, "t" }, + { GECmdFormat::TEX_LEVEL_MODE, GECmdField::TEX_LEVEL_MODE, "mode" }, + { GECmdFormat::TEX_LEVEL_MODE, GECmdField::HIGH_S4_4_FLOAT, "bias" }, + { GECmdFormat::TEX_FUNC, GECmdField::TEX_FUNC, "func" }, + { GECmdFormat::TEX_FUNC, GECmdField::TEX_FUNC, "function" }, + { GECmdFormat::TEX_FUNC, GECmdField::FLAG_AFTER_8, "alpha" }, + { GECmdFormat::TEX_FUNC, GECmdField::FLAG_AFTER_8, "a" }, + { GECmdFormat::TEX_FUNC, GECmdField::FLAG_AFTER_16, "double" }, + { GECmdFormat::TEX_FUNC, GECmdField::FLAG_AFTER_16, "doubling" }, + { GECmdFormat::CLUT_FORMAT, GECmdField::CLUT_FORMAT, "format" }, + { GECmdFormat::CLUT_FORMAT, GECmdField::CLUT_FORMAT, "fmt" }, + { GECmdFormat::CLUT_FORMAT, GECmdField::CLUT_SHIFT, "shift" }, + { GECmdFormat::CLUT_FORMAT, GECmdField::MID_U8, "mask" }, + { GECmdFormat::CLUT_FORMAT, GECmdField::CLUT_OFFSET, "offset" }, + { GECmdFormat::CLUT_FORMAT, GECmdField::CLUT_OFFSET, "base" }, + { GECmdFormat::CLEAR_MODE, GECmdField::LOW_FLAG, "on" }, + { GECmdFormat::CLEAR_MODE, GECmdField::LOW_FLAG, "enable" }, + { GECmdFormat::CLEAR_MODE, GECmdField::LOW_FLAG, "flag" }, + { GECmdFormat::CLEAR_MODE, GECmdField::FLAG_AFTER_8, "color" }, + { GECmdFormat::CLEAR_MODE, GECmdField::FLAG_AFTER_9, "alpha" }, + { GECmdFormat::CLEAR_MODE, GECmdField::FLAG_AFTER_9, "stencil" }, + { GECmdFormat::CLEAR_MODE, GECmdField::FLAG_AFTER_10, "depth" }, + { GECmdFormat::COLOR_TEST_FUNC, GECmdField::COMPARE_FUNC2, "func" }, + { GECmdFormat::ALPHA_TEST, GECmdField::COMPARE_FUNC3, "func" }, + { GECmdFormat::ALPHA_TEST, GECmdField::MID_U8, "ref" }, + { GECmdFormat::ALPHA_TEST, GECmdField::MID_U8, "reference" }, + { GECmdFormat::ALPHA_TEST, GECmdField::TOP_U8, "mask" }, + { GECmdFormat::STENCIL_OP, GECmdField::STENCIL_OP_AT_0, "sfail" }, + { GECmdFormat::STENCIL_OP, GECmdField::STENCIL_OP_AT_8, "zfail" }, + { GECmdFormat::STENCIL_OP, GECmdField::STENCIL_OP_AT_16, "zpass" }, + { GECmdFormat::STENCIL_OP, GECmdField::STENCIL_OP_AT_16, "pass" }, + { GECmdFormat::DEPTH_TEST_FUNC, GECmdField::COMPARE_FUNC3, "func" }, + { GECmdFormat::BLEND_MODE, GECmdField::BLEND_SRC, "src" }, + { GECmdFormat::BLEND_MODE, GECmdField::BLEND_SRC, "srcfactor" }, + { GECmdFormat::BLEND_MODE, GECmdField::BLEND_DST, "dst" }, + { GECmdFormat::BLEND_MODE, GECmdField::BLEND_DST, "dstfactor" }, + { GECmdFormat::BLEND_MODE, GECmdField::BLEND_DST, "dest" }, + { GECmdFormat::BLEND_MODE, GECmdField::BLEND_DST, "destfactor" }, + { GECmdFormat::BLEND_MODE, GECmdField::BLEND_EQUATION, "eq" }, + { GECmdFormat::BLEND_MODE, GECmdField::BLEND_EQUATION, "equation" }, + { GECmdFormat::BLEND_MODE, GECmdField::BLEND_EQUATION, "mode" }, + { GECmdFormat::LOGIC_OP, GECmdField::LOGIC_OP, "op" }, + { GECmdFormat::LOGIC_OP, GECmdField::LOGIC_OP, "mode" }, + { GECmdFormat::ALPHA_PRIM, GECmdField::LOW_U8, "alpha" }, + { GECmdFormat::ALPHA_PRIM, GECmdField::PRIM_TYPE, "type" }, + { GECmdFormat::ALPHA_PRIM, GECmdField::PRIM_TYPE, "prim" }, + { GECmdFormat::ALPHA_PRIM, GECmdField::FLAG_AFTER_11, "antialias" }, + // TODO: Clip bits? + { GECmdFormat::ALPHA_PRIM, GECmdField::FLAG_AFTER_18, "shading" }, + { GECmdFormat::ALPHA_PRIM, GECmdField::FLAG_AFTER_18, "gouraud" }, + { GECmdFormat::ALPHA_PRIM, GECmdField::FLAG_AFTER_19, "cull" }, + { GECmdFormat::ALPHA_PRIM, GECmdField::FLAG_AFTER_20, "cullccw" }, + { GECmdFormat::ALPHA_PRIM, GECmdField::FLAG_AFTER_21, "tex" }, + { GECmdFormat::ALPHA_PRIM, GECmdField::FLAG_AFTER_22, "fog" }, + { GECmdFormat::ALPHA_PRIM, GECmdField::FLAG_AFTER_23, "dither" }, +}; + +struct GECmdConstant { + const char *name; + uint32_t value; +}; + +// TODO: It would be nice if these were somehow typed... +static constexpr GECmdConstant constantNames[] = { + { "GE_PRIM_POINTS", GE_PRIM_POINTS }, + { "GE_PRIM_LINES", GE_PRIM_LINES }, + { "GE_PRIM_LINE_STRIP", GE_PRIM_LINE_STRIP }, + { "GE_PRIM_TRIANGLES", GE_PRIM_TRIANGLES }, + { "GE_PRIM_TRIANGLE_STRIP", GE_PRIM_TRIANGLE_STRIP }, + { "GE_PRIM_TRIANGLE_FAN", GE_PRIM_TRIANGLE_FAN }, + { "GE_PRIM_RECTANGLES", GE_PRIM_RECTANGLES }, + { "GE_PRIM_KEEP_PREVIOUS", GE_PRIM_KEEP_PREVIOUS }, + { "POINTS", GE_PRIM_POINTS }, + { "LINES", GE_PRIM_LINES }, + { "LINE_STRIP", GE_PRIM_LINE_STRIP }, + { "TRIANGLES", GE_PRIM_TRIANGLES }, + { "TRIANGLE_STRIP", GE_PRIM_TRIANGLE_STRIP }, + { "TRIANGLE_FAN", GE_PRIM_TRIANGLE_FAN }, + { "RECTANGLES", GE_PRIM_RECTANGLES }, + { "SPRITES", GE_PRIM_RECTANGLES }, + { "KEEP_PREVIOUS", GE_PRIM_KEEP_PREVIOUS }, + { "CONTINUE", GE_PRIM_KEEP_PREVIOUS }, + { "GE_PATCHPRIM_TRIANGLES", GE_PATCHPRIM_TRIANGLES, }, + { "GE_PATCHPRIM_LINES", GE_PATCHPRIM_LINES, }, + { "GE_PATCHPRIM_POINTS", GE_PATCHPRIM_POINTS, }, + { "GE_SIGNAL_NONE", PSP_GE_SIGNAL_NONE }, + { "GE_SIGNAL_HANDLER_SUSPEND", PSP_GE_SIGNAL_HANDLER_SUSPEND }, + { "GE_SIGNAL_HANDLER_CONTINUE", PSP_GE_SIGNAL_HANDLER_CONTINUE }, + { "GE_SIGNAL_HANDLER_PAUSE", PSP_GE_SIGNAL_HANDLER_PAUSE }, + { "GE_SIGNAL_SYNC", PSP_GE_SIGNAL_SYNC }, + { "GE_SIGNAL_JUMP", PSP_GE_SIGNAL_JUMP }, + { "GE_SIGNAL_CALL", PSP_GE_SIGNAL_CALL }, + { "GE_SIGNAL_RET", PSP_GE_SIGNAL_RET }, + { "GE_SIGNAL_RJUMP", PSP_GE_SIGNAL_RJUMP }, + { "GE_SIGNAL_RCALL", PSP_GE_SIGNAL_RCALL }, + { "GE_SIGNAL_OJUMP", PSP_GE_SIGNAL_OJUMP }, + { "GE_SIGNAL_OCALL", PSP_GE_SIGNAL_OCALL }, + { "GE_VTYPE_TC_NONE", GE_VTYPE_TC_NONE >> GE_VTYPE_TC_SHIFT }, + { "GE_VTYPE_TC_8BIT", GE_VTYPE_TC_8BIT >> GE_VTYPE_TC_SHIFT }, + { "GE_VTYPE_TC_16BIT", GE_VTYPE_TC_16BIT >> GE_VTYPE_TC_SHIFT }, + { "GE_VTYPE_TC_FLOAT", GE_VTYPE_TC_FLOAT >> GE_VTYPE_TC_SHIFT }, + { "GE_VTYPE_COL_NONE", GE_VTYPE_COL_NONE >> GE_VTYPE_COL_SHIFT }, + { "GE_VTYPE_COL_565", GE_VTYPE_COL_565 >> GE_VTYPE_COL_SHIFT }, + { "GE_VTYPE_COL_5650", GE_VTYPE_COL_565 >> GE_VTYPE_COL_SHIFT }, + { "GE_VTYPE_COL_5551", GE_VTYPE_COL_5551 >> GE_VTYPE_COL_SHIFT }, + { "GE_VTYPE_COL_4444", GE_VTYPE_COL_4444 >> GE_VTYPE_COL_SHIFT }, + { "GE_VTYPE_COL_8888", GE_VTYPE_COL_8888 >> GE_VTYPE_COL_SHIFT }, + { "GE_VTYPE_NRM_NONE", GE_VTYPE_NRM_NONE >> GE_VTYPE_NRM_SHIFT }, + { "GE_VTYPE_NRM_8BIT", GE_VTYPE_NRM_8BIT >> GE_VTYPE_NRM_SHIFT }, + { "GE_VTYPE_NRM_16BIT", GE_VTYPE_NRM_16BIT >> GE_VTYPE_NRM_SHIFT }, + { "GE_VTYPE_NRM_FLOAT", GE_VTYPE_NRM_FLOAT >> GE_VTYPE_NRM_SHIFT }, + { "GE_VTYPE_POS_8BIT", GE_VTYPE_POS_8BIT >> GE_VTYPE_POS_SHIFT }, + { "GE_VTYPE_POS_16BIT", GE_VTYPE_POS_16BIT >> GE_VTYPE_POS_SHIFT }, + { "GE_VTYPE_POS_FLOAT", GE_VTYPE_POS_FLOAT >> GE_VTYPE_POS_SHIFT }, + { "GE_VTYPE_WEIGHT_NONE", GE_VTYPE_WEIGHT_NONE >> GE_VTYPE_WEIGHT_SHIFT }, + { "GE_VTYPE_WEIGHT_8BIT", GE_VTYPE_WEIGHT_8BIT >> GE_VTYPE_WEIGHT_SHIFT }, + { "GE_VTYPE_WEIGHT_16BIT", GE_VTYPE_WEIGHT_16BIT >> GE_VTYPE_WEIGHT_SHIFT }, + { "GE_VTYPE_WEIGHT_FLOAT", GE_VTYPE_WEIGHT_FLOAT >> GE_VTYPE_WEIGHT_SHIFT }, + { "GE_VTYPE_IDX_NONE", GE_VTYPE_IDX_NONE >> GE_VTYPE_IDX_SHIFT }, + { "GE_VTYPE_IDX_8BIT", GE_VTYPE_IDX_8BIT >> GE_VTYPE_IDX_SHIFT }, + { "GE_VTYPE_IDX_16BIT", GE_VTYPE_IDX_16BIT >> GE_VTYPE_IDX_SHIFT }, + { "GE_VTYPE_IDX_32BIT", GE_VTYPE_IDX_32BIT >> GE_VTYPE_IDX_SHIFT }, + { "GE_LIGHTCOMP_ONLYDIFFUSE", GE_LIGHTCOMP_ONLYDIFFUSE }, + { "GE_LIGHTCOMP_BOTH", GE_LIGHTCOMP_BOTH }, + { "GE_LIGHTCOMP_ONLYPOWDIFFUSE", GE_LIGHTCOMP_ONLYPOWDIFFUSE }, + { "GE_LIGHTTYPE_DIRECTIONAL", GE_LIGHTTYPE_DIRECTIONAL }, + { "GE_LIGHTTYPE_POINT", GE_LIGHTTYPE_POINT }, + { "GE_LIGHTTYPE_SPOT", GE_LIGHTTYPE_SPOT }, + { "GE_TEXMAP_TEXTURE_COORDS", GE_TEXMAP_TEXTURE_COORDS }, + { "GE_TEXMAP_TEXTURE_MATRIX", GE_TEXMAP_TEXTURE_MATRIX }, + { "GE_TEXMAP_ENVIRONMENT_MAP", GE_TEXMAP_ENVIRONMENT_MAP }, + { "GE_PROJMAP_POSITION", GE_PROJMAP_POSITION }, + { "GE_PROJMAP_UV", GE_PROJMAP_UV }, + { "GE_PROJMAP_NORMALIZED_NORMAL", GE_PROJMAP_NORMALIZED_NORMAL }, + { "GE_PROJMAP_NORMAL", GE_PROJMAP_NORMAL }, + { "GE_TFMT_565", GE_TFMT_5650 }, + { "GE_TFMT_5650", GE_TFMT_5650 }, + { "GE_TFMT_5551", GE_TFMT_5551 }, + { "GE_TFMT_4444", GE_TFMT_4444 }, + { "GE_TFMT_8888", GE_TFMT_8888 }, + { "GE_TFMT_CLUT4", GE_TFMT_CLUT4 }, + { "GE_TFMT_CLUT8", GE_TFMT_CLUT8 }, + { "GE_TFMT_CLUT16", GE_TFMT_CLUT16 }, + { "GE_TFMT_CLUT32", GE_TFMT_CLUT32 }, + { "GE_TFMT_DXT1", GE_TFMT_DXT1 }, + { "GE_TFMT_DXT3", GE_TFMT_DXT3 }, + { "GE_TFMT_DXT5", GE_TFMT_DXT5 }, + { "GE_CMODE_16BIT_BGR5650", GE_CMODE_16BIT_BGR5650 }, + { "GE_CMODE_16BIT_ABGR5551", GE_CMODE_16BIT_ABGR5551 }, + { "GE_CMODE_16BIT_ABGR4444", GE_CMODE_16BIT_ABGR4444 }, + { "GE_CMODE_32BIT_ABGR8888", GE_CMODE_32BIT_ABGR8888 }, + { "GE_TFILT_NEAREST", GE_TFILT_NEAREST }, + { "GE_TFILT_LINEAR", GE_TFILT_LINEAR }, + { "GE_TFILT_NEAREST_MIPMAP_NEAREST", GE_TFILT_NEAREST_MIPMAP_NEAREST }, + { "GE_TFILT_LINEAR_MIPMAP_NEAREST", GE_TFILT_LINEAR_MIPMAP_NEAREST }, + { "GE_TFILT_NEAREST_MIPMAP_LINEAR", GE_TFILT_NEAREST_MIPMAP_LINEAR }, + { "GE_TFILT_LINEAR_MIPMAP_LINEAR", GE_TFILT_LINEAR_MIPMAP_LINEAR }, + { "NEAREST", GE_TFILT_NEAREST }, + { "LINEAR", GE_TFILT_LINEAR }, + { "GE_TEXLEVEL_MODE_AUTO", GE_TEXLEVEL_MODE_AUTO }, + { "GE_TEXLEVEL_MODE_CONST", GE_TEXLEVEL_MODE_CONST }, + { "GE_TEXLEVEL_MODE_SLOPE", GE_TEXLEVEL_MODE_SLOPE }, + { "GE_TEXFUNC_MODULATE", GE_TEXFUNC_MODULATE }, + { "GE_TEXFUNC_DECAL", GE_TEXFUNC_DECAL }, + { "GE_TEXFUNC_BLEND", GE_TEXFUNC_BLEND }, + { "GE_TEXFUNC_REPLACE", GE_TEXFUNC_REPLACE }, + { "GE_TEXFUNC_ADD", GE_TEXFUNC_ADD }, + { "GE_COMP_NEVER", GE_COMP_NEVER }, + { "GE_COMP_ALWAYS", GE_COMP_ALWAYS }, + { "GE_COMP_EQUAL", GE_COMP_EQUAL }, + { "GE_COMP_NOTEQUAL", GE_COMP_NOTEQUAL }, + { "GE_COMP_LESS", GE_COMP_LESS }, + { "GE_COMP_LEQUAL", GE_COMP_LEQUAL }, + { "GE_COMP_GREATER", GE_COMP_GREATER }, + { "GE_COMP_GEQUAL", GE_COMP_GEQUAL }, + { "NEVER", GE_COMP_NEVER }, + { "ALWAYS", GE_COMP_ALWAYS }, + { "EQUAL", GE_COMP_EQUAL }, + { "NOTEQUAL", GE_COMP_NOTEQUAL }, + { "LESS", GE_COMP_LESS }, + { "LEQUAL", GE_COMP_LEQUAL }, + { "LESSEQUAL", GE_COMP_LEQUAL }, + { "GREATER", GE_COMP_GREATER }, + { "GEQUAL", GE_COMP_GEQUAL }, + { "GREATEREQUAL", GE_COMP_GEQUAL }, + { "GE_STENCILOP_KEEP", GE_STENCILOP_KEEP }, + { "GE_STENCILOP_ZERO", GE_STENCILOP_ZERO }, + { "GE_STENCILOP_REPLACE", GE_STENCILOP_REPLACE }, + { "GE_STENCILOP_INVERT", GE_STENCILOP_INVERT }, + { "GE_STENCILOP_INCR", GE_STENCILOP_INCR }, + { "GE_STENCILOP_DECR", GE_STENCILOP_DECR }, + { "GE_BLENDMODE_MUL_AND_ADD", GE_BLENDMODE_MUL_AND_ADD }, + { "GE_BLENDMODE_MUL_AND_SUBTRACT", GE_BLENDMODE_MUL_AND_SUBTRACT }, + { "GE_BLENDMODE_MUL_AND_SUBTRACT_REVERSE", GE_BLENDMODE_MUL_AND_SUBTRACT_REVERSE }, + { "GE_BLENDMODE_MIN", GE_BLENDMODE_MIN }, + { "GE_BLENDMODE_MAX", GE_BLENDMODE_MAX }, + { "GE_BLENDMODE_ABSDIFF", GE_BLENDMODE_ABSDIFF }, + { "ADD", GE_BLENDMODE_MUL_AND_ADD }, + { "SUBTRACT", GE_BLENDMODE_MUL_AND_SUBTRACT }, + { "SUBTRACT_REVERSE", GE_BLENDMODE_MUL_AND_SUBTRACT_REVERSE }, + { "MIN", GE_BLENDMODE_MIN }, + { "MAX", GE_BLENDMODE_MAX }, + { "ABSDIFF", GE_BLENDMODE_ABSDIFF }, + { "GE_SRCBLEND_DSTCOLOR", GE_SRCBLEND_DSTCOLOR }, + { "GE_SRCBLEND_INVDSTCOLOR", GE_SRCBLEND_INVDSTCOLOR }, + { "GE_SRCBLEND_SRCALPHA", GE_SRCBLEND_SRCALPHA }, + { "GE_SRCBLEND_INVSRCALPHA", GE_SRCBLEND_INVSRCALPHA }, + { "GE_SRCBLEND_DSTALPHA", GE_SRCBLEND_DSTALPHA }, + { "GE_SRCBLEND_INVDSTALPHA", GE_SRCBLEND_INVDSTALPHA }, + { "GE_SRCBLEND_DOUBLESRCALPHA", GE_SRCBLEND_DOUBLESRCALPHA }, + { "GE_SRCBLEND_DOUBLEINVSRCALPHA", GE_SRCBLEND_DOUBLEINVSRCALPHA }, + { "GE_SRCBLEND_DOUBLEDSTALPHA", GE_SRCBLEND_DOUBLEDSTALPHA }, + { "GE_SRCBLEND_DOUBLEINVDSTALPHA", GE_SRCBLEND_DOUBLEINVDSTALPHA }, + { "GE_SRCBLEND_FIXA", GE_SRCBLEND_FIXA }, + { "GE_DSTBLEND_SRCCOLOR", GE_DSTBLEND_SRCCOLOR }, + { "GE_DSTBLEND_INVSRCCOLOR", GE_DSTBLEND_INVSRCCOLOR }, + { "GE_DSTBLEND_SRCALPHA", GE_DSTBLEND_SRCALPHA }, + { "GE_DSTBLEND_INVSRCALPHA", GE_DSTBLEND_INVSRCALPHA }, + { "GE_DSTBLEND_DSTALPHA", GE_DSTBLEND_DSTALPHA }, + { "GE_DSTBLEND_INVDSTALPHA", GE_DSTBLEND_INVDSTALPHA }, + { "GE_DSTBLEND_DOUBLESRCALPHA", GE_DSTBLEND_DOUBLESRCALPHA }, + { "GE_DSTBLEND_DOUBLEINVSRCALPHA", GE_DSTBLEND_DOUBLEINVSRCALPHA }, + { "GE_DSTBLEND_DOUBLEDSTALPHA", GE_DSTBLEND_DOUBLEDSTALPHA }, + { "GE_DSTBLEND_DOUBLEINVDSTALPHA", GE_DSTBLEND_DOUBLEINVDSTALPHA }, + { "GE_DSTBLEND_FIXB", GE_DSTBLEND_FIXB }, + { "SRCALPHA", GE_SRCBLEND_SRCALPHA }, + { "INVSRCALPHA", GE_SRCBLEND_INVSRCALPHA }, + { "INVERSESRCALPHA", GE_SRCBLEND_INVSRCALPHA }, + { "DSTALPHA", GE_DSTBLEND_DSTALPHA }, + { "INVDSTALPHA", GE_DSTBLEND_INVDSTALPHA }, + { "DOUBLESRCALPHA", GE_DSTBLEND_DOUBLESRCALPHA }, + { "DOUBLEINVSRCALPHA", GE_DSTBLEND_DOUBLEINVSRCALPHA }, + { "DOUBLEDSTALPHA", GE_DSTBLEND_DOUBLEDSTALPHA }, + { "DOUBLEINVDSTALPHA", GE_DSTBLEND_DOUBLEINVDSTALPHA }, + { "FIXED", GE_DSTBLEND_FIXB }, + { "GE_LOGIC_CLEAR", GE_LOGIC_CLEAR }, + { "GE_LOGIC_AND", GE_LOGIC_AND }, + { "GE_LOGIC_AND_REVERSE", GE_LOGIC_AND_REVERSE }, + { "GE_LOGIC_COPY", GE_LOGIC_COPY }, + { "GE_LOGIC_AND_INVERTED", GE_LOGIC_AND_INVERTED }, + { "GE_LOGIC_NOOP", GE_LOGIC_NOOP }, + { "GE_LOGIC_XOR", GE_LOGIC_XOR }, + { "GE_LOGIC_OR", GE_LOGIC_OR }, + { "GE_LOGIC_NOR", GE_LOGIC_NOR }, + { "GE_LOGIC_EQUIV", GE_LOGIC_EQUIV }, + { "GE_LOGIC_INVERTED", GE_LOGIC_INVERTED }, + { "GE_LOGIC_OR_REVERSE", GE_LOGIC_OR_REVERSE }, + { "GE_LOGIC_COPY_INVERTED", GE_LOGIC_COPY_INVERTED }, + { "GE_LOGIC_OR_INVERTED", GE_LOGIC_OR_INVERTED }, + { "GE_LOGIC_NAND", GE_LOGIC_NAND }, + { "GE_LOGIC_SET", GE_LOGIC_SET }, +}; + +class GEExpressionFunctions : public IExpressionFunctions { +public: + GEExpressionFunctions(GPUDebugInterface *gpu) : gpu_(gpu) {} + + bool parseReference(char *str, uint32_t &referenceIndex) override; + bool parseSymbol(char *str, uint32_t &symbolValue) override; + uint32_t getReferenceValue(uint32_t referenceIndex) override; + ExpressionType getReferenceType(uint32_t referenceIndex) override; + bool getMemoryValue(uint32_t address, int size, uint32_t &dest, char *error) override; + +private: + bool parseFieldReference(const char *ref, const char *field, uint32_t &referenceIndex); + uint32_t getFieldValue(GECmdFormat fmt, GECmdField field, uint32_t value); + ExpressionType getFieldType(GECmdFormat fmt, GECmdField field); + + GPUDebugInterface *gpu_; +}; + +bool GEExpressionFunctions::parseReference(char *str, uint32_t &referenceIndex) { + // TODO: Support formats and a form of fields (i.e. vtype.throughmode.) + // For now, let's just support the register bits directly. + GECmdInfo info; + if (GECmdInfoByName(str, info)) { + referenceIndex = info.reg; + return true; + } + + char *dot = strchr(str, '.'); + if (dot != nullptr) { + *dot = '\0'; + bool success = parseFieldReference(str, dot + 1, referenceIndex); + *dot = '.'; + if (success) + return true; + } + + // Also allow non-register references. + for (const auto &entry : referenceNames) { + if (strcasecmp(str, entry.name) == 0) { + referenceIndex = (uint32_t)entry.index; + return true; + } + } + + // And matrix data. Maybe should allow column/row specification. + int subindex = -1; + int len = -1; + + if (sscanf(str, "bone%i%n", &subindex, &len) == 1) { + if (len == strlen(str) && subindex < 96) { + referenceIndex = (uint32_t)GEReferenceIndex::BONE_MATRIX + subindex; + return true; + } + } + if (sscanf(str, "world%i%n", &subindex, &len) == 1) { + if (len == strlen(str) && subindex < 12) { + referenceIndex = (uint32_t)GEReferenceIndex::WORLD_MATRIX + subindex; + return true; + } + } + if (sscanf(str, "view%i%n", &subindex, &len) == 1) { + if (len == strlen(str) && subindex < 12) { + referenceIndex = (uint32_t)GEReferenceIndex::VIEW_MATRIX + subindex; + return true; + } + } + if (sscanf(str, "proj%i%n", &subindex, &len) == 1) { + if (len == strlen(str) && subindex < 16) { + referenceIndex = (uint32_t)GEReferenceIndex::PROJ_MATRIX + subindex; + return true; + } + } + if (sscanf(str, "tgen%i%n", &subindex, &len) == 1 || sscanf(str, "texgen%i%n", &subindex, &len) == 1) { + if (len == strlen(str) && subindex < 12) { + referenceIndex = (uint32_t)GEReferenceIndex::TGEN_MATRIX + subindex; + return true; + } + } + + return false; +} + +bool GEExpressionFunctions::parseFieldReference(const char *ref, const char *field, uint32_t &referenceIndex) { + GECmdInfo info; + if (!GECmdInfoByName(ref, info)) { + return false; + } + + for (const auto &entry : fieldNames) { + if (entry.fmt == info.fmt && strcasecmp(field, entry.name) == 0) { + referenceIndex = (info.reg << 12) | (uint32_t)entry.field; + return true; + } + } + + return false; +} + +bool GEExpressionFunctions::parseSymbol(char *str, uint32_t &symbolValue) { + // Mainly useful for checking memory addresses and constants. + + for (const auto &entry : constantNames) { + if (strcasecmp(str, entry.name) == 0) { + symbolValue = entry.value; + return true; + } + } + + return g_symbolMap->GetLabelValue(str, symbolValue); +} + +uint32_t GEExpressionFunctions::getReferenceValue(uint32_t referenceIndex) { + GPUgstate state = gpu_->GetGState(); + if (referenceIndex < 0x100) { + GECmdFormat fmt = GECmdInfoByCmd(GECommand(referenceIndex)).fmt; + uint32_t value = state.cmdmem[referenceIndex]; + if (fmt == GECmdFormat::FLOAT) + return value << 8; + return value & 0x00FFFFFF; + } + + if (referenceIndex >= (uint32_t)GEReferenceIndex::FIELD_START && referenceIndex <= (uint32_t)GEReferenceIndex::FIELD_END) { + uint32_t value = state.cmdmem[referenceIndex >> 12] & 0x00FFFFFF; + GECmdFormat fmt = GECmdInfoByCmd(GECommand(referenceIndex >> 12)).fmt; + return getFieldValue(fmt, GECmdField(referenceIndex & 0xFF), value); + } + + // We return the matrix value as float bits, which gets interpreted correctly in the parser. + if (referenceIndex >= (uint32_t)GEReferenceIndex::BONE_MATRIX && referenceIndex < (uint32_t)GEReferenceIndex::MATRIX_END) { + float value; + if (referenceIndex >= (uint32_t)GEReferenceIndex::TGEN_MATRIX) { + value = state.tgenMatrix[referenceIndex - (uint32_t)GEReferenceIndex::TGEN_MATRIX]; + } else if (referenceIndex >= (uint32_t)GEReferenceIndex::PROJ_MATRIX) { + value = state.projMatrix[referenceIndex - (uint32_t)GEReferenceIndex::PROJ_MATRIX]; + } else if (referenceIndex >= (uint32_t)GEReferenceIndex::VIEW_MATRIX) { + value = state.viewMatrix[referenceIndex - (uint32_t)GEReferenceIndex::VIEW_MATRIX]; + } else if (referenceIndex >= (uint32_t)GEReferenceIndex::WORLD_MATRIX) { + value = state.worldMatrix[referenceIndex - (uint32_t)GEReferenceIndex::WORLD_MATRIX]; + } else { + value = state.boneMatrix[referenceIndex - (uint32_t)GEReferenceIndex::BONE_MATRIX]; + } + + uint32_t result; + memcpy(&result, &value, sizeof(result)); + return result; + } + + GEReferenceIndex ref = (GEReferenceIndex)referenceIndex; + DisplayList list; + switch (ref) { + case GEReferenceIndex::VADDR: + return gpu_->GetVertexAddress(); + case GEReferenceIndex::IADDR: + return gpu_->GetIndexAddress(); + case GEReferenceIndex::OFFSET: + // TODO: Should use an interface method, probably. + return gstate_c.offsetAddr; + case GEReferenceIndex::PC: + if (gpu_->GetCurrentDisplayList(list)) { + return list.pc; + } + return 0; + case GEReferenceIndex::STALL: + if (gpu_->GetCurrentDisplayList(list)) { + return list.stall; + } + return 0; + case GEReferenceIndex::BFLAG: + if (gpu_->GetCurrentDisplayList(list)) { + return list.bboxResult ? 1 : 0; + } + return 0; + case GEReferenceIndex::OP: + if (gpu_->GetCurrentDisplayList(list)) { + return Memory::Read_U32(list.pc); + } + return 0; + case GEReferenceIndex::DATA: + if (gpu_->GetCurrentDisplayList(list)) { + return Memory::Read_U32(list.pc) & 0x00FFFFFF; + } + return 0; + + case GEReferenceIndex::CLUTADDR: + return state.getClutAddress(); + + case GEReferenceIndex::TRANSFERSRC: + return state.getTransferSrcAddress(); + + case GEReferenceIndex::TRANSFERDST: + return state.getTransferDstAddress(); + + case GEReferenceIndex::TEXADDR0: + case GEReferenceIndex::TEXADDR1: + case GEReferenceIndex::TEXADDR2: + case GEReferenceIndex::TEXADDR3: + case GEReferenceIndex::TEXADDR4: + case GEReferenceIndex::TEXADDR5: + case GEReferenceIndex::TEXADDR6: + case GEReferenceIndex::TEXADDR7: + return state.getTextureAddress((int)ref - (int)GEReferenceIndex::TEXADDR0); + + case GEReferenceIndex::BONE_MATRIX: + case GEReferenceIndex::WORLD_MATRIX: + case GEReferenceIndex::VIEW_MATRIX: + case GEReferenceIndex::PROJ_MATRIX: + case GEReferenceIndex::TGEN_MATRIX: + case GEReferenceIndex::MATRIX_END: + case GEReferenceIndex::FIELD_START: + case GEReferenceIndex::FIELD_END: + // Shouldn't have gotten here. + break; + } + + _assert_msg_(false, "Invalid reference index"); + return 0; +} + +uint32_t GEExpressionFunctions::getFieldValue(GECmdFormat fmt, GECmdField field, uint32_t value) { + switch (field) { + case GECmdField::DATA: + return value; + case GECmdField::LOW_FLAG: + return value & 1; + case GECmdField::LOW_U2: + return value & 3; + case GECmdField::LOW_U4: + return value & 0xF; + case GECmdField::LOW_U7: + return value & 0x7F; + case GECmdField::LOW_U8: + return value & 0xFF; + case GECmdField::LOW_U10: + return value & 0x03FF; + case GECmdField::LOW_U10_P1: + return (value & 0x03FF) + 1; + case GECmdField::LOW_U11: + return value & 0x07FF; + case GECmdField::LOW_U16: + return value & 0xFFFF; + case GECmdField::MID_U8: + return (value >> 8) & 0xFF; + case GECmdField::MID_U10: + return (value >> 10) & 0x03FF; + case GECmdField::MID_U10_P1: + return ((value >> 10) & 0x03FF) + 1; + case GECmdField::TOP_U8: + return (value >> 16) & 0xFF; + case GECmdField::FLAG_AFTER_1: + return (value >> 1) & 1; + case GECmdField::FLAG_AFTER_2: + return (value >> 2) & 1; + case GECmdField::FLAG_AFTER_8: + return (value >> 8) & 1; + case GECmdField::FLAG_AFTER_9: + return (value >> 8) & 1; + case GECmdField::FLAG_AFTER_10: + return (value >> 10) & 1; + case GECmdField::FLAG_AFTER_11: + return (value >> 11) & 1; + case GECmdField::FLAG_AFTER_16: + return (value >> 16) & 1; + case GECmdField::FLAG_AFTER_17: + return (value >> 17) & 1; + case GECmdField::FLAG_AFTER_18: + return (value >> 18) & 1; + case GECmdField::FLAG_AFTER_19: + return (value >> 19) & 1; + case GECmdField::FLAG_AFTER_20: + return (value >> 20) & 1; + case GECmdField::FLAG_AFTER_21: + return (value >> 21) & 1; + case GECmdField::FLAG_AFTER_22: + return (value >> 22) & 1; + case GECmdField::FLAG_AFTER_23: + return (value >> 23) & 1; + case GECmdField::U2_AFTER_8: + return (value >> 8) & 3; + case GECmdField::U3_AFTER_16: + return (value >> 16) & 7; + case GECmdField::U12_AFTER_4: + return (value >> 4) & 0x0FFF; + + // Below here are "typed" values, maybe they'll be exposed differently than integers someday. + + case GECmdField::PRIM_TYPE: + return (value >> 16) & 7; + case GECmdField::SIGNAL_TYPE: + return (value >> 16) & 0xFF; + case GECmdField::VTYPE_TC: + return value & 3; + case GECmdField::VTYPE_COL: + return (value >> 2) & 7; + case GECmdField::VTYPE_NRM: + return (value >> 5) & 3; + case GECmdField::VTYPE_POS: + return (value >> 7) & 3; + case GECmdField::VTYPE_WEIGHTTYPE: + return (value >> 9) & 3; + case GECmdField::VTYPE_INDEX: + return (value >> 11) & 3; + case GECmdField::VTYPE_WEIGHTCOUNT: + return ((value >> 14) & 7) + 1; + case GECmdField::VTYPE_MORPHCOUNT: + return ((value >> 18) & 7) + 1; + case GECmdField::PATCH_PRIM_TYPE: + return value & 3; + case GECmdField::LIGHT_COMP: + return value & 3; + case GECmdField::LIGHT_TYPE: + return (value >> 8) & 3; + case GECmdField::LIGHT_TYPE_SPECULAR: + return (value & 3) == 1; + case GECmdField::HIGH_ADDR: + return (value << 8) & 0xFF000000; + case GECmdField::TEX_W: + return 1 << (value & 0xF); + case GECmdField::TEX_H: + return 1 << ((value >> 8) & 0xF); + case GECmdField::UVGEN_TYPE: + return value & 3; + case GECmdField::UVGEN_PROJ: + return (value >> 8) & 3; + case GECmdField::TEX_FORMAT: + return value & 0xF; + case GECmdField::TEX_MINFILTER: + return value & 7; + case GECmdField::TEX_MAGFILTER: + return (value >> 8) & 1; + case GECmdField::TEX_LEVEL_MODE: + return value & 3; + case GECmdField::LOW_U12_4_FLOAT: + { + float f = (value & 0xFFFF) / 16.0f; + uint32_t result; + memcpy(&result, &f, sizeof(result)); + return result; + } + case GECmdField::HIGH_S4_4_FLOAT: // At 16, s.3.4 converted to float. + { + int value8 = (int)(s8)((value >> 16) & 0xFF); + float f = value8 / 16.0f; + uint32_t result; + memcpy(&result, &f, sizeof(result)); + return result; + } + case GECmdField::TEX_FUNC: + return value & 7; + case GECmdField::CLUT_BYTES: + return (value & 0x3F) * 8; + case GECmdField::CLUT_FORMAT: + return value & 3; + case GECmdField::CLUT_SHIFT: + return (value >> 2) & 0x1F; + case GECmdField::CLUT_OFFSET: + return ((value >> 16) & 0x1F) << 4; + case GECmdField::COMPARE_FUNC2: + return value & 3; + case GECmdField::COMPARE_FUNC3: + return value & 7; + case GECmdField::STENCIL_OP_AT_0: + return value & 7; + case GECmdField::STENCIL_OP_AT_8: + return (value >> 8) & 7; + case GECmdField::STENCIL_OP_AT_16: + return (value >> 16) & 7; + case GECmdField::BLEND_SRC: + return value & 0xF; + case GECmdField::BLEND_DST: + return (value >> 4) & 0xF; + case GECmdField::BLEND_EQUATION: + return (value >> 8) & 7; + case GECmdField::LOGIC_OP: + return value & 0xF; + } + + _assert_msg_(false, "Invalid field type"); + return 0; +} + +ExpressionType GEExpressionFunctions::getReferenceType(uint32_t referenceIndex) { + if (referenceIndex < 0x100) { + GECmdFormat fmt = GECmdInfoByCmd(GECommand(referenceIndex)).fmt; + if (fmt == GECmdFormat::FLOAT) + return EXPR_TYPE_FLOAT; + return EXPR_TYPE_UINT; + } + + if (referenceIndex >= (uint32_t)GEReferenceIndex::FIELD_START && referenceIndex <= (uint32_t)GEReferenceIndex::FIELD_END) { + GECmdFormat fmt = GECmdInfoByCmd(GECommand(referenceIndex >> 12)).fmt; + return getFieldType(fmt, GECmdField(referenceIndex & 0xFF)); + } + + if (referenceIndex >= (uint32_t)GEReferenceIndex::BONE_MATRIX && referenceIndex < (uint32_t)GEReferenceIndex::MATRIX_END) + return EXPR_TYPE_FLOAT; + return EXPR_TYPE_UINT; +} + +ExpressionType GEExpressionFunctions::getFieldType(GECmdFormat fmt, GECmdField field) { + switch (field) { + case GECmdField::LOW_U12_4_FLOAT: + case GECmdField::HIGH_S4_4_FLOAT: + return EXPR_TYPE_FLOAT; + + default: + // Almost all of these are uint, so not listing each one. + break; + } + + return EXPR_TYPE_UINT; +} + +bool GEExpressionFunctions::getMemoryValue(uint32_t address, int size, uint32_t &dest, char *error) { + if (!Memory::IsValidRange(address, size)) { + sprintf(error, "Invalid address or size %08x + %d", address, size); + return false; + } + + switch (size) { + case 1: + dest = Memory::Read_U8(address); + return true; + case 2: + dest = Memory::Read_U16(address); + return true; + case 4: + dest = Memory::Read_U32(address); + return true; + } + + sprintf(error, "Unexpected memory access size %d", size); + return false; +} + +bool GPUDebugInitExpression(GPUDebugInterface *g, const char *str, PostfixExpression &exp) { + GEExpressionFunctions funcs(g); + return initPostfixExpression(str, &funcs, exp); +} + +bool GPUDebugExecExpression(GPUDebugInterface *g, PostfixExpression &exp, uint32_t &result) { + GEExpressionFunctions funcs(g); + return parsePostfixExpression(exp, &funcs, result); +} + +bool GPUDebugExecExpression(GPUDebugInterface *g, const char *str, uint32_t &result) { + GEExpressionFunctions funcs(g); + return parseExpression(str, &funcs, result); +} void GPUDebugBuffer::Allocate(u32 stride, u32 height, GEBufferFormat fmt, bool flipped, bool reversed) { GPUDebugBufferFormat actualFmt = GPUDebugBufferFormat(fmt); diff --git a/GPU/Common/GPUDebugInterface.h b/GPU/Common/GPUDebugInterface.h index 97e97c9ea3..09254ddf53 100644 --- a/GPU/Common/GPUDebugInterface.h +++ b/GPU/Common/GPUDebugInterface.h @@ -20,9 +20,10 @@ #include #include +#include "Common/Math/expression_parser.h" +#include "Core/MemMap.h" #include "GPU/GPU.h" #include "GPU/GPUInterface.h" -#include "Core/MemMap.h" struct GPUDebugOp { u32 pc; @@ -251,3 +252,7 @@ public: // get content of specific framebuffer / texture? // vertex / texture decoding? }; + +bool GPUDebugInitExpression(GPUDebugInterface *g, const char *str, PostfixExpression &exp); +bool GPUDebugExecExpression(GPUDebugInterface *g, PostfixExpression &exp, uint32_t &result); +bool GPUDebugExecExpression(GPUDebugInterface *g, const char *str, uint32_t &result); diff --git a/GPU/Common/PresentationCommon.cpp b/GPU/Common/PresentationCommon.cpp index 552e62a0c5..e430374079 100644 --- a/GPU/Common/PresentationCommon.cpp +++ b/GPU/Common/PresentationCommon.cpp @@ -439,7 +439,7 @@ Draw::Pipeline *PresentationCommon::CreatePipeline(std::vectorCreateRasterState({}); PipelineDesc pipelineDesc{ Primitive::TRIANGLE_LIST, shaders, inputLayout, depth, blendstateOff, rasterNoCull, uniformDesc }; - Pipeline *pipeline = draw_->CreateGraphicsPipeline(pipelineDesc); + Pipeline *pipeline = draw_->CreateGraphicsPipeline(pipelineDesc, "presentation"); inputLayout->Release(); depth->Release(); diff --git a/GPU/Common/ReinterpretFramebuffer.cpp b/GPU/Common/ReinterpretFramebuffer.cpp index b30c71e504..09f2552a9b 100644 --- a/GPU/Common/ReinterpretFramebuffer.cpp +++ b/GPU/Common/ReinterpretFramebuffer.cpp @@ -185,6 +185,7 @@ Draw2DPipelineInfo GenerateReinterpretFragmentShader(ShaderWriter &writer, GEBuf writer.EndFSMain("outColor", FSFLAG_NONE); return Draw2DPipelineInfo{ + "reinterpret", RASTER_COLOR, RASTER_COLOR, }; diff --git a/GPU/Common/ShaderId.cpp b/GPU/Common/ShaderId.cpp index d05cc3a986..f873024c39 100644 --- a/GPU/Common/ShaderId.cpp +++ b/GPU/Common/ShaderId.cpp @@ -180,8 +180,12 @@ std::string FragmentShaderDesc(const FShaderID &id) { if (id.Bit(FS_BIT_COLOR_DOUBLE)) desc << "2x "; if (id.Bit(FS_BIT_FLATSHADE)) desc << "Flat "; if (id.Bit(FS_BIT_BGRA_TEXTURE)) desc << "BGRA "; - if (id.Bit(FS_BIT_SHADER_DEPAL)) desc << "Depal "; - if (id.Bit(FS_BIT_SHADER_SMOOTHED_DEPAL)) desc << "SmoothDepal "; + switch ((ShaderDepalMode)id.Bit(FS_BIT_SHADER_DEPAL_MODE)) { + case ShaderDepalMode::OFF: break; + case ShaderDepalMode::NORMAL: desc << "Depal "; break; + case ShaderDepalMode::SMOOTHED: desc << "SmoothDepal "; break; + case ShaderDepalMode::CLUT8_8888: desc << "CLUT8From8888Depal"; break; + } if (id.Bit(FS_BIT_COLOR_WRITEMASK)) desc << "WriteMask "; if (id.Bit(FS_BIT_SHADER_TEX_CLAMP)) { desc << "TClamp"; @@ -261,8 +265,9 @@ void ComputeFragmentShaderID(FShaderID *id_out, const ComputedPipelineState &pip bool doTextureProjection = (gstate.getUVGenMode() == GE_TEXMAP_TEXTURE_MATRIX && MatrixNeedsProjection(gstate.tgenMatrix)); bool doTextureAlpha = gstate.isTextureAlphaUsed(); bool doFlatShading = gstate.getShadeMode() == GE_SHADE_FLAT; - bool useShaderDepal = gstate_c.useShaderDepal; - bool useSmoothedDepal = gstate_c.useSmoothedShaderDepal; + + ShaderDepalMode shaderDepalMode = gstate_c.shaderDepalMode; + bool colorWriteMask = pipelineState.maskState.applyFramebufferRead; ReplaceBlendType replaceBlend = pipelineState.blendState.replaceBlend; @@ -289,8 +294,7 @@ void ComputeFragmentShaderID(FShaderID *id_out, const ComputedPipelineState &pip id.SetBit(FS_BIT_TEXTURE_AT_OFFSET, textureAtOffset); } id.SetBit(FS_BIT_BGRA_TEXTURE, gstate_c.bgraTexture); - id.SetBit(FS_BIT_SHADER_DEPAL, useShaderDepal); - id.SetBit(FS_BIT_SHADER_SMOOTHED_DEPAL, useSmoothedDepal); + id.SetBits(FS_BIT_SHADER_DEPAL_MODE, 2, (int)shaderDepalMode); id.SetBit(FS_BIT_3D_TEXTURE, gstate_c.curTextureIs3D); } diff --git a/GPU/Common/ShaderId.h b/GPU/Common/ShaderId.h index bd54e2bd82..999faf2e44 100644 --- a/GPU/Common/ShaderId.h +++ b/GPU/Common/ShaderId.h @@ -66,7 +66,7 @@ enum FShaderBit : uint8_t { FS_BIT_DO_TEXTURE = 1, FS_BIT_TEXFUNC = 2, // 3 bits FS_BIT_TEXALPHA = 5, - FS_BIT_SHADER_DEPAL = 6, + FS_BIT_3D_TEXTURE = 6, FS_BIT_SHADER_TEX_CLAMP = 7, FS_BIT_CLAMP_S = 8, FS_BIT_CLAMP_T = 9, @@ -93,9 +93,8 @@ enum FShaderBit : uint8_t { FS_BIT_TEST_DISCARD_TO_ZERO = 48, FS_BIT_NO_DEPTH_CANNOT_DISCARD_STENCIL = 49, FS_BIT_COLOR_WRITEMASK = 50, - FS_BIT_3D_TEXTURE = 51, - FS_BIT_SHADER_SMOOTHED_DEPAL = 52, - FS_BIT_REPLACE_LOGIC_OP = 53, // 4 bits. GE_LOGIC_COPY means no-op/off. + FS_BIT_REPLACE_LOGIC_OP = 51, // 4 bits. GE_LOGIC_COPY means no-op/off. + FS_BIT_SHADER_DEPAL_MODE = 55, // 2 bits (ShaderDepalMode) }; static inline FShaderBit operator +(FShaderBit bit, int i) { diff --git a/GPU/Common/StencilCommon.cpp b/GPU/Common/StencilCommon.cpp index 44cc9304bb..81749ef678 100644 --- a/GPU/Common/StencilCommon.cpp +++ b/GPU/Common/StencilCommon.cpp @@ -237,7 +237,7 @@ bool FramebufferManagerCommon::PerformStencilUpload(u32 addr, int size, StencilU { stencilUploadVs, stencilUploadFs }, inputLayout, stencilWrite, blendOff, rasterNoCull, &stencilUBDesc, }; - stencilUploadPipeline_ = draw_->CreateGraphicsPipeline(stencilWriteDesc); + stencilUploadPipeline_ = draw_->CreateGraphicsPipeline(stencilWriteDesc, "stencil_upload"); _assert_(stencilUploadPipeline_); delete[] fsCode; diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index 87c866fa93..e4b463360d 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -639,18 +639,7 @@ bool TextureCacheCommon::GetBestFramebufferCandidate(const TextureDefinition &en return true; } - if (Reporting::ShouldLogNTimes("multifbcandidate", 5)) { - std::string cands; - for (size_t i = 0; i < candidates.size(); i++) { - cands += candidates[i].ToString() + "\n"; - } - - WARN_LOG(G3D, "GetFramebufferCandidates: Multiple (%d) candidate framebuffers. texaddr: %08x offset: %d (%dx%d stride %d, %s):\n%s", - (int)candidates.size(), - entry.addr, texAddrOffset, dimWidth(entry.dim), dimHeight(entry.dim), entry.bufw, GeTextureFormatToString(entry.format), - cands.c_str() - ); - } + bool logging = Reporting::ShouldLogNTimes("multifbcandidate", 5); // OK, multiple possible candidates. Will need to figure out which one is the most relevant. int bestRelevancy = -1; @@ -660,7 +649,7 @@ bool TextureCacheCommon::GetBestFramebufferCandidate(const TextureDefinition &en // We simply use the sequence counter as relevancy nowadays. for (size_t i = 0; i < candidates.size(); i++) { - const AttachCandidate &candidate = candidates[i]; + AttachCandidate &candidate = candidates[i]; int relevancy = candidate.channel == RASTER_COLOR ? candidate.fb->colorBindSeq : candidate.fb->depthBindSeq; // Add a small negative penalty if the texture is currently bound as a framebuffer, and offset is not zero. @@ -678,13 +667,36 @@ bool TextureCacheCommon::GetBestFramebufferCandidate(const TextureDefinition &en continue; } + if (logging) { + candidate.relevancy = relevancy; + } + if (relevancy > bestRelevancy) { bestRelevancy = relevancy; bestIndex = i; } } + if (logging) { + std::string cands; + for (size_t i = 0; i < candidates.size(); i++) { + cands += candidates[i].ToString(); + if (i != candidates.size() - 1) + cands += "\n"; + } + + WARN_LOG(G3D, "GetFramebufferCandidates: Multiple (%d) candidate framebuffers. texaddr: %08x offset: %d (%dx%d stride %d, %s):\n%s", + (int)candidates.size(), + entry.addr, texAddrOffset, dimWidth(entry.dim), dimHeight(entry.dim), entry.bufw, GeTextureFormatToString(entry.format), + cands.c_str() + ); + logging = true; + } + if (bestIndex != -1) { + if (logging) { + WARN_LOG(G3D, "Chose candidate %d:\n%s\n", (int)bestIndex, candidates[bestIndex].ToString().c_str()); + } *bestCandidate = candidates[bestIndex]; return true; } else { @@ -871,13 +883,22 @@ bool TextureCacheCommon::MatchFramebuffer( return false; } + if (!fb_stride) { + // Hard to make decisions. + return false; + } + switch (entry.format) { case GE_TFMT_DXT1: case GE_TFMT_DXT3: case GE_TFMT_DXT5: return false; + default: break; } + uint32_t fb_stride_in_bytes = fb_stride * BufferFormatBytesPerPixel(fb_format); + uint32_t tex_stride_in_bytes = entry.bufw * textureBitsPerPixel[entry.format] / 8; // Note, we're looking up bits here so need to divide by 8. + u32 addr = fb_address & 0x3FFFFFFF; u32 texaddr = entry.addr + texaddrOffset; @@ -897,19 +918,16 @@ bool TextureCacheCommon::MatchFramebuffer( } const bool noOffset = texaddr == addr; - const bool exactMatch = noOffset && entry.format < 4 && channel == RASTER_COLOR; + const bool exactMatch = noOffset && entry.format < 4 && channel == RASTER_COLOR && fb_stride_in_bytes == tex_stride_in_bytes; + + const u32 texWidth = 1 << ((entry.dim >> 0) & 0xf); + const u32 texHeight = 1 << ((entry.dim >> 8) & 0xf); - const u32 w = 1 << ((entry.dim >> 0) & 0xf); - 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; + const u32 minSubareaHeight = texHeight / 4; // If they match "exactly", it's non-CLUT and from the top left. if (exactMatch) { - // TODO: Better checks for compatible strides here. - if (fb_stride != entry.bufw) { - WARN_LOG_ONCE(diffStrides1, G3D, "Found matching framebuffer at %08x with different strides %d != %d", fb_address, entry.bufw, (int)fb_stride); - } // NOTE: This check is okay because the first texture formats are the same as the buffer formats. if (IsTextureFormatBufferCompatible(entry.format)) { if (TextureFormatMatchesBufferFormat(entry.format, fb_format) || (framebuffer->usageFlags & FB_USAGE_BLUE_TO_ALPHA)) { @@ -936,20 +954,18 @@ bool TextureCacheCommon::MatchFramebuffer( (fb_format == GE_FORMAT_8888 && entry.format == GE_TFMT_CLUT32) || (fb_format != GE_FORMAT_8888 && entry.format == GE_TFMT_CLUT16); - const int bitOffset = (texaddr - addr) * 8; - if (bitOffset != 0) { - const int pixelOffset = bitOffset / (int)std::max(1U, (u32)textureBitsPerPixel[entry.format]); - - if (pixelOffset > 0) { - matchInfo->yOffset = entry.bufw == 0 ? 0 : pixelOffset / (int)entry.bufw; - matchInfo->xOffset = entry.bufw == 0 ? 0 : pixelOffset % (int)entry.bufw; - } else if (pixelOffset < 0) { - // We don't support negative Y offsets, and negative X offsets are only for the Killzone workaround. - if (pixelOffset < -(int)entry.bufw || !PSP_CoreParameter().compat.flags().SplitFramebufferMargin) { - return false; - } - matchInfo->xOffset = entry.bufw == 0 ? 0 : -(-pixelOffset % (int)entry.bufw); + const int texBitsPerPixel = std::max(1U, (u32)textureBitsPerPixel[entry.format]); + const int byteOffset = texaddr - addr; + if (byteOffset > 0) { + matchInfo->yOffset = byteOffset / fb_stride_in_bytes; + matchInfo->xOffset = 8 * (byteOffset % fb_stride_in_bytes) / texBitsPerPixel; + } else if (byteOffset < 0) { + int texelOffset = 8 * byteOffset / texBitsPerPixel; + // We don't support negative Y offsets, and negative X offsets are only for the Killzone workaround. + if (texelOffset < -(int)entry.bufw || !PSP_CoreParameter().compat.flags().SplitFramebufferMargin) { + return false; } + matchInfo->xOffset = entry.bufw == 0 ? 0 : -(-texelOffset % (int)entry.bufw); } if (matchInfo->yOffset > 0 && matchInfo->yOffset + minSubareaHeight >= framebuffer->height) { @@ -957,19 +973,11 @@ bool TextureCacheCommon::MatchFramebuffer( return false; } - if (fb_stride != entry.bufw) { - if (noOffset) { - WARN_LOG_ONCE(diffStrides2, G3D, "Matching framebuffer(matching_clut = %s) different strides %d != %d", matchingClutFormat ? "yes" : "no", entry.bufw, fb_stride); - // Continue on with other checks. - // Not actually sure why we even try here. There's no way it'll go well if the strides are different. - } else { - // Assume any render-to-tex with different bufw + offset is a render from ram. - return false; - } - } - // Check if it's in bufferWidth (which might be higher than width and may indicate the framebuffer includes the data.) - if (matchInfo->xOffset >= framebuffer->bufferWidth && matchInfo->xOffset + w <= (u32)fb_stride) { + // Do the computation in bytes so that it's valid even in case of weird reinterpret scenarios. + const int xOffsetInBytes = matchInfo->xOffset * 8 / texBitsPerPixel; + const int texWidthInBytes = texWidth * 8 / texBitsPerPixel; + if (xOffsetInBytes >= framebuffer->BufferWidthInBytes() && xOffsetInBytes + texWidthInBytes <= (int)fb_stride_in_bytes) { // This happens in Brave Story, see #10045 - the texture is in the space between strides, with matching stride. return false; } @@ -981,6 +989,11 @@ bool TextureCacheCommon::MatchFramebuffer( return false; } + if (fb_stride_in_bytes != tex_stride_in_bytes) { + // Probably irrelevant. Although, as we shall see soon, there are exceptions. + 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 (matchingClutFormat) { @@ -1171,6 +1184,7 @@ void TextureCacheCommon::LoadClut(u32 clutAddr, u32 loadBytes) { // And is it inside the rendered area? Sometimes games pack data outside. bool matchRegion = ((offset / bpp) % framebuffer->fb_stride) < framebuffer->width; if (matchRange && matchRegion && offset < clutRenderOffset_) { + WARN_LOG_N_TIMES(clutfb, 5, G3D, "Detected LoadCLUT(%d bytes) from framebuffer %08x (%s), byte offset %d", loadBytes, fb_address, GeBufferFormatToString(framebuffer->fb_format), offset); framebuffer->last_frame_clut = gpuStats.numFlips; framebuffer->usageFlags |= FB_USAGE_CLUT; clutRenderAddress_ = framebuffer->fb_address; @@ -1184,15 +1198,18 @@ void TextureCacheCommon::LoadClut(u32 clutAddr, u32 loadBytes) { NotifyMemInfo(MemBlockFlags::ALLOC, clutAddr, loadBytes, "CLUT"); } - // It's possible for a game to (successfully) access outside valid memory. + // It's possible for a game to load CLUT outside valid memory without crashing, should result in zeroes. u32 bytes = Memory::ValidSize(clutAddr, loadBytes); - if (clutRenderAddress_ != 0xFFFFFFFF && !g_Config.bBlockTransferGPU) { + if (clutRenderAddress_ != 0xFFFFFFFF && PSP_CoreParameter().compat.flags().AllowDownloadCLUT) { framebufferManager_->DownloadFramebufferForClut(clutRenderAddress_, clutRenderOffset_ + bytes); Memory::MemcpyUnchecked(clutBufRaw_, clutAddr, bytes); if (bytes < loadBytes) { memset((u8 *)clutBufRaw_ + bytes, 0x00, loadBytes - bytes); } } else { + // Here we could check for clutRenderAddres_ != 0xFFFFFFFF and zero the CLUT or something, + // but choosing not to for now. Though the results of loading the CLUT from RAM here is + // almost certainly going to be bogus. #ifdef _M_SSE if (bytes == loadBytes) { const __m128i *source = (const __m128i *)Memory::GetPointerUnchecked(clutAddr); @@ -1866,9 +1883,8 @@ static bool CanDepalettize(GETextureFormat texFormat, GEBufferFormat bufferForma } else if (texFormat == GE_TFMT_5650 && bufferFormat == GE_FORMAT_DEPTH16) { // We can also "depal" 565 format, this is used to read depth buffers as 565 on occasion (#15491). return true; - } else { - return false; } + return false; } // If the palette is detected as a smooth ramp, we can interpolate for higher color precision. @@ -1891,6 +1907,9 @@ static bool CanUseSmoothDepal(const GPUgstate &gstate, GEBufferFormat framebuffe return gstate.getClutIndexMask() == 0x1F; } break; + default: + // No uses for the other formats yet, add if needed. + break; } } return false; @@ -1912,7 +1931,6 @@ void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer // TODO: Implement shader depal in the fragment shader generator for D3D11 at least. switch (draw_->GetShaderLanguageDesc().shaderLanguage) { - case ShaderLanguage::HLSL_D3D11: case ShaderLanguage::HLSL_D3D9: useShaderDepal = false; break; @@ -1945,7 +1963,7 @@ void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer // Since we started/ended render passes, might need these. gstate_c.Dirty(DIRTY_DEPAL); - gstate_c.SetUseShaderDepal(true, smoothedDepal); + gstate_c.SetUseShaderDepal(smoothedDepal ? ShaderDepalMode::SMOOTHED : ShaderDepalMode::NORMAL); gstate_c.depalFramebufferFormat = framebuffer->fb_format; const u32 bytesPerColor = clutFormat == GE_CMODE_32BIT_ABGR8888 ? sizeof(u32) : sizeof(u16); @@ -1961,7 +1979,7 @@ void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer depthUpperBits = (depth && framebuffer->fb_format == GE_FORMAT_8888) ? ((gstate.getTextureAddress(0) & 0x600000) >> 20) : 0; textureShader = textureShaderCache_->GetDepalettizeShader(clutMode, texFormat, depth ? GE_FORMAT_DEPTH16 : framebuffer->fb_format, smoothedDepal, depthUpperBits); - gstate_c.SetUseShaderDepal(false, false); + gstate_c.SetUseShaderDepal(ShaderDepalMode::OFF); } if (textureShader) { @@ -2034,7 +2052,7 @@ void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer framebufferManager_->BindFramebufferAsColorTexture(0, framebuffer, BINDFBCOLOR_MAY_COPY_WITH_UV | BINDFBCOLOR_APPLY_TEX_OFFSET); BoundFramebufferTexture(); - gstate_c.SetUseShaderDepal(false, false); + gstate_c.SetUseShaderDepal(ShaderDepalMode::OFF); gstate_c.SetTextureFullAlpha(gstate.getTextureFormat() == GE_TFMT_5650); } @@ -2247,9 +2265,10 @@ void TextureCacheCommon::ClearNextFrame() { } std::string AttachCandidate::ToString() const { - return StringFromFormat("[%s seq:%d C:%08x/%d(%s) Z:%08x/%d X:%d Y:%d reint: %s]", + return StringFromFormat("[%s seq:%d rel:%d C:%08x/%d(%s) Z:%08x/%d X:%d Y:%d reint: %s]", this->channel == RASTER_COLOR ? "COLOR" : "DEPTH", this->channel == RASTER_COLOR ? this->fb->colorBindSeq : this->fb->depthBindSeq, + this->relevancy, this->fb->fb_address, this->fb->fb_stride, GeBufferFormatToString(this->fb->fb_format), this->fb->z_address, this->fb->z_stride, this->match.xOffset, this->match.yOffset, this->match.reinterpret ? "true" : "false"); @@ -2261,12 +2280,6 @@ bool TextureCacheCommon::PrepareBuildTexture(BuildTexturePlan &plan, TexCacheEnt // For the estimate, we assume cluts always point to 8888 for simplicity. cacheSizeEstimate_ += EstimateTexMemoryUsage(entry); - if ((entry->bufw == 0 || (gstate.texbufwidth[0] & 0xf800) != 0) && entry->addr >= PSP_GetKernelMemoryEnd()) { - ERROR_LOG_REPORT(G3D, "Texture with unexpected bufw (full=%d)", gstate.texbufwidth[0] & 0xffff); - // Proceeding here can cause a crash. - return false; - } - plan.badMipSizes = false; // maxLevel here is the max level to upload. Not the count. plan.levelsToLoad = entry->maxLevel + 1; diff --git a/GPU/Common/TextureCacheCommon.h b/GPU/Common/TextureCacheCommon.h index 7cb79d44ce..82c79773a3 100644 --- a/GPU/Common/TextureCacheCommon.h +++ b/GPU/Common/TextureCacheCommon.h @@ -218,6 +218,7 @@ struct AttachCandidate { VirtualFramebuffer *fb; FramebufferMatchInfo match; RasterChannel channel; + int relevancy; std::string ToString() const; }; diff --git a/GPU/Common/TextureShaderCommon.cpp b/GPU/Common/TextureShaderCommon.cpp index 79417a482e..bebc72d516 100644 --- a/GPU/Common/TextureShaderCommon.cpp +++ b/GPU/Common/TextureShaderCommon.cpp @@ -213,6 +213,7 @@ Draw2DPipeline *TextureShaderCache::GetDepalettizeShader(uint32_t clutMode, GETe Draw2DPipeline *ts = draw2D_->Create2DPipeline([=](ShaderWriter &writer) -> Draw2DPipelineInfo { GenerateDepalFs(writer, config); return Draw2DPipelineInfo{ + "depal", config.bufferFormat == GE_FORMAT_DEPTH16 ? RASTER_DEPTH : RASTER_COLOR, RASTER_COLOR, samplers diff --git a/GPU/Common/VertexDecoderArm.cpp b/GPU/Common/VertexDecoderArm.cpp index c2f6ae46fd..e3d5b11f6b 100644 --- a/GPU/Common/VertexDecoderArm.cpp +++ b/GPU/Common/VertexDecoderArm.cpp @@ -204,7 +204,7 @@ JittedVertexDecoder VertexDecoderJitCache::Compile(const VertexDecoder &dec, int // Add code to convert matrices to 4x4. // Later we might want to do this when the matrices are loaded instead. - if (dec.weighttype && g_Config.bSoftwareSkinning) { + if (dec.skinInDecode) { // Copying from R3 to R4 MOVP2R(R3, gstate.boneMatrix); MOVP2R(R4, bones); diff --git a/GPU/Common/VertexDecoderArm64.cpp b/GPU/Common/VertexDecoderArm64.cpp index 32cc5bc291..5ff1d605f3 100644 --- a/GPU/Common/VertexDecoderArm64.cpp +++ b/GPU/Common/VertexDecoderArm64.cpp @@ -190,7 +190,7 @@ JittedVertexDecoder VertexDecoderJitCache::Compile(const VertexDecoder &dec, int // Add code to convert matrices to 4x4. // Later we might want to do this when the matrices are loaded instead. - if (dec.weighttype && g_Config.bSoftwareSkinning) { + if (dec.skinInDecode) { // Copying from R3 to R4 MOVP2R(X3, gstate.boneMatrix); MOVP2R(X4, bones); diff --git a/GPU/Common/VertexDecoderCommon.cpp b/GPU/Common/VertexDecoderCommon.cpp index 6ac9806c01..a9b4a1039a 100644 --- a/GPU/Common/VertexDecoderCommon.cpp +++ b/GPU/Common/VertexDecoderCommon.cpp @@ -1083,7 +1083,7 @@ void VertexDecoder::SetVertexType(u32 fmt, const VertexDecoderOptions &options, DEBUG_LOG(G3D, "VTYPE: THRU=%i TC=%i COL=%i POS=%i NRM=%i WT=%i NW=%i IDX=%i MC=%i", (int)throughmode, tc, col, pos, nrm, weighttype, nweights, idx, morphcount); } - bool skinInDecode = weighttype != 0 && g_Config.bSoftwareSkinning; + skinInDecode = weighttype != 0 && g_Config.bSoftwareSkinning; if (weighttype) { // && nweights? weightoff = size; diff --git a/GPU/Common/VertexDecoderCommon.h b/GPU/Common/VertexDecoderCommon.h index 3d6377a86c..983f76f9b2 100644 --- a/GPU/Common/VertexDecoderCommon.h +++ b/GPU/Common/VertexDecoderCommon.h @@ -28,6 +28,7 @@ #include "GPU/ge_constants.h" #include "GPU/Common/ShaderCommon.h" #include "GPU/GPUCommon.h" +#include "GPU/GPUState.h" #if PPSSPP_ARCH(ARM) #include "Common/ArmEmitter.h" @@ -299,6 +300,8 @@ public: bool hasNormal() const { return decFmt_.nrmfmt != 0; } bool hasUV() const { return decFmt_.uvfmt != 0; } bool isThrough() const { return (vtype_ & GE_VTYPE_THROUGH) != 0; } + bool skinningEnabled() const { return vertTypeIsSkinningEnabled(vtype_); } + int numBoneWeights() const { return vertTypeGetNumBoneWeights(vtype_); } void Goto(int index) { data_ = base_ + index * decFmt_.stride; } @@ -455,6 +458,7 @@ public: DecVtxFormat decFmt; bool throughmode; + bool skinInDecode; u8 size; u8 onesize_; diff --git a/GPU/Common/VertexDecoderX86.cpp b/GPU/Common/VertexDecoderX86.cpp index 611bf56c21..d684078989 100644 --- a/GPU/Common/VertexDecoderX86.cpp +++ b/GPU/Common/VertexDecoderX86.cpp @@ -219,7 +219,7 @@ JittedVertexDecoder VertexDecoderJitCache::Compile(const VertexDecoder &dec, int // Add code to convert matrices to 4x4. // Later we might want to do this when the matrices are loaded instead. - if (dec.weighttype && g_Config.bSoftwareSkinning) { + if (dec.skinInDecode) { MOV(PTRBITS, R(tempReg1), ImmPtr(&threeMasks)); MOVAPS(XMM4, MatR(tempReg1)); MOV(PTRBITS, R(tempReg1), ImmPtr(&aOne)); diff --git a/GPU/Common/VertexShaderGenerator.cpp b/GPU/Common/VertexShaderGenerator.cpp index 071f1f4f5b..ccda9af86b 100644 --- a/GPU/Common/VertexShaderGenerator.cpp +++ b/GPU/Common/VertexShaderGenerator.cpp @@ -276,6 +276,9 @@ bool GenerateVertexShader(const VShaderID &id, char *buffer, const ShaderLanguag // See the fragment shader generator WRITE(p, "layout (location = 3) out highp float v_fogdepth;\n"); } + + WRITE(p, "invariant gl_Position;\n"); + } else if (compat.shaderLanguage == HLSL_D3D11 || compat.shaderLanguage == HLSL_D3D9) { // Note: These two share some code after this hellishly large if/else. if (compat.shaderLanguage == HLSL_D3D11) { diff --git a/GPU/D3D11/D3D11Util.cpp b/GPU/D3D11/D3D11Util.cpp index d8a68c5f14..9fd4c64a48 100644 --- a/GPU/D3D11/D3D11Util.cpp +++ b/GPU/D3D11/D3D11Util.cpp @@ -26,13 +26,14 @@ std::vector CompileShaderToBytecodeD3D11(const char *code, size_t codeS std::string errors; if (errorMsgs) { errors = std::string((const char *)errorMsgs->GetBufferPointer(), errorMsgs->GetBufferSize()); + std::string numberedCode = LineNumberString(code); if (SUCCEEDED(result)) { WARN_LOG(G3D, "%s: %s", "warnings", errors.c_str()); } else { - ERROR_LOG(G3D, "%s: %s", "errors", errors.c_str()); + ERROR_LOG(G3D, "%s: %s\n\n%s", "errors", errors.c_str(), numberedCode.c_str()); } - OutputDebugStringA(LineNumberString(code).c_str()); OutputDebugStringA(errors.c_str()); + OutputDebugStringA(numberedCode.c_str()); errorMsgs->Release(); } if (compiledCode) { diff --git a/GPU/D3D11/GPU_D3D11.cpp b/GPU/D3D11/GPU_D3D11.cpp index 94bfa6afa9..3cfe0c4b37 100644 --- a/GPU/D3D11/GPU_D3D11.cpp +++ b/GPU/D3D11/GPU_D3D11.cpp @@ -209,7 +209,7 @@ void GPU_D3D11::BeginHostFrame() { CheckGPUFeatures(); framebufferManager_->Resized(); drawEngine_.Resized(); - textureCacheD3D11_->NotifyConfigChanged(); + textureCache_->NotifyConfigChanged(); shaderManagerD3D11_->DirtyLastShader(); resized_ = false; } diff --git a/GPU/D3D11/ShaderManagerD3D11.cpp b/GPU/D3D11/ShaderManagerD3D11.cpp index 34c8980ad0..a8537c8545 100644 --- a/GPU/D3D11/ShaderManagerD3D11.cpp +++ b/GPU/D3D11/ShaderManagerD3D11.cpp @@ -224,7 +224,7 @@ void ShaderManagerD3D11::GetShaders(int prim, u32 vertType, D3D11VertexShader ** // Fragment shader not in cache. Let's compile it. std::string genErrorString; uint64_t uniformMask; - GenerateFragmentShader(FSID, codeBuffer_, draw_->GetShaderLanguageDesc(), draw_->GetBugs(), &uniformMask, &genErrorString); + GenerateFragmentShader(FSID, codeBuffer_, draw_->GetShaderLanguageDesc(), draw_->GetBugs(), &uniformMask, nullptr, &genErrorString); fs = new D3D11FragmentShader(device_, featureLevel_, FSID, codeBuffer_, useHWTransform); fsCache_[FSID] = fs; } else { diff --git a/GPU/D3D11/TextureCacheD3D11.cpp b/GPU/D3D11/TextureCacheD3D11.cpp index 5cc42adee6..3a7ead0829 100644 --- a/GPU/D3D11/TextureCacheD3D11.cpp +++ b/GPU/D3D11/TextureCacheD3D11.cpp @@ -59,7 +59,15 @@ static const D3D11_INPUT_ELEMENT_DESC g_QuadVertexElements[] = { Draw::DataFormat FromD3D11Format(u32 fmt) { switch (fmt) { - case DXGI_FORMAT_B8G8R8A8_UNORM: default: return Draw::DataFormat::R8G8B8A8_UNORM; + case DXGI_FORMAT_B4G4R4A4_UNORM: + return Draw::DataFormat::A4R4G4B4_UNORM_PACK16; + case DXGI_FORMAT_B5G5R5A1_UNORM: + return Draw::DataFormat::A1R5G5B5_UNORM_PACK16; + case DXGI_FORMAT_B5G6R5_UNORM: + return Draw::DataFormat::R5G6B5_UNORM_PACK16; + case DXGI_FORMAT_B8G8R8A8_UNORM: + default: + return Draw::DataFormat::R8G8B8A8_UNORM; } } @@ -172,8 +180,8 @@ void TextureCacheD3D11::ReleaseTexture(TexCacheEntry *entry, bool delete_them) { void TextureCacheD3D11::ForgetLastTexture() { InvalidateLastTexture(); - ID3D11ShaderResourceView *nullTex[2]{}; - context_->PSSetShaderResources(0, 2, nullTex); + ID3D11ShaderResourceView *nullTex[4]{}; + context_->PSSetShaderResources(0, 4, nullTex); } void TextureCacheD3D11::InvalidateLastTexture() { @@ -250,6 +258,7 @@ void TextureCacheD3D11::BindTexture(TexCacheEntry *entry) { SamplerCacheKey samplerKey = GetSamplingParams(maxLevel, entry); ID3D11SamplerState *state = samplerCache_.GetOrCreateSampler(device_, samplerKey); context_->PSSetSamplers(0, 1, &state); + gstate_c.SetUseShaderDepal(ShaderDepalMode::OFF); } void TextureCacheD3D11::ApplySamplingParams(const SamplerCacheKey &key) { @@ -292,6 +301,10 @@ void TextureCacheD3D11::BuildTexture(TexCacheEntry *const entry) { int tw; int th; plan.GetMipSize(0, &tw, &th); + if (tw > 16384) + tw = 16384; + if (th > 16384) + th = 16384; if (plan.depth == 1) { // We don't yet have mip generation, so clamp the number of levels to the ones we can load directly. diff --git a/GPU/Debugger/Breakpoints.cpp b/GPU/Debugger/Breakpoints.cpp index 162ec6743a..97fbca57ee 100644 --- a/GPU/Debugger/Breakpoints.cpp +++ b/GPU/Debugger/Breakpoints.cpp @@ -18,24 +18,37 @@ #include #include #include +#include #include #include "Common/CommonFuncs.h" +#include "Common/Math/expression_parser.h" +#include "GPU/Common/GPUDebugInterface.h" #include "GPU/Debugger/Breakpoints.h" #include "GPU/GPUState.h" namespace GPUBreakpoints { +static void NothingToDo(bool) { +} + +struct BreakpointInfo { + bool isConditional = false; + PostfixExpression expression; + std::string expressionString; +}; + static std::mutex breaksLock; static bool breakCmds[256]; -static std::set breakPCs; +static BreakpointInfo breakCmdsInfo[256]; +static std::unordered_map breakPCs; static std::set breakTextures; static std::set breakRenderTargets; // Small optimization to avoid a lock/lookup for the common case. static size_t breakPCsCount = 0; static size_t breakTexturesCount = 0; static size_t breakRenderTargetsCount = 0; -static std::function notifyBreakpoints; +static std::function notifyBreakpoints = &NothingToDo; // If these are set, the above are also, but they should be temporary. static bool breakCmdsTemp[256]; @@ -158,8 +171,53 @@ bool IsRenderTargetCmdBreakpoint(u32 op) { return false; } +static bool HitBreakpointCond(BreakpointInfo &bp, u32 op) { + u8 cmd = op >> 24; + + // Temporarily set the value while running the breakpoint. + // It makes more intuitive sense for the referenced data to already be set. + // Note this won't perform actions, like matrix uploads. + u32 diff = gstate.cmdmem[cmd] ^ op; + gstate.cmdmem[cmd] ^= diff; + + u32 result = 1; + if (!GPUDebugExecExpression(gpuDebug, bp.expression, result)) + result = 0; + + gstate.cmdmem[cmd] ^= diff; + return result != 0; +} + +static bool HitAddressBreakpoint(u32 pc, u32 op) { + if (breakPCsCount == 0) + return false; + + std::lock_guard guard(breaksLock); + auto entry = breakPCs.find(pc); + if (entry == breakPCs.end()) + return false; + + if (entry->second.isConditional) { + return HitBreakpointCond(entry->second, op); + } + return true; +} + +static bool HitOpBreakpoint(u32 op) { + u8 cmd = op >> 24; + if (!IsCmdBreakpoint(cmd)) + return false; + + if (breakCmdsInfo[cmd].isConditional) { + std::lock_guard guard(breaksLock); + return HitBreakpointCond(breakCmdsInfo[cmd], op); + } + + return true; +} + bool IsBreakpoint(u32 pc, u32 op) { - if (IsAddressBreakpoint(pc) || IsOpBreakpoint(op)) { + if (HitAddressBreakpoint(pc, op) || HitOpBreakpoint(op)) { return true; } @@ -275,13 +333,13 @@ void AddAddressBreakpoint(u32 addr, bool temp) { if (temp) { if (breakPCs.find(addr) == breakPCs.end()) { breakPCsTemp.insert(addr); - breakPCs.insert(addr); + breakPCs[addr].isConditional = false; } // Already normal breakpoint, let's not make it temporary. } else { // Remove the temporary marking. breakPCsTemp.erase(addr); - breakPCs.insert(addr); + breakPCs.insert(std::make_pair(addr, BreakpointInfo{})); } breakPCsCount = breakPCs.size(); @@ -293,12 +351,16 @@ void AddCmdBreakpoint(u8 cmd, bool temp) { if (!breakCmds[cmd]) { breakCmdsTemp[cmd] = true; breakCmds[cmd] = true; + breakCmdsInfo[cmd].isConditional = false; } // Ignore adding a temp breakpoint when a normal one exists. } else { // This is no longer temporary. breakCmdsTemp[cmd] = false; - breakCmds[cmd] = true; + if (!breakCmds[cmd]) { + breakCmds[cmd] = true; + breakCmdsInfo[cmd].isConditional = false; + } } notifyBreakpoints(true); } @@ -398,6 +460,63 @@ void RemoveTextureChangeTempBreakpoint() { notifyBreakpoints(HasAnyBreakpoints()); } +static bool SetupCond(BreakpointInfo &bp, const std::string &expression, std::string *error) { + bool success = true; + if (expression.length() != 0) { + if (GPUDebugInitExpression(gpuDebug, expression.c_str(), bp.expression)) { + bp.isConditional = true; + bp.expressionString = expression; + } else { + // Don't change if it failed. + if (error) + *error = getExpressionError(); + success = false; + } + } else { + bp.isConditional = false; + } + return success; +} + +bool SetAddressBreakpointCond(u32 addr, const std::string &expression, std::string *error) { + // Must have one in the first place, make sure it's not temporary. + AddAddressBreakpoint(addr); + + std::lock_guard guard(breaksLock); + auto &bp = breakPCs[addr]; + return SetupCond(breakPCs[addr], expression, error); +} + +bool GetAddressBreakpointCond(u32 addr, std::string *expression) { + std::lock_guard guard(breaksLock); + auto entry = breakPCs.find(addr); + if (entry != breakPCs.end() && entry->second.isConditional) { + if (expression) + *expression = entry->second.expressionString; + return true; + } + return false; +} + +bool SetCmdBreakpointCond(u8 cmd, const std::string &expression, std::string *error) { + // Must have one in the first place, make sure it's not temporary. + AddCmdBreakpoint(cmd); + + std::lock_guard guard(breaksLock); + return SetupCond(breakCmdsInfo[cmd], expression, error); +} + +bool GetCmdBreakpointCond(u8 cmd, std::string *expression) { + if (breakCmds[cmd] && breakCmdsInfo[cmd].isConditional) { + if (expression) { + std::lock_guard guard(breaksLock); + *expression = breakCmdsInfo[cmd].expressionString; + } + return true; + } + return false; +} + void UpdateLastTexture(u32 addr) { lastTexture = addr; } diff --git a/GPU/Debugger/Breakpoints.h b/GPU/Debugger/Breakpoints.h index fd55476643..0910a68e92 100644 --- a/GPU/Debugger/Breakpoints.h +++ b/GPU/Debugger/Breakpoints.h @@ -47,6 +47,11 @@ namespace GPUBreakpoints { void RemoveTextureChangeTempBreakpoint(); void RemoveRenderTargetBreakpoint(u32 addr); + bool SetAddressBreakpointCond(u32 addr, const std::string &expression, std::string *error); + bool GetAddressBreakpointCond(u32 addr, std::string *expression); + bool SetCmdBreakpointCond(u8 cmd, const std::string &expression, std::string *error); + bool GetCmdBreakpointCond(u8 cmd, std::string *expression); + void UpdateLastTexture(u32 addr); void ClearAllBreakpoints(); diff --git a/GPU/Debugger/Debugger.cpp b/GPU/Debugger/Debugger.cpp index 439c763e8e..fb88fdca2f 100644 --- a/GPU/Debugger/Debugger.cpp +++ b/GPU/Debugger/Debugger.cpp @@ -73,6 +73,7 @@ void SetBreakNext(BreakNext next) { GPUBreakpoints::AddCmdBreakpoint(GE_CMD_PRIM, true); GPUBreakpoints::AddCmdBreakpoint(GE_CMD_BEZIER, true); GPUBreakpoints::AddCmdBreakpoint(GE_CMD_SPLINE, true); + GPUBreakpoints::AddCmdBreakpoint(GE_CMD_VAP, true); } else if (next == BreakNext::CURVE) { GPUBreakpoints::AddCmdBreakpoint(GE_CMD_BEZIER, true); GPUBreakpoints::AddCmdBreakpoint(GE_CMD_SPLINE, true); @@ -111,7 +112,7 @@ bool NotifyCommand(u32 pc) { } bool process = true; - if (cmd == GE_CMD_PRIM || cmd == GE_CMD_BEZIER || cmd == GE_CMD_SPLINE) { + if (cmd == GE_CMD_PRIM || cmd == GE_CMD_BEZIER || cmd == GE_CMD_SPLINE || cmd == GE_CMD_VAP) { primsThisFrame++; if (!restrictPrimRanges.empty()) { diff --git a/GPU/Debugger/GECommandTable.cpp b/GPU/Debugger/GECommandTable.cpp new file mode 100644 index 0000000000..e0e9573211 --- /dev/null +++ b/GPU/Debugger/GECommandTable.cpp @@ -0,0 +1,413 @@ +// Copyright (c) 2022- 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/Common.h" +#include "Common/Log.h" +#include "GPU/Debugger/GECommandTable.h" +#include "GPU/ge_constants.h" + +struct GECmdAlias { + GECommand reg; + const char *aliases[3]; +}; + +static constexpr GECmdInfo geCmdInfo[] = { + { GE_CMD_NOP, "nop", GECmdFormat::NONE }, + { GE_CMD_VADDR, "setvaddr", GECmdFormat::RELATIVE_ADDR }, + { GE_CMD_IADDR, "setiaddr", GECmdFormat::RELATIVE_ADDR }, + { GE_CMD_UNKNOWN_03, "unknown03", GECmdFormat::NONE }, + { GE_CMD_PRIM, "prim", GECmdFormat::PRIM }, + { GE_CMD_BEZIER, "bezier", GECmdFormat::BEZIER }, + { GE_CMD_SPLINE, "spline", GECmdFormat::SPLINE }, + { GE_CMD_BOUNDINGBOX, "btest", GECmdFormat::PRIM }, + { GE_CMD_JUMP, "jump", GECmdFormat::JUMP }, + { GE_CMD_BJUMP, "bjump", GECmdFormat::JUMP }, + { GE_CMD_CALL, "call", GECmdFormat::JUMP }, + { GE_CMD_RET, "ret", GECmdFormat::NONE }, + { GE_CMD_END, "end", GECmdFormat::DATA16 }, + { GE_CMD_UNKNOWN_0D, "unknown0d", GECmdFormat::NONE }, + { GE_CMD_SIGNAL, "signal", GECmdFormat::SIGNAL }, + { GE_CMD_FINISH, "finish", GECmdFormat::NONE }, + { GE_CMD_BASE, "base", GECmdFormat::HIGH_ADDR_ONLY }, + { GE_CMD_UNKNOWN_11, "unknown11", GECmdFormat::NONE }, + { GE_CMD_VERTEXTYPE, "vtype", GECmdFormat::VERTEX_TYPE }, + { GE_CMD_OFFSETADDR, "setoffset", GECmdFormat::OFFSET_ADDR }, + { GE_CMD_ORIGIN, "origin", GECmdFormat::NONE }, + { GE_CMD_REGION1, "regionrate", GECmdFormat::X10_Y10 }, + { GE_CMD_REGION2, "regionstop", GECmdFormat::X10_Y10 }, + { GE_CMD_LIGHTINGENABLE, "lighting_on", GECmdFormat::FLAG }, + { GE_CMD_LIGHTENABLE0, "light0_on", GECmdFormat::FLAG }, + { GE_CMD_LIGHTENABLE1, "light1_on", GECmdFormat::FLAG }, + { GE_CMD_LIGHTENABLE2, "light2_on", GECmdFormat::FLAG }, + { GE_CMD_LIGHTENABLE3, "light3_on", GECmdFormat::FLAG }, + { GE_CMD_DEPTHCLAMPENABLE, "zclamp_on", GECmdFormat::FLAG }, + { GE_CMD_CULLFACEENABLE, "cull_on", GECmdFormat::FLAG }, + { GE_CMD_TEXTUREMAPENABLE, "tex_on", GECmdFormat::FLAG }, + { GE_CMD_FOGENABLE, "fog_on", GECmdFormat::FLAG }, + { GE_CMD_DITHERENABLE, "dither_on", GECmdFormat::FLAG }, + { GE_CMD_ALPHABLENDENABLE, "ablend_on", GECmdFormat::FLAG }, + { GE_CMD_ALPHABLENDENABLE, "atest_on", GECmdFormat::FLAG }, + { GE_CMD_ZTESTENABLE, "ztest_on", GECmdFormat::FLAG }, + { GE_CMD_STENCILTESTENABLE, "stest_on", GECmdFormat::FLAG }, + { GE_CMD_ANTIALIASENABLE, "antialias_on", GECmdFormat::FLAG }, + { GE_CMD_PATCHCULLENABLE, "patchcull_on", GECmdFormat::FLAG }, + { GE_CMD_COLORTESTENABLE, "ctest_on", GECmdFormat::FLAG }, + { GE_CMD_LOGICOPENABLE, "logicop_on", GECmdFormat::FLAG }, + { GE_CMD_UNKNOWN_29, "unknown29", GECmdFormat::NONE }, + { GE_CMD_BONEMATRIXNUMBER, "bonemtxnum", GECmdFormat::BONE_NUM }, + { GE_CMD_BONEMATRIXDATA, "bonemtxdata", GECmdFormat::FLOAT }, + { GE_CMD_MORPHWEIGHT0, "morph0", GECmdFormat::FLOAT }, + { GE_CMD_MORPHWEIGHT1, "morph1", GECmdFormat::FLOAT }, + { GE_CMD_MORPHWEIGHT2, "morph2", GECmdFormat::FLOAT }, + { GE_CMD_MORPHWEIGHT3, "morph3", GECmdFormat::FLOAT }, + { GE_CMD_MORPHWEIGHT4, "morph4", GECmdFormat::FLOAT }, + { GE_CMD_MORPHWEIGHT5, "morph5", GECmdFormat::FLOAT }, + { GE_CMD_MORPHWEIGHT6, "morph6", GECmdFormat::FLOAT }, + { GE_CMD_MORPHWEIGHT7, "morph7", GECmdFormat::FLOAT }, + { GE_CMD_UNKNOWN_34, "unknown34", GECmdFormat::NONE }, + { GE_CMD_UNKNOWN_35, "unknown35", GECmdFormat::NONE }, + { GE_CMD_PATCHDIVISION, "patchdivision", GECmdFormat::PATCH_DIVISION }, + { GE_CMD_PATCHPRIMITIVE, "patchprim", GECmdFormat::PATCH_PRIM }, + { GE_CMD_PATCHFACING, "patchreversenormals", GECmdFormat::FLAG }, + { GE_CMD_UNKNOWN_39, "unknown39", GECmdFormat::NONE }, + { GE_CMD_WORLDMATRIXNUMBER, "worldmtxnum", GECmdFormat::MATRIX_NUM }, + { GE_CMD_WORLDMATRIXDATA, "worldmtxdata", GECmdFormat::FLOAT }, + { GE_CMD_VIEWMATRIXNUMBER, "viewmtxnum", GECmdFormat::MATRIX_NUM }, + { GE_CMD_VIEWMATRIXDATA, "viewmtxdata", GECmdFormat::FLOAT }, + { GE_CMD_PROJMATRIXNUMBER, "projmtxnum", GECmdFormat::MATRIX_NUM }, + { GE_CMD_PROJMATRIXDATA, "projmtxdata", GECmdFormat::FLOAT }, + { GE_CMD_TGENMATRIXNUMBER, "texgenmtxnum", GECmdFormat::MATRIX_NUM }, + { GE_CMD_TGENMATRIXDATA, "texgenmtxdata", GECmdFormat::FLOAT }, + { GE_CMD_VIEWPORTXSCALE, "vpxscale", GECmdFormat::FLOAT }, + { GE_CMD_VIEWPORTYSCALE, "vpyscale", GECmdFormat::FLOAT }, + { GE_CMD_VIEWPORTZSCALE, "vpzscale", GECmdFormat::FLOAT }, + { GE_CMD_VIEWPORTXCENTER, "vpxcenter", GECmdFormat::FLOAT }, + { GE_CMD_VIEWPORTYCENTER, "vpycenter", GECmdFormat::FLOAT }, + { GE_CMD_VIEWPORTZCENTER, "vpzcenter", GECmdFormat::FLOAT }, + { GE_CMD_TEXSCALEU, "texscaleu", GECmdFormat::FLOAT }, + { GE_CMD_TEXSCALEV, "texscalev", GECmdFormat::FLOAT }, + { GE_CMD_TEXOFFSETU, "texoffsetu", GECmdFormat::FLOAT }, + { GE_CMD_TEXOFFSETV, "texoffsetv", GECmdFormat::FLOAT }, + { GE_CMD_OFFSETX, "offsetx", GECmdFormat::SUBPIXEL_COORD }, + { GE_CMD_OFFSETY, "offsety", GECmdFormat::SUBPIXEL_COORD }, + { GE_CMD_UNKNOWN_4E, "unknown4e", GECmdFormat::NONE }, + { GE_CMD_UNKNOWN_4F, "unknown4f", GECmdFormat::NONE }, + // Really shade mode, but using gouraud as the default so it can be 1/0. + { GE_CMD_SHADEMODE, "gouraud", GECmdFormat::FLAG }, + { GE_CMD_REVERSENORMAL, "reversenormals", GECmdFormat::FLAG }, + { GE_CMD_UNKNOWN_52, "unknown52", GECmdFormat::NONE }, + { GE_CMD_MATERIALUPDATE, "materialupdate", GECmdFormat::MATERIAL_UPDATE }, + { GE_CMD_MATERIALEMISSIVE, "materialemissive", GECmdFormat::RGB }, + { GE_CMD_MATERIALAMBIENT, "materialambient", GECmdFormat::RGB }, + { GE_CMD_MATERIALDIFFUSE, "materialdiffuse", GECmdFormat::RGB }, + { GE_CMD_MATERIALSPECULAR, "materialspecular", GECmdFormat::RGB }, + { GE_CMD_MATERIALALPHA, "materialambienta", GECmdFormat::DATA8 }, + { GE_CMD_UNKNOWN_59, "unknown59", GECmdFormat::NONE }, + { GE_CMD_UNKNOWN_5A, "unknown5a", GECmdFormat::NONE }, + { GE_CMD_MATERIALSPECULARCOEF, "specularcoef", GECmdFormat::FLOAT }, + { GE_CMD_AMBIENTCOLOR, "ambient", GECmdFormat::RGB }, + { GE_CMD_AMBIENTALPHA, "ambienta", GECmdFormat::DATA8 }, + { GE_CMD_LIGHTMODE, "lightseparate", GECmdFormat::FLAG }, + { GE_CMD_LIGHTTYPE0, "ltype0", GECmdFormat::LIGHT_TYPE }, + { GE_CMD_LIGHTTYPE1, "ltype1", GECmdFormat::LIGHT_TYPE }, + { GE_CMD_LIGHTTYPE2, "ltype2", GECmdFormat::LIGHT_TYPE }, + { GE_CMD_LIGHTTYPE3, "ltype3", GECmdFormat::LIGHT_TYPE }, + { GE_CMD_LX0, "light0posx", GECmdFormat::FLOAT }, + { GE_CMD_LY0, "light0posy", GECmdFormat::FLOAT }, + { GE_CMD_LZ0, "light0posz", GECmdFormat::FLOAT }, + { GE_CMD_LX1, "light1posx", GECmdFormat::FLOAT }, + { GE_CMD_LY1, "light1posy", GECmdFormat::FLOAT }, + { GE_CMD_LZ1, "light1posz", GECmdFormat::FLOAT }, + { GE_CMD_LX2, "light2posx", GECmdFormat::FLOAT }, + { GE_CMD_LY2, "light2posy", GECmdFormat::FLOAT }, + { GE_CMD_LZ2, "light2posz", GECmdFormat::FLOAT }, + { GE_CMD_LX3, "light3posx", GECmdFormat::FLOAT }, + { GE_CMD_LY3, "light3posy", GECmdFormat::FLOAT }, + { GE_CMD_LZ3, "light3posz", GECmdFormat::FLOAT }, + { GE_CMD_LDX0, "light0dirx", GECmdFormat::FLOAT }, + { GE_CMD_LDY0, "light0diry", GECmdFormat::FLOAT }, + { GE_CMD_LDZ0, "light0dirz", GECmdFormat::FLOAT }, + { GE_CMD_LDX1, "light1dirx", GECmdFormat::FLOAT }, + { GE_CMD_LDY1, "light1diry", GECmdFormat::FLOAT }, + { GE_CMD_LDZ1, "light1dirz", GECmdFormat::FLOAT }, + { GE_CMD_LDX2, "light2dirx", GECmdFormat::FLOAT }, + { GE_CMD_LDY2, "light2diry", GECmdFormat::FLOAT }, + { GE_CMD_LDZ2, "light2dirz", GECmdFormat::FLOAT }, + { GE_CMD_LDX3, "light3dirx", GECmdFormat::FLOAT }, + { GE_CMD_LDY3, "light3diry", GECmdFormat::FLOAT }, + { GE_CMD_LDZ3, "light3dirz", GECmdFormat::FLOAT }, + { GE_CMD_LKA0, "light0attpow0", GECmdFormat::FLOAT }, + { GE_CMD_LKB0, "light0attpow1", GECmdFormat::FLOAT }, + { GE_CMD_LKC0, "light0attpow2", GECmdFormat::FLOAT }, + { GE_CMD_LKA1, "light1attpow0", GECmdFormat::FLOAT }, + { GE_CMD_LKB1, "light1attpow1", GECmdFormat::FLOAT }, + { GE_CMD_LKC1, "light1attpow2", GECmdFormat::FLOAT }, + { GE_CMD_LKA2, "light2attpow0", GECmdFormat::FLOAT }, + { GE_CMD_LKB2, "light2attpow1", GECmdFormat::FLOAT }, + { GE_CMD_LKC2, "light2attpow2", GECmdFormat::FLOAT }, + { GE_CMD_LKA3, "light3attpow0", GECmdFormat::FLOAT }, + { GE_CMD_LKB3, "light3attpow1", GECmdFormat::FLOAT }, + { GE_CMD_LKC3, "light3attpow2", GECmdFormat::FLOAT }, + { GE_CMD_LKS0, "light0spotexp", GECmdFormat::FLOAT }, + { GE_CMD_LKS1, "light1spotexp", GECmdFormat::FLOAT }, + { GE_CMD_LKS2, "light2spotexp", GECmdFormat::FLOAT }, + { GE_CMD_LKS3, "light3spotexp", GECmdFormat::FLOAT }, + { GE_CMD_LKO0, "light0spotcutoff", GECmdFormat::FLOAT }, + { GE_CMD_LKO1, "light1spotcutoff", GECmdFormat::FLOAT }, + { GE_CMD_LKO2, "light2spotcutoff", GECmdFormat::FLOAT }, + { GE_CMD_LKO3, "light3spotcutoff", GECmdFormat::FLOAT }, + { GE_CMD_LAC0, "light0ambient", GECmdFormat::RGB }, + { GE_CMD_LDC0, "light0diffuse", GECmdFormat::RGB }, + { GE_CMD_LSC0, "light0specular", GECmdFormat::RGB }, + { GE_CMD_LAC1, "light1ambient", GECmdFormat::RGB }, + { GE_CMD_LDC1, "light1diffuse", GECmdFormat::RGB }, + { GE_CMD_LSC1, "light1specular", GECmdFormat::RGB }, + { GE_CMD_LAC2, "light2ambient", GECmdFormat::RGB }, + { GE_CMD_LDC2, "light2diffuse", GECmdFormat::RGB }, + { GE_CMD_LSC2, "light2specular", GECmdFormat::RGB }, + { GE_CMD_LAC3, "light3ambient", GECmdFormat::RGB }, + { GE_CMD_LDC3, "light3diffuse", GECmdFormat::RGB }, + { GE_CMD_LSC3, "light3specular", GECmdFormat::RGB }, + { GE_CMD_CULL, "cullccw", GECmdFormat::FLAG }, + { GE_CMD_FRAMEBUFPTR, "fbptr", GECmdFormat::LOW_ADDR_ONLY }, + { GE_CMD_FRAMEBUFWIDTH, "fbstride", GECmdFormat::STRIDE }, + { GE_CMD_ZBUFPTR, "zbptr", GECmdFormat::LOW_ADDR_ONLY }, + { GE_CMD_ZBUFWIDTH, "zbstride", GECmdFormat::STRIDE }, + { GE_CMD_TEXADDR0, "texaddr0low", GECmdFormat::LOW_ADDR }, + { GE_CMD_TEXADDR1, "texaddr1low", GECmdFormat::LOW_ADDR }, + { GE_CMD_TEXADDR2, "texaddr2low", GECmdFormat::LOW_ADDR }, + { GE_CMD_TEXADDR3, "texaddr3low", GECmdFormat::LOW_ADDR }, + { GE_CMD_TEXADDR4, "texaddr4low", GECmdFormat::LOW_ADDR }, + { GE_CMD_TEXADDR5, "texaddr5low", GECmdFormat::LOW_ADDR }, + { GE_CMD_TEXADDR6, "texaddr6low", GECmdFormat::LOW_ADDR }, + { GE_CMD_TEXADDR7, "texaddr7low", GECmdFormat::LOW_ADDR }, + { GE_CMD_TEXBUFWIDTH0, "texbufw0", GECmdFormat::STRIDE_HIGH_ADDR }, + { GE_CMD_TEXBUFWIDTH1, "texbufw1", GECmdFormat::STRIDE_HIGH_ADDR }, + { GE_CMD_TEXBUFWIDTH2, "texbufw2", GECmdFormat::STRIDE_HIGH_ADDR }, + { GE_CMD_TEXBUFWIDTH3, "texbufw3", GECmdFormat::STRIDE_HIGH_ADDR }, + { GE_CMD_TEXBUFWIDTH4, "texbufw4", GECmdFormat::STRIDE_HIGH_ADDR }, + { GE_CMD_TEXBUFWIDTH5, "texbufw5", GECmdFormat::STRIDE_HIGH_ADDR }, + { GE_CMD_TEXBUFWIDTH6, "texbufw6", GECmdFormat::STRIDE_HIGH_ADDR }, + { GE_CMD_TEXBUFWIDTH7, "texbufw7", GECmdFormat::STRIDE_HIGH_ADDR }, + { GE_CMD_CLUTADDR, "clutaddrlow", GECmdFormat::LOW_ADDR }, + { GE_CMD_CLUTADDRUPPER, "clutaddrhigh", GECmdFormat::HIGH_ADDR }, + { GE_CMD_TRANSFERSRC, "transfersrclow", GECmdFormat::LOW_ADDR }, + { GE_CMD_TRANSFERSRCW, "transfersrcstride", GECmdFormat::STRIDE_HIGH_ADDR }, + { GE_CMD_TRANSFERDST, "transferdstlow", GECmdFormat::LOW_ADDR }, + { GE_CMD_TRANSFERDSTW, "transferdststride", GECmdFormat::STRIDE_HIGH_ADDR }, + { GE_CMD_UNKNOWN_B6, "unknownb6", GECmdFormat::NONE }, + { GE_CMD_UNKNOWN_B7, "unknownb7", GECmdFormat::NONE }, + { GE_CMD_TEXSIZE0, "texsize0", GECmdFormat::TEX_SIZE }, + { GE_CMD_TEXSIZE1, "texsize1", GECmdFormat::TEX_SIZE }, + { GE_CMD_TEXSIZE2, "texsize2", GECmdFormat::TEX_SIZE }, + { GE_CMD_TEXSIZE3, "texsize3", GECmdFormat::TEX_SIZE }, + { GE_CMD_TEXSIZE4, "texsize4", GECmdFormat::TEX_SIZE }, + { GE_CMD_TEXSIZE5, "texsize5", GECmdFormat::TEX_SIZE }, + { GE_CMD_TEXSIZE6, "texsize6", GECmdFormat::TEX_SIZE }, + { GE_CMD_TEXSIZE7, "texsize7", GECmdFormat::TEX_SIZE }, + { GE_CMD_TEXMAPMODE, "texmapmode", GECmdFormat::TEX_MAP_MODE }, + { GE_CMD_TEXSHADELS, "texlightsrc", GECmdFormat::TEX_LIGHT_SRC }, + { GE_CMD_TEXMODE, "texmode", GECmdFormat::TEX_MODE }, + { GE_CMD_TEXFORMAT, "texformat", GECmdFormat::TEX_FORMAT }, + { GE_CMD_LOADCLUT, "loadclut", GECmdFormat::CLUT_BLOCKS }, + { GE_CMD_CLUTFORMAT, "clutformat", GECmdFormat::CLUT_FORMAT }, + { GE_CMD_TEXFILTER, "texfilter", GECmdFormat::TEX_FILTER }, + { GE_CMD_TEXWRAP, "texclamp", GECmdFormat::TEX_CLAMP }, + { GE_CMD_TEXLEVEL, "texlevelmode", GECmdFormat::TEX_LEVEL_MODE }, + { GE_CMD_TEXFUNC, "texfunc", GECmdFormat::TEX_FUNC }, + { GE_CMD_TEXENVCOLOR, "texenv", GECmdFormat::RGB }, + { GE_CMD_TEXFLUSH, "texflush", GECmdFormat::NONE }, + { GE_CMD_TEXSYNC, "texsync", GECmdFormat::NONE }, + { GE_CMD_FOG1, "fogend", GECmdFormat::FLOAT }, + { GE_CMD_FOG2, "fogslope", GECmdFormat::FLOAT }, + { GE_CMD_FOGCOLOR, "fogcolor", GECmdFormat::RGB }, + { GE_CMD_TEXLODSLOPE, "texlodslope", GECmdFormat::FLOAT }, + { GE_CMD_UNKNOWN_D1, "unknownd1", GECmdFormat::NONE }, + { GE_CMD_FRAMEBUFPIXFORMAT, "fbformat", GECmdFormat::TEX_FORMAT }, + { GE_CMD_CLEARMODE, "clearmode", GECmdFormat::CLEAR_MODE }, + { GE_CMD_SCISSOR1, "scissor1", GECmdFormat::X10_Y10 }, + { GE_CMD_SCISSOR2, "scissor2", GECmdFormat::X10_Y10 }, + { GE_CMD_MINZ, "minz", GECmdFormat::DATA16 }, + { GE_CMD_MAXZ, "maxz", GECmdFormat::DATA16 }, + { GE_CMD_COLORTEST, "ctestfunc", GECmdFormat::COLOR_TEST_FUNC }, + { GE_CMD_COLORREF, "ctestref", GECmdFormat::RGB }, + { GE_CMD_COLORTESTMASK, "ctestmask", GECmdFormat::RGB }, + { GE_CMD_ALPHATEST, "atest", GECmdFormat::ALPHA_TEST }, + { GE_CMD_STENCILTEST, "stest", GECmdFormat::ALPHA_TEST }, + { GE_CMD_STENCILOP, "stencilop", GECmdFormat::STENCIL_OP }, + { GE_CMD_ZTEST, "ztest", GECmdFormat::DEPTH_TEST_FUNC }, + { GE_CMD_BLENDMODE, "blendmode", GECmdFormat::BLEND_MODE }, + { GE_CMD_BLENDFIXEDA, "blendfixa", GECmdFormat::RGB }, + { GE_CMD_BLENDFIXEDB, "blendfixb", GECmdFormat::RGB }, + { GE_CMD_DITH0, "dither0", GECmdFormat::DITHER_ROW }, + { GE_CMD_DITH1, "dither1", GECmdFormat::DITHER_ROW }, + { GE_CMD_DITH2, "dither2", GECmdFormat::DITHER_ROW }, + { GE_CMD_DITH3, "dither3", GECmdFormat::DITHER_ROW }, + { GE_CMD_LOGICOP, "logicop", GECmdFormat::LOGIC_OP }, + { GE_CMD_ZWRITEDISABLE, "zwrite_off", GECmdFormat::FLAG }, + { GE_CMD_MASKRGB, "rgbmask_block", GECmdFormat::RGB }, + { GE_CMD_MASKALPHA, "swritemask_block", GECmdFormat::DATA8 }, + { GE_CMD_TRANSFERSTART, "transferstart_bpp", GECmdFormat::FLAG }, + { GE_CMD_TRANSFERSRCPOS, "transfersrcpos", GECmdFormat::X10_Y10 }, + { GE_CMD_TRANSFERDSTPOS, "transferdstpos", GECmdFormat::X10_Y10 }, + { GE_CMD_UNKNOWN_ED, "unknowned", GECmdFormat::NONE }, + { GE_CMD_TRANSFERSIZE, "transfersize", GECmdFormat::X10_Y10 }, + { GE_CMD_UNKNOWN_EF, "unknownef", GECmdFormat::NONE }, + { GE_CMD_VSCX, "immx", GECmdFormat::SUBPIXEL_COORD }, + { GE_CMD_VSCY, "immy", GECmdFormat::SUBPIXEL_COORD }, + { GE_CMD_VSCZ, "immz", GECmdFormat::DATA16 }, + { GE_CMD_VTCS, "imms", GECmdFormat::FLOAT }, + { GE_CMD_VTCT, "immt", GECmdFormat::FLOAT }, + { GE_CMD_VTCQ, "immq", GECmdFormat::FLOAT }, + { GE_CMD_VCV, "immrgb", GECmdFormat::RGB }, + { GE_CMD_VAP, "imma_prim", GECmdFormat::ALPHA_PRIM }, + { GE_CMD_VFC, "immfog", GECmdFormat::DATA8 }, + { GE_CMD_VSCV, "immrgb1", GECmdFormat::RGB }, + { GE_CMD_UNKNOWN_FA, "unknownfa", GECmdFormat::NONE }, + { GE_CMD_UNKNOWN_FB, "unknownfb", GECmdFormat::NONE }, + { GE_CMD_UNKNOWN_FC, "unknownfc", GECmdFormat::NONE }, + { GE_CMD_UNKNOWN_FD, "unknownfd", GECmdFormat::NONE }, + { GE_CMD_UNKNOWN_FE, "unknownfe", GECmdFormat::NONE }, + { GE_CMD_NOP_FF, "nopff", GECmdFormat::NONE }, +}; + +static constexpr GECmdAlias geCmdAliases[] = { + { GE_CMD_VADDR, { "vertexaddr" } }, + { GE_CMD_IADDR, { "indexaddr" } }, + { GE_CMD_BOUNDINGBOX, { "boundingbox", "boundtest" } }, + { GE_CMD_BJUMP, { "boundjump" } }, + { GE_CMD_BASE, { "baseaddr" } }, + { GE_CMD_VERTEXTYPE, { "vertextype" } }, + { GE_CMD_OFFSETADDR, { "offsetaddr" } }, + { GE_CMD_REGION2, { "region2" } }, + { GE_CMD_LIGHTINGENABLE, { "lightingenable", "lighting" } }, + { GE_CMD_LIGHTENABLE0, { "light0enable" } }, + { GE_CMD_LIGHTENABLE1, { "light1enable" } }, + { GE_CMD_LIGHTENABLE2, { "light2enable" } }, + { GE_CMD_LIGHTENABLE3, { "light3enable" } }, + { GE_CMD_DEPTHCLAMPENABLE, { "zclampenable", "depthclamp_on", "depthclampenable" } }, + { GE_CMD_CULLFACEENABLE, { "cullenable", "cullface_on", "cullfaceenable" } }, + { GE_CMD_TEXTUREMAPENABLE, { "texenable", "texture_on", "textureenable" } }, + { GE_CMD_FOGENABLE, { "fogenable" } }, + { GE_CMD_DITHERENABLE, { "ditherenable" } }, + { GE_CMD_ALPHABLENDENABLE, { "ablendenable", "alphablend_on", "alphablendenable" } }, + { GE_CMD_ALPHABLENDENABLE, { "atestenable", "alphatest_on", "alphatestenable" } }, + { GE_CMD_ZTESTENABLE, { "ztestenable", "depthtest_on", "depthtest_enable" } }, + { GE_CMD_STENCILTESTENABLE, { "stestenable", "stenciltest_on", "stenciltestenable" } }, + { GE_CMD_ANTIALIASENABLE, { "antialiasenable", "antialias" } }, + { GE_CMD_PATCHCULLENABLE, { "patchcullenable" } }, + { GE_CMD_COLORTESTENABLE, { "ctestenable", "colortest_on", "colortestenable" } }, + { GE_CMD_LOGICOPENABLE, { "logicopenable" } }, + { GE_CMD_BONEMATRIXNUMBER, { "bonematrixnum" } }, + { GE_CMD_BONEMATRIXDATA, { "bonematrixdata" } }, + { GE_CMD_MORPHWEIGHT0, { "morphweight0" } }, + { GE_CMD_MORPHWEIGHT1, { "morphweight1" } }, + { GE_CMD_MORPHWEIGHT2, { "morphweight2" } }, + { GE_CMD_MORPHWEIGHT3, { "morphweight3" } }, + { GE_CMD_MORPHWEIGHT4, { "morphweight4" } }, + { GE_CMD_MORPHWEIGHT5, { "morphweight5" } }, + { GE_CMD_MORPHWEIGHT6, { "morphweight6" } }, + { GE_CMD_MORPHWEIGHT7, { "morphweight7" } }, + { GE_CMD_PATCHDIVISION, { "patchdiv" } }, + { GE_CMD_PATCHFACING, { "patchreversenormal" } }, + { GE_CMD_WORLDMATRIXNUMBER, { "worldmatrixnum" } }, + { GE_CMD_WORLDMATRIXDATA, { "worldmatrixdata" } }, + { GE_CMD_VIEWMATRIXNUMBER, { "viewmatrixnum" } }, + { GE_CMD_VIEWMATRIXDATA, { "viewmatrixdata" } }, + { GE_CMD_PROJMATRIXNUMBER, { "projmatrixnum" } }, + { GE_CMD_PROJMATRIXDATA, { "projmatrixdata" } }, + { GE_CMD_TGENMATRIXNUMBER, { "texgenmatrixnum", "tgenmtxnum", "tgenmatrixnum" } }, + { GE_CMD_TGENMATRIXDATA, { "texgenmatrixdata", "tgenmtxdata", "tgenmatrixdata" } }, + { GE_CMD_VIEWPORTXSCALE, { "viewportxscale" } }, + { GE_CMD_VIEWPORTYSCALE, { "viewportyscale" } }, + { GE_CMD_VIEWPORTZSCALE, { "viewportzscale" } }, + { GE_CMD_VIEWPORTXCENTER, { "viewportxcenter" } }, + { GE_CMD_VIEWPORTYCENTER, { "viewportycenter" } }, + { GE_CMD_VIEWPORTZCENTER, { "viewportzcenter" } }, + { GE_CMD_SHADEMODE, { "shademode", "shading" } }, + { GE_CMD_REVERSENORMAL, { "reversenormal" } }, + { GE_CMD_MATERIALAMBIENT, { "materialambientrgb" } }, + { GE_CMD_MATERIALALPHA, { "materialambientalpha" } }, + { GE_CMD_MATERIALSPECULARCOEF, { "materialspecularcoef" } }, + { GE_CMD_AMBIENTCOLOR, { "ambientrgb" } }, + { GE_CMD_AMBIENTALPHA, { "ambientalpha" } }, + { GE_CMD_LIGHTMODE, { "lmode", "secondarycolor" } }, + { GE_CMD_LIGHTTYPE0, { "lighttype0" } }, + { GE_CMD_LIGHTTYPE1, { "lighttype1" } }, + { GE_CMD_LIGHTTYPE2, { "lighttype2" } }, + { GE_CMD_LIGHTTYPE3, { "lighttype3" } }, + { GE_CMD_FRAMEBUFPTR, { "framebufptr" } }, + { GE_CMD_FRAMEBUFWIDTH, { "fbwidth", "framebufstride", "framebufwidth" } }, + { GE_CMD_ZBUFPTR, { "depthbufptr" } }, + { GE_CMD_ZBUFWIDTH, { "zbwidth", "depthbufstride", "depthbufwidth" } }, + { GE_CMD_TEXBUFWIDTH0, { "texbufwidth0", "texstride0" } }, + { GE_CMD_TEXBUFWIDTH1, { "texbufwidth1", "texstride1" } }, + { GE_CMD_TEXBUFWIDTH2, { "texbufwidth2", "texstride2" } }, + { GE_CMD_TEXBUFWIDTH3, { "texbufwidth3", "texstride3" } }, + { GE_CMD_TEXBUFWIDTH4, { "texbufwidth4", "texstride4" } }, + { GE_CMD_TEXBUFWIDTH5, { "texbufwidth5", "texstride5" } }, + { GE_CMD_TEXBUFWIDTH6, { "texbufwidth6", "texstride6" } }, + { GE_CMD_TEXBUFWIDTH7, { "texbufwidth7", "texstride7" } }, + { GE_CMD_CLUTADDRUPPER, { "clutaddrupper" } }, + { GE_CMD_TEXSHADELS, { "texshadels" } }, + { GE_CMD_TEXWRAP, { "texwrap" } }, + { GE_CMD_FOGCOLOR, { "fogrgb" } }, + { GE_CMD_FRAMEBUFPIXFORMAT, { "framebufformat" } }, + { GE_CMD_CLEARMODE, { "clear" } }, + { GE_CMD_SCISSOR1, { "scissortl" } }, + { GE_CMD_SCISSOR2, { "scissorbr" } }, + { GE_CMD_COLORTEST, { "colortestfunc" } }, + { GE_CMD_COLORREF, { "colortestref" } }, + { GE_CMD_COLORTESTMASK, { "colortestmask" } }, + { GE_CMD_ALPHATEST, { "alphatest" } }, + { GE_CMD_STENCILTEST, { "stenciltest" } }, + { GE_CMD_ZTEST, { "depthtest" } }, + { GE_CMD_BLENDFIXEDA, { "blendfixsrc" } }, + { GE_CMD_BLENDFIXEDB, { "blendfixdst" } }, + { GE_CMD_ZWRITEDISABLE, { "depthwrite_off", "zwritedisable", "depthwritedisable" } }, + { GE_CMD_MASKRGB, { "rgbmask" } }, + { GE_CMD_MASKALPHA, { "swritemask", "amask", "amask_block" } }, + { GE_CMD_TRANSFERSTART, { "transferstart" } }, + { GE_CMD_VCV, { "immrgb0" } }, + { GE_CMD_VSCV, { "immsecondaryrgb" } }, +}; + +bool GECmdInfoByName(const char *name, GECmdInfo &result) { + for (const GECmdInfo &info : geCmdInfo) { + if (strcasecmp(info.name, name) == 0) { + result = info; + return true; + } + } + + for (const GECmdAlias &entry : geCmdAliases) { + for (const char *alias : entry.aliases) { + if (alias && strcasecmp(alias, name) == 0) { + result = GECmdInfoByCmd(entry.reg); + return true; + } + } + } + + return false; +} + +GECmdInfo GECmdInfoByCmd(GECommand reg) { + _assert_msg_((reg & 0xFF) == reg, "Invalid reg"); + return geCmdInfo[reg & 0xFF]; +} diff --git a/GPU/Debugger/GECommandTable.h b/GPU/Debugger/GECommandTable.h new file mode 100644 index 0000000000..01d2059079 --- /dev/null +++ b/GPU/Debugger/GECommandTable.h @@ -0,0 +1,79 @@ +// Copyright (c) 2022- 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/ge_constants.h" + +enum class GECmdFormat { + DATA, // Just regular data. + DATA16, // Data, but only 16 bits of it used. + DATA8, // 8 bits value (alpha, etc.) + NONE, // Should have no arguments or value. + RELATIVE_ADDR, // 24 bits added to base + offset. + PRIM, // 16 bits count, 3 bits type. + BEZIER, // 8 bits ucount, 8 bits vcount. + SPLINE, // 8 bits ucount, 8 bits vcount, 2 bits utype, 2 bits vtype. + JUMP, // Like RELATIVE_ADDR, but lower 2 bits ignored. + SIGNAL, // 16 bits data, 8 bits signal type. + HIGH_ADDR_ONLY, // 16 bits ignored, 8 bits for a high address. + LOW_ADDR_ONLY, // 24 bits low address. + LOW_ADDR, // 24 bits low address. + HIGH_ADDR, // 16 bits ignored, 8 bits for a high address. + VERTEX_TYPE, // 24-bits of vtype flags (complex.) + OFFSET_ADDR, // 24 bits become the high bits of offset. + X10_Y10, // 10 bits X, 10 bits Y. + FLAG, // 1 bit on/off. + BONE_NUM, // 7 bits number. + MATRIX_NUM, // 4 bits number. + FLOAT, // 24 bits float data. + PATCH_DIVISION, // 8 bits divisionu, 8 bits divisionv. + PATCH_PRIM, // 2 bits primitive type. + SUBPIXEL_COORD, // 4 bits subpixel, 12 bits integer value. + MATERIAL_UPDATE, // 3 bits colors to update. + RGB, // 24 bits RGB color. + LIGHT_TYPE, // 8 bits computation (2 bits), 2 bits type. + STRIDE, // 11 bits. + STRIDE_HIGH_ADDR, // 11 bits stride, 5 ignored, 8 bits high address. + TEX_SIZE, // 4 bits width power, 4 bits ignored, 4 bits height power. + TEX_MAP_MODE, // 8 bits mode (2 bits), 2 bits matrix factor. + TEX_LIGHT_SRC, // 8 bits lightu (2 bits), 2 bits lightv. + TEX_MODE, // 8 bits swizzle (1 bit), 8 bits separate clut4 (1 bit), 3 bits max level. + TEX_FORMAT, // 4 bits format. + TEX_FILTER, // 3 bits minify mode, 5 bits ignored, 1 bit magnify mode. + TEX_CLAMP, // 1 bit clampu, 7 bits ignored, 1 bit clampv. + TEX_LEVEL_MODE, // 2 bits mode, 15 bits ignored, 4.4 (8 bits) bias. + TEX_FUNC, // 3 bits function, 5 bits ignored, 1 bit use alpha, 7 bits ignored, 1 bit double color. + CLUT_BLOCKS, // 6 bits block count. + CLUT_FORMAT, // 2 bits format, 5 bits shift, 1 bit ignored, 8 bits mask, 5 bits base. + CLEAR_MODE, // 1 bit on, 7 bits ignored, 3 bits aspect. + COLOR_TEST_FUNC, // 2 bits test function. + ALPHA_TEST, // 3 bits function, 5 bits ignored, 8 bits ref, 8 bits mask. + STENCIL_OP, // 8 bits sfail (3 bits), 8 bits zfail (3 bits), 8 bits zpass (3 bits.) + DEPTH_TEST_FUNC, // 3 bits function. + BLEND_MODE, // 4 bits srcfactor, 4 bits dstfactor, 3 bits equation. + DITHER_ROW, // 4 s.3.0 fixed point dither offsets. + LOGIC_OP, // 4 bits logic operation. + ALPHA_PRIM, // 8 bits alpha, 3 bits primitive type, 1 bit antialias, 6 bit clip?, 1 bit shading, 1 bit cullenable, 1 bit cullface, 1 bit tex enable, 1 bit fog, 1 bit dither. +}; + +struct GECmdInfo { + GECommand reg; + const char *name; + GECmdFormat fmt; +}; + +bool GECmdInfoByName(const char *name, GECmdInfo &info); +GECmdInfo GECmdInfoByCmd(GECommand reg); diff --git a/GPU/Directx9/GPU_DX9.cpp b/GPU/Directx9/GPU_DX9.cpp index bd37b01aee..3e5d0bac57 100644 --- a/GPU/Directx9/GPU_DX9.cpp +++ b/GPU/Directx9/GPU_DX9.cpp @@ -265,7 +265,7 @@ void GPU_DX9::BeginHostFrame() { framebufferManager_->Resized(); drawEngine_.Resized(); shaderManagerDX9_->DirtyShader(); - textureCacheDX9_->NotifyConfigChanged(); + textureCache_->NotifyConfigChanged(); resized_ = false; } } diff --git a/GPU/Directx9/ShaderManagerDX9.cpp b/GPU/Directx9/ShaderManagerDX9.cpp index 1700206a02..6e20ec45e0 100644 --- a/GPU/Directx9/ShaderManagerDX9.cpp +++ b/GPU/Directx9/ShaderManagerDX9.cpp @@ -623,7 +623,7 @@ VSShader *ShaderManagerDX9::ApplyShader(bool useHWTransform, bool useHWTessellat // Fragment shader not in cache. Let's compile it. std::string errorString; uint64_t uniformMask; - bool success = GenerateFragmentShader(FSID, codeBuffer_, draw_->GetShaderLanguageDesc(), draw_->GetBugs(), &uniformMask, &errorString); + bool success = GenerateFragmentShader(FSID, codeBuffer_, draw_->GetShaderLanguageDesc(), draw_->GetBugs(), &uniformMask, nullptr, &errorString); // We're supposed to handle all possible cases. _assert_(success); fs = new PSShader(device_, FSID, codeBuffer_); diff --git a/GPU/Directx9/TextureCacheDX9.cpp b/GPU/Directx9/TextureCacheDX9.cpp index 289d52d3b7..3a06c3b4f5 100644 --- a/GPU/Directx9/TextureCacheDX9.cpp +++ b/GPU/Directx9/TextureCacheDX9.cpp @@ -41,7 +41,15 @@ Draw::DataFormat FromD3D9Format(u32 fmt) { switch (fmt) { - case D3DFMT_A8R8G8B8: default: return Draw::DataFormat::R8G8B8A8_UNORM; + case D3DFMT_A4R4G4B4: + return Draw::DataFormat::B4G4R4A4_UNORM_PACK16; + case D3DFMT_A1R5G5B5: + return Draw::DataFormat::A1R5G5B5_UNORM_PACK16; + case D3DFMT_R5G6B5: + return Draw::DataFormat::R5G6B5_UNORM_PACK16; + case D3DFMT_A8R8G8B8: + default: + return Draw::DataFormat::R8G8B8A8_UNORM; } } diff --git a/GPU/GLES/GPU_GLES.cpp b/GPU/GLES/GPU_GLES.cpp index cb41d2cff2..75fd0080b5 100644 --- a/GPU/GLES/GPU_GLES.cpp +++ b/GPU/GLES/GPU_GLES.cpp @@ -93,7 +93,7 @@ GPU_GLES::GPU_GLES(GraphicsContext *gfxCtx, Draw::DrawContext *draw) // Update again after init to be sure of any silly driver problems. UpdateVsyncInterval(true); - textureCacheGL_->NotifyConfigChanged(); + textureCache_->NotifyConfigChanged(); // Load shader cache. std::string discID = g_paramSFO.GetDiscID(); @@ -325,7 +325,7 @@ void GPU_GLES::BeginHostFrame() { framebufferManager_->Resized(); drawEngine_.Resized(); shaderManagerGL_->DirtyShader(); - textureCacheGL_->NotifyConfigChanged(); + textureCache_->NotifyConfigChanged(); resized_ = false; } diff --git a/GPU/GLES/ShaderManagerGLES.cpp b/GPU/GLES/ShaderManagerGLES.cpp index 2ea0a7ca9b..4d37ae2ba6 100644 --- a/GPU/GLES/ShaderManagerGLES.cpp +++ b/GPU/GLES/ShaderManagerGLES.cpp @@ -184,13 +184,13 @@ LinkedShader::LinkedShader(GLRenderManager *render, VShaderID VSID, Shader *vs, availableUniforms = vs->GetUniformMask() | fs->GetUniformMask(); std::vector initialize; - initialize.push_back({ &u_tex, 0, 0 }); - initialize.push_back({ &u_fbotex, 0, 1 }); - initialize.push_back({ &u_testtex, 0, 2 }); - initialize.push_back({ &u_pal, 0, 3 }); // CLUT - initialize.push_back({ &u_tess_points, 0, 4 }); // Control Points - initialize.push_back({ &u_tess_weights_u, 0, 5 }); - initialize.push_back({ &u_tess_weights_v, 0, 6 }); + initialize.push_back({ &u_tex, 0, TEX_SLOT_PSP_TEXTURE }); + initialize.push_back({ &u_fbotex, 0, TEX_SLOT_SHADERBLEND_SRC }); + initialize.push_back({ &u_testtex, 0, TEX_SLOT_ALPHATEST }); + initialize.push_back({ &u_pal, 0, TEX_SLOT_CLUT }); // CLUT + initialize.push_back({ &u_tess_points, 0, TEX_SLOT_SPLINE_POINTS }); // Control Points + initialize.push_back({ &u_tess_weights_u, 0, TEX_SLOT_SPLINE_WEIGHTS_U }); + initialize.push_back({ &u_tess_weights_v, 0, TEX_SLOT_SPLINE_WEIGHTS_V }); bool useDualSource = (gstate_c.featureFlags & GPU_SUPPORTS_DUALSOURCE_BLEND) != 0; bool useClip0 = VSID.Bit(VS_BIT_VERTEX_RANGE_CULLING) && gstate_c.Supports(GPU_SUPPORTS_CLIP_DISTANCE); @@ -709,7 +709,7 @@ void ShaderManagerGLES::DirtyLastShader() { Shader *ShaderManagerGLES::CompileFragmentShader(FShaderID FSID) { uint64_t uniformMask; std::string errorString; - if (!GenerateFragmentShader(FSID, codeBuffer_, draw_->GetShaderLanguageDesc(), draw_->GetBugs(), &uniformMask, &errorString)) { + if (!GenerateFragmentShader(FSID, codeBuffer_, draw_->GetShaderLanguageDesc(), draw_->GetBugs(), &uniformMask, nullptr, &errorString)) { ERROR_LOG(G3D, "Shader gen error: %s", errorString.c_str()); return nullptr; } diff --git a/GPU/GLES/TextureCacheGLES.cpp b/GPU/GLES/TextureCacheGLES.cpp index 928854f1e2..14ebad20be 100644 --- a/GPU/GLES/TextureCacheGLES.cpp +++ b/GPU/GLES/TextureCacheGLES.cpp @@ -230,7 +230,7 @@ void TextureCacheGLES::BindTexture(TexCacheEntry *entry) { int maxLevel = (entry->status & TexCacheEntry::STATUS_NO_MIPS) ? 0 : entry->maxLevel; SamplerCacheKey samplerKey = GetSamplingParams(maxLevel, entry); ApplySamplingParams(samplerKey); - gstate_c.SetUseShaderDepal(false, false); + gstate_c.SetUseShaderDepal(ShaderDepalMode::OFF); } void TextureCacheGLES::Unbind() { diff --git a/GPU/GPU.h b/GPU/GPU.h index 93f81fb67c..1fd455c662 100644 --- a/GPU/GPU.h +++ b/GPU/GPU.h @@ -19,6 +19,7 @@ #pragma once #include +#include class GPUInterface; class GPUDebugInterface; @@ -27,7 +28,7 @@ class GraphicsContext; // PSP rasterization has two outputs, color and depth. Stencil is packed // into the alpha channel of color (if exists), so possibly RASTER_COLOR // should be named RASTER_COLOR_STENCIL but it gets kinda hard to read. -enum RasterChannel { +enum RasterChannel : uint8_t { RASTER_COLOR = 0, RASTER_DEPTH = 1, }; @@ -39,6 +40,13 @@ enum SkipDrawReasonFlags { SKIPDRAW_WINDOW_MINIMIZED = 8, // Don't draw when the host window is minimized. }; +enum class ShaderDepalMode { + OFF = 0, + NORMAL = 1, + SMOOTHED = 2, + CLUT8_8888 = 3, // Read 8888 framebuffer as 8-bit CLUT. +}; + // Global GPU-related utility functions. // Nothing directly Ge-related in here. diff --git a/GPU/GPU.vcxproj b/GPU/GPU.vcxproj index 1f37652321..0480b490d7 100644 --- a/GPU/GPU.vcxproj +++ b/GPU/GPU.vcxproj @@ -370,6 +370,7 @@ + @@ -510,6 +511,7 @@ + diff --git a/GPU/GPU.vcxproj.filters b/GPU/GPU.vcxproj.filters index d581cb4bad..bd28a45e97 100644 --- a/GPU/GPU.vcxproj.filters +++ b/GPU/GPU.vcxproj.filters @@ -258,6 +258,9 @@ Common + + Debugger + @@ -506,6 +509,9 @@ Common + + Debugger + diff --git a/GPU/GPUCommon.cpp b/GPU/GPUCommon.cpp index 4da5fd2983..107398b7c8 100644 --- a/GPU/GPUCommon.cpp +++ b/GPU/GPUCommon.cpp @@ -1530,6 +1530,7 @@ void GPUCommon::Execute_End(u32 op, u32 diff) { break; default: + FlushImm(); currentList->subIntrToken = prev & 0xFFFF; UpdateState(GPUSTATE_DONE); // Since we marked done, we have to restore the context now before the next list runs. @@ -1651,6 +1652,7 @@ void GPUCommon::Execute_Prim(u32 op, u32 diff) { u32 count = data & 0xFFFF; if (count == 0) return; + FlushImm(); // Upper bits are ignored. GEPrimitiveType prim = static_cast((data >> 16) & 7); @@ -2143,6 +2145,7 @@ void GPUCommon::Execute_WorldMtxData(u32 op, u32 diff) { } num++; gstate.worldmtxnum = (GE_CMD_WORLDMATRIXNUMBER << 24) | (num & 0xF); + gstate.worldmtxdata = GE_CMD_WORLDMATRIXDATA << 24; } void GPUCommon::Execute_ViewMtxNum(u32 op, u32 diff) { @@ -2190,6 +2193,7 @@ void GPUCommon::Execute_ViewMtxData(u32 op, u32 diff) { } num++; gstate.viewmtxnum = (GE_CMD_VIEWMATRIXNUMBER << 24) | (num & 0xF); + gstate.viewmtxdata = GE_CMD_VIEWMATRIXDATA << 24; } void GPUCommon::Execute_ProjMtxNum(u32 op, u32 diff) { @@ -2238,6 +2242,7 @@ void GPUCommon::Execute_ProjMtxData(u32 op, u32 diff) { num++; if (num <= 16) gstate.projmtxnum = (GE_CMD_PROJMATRIXNUMBER << 24) | (num & 0xF); + gstate.projmtxdata = GE_CMD_PROJMATRIXDATA << 24; } void GPUCommon::Execute_TgenMtxNum(u32 op, u32 diff) { @@ -2285,6 +2290,7 @@ void GPUCommon::Execute_TgenMtxData(u32 op, u32 diff) { } num++; gstate.texmtxnum = (GE_CMD_TGENMATRIXNUMBER << 24) | (num & 0xF); + gstate.texmtxdata = GE_CMD_TGENMATRIXDATA << 24; } void GPUCommon::Execute_BoneMtxNum(u32 op, u32 diff) { @@ -2356,6 +2362,7 @@ void GPUCommon::Execute_BoneMtxData(u32 op, u32 diff) { } num++; gstate.boneMatrixNumber = (GE_CMD_BONEMATRIXNUMBER << 24) | (num & 0x7F); + gstate.boneMatrixData = GE_CMD_BONEMATRIXDATA << 24; } void GPUCommon::Execute_MorphWeight(u32 op, u32 diff) { @@ -2374,40 +2381,60 @@ void GPUCommon::Execute_ImmVertexAlphaPrim(u32 op, u32 diff) { return; } + int prim = (op >> 8) & 0x7; + if (prim != GE_PRIM_KEEP_PREVIOUS) { + // Flush before changing the prim type. Only continue can be used to continue a prim. + FlushImm(); + } + TransformedVertex &v = immBuffer_[immCount_++]; - // Formula deduced from ThrillVille's clear. - int offsetX = gstate.getOffsetX16(); - int offsetY = gstate.getOffsetY16(); - v.x = ((gstate.imm_vscx & 0xFFFFFF) - offsetX) / 16.0f; - v.y = ((gstate.imm_vscy & 0xFFFFFF) - offsetY) / 16.0f; + // ThrillVille does a clear with this, additional parameters found via tests. + // The current vtype affects how the coordinate is processed. + if (gstate.isModeThrough()) { + v.x = ((int)(gstate.imm_vscx & 0xFFFF) - 0x8000) / 16.0f; + v.y = ((int)(gstate.imm_vscy & 0xFFFF) - 0x8000) / 16.0f; + } else { + int offsetX = gstate.getOffsetX16(); + int offsetY = gstate.getOffsetY16(); + v.x = ((int)(gstate.imm_vscx & 0xFFFF) - offsetX) / 16.0f; + v.y = ((int)(gstate.imm_vscy & 0xFFFF) - offsetY) / 16.0f; + } v.z = gstate.imm_vscz & 0xFFFF; v.pos_w = 1.0f; v.u = getFloat24(gstate.imm_vtcs); v.v = getFloat24(gstate.imm_vtct); v.uv_w = getFloat24(gstate.imm_vtcq); v.color0_32 = (gstate.imm_cv & 0xFFFFFF) | (gstate.imm_ap << 24); - v.fog = 0.0f; // we have no information about the scale here + // TODO: When !gstate.isModeThrough(), direct fog coefficient (0 = entirely fog), ignore fog flag (also GE_IMM_FOG.) + v.fog = (gstate.imm_fc & 0xFF) / 255.0f; + // TODO: Apply if gstate.isUsingSecondaryColor() && !gstate.isModeThrough(), ignore lighting flag. v.color1_32 = gstate.imm_scv & 0xFFFFFF; - int prim = (op >> 8) & 0x7; if (prim != GE_PRIM_KEEP_PREVIOUS) { immPrim_ = (GEPrimitiveType)prim; - } else if (prim == GE_PRIM_KEEP_PREVIOUS && immCount_ == 2) { + // Flags seem to only be respected from the first prim. + immFlags_ = op & 0x00FFF800; + } else if (prim == GE_PRIM_KEEP_PREVIOUS && immPrim_ != GE_PRIM_INVALID) { + static constexpr int flushPrimCount[] = { 1, 2, 0, 3, 0, 0, 2, 0 }; // Instead of finding a proper point to flush, we just emit a full rectangle every time one // is finished. - FlushImm(); - // Need to reset immCount_ here. If we do it in FlushImm it could get skipped by gstate_c.skipDrawReason. - immCount_ = 0; + if (immCount_ == flushPrimCount[immPrim_ & 7]) + FlushImm(); } else { ERROR_LOG_REPORT_ONCE(imm_draw_prim, G3D, "Immediate draw: Unexpected primitive %d at count %d", prim, immCount_); } } void GPUCommon::FlushImm() { + if (immCount_ == 0 || immPrim_ == GE_PRIM_INVALID) + return; + SetDrawType(DRAW_PRIM, immPrim_); - framebufferManager_->SetRenderFrameBuffer(gstate_c.IsDirty(DIRTY_FRAMEBUF), gstate_c.skipDrawReason); + if (framebufferManager_) + framebufferManager_->SetRenderFrameBuffer(gstate_c.IsDirty(DIRTY_FRAMEBUF), gstate_c.skipDrawReason); if (gstate_c.skipDrawReason & (SKIPDRAW_SKIPFRAME | SKIPDRAW_NON_DISPLAYED_FB)) { // No idea how many cycles to skip, heh. + immCount_ = 0; return; } UpdateUVScaleOffset(); @@ -2417,23 +2444,69 @@ void GPUCommon::FlushImm() { // through vertices. // Since the only known use is Thrillville and it only uses it to clear, we just use color and pos. struct ImmVertex { + float uv[2]; uint32_t color; float xyz[3]; }; ImmVertex temp[MAX_IMMBUFFER_SIZE]; + uint32_t color1Used = 0; for (int i = 0; i < immCount_; i++) { + // Since we're sending through, scale back up to w/h. + temp[i].uv[0] = immBuffer_[i].u * gstate.getTextureWidth(0); + temp[i].uv[1] = immBuffer_[i].v * gstate.getTextureHeight(0); temp[i].color = immBuffer_[i].color0_32; temp[i].xyz[0] = immBuffer_[i].pos[0]; temp[i].xyz[1] = immBuffer_[i].pos[1]; temp[i].xyz[2] = immBuffer_[i].pos[2]; + color1Used |= immBuffer_[i].color1_32; + } + int vtype = GE_VTYPE_TC_FLOAT | GE_VTYPE_POS_FLOAT | GE_VTYPE_COL_8888 | GE_VTYPE_THROUGH; + + // TODO: Handle fog and secondary color somehow? + + bool antialias = (immFlags_ & GE_IMM_ANTIALIAS) != 0; + bool prevAntialias = gstate.isAntiAliasEnabled(); + bool shading = (immFlags_ & GE_IMM_SHADING) != 0; + bool prevShading = gstate.getShadeMode() == GE_SHADE_GOURAUD; + bool cullEnable = (immFlags_ & GE_IMM_CULLENABLE) != 0; + bool prevCullEnable = gstate.isCullEnabled(); + int cullMode = (immFlags_ & GE_IMM_CULLFACE) != 0 ? 1 : 0; + bool texturing = (immFlags_ & GE_IMM_TEXTURE) != 0; + bool prevTexturing = gstate.isTextureMapEnabled(); + bool dither = (immFlags_ & GE_IMM_DITHER) != 0; + bool prevDither = gstate.isDitherEnabled(); + + if ((immFlags_ & GE_IMM_CLIPMASK) != 0) { + WARN_LOG_REPORT_ONCE(geimmclipvalue, G3D, "Imm vertex used clip value, flags=%06x", immFlags_); + } else if ((immFlags_ & GE_IMM_FOG) != 0) { + WARN_LOG_REPORT_ONCE(geimmfog, G3D, "Imm vertex used fog, flags=%06x", immFlags_); + } else if (color1Used != 0 && gstate.isUsingSecondaryColor()) { + WARN_LOG_REPORT_ONCE(geimmcolor1, G3D, "Imm vertex used secondary color, flags=%06x", immFlags_); + } + + if (texturing != prevTexturing || cullEnable != prevCullEnable || dither != prevDither || prevShading != shading) { + DispatchFlush(); + gstate.antiAliasEnable = (GE_CMD_ANTIALIASENABLE << 24) | (int)antialias; + gstate.shademodel = (GE_CMD_SHADEMODE << 24) | (int)shading; + gstate.cullfaceEnable = (GE_CMD_CULLFACEENABLE << 24) | (int)cullEnable; + gstate.textureMapEnable = (GE_CMD_TEXTUREMAPENABLE << 24) | (int)texturing; + gstate.ditherEnable = (GE_CMD_DITHERENABLE << 24) | (int)dither; + gstate_c.Dirty(DIRTY_VERTEXSHADER_STATE | DIRTY_FRAGMENTSHADER_STATE | DIRTY_RASTER_STATE); } - int vtype = GE_VTYPE_POS_FLOAT | GE_VTYPE_COL_8888 | GE_VTYPE_THROUGH; int bytesRead; uint32_t vertTypeID = GetVertTypeID(vtype, 0); - drawEngineCommon_->DispatchSubmitImm(temp, nullptr, immPrim_, immCount_, vertTypeID, gstate.getCullMode(), &bytesRead); - // TOOD: In the future, make a special path for these. + drawEngineCommon_->DispatchSubmitImm(temp, nullptr, immPrim_, immCount_, vertTypeID, cullMode, &bytesRead); + // TODO: In the future, make a special path for these. // drawEngineCommon_->DispatchSubmitImm(immBuffer_, immCount_); + immCount_ = 0; + + gstate.antiAliasEnable = (GE_CMD_ANTIALIASENABLE << 24) | (int)prevAntialias; + gstate.shademodel = (GE_CMD_SHADEMODE << 24) | (int)prevShading; + gstate.cullfaceEnable = (GE_CMD_CULLFACEENABLE << 24) | (int)prevCullEnable; + gstate.textureMapEnable = (GE_CMD_TEXTUREMAPENABLE << 24) | (int)prevTexturing; + gstate.ditherEnable = (GE_CMD_DITHERENABLE << 24) | (int)prevDither; + gstate_c.Dirty(DIRTY_VERTEXSHADER_STATE | DIRTY_FRAGMENTSHADER_STATE | DIRTY_RASTER_STATE); } void GPUCommon::ExecuteOp(u32 op, u32 diff) { diff --git a/GPU/GPUCommon.h b/GPU/GPUCommon.h index f389b788e2..3a5674127f 100644 --- a/GPU/GPUCommon.h +++ b/GPU/GPUCommon.h @@ -286,6 +286,7 @@ protected: void UpdatePC(u32 currentPC, u32 newPC); void UpdateState(GPURunState state); void FastLoadBoneMatrix(u32 target); + void FlushImm(); // TODO: Unify this. virtual void FinishDeferred() {} @@ -352,13 +353,13 @@ protected: TransformedVertex immBuffer_[MAX_IMMBUFFER_SIZE]; int immCount_ = 0; - GEPrimitiveType immPrim_; + GEPrimitiveType immPrim_ = GE_PRIM_INVALID; + uint32_t immFlags_ = 0; std::string reportingPrimaryInfo_; std::string reportingFullInfo_; private: - void FlushImm(); void CheckDepthUsage(VirtualFramebuffer *vfb); void DoBlockTransfer(u32 skipDrawReason); void DoExecuteCall(u32 target); diff --git a/GPU/GPUState.h b/GPU/GPUState.h index 5b011374ac..cbfb58395d 100644 --- a/GPU/GPUState.h +++ b/GPU/GPUState.h @@ -407,7 +407,7 @@ struct GPUgstate { float getViewportYCenter() const { return getFloat24(viewportycenter); } float getViewportZCenter() const { return getFloat24(viewportzcenter); } - // Fixed 16 point. + // Fixed 12.4 point. int getOffsetX16() const { return offsetx & 0xFFFF; } int getOffsetY16() const { return offsety & 0xFFFF; } float getOffsetX() const { return (float)getOffsetX16() / 16.0f; } @@ -529,10 +529,9 @@ struct GPUStateCache { bool IsDirty(u64 what) const { return (dirty & what) != 0ULL; } - void SetUseShaderDepal(bool depal, bool smoothed) { - if (depal != useShaderDepal) { - useShaderDepal = depal; - useSmoothedShaderDepal = smoothed; + void SetUseShaderDepal(ShaderDepalMode mode) { + if (mode != shaderDepalMode) { + shaderDepalMode = mode; Dirty(DIRTY_FRAGMENTSHADER_STATE); } } @@ -628,8 +627,7 @@ struct GPUStateCache { SubmitType submitType; int spline_num_points_u; - bool useShaderDepal; - bool useSmoothedShaderDepal; + ShaderDepalMode shaderDepalMode; GEBufferFormat depalFramebufferFormat; u32 getRelativeAddress(u32 data) const; diff --git a/GPU/GeDisasm.cpp b/GPU/GeDisasm.cpp index 4f4bdb0efd..a645b5bc2b 100644 --- a/GPU/GeDisasm.cpp +++ b/GPU/GeDisasm.cpp @@ -94,6 +94,17 @@ void GeDisassembleOp(u32 pc, u32 op, u32 prev, char *buffer, int bufsize) { u32 cmd = op >> 24; u32 data = op & 0xFFFFFF; + static const char * const primTypes[8] = { + "POINTS", + "LINES", + "LINE_STRIP", + "TRIANGLES", + "TRIANGLE_STRIP", + "TRIANGLE_FAN", + "RECTANGLES", + "CONTINUE_PREVIOUS", + }; + // Handle control and drawing commands here directly. The others we delegate. switch (cmd) { @@ -132,20 +143,10 @@ void GeDisassembleOp(u32 pc, u32 op, u32 prev, char *buffer, int bufsize) { { u32 count = data & 0xFFFF; u32 type = (data >> 16) & 7; - static const char* types[8] = { - "POINTS", - "LINES", - "LINE_STRIP", - "TRIANGLES", - "TRIANGLE_STRIP", - "TRIANGLE_FAN", - "RECTANGLES", - "CONTINUE_PREVIOUS", - }; if (gstate.vertType & GE_VTYPE_IDX_MASK) - snprintf(buffer, bufsize, "DRAW PRIM %s: count= %i vaddr= %08x, iaddr= %08x", type < 7 ? types[type] : "INVALID", count, gstate_c.vertexAddr, gstate_c.indexAddr); + snprintf(buffer, bufsize, "DRAW PRIM %s: count= %i vaddr= %08x, iaddr= %08x", type < 7 ? primTypes[type] : "INVALID", count, gstate_c.vertexAddr, gstate_c.indexAddr); else - snprintf(buffer, bufsize, "DRAW PRIM %s: count= %i vaddr= %08x", type < 7 ? types[type] : "INVALID", count, gstate_c.vertexAddr); + snprintf(buffer, bufsize, "DRAW PRIM %s: count= %i vaddr= %08x", type < 7 ? primTypes[type] : "INVALID", count, gstate_c.vertexAddr); } break; @@ -347,11 +348,17 @@ void GeDisassembleOp(u32 pc, u32 op, u32 prev, char *buffer, int bufsize) { break; case GE_CMD_OFFSETX: - snprintf(buffer, bufsize, "Offset X: %i", data); + if (data & ~0xFFFF) + snprintf(buffer, bufsize, "Offset X: %04x / %d with sub %d (extra %02x)", data & 0xFFFF, data >> 4, data & 0xF, data >> 16); + else + snprintf(buffer, bufsize, "Offset X: %04x / %d with sub %d", data & 0xFFFF, data >> 4, data & 0xF); break; case GE_CMD_OFFSETY: - snprintf(buffer, bufsize, "Offset Y: %i", data); + if (data & ~0xFFFF) + snprintf(buffer, bufsize, "Offset Y: %04x / %d with sub %d (extra %02x)", data & 0xFFFF, data >> 4, data & 0xF, data >> 16); + else + snprintf(buffer, bufsize, "Offset Y: %04x / %d with sub %d", data & 0xFFFF, data >> 4, data & 0xF); break; case GE_CMD_TEXSCALEU: @@ -598,7 +605,7 @@ void GeDisassembleOp(u32 pc, u32 op, u32 prev, char *buffer, int bufsize) { { int w = 1 << (data & 0xf); int h = 1 << ((data>>8) & 0xf); - if ((data & ~0x0F0F) && w <= 512 && h <= 512) + if ((data & ~0x0F0F) == 0 && w <= 512 && h <= 512) snprintf(buffer, bufsize, "Texture size %d: %dx%d", cmd - GE_CMD_TEXSIZE0, w, h); else snprintf(buffer, bufsize, "Texture size %d: %dx%d (extra %06x)", cmd - GE_CMD_TEXSIZE0, w, h, data); @@ -736,6 +743,20 @@ void GeDisassembleOp(u32 pc, u32 op, u32 prev, char *buffer, int bufsize) { } break; + case GE_CMD_LKS0: + case GE_CMD_LKS1: + case GE_CMD_LKS2: + case GE_CMD_LKS3: + snprintf(buffer, bufsize, "Light %d spot exponent: %f", cmd - GE_CMD_LKS0, getFloat24(data)); + break; + + case GE_CMD_LKO0: + case GE_CMD_LKO1: + case GE_CMD_LKO2: + case GE_CMD_LKO3: + snprintf(buffer, bufsize, "Light %d spot cutoff: %f", cmd - GE_CMD_LKO0, getFloat24(data)); + break; + case GE_CMD_LAC0:case GE_CMD_LAC1:case GE_CMD_LAC2:case GE_CMD_LAC3: case GE_CMD_LDC0:case GE_CMD_LDC1:case GE_CMD_LDC2:case GE_CMD_LDC3: case GE_CMD_LSC0:case GE_CMD_LSC1:case GE_CMD_LSC2:case GE_CMD_LSC3: @@ -744,9 +765,15 @@ void GeDisassembleOp(u32 pc, u32 op, u32 prev, char *buffer, int bufsize) { float g = (float)((data>>8) & 0xff)/255.0f; float b = (float)(data>>16)/255.0f; + static const char * const lightColorTypes[] = { + "ambient", + "diffuse", + "specular", + }; + int l = (cmd - GE_CMD_LAC0) / 3; int t = (cmd - GE_CMD_LAC0) % 3; - snprintf(buffer, bufsize, "Light %i color %i: %f %f %f", l, t, r, g, b); + snprintf(buffer, bufsize, "Light %d %s color: %f %f %f", l, lightColorTypes[t], r, g, b); } break; @@ -1289,6 +1316,80 @@ void GeDisassembleOp(u32 pc, u32 op, u32 prev, char *buffer, int bufsize) { snprintf(buffer, bufsize, "BONE data # %f", getFloat24(data)); break; + case GE_CMD_VSCX: + if (data & ~0xFFFF) + snprintf(buffer, bufsize, "Vertex screen X: %04x / %d with sub %d (extra %02x)", data & 0xFFFF, data >> 4, data & 0xF, data >> 16); + else + snprintf(buffer, bufsize, "Vertex screen X: %04x / %d with sub %d", data & 0xFFFF, data >> 4, data & 0xF); + break; + + case GE_CMD_VSCY: + if (data & ~0xFFFF) + snprintf(buffer, bufsize, "Vertex screen Y: %04x / %d with sub %d (extra %02x)", data & 0xFFFF, data >> 4, data & 0xF, data >> 16); + else + snprintf(buffer, bufsize, "Vertex screen Y: %04x / %d with sub %d", data & 0xFFFF, data >> 4, data & 0xF); + break; + + case GE_CMD_VSCZ: + if (data & ~0xFFFF) + snprintf(buffer, bufsize, "Vertex Z: %04x (extra %02x)", data & 0xFFFF, data >> 16); + else + snprintf(buffer, bufsize, "Vertex Z: %04x", data & 0xFFFF); + break; + + case GE_CMD_VTCS: + snprintf(buffer, bufsize, "Vertex tex S: %f", getFloat24(data)); + break; + + case GE_CMD_VTCT: + snprintf(buffer, bufsize, "Vertex tex T: %f", getFloat24(data)); + break; + + case GE_CMD_VTCQ: + snprintf(buffer, bufsize, "Vertex tex Q: %f", getFloat24(data)); + break; + + case GE_CMD_VCV: + snprintf(buffer, bufsize, "Vertex color: %06x", data); + break; + + case GE_CMD_VAP: + { + bool antialias = (data & GE_IMM_ANTIALIAS) != 0; + int clip = (data & GE_IMM_CLIPMASK) >> 12; + bool shading = (data & GE_IMM_SHADING) != 0; + bool cullEnable = (data & GE_IMM_CULLENABLE) != 0; + int cullMode = (data & GE_IMM_CULLFACE) != 0 ? 1 : 0; + bool texturing = (data & GE_IMM_TEXTURE) != 0; + bool dither = (data & GE_IMM_DITHER) != 0; + char *p = buffer; + p += snprintf(p, bufsize - (p - buffer), "Vertex draw: alpha=%02x, prim=%s", data & 0xFF, primTypes[(data >> 8) & 7]); + if (antialias) + p += snprintf(p, bufsize - (p - buffer), ", antialias"); + if (clip != 0) + p += snprintf(p, bufsize - (p - buffer), ", clip=%02x", clip); + if (shading) + p += snprintf(p, bufsize - (p - buffer), ", shading"); + if (cullEnable) + p += snprintf(p, bufsize - (p - buffer), ", cull=%s", cullMode == 1 ? "back (CCW)" : "front (CW)"); + if (texturing) + p += snprintf(p, bufsize - (p - buffer), ", texturing"); + if (dither) + p += snprintf(p, bufsize - (p - buffer), ", dither"); + } + break; + + case GE_CMD_VFC: + if (data & ~0xFF) + snprintf(buffer, bufsize, "Vertex fog: %02x / %f (extra %04x)", data & 0xFF, (data & 0xFF) / 255.0f, data >> 8); + else + snprintf(buffer, bufsize, "Vertex fog: %02x / %f", data & 0xFF, (data & 0xFF) / 255.0f); + break; + + case GE_CMD_VSCV: + snprintf(buffer, bufsize, "Vertex secondary color: %06x", data); + break; + default: snprintf(buffer, bufsize, "Unknown: %08x", op); break; diff --git a/GPU/Math3D.h b/GPU/Math3D.h index dd1991f917..a87cce8318 100644 --- a/GPU/Math3D.h +++ b/GPU/Math3D.h @@ -228,11 +228,11 @@ public: Vec3() {} Vec3(const T a[3]) : x(a[0]), y(a[1]), z(a[2]) {} - Vec3(const T& _x, const T& _y, const T& _z) : x(_x), y(_y), z(_z) {} + constexpr Vec3(const T& _x, const T& _y, const T& _z) : x(_x), y(_y), z(_z) {} Vec3(const Vec2& _xy, const T& _z) : x(_xy.x), y(_xy.y), z(_z) {} #if defined(_M_SSE) - Vec3(const __m128 &_vec) : vec(_vec) {} - Vec3(const __m128i &_ivec) : ivec(_ivec) {} + constexpr Vec3(const __m128 &_vec) : vec(_vec) {} + constexpr Vec3(const __m128i &_ivec) : ivec(_ivec) {} Vec3(const Vec3Packed &_xyz) { vec = _mm_loadu_ps(_xyz.AsArray()); } @@ -249,7 +249,7 @@ public: #endif template - Vec3 Cast() const + constexpr Vec3 Cast() const { return Vec3((T2)x, (T2)y, (T2)z); } @@ -258,7 +258,7 @@ public: static Vec3 FromRGB(unsigned int rgb); unsigned int ToRGB() const; // alpha bits set to zero - static Vec3 AssignToAll(const T& f) + static constexpr Vec3 AssignToAll(const T& f) { return Vec3(f, f, f); } diff --git a/GPU/Software/BinManager.cpp b/GPU/Software/BinManager.cpp index 7f8f1ad453..9c1c1ff3ef 100644 --- a/GPU/Software/BinManager.cpp +++ b/GPU/Software/BinManager.cpp @@ -161,13 +161,13 @@ BinManager::~BinManager() { } } -void BinManager::UpdateState() { +void BinManager::UpdateState(bool throughMode) { PROFILE_THIS_SCOPE("bin_state"); if (HasDirty(SoftDirty::PIXEL_ALL | SoftDirty::SAMPLER_ALL | SoftDirty::RAST_ALL)) { if (states_.Full()) Flush("states"); - stateIndex_ = (int)states_.Push(RasterizerState()); - ComputeRasterizerState(&states_[stateIndex_]); + stateIndex_ = (uint16_t)states_.Push(RasterizerState()); + ComputeRasterizerState(&states_[stateIndex_], throughMode); states_[stateIndex_].samplerID.cached.clut = cluts_[clutIndex_].readable; ClearDirty(SoftDirty::PIXEL_ALL | SoftDirty::SAMPLER_ALL | SoftDirty::RAST_ALL); @@ -312,7 +312,7 @@ void BinManager::UpdateClut(const void *src) { PROFILE_THIS_SCOPE("bin_clut"); if (cluts_.Full()) Flush("cluts"); - clutIndex_ = (int)cluts_.Push(BinClut()); + clutIndex_ = (uint16_t)cluts_.Push(BinClut()); memcpy(cluts_[clutIndex_].readable, src, sizeof(BinClut)); } diff --git a/GPU/Software/BinManager.h b/GPU/Software/BinManager.h index 01b6837d20..79146eae1d 100644 --- a/GPU/Software/BinManager.h +++ b/GPU/Software/BinManager.h @@ -24,7 +24,7 @@ struct BinWaitable; class DrawBinItemsTask; -enum class BinItemType { +enum class BinItemType : uint8_t { TRIANGLE, CLEAR_RECT, RECT, @@ -48,7 +48,7 @@ struct BinCoords { struct BinItem { BinItemType type; - int stateIndex; + uint16_t stateIndex; BinCoords range; VertexData v0; VertexData v1; @@ -181,7 +181,7 @@ public: BinManager(); ~BinManager(); - void UpdateState(); + void UpdateState(bool throughMode); void UpdateClut(const void *src); const Rasterizer::RasterizerState &State() { @@ -237,9 +237,9 @@ protected: private: BinStateQueue states_; - int stateIndex_; BinClutQueue cluts_; - int clutIndex_; + uint16_t stateIndex_; + uint16_t clutIndex_; BinCoords scissor_; BinItemQueue queue_; BinCoords queueRange_; diff --git a/GPU/Software/Clipper.cpp b/GPU/Software/Clipper.cpp index 3627db0e3d..166947ef14 100644 --- a/GPU/Software/Clipper.cpp +++ b/GPU/Software/Clipper.cpp @@ -132,7 +132,7 @@ static inline bool CheckOutsideZ(ClipCoords p, int &pos, int &neg) { } void ProcessRect(const VertexData &v0, const VertexData &v1, BinManager &binner) { - if (!gstate.isModeThrough()) { + if (!binner.State().throughMode) { // We may discard the entire rect based on depth values. int outsidePos = 0, outsideNeg = 0; CheckOutsideZ(v0.clippos, outsidePos, outsideNeg); @@ -181,7 +181,7 @@ void ProcessPoint(const VertexData &v0, BinManager &binner) { } void ProcessLine(const VertexData &v0, const VertexData &v1, BinManager &binner) { - if (gstate.isModeThrough()) { + if (binner.State().throughMode) { // Actually, should clip this one too so we don't need to do bounds checks in the rasterizer. binner.AddLine(v0, v1); return; @@ -221,7 +221,7 @@ void ProcessLine(const VertexData &v0, const VertexData &v1, BinManager &binner) void ProcessTriangle(const VertexData &v0, const VertexData &v1, const VertexData &v2, const VertexData &provoking, BinManager &binner) { int mask = 0; - if (!gstate.isModeThrough()) { + if (!binner.State().throughMode) { mask |= CalcClipMask(v0.clippos); mask |= CalcClipMask(v1.clippos); mask |= CalcClipMask(v2.clippos); diff --git a/GPU/Software/DrawPixel.cpp b/GPU/Software/DrawPixel.cpp index 3585c9a3ff..ee47c27b94 100644 --- a/GPU/Software/DrawPixel.cpp +++ b/GPU/Software/DrawPixel.cpp @@ -325,6 +325,10 @@ static inline bool DepthTestPassed(GEComparison func, int x, int y, int stride, } } +bool CheckDepthTestPassed(GEComparison func, int x, int y, int stride, u16 z) { + return DepthTestPassed(func, x, y, stride, z); +} + static inline u32 ApplyLogicOp(GELogicOp op, u32 old_color, u32 new_color) { // All of the operations here intentionally preserve alpha/stencil. switch (op) { @@ -400,7 +404,7 @@ template void SOFTRAST_CALL DrawSinglePixel(int x, int y, int z, int fog, Vec4IntArg color_in, const PixelFuncID &pixelID) { Vec4 prim_color = Vec4(color_in).Clamp(0, 255); // Depth range test - applied in clear mode, if not through mode. - if (pixelID.applyDepthRange) + if (pixelID.applyDepthRange && !pixelID.earlyZChecks) if (z < pixelID.cached.minz || z > pixelID.cached.maxz) return; @@ -411,7 +415,9 @@ void SOFTRAST_CALL DrawSinglePixel(int x, int y, int z, int fog, Vec4IntArg colo // Fog is applied prior to color test. if (pixelID.applyFog && !clearMode) { Vec3 fogColor = Vec3::FromRGB(pixelID.cached.fogColor); - fogColor = (prim_color.rgb() * fog + fogColor * (255 - fog)) / 255; + // This is very similar to the BLEND texfunc, and simply always rounds up. + static constexpr Vec3 roundup = Vec3::AssignToAll(255); + fogColor = (prim_color.rgb() * fog + fogColor * (255 - fog) + roundup) / 256; prim_color.r() = fogColor.r(); prim_color.g() = fogColor.g(); prim_color.b() = fogColor.b(); @@ -436,14 +442,14 @@ void SOFTRAST_CALL DrawSinglePixel(int x, int y, int z, int fog, Vec4IntArg colo } // Also apply depth at the same time. If disabled, same as passing. - if (pixelID.DepthTestFunc() != GE_COMP_ALWAYS && !DepthTestPassed(pixelID.DepthTestFunc(), x, y, pixelID.cached.depthbufStride, z)) { + if (!pixelID.earlyZChecks && pixelID.DepthTestFunc() != GE_COMP_ALWAYS && !DepthTestPassed(pixelID.DepthTestFunc(), x, y, pixelID.cached.depthbufStride, z)) { stencil = ApplyStencilOp(fbFormat, stencilReplace, pixelID.ZFail(), stencil); SetPixelStencil(fbFormat, pixelID.cached.framebufStride, targetWriteMask, x, y, stencil); return; } stencil = ApplyStencilOp(fbFormat, stencilReplace, pixelID.ZPass(), stencil); - } else { + } else if (!pixelID.earlyZChecks) { if (pixelID.DepthTestFunc() != GE_COMP_ALWAYS && !DepthTestPassed(pixelID.DepthTestFunc(), x, y, pixelID.cached.depthbufStride, z)) { return; } @@ -544,8 +550,6 @@ void PixelJitCache::Clear() { constBlendHalf_11_4s_ = nullptr; constBlendInvert_11_4s_ = nullptr; - const255_16s_ = nullptr; - constBy255i_ = nullptr; } std::string PixelJitCache::DescribeCodePtr(const u8 *ptr) { diff --git a/GPU/Software/DrawPixel.h b/GPU/Software/DrawPixel.h index b1063d59a1..f813bf61c1 100644 --- a/GPU/Software/DrawPixel.h +++ b/GPU/Software/DrawPixel.h @@ -41,6 +41,8 @@ SingleFunc GetSingleFunc(const PixelFuncID &id); void Init(); void Shutdown(); +bool CheckDepthTestPassed(GEComparison func, int x, int y, int stride, u16 z); + bool DescribeCodePtr(const u8 *ptr, std::string &name); struct PixelBlendState { @@ -104,8 +106,6 @@ private: const u8 *constBlendHalf_11_4s_ = nullptr; const u8 *constBlendInvert_11_4s_ = nullptr; - const u8 *const255_16s_ = nullptr; - const u8 *constBy255i_ = nullptr; #if PPSSPP_ARCH(X86) || PPSSPP_ARCH(AMD64) void Discard(); diff --git a/GPU/Software/DrawPixelX86.cpp b/GPU/Software/DrawPixelX86.cpp index 536f1efb02..dc53be1c62 100644 --- a/GPU/Software/DrawPixelX86.cpp +++ b/GPU/Software/DrawPixelX86.cpp @@ -149,7 +149,7 @@ RegCache::Reg PixelJitCache::GetColorOff(const PixelFuncID &id) { if (!regCache_.Has(RegCache::GEN_COLOR_OFF)) { Describe("GetColorOff"); if (id.useStandardStride && !id.dithering) { - bool loadDepthOff = id.depthWrite || id.DepthTestFunc() != GE_COMP_ALWAYS; + bool loadDepthOff = id.depthWrite || (id.DepthTestFunc() != GE_COMP_ALWAYS && !id.earlyZChecks); X64Reg depthTemp = INVALID_REG; X64Reg argYReg = regCache_.Find(RegCache::GEN_ARG_Y); X64Reg argXReg = regCache_.Find(RegCache::GEN_ARG_X); @@ -336,16 +336,10 @@ void PixelJitCache::WriteConstantPool(const PixelFuncID &id) { // This is used for shifted blend factors, to inverse them. WriteSimpleConst8x16(constBlendInvert_11_4s_, 0xFF << 4); - - // A set of 255s, used to inverse fog. - WriteSimpleConst8x16(const255_16s_, 0xFF); - - // This is used for a multiply that divides by 255 with shifting. - WriteSimpleConst8x16(constBy255i_, 0x8081); } bool PixelJitCache::Jit_ApplyDepthRange(const PixelFuncID &id) { - if (id.applyDepthRange) { + if (id.applyDepthRange && !id.earlyZChecks) { Describe("ApplyDepthR"); X64Reg argZReg = regCache_.Find(RegCache::GEN_ARG_Z); X64Reg idReg = GetPixelID(); @@ -365,7 +359,7 @@ bool PixelJitCache::Jit_ApplyDepthRange(const PixelFuncID &id) { // Since this is early on, try to free up the z reg if we don't need it anymore. if (id.clearMode && !id.DepthClear()) regCache_.ForceRelease(RegCache::GEN_ARG_Z); - else if (!id.clearMode && !id.depthWrite && id.DepthTestFunc() == GE_COMP_ALWAYS) + else if (!id.clearMode && !id.depthWrite && (id.DepthTestFunc() == GE_COMP_ALWAYS || id.earlyZChecks)) regCache_.ForceRelease(RegCache::GEN_ARG_Z); return true; @@ -535,7 +529,8 @@ bool PixelJitCache::Jit_ApplyFog(const PixelFuncID &id) { // Load a set of 255s at 16 bit into a reg for later... X64Reg invertReg = regCache_.Alloc(RegCache::VEC_TEMP2); - MOVDQA(invertReg, M(const255_16s_)); + PCMPEQW(invertReg, R(invertReg)); + PSRLW(invertReg, 8); // Expand (we clamped) color to 16 bit as well, so we can multiply with fog. X64Reg argColorReg = regCache_.Find(RegCache::VEC_ARG_COLOR); @@ -568,21 +563,24 @@ bool PixelJitCache::Jit_ApplyFog(const PixelFuncID &id) { // We can free up the actual fog reg now. regCache_.ForceRelease(RegCache::GEN_ARG_FOG); + // Our goal here is to calculate this formula: + // (argColor * fog + fogColor * (255 - fog) + 255) / 256 + // Now we multiply the existing color by fog... PMULLW(argColorReg, R(fogMultReg)); - // And then inverse the fog value using those 255s we loaded, and multiply by fog color. - PSUBUSW(invertReg, R(fogMultReg)); + // Before inversing, let's add that 255 we loaded in as well, since we have it. + PADDW(argColorReg, R(invertReg)); + // And then inverse the fog value using those 255s, and multiply by fog color. + PSUBW(invertReg, R(fogMultReg)); PMULLW(fogColorReg, R(invertReg)); // At this point, argColorReg and fogColorReg are multiplied at 16-bit, so we need to sum. - PADDUSW(argColorReg, R(fogColorReg)); + PADDW(argColorReg, R(fogColorReg)); regCache_.Release(fogColorReg, RegCache::VEC_TEMP1); regCache_.Release(invertReg, RegCache::VEC_TEMP2); regCache_.Release(fogMultReg, RegCache::VEC_TEMP3); - // Now to divide by 255, we use bit tricks: multiply by 0x8081, and shift right by 16+7. - PMULHUW(argColorReg, M(constBy255i_)); - // Now shift right by 7 (PMULHUW already did 16 of the shift.) - PSRLW(argColorReg, 7); + // Now we simply divide by 256, or in other words shift by 8. + PSRLW(argColorReg, 8); // Okay, put A back in, we'll shrink it to 8888 when needed. PINSRW(argColorReg, R(alphaReg), 3); @@ -721,7 +719,7 @@ bool PixelJitCache::Jit_StencilTest(const PixelFuncID &id, RegCache::Reg stencil } bool PixelJitCache::Jit_DepthTestForStencil(const PixelFuncID &id, RegCache::Reg stencilReg) { - if (id.DepthTestFunc() == GE_COMP_ALWAYS) + if (id.DepthTestFunc() == GE_COMP_ALWAYS || id.earlyZChecks) return true; X64Reg depthOffReg = GetDepthOff(id); @@ -964,7 +962,7 @@ bool PixelJitCache::Jit_WriteStencilOnly(const PixelFuncID &id, RegCache::Reg st } bool PixelJitCache::Jit_DepthTest(const PixelFuncID &id) { - if (id.DepthTestFunc() == GE_COMP_ALWAYS) + if (id.DepthTestFunc() == GE_COMP_ALWAYS || id.earlyZChecks) return true; if (id.DepthTestFunc() == GE_COMP_NEVER) { diff --git a/GPU/Software/FuncId.cpp b/GPU/Software/FuncId.cpp index 729591212b..501b5aaf27 100644 --- a/GPU/Software/FuncId.cpp +++ b/GPU/Software/FuncId.cpp @@ -48,11 +48,11 @@ static inline PixelBlendFactor OptimizeAlphaFactor(uint32_t color) { return PixelBlendFactor::FIX; } -void ComputePixelFuncID(PixelFuncID *id) { +void ComputePixelFuncID(PixelFuncID *id, bool throughMode) { id->fullKey = 0; // TODO: Could this be minz > 0x0000 || maxz < 0xFFFF? Maybe unsafe, depending on verts... - id->applyDepthRange = !gstate.isModeThrough(); + id->applyDepthRange = !throughMode; // Dither happens even in clear mode. id->dithering = gstate.isDitherEnabled(); id->fbFormat = gstate.FrameBufFormat(); @@ -79,6 +79,7 @@ void ComputePixelFuncID(PixelFuncID *id) { id->stencilTest = gstate.isStencilTestEnabled(); } id->depthWrite = gstate.isDepthTestEnabled() && gstate.isDepthWriteEnabled(); + id->depthTestFunc = gstate.isDepthTestEnabled() ? gstate.getDepthTestFunction() : GE_COMP_ALWAYS; if (id->stencilTest) { id->stencilTestRef = gstate.getStencilTestRef() & gstate.getStencilTestMask(); @@ -93,13 +94,6 @@ void ComputePixelFuncID(PixelFuncID *id) { if (gstate.FrameBufFormat() != GE_FORMAT_565 && gstate.getStencilOpZPass() <= GE_STENCILOP_DECR) id->zPass = gstate.getStencilOpZPass(); - // Always treat zPass/zFail the same if there's no depth test. - if (!gstate.isDepthTestEnabled() || gstate.getDepthTestFunction() == GE_COMP_ALWAYS) - id->zFail = id->zPass; - // And same for sFail if there's no stencil test. - if (id->StencilTestFunc() == GE_COMP_ALWAYS) - id->sFail = id->zPass; - // Normalize REPLACE 00 to ZERO, especially if using a mask. if (gstate.getStencilTestRef() == 0) { if (id->SFail() == GE_STENCILOP_REPLACE) @@ -120,14 +114,27 @@ void ComputePixelFuncID(PixelFuncID *id) { id->zPass = GE_STENCILOP_ZERO; } - // Turn off stencil testing if it's doing nothing. - if (id->SFail() == GE_STENCILOP_KEEP && id->ZFail() == GE_STENCILOP_KEEP && id->ZPass() == GE_STENCILOP_KEEP) { - if (id->StencilTestFunc() == GE_COMP_ALWAYS) + // And same for sFail if there's no stencil test. Prefer KEEP, though. + if (id->StencilTestFunc() == GE_COMP_ALWAYS) { + if (id->DepthTestFunc() == GE_COMP_ALWAYS) + id->zFail = GE_STENCILOP_KEEP; + id->sFail = GE_STENCILOP_KEEP; + // Always doesn't need a mask. + id->stencilTestRef = gstate.getStencilTestRef(); + id->hasStencilTestMask = false; + + // Turn off stencil testing if it's doing nothing. + if (id->SFail() == GE_STENCILOP_KEEP && id->ZFail() == GE_STENCILOP_KEEP && id->ZPass() == GE_STENCILOP_KEEP) { id->stencilTest = false; + id->stencilTestFunc = 0; + id->stencilTestRef = 0; + } + } else if (id->DepthTestFunc() == GE_COMP_ALWAYS) { + // Always treat zPass/zFail the same if there's no depth test. + id->zFail = id->zPass; } } - id->depthTestFunc = gstate.isDepthTestEnabled() ? gstate.getDepthTestFunction() : GE_COMP_ALWAYS; id->alphaTestFunc = gstate.isAlphaTestEnabled() ? gstate.getAlphaTestFunction() : GE_COMP_ALWAYS; if (id->AlphaTestFunc() != GE_COMP_ALWAYS) { id->alphaTestRef = gstate.getAlphaTestRef() & gstate.getAlphaTestMask(); @@ -162,7 +169,14 @@ void ComputePixelFuncID(PixelFuncID *id) { } id->applyLogicOp = gstate.isLogicOpEnabled() && gstate.getLogicOp() != GE_LOGIC_COPY; - id->applyFog = gstate.isFogEnabled() && !gstate.isModeThrough(); + id->applyFog = gstate.isFogEnabled() && !throughMode; + + id->earlyZChecks = id->DepthTestFunc() != GE_COMP_ALWAYS; + if (id->stencilTest && id->earlyZChecks) { + // Can't do them early if stencil might need to write. + if (id->SFail() != GE_STENCILOP_KEEP || id->ZFail() != GE_STENCILOP_KEEP) + id->earlyZChecks = false; + } } // Cache some values for later convenience. @@ -272,6 +286,8 @@ std::string DescribePixelFuncID(const PixelFuncID &id) { desc = "INVALID:" + desc; } + if (id.earlyZChecks) + desc += "ZEarly:"; if (id.DepthTestFunc() != GE_COMP_ALWAYS) { if (id.clearMode) desc = "INVALID:" + desc; @@ -305,7 +321,8 @@ std::string DescribePixelFuncID(const PixelFuncID &id) { } if (id.hasStencilTestMask) desc += "Msk"; - desc += StringFromFormat("%02X:", id.stencilTestRef); + if (id.StencilTestFunc() != GE_COMP_ALWAYS || id.DepthTestFunc() != GE_COMP_ALWAYS) + desc += StringFromFormat("%02X:", id.stencilTestRef); } else if (id.hasStencilTestMask || id.stencilTestRef != 0 || id.stencilTestFunc != 0) { desc = "INVALID:" + desc; } @@ -326,13 +343,24 @@ std::string DescribePixelFuncID(const PixelFuncID &id) { case GE_STENCILOP_INCR: desc += "ZTstFInc:"; break; case GE_STENCILOP_DECR: desc += "ZTstFDec:"; break; } - switch (id.ZPass()) { - case GE_STENCILOP_KEEP: break; - case GE_STENCILOP_ZERO: desc += "ZTstT0:"; break; - case GE_STENCILOP_REPLACE: desc += "ZTstTRpl:"; break; - case GE_STENCILOP_INVERT: desc += "ZTstTXor:"; break; - case GE_STENCILOP_INCR: desc += "ZTstTInc:"; break; - case GE_STENCILOP_DECR: desc += "ZTstTDec:"; break; + if (id.StencilTestFunc() == GE_COMP_ALWAYS && id.DepthTestFunc() == GE_COMP_ALWAYS) { + switch (id.ZPass()) { + case GE_STENCILOP_KEEP: break; + case GE_STENCILOP_ZERO: desc += "Zero:"; break; + case GE_STENCILOP_REPLACE: desc += StringFromFormat("Rpl%02X:", id.stencilTestRef); break; + case GE_STENCILOP_INVERT: desc += "Xor:"; break; + case GE_STENCILOP_INCR: desc += "Inc:"; break; + case GE_STENCILOP_DECR: desc += "Dec:"; break; + } + } else { + switch (id.ZPass()) { + case GE_STENCILOP_KEEP: break; + case GE_STENCILOP_ZERO: desc += "ZTstT0:"; break; + case GE_STENCILOP_REPLACE: desc += "ZTstTRpl:"; break; + case GE_STENCILOP_INVERT: desc += "ZTstTXor:"; break; + case GE_STENCILOP_INCR: desc += "ZTstTInc:"; break; + case GE_STENCILOP_DECR: desc += "ZTstTDec:"; break; + } } if (!id.stencilTest || id.clearMode) { if (id.sFail != 0 || id.zFail != 0 || id.zPass != 0) diff --git a/GPU/Software/FuncId.h b/GPU/Software/FuncId.h index f847522e25..46307fc55c 100644 --- a/GPU/Software/FuncId.h +++ b/GPU/Software/FuncId.h @@ -107,7 +107,8 @@ struct PixelFuncID { uint8_t sFail : 3; uint8_t zFail : 3; uint8_t zPass : 3; - // 60 bits, 4 free. + bool earlyZChecks : 1; + // 61 bits, 3 free. }; }; @@ -243,7 +244,7 @@ struct hash { }; -void ComputePixelFuncID(PixelFuncID *id); +void ComputePixelFuncID(PixelFuncID *id, bool throughMode); std::string DescribePixelFuncID(const PixelFuncID &id); void ComputeSamplerID(SamplerID *id); diff --git a/GPU/Software/Lighting.cpp b/GPU/Software/Lighting.cpp index 262811318f..32596989fe 100644 --- a/GPU/Software/Lighting.cpp +++ b/GPU/Software/Lighting.cpp @@ -276,12 +276,12 @@ void Process(VertexData &vertex, const WorldCoords &worldpos, const WorldCoords } if (state.setColor1) { - vertex.color0 = final_color.Clamp(0, 255); - vertex.color1 = specular_color.Clamp(0, 255).rgb(); + vertex.color0 = final_color.Clamp(0, 255).ToRGBA(); + vertex.color1 = specular_color.Clamp(0, 255).rgb().ToRGB(); } else if (state.addColor1) { - vertex.color0 = (final_color + specular_color).Clamp(0, 255); + vertex.color0 = (final_color + specular_color).Clamp(0, 255).ToRGBA(); } else { - vertex.color0 = final_color.Clamp(0, 255); + vertex.color0 = final_color.Clamp(0, 255).ToRGBA(); } } diff --git a/GPU/Software/Rasterizer.cpp b/GPU/Software/Rasterizer.cpp index 48e51cd9b2..a47ed9b0da 100644 --- a/GPU/Software/Rasterizer.cpp +++ b/GPU/Software/Rasterizer.cpp @@ -101,8 +101,8 @@ static inline Vec4 Interpolate(const float &c0, const float &c1, const fl return Interpolate(c0, c1, c2, w0.Cast(), w1.Cast(), w2.Cast(), wsum_recip); } -void ComputeRasterizerState(RasterizerState *state) { - ComputePixelFuncID(&state->pixelID); +void ComputeRasterizerState(RasterizerState *state, bool throughMode) { + ComputePixelFuncID(&state->pixelID, throughMode); state->drawPixel = Rasterizer::GetSingleFunc(state->pixelID); state->enableTextures = gstate.isTextureMapEnabled() && !state->pixelID.clearMode; @@ -140,7 +140,7 @@ void ComputeRasterizerState(RasterizerState *state) { } state->shadeGouraud = gstate.getShadeMode() == GE_SHADE_GOURAUD; - state->throughMode = gstate.isModeThrough(); + state->throughMode = throughMode; state->antialiasLines = gstate.isAntiAliasEnabled(); state->screenOffsetX = gstate.getOffsetX16(); @@ -348,7 +348,7 @@ Vec3 AlphaBlendingResult(const PixelFuncID &pixelID, const Vec4 &sourc return Vec3(_mm_unpacklo_epi16(_mm_adds_epi16(s, d), _mm_setzero_si128())); #else - Vec3 half = Vec3::AssignToAll(1); + static constexpr Vec3 half = Vec3::AssignToAll(1); Vec3 lhs = ((source.rgb() * 2 + half) * (srcfactor * 2 + half)) / 1024; Vec3 rhs = ((dst.rgb() * 2 + half) * (dstfactor * 2 + half)) / 1024; return lhs + rhs; @@ -370,7 +370,7 @@ Vec3 AlphaBlendingResult(const PixelFuncID &pixelID, const Vec4 &sourc return Vec3(_mm_unpacklo_epi16(_mm_max_epi16(_mm_subs_epi16(s, d), _mm_setzero_si128()), _mm_setzero_si128())); #else - Vec3 half = Vec3::AssignToAll(1); + static constexpr Vec3 half = Vec3::AssignToAll(1); Vec3 lhs = ((source.rgb() * 2 + half) * (srcfactor * 2 + half)) / 1024; Vec3 rhs = ((dst.rgb() * 2 + half) * (dstfactor * 2 + half)) / 1024; return lhs - rhs; @@ -392,7 +392,7 @@ Vec3 AlphaBlendingResult(const PixelFuncID &pixelID, const Vec4 &sourc return Vec3(_mm_unpacklo_epi16(_mm_max_epi16(_mm_subs_epi16(d, s), _mm_setzero_si128()), _mm_setzero_si128())); #else - Vec3 half = Vec3::AssignToAll(1); + static constexpr Vec3 half = Vec3::AssignToAll(1); Vec3 lhs = ((source.rgb() * 2 + half) * (srcfactor * 2 + half)) / 1024; Vec3 rhs = ((dst.rgb() * 2 + half) * (dstfactor * 2 + half)) / 1024; return rhs - lhs; @@ -710,12 +710,24 @@ void DrawTriangleSlice( const bool flatColor1 = flatColorAll || (v0.color1 == v1.color1 && v0.color1 == v2.color1); const bool noFog = clearMode || !pixelID.applyFog || (v0.fogdepth >= 1.0f && v1.fogdepth >= 1.0f && v2.fogdepth >= 1.0f); + if (pixelID.applyDepthRange && flatZ) { + if (v0.screenpos.z < pixelID.cached.minz || v0.screenpos.z > pixelID.cached.maxz) + return; + } + #if defined(SOFTGPU_MEMORY_TAGGING_DETAILED) || defined(SOFTGPU_MEMORY_TAGGING_BASIC) uint32_t bpp = pixelID.FBFormat() == GE_FORMAT_8888 ? 4 : 2; std::string tag = StringFromFormat("DisplayListT_%08x", state.listPC); std::string ztag = StringFromFormat("DisplayListTZ_%08x", state.listPC); #endif + const Vec4 v0_c0 = Vec4::FromRGBA(v0.color0); + const Vec4 v1_c0 = Vec4::FromRGBA(v1.color0); + const Vec4 v2_c0 = Vec4::FromRGBA(v2.color0); + const Vec3 v0_c1 = Vec3::FromRGB(v0.color1); + const Vec3 v1_c1 = Vec3::FromRGB(v1.color1); + const Vec3 v2_c1 = Vec3::FromRGB(v2.color1); + for (int64_t curY = minY; curY <= maxY; curY += SCREEN_SCALE_FACTOR * 2, w0_base = e0.StepY(w0_base), w1_base = e1.StepY(w1_base), @@ -754,27 +766,53 @@ void DrawTriangleSlice( if (AnyMask(mask)) { Vec4 wsum_recip = EdgeRecip(w0, w1, w2); + Vec4 z; + if (flatZ) { + z = Vec4::AssignToAll(v2.screenpos.z); + } else { + // Z is interpolated pretty much directly. + Vec4 zfloats = w0.Cast() * v0.screenpos.z + w1.Cast() * v1.screenpos.z + w2.Cast() * v2.screenpos.z; + z = (zfloats * wsum_recip).Cast(); + } + + if (pixelID.earlyZChecks) { + for (int i = 0; i < 4; ++i) { + if (pixelID.applyDepthRange) { + if (z[i] < pixelID.cached.minz || z[i] > pixelID.cached.maxz) + mask[i] = -1; + } + if (mask[i] < 0) + continue; + + int x = p.x + (i & 1); + int y = p.y + (i / 2); + if (!CheckDepthTestPassed(pixelID.DepthTestFunc(), x, y, pixelID.cached.depthbufStride, z[i])) { + mask[i] = -1; + } + } + } + // Color interpolation is not perspective corrected on the PSP. Vec4 prim_color[4]; if (!flatColor0) { for (int i = 0; i < 4; ++i) { if (mask[i] >= 0) - prim_color[i] = Interpolate(v0.color0, v1.color0, v2.color0, w0[i], w1[i], w2[i], wsum_recip[i]); + prim_color[i] = Interpolate(v0_c0, v1_c0, v2_c0, w0[i], w1[i], w2[i], wsum_recip[i]); } } else { for (int i = 0; i < 4; ++i) { - prim_color[i] = v2.color0; + prim_color[i] = v2_c0; } } Vec3 sec_color[4]; if (!flatColor1) { for (int i = 0; i < 4; ++i) { if (mask[i] >= 0) - sec_color[i] = Interpolate(v0.color1, v1.color1, v2.color1, w0[i], w1[i], w2[i], wsum_recip[i]); + sec_color[i] = Interpolate(v0_c1, v1_c1, v2_c1, w0[i], w1[i], w2[i], wsum_recip[i]); } } else { for (int i = 0; i < 4; ++i) { - sec_color[i] = v2.color1; + sec_color[i] = v2_c1; } } @@ -816,15 +854,6 @@ void DrawTriangleSlice( } } - Vec4 z; - if (flatZ) { - z = Vec4::AssignToAll(v2.screenpos.z); - } else { - // Z is interpolated pretty much directly. - Vec4 zfloats = w0.Cast() * v0.screenpos.z + w1.Cast() * v1.screenpos.z + w2.Cast() * v2.screenpos.z; - z = (zfloats * wsum_recip).Cast(); - } - PROFILE_THIS_SCOPE("draw_tri_px"); DrawingCoords subp = p; for (int i = 0; i < 4; ++i) { @@ -943,9 +972,16 @@ void DrawRectangle(const VertexData &v0, const VertexData &v1, const BinCoords & const Vec4f tto4(0.0f, 0.5f * stx.t(), 0.5f * sty.t(), 0.5f * stx.t() + 0.5f * sty.t()); ScreenCoords pprime(minX, minY, 0); - Vec4 fog = Vec4::AssignToAll(ClampFogDepth(v1.fogdepth)); - Vec4 z = Vec4::AssignToAll(v1.screenpos.z); - Vec3 sec_color = v1.color1; + const Vec4 fog = Vec4::AssignToAll(ClampFogDepth(v1.fogdepth)); + const Vec4 z = Vec4::AssignToAll(v1.screenpos.z); + const Vec4 c0 = Vec4::FromRGBA(v1.color0); + const Vec3 sec_color = Vec3::FromRGB(v1.color1); + + if (state.pixelID.applyDepthRange) { + // We can bail early since the Z is flat. + if (v1.screenpos.z < state.pixelID.cached.minz || v1.screenpos.z > state.pixelID.cached.maxz) + return; + } #if defined(SOFTGPU_MEMORY_TAGGING_DETAILED) || defined(SOFTGPU_MEMORY_TAGGING_BASIC) uint32_t bpp = state.pixelID.FBFormat() == GE_FORMAT_8888 ? 4 : 2; @@ -969,7 +1005,20 @@ void DrawRectangle(const VertexData &v0, const VertexData &v1, const BinCoords & Vec4 prim_color[4]; for (int i = 0; i < 4; ++i) { - prim_color[i] = v1.color0; + prim_color[i] = c0; + } + + if (state.pixelID.earlyZChecks) { + for (int i = 0; i < 4; ++i) { + if (mask[i] < 0) + continue; + + int x = p.x + (i & 1); + int y = p.y + (i / 2); + if (!CheckDepthTestPassed(state.pixelID.DepthTestFunc(), x, y, state.pixelID.cached.depthbufStride, z[i])) { + mask[i] = -1; + } + } } if (state.enableTextures) { @@ -1032,12 +1081,26 @@ void DrawRectangle(const VertexData &v0, const VertexData &v1, const BinCoords & void DrawPoint(const VertexData &v0, const BinCoords &range, const RasterizerState &state) { ScreenCoords pos = v0.screenpos; - Vec4 prim_color = v0.color0; - Vec3 sec_color = v0.color1; + Vec4 prim_color = Vec4::FromRGBA(v0.color0); + Vec3 sec_color = Vec3::FromRGB(v0.color1); auto &pixelID = state.pixelID; auto &samplerID = state.samplerID; + DrawingCoords p = TransformUnit::ScreenToDrawing(pos); + u16 z = pos.z; + + if (pixelID.earlyZChecks) { + if (pixelID.applyDepthRange) { + if (z < pixelID.cached.minz || z > pixelID.cached.maxz) + return; + } + + if (!CheckDepthTestPassed(pixelID.DepthTestFunc(), p.x, p.y, pixelID.cached.depthbufStride, z)) { + return; + } + } + if (state.enableTextures) { float s = v0.texturecoords.s(); float t = v0.texturecoords.t(); @@ -1060,9 +1123,6 @@ void DrawPoint(const VertexData &v0, const BinCoords &range, const RasterizerSta if (!pixelID.clearMode) prim_color += Vec4(sec_color, 0); - DrawingCoords p = TransformUnit::ScreenToDrawing(pos); - u16 z = pos.z; - u8 fog = 255; if (pixelID.applyFog) { fog = ClampFogDepth(v0.fogdepth); @@ -1166,7 +1226,7 @@ void ClearRectangle(const VertexData &v0, const VertexData &v1, const BinCoords keepOldMask |= pixelID.cached.colorWriteMask; } - const u32 new_color = v1.color0.ToRGBA(); + const u32 new_color = v1.color0; u16 new_color16; switch (pixelID.FBFormat()) { case GE_FORMAT_565: @@ -1291,6 +1351,10 @@ void DrawLine(const VertexData &v0, const VertexData &v1, const BinCoords &range auto &samplerID = state.samplerID; const bool interpolateColor = !state.shadeGouraud || (v0.color0 == v1.color0 && v0.color1 == v1.color1); + const Vec4 v0_c0 = Vec4::FromRGBA(v0.color0); + const Vec4 v1_c0 = Vec4::FromRGBA(v1.color0); + const Vec3 v0_c1 = Vec3::FromRGB(v0.color1); + const Vec3 v1_c1 = Vec3::FromRGB(v1.color1); #if defined(SOFTGPU_MEMORY_TAGGING_DETAILED) || defined(SOFTGPU_MEMORY_TAGGING_BASIC) std::string tag = StringFromFormat("DisplayListL_%08x", state.listPC); @@ -1302,16 +1366,32 @@ void DrawLine(const VertexData &v0, const VertexData &v1, const BinCoords &range double z = a.z; const int steps1 = steps == 0 ? 1 : steps; for (int i = 0; i < steps; i++) { - if (x >= range.x1 && y >= range.y1 && x <= range.x2 && y <= range.y2) { + DrawingCoords p = TransformUnit::ScreenToDrawing(x, y); + + bool maskOK = x >= range.x1 && y >= range.y1 && x <= range.x2 && y <= range.y2; + if (maskOK) { + if (pixelID.earlyZChecks) { + if (pixelID.applyDepthRange) { + if (z < pixelID.cached.minz || z > pixelID.cached.maxz) + maskOK = false; + } + + if (!CheckDepthTestPassed(pixelID.DepthTestFunc(), x, y, pixelID.cached.depthbufStride, z)) { + maskOK = false; + } + } + } + + if (maskOK) { // Interpolate between the two points. Vec4 prim_color; Vec3 sec_color; if (interpolateColor) { - prim_color = (v0.color0 * (steps - i) + v1.color0 * i) / steps1; - sec_color = (v0.color1 * (steps - i) + v1.color1 * i) / steps1; + prim_color = (v0_c0 * (steps - i) + v1_c0 * i) / steps1; + sec_color = (v0_c1 * (steps - i) + v1_c1 * i) / steps1; } else { - prim_color = v1.color0; - sec_color = v1.color1; + prim_color = v1_c0; + sec_color = v1_c1; } u8 fog = 255; @@ -1368,7 +1448,6 @@ void DrawLine(const VertexData &v0, const VertexData &v1, const BinCoords &range prim_color += Vec4(sec_color, 0); PROFILE_THIS_SCOPE("draw_px"); - DrawingCoords p = TransformUnit::ScreenToDrawing(x, y); state.drawPixel(p.x, p.y, z, fog, ToVec4IntArg(prim_color), pixelID); #if defined(SOFTGPU_MEMORY_TAGGING_DETAILED) || defined(SOFTGPU_MEMORY_TAGGING_BASIC) @@ -1401,7 +1480,11 @@ bool GetCurrentTexture(GPUDebugBuffer &buffer, int level) int w = gstate.getTextureWidth(level); int h = gstate.getTextureHeight(level); - if (!texaddr || !Memory::IsValidRange(texaddr, (textureBitsPerPixel[texfmt] * texbufw * h) / 8)) + u32 sizeInBits = textureBitsPerPixel[texfmt] * (texbufw * (h - 1) + w); + if (!texaddr || !Memory::IsValidRange(texaddr, sizeInBits / 8)) + return false; + // We'll break trying to allocate this much. + if (w >= 0x8000 && h >= 0x8000) return false; buffer.Allocate(w, h, GE_FORMAT_8888, false); diff --git a/GPU/Software/Rasterizer.h b/GPU/Software/Rasterizer.h index 2725bb922e..36236f5500 100644 --- a/GPU/Software/Rasterizer.h +++ b/GPU/Software/Rasterizer.h @@ -67,7 +67,7 @@ struct RasterizerState { } }; -void ComputeRasterizerState(RasterizerState *state); +void ComputeRasterizerState(RasterizerState *state, bool throughMode); // Draws a triangle if its vertices are specified in counter-clockwise order void DrawTriangle(const VertexData &v0, const VertexData &v1, const VertexData &v2, const BinCoords &range, const RasterizerState &state); diff --git a/GPU/Software/RasterizerRectangle.cpp b/GPU/Software/RasterizerRectangle.cpp index 96e7a7f0fd..71cef64647 100644 --- a/GPU/Software/RasterizerRectangle.cpp +++ b/GPU/Software/RasterizerRectangle.cpp @@ -119,7 +119,7 @@ void DrawSprite(const VertexData &v0, const VertexData &v1, const BinCoords &ran int z = v1.screenpos.z; int fog = 255; - bool isWhite = v1.color0 == Vec4(255, 255, 255, 255); + bool isWhite = v1.color0 == 0xFFFFFFFF; if (state.enableTextures) { // 1:1 (but with mirror support) texture mapping! @@ -176,11 +176,12 @@ void DrawSprite(const VertexData &v0, const VertexData &v1, const BinCoords &ran } } else { int t = t_start; + const Vec4 c0 = Vec4::FromRGBA(v1.color0); for (int y = pos0.y; y < pos1.y; y++) { int s = s_start; u16 *pixel = fb.Get16Ptr(pos0.x, y, pixelID.cached.framebufStride); for (int x = pos0.x; x < pos1.x; x++) { - Vec4 prim_color = v1.color0; + Vec4 prim_color = c0; Vec4 tex_color = fetchFunc(s, t, texptr, texbufw, 0, state.samplerID); prim_color = Vec4(ModulateRGBA(ToVec4IntArg(prim_color), ToVec4IntArg(tex_color), state.samplerID)); if (prim_color.a() > 0) { @@ -202,11 +203,12 @@ void DrawSprite(const VertexData &v0, const VertexData &v1, const BinCoords &ran float tf_start = t_start * (1.0f / (float)(1 << state.samplerID.height0Shift)); float t = tf_start; + const Vec4 c0 = Vec4::FromRGBA(v1.color0); for (int y = pos0.y; y < pos1.y; y++) { float s = sf_start; // Not really that fast but faster than triangle. for (int x = pos0.x; x < pos1.x; x++) { - Vec4 prim_color = state.nearest(s, t, xoff, yoff, ToVec4IntArg(v1.color0), &texptr, &texbufw, 0, 0, state.samplerID); + Vec4 prim_color = state.nearest(s, t, xoff, yoff, ToVec4IntArg(c0), &texptr, &texbufw, 0, 0, state.samplerID); state.drawPixel(x, y, z, 255, ToVec4IntArg(prim_color), pixelID); s += dsf; } @@ -227,21 +229,20 @@ void DrawSprite(const VertexData &v0, const VertexData &v1, const BinCoords &ran AlphaTestIsNeedless(pixelID) && !pixelID.applyColorWriteMask && pixelID.FBFormat() == GE_FORMAT_5551) { - if (v1.color0.a() == 0) + if (Vec4::FromRGBA(v1.color0).a() == 0) return; for (int y = pos0.y; y < pos1.y; y++) { u16 *pixel = fb.Get16Ptr(pos0.x, y, pixelID.cached.framebufStride); for (int x = pos0.x; x < pos1.x; x++) { - Vec4 prim_color = v1.color0; - DrawSinglePixel5551(pixel, prim_color.ToRGBA(), pixelID); + DrawSinglePixel5551(pixel, v1.color0, pixelID); pixel++; } } } else { + const Vec4 prim_color = Vec4::FromRGBA(v1.color0); for (int y = pos0.y; y < pos1.y; y++) { for (int x = pos0.x; x < pos1.x; x++) { - Vec4 prim_color = v1.color0; state.drawPixel(x, y, z, fog, ToVec4IntArg(prim_color), pixelID); } } @@ -265,6 +266,8 @@ bool g_needsClearAfterDialog = false; static inline bool NoClampOrWrap(const RasterizerState &state, const Vec2f &tc) { if (tc.x < 0 || tc.y < 0) return false; + if (state.samplerID.cached.sizes[0].w > 512 || state.samplerID.cached.sizes[0].h > 512) + return false; return tc.x <= state.samplerID.cached.sizes[0].w && tc.y <= state.samplerID.cached.sizes[0].h; } @@ -284,9 +287,9 @@ bool RectangleFastPath(const VertexData &v0, const VertexData &v1, BinManager &b // Currently only works for TL/BR, which is the most common but not required. bool orient_check = xdiff >= 0 && ydiff >= 0; // We already have a fast path for clear in ClearRectangle. - bool state_check = !state.pixelID.clearMode && !state.samplerID.hasAnyMips && NoClampOrWrap(state, v0.texturecoords) && NoClampOrWrap(state, v1.texturecoords); + bool state_check = state.throughMode && !state.pixelID.clearMode && !state.samplerID.hasAnyMips && NoClampOrWrap(state, v0.texturecoords) && NoClampOrWrap(state, v1.texturecoords); // This doesn't work well with offset drawing, see #15876. Through never has a subpixel offset. - bool subpixel_check = ((v0.screenpos.x | v0.screenpos.y | v1.screenpos.x | v1.screenpos.y) & 0xF) != 0; + bool subpixel_check = ((v0.screenpos.x | v0.screenpos.y | v1.screenpos.x | v1.screenpos.y) & 0xF) == 0; if ((coord_check || !state.enableTextures) && orient_check && state_check && subpixel_check) { binner.AddSprite(v0, v1); return true; @@ -309,7 +312,7 @@ bool RectangleFastPath(const VertexData &v0, const VertexData &v1, BinManager &b // Afterwards, we also need to clear the actual destination. Can do a fast rectfill. gstate.textureMapEnable &= ~1; VertexData newV1 = v1; - newV1.color0 = Vec4(0, 0, 0, 255); + newV1.color0 = 0xFF000000; binner.AddSprite(v0, newV1); gstate.textureMapEnable |= 1; } @@ -321,26 +324,40 @@ bool RectangleFastPath(const VertexData &v0, const VertexData &v1, BinManager &b return false; } +static bool AreCoordsRectangleCompatible(const RasterizerState &state, const VertexData &data0, const VertexData &data1) { + if (!(data1.color0 == data0.color0)) + return false; + if (!(data1.screenpos.z == data0.screenpos.z)) { + // Sometimes, we don't actually care about z. + if (state.pixelID.depthWrite || state.pixelID.DepthTestFunc() != GE_COMP_ALWAYS) + return false; + } + if (!state.throughMode) { + if (!state.throughMode && !(data1.color1 == data0.color1)) + return false; + // Do we have to think about perspective correction or slope mip level? + if (state.enableTextures && data1.clippos.w != data0.clippos.w) { + // If the w is off by less than a factor of 1/512, it should be safe to treat as a rectangle. + static constexpr float halftexel = 0.5f / 512.0f; + if (data1.clippos.w - halftexel > data0.clippos.w || data1.clippos.w + halftexel < data0.clippos.w) + return false; + } + if (state.pixelID.applyFog && data1.fogdepth != data0.fogdepth) { + // Similar to w, this only matters if they're farther apart than 1/255. + static constexpr float foghalfstep = 0.5f / 255.0f; + if (data1.fogdepth - foghalfstep > data0.fogdepth || data1.fogdepth + foghalfstep < data0.fogdepth) + return false; + } + } + return true; +} + bool DetectRectangleFromStrip(const RasterizerState &state, const VertexData data[4], int *tlIndex, int *brIndex) { // Color and Z must be flat. Also find the TL and BR meanwhile. int tl = 0, br = 0; for (int i = 1; i < 4; ++i) { - if (!(data[i].color0 == data[0].color0)) + if (!AreCoordsRectangleCompatible(state, data[i], data[0])) return false; - if (!(data[i].screenpos.z == data[0].screenpos.z)) { - // Sometimes, we don't actually care about z. - if (state.pixelID.depthWrite || state.pixelID.DepthTestFunc() != GE_COMP_ALWAYS) - return false; - } - if (!state.throughMode) { - if (!state.throughMode && !(data[i].color1 == data[0].color1)) - return false; - // Do we have to think about perspective correction or slope mip level? - if (state.enableTextures && data[i].clippos.w != data[0].clippos.w) - return false; - if (state.pixelID.applyFog && data[i].fogdepth != data[0].fogdepth) - return false; - } if (data[i].screenpos.x <= data[tl].screenpos.x && data[i].screenpos.y <= data[tl].screenpos.y) tl = i; @@ -394,34 +411,20 @@ bool DetectRectangleFromStrip(const RasterizerState &state, const VertexData dat bool DetectRectangleFromFan(const RasterizerState &state, const VertexData *data, int c, int *tlIndex, int *brIndex) { // Color and Z must be flat. for (int i = 1; i < c; ++i) { - if (!(data[i].color0 == data[0].color0)) + if (!AreCoordsRectangleCompatible(state, data[i], data[0])) return false; - if (!(data[i].screenpos.z == data[0].screenpos.z)) { - // Sometimes, we don't actually care about z. - if (state.pixelID.depthWrite || state.pixelID.DepthTestFunc() != GE_COMP_ALWAYS) - return false; - } - if (!state.throughMode) { - if (!state.throughMode && !(data[i].color1 == data[0].color1)) - return false; - // Do we have to think about perspective correction or slope mip level? - if (state.enableTextures && data[i].clippos.w != data[0].clippos.w) - return false; - if (state.pixelID.applyFog && data[i].fogdepth != data[0].fogdepth) - return false; - } } // Check for the common case: a single TL-TR-BR-BL. if (c == 4) { - const auto &tl = data[0].screenpos, &tr = data[1].screenpos; - const auto &bl = data[3].screenpos, &br = data[2].screenpos; - if (tl.x == bl.x && tr.x == br.x && tl.y == tr.y && bl.y == br.y) { + const auto &pos0 = data[0].screenpos, &pos1 = data[1].screenpos; + const auto &pos2 = data[2].screenpos, &pos3 = data[3].screenpos; + if (pos0.x == pos3.x && pos1.x == pos2.x && pos0.y == pos1.y && pos3.y == pos2.y) { // Looking like yes. Set TL/BR based on y order first... - *tlIndex = tl.y > bl.y ? 2 : 0; - *brIndex = tl.y > bl.y ? 0 : 2; + *tlIndex = pos0.y > pos3.y ? 2 : 0; + *brIndex = pos0.y > pos3.y ? 0 : 2; // And if it's horizontally flipped, trade to the actual TL/BR. - if (tl.x > tr.x) { + if (pos0.x > pos1.x) { *tlIndex ^= 1; *brIndex ^= 1; } @@ -435,7 +438,56 @@ bool DetectRectangleFromFan(const RasterizerState &state, const VertexData *data if (textl.x == texbl.x && textr.x == texbr.x && textl.y == textr.y && texbl.y == texbr.y) { // Okay, the texture is also good, but let's avoid rotation issues. - return textl.y < texbr.y && textl.x < texbr.x; + const auto &postl = data[*tlIndex].screenpos; + const auto &posbr = data[*brIndex].screenpos; + return textl.y < texbr.y && postl.y < posbr.y && textl.x < texbr.x && postl.x < posbr.x; + } + } + } + + return false; +} + +bool DetectRectangleFromPair(const RasterizerState &state, const VertexData data[6], int *tlIndex, int *brIndex) { + // Color and Z must be flat. Also find the TL and BR meanwhile. + int tl = 0, br = 0; + for (int i = 1; i < 6; ++i) { + if (!AreCoordsRectangleCompatible(state, data[i], data[0])) + return false; + + if (data[i].screenpos.x <= data[tl].screenpos.x && data[i].screenpos.y <= data[tl].screenpos.y) + tl = i; + if (data[i].screenpos.x >= data[br].screenpos.x && data[i].screenpos.y >= data[br].screenpos.y) + br = i; + } + + *tlIndex = tl; + *brIndex = br; + + auto xat = [&](int i) { return data[i].screenpos.x; }; + auto yat = [&](int i) { return data[i].screenpos.y; }; + auto uat = [&](int i) { return data[i].texturecoords.x; }; + auto vat = [&](int i) { return data[i].texturecoords.y; }; + + // A likely order would be: TL, TR, BR, TL, BR, BL. We'd have the last index of each. + // TODO: Make more generic. + if (tl == 3 && br == 4) { + bool x1_match = xat(0) == xat(3) && xat(0) == xat(5); + bool x2_match = xat(1) == xat(2) && xat(1) == xat(4); + bool y1_match = yat(0) == yat(1) && yat(0) == yat(3); + bool y2_match = yat(2) == yat(4) && yat(2) == yat(5); + if (x1_match && y1_match && x2_match && y2_match) { + // Do we need to think about rotation or UVs? + if (!state.enableTextures) + return true; + + x1_match = uat(0) == uat(3) && uat(0) == uat(5); + x2_match = uat(1) == uat(2) && uat(1) == uat(4); + y1_match = vat(0) == vat(1) && vat(0) == vat(3); + y2_match = vat(2) == vat(4) && vat(2) == vat(5); + if (x1_match && y1_match && x2_match && y2_match) { + // Double check rotation direction. + return vat(tl) < vat(br) && yat(tl) < yat(br) && uat(tl) < uat(br) && xat(tl) < xat(br); } } } diff --git a/GPU/Software/RasterizerRectangle.h b/GPU/Software/RasterizerRectangle.h index 4407b10a01..6842215338 100644 --- a/GPU/Software/RasterizerRectangle.h +++ b/GPU/Software/RasterizerRectangle.h @@ -22,5 +22,6 @@ namespace Rasterizer { bool DetectRectangleFromStrip(const RasterizerState &state, const VertexData data[4], int *tlIndex, int *brIndex); bool DetectRectangleFromFan(const RasterizerState &state, const VertexData *data, int c, int *tlIndex, int *brIndex); + bool DetectRectangleFromPair(const RasterizerState &state, const VertexData data[6], int *tlIndex, int *brIndex); bool DetectRectangleThroughModeSlices(const RasterizerState &state, const VertexData data[4]); } diff --git a/GPU/Software/Sampler.cpp b/GPU/Software/Sampler.cpp index 8aad116b14..8c55e15760 100644 --- a/GPU/Software/Sampler.cpp +++ b/GPU/Software/Sampler.cpp @@ -383,13 +383,15 @@ inline static Nearest4 SOFTRAST_CALL SampleNearest(const int u[N], const int v[N static inline int ClampUV(int v, int height) { if (v >= height - 1) return height - 1; + if (v >= 511) + return 511; else if (v < 0) return 0; return v; } static inline int WrapUV(int v, int height) { - return v & (height - 1); + return v & (height - 1) & 511; } template diff --git a/GPU/Software/Sampler.h b/GPU/Software/Sampler.h index e663004cbf..2379c5edfb 100644 --- a/GPU/Software/Sampler.h +++ b/GPU/Software/Sampler.h @@ -114,6 +114,7 @@ private: const u8 *constVNext_ = nullptr; const u8 *constOnes32_ = nullptr; const u8 *constOnes16_ = nullptr; + const u8 *constMaxTexel32_ = nullptr; const u8 *const10All16_ = nullptr; const u8 *const10Low_ = nullptr; const u8 *const10All8_ = nullptr; diff --git a/GPU/Software/SamplerX86.cpp b/GPU/Software/SamplerX86.cpp index 415eed2723..932c6d1a62 100644 --- a/GPU/Software/SamplerX86.cpp +++ b/GPU/Software/SamplerX86.cpp @@ -903,6 +903,8 @@ void SamplerJitCache::WriteConstantPool(const SamplerID &id) { WriteSimpleConst4x32(constOnes32_, 1); WriteSimpleConst8x16(constOnes16_, 1); + // This is the mask for clamp or wrap, the max texel in the S or T direction. + WriteSimpleConst4x32(constMaxTexel32_, 511); if (constUNext_ == nullptr) { constUNext_ = AlignCode16(); @@ -927,8 +929,8 @@ void SamplerJitCache::WriteConstantPool(const SamplerID &id) { Write32(*(uint32_t *)&w256f); Write32(*(uint32_t *)&h256f); - WriteDynamicConst4x32(constWidthMinus1i_, (1 << id.width0Shift) - 1); - WriteDynamicConst4x32(constHeightMinus1i_, (1 << id.height0Shift) - 1); + WriteDynamicConst4x32(constWidthMinus1i_, id.width0Shift > 9 ? 511 : (1 << id.width0Shift) - 1); + WriteDynamicConst4x32(constHeightMinus1i_, id.height0Shift > 9 ? 511 : (1 << id.height0Shift) - 1); } else { constWidthHeight256f_ = nullptr; constWidthMinus1i_ = nullptr; @@ -2651,6 +2653,7 @@ bool SamplerJitCache::Jit_GetTexelCoords(const SamplerID &id) { } SUB(32, R(tempReg), Imm8(1)); + AND(32, R(tempReg), Imm32(0x000001FF)); if (clamp) { CMP(32, R(dest), R(tempReg)); CMOVcc(32, dest, R(tempReg), CC_G); @@ -2710,6 +2713,10 @@ bool SamplerJitCache::Jit_GetTexelCoords(const SamplerID &id) { AND(32, R(uReg), R(uReg)); auto applyClampWrap = [this](X64Reg dest, bool clamp, uint8_t shift) { + // Clamp and wrap both max out at 512. + if (shift > 9) + shift = 9; + if (clamp) { X64Reg tempReg = regCache_.Alloc(RegCache::GEN_TEMP0); MOV(32, R(tempReg), Imm32((1 << shift) - 1)); @@ -2802,6 +2809,7 @@ bool SamplerJitCache::Jit_GetTexelCoordsQuad(const SamplerID &id) { // For wrap/clamp purposes, we want width or height minus one. Do that now. PSUBD(sizesReg, M(constOnes32_)); + PAND(sizesReg, M(constMaxTexel32_)); } else { // Easy mode. UNPCKLPS(sReg, R(tReg)); diff --git a/GPU/Software/SoftGpu.cpp b/GPU/Software/SoftGpu.cpp index 8c26eac9b1..18cdb0b314 100644 --- a/GPU/Software/SoftGpu.cpp +++ b/GPU/Software/SoftGpu.cpp @@ -831,13 +831,14 @@ void SoftGPU::Execute_Prim(u32 op, u32 diff) { GEPrimitiveType prim = static_cast((op >> 16) & 7); if (count == 0) return; + FlushImm(); if (!Memory::IsValidAddress(gstate_c.vertexAddr)) { ERROR_LOG_REPORT(G3D, "Software: Bad vertex address %08x!", gstate_c.vertexAddr); return; } - const void *verts = Memory::GetPointer(gstate_c.vertexAddr); + const void *verts = Memory::GetPointerUnchecked(gstate_c.vertexAddr); const void *indices = NULL; if ((gstate.vertType & GE_VTYPE_IDX_MASK) != GE_VTYPE_IDX_NONE) { if (!Memory::IsValidAddress(gstate_c.indexAddr)) { @@ -1033,57 +1034,79 @@ void SoftGPU::Execute_VertexType(u32 op, u32 diff) { void SoftGPU::Execute_WorldMtxData(u32 op, u32 diff) { int num = gstate.worldmtxnum & 0xF; + u32 *target = num < 12 ? (u32 *)&gstate.worldMatrix[num] : (u32 *)&gstate.viewMatrix[num - 12]; u32 newVal = op << 8; - if (num < 12 && newVal != ((const u32 *)gstate.worldMatrix)[num]) { - ((u32 *)gstate.worldMatrix)[num] = newVal; + if (newVal != *target) { + *target = newVal; dirtyFlags_ |= SoftDirty::TRANSFORM_MATRIX; } num++; gstate.worldmtxnum = (GE_CMD_WORLDMATRIXNUMBER << 24) | (num & 0xF); + gstate.worldmtxdata = GE_CMD_WORLDMATRIXDATA << 24; } void SoftGPU::Execute_ViewMtxData(u32 op, u32 diff) { int num = gstate.viewmtxnum & 0xF; + u32 *target = num < 12 ? (u32 *)&gstate.viewMatrix[num] : (u32 *)&gstate.projMatrix[num - 12]; u32 newVal = op << 8; - if (num < 12 && newVal != ((const u32 *)gstate.viewMatrix)[num]) { - ((u32 *)gstate.viewMatrix)[num] = newVal; + if (newVal != *target) { + *target = newVal; dirtyFlags_ |= SoftDirty::TRANSFORM_MATRIX; } num++; gstate.viewmtxnum = (GE_CMD_VIEWMATRIXNUMBER << 24) | (num & 0xF); + gstate.viewmtxdata = GE_CMD_VIEWMATRIXDATA << 24; } void SoftGPU::Execute_ProjMtxData(u32 op, u32 diff) { - // NOTE: Changed from 0xF to catch overflows. - int num = gstate.projmtxnum & 0x1F; + int num = gstate.projmtxnum & 0xF; + u32 *target = (u32 *)&gstate.projMatrix[num]; u32 newVal = op << 8; - if (num < 0x10 && newVal != ((const u32 *)gstate.projMatrix)[num]) { - ((u32 *)gstate.projMatrix)[num] = newVal; + if (newVal != *target) { + *target = newVal; dirtyFlags_ |= SoftDirty::TRANSFORM_MATRIX; } num++; - if (num <= 16) - gstate.projmtxnum = (GE_CMD_PROJMATRIXNUMBER << 24) | (num & 0xF); + gstate.projmtxnum = (GE_CMD_PROJMATRIXNUMBER << 24) | (num & 0xF); + gstate.projmtxdata = GE_CMD_PROJMATRIXDATA << 24; } void SoftGPU::Execute_TgenMtxData(u32 op, u32 diff) { int num = gstate.texmtxnum & 0xF; u32 newVal = op << 8; + // Doesn't wrap to any other matrix. if (num < 12 && newVal != ((const u32 *)gstate.tgenMatrix)[num]) { ((u32 *)gstate.tgenMatrix)[num] = newVal; + // No dirtying, read during vertex read. } num++; gstate.texmtxnum = (GE_CMD_TGENMATRIXNUMBER << 24) | (num & 0xF); + gstate.texmtxdata = GE_CMD_TGENMATRIXDATA << 24; } void SoftGPU::Execute_BoneMtxData(u32 op, u32 diff) { int num = gstate.boneMatrixNumber & 0x7F; + u32 *target; + if (num < 96) { + target = (u32 *)&gstate.boneMatrix[num]; + } else if (num < 96 + 12) { + target = (u32 *)&gstate.worldMatrix[num - 96]; + } else if (num < 96 + 12 + 12) { + target = (u32 *)&gstate.viewMatrix[num - 96 - 12]; + } else { + target = (u32 *)&gstate.projMatrix[num - 96 - 12 - 12]; + } + u32 newVal = op << 8; - if (num < 96 && newVal != ((const u32 *)gstate.boneMatrix)[num]) { - ((u32 *)gstate.boneMatrix)[num] = newVal; + if (newVal != *target) { + *target = newVal; + // Dirty if it overflowed. We read bone data during vertex read. + if (num >= 96) + dirtyFlags_ |= SoftDirty::TRANSFORM_MATRIX; } num++; gstate.boneMatrixNumber = (GE_CMD_BONEMATRIXNUMBER << 24) | (num & 0x7F); + gstate.boneMatrixData = GE_CMD_BONEMATRIXDATA << 24; } void SoftGPU::Execute_Call(u32 op, u32 diff) { diff --git a/GPU/Software/TransformUnit.cpp b/GPU/Software/TransformUnit.cpp index db50f48bb6..0cb91dd280 100644 --- a/GPU/Software/TransformUnit.cpp +++ b/GPU/Software/TransformUnit.cpp @@ -71,10 +71,12 @@ void SoftwareDrawEngine::DispatchSubmitPrim(const void *verts, const void *inds, } void SoftwareDrawEngine::DispatchSubmitImm(const void *verts, const void *inds, GEPrimitiveType prim, int vertexCount, u32 vertTypeID, int cullMode, int *bytesRead) { - _assert_msg_(cullMode == gstate.getCullMode(), "Mixed cull mode not supported."); + int flipCull = cullMode != gstate.getCullMode() ? 1 : 0; // TODO: For now, just setting all dirty. transformUnit.SetDirty(SoftDirty(-1)); + gstate.cullmode ^= flipCull; transformUnit.SubmitPrimitive(verts, inds, prim, vertexCount, vertTypeID, bytesRead, this); + gstate.cullmode ^= flipCull; // TODO: Should really clear, but the vertex type is faked so things might need resetting... transformUnit.SetDirty(SoftDirty(-1)); } @@ -200,11 +202,11 @@ struct TransformState { }; void ComputeTransformState(TransformState *state, const VertexReader &vreader) { - state->enableTransform = !gstate.isModeThrough(); + state->enableTransform = !vreader.isThrough(); state->enableLighting = gstate.isLightingEnabled(); state->enableFog = gstate.isFogEnabled(); state->readUV = !gstate.isModeClear() && gstate.isTextureMapEnabled() && vreader.hasUV(); - state->readWeights = vertTypeIsSkinningEnabled(gstate.vertType) && state->enableTransform; + state->readWeights = vreader.skinningEnabled() && state->enableTransform; state->negateNormals = gstate.areNormalsReversed(); state->uvGenMode = gstate.getUVGenMode(); @@ -300,7 +302,7 @@ VertexData TransformUnit::ReadVertex(VertexReader &vreader, const TransformState Vec3 tmppos(0.f, 0.f, 0.f); Vec3 tmpnrm(0.f, 0.f, 0.f); - for (int i = 0; i < vertTypeGetNumBoneWeights(gstate.vertType); ++i) { + for (int i = 0; i < vreader.numBoneWeights(); ++i) { Vec3 step = Vec3ByMatrix43(pos, gstate.boneMatrix + i * 12); tmppos += step * W[i]; if (vreader.hasNormal()) { @@ -315,24 +317,12 @@ VertexData TransformUnit::ReadVertex(VertexReader &vreader, const TransformState } if (vreader.hasColor0()) { -#ifdef _M_SSE - vreader.ReadColor0_8888((u8 *)vertex.color0.AsArray()); - vertex.color0.ivec = _mm_unpacklo_epi8(vertex.color0.ivec, _mm_setzero_si128()); - vertex.color0.ivec = _mm_unpacklo_epi16(vertex.color0.ivec, _mm_setzero_si128()); -#else - float col[4]; - vreader.ReadColor0(col); - vertex.color0 = Vec4(col[0]*255, col[1]*255, col[2]*255, col[3]*255); -#endif + vreader.ReadColor0_8888((u8 *)&vertex.color0); } else { - vertex.color0 = Vec4::FromRGBA(gstate.getMaterialAmbientRGBA()); + vertex.color0 = gstate.getMaterialAmbientRGBA(); } -#ifdef _M_SSE - vertex.color1 = _mm_setzero_si128(); -#else - vertex.color1 = Vec3(0, 0, 0); -#endif + vertex.color1 = 0; if (state.enableTransform) { WorldCoords worldpos; @@ -445,12 +435,6 @@ SoftDirty TransformUnit::GetDirty() { return binner_->GetDirty(); } -enum class CullType { - CW, - CCW, - OFF, -}; - void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, GEPrimitiveType prim_type, int vertex_count, u32 vertex_type, int *bytesRead, SoftwareDrawEngine *drawEngine) { VertexDecoder &vdecoder = *drawEngine->FindVertexDecoder(vertex_type); @@ -480,16 +464,11 @@ void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, G VertexReader vreader(decoded_, vtxfmt, vertex_type); - static VertexData data[4]; // Normally max verts per prim is 3, but we temporarily need 4 to detect rectangles from strips. - // This is the index of the next vert in data (or higher, may need modulus.) - static int data_index = 0; - - static GEPrimitiveType prev_prim = GE_PRIM_POINTS; if (prim_type != GE_PRIM_KEEP_PREVIOUS) { - data_index = 0; - prev_prim = prim_type; + data_index_ = 0; + prev_prim_ = prim_type; } else { - prim_type = prev_prim; + prim_type = prev_prim_; } int vtcs_per_prim; @@ -504,7 +483,7 @@ void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, G // TODO: Do this in two passes - first process the vertices (before indexing/stripping), // then resolve the indices. This lets us avoid transforming shared vertices twice. - binner_->UpdateState(); + binner_->UpdateState(vreader.isThrough()); static TransformState transformState; if (binner_->HasDirty(SoftDirty::LIGHT_ALL | SoftDirty::TRANSFORM_ALL)) { @@ -516,6 +495,63 @@ void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, G const CullType cullType = skipCull ? CullType::OFF : (gstate.getCullMode() ? CullType::CCW : CullType::CW); bool outside_range_flag = false; + + if (vreader.isThrough() && cullType == CullType::OFF && prim_type == GE_PRIM_TRIANGLES && data_index_ + vertex_count >= 6 && ((data_index_ + vertex_count) % 6) == 0) { + // Some games send rectangles as a series of regular triangles. + // We look for this, but only in throughmode. + VertexData buf[6]; + int buf_index = data_index_; + for (int i = 0; i < data_index_; ++i) { + buf[i] = data_[i]; + } + + for (int vtx = 0; vtx < vertex_count; ++vtx) { + if (indices) { + vreader.Goto(ConvertIndex(vtx) - index_lower_bound); + } else { + vreader.Goto(vtx); + } + + buf[buf_index++] = ReadVertex(vreader, transformState, outside_range_flag); + if (buf_index >= 3 && outside_range_flag) { + // Cull, just pretend it didn't happen. + buf_index -= 3; + outside_range_flag = false; + continue; + } + + if (buf_index < 6) + continue; + + int tl = -1, br = -1; + if (Rasterizer::DetectRectangleFromPair(binner_->State(), buf, &tl, &br)) { + Clipper::ProcessRect(buf[tl], buf[br], *binner_); + } else { + SendTriangle(cullType, &buf[0]); + SendTriangle(cullType, &buf[3]); + } + + buf_index = 0; + } + + if (buf_index >= 3) { + SendTriangle(cullType, &buf[0]); + data_index_ = 0; + for (int i = 3; i < buf_index; ++i) { + data_[data_index_++] = buf[i]; + } + } else if (buf_index > 0) { + for (int i = 0; i < buf_index; ++i) { + data_[i] = buf[i]; + } + data_index_ = buf_index; + } else { + data_index_ = 0; + } + + return; + } + switch (prim_type) { case GE_PRIM_POINTS: case GE_PRIM_LINES: @@ -528,14 +564,14 @@ void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, G vreader.Goto(vtx); } - data[data_index++] = ReadVertex(vreader, transformState, outside_range_flag); - if (data_index < vtcs_per_prim) { + data_[data_index_++] = ReadVertex(vreader, transformState, outside_range_flag); + if (data_index_ < vtcs_per_prim) { // Keep reading. Note: an incomplete prim will stay read for GE_PRIM_KEEP_PREVIOUS. continue; } // Okay, we've got enough verts. Reset the index for next time. - data_index = 0; + data_index_ = 0; if (outside_range_flag) { // Cull the prim if it was outside, and move to the next prim. outside_range_flag = false; @@ -544,24 +580,15 @@ void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, G switch (prim_type) { case GE_PRIM_TRIANGLES: - { - if (cullType == CullType::OFF) { - Clipper::ProcessTriangle(data[0], data[1], data[2], data[2], *binner_); - Clipper::ProcessTriangle(data[2], data[1], data[0], data[2], *binner_); - } else if (cullType == CullType::CW) { - Clipper::ProcessTriangle(data[2], data[1], data[0], data[2], *binner_); - } else { - Clipper::ProcessTriangle(data[0], data[1], data[2], data[2], *binner_); - } + SendTriangle(cullType, &data_[0]); break; - } case GE_PRIM_LINES: - Clipper::ProcessLine(data[0], data[1], *binner_); + Clipper::ProcessLine(data_[0], data_[1], *binner_); break; case GE_PRIM_POINTS: - Clipper::ProcessPoint(data[0], *binner_); + Clipper::ProcessPoint(data_[0], *binner_); break; default: @@ -579,45 +606,45 @@ void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, G vreader.Goto(vtx); } - data[data_index++] = ReadVertex(vreader, transformState, outside_range_flag); + data_[data_index_++] = ReadVertex(vreader, transformState, outside_range_flag); if (outside_range_flag) { outside_range_flag = false; // Note: this is the post increment index. If odd, we set the first vert. - if (data_index & 1) { + if (data_index_ & 1) { // Skip the next one and forget this one. vtx++; - data_index--; + data_index_--; } else { // Forget both of the last 2. - data_index -= 2; + data_index_ -= 2; } } - if (data_index == 4 && gstate.isModeThrough() && cullType == CullType::OFF) { - if (Rasterizer::DetectRectangleThroughModeSlices(binner_->State(), data)) { - data[1] = data[3]; - data_index = 2; + if (data_index_ == 4 && vreader.isThrough() && cullType == CullType::OFF) { + if (Rasterizer::DetectRectangleThroughModeSlices(binner_->State(), data_)) { + data_[1] = data_[3]; + data_index_ = 2; } } - if (data_index == 4) { - Clipper::ProcessRect(data[0], data[1], *binner_); - Clipper::ProcessRect(data[2], data[3], *binner_); - data_index = 0; + if (data_index_ == 4) { + Clipper::ProcessRect(data_[0], data_[1], *binner_); + Clipper::ProcessRect(data_[2], data_[3], *binner_); + data_index_ = 0; } } - if (data_index >= 2) { - Clipper::ProcessRect(data[0], data[1], *binner_); - data_index -= 2; + if (data_index_ >= 2) { + Clipper::ProcessRect(data_[0], data_[1], *binner_); + data_index_ -= 2; } break; case GE_PRIM_LINE_STRIP: { // Don't draw a line when loading the first vertex. - // If data_index is 1 or 2, etc., it means we're continuing a line strip. - int skip_count = data_index == 0 ? 1 : 0; + // If data_index_ is 1 or 2, etc., it means we're continuing a line strip. + int skip_count = data_index_ == 0 ? 1 : 0; for (int vtx = 0; vtx < vertex_count; ++vtx) { if (indices) { vreader.Goto(ConvertIndex(vtx) - index_lower_bound); @@ -625,7 +652,7 @@ void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, G vreader.Goto(vtx); } - data[(data_index++) & 1] = ReadVertex(vreader, transformState, outside_range_flag); + data_[(data_index_++) & 1] = ReadVertex(vreader, transformState, outside_range_flag); if (outside_range_flag) { // Drop all primitives containing the current vertex skip_count = 2; @@ -636,8 +663,8 @@ void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, G if (skip_count) { --skip_count; } else { - // We already incremented data_index, so data_index & 1 is previous one. - Clipper::ProcessLine(data[data_index & 1], data[(data_index & 1) ^ 1], *binner_); + // We already incremented data_index_, so data_index_ & 1 is previous one. + Clipper::ProcessLine(data_[data_index_ & 1], data_[(data_index_ & 1) ^ 1], *binner_); } } break; @@ -646,39 +673,53 @@ void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, G case GE_PRIM_TRIANGLE_STRIP: { // Don't draw a triangle when loading the first two vertices. - int skip_count = data_index >= 2 ? 0 : 2 - data_index; + int skip_count = data_index_ >= 2 ? 0 : 2 - data_index_; + int start_vtx = 0; // If index count == 4, check if we can convert to a rectangle. // This is for Darkstalkers (and should speed up many 2D games). - if (data_index == 0 && vertex_count == 4 && cullType == CullType::OFF) { - for (int vtx = 0; vtx < 4; ++vtx) { - if (indices) { - vreader.Goto(ConvertIndex(vtx) - index_lower_bound); + if (data_index_ == 0 && vertex_count >= 4 && (vertex_count & 1) == 0 && cullType == CullType::OFF) { + for (int base = 0; base < vertex_count - 2; base += 2) { + for (int vtx = base == 0 ? 0 : 2; vtx < 4; ++vtx) { + if (indices) { + vreader.Goto(ConvertIndex(base + vtx) - index_lower_bound); + } else { + vreader.Goto(base + vtx); + } + data_[vtx] = ReadVertex(vreader, transformState, outside_range_flag); } - else { - vreader.Goto(vtx); - } - data[vtx] = ReadVertex(vreader, transformState, outside_range_flag); - } - // If a strip is effectively a rectangle, draw it as such! - int tl = -1, br = -1; - if (!outside_range_flag && Rasterizer::DetectRectangleFromStrip(binner_->State(), data, &tl, &br)) { - Clipper::ProcessRect(data[tl], data[br], *binner_); - break; + // If a strip is effectively a rectangle, draw it as such! + int tl = -1, br = -1; + if (!outside_range_flag && Rasterizer::DetectRectangleFromStrip(binner_->State(), data_, &tl, &br)) { + Clipper::ProcessRect(data_[tl], data_[br], *binner_); + start_vtx += 2; + if (base + 4 >= vertex_count) { + start_vtx = vertex_count; + break; + } + + // Just copy the first two so we can detect easier. + // TODO: Maybe should give detection two halves? + data_[0] = data_[2]; + data_[1] = data_[3]; + } else { + // Go into triangle mode. Unfortunately, we re-read the verts. + break; + } } } outside_range_flag = false; - for (int vtx = 0; vtx < vertex_count; ++vtx) { + for (int vtx = start_vtx; vtx < vertex_count; ++vtx) { if (indices) { vreader.Goto(ConvertIndex(vtx) - index_lower_bound); } else { vreader.Goto(vtx); } - int provoking_index = (data_index++) % 3; - data[provoking_index] = ReadVertex(vreader, transformState, outside_range_flag); + int provoking_index = (data_index_++) % 3; + data_[provoking_index] = ReadVertex(vreader, transformState, outside_range_flag); if (outside_range_flag) { // Drop all primitives containing the current vertex skip_count = 2; @@ -691,16 +732,9 @@ void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, G continue; } - if (cullType == CullType::OFF) { - Clipper::ProcessTriangle(data[0], data[1], data[2], data[provoking_index], *binner_); - Clipper::ProcessTriangle(data[2], data[1], data[0], data[provoking_index], *binner_); - } else if ((!(int)cullType) ^ ((data_index - 1) % 2)) { - // We need to reverse the vertex order for each second primitive, - // but we additionally need to do that for every primitive if CCW cullmode is used. - Clipper::ProcessTriangle(data[2], data[1], data[0], data[provoking_index], *binner_); - } else { - Clipper::ProcessTriangle(data[0], data[1], data[2], data[provoking_index], *binner_); - } + int wind = (data_index_ - 1) % 2; + CullType altCullType = cullType == CullType::OFF ? cullType : CullType((int)cullType ^ wind); + SendTriangle(altCullType, &data_[0], provoking_index); } break; } @@ -709,18 +743,18 @@ void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, G { // Don't draw a triangle when loading the first two vertices. // (this doesn't count the central one.) - int skip_count = data_index <= 1 ? 1 : 0; + int skip_count = data_index_ <= 1 ? 1 : 0; int start_vtx = 0; // Only read the central vertex if we're not continuing. - if (data_index == 0) { + if (data_index_ == 0) { if (indices) { vreader.Goto(ConvertIndex(0) - index_lower_bound); } else { vreader.Goto(0); } - data[0] = ReadVertex(vreader, transformState, outside_range_flag); - data_index++; + data_[0] = ReadVertex(vreader, transformState, outside_range_flag); + data_index_++; start_vtx = 1; // If the central vertex is outside range, all the points are toast. @@ -728,19 +762,19 @@ void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, G break; } - if (data_index == 1 && vertex_count == 4 && cullType == CullType::OFF) { + if (data_index_ == 1 && vertex_count == 4 && cullType == CullType::OFF) { for (int vtx = start_vtx; vtx < vertex_count; ++vtx) { if (indices) { vreader.Goto(ConvertIndex(vtx) - index_lower_bound); } else { vreader.Goto(vtx); } - data[vtx] = ReadVertex(vreader, transformState, outside_range_flag); + data_[vtx] = ReadVertex(vreader, transformState, outside_range_flag); } int tl = -1, br = -1; - if (!outside_range_flag && Rasterizer::DetectRectangleFromFan(binner_->State(), data, vertex_count, &tl, &br)) { - Clipper::ProcessRect(data[tl], data[br], *binner_); + if (!outside_range_flag && Rasterizer::DetectRectangleFromFan(binner_->State(), data_, vertex_count, &tl, &br)) { + Clipper::ProcessRect(data_[tl], data_[br], *binner_); break; } } @@ -753,8 +787,8 @@ void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, G vreader.Goto(vtx); } - int provoking_index = 2 - ((data_index++) % 2); - data[provoking_index] = ReadVertex(vreader, transformState, outside_range_flag); + int provoking_index = 2 - ((data_index_++) % 2); + data_[provoking_index] = ReadVertex(vreader, transformState, outside_range_flag); if (outside_range_flag) { // Drop all primitives containing the current vertex skip_count = 2; @@ -767,16 +801,9 @@ void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, G continue; } - if (cullType == CullType::OFF) { - Clipper::ProcessTriangle(data[0], data[1], data[2], data[provoking_index], *binner_); - Clipper::ProcessTriangle(data[2], data[1], data[0], data[provoking_index], *binner_); - } else if ((!(int)cullType) ^ ((data_index - 1) % 2)) { - // We need to reverse the vertex order for each second primitive, - // but we additionally need to do that for every primitive if CCW cullmode is used. - Clipper::ProcessTriangle(data[2], data[1], data[0], data[provoking_index], *binner_); - } else { - Clipper::ProcessTriangle(data[0], data[1], data[2], data[provoking_index], *binner_); - } + int wind = (data_index_ - 1) % 2; + CullType altCullType = cullType == CullType::OFF ? cullType : CullType((int)cullType ^ wind); + SendTriangle(altCullType, &data_[0], provoking_index); } break; } @@ -787,6 +814,17 @@ void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, G } } +void TransformUnit::SendTriangle(CullType cullType, const VertexData *verts, int provoking) { + if (cullType == CullType::OFF) { + Clipper::ProcessTriangle(verts[0], verts[1], verts[2], verts[provoking], *binner_); + Clipper::ProcessTriangle(verts[2], verts[1], verts[0], verts[provoking], *binner_); + } else if (cullType == CullType::CW) { + Clipper::ProcessTriangle(verts[2], verts[1], verts[0], verts[provoking], *binner_); + } else { + Clipper::ProcessTriangle(verts[0], verts[1], verts[2], verts[provoking], *binner_); + } +} + void TransformUnit::Flush(const char *reason) { binner_->Flush(reason); GPUDebug::NotifyDraw(); diff --git a/GPU/Software/TransformUnit.h b/GPU/Software/TransformUnit.h index 54f9fb5f5e..64311eedc8 100644 --- a/GPU/Software/TransformUnit.h +++ b/GPU/Software/TransformUnit.h @@ -37,6 +37,12 @@ typedef Vec4 ClipCoords; // Range: -w <= x/y/z <= w class BinManager; struct TransformState; +enum class CullType { + CW = 0, + CCW = 1, + OFF = 2, +}; + struct ScreenCoords { ScreenCoords() {} @@ -79,15 +85,15 @@ struct VertexData { texturecoords = ::Lerp(a.texturecoords, b.texturecoords, t); fogdepth = ::Lerp(a.fogdepth, b.fogdepth, t); - u16 t_int = (u16)(t*256); - color0 = LerpInt,256>(a.color0, b.color0, t_int); - color1 = LerpInt,256>(a.color1, b.color1, t_int); + u16 t_int = (u16)(t * 256); + color0 = LerpInt, 256>(Vec4::FromRGBA(a.color0), Vec4::FromRGBA(b.color0), t_int).ToRGBA(); + color1 = LerpInt, 256>(Vec3::FromRGB(a.color1), Vec3::FromRGB(b.color1), t_int).ToRGB(); } ClipCoords clippos; Vec2 texturecoords; - Vec4 color0; - Vec3 color1; + uint32_t color0; + uint32_t color1; ScreenCoords screenpos; // TODO: Shouldn't store this ? float fogdepth; }; @@ -133,9 +139,16 @@ public: private: VertexData ReadVertex(VertexReader &vreader, const TransformState &lstate, bool &outside_range_flag); + void SendTriangle(CullType cullType, const VertexData *verts, int provoking = 2); u8 *decoded_ = nullptr; BinManager *binner_ = nullptr; + + // Normally max verts per prim is 3, but we temporarily need 4 to detect rectangles from strips. + VertexData data_[4]; + // This is the index of the next vert in data (or higher, may need modulus.) + int data_index_ = 0; + GEPrimitiveType prev_prim_ = GE_PRIM_POINTS; }; class SoftwareDrawEngine : public DrawEngineCommon { diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index 0ada8b9b06..e8ebd485d1 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -141,6 +141,7 @@ void DrawEngineVulkan::InitDeviceObjects() { dsl.pBindings = bindings; VkResult res = vkCreateDescriptorSetLayout(device, &dsl, nullptr, &descriptorSetLayout_); _dbg_assert_(VK_SUCCESS == res); + vulkan->SetDebugName(descriptorSetLayout_, VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT, "drawengine_d_layout"); static constexpr int DEFAULT_DESC_POOL_SIZE = 512; std::vector dpTypes; @@ -179,6 +180,8 @@ void DrawEngineVulkan::InitDeviceObjects() { res = vkCreatePipelineLayout(device, &pl, nullptr, &pipelineLayout_); _dbg_assert_(VK_SUCCESS == res); + vulkan->SetDebugName(pipelineLayout_, VK_OBJECT_TYPE_PIPELINE_LAYOUT, "drawengine_p_layout"); + VkSamplerCreateInfo samp{ VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO }; samp.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; samp.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; @@ -768,9 +771,7 @@ void DrawEngineVulkan::DoFlush() { } _dbg_assert_msg_(vshader->UseHWTransform(), "Bad vshader"); - Draw::NativeObject object = framebufferManager_->UseBufferedRendering() ? Draw::NativeObject::FRAMEBUFFER_RENDERPASS : Draw::NativeObject::BACKBUFFER_RENDERPASS; - VkRenderPass renderPass = (VkRenderPass)draw_->GetNativeObject(object); - VulkanPipeline *pipeline = pipelineManager_->GetOrCreatePipeline(renderManager, pipelineLayout_, renderPass, pipelineKey_, &dec_->decFmt, vshader, fshader, true); + VulkanPipeline *pipeline = pipelineManager_->GetOrCreatePipeline(renderManager, pipelineLayout_, pipelineKey_, &dec_->decFmt, vshader, fshader, true, 0); if (!pipeline || !pipeline->pipeline) { // Already logged, let's bail out. return; @@ -895,9 +896,7 @@ void DrawEngineVulkan::DoFlush() { } shaderManager_->GetShaders(prim, lastVType_, &vshader, &fshader, pipelineState_, false, false, decOptions_.expandAllWeightsToFloat); // usehwtransform _dbg_assert_msg_(!vshader->UseHWTransform(), "Bad vshader"); - Draw::NativeObject object = framebufferManager_->UseBufferedRendering() ? Draw::NativeObject::FRAMEBUFFER_RENDERPASS : Draw::NativeObject::BACKBUFFER_RENDERPASS; - VkRenderPass renderPass = (VkRenderPass)draw_->GetNativeObject(object); - VulkanPipeline *pipeline = pipelineManager_->GetOrCreatePipeline(renderManager, pipelineLayout_, renderPass, pipelineKey_, &dec_->decFmt, vshader, fshader, false); + VulkanPipeline *pipeline = pipelineManager_->GetOrCreatePipeline(renderManager, pipelineLayout_, pipelineKey_, &dec_->decFmt, vshader, fshader, false, 0); if (!pipeline || !pipeline->pipeline) { // Already logged, let's bail out. decodedVerts_ = 0; diff --git a/GPU/Vulkan/GPU_Vulkan.cpp b/GPU/Vulkan/GPU_Vulkan.cpp index 6cf56b17f3..f96d282fc7 100644 --- a/GPU/Vulkan/GPU_Vulkan.cpp +++ b/GPU/Vulkan/GPU_Vulkan.cpp @@ -91,7 +91,7 @@ GPU_Vulkan::GPU_Vulkan(GraphicsContext *gfxCtx, Draw::DrawContext *draw) // Update again after init to be sure of any silly driver problems. UpdateVsyncInterval(true); - textureCacheVulkan_->NotifyConfigChanged(); + textureCache_->NotifyConfigChanged(); // Load shader cache. std::string discID = g_paramSFO.GetDiscID(); @@ -303,7 +303,7 @@ void GPU_Vulkan::BeginHostFrame() { BuildReportingInfo(); framebufferManager_->Resized(); drawEngine_.Resized(); - textureCacheVulkan_->NotifyConfigChanged(); + textureCache_->NotifyConfigChanged(); resized_ = false; } diff --git a/GPU/Vulkan/PipelineManagerVulkan.cpp b/GPU/Vulkan/PipelineManagerVulkan.cpp index 8909283884..a88fe235a5 100644 --- a/GPU/Vulkan/PipelineManagerVulkan.cpp +++ b/GPU/Vulkan/PipelineManagerVulkan.cpp @@ -18,6 +18,10 @@ using namespace PPSSPP_VK; +u32 VulkanPipeline::GetVariantsBitmask() const { + return pipeline->GetVariantsBitmask(); +} + PipelineManagerVulkan::PipelineManagerVulkan(VulkanContext *vulkan) : pipelines_(256), vulkan_(vulkan) { // The pipeline cache is created on demand (or explicitly through Load). } @@ -30,21 +34,12 @@ PipelineManagerVulkan::~PipelineManagerVulkan() { } 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. - pipelines_.Iterate([&](const VulkanPipelineKey &key, VulkanPipeline *value) { - if (value->pipeline) { - VkPipeline pipeline = value->pipeline->pipeline->BlockUntilReady(); - vulkan_->Delete().QueueDeletePipeline(pipeline); - vulkan_->Delete().QueueCallback([](void *p) { - VKRGraphicsPipeline *pipeline = (VKRGraphicsPipeline *)p; - delete pipeline; - }, value->pipeline); - } else { + if (!value->pipeline) { // Something went wrong. ERROR_LOG(G3D, "Null pipeline found in PipelineManagerVulkan::Clear - didn't wait for asyncs?"); + } else { + value->pipeline->QueueForDeletion(vulkan_); } delete value; }); @@ -175,9 +170,10 @@ static std::string CutFromMain(std::string str) { } static VulkanPipeline *CreateVulkanPipeline(VulkanRenderManager *renderManager, VkPipelineCache pipelineCache, - VkPipelineLayout layout, VkRenderPass renderPass, const VulkanPipelineRasterStateKey &key, - const DecVtxFormat *decFmt, VulkanVertexShader *vs, VulkanFragmentShader *fs, bool useHwTransform) { - VKRGraphicsPipelineDesc *desc = new VKRGraphicsPipelineDesc(); + VkPipelineLayout layout, const VulkanPipelineRasterStateKey &key, + const DecVtxFormat *decFmt, VulkanVertexShader *vs, VulkanFragmentShader *fs, bool useHwTransform, u32 variantBitmask) { + VulkanPipeline *vulkanPipeline = new VulkanPipeline(); + VKRGraphicsPipelineDesc *desc = &vulkanPipeline->desc; desc->pipelineCache = pipelineCache; PROFILE_THIS_SCOPE("pipelinebuild"); @@ -298,31 +294,10 @@ static VulkanPipeline *CreateVulkanPipeline(VulkanRenderManager *renderManager, views.pViewports = nullptr; // dynamic views.pScissors = nullptr; // dynamic - VkGraphicsPipelineCreateInfo &pipe = desc->pipe; - pipe.flags = 0; - pipe.stageCount = 2; - pipe.basePipelineIndex = 0; + desc->pipelineLayout = layout; - pipe.pColorBlendState = &desc->cbs; - pipe.pDepthStencilState = &desc->dss; - pipe.pRasterizationState = &desc->rs; + VKRGraphicsPipeline *pipeline = renderManager->CreateGraphicsPipeline(desc, variantBitmask, "game"); - // We will use dynamic viewport state. - pipe.pVertexInputState = &desc->vis; - pipe.pViewportState = &desc->views; - pipe.pTessellationState = nullptr; - pipe.pDynamicState = &desc->ds; - pipe.pInputAssemblyState = &desc->inputAssembly; - pipe.pMultisampleState = &desc->ms; - pipe.layout = layout; - pipe.basePipelineHandle = VK_NULL_HANDLE; - pipe.basePipelineIndex = 0; - pipe.renderPass = renderPass; - pipe.subpass = 0; - - VKRGraphicsPipeline *pipeline = renderManager->CreateGraphicsPipeline(desc); - - VulkanPipeline *vulkanPipeline = new VulkanPipeline(); vulkanPipeline->pipeline = pipeline; vulkanPipeline->flags = 0; if (useBlendConstant) @@ -335,7 +310,7 @@ static VulkanPipeline *CreateVulkanPipeline(VulkanRenderManager *renderManager, return vulkanPipeline; } -VulkanPipeline *PipelineManagerVulkan::GetOrCreatePipeline(VulkanRenderManager *renderManager, VkPipelineLayout layout, VkRenderPass renderPass, const VulkanPipelineRasterStateKey &rasterKey, const DecVtxFormat *decFmt, VulkanVertexShader *vs, VulkanFragmentShader *fs, bool useHwTransform) { +VulkanPipeline *PipelineManagerVulkan::GetOrCreatePipeline(VulkanRenderManager *renderManager, VkPipelineLayout layout, const VulkanPipelineRasterStateKey &rasterKey, const DecVtxFormat *decFmt, VulkanVertexShader *vs, VulkanFragmentShader *fs, bool useHwTransform, u32 variantBitmask) { if (!pipelineCache_) { VkPipelineCacheCreateInfo pc{ VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO }; VkResult res = vkCreatePipelineCache(vulkan_->GetDevice(), &pc, nullptr, &pipelineCache_); @@ -343,10 +318,8 @@ VulkanPipeline *PipelineManagerVulkan::GetOrCreatePipeline(VulkanRenderManager * } VulkanPipelineKey key{}; - _assert_msg_(renderPass, "Can't create a pipeline with a null renderpass"); key.raster = rasterKey; - key.renderPass = renderPass; key.useHWTransform = useHwTransform; key.vShader = vs->GetModule(); key.fShader = fs->GetModule(); @@ -357,8 +330,8 @@ VulkanPipeline *PipelineManagerVulkan::GetOrCreatePipeline(VulkanRenderManager * return iter; VulkanPipeline *pipeline = CreateVulkanPipeline( - renderManager, pipelineCache_, layout, renderPass, - rasterKey, decFmt, vs, fs, useHwTransform); + renderManager, pipelineCache_, layout, + rasterKey, decFmt, vs, fs, useHwTransform, variantBitmask); pipelines_.Insert(key, pipeline); // Don't return placeholder null pipelines. @@ -564,9 +537,8 @@ struct StoredVulkanPipelineKey { VShaderID vShaderID; FShaderID fShaderID; uint32_t vtxFmtId; - bool useHWTransform; - bool backbufferPass; - VulkanQueueRunner::RPKey renderPassKey; + uint32_t variants; + bool useHWTransform; // TODO: Still needed? // For std::set. Better zero-initialize the struct properly for this to work. bool operator < (const StoredVulkanPipelineKey &other) const { @@ -623,18 +595,11 @@ void PipelineManagerVulkan::SaveCache(FILE *file, bool saveRawPipelineCache, Sha key.useHWTransform = pkey.useHWTransform; key.fShaderID = fshader->GetID(); key.vShaderID = vshader->GetID(); + key.variants = value->GetVariantsBitmask(); if (key.useHWTransform) { // NOTE: This is not a vtype, but a decoded vertex format. key.vtxFmtId = pkey.vtxFmtId; } - // Figure out what kind of renderpass this pipeline uses. - if (pkey.renderPass == queueRunner->GetBackbufferRenderPass()) { - key.backbufferPass = true; - key.renderPassKey = {}; - } else { - key.backbufferPass = false; - queueRunner->GetRenderPassKey(pkey.renderPass, &key.renderPassKey); - } keys.insert(key); }); @@ -740,22 +705,16 @@ bool PipelineManagerVulkan::LoadCache(FILE *file, bool loadRawPipelineCache, Sha continue; } - VkRenderPass rp; - if (key.backbufferPass) { - rp = queueRunner->GetBackbufferRenderPass(); - } else { - rp = queueRunner->GetRenderPass(key.renderPassKey); - } - DecVtxFormat fmt; fmt.InitializeFromID(key.vtxFmtId); - VulkanPipeline *pipeline = GetOrCreatePipeline(rm, layout, rp, key.raster, - key.useHWTransform ? &fmt : 0, - vs, fs, key.useHWTransform); + VulkanPipeline *pipeline = GetOrCreatePipeline(rm, layout, key.raster, key.useHWTransform ? &fmt : 0, vs, fs, key.useHWTransform, key.variants); if (!pipeline) { pipelineCreateFailCount += 1; } } + + rm->NudgeCompilerThread(); + NOTICE_LOG(G3D, "Recreated Vulkan pipeline cache (%d pipelines, %d failed).", (int)size, pipelineCreateFailCount); return true; } diff --git a/GPU/Vulkan/PipelineManagerVulkan.h b/GPU/Vulkan/PipelineManagerVulkan.h index a6ab695cef..af32aa81bd 100644 --- a/GPU/Vulkan/PipelineManagerVulkan.h +++ b/GPU/Vulkan/PipelineManagerVulkan.h @@ -28,13 +28,14 @@ #include "GPU/Vulkan/VulkanUtil.h" #include "GPU/Vulkan/StateMappingVulkan.h" #include "GPU/Vulkan/VulkanQueueRunner.h" +#include "GPU/Vulkan/VulkanRenderManager.h" struct VKRGraphicsPipeline; class VulkanRenderManager; struct VulkanPipelineKey { VulkanPipelineRasterStateKey raster; // prim is included here - VkRenderPass renderPass; + VKRRenderPass *renderPass; Promise *vShader; Promise *fShader; uint32_t vtxFmtId; @@ -53,11 +54,14 @@ struct VulkanPipelineKey { // Simply wraps a Vulkan pipeline, providing some metadata. struct VulkanPipeline { VKRGraphicsPipeline *pipeline; + VKRGraphicsPipelineDesc desc; int flags; // PipelineFlags enum above. bool UsesBlendConstant() const { return (flags & PIPELINE_FLAG_USES_BLEND_CONSTANT) != 0; } bool UsesLines() const { return (flags & PIPELINE_FLAG_USES_LINES) != 0; } bool UsesDepthStencil() const { return (flags & PIPELINE_FLAG_USES_DEPTH_STENCIL) != 0; } + + u32 GetVariantsBitmask() const; }; class VulkanContext; @@ -71,7 +75,8 @@ public: PipelineManagerVulkan(VulkanContext *ctx); ~PipelineManagerVulkan(); - VulkanPipeline *GetOrCreatePipeline(VulkanRenderManager *renderManager, VkPipelineLayout layout, VkRenderPass renderPass, const VulkanPipelineRasterStateKey &rasterKey, const DecVtxFormat *decFmt, VulkanVertexShader *vs, VulkanFragmentShader *fs, bool useHwTransform); + // variantMask is only used when loading pipelines from cache. + VulkanPipeline *GetOrCreatePipeline(VulkanRenderManager *renderManager, VkPipelineLayout layout, const VulkanPipelineRasterStateKey &rasterKey, const DecVtxFormat *decFmt, VulkanVertexShader *vs, VulkanFragmentShader *fs, bool useHwTransform, u32 variantMask); int GetNumPipelines() const { return (int)pipelines_.size(); } void Clear(); diff --git a/GPU/Vulkan/ShaderManagerVulkan.cpp b/GPU/Vulkan/ShaderManagerVulkan.cpp index eb30aa4728..9cb91e00c6 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.cpp +++ b/GPU/Vulkan/ShaderManagerVulkan.cpp @@ -71,7 +71,7 @@ Promise *CompileShaderModuleAsync(VulkanContext *vulkan, VkShade VkShaderModule shaderModule = VK_NULL_HANDLE; if (success) { - success = vulkan->CreateShaderModule(spirv, &shaderModule); + success = vulkan->CreateShaderModule(spirv, &shaderModule, stage == VK_SHADER_STAGE_VERTEX_BIT ? "game_vertex" : "game_fragment"); #ifdef SHADERLOG OutputDebugStringA("OK"); #endif @@ -81,7 +81,7 @@ Promise *CompileShaderModuleAsync(VulkanContext *vulkan, VkShade }; #ifdef _DEBUG - // Don't parallelize in debug mode, pathological behavior due to mutex locks in allocator. + // Don't parallelize in debug mode, pathological behavior due to mutex locks in allocator which is HEAVILY used by glslang. return Promise::AlreadyDone(compile()); #else return Promise::Spawn(&g_threadManager, compile, TaskType::CPU_COMPUTE); @@ -89,8 +89,8 @@ Promise *CompileShaderModuleAsync(VulkanContext *vulkan, VkShade } -VulkanFragmentShader::VulkanFragmentShader(VulkanContext *vulkan, FShaderID id, const char *code) - : vulkan_(vulkan), id_(id) { +VulkanFragmentShader::VulkanFragmentShader(VulkanContext *vulkan, FShaderID id, FragmentShaderFlags flags, const char *code) + : vulkan_(vulkan), id_(id), flags_(flags) { source_ = code; module_ = CompileShaderModuleAsync(vulkan, VK_SHADER_STAGE_FRAGMENT_BIT, source_.c_str()); if (!module_) { @@ -276,9 +276,10 @@ void ShaderManagerVulkan::GetShaders(int prim, u32 vertType, VulkanVertexShader // Fragment shader not in cache. Let's compile it. std::string genErrorString; uint64_t uniformMask = 0; // Not used - bool success = GenerateFragmentShader(FSID, codeBuffer_, compat_, draw_->GetBugs(), &uniformMask, &genErrorString); + FragmentShaderFlags flags; + bool success = GenerateFragmentShader(FSID, codeBuffer_, compat_, draw_->GetBugs(), &uniformMask, &flags, &genErrorString); _assert_msg_(success, "FS gen error: %s", genErrorString.c_str()); - fs = new VulkanFragmentShader(vulkan, FSID, codeBuffer_); + fs = new VulkanFragmentShader(vulkan, FSID, flags, codeBuffer_); fsCache_.Insert(FSID, fs); } @@ -370,7 +371,7 @@ VulkanFragmentShader *ShaderManagerVulkan::GetFragmentShaderFromModule(VkShaderM // instantaneous. #define CACHE_HEADER_MAGIC 0xff51f420 -#define CACHE_VERSION 22 +#define CACHE_VERSION 26 struct VulkanCacheHeader { uint32_t magic; uint32_t version; @@ -417,10 +418,11 @@ bool ShaderManagerVulkan::LoadCache(FILE *f) { } std::string genErrorString; uint64_t uniformMask = 0; - if (!GenerateFragmentShader(id, codeBuffer_, compat_, draw_->GetBugs(), &uniformMask, &genErrorString)) { + FragmentShaderFlags flags; + if (!GenerateFragmentShader(id, codeBuffer_, compat_, draw_->GetBugs(), &uniformMask, &flags, &genErrorString)) { return false; } - VulkanFragmentShader *fs = new VulkanFragmentShader(vulkan, id, codeBuffer_); + VulkanFragmentShader *fs = new VulkanFragmentShader(vulkan, id, flags, codeBuffer_); fsCache_.Insert(id, fs); } diff --git a/GPU/Vulkan/ShaderManagerVulkan.h b/GPU/Vulkan/ShaderManagerVulkan.h index 50915be6a2..6593a366f4 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.h +++ b/GPU/Vulkan/ShaderManagerVulkan.h @@ -36,7 +36,7 @@ class VulkanPushBuffer; class VulkanFragmentShader { public: - VulkanFragmentShader(VulkanContext *vulkan, FShaderID id, const char *code); + VulkanFragmentShader(VulkanContext *vulkan, FShaderID id, FragmentShaderFlags flags, const char *code); ~VulkanFragmentShader(); const std::string &source() const { return source_; } @@ -45,7 +45,9 @@ public: std::string GetShaderString(DebugShaderStringType type) const; Promise *GetModule() { return module_; } - const FShaderID &GetID() { return id_; } + const FShaderID &GetID() const { return id_; } + + FragmentShaderFlags Flags() const { return flags_; } protected: Promise *module_ = nullptr; @@ -54,6 +56,7 @@ protected: std::string source_; bool failed_ = false; FShaderID id_; + FragmentShaderFlags flags_; }; class VulkanVertexShader { @@ -68,7 +71,7 @@ public: std::string GetShaderString(DebugShaderStringType type) const; Promise *GetModule() { return module_; } - const VShaderID &GetID() { return id_; } + const VShaderID &GetID() const { return id_; } protected: Promise *module_ = nullptr; diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index d11e92ba05..443670e903 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -389,13 +389,12 @@ void TextureCacheVulkan::UpdateCurrentClut(GEPaletteFormat clutFormat, u32 clutB } void TextureCacheVulkan::BindTexture(TexCacheEntry *entry) { - if (!entry) { + if (!entry || !entry->vkTex) { imageView_ = VK_NULL_HANDLE; curSampler_ = VK_NULL_HANDLE; return; } - _dbg_assert_(entry->vkTex); entry->vkTex->Touch(); int maxLevel = (entry->status & TexCacheEntry::STATUS_NO_MIPS) ? 0 : entry->maxLevel; @@ -403,7 +402,7 @@ void TextureCacheVulkan::BindTexture(TexCacheEntry *entry) { curSampler_ = samplerCache_.GetOrCreateSampler(samplerKey); imageView_ = entry->vkTex->GetImageView(); drawEngine_->SetDepalTexture(VK_NULL_HANDLE, false); - gstate_c.SetUseShaderDepal(false, false); + gstate_c.SetUseShaderDepal(ShaderDepalMode::OFF); } void TextureCacheVulkan::ApplySamplingParams(const SamplerCacheKey &key) { diff --git a/GPU/Vulkan/VulkanUtil.cpp b/GPU/Vulkan/VulkanUtil.cpp index 4664f60c8a..fb82f9a474 100644 --- a/GPU/Vulkan/VulkanUtil.cpp +++ b/GPU/Vulkan/VulkanUtil.cpp @@ -44,7 +44,7 @@ VkShaderModule CompileShaderModule(VulkanContext *vulkan, VkShaderStageFlagBits return VK_NULL_HANDLE; } else { VkShaderModule module; - if (vulkan->CreateShaderModule(spirv, &module)) { + if (vulkan->CreateShaderModule(spirv, &module, stage == VK_SHADER_STAGE_VERTEX_BIT ? "system_vs" : "system_fs")) { return module; } else { return VK_NULL_HANDLE; diff --git a/GPU/ge_constants.h b/GPU/ge_constants.h index 3559282c57..19a51ae5ab 100644 --- a/GPU/ge_constants.h +++ b/GPU/ge_constants.h @@ -350,6 +350,15 @@ inline bool IsGeBufferFormat16BitColor(GEBufferFormat fmt) { #define GE_CLEARMODE_Z (1<<10) #define GE_CLEARMODE_ALL (GE_CLEARMODE_COLOR|GE_CLEARMODE_ALPHA|GE_CLEARMODE_Z) +#define GE_IMM_ANTIALIAS 0x00000800 +#define GE_IMM_CLIPMASK 0x0003F000 +#define GE_IMM_SHADING 0x00040000 +#define GE_IMM_CULLENABLE 0x00080000 +#define GE_IMM_CULLFACE 0x00100000 +#define GE_IMM_TEXTURE 0x00200000 +#define GE_IMM_FOG 0x00400000 +#define GE_IMM_DITHER 0x00800000 + enum GEMatrixType { GE_MTX_BONE0 = 0, GE_MTX_BONE1, diff --git a/README.md b/README.md index 03df3bca66..8a9a7bc744 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,12 @@ If you want to download regularly updated builds for Android, Windows x86 and x6 For game compatibility, see [community compatibility feedback](https://report.ppsspp.org/games). +What's new in 1.13.2 +==================== +* Crashfix on Android 12 when playing certain background music ([#15990]) +* Fix Star Ocean battles in D3D backends (#[15889]) +* Minor fixes that might fix some other crashes + What's new in 1.13.1 ==================== @@ -160,110 +166,6 @@ Adhoc/Network: * Reduce HLE delays due to multiplayer performance regressions (ie. Ys vs. Sora no Kiseki) ([#14513]) * Fix socket error 10014 on Windows when hosting a game of Vulcanus Seek and Destroy ([#14849]) -What's new in 1.11.3 -==================== -* Fix for graphics glitches in the on-screen keyboard - -What's new in 1.11.2 -==================== -* An additional few crash fixes ([#14129], [#14134], [#14132]) - -What's new in 1.11.1 -==================== -* A few crash fixes ([#14085], [#14089], [#14091], [#14092]), a few adhoc fixes -* Glitchy menu audio on some devices ([#14101]), in-game UI font memory leak ([#14078]) -* Couple of adhoc fixes ([#14106], [#14117]) - -What's new in 1.11.0 -==================== -* Lots of minor bug fixes, crash fixes, and performance fixes and improvements. -* New Browse... button to allow opening SD cards on Android 11 -* Countless AdHoc networking fixes by ANR2ME, for example Dragon Ball Shin Budokai, PowerStone, - Bleach Heat The Soul 7, Kingdom Hearts, GTA: VCS and many more. -* Graphics issue with car reflections fixed in Outrun, Dirt 2 ([#13636], [#13640], [#13760]) -* Cut-off cards in Yu Gi Oh fixed ([#7124]). -* Numerous fixes to the builtin fonts by nassau-tk -* Added exception handler so PPSSPP stays alive if a game crashes ([#11795]/[#13092]) -* Desktop: Support for multiple instance multiplayer ([#13172], ...) -* Workaround for rendering bugs with flat shading in iOS 14 -* Multiple fixes to the IR interpreter ([#13897], ...) -* UI: New fullscreen button on desktop platforms, optional navigation sounds ([#13239]) -* Audio and multiple hangs fixes in UWP version ([#13792], ...) -* Partial microphone support ([#12336], ...) -* Workaround for wacky action mirroring bug in Hitman Reborn Battle Arena 2 ([#13706], [#13526]) -* Hardware texture upscaling for Vulkan, mipmap generation ([#13235], [#13514]) -* Added MMPX Vulkan texture upscaling shader ([#13986]) -* Depth texturing support in Vulkan and D3D11 ([#13262], [#13556], ...) -* Performance fix for Test Drive Unlimited ([#13355], ...) -* Allow rewind on mobile ([#13866]) -* Added option to disable on-screen messages ([#13695]) -* Added "Lower resolution for effects" on libretro ([#13654]) -* Allow chaining multiple post-processing shaders ([#12924]) -* Support for loading game-specific plugins ([#13335]) -* Fixed Assassin's Creed: Bloodlines Save issue on Android ([#12761]) -* Hanayaka Nari Wa ga Ichizoku: mono voices fixed ([#5213]) -* Additional fixed games: - * Namco Museum - Battle Collection, Vol 2 ([#9523], [#13297], [#13298]) - * Dream Club Portable (graphics bugs, GL and Vulkan) ([#6025]) - * Capcom Classic Collection Reloaded (stuck in return game) ([#4671]) - * Xyanide Resurrection (freezing) ([#8526]) - * Dissidia Final Fantasy Chinese (patched game, invalid address) ([#13204]) - * Crazy Taxi ([#13368]) - * Spiderman: Friend or Foe ([#13969]) - * Downstream Panic (US) (New Game crash) ([#13633]) - -What's new in 1.10.3 --------------------- -* Fix for control layout editor ([#13125]) - -What's new in 1.10.2 --------------------- -* More crashfixes ([#13094], [#13093]) -* Improve download performance and cancel behavior ([#13095]) -* Restore the removed I/O on Thread option ([#13096]) - -What's new in 1.10.1 --------------------- -* Fixes for common crashes ([#13077], [#13076], see [#13057]) -* Fix for offset rendering in D3D9 ([#13071]) - -What's new in 1.10.0 --------------------- -* Graphics and compatibility fixes ([#12800], [#12670], [#12635], [#12857], [#12941], [#11898], [#12695], more) -* Assorted minor performance improvements, game load speedup ([#12462], [#12652]) -* Screen inset (notch) support on Android ([#12779]) -* Analog stick support for menu navigation ([#12685]) -* Fixed audio glitches in SDL builds ([#12916], [#12920]) -* Support more languages in in-game dialogs ([#12702]). Croatian language added to PPSSPP. -* Simple multiplayer chat ([#12667]) -* More advanced postprocessing (multipass, parameters) ([#12905], [#12901]) -* Add PPSSPP-specific CWCheat ([#12816], [#12912]) -* Reintroduce Cardboard VR, allow more resolutions ([#12449], [#8714]) -* Fix some crashes ([#12908], [#12876]) -* Ghost in the Shell graphics fixed (JIT inaccuracy with inf * 0) ([#12519]) -* Mac build now supports Vulkan on top of MoltenVK ([#12583]) -* Raspberry Pi 4 EGL crash fixed ([#12474]) -* VSync now supported on all backends, frame duplication option added for 30 Hz games ([#12659], [#12602]) -* Camera supported on Windows, Linux and Mac (still no microphone though) ([#12572], [#12580], [#12607]) -* Darkstalkers fixed and working through software rendering. SW rendering fixed on GLES 2.0 ([#12443], [#12898]) -* Hot Shots Golf slowdown and flicker on Vulkan fixed ([#12873], [#12746]) -* Pangya Golf crashes and hangs fixed ([#12718]) -* Allow rebinding of right touch screen analog ([#12486]) -* Add option to prevent mipmaps from being dumped ([#12818]) -* Tilt control now have a base radius to help with deadzone ([#12756]) -* Mappable auto rotating analog stick to pass some game checks ([#12749]) -* Touch control position can now be snapped to a grid ([#12517]) -* HiDPI retina display support ([#12552]) -* Rapid-fire on touch control ([#12601]) -* Toggle mute button ([#12643]) -* Add option to resize game icons and more ([#12646], [#12637]) -* Frames in-flight now configurable to reduce input lag at the cost of speed ([#12660]) -* Add toggle mode to combo button ([#12623]) -* SDL mouse support, Qt menu upgrades ([#12612], [#12817]) -* Real support for Chinese patched version of Hatsune Miku Project Diva Extend ([#13007]) -* Some minor kernel module support ([#13028], [#12225], [#13026], [#13004], [#13038], [#13023]) -* Fixed fullscreen toggling with Vulkan in SDL builds ([#11974]) - Looking for [older news](history.md)? @@ -281,120 +183,6 @@ Credit goes to: [comment]: # (LINK_LIST_BEGIN_HERE) -[#13125]: https://github.com/hrydgard/ppsspp/issues/13125 "Refactor and fix touch control layout screen for notch" -[#13094]: https://github.com/hrydgard/ppsspp/issues/13094 "Camera initialization crash fix" -[#13093]: https://github.com/hrydgard/ppsspp/issues/13093 "Add a try/catch to Android camera device listing." -[#13095]: https://github.com/hrydgard/ppsspp/issues/13095 "http: Check cancel flag more often" -[#13096]: https://github.com/hrydgard/ppsspp/issues/13096 "Revert \"Remove the I/O on Thread option - treat it as always on.\"" -[#13077]: https://github.com/hrydgard/ppsspp/issues/13077 "SaveState: Make sure to default init net data" -[#13076]: https://github.com/hrydgard/ppsspp/issues/13076 "Add some excessive null checks to GameScreen::render()" -[#13057]: https://github.com/hrydgard/ppsspp/issues/13057 "The 1.10 Android mystery crash thread!" -[#13071]: https://github.com/hrydgard/ppsspp/issues/13071 "D3D9: Fix a sign mistake generating the projection matrix." -[#12800]: https://github.com/hrydgard/ppsspp/issues/12800 "x86jit: Force INF * 0 to +NAN" -[#12670]: https://github.com/hrydgard/ppsspp/issues/12670 "Attempts to replace 0 frame width with valid frame width.(sceMpegAvcCsc)" -[#12635]: https://github.com/hrydgard/ppsspp/issues/12635 "Kernel: Delay better in sceKernelReferThreadStatus" -[#12857]: https://github.com/hrydgard/ppsspp/issues/12857 "Mumbo Jumbo games freeze on loading screen since v1.6" -[#12941]: https://github.com/hrydgard/ppsspp/issues/12941 "Vulkan: Deal with the reformat clear better" -[#11898]: https://github.com/hrydgard/ppsspp/issues/11898 "Strike Witches - Hakugin no Tsubasa missing intro video" -[#12695]: https://github.com/hrydgard/ppsspp/issues/12695 "New heuristic for getting rid of unnecessary \"antialias-lines\"." -[#12462]: https://github.com/hrydgard/ppsspp/issues/12462 "Vulkan: Enable renderpass merging for all games" -[#12652]: https://github.com/hrydgard/ppsspp/issues/12652 "ScanForFunctions: Speed up game loading" -[#12779]: https://github.com/hrydgard/ppsspp/issues/12779 "Support drawing around notches on Android displays. Fixes #12261" -[#12685]: https://github.com/hrydgard/ppsspp/issues/12685 "UI: Simple joystick navigation. Fixes #10996." -[#12916]: https://github.com/hrydgard/ppsspp/issues/12916 "More audio buffering fixes (primarily affects SDL)" -[#12920]: https://github.com/hrydgard/ppsspp/issues/12920 "Remove the Audio Resampling setting (now always on)." -[#12702]: https://github.com/hrydgard/ppsspp/issues/12702 "PPGe: Use TextDrawer for save UI if available" -[#12667]: https://github.com/hrydgard/ppsspp/issues/12667 "Chat feature based on Adenovan's Rechat branch" -[#12905]: https://github.com/hrydgard/ppsspp/issues/12905 "Allow chained post-processing shaders" -[#12901]: https://github.com/hrydgard/ppsspp/issues/12901 "Post shader setting uniform" -[#12816]: https://github.com/hrydgard/ppsspp/issues/12816 "Implement Xinput vibration CWCheat (PPSSPP specific 0xA code type)" -[#12912]: https://github.com/hrydgard/ppsspp/issues/12912 "Add CWCHEAT for postprocessing" -[#12449]: https://github.com/hrydgard/ppsspp/issues/12449 "Reintroduce Cardboard VR" -[#8714]: https://github.com/hrydgard/ppsspp/issues/8714 "Allow > 5x PSP resolution for devices like iPad Pro 12.9" -[#12908]: https://github.com/hrydgard/ppsspp/issues/12908 "Fix \"Improved compatibility of sceGeListEnQueue: verify that stackDepth < 256\"" -[#12876]: https://github.com/hrydgard/ppsspp/issues/12876 "Windows: Add safety checks to WASAPI code" -[#12519]: https://github.com/hrydgard/ppsspp/issues/12519 "Ghost In The Shell - Stand Alone Complex (ULUS10020) - Black Textures and missing screens." -[#12583]: https://github.com/hrydgard/ppsspp/issues/12583 "macOS: Initial support for vulkan on macOS ( MoltenVK )" -[#12474]: https://github.com/hrydgard/ppsspp/issues/12474 "Egl bug on rpi4 with master mesa?" -[#12659]: https://github.com/hrydgard/ppsspp/issues/12659 "Support vsync in all hardware backends, support runtime update" -[#12602]: https://github.com/hrydgard/ppsspp/issues/12602 "Add option to improve frame pacing through duplicate frames if below 60hz." -[#12572]: https://github.com/hrydgard/ppsspp/issues/12572 "Add camera support for windows." -[#12580]: https://github.com/hrydgard/ppsspp/issues/12580 "Add camera support for linux (V4L2)" -[#12607]: https://github.com/hrydgard/ppsspp/issues/12607 "QT API for camera (Linux/macOS)" -[#12443]: https://github.com/hrydgard/ppsspp/issues/12443 "Darkstalkers Chronicle: Add specializations and speedhacks to get it kinda playable" -[#12898]: https://github.com/hrydgard/ppsspp/issues/12898 "[Android] [Mali GPU] [OpenGL] Lastest build blackscreen on buffered rendering mode" -[#12873]: https://github.com/hrydgard/ppsspp/issues/12873 "Vulkan: Framebuffer manager: Use an allocator for \"MakePixelTexture\" images." -[#12746]: https://github.com/hrydgard/ppsspp/issues/12746 "GPU: Assume a scissor of 481x273 is a mistake" -[#12718]: https://github.com/hrydgard/ppsspp/issues/12718 "Vpl: Correct allocation order when splitting block" -[#12486]: https://github.com/hrydgard/ppsspp/issues/12486 "Rebindable touch right analog" -[#12818]: https://github.com/hrydgard/ppsspp/issues/12818 "Add option to prevent Mipmaps from being dumped" -[#12756]: https://github.com/hrydgard/ppsspp/issues/12756 "Skip deadzone option on tilt" -[#12749]: https://github.com/hrydgard/ppsspp/issues/12749 "Auto rotating analog" -[#12517]: https://github.com/hrydgard/ppsspp/issues/12517 "Touch control grid snap" -[#12552]: https://github.com/hrydgard/ppsspp/issues/12552 "Qt/macOS: enable HiDPI ( retina display ) support" -[#12601]: https://github.com/hrydgard/ppsspp/issues/12601 "Add rapid fire to touch control" -[#12643]: https://github.com/hrydgard/ppsspp/issues/12643 "Toggle mute button" -[#12646]: https://github.com/hrydgard/ppsspp/issues/12646 "Resizable game icons" -[#12637]: https://github.com/hrydgard/ppsspp/issues/12637 "Region flag and game ID on game selection screen" -[#12660]: https://github.com/hrydgard/ppsspp/issues/12660 "GPU: Add setting to control inflight frame usage" -[#12623]: https://github.com/hrydgard/ppsspp/issues/12623 "Add toggle flag to combo button" -[#12612]: https://github.com/hrydgard/ppsspp/issues/12612 "SDL analog mouse input" -[#12817]: https://github.com/hrydgard/ppsspp/issues/12817 "Unification of the menu of Linux and Windows versions" -[#13007]: https://github.com/hrydgard/ppsspp/issues/13007 "Real support \"Hatsune Miku Project Diva Extend\" chinese patched version" -[#13028]: https://github.com/hrydgard/ppsspp/issues/13028 "Real support Code Geass: Lost Colors chinese patched version" -[#12225]: https://github.com/hrydgard/ppsspp/issues/12225 "Rebased: Wrap some SysMemForKernel's nids, fixing #7960" -[#13026]: https://github.com/hrydgard/ppsspp/issues/13026 "Add some ThreadManForKernel nids" -[#13004]: https://github.com/hrydgard/ppsspp/issues/13004 "Warp some ThreadManForKernel and sceKernelExitVSHKernel" -[#13038]: https://github.com/hrydgard/ppsspp/issues/13038 "Add sysclib_strncmp,sysclib_memmove" -[#13023]: https://github.com/hrydgard/ppsspp/issues/13023 "Add sysclib_strstr" -[#11974]: https://github.com/hrydgard/ppsspp/issues/11974 "[Linux] [Vulkan] Toggle fullscreen doesn't update display properly" -[#13636]: https://github.com/hrydgard/ppsspp/issues/13636 "Reinterpret framebuffer formats as needed. Outrun reflections partial fix" -[#13640]: https://github.com/hrydgard/ppsspp/issues/13640 "Fix car reflections in Outrun" -[#13760]: https://github.com/hrydgard/ppsspp/issues/13760 "Fix car lighting issues in DiRT 2." -[#7124]: https://github.com/hrydgard/ppsspp/issues/7124 "Yu-Gi-Oh! GX Tag Force Card summoning (card cut-off / cropped)" -[#11795]: https://github.com/hrydgard/ppsspp/issues/11795 "Exception handler - catch bad memory accesses" -[#13092]: https://github.com/hrydgard/ppsspp/issues/13092 "Bad memory access handling improvements" -[#13172]: https://github.com/hrydgard/ppsspp/issues/13172 "Generalized multi-instance" -[#13897]: https://github.com/hrydgard/ppsspp/issues/13897 "LittleBigPlanet - Game Not Loading, Blue Screen (iOS, Unplayable)" -[#13239]: https://github.com/hrydgard/ppsspp/issues/13239 "Add sound effects for PPSSPP interface navigation" -[#13792]: https://github.com/hrydgard/ppsspp/issues/13792 "Fix UWP audio and a hang bug" -[#12336]: https://github.com/hrydgard/ppsspp/issues/12336 "Microphone support" -[#13706]: https://github.com/hrydgard/ppsspp/issues/13706 "Add back the old implementation of vfpu_sin/cos/sincos." -[#13526]: https://github.com/hrydgard/ppsspp/issues/13526 "VFPU: Compute sines and cosines in double precision." -[#13235]: https://github.com/hrydgard/ppsspp/issues/13235 "Vulkan: Allow custom texture upscaling shaders" -[#13514]: https://github.com/hrydgard/ppsspp/issues/13514 "Vulkan: Automatically generate mipmaps for replaced/scaled textures" -[#13986]: https://github.com/hrydgard/ppsspp/issues/13986 "Vulkan: Add MMPX upscaling texture shader" -[#13355]: https://github.com/hrydgard/ppsspp/issues/13355 "Refactor framebuffer attachment. Fixes Test Drive Unlimited performance" -[#13866]: https://github.com/hrydgard/ppsspp/issues/13866 "SaveState: Allow rewind on mobile" -[#13695]: https://github.com/hrydgard/ppsspp/issues/13695 "Add developer setting \"Show on-screen messages\". Uncheck to hide them." -[#13654]: https://github.com/hrydgard/ppsspp/issues/13654 "Expose the \"Lower resolution for effects\" setting in libretro." -[#12924]: https://github.com/hrydgard/ppsspp/issues/12924 "Postprocessing: User chain support" -[#13335]: https://github.com/hrydgard/ppsspp/issues/13335 "Support for loading game-specific plugins" -[#12761]: https://github.com/hrydgard/ppsspp/issues/12761 "[Android][OpenGL&Vulkan][Save issue] Assassin's Creed : Bloodlines (ULJM05571)" -[#5213]: https://github.com/hrydgard/ppsspp/issues/5213 "Hanayaka Nari Wa ga Ichizoku strange MP3 mono voice" -[#9523]: https://github.com/hrydgard/ppsspp/issues/9523 "Namco Museum - Battle Collection - ULUS100035 loading problem" -[#13297]: https://github.com/hrydgard/ppsspp/issues/13297 "Namco Museum Vol. 2 - ULJS00047 infinite loading in some game" -[#13298]: https://github.com/hrydgard/ppsspp/issues/13298 "Fix sceKernelExitThread" -[#6025]: https://github.com/hrydgard/ppsspp/issues/6025 "Dream Club Portable crash after select girl" -[#4671]: https://github.com/hrydgard/ppsspp/issues/4671 "Capcom Classic Collection Reloaded stuck in return game" -[#8526]: https://github.com/hrydgard/ppsspp/issues/8526 "Xyanide Resurrection freezing" -[#13204]: https://github.com/hrydgard/ppsspp/issues/13204 "Dissidia Final Fantasy Chinese patch invalid address" -[#13368]: https://github.com/hrydgard/ppsspp/issues/13368 "Reschedule after resuming thread from suspend." -[#13969]: https://github.com/hrydgard/ppsspp/issues/13969 "Io: Don't allow async close while async busy" -[#13633]: https://github.com/hrydgard/ppsspp/issues/13633 "Downstream Panic (US) New Game crashes" -[#13262]: https://github.com/hrydgard/ppsspp/issues/13262 "Implement texturing from depth buffers (Vulkan only so far)" -[#13556]: https://github.com/hrydgard/ppsspp/issues/13556 "D3D11 depth texture support" -[#14085]: https://github.com/hrydgard/ppsspp/issues/14085 "Handle exec addr errors better - don't let IgnoreBadMemoryAccesses skip dispatcher exceptions" -[#14089]: https://github.com/hrydgard/ppsspp/issues/14089 "GL: Call CreateDeviceObjects *after* updating render_." -[#14091]: https://github.com/hrydgard/ppsspp/issues/14091 "Only allow sceMpegGetAvcAu warmup for God Eater Series" -[#14092]: https://github.com/hrydgard/ppsspp/issues/14092 "SaveState: Prevent crash on bad cookie marker" -[#14101]: https://github.com/hrydgard/ppsspp/issues/14101 "Menu audio glitchfix" -[#14078]: https://github.com/hrydgard/ppsspp/issues/14078 "PPGe: Decimate text images properly" -[#14106]: https://github.com/hrydgard/ppsspp/issues/14106 "[Adhoc] Fix frozen (0 FPS) issue on Kao Challengers and Asterix & Obelix XX" -[#14117]: https://github.com/hrydgard/ppsspp/issues/14117 "[Adhoc] Fix lob" -[#14129]: https://github.com/hrydgard/ppsspp/issues/14129 "GPU: Force reinterpret off without copy image" -[#14134]: https://github.com/hrydgard/ppsspp/issues/14134 "Android: Ensure shutdown waits for render" -[#14132]: https://github.com/hrydgard/ppsspp/issues/14132 "Io: Truncate reads/writes to valid memory" [#11997]: https://github.com/hrydgard/ppsspp/issues/11997 "Android 12 scoped storage hell" [#5099]: https://github.com/hrydgard/ppsspp/issues/5099 "IOS touch controls problems." [#14053]: https://github.com/hrydgard/ppsspp/issues/14053 "Toggle screenshot minor issue." diff --git a/UI/GPUDriverTestScreen.cpp b/UI/GPUDriverTestScreen.cpp index 0320a5a858..b46fd7e42e 100644 --- a/UI/GPUDriverTestScreen.cpp +++ b/UI/GPUDriverTestScreen.cpp @@ -390,39 +390,39 @@ void GPUDriverTestScreen::DiscardTest() { { draw->GetVshaderPreset(VS_TEXTURE_COLOR_2D), discardFragShader_ }, inputLayout, depthStencilWrite, blendOffNoColor, rasterNoCull, &vsColBufDesc, }; - discardWriteDepthStencil_ = draw->CreateGraphicsPipeline(discardDesc); + discardWriteDepthStencil_ = draw->CreateGraphicsPipeline(discardDesc, "test"); discardDesc.depthStencil = depthWrite; - discardWriteDepth_ = draw->CreateGraphicsPipeline(discardDesc); + discardWriteDepth_ = draw->CreateGraphicsPipeline(discardDesc, "test"); discardDesc.depthStencil = stencilWrite; - discardWriteStencil_ = draw->CreateGraphicsPipeline(discardDesc); + discardWriteStencil_ = draw->CreateGraphicsPipeline(discardDesc, "test"); PipelineDesc testDesc{ Primitive::TRIANGLE_LIST, { draw->GetVshaderPreset(VS_TEXTURE_COLOR_2D), draw->GetFshaderPreset(FS_TEXTURE_COLOR_2D) }, inputLayout, stencilEqual, blendOff, rasterNoCull, &vsColBufDesc, }; - drawTestStencilEqual_ = draw->CreateGraphicsPipeline(testDesc); + drawTestStencilEqual_ = draw->CreateGraphicsPipeline(testDesc, "test"); testDesc.depthStencil = stencilEqualDepthAlways; - drawTestStencilEqualDepthAlways_ = draw->CreateGraphicsPipeline(testDesc); + drawTestStencilEqualDepthAlways_ = draw->CreateGraphicsPipeline(testDesc, "test"); testDesc.depthStencil = stencilNotEqual; - drawTestStencilNotEqual_ = draw->CreateGraphicsPipeline(testDesc); + drawTestStencilNotEqual_ = draw->CreateGraphicsPipeline(testDesc, "test"); testDesc.depthStencil = stenciNotEqualDepthAlways; - drawTestStencilNotEqualDepthAlways_ = draw->CreateGraphicsPipeline(testDesc); + drawTestStencilNotEqualDepthAlways_ = draw->CreateGraphicsPipeline(testDesc, "test"); testDesc.depthStencil = stencilAlwaysDepthTestGreater; - drawTestStencilAlwaysDepthGreater_ = draw->CreateGraphicsPipeline(testDesc); + drawTestStencilAlwaysDepthGreater_ = draw->CreateGraphicsPipeline(testDesc, "test"); testDesc.depthStencil = stencilAlwaysDepthTestLessEqual; - drawTestStencilAlwaysDepthLessEqual_ = draw->CreateGraphicsPipeline(testDesc); + drawTestStencilAlwaysDepthLessEqual_ = draw->CreateGraphicsPipeline(testDesc, "test"); testDesc.depthStencil = depthTestGreater; - drawTestDepthGreater_ = draw->CreateGraphicsPipeline(testDesc); + drawTestDepthGreater_ = draw->CreateGraphicsPipeline(testDesc, "test"); testDesc.depthStencil = depthTestLessEqual; - drawTestDepthLessEqual_ = draw->CreateGraphicsPipeline(testDesc); + drawTestDepthLessEqual_ = draw->CreateGraphicsPipeline(testDesc, "test"); inputLayout->Release(); blendOff->Release(); @@ -557,14 +557,14 @@ void GPUDriverTestScreen::ShaderTest() { { adrenoLogicDiscardVertShader_, adrenoLogicDiscardFragShader_ }, inputLayout, depthStencilOff, blendOff, rasterNoCull, &vsColBufDesc, }; - adrenoLogicDiscardPipeline_ = draw->CreateGraphicsPipeline(adrenoLogicDiscardDesc); + adrenoLogicDiscardPipeline_ = draw->CreateGraphicsPipeline(adrenoLogicDiscardDesc, "test"); PipelineDesc flatDesc{ Primitive::TRIANGLE_LIST, { flatVertShader_, flatFragShader_ }, inputLayout, depthStencilOff, blendOff, rasterNoCull, &vsColBufDesc, }; - flatShadingPipeline_ = draw->CreateGraphicsPipeline(flatDesc); + flatShadingPipeline_ = draw->CreateGraphicsPipeline(flatDesc, "test"); inputLayout->Release(); blendOff->Release(); diff --git a/UI/GameSettingsScreen.cpp b/UI/GameSettingsScreen.cpp index c559eb027c..6c702bd7f0 100644 --- a/UI/GameSettingsScreen.cpp +++ b/UI/GameSettingsScreen.cpp @@ -1888,6 +1888,7 @@ void DeveloperToolsScreen::CreateViews() { void DeveloperToolsScreen::onFinish(DialogResult result) { g_Config.Save("DeveloperToolsScreen::onFinish"); + NativeMessageReceived("gpu_resized", ""); } void GameSettingsScreen::CallbackRestoreDefaults(bool yes) { diff --git a/UI/MiscScreens.cpp b/UI/MiscScreens.cpp index f7e22a8f78..2d94bd2ffb 100644 --- a/UI/MiscScreens.cpp +++ b/UI/MiscScreens.cpp @@ -968,6 +968,7 @@ void CreditsScreen::render() { "ANR2ME", "adenovan", "iota97", + "Lubos", "", cr->T("specialthanks", "Special thanks to:"), specialthanksMaxim.c_str(), diff --git a/UI/NativeApp.cpp b/UI/NativeApp.cpp index 871e77de18..93b11fd53e 100644 --- a/UI/NativeApp.cpp +++ b/UI/NativeApp.cpp @@ -950,13 +950,13 @@ bool CreateGlobalPipelines() { inputLayout, depth, blendNormal, rasterNoCull, &vsTexColBufDesc, }; - colorPipeline = g_draw->CreateGraphicsPipeline(colorDesc); + colorPipeline = g_draw->CreateGraphicsPipeline(colorDesc, "global_color"); if (!colorPipeline) { // Something really critical is wrong, don't care much about correct releasing of the states. return false; } - texColorPipeline = g_draw->CreateGraphicsPipeline(texColorDesc); + texColorPipeline = g_draw->CreateGraphicsPipeline(texColorDesc, "global_texcolor"); if (!texColorPipeline) { // Something really critical is wrong, don't care much about correct releasing of the states. return false; diff --git a/UWP/GPU_UWP/GPU_UWP.vcxproj b/UWP/GPU_UWP/GPU_UWP.vcxproj index 277526509c..87aac4d38b 100644 --- a/UWP/GPU_UWP/GPU_UWP.vcxproj +++ b/UWP/GPU_UWP/GPU_UWP.vcxproj @@ -413,6 +413,7 @@ + @@ -475,6 +476,7 @@ + diff --git a/UWP/GPU_UWP/GPU_UWP.vcxproj.filters b/UWP/GPU_UWP/GPU_UWP.vcxproj.filters index 2a797c0d2e..dbce632981 100644 --- a/UWP/GPU_UWP/GPU_UWP.vcxproj.filters +++ b/UWP/GPU_UWP/GPU_UWP.vcxproj.filters @@ -32,6 +32,7 @@ + @@ -89,6 +90,7 @@ + diff --git a/Windows/GEDebugger/CtrlDisplayListView.cpp b/Windows/GEDebugger/CtrlDisplayListView.cpp index 6b521c4996..eaaa8577f8 100644 --- a/Windows/GEDebugger/CtrlDisplayListView.cpp +++ b/Windows/GEDebugger/CtrlDisplayListView.cpp @@ -1,5 +1,7 @@ #include #include +#include "Common/Data/Encoding/Utf8.h" +#include "Common/StringUtils.h" #include "Common/System/Display.h" #include "Windows/GEDebugger/CtrlDisplayListView.h" #include "Windows/GEDebugger/GEDebugger.h" @@ -265,6 +267,17 @@ void CtrlDisplayListView::toggleBreakpoint() SendMessage(GetParent(wnd),WM_GEDBG_TOGGLEPCBREAKPOINT,curAddress,0); } +void CtrlDisplayListView::PromptBreakpointCond() { + std::string expression; + GPUBreakpoints::GetAddressBreakpointCond(curAddress, &expression); + if (!InputBox_GetString(GetModuleHandle(NULL), wnd, L"Expression", expression, expression)) + return; + + std::string error; + if (!GPUBreakpoints::SetAddressBreakpointCond(curAddress, expression, &error)) + MessageBox(wnd, ConvertUTF8ToWString(error).c_str(), L"Invalid expression", MB_OK | MB_ICONEXCLAMATION); +} + void CtrlDisplayListView::onMouseDown(WPARAM wParam, LPARAM lParam, int button) { int y = HIWORD(lParam); @@ -296,6 +309,9 @@ void CtrlDisplayListView::onMouseUp(WPARAM wParam, LPARAM lParam, int button) { if (button == 2) { + HMENU menu = GetContextMenu(ContextMenuID::DISPLAYLISTVIEW); + EnableMenuItem(menu, ID_GEDBG_SETCOND, GPUBreakpoints::IsAddressBreakpoint(curAddress) ? MF_ENABLED : MF_GRAYED); + switch (TriggerContextMenu(ContextMenuID::DISPLAYLISTVIEW, wnd, ContextPoint::FromEvent(lParam))) { case ID_DISASM_GOTOINMEMORYVIEW: @@ -306,6 +322,9 @@ void CtrlDisplayListView::onMouseUp(WPARAM wParam, LPARAM lParam, int button) toggleBreakpoint(); redraw(); break; + case ID_GEDBG_SETCOND: + PromptBreakpointCond(); + break; case ID_DISASM_COPYINSTRUCTIONDISASM: { int space = 256 * (selectRangeEnd - selectRangeStart) / instructionSize; @@ -369,15 +388,23 @@ void CtrlDisplayListView::onMouseUp(WPARAM wParam, LPARAM lParam, int button) break; case ID_GEDBG_GOTOADDR: { - u32 newAddress = curAddress; - if (!InputBox_GetHex(GetModuleHandle(NULL), wnd, L"Address", curAddress, newAddress)) { + std::string expression = StringFromFormat("%08x", curAddress); + if (!InputBox_GetString(GetModuleHandle(NULL), wnd, L"Address", expression, expression, true)) { break; } - if (Memory::IsValidAddress(newAddress)) { - setCurAddress(newAddress); - scrollAddressIntoView(); - redraw(); + uint32_t newAddress = curAddress; + if (!GPUDebugExecExpression(gpuDebug, expression.c_str(), newAddress)) { + MessageBox(wnd, ConvertUTF8ToWString(getExpressionError()).c_str(), L"Invalid expression", MB_OK | MB_ICONEXCLAMATION); + break; } + if (!Memory::IsValidAddress(newAddress)) { + MessageBox(wnd, L"Address not in valid memory", L"Invalid address", MB_OK | MB_ICONEXCLAMATION); + break; + } + + setCurAddress(newAddress); + scrollAddressIntoView(); + redraw(); } break; } diff --git a/Windows/GEDebugger/CtrlDisplayListView.h b/Windows/GEDebugger/CtrlDisplayListView.h index fe605f799e..28adfdd371 100644 --- a/Windows/GEDebugger/CtrlDisplayListView.h +++ b/Windows/GEDebugger/CtrlDisplayListView.h @@ -30,6 +30,8 @@ class CtrlDisplayListView } pixelPositions; void toggleBreakpoint(); + void PromptBreakpointCond(); + public: CtrlDisplayListView(HWND _wnd); ~CtrlDisplayListView(); diff --git a/Windows/GEDebugger/GEDebugger.cpp b/Windows/GEDebugger/GEDebugger.cpp index 7c78dcf80e..62026e6f07 100644 --- a/Windows/GEDebugger/GEDebugger.cpp +++ b/Windows/GEDebugger/GEDebugger.cpp @@ -21,7 +21,7 @@ #include #include -#include +#include "Common/CommonWindows.h" #include #include "Common/Data/Convert/ColorConv.h" @@ -1114,7 +1114,13 @@ BOOL CGEDebugger::DlgProc(UINT message, WPARAM wParam, LPARAM lParam) { bool temp; bool isBreak = IsAddressBreakpoint(pc, temp); if (isBreak && !temp) { - RemoveAddressBreakpoint(pc); + if (GetAddressBreakpointCond(pc, nullptr)) { + int ret = MessageBox(m_hDlg, L"This breakpoint has a custom condition.\nDo you want to remove it?", L"Confirmation", MB_YESNO); + if (ret == IDYES) + RemoveAddressBreakpoint(pc); + } else { + RemoveAddressBreakpoint(pc); + } } else { AddAddressBreakpoint(pc); } diff --git a/Windows/GEDebugger/TabState.cpp b/Windows/GEDebugger/TabState.cpp index 9d6735aabd..63a7199ed6 100644 --- a/Windows/GEDebugger/TabState.cpp +++ b/Windows/GEDebugger/TabState.cpp @@ -18,8 +18,9 @@ #include #include "Common/CommonFuncs.h" #include "Common/CommonTypes.h" -#include "Common/Log.h" +#include "Common/Data/Encoding/Utf8.h" #include "Common/Data/Text/Parsers.h" +#include "Common/Log.h" #include "Common/StringUtils.h" #include "Windows/resource.h" #include "Windows/InputBox.h" @@ -62,6 +63,7 @@ enum CmdFormatType { CMD_FMT_XY, CMD_FMT_XYXY, CMD_FMT_XYZ, + CMD_FMT_XYPLUS1, CMD_FMT_TEXSIZE, CMD_FMT_F16_XY, CMD_FMT_VERTEXTYPE, @@ -232,7 +234,7 @@ static const TabStateRow stateSettingsRows[] = { { L"Transfer src pos", GE_CMD_TRANSFERSRCPOS, CMD_FMT_XY }, { L"Transfer dst", GE_CMD_TRANSFERDST, CMD_FMT_PTRWIDTH, 0, GE_CMD_TRANSFERDSTW }, { L"Transfer dst pos", GE_CMD_TRANSFERDSTPOS, CMD_FMT_XY }, - { L"Transfer size", GE_CMD_TRANSFERSIZE, CMD_FMT_XY }, + { L"Transfer size", GE_CMD_TRANSFERSIZE, CMD_FMT_XYPLUS1 }, { L"Vertex type", GE_CMD_VERTEXTYPE, CMD_FMT_VERTEXTYPE }, { L"Offset addr", GE_CMD_OFFSETADDR, CMD_FMT_OFFSETADDR }, { L"Vertex addr", GE_CMD_VADDR, CMD_FMT_VADDR }, @@ -265,6 +267,14 @@ static const TabStateRow stateSettingsRows[] = { { L"Dither 1", GE_CMD_DITH1, CMD_FMT_HEX, GE_CMD_DITHERENABLE }, { L"Dither 2", GE_CMD_DITH2, CMD_FMT_HEX, GE_CMD_DITHERENABLE }, { L"Dither 3", GE_CMD_DITH3, CMD_FMT_HEX, GE_CMD_DITHERENABLE }, + { L"Imm vertex XY", GE_CMD_VSCX, CMD_FMT_F16_XY, 0, GE_CMD_VSCY }, + { L"Imm vertex Z", GE_CMD_VSCZ, CMD_FMT_HEX }, + { L"Imm vertex tex STQ", GE_CMD_VTCS, CMD_FMT_XYZ, 0, GE_CMD_VTCT, GE_CMD_VTCQ }, + { L"Imm vertex color0", GE_CMD_VCV, CMD_FMT_HEX }, + { L"Imm vertex color1", GE_CMD_VSCV, CMD_FMT_HEX }, + { L"Imm vertex fog", GE_CMD_VFC, CMD_FMT_HEX }, + // TODO: Format? + { L"Imm vertex prim", GE_CMD_VAP, CMD_FMT_HEX }, }; // TODO: Commands not present in the above lists (some because they don't have meaningful values...): @@ -367,6 +377,14 @@ void FormatStateRow(wchar_t *dest, const TabStateRow &info, u32 value, bool enab } break; + case CMD_FMT_XYPLUS1: + { + int x = value & 0x3FF; + int y = value >> 10; + swprintf(dest, 255, L"%d,%d", x + 1, y + 1); + } + break; + case CMD_FMT_XYXY: { int x1 = value & 0x3FF; @@ -900,7 +918,13 @@ void CtrlStateValues::OnDoubleClick(int row, int column) { const auto info = rows_[row]; if (column == STATEVALUES_COL_BREAKPOINT) { - SetItemState(row, ToggleBreakpoint(info) ? 1 : 0); + bool proceed = true; + if (GetCmdBreakpointCond(info.cmd, nullptr)) { + int ret = MessageBox(GetHandle(), L"This breakpoint has a custom condition.\nDo you want to remove it?", L"Confirmation", MB_YESNO); + proceed = ret == IDYES; + } + if (proceed) + SetItemState(row, ToggleBreakpoint(info) ? 1 : 0); return; } @@ -960,6 +984,7 @@ void CtrlStateValues::OnRightClick(int row, int column, const POINT &point) { HMENU subMenu = GetContextMenu(ContextMenuID::GEDBG_STATE); SetMenuDefaultItem(subMenu, ID_REGLIST_CHANGE, FALSE); + EnableMenuItem(subMenu, ID_GEDBG_SETCOND, GPUBreakpoints::IsCmdBreakpoint(info.cmd) ? MF_ENABLED : MF_GRAYED); // Ehh, kinda ugly. if (!watchList.empty() && rows_ == &watchList[0]) { @@ -975,8 +1000,19 @@ void CtrlStateValues::OnRightClick(int row, int column, const POINT &point) { switch (TriggerContextMenu(ContextMenuID::GEDBG_STATE, GetHandle(), ContextPoint::FromClient(point))) { - case ID_DISASM_TOGGLEBREAKPOINT: - SetItemState(row, ToggleBreakpoint(info) ? 1 : 0); + case ID_DISASM_TOGGLEBREAKPOINT: { + bool proceed = true; + if (GetCmdBreakpointCond(info.cmd, nullptr)) { + int ret = MessageBox(GetHandle(), L"This breakpoint has a custom condition.\nDo you want to remove it?", L"Confirmation", MB_YESNO); + proceed = ret == IDYES; + } + if (proceed) + SetItemState(row, ToggleBreakpoint(info) ? 1 : 0); + break; + } + + case ID_GEDBG_SETCOND: + PromptBreakpointCond(info); break; case ID_DISASM_COPYINSTRUCTIONHEX: { @@ -1043,6 +1079,24 @@ bool CtrlStateValues::RowValuesChanged(int row) { return false; } +void CtrlStateValues::PromptBreakpointCond(const TabStateRow &info) { + std::string expression; + GPUBreakpoints::GetCmdBreakpointCond(info.cmd, &expression); + if (!InputBox_GetString(GetModuleHandle(NULL), GetHandle(), L"Expression", expression, expression)) + return; + + std::string error; + if (!GPUBreakpoints::SetCmdBreakpointCond(info.cmd, expression, &error)) { + MessageBox(GetHandle(), ConvertUTF8ToWString(error).c_str(), L"Invalid expression", MB_OK | MB_ICONEXCLAMATION); + } else { + if (info.otherCmd) + GPUBreakpoints::SetCmdBreakpointCond(info.otherCmd, expression, &error); + if (info.otherCmd2) + GPUBreakpoints::SetCmdBreakpointCond(info.otherCmd2, expression, &error); + } + +} + TabStateValues::TabStateValues(const TabStateRow *rows, int rowCount, LPCSTR dialogID, HINSTANCE _hInstance, HWND _hParent) : Dialog(dialogID, _hInstance, _hParent) { values = new CtrlStateValues(rows, rowCount, GetDlgItem(m_hDlg, IDC_GEDBG_VALUES)); diff --git a/Windows/GEDebugger/TabState.h b/Windows/GEDebugger/TabState.h index dbc1558fa0..6992af14be 100644 --- a/Windows/GEDebugger/TabState.h +++ b/Windows/GEDebugger/TabState.h @@ -47,6 +47,7 @@ protected: private: bool RowValuesChanged(int row); void SetCmdValue(u32 op); + void PromptBreakpointCond(const TabStateRow &info); const TabStateRow *rows_; int rowCount_; diff --git a/Windows/GEDebugger/TabVertices.cpp b/Windows/GEDebugger/TabVertices.cpp index 0576b96032..f7ab9af7ac 100644 --- a/Windows/GEDebugger/TabVertices.cpp +++ b/Windows/GEDebugger/TabVertices.cpp @@ -17,6 +17,7 @@ #include #include "Common/CommonTypes.h" +#include "Common/Data/Encoding/Utf8.h" #include "Common/StringUtils.h" #include "Core/System.h" #include "Windows/resource.h" @@ -550,23 +551,52 @@ static constexpr MatrixCmdPair matrixCmds[] = { { MATRIXLIST_ROW_COUNT, GE_CMD_NOP }, }; -void CtrlMatrixList::ToggleBreakpoint(int row) { +static const MatrixCmdPair *FindCmdPair(int row) { for (int i = 0; i < ARRAY_SIZE(matrixCmds) - 1; ++i) { if (row < matrixCmds[i].row || row >= matrixCmds[i + 1].row) continue; - // Okay, this command is in range. Toggle the actual breakpoint. - auto &info = matrixCmds[i]; - bool state = !GPUBreakpoints::IsCmdBreakpoint(info.cmd); - if (state) - GPUBreakpoints::AddCmdBreakpoint(info.cmd); - else - GPUBreakpoints::RemoveCmdBreakpoint(info.cmd); - - for (int r = matrixCmds[i].row; r < matrixCmds[i + 1].row; ++r) { - SetItemState(r, state ? 1 : 0); - } + return &matrixCmds[i]; } + return nullptr; +} + +void CtrlMatrixList::ToggleBreakpoint(int row) { + const MatrixCmdPair *info = FindCmdPair(row); + if (!info) + return; + + // Okay, this command is in range. Toggle the actual breakpoint. + bool state = !GPUBreakpoints::IsCmdBreakpoint(info->cmd); + if (state) { + GPUBreakpoints::AddCmdBreakpoint(info->cmd); + } else { + if (GPUBreakpoints::GetCmdBreakpointCond(info->cmd, nullptr)) { + int ret = MessageBox(GetHandle(), L"This breakpoint has a custom condition.\nDo you want to remove it?", L"Confirmation", MB_YESNO); + if (ret != IDYES) + return; + } + GPUBreakpoints::RemoveCmdBreakpoint(info->cmd); + } + + for (int r = info->row; r < (info + 1)->row; ++r) { + SetItemState(r, state ? 1 : 0); + } +} + +void CtrlMatrixList::PromptBreakpointCond(int row) { + const MatrixCmdPair *info = FindCmdPair(row); + if (!info) + return; + + std::string expression; + GPUBreakpoints::GetCmdBreakpointCond(info->cmd, &expression); + if (!InputBox_GetString(GetModuleHandle(NULL), GetHandle(), L"Expression", expression, expression)) + return; + + std::string error; + if (!GPUBreakpoints::SetCmdBreakpointCond(info->cmd, expression, &error)) + MessageBox(GetHandle(), ConvertUTF8ToWString(error).c_str(), L"Invalid expression", MB_OK | MB_ICONEXCLAMATION); } void CtrlMatrixList::OnDoubleClick(int row, int column) { @@ -624,18 +654,24 @@ void CtrlMatrixList::OnDoubleClick(int row, int column) { void CtrlMatrixList::OnRightClick(int row, int column, const POINT &point) { if (row >= GetRowCount()) return; + const MatrixCmdPair *info = FindCmdPair(row); POINT screenPt(point); ClientToScreen(GetHandle(), &screenPt); HMENU subMenu = GetContextMenu(ContextMenuID::GEDBG_MATRIX); SetMenuDefaultItem(subMenu, ID_REGLIST_CHANGE, FALSE); + EnableMenuItem(subMenu, ID_GEDBG_SETCOND, info && GPUBreakpoints::IsCmdBreakpoint(info->cmd) ? MF_ENABLED : MF_GRAYED); switch (TriggerContextMenu(ContextMenuID::GEDBG_MATRIX, GetHandle(), ContextPoint::FromClient(point))) { case ID_DISASM_TOGGLEBREAKPOINT: ToggleBreakpoint(row); break; + case ID_GEDBG_SETCOND: + PromptBreakpointCond(row); + break; + case ID_DISASM_COPYINSTRUCTIONDISASM: { float val; diff --git a/Windows/GEDebugger/TabVertices.h b/Windows/GEDebugger/TabVertices.h index 116f60f06c..0a1f48be0c 100644 --- a/Windows/GEDebugger/TabVertices.h +++ b/Windows/GEDebugger/TabVertices.h @@ -90,6 +90,7 @@ private: bool GetValue(const GPUgstate &state, int row, int col, float &val); bool ColChanged(const GPUgstate &lastState, const GPUgstate &state, int row, int col); void ToggleBreakpoint(int row); + void PromptBreakpointCond(int row); }; class TabMatrices : public Dialog { diff --git a/Windows/ppsspp.rc b/Windows/ppsspp.rc index 3bc7dfed34..9ffc1747f7 100644 --- a/Windows/ppsspp.rc +++ b/Windows/ppsspp.rc @@ -763,6 +763,7 @@ BEGIN MENUITEM "Jump to Cursor", ID_DISASM_SETPCTOHERE MENUITEM "Set Stall", ID_GEDBG_SETSTALLADDR MENUITEM "Toggle Breakpoint", ID_DISASM_TOGGLEBREAKPOINT + MENUITEM "Set Breakpoint Condition", ID_GEDBG_SETCOND MENUITEM SEPARATOR MENUITEM "Go to Displaylist PC", ID_GEDBG_GOTOPC MENUITEM "Go to Address...", ID_GEDBG_GOTOADDR @@ -777,6 +778,7 @@ BEGIN MENUITEM "Copy Entire Tab (Formatted)",ID_GEDBG_COPYALL MENUITEM SEPARATOR MENUITEM "Toggle Breakpoint", ID_DISASM_TOGGLEBREAKPOINT + MENUITEM "Set Breakpoint Condition", ID_GEDBG_SETCOND MENUITEM "Add Watch", ID_GEDBG_WATCH END POPUP "gepreviewoptions" @@ -792,6 +794,7 @@ BEGIN MENUITEM "Copy Entire Tab (Formatted)",ID_GEDBG_COPYALL MENUITEM SEPARATOR MENUITEM "Toggle Breakpoint", ID_DISASM_TOGGLEBREAKPOINT + MENUITEM "Set Breakpoint Condition", ID_GEDBG_SETCOND END POPUP "getaboptions" BEGIN diff --git a/Windows/resource.h b/Windows/resource.h index 13104152e9..9ba6bc7946 100644 --- a/Windows/resource.h +++ b/Windows/resource.h @@ -332,6 +332,7 @@ #define ID_GEDBG_SHOWONRIGHT 40220 #define ID_GEDBG_SHOWONTOPRIGHT 40221 #define IDC_GEDBG_STEPVSYNC 40222 +#define ID_GEDBG_SETCOND 40223 // Dummy option to let the buffered rendering hotkey cycle through all the options. @@ -345,7 +346,7 @@ #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 256 -#define _APS_NEXT_COMMAND_VALUE 40223 +#define _APS_NEXT_COMMAND_VALUE 40224 #define _APS_NEXT_CONTROL_VALUE 1202 #define _APS_NEXT_SYMED_VALUE 101 #endif diff --git a/android/AndroidManifest.xml b/android/AndroidManifest.xml index fbb5332b0d..bee1ccda15 100644 --- a/android/AndroidManifest.xml +++ b/android/AndroidManifest.xml @@ -3,8 +3,8 @@ xmlns:tools="http://schemas.android.com/tools" package="org.ppsspp.ppsspp" android:installLocation="auto" - android:versionCode="113010000" - android:versionName="1.13.1.0"> + android:versionCode="113020000" + android:versionName="1.13.2.0"> diff --git a/android/jni/Android.mk b/android/jni/Android.mk index f5d8ec375a..b47db9d5cc 100644 --- a/android/jni/Android.mk +++ b/android/jni/Android.mk @@ -351,6 +351,7 @@ EXEC_AND_LIB_FILES := \ $(SRC)/GPU/Common/VertexShaderGenerator.cpp \ $(SRC)/GPU/Debugger/Breakpoints.cpp \ $(SRC)/GPU/Debugger/Debugger.cpp \ + $(SRC)/GPU/Debugger/GECommandTable.cpp \ $(SRC)/GPU/Debugger/Playback.cpp \ $(SRC)/GPU/Debugger/Record.cpp \ $(SRC)/GPU/Debugger/Stepping.cpp \ diff --git a/assets/compat.ini b/assets/compat.ini index 976edb0959..3d2846d377 100644 --- a/assets/compat.ini +++ b/assets/compat.ini @@ -325,6 +325,11 @@ UCJS18036 = true UCAS40292 = true UCJS18053 = true +# Rewrite +# fixes softlocks, see #15904 +ULJM06364 = true +ULJM06365 = true + # Crash Tag Team Racing used to need it to pass checking memory stick screen. # ULES00168 = true # ULES00169 = true @@ -1294,3 +1299,6 @@ ULES01301 = true ULES00262 = true ULUS10064 = true ULKS46087 = true + +[AllowDownloadCLUT] +# Temporary compatibility option, while developing a GPU CLUT-from-framebuffer path. diff --git a/history.md b/history.md index b40eaba158..2191439617 100644 --- a/history.md +++ b/history.md @@ -1,5 +1,109 @@ This is history moved out from README.md, which was getting a bit long. +What's new in 1.11.3 +==================== +* Fix for graphics glitches in the on-screen keyboard + +What's new in 1.11.2 +==================== +* An additional few crash fixes ([#14129], [#14134], [#14132]) + +What's new in 1.11.1 +==================== +* A few crash fixes ([#14085], [#14089], [#14091], [#14092]), a few adhoc fixes +* Glitchy menu audio on some devices ([#14101]), in-game UI font memory leak ([#14078]) +* Couple of adhoc fixes ([#14106], [#14117]) + +What's new in 1.11.0 +==================== +* Lots of minor bug fixes, crash fixes, and performance fixes and improvements. +* New Browse... button to allow opening SD cards on Android 11 +* Countless AdHoc networking fixes by ANR2ME, for example Dragon Ball Shin Budokai, PowerStone, + Bleach Heat The Soul 7, Kingdom Hearts, GTA: VCS and many more. +* Graphics issue with car reflections fixed in Outrun, Dirt 2 ([#13636], [#13640], [#13760]) +* Cut-off cards in Yu Gi Oh fixed ([#7124]). +* Numerous fixes to the builtin fonts by nassau-tk +* Added exception handler so PPSSPP stays alive if a game crashes ([#11795]/[#13092]) +* Desktop: Support for multiple instance multiplayer ([#13172], ...) +* Workaround for rendering bugs with flat shading in iOS 14 +* Multiple fixes to the IR interpreter ([#13897], ...) +* UI: New fullscreen button on desktop platforms, optional navigation sounds ([#13239]) +* Audio and multiple hangs fixes in UWP version ([#13792], ...) +* Partial microphone support ([#12336], ...) +* Workaround for wacky action mirroring bug in Hitman Reborn Battle Arena 2 ([#13706], [#13526]) +* Hardware texture upscaling for Vulkan, mipmap generation ([#13235], [#13514]) +* Added MMPX Vulkan texture upscaling shader ([#13986]) +* Depth texturing support in Vulkan and D3D11 ([#13262], [#13556], ...) +* Performance fix for Test Drive Unlimited ([#13355], ...) +* Allow rewind on mobile ([#13866]) +* Added option to disable on-screen messages ([#13695]) +* Added "Lower resolution for effects" on libretro ([#13654]) +* Allow chaining multiple post-processing shaders ([#12924]) +* Support for loading game-specific plugins ([#13335]) +* Fixed Assassin's Creed: Bloodlines Save issue on Android ([#12761]) +* Hanayaka Nari Wa ga Ichizoku: mono voices fixed ([#5213]) +* Additional fixed games: + * Namco Museum - Battle Collection, Vol 2 ([#9523], [#13297], [#13298]) + * Dream Club Portable (graphics bugs, GL and Vulkan) ([#6025]) + * Capcom Classic Collection Reloaded (stuck in return game) ([#4671]) + * Xyanide Resurrection (freezing) ([#8526]) + * Dissidia Final Fantasy Chinese (patched game, invalid address) ([#13204]) + * Crazy Taxi ([#13368]) + * Spiderman: Friend or Foe ([#13969]) + * Downstream Panic (US) (New Game crash) ([#13633]) + +What's new in 1.10.3 +-------------------- +* Fix for control layout editor ([#13125]) + +What's new in 1.10.2 +-------------------- +* More crashfixes ([#13094], [#13093]) +* Improve download performance and cancel behavior ([#13095]) +* Restore the removed I/O on Thread option ([#13096]) + +What's new in 1.10.1 +-------------------- +* Fixes for common crashes ([#13077], [#13076], see [#13057]) +* Fix for offset rendering in D3D9 ([#13071]) + +What's new in 1.10.0 +-------------------- +* Graphics and compatibility fixes ([#12800], [#12670], [#12635], [#12857], [#12941], [#11898], [#12695], more) +* Assorted minor performance improvements, game load speedup ([#12462], [#12652]) +* Screen inset (notch) support on Android ([#12779]) +* Analog stick support for menu navigation ([#12685]) +* Fixed audio glitches in SDL builds ([#12916], [#12920]) +* Support more languages in in-game dialogs ([#12702]). Croatian language added to PPSSPP. +* Simple multiplayer chat ([#12667]) +* More advanced postprocessing (multipass, parameters) ([#12905], [#12901]) +* Add PPSSPP-specific CWCheat ([#12816], [#12912]) +* Reintroduce Cardboard VR, allow more resolutions ([#12449], [#8714]) +* Fix some crashes ([#12908], [#12876]) +* Ghost in the Shell graphics fixed (JIT inaccuracy with inf * 0) ([#12519]) +* Mac build now supports Vulkan on top of MoltenVK ([#12583]) +* Raspberry Pi 4 EGL crash fixed ([#12474]) +* VSync now supported on all backends, frame duplication option added for 30 Hz games ([#12659], [#12602]) +* Camera supported on Windows, Linux and Mac (still no microphone though) ([#12572], [#12580], [#12607]) +* Darkstalkers fixed and working through software rendering. SW rendering fixed on GLES 2.0 ([#12443], [#12898]) +* Hot Shots Golf slowdown and flicker on Vulkan fixed ([#12873], [#12746]) +* Pangya Golf crashes and hangs fixed ([#12718]) +* Allow rebinding of right touch screen analog ([#12486]) +* Add option to prevent mipmaps from being dumped ([#12818]) +* Tilt control now have a base radius to help with deadzone ([#12756]) +* Mappable auto rotating analog stick to pass some game checks ([#12749]) +* Touch control position can now be snapped to a grid ([#12517]) +* HiDPI retina display support ([#12552]) +* Rapid-fire on touch control ([#12601]) +* Toggle mute button ([#12643]) +* Add option to resize game icons and more ([#12646], [#12637]) +* Frames in-flight now configurable to reduce input lag at the cost of speed ([#12660]) +* Add toggle mode to combo button ([#12623]) +* SDL mouse support, Qt menu upgrades ([#12612], [#12817]) +* Real support for Chinese patched version of Hatsune Miku Project Diva Extend ([#13007]) +* Some minor kernel module support ([#13028], [#12225], [#13026], [#13004], [#13038], [#13023]) +* Fixed fullscreen toggling with Vulkan in SDL builds ([#11974]) + What's new in 1.9.0/1.9.3 ------------------------- * Sizing/touch fixes on Android @@ -565,4 +669,117 @@ go to see there http://forums.ppsspp.org/showthread.php?tid=3595&pid=59241#pid59 [#11307]: https://github.com/hrydgard/ppsspp/issues/11307 "Enable Discord integration for Mac and Linux." [#10909]: https://github.com/hrydgard/ppsspp/issues/10909 "WebSocket based debugger interface" [#11447]: https://github.com/hrydgard/ppsspp/issues/11447 "Avoid calling any GL calls during shutdown on Android. Should help #11063" -[#11350]: https://github.com/hrydgard/ppsspp/issues/11350 "TexCache: Optimize DXT3/DXT5 decode to single pass" \ No newline at end of file +[#11350]: https://github.com/hrydgard/ppsspp/issues/11350 "TexCache: Optimize DXT3/DXT5 decode to single pass" +[#13023]: https://github.com/hrydgard/ppsspp/issues/13023 "Add sysclib_strstr" +[#13038]: https://github.com/hrydgard/ppsspp/issues/13038 "Add sysclib_strncmp,sysclib_memmove" +[#13004]: https://github.com/hrydgard/ppsspp/issues/13004 "Warp some ThreadManForKernel and sceKernelExitVSHKernel" +[#13026]: https://github.com/hrydgard/ppsspp/issues/13026 "Add some ThreadManForKernel nids" +[#12225]: https://github.com/hrydgard/ppsspp/issues/12225 "Rebased: Wrap some SysMemForKernel's nids, fixing #7960" +[#13028]: https://github.com/hrydgard/ppsspp/issues/13028 "Real support Code Geass: Lost Colors chinese patched version" +[#13007]: https://github.com/hrydgard/ppsspp/issues/13007 "Real support \"Hatsune Miku Project Diva Extend\" chinese patched version" +[#12817]: https://github.com/hrydgard/ppsspp/issues/12817 "Unification of the menu of Linux and Windows versions" +[#12612]: https://github.com/hrydgard/ppsspp/issues/12612 "SDL analog mouse input" +[#12623]: https://github.com/hrydgard/ppsspp/issues/12623 "Add toggle flag to combo button" +[#12660]: https://github.com/hrydgard/ppsspp/issues/12660 "GPU: Add setting to control inflight frame usage" +[#12637]: https://github.com/hrydgard/ppsspp/issues/12637 "Region flag and game ID on game selection screen" +[#12646]: https://github.com/hrydgard/ppsspp/issues/12646 "Resizable game icons" +[#12643]: https://github.com/hrydgard/ppsspp/issues/12643 "Toggle mute button" +[#12601]: https://github.com/hrydgard/ppsspp/issues/12601 "Add rapid fire to touch control" +[#12552]: https://github.com/hrydgard/ppsspp/issues/12552 "Qt/macOS: enable HiDPI ( retina display ) support" +[#12517]: https://github.com/hrydgard/ppsspp/issues/12517 "Touch control grid snap" +[#12749]: https://github.com/hrydgard/ppsspp/issues/12749 "Auto rotating analog" +[#12756]: https://github.com/hrydgard/ppsspp/issues/12756 "Skip deadzone option on tilt" +[#12818]: https://github.com/hrydgard/ppsspp/issues/12818 "Add option to prevent Mipmaps from being dumped" +[#12486]: https://github.com/hrydgard/ppsspp/issues/12486 "Rebindable touch right analog" +[#12718]: https://github.com/hrydgard/ppsspp/issues/12718 "Vpl: Correct allocation order when splitting block" +[#12746]: https://github.com/hrydgard/ppsspp/issues/12746 "GPU: Assume a scissor of 481x273 is a mistake" +[#12873]: https://github.com/hrydgard/ppsspp/issues/12873 "Vulkan: Framebuffer manager: Use an allocator for \"MakePixelTexture\" images." +[#12898]: https://github.com/hrydgard/ppsspp/issues/12898 "[Android] [Mali GPU] [OpenGL] Lastest build blackscreen on buffered rendering mode" +[#12443]: https://github.com/hrydgard/ppsspp/issues/12443 "Darkstalkers Chronicle: Add specializations and speedhacks to get it kinda playable" +[#12607]: https://github.com/hrydgard/ppsspp/issues/12607 "QT API for camera (Linux/macOS)" +[#12580]: https://github.com/hrydgard/ppsspp/issues/12580 "Add camera support for linux (V4L2)" +[#12572]: https://github.com/hrydgard/ppsspp/issues/12572 "Add camera support for windows." +[#12602]: https://github.com/hrydgard/ppsspp/issues/12602 "Add option to improve frame pacing through duplicate frames if below 60hz." +[#12659]: https://github.com/hrydgard/ppsspp/issues/12659 "Support vsync in all hardware backends, support runtime update" +[#12474]: https://github.com/hrydgard/ppsspp/issues/12474 "Egl bug on rpi4 with master mesa?" +[#12583]: https://github.com/hrydgard/ppsspp/issues/12583 "macOS: Initial support for vulkan on macOS ( MoltenVK )" +[#12519]: https://github.com/hrydgard/ppsspp/issues/12519 "Ghost In The Shell - Stand Alone Complex (ULUS10020) - Black Textures and missing screens." +[#12876]: https://github.com/hrydgard/ppsspp/issues/12876 "Windows: Add safety checks to WASAPI code" +[#12908]: https://github.com/hrydgard/ppsspp/issues/12908 "Fix \"Improved compatibility of sceGeListEnQueue: verify that stackDepth < 256\"" +[#8714]: https://github.com/hrydgard/ppsspp/issues/8714 "Allow > 5x PSP resolution for devices like iPad Pro 12.9" +[#12449]: https://github.com/hrydgard/ppsspp/issues/12449 "Reintroduce Cardboard VR" +[#12912]: https://github.com/hrydgard/ppsspp/issues/12912 "Add CWCHEAT for postprocessing" +[#12816]: https://github.com/hrydgard/ppsspp/issues/12816 "Implement Xinput vibration CWCheat (PPSSPP specific 0xA code type)" +[#12901]: https://github.com/hrydgard/ppsspp/issues/12901 "Post shader setting uniform" +[#12905]: https://github.com/hrydgard/ppsspp/issues/12905 "Allow chained post-processing shaders" +[#12667]: https://github.com/hrydgard/ppsspp/issues/12667 "Chat feature based on Adenovan's Rechat branch" +[#12702]: https://github.com/hrydgard/ppsspp/issues/12702 "PPGe: Use TextDrawer for save UI if available" +[#12920]: https://github.com/hrydgard/ppsspp/issues/12920 "Remove the Audio Resampling setting (now always on)." +[#12916]: https://github.com/hrydgard/ppsspp/issues/12916 "More audio buffering fixes (primarily affects SDL)" +[#12685]: https://github.com/hrydgard/ppsspp/issues/12685 "UI: Simple joystick navigation. Fixes #10996." +[#12779]: https://github.com/hrydgard/ppsspp/issues/12779 "Support drawing around notches on Android displays. Fixes #12261" +[#12652]: https://github.com/hrydgard/ppsspp/issues/12652 "ScanForFunctions: Speed up game loading" +[#12462]: https://github.com/hrydgard/ppsspp/issues/12462 "Vulkan: Enable renderpass merging for all games" +[#12695]: https://github.com/hrydgard/ppsspp/issues/12695 "New heuristic for getting rid of unnecessary \"antialias-lines\"." +[#11898]: https://github.com/hrydgard/ppsspp/issues/11898 "Strike Witches - Hakugin no Tsubasa missing intro video" +[#12941]: https://github.com/hrydgard/ppsspp/issues/12941 "Vulkan: Deal with the reformat clear better" +[#12857]: https://github.com/hrydgard/ppsspp/issues/12857 "Mumbo Jumbo games freeze on loading screen since v1.6" +[#12635]: https://github.com/hrydgard/ppsspp/issues/12635 "Kernel: Delay better in sceKernelReferThreadStatus" +[#12670]: https://github.com/hrydgard/ppsspp/issues/12670 "Attempts to replace 0 frame width with valid frame width.(sceMpegAvcCsc)" +[#12800]: https://github.com/hrydgard/ppsspp/issues/12800 "x86jit: Force INF * 0 to +NAN" +[#13071]: https://github.com/hrydgard/ppsspp/issues/13071 "D3D9: Fix a sign mistake generating the projection matrix." +[#13076]: https://github.com/hrydgard/ppsspp/issues/13076 "Add some excessive null checks to GameScreen::render()" +[#13057]: https://github.com/hrydgard/ppsspp/issues/13057 "The 1.10 Android mystery crash thread!" +[#13077]: https://github.com/hrydgard/ppsspp/issues/13077 "SaveState: Make sure to default init net data" +[#13096]: https://github.com/hrydgard/ppsspp/issues/13096 "Revert \"Remove the I/O on Thread option - treat it as always on.\"" +[#13095]: https://github.com/hrydgard/ppsspp/issues/13095 "http: Check cancel flag more often" +[#13093]: https://github.com/hrydgard/ppsspp/issues/13093 "Add a try/catch to Android camera device listing." +[#13094]: https://github.com/hrydgard/ppsspp/issues/13094 "Camera initialization crash fix" +[#13125]: https://github.com/hrydgard/ppsspp/issues/13125 "Refactor and fix touch control layout screen for notch" +[#13633]: https://github.com/hrydgard/ppsspp/issues/13633 "Downstream Panic (US) New Game crashes" +[#13969]: https://github.com/hrydgard/ppsspp/issues/13969 "Io: Don't allow async close while async busy" +[#13368]: https://github.com/hrydgard/ppsspp/issues/13368 "Reschedule after resuming thread from suspend." +[#13204]: https://github.com/hrydgard/ppsspp/issues/13204 "Dissidia Final Fantasy Chinese patch invalid address" +[#8526]: https://github.com/hrydgard/ppsspp/issues/8526 "Xyanide Resurrection freezing" +[#4671]: https://github.com/hrydgard/ppsspp/issues/4671 "Capcom Classic Collection Reloaded stuck in return game" +[#6025]: https://github.com/hrydgard/ppsspp/issues/6025 "Dream Club Portable crash after select girl" +[#13298]: https://github.com/hrydgard/ppsspp/issues/13298 "Fix sceKernelExitThread" +[#13297]: https://github.com/hrydgard/ppsspp/issues/13297 "Namco Museum Vol. 2 - ULJS00047 infinite loading in some game" +[#9523]: https://github.com/hrydgard/ppsspp/issues/9523 "Namco Museum - Battle Collection - ULUS100035 loading problem" +[#5213]: https://github.com/hrydgard/ppsspp/issues/5213 "Hanayaka Nari Wa ga Ichizoku strange MP3 mono voice" +[#12761]: https://github.com/hrydgard/ppsspp/issues/12761 "[Android][OpenGL&Vulkan][Save issue] Assassin's Creed : Bloodlines (ULJM05571)" +[#13335]: https://github.com/hrydgard/ppsspp/issues/13335 "Support for loading game-specific plugins" +[#12924]: https://github.com/hrydgard/ppsspp/issues/12924 "Postprocessing: User chain support" +[#13654]: https://github.com/hrydgard/ppsspp/issues/13654 "Expose the \"Lower resolution for effects\" setting in libretro." +[#13695]: https://github.com/hrydgard/ppsspp/issues/13695 "Add developer setting \"Show on-screen messages\". Uncheck to hide them." +[#13866]: https://github.com/hrydgard/ppsspp/issues/13866 "SaveState: Allow rewind on mobile" +[#13355]: https://github.com/hrydgard/ppsspp/issues/13355 "Refactor framebuffer attachment. Fixes Test Drive Unlimited performance" +[#13556]: https://github.com/hrydgard/ppsspp/issues/13556 "D3D11 depth texture support" +[#13262]: https://github.com/hrydgard/ppsspp/issues/13262 "Implement texturing from depth buffers (Vulkan only so far)" +[#13986]: https://github.com/hrydgard/ppsspp/issues/13986 "Vulkan: Add MMPX upscaling texture shader" +[#13514]: https://github.com/hrydgard/ppsspp/issues/13514 "Vulkan: Automatically generate mipmaps for replaced/scaled textures" +[#13235]: https://github.com/hrydgard/ppsspp/issues/13235 "Vulkan: Allow custom texture upscaling shaders" +[#13526]: https://github.com/hrydgard/ppsspp/issues/13526 "VFPU: Compute sines and cosines in double precision." +[#13706]: https://github.com/hrydgard/ppsspp/issues/13706 "Add back the old implementation of vfpu_sin/cos/sincos." +[#12336]: https://github.com/hrydgard/ppsspp/issues/12336 "Microphone support" +[#13792]: https://github.com/hrydgard/ppsspp/issues/13792 "Fix UWP audio and a hang bug" +[#13239]: https://github.com/hrydgard/ppsspp/issues/13239 "Add sound effects for PPSSPP interface navigation" +[#13897]: https://github.com/hrydgard/ppsspp/issues/13897 "LittleBigPlanet - Game Not Loading, Blue Screen (iOS, Unplayable)" +[#13172]: https://github.com/hrydgard/ppsspp/issues/13172 "Generalized multi-instance" +[#13092]: https://github.com/hrydgard/ppsspp/issues/13092 "Bad memory access handling improvements" +[#11795]: https://github.com/hrydgard/ppsspp/issues/11795 "Exception handler - catch bad memory accesses" +[#7124]: https://github.com/hrydgard/ppsspp/issues/7124 "Yu-Gi-Oh! GX Tag Force Card summoning (card cut-off / cropped)" +[#13760]: https://github.com/hrydgard/ppsspp/issues/13760 "Fix car lighting issues in DiRT 2." +[#13640]: https://github.com/hrydgard/ppsspp/issues/13640 "Fix car reflections in Outrun" +[#13636]: https://github.com/hrydgard/ppsspp/issues/13636 "Reinterpret framebuffer formats as needed. Outrun reflections partial fix" +[#14117]: https://github.com/hrydgard/ppsspp/issues/14117 "[Adhoc] Fix lob" +[#14106]: https://github.com/hrydgard/ppsspp/issues/14106 "[Adhoc] Fix frozen (0 FPS) issue on Kao Challengers and Asterix & Obelix XX" +[#14078]: https://github.com/hrydgard/ppsspp/issues/14078 "PPGe: Decimate text images properly" +[#14101]: https://github.com/hrydgard/ppsspp/issues/14101 "Menu audio glitchfix" +[#14092]: https://github.com/hrydgard/ppsspp/issues/14092 "SaveState: Prevent crash on bad cookie marker" +[#14091]: https://github.com/hrydgard/ppsspp/issues/14091 "Only allow sceMpegGetAvcAu warmup for God Eater Series" +[#14089]: https://github.com/hrydgard/ppsspp/issues/14089 "GL: Call CreateDeviceObjects *after* updating render_." +[#14085]: https://github.com/hrydgard/ppsspp/issues/14085 "Handle exec addr errors better - don't let IgnoreBadMemoryAccesses skip dispatcher exceptions" +[#14132]: https://github.com/hrydgard/ppsspp/issues/14132 "Io: Truncate reads/writes to valid memory" +[#14134]: https://github.com/hrydgard/ppsspp/issues/14134 "Android: Ensure shutdown waits for render" +[#14129]: https://github.com/hrydgard/ppsspp/issues/14129 "GPU: Force reinterpret off without copy image" diff --git a/libretro/Makefile.common b/libretro/Makefile.common index cb195694be..ab2c4bfe1c 100644 --- a/libretro/Makefile.common +++ b/libretro/Makefile.common @@ -161,9 +161,6 @@ ifeq ($(PLATFORM_EXT), android) $(EXTDIR)/libzip/zip_source_file_stdio_named.c \ $(EXTDIR)/libzip/zip_random_unix.c endif - - SOURCES_C +=\ - $(COMMONDIR)/Math/fast/fast_matrix.c endif SOURCES_C += $(LIBRETRODIR)/ext/glew/glew.c @@ -311,7 +308,8 @@ SOURCES_CXX += \ $(COMMONDIR)/TimeUtil.cpp SOURCES_C +=\ - $(COMMONDIR)/GPU/OpenGL/gl3stub.c + $(COMMONDIR)/GPU/OpenGL/gl3stub.c \ + $(COMMONDIR)/Math/fast/fast_matrix.c SOURCES_CXX += \ $(GPUCOMMONDIR)/Draw2D.cpp \ @@ -335,6 +333,7 @@ SOURCES_CXX += \ $(COMMONDIR)/Data/Convert/ColorConv.cpp \ $(GPUDIR)/Debugger/Breakpoints.cpp \ $(GPUDIR)/Debugger/Debugger.cpp \ + $(GPUDIR)/Debugger/GECommandTable.cpp \ $(GPUDIR)/Debugger/Playback.cpp \ $(GPUDIR)/Debugger/Record.cpp \ $(GPUDIR)/Debugger/Stepping.cpp \ @@ -657,8 +656,7 @@ ifeq ($(WITH_DYNAREC),1) SOURCES_C += $(EXTDIR)/libpng17/arm/arm_init.c \ $(EXTDIR)/libpng17/arm/filter_neon_intrinsics.c - ASMFILES += $(COMMONDIR)/Math/fast/fast_matrix_neon.S \ - $(EXTDIR)/libpng17/arm/filter_neon.S + ASMFILES += $(EXTDIR)/libpng17/arm/filter_neon.S endif else ifneq (,$(findstring msvc,$(platform))) @@ -694,7 +692,6 @@ ifeq ($(WITH_DYNAREC),1) $(COREDIR)/MIPS/x86/RegCache.cpp \ $(COREDIR)/MIPS/x86/RegCacheFPU.cpp \ $(GPUDIR)/Common/VertexDecoderX86.cpp - SOURCES_C += $(COMMONDIR)/Math/fast/fast_matrix_sse.c endif endif #UDIS86 @@ -779,11 +776,8 @@ SOURCES_C += $(ZSTDDIR)/common/debug.c \ $(ZSTDDIR)/common/error_private.c \ $(ZSTDDIR)/common/fse_decompress.c \ $(ZSTDDIR)/common/pool.c \ - $(ZSTDDIR)/common/threading.c - -#SOURCES_C += $(ZSTDDIR)/common/xxhash.c - -SOURCES_C += \ + $(ZSTDDIR)/common/threading.c \ + $(ZSTDDIR)/common/xxhash.c \ $(ZSTDDIR)/common/zstd_common.c \ $(ZSTDDIR)/compress/fse_compress.c \ $(ZSTDDIR)/compress/hist.c \ @@ -807,6 +801,13 @@ SOURCES_C += \ $(ZSTDDIR)/dictBuilder/fastcover.c \ $(ZSTDDIR)/dictBuilder/zdict.c +# zstd only uses asm for Linux/macOS and GNUC. +ifneq ($(PLATFORM_EXT), win32) +ifeq ($(TARGET_ARCH),x86_64) +SOURCES_C += $(ZSTDDIR)/decompress/huf_decompress_amd64.S +endif +endif + ifneq ($(STATIC_LINKING), 1) SOURCES_C += \ $(EXTDIR)/zlib/adler32.c \ diff --git a/ppsspp.desktop.in b/ppsspp.desktop.in index 49debf93c0..05fd1e7348 100644 --- a/ppsspp.desktop.in +++ b/ppsspp.desktop.in @@ -4,4 +4,4 @@ Exec=@TargetBin@ Icon=ppsspp Type=Application Comment=ppsspp (fast and portable PSP emulator) -Categories=Game +Categories=Game;Emulator diff --git a/unittest/TestShaderGenerators.cpp b/unittest/TestShaderGenerators.cpp index d90d893ff3..8cf73cd8b4 100644 --- a/unittest/TestShaderGenerators.cpp +++ b/unittest/TestShaderGenerators.cpp @@ -30,27 +30,27 @@ bool GenerateFShader(FShaderID id, char *buffer, ShaderLanguage lang, Draw::Bugs case ShaderLanguage::GLSL_VULKAN: { ShaderLanguageDesc compat(ShaderLanguage::GLSL_VULKAN); - return GenerateFragmentShader(id, buffer, compat, bugs, &uniformMask, errorString); + return GenerateFragmentShader(id, buffer, compat, bugs, &uniformMask, nullptr, errorString); } case ShaderLanguage::GLSL_1xx: { ShaderLanguageDesc compat(ShaderLanguage::GLSL_1xx); - return GenerateFragmentShader(id, buffer, compat, bugs, &uniformMask, errorString); + return GenerateFragmentShader(id, buffer, compat, bugs, &uniformMask, nullptr, errorString); } case ShaderLanguage::GLSL_3xx: { ShaderLanguageDesc compat(ShaderLanguage::GLSL_1xx); - return GenerateFragmentShader(id, buffer, compat, bugs, &uniformMask, errorString); + return GenerateFragmentShader(id, buffer, compat, bugs, &uniformMask, nullptr, errorString); } case ShaderLanguage::HLSL_D3D9: { ShaderLanguageDesc compat(ShaderLanguage::HLSL_D3D9); - return GenerateFragmentShader(id, buffer, compat, bugs, &uniformMask, errorString); + return GenerateFragmentShader(id, buffer, compat, bugs, &uniformMask, nullptr, errorString); } case ShaderLanguage::HLSL_D3D11: { ShaderLanguageDesc compat(ShaderLanguage::HLSL_D3D11); - return GenerateFragmentShader(id, buffer, compat, bugs, &uniformMask, errorString); + return GenerateFragmentShader(id, buffer, compat, bugs, &uniformMask, nullptr, errorString); } default: return false; @@ -402,7 +402,6 @@ bool TestFragmentShaders() { // bits we don't need to test because they are irrelevant on d3d11 id.SetBit(FS_BIT_NO_DEPTH_CANNOT_DISCARD_STENCIL, false); - id.SetBit(FS_BIT_SHADER_DEPAL, false); // DX9 disabling: if (static_cast(id.Bits(FS_BIT_STENCIL_TO_ALPHA, 2)) == ReplaceAlphaType::REPLACE_ALPHA_DUALSOURCE)