CAnimation.cpp 31 KB

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