Animation.cpp 20 KB

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