CAnimation.cpp 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211
  1. /*
  2. * CAnimation.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CAnimation.h"
  12. #include <SDL_image.h>
  13. #include "../CBitmapHandler.h"
  14. #include "../Graphics.h"
  15. #include "../gui/SDL_Extensions.h"
  16. #include "../gui/SDL_Pixels.h"
  17. #include "../lib/filesystem/Filesystem.h"
  18. #include "../lib/filesystem/ISimpleResourceLoader.h"
  19. #include "../lib/JsonNode.h"
  20. #include "../lib/CRandomGenerator.h"
  21. class SDLImageLoader;
  22. typedef std::map <size_t, std::vector <JsonNode> > source_map;
  23. typedef std::map<size_t, IImage* > image_map;
  24. typedef std::map<size_t, image_map > group_map;
  25. /// Class for def loading
  26. /// After loading will store general info (palette and frame offsets) and pointer to file itself
  27. class CDefFile
  28. {
  29. private:
  30. struct SSpriteDef
  31. {
  32. ui32 size;
  33. ui32 format; /// format in which pixel data is stored
  34. ui32 fullWidth; /// full width and height of frame, including borders
  35. ui32 fullHeight;
  36. ui32 width; /// width and height of pixel data, borders excluded
  37. ui32 height;
  38. si32 leftMargin;
  39. si32 topMargin;
  40. } PACKED_STRUCT;
  41. //offset[group][frame] - offset of frame data in file
  42. std::map<size_t, std::vector <size_t> > offset;
  43. std::unique_ptr<ui8[]> data;
  44. std::unique_ptr<SDL_Color[]> palette;
  45. public:
  46. CDefFile(std::string Name);
  47. ~CDefFile();
  48. //load frame as SDL_Surface
  49. template<class ImageLoader>
  50. void loadFrame(size_t frame, size_t group, ImageLoader &loader) const;
  51. const std::map<size_t, size_t> getEntries() const;
  52. };
  53. /*
  54. * Wrapper around SDL_Surface
  55. */
  56. class SDLImage : public IImage
  57. {
  58. public:
  59. //Surface without empty borders
  60. SDL_Surface * surf;
  61. //size of left and top borders
  62. Point margins;
  63. //total size including borders
  64. Point fullSize;
  65. public:
  66. //Load image from def file
  67. SDLImage(CDefFile *data, size_t frame, size_t group=0);
  68. //Load from bitmap file
  69. SDLImage(std::string filename);
  70. SDLImage(const JsonNode & conf);
  71. //Create using existing surface, extraRef will increase refcount on SDL_Surface
  72. SDLImage(SDL_Surface * from, bool extraRef);
  73. ~SDLImage();
  74. void draw(SDL_Surface * where, int posX=0, int posY=0, Rect *src=nullptr, ui8 alpha=255) const override;
  75. void draw(SDL_Surface * where, SDL_Rect * dest, SDL_Rect * src, ui8 alpha=255) const override;
  76. std::shared_ptr<IImage> scaleFast(float scale) const override;
  77. void exportBitmap(const boost::filesystem::path & path) const override;
  78. void playerColored(PlayerColor player) override;
  79. void setFlagColor(PlayerColor player) override;
  80. int width() const override;
  81. int height() const override;
  82. void horizontalFlip() override;
  83. void verticalFlip() override;
  84. void shiftPalette(int from, int howMany) override;
  85. void setBorderPallete(const BorderPallete & borderPallete) override;
  86. friend class SDLImageLoader;
  87. };
  88. class SDLImageLoader
  89. {
  90. SDLImage * image;
  91. ui8 * lineStart;
  92. ui8 * position;
  93. public:
  94. //load size raw pixels from data
  95. inline void Load(size_t size, const ui8 * data);
  96. //set size pixels to color
  97. inline void Load(size_t size, ui8 color=0);
  98. inline void EndLine();
  99. //init image with these sizes and palette
  100. inline void init(Point SpriteSize, Point Margins, Point FullSize, SDL_Color *pal);
  101. SDLImageLoader(SDLImage * Img);
  102. ~SDLImageLoader();
  103. };
  104. // Extremely simple file cache. TODO: smarter, more general solution
  105. class CFileCache
  106. {
  107. static const int cacheSize = 50; //Max number of cached files
  108. struct FileData
  109. {
  110. ResourceID name;
  111. size_t size;
  112. std::unique_ptr<ui8[]> data;
  113. std::unique_ptr<ui8[]> getCopy()
  114. {
  115. auto ret = std::unique_ptr<ui8[]>(new ui8[size]);
  116. std::copy(data.get(), data.get() + size, ret.get());
  117. return ret;
  118. }
  119. FileData(ResourceID name_, size_t size_, std::unique_ptr<ui8[]> data_):
  120. name{std::move(name_)},
  121. size{size_},
  122. data{std::move(data_)}
  123. {}
  124. };
  125. std::deque<FileData> cache;
  126. public:
  127. std::unique_ptr<ui8[]> getCachedFile(ResourceID rid)
  128. {
  129. for(auto & file : cache)
  130. {
  131. if (file.name == rid)
  132. return file.getCopy();
  133. }
  134. // Still here? Cache miss
  135. if (cache.size() > cacheSize)
  136. cache.pop_front();
  137. auto data = CResourceHandler::get()->load(rid)->readAll();
  138. cache.emplace_back(std::move(rid), data.second, std::move(data.first));
  139. return cache.back().getCopy();
  140. }
  141. };
  142. enum class DefType : uint32_t
  143. {
  144. SPELL = 0x40,
  145. SPRITE = 0x41,
  146. CREATURE = 0x42,
  147. MAP = 0x43,
  148. MAP_HERO = 0x44,
  149. TERRAIN = 0x45,
  150. CURSOR = 0x46,
  151. INTERFACE = 0x47,
  152. SPRITE_FRAME = 0x48,
  153. BATTLE_HERO = 0x49
  154. };
  155. static CFileCache animationCache;
  156. /*************************************************************************
  157. * DefFile, class used for def loading *
  158. *************************************************************************/
  159. bool operator== (const SDL_Color & lhs, const SDL_Color & rhs)
  160. {
  161. return (lhs.a == rhs.a) && (lhs.b == rhs.b) &&(lhs.g == rhs.g) &&(lhs.r == rhs.r);
  162. }
  163. CDefFile::CDefFile(std::string Name):
  164. data(nullptr),
  165. palette(nullptr)
  166. {
  167. #if 0
  168. static SDL_Color H3_ORIG_PALETTE[8] =
  169. {
  170. { 0, 255, 255, SDL_ALPHA_OPAQUE},
  171. {255, 150, 255, SDL_ALPHA_OPAQUE},
  172. {255, 100, 255, SDL_ALPHA_OPAQUE},
  173. {255, 50, 255, SDL_ALPHA_OPAQUE},
  174. {255, 0, 255, SDL_ALPHA_OPAQUE},
  175. {255, 255, 0, SDL_ALPHA_OPAQUE},
  176. {180, 0, 255, SDL_ALPHA_OPAQUE},
  177. { 0, 255, 0, SDL_ALPHA_OPAQUE}
  178. };
  179. #endif // 0
  180. //First 8 colors in def palette used for transparency
  181. static SDL_Color H3Palette[8] =
  182. {
  183. { 0, 0, 0, 0},// 100% - transparency
  184. { 0, 0, 0, 32},// 75% - shadow border,
  185. { 0, 0, 0, 64},// TODO: find exact value
  186. { 0, 0, 0, 128},// TODO: for transparency
  187. { 0, 0, 0, 128},// 50% - shadow body
  188. { 0, 0, 0, 0},// 100% - selection highlight
  189. { 0, 0, 0, 128},// 50% - shadow body below selection
  190. { 0, 0, 0, 64} // 75% - shadow border below selection
  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 * 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(256);
  431. SDL_SetPaletteColors(p, pal, 0, 256);
  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. SDLImage::SDLImage(CDefFile * data, size_t frame, size_t group)
  470. : surf(nullptr),
  471. margins(0, 0),
  472. fullSize(0, 0)
  473. {
  474. SDLImageLoader loader(this);
  475. data->loadFrame(frame, group, loader);
  476. }
  477. SDLImage::SDLImage(SDL_Surface * from, bool extraRef)
  478. : surf(nullptr),
  479. margins(0, 0),
  480. fullSize(0, 0)
  481. {
  482. surf = from;
  483. if (extraRef)
  484. surf->refcount++;
  485. fullSize.x = surf->w;
  486. fullSize.y = surf->h;
  487. }
  488. SDLImage::SDLImage(const JsonNode & conf)
  489. : surf(nullptr),
  490. margins(0, 0),
  491. fullSize(0, 0)
  492. {
  493. std::string filename = conf["file"].String();
  494. surf = BitmapHandler::loadBitmap(filename);
  495. if(surf == nullptr)
  496. return;
  497. const JsonNode & jsonMargins = conf["margins"];
  498. margins.x = jsonMargins["left"].Integer();
  499. margins.y = jsonMargins["top"].Integer();
  500. fullSize.x = conf["width"].Integer();
  501. fullSize.y = conf["height"].Integer();
  502. if(fullSize.x == 0)
  503. {
  504. fullSize.x = margins.x + surf->w + jsonMargins["right"].Integer();
  505. }
  506. if(fullSize.y == 0)
  507. {
  508. fullSize.y = margins.y + surf->h + jsonMargins["bottom"].Integer();
  509. }
  510. }
  511. SDLImage::SDLImage(std::string filename)
  512. : surf(nullptr),
  513. margins(0, 0),
  514. fullSize(0, 0)
  515. {
  516. surf = BitmapHandler::loadBitmap(filename);
  517. if(surf == nullptr)
  518. {
  519. logGlobal->error("Error: failed to load image %s", filename);
  520. return;
  521. }
  522. else
  523. {
  524. fullSize.x = surf->w;
  525. fullSize.y = surf->h;
  526. }
  527. }
  528. void SDLImage::draw(SDL_Surface *where, int posX, int posY, Rect *src, ui8 alpha) const
  529. {
  530. if(!surf)
  531. return;
  532. Rect destRect(posX, posY, surf->w, surf->h);
  533. draw(where, &destRect, src);
  534. }
  535. void SDLImage::draw(SDL_Surface* where, SDL_Rect* dest, SDL_Rect* src, ui8 alpha) const
  536. {
  537. if (!surf)
  538. return;
  539. Rect sourceRect(0, 0, surf->w, surf->h);
  540. Point destShift(0, 0);
  541. if(src)
  542. {
  543. if(src->x < margins.x)
  544. destShift.x += margins.x - src->x;
  545. if(src->y < margins.y)
  546. destShift.y += margins.y - src->y;
  547. sourceRect = Rect(*src) & Rect(margins.x, margins.y, surf->w, surf->h);
  548. sourceRect -= margins;
  549. }
  550. else
  551. destShift = margins;
  552. Rect destRect(destShift.x, destShift.y, surf->w, surf->h);
  553. if(dest)
  554. {
  555. destRect.x += dest->x;
  556. destRect.y += dest->y;
  557. }
  558. if(surf->format->BitsPerPixel == 8)
  559. {
  560. CSDL_Ext::blit8bppAlphaTo24bpp(surf, &sourceRect, where, &destRect);
  561. }
  562. else
  563. {
  564. SDL_UpperBlit(surf, &sourceRect, where, &destRect);
  565. }
  566. }
  567. std::shared_ptr<IImage> SDLImage::scaleFast(float scale) const
  568. {
  569. auto scaled = CSDL_Ext::scaleSurfaceFast(surf, surf->w * scale, surf->h * scale);
  570. if (scaled->format && scaled->format->palette) // fix color keying, because SDL loses it at this point
  571. CSDL_Ext::setColorKey(scaled, scaled->format->palette->colors[0]);
  572. else if(scaled->format && scaled->format->Amask)
  573. SDL_SetSurfaceBlendMode(scaled, SDL_BLENDMODE_BLEND);//just in case
  574. else
  575. CSDL_Ext::setDefaultColorKey(scaled);//just in case
  576. SDLImage * ret = new SDLImage(scaled, false);
  577. ret->fullSize.x = (int) round((float)fullSize.x * scale);
  578. ret->fullSize.y = (int) round((float)fullSize.y * scale);
  579. ret->margins.x = (int) round((float)margins.x * scale);
  580. ret->margins.y = (int) round((float)margins.y * scale);
  581. return std::shared_ptr<IImage>(ret);
  582. }
  583. void SDLImage::exportBitmap(const boost::filesystem::path& path) const
  584. {
  585. SDL_SaveBMP(surf, path.string().c_str());
  586. }
  587. void SDLImage::playerColored(PlayerColor player)
  588. {
  589. graphics->blueToPlayersAdv(surf, player);
  590. }
  591. void SDLImage::setFlagColor(PlayerColor player)
  592. {
  593. if(player < PlayerColor::PLAYER_LIMIT || player==PlayerColor::NEUTRAL)
  594. CSDL_Ext::setPlayerColor(surf, player);
  595. }
  596. int SDLImage::width() const
  597. {
  598. return fullSize.x;
  599. }
  600. int SDLImage::height() const
  601. {
  602. return fullSize.y;
  603. }
  604. void SDLImage::horizontalFlip()
  605. {
  606. margins.y = fullSize.y - surf->h - margins.y;
  607. //todo: modify in-place
  608. SDL_Surface * flipped = CSDL_Ext::horizontalFlip(surf);
  609. SDL_FreeSurface(surf);
  610. surf = flipped;
  611. }
  612. void SDLImage::verticalFlip()
  613. {
  614. margins.x = fullSize.x - surf->w - margins.x;
  615. //todo: modify in-place
  616. SDL_Surface * flipped = CSDL_Ext::verticalFlip(surf);
  617. SDL_FreeSurface(surf);
  618. surf = flipped;
  619. }
  620. void SDLImage::shiftPalette(int from, int howMany)
  621. {
  622. //works with at most 16 colors, if needed more -> increase values
  623. assert(howMany < 16);
  624. if(surf->format->palette)
  625. {
  626. SDL_Color palette[16];
  627. for(int i=0; i<howMany; ++i)
  628. {
  629. palette[(i+1)%howMany] = surf->format->palette->colors[from + i];
  630. }
  631. SDL_SetColors(surf, palette, from, howMany);
  632. }
  633. }
  634. void SDLImage::setBorderPallete(const IImage::BorderPallete & borderPallete)
  635. {
  636. if(surf->format->palette)
  637. {
  638. SDL_SetColors(surf, const_cast<SDL_Color *>(borderPallete.data()), 5, 3);
  639. }
  640. }
  641. SDLImage::~SDLImage()
  642. {
  643. SDL_FreeSurface(surf);
  644. }
  645. std::shared_ptr<IImage> CAnimation::getFromExtraDef(std::string filename)
  646. {
  647. size_t pos = filename.find(':');
  648. if (pos == -1)
  649. return nullptr;
  650. CAnimation anim(filename.substr(0, pos));
  651. pos++;
  652. size_t frame = atoi(filename.c_str()+pos);
  653. size_t group = 0;
  654. pos = filename.find(':', pos);
  655. if (pos != -1)
  656. {
  657. pos++;
  658. group = frame;
  659. frame = atoi(filename.c_str()+pos);
  660. }
  661. anim.load(frame ,group);
  662. auto ret = anim.images[group][frame];
  663. anim.images.clear();
  664. return ret;
  665. }
  666. bool CAnimation::loadFrame(size_t frame, size_t group)
  667. {
  668. if(size(group) <= frame)
  669. {
  670. printError(frame, group, "LoadFrame");
  671. return false;
  672. }
  673. auto image = getImage(frame, group, false);
  674. if(image)
  675. {
  676. return true;
  677. }
  678. //try to get image from def
  679. if(source[group][frame].getType() == JsonNode::JsonType::DATA_NULL)
  680. {
  681. if(defFile)
  682. {
  683. auto frameList = defFile->getEntries();
  684. if(vstd::contains(frameList, group) && frameList.at(group) > frame) // frame is present
  685. {
  686. images[group][frame] = std::make_shared<SDLImage>(defFile.get(), frame, group);
  687. return true;
  688. }
  689. }
  690. // still here? image is missing
  691. printError(frame, group, "LoadFrame");
  692. images[group][frame] = std::make_shared<SDLImage>("DEFAULT");
  693. }
  694. else //load from separate file
  695. {
  696. auto img = getFromExtraDef(source[group][frame]["file"].String());
  697. if(!img)
  698. img = std::make_shared<SDLImage>(source[group][frame]);
  699. images[group][frame] = img;
  700. return true;
  701. }
  702. return false;
  703. }
  704. bool CAnimation::unloadFrame(size_t frame, size_t group)
  705. {
  706. auto image = getImage(frame, group, false);
  707. if(image)
  708. {
  709. images[group].erase(frame);
  710. if(images[group].empty())
  711. images.erase(group);
  712. return true;
  713. }
  714. return false;
  715. }
  716. void CAnimation::initFromJson(const JsonNode & config)
  717. {
  718. std::string basepath;
  719. basepath = config["basepath"].String();
  720. JsonNode base(JsonNode::JsonType::DATA_STRUCT);
  721. base["margins"] = config["margins"];
  722. base["width"] = config["width"];
  723. base["height"] = config["height"];
  724. for(const JsonNode & group : config["sequences"].Vector())
  725. {
  726. size_t groupID = group["group"].Integer();//TODO: string-to-value conversion("moving" -> MOVING)
  727. source[groupID].clear();
  728. for(const JsonNode & frame : group["frames"].Vector())
  729. {
  730. JsonNode toAdd(JsonNode::JsonType::DATA_STRUCT);
  731. JsonUtils::inherit(toAdd, base);
  732. toAdd["file"].String() = basepath + frame.String();
  733. source[groupID].push_back(toAdd);
  734. }
  735. }
  736. for(const JsonNode & node : config["images"].Vector())
  737. {
  738. size_t group = node["group"].Integer();
  739. size_t frame = node["frame"].Integer();
  740. if (source[group].size() <= frame)
  741. source[group].resize(frame+1);
  742. JsonNode toAdd(JsonNode::JsonType::DATA_STRUCT);
  743. JsonUtils::inherit(toAdd, base);
  744. toAdd["file"].String() = basepath + node["file"].String();
  745. source[group][frame] = toAdd;
  746. }
  747. }
  748. void CAnimation::exportBitmaps(const boost::filesystem::path& path) const
  749. {
  750. if(images.empty())
  751. {
  752. logGlobal->error("Nothing to export, animation is empty");
  753. return;
  754. }
  755. boost::filesystem::path actualPath = path / "SPRITES" / name;
  756. boost::filesystem::create_directories(actualPath);
  757. size_t counter = 0;
  758. for(const auto & groupPair : images)
  759. {
  760. size_t group = groupPair.first;
  761. for(const auto & imagePair : groupPair.second)
  762. {
  763. size_t frame = imagePair.first;
  764. const auto img = imagePair.second;
  765. boost::format fmt("%d_%d.bmp");
  766. fmt % group % frame;
  767. img->exportBitmap(actualPath / fmt.str());
  768. counter++;
  769. }
  770. }
  771. logGlobal->info("Exported %d frames to %s", counter, actualPath.string());
  772. }
  773. void CAnimation::init()
  774. {
  775. if(defFile)
  776. {
  777. const std::map<size_t, size_t> defEntries = defFile->getEntries();
  778. for (auto & defEntry : defEntries)
  779. source[defEntry.first].resize(defEntry.second);
  780. }
  781. ResourceID resID(std::string("SPRITES/") + name, EResType::TEXT);
  782. if (vstd::contains(graphics->imageLists, resID.getName()))
  783. initFromJson(graphics->imageLists[resID.getName()]);
  784. auto configList = CResourceHandler::get()->getResourcesWithName(resID);
  785. for(auto & loader : configList)
  786. {
  787. auto stream = loader->load(resID);
  788. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  789. stream->read(textData.get(), stream->getSize());
  790. const JsonNode config((char*)textData.get(), stream->getSize());
  791. initFromJson(config);
  792. }
  793. }
  794. void CAnimation::printError(size_t frame, size_t group, std::string type) const
  795. {
  796. logGlobal->error("%s error: Request for frame not present in CAnimation! File name: %s, Group: %d, Frame: %d", type, name, group, frame);
  797. }
  798. CAnimation::CAnimation(std::string Name):
  799. name(Name),
  800. preloaded(false),
  801. defFile()
  802. {
  803. size_t dotPos = name.find_last_of('.');
  804. if ( dotPos!=-1 )
  805. name.erase(dotPos);
  806. std::transform(name.begin(), name.end(), name.begin(), toupper);
  807. ResourceID resource(std::string("SPRITES/") + name, EResType::ANIMATION);
  808. if(CResourceHandler::get()->existsResource(resource))
  809. defFile = std::make_shared<CDefFile>(name);
  810. init();
  811. if(source.empty())
  812. logAnim->error("Animation %s failed to load", Name);
  813. }
  814. CAnimation::CAnimation():
  815. name(""),
  816. preloaded(false),
  817. defFile()
  818. {
  819. init();
  820. }
  821. CAnimation::~CAnimation() = default;
  822. void CAnimation::duplicateImage(const size_t sourceGroup, const size_t sourceFrame, const size_t targetGroup)
  823. {
  824. if(!source.count(sourceGroup))
  825. {
  826. logAnim->error("Group %d missing in %s", sourceGroup, name);
  827. return;
  828. }
  829. if(source[sourceGroup].size() <= sourceFrame)
  830. {
  831. logAnim->error("Frame [%d %d] missing in %s", sourceGroup, sourceFrame, name);
  832. return;
  833. }
  834. //todo: clone actual loaded Image object
  835. JsonNode clone(source[sourceGroup][sourceFrame]);
  836. if(clone.getType() == JsonNode::JsonType::DATA_NULL)
  837. {
  838. std::string temp = name+":"+boost::lexical_cast<std::string>(sourceGroup)+":"+boost::lexical_cast<std::string>(sourceFrame);
  839. clone["file"].String() = temp;
  840. }
  841. source[targetGroup].push_back(clone);
  842. size_t index = source[targetGroup].size() - 1;
  843. if(preloaded)
  844. load(index, targetGroup);
  845. }
  846. void CAnimation::setCustom(std::string filename, size_t frame, size_t group)
  847. {
  848. if (source[group].size() <= frame)
  849. source[group].resize(frame+1);
  850. source[group][frame]["file"].String() = filename;
  851. //FIXME: update image if already loaded
  852. }
  853. std::shared_ptr<IImage> CAnimation::getImage(size_t frame, size_t group, bool verbose) const
  854. {
  855. auto groupIter = images.find(group);
  856. if (groupIter != images.end())
  857. {
  858. auto imageIter = groupIter->second.find(frame);
  859. if (imageIter != groupIter->second.end())
  860. return imageIter->second;
  861. }
  862. if (verbose)
  863. printError(frame, group, "GetImage");
  864. return nullptr;
  865. }
  866. void CAnimation::load()
  867. {
  868. for (auto & elem : source)
  869. for (size_t image=0; image < elem.second.size(); image++)
  870. loadFrame(image, elem.first);
  871. }
  872. void CAnimation::unload()
  873. {
  874. for (auto & elem : source)
  875. for (size_t image=0; image < elem.second.size(); image++)
  876. unloadFrame(image, elem.first);
  877. }
  878. void CAnimation::preload()
  879. {
  880. if(!preloaded)
  881. {
  882. preloaded = true;
  883. load();
  884. }
  885. }
  886. void CAnimation::loadGroup(size_t group)
  887. {
  888. if (vstd::contains(source, group))
  889. for (size_t image=0; image < source[group].size(); image++)
  890. loadFrame(image, group);
  891. }
  892. void CAnimation::unloadGroup(size_t group)
  893. {
  894. if (vstd::contains(source, group))
  895. for (size_t image=0; image < source[group].size(); image++)
  896. unloadFrame(image, group);
  897. }
  898. void CAnimation::load(size_t frame, size_t group)
  899. {
  900. loadFrame(frame, group);
  901. }
  902. void CAnimation::unload(size_t frame, size_t group)
  903. {
  904. unloadFrame(frame, group);
  905. }
  906. size_t CAnimation::size(size_t group) const
  907. {
  908. auto iter = source.find(group);
  909. if (iter != source.end())
  910. return iter->second.size();
  911. return 0;
  912. }
  913. void CAnimation::horizontalFlip()
  914. {
  915. for(auto & group : images)
  916. for(auto & image : group.second)
  917. image.second->horizontalFlip();
  918. }
  919. void CAnimation::verticalFlip()
  920. {
  921. for(auto & group : images)
  922. for(auto & image : group.second)
  923. image.second->verticalFlip();
  924. }
  925. void CAnimation::playerColored(PlayerColor player)
  926. {
  927. for(auto & group : images)
  928. for(auto & image : group.second)
  929. image.second->playerColored(player);
  930. }
  931. void CAnimation::createFlippedGroup(const size_t sourceGroup, const size_t targetGroup)
  932. {
  933. for(size_t frame = 0; frame < size(sourceGroup); ++frame)
  934. {
  935. duplicateImage(sourceGroup, frame, targetGroup);
  936. auto image = getImage(frame, targetGroup);
  937. image->verticalFlip();
  938. }
  939. }
  940. float CFadeAnimation::initialCounter() const
  941. {
  942. if (fadingMode == EMode::OUT)
  943. return 1.0f;
  944. return 0.0f;
  945. }
  946. void CFadeAnimation::update()
  947. {
  948. if (!fading)
  949. return;
  950. if (fadingMode == EMode::OUT)
  951. fadingCounter -= delta;
  952. else
  953. fadingCounter += delta;
  954. if (isFinished())
  955. {
  956. fading = false;
  957. if (shouldFreeSurface)
  958. {
  959. SDL_FreeSurface(fadingSurface);
  960. fadingSurface = nullptr;
  961. }
  962. }
  963. }
  964. bool CFadeAnimation::isFinished() const
  965. {
  966. if (fadingMode == EMode::OUT)
  967. return fadingCounter <= 0.0f;
  968. return fadingCounter >= 1.0f;
  969. }
  970. CFadeAnimation::CFadeAnimation()
  971. : delta(0), fadingSurface(nullptr), fading(false), fadingCounter(0), shouldFreeSurface(false),
  972. fadingMode(EMode::NONE)
  973. {
  974. }
  975. CFadeAnimation::~CFadeAnimation()
  976. {
  977. if (fadingSurface && shouldFreeSurface)
  978. SDL_FreeSurface(fadingSurface);
  979. }
  980. void CFadeAnimation::init(EMode mode, SDL_Surface * sourceSurface, bool freeSurfaceAtEnd, float animDelta)
  981. {
  982. if (fading)
  983. {
  984. // in that case, immediately finish the previous fade
  985. // (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))
  986. logGlobal->warn("Tried to init fading animation that is already running.");
  987. if (fadingSurface && shouldFreeSurface)
  988. SDL_FreeSurface(fadingSurface);
  989. }
  990. if (animDelta <= 0.0f)
  991. {
  992. logGlobal->warn("Fade anim: delta should be positive; %f given.", animDelta);
  993. animDelta = DEFAULT_DELTA;
  994. }
  995. if (sourceSurface)
  996. fadingSurface = sourceSurface;
  997. delta = animDelta;
  998. fadingMode = mode;
  999. fadingCounter = initialCounter();
  1000. fading = true;
  1001. shouldFreeSurface = freeSurfaceAtEnd;
  1002. }
  1003. void CFadeAnimation::draw(SDL_Surface * targetSurface, const SDL_Rect * sourceRect, SDL_Rect * destRect)
  1004. {
  1005. if (!fading || !fadingSurface || fadingMode == EMode::NONE)
  1006. {
  1007. fading = false;
  1008. return;
  1009. }
  1010. CSDL_Ext::setAlpha(fadingSurface, fadingCounter * 255);
  1011. SDL_BlitSurface(fadingSurface, const_cast<SDL_Rect *>(sourceRect), targetSurface, destRect); //FIXME
  1012. CSDL_Ext::setAlpha(fadingSurface, 255);
  1013. }