From 4ba200147962f37d379de283671881e6d663d2a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Thu, 9 Mar 2023 00:01:38 +0100 Subject: [PATCH] Replacer: Make the cache data model texture-centric instead of level-centric --- Core/TextureReplacer.cpp | 155 +++++++++++++++++++----------- Core/TextureReplacer.h | 67 +++---------- GPU/Common/TextureCacheCommon.cpp | 2 +- GPU/Vulkan/TextureCacheVulkan.cpp | 14 ++- 4 files changed, 121 insertions(+), 117 deletions(-) diff --git a/Core/TextureReplacer.cpp b/Core/TextureReplacer.cpp index 42c58460d5..2c2022a0ce 100644 --- a/Core/TextureReplacer.cpp +++ b/Core/TextureReplacer.cpp @@ -243,10 +243,14 @@ bool TextureReplacer::LoadIniValues(IniFile &ini, bool isOverride) { auto hashes = ini.GetOrCreateSection("hashes")->ToMap(); // Format: hashname = filename.png bool checkFilenames = g_Config.bSaveNewTextures && !g_Config.bIgnoreTextureFilenames; + + std::map> filenameMap; + for (const auto &item : hashes) { - ReplacementAliasKey key(0, 0, 0); - if (sscanf(item.first.c_str(), "%16llx%8x_%d", &key.cachekey, &key.hash, &key.level) >= 1) { - aliases_[key] = item.second; + ReplacementCacheKey key(0, 0); + int level = 0; // sscanf might fail to pluck the level, but that's ok, we default to 0. + if (sscanf(item.first.c_str(), "%16llx%8x_%d", &key.cachekey, &key.hash, &level) >= 1) { + filenameMap[key][level] = item.second; if (checkFilenames) { #if PPSSPP_PLATFORM(WINDOWS) // Uppercase probably means the filenames don't match. @@ -260,11 +264,30 @@ bool TextureReplacer::LoadIniValues(IniFile &ini, bool isOverride) { ERROR_LOG(G3D, "Unsupported syntax under [hashes]: %s", item.first.c_str()); } } + + // Now, translate the filenameMap to the final aliasMap. + for (auto &pair : filenameMap) { + std::string alias; + int mipIndex = 0; + for (auto &level : pair.second) { + if (level.first == mipIndex) { + alias += level.second + "|"; + mipIndex++; + } else { + WARN_LOG(G3D, "Non-sequential mip index %d, breaking", level.first); + break; + } + } + if (alias == "|") { + alias = ""; // marker for no replacement + } + aliases_[pair.first] = alias; + } } if (filenameWarning) { auto err = GetI18NCategory("Error"); - host->NotifyUserMessage(err->T("textures.ini filenames may not be cross-platform"), 6.0f); + host->NotifyUserMessage(err->T("textures.ini filenames may not be cross-platform (banned characters)"), 6.0f); } if (ini.HasSection("hashranges")) { @@ -475,7 +498,7 @@ ReplacedTexture *TextureReplacer::FindReplacement(u64 cachekey, u32 hash, int w, return result; } -void TextureReplacer::PopulateReplacement(ReplacedTexture *result, u64 cachekey, u32 hash, int w, int h) { +void TextureReplacer::PopulateReplacement(ReplacedTexture *texture, u64 cachekey, u32 hash, int w, int h) { int newW = w; int newH = h; LookupHashRange(cachekey >> 32, newW, newH); @@ -484,30 +507,43 @@ void TextureReplacer::PopulateReplacement(ReplacedTexture *result, u64 cachekey, cachekey = cachekey & 0xFFFFFFFFULL; } - for (int i = 0; i < MAX_MIP_LEVELS; ++i) { - const std::string hashfile = LookupHashFile(cachekey, hash, i); - if (hashfile.empty()) { + bool foundReplacement = false; + const std::string hashfiles = LookupHashFile(cachekey, hash, &foundReplacement); + + if (!foundReplacement) { + // nothing to do? + return; + } + + INFO_LOG(G3D, "Found: %s", hashfiles.c_str()); + + std::vector filenames; + SplitString(hashfiles, '|', filenames); + + for (int i = 0; i < std::min(MAX_MIP_LEVELS, (int)filenames.size()); ++i) { + if (filenames[i].empty()) { // Out of valid mip levels. Bail out. break; } - const Path filename = basePath_ / hashfile; + const Path filename = basePath_ / filenames[i]; + // TODO: Here, if we find a file with multiple built-in mipmap levels, + // we'll have to change a bit how things work... ReplacedTextureLevel level; level.fmt = Draw::DataFormat::R8G8B8A8_UNORM; level.file = filename; bool good; - bool logError = hashfile != HashName(cachekey, hash, i) + ".png"; - VFSFileReference *fileRef = vfs_->GetFile(hashfile.c_str()); + VFSFileReference *fileRef = vfs_->GetFile(filenames[i].c_str()); if (!fileRef) { // If the file doesn't exist, let's just bail immediately here. break; } level.fileRef = fileRef; - good = PopulateLevel(level, !logError); + good = PopulateLevel(level, false); // We pad files that have been hashrange'd so they are the same texture size. level.w = (level.w * w) / newW; @@ -515,26 +551,22 @@ void TextureReplacer::PopulateReplacement(ReplacedTexture *result, u64 cachekey, if (good && i != 0) { // Check that the mipmap size is correct. Can't load mips of the wrong size. - if (level.w != (result->levels_[0].w >> i) || level.h != (result->levels_[0].h >> i)) { - WARN_LOG(G3D, "Replacement mipmap invalid: size=%dx%d, expected=%dx%d (level %d, '%s')", level.w, level.h, result->levels_[0].w >> i, result->levels_[0].h >> i, i, filename.c_str()); + if (level.w != (texture->levels_[0].w >> i) || level.h != (texture->levels_[0].h >> i)) { + WARN_LOG(G3D, "Replacement mipmap invalid: size=%dx%d, expected=%dx%d (level %d, '%s')", level.w, level.h, texture->levels_[0].w >> i, texture->levels_[0].h >> i, i, filename.c_str()); good = false; } } if (good) - result->levels_.push_back(level); + texture->levels_.push_back(level); // Otherwise, we're done loading mips (bad PNG or bad size, either way.) else break; } - // Populate the level data pointers for each level. - result->levelData_.resize(result->levels_.size()); - for (size_t i = 0; i < result->levels_.size(); ++i) { - result->levelData_[i] = &levelCache_[result->levels_[i]]; - } - - result->prepareDone_ = true; + // Populate the data pointer. + texture->levelData_ = &levelCache_[hashfiles]; + texture->prepareDone_ = true; } bool TextureReplacer::PopulateLevel(ReplacedTextureLevel &level, bool ignoreError) { @@ -607,7 +639,7 @@ static bool WriteTextureToPNG(png_imagep image, const Path &filename, int conver class TextureSaveTask : public Task { public: // Could probably just use a vector. - SimpleBuf data; + std::vector rgbaData; int w = 0; int h = 0; @@ -619,7 +651,7 @@ public: bool skipIfExists = false; - TextureSaveTask(SimpleBuf _data) : data(std::move(_data)) {} + TextureSaveTask(std::vector _rgbaData) : rgbaData(std::move(_rgbaData)) {} // This must be IO blocking because of Android storage, despite being CPU heavy. TaskType Type() const override { return TaskType::IO_BLOCKING; } @@ -661,7 +693,7 @@ public: png.format = PNG_FORMAT_RGBA; png.width = w; png.height = h; - bool success = WriteTextureToPNG(&png, saveFilename, 0, data.data(), pitch, nullptr); + bool success = WriteTextureToPNG(&png, saveFilename, 0, rgbaData.data(), pitch, nullptr); png_image_free(&png); if (png.warning_or_error >= 2) { ERROR_LOG(COMMON, "Saving screenshot to PNG produced errors."); @@ -699,7 +731,9 @@ void TextureReplacer::NotifyTextureDecoded(const ReplacedTextureDecodeInfo &repl cachekey = cachekey & 0xFFFFFFFFULL; } - std::string hashfile = LookupHashFile(cachekey, replacedInfo.hash, level); + /* + bool found = false; + std::string hashfile = LookupHashFile(cachekey, replacedInfo.hash, &found); const Path filename = basePath_ / hashfile; // If it's empty, it's an ignored hash, we intentionally don't save. @@ -732,11 +766,11 @@ void TextureReplacer::NotifyTextureDecoded(const ReplacedTextureDecodeInfo &repl h = lookupH * replacedInfo.scaleFactor; } - SimpleBuf saveBuf; + std::vector saveBuf; // Copy data to a buffer so we can send it to the thread. Might as well compact-away the pitch // while we're at it. - saveBuf.resize(w * h); + saveBuf.resize(w * h * 4); for (int y = 0; y < h; y++) { memcpy((u8 *)saveBuf.data() + y * w * 4, (const u8 *)data + y * pitch, w * sizeof(u32)); } @@ -761,6 +795,7 @@ void TextureReplacer::NotifyTextureDecoded(const ReplacedTextureDecodeInfo &repl saved.w = w; saved.h = h; savedCache_[replacementKey] = std::make_pair(saved, now); + */ } void TextureReplacer::Decimate(ReplacerDecimateMode mode) { @@ -860,15 +895,16 @@ bool TextureReplacer::FindFiltering(u64 cachekey, u32 hash, TextureFiltering *fo return false; } -std::string TextureReplacer::LookupHashFile(u64 cachekey, u32 hash, int level) { - ReplacementAliasKey key(cachekey, hash, level); +std::string TextureReplacer::LookupHashFile(u64 cachekey, u32 hash, bool *foundReplacement) { + ReplacementCacheKey key(cachekey, hash); auto alias = LookupWildcard(aliases_, key, cachekey, hash, ignoreAddress_); if (alias != aliases_.end()) { // Note: this will be blank if explicitly ignored. + *foundReplacement = alias->second.size() > 0; return alias->second; } - - return HashName(cachekey, hash, level) + ".png"; + *foundReplacement = false; + return ""; } std::string TextureReplacer::HashName(u64 cachekey, u32 hash, int level) { @@ -938,11 +974,12 @@ bool ReplacedTexture::IsReady(double budget) { } // Loaded already, or not yet on a thread? - if (initDone_ && !levelData_.empty()) { - for (auto &l : levelData_) - l->lastUsed = lastUsed_; + if (initDone_ && levelData_ && !levelData_->data.empty()) { + // TODO: lock? + levelData_->lastUsed = lastUsed_; return true; } + // Let's not even start a new texture if we're already behind. if (budget < 0.0) return false; @@ -957,7 +994,7 @@ bool ReplacedTexture::IsReady(double budget) { if (threadWaitable_->WaitFor(budget)) { // If we finished all the levels, we're done. - return initDone_ && !levelData_.empty(); + return initDone_ && levelData_ != nullptr && !levelData_->data.empty(); } } else { Prepare(vfs_); @@ -990,13 +1027,18 @@ void ReplacedTexture::Prepare(VFSBackend *vfs) { void ReplacedTexture::PrepareData(int level) { _assert_msg_((size_t)level < levels_.size(), "Invalid miplevel"); - _assert_msg_(levelData_[level] != nullptr, "Level cache not set for miplevel"); + _assert_msg_(levelData_ != nullptr, "Level cache not set"); // We must lock around access to levelData_ in case two textures try to load it at once. - std::lock_guard guard(levelData_[level]->lock); + std::lock_guard guard(levelData_->lock); const ReplacedTextureLevel &info = levels_[level]; - std::vector &out = levelData_[level]->data; + + if (levelData_->data.size() <= level) { + levelData_->data.resize(level + 1); + } + + std::vector &out = levelData_->data[level]; // Already populated from cache. if (!out.empty()) @@ -1107,14 +1149,12 @@ void ReplacedTexture::PurgeIfOlder(double t) { if (lastUsed_ >= t) return; - for (auto &l : levelData_) { - if (l->lastUsed < t) { - // We have to lock since multiple textures might reference this same data. - std::lock_guard guard(l->lock); - l->data.clear(); - // This means we have to reload. If we never purge any, there's no need. - initDone_ = false; - } + if (levelData_->lastUsed < t) { + // We have to lock since multiple textures might reference this same data. + std::lock_guard guard(levelData_->lock); + levelData_->data.clear(); + // This means we have to reload. If we never purge any, there's no need. + initDone_ = false; } } @@ -1128,28 +1168,28 @@ ReplacedTexture::~ReplacedTexture() { } } -bool ReplacedTexture::Load(int level, void *out, int rowPitch) { +bool ReplacedTexture::CopyLevelTo(int level, void *out, int rowPitch) { _assert_msg_((size_t)level < levels_.size(), "Invalid miplevel"); _assert_msg_(out != nullptr && rowPitch > 0, "Invalid out/pitch"); - if (!initDone_) + if (!initDone_) { + WARN_LOG(G3D, "Init not done yet"); return false; - if (levelData_.empty()) - return false; - - _assert_msg_(levelData_[level] != nullptr, "Level cache not set for miplevel"); + } // We probably could avoid this lock, but better to play it safe. - std::lock_guard guard(levelData_[level]->lock); + std::lock_guard guard(levelData_->lock); const ReplacedTextureLevel &info = levels_[level]; - const std::vector &data = levelData_[level]->data; + const std::vector &data = levelData_->data[level]; - if (data.empty()) + if (data.empty()) { + WARN_LOG(G3D, "Level %d is empty", level); return false; + } if (rowPitch < info.w * 4) { - ERROR_LOG_REPORT(G3D, "Replacement rowPitch=%d, but w=%d (level=%d)", rowPitch, info.w * 4, level); + ERROR_LOG(G3D, "Replacement rowPitch=%d, but w=%d (level=%d)", rowPitch, info.w * 4, level); return false; } _assert_msg_(data.size() == info.w * info.h * 4, "Data has wrong size"); @@ -1165,6 +1205,7 @@ bool ReplacedTexture::Load(int level, void *out, int rowPitch) { }, 0, info.h, MIN_LINES_PER_THREAD); } + INFO_LOG(G3D, "Successfully copied texture level"); return true; } diff --git a/Core/TextureReplacer.h b/Core/TextureReplacer.h index 0b4633e05f..880b3d1d7e 100644 --- a/Core/TextureReplacer.h +++ b/Core/TextureReplacer.h @@ -46,13 +46,14 @@ enum class ReplacedTextureAlpha { FULL = 0x00, }; -// For forward comatibility, we specify the hash. +// For forward compatibility, we specify the hash. enum class ReplacedTextureHash { QUICK, XXH32, XXH64, }; +// Metadata about a given texture level. struct ReplacedTextureLevel { ReplacedTextureLevel() {} int w = 0; @@ -69,25 +70,9 @@ struct ReplacedTextureLevel { } }; -namespace std { - template <> - struct hash { - std::size_t operator()(const ReplacedTextureLevel &k) const { -#if PPSSPP_ARCH(64BIT) - uint64_t v = (uint64_t)k.w | ((uint64_t)k.h << 32); - v = __rotl64(v ^ (uint64_t)k.fmt, 13); -#else - uint32_t v = k.w ^ (uint32_t)k.fmt; - v = __rotl(__rotl(v, 13) ^ k.h, 13); -#endif - return v ^ hash()(k.file.ToString()); - } - }; -} - -struct ReplacedLevelCache { +struct ReplacedLevelsCache { std::mutex lock; - std::vector data; + std::vector> data; double lastUsed = 0.0; }; @@ -109,30 +94,6 @@ struct ReplacementCacheKey { } }; -struct ReplacementAliasKey { - u64 cachekey; - union { - u64 hashAndLevel; - struct { - u32 level; - u32 hash; - }; - }; - - ReplacementAliasKey(u64 c, u32 h, u32 l) : cachekey(c), level(l), hash(h) { } - - bool operator ==(const ReplacementAliasKey &k) const { - return k.cachekey == cachekey && k.hashAndLevel == hashAndLevel; - } - - bool operator <(const ReplacementAliasKey &k) const { - if (k.cachekey == cachekey) { - return k.hashAndLevel < hashAndLevel; - } - return k.cachekey < cachekey; - } -}; - namespace std { template <> struct hash { @@ -140,13 +101,6 @@ namespace std { return std::hash()(k.cachekey ^ ((u64)k.hash << 32)); } }; - - template <> - struct hash { - size_t operator()(const ReplacementAliasKey &k) const { - return std::hash()(k.cachekey ^ k.hashAndLevel); - } - }; } struct ReplacedTexture { @@ -196,7 +150,7 @@ struct ReplacedTexture { bool IsReady(double budget); - bool Load(int level, void *out, int rowPitch); + bool CopyLevelTo(int level, void *out, int rowPitch); protected: void Prepare(VFSBackend *vfs); @@ -204,7 +158,8 @@ protected: void PurgeIfOlder(double t); std::vector levels_; - std::vector levelData_; + ReplacedLevelsCache *levelData_; + ReplacedTextureAlpha alphaStatus_ = ReplacedTextureAlpha::UNKNOWN; double lastUsed_ = 0.0; LimitedWaitable *threadWaitable_ = nullptr; @@ -273,7 +228,7 @@ protected: void ParseReduceHashRange(const std::string& key, const std::string& value); bool LookupHashRange(u32 addr, int &w, int &h); float LookupReduceHashRange(int& w, int& h); - std::string LookupHashFile(u64 cachekey, u32 hash, int level); + std::string LookupHashFile(u64 cachekey, u32 hash, bool *foundReplacement); std::string HashName(u64 cachekey, u32 hash, int level); void PopulateReplacement(ReplacedTexture *result, u64 cachekey, u32 hash, int w, int h); bool PopulateLevel(ReplacedTextureLevel &level, bool ignoreError); @@ -297,10 +252,12 @@ protected: typedef std::pair WidthHeightPair; std::unordered_map hashranges_; std::unordered_map reducehashranges_; - std::unordered_map aliases_; + std::unordered_map aliases_; std::unordered_map filtering_; std::unordered_map cache_; std::unordered_map> savedCache_; - std::unordered_map levelCache_; + + // the key is from aliases_. It's a |-separated sequence of texture filenames of the levels of a texture. + std::unordered_map levelCache_; }; diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index 7a35252f36..9fe735487c 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -2854,7 +2854,7 @@ void TextureCacheCommon::LoadTextureLevel(TexCacheEntry &entry, uint8_t *data, i if (plan.replaceValid && plan.replaced->GetSize(srcLevel, w, h)) { double replaceStart = time_now_d(); - plan.replaced->Load(srcLevel, data, stride); + plan.replaced->CopyLevelTo(srcLevel, data, stride); replacementTimeThisFrame_ += time_now_d() - replaceStart; } else { GETextureFormat tfmt = (GETextureFormat)entry.format; diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index 6c898b5579..83bd9bc520 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -532,6 +532,8 @@ void TextureCacheVulkan::BuildTexture(TexCacheEntry *const entry) { levels = plan.levelsToLoad; } + VulkanPushBuffer *pushBuffer = drawEngine_->GetPushBufferForTextureData(); + for (int i = 0; i < levels; i++) { int mipUnscaledWidth = gstate.getTextureWidth(i); int mipUnscaledHeight = gstate.getTextureHeight(i); @@ -553,24 +555,28 @@ void TextureCacheVulkan::BuildTexture(TexCacheEntry *const entry) { void *data; std::vector saveData; + // Simple wrapper to avoid reading back from VRAM (very, very expensive). auto loadLevel = [&](int sz, int srcLevel, int lstride, int lfactor) { if (plan.saveTexture) { saveData.resize(sz); data = &saveData[0]; } else { - data = drawEngine_->GetPushBufferForTextureData()->PushAligned(sz, &bufferOffset, &texBuf, pushAlignment); + data = pushBuffer->PushAligned(sz, &bufferOffset, &texBuf, pushAlignment); } LoadVulkanTextureLevel(*entry, (uint8_t *)data, lstride, srcLevel, lfactor, actualFmt); if (plan.saveTexture) - bufferOffset = drawEngine_->GetPushBufferForTextureData()->PushAligned(&saveData[0], sz, pushAlignment, &texBuf); + bufferOffset = pushBuffer->PushAligned(&saveData[0], sz, pushAlignment, &texBuf); }; bool dataScaled = true; if (plan.replaceValid) { // Directly load the replaced image. - data = drawEngine_->GetPushBufferForTextureData()->PushAligned(uploadSize, &bufferOffset, &texBuf, pushAlignment); + data = pushBuffer->PushAligned(uploadSize, &bufferOffset, &texBuf, pushAlignment); double replaceStart = time_now_d(); - plan.replaced->Load(plan.baseLevelSrc + i, data, byteStride); // if it fails, it'll just be garbage data... OK for now. + if (!plan.replaced->CopyLevelTo(plan.baseLevelSrc + i, data, byteStride)) { // If plan.replaceValid, this shouldn't fail. + WARN_LOG(G3D, "Failed to copy replaced texture level"); + // TODO: Fill with some pattern? + } replacementTimeThisFrame_ += time_now_d() - replaceStart; VK_PROFILE_BEGIN(vulkan, cmdInit, VK_PIPELINE_STAGE_TRANSFER_BIT, "Copy Upload (replaced): %dx%d", mipWidth, mipHeight);