Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hrydgard
GitHub Repository: hrydgard/ppsspp
Path: blob/master/GPU/Common/ReplacedTexture.cpp
5654 views
1
// Copyright (c) 2016- 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
20
#include "ppsspp_config.h"
21
22
#include <png.h>
23
24
#include "ext/basis_universal/basisu_transcoder.h"
25
#include "ext/basis_universal/basisu_file_headers.h"
26
27
#include "GPU/Common/ReplacedTexture.h"
28
#include "GPU/Common/TextureReplacer.h"
29
30
#include "Common/Data/Format/DDSLoad.h"
31
#include "Common/Data/Format/ZIMLoad.h"
32
#include "Common/Data/Format/PNGLoad.h"
33
#include "Common/Thread/ParallelLoop.h"
34
#include "Common/Thread/Waitable.h"
35
#include "Common/Thread/ThreadManager.h"
36
#include "Common/Log.h"
37
#include "Common/TimeUtil.h"
38
39
#define MK_FOURCC(str) (str[0] | ((uint8_t)str[1] << 8) | ((uint8_t)str[2] << 16) | ((uint8_t)str[3] << 24))
40
41
static ReplacedImageType IdentifyMagic(const uint8_t magic[4]) {
42
if (memcmp((const char *)magic, "ZIMG", 4) == 0)
43
return ReplacedImageType::ZIM;
44
else if (magic[0] == 0x89 && strncmp((const char *)&magic[1], "PNG", 3) == 0)
45
return ReplacedImageType::PNG;
46
else if (memcmp((const char *)magic, "DDS ", 4) == 0)
47
return ReplacedImageType::DDS;
48
else if (magic[0] == 's' && magic[1] == 'B') {
49
uint16_t ver = magic[2] | (magic[3] << 8);
50
if (ver >= 0x10) {
51
return ReplacedImageType::BASIS;
52
}
53
} else if (memcmp((const char *)magic, "\xabKTX", 4) == 0) {
54
// Technically, should read 12 bytes here, but this'll do.
55
return ReplacedImageType::KTX2;
56
}
57
return ReplacedImageType::INVALID;
58
}
59
60
static ReplacedImageType Identify(VFSBackend *vfs, VFSOpenFile *openFile, std::string *outMagic) {
61
uint8_t magic[4];
62
if (vfs->Read(openFile, magic, 4) != 4) {
63
*outMagic = "FAIL";
64
return ReplacedImageType::INVALID;
65
}
66
// Turn the signature into a readable string that we can display in an error message.
67
*outMagic = std::string((const char *)magic, 4);
68
for (int i = 0; i < outMagic->size(); i++) {
69
if ((s8)(*outMagic)[i] < 32) {
70
(*outMagic)[i] = '_';
71
}
72
}
73
vfs->Rewind(openFile);
74
return IdentifyMagic(magic);
75
}
76
77
class ReplacedTextureTask : public Task {
78
public:
79
ReplacedTextureTask(VFSBackend *vfs, ReplacedTexture &tex, LimitedWaitable *w) : vfs_(vfs), tex_(tex), waitable_(w) {}
80
81
TaskType Type() const override { return TaskType::IO_BLOCKING; }
82
TaskPriority Priority() const override { return TaskPriority::NORMAL; }
83
84
void Run() override {
85
tex_.Prepare(vfs_);
86
waitable_->Notify();
87
}
88
89
private:
90
VFSBackend *vfs_;
91
ReplacedTexture &tex_;
92
LimitedWaitable *waitable_;
93
};
94
95
ReplacedTexture::ReplacedTexture(VFSBackend *vfs, const ReplacementDesc &desc) : vfs_(vfs), desc_(desc) {
96
logId_ = desc.logId;
97
}
98
99
ReplacedTexture::~ReplacedTexture() {
100
if (threadWaitable_) {
101
SetState(ReplacementState::CANCEL_INIT);
102
103
threadWaitable_->WaitAndRelease();
104
threadWaitable_ = nullptr;
105
}
106
107
for (auto &level : levels_) {
108
vfs_->ReleaseFile(level.fileRef);
109
level.fileRef = nullptr;
110
}
111
}
112
113
void ReplacedTexture::PurgeIfNotUsedSinceTime(double t) {
114
if (State() != ReplacementState::ACTIVE) {
115
return;
116
}
117
118
// If there's some leftover threadWaitable, get rid of it.
119
if (threadWaitable_) {
120
if (threadWaitable_->WaitFor(0.0)) {
121
delete threadWaitable_;
122
threadWaitable_ = nullptr;
123
// Continue with purging.
124
} else {
125
// Try next time.
126
return;
127
}
128
}
129
130
// This is the only place except shutdown where a texture can transition
131
// from ACTIVE to anything else, so we don't actually need to lock here.
132
if (lastUsed_ >= t) {
133
return;
134
}
135
136
data_.clear();
137
levels_.clear();
138
fmt = Draw::DataFormat::UNDEFINED;
139
alphaStatus_ = ReplacedTextureAlpha::UNKNOWN;
140
141
// This means we have to reload. If we never purge any, there's no need.
142
SetState(ReplacementState::UNLOADED);
143
}
144
145
// This can only return true if ACTIVE or NOT_FOUND.
146
bool ReplacedTexture::Poll(double budget) {
147
_assert_(vfs_ != nullptr);
148
149
double now = time_now_d();
150
151
switch (State()) {
152
case ReplacementState::ACTIVE:
153
case ReplacementState::NOT_FOUND:
154
if (threadWaitable_) {
155
if (!threadWaitable_->WaitFor(budget)) {
156
lastUsed_ = now;
157
return false;
158
}
159
// Successfully waited! Can get rid of it.
160
threadWaitable_->WaitAndRelease();
161
threadWaitable_ = nullptr;
162
lastUsed = now;
163
}
164
lastUsed_ = now;
165
return true;
166
case ReplacementState::CANCEL_INIT:
167
case ReplacementState::PENDING:
168
return false;
169
case ReplacementState::UNLOADED:
170
// We're gonna need to spawn a task.
171
break;
172
default:
173
break;
174
}
175
176
lastUsed_ = now;
177
178
// Let's not even start a new texture if we're already behind.
179
// Note that 0.0 is used as a signalling value that we don't want to wait (just handling already finished textures).
180
if (budget < 0.0)
181
return false;
182
183
_assert_(!threadWaitable_);
184
threadWaitable_ = new LimitedWaitable();
185
SetState(ReplacementState::PENDING);
186
g_threadManager.EnqueueTask(new ReplacedTextureTask(vfs_, *this, threadWaitable_));
187
if (threadWaitable_->WaitFor(budget)) {
188
// If we successfully wait here, we're done. The thread will set state accordingly.
189
_assert_(State() == ReplacementState::ACTIVE || State() == ReplacementState::NOT_FOUND || State() == ReplacementState::CANCEL_INIT);
190
delete threadWaitable_;
191
threadWaitable_ = nullptr;
192
return true;
193
}
194
// Still pending on thread.
195
return false;
196
}
197
198
inline uint32_t RoundUpTo4(uint32_t value) {
199
return (value + 3) & ~3;
200
}
201
202
void ReplacedTexture::Prepare(VFSBackend *vfs) {
203
_assert_(vfs != nullptr);
204
205
this->vfs_ = vfs;
206
207
std::unique_lock<std::mutex> lock(lock_);
208
209
fmt = Draw::DataFormat::UNDEFINED;
210
211
Draw::DataFormat pixelFormat;
212
LoadLevelResult result = LoadLevelResult::LOAD_ERROR;
213
if (desc_.filenames.empty()) {
214
result = LoadLevelResult::DONE;
215
}
216
for (int i = 0; i < std::min(MAX_REPLACEMENT_MIP_LEVELS, (int)desc_.filenames.size()); ++i) {
217
if (State() == ReplacementState::CANCEL_INIT) {
218
break;
219
}
220
221
if (desc_.filenames[i].empty()) {
222
// Out of valid mip levels. Bail out.
223
break;
224
}
225
226
std::string path(desc_.filenames[i]);
227
VFSFileReference *fileRef = vfs_->GetFile(path.c_str());
228
if (!fileRef) {
229
if (i == 0) {
230
INFO_LOG(Log::TexReplacement, "Texture replacement file '%s' not found in %s", desc_.filenames[i].c_str(), vfs_->toString().c_str());
231
// No file at all. Mark as NOT_FOUND.
232
SetState(ReplacementState::NOT_FOUND);
233
return;
234
}
235
// If the file doesn't exist, let's just bail immediately here.
236
// Mark as DONE, not error.
237
result = LoadLevelResult::DONE;
238
break;
239
}
240
241
if (i == 0) {
242
fmt = Draw::DataFormat::R8G8B8A8_UNORM;
243
}
244
245
result = LoadLevelData(fileRef, desc_.filenames[i], i, &pixelFormat);
246
if (result == LoadLevelResult::DONE) {
247
// Loaded all the levels we're gonna get.
248
fmt = pixelFormat;
249
break;
250
} else if (result == LoadLevelResult::CONTINUE) {
251
if (i == 0) {
252
fmt = pixelFormat;
253
} else {
254
if (fmt != pixelFormat) {
255
ERROR_LOG(Log::TexReplacement, "Replacement mipmap %d doesn't have the same pixel format as mipmap 0. Stopping.", i);
256
break;
257
}
258
}
259
} else {
260
// Error state.
261
break;
262
}
263
}
264
265
if (levels_.empty()) {
266
// No replacement found.
267
std::string name = TextureReplacer::HashName(desc_.cachekey, desc_.hash, 0);
268
if (result == LoadLevelResult::LOAD_ERROR) {
269
WARN_LOG(Log::TexReplacement, "Failed to load replacement texture '%s'", name.c_str());
270
}
271
SetState(ReplacementState::NOT_FOUND);
272
return;
273
}
274
275
// Update the level dimensions.
276
for (auto &level : levels_) {
277
level.fullW = (level.w * desc_.w) / desc_.newW;
278
level.fullH = (level.h * desc_.h) / desc_.newH;
279
280
int blockSize;
281
bool bc = Draw::DataFormatIsBlockCompressed(fmt, &blockSize);
282
if (!bc) {
283
level.fullDataSize = level.fullW * level.fullH * 4;
284
} else {
285
level.fullDataSize = RoundUpTo4(level.fullW) * RoundUpTo4(level.fullH) * blockSize / 16;
286
}
287
}
288
289
SetState(ReplacementState::ACTIVE);
290
291
// the caller calls threadWaitable->notify().
292
}
293
294
// Returns true if Prepare should keep calling this to load more levels.
295
ReplacedTexture::LoadLevelResult ReplacedTexture::LoadLevelData(VFSFileReference *fileRef, const std::string &filename, int mipLevel, Draw::DataFormat *pixelFormat) {
296
bool good = false;
297
298
if (data_.size() <= mipLevel) {
299
data_.resize(mipLevel + 1);
300
}
301
302
if (!vfs_) {
303
ERROR_LOG(Log::TexReplacement, "Unexpected null vfs_ pointer in LoadLevelData");
304
return LoadLevelResult::LOAD_ERROR;
305
}
306
307
ReplacedTextureLevel level;
308
size_t fileSize;
309
VFSOpenFile *openFile = vfs_->OpenFileForRead(fileRef, &fileSize);
310
if (!openFile) {
311
// File missing, no more levels. This is alright.
312
return LoadLevelResult::DONE;
313
}
314
315
std::string magic;
316
ReplacedImageType imageType = Identify(vfs_, openFile, &magic);
317
318
bool ddsDX10 = false;
319
int numMips = 1;
320
321
if (imageType == ReplacedImageType::KTX2) {
322
KTXHeader header;
323
good = vfs_->Read(openFile, &header, sizeof(header)) == sizeof(header);
324
325
level.w = header.pixelWidth;
326
level.h = header.pixelHeight;
327
numMips = header.levelCount;
328
329
// Additional quick checks
330
good = good && header.layerCount <= 1;
331
} else if (imageType == ReplacedImageType::BASIS) {
332
WARN_LOG(Log::TexReplacement, "The basis texture format is not supported. Use KTX2 (basisu texture.png -uastc -ktx2 -mipmap)");
333
334
// We simply don't support basis files currently.
335
good = false;
336
} else if (imageType == ReplacedImageType::DDS) {
337
DDSHeader header;
338
DDSHeaderDXT10 header10{};
339
good = vfs_->Read(openFile, &header, sizeof(header)) == sizeof(header);
340
341
*pixelFormat = Draw::DataFormat::UNDEFINED;
342
u32 format;
343
if (good && (header.ddspf.dwFlags & DDPF_FOURCC)) {
344
char *fcc = (char *)&header.ddspf.dwFourCC;
345
// INFO_LOG(Log::TexReplacement, "DDS fourcc: %c%c%c%c", fcc[0], fcc[1], fcc[2], fcc[3]);
346
if (header.ddspf.dwFourCC == MK_FOURCC("DX10")) {
347
ddsDX10 = true;
348
good = good && vfs_->Read(openFile, &header10, sizeof(header10)) == sizeof(header10);
349
format = header10.dxgiFormat;
350
switch (format) {
351
case 71: // DXGI_FORMAT_BC1_UNORM
352
case 72: // DXGI_FORMAT_BC1_UNORM_SRGB
353
if (!desc_.formatSupport.bc123) {
354
WARN_LOG(Log::TexReplacement, "BC1 format not supported, skipping texture");
355
good = false;
356
}
357
*pixelFormat = Draw::DataFormat::BC1_RGBA_UNORM_BLOCK;
358
break;
359
case 74: // DXGI_FORMAT_BC2_UNORM
360
case 75: // DXGI_FORMAT_BC2_UNORM_SRGB
361
if (!desc_.formatSupport.bc123) {
362
WARN_LOG(Log::TexReplacement, "BC2 format not supported, skipping texture");
363
good = false;
364
}
365
*pixelFormat = Draw::DataFormat::BC2_UNORM_BLOCK;
366
break;
367
case 77: // DXGI_FORMAT_BC3_UNORM
368
case 78: // DXGI_FORMAT_BC3_UNORM_SRGB
369
if (!desc_.formatSupport.bc123) {
370
WARN_LOG(Log::TexReplacement, "BC3 format not supported, skipping texture");
371
good = false;
372
}
373
*pixelFormat = Draw::DataFormat::BC3_UNORM_BLOCK;
374
break;
375
case 98: // DXGI_FORMAT_BC7_UNORM:
376
case 99: // DXGI_FORMAT_BC7_UNORM_SRGB:
377
if (!desc_.formatSupport.bc7) {
378
WARN_LOG(Log::TexReplacement, "BC7 format not supported, skipping texture");
379
good = false;
380
}
381
*pixelFormat = Draw::DataFormat::BC7_UNORM_BLOCK;
382
break;
383
default:
384
WARN_LOG(Log::TexReplacement, "DXGI pixel format %d not supported.", header10.dxgiFormat);
385
good = false;
386
}
387
} else {
388
if (!desc_.formatSupport.bc123) {
389
WARN_LOG(Log::TexReplacement, "BC1-3 formats not supported");
390
good = false;
391
}
392
format = header.ddspf.dwFourCC;
393
// OK, there are a number of possible formats we might have ended up with. We choose just a few
394
// to support for now.
395
switch (format) {
396
case MK_FOURCC("DXT1"):
397
*pixelFormat = Draw::DataFormat::BC1_RGBA_UNORM_BLOCK;
398
break;
399
case MK_FOURCC("DXT3"):
400
*pixelFormat = Draw::DataFormat::BC2_UNORM_BLOCK;
401
break;
402
case MK_FOURCC("DXT5"):
403
*pixelFormat = Draw::DataFormat::BC3_UNORM_BLOCK;
404
break;
405
default:
406
ERROR_LOG(Log::TexReplacement, "DDS pixel format not supported.");
407
good = false;
408
}
409
}
410
} else if (good) {
411
ERROR_LOG(Log::TexReplacement, "DDS non-fourCC format not supported.");
412
good = false;
413
}
414
415
level.w = header.dwWidth;
416
level.h = header.dwHeight;
417
numMips = header.dwMipMapCount;
418
} else if (imageType == ReplacedImageType::ZIM) {
419
uint32_t ignore = 0;
420
struct ZimHeader {
421
uint32_t magic;
422
uint32_t w;
423
uint32_t h;
424
uint32_t flags;
425
} header;
426
good = vfs_->Read(openFile, &header, sizeof(header)) == sizeof(header);
427
level.w = header.w;
428
level.h = header.h;
429
good = good && (header.flags & ZIM_FORMAT_MASK) == ZIM_RGBA8888;
430
*pixelFormat = Draw::DataFormat::R8G8B8A8_UNORM;
431
} else if (imageType == ReplacedImageType::PNG) {
432
PNGHeaderPeek headerPeek;
433
good = vfs_->Read(openFile, &headerPeek, sizeof(headerPeek)) == sizeof(headerPeek);
434
if (good && headerPeek.IsValidPNGHeader()) {
435
level.w = headerPeek.Width();
436
level.h = headerPeek.Height();
437
good = true;
438
} else {
439
ERROR_LOG(Log::TexReplacement, "Could not get PNG dimensions: %s (zip)", filename.c_str());
440
good = false;
441
}
442
*pixelFormat = Draw::DataFormat::R8G8B8A8_UNORM;
443
} else {
444
ERROR_LOG(Log::TexReplacement, "Could not load texture replacement info: %s - unsupported format %s", filename.c_str(), magic.c_str());
445
}
446
447
// TODO: We no longer really need to have a split in this function, the upper and lower parts can be merged now.
448
449
if (good && mipLevel != 0) {
450
// If loading a low mip directly (through png most likely), check that the mipmap size is correct.
451
// Can't load mips of the wrong size.
452
if (level.w != std::max(1, (levels_[0].w >> mipLevel)) || level.h != std::max(1, (levels_[0].h >> mipLevel))) {
453
WARN_LOG(Log::TexReplacement, "Replacement mipmap invalid: size=%dx%d, expected=%dx%d (level %d)",
454
level.w, level.h, levels_[0].w >> mipLevel, levels_[0].h >> mipLevel, mipLevel);
455
good = false;
456
}
457
}
458
459
if (!good) {
460
vfs_->CloseFile(openFile);
461
return LoadLevelResult::LOAD_ERROR;
462
}
463
464
vfs_->Rewind(openFile);
465
466
level.fileRef = fileRef;
467
468
if (imageType == ReplacedImageType::KTX2) {
469
// Just slurp the whole file in one go and feed to the decoder.
470
std::vector<uint8_t> buffer;
471
buffer.resize(fileSize);
472
buffer.resize(vfs_->Read(openFile, &buffer[0], buffer.size()));
473
vfs_->CloseFile(openFile);
474
475
basist::ktx2_transcoder transcoder;
476
if (!transcoder.init(buffer.data(), (int)buffer.size())) {
477
WARN_LOG(Log::TexReplacement, "Error reading KTX file");
478
return LoadLevelResult::LOAD_ERROR;
479
}
480
481
// Figure out the target format.
482
basist::transcoder_texture_format transcoderFormat;
483
if (transcoder.is_etc1s()) {
484
// We only support opaque colors with this compression method.
485
alphaStatus_ = ReplacedTextureAlpha::FULL;
486
// Let's pick a suitable compatible format.
487
if (desc_.formatSupport.bc123) {
488
transcoderFormat = basist::transcoder_texture_format::cTFBC1;
489
*pixelFormat = Draw::DataFormat::BC1_RGBA_UNORM_BLOCK;
490
} else if (desc_.formatSupport.etc2) {
491
transcoderFormat = basist::transcoder_texture_format::cTFETC1_RGB;
492
*pixelFormat = Draw::DataFormat::ETC2_R8G8B8_UNORM_BLOCK;
493
} else {
494
// Transcode to RGBA8 instead as a fallback. A bit slow and takes a lot of memory, but better than nothing.
495
WARN_LOG(Log::TexReplacement, "Replacement texture format not supported - transcoding to RGBA8888");
496
transcoderFormat = basist::transcoder_texture_format::cTFRGBA32;
497
*pixelFormat = Draw::DataFormat::R8G8B8A8_UNORM;
498
}
499
} else if (transcoder.is_uastc()) {
500
// TODO: Try to recover some indication of alpha from the actual data blocks.
501
alphaStatus_ = ReplacedTextureAlpha::UNKNOWN;
502
// Let's pick a suitable compatible format.
503
if (desc_.formatSupport.bc7) {
504
transcoderFormat = basist::transcoder_texture_format::cTFBC7_RGBA;
505
*pixelFormat = Draw::DataFormat::BC7_UNORM_BLOCK;
506
} else if (desc_.formatSupport.astc) {
507
transcoderFormat = basist::transcoder_texture_format::cTFASTC_4x4_RGBA;
508
*pixelFormat = Draw::DataFormat::ASTC_4x4_UNORM_BLOCK;
509
} else {
510
// Transcode to RGBA8 instead as a fallback. A bit slow and takes a lot of memory, but better than nothing.
511
WARN_LOG(Log::TexReplacement, "Replacement texture format not supported - transcoding to RGBA8888");
512
transcoderFormat = basist::transcoder_texture_format::cTFRGBA32;
513
*pixelFormat = Draw::DataFormat::R8G8B8A8_UNORM;
514
}
515
} else {
516
WARN_LOG(Log::TexReplacement, "PPSSPP currently only supports KTX for basis/UASTC textures. This may change in the future.");
517
return LoadLevelResult::LOAD_ERROR;
518
}
519
520
int blockSize = 0;
521
bool bc = Draw::DataFormatIsBlockCompressed(*pixelFormat, &blockSize);
522
_dbg_assert_(bc || *pixelFormat == Draw::DataFormat::R8G8B8A8_UNORM);
523
524
if (bc && ((level.w & 3) != 0 || (level.h & 3) != 0)) {
525
WARN_LOG(Log::TexReplacement, "Block compressed replacement texture '%s' not divisible by 4x4 (%dx%d). In D3D11 (only!) we will have to expand (potentially causing glitches).", filename.c_str(), level.w, level.h);
526
}
527
528
data_.resize(numMips);
529
530
basist::ktx2_transcoder_state transcodeState; // Each thread needs one of these.
531
532
transcoder.start_transcoding();
533
levels_.reserve(numMips);
534
for (int i = 0; i < numMips; i++) {
535
std::vector<uint8_t> &out = data_[mipLevel + i];
536
537
basist::ktx2_image_level_info levelInfo{};
538
bool result = transcoder.get_image_level_info(levelInfo, i, 0, 0);
539
_dbg_assert_(result);
540
541
size_t dataSizeBytes = levelInfo.m_total_blocks * blockSize;
542
size_t outputSize = levelInfo.m_total_blocks;
543
size_t outputPitch = levelInfo.m_num_blocks_x;
544
// Support transcoded-to-RGBA8888 images too.
545
if (!bc) {
546
dataSizeBytes = levelInfo.m_orig_width * levelInfo.m_orig_height * 4;
547
outputSize = levelInfo.m_orig_width * levelInfo.m_orig_height;
548
outputPitch = levelInfo.m_orig_width;
549
}
550
data_[i].resize(dataSizeBytes);
551
552
transcodeState.clear();
553
transcoder.transcode_image_level(i, 0, 0, &out[0], (uint32_t)outputSize, transcoderFormat, 0, (uint32_t)outputPitch, level.h, -1, -1, &transcodeState);
554
level.w = levelInfo.m_orig_width;
555
level.h = levelInfo.m_orig_height;
556
if (i != 0)
557
level.fileRef = nullptr;
558
levels_.push_back(level);
559
}
560
transcoder.clear();
561
562
return LoadLevelResult::DONE; // don't read more levels
563
} else if (imageType == ReplacedImageType::DDS) {
564
// TODO: Do better with alphaStatus, it's possible.
565
alphaStatus_ = ReplacedTextureAlpha::UNKNOWN;
566
567
DDSHeader header;
568
DDSHeaderDXT10 header10{};
569
vfs_->Read(openFile, &header, sizeof(header));
570
if (ddsDX10) {
571
vfs_->Read(openFile, &header10, sizeof(header10));
572
}
573
574
int blockSize = 0;
575
bool bc = Draw::DataFormatIsBlockCompressed(*pixelFormat, &blockSize);
576
_dbg_assert_(bc);
577
578
if (bc && ((level.w & 3) != 0 || (level.h & 3) != 0)) {
579
WARN_LOG(Log::TexReplacement, "Block compressed replacement texture '%s' not divisible by 4x4 (%dx%d). In D3D11 (only!) we will have to expand (potentially causing glitches).", filename.c_str(), level.w, level.h);
580
}
581
582
data_.resize(numMips);
583
584
// A DDS File can contain multiple mipmaps.
585
levels_.reserve(numMips);
586
for (int i = 0; i < numMips; i++) {
587
std::vector<uint8_t> &out = data_[mipLevel + i];
588
589
int bytesToRead = RoundUpTo4(level.w) * RoundUpTo4(level.h) * blockSize / 16;
590
out.resize(bytesToRead);
591
592
size_t read_bytes = vfs_->Read(openFile, &out[0], bytesToRead);
593
if (read_bytes != bytesToRead) {
594
WARN_LOG(Log::TexReplacement, "DDS: Expected %d bytes, got %d", bytesToRead, (int)read_bytes);
595
}
596
597
levels_.push_back(level);
598
level.w = std::max(level.w / 2, 1);
599
level.h = std::max(level.h / 2, 1);
600
if (i != 0)
601
level.fileRef = nullptr; // We only provide a fileref on level 0 if we have mipmaps.
602
}
603
vfs_->CloseFile(openFile);
604
605
return LoadLevelResult::DONE; // don't read more levels
606
607
} else if (imageType == ReplacedImageType::ZIM) {
608
609
auto zim = std::make_unique<uint8_t[]>(fileSize);
610
if (!zim) {
611
ERROR_LOG(Log::TexReplacement, "Failed to allocate memory for texture replacement");
612
vfs_->CloseFile(openFile);
613
return LoadLevelResult::LOAD_ERROR;
614
}
615
616
if (vfs_->Read(openFile, &zim[0], fileSize) != fileSize) {
617
ERROR_LOG(Log::TexReplacement, "Could not load texture replacement: %s - failed to read ZIM", filename.c_str());
618
vfs_->CloseFile(openFile);
619
return LoadLevelResult::LOAD_ERROR;
620
}
621
vfs_->CloseFile(openFile);
622
623
int w, h, f;
624
uint8_t *image;
625
std::vector<uint8_t> &out = data_[mipLevel];
626
// TODO: Zim files can actually hold mipmaps (although no tool has ever been made to create them :P)
627
if (LoadZIMPtr(&zim[0], fileSize, &w, &h, &f, &image)) {
628
if (w > level.w || h > level.h) {
629
ERROR_LOG(Log::TexReplacement, "Texture replacement changed since header read: %s", filename.c_str());
630
return LoadLevelResult::LOAD_ERROR;
631
}
632
633
out.resize(level.w * level.h * 4);
634
if (w == level.w) {
635
memcpy(&out[0], image, level.w * 4 * level.h);
636
} else {
637
for (int y = 0; y < h; ++y) {
638
memcpy(&out[level.w * 4 * y], image + w * 4 * y, w * 4);
639
}
640
}
641
free(image);
642
643
CheckAlphaResult res = CheckAlpha32Rect((u32 *)&out[0], level.w, w, h, 0xFF000000);
644
if (res == CHECKALPHA_ANY || mipLevel == 0) {
645
alphaStatus_ = ReplacedTextureAlpha(res);
646
}
647
levels_.push_back(level);
648
} else {
649
good = false;
650
}
651
652
return LoadLevelResult::CONTINUE;
653
654
} else if (imageType == ReplacedImageType::PNG) {
655
png_image png = {};
656
png.version = PNG_IMAGE_VERSION;
657
658
std::string pngdata;
659
pngdata.resize(fileSize);
660
pngdata.resize(vfs_->Read(openFile, &pngdata[0], fileSize));
661
vfs_->CloseFile(openFile);
662
if (!png_image_begin_read_from_memory(&png, &pngdata[0], pngdata.size())) {
663
ERROR_LOG(Log::TexReplacement, "Could not load texture replacement info: %s - %s (zip)", filename.c_str(), png.message);
664
return LoadLevelResult::LOAD_ERROR;
665
}
666
if (png.width > (uint32_t)level.w || png.height > (uint32_t)level.h) {
667
ERROR_LOG(Log::TexReplacement, "Texture replacement changed since header read: %s", filename.c_str());
668
return LoadLevelResult::LOAD_ERROR;
669
}
670
671
bool checkedAlpha = false;
672
if ((png.format & PNG_FORMAT_FLAG_ALPHA) == 0) {
673
// Well, we know for sure it doesn't have alpha.
674
if (mipLevel == 0) {
675
alphaStatus_ = ReplacedTextureAlpha::FULL;
676
}
677
checkedAlpha = true;
678
}
679
png.format = PNG_FORMAT_RGBA;
680
681
std::vector<uint8_t> &out = data_[mipLevel];
682
// TODO: Should probably try to handle out-of-memory gracefully here.
683
out.resize(level.w * level.h * 4);
684
if (!png_image_finish_read(&png, nullptr, &out[0], level.w * 4, nullptr)) {
685
ERROR_LOG(Log::TexReplacement, "Could not load texture replacement: %s - %s", filename.c_str(), png.message);
686
out.resize(0);
687
return LoadLevelResult::LOAD_ERROR;
688
}
689
png_image_free(&png);
690
691
if (!checkedAlpha) {
692
// This will only check the hashed bits.
693
CheckAlphaResult res = CheckAlpha32Rect((u32 *)&out[0], level.w, png.width, png.height, 0xFF000000);
694
if (res == CHECKALPHA_ANY || mipLevel == 0) {
695
alphaStatus_ = ReplacedTextureAlpha(res);
696
}
697
}
698
699
levels_.push_back(level);
700
return LoadLevelResult::CONTINUE;
701
} else {
702
WARN_LOG(Log::TexReplacement, "Don't know how to load this image type! %d", (int)imageType);
703
vfs_->CloseFile(openFile);
704
}
705
return LoadLevelResult::LOAD_ERROR;
706
}
707
708
bool ReplacedTexture::CopyLevelTo(int level, uint8_t *out, size_t outDataSize, int rowPitch) {
709
_assert_msg_((size_t)level < levels_.size(), "Invalid miplevel");
710
_assert_msg_(out != nullptr && rowPitch > 0, "Invalid out/pitch");
711
712
if (State() != ReplacementState::ACTIVE) {
713
WARN_LOG(Log::TexReplacement, "Init not done yet");
714
return false;
715
}
716
717
// We pad the images right here during the copy.
718
// TODO: Add support for the texture cache to scale texture coordinates instead.
719
// It already supports this for render target textures that aren't powers of 2.
720
721
int outW = levels_[level].fullW;
722
int outH = levels_[level].fullH;
723
724
// We probably could avoid this lock, but better to play it safe.
725
std::lock_guard<std::mutex> guard(lock_);
726
727
const ReplacedTextureLevel &info = levels_[level];
728
const std::vector<uint8_t> &data = data_[level];
729
730
if (data.empty()) {
731
WARN_LOG(Log::TexReplacement, "Level %d is empty", level);
732
return false;
733
}
734
735
#define PARALLEL_COPY
736
737
int blockSize;
738
if (!Draw::DataFormatIsBlockCompressed(fmt, &blockSize)) {
739
if (fmt != Draw::DataFormat::R8G8B8A8_UNORM) {
740
ERROR_LOG(Log::TexReplacement, "Unexpected linear data format");
741
return false;
742
}
743
744
if (rowPitch < info.w * 4) {
745
ERROR_LOG(Log::TexReplacement, "Replacement rowPitch=%d, but w=%d (level=%d) (too small)", rowPitch, info.w * 4, level);
746
return false;
747
}
748
749
_assert_msg_(data.size() == info.w * info.h * 4, "Data has wrong size");
750
751
if (rowPitch == info.w * 4) {
752
#ifdef PARALLEL_COPY
753
ParallelMemcpy(&g_threadManager, out, data.data(), info.w * 4 * info.h);
754
#else
755
memcpy(out, data.data(), info.w * 4 * info.h);
756
#endif
757
} else {
758
#ifdef PARALLEL_COPY
759
const int MIN_LINES_PER_THREAD = 4;
760
ParallelRangeLoop(&g_threadManager, [&](int l, int h) {
761
int extraPixels = outW - info.w;
762
for (int y = l; y < h; ++y) {
763
memcpy((uint8_t *)out + rowPitch * y, data.data() + info.w * 4 * y, info.w * 4);
764
// Fill the rest of the line with black.
765
memset((uint8_t *)out + rowPitch * y + info.w * 4, 0, extraPixels * 4);
766
}
767
}, 0, info.h, MIN_LINES_PER_THREAD);
768
#else
769
int extraPixels = outW - info.w;
770
for (int y = 0; y < info.h; ++y) {
771
memcpy((uint8_t *)out + rowPitch * y, data.data() + info.w * 4 * y, info.w * 4);
772
memset((uint8_t *)out + rowPitch * y + info.w * 4, 0, extraPixels * 4);
773
}
774
#endif
775
// Memset the rest of the padding to avoid leaky edge pixels. Guess we could parallelize this too, but meh.
776
for (int y = info.h; y < outH; y++) {
777
uint8_t *dest = (uint8_t *)out + rowPitch * y;
778
memset(dest, 0, outW * 4);
779
}
780
}
781
} else {
782
#ifdef PARALLEL_COPY
783
// Only parallel copy in the simple case for now.
784
if (info.w == outW && info.h == outH) {
785
// TODO: Add sanity checks here for other formats?
786
ParallelMemcpy(&g_threadManager, out, data.data(), data.size());
787
return true;
788
}
789
#endif
790
// Alright, so careful copying of blocks it is, padding with zero-blocks as needed.
791
int inBlocksW = (info.w + 3) / 4;
792
int inBlocksH = (info.h + 3) / 4;
793
int outBlocksW = (info.fullW + 3) / 4;
794
int outBlocksH = (info.fullH + 3) / 4;
795
796
int paddingBlocksX = outBlocksW - inBlocksW;
797
798
// Copy all the known blocks, and zero-fill out the lines.
799
for (int y = 0; y < inBlocksH; y++) {
800
const uint8_t *input = data.data() + y * inBlocksW * blockSize;
801
uint8_t *output = (uint8_t *)out + y * outBlocksW * blockSize;
802
memcpy(output, input, inBlocksW * blockSize);
803
memset(output + inBlocksW * blockSize, 0, paddingBlocksX * blockSize);
804
}
805
806
// Vertical zero-padding.
807
for (int y = inBlocksH; y < outBlocksH; y++) {
808
uint8_t *output = (uint8_t *)out + y * outBlocksW * blockSize;
809
memset(output, 0, outBlocksW * blockSize);
810
}
811
}
812
813
return true;
814
}
815
816
const char *StateString(ReplacementState state) {
817
switch (state) {
818
case ReplacementState::UNLOADED: return "UNLOADED";
819
case ReplacementState::PENDING: return "PENDING";
820
case ReplacementState::NOT_FOUND: return "NOT_FOUND";
821
case ReplacementState::ACTIVE: return "ACTIVE";
822
case ReplacementState::CANCEL_INIT: return "CANCEL_INIT";
823
default: return "N/A";
824
}
825
}
826
827