CAnimation.cpp 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564
  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. std::unique_ptr<IImage> 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. std::unique_ptr<IImage> 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(destShift.x, destShift.y, surf->w, surf->h);
  684. if(dest)
  685. {
  686. destRect.x += dest->x;
  687. destRect.y += dest->y;
  688. }
  689. if(surf->format->BitsPerPixel == 8)
  690. {
  691. CSDL_Ext::blit8bppAlphaTo24bpp(surf, &sourceRect, where, &destRect);
  692. }
  693. else
  694. {
  695. SDL_UpperBlit(surf, &sourceRect, where, &destRect);
  696. }
  697. }
  698. std::unique_ptr<IImage> SDLImage::scaleFast(float scale) const
  699. {
  700. auto scaled = CSDL_Ext::scaleSurfaceFast(surf, surf->w * scale, surf->h * scale);
  701. if (scaled->format && scaled->format->palette) // fix color keying, because SDL loses it at this point
  702. CSDL_Ext::setColorKey(scaled, scaled->format->palette->colors[0]);
  703. else if(scaled->format && scaled->format->Amask)
  704. SDL_SetSurfaceBlendMode(scaled, SDL_BLENDMODE_BLEND);//just in case
  705. else
  706. CSDL_Ext::setDefaultColorKey(scaled);//just in case
  707. SDLImage * ret = new SDLImage(scaled, false);
  708. ret->fullSize.x = (int) round((float)fullSize.x * scale);
  709. ret->fullSize.y = (int) round((float)fullSize.y * scale);
  710. ret->margins.x = (int) round((float)margins.x * scale);
  711. ret->margins.y = (int) round((float)margins.y * scale);
  712. return std::unique_ptr<IImage>(ret);
  713. }
  714. void SDLImage::playerColored(PlayerColor player)
  715. {
  716. graphics->blueToPlayersAdv(surf, player);
  717. }
  718. void SDLImage::setFlagColor(PlayerColor player)
  719. {
  720. if(player < PlayerColor::PLAYER_LIMIT || player==PlayerColor::NEUTRAL)
  721. CSDL_Ext::setPlayerColor(surf, player);
  722. }
  723. int SDLImage::width() const
  724. {
  725. return fullSize.x;
  726. }
  727. int SDLImage::height() const
  728. {
  729. return fullSize.y;
  730. }
  731. void SDLImage::horizontalFlip()
  732. {
  733. margins.y = fullSize.y - surf->h - margins.y;
  734. //todo: modify in-place
  735. SDL_Surface * flipped = CSDL_Ext::horizontalFlip(surf);
  736. SDL_FreeSurface(surf);
  737. surf = flipped;
  738. }
  739. void SDLImage::verticalFlip()
  740. {
  741. margins.x = fullSize.x - surf->w - margins.x;
  742. //todo: modify in-place
  743. SDL_Surface * flipped = CSDL_Ext::verticalFlip(surf);
  744. SDL_FreeSurface(surf);
  745. surf = flipped;
  746. }
  747. void SDLImage::shiftPalette(int from, int howMany)
  748. {
  749. //works with at most 16 colors, if needed more -> increase values
  750. assert(howMany < 16);
  751. if(surf->format->palette)
  752. {
  753. SDL_Color palette[16];
  754. for(int i=0; i<howMany; ++i)
  755. {
  756. palette[(i+1)%howMany] = surf->format->palette->colors[from + i];
  757. }
  758. SDL_SetColors(surf, palette, from, howMany);
  759. }
  760. }
  761. SDLImage::~SDLImage()
  762. {
  763. SDL_FreeSurface(surf);
  764. }
  765. CompImage::CompImage(const CDefFile *data, size_t frame, size_t group):
  766. surf(nullptr),
  767. line(nullptr),
  768. palette(nullptr)
  769. {
  770. CompImageLoader loader(this);
  771. data->loadFrame(frame, group, loader);
  772. }
  773. CompImage::CompImage(SDL_Surface * surf)
  774. {
  775. //TODO
  776. assert(0);
  777. }
  778. void CompImage::draw(SDL_Surface *where, int posX, int posY, Rect *src, ui8 alpha) const
  779. {
  780. Rect dest(posX,posY, width(), height());
  781. draw(where, &dest, src, alpha);
  782. }
  783. void CompImage::draw(SDL_Surface* where, SDL_Rect* dest, SDL_Rect* src, ui8 alpha) const
  784. {
  785. int rotation = 0; //TODO
  786. //rotation & 2 = horizontal rotation
  787. //rotation & 4 = vertical rotation
  788. if (!surf)
  789. return;
  790. Rect sourceRect(sprite);
  791. //TODO: rotation and scaling
  792. if (src)
  793. sourceRect = sourceRect & *src;
  794. //Limit source rect to sizes of surface
  795. sourceRect = sourceRect & Rect(0, 0, where->w, where->h);
  796. //Starting point on SDL surface
  797. Point dst(sourceRect.x,sourceRect.y);
  798. if (dest)
  799. {
  800. dst.x += dest->x;
  801. dst.y += dest->y;
  802. }
  803. if (rotation & 2)
  804. dst.y += sourceRect.h;
  805. if (rotation & 4)
  806. dst.x += sourceRect.w;
  807. sourceRect -= sprite.topLeft();
  808. for (int currY = 0; currY <sourceRect.h; currY++)
  809. {
  810. ui8* data = surf + line[currY+sourceRect.y];
  811. ui8 type = *(data++);
  812. ui8 size = *(data++);
  813. int currX = sourceRect.x;
  814. //Skip blocks until starting position reached
  815. while ( currX > size )
  816. {
  817. currX -= size;
  818. if (type == 0xff)
  819. data += size;
  820. type = *(data++);
  821. size = *(data++);
  822. }
  823. //This block will be shown partially - calculate size\position
  824. size -= currX;
  825. if (type == 0xff)
  826. data += currX;
  827. currX = 0;
  828. ui8 bpp = where->format->BytesPerPixel;
  829. //Calculate position for blitting: pixels + Y + X
  830. ui8* blitPos = (ui8*) where->pixels;
  831. if (rotation & 4)
  832. blitPos += (dst.y - currY) * where->pitch;
  833. else
  834. blitPos += (dst.y + currY) * where->pitch;
  835. blitPos += dst.x * bpp;
  836. //Blit blocks that must be fully visible
  837. while (currX + size < sourceRect.w)
  838. {
  839. //blit block, pointers will be modified if needed
  840. BlitBlockWithBpp(bpp, type, size, data, blitPos, alpha, rotation & 2);
  841. currX += size;
  842. type = *(data++);
  843. size = *(data++);
  844. }
  845. //Blit last, semi-visible block
  846. size = sourceRect.w - currX;
  847. BlitBlockWithBpp(bpp, type, size, data, blitPos, alpha, rotation & 2);
  848. }
  849. }
  850. std::unique_ptr<IImage> CompImage::scaleFast(float scale) const
  851. {
  852. //todo: CompImage::scaleFast
  853. logAnim->error("CompImage::scaleFast is not implemented");
  854. return nullptr;
  855. }
  856. #define CASEBPP(x,y) case x: BlitBlock<x,y>(type, size, data, dest, alpha); break
  857. //FIXME: better way to get blitter
  858. void CompImage::BlitBlockWithBpp(ui8 bpp, ui8 type, ui8 size, ui8 *&data, ui8 *&dest, ui8 alpha, bool rotated) const
  859. {
  860. assert(bpp>1 && bpp<5);
  861. if (rotated)
  862. switch (bpp)
  863. {
  864. CASEBPP(2,1);
  865. CASEBPP(3,1);
  866. CASEBPP(4,1);
  867. }
  868. else
  869. switch (bpp)
  870. {
  871. CASEBPP(2,1);
  872. CASEBPP(3,1);
  873. CASEBPP(4,1);
  874. }
  875. }
  876. #undef CASEBPP
  877. //Blit one block from RLE-d surface
  878. template<int bpp, int dir>
  879. void CompImage::BlitBlock(ui8 type, ui8 size, ui8 *&data, ui8 *&dest, ui8 alpha) const
  880. {
  881. //Raw data
  882. if (type == 0xff)
  883. {
  884. ui8 color = *data;
  885. if (alpha != 255)//Per-surface alpha is set
  886. {
  887. for (size_t i=0; i<size; i++)
  888. {
  889. SDL_Color col = palette[*(data++)];
  890. col.a = (ui32)col.a*alpha/255;
  891. ColorPutter<bpp, 1>::PutColorAlpha(dest, col);
  892. }
  893. return;
  894. }
  895. if (palette[color].a == 255)
  896. {
  897. //Put row of RGB data
  898. for (size_t i=0; i<size; i++)
  899. ColorPutter<bpp, 1>::PutColor(dest, palette[*(data++)]);
  900. }
  901. else
  902. {
  903. //Put row of RGBA data
  904. for (size_t i=0; i<size; i++)
  905. ColorPutter<bpp, 1>::PutColorAlpha(dest, palette[*(data++)]);
  906. }
  907. }
  908. //RLE-d sequence
  909. else
  910. {
  911. if (alpha != 255 && palette[type].a !=0)//Per-surface alpha is set
  912. {
  913. SDL_Color col = palette[type];
  914. col.a = (int)col.a*(255-alpha)/255;
  915. for (size_t i=0; i<size; i++)
  916. ColorPutter<bpp, 1>::PutColorAlpha(dest, col);
  917. return;
  918. }
  919. switch (palette[type].a)
  920. {
  921. case 0:
  922. {
  923. //Skip row
  924. dest += size*bpp;
  925. break;
  926. }
  927. case 255:
  928. {
  929. //Put RGB row
  930. ColorPutter<bpp, 1>::PutColorRow(dest, palette[type], size);
  931. break;
  932. }
  933. default:
  934. {
  935. //Put RGBA row
  936. for (size_t i=0; i<size; i++)
  937. ColorPutter<bpp, 1>::PutColorAlpha(dest, palette[type]);
  938. break;
  939. }
  940. }
  941. }
  942. }
  943. void CompImage::playerColored(PlayerColor player)
  944. {
  945. SDL_Color *pal = nullptr;
  946. if(player < PlayerColor::PLAYER_LIMIT)
  947. {
  948. pal = graphics->playerColorPalette + 32*player.getNum();
  949. }
  950. else if(player == PlayerColor::NEUTRAL)
  951. {
  952. pal = graphics->neutralColorPalette;
  953. }
  954. else
  955. assert(0);
  956. for(int i=0; i<32; ++i)
  957. {
  958. CSDL_Ext::colorAssign(palette[224+i],pal[i]);
  959. }
  960. }
  961. void CompImage::setFlagColor(PlayerColor player)
  962. {
  963. logAnim->error("CompImage::setFlagColor is not implemented");
  964. }
  965. int CompImage::width() const
  966. {
  967. return fullSize.x;
  968. }
  969. int CompImage::height() const
  970. {
  971. return fullSize.y;
  972. }
  973. CompImage::~CompImage()
  974. {
  975. free(surf);
  976. delete [] line;
  977. delete [] palette;
  978. }
  979. void CompImage::horizontalFlip()
  980. {
  981. logAnim->error("CompImage::horizontalFlip is not implemented");
  982. }
  983. void CompImage::verticalFlip()
  984. {
  985. logAnim->error("CompImage::verticalFlip is not implemented");
  986. }
  987. void CompImage::shiftPalette(int from, int howMany)
  988. {
  989. logAnim->error("CompImage::shiftPalette is not implemented");
  990. }
  991. /*************************************************************************
  992. * CAnimation for animations handling, can load part of file if needed *
  993. *************************************************************************/
  994. IImage * CAnimation::getFromExtraDef(std::string filename)
  995. {
  996. size_t pos = filename.find(':');
  997. if (pos == -1)
  998. return nullptr;
  999. CAnimation anim(filename.substr(0, pos));
  1000. pos++;
  1001. size_t frame = atoi(filename.c_str()+pos);
  1002. size_t group = 0;
  1003. pos = filename.find(':', pos);
  1004. if (pos != -1)
  1005. {
  1006. pos++;
  1007. group = frame;
  1008. frame = atoi(filename.c_str()+pos);
  1009. }
  1010. anim.load(frame ,group);
  1011. IImage * ret = anim.images[group][frame];
  1012. anim.images.clear();
  1013. return ret;
  1014. }
  1015. bool CAnimation::loadFrame(CDefFile * file, size_t frame, size_t group)
  1016. {
  1017. if (size(group) <= frame)
  1018. {
  1019. printError(frame, group, "LoadFrame");
  1020. return false;
  1021. }
  1022. IImage *image = getImage(frame, group, false);
  1023. if (image)
  1024. {
  1025. image->increaseRef();
  1026. return true;
  1027. }
  1028. //try to get image from def
  1029. if (source[group][frame].getType() == JsonNode::DATA_NULL)
  1030. {
  1031. if (file)
  1032. {
  1033. auto frameList = file->getEntries();
  1034. if (vstd::contains(frameList, group) && frameList.at(group) > frame) // frame is present
  1035. {
  1036. if (compressed)
  1037. images[group][frame] = new CompImage(file, frame, group);
  1038. else
  1039. images[group][frame] = new SDLImage(file, frame, group);
  1040. return true;
  1041. }
  1042. }
  1043. // still here? image is missing
  1044. printError(frame, group, "LoadFrame");
  1045. images[group][frame] = new SDLImage("DEFAULT", compressed);
  1046. }
  1047. else //load from separate file
  1048. {
  1049. std::string filename = source[group][frame]["file"].String();
  1050. IImage * img = getFromExtraDef(filename);
  1051. if (!img)
  1052. img = new SDLImage(filename, compressed);
  1053. images[group][frame] = img;
  1054. return true;
  1055. }
  1056. return false;
  1057. }
  1058. bool CAnimation::unloadFrame(size_t frame, size_t group)
  1059. {
  1060. IImage *image = getImage(frame, group, false);
  1061. if (image)
  1062. {
  1063. //decrease ref count for image and delete if needed
  1064. if (image->decreaseRef())
  1065. {
  1066. delete image;
  1067. images[group].erase(frame);
  1068. }
  1069. if (images[group].empty())
  1070. images.erase(group);
  1071. return true;
  1072. }
  1073. return false;
  1074. }
  1075. void CAnimation::initFromJson(const JsonNode & config)
  1076. {
  1077. std::string basepath;
  1078. basepath = config["basepath"].String();
  1079. for(const JsonNode &group : config["sequences"].Vector())
  1080. {
  1081. size_t groupID = group["group"].Float();//TODO: string-to-value conversion("moving" -> MOVING)
  1082. source[groupID].clear();
  1083. for(const JsonNode &frame : group["frames"].Vector())
  1084. {
  1085. source[groupID].push_back(JsonNode());
  1086. std::string filename = frame.String();
  1087. source[groupID].back()["file"].String() = basepath + filename;
  1088. }
  1089. }
  1090. for(const JsonNode &node : config["images"].Vector())
  1091. {
  1092. size_t group = node["group"].Float();
  1093. size_t frame = node["frame"].Float();
  1094. if (source[group].size() <= frame)
  1095. source[group].resize(frame+1);
  1096. source[group][frame] = node;
  1097. std::string filename = node["file"].String();
  1098. source[group][frame]["file"].String() = basepath + filename;
  1099. }
  1100. }
  1101. void CAnimation::init(CDefFile * file)
  1102. {
  1103. if (file)
  1104. {
  1105. const std::map<size_t, size_t> defEntries = file->getEntries();
  1106. for (auto & defEntry : defEntries)
  1107. source[defEntry.first].resize(defEntry.second);
  1108. }
  1109. ResourceID resID(std::string("SPRITES/") + name, EResType::TEXT);
  1110. if (vstd::contains(graphics->imageLists, resID.getName()))
  1111. initFromJson(graphics->imageLists[resID.getName()]);
  1112. auto configList = CResourceHandler::get()->getResourcesWithName(resID);
  1113. for(auto & loader : configList)
  1114. {
  1115. auto stream = loader->load(resID);
  1116. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  1117. stream->read(textData.get(), stream->getSize());
  1118. const JsonNode config((char*)textData.get(), stream->getSize());
  1119. initFromJson(config);
  1120. }
  1121. }
  1122. CDefFile * CAnimation::getFile() const
  1123. {
  1124. ResourceID identifier(std::string("SPRITES/") + name, EResType::ANIMATION);
  1125. if (CResourceHandler::get()->existsResource(identifier))
  1126. return new CDefFile(name);
  1127. return nullptr;
  1128. }
  1129. void CAnimation::printError(size_t frame, size_t group, std::string type) const
  1130. {
  1131. logGlobal->errorStream() << type << " error: Request for frame not present in CAnimation! "
  1132. << "\tFile name: " << name << " Group: " << group << " Frame: " << frame;
  1133. }
  1134. CAnimation::CAnimation(std::string Name, bool Compressed):
  1135. name(Name),
  1136. compressed(Compressed),
  1137. preloaded(false)
  1138. {
  1139. size_t dotPos = name.find_last_of('.');
  1140. if ( dotPos!=-1 )
  1141. name.erase(dotPos);
  1142. std::transform(name.begin(), name.end(), name.begin(), toupper);
  1143. CDefFile * file = getFile();
  1144. init(file);
  1145. delete file;
  1146. }
  1147. CAnimation::CAnimation():
  1148. name(""),
  1149. compressed(false),
  1150. preloaded(false)
  1151. {
  1152. init(nullptr);
  1153. }
  1154. CAnimation::~CAnimation()
  1155. {
  1156. if(preloaded)
  1157. unload();
  1158. if(!images.empty())
  1159. {
  1160. logGlobal->warnStream()<<"Warning: not all frames were unloaded from "<<name;
  1161. for (auto & elem : images)
  1162. for (auto & _image : elem.second)
  1163. delete _image.second;
  1164. }
  1165. }
  1166. void CAnimation::duplicateImage(const size_t sourceGroup, const size_t sourceFrame, const size_t targetGroup)
  1167. {
  1168. //todo: clone actual loaded Image object
  1169. JsonNode clone(source[sourceGroup][sourceFrame]);
  1170. if(clone.getType() == JsonNode::DATA_NULL)
  1171. {
  1172. std::string temp = name+":"+boost::lexical_cast<std::string>(sourceGroup)+":"+boost::lexical_cast<std::string>(sourceFrame);
  1173. clone["file"].String() = temp;
  1174. }
  1175. source[targetGroup].push_back(clone);
  1176. size_t index = source[targetGroup].size() - 1;
  1177. if(preloaded)
  1178. load(index, targetGroup);
  1179. }
  1180. void CAnimation::setCustom(std::string filename, size_t frame, size_t group)
  1181. {
  1182. if (source[group].size() <= frame)
  1183. source[group].resize(frame+1);
  1184. source[group][frame]["file"].String() = filename;
  1185. //FIXME: update image if already loaded
  1186. }
  1187. IImage * CAnimation::getImage(size_t frame, size_t group, bool verbose) const
  1188. {
  1189. auto groupIter = images.find(group);
  1190. if (groupIter != images.end())
  1191. {
  1192. auto imageIter = groupIter->second.find(frame);
  1193. if (imageIter != groupIter->second.end())
  1194. return imageIter->second;
  1195. }
  1196. if (verbose)
  1197. printError(frame, group, "GetImage");
  1198. return nullptr;
  1199. }
  1200. void CAnimation::load()
  1201. {
  1202. CDefFile * file = getFile();
  1203. for (auto & elem : source)
  1204. for (size_t image=0; image < elem.second.size(); image++)
  1205. loadFrame(file, image, elem.first);
  1206. delete file;
  1207. }
  1208. void CAnimation::unload()
  1209. {
  1210. for (auto & elem : source)
  1211. for (size_t image=0; image < elem.second.size(); image++)
  1212. unloadFrame(image, elem.first);
  1213. }
  1214. void CAnimation::preload()
  1215. {
  1216. if(!preloaded)
  1217. {
  1218. preloaded = true;
  1219. load();
  1220. }
  1221. }
  1222. void CAnimation::loadGroup(size_t group)
  1223. {
  1224. CDefFile * file = getFile();
  1225. if (vstd::contains(source, group))
  1226. for (size_t image=0; image < source[group].size(); image++)
  1227. loadFrame(file, image, group);
  1228. delete file;
  1229. }
  1230. void CAnimation::unloadGroup(size_t group)
  1231. {
  1232. if (vstd::contains(source, group))
  1233. for (size_t image=0; image < source[group].size(); image++)
  1234. unloadFrame(image, group);
  1235. }
  1236. void CAnimation::load(size_t frame, size_t group)
  1237. {
  1238. CDefFile * file = getFile();
  1239. loadFrame(file, frame, group);
  1240. delete file;
  1241. }
  1242. void CAnimation::unload(size_t frame, size_t group)
  1243. {
  1244. unloadFrame(frame, group);
  1245. }
  1246. size_t CAnimation::size(size_t group) const
  1247. {
  1248. auto iter = source.find(group);
  1249. if (iter != source.end())
  1250. return iter->second.size();
  1251. return 0;
  1252. }
  1253. float CFadeAnimation::initialCounter() const
  1254. {
  1255. if (fadingMode == EMode::OUT)
  1256. return 1.0f;
  1257. return 0.0f;
  1258. }
  1259. void CFadeAnimation::update()
  1260. {
  1261. if (!fading)
  1262. return;
  1263. if (fadingMode == EMode::OUT)
  1264. fadingCounter -= delta;
  1265. else
  1266. fadingCounter += delta;
  1267. if (isFinished())
  1268. {
  1269. fading = false;
  1270. if (shouldFreeSurface)
  1271. {
  1272. SDL_FreeSurface(fadingSurface);
  1273. fadingSurface = nullptr;
  1274. }
  1275. }
  1276. }
  1277. bool CFadeAnimation::isFinished() const
  1278. {
  1279. if (fadingMode == EMode::OUT)
  1280. return fadingCounter <= 0.0f;
  1281. return fadingCounter >= 1.0f;
  1282. }
  1283. CFadeAnimation::CFadeAnimation()
  1284. : fadingSurface(nullptr),
  1285. fading(false),
  1286. fadingMode(EMode::NONE)
  1287. {
  1288. }
  1289. CFadeAnimation::~CFadeAnimation()
  1290. {
  1291. if (fadingSurface && shouldFreeSurface)
  1292. SDL_FreeSurface(fadingSurface);
  1293. }
  1294. void CFadeAnimation::init(EMode mode, SDL_Surface * sourceSurface, bool freeSurfaceAtEnd /* = false */, float animDelta /* = DEFAULT_DELTA */)
  1295. {
  1296. if (fading)
  1297. {
  1298. // in that case, immediately finish the previous fade
  1299. // (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))
  1300. logGlobal->warnStream() << "Tried to init fading animation that is already running.";
  1301. if (fadingSurface && shouldFreeSurface)
  1302. SDL_FreeSurface(fadingSurface);
  1303. }
  1304. if (animDelta <= 0.0f)
  1305. {
  1306. logGlobal->warnStream() << "Fade anim: delta should be positive; " << animDelta << " given.";
  1307. animDelta = DEFAULT_DELTA;
  1308. }
  1309. if (sourceSurface)
  1310. fadingSurface = sourceSurface;
  1311. delta = animDelta;
  1312. fadingMode = mode;
  1313. fadingCounter = initialCounter();
  1314. fading = true;
  1315. shouldFreeSurface = freeSurfaceAtEnd;
  1316. }
  1317. void CFadeAnimation::draw(SDL_Surface * targetSurface, const SDL_Rect * sourceRect, SDL_Rect * destRect)
  1318. {
  1319. if (!fading || !fadingSurface || fadingMode == EMode::NONE)
  1320. {
  1321. fading = false;
  1322. return;
  1323. }
  1324. CSDL_Ext::setAlpha(fadingSurface, fadingCounter * 255);
  1325. SDL_BlitSurface(fadingSurface, const_cast<SDL_Rect *>(sourceRect), targetSurface, destRect); //FIXME
  1326. CSDL_Ext::setAlpha(fadingSurface, 255);
  1327. }