CAnimation.cpp 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282
  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 Rect * dest, const 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 Rect * dest, const 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).intersect(Rect(margins.x, margins.y, surf->w, surf->h));
  566. sourceRect -= margins;
  567. }
  568. else
  569. destShift = margins;
  570. if(dest)
  571. destShift += dest->topLeft();
  572. if(surf->format->BitsPerPixel == 8)
  573. {
  574. CSDL_Ext::blit8bppAlphaTo24bpp(surf, sourceRect, where, destShift);
  575. }
  576. else
  577. {
  578. CSDL_Ext::blitSurface(surf, sourceRect, where, destShift);
  579. }
  580. }
  581. std::shared_ptr<IImage> SDLImage::scaleFast(float scale) const
  582. {
  583. auto scaled = CSDL_Ext::scaleSurfaceFast(surf, (int)(surf->w * scale), (int)(surf->h * scale));
  584. if (scaled->format && scaled->format->palette) // fix color keying, because SDL loses it at this point
  585. CSDL_Ext::setColorKey(scaled, scaled->format->palette->colors[0]);
  586. else if(scaled->format && scaled->format->Amask)
  587. SDL_SetSurfaceBlendMode(scaled, SDL_BLENDMODE_BLEND);//just in case
  588. else
  589. CSDL_Ext::setDefaultColorKey(scaled);//just in case
  590. SDLImage * ret = new SDLImage(scaled, false);
  591. ret->fullSize.x = (int) round((float)fullSize.x * scale);
  592. ret->fullSize.y = (int) round((float)fullSize.y * scale);
  593. ret->margins.x = (int) round((float)margins.x * scale);
  594. ret->margins.y = (int) round((float)margins.y * scale);
  595. return std::shared_ptr<IImage>(ret);
  596. }
  597. void SDLImage::exportBitmap(const boost::filesystem::path& path) const
  598. {
  599. SDL_SaveBMP(surf, path.string().c_str());
  600. }
  601. void SDLImage::playerColored(PlayerColor player)
  602. {
  603. graphics->blueToPlayersAdv(surf, player);
  604. }
  605. void SDLImage::setFlagColor(PlayerColor player)
  606. {
  607. if(player < PlayerColor::PLAYER_LIMIT || player==PlayerColor::NEUTRAL)
  608. CSDL_Ext::setPlayerColor(surf, player);
  609. }
  610. bool SDLImage::isTransparent(const Point & coords) const
  611. {
  612. return CSDL_Ext::isTransparent(surf, coords.x, coords.y);
  613. }
  614. Point SDLImage::dimensions() const
  615. {
  616. return fullSize;
  617. }
  618. void SDLImage::horizontalFlip()
  619. {
  620. margins.y = fullSize.y - surf->h - margins.y;
  621. //todo: modify in-place
  622. SDL_Surface * flipped = CSDL_Ext::horizontalFlip(surf);
  623. SDL_FreeSurface(surf);
  624. surf = flipped;
  625. }
  626. void SDLImage::verticalFlip()
  627. {
  628. margins.x = fullSize.x - surf->w - margins.x;
  629. //todo: modify in-place
  630. SDL_Surface * flipped = CSDL_Ext::verticalFlip(surf);
  631. SDL_FreeSurface(surf);
  632. surf = flipped;
  633. }
  634. // Keep the original palette, in order to do color switching operation
  635. void SDLImage::savePalette()
  636. {
  637. // For some images that don't have palette, skip this
  638. if(surf->format->palette == nullptr)
  639. return;
  640. if(originalPalette == nullptr)
  641. originalPalette = SDL_AllocPalette(DEFAULT_PALETTE_COLORS);
  642. SDL_SetPaletteColors(originalPalette, surf->format->palette->colors, 0, DEFAULT_PALETTE_COLORS);
  643. }
  644. void SDLImage::shiftPalette(int from, int howMany)
  645. {
  646. //works with at most 16 colors, if needed more -> increase values
  647. assert(howMany < 16);
  648. if(surf->format->palette)
  649. {
  650. SDL_Color palette[16];
  651. for(int i=0; i<howMany; ++i)
  652. {
  653. palette[(i+1)%howMany] = surf->format->palette->colors[from + i];
  654. }
  655. CSDL_Ext::setColors(surf, palette, from, howMany);
  656. }
  657. }
  658. void SDLImage::adjustPalette(const ColorFilter & shifter)
  659. {
  660. if(originalPalette == nullptr)
  661. return;
  662. SDL_Palette* palette = surf->format->palette;
  663. // Note: here we skip the first 8 colors in the palette that predefined in H3Palette
  664. for(int i = 8; i < palette->ncolors; i++)
  665. {
  666. palette->colors[i] = shifter.shiftColor(originalPalette->colors[i]);
  667. }
  668. }
  669. void SDLImage::resetPalette()
  670. {
  671. if(originalPalette == nullptr)
  672. return;
  673. // Always keept the original palette not changed, copy a new palette to assign to surface
  674. SDL_SetPaletteColors(surf->format->palette, originalPalette->colors, 0, originalPalette->ncolors);
  675. }
  676. void SDLImage::resetPalette( int colorID )
  677. {
  678. if(originalPalette == nullptr)
  679. return;
  680. // Always keept the original palette not changed, copy a new palette to assign to surface
  681. SDL_SetPaletteColors(surf->format->palette, originalPalette->colors + colorID, colorID, 1);
  682. }
  683. void SDLImage::setSpecialPallete(const IImage::SpecialPalette & SpecialPalette)
  684. {
  685. if(surf->format->palette)
  686. {
  687. CSDL_Ext::setColors(surf, const_cast<SDL_Color *>(SpecialPalette.data()), 1, 7);
  688. }
  689. }
  690. SDLImage::~SDLImage()
  691. {
  692. SDL_FreeSurface(surf);
  693. if(originalPalette != nullptr)
  694. {
  695. SDL_FreePalette(originalPalette);
  696. originalPalette = nullptr;
  697. }
  698. }
  699. std::shared_ptr<IImage> CAnimation::getFromExtraDef(std::string filename)
  700. {
  701. size_t pos = filename.find(':');
  702. if (pos == -1)
  703. return nullptr;
  704. CAnimation anim(filename.substr(0, pos));
  705. pos++;
  706. size_t frame = atoi(filename.c_str()+pos);
  707. size_t group = 0;
  708. pos = filename.find(':', pos);
  709. if (pos != -1)
  710. {
  711. pos++;
  712. group = frame;
  713. frame = atoi(filename.c_str()+pos);
  714. }
  715. anim.load(frame ,group);
  716. auto ret = anim.images[group][frame];
  717. anim.images.clear();
  718. return ret;
  719. }
  720. bool CAnimation::loadFrame(size_t frame, size_t group)
  721. {
  722. if(size(group) <= frame)
  723. {
  724. printError(frame, group, "LoadFrame");
  725. return false;
  726. }
  727. auto image = getImage(frame, group, false);
  728. if(image)
  729. {
  730. return true;
  731. }
  732. //try to get image from def
  733. if(source[group][frame].getType() == JsonNode::JsonType::DATA_NULL)
  734. {
  735. if(defFile)
  736. {
  737. auto frameList = defFile->getEntries();
  738. if(vstd::contains(frameList, group) && frameList.at(group) > frame) // frame is present
  739. {
  740. images[group][frame] = std::make_shared<SDLImage>(defFile.get(), frame, group);
  741. return true;
  742. }
  743. }
  744. // still here? image is missing
  745. printError(frame, group, "LoadFrame");
  746. images[group][frame] = std::make_shared<SDLImage>("DEFAULT");
  747. }
  748. else //load from separate file
  749. {
  750. auto img = getFromExtraDef(source[group][frame]["file"].String());
  751. if(!img)
  752. img = std::make_shared<SDLImage>(source[group][frame]);
  753. images[group][frame] = img;
  754. return true;
  755. }
  756. return false;
  757. }
  758. bool CAnimation::unloadFrame(size_t frame, size_t group)
  759. {
  760. auto image = getImage(frame, group, false);
  761. if(image)
  762. {
  763. images[group].erase(frame);
  764. if(images[group].empty())
  765. images.erase(group);
  766. return true;
  767. }
  768. return false;
  769. }
  770. void CAnimation::initFromJson(const JsonNode & config)
  771. {
  772. std::string basepath;
  773. basepath = config["basepath"].String();
  774. JsonNode base(JsonNode::JsonType::DATA_STRUCT);
  775. base["margins"] = config["margins"];
  776. base["width"] = config["width"];
  777. base["height"] = config["height"];
  778. for(const JsonNode & group : config["sequences"].Vector())
  779. {
  780. size_t groupID = group["group"].Integer();//TODO: string-to-value conversion("moving" -> MOVING)
  781. source[groupID].clear();
  782. for(const JsonNode & frame : group["frames"].Vector())
  783. {
  784. JsonNode toAdd(JsonNode::JsonType::DATA_STRUCT);
  785. JsonUtils::inherit(toAdd, base);
  786. toAdd["file"].String() = basepath + frame.String();
  787. source[groupID].push_back(toAdd);
  788. }
  789. }
  790. for(const JsonNode & node : config["images"].Vector())
  791. {
  792. size_t group = node["group"].Integer();
  793. size_t frame = node["frame"].Integer();
  794. if (source[group].size() <= frame)
  795. source[group].resize(frame+1);
  796. JsonNode toAdd(JsonNode::JsonType::DATA_STRUCT);
  797. JsonUtils::inherit(toAdd, base);
  798. toAdd["file"].String() = basepath + node["file"].String();
  799. source[group][frame] = toAdd;
  800. }
  801. }
  802. void CAnimation::exportBitmaps(const boost::filesystem::path& path) const
  803. {
  804. if(images.empty())
  805. {
  806. logGlobal->error("Nothing to export, animation is empty");
  807. return;
  808. }
  809. boost::filesystem::path actualPath = path / "SPRITES" / name;
  810. boost::filesystem::create_directories(actualPath);
  811. size_t counter = 0;
  812. for(const auto & groupPair : images)
  813. {
  814. size_t group = groupPair.first;
  815. for(const auto & imagePair : groupPair.second)
  816. {
  817. size_t frame = imagePair.first;
  818. const auto img = imagePair.second;
  819. boost::format fmt("%d_%d.bmp");
  820. fmt % group % frame;
  821. img->exportBitmap(actualPath / fmt.str());
  822. counter++;
  823. }
  824. }
  825. logGlobal->info("Exported %d frames to %s", counter, actualPath.string());
  826. }
  827. void CAnimation::init()
  828. {
  829. if(defFile)
  830. {
  831. const std::map<size_t, size_t> defEntries = defFile->getEntries();
  832. for (auto & defEntry : defEntries)
  833. source[defEntry.first].resize(defEntry.second);
  834. }
  835. ResourceID resID(std::string("SPRITES/") + name, EResType::TEXT);
  836. if (vstd::contains(graphics->imageLists, resID.getName()))
  837. initFromJson(graphics->imageLists[resID.getName()]);
  838. auto configList = CResourceHandler::get()->getResourcesWithName(resID);
  839. for(auto & loader : configList)
  840. {
  841. auto stream = loader->load(resID);
  842. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  843. stream->read(textData.get(), stream->getSize());
  844. const JsonNode config((char*)textData.get(), stream->getSize());
  845. initFromJson(config);
  846. }
  847. }
  848. void CAnimation::printError(size_t frame, size_t group, std::string type) const
  849. {
  850. logGlobal->error("%s error: Request for frame not present in CAnimation! File name: %s, Group: %d, Frame: %d", type, name, group, frame);
  851. }
  852. CAnimation::CAnimation(std::string Name):
  853. name(Name),
  854. preloaded(false),
  855. defFile()
  856. {
  857. size_t dotPos = name.find_last_of('.');
  858. if ( dotPos!=-1 )
  859. name.erase(dotPos);
  860. std::transform(name.begin(), name.end(), name.begin(), toupper);
  861. ResourceID resource(std::string("SPRITES/") + name, EResType::ANIMATION);
  862. if(CResourceHandler::get()->existsResource(resource))
  863. defFile = std::make_shared<CDefFile>(name);
  864. init();
  865. if(source.empty())
  866. logAnim->error("Animation %s failed to load", Name);
  867. }
  868. CAnimation::CAnimation():
  869. name(""),
  870. preloaded(false),
  871. defFile()
  872. {
  873. init();
  874. }
  875. CAnimation::~CAnimation() = default;
  876. void CAnimation::duplicateImage(const size_t sourceGroup, const size_t sourceFrame, const size_t targetGroup)
  877. {
  878. if(!source.count(sourceGroup))
  879. {
  880. logAnim->error("Group %d missing in %s", sourceGroup, name);
  881. return;
  882. }
  883. if(source[sourceGroup].size() <= sourceFrame)
  884. {
  885. logAnim->error("Frame [%d %d] missing in %s", sourceGroup, sourceFrame, name);
  886. return;
  887. }
  888. //todo: clone actual loaded Image object
  889. JsonNode clone(source[sourceGroup][sourceFrame]);
  890. if(clone.getType() == JsonNode::JsonType::DATA_NULL)
  891. {
  892. std::string temp = name+":"+boost::lexical_cast<std::string>(sourceGroup)+":"+boost::lexical_cast<std::string>(sourceFrame);
  893. clone["file"].String() = temp;
  894. }
  895. source[targetGroup].push_back(clone);
  896. size_t index = source[targetGroup].size() - 1;
  897. if(preloaded)
  898. load(index, targetGroup);
  899. }
  900. void CAnimation::setCustom(std::string filename, size_t frame, size_t group)
  901. {
  902. if (source[group].size() <= frame)
  903. source[group].resize(frame+1);
  904. source[group][frame]["file"].String() = filename;
  905. //FIXME: update image if already loaded
  906. }
  907. std::shared_ptr<IImage> CAnimation::getImage(size_t frame, size_t group, bool verbose) const
  908. {
  909. auto groupIter = images.find(group);
  910. if (groupIter != images.end())
  911. {
  912. auto imageIter = groupIter->second.find(frame);
  913. if (imageIter != groupIter->second.end())
  914. return imageIter->second;
  915. }
  916. if (verbose)
  917. printError(frame, group, "GetImage");
  918. return nullptr;
  919. }
  920. void CAnimation::load()
  921. {
  922. for (auto & elem : source)
  923. for (size_t image=0; image < elem.second.size(); image++)
  924. loadFrame(image, elem.first);
  925. }
  926. void CAnimation::unload()
  927. {
  928. for (auto & elem : source)
  929. for (size_t image=0; image < elem.second.size(); image++)
  930. unloadFrame(image, elem.first);
  931. }
  932. void CAnimation::preload()
  933. {
  934. if(!preloaded)
  935. {
  936. preloaded = true;
  937. load();
  938. }
  939. }
  940. void CAnimation::loadGroup(size_t group)
  941. {
  942. if (vstd::contains(source, group))
  943. for (size_t image=0; image < source[group].size(); image++)
  944. loadFrame(image, group);
  945. }
  946. void CAnimation::unloadGroup(size_t group)
  947. {
  948. if (vstd::contains(source, group))
  949. for (size_t image=0; image < source[group].size(); image++)
  950. unloadFrame(image, group);
  951. }
  952. void CAnimation::load(size_t frame, size_t group)
  953. {
  954. loadFrame(frame, group);
  955. }
  956. void CAnimation::unload(size_t frame, size_t group)
  957. {
  958. unloadFrame(frame, group);
  959. }
  960. size_t CAnimation::size(size_t group) const
  961. {
  962. auto iter = source.find(group);
  963. if (iter != source.end())
  964. return iter->second.size();
  965. return 0;
  966. }
  967. void CAnimation::horizontalFlip()
  968. {
  969. for(auto & group : images)
  970. for(auto & image : group.second)
  971. image.second->horizontalFlip();
  972. }
  973. void CAnimation::verticalFlip()
  974. {
  975. for(auto & group : images)
  976. for(auto & image : group.second)
  977. image.second->verticalFlip();
  978. }
  979. void CAnimation::playerColored(PlayerColor player)
  980. {
  981. for(auto & group : images)
  982. for(auto & image : group.second)
  983. image.second->playerColored(player);
  984. }
  985. void CAnimation::createFlippedGroup(const size_t sourceGroup, const size_t targetGroup)
  986. {
  987. for(size_t frame = 0; frame < size(sourceGroup); ++frame)
  988. {
  989. duplicateImage(sourceGroup, frame, targetGroup);
  990. auto image = getImage(frame, targetGroup);
  991. image->verticalFlip();
  992. }
  993. }
  994. float CFadeAnimation::initialCounter() const
  995. {
  996. if (fadingMode == EMode::OUT)
  997. return 1.0f;
  998. return 0.0f;
  999. }
  1000. void CFadeAnimation::update()
  1001. {
  1002. if (!fading)
  1003. return;
  1004. if (fadingMode == EMode::OUT)
  1005. fadingCounter -= delta;
  1006. else
  1007. fadingCounter += delta;
  1008. if (isFinished())
  1009. {
  1010. fading = false;
  1011. if (shouldFreeSurface)
  1012. {
  1013. SDL_FreeSurface(fadingSurface);
  1014. fadingSurface = nullptr;
  1015. }
  1016. }
  1017. }
  1018. bool CFadeAnimation::isFinished() const
  1019. {
  1020. if (fadingMode == EMode::OUT)
  1021. return fadingCounter <= 0.0f;
  1022. return fadingCounter >= 1.0f;
  1023. }
  1024. CFadeAnimation::CFadeAnimation()
  1025. : delta(0), fadingSurface(nullptr), fading(false), fadingCounter(0), shouldFreeSurface(false),
  1026. fadingMode(EMode::NONE)
  1027. {
  1028. }
  1029. CFadeAnimation::~CFadeAnimation()
  1030. {
  1031. if (fadingSurface && shouldFreeSurface)
  1032. SDL_FreeSurface(fadingSurface);
  1033. }
  1034. void CFadeAnimation::init(EMode mode, SDL_Surface * sourceSurface, bool freeSurfaceAtEnd, float animDelta)
  1035. {
  1036. if (fading)
  1037. {
  1038. // in that case, immediately finish the previous fade
  1039. // (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))
  1040. logGlobal->warn("Tried to init fading animation that is already running.");
  1041. if (fadingSurface && shouldFreeSurface)
  1042. SDL_FreeSurface(fadingSurface);
  1043. }
  1044. if (animDelta <= 0.0f)
  1045. {
  1046. logGlobal->warn("Fade anim: delta should be positive; %f given.", animDelta);
  1047. animDelta = DEFAULT_DELTA;
  1048. }
  1049. if (sourceSurface)
  1050. fadingSurface = sourceSurface;
  1051. delta = animDelta;
  1052. fadingMode = mode;
  1053. fadingCounter = initialCounter();
  1054. fading = true;
  1055. shouldFreeSurface = freeSurfaceAtEnd;
  1056. }
  1057. void CFadeAnimation::draw(SDL_Surface * targetSurface, const Point &targetPoint)
  1058. {
  1059. if (!fading || !fadingSurface || fadingMode == EMode::NONE)
  1060. {
  1061. fading = false;
  1062. return;
  1063. }
  1064. CSDL_Ext::setAlpha(fadingSurface, (int)(fadingCounter * 255));
  1065. CSDL_Ext::blitSurface(fadingSurface, targetSurface, targetPoint); //FIXME
  1066. CSDL_Ext::setAlpha(fadingSurface, 255);
  1067. }