CAnimation.cpp 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562
  1. #include "StdInc.h"
  2. #include "CAnimation.h"
  3. #include <SDL_image.h>
  4. #include "../CBitmapHandler.h"
  5. #include "../Graphics.h"
  6. #include "../gui/SDL_Extensions.h"
  7. #include "../gui/SDL_Pixels.h"
  8. #include "../lib/filesystem/Filesystem.h"
  9. #include "../lib/filesystem/ISimpleResourceLoader.h"
  10. #include "../lib/JsonNode.h"
  11. #include "../lib/CRandomGenerator.h"
  12. /*
  13. * CAnimation.cpp, part of VCMI engine
  14. *
  15. * Authors: listed in file AUTHORS in main folder
  16. *
  17. * License: GNU General Public License v2.0 or later
  18. * Full text of license available in license.txt file, in main folder
  19. *
  20. */
  21. class SDLImageLoader;
  22. class CompImageLoader;
  23. typedef std::map <size_t, std::vector <JsonNode> > source_map;
  24. typedef std::map<size_t, IImage* > image_map;
  25. typedef std::map<size_t, image_map > group_map;
  26. /// Class for def loading, methods are based on CDefHandler
  27. /// After loading will store general info (palette and frame offsets) and pointer to file itself
  28. class CDefFile
  29. {
  30. private:
  31. struct SSpriteDef
  32. {
  33. ui32 size;
  34. ui32 format; /// format in which pixel data is stored
  35. ui32 fullWidth; /// full width and height of frame, including borders
  36. ui32 fullHeight;
  37. ui32 width; /// width and height of pixel data, borders excluded
  38. ui32 height;
  39. si32 leftMargin;
  40. si32 topMargin;
  41. } PACKED_STRUCT;
  42. //offset[group][frame] - offset of frame data in file
  43. std::map<size_t, std::vector <size_t> > offset;
  44. std::unique_ptr<ui8[]> data;
  45. std::unique_ptr<SDL_Color[]> palette;
  46. public:
  47. CDefFile(std::string Name);
  48. ~CDefFile();
  49. //load frame as SDL_Surface
  50. template<class ImageLoader>
  51. void loadFrame(size_t frame, size_t group, ImageLoader &loader) const;
  52. const std::map<size_t, size_t> getEntries() const;
  53. };
  54. /*
  55. * Wrapper around SDL_Surface
  56. */
  57. class SDLImage : public IImage
  58. {
  59. public:
  60. //Surface without empty borders
  61. SDL_Surface * surf;
  62. //size of left and top borders
  63. Point margins;
  64. //total size including borders
  65. Point fullSize;
  66. public:
  67. //Load image from def file
  68. SDLImage(CDefFile *data, size_t frame, size_t group=0, bool compressed=false);
  69. //Load from bitmap file
  70. SDLImage(std::string filename, bool compressed=false);
  71. //Create using existing surface, extraRef will increase refcount on SDL_Surface
  72. SDLImage(SDL_Surface * from, bool extraRef);
  73. ~SDLImage();
  74. void draw(SDL_Surface * where, int posX=0, int posY=0, Rect *src=nullptr, ui8 alpha=255) const override;
  75. void draw(SDL_Surface * where, SDL_Rect * dest, SDL_Rect * src, ui8 alpha=255) const override;
  76. SDL_Surface * scaleFast(float scale) const override;
  77. void playerColored(PlayerColor player) override;
  78. void setFlagColor(PlayerColor player) override;
  79. int width() const override;
  80. int height() const override;
  81. void horizontalFlip() override;
  82. void verticalFlip() override;
  83. void shiftPalette(int from, int howMany) override;
  84. friend class SDLImageLoader;
  85. };
  86. /*
  87. * RLE-compressed image data for 8-bit images with alpha-channel, currently far from finished
  88. * primary purpose is not high compression ratio but fast drawing.
  89. * Consist of repeatable segments with format similar to H3 def compression:
  90. * 1st byte:
  91. * if (byte == 0xff)
  92. * raw data, opaque and semi-transparent data always in separate blocks
  93. * else
  94. * RLE-compressed image data with this color
  95. * 2nd byte = size of segment
  96. * raw data (if any)
  97. */
  98. class CompImage : public IImage
  99. {
  100. //x,y - margins, w,h - sprite size
  101. Rect sprite;
  102. //total size including borders
  103. Point fullSize;
  104. //RLE-d data
  105. ui8 * surf;
  106. //array of offsets for each line
  107. ui32 * line;
  108. //palette
  109. SDL_Color *palette;
  110. //Used internally to blit one block of data
  111. template<int bpp, int dir>
  112. void BlitBlock(ui8 type, ui8 size, ui8 *&data, ui8 *&dest, ui8 alpha) const;
  113. void BlitBlockWithBpp(ui8 bpp, ui8 type, ui8 size, ui8 *&data, ui8 *&dest, ui8 alpha, bool rotated) const;
  114. public:
  115. //Load image from def file
  116. CompImage(const CDefFile *data, size_t frame, size_t group=0);
  117. //TODO: load image from SDL_Surface
  118. CompImage(SDL_Surface * surf);
  119. ~CompImage();
  120. void draw(SDL_Surface *where, int posX=0, int posY=0, Rect *src=nullptr, ui8 alpha=255) const override;
  121. void draw(SDL_Surface * where, SDL_Rect * dest, SDL_Rect * src, ui8 alpha=255) const override;
  122. SDL_Surface * scaleFast(float scale) const override;
  123. void playerColored(PlayerColor player) override;
  124. void setFlagColor(PlayerColor player) override;
  125. int width() const override;
  126. int height() const override;
  127. void horizontalFlip() override;
  128. void verticalFlip() override;
  129. void shiftPalette(int from, int howMany) override;
  130. friend class CompImageLoader;
  131. };
  132. class SDLImageLoader
  133. {
  134. SDLImage * image;
  135. ui8 * lineStart;
  136. ui8 * position;
  137. public:
  138. //load size raw pixels from data
  139. inline void Load(size_t size, const ui8 * data);
  140. //set size pixels to color
  141. inline void Load(size_t size, ui8 color=0);
  142. inline void EndLine();
  143. //init image with these sizes and palette
  144. inline void init(Point SpriteSize, Point Margins, Point FullSize, SDL_Color *pal);
  145. SDLImageLoader(SDLImage * Img);
  146. ~SDLImageLoader();
  147. };
  148. class CompImageLoader
  149. {
  150. CompImage * image;
  151. ui8 *position;
  152. ui8 *entry;
  153. ui32 currentLine;
  154. inline ui8 typeOf(ui8 color);
  155. inline void NewEntry(ui8 color, size_t size);
  156. inline void NewEntry(const ui8 * &data, size_t size);
  157. public:
  158. //load size raw pixels from data
  159. inline void Load(size_t size, const ui8 * data);
  160. //set size pixels to color
  161. inline void Load(size_t size, ui8 color=0);
  162. inline void EndLine();
  163. //init image with these sizes and palette
  164. inline void init(Point SpriteSize, Point Margins, Point FullSize, SDL_Color *pal);
  165. CompImageLoader(CompImage * Img);
  166. ~CompImageLoader();
  167. };
  168. // Extremely simple file cache. TODO: smarter, more general solution
  169. class CFileCache
  170. {
  171. static const int cacheSize = 50; //Max number of cached files
  172. struct FileData
  173. {
  174. ResourceID name;
  175. size_t size;
  176. std::unique_ptr<ui8[]> data;
  177. std::unique_ptr<ui8[]> getCopy()
  178. {
  179. auto ret = std::unique_ptr<ui8[]>(new ui8[size]);
  180. std::copy(data.get(), data.get() + size, ret.get());
  181. return ret;
  182. }
  183. FileData(ResourceID name_, size_t size_, std::unique_ptr<ui8[]> data_):
  184. name{std::move(name_)},
  185. size{size_},
  186. data{std::move(data_)}
  187. {}
  188. };
  189. std::deque<FileData> cache;
  190. public:
  191. std::unique_ptr<ui8[]> getCachedFile(ResourceID rid)
  192. {
  193. for(auto & file : cache)
  194. {
  195. if (file.name == rid)
  196. return file.getCopy();
  197. }
  198. // Still here? Cache miss
  199. if (cache.size() > cacheSize)
  200. cache.pop_front();
  201. auto data = CResourceHandler::get()->load(rid)->readAll();
  202. cache.emplace_back(std::move(rid), data.second, std::move(data.first));
  203. return cache.back().getCopy();
  204. }
  205. };
  206. static CFileCache animationCache;
  207. /*************************************************************************
  208. * DefFile, class used for def loading *
  209. *************************************************************************/
  210. CDefFile::CDefFile(std::string Name):
  211. data(nullptr),
  212. palette(nullptr)
  213. {
  214. //First 8 colors in def palette used for transparency
  215. static SDL_Color H3Palette[8] =
  216. {
  217. { 0, 0, 0, 0},// 100% - transparency
  218. { 0, 0, 0, 32},// 75% - shadow border,
  219. { 0, 0, 0, 64},// TODO: find exact value
  220. { 0, 0, 0, 128},// TODO: for transparency
  221. { 0, 0, 0, 128},// 50% - shadow body
  222. { 0, 0, 0, 0},// 100% - selection highlight
  223. { 0, 0, 0, 128},// 50% - shadow body below selection
  224. { 0, 0, 0, 64} // 75% - shadow border below selection
  225. };
  226. data = animationCache.getCachedFile(ResourceID(std::string("SPRITES/") + Name, EResType::ANIMATION));
  227. palette = std::unique_ptr<SDL_Color[]>(new SDL_Color[256]);
  228. int it = 0;
  229. ui32 type = read_le_u32(data.get() + it);
  230. it+=4;
  231. //int width = read_le_u32(data + it); it+=4;//not used
  232. //int height = read_le_u32(data + it); it+=4;
  233. it+=8;
  234. ui32 totalBlocks = read_le_u32(data.get() + it);
  235. it+=4;
  236. for (ui32 i= 0; i<256; i++)
  237. {
  238. palette[i].r = data[it++];
  239. palette[i].g = data[it++];
  240. palette[i].b = data[it++];
  241. palette[i].a = SDL_ALPHA_OPAQUE;
  242. }
  243. if (type == 71 || type == 64)//Buttons/buildings don't have shadows\semi-transparency
  244. memset(palette.get(), 0, sizeof(SDL_Color)*2);
  245. else
  246. memcpy(palette.get(), H3Palette, sizeof(SDL_Color)*8);//initialize shadow\selection colors
  247. for (ui32 i=0; i<totalBlocks; i++)
  248. {
  249. size_t blockID = read_le_u32(data.get() + it);
  250. it+=4;
  251. size_t totalEntries = read_le_u32(data.get() + it);
  252. it+=12;
  253. //8 unknown bytes - skipping
  254. //13 bytes for name of every frame in this block - not used, skipping
  255. it+= 13 * totalEntries;
  256. for (ui32 j=0; j<totalEntries; j++)
  257. {
  258. size_t currOffset = read_le_u32(data.get() + it);
  259. offset[blockID].push_back(currOffset);
  260. it += 4;
  261. }
  262. }
  263. }
  264. template<class ImageLoader>
  265. void CDefFile::loadFrame(size_t frame, size_t group, ImageLoader &loader) const
  266. {
  267. std::map<size_t, std::vector <size_t> >::const_iterator it;
  268. it = offset.find(group);
  269. assert (it != offset.end());
  270. const ui8 * FDef = data.get()+it->second[frame];
  271. const SSpriteDef sd = * reinterpret_cast<const SSpriteDef *>(FDef);
  272. SSpriteDef sprite;
  273. sprite.format = read_le_u32(&sd.format);
  274. sprite.fullWidth = read_le_u32(&sd.fullWidth);
  275. sprite.fullHeight = read_le_u32(&sd.fullHeight);
  276. sprite.width = read_le_u32(&sd.width);
  277. sprite.height = read_le_u32(&sd.height);
  278. sprite.leftMargin = read_le_u32(&sd.leftMargin);
  279. sprite.topMargin = read_le_u32(&sd.topMargin);
  280. ui32 currentOffset = sizeof(SSpriteDef);
  281. ui32 BaseOffset = sizeof(SSpriteDef);
  282. loader.init(Point(sprite.width, sprite.height),
  283. Point(sprite.leftMargin, sprite.topMargin),
  284. Point(sprite.fullWidth, sprite.fullHeight), palette.get());
  285. switch (sprite.format)
  286. {
  287. case 0:
  288. {
  289. //pixel data is not compressed, copy data to surface
  290. for (ui32 i=0; i<sprite.height; i++)
  291. {
  292. loader.Load(sprite.width, FDef + currentOffset);
  293. currentOffset += sprite.width;
  294. loader.EndLine();
  295. }
  296. break;
  297. }
  298. case 1:
  299. {
  300. //for each line we have offset of pixel data
  301. const ui32 * RWEntriesLoc = reinterpret_cast<const ui32 *>(FDef+currentOffset);
  302. currentOffset += sizeof(ui32) * sprite.height;
  303. for (ui32 i=0; i<sprite.height; i++)
  304. {
  305. //get position of the line
  306. currentOffset=BaseOffset + read_le_u32(RWEntriesLoc + i);
  307. ui32 TotalRowLength = 0;
  308. while (TotalRowLength<sprite.width)
  309. {
  310. ui8 type=FDef[currentOffset++];
  311. ui32 length=FDef[currentOffset++] + 1;
  312. if (type==0xFF)//Raw data
  313. {
  314. loader.Load(length, FDef + currentOffset);
  315. currentOffset+=length;
  316. }
  317. else// RLE
  318. {
  319. loader.Load(length, type);
  320. }
  321. TotalRowLength += length;
  322. }
  323. loader.EndLine();
  324. }
  325. break;
  326. }
  327. case 2:
  328. {
  329. currentOffset = BaseOffset + read_le_u16(FDef + BaseOffset);
  330. for (ui32 i=0; i<sprite.height; i++)
  331. {
  332. ui32 TotalRowLength=0;
  333. while (TotalRowLength<sprite.width)
  334. {
  335. ui8 SegmentType=FDef[currentOffset++];
  336. ui8 code = SegmentType / 32;
  337. ui8 length = (SegmentType & 31) + 1;
  338. if (code==7)//Raw data
  339. {
  340. loader.Load(length, FDef + currentOffset);
  341. currentOffset += length;
  342. }
  343. else//RLE
  344. {
  345. loader.Load(length, code);
  346. }
  347. TotalRowLength+=length;
  348. }
  349. loader.EndLine();
  350. }
  351. break;
  352. }
  353. case 3:
  354. {
  355. for (ui32 i=0; i<sprite.height; i++)
  356. {
  357. currentOffset = BaseOffset + read_le_u16(FDef + BaseOffset+i*2*(sprite.width/32));
  358. ui32 TotalRowLength=0;
  359. while (TotalRowLength<sprite.width)
  360. {
  361. ui8 segment = FDef[currentOffset++];
  362. ui8 code = segment / 32;
  363. ui8 length = (segment & 31) + 1;
  364. if (code==7)//Raw data
  365. {
  366. loader.Load(length, FDef + currentOffset);
  367. currentOffset += length;
  368. }
  369. else//RLE
  370. {
  371. loader.Load(length, code);
  372. }
  373. TotalRowLength += length;
  374. }
  375. loader.EndLine();
  376. }
  377. break;
  378. }
  379. default:
  380. logGlobal->errorStream()<<"Error: unsupported format of def file: "<<sprite.format;
  381. break;
  382. }
  383. };
  384. CDefFile::~CDefFile() = default;
  385. const std::map<size_t, size_t > CDefFile::getEntries() const
  386. {
  387. std::map<size_t, size_t > ret;
  388. for (auto & elem : offset)
  389. ret[elem.first] = elem.second.size();
  390. return ret;
  391. }
  392. /*************************************************************************
  393. * Classes for image loaders - helpers for loading from def files *
  394. *************************************************************************/
  395. SDLImageLoader::SDLImageLoader(SDLImage * Img):
  396. image(Img),
  397. lineStart(nullptr),
  398. position(nullptr)
  399. {
  400. }
  401. void SDLImageLoader::init(Point SpriteSize, Point Margins, Point FullSize, SDL_Color *pal)
  402. {
  403. //Init image
  404. image->surf = SDL_CreateRGBSurface(SDL_SWSURFACE, SpriteSize.x, SpriteSize.y, 8, 0, 0, 0, 0);
  405. image->margins = Margins;
  406. image->fullSize = FullSize;
  407. //Prepare surface
  408. SDL_Palette * p = SDL_AllocPalette(256);
  409. SDL_SetPaletteColors(p, pal, 0, 256);
  410. SDL_SetSurfacePalette(image->surf, p);
  411. SDL_FreePalette(p);
  412. SDL_LockSurface(image->surf);
  413. lineStart = position = (ui8*)image->surf->pixels;
  414. }
  415. inline void SDLImageLoader::Load(size_t size, const ui8 * data)
  416. {
  417. if (size)
  418. {
  419. memcpy((void *)position, data, size);
  420. position += size;
  421. }
  422. }
  423. inline void SDLImageLoader::Load(size_t size, ui8 color)
  424. {
  425. if (size)
  426. {
  427. memset((void *)position, color, size);
  428. position += size;
  429. }
  430. }
  431. inline void SDLImageLoader::EndLine()
  432. {
  433. lineStart += image->surf->pitch;
  434. position = lineStart;
  435. }
  436. SDLImageLoader::~SDLImageLoader()
  437. {
  438. SDL_UnlockSurface(image->surf);
  439. SDL_SetColorKey(image->surf, SDL_TRUE, 0);
  440. //TODO: RLE if compressed and bpp>1
  441. }
  442. ////////////////////////////////////////////////////////////////////////////////
  443. CompImageLoader::CompImageLoader(CompImage * Img):
  444. image(Img),
  445. position(nullptr),
  446. entry(nullptr),
  447. currentLine(0)
  448. {
  449. }
  450. void CompImageLoader::init(Point SpriteSize, Point Margins, Point FullSize, SDL_Color *pal)
  451. {
  452. image->sprite = Rect(Margins, SpriteSize);
  453. image->fullSize = FullSize;
  454. if (SpriteSize.x && SpriteSize.y)
  455. {
  456. image->palette = new SDL_Color[256];
  457. memcpy((void*)image->palette, (void*)pal, 256*sizeof(SDL_Color));
  458. //Allocate enought space for worst possible case, c-style malloc used due to resizing after load
  459. image->surf = (ui8*)malloc(SpriteSize.x*SpriteSize.y*3);
  460. image->line = new ui32[SpriteSize.y+1];
  461. image->line[0] = 0;
  462. position = image->surf;
  463. }
  464. }
  465. inline void CompImageLoader::NewEntry(ui8 color, size_t size)
  466. {
  467. assert(color != 0xff);
  468. assert(size && size<256);
  469. entry = position;
  470. entry[0] = color;
  471. entry[1] = size;
  472. position +=2;
  473. }
  474. inline void CompImageLoader::NewEntry(const ui8 * &data, size_t size)
  475. {
  476. assert(size && size<256);
  477. entry = position;
  478. entry[0] = 0xff;
  479. entry[1] = size;
  480. position +=2;
  481. memcpy(position, data, size);
  482. position+=size;
  483. data+=size;
  484. }
  485. inline ui8 CompImageLoader::typeOf(ui8 color)
  486. {
  487. if (color == 0)
  488. return 0;
  489. if (image->palette[color].a != 255)
  490. return 1;
  491. return 2;
  492. }
  493. inline void CompImageLoader::Load(size_t size, const ui8 * data)
  494. {
  495. while (size)
  496. {
  497. //Try to compress data
  498. while(true)
  499. {
  500. ui8 color = data[0];
  501. if (color != 0xff)
  502. {
  503. size_t runLength = 1;
  504. while (runLength < size && color == data[runLength])
  505. runLength++;
  506. if (runLength > 1 && runLength < 255)//Row of one color found - use RLE
  507. {
  508. Load(runLength, color);
  509. data += runLength;
  510. size -= runLength;
  511. if (!size)
  512. return;
  513. }
  514. else
  515. break;
  516. }
  517. else
  518. break;
  519. }
  520. //Select length for new raw entry
  521. size_t runLength = 1;
  522. ui8 color = data[0];
  523. ui8 type = typeOf(color);
  524. ui8 color2;
  525. ui8 type2;
  526. if (size > 1)
  527. {
  528. do
  529. {
  530. color2 = data[runLength];
  531. type2 = typeOf(color2);
  532. runLength++;
  533. }
  534. //While we have data of this type and different colors
  535. while ((runLength < size) && (type == type2) && ( (color2 != 0xff) || (color2 != color)));
  536. }
  537. size -= runLength;
  538. //add data to last entry
  539. if (entry && entry[0] == 0xff && type == typeOf(entry[2]))
  540. {
  541. size_t toCopy = std::min<size_t>(runLength, 255 - entry[1]);
  542. runLength -= toCopy;
  543. entry[1] += toCopy;
  544. memcpy(position, data, toCopy);
  545. data+=toCopy;
  546. position+=toCopy;
  547. }
  548. //Create new entries
  549. while (runLength > 255)
  550. {
  551. NewEntry(data, 255);
  552. runLength -= 255;
  553. }
  554. if (runLength)
  555. NewEntry(data, runLength);
  556. }
  557. }
  558. inline void CompImageLoader::Load(size_t size, ui8 color)
  559. {
  560. if (!size)
  561. return;
  562. if (color==0xff)
  563. {
  564. auto tmpbuf = new ui8[size];
  565. memset((void*)tmpbuf, color, size);
  566. Load(size, tmpbuf);
  567. delete [] tmpbuf;
  568. return;
  569. }
  570. //Current entry is RLE with same color as new block
  571. if (entry && entry[0] == color)
  572. {
  573. size_t toCopy = std::min<size_t>(size, 255 - entry[1]);
  574. size -= toCopy;
  575. entry[1] += toCopy;
  576. }
  577. //Create new entries
  578. while (size > 255)
  579. {
  580. NewEntry(color, 255);
  581. size -= 255;
  582. }
  583. if (size)
  584. NewEntry(color, size);
  585. }
  586. void CompImageLoader::EndLine()
  587. {
  588. currentLine++;
  589. image->line[currentLine] = position - image->surf;
  590. entry = nullptr;
  591. }
  592. CompImageLoader::~CompImageLoader()
  593. {
  594. if (!image->surf)
  595. return;
  596. ui8* newPtr = (ui8*)realloc((void*)image->surf, position - image->surf);
  597. if (newPtr)
  598. image->surf = newPtr;
  599. }
  600. /*************************************************************************
  601. * Classes for images, support loading from file and drawing on surface *
  602. *************************************************************************/
  603. IImage::IImage():
  604. refCount(1)
  605. {
  606. }
  607. bool IImage::decreaseRef()
  608. {
  609. refCount--;
  610. return refCount <= 0;
  611. }
  612. void IImage::increaseRef()
  613. {
  614. refCount++;
  615. }
  616. SDLImage::SDLImage(CDefFile *data, size_t frame, size_t group, bool compressed):
  617. surf(nullptr)
  618. {
  619. SDLImageLoader loader(this);
  620. data->loadFrame(frame, group, loader);
  621. }
  622. SDLImage::SDLImage(SDL_Surface * from, bool extraRef):
  623. margins(0,0)
  624. {
  625. surf = from;
  626. if (extraRef)
  627. surf->refcount++;
  628. fullSize.x = surf->w;
  629. fullSize.y = surf->h;
  630. }
  631. SDLImage::SDLImage(std::string filename, bool compressed):
  632. margins(0,0)
  633. {
  634. surf = BitmapHandler::loadBitmap(filename);
  635. if (surf == nullptr)
  636. {
  637. logGlobal->errorStream() << "Error: failed to load image "<<filename;
  638. return;
  639. }
  640. else
  641. {
  642. fullSize.x = surf->w;
  643. fullSize.y = surf->h;
  644. }
  645. if (compressed)
  646. {
  647. SDL_Surface *temp = surf;
  648. // add RLE flag
  649. if (surf->format->palette)
  650. {
  651. CSDL_Ext::setColorKey(temp,temp->format->palette->colors[0]);
  652. }
  653. SDL_SetSurfaceRLE(temp, SDL_RLEACCEL);
  654. // convert surface to enable RLE
  655. surf = SDL_ConvertSurface(temp, temp->format, temp->flags);
  656. SDL_FreeSurface(temp);
  657. }
  658. }
  659. void SDLImage::draw(SDL_Surface *where, int posX, int posY, Rect *src, ui8 alpha) const
  660. {
  661. if (!surf)
  662. return;
  663. Rect destRect(posX, posY, surf->w, surf->h);
  664. draw(where, &destRect, src);
  665. }
  666. void SDLImage::draw(SDL_Surface* where, SDL_Rect* dest, SDL_Rect* src, ui8 alpha) const
  667. {
  668. if (!surf)
  669. return;
  670. Rect sourceRect(0, 0, surf->w, surf->h);
  671. Point destShift(0,0);
  672. if(src)
  673. {
  674. if(src->x < margins.x)
  675. destShift.x += margins.x - src->x;
  676. if(src->y < margins.y)
  677. destShift.y += margins.y - src->y;
  678. sourceRect = Rect(*src) & Rect(margins.x, margins.y, surf->w, surf->h);
  679. sourceRect -= margins;
  680. }
  681. else
  682. destShift = margins;
  683. Rect destRect(margins.x, margins.y, surf->w, surf->h);
  684. if(dest)
  685. {
  686. destRect = *dest;
  687. destRect = destRect & Rect(destRect.x, destRect.y, sourceRect.w, sourceRect.h);
  688. destRect += destShift;
  689. }
  690. if(surf->format->BitsPerPixel == 8)
  691. {
  692. CSDL_Ext::blit8bppAlphaTo24bpp(surf, &sourceRect, where, &destRect);
  693. }
  694. else
  695. {
  696. SDL_UpperBlit(surf, &sourceRect, where, &destRect);
  697. }
  698. }
  699. SDL_Surface * SDLImage::scaleFast(float scale) const
  700. {
  701. //todo: margins
  702. auto scaled = CSDL_Ext::scaleSurfaceFast(surf, surf->w * scale, surf->h * scale);
  703. if (scaled->format && scaled->format->palette) // fix color keying, because SDL loses it at this point
  704. CSDL_Ext::setColorKey(scaled, scaled->format->palette->colors[0]);
  705. else if(scaled->format && scaled->format->Amask)
  706. SDL_SetSurfaceBlendMode(scaled, SDL_BLENDMODE_BLEND);//just in case
  707. else
  708. CSDL_Ext::setDefaultColorKey(scaled);//just in case
  709. return scaled;
  710. }
  711. void SDLImage::playerColored(PlayerColor player)
  712. {
  713. graphics->blueToPlayersAdv(surf, player);
  714. }
  715. void SDLImage::setFlagColor(PlayerColor player)
  716. {
  717. if(player < PlayerColor::PLAYER_LIMIT || player==PlayerColor::NEUTRAL)
  718. CSDL_Ext::setPlayerColor(surf, player);
  719. }
  720. int SDLImage::width() const
  721. {
  722. return fullSize.x;
  723. }
  724. int SDLImage::height() const
  725. {
  726. return fullSize.y;
  727. }
  728. void SDLImage::horizontalFlip()
  729. {
  730. SDL_Surface * flipped = CSDL_Ext::horizontalFlip(surf);
  731. SDL_FreeSurface(surf);
  732. surf = flipped;
  733. margins.y = fullSize.y - surf->h - margins.y;
  734. }
  735. void SDLImage::verticalFlip()
  736. {
  737. SDL_Surface * flipped = CSDL_Ext::verticalFlip(surf);
  738. SDL_FreeSurface(surf);
  739. surf = flipped;
  740. margins.x = fullSize.x - surf->w - margins.x;
  741. }
  742. void SDLImage::shiftPalette(int from, int howMany)
  743. {
  744. //works with at most 16 colors, if needed more -> increase values
  745. assert(howMany < 16);
  746. if(surf->format->palette)
  747. {
  748. SDL_Color palette[16];
  749. for(int i=0; i<howMany; ++i)
  750. {
  751. palette[(i+1)%howMany] = surf->format->palette->colors[from + i];
  752. }
  753. SDL_SetColors(surf, palette, from, howMany);
  754. }
  755. }
  756. SDLImage::~SDLImage()
  757. {
  758. SDL_FreeSurface(surf);
  759. }
  760. CompImage::CompImage(const CDefFile *data, size_t frame, size_t group):
  761. surf(nullptr),
  762. line(nullptr),
  763. palette(nullptr)
  764. {
  765. CompImageLoader loader(this);
  766. data->loadFrame(frame, group, loader);
  767. }
  768. CompImage::CompImage(SDL_Surface * surf)
  769. {
  770. //TODO
  771. assert(0);
  772. }
  773. void CompImage::draw(SDL_Surface *where, int posX, int posY, Rect *src, ui8 alpha) const
  774. {
  775. Rect dest(posX,posY, width(), height());
  776. draw(where, &dest, src, alpha);
  777. }
  778. void CompImage::draw(SDL_Surface* where, SDL_Rect* dest, SDL_Rect* src, ui8 alpha) const
  779. {
  780. int rotation = 0; //TODO
  781. //rotation & 2 = horizontal rotation
  782. //rotation & 4 = vertical rotation
  783. if (!surf)
  784. return;
  785. Rect sourceRect(sprite);
  786. //TODO: rotation and scaling
  787. if (src)
  788. sourceRect = sourceRect & *src;
  789. //Limit source rect to sizes of surface
  790. sourceRect = sourceRect & Rect(0, 0, where->w, where->h);
  791. //Starting point on SDL surface
  792. Point dst(sourceRect.x,sourceRect.y);
  793. if (dest)
  794. {
  795. dst.x += dest->x;
  796. dst.y += dest->y;
  797. }
  798. if (rotation & 2)
  799. dst.y += sourceRect.h;
  800. if (rotation & 4)
  801. dst.x += sourceRect.w;
  802. sourceRect -= sprite.topLeft();
  803. for (int currY = 0; currY <sourceRect.h; currY++)
  804. {
  805. ui8* data = surf + line[currY+sourceRect.y];
  806. ui8 type = *(data++);
  807. ui8 size = *(data++);
  808. int currX = sourceRect.x;
  809. //Skip blocks until starting position reached
  810. while ( currX > size )
  811. {
  812. currX -= size;
  813. if (type == 0xff)
  814. data += size;
  815. type = *(data++);
  816. size = *(data++);
  817. }
  818. //This block will be shown partially - calculate size\position
  819. size -= currX;
  820. if (type == 0xff)
  821. data += currX;
  822. currX = 0;
  823. ui8 bpp = where->format->BytesPerPixel;
  824. //Calculate position for blitting: pixels + Y + X
  825. ui8* blitPos = (ui8*) where->pixels;
  826. if (rotation & 4)
  827. blitPos += (dst.y - currY) * where->pitch;
  828. else
  829. blitPos += (dst.y + currY) * where->pitch;
  830. blitPos += dst.x * bpp;
  831. //Blit blocks that must be fully visible
  832. while (currX + size < sourceRect.w)
  833. {
  834. //blit block, pointers will be modified if needed
  835. BlitBlockWithBpp(bpp, type, size, data, blitPos, alpha, rotation & 2);
  836. currX += size;
  837. type = *(data++);
  838. size = *(data++);
  839. }
  840. //Blit last, semi-visible block
  841. size = sourceRect.w - currX;
  842. BlitBlockWithBpp(bpp, type, size, data, blitPos, alpha, rotation & 2);
  843. }
  844. }
  845. SDL_Surface * CompImage::scaleFast(float scale) const
  846. {
  847. //todo: CompImage::scaleFast
  848. logAnim->error("CompImage::scaleFast is not implemented");
  849. return CSDL_Ext::newSurface(width() * scale, height() * scale);
  850. }
  851. #define CASEBPP(x,y) case x: BlitBlock<x,y>(type, size, data, dest, alpha); break
  852. //FIXME: better way to get blitter
  853. void CompImage::BlitBlockWithBpp(ui8 bpp, ui8 type, ui8 size, ui8 *&data, ui8 *&dest, ui8 alpha, bool rotated) const
  854. {
  855. assert(bpp>1 && bpp<5);
  856. if (rotated)
  857. switch (bpp)
  858. {
  859. CASEBPP(2,1);
  860. CASEBPP(3,1);
  861. CASEBPP(4,1);
  862. }
  863. else
  864. switch (bpp)
  865. {
  866. CASEBPP(2,1);
  867. CASEBPP(3,1);
  868. CASEBPP(4,1);
  869. }
  870. }
  871. #undef CASEBPP
  872. //Blit one block from RLE-d surface
  873. template<int bpp, int dir>
  874. void CompImage::BlitBlock(ui8 type, ui8 size, ui8 *&data, ui8 *&dest, ui8 alpha) const
  875. {
  876. //Raw data
  877. if (type == 0xff)
  878. {
  879. ui8 color = *data;
  880. if (alpha != 255)//Per-surface alpha is set
  881. {
  882. for (size_t i=0; i<size; i++)
  883. {
  884. SDL_Color col = palette[*(data++)];
  885. col.a = (ui32)col.a*alpha/255;
  886. ColorPutter<bpp, 1>::PutColorAlpha(dest, col);
  887. }
  888. return;
  889. }
  890. if (palette[color].a == 255)
  891. {
  892. //Put row of RGB data
  893. for (size_t i=0; i<size; i++)
  894. ColorPutter<bpp, 1>::PutColor(dest, palette[*(data++)]);
  895. }
  896. else
  897. {
  898. //Put row of RGBA data
  899. for (size_t i=0; i<size; i++)
  900. ColorPutter<bpp, 1>::PutColorAlpha(dest, palette[*(data++)]);
  901. }
  902. }
  903. //RLE-d sequence
  904. else
  905. {
  906. if (alpha != 255 && palette[type].a !=0)//Per-surface alpha is set
  907. {
  908. SDL_Color col = palette[type];
  909. col.a = (int)col.a*(255-alpha)/255;
  910. for (size_t i=0; i<size; i++)
  911. ColorPutter<bpp, 1>::PutColorAlpha(dest, col);
  912. return;
  913. }
  914. switch (palette[type].a)
  915. {
  916. case 0:
  917. {
  918. //Skip row
  919. dest += size*bpp;
  920. break;
  921. }
  922. case 255:
  923. {
  924. //Put RGB row
  925. ColorPutter<bpp, 1>::PutColorRow(dest, palette[type], size);
  926. break;
  927. }
  928. default:
  929. {
  930. //Put RGBA row
  931. for (size_t i=0; i<size; i++)
  932. ColorPutter<bpp, 1>::PutColorAlpha(dest, palette[type]);
  933. break;
  934. }
  935. }
  936. }
  937. }
  938. void CompImage::playerColored(PlayerColor player)
  939. {
  940. SDL_Color *pal = nullptr;
  941. if(player < PlayerColor::PLAYER_LIMIT)
  942. {
  943. pal = graphics->playerColorPalette + 32*player.getNum();
  944. }
  945. else if(player == PlayerColor::NEUTRAL)
  946. {
  947. pal = graphics->neutralColorPalette;
  948. }
  949. else
  950. assert(0);
  951. for(int i=0; i<32; ++i)
  952. {
  953. CSDL_Ext::colorAssign(palette[224+i],pal[i]);
  954. }
  955. }
  956. void CompImage::setFlagColor(PlayerColor player)
  957. {
  958. logAnim->error("CompImage::setFlagColor is not implemented");
  959. }
  960. int CompImage::width() const
  961. {
  962. return fullSize.x;
  963. }
  964. int CompImage::height() const
  965. {
  966. return fullSize.y;
  967. }
  968. CompImage::~CompImage()
  969. {
  970. free(surf);
  971. delete [] line;
  972. delete [] palette;
  973. }
  974. void CompImage::horizontalFlip()
  975. {
  976. logAnim->error("CompImage::horizontalFlip is not implemented");
  977. }
  978. void CompImage::verticalFlip()
  979. {
  980. logAnim->error("CompImage::verticalFlip is not implemented");
  981. }
  982. void CompImage::shiftPalette(int from, int howMany)
  983. {
  984. logAnim->error("CompImage::shiftPalette is not implemented");
  985. }
  986. /*************************************************************************
  987. * CAnimation for animations handling, can load part of file if needed *
  988. *************************************************************************/
  989. IImage * CAnimation::getFromExtraDef(std::string filename)
  990. {
  991. size_t pos = filename.find(':');
  992. if (pos == -1)
  993. return nullptr;
  994. CAnimation anim(filename.substr(0, pos));
  995. pos++;
  996. size_t frame = atoi(filename.c_str()+pos);
  997. size_t group = 0;
  998. pos = filename.find(':', pos);
  999. if (pos != -1)
  1000. {
  1001. pos++;
  1002. group = frame;
  1003. frame = atoi(filename.c_str()+pos);
  1004. }
  1005. anim.load(frame ,group);
  1006. IImage * ret = anim.images[group][frame];
  1007. anim.images.clear();
  1008. return ret;
  1009. }
  1010. bool CAnimation::loadFrame(CDefFile * file, size_t frame, size_t group)
  1011. {
  1012. if (size(group) <= frame)
  1013. {
  1014. printError(frame, group, "LoadFrame");
  1015. return false;
  1016. }
  1017. IImage *image = getImage(frame, group, false);
  1018. if (image)
  1019. {
  1020. image->increaseRef();
  1021. return true;
  1022. }
  1023. //try to get image from def
  1024. if (source[group][frame].getType() == JsonNode::DATA_NULL)
  1025. {
  1026. if (file)
  1027. {
  1028. auto frameList = file->getEntries();
  1029. if (vstd::contains(frameList, group) && frameList.at(group) > frame) // frame is present
  1030. {
  1031. if (compressed)
  1032. images[group][frame] = new CompImage(file, frame, group);
  1033. else
  1034. images[group][frame] = new SDLImage(file, frame, group);
  1035. return true;
  1036. }
  1037. }
  1038. // still here? image is missing
  1039. printError(frame, group, "LoadFrame");
  1040. images[group][frame] = new SDLImage("DEFAULT", compressed);
  1041. }
  1042. else //load from separate file
  1043. {
  1044. std::string filename = source[group][frame]["file"].String();
  1045. IImage * img = getFromExtraDef(filename);
  1046. if (!img)
  1047. img = new SDLImage(filename, compressed);
  1048. images[group][frame] = img;
  1049. return true;
  1050. }
  1051. return false;
  1052. }
  1053. bool CAnimation::unloadFrame(size_t frame, size_t group)
  1054. {
  1055. IImage *image = getImage(frame, group, false);
  1056. if (image)
  1057. {
  1058. //decrease ref count for image and delete if needed
  1059. if (image->decreaseRef())
  1060. {
  1061. delete image;
  1062. images[group].erase(frame);
  1063. }
  1064. if (images[group].empty())
  1065. images.erase(group);
  1066. return true;
  1067. }
  1068. return false;
  1069. }
  1070. void CAnimation::initFromJson(const JsonNode & config)
  1071. {
  1072. std::string basepath;
  1073. basepath = config["basepath"].String();
  1074. for(const JsonNode &group : config["sequences"].Vector())
  1075. {
  1076. size_t groupID = group["group"].Float();//TODO: string-to-value conversion("moving" -> MOVING)
  1077. source[groupID].clear();
  1078. for(const JsonNode &frame : group["frames"].Vector())
  1079. {
  1080. source[groupID].push_back(JsonNode());
  1081. std::string filename = frame.String();
  1082. source[groupID].back()["file"].String() = basepath + filename;
  1083. }
  1084. }
  1085. for(const JsonNode &node : config["images"].Vector())
  1086. {
  1087. size_t group = node["group"].Float();
  1088. size_t frame = node["frame"].Float();
  1089. if (source[group].size() <= frame)
  1090. source[group].resize(frame+1);
  1091. source[group][frame] = node;
  1092. std::string filename = node["file"].String();
  1093. source[group][frame]["file"].String() = basepath + filename;
  1094. }
  1095. }
  1096. void CAnimation::init(CDefFile * file)
  1097. {
  1098. if (file)
  1099. {
  1100. const std::map<size_t, size_t> defEntries = file->getEntries();
  1101. for (auto & defEntry : defEntries)
  1102. source[defEntry.first].resize(defEntry.second);
  1103. }
  1104. ResourceID resID(std::string("SPRITES/") + name, EResType::TEXT);
  1105. if (vstd::contains(graphics->imageLists, resID.getName()))
  1106. initFromJson(graphics->imageLists[resID.getName()]);
  1107. auto configList = CResourceHandler::get()->getResourcesWithName(resID);
  1108. for(auto & loader : configList)
  1109. {
  1110. auto stream = loader->load(resID);
  1111. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  1112. stream->read(textData.get(), stream->getSize());
  1113. const JsonNode config((char*)textData.get(), stream->getSize());
  1114. initFromJson(config);
  1115. }
  1116. }
  1117. CDefFile * CAnimation::getFile() const
  1118. {
  1119. ResourceID identifier(std::string("SPRITES/") + name, EResType::ANIMATION);
  1120. if (CResourceHandler::get()->existsResource(identifier))
  1121. return new CDefFile(name);
  1122. return nullptr;
  1123. }
  1124. void CAnimation::printError(size_t frame, size_t group, std::string type) const
  1125. {
  1126. logGlobal->errorStream() << type << " error: Request for frame not present in CAnimation! "
  1127. << "\tFile name: " << name << " Group: " << group << " Frame: " << frame;
  1128. }
  1129. CAnimation::CAnimation(std::string Name, bool Compressed):
  1130. name(Name),
  1131. compressed(Compressed),
  1132. preloaded(false)
  1133. {
  1134. size_t dotPos = name.find_last_of('.');
  1135. if ( dotPos!=-1 )
  1136. name.erase(dotPos);
  1137. std::transform(name.begin(), name.end(), name.begin(), toupper);
  1138. CDefFile * file = getFile();
  1139. init(file);
  1140. delete file;
  1141. }
  1142. CAnimation::CAnimation():
  1143. name(""),
  1144. compressed(false),
  1145. preloaded(false)
  1146. {
  1147. init(nullptr);
  1148. }
  1149. CAnimation::~CAnimation()
  1150. {
  1151. if(preloaded)
  1152. unload();
  1153. if(!images.empty())
  1154. {
  1155. logGlobal->warnStream()<<"Warning: not all frames were unloaded from "<<name;
  1156. for (auto & elem : images)
  1157. for (auto & _image : elem.second)
  1158. delete _image.second;
  1159. }
  1160. }
  1161. void CAnimation::duplicateImage(const size_t sourceGroup, const size_t sourceFrame, const size_t targetGroup)
  1162. {
  1163. //todo: clone actual loaded Image object
  1164. JsonNode clone(source[sourceGroup][sourceFrame]);
  1165. if(clone.getType() == JsonNode::DATA_NULL)
  1166. {
  1167. std::string temp = name+":"+boost::lexical_cast<std::string>(sourceGroup)+":"+boost::lexical_cast<std::string>(sourceFrame);
  1168. clone["file"].String() = temp;
  1169. }
  1170. source[targetGroup].push_back(clone);
  1171. size_t index = source[targetGroup].size() - 1;
  1172. if(preloaded)
  1173. load(index, targetGroup);
  1174. }
  1175. void CAnimation::setCustom(std::string filename, size_t frame, size_t group)
  1176. {
  1177. if (source[group].size() <= frame)
  1178. source[group].resize(frame+1);
  1179. source[group][frame]["file"].String() = filename;
  1180. //FIXME: update image if already loaded
  1181. }
  1182. IImage * CAnimation::getImage(size_t frame, size_t group, bool verbose) const
  1183. {
  1184. auto groupIter = images.find(group);
  1185. if (groupIter != images.end())
  1186. {
  1187. auto imageIter = groupIter->second.find(frame);
  1188. if (imageIter != groupIter->second.end())
  1189. return imageIter->second;
  1190. }
  1191. if (verbose)
  1192. printError(frame, group, "GetImage");
  1193. return nullptr;
  1194. }
  1195. void CAnimation::load()
  1196. {
  1197. CDefFile * file = getFile();
  1198. for (auto & elem : source)
  1199. for (size_t image=0; image < elem.second.size(); image++)
  1200. loadFrame(file, image, elem.first);
  1201. delete file;
  1202. }
  1203. void CAnimation::unload()
  1204. {
  1205. for (auto & elem : source)
  1206. for (size_t image=0; image < elem.second.size(); image++)
  1207. unloadFrame(image, elem.first);
  1208. }
  1209. void CAnimation::preload()
  1210. {
  1211. if(!preloaded)
  1212. {
  1213. preloaded = true;
  1214. load();
  1215. }
  1216. }
  1217. void CAnimation::loadGroup(size_t group)
  1218. {
  1219. CDefFile * file = getFile();
  1220. if (vstd::contains(source, group))
  1221. for (size_t image=0; image < source[group].size(); image++)
  1222. loadFrame(file, image, group);
  1223. delete file;
  1224. }
  1225. void CAnimation::unloadGroup(size_t group)
  1226. {
  1227. if (vstd::contains(source, group))
  1228. for (size_t image=0; image < source[group].size(); image++)
  1229. unloadFrame(image, group);
  1230. }
  1231. void CAnimation::load(size_t frame, size_t group)
  1232. {
  1233. CDefFile * file = getFile();
  1234. loadFrame(file, frame, group);
  1235. delete file;
  1236. }
  1237. void CAnimation::unload(size_t frame, size_t group)
  1238. {
  1239. unloadFrame(frame, group);
  1240. }
  1241. size_t CAnimation::size(size_t group) const
  1242. {
  1243. auto iter = source.find(group);
  1244. if (iter != source.end())
  1245. return iter->second.size();
  1246. return 0;
  1247. }
  1248. float CFadeAnimation::initialCounter() const
  1249. {
  1250. if (fadingMode == EMode::OUT)
  1251. return 1.0f;
  1252. return 0.0f;
  1253. }
  1254. void CFadeAnimation::update()
  1255. {
  1256. if (!fading)
  1257. return;
  1258. if (fadingMode == EMode::OUT)
  1259. fadingCounter -= delta;
  1260. else
  1261. fadingCounter += delta;
  1262. if (isFinished())
  1263. {
  1264. fading = false;
  1265. if (shouldFreeSurface)
  1266. {
  1267. SDL_FreeSurface(fadingSurface);
  1268. fadingSurface = nullptr;
  1269. }
  1270. }
  1271. }
  1272. bool CFadeAnimation::isFinished() const
  1273. {
  1274. if (fadingMode == EMode::OUT)
  1275. return fadingCounter <= 0.0f;
  1276. return fadingCounter >= 1.0f;
  1277. }
  1278. CFadeAnimation::CFadeAnimation()
  1279. : fadingSurface(nullptr),
  1280. fading(false),
  1281. fadingMode(EMode::NONE)
  1282. {
  1283. }
  1284. CFadeAnimation::~CFadeAnimation()
  1285. {
  1286. if (fadingSurface && shouldFreeSurface)
  1287. SDL_FreeSurface(fadingSurface);
  1288. }
  1289. void CFadeAnimation::init(EMode mode, SDL_Surface * sourceSurface, bool freeSurfaceAtEnd /* = false */, float animDelta /* = DEFAULT_DELTA */)
  1290. {
  1291. if (fading)
  1292. {
  1293. // in that case, immediately finish the previous fade
  1294. // (alternatively, we could just return here to ignore the new fade request until this one finished (but we'd need to free the passed bitmap to avoid leaks))
  1295. logGlobal->warnStream() << "Tried to init fading animation that is already running.";
  1296. if (fadingSurface && shouldFreeSurface)
  1297. SDL_FreeSurface(fadingSurface);
  1298. }
  1299. if (animDelta <= 0.0f)
  1300. {
  1301. logGlobal->warnStream() << "Fade anim: delta should be positive; " << animDelta << " given.";
  1302. animDelta = DEFAULT_DELTA;
  1303. }
  1304. if (sourceSurface)
  1305. fadingSurface = sourceSurface;
  1306. delta = animDelta;
  1307. fadingMode = mode;
  1308. fadingCounter = initialCounter();
  1309. fading = true;
  1310. shouldFreeSurface = freeSurfaceAtEnd;
  1311. }
  1312. void CFadeAnimation::draw(SDL_Surface * targetSurface, const SDL_Rect * sourceRect, SDL_Rect * destRect)
  1313. {
  1314. if (!fading || !fadingSurface || fadingMode == EMode::NONE)
  1315. {
  1316. fading = false;
  1317. return;
  1318. }
  1319. CSDL_Ext::setAlpha(fadingSurface, fadingCounter * 255);
  1320. SDL_BlitSurface(fadingSurface, const_cast<SDL_Rect *>(sourceRect), targetSurface, destRect); //FIXME
  1321. CSDL_Ext::setAlpha(fadingSurface, 255);
  1322. }