CAnimation.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299
  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_Extensions.h"
  13. #include "SDL_Pixels.h"
  14. #include "ColorFilter.h"
  15. #include "../CBitmapHandler.h"
  16. #include "../Graphics.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. typedef std::map <size_t, std::vector <JsonNode> > source_map;
  23. typedef std::map<size_t, IImage* > image_map;
  24. typedef std::map<size_t, image_map > group_map;
  25. /// Class for def loading
  26. /// After loading will store general info (palette and frame offsets) and pointer to file itself
  27. class CDefFile
  28. {
  29. private:
  30. struct SSpriteDef
  31. {
  32. ui32 size;
  33. ui32 format; /// format in which pixel data is stored
  34. ui32 fullWidth; /// full width and height of frame, including borders
  35. ui32 fullHeight;
  36. ui32 width; /// width and height of pixel data, borders excluded
  37. ui32 height;
  38. si32 leftMargin;
  39. si32 topMargin;
  40. } PACKED_STRUCT;
  41. //offset[group][frame] - offset of frame data in file
  42. std::map<size_t, std::vector <size_t> > offset;
  43. std::unique_ptr<ui8[]> data;
  44. std::unique_ptr<SDL_Color[]> palette;
  45. public:
  46. CDefFile(std::string Name);
  47. ~CDefFile();
  48. //load frame as SDL_Surface
  49. template<class ImageLoader>
  50. void loadFrame(size_t frame, size_t group, ImageLoader &loader) const;
  51. const std::map<size_t, size_t> getEntries() const;
  52. };
  53. /*
  54. * Wrapper around SDL_Surface
  55. */
  56. class SDLImage : public IImage
  57. {
  58. public:
  59. const static int DEFAULT_PALETTE_COLORS = 256;
  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);
  69. //Load from bitmap file
  70. SDLImage(std::string filename);
  71. SDLImage(const JsonNode & conf);
  72. //Create using existing surface, extraRef will increase refcount on SDL_Surface
  73. SDLImage(SDL_Surface * from, bool extraRef);
  74. ~SDLImage();
  75. // Keep the original palette, in order to do color switching operation
  76. void savePalette();
  77. void draw(SDL_Surface * where, int posX=0, int posY=0, const Rect *src=nullptr, ui8 alpha=255) const override;
  78. void draw(SDL_Surface * where, const SDL_Rect * dest, const SDL_Rect * src, ui8 alpha=255) const override;
  79. std::shared_ptr<IImage> scaleFast(float scale) const override;
  80. void exportBitmap(const boost::filesystem::path & path) const override;
  81. void playerColored(PlayerColor player) override;
  82. void setFlagColor(PlayerColor player) override;
  83. bool isTransparent(const Point & coords) const override;
  84. Point dimensions() const override;
  85. void horizontalFlip() override;
  86. void verticalFlip() override;
  87. void shiftPalette(int from, int howMany) override;
  88. void adjustPalette(const ColorFilter & shifter) override;
  89. void resetPalette(int colorID) override;
  90. void resetPalette() override;
  91. void setSpecialPallete(const SpecialPalette & SpecialPalette) override;
  92. friend class SDLImageLoader;
  93. private:
  94. SDL_Palette * originalPalette;
  95. };
  96. class SDLImageLoader
  97. {
  98. SDLImage * image;
  99. ui8 * lineStart;
  100. ui8 * position;
  101. public:
  102. //load size raw pixels from data
  103. inline void Load(size_t size, const ui8 * data);
  104. //set size pixels to color
  105. inline void Load(size_t size, ui8 color=0);
  106. inline void EndLine();
  107. //init image with these sizes and palette
  108. inline void init(Point SpriteSize, Point Margins, Point FullSize, SDL_Color *pal);
  109. SDLImageLoader(SDLImage * Img);
  110. ~SDLImageLoader();
  111. };
  112. std::shared_ptr<IImage> IImage::createFromFile( const std::string & path )
  113. {
  114. return std::shared_ptr<IImage>(new SDLImage(path));
  115. }
  116. // Extremely simple file cache. TODO: smarter, more general solution
  117. class CFileCache
  118. {
  119. static const int cacheSize = 50; //Max number of cached files
  120. struct FileData
  121. {
  122. ResourceID name;
  123. size_t size;
  124. std::unique_ptr<ui8[]> data;
  125. std::unique_ptr<ui8[]> getCopy()
  126. {
  127. auto ret = std::unique_ptr<ui8[]>(new ui8[size]);
  128. std::copy(data.get(), data.get() + size, ret.get());
  129. return ret;
  130. }
  131. FileData(ResourceID name_, size_t size_, std::unique_ptr<ui8[]> data_):
  132. name{std::move(name_)},
  133. size{size_},
  134. data{std::move(data_)}
  135. {}
  136. };
  137. std::deque<FileData> cache;
  138. public:
  139. std::unique_ptr<ui8[]> getCachedFile(ResourceID rid)
  140. {
  141. for(auto & file : cache)
  142. {
  143. if (file.name == rid)
  144. return file.getCopy();
  145. }
  146. // Still here? Cache miss
  147. if (cache.size() > cacheSize)
  148. cache.pop_front();
  149. auto data = CResourceHandler::get()->load(rid)->readAll();
  150. cache.emplace_back(std::move(rid), data.second, std::move(data.first));
  151. return cache.back().getCopy();
  152. }
  153. };
  154. enum class DefType : uint32_t
  155. {
  156. SPELL = 0x40,
  157. SPRITE = 0x41,
  158. CREATURE = 0x42,
  159. MAP = 0x43,
  160. MAP_HERO = 0x44,
  161. TERRAIN = 0x45,
  162. CURSOR = 0x46,
  163. INTERFACE = 0x47,
  164. SPRITE_FRAME = 0x48,
  165. BATTLE_HERO = 0x49
  166. };
  167. static CFileCache animationCache;
  168. /*************************************************************************
  169. * DefFile, class used for def loading *
  170. *************************************************************************/
  171. bool operator== (const SDL_Color & lhs, const SDL_Color & rhs)
  172. {
  173. return (lhs.a == rhs.a) && (lhs.b == rhs.b) &&(lhs.g == rhs.g) &&(lhs.r == rhs.r);
  174. }
  175. CDefFile::CDefFile(std::string Name):
  176. data(nullptr),
  177. palette(nullptr)
  178. {
  179. //First 8 colors in def palette used for transparency
  180. static SDL_Color H3Palette[8] =
  181. {
  182. { 0, 0, 0, 0},// transparency ( used in most images )
  183. { 0, 0, 0, 64},// shadow border ( used in battle, adventure map def's )
  184. { 0, 0, 0, 64},// shadow border ( used in fog-of-war def's )
  185. { 0, 0, 0, 128},// shadow body ( used in fog-of-war def's )
  186. { 0, 0, 0, 128},// shadow body ( used in battle, adventure map def's )
  187. { 0, 0, 0, 0},// selection ( used in battle def's )
  188. { 0, 0, 0, 128},// shadow body below selection ( used in battle def's )
  189. { 0, 0, 0, 64} // shadow border below selection ( used in battle def's )
  190. };
  191. data = animationCache.getCachedFile(ResourceID(std::string("SPRITES/") + Name, EResType::ANIMATION));
  192. palette = std::unique_ptr<SDL_Color[]>(new SDL_Color[256]);
  193. int it = 0;
  194. ui32 type = read_le_u32(data.get() + it);
  195. it+=4;
  196. //int width = read_le_u32(data + it); it+=4;//not used
  197. //int height = read_le_u32(data + it); it+=4;
  198. it+=8;
  199. ui32 totalBlocks = read_le_u32(data.get() + it);
  200. it+=4;
  201. for (ui32 i= 0; i<256; i++)
  202. {
  203. palette[i].r = data[it++];
  204. palette[i].g = data[it++];
  205. palette[i].b = data[it++];
  206. palette[i].a = SDL_ALPHA_OPAQUE;
  207. }
  208. switch(static_cast<DefType>(type))
  209. {
  210. case DefType::SPELL:
  211. palette[0] = H3Palette[0];
  212. break;
  213. case DefType::SPRITE:
  214. case DefType::SPRITE_FRAME:
  215. for(ui32 i= 0; i<8; i++)
  216. palette[i] = H3Palette[i];
  217. break;
  218. case DefType::CREATURE:
  219. palette[0] = H3Palette[0];
  220. palette[1] = H3Palette[1];
  221. palette[4] = H3Palette[4];
  222. palette[5] = H3Palette[5];
  223. palette[6] = H3Palette[6];
  224. palette[7] = H3Palette[7];
  225. break;
  226. case DefType::MAP:
  227. case DefType::MAP_HERO:
  228. palette[0] = H3Palette[0];
  229. palette[1] = H3Palette[1];
  230. palette[4] = H3Palette[4];
  231. //5 = owner flag, handled separately
  232. break;
  233. case DefType::TERRAIN:
  234. palette[0] = H3Palette[0];
  235. palette[1] = H3Palette[1];
  236. palette[2] = H3Palette[2];
  237. palette[3] = H3Palette[3];
  238. palette[4] = H3Palette[4];
  239. break;
  240. case DefType::CURSOR:
  241. palette[0] = H3Palette[0];
  242. break;
  243. case DefType::INTERFACE:
  244. palette[0] = H3Palette[0];
  245. palette[1] = H3Palette[1];
  246. palette[4] = H3Palette[4];
  247. //player colors handled separately
  248. //TODO: disallow colorizing other def types
  249. break;
  250. case DefType::BATTLE_HERO:
  251. palette[0] = H3Palette[0];
  252. palette[1] = H3Palette[1];
  253. palette[4] = H3Palette[4];
  254. break;
  255. default:
  256. logAnim->error("Unknown def type %d in %s", type, Name);
  257. break;
  258. }
  259. for (ui32 i=0; i<totalBlocks; i++)
  260. {
  261. size_t blockID = read_le_u32(data.get() + it);
  262. it+=4;
  263. size_t totalEntries = read_le_u32(data.get() + it);
  264. it+=12;
  265. //8 unknown bytes - skipping
  266. //13 bytes for name of every frame in this block - not used, skipping
  267. it+= 13 * (int)totalEntries;
  268. for (ui32 j=0; j<totalEntries; j++)
  269. {
  270. size_t currOffset = read_le_u32(data.get() + it);
  271. offset[blockID].push_back(currOffset);
  272. it += 4;
  273. }
  274. }
  275. }
  276. template<class ImageLoader>
  277. void CDefFile::loadFrame(size_t frame, size_t group, ImageLoader &loader) const
  278. {
  279. std::map<size_t, std::vector <size_t> >::const_iterator it;
  280. it = offset.find(group);
  281. assert (it != offset.end());
  282. const ui8 * FDef = data.get()+it->second[frame];
  283. const SSpriteDef sd = * reinterpret_cast<const SSpriteDef *>(FDef);
  284. SSpriteDef sprite;
  285. sprite.format = read_le_u32(&sd.format);
  286. sprite.fullWidth = read_le_u32(&sd.fullWidth);
  287. sprite.fullHeight = read_le_u32(&sd.fullHeight);
  288. sprite.width = read_le_u32(&sd.width);
  289. sprite.height = read_le_u32(&sd.height);
  290. sprite.leftMargin = read_le_u32(&sd.leftMargin);
  291. sprite.topMargin = read_le_u32(&sd.topMargin);
  292. ui32 currentOffset = sizeof(SSpriteDef);
  293. //special case for some "old" format defs (SGTWMTA.DEF and SGTWMTB.DEF)
  294. if(sprite.format == 1 && sprite.width > sprite.fullWidth && sprite.height > sprite.fullHeight)
  295. {
  296. sprite.leftMargin = 0;
  297. sprite.topMargin = 0;
  298. sprite.width = sprite.fullWidth;
  299. sprite.height = sprite.fullHeight;
  300. currentOffset -= 16;
  301. }
  302. const ui32 BaseOffset = currentOffset;
  303. loader.init(Point(sprite.width, sprite.height),
  304. Point(sprite.leftMargin, sprite.topMargin),
  305. Point(sprite.fullWidth, sprite.fullHeight), palette.get());
  306. switch(sprite.format)
  307. {
  308. case 0:
  309. {
  310. //pixel data is not compressed, copy data to surface
  311. for(ui32 i=0; i<sprite.height; i++)
  312. {
  313. loader.Load(sprite.width, FDef + currentOffset);
  314. currentOffset += sprite.width;
  315. loader.EndLine();
  316. }
  317. break;
  318. }
  319. case 1:
  320. {
  321. //for each line we have offset of pixel data
  322. const ui32 * RWEntriesLoc = reinterpret_cast<const ui32 *>(FDef+currentOffset);
  323. currentOffset += sizeof(ui32) * sprite.height;
  324. for(ui32 i=0; i<sprite.height; i++)
  325. {
  326. //get position of the line
  327. currentOffset=BaseOffset + read_le_u32(RWEntriesLoc + i);
  328. ui32 TotalRowLength = 0;
  329. while(TotalRowLength<sprite.width)
  330. {
  331. ui8 segmentType = FDef[currentOffset++];
  332. ui32 length = FDef[currentOffset++] + 1;
  333. if(segmentType==0xFF)//Raw data
  334. {
  335. loader.Load(length, FDef + currentOffset);
  336. currentOffset+=length;
  337. }
  338. else// RLE
  339. {
  340. loader.Load(length, segmentType);
  341. }
  342. TotalRowLength += length;
  343. }
  344. loader.EndLine();
  345. }
  346. break;
  347. }
  348. case 2:
  349. {
  350. currentOffset = BaseOffset + read_le_u16(FDef + BaseOffset);
  351. for(ui32 i=0; i<sprite.height; i++)
  352. {
  353. ui32 TotalRowLength=0;
  354. while(TotalRowLength<sprite.width)
  355. {
  356. ui8 segment=FDef[currentOffset++];
  357. ui8 code = segment / 32;
  358. ui8 length = (segment & 31) + 1;
  359. if(code==7)//Raw data
  360. {
  361. loader.Load(length, FDef + currentOffset);
  362. currentOffset += length;
  363. }
  364. else//RLE
  365. {
  366. loader.Load(length, code);
  367. }
  368. TotalRowLength+=length;
  369. }
  370. loader.EndLine();
  371. }
  372. break;
  373. }
  374. case 3:
  375. {
  376. for(ui32 i=0; i<sprite.height; i++)
  377. {
  378. currentOffset = BaseOffset + read_le_u16(FDef + BaseOffset+i*2*(sprite.width/32));
  379. ui32 TotalRowLength=0;
  380. while(TotalRowLength<sprite.width)
  381. {
  382. ui8 segment = FDef[currentOffset++];
  383. ui8 code = segment / 32;
  384. ui8 length = (segment & 31) + 1;
  385. if(code==7)//Raw data
  386. {
  387. loader.Load(length, FDef + currentOffset);
  388. currentOffset += length;
  389. }
  390. else//RLE
  391. {
  392. loader.Load(length, code);
  393. }
  394. TotalRowLength += length;
  395. }
  396. loader.EndLine();
  397. }
  398. break;
  399. }
  400. default:
  401. logGlobal->error("Error: unsupported format of def file: %d", sprite.format);
  402. break;
  403. }
  404. }
  405. CDefFile::~CDefFile() = default;
  406. const std::map<size_t, size_t > CDefFile::getEntries() const
  407. {
  408. std::map<size_t, size_t > ret;
  409. for (auto & elem : offset)
  410. ret[elem.first] = elem.second.size();
  411. return ret;
  412. }
  413. /*************************************************************************
  414. * Classes for image loaders - helpers for loading from def files *
  415. *************************************************************************/
  416. SDLImageLoader::SDLImageLoader(SDLImage * Img):
  417. image(Img),
  418. lineStart(nullptr),
  419. position(nullptr)
  420. {
  421. }
  422. void SDLImageLoader::init(Point SpriteSize, Point Margins, Point FullSize, SDL_Color *pal)
  423. {
  424. //Init image
  425. image->surf = SDL_CreateRGBSurface(0, SpriteSize.x, SpriteSize.y, 8, 0, 0, 0, 0);
  426. image->margins = Margins;
  427. image->fullSize = FullSize;
  428. //Prepare surface
  429. SDL_Palette * p = SDL_AllocPalette(SDLImage::DEFAULT_PALETTE_COLORS);
  430. SDL_SetPaletteColors(p, pal, 0, SDLImage::DEFAULT_PALETTE_COLORS);
  431. SDL_SetSurfacePalette(image->surf, p);
  432. SDL_FreePalette(p);
  433. SDL_LockSurface(image->surf);
  434. lineStart = position = (ui8*)image->surf->pixels;
  435. }
  436. inline void SDLImageLoader::Load(size_t size, const ui8 * data)
  437. {
  438. if (size)
  439. {
  440. memcpy((void *)position, data, size);
  441. position += size;
  442. }
  443. }
  444. inline void SDLImageLoader::Load(size_t size, ui8 color)
  445. {
  446. if (size)
  447. {
  448. memset((void *)position, color, size);
  449. position += size;
  450. }
  451. }
  452. inline void SDLImageLoader::EndLine()
  453. {
  454. lineStart += image->surf->pitch;
  455. position = lineStart;
  456. }
  457. SDLImageLoader::~SDLImageLoader()
  458. {
  459. SDL_UnlockSurface(image->surf);
  460. SDL_SetColorKey(image->surf, SDL_TRUE, 0);
  461. //TODO: RLE if compressed and bpp>1
  462. }
  463. /*************************************************************************
  464. * Classes for images, support loading from file and drawing on surface *
  465. *************************************************************************/
  466. IImage::IImage() = default;
  467. IImage::~IImage() = default;
  468. int IImage::width() const
  469. {
  470. return dimensions().x;
  471. }
  472. int IImage::height() const
  473. {
  474. return dimensions().y;
  475. }
  476. SDLImage::SDLImage(CDefFile * data, size_t frame, size_t group)
  477. : surf(nullptr),
  478. margins(0, 0),
  479. fullSize(0, 0),
  480. originalPalette(nullptr)
  481. {
  482. SDLImageLoader loader(this);
  483. data->loadFrame(frame, group, loader);
  484. savePalette();
  485. }
  486. SDLImage::SDLImage(SDL_Surface * from, bool extraRef)
  487. : surf(nullptr),
  488. margins(0, 0),
  489. fullSize(0, 0),
  490. originalPalette(nullptr)
  491. {
  492. surf = from;
  493. if (surf == nullptr)
  494. return;
  495. savePalette();
  496. if (extraRef)
  497. surf->refcount++;
  498. fullSize.x = surf->w;
  499. fullSize.y = surf->h;
  500. }
  501. SDLImage::SDLImage(const JsonNode & conf)
  502. : surf(nullptr),
  503. margins(0, 0),
  504. fullSize(0, 0),
  505. originalPalette(nullptr)
  506. {
  507. std::string filename = conf["file"].String();
  508. surf = BitmapHandler::loadBitmap(filename);
  509. if(surf == nullptr)
  510. return;
  511. savePalette();
  512. const JsonNode & jsonMargins = conf["margins"];
  513. margins.x = static_cast<int>(jsonMargins["left"].Integer());
  514. margins.y = static_cast<int>(jsonMargins["top"].Integer());
  515. fullSize.x = static_cast<int>(conf["width"].Integer());
  516. fullSize.y = static_cast<int>(conf["height"].Integer());
  517. if(fullSize.x == 0)
  518. {
  519. fullSize.x = margins.x + surf->w + (int)jsonMargins["right"].Integer();
  520. }
  521. if(fullSize.y == 0)
  522. {
  523. fullSize.y = margins.y + surf->h + (int)jsonMargins["bottom"].Integer();
  524. }
  525. }
  526. SDLImage::SDLImage(std::string filename)
  527. : surf(nullptr),
  528. margins(0, 0),
  529. fullSize(0, 0),
  530. originalPalette(nullptr)
  531. {
  532. surf = BitmapHandler::loadBitmap(filename);
  533. if(surf == nullptr)
  534. {
  535. logGlobal->error("Error: failed to load image %s", filename);
  536. return;
  537. }
  538. else
  539. {
  540. savePalette();
  541. fullSize.x = surf->w;
  542. fullSize.y = surf->h;
  543. }
  544. }
  545. void SDLImage::draw(SDL_Surface *where, int posX, int posY, const Rect *src, ui8 alpha) const
  546. {
  547. if(!surf)
  548. return;
  549. Rect destRect(posX, posY, surf->w, surf->h);
  550. draw(where, &destRect, src);
  551. }
  552. void SDLImage::draw(SDL_Surface* where, const SDL_Rect* dest, const SDL_Rect* src, ui8 alpha) const
  553. {
  554. if (!surf)
  555. return;
  556. Rect sourceRect(0, 0, surf->w, surf->h);
  557. Point destShift(0, 0);
  558. if(src)
  559. {
  560. if(src->x < margins.x)
  561. destShift.x += margins.x - src->x;
  562. if(src->y < margins.y)
  563. destShift.y += margins.y - src->y;
  564. sourceRect = Rect(*src) & Rect(margins.x, margins.y, surf->w, surf->h);
  565. sourceRect -= margins;
  566. }
  567. else
  568. destShift = margins;
  569. Rect destRect(destShift.x, destShift.y, surf->w, surf->h);
  570. if(dest)
  571. {
  572. destRect.x += dest->x;
  573. destRect.y += dest->y;
  574. }
  575. if(surf->format->BitsPerPixel == 8)
  576. {
  577. CSDL_Ext::blit8bppAlphaTo24bpp(surf, &sourceRect, where, &destRect);
  578. }
  579. else
  580. {
  581. SDL_UpperBlit(surf, &sourceRect, where, &destRect);
  582. }
  583. }
  584. std::shared_ptr<IImage> SDLImage::scaleFast(float scale) const
  585. {
  586. auto scaled = CSDL_Ext::scaleSurfaceFast(surf, (int)(surf->w * scale), (int)(surf->h * scale));
  587. if (scaled->format && scaled->format->palette) // fix color keying, because SDL loses it at this point
  588. CSDL_Ext::setColorKey(scaled, scaled->format->palette->colors[0]);
  589. else if(scaled->format && scaled->format->Amask)
  590. SDL_SetSurfaceBlendMode(scaled, SDL_BLENDMODE_BLEND);//just in case
  591. else
  592. CSDL_Ext::setDefaultColorKey(scaled);//just in case
  593. SDLImage * ret = new SDLImage(scaled, false);
  594. ret->fullSize.x = (int) round((float)fullSize.x * scale);
  595. ret->fullSize.y = (int) round((float)fullSize.y * scale);
  596. ret->margins.x = (int) round((float)margins.x * scale);
  597. ret->margins.y = (int) round((float)margins.y * scale);
  598. return std::shared_ptr<IImage>(ret);
  599. }
  600. void SDLImage::exportBitmap(const boost::filesystem::path& path) const
  601. {
  602. SDL_SaveBMP(surf, path.string().c_str());
  603. }
  604. void SDLImage::playerColored(PlayerColor player)
  605. {
  606. graphics->blueToPlayersAdv(surf, player);
  607. }
  608. void SDLImage::setFlagColor(PlayerColor player)
  609. {
  610. if(player < PlayerColor::PLAYER_LIMIT || player==PlayerColor::NEUTRAL)
  611. CSDL_Ext::setPlayerColor(surf, player);
  612. }
  613. bool SDLImage::isTransparent(const Point & coords) const
  614. {
  615. return CSDL_Ext::isTransparent(surf, coords.x, coords.y);
  616. }
  617. Point SDLImage::dimensions() const
  618. {
  619. return fullSize;
  620. }
  621. void SDLImage::horizontalFlip()
  622. {
  623. margins.y = fullSize.y - surf->h - margins.y;
  624. //todo: modify in-place
  625. SDL_Surface * flipped = CSDL_Ext::horizontalFlip(surf);
  626. SDL_FreeSurface(surf);
  627. surf = flipped;
  628. }
  629. void SDLImage::verticalFlip()
  630. {
  631. margins.x = fullSize.x - surf->w - margins.x;
  632. //todo: modify in-place
  633. SDL_Surface * flipped = CSDL_Ext::verticalFlip(surf);
  634. SDL_FreeSurface(surf);
  635. surf = flipped;
  636. }
  637. // Keep the original palette, in order to do color switching operation
  638. void SDLImage::savePalette()
  639. {
  640. // For some images that don't have palette, skip this
  641. if(surf->format->palette == nullptr)
  642. return;
  643. if(originalPalette == nullptr)
  644. originalPalette = SDL_AllocPalette(DEFAULT_PALETTE_COLORS);
  645. SDL_SetPaletteColors(originalPalette, surf->format->palette->colors, 0, DEFAULT_PALETTE_COLORS);
  646. }
  647. void SDLImage::shiftPalette(int from, int howMany)
  648. {
  649. //works with at most 16 colors, if needed more -> increase values
  650. assert(howMany < 16);
  651. if(surf->format->palette)
  652. {
  653. SDL_Color palette[16];
  654. for(int i=0; i<howMany; ++i)
  655. {
  656. palette[(i+1)%howMany] = surf->format->palette->colors[from + i];
  657. }
  658. SDL_SetColors(surf, palette, from, howMany);
  659. }
  660. }
  661. void SDLImage::adjustPalette(const ColorFilter & shifter)
  662. {
  663. if(originalPalette == nullptr)
  664. return;
  665. SDL_Palette* palette = surf->format->palette;
  666. // Note: here we skip the first 8 colors in the palette that predefined in H3Palette
  667. for(int i = 8; i < palette->ncolors; i++)
  668. {
  669. palette->colors[i] = shifter.shiftColor(originalPalette->colors[i]);
  670. }
  671. }
  672. void SDLImage::resetPalette()
  673. {
  674. if(originalPalette == nullptr)
  675. return;
  676. // Always keept the original palette not changed, copy a new palette to assign to surface
  677. SDL_SetPaletteColors(surf->format->palette, originalPalette->colors, 0, originalPalette->ncolors);
  678. }
  679. void SDLImage::resetPalette( int colorID )
  680. {
  681. if(originalPalette == nullptr)
  682. return;
  683. // Always keept the original palette not changed, copy a new palette to assign to surface
  684. SDL_SetPaletteColors(surf->format->palette, originalPalette->colors + colorID, colorID, 1);
  685. }
  686. void SDLImage::setSpecialPallete(const IImage::SpecialPalette & SpecialPalette)
  687. {
  688. if(surf->format->palette)
  689. {
  690. SDL_SetColors(surf, const_cast<SDL_Color *>(SpecialPalette.data()), 1, 7);
  691. }
  692. }
  693. SDLImage::~SDLImage()
  694. {
  695. SDL_FreeSurface(surf);
  696. if(originalPalette != nullptr)
  697. {
  698. SDL_FreePalette(originalPalette);
  699. originalPalette = nullptr;
  700. }
  701. }
  702. std::shared_ptr<IImage> CAnimation::getFromExtraDef(std::string filename)
  703. {
  704. size_t pos = filename.find(':');
  705. if (pos == -1)
  706. return nullptr;
  707. CAnimation anim(filename.substr(0, pos));
  708. pos++;
  709. size_t frame = atoi(filename.c_str()+pos);
  710. size_t group = 0;
  711. pos = filename.find(':', pos);
  712. if (pos != -1)
  713. {
  714. pos++;
  715. group = frame;
  716. frame = atoi(filename.c_str()+pos);
  717. }
  718. anim.load(frame ,group);
  719. auto ret = anim.images[group][frame];
  720. anim.images.clear();
  721. return ret;
  722. }
  723. bool CAnimation::loadFrame(size_t frame, size_t group)
  724. {
  725. if(size(group) <= frame)
  726. {
  727. printError(frame, group, "LoadFrame");
  728. return false;
  729. }
  730. auto image = getImage(frame, group, false);
  731. if(image)
  732. {
  733. return true;
  734. }
  735. //try to get image from def
  736. if(source[group][frame].getType() == JsonNode::JsonType::DATA_NULL)
  737. {
  738. if(defFile)
  739. {
  740. auto frameList = defFile->getEntries();
  741. if(vstd::contains(frameList, group) && frameList.at(group) > frame) // frame is present
  742. {
  743. images[group][frame] = std::make_shared<SDLImage>(defFile.get(), frame, group);
  744. return true;
  745. }
  746. }
  747. // still here? image is missing
  748. printError(frame, group, "LoadFrame");
  749. images[group][frame] = std::make_shared<SDLImage>("DEFAULT");
  750. }
  751. else //load from separate file
  752. {
  753. auto img = getFromExtraDef(source[group][frame]["file"].String());
  754. if(!img)
  755. img = std::make_shared<SDLImage>(source[group][frame]);
  756. images[group][frame] = img;
  757. return true;
  758. }
  759. return false;
  760. }
  761. bool CAnimation::unloadFrame(size_t frame, size_t group)
  762. {
  763. auto image = getImage(frame, group, false);
  764. if(image)
  765. {
  766. images[group].erase(frame);
  767. if(images[group].empty())
  768. images.erase(group);
  769. return true;
  770. }
  771. return false;
  772. }
  773. void CAnimation::initFromJson(const JsonNode & config)
  774. {
  775. std::string basepath;
  776. basepath = config["basepath"].String();
  777. JsonNode base(JsonNode::JsonType::DATA_STRUCT);
  778. base["margins"] = config["margins"];
  779. base["width"] = config["width"];
  780. base["height"] = config["height"];
  781. for(const JsonNode & group : config["sequences"].Vector())
  782. {
  783. size_t groupID = group["group"].Integer();//TODO: string-to-value conversion("moving" -> MOVING)
  784. source[groupID].clear();
  785. for(const JsonNode & frame : group["frames"].Vector())
  786. {
  787. JsonNode toAdd(JsonNode::JsonType::DATA_STRUCT);
  788. JsonUtils::inherit(toAdd, base);
  789. toAdd["file"].String() = basepath + frame.String();
  790. source[groupID].push_back(toAdd);
  791. }
  792. }
  793. for(const JsonNode & node : config["images"].Vector())
  794. {
  795. size_t group = node["group"].Integer();
  796. size_t frame = node["frame"].Integer();
  797. if (source[group].size() <= frame)
  798. source[group].resize(frame+1);
  799. JsonNode toAdd(JsonNode::JsonType::DATA_STRUCT);
  800. JsonUtils::inherit(toAdd, base);
  801. toAdd["file"].String() = basepath + node["file"].String();
  802. source[group][frame] = toAdd;
  803. }
  804. }
  805. void CAnimation::exportBitmaps(const boost::filesystem::path& path) const
  806. {
  807. if(images.empty())
  808. {
  809. logGlobal->error("Nothing to export, animation is empty");
  810. return;
  811. }
  812. boost::filesystem::path actualPath = path / "SPRITES" / name;
  813. boost::filesystem::create_directories(actualPath);
  814. size_t counter = 0;
  815. for(const auto & groupPair : images)
  816. {
  817. size_t group = groupPair.first;
  818. for(const auto & imagePair : groupPair.second)
  819. {
  820. size_t frame = imagePair.first;
  821. const auto img = imagePair.second;
  822. boost::format fmt("%d_%d.bmp");
  823. fmt % group % frame;
  824. img->exportBitmap(actualPath / fmt.str());
  825. counter++;
  826. }
  827. }
  828. logGlobal->info("Exported %d frames to %s", counter, actualPath.string());
  829. }
  830. void CAnimation::init()
  831. {
  832. if(defFile)
  833. {
  834. const std::map<size_t, size_t> defEntries = defFile->getEntries();
  835. for (auto & defEntry : defEntries)
  836. source[defEntry.first].resize(defEntry.second);
  837. }
  838. ResourceID resID(std::string("SPRITES/") + name, EResType::TEXT);
  839. if (vstd::contains(graphics->imageLists, resID.getName()))
  840. initFromJson(graphics->imageLists[resID.getName()]);
  841. auto configList = CResourceHandler::get()->getResourcesWithName(resID);
  842. for(auto & loader : configList)
  843. {
  844. auto stream = loader->load(resID);
  845. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  846. stream->read(textData.get(), stream->getSize());
  847. const JsonNode config((char*)textData.get(), stream->getSize());
  848. initFromJson(config);
  849. }
  850. }
  851. void CAnimation::printError(size_t frame, size_t group, std::string type) const
  852. {
  853. logGlobal->error("%s error: Request for frame not present in CAnimation! File name: %s, Group: %d, Frame: %d", type, name, group, frame);
  854. }
  855. CAnimation::CAnimation(std::string Name):
  856. name(Name),
  857. preloaded(false),
  858. defFile()
  859. {
  860. size_t dotPos = name.find_last_of('.');
  861. if ( dotPos!=-1 )
  862. name.erase(dotPos);
  863. std::transform(name.begin(), name.end(), name.begin(), toupper);
  864. ResourceID resource(std::string("SPRITES/") + name, EResType::ANIMATION);
  865. if(CResourceHandler::get()->existsResource(resource))
  866. defFile = std::make_shared<CDefFile>(name);
  867. init();
  868. if(source.empty())
  869. logAnim->error("Animation %s failed to load", Name);
  870. }
  871. CAnimation::CAnimation():
  872. name(""),
  873. preloaded(false),
  874. defFile()
  875. {
  876. init();
  877. }
  878. CAnimation::~CAnimation() = default;
  879. void CAnimation::duplicateImage(const size_t sourceGroup, const size_t sourceFrame, const size_t targetGroup)
  880. {
  881. if(!source.count(sourceGroup))
  882. {
  883. logAnim->error("Group %d missing in %s", sourceGroup, name);
  884. return;
  885. }
  886. if(source[sourceGroup].size() <= sourceFrame)
  887. {
  888. logAnim->error("Frame [%d %d] missing in %s", sourceGroup, sourceFrame, name);
  889. return;
  890. }
  891. //todo: clone actual loaded Image object
  892. JsonNode clone(source[sourceGroup][sourceFrame]);
  893. if(clone.getType() == JsonNode::JsonType::DATA_NULL)
  894. {
  895. std::string temp = name+":"+boost::lexical_cast<std::string>(sourceGroup)+":"+boost::lexical_cast<std::string>(sourceFrame);
  896. clone["file"].String() = temp;
  897. }
  898. source[targetGroup].push_back(clone);
  899. size_t index = source[targetGroup].size() - 1;
  900. if(preloaded)
  901. load(index, targetGroup);
  902. }
  903. void CAnimation::shiftColor(const ColorFilter & shifter)
  904. {
  905. for(auto groupIter = images.begin(); groupIter != images.end(); groupIter++)
  906. {
  907. for(auto frameIter = groupIter->second.begin(); frameIter != groupIter->second.end(); frameIter++)
  908. {
  909. std::shared_ptr<IImage> image = frameIter->second;
  910. image->adjustPalette(shifter);
  911. }
  912. }
  913. }
  914. void CAnimation::setCustom(std::string filename, size_t frame, size_t group)
  915. {
  916. if (source[group].size() <= frame)
  917. source[group].resize(frame+1);
  918. source[group][frame]["file"].String() = filename;
  919. //FIXME: update image if already loaded
  920. }
  921. std::shared_ptr<IImage> CAnimation::getImage(size_t frame, size_t group, bool verbose) const
  922. {
  923. auto groupIter = images.find(group);
  924. if (groupIter != images.end())
  925. {
  926. auto imageIter = groupIter->second.find(frame);
  927. if (imageIter != groupIter->second.end())
  928. return imageIter->second;
  929. }
  930. if (verbose)
  931. printError(frame, group, "GetImage");
  932. return nullptr;
  933. }
  934. void CAnimation::load()
  935. {
  936. for (auto & elem : source)
  937. for (size_t image=0; image < elem.second.size(); image++)
  938. loadFrame(image, elem.first);
  939. }
  940. void CAnimation::unload()
  941. {
  942. for (auto & elem : source)
  943. for (size_t image=0; image < elem.second.size(); image++)
  944. unloadFrame(image, elem.first);
  945. }
  946. void CAnimation::preload()
  947. {
  948. if(!preloaded)
  949. {
  950. preloaded = true;
  951. load();
  952. }
  953. }
  954. void CAnimation::loadGroup(size_t group)
  955. {
  956. if (vstd::contains(source, group))
  957. for (size_t image=0; image < source[group].size(); image++)
  958. loadFrame(image, group);
  959. }
  960. void CAnimation::unloadGroup(size_t group)
  961. {
  962. if (vstd::contains(source, group))
  963. for (size_t image=0; image < source[group].size(); image++)
  964. unloadFrame(image, group);
  965. }
  966. void CAnimation::load(size_t frame, size_t group)
  967. {
  968. loadFrame(frame, group);
  969. }
  970. void CAnimation::unload(size_t frame, size_t group)
  971. {
  972. unloadFrame(frame, group);
  973. }
  974. size_t CAnimation::size(size_t group) const
  975. {
  976. auto iter = source.find(group);
  977. if (iter != source.end())
  978. return iter->second.size();
  979. return 0;
  980. }
  981. void CAnimation::horizontalFlip()
  982. {
  983. for(auto & group : images)
  984. for(auto & image : group.second)
  985. image.second->horizontalFlip();
  986. }
  987. void CAnimation::verticalFlip()
  988. {
  989. for(auto & group : images)
  990. for(auto & image : group.second)
  991. image.second->verticalFlip();
  992. }
  993. void CAnimation::playerColored(PlayerColor player)
  994. {
  995. for(auto & group : images)
  996. for(auto & image : group.second)
  997. image.second->playerColored(player);
  998. }
  999. void CAnimation::createFlippedGroup(const size_t sourceGroup, const size_t targetGroup)
  1000. {
  1001. for(size_t frame = 0; frame < size(sourceGroup); ++frame)
  1002. {
  1003. duplicateImage(sourceGroup, frame, targetGroup);
  1004. auto image = getImage(frame, targetGroup);
  1005. image->verticalFlip();
  1006. }
  1007. }
  1008. float CFadeAnimation::initialCounter() const
  1009. {
  1010. if (fadingMode == EMode::OUT)
  1011. return 1.0f;
  1012. return 0.0f;
  1013. }
  1014. void CFadeAnimation::update()
  1015. {
  1016. if (!fading)
  1017. return;
  1018. if (fadingMode == EMode::OUT)
  1019. fadingCounter -= delta;
  1020. else
  1021. fadingCounter += delta;
  1022. if (isFinished())
  1023. {
  1024. fading = false;
  1025. if (shouldFreeSurface)
  1026. {
  1027. SDL_FreeSurface(fadingSurface);
  1028. fadingSurface = nullptr;
  1029. }
  1030. }
  1031. }
  1032. bool CFadeAnimation::isFinished() const
  1033. {
  1034. if (fadingMode == EMode::OUT)
  1035. return fadingCounter <= 0.0f;
  1036. return fadingCounter >= 1.0f;
  1037. }
  1038. CFadeAnimation::CFadeAnimation()
  1039. : delta(0), fadingSurface(nullptr), fading(false), fadingCounter(0), shouldFreeSurface(false),
  1040. fadingMode(EMode::NONE)
  1041. {
  1042. }
  1043. CFadeAnimation::~CFadeAnimation()
  1044. {
  1045. if (fadingSurface && shouldFreeSurface)
  1046. SDL_FreeSurface(fadingSurface);
  1047. }
  1048. void CFadeAnimation::init(EMode mode, SDL_Surface * sourceSurface, bool freeSurfaceAtEnd, float animDelta)
  1049. {
  1050. if (fading)
  1051. {
  1052. // in that case, immediately finish the previous fade
  1053. // (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))
  1054. logGlobal->warn("Tried to init fading animation that is already running.");
  1055. if (fadingSurface && shouldFreeSurface)
  1056. SDL_FreeSurface(fadingSurface);
  1057. }
  1058. if (animDelta <= 0.0f)
  1059. {
  1060. logGlobal->warn("Fade anim: delta should be positive; %f given.", animDelta);
  1061. animDelta = DEFAULT_DELTA;
  1062. }
  1063. if (sourceSurface)
  1064. fadingSurface = sourceSurface;
  1065. delta = animDelta;
  1066. fadingMode = mode;
  1067. fadingCounter = initialCounter();
  1068. fading = true;
  1069. shouldFreeSurface = freeSurfaceAtEnd;
  1070. }
  1071. void CFadeAnimation::draw(SDL_Surface * targetSurface, const SDL_Rect * sourceRect, SDL_Rect * destRect)
  1072. {
  1073. if (!fading || !fadingSurface || fadingMode == EMode::NONE)
  1074. {
  1075. fading = false;
  1076. return;
  1077. }
  1078. CSDL_Ext::setAlpha(fadingSurface, (int)(fadingCounter * 255));
  1079. SDL_BlitSurface(fadingSurface, const_cast<SDL_Rect *>(sourceRect), targetSurface, destRect); //FIXME
  1080. CSDL_Ext::setAlpha(fadingSurface, 255);
  1081. }