CAnimation.cpp 32 KB

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