From a7e388168df6a9695a6553bdeb7dd3e98b6bc1ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Wed, 17 Aug 2022 14:33:38 +0200 Subject: [PATCH 01/85] Typo fix --- GPU/Common/Draw2D.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GPU/Common/Draw2D.cpp b/GPU/Common/Draw2D.cpp index ccffd4e611..923300152d 100644 --- a/GPU/Common/Draw2D.cpp +++ b/GPU/Common/Draw2D.cpp @@ -176,7 +176,7 @@ void FramebufferManagerCommon::DrawStrip2D(Draw::Texture *tex, Draw2DVertex *ver return; } if (!draw2DPipelineDepth_) { - draw2DPipelineDepth_ = Create2DPipeline(&GenerateDraw2DFs); + draw2DPipelineDepth_ = Create2DPipeline(&GenerateDraw2DDepthFs); } draw_->BindPipeline(draw2DPipelineDepth_); break; From bd6f79e473c4c0d9e11d8f7fa02ad58f8698b195 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Wed, 17 Aug 2022 14:42:13 +0200 Subject: [PATCH 02/85] Fix the raster depth blit again, which I recently broke. --- Common/GPU/D3D9/thin3d_d3d9.cpp | 2 +- GPU/Common/Draw2D.cpp | 40 ++++++++++++++----------- GPU/Common/FramebufferManagerCommon.cpp | 5 ++++ GPU/Common/FramebufferManagerCommon.h | 2 +- 4 files changed, 29 insertions(+), 20 deletions(-) diff --git a/Common/GPU/D3D9/thin3d_d3d9.cpp b/Common/GPU/D3D9/thin3d_d3d9.cpp index 938789479c..e420646a40 100644 --- a/Common/GPU/D3D9/thin3d_d3d9.cpp +++ b/Common/GPU/D3D9/thin3d_d3d9.cpp @@ -665,7 +665,7 @@ D3D9Context::D3D9Context(IDirect3D9 *d3d, IDirect3D9Ex *d3dEx, int adapterId, ID caps_.tesselationShaderSupported = false; caps_.framebufferBlitSupported = true; caps_.framebufferCopySupported = false; - caps_.framebufferDepthBlitSupported = true; + caps_.framebufferDepthBlitSupported = false; caps_.framebufferStencilBlitSupported = false; caps_.framebufferDepthCopySupported = false; caps_.framebufferSeparateDepthCopySupported = false; diff --git a/GPU/Common/Draw2D.cpp b/GPU/Common/Draw2D.cpp index 923300152d..7170aeb5f8 100644 --- a/GPU/Common/Draw2D.cpp +++ b/GPU/Common/Draw2D.cpp @@ -39,19 +39,23 @@ static const SamplerDef samplers[1] = { { "tex" }, }; -void GenerateDraw2DFs(ShaderWriter &writer) { +RasterChannel GenerateDraw2DFs(ShaderWriter &writer) { writer.DeclareSamplers(samplers); writer.BeginFSMain(Slice::empty(), varyings, FSFLAG_NONE); writer.C(" vec4 outColor = ").SampleTexture2D("tex", "v_texcoord.xy").C(";\n"); writer.EndFSMain("outColor", FSFLAG_NONE); + + return RASTER_COLOR; } -void GenerateDraw2DDepthFs(ShaderWriter &writer) { +RasterChannel GenerateDraw2DDepthFs(ShaderWriter &writer) { writer.DeclareSamplers(samplers); writer.BeginFSMain(Slice::empty(), varyings, FSFLAG_WRITEDEPTH); writer.C(" vec4 outColor = vec4(0.0, 0.0, 0.0, 0.0);\n"); writer.C(" gl_FragDepth = ").SampleTexture2D("tex", "v_texcoord.xy").C(".x;\n"); writer.EndFSMain("outColor", FSFLAG_WRITEDEPTH); + + return RASTER_DEPTH; } void GenerateDraw2DVS(ShaderWriter &writer) { @@ -98,13 +102,13 @@ void FramebufferManagerCommon::Ensure2DResources() { } } -Draw::Pipeline *FramebufferManagerCommon::Create2DPipeline(void (*generate)(ShaderWriter &)) { +Draw::Pipeline *FramebufferManagerCommon::Create2DPipeline(RasterChannel (*generate)(ShaderWriter &)) { using namespace Draw; const ShaderLanguageDesc &shaderLanguageDesc = draw_->GetShaderLanguageDesc(); char *fsCode = new char[4000]; ShaderWriter writer(fsCode, shaderLanguageDesc, ShaderStage::Fragment); - generate(writer); + RasterChannel channel = generate(writer); ShaderModule *fs = draw_->CreateShaderModule(ShaderStage::Fragment, shaderLanguageDesc.shaderLanguage, (const uint8_t *)fsCode, strlen(fsCode), "draw2d_fs"); delete[] fsCode; @@ -123,22 +127,24 @@ Draw::Pipeline *FramebufferManagerCommon::Create2DPipeline(void (*generate)(Shad }; InputLayout *inputLayout = draw_->CreateInputLayout(desc); - BlendState *blendOff = draw_->CreateBlendState({ false, 0xF }); - BlendState *blendDiscard = draw_->CreateBlendState({ false, 0x0 }); + BlendState *blend = draw_->CreateBlendState({ false, channel == RASTER_COLOR ? 0xF : 0 }); - DepthStencilState *noDepthStencil = draw_->CreateDepthStencilState(DepthStencilStateDesc{}); + DepthStencilStateDesc dsDesc{}; + if (channel == RASTER_DEPTH) { + dsDesc.depthTestEnabled = true; + dsDesc.depthWriteEnabled = true; + dsDesc.depthCompare = Draw::Comparison::ALWAYS; + } + + DepthStencilState *depthStencil = draw_->CreateDepthStencilState(dsDesc); RasterState *rasterNoCull = draw_->CreateRasterState({}); - DepthStencilStateDesc dsWriteDesc{}; - dsWriteDesc.depthTestEnabled = true; - dsWriteDesc.depthWriteEnabled = true; - dsWriteDesc.depthCompare = Draw::Comparison::ALWAYS; - DepthStencilState *depthWriteAlways = draw_->CreateDepthStencilState(dsWriteDesc); - PipelineDesc pipelineDesc{ Primitive::TRIANGLE_STRIP, { draw2DVs_, fs }, - inputLayout, noDepthStencil, blendOff, rasterNoCull, nullptr, + inputLayout, + depthStencil, + blend, rasterNoCull, nullptr, }; Draw::Pipeline *pipeline = draw_->CreateGraphicsPipeline(pipelineDesc); @@ -146,10 +152,8 @@ Draw::Pipeline *FramebufferManagerCommon::Create2DPipeline(void (*generate)(Shad fs->Release(); rasterNoCull->Release(); - blendOff->Release(); - blendDiscard->Release(); - noDepthStencil->Release(); - depthWriteAlways->Release(); + blend->Release(); + depthStencil->Release(); inputLayout->Release(); return pipeline; diff --git a/GPU/Common/FramebufferManagerCommon.cpp b/GPU/Common/FramebufferManagerCommon.cpp index 1855d088ff..e25c0b9a35 100644 --- a/GPU/Common/FramebufferManagerCommon.cpp +++ b/GPU/Common/FramebufferManagerCommon.cpp @@ -348,6 +348,9 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame break; } } else if (params.fb_address > v->fb_address && params.fb_address < v_fb_end_ptr && PSP_CoreParameter().compat.flags().AllowLargeFBTextureOffsets) { + // Fixes Juiced 2, though causes a lot of copying due to self-texturing. A better solution + // would be to copy from the overlapping framebuffer on bind. + if (params.fb_address % params.fb_stride == v->fb_address % params.fb_stride) { // Framebuffers are overlapping on the Y axis. const int y_offset = (params.fb_address - v->fb_address) / (bpp * params.fb_stride); @@ -2432,6 +2435,7 @@ void FramebufferManagerCommon::BlitFramebuffer(VirtualFramebuffer *dst, int dstX float srcYFactor = src->renderScaleFactor; const int srcBpp = src->format == GE_FORMAT_8888 ? 4 : 2; if (srcBpp != bpp && bpp != 0) { + // If we do this, we're kinda in nonsense territory since the actual formats won't match (unless intentionally blitting black or white). srcXFactor = (srcXFactor * bpp) / srcBpp; } int srcX1 = srcX * srcXFactor; @@ -2443,6 +2447,7 @@ void FramebufferManagerCommon::BlitFramebuffer(VirtualFramebuffer *dst, int dstX float dstYFactor = dst->renderScaleFactor; const int dstBpp = dst->format == GE_FORMAT_8888 ? 4 : 2; if (dstBpp != bpp && bpp != 0) { + // If we do this, we're kinda in nonsense territory since the actual formats won't match (unless intentionally blitting black or white). dstXFactor = (dstXFactor * bpp) / dstBpp; } int dstX1 = dstX * dstXFactor; diff --git a/GPU/Common/FramebufferManagerCommon.h b/GPU/Common/FramebufferManagerCommon.h index 7952e83827..e592ed7b87 100644 --- a/GPU/Common/FramebufferManagerCommon.h +++ b/GPU/Common/FramebufferManagerCommon.h @@ -382,7 +382,7 @@ protected: void DrawStrip2D(Draw::Texture *tex, Draw2DVertex *verts, int vertexCount, bool linearFilter, RasterChannel channel); void Ensure2DResources(); - Draw::Pipeline *Create2DPipeline(void (*generate)(ShaderWriter &)); + Draw::Pipeline *Create2DPipeline(RasterChannel (*generate)(ShaderWriter &)); bool UpdateSize(); From 7f169436c057a4b63ddb1611a5e19e2dfa38566b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Wed, 17 Aug 2022 22:45:13 +0200 Subject: [PATCH 03/85] Framebuffer matching simplification --- GPU/Common/TextureCacheCommon.cpp | 76 +++++++++++++------------------ GPU/Common/TextureCacheCommon.h | 10 +--- 2 files changed, 32 insertions(+), 54 deletions(-) diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index 6049b4e787..ede459941e 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -634,13 +634,9 @@ std::vector TextureCacheCommon::GetFramebufferCandidates(const const std::vector &framebuffers = framebufferManager_->Framebuffers(); for (VirtualFramebuffer *framebuffer : framebuffers) { - FramebufferMatchInfo match = MatchFramebuffer(entry, framebuffer, texAddrOffset, channel); - switch (match.match) { - case FramebufferMatch::VALID: + FramebufferMatchInfo match{}; + if (MatchFramebuffer(entry, framebuffer, texAddrOffset, channel, &match)) { candidates.push_back(AttachCandidate{ match, entry, framebuffer, channel }); - break; - default: - break; } } @@ -677,14 +673,7 @@ int TextureCacheCommon::GetBestCandidateIndex(const std::vector // a comparison function. for (int i = 0; i < (int)candidates.size(); i++) { const AttachCandidate &candidate = candidates[i]; - int relevancy = 0; - switch (candidate.match.match) { - case FramebufferMatch::VALID: - relevancy += 1000; - break; - default: - break; - } + int relevancy = 1000; // Bonus point for matching stride. if (candidate.channel == RASTER_COLOR && candidate.fb->fb_stride == candidate.entry.bufw) { @@ -876,9 +865,9 @@ void TextureCacheCommon::NotifyFramebuffer(VirtualFramebuffer *framebuffer, Fram } } -FramebufferMatchInfo TextureCacheCommon::MatchFramebuffer( +bool TextureCacheCommon::MatchFramebuffer( const TextureDefinition &entry, - VirtualFramebuffer *framebuffer, u32 texaddrOffset, RasterChannel channel) const { + VirtualFramebuffer *framebuffer, u32 texaddrOffset, RasterChannel channel, FramebufferMatchInfo *matchInfo) const { static const u32 MAX_SUBAREA_Y_OFFSET_SAFE = 32; uint32_t fb_address = channel == RASTER_DEPTH ? framebuffer->z_address : framebuffer->fb_address; @@ -891,7 +880,7 @@ FramebufferMatchInfo TextureCacheCommon::MatchFramebuffer( if (texInVRAM != fbInVRAM) { // Shortcut. Cannot possibly be a match. - return FramebufferMatchInfo{ FramebufferMatch::NO_MATCH }; + return false; } if (texInVRAM) { @@ -907,14 +896,14 @@ FramebufferMatchInfo TextureCacheCommon::MatchFramebuffer( case 0x00400000: // Don't match the depth channel with these addresses when texturing. if (channel == RasterChannel::RASTER_DEPTH) { - return FramebufferMatchInfo{ FramebufferMatch::NO_MATCH }; + return false; } break; case 0x00200000: case 0x00600000: // Don't match the color channel with these addresses when texturing. if (channel == RasterChannel::RASTER_COLOR) { - return FramebufferMatchInfo{ FramebufferMatch::NO_MATCH }; + return false; } break; } @@ -938,22 +927,23 @@ FramebufferMatchInfo TextureCacheCommon::MatchFramebuffer( // 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, framebuffer->format) || (framebuffer->usageFlags & FB_USAGE_BLUE_TO_ALPHA)) { - return FramebufferMatchInfo{ FramebufferMatch::VALID }; + return true; } else if (IsTextureFormat16Bit(entry.format) && IsBufferFormat16Bit(framebuffer->format)) { WARN_LOG_ONCE(diffFormat1, G3D, "Texturing from framebuffer with reinterpretable format: %s != %s", GeTextureFormatToString(entry.format), GeBufferFormatToString(framebuffer->format)); - return FramebufferMatchInfo{ FramebufferMatch::VALID, 0, 0, true, TextureFormatToBufferFormat(entry.format) }; + *matchInfo = FramebufferMatchInfo{ 0, 0, true, TextureFormatToBufferFormat(entry.format) }; + return true; } else { WARN_LOG_ONCE(diffFormat2, G3D, "Texturing from framebuffer with incompatible formats %s != %s", GeTextureFormatToString(entry.format), GeBufferFormatToString(framebuffer->format)); - return FramebufferMatchInfo{ FramebufferMatch::NO_MATCH }; + return false; } } else { // Format incompatible, ignoring without comment. (maybe some really gnarly hacks will end up here...) - return FramebufferMatchInfo{ FramebufferMatch::NO_MATCH }; + return false; } } else { // Apply to buffered mode only. if (!framebufferManager_->UseBufferedRendering()) { - return FramebufferMatchInfo{ FramebufferMatch::NO_MATCH }; + return false; } // Check works for D16 too (???) @@ -962,20 +952,17 @@ FramebufferMatchInfo TextureCacheCommon::MatchFramebuffer( (channel == RASTER_COLOR && framebuffer->format == GE_FORMAT_8888 && entry.format == GE_TFMT_CLUT32) || (channel == RASTER_COLOR && framebuffer->format != GE_FORMAT_8888 && entry.format == GE_TFMT_CLUT16); - // To avoid ruining git blame, kept the same name as the old struct. - FramebufferMatchInfo fbInfo{ FramebufferMatch::VALID }; - const u32 bitOffset = (texaddr - addr) * 8; if (bitOffset != 0) { const u32 pixelOffset = bitOffset / std::max(1U, (u32)textureBitsPerPixel[entry.format]); - fbInfo.yOffset = entry.bufw == 0 ? 0 : pixelOffset / entry.bufw; - fbInfo.xOffset = entry.bufw == 0 ? 0 : pixelOffset % entry.bufw; + matchInfo->yOffset = entry.bufw == 0 ? 0 : pixelOffset / entry.bufw; + matchInfo->xOffset = entry.bufw == 0 ? 0 : pixelOffset % entry.bufw; } - if (fbInfo.yOffset + minSubareaHeight >= framebuffer->height) { + if (matchInfo->yOffset + minSubareaHeight >= framebuffer->height) { // Can't be inside the framebuffer. - return FramebufferMatchInfo{ FramebufferMatch::NO_MATCH }; + return false; } if (framebuffer->fb_stride != entry.bufw) { @@ -985,34 +972,33 @@ FramebufferMatchInfo TextureCacheCommon::MatchFramebuffer( // 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 FramebufferMatchInfo{ FramebufferMatch::NO_MATCH }; + return false; } } // Check if it's in bufferWidth (which might be higher than width and may indicate the framebuffer includes the data.) - if (fbInfo.xOffset >= framebuffer->bufferWidth && fbInfo.xOffset + w <= (u32)framebuffer->fb_stride) { + if (matchInfo->xOffset >= framebuffer->bufferWidth && matchInfo->xOffset + w <= (u32)framebuffer->fb_stride) { // This happens in Brave Story, see #10045 - the texture is in the space between strides, with matching stride. - return FramebufferMatchInfo{ FramebufferMatch::NO_MATCH }; + return false; } // Trying to play it safe. Below 0x04110000 is almost always framebuffers. // TODO: Maybe we can reduce this check and find a better way above 0x04110000? - if (fbInfo.yOffset > MAX_SUBAREA_Y_OFFSET_SAFE && addr > 0x04110000 && !PSP_CoreParameter().compat.flags().AllowLargeFBTextureOffsets) { - WARN_LOG_REPORT_ONCE(subareaIgnored, G3D, "Ignoring possible texturing from framebuffer at %08x +%dx%d / %dx%d", fb_address, fbInfo.xOffset, fbInfo.yOffset, framebuffer->width, framebuffer->height); - return FramebufferMatchInfo{ FramebufferMatch::NO_MATCH }; + if (matchInfo->yOffset > MAX_SUBAREA_Y_OFFSET_SAFE && addr > 0x04110000 && !PSP_CoreParameter().compat.flags().AllowLargeFBTextureOffsets) { + WARN_LOG_REPORT_ONCE(subareaIgnored, G3D, "Ignoring possible texturing from framebuffer at %08x +%dx%d / %dx%d", fb_address, matchInfo->xOffset, matchInfo->yOffset, framebuffer->width, framebuffer->height); + 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) { if (!noOffset) { - WARN_LOG_ONCE(subareaClut, G3D, "Texturing from framebuffer using CLUT with offset at %08x +%dx%d", fb_address, fbInfo.xOffset, fbInfo.yOffset); + WARN_LOG_ONCE(subareaClut, G3D, "Texturing from framebuffer using CLUT with offset at %08x +%dx%d", fb_address, matchInfo->xOffset, matchInfo->yOffset); } - fbInfo.match = FramebufferMatch::VALID; // We check the format again later, no need to return a special value here. - return fbInfo; + return true; } else if (IsClutFormat((GETextureFormat)(entry.format)) || IsDXTFormat((GETextureFormat)(entry.format))) { WARN_LOG_ONCE(fourEightBit, G3D, "%s format not supported when texturing from framebuffer of format %s", GeTextureFormatToString(entry.format), GeBufferFormatToString(framebuffer->format)); - return FramebufferMatchInfo{ FramebufferMatch::NO_MATCH }; + return false; } // This is either normal or we failed to generate a shader to depalettize @@ -1020,15 +1006,15 @@ FramebufferMatchInfo TextureCacheCommon::MatchFramebuffer( if ((int)framebuffer->format != (int)entry.format) { WARN_LOG_ONCE(diffFormat2, G3D, "Texturing from framebuffer with different formats %s != %s at %08x", GeTextureFormatToString(entry.format), GeBufferFormatToString(framebuffer->format), fb_address); - return fbInfo; + return true; } else { - WARN_LOG_ONCE(subarea, G3D, "Texturing from framebuffer at %08x +%dx%d", fb_address, fbInfo.xOffset, fbInfo.yOffset); - return fbInfo; + WARN_LOG_ONCE(subarea, G3D, "Texturing from framebuffer at %08x +%dx%d", fb_address, matchInfo->xOffset, matchInfo->yOffset); + return true; } } else { WARN_LOG_ONCE(diffFormat2, G3D, "Texturing from framebuffer with incompatible format %s != %s at %08x", GeTextureFormatToString(entry.format), GeBufferFormatToString(framebuffer->format), fb_address); - return FramebufferMatchInfo{ FramebufferMatch::NO_MATCH }; + return false; } } } diff --git a/GPU/Common/TextureCacheCommon.h b/GPU/Common/TextureCacheCommon.h index 3095efc466..5ab6c995d1 100644 --- a/GPU/Common/TextureCacheCommon.h +++ b/GPU/Common/TextureCacheCommon.h @@ -206,15 +206,7 @@ typedef std::map> TexCache; #undef IGNORE #endif -enum class FramebufferMatch { - // Valid, exact match. - VALID = 0, - // Not a match, remove if currently attached. - NO_MATCH, -}; - struct FramebufferMatchInfo { - FramebufferMatch match; u32 xOffset; u32 yOffset; bool reinterpret; @@ -365,7 +357,7 @@ protected: SamplerCacheKey GetFramebufferSamplingParams(u16 bufferWidth, u16 bufferHeight); void UpdateMaxSeenV(TexCacheEntry *entry, bool throughMode); - FramebufferMatchInfo MatchFramebuffer(const TextureDefinition &entry, VirtualFramebuffer *framebuffer, u32 texaddrOffset, RasterChannel channel) const; + bool MatchFramebuffer(const TextureDefinition &entry, VirtualFramebuffer *framebuffer, u32 texaddrOffset, RasterChannel channel, FramebufferMatchInfo *matchInfo) const; std::vector GetFramebufferCandidates(const TextureDefinition &entry, u32 texAddrOffset); int GetBestCandidateIndex(const std::vector &candidates); From 8251932ae3d1570480141c6f4fb14ca47f51b60b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Wed, 17 Aug 2022 22:58:26 +0200 Subject: [PATCH 04/85] Stride fix in matching --- GPU/Common/TextureCacheCommon.cpp | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index ede459941e..f0d36ab656 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -871,6 +871,12 @@ bool TextureCacheCommon::MatchFramebuffer( static const u32 MAX_SUBAREA_Y_OFFSET_SAFE = 32; uint32_t fb_address = channel == RASTER_DEPTH ? framebuffer->z_address : framebuffer->fb_address; + uint32_t fb_stride = channel == RASTER_DEPTH ? framebuffer->z_stride : framebuffer->z_address; + + if (channel == RASTER_DEPTH && framebuffer->z_address == framebuffer->fb_address) { + // Try to avoid silly matches to somewhat malformed buffers. + return false; + } u32 addr = fb_address & 0x3FFFFFFF; u32 texaddr = entry.addr + texaddrOffset; @@ -921,8 +927,8 @@ bool TextureCacheCommon::MatchFramebuffer( // If they match "exactly", it's non-CLUT and from the top left. if (exactMatch) { - if (framebuffer->fb_stride != entry.bufw) { - WARN_LOG_ONCE(diffStrides1, G3D, "Texturing from framebuffer with different strides %d != %d", entry.bufw, framebuffer->fb_stride); + if (fb_stride != entry.bufw) { + WARN_LOG_ONCE(diffStrides1, G3D, "Texturing from framebuffer with different strides %d != %d", entry.bufw, fb_stride); } // NOTE: This check is okay because the first texture formats are the same as the buffer formats. if (IsTextureFormatBufferCompatible(entry.format)) { @@ -965,9 +971,9 @@ bool TextureCacheCommon::MatchFramebuffer( return false; } - if (framebuffer->fb_stride != entry.bufw) { + if (fb_stride != entry.bufw) { if (noOffset) { - WARN_LOG_ONCE(diffStrides2, G3D, "Texturing from framebuffer (matching_clut=%s) different strides %d != %d", matchingClutFormat ? "yes" : "no", entry.bufw, framebuffer->fb_stride); + WARN_LOG_ONCE(diffStrides2, G3D, "Texturing from 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 { @@ -977,7 +983,7 @@ bool TextureCacheCommon::MatchFramebuffer( } // 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)framebuffer->fb_stride) { + if (matchInfo->xOffset >= framebuffer->bufferWidth && matchInfo->xOffset + w <= (u32)fb_stride) { // This happens in Brave Story, see #10045 - the texture is in the space between strides, with matching stride. return false; } From 705b34d868c2dab0dfa1b74e3a551985a4bb2634 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Wed, 17 Aug 2022 23:25:07 +0200 Subject: [PATCH 05/85] Show seqCount in candidate list --- GPU/Common/TextureCacheCommon.cpp | 6 +++--- GPU/Common/TextureCacheCommon.h | 3 ++- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index f0d36ab656..f2c68b5777 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -636,7 +636,7 @@ std::vector TextureCacheCommon::GetFramebufferCandidates(const for (VirtualFramebuffer *framebuffer : framebuffers) { FramebufferMatchInfo match{}; if (MatchFramebuffer(entry, framebuffer, texAddrOffset, channel, &match)) { - candidates.push_back(AttachCandidate{ match, entry, framebuffer, channel }); + candidates.push_back(AttachCandidate{ match, entry, framebuffer, channel, channel == RASTER_COLOR ? framebuffer->colorBindSeq : framebuffer->depthBindSeq }); } } @@ -2150,8 +2150,8 @@ void TextureCacheCommon::ClearNextFrame() { clearCacheNextFrame_ = true; } -std::string AttachCandidate::ToString() { - return StringFromFormat("[C:%08x/%d Z:%08x/%d X:%d Y:%d reint: %s]", this->fb->fb_address, this->fb->fb_stride, this->fb->z_address, this->fb->z_stride, this->match.xOffset, this->match.yOffset, this->match.reinterpret ? "true" : "false"); +std::string AttachCandidate::ToString() const { + return StringFromFormat("[%s seq:%d C:%08x/%d Z:%08x/%d X:%d Y:%d reint: %s]", this->channel == RASTER_COLOR ? "COLOR" : "DEPTH", this->seqCount, this->fb->fb_address, this->fb->fb_stride, this->fb->z_address, this->fb->z_stride, this->match.xOffset, this->match.yOffset, this->match.reinterpret ? "true" : "false"); } bool TextureCacheCommon::PrepareBuildTexture(BuildTexturePlan &plan, TexCacheEntry *entry) { diff --git a/GPU/Common/TextureCacheCommon.h b/GPU/Common/TextureCacheCommon.h index 5ab6c995d1..5c95eb3b87 100644 --- a/GPU/Common/TextureCacheCommon.h +++ b/GPU/Common/TextureCacheCommon.h @@ -218,8 +218,9 @@ struct AttachCandidate { TextureDefinition entry; VirtualFramebuffer *fb; RasterChannel channel; + int seqCount; - std::string ToString(); + std::string ToString() const; }; class FramebufferManagerCommon; From b5f0e26c2400b73c516799d8066c27e5f740131c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Wed, 17 Aug 2022 23:30:51 +0200 Subject: [PATCH 06/85] Pre-reject DXT formats, Misc --- GPU/Common/TextureCacheCommon.cpp | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index f2c68b5777..6f2ab13e5b 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -641,15 +641,13 @@ std::vector TextureCacheCommon::GetFramebufferCandidates(const } if (candidates.size() > 1) { - bool depth = channel == RasterChannel::RASTER_DEPTH; - std::string cands; for (auto &candidate : candidates) { cands += candidate.ToString() + " "; } - WARN_LOG_REPORT_ONCE(multifbcandidate, G3D, "GetFramebufferCandidates(%s): Multiple (%d) candidate framebuffers. First will be chosen. texaddr: %08x offset: %d (%dx%d stride %d, %s):\n%s", - depth ? "DEPTH" : "COLOR", (int)candidates.size(), + WARN_LOG_REPORT_ONCE(multifbcandidate, 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() ); @@ -878,6 +876,13 @@ bool TextureCacheCommon::MatchFramebuffer( return false; } + switch (entry.format) { + case GE_TFMT_DXT1: + case GE_TFMT_DXT3: + case GE_TFMT_DXT5: + return false; + } + u32 addr = fb_address & 0x3FFFFFFF; u32 texaddr = entry.addr + texaddrOffset; From 31773b42bad5202402f0ed8af577f3bdceb1c2ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Wed, 17 Aug 2022 23:35:36 +0200 Subject: [PATCH 07/85] Always attempt to match both depth and color --- GPU/Common/TextureCacheCommon.cpp | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index 6f2ab13e5b..a2f727c00e 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -625,18 +625,15 @@ std::vector TextureCacheCommon::GetFramebufferCandidates(const std::vector candidates; - RasterChannel channel = Memory::IsDepthTexVRAMAddress(entry.addr) ? RasterChannel::RASTER_DEPTH : RasterChannel::RASTER_COLOR; - if (channel == RasterChannel::RASTER_DEPTH && !gstate_c.Supports(GPU_SUPPORTS_DEPTH_TEXTURE)) { - // Depth texture not supported. Don't try to match it, fall back to the memory behind.. - return std::vector(); - } - const std::vector &framebuffers = framebufferManager_->Framebuffers(); for (VirtualFramebuffer *framebuffer : framebuffers) { FramebufferMatchInfo match{}; - if (MatchFramebuffer(entry, framebuffer, texAddrOffset, channel, &match)) { - candidates.push_back(AttachCandidate{ match, entry, framebuffer, channel, channel == RASTER_COLOR ? framebuffer->colorBindSeq : framebuffer->depthBindSeq }); + if (MatchFramebuffer(entry, framebuffer, texAddrOffset, RASTER_COLOR, &match)) { + candidates.push_back(AttachCandidate{ match, entry, framebuffer, RASTER_COLOR, framebuffer->colorBindSeq }); + } + if (gstate_c.Supports(GPU_SUPPORTS_DEPTH_TEXTURE) && MatchFramebuffer(entry, framebuffer, texAddrOffset, RASTER_DEPTH, &match)) { + candidates.push_back(AttachCandidate{ match, entry, framebuffer, RASTER_DEPTH, framebuffer->depthBindSeq }); } } From fde369332bb5f2b8948229554f2f1cb85a03e476 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Wed, 17 Aug 2022 23:46:38 +0200 Subject: [PATCH 08/85] Remove restrictions on VRAM addresses for depth and color --- GPU/Common/TextureCacheCommon.cpp | 23 +---------------------- 1 file changed, 1 insertion(+), 22 deletions(-) diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index a2f727c00e..8d387218fe 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -632,6 +632,7 @@ std::vector TextureCacheCommon::GetFramebufferCandidates(const if (MatchFramebuffer(entry, framebuffer, texAddrOffset, RASTER_COLOR, &match)) { candidates.push_back(AttachCandidate{ match, entry, framebuffer, RASTER_COLOR, framebuffer->colorBindSeq }); } + match = {}; if (gstate_c.Supports(GPU_SUPPORTS_DEPTH_TEXTURE) && MatchFramebuffer(entry, framebuffer, texAddrOffset, RASTER_DEPTH, &match)) { candidates.push_back(AttachCandidate{ match, entry, framebuffer, RASTER_DEPTH, framebuffer->depthBindSeq }); } @@ -894,28 +895,6 @@ bool TextureCacheCommon::MatchFramebuffer( if (texInVRAM) { const u32 mirrorMask = 0x00600000; - // This bit controls swizzle. The swizzles at 0x00200000 and 0x00600000 are designed - // to perfectly match reading depth as color (which one to use I think might be related - // to the bpp of the color format used when rendering to it). - // It's fairly unlikely that games would screw this up since the result will be garbage so - // we use it to filter out unlikely matches. - switch (entry.addr & mirrorMask) { - case 0x00000000: - case 0x00400000: - // Don't match the depth channel with these addresses when texturing. - if (channel == RasterChannel::RASTER_DEPTH) { - return false; - } - break; - case 0x00200000: - case 0x00600000: - // Don't match the color channel with these addresses when texturing. - if (channel == RasterChannel::RASTER_COLOR) { - return false; - } - break; - } - addr &= ~mirrorMask; texaddr &= ~mirrorMask; } From 76333f90fe203496d7cba875d3e765bb385902c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Wed, 17 Aug 2022 23:51:05 +0200 Subject: [PATCH 09/85] Bias towards the most recently written framebuffer --- GPU/Common/TextureCacheCommon.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index 8d387218fe..00f3822fbc 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -669,22 +669,22 @@ int TextureCacheCommon::GetBestCandidateIndex(const std::vector // a comparison function. for (int i = 0; i < (int)candidates.size(); i++) { const AttachCandidate &candidate = candidates[i]; - int relevancy = 1000; + int relevancy = candidate.seqCount; // Bonus point for matching stride. if (candidate.channel == RASTER_COLOR && candidate.fb->fb_stride == candidate.entry.bufw) { - relevancy += 100; + relevancy += 1000; } // Bonus points for no offset. if (candidate.match.xOffset == 0 && candidate.match.yOffset == 0) { - relevancy += 10; + relevancy += 100; } if (candidate.channel == RASTER_COLOR && candidate.fb->last_frame_render == gpuStats.numFlips) { - relevancy += 5; + relevancy += 50; } else if (candidate.channel == RASTER_DEPTH && candidate.fb->last_frame_depth_render == gpuStats.numFlips) { - relevancy += 5; + relevancy += 50; } if (relevancy > bestRelevancy) { @@ -867,7 +867,7 @@ bool TextureCacheCommon::MatchFramebuffer( static const u32 MAX_SUBAREA_Y_OFFSET_SAFE = 32; uint32_t fb_address = channel == RASTER_DEPTH ? framebuffer->z_address : framebuffer->fb_address; - uint32_t fb_stride = channel == RASTER_DEPTH ? framebuffer->z_stride : framebuffer->z_address; + uint32_t fb_stride = channel == RASTER_DEPTH ? framebuffer->z_stride : framebuffer->fb_stride; if (channel == RASTER_DEPTH && framebuffer->z_address == framebuffer->fb_address) { // Try to avoid silly matches to somewhat malformed buffers. @@ -909,7 +909,7 @@ bool TextureCacheCommon::MatchFramebuffer( // If they match "exactly", it's non-CLUT and from the top left. if (exactMatch) { if (fb_stride != entry.bufw) { - WARN_LOG_ONCE(diffStrides1, G3D, "Texturing from framebuffer with different strides %d != %d", entry.bufw, fb_stride); + WARN_LOG_ONCE(diffStrides1, G3D, "Texturing from framebuffer with different strides %d != %d", 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)) { From 496785cd54502b3eaedd74e62aceb6aba0c0483b Mon Sep 17 00:00:00 2001 From: DDinghoya Date: Thu, 18 Aug 2022 22:54:08 +0900 Subject: [PATCH 10/85] Update ko_KR.ini Minor update#1 --- assets/lang/ko_KR.ini | 184 +++++++++++++++++++++--------------------- 1 file changed, 92 insertions(+), 92 deletions(-) diff --git a/assets/lang/ko_KR.ini b/assets/lang/ko_KR.ini index 3236d8b6cd..a2ea702766 100644 --- a/assets/lang/ko_KR.ini +++ b/assets/lang/ko_KR.ini @@ -1,122 +1,122 @@ [Audio] Alternate speed volume = 대체 속도 볼륨 -Audio backend = 오디오 처리자 (재시작 필요) -Audio Error = Audio Error -AudioBufferingForBluetooth = 블루투스 친화적 버퍼링 (느림) +Audio backend = 오디오 백엔드 (재시작 요구) +Audio Error = 오디오 오류 +AudioBufferingForBluetooth = 블루투스 친화적 버퍼 (느림) Auto = 자동 Device = 장치 -Disabled = Disabled -DSound (compatible) = DSound (호환됨) +Disabled = 비활성화 +DSound (compatible) = DSound (호환) Enable Sound = 사운드 활성화 -Global volume = 전역 볼륨 -Microphone = Microphone -Microphone Device = Microphone device +Global volume = 글로벌 볼륨 +Microphone = 마이크로폰 +Microphone Device = 마이크로폰 장치 Mute = 음소거 -Reverb volume = Reverb volume -Use new audio devices automatically = 새로운 오디오 장치로 전환 -Use global volume = 전역 볼륨 사용 +Reverb volume = 반향 볼륨 +Use new audio devices automatically = 새 오디오 장치를 자동으로 사용 +Use global volume = 글로벌 볼륨 사용 WASAPI (fast) = WASAPI (빠름) [Controls] -Analog Binding = Analog Binding -Analog Settings = Analog Settings -Analog Style = Analog Style -Auto-rotation speed = 아날로그 자동 회전 속도 -Analog Limiter = 아날로그 제한 +Analog Binding = 아날로그 바인딩 +Analog Limiter = 아날로그 리미터 +Analog Settings = 아날로그 설정 Analog Stick = 아날로그 스틱 -AnalogLimiter Tip = 아날로그 제한 버튼이 눌러졌을 때 아날로그를 제한합니다. +Analog Style = 아날로그 스타일 +AnalogLimiter Tip = 아날로그 리미터 버튼을 눌렀을 때 Auto = 자동 -Auto-centering analog stick = 아날로그 스틱 자동으로 중앙 고정 -Auto-hide buttons after seconds = 버튼 자동 숨김 -Auto-switch = Auto-switch -Base tilt position = Base tilt position -Binds = Binds -Button Binding = Button Binding -Button Opacity = 버튼 투명도 +Auto-centering analog stick = 자동 센터링 아날로그 스틱 +Auto-hide buttons after seconds = 몇 초 후 버튼 자동 숨기기 +Auto-rotation speed = 자동 회전 속도 +Auto-switch = 자동 스위치 +Base tilt position = 기본 기울기 위치 +Binds = 바인드 +Button Binding = 버튼 바인딩 +Button Opacity = 버튼 불투명도 Button style = 버튼 스타일 -Calibrate Analog Stick = Calibrate Analog Stick -Calibrate D-Pad = 십자 패드 보정 -Calibrated = Calibrated -Calibration = 보정 -Circular stick input = Circular stick input +Calibrate Analog Stick = 아날로그 스틱 보정 +Calibrate D-Pad = 보정 +Calibrated = 보정됨 +Calibration = 교정 +Circular stick input = 원형 스틱 입력 Classic = 클래식 -Confine Mouse = 창/화면 안에 커서를 가두기 -Control Mapping = 컨트롤 맵핑 -Custom Key Setting = Custom Key Setting -Customize = Customize -Customize Touch Controls = 터치 컨트롤 레이아웃 편집... -Customize tilt = 기울기 사용자화... -D-PAD = 십자 패드 -Deadzone radius = 데드존 범위 -Disable D-Pad diagonals (4-way touch) = 십자 패드 대각선 비활성 (4방향 터치) -Disable diagonal input = Disable diagonal input -Double tap = Double tap -Enable gesture control = Enable gesture control -Enable standard shortcut keys = Enable standard shortcut keys -Gesture = Gesture -Gesture mapping = Gesture mapping -Glowing borders = 빛나는 테두리 +Confine Mouse = 창/표시 영역 내에서 마우스 트랩 +Control Mapping = 제어 맵핑 +Custom Key Setting = 커스텀 키 설정 +Customize = 맞춤설정 +Customize Touch Controls = 터치 제어 레이아웃 수정... +Customize tilt = 기울기 맞춤설정... +D-PAD = D-패드 +Deadzone radius = 데드존 반경 +Disable D-Pad diagonals (4-way touch) = D-패드 대각선 비활성화 (4 방향 터치) +Disable diagonal input = 대각선 입력 비활성화 +Double tap = 두 번 탭 +Enable gesture control = 제스처 제어 활성화 +Enable standard shortcut keys = 표준 단축키 활성화 +Gesture = 제스처 +Gesture mapping = 제스처 맵핑 +Glowing borders = 광선 테두리 HapticFeedback = 햅틱 피드백 (진동) -Hide touch analog stick background circle = Hide touch analog stick background circle -Icon = Icon -Ignore gamepads when not focused = 창이 활성화 되지 않았을 때 게임패드 무시 -Ignore Windows Key = 윈도우 키 무시 +Hide touch analog stick background circle = 터치 아날로그 스틱 배경 원 숨기기 +Icon = 아이콘 +Ignore gamepads when not focused = 초점이 맞지 않을 때 게임패드 무시 +Ignore Windows Key = Windows 키 비활성화 Invert Axes = 축 반전 -Invert Tilt along X axis = X축 기울기 반전 -Invert Tilt along Y axis = Y축 기울기 반전 -Keep this button pressed when right analog is pressed = 오른쪽 아날로그가 눌렸을 때 이 버튼을 눌리게끔 유지 -Keyboard = 키보드 조작 설정 +Invert Tilt along X axis = X 축을 따라 기울기 반전 +Invert Tilt along Y axis = Y 축을 따라 기울기 반전 +Keep this button pressed when right analog is pressed = 오른쪽 아날로그를 눌렀을 때 이 버튼을 계속 누른 상태 유지 +Keyboard = 키보드 제어 설정 L/R Trigger Buttons = L/R 트리거 버튼 -Landscape = 가로 -Landscape Auto = 가로 자동 -Landscape Reversed = 가로 반전 -Low end radius = Low end radius +Landscape = 가로 방향 +Landscape Auto = 가로 방향 자동 +Landscape Reversed = 가로 방향 반전 +Low end radius = 하단 반경 Mouse = 마우스 설정 -Mouse sensitivity = 마우스 민감도 -Mouse smoothing = 마우스 가속도(Smoothing) -MouseControl Tip = 'M' 아이콘을 눌러 조작 매핑 화면에 들어가 마우스를 매핑할 수 있습니다. -None (Disabled) = 없음 (비활성) -Off = 끄기 -OnScreen = 화면 터치 컨트롤 -Portrait = 세로 -Portrait Reversed = 세로 반전 +Mouse sensitivity = 마우스 감도 +Mouse smoothing = 마우스 스무딩 +MouseControl Tip = 이제 'M' 아이콘을 눌러 제어 매핑 화면에서 마우스를 매핑할 수 있습니다. +None (Disabled) = 없음 (비활성화) +Off = 끔 +OnScreen = 화면 터치 제어 +Portrait = 세로 방향 +Portrait Reversed = 세로 방향 반전 PSP Action Buttons = PSP 액션 버튼 -Raw input = Raw input -Repeat mode = Repeat mode -Reset to defaults = Reset to defaults -Screen aligned to ground = Screen aligned to ground -Screen at right angle to ground = Screen at right angle to ground +Raw input = 원시 입력 +Reset to defaults = 기본값으로 재설정 +Screen aligned to ground = 지면에 맞춰진 화면 +Screen at right angle to ground = 지면과 직각의 스크린 Screen Rotation = 화면 회전 -seconds, 0 : off = 초 단위, 0 : 끄기 -Sensitivity (scale) = Sensitivity (scale) -Sensitivity = 민감도 -Shape = Shape -Show Touch Pause Menu Button = 일시 정지 메뉴 버튼 표시 -Swipe = Swipe -Swipe sensitivity = Swipe sensitivity -Swipe smoothing = Swipe smoothing +seconds, 0 : off = 초 단위, 0 = 끔 +Sensitivity = 감도 +Sensitivity (scale) = 감도 (스케일) +Shape = 모양 +Show Touch Pause Menu Button = 일시중지 메뉴 버튼 표시 +Swipe = 스와이프 +Swipe sensitivity = 스와이프 감도 +Swipe smoothing = 스와이프 스무딩 Thin borders = 얇은 테두리 -Tilt Base Radius = Tilt base radius -Tilt Input Type = 기울기 입력 방식 -Tilt Sensitivity along X axis = X축 기울기 민감도 -Tilt Sensitivity along Y axis = Y축 기울기 민감도 -To Calibrate = 보정하려면, 기기를 평평한 곳에 놓고 "보정"을 눌러주십시오. -Toggle mode = Toggle mode -Touch Control Visibility = 터치 컨트롤 표시 -Use custom right analog = 사용자 정의 오른쪽 아날로그 사용 -Use Mouse Control = 마우스 사용하기 -Visibility = 표시 -Visible = Visible +Tilt Base Radius = 기울기 기반 반경 +Tilt Input Type = 기울기 입력 유형 +Tilt Sensitivity along X axis = X 축 기울기 감도 +Tilt Sensitivity along Y axis = Y 축 기울기 감도 +To Calibrate = 보정하려면 장치를 평평한 표면에 놓고 "보정"을 누르세요. +Toggle mode = 토글 모드 +Repeat mode = 반복 모드 +Touch Control Visibility = 터치 제어 가시성 +Use custom right analog = 커스텀 오른쪽 아날로그 사용 +Use Mouse Control = 마우스 제어 사용 +Visibility = 가시성 +Visible = 가시적 X = X Y = Y [CwCheats] Cheats = 치트 -Edit Cheat File = 치트 파일 편집 +Edit Cheat File = 치트 파일 수정 Enable/Disable All = 모든 치트 활성화/비활성화 -Import Cheats = 치트 가져오기 (cheat.db에서) +Import Cheats = cheat.db에서 가져오기 Options = 옵션 -Refresh Rate = 재생률 +Refresh Rate = 주사율 [DesktopUI] # If your language does not show well with the default font, you can use Font to specify a different one. From 87f51c5eadd9e9d5a73b7062224be3e3c889f1f9 Mon Sep 17 00:00:00 2001 From: Felix Yan Date: Thu, 18 Aug 2022 17:41:53 +0300 Subject: [PATCH 11/85] Fix dependency of RISC-V targets on common JIT code Fixes #15861 --- CMakeLists.txt | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 97b9bbde52..8c5dbcd989 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -426,6 +426,15 @@ if(WIN32) endif() +set(CommonJIT + Core/MIPS/JitCommon/JitCommon.cpp + Core/MIPS/JitCommon/JitCommon.h + Core/MIPS/JitCommon/JitBlockCache.cpp + Core/MIPS/JitCommon/JitBlockCache.h + Core/MIPS/JitCommon/JitState.cpp + Core/MIPS/JitCommon/JitState.h +) + set(CommonX86 Common/ABI.cpp Common/ABI.h @@ -464,6 +473,7 @@ set(CommonMIPS source_group(MIPS FILES ${CommonMIPS}) set(CommonRISCV64 + ${CommonJIT} Common/RiscVCPUDetect.cpp Core/MIPS/fake/FakeJit.cpp Core/MIPS/fake/FakeJit.h @@ -1626,6 +1636,7 @@ set(GPU_SOURCES # SHARED on ANDROID, STATIC everywhere else add_library(${CoreLibName} ${CoreLinkType} ${CoreExtra} + ${CommonJIT} Core/Config.cpp Core/Config.h Core/ConfigValues.h @@ -1933,12 +1944,6 @@ add_library(${CoreLibName} ${CoreLinkType} Core/FileLoaders/RamCachingFileLoader.h Core/FileLoaders/RetryingFileLoader.cpp Core/FileLoaders/RetryingFileLoader.h - Core/MIPS/JitCommon/JitCommon.cpp - Core/MIPS/JitCommon/JitCommon.h - Core/MIPS/JitCommon/JitBlockCache.cpp - Core/MIPS/JitCommon/JitBlockCache.h - Core/MIPS/JitCommon/JitState.cpp - Core/MIPS/JitCommon/JitState.h Core/MIPS/MIPS.cpp Core/MIPS/MIPS.h Core/MIPS/MIPSAnalyst.cpp From 70b9dcc9a3f35507fd5af8d7935d9aa87359f393 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Thu, 18 Aug 2022 15:20:16 +0200 Subject: [PATCH 12/85] Initialize a bunch of Dialog structs --- Core/Dialog/PSPDialog.h | 10 +++++----- Core/Dialog/PSPGamedataInstallDialog.h | 18 +++++++++--------- Core/Dialog/PSPMsgDialog.h | 6 +++--- Core/Dialog/PSPOskDialog.h | 9 ++++----- Core/Dialog/PSPSaveDialog.h | 6 +++--- Core/Dialog/SavedataParam.cpp | 11 +---------- Core/Dialog/SavedataParam.h | 13 ++++++------- 7 files changed, 31 insertions(+), 42 deletions(-) diff --git a/Core/Dialog/PSPDialog.h b/Core/Dialog/PSPDialog.h index 54a9488e36..636fc20334 100644 --- a/Core/Dialog/PSPDialog.h +++ b/Core/Dialog/PSPDialog.h @@ -99,7 +99,7 @@ protected: void ChangeStatus(DialogStatus newStatus, int delayUs); void ChangeStatusInit(int delayUs); void ChangeStatusShutdown(int delayUs); - DialogStatus ReadStatus() { + DialogStatus ReadStatus() const { return status; } @@ -117,10 +117,10 @@ protected: unsigned int lastButtons = 0; unsigned int buttons = 0; - float fadeTimer; - bool isFading; - bool fadeIn; - u32 fadeValue; + float fadeTimer = 0.0f; + bool isFading = false; + bool fadeIn = false; + u32 fadeValue = 0; ImageID okButtonImg; ImageID cancelButtonImg; diff --git a/Core/Dialog/PSPGamedataInstallDialog.h b/Core/Dialog/PSPGamedataInstallDialog.h index 3dfd8687ef..e669a31873 100644 --- a/Core/Dialog/PSPGamedataInstallDialog.h +++ b/Core/Dialog/PSPGamedataInstallDialog.h @@ -59,16 +59,16 @@ private: void CloseCurrentFile(); void WriteSfoFile(); - SceUtilityGamedataInstallParam request; + SceUtilityGamedataInstallParam request{}; PSPPointer param; std::vector inFileNames; - int numFiles; - int readFiles; - u64 allFilesSize; // use this to calculate progress value. - u64 allReadSize; // use this to calculate progress value. - int progressValue; + int numFiles = 0; + int readFiles = 0; + u64 allFilesSize = 0; // use this to calculate progress value. + u64 allReadSize = 0; // use this to calculate progress value. + int progressValue = 0; - int currentInputFile; - u32 currentInputBytesLeft; - int currentOutputFile; + int currentInputFile = 0; + u32 currentInputBytesLeft = 0; + int currentOutputFile = 0; }; diff --git a/Core/Dialog/PSPMsgDialog.h b/Core/Dialog/PSPMsgDialog.h index e5912d2ee3..78ee4e54f4 100644 --- a/Core/Dialog/PSPMsgDialog.h +++ b/Core/Dialog/PSPMsgDialog.h @@ -94,11 +94,11 @@ private: u32 flag = 0; - pspMessageDialog messageDialog; - int messageDialogAddr; + pspMessageDialog messageDialog{}; + int messageDialogAddr = 0; char msgText[512]; - int yesnoChoice; + int yesnoChoice = 0; float scrollPos_ = 0.0f; int framesUpHeld_ = 0; int framesDownHeld_ = 0; diff --git a/Core/Dialog/PSPOskDialog.h b/Core/Dialog/PSPOskDialog.h index 8eb55586c0..c760afb1e4 100644 --- a/Core/Dialog/PSPOskDialog.h +++ b/Core/Dialog/PSPOskDialog.h @@ -148,7 +148,6 @@ struct SceUtilityOskParams SceUtilityOskState_le state; // Maybe just padding? s32_le unk_60; - }; // Internal enum, not from PSP. @@ -245,16 +244,16 @@ private: std::string oskIntext; std::string oskOuttext; - int selectedChar; + int selectedChar = 0; std::u16string inputChars; OskKeyboardDisplay currentKeyboard; OskKeyboardLanguage currentKeyboardLanguage; - bool isCombinated; + bool isCombinated = false; std::mutex nativeMutex_; PSPOskNativeStatus nativeStatus_ = PSPOskNativeStatus::IDLE; std::string nativeValue_; - int i_level; // for Korean Keyboard support - int i_value[3]; // for Korean Keyboard support + int i_level = 0; // for Korean Keyboard support + int i_value[3]{}; // for Korean Keyboard support }; diff --git a/Core/Dialog/PSPSaveDialog.h b/Core/Dialog/PSPSaveDialog.h index 8058d8a962..90f8d6312a 100644 --- a/Core/Dialog/PSPSaveDialog.h +++ b/Core/Dialog/PSPSaveDialog.h @@ -139,13 +139,13 @@ private: DisplayState display = DS_NONE; SavedataParam param; - SceUtilitySavedataParam request; + SceUtilitySavedataParam request{}; // For detecting changes made by the game. - SceUtilitySavedataParam originalRequest; + SceUtilitySavedataParam originalRequest{}; u32 requestAddr = 0; int currentSelectedSave = 0; - int yesnoChoice; + int yesnoChoice = 0; enum SaveIOStatus { diff --git a/Core/Dialog/SavedataParam.cpp b/Core/Dialog/SavedataParam.cpp index f4ba47a20e..980a3edf31 100644 --- a/Core/Dialog/SavedataParam.cpp +++ b/Core/Dialog/SavedataParam.cpp @@ -193,16 +193,7 @@ void SaveFileInfo::DoState(PointerWrap &p) } } -SavedataParam::SavedataParam() - : pspParam(0) - , selectedSave(0) - , saveDataList(0) - , noSaveIcon(0) - , saveDataListCount(0) - , saveNameListDataCount(0) -{ - -} +SavedataParam::SavedataParam() { } void SavedataParam::Init() { diff --git a/Core/Dialog/SavedataParam.h b/Core/Dialog/SavedataParam.h index b7daa02845..e7bdf9ad46 100644 --- a/Core/Dialog/SavedataParam.h +++ b/Core/Dialog/SavedataParam.h @@ -265,7 +265,6 @@ struct SceUtilitySavedataParam // Function 22 GETSIZES PSPPointer sizeInfo; - }; // Non native, this one we can reorganize as we like @@ -377,10 +376,10 @@ private: std::set GetSecureFileNames(const std::string &dirPath); bool GetExpectedHash(const std::string &dirPath, const std::string &filename, u8 hash[16]); - SceUtilitySavedataParam* pspParam; - int selectedSave; - SaveFileInfo *saveDataList; - SaveFileInfo *noSaveIcon; - int saveDataListCount; - int saveNameListDataCount; + SceUtilitySavedataParam* pspParam = nullptr; + int selectedSave = 0; + SaveFileInfo *saveDataList = nullptr; + SaveFileInfo *noSaveIcon = nullptr; + int saveDataListCount = 0; + int saveNameListDataCount = 0; }; From cdd134b5f8d785b3230ac9667410381fcaea7c26 Mon Sep 17 00:00:00 2001 From: DDinghoya Date: Fri, 19 Aug 2022 11:04:54 +0900 Subject: [PATCH 13/85] Update ko_KR.ini Minor update#2 --- assets/lang/ko_KR.ini | 306 +++++++++++++++++++++--------------------- 1 file changed, 152 insertions(+), 154 deletions(-) diff --git a/assets/lang/ko_KR.ini b/assets/lang/ko_KR.ini index a2ea702766..e6dad1ac55 100644 --- a/assets/lang/ko_KR.ini +++ b/assets/lang/ko_KR.ini @@ -971,255 +971,253 @@ View Feedback = 모든 피드백 보기 [Savedata] Date = 날짜 -Filename = 파일 이름 +Filename = 파일이름 No screenshot = 스크린샷 없음 -None yet. Things will appear here after you save. = 아직 없음. 저장하면 나타납니다. -Nothing matching '%1' was found. = Nothing matching '%1' was found. +None yet. Things will appear here after you save. = 아직 없습니다. 저장하면 여기에 항목이 표시됩니다. +Nothing matching '%1' was found. = '%1'과(와) 일치하는 항목이 없습니다. Save Data = 저장 데이터 Save States = 상태 저장 -Savedata Manager = 저장 데이터 관리자 -Showing matches for '%1'. = Showing matches for '%1'. +Savedata Manager = 저장데이터 관리자 +Showing matches for '%1'. = '%1'에 대한 일치 항목을 표시합니다. Size = 크기 [Screen] -Cardboard VR OFF = 구글 카드보드 끄기 -Chainfire3DWarning = 경고: 체인파이어 3D가 검출되었습니다. 문제가 발생할 수 있습니다. -Failed to load state = 상태 불러오기에 실패했습니다 -Failed to save state = 상태 저장에 실패했습니다 -fixed = 속도: 고정 -GLToolsWarning = 경고: GLTools가 감지되었습니다. 문제가 발생할 수 있습니다. +Cardboard VR OFF = 카드보드 VR off +Chainfire3DWarning = 경고: Chainfire3D가 감지되어 문제를 일으킬 수 있습니다. +Failed to load state = 상태를 로드하지 못함 +Failed to save state = 상태를 저장하지 못함 +fixed = 속도: 대체 +GLToolsWarning = 경고: GLTools가 감지되어 문제를 일으킬 수 있습니다. In menu = 메뉴 -Load savestate failed = 상태 불러오기 실패 -Loaded State = 상태 불러옴 -Loaded. Game may refuse to save over different savedata. = Loaded. Game may refuse to save over different savedata. -Loaded. Game may refuse to save over newer savedata. = Loaded. Game may refuse to save over newer savedata. -Loaded. Save in game, restart, and load for less bugs. = 불러왔습니다. 게임을 저장한 다음 재시작하면 적은 버그로 로드됩니다. -LoadStateDoesntExist = 상태를 불러오지 못했습니다: 상태 저장이 존재하지 않습니다! -LoadStateWrongVersion = 상태를 불러오지 못했습니다: 구 버전의 상태 저장입니다! -norewind = 되감기 저장 상태가 없습니다. -Playing = 실행 -PressESC = ESC를 누르면 중지 메뉴가 열립니다. -replaceTextures_false = 텍스처가 더 이상 대체되지 않습니다. +Load savestate failed = 저장 상태 로드 실패 +Loaded State = 로드된 상태 +Loaded. Save in game, restart, and load for less bugs. = 로드되었습니다. 버그를 줄이기 위해 게임을 저장하고 다시 시작하고 로드하세요. +Loaded. Game may refuse to save over different savedata. = 로드되었습니다. 게임이 다른 저장 데이터에 대한 저장을 거부할 수 있습니다. +Loaded. Game may refuse to save over newer savedata. = 로드되었습니다. 게임이 최신 저장 데이터에 대한 저장을 거부할 수 있습니다. +LoadStateDoesntExist = 상태 로드 실패: 저장상태가 존재하지 않습니다! +LoadStateWrongVersion = 상태 로드 실패: 저장상태는 이전 버전의 PPSSPP용입니다! +norewind = 되감기 저장 상태를 사용할 수 없습니다. +Playing = 게임 중 +PressESC = 일시 중지 메뉴를 열려면 ESC를 누르세요. +replaceTextures_false = 텍스처가 더 이상 교체되지 않습니다. replaceTextures_true = 텍스처 교체가 활성화되었습니다. -Save State Failed = 상태를 저장하지 못했습니다! -Saved State = 상태 저장됨 +Save State Failed = 상태 저장 실패! +Saved State = 저장된 상태 saveNewTextures_false = 텍스처 저장이 비활성화되었습니다. -saveNewTextures_true = 텍스처가 이제 저장 공간에 저장됩니다. -SpeedCustom2 = 속도: 고정 속도 2 +saveNewTextures_true = 이제 텍스처가 저장 공간에 저장됩니다. +SpeedCustom2 = Speed: 대체 2 standard = 속도: 표준 -State load undone = State load undone -Untitled PSP game = 이름 없는 PSP 게임 - -[Search] -Clear filter = Clear filter -Filter = Filter -Filtering settings by '%1' = Filtering settings by '%1' -Find settings = Find settings -No settings matched '%1' = No settings matched '%1' - +State load undone = 상태 로드 취소 +Untitled PSP game = 제목 없는 PSP 게임 [Store] -Already Installed = 이미 설치되어 있습니다 +Already Installed = 이미 설치됨 Connection Error = 연결 오류 Install = 설치 Launch Game = 게임 실행 -Loading... = 불러오는 중... +Loading... = 로딩 중... MB = MB Size = 크기 Uninstall = 제거 - [SysInfo] -%d (%d per core, %d cores) = %d (코어 당 %d, 코어 %d개) +%d (%d per core, %d cores) = %d (코어 당 %d, 코어 %d 개) %d bytes = %d 바이트 (none detected) = (감지되지 않음) 3D API = 3D API ABI = ABI API Version = API 버전 Audio Information = 오디오 정보 -Board = Board -Build Config = 빌드 설정 -Build Configuration = 빌드 설정 -Built by = 빌드 실행자 +Board = 보드 +Build Config = 빌드 구성 +Build Configuration = 빌드 구성 +Built by = 빌더 Core Context = 코어 컨텍스트 Cores = 코어 CPU Extensions = CPU 확장 CPU Information = CPU 정보 CPU Name = 이름 -D3DCompiler Version = D3DCompiler 버전 +D3DCompiler Version = D3D컴파일러 버전 Debug = 디버그 -Debugger Present = 디버거 표시 +Debugger Present = 디버거 탐지 Device Info = 장치 정보 -Directories = Directories -Display Color Formats = Display Color Formats -Display Information = 디스플레이 정보 -Driver bugs = Driver bugs +Directories = 디렉토리 +Display Information = 정보 표시 +Driver bugs = 드라이버 버그 Driver Version = 드라이버 버전 EGL Extensions = EGL 확장 Frames per buffer = 버퍼당 프레임 GPU Information = GPU 정보 -High precision float range = High precision float range -High precision int range = 정밀한 정수 범위 +High precision float range = 고정밀 부동소수점 범위 +High precision int range = 고정밀 정수 범위 Lang/Region = 언어/지역 Memory Page Size = 메모리 페이지 크기 Native Resolution = 기본 해상도 -No GPU driver bugs detected = No GPU driver bugs detected +No GPU driver bugs detected = GPU 드라이버 버그가 감지되지 않았음 OGL Extensions = OGL 확장 OpenGL ES 2.0 Extensions = OpenGL ES 2.0 확장 OpenGL ES 3.0 Extensions = OpenGL ES 3.0 확장 OpenGL Extensions = OpenGL 확장 Optimal frames per buffer = 버퍼당 최적 프레임 -Optimal sample rate = 최적 샘플 속도 +Optimal sample rate = 최적의 샘플 속도 OS Information = OS 정보 PPSSPP build = PPSSPP 빌드 Refresh rate = 주사율 -Release = 출시 -RW/RX exclusive = RW/RX 독점 +Release = 개정 +RW/RX exclusive = RW/RX 전용 Sample rate = 샘플 속도 -Shading Language = 셰이딩 언어 -Storage = Storage +Shading Language = 쉐이딩 언어 +Storage = 저장소 Sustained perf mode = 지속 성능 모드 System Information = 시스템 정보 -System Name = 시스템 이름 +System Name = 이름 System Version = 시스템 버전 Threads = 스레드 -Vendor = 공급 업체 -Vendor (detected) = 공급 업체 (감지됨) +Vendor = 공급업체 +Vendor (detected) = 공급업체 (탐지됨) Version Information = 버전 정보 -Vulkan Extensions = 벌칸 확장 -Vulkan Features = 벌칸 기능 - +Vulkan Extensions = Vulkan 확장 +Vulkan Features = Vulkan 기능 +Display Color Formats = 디스플레이 색상 형식 [System] -(broken) = (이용 불가) +(broken) = (고장) 12HR = 12시간 24HR = 24시간 Auto = 자동 Auto Load Savestate = 상태 저장 자동 불러오기 -AVI Dump started. = AVI 덤프 시작됨 -AVI Dump stopped. = AVI 덤프 정지됨 -Cache ISO in RAM = ISO 전체를 램에 캐싱 -Change CPU Clock = CPU 클럭 변경 (불안정) -Color Saturation = Color Saturation -Color Tint = Color Tint -Error: load undo state is from a different game = Error: load undo state is from a different game -Failed to load state for load undo. Error in the file system. = Failed to load state for load undo. Error in the file system. -Floating symbols = Floating symbols -Memory Stick folder = 메모리 스틱 폴더 변경 -Memory Stick size = Memory Stick size +AVI Dump started. = AVI 덤프가 시작됨 +AVI Dump stopped. = AVI 덤프가 중지됨 +Cache ISO in RAM = RAM에 전체 ISO 캐시 +Change CPU Clock = 에뮬레이트된 PSP의 CPU 클럭 변경 (불안정) +Memory Stick folder = 메모리 스틱 폴더 +Memory Stick size = 메모리 스틱 크기 Change Nickname = 별명 변경 -ChangingMemstickPath = 게임 저장, 상태 저장, 기타 데이터는 이 폴더에 복사되지 않습니다.\n\n메모리 스틱 폴더를 변경하시겠습니까? -ChangingMemstickPathInvalid = 이 경로는 메모리 스틱 파일을 저장하는데 사용할 수 없습니다. -Cheats = 치트 (실험적, 포럼 참조) +ChangingMemstickPath = 게임 저장, 상태 저장, 기타 데이터는 이 폴더에 복사되지 않습니다.\n\n메모리 스틱 폴더를 변경하겠습니까? +ChangingMemstickPathInvalid = 해당 경로는 메모리 스틱 파일을 저장하는 데 사용할 수 없습니다. +Cheats = 치트 Clear Recent = "최근" 지우기 -Clear Recent Games List = 최근 게임 목록 지우기 -Clear UI background = UI 배경화면 초기화 +Clear Recent Games List = "최근" 목록 지우기 +Clear UI background = UI 배경 지움 Confirmation Button = 확인 버튼 -Date Format = 날짜 표시 방식 +Date Format = 날짜 형식 Day Light Saving = 서머 타임 DDMMYYYY = DDMMYYYY Decrease size = 크기 줄이기 Developer Tools = 개발자 도구 Display Extra Info = 추가 정보 표시 -Display Games on a grid = 그리드에 "게임 탭" 표시 -Display Homebrew on a grid = 그리드에 "홈브류 및 데모 탭" 표시 -Display Recent on a grid = 그리드에 "최근 탭" 표시 +Display Games on a grid = 그리드에 "게임" 표시 +Display Homebrew on a grid = 그리드에 "홈브류 && 데모" 표시 +Display Recent on a grid = 그리드에 "최근" 표시 Dynarec (JIT) = 동적 재컴파일 (JIT) Emulation = 에뮬레이션 Enable Cheats = 치트 활성화 -Enable Compatibility Server Reports = 서버에 호환성 문제를 보고 -Failed to load state. Error in the file system. = 상태 저장을 불러올 수 없었습니다. 파일 시스템에 오류가 있습니다. -Failed to save state. Error in the file system. = 상태 저장을 저장할 수 없었습니다. 파일 시스템에 오류가 있습니다. -Fast (lag on slow storage) = 빠름 (느린 저장 장치에서 지연 발생) +Enable Compatibility Server Reports = 호환성 서버 보고서 활성화 +Error: load undo state is from a different game = 오류: 로드 취소 상태는 다른 게임에서 가져옴 +Failed to load state. Error in the file system. = 상태를 로드하지 못했습니다. 파일 시스템에 오류가 있습니다. +Failed to save state. Error in the file system. = 상태를 저장하지 못했습니다. 파일 시스템에 오류가 있습니다. +Failed to load state for load undo. Error in the file system. = 로드 실행 취소 상태를 로드하지 못했습니다. 파일 시스템에 오류가 있습니다. +Fast (lag on slow storage) = 빠름 (저속 저장 시 지연) Fast Memory = 빠른 메모리 (불안정) -Force real clock sync (slower, less lag) = 강제 실제 클럭 동기화 (느림, 약간의 지연) -frames, 0:off = 프레임, 0 = 끄기 +Floating symbols = 부동 기호 +Force real clock sync (slower, less lag) = 실제 클럭 동기화 강제 실행(느림, 지연 감소) +frames, 0:off = 프레임, 0 = 끔 Games list settings = 게임 목록 설정 General = 일반 Grid icon size = 그리드 아이콘 크기 Help the PPSSPP team = PPSSPP 팀 돕기 -Host (bugs, less lag) = 호스트 (버그, 약간의 지연) -Ignore bad memory accesses = Ignore bad memory accesses -Increase size = 크기 늘리기 +Host (bugs, less lag) = 호스트 (버그, 지연 감소) +Ignore bad memory accesses = 잘못된 메모리 접속 무시 +Increase size = 크기 증가 Interpreter = 해석기 -IO timing method = I/O 타이밍 방법 -IR Interpreter = IR 인터프리터 +IO timing method = I/O 타이밍 방식 +IR Interpreter = IR 해석기 Memory Stick Folder = 메모리 스틱 폴더 -Memory Stick inserted = 메모리 스틱 삽입됨 -MHz, 0:default = MHz, 0 = 기본 값 +Memory Stick inserted = 메모리 스틱 삽입 +MHz, 0:default = MHz, 0 = 기본 MMDDYYYY = MMDDYYYY -Moving background = Moving background -Newest Save = 제일 새로운 저장 -No animation = No animation +Moving background = 움직이는 배경 +Newest Save = 가장 최신 저장 +No animation = 애니메이션 없음 Not a PSP game = PSP 게임이 아님 -Off = 끄기 -Oldest Save = 제일 오래된 저장 -Path does not exist! = Path does not exist! -PSP Memory Stick = PSP Memory Stick -PSP Model = PSP 기종 +Off = 끔 +Oldest Save = 가장 오래된 저장 +Path does not exist! = 경로가 존재하지 않습니다! +PSP Memory Stick = PSP 메모리 스틱 +PSP Model = PSP 모델 PSP Settings = PSP 설정 PSP-1000 = PSP-1000 PSP-2000/3000 = PSP-2000/3000 -Recent games = Recent games -Record Audio = 소리 녹음하기 -Record Display = 영상 녹화하기 -Reset Recording on Save/Load State = 저장/불러올 때 기록된 것을 재설정하기 -Restore Default Settings = PPSSPP의 설정을 기본으로 복원 -Rewind Snapshot Frequency = 스냅샷 주기 되감기 (mem hog) -Save path in installed.txt = 경로를 installed.txt에 저장 -Save path in My Documents = 경로를 내 문서에 저장 -Savestate Slot = 상태 저장 슬롯 -Savestate slot backups = 상태 저장 백업 -Screenshots as PNG = PNG 형식으로 스크린샷 저장 -Set UI background... = UI 배경화면 지정하기... -Show ID = ID 보기 -Show Memory Stick folder = Show Memory Stick folder -Show region flag = 지역코드 플래그 보기 +Recent games = 최근 게임 +Record Audio = 오디오 녹음 +Record Display = 녹화 표시 +Reset Recording on Save/Load State = 저장/불러오기 상태에서 녹화 재설정 +Restore Default Settings = PPSSPP의 설정을 기본값으로 복원 +Rewind Snapshot Frequency = 되감기 스냅샷 빈도 (메모리 호그) +Save path in installed.txt = install.txt에 경로 저장 +Save path in My Documents = 내 문서에 경로 저장 +Savestate Slot = 저장 상태 슬롯 +Savestate slot backups = 저장 상태 슬롯 백업 +Screenshots as PNG = 스크린샷을 PNG 형식으로 저장 +Set UI background... = UI 배경 설정... +Show ID = ID 표시 +Show region flag = 지역 플래그 표시 Simulate UMD delays = UMD 지연 시뮬레이션 Slot 1 = 슬롯 1 Slot 2 = 슬롯 2 Slot 3 = 슬롯 3 Slot 4 = 슬롯 4 Slot 5 = 슬롯 5 -Storage full = 저장 공간 가득참 +Storage full = 저장 공간 가득 참 Sustained performance mode = 지속 성능 모드 -Theme = Theme -Time Format = 시간 표시 방식 -UI = 사용자 인터페이스 -UI background animation = UI background animation -UI Sound = UI sound +Time Format = 시간 형식 +UI = UI +UI Sound = UI 사운드 +UI background animation = UI 배경 애니메이션 undo %c = %c 백업 USB = USB Use Lossless Video Codec (FFV1) = 무손실 비디오 코덱 사용 (FFV1) -Use O to confirm = 확인 버튼으로 O 사용 -Use output buffer (with overlay) for recording = 기록에 출력 버퍼(오버레이 포함) 사용 +Use O to confirm = O를 확인 버튼으로 사용 +Use output buffer (with overlay) for recording = 기록을 위해 (오버레이가 있는) 출력 버퍼 사용 Use system native keyboard = 시스템 기본 키보드 사용 -Use X to confirm = 확인 버튼으로 X 사용 -VersionCheck = PPSSPP의 새로운 버전을 확인 -WARNING: Android battery save mode is on = 주의: 안드로이드 배터리 절약 모드가 켜짐 -WARNING: Battery save mode is on = 주의: 배터리 절약 모드가 켜짐 -Waves = Waves +Use X to confirm = X를 확인 버튼으로 사용 +VersionCheck = PPSSPP의 새 버전 확인 +WARNING: Android battery save mode is on = 경고: 안드로이드 배터리 절약 모드가 켜져 있음 +WARNING: Battery save mode is on = 경고: 배터리 절약 모드가 켜져 있음 +Waves = 파형 YYYYMMDD = YYYYMMDD - -[TextureShaders] -Off = Off -TexMMPX = TexMMPX -Tex2xBRZ = Tex2xBRZ -Tex4xBRZ = Tex4xBRZ +Theme = 테마 +Color Tint = 색조 +Color Saturation = 채도 +Show Memory Stick folder = 메모리 스틱 폴더 표시 [Themes] -Default = Default +Default = 기본 + +[TextureShaders] +Off = 끔 +TexMMPX = TexMMPX +Tex2xBRZ = Tex2xBRZ +Tex4xBRZ = Tex4xBRZ + +[Search] +No settings matched '%1' = '%1'과(와) 일치하는 설정이 없음 +Filtering settings by '%1' = '%1'(으)로 설정 필터링 +Find settings = 찾기 설정 +Filter = 필터 +Clear filter = 필터 지움 -[UI Elements] -%1 button = %1 button -%1 checkbox = %1 checkbox -%1 choice = %1 choice -%1 heading = %1 heading -%1 radio button = %1 radio button -%1 text field = %1 text field -Choices: = Choices: -List: = List: -Progress: %1% = Progress: %1% -Screen representation = Screen representation [Upgrade] -Details = Details +Details = 상세 Dismiss = 거절 Download = 다운로드 -New version of PPSSPP available = 새로운 버전의 PPSSPP를 이용할 수 있습니다. +New version of PPSSPP available = PPSSPP의 새 버전 사용 가능 + +[UI Elements] +%1 button = %1 버튼 +%1 checkbox = %1 체크박스 +%1 choice = %1 선택 +%1 heading = %1 제목 +%1 radio button = %1 라디오 버튼 +%1 text field = %1 텍스트 필드 +Choices: = 선택: +List: = 목록: +Progress: %1% = 진행율: %1% +Screen representation = 화면 표현 From 1c882e3c638ec910fb644b206940effa3741f56a Mon Sep 17 00:00:00 2001 From: DDinghoya Date: Fri, 19 Aug 2022 16:49:51 +0900 Subject: [PATCH 14/85] Update ko_KR.ini Minor update#3 --- assets/lang/ko_KR.ini | 359 +++++++++++++++++++++--------------------- 1 file changed, 178 insertions(+), 181 deletions(-) diff --git a/assets/lang/ko_KR.ini b/assets/lang/ko_KR.ini index e6dad1ac55..3d08de9745 100644 --- a/assets/lang/ko_KR.ini +++ b/assets/lang/ko_KR.ini @@ -121,30 +121,30 @@ Refresh Rate = 주사율 [DesktopUI] # If your language does not show well with the default font, you can use Font to specify a different one. # Just add it to your language's ini file and uncomment it (remove the # by Font). -Auto Max Quality = Auto Max &Quality Font = NanumGothic About PPSSPP... = PPSSPP 정보(&A)... Auto = 자동(&A) -Backend = 렌더링 처리자(&B) (PPSSPP 재시작) -Bicubic = 쌍입방(&B) -Break = 중단 -Break on Load = 불러올 때 중단 +Auto Max Quality = 자동 최대 품질(&Q) +Backend = 렌더링 백엔드(&B) (PPSSPP 재시작) +Bicubic = 고등차수보간(&B) +Break = 증딘 +Break on Load = 로드 시 중단 Buffered Rendering = 버퍼링된 렌더링(&B) Buy Gold = 골드 버전 구매(&G) -Control Mapping... = 컨트롤 맵핑(&O)... +Control Mapping... = 제어 맵핑(&O)... Debugging = 디버그(&D) Deposterize = 색조 융합(&D) -Direct3D9 = Direct3D 9(&D) -Direct3D11 = Direct3D &11 +Direct3D9 = Direct3D 9(&9) +Direct3D11 = Direct3D 11(&1) Disassembly = 역어셈블리(&D)... -Discord = Discord -Display Layout Editor = 화면 레이아웃 편집기... +Discord = 디스코드 +Display Layout Editor = 레이아웃 편집기 표시... Display Rotation = 화면 회전 Dump Next Frame to Log = 로그에 다음 프레임 덤프(&U) Emulation = 에뮬레이션(&E) Enable Cheats = 치트 활성화(&C) Enable Sound = 사운드 활성화(&O) -Exit = 종료(&X) +Exit =종료(&X) Extract File... = 파일 추출(&X)... File = 파일(&F) Frame Skipping = 프레임 생략(&F) @@ -152,55 +152,55 @@ Frame Skipping Type = 프레임 생략 유형 Fullscreen = 전체 화면(&L) Game Settings = 게임 설정(&G) GE Debugger... = GE 디버거(&R)... -GitHub = Git&Hub +GitHub = 깃허브(&H) Hardware Transform = 하드웨어 변환(&H) Help = 도움말(&H) Hybrid = 혼합(&H) -Hybrid + Bicubic = 혼합 + 쌍입방(&Y) +Hybrid + Bicubic = 혼합 + 고등차수보간(&Y) Ignore Illegal Reads/Writes = 잘못된 읽기/쓰기 무시(&I) -Ignore Windows Key = 윈도우 키 무시 +Ignore Windows Key = 윈도우즈 키 무시 Keep PPSSPP On Top = PPSSPP 항상 위에 표시(&K) -Landscape = 가로 -Landscape reversed = 가로 반전 +Landscape = 가로방향 +Landscape reversed = 가로방향 반전 Language... = 언어(&N)... Linear = 선형 필터링(&L) Load = 불러오기(&L)... Load .sym File... = sym 파일 불러오기(&A)... -Load Map File... = 맵 파일 불러오기(&M)... +Load Map File... = Map 파일 불러오기(&M)... Load State = 상태 불러오기(&O) Load State File... = 상태 파일 불러오기(&L)... Log Console = 콘솔 로그(&L) -Memory View... = 메모리 뷰(&V)... +Memory View... = 메모리 보기(&V)... More Settings... = 기타 설정(&M)... Nearest = 근접 필터링(&N) -Non-Buffered Rendering = 버퍼 없는 렌더링(&S) -Off = 끄기(&O) -Open Chat = Open Chat +Non-Buffered Rendering = 버퍼 효과 건너뛰기(버퍼되지 않음, 더 빠름)(&S) +Off = 끔(&O) +Open Chat = 채팅 열기 Open Directory... = 디렉터리 열기(&D)... Open from MS:/PSP/GAME... = MS:/PSP/GAME에서 열기(&P)... Open Memory Stick = 메모리 스틱 열기(&M) -Open New Instance = Open new instance +Open New Instance = 새로운 인스턴트 열기 OpenGL = OpenGL(&O) Pause = 일시 정지(&P) Pause When Not Focused = 포커싱되지 않았을 때 일시 정지(&P) -Portrait = 세로 -Portrait reversed = 세로 반전 +Portrait = 세로방향 +Portrait reversed = 세로방향 반전 Postprocessing Shader = 후처리 셰이더(&G) PPSSPP Forums = PPSSPP 포럼(&F) -Record = 기록(&R) -Record Audio = 소리 녹음(&A) +Record = 녹음(&R) +Record Audio = 사운드 녹음(&A) Record Display = 영상 녹화(&D) -Rendering Mode = 렌더링 방식(&O) +Rendering Mode = 렌더링 모드(&O) Rendering Resolution = 렌더링 해상도(&R) -Reset = 리셋(&E) -Reset Symbol Table = 심볼 테이블 리셋(&Y) +Reset = 재설정(&E) +Reset Symbol Table = 심볼 테이블 재설정(&Y) Run = 실행(&R) Save .sym File... = sym 파일 저장하기(&E)... -Save Map File... = 맵 파일 저장하기(&S)... +Save Map File... = map 파일 저장하기(&S)... Save State = 상태 저장하기(&A) Save State File... = 상태 파일 저장하기(&S)... Savestate Slot = 상태 저장 슬롯(&T) -Screen Scaling Filter = 화면 크기 조절 필터(&E) +Screen Scaling Filter = 화면 크기 조정 필터(&E) Show Debug Statistics = 디버그 통계 표시(&G) Show FPS Counter = FPS 카운터 표시(&F) Skip Number of Frames = 프레임 수 생략 @@ -212,210 +212,208 @@ Texture Filtering = 텍스처 필터링(&X) Texture Scaling = 텍스처 크기 조절(&T) Use Lossless Video Codec (FFV1) = 무손실 비디오 코덱 사용 (FFV1)(&U) Use output buffer for video = 비디오에 출력 버퍼 사용 -Vertex Cache = 버텍스 캐시(&V) -VSync = 수직 동기(&Y) -Vulkan = 벌칸(Vulkan) +Vertex Cache = 정점 캐시(&V) +VSync = 수직 동기화(&Y) +Vulkan = Vulkan Window Size = 창 크기(&W) -www.ppsspp.org = www.ppsspp.org 방문(&P) -xBRZ = xBRZ(&X) +www.ppsspp.org = www.&ppsspp.org 방문 +xBRZ = xBRZ 필터(&X) [Developer] -Allocator Viewer = 할당기(Allocator) 뷰어 (Vulkan) +Allocator Viewer = 할당기 뷰어 (Vulkan) Allow remote debugger = 원격 디버거 허용 Backspace = 백스페이스 -Block address = 주소를 차단 -By Address = 주소로 -Copy savestates to memstick root = Copy save states to Memory Stick root -Create/Open textures.ini file for current game = 현재 게임의 textures.ini 파일 생성 및 열기 +Block address = 주소 차단 +By Address = 주소별 +Copy savestates to memstick root = 메모리 스틱 루트에 저장 상태 복사 +Create/Open textures.ini file for current game = 현재 게임에 대한 textures.ini 파일 생성/열기 Current = 현재 -Dev Tools = 개발자 도구 -DevMenu = 개발 메뉴 -Disabled JIT functionality = 비활성화 된 JIT 기능 -Draw Frametimes Graph = 프레임 레이트 그래프 그리기 -Dump Decrypted Eboot = 게임 부팅 시 복호화된 EBOOT.BIN 덤프 (암호화 되어 있는 경우) -Dump Frame GPU Commands = 프레임 GPU 명령어를 덤프 -Enable driver bug workarounds = Enable driver bug workarounds +Dev Tools = 개발 도구 +DevMenu = 개발메뉴 +Disabled JIT functionality = 비활성화된 JIT 기능 +Draw Frametimes Graph = 프레임 시간 그래프 그리기 +Dump Decrypted Eboot = 게임 부팅 시 해독된 EBOOT.BIN 덤프 +Dump Frame GPU Commands = 덤프 프레임 GPU 명령 +Enable driver bug workarounds = 드라이버 버그 해결 방법 활성화 Enable Logging = 디버그 로깅 활성화 Enter address = 주소 입력 FPU = FPU -Framedump tests = Framedump tests +Framedump tests = 프레임 덤프 테스트 Frame Profiler = 프레임 프로파일러 GPU Driver Test = GPU 드라이버 테스트 -GPU Log Profiler = GPU Log Profiler GPU Profile = GPU 프로파일 +GPU Log Profiler = GPU 로그 프로파일러 Jit Compare = JIT 비교 -JIT debug tools = JIT 디버그 툴 +JIT debug tools = JIT 디버그 도구 Language = 언어 -Load language ini = 언어 ini 불러오기 -Log Dropped Frame Statistics = 프레임 저하 통계 기록하기 -Log Level = 로그 깊이 +Load language ini = 언어 ini 로드 +Log Dropped Frame Statistics = 삭제된 프레임 통계 기록 +Log Level = 로그 레벨 Log View = 로그 보기 Logging Channels = 로깅 채널 Next = 다음 -No block = 블록 없음 +No block = 차단 없음 Prev = 이전 Random = 랜덤 -Replace textures = 텍스처 덮어쓰기 -Reset = Reset -Reset limited logging = Reset limited logging -RestoreDefaultSettings = 모든 설정을 다시 기본으로 복원 하시겠습니까?\n컨트롤 맵핑 설정은 변경되지 않습니다.\n\n\n이 작업은 되돌릴 수 없습니다.\n변경 사항을 적용하기 위해 PPSSPP를 재시작해 주십시오. -RestoreGameDefaultSettings = 게임 지정 설정을 다시\nPPSSPP 기본 설정으로 복원하시겠습니까? -Resume = Resume +Replace textures = 텍스처 교체 +Reset = 재설정 +Reset limited logging = 제한된 로깅 재설정 +RestoreDefaultSettings = 모든 설정을 기본값으로 되돌리겠습니까?\n제어 매핑 설정은 변경되지 않습니다.\n\n이 작업은 취소할 수 없습니다.\n변경 사항을 적용하려면 PPSSPP를 다시 시작하세요. +RestoreGameDefaultSettings = 게임별 설정을\nPPSSPP 기본값으로 복원하겠습니까? +Resume = 다시 시작 Run CPU Tests = CPU 테스트 실행 -Save language ini = 언어 ini 저장하기 +Save language ini = 언어 ini 저장 Save new textures = 새로운 텍스처 저장 Shader Viewer = 셰이더 뷰어 Show Developer Menu = 개발자 메뉴 표시 -Show on-screen messages = Show on-screen messages +Show on-screen messages = 화면 메시지 표시 Stats = 상태 System Information = 시스템 정보 -Texture ini file created = Texture ini file created -Texture Replacement = 텍스처 교체하기 +Texture ini file created = 텍스처 ini 파일 생성 +Texture Replacement = 텍스쳐 교체 Toggle Audio Debug = 오디오 디버그 토글 -Toggle Freeze = 토글 프리징 -Touchscreen Test = 터치 스크린 테스트 +Toggle Freeze = 프리징 토글 +Touchscreen Test = 터치화면 테스트 VFPU = VFPU - [Dialog] * PSP res = * PSP 리소스 Active = 활성화 -Back = 뒤로 +Back = 뒤로가기 Cancel = 취소 Center = 중앙 -ChangingGPUBackends = GPU 처리자를 변경하기 위해서는 PPSSPP를 재시작해야 합니다. 재시작할까요? -ChangingInflightFrames = 그래픽 커멘드 버퍼링을 변경하기 위해서는 PPSSPP를 재시작해야 합니다. 재시작할까요? -Channel: = Channel: +ChangingGPUBackends = GPU 백엔드를 변경하려면 PPSSPP를 다시 시작해야 합니다. 지금 다시 시작하겠습니까? +ChangingInflightFrames = 그래픽 명령 버퍼링을 변경하려면 PPSSPP를 다시 시작해야 합니다. 지금 다시 시작하겠습니까? +Channel: = 채널: Choose PPSSPP save folder = PPSSPP 저장 폴더 선택 -Confirm Overwrite = 데이터를 덮어쓰시겠습니까? -Confirm Save = 이 데이터를 저장하시겠습니까? -ConfirmLoad = 이 데이터를 불러오시겠습니까? -ConnectingAP = Connecting to the access point.\nPlease wait... -ConnectingPleaseWait = Connecting.\nPlease wait... -ConnectionName = Connection name -Corrupted Data = Corrupted data +Confirm Overwrite = 데이터를 덮어쓰겠습니까? +Confirm Save = 이 데이터를 저장하겠습니까? +ConfirmLoad = 이 데이터를 로드하겠습니까? +ConnectingAP = 접속 포인트에 연결하는 중입니다.\n잠시만 기다려 주세요... +ConnectingPleaseWait = 연결 중입니다.\n잠시만 기다려 주세요... +ConnectionName = 결 이름 +Corrupted Data = 손상된 데이터 Delete = 삭제 -Delete all = 전체 삭제 -Delete completed = 삭제를 완료했습니다. -DeleteConfirm = 이 데이터는 삭제됩니다.\n계속하시겠습니까? -DeleteConfirmAll = 이 게임에 대한 모든 저장 데이터를\n삭제하시겠습니까? -DeleteConfirmGame = 이 게임을 정말로 당신의 장치에서\n삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다. -DeleteConfirmGameConfig = 이 게임의 설정을 정말로 삭제하시겠습니까? -DeleteFailed = 삭제할 수 없습니다. -Deleting = 삭제 중입니다.\n잠시 기다려 주세요... +Delete all = 모두 삭제 +Delete completed = 삭제가 완료되었습니다. +DeleteConfirm = 이 저장 데이터는 삭제됩니다.\n계속하겠습니까? +DeleteConfirmAll = 이 게임에 대한 모든 저장 데이터를\n삭제하겠습니까? +DeleteConfirmGame = 이 게임을 정말로 장치에서\n삭제하겠습니까? 이 작업은 취소할 수 없습니다. +DeleteConfirmGameConfig = 이 게임의 설정을 삭제하겠습니까? +DeleteFailed = 데이터를 삭제할 수 없습니다. +Deleting = 삭제 중\n잠시만 기다려 주세요... Disable All = 모두 비활성화 -Dumps = Dumps -Edit = Edit +Dumps = 덤프 +Edit = 편집 Enable All = 모두 활성화 -Enter = 결정 -Filter = Filter -Finish = 완료 -GE Frame Dumps = GE Frame Dumps -Grid = 격자 -Inactive = 비활성화 -InternalError = An internal error has occurred. -Load = 불러오기 -Load completed = 불러오기를 완료했습니다. -Loading = 불러오는 중입니다.\n잠시 기다려 주세요... -LoadingFailed = 불러올 수 없습니다. +Enter = 입력 +Filter = 필터 +Finish = 마침 +GE Frame Dumps = GE 프레임 덤프 +Grid = 그리드 +Inactive = 비활성 +InternalError = 내부 오류가 발생했습니다. +Load = 로드 +Load completed = 로드가 완료되었습니다. +Loading = 로딩 중\n잠시만 기다려 주세요... +LoadingFailed = 데이터를 로드할 수 없습니다. Move = 이동 Network Connection = 네트워크 연결 NEW DATA = 새로운 데이터 No = 아니오 -ObtainingIP = Obtaining IP address.\nPlease wait... +ObtainingIP = IP 주소를 가져오는 중입니다.\n잠시만 기다려 주세요... OK = 확인 -Old savedata detected = 구 버전 저장 데이터 감지됨 +Old savedata detected = 오래된 저장 데이터 감지됨 Options = 옵션 -Reset = 리셋 +Reset = 재설정 Resize = 크기 조정 -Retry = 다시 시도 -Save = 저장하기 -Save completed = 저장을 완료했습니다. -Saving = 저장 중입니다.\n잠시 기다려 주세요... -SavingFailed = 저장할 수 없습니다. -Search = Search +Retry = 재시도 +Save = 저장 +Save completed = 저장이 완료되었습니다. +Saving = 저장 중\n잠시만 기다려 주세요... +SavingFailed = 데이터를 저장할 수 없습니다. +Search = 검색 Select = 선택 Shift = 전환 -Skip = Skip -Snap = Snap -Space = 스페이스 +Skip = 건너뜀 +Snap = 스냅 +Space = 공간 SSID = SSID Submit = 전송 Supported = 지원 There is no data = 데이터가 없습니다. -Toggle All = 전체 선택 -Toggle List = Toggle list -Unsupported = 지원되지 않음 -When you save, it will load on a PSP, but not an older PPSSPP = 저장할 경우 PSP에서는 불러올 수 있지만 구 버전의 PPSSPP에서는 불러올 수 없습니다. -When you save, it will not work on outdated PSP Firmware anymore = 저장할 경우 더 이상 구 버전의 PSP 펌웨어에서는 작동하지 않을 것입니다. -Yes = 네 -Zoom = 확대 +Toggle All = 모두 토글 +Toggle List = 토글 목록 +Unsupported = 미지원 +When you save, it will load on a PSP, but not an older PPSSPP = 저장하면 PSP에 로드되지만 이전 PPSSPP에는 로드되지 않습니다. +When you save, it will not work on outdated PSP Firmware anymore = 저장하면 오래된 PSP 펌웨어에서는 더 이상 작동하지 않습니다. +Yes = 예 +Zoom = 확대/축소 [Error] -7z file detected (Require 7-Zip) = 파일이 7z 형식으로 압축되어 있습니다.\n먼저 압축을 해제해 주십시오. (7-Zip 또는 WinRAR) +7z file detected (Require 7-Zip) = 파일은 (7z로) 압축되어 있습니다.\n먼저 압축을 해제하십시오 (7-Zip 또는 WinRAR 시도). A PSP game couldn't be found on the disc. = 디스크에서 PSP 게임을 찾을 수 없습니다. -Cannot boot ELF located outside mountRoot. = 삽입된 Root 이외의 경로에 위치한 ELF는 부팅할 수 없습니다. +Cannot boot ELF located outside mountRoot. = mountRoot 외부에 있는 ELF를 부팅할 수 없습니다. Could not save screenshot file = 스크린샷 파일을 저장할 수 없습니다. -D3D9or11 = Direct3D 9를 사용할까요? ("아니오"를 선택할 경우 Direct3D 11를 사용합니다.) -D3D11CompilerMissing = D3DCompiler_47.dll 을 찾을 수 없었습니다. 설치한 후 재시도하거나 대신 예 버튼을 눌러 Direct3D 9 를 사용할 수 있습니다. +D3D9or11 = 다이렉트3D 9? (또는 Direct3D 11의 경우 "아니오") +D3D11CompilerMissing = D3DCompiler_47.dll을 찾을 수 없습니다. 설치하세요. 또는 예를 눌러 대신 Direct3D 9를 사용하여 다시 시도하세요. D3D11InitializationError = Direct3D 11 초기화 오류 -D3D11Missing = 현재 사용중인 OS가 D3D11을 포함하지 않고 있습니다. 업데이트를 진행해 보십시오.\n\n예를 눌러 Direct3D 9를 대신 사용합니다. -D3D11NotSupported = 현재 사용중인 GPU가 Direct3D 11을 지원하지 않습니다.\n\n예를 눌러 Direct3D 9를 대신 사용할 수 있습니다. -Disk full while writing data = 데이터를 쓰는 도중 디스크가 가득 찼습니다. -ELF file truncated - can't load = ELF 파일이 불완전합니다 - 불러올 수 없습니다. -Error loading file = 파일 불러오는 중 오류 : -Error reading file = 파일을 읽는 동안 오류가 발생했습니다. -Failed initializing CPU/Memory = Failed initializing CPU or memory -Failed to load executable: = 실행 파일을 불러오는데 실패했습니다: -File corrupt = 파일이 손상되었습니다. -Game disc read error - ISO corrupt = 게임 디스크 읽기 오류: ISO 파일이 손상되었습니다. -GenericAllStartupError = PPSSPP failed to start up with any graphics backend. Try upgrading your graphics and other drivers. -GenericBackendSwitchCrash = PPSSPP crashed while starting.\n\nThis usually means a graphics driver problem. Try upgrading your graphics drivers.\n\nGraphics backend has been switched: -GenericDirect3D9Error = Direct 3D 9 그래픽 초기화에 실패했습니다. 그래픽 드라이버와 DirectX 9 런타임을 업데이트해 보십시오.\n\nOpenGL으로 전환해 보시겠습니까?\n\오류 메시지: +D3D11Missing = 운영 체제 버전에 D3D11이 포함되어 있지 않습니다. 윈도우즈 업데이트를 실행하세요.\n\n대신 Direct3D 9를 사용하여 다시 시도하려면 예를 누르세요. +D3D11NotSupported = GPU가 Direct3D 11을 지원하지 않는 것 같습니다.\n\n대신 Direct3D 9를 사용하여 다시 시도하겠습니까? +Disk full while writing data = 데이터를 쓰는 동안 디스크가 가득 찼습니다. +ELF file truncated - can't load = ELF 파일이 불완전함 - 로드할 수 없음 +Error loading file = 게임을 로드할 수 없습니다. +Error reading file = 파일 읽기 오류입니다. +Failed initializing CPU/Memory = CPU 또는 메모리 초기화 실패 +Failed to load executable: = 실행 파일 로드 실패: +File corrupt = 파일 손상 +Game disc read error - ISO corrupt = 게임 디스크 읽기 오류: ISO 손상되었습니다. +GenericAllStartupError = PPSSPP가 그래픽 백엔드로 시작하지 못했습니다. 그래픽 및 기타 드라이버를 업그레이드해 보세요. +GenericBackendSwitchCrash = 시작하는 동안 PPSSPP가 충돌했습니다.\n\n이것은 일반적으로 그래픽 드라이버 문제를 의미합니다. 그래픽 드라이버를 업그레이드해 보세요.\n\n그래픽 백엔드가 전환되었습니다: +GenericDirect3D9Error = 그래픽 초기화에 실패했습니다. 그래픽 드라이버와 DirectX 9 런타임을 업그레이드해 보세요.\n\nOpenGL로 전환하시겠습니까?\n\n오류 메세지: GenericGraphicsError = 그래픽 오류 -GenericOpenGLError = OpenGL 그래픽 초기화에 실패했습니다. 그래픽 드라이버를 업데이트해 보십시오.\n\nDirectX 9로 전환해 보시겠습니까?\n\n오류 메시지: -GenericVulkanError = Vulkan 그래픽 초기화에 실패했습니다. 그래픽 드라이버를 업데이트해 보십시오.\n\nOpenGL으로 전환해 보시겠습니까?\n\n오류 메시지: -InsufficientOpenGLDriver = OpenGL 드라이버 지원 부족 감지!\n\n현재 PPSSPP를 실행하는데 필요한 OpenGL 2.0을 지원하지 않는 것 같습니다.\n\n당신의 GPU가 OpenGL 2.0과 호환되는지 확인해 주십시오. 호환되는 경우, 당신의 GPU 공급업체의 웹사이트에서 새로운 그래픽 드라이버를 찾아서 설치해야 합니다.\n\n자세한 내용은 https://forums.ppsspp.org 포럼을 방문하십시오. -Just a directory. = 디렉토리 입니다. -Missing key = 키가 누락되었습니다. -MsgErrorCode = Error code: -MsgErrorSavedataDataBroken = Save data was corrupt. -MsgErrorSavedataMSFull = Memory Stick full. Check your storage space. -MsgErrorSavedataNoData = Warning: no save data was found. -MsgErrorSavedataNoMS = Memory Stick not inserted. -No EBOOT.PBP, misidentified game = EBOOT.PBP가 없으면, 게임을 식별할 수 없습니다. +GenericOpenGLError = 그래픽 초기화에 실패했습니다. 그래픽 드라이버를 업그레이드해 보세요.\n\nDirectX 9로 전환하겠습니까?\n\n오류 메세지: +GenericVulkanError = 그래픽 초기화에 실패했습니다. 그래픽 드라이버를 업그레이드해 보세요.\n\nOpenGL로 전환하겠습니까?\n\n오류 메세지: +InsufficientOpenGLDriver = 불충분한 OpenGL 드라이버 지원이 감지되었습니다!\n\nGPU가 OpenGL 2.0을 지원하지 않는다고 보고합니다. DirectX를 대신 사용하겠습니까?\n\nDirectX는 현재 더 적은 수의 게임과 호환되지만 GPU에서는 유일한 선택일 수 있습니다.\n\n자세한 내용은 https://forums.ppsspp.org의 포럼을 방문하세요.\n\n +Just a directory. = 그냥 디렉토리입니다. +Missing key = 키 누락 +MsgErrorCode = 오류 코드: +MsgErrorSavedataDataBroken = 저장 데이터가 손상되었습니다. +MsgErrorSavedataMSFull = 메모리 스틱이 가득 찼습니다. 저장 공간을 확인하세요. +MsgErrorSavedataNoData = 경고: 저장 데이터를 찾을 수 없습니다. +MsgErrorSavedataNoMS = 메모리 스틱이 삽입되지 않았습니다. +No EBOOT.PBP, misidentified game = EBOOT.PBP 없음, 잘못 식별된 게임입니다. Not a valid disc image. = 유효한 디스크 이미지가 아닙니다. OpenGLDriverError = OpenGL 드라이버 오류 -PPSSPP doesn't support UMD Music. = PPSSPP는 UMD 음악을 지원하지 않습니다. +PPSSPP doesn't support UMD Music. = PPSSPP는 UMD Music을 지원하지 않습니다. PPSSPP doesn't support UMD Video. = PPSSPP는 UMD 비디오를 지원하지 않습니다. -PPSSPP plays PSP games, not PlayStation 1 or 2 games. = PPSSPP plays PSP games, not PlayStation 1 or 2 games. -PPSSPPDoesNotSupportInternet = PPSSPP는 현재 DLC, PSN, 게임 업데이트에 대한 인터넷 연결을 지원하지 않습니다. -PS1 EBOOTs are not supported by PPSSPP. = PS1 EBOOTs는 PPSSPP에서 지원되지 않습니다. -PSX game image detected. = MODE2 이미지 파일입니다. PPSSPP는 PS1 게임을 지원하지 않습니다. -RAR file detected (Require UnRAR) = 파일이 RAR 형식으로 압축되어 있습니다.\n먼저 압축을 해제해 주십시오. (UnRAR로 시도) -RAR file detected (Require WINRAR) = 파일이 RAR 형식으로 압축되어 있습니다.\n먼저 압축을 해제해 주십시오. (WinRAR로 시도) -Running slow: try frameskip, sound is choppy when slow = 느리게 작동 중입니다: 게임 소리가 제대로 재생되지 않을 경우 프레임 스킵을 시도해 보십시오. -Running slow: Try turning off Software Rendering = 느리게 작동 중입니다: 소프트웨어 렌더링 모드를 해제해 보십시오. -Save encryption failed. This save won't work on real PSP = 저장 파일 암호화에 실패했습니다. 이 저장 파일은 실제 PSP상에서 동작하지 않을 것입니다. -textures.ini filenames may not be cross-platform = 다른 운영체제의 "textures.ini" 파일을 사용할 수 없습니다. -This is a saved state, not a game. = 게임이 아닌 상태 저장 파일입니다. 게임 파일을 선택해 주십시오. -This is save data, not a game. = 게임이 아닌 저장 파일입니다. 게임 파일을 선택해 주십시오. -Unable to create cheat file, disk may be full = 치트 파일을 생성할 수 없습니다. 디스크 용량이 꽉 찼을 수도 있습니다. +PPSSPP plays PSP games, not PlayStation 1 or 2 games. = PPSSPP는 플레이스테이션 1 또는 2 게임이 아닌 PSP 게임을 실행합니다. +PPSSPPDoesNotSupportInternet = PPSSPP는 현재 DLC, PSN 또는 게임 업데이트를 위한 인터넷 연결을 지원하지 않습니다. +PS1 EBOOTs are not supported by PPSSPP. = 플레이스테이션 1 EBOOT는 PPSSPP에서 지원되지 않습니다. +PSX game image detected. = 파일은 MODE2 이미지입니다. PPSSPP는 플레이스테이션 1 게임을 지원하지 않습니다. +RAR file detected (Require UnRAR) = 파일은 (RAR로) 압축되어 있습니다.\n먼저 압축을 해제하세요 (UnRAR 시도). +RAR file detected (Require WINRAR) = 파일은 (RAR로) 압축되어 있습니다.\n먼저 압축을 해제하세요 (WinRAR 시도). +Running slow: try frameskip, sound is choppy when slow = 느리게 실행: 프레임생략 시도, 느릴 때 소리가 고르지 않음 +Running slow: Try turning off Software Rendering = 느리게 실행: "소프트웨어 렌더링" 끄기 시도 +Save encryption failed. This save won't work on real PSP = 저장 암호화에 실패했습니다. 이 저장은 실제 PSP에서 작동하지 않습니다. +textures.ini filenames may not be cross-platform = "textures.ini" 파일 이름은 크로스 플랫폼이 아닐 수 있습니다. +This is a saved state, not a game. = 이것은 게임이 아닌 저장된 상태입니다. +This is save data, not a game. = 이것은 게임이 아닌 세이브 데이터입니다. +Unable to create cheat file, disk may be full = 치트 파일을 생성할 수 없습니다. 디스크가 가득 찼을 수 있습니다. Unable to initialize rendering engine. = 렌더링 엔진을 초기화할 수 없습니다. -Unable to write savedata, disk may be full = 저장 파일을 작성할 수 없습니다. 디스크 용량이 꽉 찼을 수도 있습니다. -Warning: Video memory FULL, reducing upscaling and switching to slow caching mode = 경고: 비디오 메모리가 꽉 찼습니다. 업스케일링을 줄이고 느린 캐시 모드로 전환합니다. -Warning: Video memory FULL, switching to slow caching mode = 경고: 비디오 메모리가 꽉 찼습니다. 느린 캐시 모드로 전환합니다. -ZIP file detected (Require UnRAR) = 파일이 ZIP 형식으로 압축되어 있습니다.\n먼저 압축을 해제해 주십시오. (UnRAR로 시도) -ZIP file detected (Require WINRAR) = 파일이 ZIP 형식으로 압축되어 있습니다.\n먼저 압축을 해제해 주십시오. (WinRAR로 시도) - +Unable to write savedata, disk may be full = 저장 데이터를 쓸 수 없습니다. 디스크가 가득 찼을 수 있습니다. +Warning: Video memory FULL, reducing upscaling and switching to slow caching mode = 경고: 비디오 메모리가 가득 찼서, 업스케일링을 줄이고 느린 캐싱 모드로 전환합니다. +Warning: Video memory FULL, switching to slow caching mode = 비디오 메모리가 가득 찼서, 저속 캐싱 모드로 전환합니다. +ZIP file detected (Require UnRAR) = 파일은 (ZIP으로) 압축되어 있습니다.\n먼저 압축을 해제하세요 (UnRAR 시도). +ZIP file detected (Require WINRAR) = 파일은 (ZIP으로) 압축되어 있습니다.\n먼저 압축을 해제하세요 (WinRAR 시도). [Game] Asia = 아시아 -Calculate CRC = Calculate CRC +Calculate CRC = CRC 계산 ConfirmDelete = 삭제 -Create Game Config = 게임 설정파일 만들기 -Create Shortcut = 바로가기 만들기 +Create Game Config = 게임 구성 생성 +Create Shortcut = 단축 키 생성 Delete Game = 게임 삭제 -Delete Game Config = 게임 설정파일 삭제 -Delete Save Data = 저장 데이터 삭제 +Delete Game Config = 게임 구성 삭제 +Delete Save Data = 저장데이터 삭제 Europe = 유럽 Game = 게임 Game Settings = 게임 설정 @@ -423,17 +421,16 @@ Homebrew = 홈브류 Hong Kong = 홍콩 InstallData = 데이터 설치 Japan = 일본 -Korea = 대한민국 +Korea = 한국 MB = MB -One moment please... = 잠시만 기다려 주세요... +One moment please... = 잠깐만 기다려 주세요... Play = 재생 -Remove From Recent = 최근 기록 제거 -SaveData = 저장 데이터 -Setting Background = 배경화면 설정 -Show In Folder = 폴더에 표시 -USA = 북미 -Use UI background = UI 배경화면 사용 - +Remove From Recent = "최근"에서 제거 +SaveData = 저장데이터 +Setting Background = 배경 설정 +Show In Folder = 폴더에 표기 +USA = 미국 +Use UI background = UI 배경 사용 [Graphics] % of the void = 무효 영역의 백분율 % of viewport = 뷰포트의 백분율 From c3241bc9112e47d7bdeeb2469bcf42851f644a1f Mon Sep 17 00:00:00 2001 From: DDinghoya Date: Fri, 19 Aug 2022 19:20:25 +0900 Subject: [PATCH 15/85] Update ko_KR.ini Minor update#4 --- assets/lang/ko_KR.ini | 327 ++++++++++++++++++++---------------------- 1 file changed, 152 insertions(+), 175 deletions(-) diff --git a/assets/lang/ko_KR.ini b/assets/lang/ko_KR.ini index 3d08de9745..152f8baa4b 100644 --- a/assets/lang/ko_KR.ini +++ b/assets/lang/ko_KR.ini @@ -275,6 +275,7 @@ Toggle Audio Debug = 오디오 디버그 토글 Toggle Freeze = 프리징 토글 Touchscreen Test = 터치화면 테스트 VFPU = VFPU + [Dialog] * PSP res = * PSP 리소스 Active = 활성화 @@ -405,6 +406,7 @@ Warning: Video memory FULL, reducing upscaling and switching to slow caching mod Warning: Video memory FULL, switching to slow caching mode = 비디오 메모리가 가득 찼서, 저속 캐싱 모드로 전환합니다. ZIP file detected (Require UnRAR) = 파일은 (ZIP으로) 압축되어 있습니다.\n먼저 압축을 해제하세요 (UnRAR 시도). ZIP file detected (Require WINRAR) = 파일은 (ZIP으로) 압축되어 있습니다.\n먼저 압축을 해제하세요 (WinRAR 시도). + [Game] Asia = 아시아 Calculate CRC = CRC 계산 @@ -431,11 +433,12 @@ Setting Background = 배경 설정 Show In Folder = 폴더에 표기 USA = 미국 Use UI background = UI 배경 사용 + [Graphics] -% of the void = 무효 영역의 백분율 -% of viewport = 뷰포트의 백분율 +% of the void = 공백의 % +% of viewport = 뷰포트의 % %, 0:unlimited = %, 0 = 무제한 -(supersampling) = (슈퍼 샘플링) +(supersampling) = (슈퍼샘플링) (upscaling) = (업스케일링) 1x PSP = PSP 1배 2x = 2배 @@ -453,172 +456,172 @@ Use UI background = UI 배경 사용 9x PSP = PSP 9배 10x PSP = PSP 10배 16x = 16배 -Aggressive = 급격한 -Alternative Speed = 대체 속도 -Alternative Speed 2 = 대체 속도 2 (단위 퍼센트, 0 = 무제한) +Aggressive = 과격 +Alternative Speed = 대체 속도 (%, 0 = 무제한) +Alternative Speed 2 = 대체 속도 2 (%, 0 = 무제한) Anisotropic Filtering = 비등방성 필터링 Auto = 자동 Auto (1:1) = 자동 (1:1) -Auto (same as Rendering) = 자동 (렌더링 해상도와 같음) -Auto FrameSkip = 자동 프레임 생략 -Auto Max Quality = Auto Max Quality +Auto (same as Rendering) = 자동 (렌더링 해상도와 동일) +Auto FrameSkip = 자동 프레임생략 +Auto Max Quality = 자동 최대 품질 Auto Scaling = 자동 스케일링 -Backend = 처리자 +Backend = 백엔드 Balanced = 평형 -Bicubic = 쌍입방 -BlockTransfer Tip = 몇몇 게임들의 그래픽 오류를 고치기 위해 이 설정이 필요합니다. -BlockTransferRequired = 주의 - 이 설정을 키기 위해 이 게임은 "블럭단위 전송 효과 시뮬레이트"를 사용해야 합니다. -Both = 모두 표시 -Buffer graphics commands (faster, input lag) = 버퍼 그래픽 커맨드 (빠름, 입력 렉 발생) +Bicubic = 고등차수보간 +BlockTransfer Tip = 일부 게임에서는 올바른 그래픽을 위해 이 기능을 켜야 합니다. +BlockTransferRequired = 경고: 이 게임은 "블록 전송 효과 시뮬레이션"을 켬으로 설정해야 합니다. +Both = 둘 다 +Buffer graphics commands (faster, input lag) = 버퍼 그래픽 명령 (빠름, 입력 지연) Buffered Rendering = 버퍼링된 렌더링 -BufferedRenderingRequired = 주의 - 이 게임은 "렌더링 모드"가 "버퍼됨" 이어야 합니다. +BufferedRenderingRequired = 경고: 이 게임은 "렌더링 모드"를 "버퍼링"으로 설정해야 합니다. Camera = 카메라 Camera Device = 카메라 장치 -Cardboard Screen Size = 화면 크기 (뷰포트의 백분율) -Cardboard Screen X Shift = X축 이동 (여백의 백분율) -Cardboard Screen Y Shift = Y축 이동 (여백의 백분율) -Cardboard VR Settings = 구글 카드보드 설정 +Cardboard Screen Size = 화면 크기(뷰포트의 %) +Cardboard Screen X Shift = X 축 이동 (공백의 %) +Cardboard Screen Y Shift = Y 축 이동 (공백의 %) +Cardboard VR Settings = 구글 카드보드 VR 설정 Cheats = 치트 CPU Core = CPU 코어 Debugging = 디버깅 -DefaultCPUClockRequired = 주의 - 이 게임은 CPU 클럭이 기본 설정이어야 합니다. +DefaultCPUClockRequired = 경고: 이 게임은 CPU 클럭을 기본값으로 설정해야 합니다. Deposterize = 색조 융합 -Deposterize Tip = 업스케일링된 텍스처의 왜곡 현상 고치기 +Deposterize Tip = 업스케일링된 텍스처의 시각적 밴딩 결함 수정 Device = 장치 Direct3D 9 = Direct3D 9 Direct3D 11 = Direct3D 11 -Disable slower effects (speedup) = 느림 효과를 비활성화 (속도 상승) +Disable slower effects (speedup) = 느린 효과 비활성화 (속도 향상) Disabled = 비활성화 Display layout editor = 화면 레이아웃 편집기 -Display Resolution (HW scaler) = 화면 해상도 (하드웨어 스케일러) -Dump next frame to log = 로그에 다음 프레임 덤프 -Enable Cardboard VR = 구글 카드보드 활성화 +Display Resolution (HW scaler) = 화면 해상도(HW 스케일러) +Dump next frame to log = 다음 프레임을 로그로 덤프 +Enable Cardboard VR = 카드보드 VR 활성화 FPS = FPS -Frame Rate Control = 프레임 비율 제어 +Frame Rate Control = 프레임속도 제어 Frame Skipping = 프레임 생략 Frame Skipping Type = 프레임 생략 유형 -FullScreen = 전체 화면 -GPU log profiler = GPU log profiler -Hack Settings = 핵 설정 (이것은 오류의 원인이 됩니다) -Hardware Tessellation = 하드웨어 테셀레이션 +FullScreen = 전체화면 +Hack Settings = 핵 설정 (결함을 일으킬 수 있음) +Hardware Tessellation = 하드웨어 조각화 Hardware Transform = 하드웨어 변환 -hardware transform error - falling back to software = 하드웨어 변환 오류 - 소프트웨어로 전환 -HardwareTessellation Tip = 하드웨어가 곡선을 그리게 하여 언제나 고정된 품질을 사용합니다. +hardware transform error - falling back to software = 하드웨어 변환 오류, 소프트웨어로 폴백 +HardwareTessellation Tip = 곡선을 만들기 위해 하드웨어 사용 High = 높음 Hybrid = 혼합 -Hybrid + Bicubic = 혼합 + 쌍입방 -Ignore camera notch when centering = Ignore camera notch when centering +Hybrid + Bicubic = 혼합 + 고등차수보간 +Ignore camera notch when centering = 센터링 시 카메라 노치 무시 Internal Resolution = 내부 해상도 -Lazy texture caching = 텍스처 캐싱을 줄임 (속도 상승) -Lazy texture caching Tip = Faster, but can cause text problems in a few games +Lazy texture caching = 레이지 텍스처 캐싱 (속도 상승) +Lazy texture caching Tip = 더 빠르지만 몇몇 게임에서 텍스트 문제를 일으킬 수 있음 Linear = 선형 필터링 Low = 낮음 -LowCurves = 낮은 품질의 스플라인 및 베지어 곡선 (속도 상승) -LowCurves Tip = 몇몇 게임에만 사용됩니다. 곡선의 부드러움의 정도를 조정합니다. -Lower resolution for effects (reduces artifacts) = 효과 해상도 저하 (질감 감소) +LowCurves = 스플라인/베지어 곡선 품질 +LowCurves Tip = 일부 게임에서만 사용되며 곡선의 부드러움을 제어합니다. +Lower resolution for effects (reduces artifacts) = 효과에 대한 낮은 해상도 (인공물 감소) Manual Scaling = 수동 스케일링 Medium = 중간 -Mode = 방식 -Must Restart = 이 설정을 적용하기 위해서는 PPSSPP를 재시작해 주십시오. +Mode = 모드 +Must Restart = 이 변경 사항을 적용하려면 PPSSPP를 다시 시작해야 합니다. Native device resolution = 기본 장치 해상도 Nearest = 근접 필터링 No buffer = 버퍼 없음 -Non-Buffered Rendering = 버퍼 없는 렌더링 (속도 상승) +Non-Buffered Rendering = 버퍼 효과 건너뛰기(버퍼되지 않음, 더 빠름) None = 없음 Number of Frames = 프레임 수 -Off = 끄기 +Off = 끔 OpenGL = OpenGL Overlay Information = 오버레이 정보 Partial Stretch = 부분 늘이기 Percent of FPS = FPS 비율 Performance = 성능 -Postprocessing effect = Postprocessing effects -Postprocessing Shader = 후처리 셰이더 -Recreate Activity = Recreate activity -Render duplicate frames to 60hz = 중복된 프레임을 60Hz로 렌더링 -RenderDuplicateFrames Tip = 낮은 프레임 레이트에서 동작하는 게임을 부드럽게 해 줍니다. -Rendering Mode = 렌더링 방식 +Postprocessing effect = 후처리 효과 +Postprocessing Shader = 후처리 쉐이더 +Recreate Activity = 활동 재생성 +Render duplicate frames to 60hz = 중복 프레임을 60Hz로 렌더링 +RenderDuplicateFrames Tip = 낮은 프레임 속도에서 실행되는 게임에서 프레임 속도를 더 부드럽게 만들 수 있습니다. +Rendering Mode = 렌더링 모드 Rendering Resolution = 렌더링 해상도 -RenderingMode NonBuffered Tip = 빠르지만 몇몇 게임에서는 작동하지 않을 수 있습니다. -Retain changed textures = 변경된 텍스처를 보유 (속도 감소) -RetainChangedTextures Tip = 많은 게임들이 이 설정을 적용하면 대부분 느려지지만 몇몇 게임은 더 빨라질 수 있습니다. +RenderingMode NonBuffered Tip = 더 빠르지만 일부 게임에서는 아무 것도 표현되지 않을 수 있습니다. +Retain changed textures = 변경된 텍스처 유지 (때로는 느림) +RetainChangedTextures Tip = 많은 게임을 느리게 하지만 일부 게임은 훨씬 빠르게 만듭니다. Rotation = 회전 Safe = 안전 -Screen layout = Screen layout -Screen Scaling Filter = 화면 크기 조절 필터 +Screen layout = 화면 레이아웃 +Screen Scaling Filter = 화면 크기 조정 필터 Show Debug Statistics = 디버그 통계 표시 Show FPS Counter = FPS 카운터 표시 -Simulate Block Transfer = 블록 전송 효과를 시뮬레이션 -Software Rendering = 소프트웨어 렌더링 (실험적) +Simulate Block Transfer = 블록 전송 효과 시뮬레이션 +Software Rendering = 소프트웨어 렌더링 (느림) Software Skinning = 소프트웨어 스키닝 -SoftwareSkinning Tip = 스키닝 된 모델을 합쳐 CPU에 그립니다. 대부분에 게임이 빨라집니다. +SoftwareSkinning Tip = 대부분의 게임에서 더 빠르게 CPU에서 스킨 모델 드로우를 결합합니다. Speed = 속도 Stretching = 늘이기 Texture Filter = 텍스처 필터링 Texture Filtering = 텍스처 필터링 -Texture Scaling = 텍스처 크기 조절 -Texture Shader = Texture shader -Turn off Hardware Tessellation - unsupported = "하드웨어 테셀레이션" 끄기: 지원하지 않음 +Texture Scaling = 텍스처 스케일링 +Texture Shader = 텍스처 쉐이더 +Turn off Hardware Tessellation - unsupported = "하드웨어 조각화" 끄기: 지원되지 않음 Unlimited = 무제한 Up to 1 = 최대 1까지 Up to 2 = 최대 2까지 -Upscale Level = 확대 수준 -Upscale Type = 확대 종류 -UpscaleLevel Tip = CPU가 할 일이 많아집니다 - 또한 끊김 현상을 줄이기 위해 스케일링이 늦어질 수 있습니다. -Use all displays = 모든 디스플레이 사용하기 -Vertex Cache = 버텍스 캐시 -VertexCache Tip = 빠르지만 잠시동안 화면이 깜빡거릴 수 있습니다. -VSync = 수직 동기 -Vulkan = 벌칸(Vulkan) +Upscale Level = 업스케일 레벨 +Upscale Type = 업스케일 유형 +UpscaleLevel Tip = CPU 사용률 높음 - 버벅거림을 방지하기 위해 일부 확장이 지연될 수 있음 +Use all displays = 모든 화면 사용 +Vertex Cache = 정점 캐시 +VertexCache Tip = 더 빠르지만 일시적인 깜박임이 발생할 수 있습니다. +VSync = 수직 동기화 +Vulkan = Vulkan Window Size = 창 크기 -xBRZ = xBRZ +xBRZ = xBRZ 필터 +GPU log profiler = GPU 로그 프로파일러 [InstallZip] Delete ZIP file = ZIP 파일 삭제 Install = 설치 -Install game from ZIP file? = ZIP 파일로부터 게임을 설치하시겠습니까? -Install textures from ZIP file? = ZIP 파일로부터 텍스처팩을 설치하시겠습니까? +Install game from ZIP file? = ZIP 파일에서 게임을 설치하겠습니까? +Install textures from ZIP file? = ZIP 파일에서 텍스처를 설치하겠습니까? Installed! = 설치되었습니다! -Texture pack doesn't support install = 이 텍스처팩의 설치는 지원하지 않습니다. -Zip archive corrupt = ZIP 파일이 손상되었습니다. -Zip file does not contain PSP software = ZIP 파일에 PSP 소프트웨어가 들어있지 않습니다. +Texture pack doesn't support install = 텍스처 팩은 설치를 지원하지 않습니다. +Zip archive corrupt = ZIP 아카이브가 손상되었습니다. +Zip file does not contain PSP software = ZIP 파일에 PSP 소프트웨어가 포함되어 있지 않음 [KeyMapping] -Autoconfigure = 자동 설정 -Autoconfigure for device = 디바이스에 맞게 자동 설정 -Bind All = Bind All -Clear All = 모두 지우기 +Autoconfigure = 자동 구성 +Autoconfigure for device = 장치 자동 구성 +Bind All = 모두 바인딩 +Clear All = 모두 지움 Default All = 기본값 복원 Map a new key for = 새로운 키 입력 Map Key = 키 매핑 Map Mouse = 마우스 매핑 -Replace = Replace -Show PSP = Show PSP -You can press ESC to cancel. = 취소하려면 ESC를 눌러주십시오. +Replace = 교체 +Show PSP = PSP 표시 +You can press ESC to cancel. = Esc를 눌러 취소할 수 있습니다. [MainMenu] Browse = 찾아보기... Buy PPSSPP Gold = PPSSPP Gold 구매 -Choose folder = 폴더 선택하기 -Credits = 만든이 -PPSSPP Homebrew Store = PPSSPP 홈브류 스토어. +Choose folder = 폴더 선택 +Credits = 크레딧 +PPSSPP Homebrew Store = PPSSPP 홈브류 스토어 Exit = 종료 -Game Settings = 게임 설정 +Game Settings = 설정 Games = 게임 -Give PPSSPP permission to access storage = 저장공간에 접근하기 위해 PPSSPP에 권한이 필요합니다. -Homebrew & Demos = 홈브류 및 데모 -How to get games = 어떻게 게임을 구할 수 있나요? -How to get homebrew & demos = 어떻게 홈브류 및 데모를 구할 수 있나요? +Give PPSSPP permission to access storage = PPSSPP에 저장공간 접속 권한 부여 +Homebrew & Demos = 홈브류 && 데모 +How to get games = 게임을 어떻게 구할 수 있나요? +How to get homebrew & demos = 홈브류 및 데모를 어떻게 구할 수 있나요? Load = 불러오기... Loading... = 불러오는 중... PinPath = 경로 고정 -PPSSPP can't load games or save right now = 현재 PPSSPP에서 게임을 불러오거나 저장할 수 없습니다 -Recent = 최근 게임 -SavesAreTemporary = 임시 저장장치에 저장하는 중 -SavesAreTemporaryGuidance = 영구적으로 사용하기 위해 PPSSPP를 기억장치에 복사해 주십시오. -SavesAreTemporaryIgnore = 무시하기 +PPSSPP can't load games or save right now = PPSSPP는 지금 게임을 로드하거나 저장할 수 없습니다. +Recent = 최근 +SavesAreTemporary = PPSSPP가 임시 저장공간에 저장 중입니다. +SavesAreTemporaryGuidance = 영구적으로 저장하기 위해 어딘가에 PPSSPP 추출 +SavesAreTemporaryIgnore = 경고 무시 UnpinPath = 고정 해제 -UseBrowseOrLoad = Use Browse to choose a folder, or Load to choose a file. +UseBrowseOrLoad = 찾아보기를 사용하여 폴더를 선택하거나 로드를 사용하여 파일을 선택합니다. www.ppsspp.org = www.ppsspp.org [MainSettings] @@ -626,121 +629,92 @@ Audio = 오디오 Controls = 조작 Graphics = 그래픽 Networking = 네트워킹 -Search = Search System = 시스템 Tools = 도구 +Search = 검색 [MappableControls] Alt speed 1 = 대체 속도 1 Alt speed 2 = 대체 속도 2 -An.Down = 아날로그.하 -An.Left = 아날로그.좌 -An.Right = 아날로그.우 -An.Up = 아날로그.상 -Analog limiter = 아날로그 제한자 +An.Down = 아날로그 아래쪽 +An.Left = 아날로그 왼쪽 +An.Right = 아날로그 오른쪽 +An.Up = 아날로그 위쪽 +Analog limiter = 아날로그 리미터 Analog Stick = 아날로그 스틱 -Audio/Video Recording = 소리/영상 녹화 +Audio/Video Recording = 오디오/비디오 녹화 AxisSwap = 축 스왑 Circle = 동그라미 Cross = 십자 -Custom 1 = Custom 1 -Custom 10 = Custom 10 -Custom 2 = Custom 2 -Custom 3 = Custom 3 -Custom 4 = Custom 4 -Custom 5 = Custom 5 -Custom 6 = Custom 6 -Custom 7 = Custom 7 -Custom 8 = Custom 8 -Custom 9 = Custom 9 -D-pad down = 방향 패드.하 -D-pad left = 방향 패드.좌 -D-pad right = 방향 패드.우 -D-pad up = 방향 패드.상 -DevMenu = 개발 메뉴 -Display Landscape = Display Landscape -Display Landscape Reversed = Display Landscape Reversed -Display Portrait = Display Portrait -Display Portrait Reversed = Display Portrait Reversed -Double tap button = Double tap button -Down = 방향 패드.하 -Dpad = 방향 패드 -Frame Advance = 프레임 건너뛰기 +Custom 1 = 커스텀 1 +Custom 2 = 커스텀 2 +Custom 3 = 커스텀 3 +Custom 4 = 커스텀 4 +Custom 5 = 커스텀 5 +Custom 6 = 커스텀 6 +Custom 7 = 커스텀 7 +Custom 8 = 커스텀 8 +Custom 9 = 커스텀 9 +Custom 10 = 커스텀 10 +D-pad down = D-패드 아래쪽 +D-pad left = D-패드 왼쪽 +D-pad right = D-패드 오른쪽 +D-pad up = D-패드 위쪽 +DevMenu = 개발메뉴 +Double tap button = 두 번 탭 버튼 +Down = D패드 아래쪽 +Dpad = D패드 +Frame Advance = 프레임 어드밴스 Hold = 잠금 Home = 홈 L = L -Left = 방향 패드.좌 +Left = D패드 왼쪽 Load State = 상태 불러오기 -Mute toggle = 음소거 전환 +Mute toggle = 무음 토글 Next Slot = 다음 슬롯 None = 없음 Note = 참고 -OpenChat = 대화 열기 +OpenChat = 채팅 열기 Pause = 일시 정지 R = R RapidFire = 연사 -Record = Record +Record = 녹화 Remote hold = 리모트 잠금 Rewind = 되감기 -Right = 방향 패드.우 -Right Analog Stick = Right Analog Stick -RightAn.Down = 우측An.하 -RightAn.Left = 우측An.좌 -RightAn.Right = 우측An.우 -RightAn.Up = 우측An.상 +Right = D패드 오른쪽 +Right Analog Stick = 오른쪽 아날로그 스틱 +RightAn.Down = 우측 아날로그 아래쪽 +RightAn.Left = 우측 아날로그 왼쪽 +RightAn.Right = 우측 아날로그 오른쪽 +RightAn.Up = 우측 아날로그 위쪽 Rotate Analog (CCW) = 아날로그 회전 (CCW) Rotate Analog (CW) = 아날로그 회전 (CW) Save State = 상태 저장하기 Screen = 화면 Screenshot = 스크린샷 Select = 선택 -SpeedToggle = 속도 전환 +SpeedToggle = 속도 토글 Square = 네모 Start = 시작 -Swipe Down = Swipe Down -Swipe Left = Swipe Left -Swipe Right = Swipe Right -Swipe Up = Swipe Up -tap to customize = tap to customize -Texture Dumping = 텍스처 덤프 +Swipe Down = 아래로 쓸어내림 +Swipe Left = 왼쪽으로 쓸어내림 +Swipe Right = 오른쪽으로 쓸어내림 +Swipe Up = 위로 쓸어내림 +tap to customize = 탭하여 맞춤 설정 +Texture Dumping = 텍스처 덤핑 Texture Replacement = 텍스처 교체 -Toggle Fullscreen = 전체화면 고정 +Toggle Fullscreen = 전체 화면 토글 Toggle mode = 토글 모드 Triangle = 세모 -Fast-forward = 터보 -Up = 방향 패드.상 +Fast-forward = 빨리 감기 +Up = Dpad Up Vol + = 볼륨 + Vol - = 볼륨 - Wlan = 무선랜 - -[MemStick] -Already contains PSP data = Already contains PSP data -Create or Choose a PSP folder = Create or Choose a PSP folder -Current = Current -DataCanBeShared = Data can be shared between PPSSPP regular/Gold -DataCannotBeShared = Data CANNOT be shared between PPSSPP regular/Gold! -DataWillBeLostOnUninstall = Warning! Data will be lost when you uninstall PPSSPP! -DataWillStay = Data will stay even if you uninstall PPSSPP. -Done! = Done! -EasyUSBAccess = Easy USB access -Failed to move some files! = Failed to move some files! -Failed to save config = Failed to save config -Free space = Free space -Manually specify PSP folder = Manually specify PSP folder -MemoryStickDescription = Choose where to keep PSP data (Memory Stick) -Move Data = Move Data -Selected PSP Data Folder = Selected PSP Data Folder -No data will be changed = No data will be changed -PPSSPP will restart after the change = PPSSPP will restart after the change -Skip for now = Skip for now -Starting move... = Starting move... -That folder doesn't work as a memstick folder. = That folder doesn't work as a memstick folder. -USBAccessThrough = USB access through Android/data/org.ppsspp.ppsspp/files -USBAccessThroughGold = USB access through Android/data/org.ppsspp.ppssppgold/files -Use App Private Data = Use App Private Data -Use PSP folder at root of storage = Use PSP folder at root of storage -Welcome to PPSSPP! = Welcome to PPSSPP! -WhatsThis = What's this? +Display Landscape = 가로방향 표시 +Display Landscape Reversed = 가로방향 반전 표시 +Display Portrait = 세로방향 표시 +Display Portrait Reversed = 세로방향 반전 표시 [Networking] AdHoc Server = Ad hoc server @@ -1006,6 +980,7 @@ SpeedCustom2 = Speed: 대체 2 standard = 속도: 표준 State load undone = 상태 로드 취소 Untitled PSP game = 제목 없는 PSP 게임 + [Store] Already Installed = 이미 설치됨 Connection Error = 연결 오류 @@ -1015,6 +990,7 @@ Loading... = 로딩 중... MB = MB Size = 크기 Uninstall = 제거 + [SysInfo] %d (%d per core, %d cores) = %d (코어 당 %d, 코어 %d 개) %d bytes = %d 바이트 @@ -1074,6 +1050,7 @@ Version Information = 버전 정보 Vulkan Extensions = Vulkan 확장 Vulkan Features = Vulkan 기능 Display Color Formats = 디스플레이 색상 형식 + [System] (broken) = (고장) 12HR = 12시간 From 824de45d52de1e76a1d4ff280292313a3df4be93 Mon Sep 17 00:00:00 2001 From: DDinghoya Date: Sat, 20 Aug 2022 13:05:30 +0900 Subject: [PATCH 16/85] Update ko_KR.ini Minor update of final --- assets/lang/ko_KR.ini | 375 ++++++++++++++++++++++++------------------ 1 file changed, 211 insertions(+), 164 deletions(-) diff --git a/assets/lang/ko_KR.ini b/assets/lang/ko_KR.ini index 152f8baa4b..b83bb8a381 100644 --- a/assets/lang/ko_KR.ini +++ b/assets/lang/ko_KR.ini @@ -128,7 +128,7 @@ Auto Max Quality = 자동 최대 품질(&Q) Backend = 렌더링 백엔드(&B) (PPSSPP 재시작) Bicubic = 고등차수보간(&B) Break = 증딘 -Break on Load = 로드 시 중단 +Break on Load = 불러오기 시 중단 Buffered Rendering = 버퍼링된 렌더링(&B) Buy Gold = 골드 버전 구매(&G) Control Mapping... = 제어 맵핑(&O)... @@ -246,7 +246,7 @@ GPU Log Profiler = GPU 로그 프로파일러 Jit Compare = JIT 비교 JIT debug tools = JIT 디버그 도구 Language = 언어 -Load language ini = 언어 ini 로드 +Load language ini = 언어 ini 불러오기 Log Dropped Frame Statistics = 삭제된 프레임 통계 기록 Log Level = 로그 레벨 Log View = 로그 보기 @@ -288,7 +288,7 @@ Channel: = 채널: Choose PPSSPP save folder = PPSSPP 저장 폴더 선택 Confirm Overwrite = 데이터를 덮어쓰겠습니까? Confirm Save = 이 데이터를 저장하겠습니까? -ConfirmLoad = 이 데이터를 로드하겠습니까? +ConfirmLoad = 이 데이터를 불러오겠습니까? ConnectingAP = 접속 포인트에 연결하는 중입니다.\n잠시만 기다려 주세요... ConnectingPleaseWait = 연결 중입니다.\n잠시만 기다려 주세요... ConnectionName = 결 이름 @@ -313,10 +313,10 @@ GE Frame Dumps = GE 프레임 덤프 Grid = 그리드 Inactive = 비활성 InternalError = 내부 오류가 발생했습니다. -Load = 로드 -Load completed = 로드가 완료되었습니다. +Load = 불러오기 +Load completed = 불러오기가 완료되었습니다. Loading = 로딩 중\n잠시만 기다려 주세요... -LoadingFailed = 데이터를 로드할 수 없습니다. +LoadingFailed = 데이터를 불러올 수 없습니다. Move = 이동 Network Connection = 네트워크 연결 NEW DATA = 새로운 데이터 @@ -345,7 +345,7 @@ There is no data = 데이터가 없습니다. Toggle All = 모두 토글 Toggle List = 토글 목록 Unsupported = 미지원 -When you save, it will load on a PSP, but not an older PPSSPP = 저장하면 PSP에 로드되지만 이전 PPSSPP에는 로드되지 않습니다. +When you save, it will load on a PSP, but not an older PPSSPP = 저장하면 PSP에 불러오지만 이전 PPSSPP에는 부러오지 않습니다. When you save, it will not work on outdated PSP Firmware anymore = 저장하면 오래된 PSP 펌웨어에서는 더 이상 작동하지 않습니다. Yes = 예 Zoom = 확대/축소 @@ -361,11 +361,11 @@ D3D11InitializationError = Direct3D 11 초기화 오류 D3D11Missing = 운영 체제 버전에 D3D11이 포함되어 있지 않습니다. 윈도우즈 업데이트를 실행하세요.\n\n대신 Direct3D 9를 사용하여 다시 시도하려면 예를 누르세요. D3D11NotSupported = GPU가 Direct3D 11을 지원하지 않는 것 같습니다.\n\n대신 Direct3D 9를 사용하여 다시 시도하겠습니까? Disk full while writing data = 데이터를 쓰는 동안 디스크가 가득 찼습니다. -ELF file truncated - can't load = ELF 파일이 불완전함 - 로드할 수 없음 -Error loading file = 게임을 로드할 수 없습니다. +ELF file truncated - can't load = ELF 파일이 불완전함 - 불러올 수 없음 +Error loading file = 게임을 불러올 수 없습니다. Error reading file = 파일 읽기 오류입니다. Failed initializing CPU/Memory = CPU 또는 메모리 초기화 실패 -Failed to load executable: = 실행 파일 로드 실패: +Failed to load executable: = 실행 파일 불러오기 실패: File corrupt = 파일 손상 Game disc read error - ISO corrupt = 게임 디스크 읽기 오류: ISO 손상되었습니다. GenericAllStartupError = PPSSPP가 그래픽 백엔드로 시작하지 못했습니다. 그래픽 및 기타 드라이버를 업그레이드해 보세요. @@ -615,13 +615,13 @@ How to get homebrew & demos = 홈브류 및 데모를 어떻게 구할 수 있 Load = 불러오기... Loading... = 불러오는 중... PinPath = 경로 고정 -PPSSPP can't load games or save right now = PPSSPP는 지금 게임을 로드하거나 저장할 수 없습니다. +PPSSPP can't load games or save right now = PPSSPP는 지금 게임을 불러오거나 저장할 수 없습니다. Recent = 최근 SavesAreTemporary = PPSSPP가 임시 저장공간에 저장 중입니다. SavesAreTemporaryGuidance = 영구적으로 저장하기 위해 어딘가에 PPSSPP 추출 SavesAreTemporaryIgnore = 경고 무시 UnpinPath = 고정 해제 -UseBrowseOrLoad = 찾아보기를 사용하여 폴더를 선택하거나 로드를 사용하여 파일을 선택합니다. +UseBrowseOrLoad = 찾아보기를 사용하여 폴더를 선택하거나 불러오기를 사용하여 파일을 선택합니다. www.ppsspp.org = www.ppsspp.org [MainSettings] @@ -717,165 +717,163 @@ Display Portrait = 세로방향 표시 Display Portrait Reversed = 세로방향 반전 표시 [Networking] -AdHoc Server = Ad hoc server -AdhocServer Failed to Bind Port = Ad hoc server failed to bind port -AM: Data from Unknown Port = AM: Data from Unknown Port -Auto = Auto -Bottom Center = Bottom center -Bottom Left = Bottom left -Bottom Right = Bottom right -Center Left = Center left -Center Right = Center right -Change Mac Address = Mac 주소 변경 -Change proAdhocServer Address = PRO 애드혹 서버 IP 주소 변경 (localhost = multiple instances) -ChangeMacSaveConfirm = Generate a new MAC address? -ChangeMacSaveWarning = Some games verify the MAC address when loading savedata, so this may break old saves. -Chat = 대화 -Chat Button Position = 대화 버튼 위치 -Chat Here = 여기에 입력 -Chat message = Chat message -Chat Screen Position = 대화 화면 위치 -Disconnected from AdhocServer = Disconnected from ad hoc server -DNS Error Resolving = DNS error resolving -Enable built-in PRO Adhoc Server = 내장된 PRO 애드혹 서버 활성화 -Enable network chat = 네트워크 대화 활성화 -Enable networking = 네트워킹/무선 랜 활성화 (베타, 게임 작동을 방해할 수 있음) -Enable UPnP = Enable UPnP (need a few seconds to detect) -EnableQuickChat = 빠른 대화 활성화 +AdHoc Server = Ad hoc 서버 +AdhocServer Failed to Bind Port = Ad Hoc 서버가 포트를 바인딩하지 못했습니다. +AM: Data from Unknown Port = AM: 알 수 없는 포트의 데이터 +Auto = 자동 +Bottom Center = 하단 중앙 +Bottom Left = 하단 왼쪽 +Bottom Right = 하단 오른쪽 +Center Left = 중앙 왼쪽 +Center Right = 중앙 오른쪽 +Change Mac Address = MAC 주소 변경 +ChangeMacSaveConfirm = 새로운 MAC 주소를 생성하시겠습니까? +ChangeMacSaveWarning = 일부 게임은 저장 데이터를 불러올 때 MAC 주소를 확인하므로 이전 저장이 손상될 수 있습니다. +Change proAdhocServer Address = PRO ad hoc 서버 IP 주소 변경 (로컬호스트 = 다중 인스턴스) +Chat = 채팅 +Chat Button Position = 채팅 버튼 위치 +Chat Here = 여기에서 채팅 +Chat message = 채팅 메세지 +Chat Screen Position = 채팅 화면 위치 +Disconnected from AdhocServer = Ad Hoc 서버에서 연결 해제됨 +DNS Error Resolving = DNS 오류 해결 +Enable built-in PRO Adhoc Server = 내장 PRO Ad Hoc 서버 활성화 +Enable network chat = 네트워크 채팅 활성화 +Enable networking = 네트워킹/무선랜 활성화 (베타, 게임이 중단될 수 있음) +Enable UPnP = UPnP 활성화 (감지하는 데 몇 초 필요) +EnableQuickChat = 빠른 채팅 활성화 Enter a new PSP nickname = 새로운 PSP 별명 입력 -Enter Quick Chat 1 = 빠른 대화 1 참가 -Enter Quick Chat 2 = 빠른 대화 2 참가 -Enter Quick Chat 3 = 빠른 대화 3 참가 -Enter Quick Chat 4 = 빠른 대화 4 참가 -Enter Quick Chat 5 = 빠른 대화 5 참가 -Error = Error -Failed to Bind Localhost IP = Failed to bind localhost IP -Failed to Bind Port = Failed to bind port -Failed to connect to Adhoc Server = Failed to connect to ad hoc server -Forced First Connect = Forced first connect (faster connect) -GM: Data from Unknown Port = GM: Data from Unknown Port -Hostname = Hostname -Invalid IP or hostname = 올바르지 않은 IP 또는 호스트 이름 -Minimum Timeout = Minimum timeout (override in ms, 0 = default) -Misc = Miscellaneous (default = PSP compatibility) -Network Initialized = 네트워크 초기화됨 -None = None -Please change your Port Offset = Please change your port offset -Port offset = 포트 오프셋(0 = PSP 호환) -Open PPSSPP Multiplayer Wiki Page = Open PPSSPP Multiplayer Wiki Page -proAdhocServer Address: = Ad hoc server address: -Quick Chat 1 = 빠른 대화 1 -Quick Chat 2 = 빠른 대화 2 -Quick Chat 3 = 빠른 대화 3 -Quick Chat 4 = 빠른 대화 4 -Quick Chat 5 = 빠른 대화 5 -QuickChat = 빠른 대화 +Enter Quick Chat 1 = 빠른 채팅 1 입력 +Enter Quick Chat 2 = 빠른 채팅 2 입력 +Enter Quick Chat 3 = 빠른 채팅 3 입력 +Enter Quick Chat 4 = 빠른 채팅 4 입력 +Enter Quick Chat 5 = 빠른 채팅 5 입력 +Error = 오류 +Failed to Bind Localhost IP = 로컬 호스트 IP를 바인딩하지 못했습니다. +Failed to Bind Port = 포트를 바인딩하지 못했습니다. +Failed to connect to Adhoc Server = Ad Hoc 서버에 연결하지 못했습니다. +Forced First Connect = 강제 첫 번째 연결 (빠른 연결) +GM: Data from Unknown Port = GM: 알 수 없는 포트의 데이터 +Hostname = 호스트 이름 +Invalid IP or hostname = 잘못된 IP 또는 호스트 이름 +Minimum Timeout = 최소 시간 초과 (ms 단위로 재정의, 0 = 기본값) +Misc = 기타 (기본값 = PSP 호환성) +Network Initialized = 네트워크 초기화 +None = 없음 +Please change your Port Offset = 포트 오프셋을 변경하세요. +Port offset = 포트 오프셋 (0 = PSP 호환성) +Open PPSSPP Multiplayer Wiki Page = PPSSPP 멀티플레이어 위키 페이지 열기 +proAdhocServer Address: = Ad hoc 서버 주소: +Quick Chat 1 = 빠른 채팅 1 +Quick Chat 2 = 빠른 채팅 2 +Quick Chat 3 = 빠른 채팅 3 +Quick Chat 4 = 빠른 채팅 4 +Quick Chat 5 = 빠른 채팅 5 +QuickChat = 빠른 채팅 Send = 보내기 -Send Discord Presence information = Discord 프로필에 PPSSPP 표시 -Top Center = Top center -Top Left = Top left -Top Right = Top right -Unable to find UPnP device = Unable to find UPnP device -UPnP (port-forwarding) = UPnP (port forwarding) -UPnP need to be reinitialized = UPnP need to be reinitialized -UPnP use original port = UPnP use original port (enabled = PSP compatibility) +Send Discord Presence information = 디스코드 "리치 프레즌스" 정보 보내기 +Top Center = 상단 중앙 +Top Left = 상단 왼쪽 +Top Right = 상단 오른쪽 +Unable to find UPnP device = UPnP 장치를 찾을 수 없습니다. +UPnP (port-forwarding) = UPnP (포트 포워딩) +UPnP need to be reinitialized = UPnP를 다시 초기화해야 합니다. +UPnP use original port = UPnP는 원래 포트를 사용합니다 (활성화됨 = PSP 호환성) Validating address... = 주소 검증하는 중... -WLAN Channel = WLAN channel -You're in Offline Mode, go to lobby or online hall = 현재 오프라인 모드입니다. 로비나 온라인 홀로 돌아갑니다. +WLAN Channel = 무선랜 채널 +You're in Offline Mode, go to lobby or online hall = 오프라인 모드입니다. 로비 또는 온라인 홀으로 이동합니다. [Pause] Cheats = 치트 Continue = 계속 -Create Game Config = 게임 설정파일 생성 -Delete Game Config = 게임 설정파일 제거 -Exit to menu = 종료 후 메뉴로 +Create Game Config = 게임 구성 생성 +Delete Game Config = 게임 구성 삭제 +Exit to menu = 메뉴로 나가기 Game Settings = 게임 설정 Load State = 상태 불러오기 Rewind = 되감기 Save State = 상태 저장하기 Settings = 설정 Switch UMD = UMD 교체 -Undo last load = Undo last load -Undo last save = Undo last save +Undo last load = 마지막 불러오기 실행 취소 +Undo last save = 마지막 저장 실행 취소 [PostShaders] -(duplicated setting, previous slider will be used) = (duplicated setting, previous slider will be used) -4xHqGLSL = 4배 HQ GLSL (OpenGL 셰이딩 언어) +(duplicated setting, previous slider will be used) = (설정이 중복되면 이전 슬라이더가 사용됩니다.) +4xHqGLSL = 4×HQ GLSL 5xBR = 5xBR 5xBR-lv2 = 5xBR-lv2 -AAColor = AA 색상 -Amount = Amount -Animation speed (0 -> disable) = Animation speed (0 -> disable) +AAColor = AA-색상 +Amount = 양 Black border = 검정 테두리 Bloom = 블룸 Brightness = 밝기 Cartoon = 카툰 -CatmullRom = Bicubic (Catmull-Rom) Upscaler ColorCorrection = 색상 교정 Contrast = 명암 CRT = CRT 스캔라인 -FXAA = FXAA (Fast Approximate Anti-Aliasing) +FXAA = FXAA 안티 에일리어싱 Gamma = 감마 Grayscale = 그레이스케일 Intensity = 강도 InverseColors = 색 반전 -MitchellNetravali = Bicubic (Mitchell-Netravali) Upscaler -Natural = 자연 색상 -NaturalA = 자연 색상 (블러 없음) -Off = 끄기 -Power = Power -PSPColor = PSP color +Natural = 자연스러운 색상 +NaturalA = 자연스러운 색상 (흐림 없음) +Off = 끔 +Power = 전원 +PSPColor = PSP 색상 Saturation = 채도 Scanlines = 스캔라인 (CRT) -Sharpen = 선명하게 -SSAA(Gauss) = 슈퍼샘플링 AA (가우스) +Sharpen = 선명함 +SSAA(Gauss) = 슈퍼샘플 AA (가우스) Tex4xBRZ = 4xBRZ TexMMPX = MMPX -UpscaleSpline36 = 스플라인36 확대 -VideoSmoothingAA = VideoSmoothingAA -Vignette = 비네트 +UpscaleSpline36 = 스플라인36 업스케일러 +VideoSmoothingAA = 비디오 스무딩 AA +Vignette = 비네트 효과 +Animation speed (0 -> disable) = 애니메이션 속도 (0 -> 비활성화) +CatmullRom = 고등차수보간 (카트물-롬) 업스케일러 +MitchellNetravali = 고등차수보간 (미첼-네트라발리) 업스케일러 [PSPCredits] all the forum mods = 모든 포럼 모드 build server = 빌드 서버 Buy Gold = 골드 버전 구매 -check = 최고의 Wii/GC 에뮬 Dolphin 또한 확인하십시오. -CheckOutPPSSPP = 멋진 PSP 에뮬레이터 PPSSPP를 확인해 보십시오: https://www.ppsspp.org/ +check = 또한 최고의 Wii/GC 에뮤인 돌핀도 확인하세요: +CheckOutPPSSPP = 멋진 PSP 에뮬레이터인 PPSSPP를 확인하세요: https://www.ppsspp.org/ contributors = 도움을 주신 분들: -created = 만든이: -Discord = Discord -info1 = PPSSPP는 교육적인 목적으로만 사용할 수 있습니다. -info2 = 설치한 게임의 소유 권리가 분명한지를 확인해 주십시오. -info3 = 해당 게임의 UMD를 소유하거나 디지털로 구매하여 플레이하십시오. -info4 = 해당 게임을 실제 PSP에 존재하는 PSN Store에서 구매해 주십시오. -info5 = PSP는 주식회사 소니의 등록 상표입니다. +created = 만든이 +Discord = 디스코드 +info1 = PPSSPP는 교육 목적으로만 사용됩니다. +info2 = 모든 게임에 대한 권리를 소유하고 있는지 확인하세요. +info3 = UMD를 소유하거나 디지털을 구매하여 플레이합니다. +info4 = 실제 PSP의 PSN 스토어에서 다운로드하십시오. +info5 = PSP는 Sony, Inc.의 상표입니다. iOS builds = iOS 빌드 -license = GPL 2.0+ 라이선스를 따르는 무료 소프트웨어 -list = 호환 목록, 포럼 및 개발 정보 +license = GPL 2.0+에 따른 무료 소프트웨어 +list = 호환성 목록, 포럼 및 개발 정보 PPSSPP Forums = PPSSPP 포럼 Privacy Policy = 개인 정보 정책 Share PPSSPP = PPSSPP 공유 -specialthanks = 특별히 감사드립니다: -specialthanksKeithGalocy = - NVIDIA 로부터 (하드웨어, 지도) -specialthanksMaxim = - 놀라운 Atrac3+ 디코더 지원 +specialthanks = 특별히 감사한 분: +specialthanksKeithGalocy = NVIDIA (하드웨어, 조언) +specialthanksMaxim = 놀라운 Atrac3+ 디코더 작업 testing = 테스트 -this translation by = 번역: -title = 빠르고 휴대성이 높은 PSP 에뮬레이터 -tools = 사용된 무료 도구들: +this translation by = 번역자: +title = 빠르고 휴대 가능한 PSP 에뮬레이터 +tools = 사용된 무료 도구: # Add translators or contributors who translated PPSSPP into your language here. # Add translators1-6 for up to 6 lines of translator credits. # Leave extra lines blank. 4 contributors per line seems to look best. -# It is character-set for keyboard(atlas) -# ㄱㄲㄳㄴㄵㄶㄷㄸㄹㄺㄻㄼㄽㄾㄿㅀㅁㅂㅃㅄㅅㅆㅇㅈㅉㅊㅋㅌㅍㅎㅏㅐㅑㅒㅓㅔㅕㅖㅗㅛㅜㅠㅡㅣ translators1 = mgaver Hisman_Yosika 오원식 MrGiKILL translators2 = DDinghoya translators3 = translators4 = translators5 = translators6 = -Twitter @PPSSPP_emu = Twitter @PPSSPP_emu -website = 웹 사이트에서 확인하세요: -written = 속도와 이식성을 보장하기 위해 C++로 작성되었습니다. +Twitter @PPSSPP_emu = 트위터 @PPSSPP_emu +website = 웹사이트를 확인하세요: +written = 속도와 이식성을 위해 C++로 작성되었습니다. [RemoteISO] Browse Games = 게임 찾아보기 @@ -897,47 +895,96 @@ Share on PPSSPP startup = PPSSPP 시작시 자동으로 공유하기 Stop Sharing = 공유 끝내기 Stopping.. = 중지하는 중... +[MemStick] +Already contains PSP data = 이미 PSP 데이터가 포함되어 있습니다. +Create or Choose a PSP folder = PSP 폴더 생성 또는 선택 +Current = 현재 +DataCanBeShared = PPSSPP 레귤러/골드 간에 데이터 공유 가능 +DataCannotBeShared = PPSSPP 레귤러/골드 간에 데이터를 공유할 수 없습니다! +DataWillBeLostOnUninstall = 경고! PPSSPP를 제거하면 데이터가 손실됩니다! +DataWillStay = PPSSPP를 제거해도 데이터는 유지됩니다. +Done! = 완료! +EasyUSBAccess = 쉬운 USB 접속 +Failed to move some files! = 일부 파일을 이동하지 못했습니다! +Failed to save config = 구성을 저장하지 못했습니다. +Free space = 여유 공간 +Manually specify PSP folder = 수동으로 PSP 폴더 지정 +MemoryStickDescription = PSP 데이터를 보관할 위치 선택 (메모리 스틱) +Move Data = 데이터 이동 +Selected PSP Data Folder = 선택한 PSP 데이터 폴더 +Skip for now = 일단은 건너뜀 +No data will be changed = 데이터가 변경되지 않습니다. +PPSSPP will restart after the change = 변경 후 PPSSPP가 다시 시작됩니다. +Starting move... = 이동 시작 중... +That folder doesn't work as a memstick folder. = 해당 폴더는 메모리스틱 폴더로 작동하지 않습니다. +USBAccessThrough = Android/data/org.ppsspp.ppsspp/files를 통한 USB 접속 +USBAccessThroughGold = Android/data/org.ppsspp.ppssppgold/files를 통한 USB 접속 +Use App Private Data = 앱 개인 데이터 사용 +Use PSP folder at root of storage = 저장공간 루트에서 PSP 폴더 사용 +Welcome to PPSSPP! = PPSSPP에 오신 것을 환영합니다! +WhatsThis = 이것은 무엇입니까? + +[RemoteISO] +Browse Games = 게임 찾아보기 +Local Server Port = 로컬 서버 포트 +Manual Mode Client = 수동으로 클라이언트 구성 +Remote disc streaming = 원격 디스크 스트리밍 +Remote Port = 원격 포트 +Remote Server = 원격 서버 +Remote Subdirectory = 원격 하위 디렉토리 +RemoteISODesc = "최근" 목록에 있는 게임이 공유됩니다. +RemoteISOLoading = 연결됨, 게임 목록 불러오기 중... +RemoteISOScanning = 검색 중... 서버 장치에서 "게임 공유"를 클릭하세요. +RemoteISOScanningTimeout = 검색 중... 바탕 화면의 방화벽 설정을 확인하세요. +RemoteISOWifi = 참고: 두 장치를 동일한 와이파이 네트워크에 연결하세요. +RemoteISOWinFirewall = 경고: 윈도우즈 방화벽이 공유를 차단하고 있습니다. +Settings = 설정 +Share Games (Server) = 게임 공유하기 (서버) +Share on PPSSPP startup = PPSSPP 시작시 자동으로 공유하기 +Stop Sharing = 공유 끝내기 +Stopping.. = 중지하는 중... + [Reporting] Bad = 나쁨 -FeedbackCRCCalculating = Disc CRC: Calculating... -FeedbackCRCValue = Disc CRC: %1 -FeedbackDelayInfo = 피드백 데이터를 전송 중입니다. -FeedbackDesc = 게임이 어땠나요? 저희에게 알려주십시오! -FeedbackDisabled = 서버에 호환성 문제 보고를 체크해 주십시오. -FeedbackIncludeCRC = 참고: 디스크 CRC를 위해 배터리가 사용될 수 있습니다. -FeedbackIncludeScreen = 스크린샷 포함하기 -FeedbackSubmitDone = 피드백 데이터가 전송되었습니다. -FeedbackSubmitFail = 서버에 피드백을 전송할 수 없었습니다. PPSSPP를 업데이트해 보십시오. -FeedbackThanks = 피드백 고맙습니다! -Gameplay = 게임 플레이 +FeedbackCRCCalculating = 디스크 CRC: 계산 중... +FeedbackCRCValue = 디스크 CRC: %1 +FeedbackDelayInfo = 데이터가 백그라운드에서 제출되고 있습니다. +FeedbackDesc = 에뮬레이션은 어떻습니까? 우리와 커뮤니티에 알려주세요! +FeedbackDisabled = 호환성 서버 보고서를 활성화해야 합니다. +FeedbackIncludeCRC = 참고: 배터리는 디스크 CRC를 보내는 데 사용됩니다. +FeedbackIncludeScreen = 스크린샷 포함 +FeedbackSubmitDone = 데이터가 제출되었습니다. +FeedbackSubmitFail = 서버에 데이터를 제출할 수 없습니다. PPSSPP 업데이트를 시도하세요. +FeedbackThanks = 피드백 주셔서 감사합니다! +Gameplay = 게임플레이 Graphics = 그래픽 Great = 좋음 In-game = 게임 내 -In-game Description = 게임이 실행되었지만 제대로 작동하지 않았습니다 +In-game Description = 게임이 실행되었지만 제대로 작동하지 않았습니다. Menu/Intro = 메뉴/인트로 -Menu/Intro Description = 게임 내에 진입할 수 없었습니다 -Nothing = 전부 -Nothing Description = 전혀 동작하지 않았습니다 -OK = 괜찮음 -Open Browser = 브라우저 열기 -Overall = 평가 -Perfect = 완벽함 -Perfect Description = 게임 전체가 흠 없이 매끄럽게 작동했습니다 - 대박! -Plays = 플레이 중 -Plays Description = 게임을 즐길 수는 있지만 문제가 있을 수 있습니다 -ReportButton = 피드백 남기기 -Show disc CRC = Show disc CRC +Menu/Intro Description = 게임 자체에 참여할 수 없음 +Nothing = 아무것도 없음 +Nothing Description = 완전히 파손됨 +OK = 확인 +Open Browser = 보고 웹사이트 열기 +Overall = 전체 +Perfect = 완벽 +Perfect Description = 전체 게임을 위한 완벽한 에뮬레이션 - 훌륭함! +Plays = 게임 중 +Plays Description = 완전히 재생할 수 있지만 결함이 있을 수 있음 +ReportButton = 피드백 보고 +Show disc CRC = 디스크 CRC 표시 Speed = 속도 Submit Feedback = 피드백 전송 -SuggestionConfig = 적합한 설정을 위해 웹사이트에 올라온 보고서들을 확인해 보십시오. -SuggestionCPUSpeed0 = 잠긴 CPU 설정을 비활성화해 주십시오. -SuggestionDowngrade = 구 버전의 PPSSPP로 내려보십시오. (그리고 이 버그를 신고해 주십시오). -SuggestionsFound = 다른 유저들이 더 나은 결과를 보고했습니다. 피드백 보기를 눌러 확인해 주십시오. -SuggestionsNone = 다른 유저들도 이 게임이 제대로 작동하지 않았습니다. -SuggestionsWaiting = 전송 및 다른 유저의 보고서 확인 중... -SuggestionUpgrade = 새로운 PPSSPP 버전으로 업데이트 하십시오. -SuggestionVerifyDisc = ISO 파일이 제대로 디스크로부터 복사되었는지 확인해 보십시오. -Unselected Overall Description = 이 게임이 얼마만큼 잘 작동했나요? +SuggestionConfig = 좋은 설정은 웹사이트의 보고서를 참조하세요. +SuggestionCPUSpeed0 = 잠긴 CPU 속도 설정을 비활성화합니다. +SuggestionDowngrade = 이전 PPSSPP 버전으로 다운그레이드합니다 (이 버그를 보고하세요). +SuggestionsFound = 다른 사용자가 더 나은 결과를 보고했습니다. 자세한 내용은 "피드백 보기"를 탭하세요. +SuggestionsNone = 이 게임은 다른 사용자에게도 작동하지 않습니다. +SuggestionsWaiting = 다른 사용자 의견 제출 및 확인 중... +SuggestionUpgrade = 최신 PPSSPP 빌드로 업그레이드하세요. +SuggestionVerifyDisc = ISO가 제대로 디스크로부터 복사되었는지 확인하세요. +Unselected Overall Description = 이 게임은 얼마나 잘 에뮬레이트하나요? View Feedback = 모든 피드백 보기 [Savedata] @@ -955,18 +1002,18 @@ Size = 크기 [Screen] Cardboard VR OFF = 카드보드 VR off Chainfire3DWarning = 경고: Chainfire3D가 감지되어 문제를 일으킬 수 있습니다. -Failed to load state = 상태를 로드하지 못함 +Failed to load state = 상태를 불러오지 못함 Failed to save state = 상태를 저장하지 못함 fixed = 속도: 대체 GLToolsWarning = 경고: GLTools가 감지되어 문제를 일으킬 수 있습니다. In menu = 메뉴 -Load savestate failed = 저장 상태 로드 실패 -Loaded State = 로드된 상태 -Loaded. Save in game, restart, and load for less bugs. = 로드되었습니다. 버그를 줄이기 위해 게임을 저장하고 다시 시작하고 로드하세요. -Loaded. Game may refuse to save over different savedata. = 로드되었습니다. 게임이 다른 저장 데이터에 대한 저장을 거부할 수 있습니다. -Loaded. Game may refuse to save over newer savedata. = 로드되었습니다. 게임이 최신 저장 데이터에 대한 저장을 거부할 수 있습니다. -LoadStateDoesntExist = 상태 로드 실패: 저장상태가 존재하지 않습니다! -LoadStateWrongVersion = 상태 로드 실패: 저장상태는 이전 버전의 PPSSPP용입니다! +Load savestate failed = 저장 상태 불러오기 실패 +Loaded State = 불러온 상태 +Loaded. Save in game, restart, and load for less bugs. = 불러왔습니다. 버그를 줄이기 위해 게임을 저장하고 다시 시작하고 불러오세요. +Loaded. Game may refuse to save over different savedata. = 불러왔습니다. 게임이 다른 저장 데이터에 대한 저장을 거부할 수 있습니다. +Loaded. Game may refuse to save over newer savedata. = 불러왔습니다. 게임이 최신 저장 데이터에 대한 저장을 거부할 수 있습니다. +LoadStateDoesntExist = 상태 불러오기 실패: 저장상태가 존재하지 않습니다! +LoadStateWrongVersion = 상태 불러오기 실패: 저장상태는 이전 버전의 PPSSPP용입니다! norewind = 되감기 저장 상태를 사용할 수 없습니다. Playing = 게임 중 PressESC = 일시 중지 메뉴를 열려면 ESC를 누르세요. @@ -978,7 +1025,7 @@ saveNewTextures_false = 텍스처 저장이 비활성화되었습니다. saveNewTextures_true = 이제 텍스처가 저장 공간에 저장됩니다. SpeedCustom2 = Speed: 대체 2 standard = 속도: 표준 -State load undone = 상태 로드 취소 +State load undone = 상태 불러오기 취소 Untitled PSP game = 제목 없는 PSP 게임 [Store] @@ -1084,10 +1131,10 @@ Dynarec (JIT) = 동적 재컴파일 (JIT) Emulation = 에뮬레이션 Enable Cheats = 치트 활성화 Enable Compatibility Server Reports = 호환성 서버 보고서 활성화 -Error: load undo state is from a different game = 오류: 로드 취소 상태는 다른 게임에서 가져옴 -Failed to load state. Error in the file system. = 상태를 로드하지 못했습니다. 파일 시스템에 오류가 있습니다. +Error: load undo state is from a different game = 오류: 불러오기 취소 상태는 다른 게임에서 가져옴 +Failed to load state. Error in the file system. = 상태를 불러오지 못했습니다. 파일 시스템에 오류가 있습니다. Failed to save state. Error in the file system. = 상태를 저장하지 못했습니다. 파일 시스템에 오류가 있습니다. -Failed to load state for load undo. Error in the file system. = 로드 실행 취소 상태를 로드하지 못했습니다. 파일 시스템에 오류가 있습니다. +Failed to load state for load undo. Error in the file system. = 불러오기 실행 취소 상태를 불러오지 못했습니다. 파일 시스템에 오류가 있습니다. Fast (lag on slow storage) = 빠름 (저속 저장 시 지연) Fast Memory = 빠른 메모리 (불안정) Floating symbols = 부동 기호 From bd3d97b17b641bcb174d188049fc0ce581a0ff16 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Sat, 20 Aug 2022 07:59:11 +0200 Subject: [PATCH 17/85] Fix bug in framebuffer matching where the wrong format was checked for depth matching. Fixes #15867 --- GPU/Common/TextureCacheCommon.cpp | 25 +++++++++++++------------ GPU/GeConstants.cpp | 1 + 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index 00f3822fbc..774aa8116d 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -868,6 +868,7 @@ bool TextureCacheCommon::MatchFramebuffer( uint32_t fb_address = channel == RASTER_DEPTH ? framebuffer->z_address : framebuffer->fb_address; uint32_t fb_stride = channel == RASTER_DEPTH ? framebuffer->z_stride : framebuffer->fb_stride; + GEBufferFormat fb_format = channel == RASTER_DEPTH ? GE_FORMAT_DEPTH16 : framebuffer->format; if (channel == RASTER_DEPTH && framebuffer->z_address == framebuffer->fb_address) { // Try to avoid silly matches to somewhat malformed buffers. @@ -913,14 +914,14 @@ bool TextureCacheCommon::MatchFramebuffer( } // 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, framebuffer->format) || (framebuffer->usageFlags & FB_USAGE_BLUE_TO_ALPHA)) { + if (TextureFormatMatchesBufferFormat(entry.format, fb_format) || (framebuffer->usageFlags & FB_USAGE_BLUE_TO_ALPHA)) { return true; - } else if (IsTextureFormat16Bit(entry.format) && IsBufferFormat16Bit(framebuffer->format)) { - WARN_LOG_ONCE(diffFormat1, G3D, "Texturing from framebuffer with reinterpretable format: %s != %s", GeTextureFormatToString(entry.format), GeBufferFormatToString(framebuffer->format)); + } else if (IsTextureFormat16Bit(entry.format) && IsBufferFormat16Bit(fb_format) && channel == RASTER_COLOR) { + WARN_LOG_ONCE(diffFormat1, G3D, "Texturing from framebuffer with reinterpretable format: %s != %s", GeTextureFormatToString(entry.format), GeBufferFormatToString(fb_format)); *matchInfo = FramebufferMatchInfo{ 0, 0, true, TextureFormatToBufferFormat(entry.format) }; return true; } else { - WARN_LOG_ONCE(diffFormat2, G3D, "Texturing from framebuffer with incompatible formats %s != %s", GeTextureFormatToString(entry.format), GeBufferFormatToString(framebuffer->format)); + WARN_LOG_ONCE(diffFormat2, G3D, "Not texturing from framebuffer with incompatible formats %s != %s", GeTextureFormatToString(entry.format), GeBufferFormatToString(fb_format)); return false; } } else { @@ -935,9 +936,9 @@ bool TextureCacheCommon::MatchFramebuffer( // Check works for D16 too (???) const bool matchingClutFormat = - (channel != RASTER_COLOR && entry.format == GE_TFMT_CLUT16) || - (channel == RASTER_COLOR && framebuffer->format == GE_FORMAT_8888 && entry.format == GE_TFMT_CLUT32) || - (channel == RASTER_COLOR && framebuffer->format != GE_FORMAT_8888 && entry.format == GE_TFMT_CLUT16); + (fb_format == GE_FORMAT_DEPTH16 && entry.format == GE_TFMT_CLUT16) || + (fb_format == GE_FORMAT_8888 && entry.format == GE_TFMT_CLUT32) || + (fb_format != GE_FORMAT_8888 && entry.format == GE_TFMT_CLUT16); const u32 bitOffset = (texaddr - addr) * 8; if (bitOffset != 0) { @@ -984,15 +985,15 @@ bool TextureCacheCommon::MatchFramebuffer( } return true; } else if (IsClutFormat((GETextureFormat)(entry.format)) || IsDXTFormat((GETextureFormat)(entry.format))) { - WARN_LOG_ONCE(fourEightBit, G3D, "%s format not supported when texturing from framebuffer of format %s", GeTextureFormatToString(entry.format), GeBufferFormatToString(framebuffer->format)); + WARN_LOG_ONCE(fourEightBit, G3D, "%s format not supported when texturing from framebuffer of format %s", GeTextureFormatToString(entry.format), GeBufferFormatToString(fb_format)); return false; } // This is either normal or we failed to generate a shader to depalettize - if ((int)framebuffer->format == (int)entry.format || matchingClutFormat) { - if ((int)framebuffer->format != (int)entry.format) { + if ((int)fb_format == (int)entry.format || matchingClutFormat) { + if ((int)fb_format != (int)entry.format) { WARN_LOG_ONCE(diffFormat2, G3D, "Texturing from framebuffer with different formats %s != %s at %08x", - GeTextureFormatToString(entry.format), GeBufferFormatToString(framebuffer->format), fb_address); + GeTextureFormatToString(entry.format), GeBufferFormatToString(fb_format), fb_address); return true; } else { WARN_LOG_ONCE(subarea, G3D, "Texturing from framebuffer at %08x +%dx%d", fb_address, matchInfo->xOffset, matchInfo->yOffset); @@ -1000,7 +1001,7 @@ bool TextureCacheCommon::MatchFramebuffer( } } else { WARN_LOG_ONCE(diffFormat2, G3D, "Texturing from framebuffer with incompatible format %s != %s at %08x", - GeTextureFormatToString(entry.format), GeBufferFormatToString(framebuffer->format), fb_address); + GeTextureFormatToString(entry.format), GeBufferFormatToString(fb_format), fb_address); return false; } } diff --git a/GPU/GeConstants.cpp b/GPU/GeConstants.cpp index ab627ee473..b093d96d56 100644 --- a/GPU/GeConstants.cpp +++ b/GPU/GeConstants.cpp @@ -6,6 +6,7 @@ const char *GeBufferFormatToString(GEBufferFormat fmt) { case GE_FORMAT_5551: return "5551"; case GE_FORMAT_565: return "565"; case GE_FORMAT_8888: return "8888"; + case GE_FORMAT_DEPTH16: return "DEPTH16"; default: return "N/A"; } } From 295f5f391e10a30b5884c563de6c36cf221ba94f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Thu, 18 Aug 2022 09:17:36 +0200 Subject: [PATCH 18/85] More consistent handling of lack of depth texture support. Small log improvement. --- GPU/Common/DepalettizeShaderCommon.cpp | 6 +++--- GPU/Common/TextureCacheCommon.cpp | 28 +++++++++++++++++--------- GPU/Common/TextureCacheCommon.h | 1 + GPU/D3D11/TextureCacheD3D11.cpp | 5 +++++ GPU/Directx9/TextureCacheDX9.cpp | 6 +++++- GPU/Vulkan/TextureCacheVulkan.cpp | 11 +++++++--- 6 files changed, 41 insertions(+), 16 deletions(-) diff --git a/GPU/Common/DepalettizeShaderCommon.cpp b/GPU/Common/DepalettizeShaderCommon.cpp index 0ec0b6c66c..9874e91d6e 100644 --- a/GPU/Common/DepalettizeShaderCommon.cpp +++ b/GPU/Common/DepalettizeShaderCommon.cpp @@ -44,7 +44,7 @@ static const VaryingDef varyings[1] = { { "vec2", "v_texcoord", Draw::SEM_TEXCOORD0, 0, "highp" }, }; -// Uses integer instructions available since OpenGL 3.0. Suitable for ES 3.0 as well. +// Uses integer instructions available since OpenGL 3.0, ES 3.0 (and 2.0 with extensions), and of course Vulkan and D3D11. void GenerateDepalShader300(ShaderWriter &writer, const DepalConfig &config, const ShaderLanguageDesc &lang) { const int shift = config.shift; const int mask = config.mask; @@ -128,7 +128,7 @@ void GenerateDepalShader300(ShaderWriter &writer, const DepalConfig &config, con writer.C(" vec4 outColor = ").SampleTexture2D("pal", "uv").C(";\n"); } -// FP only, to suit GL(ES) 2.0 +// FP only, to suit GL(ES) 2.0 and DX9 void GenerateDepalShaderFloat(ShaderWriter &writer, const DepalConfig &config, const ShaderLanguageDesc &lang) { char lookupMethod[128] = "index.r"; @@ -249,7 +249,7 @@ void GenerateDepalShaderFloat(ShaderWriter &writer, const DepalConfig &config, c // index_multiplier -= 0.01f / texturePixels; if (!formatOK) { - ERROR_LOG_REPORT_ONCE(depal, G3D, "%i depal unsupported: shift=%i mask=%02x offset=%d", config.pixelFormat, shift, mask, config.startPos); + ERROR_LOG_REPORT_ONCE(depal, G3D, "%s depal unsupported: shift=%d mask=%02x offset=%d", GeBufferFormatToString(config.pixelFormat), shift, mask, config.startPos); } // Offset by half a texel (plus clutBase) to turn NEAREST filtering into FLOOR. diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index 774aa8116d..d5de94ea28 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -515,6 +515,7 @@ TexCacheEntry *TextureCacheCommon::SetTexture() { nextNeedsChange_ = false; // Might need a rebuild if the hash fails, but that will be set later. nextNeedsRebuild_ = false; + failedTexture_ = false; VERBOSE_LOG(G3D, "Texture at %08x found in cache, applying", texaddr); return entry; //Done! } else { @@ -610,10 +611,9 @@ TexCacheEntry *TextureCacheCommon::SetTexture() { gstate_c.curTextureHeight = h; gstate_c.SetTextureIs3D((entry->status & TexCacheEntry::STATUS_3D) != 0); + failedTexture_ = false; nextTexture_ = entry; - if (nextFramebufferTexture_) { - nextFramebufferTexture_ = nullptr; // in case it was accidentally set somehow? - } + nextFramebufferTexture_ = nullptr; nextNeedsRehash_ = true; // We still need to rebuild, to allocate a texture. But we'll bail early. nextNeedsRebuild_ = true; @@ -633,7 +633,7 @@ std::vector TextureCacheCommon::GetFramebufferCandidates(const candidates.push_back(AttachCandidate{ match, entry, framebuffer, RASTER_COLOR, framebuffer->colorBindSeq }); } match = {}; - if (gstate_c.Supports(GPU_SUPPORTS_DEPTH_TEXTURE) && MatchFramebuffer(entry, framebuffer, texAddrOffset, RASTER_DEPTH, &match)) { + if (MatchFramebuffer(entry, framebuffer, texAddrOffset, RASTER_DEPTH, &match)) { candidates.push_back(AttachCandidate{ match, entry, framebuffer, RASTER_DEPTH, framebuffer->depthBindSeq }); } } @@ -1020,10 +1020,10 @@ void TextureCacheCommon::SetTextureFramebuffer(const AttachCandidate &candidate) _dbg_assert_msg_(framebuffer != nullptr, "Framebuffer must not be null."); framebuffer->usageFlags |= FB_USAGE_TEXTURE; - if (framebufferManager_->UseBufferedRendering()) { - // Keep the framebuffer alive. - framebuffer->last_frame_used = gpuStats.numFlips; + // Keep the framebuffer alive. + framebuffer->last_frame_used = gpuStats.numFlips; + if (framebufferManager_->UseBufferedRendering()) { // We need to force it, since we may have set it on a texture before attaching. gstate_c.curTextureWidth = framebuffer->bufferWidth; gstate_c.curTextureHeight = framebuffer->bufferHeight; @@ -1042,7 +1042,14 @@ void TextureCacheCommon::SetTextureFramebuffer(const AttachCandidate &candidate) gstate_c.SetNeedShaderTexclamp(true); } - nextFramebufferTexture_ = framebuffer; + if (candidate.channel == RASTER_DEPTH && !gstate_c.Supports(GPU_SUPPORTS_DEPTH_TEXTURE)) { + // Flag to bind a null texture if we can't support depth textures. + // Should only happen on old OpenGL. + nextFramebufferTexture_ = nullptr; + failedTexture_ = true; + } else { + nextFramebufferTexture_ = framebuffer; + } nextTexture_ = nullptr; } else { if (framebuffer->fbo) { @@ -1753,7 +1760,10 @@ void TextureCacheCommon::ApplyTexture() { if (!entry) { // Maybe we bound a framebuffer? InvalidateLastTexture(); - if (nextFramebufferTexture_) { + if (failedTexture_) { + // Backends should handle this by binding a black texture with 0 alpha. + BindTexture(nullptr); + } else if (nextFramebufferTexture_) { bool depth = Memory::IsDepthTexVRAMAddress(gstate.getTextureAddress(0)); // ApplyTextureFrameBuffer is responsible for setting SetTextureFullAlpha. ApplyTextureFramebuffer(nextFramebufferTexture_, gstate.getTextureFormat(), depth ? RASTER_DEPTH : RASTER_COLOR); diff --git a/GPU/Common/TextureCacheCommon.h b/GPU/Common/TextureCacheCommon.h index 5c95eb3b87..dbfbb316e4 100644 --- a/GPU/Common/TextureCacheCommon.h +++ b/GPU/Common/TextureCacheCommon.h @@ -433,6 +433,7 @@ protected: SimpleBuf tmpTexBufRearrange_; TexCacheEntry *nextTexture_ = nullptr; + bool failedTexture_ = false; VirtualFramebuffer *nextFramebufferTexture_ = nullptr; u32 clutHash_ = 0; diff --git a/GPU/D3D11/TextureCacheD3D11.cpp b/GPU/D3D11/TextureCacheD3D11.cpp index 8479a3dcb1..55917a7c24 100644 --- a/GPU/D3D11/TextureCacheD3D11.cpp +++ b/GPU/D3D11/TextureCacheD3D11.cpp @@ -236,6 +236,11 @@ void TextureCacheD3D11::UpdateCurrentClut(GEPaletteFormat clutFormat, u32 clutBa } void TextureCacheD3D11::BindTexture(TexCacheEntry *entry) { + if (!entry) { + ID3D11ShaderResourceView *textureView = nullptr; + context_->PSSetShaderResources(0, 1, &textureView); + return; + } ID3D11ShaderResourceView *textureView = DxView(entry); if (textureView != lastBoundTexture) { context_->PSSetShaderResources(0, 1, &textureView); diff --git a/GPU/Directx9/TextureCacheDX9.cpp b/GPU/Directx9/TextureCacheDX9.cpp index 1394183f1b..ea6b47e2e9 100644 --- a/GPU/Directx9/TextureCacheDX9.cpp +++ b/GPU/Directx9/TextureCacheDX9.cpp @@ -204,6 +204,10 @@ void TextureCacheDX9::UpdateCurrentClut(GEPaletteFormat clutFormat, u32 clutBase } void TextureCacheDX9::BindTexture(TexCacheEntry *entry) { + if (!entry) { + device_->SetTexture(0, nullptr); + return; + } LPDIRECT3DBASETEXTURE9 texture = DxTex(entry); if (texture != lastBoundTexture) { device_->SetTexture(0, texture); @@ -215,7 +219,7 @@ void TextureCacheDX9::BindTexture(TexCacheEntry *entry) { } void TextureCacheDX9::Unbind() { - device_->SetTexture(0, NULL); + device_->SetTexture(0, nullptr); InvalidateLastTexture(); } diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index eb6ab9507a..51ca567183 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -388,14 +388,19 @@ void TextureCacheVulkan::UpdateCurrentClut(GEPaletteFormat clutFormat, u32 clutB } void TextureCacheVulkan::BindTexture(TexCacheEntry *entry) { - _assert_(entry); - _assert_(entry->vkTex); + if (!entry) { + imageView_ = VK_NULL_HANDLE; + curSampler_ = VK_NULL_HANDLE; + return; + } + _dbg_assert_(entry->vkTex); entry->vkTex->Touch(); - imageView_ = entry->vkTex->GetImageView(); + int maxLevel = (entry->status & TexCacheEntry::STATUS_NO_MIPS) ? 0 : entry->maxLevel; SamplerCacheKey samplerKey = GetSamplingParams(maxLevel, entry); curSampler_ = samplerCache_.GetOrCreateSampler(samplerKey); + imageView_ = entry->vkTex->GetImageView(); drawEngine_->SetDepalTexture(VK_NULL_HANDLE); gstate_c.SetUseShaderDepal(false); } From 68480c548d33677ee31f188f3f0d52b41e1d0405 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Fri, 19 Aug 2022 00:02:22 +0200 Subject: [PATCH 19/85] Texture bind channel fix --- GPU/Common/TextureCacheCommon.cpp | 6 ++++-- GPU/Common/TextureCacheCommon.h | 1 + 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index d5de94ea28..7f1c86feb3 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -1023,6 +1023,8 @@ void TextureCacheCommon::SetTextureFramebuffer(const AttachCandidate &candidate) // Keep the framebuffer alive. framebuffer->last_frame_used = gpuStats.numFlips; + nextFramebufferTextureChannel_ = RASTER_COLOR; + if (framebufferManager_->UseBufferedRendering()) { // We need to force it, since we may have set it on a texture before attaching. gstate_c.curTextureWidth = framebuffer->bufferWidth; @@ -1049,6 +1051,7 @@ void TextureCacheCommon::SetTextureFramebuffer(const AttachCandidate &candidate) failedTexture_ = true; } else { nextFramebufferTexture_ = framebuffer; + nextFramebufferTextureChannel_ = candidate.channel; } nextTexture_ = nullptr; } else { @@ -1764,9 +1767,8 @@ void TextureCacheCommon::ApplyTexture() { // Backends should handle this by binding a black texture with 0 alpha. BindTexture(nullptr); } else if (nextFramebufferTexture_) { - bool depth = Memory::IsDepthTexVRAMAddress(gstate.getTextureAddress(0)); // ApplyTextureFrameBuffer is responsible for setting SetTextureFullAlpha. - ApplyTextureFramebuffer(nextFramebufferTexture_, gstate.getTextureFormat(), depth ? RASTER_DEPTH : RASTER_COLOR); + ApplyTextureFramebuffer(nextFramebufferTexture_, gstate.getTextureFormat(), nextFramebufferTextureChannel_); nextFramebufferTexture_ = nullptr; } diff --git a/GPU/Common/TextureCacheCommon.h b/GPU/Common/TextureCacheCommon.h index dbfbb316e4..a8b48878e2 100644 --- a/GPU/Common/TextureCacheCommon.h +++ b/GPU/Common/TextureCacheCommon.h @@ -435,6 +435,7 @@ protected: TexCacheEntry *nextTexture_ = nullptr; bool failedTexture_ = false; VirtualFramebuffer *nextFramebufferTexture_ = nullptr; + RasterChannel nextFramebufferTextureChannel_ = RASTER_COLOR; u32 clutHash_ = 0; From a0ac2dffc7496fd3ffe668c83546ef3d482496b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Mon, 1 Aug 2022 23:55:58 +0200 Subject: [PATCH 20/85] Defer depth copies until depth buffer is actually used. Fixes --- GPU/Common/FramebufferManagerCommon.cpp | 54 ++++++++++++++----------- GPU/Common/FramebufferManagerCommon.h | 2 + GPU/GPUCommon.cpp | 10 +++++ GPU/GPUState.h | 3 ++ 4 files changed, 45 insertions(+), 24 deletions(-) diff --git a/GPU/Common/FramebufferManagerCommon.cpp b/GPU/Common/FramebufferManagerCommon.cpp index e25c0b9a35..eeae895d53 100644 --- a/GPU/Common/FramebufferManagerCommon.cpp +++ b/GPU/Common/FramebufferManagerCommon.cpp @@ -377,6 +377,11 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame // // We use a special fragment shader flag to convert color to depth. vfb = GetLatestDepthBufferAt(params.fb_address /* !!! */, params.fb_stride); + if (vfb) { + vfb->depthBindSeq = GetBindSeqCount(); + } + // Avoid causing another depth copy on top. + gstate_c.usingDepth = true; } gstate_c.SetFramebufferRenderMode(mode); @@ -416,6 +421,8 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame // None found? Create one. if (!vfb) { + gstate_c.usingDepth = false; // reset depth buffer tracking + vfb = new VirtualFramebuffer{}; vfb->fbo = nullptr; vfb->fb_address = params.fb_address; @@ -442,17 +449,6 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame ResizeFramebufFBO(vfb, drawing_width, drawing_height, true); NotifyRenderFramebufferCreated(vfb); - // Looks up by z_address, so if one is found here and not have last pointers equal to this one, - // there is another one. - VirtualFramebuffer *prevDepth = GetLatestDepthBufferAt(vfb->z_address, vfb->z_stride); - - // We might already want to copy depth, in case this is a temp buffer. See #7810. - if (prevDepth != vfb) { - if (!params.isClearingDepth && prevDepth) { - BlitFramebufferDepth(prevDepth, vfb); - } - } - SetColorUpdated(vfb, skipDrawReason); INFO_LOG(FRAMEBUF, "Creating FBO for %08x (z: %08x) : %d x %d x %s", vfb->fb_address, vfb->z_address, vfb->width, vfb->height, GeBufferFormatToString(vfb->format)); @@ -510,18 +506,19 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame VirtualFramebuffer *prev = currentRenderVfb_; currentRenderVfb_ = vfb; NotifyRenderFramebufferSwitched(prev, vfb, params.isClearingDepth); + gstate_c.usingDepth = false; // reset depth buffer tracking } else { + // Something changed, but we still got the same framebuffer we were already rendering to. + // Might not be a lot to do here, we check in NotifyRenderFramebufferUpdated vfb->last_frame_render = gpuStats.numFlips; frameLastFramebufUsed_ = gpuStats.numFlips; vfb->dirtyAfterDisplay = true; if ((skipDrawReason & SKIPDRAW_SKIPFRAME) == 0) vfb->reallyDirtyAfterDisplay = true; - NotifyRenderFramebufferUpdated(vfb, vfbFormatChanged); } vfb->colorBindSeq = GetBindSeqCount(); - vfb->depthBindSeq = GetBindSeqCount(); gstate_c.curRTWidth = vfb->width; gstate_c.curRTHeight = vfb->height; @@ -530,6 +527,26 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame return vfb; } +// Called on the first use of depth in a render pass. +void FramebufferManagerCommon::SetDepthFrameBuffer() { + if (!currentRenderVfb_) { + return; + } + + // Looks up by z_address, so if one is found here and not have last pointers equal to this one, + // there is another one. + VirtualFramebuffer *prevDepth = GetLatestDepthBufferAt(currentRenderVfb_->z_address, currentRenderVfb_->z_stride); + + if (prevDepth != currentRenderVfb_) { + if (!gstate_c.clearingDepth && prevDepth) { + BlitFramebufferDepth(prevDepth, currentRenderVfb_); + } + prevDepth = currentRenderVfb_; + } + + currentRenderVfb_->depthBindSeq = GetBindSeqCount(); +} + void FramebufferManagerCommon::DestroyFramebuf(VirtualFramebuffer *v) { // Notify the texture cache of both the color and depth buffers. textureCache_->NotifyFramebuffer(v, NOTIFY_FB_DESTROYED); @@ -669,17 +686,6 @@ void FramebufferManagerCommon::NotifyRenderFramebufferSwitched(VirtualFramebuffe textureCache_->ForgetLastTexture(); shaderManager_->DirtyLastShader(); - // Copy depth between the framebuffers, if the z_address is the same (checked inside.) - VirtualFramebuffer * prevDepth = GetLatestDepthBufferAt(vfb->z_address, vfb->z_stride); - - // We might already want to copy depth, in case this is a temp buffer. See #7810. - if (prevDepth != vfb) { - if (!isClearingDepth && prevDepth) { - BlitFramebufferDepth(prevDepth, vfb); - } - prevDepth = vfb; - } - if (vfb->drawnFormat != vfb->format) { ReinterpretFramebuffer(vfb, vfb->drawnFormat, vfb->format); } diff --git a/GPU/Common/FramebufferManagerCommon.h b/GPU/Common/FramebufferManagerCommon.h index e592ed7b87..87a4e577cd 100644 --- a/GPU/Common/FramebufferManagerCommon.h +++ b/GPU/Common/FramebufferManagerCommon.h @@ -266,6 +266,8 @@ public: return vfb; } } + void SetDepthFrameBuffer(); + void RebindFramebuffer(const char *tag); std::vector GetFramebufferList() const; diff --git a/GPU/GPUCommon.cpp b/GPU/GPUCommon.cpp index a0deb403aa..d751291a9b 100644 --- a/GPU/GPUCommon.cpp +++ b/GPU/GPUCommon.cpp @@ -1685,6 +1685,16 @@ void GPUCommon::Execute_Prim(u32 op, u32 diff) { return; } + if (!gstate_c.usingDepth) { + bool isClearingDepth = gstate.isModeClear() && gstate.isClearModeDepthMask();; + + if ((gstate.isDepthTestEnabled() || isClearingDepth)) { + gstate_c.usingDepth = true; + gstate_c.clearingDepth = isClearingDepth; + framebufferManager_->SetDepthFrameBuffer(); + } + } + const void *verts = Memory::GetPointerUnchecked(gstate_c.vertexAddr); const void *inds = nullptr; u32 vertexType = gstate.vertType; diff --git a/GPU/GPUState.h b/GPU/GPUState.h index 8d6d04039b..3f30be89f7 100644 --- a/GPU/GPUState.h +++ b/GPU/GPUState.h @@ -572,6 +572,9 @@ struct GPUStateCache { uint64_t dirty; + bool usingDepth; // For deferred depth copies. + bool clearingDepth; + bool textureFullAlpha; bool vertexFullAlpha; From 886679c7ec71a7adb89e7ce9c2d21218b15e2df1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Wed, 17 Aug 2022 11:31:02 +0200 Subject: [PATCH 21/85] Remove the color-to-depth mode --- GPU/Common/FragmentShaderGenerator.cpp | 29 ++-------------------- GPU/Common/FramebufferManagerCommon.cpp | 33 ------------------------- GPU/Common/GPUStateUtils.cpp | 10 -------- GPU/Common/ShaderId.cpp | 5 ---- GPU/Common/ShaderId.h | 1 - GPU/Common/TextureCacheCommon.cpp | 9 ------- GPU/D3D11/StateMappingD3D11.cpp | 9 +------ GPU/Directx9/StateMappingDX9.cpp | 9 +------ GPU/GLES/StateMappingGLES.cpp | 6 +---- GPU/GPU.h | 5 ---- GPU/GPUState.h | 11 --------- GPU/Vulkan/StateMappingVulkan.cpp | 9 +------ 12 files changed, 6 insertions(+), 130 deletions(-) diff --git a/GPU/Common/FragmentShaderGenerator.cpp b/GPU/Common/FragmentShaderGenerator.cpp index ad3f22af8c..f956217b38 100644 --- a/GPU/Common/FragmentShaderGenerator.cpp +++ b/GPU/Common/FragmentShaderGenerator.cpp @@ -90,7 +90,6 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu bool shaderDepal = id.Bit(FS_BIT_SHADER_DEPAL) && !texture3D; // combination with texture3D not supported. Enforced elsewhere too. bool bgraTexture = id.Bit(FS_BIT_BGRA_TEXTURE); bool colorWriteMask = id.Bit(FS_BIT_COLOR_WRITEMASK) && compat.bitwiseOps; - bool colorToDepth = id.Bit(FS_BIT_COLOR_TO_DEPTH); GEComparison alphaTestFunc = (GEComparison)id.Bits(FS_BIT_ALPHA_TEST_FUNC, 3); GEComparison colorTestFunc = (GEComparison)id.Bits(FS_BIT_COLOR_TEST_FUNC, 2); @@ -123,7 +122,7 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu bool readFramebufferTex = readFramebuffer && !gstate_c.Supports(GPU_SUPPORTS_ANY_FRAMEBUFFER_FETCH); bool needFragCoord = readFramebuffer || gstate_c.Supports(GPU_ROUND_FRAGMENT_DEPTH_TO_16BIT); - bool writeDepth = gstate_c.Supports(GPU_ROUND_FRAGMENT_DEPTH_TO_16BIT) || colorToDepth; + bool writeDepth = gstate_c.Supports(GPU_ROUND_FRAGMENT_DEPTH_TO_16BIT); if (shaderDepal && !doTexture) { *errorString = "depal requires a texture"; @@ -136,11 +135,6 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu } if (compat.shaderLanguage == ShaderLanguage::GLSL_VULKAN) { - if (colorToDepth) { - WRITE(p, "precision highp int;\n"); - WRITE(p, "precision highp float;\n"); - } - if (useDiscardStencilBugWorkaround && !gstate_c.Supports(GPU_ROUND_FRAGMENT_DEPTH_TO_16BIT)) { WRITE(p, "layout (depth_unchanged) out float gl_FragDepth;\n"); } @@ -293,7 +287,7 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu WRITE(p, "};\n"); } } else if (ShaderLanguageIsOpenGL(compat.shaderLanguage)) { - if ((shaderDepal || colorWriteMask || colorToDepth) && gl_extensions.IsGLES) { + if ((shaderDepal || colorWriteMask) && gl_extensions.IsGLES) { WRITE(p, "precision highp int;\n"); } @@ -461,9 +455,6 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu WRITE(p, "PS_OUT main( PS_IN In ) {\n"); WRITE(p, " PS_OUT outfragment;\n"); WRITE(p, " vec4 target;\n"); - if (colorToDepth) { - WRITE(p, " float gl_FragDepth;\n"); - } } else { WRITE(p, "void main() {\n"); } @@ -1070,22 +1061,6 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu WRITE(p, " %s = vec4(0.0, 0.0, 0.0, %s.z); // blue to alpha\n", compat.fragColor0, compat.fragColor0); } - if (colorToDepth) { - DepthScaleFactors factors = GetDepthScaleFactors(); - - if (compat.bitwiseOps) { - WRITE(p, " highp float depthValue = float(int(%s.x * 31.99) | (int(%s.y * 63.99) << 5) | (int(%s.z * 31.99) << 11)) / 65535.0;\n", "v", "v", "v"); // compat.fragColor0, compat.fragColor0, compat.fragColor0); - } else { - // D3D9-compatible alternative - WRITE(p, " highp float depthValue = (floor(%s.x * 31.99) + floor(%s.y * 63.99) * 32.0 + floor(%s.z * 31.99) * 2048.0) / 65535.0;\n", "v", "v", "v"); // compat.fragColor0, compat.fragColor0, compat.fragColor0); - } - if (factors.scale != 1.0 || factors.offset != 0.0) { - WRITE(p, " gl_FragDepth = (depthValue / %f) + %f;\n", factors.scale / 65535.0f, factors.offset); - } else { - WRITE(p, " gl_FragDepth = depthValue;\n"); - } - } - if (gstate_c.Supports(GPU_ROUND_FRAGMENT_DEPTH_TO_16BIT)) { const double scale = DepthSliceFactor() * 65535.0; diff --git a/GPU/Common/FramebufferManagerCommon.cpp b/GPU/Common/FramebufferManagerCommon.cpp index eeae895d53..e0b05f76c7 100644 --- a/GPU/Common/FramebufferManagerCommon.cpp +++ b/GPU/Common/FramebufferManagerCommon.cpp @@ -280,8 +280,6 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame WARN_LOG_ONCE(color_equal_z, G3D, "Framebuffer bound with color addr == z addr, likely will not use Z in this pass: %08x", params.fb_address); } - RasterMode mode = RASTER_MODE_NORMAL; - // Find a matching framebuffer VirtualFramebuffer *vfb = nullptr; for (size_t i = 0; i < vfbs_.size(); ++i) { @@ -318,19 +316,6 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame vfb->height = drawing_height; } break; - } else if (params.fb_address == v->z_address && params.fmt != GE_FORMAT_8888 && params.fb_stride == v->z_stride && !params.isBlending) { - // Looks like the game might be intending to use color to write directly to a Z buffer. - // This is seen in Kuroyou 2. - - // Ignore this in this loop, BUT, we do a lookup in the depth tracking afterwards to - // make sure we get the latest one. - WARN_LOG_ONCE(color_matches_z, G3D, "Color framebuffer bound at %08x with likely intent to write explicit Z values using color. fmt = %s", params.fb_address, GeBufferFormatToString(params.fmt)); - // Seems impractical to use the other 16-bit formats for this due to the limited control over alpha, - // so we'll simply only support 565. - if (params.fmt == GE_FORMAT_565) { - mode = RASTER_MODE_COLOR_TO_DEPTH; - break; - } } else if (v->fb_stride == params.fb_stride && v->format == params.fmt) { u32 v_fb_first_line_end_ptr = v->fb_address + v->fb_stride * 4; // This should be * bpp, but leaving like this until after 1.13 to be safe. The God of War games use this for shadows. u32 v_fb_end_ptr = v->fb_address + v->fb_stride * v->height * bpp; @@ -368,24 +353,6 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame } } - if (mode == RASTER_MODE_COLOR_TO_DEPTH) { - // Lookup in the depth tracking to find which VFB has the latest version of this Z buffer. - // Then bind it in color-to-depth mode. - // - // We do this by having a special render mode where we take color and move to - // depth in the fragment shader, and set color writes to off. - // - // We use a special fragment shader flag to convert color to depth. - vfb = GetLatestDepthBufferAt(params.fb_address /* !!! */, params.fb_stride); - if (vfb) { - vfb->depthBindSeq = GetBindSeqCount(); - } - // Avoid causing another depth copy on top. - gstate_c.usingDepth = true; - } - - gstate_c.SetFramebufferRenderMode(mode); - if (vfb) { if ((drawing_width != vfb->bufferWidth || drawing_height != vfb->bufferHeight)) { // Even if it's not newly wrong, if this is larger we need to resize up. diff --git a/GPU/Common/GPUStateUtils.cpp b/GPU/Common/GPUStateUtils.cpp index e86c056c5a..51f0e3f8eb 100644 --- a/GPU/Common/GPUStateUtils.cpp +++ b/GPU/Common/GPUStateUtils.cpp @@ -1018,16 +1018,6 @@ void ConvertMaskState(GenericMaskState &maskState, bool allowFramebufferRead) { return; } - if (gstate_c.renderMode == RASTER_MODE_COLOR_TO_DEPTH) { - // Suppress color writes entirely in this mode. - maskState.applyFramebufferRead = false; - maskState.rgba[0] = false; - maskState.rgba[1] = false; - maskState.rgba[2] = false; - maskState.rgba[3] = false; - return; - } - // Invert to convert masks from the PSP's format where 1 is don't draw to PC where 1 is draw. uint32_t colorMask = ~((gstate.pmskc & 0xFFFFFF) | (gstate.pmska << 24)); diff --git a/GPU/Common/ShaderId.cpp b/GPU/Common/ShaderId.cpp index 1176200799..510e90e929 100644 --- a/GPU/Common/ShaderId.cpp +++ b/GPU/Common/ShaderId.cpp @@ -240,8 +240,6 @@ std::string FragmentShaderDesc(const FShaderID &id) { if (id.Bit(FS_BIT_COLOR_AGAINST_ZERO)) desc << "ColorTest0 " << alphaTestFuncs[id.Bits(FS_BIT_COLOR_TEST_FUNC, 2)] << " "; // first 4 match; else if (id.Bit(FS_BIT_COLOR_TEST)) desc << "ColorTest " << alphaTestFuncs[id.Bits(FS_BIT_COLOR_TEST_FUNC, 2)] << " "; // first 4 match - if (id.Bit(FS_BIT_COLOR_TO_DEPTH)) desc << "ColorToDepth "; - return desc.str(); } @@ -264,7 +262,6 @@ void ComputeFragmentShaderID(FShaderID *id_out, const Draw::Bugs &bugs) { bool doFlatShading = gstate.getShadeMode() == GE_SHADE_FLAT; bool useShaderDepal = gstate_c.useShaderDepal; bool colorWriteMask = IsColorWriteMaskComplex(gstate_c.allowFramebufferRead); - bool colorToDepth = gstate_c.renderMode == RasterMode::RASTER_MODE_COLOR_TO_DEPTH; // Note how we here recompute some of the work already done in state mapping. // Not ideal! At least we share the code. @@ -296,8 +293,6 @@ void ComputeFragmentShaderID(FShaderID *id_out, const Draw::Bugs &bugs) { id.SetBit(FS_BIT_3D_TEXTURE, gstate_c.curTextureIs3D); } - id.SetBit(FS_BIT_COLOR_TO_DEPTH, colorToDepth); - id.SetBit(FS_BIT_LMODE, lmode); if (enableAlphaTest) { // 5 bits total. diff --git a/GPU/Common/ShaderId.h b/GPU/Common/ShaderId.h index bcdf4f723c..8dcee32c1e 100644 --- a/GPU/Common/ShaderId.h +++ b/GPU/Common/ShaderId.h @@ -94,7 +94,6 @@ enum FShaderBit : uint8_t { FS_BIT_NO_DEPTH_CANNOT_DISCARD_STENCIL = 49, FS_BIT_COLOR_WRITEMASK = 50, FS_BIT_3D_TEXTURE = 51, - FS_BIT_COLOR_TO_DEPTH = 52, }; static inline FShaderBit operator +(FShaderBit bit, int i) { diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index 7f1c86feb3..488aa86d30 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -265,10 +265,6 @@ SamplerCacheKey TextureCacheCommon::GetSamplingParams(int maxLevel, const TexCac } } - if (gstate_c.renderMode == RASTER_MODE_COLOR_TO_DEPTH) { - forceFiltering = TEX_FILTER_FORCE_NEAREST; - } - switch (forceFiltering) { case TEX_FILTER_AUTO: break; @@ -2247,11 +2243,6 @@ bool TextureCacheCommon::PrepareBuildTexture(BuildTexturePlan &plan, TexCacheEnt plan.scaleFactor = 1; } - // Don't upscale textures in color-to-depth mode. - if (gstate_c.renderMode == RASTER_MODE_COLOR_TO_DEPTH) { - plan.scaleFactor = 1; - } - if ((entry->status & TexCacheEntry::STATUS_CHANGE_FREQUENT) != 0 && plan.scaleFactor != 1 && plan.slowScaler) { // Remember for later that we /wanted/ to scale this texture. entry->status |= TexCacheEntry::STATUS_TO_SCALE; diff --git a/GPU/D3D11/StateMappingD3D11.cpp b/GPU/D3D11/StateMappingD3D11.cpp index 79a169a8ab..da9ec068e6 100644 --- a/GPU/D3D11/StateMappingD3D11.cpp +++ b/GPU/D3D11/StateMappingD3D11.cpp @@ -293,14 +293,7 @@ void DrawEngineD3D11::ApplyDrawState(int prim) { GenericStencilFuncState stencilState; ConvertStencilFuncState(stencilState); - if (gstate_c.renderMode == RASTER_MODE_COLOR_TO_DEPTH) { - // Enforce plain depth writing. - keys_.depthStencil.value = 0; - keys_.depthStencil.depthTestEnable = true; - keys_.depthStencil.depthWriteEnable = true; - keys_.depthStencil.stencilTestEnable = false; - keys_.depthStencil.depthCompareOp = D3D11_COMPARISON_ALWAYS; - } else if (gstate.isModeClear()) { + if (gstate.isModeClear()) { keys_.depthStencil.value = 0; keys_.depthStencil.depthTestEnable = true; keys_.depthStencil.depthCompareOp = D3D11_COMPARISON_ALWAYS; diff --git a/GPU/Directx9/StateMappingDX9.cpp b/GPU/Directx9/StateMappingDX9.cpp index 0de9c1774d..3d06b380e0 100644 --- a/GPU/Directx9/StateMappingDX9.cpp +++ b/GPU/Directx9/StateMappingDX9.cpp @@ -211,14 +211,7 @@ void DrawEngineDX9::ApplyDrawState(int prim) { ConvertStencilFuncState(stencilState); // Set Stencil/Depth - - if (gstate_c.renderMode == RASTER_MODE_COLOR_TO_DEPTH) { - // Enforce plain depth writing. - dxstate.depthTest.enable(); - dxstate.depthFunc.set(D3DCMP_ALWAYS); - dxstate.depthWrite.set(true); - dxstate.stencilTest.disable(); - } else if (gstate.isModeClear()) { + if (gstate.isModeClear()) { // Depth Test dxstate.depthTest.enable(); dxstate.depthFunc.set(D3DCMP_ALWAYS); diff --git a/GPU/GLES/StateMappingGLES.cpp b/GPU/GLES/StateMappingGLES.cpp index 54c94ccbd3..6e498875f1 100644 --- a/GPU/GLES/StateMappingGLES.cpp +++ b/GPU/GLES/StateMappingGLES.cpp @@ -251,11 +251,7 @@ void DrawEngineGLES::ApplyDrawState(int prim) { GenericStencilFuncState stencilState; ConvertStencilFuncState(stencilState); - if (gstate_c.renderMode == RASTER_MODE_COLOR_TO_DEPTH) { - // Enforce plain depth writing. - renderManager->SetStencilDisabled(); - renderManager->SetDepth(true, true, GL_ALWAYS); - } else if (gstate.isModeClear()) { + if (gstate.isModeClear()) { // Depth Test if (gstate.isClearModeDepthMask()) { framebufferManager_->SetDepthUpdated(); diff --git a/GPU/GPU.h b/GPU/GPU.h index ecb9ae33c4..18af975ae8 100644 --- a/GPU/GPU.h +++ b/GPU/GPU.h @@ -24,11 +24,6 @@ class GPUInterface; class GPUDebugInterface; class GraphicsContext; -enum RasterMode { - RASTER_MODE_NORMAL = 0, - RASTER_MODE_COLOR_TO_DEPTH = 1, -}; - // 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. diff --git a/GPU/GPUState.h b/GPU/GPUState.h index 3f30be89f7..6aaa79a8fd 100644 --- a/GPU/GPUState.h +++ b/GPU/GPUState.h @@ -555,14 +555,6 @@ struct GPUStateCache { Dirty(DIRTY_FRAGMENTSHADER_STATE | (is3D ? DIRTY_MIPBIAS : 0)); } } - void SetFramebufferRenderMode(RasterMode mode) { - if (mode != renderMode) { - // This mode modifies the fragment shader to write depth, the depth state to write without testing, and the blend state to write nothing to color. - // So we need to re-evaluate those states. - Dirty(DIRTY_FRAGMENTSHADER_STATE | DIRTY_BLEND_STATE | DIRTY_DEPTHSTENCIL_STATE | DIRTY_TEXTURE_PARAMS); - renderMode = mode; - } - } u32 featureFlags; @@ -616,9 +608,6 @@ struct GPUStateCache { // We detect this case and go into a special drawing mode. bool blueToAlpha; - // Some games try to write to the Z buffer using color. Catch that and actually do the writes to the Z buffer instead. - RasterMode renderMode; - // TODO: These should be accessed from the current VFB object directly. u32 curRTWidth; u32 curRTHeight; diff --git a/GPU/Vulkan/StateMappingVulkan.cpp b/GPU/Vulkan/StateMappingVulkan.cpp index 6aa176c864..166f3dc153 100644 --- a/GPU/Vulkan/StateMappingVulkan.cpp +++ b/GPU/Vulkan/StateMappingVulkan.cpp @@ -250,14 +250,7 @@ void DrawEngineVulkan::ConvertStateToVulkanKey(FramebufferManagerVulkan &fbManag GenericStencilFuncState stencilState; ConvertStencilFuncState(stencilState); - if (gstate_c.renderMode == RASTER_MODE_COLOR_TO_DEPTH) { - // Enforce plain depth writing. - key.depthTestEnable = true; - key.depthWriteEnable = true; - key.stencilTestEnable = false; - key.depthCompareOp = VK_COMPARE_OP_ALWAYS; - key.depthClampEnable = false; - } else if (gstate.isModeClear()) { + if (gstate.isModeClear()) { key.depthTestEnable = true; key.depthCompareOp = VK_COMPARE_OP_ALWAYS; key.depthWriteEnable = gstate.isClearModeDepthMask(); From 94ade8c75142fea41eda38089318457cdbf47ae4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Wed, 17 Aug 2022 12:11:00 +0200 Subject: [PATCH 22/85] Extract depth copies to CopyToDepthFromOverlappingFramebuffers --- GPU/Common/FramebufferManagerCommon.cpp | 63 +++++++++++++++++++++++-- GPU/Common/FramebufferManagerCommon.h | 2 + 2 files changed, 61 insertions(+), 4 deletions(-) diff --git a/GPU/Common/FramebufferManagerCommon.cpp b/GPU/Common/FramebufferManagerCommon.cpp index e0b05f76c7..0452b529a1 100644 --- a/GPU/Common/FramebufferManagerCommon.cpp +++ b/GPU/Common/FramebufferManagerCommon.cpp @@ -416,6 +416,10 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame ResizeFramebufFBO(vfb, drawing_width, drawing_height, true); NotifyRenderFramebufferCreated(vfb); + if (!params.isClearingDepth) { + CopyToDepthFromOverlappingFramebuffers(vfb); + } + SetColorUpdated(vfb, skipDrawReason); INFO_LOG(FRAMEBUF, "Creating FBO for %08x (z: %08x) : %d x %d x %s", vfb->fb_address, vfb->z_address, vfb->width, vfb->height, GeBufferFormatToString(vfb->format)); @@ -459,7 +463,7 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame } } - // We already have it! + // We already have it! } else if (vfb != currentRenderVfb_) { // Use it as a render target. DEBUG_LOG(FRAMEBUF, "Switching render target to FBO for %08x: %d x %d x %d ", vfb->fb_address, vfb->width, vfb->height, vfb->format); @@ -514,6 +518,54 @@ void FramebufferManagerCommon::SetDepthFrameBuffer() { currentRenderVfb_->depthBindSeq = GetBindSeqCount(); } +void FramebufferManagerCommon::CopyToDepthFromOverlappingFramebuffers(VirtualFramebuffer *dest) { + struct CopySource { + VirtualFramebuffer *vfb; + RasterChannel channel; + + int seq() const { + return channel == RASTER_DEPTH ? vfb->depthBindSeq : vfb->colorBindSeq; + } + + bool operator < (const CopySource &other) const { + return seq() < other.seq(); + } + }; + + std::vector sources; + for (auto src: vfbs_) { + if (src == dest) + continue; + + if (src->fb_address == dest->z_address && src->fb_stride == dest->z_stride && src->format == GE_FORMAT_565) { + if (src->colorBindSeq > dest->depthBindSeq) { + // Source has older data than the current buffer, ignore. + continue; + } + sources.push_back(CopySource{ src, RASTER_COLOR }); + } else if (src->z_address == dest->z_address && src->z_stride == dest->z_stride && src->depthBindSeq > dest->depthBindSeq) { + sources.push_back(CopySource{ src, RASTER_DEPTH }); + } else { + // TODO: Do more detailed overlap checks here. + } + } + + // TODO: A full depth copy will overwrite anything else. So we can eliminate + // anything that comes before such a copy. + + for (auto &source : sources) { + if (source.channel == RASTER_DEPTH) { + // Good old depth->depth copy. + BlitFramebufferDepth(source.vfb, dest); + + gpuStats.numDepthCopies++; + dest->last_frame_depth_updated = gpuStats.numFlips; + } + } + + gstate_c.Dirty(DIRTY_TEXTURE_IMAGE | DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_RASTER_STATE | DIRTY_DEPTHSTENCIL_STATE | DIRTY_BLEND_STATE); +} + void FramebufferManagerCommon::DestroyFramebuf(VirtualFramebuffer *v) { // Notify the texture cache of both the color and depth buffers. textureCache_->NotifyFramebuffer(v, NOTIFY_FB_DESTROYED); @@ -588,9 +640,6 @@ void FramebufferManagerCommon::BlitFramebufferDepth(VirtualFramebuffer *src, Vir } draw_->InvalidateCachedState(); - - gpuStats.numDepthCopies++; - dst->last_frame_depth_updated = gpuStats.numFlips; } VirtualFramebuffer *FramebufferManagerCommon::GetLatestDepthBufferAt(u32 z_address, u16 z_stride) { @@ -653,6 +702,12 @@ void FramebufferManagerCommon::NotifyRenderFramebufferSwitched(VirtualFramebuffe textureCache_->ForgetLastTexture(); shaderManager_->DirtyLastShader(); + if (!isClearingDepth) { + // TODO: We should do this as part of the bind below. Then we can optimize the RPAction properly, + // and also do the copies using raster. + CopyToDepthFromOverlappingFramebuffers(vfb); + } + if (vfb->drawnFormat != vfb->format) { ReinterpretFramebuffer(vfb, vfb->drawnFormat, vfb->format); } diff --git a/GPU/Common/FramebufferManagerCommon.h b/GPU/Common/FramebufferManagerCommon.h index 87a4e577cd..901e821590 100644 --- a/GPU/Common/FramebufferManagerCommon.h +++ b/GPU/Common/FramebufferManagerCommon.h @@ -386,6 +386,8 @@ protected: void Ensure2DResources(); Draw::Pipeline *Create2DPipeline(RasterChannel (*generate)(ShaderWriter &)); + void CopyToDepthFromOverlappingFramebuffers(VirtualFramebuffer *dest); + bool UpdateSize(); void FlushBeforeCopy(); From 5d8fe4c2a86faaf10062c8e470483b8a5ba1d99c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Wed, 17 Aug 2022 14:28:34 +0200 Subject: [PATCH 23/85] Implement copying color to depth on load. However, weird stuff is happening.. --- GPU/Common/Draw2D.cpp | 38 +++++++++++-- GPU/Common/Draw2D.h | 19 +++++++ GPU/Common/FramebufferManagerCommon.cpp | 76 ++++++++++--------------- GPU/Common/FramebufferManagerCommon.h | 7 +-- 4 files changed, 85 insertions(+), 55 deletions(-) diff --git a/GPU/Common/Draw2D.cpp b/GPU/Common/Draw2D.cpp index 7170aeb5f8..d9d0c5bc93 100644 --- a/GPU/Common/Draw2D.cpp +++ b/GPU/Common/Draw2D.cpp @@ -25,6 +25,7 @@ #include "GPU/Common/DrawEngineCommon.h" #include "GPU/Common/FramebufferManagerCommon.h" #include "GPU/Common/TextureCacheCommon.h" +#include "GPU/Common/GPUStateUtils.h" static const InputDef inputs[2] = { { "vec2", "a_position", Draw::SEM_POSITION }, @@ -58,6 +59,24 @@ RasterChannel GenerateDraw2DDepthFs(ShaderWriter &writer) { return RASTER_DEPTH; } +RasterChannel GenerateDraw2D565ToDepthFs(ShaderWriter &writer) { + writer.DeclareSamplers(samplers); + writer.BeginFSMain(Slice::empty(), varyings, FSFLAG_WRITEDEPTH); + writer.C(" vec4 outColor = vec4(0.0, 0.0, 0.0, 0.0);\n"); + // Unlike when just copying a depth buffer, here we're generating new depth values so we'll + // have to apply the scaling. + DepthScaleFactors factors = GetDepthScaleFactors(); + writer.C(" vec3 rgb = ").SampleTexture2D("tex", "v_texcoord.xy").C(".xyz;\n"); + writer.F(" highp float depthValue = (floor(rgb.x * 31.99) + floor(rgb.y * 63.99) * 32.0 + floor(rgb.z * 31.99) * 2048.0) / 65535.0; \n"); + if (factors.scale != 1.0 || factors.offset != 0.0) { + writer.F(" gl_FragDepth = (depthValue / %f) + %f;\n", factors.scale / 65535.0f, factors.offset); + } else { + writer.C(" gl_FragDepth = depthValue;\n"); + } + writer.EndFSMain("outColor", FSFLAG_WRITEDEPTH); + return RASTER_DEPTH; +} + void GenerateDraw2DVS(ShaderWriter &writer) { writer.BeginVSMain(inputs, Slice::empty(), varyings); @@ -159,22 +178,22 @@ Draw::Pipeline *FramebufferManagerCommon::Create2DPipeline(RasterChannel (*gener return pipeline; } -void FramebufferManagerCommon::DrawStrip2D(Draw::Texture *tex, Draw2DVertex *verts, int vertexCount, bool linearFilter, RasterChannel channel) { +void FramebufferManagerCommon::DrawStrip2D(Draw::Texture *tex, Draw2DVertex *verts, int vertexCount, bool linearFilter, Draw2DShader shader) { using namespace Draw; Ensure2DResources(); const ShaderLanguageDesc &shaderLanguageDesc = draw_->GetShaderLanguageDesc(); - switch (channel) { - case RASTER_COLOR: + switch (shader) { + case DRAW2D_COPY_COLOR: if (!draw2DPipelineColor_) { draw2DPipelineColor_ = Create2DPipeline(&GenerateDraw2DFs); } draw_->BindPipeline(draw2DPipelineColor_); break; - case RASTER_DEPTH: + case DRAW2D_COPY_DEPTH: if (!draw_->GetDeviceCaps().fragmentShaderDepthWriteSupported) { // Can't do it return; @@ -184,6 +203,17 @@ void FramebufferManagerCommon::DrawStrip2D(Draw::Texture *tex, Draw2DVertex *ver } draw_->BindPipeline(draw2DPipelineDepth_); break; + + case DRAW2D_565_TO_DEPTH: + if (!draw_->GetDeviceCaps().fragmentShaderDepthWriteSupported) { + // Can't do it + return; + } + if (!draw2DPipeline565ToDepth_) { + draw2DPipeline565ToDepth_ = Create2DPipeline(&GenerateDraw2D565ToDepthFs); + } + draw_->BindPipeline(draw2DPipeline565ToDepth_); + break; } if (tex) { diff --git a/GPU/Common/Draw2D.h b/GPU/Common/Draw2D.h index 34c171e7a0..fee2d4cef3 100644 --- a/GPU/Common/Draw2D.h +++ b/GPU/Common/Draw2D.h @@ -1,5 +1,7 @@ #pragma once +#include "GPU/GPU.h" + // For framebuffer copies and similar things that just require passthrough. struct Draw2DVertex { float x; @@ -7,3 +9,20 @@ struct Draw2DVertex { float u; float v; }; + +enum Draw2DShader { + DRAW2D_COPY_COLOR, + DRAW2D_COPY_DEPTH, + DRAW2D_565_TO_DEPTH, +}; + +inline RasterChannel Draw2DSourceChannel(Draw2DShader shader) { + switch (shader) { + case DRAW2D_COPY_DEPTH: + return RASTER_DEPTH; + case DRAW2D_COPY_COLOR: + case DRAW2D_565_TO_DEPTH: + default: + return RASTER_COLOR; + } +} diff --git a/GPU/Common/FramebufferManagerCommon.cpp b/GPU/Common/FramebufferManagerCommon.cpp index 0452b529a1..b07bb171ba 100644 --- a/GPU/Common/FramebufferManagerCommon.cpp +++ b/GPU/Common/FramebufferManagerCommon.cpp @@ -416,9 +416,7 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame ResizeFramebufFBO(vfb, drawing_width, drawing_height, true); NotifyRenderFramebufferCreated(vfb); - if (!params.isClearingDepth) { - CopyToDepthFromOverlappingFramebuffers(vfb); - } + // Note that we do not even think about depth right now. SetColorUpdated(vfb, skipDrawReason); @@ -504,16 +502,8 @@ void FramebufferManagerCommon::SetDepthFrameBuffer() { return; } - // Looks up by z_address, so if one is found here and not have last pointers equal to this one, - // there is another one. - VirtualFramebuffer *prevDepth = GetLatestDepthBufferAt(currentRenderVfb_->z_address, currentRenderVfb_->z_stride); - - if (prevDepth != currentRenderVfb_) { - if (!gstate_c.clearingDepth && prevDepth) { - BlitFramebufferDepth(prevDepth, currentRenderVfb_); - } - prevDepth = currentRenderVfb_; - } + // "Resolve" the depth buffer, by copying from any overlapping buffers with fresher content. + CopyToDepthFromOverlappingFramebuffers(currentRenderVfb_); currentRenderVfb_->depthBindSeq = GetBindSeqCount(); } @@ -538,11 +528,10 @@ void FramebufferManagerCommon::CopyToDepthFromOverlappingFramebuffers(VirtualFra continue; if (src->fb_address == dest->z_address && src->fb_stride == dest->z_stride && src->format == GE_FORMAT_565) { - if (src->colorBindSeq > dest->depthBindSeq) { - // Source has older data than the current buffer, ignore. - continue; + if (src->colorBindSeq < dest->depthBindSeq) { + // Source has newer data than the current buffer, use it. + sources.push_back(CopySource{ src, RASTER_COLOR }); } - sources.push_back(CopySource{ src, RASTER_COLOR }); } else if (src->z_address == dest->z_address && src->z_stride == dest->z_stride && src->depthBindSeq > dest->depthBindSeq) { sources.push_back(CopySource{ src, RASTER_DEPTH }); } else { @@ -550,16 +539,25 @@ void FramebufferManagerCommon::CopyToDepthFromOverlappingFramebuffers(VirtualFra } } - // TODO: A full depth copy will overwrite anything else. So we can eliminate + std::sort(sources.begin(), sources.end()); + + // TODO: A full copy will overwrite anything else. So we can eliminate // anything that comes before such a copy. - for (auto &source : sources) { + // For now, let's just do the last thing, if there are multiple. + + // for (auto &source : sources) { + if (sources.size()) { + auto &source = sources.back(); if (source.channel == RASTER_DEPTH) { // Good old depth->depth copy. BlitFramebufferDepth(source.vfb, dest); - gpuStats.numDepthCopies++; dest->last_frame_depth_updated = gpuStats.numFlips; + } else if (source.channel == RASTER_COLOR) { + VirtualFramebuffer *src = source.vfb; + // Copying color to depth. + BlitUsingRaster(src->fbo, 0.0f, 0.0f, src->renderWidth, src->renderHeight, dest->fbo, 0.0f, 0.0f, dest->renderWidth, dest->renderHeight, false, DRAW2D_565_TO_DEPTH, "565_to_depth"); } } @@ -636,24 +634,12 @@ void FramebufferManagerCommon::BlitFramebufferDepth(VirtualFramebuffer *src, Vir draw_->BlitFramebuffer(src->fbo, 0, 0, w, h, dst->fbo, 0, 0, w, h, Draw::FB_DEPTH_BIT, Draw::FB_BLIT_NEAREST, "BlitFramebufferDepth"); RebindFramebuffer("After BlitFramebufferDepth"); } else if (useRaster) { - BlitUsingRaster(src->fbo, 0, 0, w, h, dst->fbo, 0, 0, w, h, false, RasterChannel::RASTER_DEPTH); + BlitUsingRaster(src->fbo, 0, 0, w, h, dst->fbo, 0, 0, w, h, false, Draw2DShader::DRAW2D_COPY_DEPTH, "BlitDepthRaster"); } draw_->InvalidateCachedState(); } -VirtualFramebuffer *FramebufferManagerCommon::GetLatestDepthBufferAt(u32 z_address, u16 z_stride) { - int maxSeq = -1; - VirtualFramebuffer *latestDepth = nullptr; - for (auto vfb : vfbs_) { - if (vfb->z_address == z_address && vfb->z_stride == z_stride && vfb->depthBindSeq > maxSeq) { - maxSeq = vfb->depthBindSeq; - latestDepth = vfb; - } - } - return latestDepth; -} - void FramebufferManagerCommon::NotifyRenderFramebufferCreated(VirtualFramebuffer *vfb) { if (!useBufferedRendering_) { // Let's ignore rendering to targets that have not (yet) been displayed. @@ -702,12 +688,6 @@ void FramebufferManagerCommon::NotifyRenderFramebufferSwitched(VirtualFramebuffe textureCache_->ForgetLastTexture(); shaderManager_->DirtyLastShader(); - if (!isClearingDepth) { - // TODO: We should do this as part of the bind below. Then we can optimize the RPAction properly, - // and also do the copies using raster. - CopyToDepthFromOverlappingFramebuffers(vfb); - } - if (vfb->drawnFormat != vfb->format) { ReinterpretFramebuffer(vfb, vfb->drawnFormat, vfb->format); } @@ -2355,6 +2335,7 @@ void FramebufferManagerCommon::DeviceLost() { DoRelease(draw2DVs_); DoRelease(draw2DPipelineColor_); DoRelease(draw2DPipelineDepth_); + DoRelease(draw2DPipeline565ToDepth_); draw_ = nullptr; } @@ -2412,7 +2393,7 @@ void FramebufferManagerCommon::DrawActiveTexture(float x, float y, float w, floa // Rearrange to strip form. std::swap(coord[2], coord[3]); - DrawStrip2D(nullptr, coord, 4, (flags & DRAWTEX_LINEAR) != 0, RASTER_COLOR); + DrawStrip2D(nullptr, coord, 4, (flags & DRAWTEX_LINEAR) != 0, DRAW2D_COPY_COLOR); gstate_c.Dirty(DIRTY_BLEND_STATE | DIRTY_RASTER_STATE | DIRTY_DEPTHSTENCIL_STATE | DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_TEXTURE_IMAGE | DIRTY_TEXTURE_PARAMS | DIRTY_VERTEXSHADER_STATE | DIRTY_FRAGMENTSHADER_STATE); } @@ -2508,13 +2489,14 @@ void FramebufferManagerCommon::BlitFramebuffer(VirtualFramebuffer *dst, int dstX draw_->BlitFramebuffer(src->fbo, srcX1, srcY1, srcX2, srcY2, dst->fbo, dstX1, dstY1, dstX2, dstY2, channel == RASTER_COLOR ? Draw::FB_COLOR_BIT : Draw::FB_DEPTH_BIT, Draw::FB_BLIT_NEAREST, tag); } else { + Draw2DShader shader = channel == RASTER_COLOR ? DRAW2D_COPY_COLOR : DRAW2D_COPY_DEPTH; Draw::Framebuffer *srcFBO = src->fbo; if (src == dst) { Draw::Framebuffer *tempFBO = GetTempFBO(TempFBO::BLIT, src->renderWidth, src->renderHeight); - BlitUsingRaster(src->fbo, srcX1, srcY1, srcX2, srcY2, tempFBO, dstX1, dstY1, dstX2, dstY2, false, channel); + BlitUsingRaster(src->fbo, srcX1, srcY1, srcX2, srcY2, tempFBO, dstX1, dstY1, dstX2, dstY2, false, shader, tag); srcFBO = tempFBO; } - BlitUsingRaster(srcFBO, srcX1, srcY1, srcX2, srcY2, dst->fbo, dstX1, dstY1, dstX2, dstY2, false, channel); + BlitUsingRaster(srcFBO, srcX1, srcY1, srcX2, srcY2, dst->fbo, dstX1, dstY1, dstX2, dstY2, false, shader, tag); } draw_->InvalidateCachedState(); @@ -2526,9 +2508,9 @@ void FramebufferManagerCommon::BlitUsingRaster( Draw::Framebuffer *src, float srcX1, float srcY1, float srcX2, float srcY2, Draw::Framebuffer *dest, float destX1, float destY1, float destX2, float destY2, bool linearFilter, - RasterChannel channel) { + Draw2DShader shader, const char *tag) { - if (channel == RASTER_DEPTH) { + if (shader == DRAW2D_COPY_DEPTH || shader == DRAW2D_565_TO_DEPTH) { _dbg_assert_(draw_->GetDeviceCaps().fragmentShaderDepthWriteSupported); } @@ -2550,13 +2532,13 @@ void FramebufferManagerCommon::BlitUsingRaster( // Unbind the texture first to avoid the D3D11 hazard check (can't set render target to things bound as textures and vice versa, not even temporarily). draw_->BindTexture(0, nullptr); // This will get optimized away in case it's already bound (in VK and GL at least..) - draw_->BindFramebufferAsRenderTarget(dest, { Draw::RPAction::KEEP, Draw::RPAction::KEEP, Draw::RPAction::KEEP }, "BlitUsingRaster"); - draw_->BindFramebufferAsTexture(src, 0, channel == RASTER_COLOR ? Draw::FB_COLOR_BIT : Draw::FB_DEPTH_BIT, 0); + draw_->BindFramebufferAsRenderTarget(dest, { Draw::RPAction::KEEP, Draw::RPAction::KEEP, Draw::RPAction::KEEP }, tag ? tag : "BlitUsingRaster"); + draw_->BindFramebufferAsTexture(src, 0, Draw2DSourceChannel(shader) == RASTER_COLOR ? Draw::FB_COLOR_BIT : Draw::FB_DEPTH_BIT, 0); Draw::Viewport vp{ 0.0f, 0.0f, (float)dest->Width(), (float)dest->Height(), 0.0f, 1.0f }; draw_->SetViewports(1, &vp); draw_->SetScissorRect(0, 0, (int)dest->Width(), (int)dest->Height()); - DrawStrip2D(nullptr, vtx, 4, linearFilter, channel); + DrawStrip2D(nullptr, vtx, 4, linearFilter, shader); gstate_c.Dirty(DIRTY_BLEND_STATE | DIRTY_DEPTHSTENCIL_STATE | DIRTY_RASTER_STATE | DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_VERTEXSHADER_STATE | DIRTY_FRAGMENTSHADER_STATE); } diff --git a/GPU/Common/FramebufferManagerCommon.h b/GPU/Common/FramebufferManagerCommon.h index 901e821590..7fca956632 100644 --- a/GPU/Common/FramebufferManagerCommon.h +++ b/GPU/Common/FramebufferManagerCommon.h @@ -290,8 +290,6 @@ public: void DownloadFramebufferForClut(u32 fb_address, u32 loadBytes); void DrawFramebufferToOutput(const u8 *srcPixels, GEBufferFormat srcPixelFormat, int srcStride); - VirtualFramebuffer *GetLatestDepthBufferAt(u32 z_address, u16 z_stride); - void DrawPixels(VirtualFramebuffer *vfb, int dstX, int dstY, const u8 *srcPixels, GEBufferFormat srcPixelFormat, int srcStride, int width, int height); size_t NumVFBs() const { return vfbs_.size(); } @@ -382,7 +380,7 @@ protected: Draw::Texture *MakePixelTexture(const u8 *srcPixels, GEBufferFormat srcPixelFormat, int srcStride, int width, int height); void DrawActiveTexture(float x, float y, float w, float h, float destW, float destH, float u0, float v0, float u1, float v1, int uvRotation, int flags); - void DrawStrip2D(Draw::Texture *tex, Draw2DVertex *verts, int vertexCount, bool linearFilter, RasterChannel channel); + void DrawStrip2D(Draw::Texture *tex, Draw2DVertex *verts, int vertexCount, bool linearFilter, Draw2DShader channel); void Ensure2DResources(); Draw::Pipeline *Create2DPipeline(RasterChannel (*generate)(ShaderWriter &)); @@ -398,7 +396,7 @@ protected: void BlitUsingRaster( Draw::Framebuffer *src, float srcX1, float srcY1, float srcX2, float srcY2, - Draw::Framebuffer *dest, float destX1, float destY1, float destX2, float destY2, bool linearFilter, RasterChannel channel); + Draw::Framebuffer *dest, float destX1, float destY1, float destX2, float destY2, bool linearFilter, Draw2DShader shader, const char *tag); void CopyFramebufferForColorTexture(VirtualFramebuffer *dst, VirtualFramebuffer *src, int flags); @@ -517,6 +515,7 @@ protected: // Draw2D pipelines Draw::Pipeline *draw2DPipelineColor_ = nullptr; Draw::Pipeline *draw2DPipelineDepth_ = nullptr; + Draw::Pipeline *draw2DPipeline565ToDepth_ = nullptr; Draw::SamplerState *draw2DSamplerLinear_ = nullptr; Draw::SamplerState *draw2DSamplerNearest_ = nullptr; Draw::ShaderModule *draw2DVs_ = nullptr; From 97dbba0ec301fd5f003844e13e1252126c5172e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Wed, 17 Aug 2022 19:55:19 +0200 Subject: [PATCH 24/85] Minor fixes. Everything seems fine now. --- GPU/Common/Draw2D.cpp | 10 ++++------ GPU/Common/FramebufferManagerCommon.cpp | 18 ++++++++++-------- GPU/Common/FramebufferManagerCommon.h | 3 ++- GPU/Common/TextureCacheCommon.cpp | 8 +------- GPU/Common/TextureCacheCommon.h | 12 ++++++------ 5 files changed, 23 insertions(+), 28 deletions(-) diff --git a/GPU/Common/Draw2D.cpp b/GPU/Common/Draw2D.cpp index d9d0c5bc93..a6b4abb68c 100644 --- a/GPU/Common/Draw2D.cpp +++ b/GPU/Common/Draw2D.cpp @@ -67,12 +67,8 @@ RasterChannel GenerateDraw2D565ToDepthFs(ShaderWriter &writer) { // have to apply the scaling. DepthScaleFactors factors = GetDepthScaleFactors(); writer.C(" vec3 rgb = ").SampleTexture2D("tex", "v_texcoord.xy").C(".xyz;\n"); - writer.F(" highp float depthValue = (floor(rgb.x * 31.99) + floor(rgb.y * 63.99) * 32.0 + floor(rgb.z * 31.99) * 2048.0) / 65535.0; \n"); - if (factors.scale != 1.0 || factors.offset != 0.0) { - writer.F(" gl_FragDepth = (depthValue / %f) + %f;\n", factors.scale / 65535.0f, factors.offset); - } else { - writer.C(" gl_FragDepth = depthValue;\n"); - } + writer.F(" highp float depthValue = (floor(rgb.x * 31.99) + floor(rgb.y * 63.99) * 32.0 + floor(rgb.z * 31.99) * 2048.0); \n"); + writer.F(" gl_FragDepth = (depthValue / %f) + %f;\n", factors.scale, factors.offset); writer.EndFSMain("outColor", FSFLAG_WRITEDEPTH); return RASTER_DEPTH; } @@ -200,6 +196,7 @@ void FramebufferManagerCommon::DrawStrip2D(Draw::Texture *tex, Draw2DVertex *ver } if (!draw2DPipelineDepth_) { draw2DPipelineDepth_ = Create2DPipeline(&GenerateDraw2DDepthFs); + linearFilter = false; } draw_->BindPipeline(draw2DPipelineDepth_); break; @@ -211,6 +208,7 @@ void FramebufferManagerCommon::DrawStrip2D(Draw::Texture *tex, Draw2DVertex *ver } if (!draw2DPipeline565ToDepth_) { draw2DPipeline565ToDepth_ = Create2DPipeline(&GenerateDraw2D565ToDepthFs); + linearFilter = false; } draw_->BindPipeline(draw2DPipeline565ToDepth_); break; diff --git a/GPU/Common/FramebufferManagerCommon.cpp b/GPU/Common/FramebufferManagerCommon.cpp index b07bb171ba..df2e09514c 100644 --- a/GPU/Common/FramebufferManagerCommon.cpp +++ b/GPU/Common/FramebufferManagerCommon.cpp @@ -405,7 +405,7 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame vfb->lastFrameNewSize = gpuStats.numFlips; vfb->format = params.fmt; vfb->drawnFormat = params.fmt; - vfb->usageFlags = FB_USAGE_RENDERTARGET; + vfb->usageFlags = FB_USAGE_RENDER_COLOR; u32 byteSize = ColorBufferByteSize(vfb); if (Memory::IsVRAMAddress(params.fb_address) && params.fb_address + byteSize > framebufRangeEnd_) { @@ -454,7 +454,7 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame } else if (vfbs_[i]->z_stride != 0 && params.z_address == vfbs_[i]->z_address && params.fb_address != vfbs_[i]->fb_address && !sharingReported) { // This happens a lot, but virtually always it's cleared. // It's possible the other might not clear, but when every game is reported it's not useful. - if (params.isWritingDepth) { + if (params.isWritingDepth && (vfbs_[i]->usageFlags & FB_USAGE_RENDER_DEPTH)) { WARN_LOG(SCEGE, "FBO reusing depthbuffer, c=%08x/d=%08x and c=%08x/d=%08x", params.fb_address, params.z_address, vfbs_[i]->fb_address, vfbs_[i]->z_address); sharingReported = true; } @@ -465,7 +465,7 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame } else if (vfb != currentRenderVfb_) { // Use it as a render target. DEBUG_LOG(FRAMEBUF, "Switching render target to FBO for %08x: %d x %d x %d ", vfb->fb_address, vfb->width, vfb->height, vfb->format); - vfb->usageFlags |= FB_USAGE_RENDERTARGET; + vfb->usageFlags |= FB_USAGE_RENDER_COLOR; vfb->last_frame_render = gpuStats.numFlips; frameLastFramebufUsed_ = gpuStats.numFlips; vfb->dirtyAfterDisplay = true; @@ -505,6 +505,7 @@ void FramebufferManagerCommon::SetDepthFrameBuffer() { // "Resolve" the depth buffer, by copying from any overlapping buffers with fresher content. CopyToDepthFromOverlappingFramebuffers(currentRenderVfb_); + currentRenderVfb_->usageFlags |= FB_USAGE_RENDER_DEPTH; currentRenderVfb_->depthBindSeq = GetBindSeqCount(); } @@ -523,16 +524,17 @@ void FramebufferManagerCommon::CopyToDepthFromOverlappingFramebuffers(VirtualFra }; std::vector sources; - for (auto src: vfbs_) { + for (auto src : vfbs_) { if (src == dest) continue; if (src->fb_address == dest->z_address && src->fb_stride == dest->z_stride && src->format == GE_FORMAT_565) { - if (src->colorBindSeq < dest->depthBindSeq) { + if (src->colorBindSeq > dest->depthBindSeq) { // Source has newer data than the current buffer, use it. sources.push_back(CopySource{ src, RASTER_COLOR }); } } else if (src->z_address == dest->z_address && src->z_stride == dest->z_stride && src->depthBindSeq > dest->depthBindSeq) { + // Don't bother if the buffer was from another frame. This heuristic is old. sources.push_back(CopySource{ src, RASTER_DEPTH }); } else { // TODO: Do more detailed overlap checks here. @@ -1572,7 +1574,7 @@ VirtualFramebuffer *FramebufferManagerCommon::CreateRAMFramebuffer(uint32_t fbAd vfb->bufferHeight = vfb->height; vfb->format = format; vfb->drawnFormat = GE_FORMAT_8888; - vfb->usageFlags = FB_USAGE_RENDERTARGET; + vfb->usageFlags = FB_USAGE_RENDER_COLOR; SetColorUpdated(vfb, 0); char name[64]; snprintf(name, sizeof(name), "%08x_color_RAM", vfb->fb_address); @@ -1640,7 +1642,7 @@ VirtualFramebuffer *FramebufferManagerCommon::FindDownloadTempBuffer(VirtualFram UpdateDownloadTempBuffer(nvfb); } - nvfb->usageFlags |= FB_USAGE_RENDERTARGET; + nvfb->usageFlags |= FB_USAGE_RENDER_COLOR; nvfb->last_frame_render = gpuStats.numFlips; nvfb->dirtyAfterDisplay = true; @@ -1957,7 +1959,7 @@ void FramebufferManagerCommon::UpdateFramebufUsage(VirtualFramebuffer *vfb) { checkFlag(FB_USAGE_DISPLAYED_FRAMEBUFFER, vfb->last_frame_displayed); checkFlag(FB_USAGE_TEXTURE, vfb->last_frame_used); - checkFlag(FB_USAGE_RENDERTARGET, vfb->last_frame_render); + checkFlag(FB_USAGE_RENDER_COLOR, vfb->last_frame_render); checkFlag(FB_USAGE_CLUT, vfb->last_frame_clut); } diff --git a/GPU/Common/FramebufferManagerCommon.h b/GPU/Common/FramebufferManagerCommon.h index 7fca956632..13a1fd57d8 100644 --- a/GPU/Common/FramebufferManagerCommon.h +++ b/GPU/Common/FramebufferManagerCommon.h @@ -37,13 +37,14 @@ enum { FB_USAGE_DISPLAYED_FRAMEBUFFER = 1, - FB_USAGE_RENDERTARGET = 2, + FB_USAGE_RENDER_COLOR = 2, FB_USAGE_TEXTURE = 4, FB_USAGE_CLUT = 8, FB_USAGE_DOWNLOAD = 16, FB_USAGE_DOWNLOAD_CLEAR = 32, FB_USAGE_BLUE_TO_ALPHA = 64, FB_USAGE_FIRST_FRAME_SAVED = 128, + FB_USAGE_RENDER_DEPTH = 256, }; enum { diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index 488aa86d30..014b8feb3a 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -106,13 +106,7 @@ inline int dimHeight(u16 dim) { // Vulkan color formats: // TODO TextureCacheCommon::TextureCacheCommon(Draw::DrawContext *draw) - : draw_(draw), - clutLastFormat_(0xFFFFFFFF), - clutTotalBytes_(0), - clutMaxBytes_(0), - clutRenderAddress_(0xFFFFFFFF), - clutAlphaLinear_(false), - isBgraBackend_(false) { + : draw_(draw) { decimationCounter_ = TEXCACHE_DECIMATION_INTERVAL; // TODO: Clamp down to 256/1KB? Need to check mipmapShareClut and clamp loadclut. diff --git a/GPU/Common/TextureCacheCommon.h b/GPU/Common/TextureCacheCommon.h index a8b48878e2..12f0d64213 100644 --- a/GPU/Common/TextureCacheCommon.h +++ b/GPU/Common/TextureCacheCommon.h @@ -444,13 +444,13 @@ protected: u32 *clutBufConverted_; // This is the active one. u32 *clutBuf_; - u32 clutLastFormat_; - u32 clutTotalBytes_; - u32 clutMaxBytes_; - u32 clutRenderAddress_; + u32 clutLastFormat_ = 0xFFFFFFFF; + u32 clutTotalBytes_ = 0; + u32 clutMaxBytes_ = 0; + u32 clutRenderAddress_ = 0xFFFFFFFF; u32 clutRenderOffset_; // True if the clut is just alpha values in the same order (RGBA4444-bit only.) - bool clutAlphaLinear_; + bool clutAlphaLinear_ = false; u16 clutAlphaLinearColor_; int standardScaleFactor_; @@ -461,7 +461,7 @@ protected: bool nextNeedsChange_; bool nextNeedsRebuild_; - bool isBgraBackend_; + bool isBgraBackend_ = false; u32 expandClut_[256]; }; From 12db0e52d4d3d955c930bbdb942048a1d4cbb21d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Thu, 18 Aug 2022 09:38:17 +0200 Subject: [PATCH 25/85] Fix deferred-depth for bezier/spline. Move updating of last_frame_depth_render to GPUCommon. --- GPU/Common/FramebufferManagerCommon.cpp | 2 +- GPU/Common/FramebufferManagerCommon.h | 6 ----- GPU/D3D11/DrawEngineD3D11.cpp | 3 --- GPU/D3D11/StateMappingD3D11.cpp | 6 ----- GPU/Directx9/DrawEngineDX9.cpp | 3 --- GPU/Directx9/StateMappingDX9.cpp | 6 ----- GPU/GLES/DrawEngineGLES.cpp | 3 --- GPU/GLES/StateMappingGLES.cpp | 6 ----- GPU/GPUCommon.cpp | 33 ++++++++++++++++--------- GPU/GPUCommon.h | 17 +++++++------ GPU/Vulkan/FramebufferManagerVulkan.cpp | 3 --- GPU/Vulkan/StateMappingVulkan.cpp | 6 ----- 12 files changed, 33 insertions(+), 61 deletions(-) diff --git a/GPU/Common/FramebufferManagerCommon.cpp b/GPU/Common/FramebufferManagerCommon.cpp index df2e09514c..7c2159146c 100644 --- a/GPU/Common/FramebufferManagerCommon.cpp +++ b/GPU/Common/FramebufferManagerCommon.cpp @@ -317,7 +317,7 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame } break; } else if (v->fb_stride == params.fb_stride && v->format == params.fmt) { - u32 v_fb_first_line_end_ptr = v->fb_address + v->fb_stride * 4; // This should be * bpp, but leaving like this until after 1.13 to be safe. The God of War games use this for shadows. + u32 v_fb_first_line_end_ptr = v->fb_address + v->fb_stride * bpp; u32 v_fb_end_ptr = v->fb_address + v->fb_stride * v->height * bpp; if (params.fb_address > v->fb_address && params.fb_address < v_fb_first_line_end_ptr) { diff --git a/GPU/Common/FramebufferManagerCommon.h b/GPU/Common/FramebufferManagerCommon.h index 13a1fd57d8..3acff211dd 100644 --- a/GPU/Common/FramebufferManagerCommon.h +++ b/GPU/Common/FramebufferManagerCommon.h @@ -343,12 +343,6 @@ public: int GetTargetStride() const { return currentRenderVfb_ ? currentRenderVfb_->fb_stride : 512; } GEBufferFormat GetTargetFormat() const { return currentRenderVfb_ ? currentRenderVfb_->format : displayFormat_; } - void SetDepthUpdated() { - if (currentRenderVfb_) { - currentRenderVfb_->last_frame_depth_render = gpuStats.numFlips; - currentRenderVfb_->last_frame_depth_updated = gpuStats.numFlips; - } - } void SetColorUpdated(int skipDrawReason) { if (currentRenderVfb_) { SetColorUpdated(currentRenderVfb_, skipDrawReason); diff --git a/GPU/D3D11/DrawEngineD3D11.cpp b/GPU/D3D11/DrawEngineD3D11.cpp index 6bc808ef6a..91a4dda0d3 100644 --- a/GPU/D3D11/DrawEngineD3D11.cpp +++ b/GPU/D3D11/DrawEngineD3D11.cpp @@ -693,9 +693,6 @@ rotateVBO: if (gstate.isClearModeAlphaMask()) clearFlag |= Draw::FBChannel::FB_STENCIL_BIT; if (gstate.isClearModeDepthMask()) clearFlag |= Draw::FBChannel::FB_DEPTH_BIT; - if (clearFlag & Draw::FBChannel::FB_DEPTH_BIT) { - framebufferManager_->SetDepthUpdated(); - } if (clearFlag & Draw::FBChannel::FB_COLOR_BIT) { framebufferManager_->SetColorUpdated(gstate_c.skipDrawReason); } diff --git a/GPU/D3D11/StateMappingD3D11.cpp b/GPU/D3D11/StateMappingD3D11.cpp index da9ec068e6..0cbc600ebc 100644 --- a/GPU/D3D11/StateMappingD3D11.cpp +++ b/GPU/D3D11/StateMappingD3D11.cpp @@ -298,9 +298,6 @@ void DrawEngineD3D11::ApplyDrawState(int prim) { keys_.depthStencil.depthTestEnable = true; keys_.depthStencil.depthCompareOp = D3D11_COMPARISON_ALWAYS; keys_.depthStencil.depthWriteEnable = gstate.isClearModeDepthMask(); - if (gstate.isClearModeDepthMask()) { - framebufferManager_->SetDepthUpdated(); - } // Stencil Test bool alphaMask = gstate.isClearModeAlphaMask(); @@ -329,9 +326,6 @@ void DrawEngineD3D11::ApplyDrawState(int prim) { keys_.depthStencil.depthTestEnable = true; keys_.depthStencil.depthCompareOp = compareOps[gstate.getDepthTestFunction()]; keys_.depthStencil.depthWriteEnable = gstate.isDepthWriteEnabled(); - if (gstate.isDepthWriteEnabled()) { - framebufferManager_->SetDepthUpdated(); - } } else { keys_.depthStencil.depthTestEnable = false; keys_.depthStencil.depthWriteEnable = false; diff --git a/GPU/Directx9/DrawEngineDX9.cpp b/GPU/Directx9/DrawEngineDX9.cpp index ffad2bd469..889e08387c 100644 --- a/GPU/Directx9/DrawEngineDX9.cpp +++ b/GPU/Directx9/DrawEngineDX9.cpp @@ -640,9 +640,6 @@ rotateVBO: if (gstate.isClearModeAlphaMask()) mask |= D3DCLEAR_STENCIL; if (gstate.isClearModeDepthMask()) mask |= D3DCLEAR_ZBUFFER; - if (mask & D3DCLEAR_ZBUFFER) { - framebufferManager_->SetDepthUpdated(); - } if (mask & D3DCLEAR_TARGET) { framebufferManager_->SetColorUpdated(gstate_c.skipDrawReason); } diff --git a/GPU/Directx9/StateMappingDX9.cpp b/GPU/Directx9/StateMappingDX9.cpp index 3d06b380e0..828f9d4b4d 100644 --- a/GPU/Directx9/StateMappingDX9.cpp +++ b/GPU/Directx9/StateMappingDX9.cpp @@ -216,9 +216,6 @@ void DrawEngineDX9::ApplyDrawState(int prim) { dxstate.depthTest.enable(); dxstate.depthFunc.set(D3DCMP_ALWAYS); dxstate.depthWrite.set(gstate.isClearModeDepthMask()); - if (gstate.isClearModeDepthMask()) { - framebufferManager_->SetDepthUpdated(); - } // Stencil Test bool alphaMask = gstate.isClearModeAlphaMask(); @@ -239,9 +236,6 @@ void DrawEngineDX9::ApplyDrawState(int prim) { dxstate.depthTest.enable(); dxstate.depthFunc.set(ztests[gstate.getDepthTestFunction()]); dxstate.depthWrite.set(gstate.isDepthWriteEnabled()); - if (gstate.isDepthWriteEnabled()) { - framebufferManager_->SetDepthUpdated(); - } } else { dxstate.depthTest.disable(); } diff --git a/GPU/GLES/DrawEngineGLES.cpp b/GPU/GLES/DrawEngineGLES.cpp index ab0960abd5..6610fcde6a 100644 --- a/GPU/GLES/DrawEngineGLES.cpp +++ b/GPU/GLES/DrawEngineGLES.cpp @@ -423,9 +423,6 @@ void DrawEngineGLES::DoFlush() { bool colorMask = gstate.isClearModeColorMask(); bool alphaMask = gstate.isClearModeAlphaMask(); bool depthMask = gstate.isClearModeDepthMask(); - if (depthMask) { - framebufferManager_->SetDepthUpdated(); - } GLbitfield target = 0; // Without this, we will clear RGB when clearing stencil, which breaks games. diff --git a/GPU/GLES/StateMappingGLES.cpp b/GPU/GLES/StateMappingGLES.cpp index 6e498875f1..35f9329629 100644 --- a/GPU/GLES/StateMappingGLES.cpp +++ b/GPU/GLES/StateMappingGLES.cpp @@ -253,18 +253,12 @@ void DrawEngineGLES::ApplyDrawState(int prim) { if (gstate.isModeClear()) { // Depth Test - if (gstate.isClearModeDepthMask()) { - framebufferManager_->SetDepthUpdated(); - } renderManager->SetStencilFunc(gstate.isClearModeAlphaMask(), GL_ALWAYS, 0xFF, 0xFF); renderManager->SetStencilOp(stencilState.writeMask, GL_REPLACE, GL_REPLACE, GL_REPLACE); renderManager->SetDepth(true, gstate.isClearModeDepthMask() ? true : false, GL_ALWAYS); } else { // Depth Test renderManager->SetDepth(gstate.isDepthTestEnabled(), gstate.isDepthWriteEnabled(), compareOps[gstate.getDepthTestFunction()]); - if (gstate.isDepthTestEnabled() && gstate.isDepthWriteEnabled()) { - framebufferManager_->SetDepthUpdated(); - } // Stencil Test if (stencilState.enabled) { diff --git a/GPU/GPUCommon.cpp b/GPU/GPUCommon.cpp index d751291a9b..14c4cf1f5e 100644 --- a/GPU/GPUCommon.cpp +++ b/GPU/GPUCommon.cpp @@ -1624,6 +1624,21 @@ void GPUCommon::Execute_VertexTypeSkinning(u32 op, u32 diff) { gstate_c.Dirty(DIRTY_RASTER_STATE | DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_FRAGMENTSHADER_STATE | DIRTY_CULLRANGE); } +void GPUCommon::CheckDepthUsage(VirtualFramebuffer *vfb) { + if (!gstate_c.usingDepth) { + bool isClearingDepth = gstate.isModeClear() && gstate.isClearModeDepthMask(); + + if ((gstate.isDepthTestEnabled() || isClearingDepth)) { + gstate_c.usingDepth = true; + gstate_c.clearingDepth = isClearingDepth; + vfb->last_frame_depth_render = gpuStats.numFlips; + if (isClearingDepth || gstate.isDepthWriteEnabled()) { + vfb->last_frame_depth_updated = gpuStats.numFlips; + } + framebufferManager_->SetDepthFrameBuffer(); + } + } +} void GPUCommon::Execute_Prim(u32 op, u32 diff) { // This drives all drawing. All other state we just buffer up, then we apply it only @@ -1685,15 +1700,7 @@ void GPUCommon::Execute_Prim(u32 op, u32 diff) { return; } - if (!gstate_c.usingDepth) { - bool isClearingDepth = gstate.isModeClear() && gstate.isClearModeDepthMask();; - - if ((gstate.isDepthTestEnabled() || isClearingDepth)) { - gstate_c.usingDepth = true; - gstate_c.clearingDepth = isClearingDepth; - framebufferManager_->SetDepthFrameBuffer(); - } - } + CheckDepthUsage(vfb); const void *verts = Memory::GetPointerUnchecked(gstate_c.vertexAddr); const void *inds = nullptr; @@ -1893,12 +1900,14 @@ void GPUCommon::Execute_Bezier(u32 op, u32 diff) { gstate_c.framebufFormat = gstate.FrameBufFormat(); // This also make skipping drawing very effective. - framebufferManager_->SetRenderFrameBuffer(gstate_c.IsDirty(DIRTY_FRAMEBUF), gstate_c.skipDrawReason); + VirtualFramebuffer *vfb = framebufferManager_->SetRenderFrameBuffer(gstate_c.IsDirty(DIRTY_FRAMEBUF), gstate_c.skipDrawReason); if (gstate_c.skipDrawReason & (SKIPDRAW_SKIPFRAME | SKIPDRAW_NON_DISPLAYED_FB)) { // TODO: Should this eat some cycles? Probably yes. Not sure if important. return; } + CheckDepthUsage(vfb); + if (!Memory::IsValidAddress(gstate_c.vertexAddr)) { ERROR_LOG_REPORT(G3D, "Bad vertex address %08x!", gstate_c.vertexAddr); return; @@ -1963,12 +1972,14 @@ void GPUCommon::Execute_Spline(u32 op, u32 diff) { gstate_c.framebufFormat = gstate.FrameBufFormat(); // This also make skipping drawing very effective. - framebufferManager_->SetRenderFrameBuffer(gstate_c.IsDirty(DIRTY_FRAMEBUF), gstate_c.skipDrawReason); + VirtualFramebuffer *vfb = framebufferManager_->SetRenderFrameBuffer(gstate_c.IsDirty(DIRTY_FRAMEBUF), gstate_c.skipDrawReason); if (gstate_c.skipDrawReason & (SKIPDRAW_SKIPFRAME | SKIPDRAW_NON_DISPLAYED_FB)) { // TODO: Should this eat some cycles? Probably yes. Not sure if important. return; } + CheckDepthUsage(vfb); + if (!Memory::IsValidAddress(gstate_c.vertexAddr)) { ERROR_LOG_REPORT(G3D, "Bad vertex address %08x!", gstate_c.vertexAddr); return; diff --git a/GPU/GPUCommon.h b/GPU/GPUCommon.h index 59298d8e92..e61d5dada9 100644 --- a/GPU/GPUCommon.h +++ b/GPU/GPUCommon.h @@ -15,6 +15,8 @@ class FramebufferManagerCommon; class TextureCacheCommon; class DrawEngineCommon; class GraphicsContext; +struct VirtualFramebuffer; + namespace Draw { class DrawContext; } @@ -282,17 +284,11 @@ protected: void SlowRunLoop(DisplayList &list); void UpdatePC(u32 currentPC, u32 newPC); void UpdateState(GPURunState state); - void PopDLQueue(); - void CheckDrawSync(); - int GetNextListIndex(); - virtual void FastLoadBoneMatrix(u32 target); + void FastLoadBoneMatrix(u32 target); // TODO: Unify this. virtual void FinishDeferred() {} - void DoBlockTransfer(u32 skipDrawReason); - void DoExecuteCall(u32 target); - void AdvanceVerts(u32 vertType, int count, int bytesRead) { if ((vertType & GE_VTYPE_IDX_MASK) != GE_VTYPE_IDX_NONE) { int indexShift = ((vertType & GE_VTYPE_IDX_MASK) >> GE_VTYPE_IDX_SHIFT) - 1; @@ -362,6 +358,13 @@ protected: private: void FlushImm(); + void CheckDepthUsage(VirtualFramebuffer *vfb); + void DoBlockTransfer(u32 skipDrawReason); + void DoExecuteCall(u32 target); + void PopDLQueue(); + void CheckDrawSync(); + int GetNextListIndex(); + // Debug stats. double timeSteppingStarted_; double timeSpentStepping_; diff --git a/GPU/Vulkan/FramebufferManagerVulkan.cpp b/GPU/Vulkan/FramebufferManagerVulkan.cpp index 7748f24371..7061f68ae7 100644 --- a/GPU/Vulkan/FramebufferManagerVulkan.cpp +++ b/GPU/Vulkan/FramebufferManagerVulkan.cpp @@ -75,7 +75,4 @@ void FramebufferManagerVulkan::NotifyClear(bool clearColor, bool clearAlpha, boo if (clearColor || clearAlpha) { SetColorUpdated(gstate_c.skipDrawReason); } - if (clearDepth) { - SetDepthUpdated(); - } } diff --git a/GPU/Vulkan/StateMappingVulkan.cpp b/GPU/Vulkan/StateMappingVulkan.cpp index 166f3dc153..cb1f45aaca 100644 --- a/GPU/Vulkan/StateMappingVulkan.cpp +++ b/GPU/Vulkan/StateMappingVulkan.cpp @@ -254,9 +254,6 @@ void DrawEngineVulkan::ConvertStateToVulkanKey(FramebufferManagerVulkan &fbManag key.depthTestEnable = true; key.depthCompareOp = VK_COMPARE_OP_ALWAYS; key.depthWriteEnable = gstate.isClearModeDepthMask(); - if (gstate.isClearModeDepthMask()) { - fbManager.SetDepthUpdated(); - } // Stencil Test bool alphaMask = gstate.isClearModeAlphaMask(); @@ -287,9 +284,6 @@ void DrawEngineVulkan::ConvertStateToVulkanKey(FramebufferManagerVulkan &fbManag key.depthTestEnable = true; key.depthCompareOp = compareOps[gstate.getDepthTestFunction()]; key.depthWriteEnable = gstate.isDepthWriteEnabled(); - if (gstate.isDepthWriteEnabled()) { - fbManager.SetDepthUpdated(); - } } else { key.depthTestEnable = false; key.depthWriteEnable = false; From 29ea3ffe0c85a7d2bde037a304e0e4a836b240da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Sat, 20 Aug 2022 09:46:15 +0200 Subject: [PATCH 26/85] Restore the clearing optimization, avoiding unnecessary depth copies --- GPU/Common/FramebufferManagerCommon.cpp | 9 ++++++--- GPU/Common/FramebufferManagerCommon.h | 2 +- GPU/GPUCommon.cpp | 2 +- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/GPU/Common/FramebufferManagerCommon.cpp b/GPU/Common/FramebufferManagerCommon.cpp index 7c2159146c..308f1b7fd5 100644 --- a/GPU/Common/FramebufferManagerCommon.cpp +++ b/GPU/Common/FramebufferManagerCommon.cpp @@ -497,13 +497,16 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame } // Called on the first use of depth in a render pass. -void FramebufferManagerCommon::SetDepthFrameBuffer() { +void FramebufferManagerCommon::SetDepthFrameBuffer(bool isClearingDepth) { if (!currentRenderVfb_) { return; } - // "Resolve" the depth buffer, by copying from any overlapping buffers with fresher content. - CopyToDepthFromOverlappingFramebuffers(currentRenderVfb_); + // If this first draw call is anything other than a clear, "resolve" the depth buffer, + // by copying from any overlapping buffers with fresher content. + if (!isClearingDepth) { + CopyToDepthFromOverlappingFramebuffers(currentRenderVfb_); + } currentRenderVfb_->usageFlags |= FB_USAGE_RENDER_DEPTH; currentRenderVfb_->depthBindSeq = GetBindSeqCount(); diff --git a/GPU/Common/FramebufferManagerCommon.h b/GPU/Common/FramebufferManagerCommon.h index 3acff211dd..447554f376 100644 --- a/GPU/Common/FramebufferManagerCommon.h +++ b/GPU/Common/FramebufferManagerCommon.h @@ -267,7 +267,7 @@ public: return vfb; } } - void SetDepthFrameBuffer(); + void SetDepthFrameBuffer(bool isClearingDepth); void RebindFramebuffer(const char *tag); std::vector GetFramebufferList() const; diff --git a/GPU/GPUCommon.cpp b/GPU/GPUCommon.cpp index 14c4cf1f5e..7db2fd4b42 100644 --- a/GPU/GPUCommon.cpp +++ b/GPU/GPUCommon.cpp @@ -1635,7 +1635,7 @@ void GPUCommon::CheckDepthUsage(VirtualFramebuffer *vfb) { if (isClearingDepth || gstate.isDepthWriteEnabled()) { vfb->last_frame_depth_updated = gpuStats.numFlips; } - framebufferManager_->SetDepthFrameBuffer(); + framebufferManager_->SetDepthFrameBuffer(isClearingDepth); } } } From 5046cbd015de1dc081d7cbae0698468e8d516398 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Sat, 20 Aug 2022 17:23:51 +0200 Subject: [PATCH 27/85] Address feedback to PR #15858 --- GPU/Common/FramebufferManagerCommon.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/GPU/Common/FramebufferManagerCommon.cpp b/GPU/Common/FramebufferManagerCommon.cpp index 308f1b7fd5..a1164c686f 100644 --- a/GPU/Common/FramebufferManagerCommon.cpp +++ b/GPU/Common/FramebufferManagerCommon.cpp @@ -537,7 +537,6 @@ void FramebufferManagerCommon::CopyToDepthFromOverlappingFramebuffers(VirtualFra sources.push_back(CopySource{ src, RASTER_COLOR }); } } else if (src->z_address == dest->z_address && src->z_stride == dest->z_stride && src->depthBindSeq > dest->depthBindSeq) { - // Don't bother if the buffer was from another frame. This heuristic is old. sources.push_back(CopySource{ src, RASTER_DEPTH }); } else { // TODO: Do more detailed overlap checks here. @@ -562,6 +561,9 @@ void FramebufferManagerCommon::CopyToDepthFromOverlappingFramebuffers(VirtualFra } else if (source.channel == RASTER_COLOR) { VirtualFramebuffer *src = source.vfb; // Copying color to depth. + if (src->drawnFormat != GE_FORMAT_565) { + WARN_LOG_ONCE(not565, G3D, "Drawn format of buffer at %08x not 565 as expected", src->fb_address); + } BlitUsingRaster(src->fbo, 0.0f, 0.0f, src->renderWidth, src->renderHeight, dest->fbo, 0.0f, 0.0f, dest->renderWidth, dest->renderHeight, false, DRAW2D_565_TO_DEPTH, "565_to_depth"); } } From d61619db47308ad29f936df646275352b08f0e46 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sat, 20 Aug 2022 14:03:24 -0700 Subject: [PATCH 28/85] GPU: Dirty params when converting viewport state. This flag will be false when we convert next time, so parameters won't get updated as expected. --- GPU/D3D11/DrawEngineD3D11.cpp | 7 +++++++ GPU/Directx9/DrawEngineDX9.cpp | 7 +++++++ GPU/GLES/DrawEngineGLES.cpp | 7 +++++++ GPU/Vulkan/DrawEngineVulkan.cpp | 7 +++++++ 4 files changed, 28 insertions(+) diff --git a/GPU/D3D11/DrawEngineD3D11.cpp b/GPU/D3D11/DrawEngineD3D11.cpp index 91a4dda0d3..ec4240ce9a 100644 --- a/GPU/D3D11/DrawEngineD3D11.cpp +++ b/GPU/D3D11/DrawEngineD3D11.cpp @@ -617,6 +617,13 @@ rotateVBO: framebufferManager_->GetRenderWidth(), framebufferManager_->GetRenderHeight(), framebufferManager_->GetTargetBufferWidth(), framebufferManager_->GetTargetBufferHeight(), vpAndScissor); + + if (vpAndScissor.dirtyProj) { + gstate_c.Dirty(DIRTY_PROJMATRIX); + } + if (vpAndScissor.dirtyDepth) { + gstate_c.Dirty(DIRTY_DEPTHRANGE); + } } int maxIndex = indexGen.MaxIndex(); diff --git a/GPU/Directx9/DrawEngineDX9.cpp b/GPU/Directx9/DrawEngineDX9.cpp index 889e08387c..c206e0188c 100644 --- a/GPU/Directx9/DrawEngineDX9.cpp +++ b/GPU/Directx9/DrawEngineDX9.cpp @@ -582,6 +582,13 @@ rotateVBO: framebufferManager_->GetRenderWidth(), framebufferManager_->GetRenderHeight(), framebufferManager_->GetTargetBufferWidth(), framebufferManager_->GetTargetBufferHeight(), vpAndScissor); + + if (vpAndScissor.dirtyProj) { + gstate_c.Dirty(DIRTY_PROJMATRIX); + } + if (vpAndScissor.dirtyDepth) { + gstate_c.Dirty(DIRTY_DEPTHRANGE); + } } int maxIndex = indexGen.MaxIndex(); diff --git a/GPU/GLES/DrawEngineGLES.cpp b/GPU/GLES/DrawEngineGLES.cpp index 6610fcde6a..5ff37bf13a 100644 --- a/GPU/GLES/DrawEngineGLES.cpp +++ b/GPU/GLES/DrawEngineGLES.cpp @@ -364,6 +364,13 @@ void DrawEngineGLES::DoFlush() { framebufferManager_->GetRenderWidth(), framebufferManager_->GetRenderHeight(), framebufferManager_->GetTargetBufferWidth(), framebufferManager_->GetTargetBufferHeight(), vpAndScissor); + + if (vpAndScissor.dirtyProj) { + gstate_c.Dirty(DIRTY_PROJMATRIX); + } + if (vpAndScissor.dirtyDepth) { + gstate_c.Dirty(DIRTY_DEPTHRANGE); + } } int maxIndex = indexGen.MaxIndex(); diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index 7be943ed63..a29d9fc8ce 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -856,6 +856,13 @@ void DrawEngineVulkan::DoFlush() { framebufferManager_->GetRenderWidth(), framebufferManager_->GetRenderHeight(), framebufferManager_->GetTargetBufferWidth(), framebufferManager_->GetTargetBufferHeight(), vpAndScissor); + + if (vpAndScissor.dirtyProj) { + gstate_c.Dirty(DIRTY_PROJMATRIX); + } + if (vpAndScissor.dirtyDepth) { + gstate_c.Dirty(DIRTY_DEPTHRANGE); + } } int maxIndex = indexGen.MaxIndex(); From b5a4843c1fb06372bf14b5cb921d7c3e2b5b7607 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sat, 20 Aug 2022 14:16:55 -0700 Subject: [PATCH 29/85] GPU: Purify ConvertViewportAndScissor(). This makes it harder to misuse. See #15856. --- GPU/Common/GPUStateUtils.cpp | 62 +++++++++++++++++-------------- GPU/Common/GPUStateUtils.h | 10 ++++- GPU/D3D11/DrawEngineD3D11.cpp | 8 +--- GPU/D3D11/StateMappingD3D11.cpp | 8 +--- GPU/Directx9/DrawEngineDX9.cpp | 8 +--- GPU/Directx9/StateMappingDX9.cpp | 7 +--- GPU/GLES/DrawEngineGLES.cpp | 8 +--- GPU/GLES/StateMappingGLES.cpp | 8 +--- GPU/Vulkan/DrawEngineVulkan.cpp | 8 +--- GPU/Vulkan/StateMappingVulkan.cpp | 8 +--- 10 files changed, 50 insertions(+), 85 deletions(-) diff --git a/GPU/Common/GPUStateUtils.cpp b/GPU/Common/GPUStateUtils.cpp index 51f0e3f8eb..1272a0d7c0 100644 --- a/GPU/Common/GPUStateUtils.cpp +++ b/GPU/Common/GPUStateUtils.cpp @@ -557,9 +557,7 @@ DepthScaleFactors GetDepthScaleFactors() { } void ConvertViewportAndScissor(bool useBufferedRendering, float renderWidth, float renderHeight, int bufferWidth, int bufferHeight, ViewportAndScissor &out) { - bool throughmode = gstate.isModeThrough(); - out.dirtyProj = false; - out.dirtyDepth = false; + out.throughMode = gstate.isModeThrough(); float renderWidthFactor, renderHeightFactor; float renderX = 0.0f, renderY = 0.0f; @@ -610,7 +608,7 @@ void ConvertViewportAndScissor(bool useBufferedRendering, float renderWidth, flo float offsetX = gstate.getOffsetX(); float offsetY = gstate.getOffsetY(); - if (throughmode) { + if (out.throughMode) { out.viewportX = renderX * renderWidthFactor + displayOffsetX; out.viewportY = renderY * renderHeightFactor + displayOffsetY; out.viewportW = curRTWidth * renderWidthFactor; @@ -647,10 +645,10 @@ void ConvertViewportAndScissor(bool useBufferedRendering, float renderWidth, flo float right = left + vpWidth; float bottom = top + vpHeight; - float wScale = 1.0f; - float xOffset = 0.0f; - float hScale = 1.0f; - float yOffset = 0.0f; + out.widthScale = 1.0f; + out.xOffset = 0.0f; + out.heightScale = 1.0f; + out.yOffset = 0.0f; // If we're within the bounds, we want clipping the viewport way. So leave it be. { @@ -678,8 +676,8 @@ void ConvertViewportAndScissor(bool useBufferedRendering, float renderWidth, flo right = left + 1.0f; } - wScale = vpWidth / (right - left); - xOffset = drift / (right - left); + out.widthScale = vpWidth / (right - left); + out.xOffset = drift / (right - left); } } @@ -707,8 +705,8 @@ void ConvertViewportAndScissor(bool useBufferedRendering, float renderWidth, flo bottom = top + 1.0f; } - hScale = vpHeight / (bottom - top); - yOffset = drift / (bottom - top); + out.heightScale = vpHeight / (bottom - top); + out.yOffset = drift / (bottom - top); } } @@ -740,13 +738,13 @@ void ConvertViewportAndScissor(bool useBufferedRendering, float renderWidth, flo } // Okay. So, in our shader, -1 will map to minz, and +1 will map to maxz. float halfActualZRange = (maxz - minz) * (1.0f / 2.0f); - float zScale = halfActualZRange < std::numeric_limits::epsilon() ? 1.0f : vpZScale / halfActualZRange; + out.depthScale = halfActualZRange < std::numeric_limits::epsilon() ? 1.0f : vpZScale / halfActualZRange; // This adjusts the center from halfActualZRange to vpZCenter. - float zOffset = halfActualZRange < std::numeric_limits::epsilon() ? 0.0f : (vpZCenter - (minz + halfActualZRange)) / halfActualZRange; + out.zOffset = halfActualZRange < std::numeric_limits::epsilon() ? 0.0f : (vpZCenter - (minz + halfActualZRange)) / halfActualZRange; if (!gstate_c.Supports(GPU_SUPPORTS_ACCURATE_DEPTH)) { - zScale = 1.0f; - zOffset = 0.0f; + out.depthScale = 1.0f; + out.zOffset = 0.0f; out.depthRangeMin = ToScaledDepthFromIntegerScale(vpZCenter - vpZScale); out.depthRangeMax = ToScaledDepthFromIntegerScale(vpZCenter + vpZScale); } else { @@ -757,19 +755,27 @@ void ConvertViewportAndScissor(bool useBufferedRendering, float renderWidth, flo // OpenGL will clamp these for us anyway, and Direct3D will error if not clamped. out.depthRangeMin = std::max(out.depthRangeMin, 0.0f); out.depthRangeMax = std::min(out.depthRangeMax, 1.0f); + } +} - bool scaleChanged = gstate_c.vpWidthScale != wScale || gstate_c.vpHeightScale != hScale; - bool offsetChanged = gstate_c.vpXOffset != xOffset || gstate_c.vpYOffset != yOffset; - bool depthChanged = gstate_c.vpDepthScale != zScale || gstate_c.vpZOffset != zOffset; - if (scaleChanged || offsetChanged || depthChanged) { - gstate_c.vpWidthScale = wScale; - gstate_c.vpHeightScale = hScale; - gstate_c.vpDepthScale = zScale; - gstate_c.vpXOffset = xOffset; - gstate_c.vpYOffset = yOffset; - gstate_c.vpZOffset = zOffset; - out.dirtyProj = true; - out.dirtyDepth = depthChanged; +void UpdateCachedViewportState(const ViewportAndScissor &vpAndScissor) { + if (vpAndScissor.throughMode) + return; + + bool scaleChanged = gstate_c.vpWidthScale != vpAndScissor.widthScale || gstate_c.vpHeightScale != vpAndScissor.heightScale; + bool offsetChanged = gstate_c.vpXOffset != vpAndScissor.xOffset || gstate_c.vpYOffset != vpAndScissor.yOffset; + bool depthChanged = gstate_c.vpDepthScale != vpAndScissor.depthScale || gstate_c.vpZOffset != vpAndScissor.zOffset; + if (scaleChanged || offsetChanged || depthChanged) { + gstate_c.vpWidthScale = vpAndScissor.widthScale; + gstate_c.vpHeightScale = vpAndScissor.heightScale; + gstate_c.vpDepthScale = vpAndScissor.depthScale; + gstate_c.vpXOffset = vpAndScissor.xOffset; + gstate_c.vpYOffset = vpAndScissor.yOffset; + gstate_c.vpZOffset = vpAndScissor.zOffset; + + gstate_c.Dirty(DIRTY_PROJMATRIX); + if (depthChanged) { + gstate_c.Dirty(DIRTY_DEPTHRANGE); } } } diff --git a/GPU/Common/GPUStateUtils.h b/GPU/Common/GPUStateUtils.h index 956a71e7f6..41ee3adc73 100644 --- a/GPU/Common/GPUStateUtils.h +++ b/GPU/Common/GPUStateUtils.h @@ -75,10 +75,16 @@ struct ViewportAndScissor { float viewportH; float depthRangeMin; float depthRangeMax; - bool dirtyProj; - bool dirtyDepth; + float widthScale; + float heightScale; + float depthScale; + float xOffset; + float yOffset; + float zOffset; + bool throughMode; }; void ConvertViewportAndScissor(bool useBufferedRendering, float renderWidth, float renderHeight, int bufferWidth, int bufferHeight, ViewportAndScissor &out); +void UpdateCachedViewportState(const ViewportAndScissor &vpAndScissor); float ToScaledDepthFromIntegerScale(float z); struct DepthScaleFactors { diff --git a/GPU/D3D11/DrawEngineD3D11.cpp b/GPU/D3D11/DrawEngineD3D11.cpp index ec4240ce9a..eea3004b30 100644 --- a/GPU/D3D11/DrawEngineD3D11.cpp +++ b/GPU/D3D11/DrawEngineD3D11.cpp @@ -617,13 +617,7 @@ rotateVBO: framebufferManager_->GetRenderWidth(), framebufferManager_->GetRenderHeight(), framebufferManager_->GetTargetBufferWidth(), framebufferManager_->GetTargetBufferHeight(), vpAndScissor); - - if (vpAndScissor.dirtyProj) { - gstate_c.Dirty(DIRTY_PROJMATRIX); - } - if (vpAndScissor.dirtyDepth) { - gstate_c.Dirty(DIRTY_DEPTHRANGE); - } + UpdateCachedViewportState(vpAndScissor); } int maxIndex = indexGen.MaxIndex(); diff --git a/GPU/D3D11/StateMappingD3D11.cpp b/GPU/D3D11/StateMappingD3D11.cpp index 0cbc600ebc..11db65c553 100644 --- a/GPU/D3D11/StateMappingD3D11.cpp +++ b/GPU/D3D11/StateMappingD3D11.cpp @@ -374,15 +374,13 @@ void DrawEngineD3D11::ApplyDrawState(int prim) { framebufferManager_->GetRenderWidth(), framebufferManager_->GetRenderHeight(), framebufferManager_->GetTargetBufferWidth(), framebufferManager_->GetTargetBufferHeight(), vpAndScissor); + UpdateCachedViewportState(vpAndScissor); float depthMin = vpAndScissor.depthRangeMin; float depthMax = vpAndScissor.depthRangeMax; if (depthMin < 0.0f) depthMin = 0.0f; if (depthMax > 1.0f) depthMax = 1.0f; - if (vpAndScissor.dirtyDepth) { - gstate_c.Dirty(DIRTY_DEPTHRANGE); - } Draw::Viewport &vp = dynState_.viewport; vp.TopLeftX = vpAndScissor.viewportX; @@ -392,10 +390,6 @@ void DrawEngineD3D11::ApplyDrawState(int prim) { vp.MinDepth = depthMin; vp.MaxDepth = depthMax; - if (vpAndScissor.dirtyProj) { - gstate_c.Dirty(DIRTY_PROJMATRIX); - } - D3D11_RECT &scissor = dynState_.scissor; scissor.left = vpAndScissor.scissorX; scissor.top = vpAndScissor.scissorY; diff --git a/GPU/Directx9/DrawEngineDX9.cpp b/GPU/Directx9/DrawEngineDX9.cpp index c206e0188c..130ee36b8f 100644 --- a/GPU/Directx9/DrawEngineDX9.cpp +++ b/GPU/Directx9/DrawEngineDX9.cpp @@ -582,13 +582,7 @@ rotateVBO: framebufferManager_->GetRenderWidth(), framebufferManager_->GetRenderHeight(), framebufferManager_->GetTargetBufferWidth(), framebufferManager_->GetTargetBufferHeight(), vpAndScissor); - - if (vpAndScissor.dirtyProj) { - gstate_c.Dirty(DIRTY_PROJMATRIX); - } - if (vpAndScissor.dirtyDepth) { - gstate_c.Dirty(DIRTY_DEPTHRANGE); - } + UpdateCachedViewportState(vpAndScissor); } int maxIndex = indexGen.MaxIndex(); diff --git a/GPU/Directx9/StateMappingDX9.cpp b/GPU/Directx9/StateMappingDX9.cpp index 828f9d4b4d..9fb92db6fe 100644 --- a/GPU/Directx9/StateMappingDX9.cpp +++ b/GPU/Directx9/StateMappingDX9.cpp @@ -260,6 +260,7 @@ void DrawEngineDX9::ApplyDrawState(int prim) { framebufferManager_->GetRenderWidth(), framebufferManager_->GetRenderHeight(), framebufferManager_->GetTargetBufferWidth(), framebufferManager_->GetTargetBufferHeight(), vpAndScissor); + UpdateCachedViewportState(vpAndScissor); dxstate.scissorTest.enable(); dxstate.scissorRect.set(vpAndScissor.scissorX, vpAndScissor.scissorY, vpAndScissor.scissorX + vpAndScissor.scissorW, vpAndScissor.scissorY + vpAndScissor.scissorH); @@ -268,12 +269,6 @@ void DrawEngineDX9::ApplyDrawState(int prim) { float depthMax = vpAndScissor.depthRangeMax; dxstate.viewport.set(vpAndScissor.viewportX, vpAndScissor.viewportY, vpAndScissor.viewportW, vpAndScissor.viewportH, depthMin, depthMax); - if (vpAndScissor.dirtyProj) { - gstate_c.Dirty(DIRTY_PROJMATRIX); - } - if (vpAndScissor.dirtyDepth) { - gstate_c.Dirty(DIRTY_DEPTHRANGE); - } } gstate_c.Clean(DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_DEPTHSTENCIL_STATE | DIRTY_RASTER_STATE | DIRTY_BLEND_STATE); diff --git a/GPU/GLES/DrawEngineGLES.cpp b/GPU/GLES/DrawEngineGLES.cpp index 5ff37bf13a..96dc11ea22 100644 --- a/GPU/GLES/DrawEngineGLES.cpp +++ b/GPU/GLES/DrawEngineGLES.cpp @@ -364,13 +364,7 @@ void DrawEngineGLES::DoFlush() { framebufferManager_->GetRenderWidth(), framebufferManager_->GetRenderHeight(), framebufferManager_->GetTargetBufferWidth(), framebufferManager_->GetTargetBufferHeight(), vpAndScissor); - - if (vpAndScissor.dirtyProj) { - gstate_c.Dirty(DIRTY_PROJMATRIX); - } - if (vpAndScissor.dirtyDepth) { - gstate_c.Dirty(DIRTY_DEPTHRANGE); - } + UpdateCachedViewportState(vpAndScissor); } int maxIndex = indexGen.MaxIndex(); diff --git a/GPU/GLES/StateMappingGLES.cpp b/GPU/GLES/StateMappingGLES.cpp index 35f9329629..4ebdd165d2 100644 --- a/GPU/GLES/StateMappingGLES.cpp +++ b/GPU/GLES/StateMappingGLES.cpp @@ -276,19 +276,13 @@ void DrawEngineGLES::ApplyDrawState(int prim) { framebufferManager_->GetRenderWidth(), framebufferManager_->GetRenderHeight(), framebufferManager_->GetTargetBufferWidth(), framebufferManager_->GetTargetBufferHeight(), vpAndScissor); + UpdateCachedViewportState(vpAndScissor); renderManager->SetScissor(GLRect2D{ vpAndScissor.scissorX, vpAndScissor.scissorY, vpAndScissor.scissorW, vpAndScissor.scissorH }); renderManager->SetViewport({ vpAndScissor.viewportX, vpAndScissor.viewportY, vpAndScissor.viewportW, vpAndScissor.viewportH, vpAndScissor.depthRangeMin, vpAndScissor.depthRangeMax }); - - if (vpAndScissor.dirtyProj) { - gstate_c.Dirty(DIRTY_PROJMATRIX); - } - if (vpAndScissor.dirtyDepth) { - gstate_c.Dirty(DIRTY_DEPTHRANGE); - } } } diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index a29d9fc8ce..256c1adbac 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -856,13 +856,7 @@ void DrawEngineVulkan::DoFlush() { framebufferManager_->GetRenderWidth(), framebufferManager_->GetRenderHeight(), framebufferManager_->GetTargetBufferWidth(), framebufferManager_->GetTargetBufferHeight(), vpAndScissor); - - if (vpAndScissor.dirtyProj) { - gstate_c.Dirty(DIRTY_PROJMATRIX); - } - if (vpAndScissor.dirtyDepth) { - gstate_c.Dirty(DIRTY_DEPTHRANGE); - } + UpdateCachedViewportState(vpAndScissor); } int maxIndex = indexGen.MaxIndex(); diff --git a/GPU/Vulkan/StateMappingVulkan.cpp b/GPU/Vulkan/StateMappingVulkan.cpp index cb1f45aaca..566708480a 100644 --- a/GPU/Vulkan/StateMappingVulkan.cpp +++ b/GPU/Vulkan/StateMappingVulkan.cpp @@ -318,15 +318,13 @@ void DrawEngineVulkan::ConvertStateToVulkanKey(FramebufferManagerVulkan &fbManag fbManager.GetRenderWidth(), fbManager.GetRenderHeight(), fbManager.GetTargetBufferWidth(), fbManager.GetTargetBufferHeight(), vpAndScissor); + UpdateCachedViewportState(vpAndScissor); float depthMin = vpAndScissor.depthRangeMin; float depthMax = vpAndScissor.depthRangeMax; if (depthMin < 0.0f) depthMin = 0.0f; if (depthMax > 1.0f) depthMax = 1.0f; - if (vpAndScissor.dirtyDepth) { - gstate_c.Dirty(DIRTY_DEPTHRANGE); - } VkViewport &vp = dynState.viewport; vp.x = vpAndScissor.viewportX; @@ -336,10 +334,6 @@ void DrawEngineVulkan::ConvertStateToVulkanKey(FramebufferManagerVulkan &fbManag vp.minDepth = vpAndScissor.depthRangeMin; vp.maxDepth = vpAndScissor.depthRangeMax; - if (vpAndScissor.dirtyProj) { - gstate_c.Dirty(DIRTY_PROJMATRIX); - } - ScissorRect &scissor = dynState.scissor; scissor.x = vpAndScissor.scissorX; scissor.y = vpAndScissor.scissorY; From 5d46948ecac5e145dbdb71bf2ff3221b93c1b6ff Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sat, 20 Aug 2022 15:36:13 -0700 Subject: [PATCH 30/85] GPU: Correct depal CLUT texture for 5551/565. See #15823. --- GPU/Common/DepalettizeCommon.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/GPU/Common/DepalettizeCommon.cpp b/GPU/Common/DepalettizeCommon.cpp index 85c74d4c55..70214fc3d5 100644 --- a/GPU/Common/DepalettizeCommon.cpp +++ b/GPU/Common/DepalettizeCommon.cpp @@ -80,11 +80,11 @@ Draw::Texture *DepalShaderCache::GetClutTexture(GEPaletteFormat clutFormat, cons desc.initData.push_back((const uint8_t *)rawClut); break; case GEPaletteFormat::GE_CMODE_16BIT_BGR5650: - ConvertRGBA5551ToRGBA8888((u32 *)convTemp, (const u16 *)rawClut, texturePixels); + ConvertRGB565ToRGBA8888((u32 *)convTemp, (const u16 *)rawClut, texturePixels); desc.initData.push_back(convTemp); break; case GEPaletteFormat::GE_CMODE_16BIT_ABGR5551: - ConvertRGB565ToRGBA8888((u32 *)convTemp, (const u16 *)rawClut, texturePixels); + ConvertRGBA5551ToRGBA8888((u32 *)convTemp, (const u16 *)rawClut, texturePixels); desc.initData.push_back(convTemp); break; case GEPaletteFormat::GE_CMODE_16BIT_ABGR4444: From 01bfb88f1545df77a0d63400d3cd56ceebeaeb38 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sat, 20 Aug 2022 15:51:46 -0700 Subject: [PATCH 31/85] GE Debugger: Correct 16-bit CLUT display. --- Windows/GEDebugger/GEDebugger.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Windows/GEDebugger/GEDebugger.cpp b/Windows/GEDebugger/GEDebugger.cpp index 60ae3a0b3b..49ecc6af4e 100644 --- a/Windows/GEDebugger/GEDebugger.cpp +++ b/Windows/GEDebugger/GEDebugger.cpp @@ -649,11 +649,13 @@ void CGEDebugger::SecondPreviewHover(int x, int y) { } DescribeSecondPreview(state, desc); } else { - u32 pix = secondBuffer_->GetRawPixel(x, y); if (showClut_) { - // Show the clut index, rather than coords. - DescribePixel(pix, secondBuffer_->GetFormat(), y * 16 + x, 0, desc); + // Use the clut index, rather than coords. + uint32_t clutWidth = secondBuffer_->GetStride() / 16; + u32 pix = secondBuffer_->GetRawPixel(y * clutWidth + x, 0); + DescribePixel(pix, secondBuffer_->GetFormat(), y * clutWidth + x, 0, desc); } else { + u32 pix = secondBuffer_->GetRawPixel(x, y); DescribePixel(pix, secondBuffer_->GetFormat(), x, y, desc); } } From e374ea6b21e5117c8410c18f5dcceaf3e6f73fc7 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sat, 20 Aug 2022 17:32:45 -0700 Subject: [PATCH 32/85] GPU: Restrict mip CLUT enhancement a bit. Can't replicate this behavior on a real PSP. In case a game sets the separate CLUT flag by accident, ignore except in a safe case that occurs in Misshitsu no Sacrifice. See #15727. --- GPU/Common/TextureCacheCommon.cpp | 4 +++- GPU/GPUState.h | 10 ++++++++-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index 014b8feb3a..af642a7df1 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -1666,7 +1666,9 @@ CheckAlphaResult TextureCacheCommon::ReadIndexedTex(u8 *out, int outPitch, int l texptr = (u8 *)tmpTexBuf32_.data(); } - const bool mipmapShareClut = gstate.isClutSharedForMipmaps(); + // Misshitsu no Sacrifice has separate CLUT data, this is a hack to allow it. + // Normally separate CLUTs are not allowed for 8-bit or higher indices. + const bool mipmapShareClut = gstate.isClutSharedForMipmaps() && gstate.getClutLoadBlocks() == 0x40; const int clutSharingOffset = mipmapShareClut ? 0 : (level & 1) * 256; GEPaletteFormat palFormat = (GEPaletteFormat)gstate.getClutPaletteFormat(); diff --git a/GPU/GPUState.h b/GPU/GPUState.h index 6aaa79a8fd..ae1c2c6510 100644 --- a/GPU/GPUState.h +++ b/GPU/GPUState.h @@ -300,8 +300,14 @@ struct GPUgstate { bool isTextureFormatIndexed() const { return (texformat & 4) != 0; } // GE_TFMT_CLUT4 - GE_TFMT_CLUT32 are 0b1xx. int getTextureEnvColRGB() const { return texenvcolor & 0x00FFFFFF; } u32 getClutAddress() const { return (clutaddr & 0x00FFFFF0) | ((clutaddrupper << 8) & 0x0F000000); } - int getClutLoadBytes() const { return (loadclut & 0x7F) * 32; } - int getClutLoadBlocks() const { return (loadclut & 0x7F); } + int getClutLoadBytes() const { return getClutLoadBlocks() * 32; } + int getClutLoadBlocks() const { + // The PSP only supports 0x3F, but Misshitsu no Sacrifice has extra color data (see #15727.) + // 0x40 would be 0, which would be a no-op, so we allow it. + if ((loadclut & 0x7F) == 0x40) + return 0x40; + return loadclut & 0x3F; + } GEPaletteFormat getClutPaletteFormat() const { return static_cast(clutformat & 3); } int getClutIndexShift() const { return (clutformat >> 2) & 0x1F; } int getClutIndexMask() const { return (clutformat >> 8) & 0xFF; } From 229c9442088fc8dc7e84c1448653337e2c3facee Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sat, 20 Aug 2022 17:35:06 -0700 Subject: [PATCH 33/85] GE Debugger: Include extended CLUT in frame dumps. Not available on a real PSP, but used in an enhancement (see #15727.) --- GPU/Debugger/Record.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/GPU/Debugger/Record.cpp b/GPU/Debugger/Record.cpp index 0a15fb8f43..907c7b82c4 100644 --- a/GPU/Debugger/Record.cpp +++ b/GPU/Debugger/Record.cpp @@ -454,7 +454,9 @@ static void EmitTransfer(u32 op) { static void EmitClut(u32 op) { u32 addr = gstate.getClutAddress(); - u32 bytes = (op & 0x3F) * 32; + // Actually should only be 0x3F, but we allow enhanced CLUTs. See #15727. + u32 blocks = (op & 0x7F) == 0x40 ? 0x40 : (op & 0x3F); + u32 bytes = blocks * 32; bytes = Memory::ValidSize(addr, bytes); if (bytes != 0) { From 3d52b445f17adb74e273f04c9016b5a0dbb8c949 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sat, 20 Aug 2022 17:36:15 -0700 Subject: [PATCH 34/85] softgpu: Restrict CLUT to proper size. We had 15 KB more space than needed before. --- GPU/Software/Rasterizer.cpp | 2 +- GPU/Software/SoftGpu.cpp | 7 +++++-- GPU/Software/SoftGpu.h | 2 +- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/GPU/Software/Rasterizer.cpp b/GPU/Software/Rasterizer.cpp index 36cd871ecb..48e51cd9b2 100644 --- a/GPU/Software/Rasterizer.cpp +++ b/GPU/Software/Rasterizer.cpp @@ -1408,7 +1408,7 @@ bool GetCurrentTexture(GPUDebugBuffer &buffer, int level) SamplerID id; ComputeSamplerID(&id); - id.cached.clut = (const u8 *)clut; + id.cached.clut = clut; Sampler::FetchFunc sampler = Sampler::GetFetchFunc(id); diff --git a/GPU/Software/SoftGpu.cpp b/GPU/Software/SoftGpu.cpp index 8015a9db05..117faced52 100644 --- a/GPU/Software/SoftGpu.cpp +++ b/GPU/Software/SoftGpu.cpp @@ -52,7 +52,7 @@ const int FB_WIDTH = 480; const int FB_HEIGHT = 272; -u32 clut[4096]; +uint8_t clut[1024]; FormatBuffer fb; FormatBuffer depthbuf; @@ -971,7 +971,10 @@ void SoftGPU::Execute_Spline(u32 op, u32 diff) { void SoftGPU::Execute_LoadClut(u32 op, u32 diff) { u32 clutAddr = gstate.getClutAddress(); - u32 clutTotalBytes = gstate.getClutLoadBytes(); + // Avoid the hack in getClutLoadBytes() to inaccurately allow more palette data. + u32 clutTotalBytes = (gstate.getClutLoadBlocks() & 0x3F) * 32; + if (clutTotalBytes > 1024) + clutTotalBytes = 1024; // Might be copying drawing into the CLUT, so flush. drawEngine_->transformUnit.FlushIfOverlap("loadclut", clutAddr, clutTotalBytes, clutTotalBytes, 1); diff --git a/GPU/Software/SoftGpu.h b/GPU/Software/SoftGpu.h index 712ec6bbdd..11d5dd16f3 100644 --- a/GPU/Software/SoftGpu.h +++ b/GPU/Software/SoftGpu.h @@ -216,7 +216,7 @@ private: }; // TODO: These shouldn't be global. -extern u32 clut[4096]; +extern uint8_t clut[1024]; extern FormatBuffer fb; extern FormatBuffer depthbuf; From 88e8f952931542bc3b9db0228ea7021b77be64b8 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sat, 20 Aug 2022 23:22:21 -0700 Subject: [PATCH 35/85] softgpu: Flush on transfer to pending tex read. Potentially could use these for self-render, but so far we should be detecting that so leaving it alone. --- GPU/Software/BinManager.cpp | 60 ++++++++++++++++++++++++++++++++-- GPU/Software/BinManager.h | 5 +++ GPU/Software/SoftGpu.cpp | 6 ++-- GPU/Software/TransformUnit.cpp | 4 ++- GPU/Software/TransformUnit.h | 2 +- 5 files changed, 69 insertions(+), 8 deletions(-) diff --git a/GPU/Software/BinManager.cpp b/GPU/Software/BinManager.cpp index 4005e42945..7f8f1ad453 100644 --- a/GPU/Software/BinManager.cpp +++ b/GPU/Software/BinManager.cpp @@ -210,6 +210,9 @@ void BinManager::UpdateState() { } if (HasDirty(SoftDirty::BINNER_OVERLAP)) { + // This is a good place to record any dependencies for block transfer overlap. + MarkPendingReads(state); + // Disallow threads when rendering to the target, even offset. bool selfRender = HasTextureWrite(state); int newMaxTasks = selfRender ? 1 : g_threadManager.GetNumLooperThreads(); @@ -251,6 +254,34 @@ bool BinManager::HasTextureWrite(const RasterizerState &state) { return false; } +void BinManager::MarkPendingReads(const Rasterizer::RasterizerState &state) { + if (!state.enableTextures) + return; + + const uint8_t textureBits = textureBitsPerPixel[state.samplerID.texfmt]; + for (int i = 0; i <= state.maxTexLevel; ++i) { + uint32_t byteStride = (state.texbufw[i] * textureBits) / 8; + uint32_t byteWidth = (state.samplerID.cached.sizes[i].w * textureBits) / 8; + uint32_t h = state.samplerID.cached.sizes[i].h; + auto it = pendingReads_.find(state.texaddr[i]); + if (it != pendingReads_.end()) { + uint32_t total = byteStride * (h - 1) + byteWidth; + uint32_t existing = it->second.strideBytes * (it->second.height - 1) + it->second.widthBytes; + if (existing < total) { + it->second.strideBytes = std::max(it->second.strideBytes, byteStride); + it->second.widthBytes = std::max(it->second.widthBytes, byteWidth); + it->second.height = std::max(it->second.height, h); + } + } else { + auto &range = pendingReads_[state.texaddr[i]]; + range.base = state.texaddr[i]; + range.strideBytes = byteStride; + range.widthBytes = byteWidth; + range.height = h; + } + } +} + inline void BinDirtyRange::Expand(uint32_t newBase, uint32_t bpp, uint32_t stride, DrawingCoords &tl, DrawingCoords &br) { const uint32_t w = br.x - tl.x + 1; const uint32_t h = br.y - tl.y + 1; @@ -465,9 +496,10 @@ void BinManager::Flush(const char *reason) { for (auto &pending : pendingWrites_) pending.base = 0; pendingOverlap_ = false; + pendingReads_.clear(); - // We'll need to set the pending writes again, since we just flushed it. - dirty_ |= SoftDirty::BINNER_RANGE; + // We'll need to set the pending writes and reads again, since we just flushed it. + dirty_ |= SoftDirty::BINNER_RANGE | SoftDirty::BINNER_OVERLAP; if (coreCollectDebugStats) { double et = time_now_d(); @@ -486,7 +518,7 @@ bool BinManager::HasPendingWrite(uint32_t start, uint32_t stride, uint32_t w, ui // Ignore mirrors for overlap detection. start &= 0x0FFFFFFF & ~0x00600000; - uint32_t size = stride * h; + uint32_t size = stride * (h - 1) + w; for (const auto &range : pendingWrites_) { if (range.base == 0 || range.strideBytes == 0) continue; @@ -512,6 +544,28 @@ bool BinManager::HasPendingWrite(uint32_t start, uint32_t stride, uint32_t w, ui return false; } +bool BinManager::HasPendingRead(uint32_t start, uint32_t stride, uint32_t w, uint32_t h) { + if (Memory::IsVRAMAddress(start)) { + // Ignore VRAM mirrors. + start &= 0x0FFFFFFF & ~0x00600000; + } else { + // Ignore only regular RAM mirrors. + start &= 0x3FFFFFFF; + } + + uint32_t size = stride * (h - 1) + w; + for (const auto &pair : pendingReads_) { + const auto &range = pair.second; + if (start >= range.base + range.height * range.strideBytes || start + size <= range.base) + continue; + + // Stride gaps are uncommon with reads, so don't bother. + return true; + } + + return false; +} + void BinManager::GetStats(char *buffer, size_t bufsize) { double allTotal = 0.0; double slowestTotalTime = 0.0; diff --git a/GPU/Software/BinManager.h b/GPU/Software/BinManager.h index 44ae81e2b2..01b6837d20 100644 --- a/GPU/Software/BinManager.h +++ b/GPU/Software/BinManager.h @@ -198,6 +198,8 @@ public: void Drain(); void Flush(const char *reason); bool HasPendingWrite(uint32_t start, uint32_t stride, uint32_t w, uint32_t h); + // Assumes you've also checked for a write (writes are partial so are automatically reads.) + bool HasPendingRead(uint32_t start, uint32_t stride, uint32_t w, uint32_t h); void GetStats(char *buffer, size_t bufsize); void ResetStats(); @@ -252,6 +254,8 @@ private: BinWaitable *waitable_ = nullptr; BinDirtyRange pendingWrites_[2]{}; + std::unordered_map pendingReads_; + bool pendingOverlap_ = false; std::unordered_map flushReasonTimes_; @@ -262,6 +266,7 @@ private: int enqueues_ = 0; int mostThreads_ = 0; + void MarkPendingReads(const Rasterizer::RasterizerState &state); bool HasTextureWrite(const Rasterizer::RasterizerState &state); BinCoords Scissor(BinCoords range); BinCoords Range(const VertexData &v0, const VertexData &v1, const VertexData &v2); diff --git a/GPU/Software/SoftGpu.cpp b/GPU/Software/SoftGpu.cpp index 8015a9db05..b677a5ec9a 100644 --- a/GPU/Software/SoftGpu.cpp +++ b/GPU/Software/SoftGpu.cpp @@ -787,8 +787,8 @@ void SoftGPU::Execute_BlockTransferStart(u32 op, u32 diff) { const uint32_t dstSize = height * dstStride * bpp; // Need to flush both source and target, so we overwrite properly. - drawEngine_->transformUnit.FlushIfOverlap("blockxfer", src, srcStride, width * bpp, height); - drawEngine_->transformUnit.FlushIfOverlap("blockxfer", dst, dstStride, width * bpp, height); + drawEngine_->transformUnit.FlushIfOverlap("blockxfer", false, src, srcStride, width * bpp, height); + drawEngine_->transformUnit.FlushIfOverlap("blockxfer", true, dst, dstStride, width * bpp, height); DEBUG_LOG(G3D, "Block transfer: %08x/%x -> %08x/%x, %ix%ix%i (%i,%i)->(%i,%i)", srcBasePtr, srcStride, dstBasePtr, dstStride, width, height, bpp, srcX, srcY, dstX, dstY); @@ -974,7 +974,7 @@ void SoftGPU::Execute_LoadClut(u32 op, u32 diff) { u32 clutTotalBytes = gstate.getClutLoadBytes(); // Might be copying drawing into the CLUT, so flush. - drawEngine_->transformUnit.FlushIfOverlap("loadclut", clutAddr, clutTotalBytes, clutTotalBytes, 1); + drawEngine_->transformUnit.FlushIfOverlap("loadclut", false, clutAddr, clutTotalBytes, clutTotalBytes, 1); bool changed = false; if (Memory::IsValidAddress(clutAddr)) { diff --git a/GPU/Software/TransformUnit.cpp b/GPU/Software/TransformUnit.cpp index b765df8404..db50f48bb6 100644 --- a/GPU/Software/TransformUnit.cpp +++ b/GPU/Software/TransformUnit.cpp @@ -797,9 +797,11 @@ void TransformUnit::GetStats(char *buffer, size_t bufsize) { binner_->GetStats(buffer, bufsize); } -void TransformUnit::FlushIfOverlap(const char *reason, uint32_t addr, uint32_t stride, uint32_t w, uint32_t h) { +void TransformUnit::FlushIfOverlap(const char *reason, bool modifying, uint32_t addr, uint32_t stride, uint32_t w, uint32_t h) { if (binner_->HasPendingWrite(addr, stride, w, h)) Flush(reason); + if (modifying && binner_->HasPendingRead(addr, stride, w, h)) + Flush(reason); } void TransformUnit::NotifyClutUpdate(const void *src) { diff --git a/GPU/Software/TransformUnit.h b/GPU/Software/TransformUnit.h index 9f17ed1197..54f9fb5f5e 100644 --- a/GPU/Software/TransformUnit.h +++ b/GPU/Software/TransformUnit.h @@ -123,7 +123,7 @@ public: bool GetCurrentSimpleVertices(int count, std::vector &vertices, std::vector &indices); void Flush(const char *reason); - void FlushIfOverlap(const char *reason, uint32_t addr, uint32_t stride, uint32_t w, uint32_t h); + void FlushIfOverlap(const char *reason, bool modifying, uint32_t addr, uint32_t stride, uint32_t w, uint32_t h); void NotifyClutUpdate(const void *src); void GetStats(char *buffer, size_t bufsize); From e14ca8790037c4a92857548a8f792f7656216fde Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sun, 21 Aug 2022 00:27:31 -0700 Subject: [PATCH 36/85] softgpu: Correct morph weight updates. Broke LittleBigPlanet character's face, for example. --- GPU/Software/SoftGpu.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/GPU/Software/SoftGpu.cpp b/GPU/Software/SoftGpu.cpp index 8015a9db05..988b71fbff 100644 --- a/GPU/Software/SoftGpu.cpp +++ b/GPU/Software/SoftGpu.cpp @@ -201,14 +201,14 @@ const SoftwareCommandTableEntry softgpuCommandTable[] = { { GE_CMD_CLUTFORMAT, 0, SoftDirty::SAMPLER_BASIC }, // Morph weights. TODO: Remove precomputation? - { GE_CMD_MORPHWEIGHT0, 0, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, - { GE_CMD_MORPHWEIGHT1, 0, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, - { GE_CMD_MORPHWEIGHT2, 0, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, - { GE_CMD_MORPHWEIGHT3, 0, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, - { GE_CMD_MORPHWEIGHT4, 0, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, - { GE_CMD_MORPHWEIGHT5, 0, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, - { GE_CMD_MORPHWEIGHT6, 0, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, - { GE_CMD_MORPHWEIGHT7, 0, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, + { GE_CMD_MORPHWEIGHT0, FLAG_EXECUTEONCHANGE, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, + { GE_CMD_MORPHWEIGHT1, FLAG_EXECUTEONCHANGE, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, + { GE_CMD_MORPHWEIGHT2, FLAG_EXECUTEONCHANGE, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, + { GE_CMD_MORPHWEIGHT3, FLAG_EXECUTEONCHANGE, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, + { GE_CMD_MORPHWEIGHT4, FLAG_EXECUTEONCHANGE, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, + { GE_CMD_MORPHWEIGHT5, FLAG_EXECUTEONCHANGE, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, + { GE_CMD_MORPHWEIGHT6, FLAG_EXECUTEONCHANGE, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, + { GE_CMD_MORPHWEIGHT7, FLAG_EXECUTEONCHANGE, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, // No state of flushing required for patch parameters, currently. { GE_CMD_PATCHDIVISION }, From 5a7bddbfa604d252e1a69006ace30ec4c39f0497 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Thu, 18 Aug 2022 11:44:20 +0200 Subject: [PATCH 37/85] Allow binding depth as 565 by going through depal. This is a partial fix for #6105 (Ratchet & Clank particles visible through things), but there's still weird glitchiness. There's a pass during rendering that scrambles the mini depth buffer by using a triangle mesh. I wonder if it's trying to simulate the swizzle? But it doesn't really look like it... --- GPU/Common/DepalettizeCommon.cpp | 7 +++--- GPU/Common/DepalettizeCommon.h | 6 ++--- GPU/Common/DepalettizeShaderCommon.cpp | 21 ++++++++++++---- GPU/Common/DepalettizeShaderCommon.h | 3 ++- GPU/Common/TextureCacheCommon.cpp | 35 +++++++++++++++++++++++--- unittest/TestShaderGenerators.cpp | 3 ++- 6 files changed, 59 insertions(+), 16 deletions(-) diff --git a/GPU/Common/DepalettizeCommon.cpp b/GPU/Common/DepalettizeCommon.cpp index 70214fc3d5..185eecdbc4 100644 --- a/GPU/Common/DepalettizeCommon.cpp +++ b/GPU/Common/DepalettizeCommon.cpp @@ -147,10 +147,10 @@ Draw::SamplerState *DepalShaderCache::GetSampler() { return nearestSampler_; } -DepalShader *DepalShaderCache::GetDepalettizeShader(uint32_t clutMode, GEBufferFormat pixelFormat) { +DepalShader *DepalShaderCache::GetDepalettizeShader(uint32_t clutMode, GETextureFormat textureFormat, GEBufferFormat bufferFormat) { using namespace Draw; - u32 id = GenerateShaderID(clutMode, pixelFormat); + u32 id = GenerateShaderID(clutMode, textureFormat, bufferFormat); auto shader = cache_.find(id); if (shader != cache_.end()) { @@ -171,7 +171,8 @@ DepalShader *DepalShaderCache::GetDepalettizeShader(uint32_t clutMode, GEBufferF config.startPos = gstate.getClutIndexStartPos(); config.shift = gstate.getClutIndexShift(); config.mask = gstate.getClutIndexMask(); - config.pixelFormat = pixelFormat; + config.bufferFormat = bufferFormat; + config.textureFormat = textureFormat; GenerateDepalFs(buffer, config, draw_->GetShaderLanguageDesc()); diff --git a/GPU/Common/DepalettizeCommon.h b/GPU/Common/DepalettizeCommon.h index c394f47eb7..fbac86300d 100644 --- a/GPU/Common/DepalettizeCommon.h +++ b/GPU/Common/DepalettizeCommon.h @@ -49,7 +49,7 @@ public: ~DepalShaderCache(); // This also uploads the palette and binds the correct texture. - DepalShader *GetDepalettizeShader(uint32_t clutMode, GEBufferFormat pixelFormat); + DepalShader *GetDepalettizeShader(uint32_t clutMode, GETextureFormat texFormat, GEBufferFormat pixelFormat); Draw::Texture *GetClutTexture(GEPaletteFormat clutFormat, const u32 clutHash, u32 *rawClut); Draw::SamplerState *GetSampler(); @@ -63,8 +63,8 @@ public: void DeviceRestore(Draw::DrawContext *draw); private: - static uint32_t GenerateShaderID(uint32_t clutMode, GEBufferFormat pixelFormat) { - return (clutMode & 0xFFFFFF) | (pixelFormat << 24); + static uint32_t GenerateShaderID(uint32_t clutMode, GETextureFormat texFormat, GEBufferFormat pixelFormat) { + return (clutMode & 0xFFFFFF) | (pixelFormat << 24) | (texFormat << 28); } static uint32_t GetClutID(GEPaletteFormat clutFormat, uint32_t clutHash) { diff --git a/GPU/Common/DepalettizeShaderCommon.cpp b/GPU/Common/DepalettizeShaderCommon.cpp index 9874e91d6e..11c3c50394 100644 --- a/GPU/Common/DepalettizeShaderCommon.cpp +++ b/GPU/Common/DepalettizeShaderCommon.cpp @@ -49,7 +49,7 @@ void GenerateDepalShader300(ShaderWriter &writer, const DepalConfig &config, con const int shift = config.shift; const int mask = config.mask; - if (config.pixelFormat == GE_FORMAT_DEPTH16) { + if (config.bufferFormat == GE_FORMAT_DEPTH16) { DepthScaleFactors factors = GetDepthScaleFactors(); writer.ConstFloat("z_scale", factors.scale); writer.ConstFloat("z_offset", factors.offset); @@ -71,7 +71,7 @@ void GenerateDepalShader300(ShaderWriter &writer, const DepalConfig &config, con writer.C(" vec4 color = ").SampleTexture2D("tex", "v_texcoord").C(";\n"); int shiftedMask = mask << shift; - switch (config.pixelFormat) { + switch (config.bufferFormat) { case GE_FORMAT_8888: if (shiftedMask & 0xFF) writer.C(" int r = int(color.r * 255.99);\n"); else writer.C(" int r = 0;\n"); if (shiftedMask & 0xFF00) writer.C(" int g = int(color.g * 255.99);\n"); else writer.C(" int g = 0;\n"); @@ -102,6 +102,17 @@ void GenerateDepalShader300(ShaderWriter &writer, const DepalConfig &config, con case GE_FORMAT_DEPTH16: // Remap depth buffer. writer.C(" float depth = (color.x - z_offset) * z_scale;\n"); + + if (config.bufferFormat == GE_FORMAT_DEPTH16 && config.textureFormat == GE_TFMT_5650) { + // Convert depth to 565, without going through a CLUT. + writer.C(" int idepth = int(clamp(depth, 0.0, 65535.0));\n"); + writer.C(" float r = (idepth & 31) / 31.0f;\n"); + writer.C(" float g = ((idepth >> 5) & 63) / 63.0f;\n"); + writer.C(" float b = ((idepth >> 11) & 31) / 31.0f;\n"); + writer.C(" vec4 outColor = vec4(r, g, b, 1.0);\n"); + return; + } + writer.C(" int index = int(clamp(depth, 0.0, 65535.0));\n"); break; default: @@ -135,7 +146,7 @@ void GenerateDepalShaderFloat(ShaderWriter &writer, const DepalConfig &config, c const int shift = config.shift; const int mask = config.mask; - if (config.pixelFormat == GE_FORMAT_DEPTH16) { + if (config.bufferFormat == GE_FORMAT_DEPTH16) { DepthScaleFactors factors = GetDepthScaleFactors(); writer.ConstFloat("z_scale", factors.scale); writer.ConstFloat("z_offset", factors.offset); @@ -144,7 +155,7 @@ void GenerateDepalShaderFloat(ShaderWriter &writer, const DepalConfig &config, c float index_multiplier = 1.0f; // pixelformat is the format of the texture we are sampling. bool formatOK = true; - switch (config.pixelFormat) { + switch (config.bufferFormat) { case GE_FORMAT_8888: if ((mask & (mask + 1)) == 0) { // If the value has all bits contiguous (bitmask check above), we can mod by it + 1. @@ -249,7 +260,7 @@ void GenerateDepalShaderFloat(ShaderWriter &writer, const DepalConfig &config, c // index_multiplier -= 0.01f / texturePixels; if (!formatOK) { - ERROR_LOG_REPORT_ONCE(depal, G3D, "%s depal unsupported: shift=%d mask=%02x offset=%d", GeBufferFormatToString(config.pixelFormat), shift, mask, config.startPos); + ERROR_LOG_REPORT_ONCE(depal, G3D, "%s depal unsupported: shift=%d mask=%02x offset=%d", GeBufferFormatToString(config.bufferFormat), shift, mask, config.startPos); } // Offset by half a texel (plus clutBase) to turn NEAREST filtering into FLOOR. diff --git a/GPU/Common/DepalettizeShaderCommon.h b/GPU/Common/DepalettizeShaderCommon.h index 5ce5ef88a8..74bb38d196 100644 --- a/GPU/Common/DepalettizeShaderCommon.h +++ b/GPU/Common/DepalettizeShaderCommon.h @@ -29,7 +29,8 @@ struct DepalConfig { int shift; u32 startPos; GEPaletteFormat clutFormat; - GEBufferFormat pixelFormat; + GETextureFormat textureFormat; + GEBufferFormat bufferFormat; }; void GenerateDepalFs(char *buffer, const DepalConfig &config, const ShaderLanguageDesc &lang); diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index af642a7df1..64a48537b6 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -525,6 +525,10 @@ TexCacheEntry *TextureCacheCommon::SetTexture() { def.format = format; def.bufw = bufw; + if (texaddr == 0x04710000) { + texaddr = texaddr; + } + std::vector candidates = GetFramebufferCandidates(def, 0); if (candidates.size() > 0) { int index = GetBestCandidateIndex(candidates); @@ -892,6 +896,7 @@ bool TextureCacheCommon::MatchFramebuffer( const bool noOffset = texaddr == addr; const bool exactMatch = noOffset && entry.format < 4 && channel == RASTER_COLOR; + 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. @@ -927,6 +932,7 @@ bool TextureCacheCommon::MatchFramebuffer( // Check works for D16 too (???) const bool matchingClutFormat = (fb_format == GE_FORMAT_DEPTH16 && entry.format == GE_TFMT_CLUT16) || + (fb_format == GE_FORMAT_DEPTH16 && entry.format == GE_TFMT_5650) || (fb_format == GE_FORMAT_8888 && entry.format == GE_TFMT_CLUT32) || (fb_format != GE_FORMAT_8888 && entry.format == GE_TFMT_CLUT16); @@ -971,7 +977,9 @@ bool TextureCacheCommon::MatchFramebuffer( // 3rd Birthday (and a bunch of other games) render to a 16 bit clut texture. if (matchingClutFormat) { if (!noOffset) { - WARN_LOG_ONCE(subareaClut, G3D, "Texturing from framebuffer using CLUT with offset at %08x +%dx%d", fb_address, matchInfo->xOffset, matchInfo->yOffset); + WARN_LOG_ONCE(subareaClut, G3D, "Texturing from framebuffer (%s) using %s with offset at %08x +%dx%d", channel == RASTER_DEPTH ? "DEPTH" : "COLOR", GeTextureFormatToString(entry.format), fb_address, matchInfo->xOffset, matchInfo->yOffset); + } else { + WARN_LOG_ONCE(subareaClut, G3D, "Texturing from framebuffer (%s) using %s at %08x", channel == RASTER_DEPTH ? "DEPTH" : "COLOR", GeTextureFormatToString(entry.format), fb_address); } return true; } else if (IsClutFormat((GETextureFormat)(entry.format)) || IsDXTFormat((GETextureFormat)(entry.format))) { @@ -1823,12 +1831,33 @@ void TextureCacheCommon::ApplyTexture() { gstate_c.SetTextureIs3D((entry->status & TexCacheEntry::STATUS_3D) != 0); } +bool CanDepalettize(GETextureFormat texFormat, GEBufferFormat bufferFormat) { + if (IsClutFormat(texFormat)) { + switch (bufferFormat) { + case GE_FORMAT_4444: + case GE_FORMAT_565: + case GE_FORMAT_5551: + case GE_FORMAT_DEPTH16: + return texFormat == GE_TFMT_CLUT16; + case GE_FORMAT_8888: + return texFormat == GE_TFMT_CLUT32; + } + WARN_LOG(G3D, "Invalid CLUT/framebuffer combination: %s vs %s", GeTextureFormatToString(texFormat), GeBufferFormatToString(bufferFormat)); + return false; + } 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; + } +} + void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer, GETextureFormat texFormat, RasterChannel channel) { DepalShader *depalShader = nullptr; uint32_t clutMode = gstate.clutformat & 0xFFFFFF; - bool need_depalettize = IsClutFormat(texFormat); bool depth = channel == RASTER_DEPTH; + bool need_depalettize = CanDepalettize(texFormat, depth ? GE_FORMAT_DEPTH16 : framebuffer->drawnFormat); bool useShaderDepal = framebufferManager_->GetCurrentRenderVFB() != framebuffer && !depth && !gstate_c.curTextureIs3D; // TODO: Implement shader depal in the fragment shader generator for D3D11 at least. @@ -1878,7 +1907,7 @@ void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer return; } - depalShader = depalShaderCache_->GetDepalettizeShader(clutMode, depth ? GE_FORMAT_DEPTH16 : framebuffer->drawnFormat); + depalShader = depalShaderCache_->GetDepalettizeShader(clutMode, texFormat, depth ? GE_FORMAT_DEPTH16 : framebuffer->drawnFormat); gstate_c.SetUseShaderDepal(false); } diff --git a/unittest/TestShaderGenerators.cpp b/unittest/TestShaderGenerators.cpp index 19b0b0d2e9..a96df6657c 100644 --- a/unittest/TestShaderGenerators.cpp +++ b/unittest/TestShaderGenerators.cpp @@ -309,7 +309,8 @@ bool TestDepalShaders() { config.shift = 8; config.startPos = 64; config.mask = 0xFF; - config.pixelFormat = GE_FORMAT_8888; + config.bufferFormat = GE_FORMAT_8888; + config.textureFormat = GE_TFMT_CLUT32; GenerateDepalFs(buffer, config, desc); if (!TestCompileShader(buffer, languages[k], ShaderStage::Fragment, &errorMessage)) { From 346a252593c5d2d7bca4c3705ea86d5ac20be67f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Thu, 18 Aug 2022 12:08:03 +0200 Subject: [PATCH 38/85] Fix naming of temp fbos to be in PSP pixels --- GPU/Common/FramebufferManagerCommon.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GPU/Common/FramebufferManagerCommon.cpp b/GPU/Common/FramebufferManagerCommon.cpp index a1164c686f..3e524da19f 100644 --- a/GPU/Common/FramebufferManagerCommon.cpp +++ b/GPU/Common/FramebufferManagerCommon.cpp @@ -1941,7 +1941,7 @@ Draw::Framebuffer *FramebufferManagerCommon::GetTempFBO(TempFBO reason, u16 w, u bool z_stencil = reason == TempFBO::STENCIL; char name[128]; - snprintf(name, sizeof(name), "temp_fbo_%dx%d%s", w, h, z_stencil ? "_depth" : ""); + snprintf(name, sizeof(name), "temp_fbo_%dx%d%s", w / renderScaleFactor_, h / renderScaleFactor_, z_stencil ? "_depth" : ""); Draw::Framebuffer *fbo = draw_->CreateFramebuffer({ w, h, 1, 1, z_stencil, name }); if (!fbo) { return nullptr; From e6b60026d17b96484d78892d78ab23f9f6db4611 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Thu, 18 Aug 2022 15:46:20 +0200 Subject: [PATCH 39/85] Fix graphics in Ratchet & Clank. WIP --- GPU/Common/DepalettizeCommon.cpp | 1 + GPU/Common/DepalettizeShaderCommon.h | 1 + GPU/Common/Draw2D.cpp | 36 +++++++++++++++++++++++++ GPU/Common/Draw2D.h | 2 ++ GPU/Common/FramebufferManagerCommon.cpp | 8 ++++-- GPU/Common/FramebufferManagerCommon.h | 1 + 6 files changed, 47 insertions(+), 2 deletions(-) diff --git a/GPU/Common/DepalettizeCommon.cpp b/GPU/Common/DepalettizeCommon.cpp index 185eecdbc4..4d395a2d4a 100644 --- a/GPU/Common/DepalettizeCommon.cpp +++ b/GPU/Common/DepalettizeCommon.cpp @@ -173,6 +173,7 @@ DepalShader *DepalShaderCache::GetDepalettizeShader(uint32_t clutMode, GETexture config.mask = gstate.getClutIndexMask(); config.bufferFormat = bufferFormat; config.textureFormat = textureFormat; + config.resolutionScale = 3; GenerateDepalFs(buffer, config, draw_->GetShaderLanguageDesc()); diff --git a/GPU/Common/DepalettizeShaderCommon.h b/GPU/Common/DepalettizeShaderCommon.h index 74bb38d196..c4577be920 100644 --- a/GPU/Common/DepalettizeShaderCommon.h +++ b/GPU/Common/DepalettizeShaderCommon.h @@ -31,6 +31,7 @@ struct DepalConfig { GEPaletteFormat clutFormat; GETextureFormat textureFormat; GEBufferFormat bufferFormat; + int resolutionScale; }; void GenerateDepalFs(char *buffer, const DepalConfig &config, const ShaderLanguageDesc &lang); diff --git a/GPU/Common/Draw2D.cpp b/GPU/Common/Draw2D.cpp index a6b4abb68c..89292adfaf 100644 --- a/GPU/Common/Draw2D.cpp +++ b/GPU/Common/Draw2D.cpp @@ -73,6 +73,29 @@ RasterChannel GenerateDraw2D565ToDepthFs(ShaderWriter &writer) { return RASTER_DEPTH; } +// ugly way to get the scale into the function +static float g_scale; + +RasterChannel GenerateDraw2D565ToDepthDeswizzleFs(ShaderWriter &writer) { + writer.DeclareSamplers(samplers); + writer.BeginFSMain(Slice::empty(), varyings, FSFLAG_WRITEDEPTH); + writer.C(" vec4 outColor = vec4(0.0, 0.0, 0.0, 0.0);\n"); + // Unlike when just copying a depth buffer, here we're generating new depth values so we'll + // have to apply the scaling. + DepthScaleFactors factors = GetDepthScaleFactors(); + writer.C(" vec2 tsize = vec2(textureSize(tex, 0));\n"); + writer.C(" vec2 coord = v_texcoord * tsize;\n"); + writer.F(" float strip = 4.0 * %f;\n", g_scale); + writer.C(" float in_strip = mod(coord.y, strip);\n"); + writer.C(" coord.y = coord.y - in_strip + strip - in_strip;\n"); + writer.C(" coord /= tsize;\n"); + writer.C(" vec3 rgb = ").SampleTexture2D("tex", "coord").C(".xyz;\n"); + writer.F(" highp float depthValue = (floor(rgb.x * 31.99) + floor(rgb.y * 63.99) * 32.0 + floor(rgb.z * 31.99) * 2048.0); \n"); + writer.F(" gl_FragDepth = (depthValue / %f) + %f;\n", factors.scale, factors.offset); + writer.EndFSMain("outColor", FSFLAG_WRITEDEPTH); + return RASTER_DEPTH; +} + void GenerateDraw2DVS(ShaderWriter &writer) { writer.BeginVSMain(inputs, Slice::empty(), varyings); @@ -212,6 +235,19 @@ void FramebufferManagerCommon::DrawStrip2D(Draw::Texture *tex, Draw2DVertex *ver } draw_->BindPipeline(draw2DPipeline565ToDepth_); break; + + case DRAW2D_565_TO_DEPTH_DESWIZZLE: + if (!draw_->GetDeviceCaps().fragmentShaderDepthWriteSupported) { + // Can't do it + return; + } + if (!draw2DPipeline565ToDepthDeswizzle_) { + g_scale = renderScaleFactor_; + draw2DPipeline565ToDepthDeswizzle_ = Create2DPipeline(&GenerateDraw2D565ToDepthDeswizzleFs); + linearFilter = false; + } + draw_->BindPipeline(draw2DPipeline565ToDepthDeswizzle_); + break; } if (tex) { diff --git a/GPU/Common/Draw2D.h b/GPU/Common/Draw2D.h index fee2d4cef3..e1ed615ba8 100644 --- a/GPU/Common/Draw2D.h +++ b/GPU/Common/Draw2D.h @@ -14,6 +14,7 @@ enum Draw2DShader { DRAW2D_COPY_COLOR, DRAW2D_COPY_DEPTH, DRAW2D_565_TO_DEPTH, + DRAW2D_565_TO_DEPTH_DESWIZZLE, }; inline RasterChannel Draw2DSourceChannel(Draw2DShader shader) { @@ -22,6 +23,7 @@ inline RasterChannel Draw2DSourceChannel(Draw2DShader shader) { return RASTER_DEPTH; case DRAW2D_COPY_COLOR: case DRAW2D_565_TO_DEPTH: + case DRAW2D_565_TO_DEPTH_DESWIZZLE: default: return RASTER_COLOR; } diff --git a/GPU/Common/FramebufferManagerCommon.cpp b/GPU/Common/FramebufferManagerCommon.cpp index 3e524da19f..c1052b785d 100644 --- a/GPU/Common/FramebufferManagerCommon.cpp +++ b/GPU/Common/FramebufferManagerCommon.cpp @@ -560,11 +560,14 @@ void FramebufferManagerCommon::CopyToDepthFromOverlappingFramebuffers(VirtualFra dest->last_frame_depth_updated = gpuStats.numFlips; } else if (source.channel == RASTER_COLOR) { VirtualFramebuffer *src = source.vfb; - // Copying color to depth. if (src->drawnFormat != GE_FORMAT_565) { WARN_LOG_ONCE(not565, G3D, "Drawn format of buffer at %08x not 565 as expected", src->fb_address); } - BlitUsingRaster(src->fbo, 0.0f, 0.0f, src->renderWidth, src->renderHeight, dest->fbo, 0.0f, 0.0f, dest->renderWidth, dest->renderHeight, false, DRAW2D_565_TO_DEPTH, "565_to_depth"); + // Copying color to depth. + BlitUsingRaster( + src->fbo, 0.0f, 0.0f, src->renderWidth, src->renderHeight, + dest->fbo, 0.0f, 0.0f, src->renderWidth, src->renderHeight, + false, DRAW2D_565_TO_DEPTH_DESWIZZLE, "565_to_depth"); } } @@ -2343,6 +2346,7 @@ void FramebufferManagerCommon::DeviceLost() { DoRelease(draw2DPipelineColor_); DoRelease(draw2DPipelineDepth_); DoRelease(draw2DPipeline565ToDepth_); + DoRelease(draw2DPipeline565ToDepthDeswizzle_); draw_ = nullptr; } diff --git a/GPU/Common/FramebufferManagerCommon.h b/GPU/Common/FramebufferManagerCommon.h index 447554f376..ce5a31a87a 100644 --- a/GPU/Common/FramebufferManagerCommon.h +++ b/GPU/Common/FramebufferManagerCommon.h @@ -511,6 +511,7 @@ protected: Draw::Pipeline *draw2DPipelineColor_ = nullptr; Draw::Pipeline *draw2DPipelineDepth_ = nullptr; Draw::Pipeline *draw2DPipeline565ToDepth_ = nullptr; + Draw::Pipeline *draw2DPipeline565ToDepthDeswizzle_ = nullptr; Draw::SamplerState *draw2DSamplerLinear_ = nullptr; Draw::SamplerState *draw2DSamplerNearest_ = nullptr; Draw::ShaderModule *draw2DVs_ = nullptr; From f3496d34c859d2d41189df3ac708f6042cad1447 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Fri, 19 Aug 2022 00:02:22 +0200 Subject: [PATCH 40/85] Texture bind channel fix. Still need to figure out a way to decide to swizzle or not. --- GPU/Common/TextureCacheCommon.cpp | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index 64a48537b6..1c542633ca 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -1838,9 +1838,15 @@ bool CanDepalettize(GETextureFormat texFormat, GEBufferFormat bufferFormat) { case GE_FORMAT_565: case GE_FORMAT_5551: case GE_FORMAT_DEPTH16: - return texFormat == GE_TFMT_CLUT16; + if (texFormat == GE_TFMT_CLUT16) { + return true; + } + break; case GE_FORMAT_8888: - return texFormat == GE_TFMT_CLUT32; + if (texFormat == GE_TFMT_CLUT32) { + return true; + } + break; } WARN_LOG(G3D, "Invalid CLUT/framebuffer combination: %s vs %s", GeTextureFormatToString(texFormat), GeBufferFormatToString(bufferFormat)); return false; From 89c96142a17d9ad7e5ad433bbeeb6516e411d6c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Fri, 19 Aug 2022 00:34:02 +0200 Subject: [PATCH 41/85] Really not sure how we can detect whether a depth deswizzle is needed :( Hopefully temporary flag... --- Core/Compatibility.cpp | 1 + Core/Compatibility.h | 1 + Core/CoreParameter.h | 2 +- GPU/Common/FramebufferManagerCommon.cpp | 12 ++++++++++-- assets/compat.ini | 10 ++++++++++ 5 files changed, 23 insertions(+), 3 deletions(-) diff --git a/Core/Compatibility.cpp b/Core/Compatibility.cpp index c56cf702f8..f17c1fd6a1 100644 --- a/Core/Compatibility.cpp +++ b/Core/Compatibility.cpp @@ -97,6 +97,7 @@ void Compatibility::CheckSettings(IniFile &iniFile, const std::string &gameID) { CheckSetting(iniFile, gameID, "ZZT3SelectHack", &flags_.ZZT3SelectHack); CheckSetting(iniFile, gameID, "AllowLargeFBTextureOffsets", &flags_.AllowLargeFBTextureOffsets); CheckSetting(iniFile, gameID, "AtracLoopHack", &flags_.AtracLoopHack); + CheckSetting(iniFile, gameID, "DeswizzleDepth", &flags_.DeswizzleDepth); } 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 c293fdfa17..29345aee42 100644 --- a/Core/Compatibility.h +++ b/Core/Compatibility.h @@ -87,6 +87,7 @@ struct CompatFlags { bool ZZT3SelectHack; bool AllowLargeFBTextureOffsets; bool AtracLoopHack; + bool DeswizzleDepth; }; class IniFile; diff --git a/Core/CoreParameter.h b/Core/CoreParameter.h index 7e9ea60b2e..9ef01c4d9b 100644 --- a/Core/CoreParameter.h +++ b/Core/CoreParameter.h @@ -66,7 +66,7 @@ struct CoreParameter { bool headLess; // Try to avoid messageboxes etc // Internal PSP rendering resolution and scale factor. - int renderScaleFactor; + int renderScaleFactor = 1; int renderWidth; int renderHeight; diff --git a/GPU/Common/FramebufferManagerCommon.cpp b/GPU/Common/FramebufferManagerCommon.cpp index c1052b785d..1bfdafb5eb 100644 --- a/GPU/Common/FramebufferManagerCommon.cpp +++ b/GPU/Common/FramebufferManagerCommon.cpp @@ -551,7 +551,7 @@ void FramebufferManagerCommon::CopyToDepthFromOverlappingFramebuffers(VirtualFra // For now, let's just do the last thing, if there are multiple. // for (auto &source : sources) { - if (sources.size()) { + if (!sources.empty()) { auto &source = sources.back(); if (source.channel == RASTER_DEPTH) { // Good old depth->depth copy. @@ -563,11 +563,19 @@ void FramebufferManagerCommon::CopyToDepthFromOverlappingFramebuffers(VirtualFra if (src->drawnFormat != GE_FORMAT_565) { WARN_LOG_ONCE(not565, G3D, "Drawn format of buffer at %08x not 565 as expected", src->fb_address); } + + // Really hate to do this, but tracking the depth swizzle state across multiple + // copies is not easy. + Draw2DShader shader = DRAW2D_565_TO_DEPTH; + if (PSP_CoreParameter().compat.flags().DeswizzleDepth) { + shader = DRAW2D_565_TO_DEPTH_DESWIZZLE; + } + // Copying color to depth. BlitUsingRaster( src->fbo, 0.0f, 0.0f, src->renderWidth, src->renderHeight, dest->fbo, 0.0f, 0.0f, src->renderWidth, src->renderHeight, - false, DRAW2D_565_TO_DEPTH_DESWIZZLE, "565_to_depth"); + false, shader, "565_to_depth"); } } diff --git a/assets/compat.ini b/assets/compat.ini index c6011605d7..0903e52441 100644 --- a/assets/compat.ini +++ b/assets/compat.ini @@ -1266,3 +1266,13 @@ ULES00618 = true # Silver Fall ULES00808 = true ULUS10270 = true + +[DeswizzleDepth] +UCUS98633 = true +UCAS40145 = true +UCES00420 = true +UCJS10052 = true +UCKS45048 = true +UCJS18030 = true +UCJS18047 = true +NPJG00015 = true From 412d44dc9253943b34bdeb59acc97aee9919f0ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Sat, 20 Aug 2022 12:20:37 +0200 Subject: [PATCH 42/85] Fix glitch when changing render resolution --- GPU/Common/FramebufferManagerCommon.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/GPU/Common/FramebufferManagerCommon.cpp b/GPU/Common/FramebufferManagerCommon.cpp index 1bfdafb5eb..8bc5c9af03 100644 --- a/GPU/Common/FramebufferManagerCommon.cpp +++ b/GPU/Common/FramebufferManagerCommon.cpp @@ -1906,6 +1906,13 @@ void FramebufferManagerCommon::Resized() { // Might have a new post shader - let's compile it. presentation_->UpdatePostShader(); + // Reset all shaders that might have resolution compiled-in. + if (draw2DPipeline565ToDepthDeswizzle_) { + draw2DPipeline565ToDepthDeswizzle_->Release(); + draw2DPipeline565ToDepthDeswizzle_ = nullptr; + } + + #ifdef _WIN32 // Seems related - if you're ok with numbers all the time, show some more :) if (g_Config.iShowFPSCounter != 0) { From e2707d3ab393eaa9f084884b767d7919efeab224 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Sat, 20 Aug 2022 16:31:53 +0200 Subject: [PATCH 43/85] Remove debug code, cleanup --- GPU/Common/TextureCacheCommon.cpp | 6 ------ assets/compat.ini | 8 ++++---- 2 files changed, 4 insertions(+), 10 deletions(-) diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index 1c542633ca..bca4d6a9f4 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -525,10 +525,6 @@ TexCacheEntry *TextureCacheCommon::SetTexture() { def.format = format; def.bufw = bufw; - if (texaddr == 0x04710000) { - texaddr = texaddr; - } - std::vector candidates = GetFramebufferCandidates(def, 0); if (candidates.size() > 0) { int index = GetBestCandidateIndex(candidates); @@ -978,8 +974,6 @@ bool TextureCacheCommon::MatchFramebuffer( if (matchingClutFormat) { if (!noOffset) { WARN_LOG_ONCE(subareaClut, G3D, "Texturing from framebuffer (%s) using %s with offset at %08x +%dx%d", channel == RASTER_DEPTH ? "DEPTH" : "COLOR", GeTextureFormatToString(entry.format), fb_address, matchInfo->xOffset, matchInfo->yOffset); - } else { - WARN_LOG_ONCE(subareaClut, G3D, "Texturing from framebuffer (%s) using %s at %08x", channel == RASTER_DEPTH ? "DEPTH" : "COLOR", GeTextureFormatToString(entry.format), fb_address); } return true; } else if (IsClutFormat((GETextureFormat)(entry.format)) || IsDXTFormat((GETextureFormat)(entry.format))) { diff --git a/assets/compat.ini b/assets/compat.ini index 0903e52441..974a6216de 100644 --- a/assets/compat.ini +++ b/assets/compat.ini @@ -1102,6 +1102,10 @@ NPEH00029 = true ULUS10455 = true [BlueToAlpha] +# Some games render first to RGB of a 4444 texture, then they switch to 565 and render masked to blue, +# just to be able to render to the alpha channel of the 4444. We can detect that and reroute rendering +# to avoid problems. + # Split/Second ULES01402 = true ULUS10513 = true @@ -1121,10 +1125,6 @@ ULES00262 = true ULUS10064 = true ULKS46087 = true -# Some games render first to RGB of a 4444 texture, then they switch to 565 and render masked to blue, -# just to be able to render to the alpha channel of the 4444. We can detect that and reroute rendering -# to avoid problems. - [DateLimited] # Car Jack Streets - issue #12698 NPUZ00043 = true From ca24f1b9aab0d3d775f2382761a22381c47cf790 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Sat, 20 Aug 2022 16:32:04 +0200 Subject: [PATCH 44/85] Fixes for D3D11 --- Common/GPU/ShaderWriter.cpp | 16 ++++++++++++++++ Common/GPU/ShaderWriter.h | 3 ++- GPU/Common/Draw2D.cpp | 7 ++++++- GPU/Common/FramebufferManagerCommon.cpp | 2 ++ 4 files changed, 26 insertions(+), 2 deletions(-) diff --git a/Common/GPU/ShaderWriter.cpp b/Common/GPU/ShaderWriter.cpp index 900e2d1160..0332e4d346 100644 --- a/Common/GPU/ShaderWriter.cpp +++ b/Common/GPU/ShaderWriter.cpp @@ -423,3 +423,19 @@ ShaderWriter &ShaderWriter::SampleTexture2D(const char *sampName, const char *uv } return *this; } + +ShaderWriter &ShaderWriter::GetTextureSize(const char *szVariable, const char *texName) { + switch (lang_.shaderLanguage) { + case HLSL_D3D11: + F(" float2 %s; %s.GetDimensions(%s.x, %s.y);", szVariable, texName, szVariable, szVariable); + break; + case HLSL_D3D9: + F(" float2 %s; %s.GetDimensions(%s.x, %s.y);", szVariable, texName, szVariable, szVariable); + break; + default: + // Note: we ignore the sampler. make sure you bound samplers to the textures correctly. + F("vec2 %s = textureSize(%s, 0);", szVariable, texName); + break; + } + return *this; +} diff --git a/Common/GPU/ShaderWriter.h b/Common/GPU/ShaderWriter.h index f07d4159f5..1a1896c75b 100644 --- a/Common/GPU/ShaderWriter.h +++ b/Common/GPU/ShaderWriter.h @@ -83,7 +83,8 @@ public: void ConstFloat(const char *name, float value); - ShaderWriter &SampleTexture2D(const char *sampName, const char *uv); + ShaderWriter &SampleTexture2D(const char *texName, const char *uv); + ShaderWriter &GetTextureSize(const char *szVariable, const char *texName); // Simple shaders with no special tricks. void BeginVSMain(Slice inputs, Slice uniforms, Slice varyings); diff --git a/GPU/Common/Draw2D.cpp b/GPU/Common/Draw2D.cpp index 89292adfaf..7a6d0e60f2 100644 --- a/GPU/Common/Draw2D.cpp +++ b/GPU/Common/Draw2D.cpp @@ -70,6 +70,7 @@ RasterChannel GenerateDraw2D565ToDepthFs(ShaderWriter &writer) { writer.F(" highp float depthValue = (floor(rgb.x * 31.99) + floor(rgb.y * 63.99) * 32.0 + floor(rgb.z * 31.99) * 2048.0); \n"); writer.F(" gl_FragDepth = (depthValue / %f) + %f;\n", factors.scale, factors.offset); writer.EndFSMain("outColor", FSFLAG_WRITEDEPTH); + return RASTER_DEPTH; } @@ -83,7 +84,7 @@ RasterChannel GenerateDraw2D565ToDepthDeswizzleFs(ShaderWriter &writer) { // Unlike when just copying a depth buffer, here we're generating new depth values so we'll // have to apply the scaling. DepthScaleFactors factors = GetDepthScaleFactors(); - writer.C(" vec2 tsize = vec2(textureSize(tex, 0));\n"); + writer.GetTextureSize("tsize", "tex").C("\n"); writer.C(" vec2 coord = v_texcoord * tsize;\n"); writer.F(" float strip = 4.0 * %f;\n", g_scale); writer.C(" float in_strip = mod(coord.y, strip);\n"); @@ -255,4 +256,8 @@ void FramebufferManagerCommon::DrawStrip2D(Draw::Texture *tex, Draw2DVertex *ver } draw_->BindSamplerStates(TEX_SLOT_PSP_TEXTURE, 1, linearFilter ? &draw2DSamplerLinear_ : &draw2DSamplerNearest_); draw_->DrawUP(verts, vertexCount); + + draw_->InvalidateCachedState(); + + gstate_c.Dirty(DIRTY_FRAGMENTSHADER_STATE | DIRTY_VERTEXSHADER_STATE); } diff --git a/GPU/Common/FramebufferManagerCommon.cpp b/GPU/Common/FramebufferManagerCommon.cpp index 8bc5c9af03..8e82cc83f1 100644 --- a/GPU/Common/FramebufferManagerCommon.cpp +++ b/GPU/Common/FramebufferManagerCommon.cpp @@ -552,6 +552,8 @@ void FramebufferManagerCommon::CopyToDepthFromOverlappingFramebuffers(VirtualFra // for (auto &source : sources) { if (!sources.empty()) { + draw_->InvalidateCachedState(); + auto &source = sources.back(); if (source.channel == RASTER_DEPTH) { // Good old depth->depth copy. From 9cc8cfaa082c113f4af18d48e0394d7b63fc7756 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Sat, 20 Aug 2022 16:57:02 +0200 Subject: [PATCH 45/85] Use a DX9-compatible method to pass texwidth and height. the effect doesn't work on DX9 yet though. --- GPU/Common/Draw2D.cpp | 27 +++++++++++++++++++++---- GPU/Common/FramebufferManagerCommon.cpp | 2 +- GPU/Common/FramebufferManagerCommon.h | 2 +- 3 files changed, 25 insertions(+), 6 deletions(-) diff --git a/GPU/Common/Draw2D.cpp b/GPU/Common/Draw2D.cpp index 7a6d0e60f2..9c045ecfe0 100644 --- a/GPU/Common/Draw2D.cpp +++ b/GPU/Common/Draw2D.cpp @@ -40,6 +40,20 @@ static const SamplerDef samplers[1] = { { "tex" }, }; +static const UniformDef uniforms[1] = { + { "vec2", "texSize", 0 }, +}; + +struct Draw2DUB { + float texSizeX; + float texSizeY; +}; + +const UniformBufferDesc draw2DUBDesc{ sizeof(Draw2DUB), { + { "texSize", -1, 0, UniformType::FLOAT2, 0 }, +} }; + + RasterChannel GenerateDraw2DFs(ShaderWriter &writer) { writer.DeclareSamplers(samplers); writer.BeginFSMain(Slice::empty(), varyings, FSFLAG_NONE); @@ -79,12 +93,12 @@ static float g_scale; RasterChannel GenerateDraw2D565ToDepthDeswizzleFs(ShaderWriter &writer) { writer.DeclareSamplers(samplers); - writer.BeginFSMain(Slice::empty(), varyings, FSFLAG_WRITEDEPTH); + writer.BeginFSMain(uniforms, varyings, FSFLAG_WRITEDEPTH); writer.C(" vec4 outColor = vec4(0.0, 0.0, 0.0, 0.0);\n"); // Unlike when just copying a depth buffer, here we're generating new depth values so we'll // have to apply the scaling. DepthScaleFactors factors = GetDepthScaleFactors(); - writer.GetTextureSize("tsize", "tex").C("\n"); + writer.C(" vec2 tsize = texSize;\n"); writer.C(" vec2 coord = v_texcoord * tsize;\n"); writer.F(" float strip = 4.0 * %f;\n", g_scale); writer.C(" float in_strip = mod(coord.y, strip);\n"); @@ -183,7 +197,7 @@ Draw::Pipeline *FramebufferManagerCommon::Create2DPipeline(RasterChannel (*gener { draw2DVs_, fs }, inputLayout, depthStencil, - blend, rasterNoCull, nullptr, + blend, rasterNoCull, &draw2DUBDesc, }; Draw::Pipeline *pipeline = draw_->CreateGraphicsPipeline(pipelineDesc); @@ -198,7 +212,7 @@ Draw::Pipeline *FramebufferManagerCommon::Create2DPipeline(RasterChannel (*gener return pipeline; } -void FramebufferManagerCommon::DrawStrip2D(Draw::Texture *tex, Draw2DVertex *verts, int vertexCount, bool linearFilter, Draw2DShader shader) { +void FramebufferManagerCommon::DrawStrip2D(Draw::Texture *tex, Draw2DVertex *verts, int vertexCount, bool linearFilter, Draw2DShader shader, float texW, float texH) { using namespace Draw; Ensure2DResources(); @@ -251,6 +265,11 @@ void FramebufferManagerCommon::DrawStrip2D(Draw::Texture *tex, Draw2DVertex *ver break; } + Draw2DUB ub; + ub.texSizeX = tex ? tex->Width() : texW; + ub.texSizeY = tex ? tex->Height() : texH; + draw_->UpdateDynamicUniformBuffer(&ub, sizeof(ub)); + if (tex) { draw_->BindTextures(TEX_SLOT_PSP_TEXTURE, 1, &tex); } diff --git a/GPU/Common/FramebufferManagerCommon.cpp b/GPU/Common/FramebufferManagerCommon.cpp index 8e82cc83f1..aec33f43a8 100644 --- a/GPU/Common/FramebufferManagerCommon.cpp +++ b/GPU/Common/FramebufferManagerCommon.cpp @@ -2566,7 +2566,7 @@ void FramebufferManagerCommon::BlitUsingRaster( Draw::Viewport vp{ 0.0f, 0.0f, (float)dest->Width(), (float)dest->Height(), 0.0f, 1.0f }; draw_->SetViewports(1, &vp); draw_->SetScissorRect(0, 0, (int)dest->Width(), (int)dest->Height()); - DrawStrip2D(nullptr, vtx, 4, linearFilter, shader); + DrawStrip2D(nullptr, vtx, 4, linearFilter, shader, src->Width(), src->Height()); gstate_c.Dirty(DIRTY_BLEND_STATE | DIRTY_DEPTHSTENCIL_STATE | DIRTY_RASTER_STATE | DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_VERTEXSHADER_STATE | DIRTY_FRAGMENTSHADER_STATE); } diff --git a/GPU/Common/FramebufferManagerCommon.h b/GPU/Common/FramebufferManagerCommon.h index ce5a31a87a..f63b319c36 100644 --- a/GPU/Common/FramebufferManagerCommon.h +++ b/GPU/Common/FramebufferManagerCommon.h @@ -375,7 +375,7 @@ protected: Draw::Texture *MakePixelTexture(const u8 *srcPixels, GEBufferFormat srcPixelFormat, int srcStride, int width, int height); void DrawActiveTexture(float x, float y, float w, float h, float destW, float destH, float u0, float v0, float u1, float v1, int uvRotation, int flags); - void DrawStrip2D(Draw::Texture *tex, Draw2DVertex *verts, int vertexCount, bool linearFilter, Draw2DShader channel); + void DrawStrip2D(Draw::Texture *tex, Draw2DVertex *verts, int vertexCount, bool linearFilter, Draw2DShader channel, float texW = 0.0f, float texH = 0.0f); void Ensure2DResources(); Draw::Pipeline *Create2DPipeline(RasterChannel (*generate)(ShaderWriter &)); From 668de1f5448277ed5eb228f7290ab4fac5b64199 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Sat, 20 Aug 2022 16:58:59 +0200 Subject: [PATCH 46/85] Compatibility check --- GPU/Common/FramebufferManagerCommon.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GPU/Common/FramebufferManagerCommon.cpp b/GPU/Common/FramebufferManagerCommon.cpp index aec33f43a8..db493407ff 100644 --- a/GPU/Common/FramebufferManagerCommon.cpp +++ b/GPU/Common/FramebufferManagerCommon.cpp @@ -560,7 +560,7 @@ void FramebufferManagerCommon::CopyToDepthFromOverlappingFramebuffers(VirtualFra BlitFramebufferDepth(source.vfb, dest); gpuStats.numDepthCopies++; dest->last_frame_depth_updated = gpuStats.numFlips; - } else if (source.channel == RASTER_COLOR) { + } else if (source.channel == RASTER_COLOR && draw_->GetDeviceCaps().fragmentShaderDepthWriteSupported) { VirtualFramebuffer *src = source.vfb; if (src->drawnFormat != GE_FORMAT_565) { WARN_LOG_ONCE(not565, G3D, "Drawn format of buffer at %08x not 565 as expected", src->fb_address); From 80772dd18edd30da5a8ee11270fcf74c85943725 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Sun, 21 Aug 2022 08:46:32 +0200 Subject: [PATCH 47/85] Remove leftover resolutionScale depal config parameter --- GPU/Common/DepalettizeCommon.cpp | 1 - GPU/Common/DepalettizeShaderCommon.h | 1 - 2 files changed, 2 deletions(-) diff --git a/GPU/Common/DepalettizeCommon.cpp b/GPU/Common/DepalettizeCommon.cpp index 4d395a2d4a..185eecdbc4 100644 --- a/GPU/Common/DepalettizeCommon.cpp +++ b/GPU/Common/DepalettizeCommon.cpp @@ -173,7 +173,6 @@ DepalShader *DepalShaderCache::GetDepalettizeShader(uint32_t clutMode, GETexture config.mask = gstate.getClutIndexMask(); config.bufferFormat = bufferFormat; config.textureFormat = textureFormat; - config.resolutionScale = 3; GenerateDepalFs(buffer, config, draw_->GetShaderLanguageDesc()); diff --git a/GPU/Common/DepalettizeShaderCommon.h b/GPU/Common/DepalettizeShaderCommon.h index c4577be920..74bb38d196 100644 --- a/GPU/Common/DepalettizeShaderCommon.h +++ b/GPU/Common/DepalettizeShaderCommon.h @@ -31,7 +31,6 @@ struct DepalConfig { GEPaletteFormat clutFormat; GETextureFormat textureFormat; GEBufferFormat bufferFormat; - int resolutionScale; }; void GenerateDepalFs(char *buffer, const DepalConfig &config, const ShaderLanguageDesc &lang); From 8e7cf596b6e612e761e517c1c97e5e9774599b15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Sun, 21 Aug 2022 08:53:34 +0200 Subject: [PATCH 48/85] Address more feedback, cleanup scale parameter --- GPU/Common/Draw2D.cpp | 18 +++++++++--------- GPU/Common/FramebufferManagerCommon.cpp | 7 ------- 2 files changed, 9 insertions(+), 16 deletions(-) diff --git a/GPU/Common/Draw2D.cpp b/GPU/Common/Draw2D.cpp index 9c045ecfe0..663ff2cc90 100644 --- a/GPU/Common/Draw2D.cpp +++ b/GPU/Common/Draw2D.cpp @@ -40,17 +40,20 @@ static const SamplerDef samplers[1] = { { "tex" }, }; -static const UniformDef uniforms[1] = { +static const UniformDef uniforms[2] = { { "vec2", "texSize", 0 }, + { "float", "scaleFactor", 1}, }; struct Draw2DUB { float texSizeX; float texSizeY; + float scaleFactor; }; const UniformBufferDesc draw2DUBDesc{ sizeof(Draw2DUB), { { "texSize", -1, 0, UniformType::FLOAT2, 0 }, + { "scaleFactor", -1, 1, UniformType::FLOAT1, 0 }, } }; @@ -88,9 +91,6 @@ RasterChannel GenerateDraw2D565ToDepthFs(ShaderWriter &writer) { return RASTER_DEPTH; } -// ugly way to get the scale into the function -static float g_scale; - RasterChannel GenerateDraw2D565ToDepthDeswizzleFs(ShaderWriter &writer) { writer.DeclareSamplers(samplers); writer.BeginFSMain(uniforms, varyings, FSFLAG_WRITEDEPTH); @@ -100,7 +100,7 @@ RasterChannel GenerateDraw2D565ToDepthDeswizzleFs(ShaderWriter &writer) { DepthScaleFactors factors = GetDepthScaleFactors(); writer.C(" vec2 tsize = texSize;\n"); writer.C(" vec2 coord = v_texcoord * tsize;\n"); - writer.F(" float strip = 4.0 * %f;\n", g_scale); + writer.F(" float strip = 4.0 * scaleFactor;\n"); writer.C(" float in_strip = mod(coord.y, strip);\n"); writer.C(" coord.y = coord.y - in_strip + strip - in_strip;\n"); writer.C(" coord /= tsize;\n"); @@ -234,8 +234,8 @@ void FramebufferManagerCommon::DrawStrip2D(Draw::Texture *tex, Draw2DVertex *ver } if (!draw2DPipelineDepth_) { draw2DPipelineDepth_ = Create2DPipeline(&GenerateDraw2DDepthFs); - linearFilter = false; } + linearFilter = false; draw_->BindPipeline(draw2DPipelineDepth_); break; @@ -246,8 +246,8 @@ void FramebufferManagerCommon::DrawStrip2D(Draw::Texture *tex, Draw2DVertex *ver } if (!draw2DPipeline565ToDepth_) { draw2DPipeline565ToDepth_ = Create2DPipeline(&GenerateDraw2D565ToDepthFs); - linearFilter = false; } + linearFilter = false; draw_->BindPipeline(draw2DPipeline565ToDepth_); break; @@ -257,10 +257,9 @@ void FramebufferManagerCommon::DrawStrip2D(Draw::Texture *tex, Draw2DVertex *ver return; } if (!draw2DPipeline565ToDepthDeswizzle_) { - g_scale = renderScaleFactor_; draw2DPipeline565ToDepthDeswizzle_ = Create2DPipeline(&GenerateDraw2D565ToDepthDeswizzleFs); - linearFilter = false; } + linearFilter = false; draw_->BindPipeline(draw2DPipeline565ToDepthDeswizzle_); break; } @@ -268,6 +267,7 @@ void FramebufferManagerCommon::DrawStrip2D(Draw::Texture *tex, Draw2DVertex *ver Draw2DUB ub; ub.texSizeX = tex ? tex->Width() : texW; ub.texSizeY = tex ? tex->Height() : texH; + ub.scaleFactor = (float)renderScaleFactor_; draw_->UpdateDynamicUniformBuffer(&ub, sizeof(ub)); if (tex) { diff --git a/GPU/Common/FramebufferManagerCommon.cpp b/GPU/Common/FramebufferManagerCommon.cpp index db493407ff..bfdc23815f 100644 --- a/GPU/Common/FramebufferManagerCommon.cpp +++ b/GPU/Common/FramebufferManagerCommon.cpp @@ -1908,13 +1908,6 @@ void FramebufferManagerCommon::Resized() { // Might have a new post shader - let's compile it. presentation_->UpdatePostShader(); - // Reset all shaders that might have resolution compiled-in. - if (draw2DPipeline565ToDepthDeswizzle_) { - draw2DPipeline565ToDepthDeswizzle_->Release(); - draw2DPipeline565ToDepthDeswizzle_ = nullptr; - } - - #ifdef _WIN32 // Seems related - if you're ok with numbers all the time, show some more :) if (g_Config.iShowFPSCounter != 0) { From a11e7e167bfed310f2d9af25620a4293f8c4b1b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Sun, 21 Aug 2022 09:57:19 +0200 Subject: [PATCH 49/85] More D3D9 work on depth textures. Something still missing. --- GPU/Common/DepalettizeShaderCommon.cpp | 16 +++++++++++++++- GPU/Common/TextureCacheCommon.cpp | 1 - GPU/Directx9/GPU_DX9.cpp | 1 + 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/GPU/Common/DepalettizeShaderCommon.cpp b/GPU/Common/DepalettizeShaderCommon.cpp index 11c3c50394..af2bf13437 100644 --- a/GPU/Common/DepalettizeShaderCommon.cpp +++ b/GPU/Common/DepalettizeShaderCommon.cpp @@ -152,6 +152,8 @@ void GenerateDepalShaderFloat(ShaderWriter &writer, const DepalConfig &config, c writer.ConstFloat("z_offset", factors.offset); } + writer.C(" vec4 index = ").SampleTexture2D("tex", "v_texcoord").C(";\n"); + float index_multiplier = 1.0f; // pixelformat is the format of the texture we are sampling. bool formatOK = true; @@ -233,6 +235,19 @@ void GenerateDepalShaderFloat(ShaderWriter &writer, const DepalConfig &config, c case GE_FORMAT_DEPTH16: { // TODO: I think we can handle most scenarios here, but texturing from depth buffers requires an extension on ES 2.0 anyway. + // Not on D3D9 though, so this path is still relevant. + + if (config.bufferFormat == GE_FORMAT_DEPTH16 && config.textureFormat == GE_TFMT_5650) { + // Convert depth to 565, without going through a CLUT. + writer.C(" float depth = (index.x - z_offset) * z_scale;\n"); + writer.C(" float idepth = floor(clamp(depth, 0.0, 65535.0));\n"); + writer.C(" float r = mod(idepth, 32.0) / 31.0f;\n"); + writer.C(" float g = mod(floor(idepth / 32.0), 64.0) / 63.0f;\n"); + writer.C(" float b = mod(floor(idepth / 2048.0), 32.0) / 31.0f;\n"); + writer.C(" vec4 outColor = vec4(r, g, b, 1.0);\n"); + return; + } + if (shift < 16) { index_multiplier = 1.0f / (float)(1 << shift); truncate_cpy(lookupMethod, "((index.x - z_offset) * z_scale)"); @@ -269,7 +284,6 @@ void GenerateDepalShaderFloat(ShaderWriter &writer, const DepalConfig &config, c char offset[128] = ""; sprintf(offset, " + %f", texel_offset); - writer.C(" vec4 index = ").SampleTexture2D("tex", "v_texcoord").C(";\n"); writer.F(" float coord = (%s * %f)%s;\n", lookupMethod, index_multiplier, offset); writer.C(" vec4 outColor = ").SampleTexture2D("pal", "vec2(coord, 0.0)").C(";\n"); } diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index bca4d6a9f4..e4a8c9cd33 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -1863,7 +1863,6 @@ void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer // TODO: Implement shader depal in the fragment shader generator for D3D11 at least. if (!draw_->GetDeviceCaps().fragmentShaderInt32Supported) { useShaderDepal = false; - depth = false; // Can't support this } switch (draw_->GetShaderLanguageDesc().shaderLanguage) { diff --git a/GPU/Directx9/GPU_DX9.cpp b/GPU/Directx9/GPU_DX9.cpp index c3f4476fcb..b36cb34288 100644 --- a/GPU/Directx9/GPU_DX9.cpp +++ b/GPU/Directx9/GPU_DX9.cpp @@ -160,6 +160,7 @@ void GPU_DX9::CheckGPUFeatures() { u32 features = 0; features |= GPU_SUPPORTS_16BIT_FORMATS; features |= GPU_SUPPORTS_BLEND_MINMAX; + features |= GPU_SUPPORTS_DEPTH_TEXTURE; features |= GPU_SUPPORTS_TEXTURE_LOD_CONTROL; // Accurate depth is required because the Direct3D API does not support inverse Z. From 6715f41410976d081d0ff45fe28e544343723f42 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sun, 21 Aug 2022 12:44:35 -0700 Subject: [PATCH 50/85] irjit: Add constructs for validing mem access. Basically to allow slow/fast memory to work with IR, including for alignment checks. --- Core/MIPS/IR/IRFrontend.cpp | 1 + Core/MIPS/IR/IRInst.cpp | 5 +++++ Core/MIPS/IR/IRInst.h | 7 ++++++ Core/MIPS/IR/IRInterpreter.cpp | 38 +++++++++++++++++++++++++++++++++ Core/MIPS/IR/IRPassSimplify.cpp | 26 ++++++++++++++++++++++ Core/MIPS/IR/IRPassSimplify.h | 1 + 6 files changed, 78 insertions(+) diff --git a/Core/MIPS/IR/IRFrontend.cpp b/Core/MIPS/IR/IRFrontend.cpp index c3a2df444a..71fdea7eb6 100644 --- a/Core/MIPS/IR/IRFrontend.cpp +++ b/Core/MIPS/IR/IRFrontend.cpp @@ -264,6 +264,7 @@ void IRFrontend::DoJit(u32 em_address, std::vector &instructions, u32 &m &OptimizeFPMoves, &PropagateConstants, &PurgeTemps, + &ApplyMemoryValidation, // &ReorderLoadStore, // &MergeLoadStore, // &ThreeOpToTwoOp, diff --git a/Core/MIPS/IR/IRInst.cpp b/Core/MIPS/IR/IRInst.cpp index b8339896e7..13b2509f18 100644 --- a/Core/MIPS/IR/IRInst.cpp +++ b/Core/MIPS/IR/IRInst.cpp @@ -163,6 +163,11 @@ static const IRMeta irMeta[] = { { IROp::Breakpoint, "Breakpoint", "", IRFLAG_EXIT }, { IROp::MemoryCheck, "MemoryCheck", "_GC", IRFLAG_EXIT }, + { IROp::ValidateAddress8, "ValidAddr8", "_GC", IRFLAG_EXIT }, + { IROp::ValidateAddress16, "ValidAddr16", "_GC", IRFLAG_EXIT }, + { IROp::ValidateAddress32, "ValidAddr32", "_GC", IRFLAG_EXIT }, + { IROp::ValidateAddress128, "ValidAddr128", "_GC", IRFLAG_EXIT }, + { IROp::RestoreRoundingMode, "RestoreRoundingMode", "" }, { IROp::ApplyRoundingMode, "ApplyRoundingMode", "" }, { IROp::UpdateRoundingMode, "UpdateRoundingMode", "" }, diff --git a/Core/MIPS/IR/IRInst.h b/Core/MIPS/IR/IRInst.h index 1e2b6c1410..8c7b67b00a 100644 --- a/Core/MIPS/IR/IRInst.h +++ b/Core/MIPS/IR/IRInst.h @@ -213,8 +213,15 @@ enum class IROp : u8 { SetPCConst, // hack to make replacement know PC CallReplacement, Break, + + // Debugging breakpoints. Breakpoint, MemoryCheck, + + ValidateAddress8, + ValidateAddress16, + ValidateAddress32, + ValidateAddress128, }; enum IRComparison { diff --git a/Core/MIPS/IR/IRInterpreter.cpp b/Core/MIPS/IR/IRInterpreter.cpp index 8538748a21..363a52cd31 100644 --- a/Core/MIPS/IR/IRInterpreter.cpp +++ b/Core/MIPS/IR/IRInterpreter.cpp @@ -79,6 +79,19 @@ u32 RunMemCheck(u32 pc, u32 addr) { return coreState != CORE_RUNNING ? 1 : 0; } +template +u32 RunValidateAddress(u32 pc, u32 addr) { + if (!Memory::IsValidRange(addr, alignment)) { + Core_MemoryException(addr, pc, MemoryExceptionType::UNKNOWN); + return coreState != CORE_RUNNING ? 1 : 0; + } + if (alignment > 1 && (addr & (alignment - 1)) != 0) { + Core_MemoryException(addr, pc, MemoryExceptionType::UNKNOWN); + return coreState != CORE_RUNNING ? 1 : 0; + } + return 0; +} + // We cannot use NEON on ARM32 here until we make it a hard dependency. We can, however, on ARM64. u32 IRInterpret(MIPSState *mips, const IRInst *inst, int count) { const IRInst *end = inst + count; @@ -142,6 +155,31 @@ u32 IRInterpret(MIPSState *mips, const IRInst *inst, int count) { mips->r[inst->dest] = ReverseBits32(mips->r[inst->src1]); break; + case IROp::ValidateAddress8: + if (RunValidateAddress<1>(mips->pc, mips->r[inst->src1] + inst->constant)) { + CoreTiming::ForceCheck(); + return mips->pc; + } + break; + case IROp::ValidateAddress16: + if (RunValidateAddress<2>(mips->pc, mips->r[inst->src1] + inst->constant)) { + CoreTiming::ForceCheck(); + return mips->pc; + } + break; + case IROp::ValidateAddress32: + if (RunValidateAddress<4>(mips->pc, mips->r[inst->src1] + inst->constant)) { + CoreTiming::ForceCheck(); + return mips->pc; + } + break; + case IROp::ValidateAddress128: + if (RunValidateAddress<16>(mips->pc, mips->r[inst->src1] + inst->constant)) { + CoreTiming::ForceCheck(); + return mips->pc; + } + break; + case IROp::Load8: mips->r[inst->dest] = Memory::ReadUnchecked_U8(mips->r[inst->src1] + inst->constant); break; diff --git a/Core/MIPS/IR/IRPassSimplify.cpp b/Core/MIPS/IR/IRPassSimplify.cpp index 80aa692f86..24f2d8cfda 100644 --- a/Core/MIPS/IR/IRPassSimplify.cpp +++ b/Core/MIPS/IR/IRPassSimplify.cpp @@ -5,6 +5,7 @@ #include "Common/BitSet.h" #include "Common/Data/Convert/SmallDataConvert.h" #include "Common/Log.h" +#include "Core/Config.h" #include "Core/MIPS/IR/IRInterpreter.h" #include "Core/MIPS/IR/IRPassSimplify.h" #include "Core/MIPS/IR/IRRegCache.h" @@ -622,6 +623,18 @@ bool PropagateConstants(const IRWriter &in, IRWriter &out, const IROptions &opts } break; + case IROp::ValidateAddress8: + case IROp::ValidateAddress16: + case IROp::ValidateAddress32: + case IROp::ValidateAddress128: + if (gpr.IsImm(inst.src1)) { + out.Write(inst.op, inst.dest, 0, out.AddConstant(gpr.GetImm(inst.src1) + inst.constant)); + } else { + gpr.MapIn(inst.src1); + goto doDefault; + } + break; + case IROp::Downcount: case IROp::SetPCConst: goto doDefault; @@ -1428,3 +1441,16 @@ bool MergeLoadStore(const IRWriter &in, IRWriter &out, const IROptions &opts) { } return logBlocks; } + +bool ApplyMemoryValidation(const IRWriter &in, IRWriter &out, const IROptions &opts) { + CONDITIONAL_DISABLE; + if (g_Config.bFastMemory) + DISABLE; + + bool logBlocks = false; + for (IRInst inst : in.GetInstructions()) { + // TODO + out.Write(inst); + } + return logBlocks; +} diff --git a/Core/MIPS/IR/IRPassSimplify.h b/Core/MIPS/IR/IRPassSimplify.h index e3020a4f61..7fdc5d1c7d 100644 --- a/Core/MIPS/IR/IRPassSimplify.h +++ b/Core/MIPS/IR/IRPassSimplify.h @@ -14,3 +14,4 @@ bool ThreeOpToTwoOp(const IRWriter &in, IRWriter &out, const IROptions &opts); bool OptimizeFPMoves(const IRWriter &in, IRWriter &out, const IROptions &opts); bool ReorderLoadStore(const IRWriter &in, IRWriter &out, const IROptions &opts); bool MergeLoadStore(const IRWriter &in, IRWriter &out, const IROptions &opts); +bool ApplyMemoryValidation(const IRWriter &in, IRWriter &out, const IROptions &opts); From 90517ace59f0c092c850c472882944bc572b6774 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sun, 21 Aug 2022 13:24:10 -0700 Subject: [PATCH 51/85] irjit: Validate alignment in slow memory mode. --- Core/Core.cpp | 1 + Core/Core.h | 1 + Core/MIPS/IR/IRCompVFPU.cpp | 4 +++ Core/MIPS/IR/IRFrontend.cpp | 2 +- Core/MIPS/IR/IRInterpreter.cpp | 24 +++++++++++------- Core/MIPS/IR/IRPassSimplify.cpp | 44 ++++++++++++++++++++++++++++++++- 6 files changed, 65 insertions(+), 11 deletions(-) diff --git a/Core/Core.cpp b/Core/Core.cpp index 5fb5357352..e723107d30 100644 --- a/Core/Core.cpp +++ b/Core/Core.cpp @@ -419,6 +419,7 @@ const char *MemoryExceptionTypeAsString(MemoryExceptionType type) { case MemoryExceptionType::WRITE_WORD: return "Write Word"; case MemoryExceptionType::READ_BLOCK: return "Read Block"; case MemoryExceptionType::WRITE_BLOCK: return "Read/Write Block"; + case MemoryExceptionType::ALIGNMENT: return "Alignment"; default: return "N/A"; } diff --git a/Core/Core.h b/Core/Core.h index 62018b832d..894accd6ae 100644 --- a/Core/Core.h +++ b/Core/Core.h @@ -93,6 +93,7 @@ enum class MemoryExceptionType { WRITE_WORD, READ_BLOCK, WRITE_BLOCK, + ALIGNMENT, }; enum class ExecExceptionType { JUMP, diff --git a/Core/MIPS/IR/IRCompVFPU.cpp b/Core/MIPS/IR/IRCompVFPU.cpp index 2a5e00a861..4fffc6765d 100644 --- a/Core/MIPS/IR/IRCompVFPU.cpp +++ b/Core/MIPS/IR/IRCompVFPU.cpp @@ -330,6 +330,8 @@ namespace MIPSComp { ir.Write(IROp::LoadVec4, vregs[0], rs, ir.AddConstant(imm)); } else { // Let's not even bother with "vertical" loads for now. + if (!g_Config.bFastMemory) + ir.Write({ IROp::ValidateAddress128, { 0 }, (u8)rs, 0, (u32)imm }); ir.Write(IROp::LoadFloat, vregs[0], rs, ir.AddConstant(imm)); ir.Write(IROp::LoadFloat, vregs[1], rs, ir.AddConstant(imm + 4)); ir.Write(IROp::LoadFloat, vregs[2], rs, ir.AddConstant(imm + 8)); @@ -342,6 +344,8 @@ namespace MIPSComp { ir.Write(IROp::StoreVec4, vregs[0], rs, ir.AddConstant(imm)); } else { // Let's not even bother with "vertical" stores for now. + if (!g_Config.bFastMemory) + ir.Write({ IROp::ValidateAddress128, { 0 }, (u8)rs, 1, (u32)imm }); ir.Write(IROp::StoreFloat, vregs[0], rs, ir.AddConstant(imm)); ir.Write(IROp::StoreFloat, vregs[1], rs, ir.AddConstant(imm + 4)); ir.Write(IROp::StoreFloat, vregs[2], rs, ir.AddConstant(imm + 8)); diff --git a/Core/MIPS/IR/IRFrontend.cpp b/Core/MIPS/IR/IRFrontend.cpp index 71fdea7eb6..66a3efbafe 100644 --- a/Core/MIPS/IR/IRFrontend.cpp +++ b/Core/MIPS/IR/IRFrontend.cpp @@ -260,11 +260,11 @@ void IRFrontend::DoJit(u32 em_address, std::vector &instructions, u32 &m IRWriter *code = &ir; if (!js.hadBreakpoints) { static const IRPassFunc passes[] = { + &ApplyMemoryValidation, &RemoveLoadStoreLeftRight, &OptimizeFPMoves, &PropagateConstants, &PurgeTemps, - &ApplyMemoryValidation, // &ReorderLoadStore, // &MergeLoadStore, // &ThreeOpToTwoOp, diff --git a/Core/MIPS/IR/IRInterpreter.cpp b/Core/MIPS/IR/IRInterpreter.cpp index 363a52cd31..bc97b52b73 100644 --- a/Core/MIPS/IR/IRInterpreter.cpp +++ b/Core/MIPS/IR/IRInterpreter.cpp @@ -80,14 +80,20 @@ u32 RunMemCheck(u32 pc, u32 addr) { } template -u32 RunValidateAddress(u32 pc, u32 addr) { - if (!Memory::IsValidRange(addr, alignment)) { - Core_MemoryException(addr, pc, MemoryExceptionType::UNKNOWN); +u32 RunValidateAddress(u32 pc, u32 addr, u32 isWrite) { + const auto toss = [&](MemoryExceptionType t) { + Core_MemoryException(addr, pc, t); return coreState != CORE_RUNNING ? 1 : 0; + }; + + if (!Memory::IsValidRange(addr, alignment)) { + MemoryExceptionType t = isWrite == 1 ? MemoryExceptionType::WRITE_WORD : MemoryExceptionType::READ_WORD; + if (alignment > 4) + t = isWrite ? MemoryExceptionType::WRITE_BLOCK : MemoryExceptionType::READ_BLOCK; + return toss(t); } if (alignment > 1 && (addr & (alignment - 1)) != 0) { - Core_MemoryException(addr, pc, MemoryExceptionType::UNKNOWN); - return coreState != CORE_RUNNING ? 1 : 0; + return toss(MemoryExceptionType::ALIGNMENT); } return 0; } @@ -156,25 +162,25 @@ u32 IRInterpret(MIPSState *mips, const IRInst *inst, int count) { break; case IROp::ValidateAddress8: - if (RunValidateAddress<1>(mips->pc, mips->r[inst->src1] + inst->constant)) { + if (RunValidateAddress<1>(mips->pc, mips->r[inst->src1] + inst->constant, inst->src2)) { CoreTiming::ForceCheck(); return mips->pc; } break; case IROp::ValidateAddress16: - if (RunValidateAddress<2>(mips->pc, mips->r[inst->src1] + inst->constant)) { + if (RunValidateAddress<2>(mips->pc, mips->r[inst->src1] + inst->constant, inst->src2)) { CoreTiming::ForceCheck(); return mips->pc; } break; case IROp::ValidateAddress32: - if (RunValidateAddress<4>(mips->pc, mips->r[inst->src1] + inst->constant)) { + if (RunValidateAddress<4>(mips->pc, mips->r[inst->src1] + inst->constant, inst->src2)) { CoreTiming::ForceCheck(); return mips->pc; } break; case IROp::ValidateAddress128: - if (RunValidateAddress<16>(mips->pc, mips->r[inst->src1] + inst->constant)) { + if (RunValidateAddress<16>(mips->pc, mips->r[inst->src1] + inst->constant, inst->src2)) { CoreTiming::ForceCheck(); return mips->pc; } diff --git a/Core/MIPS/IR/IRPassSimplify.cpp b/Core/MIPS/IR/IRPassSimplify.cpp index 24f2d8cfda..5725454841 100644 --- a/Core/MIPS/IR/IRPassSimplify.cpp +++ b/Core/MIPS/IR/IRPassSimplify.cpp @@ -1447,9 +1447,51 @@ bool ApplyMemoryValidation(const IRWriter &in, IRWriter &out, const IROptions &o if (g_Config.bFastMemory) DISABLE; + const auto addValidate = [&out](IROp validate, const IRInst &inst, bool isStore) { + out.Write({ validate, { 0 }, inst.src1, isStore ? (u8)1 : (u8)0, inst.constant }); + }; + + // TODO: Could be smart about not double-validating an address that has a load / store, etc. bool logBlocks = false; for (IRInst inst : in.GetInstructions()) { - // TODO + switch (inst.op) { + case IROp::Load8: + case IROp::Load8Ext: + case IROp::Store8: + addValidate(IROp::ValidateAddress8, inst, inst.op == IROp::Store8); + break; + + case IROp::Load16: + case IROp::Load16Ext: + case IROp::Store16: + addValidate(IROp::ValidateAddress16, inst, inst.op == IROp::Store16); + break; + + case IROp::Load32: + case IROp::LoadFloat: + case IROp::Store32: + case IROp::StoreFloat: + addValidate(IROp::ValidateAddress32, inst, inst.op == IROp::Store32 || inst.op == IROp::StoreFloat); + break; + + case IROp::LoadVec4: + case IROp::StoreVec4: + addValidate(IROp::ValidateAddress128, inst, inst.op == IROp::StoreVec4); + break; + + case IROp::Load32Left: + case IROp::Load32Right: + case IROp::Store32Left: + case IROp::Store32Right: + // This explicitly does not require alignment, so validate as an 8-bit operation. + addValidate(IROp::ValidateAddress8, inst, inst.op == IROp::Store32Left || inst.op == IROp::Store32Right); + break; + + default: + break; + } + + // Always write out the original. We're only adding. out.Write(inst); } return logBlocks; From 80e481bbdc4dd562714d3c395710c5a25f957279 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sun, 21 Aug 2022 14:00:15 -0700 Subject: [PATCH 52/85] Core: Show exception on misaligned jump. --- Core/HLE/sceKernelThread.cpp | 38 +++++++++++------------------ Core/MIPS/ARM/ArmCompBranch.cpp | 2 +- Core/MIPS/ARM64/Arm64CompBranch.cpp | 2 +- Core/MIPS/IR/IRJit.cpp | 5 ++-- Core/MIPS/MIPSInt.cpp | 3 +-- Core/MIPS/x86/CompBranch.cpp | 2 +- Core/MIPS/x86/Jit.cpp | 12 ++++++--- 7 files changed, 30 insertions(+), 34 deletions(-) diff --git a/Core/HLE/sceKernelThread.cpp b/Core/HLE/sceKernelThread.cpp index 57f62944f4..86a234cd3b 100644 --- a/Core/HLE/sceKernelThread.cpp +++ b/Core/HLE/sceKernelThread.cpp @@ -1086,6 +1086,12 @@ void __KernelStartIdleThreads(SceUID moduleId) } } +void KernelValidateThreadTarget(uint32_t pc) { + if (!Memory::IsValidAddress(pc) || (pc & 3) != 0) { + Core_ExecException(pc, currentMIPS->pc, ExecExceptionType::THREAD); + } +} + bool __KernelSwitchOffThread(const char *reason) { if (!reason) @@ -1141,9 +1147,7 @@ bool __KernelSwitchToThread(SceUID threadID, const char *reason) if (current && current->isRunning()) __KernelChangeReadyState(current, currentThread, true); - if (!Memory::IsValidAddress(t->context.pc)) { - Core_ExecException(t->context.pc, currentMIPS->pc, ExecExceptionType::THREAD); - } + KernelValidateThreadTarget(t->context.pc); __KernelSwitchContext(t, reason); return true; @@ -1471,9 +1475,7 @@ void __KernelLoadContext(PSPThreadContext *ctx, bool vfpuEnabled) { memcpy(currentMIPS->vfpuCtrl, ctx->vfpuCtrl, sizeof(ctx->vfpuCtrl)); } - if (!Memory::IsValidAddress(ctx->pc)) { - Core_ExecException(ctx->pc, currentMIPS->pc, ExecExceptionType::THREAD); - } + KernelValidateThreadTarget(ctx->pc); memcpy(currentMIPS->other, ctx->other, sizeof(ctx->other)); // Not locking here, we assume the jit isn't switched during execution. @@ -1924,9 +1926,7 @@ SceUID __KernelSetupRootThread(SceUID moduleID, int args, const char *argp, int strcpy(thread->nt.name, "root"); - if (!Memory::IsValidAddress(thread->context.pc)) { - Core_ExecException(thread->context.pc, currentMIPS->pc, ExecExceptionType::THREAD); - } + KernelValidateThreadTarget(thread->context.pc); __KernelLoadContext(&thread->context, (attr & PSP_THREAD_ATTR_VFPU) != 0); currentMIPS->r[MIPS_REG_A0] = args; @@ -2057,9 +2057,7 @@ int __KernelStartThread(SceUID threadToStartID, int argSize, u32 argBlockPtr, bo // Smaller is better for priority. Only switch if the new thread is better. if (cur && cur->nt.currentPriority > startThread->nt.currentPriority) { - if (!Memory::IsValidAddress(startThread->context.pc)) { - Core_ExecException(startThread->context.pc, currentMIPS->pc, ExecExceptionType::THREAD); - } + KernelValidateThreadTarget(startThread->context.pc); __KernelChangeReadyState(cur, currentThread, true); if (__InterruptsEnabled()) hleReSchedule("thread started"); @@ -2939,9 +2937,7 @@ u32 sceKernelExtendThreadStack(u32 size, u32 entryAddr, u32 entryParameter) Memory::Write_U32(currentMIPS->r[MIPS_REG_SP], thread->currentStack.end - 8); Memory::Write_U32(currentMIPS->pc, thread->currentStack.end - 12); - if (!Memory::IsValidAddress(entryAddr)) { - Core_ExecException(entryAddr, currentMIPS->pc, ExecExceptionType::THREAD); - } + KernelValidateThreadTarget(entryAddr); currentMIPS->pc = entryAddr; currentMIPS->r[MIPS_REG_A0] = entryParameter; @@ -2975,9 +2971,7 @@ void __KernelReturnFromExtendStack() return; } - if (!Memory::IsValidAddress(restorePC)) { - Core_ExecException(restorePC, currentMIPS->pc, ExecExceptionType::THREAD); - } + KernelValidateThreadTarget(restorePC); DEBUG_LOG(SCEKERNEL, "__KernelReturnFromExtendStack()"); currentMIPS->r[MIPS_REG_RA] = restoreRA; @@ -3259,9 +3253,7 @@ bool __KernelExecuteMipsCallOnCurrentThread(u32 callId, bool reschedAfter) call->savedId = cur->currentMipscallId; call->reschedAfter = reschedAfter; - if (!Memory::IsValidAddress(call->entryPoint)) { - Core_ExecException(call->entryPoint, currentMIPS->pc, ExecExceptionType::THREAD); - } + KernelValidateThreadTarget(call->entryPoint); // Set up the new state currentMIPS->pc = call->entryPoint; @@ -3312,9 +3304,7 @@ void __KernelReturnFromMipsCall() currentMIPS->r[MIPS_REG_RA] = Memory::Read_U32(sp + MIPS_REG_RA * 4); sp += 32 * 4; - if (!Memory::IsValidAddress(call->savedPc)) { - Core_ExecException(call->savedPc, currentMIPS->pc, ExecExceptionType::THREAD); - } + KernelValidateThreadTarget(call->savedPc); currentMIPS->pc = call->savedPc; // This is how we set the return value. diff --git a/Core/MIPS/ARM/ArmCompBranch.cpp b/Core/MIPS/ARM/ArmCompBranch.cpp index bf687c045d..ec3d180be9 100644 --- a/Core/MIPS/ARM/ArmCompBranch.cpp +++ b/Core/MIPS/ARM/ArmCompBranch.cpp @@ -466,7 +466,7 @@ void ArmJit::Comp_Jump(MIPSOpcode op) { u32 targetAddr = (GetCompilerPC() & 0xF0000000) | off; // Might be a stubbed address or something? - if (!Memory::IsValidAddress(targetAddr)) { + if (!Memory::IsValidAddress(targetAddr) || (targetAddr & 3) != 0) { if (js.nextExit == 0) { ERROR_LOG_REPORT(JIT, "Jump to invalid address: %08x", targetAddr); } else { diff --git a/Core/MIPS/ARM64/Arm64CompBranch.cpp b/Core/MIPS/ARM64/Arm64CompBranch.cpp index ee86994211..026cf539e3 100644 --- a/Core/MIPS/ARM64/Arm64CompBranch.cpp +++ b/Core/MIPS/ARM64/Arm64CompBranch.cpp @@ -481,7 +481,7 @@ void Arm64Jit::Comp_Jump(MIPSOpcode op) { u32 targetAddr = (GetCompilerPC() & 0xF0000000) | off; // Might be a stubbed address or something? - if (!Memory::IsValidAddress(targetAddr)) { + if (!Memory::IsValidAddress(targetAddr) || (targetAddr & 3) != 0) { if (js.nextExit == 0) { ERROR_LOG_REPORT(JIT, "Jump to invalid address: %08x", targetAddr); } else { diff --git a/Core/MIPS/IR/IRJit.cpp b/Core/MIPS/IR/IRJit.cpp index f029f56731..66608fc86f 100644 --- a/Core/MIPS/IR/IRJit.cpp +++ b/Core/MIPS/IR/IRJit.cpp @@ -227,9 +227,10 @@ void IRJit::RunLoopUntil(u64 globalticks) { if (opcode == MIPS_EMUHACK_OPCODE) { u32 data = inst & 0xFFFFFF; IRBlock *block = blocks_.GetBlock(data); + u32 startPC = mips_->pc; mips_->pc = IRInterpret(mips_, block->GetInstructions(), block->GetNumInstructions()); - if (!Memory::IsValidAddress(mips_->pc)) { - Core_ExecException(mips_->pc, mips_->pc, ExecExceptionType::JUMP); + if (!Memory::IsValidAddress(mips_->pc) || (mips_->pc & 3) != 0) { + Core_ExecException(mips_->pc, startPC, ExecExceptionType::JUMP); break; } } else { diff --git a/Core/MIPS/MIPSInt.cpp b/Core/MIPS/MIPSInt.cpp index 305041ecb6..99cad4df3e 100644 --- a/Core/MIPS/MIPSInt.cpp +++ b/Core/MIPS/MIPSInt.cpp @@ -57,8 +57,7 @@ static inline void DelayBranchTo(u32 where) { - if (!Memory::IsValidAddress(where)) { - // TODO: What about misaligned? + if (!Memory::IsValidAddress(where) || (where & 3) != 0) { Core_ExecException(where, PC, ExecExceptionType::JUMP); } PC += 4; diff --git a/Core/MIPS/x86/CompBranch.cpp b/Core/MIPS/x86/CompBranch.cpp index 835768bf96..9bd167d2e2 100644 --- a/Core/MIPS/x86/CompBranch.cpp +++ b/Core/MIPS/x86/CompBranch.cpp @@ -612,7 +612,7 @@ void Jit::Comp_Jump(MIPSOpcode op) { u32 targetAddr = (GetCompilerPC() & 0xF0000000) | off; // Might be a stubbed address or something? - if (!Memory::IsValidAddress(targetAddr)) { + if (!Memory::IsValidAddress(targetAddr) || (targetAddr & 3) != 0) { if (js.nextExit == 0) { ERROR_LOG_REPORT(JIT, "Jump to invalid address: %08x PC %08x LR %08x", targetAddr, GetCompilerPC(), currentMIPS->r[MIPS_REG_RA]); } else { diff --git a/Core/MIPS/x86/Jit.cpp b/Core/MIPS/x86/Jit.cpp index 5c3f2121f9..c27ee3b502 100644 --- a/Core/MIPS/x86/Jit.cpp +++ b/Core/MIPS/x86/Jit.cpp @@ -275,7 +275,7 @@ void Jit::Compile(u32 em_address) { ClearCache(); } - if (!Memory::IsValidAddress(em_address)) { + if (!Memory::IsValidAddress(em_address) || (em_address & 3) != 0) { Core_ExecException(em_address, em_address, ExecExceptionType::JUMP); return; } @@ -672,7 +672,7 @@ static void HitInvalidBranch(uint32_t dest) { void Jit::WriteExit(u32 destination, int exit_num) { _dbg_assert_msg_(exit_num < MAX_JIT_BLOCK_EXITS, "Expected a valid exit_num"); - if (!Memory::IsValidAddress(destination)) { + if (!Memory::IsValidAddress(destination) || (destination & 3) != 0) { ERROR_LOG_REPORT(JIT, "Trying to write block exit to illegal destination %08x: pc = %08x", destination, currentMIPS->pc); MOV(32, MIPSSTATE_VAR(pc), Imm32(GetCompilerPC())); ABI_CallFunctionC(&HitInvalidBranch, destination); @@ -721,6 +721,12 @@ void Jit::WriteExit(u32 destination, int exit_num) { } } +static u32 IsValidJumpTarget(uint32_t addr) { + if (Memory::IsValidAddress(addr) && (addr & 3) == 0) + return 1; + return 0; +} + static void HitInvalidJumpReg(uint32_t source) { Core_ExecException(currentMIPS->pc, source, ExecExceptionType::JUMP); currentMIPS->pc = source + 8; @@ -762,7 +768,7 @@ void Jit::WriteExitDestInReg(X64Reg reg) { SetJumpTarget(tooLow); SetJumpTarget(tooHigh); - ABI_CallFunctionA((const void *)&Memory::IsValidAddress, R(reg)); + ABI_CallFunctionA((const void *)&IsValidJumpTarget, R(reg)); // If we're ignoring, coreState didn't trip - so trip it now. CMP(32, R(EAX), Imm32(0)); From 8e7847f6d959e25b7cda3ebe9289c85594a44215 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sun, 21 Aug 2022 14:09:52 -0700 Subject: [PATCH 53/85] UI: Show return address for exec crashes. --- Core/Core.cpp | 7 +++++-- Core/Core.h | 3 ++- Core/MIPS/IR/IRInterpreter.cpp | 2 +- Core/MIPS/MIPSInt.cpp | 2 +- UI/EmuScreen.cpp | 17 +++++++++++++---- 5 files changed, 22 insertions(+), 9 deletions(-) diff --git a/Core/Core.cpp b/Core/Core.cpp index e723107d30..52a1df8f4c 100644 --- a/Core/Core.cpp +++ b/Core/Core.cpp @@ -487,16 +487,19 @@ void Core_ExecException(u32 address, u32 pc, ExecExceptionType type) { e.exec_type = type; e.address = address; e.pc = pc; - Core_EnableStepping(true, "cpu.exception", pc); + // This just records the closest value that could be useful as reference. + e.ra = currentMIPS->r[MIPS_REG_RA]; + Core_EnableStepping(true, "cpu.exception", address); } -void Core_Break() { +void Core_Break(u32 pc) { ERROR_LOG(CPU, "BREAK!"); ExceptionInfo &e = g_exceptionInfo; e = {}; e.type = ExceptionType::BREAK; e.info = ""; + e.pc = pc; if (!g_Config.bIgnoreBadMemAccess) { Core_EnableStepping(true, "cpu.breakInstruction", currentMIPS->pc); diff --git a/Core/Core.h b/Core/Core.h index 894accd6ae..d706e7afec 100644 --- a/Core/Core.h +++ b/Core/Core.h @@ -106,7 +106,7 @@ void Core_MemoryException(u32 address, u32 pc, MemoryExceptionType type); void Core_MemoryExceptionInfo(u32 address, u32 pc, MemoryExceptionType type, std::string additionalInfo); void Core_ExecException(u32 address, u32 pc, ExecExceptionType type); -void Core_Break(); +void Core_Break(u32 pc); // Call when loading save states, etc. void Core_ResetException(); @@ -125,6 +125,7 @@ struct ExceptionInfo { MemoryExceptionType memory_type; uint32_t pc; uint32_t address; + uint32_t ra = 0; // Reuses pc and address from memory type, where address is the failed destination. ExecExceptionType exec_type; diff --git a/Core/MIPS/IR/IRInterpreter.cpp b/Core/MIPS/IR/IRInterpreter.cpp index bc97b52b73..27b0ba0ca3 100644 --- a/Core/MIPS/IR/IRInterpreter.cpp +++ b/Core/MIPS/IR/IRInterpreter.cpp @@ -998,7 +998,7 @@ u32 IRInterpret(MIPSState *mips, const IRInst *inst, int count) { } case IROp::Break: - Core_Break(); + Core_Break(mips->pc); return mips->pc + 4; case IROp::SetCtrlVFPU: diff --git a/Core/MIPS/MIPSInt.cpp b/Core/MIPS/MIPSInt.cpp index 99cad4df3e..46585b69a9 100644 --- a/Core/MIPS/MIPSInt.cpp +++ b/Core/MIPS/MIPSInt.cpp @@ -157,7 +157,7 @@ namespace MIPSInt void Int_Break(MIPSOpcode op) { Reporting::ReportMessage("BREAK instruction hit"); - Core_Break(); + Core_Break(PC); PC += 4; } diff --git a/UI/EmuScreen.cpp b/UI/EmuScreen.cpp index aa08576467..1b98b91bb8 100644 --- a/UI/EmuScreen.cpp +++ b/UI/EmuScreen.cpp @@ -1209,16 +1209,25 @@ PC: %08x } else if (info.type == ExceptionType::BAD_EXEC_ADDR) { snprintf(statbuf, sizeof(statbuf), R"( Destination: %s to %08x -PC: %08x)", +PC: %08x +RA: %08x)", ExecExceptionTypeAsString(info.exec_type), info.address, - info.pc); + info.pc, + info.ra); + ctx->Draw()->DrawTextShadow(ubuntu24, statbuf, x, y, 0xFFFFFFFF); + y += 180; + } else if (info.type == ExceptionType::BREAK) { + snprintf(statbuf, sizeof(statbuf), R"( +BREAK +PC: %08x +)", info.pc); ctx->Draw()->DrawTextShadow(ubuntu24, statbuf, x, y, 0xFFFFFFFF); y += 180; } else { snprintf(statbuf, sizeof(statbuf), R"( -BREAK -)"); +Invalid / Unknown (%d) +)", (int)info.type); ctx->Draw()->DrawTextShadow(ubuntu24, statbuf, x, y, 0xFFFFFFFF); y += 180; } From 1b72311e7dc7216032816b0b982955a1e4c1ec7a Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sun, 21 Aug 2022 15:51:56 -0700 Subject: [PATCH 54/85] Headless: Fix comparison for oversized buffers. At least when not flipping. --- headless/Compare.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/headless/Compare.cpp b/headless/Compare.cpp index 890ff6cc6a..f5127e5ee0 100644 --- a/headless/Compare.cpp +++ b/headless/Compare.cpp @@ -326,7 +326,7 @@ std::vector TranslateDebugBufferToCompare(const GPUDebugBuffer *buffer, u32 int outStride = buffer->GetStride(); if (!buffer->GetFlipped()) { // Bitmaps are flipped, so we have to compare backwards in this case. - int toLastRow = outStride * (buffer->GetHeight() - 1); + int toLastRow = outStride * (h > buffer->GetHeight() ? buffer->GetHeight() - 1 : h - 1); pixels32 += toLastRow; pixels16 += toLastRow; outStride = -outStride; From 05ad644c690a048fbc0627c916071d7d38bec99b Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sun, 21 Aug 2022 15:52:18 -0700 Subject: [PATCH 55/85] Headless: Set softgpu config flag. This affects dump playback (whether it updates RAM with what's in the frame dump), so it's confusing when it's not set matching the core. --- headless/Headless.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/headless/Headless.cpp b/headless/Headless.cpp index bb8a0225b7..cad0c9fb20 100644 --- a/headless/Headless.cpp +++ b/headless/Headless.cpp @@ -416,6 +416,7 @@ int main(int argc, const char* argv[]) g_Config.bEnableLogging = fullLog; g_Config.bSoftwareSkinning = true; g_Config.bVertexDecoderJit = true; + g_Config.bSoftwareRendering = coreParameter.gpuCore == GPUCORE_SOFTWARE; g_Config.bSoftwareRenderingJit = true; g_Config.bBlockTransferGPU = true; g_Config.iSplineBezierQuality = 2; From afc9a14b375068ceff4c57ff6f40a5f8dfb01d6c Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sun, 21 Aug 2022 16:46:51 -0700 Subject: [PATCH 56/85] GPU: Share CLUTs if no extended CLUT. Oops, this was backwards. See #15878. --- GPU/Common/TextureCacheCommon.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index e4a8c9cd33..72839eb97a 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -1670,7 +1670,7 @@ CheckAlphaResult TextureCacheCommon::ReadIndexedTex(u8 *out, int outPitch, int l // Misshitsu no Sacrifice has separate CLUT data, this is a hack to allow it. // Normally separate CLUTs are not allowed for 8-bit or higher indices. - const bool mipmapShareClut = gstate.isClutSharedForMipmaps() && gstate.getClutLoadBlocks() == 0x40; + const bool mipmapShareClut = gstate.isClutSharedForMipmaps() || gstate.getClutLoadBlocks() != 0x40; const int clutSharingOffset = mipmapShareClut ? 0 : (level & 1) * 256; GEPaletteFormat palFormat = (GEPaletteFormat)gstate.getClutPaletteFormat(); From 89a499b4d2f0c2587551d94a4bc925a6f34ef052 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sun, 21 Aug 2022 16:47:46 -0700 Subject: [PATCH 57/85] GLES: Correct preview of mip levels > 0. Don't need to force level 0 anymore. Software can show levels hardware refuses to load. This is consistent with other backends. --- GPU/D3D11/TextureCacheD3D11.cpp | 2 ++ GPU/GLES/TextureCacheGLES.cpp | 15 --------------- GPU/Vulkan/TextureCacheVulkan.cpp | 2 ++ 3 files changed, 4 insertions(+), 15 deletions(-) diff --git a/GPU/D3D11/TextureCacheD3D11.cpp b/GPU/D3D11/TextureCacheD3D11.cpp index 55917a7c24..2fea477610 100644 --- a/GPU/D3D11/TextureCacheD3D11.cpp +++ b/GPU/D3D11/TextureCacheD3D11.cpp @@ -465,6 +465,8 @@ bool TextureCacheD3D11::GetCurrentTextureDebug(GPUDebugBuffer &buffer, int level gstate_c.Dirty(DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_BLEND_STATE | DIRTY_DEPTHSTENCIL_STATE); // We may have blitted to a temp FBO. framebufferManager_->RebindFramebuffer("RebindFramebuffer - GetCurrentTextureDebug"); + if (!retval) + ERROR_LOG(G3D, "Failed to get debug texture: copy to memory failed"); return retval; } else { return false; diff --git a/GPU/GLES/TextureCacheGLES.cpp b/GPU/GLES/TextureCacheGLES.cpp index beb89c6b43..fb3c1a01b3 100644 --- a/GPU/GLES/TextureCacheGLES.cpp +++ b/GPU/GLES/TextureCacheGLES.cpp @@ -382,19 +382,8 @@ Draw::DataFormat TextureCacheGLES::GetDestFormat(GETextureFormat format, GEPalet } bool TextureCacheGLES::GetCurrentTextureDebug(GPUDebugBuffer &buffer, int level) { - GPUgstate saved; - if (level != 0) { - saved = gstate; - - // The way we set textures is a bit complex. Let's just override level 0. - gstate.texsize[0] = gstate.texsize[level]; - gstate.texaddr[0] = gstate.texaddr[level]; - gstate.texbufwidth[0] = gstate.texbufwidth[level]; - } - InvalidateLastTexture(); SetTexture(); - if (!nextTexture_) { if (nextFramebufferTexture_) { VirtualFramebuffer *vfb = nextFramebufferTexture_; @@ -427,10 +416,6 @@ bool TextureCacheGLES::GetCurrentTextureDebug(GPUDebugBuffer &buffer, int level) int w = gstate.getTextureWidth(level); int h = gstate.getTextureHeight(level); - if (level != 0) { - gstate = saved; - } - bool result = entry->textureName != nullptr; if (result) { buffer.Allocate(w, h, GE_FORMAT_8888, false); diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index 51ca567183..ba860c1be5 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -777,6 +777,8 @@ bool TextureCacheVulkan::GetCurrentTextureDebug(GPUDebugBuffer &buffer, int leve gstate_c.Dirty(DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_BLEND_STATE | DIRTY_DEPTHSTENCIL_STATE); // We may have blitted to a temp FBO. framebufferManager_->RebindFramebuffer("RebindFramebuffer - GetCurrentTextureDebug"); + if (!retval) + ERROR_LOG(G3D, "Failed to get debug texture: copy to memory failed"); return retval; } else { return false; From 4924b22b511f0badfce97d9d6703a80c1c718a3c Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sun, 21 Aug 2022 19:00:10 -0700 Subject: [PATCH 58/85] Linux: Consider Vulkan if OpenGL init fails. --- Core/Config.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Core/Config.cpp b/Core/Config.cpp index 4c5d312bf2..e7ec5d1e5a 100644 --- a/Core/Config.cpp +++ b/Core/Config.cpp @@ -748,7 +748,7 @@ int Config::NextValidBackend() { if (failed.count((GPUBackend)iGPUBackend)) { ERROR_LOG(LOADER, "Graphics backend failed for %d, trying another", iGPUBackend); -#if (PPSSPP_PLATFORM(WINDOWS) || PPSSPP_PLATFORM(ANDROID)) && !PPSSPP_PLATFORM(UWP) +#if !PPSSPP_PLATFORM(UWP) if (!failed.count(GPUBackend::VULKAN) && VulkanMayBeAvailable()) { return (int)GPUBackend::VULKAN; } @@ -797,6 +797,9 @@ bool Config::IsBackendEnabled(GPUBackend backend, bool validate) { #if PPSSPP_PLATFORM(UWP) if (backend != GPUBackend::DIRECT3D11) return false; +#elif PPSSPP_PLATFORM(SWITCH) + if (backend != GPUBackend::OPENGL) + return false; #elif PPSSPP_PLATFORM(WINDOWS) if (validate) { if (backend == GPUBackend::DIRECT3D11 && !DoesVersionMatchWindows(6, 0, 0, 0, true)) From 842bf86b1a6c8315cf4675549f55f77d03b06d59 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sun, 21 Aug 2022 19:05:51 -0700 Subject: [PATCH 59/85] Config: Default PSP model to SLIM on all platforms. --- Core/Config.cpp | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/Core/Config.cpp b/Core/Config.cpp index e7ec5d1e5a..1949ecf426 100644 --- a/Core/Config.cpp +++ b/Core/Config.cpp @@ -1116,15 +1116,6 @@ static ConfigSetting networkSettings[] = { ConfigSetting(false), }; -static int DefaultPSPModel() { - // TODO: Can probably default this on, but not sure about its memory differences. -#if !PPSSPP_ARCH(AMD64) && !defined(_WIN32) - return PSP_MODEL_FAT; -#else - return PSP_MODEL_SLIM; -#endif -} - static int DefaultSystemParamLanguage() { int defaultLang = PSP_SYSTEMPARAM_LANGUAGE_ENGLISH; if (g_Config.bFirstRun) { @@ -1138,7 +1129,7 @@ static int DefaultSystemParamLanguage() { } static ConfigSetting systemParamSettings[] = { - ReportedConfigSetting("PSPModel", &g_Config.iPSPModel, &DefaultPSPModel, true, true), + ReportedConfigSetting("PSPModel", &g_Config.iPSPModel, PSP_MODEL_SLIM, true, true), ReportedConfigSetting("PSPFirmwareVersion", &g_Config.iFirmwareVersion, PSP_DEFAULT_FIRMWARE, true, true), ConfigSetting("NickName", &g_Config.sNickName, "PPSSPP", true, true), ConfigSetting("MacAddress", &g_Config.sMACAddress, "", true, true), From c13f57e64f02fb429b1a95ef33f0795db8b2aa11 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sun, 21 Aug 2022 19:40:02 -0700 Subject: [PATCH 60/85] Vulkan: Cleanup minor logging. --- Common/GPU/Vulkan/VulkanContext.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Common/GPU/Vulkan/VulkanContext.cpp b/Common/GPU/Vulkan/VulkanContext.cpp index 23a854dd8e..1a938a5235 100644 --- a/Common/GPU/Vulkan/VulkanContext.cpp +++ b/Common/GPU/Vulkan/VulkanContext.cpp @@ -684,7 +684,7 @@ VkResult VulkanContext::CreateDevice() { } else { VulkanLoadDeviceFunctions(device_, extensionsLookup_); } - INFO_LOG(G3D, "Device created.\n"); + INFO_LOG(G3D, "Vulkan Device created"); VulkanSetAvailable(true); VmaAllocatorCreateInfo allocatorInfo = {}; From 73c06bb77605415648c9b92102e78bc4ad4d7b07 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sun, 21 Aug 2022 22:03:16 -0700 Subject: [PATCH 61/85] Replacement: Be more consistent about base level. --- GPU/Vulkan/TextureCacheVulkan.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index 51ca567183..b85339a4bc 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -464,7 +464,7 @@ void TextureCacheVulkan::BuildTexture(TexCacheEntry *const entry) { // Any texture scaling is gonna move away from the original 16-bit format, if any. VkFormat actualFmt = plan.scaleFactor > 1 ? VULKAN_8888_FORMAT : dstFmt; if (plan.replaced->Valid()) { - actualFmt = ToVulkanFormat(plan.replaced->Format(0)); + actualFmt = ToVulkanFormat(plan.replaced->Format(plan.baseLevelSrc)); } bool computeUpload = false; @@ -565,7 +565,7 @@ void TextureCacheVulkan::BuildTexture(TexCacheEntry *const entry) { int mipWidth = mipUnscaledWidth * plan.scaleFactor; int mipHeight = mipUnscaledHeight * plan.scaleFactor; if (plan.replaced->Valid()) { - plan.replaced->GetSize(i, mipWidth, mipHeight); + plan.replaced->GetSize(plan.baseLevelSrc + i, mipWidth, mipHeight); } int bpp = actualFmt == VULKAN_8888_FORMAT ? 4 : 2; // output bpp @@ -595,7 +595,7 @@ void TextureCacheVulkan::BuildTexture(TexCacheEntry *const entry) { // Directly load the replaced image. data = drawEngine_->GetPushBufferForTextureData()->PushAligned(size, &bufferOffset, &texBuf, pushAlignment); double replaceStart = time_now_d(); - plan.replaced->Load(i, data, stride); // if it fails, it'll just be garbage data... OK for now. + plan.replaced->Load(plan.baseLevelSrc + i, data, stride); // if it fails, it'll just be garbage data... OK for now. replacementTimeThisFrame_ += time_now_d() - replaceStart; VK_PROFILE_BEGIN(vulkan, cmdInit, VK_PIPELINE_STAGE_TRANSFER_BIT, "Copy Upload (replaced): %dx%d", mipWidth, mipHeight); @@ -636,7 +636,7 @@ void TextureCacheVulkan::BuildTexture(TexCacheEntry *const entry) { int w = dataScaled ? mipWidth : mipUnscaledWidth; int h = dataScaled ? mipHeight : mipUnscaledHeight; // At this point, data should be saveData, and not slow. - replacer_.NotifyTextureDecoded(replacedInfo, data, stride, i, w, h); + replacer_.NotifyTextureDecoded(replacedInfo, data, stride, plan.baseLevelSrc + i, w, h); } } } From e473eb9f5e98222f49f17083719ae7e13396c9b1 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sun, 21 Aug 2022 22:07:05 -0700 Subject: [PATCH 62/85] Replacement: Read files only within time budget. When delayed texture load is enabled. Intended to reduce IO delays on Android. --- Core/TextureReplacer.cpp | 34 ++++++++++++++++++++++--------- Core/TextureReplacer.h | 24 ++++++++++++++++++---- GPU/Common/TextureCacheCommon.cpp | 29 ++++++++++++++++---------- GPU/Vulkan/TextureCacheVulkan.cpp | 2 +- 4 files changed, 63 insertions(+), 26 deletions(-) diff --git a/Core/TextureReplacer.cpp b/Core/TextureReplacer.cpp index 48c9905e38..c0b965e9b1 100644 --- a/Core/TextureReplacer.cpp +++ b/Core/TextureReplacer.cpp @@ -49,7 +49,8 @@ static const int VERSION = 1; static const int MAX_MIP_LEVELS = 12; // 12 should be plenty, 8 is the max mip levels supported by the PSP. TextureReplacer::TextureReplacer() { - none_.alphaStatus_ = ReplacedTextureAlpha::UNKNOWN; + none_.initDone_ = true; + none_.prepareDone_ = true; } TextureReplacer::~TextureReplacer() { @@ -373,7 +374,7 @@ u32 TextureReplacer::ComputeHash(u32 addr, int bufw, int w, int h, GETextureForm } } -ReplacedTexture &TextureReplacer::FindReplacement(u64 cachekey, u32 hash, int w, int h) { +ReplacedTexture &TextureReplacer::FindReplacement(u64 cachekey, u32 hash, int w, int h, double budget) { // Only actually replace if we're replacing. We might just be saving. if (!Enabled() || !g_Config.bReplaceTextures) { return none_; @@ -382,13 +383,18 @@ ReplacedTexture &TextureReplacer::FindReplacement(u64 cachekey, u32 hash, int w, ReplacementCacheKey replacementKey(cachekey, hash); auto it = cache_.find(replacementKey); if (it != cache_.end()) { + if (!it->second.prepareDone_ && budget > 0.0) { + // We don't do this on a thread, but we only do it while within budget. + PopulateReplacement(&it->second, cachekey, hash, w, h); + } return it->second; } // Okay, let's construct the result. ReplacedTexture &result = cache_[replacementKey]; - result.alphaStatus_ = ReplacedTextureAlpha::UNKNOWN; - PopulateReplacement(&result, cachekey, hash, w, h); + if (!g_Config.bReplaceTexturesAllowLate || budget > 0.0) { + PopulateReplacement(&result, cachekey, hash, w, h); + } return result; } @@ -433,7 +439,7 @@ void TextureReplacer::PopulateReplacement(ReplacedTexture *result, u64 cachekey, break; } - result->alphaStatus_ = ReplacedTextureAlpha::UNKNOWN; + result->prepareDone_ = true; } enum class ReplacedImageType { @@ -815,11 +821,13 @@ bool ReplacedTexture::IsReady(double budget) { } // Loaded already, or not yet on a thread? - if (!levelData_.empty()) + if (initDone_ && !levelData_.empty()) return true; // Let's not even start a new texture if we're already behind. if (budget < 0.0) return false; + if (!prepareDone_) + return false; if (g_Config.bReplaceTexturesAllowLate) { if (threadWaitable_) @@ -829,10 +837,11 @@ bool ReplacedTexture::IsReady(double budget) { if (threadWaitable_->WaitFor(budget)) { // If we finished all the levels, we're done. - return !levelData_.empty(); + return initDone_ && !levelData_.empty(); } } else { Prepare(); + _assert_(initDone_); return true; } @@ -842,16 +851,19 @@ bool ReplacedTexture::IsReady(double budget) { void ReplacedTexture::Prepare() { std::unique_lock lock(mutex_); - if (cancelPrepare_) + if (cancelPrepare_) { + initDone_ = true; return; + } - levelData_.resize(NumLevels()); - for (int i = 0; i < NumLevels(); ++i) { + levelData_.resize(levels_.size()); + for (int i = 0; i < (int)levels_.size(); ++i) { if (cancelPrepare_) break; PrepareData(i); } + initDone_ = true; if (!cancelPrepare_ && threadWaitable_) threadWaitable_->Notify(); } @@ -975,6 +987,8 @@ bool ReplacedTexture::Load(int level, void *out, int rowPitch) { _assert_msg_((size_t)level < levels_.size(), "Invalid miplevel"); _assert_msg_(out != nullptr && rowPitch > 0, "Invalid out/pitch"); + if (!initDone_) + return false; if (levelData_.empty()) return false; diff --git a/Core/TextureReplacer.h b/Core/TextureReplacer.h index e01a03d2a4..b32d31a7d3 100644 --- a/Core/TextureReplacer.h +++ b/Core/TextureReplacer.h @@ -118,10 +118,20 @@ struct ReplacedTexture { ~ReplacedTexture(); inline bool Valid() const { + if (!initDone_) + return false; return !levels_.empty(); } + inline bool IsInvalid() const { + if (!initDone_) + return false; + return levels_.empty(); + } + bool GetSize(int level, int &w, int &h) const { + if (!initDone_) + return false; if ((size_t)level < levels_.size()) { w = levels_[level].w; h = levels_[level].h; @@ -131,12 +141,16 @@ struct ReplacedTexture { } int NumLevels() const { + if (!initDone_) + return 0; return (int)levels_.size(); } Draw::DataFormat Format(int level) const { - if ((size_t)level < levels_.size()) { - return levels_[level].fmt; + if (initDone_) { + if ((size_t)level < levels_.size()) { + return levels_[level].fmt; + } } return Draw::DataFormat::R8G8B8A8_UNORM; } @@ -156,11 +170,13 @@ protected: std::vector levels_; std::vector> levelData_; - ReplacedTextureAlpha alphaStatus_; + ReplacedTextureAlpha alphaStatus_ = ReplacedTextureAlpha::UNKNOWN; double lastUsed_ = 0.0; LimitedWaitable *threadWaitable_ = nullptr; std::mutex mutex_; bool cancelPrepare_ = false; + bool initDone_ = false; + bool prepareDone_ = false; friend TextureReplacer; friend ReplacedTextureTask; @@ -196,7 +212,7 @@ public: u32 ComputeHash(u32 addr, int bufw, int w, int h, GETextureFormat fmt, u16 maxSeenV); - ReplacedTexture &FindReplacement(u64 cachekey, u32 hash, int w, int h); + ReplacedTexture &FindReplacement(u64 cachekey, u32 hash, int w, int h, double budget); bool FindFiltering(u64 cachekey, u32 hash, TextureFiltering *forceFiltering); ReplacedTexture &FindNone() { return none_; diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index e4a8c9cd33..55a44cef2f 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -482,7 +482,14 @@ TexCacheEntry *TextureCacheCommon::SetTexture() { int h0 = gstate.getTextureHeight(0); int d0 = 1; ReplacedTexture &replaced = FindReplacement(entry, w0, h0, d0); - if (replaced.Valid()) { + if (replaced.IsInvalid()) { + entry->status &= ~TexCacheEntry::STATUS_TO_REPLACE; + if (g_Config.bSaveNewTextures) { + // Load once more to actually save. + match = false; + reason = "replacing"; + } + } else { match = false; reason = "replacing"; } @@ -1303,22 +1310,22 @@ ReplacedTexture &TextureCacheCommon::FindReplacement(TexCacheEntry *entry, int & constexpr double MAX_BUDGET_PER_TEX = 0.25 / 60.0; double replaceStart = time_now_d(); + double budget = std::min(MAX_BUDGET_PER_TEX, replacementFrameBudget_ - replacementTimeThisFrame_); u64 cachekey = replacer_.Enabled() ? entry->CacheKey() : 0; - ReplacedTexture &replaced = replacer_.FindReplacement(cachekey, entry->fullhash, w, h); - if (replaced.IsReady(std::min(MAX_BUDGET_PER_TEX, replacementFrameBudget_ - replacementTimeThisFrame_))) { + ReplacedTexture &replaced = replacer_.FindReplacement(cachekey, entry->fullhash, w, h, budget); + if (replaced.IsReady(budget)) { if (replaced.GetSize(0, w, h)) { - replacementTimeThisFrame_ += time_now_d() - replaceStart; - - // Consider it already "scaled" and remove any delayed replace flag. + // Consider it already "scaled." entry->status |= TexCacheEntry::STATUS_IS_SCALED; - entry->status &= ~TexCacheEntry::STATUS_TO_REPLACE; - return replaced; } - } else if (replaced.Valid()) { + + // Remove the flag, even if it was invalid. + entry->status &= ~TexCacheEntry::STATUS_TO_REPLACE; + } else if (!replaced.IsInvalid()) { entry->status |= TexCacheEntry::STATUS_TO_REPLACE; } replacementTimeThisFrame_ += time_now_d() - replaceStart; - return replacer_.FindNone(); + return replaced; } // This is only used in the GLES backend, where we don't point these to video memory. @@ -2375,7 +2382,7 @@ void TextureCacheCommon::LoadTextureLevel(TexCacheEntry &entry, uint8_t *data, i } } - if (replacer_.Enabled()) { + if (replacer_.Enabled() && replaced.IsInvalid()) { ReplacedTextureDecodeInfo replacedInfo; replacedInfo.cachekey = entry.CacheKey(); replacedInfo.hash = entry.fullhash; diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index b85339a4bc..741f785c80 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -536,7 +536,7 @@ void TextureCacheVulkan::BuildTexture(TexCacheEntry *const entry) { ReplacedTextureDecodeInfo replacedInfo; bool willSaveTex = false; - if (replacer_.Enabled() && !plan.replaced->Valid() && plan.depth == 1) { + if (replacer_.Enabled() && plan.replaced->IsInvalid() && plan.depth == 1) { replacedInfo.cachekey = entry->CacheKey(); replacedInfo.hash = entry->fullhash; replacedInfo.addr = entry->addr; From 383adcb8706c307badb3ecb5fe0e69128a356814 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Mon, 22 Aug 2022 11:17:50 +0200 Subject: [PATCH 63/85] Simplify depal shader apply code a bit. --- GPU/Common/DepalettizeCommon.h | 65 +++++++------------------------ GPU/Common/TextureCacheCommon.cpp | 4 +- 2 files changed, 15 insertions(+), 54 deletions(-) diff --git a/GPU/Common/DepalettizeCommon.h b/GPU/Common/DepalettizeCommon.h index fbac86300d..6e3ef680ef 100644 --- a/GPU/Common/DepalettizeCommon.h +++ b/GPU/Common/DepalettizeCommon.h @@ -83,35 +83,18 @@ private: // TODO: Merge with DepalShaderCache? class TextureShaderApplier { public: - struct Pos { - float x; - float y; - }; - struct UV { - float u; - float v; - }; - TextureShaderApplier(Draw::DrawContext *draw, DepalShader *shader, float bufferW, float bufferH, int renderW, int renderH) : draw_(draw), shader_(shader), bufferW_(bufferW), bufferH_(bufferH), renderW_(renderW), renderH_(renderH) { - static const Pos pos[4] = { - {-1, -1 }, - { 1, -1 }, - {-1, 1 }, - { 1, 1 }, + static const Draw2DVertex defaultVerts[4] = { + {-1, -1, 0, 0 }, + { 1, -1, 1, 0 }, + {-1, 1, 0, 1 }, + { 1, 1, 1, 1 }, }; - memcpy(pos_, pos, sizeof(pos_)); - - static const UV uv[4] = { - { 0, 0 }, - { 1, 0 }, - { 0, 1 }, - { 1, 1 }, - }; - memcpy(uv_, uv, sizeof(uv_)); + memcpy(verts_, defaultVerts, sizeof(defaultVerts)); } - void ApplyBounds(const KnownVertexBounds &bounds, u32 uoff, u32 voff) { + void Shade(const KnownVertexBounds &bounds, u32 uoff, u32 voff) { // If min is not < max, then we don't have values (wasn't set during decode.) if (bounds.minV < bounds.maxV) { const float invWidth = 1.0f / bufferW_; @@ -129,41 +112,23 @@ public: const float right = u2 * invHalfWidth - 1.0f; const float top = v1 * invHalfHeight - 1.0f; const float bottom = v2 * invHalfHeight - 1.0f; - // Points are: BL, BR, TR, TL. - pos_[0] = Pos{ left, bottom }; - pos_[1] = Pos{ right, bottom }; - pos_[2] = Pos{ left, top }; - pos_[3] = Pos{ right, top }; - // And also the UVs, same order. const float uvleft = u1 * invWidth; const float uvright = u2 * invWidth; const float uvtop = v1 * invHeight; const float uvbottom = v2 * invHeight; - uv_[0] = UV{ uvleft, uvbottom }; - uv_[1] = UV{ uvright, uvbottom }; - uv_[2] = UV{ uvleft, uvtop }; - uv_[3] = UV{ uvright, uvtop }; + + // Points are: BL, BR, TR, TL. + verts_[0] = Draw2DVertex{ left, bottom, uvleft, uvbottom }; + verts_[1] = Draw2DVertex{ right, bottom, uvright, uvbottom }; + verts_[2] = Draw2DVertex{ left, top, uvleft, uvtop }; + verts_[3] = Draw2DVertex{ right, top, uvright, uvtop }; // We need to reapply the texture next time since we cropped UV. gstate_c.Dirty(DIRTY_TEXTURE_PARAMS); } - } - - void Use() { - draw_->BindPipeline(shader_->pipeline); - struct SimpleVertex { - float pos[2]; - float uv[2]; - }; - for (int i = 0; i < 4; i++) { - memcpy(&verts_[i].x, &pos_[i], sizeof(Pos)); - memcpy(&verts_[i].u, &uv_[i], sizeof(UV)); - } - } - - void Shade() { Draw::Viewport vp{ 0.0f, 0.0f, (float)renderW_, (float)renderH_, 0.0f, 1.0f }; + draw_->BindPipeline(shader_->pipeline); draw_->SetViewports(1, &vp); draw_->SetScissorRect(0, 0, renderW_, renderH_); draw_->DrawUP((const uint8_t *)verts_, 4); @@ -172,8 +137,6 @@ public: protected: Draw::DrawContext *draw_; DepalShader *shader_; - Pos pos_[4]; - UV uv_[4]; Draw2DVertex verts_[4]; float bufferW_; float bufferH_; diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index a5b2749d62..3022f1d1c4 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -1930,8 +1930,6 @@ void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer draw_->SetViewports(1, &vp); TextureShaderApplier shaderApply(draw_, depalShader, framebuffer->bufferWidth, framebuffer->bufferHeight, framebuffer->renderWidth, framebuffer->renderHeight); - shaderApply.ApplyBounds(gstate_c.vertBounds, gstate_c.curTextureXOffset, gstate_c.curTextureYOffset); - shaderApply.Use(); draw_->BindFramebufferAsTexture(framebuffer->fbo, 0, depth ? Draw::FB_DEPTH_BIT : Draw::FB_COLOR_BIT, 0); draw_->BindTexture(1, clutTexture); @@ -1939,7 +1937,7 @@ void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer draw_->BindSamplerStates(0, 1, &nearest); draw_->BindSamplerStates(1, 1, &nearest); - shaderApply.Shade(); + shaderApply.Shade(gstate_c.vertBounds, gstate_c.curTextureXOffset, gstate_c.curTextureYOffset); draw_->BindTexture(0, nullptr); framebufferManager_->RebindFramebuffer("ApplyTextureFramebuffer"); From 58a6fd3395fe9674a526d68098e5f9a070497ec1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Mon, 22 Aug 2022 11:45:52 +0200 Subject: [PATCH 64/85] Convert TextureShaderApplier to a member function in DepalCache. --- GPU/Common/DepalettizeCommon.cpp | 49 +++++++++++++++++++++++ GPU/Common/DepalettizeCommon.h | 66 +------------------------------ GPU/Common/TextureCacheCommon.cpp | 7 ++-- 3 files changed, 55 insertions(+), 67 deletions(-) diff --git a/GPU/Common/DepalettizeCommon.cpp b/GPU/Common/DepalettizeCommon.cpp index 185eecdbc4..f23e2607ba 100644 --- a/GPU/Common/DepalettizeCommon.cpp +++ b/GPU/Common/DepalettizeCommon.cpp @@ -243,3 +243,52 @@ std::string DepalShaderCache::DebugGetShaderString(std::string idstr, DebugShade return ""; } } + +// TODO: Merge with DepalShaderCache? +void DepalShaderCache::ApplyShader(DepalShader *shader, float bufferW, float bufferH, int renderW, int renderH, const KnownVertexBounds &bounds, u32 uoff, u32 voff) { + Draw2DVertex verts[4] = { + {-1, -1, 0, 0 }, + { 1, -1, 1, 0 }, + {-1, 1, 0, 1 }, + { 1, 1, 1, 1 }, + }; + + // If min is not < max, then we don't have values (wasn't set during decode.) + if (bounds.minV < bounds.maxV) { + const float invWidth = 1.0f / bufferW; + const float invHeight = 1.0f / bufferH; + // Inverse of half = double. + const float invHalfWidth = invWidth * 2.0f; + const float invHalfHeight = invHeight * 2.0f; + + const int u1 = bounds.minU + uoff; + const int v1 = bounds.minV + voff; + const int u2 = bounds.maxU + uoff; + const int v2 = bounds.maxV + voff; + + const float left = u1 * invHalfWidth - 1.0f; + const float right = u2 * invHalfWidth - 1.0f; + const float top = v1 * invHalfHeight - 1.0f; + const float bottom = v2 * invHalfHeight - 1.0f; + + const float uvleft = u1 * invWidth; + const float uvright = u2 * invWidth; + const float uvtop = v1 * invHeight; + const float uvbottom = v2 * invHeight; + + // Points are: BL, BR, TR, TL. + verts[0] = Draw2DVertex{ left, bottom, uvleft, uvbottom }; + verts[1] = Draw2DVertex{ right, bottom, uvright, uvbottom }; + verts[2] = Draw2DVertex{ left, top, uvleft, uvtop }; + verts[3] = Draw2DVertex{ right, top, uvright, uvtop }; + + // We need to reapply the texture next time since we cropped UV. + gstate_c.Dirty(DIRTY_TEXTURE_PARAMS); + } + + Draw::Viewport vp{ 0.0f, 0.0f, (float)renderW, (float)renderH, 0.0f, 1.0f }; + draw_->BindPipeline(shader->pipeline); + draw_->SetViewports(1, &vp); + draw_->SetScissorRect(0, 0, renderW, renderH); + draw_->DrawUP((const uint8_t *)verts, 4); +} diff --git a/GPU/Common/DepalettizeCommon.h b/GPU/Common/DepalettizeCommon.h index 6e3ef680ef..169e7e8b9d 100644 --- a/GPU/Common/DepalettizeCommon.h +++ b/GPU/Common/DepalettizeCommon.h @@ -54,6 +54,8 @@ public: Draw::SamplerState *GetSampler(); + void ApplyShader(DepalShader *shader, float bufferW, float bufferH, int renderW, int renderH, const KnownVertexBounds &bounds, u32 uoff, u32 voff); + void Clear(); void Decimate(); std::vector DebugGetShaderIDs(DebugShaderType type); @@ -79,67 +81,3 @@ private: std::map cache_; std::map texCache_; }; - -// TODO: Merge with DepalShaderCache? -class TextureShaderApplier { -public: - TextureShaderApplier(Draw::DrawContext *draw, DepalShader *shader, float bufferW, float bufferH, int renderW, int renderH) - : draw_(draw), shader_(shader), bufferW_(bufferW), bufferH_(bufferH), renderW_(renderW), renderH_(renderH) { - static const Draw2DVertex defaultVerts[4] = { - {-1, -1, 0, 0 }, - { 1, -1, 1, 0 }, - {-1, 1, 0, 1 }, - { 1, 1, 1, 1 }, - }; - memcpy(verts_, defaultVerts, sizeof(defaultVerts)); - } - - void Shade(const KnownVertexBounds &bounds, u32 uoff, u32 voff) { - // If min is not < max, then we don't have values (wasn't set during decode.) - if (bounds.minV < bounds.maxV) { - const float invWidth = 1.0f / bufferW_; - const float invHeight = 1.0f / bufferH_; - // Inverse of half = double. - const float invHalfWidth = invWidth * 2.0f; - const float invHalfHeight = invHeight * 2.0f; - - const int u1 = bounds.minU + uoff; - const int v1 = bounds.minV + voff; - const int u2 = bounds.maxU + uoff; - const int v2 = bounds.maxV + voff; - - const float left = u1 * invHalfWidth - 1.0f; - const float right = u2 * invHalfWidth - 1.0f; - const float top = v1 * invHalfHeight - 1.0f; - const float bottom = v2 * invHalfHeight - 1.0f; - - const float uvleft = u1 * invWidth; - const float uvright = u2 * invWidth; - const float uvtop = v1 * invHeight; - const float uvbottom = v2 * invHeight; - - // Points are: BL, BR, TR, TL. - verts_[0] = Draw2DVertex{ left, bottom, uvleft, uvbottom }; - verts_[1] = Draw2DVertex{ right, bottom, uvright, uvbottom }; - verts_[2] = Draw2DVertex{ left, top, uvleft, uvtop }; - verts_[3] = Draw2DVertex{ right, top, uvright, uvtop }; - - // We need to reapply the texture next time since we cropped UV. - gstate_c.Dirty(DIRTY_TEXTURE_PARAMS); - } - Draw::Viewport vp{ 0.0f, 0.0f, (float)renderW_, (float)renderH_, 0.0f, 1.0f }; - draw_->BindPipeline(shader_->pipeline); - draw_->SetViewports(1, &vp); - draw_->SetScissorRect(0, 0, renderW_, renderH_); - draw_->DrawUP((const uint8_t *)verts_, 4); - } - -protected: - Draw::DrawContext *draw_; - DepalShader *shader_; - Draw2DVertex verts_[4]; - float bufferW_; - float bufferH_; - int renderW_; - int renderH_; -}; diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index 3022f1d1c4..9b092f0e7c 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -1929,15 +1929,16 @@ void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer Draw::Viewport vp{ 0.0f, 0.0f, (float)framebuffer->renderWidth, (float)framebuffer->renderHeight, 0.0f, 1.0f }; draw_->SetViewports(1, &vp); - TextureShaderApplier shaderApply(draw_, depalShader, framebuffer->bufferWidth, framebuffer->bufferHeight, framebuffer->renderWidth, framebuffer->renderHeight); - draw_->BindFramebufferAsTexture(framebuffer->fbo, 0, depth ? Draw::FB_DEPTH_BIT : Draw::FB_COLOR_BIT, 0); draw_->BindTexture(1, clutTexture); Draw::SamplerState *nearest = depalShaderCache_->GetSampler(); draw_->BindSamplerStates(0, 1, &nearest); draw_->BindSamplerStates(1, 1, &nearest); - shaderApply.Shade(gstate_c.vertBounds, gstate_c.curTextureXOffset, gstate_c.curTextureYOffset); + depalShaderCache_->ApplyShader(depalShader, + framebuffer->bufferWidth, framebuffer->bufferHeight, framebuffer->renderWidth, framebuffer->renderHeight, + gstate_c.vertBounds, gstate_c.curTextureXOffset, gstate_c.curTextureYOffset); + draw_->BindTexture(0, nullptr); framebufferManager_->RebindFramebuffer("ApplyTextureFramebuffer"); From 82a6c42e174fef9670581997efe26069031d5a25 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Mon, 22 Aug 2022 12:20:21 +0200 Subject: [PATCH 65/85] DepalettizeCommon -> TextureShaderCommon. Simplifications. --- CMakeLists.txt | 4 +- GPU/Common/DepalettizeShaderCommon.cpp | 4 +- GPU/Common/DepalettizeShaderCommon.h | 2 +- GPU/Common/TextureCacheCommon.cpp | 4 +- GPU/Common/TextureCacheCommon.h | 6 +- ...tizeCommon.cpp => TextureShaderCommon.cpp} | 114 +++++++++--------- ...alettizeCommon.h => TextureShaderCommon.h} | 26 ++-- GPU/D3D11/GPU_D3D11.h | 2 +- GPU/D3D11/TextureCacheD3D11.cpp | 2 +- GPU/D3D11/TextureCacheD3D11.h | 2 +- GPU/Directx9/GPU_DX9.h | 2 +- GPU/Directx9/TextureCacheDX9.cpp | 2 +- GPU/Directx9/TextureCacheDX9.h | 2 +- GPU/GLES/GPU_GLES.h | 2 +- GPU/GLES/TextureCacheGLES.cpp | 2 +- GPU/GLES/TextureCacheGLES.h | 4 +- GPU/GPU.vcxproj | 4 +- GPU/GPU.vcxproj.filters | 4 +- GPU/Vulkan/GPU_Vulkan.h | 2 +- GPU/Vulkan/TextureCacheVulkan.cpp | 2 +- GPU/Vulkan/TextureCacheVulkan.h | 2 +- UWP/GPU_UWP/GPU_UWP.vcxproj | 6 +- UWP/GPU_UWP/GPU_UWP.vcxproj.filters | 6 +- android/jni/Android.mk | 2 +- libretro/Makefile.common | 2 +- unittest/TestShaderGenerators.cpp | 2 +- 26 files changed, 105 insertions(+), 107 deletions(-) rename GPU/Common/{DepalettizeCommon.cpp => TextureShaderCommon.cpp} (78%) rename GPU/Common/{DepalettizeCommon.h => TextureShaderCommon.h} (68%) diff --git a/CMakeLists.txt b/CMakeLists.txt index 8c5dbcd989..09cae88753 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1536,8 +1536,8 @@ set(GPU_SOURCES ${GPU_NEON} GPU/Common/Draw2D.cpp GPU/Common/Draw2D.h - GPU/Common/DepalettizeCommon.cpp - GPU/Common/DepalettizeCommon.h + GPU/Common/TextureShaderCommon.cpp + GPU/Common/TextureShaderCommon.h GPU/Common/DepalettizeShaderCommon.cpp GPU/Common/DepalettizeShaderCommon.h GPU/Common/FragmentShaderGenerator.cpp diff --git a/GPU/Common/DepalettizeShaderCommon.cpp b/GPU/Common/DepalettizeShaderCommon.cpp index af2bf13437..2b9ddca413 100644 --- a/GPU/Common/DepalettizeShaderCommon.cpp +++ b/GPU/Common/DepalettizeShaderCommon.cpp @@ -34,7 +34,7 @@ static const InputDef vsInputs[2] = { { "vec2", "a_texcoord0", Draw::SEM_TEXCOORD0, }, }; -// TODO: Deduplicate with DepalettizeCommon.cpp +// TODO: Deduplicate with TextureShaderCommon.cpp static const SamplerDef samplers[2] = { { "tex" }, { "pal" }, @@ -309,7 +309,7 @@ void GenerateDepalFs(char *buffer, const DepalConfig &config, const ShaderLangua writer.EndFSMain("outColor", FSFLAG_NONE); } -void GenerateDepalVs(char *buffer, const ShaderLanguageDesc &lang) { +void GenerateVs(char *buffer, const ShaderLanguageDesc &lang) { ShaderWriter writer(buffer, lang, ShaderStage::Vertex, nullptr, 0); writer.BeginVSMain(vsInputs, Slice::empty(), varyings); writer.C(" v_texcoord = a_texcoord0;\n"); diff --git a/GPU/Common/DepalettizeShaderCommon.h b/GPU/Common/DepalettizeShaderCommon.h index 74bb38d196..91186f5d20 100644 --- a/GPU/Common/DepalettizeShaderCommon.h +++ b/GPU/Common/DepalettizeShaderCommon.h @@ -34,4 +34,4 @@ struct DepalConfig { }; void GenerateDepalFs(char *buffer, const DepalConfig &config, const ShaderLanguageDesc &lang); -void GenerateDepalVs(char *buffer, const ShaderLanguageDesc &lang); +void GenerateVs(char *buffer, const ShaderLanguageDesc &lang); diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index 9b092f0e7c..b237c3a97e 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -124,7 +124,7 @@ TextureCacheCommon::TextureCacheCommon(Draw::DrawContext *draw) replacer_.Init(); - depalShaderCache_ = new DepalShaderCache(draw); + depalShaderCache_ = new TextureShaderCache(draw); } TextureCacheCommon::~TextureCacheCommon() { @@ -1860,7 +1860,7 @@ bool CanDepalettize(GETextureFormat texFormat, GEBufferFormat bufferFormat) { } void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer, GETextureFormat texFormat, RasterChannel channel) { - DepalShader *depalShader = nullptr; + TextureShader *depalShader = nullptr; uint32_t clutMode = gstate.clutformat & 0xFFFFFF; bool depth = channel == RASTER_DEPTH; diff --git a/GPU/Common/TextureCacheCommon.h b/GPU/Common/TextureCacheCommon.h index 12f0d64213..8be81d3433 100644 --- a/GPU/Common/TextureCacheCommon.h +++ b/GPU/Common/TextureCacheCommon.h @@ -29,7 +29,7 @@ #include "GPU/Common/GPUDebugInterface.h" #include "GPU/Common/TextureDecoder.h" #include "GPU/Common/TextureScalerCommon.h" -#include "GPU/Common/DepalettizeCommon.h" +#include "GPU/Common/TextureShaderCommon.h" enum FramebufferNotification { NOTIFY_FB_CREATED, @@ -291,7 +291,7 @@ public: void InvalidateAll(GPUInvalidationType type); void ClearNextFrame(); - DepalShaderCache *GetDepalShaderCache() { return depalShaderCache_; } + TextureShaderCache *GetDepalShaderCache() { return depalShaderCache_; } virtual void ForgetLastTexture() = 0; virtual void InvalidateLastTexture() = 0; @@ -403,7 +403,7 @@ protected: TextureReplacer replacer_; TextureScalerCommon scaler_; FramebufferManagerCommon *framebufferManager_; - DepalShaderCache *depalShaderCache_; + TextureShaderCache *depalShaderCache_; ShaderManagerCommon *shaderManager_; bool clearCacheNextFrame_ = false; diff --git a/GPU/Common/DepalettizeCommon.cpp b/GPU/Common/TextureShaderCommon.cpp similarity index 78% rename from GPU/Common/DepalettizeCommon.cpp rename to GPU/Common/TextureShaderCommon.cpp index f23e2607ba..77072565ea 100644 --- a/GPU/Common/DepalettizeCommon.cpp +++ b/GPU/Common/TextureShaderCommon.cpp @@ -25,8 +25,8 @@ #include "Core/Reporting.h" #include "GPU/Common/DrawEngineCommon.h" #include "GPU/Common/TextureCacheCommon.h" +#include "GPU/Common/TextureShaderCommon.h" #include "GPU/Common/DepalettizeShaderCommon.h" -#include "GPU/Common/DepalettizeCommon.h" static const VaryingDef varyings[1] = { { "vec2", "v_texcoord", Draw::SEM_TEXCOORD0, 0, "highp" }, @@ -37,22 +37,23 @@ static const SamplerDef samplers[2] = { { "pal" }, }; -DepalShaderCache::DepalShaderCache(Draw::DrawContext *draw) : draw_(draw) { } +TextureShaderCache::TextureShaderCache(Draw::DrawContext *draw) : draw_(draw) { } -DepalShaderCache::~DepalShaderCache() { +TextureShaderCache::~TextureShaderCache() { DeviceLost(); } -void DepalShaderCache::DeviceRestore(Draw::DrawContext *draw) { +void TextureShaderCache::DeviceRestore(Draw::DrawContext *draw) { draw_ = draw; } -void DepalShaderCache::DeviceLost() { +void TextureShaderCache::DeviceLost() { Clear(); } -Draw::Texture *DepalShaderCache::GetClutTexture(GEPaletteFormat clutFormat, const u32 clutHash, u32 *rawClut) { - u32 clutId = GetClutID(clutFormat, clutHash); +Draw::Texture *TextureShaderCache::GetClutTexture(GEPaletteFormat clutFormat, const u32 clutHash, u32 *rawClut) { + // Simplistic, but works well enough. + u32 clutId = clutHash ^ (uint32_t)clutFormat; auto oldtex = texCache_.find(clutId); if (oldtex != texCache_.end()) { @@ -100,15 +101,14 @@ Draw::Texture *DepalShaderCache::GetClutTexture(GEPaletteFormat clutFormat, cons return tex->texture; } -void DepalShaderCache::Clear() { - for (auto shader = cache_.begin(); shader != cache_.end(); ++shader) { - shader->second->fragShader->Release(); +void TextureShaderCache::Clear() { + for (auto shader = depalCache_.begin(); shader != depalCache_.end(); ++shader) { if (shader->second->pipeline) { shader->second->pipeline->Release(); } delete shader->second; } - cache_.clear(); + depalCache_.clear(); for (auto tex = texCache_.begin(); tex != texCache_.end(); ++tex) { tex->second->texture->Release(); delete tex->second; @@ -124,7 +124,7 @@ void DepalShaderCache::Clear() { } } -void DepalShaderCache::Decimate() { +void TextureShaderCache::Decimate() { for (auto tex = texCache_.begin(); tex != texCache_.end(); ) { if (tex->second->lastFrame + DEPAL_TEXTURE_OLD_AGE < gpuStats.numFlips) { tex->second->texture->Release(); @@ -136,7 +136,7 @@ void DepalShaderCache::Decimate() { } } -Draw::SamplerState *DepalShaderCache::GetSampler() { +Draw::SamplerState *TextureShaderCache::GetSampler() { if (!nearestSampler_) { Draw::SamplerStateDesc desc{}; desc.wrapU = Draw::TextureAddressMode::CLAMP_TO_EDGE; @@ -147,39 +147,16 @@ Draw::SamplerState *DepalShaderCache::GetSampler() { return nearestSampler_; } -DepalShader *DepalShaderCache::GetDepalettizeShader(uint32_t clutMode, GETextureFormat textureFormat, GEBufferFormat bufferFormat) { +TextureShader *TextureShaderCache::CreateShader(const char *fs) { using namespace Draw; - - u32 id = GenerateShaderID(clutMode, textureFormat, bufferFormat); - - auto shader = cache_.find(id); - if (shader != cache_.end()) { - DepalShader *depal = shader->second; - return shader->second; - } - - char *buffer = new char[4096]; - if (!vertexShader_) { - GenerateDepalVs(buffer, draw_->GetShaderLanguageDesc()); + char *buffer = new char[4096]; + GenerateVs(buffer, draw_->GetShaderLanguageDesc()); vertexShader_ = draw_->CreateShaderModule(ShaderStage::Vertex, draw_->GetShaderLanguageDesc().shaderLanguage, (const uint8_t *)buffer, strlen(buffer), "depal_vs"); + delete[] buffer; } - // TODO: Parse these out of clutMode some nice way, to become a bit more stateless. - DepalConfig config; - config.clutFormat = gstate.getClutPaletteFormat(); - config.startPos = gstate.getClutIndexStartPos(); - config.shift = gstate.getClutIndexShift(); - config.mask = gstate.getClutIndexMask(); - config.bufferFormat = bufferFormat; - config.textureFormat = textureFormat; - - GenerateDepalFs(buffer, config, draw_->GetShaderLanguageDesc()); - - std::string src(buffer); - ShaderModule *fragShader = draw_->CreateShaderModule(ShaderStage::Fragment, draw_->GetShaderLanguageDesc().shaderLanguage, (const uint8_t *)buffer, strlen(buffer), "depal_fs"); - - DepalShader *depal = new DepalShader(); + ShaderModule *fragShader = draw_->CreateShaderModule(ShaderStage::Fragment, draw_->GetShaderLanguageDesc().shaderLanguage, (const uint8_t *)fs, strlen(fs), "depal_fs"); static const InputLayoutDesc desc = { { @@ -201,38 +178,67 @@ DepalShader *DepalShaderCache::GetDepalettizeShader(uint32_t clutMode, GETexture { vertexShader_, fragShader }, inputLayout, noDepthStencil, blendOff, rasterNoCull, nullptr, samplers }; - + Pipeline *pipeline = draw_->CreateGraphicsPipeline(depalPipelineDesc); inputLayout->Release(); blendOff->Release(); noDepthStencil->Release(); rasterNoCull->Release(); + fragShader->Release(); _assert_(pipeline); + TextureShader *depal = new TextureShader(); depal->pipeline = pipeline; - depal->fragShader = fragShader; - depal->code = buffer; - cache_[id] = depal; - - delete[] buffer; - return depal->pipeline ? depal : nullptr; + depal->code = fs; // to std::string + return depal; } -std::vector DepalShaderCache::DebugGetShaderIDs(DebugShaderType type) { +TextureShader *TextureShaderCache::GetDepalettizeShader(uint32_t clutMode, GETextureFormat textureFormat, GEBufferFormat bufferFormat) { + using namespace Draw; + + // Generate an ID for depal shaders. + u32 id = (clutMode & 0xFFFFFF) | (textureFormat << 24) | (bufferFormat << 28); + + auto shader = depalCache_.find(id); + if (shader != depalCache_.end()) { + TextureShader *depal = shader->second; + return shader->second; + } + + // TODO: Parse these out of clutMode some nice way, to become a bit more stateless. + DepalConfig config; + config.clutFormat = gstate.getClutPaletteFormat(); + config.startPos = gstate.getClutIndexStartPos(); + config.shift = gstate.getClutIndexShift(); + config.mask = gstate.getClutIndexMask(); + config.bufferFormat = bufferFormat; + config.textureFormat = textureFormat; + + char *buffer = new char[4096]; + GenerateDepalFs(buffer, config, draw_->GetShaderLanguageDesc()); + TextureShader *ts = CreateShader(buffer); + delete[] buffer; + + depalCache_[id] = ts; + + return ts->pipeline ? ts : nullptr; +} + +std::vector TextureShaderCache::DebugGetShaderIDs(DebugShaderType type) { std::vector ids; - for (auto &iter : cache_) { + for (auto &iter : depalCache_) { ids.push_back(StringFromFormat("%08x", iter.first)); } return ids; } -std::string DepalShaderCache::DebugGetShaderString(std::string idstr, DebugShaderType type, DebugShaderStringType stringType) { +std::string TextureShaderCache::DebugGetShaderString(std::string idstr, DebugShaderType type, DebugShaderStringType stringType) { uint32_t id; sscanf(idstr.c_str(), "%08x", &id); - auto iter = cache_.find(id); - if (iter == cache_.end()) + auto iter = depalCache_.find(id); + if (iter == depalCache_.end()) return ""; switch (stringType) { case SHADER_STRING_SHORT_DESC: @@ -245,7 +251,7 @@ std::string DepalShaderCache::DebugGetShaderString(std::string idstr, DebugShade } // TODO: Merge with DepalShaderCache? -void DepalShaderCache::ApplyShader(DepalShader *shader, float bufferW, float bufferH, int renderW, int renderH, const KnownVertexBounds &bounds, u32 uoff, u32 voff) { +void TextureShaderCache::ApplyShader(TextureShader *shader, float bufferW, float bufferH, int renderW, int renderH, const KnownVertexBounds &bounds, u32 uoff, u32 voff) { Draw2DVertex verts[4] = { {-1, -1, 0, 0 }, { 1, -1, 1, 0 }, diff --git a/GPU/Common/DepalettizeCommon.h b/GPU/Common/TextureShaderCommon.h similarity index 68% rename from GPU/Common/DepalettizeCommon.h rename to GPU/Common/TextureShaderCommon.h index 169e7e8b9d..628746b465 100644 --- a/GPU/Common/DepalettizeCommon.h +++ b/GPU/Common/TextureShaderCommon.h @@ -29,9 +29,8 @@ #include "GPU/Common/ShaderCommon.h" #include "GPU/Common/DepalettizeShaderCommon.h" -class DepalShader { +class TextureShader { public: - Draw::ShaderModule *fragShader; Draw::Pipeline *pipeline; std::string code; }; @@ -42,19 +41,19 @@ public: int lastFrame; }; +// For CLUT depal shaders, and other pre-bind texture shaders. // Caches both shaders and palette textures. -class DepalShaderCache { +class TextureShaderCache { public: - DepalShaderCache(Draw::DrawContext *draw); - ~DepalShaderCache(); + TextureShaderCache(Draw::DrawContext *draw); + ~TextureShaderCache(); - // This also uploads the palette and binds the correct texture. - DepalShader *GetDepalettizeShader(uint32_t clutMode, GETextureFormat texFormat, GEBufferFormat pixelFormat); + TextureShader *GetDepalettizeShader(uint32_t clutMode, GETextureFormat texFormat, GEBufferFormat pixelFormat); Draw::Texture *GetClutTexture(GEPaletteFormat clutFormat, const u32 clutHash, u32 *rawClut); Draw::SamplerState *GetSampler(); - void ApplyShader(DepalShader *shader, float bufferW, float bufferH, int renderW, int renderH, const KnownVertexBounds &bounds, u32 uoff, u32 voff); + void ApplyShader(TextureShader *shader, float bufferW, float bufferH, int renderW, int renderH, const KnownVertexBounds &bounds, u32 uoff, u32 voff); void Clear(); void Decimate(); @@ -65,19 +64,12 @@ public: void DeviceRestore(Draw::DrawContext *draw); private: - static uint32_t GenerateShaderID(uint32_t clutMode, GETextureFormat texFormat, GEBufferFormat pixelFormat) { - return (clutMode & 0xFFFFFF) | (pixelFormat << 24) | (texFormat << 28); - } - - static uint32_t GetClutID(GEPaletteFormat clutFormat, uint32_t clutHash) { - // Simplistic. - return clutHash ^ (uint32_t)clutFormat; - } + TextureShader *CreateShader(const char *fs); Draw::DrawContext *draw_; Draw::ShaderModule *vertexShader_ = nullptr; Draw::SamplerState *nearestSampler_ = nullptr; - std::map cache_; + std::map depalCache_; std::map texCache_; }; diff --git a/GPU/D3D11/GPU_D3D11.h b/GPU/D3D11/GPU_D3D11.h index 94a0aef915..33790c7f99 100644 --- a/GPU/D3D11/GPU_D3D11.h +++ b/GPU/D3D11/GPU_D3D11.h @@ -23,7 +23,7 @@ #include "GPU/GPUCommon.h" #include "GPU/D3D11/DrawEngineD3D11.h" -#include "GPU/Common/DepalettizeCommon.h" +#include "GPU/Common/TextureShaderCommon.h" #include "GPU/Common/VertexDecoderCommon.h" class FramebufferManagerD3D11; diff --git a/GPU/D3D11/TextureCacheD3D11.cpp b/GPU/D3D11/TextureCacheD3D11.cpp index 2fea477610..fabb7cca4a 100644 --- a/GPU/D3D11/TextureCacheD3D11.cpp +++ b/GPU/D3D11/TextureCacheD3D11.cpp @@ -31,7 +31,7 @@ #include "GPU/D3D11/TextureCacheD3D11.h" #include "GPU/D3D11/FramebufferManagerD3D11.h" #include "GPU/D3D11/ShaderManagerD3D11.h" -#include "GPU/Common/DepalettizeCommon.h" +#include "GPU/Common/TextureShaderCommon.h" #include "GPU/D3D11/D3D11Util.h" #include "GPU/Common/FramebufferManagerCommon.h" #include "GPU/Common/TextureDecoder.h" diff --git a/GPU/D3D11/TextureCacheD3D11.h b/GPU/D3D11/TextureCacheD3D11.h index 433f6e824e..b641c72866 100644 --- a/GPU/D3D11/TextureCacheD3D11.h +++ b/GPU/D3D11/TextureCacheD3D11.h @@ -28,7 +28,7 @@ struct VirtualFramebuffer; class FramebufferManagerD3D11; -class DepalShaderCache; +class TextureShaderCache; class ShaderManagerD3D11; class SamplerCacheD3D11 { diff --git a/GPU/Directx9/GPU_DX9.h b/GPU/Directx9/GPU_DX9.h index 349d2bd0a8..35ac9817e1 100644 --- a/GPU/Directx9/GPU_DX9.h +++ b/GPU/Directx9/GPU_DX9.h @@ -23,7 +23,7 @@ #include "GPU/GPUCommon.h" #include "GPU/Directx9/FramebufferManagerDX9.h" #include "GPU/Directx9/DrawEngineDX9.h" -#include "GPU/Common/DepalettizeCommon.h" +#include "GPU/Common/TextureShaderCommon.h" #include "GPU/Common/VertexDecoderCommon.h" class ShaderManagerDX9; diff --git a/GPU/Directx9/TextureCacheDX9.cpp b/GPU/Directx9/TextureCacheDX9.cpp index ea6b47e2e9..905f445c1c 100644 --- a/GPU/Directx9/TextureCacheDX9.cpp +++ b/GPU/Directx9/TextureCacheDX9.cpp @@ -28,7 +28,7 @@ #include "GPU/Directx9/FramebufferManagerDX9.h" #include "GPU/Directx9/ShaderManagerDX9.h" #include "Common/GPU/D3D9/D3D9StateCache.h" -#include "GPU/Common/DepalettizeCommon.h" +#include "GPU/Common/TextureShaderCommon.h" #include "GPU/Common/FramebufferManagerCommon.h" #include "GPU/Common/TextureDecoder.h" #include "Core/Config.h" diff --git a/GPU/Directx9/TextureCacheDX9.h b/GPU/Directx9/TextureCacheDX9.h index 47005cbd5c..40351be611 100644 --- a/GPU/Directx9/TextureCacheDX9.h +++ b/GPU/Directx9/TextureCacheDX9.h @@ -24,7 +24,7 @@ #include "GPU/Common/TextureCacheCommon.h" struct VirtualFramebuffer; -class DepalShaderCache; +class TextureShaderCache; class FramebufferManagerDX9; class ShaderManagerDX9; diff --git a/GPU/GLES/GPU_GLES.h b/GPU/GLES/GPU_GLES.h index a6e521763a..f308d15445 100644 --- a/GPU/GLES/GPU_GLES.h +++ b/GPU/GLES/GPU_GLES.h @@ -23,7 +23,7 @@ #include "Common/File/Path.h" #include "GPU/GPUCommon.h" -#include "GPU/Common/DepalettizeCommon.h" +#include "GPU/Common/TextureShaderCommon.h" #include "GPU/GLES/FramebufferManagerGLES.h" #include "GPU/GLES/DrawEngineGLES.h" #include "GPU/GLES/FragmentTestCacheGLES.h" diff --git a/GPU/GLES/TextureCacheGLES.cpp b/GPU/GLES/TextureCacheGLES.cpp index fb3c1a01b3..ddaad253bc 100644 --- a/GPU/GLES/TextureCacheGLES.cpp +++ b/GPU/GLES/TextureCacheGLES.cpp @@ -36,7 +36,7 @@ #include "GPU/GLES/TextureCacheGLES.h" #include "GPU/GLES/FramebufferManagerGLES.h" #include "GPU/Common/FragmentShaderGenerator.h" -#include "GPU/Common/DepalettizeCommon.h" +#include "GPU/Common/TextureShaderCommon.h" #include "GPU/GLES/ShaderManagerGLES.h" #include "GPU/GLES/DrawEngineGLES.h" #include "GPU/Common/TextureDecoder.h" diff --git a/GPU/GLES/TextureCacheGLES.h b/GPU/GLES/TextureCacheGLES.h index ac5313c3cb..b23af129f5 100644 --- a/GPU/GLES/TextureCacheGLES.h +++ b/GPU/GLES/TextureCacheGLES.h @@ -27,7 +27,7 @@ struct VirtualFramebuffer; class FramebufferManagerGLES; -class DepalShaderCache; +class TextureShaderCache; class ShaderManagerGLES; class DrawEngineGLES; class GLRTexture; @@ -41,7 +41,7 @@ public: void StartFrame() override; void SetFramebufferManager(FramebufferManagerGLES *fbManager); - void SetDepalShaderCache(DepalShaderCache *dpCache) { + void SetDepalShaderCache(TextureShaderCache *dpCache) { depalShaderCache_ = dpCache; } void SetDrawEngine(DrawEngineGLES *td) { diff --git a/GPU/GPU.vcxproj b/GPU/GPU.vcxproj index 86d21d3690..1f37652321 100644 --- a/GPU/GPU.vcxproj +++ b/GPU/GPU.vcxproj @@ -338,7 +338,7 @@ - + @@ -452,7 +452,7 @@ - + diff --git a/GPU/GPU.vcxproj.filters b/GPU/GPU.vcxproj.filters index cb2832c032..d581cb4bad 100644 --- a/GPU/GPU.vcxproj.filters +++ b/GPU/GPU.vcxproj.filters @@ -255,7 +255,7 @@ Common - + Common @@ -503,7 +503,7 @@ Common - + Common diff --git a/GPU/Vulkan/GPU_Vulkan.h b/GPU/Vulkan/GPU_Vulkan.h index 87e54dbf19..18da82e6b0 100644 --- a/GPU/Vulkan/GPU_Vulkan.h +++ b/GPU/Vulkan/GPU_Vulkan.h @@ -25,7 +25,7 @@ #include "GPU/GPUCommon.h" #include "GPU/Vulkan/DrawEngineVulkan.h" #include "GPU/Vulkan/PipelineManagerVulkan.h" -#include "GPU/Common/DepalettizeCommon.h" +#include "GPU/Common/TextureShaderCommon.h" class FramebufferManagerVulkan; class ShaderManagerVulkan; diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index 603b064f8b..132c0e081a 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -41,7 +41,7 @@ #include "GPU/ge_constants.h" #include "GPU/GPUState.h" -#include "GPU/Common/DepalettizeCommon.h" +#include "GPU/Common/TextureShaderCommon.h" #include "GPU/Common/PostShader.h" #include "GPU/Common/TextureCacheCommon.h" #include "GPU/Common/TextureDecoder.h" diff --git a/GPU/Vulkan/TextureCacheVulkan.h b/GPU/Vulkan/TextureCacheVulkan.h index c3fc55945e..c56652d2c9 100644 --- a/GPU/Vulkan/TextureCacheVulkan.h +++ b/GPU/Vulkan/TextureCacheVulkan.h @@ -22,7 +22,7 @@ #include "GPU/GPUState.h" #include "Common/GPU/Vulkan/VulkanContext.h" #include "GPU/Common/TextureCacheCommon.h" -#include "GPU/Common/DepalettizeCommon.h" +#include "GPU/Common/TextureShaderCommon.h" #include "GPU/Vulkan/VulkanUtil.h" struct VirtualFramebuffer; diff --git a/UWP/GPU_UWP/GPU_UWP.vcxproj b/UWP/GPU_UWP/GPU_UWP.vcxproj index 9a24b23185..277526509c 100644 --- a/UWP/GPU_UWP/GPU_UWP.vcxproj +++ b/UWP/GPU_UWP/GPU_UWP.vcxproj @@ -379,7 +379,7 @@ - + @@ -439,7 +439,7 @@ - + @@ -527,4 +527,4 @@ - \ No newline at end of file + diff --git a/UWP/GPU_UWP/GPU_UWP.vcxproj.filters b/UWP/GPU_UWP/GPU_UWP.vcxproj.filters index affb707ff7..2a797c0d2e 100644 --- a/UWP/GPU_UWP/GPU_UWP.vcxproj.filters +++ b/UWP/GPU_UWP/GPU_UWP.vcxproj.filters @@ -57,7 +57,7 @@ - + @@ -117,6 +117,6 @@ - + - \ No newline at end of file + diff --git a/android/jni/Android.mk b/android/jni/Android.mk index 71fcf8de3a..7f3afa7849 100644 --- a/android/jni/Android.mk +++ b/android/jni/Android.mk @@ -319,7 +319,7 @@ EXEC_AND_LIB_FILES := \ $(SRC)/GPU/GeConstants.cpp \ $(SRC)/GPU/GeDisasm.cpp \ $(SRC)/GPU/Common/Draw2D.cpp \ - $(SRC)/GPU/Common/DepalettizeCommon.cpp \ + $(SRC)/GPU/Common/TextureShaderCommon.cpp \ $(SRC)/GPU/Common/DepalettizeShaderCommon.cpp \ $(SRC)/GPU/Common/FragmentShaderGenerator.cpp \ $(SRC)/GPU/Common/FramebufferManagerCommon.cpp \ diff --git a/libretro/Makefile.common b/libretro/Makefile.common index 183afdf060..6e5a9726cb 100644 --- a/libretro/Makefile.common +++ b/libretro/Makefile.common @@ -327,7 +327,7 @@ SOURCES_CXX += \ $(GPUCOMMONDIR)/ShaderCommon.cpp \ $(GPUCOMMONDIR)/ShaderUniforms.cpp \ $(GPUCOMMONDIR)/GPUDebugInterface.cpp \ - $(GPUCOMMONDIR)/DepalettizeCommon.cpp \ + $(GPUCOMMONDIR)/TextureShaderCommon.cpp \ $(GPUCOMMONDIR)/DepalettizeShaderCommon.cpp \ $(GPUCOMMONDIR)/TransformCommon.cpp \ $(GPUCOMMONDIR)/IndexGenerator.cpp \ diff --git a/unittest/TestShaderGenerators.cpp b/unittest/TestShaderGenerators.cpp index a96df6657c..2463fde971 100644 --- a/unittest/TestShaderGenerators.cpp +++ b/unittest/TestShaderGenerators.cpp @@ -321,7 +321,7 @@ bool TestDepalShaders() { printf("===\n%s\n===\n", buffer); } - GenerateDepalVs(buffer, desc); + GenerateVs(buffer, desc); if (!TestCompileShader(buffer, languages[k], ShaderStage::Vertex, &errorMessage)) { printf("Error compiling depal shader:\n\n%s\n\n%s\n", LineNumberString(buffer).c_str(), errorMessage.c_str()); failed = true; From b39b74e602d36d9ff2b433670bd5cdfa36d09902 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Mon, 22 Aug 2022 12:28:46 +0200 Subject: [PATCH 66/85] More renaming. Fix shader view for Vulkan --- GPU/Common/ShaderCommon.h | 2 +- GPU/Common/TextureCacheCommon.cpp | 22 +++++++++++----------- GPU/Common/TextureCacheCommon.h | 4 ++-- GPU/Common/TextureShaderCommon.cpp | 3 +-- GPU/Common/TextureShaderCommon.h | 4 ++-- GPU/D3D11/GPU_D3D11.cpp | 8 ++++---- GPU/Directx9/GPU_DX9.cpp | 8 ++++---- GPU/GLES/GPU_GLES.cpp | 8 ++++---- GPU/GLES/TextureCacheGLES.cpp | 4 ++-- GPU/GLES/TextureCacheGLES.h | 2 +- GPU/Vulkan/GPU_Vulkan.cpp | 9 ++++----- GPU/Vulkan/TextureCacheVulkan.cpp | 6 +++--- UI/DevScreens.cpp | 2 +- 13 files changed, 40 insertions(+), 42 deletions(-) diff --git a/GPU/Common/ShaderCommon.h b/GPU/Common/ShaderCommon.h index d15d666e0f..1a69e5c387 100644 --- a/GPU/Common/ShaderCommon.h +++ b/GPU/Common/ShaderCommon.h @@ -29,7 +29,7 @@ enum DebugShaderType { SHADER_TYPE_GEOMETRY = 2, SHADER_TYPE_VERTEXLOADER = 3, // Not really a shader, but might as well re-use this mechanism SHADER_TYPE_PIPELINE = 4, // Vulkan and DX12 combines a bunch of state into pipeline objects. Might as well make them inspectable. - SHADER_TYPE_DEPAL = 5, + SHADER_TYPE_TEXTURE = 5, SHADER_TYPE_SAMPLER = 6, // Not really a shader either. Need to rename this enum... }; diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index b237c3a97e..de6c840722 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -124,11 +124,11 @@ TextureCacheCommon::TextureCacheCommon(Draw::DrawContext *draw) replacer_.Init(); - depalShaderCache_ = new TextureShaderCache(draw); + textureShaderCache_ = new TextureShaderCache(draw); } TextureCacheCommon::~TextureCacheCommon() { - delete depalShaderCache_; + delete textureShaderCache_; FreeAlignedMemory(clutBufConverted_); FreeAlignedMemory(clutBufRaw_); @@ -1860,7 +1860,7 @@ bool CanDepalettize(GETextureFormat texFormat, GEBufferFormat bufferFormat) { } void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer, GETextureFormat texFormat, RasterChannel channel) { - TextureShader *depalShader = nullptr; + TextureShader *textureShader = nullptr; uint32_t clutMode = gstate.clutformat & 0xFFFFFF; bool depth = channel == RASTER_DEPTH; @@ -1886,7 +1886,7 @@ void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer const GEPaletteFormat clutFormat = gstate.getClutPaletteFormat(); // Very icky conflation here of native and thin3d rendering. This will need careful work per backend in BindAsClutTexture. - Draw::Texture *clutTexture = depalShaderCache_->GetClutTexture(clutFormat, clutHash_, clutBufRaw_); + Draw::Texture *clutTexture = textureShaderCache_->GetClutTexture(clutFormat, clutHash_, clutBufRaw_); BindAsClutTexture(clutTexture); framebufferManager_->BindFramebufferAsColorTexture(0, framebuffer, BINDFBCOLOR_MAY_COPY_WITH_UV | BINDFBCOLOR_APPLY_TEX_OFFSET); @@ -1913,13 +1913,13 @@ void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer return; } - depalShader = depalShaderCache_->GetDepalettizeShader(clutMode, texFormat, depth ? GE_FORMAT_DEPTH16 : framebuffer->drawnFormat); + textureShader = textureShaderCache_->GetDepalettizeShader(clutMode, texFormat, depth ? GE_FORMAT_DEPTH16 : framebuffer->drawnFormat); gstate_c.SetUseShaderDepal(false); } - if (depalShader) { + if (textureShader) { const GEPaletteFormat clutFormat = gstate.getClutPaletteFormat(); - Draw::Texture *clutTexture = depalShaderCache_->GetClutTexture(clutFormat, clutHash_, clutBufRaw_); + Draw::Texture *clutTexture = textureShaderCache_->GetClutTexture(clutFormat, clutHash_, clutBufRaw_); Draw::Framebuffer *depalFBO = framebufferManager_->GetTempFBO(TempFBO::DEPAL, framebuffer->renderWidth, framebuffer->renderHeight); draw_->BindTexture(0, nullptr); draw_->BindTexture(1, nullptr); @@ -1931,11 +1931,11 @@ void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer draw_->BindFramebufferAsTexture(framebuffer->fbo, 0, depth ? Draw::FB_DEPTH_BIT : Draw::FB_COLOR_BIT, 0); draw_->BindTexture(1, clutTexture); - Draw::SamplerState *nearest = depalShaderCache_->GetSampler(); + Draw::SamplerState *nearest = textureShaderCache_->GetSampler(); draw_->BindSamplerStates(0, 1, &nearest); draw_->BindSamplerStates(1, 1, &nearest); - depalShaderCache_->ApplyShader(depalShader, + textureShaderCache_->ApplyShader(textureShader, framebuffer->bufferWidth, framebuffer->bufferHeight, framebuffer->renderWidth, framebuffer->renderHeight, gstate_c.vertBounds, gstate_c.curTextureXOffset, gstate_c.curTextureYOffset); @@ -1970,7 +1970,7 @@ void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer } void TextureCacheCommon::Clear(bool delete_them) { - depalShaderCache_->Clear(); + textureShaderCache_->Clear(); ForgetLastTexture(); for (TexCache::iterator iter = cache_.begin(); iter != cache_.end(); ++iter) { @@ -2412,5 +2412,5 @@ CheckAlphaResult TextureCacheCommon::CheckCLUTAlpha(const uint8_t *pixelData, GE } void TextureCacheCommon::StartFrame() { - depalShaderCache_->Decimate(); + textureShaderCache_->Decimate(); } diff --git a/GPU/Common/TextureCacheCommon.h b/GPU/Common/TextureCacheCommon.h index 8be81d3433..080e11a00b 100644 --- a/GPU/Common/TextureCacheCommon.h +++ b/GPU/Common/TextureCacheCommon.h @@ -291,7 +291,7 @@ public: void InvalidateAll(GPUInvalidationType type); void ClearNextFrame(); - TextureShaderCache *GetDepalShaderCache() { return depalShaderCache_; } + TextureShaderCache *GetTextureShaderCache() { return textureShaderCache_; } virtual void ForgetLastTexture() = 0; virtual void InvalidateLastTexture() = 0; @@ -403,7 +403,7 @@ protected: TextureReplacer replacer_; TextureScalerCommon scaler_; FramebufferManagerCommon *framebufferManager_; - TextureShaderCache *depalShaderCache_; + TextureShaderCache *textureShaderCache_; ShaderManagerCommon *shaderManager_; bool clearCacheNextFrame_ = false; diff --git a/GPU/Common/TextureShaderCommon.cpp b/GPU/Common/TextureShaderCommon.cpp index 77072565ea..defbeb1575 100644 --- a/GPU/Common/TextureShaderCommon.cpp +++ b/GPU/Common/TextureShaderCommon.cpp @@ -63,7 +63,7 @@ Draw::Texture *TextureShaderCache::GetClutTexture(GEPaletteFormat clutFormat, co int texturePixels = clutFormat == GE_CMODE_32BIT_ABGR8888 ? 256 : 512; - DepalTexture *tex = new DepalTexture(); + ClutTexture *tex = new ClutTexture(); Draw::TextureDesc desc{}; desc.width = texturePixels; @@ -250,7 +250,6 @@ std::string TextureShaderCache::DebugGetShaderString(std::string idstr, DebugSha } } -// TODO: Merge with DepalShaderCache? void TextureShaderCache::ApplyShader(TextureShader *shader, float bufferW, float bufferH, int renderW, int renderH, const KnownVertexBounds &bounds, u32 uoff, u32 voff) { Draw2DVertex verts[4] = { {-1, -1, 0, 0 }, diff --git a/GPU/Common/TextureShaderCommon.h b/GPU/Common/TextureShaderCommon.h index 628746b465..e2967ea89c 100644 --- a/GPU/Common/TextureShaderCommon.h +++ b/GPU/Common/TextureShaderCommon.h @@ -35,7 +35,7 @@ public: std::string code; }; -class DepalTexture { +class ClutTexture { public: Draw::Texture *texture; int lastFrame; @@ -71,5 +71,5 @@ private: Draw::SamplerState *nearestSampler_ = nullptr; std::map depalCache_; - std::map texCache_; + std::map texCache_; }; diff --git a/GPU/D3D11/GPU_D3D11.cpp b/GPU/D3D11/GPU_D3D11.cpp index ba41521fde..956d17fc85 100644 --- a/GPU/D3D11/GPU_D3D11.cpp +++ b/GPU/D3D11/GPU_D3D11.cpp @@ -332,8 +332,8 @@ std::vector GPU_D3D11::DebugGetShaderIDs(DebugShaderType type) { switch (type) { case SHADER_TYPE_VERTEXLOADER: return drawEngine_.DebugGetVertexLoaderIDs(); - case SHADER_TYPE_DEPAL: - return textureCache_->GetDepalShaderCache()->DebugGetShaderIDs(type); + case SHADER_TYPE_TEXTURE: + return textureCache_->GetTextureShaderCache()->DebugGetShaderIDs(type); default: return shaderManagerD3D11_->DebugGetShaderIDs(type); } @@ -343,8 +343,8 @@ std::string GPU_D3D11::DebugGetShaderString(std::string id, DebugShaderType type switch (type) { case SHADER_TYPE_VERTEXLOADER: return drawEngine_.DebugGetVertexLoaderString(id, stringType); - case SHADER_TYPE_DEPAL: - return textureCache_->GetDepalShaderCache()->DebugGetShaderString(id, type, stringType); + case SHADER_TYPE_TEXTURE: + return textureCache_->GetTextureShaderCache()->DebugGetShaderString(id, type, stringType); default: return shaderManagerD3D11_->DebugGetShaderString(id, type, stringType); } diff --git a/GPU/Directx9/GPU_DX9.cpp b/GPU/Directx9/GPU_DX9.cpp index b36cb34288..deaeeafb68 100644 --- a/GPU/Directx9/GPU_DX9.cpp +++ b/GPU/Directx9/GPU_DX9.cpp @@ -375,8 +375,8 @@ std::vector GPU_DX9::DebugGetShaderIDs(DebugShaderType type) { switch (type) { case SHADER_TYPE_VERTEXLOADER: return drawEngine_.DebugGetVertexLoaderIDs(); - case SHADER_TYPE_DEPAL: - return textureCache_->GetDepalShaderCache()->DebugGetShaderIDs(type); + case SHADER_TYPE_TEXTURE: + return textureCache_->GetTextureShaderCache()->DebugGetShaderIDs(type); default: return shaderManagerDX9_->DebugGetShaderIDs(type); } @@ -386,8 +386,8 @@ std::string GPU_DX9::DebugGetShaderString(std::string id, DebugShaderType type, switch (type) { case SHADER_TYPE_VERTEXLOADER: return drawEngine_.DebugGetVertexLoaderString(id, stringType); - case SHADER_TYPE_DEPAL: - return textureCache_->GetDepalShaderCache()->DebugGetShaderString(id, type, stringType); + case SHADER_TYPE_TEXTURE: + return textureCache_->GetTextureShaderCache()->DebugGetShaderString(id, type, stringType); default: return shaderManagerDX9_->DebugGetShaderString(id, type, stringType); } diff --git a/GPU/GLES/GPU_GLES.cpp b/GPU/GLES/GPU_GLES.cpp index f774e4bebd..1dd004aab8 100644 --- a/GPU/GLES/GPU_GLES.cpp +++ b/GPU/GLES/GPU_GLES.cpp @@ -453,8 +453,8 @@ std::vector GPU_GLES::DebugGetShaderIDs(DebugShaderType type) { switch (type) { case SHADER_TYPE_VERTEXLOADER: return drawEngine_.DebugGetVertexLoaderIDs(); - case SHADER_TYPE_DEPAL: - return textureCache_->GetDepalShaderCache()->DebugGetShaderIDs(type); + case SHADER_TYPE_TEXTURE: + return textureCache_->GetTextureShaderCache()->DebugGetShaderIDs(type); default: return shaderManagerGL_->DebugGetShaderIDs(type); } @@ -464,8 +464,8 @@ std::string GPU_GLES::DebugGetShaderString(std::string id, DebugShaderType type, switch (type) { case SHADER_TYPE_VERTEXLOADER: return drawEngine_.DebugGetVertexLoaderString(id, stringType); - case SHADER_TYPE_DEPAL: - return textureCache_->GetDepalShaderCache()->DebugGetShaderString(id, type, stringType); + case SHADER_TYPE_TEXTURE: + return textureCache_->GetTextureShaderCache()->DebugGetShaderString(id, type, stringType); default: return shaderManagerGL_->DebugGetShaderString(id, type, stringType); } diff --git a/GPU/GLES/TextureCacheGLES.cpp b/GPU/GLES/TextureCacheGLES.cpp index ddaad253bc..6fb19338d9 100644 --- a/GPU/GLES/TextureCacheGLES.cpp +++ b/GPU/GLES/TextureCacheGLES.cpp @@ -430,7 +430,7 @@ bool TextureCacheGLES::GetCurrentTextureDebug(GPUDebugBuffer &buffer, int level) } void TextureCacheGLES::DeviceLost() { - depalShaderCache_->DeviceLost(); + textureShaderCache_->DeviceLost(); Clear(false); draw_ = nullptr; render_ = nullptr; @@ -439,5 +439,5 @@ void TextureCacheGLES::DeviceLost() { void TextureCacheGLES::DeviceRestore(Draw::DrawContext *draw) { draw_ = draw; render_ = (GLRenderManager *)draw_->GetNativeObject(Draw::NativeObject::RENDER_MANAGER); - depalShaderCache_->DeviceRestore(draw); + textureShaderCache_->DeviceRestore(draw); } diff --git a/GPU/GLES/TextureCacheGLES.h b/GPU/GLES/TextureCacheGLES.h index b23af129f5..d192a2369a 100644 --- a/GPU/GLES/TextureCacheGLES.h +++ b/GPU/GLES/TextureCacheGLES.h @@ -42,7 +42,7 @@ public: void SetFramebufferManager(FramebufferManagerGLES *fbManager); void SetDepalShaderCache(TextureShaderCache *dpCache) { - depalShaderCache_ = dpCache; + textureShaderCache_ = dpCache; } void SetDrawEngine(DrawEngineGLES *td) { drawEngine_ = td; diff --git a/GPU/Vulkan/GPU_Vulkan.cpp b/GPU/Vulkan/GPU_Vulkan.cpp index 7d2dc8b5c0..adc0a9c127 100644 --- a/GPU/Vulkan/GPU_Vulkan.cpp +++ b/GPU/Vulkan/GPU_Vulkan.cpp @@ -604,9 +604,8 @@ std::vector GPU_Vulkan::DebugGetShaderIDs(DebugShaderType type) { return drawEngine_.DebugGetVertexLoaderIDs(); } else if (type == SHADER_TYPE_PIPELINE) { return pipelineManager_->DebugGetObjectIDs(type); - } else if (type == SHADER_TYPE_DEPAL) { - ///... - return std::vector(); + } else if (type == SHADER_TYPE_TEXTURE) { + return textureCache_->GetTextureShaderCache()->DebugGetShaderIDs(type); } else if (type == SHADER_TYPE_VERTEX || type == SHADER_TYPE_FRAGMENT) { return shaderManagerVulkan_->DebugGetShaderIDs(type); } else if (type == SHADER_TYPE_SAMPLER) { @@ -621,8 +620,8 @@ std::string GPU_Vulkan::DebugGetShaderString(std::string id, DebugShaderType typ return drawEngine_.DebugGetVertexLoaderString(id, stringType); } else if (type == SHADER_TYPE_PIPELINE) { return pipelineManager_->DebugGetObjectString(id, type, stringType); - } else if (type == SHADER_TYPE_DEPAL) { - return ""; + } else if (type == SHADER_TYPE_TEXTURE) { + return textureCache_->GetTextureShaderCache()->DebugGetShaderString(id, type, stringType); } else if (type == SHADER_TYPE_SAMPLER) { return textureCacheVulkan_->DebugGetSamplerString(id, stringType); } else if (type == SHADER_TYPE_VERTEX || type == SHADER_TYPE_FRAGMENT) { diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index 132c0e081a..6c15264b1f 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -200,7 +200,7 @@ void TextureCacheVulkan::SetFramebufferManager(FramebufferManagerVulkan *fbManag } void TextureCacheVulkan::DeviceLost() { - depalShaderCache_->DeviceLost(); + textureShaderCache_->DeviceLost(); VulkanContext *vulkan = draw_ ? (VulkanContext *)draw_->GetNativeObject(Draw::NativeObject::CONTEXT) : nullptr; @@ -227,7 +227,7 @@ void TextureCacheVulkan::DeviceRestore(Draw::DrawContext *draw) { _assert_(!allocator_); samplerCache_.DeviceRestore(vulkan); - depalShaderCache_->DeviceRestore(draw); + textureShaderCache_->DeviceRestore(draw); VkSamplerCreateInfo samp{ VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO }; samp.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT; @@ -320,7 +320,7 @@ void TextureCacheVulkan::StartFrame() { TextureCacheCommon::StartFrame(); InvalidateLastTexture(); - depalShaderCache_->Decimate(); + textureShaderCache_->Decimate(); timesInvalidatedAllThisFrame_ = 0; texelsScaledThisFrame_ = 0; diff --git a/UI/DevScreens.cpp b/UI/DevScreens.cpp index 1c938596ac..a804eb98f0 100644 --- a/UI/DevScreens.cpp +++ b/UI/DevScreens.cpp @@ -1151,7 +1151,7 @@ struct { DebugShaderType type; const char *name; } shaderTypes[] = { // { SHADER_TYPE_GEOMETRY, "Geometry" }, { SHADER_TYPE_VERTEXLOADER, "VertexLoader" }, { SHADER_TYPE_PIPELINE, "Pipeline" }, - { SHADER_TYPE_DEPAL, "Depal" }, + { SHADER_TYPE_TEXTURE, "Texture" }, { SHADER_TYPE_SAMPLER, "Sampler" }, }; From f5e6754ac013a97698ef4c3ded5780176f43d58c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Wed, 20 Jul 2022 00:05:07 +0200 Subject: [PATCH 67/85] Special case depal lookups for Test Drive's strange usage. This implements the hack I suggested in #13355, where instead of first reducing the color to RGB565 as the real game does, we just take each channel at full precision and do the lookup according to the mask, linearly filtering the palette. This makes the game look a lot nicer and is also a small optimization, but the hack is very specific so kinda ugly in a way. --- Core/Compatibility.cpp | 1 + Core/Compatibility.h | 1 + GPU/Common/FragmentShaderGenerator.cpp | 25 +++++++++++++++++++++++++ GPU/Vulkan/DrawEngineVulkan.cpp | 4 ++-- GPU/Vulkan/DrawEngineVulkan.h | 2 +- assets/compat.ini | 7 +++++++ 6 files changed, 37 insertions(+), 3 deletions(-) diff --git a/Core/Compatibility.cpp b/Core/Compatibility.cpp index f17c1fd6a1..7a5e12d349 100644 --- a/Core/Compatibility.cpp +++ b/Core/Compatibility.cpp @@ -98,6 +98,7 @@ void Compatibility::CheckSettings(IniFile &iniFile, const std::string &gameID) { CheckSetting(iniFile, gameID, "AllowLargeFBTextureOffsets", &flags_.AllowLargeFBTextureOffsets); CheckSetting(iniFile, gameID, "AtracLoopHack", &flags_.AtracLoopHack); CheckSetting(iniFile, gameID, "DeswizzleDepth", &flags_.DeswizzleDepth); + CheckSetting(iniFile, gameID, "SmoothedDepal", &flags_.SmoothedDepal); } 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 29345aee42..5d52e3aec9 100644 --- a/Core/Compatibility.h +++ b/Core/Compatibility.h @@ -88,6 +88,7 @@ struct CompatFlags { bool AllowLargeFBTextureOffsets; bool AtracLoopHack; bool DeswizzleDepth; + bool SmoothedDepal; }; class IniFile; diff --git a/GPU/Common/FragmentShaderGenerator.cpp b/GPU/Common/FragmentShaderGenerator.cpp index f956217b38..e7fd8b5fed 100644 --- a/GPU/Common/FragmentShaderGenerator.cpp +++ b/GPU/Common/FragmentShaderGenerator.cpp @@ -23,8 +23,10 @@ #include "Common/GPU/OpenGL/GLFeatures.h" #include "Common/GPU/ShaderWriter.h" #include "Common/GPU/thin3d.h" +#include "Core/Compatibility.h" #include "Core/Reporting.h" #include "Core/Config.h" +#include "Core/System.h" #include "GPU/Common/GPUStateUtils.h" #include "GPU/Common/ShaderId.h" #include "GPU/Common/ShaderUniforms.h" @@ -88,6 +90,7 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu 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 = PSP_CoreParameter().compat.flags().SmoothedDepal; bool bgraTexture = id.Bit(FS_BIT_BGRA_TEXTURE); bool colorWriteMask = id.Bit(FS_BIT_COLOR_WRITEMASK) && compat.bitwiseOps; @@ -590,6 +593,28 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu } } } + } else if (shaderDepal && smoothedDepal) { + // 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); + } else { + WRITE(p, " vec2 uv = %s.xy;\n vec2 uv_round;\n", texcoord); + } + 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 mul = 32.0 / 256.0;\n"); + WRITE(p, " if (depalFmt == 0) {\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 == 5) { index0 = t.g; mul = 64.0 / 256.0; }\n"); + WRITE(p, " else if (depalShift == 11) { index0 = t.b; }\n"); + WRITE(p, " } else {\n"); + WRITE(p, " if (depalShift == 5) { index0 = t.g; }\n"); + WRITE(p, " else if (depalShift == 10) { index0 = t.b; }\n"); + WRITE(p, " }\n"); + WRITE(p, " t = %s(pal, vec2(index0 * mul, 0.0));\n", compat.texture); } else { if (doTextureProjection) { // We don't use textureProj because we need better control and it's probably not much of a savings anyway. diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index 256c1adbac..27d1fda33f 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -185,8 +185,8 @@ void DrawEngineVulkan::InitDeviceObjects() { samp.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; samp.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; samp.flags = 0; - samp.magFilter = VK_FILTER_NEAREST; - samp.minFilter = VK_FILTER_NEAREST; + samp.magFilter = VK_FILTER_LINEAR; + samp.minFilter = VK_FILTER_LINEAR; res = vkCreateSampler(device, &samp, nullptr, &samplerSecondary_); _dbg_assert_(VK_SUCCESS == res); res = vkCreateSampler(device, &samp, nullptr, &nullSampler_); diff --git a/GPU/Vulkan/DrawEngineVulkan.h b/GPU/Vulkan/DrawEngineVulkan.h index 48b8369fd7..e4a75f2a35 100644 --- a/GPU/Vulkan/DrawEngineVulkan.h +++ b/GPU/Vulkan/DrawEngineVulkan.h @@ -218,7 +218,7 @@ private: // Secondary texture for shader blending VkImageView boundSecondary_ = VK_NULL_HANDLE; VkImageView boundDepal_ = VK_NULL_HANDLE; - VkSampler samplerSecondary_ = VK_NULL_HANDLE; // This one is actually never used since we use fetch. + VkSampler samplerSecondary_ = VK_NULL_HANDLE; // This one is actually never used since we use fetch (except in SmoothedDepal mode for Test Drive). PrehashMap vai_; VulkanPushBuffer *vertexCache_; diff --git a/assets/compat.ini b/assets/compat.ini index 974a6216de..55ddf688fc 100644 --- a/assets/compat.ini +++ b/assets/compat.ini @@ -1276,3 +1276,10 @@ UCKS45048 = true UCJS18030 = true UCJS18047 = true NPJG00015 = true + +[SmoothedDepal] +# Test Drive Unlimited smoothed CLUT lookups. See comments in #13355 +ULET00386 = true +ULES00637 = true +ULKS46126 = true +ULUS10249 = true From 6558bde0f6fdc54d6d7787af472725d020090c40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Sun, 21 Aug 2022 23:46:01 +0200 Subject: [PATCH 68/85] Remove SmoothedDepal compat setting, instead detect the ramp directly. --- Core/Compatibility.cpp | 1 - Core/Compatibility.h | 1 - GPU/Common/FragmentShaderGenerator.cpp | 2 +- GPU/Common/ShaderId.cpp | 2 ++ GPU/Common/ShaderId.h | 1 + GPU/Common/TextureCacheCommon.cpp | 14 ++++----- GPU/Common/TextureShaderCommon.cpp | 41 +++++++++++++++++++++----- GPU/Common/TextureShaderCommon.h | 3 +- GPU/GLES/TextureCacheGLES.cpp | 2 +- GPU/GPUState.h | 4 ++- GPU/Vulkan/TextureCacheVulkan.cpp | 2 +- assets/compat.ini | 7 ----- 12 files changed, 51 insertions(+), 29 deletions(-) diff --git a/Core/Compatibility.cpp b/Core/Compatibility.cpp index 7a5e12d349..f17c1fd6a1 100644 --- a/Core/Compatibility.cpp +++ b/Core/Compatibility.cpp @@ -98,7 +98,6 @@ void Compatibility::CheckSettings(IniFile &iniFile, const std::string &gameID) { CheckSetting(iniFile, gameID, "AllowLargeFBTextureOffsets", &flags_.AllowLargeFBTextureOffsets); CheckSetting(iniFile, gameID, "AtracLoopHack", &flags_.AtracLoopHack); CheckSetting(iniFile, gameID, "DeswizzleDepth", &flags_.DeswizzleDepth); - CheckSetting(iniFile, gameID, "SmoothedDepal", &flags_.SmoothedDepal); } 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 5d52e3aec9..29345aee42 100644 --- a/Core/Compatibility.h +++ b/Core/Compatibility.h @@ -88,7 +88,6 @@ struct CompatFlags { bool AllowLargeFBTextureOffsets; bool AtracLoopHack; bool DeswizzleDepth; - bool SmoothedDepal; }; class IniFile; diff --git a/GPU/Common/FragmentShaderGenerator.cpp b/GPU/Common/FragmentShaderGenerator.cpp index e7fd8b5fed..a38e70fd5c 100644 --- a/GPU/Common/FragmentShaderGenerator.cpp +++ b/GPU/Common/FragmentShaderGenerator.cpp @@ -90,7 +90,7 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu 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 = PSP_CoreParameter().compat.flags().SmoothedDepal; + bool smoothedDepal = id.Bit(FS_BIT_SHADER_SMOOTHED_DEPAL); bool bgraTexture = id.Bit(FS_BIT_BGRA_TEXTURE); bool colorWriteMask = id.Bit(FS_BIT_COLOR_WRITEMASK) && compat.bitwiseOps; diff --git a/GPU/Common/ShaderId.cpp b/GPU/Common/ShaderId.cpp index 510e90e929..849a1b8b19 100644 --- a/GPU/Common/ShaderId.cpp +++ b/GPU/Common/ShaderId.cpp @@ -261,6 +261,7 @@ void ComputeFragmentShaderID(FShaderID *id_out, const Draw::Bugs &bugs) { bool doTextureAlpha = gstate.isTextureAlphaUsed(); bool doFlatShading = gstate.getShadeMode() == GE_SHADE_FLAT; bool useShaderDepal = gstate_c.useShaderDepal; + bool useSmoothedDepal = gstate_c.useSmoothedShaderDepal; bool colorWriteMask = IsColorWriteMaskComplex(gstate_c.allowFramebufferRead); // Note how we here recompute some of the work already done in state mapping. @@ -290,6 +291,7 @@ void ComputeFragmentShaderID(FShaderID *id_out, const Draw::Bugs &bugs) { } 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.SetBit(FS_BIT_3D_TEXTURE, gstate_c.curTextureIs3D); } diff --git a/GPU/Common/ShaderId.h b/GPU/Common/ShaderId.h index 8dcee32c1e..a105af6746 100644 --- a/GPU/Common/ShaderId.h +++ b/GPU/Common/ShaderId.h @@ -94,6 +94,7 @@ enum FShaderBit : uint8_t { FS_BIT_NO_DEPTH_CANNOT_DISCARD_STENCIL = 49, FS_BIT_COLOR_WRITEMASK = 50, FS_BIT_3D_TEXTURE = 51, + FS_BIT_SHADER_SMOOTHED_DEPAL = 52, }; static inline FShaderBit operator +(FShaderBit bit, int i) { diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index de6c840722..6d14e0cd4e 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -1886,8 +1886,8 @@ void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer const GEPaletteFormat clutFormat = gstate.getClutPaletteFormat(); // Very icky conflation here of native and thin3d rendering. This will need careful work per backend in BindAsClutTexture. - Draw::Texture *clutTexture = textureShaderCache_->GetClutTexture(clutFormat, clutHash_, clutBufRaw_); - BindAsClutTexture(clutTexture); + ClutTexture clutTexture = textureShaderCache_->GetClutTexture(clutFormat, clutHash_, clutBufRaw_); + BindAsClutTexture(clutTexture.texture); framebufferManager_->BindFramebufferAsColorTexture(0, framebuffer, BINDFBCOLOR_MAY_COPY_WITH_UV | BINDFBCOLOR_APPLY_TEX_OFFSET); // Vulkan needs to do some extra work here to pick out the native handle from Draw. @@ -1901,7 +1901,7 @@ void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer // Since we started/ended render passes, might need these. gstate_c.Dirty(DIRTY_DEPAL); - gstate_c.SetUseShaderDepal(true); + gstate_c.SetUseShaderDepal(true, gstate.getClutIndexStartPos() == 0 && gstate.getClutIndexMask() <= clutTexture.rampLength); gstate_c.depalFramebufferFormat = framebuffer->drawnFormat; const u32 bytesPerColor = clutFormat == GE_CMODE_32BIT_ABGR8888 ? sizeof(u32) : sizeof(u16); const u32 clutTotalColors = clutMaxBytes_ / bytesPerColor; @@ -1914,12 +1914,12 @@ void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer } textureShader = textureShaderCache_->GetDepalettizeShader(clutMode, texFormat, depth ? GE_FORMAT_DEPTH16 : framebuffer->drawnFormat); - gstate_c.SetUseShaderDepal(false); + gstate_c.SetUseShaderDepal(false, false); } if (textureShader) { const GEPaletteFormat clutFormat = gstate.getClutPaletteFormat(); - Draw::Texture *clutTexture = textureShaderCache_->GetClutTexture(clutFormat, clutHash_, clutBufRaw_); + ClutTexture clutTexture = textureShaderCache_->GetClutTexture(clutFormat, clutHash_, clutBufRaw_); Draw::Framebuffer *depalFBO = framebufferManager_->GetTempFBO(TempFBO::DEPAL, framebuffer->renderWidth, framebuffer->renderHeight); draw_->BindTexture(0, nullptr); draw_->BindTexture(1, nullptr); @@ -1930,7 +1930,7 @@ void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer draw_->SetViewports(1, &vp); draw_->BindFramebufferAsTexture(framebuffer->fbo, 0, depth ? Draw::FB_DEPTH_BIT : Draw::FB_COLOR_BIT, 0); - draw_->BindTexture(1, clutTexture); + draw_->BindTexture(1, clutTexture.texture); Draw::SamplerState *nearest = textureShaderCache_->GetSampler(); draw_->BindSamplerStates(0, 1, &nearest); draw_->BindSamplerStates(1, 1, &nearest); @@ -1958,7 +1958,7 @@ void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer framebufferManager_->BindFramebufferAsColorTexture(0, framebuffer, BINDFBCOLOR_MAY_COPY_WITH_UV | BINDFBCOLOR_APPLY_TEX_OFFSET); BoundFramebufferTexture(); - gstate_c.SetUseShaderDepal(false); + gstate_c.SetUseShaderDepal(false, false); gstate_c.SetTextureFullAlpha(gstate.getTextureFormat() == GE_TFMT_5650); } diff --git a/GPU/Common/TextureShaderCommon.cpp b/GPU/Common/TextureShaderCommon.cpp index defbeb1575..1f684af5da 100644 --- a/GPU/Common/TextureShaderCommon.cpp +++ b/GPU/Common/TextureShaderCommon.cpp @@ -51,22 +51,22 @@ void TextureShaderCache::DeviceLost() { Clear(); } -Draw::Texture *TextureShaderCache::GetClutTexture(GEPaletteFormat clutFormat, const u32 clutHash, u32 *rawClut) { +ClutTexture TextureShaderCache::GetClutTexture(GEPaletteFormat clutFormat, const u32 clutHash, u32 *rawClut) { // Simplistic, but works well enough. u32 clutId = clutHash ^ (uint32_t)clutFormat; auto oldtex = texCache_.find(clutId); if (oldtex != texCache_.end()) { oldtex->second->lastFrame = gpuStats.numFlips; - return oldtex->second->texture; + return *oldtex->second; } - int texturePixels = clutFormat == GE_CMODE_32BIT_ABGR8888 ? 256 : 512; + int maxClutEntries = clutFormat == GE_CMODE_32BIT_ABGR8888 ? 256 : 512; ClutTexture *tex = new ClutTexture(); Draw::TextureDesc desc{}; - desc.width = texturePixels; + desc.width = maxClutEntries; desc.height = 1; desc.depth = 1; desc.mipLevels = 1; @@ -81,24 +81,49 @@ Draw::Texture *TextureShaderCache::GetClutTexture(GEPaletteFormat clutFormat, co desc.initData.push_back((const uint8_t *)rawClut); break; case GEPaletteFormat::GE_CMODE_16BIT_BGR5650: - ConvertRGB565ToRGBA8888((u32 *)convTemp, (const u16 *)rawClut, texturePixels); + ConvertRGB565ToRGBA8888((u32 *)convTemp, (const u16 *)rawClut, maxClutEntries); desc.initData.push_back(convTemp); break; case GEPaletteFormat::GE_CMODE_16BIT_ABGR5551: - ConvertRGBA5551ToRGBA8888((u32 *)convTemp, (const u16 *)rawClut, texturePixels); + ConvertRGBA5551ToRGBA8888((u32 *)convTemp, (const u16 *)rawClut, maxClutEntries); desc.initData.push_back(convTemp); break; case GEPaletteFormat::GE_CMODE_16BIT_ABGR4444: - ConvertRGBA4444ToRGBA8888((u32 *)convTemp, (const u16 *)rawClut, texturePixels); + ConvertRGBA4444ToRGBA8888((u32 *)convTemp, (const u16 *)rawClut, maxClutEntries); desc.initData.push_back(convTemp); break; } + int lastR = 0; + int lastG = 0; + int lastB = 0; + int lastA = 0; + + int rampLength = 0; + // Quick check for how many continouosly growing entries we have at the start. + // Bilinearly filtering CLUTs only really makes sense for this kind of ramp. + for (int i = 0; i < maxClutEntries; i++) { + rampLength = i + 1; + int r = desc.initData[0][i * 4]; + int g = desc.initData[0][i * 4 + 1]; + int b = desc.initData[0][i * 4 + 2]; + int a = desc.initData[0][i * 4 + 3]; + if (r < lastR || g < lastG || b < lastB || a < lastA) { + break; + } else { + lastR = r; + lastG = g; + lastB = b; + lastA = a; + } + } + tex->texture = draw_->CreateTexture(desc); tex->lastFrame = gpuStats.numFlips; + tex->rampLength = rampLength; texCache_[clutId] = tex; - return tex->texture; + return *tex; } void TextureShaderCache::Clear() { diff --git a/GPU/Common/TextureShaderCommon.h b/GPU/Common/TextureShaderCommon.h index e2967ea89c..f5ff0af8dc 100644 --- a/GPU/Common/TextureShaderCommon.h +++ b/GPU/Common/TextureShaderCommon.h @@ -39,6 +39,7 @@ class ClutTexture { public: Draw::Texture *texture; int lastFrame; + int rampLength; }; // For CLUT depal shaders, and other pre-bind texture shaders. @@ -49,7 +50,7 @@ public: ~TextureShaderCache(); TextureShader *GetDepalettizeShader(uint32_t clutMode, GETextureFormat texFormat, GEBufferFormat pixelFormat); - Draw::Texture *GetClutTexture(GEPaletteFormat clutFormat, const u32 clutHash, u32 *rawClut); + ClutTexture GetClutTexture(GEPaletteFormat clutFormat, const u32 clutHash, u32 *rawClut); Draw::SamplerState *GetSampler(); diff --git a/GPU/GLES/TextureCacheGLES.cpp b/GPU/GLES/TextureCacheGLES.cpp index 6fb19338d9..3af9488560 100644 --- a/GPU/GLES/TextureCacheGLES.cpp +++ b/GPU/GLES/TextureCacheGLES.cpp @@ -225,7 +225,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); + gstate_c.SetUseShaderDepal(false, false); } void TextureCacheGLES::Unbind() { diff --git a/GPU/GPUState.h b/GPU/GPUState.h index ae1c2c6510..f75a09fdad 100644 --- a/GPU/GPUState.h +++ b/GPU/GPUState.h @@ -529,9 +529,10 @@ struct GPUStateCache { bool IsDirty(u64 what) const { return (dirty & what) != 0ULL; } - void SetUseShaderDepal(bool depal) { + void SetUseShaderDepal(bool depal, bool smoothed) { if (depal != useShaderDepal) { useShaderDepal = depal; + useSmoothedShaderDepal = smoothed; Dirty(DIRTY_FRAGMENTSHADER_STATE); } } @@ -635,6 +636,7 @@ struct GPUStateCache { int spline_num_points_u; bool useShaderDepal; + bool useSmoothedShaderDepal; GEBufferFormat depalFramebufferFormat; u32 getRelativeAddress(u32 data) const; diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index 6c15264b1f..522d88ce5a 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -402,7 +402,7 @@ void TextureCacheVulkan::BindTexture(TexCacheEntry *entry) { curSampler_ = samplerCache_.GetOrCreateSampler(samplerKey); imageView_ = entry->vkTex->GetImageView(); drawEngine_->SetDepalTexture(VK_NULL_HANDLE); - gstate_c.SetUseShaderDepal(false); + gstate_c.SetUseShaderDepal(false, false); } void TextureCacheVulkan::ApplySamplingParams(const SamplerCacheKey &key) { diff --git a/assets/compat.ini b/assets/compat.ini index 55ddf688fc..974a6216de 100644 --- a/assets/compat.ini +++ b/assets/compat.ini @@ -1276,10 +1276,3 @@ UCKS45048 = true UCJS18030 = true UCJS18047 = true NPJG00015 = true - -[SmoothedDepal] -# Test Drive Unlimited smoothed CLUT lookups. See comments in #13355 -ULET00386 = true -ULES00637 = true -ULKS46126 = true -ULUS10249 = true From 2a6015c1e3b7ae3ac0ee87584d4edd32cfaceb13 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Mon, 22 Aug 2022 10:32:02 +0200 Subject: [PATCH 69/85] Better checks for smoothed depal --- GPU/Common/FragmentShaderGenerator.cpp | 3 +++ GPU/Common/TextureCacheCommon.cpp | 28 +++++++++++++++++++++++++- 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/GPU/Common/FragmentShaderGenerator.cpp b/GPU/Common/FragmentShaderGenerator.cpp index a38e70fd5c..f278363e5f 100644 --- a/GPU/Common/FragmentShaderGenerator.cpp +++ b/GPU/Common/FragmentShaderGenerator.cpp @@ -602,6 +602,9 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu } else { WRITE(p, " 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. 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"); diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index 6d14e0cd4e..93d1201286 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -1859,6 +1859,31 @@ bool CanDepalettize(GETextureFormat texFormat, GEBufferFormat bufferFormat) { } } +// If the palette is detected as a smooth ramp, we can interpolate for higher color precision. +// But we only do it if the mask/shift exactly matches a color channel, else something different might be going +// on and we definitely don't want to interpolate. +// Great enhancement for Test Drive. +static bool CanUseSmoothDepal(const GPUgstate &gstate, GEBufferFormat framebufferFormat, int rampLength) { + if (gstate.getClutIndexStartPos() == 0 && + gstate.getClutIndexMask() <= rampLength) { + switch (framebufferFormat) { + case GE_FORMAT_565: + if (gstate.getClutIndexShift() == 0 || gstate.getClutIndexShift() == 11) { + return gstate.getClutIndexMask() == 0x1F; + } else if (gstate.getClutIndexShift() == 5) { + return gstate.getClutIndexMask() == 0x3F; + } + break; + case GE_FORMAT_5551: + if (gstate.getClutIndexShift() == 0 || gstate.getClutIndexShift() == 5 || gstate.getClutIndexShift() == 10) { + return gstate.getClutIndexMask() == 0x1F; + } + break; + } + } + return false; +} + void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer, GETextureFormat texFormat, RasterChannel channel) { TextureShader *textureShader = nullptr; uint32_t clutMode = gstate.clutformat & 0xFFFFFF; @@ -1901,7 +1926,8 @@ void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer // Since we started/ended render passes, might need these. gstate_c.Dirty(DIRTY_DEPAL); - gstate_c.SetUseShaderDepal(true, gstate.getClutIndexStartPos() == 0 && gstate.getClutIndexMask() <= clutTexture.rampLength); + + gstate_c.SetUseShaderDepal(true, CanUseSmoothDepal(gstate, framebuffer->drawnFormat, clutTexture.rampLength)); gstate_c.depalFramebufferFormat = framebuffer->drawnFormat; const u32 bytesPerColor = clutFormat == GE_CMODE_32BIT_ABGR8888 ? sizeof(u32) : sizeof(u16); const u32 clutTotalColors = clutMaxBytes_ / bytesPerColor; From e3943f6d0ddf7ce9d5512d571cfa7ca0d3c8db8f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Mon, 22 Aug 2022 11:07:25 +0200 Subject: [PATCH 70/85] Implement smoothed depal for the "old" depal path as well. --- GPU/Common/DepalettizeShaderCommon.cpp | 69 ++++++++++++++++++++------ GPU/Common/DepalettizeShaderCommon.h | 1 + GPU/Common/TextureCacheCommon.cpp | 18 ++++--- GPU/Common/TextureShaderCommon.cpp | 36 ++++++++++---- GPU/Common/TextureShaderCommon.h | 5 +- 5 files changed, 98 insertions(+), 31 deletions(-) diff --git a/GPU/Common/DepalettizeShaderCommon.cpp b/GPU/Common/DepalettizeShaderCommon.cpp index 2b9ddca413..6e34d02402 100644 --- a/GPU/Common/DepalettizeShaderCommon.cpp +++ b/GPU/Common/DepalettizeShaderCommon.cpp @@ -45,7 +45,7 @@ static const VaryingDef varyings[1] = { }; // Uses integer instructions available since OpenGL 3.0, ES 3.0 (and 2.0 with extensions), and of course Vulkan and D3D11. -void GenerateDepalShader300(ShaderWriter &writer, const DepalConfig &config, const ShaderLanguageDesc &lang) { +void GenerateDepalShader300(ShaderWriter &writer, const DepalConfig &config) { const int shift = config.shift; const int mask = config.mask; @@ -140,7 +140,7 @@ void GenerateDepalShader300(ShaderWriter &writer, const DepalConfig &config, con } // FP only, to suit GL(ES) 2.0 and DX9 -void GenerateDepalShaderFloat(ShaderWriter &writer, const DepalConfig &config, const ShaderLanguageDesc &lang) { +void GenerateDepalShaderFloat(ShaderWriter &writer, const DepalConfig &config) { char lookupMethod[128] = "index.r"; const int shift = config.shift; @@ -288,23 +288,64 @@ void GenerateDepalShaderFloat(ShaderWriter &writer, const DepalConfig &config, c writer.C(" vec4 outColor = ").SampleTexture2D("pal", "vec2(coord, 0.0)").C(";\n"); } +void GenerateDepalSmoothed(ShaderWriter &writer, const DepalConfig &config) { + const char *sourceChannel = "error"; + float indexMultiplier = 32.0f; + + if (config.bufferFormat == GE_FORMAT_5551) { + _dbg_assert_(config.mask == 0x1F); + switch (config.shift) { + case 0: sourceChannel = "r"; break; + case 5: sourceChannel = "g"; break; + case 10: sourceChannel = "b"; break; + default: _dbg_assert_(false); + } + } else if (config.bufferFormat == GE_FORMAT_565) { + _dbg_assert_(config.mask == 0x1F || config.mask == 0x3F); + switch (config.shift) { + case 0: sourceChannel = "r"; break; + case 5: sourceChannel = "g"; indexMultiplier = 64.0f; break; + case 11: sourceChannel = "b"; break; + default: _dbg_assert_(false); + } + } else { + _dbg_assert_(false); + } + + writer.C(" float index = ").SampleTexture2D("tex", "v_texcoord").F(".%s * %0.1f;\n", sourceChannel, indexMultiplier); + + float texturePixels = 256.f; + if (config.clutFormat != GE_CMODE_32BIT_ABGR8888) { + texturePixels = 512.f; + } + + writer.F(" float coord = (index + 0.5) * %f;\n", 1.0 / texturePixels); + writer.C(" vec4 outColor = ").SampleTexture2D("pal", "vec2(coord, 0.0)").C(";\n"); +} + void GenerateDepalFs(char *buffer, const DepalConfig &config, const ShaderLanguageDesc &lang) { ShaderWriter writer(buffer, lang, ShaderStage::Fragment); writer.DeclareSamplers(samplers); writer.HighPrecisionFloat(); writer.BeginFSMain(Slice::empty(), varyings, FSFLAG_NONE); - switch (lang.shaderLanguage) { - case HLSL_D3D9: - case GLSL_1xx: - GenerateDepalShaderFloat(writer, config, lang); - break; - case GLSL_VULKAN: - case GLSL_3xx: - case HLSL_D3D11: - GenerateDepalShader300(writer, config, lang); - break; - default: - _assert_msg_(false, "Depal shader language not supported: %d", (int)lang.shaderLanguage); + if (config.smoothedDepal) { + // Handles a limited set of cases, but doesn't need any integer math so we don't + // need two variants. + GenerateDepalSmoothed(writer, config); + } else { + switch (lang.shaderLanguage) { + case HLSL_D3D9: + case GLSL_1xx: + GenerateDepalShaderFloat(writer, config); + break; + case GLSL_VULKAN: + case GLSL_3xx: + case HLSL_D3D11: + GenerateDepalShader300(writer, config); + break; + default: + _assert_msg_(false, "Depal shader language not supported: %d", (int)lang.shaderLanguage); + } } writer.EndFSMain("outColor", FSFLAG_NONE); } diff --git a/GPU/Common/DepalettizeShaderCommon.h b/GPU/Common/DepalettizeShaderCommon.h index 91186f5d20..322784c0f0 100644 --- a/GPU/Common/DepalettizeShaderCommon.h +++ b/GPU/Common/DepalettizeShaderCommon.h @@ -31,6 +31,7 @@ struct DepalConfig { GEPaletteFormat clutFormat; GETextureFormat textureFormat; GEBufferFormat bufferFormat; + bool smoothedDepal; }; void GenerateDepalFs(char *buffer, const DepalConfig &config, const ShaderLanguageDesc &lang); diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index 93d1201286..0f3e82ff49 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -1906,12 +1906,17 @@ void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer break; } + const GEPaletteFormat clutFormat = gstate.getClutPaletteFormat(); + ClutTexture clutTexture{}; + bool smoothedDepal = false; + if (need_depalettize && !g_Config.bDisableSlowFramebufEffects) { + clutTexture = textureShaderCache_->GetClutTexture(clutFormat, clutHash_, clutBufRaw_); + smoothedDepal = CanUseSmoothDepal(gstate, framebuffer->drawnFormat, clutTexture.rampLength); + if (useShaderDepal) { - const GEPaletteFormat clutFormat = gstate.getClutPaletteFormat(); // Very icky conflation here of native and thin3d rendering. This will need careful work per backend in BindAsClutTexture. - ClutTexture clutTexture = textureShaderCache_->GetClutTexture(clutFormat, clutHash_, clutBufRaw_); BindAsClutTexture(clutTexture.texture); framebufferManager_->BindFramebufferAsColorTexture(0, framebuffer, BINDFBCOLOR_MAY_COPY_WITH_UV | BINDFBCOLOR_APPLY_TEX_OFFSET); @@ -1927,7 +1932,7 @@ void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer // Since we started/ended render passes, might need these. gstate_c.Dirty(DIRTY_DEPAL); - gstate_c.SetUseShaderDepal(true, CanUseSmoothDepal(gstate, framebuffer->drawnFormat, clutTexture.rampLength)); + gstate_c.SetUseShaderDepal(true, smoothedDepal); gstate_c.depalFramebufferFormat = framebuffer->drawnFormat; const u32 bytesPerColor = clutFormat == GE_CMODE_32BIT_ABGR8888 ? sizeof(u32) : sizeof(u16); const u32 clutTotalColors = clutMaxBytes_ / bytesPerColor; @@ -1939,7 +1944,7 @@ void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer return; } - textureShader = textureShaderCache_->GetDepalettizeShader(clutMode, texFormat, depth ? GE_FORMAT_DEPTH16 : framebuffer->drawnFormat); + textureShader = textureShaderCache_->GetDepalettizeShader(clutMode, texFormat, depth ? GE_FORMAT_DEPTH16 : framebuffer->drawnFormat, smoothedDepal); gstate_c.SetUseShaderDepal(false, false); } @@ -1957,9 +1962,10 @@ void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer draw_->BindFramebufferAsTexture(framebuffer->fbo, 0, depth ? Draw::FB_DEPTH_BIT : Draw::FB_COLOR_BIT, 0); draw_->BindTexture(1, clutTexture.texture); - Draw::SamplerState *nearest = textureShaderCache_->GetSampler(); + Draw::SamplerState *nearest = textureShaderCache_->GetSampler(false); + Draw::SamplerState *clutSampler = textureShaderCache_->GetSampler(smoothedDepal); draw_->BindSamplerStates(0, 1, &nearest); - draw_->BindSamplerStates(1, 1, &nearest); + draw_->BindSamplerStates(1, 1, &clutSampler); textureShaderCache_->ApplyShader(textureShader, framebuffer->bufferWidth, framebuffer->bufferHeight, framebuffer->renderWidth, framebuffer->renderHeight, diff --git a/GPU/Common/TextureShaderCommon.cpp b/GPU/Common/TextureShaderCommon.cpp index 1f684af5da..c30ccb0204 100644 --- a/GPU/Common/TextureShaderCommon.cpp +++ b/GPU/Common/TextureShaderCommon.cpp @@ -147,6 +147,10 @@ void TextureShaderCache::Clear() { nearestSampler_->Release(); nearestSampler_ = nullptr; } + if (linearSampler_) { + linearSampler_->Release(); + linearSampler_ = nullptr; + } } void TextureShaderCache::Decimate() { @@ -161,15 +165,28 @@ void TextureShaderCache::Decimate() { } } -Draw::SamplerState *TextureShaderCache::GetSampler() { - if (!nearestSampler_) { - Draw::SamplerStateDesc desc{}; - desc.wrapU = Draw::TextureAddressMode::CLAMP_TO_EDGE; - desc.wrapV = Draw::TextureAddressMode::CLAMP_TO_EDGE; - desc.wrapW = Draw::TextureAddressMode::CLAMP_TO_EDGE; - nearestSampler_ = draw_->CreateSamplerState(desc); +Draw::SamplerState *TextureShaderCache::GetSampler(bool linearFilter) { + if (linearFilter) { + if (!linearSampler_) { + Draw::SamplerStateDesc desc{}; + desc.magFilter = Draw::TextureFilter::LINEAR; + desc.minFilter = Draw::TextureFilter::LINEAR; + desc.wrapU = Draw::TextureAddressMode::CLAMP_TO_EDGE; + desc.wrapV = Draw::TextureAddressMode::CLAMP_TO_EDGE; + desc.wrapW = Draw::TextureAddressMode::CLAMP_TO_EDGE; + linearSampler_ = draw_->CreateSamplerState(desc); + } + return linearSampler_; + } else { + if (!nearestSampler_) { + Draw::SamplerStateDesc desc{}; + desc.wrapU = Draw::TextureAddressMode::CLAMP_TO_EDGE; + desc.wrapV = Draw::TextureAddressMode::CLAMP_TO_EDGE; + desc.wrapW = Draw::TextureAddressMode::CLAMP_TO_EDGE; + nearestSampler_ = draw_->CreateSamplerState(desc); + } + return nearestSampler_; } - return nearestSampler_; } TextureShader *TextureShaderCache::CreateShader(const char *fs) { @@ -220,7 +237,7 @@ TextureShader *TextureShaderCache::CreateShader(const char *fs) { return depal; } -TextureShader *TextureShaderCache::GetDepalettizeShader(uint32_t clutMode, GETextureFormat textureFormat, GEBufferFormat bufferFormat) { +TextureShader *TextureShaderCache::GetDepalettizeShader(uint32_t clutMode, GETextureFormat textureFormat, GEBufferFormat bufferFormat, bool smoothedDepal) { using namespace Draw; // Generate an ID for depal shaders. @@ -240,6 +257,7 @@ TextureShader *TextureShaderCache::GetDepalettizeShader(uint32_t clutMode, GETex config.mask = gstate.getClutIndexMask(); config.bufferFormat = bufferFormat; config.textureFormat = textureFormat; + config.smoothedDepal = smoothedDepal; char *buffer = new char[4096]; GenerateDepalFs(buffer, config, draw_->GetShaderLanguageDesc()); diff --git a/GPU/Common/TextureShaderCommon.h b/GPU/Common/TextureShaderCommon.h index f5ff0af8dc..583aa3d516 100644 --- a/GPU/Common/TextureShaderCommon.h +++ b/GPU/Common/TextureShaderCommon.h @@ -49,10 +49,10 @@ public: TextureShaderCache(Draw::DrawContext *draw); ~TextureShaderCache(); - TextureShader *GetDepalettizeShader(uint32_t clutMode, GETextureFormat texFormat, GEBufferFormat pixelFormat); + TextureShader *GetDepalettizeShader(uint32_t clutMode, GETextureFormat texFormat, GEBufferFormat pixelFormat, bool smoothedDepal); ClutTexture GetClutTexture(GEPaletteFormat clutFormat, const u32 clutHash, u32 *rawClut); - Draw::SamplerState *GetSampler(); + Draw::SamplerState *GetSampler(bool linearFilter); void ApplyShader(TextureShader *shader, float bufferW, float bufferH, int renderW, int renderH, const KnownVertexBounds &bounds, u32 uoff, u32 voff); @@ -70,6 +70,7 @@ private: Draw::DrawContext *draw_; Draw::ShaderModule *vertexShader_ = nullptr; Draw::SamplerState *nearestSampler_ = nullptr; + Draw::SamplerState *linearSampler_ = nullptr; std::map depalCache_; std::map texCache_; From 51686f4936f7547cf6f1cfe686c2a5993587e8b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Thu, 18 Aug 2022 10:51:50 +0200 Subject: [PATCH 71/85] Copy color from overlapping framebuffers on bind, under certain conditions. Leads to much faster performance in Juiced 2. This will later be expanded to handle more things in a more elegant way, like the framebuffer overlap in God of War for the shadows and color reinterpretation in a generic way. Fixes #15728 --- GPU/Common/FramebufferManagerCommon.cpp | 162 ++++++++++++++++++------ GPU/Common/FramebufferManagerCommon.h | 1 + GPU/Common/TextureCacheCommon.cpp | 4 +- GPU/GPU.h | 4 + GPU/GPUCommon.cpp | 5 +- GPU/ge_constants.h | 5 + 6 files changed, 136 insertions(+), 45 deletions(-) diff --git a/GPU/Common/FramebufferManagerCommon.cpp b/GPU/Common/FramebufferManagerCommon.cpp index bfdc23815f..6cf098cbed 100644 --- a/GPU/Common/FramebufferManagerCommon.cpp +++ b/GPU/Common/FramebufferManagerCommon.cpp @@ -190,7 +190,7 @@ void FramebufferManagerCommon::EstimateDrawingSize(u32 fb_address, GEBufferForma // Unless the game is using overlapping buffers, the next buffer should be far enough away. // This catches some cases where we can know this. // Hmm. The problem is that we could only catch it for the first of two buffers... - const u32 bpp = fb_format == GE_FORMAT_8888 ? 4 : 2; + const u32 bpp = BufferFormatBytesPerPixel(fb_format); int avail_height = (nearest_address - fb_address) / (fb_stride * bpp); if (avail_height < drawing_height && avail_height == region_height) { drawing_width = std::min(region_width, fb_stride); @@ -285,7 +285,7 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame for (size_t i = 0; i < vfbs_.size(); ++i) { VirtualFramebuffer *v = vfbs_[i]; - const u32 bpp = v->format == GE_FORMAT_8888 ? 4 : 2; + const u32 bpp = BufferFormatBytesPerPixel(v->format); if (params.fb_address == v->fb_address) { vfb = v; @@ -332,20 +332,6 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame drawing_width += x_offset; break; } - } else if (params.fb_address > v->fb_address && params.fb_address < v_fb_end_ptr && PSP_CoreParameter().compat.flags().AllowLargeFBTextureOffsets) { - // Fixes Juiced 2, though causes a lot of copying due to self-texturing. A better solution - // would be to copy from the overlapping framebuffer on bind. - - if (params.fb_address % params.fb_stride == v->fb_address % params.fb_stride) { - // Framebuffers are overlapping on the Y axis. - const int y_offset = (params.fb_address - v->fb_address) / (bpp * params.fb_stride); - - vfb = v; - gstate_c.SetCurRTOffset(0, y_offset); - // To prevent the newSize code from being confused. - drawing_height += y_offset; - break; - } } else { // We ignore this match. // TODO: We can allow X/Y overlaps too, but haven't seen any so safer to not. @@ -416,8 +402,10 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame ResizeFramebufFBO(vfb, drawing_width, drawing_height, true); NotifyRenderFramebufferCreated(vfb); - // Note that we do not even think about depth right now. + // Note that we do not even think about depth right now. That'll be handled + // on the first depth access, which will call SetDepthFramebuffer. + CopyToColorFromOverlappingFramebuffers(vfb); SetColorUpdated(vfb, skipDrawReason); INFO_LOG(FRAMEBUF, "Creating FBO for %08x (z: %08x) : %d x %d x %s", vfb->fb_address, vfb->z_address, vfb->width, vfb->height, GeBufferFormatToString(vfb->format)); @@ -475,6 +463,7 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame VirtualFramebuffer *prev = currentRenderVfb_; currentRenderVfb_ = vfb; NotifyRenderFramebufferSwitched(prev, vfb, params.isClearingDepth); + CopyToColorFromOverlappingFramebuffers(vfb); gstate_c.usingDepth = false; // reset depth buffer tracking } else { // Something changed, but we still got the same framebuffer we were already rendering to. @@ -512,20 +501,25 @@ void FramebufferManagerCommon::SetDepthFrameBuffer(bool isClearingDepth) { currentRenderVfb_->depthBindSeq = GetBindSeqCount(); } +struct CopySource { + VirtualFramebuffer *vfb; + RasterChannel channel; + int xOffset; + int yOffset; + + int seq() const { + return channel == RASTER_DEPTH ? vfb->depthBindSeq : vfb->colorBindSeq; + } + + bool operator < (const CopySource &other) const { + return seq() < other.seq(); + } +}; + +// Not sure if it's more profitable to always do these copies with raster (which may screw up early-Z due to explicit depth buffer write) +// or to use image copies when possible (which may make it easier for the driver to preserve early-Z, but on the other hand, will cost additional memory +// bandwidth on tilers due to the load operation, which we might otherwise be able to skip). void FramebufferManagerCommon::CopyToDepthFromOverlappingFramebuffers(VirtualFramebuffer *dest) { - struct CopySource { - VirtualFramebuffer *vfb; - RasterChannel channel; - - int seq() const { - return channel == RASTER_DEPTH ? vfb->depthBindSeq : vfb->colorBindSeq; - } - - bool operator < (const CopySource &other) const { - return seq() < other.seq(); - } - }; - std::vector sources; for (auto src : vfbs_) { if (src == dest) @@ -534,10 +528,10 @@ void FramebufferManagerCommon::CopyToDepthFromOverlappingFramebuffers(VirtualFra if (src->fb_address == dest->z_address && src->fb_stride == dest->z_stride && src->format == GE_FORMAT_565) { if (src->colorBindSeq > dest->depthBindSeq) { // Source has newer data than the current buffer, use it. - sources.push_back(CopySource{ src, RASTER_COLOR }); + sources.push_back(CopySource{ src, RASTER_COLOR, 0, 0 }); } } else if (src->z_address == dest->z_address && src->z_stride == dest->z_stride && src->depthBindSeq > dest->depthBindSeq) { - sources.push_back(CopySource{ src, RASTER_DEPTH }); + sources.push_back(CopySource{ src, RASTER_DEPTH, 0, 0 }); } else { // TODO: Do more detailed overlap checks here. } @@ -573,6 +567,8 @@ void FramebufferManagerCommon::CopyToDepthFromOverlappingFramebuffers(VirtualFra shader = DRAW2D_565_TO_DEPTH_DESWIZZLE; } + gpuStats.numReinterpretCopies++; + // Copying color to depth. BlitUsingRaster( src->fbo, 0.0f, 0.0f, src->renderWidth, src->renderHeight, @@ -584,6 +580,87 @@ void FramebufferManagerCommon::CopyToDepthFromOverlappingFramebuffers(VirtualFra gstate_c.Dirty(DIRTY_TEXTURE_IMAGE | DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_RASTER_STATE | DIRTY_DEPTHSTENCIL_STATE | DIRTY_BLEND_STATE); } +// Call this after the target has been bound for rendering. For color, raster is probably always going to win over blits/copies. +void FramebufferManagerCommon::CopyToColorFromOverlappingFramebuffers(VirtualFramebuffer *dst) { + std::vector sources; + for (auto src : vfbs_) { + // Discard old and equal potential inputs. + if (src == dst || src->colorBindSeq < dst->colorBindSeq) + continue; + + if (src->fb_address == dst->fb_address && src->fb_stride == dst->fb_stride) { + // Another render target at the exact same location but gotta be a different format, otherwise + // it would be the same. + _dbg_assert_(src->format != dst->format); + WARN_LOG_ONCE(reint, G3D, "Reinterpret detected at %08x", src->fb_address); + // This is where we'll do reinterprets in the future. + } else if (src->fb_stride == dst->fb_stride && src->format == dst->format) { + u32 bytesPerPixel = BufferFormatBytesPerPixel(src->format); + + u32 strideInBytes = src->fb_stride * bytesPerPixel; // Same for both src and dest + + u32 srcColorStart = src->fb_address; + u32 srcFirstLineEnd = src->fb_address + strideInBytes; + u32 srcColorEnd = strideInBytes * src->height; + + u32 dstColorStart = dst->fb_address; + u32 dstFirstLineEnd = dst->fb_address + strideInBytes; + u32 dstColorEnd = strideInBytes * dst->height; + + // Initially we'll only allow pure horizontal and vertical overlap, + // to reduce the risk for false positives. We can allow diagonal overlap too if needed + // in the future. + + // Check for potential vertical overlap, like in Juiced 2. + int xOffset = 0; + int yOffset = 0; + + // TODO: Get rid of the compatibility flag check. + if ((dstColorStart - srcColorStart) % strideInBytes == 0 + && PSP_CoreParameter().compat.flags().AllowLargeFBTextureOffsets) { + // Buffers are aligned. + yOffset = ((int)dstColorStart - (int)srcColorStart) / strideInBytes; + if (yOffset <= -(int)src->height) { + // Not overlapping + continue; + } else if (yOffset >= dst->height) { + // Not overlapping + continue; + } + } else { + // Buffers not stride-aligned - ignoring for now. + continue; + } + gpuStats.numColorCopies++; + sources.push_back(CopySource{ src, RASTER_COLOR, xOffset, yOffset }); + } + } + + std::sort(sources.begin(), sources.end()); + + draw_->InvalidateCachedState(); + + for (const CopySource &source : sources) { + VirtualFramebuffer *src = source.vfb; + + // Copy a rectangle from the original to the new buffer. + // Yes, we mean to look at src->width/height for the dest rectangle. + int srcWidth = src->width * src->renderScaleFactor; + int srcHeight = src->height * src->renderScaleFactor; + int dstWidth = src->width * dst->renderScaleFactor; + int dstHeight = src->height * dst->renderScaleFactor; + + int dstX1 = -source.xOffset * dst->renderScaleFactor; + int dstY1 = -source.yOffset * dst->renderScaleFactor; + int dstX2 = dstX1 + dstWidth; + int dstY2 = dstY1 + dstHeight; + + BlitUsingRaster(src->fbo, 0.0f, 0.0f, srcWidth, srcHeight, + dst->fbo, dstX1, dstY1, dstX2, dstY2, false, DRAW2D_COPY_COLOR, "copy_color"); + } +} + + void FramebufferManagerCommon::DestroyFramebuf(VirtualFramebuffer *v) { // Notify the texture cache of both the color and depth buffers. textureCache_->NotifyFramebuffer(v, NOTIFY_FB_DESTROYED); @@ -765,7 +842,7 @@ void FramebufferManagerCommon::NotifyVideoUpload(u32 addr, int size, int width, if (vfb->fb_stride < width) { DEBUG_LOG(ME, "Changing stride for %08x from %d to %d", addr, vfb->fb_stride, width); - const int bpp = fmt == GE_FORMAT_8888 ? 4 : 2; + const int bpp = BufferFormatBytesPerPixel(fmt); ResizeFramebufFBO(vfb, width, size / (bpp * width)); // Resizing may change the viewport/etc. gstate_c.Dirty(DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_CULLRANGE); @@ -1076,7 +1153,7 @@ void FramebufferManagerCommon::CopyDisplayToOutput(bool reallyDirty) { const u32 v_addr = v->fb_address & 0x3FFFFFFF; const u32 v_size = ColorBufferByteSize(v); if (addr >= v_addr && addr < v_addr + v_size) { - const u32 dstBpp = v->format == GE_FORMAT_8888 ? 4 : 2; + const u32 dstBpp = BufferFormatBytesPerPixel(v->format); const u32 v_offsetX = ((addr - v_addr) / dstBpp) % v->fb_stride; const u32 v_offsetY = ((addr - v_addr) / dstBpp) / v->fb_stride; // We have enough space there for the display, right? @@ -1358,7 +1435,7 @@ bool FramebufferManagerCommon::NotifyFramebufferCopy(u32 src, u32 dst, int size, // We only remove the kernel and uncached bits when comparing. const u32 vfb_address = vfb->fb_address & 0x3FFFFFFF; const u32 vfb_size = ColorBufferByteSize(vfb); - const u32 vfb_bpp = vfb->format == GE_FORMAT_8888 ? 4 : 2; + const u32 vfb_bpp = BufferFormatBytesPerPixel(vfb->format); const u32 vfb_byteStride = vfb->fb_stride * vfb_bpp; const int vfb_byteWidth = vfb->width * vfb_bpp; @@ -1468,7 +1545,7 @@ void FramebufferManagerCommon::FindTransferFramebuffers(VirtualFramebuffer *&dst VirtualFramebuffer *vfb = vfbs_[i]; const u32 vfb_address = vfb->fb_address & 0x3FFFFFFF; const u32 vfb_size = ColorBufferByteSize(vfb); - const u32 vfb_bpp = vfb->format == GE_FORMAT_8888 ? 4 : 2; + const u32 vfb_bpp = BufferFormatBytesPerPixel(vfb->format); const u32 vfb_byteStride = vfb->fb_stride * vfb_bpp; const u32 vfb_byteWidth = vfb->width * vfb_bpp; @@ -1680,7 +1757,7 @@ void FramebufferManagerCommon::ApplyClearToMemory(int x1, int y1, int x2, int y2 } u8 *addr = Memory::GetPointerWriteUnchecked(gstate.getFrameBufAddress()); - const int bpp = gstate_c.framebufFormat == GE_FORMAT_8888 ? 4 : 2; + const int bpp = BufferFormatBytesPerPixel(gstate_c.framebufFormat); u32 clearBits = clearColor; if (bpp == 2) { @@ -1813,7 +1890,7 @@ bool FramebufferManagerCommon::NotifyBlockTransferBefore(u32 dstBasePtr, int dst dstBasePtr, dstX, dstY, dstStride); FlushBeforeCopy(); if (g_Config.bBlockTransferGPU && !srcBuffer->memoryUpdated) { - const int srcBpp = srcBuffer->format == GE_FORMAT_8888 ? 4 : 2; + const int srcBpp = BufferFormatBytesPerPixel(srcBuffer->format); const float srcXFactor = (float)bpp / srcBpp; const bool tooTall = srcY + srcHeight > srcBuffer->bufferHeight; if (srcHeight <= 0 || (tooTall && srcY != 0)) { @@ -1864,7 +1941,7 @@ void FramebufferManagerCommon::NotifyBlockTransferAfter(u32 dstBasePtr, int dstS WARN_LOG_ONCE(btu, G3D, "Block transfer upload %08x -> %08x", srcBasePtr, dstBasePtr); FlushBeforeCopy(); const u8 *srcBase = Memory::GetPointerUnchecked(srcBasePtr) + (srcX + srcY * srcStride) * bpp; - int dstBpp = dstBuffer->format == GE_FORMAT_8888 ? 4 : 2; + int dstBpp = BufferFormatBytesPerPixel(dstBuffer->format); float dstXFactor = (float)bpp / dstBpp; if (dstWidth > dstBuffer->width || dstHeight > dstBuffer->height) { // The buffer isn't big enough, and we have a clear hint of size. Resize. @@ -2264,7 +2341,7 @@ void FramebufferManagerCommon::FlushBeforeCopy() { void FramebufferManagerCommon::DownloadFramebufferForClut(u32 fb_address, u32 loadBytes) { VirtualFramebuffer *vfb = GetVFBAt(fb_address); if (vfb && vfb->fb_stride != 0) { - const u32 bpp = vfb->drawnFormat == GE_FORMAT_8888 ? 4 : 2; + const u32 bpp = BufferFormatBytesPerPixel(vfb->drawnFormat); int x = 0; int y = 0; int pixels = loadBytes / bpp; @@ -2463,7 +2540,7 @@ void FramebufferManagerCommon::BlitFramebuffer(VirtualFramebuffer *dst, int dstX float srcXFactor = src->renderScaleFactor; float srcYFactor = src->renderScaleFactor; - const int srcBpp = src->format == GE_FORMAT_8888 ? 4 : 2; + const int srcBpp = BufferFormatBytesPerPixel(src->format); if (srcBpp != bpp && bpp != 0) { // If we do this, we're kinda in nonsense territory since the actual formats won't match (unless intentionally blitting black or white). srcXFactor = (srcXFactor * bpp) / srcBpp; @@ -2475,7 +2552,7 @@ void FramebufferManagerCommon::BlitFramebuffer(VirtualFramebuffer *dst, int dstX float dstXFactor = dst->renderScaleFactor; float dstYFactor = dst->renderScaleFactor; - const int dstBpp = dst->format == GE_FORMAT_8888 ? 4 : 2; + const int dstBpp = BufferFormatBytesPerPixel(dst->format); if (dstBpp != bpp && bpp != 0) { // If we do this, we're kinda in nonsense territory since the actual formats won't match (unless intentionally blitting black or white). dstXFactor = (dstXFactor * bpp) / dstBpp; @@ -2525,6 +2602,7 @@ void FramebufferManagerCommon::BlitFramebuffer(VirtualFramebuffer *dst, int dstX gstate_c.Dirty(DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_BLEND_STATE | DIRTY_RASTER_STATE); } +// The input is raw pixel coordinates, scale not taken into account. void FramebufferManagerCommon::BlitUsingRaster( Draw::Framebuffer *src, float srcX1, float srcY1, float srcX2, float srcY2, Draw::Framebuffer *dest, float destX1, float destY1, float destX2, float destY2, diff --git a/GPU/Common/FramebufferManagerCommon.h b/GPU/Common/FramebufferManagerCommon.h index f63b319c36..891892041f 100644 --- a/GPU/Common/FramebufferManagerCommon.h +++ b/GPU/Common/FramebufferManagerCommon.h @@ -379,6 +379,7 @@ protected: void Ensure2DResources(); Draw::Pipeline *Create2DPipeline(RasterChannel (*generate)(ShaderWriter &)); + void CopyToColorFromOverlappingFramebuffers(VirtualFramebuffer *dest); void CopyToDepthFromOverlappingFramebuffers(VirtualFramebuffer *dest); bool UpdateSize(); diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index de6c840722..7cd7c21aba 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -807,7 +807,7 @@ void TextureCacheCommon::NotifyFramebuffer(VirtualFramebuffer *framebuffer, Fram const u32 z_addr = framebuffer->z_address & ~mirrorMask; // Probably unnecessary. - const u32 fb_bpp = framebuffer->format == GE_FORMAT_8888 ? 4 : 2; + const u32 fb_bpp = BufferFormatBytesPerPixel(framebuffer->format); const u32 z_bpp = 2; // No other format exists. const u32 fb_stride = framebuffer->fb_stride; const u32 z_stride = framebuffer->z_stride; @@ -1151,7 +1151,7 @@ void TextureCacheCommon::LoadClut(u32 clutAddr, u32 loadBytes) { const std::vector &framebuffers = framebufferManager_->Framebuffers(); for (VirtualFramebuffer *framebuffer : framebuffers) { const u32 fb_address = framebuffer->fb_address & 0x3FFFFFFF; - const u32 bpp = framebuffer->drawnFormat == GE_FORMAT_8888 ? 4 : 2; + const u32 bpp = BufferFormatBytesPerPixel(framebuffer->drawnFormat); u32 offset = clutFramebufAddr - fb_address; // Is this inside the framebuffer at all? diff --git a/GPU/GPU.h b/GPU/GPU.h index 18af975ae8..0d7fd03430 100644 --- a/GPU/GPU.h +++ b/GPU/GPU.h @@ -84,6 +84,8 @@ struct GPUStatistics { numUploads = 0; numClears = 0; numDepthCopies = 0; + numReinterpretCopies = 0; + numColorCopies = 0; msProcessingDisplayLists = 0; vertexGPUCycles = 0; otherGPUCycles = 0; @@ -110,6 +112,8 @@ struct GPUStatistics { int numUploads; int numClears; int numDepthCopies; + int numReinterpretCopies; + int numColorCopies; double msProcessingDisplayLists; int vertexGPUCycles; int otherGPUCycles; diff --git a/GPU/GPUCommon.cpp b/GPU/GPUCommon.cpp index 7db2fd4b42..e95c34c587 100644 --- a/GPU/GPUCommon.cpp +++ b/GPU/GPUCommon.cpp @@ -3062,7 +3062,8 @@ size_t GPUCommon::FormatGPUStatsCommon(char *buffer, size_t size) { "Vertices: %d cached: %d uncached: %d\n" "FBOs active: %d (evaluations: %d)\n" "Textures: %d, dec: %d, invalidated: %d, hashed: %d kB\n" - "Readbacks: %d, uploads: %d, depth copies: %d\n" + "Readbacks: %d, uploads: %d\n" + "Copies: depth %d, color %d, reinterpret: %d\n" "GPU cycles executed: %d (%f per vertex)\n", gpuStats.msProcessingDisplayLists * 1000.0f, gpuStats.numDrawCalls, @@ -3083,6 +3084,8 @@ size_t GPUCommon::FormatGPUStatsCommon(char *buffer, size_t size) { gpuStats.numReadbacks, gpuStats.numUploads, gpuStats.numDepthCopies, + gpuStats.numColorCopies, + gpuStats.numReinterpretCopies, gpuStats.vertexGPUCycles + gpuStats.otherGPUCycles, vertexAverageCycles ); diff --git a/GPU/ge_constants.h b/GPU/ge_constants.h index 78363c3879..8cd455ba79 100644 --- a/GPU/ge_constants.h +++ b/GPU/ge_constants.h @@ -435,6 +435,11 @@ inline bool IsBufferFormat16Bit(GEBufferFormat bfmt) { inline bool IsTextureFormat16Bit(GETextureFormat tfmt) { return (int)tfmt < 3; } + +inline int BufferFormatBytesPerPixel(GEBufferFormat format) { + return format == GE_FORMAT_8888 ? 4 : 2; // applies to depth as well. +} + inline bool TextureFormatMatchesBufferFormat(GETextureFormat fmt, GEBufferFormat bfmt) { // First four matches perfectly. if ((int)fmt < 4) { From 86e754fb4a24af548a72a7a28ec708821b798d98 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Mon, 22 Aug 2022 21:29:49 -0700 Subject: [PATCH 72/85] D3D11: Correct viewport offset sign handling. --- GPU/D3D11/DrawEngineD3D11.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GPU/D3D11/DrawEngineD3D11.cpp b/GPU/D3D11/DrawEngineD3D11.cpp index eea3004b30..1822fc5256 100644 --- a/GPU/D3D11/DrawEngineD3D11.cpp +++ b/GPU/D3D11/DrawEngineD3D11.cpp @@ -623,7 +623,7 @@ rotateVBO: int maxIndex = indexGen.MaxIndex(); SoftwareTransform swTransform(params); - const Lin::Vec3 trans(gstate_c.vpXOffset, gstate_c.vpYOffset, gstate_c.vpZOffset * 0.5f + 0.5f); + const Lin::Vec3 trans(gstate_c.vpXOffset, -gstate_c.vpYOffset, gstate_c.vpZOffset * 0.5f + 0.5f); const Lin::Vec3 scale(gstate_c.vpWidthScale, -gstate_c.vpHeightScale, gstate_c.vpDepthScale * 0.5f); swTransform.SetProjMatrix(gstate.projMatrix, gstate_c.vpWidth < 0, gstate_c.vpHeight < 0, trans, scale); From d1c75209320200ff59f7b198ab8e7a7c5fa36051 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Mon, 22 Aug 2022 21:30:10 -0700 Subject: [PATCH 73/85] D3D9: Correct viewport offset sign. --- GPU/Directx9/DrawEngineDX9.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/GPU/Directx9/DrawEngineDX9.cpp b/GPU/Directx9/DrawEngineDX9.cpp index 130ee36b8f..1ab4da1a63 100644 --- a/GPU/Directx9/DrawEngineDX9.cpp +++ b/GPU/Directx9/DrawEngineDX9.cpp @@ -589,12 +589,10 @@ rotateVBO: SoftwareTransform swTransform(params); // Half pixel offset hack. - float xScale = gstate_c.vpWidth < 0 ? -1.0f : 1.0f; float xOffset = -1.0f / gstate_c.curRTRenderWidth; - float yScale = gstate_c.vpHeight > 0 ? -1.0f : 1.0f; float yOffset = 1.0f / gstate_c.curRTRenderHeight; - const Lin::Vec3 trans(gstate_c.vpXOffset * xScale + xOffset, gstate_c.vpYOffset * yScale + yOffset, gstate_c.vpZOffset * 0.5f + 0.5f); + const Lin::Vec3 trans(gstate_c.vpXOffset + xOffset, -gstate_c.vpYOffset + yOffset, gstate_c.vpZOffset * 0.5f + 0.5f); const Lin::Vec3 scale(gstate_c.vpWidthScale, gstate_c.vpHeightScale, gstate_c.vpDepthScale * 0.5f); swTransform.SetProjMatrix(gstate.projMatrix, gstate_c.vpWidth < 0, gstate_c.vpHeight > 0, trans, scale); From a0722af10769a19421b6ce8492c49e7254001e82 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Mon, 22 Aug 2022 21:22:00 +0200 Subject: [PATCH 74/85] Rename fmt->fb_format --- GPU/Common/FramebufferManagerCommon.cpp | 14 +++++++------- GPU/Common/FramebufferManagerCommon.h | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/GPU/Common/FramebufferManagerCommon.cpp b/GPU/Common/FramebufferManagerCommon.cpp index 6cf098cbed..f8eb24d8c6 100644 --- a/GPU/Common/FramebufferManagerCommon.cpp +++ b/GPU/Common/FramebufferManagerCommon.cpp @@ -220,7 +220,7 @@ void GetFramebufferHeuristicInputs(FramebufferHeuristicParams *params, const GPU params->z_stride = 0; } - params->fmt = gstate_c.framebufFormat; + params->fb_format = gstate_c.framebufFormat; params->isClearingDepth = gstate.isModeClear() && gstate.isClearModeDepthMask(); // Technically, it may write depth later, but we're trying to detect it only when it's really true. @@ -269,7 +269,7 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame // As there are no clear "framebuffer width" and "framebuffer height" registers, // we need to infer the size of the current framebuffer somehow. int drawing_width, drawing_height; - EstimateDrawingSize(params.fb_address, params.fmt, params.viewportWidth, params.viewportHeight, params.regionWidth, params.regionHeight, params.scissorWidth, params.scissorHeight, std::max(params.fb_stride, (u16)4), drawing_width, drawing_height); + EstimateDrawingSize(params.fb_address, params.fb_format, params.viewportWidth, params.viewportHeight, params.regionWidth, params.regionHeight, params.scissorWidth, params.scissorHeight, std::max(params.fb_stride, (u16)4), drawing_width, drawing_height); gstate_c.SetCurRTOffset(0, 0); bool vfbFormatChanged = false; @@ -294,8 +294,8 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame vfb->fb_stride = params.fb_stride; vfbFormatChanged = true; } - if (vfb->format != params.fmt) { - vfb->format = params.fmt; + if (vfb->format != params.fb_format) { + vfb->format = params.fb_format; vfbFormatChanged = true; } @@ -316,7 +316,7 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame vfb->height = drawing_height; } break; - } else if (v->fb_stride == params.fb_stride && v->format == params.fmt) { + } else if (v->fb_stride == params.fb_stride && v->format == params.fb_format) { u32 v_fb_first_line_end_ptr = v->fb_address + v->fb_stride * bpp; u32 v_fb_end_ptr = v->fb_address + v->fb_stride * v->height * bpp; @@ -389,8 +389,8 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame vfb->newWidth = drawing_width; vfb->newHeight = drawing_height; vfb->lastFrameNewSize = gpuStats.numFlips; - vfb->format = params.fmt; - vfb->drawnFormat = params.fmt; + vfb->format = params.fb_format; + vfb->drawnFormat = params.fb_format; vfb->usageFlags = FB_USAGE_RENDER_COLOR; u32 byteSize = ColorBufferByteSize(vfb); diff --git a/GPU/Common/FramebufferManagerCommon.h b/GPU/Common/FramebufferManagerCommon.h index 891892041f..0e97df47b7 100644 --- a/GPU/Common/FramebufferManagerCommon.h +++ b/GPU/Common/FramebufferManagerCommon.h @@ -153,7 +153,7 @@ struct FramebufferHeuristicParams { u32 z_address; u16 fb_stride; u16 z_stride; - GEBufferFormat fmt; + GEBufferFormat fb_format; bool isClearingDepth; bool isWritingDepth; bool isDrawing; From 5415da10bfb0c335f125922e16980c095b48348f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Mon, 22 Aug 2022 21:28:43 +0200 Subject: [PATCH 75/85] Rename VirtualFramebuffer->format to fb_format to line up with fb_address and fb_stride (fundamental parameters) --- GPU/Common/FramebufferManagerCommon.cpp | 98 ++++++++++++------------- GPU/Common/FramebufferManagerCommon.h | 14 ++-- GPU/Common/ReinterpretFramebuffer.cpp | 2 +- GPU/Common/StencilCommon.cpp | 8 +- GPU/Common/TextureCacheCommon.cpp | 12 +-- GPU/Directx9/FramebufferManagerDX9.cpp | 4 +- 6 files changed, 69 insertions(+), 69 deletions(-) diff --git a/GPU/Common/FramebufferManagerCommon.cpp b/GPU/Common/FramebufferManagerCommon.cpp index f8eb24d8c6..4e7e9a07ee 100644 --- a/GPU/Common/FramebufferManagerCommon.cpp +++ b/GPU/Common/FramebufferManagerCommon.cpp @@ -124,7 +124,7 @@ VirtualFramebuffer *FramebufferManagerCommon::GetVFBAt(u32 addr) const { } u32 FramebufferManagerCommon::ColorBufferByteSize(const VirtualFramebuffer *vfb) const { - return vfb->fb_stride * vfb->height * (vfb->format == GE_FORMAT_8888 ? 4 : 2); + return vfb->fb_stride * vfb->height * (vfb->fb_format == GE_FORMAT_8888 ? 4 : 2); } bool FramebufferManagerCommon::ShouldDownloadFramebuffer(const VirtualFramebuffer *vfb) const { @@ -285,7 +285,7 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame for (size_t i = 0; i < vfbs_.size(); ++i) { VirtualFramebuffer *v = vfbs_[i]; - const u32 bpp = BufferFormatBytesPerPixel(v->format); + const u32 bpp = BufferFormatBytesPerPixel(v->fb_format); if (params.fb_address == v->fb_address) { vfb = v; @@ -294,8 +294,8 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame vfb->fb_stride = params.fb_stride; vfbFormatChanged = true; } - if (vfb->format != params.fb_format) { - vfb->format = params.fb_format; + if (vfb->fb_format != params.fb_format) { + vfb->fb_format = params.fb_format; vfbFormatChanged = true; } @@ -316,7 +316,7 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame vfb->height = drawing_height; } break; - } else if (v->fb_stride == params.fb_stride && v->format == params.fb_format) { + } else if (v->fb_stride == params.fb_stride && v->fb_format == params.fb_format) { u32 v_fb_first_line_end_ptr = v->fb_address + v->fb_stride * bpp; u32 v_fb_end_ptr = v->fb_address + v->fb_stride * v->height * bpp; @@ -389,7 +389,7 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame vfb->newWidth = drawing_width; vfb->newHeight = drawing_height; vfb->lastFrameNewSize = gpuStats.numFlips; - vfb->format = params.fb_format; + vfb->fb_format = params.fb_format; vfb->drawnFormat = params.fb_format; vfb->usageFlags = FB_USAGE_RENDER_COLOR; @@ -408,7 +408,7 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame CopyToColorFromOverlappingFramebuffers(vfb); SetColorUpdated(vfb, skipDrawReason); - INFO_LOG(FRAMEBUF, "Creating FBO for %08x (z: %08x) : %d x %d x %s", vfb->fb_address, vfb->z_address, vfb->width, vfb->height, GeBufferFormatToString(vfb->format)); + INFO_LOG(FRAMEBUF, "Creating FBO for %08x (z: %08x) : %d x %d x %s", vfb->fb_address, vfb->z_address, vfb->width, vfb->height, GeBufferFormatToString(vfb->fb_format)); vfb->last_frame_render = gpuStats.numFlips; frameLastFramebufUsed_ = gpuStats.numFlips; @@ -452,7 +452,7 @@ VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(const Frame // We already have it! } else if (vfb != currentRenderVfb_) { // Use it as a render target. - DEBUG_LOG(FRAMEBUF, "Switching render target to FBO for %08x: %d x %d x %d ", vfb->fb_address, vfb->width, vfb->height, vfb->format); + DEBUG_LOG(FRAMEBUF, "Switching render target to FBO for %08x: %d x %d x %d ", vfb->fb_address, vfb->width, vfb->height, vfb->fb_format); vfb->usageFlags |= FB_USAGE_RENDER_COLOR; vfb->last_frame_render = gpuStats.numFlips; frameLastFramebufUsed_ = gpuStats.numFlips; @@ -525,7 +525,7 @@ void FramebufferManagerCommon::CopyToDepthFromOverlappingFramebuffers(VirtualFra if (src == dest) continue; - if (src->fb_address == dest->z_address && src->fb_stride == dest->z_stride && src->format == GE_FORMAT_565) { + if (src->fb_address == dest->z_address && src->fb_stride == dest->z_stride && src->fb_format == GE_FORMAT_565) { if (src->colorBindSeq > dest->depthBindSeq) { // Source has newer data than the current buffer, use it. sources.push_back(CopySource{ src, RASTER_COLOR, 0, 0 }); @@ -557,7 +557,7 @@ void FramebufferManagerCommon::CopyToDepthFromOverlappingFramebuffers(VirtualFra } else if (source.channel == RASTER_COLOR && draw_->GetDeviceCaps().fragmentShaderDepthWriteSupported) { VirtualFramebuffer *src = source.vfb; if (src->drawnFormat != GE_FORMAT_565) { - WARN_LOG_ONCE(not565, G3D, "Drawn format of buffer at %08x not 565 as expected", src->fb_address); + WARN_LOG_ONCE(not565, G3D, "Drawn fb_format of buffer at %08x not 565 as expected", src->fb_address); } // Really hate to do this, but tracking the depth swizzle state across multiple @@ -591,11 +591,11 @@ void FramebufferManagerCommon::CopyToColorFromOverlappingFramebuffers(VirtualFra if (src->fb_address == dst->fb_address && src->fb_stride == dst->fb_stride) { // Another render target at the exact same location but gotta be a different format, otherwise // it would be the same. - _dbg_assert_(src->format != dst->format); + _dbg_assert_(src->fb_format != dst->fb_format); WARN_LOG_ONCE(reint, G3D, "Reinterpret detected at %08x", src->fb_address); // This is where we'll do reinterprets in the future. - } else if (src->fb_stride == dst->fb_stride && src->format == dst->format) { - u32 bytesPerPixel = BufferFormatBytesPerPixel(src->format); + } else if (src->fb_stride == dst->fb_stride && src->fb_format == dst->fb_format) { + u32 bytesPerPixel = BufferFormatBytesPerPixel(src->fb_format); u32 strideInBytes = src->fb_stride * bytesPerPixel; // Same for both src and dest @@ -760,8 +760,8 @@ void FramebufferManagerCommon::NotifyRenderFramebufferCreated(VirtualFramebuffer void FramebufferManagerCommon::NotifyRenderFramebufferUpdated(VirtualFramebuffer *vfb, bool vfbFormatChanged) { if (vfbFormatChanged) { textureCache_->NotifyFramebuffer(vfb, NOTIFY_FB_UPDATED); - if (vfb->drawnFormat != vfb->format) { - ReinterpretFramebuffer(vfb, vfb->drawnFormat, vfb->format); + if (vfb->drawnFormat != vfb->fb_format) { + ReinterpretFramebuffer(vfb, vfb->drawnFormat, vfb->fb_format); } } @@ -785,8 +785,8 @@ void FramebufferManagerCommon::NotifyRenderFramebufferSwitched(VirtualFramebuffe textureCache_->ForgetLastTexture(); shaderManager_->DirtyLastShader(); - if (vfb->drawnFormat != vfb->format) { - ReinterpretFramebuffer(vfb, vfb->drawnFormat, vfb->format); + if (vfb->drawnFormat != vfb->fb_format) { + ReinterpretFramebuffer(vfb, vfb->drawnFormat, vfb->fb_format); } if (useBufferedRendering_) { @@ -831,9 +831,9 @@ void FramebufferManagerCommon::NotifyVideoUpload(u32 addr, int size, int width, // TODO: Could possibly be an offset... VirtualFramebuffer *vfb = GetVFBAt(addr); if (vfb) { - if (vfb->format != fmt || vfb->drawnFormat != fmt) { - DEBUG_LOG(ME, "Changing format for %08x from %d to %d", addr, vfb->drawnFormat, fmt); - vfb->format = fmt; + if (vfb->fb_format != fmt || vfb->drawnFormat != fmt) { + DEBUG_LOG(ME, "Changing fb_format for %08x from %d to %d", addr, vfb->drawnFormat, fmt); + vfb->fb_format = fmt; vfb->drawnFormat = fmt; // Let's count this as a "render". This will also force us to use the correct format. @@ -870,7 +870,7 @@ void FramebufferManagerCommon::UpdateFromMemory(u32 addr, int size, bool safe) { FlushBeforeCopy(); if (useBufferedRendering_ && vfb->fbo) { - GEBufferFormat fmt = vfb->format; + GEBufferFormat fmt = vfb->fb_format; if (vfb->last_frame_render + 1 < gpuStats.numFlips && isDisplayBuf) { // If we're not rendering to it, format may be wrong. Use displayFormat_ instead. fmt = displayFormat_; @@ -878,7 +878,7 @@ void FramebufferManagerCommon::UpdateFromMemory(u32 addr, int size, bool safe) { DrawPixels(vfb, 0, 0, Memory::GetPointer(addr), fmt, vfb->fb_stride, vfb->width, vfb->height); SetColorUpdated(vfb, gstate_c.skipDrawReason); } else { - INFO_LOG(FRAMEBUF, "Invalidating FBO for %08x (%i x %i x %i)", vfb->fb_address, vfb->width, vfb->height, vfb->format); + INFO_LOG(FRAMEBUF, "Invalidating FBO for %08x (%i x %i x %i)", vfb->fb_address, vfb->width, vfb->height, vfb->fb_format); DestroyFramebuf(vfb); vfbs_.erase(vfbs_.begin() + i--); } @@ -1153,7 +1153,7 @@ void FramebufferManagerCommon::CopyDisplayToOutput(bool reallyDirty) { const u32 v_addr = v->fb_address & 0x3FFFFFFF; const u32 v_size = ColorBufferByteSize(v); if (addr >= v_addr && addr < v_addr + v_size) { - const u32 dstBpp = BufferFormatBytesPerPixel(v->format); + const u32 dstBpp = BufferFormatBytesPerPixel(v->fb_format); const u32 v_offsetX = ((addr - v_addr) / dstBpp) % v->fb_stride; const u32 v_offsetY = ((addr - v_addr) / dstBpp) / v->fb_stride; // We have enough space there for the display, right? @@ -1176,10 +1176,10 @@ void FramebufferManagerCommon::CopyDisplayToOutput(bool reallyDirty) { } } - if (vfb && vfb->format != displayFormat_) { + if (vfb && vfb->fb_format != displayFormat_) { if (vfb->last_frame_render + FBO_OLD_AGE < gpuStats.numFlips) { // The game probably switched formats on us. - vfb->format = displayFormat_; + vfb->fb_format = displayFormat_; } else { vfb = 0; } @@ -1279,7 +1279,7 @@ void FramebufferManagerCommon::DecimateFBOs() { if (vfb != displayFramebuf_ && vfb != prevDisplayFramebuf_ && vfb != prevPrevDisplayFramebuf_) { if (age > FBO_OLD_AGE) { - INFO_LOG(FRAMEBUF, "Decimating FBO for %08x (%i x %i x %i), age %i", vfb->fb_address, vfb->width, vfb->height, vfb->format, age); + INFO_LOG(FRAMEBUF, "Decimating FBO for %08x (%i x %i x %i), age %i", vfb->fb_address, vfb->width, vfb->height, vfb->fb_format, age); DestroyFramebuf(vfb); vfbs_.erase(vfbs_.begin() + i--); } @@ -1301,7 +1301,7 @@ void FramebufferManagerCommon::DecimateFBOs() { VirtualFramebuffer *vfb = bvfbs_[i]; int age = frameLastFramebufUsed_ - vfb->last_frame_render; if (age > FBO_OLD_AGE) { - INFO_LOG(FRAMEBUF, "Decimating FBO for %08x (%i x %i x %i), age %i", vfb->fb_address, vfb->width, vfb->height, vfb->format, age); + INFO_LOG(FRAMEBUF, "Decimating FBO for %08x (%i x %i x %i), age %i", vfb->fb_address, vfb->width, vfb->height, vfb->fb_format, age); DestroyFramebuf(vfb); bvfbs_.erase(bvfbs_.begin() + i--); } @@ -1377,7 +1377,7 @@ void FramebufferManagerCommon::ResizeFramebufFBO(VirtualFramebuffer *vfb, int w, shaderManager_->DirtyLastShader(); char tag[128]; - size_t len = snprintf(tag, sizeof(tag), "FB_%08x_%08x_%dx%d_%s", vfb->fb_address, vfb->z_address, w, h, GeBufferFormatToString(vfb->format)); + size_t len = snprintf(tag, sizeof(tag), "FB_%08x_%08x_%dx%d_%s", vfb->fb_address, vfb->z_address, w, h, GeBufferFormatToString(vfb->fb_format)); vfb->fbo = draw_->CreateFramebuffer({ vfb->renderWidth, vfb->renderHeight, 1, 1, true, tag }); if (Memory::IsVRAMAddress(vfb->fb_address) && vfb->fb_stride != 0) { NotifyMemInfo(MemBlockFlags::ALLOC, vfb->fb_address, ColorBufferByteSize(vfb), tag, len); @@ -1388,7 +1388,7 @@ void FramebufferManagerCommon::ResizeFramebufFBO(VirtualFramebuffer *vfb, int w, NotifyMemInfo(MemBlockFlags::ALLOC, vfb->z_address, vfb->fb_stride * vfb->height * sizeof(uint16_t), buf, len); } if (old.fbo) { - INFO_LOG(FRAMEBUF, "Resizing FBO for %08x : %dx%dx%s", vfb->fb_address, w, h, GeBufferFormatToString(vfb->format)); + INFO_LOG(FRAMEBUF, "Resizing FBO for %08x : %dx%dx%s", vfb->fb_address, w, h, GeBufferFormatToString(vfb->fb_format)); if (vfb->fbo) { draw_->BindFramebufferAsRenderTarget(vfb->fbo, { Draw::RPAction::CLEAR, Draw::RPAction::CLEAR, Draw::RPAction::CLEAR }, "ResizeFramebufFBO"); if (!skipCopy) { @@ -1435,7 +1435,7 @@ bool FramebufferManagerCommon::NotifyFramebufferCopy(u32 src, u32 dst, int size, // We only remove the kernel and uncached bits when comparing. const u32 vfb_address = vfb->fb_address & 0x3FFFFFFF; const u32 vfb_size = ColorBufferByteSize(vfb); - const u32 vfb_bpp = BufferFormatBytesPerPixel(vfb->format); + const u32 vfb_bpp = BufferFormatBytesPerPixel(vfb->fb_format); const u32 vfb_byteStride = vfb->fb_stride * vfb_bpp; const int vfb_byteWidth = vfb->width * vfb_bpp; @@ -1483,7 +1483,7 @@ bool FramebufferManagerCommon::NotifyFramebufferCopy(u32 src, u32 dst, int size, // Note - if we're here, we're in a memcpy, not a block transfer. Not allowing IntraVRAMBlockTransferAllowCreateFB. // Technically, that makes BlockTransferAllowCreateFB a bit of a misnomer. if (PSP_CoreParameter().compat.flags().BlockTransferAllowCreateFB) { - dstBuffer = CreateRAMFramebuffer(dst, srcBuffer->width, srcBuffer->height, srcBuffer->fb_stride, srcBuffer->format); + dstBuffer = CreateRAMFramebuffer(dst, srcBuffer->width, srcBuffer->height, srcBuffer->fb_stride, srcBuffer->fb_format); dstY = 0; } } @@ -1509,7 +1509,7 @@ bool FramebufferManagerCommon::NotifyFramebufferCopy(u32 src, u32 dst, int size, WARN_LOG_ONCE(btucpy, G3D, "Memcpy fbo upload %08x -> %08x (size: %x)", src, dst, size); FlushBeforeCopy(); const u8 *srcBase = Memory::GetPointerUnchecked(src); - DrawPixels(dstBuffer, 0, dstY, srcBase, dstBuffer->format, dstBuffer->fb_stride, dstBuffer->width, dstH); + DrawPixels(dstBuffer, 0, dstY, srcBase, dstBuffer->fb_format, dstBuffer->fb_stride, dstBuffer->width, dstH); SetColorUpdated(dstBuffer, skipDrawReason); RebindFramebuffer("RebindFramebuffer - Memcpy fbo upload"); // This is a memcpy, let's still copy just in case. @@ -1545,7 +1545,7 @@ void FramebufferManagerCommon::FindTransferFramebuffers(VirtualFramebuffer *&dst VirtualFramebuffer *vfb = vfbs_[i]; const u32 vfb_address = vfb->fb_address & 0x3FFFFFFF; const u32 vfb_size = ColorBufferByteSize(vfb); - const u32 vfb_bpp = BufferFormatBytesPerPixel(vfb->format); + const u32 vfb_bpp = BufferFormatBytesPerPixel(vfb->fb_format); const u32 vfb_byteStride = vfb->fb_stride * vfb_bpp; const u32 vfb_byteWidth = vfb->width * vfb_bpp; @@ -1620,10 +1620,10 @@ void FramebufferManagerCommon::FindTransferFramebuffers(VirtualFramebuffer *&dst if (bpp == 4) { // Only one possibility unless it's doing split pixel tricks (which we could detect through stride maybe). ramFormat = GE_FORMAT_8888; - } else if (srcBuffer->format != GE_FORMAT_8888) { + } else if (srcBuffer->fb_format != GE_FORMAT_8888) { // We guess that the game will interpret the data the same as it was in the source of the copy. // Seems like a likely good guess, and works in Test Drive Unlimited. - ramFormat = srcBuffer->format; + ramFormat = srcBuffer->fb_format; } else { // No info left - just fall back to something. But this is definitely split pixel tricks. ramFormat = GE_FORMAT_5551; @@ -1646,7 +1646,7 @@ void FramebufferManagerCommon::FindTransferFramebuffers(VirtualFramebuffer *&dst } VirtualFramebuffer *FramebufferManagerCommon::CreateRAMFramebuffer(uint32_t fbAddress, int width, int height, int stride, GEBufferFormat format) { - INFO_LOG(G3D, "Creating RAM framebuffer at %08x (%dx%d, stride %d, format %d)", fbAddress, width, height, stride, format); + INFO_LOG(G3D, "Creating RAM framebuffer at %08x (%dx%d, stride %d, fb_format %d)", fbAddress, width, height, stride, format); // A target for the destination is missing - so just create one! // Make sure this one would be found by the algorithm above so we wouldn't @@ -1667,7 +1667,7 @@ VirtualFramebuffer *FramebufferManagerCommon::CreateRAMFramebuffer(uint32_t fbAd vfb->renderHeight = (u16)(vfb->height * renderScaleFactor_); vfb->bufferWidth = vfb->width; vfb->bufferHeight = vfb->height; - vfb->format = format; + vfb->fb_format = format; vfb->drawnFormat = GE_FORMAT_8888; vfb->usageFlags = FB_USAGE_RENDER_COLOR; SetColorUpdated(vfb, 0); @@ -1693,7 +1693,7 @@ VirtualFramebuffer *FramebufferManagerCommon::FindDownloadTempBuffer(VirtualFram // We maintain a separate vector of framebuffer objects for blitting. for (VirtualFramebuffer *v : bvfbs_) { - if (v->fb_address == vfb->fb_address && v->format == vfb->format) { + if (v->fb_address == vfb->fb_address && v->fb_format == vfb->fb_format) { if (v->bufferWidth == vfb->bufferWidth && v->bufferHeight == vfb->bufferHeight) { nvfb = v; v->fb_stride = vfb->fb_stride; @@ -1719,10 +1719,10 @@ VirtualFramebuffer *FramebufferManagerCommon::FindDownloadTempBuffer(VirtualFram nvfb->renderScaleFactor = 1; // For readbacks we resize to the original size, of course. nvfb->bufferWidth = vfb->bufferWidth; nvfb->bufferHeight = vfb->bufferHeight; - nvfb->format = vfb->format; + nvfb->fb_format = vfb->fb_format; nvfb->drawnWidth = vfb->drawnWidth; nvfb->drawnHeight = vfb->drawnHeight; - nvfb->drawnFormat = vfb->format; + nvfb->drawnFormat = vfb->fb_format; char name[64]; snprintf(name, sizeof(name), "download_temp"); @@ -1890,7 +1890,7 @@ bool FramebufferManagerCommon::NotifyBlockTransferBefore(u32 dstBasePtr, int dst dstBasePtr, dstX, dstY, dstStride); FlushBeforeCopy(); if (g_Config.bBlockTransferGPU && !srcBuffer->memoryUpdated) { - const int srcBpp = BufferFormatBytesPerPixel(srcBuffer->format); + const int srcBpp = BufferFormatBytesPerPixel(srcBuffer->fb_format); const float srcXFactor = (float)bpp / srcBpp; const bool tooTall = srcY + srcHeight > srcBuffer->bufferHeight; if (srcHeight <= 0 || (tooTall && srcY != 0)) { @@ -1941,7 +1941,7 @@ void FramebufferManagerCommon::NotifyBlockTransferAfter(u32 dstBasePtr, int dstS WARN_LOG_ONCE(btu, G3D, "Block transfer upload %08x -> %08x", srcBasePtr, dstBasePtr); FlushBeforeCopy(); const u8 *srcBase = Memory::GetPointerUnchecked(srcBasePtr) + (srcX + srcY * srcStride) * bpp; - int dstBpp = BufferFormatBytesPerPixel(dstBuffer->format); + int dstBpp = BufferFormatBytesPerPixel(dstBuffer->fb_format); float dstXFactor = (float)bpp / dstBpp; if (dstWidth > dstBuffer->width || dstHeight > dstBuffer->height) { // The buffer isn't big enough, and we have a clear hint of size. Resize. @@ -1954,7 +1954,7 @@ void FramebufferManagerCommon::NotifyBlockTransferAfter(u32 dstBasePtr, int dstS // Resizing may change the viewport/etc. gstate_c.Dirty(DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_CULLRANGE); } - DrawPixels(dstBuffer, static_cast(dstX * dstXFactor), dstY, srcBase, dstBuffer->format, static_cast(srcStride * dstXFactor), static_cast(dstWidth * dstXFactor), dstHeight); + DrawPixels(dstBuffer, static_cast(dstX * dstXFactor), dstY, srcBase, dstBuffer->fb_format, static_cast(srcStride * dstXFactor), static_cast(dstWidth * dstXFactor), dstHeight); SetColorUpdated(dstBuffer, skipDrawReason); RebindFramebuffer("RebindFramebuffer - NotifyBlockTransferAfter"); } @@ -2000,7 +2000,7 @@ void FramebufferManagerCommon::DestroyAllFBOs() { prevPrevDisplayFramebuf_ = nullptr; for (VirtualFramebuffer *vfb : vfbs_) { - INFO_LOG(FRAMEBUF, "Destroying FBO for %08x : %i x %i x %i", vfb->fb_address, vfb->width, vfb->height, vfb->format); + INFO_LOG(FRAMEBUF, "Destroying FBO for %08x : %i x %i x %i", vfb->fb_address, vfb->width, vfb->height, vfb->fb_format); DestroyFramebuf(vfb); } vfbs_.clear(); @@ -2244,7 +2244,7 @@ void FramebufferManagerCommon::PackFramebufferSync_(VirtualFramebuffer *vfb, int const u32 fb_address = vfb->fb_address & 0x3FFFFFFF; - Draw::DataFormat destFormat = GEFormatToThin3D(vfb->format); + Draw::DataFormat destFormat = GEFormatToThin3D(vfb->fb_format); const int dstBpp = (int)DataFormatSizeInBytes(destFormat); const int dstByteOffset = (y * vfb->fb_stride + x) * dstBpp; @@ -2264,7 +2264,7 @@ void FramebufferManagerCommon::PackFramebufferSync_(VirtualFramebuffer *vfb, int if (destPtr) { draw_->CopyFramebufferToMemorySync(vfb->fbo, Draw::FB_COLOR_BIT, x, y, w, h, destFormat, destPtr, vfb->fb_stride, "PackFramebufferSync_"); char tag[128]; - size_t len = snprintf(tag, sizeof(tag), "FramebufferPack/%08x_%08x_%dx%d_%s", vfb->fb_address, vfb->z_address, w, h, GeBufferFormatToString(vfb->format)); + size_t len = snprintf(tag, sizeof(tag), "FramebufferPack/%08x_%08x_%dx%d_%s", vfb->fb_address, vfb->z_address, w, h, GeBufferFormatToString(vfb->fb_format)); NotifyMemInfo(MemBlockFlags::WRITE, fb_address + dstByteOffset, dstSize, tag, len); } else { ERROR_LOG(G3D, "PackFramebufferSync_: Tried to readback to bad address %08x (stride = %d)", fb_address + dstByteOffset, vfb->fb_stride); @@ -2395,7 +2395,7 @@ std::vector FramebufferManagerCommon::GetFramebufferList() cons FramebufferInfo info; info.fb_address = vfb->fb_address; info.z_address = vfb->z_address; - info.format = vfb->format; + info.format = vfb->fb_format; info.width = vfb->width; info.height = vfb->height; info.fbo = vfb->fbo; @@ -2540,7 +2540,7 @@ void FramebufferManagerCommon::BlitFramebuffer(VirtualFramebuffer *dst, int dstX float srcXFactor = src->renderScaleFactor; float srcYFactor = src->renderScaleFactor; - const int srcBpp = BufferFormatBytesPerPixel(src->format); + const int srcBpp = BufferFormatBytesPerPixel(src->fb_format); if (srcBpp != bpp && bpp != 0) { // If we do this, we're kinda in nonsense territory since the actual formats won't match (unless intentionally blitting black or white). srcXFactor = (srcXFactor * bpp) / srcBpp; @@ -2552,7 +2552,7 @@ void FramebufferManagerCommon::BlitFramebuffer(VirtualFramebuffer *dst, int dstX float dstXFactor = dst->renderScaleFactor; float dstYFactor = dst->renderScaleFactor; - const int dstBpp = BufferFormatBytesPerPixel(dst->format); + const int dstBpp = BufferFormatBytesPerPixel(dst->fb_format); if (dstBpp != bpp && bpp != 0) { // If we do this, we're kinda in nonsense territory since the actual formats won't match (unless intentionally blitting black or white). dstXFactor = (dstXFactor * bpp) / dstBpp; diff --git a/GPU/Common/FramebufferManagerCommon.h b/GPU/Common/FramebufferManagerCommon.h index 0e97df47b7..43bc7c293c 100644 --- a/GPU/Common/FramebufferManagerCommon.h +++ b/GPU/Common/FramebufferManagerCommon.h @@ -72,6 +72,11 @@ struct VirtualFramebuffer { u16 fb_stride; u16 z_stride; + // The original PSP format of the framebuffer. + // In reality they are all RGBA8888 for better quality but this is what the PSP thinks it is. This is necessary + // when we need to interpret the bits directly (depal or buffer aliasing). + GEBufferFormat fb_format; + // width/height: The detected size of the current framebuffer, in original PSP pixels. u16 width; u16 height; @@ -99,11 +104,6 @@ struct VirtualFramebuffer { // The scale factor at which we are rendering (to achieve higher resolution). u8 renderScaleFactor; - // The original PSP format of the framebuffer. - // In reality they are all RGBA8888 for better quality but this is what the PSP thinks it is. This is necessary - // when we need to interpret the bits directly (depal or buffer aliasing). - GEBufferFormat format; - // The configured buffer format at the time of the latest/current draw. This will change first, then // if different we'll "reinterpret" the framebuffer to match 'format' as needed. GEBufferFormat drawnFormat; @@ -341,7 +341,7 @@ public: int GetTargetBufferWidth() const { return currentRenderVfb_ ? currentRenderVfb_->bufferWidth : 480; } int GetTargetBufferHeight() const { return currentRenderVfb_ ? currentRenderVfb_->bufferHeight : 272; } int GetTargetStride() const { return currentRenderVfb_ ? currentRenderVfb_->fb_stride : 512; } - GEBufferFormat GetTargetFormat() const { return currentRenderVfb_ ? currentRenderVfb_->format : displayFormat_; } + GEBufferFormat GetTargetFormat() const { return currentRenderVfb_ ? currentRenderVfb_->fb_format : displayFormat_; } void SetColorUpdated(int skipDrawReason) { if (currentRenderVfb_) { @@ -424,7 +424,7 @@ protected: dstBuffer->dirtyAfterDisplay = true; dstBuffer->drawnWidth = dstBuffer->width; dstBuffer->drawnHeight = dstBuffer->height; - dstBuffer->drawnFormat = dstBuffer->format; + dstBuffer->drawnFormat = dstBuffer->fb_format; if ((skipDrawReason & SKIPDRAW_SKIPFRAME) == 0) dstBuffer->reallyDirtyAfterDisplay = true; } diff --git a/GPU/Common/ReinterpretFramebuffer.cpp b/GPU/Common/ReinterpretFramebuffer.cpp index b453a4d3d6..e6b28f3f5e 100644 --- a/GPU/Common/ReinterpretFramebuffer.cpp +++ b/GPU/Common/ReinterpretFramebuffer.cpp @@ -112,7 +112,7 @@ void FramebufferManagerCommon::ReinterpretFramebuffer(VirtualFramebuffer *vfb, G _assert_(newFormat != oldFormat); // The caller is responsible for updating the format. - _assert_(newFormat == vfb->format); + _assert_(newFormat == vfb->fb_format); ShaderLanguage lang = draw_->GetShaderLanguageDesc().shaderLanguage; diff --git a/GPU/Common/StencilCommon.cpp b/GPU/Common/StencilCommon.cpp index 5cd0f9d795..44cc9304bb 100644 --- a/GPU/Common/StencilCommon.cpp +++ b/GPU/Common/StencilCommon.cpp @@ -153,7 +153,7 @@ bool FramebufferManagerCommon::PerformStencilUpload(u32 addr, int size, StencilU if (!src) return false; - switch (dstBuffer->format) { + switch (dstBuffer->fb_format) { case GE_FORMAT_565: // Well, this doesn't make much sense. return false; @@ -290,7 +290,7 @@ bool FramebufferManagerCommon::PerformStencilUpload(u32 addr, int size, StencilU draw_->SetViewports(1, &viewport); // TODO: Switch the format to a single channel format? - Draw::Texture *tex = MakePixelTexture(src, dstBuffer->format, dstBuffer->fb_stride, dstBuffer->width, dstBuffer->height); + Draw::Texture *tex = MakePixelTexture(src, dstBuffer->fb_format, dstBuffer->fb_stride, dstBuffer->width, dstBuffer->height); if (!tex) { // Bad! return false; @@ -309,10 +309,10 @@ bool FramebufferManagerCommon::PerformStencilUpload(u32 addr, int size, StencilU continue; } StencilUB ub{}; - if (dstBuffer->format == GE_FORMAT_4444) { + if (dstBuffer->fb_format == GE_FORMAT_4444) { draw_->SetStencilParams(0xFF, (i << 4) | i, 0xFF); ub.stencilValue = i * (16.0f / 255.0f); - } else if (dstBuffer->format == GE_FORMAT_5551) { + } else if (dstBuffer->fb_format == GE_FORMAT_5551) { draw_->SetStencilParams(0xFF, 0xFF, 0xFF); ub.stencilValue = i * (128.0f / 255.0f); } else { diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index c696a1c0ca..b24e3aa514 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -807,7 +807,7 @@ void TextureCacheCommon::NotifyFramebuffer(VirtualFramebuffer *framebuffer, Fram const u32 z_addr = framebuffer->z_address & ~mirrorMask; // Probably unnecessary. - const u32 fb_bpp = BufferFormatBytesPerPixel(framebuffer->format); + const u32 fb_bpp = BufferFormatBytesPerPixel(framebuffer->fb_format); const u32 z_bpp = 2; // No other format exists. const u32 fb_stride = framebuffer->fb_stride; const u32 z_stride = framebuffer->z_stride; @@ -865,7 +865,7 @@ bool TextureCacheCommon::MatchFramebuffer( uint32_t fb_address = channel == RASTER_DEPTH ? framebuffer->z_address : framebuffer->fb_address; uint32_t fb_stride = channel == RASTER_DEPTH ? framebuffer->z_stride : framebuffer->fb_stride; - GEBufferFormat fb_format = channel == RASTER_DEPTH ? GE_FORMAT_DEPTH16 : framebuffer->format; + GEBufferFormat fb_format = channel == RASTER_DEPTH ? GE_FORMAT_DEPTH16 : framebuffer->fb_format; if (channel == RASTER_DEPTH && framebuffer->z_address == framebuffer->fb_address) { // Try to avoid silly matches to somewhat malformed buffers. @@ -915,7 +915,7 @@ bool TextureCacheCommon::MatchFramebuffer( if (TextureFormatMatchesBufferFormat(entry.format, fb_format) || (framebuffer->usageFlags & FB_USAGE_BLUE_TO_ALPHA)) { return true; } else if (IsTextureFormat16Bit(entry.format) && IsBufferFormat16Bit(fb_format) && channel == RASTER_COLOR) { - WARN_LOG_ONCE(diffFormat1, G3D, "Texturing from framebuffer with reinterpretable format: %s != %s", GeTextureFormatToString(entry.format), GeBufferFormatToString(fb_format)); + WARN_LOG_ONCE(diffFormat1, G3D, "Texturing from framebuffer with reinterpretable fb_format: %s != %s", GeTextureFormatToString(entry.format), GeBufferFormatToString(fb_format)); *matchInfo = FramebufferMatchInfo{ 0, 0, true, TextureFormatToBufferFormat(entry.format) }; return true; } else { @@ -984,7 +984,7 @@ bool TextureCacheCommon::MatchFramebuffer( } return true; } else if (IsClutFormat((GETextureFormat)(entry.format)) || IsDXTFormat((GETextureFormat)(entry.format))) { - WARN_LOG_ONCE(fourEightBit, G3D, "%s format not supported when texturing from framebuffer of format %s", GeTextureFormatToString(entry.format), GeBufferFormatToString(fb_format)); + WARN_LOG_ONCE(fourEightBit, G3D, "%s fb_format not supported when texturing from framebuffer of format %s", GeTextureFormatToString(entry.format), GeBufferFormatToString(fb_format)); return false; } @@ -1011,8 +1011,8 @@ void TextureCacheCommon::SetTextureFramebuffer(const AttachCandidate &candidate) FramebufferMatchInfo fbInfo = candidate.match; if (candidate.match.reinterpret) { - GEBufferFormat oldFormat = candidate.fb->format; - candidate.fb->format = candidate.match.reinterpretTo; + GEBufferFormat oldFormat = candidate.fb->fb_format; + candidate.fb->fb_format = candidate.match.reinterpretTo; framebufferManager_->ReinterpretFramebuffer(candidate.fb, oldFormat, candidate.match.reinterpretTo); } diff --git a/GPU/Directx9/FramebufferManagerDX9.cpp b/GPU/Directx9/FramebufferManagerDX9.cpp index 610940584c..8de6f438a9 100644 --- a/GPU/Directx9/FramebufferManagerDX9.cpp +++ b/GPU/Directx9/FramebufferManagerDX9.cpp @@ -140,7 +140,7 @@ } const u32 fb_address = vfb->fb_address & 0x3FFFFFFF; - const int dstBpp = vfb->format == GE_FORMAT_8888 ? 4 : 2; + const int dstBpp = vfb->fb_format == GE_FORMAT_8888 ? 4 : 2; // We always need to convert from the framebuffer native format. // Right now that's always 8888. @@ -163,7 +163,7 @@ // TODO: Handle the other formats? We don't currently create them, I think. const int dstByteOffset = (y * vfb->fb_stride + x) * dstBpp; // Pixel size always 4 here because we always request BGRA8888. - ConvertFromBGRA8888(Memory::GetPointerWrite(fb_address + dstByteOffset), (u8 *)locked.pBits, vfb->fb_stride, locked.Pitch / 4, w, h, vfb->format); + ConvertFromBGRA8888(Memory::GetPointerWrite(fb_address + dstByteOffset), (u8 *)locked.pBits, vfb->fb_stride, locked.Pitch / 4, w, h, vfb->fb_format); offscreen->UnlockRect(); } else { ERROR_LOG_REPORT(G3D, "Unable to lock rect from %08x: %d,%d %dx%d of %dx%d", fb_address, (int)rect.left, (int)rect.top, (int)rect.right, (int)rect.bottom, vfb->renderWidth, vfb->renderHeight); From d1336fe15faf44d4d48eca100cdfa04f9d5b6060 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Mon, 22 Aug 2022 23:50:36 +0200 Subject: [PATCH 76/85] Small Draw2D refactor --- GPU/Common/Draw2D.cpp | 115 ++++++++++++++------------ GPU/Common/FramebufferManagerCommon.h | 4 +- 2 files changed, 67 insertions(+), 52 deletions(-) diff --git a/GPU/Common/Draw2D.cpp b/GPU/Common/Draw2D.cpp index 663ff2cc90..f1e6c187ef 100644 --- a/GPU/Common/Draw2D.cpp +++ b/GPU/Common/Draw2D.cpp @@ -155,7 +155,9 @@ void FramebufferManagerCommon::Ensure2DResources() { } } -Draw::Pipeline *FramebufferManagerCommon::Create2DPipeline(RasterChannel (*generate)(ShaderWriter &)) { +Draw::Pipeline *FramebufferManagerCommon::Create2DPipeline(std::function generate) { + Ensure2DResources(); + using namespace Draw; const ShaderLanguageDesc &shaderLanguageDesc = draw_->GetShaderLanguageDesc(); @@ -212,62 +214,16 @@ Draw::Pipeline *FramebufferManagerCommon::Create2DPipeline(RasterChannel (*gener return pipeline; } -void FramebufferManagerCommon::DrawStrip2D(Draw::Texture *tex, Draw2DVertex *verts, int vertexCount, bool linearFilter, Draw2DShader shader, float texW, float texH) { + +void FramebufferManagerCommon::DrawStrip2D(Draw::Texture *tex, Draw2DVertex *verts, int vertexCount, bool linearFilter, Draw::Pipeline *pipeline, float texW, float texH) { using namespace Draw; - Ensure2DResources(); - - const ShaderLanguageDesc &shaderLanguageDesc = draw_->GetShaderLanguageDesc(); - - switch (shader) { - case DRAW2D_COPY_COLOR: - if (!draw2DPipelineColor_) { - draw2DPipelineColor_ = Create2DPipeline(&GenerateDraw2DFs); - } - draw_->BindPipeline(draw2DPipelineColor_); - break; - - case DRAW2D_COPY_DEPTH: - if (!draw_->GetDeviceCaps().fragmentShaderDepthWriteSupported) { - // Can't do it - return; - } - if (!draw2DPipelineDepth_) { - draw2DPipelineDepth_ = Create2DPipeline(&GenerateDraw2DDepthFs); - } - linearFilter = false; - draw_->BindPipeline(draw2DPipelineDepth_); - break; - - case DRAW2D_565_TO_DEPTH: - if (!draw_->GetDeviceCaps().fragmentShaderDepthWriteSupported) { - // Can't do it - return; - } - if (!draw2DPipeline565ToDepth_) { - draw2DPipeline565ToDepth_ = Create2DPipeline(&GenerateDraw2D565ToDepthFs); - } - linearFilter = false; - draw_->BindPipeline(draw2DPipeline565ToDepth_); - break; - - case DRAW2D_565_TO_DEPTH_DESWIZZLE: - if (!draw_->GetDeviceCaps().fragmentShaderDepthWriteSupported) { - // Can't do it - return; - } - if (!draw2DPipeline565ToDepthDeswizzle_) { - draw2DPipeline565ToDepthDeswizzle_ = Create2DPipeline(&GenerateDraw2D565ToDepthDeswizzleFs); - } - linearFilter = false; - draw_->BindPipeline(draw2DPipeline565ToDepthDeswizzle_); - break; - } - Draw2DUB ub; ub.texSizeX = tex ? tex->Width() : texW; ub.texSizeY = tex ? tex->Height() : texH; ub.scaleFactor = (float)renderScaleFactor_; + + draw_->BindPipeline(pipeline); draw_->UpdateDynamicUniformBuffer(&ub, sizeof(ub)); if (tex) { @@ -280,3 +236,60 @@ void FramebufferManagerCommon::DrawStrip2D(Draw::Texture *tex, Draw2DVertex *ver gstate_c.Dirty(DIRTY_FRAGMENTSHADER_STATE | DIRTY_VERTEXSHADER_STATE); } + +void FramebufferManagerCommon::DrawStrip2D(Draw::Texture *tex, Draw2DVertex *verts, int vertexCount, bool linearFilter, Draw2DShader shader, float texW, float texH) { + using namespace Draw; + + const ShaderLanguageDesc &shaderLanguageDesc = draw_->GetShaderLanguageDesc(); + + Draw::Pipeline *pipeline = nullptr; + + switch (shader) { + case DRAW2D_COPY_COLOR: + if (!draw2DPipelineColor_) { + draw2DPipelineColor_ = Create2DPipeline(&GenerateDraw2DFs); + } + pipeline = draw2DPipelineColor_; + break; + + case DRAW2D_COPY_DEPTH: + if (!draw_->GetDeviceCaps().fragmentShaderDepthWriteSupported) { + // Can't do it + return; + } + if (!draw2DPipelineDepth_) { + draw2DPipelineDepth_ = Create2DPipeline(&GenerateDraw2DDepthFs); + } + linearFilter = false; + pipeline = draw2DPipelineDepth_; + break; + + case DRAW2D_565_TO_DEPTH: + if (!draw_->GetDeviceCaps().fragmentShaderDepthWriteSupported) { + // Can't do it + return; + } + if (!draw2DPipeline565ToDepth_) { + draw2DPipeline565ToDepth_ = Create2DPipeline(&GenerateDraw2D565ToDepthFs); + } + linearFilter = false; + pipeline = draw2DPipeline565ToDepth_; + break; + + case DRAW2D_565_TO_DEPTH_DESWIZZLE: + if (!draw_->GetDeviceCaps().fragmentShaderDepthWriteSupported) { + // Can't do it + return; + } + if (!draw2DPipeline565ToDepthDeswizzle_) { + draw2DPipeline565ToDepthDeswizzle_ = Create2DPipeline(&GenerateDraw2D565ToDepthDeswizzleFs); + } + linearFilter = false; + pipeline = draw2DPipeline565ToDepthDeswizzle_; + break; + } + + if (pipeline) { + DrawStrip2D(tex, verts, vertexCount, linearFilter, pipeline, texW, texH); + } +} diff --git a/GPU/Common/FramebufferManagerCommon.h b/GPU/Common/FramebufferManagerCommon.h index 43bc7c293c..fab01b9ceb 100644 --- a/GPU/Common/FramebufferManagerCommon.h +++ b/GPU/Common/FramebufferManagerCommon.h @@ -376,8 +376,10 @@ protected: void DrawActiveTexture(float x, float y, float w, float h, float destW, float destH, float u0, float v0, float u1, float v1, int uvRotation, int flags); void DrawStrip2D(Draw::Texture *tex, Draw2DVertex *verts, int vertexCount, bool linearFilter, Draw2DShader channel, float texW = 0.0f, float texH = 0.0f); + void DrawStrip2D(Draw::Texture *tex, Draw2DVertex *verts, int vertexCount, bool linearFilter, Draw::Pipeline *pipeline, float texW = 0.0f, float texH = 0.0f); + void Ensure2DResources(); - Draw::Pipeline *Create2DPipeline(RasterChannel (*generate)(ShaderWriter &)); + Draw::Pipeline *Create2DPipeline(std::function generate); void CopyToColorFromOverlappingFramebuffers(VirtualFramebuffer *dest); void CopyToDepthFromOverlappingFramebuffers(VirtualFramebuffer *dest); From 65e4e249ecca5f25aee187e28e10bb2ae6e698b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Tue, 23 Aug 2022 10:05:44 +0200 Subject: [PATCH 77/85] More Draw2D refactoring --- GPU/Common/Draw2D.cpp | 76 ++++++++++++++++--------- GPU/Common/Draw2D.h | 14 +++++ GPU/Common/FramebufferManagerCommon.cpp | 22 +++---- GPU/Common/FramebufferManagerCommon.h | 16 +++--- 4 files changed, 81 insertions(+), 47 deletions(-) diff --git a/GPU/Common/Draw2D.cpp b/GPU/Common/Draw2D.cpp index f1e6c187ef..78086bd682 100644 --- a/GPU/Common/Draw2D.cpp +++ b/GPU/Common/Draw2D.cpp @@ -57,26 +57,32 @@ const UniformBufferDesc draw2DUBDesc{ sizeof(Draw2DUB), { } }; -RasterChannel GenerateDraw2DFs(ShaderWriter &writer) { +Draw2DPipelineInfo GenerateDraw2DCopyColorFs(ShaderWriter &writer) { writer.DeclareSamplers(samplers); writer.BeginFSMain(Slice::empty(), varyings, FSFLAG_NONE); writer.C(" vec4 outColor = ").SampleTexture2D("tex", "v_texcoord.xy").C(";\n"); writer.EndFSMain("outColor", FSFLAG_NONE); - return RASTER_COLOR; + return Draw2DPipelineInfo{ + RASTER_COLOR, + RASTER_COLOR, + }; } -RasterChannel GenerateDraw2DDepthFs(ShaderWriter &writer) { +Draw2DPipelineInfo GenerateDraw2DCopyDepthFs(ShaderWriter &writer) { writer.DeclareSamplers(samplers); writer.BeginFSMain(Slice::empty(), varyings, FSFLAG_WRITEDEPTH); writer.C(" vec4 outColor = vec4(0.0, 0.0, 0.0, 0.0);\n"); writer.C(" gl_FragDepth = ").SampleTexture2D("tex", "v_texcoord.xy").C(".x;\n"); writer.EndFSMain("outColor", FSFLAG_WRITEDEPTH); - return RASTER_DEPTH; + return Draw2DPipelineInfo{ + RASTER_DEPTH, + RASTER_DEPTH, + }; } -RasterChannel GenerateDraw2D565ToDepthFs(ShaderWriter &writer) { +Draw2DPipelineInfo GenerateDraw2D565ToDepthFs(ShaderWriter &writer) { writer.DeclareSamplers(samplers); writer.BeginFSMain(Slice::empty(), varyings, FSFLAG_WRITEDEPTH); writer.C(" vec4 outColor = vec4(0.0, 0.0, 0.0, 0.0);\n"); @@ -88,10 +94,13 @@ RasterChannel GenerateDraw2D565ToDepthFs(ShaderWriter &writer) { writer.F(" gl_FragDepth = (depthValue / %f) + %f;\n", factors.scale, factors.offset); writer.EndFSMain("outColor", FSFLAG_WRITEDEPTH); - return RASTER_DEPTH; + return Draw2DPipelineInfo{ + RASTER_COLOR, + RASTER_DEPTH, + }; } -RasterChannel GenerateDraw2D565ToDepthDeswizzleFs(ShaderWriter &writer) { +Draw2DPipelineInfo GenerateDraw2D565ToDepthDeswizzleFs(ShaderWriter &writer) { writer.DeclareSamplers(samplers); writer.BeginFSMain(uniforms, varyings, FSFLAG_WRITEDEPTH); writer.C(" vec4 outColor = vec4(0.0, 0.0, 0.0, 0.0);\n"); @@ -108,7 +117,11 @@ RasterChannel GenerateDraw2D565ToDepthDeswizzleFs(ShaderWriter &writer) { writer.F(" highp float depthValue = (floor(rgb.x * 31.99) + floor(rgb.y * 63.99) * 32.0 + floor(rgb.z * 31.99) * 2048.0); \n"); writer.F(" gl_FragDepth = (depthValue / %f) + %f;\n", factors.scale, factors.offset); writer.EndFSMain("outColor", FSFLAG_WRITEDEPTH); - return RASTER_DEPTH; + + return Draw2DPipelineInfo{ + RASTER_COLOR, + RASTER_DEPTH + }; } void GenerateDraw2DVS(ShaderWriter &writer) { @@ -155,7 +168,7 @@ void FramebufferManagerCommon::Ensure2DResources() { } } -Draw::Pipeline *FramebufferManagerCommon::Create2DPipeline(std::function generate) { +Draw2DPipeline *FramebufferManagerCommon::Create2DPipeline(std::function generate) { Ensure2DResources(); using namespace Draw; @@ -163,7 +176,7 @@ Draw::Pipeline *FramebufferManagerCommon::Create2DPipeline(std::functionCreateShaderModule(ShaderStage::Fragment, shaderLanguageDesc.shaderLanguage, (const uint8_t *)fsCode, strlen(fsCode), "draw2d_fs"); delete[] fsCode; @@ -182,10 +195,10 @@ Draw::Pipeline *FramebufferManagerCommon::Create2DPipeline(std::functionCreateInputLayout(desc); - BlendState *blend = draw_->CreateBlendState({ false, channel == RASTER_COLOR ? 0xF : 0 }); + BlendState *blend = draw_->CreateBlendState({ false, info.writeChannel == RASTER_COLOR ? 0xF : 0 }); DepthStencilStateDesc dsDesc{}; - if (channel == RASTER_DEPTH) { + if (info.writeChannel == RASTER_DEPTH) { dsDesc.depthTestEnabled = true; dsDesc.depthWriteEnabled = true; dsDesc.depthCompare = Draw::Comparison::ALWAYS; @@ -211,19 +224,31 @@ Draw::Pipeline *FramebufferManagerCommon::Create2DPipeline(std::functionRelease(); inputLayout->Release(); - return pipeline; + return new Draw2DPipeline { + pipeline, + info + }; } -void FramebufferManagerCommon::DrawStrip2D(Draw::Texture *tex, Draw2DVertex *verts, int vertexCount, bool linearFilter, Draw::Pipeline *pipeline, float texW, float texH) { +void FramebufferManagerCommon::DrawStrip2D(Draw::Texture *tex, Draw2DVertex *verts, int vertexCount, bool linearFilter, Draw2DPipeline *pipeline, float texW, float texH) { using namespace Draw; + _dbg_assert_(pipeline); + + if (pipeline->info.writeChannel == RASTER_DEPTH) { + _dbg_assert_(draw_->GetDeviceCaps().fragmentShaderDepthWriteSupported); + + // We don't filter inputs when writing depth, results will be bad. + linearFilter = false; + } + Draw2DUB ub; ub.texSizeX = tex ? tex->Width() : texW; ub.texSizeY = tex ? tex->Height() : texH; ub.scaleFactor = (float)renderScaleFactor_; - draw_->BindPipeline(pipeline); + draw_->BindPipeline(pipeline->pipeline); draw_->UpdateDynamicUniformBuffer(&ub, sizeof(ub)); if (tex) { @@ -237,17 +262,17 @@ void FramebufferManagerCommon::DrawStrip2D(Draw::Texture *tex, Draw2DVertex *ver gstate_c.Dirty(DIRTY_FRAGMENTSHADER_STATE | DIRTY_VERTEXSHADER_STATE); } -void FramebufferManagerCommon::DrawStrip2D(Draw::Texture *tex, Draw2DVertex *verts, int vertexCount, bool linearFilter, Draw2DShader shader, float texW, float texH) { +Draw2DPipeline *FramebufferManagerCommon::Get2DPipeline(Draw2DShader shader) { using namespace Draw; const ShaderLanguageDesc &shaderLanguageDesc = draw_->GetShaderLanguageDesc(); - Draw::Pipeline *pipeline = nullptr; + Draw2DPipeline *pipeline = nullptr; switch (shader) { case DRAW2D_COPY_COLOR: if (!draw2DPipelineColor_) { - draw2DPipelineColor_ = Create2DPipeline(&GenerateDraw2DFs); + draw2DPipelineColor_ = Create2DPipeline(&GenerateDraw2DCopyColorFs); } pipeline = draw2DPipelineColor_; break; @@ -255,41 +280,36 @@ void FramebufferManagerCommon::DrawStrip2D(Draw::Texture *tex, Draw2DVertex *ver case DRAW2D_COPY_DEPTH: if (!draw_->GetDeviceCaps().fragmentShaderDepthWriteSupported) { // Can't do it - return; + return nullptr; } if (!draw2DPipelineDepth_) { - draw2DPipelineDepth_ = Create2DPipeline(&GenerateDraw2DDepthFs); + draw2DPipelineDepth_ = Create2DPipeline(&GenerateDraw2DCopyDepthFs); } - linearFilter = false; pipeline = draw2DPipelineDepth_; break; case DRAW2D_565_TO_DEPTH: if (!draw_->GetDeviceCaps().fragmentShaderDepthWriteSupported) { // Can't do it - return; + return nullptr; } if (!draw2DPipeline565ToDepth_) { draw2DPipeline565ToDepth_ = Create2DPipeline(&GenerateDraw2D565ToDepthFs); } - linearFilter = false; pipeline = draw2DPipeline565ToDepth_; break; case DRAW2D_565_TO_DEPTH_DESWIZZLE: if (!draw_->GetDeviceCaps().fragmentShaderDepthWriteSupported) { // Can't do it - return; + return nullptr; } if (!draw2DPipeline565ToDepthDeswizzle_) { draw2DPipeline565ToDepthDeswizzle_ = Create2DPipeline(&GenerateDraw2D565ToDepthDeswizzleFs); } - linearFilter = false; pipeline = draw2DPipeline565ToDepthDeswizzle_; break; } - if (pipeline) { - DrawStrip2D(tex, verts, vertexCount, linearFilter, pipeline, texW, texH); - } + return pipeline; } diff --git a/GPU/Common/Draw2D.h b/GPU/Common/Draw2D.h index e1ed615ba8..332c2c707d 100644 --- a/GPU/Common/Draw2D.h +++ b/GPU/Common/Draw2D.h @@ -28,3 +28,17 @@ inline RasterChannel Draw2DSourceChannel(Draw2DShader shader) { return RASTER_COLOR; } } + +struct Draw2DPipelineInfo { + RasterChannel readChannel; + RasterChannel writeChannel; +}; + +struct Draw2DPipeline { + Draw::Pipeline *pipeline; + Draw2DPipelineInfo info; + void Release() { + pipeline->Release(); + delete this; + } +}; diff --git a/GPU/Common/FramebufferManagerCommon.cpp b/GPU/Common/FramebufferManagerCommon.cpp index 4e7e9a07ee..a3bce4e3fc 100644 --- a/GPU/Common/FramebufferManagerCommon.cpp +++ b/GPU/Common/FramebufferManagerCommon.cpp @@ -573,7 +573,7 @@ void FramebufferManagerCommon::CopyToDepthFromOverlappingFramebuffers(VirtualFra BlitUsingRaster( src->fbo, 0.0f, 0.0f, src->renderWidth, src->renderHeight, dest->fbo, 0.0f, 0.0f, src->renderWidth, src->renderHeight, - false, shader, "565_to_depth"); + false, Get2DPipeline(shader), "565_to_depth"); } } @@ -656,7 +656,7 @@ void FramebufferManagerCommon::CopyToColorFromOverlappingFramebuffers(VirtualFra int dstY2 = dstY1 + dstHeight; BlitUsingRaster(src->fbo, 0.0f, 0.0f, srcWidth, srcHeight, - dst->fbo, dstX1, dstY1, dstX2, dstY2, false, DRAW2D_COPY_COLOR, "copy_color"); + dst->fbo, dstX1, dstY1, dstX2, dstY2, false, Get2DPipeline(DRAW2D_COPY_COLOR), "copy_color"); } } @@ -731,7 +731,7 @@ void FramebufferManagerCommon::BlitFramebufferDepth(VirtualFramebuffer *src, Vir draw_->BlitFramebuffer(src->fbo, 0, 0, w, h, dst->fbo, 0, 0, w, h, Draw::FB_DEPTH_BIT, Draw::FB_BLIT_NEAREST, "BlitFramebufferDepth"); RebindFramebuffer("After BlitFramebufferDepth"); } else if (useRaster) { - BlitUsingRaster(src->fbo, 0, 0, w, h, dst->fbo, 0, 0, w, h, false, Draw2DShader::DRAW2D_COPY_DEPTH, "BlitDepthRaster"); + BlitUsingRaster(src->fbo, 0, 0, w, h, dst->fbo, 0, 0, w, h, false, Get2DPipeline(Draw2DShader::DRAW2D_COPY_DEPTH), "BlitDepthRaster"); } draw_->InvalidateCachedState(); @@ -2491,7 +2491,7 @@ void FramebufferManagerCommon::DrawActiveTexture(float x, float y, float w, floa // Rearrange to strip form. std::swap(coord[2], coord[3]); - DrawStrip2D(nullptr, coord, 4, (flags & DRAWTEX_LINEAR) != 0, DRAW2D_COPY_COLOR); + DrawStrip2D(nullptr, coord, 4, (flags & DRAWTEX_LINEAR) != 0, Get2DPipeline(DRAW2D_COPY_COLOR)); gstate_c.Dirty(DIRTY_BLEND_STATE | DIRTY_RASTER_STATE | DIRTY_DEPTHSTENCIL_STATE | DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_TEXTURE_IMAGE | DIRTY_TEXTURE_PARAMS | DIRTY_VERTEXSHADER_STATE | DIRTY_FRAGMENTSHADER_STATE); } @@ -2587,14 +2587,14 @@ void FramebufferManagerCommon::BlitFramebuffer(VirtualFramebuffer *dst, int dstX draw_->BlitFramebuffer(src->fbo, srcX1, srcY1, srcX2, srcY2, dst->fbo, dstX1, dstY1, dstX2, dstY2, channel == RASTER_COLOR ? Draw::FB_COLOR_BIT : Draw::FB_DEPTH_BIT, Draw::FB_BLIT_NEAREST, tag); } else { - Draw2DShader shader = channel == RASTER_COLOR ? DRAW2D_COPY_COLOR : DRAW2D_COPY_DEPTH; + Draw2DPipeline *pipeline = Get2DPipeline(channel == RASTER_COLOR ? DRAW2D_COPY_COLOR : DRAW2D_COPY_DEPTH); Draw::Framebuffer *srcFBO = src->fbo; if (src == dst) { Draw::Framebuffer *tempFBO = GetTempFBO(TempFBO::BLIT, src->renderWidth, src->renderHeight); - BlitUsingRaster(src->fbo, srcX1, srcY1, srcX2, srcY2, tempFBO, dstX1, dstY1, dstX2, dstY2, false, shader, tag); + BlitUsingRaster(src->fbo, srcX1, srcY1, srcX2, srcY2, tempFBO, dstX1, dstY1, dstX2, dstY2, false, pipeline, tag); srcFBO = tempFBO; } - BlitUsingRaster(srcFBO, srcX1, srcY1, srcX2, srcY2, dst->fbo, dstX1, dstY1, dstX2, dstY2, false, shader, tag); + BlitUsingRaster(srcFBO, srcX1, srcY1, srcX2, srcY2, dst->fbo, dstX1, dstY1, dstX2, dstY2, false, pipeline, tag); } draw_->InvalidateCachedState(); @@ -2607,9 +2607,9 @@ void FramebufferManagerCommon::BlitUsingRaster( Draw::Framebuffer *src, float srcX1, float srcY1, float srcX2, float srcY2, Draw::Framebuffer *dest, float destX1, float destY1, float destX2, float destY2, bool linearFilter, - Draw2DShader shader, const char *tag) { + Draw2DPipeline *pipeline, const char *tag) { - if (shader == DRAW2D_COPY_DEPTH || shader == DRAW2D_565_TO_DEPTH) { + if (pipeline->info.writeChannel == RASTER_DEPTH) { _dbg_assert_(draw_->GetDeviceCaps().fragmentShaderDepthWriteSupported); } @@ -2632,12 +2632,12 @@ void FramebufferManagerCommon::BlitUsingRaster( draw_->BindTexture(0, nullptr); // This will get optimized away in case it's already bound (in VK and GL at least..) draw_->BindFramebufferAsRenderTarget(dest, { Draw::RPAction::KEEP, Draw::RPAction::KEEP, Draw::RPAction::KEEP }, tag ? tag : "BlitUsingRaster"); - draw_->BindFramebufferAsTexture(src, 0, Draw2DSourceChannel(shader) == RASTER_COLOR ? Draw::FB_COLOR_BIT : Draw::FB_DEPTH_BIT, 0); + draw_->BindFramebufferAsTexture(src, 0, pipeline->info.readChannel == RASTER_COLOR ? Draw::FB_COLOR_BIT : Draw::FB_DEPTH_BIT, 0); Draw::Viewport vp{ 0.0f, 0.0f, (float)dest->Width(), (float)dest->Height(), 0.0f, 1.0f }; draw_->SetViewports(1, &vp); draw_->SetScissorRect(0, 0, (int)dest->Width(), (int)dest->Height()); - DrawStrip2D(nullptr, vtx, 4, linearFilter, shader, src->Width(), src->Height()); + DrawStrip2D(nullptr, vtx, 4, linearFilter, pipeline, src->Width(), src->Height()); gstate_c.Dirty(DIRTY_BLEND_STATE | DIRTY_DEPTHSTENCIL_STATE | DIRTY_RASTER_STATE | DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_VERTEXSHADER_STATE | DIRTY_FRAGMENTSHADER_STATE); } diff --git a/GPU/Common/FramebufferManagerCommon.h b/GPU/Common/FramebufferManagerCommon.h index fab01b9ceb..6913839797 100644 --- a/GPU/Common/FramebufferManagerCommon.h +++ b/GPU/Common/FramebufferManagerCommon.h @@ -375,11 +375,11 @@ protected: Draw::Texture *MakePixelTexture(const u8 *srcPixels, GEBufferFormat srcPixelFormat, int srcStride, int width, int height); void DrawActiveTexture(float x, float y, float w, float h, float destW, float destH, float u0, float v0, float u1, float v1, int uvRotation, int flags); - void DrawStrip2D(Draw::Texture *tex, Draw2DVertex *verts, int vertexCount, bool linearFilter, Draw2DShader channel, float texW = 0.0f, float texH = 0.0f); - void DrawStrip2D(Draw::Texture *tex, Draw2DVertex *verts, int vertexCount, bool linearFilter, Draw::Pipeline *pipeline, float texW = 0.0f, float texH = 0.0f); + Draw2DPipeline *FramebufferManagerCommon::Get2DPipeline(Draw2DShader shader); + void DrawStrip2D(Draw::Texture *tex, Draw2DVertex *verts, int vertexCount, bool linearFilter, Draw2DPipeline *pipeline, float texW = 0.0f, float texH = 0.0f); void Ensure2DResources(); - Draw::Pipeline *Create2DPipeline(std::function generate); + Draw2DPipeline *Create2DPipeline(std::function generate); void CopyToColorFromOverlappingFramebuffers(VirtualFramebuffer *dest); void CopyToDepthFromOverlappingFramebuffers(VirtualFramebuffer *dest); @@ -394,7 +394,7 @@ protected: void BlitUsingRaster( Draw::Framebuffer *src, float srcX1, float srcY1, float srcX2, float srcY2, - Draw::Framebuffer *dest, float destX1, float destY1, float destX2, float destY2, bool linearFilter, Draw2DShader shader, const char *tag); + Draw::Framebuffer *dest, float destX1, float destY1, float destX2, float destY2, bool linearFilter, Draw2DPipeline *pipeline, const char *tag); void CopyFramebufferForColorTexture(VirtualFramebuffer *dst, VirtualFramebuffer *src, int flags); @@ -511,10 +511,10 @@ protected: Draw::SamplerState *stencilUploadSampler_ = nullptr; // Draw2D pipelines - Draw::Pipeline *draw2DPipelineColor_ = nullptr; - Draw::Pipeline *draw2DPipelineDepth_ = nullptr; - Draw::Pipeline *draw2DPipeline565ToDepth_ = nullptr; - Draw::Pipeline *draw2DPipeline565ToDepthDeswizzle_ = nullptr; + Draw2DPipeline *draw2DPipelineColor_ = nullptr; + Draw2DPipeline *draw2DPipelineDepth_ = nullptr; + Draw2DPipeline *draw2DPipeline565ToDepth_ = nullptr; + Draw2DPipeline *draw2DPipeline565ToDepthDeswizzle_ = nullptr; Draw::SamplerState *draw2DSamplerLinear_ = nullptr; Draw::SamplerState *draw2DSamplerNearest_ = nullptr; Draw::ShaderModule *draw2DVs_ = nullptr; From 83b7386f7dd1f60e1671013d0439e211e6f10e40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Tue, 23 Aug 2022 10:15:53 +0200 Subject: [PATCH 78/85] Switch reinterpret shaders over to the Draw2D framework. --- GPU/Common/FramebufferManagerCommon.cpp | 3 - GPU/Common/FramebufferManagerCommon.h | 5 +- GPU/Common/ReinterpretFramebuffer.cpp | 93 ++++--------------------- GPU/Common/ReinterpretFramebuffer.h | 10 ++- unittest/TestShaderGenerators.cpp | 24 +------ 5 files changed, 20 insertions(+), 115 deletions(-) diff --git a/GPU/Common/FramebufferManagerCommon.cpp b/GPU/Common/FramebufferManagerCommon.cpp index a3bce4e3fc..9d10953967 100644 --- a/GPU/Common/FramebufferManagerCommon.cpp +++ b/GPU/Common/FramebufferManagerCommon.cpp @@ -2422,9 +2422,6 @@ void FramebufferManagerCommon::DeviceLost() { DoRelease(reinterpretFromTo_[i][j]); } } - DoRelease(reinterpretVBuf_); - DoRelease(reinterpretSampler_); - DoRelease(reinterpretVS_); DoRelease(stencilUploadSampler_); DoRelease(stencilUploadPipeline_); DoRelease(draw2DSamplerNearest_); diff --git a/GPU/Common/FramebufferManagerCommon.h b/GPU/Common/FramebufferManagerCommon.h index 6913839797..d0a692d3bf 100644 --- a/GPU/Common/FramebufferManagerCommon.h +++ b/GPU/Common/FramebufferManagerCommon.h @@ -500,10 +500,7 @@ protected: // Thin3D stuff for reinterpreting image data between the various 16-bit formats. // Safe, not optimal - there might be input attachment tricks, etc, but we can't use them // since we don't want N different implementations. - Draw::Pipeline *reinterpretFromTo_[3][3]{}; - Draw::ShaderModule *reinterpretVS_ = nullptr; - Draw::SamplerState *reinterpretSampler_ = nullptr; - Draw::Buffer *reinterpretVBuf_ = nullptr; + Draw2DPipeline *reinterpretFromTo_[3][3]{}; // Common implementation of stencil buffer upload. Also not 100% optimal, but not performance // critical either. diff --git a/GPU/Common/ReinterpretFramebuffer.cpp b/GPU/Common/ReinterpretFramebuffer.cpp index e6b28f3f5e..8951f08bbd 100644 --- a/GPU/Common/ReinterpretFramebuffer.cpp +++ b/GPU/Common/ReinterpretFramebuffer.cpp @@ -20,11 +20,7 @@ static const SamplerDef samplers[1] = { // TODO: We could possibly have an option to preserve any extra color precision? But gonna start without it. // Requires full size integer math. It would be possible to make a floating point-only version with lots of // modulo and stuff, might do it one day. -void GenerateReinterpretFragmentShader(char *buffer, GEBufferFormat from, GEBufferFormat to, const ShaderLanguageDesc &lang) { - _assert_(lang.bitwiseOps); - - ShaderWriter writer(buffer, lang, ShaderStage::Fragment); - +Draw2DPipelineInfo GenerateReinterpretFragmentShader(ShaderWriter &writer, GEBufferFormat from, GEBufferFormat to) { writer.HighPrecisionFloat(); writer.DeclareSamplers(samplers); @@ -70,22 +66,13 @@ void GenerateReinterpretFragmentShader(char *buffer, GEBufferFormat from, GEBuff } writer.EndFSMain("outColor", FSFLAG_NONE); + + return Draw2DPipelineInfo{ + RASTER_COLOR, + RASTER_COLOR, + }; } -void GenerateReinterpretVertexShader(char *buffer, const ShaderLanguageDesc &lang) { - _assert_(lang.bitwiseOps); - ShaderWriter writer(buffer, lang, ShaderStage::Vertex); - - writer.BeginVSMain(Slice::empty(), Slice::empty(), varyings); - - writer.C(" float x = -1.0 + float((gl_VertexIndex & 1) << 2);\n"); - writer.C(" float y = -1.0 + float((gl_VertexIndex & 2) << 1);\n"); - writer.C(" v_texcoord = (vec2(x, y) + vec2(1.0, 1.0)) * 0.5;\n"); - writer.C(" gl_Position = vec4(x, y, 0.0, 1.0);\n"); - writer.EndVSMain(varyings); -} - - // Can't easily dynamically create these strings, we just pass along the pointer. static const char *reinterpretStrings[3][3] = { { @@ -150,60 +137,15 @@ void FramebufferManagerCommon::ReinterpretFramebuffer(VirtualFramebuffer *vfb, G return; } - if (!reinterpretVS_) { - char *vsCode = new char[4000]; - const ShaderLanguageDesc &shaderLanguageDesc = draw_->GetShaderLanguageDesc(); - GenerateReinterpretVertexShader(vsCode, shaderLanguageDesc); - reinterpretVS_ = draw_->CreateShaderModule(ShaderStage::Vertex, shaderLanguageDesc.shaderLanguage, (const uint8_t *)vsCode, strlen(vsCode), "reinterpret_vs"); - _assert_(reinterpretVS_); - delete[] vsCode; - } - - if (!reinterpretSampler_) { - Draw::SamplerStateDesc samplerDesc{}; - samplerDesc.magFilter = Draw::TextureFilter::LINEAR; - samplerDesc.minFilter = Draw::TextureFilter::LINEAR; - reinterpretSampler_ = draw_->CreateSamplerState(samplerDesc); - } - - if (!reinterpretVBuf_) { - reinterpretVBuf_ = draw_->CreateBuffer(12 * 3, Draw::BufferUsageFlag::DYNAMIC | Draw::BufferUsageFlag::VERTEXDATA); - } - // See if we need to create a new pipeline. - Draw::Pipeline *pipeline = reinterpretFromTo_[(int)oldFormat][(int)newFormat]; + Draw2DPipeline *pipeline = reinterpretFromTo_[(int)oldFormat][(int)newFormat]; if (!pipeline) { - char *fsCode = new char[4000]; - const ShaderLanguageDesc &shaderLanguageDesc = draw_->GetShaderLanguageDesc(); - GenerateReinterpretFragmentShader(fsCode, oldFormat, newFormat, shaderLanguageDesc); - Draw::ShaderModule *reinterpretFS = draw_->CreateShaderModule(ShaderStage::Fragment, shaderLanguageDesc.shaderLanguage, (const uint8_t *)fsCode, strlen(fsCode), "reinterpret_fs"); - _assert_(reinterpretFS); - delete[] fsCode; + pipeline = Create2DPipeline([=](ShaderWriter &shaderWriter) -> Draw2DPipelineInfo { + return GenerateReinterpretFragmentShader(shaderWriter, oldFormat, newFormat); + }); - std::vector shaders; - shaders.push_back(reinterpretVS_); - shaders.push_back(reinterpretFS); - - using namespace Draw; - Draw::PipelineDesc desc{}; - // We use a "fullscreen triangle". - // TODO: clear the stencil buffer. Hard to actually initialize it with the new alpha, though possible - let's see if - // we need it. - DepthStencilState *depth = draw_->CreateDepthStencilState({ false, false, Comparison::LESS }); - BlendState *blendstateOff = draw_->CreateBlendState({ false, 0xF }); - RasterState *rasterNoCull = draw_->CreateRasterState({}); - - // No uniforms for these, only a single texture input. - PipelineDesc pipelineDesc{ Primitive::TRIANGLE_LIST, shaders, nullptr, depth, blendstateOff, rasterNoCull, nullptr }; - pipeline = draw_->CreateGraphicsPipeline(pipelineDesc); - _assert_(pipeline != nullptr); reinterpretFromTo_[(int)oldFormat][(int)newFormat] = pipeline; - - depth->Release(); - blendstateOff->Release(); - rasterNoCull->Release(); - reinterpretFS->Release(); } // Copy to a temp framebuffer. @@ -213,18 +155,9 @@ void FramebufferManagerCommon::ReinterpretFramebuffer(VirtualFramebuffer *vfb, G // itself while writing. draw_->InvalidateCachedState(); draw_->CopyFramebufferImage(vfb->fbo, 0, 0, 0, 0, temp, 0, 0, 0, 0, vfb->renderWidth, vfb->renderHeight, 1, Draw::FBChannel::FB_COLOR_BIT, "reinterpret_prep"); - draw_->BindFramebufferAsRenderTarget(vfb->fbo, { Draw::RPAction::DONT_CARE, Draw::RPAction::KEEP, Draw::RPAction::KEEP }, reinterpretStrings[(int)oldFormat][(int)newFormat]); - draw_->BindPipeline(pipeline); - draw_->BindFramebufferAsTexture(temp, 0, Draw::FBChannel::FB_COLOR_BIT, 0); - draw_->BindSamplerStates(0, 1, &reinterpretSampler_); - draw_->SetScissorRect(0, 0, vfb->renderWidth, vfb->renderHeight); - Draw::Viewport vp = Draw::Viewport{ 0.0f, 0.0f, (float)vfb->renderWidth, (float)vfb->renderHeight, 0.0f, 1.0f }; - draw_->SetViewports(1, &vp); - // Vertex buffer not used - vertices generated in shader. - // TODO: Switch to a vertex buffer for GLES2/D3D9 compat. - draw_->BindVertexBuffers(0, 1, &reinterpretVBuf_, nullptr); - draw_->Draw(3, 0); - draw_->InvalidateCachedState(); + + BlitUsingRaster(temp, 0.0f, 0.0f, vfb->renderWidth, vfb->renderHeight, + vfb->fbo, 0.0f, 0.0f, vfb->renderWidth, vfb->renderHeight, false, pipeline, "reinterpret"); // Unbind. draw_->BindTexture(0, nullptr); diff --git a/GPU/Common/ReinterpretFramebuffer.h b/GPU/Common/ReinterpretFramebuffer.h index 5819366887..ac97e46a9e 100644 --- a/GPU/Common/ReinterpretFramebuffer.h +++ b/GPU/Common/ReinterpretFramebuffer.h @@ -1,11 +1,9 @@ #pragma once +#include "Common/GPU/ShaderWriter.h" + #include "GPU/ge_constants.h" #include "GPU/GPUCommon.h" -#include "Common/GPU/ShaderWriter.h" +#include "GPU/Common/Draw2D.h" -void GenerateReinterpretFragmentShader(char *buffer, GEBufferFormat from, GEBufferFormat to, const ShaderLanguageDesc &lang); - -// Just a single one. Can probably be shared with a lot of similar use cases. -// Generates the coordinates for a fullscreen triangle. -void GenerateReinterpretVertexShader(char *buffer, const ShaderLanguageDesc &lang); +Draw2DPipelineInfo GenerateReinterpretFragmentShader(ShaderWriter &writer, GEBufferFormat from, GEBufferFormat to); diff --git a/unittest/TestShaderGenerators.cpp b/unittest/TestShaderGenerators.cpp index 2463fde971..b37483fcd9 100644 --- a/unittest/TestShaderGenerators.cpp +++ b/unittest/TestShaderGenerators.cpp @@ -180,27 +180,6 @@ bool TestReinterpretShaders() { // Generate all despite failures - it's only 6. bool failed = false; - for (int k = 0; k < ARRAY_SIZE(languages); k++) { - printf("=== %s ===\n\n", ShaderLanguageToString(languages[k])); - - ShaderLanguageDesc desc(languages[k]); - - // These require bitwise operations. - if (!desc.bitwiseOps) { - continue; - } - - GenerateReinterpretVertexShader(buffer, desc); - std::string errorMessage; - if (!TestCompileShader(buffer, languages[k], ShaderStage::Vertex, &errorMessage)) { - printf("Error compiling fragment shader:\n\n%s\n\n%s\n", LineNumberString(buffer).c_str(), errorMessage.c_str()); - failed = true; - return false; - } else { - //printf("===\n%s\n===\n", buffer); - } - } - for (int k = 0; k < ARRAY_SIZE(languages); k++) { printf("=== %s ===\n\n", ShaderLanguageToString(languages[k])); @@ -217,7 +196,8 @@ bool TestReinterpretShaders() { for (int j = 0; j < 3; j++) { if (i == j) continue; // useless shader! - GenerateReinterpretFragmentShader(buffer, fmts[i], fmts[j], desc); + ShaderWriter writer(buffer, desc, ShaderStage::Fragment, nullptr, 0); + GenerateReinterpretFragmentShader(writer, fmts[i], fmts[j]); if (!TestCompileShader(buffer, languages[k], ShaderStage::Fragment, &errorMessage)) { printf("Error compiling fragment shader %d:\n\n%s\n\n%s\n", (int)j, LineNumberString(buffer).c_str(), errorMessage.c_str()); failed = true; From 60e129d88e63e79bbe8ef22ed9d3b92526bb88bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Tue, 23 Aug 2022 10:35:58 +0200 Subject: [PATCH 79/85] Break out Draw2D in a class --- GPU/Common/Draw2D.cpp | 33 +++++++++++++++++++------ GPU/Common/Draw2D.h | 21 ++++++++++++++++ GPU/Common/FramebufferManagerCommon.cpp | 13 +++++----- GPU/Common/FramebufferManagerCommon.h | 11 +++------ GPU/Common/ReinterpretFramebuffer.cpp | 2 +- 5 files changed, 57 insertions(+), 23 deletions(-) diff --git a/GPU/Common/Draw2D.cpp b/GPU/Common/Draw2D.cpp index 78086bd682..f9e7b13d7f 100644 --- a/GPU/Common/Draw2D.cpp +++ b/GPU/Common/Draw2D.cpp @@ -133,7 +133,24 @@ void GenerateDraw2DVS(ShaderWriter &writer) { writer.EndVSMain(varyings); } -void FramebufferManagerCommon::Ensure2DResources() { +template +static void DoRelease(T *&obj) { + if (obj) + obj->Release(); + obj = nullptr; +} + +void Draw2D::DeviceLost() { + DoRelease(draw2DVs_); + DoRelease(draw2DSamplerLinear_); + DoRelease(draw2DSamplerNearest_); +} + +void Draw2D::DeviceRestore(Draw::DrawContext *draw) { + +} + +void Draw2D::Ensure2DResources() { using namespace Draw; const ShaderLanguageDesc &shaderLanguageDesc = draw_->GetShaderLanguageDesc(); @@ -168,7 +185,7 @@ void FramebufferManagerCommon::Ensure2DResources() { } } -Draw2DPipeline *FramebufferManagerCommon::Create2DPipeline(std::function generate) { +Draw2DPipeline *Draw2D::Create2DPipeline(std::function generate) { Ensure2DResources(); using namespace Draw; @@ -231,7 +248,7 @@ Draw2DPipeline *FramebufferManagerCommon::Create2DPipeline(std::functionWidth() : texW; ub.texSizeY = tex ? tex->Height() : texH; - ub.scaleFactor = (float)renderScaleFactor_; + ub.scaleFactor = (float)scaleFactor; draw_->BindPipeline(pipeline->pipeline); draw_->UpdateDynamicUniformBuffer(&ub, sizeof(ub)); @@ -272,7 +289,7 @@ Draw2DPipeline *FramebufferManagerCommon::Get2DPipeline(Draw2DShader shader) { switch (shader) { case DRAW2D_COPY_COLOR: if (!draw2DPipelineColor_) { - draw2DPipelineColor_ = Create2DPipeline(&GenerateDraw2DCopyColorFs); + draw2DPipelineColor_ = draw2D_.Create2DPipeline(&GenerateDraw2DCopyColorFs); } pipeline = draw2DPipelineColor_; break; @@ -283,7 +300,7 @@ Draw2DPipeline *FramebufferManagerCommon::Get2DPipeline(Draw2DShader shader) { return nullptr; } if (!draw2DPipelineDepth_) { - draw2DPipelineDepth_ = Create2DPipeline(&GenerateDraw2DCopyDepthFs); + draw2DPipelineDepth_ = draw2D_.Create2DPipeline(&GenerateDraw2DCopyDepthFs); } pipeline = draw2DPipelineDepth_; break; @@ -294,7 +311,7 @@ Draw2DPipeline *FramebufferManagerCommon::Get2DPipeline(Draw2DShader shader) { return nullptr; } if (!draw2DPipeline565ToDepth_) { - draw2DPipeline565ToDepth_ = Create2DPipeline(&GenerateDraw2D565ToDepthFs); + draw2DPipeline565ToDepth_ = draw2D_.Create2DPipeline(&GenerateDraw2D565ToDepthFs); } pipeline = draw2DPipeline565ToDepth_; break; @@ -305,7 +322,7 @@ Draw2DPipeline *FramebufferManagerCommon::Get2DPipeline(Draw2DShader shader) { return nullptr; } if (!draw2DPipeline565ToDepthDeswizzle_) { - draw2DPipeline565ToDepthDeswizzle_ = Create2DPipeline(&GenerateDraw2D565ToDepthDeswizzleFs); + draw2DPipeline565ToDepthDeswizzle_ = draw2D_.Create2DPipeline(&GenerateDraw2D565ToDepthDeswizzleFs); } pipeline = draw2DPipeline565ToDepthDeswizzle_; break; diff --git a/GPU/Common/Draw2D.h b/GPU/Common/Draw2D.h index 332c2c707d..086d0fc61e 100644 --- a/GPU/Common/Draw2D.h +++ b/GPU/Common/Draw2D.h @@ -42,3 +42,24 @@ struct Draw2DPipeline { delete this; } }; + +class ShaderWriter; + +class Draw2D { +public: + Draw2D(Draw::DrawContext *draw) : draw_(draw) {} + void DeviceLost(); + void DeviceRestore(Draw::DrawContext *draw); + + Draw2DPipeline *Create2DPipeline(std::function generate); + + void DrawStrip2D(Draw::Texture *tex, Draw2DVertex *verts, int vertexCount, bool linearFilter, Draw2DPipeline *pipeline, float texW = 0.0f, float texH = 0.0f, int scaleFactor = 0); + void Ensure2DResources(); + +private: + Draw::DrawContext *draw_; + + Draw::SamplerState *draw2DSamplerLinear_ = nullptr; + Draw::SamplerState *draw2DSamplerNearest_ = nullptr; + Draw::ShaderModule *draw2DVs_ = nullptr; +}; diff --git a/GPU/Common/FramebufferManagerCommon.cpp b/GPU/Common/FramebufferManagerCommon.cpp index 9d10953967..ffc4777aa2 100644 --- a/GPU/Common/FramebufferManagerCommon.cpp +++ b/GPU/Common/FramebufferManagerCommon.cpp @@ -47,7 +47,7 @@ #include "GPU/GPUState.h" FramebufferManagerCommon::FramebufferManagerCommon(Draw::DrawContext *draw) - : draw_(draw) { + : draw_(draw), draw2D_(draw_) { presentation_ = new PresentationCommon(draw); } @@ -2424,19 +2424,19 @@ void FramebufferManagerCommon::DeviceLost() { } DoRelease(stencilUploadSampler_); DoRelease(stencilUploadPipeline_); - DoRelease(draw2DSamplerNearest_); - DoRelease(draw2DSamplerLinear_); - DoRelease(draw2DVs_); DoRelease(draw2DPipelineColor_); DoRelease(draw2DPipelineDepth_); DoRelease(draw2DPipeline565ToDepth_); DoRelease(draw2DPipeline565ToDepthDeswizzle_); + draw2D_.DeviceLost(); + draw_ = nullptr; } void FramebufferManagerCommon::DeviceRestore(Draw::DrawContext *draw) { draw_ = draw; + draw2D_.DeviceRestore(draw_); presentation_->DeviceRestore(draw); } @@ -2488,7 +2488,7 @@ void FramebufferManagerCommon::DrawActiveTexture(float x, float y, float w, floa // Rearrange to strip form. std::swap(coord[2], coord[3]); - DrawStrip2D(nullptr, coord, 4, (flags & DRAWTEX_LINEAR) != 0, Get2DPipeline(DRAW2D_COPY_COLOR)); + draw2D_.DrawStrip2D(nullptr, coord, 4, (flags & DRAWTEX_LINEAR) != 0, Get2DPipeline(DRAW2D_COPY_COLOR)); gstate_c.Dirty(DIRTY_BLEND_STATE | DIRTY_RASTER_STATE | DIRTY_DEPTHSTENCIL_STATE | DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_TEXTURE_IMAGE | DIRTY_TEXTURE_PARAMS | DIRTY_VERTEXSHADER_STATE | DIRTY_FRAGMENTSHADER_STATE); } @@ -2634,7 +2634,8 @@ void FramebufferManagerCommon::BlitUsingRaster( Draw::Viewport vp{ 0.0f, 0.0f, (float)dest->Width(), (float)dest->Height(), 0.0f, 1.0f }; draw_->SetViewports(1, &vp); draw_->SetScissorRect(0, 0, (int)dest->Width(), (int)dest->Height()); - DrawStrip2D(nullptr, vtx, 4, linearFilter, pipeline, src->Width(), src->Height()); + + draw2D_.DrawStrip2D(nullptr, vtx, 4, linearFilter, pipeline, src->Width(), src->Height(), renderScaleFactor_); gstate_c.Dirty(DIRTY_BLEND_STATE | DIRTY_DEPTHSTENCIL_STATE | DIRTY_RASTER_STATE | DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_VERTEXSHADER_STATE | DIRTY_FRAGMENTSHADER_STATE); } diff --git a/GPU/Common/FramebufferManagerCommon.h b/GPU/Common/FramebufferManagerCommon.h index d0a692d3bf..0efa23cf4a 100644 --- a/GPU/Common/FramebufferManagerCommon.h +++ b/GPU/Common/FramebufferManagerCommon.h @@ -375,11 +375,7 @@ protected: Draw::Texture *MakePixelTexture(const u8 *srcPixels, GEBufferFormat srcPixelFormat, int srcStride, int width, int height); void DrawActiveTexture(float x, float y, float w, float h, float destW, float destH, float u0, float v0, float u1, float v1, int uvRotation, int flags); - Draw2DPipeline *FramebufferManagerCommon::Get2DPipeline(Draw2DShader shader); - void DrawStrip2D(Draw::Texture *tex, Draw2DVertex *verts, int vertexCount, bool linearFilter, Draw2DPipeline *pipeline, float texW = 0.0f, float texH = 0.0f); - - void Ensure2DResources(); - Draw2DPipeline *Create2DPipeline(std::function generate); + Draw2DPipeline *Get2DPipeline(Draw2DShader shader); void CopyToColorFromOverlappingFramebuffers(VirtualFramebuffer *dest); void CopyToDepthFromOverlappingFramebuffers(VirtualFramebuffer *dest); @@ -512,8 +508,7 @@ protected: Draw2DPipeline *draw2DPipelineDepth_ = nullptr; Draw2DPipeline *draw2DPipeline565ToDepth_ = nullptr; Draw2DPipeline *draw2DPipeline565ToDepthDeswizzle_ = nullptr; - Draw::SamplerState *draw2DSamplerLinear_ = nullptr; - Draw::SamplerState *draw2DSamplerNearest_ = nullptr; - Draw::ShaderModule *draw2DVs_ = nullptr; + + Draw2D draw2D_; // The fragment shaders are "owned" by the pipelines since they're 1:1. }; diff --git a/GPU/Common/ReinterpretFramebuffer.cpp b/GPU/Common/ReinterpretFramebuffer.cpp index 8951f08bbd..a981742aa8 100644 --- a/GPU/Common/ReinterpretFramebuffer.cpp +++ b/GPU/Common/ReinterpretFramebuffer.cpp @@ -141,7 +141,7 @@ void FramebufferManagerCommon::ReinterpretFramebuffer(VirtualFramebuffer *vfb, G Draw2DPipeline *pipeline = reinterpretFromTo_[(int)oldFormat][(int)newFormat]; if (!pipeline) { - pipeline = Create2DPipeline([=](ShaderWriter &shaderWriter) -> Draw2DPipelineInfo { + pipeline = draw2D_.Create2DPipeline([=](ShaderWriter &shaderWriter) -> Draw2DPipelineInfo { return GenerateReinterpretFragmentShader(shaderWriter, oldFormat, newFormat); }); From 5084743bbbe08794ff297dd84a01b3ca2e1820c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Tue, 23 Aug 2022 11:11:04 +0200 Subject: [PATCH 80/85] Use Draw2D for depal shaders (except the actual blit, for now) --- Common/GPU/ShaderWriter.h | 3 + GPU/Common/DepalettizeShaderCommon.cpp | 19 +----- GPU/Common/DepalettizeShaderCommon.h | 5 +- GPU/Common/Draw2D.cpp | 4 +- GPU/Common/Draw2D.h | 3 + GPU/Common/FramebufferManagerCommon.h | 4 ++ GPU/Common/TextureCacheCommon.cpp | 8 +-- GPU/Common/TextureCacheCommon.h | 6 +- GPU/Common/TextureShaderCommon.cpp | 89 ++++++-------------------- GPU/Common/TextureShaderCommon.h | 18 ++---- GPU/D3D11/GPU_D3D11.cpp | 2 +- GPU/D3D11/TextureCacheD3D11.cpp | 4 +- GPU/D3D11/TextureCacheD3D11.h | 2 +- GPU/Directx9/GPU_DX9.cpp | 2 +- GPU/Directx9/TextureCacheDX9.cpp | 4 +- GPU/Directx9/TextureCacheDX9.h | 2 +- GPU/GLES/GPU_GLES.cpp | 2 +- GPU/GLES/TextureCacheGLES.cpp | 4 +- GPU/GLES/TextureCacheGLES.h | 2 +- GPU/Vulkan/GPU_Vulkan.cpp | 2 +- GPU/Vulkan/TextureCacheVulkan.cpp | 4 +- GPU/Vulkan/TextureCacheVulkan.h | 2 +- unittest/TestShaderGenerators.cpp | 12 +--- 23 files changed, 71 insertions(+), 132 deletions(-) diff --git a/Common/GPU/ShaderWriter.h b/Common/GPU/ShaderWriter.h index 1a1896c75b..a2d80a6910 100644 --- a/Common/GPU/ShaderWriter.h +++ b/Common/GPU/ShaderWriter.h @@ -94,6 +94,9 @@ public: void EndVSMain(Slice varyings); void EndFSMain(const char *vec4_color_variable, FSFlags flags); + const ShaderLanguageDesc &Lang() const { + return lang_; + } void Rewind(size_t offset) { p_ -= offset; diff --git a/GPU/Common/DepalettizeShaderCommon.cpp b/GPU/Common/DepalettizeShaderCommon.cpp index 6e34d02402..15906c616e 100644 --- a/GPU/Common/DepalettizeShaderCommon.cpp +++ b/GPU/Common/DepalettizeShaderCommon.cpp @@ -27,8 +27,6 @@ #include "GPU/Common/GPUStateUtils.h" #include "GPU/Common/DepalettizeShaderCommon.h" -#define WRITE p+=sprintf - static const InputDef vsInputs[2] = { { "vec2", "a_position", Draw::SEM_POSITION, }, { "vec2", "a_texcoord0", Draw::SEM_TEXCOORD0, }, @@ -323,8 +321,7 @@ void GenerateDepalSmoothed(ShaderWriter &writer, const DepalConfig &config) { writer.C(" vec4 outColor = ").SampleTexture2D("pal", "vec2(coord, 0.0)").C(";\n"); } -void GenerateDepalFs(char *buffer, const DepalConfig &config, const ShaderLanguageDesc &lang) { - ShaderWriter writer(buffer, lang, ShaderStage::Fragment); +void GenerateDepalFs(ShaderWriter &writer, const DepalConfig &config) { writer.DeclareSamplers(samplers); writer.HighPrecisionFloat(); writer.BeginFSMain(Slice::empty(), varyings, FSFLAG_NONE); @@ -333,7 +330,7 @@ void GenerateDepalFs(char *buffer, const DepalConfig &config, const ShaderLangua // need two variants. GenerateDepalSmoothed(writer, config); } else { - switch (lang.shaderLanguage) { + switch (writer.Lang().shaderLanguage) { case HLSL_D3D9: case GLSL_1xx: GenerateDepalShaderFloat(writer, config); @@ -344,18 +341,8 @@ void GenerateDepalFs(char *buffer, const DepalConfig &config, const ShaderLangua GenerateDepalShader300(writer, config); break; default: - _assert_msg_(false, "Depal shader language not supported: %d", (int)lang.shaderLanguage); + _assert_msg_(false, "Shader language not supported for depal: %d", (int)writer.Lang().shaderLanguage); } } writer.EndFSMain("outColor", FSFLAG_NONE); } - -void GenerateVs(char *buffer, const ShaderLanguageDesc &lang) { - ShaderWriter writer(buffer, lang, ShaderStage::Vertex, nullptr, 0); - writer.BeginVSMain(vsInputs, Slice::empty(), varyings); - writer.C(" v_texcoord = a_texcoord0;\n"); - writer.C(" gl_Position = vec4(a_position, 0.0, 1.0);\n"); - writer.EndVSMain(varyings); -} - -#undef WRITE diff --git a/GPU/Common/DepalettizeShaderCommon.h b/GPU/Common/DepalettizeShaderCommon.h index 322784c0f0..433dfa74df 100644 --- a/GPU/Common/DepalettizeShaderCommon.h +++ b/GPU/Common/DepalettizeShaderCommon.h @@ -22,6 +22,8 @@ #include "Common/GPU/Shader.h" #include "GPU/ge_constants.h" +class ShaderWriter; + static const int DEPAL_TEXTURE_OLD_AGE = 120; struct DepalConfig { @@ -34,5 +36,4 @@ struct DepalConfig { bool smoothedDepal; }; -void GenerateDepalFs(char *buffer, const DepalConfig &config, const ShaderLanguageDesc &lang); -void GenerateVs(char *buffer, const ShaderLanguageDesc &lang); +void GenerateDepalFs(ShaderWriter &writer, const DepalConfig &config); diff --git a/GPU/Common/Draw2D.cpp b/GPU/Common/Draw2D.cpp index f9e7b13d7f..6759f8e3bf 100644 --- a/GPU/Common/Draw2D.cpp +++ b/GPU/Common/Draw2D.cpp @@ -196,7 +196,6 @@ Draw2DPipeline *Draw2D::Create2DPipeline(std::functionCreateShaderModule(ShaderStage::Fragment, shaderLanguageDesc.shaderLanguage, (const uint8_t *)fsCode, strlen(fsCode), "draw2d_fs"); - delete[] fsCode; _assert_(fs); @@ -243,7 +242,8 @@ Draw2DPipeline *Draw2D::Create2DPipeline(std::functionRelease(); + delete[] code; delete this; } }; diff --git a/GPU/Common/FramebufferManagerCommon.h b/GPU/Common/FramebufferManagerCommon.h index 0efa23cf4a..23b505b772 100644 --- a/GPU/Common/FramebufferManagerCommon.h +++ b/GPU/Common/FramebufferManagerCommon.h @@ -369,6 +369,10 @@ public: } void ReinterpretFramebuffer(VirtualFramebuffer *vfb, GEBufferFormat oldFormat, GEBufferFormat newFormat); + Draw2D *GetDraw2D() { + return &draw2D_; + } + protected: virtual void PackFramebufferSync_(VirtualFramebuffer *vfb, int x, int y, int w, int h); void SetViewport2D(int x, int y, int w, int h); diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index b24e3aa514..aaa38bb7c7 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -105,8 +105,8 @@ inline int dimHeight(u16 dim) { // Vulkan color formats: // TODO -TextureCacheCommon::TextureCacheCommon(Draw::DrawContext *draw) - : draw_(draw) { +TextureCacheCommon::TextureCacheCommon(Draw::DrawContext *draw, Draw2D *draw2D) + : draw_(draw), draw2D_(draw2D) { decimationCounter_ = TEXCACHE_DECIMATION_INTERVAL; // TODO: Clamp down to 256/1KB? Need to check mipmapShareClut and clamp loadclut. @@ -124,7 +124,7 @@ TextureCacheCommon::TextureCacheCommon(Draw::DrawContext *draw) replacer_.Init(); - textureShaderCache_ = new TextureShaderCache(draw); + textureShaderCache_ = new TextureShaderCache(draw, draw2D_); } TextureCacheCommon::~TextureCacheCommon() { @@ -1885,7 +1885,7 @@ static bool CanUseSmoothDepal(const GPUgstate &gstate, GEBufferFormat framebuffe } void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer, GETextureFormat texFormat, RasterChannel channel) { - TextureShader *textureShader = nullptr; + Draw2DPipeline *textureShader = nullptr; uint32_t clutMode = gstate.clutformat & 0xFFFFFF; bool depth = channel == RASTER_DEPTH; diff --git a/GPU/Common/TextureCacheCommon.h b/GPU/Common/TextureCacheCommon.h index 080e11a00b..145e0ee2e2 100644 --- a/GPU/Common/TextureCacheCommon.h +++ b/GPU/Common/TextureCacheCommon.h @@ -31,6 +31,8 @@ #include "GPU/Common/TextureScalerCommon.h" #include "GPU/Common/TextureShaderCommon.h" +class Draw2D; + enum FramebufferNotification { NOTIFY_FB_CREATED, NOTIFY_FB_UPDATED, @@ -271,7 +273,7 @@ struct BuildTexturePlan { class TextureCacheCommon { public: - TextureCacheCommon(Draw::DrawContext *draw); + TextureCacheCommon(Draw::DrawContext *draw, Draw2D *draw2D); virtual ~TextureCacheCommon(); void LoadClut(u32 clutAddr, u32 loadBytes); @@ -400,6 +402,8 @@ protected: } Draw::DrawContext *draw_; + Draw2D *draw2D_; + TextureReplacer replacer_; TextureScalerCommon scaler_; FramebufferManagerCommon *framebufferManager_; diff --git a/GPU/Common/TextureShaderCommon.cpp b/GPU/Common/TextureShaderCommon.cpp index c30ccb0204..694a646131 100644 --- a/GPU/Common/TextureShaderCommon.cpp +++ b/GPU/Common/TextureShaderCommon.cpp @@ -23,6 +23,7 @@ #include "Common/GPU/ShaderWriter.h" #include "Common/Data/Convert/ColorConv.h" #include "Core/Reporting.h" +#include "GPU/Common/Draw2D.h" #include "GPU/Common/DrawEngineCommon.h" #include "GPU/Common/TextureCacheCommon.h" #include "GPU/Common/TextureShaderCommon.h" @@ -37,7 +38,7 @@ static const SamplerDef samplers[2] = { { "pal" }, }; -TextureShaderCache::TextureShaderCache(Draw::DrawContext *draw) : draw_(draw) { } +TextureShaderCache::TextureShaderCache(Draw::DrawContext *draw, Draw2D *draw2D) : draw_(draw), draw2D_(draw2D) { } TextureShaderCache::~TextureShaderCache() { DeviceLost(); @@ -139,10 +140,6 @@ void TextureShaderCache::Clear() { delete tex->second; } texCache_.clear(); - if (vertexShader_) { - vertexShader_->Release(); - vertexShader_ = nullptr; - } if (nearestSampler_) { nearestSampler_->Release(); nearestSampler_ = nullptr; @@ -153,18 +150,6 @@ void TextureShaderCache::Clear() { } } -void TextureShaderCache::Decimate() { - for (auto tex = texCache_.begin(); tex != texCache_.end(); ) { - if (tex->second->lastFrame + DEPAL_TEXTURE_OLD_AGE < gpuStats.numFlips) { - tex->second->texture->Release(); - delete tex->second; - texCache_.erase(tex++); - } else { - ++tex; - } - } -} - Draw::SamplerState *TextureShaderCache::GetSampler(bool linearFilter) { if (linearFilter) { if (!linearSampler_) { @@ -189,55 +174,19 @@ Draw::SamplerState *TextureShaderCache::GetSampler(bool linearFilter) { } } -TextureShader *TextureShaderCache::CreateShader(const char *fs) { - using namespace Draw; - if (!vertexShader_) { - char *buffer = new char[4096]; - GenerateVs(buffer, draw_->GetShaderLanguageDesc()); - vertexShader_ = draw_->CreateShaderModule(ShaderStage::Vertex, draw_->GetShaderLanguageDesc().shaderLanguage, (const uint8_t *)buffer, strlen(buffer), "depal_vs"); - delete[] buffer; +void TextureShaderCache::Decimate() { + for (auto tex = texCache_.begin(); tex != texCache_.end(); ) { + if (tex->second->lastFrame + DEPAL_TEXTURE_OLD_AGE < gpuStats.numFlips) { + tex->second->texture->Release(); + delete tex->second; + texCache_.erase(tex++); + } else { + ++tex; + } } - - ShaderModule *fragShader = draw_->CreateShaderModule(ShaderStage::Fragment, draw_->GetShaderLanguageDesc().shaderLanguage, (const uint8_t *)fs, strlen(fs), "depal_fs"); - - static const InputLayoutDesc desc = { - { - { 16, false }, - }, - { - { 0, SEM_POSITION, DataFormat::R32G32_FLOAT, 0 }, - { 0, SEM_TEXCOORD0, DataFormat::R32G32_FLOAT, 8 }, - }, - }; - InputLayout *inputLayout = draw_->CreateInputLayout(desc); - BlendState *blendOff = draw_->CreateBlendState({ false, 0xF }); - DepthStencilStateDesc dsDesc{}; - DepthStencilState *noDepthStencil = draw_->CreateDepthStencilState(dsDesc); - RasterState *rasterNoCull = draw_->CreateRasterState({}); - - PipelineDesc depalPipelineDesc{ - Primitive::TRIANGLE_STRIP, // Could have use a single triangle too (in which case we'd use LIST here) but want to be prepared to do subrectangles. - { vertexShader_, fragShader }, - inputLayout, noDepthStencil, blendOff, rasterNoCull, nullptr, samplers - }; - - Pipeline *pipeline = draw_->CreateGraphicsPipeline(depalPipelineDesc); - - inputLayout->Release(); - blendOff->Release(); - noDepthStencil->Release(); - rasterNoCull->Release(); - fragShader->Release(); - - _assert_(pipeline); - - TextureShader *depal = new TextureShader(); - depal->pipeline = pipeline; - depal->code = fs; // to std::string - return depal; } -TextureShader *TextureShaderCache::GetDepalettizeShader(uint32_t clutMode, GETextureFormat textureFormat, GEBufferFormat bufferFormat, bool smoothedDepal) { +Draw2DPipeline *TextureShaderCache::GetDepalettizeShader(uint32_t clutMode, GETextureFormat textureFormat, GEBufferFormat bufferFormat, bool smoothedDepal) { using namespace Draw; // Generate an ID for depal shaders. @@ -245,7 +194,6 @@ TextureShader *TextureShaderCache::GetDepalettizeShader(uint32_t clutMode, GETex auto shader = depalCache_.find(id); if (shader != depalCache_.end()) { - TextureShader *depal = shader->second; return shader->second; } @@ -260,8 +208,13 @@ TextureShader *TextureShaderCache::GetDepalettizeShader(uint32_t clutMode, GETex config.smoothedDepal = smoothedDepal; char *buffer = new char[4096]; - GenerateDepalFs(buffer, config, draw_->GetShaderLanguageDesc()); - TextureShader *ts = CreateShader(buffer); + Draw2DPipeline *ts = draw2D_->Create2DPipeline([=](ShaderWriter &writer) -> Draw2DPipelineInfo { + GenerateDepalFs(writer, config); + return Draw2DPipelineInfo{ + config.bufferFormat == GE_FORMAT_DEPTH16 ? RASTER_DEPTH : RASTER_COLOR, + RASTER_COLOR, + }; + }); delete[] buffer; depalCache_[id] = ts; @@ -293,7 +246,7 @@ std::string TextureShaderCache::DebugGetShaderString(std::string idstr, DebugSha } } -void TextureShaderCache::ApplyShader(TextureShader *shader, float bufferW, float bufferH, int renderW, int renderH, const KnownVertexBounds &bounds, u32 uoff, u32 voff) { +void TextureShaderCache::ApplyShader(Draw2DPipeline *pipeline, float bufferW, float bufferH, int renderW, int renderH, const KnownVertexBounds &bounds, u32 uoff, u32 voff) { Draw2DVertex verts[4] = { {-1, -1, 0, 0 }, { 1, -1, 1, 0 }, @@ -335,7 +288,7 @@ void TextureShaderCache::ApplyShader(TextureShader *shader, float bufferW, float } Draw::Viewport vp{ 0.0f, 0.0f, (float)renderW, (float)renderH, 0.0f, 1.0f }; - draw_->BindPipeline(shader->pipeline); + draw_->BindPipeline(pipeline->pipeline); draw_->SetViewports(1, &vp); draw_->SetScissorRect(0, 0, renderW, renderH); draw_->DrawUP((const uint8_t *)verts, 4); diff --git a/GPU/Common/TextureShaderCommon.h b/GPU/Common/TextureShaderCommon.h index 583aa3d516..5e0c5fe476 100644 --- a/GPU/Common/TextureShaderCommon.h +++ b/GPU/Common/TextureShaderCommon.h @@ -29,12 +29,6 @@ #include "GPU/Common/ShaderCommon.h" #include "GPU/Common/DepalettizeShaderCommon.h" -class TextureShader { -public: - Draw::Pipeline *pipeline; - std::string code; -}; - class ClutTexture { public: Draw::Texture *texture; @@ -46,15 +40,15 @@ public: // Caches both shaders and palette textures. class TextureShaderCache { public: - TextureShaderCache(Draw::DrawContext *draw); + TextureShaderCache(Draw::DrawContext *draw, Draw2D *draw2D); ~TextureShaderCache(); - TextureShader *GetDepalettizeShader(uint32_t clutMode, GETextureFormat texFormat, GEBufferFormat pixelFormat, bool smoothedDepal); + Draw2DPipeline *GetDepalettizeShader(uint32_t clutMode, GETextureFormat texFormat, GEBufferFormat pixelFormat, bool smoothedDepal); ClutTexture GetClutTexture(GEPaletteFormat clutFormat, const u32 clutHash, u32 *rawClut); Draw::SamplerState *GetSampler(bool linearFilter); - void ApplyShader(TextureShader *shader, float bufferW, float bufferH, int renderW, int renderH, const KnownVertexBounds &bounds, u32 uoff, u32 voff); + void ApplyShader(Draw2DPipeline *pipeline, float bufferW, float bufferH, int renderW, int renderH, const KnownVertexBounds &bounds, u32 uoff, u32 voff); void Clear(); void Decimate(); @@ -65,13 +59,11 @@ public: void DeviceRestore(Draw::DrawContext *draw); private: - TextureShader *CreateShader(const char *fs); - Draw::DrawContext *draw_; - Draw::ShaderModule *vertexShader_ = nullptr; Draw::SamplerState *nearestSampler_ = nullptr; Draw::SamplerState *linearSampler_ = nullptr; + Draw2D *draw2D_; - std::map depalCache_; + std::map depalCache_; std::map texCache_; }; diff --git a/GPU/D3D11/GPU_D3D11.cpp b/GPU/D3D11/GPU_D3D11.cpp index 956d17fc85..4c251bef46 100644 --- a/GPU/D3D11/GPU_D3D11.cpp +++ b/GPU/D3D11/GPU_D3D11.cpp @@ -60,7 +60,7 @@ GPU_D3D11::GPU_D3D11(GraphicsContext *gfxCtx, Draw::DrawContext *draw) shaderManagerD3D11_ = new ShaderManagerD3D11(draw, device_, context_, featureLevel); framebufferManagerD3D11_ = new FramebufferManagerD3D11(draw); framebufferManager_ = framebufferManagerD3D11_; - textureCacheD3D11_ = new TextureCacheD3D11(draw); + textureCacheD3D11_ = new TextureCacheD3D11(draw, framebufferManager_->GetDraw2D()); textureCache_ = textureCacheD3D11_; drawEngineCommon_ = &drawEngine_; shaderManager_ = shaderManagerD3D11_; diff --git a/GPU/D3D11/TextureCacheD3D11.cpp b/GPU/D3D11/TextureCacheD3D11.cpp index fabb7cca4a..1288db58d8 100644 --- a/GPU/D3D11/TextureCacheD3D11.cpp +++ b/GPU/D3D11/TextureCacheD3D11.cpp @@ -127,8 +127,8 @@ ID3D11SamplerState *SamplerCacheD3D11::GetOrCreateSampler(ID3D11Device *device, return sampler; } -TextureCacheD3D11::TextureCacheD3D11(Draw::DrawContext *draw) - : TextureCacheCommon(draw) { +TextureCacheD3D11::TextureCacheD3D11(Draw::DrawContext *draw, Draw2D *draw2D) + : TextureCacheCommon(draw, draw2D) { device_ = (ID3D11Device *)draw->GetNativeObject(Draw::NativeObject::DEVICE); context_ = (ID3D11DeviceContext *)draw->GetNativeObject(Draw::NativeObject::CONTEXT); diff --git a/GPU/D3D11/TextureCacheD3D11.h b/GPU/D3D11/TextureCacheD3D11.h index b641c72866..86313d0be1 100644 --- a/GPU/D3D11/TextureCacheD3D11.h +++ b/GPU/D3D11/TextureCacheD3D11.h @@ -43,7 +43,7 @@ private: class TextureCacheD3D11 : public TextureCacheCommon { public: - TextureCacheD3D11(Draw::DrawContext *draw); + TextureCacheD3D11(Draw::DrawContext *draw, Draw2D *draw2D); ~TextureCacheD3D11(); void StartFrame() override; diff --git a/GPU/Directx9/GPU_DX9.cpp b/GPU/Directx9/GPU_DX9.cpp index deaeeafb68..fdfb952022 100644 --- a/GPU/Directx9/GPU_DX9.cpp +++ b/GPU/Directx9/GPU_DX9.cpp @@ -58,7 +58,7 @@ GPU_DX9::GPU_DX9(GraphicsContext *gfxCtx, Draw::DrawContext *draw) shaderManagerDX9_ = new ShaderManagerDX9(draw, device_); framebufferManagerDX9_ = new FramebufferManagerDX9(draw); framebufferManager_ = framebufferManagerDX9_; - textureCacheDX9_ = new TextureCacheDX9(draw); + textureCacheDX9_ = new TextureCacheDX9(draw, framebufferManager_->GetDraw2D()); textureCache_ = textureCacheDX9_; drawEngineCommon_ = &drawEngine_; shaderManager_ = shaderManagerDX9_; diff --git a/GPU/Directx9/TextureCacheDX9.cpp b/GPU/Directx9/TextureCacheDX9.cpp index 905f445c1c..a300ad6b82 100644 --- a/GPU/Directx9/TextureCacheDX9.cpp +++ b/GPU/Directx9/TextureCacheDX9.cpp @@ -59,8 +59,8 @@ static const D3DVERTEXELEMENT9 g_FramebufferVertexElements[] = { D3DDECL_END() }; -TextureCacheDX9::TextureCacheDX9(Draw::DrawContext *draw) - : TextureCacheCommon(draw) { +TextureCacheDX9::TextureCacheDX9(Draw::DrawContext *draw, Draw2D *draw2D) + : TextureCacheCommon(draw, draw2D) { lastBoundTexture = INVALID_TEX; isBgraBackend_ = true; diff --git a/GPU/Directx9/TextureCacheDX9.h b/GPU/Directx9/TextureCacheDX9.h index 40351be611..8773b18273 100644 --- a/GPU/Directx9/TextureCacheDX9.h +++ b/GPU/Directx9/TextureCacheDX9.h @@ -31,7 +31,7 @@ class ShaderManagerDX9; class TextureCacheDX9 : public TextureCacheCommon { public: - TextureCacheDX9(Draw::DrawContext *draw); + TextureCacheDX9(Draw::DrawContext *draw, Draw2D *draw2D); ~TextureCacheDX9(); void StartFrame() override; diff --git a/GPU/GLES/GPU_GLES.cpp b/GPU/GLES/GPU_GLES.cpp index 1dd004aab8..809923cf31 100644 --- a/GPU/GLES/GPU_GLES.cpp +++ b/GPU/GLES/GPU_GLES.cpp @@ -60,7 +60,7 @@ GPU_GLES::GPU_GLES(GraphicsContext *gfxCtx, Draw::DrawContext *draw) shaderManagerGL_ = new ShaderManagerGLES(draw); framebufferManagerGL_ = new FramebufferManagerGLES(draw); framebufferManager_ = framebufferManagerGL_; - textureCacheGL_ = new TextureCacheGLES(draw); + textureCacheGL_ = new TextureCacheGLES(draw, framebufferManager_->GetDraw2D()); textureCache_ = textureCacheGL_; drawEngineCommon_ = &drawEngine_; shaderManager_ = shaderManagerGL_; diff --git a/GPU/GLES/TextureCacheGLES.cpp b/GPU/GLES/TextureCacheGLES.cpp index 3af9488560..97e51dcd6c 100644 --- a/GPU/GLES/TextureCacheGLES.cpp +++ b/GPU/GLES/TextureCacheGLES.cpp @@ -45,8 +45,8 @@ #include #endif -TextureCacheGLES::TextureCacheGLES(Draw::DrawContext *draw) - : TextureCacheCommon(draw) { +TextureCacheGLES::TextureCacheGLES(Draw::DrawContext *draw, Draw2D *draw2D) + : TextureCacheCommon(draw, draw2D) { render_ = (GLRenderManager *)draw_->GetNativeObject(Draw::NativeObject::RENDER_MANAGER); nextTexture_ = nullptr; diff --git a/GPU/GLES/TextureCacheGLES.h b/GPU/GLES/TextureCacheGLES.h index d192a2369a..a0f2ed5840 100644 --- a/GPU/GLES/TextureCacheGLES.h +++ b/GPU/GLES/TextureCacheGLES.h @@ -34,7 +34,7 @@ class GLRTexture; class TextureCacheGLES : public TextureCacheCommon { public: - TextureCacheGLES(Draw::DrawContext *draw); + TextureCacheGLES(Draw::DrawContext *draw, Draw2D *draw2D); ~TextureCacheGLES(); void Clear(bool delete_them) override; diff --git a/GPU/Vulkan/GPU_Vulkan.cpp b/GPU/Vulkan/GPU_Vulkan.cpp index adc0a9c127..cab0ccf3cd 100644 --- a/GPU/Vulkan/GPU_Vulkan.cpp +++ b/GPU/Vulkan/GPU_Vulkan.cpp @@ -63,7 +63,7 @@ GPU_Vulkan::GPU_Vulkan(GraphicsContext *gfxCtx, Draw::DrawContext *draw) pipelineManager_ = new PipelineManagerVulkan(vulkan); framebufferManagerVulkan_ = new FramebufferManagerVulkan(draw); framebufferManager_ = framebufferManagerVulkan_; - textureCacheVulkan_ = new TextureCacheVulkan(draw, vulkan); + textureCacheVulkan_ = new TextureCacheVulkan(draw, framebufferManager_->GetDraw2D(), vulkan); textureCache_ = textureCacheVulkan_; drawEngineCommon_ = &drawEngine_; shaderManager_ = shaderManagerVulkan_; diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index 522d88ce5a..555e23b1fd 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -184,8 +184,8 @@ std::vector SamplerCache::DebugGetSamplerIDs() const { return ids; } -TextureCacheVulkan::TextureCacheVulkan(Draw::DrawContext *draw, VulkanContext *vulkan) - : TextureCacheCommon(draw), +TextureCacheVulkan::TextureCacheVulkan(Draw::DrawContext *draw, Draw2D *draw2D, VulkanContext *vulkan) + : TextureCacheCommon(draw, draw2D), computeShaderManager_(vulkan), samplerCache_(vulkan) { DeviceRestore(draw); diff --git a/GPU/Vulkan/TextureCacheVulkan.h b/GPU/Vulkan/TextureCacheVulkan.h index c56652d2c9..2fe4b4d59c 100644 --- a/GPU/Vulkan/TextureCacheVulkan.h +++ b/GPU/Vulkan/TextureCacheVulkan.h @@ -54,7 +54,7 @@ private: class TextureCacheVulkan : public TextureCacheCommon { public: - TextureCacheVulkan(Draw::DrawContext *draw, VulkanContext *vulkan); + TextureCacheVulkan(Draw::DrawContext *draw, Draw2D *draw2D, VulkanContext *vulkan); ~TextureCacheVulkan(); void StartFrame() override; diff --git a/unittest/TestShaderGenerators.cpp b/unittest/TestShaderGenerators.cpp index b37483fcd9..0b87831536 100644 --- a/unittest/TestShaderGenerators.cpp +++ b/unittest/TestShaderGenerators.cpp @@ -292,7 +292,8 @@ bool TestDepalShaders() { config.bufferFormat = GE_FORMAT_8888; config.textureFormat = GE_TFMT_CLUT32; - GenerateDepalFs(buffer, config, desc); + ShaderWriter writer(buffer, desc, ShaderStage::Fragment); + GenerateDepalFs(writer, config); if (!TestCompileShader(buffer, languages[k], ShaderStage::Fragment, &errorMessage)) { printf("Error compiling depal shader:\n\n%s\n\n%s\n", LineNumberString(buffer).c_str(), errorMessage.c_str()); failed = true; @@ -300,15 +301,6 @@ bool TestDepalShaders() { } else { printf("===\n%s\n===\n", buffer); } - - GenerateVs(buffer, desc); - if (!TestCompileShader(buffer, languages[k], ShaderStage::Vertex, &errorMessage)) { - printf("Error compiling depal shader:\n\n%s\n\n%s\n", LineNumberString(buffer).c_str(), errorMessage.c_str()); - failed = true; - return false; - } else { - printf("===\n%s\n===\n", buffer); - } } delete[] buffer; From fc81b76b98e56b78a46fa80a3e719d0dd606f1a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Tue, 23 Aug 2022 23:55:53 +0200 Subject: [PATCH 81/85] Vulkan: Very minor chnages after checking Best Practices with new validation layer --- Common/GPU/Vulkan/VulkanContext.cpp | 1 + Common/GPU/Vulkan/thin3d_vulkan.cpp | 2 +- Common/GPU/thin3d.h | 1 - GPU/Common/Draw2D.cpp | 2 ++ 4 files changed, 4 insertions(+), 2 deletions(-) diff --git a/Common/GPU/Vulkan/VulkanContext.cpp b/Common/GPU/Vulkan/VulkanContext.cpp index 1a938a5235..63351eaf45 100644 --- a/Common/GPU/Vulkan/VulkanContext.cpp +++ b/Common/GPU/Vulkan/VulkanContext.cpp @@ -648,6 +648,7 @@ VkResult VulkanContext::CreateDevice() { } _dbg_assert_(found); + // TODO: A lot of these are on by default in later Vulkan versions, should check for that, technically. extensionsLookup_.KHR_maintenance1 = EnableDeviceExtension(VK_KHR_MAINTENANCE1_EXTENSION_NAME); extensionsLookup_.KHR_maintenance2 = EnableDeviceExtension(VK_KHR_MAINTENANCE2_EXTENSION_NAME); extensionsLookup_.KHR_maintenance3 = EnableDeviceExtension(VK_KHR_MAINTENANCE3_EXTENSION_NAME); diff --git a/Common/GPU/Vulkan/thin3d_vulkan.cpp b/Common/GPU/Vulkan/thin3d_vulkan.cpp index 72236d5e74..9cb7393512 100644 --- a/Common/GPU/Vulkan/thin3d_vulkan.cpp +++ b/Common/GPU/Vulkan/thin3d_vulkan.cpp @@ -667,7 +667,7 @@ public: s.magFilter = desc.magFilter == TextureFilter::LINEAR ? VK_FILTER_LINEAR : VK_FILTER_NEAREST; s.minFilter = desc.minFilter == TextureFilter::LINEAR ? VK_FILTER_LINEAR : VK_FILTER_NEAREST; s.mipmapMode = desc.mipFilter == TextureFilter::LINEAR ? VK_SAMPLER_MIPMAP_MODE_LINEAR : VK_SAMPLER_MIPMAP_MODE_NEAREST; - s.maxLod = desc.maxLod; + s.maxLod = VK_LOD_CLAMP_NONE; VkResult res = vkCreateSampler(vulkan_->GetDevice(), &s, nullptr, &sampler_); _assert_(VK_SUCCESS == res); } diff --git a/Common/GPU/thin3d.h b/Common/GPU/thin3d.h index 264e240fa9..ce06ec79c3 100644 --- a/Common/GPU/thin3d.h +++ b/Common/GPU/thin3d.h @@ -494,7 +494,6 @@ struct SamplerStateDesc { TextureAddressMode wrapU; TextureAddressMode wrapV; TextureAddressMode wrapW; - float maxLod; bool shadowCompareEnabled; Comparison shadowCompareFunc; BorderColor borderColor; diff --git a/GPU/Common/Draw2D.cpp b/GPU/Common/Draw2D.cpp index 6759f8e3bf..b9ac114f92 100644 --- a/GPU/Common/Draw2D.cpp +++ b/GPU/Common/Draw2D.cpp @@ -171,6 +171,7 @@ void Draw2D::Ensure2DResources() { descLinear.mipFilter = TextureFilter::LINEAR; descLinear.wrapU = TextureAddressMode::CLAMP_TO_EDGE; descLinear.wrapV = TextureAddressMode::CLAMP_TO_EDGE; + descLinear.wrapW = TextureAddressMode::CLAMP_TO_EDGE; draw2DSamplerLinear_ = draw_->CreateSamplerState(descLinear); } @@ -181,6 +182,7 @@ void Draw2D::Ensure2DResources() { descNearest.mipFilter = TextureFilter::NEAREST; descNearest.wrapU = TextureAddressMode::CLAMP_TO_EDGE; descNearest.wrapV = TextureAddressMode::CLAMP_TO_EDGE; + descNearest.wrapW = TextureAddressMode::CLAMP_TO_EDGE; draw2DSamplerNearest_ = draw_->CreateSamplerState(descNearest); } } From 86085335ca3841aa64c5c459a99749ef6a6cfcab Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Tue, 23 Aug 2022 19:20:14 -0700 Subject: [PATCH 82/85] GE Debugger: Record 1 flip if no display calls. Before we were waiting 4 flips before ending recording. --- GPU/Debugger/Record.cpp | 12 +++++++++--- GPU/Debugger/Record.h | 2 +- GPU/GPUCommon.cpp | 2 +- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/GPU/Debugger/Record.cpp b/GPU/Debugger/Record.cpp index 907c7b82c4..cc63dccf72 100644 --- a/GPU/Debugger/Record.cpp +++ b/GPU/Debugger/Record.cpp @@ -50,6 +50,7 @@ namespace GPURecord { static bool active = false; static bool nextFrame = false; static int flipLastAction = -1; +static int flipFinishAt = -1; static std::function writeCallback; static std::vector pushbuf; @@ -145,6 +146,7 @@ static void BeginRecording() { lastTextures.clear(); lastRenderTargets.clear(); flipLastAction = gpuStats.numFlips; + flipFinishAt = -1; u32 ptr = (u32)pushbuf.size(); u32 sz = 512 * 4; @@ -494,6 +496,7 @@ bool Activate() { if (!nextFrame) { nextFrame = true; flipLastAction = gpuStats.numFlips; + flipFinishAt = -1; return true; } return false; @@ -512,6 +515,7 @@ static void FinishRecording() { NOTICE_LOG(SYSTEM, "Recording finished"); active = false; flipLastAction = gpuStats.numFlips; + flipFinishAt = -1; if (writeCallback) writeCallback(filename); @@ -673,10 +677,10 @@ void NotifyDisplay(u32 framebuf, int stride, int fmt) { } } -void NotifyFrame() { +void NotifyBeginFrame() { const bool noDisplayAction = flipLastAction + 4 < gpuStats.numFlips; - // We do this only to catch things that don't call NotifyFrame. - if (active && HasDrawCommands() && noDisplayAction) { + // We do this only to catch things that don't call NotifyDisplay. + if (active && HasDrawCommands() && (noDisplayAction || gpuStats.numFlips == flipFinishAt)) { NOTICE_LOG(SYSTEM, "Recording complete on frame"); struct DisplayBufData { @@ -700,6 +704,8 @@ void NotifyFrame() { if (nextFrame && (gstate_c.skipDrawReason & SKIPDRAW_SKIPFRAME) == 0 && noDisplayAction) { NOTICE_LOG(SYSTEM, "Recording starting on frame..."); BeginRecording(); + // If we began on a BeginFrame, end on a BeginFrame. + flipFinishAt = gpuStats.numFlips + 1; } } diff --git a/GPU/Debugger/Record.h b/GPU/Debugger/Record.h index b66a2ea17f..5c5d2f6dbc 100644 --- a/GPU/Debugger/Record.h +++ b/GPU/Debugger/Record.h @@ -36,7 +36,7 @@ void NotifyMemcpy(u32 dest, u32 src, u32 sz); void NotifyMemset(u32 dest, int v, u32 sz); void NotifyUpload(u32 dest, u32 sz); void NotifyDisplay(u32 addr, int stride, int fmt); -void NotifyFrame(); +void NotifyBeginFrame(); void NotifyCPU(); }; diff --git a/GPU/GPUCommon.cpp b/GPU/GPUCommon.cpp index 7db2fd4b42..841547302a 100644 --- a/GPU/GPUCommon.cpp +++ b/GPU/GPUCommon.cpp @@ -1109,7 +1109,7 @@ void GPUCommon::BeginFrame() { } else if (dumpThisFrame_) { dumpThisFrame_ = false; } - GPURecord::NotifyFrame(); + GPURecord::NotifyBeginFrame(); } void GPUCommon::SlowRunLoop(DisplayList &list) From c581a8389677a5a32314eb76ef80429f8bc00a27 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Tue, 23 Aug 2022 19:29:06 -0700 Subject: [PATCH 83/85] GPU: Centralize SetDisplayFramebuffer(). --- GPU/Common/FramebufferManagerCommon.cpp | 4 ++++ GPU/D3D11/GPU_D3D11.cpp | 8 -------- GPU/D3D11/GPU_D3D11.h | 1 - GPU/Directx9/GPU_DX9.cpp | 6 ------ GPU/Directx9/GPU_DX9.h | 1 - GPU/GLES/GPU_GLES.cpp | 6 ------ GPU/GLES/GPU_GLES.h | 1 - GPU/GPUCommon.cpp | 4 ++++ GPU/GPUCommon.h | 1 + GPU/Vulkan/GPU_Vulkan.cpp | 2 -- GPU/Vulkan/GPU_Vulkan.h | 1 - 11 files changed, 9 insertions(+), 26 deletions(-) diff --git a/GPU/Common/FramebufferManagerCommon.cpp b/GPU/Common/FramebufferManagerCommon.cpp index bfdc23815f..92da28b882 100644 --- a/GPU/Common/FramebufferManagerCommon.cpp +++ b/GPU/Common/FramebufferManagerCommon.cpp @@ -41,6 +41,7 @@ #include "GPU/Common/PresentationCommon.h" #include "GPU/Common/TextureCacheCommon.h" #include "GPU/Common/ReinterpretFramebuffer.h" +#include "GPU/Debugger/Debugger.h" #include "GPU/Debugger/Record.h" #include "GPU/Debugger/Stepping.h" #include "GPU/GPUInterface.h" @@ -105,6 +106,9 @@ void FramebufferManagerCommon::SetDisplayFramebuffer(u32 framebuf, u32 stride, G displayFramebufPtr_ = framebuf; displayStride_ = stride; displayFormat_ = format; + // TODO: Some games like Spongebob - Yellow Avenger, never change framebuffer, they blit to it. + // So breaking on frames doesn't work. Might want to move this to sceDisplay vsync. + GPUDebug::NotifyDisplay(framebuf, stride, format); GPURecord::NotifyDisplay(framebuf, stride, format); } diff --git a/GPU/D3D11/GPU_D3D11.cpp b/GPU/D3D11/GPU_D3D11.cpp index 956d17fc85..4d1e299a6a 100644 --- a/GPU/D3D11/GPU_D3D11.cpp +++ b/GPU/D3D11/GPU_D3D11.cpp @@ -35,7 +35,6 @@ #include "GPU/GeDisasm.h" #include "GPU/Common/FramebufferManagerCommon.h" -#include "GPU/Debugger/Debugger.h" #include "GPU/D3D11/ShaderManagerD3D11.h" #include "GPU/D3D11/GPU_D3D11.h" #include "GPU/D3D11/FramebufferManagerD3D11.h" @@ -239,13 +238,6 @@ void GPU_D3D11::BeginFrame() { gstate_c.Dirty(DIRTY_PROJTHROUGHMATRIX); } -void GPU_D3D11::SetDisplayFramebuffer(u32 framebuf, u32 stride, GEBufferFormat format) { - // TODO: Some games like Spongebob - Yellow Avenger, never change framebuffer, they blit to it. - // So breaking on frames doesn't work. Might want to move this to sceDisplay vsync. - GPUDebug::NotifyDisplay(framebuf, stride, format); - framebufferManagerD3D11_->SetDisplayFramebuffer(framebuf, stride, format); -} - void GPU_D3D11::CopyDisplayToOutput(bool reallyDirty) { // Flush anything left over. drawEngine_.Flush(); diff --git a/GPU/D3D11/GPU_D3D11.h b/GPU/D3D11/GPU_D3D11.h index 33790c7f99..d1e5287782 100644 --- a/GPU/D3D11/GPU_D3D11.h +++ b/GPU/D3D11/GPU_D3D11.h @@ -41,7 +41,6 @@ public: void ExecuteOp(u32 op, u32 diff) override; void ReapplyGfxState() override; - void SetDisplayFramebuffer(u32 framebuf, u32 stride, GEBufferFormat format) override; void GetStats(char *buffer, size_t bufsize) override; void ClearCacheNextFrame() override; void DeviceLost() override; // Only happens on Android. Drop all textures and shaders. diff --git a/GPU/Directx9/GPU_DX9.cpp b/GPU/Directx9/GPU_DX9.cpp index deaeeafb68..61be1a5d39 100644 --- a/GPU/Directx9/GPU_DX9.cpp +++ b/GPU/Directx9/GPU_DX9.cpp @@ -38,7 +38,6 @@ #include "GPU/GeDisasm.h" #include "GPU/Common/FramebufferManagerCommon.h" -#include "GPU/Debugger/Debugger.h" #include "GPU/Directx9/ShaderManagerDX9.h" #include "GPU/Directx9/GPU_DX9.h" #include "GPU/Directx9/FramebufferManagerDX9.h" @@ -286,11 +285,6 @@ void GPU_DX9::BeginFrame() { framebufferManager_->BeginFrame(); } -void GPU_DX9::SetDisplayFramebuffer(u32 framebuf, u32 stride, GEBufferFormat format) { - GPUDebug::NotifyDisplay(framebuf, stride, format); - framebufferManagerDX9_->SetDisplayFramebuffer(framebuf, stride, format); -} - void GPU_DX9::CopyDisplayToOutput(bool reallyDirty) { dxstate.depthWrite.set(true); dxstate.colorMask.set(0xF); diff --git a/GPU/Directx9/GPU_DX9.h b/GPU/Directx9/GPU_DX9.h index 35ac9817e1..0e313da397 100644 --- a/GPU/Directx9/GPU_DX9.h +++ b/GPU/Directx9/GPU_DX9.h @@ -40,7 +40,6 @@ public: void ExecuteOp(u32 op, u32 diff) override; void ReapplyGfxState() override; - void SetDisplayFramebuffer(u32 framebuf, u32 stride, GEBufferFormat format) override; void GetStats(char *buffer, size_t bufsize) override; void ClearCacheNextFrame() override; void DeviceLost() override; // Only happens on Android. Drop all textures and shaders. diff --git a/GPU/GLES/GPU_GLES.cpp b/GPU/GLES/GPU_GLES.cpp index 1dd004aab8..6b135e273e 100644 --- a/GPU/GLES/GPU_GLES.cpp +++ b/GPU/GLES/GPU_GLES.cpp @@ -36,7 +36,6 @@ #include "GPU/ge_constants.h" #include "GPU/GeDisasm.h" #include "GPU/Common/FramebufferManagerCommon.h" -#include "GPU/Debugger/Debugger.h" #include "GPU/GLES/ShaderManagerGLES.h" #include "GPU/GLES/GPU_GLES.h" #include "GPU/GLES/FramebufferManagerGLES.h" @@ -360,11 +359,6 @@ void GPU_GLES::BeginFrame() { framebufferManagerGL_->BeginFrame(); } -void GPU_GLES::SetDisplayFramebuffer(u32 framebuf, u32 stride, GEBufferFormat format) { - GPUDebug::NotifyDisplay(framebuf, stride, format); - framebufferManagerGL_->SetDisplayFramebuffer(framebuf, stride, format); -} - void GPU_GLES::CopyDisplayToOutput(bool reallyDirty) { // Flush anything left over. framebufferManagerGL_->RebindFramebuffer("RebindFramebuffer - CopyDisplayToOutput"); diff --git a/GPU/GLES/GPU_GLES.h b/GPU/GLES/GPU_GLES.h index f308d15445..cbe6bc00b0 100644 --- a/GPU/GLES/GPU_GLES.h +++ b/GPU/GLES/GPU_GLES.h @@ -47,7 +47,6 @@ public: void ExecuteOp(u32 op, u32 diff) override; void ReapplyGfxState() override; - void SetDisplayFramebuffer(u32 framebuf, u32 stride, GEBufferFormat format) override; void GetStats(char *buffer, size_t bufsize) override; void ClearCacheNextFrame() override; diff --git a/GPU/GPUCommon.cpp b/GPU/GPUCommon.cpp index 841547302a..ea6bab864f 100644 --- a/GPU/GPUCommon.cpp +++ b/GPU/GPUCommon.cpp @@ -2765,6 +2765,10 @@ void GPUCommon::SetCmdValue(u32 op) { downcount = 0; } +void GPUCommon::SetDisplayFramebuffer(u32 framebuf, u32 stride, GEBufferFormat format) { + framebufferManager_->SetDisplayFramebuffer(framebuf, stride, format); +} + void GPUCommon::DoBlockTransfer(u32 skipDrawReason) { // TODO: This is used a lot to copy data around between render targets and textures, // and also to quickly load textures from RAM to VRAM. So we should do checks like the following: diff --git a/GPU/GPUCommon.h b/GPU/GPUCommon.h index e61d5dada9..f389b788e2 100644 --- a/GPU/GPUCommon.h +++ b/GPU/GPUCommon.h @@ -117,6 +117,7 @@ public: u32 Break(int mode) override; void ReapplyGfxState() override; + void SetDisplayFramebuffer(u32 framebuf, u32 stride, GEBufferFormat format) override; void CopyDisplayToOutput(bool reallyDirty) override = 0; void InitClear() override = 0; bool PerformMemoryCopy(u32 dest, u32 src, int size) override; diff --git a/GPU/Vulkan/GPU_Vulkan.cpp b/GPU/Vulkan/GPU_Vulkan.cpp index adc0a9c127..ee902e92f6 100644 --- a/GPU/Vulkan/GPU_Vulkan.cpp +++ b/GPU/Vulkan/GPU_Vulkan.cpp @@ -37,7 +37,6 @@ #include "GPU/ge_constants.h" #include "GPU/GeDisasm.h" #include "GPU/Common/FramebufferManagerCommon.h" -#include "GPU/Debugger/Debugger.h" #include "GPU/Vulkan/ShaderManagerVulkan.h" #include "GPU/Vulkan/GPU_Vulkan.h" #include "GPU/Vulkan/FramebufferManagerVulkan.h" @@ -432,7 +431,6 @@ void GPU_Vulkan::InitClear() { } void GPU_Vulkan::SetDisplayFramebuffer(u32 framebuf, u32 stride, GEBufferFormat format) { - GPUDebug::NotifyDisplay(framebuf, stride, format); framebufferManager_->SetDisplayFramebuffer(framebuf, stride, format); } diff --git a/GPU/Vulkan/GPU_Vulkan.h b/GPU/Vulkan/GPU_Vulkan.h index 18da82e6b0..3c13d57621 100644 --- a/GPU/Vulkan/GPU_Vulkan.h +++ b/GPU/Vulkan/GPU_Vulkan.h @@ -50,7 +50,6 @@ public: void PreExecuteOp(u32 op, u32 diff) override; void ExecuteOp(u32 op, u32 diff) override; - void SetDisplayFramebuffer(u32 framebuf, u32 stride, GEBufferFormat format) override; void GetStats(char *buffer, size_t bufsize) override; void ClearCacheNextFrame() override; void DeviceLost() override; // Only happens on Android. Drop all textures and shaders. From a901fa431520588f4207ce232e6087296bb7df6d Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Tue, 23 Aug 2022 19:48:34 -0700 Subject: [PATCH 84/85] GE Debugger: Add separate step based on vsync. I think there were some games where this would step in the middle of a frame, but not seeing it commonly now. So make it the default, but allow both methods in the menu. Fixes #15893. --- GPU/Common/FramebufferManagerCommon.cpp | 2 -- GPU/Debugger/Debugger.cpp | 9 +++++++++ GPU/Debugger/Debugger.h | 2 ++ GPU/GPUCommon.cpp | 1 + GPU/Vulkan/GPU_Vulkan.cpp | 4 ---- Windows/GEDebugger/GEDebugger.cpp | 4 ++++ Windows/ppsspp.rc | 5 +++-- Windows/resource.h | 3 ++- 8 files changed, 21 insertions(+), 9 deletions(-) diff --git a/GPU/Common/FramebufferManagerCommon.cpp b/GPU/Common/FramebufferManagerCommon.cpp index 92da28b882..95be5742fa 100644 --- a/GPU/Common/FramebufferManagerCommon.cpp +++ b/GPU/Common/FramebufferManagerCommon.cpp @@ -106,8 +106,6 @@ void FramebufferManagerCommon::SetDisplayFramebuffer(u32 framebuf, u32 stride, G displayFramebufPtr_ = framebuf; displayStride_ = stride; displayFormat_ = format; - // TODO: Some games like Spongebob - Yellow Avenger, never change framebuffer, they blit to it. - // So breaking on frames doesn't work. Might want to move this to sceDisplay vsync. GPUDebug::NotifyDisplay(framebuf, stride, format); GPURecord::NotifyDisplay(framebuf, stride, format); } diff --git a/GPU/Debugger/Debugger.cpp b/GPU/Debugger/Debugger.cpp index 04fb647f1d..439c763e8e 100644 --- a/GPU/Debugger/Debugger.cpp +++ b/GPU/Debugger/Debugger.cpp @@ -154,6 +154,15 @@ void NotifyDisplay(u32 framebuf, u32 stride, int format) { } } +void NotifyBeginFrame() { + if (!active) + return; + if (breakNext == BreakNext::VSYNC) { + // Just start stepping as soon as we can once the vblank finishes. + breakNext = BreakNext::OP; + } +} + int PrimsThisFrame() { return primsThisFrame; } diff --git a/GPU/Debugger/Debugger.h b/GPU/Debugger/Debugger.h index 43ec3174b9..b17c6b4ad0 100644 --- a/GPU/Debugger/Debugger.h +++ b/GPU/Debugger/Debugger.h @@ -28,6 +28,7 @@ enum class BreakNext { TEX, NONTEX, FRAME, + VSYNC, PRIM, CURVE, COUNT, @@ -43,6 +44,7 @@ void SetBreakCount(int c, bool relative = false); bool NotifyCommand(u32 pc); void NotifyDraw(); void NotifyDisplay(u32 framebuf, u32 stride, int format); +void NotifyBeginFrame(); int PrimsThisFrame(); int PrimsLastFrame(); diff --git a/GPU/GPUCommon.cpp b/GPU/GPUCommon.cpp index ea6bab864f..9358a99ed9 100644 --- a/GPU/GPUCommon.cpp +++ b/GPU/GPUCommon.cpp @@ -1109,6 +1109,7 @@ void GPUCommon::BeginFrame() { } else if (dumpThisFrame_) { dumpThisFrame_ = false; } + GPUDebug::NotifyBeginFrame(); GPURecord::NotifyBeginFrame(); } diff --git a/GPU/Vulkan/GPU_Vulkan.cpp b/GPU/Vulkan/GPU_Vulkan.cpp index ee902e92f6..fa1024670b 100644 --- a/GPU/Vulkan/GPU_Vulkan.cpp +++ b/GPU/Vulkan/GPU_Vulkan.cpp @@ -430,10 +430,6 @@ void GPU_Vulkan::InitClear() { } } -void GPU_Vulkan::SetDisplayFramebuffer(u32 framebuf, u32 stride, GEBufferFormat format) { - framebufferManager_->SetDisplayFramebuffer(framebuf, stride, format); -} - void GPU_Vulkan::CopyDisplayToOutput(bool reallyDirty) { // Flush anything left over. drawEngine_.Flush(); diff --git a/Windows/GEDebugger/GEDebugger.cpp b/Windows/GEDebugger/GEDebugger.cpp index 49ecc6af4e..7c78dcf80e 100644 --- a/Windows/GEDebugger/GEDebugger.cpp +++ b/Windows/GEDebugger/GEDebugger.cpp @@ -979,6 +979,10 @@ BOOL CGEDebugger::DlgProc(UINT message, WPARAM wParam, LPARAM lParam) { SetBreakNext(BreakNext::FRAME); break; + case IDC_GEDBG_STEPVSYNC: + SetBreakNext(BreakNext::VSYNC); + break; + case IDC_GEDBG_STEPPRIM: SetBreakNext(BreakNext::PRIM); break; diff --git a/Windows/ppsspp.rc b/Windows/ppsspp.rc index e2f38fd8e6..3bc7dfed34 100644 --- a/Windows/ppsspp.rc +++ b/Windows/ppsspp.rc @@ -202,7 +202,7 @@ EXSTYLE WS_EX_ACCEPTFILES | WS_EX_TOOLWINDOW CAPTION "GE" FONT 8, "MS Shell Dlg", 0, 0, 0x1 BEGIN - PUSHBUTTON "Step &Frame",IDC_GEDBG_STEPFRAME,10,2,44,14 + PUSHBUTTON "Step &Frame",IDC_GEDBG_STEPVSYNC,10,2,44,14 PUSHBUTTON "Step &Tex",IDC_GEDBG_STEPTEX,60,2,44,14 PUSHBUTTON "Step &Draw",IDC_GEDBG_STEPDRAW,105,2,44,14 PUSHBUTTON "Step &Prim",IDC_GEDBG_STEPPRIM,150,2,44,14 @@ -679,7 +679,8 @@ BEGIN MENUITEM "Next &Curve", IDC_GEDBG_STEPCURVE MENUITEM "Next &Texture", IDC_GEDBG_STEPTEX MENUITEM "Next &Draw Flush", IDC_GEDBG_STEPDRAW - MENUITEM "Next &Frame", IDC_GEDBG_STEPFRAME + MENUITEM "Next Display &Framebuf", IDC_GEDBG_STEPFRAME + MENUITEM "Next &Vsync Frame", IDC_GEDBG_STEPVSYNC MENUITEM "", 0, MFT_SEPARATOR MENUITEM "&Auto Flush Pending", IDC_GEDBG_FLUSHAUTO END diff --git a/Windows/resource.h b/Windows/resource.h index eacb42760b..13104152e9 100644 --- a/Windows/resource.h +++ b/Windows/resource.h @@ -331,6 +331,7 @@ #define ID_GEDBG_SHOWONLEFT 40219 #define ID_GEDBG_SHOWONRIGHT 40220 #define ID_GEDBG_SHOWONTOPRIGHT 40221 +#define IDC_GEDBG_STEPVSYNC 40222 // Dummy option to let the buffered rendering hotkey cycle through all the options. @@ -344,7 +345,7 @@ #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 256 -#define _APS_NEXT_COMMAND_VALUE 40222 +#define _APS_NEXT_COMMAND_VALUE 40223 #define _APS_NEXT_CONTROL_VALUE 1202 #define _APS_NEXT_SYMED_VALUE 101 #endif From 27d00199c8b5a2d9420a3cd2e0591f4f55743dc3 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Tue, 23 Aug 2022 19:50:01 -0700 Subject: [PATCH 85/85] GE Debugger: Fix bad read on step at start of VRAM. --- GPU/GPUCommon.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/GPU/GPUCommon.cpp b/GPU/GPUCommon.cpp index 9358a99ed9..167f7ddbf8 100644 --- a/GPU/GPUCommon.cpp +++ b/GPU/GPUCommon.cpp @@ -2708,7 +2708,8 @@ void GPUCommon::ResetListState(int listID, DisplayListState state) { GPUDebugOp GPUCommon::DissassembleOp(u32 pc, u32 op) { char buffer[1024]; - GeDisassembleOp(pc, op, Memory::Read_U32(pc - 4), buffer, sizeof(buffer)); + u32 prev = Memory::IsValidAddress(pc - 4) ? Memory::ReadUnchecked_U32(pc - 4) : 0; + GeDisassembleOp(pc, op, prev, buffer, sizeof(buffer)); GPUDebugOp info; info.pc = pc;