CAnimation.cpp 32 KB

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