SDL_Extensions.cpp 28 KB

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