Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hrydgard
GitHub Repository: hrydgard/ppsspp
Path: blob/master/GPU/Vulkan/TextureCacheVulkan.cpp
3186 views
1
// Copyright (c) 2012- 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 <algorithm>
19
#include <cstring>
20
21
#include "ext/xxhash.h"
22
23
#include "Common/File/VFS/VFS.h"
24
#include "Common/Data/Text/I18n.h"
25
#include "Common/LogReporting.h"
26
#include "Common/Math/math_util.h"
27
#include "Common/Profiler/Profiler.h"
28
#include "Common/GPU/thin3d.h"
29
#include "Common/GPU/Vulkan/VulkanRenderManager.h"
30
#include "Common/System/OSD.h"
31
#include "Common/StringUtils.h"
32
#include "Common/TimeUtil.h"
33
#include "Common/GPU/Vulkan/VulkanContext.h"
34
#include "Common/GPU/Vulkan/VulkanImage.h"
35
#include "Common/GPU/Vulkan/VulkanMemory.h"
36
37
#include "Core/Config.h"
38
39
#include "GPU/ge_constants.h"
40
#include "GPU/GPUState.h"
41
#include "GPU/Common/TextureShaderCommon.h"
42
#include "GPU/Common/PostShader.h"
43
#include "GPU/Common/TextureCacheCommon.h"
44
#include "GPU/Common/TextureDecoder.h"
45
#include "GPU/Vulkan/VulkanContext.h"
46
#include "GPU/Vulkan/TextureCacheVulkan.h"
47
#include "GPU/Vulkan/FramebufferManagerVulkan.h"
48
#include "GPU/Vulkan/ShaderManagerVulkan.h"
49
#include "GPU/Vulkan/DrawEngineVulkan.h"
50
51
using namespace PPSSPP_VK;
52
53
#define TEXCACHE_MIN_SLAB_SIZE (8 * 1024 * 1024)
54
#define TEXCACHE_MAX_SLAB_SIZE (32 * 1024 * 1024)
55
#define TEXCACHE_SLAB_PRESSURE 4
56
57
const char *uploadShader = R"(
58
#version 450
59
#extension GL_ARB_separate_shader_objects : enable
60
61
// 8x8 is the most common compute shader workgroup size, and works great on all major
62
// hardware vendors.
63
layout (local_size_x = 8, local_size_y = 8, local_size_z = 1) in;
64
65
uniform layout(set = 0, binding = 0, rgba8) writeonly image2D img;
66
67
layout(std430, set = 0, binding = 1) buffer Buf {
68
uint data[];
69
} buf;
70
71
layout(push_constant) uniform Params {
72
int width;
73
int height;
74
} params;
75
76
uint readColoru(uvec2 p) {
77
return buf.data[p.y * params.width + p.x];
78
}
79
80
vec4 readColorf(uvec2 p) {
81
// Unpack the color (we could look it up in a CLUT here if we wanted...)
82
// The imageStore repack is free.
83
return unpackUnorm4x8(readColoru(p));
84
}
85
86
void writeColorf(ivec2 p, vec4 c) {
87
imageStore(img, p, c);
88
}
89
90
%s
91
92
// Note that main runs once per INPUT pixel, unlike the old model.
93
void main() {
94
uvec2 xy = gl_GlobalInvocationID.xy;
95
// Kill off any out-of-image threads to avoid stray writes.
96
// Should only happen on the tiniest mipmaps as PSP textures are power-of-2,
97
// and we use a 8x8 workgroup size. Probably not really necessary.
98
if (xy.x >= params.width || xy.y >= params.height)
99
return;
100
// applyScaling will write the upscaled pixels, using writeColorf above.
101
// It's expected to write a square of scale*scale pixels, at the location xy*scale.
102
applyScaling(xy);
103
}
104
105
)";
106
107
static int VkFormatBytesPerPixel(VkFormat format) {
108
switch (format) {
109
case VULKAN_8888_FORMAT: return 4;
110
case VULKAN_CLUT8_FORMAT: return 1;
111
default: break;
112
}
113
return 2;
114
}
115
116
SamplerCache::~SamplerCache() {
117
DeviceLost();
118
}
119
120
VkSampler SamplerCache::GetOrCreateSampler(const SamplerCacheKey &key) {
121
VkSampler sampler;
122
if (cache_.Get(key, &sampler)) {
123
return sampler;
124
}
125
126
VkSamplerCreateInfo samp = { VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO };
127
samp.addressModeU = key.sClamp ? VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE : VK_SAMPLER_ADDRESS_MODE_REPEAT;
128
samp.addressModeV = key.tClamp ? VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE : VK_SAMPLER_ADDRESS_MODE_REPEAT;
129
// W addressing is irrelevant for 2d textures, but Mali recommends that all clamp modes are the same if possible so just copy from U.
130
samp.addressModeW = key.texture3d ? VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE : samp.addressModeU;
131
samp.compareOp = VK_COMPARE_OP_ALWAYS;
132
samp.flags = 0;
133
samp.magFilter = key.magFilt ? VK_FILTER_LINEAR : VK_FILTER_NEAREST;
134
samp.minFilter = key.minFilt ? VK_FILTER_LINEAR : VK_FILTER_NEAREST;
135
samp.mipmapMode = key.mipFilt ? VK_SAMPLER_MIPMAP_MODE_LINEAR : VK_SAMPLER_MIPMAP_MODE_NEAREST;
136
137
if (key.aniso) {
138
// Docs say the min of this value and the supported max are used.
139
samp.maxAnisotropy = 1 << g_Config.iAnisotropyLevel;
140
samp.anisotropyEnable = true;
141
} else {
142
samp.maxAnisotropy = 1.0f;
143
samp.anisotropyEnable = false;
144
}
145
if (key.maxLevel == 9 * 256) {
146
// No max level needed. Better for performance on some archs like ARM Mali.
147
samp.maxLod = VK_LOD_CLAMP_NONE;
148
} else {
149
samp.maxLod = (float)(int32_t)key.maxLevel * (1.0f / 256.0f);
150
}
151
samp.minLod = (float)(int32_t)key.minLevel * (1.0f / 256.0f);
152
samp.mipLodBias = (float)(int32_t)key.lodBias * (1.0f / 256.0f);
153
154
VkResult res = vkCreateSampler(vulkan_->GetDevice(), &samp, nullptr, &sampler);
155
_assert_(res == VK_SUCCESS);
156
cache_.Insert(key, sampler);
157
return sampler;
158
}
159
160
std::string SamplerCache::DebugGetSamplerString(const std::string &id, DebugShaderStringType stringType) {
161
SamplerCacheKey key;
162
key.FromString(id);
163
return StringFromFormat("%s/%s mag:%s min:%s mip:%s maxLod:%f minLod:%f bias:%f",
164
key.sClamp ? "Clamp" : "Wrap",
165
key.tClamp ? "Clamp" : "Wrap",
166
key.magFilt ? "Linear" : "Nearest",
167
key.minFilt ? "Linear" : "Nearest",
168
key.mipFilt ? "Linear" : "Nearest",
169
key.maxLevel / 256.0f,
170
key.minLevel / 256.0f,
171
key.lodBias / 256.0f);
172
}
173
174
void SamplerCache::DeviceLost() {
175
cache_.Iterate([&](const SamplerCacheKey &key, VkSampler sampler) {
176
vulkan_->Delete().QueueDeleteSampler(sampler);
177
});
178
cache_.Clear();
179
vulkan_ = nullptr;
180
}
181
182
void SamplerCache::DeviceRestore(VulkanContext *vulkan) {
183
vulkan_ = vulkan;
184
}
185
186
std::vector<std::string> SamplerCache::DebugGetSamplerIDs() const {
187
std::vector<std::string> ids;
188
cache_.Iterate([&](const SamplerCacheKey &id, VkSampler sampler) {
189
std::string idstr;
190
id.ToString(&idstr);
191
ids.push_back(idstr);
192
});
193
return ids;
194
}
195
196
TextureCacheVulkan::TextureCacheVulkan(Draw::DrawContext *draw, Draw2D *draw2D, VulkanContext *vulkan)
197
: TextureCacheCommon(draw, draw2D),
198
computeShaderManager_(vulkan),
199
samplerCache_(vulkan) {
200
DeviceRestore(draw);
201
}
202
203
TextureCacheVulkan::~TextureCacheVulkan() {
204
DeviceLost();
205
}
206
207
void TextureCacheVulkan::SetFramebufferManager(FramebufferManagerVulkan *fbManager) {
208
framebufferManager_ = fbManager;
209
}
210
211
void TextureCacheVulkan::DeviceLost() {
212
textureShaderCache_->DeviceLost();
213
214
VulkanContext *vulkan = draw_ ? (VulkanContext *)draw_->GetNativeObject(Draw::NativeObject::CONTEXT) : nullptr;
215
216
Clear(true);
217
218
samplerCache_.DeviceLost();
219
if (samplerNearest_)
220
vulkan->Delete().QueueDeleteSampler(samplerNearest_);
221
222
if (uploadCS_ != VK_NULL_HANDLE)
223
vulkan->Delete().QueueDeleteShaderModule(uploadCS_);
224
225
computeShaderManager_.DeviceLost();
226
227
nextTexture_ = nullptr;
228
draw_ = nullptr;
229
Unbind();
230
}
231
232
void TextureCacheVulkan::DeviceRestore(Draw::DrawContext *draw) {
233
draw_ = draw;
234
235
VulkanContext *vulkan = (VulkanContext *)draw->GetNativeObject(Draw::NativeObject::CONTEXT);
236
_assert_(vulkan);
237
238
samplerCache_.DeviceRestore(vulkan);
239
textureShaderCache_->DeviceRestore(draw);
240
241
VkSamplerCreateInfo samp{ VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO };
242
samp.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
243
samp.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
244
samp.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
245
samp.magFilter = VK_FILTER_NEAREST;
246
samp.minFilter = VK_FILTER_NEAREST;
247
samp.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST;
248
VkResult res = vkCreateSampler(vulkan->GetDevice(), &samp, nullptr, &samplerNearest_);
249
_assert_(res == VK_SUCCESS);
250
251
CompileScalingShader();
252
253
computeShaderManager_.DeviceRestore(draw);
254
}
255
256
void TextureCacheVulkan::NotifyConfigChanged() {
257
TextureCacheCommon::NotifyConfigChanged();
258
CompileScalingShader();
259
}
260
261
static std::string ReadShaderSrc(const Path &filename) {
262
size_t sz = 0;
263
char *data = (char *)g_VFS.ReadFile(filename.c_str(), &sz);
264
if (!data)
265
return std::string();
266
267
std::string src(data, sz);
268
delete[] data;
269
return src;
270
}
271
272
void TextureCacheVulkan::CompileScalingShader() {
273
if (!draw_) {
274
// Something is very wrong.
275
return;
276
}
277
278
VulkanContext *vulkan = (VulkanContext *)draw_->GetNativeObject(Draw::NativeObject::CONTEXT);
279
280
if (!g_Config.bTexHardwareScaling || g_Config.sTextureShaderName != textureShader_) {
281
if (uploadCS_ != VK_NULL_HANDLE)
282
vulkan->Delete().QueueDeleteShaderModule(uploadCS_);
283
textureShader_.clear();
284
shaderScaleFactor_ = 0; // no texture scaling shader
285
} else if (uploadCS_) {
286
// No need to recreate.
287
return;
288
}
289
290
if (!g_Config.bTexHardwareScaling)
291
return;
292
293
ReloadAllPostShaderInfo(draw_);
294
const TextureShaderInfo *shaderInfo = GetTextureShaderInfo(g_Config.sTextureShaderName);
295
if (!shaderInfo || shaderInfo->computeShaderFile.empty())
296
return;
297
298
std::string shaderSource = ReadShaderSrc(shaderInfo->computeShaderFile);
299
std::string fullUploadShader = StringFromFormat(uploadShader, shaderSource.c_str());
300
301
std::string error;
302
uploadCS_ = CompileShaderModule(vulkan, VK_SHADER_STAGE_COMPUTE_BIT, fullUploadShader.c_str(), &error);
303
_dbg_assert_msg_(uploadCS_ != VK_NULL_HANDLE, "failed to compile upload shader");
304
305
textureShader_ = g_Config.sTextureShaderName;
306
shaderScaleFactor_ = shaderInfo->scaleFactor;
307
}
308
309
void TextureCacheVulkan::ReleaseTexture(TexCacheEntry *entry, bool delete_them) {
310
delete entry->vkTex;
311
entry->vkTex = nullptr;
312
}
313
314
VkFormat getClutDestFormatVulkan(GEPaletteFormat format) {
315
switch (format) {
316
case GE_CMODE_16BIT_ABGR4444:
317
return VULKAN_4444_FORMAT;
318
case GE_CMODE_16BIT_ABGR5551:
319
return VULKAN_1555_FORMAT;
320
case GE_CMODE_16BIT_BGR5650:
321
return VULKAN_565_FORMAT;
322
case GE_CMODE_32BIT_ABGR8888:
323
return VULKAN_8888_FORMAT;
324
}
325
return VK_FORMAT_UNDEFINED;
326
}
327
328
static const VkFilter MagFiltVK[2] = {
329
VK_FILTER_NEAREST,
330
VK_FILTER_LINEAR
331
};
332
333
void TextureCacheVulkan::StartFrame() {
334
TextureCacheCommon::StartFrame();
335
// TODO: For low memory detection, maybe use some indication from VMA.
336
// Maybe see https://gpuopen-librariesandsdks.github.io/VulkanMemoryAllocator/html/staying_within_budget.html#staying_within_budget_querying_for_budget .
337
computeShaderManager_.BeginFrame();
338
}
339
340
void TextureCacheVulkan::UpdateCurrentClut(GEPaletteFormat clutFormat, u32 clutBase, bool clutIndexIsSimple) {
341
const u32 clutBaseBytes = clutFormat == GE_CMODE_32BIT_ABGR8888 ? (clutBase * sizeof(u32)) : (clutBase * sizeof(u16));
342
// Technically, these extra bytes weren't loaded, but hopefully it was loaded earlier.
343
// If not, we're going to hash random data, which hopefully doesn't cause a performance issue.
344
//
345
// TODO: Actually, this seems like a hack. The game can upload part of a CLUT and reference other data.
346
// clutTotalBytes_ is the last amount uploaded. We should hash clutMaxBytes_, but this will often hash
347
// unrelated old entries for small palettes.
348
// Adding clutBaseBytes may just be mitigating this for some usage patterns.
349
const u32 clutExtendedBytes = std::min(clutTotalBytes_ + clutBaseBytes, clutMaxBytes_);
350
351
if (replacer_.Enabled())
352
clutHash_ = XXH32((const char *)clutBufRaw_, clutExtendedBytes, 0xC0108888);
353
else
354
clutHash_ = XXH3_64bits((const char *)clutBufRaw_, clutExtendedBytes) & 0xFFFFFFFF;
355
clutBuf_ = clutBufRaw_;
356
357
// Special optimization: fonts typically draw clut4 with just alpha values in a single color.
358
clutAlphaLinear_ = false;
359
clutAlphaLinearColor_ = 0;
360
if (clutFormat == GE_CMODE_16BIT_ABGR4444 && clutIndexIsSimple) {
361
const u16_le *clut = GetCurrentClut<u16_le>();
362
clutAlphaLinear_ = true;
363
clutAlphaLinearColor_ = clut[15] & 0x0FFF;
364
for (int i = 0; i < 16; ++i) {
365
u16 step = clutAlphaLinearColor_ | (i << 12);
366
if (clut[i] != step) {
367
clutAlphaLinear_ = false;
368
break;
369
}
370
}
371
}
372
373
clutLastFormat_ = gstate.clutformat;
374
}
375
376
void TextureCacheVulkan::BindTexture(TexCacheEntry *entry) {
377
if (!entry || !entry->vkTex) {
378
Unbind();
379
return;
380
}
381
382
int maxLevel = (entry->status & TexCacheEntry::STATUS_NO_MIPS) ? 0 : entry->maxLevel;
383
SamplerCacheKey samplerKey = GetSamplingParams(maxLevel, entry);
384
curSampler_ = samplerCache_.GetOrCreateSampler(samplerKey);
385
imageView_ = entry->vkTex->GetImageView();
386
drawEngine_->SetDepalTexture(VK_NULL_HANDLE, false);
387
gstate_c.SetUseShaderDepal(ShaderDepalMode::OFF);
388
}
389
390
void TextureCacheVulkan::ApplySamplingParams(const SamplerCacheKey &key) {
391
curSampler_ = samplerCache_.GetOrCreateSampler(key);
392
}
393
394
void TextureCacheVulkan::Unbind() {
395
imageView_ = VK_NULL_HANDLE;
396
curSampler_ = VK_NULL_HANDLE;
397
}
398
399
void TextureCacheVulkan::BindAsClutTexture(Draw::Texture *tex, bool smooth) {
400
VkImageView clutTexture = (VkImageView)draw_->GetNativeObject(Draw::NativeObject::TEXTURE_VIEW, tex);
401
drawEngine_->SetDepalTexture(clutTexture, smooth);
402
}
403
404
static Draw::DataFormat FromVulkanFormat(VkFormat fmt) {
405
switch (fmt) {
406
case VULKAN_8888_FORMAT: default: return Draw::DataFormat::R8G8B8A8_UNORM;
407
}
408
}
409
410
static VkFormat ToVulkanFormat(Draw::DataFormat fmt) {
411
switch (fmt) {
412
case Draw::DataFormat::BC1_RGBA_UNORM_BLOCK: return VK_FORMAT_BC1_RGBA_UNORM_BLOCK;
413
case Draw::DataFormat::BC2_UNORM_BLOCK: return VK_FORMAT_BC2_UNORM_BLOCK;
414
case Draw::DataFormat::BC3_UNORM_BLOCK: return VK_FORMAT_BC3_UNORM_BLOCK;
415
case Draw::DataFormat::BC4_UNORM_BLOCK: return VK_FORMAT_BC4_UNORM_BLOCK;
416
case Draw::DataFormat::BC5_UNORM_BLOCK: return VK_FORMAT_BC5_UNORM_BLOCK;
417
case Draw::DataFormat::BC7_UNORM_BLOCK: return VK_FORMAT_BC7_UNORM_BLOCK;
418
case Draw::DataFormat::ASTC_4x4_UNORM_BLOCK: return VK_FORMAT_ASTC_4x4_UNORM_BLOCK;
419
case Draw::DataFormat::ETC2_R8G8B8_UNORM_BLOCK: return VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK;
420
case Draw::DataFormat::ETC2_R8G8B8A1_UNORM_BLOCK: return VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK;
421
case Draw::DataFormat::ETC2_R8G8B8A8_UNORM_BLOCK: return VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK;
422
423
case Draw::DataFormat::R8G8B8A8_UNORM: return VULKAN_8888_FORMAT;
424
default: _assert_msg_(false, "Bad texture pixel format"); return VULKAN_8888_FORMAT;
425
}
426
}
427
428
void TextureCacheVulkan::BuildTexture(TexCacheEntry *const entry) {
429
VulkanContext *vulkan = (VulkanContext *)draw_->GetNativeObject(Draw::NativeObject::CONTEXT);
430
431
BuildTexturePlan plan;
432
plan.hardwareScaling = g_Config.bTexHardwareScaling && uploadCS_ != VK_NULL_HANDLE;
433
plan.slowScaler = !plan.hardwareScaling || vulkan->DevicePerfClass() == PerfClass::SLOW;
434
if (!PrepareBuildTexture(plan, entry)) {
435
// We're screwed (invalid size or something, corrupt display list), let's just zap it.
436
if (entry->vkTex) {
437
delete entry->vkTex;
438
entry->vkTex = nullptr;
439
}
440
return;
441
}
442
443
VkFormat dstFmt = GetDestFormat(GETextureFormat(entry->format), gstate.getClutPaletteFormat());
444
445
if (plan.scaleFactor > 1) {
446
_dbg_assert_(!plan.doReplace);
447
// Whether hardware or software scaling, this is the dest format.
448
dstFmt = VULKAN_8888_FORMAT;
449
} else if (plan.decodeToClut8) {
450
dstFmt = VULKAN_CLUT8_FORMAT;
451
}
452
453
_dbg_assert_(plan.levelsToLoad <= plan.maxPossibleLevels);
454
455
// We don't generate mipmaps for 512x512 textures because they're almost exclusively used for menu backgrounds
456
// and similar, which don't really need it.
457
// Also, if using replacements, check that we really can generate mips for this format - that's not possible for compressed ones.
458
if (g_Config.iTexFiltering == TEX_FILTER_AUTO_MAX_QUALITY && plan.w <= 256 && plan.h <= 256 && (!plan.doReplace || plan.replaced->Format() == Draw::DataFormat::R8G8B8A8_UNORM)) {
459
// Boost the number of mipmaps.
460
if (plan.maxPossibleLevels > plan.levelsToCreate) { // TODO: Should check against levelsToLoad, no?
461
// We have to generate mips with a shader. This requires decoding to R8G8B8A8_UNORM format to avoid extra complications.
462
dstFmt = VULKAN_8888_FORMAT;
463
}
464
plan.levelsToCreate = plan.maxPossibleLevels;
465
}
466
467
_dbg_assert_(plan.levelsToCreate >= plan.levelsToLoad);
468
469
// Any texture scaling is gonna move away from the original 16-bit format, if any.
470
VkFormat actualFmt = plan.scaleFactor > 1 ? VULKAN_8888_FORMAT : dstFmt;
471
bool bcFormat = false;
472
int bcAlign = 0;
473
if (plan.doReplace) {
474
Draw::DataFormat fmt = plan.replaced->Format();
475
bcFormat = Draw::DataFormatIsBlockCompressed(fmt, &bcAlign);
476
actualFmt = ToVulkanFormat(fmt);
477
}
478
479
bool computeUpload = false;
480
VkCommandBuffer cmdInit = (VkCommandBuffer)draw_->GetNativeObject(Draw::NativeObject::INIT_COMMANDBUFFER);
481
482
delete entry->vkTex;
483
484
VkImageLayout imageLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
485
VkImageUsageFlags usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
486
487
if (actualFmt == VULKAN_8888_FORMAT && plan.scaleFactor > 1 && plan.hardwareScaling) {
488
if (uploadCS_ != VK_NULL_HANDLE) {
489
computeUpload = true;
490
} else {
491
WARN_LOG(Log::G3D, "Falling back to software scaling, hardware shader didn't compile");
492
}
493
}
494
495
if (computeUpload) {
496
usage |= VK_IMAGE_USAGE_STORAGE_BIT;
497
imageLayout = VK_IMAGE_LAYOUT_GENERAL;
498
}
499
500
if (plan.saveTexture) {
501
DEBUG_LOG(Log::G3D, "About to save texture (%dx%d) (might not, if it already exists)", plan.createW, plan.createH);
502
actualFmt = VULKAN_8888_FORMAT;
503
}
504
505
const VkComponentMapping *mapping;
506
switch (actualFmt) {
507
case VULKAN_4444_FORMAT: mapping = &VULKAN_4444_SWIZZLE; break;
508
case VULKAN_1555_FORMAT: mapping = &VULKAN_1555_SWIZZLE; break;
509
case VULKAN_565_FORMAT: mapping = &VULKAN_565_SWIZZLE; break;
510
default: mapping = &VULKAN_8888_SWIZZLE; break; // no channel swizzle
511
}
512
513
char texName[64];
514
snprintf(texName, sizeof(texName), "tex_%08x_%s_%s", entry->addr, GeTextureFormatToString((GETextureFormat)entry->format, gstate.getClutPaletteFormat()), gstate.isTextureSwizzled() ? "swz" : "lin");
515
entry->vkTex = new VulkanTexture(vulkan, texName);
516
VulkanTexture *image = entry->vkTex;
517
518
VulkanBarrierBatch barrier;
519
bool allocSuccess = image->CreateDirect(plan.createW, plan.createH, plan.depth, plan.levelsToCreate, actualFmt, imageLayout, usage, &barrier, mapping);
520
barrier.Flush(cmdInit);
521
if (!allocSuccess && !lowMemoryMode_) {
522
WARN_LOG_REPORT(Log::G3D, "Texture cache ran out of GPU memory; switching to low memory mode");
523
lowMemoryMode_ = true;
524
decimationCounter_ = 0;
525
Decimate(entry, true);
526
527
// TODO: We should stall the GPU here and wipe things out of memory.
528
// As is, it will almost definitely fail the second time, but next frame it may recover.
529
530
auto err = GetI18NCategory(I18NCat::ERRORS);
531
if (plan.scaleFactor > 1) {
532
g_OSD.Show(OSDType::MESSAGE_WARNING, err->T("Warning: Video memory FULL, reducing upscaling and switching to slow caching mode"), 2.0f);
533
} else {
534
g_OSD.Show(OSDType::MESSAGE_WARNING, err->T("Warning: Video memory FULL, switching to slow caching mode"), 2.0f);
535
}
536
537
// Turn off texture replacement for this texture.
538
plan.replaced = nullptr;
539
540
plan.createW /= plan.scaleFactor;
541
plan.createH /= plan.scaleFactor;
542
plan.scaleFactor = 1;
543
actualFmt = dstFmt;
544
545
allocSuccess = image->CreateDirect(plan.createW, plan.createH, plan.depth, plan.levelsToCreate, actualFmt, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, &barrier, mapping);
546
barrier.Flush(cmdInit);
547
}
548
549
if (!allocSuccess) {
550
ERROR_LOG(Log::G3D, "Failed to create texture (%dx%d)", plan.w, plan.h);
551
delete entry->vkTex;
552
entry->vkTex = nullptr;
553
}
554
555
if (!entry->vkTex) {
556
return;
557
}
558
559
VK_PROFILE_BEGIN(vulkan, cmdInit, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
560
"Texture Upload (%08x) video=%d", entry->addr, plan.isVideo);
561
562
// Upload the texture data. We simply reuse the same loop for 3D texture slices instead of mips, if we have those.
563
int levels;
564
if (plan.depth > 1) {
565
levels = plan.depth;
566
} else {
567
levels = plan.levelsToLoad;
568
}
569
570
VulkanPushPool *pushBuffer = drawEngine_->GetPushBufferForTextureData();
571
572
// Batch the copies.
573
TextureCopyBatch copyBatch;
574
copyBatch.reserve(levels);
575
576
for (int i = 0; i < levels; i++) {
577
int mipUnscaledWidth = gstate.getTextureWidth(i);
578
int mipUnscaledHeight = gstate.getTextureHeight(i);
579
580
int mipWidth;
581
int mipHeight;
582
plan.GetMipSize(i, &mipWidth, &mipHeight);
583
584
int bpp = VkFormatBytesPerPixel(actualFmt);
585
int optimalStrideAlignment = std::max(4, (int)vulkan->GetPhysicalDeviceProperties().properties.limits.optimalBufferCopyRowPitchAlignment);
586
int byteStride = RoundUpToPowerOf2(mipWidth * bpp, optimalStrideAlignment); // output stride
587
int pixelStride = byteStride / bpp;
588
int uploadSize = byteStride * mipHeight;
589
590
uint32_t bufferOffset;
591
VkBuffer texBuf;
592
// NVIDIA reports a min alignment of 1 but that can't be healthy... let's align by 16 as a minimum.
593
int pushAlignment = std::max(16, (int)vulkan->GetPhysicalDeviceProperties().properties.limits.optimalBufferCopyOffsetAlignment);
594
void *data;
595
std::vector<uint8_t> saveData;
596
597
// Simple wrapper to avoid reading back from VRAM (very, very expensive).
598
auto loadLevel = [&](int sz, int srcLevel, int lstride, int lfactor) {
599
if (plan.saveTexture) {
600
saveData.resize(sz);
601
data = &saveData[0];
602
} else {
603
data = pushBuffer->Allocate(sz, pushAlignment, &texBuf, &bufferOffset);
604
}
605
LoadVulkanTextureLevel(*entry, (uint8_t *)data, lstride, srcLevel, lfactor, actualFmt);
606
if (plan.saveTexture)
607
bufferOffset = pushBuffer->Push(&saveData[0], sz, pushAlignment, &texBuf);
608
};
609
610
bool dataScaled = true;
611
int srcStride = byteStride;
612
if (plan.doReplace) {
613
int rowLength = pixelStride;
614
if (bcFormat) {
615
// For block compressed formats, we just set the upload size to the data size..
616
uploadSize = plan.replaced->GetLevelDataSizeAfterCopy(plan.baseLevelSrc + i);
617
rowLength = (mipWidth + 3) & ~3;
618
}
619
// Directly load the replaced image.
620
data = pushBuffer->Allocate(uploadSize, pushAlignment, &texBuf, &bufferOffset);
621
double replaceStart = time_now_d();
622
if (!plan.replaced->CopyLevelTo(plan.baseLevelSrc + i, (uint8_t *)data, uploadSize, byteStride)) { // If plan.doReplace, this shouldn't fail.
623
WARN_LOG(Log::G3D, "Failed to copy replaced texture level");
624
// TODO: Fill with some pattern?
625
}
626
replacementTimeThisFrame_ += time_now_d() - replaceStart;
627
entry->vkTex->CopyBufferToMipLevel(cmdInit, &copyBatch, i, mipWidth, mipHeight, 0, texBuf, bufferOffset, rowLength);
628
} else {
629
if (plan.depth != 1) {
630
// 3D texturing.
631
loadLevel(uploadSize, i, byteStride, plan.scaleFactor);
632
entry->vkTex->CopyBufferToMipLevel(cmdInit, &copyBatch, 0, mipWidth, mipHeight, i, texBuf, bufferOffset, pixelStride);
633
} else if (computeUpload) {
634
int srcBpp = VkFormatBytesPerPixel(dstFmt);
635
srcStride = mipUnscaledWidth * srcBpp;
636
int srcSize = srcStride * mipUnscaledHeight;
637
loadLevel(srcSize, i == 0 ? plan.baseLevelSrc : i, srcStride, 1);
638
dataScaled = false;
639
640
// This format can be used with storage images.
641
VkImageView view = entry->vkTex->CreateViewForMip(i);
642
VkDescriptorSet descSet = computeShaderManager_.GetDescriptorSet(view, texBuf, bufferOffset, srcSize);
643
struct Params { int x; int y; } params{ mipUnscaledWidth, mipUnscaledHeight };
644
VK_PROFILE_BEGIN(vulkan, cmdInit, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
645
"Compute Upload: %dx%d->%dx%d", mipUnscaledWidth, mipUnscaledHeight, mipWidth, mipHeight);
646
vkCmdBindPipeline(cmdInit, VK_PIPELINE_BIND_POINT_COMPUTE, computeShaderManager_.GetPipeline(uploadCS_));
647
vkCmdBindDescriptorSets(cmdInit, VK_PIPELINE_BIND_POINT_COMPUTE, computeShaderManager_.GetPipelineLayout(), 0, 1, &descSet, 0, nullptr);
648
vkCmdPushConstants(cmdInit, computeShaderManager_.GetPipelineLayout(), VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(params), &params);
649
vkCmdDispatch(cmdInit, (mipUnscaledWidth + 7) / 8, (mipUnscaledHeight + 7) / 8, 1);
650
VK_PROFILE_END(vulkan, cmdInit, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
651
vulkan->Delete().QueueDeleteImageView(view);
652
} else {
653
loadLevel(uploadSize, i == 0 ? plan.baseLevelSrc : i, byteStride, plan.scaleFactor);
654
entry->vkTex->CopyBufferToMipLevel(cmdInit, &copyBatch, i, mipWidth, mipHeight, 0, texBuf, bufferOffset, pixelStride);
655
}
656
// Format might be wrong in lowMemoryMode_, so don't save.
657
if (plan.saveTexture && !lowMemoryMode_) {
658
// When hardware texture scaling is enabled, this saves the original.
659
const int w = dataScaled ? mipWidth : mipUnscaledWidth;
660
const int h = dataScaled ? mipHeight : mipUnscaledHeight;
661
const int stride = dataScaled ? byteStride : srcStride;
662
// At this point, data should be saveData, and not slow.
663
ReplacedTextureDecodeInfo replacedInfo;
664
replacedInfo.cachekey = entry->CacheKey();
665
replacedInfo.hash = entry->fullhash;
666
replacedInfo.addr = entry->addr;
667
replacedInfo.isVideo = IsVideo(entry->addr);
668
replacedInfo.isFinal = (entry->status & TexCacheEntry::STATUS_TO_SCALE) == 0;
669
replacedInfo.fmt = FromVulkanFormat(actualFmt);
670
replacer_.NotifyTextureDecoded(plan.replaced, replacedInfo, data, stride, plan.baseLevelSrc + i, mipUnscaledWidth, mipUnscaledHeight, w, h);
671
}
672
}
673
}
674
675
if (!copyBatch.empty()) {
676
VK_PROFILE_BEGIN(vulkan, cmdInit, VK_PIPELINE_STAGE_TRANSFER_BIT, "Copy Upload");
677
// Submit the whole batch of mip uploads.
678
entry->vkTex->FinishCopyBatch(cmdInit, &copyBatch);
679
VK_PROFILE_END(vulkan, cmdInit, VK_PIPELINE_STAGE_TRANSFER_BIT);
680
}
681
682
VkImageLayout layout = computeUpload ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
683
VkPipelineStageFlags prevStage = computeUpload ? VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT : VK_PIPELINE_STAGE_TRANSFER_BIT;
684
685
// Generate any additional mipmap levels.
686
// This will transition the whole stack to GENERAL if it wasn't already.
687
if (plan.levelsToLoad < plan.levelsToCreate) {
688
VK_PROFILE_BEGIN(vulkan, cmdInit, VK_PIPELINE_STAGE_TRANSFER_BIT, "Mipgen up to level %d", plan.levelsToCreate);
689
entry->vkTex->GenerateMips(cmdInit, plan.levelsToLoad, computeUpload);
690
layout = VK_IMAGE_LAYOUT_GENERAL;
691
prevStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
692
VK_PROFILE_END(vulkan, cmdInit, VK_PIPELINE_STAGE_TRANSFER_BIT);
693
}
694
695
entry->vkTex->EndCreate(cmdInit, false, prevStage, layout);
696
VK_PROFILE_END(vulkan, cmdInit, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
697
698
// Signal that we support depth textures so use it as one.
699
if (plan.depth > 1) {
700
entry->status |= TexCacheEntry::STATUS_3D;
701
}
702
703
if (plan.doReplace) {
704
entry->SetAlphaStatus(TexCacheEntry::TexStatus(plan.replaced->AlphaStatus()));
705
}
706
}
707
708
VkFormat TextureCacheVulkan::GetDestFormat(GETextureFormat format, GEPaletteFormat clutFormat) {
709
if (!gstate_c.Use(GPU_USE_16BIT_FORMATS)) {
710
return VK_FORMAT_R8G8B8A8_UNORM;
711
}
712
switch (format) {
713
case GE_TFMT_CLUT4:
714
case GE_TFMT_CLUT8:
715
case GE_TFMT_CLUT16:
716
case GE_TFMT_CLUT32:
717
return getClutDestFormatVulkan(clutFormat);
718
case GE_TFMT_4444:
719
return VULKAN_4444_FORMAT;
720
case GE_TFMT_5551:
721
return VULKAN_1555_FORMAT;
722
case GE_TFMT_5650:
723
return VULKAN_565_FORMAT;
724
case GE_TFMT_8888:
725
case GE_TFMT_DXT1:
726
case GE_TFMT_DXT3:
727
case GE_TFMT_DXT5:
728
default:
729
return VULKAN_8888_FORMAT;
730
}
731
}
732
733
void TextureCacheVulkan::LoadVulkanTextureLevel(TexCacheEntry &entry, uint8_t *writePtr, int rowPitch, int level, int scaleFactor, VkFormat dstFmt) {
734
int w = gstate.getTextureWidth(level);
735
int h = gstate.getTextureHeight(level);
736
737
GETextureFormat tfmt = (GETextureFormat)entry.format;
738
GEPaletteFormat clutformat = gstate.getClutPaletteFormat();
739
u32 texaddr = gstate.getTextureAddress(level);
740
741
_assert_msg_(texaddr != 0, "Can't load a texture from address null")
742
743
int bufw = GetTextureBufw(level, texaddr, tfmt);
744
int bpp = VkFormatBytesPerPixel(dstFmt);
745
746
u32 *pixelData;
747
int decPitch;
748
749
TexDecodeFlags texDecFlags{};
750
if (!gstate_c.Use(GPU_USE_16BIT_FORMATS) || scaleFactor > 1 || dstFmt == VULKAN_8888_FORMAT) {
751
texDecFlags |= TexDecodeFlags::EXPAND32;
752
}
753
if (entry.status & TexCacheEntry::STATUS_CLUT_GPU) {
754
texDecFlags |= TexDecodeFlags::TO_CLUT8;
755
}
756
757
if (scaleFactor > 1) {
758
tmpTexBufRearrange_.resize(std::max(bufw, w) * h);
759
pixelData = tmpTexBufRearrange_.data();
760
// We want to end up with a neatly packed texture for scaling.
761
decPitch = w * bpp;
762
} else {
763
pixelData = (u32 *)writePtr;
764
decPitch = rowPitch;
765
}
766
767
CheckAlphaResult alphaResult = DecodeTextureLevel((u8 *)pixelData, decPitch, tfmt, clutformat, texaddr, level, bufw, texDecFlags);
768
entry.SetAlphaStatus(alphaResult, level);
769
770
if (scaleFactor > 1) {
771
u32 fmt = dstFmt;
772
// CPU scaling reads from the destination buffer so we want cached RAM.
773
size_t allocBytes = w * scaleFactor * h * scaleFactor * 4;
774
uint8_t *scaleBuf = (uint8_t *)AllocateAlignedMemory(allocBytes, 16);
775
_assert_msg_(scaleBuf, "Failed to allocate %d aligned bytes for texture scaler", (int)allocBytes);
776
777
scaler_.ScaleAlways((u32 *)scaleBuf, pixelData, w, h, &w, &h, scaleFactor);
778
pixelData = (u32 *)writePtr;
779
780
// We always end up at 8888. Other parts assume this.
781
_assert_(dstFmt == VULKAN_8888_FORMAT);
782
bpp = sizeof(u32);
783
decPitch = w * bpp;
784
785
if (decPitch != rowPitch) {
786
for (int y = 0; y < h; ++y) {
787
memcpy(writePtr + rowPitch * y, scaleBuf + decPitch * y, w * bpp);
788
}
789
decPitch = rowPitch;
790
} else {
791
memcpy(writePtr, scaleBuf, w * h * 4);
792
}
793
FreeAlignedMemory(scaleBuf);
794
}
795
}
796
797
void TextureCacheVulkan::BoundFramebufferTexture() {
798
imageView_ = (VkImageView)draw_->GetNativeObject(Draw::NativeObject::BOUND_TEXTURE0_IMAGEVIEW);
799
}
800
801
bool TextureCacheVulkan::GetCurrentTextureDebug(GPUDebugBuffer &buffer, int level, bool *isFramebuffer) {
802
SetTexture();
803
if (!nextTexture_) {
804
return GetCurrentFramebufferTextureDebug(buffer, isFramebuffer);
805
}
806
807
// Apply texture may need to rebuild the texture if we're about to render, or bind a framebuffer.
808
TexCacheEntry *entry = nextTexture_;
809
ApplyTexture();
810
811
if (!entry->vkTex)
812
return false;
813
814
VulkanTexture *texture = entry->vkTex;
815
VulkanRenderManager *renderManager = (VulkanRenderManager *)draw_->GetNativeObject(Draw::NativeObject::RENDER_MANAGER);
816
817
GPUDebugBufferFormat bufferFormat;
818
Draw::DataFormat drawFormat;
819
switch (texture->GetFormat()) {
820
case VULKAN_565_FORMAT:
821
bufferFormat = GPU_DBG_FORMAT_565;
822
drawFormat = Draw::DataFormat::B5G6R5_UNORM_PACK16;
823
break;
824
case VULKAN_1555_FORMAT:
825
bufferFormat = GPU_DBG_FORMAT_5551;
826
drawFormat = Draw::DataFormat::B5G5R5A1_UNORM_PACK16;
827
break;
828
case VULKAN_4444_FORMAT:
829
bufferFormat = GPU_DBG_FORMAT_4444;
830
drawFormat = Draw::DataFormat::B4G4R4A4_UNORM_PACK16;
831
break;
832
case VULKAN_8888_FORMAT:
833
default:
834
bufferFormat = GPU_DBG_FORMAT_8888;
835
drawFormat = Draw::DataFormat::R8G8B8A8_UNORM;
836
break;
837
}
838
839
int w = texture->GetWidth();
840
int h = texture->GetHeight();
841
if (level > 0) {
842
// In the future, maybe this could do something for 3D textures...
843
if (level >= texture->GetNumMips())
844
return false;
845
w >>= level;
846
h >>= level;
847
}
848
buffer.Allocate(w, h, bufferFormat);
849
850
renderManager->CopyImageToMemorySync(texture->GetImage(), level, 0, 0, w, h, drawFormat, (uint8_t *)buffer.GetData(), w, "GetCurrentTextureDebug");
851
852
// Vulkan requires us to re-apply all dynamic state for each command buffer, and the above will cause us to start a new cmdbuf.
853
// So let's dirty the things that are involved in Vulkan dynamic state. Readbacks are not frequent so this won't hurt other backends.
854
gstate_c.Dirty(DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_BLEND_STATE | DIRTY_DEPTHSTENCIL_STATE);
855
framebufferManager_->RebindFramebuffer("RebindFramebuffer - GetCurrentTextureDebug");
856
*isFramebuffer = false;
857
return true;
858
}
859
860
void TextureCacheVulkan::GetStats(char *ptr, size_t size) {
861
snprintf(ptr, size, "N/A");
862
}
863
864
std::vector<std::string> TextureCacheVulkan::DebugGetSamplerIDs() const {
865
return samplerCache_.DebugGetSamplerIDs();
866
}
867
868
std::string TextureCacheVulkan::DebugGetSamplerString(const std::string &id, DebugShaderStringType stringType) {
869
return samplerCache_.DebugGetSamplerString(id, stringType);
870
}
871
872
void *TextureCacheVulkan::GetNativeTextureView(const TexCacheEntry *entry, bool flat) const {
873
VkImageView view = flat ? entry->vkTex->GetImageView() : entry->vkTex->GetImageArrayView();
874
return (void *)view;
875
}
876
877