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