SDL_Extensions.cpp 26 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016
  1. /*
  2. * SDL_Extensions.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 "SDL_Extensions.h"
  12. #include "SDL_PixelAccess.h"
  13. #include "../GameEngine.h"
  14. #include "../render/Graphics.h"
  15. #include "../render/IImage.h"
  16. #include "../render/IScreenHandler.h"
  17. #include "../render/Colors.h"
  18. #include "../CMT.h"
  19. #include "../xBRZ/xbrz.h"
  20. #include "../../lib/GameConstants.h"
  21. #include <tbb/parallel_for.h>
  22. #include <SDL_render.h>
  23. #include <SDL_surface.h>
  24. #include <SDL_version.h>
  25. Rect CSDL_Ext::fromSDL(const SDL_Rect & rect)
  26. {
  27. return Rect(Point(rect.x, rect.y), Point(rect.w, rect.h));
  28. }
  29. SDL_Rect CSDL_Ext::toSDL(const Rect & rect)
  30. {
  31. SDL_Rect result;
  32. result.x = rect.x;
  33. result.y = rect.y;
  34. result.w = rect.w;
  35. result.h = rect.h;
  36. return result;
  37. }
  38. ColorRGBA CSDL_Ext::fromSDL(const SDL_Color & color)
  39. {
  40. return { color.r, color.g, color.b, color.a };
  41. }
  42. SDL_Color CSDL_Ext::toSDL(const ColorRGBA & color)
  43. {
  44. SDL_Color result;
  45. result.r = color.r;
  46. result.g = color.g;
  47. result.b = color.b;
  48. result.a = color.a;
  49. return result;
  50. }
  51. SDL_Surface * CSDL_Ext::newSurface(const Point & dimensions)
  52. {
  53. return newSurface(dimensions, nullptr);
  54. }
  55. SDL_Surface * CSDL_Ext::newSurface(const Point & dimensions, SDL_Surface * mod) //creates new surface, with flags/format same as in surface given
  56. {
  57. SDL_Surface * ret = nullptr;
  58. if (mod != nullptr)
  59. ret = SDL_CreateRGBSurface(0,dimensions.x,dimensions.y,mod->format->BitsPerPixel,mod->format->Rmask,mod->format->Gmask,mod->format->Bmask,mod->format->Amask);
  60. else
  61. ret = SDL_CreateRGBSurfaceWithFormat(0,dimensions.x,dimensions.y,32,SDL_PixelFormatEnum::SDL_PIXELFORMAT_ARGB8888);
  62. if(ret == nullptr)
  63. {
  64. const char * error = SDL_GetError();
  65. std::string messagePattern = "Failed to create SDL Surface of size %d x %d. Reason: %s";
  66. std::string message = boost::str(boost::format(messagePattern) % dimensions.x % dimensions.y % error);
  67. throw std::runtime_error(message);
  68. }
  69. if (mod && mod->format->palette)
  70. {
  71. assert(ret->format->palette);
  72. assert(ret->format->palette->ncolors >= mod->format->palette->ncolors);
  73. memcpy(ret->format->palette->colors, mod->format->palette->colors, mod->format->palette->ncolors * sizeof(SDL_Color));
  74. }
  75. return ret;
  76. }
  77. void CSDL_Ext::blitAt(SDL_Surface * src, int x, int y, SDL_Surface * dst)
  78. {
  79. CSDL_Ext::blitSurface(src, dst, Point(x, y));
  80. }
  81. void CSDL_Ext::blitAt(SDL_Surface * src, const Rect & pos, SDL_Surface * dst)
  82. {
  83. if (src)
  84. blitAt(src,pos.x,pos.y,dst);
  85. }
  86. // Vertical flip
  87. SDL_Surface * CSDL_Ext::verticalFlip(SDL_Surface * toRot)
  88. {
  89. SDL_Surface * ret = SDL_ConvertSurface(toRot, toRot->format, toRot->flags);
  90. SDL_LockSurface(ret);
  91. SDL_LockSurface(toRot);
  92. const int bpp = ret->format->BytesPerPixel;
  93. char * src = reinterpret_cast<char *>(toRot->pixels);
  94. char * dst = reinterpret_cast<char *>(ret->pixels);
  95. for(int i=0; i<ret->h; i++)
  96. {
  97. //FIXME: optimization bugged
  98. // if (bpp == 1)
  99. // {
  100. // // much faster for 8-bit surfaces (majority of our data)
  101. // std::reverse_copy(src, src + toRot->pitch, dst);
  102. // }
  103. // else
  104. // {
  105. char * srcPxl = src;
  106. char * dstPxl = dst + ret->w * bpp;
  107. for(int j=0; j<ret->w; j++)
  108. {
  109. dstPxl -= bpp;
  110. std::copy(srcPxl, srcPxl + bpp, dstPxl);
  111. srcPxl += bpp;
  112. }
  113. // }
  114. src += toRot->pitch;
  115. dst += ret->pitch;
  116. }
  117. SDL_UnlockSurface(ret);
  118. SDL_UnlockSurface(toRot);
  119. return ret;
  120. }
  121. // Horizontal flip
  122. SDL_Surface * CSDL_Ext::horizontalFlip(SDL_Surface * toRot)
  123. {
  124. SDL_Surface * ret = SDL_ConvertSurface(toRot, toRot->format, toRot->flags);
  125. SDL_LockSurface(ret);
  126. SDL_LockSurface(toRot);
  127. char * src = reinterpret_cast<char *>(toRot->pixels);
  128. char * dst = reinterpret_cast<char *>(ret->pixels) + ret->h * ret->pitch;
  129. for(int i=0; i<ret->h; i++)
  130. {
  131. dst -= ret->pitch;
  132. std::copy(src, src + toRot->pitch, dst);
  133. src += toRot->pitch;
  134. }
  135. SDL_UnlockSurface(ret);
  136. SDL_UnlockSurface(toRot);
  137. return ret;
  138. }
  139. uint32_t CSDL_Ext::getPixel(SDL_Surface *surface, const int & x, const int & y, bool colorByte)
  140. {
  141. int bpp = surface->format->BytesPerPixel;
  142. /* Here p is the address to the pixel we want to retrieve */
  143. uint8_t *p = (uint8_t *)surface->pixels + y * surface->pitch + x * bpp;
  144. switch(bpp)
  145. {
  146. case 1:
  147. if(colorByte)
  148. return colorTouint32_t(surface->format->palette->colors+(*p));
  149. else
  150. return *p;
  151. case 2:
  152. return *(uint16_t *)p;
  153. case 3:
  154. return p[0] | p[1] << 8 | p[2] << 16;
  155. case 4:
  156. return *(uint32_t *)p;
  157. default:
  158. return 0; // shouldn't happen, but avoids warnings
  159. }
  160. }
  161. template<int bpp, bool useAlpha>
  162. int CSDL_Ext::blit8bppAlphaTo24bppT(const SDL_Surface * src, const Rect & srcRectInput, SDL_Surface * dst, const Point & dstPointInput, [[maybe_unused]] uint8_t alpha)
  163. {
  164. SDL_Rect srcRectInstance = CSDL_Ext::toSDL(srcRectInput);
  165. SDL_Rect dstRectInstance = CSDL_Ext::toSDL(Rect(dstPointInput, srcRectInput.dimensions()));
  166. SDL_Rect * srcRect =&srcRectInstance;
  167. SDL_Rect * dstRect =&dstRectInstance;
  168. /* Make sure the surfaces aren't locked */
  169. if ( ! src || ! dst )
  170. {
  171. SDL_SetError("SDL_UpperBlit: passed a nullptr surface");
  172. return -1;
  173. }
  174. if ( src->locked || dst->locked )
  175. {
  176. SDL_SetError("Surfaces must not be locked during blit");
  177. return -1;
  178. }
  179. if (src->format->BytesPerPixel==1 && (bpp==3 || bpp==4 || bpp==2)) //everything's ok
  180. {
  181. SDL_Rect fulldst;
  182. int srcx;
  183. int srcy;
  184. int w;
  185. int h;
  186. /* If the destination rectangle is nullptr, use the entire dest surface */
  187. if ( dstRect == nullptr )
  188. {
  189. fulldst.x = fulldst.y = 0;
  190. dstRect = &fulldst;
  191. }
  192. /* clip the source rectangle to the source surface */
  193. if(srcRect)
  194. {
  195. int maxw;
  196. int maxh;
  197. srcx = srcRect->x;
  198. w = srcRect->w;
  199. if(srcx < 0)
  200. {
  201. w += srcx;
  202. dstRect->x -= srcx;
  203. srcx = 0;
  204. }
  205. maxw = src->w - srcx;
  206. if(maxw < w)
  207. w = maxw;
  208. srcy = srcRect->y;
  209. h = srcRect->h;
  210. if(srcy < 0)
  211. {
  212. h += srcy;
  213. dstRect->y -= srcy;
  214. srcy = 0;
  215. }
  216. maxh = src->h - srcy;
  217. if(maxh < h)
  218. h = maxh;
  219. }
  220. else
  221. {
  222. srcx = srcy = 0;
  223. w = src->w;
  224. h = src->h;
  225. }
  226. /* clip the destination rectangle against the clip rectangle */
  227. {
  228. SDL_Rect *clip = &dst->clip_rect;
  229. int dx;
  230. int dy;
  231. dx = clip->x - dstRect->x;
  232. if(dx > 0)
  233. {
  234. w -= dx;
  235. dstRect->x += dx;
  236. srcx += dx;
  237. }
  238. dx = dstRect->x + w - clip->x - clip->w;
  239. if(dx > 0)
  240. w -= dx;
  241. dy = clip->y - dstRect->y;
  242. if(dy > 0)
  243. {
  244. h -= dy;
  245. dstRect->y += dy;
  246. srcy += dy;
  247. }
  248. dy = dstRect->y + h - clip->y - clip->h;
  249. if(dy > 0)
  250. h -= dy;
  251. }
  252. if(w > 0 && h > 0)
  253. {
  254. dstRect->w = w;
  255. dstRect->h = h;
  256. if(SDL_LockSurface(dst))
  257. return -1; //if we cannot lock the surface
  258. const SDL_Color *colors = src->format->palette->colors;
  259. uint8_t *colory = (uint8_t*)src->pixels + srcy*src->pitch + srcx;
  260. uint8_t *py = (uint8_t*)dst->pixels + dstRect->y*dst->pitch + dstRect->x*bpp;
  261. for(int y=0; y<h; ++y, colory+=src->pitch, py+=dst->pitch)
  262. {
  263. uint8_t *color = colory;
  264. uint8_t *p = py;
  265. for(int x = 0; x < w; ++x)
  266. {
  267. const SDL_Color &tbc = colors[*color++]; //color to blit
  268. if constexpr (useAlpha)
  269. ColorPutter<bpp>::PutColorAlphaSwitch(p, tbc.r, tbc.g, tbc.b, int(alpha) * tbc.a / 255 );
  270. else
  271. ColorPutter<bpp>::PutColorAlphaSwitch(p, tbc.r, tbc.g, tbc.b, tbc.a);
  272. p += bpp;
  273. }
  274. }
  275. SDL_UnlockSurface(dst);
  276. }
  277. }
  278. return 0;
  279. }
  280. int CSDL_Ext::blit8bppAlphaTo24bpp(const SDL_Surface * src, const Rect & srcRect, SDL_Surface * dst, const Point & dstPoint, uint8_t alpha)
  281. {
  282. if (alpha == SDL_ALPHA_OPAQUE)
  283. {
  284. switch(dst->format->BytesPerPixel)
  285. {
  286. case 3: return blit8bppAlphaTo24bppT<3, false>(src, srcRect, dst, dstPoint, alpha);
  287. case 4: return blit8bppAlphaTo24bppT<4, false>(src, srcRect, dst, dstPoint, alpha);
  288. }
  289. }
  290. else
  291. {
  292. switch(dst->format->BytesPerPixel)
  293. {
  294. case 3: return blit8bppAlphaTo24bppT<3, true>(src, srcRect, dst, dstPoint, alpha);
  295. case 4: return blit8bppAlphaTo24bppT<4, true>(src, srcRect, dst, dstPoint, alpha);
  296. }
  297. }
  298. logGlobal->error("%d bpp is not supported!", (int)dst->format->BitsPerPixel);
  299. return -1;
  300. }
  301. uint32_t CSDL_Ext::colorTouint32_t(const SDL_Color * color)
  302. {
  303. uint32_t ret = 0;
  304. ret+=color->a;
  305. ret<<=8; //*=256
  306. ret+=color->b;
  307. ret<<=8; //*=256
  308. ret+=color->g;
  309. ret<<=8; //*=256
  310. ret+=color->r;
  311. return ret;
  312. }
  313. static void drawLineXDashed(SDL_Surface * sur, int x1, int y1, int x2, int y2, const SDL_Color & color)
  314. {
  315. double length(x2 - x1);
  316. for(int x = x1; x <= x2; x++)
  317. {
  318. double f = (x - x1) / length;
  319. int y = vstd::lerp(y1, y2, f);
  320. if (std::abs(x - x1) % 5 != 4)
  321. CSDL_Ext::putPixelWithoutRefreshIfInSurf(sur, x, y, color.r, color.g, color.b);
  322. }
  323. }
  324. static void drawLineYDashed(SDL_Surface * sur, int x1, int y1, int x2, int y2, const SDL_Color & color)
  325. {
  326. double length(y2 - y1);
  327. for(int y = y1; y <= y2; y++)
  328. {
  329. double f = (y - y1) / length;
  330. int x = vstd::lerp(x1, x2, f);
  331. if (std::abs(y - y1) % 5 != 4)
  332. CSDL_Ext::putPixelWithoutRefreshIfInSurf(sur, x, y, color.r, color.g, color.b);
  333. }
  334. }
  335. static void drawLineX(SDL_Surface * sur, int x1, int y1, int x2, int y2, const SDL_Color & color1, const SDL_Color & color2)
  336. {
  337. double length(x2 - x1);
  338. for(int x = x1; x <= x2; x++)
  339. {
  340. double f = (x - x1) / length;
  341. int y = vstd::lerp(y1, y2, f);
  342. uint8_t r = vstd::lerp(color1.r, color2.r, f);
  343. uint8_t g = vstd::lerp(color1.g, color2.g, f);
  344. uint8_t b = vstd::lerp(color1.b, color2.b, f);
  345. uint8_t a = vstd::lerp(color1.a, color2.a, f);
  346. uint8_t *p = CSDL_Ext::getPxPtr(sur, x, y);
  347. ColorPutter<4>::PutColor(p, r,g,b,a);
  348. }
  349. }
  350. static void drawLineY(SDL_Surface * sur, int x1, int y1, int x2, int y2, const SDL_Color & color1, const SDL_Color & color2)
  351. {
  352. double length(y2 - y1);
  353. for(int y = y1; y <= y2; y++)
  354. {
  355. double f = (y - y1) / length;
  356. int x = vstd::lerp(x1, x2, f);
  357. uint8_t r = vstd::lerp(color1.r, color2.r, f);
  358. uint8_t g = vstd::lerp(color1.g, color2.g, f);
  359. uint8_t b = vstd::lerp(color1.b, color2.b, f);
  360. uint8_t a = vstd::lerp(color1.a, color2.a, f);
  361. uint8_t *p = CSDL_Ext::getPxPtr(sur, x, y);
  362. ColorPutter<4>::PutColor(p, r,g,b,a);
  363. }
  364. }
  365. void CSDL_Ext::drawLine(SDL_Surface * sur, const Point & from, const Point & dest, const SDL_Color & color1, const SDL_Color & color2, int thickness)
  366. {
  367. //FIXME: duplicated code with drawLineDashed
  368. int width = std::abs(from.x - dest.x);
  369. int height = std::abs(from.y - dest.y);
  370. if(width == 0 && height == 0)
  371. {
  372. uint8_t * p = CSDL_Ext::getPxPtr(sur, from.x, from.y);
  373. ColorPutter<4>::PutColorAlpha(p, color1);
  374. return;
  375. }
  376. for(int i = 0; i < thickness; ++i)
  377. {
  378. if(width > height)
  379. {
  380. if(from.x < dest.x)
  381. drawLineX(sur, from.x, from.y + i, dest.x, dest.y + i, color1, color2);
  382. else
  383. drawLineX(sur, dest.x, dest.y + i, from.x, from.y + i, color2, color1);
  384. }
  385. else
  386. {
  387. if(from.y < dest.y)
  388. drawLineY(sur, from.x + i, from.y, dest.x + i, dest.y, color1, color2);
  389. else
  390. drawLineY(sur, dest.x + i, dest.y, from.x + i, from.y, color2, color1);
  391. }
  392. }
  393. }
  394. void CSDL_Ext::drawLineDashed(SDL_Surface * sur, const Point & from, const Point & dest, const SDL_Color & color)
  395. {
  396. //FIXME: duplicated code with drawLine
  397. int width = std::abs(from.x - dest.x);
  398. int height = std::abs(from.y - dest.y);
  399. if ( width == 0 && height == 0)
  400. {
  401. CSDL_Ext::putPixelWithoutRefreshIfInSurf(sur, from.x, from.y, color.r, color.g, color.b);
  402. return;
  403. }
  404. if (width > height)
  405. {
  406. if ( from.x < dest.x)
  407. drawLineXDashed(sur, from.x, from.y, dest.x, dest.y, color);
  408. else
  409. drawLineXDashed(sur, dest.x, dest.y, from.x, from.y, color);
  410. }
  411. else
  412. {
  413. if ( from.y < dest.y)
  414. drawLineYDashed(sur, from.x, from.y, dest.x, dest.y, color);
  415. else
  416. drawLineYDashed(sur, dest.x, dest.y, from.x, from.y, color);
  417. }
  418. }
  419. void CSDL_Ext::drawBorder(SDL_Surface * sur, int x, int y, int w, int h, const SDL_Color &color, int depth)
  420. {
  421. depth = std::max(1, depth);
  422. for(int depthIterator = 0; depthIterator < depth; depthIterator++)
  423. {
  424. for(int i = 0; i < w; i++)
  425. {
  426. CSDL_Ext::putPixelWithoutRefreshIfInSurf(sur,x+i,y+depthIterator,color.r,color.g,color.b);
  427. CSDL_Ext::putPixelWithoutRefreshIfInSurf(sur,x+i,y+h-1-depthIterator,color.r,color.g,color.b);
  428. }
  429. for(int i = 0; i < h; i++)
  430. {
  431. CSDL_Ext::putPixelWithoutRefreshIfInSurf(sur,x+depthIterator,y+i,color.r,color.g,color.b);
  432. CSDL_Ext::putPixelWithoutRefreshIfInSurf(sur,x+w-1-depthIterator,y+i,color.r,color.g,color.b);
  433. }
  434. }
  435. }
  436. void CSDL_Ext::drawBorder( SDL_Surface * sur, const Rect &r, const SDL_Color &color, int depth)
  437. {
  438. drawBorder(sur, r.x, r.y, r.w, r.h, color, depth);
  439. }
  440. uint8_t * CSDL_Ext::getPxPtr(const SDL_Surface * const &srf, const int x, const int y)
  441. {
  442. return (uint8_t *)srf->pixels + y * srf->pitch + x * srf->format->BytesPerPixel;
  443. }
  444. void CSDL_Ext::putPixelWithoutRefresh(SDL_Surface *ekran, const int & x, const int & y, const uint8_t & R, const uint8_t & G, const uint8_t & B, uint8_t A)
  445. {
  446. uint8_t *p = getPxPtr(ekran, x, y);
  447. switch(ekran->format->BytesPerPixel)
  448. {
  449. case 3:
  450. ColorPutter<3>::PutColor(p, R, G, B);
  451. Channels::px<3>::a.set(p, A); break;
  452. case 4:
  453. ColorPutter<4>::PutColor(p, R, G, B);
  454. Channels::px<4>::a.set(p, A); break;
  455. }
  456. }
  457. void CSDL_Ext::putPixelWithoutRefreshIfInSurf(SDL_Surface *ekran, const int & x, const int & y, const uint8_t & R, const uint8_t & G, const uint8_t & B, uint8_t A)
  458. {
  459. const SDL_Rect & rect = ekran->clip_rect;
  460. if(x >= rect.x && x < rect.w + rect.x
  461. && y >= rect.y && y < rect.h + rect.y)
  462. CSDL_Ext::putPixelWithoutRefresh(ekran, x, y, R, G, B, A);
  463. }
  464. template<typename Functor>
  465. void loopOverPixel(SDL_Surface * surf, const Rect & rect, Functor functor)
  466. {
  467. uint8_t * pixels = static_cast<uint8_t*>(surf->pixels);
  468. tbb::parallel_for(tbb::blocked_range<size_t>(rect.top(), rect.bottom()), [&](const tbb::blocked_range<size_t>& r)
  469. {
  470. for(int yp = r.begin(); yp != r.end(); ++yp)
  471. {
  472. uint8_t * pixel_from = pixels + yp * surf->pitch + rect.left() * surf->format->BytesPerPixel;
  473. uint8_t * pixel_dest = pixels + yp * surf->pitch + rect.right() * surf->format->BytesPerPixel;
  474. for (uint8_t * pixel = pixel_from; pixel < pixel_dest; pixel += surf->format->BytesPerPixel)
  475. {
  476. int r = Channels::px<4>::r.get(pixel);
  477. int g = Channels::px<4>::g.get(pixel);
  478. int b = Channels::px<4>::b.get(pixel);
  479. functor(r, g, b);
  480. Channels::px<4>::r.set(pixel, r);
  481. Channels::px<4>::g.set(pixel, g);
  482. Channels::px<4>::b.set(pixel, b);
  483. }
  484. }
  485. });
  486. }
  487. void CSDL_Ext::convertToGrayscale(SDL_Surface * surf, const Rect & rect )
  488. {
  489. loopOverPixel(surf, rect, [](int &r, int &g, int &b){
  490. int gray = static_cast<int>(0.299 * r + 0.587 * g + 0.114 * b);
  491. r = gray;
  492. g = gray;
  493. b = gray;
  494. });
  495. }
  496. void CSDL_Ext::convertToH2Scheme(SDL_Surface * surf, const Rect & rect )
  497. {
  498. loopOverPixel(surf, rect, [](int &r, int &g, int &b){
  499. double gray = 0.3 * r + 0.59 * g + 0.11 * b;
  500. double factor = 2.0;
  501. //fast approximation instead of colorspace conversion
  502. r = static_cast<int>(gray + (r - gray) * factor);
  503. g = static_cast<int>(gray + (g - gray) * factor);
  504. b = static_cast<int>(gray + (b - gray) * factor);
  505. r = std::clamp(r, 0, 255);
  506. g = std::clamp(g, 0, 255);
  507. b = std::clamp(b, 0, 255);
  508. });
  509. }
  510. void CSDL_Ext::blitSurface(SDL_Surface * src, const Rect & srcRectInput, SDL_Surface * dst, const Point & dstPoint)
  511. {
  512. SDL_Rect srcRect = CSDL_Ext::toSDL(srcRectInput);
  513. SDL_Rect dstRect = CSDL_Ext::toSDL(Rect(dstPoint, srcRectInput.dimensions()));
  514. int result = SDL_UpperBlit(src, &srcRect, dst, &dstRect);
  515. if (result != 0)
  516. logGlobal->error("SDL_UpperBlit failed! %s", SDL_GetError());
  517. }
  518. void CSDL_Ext::blitSurface(SDL_Surface * src, SDL_Surface * dst, const Point & dest)
  519. {
  520. Rect allSurface( Point(0,0), Point(src->w, src->h));
  521. blitSurface(src, allSurface, dst, dest);
  522. }
  523. void CSDL_Ext::fillSurface( SDL_Surface *dst, const SDL_Color & color )
  524. {
  525. Rect allSurface( Point(0,0), Point(dst->w, dst->h));
  526. fillRect(dst, allSurface, color);
  527. }
  528. void CSDL_Ext::fillRect( SDL_Surface *dst, const Rect & dstrect, const SDL_Color & color)
  529. {
  530. SDL_Rect newRect = CSDL_Ext::toSDL(dstrect);
  531. uint32_t sdlColor = SDL_MapRGBA(dst->format, color.r, color.g, color.b, color.a);
  532. SDL_FillRect(dst, &newRect, sdlColor);
  533. }
  534. void CSDL_Ext::fillRectBlended( SDL_Surface *dst, const Rect & dstrect, const SDL_Color & color)
  535. {
  536. SDL_Rect newRect = CSDL_Ext::toSDL(dstrect);
  537. uint32_t sdlColor = SDL_MapRGBA(dst->format, color.r, color.g, color.b, color.a);
  538. SDL_Surface * tmp = SDL_CreateRGBSurface(0, newRect.w, newRect.h, dst->format->BitsPerPixel, dst->format->Rmask, dst->format->Gmask, dst->format->Bmask, dst->format->Amask);
  539. SDL_FillRect(tmp, nullptr, sdlColor);
  540. SDL_BlitSurface(tmp, nullptr, dst, &newRect);
  541. SDL_FreeSurface(tmp);
  542. }
  543. STRONG_INLINE static uint32_t mapColor(SDL_Surface * surface, SDL_Color color)
  544. {
  545. return SDL_MapRGBA(surface->format, color.r, color.g, color.b, color.a);
  546. }
  547. void CSDL_Ext::setColorKey(SDL_Surface * surface, SDL_Color color)
  548. {
  549. uint32_t key = mapColor(surface,color);
  550. SDL_SetColorKey(surface, SDL_TRUE, key);
  551. }
  552. void CSDL_Ext::setDefaultColorKey(SDL_Surface * surface)
  553. {
  554. setColorKey(surface, toSDL(Colors::DEFAULT_KEY_COLOR));
  555. }
  556. void CSDL_Ext::setDefaultColorKeyPresize(SDL_Surface * surface)
  557. {
  558. uint32_t key = mapColor(surface, toSDL(Colors::DEFAULT_KEY_COLOR));
  559. auto & color = surface->format->palette->colors[key];
  560. // set color key only if exactly such color was found
  561. if (color.r == Colors::DEFAULT_KEY_COLOR.r && color.g == Colors::DEFAULT_KEY_COLOR.g && color.b == Colors::DEFAULT_KEY_COLOR.b)
  562. {
  563. SDL_SetColorKey(surface, SDL_TRUE, key);
  564. color.a = SDL_ALPHA_TRANSPARENT;
  565. }
  566. }
  567. void CSDL_Ext::setClipRect(SDL_Surface * src, const Rect & other)
  568. {
  569. SDL_Rect rect = CSDL_Ext::toSDL(other);
  570. SDL_SetClipRect(src, &rect);
  571. }
  572. void CSDL_Ext::getClipRect(SDL_Surface * src, Rect & other)
  573. {
  574. SDL_Rect rect;
  575. SDL_GetClipRect(src, &rect);
  576. other = CSDL_Ext::fromSDL(rect);
  577. }
  578. SDL_Surface* CSDL_Ext::drawOutline(SDL_Surface* source, const SDL_Color& color, int thickness)
  579. {
  580. if(thickness < 1)
  581. return nullptr;
  582. SDL_Surface* sourceSurface = SDL_ConvertSurfaceFormat(source, SDL_PIXELFORMAT_ARGB8888, 0);
  583. SDL_Surface* destSurface = newSurface(Point(source->w, source->h));
  584. if(SDL_MUSTLOCK(sourceSurface)) SDL_LockSurface(sourceSurface);
  585. if(SDL_MUSTLOCK(destSurface)) SDL_LockSurface(destSurface);
  586. int width = sourceSurface->w;
  587. int height = sourceSurface->h;
  588. // Helper lambda to get alpha
  589. auto getAlpha = [&](int x, int y) -> Uint8 {
  590. if (x < 0 || x >= width || y < 0 || y >= height)
  591. return 0;
  592. Uint32 pixel = *((Uint32*)sourceSurface->pixels + y * width + x);
  593. Uint8 r, g, b, a;
  594. SDL_GetRGBA(pixel, sourceSurface->format, &r, &g, &b, &a);
  595. return a;
  596. };
  597. // Go through all transparent pixels and check if they border an opaque region
  598. for(int y = 0; y < height; y++)
  599. {
  600. for(int x = 0; x < width; x++)
  601. {
  602. if(getAlpha(x, y) != 0)
  603. continue; // Skip opaque pixels
  604. bool isOutline = false;
  605. for(int dy = -thickness; dy <= thickness && !isOutline; ++dy)
  606. {
  607. for(int dx = -thickness; dx <= thickness; ++dx)
  608. {
  609. // circular neighborhood
  610. if(dx * dx + dy * dy > thickness * thickness)
  611. continue;
  612. if(getAlpha(x + dx, y + dy) > 0)
  613. {
  614. isOutline = true;
  615. break; // break inner loop only
  616. }
  617. }
  618. }
  619. if(isOutline)
  620. {
  621. Uint32 newPixel = SDL_MapRGBA(destSurface->format, color.r, color.g, color.b, color.a);
  622. *((Uint32*)destSurface->pixels + y * width + x) = newPixel;
  623. }
  624. }
  625. }
  626. if(SDL_MUSTLOCK(sourceSurface)) SDL_UnlockSurface(sourceSurface);
  627. if(SDL_MUSTLOCK(destSurface)) SDL_UnlockSurface(destSurface);
  628. SDL_FreeSurface(sourceSurface);
  629. return destSurface;
  630. }
  631. void applyAffineTransform(SDL_Surface* src, SDL_Surface* dst, double a, double b, double c, double d, double tx, double ty)
  632. {
  633. assert(src->format->format == SDL_PIXELFORMAT_ARGB8888);
  634. assert(dst->format->format == SDL_PIXELFORMAT_ARGB8888);
  635. // Lock surfaces for direct pixel access
  636. if (SDL_MUSTLOCK(src)) SDL_LockSurface(src);
  637. if (SDL_MUSTLOCK(dst)) SDL_LockSurface(dst);
  638. // Calculate inverse matrix M_inv for mapping dst -> src
  639. double det = a * d - b * c;
  640. if (std::abs(det) < 1e-10)
  641. throw std::runtime_error("Singular transform matrix!");
  642. double invDet = 1.0 / det;
  643. double ia = d * invDet;
  644. double ib = -b * invDet;
  645. double ic = -c * invDet;
  646. double id = a * invDet;
  647. // For each pixel in the destination image
  648. for(int y = 0; y < dst->h; y++)
  649. {
  650. for(int x = 0; x < dst->w; x++)
  651. {
  652. // Map destination pixel (x,y) back to source coordinates (srcX, srcY)
  653. double srcX = ia * (x - tx) + ib * (y - ty);
  654. double srcY = ic * (x - tx) + id * (y - ty);
  655. // Nearest neighbor sampling (can be improved to bilinear)
  656. auto srcXi = static_cast<int>(round(srcX));
  657. auto srcYi = static_cast<int>(round(srcY));
  658. // Check bounds
  659. if (srcXi >= 0 && srcXi < src->w && srcYi >= 0 && srcYi < src->h)
  660. {
  661. auto srcPixels = (Uint32*)src->pixels;
  662. auto dstPixels = (Uint32*)dst->pixels;
  663. Uint32 pixel = srcPixels[srcYi * src->w + srcXi];
  664. dstPixels[y * dst->w + x] = pixel;
  665. }
  666. else
  667. {
  668. // Outside source bounds: set transparent or black
  669. auto dstPixels = (Uint32*)dst->pixels;
  670. dstPixels[y * dst->w + x] = 0x00000000; // transparent black
  671. }
  672. }
  673. }
  674. if (SDL_MUSTLOCK(src)) SDL_UnlockSurface(src);
  675. if (SDL_MUSTLOCK(dst)) SDL_UnlockSurface(dst);
  676. }
  677. int getLowestNonTransparentY(SDL_Surface* surface)
  678. {
  679. assert(surface->format->format == SDL_PIXELFORMAT_ARGB8888);
  680. if(SDL_MUSTLOCK(surface)) SDL_LockSurface(surface);
  681. int w = surface->w;
  682. int h = surface->h;
  683. int bpp = surface->format->BytesPerPixel;
  684. auto pixels = (Uint8*)surface->pixels;
  685. for(int y = h - 1; y >= 0; --y)
  686. {
  687. Uint8* row = pixels + y * surface->pitch;
  688. for(int x = 0; x < w; ++x)
  689. {
  690. Uint32 pixel = *(Uint32*)(row + x * bpp);
  691. Uint8 r;
  692. Uint8 g;
  693. Uint8 b;
  694. Uint8 a;
  695. SDL_GetRGBA(pixel, surface->format, &r, &g, &b, &a);
  696. if (a > 0)
  697. {
  698. if(SDL_MUSTLOCK(surface))
  699. SDL_UnlockSurface(surface);
  700. return y;
  701. }
  702. }
  703. }
  704. if (SDL_MUSTLOCK(surface)) SDL_UnlockSurface(surface);
  705. return -1; // fully transparent
  706. }
  707. void fillAlphaPixelWithRGBA(SDL_Surface* surface, Uint8 r, Uint8 g, Uint8 b, Uint8 a)
  708. {
  709. assert(surface->format->format == SDL_PIXELFORMAT_ARGB8888);
  710. if (SDL_MUSTLOCK(surface)) SDL_LockSurface(surface);
  711. auto pixels = (Uint32*)surface->pixels;
  712. int pixelCount = surface->w * surface->h;
  713. for (int i = 0; i < pixelCount; i++)
  714. {
  715. Uint32 pixel = pixels[i];
  716. Uint8 pr;
  717. Uint8 pg;
  718. Uint8 pb;
  719. Uint8 pa;
  720. // Extract existing RGBA components using SDL_GetRGBA
  721. SDL_GetRGBA(pixel, surface->format, &pr, &pg, &pb, &pa);
  722. Uint32 newPixel = SDL_MapRGBA(surface->format, r, g, b, a);
  723. if(pa == 0)
  724. newPixel = SDL_MapRGBA(surface->format, 0, 0, 0, 0);
  725. pixels[i] = newPixel;
  726. }
  727. if (SDL_MUSTLOCK(surface)) SDL_UnlockSurface(surface);
  728. }
  729. void gaussianBlur(SDL_Surface* surface, int amount)
  730. {
  731. assert(surface->format->format == SDL_PIXELFORMAT_ARGB8888);
  732. if (!surface || amount <= 0) return;
  733. if (SDL_MUSTLOCK(surface)) SDL_LockSurface(surface);
  734. int width = surface->w;
  735. int height = surface->h;
  736. int pixelCount = width * height;
  737. auto pixels = static_cast<Uint32*>(surface->pixels);
  738. std::vector<Uint8> srcR(pixelCount);
  739. std::vector<Uint8> srcG(pixelCount);
  740. std::vector<Uint8> srcB(pixelCount);
  741. std::vector<Uint8> srcA(pixelCount);
  742. std::vector<Uint8> dstR(pixelCount);
  743. std::vector<Uint8> dstG(pixelCount);
  744. std::vector<Uint8> dstB(pixelCount);
  745. std::vector<Uint8> dstA(pixelCount);
  746. // Initialize src channels from surface pixels
  747. for (int y = 0; y < height; ++y)
  748. {
  749. for (int x = 0; x < width; ++x)
  750. {
  751. Uint32 pixel = pixels[y * width + x];
  752. Uint8 r;
  753. Uint8 g;
  754. Uint8 b;
  755. Uint8 a;
  756. SDL_GetRGBA(pixel, surface->format, &r, &g, &b, &a);
  757. int idx = y * width + x;
  758. srcR[idx] = r;
  759. srcG[idx] = g;
  760. srcB[idx] = b;
  761. srcA[idx] = a;
  762. }
  763. }
  764. // 3x3 Gaussian kernel
  765. std::array<std::array<float, 3>, 3> kernel = {{
  766. {{1.f/16, 2.f/16, 1.f/16}},
  767. {{2.f/16, 4.f/16, 2.f/16}},
  768. {{1.f/16, 2.f/16, 1.f/16}}
  769. }};
  770. // Apply the blur 'amount' times for stronger blur
  771. for (int iteration = 0; iteration < amount; ++iteration)
  772. {
  773. for (int y = 0; y < height; ++y)
  774. {
  775. for (int x = 0; x < width; ++x)
  776. {
  777. float sumR = 0.f;
  778. float sumG = 0.f;
  779. float sumB = 0.f;
  780. float sumA = 0.f;
  781. for (int ky = -1; ky <= 1; ++ky)
  782. {
  783. for (int kx = -1; kx <= 1; ++kx)
  784. {
  785. int nx = x + kx;
  786. int ny = y + ky;
  787. // Clamp edges
  788. if (nx < 0) nx = 0;
  789. else if (nx >= width) nx = width - 1;
  790. if (ny < 0) ny = 0;
  791. else if (ny >= height) ny = height - 1;
  792. int nIdx = ny * width + nx;
  793. float kval = kernel[ky + 1][kx + 1];
  794. sumR += srcR[nIdx] * kval;
  795. sumG += srcG[nIdx] * kval;
  796. sumB += srcB[nIdx] * kval;
  797. sumA += srcA[nIdx] * kval;
  798. }
  799. }
  800. int idx = y * width + x;
  801. dstR[idx] = static_cast<Uint8>(sumR);
  802. dstG[idx] = static_cast<Uint8>(sumG);
  803. dstB[idx] = static_cast<Uint8>(sumB);
  804. dstA[idx] = static_cast<Uint8>(sumA);
  805. }
  806. }
  807. // Swap src and dst for next iteration (blur chaining)
  808. srcR.swap(dstR);
  809. srcG.swap(dstG);
  810. srcB.swap(dstB);
  811. srcA.swap(dstA);
  812. }
  813. // After final iteration, write back to surface pixels
  814. for (int y = 0; y < height; ++y)
  815. {
  816. for (int x = 0; x < width; ++x)
  817. {
  818. int idx = y * width + x;
  819. pixels[idx] = SDL_MapRGBA(surface->format, srcR[idx], srcG[idx], srcB[idx], srcA[idx]);
  820. }
  821. }
  822. if (SDL_MUSTLOCK(surface)) SDL_UnlockSurface(surface);
  823. }
  824. SDL_Surface * CSDL_Ext::drawShadow(SDL_Surface * source, bool doSheer)
  825. {
  826. SDL_Surface *sourceSurface = SDL_ConvertSurfaceFormat(source, SDL_PIXELFORMAT_ARGB8888, 0);
  827. SDL_Surface *destSurface = newSurface(Point(source->w, source->h));
  828. assert(destSurface->format->format == SDL_PIXELFORMAT_ARGB8888);
  829. double shearX = doSheer ? 0.5 : 0.0;
  830. double scaleY = doSheer ? 0.5 : 0.25;
  831. int lowestSource = getLowestNonTransparentY(sourceSurface);
  832. int lowestTransformed = lowestSource * scaleY;
  833. // Parameters for applyAffineTransform
  834. double a = 1.0;
  835. double b = shearX;
  836. double c = 0.0;
  837. double d = scaleY;
  838. double tx = -shearX * lowestSource;
  839. double ty = lowestSource - lowestTransformed;
  840. applyAffineTransform(sourceSurface, destSurface, a, b, c, d, tx, ty);
  841. fillAlphaPixelWithRGBA(destSurface, 0, 0, 0, 128);
  842. gaussianBlur(destSurface, 1);
  843. SDL_FreeSurface(sourceSurface);
  844. return destSurface;
  845. }