SDLImage.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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 = SDLImageShared::createScaled(this, factor, algorithm);
  192. if (surf->format->palette)
  193. SDL_SetSurfacePalette(surf, originalPalette);
  194. return result;
  195. }
  196. std::shared_ptr<SDLImageShared> SDLImageShared::createScaled(const SDLImageShared * from, int integerScaleFactor, EScalingAlgorithm algorithm)
  197. {
  198. auto self = std::make_shared<SDLImageShared>(nullptr);
  199. self->upscalingInProgress = true;
  200. auto scaler = std::make_shared<SDLImageScaler>(from->surf, Rect(from->margins, from->fullSize), true);
  201. const auto & scalingTask = [self, algorithm, scaler]()
  202. {
  203. scaler->scaleSurfaceIntegerFactor(ENGINE->screenHandler().getScalingFactor(), algorithm);
  204. self->surf = scaler->acquireResultSurface();
  205. self->fullSize = scaler->getResultDimensions().dimensions();
  206. self->margins = scaler->getResultDimensions().topLeft();
  207. self->upscalingInProgress = false;
  208. };
  209. if(settings["video"]["asyncUpscaling"].Bool())
  210. ENGINE->async().run(scalingTask);
  211. else
  212. scalingTask();
  213. return self;
  214. }
  215. bool SDLImageShared::isLoading() const
  216. {
  217. return upscalingInProgress;
  218. }
  219. std::shared_ptr<const ISharedImage> SDLImageShared::scaleTo(const Point & size, SDL_Palette * palette) const
  220. {
  221. if(upscalingInProgress)
  222. throw std::runtime_error("Attempt to access images that is still being loaded!");
  223. if (palette && surf->format->palette)
  224. SDL_SetSurfacePalette(surf, palette);
  225. SDLImageScaler scaler(surf, Rect(margins, fullSize), true);
  226. scaler.scaleSurface(size, EScalingAlgorithm::XBRZ_ALPHA);
  227. auto scaled = scaler.acquireResultSurface();
  228. if (scaled->format && scaled->format->palette) // fix color keying, because SDL loses it at this point
  229. CSDL_Ext::setColorKey(scaled, scaled->format->palette->colors[0]);
  230. else if(scaled->format && scaled->format->Amask)
  231. SDL_SetSurfaceBlendMode(scaled, SDL_BLENDMODE_BLEND);//just in case
  232. else
  233. CSDL_Ext::setDefaultColorKey(scaled);//just in case
  234. auto ret = std::make_shared<SDLImageShared>(scaled);
  235. ret->fullSize = scaler.getResultDimensions().dimensions();
  236. ret->margins = scaler.getResultDimensions().topLeft();
  237. // erase our own reference
  238. SDL_FreeSurface(scaled);
  239. if (surf->format->palette)
  240. SDL_SetSurfacePalette(surf, originalPalette);
  241. return ret;
  242. }
  243. void SDLImageShared::exportBitmap(const boost::filesystem::path& path, SDL_Palette * palette) const
  244. {
  245. auto directory = path;
  246. directory.remove_filename();
  247. boost::filesystem::create_directories(directory);
  248. if(upscalingInProgress)
  249. throw std::runtime_error("Attempt to access images that is still being loaded!");
  250. if (!surf)
  251. return;
  252. if (palette && surf->format->palette)
  253. SDL_SetSurfacePalette(surf, palette);
  254. IMG_SavePNG(surf, path.string().c_str());
  255. if (palette && surf->format->palette)
  256. SDL_SetSurfacePalette(surf, originalPalette);
  257. }
  258. bool SDLImageShared::isTransparent(const Point & coords) const
  259. {
  260. if(upscalingInProgress)
  261. throw std::runtime_error("Attempt to access images that is still being loaded!");
  262. if (!surf)
  263. return true;
  264. Point test = coords - margins;
  265. if (test.x < 0 || test.y < 0 || test.x >= surf->w || test.y >= surf->h)
  266. return true;
  267. SDL_Color color;
  268. SDL_GetRGBA(CSDL_Ext::getPixel(surf, test.x, test.y), surf->format, &color.r, &color.g, &color.b, &color.a);
  269. bool pixelTransparent = color.a < 128;
  270. bool pixelCyan = (color.r == 0 && color.g == 255 && color.b == 255);
  271. return pixelTransparent || pixelCyan;
  272. }
  273. Rect SDLImageShared::contentRect() const
  274. {
  275. if(upscalingInProgress)
  276. throw std::runtime_error("Attempt to access images that is still being loaded!");
  277. if (!surf)
  278. return Rect();
  279. return Rect(margins, Point(surf->w, surf->h));
  280. }
  281. const SDL_Palette * SDLImageShared::getPalette() const
  282. {
  283. if(upscalingInProgress)
  284. throw std::runtime_error("Attempt to access images that is still being loaded!");
  285. if (!surf)
  286. return nullptr;
  287. return surf->format->palette;
  288. }
  289. Point SDLImageShared::dimensions() const
  290. {
  291. if(upscalingInProgress)
  292. throw std::runtime_error("Attempt to access images that is still being loaded!");
  293. return fullSize;
  294. }
  295. std::shared_ptr<const ISharedImage> SDLImageShared::horizontalFlip() const
  296. {
  297. if(upscalingInProgress)
  298. throw std::runtime_error("Attempt to access images that is still being loaded!");
  299. if (!surf)
  300. return shared_from_this();
  301. SDL_Surface * flipped = CSDL_Ext::horizontalFlip(surf);
  302. auto ret = std::make_shared<SDLImageShared>(flipped);
  303. ret->fullSize = fullSize;
  304. ret->margins.x = margins.x;
  305. ret->margins.y = fullSize.y - surf->h - margins.y;
  306. ret->fullSize = fullSize;
  307. // erase our own reference
  308. SDL_FreeSurface(flipped);
  309. return ret;
  310. }
  311. std::shared_ptr<const ISharedImage> SDLImageShared::verticalFlip() const
  312. {
  313. if(upscalingInProgress)
  314. throw std::runtime_error("Attempt to access images that is still being loaded!");
  315. if (!surf)
  316. return shared_from_this();
  317. SDL_Surface * flipped = CSDL_Ext::verticalFlip(surf);
  318. auto ret = std::make_shared<SDLImageShared>(flipped);
  319. ret->fullSize = fullSize;
  320. ret->margins.x = fullSize.x - surf->w - margins.x;
  321. ret->margins.y = margins.y;
  322. ret->fullSize = fullSize;
  323. // erase our own reference
  324. SDL_FreeSurface(flipped);
  325. return ret;
  326. }
  327. std::shared_ptr<const ISharedImage> SDLImageShared::drawShadow(bool doSheer) const
  328. {
  329. if(upscalingInProgress)
  330. throw std::runtime_error("Attempt to access images that is still being loaded!");
  331. if (!surf)
  332. return shared_from_this();
  333. SDL_Surface * shadow = CSDL_Ext::drawShadow(surf, doSheer);
  334. auto ret = std::make_shared<SDLImageShared>(shadow);
  335. ret->fullSize = fullSize;
  336. ret->margins.x = margins.x;
  337. ret->margins.y = margins.y;
  338. // erase our own reference
  339. SDL_FreeSurface(shadow);
  340. return ret;
  341. }
  342. std::shared_ptr<const ISharedImage> SDLImageShared::drawOutline(const ColorRGBA & color, int thickness) const
  343. {
  344. if(upscalingInProgress)
  345. throw std::runtime_error("Attempt to access images that is still being loaded!");
  346. if (!surf)
  347. return shared_from_this();
  348. SDL_Color sdlColor = { color.r, color.g, color.b, color.a };
  349. SDL_Surface * outline = CSDL_Ext::drawOutline(surf, sdlColor, thickness);
  350. auto ret = std::make_shared<SDLImageShared>(outline);
  351. ret->fullSize = fullSize;
  352. ret->margins.x = margins.x;
  353. ret->margins.y = margins.y;
  354. // erase our own reference
  355. SDL_FreeSurface(outline);
  356. return ret;
  357. }
  358. // Keep the original palette, in order to do color switching operation
  359. void SDLImageShared::savePalette()
  360. {
  361. if(upscalingInProgress)
  362. throw std::runtime_error("Attempt to access images that is still being loaded!");
  363. // For some images that don't have palette, skip this
  364. if(surf->format->palette == nullptr)
  365. return;
  366. if(originalPalette == nullptr)
  367. originalPalette = SDL_AllocPalette(surf->format->palette->ncolors);
  368. SDL_SetPaletteColors(originalPalette, surf->format->palette->colors, 0, surf->format->palette->ncolors);
  369. }
  370. SDLImageShared::~SDLImageShared()
  371. {
  372. SDL_FreeSurface(surf);
  373. if (originalPalette)
  374. SDL_FreePalette(originalPalette);
  375. }