From 875d3d2bcf2a0d4e7e3093ca051a056ecb4ba8d1 Mon Sep 17 00:00:00 2001 From: scawful Date: Wed, 16 Apr 2025 22:35:42 -0400 Subject: [PATCH] Introduce TexturePool for efficient texture reuse. --- src/app/gfx/texture_pool.h | 65 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 src/app/gfx/texture_pool.h diff --git a/src/app/gfx/texture_pool.h b/src/app/gfx/texture_pool.h new file mode 100644 index 00000000..d0289a88 --- /dev/null +++ b/src/app/gfx/texture_pool.h @@ -0,0 +1,65 @@ +#ifndef YAZE_APP_GFX_TEXTURE_POOL_H +#define YAZE_APP_GFX_TEXTURE_POOL_H + +#include +#include +#include +#include +#include +#include "app/core/platform/sdl_deleter.h" + +namespace yaze { +namespace gfx { + +class TexturePool { +public: + static TexturePool& GetInstance() { + static TexturePool instance; + return instance; + } + + SDL_Texture* GetTexture(SDL_Renderer* renderer, int width, int height, Uint32 format) { + std::string key = GenerateKey(width, height, format); + + // Check if we have a suitable texture in the pool + auto it = available_textures_.find(key); + if (it != available_textures_.end() && !it->second.empty()) { + SDL_Texture* texture = it->second.back(); + it->second.pop_back(); + return texture; + } + + // Create a new texture + return SDL_CreateTexture(renderer, format, SDL_TEXTUREACCESS_STREAMING, width, height); + } + + void ReturnTexture(SDL_Texture* texture, int width, int height, Uint32 format) { + if (!texture) return; + + std::string key = GenerateKey(width, height, format); + available_textures_[key].push_back(texture); + } + + void Clear() { + for (auto& pair : available_textures_) { + for (SDL_Texture* texture : pair.second) { + SDL_DestroyTexture(texture); + } + } + available_textures_.clear(); + } + +private: + TexturePool() = default; + + std::string GenerateKey(int width, int height, Uint32 format) { + return std::to_string(width) + "x" + std::to_string(height) + "_" + std::to_string(format); + } + + std::unordered_map> available_textures_; +}; + +} // namespace gfx +} // namespace yaze + +#endif // YAZE_APP_GFX_TEXTURE_POOL_H