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