CAnimation.cpp 38 KB

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