Animation.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  1. /*
  2. * Animation.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. //code is copied from vcmiclient/CAnimation.cpp with minimal changes
  11. #include "StdInc.h"
  12. #include "Animation.h"
  13. #include "BitmapHandler.h"
  14. #include "graphics.h"
  15. #include "../lib/vcmi_endian.h"
  16. #include "../lib/filesystem/Filesystem.h"
  17. #include "../lib/filesystem/ISimpleResourceLoader.h"
  18. #include "../lib/JsonNode.h"
  19. #include "../lib/CRandomGenerator.h"
  20. #include "../lib/VCMIDirs.h"
  21. typedef std::map<size_t, std::vector<JsonNode>> source_map;
  22. /// Class for def loading
  23. /// After loading will store general info (palette and frame offsets) and pointer to file itself
  24. class DefFile
  25. {
  26. private:
  27. struct SSpriteDef
  28. {
  29. ui32 size;
  30. ui32 format; /// format in which pixel data is stored
  31. ui32 fullWidth; /// full width and height of frame, including borders
  32. ui32 fullHeight;
  33. ui32 width; /// width and height of pixel data, borders excluded
  34. ui32 height;
  35. si32 leftMargin;
  36. si32 topMargin;
  37. };
  38. //offset[group][frame] - offset of frame data in file
  39. std::map<size_t, std::vector <size_t> > offset;
  40. std::unique_ptr<ui8[]> data;
  41. std::unique_ptr<QVector<QRgb>> palette;
  42. public:
  43. DefFile(std::string Name);
  44. ~DefFile();
  45. std::shared_ptr<QImage> loadFrame(size_t frame, size_t group) const;
  46. const std::map<size_t, size_t> getEntries() const;
  47. };
  48. class ImageLoader
  49. {
  50. QImage * image;
  51. ui8 * lineStart;
  52. ui8 * position;
  53. QPoint spriteSize, margins, fullSize;
  54. public:
  55. //load size raw pixels from data
  56. inline void Load(size_t size, const ui8 * data);
  57. //set size pixels to color
  58. inline void Load(size_t size, ui8 color=0);
  59. inline void EndLine();
  60. //init image with these sizes and palette
  61. inline void init(QPoint SpriteSize, QPoint Margins, QPoint FullSize);
  62. ImageLoader(QImage * Img);
  63. ~ImageLoader();
  64. };
  65. // Extremely simple file cache. TODO: smarter, more general solution
  66. class FileCache
  67. {
  68. static const int cacheSize = 50; //Max number of cached files
  69. struct FileData
  70. {
  71. ResourcePath name;
  72. size_t size;
  73. std::unique_ptr<ui8[]> data;
  74. std::unique_ptr<ui8[]> getCopy()
  75. {
  76. auto ret = std::unique_ptr<ui8[]>(new ui8[size]);
  77. std::copy(data.get(), data.get() + size, ret.get());
  78. return ret;
  79. }
  80. FileData(ResourcePath name_, size_t size_, std::unique_ptr<ui8[]> data_):
  81. name{std::move(name_)},
  82. size{size_},
  83. data{std::move(data_)}
  84. {}
  85. };
  86. std::deque<FileData> cache;
  87. public:
  88. std::unique_ptr<ui8[]> getCachedFile(ResourcePath rid)
  89. {
  90. for(auto & file : cache)
  91. {
  92. if(file.name == rid)
  93. return file.getCopy();
  94. }
  95. // Still here? Cache miss
  96. if(cache.size() > cacheSize)
  97. cache.pop_front();
  98. auto data = CResourceHandler::get()->load(rid)->readAll();
  99. cache.emplace_back(std::move(rid), data.second, std::move(data.first));
  100. return cache.back().getCopy();
  101. }
  102. };
  103. enum class DefType : uint32_t
  104. {
  105. SPELL = 0x40,
  106. SPRITE = 0x41,
  107. CREATURE = 0x42,
  108. MAP = 0x43,
  109. MAP_HERO = 0x44,
  110. TERRAIN = 0x45,
  111. CURSOR = 0x46,
  112. INTERFACE = 0x47,
  113. SPRITE_FRAME = 0x48,
  114. BATTLE_HERO = 0x49
  115. };
  116. static FileCache animationCache;
  117. /*************************************************************************
  118. * DefFile, class used for def loading *
  119. *************************************************************************/
  120. DefFile::DefFile(std::string Name):
  121. data(nullptr)
  122. {
  123. #if 0
  124. static QRgba H3_ORIG_PALETTE[8] =
  125. {
  126. { 0, 255, 255, SDL_ALPHA_OPAQUE},
  127. {255, 150, 255, SDL_ALPHA_OPAQUE},
  128. {255, 100, 255, SDL_ALPHA_OPAQUE},
  129. {255, 50, 255, SDL_ALPHA_OPAQUE},
  130. {255, 0, 255, SDL_ALPHA_OPAQUE},
  131. {255, 255, 0, SDL_ALPHA_OPAQUE},
  132. {180, 0, 255, SDL_ALPHA_OPAQUE},
  133. { 0, 255, 0, SDL_ALPHA_OPAQUE}
  134. };
  135. #endif // 0
  136. //First 8 colors in def palette used for transparency
  137. static QRgb H3Palette[8] =
  138. {
  139. qRgba(0, 0, 0, 0), // 100% - transparency
  140. qRgba(0, 0, 0, 32), // 75% - shadow border,
  141. qRgba(0, 0, 0, 64), // TODO: find exact value
  142. qRgba(0, 0, 0, 128), // TODO: for transparency
  143. qRgba(0, 0, 0, 128), // 50% - shadow body
  144. qRgba(0, 0, 0, 0), // 100% - selection highlight
  145. qRgba(0, 0, 0, 128), // 50% - shadow body below selection
  146. qRgba(0, 0, 0, 64) // 75% - shadow border below selection
  147. };
  148. data = animationCache.getCachedFile(AnimationPath::builtin("SPRITES/" + Name));
  149. palette = std::make_unique<QVector<QRgb>>(256);
  150. int it = 0;
  151. ui32 type = read_le_u32(data.get() + it);
  152. it += 4;
  153. //int width = read_le_u32(data + it); it+=4;//not used
  154. //int height = read_le_u32(data + it); it+=4;
  155. it += 8;
  156. ui32 totalBlocks = read_le_u32(data.get() + it);
  157. it += 4;
  158. for (ui32 i= 0; i<256; i++)
  159. {
  160. ui8 c[3];
  161. c[0] = data[it++];
  162. c[1] = data[it++];
  163. c[2] = data[it++];
  164. (*palette)[i] = qRgba(c[0], c[1], c[2], 255);
  165. }
  166. switch(static_cast<DefType>(type))
  167. {
  168. case DefType::SPELL:
  169. (*palette)[0] = H3Palette[0];
  170. break;
  171. case DefType::SPRITE:
  172. case DefType::SPRITE_FRAME:
  173. for(ui32 i= 0; i<8; i++)
  174. (*palette)[i] = H3Palette[i];
  175. break;
  176. case DefType::CREATURE:
  177. (*palette)[0] = H3Palette[0];
  178. (*palette)[1] = H3Palette[1];
  179. (*palette)[4] = H3Palette[4];
  180. (*palette)[5] = H3Palette[5];
  181. (*palette)[6] = H3Palette[6];
  182. (*palette)[7] = H3Palette[7];
  183. break;
  184. case DefType::MAP:
  185. case DefType::MAP_HERO:
  186. (*palette)[0] = H3Palette[0];
  187. (*palette)[1] = H3Palette[1];
  188. (*palette)[4] = H3Palette[4];
  189. //5 = owner flag, handled separately
  190. break;
  191. case DefType::TERRAIN:
  192. (*palette)[0] = H3Palette[0];
  193. (*palette)[1] = H3Palette[1];
  194. (*palette)[2] = H3Palette[2];
  195. (*palette)[3] = H3Palette[3];
  196. (*palette)[4] = H3Palette[4];
  197. break;
  198. case DefType::CURSOR:
  199. (*palette)[0] = H3Palette[0];
  200. break;
  201. case DefType::INTERFACE:
  202. (*palette)[0] = H3Palette[0];
  203. (*palette)[1] = H3Palette[1];
  204. (*palette)[4] = H3Palette[4];
  205. //player colors handled separately
  206. //TODO: disallow colorizing other def types
  207. break;
  208. case DefType::BATTLE_HERO:
  209. (*palette)[0] = H3Palette[0];
  210. (*palette)[1] = H3Palette[1];
  211. (*palette)[4] = H3Palette[4];
  212. break;
  213. default:
  214. logAnim->error("Unknown def type %d in %s", type, Name);
  215. break;
  216. }
  217. for (ui32 i=0; i<totalBlocks; i++)
  218. {
  219. size_t blockID = read_le_u32(data.get() + it);
  220. it+=4;
  221. size_t totalEntries = read_le_u32(data.get() + it);
  222. it+=12;
  223. //8 unknown bytes - skipping
  224. //13 bytes for name of every frame in this block - not used, skipping
  225. it+= 13 * (int)totalEntries;
  226. for (ui32 j=0; j<totalEntries; j++)
  227. {
  228. size_t currOffset = read_le_u32(data.get() + it);
  229. offset[blockID].push_back(currOffset);
  230. it += 4;
  231. }
  232. }
  233. }
  234. std::shared_ptr<QImage> DefFile::loadFrame(size_t frame, size_t group) const
  235. {
  236. std::map<size_t, std::vector <size_t> >::const_iterator it;
  237. it = offset.find(group);
  238. assert (it != offset.end());
  239. const ui8 * FDef = data.get()+it->second[frame];
  240. const SSpriteDef sd = * reinterpret_cast<const SSpriteDef *>(FDef);
  241. SSpriteDef sprite;
  242. sprite.format = read_le_u32(&sd.format);
  243. sprite.fullWidth = read_le_u32(&sd.fullWidth);
  244. sprite.fullHeight = read_le_u32(&sd.fullHeight);
  245. sprite.width = read_le_u32(&sd.width);
  246. sprite.height = read_le_u32(&sd.height);
  247. sprite.leftMargin = read_le_u32(&sd.leftMargin);
  248. sprite.topMargin = read_le_u32(&sd.topMargin);
  249. ui32 currentOffset = sizeof(SSpriteDef);
  250. //special case for some "old" format defs (SGTWMTA.DEF and SGTWMTB.DEF)
  251. if(sprite.format == 1 && sprite.width > sprite.fullWidth && sprite.height > sprite.fullHeight)
  252. {
  253. sprite.leftMargin = 0;
  254. sprite.topMargin = 0;
  255. sprite.width = sprite.fullWidth;
  256. sprite.height = sprite.fullHeight;
  257. currentOffset -= 16;
  258. }
  259. const ui32 BaseOffset = currentOffset;
  260. std::shared_ptr<QImage> img = std::make_shared<QImage>(sprite.fullWidth, sprite.fullHeight, QImage::Format_Indexed8);
  261. if(!img)
  262. throw std::runtime_error("Image memory cannot be allocated");
  263. ImageLoader loader(img.get());
  264. loader.init(QPoint(sprite.width, sprite.height),
  265. QPoint(sprite.leftMargin, sprite.topMargin),
  266. QPoint(sprite.fullWidth, sprite.fullHeight));
  267. switch(sprite.format)
  268. {
  269. case 0:
  270. {
  271. //pixel data is not compressed, copy data to surface
  272. for(ui32 i=0; i<sprite.height; i++)
  273. {
  274. loader.Load(sprite.width, FDef + currentOffset);
  275. currentOffset += sprite.width;
  276. loader.EndLine();
  277. }
  278. break;
  279. }
  280. case 1:
  281. {
  282. //for each line we have offset of pixel data
  283. const ui32 * RWEntriesLoc = reinterpret_cast<const ui32 *>(FDef+currentOffset);
  284. currentOffset += sizeof(ui32) * sprite.height;
  285. for(ui32 i=0; i<sprite.height; i++)
  286. {
  287. //get position of the line
  288. currentOffset=BaseOffset + read_le_u32(RWEntriesLoc + i);
  289. ui32 TotalRowLength = 0;
  290. while(TotalRowLength<sprite.width)
  291. {
  292. ui8 segmentType = FDef[currentOffset++];
  293. ui32 length = FDef[currentOffset++] + 1;
  294. if(segmentType==0xFF)//Raw data
  295. {
  296. loader.Load(length, FDef + currentOffset);
  297. currentOffset+=length;
  298. }
  299. else// RLE
  300. {
  301. loader.Load(length, segmentType);
  302. }
  303. TotalRowLength += length;
  304. }
  305. loader.EndLine();
  306. }
  307. break;
  308. }
  309. case 2:
  310. {
  311. currentOffset = BaseOffset + read_le_u16(FDef + BaseOffset);
  312. for(ui32 i=0; i<sprite.height; i++)
  313. {
  314. ui32 TotalRowLength=0;
  315. while(TotalRowLength<sprite.width)
  316. {
  317. ui8 segment=FDef[currentOffset++];
  318. ui8 code = segment / 32;
  319. ui8 length = (segment & 31) + 1;
  320. if(code==7)//Raw data
  321. {
  322. loader.Load(length, FDef + currentOffset);
  323. currentOffset += length;
  324. }
  325. else//RLE
  326. {
  327. loader.Load(length, code);
  328. }
  329. TotalRowLength+=length;
  330. }
  331. loader.EndLine();
  332. }
  333. break;
  334. }
  335. case 3:
  336. {
  337. for(ui32 i=0; i<sprite.height; i++)
  338. {
  339. currentOffset = BaseOffset + read_le_u16(FDef + BaseOffset+i*2*(sprite.width/32));
  340. ui32 TotalRowLength=0;
  341. while(TotalRowLength<sprite.width)
  342. {
  343. ui8 segment = FDef[currentOffset++];
  344. ui8 code = segment / 32;
  345. ui8 length = (segment & 31) + 1;
  346. if(code==7)//Raw data
  347. {
  348. loader.Load(length, FDef + currentOffset);
  349. currentOffset += length;
  350. }
  351. else//RLE
  352. {
  353. loader.Load(length, code);
  354. }
  355. TotalRowLength += length;
  356. }
  357. loader.EndLine();
  358. }
  359. break;
  360. }
  361. default:
  362. logGlobal->error("Error: unsupported format of def file: %d", sprite.format);
  363. break;
  364. }
  365. img->setColorTable(*palette);
  366. return img;
  367. }
  368. DefFile::~DefFile() = default;
  369. const std::map<size_t, size_t > DefFile::getEntries() const
  370. {
  371. std::map<size_t, size_t > ret;
  372. for (auto & elem : offset)
  373. ret[elem.first] = elem.second.size();
  374. return ret;
  375. }
  376. /*************************************************************************
  377. * Classes for image loaders - helpers for loading from def files *
  378. *************************************************************************/
  379. ImageLoader::ImageLoader(QImage * Img):
  380. image(Img),
  381. lineStart(Img->bits()),
  382. position(Img->bits())
  383. {
  384. }
  385. void ImageLoader::init(QPoint SpriteSize, QPoint Margins, QPoint FullSize)
  386. {
  387. spriteSize = SpriteSize;
  388. margins = Margins;
  389. fullSize = FullSize;
  390. memset((void *)image->bits(), 0, fullSize.y() * image->bytesPerLine());
  391. lineStart = image->bits();
  392. lineStart += margins.y() * image->bytesPerLine() + margins.x();
  393. position = lineStart;
  394. }
  395. inline void ImageLoader::Load(size_t size, const ui8 * data)
  396. {
  397. if(size)
  398. {
  399. memcpy((void *)position, data, size);
  400. position += size;
  401. }
  402. }
  403. inline void ImageLoader::Load(size_t size, ui8 color)
  404. {
  405. if(size)
  406. {
  407. memset((void *)position, color, size);
  408. position += size;
  409. }
  410. }
  411. inline void ImageLoader::EndLine()
  412. {
  413. lineStart += image->bytesPerLine();
  414. position = lineStart;
  415. }
  416. ImageLoader::~ImageLoader()
  417. {
  418. }
  419. /*************************************************************************
  420. * Classes for images, support loading from file and drawing on surface *
  421. *************************************************************************/
  422. std::shared_ptr<QImage> Animation::getFromExtraDef(std::string filename)
  423. {
  424. size_t pos = filename.find(':');
  425. if(pos == -1)
  426. return nullptr;
  427. Animation anim(filename.substr(0, pos));
  428. pos++;
  429. size_t frame = atoi(filename.c_str()+pos);
  430. size_t group = 0;
  431. pos = filename.find(':', pos);
  432. if(pos != -1)
  433. {
  434. pos++;
  435. group = frame;
  436. frame = atoi(filename.c_str()+pos);
  437. }
  438. anim.load(frame ,group);
  439. auto ret = anim.images[group][frame];
  440. anim.images.clear();
  441. return ret;
  442. }
  443. bool Animation::loadFrame(size_t frame, size_t group)
  444. {
  445. if(size(group) <= frame)
  446. {
  447. printError(frame, group, "LoadFrame");
  448. return false;
  449. }
  450. auto image = getImage(frame, group, false);
  451. if(image)
  452. {
  453. return true;
  454. }
  455. //try to get image from def
  456. if(source[group][frame].getType() == JsonNode::JsonType::DATA_NULL)
  457. {
  458. if(defFile)
  459. {
  460. auto frameList = defFile->getEntries();
  461. if(vstd::contains(frameList, group) && frameList.at(group) > frame) // frame is present
  462. {
  463. images[group][frame] = defFile->loadFrame(frame, group);
  464. return true;
  465. }
  466. }
  467. // still here? image is missing
  468. printError(frame, group, "LoadFrame");
  469. images[group][frame] = std::make_shared<QImage>("DEFAULT");
  470. }
  471. else //load from separate file
  472. {
  473. auto img = getFromExtraDef(source[group][frame]["file"].String());
  474. if(!img)
  475. {
  476. auto bitmap = BitmapHandler::loadBitmap(source[group][frame]["file"].String());
  477. img.reset(new QImage(bitmap));
  478. }
  479. images[group][frame] = img;
  480. return true;
  481. }
  482. return false;
  483. }
  484. bool Animation::unloadFrame(size_t frame, size_t group)
  485. {
  486. auto image = getImage(frame, group, false);
  487. if(image)
  488. {
  489. images[group].erase(frame);
  490. if(images[group].empty())
  491. images.erase(group);
  492. return true;
  493. }
  494. return false;
  495. }
  496. void Animation::init()
  497. {
  498. if(defFile)
  499. {
  500. const std::map<size_t, size_t> defEntries = defFile->getEntries();
  501. for (auto & defEntry : defEntries)
  502. source[defEntry.first].resize(defEntry.second);
  503. }
  504. JsonPath resID = JsonPath::builtin("SPRITES/" + name);
  505. if(vstd::contains(graphics->imageLists, resID.getName()))
  506. initFromJson(graphics->imageLists[resID.getName()]);
  507. auto configList = CResourceHandler::get()->getResourcesWithName(resID);
  508. for(auto & loader : configList)
  509. {
  510. auto stream = loader->load(resID);
  511. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  512. stream->read(textData.get(), stream->getSize());
  513. const JsonNode config((char*)textData.get(), stream->getSize());
  514. initFromJson(config);
  515. }
  516. }
  517. void Animation::initFromJson(const JsonNode & config)
  518. {
  519. std::string basepath;
  520. basepath = config["basepath"].String();
  521. JsonNode base(JsonNode::JsonType::DATA_STRUCT);
  522. base["margins"] = config["margins"];
  523. base["width"] = config["width"];
  524. base["height"] = config["height"];
  525. for(const JsonNode & group : config["sequences"].Vector())
  526. {
  527. size_t groupID = group["group"].Integer();//TODO: string-to-value conversion("moving" -> MOVING)
  528. source[groupID].clear();
  529. for(const JsonNode & frame : group["frames"].Vector())
  530. {
  531. JsonNode toAdd(JsonNode::JsonType::DATA_STRUCT);
  532. JsonUtils::inherit(toAdd, base);
  533. toAdd["file"].String() = basepath + frame.String();
  534. source[groupID].push_back(toAdd);
  535. }
  536. }
  537. for(const JsonNode & node : config["images"].Vector())
  538. {
  539. size_t group = node["group"].Integer();
  540. size_t frame = node["frame"].Integer();
  541. if (source[group].size() <= frame)
  542. source[group].resize(frame+1);
  543. JsonNode toAdd(JsonNode::JsonType::DATA_STRUCT);
  544. JsonUtils::inherit(toAdd, base);
  545. toAdd["file"].String() = basepath + node["file"].String();
  546. source[group][frame] = toAdd;
  547. }
  548. }
  549. void Animation::printError(size_t frame, size_t group, std::string type) const
  550. {
  551. logGlobal->error("%s error: Request for frame not present in CAnimation! File name: %s, Group: %d, Frame: %d", type, name, group, frame);
  552. }
  553. Animation::Animation(std::string Name):
  554. name(Name),
  555. preloaded(false),
  556. defFile()
  557. {
  558. size_t dotPos = name.find_last_of('.');
  559. if( dotPos!=-1 )
  560. name.erase(dotPos);
  561. std::transform(name.begin(), name.end(), name.begin(), toupper);
  562. auto resource = AnimationPath::builtin("SPRITES/" + name);
  563. if(CResourceHandler::get()->existsResource(resource))
  564. defFile = std::make_shared<DefFile>(name);
  565. init();
  566. if(source.empty())
  567. logAnim->error("Animation %s failed to load", Name);
  568. }
  569. Animation::Animation():
  570. name(""),
  571. preloaded(false),
  572. defFile()
  573. {
  574. init();
  575. }
  576. Animation::~Animation() = default;
  577. void Animation::duplicateImage(const size_t sourceGroup, const size_t sourceFrame, const size_t targetGroup)
  578. {
  579. if(!source.count(sourceGroup))
  580. {
  581. logAnim->error("Group %d missing in %s", sourceGroup, name);
  582. return;
  583. }
  584. if(source[sourceGroup].size() <= sourceFrame)
  585. {
  586. logAnim->error("Frame [%d %d] missing in %s", sourceGroup, sourceFrame, name);
  587. return;
  588. }
  589. //todo: clone actual loaded Image object
  590. JsonNode clone(source[sourceGroup][sourceFrame]);
  591. if(clone.getType() == JsonNode::JsonType::DATA_NULL)
  592. {
  593. std::string temp = name+":"+std::to_string(sourceGroup)+":"+std::to_string(sourceFrame);
  594. clone["file"].String() = temp;
  595. }
  596. source[targetGroup].push_back(clone);
  597. size_t index = source[targetGroup].size() - 1;
  598. if(preloaded)
  599. load(index, targetGroup);
  600. }
  601. void Animation::setCustom(std::string filename, size_t frame, size_t group)
  602. {
  603. if(source[group].size() <= frame)
  604. source[group].resize(frame+1);
  605. source[group][frame]["file"].String() = filename;
  606. //FIXME: update image if already loaded
  607. }
  608. std::shared_ptr<QImage> Animation::getImage(size_t frame, size_t group, bool verbose) const
  609. {
  610. auto groupIter = images.find(group);
  611. if(groupIter != images.end())
  612. {
  613. auto imageIter = groupIter->second.find(frame);
  614. if(imageIter != groupIter->second.end())
  615. return imageIter->second;
  616. }
  617. if(verbose)
  618. printError(frame, group, "GetImage");
  619. return nullptr;
  620. }
  621. void Animation::exportBitmaps(const QDir & path) const
  622. {
  623. if(images.empty())
  624. {
  625. logGlobal->error("Nothing to export, animation is empty");
  626. return;
  627. }
  628. QString actualPath = path.absolutePath() + "/" + QString::fromStdString(name);
  629. QDir().mkdir(actualPath);
  630. size_t counter = 0;
  631. for(const auto& groupPair : images)
  632. {
  633. size_t group = groupPair.first;
  634. for(const auto& imagePair : groupPair.second)
  635. {
  636. size_t frame = imagePair.first;
  637. const auto img = imagePair.second;
  638. QString filename = QString("%1_%2_%3.png").arg(QString::fromStdString(name)).arg(group).arg(frame);
  639. QString filePath = actualPath + "/" + filename;
  640. img->save(filePath, "PNG");
  641. counter++;
  642. }
  643. }
  644. logGlobal->info("Exported %d frames to %s", counter, actualPath.toStdString());
  645. }
  646. void Animation::load()
  647. {
  648. for (auto & elem : source)
  649. for (size_t image=0; image < elem.second.size(); image++)
  650. loadFrame(image, elem.first);
  651. }
  652. void Animation::unload()
  653. {
  654. for (auto & elem : source)
  655. for (size_t image=0; image < elem.second.size(); image++)
  656. unloadFrame(image, elem.first);
  657. }
  658. void Animation::preload()
  659. {
  660. if(!preloaded)
  661. {
  662. preloaded = true;
  663. load();
  664. }
  665. }
  666. void Animation::loadGroup(size_t group)
  667. {
  668. if(vstd::contains(source, group))
  669. for (size_t image=0; image < source[group].size(); image++)
  670. loadFrame(image, group);
  671. }
  672. void Animation::unloadGroup(size_t group)
  673. {
  674. if(vstd::contains(source, group))
  675. for (size_t image=0; image < source[group].size(); image++)
  676. unloadFrame(image, group);
  677. }
  678. void Animation::load(size_t frame, size_t group)
  679. {
  680. loadFrame(frame, group);
  681. }
  682. void Animation::unload(size_t frame, size_t group)
  683. {
  684. unloadFrame(frame, group);
  685. }
  686. size_t Animation::size(size_t group) const
  687. {
  688. auto iter = source.find(group);
  689. if(iter != source.end())
  690. return iter->second.size();
  691. return 0;
  692. }
  693. void Animation::horizontalFlip()
  694. {
  695. for(auto & group : images)
  696. for(auto & image : group.second)
  697. *image.second = image.second->transformed(QTransform::fromScale(-1, 1));
  698. }
  699. void Animation::verticalFlip()
  700. {
  701. for(auto & group : images)
  702. for(auto & image : group.second)
  703. *image.second = image.second->transformed(QTransform::fromScale(1, -1));
  704. }
  705. void Animation::playerColored(PlayerColor player)
  706. {
  707. #if 0 //can be required in image preview?
  708. for(auto & group : images)
  709. for(auto & image : group.second)
  710. image.second->playerColored(player);
  711. #endif
  712. }
  713. void Animation::createFlippedGroup(const size_t sourceGroup, const size_t targetGroup)
  714. {
  715. for(size_t frame = 0; frame < size(sourceGroup); ++frame)
  716. {
  717. duplicateImage(sourceGroup, frame, targetGroup);
  718. auto image = getImage(frame, targetGroup);
  719. *image = image->transformed(QTransform::fromScale(1, -1));
  720. }
  721. }