Animation.cpp 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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 "ColorFilter.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. #include "../../lib/vcmi_endian.h"
  21. #include <SDL_surface.h>
  22. std::shared_ptr<IImage> CAnimation::getFromExtraDef(std::string filename)
  23. {
  24. size_t pos = filename.find(':');
  25. if (pos == -1)
  26. return nullptr;
  27. CAnimation anim(filename.substr(0, pos));
  28. pos++;
  29. size_t frame = atoi(filename.c_str()+pos);
  30. size_t group = 0;
  31. pos = filename.find(':', pos);
  32. if (pos != -1)
  33. {
  34. pos++;
  35. group = frame;
  36. frame = atoi(filename.c_str()+pos);
  37. }
  38. anim.load(frame ,group);
  39. auto ret = anim.images[group][frame];
  40. anim.images.clear();
  41. return ret;
  42. }
  43. bool CAnimation::loadFrame(size_t frame, size_t group)
  44. {
  45. if(size(group) <= frame)
  46. {
  47. printError(frame, group, "LoadFrame");
  48. return false;
  49. }
  50. auto image = getImage(frame, group, false);
  51. if(image)
  52. {
  53. return true;
  54. }
  55. //try to get image from def
  56. if(source[group][frame].getType() == JsonNode::JsonType::DATA_NULL)
  57. {
  58. if(defFile)
  59. {
  60. auto frameList = defFile->getEntries();
  61. if(vstd::contains(frameList, group) && frameList.at(group) > frame) // frame is present
  62. {
  63. images[group][frame] = std::make_shared<SDLImage>(defFile.get(), frame, group);
  64. return true;
  65. }
  66. }
  67. // still here? image is missing
  68. printError(frame, group, "LoadFrame");
  69. images[group][frame] = std::make_shared<SDLImage>("DEFAULT");
  70. }
  71. else //load from separate file
  72. {
  73. auto img = getFromExtraDef(source[group][frame]["file"].String());
  74. if(!img)
  75. img = std::make_shared<SDLImage>(source[group][frame]);
  76. images[group][frame] = img;
  77. return true;
  78. }
  79. return false;
  80. }
  81. bool CAnimation::unloadFrame(size_t frame, size_t group)
  82. {
  83. auto image = getImage(frame, group, false);
  84. if(image)
  85. {
  86. images[group].erase(frame);
  87. if(images[group].empty())
  88. images.erase(group);
  89. return true;
  90. }
  91. return false;
  92. }
  93. void CAnimation::initFromJson(const JsonNode & config)
  94. {
  95. std::string basepath;
  96. basepath = config["basepath"].String();
  97. JsonNode base(JsonNode::JsonType::DATA_STRUCT);
  98. base["margins"] = config["margins"];
  99. base["width"] = config["width"];
  100. base["height"] = config["height"];
  101. for(const JsonNode & group : config["sequences"].Vector())
  102. {
  103. size_t groupID = group["group"].Integer();//TODO: string-to-value conversion("moving" -> MOVING)
  104. source[groupID].clear();
  105. for(const JsonNode & frame : group["frames"].Vector())
  106. {
  107. JsonNode toAdd(JsonNode::JsonType::DATA_STRUCT);
  108. JsonUtils::inherit(toAdd, base);
  109. toAdd["file"].String() = basepath + frame.String();
  110. source[groupID].push_back(toAdd);
  111. }
  112. }
  113. for(const JsonNode & node : config["images"].Vector())
  114. {
  115. size_t group = node["group"].Integer();
  116. size_t frame = node["frame"].Integer();
  117. if (source[group].size() <= frame)
  118. source[group].resize(frame+1);
  119. JsonNode toAdd(JsonNode::JsonType::DATA_STRUCT);
  120. JsonUtils::inherit(toAdd, base);
  121. toAdd["file"].String() = basepath + node["file"].String();
  122. source[group][frame] = toAdd;
  123. }
  124. }
  125. void CAnimation::exportBitmaps(const boost::filesystem::path& path) const
  126. {
  127. if(images.empty())
  128. {
  129. logGlobal->error("Nothing to export, animation is empty");
  130. return;
  131. }
  132. boost::filesystem::path actualPath = path / "SPRITES" / name;
  133. boost::filesystem::create_directories(actualPath);
  134. size_t counter = 0;
  135. for(const auto & groupPair : images)
  136. {
  137. size_t group = groupPair.first;
  138. for(const auto & imagePair : groupPair.second)
  139. {
  140. size_t frame = imagePair.first;
  141. const auto img = imagePair.second;
  142. boost::format fmt("%d_%d.bmp");
  143. fmt % group % frame;
  144. img->exportBitmap(actualPath / fmt.str());
  145. counter++;
  146. }
  147. }
  148. logGlobal->info("Exported %d frames to %s", counter, actualPath.string());
  149. }
  150. void CAnimation::init()
  151. {
  152. if(defFile)
  153. {
  154. const std::map<size_t, size_t> defEntries = defFile->getEntries();
  155. for (auto & defEntry : defEntries)
  156. source[defEntry.first].resize(defEntry.second);
  157. }
  158. ResourceID resID(std::string("SPRITES/") + name, EResType::TEXT);
  159. if (vstd::contains(graphics->imageLists, resID.getName()))
  160. initFromJson(graphics->imageLists[resID.getName()]);
  161. auto configList = CResourceHandler::get()->getResourcesWithName(resID);
  162. for(auto & loader : configList)
  163. {
  164. auto stream = loader->load(resID);
  165. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  166. stream->read(textData.get(), stream->getSize());
  167. const JsonNode config((char*)textData.get(), stream->getSize());
  168. initFromJson(config);
  169. }
  170. }
  171. void CAnimation::printError(size_t frame, size_t group, std::string type) const
  172. {
  173. logGlobal->error("%s error: Request for frame not present in CAnimation! File name: %s, Group: %d, Frame: %d", type, name, group, frame);
  174. }
  175. CAnimation::CAnimation(std::string Name):
  176. name(Name),
  177. preloaded(false),
  178. defFile()
  179. {
  180. size_t dotPos = name.find_last_of('.');
  181. if ( dotPos!=-1 )
  182. name.erase(dotPos);
  183. std::transform(name.begin(), name.end(), name.begin(), toupper);
  184. ResourceID resource(std::string("SPRITES/") + name, EResType::ANIMATION);
  185. if(CResourceHandler::get()->existsResource(resource))
  186. defFile = std::make_shared<CDefFile>(name);
  187. init();
  188. if(source.empty())
  189. logAnim->error("Animation %s failed to load", Name);
  190. }
  191. CAnimation::CAnimation():
  192. name(""),
  193. preloaded(false),
  194. defFile()
  195. {
  196. init();
  197. }
  198. CAnimation::~CAnimation() = default;
  199. void CAnimation::duplicateImage(const size_t sourceGroup, const size_t sourceFrame, const size_t targetGroup)
  200. {
  201. if(!source.count(sourceGroup))
  202. {
  203. logAnim->error("Group %d missing in %s", sourceGroup, name);
  204. return;
  205. }
  206. if(source[sourceGroup].size() <= sourceFrame)
  207. {
  208. logAnim->error("Frame [%d %d] missing in %s", sourceGroup, sourceFrame, name);
  209. return;
  210. }
  211. //todo: clone actual loaded Image object
  212. JsonNode clone(source[sourceGroup][sourceFrame]);
  213. if(clone.getType() == JsonNode::JsonType::DATA_NULL)
  214. {
  215. std::string temp = name+":"+boost::lexical_cast<std::string>(sourceGroup)+":"+boost::lexical_cast<std::string>(sourceFrame);
  216. clone["file"].String() = temp;
  217. }
  218. source[targetGroup].push_back(clone);
  219. size_t index = source[targetGroup].size() - 1;
  220. if(preloaded)
  221. load(index, targetGroup);
  222. }
  223. void CAnimation::setCustom(std::string filename, size_t frame, size_t group)
  224. {
  225. if (source[group].size() <= frame)
  226. source[group].resize(frame+1);
  227. source[group][frame]["file"].String() = filename;
  228. //FIXME: update image if already loaded
  229. }
  230. std::shared_ptr<IImage> CAnimation::getImage(size_t frame, size_t group, bool verbose) const
  231. {
  232. auto groupIter = images.find(group);
  233. if (groupIter != images.end())
  234. {
  235. auto imageIter = groupIter->second.find(frame);
  236. if (imageIter != groupIter->second.end())
  237. return imageIter->second;
  238. }
  239. if (verbose)
  240. printError(frame, group, "GetImage");
  241. return nullptr;
  242. }
  243. void CAnimation::load()
  244. {
  245. for (auto & elem : source)
  246. for (size_t image=0; image < elem.second.size(); image++)
  247. loadFrame(image, elem.first);
  248. }
  249. void CAnimation::unload()
  250. {
  251. for (auto & elem : source)
  252. for (size_t image=0; image < elem.second.size(); image++)
  253. unloadFrame(image, elem.first);
  254. }
  255. void CAnimation::preload()
  256. {
  257. if(!preloaded)
  258. {
  259. preloaded = true;
  260. load();
  261. }
  262. }
  263. void CAnimation::loadGroup(size_t group)
  264. {
  265. if (vstd::contains(source, group))
  266. for (size_t image=0; image < source[group].size(); image++)
  267. loadFrame(image, group);
  268. }
  269. void CAnimation::unloadGroup(size_t group)
  270. {
  271. if (vstd::contains(source, group))
  272. for (size_t image=0; image < source[group].size(); image++)
  273. unloadFrame(image, group);
  274. }
  275. void CAnimation::load(size_t frame, size_t group)
  276. {
  277. loadFrame(frame, group);
  278. }
  279. void CAnimation::unload(size_t frame, size_t group)
  280. {
  281. unloadFrame(frame, group);
  282. }
  283. size_t CAnimation::size(size_t group) const
  284. {
  285. auto iter = source.find(group);
  286. if (iter != source.end())
  287. return iter->second.size();
  288. return 0;
  289. }
  290. void CAnimation::horizontalFlip()
  291. {
  292. for(auto & group : images)
  293. for(auto & image : group.second)
  294. image.second->horizontalFlip();
  295. }
  296. void CAnimation::verticalFlip()
  297. {
  298. for(auto & group : images)
  299. for(auto & image : group.second)
  300. image.second->verticalFlip();
  301. }
  302. void CAnimation::playerColored(PlayerColor player)
  303. {
  304. for(auto & group : images)
  305. for(auto & image : group.second)
  306. image.second->playerColored(player);
  307. }
  308. void CAnimation::createFlippedGroup(const size_t sourceGroup, const size_t targetGroup)
  309. {
  310. for(size_t frame = 0; frame < size(sourceGroup); ++frame)
  311. {
  312. duplicateImage(sourceGroup, frame, targetGroup);
  313. auto image = getImage(frame, targetGroup);
  314. image->verticalFlip();
  315. }
  316. }