CAnimation.cpp 31 KB

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