SDLImage.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. /*
  2. * SDLImage.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "SDLImage.h"
  12. #include "SDLImageLoader.h"
  13. #include "SDLImageScaler.h"
  14. #include "SDL_Extensions.h"
  15. #include "../render/ColorFilter.h"
  16. #include "../render/CBitmapHandler.h"
  17. #include "../render/CDefFile.h"
  18. #include "../gui/CGuiHandler.h"
  19. #include "../render/IScreenHandler.h"
  20. #include <tbb/parallel_for.h>
  21. #include <tbb/task_arena.h>
  22. #include <SDL_image.h>
  23. #include <SDL_surface.h>
  24. #include <SDL_version.h>
  25. class SDLImageLoader;
  26. int IImage::width() const
  27. {
  28. return dimensions().x;
  29. }
  30. int IImage::height() const
  31. {
  32. return dimensions().y;
  33. }
  34. SDLImageShared::SDLImageShared(const CDefFile * data, size_t frame, size_t group)
  35. : surf(nullptr),
  36. margins(0, 0),
  37. fullSize(0, 0),
  38. originalPalette(nullptr)
  39. {
  40. SDLImageLoader loader(this);
  41. data->loadFrame(frame, group, loader);
  42. savePalette();
  43. }
  44. SDLImageShared::SDLImageShared(SDL_Surface * from)
  45. : surf(nullptr),
  46. margins(0, 0),
  47. fullSize(0, 0),
  48. originalPalette(nullptr)
  49. {
  50. surf = from;
  51. if (surf == nullptr)
  52. return;
  53. savePalette();
  54. surf->refcount++;
  55. fullSize.x = surf->w;
  56. fullSize.y = surf->h;
  57. }
  58. SDLImageShared::SDLImageShared(const ImagePath & filename)
  59. : surf(nullptr),
  60. margins(0, 0),
  61. fullSize(0, 0),
  62. originalPalette(nullptr)
  63. {
  64. surf = BitmapHandler::loadBitmap(filename);
  65. if(surf == nullptr)
  66. {
  67. logGlobal->error("Error: failed to load image %s", filename.getOriginalName());
  68. return;
  69. }
  70. else
  71. {
  72. savePalette();
  73. fullSize.x = surf->w;
  74. fullSize.y = surf->h;
  75. optimizeSurface();
  76. }
  77. }
  78. void SDLImageShared::scaledDraw(SDL_Surface * where, SDL_Palette * palette, const Point & scaleTo, const Point & dest, const Rect * src, const ColorRGBA & colorMultiplier, uint8_t alpha, EImageBlitMode mode) const
  79. {
  80. if(upscalingInProgress)
  81. throw std::runtime_error("Attempt to access images that is still being loaded!");
  82. if (!surf)
  83. return;
  84. Rect sourceRect(0, 0, surf->w, surf->h);
  85. Point destShift(0, 0);
  86. Point destScale = Point(surf->w, surf->h) * scaleTo / dimensions();
  87. Point marginsScaled = margins * scaleTo / dimensions();
  88. if(src)
  89. {
  90. Rect srcUnscaled(Point(src->topLeft() * dimensions() / scaleTo), Point(src->dimensions() * dimensions() / scaleTo));
  91. if(srcUnscaled.x < margins.x)
  92. destShift.x += marginsScaled.x - src->x;
  93. if(srcUnscaled.y < margins.y)
  94. destShift.y += marginsScaled.y - src->y;
  95. sourceRect = Rect(srcUnscaled).intersect(Rect(margins.x, margins.y, surf->w, surf->h));
  96. destScale.x = std::min(destScale.x, sourceRect.w * scaleTo.x / dimensions().x);
  97. destScale.y = std::min(destScale.y, sourceRect.h * scaleTo.y / dimensions().y);
  98. sourceRect -= margins;
  99. }
  100. else
  101. destShift = marginsScaled;
  102. destShift += dest;
  103. SDL_SetSurfaceColorMod(surf, colorMultiplier.r, colorMultiplier.g, colorMultiplier.b);
  104. SDL_SetSurfaceAlphaMod(surf, alpha);
  105. if (alpha != SDL_ALPHA_OPAQUE || (mode != EImageBlitMode::OPAQUE && surf->format->Amask != 0))
  106. SDL_SetSurfaceBlendMode(surf, SDL_BLENDMODE_BLEND);
  107. else
  108. SDL_SetSurfaceBlendMode(surf, SDL_BLENDMODE_NONE);
  109. if (palette && surf->format->palette)
  110. SDL_SetSurfacePalette(surf, palette);
  111. SDL_Rect srcRect = CSDL_Ext::toSDL(sourceRect);
  112. SDL_Rect dstRect = CSDL_Ext::toSDL(Rect(destShift, destScale));
  113. if (sourceRect.dimensions() * scaleTo / dimensions() != destScale)
  114. logGlobal->info("???");
  115. SDL_Surface * tempSurface = SDL_ConvertSurface(surf, where->format, 0);
  116. int result = SDL_BlitScaled(tempSurface, &srcRect, where, &dstRect);
  117. SDL_FreeSurface(tempSurface);
  118. if (result != 0)
  119. logGlobal->error("SDL_BlitScaled failed! %s", SDL_GetError());
  120. if (surf->format->palette)
  121. SDL_SetSurfacePalette(surf, originalPalette);
  122. }
  123. void SDLImageShared::draw(SDL_Surface * where, SDL_Palette * palette, const Point & dest, const Rect * src, const ColorRGBA & colorMultiplier, uint8_t alpha, EImageBlitMode mode) const
  124. {
  125. if(upscalingInProgress)
  126. throw std::runtime_error("Attempt to access images that is still being loaded!");
  127. if (!surf)
  128. return;
  129. Rect sourceRect(0, 0, surf->w, surf->h);
  130. Point destShift(0, 0);
  131. if(src)
  132. {
  133. if(src->x < margins.x)
  134. destShift.x += margins.x - src->x;
  135. if(src->y < margins.y)
  136. destShift.y += margins.y - src->y;
  137. sourceRect = Rect(*src).intersect(Rect(margins.x, margins.y, surf->w, surf->h));
  138. sourceRect -= margins;
  139. }
  140. else
  141. destShift = margins;
  142. destShift += dest;
  143. SDL_SetSurfaceColorMod(surf, colorMultiplier.r, colorMultiplier.g, colorMultiplier.b);
  144. SDL_SetSurfaceAlphaMod(surf, alpha);
  145. if (alpha != SDL_ALPHA_OPAQUE || (mode != EImageBlitMode::OPAQUE && surf->format->Amask != 0))
  146. SDL_SetSurfaceBlendMode(surf, SDL_BLENDMODE_BLEND);
  147. else
  148. SDL_SetSurfaceBlendMode(surf, SDL_BLENDMODE_NONE);
  149. if (palette && surf->format->palette)
  150. SDL_SetSurfacePalette(surf, palette);
  151. if(surf->format->palette && mode != EImageBlitMode::OPAQUE && mode != EImageBlitMode::COLORKEY)
  152. {
  153. CSDL_Ext::blit8bppAlphaTo24bpp(surf, sourceRect, where, destShift, alpha);
  154. }
  155. else
  156. {
  157. CSDL_Ext::blitSurface(surf, sourceRect, where, destShift);
  158. }
  159. if (surf->format->palette)
  160. SDL_SetSurfacePalette(surf, originalPalette);
  161. }
  162. void SDLImageShared::optimizeSurface()
  163. {
  164. assert(upscalingInProgress == false);
  165. if (!surf)
  166. return;
  167. SDLImageOptimizer optimizer(surf, Rect(margins, fullSize));
  168. optimizer.optimizeSurface(surf);
  169. SDL_FreeSurface(surf);
  170. surf = optimizer.acquireResultSurface();
  171. margins = optimizer.getResultDimensions().topLeft();
  172. fullSize = optimizer.getResultDimensions().dimensions();
  173. }
  174. std::shared_ptr<const ISharedImage> SDLImageShared::scaleInteger(int factor, SDL_Palette * palette, EImageBlitMode mode) const
  175. {
  176. if(upscalingInProgress)
  177. throw std::runtime_error("Attempt to access images that is still being loaded!");
  178. if (factor <= 0)
  179. throw std::runtime_error("Unable to scale by integer value of " + std::to_string(factor));
  180. if (!surf)
  181. return shared_from_this();
  182. if (palette && surf->format->palette)
  183. SDL_SetSurfacePalette(surf, palette);
  184. // simple heuristics to differentiate tileable UI elements from map object / combat assets
  185. EScalingAlgorithm algorithm;
  186. if (mode == EImageBlitMode::OPAQUE || mode == EImageBlitMode::COLORKEY || mode == EImageBlitMode::SIMPLE)
  187. algorithm = EScalingAlgorithm::XBRZ_OPAQUE;
  188. else
  189. algorithm = EScalingAlgorithm::XBRZ_ALPHA;
  190. auto result = std::make_shared<SDLImageShared>(this, factor, algorithm);
  191. if (surf->format->palette)
  192. SDL_SetSurfacePalette(surf, originalPalette);
  193. return result;
  194. }
  195. SDLImageShared::SDLImageShared(const SDLImageShared * from, int integerScaleFactor, EScalingAlgorithm algorithm)
  196. {
  197. static tbb::task_arena upscalingArena;
  198. upscalingInProgress = true;
  199. auto scaler = std::make_shared<SDLImageScaler>(from->surf, Rect(from->margins, from->fullSize), true);
  200. const auto & scalingTask = [this, algorithm, scaler]()
  201. {
  202. scaler->scaleSurfaceIntegerFactor(GH.screenHandler().getScalingFactor(), algorithm);
  203. surf = scaler->acquireResultSurface();
  204. fullSize = scaler->getResultDimensions().dimensions();
  205. margins = scaler->getResultDimensions().topLeft();
  206. upscalingInProgress = false;
  207. };
  208. upscalingArena.enqueue(scalingTask);
  209. }
  210. bool SDLImageShared::isLoading() const
  211. {
  212. return upscalingInProgress;
  213. }
  214. std::shared_ptr<const ISharedImage> SDLImageShared::scaleTo(const Point & size, SDL_Palette * palette) const
  215. {
  216. if(upscalingInProgress)
  217. throw std::runtime_error("Attempt to access images that is still being loaded!");
  218. if (palette && surf->format->palette)
  219. SDL_SetSurfacePalette(surf, palette);
  220. SDLImageScaler scaler(surf, Rect(margins, fullSize), true);
  221. scaler.scaleSurface(size, EScalingAlgorithm::XBRZ_ALPHA);
  222. auto scaled = scaler.acquireResultSurface();
  223. if (scaled->format && scaled->format->palette) // fix color keying, because SDL loses it at this point
  224. CSDL_Ext::setColorKey(scaled, scaled->format->palette->colors[0]);
  225. else if(scaled->format && scaled->format->Amask)
  226. SDL_SetSurfaceBlendMode(scaled, SDL_BLENDMODE_BLEND);//just in case
  227. else
  228. CSDL_Ext::setDefaultColorKey(scaled);//just in case
  229. auto ret = std::make_shared<SDLImageShared>(scaled);
  230. ret->fullSize = scaler.getResultDimensions().dimensions();
  231. ret->margins = scaler.getResultDimensions().topLeft();
  232. // erase our own reference
  233. SDL_FreeSurface(scaled);
  234. if (surf->format->palette)
  235. SDL_SetSurfacePalette(surf, originalPalette);
  236. return ret;
  237. }
  238. void SDLImageShared::exportBitmap(const boost::filesystem::path& path, SDL_Palette * palette) const
  239. {
  240. auto directory = path;
  241. directory.remove_filename();
  242. boost::filesystem::create_directories(directory);
  243. if(upscalingInProgress)
  244. throw std::runtime_error("Attempt to access images that is still being loaded!");
  245. if (!surf)
  246. return;
  247. if (palette && surf->format->palette)
  248. SDL_SetSurfacePalette(surf, palette);
  249. IMG_SavePNG(surf, path.string().c_str());
  250. if (palette && surf->format->palette)
  251. SDL_SetSurfacePalette(surf, originalPalette);
  252. }
  253. bool SDLImageShared::isTransparent(const Point & coords) const
  254. {
  255. if(upscalingInProgress)
  256. throw std::runtime_error("Attempt to access images that is still being loaded!");
  257. if (surf)
  258. return CSDL_Ext::isTransparent(surf, coords.x - margins.x, coords.y - margins.y);
  259. else
  260. return true;
  261. }
  262. Rect SDLImageShared::contentRect() const
  263. {
  264. if(upscalingInProgress)
  265. throw std::runtime_error("Attempt to access images that is still being loaded!");
  266. auto tmpMargins = margins;
  267. auto tmpSize = Point(surf->w, surf->h);
  268. return Rect(tmpMargins, tmpSize);
  269. }
  270. const SDL_Palette * SDLImageShared::getPalette() const
  271. {
  272. if(upscalingInProgress)
  273. throw std::runtime_error("Attempt to access images that is still being loaded!");
  274. if (!surf)
  275. return nullptr;
  276. return surf->format->palette;
  277. }
  278. Point SDLImageShared::dimensions() const
  279. {
  280. if(upscalingInProgress)
  281. throw std::runtime_error("Attempt to access images that is still being loaded!");
  282. return fullSize;
  283. }
  284. std::shared_ptr<const ISharedImage> SDLImageShared::horizontalFlip() const
  285. {
  286. if(upscalingInProgress)
  287. throw std::runtime_error("Attempt to access images that is still being loaded!");
  288. if (!surf)
  289. return shared_from_this();
  290. SDL_Surface * flipped = CSDL_Ext::horizontalFlip(surf);
  291. auto ret = std::make_shared<SDLImageShared>(flipped);
  292. ret->fullSize = fullSize;
  293. ret->margins.x = margins.x;
  294. ret->margins.y = fullSize.y - surf->h - margins.y;
  295. ret->fullSize = fullSize;
  296. return ret;
  297. }
  298. std::shared_ptr<const ISharedImage> SDLImageShared::verticalFlip() const
  299. {
  300. if(upscalingInProgress)
  301. throw std::runtime_error("Attempt to access images that is still being loaded!");
  302. if (!surf)
  303. return shared_from_this();
  304. SDL_Surface * flipped = CSDL_Ext::verticalFlip(surf);
  305. auto ret = std::make_shared<SDLImageShared>(flipped);
  306. ret->fullSize = fullSize;
  307. ret->margins.x = fullSize.x - surf->w - margins.x;
  308. ret->margins.y = margins.y;
  309. ret->fullSize = fullSize;
  310. return ret;
  311. }
  312. // Keep the original palette, in order to do color switching operation
  313. void SDLImageShared::savePalette()
  314. {
  315. if(upscalingInProgress)
  316. throw std::runtime_error("Attempt to access images that is still being loaded!");
  317. // For some images that don't have palette, skip this
  318. if(surf->format->palette == nullptr)
  319. return;
  320. if(originalPalette == nullptr)
  321. originalPalette = SDL_AllocPalette(surf->format->palette->ncolors);
  322. SDL_SetPaletteColors(originalPalette, surf->format->palette->colors, 0, surf->format->palette->ncolors);
  323. }
  324. SDLImageShared::~SDLImageShared()
  325. {
  326. SDL_FreeSurface(surf);
  327. SDL_FreePalette(originalPalette);
  328. }