CAnimation.cpp 32 KB

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