SDLImage.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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 "SDL_Extensions.h"
  14. #include "../render/ColorFilter.h"
  15. #include "../render/Colors.h"
  16. #include "../render/CBitmapHandler.h"
  17. #include "../render/CDefFile.h"
  18. #include "../render/Graphics.h"
  19. #include <SDL_surface.h>
  20. class SDLImageLoader;
  21. //First 8 colors in def palette used for transparency
  22. static const SDL_Color sourcePalette[8] = {
  23. {0, 255, 255, SDL_ALPHA_OPAQUE},
  24. {255, 150, 255, SDL_ALPHA_OPAQUE},
  25. {255, 100, 255, SDL_ALPHA_OPAQUE},
  26. {255, 50, 255, SDL_ALPHA_OPAQUE},
  27. {255, 0, 255, SDL_ALPHA_OPAQUE},
  28. {255, 255, 0, SDL_ALPHA_OPAQUE},
  29. {180, 0, 255, SDL_ALPHA_OPAQUE},
  30. {0, 255, 0, SDL_ALPHA_OPAQUE}
  31. };
  32. static const ColorRGBA targetPalette[8] = {
  33. {0, 0, 0, 0 }, // 0 - transparency ( used in most images )
  34. {0, 0, 0, 64 }, // 1 - shadow border ( used in battle, adventure map def's )
  35. {0, 0, 0, 64 }, // 2 - shadow border ( used in fog-of-war def's )
  36. {0, 0, 0, 128}, // 3 - shadow body ( used in fog-of-war def's )
  37. {0, 0, 0, 128}, // 4 - shadow body ( used in battle, adventure map def's )
  38. {0, 0, 0, 0 }, // 5 - selection / owner flag ( used in battle, adventure map def's )
  39. {0, 0, 0, 128}, // 6 - shadow body below selection ( used in battle def's )
  40. {0, 0, 0, 64 } // 7 - shadow border below selection ( used in battle def's )
  41. };
  42. static ui8 mixChannels(ui8 c1, ui8 c2, ui8 a1, ui8 a2)
  43. {
  44. return c1*a1 / 256 + c2*a2*(255 - a1) / 256 / 256;
  45. }
  46. static ColorRGBA addColors(const ColorRGBA & base, const ColorRGBA & over)
  47. {
  48. return ColorRGBA(
  49. mixChannels(over.r, base.r, over.a, base.a),
  50. mixChannels(over.g, base.g, over.a, base.a),
  51. mixChannels(over.b, base.b, over.a, base.a),
  52. ui8(over.a + base.a * (255 - over.a) / 256)
  53. );
  54. }
  55. static bool colorsSimilar (const SDL_Color & lhs, const SDL_Color & rhs)
  56. {
  57. // it seems that H3 does not requires exact match to replace colors -> (255, 103, 255) gets interpreted as shadow
  58. // exact logic is not clear and requires extensive testing with image editing
  59. // potential reason is that H3 uses 16-bit color format (565 RGB bits), meaning that 3 least significant bits are lost in red and blue component
  60. static const int threshold = 8;
  61. int diffR = static_cast<int>(lhs.r) - rhs.r;
  62. int diffG = static_cast<int>(lhs.g) - rhs.g;
  63. int diffB = static_cast<int>(lhs.b) - rhs.b;
  64. int diffA = static_cast<int>(lhs.a) - rhs.a;
  65. return std::abs(diffR) < threshold && std::abs(diffG) < threshold && std::abs(diffB) < threshold && std::abs(diffA) < threshold;
  66. }
  67. int IImage::width() const
  68. {
  69. return dimensions().x;
  70. }
  71. int IImage::height() const
  72. {
  73. return dimensions().y;
  74. }
  75. SDLImageShared::SDLImageShared(CDefFile * data, size_t frame, size_t group)
  76. : surf(nullptr),
  77. margins(0, 0),
  78. fullSize(0, 0),
  79. originalPalette(nullptr)
  80. {
  81. SDLImageLoader loader(this);
  82. data->loadFrame(frame, group, loader);
  83. savePalette();
  84. }
  85. SDLImageShared::SDLImageShared(SDL_Surface * from)
  86. : surf(nullptr),
  87. margins(0, 0),
  88. fullSize(0, 0),
  89. originalPalette(nullptr)
  90. {
  91. surf = from;
  92. if (surf == nullptr)
  93. return;
  94. savePalette();
  95. surf->refcount++;
  96. fullSize.x = surf->w;
  97. fullSize.y = surf->h;
  98. }
  99. SDLImageShared::SDLImageShared(const ImagePath & filename)
  100. : surf(nullptr),
  101. margins(0, 0),
  102. fullSize(0, 0),
  103. originalPalette(nullptr)
  104. {
  105. surf = BitmapHandler::loadBitmap(filename);
  106. if(surf == nullptr)
  107. {
  108. logGlobal->error("Error: failed to load image %s", filename.getOriginalName());
  109. return;
  110. }
  111. else
  112. {
  113. savePalette();
  114. fullSize.x = surf->w;
  115. fullSize.y = surf->h;
  116. }
  117. }
  118. void SDLImageShared::draw(SDL_Surface * where, SDL_Palette * palette, const Point & dest, const Rect * src, const ColorRGBA & colorMultiplier, uint8_t alpha, EImageBlitMode mode) const
  119. {
  120. if (!surf)
  121. return;
  122. Rect sourceRect(0, 0, surf->w, surf->h);
  123. Point destShift(0, 0);
  124. if(src)
  125. {
  126. if(src->x < margins.x)
  127. destShift.x += margins.x - src->x;
  128. if(src->y < margins.y)
  129. destShift.y += margins.y - src->y;
  130. sourceRect = Rect(*src).intersect(Rect(margins.x, margins.y, surf->w, surf->h));
  131. sourceRect -= margins;
  132. }
  133. else
  134. destShift = margins;
  135. destShift += dest;
  136. SDL_SetSurfaceColorMod(surf, colorMultiplier.r, colorMultiplier.g, colorMultiplier.b);
  137. SDL_SetSurfaceAlphaMod(surf, alpha);
  138. if (alpha != SDL_ALPHA_OPAQUE || (mode != EImageBlitMode::OPAQUE && surf->format->Amask != 0))
  139. SDL_SetSurfaceBlendMode(surf, SDL_BLENDMODE_BLEND);
  140. else
  141. SDL_SetSurfaceBlendMode(surf, SDL_BLENDMODE_NONE);
  142. if (palette && surf->format->palette)
  143. SDL_SetSurfacePalette(surf, palette);
  144. if(surf->format->palette && mode == EImageBlitMode::ALPHA)
  145. {
  146. CSDL_Ext::blit8bppAlphaTo24bpp(surf, sourceRect, where, destShift, alpha);
  147. }
  148. else
  149. {
  150. CSDL_Ext::blitSurface(surf, sourceRect, where, destShift);
  151. }
  152. if (surf->format->palette)
  153. SDL_SetSurfacePalette(surf, originalPalette);
  154. }
  155. std::shared_ptr<ISharedImage> SDLImageShared::scaleFast(const Point & size, SDL_Palette * palette) const
  156. {
  157. float scaleX = float(size.x) / dimensions().x;
  158. float scaleY = float(size.y) / dimensions().y;
  159. if (palette && surf->format->palette)
  160. SDL_SetSurfacePalette(surf, palette);
  161. auto scaled = CSDL_Ext::scaleSurface(surf, (int)(surf->w * scaleX), (int)(surf->h * scaleY));
  162. if (scaled->format && scaled->format->palette) // fix color keying, because SDL loses it at this point
  163. CSDL_Ext::setColorKey(scaled, scaled->format->palette->colors[0]);
  164. else if(scaled->format && scaled->format->Amask)
  165. SDL_SetSurfaceBlendMode(scaled, SDL_BLENDMODE_BLEND);//just in case
  166. else
  167. CSDL_Ext::setDefaultColorKey(scaled);//just in case
  168. auto ret = std::make_shared<SDLImageShared>(scaled);
  169. ret->fullSize.x = (int) round((float)fullSize.x * scaleX);
  170. ret->fullSize.y = (int) round((float)fullSize.y * scaleY);
  171. ret->margins.x = (int) round((float)margins.x * scaleX);
  172. ret->margins.y = (int) round((float)margins.y * scaleY);
  173. // erase our own reference
  174. SDL_FreeSurface(scaled);
  175. if (surf->format->palette)
  176. SDL_SetSurfacePalette(surf, originalPalette);
  177. return ret;
  178. }
  179. void SDLImageShared::exportBitmap(const boost::filesystem::path& path) const
  180. {
  181. SDL_SaveBMP(surf, path.string().c_str());
  182. }
  183. void SDLImageIndexed::playerColored(PlayerColor player)
  184. {
  185. graphics->setPlayerPalette(currentPalette, player);
  186. }
  187. bool SDLImageShared::isTransparent(const Point & coords) const
  188. {
  189. if (surf)
  190. return CSDL_Ext::isTransparent(surf, coords.x, coords.y);
  191. else
  192. return true;
  193. }
  194. Point SDLImageShared::dimensions() const
  195. {
  196. return fullSize;
  197. }
  198. std::shared_ptr<IImage> SDLImageShared::createImageReference(EImageBlitMode mode)
  199. {
  200. if (surf && surf->format->palette)
  201. return std::make_shared<SDLImageIndexed>(shared_from_this(), originalPalette, mode);
  202. else
  203. return std::make_shared<SDLImageRGB>(shared_from_this(), mode);
  204. }
  205. std::shared_ptr<ISharedImage> SDLImageShared::horizontalFlip() const
  206. {
  207. SDL_Surface * flipped = CSDL_Ext::horizontalFlip(surf);
  208. auto ret = std::make_shared<SDLImageShared>(flipped);
  209. ret->fullSize = fullSize;
  210. ret->margins.x = margins.x;
  211. ret->margins.y = fullSize.y - surf->h - margins.y;
  212. ret->fullSize = fullSize;
  213. return ret;
  214. }
  215. std::shared_ptr<ISharedImage> SDLImageShared::verticalFlip() const
  216. {
  217. SDL_Surface * flipped = CSDL_Ext::verticalFlip(surf);
  218. auto ret = std::make_shared<SDLImageShared>(flipped);
  219. ret->fullSize = fullSize;
  220. ret->margins.x = fullSize.x - surf->w - margins.x;
  221. ret->margins.y = margins.y;
  222. ret->fullSize = fullSize;
  223. return ret;
  224. }
  225. // Keep the original palette, in order to do color switching operation
  226. void SDLImageShared::savePalette()
  227. {
  228. // For some images that don't have palette, skip this
  229. if(surf->format->palette == nullptr)
  230. return;
  231. if(originalPalette == nullptr)
  232. originalPalette = SDL_AllocPalette(surf->format->palette->ncolors);
  233. SDL_SetPaletteColors(originalPalette, surf->format->palette->colors, 0, surf->format->palette->ncolors);
  234. }
  235. void SDLImageIndexed::shiftPalette(uint32_t firstColorID, uint32_t colorsToMove, uint32_t distanceToMove)
  236. {
  237. std::vector<SDL_Color> shifterColors(colorsToMove);
  238. for(uint32_t i=0; i<colorsToMove; ++i)
  239. shifterColors[(i+distanceToMove)%colorsToMove] = originalPalette->colors[firstColorID + i];
  240. SDL_SetPaletteColors(currentPalette, shifterColors.data(), firstColorID, colorsToMove);
  241. }
  242. void SDLImageIndexed::adjustPalette(const ColorFilter & shifter, uint32_t colorsToSkipMask)
  243. {
  244. // Note: here we skip first colors in the palette that are predefined in H3 images
  245. for(int i = 0; i < currentPalette->ncolors; i++)
  246. {
  247. if (i < std::size(sourcePalette) && colorsSimilar(sourcePalette[i], originalPalette->colors[i]))
  248. continue;
  249. if(i < std::numeric_limits<uint32_t>::digits && ((colorsToSkipMask >> i) & 1) == 1)
  250. continue;
  251. currentPalette->colors[i] = CSDL_Ext::toSDL(shifter.shiftColor(CSDL_Ext::fromSDL(originalPalette->colors[i])));
  252. }
  253. }
  254. SDLImageIndexed::SDLImageIndexed(const std::shared_ptr<ISharedImage> & image, SDL_Palette * originalPalette, EImageBlitMode mode)
  255. :SDLImageBase::SDLImageBase(image, mode)
  256. ,originalPalette(originalPalette)
  257. {
  258. currentPalette = SDL_AllocPalette(originalPalette->ncolors);
  259. SDL_SetPaletteColors(currentPalette, originalPalette->colors, 0, originalPalette->ncolors);
  260. setOverlayColor(Colors::TRANSPARENCY);
  261. setShadowTransparency(0);
  262. }
  263. SDLImageIndexed::~SDLImageIndexed()
  264. {
  265. SDL_FreePalette(currentPalette);
  266. }
  267. void SDLImageIndexed::setShadowTransparency(float factor)
  268. {
  269. ColorRGBA shadow50(0, 0, 0, 128 * factor);
  270. ColorRGBA shadow25(0, 0, 0, 64 * factor);
  271. // seems to be used unconditionally
  272. currentPalette->colors[1] = CSDL_Ext::toSDL(shadow25);
  273. currentPalette->colors[4] = CSDL_Ext::toSDL(shadow50);
  274. // seems to be used only if color matches
  275. if (colorsSimilar(originalPalette->colors[2], sourcePalette[2]))
  276. currentPalette->colors[2] = CSDL_Ext::toSDL(shadow25);
  277. if (colorsSimilar(originalPalette->colors[3], sourcePalette[3]))
  278. currentPalette->colors[3] = CSDL_Ext::toSDL(shadow50);
  279. }
  280. void SDLImageIndexed::setOverlayColor(const ColorRGBA & color)
  281. {
  282. for (int i : {5,6,7})
  283. {
  284. if (colorsSimilar(originalPalette->colors[i], sourcePalette[i]))
  285. currentPalette->colors[i] = CSDL_Ext::toSDL(addColors(targetPalette[i], color));
  286. }
  287. }
  288. void SDLImageIndexed::setShadowEnabled(bool on)
  289. {
  290. if (on)
  291. setShadowTransparency(1.0);
  292. else
  293. setShadowTransparency(0);
  294. shadowEnabled = on;
  295. }
  296. void SDLImageIndexed::setBodyEnabled(bool on)
  297. {
  298. if (on)
  299. adjustPalette(ColorFilter::genEmptyShifter(), 0);
  300. else
  301. adjustPalette(ColorFilter::genAlphaShifter(0), 0);
  302. bodyEnabled = on;
  303. }
  304. void SDLImageIndexed::setOverlayEnabled(bool on)
  305. {
  306. if (on)
  307. setOverlayColor(Colors::WHITE_TRUE);
  308. else
  309. setOverlayColor(Colors::TRANSPARENCY);
  310. overlayEnabled = on;
  311. }
  312. SDLImageShared::~SDLImageShared()
  313. {
  314. SDL_FreeSurface(surf);
  315. SDL_FreePalette(originalPalette);
  316. }
  317. SDLImageBase::SDLImageBase(const std::shared_ptr<ISharedImage> & image, EImageBlitMode mode)
  318. :image(image)
  319. , alphaValue(SDL_ALPHA_OPAQUE)
  320. , blitMode(mode)
  321. {}
  322. std::shared_ptr<ISharedImage> SDLImageBase::getSharedImage() const
  323. {
  324. return image;
  325. }
  326. void SDLImageRGB::draw(SDL_Surface * where, const Point & pos, const Rect * src) const
  327. {
  328. image->draw(where, nullptr, pos, src, Colors::WHITE_TRUE, alphaValue, blitMode);
  329. }
  330. void SDLImageIndexed::draw(SDL_Surface * where, const Point & pos, const Rect * src) const
  331. {
  332. image->draw(where, currentPalette, pos, src, Colors::WHITE_TRUE, alphaValue, blitMode);
  333. }
  334. void SDLImageIndexed::scaleFast(const Point & size)
  335. {
  336. image = image->scaleFast(size, currentPalette);
  337. }
  338. void SDLImageRGB::scaleFast(const Point & size)
  339. {
  340. image = image->scaleFast(size, nullptr);
  341. }
  342. void SDLImageBase::exportBitmap(const boost::filesystem::path & path) const
  343. {
  344. image->exportBitmap(path);
  345. }
  346. bool SDLImageBase::isTransparent(const Point & coords) const
  347. {
  348. return image->isTransparent(coords);
  349. }
  350. Point SDLImageBase::dimensions() const
  351. {
  352. return image->dimensions();
  353. }
  354. void SDLImageBase::setAlpha(uint8_t value)
  355. {
  356. alphaValue = value;
  357. }
  358. void SDLImageBase::setBlitMode(EImageBlitMode mode)
  359. {
  360. blitMode = mode;
  361. }
  362. void SDLImageRGB::setShadowEnabled(bool on)
  363. {
  364. // Not supported. Theoretically we can try to extract all pixels of specific colors, but better to use 8-bit images or composite images
  365. }
  366. void SDLImageRGB::setBodyEnabled(bool on)
  367. {
  368. // Not supported. Theoretically we can try to extract all pixels of specific colors, but better to use 8-bit images or composite images
  369. }
  370. void SDLImageRGB::setOverlayEnabled(bool on)
  371. {
  372. // Not supported. Theoretically we can try to extract all pixels of specific colors, but better to use 8-bit images or composite images
  373. }
  374. void SDLImageRGB::setOverlayColor(const ColorRGBA & color)
  375. {}
  376. void SDLImageRGB::playerColored(PlayerColor player)
  377. {}
  378. void SDLImageRGB::shiftPalette(uint32_t firstColorID, uint32_t colorsToMove, uint32_t distanceToMove)
  379. {}
  380. void SDLImageRGB::adjustPalette(const ColorFilter & shifter, uint32_t colorsToSkipMask)
  381. {}