CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
hrydgard

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: hrydgard/ppsspp
Path: blob/master/GPU/Common/TextureCacheCommon.cpp
Views: 1401
1
// Copyright (c) 2013- PPSSPP Project.
2
3
// This program is free software: you can redistribute it and/or modify
4
// it under the terms of the GNU General Public License as published by
5
// the Free Software Foundation, version 2.0 or later versions.
6
7
// This program is distributed in the hope that it will be useful,
8
// but WITHOUT ANY WARRANTY; without even the implied warranty of
9
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10
// GNU General Public License 2.0 for more details.
11
12
// A copy of the GPL 2.0 should have been included with the program.
13
// If not, see http://www.gnu.org/licenses/
14
15
// Official git repository and contact information can be found at
16
// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/.
17
18
#include "ppsspp_config.h"
19
20
#include <algorithm>
21
22
#include "Common/Common.h"
23
#include "Common/Data/Convert/ColorConv.h"
24
#include "Common/Data/Collections/TinySet.h"
25
#include "Common/Profiler/Profiler.h"
26
#include "Common/LogReporting.h"
27
#include "Common/MemoryUtil.h"
28
#include "Common/StringUtils.h"
29
#include "Common/TimeUtil.h"
30
#include "Common/Math/math_util.h"
31
#include "Common/GPU/thin3d.h"
32
#include "Core/HDRemaster.h"
33
#include "Core/Config.h"
34
#include "Core/Debugger/MemBlockInfo.h"
35
#include "Core/System.h"
36
#include "GPU/Common/FramebufferManagerCommon.h"
37
#include "GPU/Common/TextureCacheCommon.h"
38
#include "GPU/Common/TextureDecoder.h"
39
#include "GPU/Common/ShaderId.h"
40
#include "GPU/Common/GPUStateUtils.h"
41
#include "GPU/Debugger/Debugger.h"
42
#include "GPU/Debugger/Record.h"
43
#include "GPU/GPUCommon.h"
44
#include "GPU/GPUInterface.h"
45
#include "GPU/GPUState.h"
46
#include "Core/Util/PPGeDraw.h"
47
48
#if defined(_M_SSE)
49
#include <emmintrin.h>
50
#endif
51
#if PPSSPP_ARCH(ARM_NEON)
52
#if defined(_MSC_VER) && PPSSPP_ARCH(ARM64)
53
#include <arm64_neon.h>
54
#else
55
#include <arm_neon.h>
56
#endif
57
#endif
58
59
// Videos should be updated every few frames, so we forget quickly.
60
#define VIDEO_DECIMATE_AGE 4
61
62
// If a texture hasn't been seen for this many frames, get rid of it.
63
#define TEXTURE_KILL_AGE 200
64
#define TEXTURE_KILL_AGE_LOWMEM 60
65
// Not used in lowmem mode.
66
#define TEXTURE_SECOND_KILL_AGE 100
67
// Used when there are multiple CLUT variants of a texture.
68
#define TEXTURE_KILL_AGE_CLUT 6
69
70
#define TEXTURE_CLUT_VARIANTS_MIN 6
71
72
// Try to be prime to other decimation intervals.
73
#define TEXCACHE_DECIMATION_INTERVAL 13
74
75
#define TEXCACHE_MIN_PRESSURE 16 * 1024 * 1024 // Total in VRAM
76
#define TEXCACHE_SECOND_MIN_PRESSURE 4 * 1024 * 1024
77
78
// Just for reference
79
80
// PSP Color formats:
81
// 565: BBBBBGGGGGGRRRRR
82
// 5551: ABBBBBGGGGGRRRRR
83
// 4444: AAAABBBBGGGGRRRR
84
// 8888: AAAAAAAABBBBBBBBGGGGGGGGRRRRRRRR (Bytes in memory: RGBA)
85
86
// D3D11/9 Color formats:
87
// DXGI_FORMAT_B4G4R4A4/D3DFMT_A4R4G4B4: AAAARRRRGGGGBBBB
88
// DXGI_FORMAT_B5G5R5A1/D3DFMT_A1R5G6B5: ARRRRRGGGGGBBBBB
89
// DXGI_FORMAT_B5G6R6/D3DFMT_R5G6B5: RRRRRGGGGGGBBBBB
90
// DXGI_FORMAT_B8G8R8A8: AAAAAAAARRRRRRRRGGGGGGGGBBBBBBBB (Bytes in memory: BGRA)
91
// These are Data::Format:: A4R4G4B4_PACK16, A1R5G6B5_PACK16, R5G6B5_PACK16, B8G8R8A8.
92
// So these are good matches, just with R/B swapped.
93
94
// OpenGL ES color formats:
95
// GL_UNSIGNED_SHORT_4444: BBBBGGGGRRRRAAAA (4-bit rotation)
96
// GL_UNSIGNED_SHORT_565: BBBBBGGGGGGRRRRR (match)
97
// GL_UNSIGNED_SHORT_1555: BBBBBGGGGGRRRRRA (1-bit rotation)
98
// GL_UNSIGNED_BYTE/RGBA: AAAAAAAABBBBBBBBGGGGGGGGRRRRRRRR (match)
99
// These are Data::Format:: B4G4R4A4_PACK16, B5G6R6_PACK16, B5G5R5A1_PACK16, R8G8B8A8
100
101
TextureCacheCommon::TextureCacheCommon(Draw::DrawContext *draw, Draw2D *draw2D)
102
: draw_(draw), draw2D_(draw2D), replacer_(draw) {
103
decimationCounter_ = TEXCACHE_DECIMATION_INTERVAL;
104
105
// It's only possible to have 1KB of palette entries, although we allow 2KB in a hack.
106
clutBufRaw_ = (u32 *)AllocateAlignedMemory(2048, 16);
107
clutBufConverted_ = (u32 *)AllocateAlignedMemory(2048, 16);
108
// Here we need 2KB to expand a 1KB CLUT.
109
expandClut_ = (u32 *)AllocateAlignedMemory(2048, 16);
110
111
// Zap so we get consistent behavior if the game fails to load some of the CLUT.
112
memset(clutBufRaw_, 0, 2048);
113
memset(clutBufConverted_, 0, 2048);
114
clutBuf_ = clutBufConverted_;
115
116
// These buffers will grow if necessary, but most won't need more than this.
117
tmpTexBuf32_.resize(512 * 512); // 1MB
118
tmpTexBufRearrange_.resize(512 * 512); // 1MB
119
120
textureShaderCache_ = new TextureShaderCache(draw, draw2D_);
121
}
122
123
TextureCacheCommon::~TextureCacheCommon() {
124
delete textureShaderCache_;
125
126
FreeAlignedMemory(clutBufConverted_);
127
FreeAlignedMemory(clutBufRaw_);
128
FreeAlignedMemory(expandClut_);
129
}
130
131
void TextureCacheCommon::StartFrame() {
132
ForgetLastTexture();
133
textureShaderCache_->Decimate();
134
timesInvalidatedAllThisFrame_ = 0;
135
replacementTimeThisFrame_ = 0.0;
136
137
if ((DebugOverlay)g_Config.iDebugOverlay == DebugOverlay::DEBUG_STATS) {
138
gpuStats.numReplacerTrackedTex = replacer_.GetNumTrackedTextures();
139
gpuStats.numCachedReplacedTextures = replacer_.GetNumCachedReplacedTextures();
140
}
141
142
if (texelsScaledThisFrame_) {
143
VERBOSE_LOG(Log::G3D, "Scaled %d texels", texelsScaledThisFrame_);
144
}
145
texelsScaledThisFrame_ = 0;
146
147
if (clearCacheNextFrame_) {
148
Clear(true);
149
clearCacheNextFrame_ = false;
150
} else {
151
Decimate(nullptr, false);
152
}
153
}
154
155
// Produces a signed 1.23.8 value.
156
static int TexLog2(float delta) {
157
union FloatBits {
158
float f;
159
u32 u;
160
};
161
FloatBits f;
162
f.f = delta;
163
// Use the exponent as the tex level, and the top mantissa bits for a frac.
164
// We can't support more than 8 bits of frac, so truncate.
165
int useful = (f.u >> 15) & 0xFFFF;
166
// Now offset so the exponent aligns with log2f (exp=127 is 0.)
167
return useful - 127 * 256;
168
}
169
170
SamplerCacheKey TextureCacheCommon::GetSamplingParams(int maxLevel, const TexCacheEntry *entry) {
171
SamplerCacheKey key{};
172
173
int minFilt = gstate.texfilter & 0x7;
174
key.minFilt = minFilt & 1;
175
key.mipEnable = (minFilt >> 2) & 1;
176
key.mipFilt = (minFilt >> 1) & 1;
177
key.magFilt = gstate.isMagnifyFilteringEnabled();
178
key.sClamp = gstate.isTexCoordClampedS();
179
key.tClamp = gstate.isTexCoordClampedT();
180
key.aniso = false;
181
key.texture3d = gstate_c.curTextureIs3D;
182
183
GETexLevelMode mipMode = gstate.getTexLevelMode();
184
bool autoMip = mipMode == GE_TEXLEVEL_MODE_AUTO;
185
186
// TODO: Slope mipmap bias is still not well understood.
187
float lodBias = (float)gstate.getTexLevelOffset16() * (1.0f / 16.0f);
188
if (mipMode == GE_TEXLEVEL_MODE_SLOPE) {
189
lodBias += 1.0f + TexLog2(gstate.getTextureLodSlope()) * (1.0f / 256.0f);
190
}
191
192
// If mip level is forced to zero, disable mipmapping.
193
bool noMip = maxLevel == 0 || (!autoMip && lodBias <= 0.0f);
194
if (noMip) {
195
// Enforce no mip filtering, for safety.
196
key.mipEnable = false;
197
key.mipFilt = 0;
198
lodBias = 0.0f;
199
}
200
201
if (!key.mipEnable) {
202
key.maxLevel = 0;
203
key.minLevel = 0;
204
key.lodBias = 0;
205
key.mipFilt = 0;
206
} else {
207
switch (mipMode) {
208
case GE_TEXLEVEL_MODE_AUTO:
209
key.maxLevel = maxLevel * 256;
210
key.minLevel = 0;
211
key.lodBias = (int)(lodBias * 256.0f);
212
if (gstate_c.Use(GPU_USE_ANISOTROPY) && g_Config.iAnisotropyLevel > 0) {
213
key.aniso = true;
214
}
215
break;
216
case GE_TEXLEVEL_MODE_CONST:
217
case GE_TEXLEVEL_MODE_UNKNOWN:
218
key.maxLevel = (int)(lodBias * 256.0f);
219
key.minLevel = (int)(lodBias * 256.0f);
220
key.lodBias = 0;
221
break;
222
case GE_TEXLEVEL_MODE_SLOPE:
223
// It's incorrect to use the slope as a bias. Instead it should be passed
224
// into the shader directly as an explicit lod level, with the bias on top. For now, we just kill the
225
// lodBias in this mode, working around #9772.
226
key.maxLevel = maxLevel * 256;
227
key.minLevel = 0;
228
key.lodBias = 0;
229
break;
230
}
231
}
232
233
// Video bilinear override
234
if (!key.magFilt && entry != nullptr && IsVideo(entry->addr)) {
235
// Enforce bilinear filtering on magnification.
236
key.magFilt = 1;
237
}
238
239
// Filtering overrides from replacements or settings.
240
TextureFiltering forceFiltering = TEX_FILTER_AUTO;
241
bool useReplacerFiltering = false;
242
if (entry && replacer_.Enabled() && entry->replacedTexture) {
243
// If replacement textures have multiple mip levels, enforce mip filtering.
244
if (entry->replacedTexture->State() == ReplacementState::ACTIVE && entry->replacedTexture->NumLevels() > 1) {
245
key.mipEnable = true;
246
key.mipFilt = 1;
247
key.maxLevel = 9 * 256;
248
if (gstate_c.Use(GPU_USE_ANISOTROPY) && g_Config.iAnisotropyLevel > 0) {
249
key.aniso = true;
250
}
251
}
252
useReplacerFiltering = entry->replacedTexture->ForceFiltering(&forceFiltering);
253
}
254
if (!useReplacerFiltering) {
255
switch (g_Config.iTexFiltering) {
256
case TEX_FILTER_AUTO:
257
// Follow what the game wants. We just do a single heuristic change to avoid bleeding of wacky color test colors
258
// in higher resolution (used by some games for sprites, and they accidentally have linear filter on).
259
if (gstate.isModeThrough() && g_Config.iInternalResolution != 1) {
260
bool uglyColorTest = gstate.isColorTestEnabled() && !IsColorTestTriviallyTrue() && gstate.getColorTestRef() != 0;
261
if (uglyColorTest)
262
forceFiltering = TEX_FILTER_FORCE_NEAREST;
263
}
264
if (gstate_c.pixelMapped) {
265
forceFiltering = TEX_FILTER_FORCE_NEAREST;
266
}
267
break;
268
case TEX_FILTER_FORCE_LINEAR:
269
// Override to linear filtering if there's no alpha or color testing going on.
270
if ((!gstate.isColorTestEnabled() || IsColorTestTriviallyTrue()) &&
271
(!gstate.isAlphaTestEnabled() || IsAlphaTestTriviallyTrue())) {
272
forceFiltering = TEX_FILTER_FORCE_LINEAR;
273
}
274
break;
275
case TEX_FILTER_FORCE_NEAREST:
276
// Just force to nearest without checks. Safe (but ugly).
277
forceFiltering = TEX_FILTER_FORCE_NEAREST;
278
break;
279
case TEX_FILTER_AUTO_MAX_QUALITY:
280
default:
281
forceFiltering = TEX_FILTER_AUTO_MAX_QUALITY;
282
if (gstate.isModeThrough() && g_Config.iInternalResolution != 1) {
283
bool uglyColorTest = gstate.isColorTestEnabled() && !IsColorTestTriviallyTrue() && gstate.getColorTestRef() != 0;
284
if (uglyColorTest)
285
forceFiltering = TEX_FILTER_FORCE_NEAREST;
286
}
287
if (gstate_c.pixelMapped) {
288
forceFiltering = TEX_FILTER_FORCE_NEAREST;
289
}
290
break;
291
}
292
}
293
294
switch (forceFiltering) {
295
case TEX_FILTER_AUTO:
296
break;
297
case TEX_FILTER_FORCE_LINEAR:
298
key.magFilt = 1;
299
key.minFilt = 1;
300
key.mipFilt = 1;
301
break;
302
case TEX_FILTER_FORCE_NEAREST:
303
key.magFilt = 0;
304
key.minFilt = 0;
305
break;
306
case TEX_FILTER_AUTO_MAX_QUALITY:
307
// NOTE: We do not override magfilt here. If a game should have pixellated filtering,
308
// let it keep it. But we do enforce minification and mipmap filtering and max out the level.
309
// Later we'll also auto-generate any missing mipmaps.
310
key.minFilt = 1;
311
key.mipFilt = 1;
312
key.maxLevel = 9 * 256;
313
key.lodBias = 0.0f;
314
if (gstate_c.Use(GPU_USE_ANISOTROPY) && g_Config.iAnisotropyLevel > 0) {
315
key.aniso = true;
316
}
317
break;
318
}
319
320
return key;
321
}
322
323
SamplerCacheKey TextureCacheCommon::GetFramebufferSamplingParams(u16 bufferWidth, u16 bufferHeight) {
324
SamplerCacheKey key = GetSamplingParams(0, nullptr);
325
326
// In case auto max quality was on, restore min filt. Another fix for water in Outrun.
327
if (g_Config.iTexFiltering == TEX_FILTER_AUTO_MAX_QUALITY) {
328
int minFilt = gstate.texfilter & 0x7;
329
key.minFilt = minFilt & 1;
330
}
331
332
// Kill any mipmapping settings.
333
key.mipEnable = false;
334
key.mipFilt = false;
335
key.aniso = 0.0f;
336
key.maxLevel = 0.0f;
337
key.lodBias = 0.0f;
338
339
// Often the framebuffer will not match the texture size. We'll wrap/clamp in the shader in that case.
340
int w = gstate.getTextureWidth(0);
341
int h = gstate.getTextureHeight(0);
342
if (w != bufferWidth || h != bufferHeight) {
343
key.sClamp = true;
344
key.tClamp = true;
345
}
346
return key;
347
}
348
349
void TextureCacheCommon::UpdateMaxSeenV(TexCacheEntry *entry, bool throughMode) {
350
// If the texture is >= 512 pixels tall...
351
if (entry->dim >= 0x900) {
352
if (entry->cluthash != 0 && entry->maxSeenV == 0) {
353
const u64 cachekeyMin = (u64)(entry->addr & 0x3FFFFFFF) << 32;
354
const u64 cachekeyMax = cachekeyMin + (1ULL << 32);
355
for (auto it = cache_.lower_bound(cachekeyMin), end = cache_.upper_bound(cachekeyMax); it != end; ++it) {
356
// They should all be the same, just make sure we take any that has already increased.
357
// This is for a new texture.
358
if (it->second->maxSeenV != 0) {
359
entry->maxSeenV = it->second->maxSeenV;
360
break;
361
}
362
}
363
}
364
365
// Texture scale/offset and gen modes don't apply in through.
366
// So we can optimize how much of the texture we look at.
367
if (throughMode) {
368
if (entry->maxSeenV == 0 && gstate_c.vertBounds.maxV > 0) {
369
// Let's not hash less than 272, we might use more later and have to rehash. 272 is very common.
370
entry->maxSeenV = std::max((u16)272, gstate_c.vertBounds.maxV);
371
} else if (gstate_c.vertBounds.maxV > entry->maxSeenV) {
372
// The max height changed, so we're better off hashing the entire thing.
373
entry->maxSeenV = 512;
374
entry->status |= TexCacheEntry::STATUS_FREE_CHANGE;
375
}
376
} else {
377
// Otherwise, we need to reset to ensure we use the whole thing.
378
// Can't tell how much is used.
379
// TODO: We could tell for texcoord UV gen, and apply scale to max?
380
entry->maxSeenV = 512;
381
}
382
383
// We need to keep all CLUT variants in sync so we detect changes properly.
384
// See HandleTextureChange / STATUS_CLUT_RECHECK.
385
if (entry->cluthash != 0) {
386
const u64 cachekeyMin = (u64)(entry->addr & 0x3FFFFFFF) << 32;
387
const u64 cachekeyMax = cachekeyMin + (1ULL << 32);
388
for (auto it = cache_.lower_bound(cachekeyMin), end = cache_.upper_bound(cachekeyMax); it != end; ++it) {
389
it->second->maxSeenV = entry->maxSeenV;
390
}
391
}
392
}
393
}
394
395
TexCacheEntry *TextureCacheCommon::SetTexture() {
396
u8 level = 0;
397
if (IsFakeMipmapChange()) {
398
level = std::max(0, gstate.getTexLevelOffset16() / 16);
399
}
400
u32 texaddr = gstate.getTextureAddress(level);
401
if (!Memory::IsValidAddress(texaddr)) {
402
// Bind a null texture and return.
403
Unbind();
404
gstate_c.SetTextureIsVideo(false);
405
gstate_c.SetTextureIs3D(false);
406
gstate_c.SetTextureIsArray(false);
407
gstate_c.SetTextureIsFramebuffer(false);
408
return nullptr;
409
}
410
411
const u16 dim = gstate.getTextureDimension(level);
412
int w = gstate.getTextureWidth(level);
413
int h = gstate.getTextureHeight(level);
414
415
GETextureFormat texFormat = gstate.getTextureFormat();
416
if (texFormat >= 11) {
417
// TODO: Better assumption? Doesn't really matter, these are invalid.
418
texFormat = GE_TFMT_5650;
419
}
420
421
bool hasClut = gstate.isTextureFormatIndexed();
422
bool hasClutGPU = false;
423
u32 cluthash;
424
if (hasClut) {
425
if (clutRenderAddress_ != 0xFFFFFFFF) {
426
gstate_c.curTextureXOffset = 0.0f;
427
gstate_c.curTextureYOffset = 0.0f;
428
hasClutGPU = true;
429
cluthash = 0; // Or should we use some other marker value?
430
} else {
431
if (clutLastFormat_ != gstate.clutformat) {
432
// We update here because the clut format can be specified after the load.
433
// TODO: Unify this as far as possible (I think only GLES backend really needs its own implementation due to different component order).
434
UpdateCurrentClut(gstate.getClutPaletteFormat(), gstate.getClutIndexStartPos(), gstate.isClutIndexSimple());
435
}
436
cluthash = clutHash_ ^ gstate.clutformat;
437
}
438
} else {
439
cluthash = 0;
440
}
441
u64 cachekey = TexCacheEntry::CacheKey(texaddr, texFormat, dim, cluthash);
442
443
int bufw = GetTextureBufw(0, texaddr, texFormat);
444
u8 maxLevel = gstate.getTextureMaxLevel();
445
446
u32 minihash = MiniHash((const u32 *)Memory::GetPointerUnchecked(texaddr));
447
448
TexCache::iterator entryIter = cache_.find(cachekey);
449
TexCacheEntry *entry = nullptr;
450
451
// Note: It's necessary to reset needshadertexclamp, for otherwise DIRTY_TEXCLAMP won't get set later.
452
// Should probably revisit how this works..
453
gstate_c.SetNeedShaderTexclamp(false);
454
gstate_c.skipDrawReason &= ~SKIPDRAW_BAD_FB_TEXTURE;
455
456
if (entryIter != cache_.end()) {
457
entry = entryIter->second.get();
458
459
// Validate the texture still matches the cache entry.
460
bool match = entry->Matches(dim, texFormat, maxLevel);
461
const char *reason = "different params";
462
463
// Check for dynamic CLUT status
464
if (((entry->status & TexCacheEntry::STATUS_CLUT_GPU) != 0) != hasClutGPU) {
465
// Need to recreate, suddenly a CLUT GPU texture was used without it, or vice versa.
466
// I think this can only happen on a clut hash collision with the marker value, so highly unlikely.
467
match = false;
468
}
469
470
// Check for FBO changes.
471
if (entry->status & TexCacheEntry::STATUS_FRAMEBUFFER_OVERLAP) {
472
// Fall through to the end where we'll delete the entry if there's a framebuffer.
473
entry->status &= ~TexCacheEntry::STATUS_FRAMEBUFFER_OVERLAP;
474
match = false;
475
}
476
477
bool rehash = entry->GetHashStatus() == TexCacheEntry::STATUS_UNRELIABLE;
478
479
// First let's see if another texture with the same address had a hashfail.
480
if (entry->status & TexCacheEntry::STATUS_CLUT_RECHECK) {
481
// Always rehash in this case, if one changed the rest all probably did.
482
rehash = true;
483
entry->status &= ~TexCacheEntry::STATUS_CLUT_RECHECK;
484
} else if (!gstate_c.IsDirty(DIRTY_TEXTURE_IMAGE)) {
485
// Okay, just some parameter change - the data didn't change, no need to rehash.
486
rehash = false;
487
}
488
489
// Do we need to recreate?
490
if (entry->status & TexCacheEntry::STATUS_FORCE_REBUILD) {
491
match = false;
492
entry->status &= ~TexCacheEntry::STATUS_FORCE_REBUILD;
493
}
494
495
if (match) {
496
if (entry->lastFrame != gpuStats.numFlips) {
497
u32 diff = gpuStats.numFlips - entry->lastFrame;
498
entry->numFrames++;
499
500
if (entry->framesUntilNextFullHash < diff) {
501
// Exponential backoff up to 512 frames. Textures are often reused.
502
if (entry->numFrames > 32) {
503
// Also, try to add some "randomness" to avoid rehashing several textures the same frame.
504
// textureName is unioned with texturePtr and vkTex so will work for the other backends.
505
entry->framesUntilNextFullHash = std::min(512, entry->numFrames) + (((intptr_t)(entry->textureName) >> 12) & 15);
506
} else {
507
entry->framesUntilNextFullHash = entry->numFrames;
508
}
509
rehash = true;
510
} else {
511
entry->framesUntilNextFullHash -= diff;
512
}
513
}
514
515
// If it's not huge or has been invalidated many times, recheck the whole texture.
516
if (entry->invalidHint > 180 || (entry->invalidHint > 15 && (dim >> 8) < 9 && (dim & 0xF) < 9)) {
517
entry->invalidHint = 0;
518
rehash = true;
519
}
520
521
if (minihash != entry->minihash) {
522
match = false;
523
reason = "minihash";
524
} else if (entry->GetHashStatus() == TexCacheEntry::STATUS_RELIABLE) {
525
rehash = false;
526
}
527
}
528
529
if (match && (entry->status & TexCacheEntry::STATUS_TO_SCALE) && standardScaleFactor_ != 1 && texelsScaledThisFrame_ < TEXCACHE_MAX_TEXELS_SCALED) {
530
if ((entry->status & TexCacheEntry::STATUS_CHANGE_FREQUENT) == 0) {
531
// INFO_LOG(Log::G3D, "Reloading texture to do the scaling we skipped..");
532
match = false;
533
reason = "scaling";
534
}
535
}
536
537
if (match && (entry->status & TexCacheEntry::STATUS_TO_REPLACE) && replacementTimeThisFrame_ < replacementFrameBudget_) {
538
int w0 = gstate.getTextureWidth(0);
539
int h0 = gstate.getTextureHeight(0);
540
int d0 = 1;
541
if (entry->replacedTexture) {
542
PollReplacement(entry, &w0, &h0, &d0);
543
// This texture is pending a replacement load.
544
// So check the replacer if it's reached a conclusion.
545
switch (entry->replacedTexture->State()) {
546
case ReplacementState::NOT_FOUND:
547
// Didn't find a replacement, so stop looking.
548
// DEBUG_LOG(Log::G3D, "No replacement for texture %dx%d", w0, h0);
549
entry->status &= ~TexCacheEntry::STATUS_TO_REPLACE;
550
if (g_Config.bSaveNewTextures) {
551
// Load it once more to actually save it. Since we don't set STATUS_TO_REPLACE, we won't end up looping.
552
match = false;
553
reason = "replacing";
554
}
555
break;
556
case ReplacementState::ACTIVE:
557
// There is now replacement data available!
558
// Just reload the texture to process the replacement.
559
match = false;
560
reason = "replacing";
561
break;
562
default:
563
// We'll just wait for a result.
564
break;
565
}
566
}
567
}
568
569
if (match) {
570
// got one!
571
gstate_c.curTextureWidth = w;
572
gstate_c.curTextureHeight = h;
573
gstate_c.SetTextureIsVideo(false);
574
gstate_c.SetTextureIs3D((entry->status & TexCacheEntry::STATUS_3D) != 0);
575
gstate_c.SetTextureIsArray(false);
576
gstate_c.SetTextureIsBGRA((entry->status & TexCacheEntry::STATUS_BGRA) != 0);
577
gstate_c.SetTextureIsFramebuffer(false);
578
579
if (rehash) {
580
// Update in case any of these changed.
581
entry->bufw = bufw;
582
entry->cluthash = cluthash;
583
}
584
585
nextTexture_ = entry;
586
nextNeedsRehash_ = rehash;
587
nextNeedsChange_ = false;
588
// Might need a rebuild if the hash fails, but that will be set later.
589
nextNeedsRebuild_ = false;
590
failedTexture_ = false;
591
VERBOSE_LOG(Log::G3D, "Texture at %08x found in cache, applying", texaddr);
592
return entry; //Done!
593
} else {
594
// Wasn't a match, we will rebuild.
595
nextChangeReason_ = reason;
596
nextNeedsChange_ = true;
597
// Fall through to the rebuild case.
598
}
599
}
600
601
// No texture found, or changed (depending on entry).
602
// Check for framebuffers.
603
604
TextureDefinition def{};
605
def.addr = texaddr;
606
def.dim = dim;
607
def.format = texFormat;
608
def.bufw = bufw;
609
610
AttachCandidate bestCandidate;
611
if (GetBestFramebufferCandidate(def, 0, &bestCandidate)) {
612
// If we had a texture entry here, let's get rid of it.
613
if (entryIter != cache_.end()) {
614
DeleteTexture(entryIter);
615
}
616
617
nextTexture_ = nullptr;
618
nextNeedsRebuild_ = false;
619
620
SetTextureFramebuffer(bestCandidate); // sets curTexture3D
621
return nullptr;
622
}
623
624
// Didn't match a framebuffer, keep going.
625
626
if (!entry) {
627
VERBOSE_LOG(Log::G3D, "No texture in cache for %08x, decoding...", texaddr);
628
entry = new TexCacheEntry{};
629
cache_[cachekey].reset(entry);
630
631
if (PPGeIsFontTextureAddress(texaddr)) {
632
// It's the builtin font texture.
633
entry->status = TexCacheEntry::STATUS_RELIABLE;
634
} else if (g_Config.bTextureBackoffCache && !IsVideo(texaddr)) {
635
entry->status = TexCacheEntry::STATUS_HASHING;
636
} else {
637
entry->status = TexCacheEntry::STATUS_UNRELIABLE;
638
}
639
640
if (hasClutGPU) {
641
WARN_LOG_N_TIMES(clutUseRender, 5, Log::G3D, "Using texture with dynamic CLUT: texfmt=%d, clutfmt=%d", gstate.getTextureFormat(), gstate.getClutPaletteFormat());
642
entry->status |= TexCacheEntry::STATUS_CLUT_GPU;
643
}
644
645
if (hasClut && clutRenderAddress_ == 0xFFFFFFFF) {
646
const u64 cachekeyMin = (u64)(texaddr & 0x3FFFFFFF) << 32;
647
const u64 cachekeyMax = cachekeyMin + (1ULL << 32);
648
649
int found = 0;
650
for (auto it = cache_.lower_bound(cachekeyMin), end = cache_.upper_bound(cachekeyMax); it != end; ++it) {
651
found++;
652
}
653
654
if (found >= TEXTURE_CLUT_VARIANTS_MIN) {
655
for (auto it = cache_.lower_bound(cachekeyMin), end = cache_.upper_bound(cachekeyMax); it != end; ++it) {
656
it->second->status |= TexCacheEntry::STATUS_CLUT_VARIANTS;
657
}
658
659
entry->status |= TexCacheEntry::STATUS_CLUT_VARIANTS;
660
}
661
}
662
663
nextNeedsChange_ = false;
664
}
665
666
// We have to decode it, let's setup the cache entry first.
667
entry->addr = texaddr;
668
entry->minihash = minihash;
669
entry->dim = dim;
670
entry->format = texFormat;
671
entry->maxLevel = maxLevel;
672
entry->status &= ~TexCacheEntry::STATUS_BGRA;
673
674
entry->bufw = bufw;
675
676
entry->cluthash = cluthash;
677
678
gstate_c.curTextureWidth = w;
679
gstate_c.curTextureHeight = h;
680
gstate_c.SetTextureIsVideo(false);
681
gstate_c.SetTextureIs3D((entry->status & TexCacheEntry::STATUS_3D) != 0);
682
gstate_c.SetTextureIsArray(false); // Ordinary 2D textures still aren't used by array view in VK. We probably might as well, though, at this point..
683
gstate_c.SetTextureIsFramebuffer(false);
684
685
failedTexture_ = false;
686
nextTexture_ = entry;
687
nextFramebufferTexture_ = nullptr;
688
nextNeedsRehash_ = true;
689
// We still need to rebuild, to allocate a texture. But we'll bail early.
690
nextNeedsRebuild_ = true;
691
return entry;
692
}
693
694
bool TextureCacheCommon::GetBestFramebufferCandidate(const TextureDefinition &entry, u32 texAddrOffset, AttachCandidate *bestCandidate) const {
695
gpuStats.numFramebufferEvaluations++;
696
697
TinySet<AttachCandidate, 6> candidates;
698
699
const std::vector<VirtualFramebuffer *> &framebuffers = framebufferManager_->Framebuffers();
700
701
for (VirtualFramebuffer *framebuffer : framebuffers) {
702
FramebufferMatchInfo match{};
703
if (MatchFramebuffer(entry, framebuffer, texAddrOffset, RASTER_COLOR, &match)) {
704
candidates.push_back(AttachCandidate{ framebuffer, match, RASTER_COLOR });
705
}
706
match = {};
707
if (MatchFramebuffer(entry, framebuffer, texAddrOffset, RASTER_DEPTH, &match)) {
708
candidates.push_back(AttachCandidate{ framebuffer, match, RASTER_DEPTH });
709
}
710
}
711
712
if (candidates.size() == 0) {
713
return false;
714
} else if (candidates.size() == 1) {
715
*bestCandidate = candidates[0];
716
return true;
717
}
718
719
bool logging = Reporting::ShouldLogNTimes("multifbcandidate", 5);
720
721
// OK, multiple possible candidates. Will need to figure out which one is the most relevant.
722
int bestRelevancy = -1;
723
size_t bestIndex = -1;
724
725
bool kzCompat = PSP_CoreParameter().compat.flags().SplitFramebufferMargin;
726
727
// We simply use the sequence counter as relevancy nowadays.
728
for (size_t i = 0; i < candidates.size(); i++) {
729
AttachCandidate &candidate = candidates[i];
730
int relevancy = candidate.channel == RASTER_COLOR ? candidate.fb->colorBindSeq : candidate.fb->depthBindSeq;
731
732
// Add a small negative penalty if the texture is currently bound as a framebuffer, and offset is not zero.
733
// Should avoid problems when pingponging two nearby buffers, like in Wipeout Pure in #15927.
734
if (candidate.channel == RASTER_COLOR &&
735
(candidate.match.yOffset != 0 || candidate.match.xOffset != 0) &&
736
candidate.fb->fb_address == (gstate.getFrameBufRawAddress() | 0x04000000)) {
737
relevancy -= 2;
738
}
739
740
if (candidate.match.xOffset != 0 && PSP_CoreParameter().compat.flags().DisallowFramebufferAtOffset) {
741
continue;
742
}
743
744
// Avoid binding as texture the framebuffer we're rendering to.
745
// In Killzone, we split the framebuffer but the matching algorithm can still pick the wrong one,
746
// which this avoids completely.
747
if (kzCompat && candidate.fb == framebufferManager_->GetCurrentRenderVFB()) {
748
continue;
749
}
750
751
if (logging) {
752
candidate.relevancy = relevancy;
753
}
754
755
if (relevancy > bestRelevancy) {
756
bestRelevancy = relevancy;
757
bestIndex = i;
758
}
759
}
760
761
if (logging) {
762
std::string cands;
763
for (size_t i = 0; i < candidates.size(); i++) {
764
cands += candidates[i].ToString();
765
if (i != candidates.size() - 1)
766
cands += "\n";
767
}
768
cands += "\n";
769
770
WARN_LOG(Log::G3D, "GetFramebufferCandidates(tex): Multiple (%d) candidate framebuffers. texaddr: %08x offset: %d (%dx%d stride %d, %s):\n%s",
771
(int)candidates.size(),
772
entry.addr, texAddrOffset, dimWidth(entry.dim), dimHeight(entry.dim), entry.bufw, GeTextureFormatToString(entry.format),
773
cands.c_str()
774
);
775
logging = true;
776
}
777
778
if (bestIndex != -1) {
779
if (logging) {
780
WARN_LOG(Log::G3D, "Chose candidate %d:\n%s\n", (int)bestIndex, candidates[bestIndex].ToString().c_str());
781
}
782
*bestCandidate = candidates[bestIndex];
783
return true;
784
} else {
785
return false;
786
}
787
}
788
789
// Removes old textures.
790
void TextureCacheCommon::Decimate(TexCacheEntry *exceptThisOne, bool forcePressure) {
791
if (--decimationCounter_ <= 0) {
792
decimationCounter_ = TEXCACHE_DECIMATION_INTERVAL;
793
} else {
794
return;
795
}
796
797
if (forcePressure || cacheSizeEstimate_ >= TEXCACHE_MIN_PRESSURE) {
798
const u32 had = cacheSizeEstimate_;
799
800
ForgetLastTexture();
801
int killAgeBase = lowMemoryMode_ ? TEXTURE_KILL_AGE_LOWMEM : TEXTURE_KILL_AGE;
802
for (TexCache::iterator iter = cache_.begin(); iter != cache_.end(); ) {
803
if (iter->second.get() == exceptThisOne) {
804
++iter;
805
continue;
806
}
807
bool hasClut = (iter->second->status & TexCacheEntry::STATUS_CLUT_VARIANTS) != 0;
808
int killAge = hasClut ? TEXTURE_KILL_AGE_CLUT : killAgeBase;
809
if (iter->second->lastFrame + killAge < gpuStats.numFlips) {
810
DeleteTexture(iter++);
811
} else {
812
++iter;
813
}
814
}
815
816
VERBOSE_LOG(Log::G3D, "Decimated texture cache, saved %d estimated bytes - now %d bytes", had - cacheSizeEstimate_, cacheSizeEstimate_);
817
}
818
819
// If enabled, we also need to clear the secondary cache.
820
if (PSP_CoreParameter().compat.flags().SecondaryTextureCache && (forcePressure || secondCacheSizeEstimate_ >= TEXCACHE_SECOND_MIN_PRESSURE)) {
821
const u32 had = secondCacheSizeEstimate_;
822
823
for (TexCache::iterator iter = secondCache_.begin(); iter != secondCache_.end(); ) {
824
if (iter->second.get() == exceptThisOne) {
825
++iter;
826
continue;
827
}
828
// In low memory mode, we kill them all since secondary cache is disabled.
829
if (lowMemoryMode_ || iter->second->lastFrame + TEXTURE_SECOND_KILL_AGE < gpuStats.numFlips) {
830
ReleaseTexture(iter->second.get(), true);
831
secondCacheSizeEstimate_ -= EstimateTexMemoryUsage(iter->second.get());
832
secondCache_.erase(iter++);
833
} else {
834
++iter;
835
}
836
}
837
838
VERBOSE_LOG(Log::G3D, "Decimated second texture cache, saved %d estimated bytes - now %d bytes", had - secondCacheSizeEstimate_, secondCacheSizeEstimate_);
839
}
840
841
DecimateVideos();
842
replacer_.Decimate(forcePressure ? ReplacerDecimateMode::FORCE_PRESSURE : ReplacerDecimateMode::NEW_FRAME);
843
}
844
845
void TextureCacheCommon::DecimateVideos() {
846
for (auto iter = videos_.begin(); iter != videos_.end(); ) {
847
if (iter->flips + VIDEO_DECIMATE_AGE < gpuStats.numFlips) {
848
iter = videos_.erase(iter++);
849
} else {
850
++iter;
851
}
852
}
853
}
854
855
bool TextureCacheCommon::IsVideo(u32 texaddr) const {
856
texaddr &= 0x3FFFFFFF;
857
for (auto &info : videos_) {
858
if (texaddr < info.addr) {
859
continue;
860
}
861
if (texaddr < info.addr + info.size) {
862
return true;
863
}
864
}
865
return false;
866
}
867
868
void TextureCacheCommon::HandleTextureChange(TexCacheEntry *const entry, const char *reason, bool initialMatch, bool doDelete) {
869
cacheSizeEstimate_ -= EstimateTexMemoryUsage(entry);
870
entry->numInvalidated++;
871
gpuStats.numTextureInvalidations++;
872
DEBUG_LOG(Log::G3D, "Texture different or overwritten, reloading at %08x: %s", entry->addr, reason);
873
if (doDelete) {
874
ForgetLastTexture();
875
ReleaseTexture(entry, true);
876
entry->status &= ~(TexCacheEntry::STATUS_IS_SCALED_OR_REPLACED | TexCacheEntry::STATUS_TO_REPLACE);
877
}
878
879
// Mark as hashing, if marked as reliable.
880
if (entry->GetHashStatus() == TexCacheEntry::STATUS_RELIABLE) {
881
entry->SetHashStatus(TexCacheEntry::STATUS_HASHING);
882
}
883
884
// Also, mark any textures with the same address but different clut. They need rechecking.
885
if (entry->cluthash != 0) {
886
const u64 cachekeyMin = (u64)(entry->addr & 0x3FFFFFFF) << 32;
887
const u64 cachekeyMax = cachekeyMin + (1ULL << 32);
888
for (auto it = cache_.lower_bound(cachekeyMin), end = cache_.upper_bound(cachekeyMax); it != end; ++it) {
889
if (it->second->cluthash != entry->cluthash) {
890
it->second->status |= TexCacheEntry::STATUS_CLUT_RECHECK;
891
}
892
}
893
}
894
895
if (entry->numFrames < TEXCACHE_FRAME_CHANGE_FREQUENT) {
896
if (entry->status & TexCacheEntry::STATUS_FREE_CHANGE) {
897
entry->status &= ~TexCacheEntry::STATUS_FREE_CHANGE;
898
} else {
899
entry->status |= TexCacheEntry::STATUS_CHANGE_FREQUENT;
900
}
901
}
902
entry->numFrames = 0;
903
}
904
905
void TextureCacheCommon::NotifyFramebuffer(VirtualFramebuffer *framebuffer, FramebufferNotification msg) {
906
const u32 fb_addr = framebuffer->fb_address;
907
const u32 z_addr = framebuffer->z_address;
908
909
const u32 fb_bpp = BufferFormatBytesPerPixel(framebuffer->fb_format);
910
const u32 z_bpp = 2; // No other format exists.
911
const u32 fb_stride = framebuffer->fb_stride;
912
const u32 z_stride = framebuffer->z_stride;
913
914
// NOTE: Some games like Burnout massively misdetects the height of some framebuffers, leading to a lot of unnecessary invalidations.
915
// Let's only actually get rid of textures that cover the very start of the framebuffer.
916
const u32 fb_endAddr = fb_addr + fb_stride * std::min((int)framebuffer->height, 16) * fb_bpp;
917
const u32 z_endAddr = z_addr + z_stride * std::min((int)framebuffer->height, 16) * z_bpp;
918
919
switch (msg) {
920
case NOTIFY_FB_CREATED:
921
case NOTIFY_FB_UPDATED:
922
{
923
// Try to match the new framebuffer to existing textures.
924
// Backwards from the "usual" texturing case so can't share a utility function.
925
926
u64 cacheKey = (u64)fb_addr << 32;
927
// If it has a clut, those are the low 32 bits, so it'll be inside this range.
928
// Also, if it's a subsample of the buffer, it'll also be within the FBO.
929
u64 cacheKeyEnd = (u64)fb_endAddr << 32;
930
931
// Color - no need to look in the mirrors.
932
for (auto it = cache_.lower_bound(cacheKey), end = cache_.upper_bound(cacheKeyEnd); it != end; ++it) {
933
it->second->status |= TexCacheEntry::STATUS_FRAMEBUFFER_OVERLAP;
934
gpuStats.numTextureInvalidationsByFramebuffer++;
935
}
936
937
if (z_stride != 0) {
938
// Depth. Just look at the range, but in each mirror (0x04200000 and 0x04600000).
939
// Games don't use 0x04400000 as far as I know - it has no swizzle effect so kinda useless.
940
cacheKey = (u64)z_addr << 32;
941
cacheKeyEnd = (u64)z_endAddr << 32;
942
for (auto it = cache_.lower_bound(cacheKey | 0x200000), end = cache_.upper_bound(cacheKeyEnd | 0x200000); it != end; ++it) {
943
it->second->status |= TexCacheEntry::STATUS_FRAMEBUFFER_OVERLAP;
944
gpuStats.numTextureInvalidationsByFramebuffer++;
945
}
946
for (auto it = cache_.lower_bound(cacheKey | 0x600000), end = cache_.upper_bound(cacheKeyEnd | 0x600000); it != end; ++it) {
947
it->second->status |= TexCacheEntry::STATUS_FRAMEBUFFER_OVERLAP;
948
gpuStats.numTextureInvalidationsByFramebuffer++;
949
}
950
}
951
break;
952
}
953
default:
954
break;
955
}
956
}
957
958
bool TextureCacheCommon::MatchFramebuffer(
959
const TextureDefinition &entry,
960
VirtualFramebuffer *framebuffer, u32 texaddrOffset, RasterChannel channel, FramebufferMatchInfo *matchInfo) const {
961
static const u32 MAX_SUBAREA_Y_OFFSET_SAFE = 32;
962
963
uint32_t fb_address = channel == RASTER_DEPTH ? framebuffer->z_address : framebuffer->fb_address;
964
uint32_t fb_stride = channel == RASTER_DEPTH ? framebuffer->z_stride : framebuffer->fb_stride;
965
GEBufferFormat fb_format = channel == RASTER_DEPTH ? GE_FORMAT_DEPTH16 : framebuffer->fb_format;
966
967
if (channel == RASTER_DEPTH && (framebuffer->z_address == framebuffer->fb_address || framebuffer->z_address == 0)) {
968
// Try to avoid silly matches to somewhat malformed buffers.
969
return false;
970
}
971
972
if (!fb_stride) {
973
// Hard to make decisions.
974
return false;
975
}
976
977
switch (entry.format) {
978
case GE_TFMT_DXT1:
979
case GE_TFMT_DXT3:
980
case GE_TFMT_DXT5:
981
return false;
982
default: break;
983
}
984
985
uint32_t fb_stride_in_bytes = fb_stride * BufferFormatBytesPerPixel(fb_format);
986
uint32_t tex_stride_in_bytes = entry.bufw * textureBitsPerPixel[entry.format] / 8; // Note, we're looking up bits here so need to divide by 8.
987
988
u32 addr = fb_address;
989
u32 texaddr = entry.addr + texaddrOffset;
990
991
bool texInVRAM = Memory::IsVRAMAddress(texaddr);
992
bool fbInVRAM = Memory::IsVRAMAddress(fb_address);
993
994
if (texInVRAM != fbInVRAM) {
995
// Shortcut. Cannot possibly be a match.
996
return false;
997
}
998
999
if (texInVRAM) {
1000
const u32 mirrorMask = 0x041FFFFF;
1001
1002
addr &= mirrorMask;
1003
texaddr &= mirrorMask;
1004
}
1005
1006
const bool noOffset = texaddr == addr;
1007
const bool exactMatch = noOffset && entry.format < 4 && channel == RASTER_COLOR && fb_stride_in_bytes == tex_stride_in_bytes;
1008
1009
const u32 texWidth = 1 << ((entry.dim >> 0) & 0xf);
1010
const u32 texHeight = 1 << ((entry.dim >> 8) & 0xf);
1011
1012
// 512 on a 272 framebuffer is sane, so let's be lenient.
1013
const u32 minSubareaHeight = texHeight / 4;
1014
1015
// If they match "exactly", it's non-CLUT and from the top left.
1016
if (exactMatch) {
1017
// NOTE: This check is okay because the first texture formats are the same as the buffer formats.
1018
if (IsTextureFormatBufferCompatible(entry.format)) {
1019
if (TextureFormatMatchesBufferFormat(entry.format, fb_format) || (framebuffer->usageFlags & FB_USAGE_BLUE_TO_ALPHA)) {
1020
return true;
1021
} else {
1022
WARN_LOG_ONCE(diffFormat1, Log::G3D, "Found matching framebuffer with reinterpretable fb_format: %s != %s at %08x", GeTextureFormatToString(entry.format), GeBufferFormatToString(fb_format), fb_address);
1023
*matchInfo = FramebufferMatchInfo{ 0, 0, true, TextureFormatToBufferFormat(entry.format) };
1024
return true;
1025
}
1026
} else {
1027
// Format incompatible, ignoring without comment. (maybe some really gnarly hacks will end up here...)
1028
return false;
1029
}
1030
} else {
1031
// Apply to buffered mode only.
1032
if (!framebufferManager_->UseBufferedRendering()) {
1033
return false;
1034
}
1035
1036
// Check works for D16 too.
1037
// These are combinations that we have special-cased handling for. There are more
1038
// ones possible, but rare - we'll add them as we find them used.
1039
const bool matchingClutFormat =
1040
(fb_format == GE_FORMAT_DEPTH16 && entry.format == GE_TFMT_CLUT16) ||
1041
(fb_format == GE_FORMAT_DEPTH16 && entry.format == GE_TFMT_5650) ||
1042
(fb_format == GE_FORMAT_8888 && entry.format == GE_TFMT_CLUT32) ||
1043
(fb_format != GE_FORMAT_8888 && entry.format == GE_TFMT_CLUT16) ||
1044
(fb_format == GE_FORMAT_8888 && entry.format == GE_TFMT_CLUT8) ||
1045
(fb_format == GE_FORMAT_5551 && entry.format == GE_TFMT_CLUT8 && PSP_CoreParameter().compat.flags().SOCOMClut8Replacement);
1046
1047
const int texBitsPerPixel = TextureFormatBitsPerPixel(entry.format);
1048
const int byteOffset = texaddr - addr;
1049
if (byteOffset > 0) {
1050
int texbpp = texBitsPerPixel;
1051
if (fb_format == GE_FORMAT_5551 && entry.format == GE_TFMT_CLUT8) {
1052
// In this case we treat CLUT8 as if it were CLUT16, see issue #16210. So we need
1053
// to compute the x offset appropriately.
1054
texbpp = 16;
1055
}
1056
1057
matchInfo->yOffset = byteOffset / fb_stride_in_bytes;
1058
matchInfo->xOffset = 8 * (byteOffset % fb_stride_in_bytes) / texbpp;
1059
} else if (byteOffset < 0) {
1060
int texelOffset = 8 * byteOffset / texBitsPerPixel;
1061
// We don't support negative Y offsets, and negative X offsets are only for the Killzone workaround.
1062
if (texelOffset < -(int)entry.bufw || !PSP_CoreParameter().compat.flags().SplitFramebufferMargin) {
1063
return false;
1064
}
1065
matchInfo->xOffset = entry.bufw == 0 ? 0 : -(-texelOffset % (int)entry.bufw);
1066
}
1067
1068
if (matchInfo->yOffset > 0 && matchInfo->yOffset + minSubareaHeight >= framebuffer->height) {
1069
// Can't be inside the framebuffer.
1070
return false;
1071
}
1072
1073
// Check if it's in bufferWidth (which might be higher than width and may indicate the framebuffer includes the data.)
1074
// Do the computation in bytes so that it's valid even in case of weird reinterpret scenarios.
1075
const int xOffsetInBytes = matchInfo->xOffset * 8 / texBitsPerPixel;
1076
const int texWidthInBytes = texWidth * 8 / texBitsPerPixel;
1077
if (xOffsetInBytes >= framebuffer->BufferWidthInBytes() && xOffsetInBytes + texWidthInBytes <= (int)fb_stride_in_bytes) {
1078
// This happens in Brave Story, see #10045 - the texture is in the space between strides, with matching stride.
1079
return false;
1080
}
1081
1082
// Trying to play it safe. Below 0x04110000 is almost always framebuffers.
1083
// TODO: Maybe we can reduce this check and find a better way above 0x04110000?
1084
if (matchInfo->yOffset > MAX_SUBAREA_Y_OFFSET_SAFE && addr > 0x04110000 && !PSP_CoreParameter().compat.flags().AllowLargeFBTextureOffsets) {
1085
WARN_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);
1086
return false;
1087
}
1088
1089
// Note the check for texHeight - we really don't care about a stride mismatch if texHeight == 1.
1090
// This also takes care of the 4x1 texture check we used to have here for Burnout Dominator.
1091
if (fb_stride_in_bytes != tex_stride_in_bytes && texHeight > 1) {
1092
// Probably irrelevant.
1093
return false;
1094
}
1095
1096
// Check for CLUT. The framebuffer is always RGB, but it can be interpreted as a CLUT texture.
1097
// 3rd Birthday (and a bunch of other games) render to a 16 bit clut texture.
1098
if (matchingClutFormat) {
1099
if (!noOffset) {
1100
WARN_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);
1101
}
1102
return true;
1103
} else if (IsClutFormat((GETextureFormat)(entry.format)) || IsDXTFormat((GETextureFormat)(entry.format))) {
1104
WARN_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);
1105
return false;
1106
}
1107
1108
// This is either normal or we failed to generate a shader to depalettize
1109
if ((int)fb_format == (int)entry.format || matchingClutFormat) {
1110
if ((int)fb_format != (int)entry.format) {
1111
WARN_LOG_ONCE(diffFormat2, Log::G3D, "Matching framebuffer with different formats %s != %s at %08x",
1112
GeTextureFormatToString(entry.format), GeBufferFormatToString(fb_format), fb_address);
1113
return true;
1114
} else {
1115
WARN_LOG_ONCE(subarea, Log::G3D, "Matching from framebuffer at %08x +%dx%d", fb_address, matchInfo->xOffset, matchInfo->yOffset);
1116
return true;
1117
}
1118
} else {
1119
WARN_LOG_ONCE(diffFormat2, Log::G3D, "Ignoring possible texturing from framebuffer at %08x with incompatible format %s != %s (+%dx%d)",
1120
fb_address, GeTextureFormatToString(entry.format), GeBufferFormatToString(fb_format), matchInfo->xOffset, matchInfo->yOffset);
1121
return false;
1122
}
1123
}
1124
}
1125
1126
void TextureCacheCommon::SetTextureFramebuffer(const AttachCandidate &candidate) {
1127
VirtualFramebuffer *framebuffer = candidate.fb;
1128
RasterChannel channel = candidate.channel;
1129
1130
if (candidate.match.reinterpret) {
1131
framebuffer = framebufferManager_->ResolveFramebufferColorToFormat(candidate.fb, candidate.match.reinterpretTo);
1132
}
1133
1134
_dbg_assert_msg_(framebuffer != nullptr, "Framebuffer must not be null.");
1135
1136
framebuffer->usageFlags |= FB_USAGE_TEXTURE;
1137
// Keep the framebuffer alive.
1138
framebuffer->last_frame_used = gpuStats.numFlips;
1139
1140
nextFramebufferTextureChannel_ = RASTER_COLOR;
1141
1142
if (framebufferManager_->UseBufferedRendering()) {
1143
FramebufferMatchInfo fbInfo = candidate.match;
1144
// Detect when we need to apply the horizontal texture swizzle.
1145
u64 depthUpperBits = (channel == RASTER_DEPTH && framebuffer->fb_format == GE_FORMAT_8888) ? ((gstate.getTextureAddress(0) & 0x600000) >> 20) : 0;
1146
bool needsDepthXSwizzle = depthUpperBits == 2;
1147
1148
// We need to force it, since we may have set it on a texture before attaching.
1149
int texWidth = framebuffer->bufferWidth;
1150
int texHeight = framebuffer->bufferHeight;
1151
if (candidate.channel == RASTER_COLOR && gstate.getTextureFormat() == GE_TFMT_CLUT8 && framebuffer->fb_format == GE_FORMAT_5551 && PSP_CoreParameter().compat.flags().SOCOMClut8Replacement) {
1152
// See #16210. UV must be adjusted as if the texture was twice the width.
1153
texWidth *= 2.0f;
1154
}
1155
1156
if (needsDepthXSwizzle) {
1157
texWidth = RoundUpToPowerOf2(texWidth);
1158
}
1159
1160
gstate_c.curTextureWidth = texWidth;
1161
gstate_c.curTextureHeight = texHeight;
1162
gstate_c.SetTextureIsFramebuffer(true);
1163
gstate_c.SetTextureIsBGRA(false);
1164
1165
if ((gstate_c.curTextureXOffset == 0) != (fbInfo.xOffset == 0) || (gstate_c.curTextureYOffset == 0) != (fbInfo.yOffset == 0)) {
1166
gstate_c.Dirty(DIRTY_FRAGMENTSHADER_STATE);
1167
}
1168
1169
gstate_c.curTextureXOffset = fbInfo.xOffset;
1170
gstate_c.curTextureYOffset = fbInfo.yOffset;
1171
u32 texW = (u32)gstate.getTextureWidth(0);
1172
u32 texH = (u32)gstate.getTextureHeight(0);
1173
gstate_c.SetNeedShaderTexclamp(gstate_c.curTextureWidth != texW || gstate_c.curTextureHeight != texH);
1174
if (gstate_c.curTextureXOffset != 0 || gstate_c.curTextureYOffset != 0) {
1175
gstate_c.SetNeedShaderTexclamp(true);
1176
}
1177
if (channel == RASTER_DEPTH) {
1178
framebuffer->usageFlags |= FB_USAGE_COLOR_MIXED_DEPTH;
1179
}
1180
1181
if (channel == RASTER_DEPTH && !gstate_c.Use(GPU_USE_DEPTH_TEXTURE)) {
1182
WARN_LOG_ONCE(ndepthtex, Log::G3D, "Depth textures not supported, not binding");
1183
// Flag to bind a null texture if we can't support depth textures.
1184
// Should only happen on old OpenGL.
1185
nextFramebufferTexture_ = nullptr;
1186
failedTexture_ = true;
1187
} else {
1188
nextFramebufferTexture_ = framebuffer;
1189
nextFramebufferTextureChannel_ = channel;
1190
}
1191
nextTexture_ = nullptr;
1192
} else {
1193
if (framebuffer->fbo) {
1194
framebuffer->fbo->Release();
1195
framebuffer->fbo = nullptr;
1196
}
1197
Unbind();
1198
gstate_c.SetNeedShaderTexclamp(false);
1199
nextFramebufferTexture_ = nullptr;
1200
nextTexture_ = nullptr;
1201
}
1202
1203
gstate_c.SetTextureIsVideo(false);
1204
gstate_c.SetTextureIs3D(false);
1205
gstate_c.SetTextureIsArray(true);
1206
1207
nextNeedsRehash_ = false;
1208
nextNeedsChange_ = false;
1209
nextNeedsRebuild_ = false;
1210
}
1211
1212
// Only looks for framebuffers.
1213
bool TextureCacheCommon::SetOffsetTexture(u32 yOffset) {
1214
if (!framebufferManager_->UseBufferedRendering()) {
1215
return false;
1216
}
1217
1218
u32 texaddr = gstate.getTextureAddress(0);
1219
GETextureFormat fmt = gstate.getTextureFormat();
1220
const u32 bpp = fmt == GE_TFMT_8888 ? 4 : 2;
1221
const u32 texaddrOffset = yOffset * gstate.getTextureWidth(0) * bpp;
1222
1223
if (!Memory::IsValidAddress(texaddr) || !Memory::IsValidAddress(texaddr + texaddrOffset)) {
1224
return false;
1225
}
1226
1227
TextureDefinition def;
1228
def.addr = texaddr;
1229
def.format = fmt;
1230
def.bufw = GetTextureBufw(0, texaddr, fmt);
1231
def.dim = gstate.getTextureDimension(0);
1232
1233
AttachCandidate bestCandidate;
1234
if (GetBestFramebufferCandidate(def, texaddrOffset, &bestCandidate)) {
1235
SetTextureFramebuffer(bestCandidate);
1236
return true;
1237
} else {
1238
return false;
1239
}
1240
}
1241
1242
bool TextureCacheCommon::GetCurrentFramebufferTextureDebug(GPUDebugBuffer &buffer, bool *isFramebuffer) {
1243
if (!nextFramebufferTexture_)
1244
return false;
1245
*isFramebuffer = true;
1246
1247
VirtualFramebuffer *vfb = nextFramebufferTexture_;
1248
u8 sf = vfb->renderScaleFactor;
1249
int x = gstate_c.curTextureXOffset * sf;
1250
int y = gstate_c.curTextureYOffset * sf;
1251
int desiredW = gstate.getTextureWidth(0) * sf;
1252
int desiredH = gstate.getTextureHeight(0) * sf;
1253
int w = std::min(desiredW, vfb->bufferWidth * sf - x);
1254
int h = std::min(desiredH, vfb->bufferHeight * sf - y);
1255
1256
bool retval;
1257
if (nextFramebufferTextureChannel_ == RASTER_DEPTH) {
1258
buffer.Allocate(desiredW, desiredH, GPU_DBG_FORMAT_FLOAT, false);
1259
if (w < desiredW || h < desiredH)
1260
buffer.ZeroBytes();
1261
retval = draw_->CopyFramebufferToMemory(vfb->fbo, Draw::FB_DEPTH_BIT, x, y, w, h, Draw::DataFormat::D32F, buffer.GetData(), desiredW, Draw::ReadbackMode::BLOCK, "GetCurrentTextureDebug");
1262
} else {
1263
buffer.Allocate(desiredW, desiredH, GPU_DBG_FORMAT_8888, false);
1264
if (w < desiredW || h < desiredH)
1265
buffer.ZeroBytes();
1266
retval = draw_->CopyFramebufferToMemory(vfb->fbo, Draw::FB_COLOR_BIT, x, y, w, h, Draw::DataFormat::R8G8B8A8_UNORM, buffer.GetData(), desiredW, Draw::ReadbackMode::BLOCK, "GetCurrentTextureDebug");
1267
}
1268
1269
// Vulkan requires us to re-apply all dynamic state for each command buffer, and the above will cause us to start a new cmdbuf.
1270
// So let's dirty the things that are involved in Vulkan dynamic state. Readbacks are not frequent so this won't hurt other backends.
1271
gstate_c.Dirty(DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_BLEND_STATE | DIRTY_DEPTHSTENCIL_STATE);
1272
// We may have blitted to a temp FBO.
1273
framebufferManager_->RebindFramebuffer("RebindFramebuffer - GetCurrentTextureDebug");
1274
if (!retval)
1275
ERROR_LOG(Log::G3D, "Failed to get debug texture: copy to memory failed");
1276
return retval;
1277
}
1278
1279
void TextureCacheCommon::NotifyConfigChanged() {
1280
int scaleFactor = g_Config.iTexScalingLevel;
1281
1282
if (!gstate_c.Use(GPU_USE_TEXTURE_NPOT)) {
1283
// Reduce the scale factor to a power of two (e.g. 2 or 4) if textures must be a power of two.
1284
// TODO: In addition we should probably remove these options from the UI in this case.
1285
while ((scaleFactor & (scaleFactor - 1)) != 0) {
1286
--scaleFactor;
1287
}
1288
}
1289
1290
// Just in case, small display with auto resolution or something.
1291
if (scaleFactor <= 0) {
1292
scaleFactor = 1;
1293
}
1294
1295
standardScaleFactor_ = scaleFactor;
1296
1297
replacer_.NotifyConfigChanged();
1298
}
1299
1300
void TextureCacheCommon::NotifyWriteFormattedFromMemory(u32 addr, int size, int width, GEBufferFormat fmt) {
1301
addr &= 0x3FFFFFFF;
1302
videos_.push_back({ addr, (u32)size, gpuStats.numFlips });
1303
}
1304
1305
void TextureCacheCommon::LoadClut(u32 clutAddr, u32 loadBytes) {
1306
if (loadBytes == 0) {
1307
// Don't accidentally overwrite clutTotalBytes_ with a zero.
1308
return;
1309
}
1310
1311
_assert_(loadBytes <= 2048);
1312
clutTotalBytes_ = loadBytes;
1313
clutRenderAddress_ = 0xFFFFFFFF;
1314
1315
if (!Memory::IsValidAddress(clutAddr)) {
1316
memset(clutBufRaw_, 0x00, loadBytes);
1317
// Reload the clut next time (should we really do it in this case?)
1318
clutLastFormat_ = 0xFFFFFFFF;
1319
clutMaxBytes_ = std::max(clutMaxBytes_, loadBytes);
1320
return;
1321
}
1322
1323
if (Memory::IsVRAMAddress(clutAddr)) {
1324
// Clear the uncached and mirror bits, etc. to match framebuffers.
1325
const u32 clutLoadAddr = clutAddr & 0x041FFFFF;
1326
const u32 clutLoadEnd = clutLoadAddr + loadBytes;
1327
static const u32 MAX_CLUT_OFFSET = 4096;
1328
1329
clutRenderOffset_ = MAX_CLUT_OFFSET;
1330
const std::vector<VirtualFramebuffer *> &framebuffers = framebufferManager_->Framebuffers();
1331
1332
u32 bestClutAddress = 0xFFFFFFFF;
1333
1334
VirtualFramebuffer *chosenFramebuffer = nullptr;
1335
for (VirtualFramebuffer *framebuffer : framebuffers) {
1336
// Let's not deal with divide by zero.
1337
if (framebuffer->fb_stride == 0)
1338
continue;
1339
1340
const u32 fb_address = framebuffer->fb_address;
1341
const u32 fb_bpp = BufferFormatBytesPerPixel(framebuffer->fb_format);
1342
int offset = clutLoadAddr - fb_address;
1343
1344
// Is this inside the framebuffer at all? Note that we only check the first line here, this should
1345
// be changed.
1346
bool matchRange = offset >= 0 && offset < (int)(framebuffer->fb_stride * fb_bpp);
1347
if (matchRange) {
1348
// And is it inside the rendered area? Sometimes games pack data in the margin between width and stride.
1349
// If the framebuffer width was detected as 512, we're gonna assume it's really 480.
1350
int fbMatchWidth = framebuffer->width;
1351
if (fbMatchWidth == 512) {
1352
fbMatchWidth = 480;
1353
}
1354
int pixelOffsetX = ((offset / fb_bpp) % framebuffer->fb_stride);
1355
bool inMargin = pixelOffsetX >= fbMatchWidth && (pixelOffsetX + (loadBytes / fb_bpp) <= framebuffer->fb_stride);
1356
1357
// The offset check here means, in the context of the loop, that we'll pick
1358
// the framebuffer with the smallest offset. This is yet another framebuffer matching
1359
// loop with its own rules, eventually we'll probably want to do something
1360
// more systematic.
1361
bool okAge = !PSP_CoreParameter().compat.flags().LoadCLUTFromCurrentFrameOnly || framebuffer->last_frame_render == gpuStats.numFlips; // Here we can try heuristics.
1362
if (matchRange && !inMargin && offset < (int)clutRenderOffset_) {
1363
if (okAge) {
1364
WARN_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",
1365
loadBytes, fb_address, GeBufferFormatToString(framebuffer->fb_format), gpuStats.numFlips - framebuffer->last_frame_render, offset, offset / fb_bpp);
1366
framebuffer->last_frame_clut = gpuStats.numFlips;
1367
// Also mark used so it's not decimated.
1368
framebuffer->last_frame_used = gpuStats.numFlips;
1369
framebuffer->usageFlags |= FB_USAGE_CLUT;
1370
bestClutAddress = framebuffer->fb_address;
1371
clutRenderOffset_ = (u32)offset;
1372
chosenFramebuffer = framebuffer;
1373
if (offset == 0) {
1374
// Not gonna find a better match according to the smallest-offset rule, so we'll go with this one.
1375
break;
1376
}
1377
} else {
1378
WARN_LOG(Log::G3D, "Ignoring CLUT load from %d frames old buffer at %08x", gpuStats.numFlips - framebuffer->last_frame_render, fb_address);
1379
}
1380
}
1381
}
1382
}
1383
1384
// To turn off dynamic CLUT (for demonstration or testing purposes), add "false &&" to this check.
1385
if (chosenFramebuffer && chosenFramebuffer->fbo) {
1386
clutRenderAddress_ = bestClutAddress;
1387
1388
if (!dynamicClutTemp_) {
1389
Draw::FramebufferDesc desc{};
1390
desc.width = 512;
1391
desc.height = 1;
1392
desc.depth = 1;
1393
desc.z_stencil = false;
1394
desc.numLayers = 1;
1395
desc.multiSampleLevel = 0;
1396
desc.tag = "dynamic_clut";
1397
dynamicClutFbo_ = draw_->CreateFramebuffer(desc);
1398
desc.tag = "dynamic_clut_temp";
1399
dynamicClutTemp_ = draw_->CreateFramebuffer(desc);
1400
}
1401
1402
// We'll need to copy from the offset.
1403
const u32 fb_bpp = BufferFormatBytesPerPixel(chosenFramebuffer->fb_format);
1404
const int totalPixelsOffset = clutRenderOffset_ / fb_bpp;
1405
const int clutYOffset = totalPixelsOffset / chosenFramebuffer->fb_stride;
1406
const int clutXOffset = totalPixelsOffset % chosenFramebuffer->fb_stride;
1407
const int scale = chosenFramebuffer->renderScaleFactor;
1408
1409
// Copy the pixels to our temp clut, scaling down if needed and wrapping.
1410
framebufferManager_->BlitUsingRaster(
1411
chosenFramebuffer->fbo, clutXOffset * scale, clutYOffset * scale, (clutXOffset + 512.0f) * scale, (clutYOffset + 1.0f) * scale,
1412
dynamicClutTemp_, 0.0f, 0.0f, 512.0f, 1.0f,
1413
false, scale, framebufferManager_->Get2DPipeline(DRAW2D_COPY_COLOR_RECT2LIN), "copy_clut_to_temp");
1414
1415
framebufferManager_->RebindFramebuffer("after_copy_clut_to_temp");
1416
clutRenderFormat_ = chosenFramebuffer->fb_format;
1417
}
1418
NotifyMemInfo(MemBlockFlags::ALLOC, clutAddr, loadBytes, "CLUT");
1419
}
1420
1421
// It's possible for a game to load CLUT outside valid memory without crashing, should result in zeroes.
1422
u32 bytes = Memory::ValidSize(clutAddr, loadBytes);
1423
_assert_(bytes <= 2048);
1424
bool performDownload = PSP_CoreParameter().compat.flags().AllowDownloadCLUT;
1425
if (GPURecord::IsActive())
1426
performDownload = true;
1427
if (clutRenderAddress_ != 0xFFFFFFFF && performDownload) {
1428
framebufferManager_->DownloadFramebufferForClut(clutRenderAddress_, clutRenderOffset_ + bytes);
1429
Memory::MemcpyUnchecked(clutBufRaw_, clutAddr, bytes);
1430
if (bytes < loadBytes) {
1431
memset((u8 *)clutBufRaw_ + bytes, 0x00, loadBytes - bytes);
1432
}
1433
} else {
1434
// Here we could check for clutRenderAddress_ != 0xFFFFFFFF and zero the CLUT or something,
1435
// but choosing not to for now. Though the results of loading the CLUT from RAM here is
1436
// almost certainly going to be bogus.
1437
#ifdef _M_SSE
1438
if (bytes == loadBytes) {
1439
const __m128i *source = (const __m128i *)Memory::GetPointerUnchecked(clutAddr);
1440
__m128i *dest = (__m128i *)clutBufRaw_;
1441
int numBlocks = bytes / 32;
1442
for (int i = 0; i < numBlocks; i++, source += 2, dest += 2) {
1443
__m128i data1 = _mm_loadu_si128(source);
1444
__m128i data2 = _mm_loadu_si128(source + 1);
1445
_mm_store_si128(dest, data1);
1446
_mm_store_si128(dest + 1, data2);
1447
}
1448
} else {
1449
Memory::MemcpyUnchecked(clutBufRaw_, clutAddr, bytes);
1450
if (bytes < loadBytes) {
1451
memset((u8 *)clutBufRaw_ + bytes, 0x00, loadBytes - bytes);
1452
}
1453
}
1454
#elif PPSSPP_ARCH(ARM_NEON)
1455
if (bytes == loadBytes) {
1456
const uint32_t *source = (const uint32_t *)Memory::GetPointerUnchecked(clutAddr);
1457
uint32_t *dest = (uint32_t *)clutBufRaw_;
1458
int numBlocks = bytes / 32;
1459
for (int i = 0; i < numBlocks; i++, source += 8, dest += 8) {
1460
uint32x4_t data1 = vld1q_u32(source);
1461
uint32x4_t data2 = vld1q_u32(source + 4);
1462
vst1q_u32(dest, data1);
1463
vst1q_u32(dest + 4, data2);
1464
}
1465
} else {
1466
Memory::MemcpyUnchecked(clutBufRaw_, clutAddr, bytes);
1467
if (bytes < loadBytes) {
1468
memset((u8 *)clutBufRaw_ + bytes, 0x00, loadBytes - bytes);
1469
}
1470
}
1471
#else
1472
Memory::MemcpyUnchecked(clutBufRaw_, clutAddr, bytes);
1473
if (bytes < loadBytes) {
1474
memset((u8 *)clutBufRaw_ + bytes, 0x00, loadBytes - bytes);
1475
}
1476
#endif
1477
}
1478
1479
// Reload the clut next time.
1480
clutLastFormat_ = 0xFFFFFFFF;
1481
clutMaxBytes_ = std::max(clutMaxBytes_, loadBytes);
1482
}
1483
1484
void TextureCacheCommon::UnswizzleFromMem(u32 *dest, u32 destPitch, const u8 *texptr, u32 bufw, u32 height, u32 bytesPerPixel) {
1485
// Note: bufw is always aligned to 16 bytes, so rowWidth is always >= 16.
1486
const u32 rowWidth = (bytesPerPixel > 0) ? (bufw * bytesPerPixel) : (bufw / 2);
1487
// A visual mapping of unswizzling, where each letter is 16-byte and 8 letters is a block:
1488
//
1489
// ABCDEFGH IJKLMNOP
1490
// ->
1491
// AI
1492
// BJ
1493
// CK
1494
// ...
1495
//
1496
// bxc is the number of blocks in the x direction, and byc the number in the y direction.
1497
const int bxc = rowWidth / 16;
1498
// The height is not always aligned to 8, but rounds up.
1499
int byc = (height + 7) / 8;
1500
1501
DoUnswizzleTex16(texptr, dest, bxc, byc, destPitch);
1502
}
1503
1504
bool TextureCacheCommon::GetCurrentClutBuffer(GPUDebugBuffer &buffer) {
1505
const u32 bpp = gstate.getClutPaletteFormat() == GE_CMODE_32BIT_ABGR8888 ? 4 : 2;
1506
const u32 pixels = 1024 / bpp;
1507
1508
buffer.Allocate(pixels, 1, (GEBufferFormat)gstate.getClutPaletteFormat());
1509
memcpy(buffer.GetData(), clutBufRaw_, 1024);
1510
return true;
1511
}
1512
1513
// Host memory usage, not PSP memory usage.
1514
u32 TextureCacheCommon::EstimateTexMemoryUsage(const TexCacheEntry *entry) {
1515
const u16 dim = entry->dim;
1516
// TODO: This does not take into account the HD remaster's larger textures.
1517
const u8 dimW = ((dim >> 0) & 0xf);
1518
const u8 dimH = ((dim >> 8) & 0xf);
1519
1520
u32 pixelSize = 2;
1521
switch (entry->format) {
1522
case GE_TFMT_CLUT4:
1523
case GE_TFMT_CLUT8:
1524
case GE_TFMT_CLUT16:
1525
case GE_TFMT_CLUT32:
1526
// We assume cluts always point to 8888 for simplicity.
1527
pixelSize = 4;
1528
break;
1529
case GE_TFMT_4444:
1530
case GE_TFMT_5551:
1531
case GE_TFMT_5650:
1532
break;
1533
1534
case GE_TFMT_8888:
1535
case GE_TFMT_DXT1:
1536
case GE_TFMT_DXT3:
1537
case GE_TFMT_DXT5:
1538
default:
1539
pixelSize = 4;
1540
break;
1541
}
1542
1543
// This in other words multiplies by w and h.
1544
return pixelSize << (dimW + dimH);
1545
}
1546
1547
ReplacedTexture *TextureCacheCommon::FindReplacement(TexCacheEntry *entry, int *w, int *h, int *d) {
1548
if (*d != 1) {
1549
// We don't yet support replacing 3D textures.
1550
return nullptr;
1551
}
1552
1553
// Short circuit the non-enabled case.
1554
// Otherwise, due to bReplaceTexturesAllowLate, we'll still spawn tasks looking for replacements
1555
// that then won't be used.
1556
if (!replacer_.ReplaceEnabled()) {
1557
return nullptr;
1558
}
1559
1560
if ((entry->status & TexCacheEntry::STATUS_VIDEO) && !replacer_.AllowVideo()) {
1561
return nullptr;
1562
}
1563
1564
double replaceStart = time_now_d();
1565
u64 cachekey = entry->CacheKey();
1566
ReplacedTexture *replaced = replacer_.FindReplacement(cachekey, entry->fullhash, *w, *h);
1567
replacementTimeThisFrame_ += time_now_d() - replaceStart;
1568
if (!replaced) {
1569
// TODO: Remove the flag here?
1570
// entry->status &= ~TexCacheEntry::STATUS_TO_REPLACE;
1571
return nullptr;
1572
}
1573
entry->replacedTexture = replaced; // we know it's non-null here.
1574
PollReplacement(entry, w, h, d);
1575
return replaced;
1576
}
1577
1578
void TextureCacheCommon::PollReplacement(TexCacheEntry *entry, int *w, int *h, int *d) {
1579
// Allow some delay to reduce pop-in.
1580
constexpr double MAX_BUDGET_PER_TEX = 0.25 / 60.0;
1581
1582
double budget = std::min(MAX_BUDGET_PER_TEX, replacementFrameBudget_ - replacementTimeThisFrame_);
1583
1584
double replaceStart = time_now_d();
1585
if (entry->replacedTexture->Poll(budget)) {
1586
if (entry->replacedTexture->State() == ReplacementState::ACTIVE) {
1587
entry->replacedTexture->GetSize(0, w, h);
1588
// Consider it already "scaled.".
1589
entry->status |= TexCacheEntry::STATUS_IS_SCALED_OR_REPLACED;
1590
}
1591
1592
// Remove the flag, even if it was invalid.
1593
entry->status &= ~TexCacheEntry::STATUS_TO_REPLACE;
1594
}
1595
replacementTimeThisFrame_ += time_now_d() - replaceStart;
1596
1597
switch (entry->replacedTexture->State()) {
1598
case ReplacementState::UNLOADED:
1599
case ReplacementState::PENDING:
1600
// Make sure we keep polling.
1601
entry->status |= TexCacheEntry::STATUS_TO_REPLACE;
1602
break;
1603
default:
1604
break;
1605
}
1606
}
1607
1608
// This is only used in the GLES backend, where we don't point these to video memory.
1609
// So we shouldn't add a check for dstBuf != srcBuf, as long as the functions we call can handle that.
1610
static void ReverseColors(void *dstBuf, const void *srcBuf, GETextureFormat fmt, int numPixels) {
1611
switch (fmt) {
1612
case GE_TFMT_4444:
1613
ConvertRGBA4444ToABGR4444((u16 *)dstBuf, (const u16 *)srcBuf, numPixels);
1614
break;
1615
// Final Fantasy 2 uses this heavily in animated textures.
1616
case GE_TFMT_5551:
1617
ConvertRGBA5551ToABGR1555((u16 *)dstBuf, (const u16 *)srcBuf, numPixels);
1618
break;
1619
case GE_TFMT_5650:
1620
ConvertRGB565ToBGR565((u16 *)dstBuf, (const u16 *)srcBuf, numPixels);
1621
break;
1622
default:
1623
// No need to convert RGBA8888, right order already
1624
if (dstBuf != srcBuf) {
1625
memcpy(dstBuf, srcBuf, numPixels * sizeof(u32));
1626
}
1627
break;
1628
}
1629
}
1630
1631
static inline void ConvertFormatToRGBA8888(GETextureFormat format, u32 *dst, const u16 *src, u32 numPixels) {
1632
switch (format) {
1633
case GE_TFMT_4444:
1634
ConvertRGBA4444ToRGBA8888(dst, src, numPixels);
1635
break;
1636
case GE_TFMT_5551:
1637
ConvertRGBA5551ToRGBA8888(dst, src, numPixels);
1638
break;
1639
case GE_TFMT_5650:
1640
ConvertRGB565ToRGBA8888(dst, src, numPixels);
1641
break;
1642
default:
1643
_dbg_assert_msg_(false, "Incorrect texture format.");
1644
break;
1645
}
1646
}
1647
1648
static inline void ConvertFormatToRGBA8888(GEPaletteFormat format, u32 *dst, const u16 *src, u32 numPixels) {
1649
// The supported values are 1:1 identical.
1650
ConvertFormatToRGBA8888(GETextureFormat(format), dst, src, numPixels);
1651
}
1652
1653
template <typename DXTBlock, int n>
1654
static CheckAlphaResult DecodeDXTBlocks(uint8_t *out, int outPitch, uint32_t texaddr, const uint8_t *texptr,
1655
int w, int h, int bufw, bool reverseColors) {
1656
1657
int minw = std::min(bufw, w);
1658
uint32_t *dst = (uint32_t *)out;
1659
int outPitch32 = outPitch / sizeof(uint32_t);
1660
const DXTBlock *src = (const DXTBlock *)texptr;
1661
1662
if (!Memory::IsValidRange(texaddr, (h / 4) * (bufw / 4) * sizeof(DXTBlock))) {
1663
ERROR_LOG_REPORT(Log::G3D, "DXT%d texture extends beyond valid RAM: %08x + %d x %d", n, texaddr, bufw, h);
1664
uint32_t limited = Memory::ValidSize(texaddr, (h / 4) * (bufw / 4) * sizeof(DXTBlock));
1665
// This might possibly be 0, but try to decode what we can (might even be how the PSP behaves.)
1666
h = (((int)limited / sizeof(DXTBlock)) / (bufw / 4)) * 4;
1667
}
1668
1669
u32 alphaSum = 1;
1670
for (int y = 0; y < h; y += 4) {
1671
u32 blockIndex = (y / 4) * (bufw / 4);
1672
int blockHeight = std::min(h - y, 4);
1673
for (int x = 0; x < minw; x += 4) {
1674
int blockWidth = std::min(minw - x, 4);
1675
if constexpr (n == 1)
1676
DecodeDXT1Block(dst + outPitch32 * y + x, (const DXT1Block *)src + blockIndex, outPitch32, blockWidth, blockHeight, &alphaSum);
1677
else if constexpr (n == 3)
1678
DecodeDXT3Block(dst + outPitch32 * y + x, (const DXT3Block *)src + blockIndex, outPitch32, blockWidth, blockHeight);
1679
else if constexpr (n == 5)
1680
DecodeDXT5Block(dst + outPitch32 * y + x, (const DXT5Block *)src + blockIndex, outPitch32, blockWidth, blockHeight);
1681
blockIndex++;
1682
}
1683
}
1684
1685
if (reverseColors) {
1686
ReverseColors(out, out, GE_TFMT_8888, outPitch32 * h);
1687
}
1688
1689
if constexpr (n == 1) {
1690
return alphaSum == 1 ? CHECKALPHA_FULL : CHECKALPHA_ANY;
1691
} else {
1692
// Just report that we don't have full alpha, since these formats are made for that.
1693
return CHECKALPHA_ANY;
1694
}
1695
}
1696
1697
inline u32 ClutFormatToFullAlpha(GEPaletteFormat fmt, bool reverseColors) {
1698
switch (fmt) {
1699
case GE_CMODE_16BIT_ABGR4444: return reverseColors ? 0x000F : 0xF000;
1700
case GE_CMODE_16BIT_ABGR5551: return reverseColors ? 0x0001 : 0x8000;
1701
case GE_CMODE_32BIT_ABGR8888: return 0xFF000000;
1702
case GE_CMODE_16BIT_BGR5650: return 0;
1703
default: return 0;
1704
}
1705
}
1706
1707
inline u32 TfmtRawToFullAlpha(GETextureFormat fmt) {
1708
switch (fmt) {
1709
case GE_TFMT_4444: return 0xF000;
1710
case GE_TFMT_5551: return 0x8000;
1711
case GE_TFMT_8888: return 0xFF000000;
1712
case GE_TFMT_5650: return 0;
1713
default: return 0;
1714
}
1715
}
1716
1717
// Used for converting CLUT4 to CLUT8.
1718
// Could SIMD or whatever, though will hardly be a bottleneck.
1719
static void Expand4To8Bits(u8 *dest, const u8 *src, int srcWidth) {
1720
for (int i = 0; i < (srcWidth + 1) / 2; i++) {
1721
u8 lower = src[i] & 0xF;
1722
u8 upper = src[i] >> 4;
1723
dest[i * 2] = lower;
1724
dest[i * 2 + 1] = upper;
1725
}
1726
}
1727
1728
CheckAlphaResult TextureCacheCommon::DecodeTextureLevel(u8 *out, int outPitch, GETextureFormat format, GEPaletteFormat clutformat, uint32_t texaddr, int level, int bufw, TexDecodeFlags flags) {
1729
u32 alphaSum = 0xFFFFFFFF;
1730
u32 fullAlphaMask = 0x0;
1731
1732
bool expandTo32bit = (flags & TexDecodeFlags::EXPAND32) != 0;
1733
bool reverseColors = (flags & TexDecodeFlags::REVERSE_COLORS) != 0;
1734
bool toClut8 = (flags & TexDecodeFlags::TO_CLUT8) != 0;
1735
1736
if (toClut8 && format != GE_TFMT_CLUT8 && format != GE_TFMT_CLUT4) {
1737
_dbg_assert_(false);
1738
}
1739
1740
bool swizzled = gstate.isTextureSwizzled();
1741
if ((texaddr & 0x00600000) != 0 && Memory::IsVRAMAddress(texaddr)) {
1742
// This means it's in a mirror, possibly a swizzled mirror. Let's report.
1743
WARN_LOG_REPORT_ONCE(texmirror, Log::G3D, "Decoding texture from VRAM mirror at %08x swizzle=%d", texaddr, swizzled ? 1 : 0);
1744
if ((texaddr & 0x00200000) == 0x00200000) {
1745
// Technically 2 and 6 are slightly different, but this is better than nothing probably.
1746
// We should only see this with depth textures anyway which we don't support uploading (yet).
1747
swizzled = !swizzled;
1748
}
1749
// Note that (texaddr & 0x00600000) == 0x00600000 is very likely to be depth texturing.
1750
}
1751
1752
int w = gstate.getTextureWidth(level);
1753
int h = gstate.getTextureHeight(level);
1754
const u8 *texptr = Memory::GetPointer(texaddr);
1755
const uint32_t byteSize = (textureBitsPerPixel[format] * bufw * h) / 8;
1756
1757
char buf[128];
1758
size_t len = snprintf(buf, sizeof(buf), "Tex_%08x_%dx%d_%s", texaddr, w, h, GeTextureFormatToString(format, clutformat));
1759
NotifyMemInfo(MemBlockFlags::TEXTURE, texaddr, byteSize, buf, len);
1760
1761
switch (format) {
1762
case GE_TFMT_CLUT4:
1763
{
1764
const bool mipmapShareClut = gstate.isClutSharedForMipmaps();
1765
const int clutSharingOffset = mipmapShareClut ? 0 : level * 16;
1766
1767
if (swizzled) {
1768
tmpTexBuf32_.resize(bufw * ((h + 7) & ~7));
1769
UnswizzleFromMem(tmpTexBuf32_.data(), bufw / 2, texptr, bufw, h, 0);
1770
texptr = (u8 *)tmpTexBuf32_.data();
1771
}
1772
1773
if (toClut8) {
1774
// We just need to expand from 4 to 8 bits.
1775
for (int y = 0; y < h; ++y) {
1776
Expand4To8Bits((u8 *)out + outPitch * y, texptr + (bufw * y) / 2, w);
1777
}
1778
// We can't know anything about alpha.
1779
return CHECKALPHA_ANY;
1780
}
1781
1782
switch (clutformat) {
1783
case GE_CMODE_16BIT_BGR5650:
1784
case GE_CMODE_16BIT_ABGR5551:
1785
case GE_CMODE_16BIT_ABGR4444:
1786
{
1787
// The w > 1 check is to not need a case that handles a single pixel
1788
// in DeIndexTexture4Optimal<u16>.
1789
if (clutAlphaLinear_ && mipmapShareClut && !expandTo32bit && w >= 4) {
1790
// We don't bother with fullalpha here (clutAlphaLinear_)
1791
// Here, reverseColors means the CLUT is already reversed.
1792
if (reverseColors) {
1793
for (int y = 0; y < h; ++y) {
1794
DeIndexTexture4Optimal((u16 *)(out + outPitch * y), texptr + (bufw * y) / 2, w, clutAlphaLinearColor_);
1795
}
1796
} else {
1797
for (int y = 0; y < h; ++y) {
1798
DeIndexTexture4OptimalRev((u16 *)(out + outPitch * y), texptr + (bufw * y) / 2, w, clutAlphaLinearColor_);
1799
}
1800
}
1801
} else {
1802
// Need to have the "un-reversed" (raw) CLUT here since we are using a generic conversion function.
1803
if (expandTo32bit) {
1804
// We simply expand the CLUT to 32-bit, then we deindex as usual. Probably the fastest way.
1805
const u16 *clut = GetCurrentRawClut<u16>() + clutSharingOffset;
1806
const int clutStart = gstate.getClutIndexStartPos();
1807
if (gstate.getClutIndexShift() == 0 || gstate.getClutIndexMask() <= 16) {
1808
ConvertFormatToRGBA8888(clutformat, expandClut_ + clutStart, clut + clutStart, 16);
1809
} else {
1810
// To be safe for shifts and wrap around, convert the entire CLUT.
1811
ConvertFormatToRGBA8888(clutformat, expandClut_, clut, 512);
1812
}
1813
fullAlphaMask = 0xFF000000;
1814
for (int y = 0; y < h; ++y) {
1815
DeIndexTexture4<u32>((u32 *)(out + outPitch * y), texptr + (bufw * y) / 2, w, expandClut_, &alphaSum);
1816
}
1817
} else {
1818
// If we're reversing colors, the CLUT was already reversed, no special handling needed.
1819
const u16 *clut = GetCurrentClut<u16>() + clutSharingOffset;
1820
fullAlphaMask = ClutFormatToFullAlpha(clutformat, reverseColors);
1821
for (int y = 0; y < h; ++y) {
1822
DeIndexTexture4<u16>((u16 *)(out + outPitch * y), texptr + (bufw * y) / 2, w, clut, &alphaSum);
1823
}
1824
}
1825
}
1826
1827
if (clutformat == GE_CMODE_16BIT_BGR5650) {
1828
// Our formula at the end of the function can't handle this cast so we return early.
1829
return CHECKALPHA_FULL;
1830
}
1831
}
1832
break;
1833
1834
case GE_CMODE_32BIT_ABGR8888:
1835
{
1836
const u32 *clut = GetCurrentClut<u32>() + clutSharingOffset;
1837
fullAlphaMask = 0xFF000000;
1838
for (int y = 0; y < h; ++y) {
1839
DeIndexTexture4<u32>((u32 *)(out + outPitch * y), texptr + (bufw * y) / 2, w, clut, &alphaSum);
1840
}
1841
}
1842
break;
1843
1844
default:
1845
ERROR_LOG_REPORT(Log::G3D, "Unknown CLUT4 texture mode %d", gstate.getClutPaletteFormat());
1846
return CHECKALPHA_ANY;
1847
}
1848
}
1849
break;
1850
1851
case GE_TFMT_CLUT8:
1852
if (toClut8) {
1853
if (gstate.isTextureSwizzled()) {
1854
tmpTexBuf32_.resize(bufw * ((h + 7) & ~7));
1855
UnswizzleFromMem(tmpTexBuf32_.data(), bufw, texptr, bufw, h, 1);
1856
texptr = (u8 *)tmpTexBuf32_.data();
1857
}
1858
// After deswizzling, we are in the correct format and can just copy.
1859
for (int y = 0; y < h; ++y) {
1860
memcpy((u8 *)out + outPitch * y, texptr + (bufw * y), w);
1861
}
1862
// We can't know anything about alpha.
1863
return CHECKALPHA_ANY;
1864
}
1865
return ReadIndexedTex(out, outPitch, level, texptr, 1, bufw, reverseColors, expandTo32bit);
1866
1867
case GE_TFMT_CLUT16:
1868
return ReadIndexedTex(out, outPitch, level, texptr, 2, bufw, reverseColors, expandTo32bit);
1869
1870
case GE_TFMT_CLUT32:
1871
return ReadIndexedTex(out, outPitch, level, texptr, 4, bufw, reverseColors, expandTo32bit);
1872
1873
case GE_TFMT_4444:
1874
case GE_TFMT_5551:
1875
case GE_TFMT_5650:
1876
if (!swizzled) {
1877
// Just a simple copy, we swizzle the color format.
1878
fullAlphaMask = TfmtRawToFullAlpha(format);
1879
if (expandTo32bit) {
1880
// This is OK even if reverseColors is on, because it expands to the 8888 format which is the same in reverse mode.
1881
for (int y = 0; y < h; ++y) {
1882
CheckMask16((const u16 *)(texptr + bufw * sizeof(u16) * y), w, &alphaSum);
1883
ConvertFormatToRGBA8888(format, (u32 *)(out + outPitch * y), (const u16 *)texptr + bufw * y, w);
1884
}
1885
} else if (reverseColors) {
1886
// Just check the input's alpha to reuse code. TODO: make a specialized ReverseColors that checks as we go.
1887
for (int y = 0; y < h; ++y) {
1888
CheckMask16((const u16 *)(texptr + bufw * sizeof(u16) * y), w, &alphaSum);
1889
ReverseColors(out + outPitch * y, texptr + bufw * sizeof(u16) * y, format, w);
1890
}
1891
} else {
1892
for (int y = 0; y < h; ++y) {
1893
CopyAndSumMask16((u16 *)(out + outPitch * y), (u16 *)(texptr + bufw * sizeof(u16) * y), w, &alphaSum);
1894
}
1895
}
1896
} /* else if (h >= 8 && bufw <= w && !expandTo32bit) {
1897
// TODO: Handle alpha mask. This will require special versions of UnswizzleFromMem to keep the optimization.
1898
// Note: this is always safe since h must be a power of 2, so a multiple of 8.
1899
UnswizzleFromMem((u32 *)out, outPitch, texptr, bufw, h, 2);
1900
if (reverseColors) {
1901
ReverseColors(out, out, format, h * outPitch / 2, useBGRA);
1902
}
1903
}*/ else {
1904
// We don't have enough space for all rows in out, so use a temp buffer.
1905
tmpTexBuf32_.resize(bufw * ((h + 7) & ~7));
1906
UnswizzleFromMem(tmpTexBuf32_.data(), bufw * 2, texptr, bufw, h, 2);
1907
const u8 *unswizzled = (u8 *)tmpTexBuf32_.data();
1908
1909
fullAlphaMask = TfmtRawToFullAlpha(format);
1910
if (expandTo32bit) {
1911
// This is OK even if reverseColors is on, because it expands to the 8888 format which is the same in reverse mode.
1912
// Just check the swizzled input's alpha to reuse code. TODO: make a specialized ConvertFormatToRGBA8888 that checks as we go.
1913
for (int y = 0; y < h; ++y) {
1914
CheckMask16((const u16 *)(unswizzled + bufw * sizeof(u16) * y), w, &alphaSum);
1915
ConvertFormatToRGBA8888(format, (u32 *)(out + outPitch * y), (const u16 *)unswizzled + bufw * y, w);
1916
}
1917
} else if (reverseColors) {
1918
// Just check the swizzled input's alpha to reuse code. TODO: make a specialized ReverseColors that checks as we go.
1919
for (int y = 0; y < h; ++y) {
1920
CheckMask16((const u16 *)(unswizzled + bufw * sizeof(u16) * y), w, &alphaSum);
1921
ReverseColors(out + outPitch * y, unswizzled + bufw * sizeof(u16) * y, format, w);
1922
}
1923
} else {
1924
for (int y = 0; y < h; ++y) {
1925
CopyAndSumMask16((u16 *)(out + outPitch * y), (const u16 *)(unswizzled + bufw * sizeof(u16) * y), w, &alphaSum);
1926
}
1927
}
1928
}
1929
if (format == GE_TFMT_5650) {
1930
return CHECKALPHA_FULL;
1931
}
1932
break;
1933
1934
case GE_TFMT_8888:
1935
if (!swizzled) {
1936
fullAlphaMask = TfmtRawToFullAlpha(format);
1937
if (reverseColors) {
1938
for (int y = 0; y < h; ++y) {
1939
CheckMask32((const u32 *)(texptr + bufw * sizeof(u32) * y), w, &alphaSum);
1940
ReverseColors(out + outPitch * y, texptr + bufw * sizeof(u32) * y, format, w);
1941
}
1942
} else {
1943
for (int y = 0; y < h; ++y) {
1944
CopyAndSumMask32((u32 *)(out + outPitch * y), (const u32 *)(texptr + bufw * sizeof(u32) * y), w, &alphaSum);
1945
}
1946
}
1947
} /* else if (h >= 8 && bufw <= w) {
1948
// TODO: Handle alpha mask
1949
UnswizzleFromMem((u32 *)out, outPitch, texptr, bufw, h, 4);
1950
if (reverseColors) {
1951
ReverseColors(out, out, format, h * outPitch / 4, useBGRA);
1952
}
1953
}*/ else {
1954
tmpTexBuf32_.resize(bufw * ((h + 7) & ~7));
1955
UnswizzleFromMem(tmpTexBuf32_.data(), bufw * 4, texptr, bufw, h, 4);
1956
const u8 *unswizzled = (u8 *)tmpTexBuf32_.data();
1957
1958
fullAlphaMask = TfmtRawToFullAlpha(format);
1959
if (reverseColors) {
1960
for (int y = 0; y < h; ++y) {
1961
CheckMask32((const u32 *)(unswizzled + bufw * sizeof(u32) * y), w, &alphaSum);
1962
ReverseColors(out + outPitch * y, unswizzled + bufw * sizeof(u32) * y, format, w);
1963
}
1964
} else {
1965
for (int y = 0; y < h; ++y) {
1966
CopyAndSumMask32((u32 *)(out + outPitch * y), (const u32 *)(unswizzled + bufw * sizeof(u32) * y), w, &alphaSum);
1967
}
1968
}
1969
}
1970
break;
1971
1972
case GE_TFMT_DXT1:
1973
return DecodeDXTBlocks<DXT1Block, 1>(out, outPitch, texaddr, texptr, w, h, bufw, reverseColors);
1974
1975
case GE_TFMT_DXT3:
1976
return DecodeDXTBlocks<DXT3Block, 3>(out, outPitch, texaddr, texptr, w, h, bufw, reverseColors);
1977
1978
case GE_TFMT_DXT5:
1979
return DecodeDXTBlocks<DXT5Block, 5>(out, outPitch, texaddr, texptr, w, h, bufw, reverseColors);
1980
1981
default:
1982
ERROR_LOG_REPORT(Log::G3D, "Unknown Texture Format %d!!!", format);
1983
break;
1984
}
1985
1986
return AlphaSumIsFull(alphaSum, fullAlphaMask) ? CHECKALPHA_FULL : CHECKALPHA_ANY;
1987
}
1988
1989
CheckAlphaResult TextureCacheCommon::ReadIndexedTex(u8 *out, int outPitch, int level, const u8 *texptr, int bytesPerIndex, int bufw, bool reverseColors, bool expandTo32Bit) {
1990
int w = gstate.getTextureWidth(level);
1991
int h = gstate.getTextureHeight(level);
1992
1993
if (gstate.isTextureSwizzled()) {
1994
tmpTexBuf32_.resize(bufw * ((h + 7) & ~7));
1995
UnswizzleFromMem(tmpTexBuf32_.data(), bufw * bytesPerIndex, texptr, bufw, h, bytesPerIndex);
1996
texptr = (u8 *)tmpTexBuf32_.data();
1997
}
1998
1999
// Misshitsu no Sacrifice has separate CLUT data, this is a hack to allow it.
2000
// Normally separate CLUTs are not allowed for 8-bit or higher indices.
2001
const bool mipmapShareClut = gstate.isClutSharedForMipmaps() || gstate.getClutLoadBlocks() != 0x40;
2002
const int clutSharingOffset = mipmapShareClut ? 0 : (level & 1) * 256;
2003
2004
GEPaletteFormat palFormat = (GEPaletteFormat)gstate.getClutPaletteFormat();
2005
2006
const u16 *clut16 = (const u16 *)clutBuf_ + clutSharingOffset;
2007
const u32 *clut32 = (const u32 *)clutBuf_ + clutSharingOffset;
2008
2009
if (expandTo32Bit && palFormat != GE_CMODE_32BIT_ABGR8888) {
2010
const u16 *clut16raw = (const u16 *)clutBufRaw_ + clutSharingOffset;
2011
// It's possible to access the latter half of the CLUT using the start pos.
2012
const int clutStart = gstate.getClutIndexStartPos();
2013
if (clutStart > 256) {
2014
// Access wraps around when start + index goes over.
2015
ConvertFormatToRGBA8888(GEPaletteFormat(palFormat), expandClut_, clut16raw, 512);
2016
} else {
2017
ConvertFormatToRGBA8888(GEPaletteFormat(palFormat), expandClut_ + clutStart, clut16raw + clutStart, 256);
2018
}
2019
clut32 = expandClut_;
2020
palFormat = GE_CMODE_32BIT_ABGR8888;
2021
}
2022
2023
u32 alphaSum = 0xFFFFFFFF;
2024
u32 fullAlphaMask = ClutFormatToFullAlpha(palFormat, reverseColors);
2025
2026
switch (palFormat) {
2027
case GE_CMODE_16BIT_BGR5650:
2028
case GE_CMODE_16BIT_ABGR5551:
2029
case GE_CMODE_16BIT_ABGR4444:
2030
{
2031
switch (bytesPerIndex) {
2032
case 1:
2033
for (int y = 0; y < h; ++y) {
2034
DeIndexTexture((u16 *)(out + outPitch * y), (const u8 *)texptr + bufw * y, w, clut16, &alphaSum);
2035
}
2036
break;
2037
2038
case 2:
2039
for (int y = 0; y < h; ++y) {
2040
DeIndexTexture((u16 *)(out + outPitch * y), (const u16_le *)texptr + bufw * y, w, clut16, &alphaSum);
2041
}
2042
break;
2043
2044
case 4:
2045
for (int y = 0; y < h; ++y) {
2046
DeIndexTexture((u16 *)(out + outPitch * y), (const u32_le *)texptr + bufw * y, w, clut16, &alphaSum);
2047
}
2048
break;
2049
}
2050
}
2051
break;
2052
2053
case GE_CMODE_32BIT_ABGR8888:
2054
{
2055
2056
switch (bytesPerIndex) {
2057
case 1:
2058
for (int y = 0; y < h; ++y) {
2059
DeIndexTexture((u32 *)(out + outPitch * y), (const u8 *)texptr + bufw * y, w, clut32, &alphaSum);
2060
}
2061
break;
2062
2063
case 2:
2064
for (int y = 0; y < h; ++y) {
2065
DeIndexTexture((u32 *)(out + outPitch * y), (const u16_le *)texptr + bufw * y, w, clut32, &alphaSum);
2066
}
2067
break;
2068
2069
case 4:
2070
for (int y = 0; y < h; ++y) {
2071
DeIndexTexture((u32 *)(out + outPitch * y), (const u32_le *)texptr + bufw * y, w, clut32, &alphaSum);
2072
}
2073
break;
2074
}
2075
}
2076
break;
2077
2078
default:
2079
ERROR_LOG_REPORT(Log::G3D, "Unhandled clut texture mode %d!!!", gstate.getClutPaletteFormat());
2080
break;
2081
}
2082
2083
if (palFormat == GE_CMODE_16BIT_BGR5650) {
2084
return CHECKALPHA_FULL;
2085
} else {
2086
return AlphaSumIsFull(alphaSum, fullAlphaMask) ? CHECKALPHA_FULL : CHECKALPHA_ANY;
2087
}
2088
}
2089
2090
void TextureCacheCommon::ApplyTexture() {
2091
TexCacheEntry *entry = nextTexture_;
2092
if (!entry) {
2093
// Maybe we bound a framebuffer?
2094
ForgetLastTexture();
2095
if (failedTexture_) {
2096
// Backends should handle this by binding a black texture with 0 alpha.
2097
BindTexture(nullptr);
2098
} else if (nextFramebufferTexture_) {
2099
// ApplyTextureFrameBuffer is responsible for setting SetTextureFullAlpha.
2100
ApplyTextureFramebuffer(nextFramebufferTexture_, gstate.getTextureFormat(), nextFramebufferTextureChannel_);
2101
nextFramebufferTexture_ = nullptr;
2102
}
2103
2104
// We don't set the 3D texture state here or anything else, on some backends (?)
2105
// a nextTexture_ of nullptr means keep the current texture.
2106
return;
2107
}
2108
2109
nextTexture_ = nullptr;
2110
2111
UpdateMaxSeenV(entry, gstate.isModeThrough());
2112
2113
if (nextNeedsRebuild_) {
2114
// Regardless of hash fails or otherwise, if this is a video, mark it frequently changing.
2115
// This prevents temporary scaling perf hits on the first second of video.
2116
if (IsVideo(entry->addr)) {
2117
entry->status |= TexCacheEntry::STATUS_CHANGE_FREQUENT | TexCacheEntry::STATUS_VIDEO;
2118
} else {
2119
entry->status &= ~TexCacheEntry::STATUS_VIDEO;
2120
}
2121
2122
if (nextNeedsRehash_) {
2123
PROFILE_THIS_SCOPE("texhash");
2124
// Update the hash on the texture.
2125
int w = gstate.getTextureWidth(0);
2126
int h = gstate.getTextureHeight(0);
2127
bool swizzled = gstate.isTextureSwizzled();
2128
entry->fullhash = QuickTexHash(replacer_, entry->addr, entry->bufw, w, h, swizzled, GETextureFormat(entry->format), entry);
2129
2130
// TODO: Here we could check the secondary cache; maybe the texture is in there?
2131
// We would need to abort the build if so.
2132
}
2133
if (nextNeedsChange_) {
2134
// This texture existed previously, let's handle the change.
2135
HandleTextureChange(entry, nextChangeReason_, false, true);
2136
}
2137
// We actually build afterward (shared with rehash rebuild.)
2138
} else if (nextNeedsRehash_) {
2139
// Okay, this matched and didn't change - but let's check the hash. Maybe it will change.
2140
bool doDelete = true;
2141
if (!CheckFullHash(entry, doDelete)) {
2142
HandleTextureChange(entry, "hash fail", true, doDelete);
2143
nextNeedsRebuild_ = true;
2144
} else if (nextTexture_ != nullptr) {
2145
// The secondary cache may choose an entry from its storage by setting nextTexture_.
2146
// This means we should set that, instead of our previous entry.
2147
entry = nextTexture_;
2148
nextTexture_ = nullptr;
2149
UpdateMaxSeenV(entry, gstate.isModeThrough());
2150
}
2151
}
2152
2153
// Okay, now actually rebuild the texture if needed.
2154
if (nextNeedsRebuild_) {
2155
_assert_(!entry->texturePtr);
2156
BuildTexture(entry);
2157
ForgetLastTexture();
2158
}
2159
2160
gstate_c.SetTextureIsVideo((entry->status & TexCacheEntry::STATUS_VIDEO) != 0);
2161
if (entry->status & TexCacheEntry::STATUS_CLUT_GPU) {
2162
// Special process.
2163
ApplyTextureDepal(entry);
2164
entry->lastFrame = gpuStats.numFlips;
2165
gstate_c.SetTextureFullAlpha(false);
2166
gstate_c.SetTextureIs3D(false);
2167
gstate_c.SetTextureIsArray(false);
2168
gstate_c.SetTextureIsBGRA(false);
2169
} else {
2170
entry->lastFrame = gpuStats.numFlips;
2171
BindTexture(entry);
2172
gstate_c.SetTextureFullAlpha(entry->GetAlphaStatus() == TexCacheEntry::STATUS_ALPHA_FULL);
2173
gstate_c.SetTextureIs3D((entry->status & TexCacheEntry::STATUS_3D) != 0);
2174
gstate_c.SetTextureIsArray(false);
2175
gstate_c.SetTextureIsBGRA((entry->status & TexCacheEntry::STATUS_BGRA) != 0);
2176
gstate_c.SetUseShaderDepal(ShaderDepalMode::OFF);
2177
}
2178
}
2179
2180
// Can we depalettize at all? This refers to both in-fragment-shader depal and "traditional" depal through a separate pass.
2181
static bool CanDepalettize(GETextureFormat texFormat, GEBufferFormat bufferFormat) {
2182
if (IsClutFormat(texFormat)) {
2183
switch (bufferFormat) {
2184
case GE_FORMAT_4444:
2185
case GE_FORMAT_565:
2186
case GE_FORMAT_5551:
2187
case GE_FORMAT_DEPTH16:
2188
if (texFormat == GE_TFMT_CLUT16) {
2189
return true;
2190
}
2191
if (texFormat == GE_TFMT_CLUT8 && bufferFormat == GE_FORMAT_5551 && PSP_CoreParameter().compat.flags().SOCOMClut8Replacement) {
2192
// Wacky case from issue #16210 (SOCOM etc).
2193
return true;
2194
}
2195
break;
2196
case GE_FORMAT_8888:
2197
if (texFormat == GE_TFMT_CLUT32 || texFormat == GE_TFMT_CLUT8) { // clut8 takes a special depal mode.
2198
return true;
2199
}
2200
break;
2201
case GE_FORMAT_CLUT8:
2202
case GE_FORMAT_INVALID:
2203
// Shouldn't happen here.
2204
return false;
2205
}
2206
WARN_LOG(Log::G3D, "Invalid CLUT/framebuffer combination: %s vs %s", GeTextureFormatToString(texFormat), GeBufferFormatToString(bufferFormat));
2207
return false;
2208
} else if (texFormat == GE_TFMT_5650 && bufferFormat == GE_FORMAT_DEPTH16) {
2209
// We can also "depal" 565 format, this is used to read depth buffers as 565 on occasion (#15491).
2210
return true;
2211
}
2212
return false;
2213
}
2214
2215
// If the palette is detected as a smooth ramp, we can interpolate for higher color precision.
2216
// But we only do it if the mask/shift exactly matches a color channel, else something different might be going
2217
// on and we definitely don't want to interpolate.
2218
// Great enhancement for Test Drive and Manhunt 2.
2219
static bool CanUseSmoothDepal(const GPUgstate &gstate, GEBufferFormat framebufferFormat, const ClutTexture &clutTexture) {
2220
for (int i = 0; i < ClutTexture::MAX_RAMPS; i++) {
2221
if (gstate.getClutIndexStartPos() == clutTexture.rampStarts[i] &&
2222
gstate.getClutIndexMask() < clutTexture.rampLengths[i]) {
2223
switch (framebufferFormat) {
2224
case GE_FORMAT_565:
2225
if (gstate.getClutIndexShift() == 0 || gstate.getClutIndexShift() == 11) {
2226
return gstate.getClutIndexMask() == 0x1F;
2227
} else if (gstate.getClutIndexShift() == 5) {
2228
return gstate.getClutIndexMask() == 0x3F;
2229
}
2230
break;
2231
case GE_FORMAT_5551:
2232
if (gstate.getClutIndexShift() == 0 || gstate.getClutIndexShift() == 5 || gstate.getClutIndexShift() == 10) {
2233
return gstate.getClutIndexMask() == 0x1F;
2234
}
2235
break;
2236
default:
2237
// No uses for the other formats yet, add if needed.
2238
break;
2239
}
2240
}
2241
}
2242
return false;
2243
}
2244
2245
void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer, GETextureFormat texFormat, RasterChannel channel) {
2246
Draw2DPipeline *textureShader = nullptr;
2247
uint32_t clutMode = gstate.clutformat & 0xFFFFFF;
2248
2249
bool depth = channel == RASTER_DEPTH;
2250
bool need_depalettize = CanDepalettize(texFormat, depth ? GE_FORMAT_DEPTH16 : framebuffer->fb_format);
2251
2252
// Shader depal is not supported during 3D texturing or depth texturing, and requires 32-bit integer instructions in the shader.
2253
bool useShaderDepal = framebufferManager_->GetCurrentRenderVFB() != framebuffer &&
2254
!depth && clutRenderAddress_ == 0xFFFFFFFF &&
2255
!gstate_c.curTextureIs3D &&
2256
draw_->GetShaderLanguageDesc().bitwiseOps &&
2257
!(texFormat == GE_TFMT_CLUT8 && framebuffer->fb_format == GE_FORMAT_5551); // socom
2258
2259
switch (draw_->GetShaderLanguageDesc().shaderLanguage) {
2260
case ShaderLanguage::HLSL_D3D9:
2261
useShaderDepal = false;
2262
break;
2263
case ShaderLanguage::GLSL_1xx:
2264
// Force off for now, in case <= GLSL 1.20 or GLES 2, which don't support switch-case.
2265
useShaderDepal = false;
2266
break;
2267
default:
2268
break;
2269
}
2270
2271
const GEPaletteFormat clutFormat = gstate.getClutPaletteFormat();
2272
ClutTexture clutTexture{};
2273
bool smoothedDepal = false;
2274
u32 depthUpperBits = 0;
2275
2276
if (need_depalettize) {
2277
if (clutRenderAddress_ == 0xFFFFFFFF) {
2278
clutTexture = textureShaderCache_->GetClutTexture(clutFormat, clutHash_, clutBufRaw_);
2279
smoothedDepal = CanUseSmoothDepal(gstate, framebuffer->fb_format, clutTexture);
2280
} else {
2281
// The CLUT texture is dynamic, it's the framebuffer pointed to by clutRenderAddress.
2282
// Instead of texturing directly from that, we copy to a temporary CLUT texture.
2283
GEBufferFormat expectedCLUTBufferFormat = (GEBufferFormat)clutFormat;
2284
2285
// OK, figure out what format we want our framebuffer in, so it can be reinterpreted if needed.
2286
// If no reinterpretation is needed, we'll automatically just get a copy shader.
2287
float scaleFactorX = 1.0f;
2288
Draw2DPipeline *reinterpret = framebufferManager_->GetReinterpretPipeline(clutRenderFormat_, expectedCLUTBufferFormat, &scaleFactorX);
2289
framebufferManager_->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");
2290
}
2291
2292
if (useShaderDepal) {
2293
// Very icky conflation here of native and thin3d rendering. This will need careful work per backend in BindAsClutTexture.
2294
BindAsClutTexture(clutTexture.texture, smoothedDepal);
2295
2296
framebufferManager_->BindFramebufferAsColorTexture(0, framebuffer, BINDFBCOLOR_MAY_COPY_WITH_UV | BINDFBCOLOR_APPLY_TEX_OFFSET, Draw::ALL_LAYERS);
2297
// Vulkan needs to do some extra work here to pick out the native handle from Draw.
2298
BoundFramebufferTexture();
2299
2300
SamplerCacheKey samplerKey = GetFramebufferSamplingParams(framebuffer->bufferWidth, framebuffer->bufferHeight);
2301
samplerKey.magFilt = false;
2302
samplerKey.minFilt = false;
2303
samplerKey.mipEnable = false;
2304
ApplySamplingParams(samplerKey);
2305
2306
ShaderDepalMode mode = ShaderDepalMode::NORMAL;
2307
if (texFormat == GE_TFMT_CLUT8 && framebuffer->fb_format == GE_FORMAT_8888) {
2308
mode = ShaderDepalMode::CLUT8_8888;
2309
smoothedDepal = false; // just in case
2310
} else if (smoothedDepal) {
2311
mode = ShaderDepalMode::SMOOTHED;
2312
}
2313
2314
gstate_c.Dirty(DIRTY_DEPAL);
2315
gstate_c.SetUseShaderDepal(mode);
2316
gstate_c.depalFramebufferFormat = framebuffer->fb_format;
2317
2318
const u32 bytesPerColor = clutFormat == GE_CMODE_32BIT_ABGR8888 ? sizeof(u32) : sizeof(u16);
2319
const u32 clutTotalColors = clutMaxBytes_ / bytesPerColor;
2320
CheckAlphaResult alphaStatus = CheckCLUTAlpha((const uint8_t *)clutBufRaw_, clutFormat, clutTotalColors);
2321
gstate_c.SetTextureFullAlpha(alphaStatus == CHECKALPHA_FULL);
2322
2323
draw_->Invalidate(InvalidationFlags::CACHED_RENDER_STATE);
2324
return;
2325
}
2326
2327
depthUpperBits = (depth && framebuffer->fb_format == GE_FORMAT_8888) ? ((gstate.getTextureAddress(0) & 0x600000) >> 20) : 0;
2328
2329
textureShader = textureShaderCache_->GetDepalettizeShader(clutMode, texFormat, depth ? GE_FORMAT_DEPTH16 : framebuffer->fb_format, smoothedDepal, depthUpperBits);
2330
gstate_c.SetUseShaderDepal(ShaderDepalMode::OFF);
2331
}
2332
2333
if (textureShader) {
2334
bool needsDepthXSwizzle = depthUpperBits == 2;
2335
2336
int depalWidth = framebuffer->renderWidth;
2337
int texWidth = framebuffer->bufferWidth;
2338
if (needsDepthXSwizzle) {
2339
texWidth = RoundUpToPowerOf2(framebuffer->bufferWidth);
2340
depalWidth = texWidth * framebuffer->renderScaleFactor;
2341
gstate_c.Dirty(DIRTY_UVSCALEOFFSET);
2342
}
2343
2344
// If min is not < max, then we don't have values (wasn't set during decode.)
2345
const KnownVertexBounds &bounds = gstate_c.vertBounds;
2346
float u1 = 0.0f;
2347
float v1 = 0.0f;
2348
float u2 = depalWidth;
2349
float v2 = framebuffer->renderHeight;
2350
if (bounds.minV < bounds.maxV) {
2351
u1 = (bounds.minU + gstate_c.curTextureXOffset) * framebuffer->renderScaleFactor;
2352
v1 = (bounds.minV + gstate_c.curTextureYOffset) * framebuffer->renderScaleFactor;
2353
u2 = (bounds.maxU + gstate_c.curTextureXOffset) * framebuffer->renderScaleFactor;
2354
v2 = (bounds.maxV + gstate_c.curTextureYOffset) * framebuffer->renderScaleFactor;
2355
// We need to reapply the texture next time since we cropped UV.
2356
gstate_c.Dirty(DIRTY_TEXTURE_PARAMS);
2357
}
2358
2359
Draw::Framebuffer *depalFBO = framebufferManager_->GetTempFBO(TempFBO::DEPAL, depalWidth, framebuffer->renderHeight);
2360
draw_->BindTexture(0, nullptr);
2361
draw_->BindTexture(1, nullptr);
2362
draw_->BindFramebufferAsRenderTarget(depalFBO, { Draw::RPAction::DONT_CARE, Draw::RPAction::DONT_CARE, Draw::RPAction::DONT_CARE }, "Depal");
2363
draw_->InvalidateFramebuffer(Draw::FB_INVALIDATION_STORE, Draw::FB_DEPTH_BIT | Draw::FB_STENCIL_BIT);
2364
draw_->SetScissorRect(u1, v1, u2 - u1, v2 - v1);
2365
Draw::Viewport viewport{ 0.0f, 0.0f, (float)depalWidth, (float)framebuffer->renderHeight, 0.0f, 1.0f };
2366
draw_->SetViewport(viewport);
2367
2368
draw_->BindFramebufferAsTexture(framebuffer->fbo, 0, depth ? Draw::FB_DEPTH_BIT : Draw::FB_COLOR_BIT, Draw::ALL_LAYERS);
2369
if (clutRenderAddress_ == 0xFFFFFFFF) {
2370
draw_->BindTexture(1, clutTexture.texture);
2371
} else {
2372
draw_->BindFramebufferAsTexture(dynamicClutFbo_, 1, Draw::FB_COLOR_BIT, 0);
2373
}
2374
Draw::SamplerState *nearest = textureShaderCache_->GetSampler(false);
2375
Draw::SamplerState *clutSampler = textureShaderCache_->GetSampler(smoothedDepal);
2376
draw_->BindSamplerStates(0, 1, &nearest);
2377
draw_->BindSamplerStates(1, 1, &clutSampler);
2378
2379
draw2D_->Blit(textureShader, u1, v1, u2, v2, u1, v1, u2, v2, framebuffer->renderWidth, framebuffer->renderHeight, depalWidth, framebuffer->renderHeight, false, framebuffer->renderScaleFactor);
2380
2381
gpuStats.numDepal++;
2382
2383
gstate_c.curTextureWidth = texWidth;
2384
gstate_c.Dirty(DIRTY_UVSCALEOFFSET);
2385
2386
draw_->BindTexture(0, nullptr);
2387
framebufferManager_->RebindFramebuffer("ApplyTextureFramebuffer");
2388
2389
draw_->BindFramebufferAsTexture(depalFBO, 0, Draw::FB_COLOR_BIT, Draw::ALL_LAYERS);
2390
BoundFramebufferTexture();
2391
2392
const u32 bytesPerColor = clutFormat == GE_CMODE_32BIT_ABGR8888 ? sizeof(u32) : sizeof(u16);
2393
const u32 clutTotalColors = clutMaxBytes_ / bytesPerColor;
2394
2395
CheckAlphaResult alphaStatus = CheckCLUTAlpha((const uint8_t *)clutBufRaw_, clutFormat, clutTotalColors);
2396
gstate_c.SetTextureFullAlpha(alphaStatus == CHECKALPHA_FULL);
2397
2398
draw_->Invalidate(InvalidationFlags::CACHED_RENDER_STATE);
2399
shaderManager_->DirtyLastShader();
2400
} else {
2401
framebufferManager_->RebindFramebuffer("ApplyTextureFramebuffer");
2402
framebufferManager_->BindFramebufferAsColorTexture(0, framebuffer, BINDFBCOLOR_MAY_COPY_WITH_UV | BINDFBCOLOR_APPLY_TEX_OFFSET, Draw::ALL_LAYERS);
2403
BoundFramebufferTexture();
2404
2405
gstate_c.SetUseShaderDepal(ShaderDepalMode::OFF);
2406
gstate_c.SetTextureFullAlpha(gstate.getTextureFormat() == GE_TFMT_5650);
2407
}
2408
2409
SamplerCacheKey samplerKey = GetFramebufferSamplingParams(framebuffer->bufferWidth, framebuffer->bufferHeight);
2410
ApplySamplingParams(samplerKey);
2411
2412
// Since we've drawn using thin3d, might need these.
2413
gstate_c.Dirty(DIRTY_ALL_RENDER_STATE);
2414
}
2415
2416
// Applies depal to a normal (non-framebuffer) texture, pre-decoded to CLUT8 format.
2417
void TextureCacheCommon::ApplyTextureDepal(TexCacheEntry *entry) {
2418
uint32_t clutMode = gstate.clutformat & 0xFFFFFF;
2419
2420
switch (entry->format) {
2421
case GE_TFMT_CLUT4:
2422
case GE_TFMT_CLUT8:
2423
break; // These are OK
2424
default:
2425
_dbg_assert_(false);
2426
return;
2427
}
2428
2429
const GEPaletteFormat clutFormat = gstate.getClutPaletteFormat();
2430
u32 depthUpperBits = 0;
2431
2432
// The CLUT texture is dynamic, it's the framebuffer pointed to by clutRenderAddress.
2433
// Instead of texturing directly from that, we copy to a temporary CLUT texture.
2434
GEBufferFormat expectedCLUTBufferFormat = (GEBufferFormat)clutFormat; // All entries from clutFormat correspond directly to buffer formats.
2435
2436
// OK, figure out what format we want our framebuffer in, so it can be reinterpreted if needed.
2437
// If no reinterpretation is needed, we'll automatically just get a copy shader.
2438
float scaleFactorX = 1.0f;
2439
Draw2DPipeline *reinterpret = framebufferManager_->GetReinterpretPipeline(clutRenderFormat_, expectedCLUTBufferFormat, &scaleFactorX);
2440
framebufferManager_->BlitUsingRaster(
2441
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");
2442
2443
Draw2DPipeline *textureShader = textureShaderCache_->GetDepalettizeShader(clutMode, GE_TFMT_CLUT8, GE_FORMAT_CLUT8, false, 0);
2444
gstate_c.SetUseShaderDepal(ShaderDepalMode::OFF);
2445
2446
int texWidth = gstate.getTextureWidth(0);
2447
int texHeight = gstate.getTextureHeight(0);
2448
2449
// If min is not < max, then we don't have values (wasn't set during decode.)
2450
const KnownVertexBounds &bounds = gstate_c.vertBounds;
2451
float u1 = 0.0f;
2452
float v1 = 0.0f;
2453
float u2 = texWidth;
2454
float v2 = texHeight;
2455
if (bounds.minV < bounds.maxV) {
2456
// These are already in pixel coords! Doesn't seem like we should multiply by texwidth/height.
2457
u1 = bounds.minU + gstate_c.curTextureXOffset;
2458
v1 = bounds.minV + gstate_c.curTextureYOffset;
2459
u2 = bounds.maxU + gstate_c.curTextureXOffset + 1.0f;
2460
v2 = bounds.maxV + gstate_c.curTextureYOffset + 1.0f;
2461
// We need to reapply the texture next time since we cropped UV.
2462
gstate_c.Dirty(DIRTY_TEXTURE_PARAMS);
2463
}
2464
2465
Draw::Framebuffer *depalFBO = framebufferManager_->GetTempFBO(TempFBO::DEPAL, texWidth, texHeight);
2466
draw_->BindTexture(0, nullptr);
2467
draw_->BindTexture(1, nullptr);
2468
draw_->BindFramebufferAsRenderTarget(depalFBO, { Draw::RPAction::DONT_CARE, Draw::RPAction::DONT_CARE, Draw::RPAction::DONT_CARE }, "Depal");
2469
draw_->InvalidateFramebuffer(Draw::FB_INVALIDATION_STORE, Draw::FB_DEPTH_BIT | Draw::FB_STENCIL_BIT);
2470
draw_->SetScissorRect(u1, v1, u2 - u1, v2 - v1);
2471
Draw::Viewport viewport{ 0.0f, 0.0f, (float)texWidth, (float)texHeight, 0.0f, 1.0f };
2472
draw_->SetViewport(viewport);
2473
2474
draw_->BindNativeTexture(0, GetNativeTextureView(entry));
2475
draw_->BindFramebufferAsTexture(dynamicClutFbo_, 1, Draw::FB_COLOR_BIT, 0);
2476
Draw::SamplerState *nearest = textureShaderCache_->GetSampler(false);
2477
Draw::SamplerState *clutSampler = textureShaderCache_->GetSampler(false);
2478
draw_->BindSamplerStates(0, 1, &nearest);
2479
draw_->BindSamplerStates(1, 1, &clutSampler);
2480
2481
draw2D_->Blit(textureShader, u1, v1, u2, v2, u1, v1, u2, v2, texWidth, texHeight, texWidth, texHeight, false, 1);
2482
2483
gpuStats.numDepal++;
2484
2485
gstate_c.curTextureWidth = texWidth;
2486
gstate_c.Dirty(DIRTY_UVSCALEOFFSET);
2487
2488
draw_->BindTexture(0, nullptr);
2489
framebufferManager_->RebindFramebuffer("ApplyTextureFramebuffer");
2490
2491
draw_->BindFramebufferAsTexture(depalFBO, 0, Draw::FB_COLOR_BIT, 0);
2492
BoundFramebufferTexture();
2493
2494
const u32 bytesPerColor = clutFormat == GE_CMODE_32BIT_ABGR8888 ? sizeof(u32) : sizeof(u16);
2495
const u32 clutTotalColors = clutMaxBytes_ / bytesPerColor;
2496
2497
// We don't know about alpha at all.
2498
gstate_c.SetTextureFullAlpha(false);
2499
2500
draw_->Invalidate(InvalidationFlags::CACHED_RENDER_STATE);
2501
shaderManager_->DirtyLastShader();
2502
2503
SamplerCacheKey samplerKey = GetFramebufferSamplingParams(texWidth, texHeight);
2504
ApplySamplingParams(samplerKey);
2505
2506
// Since we've drawn using thin3d, might need these.
2507
gstate_c.Dirty(DIRTY_ALL_RENDER_STATE);
2508
}
2509
2510
void TextureCacheCommon::Clear(bool delete_them) {
2511
textureShaderCache_->Clear();
2512
2513
ForgetLastTexture();
2514
for (TexCache::iterator iter = cache_.begin(); iter != cache_.end(); ++iter) {
2515
ReleaseTexture(iter->second.get(), delete_them);
2516
}
2517
// In case the setting was changed, we ALWAYS clear the secondary cache (enabled or not.)
2518
for (TexCache::iterator iter = secondCache_.begin(); iter != secondCache_.end(); ++iter) {
2519
ReleaseTexture(iter->second.get(), delete_them);
2520
}
2521
if (cache_.size() + secondCache_.size()) {
2522
INFO_LOG(Log::G3D, "Texture cached cleared from %i textures", (int)(cache_.size() + secondCache_.size()));
2523
cache_.clear();
2524
secondCache_.clear();
2525
cacheSizeEstimate_ = 0;
2526
secondCacheSizeEstimate_ = 0;
2527
}
2528
videos_.clear();
2529
2530
if (dynamicClutFbo_) {
2531
dynamicClutFbo_->Release();
2532
dynamicClutFbo_ = nullptr;
2533
}
2534
if (dynamicClutTemp_) {
2535
dynamicClutTemp_->Release();
2536
dynamicClutTemp_ = nullptr;
2537
}
2538
}
2539
2540
void TextureCacheCommon::DeleteTexture(TexCache::iterator it) {
2541
ReleaseTexture(it->second.get(), true);
2542
cacheSizeEstimate_ -= EstimateTexMemoryUsage(it->second.get());
2543
cache_.erase(it);
2544
}
2545
2546
bool TextureCacheCommon::CheckFullHash(TexCacheEntry *entry, bool &doDelete) {
2547
int w = gstate.getTextureWidth(0);
2548
int h = gstate.getTextureHeight(0);
2549
bool isVideo = IsVideo(entry->addr);
2550
bool swizzled = gstate.isTextureSwizzled();
2551
2552
// Don't even check the texture, just assume it has changed.
2553
if (isVideo && g_Config.bTextureBackoffCache) {
2554
// Attempt to ensure the hash doesn't incorrectly match in if the video stops.
2555
entry->fullhash = (entry->fullhash + 0xA535A535) * 11 + (entry->fullhash & 4);
2556
return false;
2557
}
2558
2559
u32 fullhash;
2560
{
2561
PROFILE_THIS_SCOPE("texhash");
2562
fullhash = QuickTexHash(replacer_, entry->addr, entry->bufw, w, h, swizzled, GETextureFormat(entry->format), entry);
2563
}
2564
2565
if (fullhash == entry->fullhash) {
2566
if (g_Config.bTextureBackoffCache && !isVideo) {
2567
if (entry->GetHashStatus() != TexCacheEntry::STATUS_HASHING && entry->numFrames > TexCacheEntry::FRAMES_REGAIN_TRUST) {
2568
// Reset to STATUS_HASHING.
2569
entry->SetHashStatus(TexCacheEntry::STATUS_HASHING);
2570
entry->status &= ~TexCacheEntry::STATUS_CHANGE_FREQUENT;
2571
}
2572
} else if (entry->numFrames > TEXCACHE_FRAME_CHANGE_FREQUENT_REGAIN_TRUST) {
2573
entry->status &= ~TexCacheEntry::STATUS_CHANGE_FREQUENT;
2574
}
2575
2576
return true;
2577
}
2578
2579
// Don't give up just yet. Let's try the secondary cache if it's been invalidated before.
2580
if (PSP_CoreParameter().compat.flags().SecondaryTextureCache) {
2581
// Don't forget this one was unreliable (in case we match a secondary entry.)
2582
entry->status |= TexCacheEntry::STATUS_UNRELIABLE;
2583
2584
// If it's failed a bunch of times, then the second cache is just wasting time and VRAM.
2585
// In that case, skip.
2586
if (entry->numInvalidated > 2 && entry->numInvalidated < 128 && !lowMemoryMode_) {
2587
// We have a new hash: look for that hash in the secondary cache.
2588
u64 secondKey = fullhash | (u64)entry->cluthash << 32;
2589
TexCache::iterator secondIter = secondCache_.find(secondKey);
2590
if (secondIter != secondCache_.end()) {
2591
// Found it, but does it match our current params? If not, abort.
2592
TexCacheEntry *secondEntry = secondIter->second.get();
2593
if (secondEntry->Matches(entry->dim, entry->format, entry->maxLevel)) {
2594
// Reset the numInvalidated value lower, we got a match.
2595
if (entry->numInvalidated > 8) {
2596
--entry->numInvalidated;
2597
}
2598
2599
// Now just use our archived texture, instead of entry.
2600
nextTexture_ = secondEntry;
2601
return true;
2602
}
2603
} else {
2604
// It wasn't found, so we're about to throw away the entry and rebuild a texture.
2605
// Let's save this in the secondary cache in case it gets used again.
2606
secondKey = entry->fullhash | ((u64)entry->cluthash << 32);
2607
secondCacheSizeEstimate_ += EstimateTexMemoryUsage(entry);
2608
2609
// If the entry already exists in the secondary texture cache, drop it nicely.
2610
auto oldIter = secondCache_.find(secondKey);
2611
if (oldIter != secondCache_.end()) {
2612
ReleaseTexture(oldIter->second.get(), true);
2613
}
2614
2615
// Archive the entire texture entry as is, since we'll use its params if it is seen again.
2616
// We keep parameters on the current entry, since we are STILL building a new texture here.
2617
secondCache_[secondKey].reset(new TexCacheEntry(*entry));
2618
2619
// Make sure we don't delete the texture we just archived.
2620
entry->texturePtr = nullptr;
2621
doDelete = false;
2622
}
2623
}
2624
}
2625
2626
// We know it failed, so update the full hash right away.
2627
entry->fullhash = fullhash;
2628
return false;
2629
}
2630
2631
void TextureCacheCommon::Invalidate(u32 addr, int size, GPUInvalidationType type) {
2632
// They could invalidate inside the texture, let's just give a bit of leeway.
2633
// TODO: Keep track of the largest texture size in bytes, and use that instead of this
2634
// humongous unrealistic value.
2635
2636
const int LARGEST_TEXTURE_SIZE = 512 * 512 * 4;
2637
2638
addr &= 0x3FFFFFFF;
2639
const u32 addr_end = addr + size;
2640
2641
if (type == GPU_INVALIDATE_ALL) {
2642
// This is an active signal from the game that something in the texture cache may have changed.
2643
gstate_c.Dirty(DIRTY_TEXTURE_IMAGE);
2644
} else {
2645
// Do a quick check to see if the current texture could potentially be in range.
2646
const u32 currentAddr = gstate.getTextureAddress(0);
2647
// TODO: This can be made tighter.
2648
if (addr_end >= currentAddr && addr < currentAddr + LARGEST_TEXTURE_SIZE) {
2649
gstate_c.Dirty(DIRTY_TEXTURE_IMAGE);
2650
}
2651
}
2652
2653
// If we're hashing every use, without backoff, then this isn't needed.
2654
if (!g_Config.bTextureBackoffCache && type != GPU_INVALIDATE_FORCE) {
2655
return;
2656
}
2657
2658
const u64 startKey = (u64)(addr - LARGEST_TEXTURE_SIZE) << 32;
2659
u64 endKey = (u64)(addr + size + LARGEST_TEXTURE_SIZE) << 32;
2660
if (endKey < startKey) {
2661
endKey = (u64)-1;
2662
}
2663
2664
for (TexCache::iterator iter = cache_.lower_bound(startKey), end = cache_.upper_bound(endKey); iter != end; ++iter) {
2665
auto &entry = iter->second;
2666
u32 texAddr = entry->addr;
2667
// Intentional underestimate here.
2668
u32 texEnd = entry->addr + entry->SizeInRAM() / 2;
2669
2670
// Quick check for overlap. Yes the check is right.
2671
if (addr < texEnd && addr_end > texAddr) {
2672
if (entry->GetHashStatus() == TexCacheEntry::STATUS_RELIABLE) {
2673
entry->SetHashStatus(TexCacheEntry::STATUS_HASHING);
2674
}
2675
if (type == GPU_INVALIDATE_FORCE) {
2676
// Just random values to force the hash not to match.
2677
entry->fullhash = (entry->fullhash ^ 0x12345678) + 13;
2678
entry->minihash = (entry->minihash ^ 0x89ABCDEF) + 89;
2679
}
2680
if (type != GPU_INVALIDATE_ALL) {
2681
gpuStats.numTextureInvalidations++;
2682
// Start it over from 0 (unless it's safe.)
2683
entry->numFrames = type == GPU_INVALIDATE_SAFE ? 256 : 0;
2684
if (type == GPU_INVALIDATE_SAFE) {
2685
u32 diff = gpuStats.numFlips - entry->lastFrame;
2686
// We still need to mark if the texture is frequently changing, even if it's safely changing.
2687
if (diff < TEXCACHE_FRAME_CHANGE_FREQUENT) {
2688
entry->status |= TexCacheEntry::STATUS_CHANGE_FREQUENT;
2689
}
2690
}
2691
entry->framesUntilNextFullHash = 0;
2692
} else {
2693
entry->invalidHint++;
2694
}
2695
}
2696
}
2697
}
2698
2699
void TextureCacheCommon::InvalidateAll(GPUInvalidationType /*unused*/) {
2700
// If we're hashing every use, without backoff, then this isn't needed.
2701
if (!g_Config.bTextureBackoffCache) {
2702
return;
2703
}
2704
2705
if (timesInvalidatedAllThisFrame_ > 5) {
2706
return;
2707
}
2708
timesInvalidatedAllThisFrame_++;
2709
2710
for (TexCache::iterator iter = cache_.begin(), end = cache_.end(); iter != end; ++iter) {
2711
if (iter->second->GetHashStatus() == TexCacheEntry::STATUS_RELIABLE) {
2712
iter->second->SetHashStatus(TexCacheEntry::STATUS_HASHING);
2713
}
2714
iter->second->invalidHint++;
2715
}
2716
}
2717
2718
void TextureCacheCommon::ClearNextFrame() {
2719
clearCacheNextFrame_ = true;
2720
}
2721
2722
std::string AttachCandidate::ToString() const {
2723
return StringFromFormat("[%s seq:%d rel:%d C:%08x/%d(%s) Z:%08x/%d X:%d Y:%d reint: %s]",
2724
RasterChannelToString(this->channel),
2725
this->channel == RASTER_COLOR ? this->fb->colorBindSeq : this->fb->depthBindSeq,
2726
this->relevancy,
2727
this->fb->fb_address, this->fb->fb_stride, GeBufferFormatToString(this->fb->fb_format),
2728
this->fb->z_address, this->fb->z_stride,
2729
this->match.xOffset, this->match.yOffset, this->match.reinterpret ? "true" : "false");
2730
}
2731
2732
bool TextureCacheCommon::PrepareBuildTexture(BuildTexturePlan &plan, TexCacheEntry *entry) {
2733
gpuStats.numTexturesDecoded++;
2734
2735
// For the estimate, we assume cluts always point to 8888 for simplicity.
2736
cacheSizeEstimate_ += EstimateTexMemoryUsage(entry);
2737
2738
plan.badMipSizes = false;
2739
// maxLevel here is the max level to upload. Not the count.
2740
plan.levelsToLoad = entry->maxLevel + 1;
2741
for (int i = 0; i < plan.levelsToLoad; i++) {
2742
// If encountering levels pointing to nothing, adjust max level.
2743
u32 levelTexaddr = gstate.getTextureAddress(i);
2744
if (!Memory::IsValidAddress(levelTexaddr)) {
2745
plan.levelsToLoad = i;
2746
break;
2747
}
2748
2749
// If size reaches 1, stop, and override maxlevel.
2750
int tw = gstate.getTextureWidth(i);
2751
int th = gstate.getTextureHeight(i);
2752
if (tw == 1 || th == 1) {
2753
plan.levelsToLoad = i + 1; // next level is assumed to be invalid
2754
break;
2755
}
2756
2757
if (i > 0) {
2758
int lastW = gstate.getTextureWidth(i - 1);
2759
int lastH = gstate.getTextureHeight(i - 1);
2760
2761
if (gstate_c.Use(GPU_USE_TEXTURE_LOD_CONTROL)) {
2762
if (tw != 1 && tw != (lastW >> 1))
2763
plan.badMipSizes = true;
2764
else if (th != 1 && th != (lastH >> 1))
2765
plan.badMipSizes = true;
2766
}
2767
}
2768
}
2769
2770
plan.scaleFactor = standardScaleFactor_;
2771
plan.depth = 1;
2772
2773
// Rachet down scale factor in low-memory mode.
2774
// TODO: I think really we should just turn it off?
2775
if (lowMemoryMode_ && !plan.hardwareScaling) {
2776
// Keep it even, though, just in case of npot troubles.
2777
plan.scaleFactor = plan.scaleFactor > 4 ? 4 : (plan.scaleFactor > 2 ? 2 : 1);
2778
}
2779
2780
bool isFakeMipmapChange = false;
2781
if (plan.badMipSizes) {
2782
isFakeMipmapChange = IsFakeMipmapChange();
2783
2784
// Check for pure 3D texture.
2785
int tw = gstate.getTextureWidth(0);
2786
int th = gstate.getTextureHeight(0);
2787
bool pure3D = true;
2788
for (int i = 0; i < plan.levelsToLoad; i++) {
2789
if (gstate.getTextureWidth(i) != gstate.getTextureWidth(0) || gstate.getTextureHeight(i) != gstate.getTextureHeight(0)) {
2790
pure3D = false;
2791
break;
2792
}
2793
}
2794
2795
// Check early for the degenerate case from Tactics Ogre.
2796
if (pure3D && plan.levelsToLoad == 2 && gstate.getTextureAddress(0) == gstate.getTextureAddress(1)) {
2797
// Simply treat it as a regular 2D texture, no fake mipmaps or anything.
2798
// levelsToLoad/Create gets set to 1 on the way out from the surrounding if.
2799
isFakeMipmapChange = false;
2800
pure3D = false;
2801
} else if (isFakeMipmapChange) {
2802
// We don't want to create a volume texture, if this is a "fake mipmap change".
2803
// In practice due to the compat flag, the only time we end up here is in JP Tactics Ogre.
2804
pure3D = false;
2805
}
2806
2807
if (pure3D && draw_->GetDeviceCaps().texture3DSupported) {
2808
plan.depth = plan.levelsToLoad;
2809
plan.scaleFactor = 1;
2810
}
2811
2812
plan.levelsToLoad = 1;
2813
plan.levelsToCreate = 1;
2814
}
2815
2816
if (plan.hardwareScaling) {
2817
plan.scaleFactor = shaderScaleFactor_;
2818
}
2819
2820
// We generate missing mipmaps from maxLevel+1 up to this level. maxLevel can get overwritten below
2821
// such as when using replacement textures - but let's keep the same amount of levels for generation.
2822
// Not all backends will generate mipmaps, and in GL we can't really control the number of levels.
2823
plan.levelsToCreate = plan.levelsToLoad;
2824
2825
plan.w = gstate.getTextureWidth(0);
2826
plan.h = gstate.getTextureHeight(0);
2827
2828
bool isPPGETexture = entry->addr >= PSP_GetKernelMemoryBase() && entry->addr < PSP_GetKernelMemoryEnd();
2829
2830
// Don't scale the PPGe texture.
2831
if (isPPGETexture) {
2832
plan.scaleFactor = 1;
2833
} else if (!g_DoubleTextureCoordinates) {
2834
// Refuse to load invalid-ly sized textures, which can happen through display list corruption.
2835
// However, turns out some games uses huge textures for font rendering for no apparent reason.
2836
// These will only work correctly in the top 512x512 part. So, I've increased the threshold quite a bit.
2837
// We probably should handle these differently, by clamping the texture size and texture coordinates, but meh.
2838
if (plan.w > 2048 || plan.h > 2048) {
2839
ERROR_LOG(Log::G3D, "Bad texture dimensions: %dx%d", plan.w, plan.h);
2840
return false;
2841
}
2842
}
2843
2844
if (PSP_CoreParameter().compat.flags().ForceLowerResolutionForEffectsOn && gstate.FrameBufStride() < 0x1E0) {
2845
// A bit of an esoteric workaround - force off upscaling for static textures that participate directly in small-resolution framebuffer effects.
2846
// This fixes the water in Outrun/DiRT 2 with upscaling enabled.
2847
plan.scaleFactor = 1;
2848
}
2849
2850
if ((entry->status & TexCacheEntry::STATUS_CHANGE_FREQUENT) != 0 && plan.scaleFactor != 1 && plan.slowScaler) {
2851
// Remember for later that we /wanted/ to scale this texture.
2852
entry->status |= TexCacheEntry::STATUS_TO_SCALE;
2853
plan.scaleFactor = 1;
2854
}
2855
2856
if (plan.scaleFactor != 1) {
2857
if (texelsScaledThisFrame_ >= TEXCACHE_MAX_TEXELS_SCALED && plan.slowScaler) {
2858
entry->status |= TexCacheEntry::STATUS_TO_SCALE;
2859
plan.scaleFactor = 1;
2860
} else {
2861
entry->status &= ~TexCacheEntry::STATUS_TO_SCALE;
2862
entry->status |= TexCacheEntry::STATUS_IS_SCALED_OR_REPLACED;
2863
texelsScaledThisFrame_ += plan.w * plan.h;
2864
}
2865
}
2866
2867
plan.isVideo = IsVideo(entry->addr);
2868
2869
// TODO: Support reading actual mip levels for upscaled images, instead of just generating them.
2870
// Maybe can just remove this check?
2871
if (plan.scaleFactor > 1) {
2872
plan.levelsToLoad = 1;
2873
2874
bool enableVideoUpscaling = false;
2875
2876
if (!enableVideoUpscaling && plan.isVideo) {
2877
plan.scaleFactor = 1;
2878
plan.levelsToCreate = 1;
2879
}
2880
}
2881
2882
bool canReplace = !isPPGETexture;
2883
if (entry->status & TexCacheEntry::TexStatus::STATUS_CLUT_GPU) {
2884
_dbg_assert_(entry->format == GE_TFMT_CLUT4 || entry->format == GE_TFMT_CLUT8);
2885
plan.decodeToClut8 = true;
2886
// We only support 1 mip level when doing CLUT on GPU for now.
2887
// Supporting more would be possible, just not very interesting until we need it.
2888
plan.levelsToCreate = 1;
2889
plan.levelsToLoad = 1;
2890
plan.maxPossibleLevels = 1;
2891
plan.scaleFactor = 1;
2892
plan.saveTexture = false; // Can't yet save these properly.
2893
canReplace = false;
2894
} else {
2895
plan.decodeToClut8 = false;
2896
}
2897
2898
if (canReplace) {
2899
// This is the "trigger point" for replacement.
2900
plan.replaced = FindReplacement(entry, &plan.w, &plan.h, &plan.depth);
2901
plan.doReplace = plan.replaced ? plan.replaced->State() == ReplacementState::ACTIVE : false;
2902
} else {
2903
plan.replaced = nullptr;
2904
plan.doReplace = false;
2905
}
2906
2907
// NOTE! Last chance to change scale factor here!
2908
2909
plan.saveTexture = false;
2910
if (plan.doReplace) {
2911
// We're replacing, so we won't scale.
2912
plan.scaleFactor = 1;
2913
// We're ignoring how many levels were specified - instead we just load all available from the replacer.
2914
plan.levelsToLoad = plan.replaced->NumLevels();
2915
plan.levelsToCreate = plan.levelsToLoad; // Or more, if we wanted to generate.
2916
plan.badMipSizes = false;
2917
// But, we still need to create the texture at a larger size.
2918
plan.replaced->GetSize(0, &plan.createW, &plan.createH);
2919
} else {
2920
if (replacer_.SaveEnabled() && !plan.doReplace && plan.depth == 1 && canReplace) {
2921
ReplacedTextureDecodeInfo replacedInfo;
2922
// TODO: Do we handle the race where a replacement becomes valid AFTER this but before we save?
2923
replacedInfo.cachekey = entry->CacheKey();
2924
replacedInfo.hash = entry->fullhash;
2925
replacedInfo.addr = entry->addr;
2926
replacedInfo.isFinal = (entry->status & TexCacheEntry::STATUS_TO_SCALE) == 0;
2927
replacedInfo.isVideo = plan.isVideo;
2928
replacedInfo.fmt = Draw::DataFormat::R8G8B8A8_UNORM;
2929
plan.saveTexture = replacer_.WillSave(replacedInfo);
2930
}
2931
plan.createW = plan.w * plan.scaleFactor;
2932
plan.createH = plan.h * plan.scaleFactor;
2933
}
2934
2935
// Always load base level texture here
2936
plan.baseLevelSrc = 0;
2937
if (isFakeMipmapChange) {
2938
// NOTE: Since the level is not part of the cache key, we assume it never changes.
2939
plan.baseLevelSrc = std::max(0, gstate.getTexLevelOffset16() / 16);
2940
// Tactics Ogre: If this is an odd level and it has the same texture address the below even level,
2941
// let's just say it's the even level for the purposes of replacement.
2942
// I assume this is done to avoid blending between levels accidentally?
2943
// The Japanese version of Tactics Ogre uses multiple of these "double" levels to fit more characters.
2944
if ((plan.baseLevelSrc & 1) && gstate.getTextureAddress(plan.baseLevelSrc) == gstate.getTextureAddress(plan.baseLevelSrc & ~1)) {
2945
plan.baseLevelSrc &= ~1;
2946
}
2947
plan.levelsToCreate = 1;
2948
plan.levelsToLoad = 1;
2949
// Make sure we already decided not to do a 3D texture above.
2950
_dbg_assert_(plan.depth == 1);
2951
}
2952
2953
if (plan.isVideo || plan.depth != 1 || plan.decodeToClut8) {
2954
plan.levelsToLoad = 1;
2955
plan.maxPossibleLevels = 1;
2956
} else {
2957
plan.maxPossibleLevels = log2i(std::max(plan.createW, plan.createH)) + 1;
2958
}
2959
2960
if (plan.levelsToCreate == 1) {
2961
entry->status |= TexCacheEntry::STATUS_NO_MIPS;
2962
} else {
2963
entry->status &= ~TexCacheEntry::STATUS_NO_MIPS;
2964
}
2965
2966
// Will be filled in again during decode.
2967
entry->status &= ~TexCacheEntry::STATUS_ALPHA_MASK;
2968
return true;
2969
}
2970
2971
// Passing 0 into dataSize will disable checking.
2972
void TextureCacheCommon::LoadTextureLevel(TexCacheEntry &entry, uint8_t *data, size_t dataSize, int stride, BuildTexturePlan &plan, int srcLevel, Draw::DataFormat dstFmt, TexDecodeFlags texDecFlags) {
2973
int w = gstate.getTextureWidth(srcLevel);
2974
int h = gstate.getTextureHeight(srcLevel);
2975
2976
PROFILE_THIS_SCOPE("decodetex");
2977
2978
if (plan.doReplace) {
2979
plan.replaced->GetSize(srcLevel, &w, &h);
2980
double replaceStart = time_now_d();
2981
plan.replaced->CopyLevelTo(srcLevel, data, dataSize, stride);
2982
replacementTimeThisFrame_ += time_now_d() - replaceStart;
2983
} else {
2984
GETextureFormat tfmt = (GETextureFormat)entry.format;
2985
GEPaletteFormat clutformat = gstate.getClutPaletteFormat();
2986
u32 texaddr = gstate.getTextureAddress(srcLevel);
2987
const int bufw = GetTextureBufw(srcLevel, texaddr, tfmt);
2988
u32 *pixelData;
2989
int decPitch;
2990
if (plan.scaleFactor > 1) {
2991
tmpTexBufRearrange_.resize(std::max(bufw, w) * h);
2992
pixelData = tmpTexBufRearrange_.data();
2993
// We want to end up with a neatly packed texture for scaling.
2994
decPitch = w * 4;
2995
} else {
2996
pixelData = (u32 *)data;
2997
decPitch = stride;
2998
}
2999
3000
if (!gstate_c.Use(GPU_USE_16BIT_FORMATS) || dstFmt == Draw::DataFormat::R8G8B8A8_UNORM) {
3001
texDecFlags |= TexDecodeFlags::EXPAND32;
3002
}
3003
if (entry.status & TexCacheEntry::STATUS_CLUT_GPU) {
3004
texDecFlags |= TexDecodeFlags::TO_CLUT8;
3005
}
3006
3007
CheckAlphaResult alphaResult = DecodeTextureLevel((u8 *)pixelData, decPitch, tfmt, clutformat, texaddr, srcLevel, bufw, texDecFlags);
3008
entry.SetAlphaStatus(alphaResult, srcLevel);
3009
3010
int scaledW = w, scaledH = h;
3011
if (plan.scaleFactor > 1) {
3012
// Note that this updates w and h!
3013
scaler_.ScaleAlways((u32 *)data, pixelData, w, h, &scaledW, &scaledH, plan.scaleFactor);
3014
pixelData = (u32 *)data;
3015
3016
decPitch = scaledW * sizeof(u32);
3017
3018
if (decPitch != stride) {
3019
// Rearrange in place to match the requested pitch.
3020
// (it can only be larger than w * bpp, and a match is likely.)
3021
// Note! This is bad because it reads the mapped memory! TODO: Look into if DX9 does this right.
3022
for (int y = scaledH - 1; y >= 0; --y) {
3023
memcpy((u8 *)data + stride * y, (u8 *)data + decPitch * y, scaledW *4);
3024
}
3025
decPitch = stride;
3026
}
3027
}
3028
3029
if (plan.saveTexture && !lowMemoryMode_) {
3030
ReplacedTextureDecodeInfo replacedInfo;
3031
replacedInfo.cachekey = entry.CacheKey();
3032
replacedInfo.hash = entry.fullhash;
3033
replacedInfo.addr = entry.addr;
3034
replacedInfo.isVideo = IsVideo(entry.addr);
3035
replacedInfo.isFinal = (entry.status & TexCacheEntry::STATUS_TO_SCALE) == 0;
3036
replacedInfo.fmt = dstFmt;
3037
3038
// NOTE: Reading the decoded texture here may be very slow, if we just wrote it to write-combined memory.
3039
replacer_.NotifyTextureDecoded(plan.replaced, replacedInfo, pixelData, decPitch, srcLevel, w, h, scaledW, scaledH);
3040
}
3041
}
3042
}
3043
3044
CheckAlphaResult TextureCacheCommon::CheckCLUTAlpha(const uint8_t *pixelData, GEPaletteFormat clutFormat, int w) {
3045
switch (clutFormat) {
3046
case GE_CMODE_16BIT_ABGR4444:
3047
return CheckAlpha16((const u16 *)pixelData, w, 0xF000);
3048
case GE_CMODE_16BIT_ABGR5551:
3049
return CheckAlpha16((const u16 *)pixelData, w, 0x8000);
3050
case GE_CMODE_16BIT_BGR5650:
3051
// Never has any alpha.
3052
return CHECKALPHA_FULL;
3053
default:
3054
return CheckAlpha32((const u32 *)pixelData, w, 0xFF000000);
3055
}
3056
}
3057
3058