CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
Path: blob/master/GPU/Common/TextureCacheCommon.cpp
Views: 1401
// Copyright (c) 2013- PPSSPP Project.12// This program is free software: you can redistribute it and/or modify3// it under the terms of the GNU General Public License as published by4// the Free Software Foundation, version 2.0 or later versions.56// This program is distributed in the hope that it will be useful,7// but WITHOUT ANY WARRANTY; without even the implied warranty of8// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the9// GNU General Public License 2.0 for more details.1011// A copy of the GPL 2.0 should have been included with the program.12// If not, see http://www.gnu.org/licenses/1314// Official git repository and contact information can be found at15// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/.1617#include "ppsspp_config.h"1819#include <algorithm>2021#include "Common/Common.h"22#include "Common/Data/Convert/ColorConv.h"23#include "Common/Data/Collections/TinySet.h"24#include "Common/Profiler/Profiler.h"25#include "Common/LogReporting.h"26#include "Common/MemoryUtil.h"27#include "Common/StringUtils.h"28#include "Common/TimeUtil.h"29#include "Common/Math/math_util.h"30#include "Common/GPU/thin3d.h"31#include "Core/HDRemaster.h"32#include "Core/Config.h"33#include "Core/Debugger/MemBlockInfo.h"34#include "Core/System.h"35#include "GPU/Common/FramebufferManagerCommon.h"36#include "GPU/Common/TextureCacheCommon.h"37#include "GPU/Common/TextureDecoder.h"38#include "GPU/Common/ShaderId.h"39#include "GPU/Common/GPUStateUtils.h"40#include "GPU/Debugger/Debugger.h"41#include "GPU/Debugger/Record.h"42#include "GPU/GPUCommon.h"43#include "GPU/GPUInterface.h"44#include "GPU/GPUState.h"45#include "Core/Util/PPGeDraw.h"4647#if defined(_M_SSE)48#include <emmintrin.h>49#endif50#if PPSSPP_ARCH(ARM_NEON)51#if defined(_MSC_VER) && PPSSPP_ARCH(ARM64)52#include <arm64_neon.h>53#else54#include <arm_neon.h>55#endif56#endif5758// Videos should be updated every few frames, so we forget quickly.59#define VIDEO_DECIMATE_AGE 46061// If a texture hasn't been seen for this many frames, get rid of it.62#define TEXTURE_KILL_AGE 20063#define TEXTURE_KILL_AGE_LOWMEM 6064// Not used in lowmem mode.65#define TEXTURE_SECOND_KILL_AGE 10066// Used when there are multiple CLUT variants of a texture.67#define TEXTURE_KILL_AGE_CLUT 66869#define TEXTURE_CLUT_VARIANTS_MIN 67071// Try to be prime to other decimation intervals.72#define TEXCACHE_DECIMATION_INTERVAL 137374#define TEXCACHE_MIN_PRESSURE 16 * 1024 * 1024 // Total in VRAM75#define TEXCACHE_SECOND_MIN_PRESSURE 4 * 1024 * 10247677// Just for reference7879// PSP Color formats:80// 565: BBBBBGGGGGGRRRRR81// 5551: ABBBBBGGGGGRRRRR82// 4444: AAAABBBBGGGGRRRR83// 8888: AAAAAAAABBBBBBBBGGGGGGGGRRRRRRRR (Bytes in memory: RGBA)8485// D3D11/9 Color formats:86// DXGI_FORMAT_B4G4R4A4/D3DFMT_A4R4G4B4: AAAARRRRGGGGBBBB87// DXGI_FORMAT_B5G5R5A1/D3DFMT_A1R5G6B5: ARRRRRGGGGGBBBBB88// DXGI_FORMAT_B5G6R6/D3DFMT_R5G6B5: RRRRRGGGGGGBBBBB89// DXGI_FORMAT_B8G8R8A8: AAAAAAAARRRRRRRRGGGGGGGGBBBBBBBB (Bytes in memory: BGRA)90// These are Data::Format:: A4R4G4B4_PACK16, A1R5G6B5_PACK16, R5G6B5_PACK16, B8G8R8A8.91// So these are good matches, just with R/B swapped.9293// OpenGL ES color formats:94// GL_UNSIGNED_SHORT_4444: BBBBGGGGRRRRAAAA (4-bit rotation)95// GL_UNSIGNED_SHORT_565: BBBBBGGGGGGRRRRR (match)96// GL_UNSIGNED_SHORT_1555: BBBBBGGGGGRRRRRA (1-bit rotation)97// GL_UNSIGNED_BYTE/RGBA: AAAAAAAABBBBBBBBGGGGGGGGRRRRRRRR (match)98// These are Data::Format:: B4G4R4A4_PACK16, B5G6R6_PACK16, B5G5R5A1_PACK16, R8G8B8A899100TextureCacheCommon::TextureCacheCommon(Draw::DrawContext *draw, Draw2D *draw2D)101: draw_(draw), draw2D_(draw2D), replacer_(draw) {102decimationCounter_ = TEXCACHE_DECIMATION_INTERVAL;103104// It's only possible to have 1KB of palette entries, although we allow 2KB in a hack.105clutBufRaw_ = (u32 *)AllocateAlignedMemory(2048, 16);106clutBufConverted_ = (u32 *)AllocateAlignedMemory(2048, 16);107// Here we need 2KB to expand a 1KB CLUT.108expandClut_ = (u32 *)AllocateAlignedMemory(2048, 16);109110// Zap so we get consistent behavior if the game fails to load some of the CLUT.111memset(clutBufRaw_, 0, 2048);112memset(clutBufConverted_, 0, 2048);113clutBuf_ = clutBufConverted_;114115// These buffers will grow if necessary, but most won't need more than this.116tmpTexBuf32_.resize(512 * 512); // 1MB117tmpTexBufRearrange_.resize(512 * 512); // 1MB118119textureShaderCache_ = new TextureShaderCache(draw, draw2D_);120}121122TextureCacheCommon::~TextureCacheCommon() {123delete textureShaderCache_;124125FreeAlignedMemory(clutBufConverted_);126FreeAlignedMemory(clutBufRaw_);127FreeAlignedMemory(expandClut_);128}129130void TextureCacheCommon::StartFrame() {131ForgetLastTexture();132textureShaderCache_->Decimate();133timesInvalidatedAllThisFrame_ = 0;134replacementTimeThisFrame_ = 0.0;135136if ((DebugOverlay)g_Config.iDebugOverlay == DebugOverlay::DEBUG_STATS) {137gpuStats.numReplacerTrackedTex = replacer_.GetNumTrackedTextures();138gpuStats.numCachedReplacedTextures = replacer_.GetNumCachedReplacedTextures();139}140141if (texelsScaledThisFrame_) {142VERBOSE_LOG(Log::G3D, "Scaled %d texels", texelsScaledThisFrame_);143}144texelsScaledThisFrame_ = 0;145146if (clearCacheNextFrame_) {147Clear(true);148clearCacheNextFrame_ = false;149} else {150Decimate(nullptr, false);151}152}153154// Produces a signed 1.23.8 value.155static int TexLog2(float delta) {156union FloatBits {157float f;158u32 u;159};160FloatBits f;161f.f = delta;162// Use the exponent as the tex level, and the top mantissa bits for a frac.163// We can't support more than 8 bits of frac, so truncate.164int useful = (f.u >> 15) & 0xFFFF;165// Now offset so the exponent aligns with log2f (exp=127 is 0.)166return useful - 127 * 256;167}168169SamplerCacheKey TextureCacheCommon::GetSamplingParams(int maxLevel, const TexCacheEntry *entry) {170SamplerCacheKey key{};171172int minFilt = gstate.texfilter & 0x7;173key.minFilt = minFilt & 1;174key.mipEnable = (minFilt >> 2) & 1;175key.mipFilt = (minFilt >> 1) & 1;176key.magFilt = gstate.isMagnifyFilteringEnabled();177key.sClamp = gstate.isTexCoordClampedS();178key.tClamp = gstate.isTexCoordClampedT();179key.aniso = false;180key.texture3d = gstate_c.curTextureIs3D;181182GETexLevelMode mipMode = gstate.getTexLevelMode();183bool autoMip = mipMode == GE_TEXLEVEL_MODE_AUTO;184185// TODO: Slope mipmap bias is still not well understood.186float lodBias = (float)gstate.getTexLevelOffset16() * (1.0f / 16.0f);187if (mipMode == GE_TEXLEVEL_MODE_SLOPE) {188lodBias += 1.0f + TexLog2(gstate.getTextureLodSlope()) * (1.0f / 256.0f);189}190191// If mip level is forced to zero, disable mipmapping.192bool noMip = maxLevel == 0 || (!autoMip && lodBias <= 0.0f);193if (noMip) {194// Enforce no mip filtering, for safety.195key.mipEnable = false;196key.mipFilt = 0;197lodBias = 0.0f;198}199200if (!key.mipEnable) {201key.maxLevel = 0;202key.minLevel = 0;203key.lodBias = 0;204key.mipFilt = 0;205} else {206switch (mipMode) {207case GE_TEXLEVEL_MODE_AUTO:208key.maxLevel = maxLevel * 256;209key.minLevel = 0;210key.lodBias = (int)(lodBias * 256.0f);211if (gstate_c.Use(GPU_USE_ANISOTROPY) && g_Config.iAnisotropyLevel > 0) {212key.aniso = true;213}214break;215case GE_TEXLEVEL_MODE_CONST:216case GE_TEXLEVEL_MODE_UNKNOWN:217key.maxLevel = (int)(lodBias * 256.0f);218key.minLevel = (int)(lodBias * 256.0f);219key.lodBias = 0;220break;221case GE_TEXLEVEL_MODE_SLOPE:222// It's incorrect to use the slope as a bias. Instead it should be passed223// into the shader directly as an explicit lod level, with the bias on top. For now, we just kill the224// lodBias in this mode, working around #9772.225key.maxLevel = maxLevel * 256;226key.minLevel = 0;227key.lodBias = 0;228break;229}230}231232// Video bilinear override233if (!key.magFilt && entry != nullptr && IsVideo(entry->addr)) {234// Enforce bilinear filtering on magnification.235key.magFilt = 1;236}237238// Filtering overrides from replacements or settings.239TextureFiltering forceFiltering = TEX_FILTER_AUTO;240bool useReplacerFiltering = false;241if (entry && replacer_.Enabled() && entry->replacedTexture) {242// If replacement textures have multiple mip levels, enforce mip filtering.243if (entry->replacedTexture->State() == ReplacementState::ACTIVE && entry->replacedTexture->NumLevels() > 1) {244key.mipEnable = true;245key.mipFilt = 1;246key.maxLevel = 9 * 256;247if (gstate_c.Use(GPU_USE_ANISOTROPY) && g_Config.iAnisotropyLevel > 0) {248key.aniso = true;249}250}251useReplacerFiltering = entry->replacedTexture->ForceFiltering(&forceFiltering);252}253if (!useReplacerFiltering) {254switch (g_Config.iTexFiltering) {255case TEX_FILTER_AUTO:256// Follow what the game wants. We just do a single heuristic change to avoid bleeding of wacky color test colors257// in higher resolution (used by some games for sprites, and they accidentally have linear filter on).258if (gstate.isModeThrough() && g_Config.iInternalResolution != 1) {259bool uglyColorTest = gstate.isColorTestEnabled() && !IsColorTestTriviallyTrue() && gstate.getColorTestRef() != 0;260if (uglyColorTest)261forceFiltering = TEX_FILTER_FORCE_NEAREST;262}263if (gstate_c.pixelMapped) {264forceFiltering = TEX_FILTER_FORCE_NEAREST;265}266break;267case TEX_FILTER_FORCE_LINEAR:268// Override to linear filtering if there's no alpha or color testing going on.269if ((!gstate.isColorTestEnabled() || IsColorTestTriviallyTrue()) &&270(!gstate.isAlphaTestEnabled() || IsAlphaTestTriviallyTrue())) {271forceFiltering = TEX_FILTER_FORCE_LINEAR;272}273break;274case TEX_FILTER_FORCE_NEAREST:275// Just force to nearest without checks. Safe (but ugly).276forceFiltering = TEX_FILTER_FORCE_NEAREST;277break;278case TEX_FILTER_AUTO_MAX_QUALITY:279default:280forceFiltering = TEX_FILTER_AUTO_MAX_QUALITY;281if (gstate.isModeThrough() && g_Config.iInternalResolution != 1) {282bool uglyColorTest = gstate.isColorTestEnabled() && !IsColorTestTriviallyTrue() && gstate.getColorTestRef() != 0;283if (uglyColorTest)284forceFiltering = TEX_FILTER_FORCE_NEAREST;285}286if (gstate_c.pixelMapped) {287forceFiltering = TEX_FILTER_FORCE_NEAREST;288}289break;290}291}292293switch (forceFiltering) {294case TEX_FILTER_AUTO:295break;296case TEX_FILTER_FORCE_LINEAR:297key.magFilt = 1;298key.minFilt = 1;299key.mipFilt = 1;300break;301case TEX_FILTER_FORCE_NEAREST:302key.magFilt = 0;303key.minFilt = 0;304break;305case TEX_FILTER_AUTO_MAX_QUALITY:306// NOTE: We do not override magfilt here. If a game should have pixellated filtering,307// let it keep it. But we do enforce minification and mipmap filtering and max out the level.308// Later we'll also auto-generate any missing mipmaps.309key.minFilt = 1;310key.mipFilt = 1;311key.maxLevel = 9 * 256;312key.lodBias = 0.0f;313if (gstate_c.Use(GPU_USE_ANISOTROPY) && g_Config.iAnisotropyLevel > 0) {314key.aniso = true;315}316break;317}318319return key;320}321322SamplerCacheKey TextureCacheCommon::GetFramebufferSamplingParams(u16 bufferWidth, u16 bufferHeight) {323SamplerCacheKey key = GetSamplingParams(0, nullptr);324325// In case auto max quality was on, restore min filt. Another fix for water in Outrun.326if (g_Config.iTexFiltering == TEX_FILTER_AUTO_MAX_QUALITY) {327int minFilt = gstate.texfilter & 0x7;328key.minFilt = minFilt & 1;329}330331// Kill any mipmapping settings.332key.mipEnable = false;333key.mipFilt = false;334key.aniso = 0.0f;335key.maxLevel = 0.0f;336key.lodBias = 0.0f;337338// Often the framebuffer will not match the texture size. We'll wrap/clamp in the shader in that case.339int w = gstate.getTextureWidth(0);340int h = gstate.getTextureHeight(0);341if (w != bufferWidth || h != bufferHeight) {342key.sClamp = true;343key.tClamp = true;344}345return key;346}347348void TextureCacheCommon::UpdateMaxSeenV(TexCacheEntry *entry, bool throughMode) {349// If the texture is >= 512 pixels tall...350if (entry->dim >= 0x900) {351if (entry->cluthash != 0 && entry->maxSeenV == 0) {352const u64 cachekeyMin = (u64)(entry->addr & 0x3FFFFFFF) << 32;353const u64 cachekeyMax = cachekeyMin + (1ULL << 32);354for (auto it = cache_.lower_bound(cachekeyMin), end = cache_.upper_bound(cachekeyMax); it != end; ++it) {355// They should all be the same, just make sure we take any that has already increased.356// This is for a new texture.357if (it->second->maxSeenV != 0) {358entry->maxSeenV = it->second->maxSeenV;359break;360}361}362}363364// Texture scale/offset and gen modes don't apply in through.365// So we can optimize how much of the texture we look at.366if (throughMode) {367if (entry->maxSeenV == 0 && gstate_c.vertBounds.maxV > 0) {368// Let's not hash less than 272, we might use more later and have to rehash. 272 is very common.369entry->maxSeenV = std::max((u16)272, gstate_c.vertBounds.maxV);370} else if (gstate_c.vertBounds.maxV > entry->maxSeenV) {371// The max height changed, so we're better off hashing the entire thing.372entry->maxSeenV = 512;373entry->status |= TexCacheEntry::STATUS_FREE_CHANGE;374}375} else {376// Otherwise, we need to reset to ensure we use the whole thing.377// Can't tell how much is used.378// TODO: We could tell for texcoord UV gen, and apply scale to max?379entry->maxSeenV = 512;380}381382// We need to keep all CLUT variants in sync so we detect changes properly.383// See HandleTextureChange / STATUS_CLUT_RECHECK.384if (entry->cluthash != 0) {385const u64 cachekeyMin = (u64)(entry->addr & 0x3FFFFFFF) << 32;386const u64 cachekeyMax = cachekeyMin + (1ULL << 32);387for (auto it = cache_.lower_bound(cachekeyMin), end = cache_.upper_bound(cachekeyMax); it != end; ++it) {388it->second->maxSeenV = entry->maxSeenV;389}390}391}392}393394TexCacheEntry *TextureCacheCommon::SetTexture() {395u8 level = 0;396if (IsFakeMipmapChange()) {397level = std::max(0, gstate.getTexLevelOffset16() / 16);398}399u32 texaddr = gstate.getTextureAddress(level);400if (!Memory::IsValidAddress(texaddr)) {401// Bind a null texture and return.402Unbind();403gstate_c.SetTextureIsVideo(false);404gstate_c.SetTextureIs3D(false);405gstate_c.SetTextureIsArray(false);406gstate_c.SetTextureIsFramebuffer(false);407return nullptr;408}409410const u16 dim = gstate.getTextureDimension(level);411int w = gstate.getTextureWidth(level);412int h = gstate.getTextureHeight(level);413414GETextureFormat texFormat = gstate.getTextureFormat();415if (texFormat >= 11) {416// TODO: Better assumption? Doesn't really matter, these are invalid.417texFormat = GE_TFMT_5650;418}419420bool hasClut = gstate.isTextureFormatIndexed();421bool hasClutGPU = false;422u32 cluthash;423if (hasClut) {424if (clutRenderAddress_ != 0xFFFFFFFF) {425gstate_c.curTextureXOffset = 0.0f;426gstate_c.curTextureYOffset = 0.0f;427hasClutGPU = true;428cluthash = 0; // Or should we use some other marker value?429} else {430if (clutLastFormat_ != gstate.clutformat) {431// We update here because the clut format can be specified after the load.432// TODO: Unify this as far as possible (I think only GLES backend really needs its own implementation due to different component order).433UpdateCurrentClut(gstate.getClutPaletteFormat(), gstate.getClutIndexStartPos(), gstate.isClutIndexSimple());434}435cluthash = clutHash_ ^ gstate.clutformat;436}437} else {438cluthash = 0;439}440u64 cachekey = TexCacheEntry::CacheKey(texaddr, texFormat, dim, cluthash);441442int bufw = GetTextureBufw(0, texaddr, texFormat);443u8 maxLevel = gstate.getTextureMaxLevel();444445u32 minihash = MiniHash((const u32 *)Memory::GetPointerUnchecked(texaddr));446447TexCache::iterator entryIter = cache_.find(cachekey);448TexCacheEntry *entry = nullptr;449450// Note: It's necessary to reset needshadertexclamp, for otherwise DIRTY_TEXCLAMP won't get set later.451// Should probably revisit how this works..452gstate_c.SetNeedShaderTexclamp(false);453gstate_c.skipDrawReason &= ~SKIPDRAW_BAD_FB_TEXTURE;454455if (entryIter != cache_.end()) {456entry = entryIter->second.get();457458// Validate the texture still matches the cache entry.459bool match = entry->Matches(dim, texFormat, maxLevel);460const char *reason = "different params";461462// Check for dynamic CLUT status463if (((entry->status & TexCacheEntry::STATUS_CLUT_GPU) != 0) != hasClutGPU) {464// Need to recreate, suddenly a CLUT GPU texture was used without it, or vice versa.465// I think this can only happen on a clut hash collision with the marker value, so highly unlikely.466match = false;467}468469// Check for FBO changes.470if (entry->status & TexCacheEntry::STATUS_FRAMEBUFFER_OVERLAP) {471// Fall through to the end where we'll delete the entry if there's a framebuffer.472entry->status &= ~TexCacheEntry::STATUS_FRAMEBUFFER_OVERLAP;473match = false;474}475476bool rehash = entry->GetHashStatus() == TexCacheEntry::STATUS_UNRELIABLE;477478// First let's see if another texture with the same address had a hashfail.479if (entry->status & TexCacheEntry::STATUS_CLUT_RECHECK) {480// Always rehash in this case, if one changed the rest all probably did.481rehash = true;482entry->status &= ~TexCacheEntry::STATUS_CLUT_RECHECK;483} else if (!gstate_c.IsDirty(DIRTY_TEXTURE_IMAGE)) {484// Okay, just some parameter change - the data didn't change, no need to rehash.485rehash = false;486}487488// Do we need to recreate?489if (entry->status & TexCacheEntry::STATUS_FORCE_REBUILD) {490match = false;491entry->status &= ~TexCacheEntry::STATUS_FORCE_REBUILD;492}493494if (match) {495if (entry->lastFrame != gpuStats.numFlips) {496u32 diff = gpuStats.numFlips - entry->lastFrame;497entry->numFrames++;498499if (entry->framesUntilNextFullHash < diff) {500// Exponential backoff up to 512 frames. Textures are often reused.501if (entry->numFrames > 32) {502// Also, try to add some "randomness" to avoid rehashing several textures the same frame.503// textureName is unioned with texturePtr and vkTex so will work for the other backends.504entry->framesUntilNextFullHash = std::min(512, entry->numFrames) + (((intptr_t)(entry->textureName) >> 12) & 15);505} else {506entry->framesUntilNextFullHash = entry->numFrames;507}508rehash = true;509} else {510entry->framesUntilNextFullHash -= diff;511}512}513514// If it's not huge or has been invalidated many times, recheck the whole texture.515if (entry->invalidHint > 180 || (entry->invalidHint > 15 && (dim >> 8) < 9 && (dim & 0xF) < 9)) {516entry->invalidHint = 0;517rehash = true;518}519520if (minihash != entry->minihash) {521match = false;522reason = "minihash";523} else if (entry->GetHashStatus() == TexCacheEntry::STATUS_RELIABLE) {524rehash = false;525}526}527528if (match && (entry->status & TexCacheEntry::STATUS_TO_SCALE) && standardScaleFactor_ != 1 && texelsScaledThisFrame_ < TEXCACHE_MAX_TEXELS_SCALED) {529if ((entry->status & TexCacheEntry::STATUS_CHANGE_FREQUENT) == 0) {530// INFO_LOG(Log::G3D, "Reloading texture to do the scaling we skipped..");531match = false;532reason = "scaling";533}534}535536if (match && (entry->status & TexCacheEntry::STATUS_TO_REPLACE) && replacementTimeThisFrame_ < replacementFrameBudget_) {537int w0 = gstate.getTextureWidth(0);538int h0 = gstate.getTextureHeight(0);539int d0 = 1;540if (entry->replacedTexture) {541PollReplacement(entry, &w0, &h0, &d0);542// This texture is pending a replacement load.543// So check the replacer if it's reached a conclusion.544switch (entry->replacedTexture->State()) {545case ReplacementState::NOT_FOUND:546// Didn't find a replacement, so stop looking.547// DEBUG_LOG(Log::G3D, "No replacement for texture %dx%d", w0, h0);548entry->status &= ~TexCacheEntry::STATUS_TO_REPLACE;549if (g_Config.bSaveNewTextures) {550// Load it once more to actually save it. Since we don't set STATUS_TO_REPLACE, we won't end up looping.551match = false;552reason = "replacing";553}554break;555case ReplacementState::ACTIVE:556// There is now replacement data available!557// Just reload the texture to process the replacement.558match = false;559reason = "replacing";560break;561default:562// We'll just wait for a result.563break;564}565}566}567568if (match) {569// got one!570gstate_c.curTextureWidth = w;571gstate_c.curTextureHeight = h;572gstate_c.SetTextureIsVideo(false);573gstate_c.SetTextureIs3D((entry->status & TexCacheEntry::STATUS_3D) != 0);574gstate_c.SetTextureIsArray(false);575gstate_c.SetTextureIsBGRA((entry->status & TexCacheEntry::STATUS_BGRA) != 0);576gstate_c.SetTextureIsFramebuffer(false);577578if (rehash) {579// Update in case any of these changed.580entry->bufw = bufw;581entry->cluthash = cluthash;582}583584nextTexture_ = entry;585nextNeedsRehash_ = rehash;586nextNeedsChange_ = false;587// Might need a rebuild if the hash fails, but that will be set later.588nextNeedsRebuild_ = false;589failedTexture_ = false;590VERBOSE_LOG(Log::G3D, "Texture at %08x found in cache, applying", texaddr);591return entry; //Done!592} else {593// Wasn't a match, we will rebuild.594nextChangeReason_ = reason;595nextNeedsChange_ = true;596// Fall through to the rebuild case.597}598}599600// No texture found, or changed (depending on entry).601// Check for framebuffers.602603TextureDefinition def{};604def.addr = texaddr;605def.dim = dim;606def.format = texFormat;607def.bufw = bufw;608609AttachCandidate bestCandidate;610if (GetBestFramebufferCandidate(def, 0, &bestCandidate)) {611// If we had a texture entry here, let's get rid of it.612if (entryIter != cache_.end()) {613DeleteTexture(entryIter);614}615616nextTexture_ = nullptr;617nextNeedsRebuild_ = false;618619SetTextureFramebuffer(bestCandidate); // sets curTexture3D620return nullptr;621}622623// Didn't match a framebuffer, keep going.624625if (!entry) {626VERBOSE_LOG(Log::G3D, "No texture in cache for %08x, decoding...", texaddr);627entry = new TexCacheEntry{};628cache_[cachekey].reset(entry);629630if (PPGeIsFontTextureAddress(texaddr)) {631// It's the builtin font texture.632entry->status = TexCacheEntry::STATUS_RELIABLE;633} else if (g_Config.bTextureBackoffCache && !IsVideo(texaddr)) {634entry->status = TexCacheEntry::STATUS_HASHING;635} else {636entry->status = TexCacheEntry::STATUS_UNRELIABLE;637}638639if (hasClutGPU) {640WARN_LOG_N_TIMES(clutUseRender, 5, Log::G3D, "Using texture with dynamic CLUT: texfmt=%d, clutfmt=%d", gstate.getTextureFormat(), gstate.getClutPaletteFormat());641entry->status |= TexCacheEntry::STATUS_CLUT_GPU;642}643644if (hasClut && clutRenderAddress_ == 0xFFFFFFFF) {645const u64 cachekeyMin = (u64)(texaddr & 0x3FFFFFFF) << 32;646const u64 cachekeyMax = cachekeyMin + (1ULL << 32);647648int found = 0;649for (auto it = cache_.lower_bound(cachekeyMin), end = cache_.upper_bound(cachekeyMax); it != end; ++it) {650found++;651}652653if (found >= TEXTURE_CLUT_VARIANTS_MIN) {654for (auto it = cache_.lower_bound(cachekeyMin), end = cache_.upper_bound(cachekeyMax); it != end; ++it) {655it->second->status |= TexCacheEntry::STATUS_CLUT_VARIANTS;656}657658entry->status |= TexCacheEntry::STATUS_CLUT_VARIANTS;659}660}661662nextNeedsChange_ = false;663}664665// We have to decode it, let's setup the cache entry first.666entry->addr = texaddr;667entry->minihash = minihash;668entry->dim = dim;669entry->format = texFormat;670entry->maxLevel = maxLevel;671entry->status &= ~TexCacheEntry::STATUS_BGRA;672673entry->bufw = bufw;674675entry->cluthash = cluthash;676677gstate_c.curTextureWidth = w;678gstate_c.curTextureHeight = h;679gstate_c.SetTextureIsVideo(false);680gstate_c.SetTextureIs3D((entry->status & TexCacheEntry::STATUS_3D) != 0);681gstate_c.SetTextureIsArray(false); // Ordinary 2D textures still aren't used by array view in VK. We probably might as well, though, at this point..682gstate_c.SetTextureIsFramebuffer(false);683684failedTexture_ = false;685nextTexture_ = entry;686nextFramebufferTexture_ = nullptr;687nextNeedsRehash_ = true;688// We still need to rebuild, to allocate a texture. But we'll bail early.689nextNeedsRebuild_ = true;690return entry;691}692693bool TextureCacheCommon::GetBestFramebufferCandidate(const TextureDefinition &entry, u32 texAddrOffset, AttachCandidate *bestCandidate) const {694gpuStats.numFramebufferEvaluations++;695696TinySet<AttachCandidate, 6> candidates;697698const std::vector<VirtualFramebuffer *> &framebuffers = framebufferManager_->Framebuffers();699700for (VirtualFramebuffer *framebuffer : framebuffers) {701FramebufferMatchInfo match{};702if (MatchFramebuffer(entry, framebuffer, texAddrOffset, RASTER_COLOR, &match)) {703candidates.push_back(AttachCandidate{ framebuffer, match, RASTER_COLOR });704}705match = {};706if (MatchFramebuffer(entry, framebuffer, texAddrOffset, RASTER_DEPTH, &match)) {707candidates.push_back(AttachCandidate{ framebuffer, match, RASTER_DEPTH });708}709}710711if (candidates.size() == 0) {712return false;713} else if (candidates.size() == 1) {714*bestCandidate = candidates[0];715return true;716}717718bool logging = Reporting::ShouldLogNTimes("multifbcandidate", 5);719720// OK, multiple possible candidates. Will need to figure out which one is the most relevant.721int bestRelevancy = -1;722size_t bestIndex = -1;723724bool kzCompat = PSP_CoreParameter().compat.flags().SplitFramebufferMargin;725726// We simply use the sequence counter as relevancy nowadays.727for (size_t i = 0; i < candidates.size(); i++) {728AttachCandidate &candidate = candidates[i];729int relevancy = candidate.channel == RASTER_COLOR ? candidate.fb->colorBindSeq : candidate.fb->depthBindSeq;730731// Add a small negative penalty if the texture is currently bound as a framebuffer, and offset is not zero.732// Should avoid problems when pingponging two nearby buffers, like in Wipeout Pure in #15927.733if (candidate.channel == RASTER_COLOR &&734(candidate.match.yOffset != 0 || candidate.match.xOffset != 0) &&735candidate.fb->fb_address == (gstate.getFrameBufRawAddress() | 0x04000000)) {736relevancy -= 2;737}738739if (candidate.match.xOffset != 0 && PSP_CoreParameter().compat.flags().DisallowFramebufferAtOffset) {740continue;741}742743// Avoid binding as texture the framebuffer we're rendering to.744// In Killzone, we split the framebuffer but the matching algorithm can still pick the wrong one,745// which this avoids completely.746if (kzCompat && candidate.fb == framebufferManager_->GetCurrentRenderVFB()) {747continue;748}749750if (logging) {751candidate.relevancy = relevancy;752}753754if (relevancy > bestRelevancy) {755bestRelevancy = relevancy;756bestIndex = i;757}758}759760if (logging) {761std::string cands;762for (size_t i = 0; i < candidates.size(); i++) {763cands += candidates[i].ToString();764if (i != candidates.size() - 1)765cands += "\n";766}767cands += "\n";768769WARN_LOG(Log::G3D, "GetFramebufferCandidates(tex): Multiple (%d) candidate framebuffers. texaddr: %08x offset: %d (%dx%d stride %d, %s):\n%s",770(int)candidates.size(),771entry.addr, texAddrOffset, dimWidth(entry.dim), dimHeight(entry.dim), entry.bufw, GeTextureFormatToString(entry.format),772cands.c_str()773);774logging = true;775}776777if (bestIndex != -1) {778if (logging) {779WARN_LOG(Log::G3D, "Chose candidate %d:\n%s\n", (int)bestIndex, candidates[bestIndex].ToString().c_str());780}781*bestCandidate = candidates[bestIndex];782return true;783} else {784return false;785}786}787788// Removes old textures.789void TextureCacheCommon::Decimate(TexCacheEntry *exceptThisOne, bool forcePressure) {790if (--decimationCounter_ <= 0) {791decimationCounter_ = TEXCACHE_DECIMATION_INTERVAL;792} else {793return;794}795796if (forcePressure || cacheSizeEstimate_ >= TEXCACHE_MIN_PRESSURE) {797const u32 had = cacheSizeEstimate_;798799ForgetLastTexture();800int killAgeBase = lowMemoryMode_ ? TEXTURE_KILL_AGE_LOWMEM : TEXTURE_KILL_AGE;801for (TexCache::iterator iter = cache_.begin(); iter != cache_.end(); ) {802if (iter->second.get() == exceptThisOne) {803++iter;804continue;805}806bool hasClut = (iter->second->status & TexCacheEntry::STATUS_CLUT_VARIANTS) != 0;807int killAge = hasClut ? TEXTURE_KILL_AGE_CLUT : killAgeBase;808if (iter->second->lastFrame + killAge < gpuStats.numFlips) {809DeleteTexture(iter++);810} else {811++iter;812}813}814815VERBOSE_LOG(Log::G3D, "Decimated texture cache, saved %d estimated bytes - now %d bytes", had - cacheSizeEstimate_, cacheSizeEstimate_);816}817818// If enabled, we also need to clear the secondary cache.819if (PSP_CoreParameter().compat.flags().SecondaryTextureCache && (forcePressure || secondCacheSizeEstimate_ >= TEXCACHE_SECOND_MIN_PRESSURE)) {820const u32 had = secondCacheSizeEstimate_;821822for (TexCache::iterator iter = secondCache_.begin(); iter != secondCache_.end(); ) {823if (iter->second.get() == exceptThisOne) {824++iter;825continue;826}827// In low memory mode, we kill them all since secondary cache is disabled.828if (lowMemoryMode_ || iter->second->lastFrame + TEXTURE_SECOND_KILL_AGE < gpuStats.numFlips) {829ReleaseTexture(iter->second.get(), true);830secondCacheSizeEstimate_ -= EstimateTexMemoryUsage(iter->second.get());831secondCache_.erase(iter++);832} else {833++iter;834}835}836837VERBOSE_LOG(Log::G3D, "Decimated second texture cache, saved %d estimated bytes - now %d bytes", had - secondCacheSizeEstimate_, secondCacheSizeEstimate_);838}839840DecimateVideos();841replacer_.Decimate(forcePressure ? ReplacerDecimateMode::FORCE_PRESSURE : ReplacerDecimateMode::NEW_FRAME);842}843844void TextureCacheCommon::DecimateVideos() {845for (auto iter = videos_.begin(); iter != videos_.end(); ) {846if (iter->flips + VIDEO_DECIMATE_AGE < gpuStats.numFlips) {847iter = videos_.erase(iter++);848} else {849++iter;850}851}852}853854bool TextureCacheCommon::IsVideo(u32 texaddr) const {855texaddr &= 0x3FFFFFFF;856for (auto &info : videos_) {857if (texaddr < info.addr) {858continue;859}860if (texaddr < info.addr + info.size) {861return true;862}863}864return false;865}866867void TextureCacheCommon::HandleTextureChange(TexCacheEntry *const entry, const char *reason, bool initialMatch, bool doDelete) {868cacheSizeEstimate_ -= EstimateTexMemoryUsage(entry);869entry->numInvalidated++;870gpuStats.numTextureInvalidations++;871DEBUG_LOG(Log::G3D, "Texture different or overwritten, reloading at %08x: %s", entry->addr, reason);872if (doDelete) {873ForgetLastTexture();874ReleaseTexture(entry, true);875entry->status &= ~(TexCacheEntry::STATUS_IS_SCALED_OR_REPLACED | TexCacheEntry::STATUS_TO_REPLACE);876}877878// Mark as hashing, if marked as reliable.879if (entry->GetHashStatus() == TexCacheEntry::STATUS_RELIABLE) {880entry->SetHashStatus(TexCacheEntry::STATUS_HASHING);881}882883// Also, mark any textures with the same address but different clut. They need rechecking.884if (entry->cluthash != 0) {885const u64 cachekeyMin = (u64)(entry->addr & 0x3FFFFFFF) << 32;886const u64 cachekeyMax = cachekeyMin + (1ULL << 32);887for (auto it = cache_.lower_bound(cachekeyMin), end = cache_.upper_bound(cachekeyMax); it != end; ++it) {888if (it->second->cluthash != entry->cluthash) {889it->second->status |= TexCacheEntry::STATUS_CLUT_RECHECK;890}891}892}893894if (entry->numFrames < TEXCACHE_FRAME_CHANGE_FREQUENT) {895if (entry->status & TexCacheEntry::STATUS_FREE_CHANGE) {896entry->status &= ~TexCacheEntry::STATUS_FREE_CHANGE;897} else {898entry->status |= TexCacheEntry::STATUS_CHANGE_FREQUENT;899}900}901entry->numFrames = 0;902}903904void TextureCacheCommon::NotifyFramebuffer(VirtualFramebuffer *framebuffer, FramebufferNotification msg) {905const u32 fb_addr = framebuffer->fb_address;906const u32 z_addr = framebuffer->z_address;907908const u32 fb_bpp = BufferFormatBytesPerPixel(framebuffer->fb_format);909const u32 z_bpp = 2; // No other format exists.910const u32 fb_stride = framebuffer->fb_stride;911const u32 z_stride = framebuffer->z_stride;912913// NOTE: Some games like Burnout massively misdetects the height of some framebuffers, leading to a lot of unnecessary invalidations.914// Let's only actually get rid of textures that cover the very start of the framebuffer.915const u32 fb_endAddr = fb_addr + fb_stride * std::min((int)framebuffer->height, 16) * fb_bpp;916const u32 z_endAddr = z_addr + z_stride * std::min((int)framebuffer->height, 16) * z_bpp;917918switch (msg) {919case NOTIFY_FB_CREATED:920case NOTIFY_FB_UPDATED:921{922// Try to match the new framebuffer to existing textures.923// Backwards from the "usual" texturing case so can't share a utility function.924925u64 cacheKey = (u64)fb_addr << 32;926// If it has a clut, those are the low 32 bits, so it'll be inside this range.927// Also, if it's a subsample of the buffer, it'll also be within the FBO.928u64 cacheKeyEnd = (u64)fb_endAddr << 32;929930// Color - no need to look in the mirrors.931for (auto it = cache_.lower_bound(cacheKey), end = cache_.upper_bound(cacheKeyEnd); it != end; ++it) {932it->second->status |= TexCacheEntry::STATUS_FRAMEBUFFER_OVERLAP;933gpuStats.numTextureInvalidationsByFramebuffer++;934}935936if (z_stride != 0) {937// Depth. Just look at the range, but in each mirror (0x04200000 and 0x04600000).938// Games don't use 0x04400000 as far as I know - it has no swizzle effect so kinda useless.939cacheKey = (u64)z_addr << 32;940cacheKeyEnd = (u64)z_endAddr << 32;941for (auto it = cache_.lower_bound(cacheKey | 0x200000), end = cache_.upper_bound(cacheKeyEnd | 0x200000); it != end; ++it) {942it->second->status |= TexCacheEntry::STATUS_FRAMEBUFFER_OVERLAP;943gpuStats.numTextureInvalidationsByFramebuffer++;944}945for (auto it = cache_.lower_bound(cacheKey | 0x600000), end = cache_.upper_bound(cacheKeyEnd | 0x600000); it != end; ++it) {946it->second->status |= TexCacheEntry::STATUS_FRAMEBUFFER_OVERLAP;947gpuStats.numTextureInvalidationsByFramebuffer++;948}949}950break;951}952default:953break;954}955}956957bool TextureCacheCommon::MatchFramebuffer(958const TextureDefinition &entry,959VirtualFramebuffer *framebuffer, u32 texaddrOffset, RasterChannel channel, FramebufferMatchInfo *matchInfo) const {960static const u32 MAX_SUBAREA_Y_OFFSET_SAFE = 32;961962uint32_t fb_address = channel == RASTER_DEPTH ? framebuffer->z_address : framebuffer->fb_address;963uint32_t fb_stride = channel == RASTER_DEPTH ? framebuffer->z_stride : framebuffer->fb_stride;964GEBufferFormat fb_format = channel == RASTER_DEPTH ? GE_FORMAT_DEPTH16 : framebuffer->fb_format;965966if (channel == RASTER_DEPTH && (framebuffer->z_address == framebuffer->fb_address || framebuffer->z_address == 0)) {967// Try to avoid silly matches to somewhat malformed buffers.968return false;969}970971if (!fb_stride) {972// Hard to make decisions.973return false;974}975976switch (entry.format) {977case GE_TFMT_DXT1:978case GE_TFMT_DXT3:979case GE_TFMT_DXT5:980return false;981default: break;982}983984uint32_t fb_stride_in_bytes = fb_stride * BufferFormatBytesPerPixel(fb_format);985uint32_t tex_stride_in_bytes = entry.bufw * textureBitsPerPixel[entry.format] / 8; // Note, we're looking up bits here so need to divide by 8.986987u32 addr = fb_address;988u32 texaddr = entry.addr + texaddrOffset;989990bool texInVRAM = Memory::IsVRAMAddress(texaddr);991bool fbInVRAM = Memory::IsVRAMAddress(fb_address);992993if (texInVRAM != fbInVRAM) {994// Shortcut. Cannot possibly be a match.995return false;996}997998if (texInVRAM) {999const u32 mirrorMask = 0x041FFFFF;10001001addr &= mirrorMask;1002texaddr &= mirrorMask;1003}10041005const bool noOffset = texaddr == addr;1006const bool exactMatch = noOffset && entry.format < 4 && channel == RASTER_COLOR && fb_stride_in_bytes == tex_stride_in_bytes;10071008const u32 texWidth = 1 << ((entry.dim >> 0) & 0xf);1009const u32 texHeight = 1 << ((entry.dim >> 8) & 0xf);10101011// 512 on a 272 framebuffer is sane, so let's be lenient.1012const u32 minSubareaHeight = texHeight / 4;10131014// If they match "exactly", it's non-CLUT and from the top left.1015if (exactMatch) {1016// NOTE: This check is okay because the first texture formats are the same as the buffer formats.1017if (IsTextureFormatBufferCompatible(entry.format)) {1018if (TextureFormatMatchesBufferFormat(entry.format, fb_format) || (framebuffer->usageFlags & FB_USAGE_BLUE_TO_ALPHA)) {1019return true;1020} else {1021WARN_LOG_ONCE(diffFormat1, Log::G3D, "Found matching framebuffer with reinterpretable fb_format: %s != %s at %08x", GeTextureFormatToString(entry.format), GeBufferFormatToString(fb_format), fb_address);1022*matchInfo = FramebufferMatchInfo{ 0, 0, true, TextureFormatToBufferFormat(entry.format) };1023return true;1024}1025} else {1026// Format incompatible, ignoring without comment. (maybe some really gnarly hacks will end up here...)1027return false;1028}1029} else {1030// Apply to buffered mode only.1031if (!framebufferManager_->UseBufferedRendering()) {1032return false;1033}10341035// Check works for D16 too.1036// These are combinations that we have special-cased handling for. There are more1037// ones possible, but rare - we'll add them as we find them used.1038const bool matchingClutFormat =1039(fb_format == GE_FORMAT_DEPTH16 && entry.format == GE_TFMT_CLUT16) ||1040(fb_format == GE_FORMAT_DEPTH16 && entry.format == GE_TFMT_5650) ||1041(fb_format == GE_FORMAT_8888 && entry.format == GE_TFMT_CLUT32) ||1042(fb_format != GE_FORMAT_8888 && entry.format == GE_TFMT_CLUT16) ||1043(fb_format == GE_FORMAT_8888 && entry.format == GE_TFMT_CLUT8) ||1044(fb_format == GE_FORMAT_5551 && entry.format == GE_TFMT_CLUT8 && PSP_CoreParameter().compat.flags().SOCOMClut8Replacement);10451046const int texBitsPerPixel = TextureFormatBitsPerPixel(entry.format);1047const int byteOffset = texaddr - addr;1048if (byteOffset > 0) {1049int texbpp = texBitsPerPixel;1050if (fb_format == GE_FORMAT_5551 && entry.format == GE_TFMT_CLUT8) {1051// In this case we treat CLUT8 as if it were CLUT16, see issue #16210. So we need1052// to compute the x offset appropriately.1053texbpp = 16;1054}10551056matchInfo->yOffset = byteOffset / fb_stride_in_bytes;1057matchInfo->xOffset = 8 * (byteOffset % fb_stride_in_bytes) / texbpp;1058} else if (byteOffset < 0) {1059int texelOffset = 8 * byteOffset / texBitsPerPixel;1060// We don't support negative Y offsets, and negative X offsets are only for the Killzone workaround.1061if (texelOffset < -(int)entry.bufw || !PSP_CoreParameter().compat.flags().SplitFramebufferMargin) {1062return false;1063}1064matchInfo->xOffset = entry.bufw == 0 ? 0 : -(-texelOffset % (int)entry.bufw);1065}10661067if (matchInfo->yOffset > 0 && matchInfo->yOffset + minSubareaHeight >= framebuffer->height) {1068// Can't be inside the framebuffer.1069return false;1070}10711072// Check if it's in bufferWidth (which might be higher than width and may indicate the framebuffer includes the data.)1073// Do the computation in bytes so that it's valid even in case of weird reinterpret scenarios.1074const int xOffsetInBytes = matchInfo->xOffset * 8 / texBitsPerPixel;1075const int texWidthInBytes = texWidth * 8 / texBitsPerPixel;1076if (xOffsetInBytes >= framebuffer->BufferWidthInBytes() && xOffsetInBytes + texWidthInBytes <= (int)fb_stride_in_bytes) {1077// This happens in Brave Story, see #10045 - the texture is in the space between strides, with matching stride.1078return false;1079}10801081// Trying to play it safe. Below 0x04110000 is almost always framebuffers.1082// TODO: Maybe we can reduce this check and find a better way above 0x04110000?1083if (matchInfo->yOffset > MAX_SUBAREA_Y_OFFSET_SAFE && addr > 0x04110000 && !PSP_CoreParameter().compat.flags().AllowLargeFBTextureOffsets) {1084WARN_LOG_ONCE(subareaIgnored, Log::G3D, "Ignoring possible texturing from framebuffer at %08x +%dx%d / %dx%d", fb_address, matchInfo->xOffset, matchInfo->yOffset, framebuffer->width, framebuffer->height);1085return false;1086}10871088// Note the check for texHeight - we really don't care about a stride mismatch if texHeight == 1.1089// This also takes care of the 4x1 texture check we used to have here for Burnout Dominator.1090if (fb_stride_in_bytes != tex_stride_in_bytes && texHeight > 1) {1091// Probably irrelevant.1092return false;1093}10941095// Check for CLUT. The framebuffer is always RGB, but it can be interpreted as a CLUT texture.1096// 3rd Birthday (and a bunch of other games) render to a 16 bit clut texture.1097if (matchingClutFormat) {1098if (!noOffset) {1099WARN_LOG_ONCE(subareaClut, Log::G3D, "Matching framebuffer (%s) using %s with offset at %08x +%dx%d", RasterChannelToString(channel), GeTextureFormatToString(entry.format), fb_address, matchInfo->xOffset, matchInfo->yOffset);1100}1101return true;1102} else if (IsClutFormat((GETextureFormat)(entry.format)) || IsDXTFormat((GETextureFormat)(entry.format))) {1103WARN_LOG_ONCE(fourEightBit, Log::G3D, "%s texture format not matching framebuffer of format %s at %08x/%d", GeTextureFormatToString(entry.format), GeBufferFormatToString(fb_format), fb_address, fb_stride);1104return false;1105}11061107// This is either normal or we failed to generate a shader to depalettize1108if ((int)fb_format == (int)entry.format || matchingClutFormat) {1109if ((int)fb_format != (int)entry.format) {1110WARN_LOG_ONCE(diffFormat2, Log::G3D, "Matching framebuffer with different formats %s != %s at %08x",1111GeTextureFormatToString(entry.format), GeBufferFormatToString(fb_format), fb_address);1112return true;1113} else {1114WARN_LOG_ONCE(subarea, Log::G3D, "Matching from framebuffer at %08x +%dx%d", fb_address, matchInfo->xOffset, matchInfo->yOffset);1115return true;1116}1117} else {1118WARN_LOG_ONCE(diffFormat2, Log::G3D, "Ignoring possible texturing from framebuffer at %08x with incompatible format %s != %s (+%dx%d)",1119fb_address, GeTextureFormatToString(entry.format), GeBufferFormatToString(fb_format), matchInfo->xOffset, matchInfo->yOffset);1120return false;1121}1122}1123}11241125void TextureCacheCommon::SetTextureFramebuffer(const AttachCandidate &candidate) {1126VirtualFramebuffer *framebuffer = candidate.fb;1127RasterChannel channel = candidate.channel;11281129if (candidate.match.reinterpret) {1130framebuffer = framebufferManager_->ResolveFramebufferColorToFormat(candidate.fb, candidate.match.reinterpretTo);1131}11321133_dbg_assert_msg_(framebuffer != nullptr, "Framebuffer must not be null.");11341135framebuffer->usageFlags |= FB_USAGE_TEXTURE;1136// Keep the framebuffer alive.1137framebuffer->last_frame_used = gpuStats.numFlips;11381139nextFramebufferTextureChannel_ = RASTER_COLOR;11401141if (framebufferManager_->UseBufferedRendering()) {1142FramebufferMatchInfo fbInfo = candidate.match;1143// Detect when we need to apply the horizontal texture swizzle.1144u64 depthUpperBits = (channel == RASTER_DEPTH && framebuffer->fb_format == GE_FORMAT_8888) ? ((gstate.getTextureAddress(0) & 0x600000) >> 20) : 0;1145bool needsDepthXSwizzle = depthUpperBits == 2;11461147// We need to force it, since we may have set it on a texture before attaching.1148int texWidth = framebuffer->bufferWidth;1149int texHeight = framebuffer->bufferHeight;1150if (candidate.channel == RASTER_COLOR && gstate.getTextureFormat() == GE_TFMT_CLUT8 && framebuffer->fb_format == GE_FORMAT_5551 && PSP_CoreParameter().compat.flags().SOCOMClut8Replacement) {1151// See #16210. UV must be adjusted as if the texture was twice the width.1152texWidth *= 2.0f;1153}11541155if (needsDepthXSwizzle) {1156texWidth = RoundUpToPowerOf2(texWidth);1157}11581159gstate_c.curTextureWidth = texWidth;1160gstate_c.curTextureHeight = texHeight;1161gstate_c.SetTextureIsFramebuffer(true);1162gstate_c.SetTextureIsBGRA(false);11631164if ((gstate_c.curTextureXOffset == 0) != (fbInfo.xOffset == 0) || (gstate_c.curTextureYOffset == 0) != (fbInfo.yOffset == 0)) {1165gstate_c.Dirty(DIRTY_FRAGMENTSHADER_STATE);1166}11671168gstate_c.curTextureXOffset = fbInfo.xOffset;1169gstate_c.curTextureYOffset = fbInfo.yOffset;1170u32 texW = (u32)gstate.getTextureWidth(0);1171u32 texH = (u32)gstate.getTextureHeight(0);1172gstate_c.SetNeedShaderTexclamp(gstate_c.curTextureWidth != texW || gstate_c.curTextureHeight != texH);1173if (gstate_c.curTextureXOffset != 0 || gstate_c.curTextureYOffset != 0) {1174gstate_c.SetNeedShaderTexclamp(true);1175}1176if (channel == RASTER_DEPTH) {1177framebuffer->usageFlags |= FB_USAGE_COLOR_MIXED_DEPTH;1178}11791180if (channel == RASTER_DEPTH && !gstate_c.Use(GPU_USE_DEPTH_TEXTURE)) {1181WARN_LOG_ONCE(ndepthtex, Log::G3D, "Depth textures not supported, not binding");1182// Flag to bind a null texture if we can't support depth textures.1183// Should only happen on old OpenGL.1184nextFramebufferTexture_ = nullptr;1185failedTexture_ = true;1186} else {1187nextFramebufferTexture_ = framebuffer;1188nextFramebufferTextureChannel_ = channel;1189}1190nextTexture_ = nullptr;1191} else {1192if (framebuffer->fbo) {1193framebuffer->fbo->Release();1194framebuffer->fbo = nullptr;1195}1196Unbind();1197gstate_c.SetNeedShaderTexclamp(false);1198nextFramebufferTexture_ = nullptr;1199nextTexture_ = nullptr;1200}12011202gstate_c.SetTextureIsVideo(false);1203gstate_c.SetTextureIs3D(false);1204gstate_c.SetTextureIsArray(true);12051206nextNeedsRehash_ = false;1207nextNeedsChange_ = false;1208nextNeedsRebuild_ = false;1209}12101211// Only looks for framebuffers.1212bool TextureCacheCommon::SetOffsetTexture(u32 yOffset) {1213if (!framebufferManager_->UseBufferedRendering()) {1214return false;1215}12161217u32 texaddr = gstate.getTextureAddress(0);1218GETextureFormat fmt = gstate.getTextureFormat();1219const u32 bpp = fmt == GE_TFMT_8888 ? 4 : 2;1220const u32 texaddrOffset = yOffset * gstate.getTextureWidth(0) * bpp;12211222if (!Memory::IsValidAddress(texaddr) || !Memory::IsValidAddress(texaddr + texaddrOffset)) {1223return false;1224}12251226TextureDefinition def;1227def.addr = texaddr;1228def.format = fmt;1229def.bufw = GetTextureBufw(0, texaddr, fmt);1230def.dim = gstate.getTextureDimension(0);12311232AttachCandidate bestCandidate;1233if (GetBestFramebufferCandidate(def, texaddrOffset, &bestCandidate)) {1234SetTextureFramebuffer(bestCandidate);1235return true;1236} else {1237return false;1238}1239}12401241bool TextureCacheCommon::GetCurrentFramebufferTextureDebug(GPUDebugBuffer &buffer, bool *isFramebuffer) {1242if (!nextFramebufferTexture_)1243return false;1244*isFramebuffer = true;12451246VirtualFramebuffer *vfb = nextFramebufferTexture_;1247u8 sf = vfb->renderScaleFactor;1248int x = gstate_c.curTextureXOffset * sf;1249int y = gstate_c.curTextureYOffset * sf;1250int desiredW = gstate.getTextureWidth(0) * sf;1251int desiredH = gstate.getTextureHeight(0) * sf;1252int w = std::min(desiredW, vfb->bufferWidth * sf - x);1253int h = std::min(desiredH, vfb->bufferHeight * sf - y);12541255bool retval;1256if (nextFramebufferTextureChannel_ == RASTER_DEPTH) {1257buffer.Allocate(desiredW, desiredH, GPU_DBG_FORMAT_FLOAT, false);1258if (w < desiredW || h < desiredH)1259buffer.ZeroBytes();1260retval = draw_->CopyFramebufferToMemory(vfb->fbo, Draw::FB_DEPTH_BIT, x, y, w, h, Draw::DataFormat::D32F, buffer.GetData(), desiredW, Draw::ReadbackMode::BLOCK, "GetCurrentTextureDebug");1261} else {1262buffer.Allocate(desiredW, desiredH, GPU_DBG_FORMAT_8888, false);1263if (w < desiredW || h < desiredH)1264buffer.ZeroBytes();1265retval = draw_->CopyFramebufferToMemory(vfb->fbo, Draw::FB_COLOR_BIT, x, y, w, h, Draw::DataFormat::R8G8B8A8_UNORM, buffer.GetData(), desiredW, Draw::ReadbackMode::BLOCK, "GetCurrentTextureDebug");1266}12671268// Vulkan requires us to re-apply all dynamic state for each command buffer, and the above will cause us to start a new cmdbuf.1269// So let's dirty the things that are involved in Vulkan dynamic state. Readbacks are not frequent so this won't hurt other backends.1270gstate_c.Dirty(DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_BLEND_STATE | DIRTY_DEPTHSTENCIL_STATE);1271// We may have blitted to a temp FBO.1272framebufferManager_->RebindFramebuffer("RebindFramebuffer - GetCurrentTextureDebug");1273if (!retval)1274ERROR_LOG(Log::G3D, "Failed to get debug texture: copy to memory failed");1275return retval;1276}12771278void TextureCacheCommon::NotifyConfigChanged() {1279int scaleFactor = g_Config.iTexScalingLevel;12801281if (!gstate_c.Use(GPU_USE_TEXTURE_NPOT)) {1282// Reduce the scale factor to a power of two (e.g. 2 or 4) if textures must be a power of two.1283// TODO: In addition we should probably remove these options from the UI in this case.1284while ((scaleFactor & (scaleFactor - 1)) != 0) {1285--scaleFactor;1286}1287}12881289// Just in case, small display with auto resolution or something.1290if (scaleFactor <= 0) {1291scaleFactor = 1;1292}12931294standardScaleFactor_ = scaleFactor;12951296replacer_.NotifyConfigChanged();1297}12981299void TextureCacheCommon::NotifyWriteFormattedFromMemory(u32 addr, int size, int width, GEBufferFormat fmt) {1300addr &= 0x3FFFFFFF;1301videos_.push_back({ addr, (u32)size, gpuStats.numFlips });1302}13031304void TextureCacheCommon::LoadClut(u32 clutAddr, u32 loadBytes) {1305if (loadBytes == 0) {1306// Don't accidentally overwrite clutTotalBytes_ with a zero.1307return;1308}13091310_assert_(loadBytes <= 2048);1311clutTotalBytes_ = loadBytes;1312clutRenderAddress_ = 0xFFFFFFFF;13131314if (!Memory::IsValidAddress(clutAddr)) {1315memset(clutBufRaw_, 0x00, loadBytes);1316// Reload the clut next time (should we really do it in this case?)1317clutLastFormat_ = 0xFFFFFFFF;1318clutMaxBytes_ = std::max(clutMaxBytes_, loadBytes);1319return;1320}13211322if (Memory::IsVRAMAddress(clutAddr)) {1323// Clear the uncached and mirror bits, etc. to match framebuffers.1324const u32 clutLoadAddr = clutAddr & 0x041FFFFF;1325const u32 clutLoadEnd = clutLoadAddr + loadBytes;1326static const u32 MAX_CLUT_OFFSET = 4096;13271328clutRenderOffset_ = MAX_CLUT_OFFSET;1329const std::vector<VirtualFramebuffer *> &framebuffers = framebufferManager_->Framebuffers();13301331u32 bestClutAddress = 0xFFFFFFFF;13321333VirtualFramebuffer *chosenFramebuffer = nullptr;1334for (VirtualFramebuffer *framebuffer : framebuffers) {1335// Let's not deal with divide by zero.1336if (framebuffer->fb_stride == 0)1337continue;13381339const u32 fb_address = framebuffer->fb_address;1340const u32 fb_bpp = BufferFormatBytesPerPixel(framebuffer->fb_format);1341int offset = clutLoadAddr - fb_address;13421343// Is this inside the framebuffer at all? Note that we only check the first line here, this should1344// be changed.1345bool matchRange = offset >= 0 && offset < (int)(framebuffer->fb_stride * fb_bpp);1346if (matchRange) {1347// And is it inside the rendered area? Sometimes games pack data in the margin between width and stride.1348// If the framebuffer width was detected as 512, we're gonna assume it's really 480.1349int fbMatchWidth = framebuffer->width;1350if (fbMatchWidth == 512) {1351fbMatchWidth = 480;1352}1353int pixelOffsetX = ((offset / fb_bpp) % framebuffer->fb_stride);1354bool inMargin = pixelOffsetX >= fbMatchWidth && (pixelOffsetX + (loadBytes / fb_bpp) <= framebuffer->fb_stride);13551356// The offset check here means, in the context of the loop, that we'll pick1357// the framebuffer with the smallest offset. This is yet another framebuffer matching1358// loop with its own rules, eventually we'll probably want to do something1359// more systematic.1360bool okAge = !PSP_CoreParameter().compat.flags().LoadCLUTFromCurrentFrameOnly || framebuffer->last_frame_render == gpuStats.numFlips; // Here we can try heuristics.1361if (matchRange && !inMargin && offset < (int)clutRenderOffset_) {1362if (okAge) {1363WARN_LOG_N_TIMES(clutfb, 5, Log::G3D, "Detected LoadCLUT(%d bytes) from framebuffer %08x (%s), last render %d frames ago, byte offset %d, pixel offset %d",1364loadBytes, fb_address, GeBufferFormatToString(framebuffer->fb_format), gpuStats.numFlips - framebuffer->last_frame_render, offset, offset / fb_bpp);1365framebuffer->last_frame_clut = gpuStats.numFlips;1366// Also mark used so it's not decimated.1367framebuffer->last_frame_used = gpuStats.numFlips;1368framebuffer->usageFlags |= FB_USAGE_CLUT;1369bestClutAddress = framebuffer->fb_address;1370clutRenderOffset_ = (u32)offset;1371chosenFramebuffer = framebuffer;1372if (offset == 0) {1373// Not gonna find a better match according to the smallest-offset rule, so we'll go with this one.1374break;1375}1376} else {1377WARN_LOG(Log::G3D, "Ignoring CLUT load from %d frames old buffer at %08x", gpuStats.numFlips - framebuffer->last_frame_render, fb_address);1378}1379}1380}1381}13821383// To turn off dynamic CLUT (for demonstration or testing purposes), add "false &&" to this check.1384if (chosenFramebuffer && chosenFramebuffer->fbo) {1385clutRenderAddress_ = bestClutAddress;13861387if (!dynamicClutTemp_) {1388Draw::FramebufferDesc desc{};1389desc.width = 512;1390desc.height = 1;1391desc.depth = 1;1392desc.z_stencil = false;1393desc.numLayers = 1;1394desc.multiSampleLevel = 0;1395desc.tag = "dynamic_clut";1396dynamicClutFbo_ = draw_->CreateFramebuffer(desc);1397desc.tag = "dynamic_clut_temp";1398dynamicClutTemp_ = draw_->CreateFramebuffer(desc);1399}14001401// We'll need to copy from the offset.1402const u32 fb_bpp = BufferFormatBytesPerPixel(chosenFramebuffer->fb_format);1403const int totalPixelsOffset = clutRenderOffset_ / fb_bpp;1404const int clutYOffset = totalPixelsOffset / chosenFramebuffer->fb_stride;1405const int clutXOffset = totalPixelsOffset % chosenFramebuffer->fb_stride;1406const int scale = chosenFramebuffer->renderScaleFactor;14071408// Copy the pixels to our temp clut, scaling down if needed and wrapping.1409framebufferManager_->BlitUsingRaster(1410chosenFramebuffer->fbo, clutXOffset * scale, clutYOffset * scale, (clutXOffset + 512.0f) * scale, (clutYOffset + 1.0f) * scale,1411dynamicClutTemp_, 0.0f, 0.0f, 512.0f, 1.0f,1412false, scale, framebufferManager_->Get2DPipeline(DRAW2D_COPY_COLOR_RECT2LIN), "copy_clut_to_temp");14131414framebufferManager_->RebindFramebuffer("after_copy_clut_to_temp");1415clutRenderFormat_ = chosenFramebuffer->fb_format;1416}1417NotifyMemInfo(MemBlockFlags::ALLOC, clutAddr, loadBytes, "CLUT");1418}14191420// It's possible for a game to load CLUT outside valid memory without crashing, should result in zeroes.1421u32 bytes = Memory::ValidSize(clutAddr, loadBytes);1422_assert_(bytes <= 2048);1423bool performDownload = PSP_CoreParameter().compat.flags().AllowDownloadCLUT;1424if (GPURecord::IsActive())1425performDownload = true;1426if (clutRenderAddress_ != 0xFFFFFFFF && performDownload) {1427framebufferManager_->DownloadFramebufferForClut(clutRenderAddress_, clutRenderOffset_ + bytes);1428Memory::MemcpyUnchecked(clutBufRaw_, clutAddr, bytes);1429if (bytes < loadBytes) {1430memset((u8 *)clutBufRaw_ + bytes, 0x00, loadBytes - bytes);1431}1432} else {1433// Here we could check for clutRenderAddress_ != 0xFFFFFFFF and zero the CLUT or something,1434// but choosing not to for now. Though the results of loading the CLUT from RAM here is1435// almost certainly going to be bogus.1436#ifdef _M_SSE1437if (bytes == loadBytes) {1438const __m128i *source = (const __m128i *)Memory::GetPointerUnchecked(clutAddr);1439__m128i *dest = (__m128i *)clutBufRaw_;1440int numBlocks = bytes / 32;1441for (int i = 0; i < numBlocks; i++, source += 2, dest += 2) {1442__m128i data1 = _mm_loadu_si128(source);1443__m128i data2 = _mm_loadu_si128(source + 1);1444_mm_store_si128(dest, data1);1445_mm_store_si128(dest + 1, data2);1446}1447} else {1448Memory::MemcpyUnchecked(clutBufRaw_, clutAddr, bytes);1449if (bytes < loadBytes) {1450memset((u8 *)clutBufRaw_ + bytes, 0x00, loadBytes - bytes);1451}1452}1453#elif PPSSPP_ARCH(ARM_NEON)1454if (bytes == loadBytes) {1455const uint32_t *source = (const uint32_t *)Memory::GetPointerUnchecked(clutAddr);1456uint32_t *dest = (uint32_t *)clutBufRaw_;1457int numBlocks = bytes / 32;1458for (int i = 0; i < numBlocks; i++, source += 8, dest += 8) {1459uint32x4_t data1 = vld1q_u32(source);1460uint32x4_t data2 = vld1q_u32(source + 4);1461vst1q_u32(dest, data1);1462vst1q_u32(dest + 4, data2);1463}1464} else {1465Memory::MemcpyUnchecked(clutBufRaw_, clutAddr, bytes);1466if (bytes < loadBytes) {1467memset((u8 *)clutBufRaw_ + bytes, 0x00, loadBytes - bytes);1468}1469}1470#else1471Memory::MemcpyUnchecked(clutBufRaw_, clutAddr, bytes);1472if (bytes < loadBytes) {1473memset((u8 *)clutBufRaw_ + bytes, 0x00, loadBytes - bytes);1474}1475#endif1476}14771478// Reload the clut next time.1479clutLastFormat_ = 0xFFFFFFFF;1480clutMaxBytes_ = std::max(clutMaxBytes_, loadBytes);1481}14821483void TextureCacheCommon::UnswizzleFromMem(u32 *dest, u32 destPitch, const u8 *texptr, u32 bufw, u32 height, u32 bytesPerPixel) {1484// Note: bufw is always aligned to 16 bytes, so rowWidth is always >= 16.1485const u32 rowWidth = (bytesPerPixel > 0) ? (bufw * bytesPerPixel) : (bufw / 2);1486// A visual mapping of unswizzling, where each letter is 16-byte and 8 letters is a block:1487//1488// ABCDEFGH IJKLMNOP1489// ->1490// AI1491// BJ1492// CK1493// ...1494//1495// bxc is the number of blocks in the x direction, and byc the number in the y direction.1496const int bxc = rowWidth / 16;1497// The height is not always aligned to 8, but rounds up.1498int byc = (height + 7) / 8;14991500DoUnswizzleTex16(texptr, dest, bxc, byc, destPitch);1501}15021503bool TextureCacheCommon::GetCurrentClutBuffer(GPUDebugBuffer &buffer) {1504const u32 bpp = gstate.getClutPaletteFormat() == GE_CMODE_32BIT_ABGR8888 ? 4 : 2;1505const u32 pixels = 1024 / bpp;15061507buffer.Allocate(pixels, 1, (GEBufferFormat)gstate.getClutPaletteFormat());1508memcpy(buffer.GetData(), clutBufRaw_, 1024);1509return true;1510}15111512// Host memory usage, not PSP memory usage.1513u32 TextureCacheCommon::EstimateTexMemoryUsage(const TexCacheEntry *entry) {1514const u16 dim = entry->dim;1515// TODO: This does not take into account the HD remaster's larger textures.1516const u8 dimW = ((dim >> 0) & 0xf);1517const u8 dimH = ((dim >> 8) & 0xf);15181519u32 pixelSize = 2;1520switch (entry->format) {1521case GE_TFMT_CLUT4:1522case GE_TFMT_CLUT8:1523case GE_TFMT_CLUT16:1524case GE_TFMT_CLUT32:1525// We assume cluts always point to 8888 for simplicity.1526pixelSize = 4;1527break;1528case GE_TFMT_4444:1529case GE_TFMT_5551:1530case GE_TFMT_5650:1531break;15321533case GE_TFMT_8888:1534case GE_TFMT_DXT1:1535case GE_TFMT_DXT3:1536case GE_TFMT_DXT5:1537default:1538pixelSize = 4;1539break;1540}15411542// This in other words multiplies by w and h.1543return pixelSize << (dimW + dimH);1544}15451546ReplacedTexture *TextureCacheCommon::FindReplacement(TexCacheEntry *entry, int *w, int *h, int *d) {1547if (*d != 1) {1548// We don't yet support replacing 3D textures.1549return nullptr;1550}15511552// Short circuit the non-enabled case.1553// Otherwise, due to bReplaceTexturesAllowLate, we'll still spawn tasks looking for replacements1554// that then won't be used.1555if (!replacer_.ReplaceEnabled()) {1556return nullptr;1557}15581559if ((entry->status & TexCacheEntry::STATUS_VIDEO) && !replacer_.AllowVideo()) {1560return nullptr;1561}15621563double replaceStart = time_now_d();1564u64 cachekey = entry->CacheKey();1565ReplacedTexture *replaced = replacer_.FindReplacement(cachekey, entry->fullhash, *w, *h);1566replacementTimeThisFrame_ += time_now_d() - replaceStart;1567if (!replaced) {1568// TODO: Remove the flag here?1569// entry->status &= ~TexCacheEntry::STATUS_TO_REPLACE;1570return nullptr;1571}1572entry->replacedTexture = replaced; // we know it's non-null here.1573PollReplacement(entry, w, h, d);1574return replaced;1575}15761577void TextureCacheCommon::PollReplacement(TexCacheEntry *entry, int *w, int *h, int *d) {1578// Allow some delay to reduce pop-in.1579constexpr double MAX_BUDGET_PER_TEX = 0.25 / 60.0;15801581double budget = std::min(MAX_BUDGET_PER_TEX, replacementFrameBudget_ - replacementTimeThisFrame_);15821583double replaceStart = time_now_d();1584if (entry->replacedTexture->Poll(budget)) {1585if (entry->replacedTexture->State() == ReplacementState::ACTIVE) {1586entry->replacedTexture->GetSize(0, w, h);1587// Consider it already "scaled.".1588entry->status |= TexCacheEntry::STATUS_IS_SCALED_OR_REPLACED;1589}15901591// Remove the flag, even if it was invalid.1592entry->status &= ~TexCacheEntry::STATUS_TO_REPLACE;1593}1594replacementTimeThisFrame_ += time_now_d() - replaceStart;15951596switch (entry->replacedTexture->State()) {1597case ReplacementState::UNLOADED:1598case ReplacementState::PENDING:1599// Make sure we keep polling.1600entry->status |= TexCacheEntry::STATUS_TO_REPLACE;1601break;1602default:1603break;1604}1605}16061607// This is only used in the GLES backend, where we don't point these to video memory.1608// So we shouldn't add a check for dstBuf != srcBuf, as long as the functions we call can handle that.1609static void ReverseColors(void *dstBuf, const void *srcBuf, GETextureFormat fmt, int numPixels) {1610switch (fmt) {1611case GE_TFMT_4444:1612ConvertRGBA4444ToABGR4444((u16 *)dstBuf, (const u16 *)srcBuf, numPixels);1613break;1614// Final Fantasy 2 uses this heavily in animated textures.1615case GE_TFMT_5551:1616ConvertRGBA5551ToABGR1555((u16 *)dstBuf, (const u16 *)srcBuf, numPixels);1617break;1618case GE_TFMT_5650:1619ConvertRGB565ToBGR565((u16 *)dstBuf, (const u16 *)srcBuf, numPixels);1620break;1621default:1622// No need to convert RGBA8888, right order already1623if (dstBuf != srcBuf) {1624memcpy(dstBuf, srcBuf, numPixels * sizeof(u32));1625}1626break;1627}1628}16291630static inline void ConvertFormatToRGBA8888(GETextureFormat format, u32 *dst, const u16 *src, u32 numPixels) {1631switch (format) {1632case GE_TFMT_4444:1633ConvertRGBA4444ToRGBA8888(dst, src, numPixels);1634break;1635case GE_TFMT_5551:1636ConvertRGBA5551ToRGBA8888(dst, src, numPixels);1637break;1638case GE_TFMT_5650:1639ConvertRGB565ToRGBA8888(dst, src, numPixels);1640break;1641default:1642_dbg_assert_msg_(false, "Incorrect texture format.");1643break;1644}1645}16461647static inline void ConvertFormatToRGBA8888(GEPaletteFormat format, u32 *dst, const u16 *src, u32 numPixels) {1648// The supported values are 1:1 identical.1649ConvertFormatToRGBA8888(GETextureFormat(format), dst, src, numPixels);1650}16511652template <typename DXTBlock, int n>1653static CheckAlphaResult DecodeDXTBlocks(uint8_t *out, int outPitch, uint32_t texaddr, const uint8_t *texptr,1654int w, int h, int bufw, bool reverseColors) {16551656int minw = std::min(bufw, w);1657uint32_t *dst = (uint32_t *)out;1658int outPitch32 = outPitch / sizeof(uint32_t);1659const DXTBlock *src = (const DXTBlock *)texptr;16601661if (!Memory::IsValidRange(texaddr, (h / 4) * (bufw / 4) * sizeof(DXTBlock))) {1662ERROR_LOG_REPORT(Log::G3D, "DXT%d texture extends beyond valid RAM: %08x + %d x %d", n, texaddr, bufw, h);1663uint32_t limited = Memory::ValidSize(texaddr, (h / 4) * (bufw / 4) * sizeof(DXTBlock));1664// This might possibly be 0, but try to decode what we can (might even be how the PSP behaves.)1665h = (((int)limited / sizeof(DXTBlock)) / (bufw / 4)) * 4;1666}16671668u32 alphaSum = 1;1669for (int y = 0; y < h; y += 4) {1670u32 blockIndex = (y / 4) * (bufw / 4);1671int blockHeight = std::min(h - y, 4);1672for (int x = 0; x < minw; x += 4) {1673int blockWidth = std::min(minw - x, 4);1674if constexpr (n == 1)1675DecodeDXT1Block(dst + outPitch32 * y + x, (const DXT1Block *)src + blockIndex, outPitch32, blockWidth, blockHeight, &alphaSum);1676else if constexpr (n == 3)1677DecodeDXT3Block(dst + outPitch32 * y + x, (const DXT3Block *)src + blockIndex, outPitch32, blockWidth, blockHeight);1678else if constexpr (n == 5)1679DecodeDXT5Block(dst + outPitch32 * y + x, (const DXT5Block *)src + blockIndex, outPitch32, blockWidth, blockHeight);1680blockIndex++;1681}1682}16831684if (reverseColors) {1685ReverseColors(out, out, GE_TFMT_8888, outPitch32 * h);1686}16871688if constexpr (n == 1) {1689return alphaSum == 1 ? CHECKALPHA_FULL : CHECKALPHA_ANY;1690} else {1691// Just report that we don't have full alpha, since these formats are made for that.1692return CHECKALPHA_ANY;1693}1694}16951696inline u32 ClutFormatToFullAlpha(GEPaletteFormat fmt, bool reverseColors) {1697switch (fmt) {1698case GE_CMODE_16BIT_ABGR4444: return reverseColors ? 0x000F : 0xF000;1699case GE_CMODE_16BIT_ABGR5551: return reverseColors ? 0x0001 : 0x8000;1700case GE_CMODE_32BIT_ABGR8888: return 0xFF000000;1701case GE_CMODE_16BIT_BGR5650: return 0;1702default: return 0;1703}1704}17051706inline u32 TfmtRawToFullAlpha(GETextureFormat fmt) {1707switch (fmt) {1708case GE_TFMT_4444: return 0xF000;1709case GE_TFMT_5551: return 0x8000;1710case GE_TFMT_8888: return 0xFF000000;1711case GE_TFMT_5650: return 0;1712default: return 0;1713}1714}17151716// Used for converting CLUT4 to CLUT8.1717// Could SIMD or whatever, though will hardly be a bottleneck.1718static void Expand4To8Bits(u8 *dest, const u8 *src, int srcWidth) {1719for (int i = 0; i < (srcWidth + 1) / 2; i++) {1720u8 lower = src[i] & 0xF;1721u8 upper = src[i] >> 4;1722dest[i * 2] = lower;1723dest[i * 2 + 1] = upper;1724}1725}17261727CheckAlphaResult TextureCacheCommon::DecodeTextureLevel(u8 *out, int outPitch, GETextureFormat format, GEPaletteFormat clutformat, uint32_t texaddr, int level, int bufw, TexDecodeFlags flags) {1728u32 alphaSum = 0xFFFFFFFF;1729u32 fullAlphaMask = 0x0;17301731bool expandTo32bit = (flags & TexDecodeFlags::EXPAND32) != 0;1732bool reverseColors = (flags & TexDecodeFlags::REVERSE_COLORS) != 0;1733bool toClut8 = (flags & TexDecodeFlags::TO_CLUT8) != 0;17341735if (toClut8 && format != GE_TFMT_CLUT8 && format != GE_TFMT_CLUT4) {1736_dbg_assert_(false);1737}17381739bool swizzled = gstate.isTextureSwizzled();1740if ((texaddr & 0x00600000) != 0 && Memory::IsVRAMAddress(texaddr)) {1741// This means it's in a mirror, possibly a swizzled mirror. Let's report.1742WARN_LOG_REPORT_ONCE(texmirror, Log::G3D, "Decoding texture from VRAM mirror at %08x swizzle=%d", texaddr, swizzled ? 1 : 0);1743if ((texaddr & 0x00200000) == 0x00200000) {1744// Technically 2 and 6 are slightly different, but this is better than nothing probably.1745// We should only see this with depth textures anyway which we don't support uploading (yet).1746swizzled = !swizzled;1747}1748// Note that (texaddr & 0x00600000) == 0x00600000 is very likely to be depth texturing.1749}17501751int w = gstate.getTextureWidth(level);1752int h = gstate.getTextureHeight(level);1753const u8 *texptr = Memory::GetPointer(texaddr);1754const uint32_t byteSize = (textureBitsPerPixel[format] * bufw * h) / 8;17551756char buf[128];1757size_t len = snprintf(buf, sizeof(buf), "Tex_%08x_%dx%d_%s", texaddr, w, h, GeTextureFormatToString(format, clutformat));1758NotifyMemInfo(MemBlockFlags::TEXTURE, texaddr, byteSize, buf, len);17591760switch (format) {1761case GE_TFMT_CLUT4:1762{1763const bool mipmapShareClut = gstate.isClutSharedForMipmaps();1764const int clutSharingOffset = mipmapShareClut ? 0 : level * 16;17651766if (swizzled) {1767tmpTexBuf32_.resize(bufw * ((h + 7) & ~7));1768UnswizzleFromMem(tmpTexBuf32_.data(), bufw / 2, texptr, bufw, h, 0);1769texptr = (u8 *)tmpTexBuf32_.data();1770}17711772if (toClut8) {1773// We just need to expand from 4 to 8 bits.1774for (int y = 0; y < h; ++y) {1775Expand4To8Bits((u8 *)out + outPitch * y, texptr + (bufw * y) / 2, w);1776}1777// We can't know anything about alpha.1778return CHECKALPHA_ANY;1779}17801781switch (clutformat) {1782case GE_CMODE_16BIT_BGR5650:1783case GE_CMODE_16BIT_ABGR5551:1784case GE_CMODE_16BIT_ABGR4444:1785{1786// The w > 1 check is to not need a case that handles a single pixel1787// in DeIndexTexture4Optimal<u16>.1788if (clutAlphaLinear_ && mipmapShareClut && !expandTo32bit && w >= 4) {1789// We don't bother with fullalpha here (clutAlphaLinear_)1790// Here, reverseColors means the CLUT is already reversed.1791if (reverseColors) {1792for (int y = 0; y < h; ++y) {1793DeIndexTexture4Optimal((u16 *)(out + outPitch * y), texptr + (bufw * y) / 2, w, clutAlphaLinearColor_);1794}1795} else {1796for (int y = 0; y < h; ++y) {1797DeIndexTexture4OptimalRev((u16 *)(out + outPitch * y), texptr + (bufw * y) / 2, w, clutAlphaLinearColor_);1798}1799}1800} else {1801// Need to have the "un-reversed" (raw) CLUT here since we are using a generic conversion function.1802if (expandTo32bit) {1803// We simply expand the CLUT to 32-bit, then we deindex as usual. Probably the fastest way.1804const u16 *clut = GetCurrentRawClut<u16>() + clutSharingOffset;1805const int clutStart = gstate.getClutIndexStartPos();1806if (gstate.getClutIndexShift() == 0 || gstate.getClutIndexMask() <= 16) {1807ConvertFormatToRGBA8888(clutformat, expandClut_ + clutStart, clut + clutStart, 16);1808} else {1809// To be safe for shifts and wrap around, convert the entire CLUT.1810ConvertFormatToRGBA8888(clutformat, expandClut_, clut, 512);1811}1812fullAlphaMask = 0xFF000000;1813for (int y = 0; y < h; ++y) {1814DeIndexTexture4<u32>((u32 *)(out + outPitch * y), texptr + (bufw * y) / 2, w, expandClut_, &alphaSum);1815}1816} else {1817// If we're reversing colors, the CLUT was already reversed, no special handling needed.1818const u16 *clut = GetCurrentClut<u16>() + clutSharingOffset;1819fullAlphaMask = ClutFormatToFullAlpha(clutformat, reverseColors);1820for (int y = 0; y < h; ++y) {1821DeIndexTexture4<u16>((u16 *)(out + outPitch * y), texptr + (bufw * y) / 2, w, clut, &alphaSum);1822}1823}1824}18251826if (clutformat == GE_CMODE_16BIT_BGR5650) {1827// Our formula at the end of the function can't handle this cast so we return early.1828return CHECKALPHA_FULL;1829}1830}1831break;18321833case GE_CMODE_32BIT_ABGR8888:1834{1835const u32 *clut = GetCurrentClut<u32>() + clutSharingOffset;1836fullAlphaMask = 0xFF000000;1837for (int y = 0; y < h; ++y) {1838DeIndexTexture4<u32>((u32 *)(out + outPitch * y), texptr + (bufw * y) / 2, w, clut, &alphaSum);1839}1840}1841break;18421843default:1844ERROR_LOG_REPORT(Log::G3D, "Unknown CLUT4 texture mode %d", gstate.getClutPaletteFormat());1845return CHECKALPHA_ANY;1846}1847}1848break;18491850case GE_TFMT_CLUT8:1851if (toClut8) {1852if (gstate.isTextureSwizzled()) {1853tmpTexBuf32_.resize(bufw * ((h + 7) & ~7));1854UnswizzleFromMem(tmpTexBuf32_.data(), bufw, texptr, bufw, h, 1);1855texptr = (u8 *)tmpTexBuf32_.data();1856}1857// After deswizzling, we are in the correct format and can just copy.1858for (int y = 0; y < h; ++y) {1859memcpy((u8 *)out + outPitch * y, texptr + (bufw * y), w);1860}1861// We can't know anything about alpha.1862return CHECKALPHA_ANY;1863}1864return ReadIndexedTex(out, outPitch, level, texptr, 1, bufw, reverseColors, expandTo32bit);18651866case GE_TFMT_CLUT16:1867return ReadIndexedTex(out, outPitch, level, texptr, 2, bufw, reverseColors, expandTo32bit);18681869case GE_TFMT_CLUT32:1870return ReadIndexedTex(out, outPitch, level, texptr, 4, bufw, reverseColors, expandTo32bit);18711872case GE_TFMT_4444:1873case GE_TFMT_5551:1874case GE_TFMT_5650:1875if (!swizzled) {1876// Just a simple copy, we swizzle the color format.1877fullAlphaMask = TfmtRawToFullAlpha(format);1878if (expandTo32bit) {1879// This is OK even if reverseColors is on, because it expands to the 8888 format which is the same in reverse mode.1880for (int y = 0; y < h; ++y) {1881CheckMask16((const u16 *)(texptr + bufw * sizeof(u16) * y), w, &alphaSum);1882ConvertFormatToRGBA8888(format, (u32 *)(out + outPitch * y), (const u16 *)texptr + bufw * y, w);1883}1884} else if (reverseColors) {1885// Just check the input's alpha to reuse code. TODO: make a specialized ReverseColors that checks as we go.1886for (int y = 0; y < h; ++y) {1887CheckMask16((const u16 *)(texptr + bufw * sizeof(u16) * y), w, &alphaSum);1888ReverseColors(out + outPitch * y, texptr + bufw * sizeof(u16) * y, format, w);1889}1890} else {1891for (int y = 0; y < h; ++y) {1892CopyAndSumMask16((u16 *)(out + outPitch * y), (u16 *)(texptr + bufw * sizeof(u16) * y), w, &alphaSum);1893}1894}1895} /* else if (h >= 8 && bufw <= w && !expandTo32bit) {1896// TODO: Handle alpha mask. This will require special versions of UnswizzleFromMem to keep the optimization.1897// Note: this is always safe since h must be a power of 2, so a multiple of 8.1898UnswizzleFromMem((u32 *)out, outPitch, texptr, bufw, h, 2);1899if (reverseColors) {1900ReverseColors(out, out, format, h * outPitch / 2, useBGRA);1901}1902}*/ else {1903// We don't have enough space for all rows in out, so use a temp buffer.1904tmpTexBuf32_.resize(bufw * ((h + 7) & ~7));1905UnswizzleFromMem(tmpTexBuf32_.data(), bufw * 2, texptr, bufw, h, 2);1906const u8 *unswizzled = (u8 *)tmpTexBuf32_.data();19071908fullAlphaMask = TfmtRawToFullAlpha(format);1909if (expandTo32bit) {1910// This is OK even if reverseColors is on, because it expands to the 8888 format which is the same in reverse mode.1911// Just check the swizzled input's alpha to reuse code. TODO: make a specialized ConvertFormatToRGBA8888 that checks as we go.1912for (int y = 0; y < h; ++y) {1913CheckMask16((const u16 *)(unswizzled + bufw * sizeof(u16) * y), w, &alphaSum);1914ConvertFormatToRGBA8888(format, (u32 *)(out + outPitch * y), (const u16 *)unswizzled + bufw * y, w);1915}1916} else if (reverseColors) {1917// Just check the swizzled input's alpha to reuse code. TODO: make a specialized ReverseColors that checks as we go.1918for (int y = 0; y < h; ++y) {1919CheckMask16((const u16 *)(unswizzled + bufw * sizeof(u16) * y), w, &alphaSum);1920ReverseColors(out + outPitch * y, unswizzled + bufw * sizeof(u16) * y, format, w);1921}1922} else {1923for (int y = 0; y < h; ++y) {1924CopyAndSumMask16((u16 *)(out + outPitch * y), (const u16 *)(unswizzled + bufw * sizeof(u16) * y), w, &alphaSum);1925}1926}1927}1928if (format == GE_TFMT_5650) {1929return CHECKALPHA_FULL;1930}1931break;19321933case GE_TFMT_8888:1934if (!swizzled) {1935fullAlphaMask = TfmtRawToFullAlpha(format);1936if (reverseColors) {1937for (int y = 0; y < h; ++y) {1938CheckMask32((const u32 *)(texptr + bufw * sizeof(u32) * y), w, &alphaSum);1939ReverseColors(out + outPitch * y, texptr + bufw * sizeof(u32) * y, format, w);1940}1941} else {1942for (int y = 0; y < h; ++y) {1943CopyAndSumMask32((u32 *)(out + outPitch * y), (const u32 *)(texptr + bufw * sizeof(u32) * y), w, &alphaSum);1944}1945}1946} /* else if (h >= 8 && bufw <= w) {1947// TODO: Handle alpha mask1948UnswizzleFromMem((u32 *)out, outPitch, texptr, bufw, h, 4);1949if (reverseColors) {1950ReverseColors(out, out, format, h * outPitch / 4, useBGRA);1951}1952}*/ else {1953tmpTexBuf32_.resize(bufw * ((h + 7) & ~7));1954UnswizzleFromMem(tmpTexBuf32_.data(), bufw * 4, texptr, bufw, h, 4);1955const u8 *unswizzled = (u8 *)tmpTexBuf32_.data();19561957fullAlphaMask = TfmtRawToFullAlpha(format);1958if (reverseColors) {1959for (int y = 0; y < h; ++y) {1960CheckMask32((const u32 *)(unswizzled + bufw * sizeof(u32) * y), w, &alphaSum);1961ReverseColors(out + outPitch * y, unswizzled + bufw * sizeof(u32) * y, format, w);1962}1963} else {1964for (int y = 0; y < h; ++y) {1965CopyAndSumMask32((u32 *)(out + outPitch * y), (const u32 *)(unswizzled + bufw * sizeof(u32) * y), w, &alphaSum);1966}1967}1968}1969break;19701971case GE_TFMT_DXT1:1972return DecodeDXTBlocks<DXT1Block, 1>(out, outPitch, texaddr, texptr, w, h, bufw, reverseColors);19731974case GE_TFMT_DXT3:1975return DecodeDXTBlocks<DXT3Block, 3>(out, outPitch, texaddr, texptr, w, h, bufw, reverseColors);19761977case GE_TFMT_DXT5:1978return DecodeDXTBlocks<DXT5Block, 5>(out, outPitch, texaddr, texptr, w, h, bufw, reverseColors);19791980default:1981ERROR_LOG_REPORT(Log::G3D, "Unknown Texture Format %d!!!", format);1982break;1983}19841985return AlphaSumIsFull(alphaSum, fullAlphaMask) ? CHECKALPHA_FULL : CHECKALPHA_ANY;1986}19871988CheckAlphaResult TextureCacheCommon::ReadIndexedTex(u8 *out, int outPitch, int level, const u8 *texptr, int bytesPerIndex, int bufw, bool reverseColors, bool expandTo32Bit) {1989int w = gstate.getTextureWidth(level);1990int h = gstate.getTextureHeight(level);19911992if (gstate.isTextureSwizzled()) {1993tmpTexBuf32_.resize(bufw * ((h + 7) & ~7));1994UnswizzleFromMem(tmpTexBuf32_.data(), bufw * bytesPerIndex, texptr, bufw, h, bytesPerIndex);1995texptr = (u8 *)tmpTexBuf32_.data();1996}19971998// Misshitsu no Sacrifice has separate CLUT data, this is a hack to allow it.1999// Normally separate CLUTs are not allowed for 8-bit or higher indices.2000const bool mipmapShareClut = gstate.isClutSharedForMipmaps() || gstate.getClutLoadBlocks() != 0x40;2001const int clutSharingOffset = mipmapShareClut ? 0 : (level & 1) * 256;20022003GEPaletteFormat palFormat = (GEPaletteFormat)gstate.getClutPaletteFormat();20042005const u16 *clut16 = (const u16 *)clutBuf_ + clutSharingOffset;2006const u32 *clut32 = (const u32 *)clutBuf_ + clutSharingOffset;20072008if (expandTo32Bit && palFormat != GE_CMODE_32BIT_ABGR8888) {2009const u16 *clut16raw = (const u16 *)clutBufRaw_ + clutSharingOffset;2010// It's possible to access the latter half of the CLUT using the start pos.2011const int clutStart = gstate.getClutIndexStartPos();2012if (clutStart > 256) {2013// Access wraps around when start + index goes over.2014ConvertFormatToRGBA8888(GEPaletteFormat(palFormat), expandClut_, clut16raw, 512);2015} else {2016ConvertFormatToRGBA8888(GEPaletteFormat(palFormat), expandClut_ + clutStart, clut16raw + clutStart, 256);2017}2018clut32 = expandClut_;2019palFormat = GE_CMODE_32BIT_ABGR8888;2020}20212022u32 alphaSum = 0xFFFFFFFF;2023u32 fullAlphaMask = ClutFormatToFullAlpha(palFormat, reverseColors);20242025switch (palFormat) {2026case GE_CMODE_16BIT_BGR5650:2027case GE_CMODE_16BIT_ABGR5551:2028case GE_CMODE_16BIT_ABGR4444:2029{2030switch (bytesPerIndex) {2031case 1:2032for (int y = 0; y < h; ++y) {2033DeIndexTexture((u16 *)(out + outPitch * y), (const u8 *)texptr + bufw * y, w, clut16, &alphaSum);2034}2035break;20362037case 2:2038for (int y = 0; y < h; ++y) {2039DeIndexTexture((u16 *)(out + outPitch * y), (const u16_le *)texptr + bufw * y, w, clut16, &alphaSum);2040}2041break;20422043case 4:2044for (int y = 0; y < h; ++y) {2045DeIndexTexture((u16 *)(out + outPitch * y), (const u32_le *)texptr + bufw * y, w, clut16, &alphaSum);2046}2047break;2048}2049}2050break;20512052case GE_CMODE_32BIT_ABGR8888:2053{20542055switch (bytesPerIndex) {2056case 1:2057for (int y = 0; y < h; ++y) {2058DeIndexTexture((u32 *)(out + outPitch * y), (const u8 *)texptr + bufw * y, w, clut32, &alphaSum);2059}2060break;20612062case 2:2063for (int y = 0; y < h; ++y) {2064DeIndexTexture((u32 *)(out + outPitch * y), (const u16_le *)texptr + bufw * y, w, clut32, &alphaSum);2065}2066break;20672068case 4:2069for (int y = 0; y < h; ++y) {2070DeIndexTexture((u32 *)(out + outPitch * y), (const u32_le *)texptr + bufw * y, w, clut32, &alphaSum);2071}2072break;2073}2074}2075break;20762077default:2078ERROR_LOG_REPORT(Log::G3D, "Unhandled clut texture mode %d!!!", gstate.getClutPaletteFormat());2079break;2080}20812082if (palFormat == GE_CMODE_16BIT_BGR5650) {2083return CHECKALPHA_FULL;2084} else {2085return AlphaSumIsFull(alphaSum, fullAlphaMask) ? CHECKALPHA_FULL : CHECKALPHA_ANY;2086}2087}20882089void TextureCacheCommon::ApplyTexture() {2090TexCacheEntry *entry = nextTexture_;2091if (!entry) {2092// Maybe we bound a framebuffer?2093ForgetLastTexture();2094if (failedTexture_) {2095// Backends should handle this by binding a black texture with 0 alpha.2096BindTexture(nullptr);2097} else if (nextFramebufferTexture_) {2098// ApplyTextureFrameBuffer is responsible for setting SetTextureFullAlpha.2099ApplyTextureFramebuffer(nextFramebufferTexture_, gstate.getTextureFormat(), nextFramebufferTextureChannel_);2100nextFramebufferTexture_ = nullptr;2101}21022103// We don't set the 3D texture state here or anything else, on some backends (?)2104// a nextTexture_ of nullptr means keep the current texture.2105return;2106}21072108nextTexture_ = nullptr;21092110UpdateMaxSeenV(entry, gstate.isModeThrough());21112112if (nextNeedsRebuild_) {2113// Regardless of hash fails or otherwise, if this is a video, mark it frequently changing.2114// This prevents temporary scaling perf hits on the first second of video.2115if (IsVideo(entry->addr)) {2116entry->status |= TexCacheEntry::STATUS_CHANGE_FREQUENT | TexCacheEntry::STATUS_VIDEO;2117} else {2118entry->status &= ~TexCacheEntry::STATUS_VIDEO;2119}21202121if (nextNeedsRehash_) {2122PROFILE_THIS_SCOPE("texhash");2123// Update the hash on the texture.2124int w = gstate.getTextureWidth(0);2125int h = gstate.getTextureHeight(0);2126bool swizzled = gstate.isTextureSwizzled();2127entry->fullhash = QuickTexHash(replacer_, entry->addr, entry->bufw, w, h, swizzled, GETextureFormat(entry->format), entry);21282129// TODO: Here we could check the secondary cache; maybe the texture is in there?2130// We would need to abort the build if so.2131}2132if (nextNeedsChange_) {2133// This texture existed previously, let's handle the change.2134HandleTextureChange(entry, nextChangeReason_, false, true);2135}2136// We actually build afterward (shared with rehash rebuild.)2137} else if (nextNeedsRehash_) {2138// Okay, this matched and didn't change - but let's check the hash. Maybe it will change.2139bool doDelete = true;2140if (!CheckFullHash(entry, doDelete)) {2141HandleTextureChange(entry, "hash fail", true, doDelete);2142nextNeedsRebuild_ = true;2143} else if (nextTexture_ != nullptr) {2144// The secondary cache may choose an entry from its storage by setting nextTexture_.2145// This means we should set that, instead of our previous entry.2146entry = nextTexture_;2147nextTexture_ = nullptr;2148UpdateMaxSeenV(entry, gstate.isModeThrough());2149}2150}21512152// Okay, now actually rebuild the texture if needed.2153if (nextNeedsRebuild_) {2154_assert_(!entry->texturePtr);2155BuildTexture(entry);2156ForgetLastTexture();2157}21582159gstate_c.SetTextureIsVideo((entry->status & TexCacheEntry::STATUS_VIDEO) != 0);2160if (entry->status & TexCacheEntry::STATUS_CLUT_GPU) {2161// Special process.2162ApplyTextureDepal(entry);2163entry->lastFrame = gpuStats.numFlips;2164gstate_c.SetTextureFullAlpha(false);2165gstate_c.SetTextureIs3D(false);2166gstate_c.SetTextureIsArray(false);2167gstate_c.SetTextureIsBGRA(false);2168} else {2169entry->lastFrame = gpuStats.numFlips;2170BindTexture(entry);2171gstate_c.SetTextureFullAlpha(entry->GetAlphaStatus() == TexCacheEntry::STATUS_ALPHA_FULL);2172gstate_c.SetTextureIs3D((entry->status & TexCacheEntry::STATUS_3D) != 0);2173gstate_c.SetTextureIsArray(false);2174gstate_c.SetTextureIsBGRA((entry->status & TexCacheEntry::STATUS_BGRA) != 0);2175gstate_c.SetUseShaderDepal(ShaderDepalMode::OFF);2176}2177}21782179// Can we depalettize at all? This refers to both in-fragment-shader depal and "traditional" depal through a separate pass.2180static bool CanDepalettize(GETextureFormat texFormat, GEBufferFormat bufferFormat) {2181if (IsClutFormat(texFormat)) {2182switch (bufferFormat) {2183case GE_FORMAT_4444:2184case GE_FORMAT_565:2185case GE_FORMAT_5551:2186case GE_FORMAT_DEPTH16:2187if (texFormat == GE_TFMT_CLUT16) {2188return true;2189}2190if (texFormat == GE_TFMT_CLUT8 && bufferFormat == GE_FORMAT_5551 && PSP_CoreParameter().compat.flags().SOCOMClut8Replacement) {2191// Wacky case from issue #16210 (SOCOM etc).2192return true;2193}2194break;2195case GE_FORMAT_8888:2196if (texFormat == GE_TFMT_CLUT32 || texFormat == GE_TFMT_CLUT8) { // clut8 takes a special depal mode.2197return true;2198}2199break;2200case GE_FORMAT_CLUT8:2201case GE_FORMAT_INVALID:2202// Shouldn't happen here.2203return false;2204}2205WARN_LOG(Log::G3D, "Invalid CLUT/framebuffer combination: %s vs %s", GeTextureFormatToString(texFormat), GeBufferFormatToString(bufferFormat));2206return false;2207} else if (texFormat == GE_TFMT_5650 && bufferFormat == GE_FORMAT_DEPTH16) {2208// We can also "depal" 565 format, this is used to read depth buffers as 565 on occasion (#15491).2209return true;2210}2211return false;2212}22132214// If the palette is detected as a smooth ramp, we can interpolate for higher color precision.2215// But we only do it if the mask/shift exactly matches a color channel, else something different might be going2216// on and we definitely don't want to interpolate.2217// Great enhancement for Test Drive and Manhunt 2.2218static bool CanUseSmoothDepal(const GPUgstate &gstate, GEBufferFormat framebufferFormat, const ClutTexture &clutTexture) {2219for (int i = 0; i < ClutTexture::MAX_RAMPS; i++) {2220if (gstate.getClutIndexStartPos() == clutTexture.rampStarts[i] &&2221gstate.getClutIndexMask() < clutTexture.rampLengths[i]) {2222switch (framebufferFormat) {2223case GE_FORMAT_565:2224if (gstate.getClutIndexShift() == 0 || gstate.getClutIndexShift() == 11) {2225return gstate.getClutIndexMask() == 0x1F;2226} else if (gstate.getClutIndexShift() == 5) {2227return gstate.getClutIndexMask() == 0x3F;2228}2229break;2230case GE_FORMAT_5551:2231if (gstate.getClutIndexShift() == 0 || gstate.getClutIndexShift() == 5 || gstate.getClutIndexShift() == 10) {2232return gstate.getClutIndexMask() == 0x1F;2233}2234break;2235default:2236// No uses for the other formats yet, add if needed.2237break;2238}2239}2240}2241return false;2242}22432244void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer, GETextureFormat texFormat, RasterChannel channel) {2245Draw2DPipeline *textureShader = nullptr;2246uint32_t clutMode = gstate.clutformat & 0xFFFFFF;22472248bool depth = channel == RASTER_DEPTH;2249bool need_depalettize = CanDepalettize(texFormat, depth ? GE_FORMAT_DEPTH16 : framebuffer->fb_format);22502251// Shader depal is not supported during 3D texturing or depth texturing, and requires 32-bit integer instructions in the shader.2252bool useShaderDepal = framebufferManager_->GetCurrentRenderVFB() != framebuffer &&2253!depth && clutRenderAddress_ == 0xFFFFFFFF &&2254!gstate_c.curTextureIs3D &&2255draw_->GetShaderLanguageDesc().bitwiseOps &&2256!(texFormat == GE_TFMT_CLUT8 && framebuffer->fb_format == GE_FORMAT_5551); // socom22572258switch (draw_->GetShaderLanguageDesc().shaderLanguage) {2259case ShaderLanguage::HLSL_D3D9:2260useShaderDepal = false;2261break;2262case ShaderLanguage::GLSL_1xx:2263// Force off for now, in case <= GLSL 1.20 or GLES 2, which don't support switch-case.2264useShaderDepal = false;2265break;2266default:2267break;2268}22692270const GEPaletteFormat clutFormat = gstate.getClutPaletteFormat();2271ClutTexture clutTexture{};2272bool smoothedDepal = false;2273u32 depthUpperBits = 0;22742275if (need_depalettize) {2276if (clutRenderAddress_ == 0xFFFFFFFF) {2277clutTexture = textureShaderCache_->GetClutTexture(clutFormat, clutHash_, clutBufRaw_);2278smoothedDepal = CanUseSmoothDepal(gstate, framebuffer->fb_format, clutTexture);2279} else {2280// The CLUT texture is dynamic, it's the framebuffer pointed to by clutRenderAddress.2281// Instead of texturing directly from that, we copy to a temporary CLUT texture.2282GEBufferFormat expectedCLUTBufferFormat = (GEBufferFormat)clutFormat;22832284// OK, figure out what format we want our framebuffer in, so it can be reinterpreted if needed.2285// If no reinterpretation is needed, we'll automatically just get a copy shader.2286float scaleFactorX = 1.0f;2287Draw2DPipeline *reinterpret = framebufferManager_->GetReinterpretPipeline(clutRenderFormat_, expectedCLUTBufferFormat, &scaleFactorX);2288framebufferManager_->BlitUsingRaster(dynamicClutTemp_, 0.0f, 0.0f, 512.0f, 1.0f, dynamicClutFbo_, 0.0f, 0.0f, scaleFactorX * 512.0f, 1.0f, false, 1.0f, reinterpret, "reinterpret_clut");2289}22902291if (useShaderDepal) {2292// Very icky conflation here of native and thin3d rendering. This will need careful work per backend in BindAsClutTexture.2293BindAsClutTexture(clutTexture.texture, smoothedDepal);22942295framebufferManager_->BindFramebufferAsColorTexture(0, framebuffer, BINDFBCOLOR_MAY_COPY_WITH_UV | BINDFBCOLOR_APPLY_TEX_OFFSET, Draw::ALL_LAYERS);2296// Vulkan needs to do some extra work here to pick out the native handle from Draw.2297BoundFramebufferTexture();22982299SamplerCacheKey samplerKey = GetFramebufferSamplingParams(framebuffer->bufferWidth, framebuffer->bufferHeight);2300samplerKey.magFilt = false;2301samplerKey.minFilt = false;2302samplerKey.mipEnable = false;2303ApplySamplingParams(samplerKey);23042305ShaderDepalMode mode = ShaderDepalMode::NORMAL;2306if (texFormat == GE_TFMT_CLUT8 && framebuffer->fb_format == GE_FORMAT_8888) {2307mode = ShaderDepalMode::CLUT8_8888;2308smoothedDepal = false; // just in case2309} else if (smoothedDepal) {2310mode = ShaderDepalMode::SMOOTHED;2311}23122313gstate_c.Dirty(DIRTY_DEPAL);2314gstate_c.SetUseShaderDepal(mode);2315gstate_c.depalFramebufferFormat = framebuffer->fb_format;23162317const u32 bytesPerColor = clutFormat == GE_CMODE_32BIT_ABGR8888 ? sizeof(u32) : sizeof(u16);2318const u32 clutTotalColors = clutMaxBytes_ / bytesPerColor;2319CheckAlphaResult alphaStatus = CheckCLUTAlpha((const uint8_t *)clutBufRaw_, clutFormat, clutTotalColors);2320gstate_c.SetTextureFullAlpha(alphaStatus == CHECKALPHA_FULL);23212322draw_->Invalidate(InvalidationFlags::CACHED_RENDER_STATE);2323return;2324}23252326depthUpperBits = (depth && framebuffer->fb_format == GE_FORMAT_8888) ? ((gstate.getTextureAddress(0) & 0x600000) >> 20) : 0;23272328textureShader = textureShaderCache_->GetDepalettizeShader(clutMode, texFormat, depth ? GE_FORMAT_DEPTH16 : framebuffer->fb_format, smoothedDepal, depthUpperBits);2329gstate_c.SetUseShaderDepal(ShaderDepalMode::OFF);2330}23312332if (textureShader) {2333bool needsDepthXSwizzle = depthUpperBits == 2;23342335int depalWidth = framebuffer->renderWidth;2336int texWidth = framebuffer->bufferWidth;2337if (needsDepthXSwizzle) {2338texWidth = RoundUpToPowerOf2(framebuffer->bufferWidth);2339depalWidth = texWidth * framebuffer->renderScaleFactor;2340gstate_c.Dirty(DIRTY_UVSCALEOFFSET);2341}23422343// If min is not < max, then we don't have values (wasn't set during decode.)2344const KnownVertexBounds &bounds = gstate_c.vertBounds;2345float u1 = 0.0f;2346float v1 = 0.0f;2347float u2 = depalWidth;2348float v2 = framebuffer->renderHeight;2349if (bounds.minV < bounds.maxV) {2350u1 = (bounds.minU + gstate_c.curTextureXOffset) * framebuffer->renderScaleFactor;2351v1 = (bounds.minV + gstate_c.curTextureYOffset) * framebuffer->renderScaleFactor;2352u2 = (bounds.maxU + gstate_c.curTextureXOffset) * framebuffer->renderScaleFactor;2353v2 = (bounds.maxV + gstate_c.curTextureYOffset) * framebuffer->renderScaleFactor;2354// We need to reapply the texture next time since we cropped UV.2355gstate_c.Dirty(DIRTY_TEXTURE_PARAMS);2356}23572358Draw::Framebuffer *depalFBO = framebufferManager_->GetTempFBO(TempFBO::DEPAL, depalWidth, framebuffer->renderHeight);2359draw_->BindTexture(0, nullptr);2360draw_->BindTexture(1, nullptr);2361draw_->BindFramebufferAsRenderTarget(depalFBO, { Draw::RPAction::DONT_CARE, Draw::RPAction::DONT_CARE, Draw::RPAction::DONT_CARE }, "Depal");2362draw_->InvalidateFramebuffer(Draw::FB_INVALIDATION_STORE, Draw::FB_DEPTH_BIT | Draw::FB_STENCIL_BIT);2363draw_->SetScissorRect(u1, v1, u2 - u1, v2 - v1);2364Draw::Viewport viewport{ 0.0f, 0.0f, (float)depalWidth, (float)framebuffer->renderHeight, 0.0f, 1.0f };2365draw_->SetViewport(viewport);23662367draw_->BindFramebufferAsTexture(framebuffer->fbo, 0, depth ? Draw::FB_DEPTH_BIT : Draw::FB_COLOR_BIT, Draw::ALL_LAYERS);2368if (clutRenderAddress_ == 0xFFFFFFFF) {2369draw_->BindTexture(1, clutTexture.texture);2370} else {2371draw_->BindFramebufferAsTexture(dynamicClutFbo_, 1, Draw::FB_COLOR_BIT, 0);2372}2373Draw::SamplerState *nearest = textureShaderCache_->GetSampler(false);2374Draw::SamplerState *clutSampler = textureShaderCache_->GetSampler(smoothedDepal);2375draw_->BindSamplerStates(0, 1, &nearest);2376draw_->BindSamplerStates(1, 1, &clutSampler);23772378draw2D_->Blit(textureShader, u1, v1, u2, v2, u1, v1, u2, v2, framebuffer->renderWidth, framebuffer->renderHeight, depalWidth, framebuffer->renderHeight, false, framebuffer->renderScaleFactor);23792380gpuStats.numDepal++;23812382gstate_c.curTextureWidth = texWidth;2383gstate_c.Dirty(DIRTY_UVSCALEOFFSET);23842385draw_->BindTexture(0, nullptr);2386framebufferManager_->RebindFramebuffer("ApplyTextureFramebuffer");23872388draw_->BindFramebufferAsTexture(depalFBO, 0, Draw::FB_COLOR_BIT, Draw::ALL_LAYERS);2389BoundFramebufferTexture();23902391const u32 bytesPerColor = clutFormat == GE_CMODE_32BIT_ABGR8888 ? sizeof(u32) : sizeof(u16);2392const u32 clutTotalColors = clutMaxBytes_ / bytesPerColor;23932394CheckAlphaResult alphaStatus = CheckCLUTAlpha((const uint8_t *)clutBufRaw_, clutFormat, clutTotalColors);2395gstate_c.SetTextureFullAlpha(alphaStatus == CHECKALPHA_FULL);23962397draw_->Invalidate(InvalidationFlags::CACHED_RENDER_STATE);2398shaderManager_->DirtyLastShader();2399} else {2400framebufferManager_->RebindFramebuffer("ApplyTextureFramebuffer");2401framebufferManager_->BindFramebufferAsColorTexture(0, framebuffer, BINDFBCOLOR_MAY_COPY_WITH_UV | BINDFBCOLOR_APPLY_TEX_OFFSET, Draw::ALL_LAYERS);2402BoundFramebufferTexture();24032404gstate_c.SetUseShaderDepal(ShaderDepalMode::OFF);2405gstate_c.SetTextureFullAlpha(gstate.getTextureFormat() == GE_TFMT_5650);2406}24072408SamplerCacheKey samplerKey = GetFramebufferSamplingParams(framebuffer->bufferWidth, framebuffer->bufferHeight);2409ApplySamplingParams(samplerKey);24102411// Since we've drawn using thin3d, might need these.2412gstate_c.Dirty(DIRTY_ALL_RENDER_STATE);2413}24142415// Applies depal to a normal (non-framebuffer) texture, pre-decoded to CLUT8 format.2416void TextureCacheCommon::ApplyTextureDepal(TexCacheEntry *entry) {2417uint32_t clutMode = gstate.clutformat & 0xFFFFFF;24182419switch (entry->format) {2420case GE_TFMT_CLUT4:2421case GE_TFMT_CLUT8:2422break; // These are OK2423default:2424_dbg_assert_(false);2425return;2426}24272428const GEPaletteFormat clutFormat = gstate.getClutPaletteFormat();2429u32 depthUpperBits = 0;24302431// The CLUT texture is dynamic, it's the framebuffer pointed to by clutRenderAddress.2432// Instead of texturing directly from that, we copy to a temporary CLUT texture.2433GEBufferFormat expectedCLUTBufferFormat = (GEBufferFormat)clutFormat; // All entries from clutFormat correspond directly to buffer formats.24342435// OK, figure out what format we want our framebuffer in, so it can be reinterpreted if needed.2436// If no reinterpretation is needed, we'll automatically just get a copy shader.2437float scaleFactorX = 1.0f;2438Draw2DPipeline *reinterpret = framebufferManager_->GetReinterpretPipeline(clutRenderFormat_, expectedCLUTBufferFormat, &scaleFactorX);2439framebufferManager_->BlitUsingRaster(2440dynamicClutTemp_, 0.0f, 0.0f, 512.0f, 1.0f, dynamicClutFbo_, 0.0f, 0.0f, scaleFactorX * 512.0f, 1.0f, false, 1.0f, reinterpret, "reinterpret_clut");24412442Draw2DPipeline *textureShader = textureShaderCache_->GetDepalettizeShader(clutMode, GE_TFMT_CLUT8, GE_FORMAT_CLUT8, false, 0);2443gstate_c.SetUseShaderDepal(ShaderDepalMode::OFF);24442445int texWidth = gstate.getTextureWidth(0);2446int texHeight = gstate.getTextureHeight(0);24472448// If min is not < max, then we don't have values (wasn't set during decode.)2449const KnownVertexBounds &bounds = gstate_c.vertBounds;2450float u1 = 0.0f;2451float v1 = 0.0f;2452float u2 = texWidth;2453float v2 = texHeight;2454if (bounds.minV < bounds.maxV) {2455// These are already in pixel coords! Doesn't seem like we should multiply by texwidth/height.2456u1 = bounds.minU + gstate_c.curTextureXOffset;2457v1 = bounds.minV + gstate_c.curTextureYOffset;2458u2 = bounds.maxU + gstate_c.curTextureXOffset + 1.0f;2459v2 = bounds.maxV + gstate_c.curTextureYOffset + 1.0f;2460// We need to reapply the texture next time since we cropped UV.2461gstate_c.Dirty(DIRTY_TEXTURE_PARAMS);2462}24632464Draw::Framebuffer *depalFBO = framebufferManager_->GetTempFBO(TempFBO::DEPAL, texWidth, texHeight);2465draw_->BindTexture(0, nullptr);2466draw_->BindTexture(1, nullptr);2467draw_->BindFramebufferAsRenderTarget(depalFBO, { Draw::RPAction::DONT_CARE, Draw::RPAction::DONT_CARE, Draw::RPAction::DONT_CARE }, "Depal");2468draw_->InvalidateFramebuffer(Draw::FB_INVALIDATION_STORE, Draw::FB_DEPTH_BIT | Draw::FB_STENCIL_BIT);2469draw_->SetScissorRect(u1, v1, u2 - u1, v2 - v1);2470Draw::Viewport viewport{ 0.0f, 0.0f, (float)texWidth, (float)texHeight, 0.0f, 1.0f };2471draw_->SetViewport(viewport);24722473draw_->BindNativeTexture(0, GetNativeTextureView(entry));2474draw_->BindFramebufferAsTexture(dynamicClutFbo_, 1, Draw::FB_COLOR_BIT, 0);2475Draw::SamplerState *nearest = textureShaderCache_->GetSampler(false);2476Draw::SamplerState *clutSampler = textureShaderCache_->GetSampler(false);2477draw_->BindSamplerStates(0, 1, &nearest);2478draw_->BindSamplerStates(1, 1, &clutSampler);24792480draw2D_->Blit(textureShader, u1, v1, u2, v2, u1, v1, u2, v2, texWidth, texHeight, texWidth, texHeight, false, 1);24812482gpuStats.numDepal++;24832484gstate_c.curTextureWidth = texWidth;2485gstate_c.Dirty(DIRTY_UVSCALEOFFSET);24862487draw_->BindTexture(0, nullptr);2488framebufferManager_->RebindFramebuffer("ApplyTextureFramebuffer");24892490draw_->BindFramebufferAsTexture(depalFBO, 0, Draw::FB_COLOR_BIT, 0);2491BoundFramebufferTexture();24922493const u32 bytesPerColor = clutFormat == GE_CMODE_32BIT_ABGR8888 ? sizeof(u32) : sizeof(u16);2494const u32 clutTotalColors = clutMaxBytes_ / bytesPerColor;24952496// We don't know about alpha at all.2497gstate_c.SetTextureFullAlpha(false);24982499draw_->Invalidate(InvalidationFlags::CACHED_RENDER_STATE);2500shaderManager_->DirtyLastShader();25012502SamplerCacheKey samplerKey = GetFramebufferSamplingParams(texWidth, texHeight);2503ApplySamplingParams(samplerKey);25042505// Since we've drawn using thin3d, might need these.2506gstate_c.Dirty(DIRTY_ALL_RENDER_STATE);2507}25082509void TextureCacheCommon::Clear(bool delete_them) {2510textureShaderCache_->Clear();25112512ForgetLastTexture();2513for (TexCache::iterator iter = cache_.begin(); iter != cache_.end(); ++iter) {2514ReleaseTexture(iter->second.get(), delete_them);2515}2516// In case the setting was changed, we ALWAYS clear the secondary cache (enabled or not.)2517for (TexCache::iterator iter = secondCache_.begin(); iter != secondCache_.end(); ++iter) {2518ReleaseTexture(iter->second.get(), delete_them);2519}2520if (cache_.size() + secondCache_.size()) {2521INFO_LOG(Log::G3D, "Texture cached cleared from %i textures", (int)(cache_.size() + secondCache_.size()));2522cache_.clear();2523secondCache_.clear();2524cacheSizeEstimate_ = 0;2525secondCacheSizeEstimate_ = 0;2526}2527videos_.clear();25282529if (dynamicClutFbo_) {2530dynamicClutFbo_->Release();2531dynamicClutFbo_ = nullptr;2532}2533if (dynamicClutTemp_) {2534dynamicClutTemp_->Release();2535dynamicClutTemp_ = nullptr;2536}2537}25382539void TextureCacheCommon::DeleteTexture(TexCache::iterator it) {2540ReleaseTexture(it->second.get(), true);2541cacheSizeEstimate_ -= EstimateTexMemoryUsage(it->second.get());2542cache_.erase(it);2543}25442545bool TextureCacheCommon::CheckFullHash(TexCacheEntry *entry, bool &doDelete) {2546int w = gstate.getTextureWidth(0);2547int h = gstate.getTextureHeight(0);2548bool isVideo = IsVideo(entry->addr);2549bool swizzled = gstate.isTextureSwizzled();25502551// Don't even check the texture, just assume it has changed.2552if (isVideo && g_Config.bTextureBackoffCache) {2553// Attempt to ensure the hash doesn't incorrectly match in if the video stops.2554entry->fullhash = (entry->fullhash + 0xA535A535) * 11 + (entry->fullhash & 4);2555return false;2556}25572558u32 fullhash;2559{2560PROFILE_THIS_SCOPE("texhash");2561fullhash = QuickTexHash(replacer_, entry->addr, entry->bufw, w, h, swizzled, GETextureFormat(entry->format), entry);2562}25632564if (fullhash == entry->fullhash) {2565if (g_Config.bTextureBackoffCache && !isVideo) {2566if (entry->GetHashStatus() != TexCacheEntry::STATUS_HASHING && entry->numFrames > TexCacheEntry::FRAMES_REGAIN_TRUST) {2567// Reset to STATUS_HASHING.2568entry->SetHashStatus(TexCacheEntry::STATUS_HASHING);2569entry->status &= ~TexCacheEntry::STATUS_CHANGE_FREQUENT;2570}2571} else if (entry->numFrames > TEXCACHE_FRAME_CHANGE_FREQUENT_REGAIN_TRUST) {2572entry->status &= ~TexCacheEntry::STATUS_CHANGE_FREQUENT;2573}25742575return true;2576}25772578// Don't give up just yet. Let's try the secondary cache if it's been invalidated before.2579if (PSP_CoreParameter().compat.flags().SecondaryTextureCache) {2580// Don't forget this one was unreliable (in case we match a secondary entry.)2581entry->status |= TexCacheEntry::STATUS_UNRELIABLE;25822583// If it's failed a bunch of times, then the second cache is just wasting time and VRAM.2584// In that case, skip.2585if (entry->numInvalidated > 2 && entry->numInvalidated < 128 && !lowMemoryMode_) {2586// We have a new hash: look for that hash in the secondary cache.2587u64 secondKey = fullhash | (u64)entry->cluthash << 32;2588TexCache::iterator secondIter = secondCache_.find(secondKey);2589if (secondIter != secondCache_.end()) {2590// Found it, but does it match our current params? If not, abort.2591TexCacheEntry *secondEntry = secondIter->second.get();2592if (secondEntry->Matches(entry->dim, entry->format, entry->maxLevel)) {2593// Reset the numInvalidated value lower, we got a match.2594if (entry->numInvalidated > 8) {2595--entry->numInvalidated;2596}25972598// Now just use our archived texture, instead of entry.2599nextTexture_ = secondEntry;2600return true;2601}2602} else {2603// It wasn't found, so we're about to throw away the entry and rebuild a texture.2604// Let's save this in the secondary cache in case it gets used again.2605secondKey = entry->fullhash | ((u64)entry->cluthash << 32);2606secondCacheSizeEstimate_ += EstimateTexMemoryUsage(entry);26072608// If the entry already exists in the secondary texture cache, drop it nicely.2609auto oldIter = secondCache_.find(secondKey);2610if (oldIter != secondCache_.end()) {2611ReleaseTexture(oldIter->second.get(), true);2612}26132614// Archive the entire texture entry as is, since we'll use its params if it is seen again.2615// We keep parameters on the current entry, since we are STILL building a new texture here.2616secondCache_[secondKey].reset(new TexCacheEntry(*entry));26172618// Make sure we don't delete the texture we just archived.2619entry->texturePtr = nullptr;2620doDelete = false;2621}2622}2623}26242625// We know it failed, so update the full hash right away.2626entry->fullhash = fullhash;2627return false;2628}26292630void TextureCacheCommon::Invalidate(u32 addr, int size, GPUInvalidationType type) {2631// They could invalidate inside the texture, let's just give a bit of leeway.2632// TODO: Keep track of the largest texture size in bytes, and use that instead of this2633// humongous unrealistic value.26342635const int LARGEST_TEXTURE_SIZE = 512 * 512 * 4;26362637addr &= 0x3FFFFFFF;2638const u32 addr_end = addr + size;26392640if (type == GPU_INVALIDATE_ALL) {2641// This is an active signal from the game that something in the texture cache may have changed.2642gstate_c.Dirty(DIRTY_TEXTURE_IMAGE);2643} else {2644// Do a quick check to see if the current texture could potentially be in range.2645const u32 currentAddr = gstate.getTextureAddress(0);2646// TODO: This can be made tighter.2647if (addr_end >= currentAddr && addr < currentAddr + LARGEST_TEXTURE_SIZE) {2648gstate_c.Dirty(DIRTY_TEXTURE_IMAGE);2649}2650}26512652// If we're hashing every use, without backoff, then this isn't needed.2653if (!g_Config.bTextureBackoffCache && type != GPU_INVALIDATE_FORCE) {2654return;2655}26562657const u64 startKey = (u64)(addr - LARGEST_TEXTURE_SIZE) << 32;2658u64 endKey = (u64)(addr + size + LARGEST_TEXTURE_SIZE) << 32;2659if (endKey < startKey) {2660endKey = (u64)-1;2661}26622663for (TexCache::iterator iter = cache_.lower_bound(startKey), end = cache_.upper_bound(endKey); iter != end; ++iter) {2664auto &entry = iter->second;2665u32 texAddr = entry->addr;2666// Intentional underestimate here.2667u32 texEnd = entry->addr + entry->SizeInRAM() / 2;26682669// Quick check for overlap. Yes the check is right.2670if (addr < texEnd && addr_end > texAddr) {2671if (entry->GetHashStatus() == TexCacheEntry::STATUS_RELIABLE) {2672entry->SetHashStatus(TexCacheEntry::STATUS_HASHING);2673}2674if (type == GPU_INVALIDATE_FORCE) {2675// Just random values to force the hash not to match.2676entry->fullhash = (entry->fullhash ^ 0x12345678) + 13;2677entry->minihash = (entry->minihash ^ 0x89ABCDEF) + 89;2678}2679if (type != GPU_INVALIDATE_ALL) {2680gpuStats.numTextureInvalidations++;2681// Start it over from 0 (unless it's safe.)2682entry->numFrames = type == GPU_INVALIDATE_SAFE ? 256 : 0;2683if (type == GPU_INVALIDATE_SAFE) {2684u32 diff = gpuStats.numFlips - entry->lastFrame;2685// We still need to mark if the texture is frequently changing, even if it's safely changing.2686if (diff < TEXCACHE_FRAME_CHANGE_FREQUENT) {2687entry->status |= TexCacheEntry::STATUS_CHANGE_FREQUENT;2688}2689}2690entry->framesUntilNextFullHash = 0;2691} else {2692entry->invalidHint++;2693}2694}2695}2696}26972698void TextureCacheCommon::InvalidateAll(GPUInvalidationType /*unused*/) {2699// If we're hashing every use, without backoff, then this isn't needed.2700if (!g_Config.bTextureBackoffCache) {2701return;2702}27032704if (timesInvalidatedAllThisFrame_ > 5) {2705return;2706}2707timesInvalidatedAllThisFrame_++;27082709for (TexCache::iterator iter = cache_.begin(), end = cache_.end(); iter != end; ++iter) {2710if (iter->second->GetHashStatus() == TexCacheEntry::STATUS_RELIABLE) {2711iter->second->SetHashStatus(TexCacheEntry::STATUS_HASHING);2712}2713iter->second->invalidHint++;2714}2715}27162717void TextureCacheCommon::ClearNextFrame() {2718clearCacheNextFrame_ = true;2719}27202721std::string AttachCandidate::ToString() const {2722return StringFromFormat("[%s seq:%d rel:%d C:%08x/%d(%s) Z:%08x/%d X:%d Y:%d reint: %s]",2723RasterChannelToString(this->channel),2724this->channel == RASTER_COLOR ? this->fb->colorBindSeq : this->fb->depthBindSeq,2725this->relevancy,2726this->fb->fb_address, this->fb->fb_stride, GeBufferFormatToString(this->fb->fb_format),2727this->fb->z_address, this->fb->z_stride,2728this->match.xOffset, this->match.yOffset, this->match.reinterpret ? "true" : "false");2729}27302731bool TextureCacheCommon::PrepareBuildTexture(BuildTexturePlan &plan, TexCacheEntry *entry) {2732gpuStats.numTexturesDecoded++;27332734// For the estimate, we assume cluts always point to 8888 for simplicity.2735cacheSizeEstimate_ += EstimateTexMemoryUsage(entry);27362737plan.badMipSizes = false;2738// maxLevel here is the max level to upload. Not the count.2739plan.levelsToLoad = entry->maxLevel + 1;2740for (int i = 0; i < plan.levelsToLoad; i++) {2741// If encountering levels pointing to nothing, adjust max level.2742u32 levelTexaddr = gstate.getTextureAddress(i);2743if (!Memory::IsValidAddress(levelTexaddr)) {2744plan.levelsToLoad = i;2745break;2746}27472748// If size reaches 1, stop, and override maxlevel.2749int tw = gstate.getTextureWidth(i);2750int th = gstate.getTextureHeight(i);2751if (tw == 1 || th == 1) {2752plan.levelsToLoad = i + 1; // next level is assumed to be invalid2753break;2754}27552756if (i > 0) {2757int lastW = gstate.getTextureWidth(i - 1);2758int lastH = gstate.getTextureHeight(i - 1);27592760if (gstate_c.Use(GPU_USE_TEXTURE_LOD_CONTROL)) {2761if (tw != 1 && tw != (lastW >> 1))2762plan.badMipSizes = true;2763else if (th != 1 && th != (lastH >> 1))2764plan.badMipSizes = true;2765}2766}2767}27682769plan.scaleFactor = standardScaleFactor_;2770plan.depth = 1;27712772// Rachet down scale factor in low-memory mode.2773// TODO: I think really we should just turn it off?2774if (lowMemoryMode_ && !plan.hardwareScaling) {2775// Keep it even, though, just in case of npot troubles.2776plan.scaleFactor = plan.scaleFactor > 4 ? 4 : (plan.scaleFactor > 2 ? 2 : 1);2777}27782779bool isFakeMipmapChange = false;2780if (plan.badMipSizes) {2781isFakeMipmapChange = IsFakeMipmapChange();27822783// Check for pure 3D texture.2784int tw = gstate.getTextureWidth(0);2785int th = gstate.getTextureHeight(0);2786bool pure3D = true;2787for (int i = 0; i < plan.levelsToLoad; i++) {2788if (gstate.getTextureWidth(i) != gstate.getTextureWidth(0) || gstate.getTextureHeight(i) != gstate.getTextureHeight(0)) {2789pure3D = false;2790break;2791}2792}27932794// Check early for the degenerate case from Tactics Ogre.2795if (pure3D && plan.levelsToLoad == 2 && gstate.getTextureAddress(0) == gstate.getTextureAddress(1)) {2796// Simply treat it as a regular 2D texture, no fake mipmaps or anything.2797// levelsToLoad/Create gets set to 1 on the way out from the surrounding if.2798isFakeMipmapChange = false;2799pure3D = false;2800} else if (isFakeMipmapChange) {2801// We don't want to create a volume texture, if this is a "fake mipmap change".2802// In practice due to the compat flag, the only time we end up here is in JP Tactics Ogre.2803pure3D = false;2804}28052806if (pure3D && draw_->GetDeviceCaps().texture3DSupported) {2807plan.depth = plan.levelsToLoad;2808plan.scaleFactor = 1;2809}28102811plan.levelsToLoad = 1;2812plan.levelsToCreate = 1;2813}28142815if (plan.hardwareScaling) {2816plan.scaleFactor = shaderScaleFactor_;2817}28182819// We generate missing mipmaps from maxLevel+1 up to this level. maxLevel can get overwritten below2820// such as when using replacement textures - but let's keep the same amount of levels for generation.2821// Not all backends will generate mipmaps, and in GL we can't really control the number of levels.2822plan.levelsToCreate = plan.levelsToLoad;28232824plan.w = gstate.getTextureWidth(0);2825plan.h = gstate.getTextureHeight(0);28262827bool isPPGETexture = entry->addr >= PSP_GetKernelMemoryBase() && entry->addr < PSP_GetKernelMemoryEnd();28282829// Don't scale the PPGe texture.2830if (isPPGETexture) {2831plan.scaleFactor = 1;2832} else if (!g_DoubleTextureCoordinates) {2833// Refuse to load invalid-ly sized textures, which can happen through display list corruption.2834// However, turns out some games uses huge textures for font rendering for no apparent reason.2835// These will only work correctly in the top 512x512 part. So, I've increased the threshold quite a bit.2836// We probably should handle these differently, by clamping the texture size and texture coordinates, but meh.2837if (plan.w > 2048 || plan.h > 2048) {2838ERROR_LOG(Log::G3D, "Bad texture dimensions: %dx%d", plan.w, plan.h);2839return false;2840}2841}28422843if (PSP_CoreParameter().compat.flags().ForceLowerResolutionForEffectsOn && gstate.FrameBufStride() < 0x1E0) {2844// A bit of an esoteric workaround - force off upscaling for static textures that participate directly in small-resolution framebuffer effects.2845// This fixes the water in Outrun/DiRT 2 with upscaling enabled.2846plan.scaleFactor = 1;2847}28482849if ((entry->status & TexCacheEntry::STATUS_CHANGE_FREQUENT) != 0 && plan.scaleFactor != 1 && plan.slowScaler) {2850// Remember for later that we /wanted/ to scale this texture.2851entry->status |= TexCacheEntry::STATUS_TO_SCALE;2852plan.scaleFactor = 1;2853}28542855if (plan.scaleFactor != 1) {2856if (texelsScaledThisFrame_ >= TEXCACHE_MAX_TEXELS_SCALED && plan.slowScaler) {2857entry->status |= TexCacheEntry::STATUS_TO_SCALE;2858plan.scaleFactor = 1;2859} else {2860entry->status &= ~TexCacheEntry::STATUS_TO_SCALE;2861entry->status |= TexCacheEntry::STATUS_IS_SCALED_OR_REPLACED;2862texelsScaledThisFrame_ += plan.w * plan.h;2863}2864}28652866plan.isVideo = IsVideo(entry->addr);28672868// TODO: Support reading actual mip levels for upscaled images, instead of just generating them.2869// Maybe can just remove this check?2870if (plan.scaleFactor > 1) {2871plan.levelsToLoad = 1;28722873bool enableVideoUpscaling = false;28742875if (!enableVideoUpscaling && plan.isVideo) {2876plan.scaleFactor = 1;2877plan.levelsToCreate = 1;2878}2879}28802881bool canReplace = !isPPGETexture;2882if (entry->status & TexCacheEntry::TexStatus::STATUS_CLUT_GPU) {2883_dbg_assert_(entry->format == GE_TFMT_CLUT4 || entry->format == GE_TFMT_CLUT8);2884plan.decodeToClut8 = true;2885// We only support 1 mip level when doing CLUT on GPU for now.2886// Supporting more would be possible, just not very interesting until we need it.2887plan.levelsToCreate = 1;2888plan.levelsToLoad = 1;2889plan.maxPossibleLevels = 1;2890plan.scaleFactor = 1;2891plan.saveTexture = false; // Can't yet save these properly.2892canReplace = false;2893} else {2894plan.decodeToClut8 = false;2895}28962897if (canReplace) {2898// This is the "trigger point" for replacement.2899plan.replaced = FindReplacement(entry, &plan.w, &plan.h, &plan.depth);2900plan.doReplace = plan.replaced ? plan.replaced->State() == ReplacementState::ACTIVE : false;2901} else {2902plan.replaced = nullptr;2903plan.doReplace = false;2904}29052906// NOTE! Last chance to change scale factor here!29072908plan.saveTexture = false;2909if (plan.doReplace) {2910// We're replacing, so we won't scale.2911plan.scaleFactor = 1;2912// We're ignoring how many levels were specified - instead we just load all available from the replacer.2913plan.levelsToLoad = plan.replaced->NumLevels();2914plan.levelsToCreate = plan.levelsToLoad; // Or more, if we wanted to generate.2915plan.badMipSizes = false;2916// But, we still need to create the texture at a larger size.2917plan.replaced->GetSize(0, &plan.createW, &plan.createH);2918} else {2919if (replacer_.SaveEnabled() && !plan.doReplace && plan.depth == 1 && canReplace) {2920ReplacedTextureDecodeInfo replacedInfo;2921// TODO: Do we handle the race where a replacement becomes valid AFTER this but before we save?2922replacedInfo.cachekey = entry->CacheKey();2923replacedInfo.hash = entry->fullhash;2924replacedInfo.addr = entry->addr;2925replacedInfo.isFinal = (entry->status & TexCacheEntry::STATUS_TO_SCALE) == 0;2926replacedInfo.isVideo = plan.isVideo;2927replacedInfo.fmt = Draw::DataFormat::R8G8B8A8_UNORM;2928plan.saveTexture = replacer_.WillSave(replacedInfo);2929}2930plan.createW = plan.w * plan.scaleFactor;2931plan.createH = plan.h * plan.scaleFactor;2932}29332934// Always load base level texture here2935plan.baseLevelSrc = 0;2936if (isFakeMipmapChange) {2937// NOTE: Since the level is not part of the cache key, we assume it never changes.2938plan.baseLevelSrc = std::max(0, gstate.getTexLevelOffset16() / 16);2939// Tactics Ogre: If this is an odd level and it has the same texture address the below even level,2940// let's just say it's the even level for the purposes of replacement.2941// I assume this is done to avoid blending between levels accidentally?2942// The Japanese version of Tactics Ogre uses multiple of these "double" levels to fit more characters.2943if ((plan.baseLevelSrc & 1) && gstate.getTextureAddress(plan.baseLevelSrc) == gstate.getTextureAddress(plan.baseLevelSrc & ~1)) {2944plan.baseLevelSrc &= ~1;2945}2946plan.levelsToCreate = 1;2947plan.levelsToLoad = 1;2948// Make sure we already decided not to do a 3D texture above.2949_dbg_assert_(plan.depth == 1);2950}29512952if (plan.isVideo || plan.depth != 1 || plan.decodeToClut8) {2953plan.levelsToLoad = 1;2954plan.maxPossibleLevels = 1;2955} else {2956plan.maxPossibleLevels = log2i(std::max(plan.createW, plan.createH)) + 1;2957}29582959if (plan.levelsToCreate == 1) {2960entry->status |= TexCacheEntry::STATUS_NO_MIPS;2961} else {2962entry->status &= ~TexCacheEntry::STATUS_NO_MIPS;2963}29642965// Will be filled in again during decode.2966entry->status &= ~TexCacheEntry::STATUS_ALPHA_MASK;2967return true;2968}29692970// Passing 0 into dataSize will disable checking.2971void TextureCacheCommon::LoadTextureLevel(TexCacheEntry &entry, uint8_t *data, size_t dataSize, int stride, BuildTexturePlan &plan, int srcLevel, Draw::DataFormat dstFmt, TexDecodeFlags texDecFlags) {2972int w = gstate.getTextureWidth(srcLevel);2973int h = gstate.getTextureHeight(srcLevel);29742975PROFILE_THIS_SCOPE("decodetex");29762977if (plan.doReplace) {2978plan.replaced->GetSize(srcLevel, &w, &h);2979double replaceStart = time_now_d();2980plan.replaced->CopyLevelTo(srcLevel, data, dataSize, stride);2981replacementTimeThisFrame_ += time_now_d() - replaceStart;2982} else {2983GETextureFormat tfmt = (GETextureFormat)entry.format;2984GEPaletteFormat clutformat = gstate.getClutPaletteFormat();2985u32 texaddr = gstate.getTextureAddress(srcLevel);2986const int bufw = GetTextureBufw(srcLevel, texaddr, tfmt);2987u32 *pixelData;2988int decPitch;2989if (plan.scaleFactor > 1) {2990tmpTexBufRearrange_.resize(std::max(bufw, w) * h);2991pixelData = tmpTexBufRearrange_.data();2992// We want to end up with a neatly packed texture for scaling.2993decPitch = w * 4;2994} else {2995pixelData = (u32 *)data;2996decPitch = stride;2997}29982999if (!gstate_c.Use(GPU_USE_16BIT_FORMATS) || dstFmt == Draw::DataFormat::R8G8B8A8_UNORM) {3000texDecFlags |= TexDecodeFlags::EXPAND32;3001}3002if (entry.status & TexCacheEntry::STATUS_CLUT_GPU) {3003texDecFlags |= TexDecodeFlags::TO_CLUT8;3004}30053006CheckAlphaResult alphaResult = DecodeTextureLevel((u8 *)pixelData, decPitch, tfmt, clutformat, texaddr, srcLevel, bufw, texDecFlags);3007entry.SetAlphaStatus(alphaResult, srcLevel);30083009int scaledW = w, scaledH = h;3010if (plan.scaleFactor > 1) {3011// Note that this updates w and h!3012scaler_.ScaleAlways((u32 *)data, pixelData, w, h, &scaledW, &scaledH, plan.scaleFactor);3013pixelData = (u32 *)data;30143015decPitch = scaledW * sizeof(u32);30163017if (decPitch != stride) {3018// Rearrange in place to match the requested pitch.3019// (it can only be larger than w * bpp, and a match is likely.)3020// Note! This is bad because it reads the mapped memory! TODO: Look into if DX9 does this right.3021for (int y = scaledH - 1; y >= 0; --y) {3022memcpy((u8 *)data + stride * y, (u8 *)data + decPitch * y, scaledW *4);3023}3024decPitch = stride;3025}3026}30273028if (plan.saveTexture && !lowMemoryMode_) {3029ReplacedTextureDecodeInfo replacedInfo;3030replacedInfo.cachekey = entry.CacheKey();3031replacedInfo.hash = entry.fullhash;3032replacedInfo.addr = entry.addr;3033replacedInfo.isVideo = IsVideo(entry.addr);3034replacedInfo.isFinal = (entry.status & TexCacheEntry::STATUS_TO_SCALE) == 0;3035replacedInfo.fmt = dstFmt;30363037// NOTE: Reading the decoded texture here may be very slow, if we just wrote it to write-combined memory.3038replacer_.NotifyTextureDecoded(plan.replaced, replacedInfo, pixelData, decPitch, srcLevel, w, h, scaledW, scaledH);3039}3040}3041}30423043CheckAlphaResult TextureCacheCommon::CheckCLUTAlpha(const uint8_t *pixelData, GEPaletteFormat clutFormat, int w) {3044switch (clutFormat) {3045case GE_CMODE_16BIT_ABGR4444:3046return CheckAlpha16((const u16 *)pixelData, w, 0xF000);3047case GE_CMODE_16BIT_ABGR5551:3048return CheckAlpha16((const u16 *)pixelData, w, 0x8000);3049case GE_CMODE_16BIT_BGR5650:3050// Never has any alpha.3051return CHECKALPHA_FULL;3052default:3053return CheckAlpha32((const u32 *)pixelData, w, 0xFF000000);3054}3055}305630573058