SDLImage.cpp 12 KB

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