The Battle for Wesnoth  1.19.10+dev
picture.cpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2003 - 2025
3  by David White <dave@whitevine.net>
4  Part of the Battle for Wesnoth Project https://www.wesnoth.org/
5 
6  This program is free software; you can redistribute it and/or modify
7  it under the terms of the GNU General Public License as published by
8  the Free Software Foundation; either version 2 of the License, or
9  (at your option) any later version.
10  This program is distributed in the hope that it will be useful,
11  but WITHOUT ANY WARRANTY.
12 
13  See the COPYING file for more details.
14 */
15 
16 /**
17  * @file
18  * Routines for images: load, scale, re-color, etc.
19  */
20 
21 #include "picture.hpp"
22 
23 #include "filesystem.hpp"
24 #include "game_config.hpp"
25 #include "image_modifications.hpp"
26 #include "log.hpp"
27 #include "serialization/base64.hpp"
29 #include "sdl/rect.hpp"
30 #include "sdl/texture.hpp"
31 
32 #include <SDL2/SDL_image.h>
33 
34 
35 #include <boost/algorithm/string.hpp>
36 
37 #include <array>
38 #include <set>
39 
40 static lg::log_domain log_image("image");
41 #define ERR_IMG LOG_STREAM(err, log_image)
42 #define WRN_IMG LOG_STREAM(warn, log_image)
43 #define LOG_IMG LOG_STREAM(info, log_image)
44 #define DBG_IMG LOG_STREAM(debug, log_image)
45 
46 static lg::log_domain log_config("config");
47 #define ERR_CFG LOG_STREAM(err, log_config)
48 
50 
51 template<>
52 struct std::hash<image::locator>
53 {
54  std::size_t operator()(const image::locator& val) const
55  {
56  std::size_t hash = std::hash<unsigned>{}(val.type_);
57 
59  boost::hash_combine(hash, val.filename_);
60  }
61 
62  if(val.type_ == image::locator::SUB_FILE) {
63  boost::hash_combine(hash, val.loc_.x);
64  boost::hash_combine(hash, val.loc_.y);
65  boost::hash_combine(hash, val.center_x_);
66  boost::hash_combine(hash, val.center_y_);
67  boost::hash_combine(hash, val.modifications_);
68  }
69 
70  return hash;
71  }
72 };
73 
74 namespace image
75 {
76 template<typename T>
78 {
79 public:
80  bool in_cache(const locator& item) const
81  {
82  return content_.find(item) != content_.end(); // TODO C++20: use content_.contains()
83  }
84 
85  /** Returns a pointer to the cached value, or nullptr if not found. */
86  const T* locate_in_cache(const locator& item) const
87  {
88  if(auto iter = content_.find(item); iter != content_.end()) {
89  return &iter->second;
90  } else {
91  return nullptr;
92  }
93  }
94 
95  /**
96  * Returns a reference to the cache item associated with the given key.
97  * If no corresponding value is found, a default instance will be created.
98  */
99  T& access_in_cache(const locator& item)
100  {
101  return content_[item];
102  }
103 
104  void add_to_cache(const locator& item, T data)
105  {
106  content_.insert_or_assign(item, std::move(data));
107  }
108 
109  void flush()
110  {
111  content_.clear();
112  }
113 
114 private:
115  std::unordered_map<locator, T> content_;
116 };
117 
118 namespace
119 {
120 using surface_cache = cache_type<surface>;
121 using texture_cache = cache_type<texture>;
122 using bool_cache = cache_type<bool>;
123 
124 /** Type used to pair light possibilities with the corresponding lit surface. */
125 using lit_surface_variants = std::map<light_string, surface>;
126 using lit_texture_variants = std::map<light_string, texture>;
127 
128 /** Lit variants for each locator. */
129 using lit_surface_cache = cache_type<lit_surface_variants>;
130 using lit_texture_cache = cache_type<lit_texture_variants>;
131 
132 /** Definition of all image maps */
133 std::array<surface_cache, NUM_TYPES> surfaces_;
134 
135 /**
136  * Texture caches.
137  * Note that the latter two are temporary and should be removed once we have OGL and shader support.
138  */
139 using texture_cache_map = std::map<image::scale_quality, image::texture_cache>;
140 
141 texture_cache_map textures_;
142 texture_cache_map textures_hexed_;
143 texture_cache_map texture_tod_colored_;
144 
145 // cache storing if each image fit in a hex
146 image::bool_cache in_hex_info_;
147 
148 // cache storing if this is an empty hex
149 image::bool_cache is_empty_hex_;
150 
151 // caches storing the different lighted cases for each image
152 image::lit_surface_cache lit_surfaces_;
153 image::lit_texture_cache lit_textures_;
154 // caches storing each lightmap generated
155 image::lit_surface_variants surface_lightmaps_;
156 image::lit_texture_variants texture_lightmaps_;
157 
158 // diagnostics for tracking skipped cache impact
159 std::array<bool_cache, NUM_TYPES> skipped_cache_;
160 int duplicate_loads_ = 0;
161 int total_loads_ = 0;
162 
163 // const int cache_version_ = 0;
164 
165 std::map<std::string, bool> image_existence_map;
166 
167 // directories where we already cached file existence
168 std::set<std::string> precached_dirs;
169 
170 int red_adjust = 0, green_adjust = 0, blue_adjust = 0;
171 
172 const std::string data_uri_prefix = "data:";
173 struct parsed_data_URI{
174  explicit parsed_data_URI(std::string_view data_URI);
175  std::string_view scheme;
176  std::string_view mime;
177  std::string_view base64;
178  std::string_view data;
179  bool good;
180 };
181 parsed_data_URI::parsed_data_URI(std::string_view data_URI)
182 {
183  const std::size_t colon = data_URI.find(':');
184  const std::string_view after_scheme = data_URI.substr(colon + 1);
185 
186  const std::size_t comma = after_scheme.find(',');
187  const std::string_view type_info = after_scheme.substr(0, comma);
188 
189  const std::size_t semicolon = type_info.find(';');
190 
191  scheme = data_URI.substr(0, colon);
192  base64 = type_info.substr(semicolon + 1);
193  mime = type_info.substr(0, semicolon);
194  data = after_scheme.substr(comma + 1);
195  good = (scheme == "data" && base64 == "base64" && mime.length() > 0 && data.length() > 0);
196 }
197 
198 } // end anon namespace
199 
201 {
202  for(surface_cache& cache : surfaces_) {
203  cache.flush();
204  }
205  lit_surfaces_.flush();
206  lit_textures_.flush();
207  surface_lightmaps_.clear();
208  texture_lightmaps_.clear();
209  in_hex_info_.flush();
210  is_empty_hex_.flush();
211  textures_.clear();
212  textures_hexed_.clear();
213  texture_tod_colored_.clear();
214  image_existence_map.clear();
215  precached_dirs.clear();
216 }
217 
218 locator locator::clone(const std::string& mods) const
219 {
220  locator res = *this;
221  if(!mods.empty()) {
222  res.modifications_ += mods;
223  res.type_ = SUB_FILE;
224  }
225 
226  return res;
227 }
228 
229 std::ostream& operator<<(std::ostream& s, const locator& l)
230 {
231  s << l.get_filename();
232  if(!l.get_modifications().empty()) {
233  if(l.get_modifications()[0] != '~') {
234  s << '~';
235  }
236  s << l.get_modifications();
237  }
238  return s;
239 }
240 
241 locator::locator(const std::string& fn)
242  : filename_(fn)
243 {
244  if(filename_.empty()) {
245  return;
246  }
247 
248  if(boost::algorithm::starts_with(filename_, data_uri_prefix)) {
249  if(parsed_data_URI parsed{ filename_ }; !parsed.good) {
250  std::string_view view{ filename_ };
251  std::string_view stripped = view.substr(0, view.find(","));
252  ERR_IMG << "Invalid data URI: " << stripped;
253  }
254 
255  is_data_uri_ = true;
256  }
257 
258  if(const std::size_t markup_field = filename_.find('~'); markup_field != std::string::npos) {
259  type_ = SUB_FILE;
260  modifications_ = filename_.substr(markup_field, filename_.size() - markup_field);
261  filename_ = filename_.substr(0, markup_field);
262  } else {
263  type_ = FILE;
264  }
265 }
266 
267 locator::locator(const std::string& filename, const std::string& modifications)
268  : type_(SUB_FILE)
270  , modifications_(modifications)
271 {
272 }
273 
275  const std::string& filename,
276  const map_location& loc,
277  int center_x,
278  int center_y,
279  const std::string& modifications)
280  : type_(SUB_FILE)
282  , modifications_(modifications)
283  , loc_(loc)
284  , center_x_(center_x)
285  , center_y_(center_y)
286 {
287 }
288 
289 bool locator::operator==(const locator& a) const
290 {
291  if(a.type_ != type_) {
292  return false;
293  } else if(type_ == FILE) {
294  return filename_ == a.filename_;
295  } else if(type_ == SUB_FILE) {
296  return std::tie(filename_, loc_, modifications_, center_x_, center_y_) ==
297  std::tie(a.filename_, a.loc_, a.modifications_, a.center_x_, a.center_y_);
298  }
299 
300  return false;
301 }
302 
303 bool locator::operator<(const locator& a) const
304 {
305  if(type_ != a.type_) {
306  return type_ < a.type_;
307  } else if(type_ == FILE) {
308  return filename_ < a.filename_;
309  } else if(type_ == SUB_FILE) {
310  return std::tie(filename_, loc_, modifications_, center_x_, center_y_) <
311  std::tie(a.filename_, a.loc_, a.modifications_, a.center_x_, a.center_y_);
312  }
313 
314  return false;
315 }
316 
317 // Load overlay image and compose it with the original surface.
318 static void add_localized_overlay(const std::string& ovr_file, surface& orig_surf)
319 {
321  surface ovr_surf = IMG_Load_RW(rwops.release(), true); // SDL takes ownership of rwops
322  if(!ovr_surf) {
323  return;
324  }
325 
326  SDL_Rect area {0, 0, ovr_surf->w, ovr_surf->h};
327 
328  sdl_blit(ovr_surf, nullptr, orig_surf, &area);
329 }
330 
332 {
333  surface res;
334  const std::string& name = loc.get_filename();
335 
336  auto location = filesystem::get_binary_file_location("images", name);
337 
338  // Many images have been converted from PNG to WEBP format,
339  // but the old filename may still be saved in savegame files etc.
340  // If the file does not exist in ".png" format, also try ".webp".
341  // Similarly for ".jpg", which conveniently has the same number of letters as ".png".
342  if(!location && (boost::algorithm::ends_with(name, ".png") || boost::algorithm::ends_with(name, ".jpg"))) {
343  std::string webp_name = name.substr(0, name.size() - 4) + ".webp";
344  location = filesystem::get_binary_file_location("images", webp_name);
345  if(location) {
346  WRN_IMG << "Replaced missing '" << name << "' with found '"
347  << webp_name << "'.";
348  }
349  }
350 
351  {
352  if(location) {
353  // Check if there is a localized image.
354  const auto loc_location = filesystem::get_localized_path(location.value());
355  if(loc_location) {
356  location = loc_location.value();
357  }
358 
359  filesystem::rwops_ptr rwops = filesystem::make_read_RWops(location.value());
360  res = IMG_Load_RW(rwops.release(), true); // SDL takes ownership of rwops
361 
362  // If there was no standalone localized image, check if there is an overlay.
363  if(res && !loc_location) {
364  const auto ovr_location = filesystem::get_localized_path(location.value(), "--overlay");
365  if(ovr_location) {
366  add_localized_overlay(ovr_location.value(), res);
367  }
368  }
369  }
370  }
371 
372  if(!res && !name.empty()) {
373  ERR_IMG << "could not open image '" << name << "'";
376  if(name != game_config::images::blank)
378  }
379 
380  return res;
381 }
382 
384 {
385  // Create a new surface in-memory on which to apply the modifications
386  surface surf = get_surface(loc.get_filename(), UNSCALED).clone();
387  if(surf == nullptr) {
388  return nullptr;
389  }
390 
391  modification_queue mods = modification::decode(loc.get_modifications());
392 
393  while(!mods.empty()) {
394  modification* mod = mods.top();
395 
396  try {
397  std::invoke(*mod, surf);
398  } catch(const image::modification::imod_exception& e) {
399  std::ostringstream ss;
400  ss << "\n";
401 
402  for(const std::string& mod_name : utils::parenthetical_split(loc.get_modifications(), '~')) {
403  ss << "\t" << mod_name << "\n";
404  }
405 
406  ERR_CFG << "Failed to apply a modification to an image:\n"
407  << "Image: " << loc.get_filename() << "\n"
408  << "Modifications: " << ss.str() << "\n"
409  << "Error: " << e.message;
410  }
411 
412  // NOTE: do this *after* applying the mod or you'll get crashes!
413  mods.pop();
414  }
415 
416  if(loc.get_loc().valid()) {
417  rect srcrect(
418  ((tile_size * 3) / 4) * loc.get_loc().x,
419  tile_size * loc.get_loc().y + (tile_size / 2) * (loc.get_loc().x % 2),
420  tile_size,
421  tile_size
422  );
423 
424  if(loc.get_center_x() >= 0 && loc.get_center_y() >= 0) {
425  srcrect.x += surf->w / 2 - loc.get_center_x();
426  srcrect.y += surf->h / 2 - loc.get_center_y();
427  }
428 
429  // cut and hex mask, but also check and cache if empty result
430  surface cut = cut_surface(surf, srcrect);
431  bool is_empty = false;
432  mask_surface(cut, get_hexmask(), &is_empty);
433 
434  // discard empty images to free memory
435  if(is_empty) {
436  // Safe because those images are only used by terrain rendering
437  // and it filters them out.
438  // A safer and more general way would be to keep only one copy of it
439  surf = nullptr;
440  } else {
441  surf = cut;
442  }
443 
444  is_empty_hex_.add_to_cache(loc, is_empty);
445  }
446 
447  return surf;
448 }
449 
451 {
452  surface surf;
453 
454  parsed_data_URI parsed{loc.get_filename()};
455 
456  if(!parsed.good) {
457  std::string_view fn = loc.get_filename();
458  std::string_view stripped = fn.substr(0, fn.find(","));
459  ERR_IMG << "Invalid data URI: " << stripped;
460  } else if(parsed.mime.substr(0, 5) != "image") {
461  ERR_IMG << "Data URI not of image MIME type: " << parsed.mime;
462  } else {
463  const std::vector<uint8_t> image_data = base64::decode(parsed.data);
464  filesystem::rwops_ptr rwops{SDL_RWFromConstMem(image_data.data(), image_data.size())};
465 
466  if(image_data.empty()) {
467  ERR_IMG << "Invalid encoding in data URI";
468  } else if(parsed.mime == "image/png") {
469  surf = IMG_LoadPNG_RW(rwops.release());
470  } else if(parsed.mime == "image/jpeg") {
471  surf = IMG_LoadJPG_RW(rwops.release());
472  } else if(parsed.mime == "image/webp") {
473  surf = IMG_LoadWEBP_RW(rwops.release());
474  } else {
475  ERR_IMG << "Invalid image MIME type: " << parsed.mime;
476  }
477  }
478 
479  return surf;
480 }
481 
482 // small utility function to store an int from (-256,254) to an signed char
483 static int8_t col_to_uchar(int i)
484 {
485  return static_cast<int8_t>(std::clamp(i / 2, -128, 127));
486 }
487 
488 light_string get_light_string(int op, int r, int g, int b)
489 {
490  return {
491  static_cast<int8_t>(op),
492  col_to_uchar(r),
493  col_to_uchar(g),
494  col_to_uchar(b),
495  };
496 }
497 
499 {
500  // atomic lightmap operation are handled directly (important to end recursion)
501  if(ls.size() == 4) {
502  // if no lightmap (first char = -1) then we need the initial value
503  //(before the halving done for lightmap)
504  int m = ls[0] == -1 ? 2 : 1;
505  adjust_surface_color(surf, ls[1] * m, ls[2] * m, ls[3] * m);
506  return surf;
507  }
508 
509  // check if the lightmap is already cached or need to be generated
510  surface lightmap = nullptr;
511  auto i = surface_lightmaps_.find(ls);
512  if(i != surface_lightmaps_.end()) {
513  lightmap = i->second;
514  } else {
515  // build all the paths for lightmap sources
516  static const std::string p = "terrain/light/light";
517  static const std::string lm_img[19] {
518  p + ".png",
519  p + "-concave-2-tr.png", p + "-concave-2-r.png", p + "-concave-2-br.png",
520  p + "-concave-2-bl.png", p + "-concave-2-l.png", p + "-concave-2-tl.png",
521  p + "-convex-br-bl.png", p + "-convex-bl-l.png", p + "-convex-l-tl.png",
522  p + "-convex-tl-tr.png", p + "-convex-tr-r.png", p + "-convex-r-br.png",
523  p + "-convex-l-bl.png", p + "-convex-tl-l.png", p + "-convex-tr-tl.png",
524  p + "-convex-r-tr.png", p + "-convex-br-r.png", p + "-convex-bl-br.png"
525  };
526 
527  // decompose into atomic lightmap operations (4 chars)
528  for(std::size_t c = 0; c + 3 < ls.size(); c += 4) {
529  light_string sls = ls.substr(c, 4);
530 
531  // get the corresponding image and apply the lightmap operation to it
532  // This allows to also cache lightmap parts.
533  // note that we avoid infinite recursion by using only atomic operation
534  surface lts = image::get_lighted_image(lm_img[sls[0]], sls);
535 
536  // first image will be the base where we blit the others
537  if(lightmap == nullptr) {
538  // copy the cached image to avoid modifying the cache
539  lightmap = lts.clone();
540  } else {
541  sdl_blit(lts, nullptr, lightmap, nullptr);
542  }
543  }
544 
545  // cache the result
546  surface_lightmaps_[ls] = lightmap;
547  }
548 
549  // apply the final lightmap
550  light_surface(surf, lightmap);
551  return surf;
552 }
553 
555 {
556  switch(loc.get_type()) {
557  case locator::FILE:
558  if(loc.is_data_uri()){
559  return load_image_data_uri(loc);
560  } else {
561  return load_image_file(loc);
562  }
563  case locator::SUB_FILE:
564  return load_image_sub_file(loc);
565  default:
566  return surface(nullptr);
567  }
568 }
569 
571 {
572 }
573 
575 {
576  flush_cache();
577 }
578 
579 void set_color_adjustment(int r, int g, int b)
580 {
581  if(r != red_adjust || g != green_adjust || b != blue_adjust) {
582  red_adjust = r;
583  green_adjust = g;
584  blue_adjust = b;
585  surfaces_[TOD_COLORED].flush();
586  lit_surfaces_.flush();
587  lit_textures_.flush();
588  texture_tod_colored_.clear();
589  }
590 }
591 
592 static surface get_hexed(const locator& i_locator, bool skip_cache = false)
593 {
594  surface image = get_surface(i_locator, UNSCALED, skip_cache).clone();
595  surface mask = get_hexmask();
596  // Ensure the image is the correct size by cropping and/or centering.
597  // TODO: this should probably be a function of sdl/utils
598  if(image && (image->w != mask->w || image->h != mask->h)) {
599  DBG_IMG << "adjusting [" << image->w << ',' << image->h << ']'
600  << " image to hex mask: " << i_locator;
601  // the fitted surface
602  surface fit(mask->w, mask->h);
603  // if the image is too large in either dimension, crop it.
604  if(image->w > mask->w || image->h >= mask->h) {
605  // fill the crop surface with transparency
606  SDL_FillRect(fit, nullptr, SDL_MapRGBA(fit->format, 0, 0, 0, 0));
607  // crop the input image to hexmask dimensions
608  int cutx = std::max(0, image->w - mask->w) / 2;
609  int cuty = std::max(0, image->h - mask->h) / 2;
610  int cutw = std::min(image->w, mask->w);
611  int cuth = std::min(image->h, mask->h);
612  image = cut_surface(image, {cutx, cuty, cutw, cuth});
613  // image will now have dimensions <= mask
614  }
615  // center image
616  int placex = (mask->w - image->w) / 2;
617  int placey = (mask->h - image->h) / 2;
618  rect dst = {placex, placey, image->w, image->h};
619  sdl_blit(image, nullptr, fit, &dst);
620  image = fit;
621  }
622  // hex cut tiles, also check and cache if empty result
623  bool is_empty = false;
624  mask_surface(image, mask, &is_empty, i_locator.get_filename());
625  is_empty_hex_.add_to_cache(i_locator, is_empty);
626  return image;
627 }
628 
629 static surface get_tod_colored(const locator& i_locator, bool skip_cache = false)
630 {
631  surface img = get_surface(i_locator, HEXED, skip_cache).clone();
632  adjust_surface_color(img, red_adjust, green_adjust, blue_adjust);
633  return img;
634 }
635 
636 /** translate type to a simpler one when possible */
637 static TYPE simplify_type(const image::locator& i_locator, TYPE type)
638 {
639  if(type == TOD_COLORED) {
640  if(red_adjust == 0 && green_adjust == 0 && blue_adjust == 0) {
641  type = HEXED;
642  }
643  }
644 
645  if(type == HEXED) {
646  // check if the image is already hex-cut by the location system
647  if(i_locator.get_loc().valid()) {
648  type = UNSCALED;
649  }
650  }
651 
652  return type;
653 }
654 
656  const image::locator& i_locator,
657  TYPE type,
658  bool skip_cache)
659 {
660  surface res;
661 
662  if(i_locator.is_void()) {
663  return res;
664  }
665 
666  type = simplify_type(i_locator, type);
667 
668  // select associated cache
669  if(type >= NUM_TYPES) {
670  WRN_IMG << "get_surface called with unknown image type";
671  return res;
672  }
673  surface_cache& imap = surfaces_[type];
674 
675  // return the image if already cached
676  if(const surface* cached_surf = imap.locate_in_cache(i_locator)) {
677  return *cached_surf;
678  } else {
679  DBG_IMG << "surface cache [" << type << "] miss: " << i_locator;
680  }
681 
682  // not cached, generate it
683  switch(type) {
684  case UNSCALED:
685  // If type is unscaled, directly load the image from the disk.
686  res = load_from_disk(i_locator);
687  break;
688  case TOD_COLORED:
689  res = get_tod_colored(i_locator, skip_cache);
690  break;
691  case HEXED:
692  res = get_hexed(i_locator, skip_cache);
693  break;
694  default:
695  throw game::error("get_surface somehow lost image type?");
696  }
697 
698  bool_cache& skip = skipped_cache_[type];
699 
700  // In cache...
701  if(const bool* cached_value = skip.locate_in_cache(i_locator)) {
702  // ... and cached as true
703  if(*cached_value) {
704  DBG_IMG << "duplicate load: " << i_locator
705  << " [" << type << "]"
706  << " (" << duplicate_loads_ << "/" << total_loads_ << " total)";
707  ++duplicate_loads_;
708  }
709  }
710 
711  ++total_loads_;
712 
713  if(skip_cache) {
714  DBG_IMG << "surface cache [" << type << "] skip: " << i_locator;
715  skip.add_to_cache(i_locator, true);
716  } else {
717  imap.add_to_cache(i_locator, res);
718  }
719 
720  return res;
721 }
722 
724 {
725  if(i_locator.is_void()) {
726  return {};
727  }
728 
729  lit_surface_variants& lvar = lit_surfaces_.access_in_cache(i_locator);
730 
731  // Check the matching list_string variants for this locator
732  if(auto lvi = lvar.find(ls); lvi != lvar.end()) {
733  return lvi->second;
734  }
735 
736  DBG_IMG << "lit surface cache miss: " << i_locator;
737 
738  // not cached yet, generate it
739  surface res = apply_light(get_surface(i_locator, HEXED).clone(), ls);
740 
741  // record the lighted surface in the corresponding variants cache
742  lvar[ls] = res;
743 
744  return res;
745 }
746 
748  const image::locator& i_locator,
749  const light_string& ls)
750 {
751  if(i_locator.is_void()) {
752  return texture();
753  }
754 
755  lit_texture_variants& lvar = lit_textures_.access_in_cache(i_locator);
756 
757  // Check the matching list_string variants for this locator
758  if(auto lvi = lvar.find(ls); lvi != lvar.end()) {
759  return lvi->second;
760  }
761 
762  DBG_IMG << "lit texture cache miss: " << i_locator;
763 
764  // not cached yet, generate it
765  texture tex(get_lighted_image(i_locator, ls));
766 
767  // record the lighted texture in the corresponding variants cache
768  lvar[ls] = tex;
769 
770  return tex;
771 }
772 
774 {
777 }
778 
779 point get_size(const locator& i_locator, bool skip_cache)
780 {
781  if(const surface s = get_surface(i_locator, UNSCALED, skip_cache)) {
782  return {s->w, s->h};
783  } else {
784  return {0, 0};
785  }
786 }
787 
788 bool is_in_hex(const locator& i_locator)
789 {
790  if(const bool* cached_value = in_hex_info_.locate_in_cache(i_locator)) {
791  return *cached_value;
792  } else {
793  bool res = in_mask_surface(get_surface(i_locator, UNSCALED), get_hexmask());
794  in_hex_info_.add_to_cache(i_locator, res);
795  return res;
796  }
797 }
798 
799 bool is_empty_hex(const locator& i_locator)
800 {
801  if(const bool* cached_value = is_empty_hex_.locate_in_cache(i_locator)) {
802  return *cached_value;
803  }
804 
805  surface surf = get_surface(i_locator, HEXED);
806 
807  // Empty state should be cached during surface fetch. Let's check again
808  if(const bool* cached_value = is_empty_hex_.locate_in_cache(i_locator)) {
809  return *cached_value;
810  }
811 
812  // Should never reach this point, but let's manually do it anyway.
813  surf = surf.clone();
814  bool is_empty = false;
815  mask_surface(surf, get_hexmask(), &is_empty);
816  is_empty_hex_.add_to_cache(i_locator, is_empty);
817  return is_empty;
818 }
819 
820 bool exists(const image::locator& i_locator)
821 {
822  if(i_locator.is_void()) {
823  return false;
824  }
825 
826  // The insertion will fail if there is already an element in the cache
827  // and this will point to the existing element.
828  auto [iter, success] = image_existence_map.emplace(i_locator.get_filename(), false);
829 
830  bool& cache = iter->second;
831  if(success) {
832  if(i_locator.is_data_uri()) {
833  cache = parsed_data_URI{i_locator.get_filename()}.good;
834  } else {
835  cache = filesystem::get_binary_file_location("images", i_locator.get_filename()).has_value();
836  }
837  }
838 
839  return cache;
840 }
841 
842 static void precache_file_existence_internal(const std::string& dir, const std::string& subdir)
843 {
844  const std::string checked_dir = dir + "/" + subdir;
845  if(precached_dirs.find(checked_dir) != precached_dirs.end()) {
846  return;
847  }
848 
849  precached_dirs.insert(checked_dir);
850 
851  if(!filesystem::is_directory(checked_dir)) {
852  return;
853  }
854 
855  std::vector<std::string> files_found;
856  std::vector<std::string> dirs_found;
857  filesystem::get_files_in_dir(checked_dir, &files_found, &dirs_found, filesystem::name_mode::FILE_NAME_ONLY,
859 
860  for(const auto& f : files_found) {
861  image_existence_map[subdir + f] = true;
862  }
863 
864  for(const auto& d : dirs_found) {
865  precache_file_existence_internal(dir, subdir + d + "/");
866  }
867 }
868 
869 void precache_file_existence(const std::string& subdir)
870 {
871  for(const auto& p : filesystem::get_binary_paths("images")) {
873  }
874 }
875 
876 bool precached_file_exists(const std::string& file)
877 {
878  const auto b = image_existence_map.find(file);
879  if(b != image_existence_map.end()) {
880  return b->second;
881  }
882 
883  return false;
884 }
885 
886 save_result save_image(const locator& i_locator, const std::string& filename)
887 {
888  return save_image(get_surface(i_locator), filename);
889 }
890 
891 save_result save_image(const surface& surf, const std::string& filename)
892 {
893  if(!surf) {
894  return save_result::no_image;
895  }
896 
897  if(boost::algorithm::ends_with(filename, ".jpeg") || boost::algorithm::ends_with(filename, ".jpg") || boost::algorithm::ends_with(filename, ".jpe")) {
898  LOG_IMG << "Writing a JPG image to " << filename;
899 
900  const int err = IMG_SaveJPG_RW(surf, filesystem::make_write_RWops(filename).release(), true, 75); // SDL takes ownership of the RWops
902  }
903 
904  if(boost::algorithm::ends_with(filename, ".png")) {
905  LOG_IMG << "Writing a PNG image to " << filename;
906 
907  const int err = IMG_SavePNG_RW(surf, filesystem::make_write_RWops(filename).release(), true); // SDL takes ownership of the RWops
909  }
910 
912 }
913 
914 /*
915  * TEXTURE INTERFACE ======================================================================
916  *
917  * The only important difference here is that textures must have their
918  * scale quality set before creation. All other handling is done by
919  * get_surface.
920  */
921 
922 texture get_texture(const image::locator& i_locator, TYPE type, bool skip_cache)
923 {
924  return get_texture(i_locator, scale_quality::nearest, type, skip_cache);
925 }
926 
927 /** Returns a texture for the corresponding image. */
928 texture get_texture(const image::locator& i_locator, scale_quality quality, TYPE type, bool skip_cache)
929 {
930  texture res;
931 
932  if(i_locator.is_void()) {
933  return res;
934  }
935 
936  type = simplify_type(i_locator, type);
937 
938  //
939  // Select the appropriate cache. We don't need caches for every single image types,
940  // since some types can be handled by render-time operations.
941  //
942  texture_cache* cache = nullptr;
943 
944  switch(type) {
945  case HEXED:
946  cache = &textures_hexed_[quality];
947  break;
948  case TOD_COLORED:
949  cache = &texture_tod_colored_[quality];
950  break;
951  default:
952  cache = &textures_[quality];
953  }
954 
955  //
956  // Now attempt to find a cached texture. If found, return it.
957  //
958  if(const texture* cached_texture = cache->locate_in_cache(i_locator)) {
959  return *cached_texture;
960  } else {
961  DBG_IMG << "texture cache [" << type << "] miss: " << i_locator;
962  }
963 
964  //
965  // No texture was cached. In that case, create a new one. The explicit cases require special
966  // handling with surfaces in order to generate the desired effect. This shouldn't be the case
967  // once we get OGL and shader support.
968  //
969 
970  // Get it from the surface cache, also setting the desired scale quality.
971  const bool linear_scaling = quality == scale_quality::linear ? true : false;
972  if(i_locator.get_modifications().empty()) {
973  // skip cache if we're loading plain files with no modifications
974  res = texture(get_surface(i_locator, type, true), linear_scaling);
975  } else {
976  res = texture(get_surface(i_locator, type, skip_cache), linear_scaling);
977  }
978 
979  // Cache the texture.
980  if(skip_cache) {
981  DBG_IMG << "texture cache [" << type << "] skip: " << i_locator;
982  } else {
983  cache->add_to_cache(i_locator, res);
984  }
985 
986  return res;
987 }
988 
989 } // end namespace image
std::string filename_
Definition: action_wml.cpp:534
map_location loc
Definition: move.cpp:172
double g
Definition: astarsearch.cpp:63
bool in_cache(const locator &item) const
Definition: picture.cpp:80
T & access_in_cache(const locator &item)
Returns a reference to the cache item associated with the given key.
Definition: picture.cpp:99
const T * locate_in_cache(const locator &item) const
Returns a pointer to the cached value, or nullptr if not found.
Definition: picture.cpp:86
void add_to_cache(const locator &item, T data)
Definition: picture.cpp:104
std::unordered_map< locator, T > content_
Definition: picture.cpp:115
Generic locator abstracting the location of an image.
Definition: picture.hpp:59
bool is_void() const
Returns true if the locator does not correspond to an actual image.
Definition: picture.hpp:93
map_location loc_
Definition: picture.hpp:100
std::string filename_
Definition: picture.hpp:98
const std::string & get_filename() const
Definition: picture.hpp:82
bool is_data_uri() const
Definition: picture.hpp:83
const std::string & get_modifications() const
Definition: picture.hpp:87
bool is_data_uri_
Definition: picture.hpp:97
const map_location & get_loc() const
Definition: picture.hpp:84
locator::type type_
Definition: picture.hpp:96
locator()=default
bool operator<(const locator &a) const
Definition: picture.cpp:303
bool operator==(const locator &a) const
Definition: picture.cpp:289
locator clone(const std::string &mods) const
Returns a copy of this locator with the given IPF.
Definition: picture.cpp:218
std::string modifications_
Definition: picture.hpp:99
A modified priority queue used to order image modifications.
modification * top() const
Returns the top element in the queue .
void pop()
Removes the top element from the queue.
Base abstract class for an image-path modification.
static modification_queue decode(const std::string &)
Decodes modifications from a modification string.
surface clone() const
Creates a new, duplicate surface in memory using the 'neutral' pixel format.
Definition: surface.cpp:97
Wrapper class to encapsulate creation and management of an SDL_Texture.
Definition: texture.hpp:33
Declarations for File-IO.
std::size_t i
Definition: function.cpp:1030
map_location loc_
Standard logging facilities (interface).
std::vector< uint8_t > decode(std::string_view in)
Definition: base64.cpp:221
void get_files_in_dir(const std::string &dir, std::vector< std::string > *files, std::vector< std::string > *dirs, name_mode mode, filter_mode filter, reorder_mode reorder, file_tree_checksum *checksum)
Get a list of all files and/or directories in a given directory.
Definition: filesystem.cpp:450
std::unique_ptr< SDL_RWops, sdl_rwops_deleter > rwops_ptr
Definition: filesystem.hpp:61
bool is_directory(const std::string &fname)
Returns true if the given file is a directory.
rwops_ptr make_read_RWops(const std::string &path)
utils::optional< std::string > get_binary_file_location(const std::string &type, const std::string &filename)
Returns a complete path to the actual file of a given type, if it exists.
utils::optional< std::string > get_localized_path(const std::string &file, const std::string &suff)
Returns the localized version of the given filename, if it exists.
rwops_ptr make_write_RWops(const std::string &path)
const std::vector< std::string > & get_binary_paths(const std::string &type)
Returns a vector with all possible paths to a given type of binary, e.g.
std::string terrain_mask
const bool & debug
Definition: game_config.cpp:95
unsigned int tile_size
Definition: game_config.cpp:55
Functions to load and save images from/to disk.
static surface load_image_sub_file(const image::locator &loc)
Definition: picture.cpp:383
bool is_empty_hex(const locator &i_locator)
Checks if an image is empty after hex masking.
Definition: picture.cpp:799
static void add_localized_overlay(const std::string &ovr_file, surface &orig_surf)
Definition: picture.cpp:318
static surface apply_light(surface surf, const light_string &ls)
Definition: picture.cpp:498
bool precached_file_exists(const std::string &file)
Definition: picture.cpp:876
save_result
Definition: picture.hpp:262
static TYPE simplify_type(const image::locator &i_locator, TYPE type)
translate type to a simpler one when possible
Definition: picture.cpp:637
static surface load_image_data_uri(const image::locator &loc)
Definition: picture.cpp:450
static surface get_tod_colored(const locator &i_locator, bool skip_cache=false)
Definition: picture.cpp:629
bool exists(const image::locator &i_locator)
Returns true if the given image actually exists, without loading it.
Definition: picture.cpp:820
void flush_cache()
Purges all image caches.
Definition: picture.cpp:200
static void precache_file_existence_internal(const std::string &dir, const std::string &subdir)
Definition: picture.cpp:842
static surface load_from_disk(const locator &loc)
Definition: picture.cpp:554
surface get_surface(const image::locator &i_locator, TYPE type, bool skip_cache)
Returns an image surface suitable for software manipulation.
Definition: picture.cpp:655
surface get_hexmask()
Retrieves the standard hexagonal tile mask.
Definition: picture.cpp:773
std::ostream & operator<<(std::ostream &s, const locator &l)
Definition: picture.cpp:229
texture get_lighted_texture(const image::locator &i_locator, const light_string &ls)
Definition: picture.cpp:747
save_result save_image(const locator &i_locator, const std::string &filename)
Definition: picture.cpp:886
std::basic_string< signed char > light_string
Type used to store color information of central and adjacent hexes.
Definition: picture.hpp:123
void precache_file_existence(const std::string &subdir)
Precache the existence of files in a binary path subdirectory (e.g.
Definition: picture.cpp:869
TYPE
Used to specify the rendering format of images.
Definition: picture.hpp:162
@ HEXED
Standard hexagonal tile mask applied, removing portions that don't fit.
Definition: picture.hpp:166
@ NUM_TYPES
Definition: picture.hpp:169
@ TOD_COLORED
Same as HEXED, but with Time of Day color tint applied.
Definition: picture.hpp:168
@ UNSCALED
Unmodified original-size image.
Definition: picture.hpp:164
texture get_texture(const image::locator &i_locator, TYPE type, bool skip_cache)
Returns an image texture suitable for hardware-accelerated rendering.
Definition: picture.cpp:922
point get_size(const locator &i_locator, bool skip_cache)
Returns the width and height of an image.
Definition: picture.cpp:779
static surface get_hexed(const locator &i_locator, bool skip_cache=false)
Definition: picture.cpp:592
surface get_lighted_image(const image::locator &i_locator, const light_string &ls)
Caches and returns an image with a lightmap applied to it.
Definition: picture.cpp:723
void set_color_adjustment(int r, int g, int b)
Changes Time of Day color tint for all applicable image types.
Definition: picture.cpp:579
static int8_t col_to_uchar(int i)
Definition: picture.cpp:483
light_string get_light_string(int op, int r, int g, int b)
Returns the light_string for one light operation.
Definition: picture.cpp:488
bool is_in_hex(const locator &i_locator)
Checks if an image fits into a single hex.
Definition: picture.cpp:788
scale_quality
Definition: picture.hpp:172
static surface load_image_file(const image::locator &loc)
Definition: picture.cpp:331
logger & err()
Definition: log.cpp:306
std::string img(const std::string &src, const std::string &align, bool floating)
Generates a Help markup tag corresponding to an image.
Definition: markup.cpp:31
std::vector< std::string > parenthetical_split(std::string_view val, const char separator, std::string_view left, std::string_view right, const int flags)
Splits a string based either on a separator, except then the text appears within specified parenthesi...
#define DBG_IMG
Definition: picture.cpp:44
static lg::log_domain log_image("image")
#define ERR_CFG
Definition: picture.cpp:47
std::string_view scheme
Definition: picture.cpp:175
std::string_view mime
Definition: picture.cpp:176
bool good
Definition: picture.cpp:179
#define WRN_IMG
Definition: picture.cpp:42
std::string_view base64
Definition: picture.cpp:177
#define LOG_IMG
Definition: picture.cpp:43
#define ERR_IMG
Definition: picture.cpp:41
std::string_view data
Definition: picture.cpp:178
static lg::log_domain log_config("config")
Contains the SDL_Rect helper code.
rect dst
Location on the final composed sheet.
surface surf
Image.
std::string filename
Filename.
Base class for all the errors encountered by the engine.
Definition: exceptions.hpp:29
Exception thrown by the operator() when an error occurs.
Encapsulates the map of the game.
Definition: location.hpp:45
bool valid() const
Definition: location.hpp:110
Holds a 2D point.
Definition: point.hpp:25
An abstract description of a rectangle with integer coordinates.
Definition: rect.hpp:49
std::size_t operator()(const image::locator &val) const
Definition: picture.cpp:54
mock_char c
mock_party p
static map_location::direction s
void mask_surface(surface &nsurf, const surface &nmask, bool *empty_result, const std::string &filename)
Applies a mask on a surface.
Definition: utils.cpp:761
void adjust_surface_color(surface &nsurf, int red, int green, int blue)
Definition: utils.cpp:405
surface cut_surface(const surface &surf, const SDL_Rect &r)
Cuts a rectangle from a surface.
Definition: utils.cpp:1171
void light_surface(surface &nsurf, const surface &lightmap)
Light surf using lightmap.
Definition: utils.cpp:860
bool in_mask_surface(const surface &nsurf, const surface &nmask)
Check if a surface fit into a mask.
Definition: utils.cpp:822
void sdl_blit(const surface &src, const SDL_Rect *src_rect, surface &dst, SDL_Rect *dst_rect)
Definition: utils.hpp:44
#define d
#define e
#define f
#define b