diff --git a/Source/Core/VideoBackends/D3D/TextureCache.cpp b/Source/Core/VideoBackends/D3D/TextureCache.cpp index 73d45f9ad2e6..6a269df60b7a 100644 --- a/Source/Core/VideoBackends/D3D/TextureCache.cpp +++ b/Source/Core/VideoBackends/D3D/TextureCache.cpp @@ -4,6 +4,7 @@ #include "Core/HW/Memmap.h" #include "VideoBackends/D3D/D3DBase.h" +#include "VideoBackends/D3D/D3DShader.h" #include "VideoBackends/D3D/D3DState.h" #include "VideoBackends/D3D/D3DUtil.h" #include "VideoBackends/D3D/FramebufferManager.h" @@ -14,6 +15,7 @@ #include "VideoBackends/D3D/TextureEncoder.h" #include "VideoBackends/D3D/VertexShaderCache.h" #include "VideoCommon/ImageWrite.h" +#include "VideoCommon/LookUpTables.h" #include "VideoCommon/RenderBase.h" #include "VideoCommon/VideoConfig.h" @@ -179,17 +181,165 @@ void TextureCache::TCacheEntry::FromRenderTarget(u32 dstAddr, unsigned int dstFo size_in_bytes = (u32)encoded_size; - TextureCache::MakeRangeDynamic(addr, (u32)encoded_size); + TextureCache::MakeRangeDynamic(dstAddr, (u32)encoded_size); this->hash = hash; } } +const char palette_shader[] = +R"HLSL( +sampler samp0 : register(s0); +Texture2DArray Tex0 : register(t0); +Buffer Tex1 : register(t1); +uniform float Multiply; + +uint Convert3To8(uint v) +{ + // Swizzle bits: 00000123 -> 12312312 + return (v << 5) | (v << 2) | (v >> 1); +} + +uint Convert4To8(uint v) +{ + // Swizzle bits: 00001234 -> 12341234 + return (v << 4) | v; +} + +uint Convert5To8(uint v) +{ + // Swizzle bits: 00012345 -> 12345123 + return (v << 3) | (v >> 2); +} + +uint Convert6To8(uint v) +{ + // Swizzle bits: 00123456 -> 12345612 + return (v << 2) | (v >> 4); +} + +float4 DecodePixel_RGB5A3(uint val) +{ + int r,g,b,a; + if ((val&0x8000)) + { + r=Convert5To8((val>>10) & 0x1f); + g=Convert5To8((val>>5 ) & 0x1f); + b=Convert5To8((val ) & 0x1f); + a=0xFF; + } + else + { + a=Convert3To8((val>>12) & 0x7); + r=Convert4To8((val>>8 ) & 0xf); + g=Convert4To8((val>>4 ) & 0xf); + b=Convert4To8((val ) & 0xf); + } + return float4(r, g, b, a) / 255; +} + +float4 DecodePixel_RGB565(uint val) +{ + int r, g, b, a; + r = Convert5To8((val >> 11) & 0x1f); + g = Convert6To8((val >> 5) & 0x3f); + b = Convert5To8((val)& 0x1f); + a = 0xFF; + return float4(r, g, b, a) / 255; +} + +float4 DecodePixel_IA8(uint val) +{ + int i = val & 0xFF; + int a = val >> 8; + return float4(i, i, i, a) / 255; +} + +void main( + out float4 ocol0 : SV_Target, + in float4 pos : SV_Position, + in float3 uv0 : TEXCOORD0) +{ + uint src = round(Tex0.Sample(samp0,uv0) * Multiply).r; + src = Tex1.Load(src); + src = ((src << 8) & 0xFF00) | (src >> 8); + ocol0 = DECODE(src); +} +)HLSL"; + +void TextureCache::ConvertTexture(TCacheEntryBase* entry, TCacheEntryBase* unconverted, void* palette, TlutFormat format) +{ + g_renderer->ResetAPIState(); + + // stretch picture with increased internal resolution + const D3D11_VIEWPORT vp = CD3D11_VIEWPORT(0.f, 0.f, (float)unconverted->config.width, (float)unconverted->config.height); + D3D::context->RSSetViewports(1, &vp); + + D3D11_BOX box{ 0, 0, 0, 512, 1, 1 }; + D3D::context->UpdateSubresource(palette_buf, 0, &box, palette, 0, 0); + + D3D::stateman->SetTexture(1, palette_buf_srv); + + float params[4] = { unconverted->format == 0 ? 15.f : 255.f }; + D3D::context->UpdateSubresource(palette_uniform, 0, nullptr, ¶ms, 0, 0); + D3D::stateman->SetPixelConstants(palette_uniform); + + const D3D11_RECT sourcerect = CD3D11_RECT(0, 0, unconverted->config.width, unconverted->config.height); + + D3D::SetPointCopySampler(); + + // Make sure we don't draw with the texture set as both a source and target. + // (This can happen because we don't unbind textures when we free them.) + D3D::stateman->UnsetTexture(static_cast(entry)->texture->GetSRV()); + + D3D::context->OMSetRenderTargets(1, &static_cast(entry)->texture->GetRTV(), nullptr); + + // Create texture copy + D3D::drawShadedTexQuad( + static_cast(unconverted)->texture->GetSRV(), + &sourcerect, unconverted->config.width, unconverted->config.height, + palette_pixel_shader[format], + VertexShaderCache::GetSimpleVertexShader(), VertexShaderCache::GetSimpleInputLayout(), + GeometryShaderCache::GetCopyGeometryShader()); + + D3D::context->OMSetRenderTargets(1, &FramebufferManager::GetEFBColorTexture()->GetRTV(), FramebufferManager::GetEFBDepthTexture()->GetDSV()); + + g_renderer->RestoreAPIState(); +} + +ID3D11PixelShader *GetConvertShader(const char* Type) +{ + std::string shader = "#define DECODE DecodePixel_"; + shader.append(Type); + shader.append("\n"); + shader.append(palette_shader); + return D3D::CompileAndCreatePixelShader(shader); +} + TextureCache::TextureCache() { // FIXME: Is it safe here? g_encoder = new PSTextureEncoder; g_encoder->Init(); + + palette_buf = nullptr; + palette_buf_srv = nullptr; + palette_uniform = nullptr; + palette_pixel_shader[GX_TL_IA8] = GetConvertShader("IA8"); + palette_pixel_shader[GX_TL_RGB565] = GetConvertShader("RGB565"); + palette_pixel_shader[GX_TL_RGB5A3] = GetConvertShader("RGB5A3"); + auto lutBd = CD3D11_BUFFER_DESC(sizeof(u16) * 256, D3D11_BIND_SHADER_RESOURCE); + HRESULT hr = D3D::device->CreateBuffer(&lutBd, nullptr, &palette_buf); + CHECK(SUCCEEDED(hr), "create palette decoder lut buffer"); + D3D::SetDebugObjectName(palette_buf, "texture decoder lut buffer"); + auto outlutUavDesc = CD3D11_SHADER_RESOURCE_VIEW_DESC(palette_buf, DXGI_FORMAT_R16_UINT, 0, 256, 0); + hr = D3D::device->CreateShaderResourceView(palette_buf, &outlutUavDesc, &palette_buf_srv); + CHECK(SUCCEEDED(hr), "create palette decoder lut srv"); + D3D::SetDebugObjectName(palette_buf_srv, "texture decoder lut srv"); + const D3D11_BUFFER_DESC cbdesc = CD3D11_BUFFER_DESC(16, D3D11_BIND_CONSTANT_BUFFER, D3D11_USAGE_DEFAULT); + hr = D3D::device->CreateBuffer(&cbdesc, nullptr, &palette_uniform); + CHECK(SUCCEEDED(hr), "Create palette decoder constant buffer"); + D3D::SetDebugObjectName((ID3D11DeviceChild*)palette_uniform, "a constant buffer used in TextureCache::CopyRenderTargetToTexture"); } TextureCache::~TextureCache() @@ -200,6 +350,12 @@ TextureCache::~TextureCache() g_encoder->Shutdown(); delete g_encoder; g_encoder = nullptr; + + SAFE_RELEASE(palette_buf); + SAFE_RELEASE(palette_buf_srv); + SAFE_RELEASE(palette_uniform); + for (ID3D11PixelShader*& shader : palette_pixel_shader) + SAFE_RELEASE(shader); } } diff --git a/Source/Core/VideoBackends/D3D/TextureCache.h b/Source/Core/VideoBackends/D3D/TextureCache.h index 49dfc153400c..0866de2b31c7 100644 --- a/Source/Core/VideoBackends/D3D/TextureCache.h +++ b/Source/Core/VideoBackends/D3D/TextureCache.h @@ -42,8 +42,15 @@ class TextureCache : public ::TextureCache u64 EncodeToRamFromTexture(u32 address, void* source_texture, u32 SourceW, u32 SourceH, bool bFromZBuffer, bool bIsIntensityFmt, u32 copyfmt, int bScaleByHalf, const EFBRectangle& source) {return 0;}; + virtual void ConvertTexture(TCacheEntryBase* entry, TCacheEntryBase* unconverted, void* palette, TlutFormat format) override; + void CompileShaders() override { } void DeleteShaders() override { } + + ID3D11Buffer *palette_buf; + ID3D11ShaderResourceView *palette_buf_srv; + ID3D11Buffer *palette_uniform; + ID3D11PixelShader* palette_pixel_shader[3]; }; } diff --git a/Source/Core/VideoBackends/OGL/TextureCache.cpp b/Source/Core/VideoBackends/OGL/TextureCache.cpp index 83c4af7a988b..e579909a9d69 100644 --- a/Source/Core/VideoBackends/OGL/TextureCache.cpp +++ b/Source/Core/VideoBackends/OGL/TextureCache.cpp @@ -204,7 +204,7 @@ void TextureCache::TCacheEntry::FromRenderTarget(u32 dstAddr, unsigned int dstFo if (false == g_ActiveConfig.bCopyEFBToTexture) { int encoded_size = TextureConverter::EncodeToRamFromTexture( - addr, + dstAddr, read_texture, srcFormat == PEControl::Z24, isIntensity, @@ -212,12 +212,12 @@ void TextureCache::TCacheEntry::FromRenderTarget(u32 dstAddr, unsigned int dstFo scaleByHalf, srcRect); - u8* dst = Memory::GetPointer(addr); + u8* dst = Memory::GetPointer(dstAddr); u64 const new_hash = GetHash64(dst,encoded_size,g_ActiveConfig.iSafeTextureCache_ColorSamples); size_in_bytes = (u32)encoded_size; - TextureCache::MakeRangeDynamic(addr,encoded_size); + TextureCache::MakeRangeDynamic(dstAddr, encoded_size); hash = new_hash; } @@ -359,4 +359,10 @@ void TextureCache::DeleteShaders() s_DepthMatrixProgram.Destroy(); } +void TextureCache::ConvertTexture(TextureCache::TCacheEntryBase* entry, TCacheEntryBase* unconverted, void* palette, TlutFormat format) +{ + // TODO: Implement. + return; +} + } diff --git a/Source/Core/VideoBackends/OGL/TextureCache.h b/Source/Core/VideoBackends/OGL/TextureCache.h index a855b450b682..bdf6fd6309e9 100644 --- a/Source/Core/VideoBackends/OGL/TextureCache.h +++ b/Source/Core/VideoBackends/OGL/TextureCache.h @@ -48,6 +48,7 @@ class TextureCache : public ::TextureCache ~TextureCache(); TCacheEntryBase* CreateTexture(const TCacheEntryConfig& config) override; + void ConvertTexture(TCacheEntryBase* entry, TCacheEntryBase* unconverted, void* palette, TlutFormat format) override; void CompileShaders() override; void DeleteShaders() override; diff --git a/Source/Core/VideoCommon/TextureCacheBase.cpp b/Source/Core/VideoCommon/TextureCacheBase.cpp index b40f9d0882e0..6d40e788b588 100644 --- a/Source/Core/VideoCommon/TextureCacheBase.cpp +++ b/Source/Core/VideoCommon/TextureCacheBase.cpp @@ -32,6 +32,8 @@ size_t TextureCache::temp_size; TextureCache::TexCache TextureCache::textures; TextureCache::TexPool TextureCache::texture_pool; +TextureCache::TCacheEntryBase* TextureCache::bound_textures[8]; +std::vector TextureCache::to_free_list; TextureCache::BackupConfig TextureCache::backup_config; @@ -74,6 +76,8 @@ void TextureCache::RequestInvalidateTextureCache() void TextureCache::Invalidate() { + UnbindTextures(); + for (auto& tex : textures) { delete tex.second; @@ -143,7 +147,7 @@ void TextureCache::Cleanup(int _frameCount) } if (_frameCount > TEXTURE_KILL_THRESHOLD + iter->second->frameCount && // EFB copies living on the host GPU are unrecoverable and thus shouldn't be deleted - !iter->second->IsEfbCopy()) + !iter->second->IsUnrecoverable()) { FreeTexture(iter->second); iter = textures.erase(iter); @@ -174,17 +178,17 @@ void TextureCache::Cleanup(int _frameCount) } } -void TextureCache::InvalidateRange(u32 start_address, u32 size) +void TextureCache::MakeRangeDynamic(u32 start_address, u32 size) { TexCache::iterator - iter = textures.begin(), - tcend = textures.end(); - while (iter != tcend) + iter = textures.begin(); + + while (iter != textures.end()) { if (iter->second->OverlapsMemoryRange(start_address, size)) { FreeTexture(iter->second); - textures.erase(iter++); + iter = textures.erase(iter); } else { @@ -193,53 +197,19 @@ void TextureCache::InvalidateRange(u32 start_address, u32 size) } } -void TextureCache::MakeRangeDynamic(u32 start_address, u32 size) -{ - TexCache::iterator - iter = textures.lower_bound(start_address), - tcend = textures.upper_bound(start_address + size); - - if (iter != textures.begin()) - --iter; - - for (; iter != tcend; ++iter) - { - if (iter->second->OverlapsMemoryRange(start_address, size)) - { - iter->second->SetHashes(TEXHASH_INVALID); - } - } -} - bool TextureCache::TCacheEntryBase::OverlapsMemoryRange(u32 range_address, u32 range_size) const { - if (addr + size_in_bytes <= range_address) + if (!addr.HasMemAddress()) return false; - if (addr >= range_address + range_size) + u32 memaddr = addr.GetMemAddress(); + if (memaddr + size_in_bytes <= range_address) return false; - return true; -} - -void TextureCache::ClearRenderTargets() -{ - TexCache::iterator - iter = textures.begin(), - tcend = textures.end(); + if (memaddr >= range_address + range_size) + return false; - while (iter != tcend) - { - if (iter->second->IsEfbCopy()) - { - FreeTexture(iter->second); - textures.erase(iter++); - } - else - { - ++iter; - } - } + return true; } void TextureCache::DumpTexture(TCacheEntryBase* entry, std::string basename, unsigned int level) @@ -267,16 +237,34 @@ static u32 CalculateLevelSize(u32 level_0_size, u32 level) } // Used by TextureCache::Load -static TextureCache::TCacheEntryBase* ReturnEntry(unsigned int stage, TextureCache::TCacheEntryBase* entry) +TextureCache::TCacheEntryBase* TextureCache::ReturnEntry(unsigned int stage, TCacheEntryBase* entry) { entry->frameCount = FRAMECOUNT_INVALID; - entry->Bind(stage); + bound_textures[stage] = entry; GFX_DEBUGGER_PAUSE_AT(NEXT_TEXTURE_CHANGE, true); return entry; } +void TextureCache::BindTextures() +{ + for (int i = 0; i < 8; ++i) + { + if (bound_textures[i]) + bound_textures[i]->Bind(i); + } +} + +void TextureCache::UnbindTextures() +{ + for (auto entry : to_free_list) + FreeTexture(entry); + to_free_list.clear(); + + std::fill(std::begin(bound_textures), std::end(bound_textures), nullptr); +} + TextureCache::TCacheEntryBase* TextureCache::Load(const u32 stage) { const FourTexUnits &tex = bpmem.tex[stage >> 2]; @@ -303,13 +291,16 @@ TextureCache::TCacheEntryBase* TextureCache::Load(const u32 stage) const unsigned int nativeW = width; const unsigned int nativeH = height; - u32 texID = address; // Hash assigned to texcache entry (also used to generate filenames used for texture dumping and custom texture lookup) u64 tex_hash = TEXHASH_INVALID; u32 full_format = texformat; const bool isPaletteTexture = (texformat == GX_TF_C4 || texformat == GX_TF_C8 || texformat == GX_TF_C14X2); + + if (isPaletteTexture && tlutfmt > GX_TL_RGB5A3) + return nullptr; + if (isPaletteTexture) full_format = texformat | (tlutfmt << 16); @@ -324,61 +315,105 @@ TextureCache::TCacheEntryBase* TextureCache::Load(const u32 stage) // TODO: This doesn't hash GB tiles for preloaded RGBA8 textures (instead, it's hashing more data from the low tmem bank than it should) tex_hash = GetHash64(src_data, texture_size, g_ActiveConfig.iSafeTextureCache_ColorSamples); u32 palette_size = 0; + u64 tlut_hash = 0; if (isPaletteTexture) { palette_size = TexDecoder_GetPaletteSize(texformat); - u64 tlut_hash = GetHash64(&texMem[tlutaddr], palette_size, g_ActiveConfig.iSafeTextureCache_ColorSamples); - - // Mix the tlut hash into the texture hash. So we only have to compare it one. - tex_hash ^= tlut_hash; - - // NOTE: For non-paletted textures, texID is equal to the texture address. - // A paletted texture, however, may have multiple texIDs assigned though depending on the currently used tlut. - // This (changing texID depending on the tlut_hash) is a trick to get around - // an issue with Metroid Prime's fonts (it has multiple sets of fonts on each other - // stored in a single texture and uses the palette to make different characters - // visible or invisible. Thus, unless we want to recreate the textures for every drawn character, - // we must make sure that a paletted texture gets assigned multiple IDs for each tlut used. - // - // EFB copys however didn't know anything about the tlut, so don't change the texID if there - // already is an efb copy at this source. This makes those textures less broken when using efb to texture. - // Examples are the mini map in Twilight Princess and objects on the targetting computer in Rogue Squadron 2(RS2). - // TODO: Convert those textures using the right palette, so they display correctly - auto iter = textures.find(texID); - if (iter == textures.end() || !iter->second->IsEfbCopy()) - texID ^= ((u32)tlut_hash) ^(u32)(tlut_hash >> 32); + tlut_hash = GetHash64(&texMem[tlutaddr], palette_size, g_ActiveConfig.iSafeTextureCache_ColorSamples); } // GPUs don't like when the specified mipmap count would require more than one 1x1-sized LOD in the mipmap chain // e.g. 64x64 with 7 LODs would have the mipmap chain 64x64,32x32,16x16,8x8,4x4,2x2,1x1,0x0, so we limit the mipmap count to 6 there tex_levels = std::min(IntLog2(std::max(width, height)) + 1, tex_levels); - TCacheEntryBase*& entry = textures[texID]; - if (entry) + TextureAddress texID; + TextureAddress paletteDecodedID; + if (from_tmem) { - // 1. Calculate reference hash: - // calculated from RAM texture data for normal textures. Hashes for paletted textures are modified by tlut_hash. 0 for virtual EFB copies. - if (g_ActiveConfig.bCopyEFBToTexture && entry->IsEfbCopy()) - tex_hash = TEXHASH_INVALID; + u32 tmem_addr = bpmem.tex[stage / 4].texImage1[stage % 4].tmem_even * TMEM_LINE_SIZE; + if (texformat == GX_TF_RGBA8 && from_tmem) + { + u32 tmem_odd_addr = bpmem.tex[stage / 4].texImage2[stage % 4].tmem_odd * TMEM_LINE_SIZE; + texID = TextureAddress::TMem(tmem_addr, tmem_odd_addr); + } + else + { + texID = TextureAddress::TMem(tmem_addr); + if (isPaletteTexture) + paletteDecodedID = TextureAddress::TMem(tmem_addr, tlutaddr); + } + } + else + { + texID = TextureAddress::Mem(address); + if (isPaletteTexture) + paletteDecodedID = TextureAddress::MemPalette(address, tlutaddr); + } - // 2. a) For EFB copies, only the hash and the texture address need to match - if (entry->IsEfbCopy() && tex_hash == entry->hash && address == entry->addr) + auto search_result = textures.find(texID); + bool palette_decoded_entry = false; + if (isPaletteTexture && search_result == textures.end()) + { + search_result = textures.find(paletteDecodedID); + palette_decoded_entry = true; + } + + TCacheEntryBase* entry = nullptr; + if (search_result != textures.end()) + entry = search_result->second; + + if (entry) + { + // EFB copies have slightly different rules: the hash doesn't need to match + // in EFB2Tex mode, and EFB copy formats have different meanings from texture + // formats. + if (entry->IsEfbCopy() && (g_ActiveConfig.bCopyEFBToTexture || tex_hash == entry->hash)) { - // TODO: Print a warning if the format changes! In this case, - // we could reinterpret the internal texture object data to the new pixel format - // (similar to what is already being done in Renderer::ReinterpretPixelFormat()) + // TODO: We should check format/width/height/levels for EFB copies. Checking + // format is complicated because EFB copy formats don't exactly match + // texture formats. I'm not sure what effect checking width/height/levels + // would have. + if (!palette_decoded_entry && isPaletteTexture) + { + // Perform palette decoding. + // TODO: Skip decoding if we find a match. + auto decoded_entry_iter = textures.find(paletteDecodedID); + if (decoded_entry_iter != textures.end()) + { + // Pool this texture and make a new one later. We delay actually freeing + // the texture if it's currently bound; this can happen in edge cases + // involving multiple stages bound to the same address. + MaybeFreeTexture(decoded_entry_iter->second); + textures.erase(decoded_entry_iter); + } + + TCacheEntryBase *decoded_entry = AllocateTexture(entry->config); + + decoded_entry->SetGeneralParameters(paletteDecodedID, texture_size, full_format); + decoded_entry->SetDimensions(entry->native_width, entry->native_height, 1); + decoded_entry->SetHashes(TEXHASH_INVALID); + decoded_entry->frameCount = FRAMECOUNT_INVALID; + + g_texture_cache->ConvertTexture(decoded_entry, entry, &texMem[tlutaddr], (TlutFormat)tlutfmt); + textures[paletteDecodedID] = decoded_entry; + entry = decoded_entry; + } return ReturnEntry(stage, entry); } - // 2. b) For normal textures, all texture parameters need to match - if (address == entry->addr && tex_hash == entry->hash && full_format == entry->format && + // For normal textures, all texture parameters need to match. + if ((tex_hash ^ tlut_hash) == entry->hash && full_format == entry->format && entry->native_levels >= tex_levels && entry->native_width == nativeW && entry->native_height == nativeH) { + // TODO: We have palette decoding code, we might want to use it in some cases. return ReturnEntry(stage, entry); } - // pool this texture and make a new one later - FreeTexture(entry); + // Pool this texture and make a new one later. We delay actually freeing + // the texture if it's currently bound; this can happen in edge cases involving + // multiple stages bound to the same address. + MaybeFreeTexture(entry); + textures.erase(search_result); } std::unique_ptr hires_tex; @@ -434,9 +469,9 @@ TextureCache::TCacheEntryBase* TextureCache::Load(const u32 stage) entry = AllocateTexture(config); GFX_DEBUGGER_PAUSE_AT(NEXT_NEW_TEXTURE, true); - entry->SetGeneralParameters(address, texture_size, full_format); + entry->SetGeneralParameters(isPaletteTexture ? paletteDecodedID : texID, texture_size, full_format); entry->SetDimensions(nativeW, nativeH, tex_levels); - entry->hash = tex_hash; + entry->hash = tex_hash ^ tlut_hash; // load texture entry->Load(width, height, expandedWidth, 0); @@ -502,6 +537,7 @@ TextureCache::TCacheEntryBase* TextureCache::Load(const u32 stage) INCSTAT(stats.numTexturesUploaded); SETSTAT(stats.numTexturesAlive, textures.size()); + textures[entry->addr] = entry; return ReturnEntry(stage, entry); } @@ -791,9 +827,12 @@ void TextureCache::CopyRenderTargetToTexture(u32 dstAddr, unsigned int dstFormat unsigned int scaled_tex_w = g_ActiveConfig.bCopyEFBScaled ? Renderer::EFBToScaledX(tex_w) : tex_w; unsigned int scaled_tex_h = g_ActiveConfig.bCopyEFBScaled ? Renderer::EFBToScaledY(tex_h) : tex_h; - TCacheEntryBase*& entry = textures[dstAddr]; - if (entry) - FreeTexture(entry); + auto entry_iter = textures.find(TextureAddress::Mem(dstAddr)); + if (entry_iter != textures.end()) + { + FreeTexture(entry_iter->second); + textures.erase(entry_iter); + } // create the texture TCacheEntryConfig config; @@ -802,16 +841,17 @@ void TextureCache::CopyRenderTargetToTexture(u32 dstAddr, unsigned int dstFormat config.height = scaled_tex_h; config.layers = FramebufferManagerBase::GetEFBLayers(); - entry = AllocateTexture(config); + TCacheEntryBase *entry = AllocateTexture(config); // TODO: Using the wrong dstFormat, dumb... - entry->SetGeneralParameters(dstAddr, 0, dstFormat); + entry->SetGeneralParameters(TextureAddress::Mem(dstAddr), 0, dstFormat); entry->SetDimensions(tex_w, tex_h, 1); entry->SetHashes(TEXHASH_INVALID); entry->frameCount = FRAMECOUNT_INVALID; entry->FromRenderTarget(dstAddr, dstFormat, srcFormat, srcRect, isIntensity, scaleByHalf, cbufid, colmat); + textures[TextureAddress::Mem(dstAddr)] = entry; } TextureCache::TCacheEntryBase* TextureCache::AllocateTexture(const TCacheEntryConfig& config) @@ -828,6 +868,15 @@ TextureCache::TCacheEntryBase* TextureCache::AllocateTexture(const TCacheEntryCo return g_texture_cache->CreateTexture(config); } +void TextureCache::MaybeFreeTexture(TCacheEntryBase* entry) +{ + if (std::find(std::begin(bound_textures), std::end(bound_textures), entry)) + to_free_list.push_back(entry); + else + FreeTexture(entry); +} + + void TextureCache::FreeTexture(TCacheEntryBase* entry) { entry->frameCount = FRAMECOUNT_INVALID; diff --git a/Source/Core/VideoCommon/TextureCacheBase.h b/Source/Core/VideoCommon/TextureCacheBase.h index 1d4ebe9ba7e4..f6a227d86bf2 100644 --- a/Source/Core/VideoCommon/TextureCacheBase.h +++ b/Source/Core/VideoCommon/TextureCacheBase.h @@ -43,13 +43,54 @@ class TextureCache }; }; - + class TextureAddress + { + u32 address1; + u32 address2; + enum AddressKind + { + // A texture in RAM + RAM, + // A texture loaded into TMEM + TMEM, + // A texture in RAM, fully decoded using a palette. + RAM_PALETTE, + // A texture with two TMEM addresses. + // May be either decoded with a palette or an RGBA8 texture with two parts. + DUAL_TMEM, + // Uninitialized address. + INVALID + }; + AddressKind kind; + TextureAddress(u32 a, u32 b, AddressKind k) : address1(a), address2(b), kind(k) {} + public: + TextureAddress() : kind(INVALID), address1(0), address2(0) {} + static TextureAddress Mem(u32 a) { return TextureAddress(a, 0, RAM); } + static TextureAddress MemPalette(u32 a, u32 b) { return TextureAddress(a, b, RAM_PALETTE); } + static TextureAddress TMem(u32 a) { return TextureAddress(a, 0, TMEM); } + static TextureAddress TMem(u32 a, u32 b) { return TextureAddress(a, b, DUAL_TMEM); } + bool operator == (const TextureAddress& b) const + { + return kind == b.kind && address1 == b.address1 && address2 == b.address2; + } + bool operator < (const TextureAddress& b) const + { + if (kind != b.kind) + return kind < b.kind; + if (address1 != b.address1) + return address1 < b.address1; + return address2 < b.address2; + } + bool IsMemOnlyAddress() const { return kind == RAM; } + bool HasMemAddress() const { return kind == RAM || kind == RAM_PALETTE; } + u32 GetMemAddress() const { return address1; } + }; struct TCacheEntryBase { const TCacheEntryConfig config; // common members - u32 addr; + TextureAddress addr; u32 size_in_bytes; u64 hash; u32 format; @@ -61,7 +102,7 @@ class TextureCache int frameCount; - void SetGeneralParameters(u32 _addr, u32 _size, u32 _format) + void SetGeneralParameters(TextureAddress _addr, u32 _size, u32 _format) { addr = _addr; size_in_bytes = _size; @@ -96,6 +137,7 @@ class TextureCache bool OverlapsMemoryRange(u32 range_address, u32 range_size) const; bool IsEfbCopy() { return config.rendertarget; } + bool IsUnrecoverable() { return IsEfbCopy() && addr.IsMemOnlyAddress(); } }; virtual ~TextureCache(); // needs virtual for DX11 dtor @@ -107,9 +149,7 @@ class TextureCache static void Cleanup(int frameCount); static void Invalidate(); - static void InvalidateRange(u32 start_address, u32 size); static void MakeRangeDynamic(u32 start_address, u32 size); - static void ClearRenderTargets(); // currently only used by OGL virtual TCacheEntryBase* CreateTexture(const TCacheEntryConfig& config) = 0; @@ -117,11 +157,15 @@ class TextureCache virtual void DeleteShaders() = 0; // currently only implemented by OGL static TCacheEntryBase* Load(const u32 stage); + static void UnbindTextures(); + static void BindTextures(); static void CopyRenderTargetToTexture(u32 dstAddr, unsigned int dstFormat, PEControl::PixelFormat srcFormat, const EFBRectangle& srcRect, bool isIntensity, bool scaleByHalf); static void RequestInvalidateTextureCache(); + virtual void ConvertTexture(TCacheEntryBase* entry, TCacheEntryBase* unconverted, void* palette, TlutFormat format) = 0; + protected: TextureCache(); @@ -134,12 +178,17 @@ class TextureCache static TCacheEntryBase* AllocateTexture(const TCacheEntryConfig& config); static void FreeTexture(TCacheEntryBase* entry); + static void MaybeFreeTexture(TCacheEntryBase* entry); + + static TCacheEntryBase* ReturnEntry(unsigned int stage, TCacheEntryBase* entry); - typedef std::map TexCache; + typedef std::map TexCache; typedef std::unordered_multimap TexPool; static TexCache textures; static TexPool texture_pool; + static TCacheEntryBase* bound_textures[8]; + static std::vector to_free_list; // Backup configuration values static struct BackupConfig diff --git a/Source/Core/VideoCommon/VertexManagerBase.cpp b/Source/Core/VideoCommon/VertexManagerBase.cpp index 2ebb42122f3a..bf7800cc9ab4 100644 --- a/Source/Core/VideoCommon/VertexManagerBase.cpp +++ b/Source/Core/VideoCommon/VertexManagerBase.cpp @@ -209,6 +209,7 @@ void VertexManager::Flush() if (bpmem.tevind[i].IsActive() && bpmem.tevind[i].bt < bpmem.genMode.numindstages) usedtextures[bpmem.tevindref.getTexMap(bpmem.tevind[i].bt)] = true; + TextureCache::UnbindTextures(); for (unsigned int i : usedtextures) { g_renderer->SetSamplerState(i & 3, i >> 2); @@ -224,6 +225,7 @@ void VertexManager::Flush() ERROR_LOG(VIDEO, "error loading texture"); } } + TextureCache::BindTextures(); } // set global vertex constants