ST_engine  0.3-ALPHA
font_cache.cpp
1 /* This file is part of the "ST" project.
2  * You may use, distribute or modify this code under the terms
3  * of the GNU General Public License version 2.
4  * See LICENCE.txt in the root directory of the project.
5  *
6  * Author: Maxim Atanasov
7  * E-mail: maxim.atanasov@protonmail.com
8  */
9 
10 #include "font_cache.hpp"
11 
12 static uint32_t entries = 0;
13 static cache_list cache;
14 static cache_hash hash;
15 static uint32_t cache_size = 0;
16 
22 void ST::renderer_sdl::font_cache::move_to_front(std::list<key_pair> &list, std::list<key_pair>::iterator element) {
23  if (element != list.begin()) {
24  list.splice(list.begin(), list, element, std::next(element));
25  }
26 }
27 
32 void ST::renderer_sdl::font_cache::set_max(uint32_t max) {
33  cache_size = max;
34 }
35 
42 SDL_Texture *ST::renderer_sdl::font_cache::get_cached_string(const std::string &str, uint16_t font) {
43  font_cache_tuple temp = std::make_tuple(str, font);
44  if (hash.find(temp) != hash.end()) {
45  move_to_front(cache, hash[temp]);
46  return hash.at(temp)->second;;
47  }
48  return nullptr;
49 }
50 
58 void ST::renderer_sdl::font_cache::cache_string(const std::string &str, SDL_Texture *texture, uint16_t font) {
59  font_cache_tuple temp = std::make_tuple(str, font);
60  cache.push_front(std::make_pair(temp, texture));
61  hash[temp] = cache.begin();
62  entries++;
63  if (entries > cache_size) {
64  hash.erase(cache.back().first);
65  SDL_DestroyTexture(cache.back().second);
66  cache.pop_back();
67  entries--;
68  }
69 }
70 
74 void ST::renderer_sdl::font_cache::close() {
75  for (auto &i: cache) {
76  SDL_DestroyTexture(i.second);
77  }
78 }
79 
80 void ST::renderer_sdl::font_cache::clear() {
81  cache.clear();
82  hash.clear();
83 }