CAnimation.cpp 40 KB

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