RenderHandler.cpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. /*
  2. * RenderHandler.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 "RenderHandler.h"
  12. #include "SDLImage.h"
  13. #include "ImageScaled.h"
  14. #include "../render/CAnimation.h"
  15. #include "../render/CDefFile.h"
  16. #include "../render/Colors.h"
  17. #include "../render/ColorFilter.h"
  18. #include "../../lib/json/JsonUtils.h"
  19. #include "../../lib/filesystem/Filesystem.h"
  20. #include <vcmi/ArtifactService.h>
  21. #include <vcmi/CreatureService.h>
  22. #include <vcmi/Entity.h>
  23. #include <vcmi/FactionService.h>
  24. #include <vcmi/HeroTypeService.h>
  25. #include <vcmi/Services.h>
  26. #include <vcmi/SkillService.h>
  27. #include <vcmi/spells/Service.h>
  28. std::shared_ptr<CDefFile> RenderHandler::getAnimationFile(const AnimationPath & path)
  29. {
  30. AnimationPath actualPath = boost::starts_with(path.getName(), "SPRITES") ? path : path.addPrefix("SPRITES/");
  31. auto it = animationFiles.find(actualPath);
  32. if (it != animationFiles.end())
  33. return it->second;
  34. if (!CResourceHandler::get()->existsResource(actualPath))
  35. {
  36. animationFiles[actualPath] = nullptr;
  37. return nullptr;
  38. }
  39. auto result = std::make_shared<CDefFile>(actualPath);
  40. animationFiles[actualPath] = result;
  41. return result;
  42. }
  43. void RenderHandler::initFromJson(AnimationLayoutMap & source, const JsonNode & config)
  44. {
  45. std::string basepath;
  46. basepath = config["basepath"].String();
  47. JsonNode base;
  48. base["margins"] = config["margins"];
  49. base["width"] = config["width"];
  50. base["height"] = config["height"];
  51. for(const JsonNode & group : config["sequences"].Vector())
  52. {
  53. size_t groupID = group["group"].Integer();//TODO: string-to-value conversion("moving" -> MOVING)
  54. source[groupID].clear();
  55. for(const JsonNode & frame : group["frames"].Vector())
  56. {
  57. JsonNode toAdd = frame;
  58. JsonUtils::inherit(toAdd, base);
  59. toAdd["file"].String() = basepath + frame.String();
  60. source[groupID].emplace_back(toAdd);
  61. }
  62. }
  63. for(const JsonNode & node : config["images"].Vector())
  64. {
  65. size_t group = node["group"].Integer();
  66. size_t frame = node["frame"].Integer();
  67. if (source[group].size() <= frame)
  68. source[group].resize(frame+1);
  69. JsonNode toAdd = node;
  70. JsonUtils::inherit(toAdd, base);
  71. toAdd["file"].String() = basepath + node["file"].String();
  72. source[group][frame] = ImageLocator(toAdd);
  73. }
  74. }
  75. RenderHandler::AnimationLayoutMap & RenderHandler::getAnimationLayout(const AnimationPath & path)
  76. {
  77. AnimationPath actualPath = boost::starts_with(path.getName(), "SPRITES") ? path : path.addPrefix("SPRITES/");
  78. auto it = animationLayouts.find(actualPath);
  79. if (it != animationLayouts.end())
  80. return it->second;
  81. AnimationLayoutMap result;
  82. auto defFile = getAnimationFile(actualPath);
  83. if(defFile)
  84. {
  85. const std::map<size_t, size_t> defEntries = defFile->getEntries();
  86. for (const auto & defEntry : defEntries)
  87. result[defEntry.first].resize(defEntry.second);
  88. }
  89. auto jsonResource = actualPath.toType<EResType::JSON>();
  90. auto configList = CResourceHandler::get()->getResourcesWithName(jsonResource);
  91. for(auto & loader : configList)
  92. {
  93. auto stream = loader->load(jsonResource);
  94. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  95. stream->read(textData.get(), stream->getSize());
  96. const JsonNode config(reinterpret_cast<const std::byte*>(textData.get()), stream->getSize(), path.getOriginalName());
  97. initFromJson(result, config);
  98. }
  99. animationLayouts[actualPath] = result;
  100. return animationLayouts[actualPath];
  101. }
  102. int RenderHandler::getScalingFactor() const
  103. {
  104. return 2;
  105. }
  106. std::shared_ptr<IImage> RenderHandler::createImageReference(const ImageLocator & locator, std::shared_ptr<ISharedImage> input, EImageBlitMode mode)
  107. {
  108. if (getScalingFactor() == 1 || locator.scalingFactor != 1 || locator.empty())
  109. return input->createImageReference(mode);
  110. else
  111. return std::make_shared<ImageScaled>(locator, input, mode);
  112. }
  113. ImageLocator RenderHandler::getLocatorForAnimationFrame(const AnimationPath & path, int frame, int group)
  114. {
  115. const auto & layout = getAnimationLayout(path);
  116. if (!layout.count(group))
  117. return ImageLocator(ImagePath::builtin("DEFAULT"));
  118. if (frame >= layout.at(group).size())
  119. return ImageLocator(ImagePath::builtin("DEFAULT"));
  120. const auto & locator = layout.at(group).at(frame);
  121. if (locator.image || locator.defFile)
  122. return locator;
  123. return ImageLocator(path, frame, group);
  124. }
  125. std::shared_ptr<ISharedImage> RenderHandler::loadImageImpl(const ImageLocator & locator)
  126. {
  127. auto it = imageFiles.find(locator);
  128. if (it != imageFiles.end())
  129. return it->second;
  130. // TODO: order should be different:
  131. // 1) try to find correctly scaled image
  132. // 2) if fails -> try to find correctly transformed
  133. // 3) if also fails -> try to find image from correct file
  134. // 4) load missing part of the sequence
  135. // TODO: check whether (load -> transform -> scale) or (load -> scale -> transform) order should be used for proper loading of pre-scaled data
  136. auto imageFromFile = loadImageFromFile(locator.copyFile());
  137. auto transformedImage = transformImage(locator.copyFileTransform(), imageFromFile);
  138. auto scaledImage = scaleImage(locator.copyFileTransformScale(), transformedImage);
  139. return scaledImage;
  140. }
  141. std::shared_ptr<ISharedImage> RenderHandler::loadImageFromFileUncached(const ImageLocator & locator)
  142. {
  143. if (locator.image)
  144. {
  145. // TODO: create EmptySharedImage class that will be instantiated if image does not exists or fails to load
  146. return std::make_shared<SDLImageShared>(*locator.image);
  147. }
  148. if (locator.defFile)
  149. {
  150. auto defFile = getAnimationFile(*locator.defFile);
  151. return std::make_shared<SDLImageShared>(defFile.get(), locator.defFrame, locator.defGroup);
  152. }
  153. throw std::runtime_error("Invalid image locator received!");
  154. }
  155. std::shared_ptr<ISharedImage> RenderHandler::loadImageFromFile(const ImageLocator & locator)
  156. {
  157. if (imageFiles.count(locator))
  158. return imageFiles.at(locator);
  159. auto result = loadImageFromFileUncached(locator);
  160. imageFiles[locator] = result;
  161. return result;
  162. }
  163. std::shared_ptr<ISharedImage> RenderHandler::transformImage(const ImageLocator & locator, std::shared_ptr<ISharedImage> image)
  164. {
  165. if (imageFiles.count(locator))
  166. return imageFiles.at(locator);
  167. auto result = image;
  168. if (locator.verticalFlip)
  169. result = result->verticalFlip();
  170. if (locator.horizontalFlip)
  171. result = result->horizontalFlip();
  172. imageFiles[locator] = result;
  173. return result;
  174. }
  175. std::shared_ptr<ISharedImage> RenderHandler::scaleImage(const ImageLocator & locator, std::shared_ptr<ISharedImage> image)
  176. {
  177. if (imageFiles.count(locator))
  178. return imageFiles.at(locator);
  179. auto handle = image->createImageReference(EImageBlitMode::OPAQUE);
  180. assert(locator.scalingFactor != 1); // should be filtered-out before
  181. handle->setOverlayEnabled(locator.layerOverlay);
  182. handle->setBodyEnabled(locator.layerBody);
  183. handle->setShadowEnabled(locator.layerShadow);
  184. if (locator.layerBody && locator.playerColored != PlayerColor::CANNOT_DETERMINE)
  185. handle->playerColored(locator.playerColored);
  186. handle->scaleFast(handle->dimensions() * locator.scalingFactor);
  187. // TODO: try to optimize image size (possibly even before scaling?) - trim image borders if they are completely transparent
  188. auto result = handle->getSharedImage();
  189. imageFiles[locator] = result;
  190. return result;
  191. }
  192. std::shared_ptr<IImage> RenderHandler::loadImage(const ImageLocator & locator, EImageBlitMode mode)
  193. {
  194. return createImageReference(locator, loadImageImpl(locator), mode);
  195. }
  196. std::shared_ptr<IImage> RenderHandler::loadImage(const AnimationPath & path, int frame, int group, EImageBlitMode mode)
  197. {
  198. auto locator = getLocatorForAnimationFrame(path, frame, group);
  199. return loadImage(locator, mode);
  200. }
  201. std::shared_ptr<IImage> RenderHandler::loadImage(const ImagePath & path, EImageBlitMode mode)
  202. {
  203. return loadImage(ImageLocator(path), mode);
  204. }
  205. std::shared_ptr<IImage> RenderHandler::createImage(SDL_Surface * source)
  206. {
  207. return createImageReference(ImageLocator(), std::make_shared<SDLImageShared>(source), EImageBlitMode::ALPHA);
  208. }
  209. std::shared_ptr<CAnimation> RenderHandler::loadAnimation(const AnimationPath & path, EImageBlitMode mode)
  210. {
  211. return std::make_shared<CAnimation>(path, getAnimationLayout(path), mode);
  212. }
  213. void RenderHandler::addImageListEntries(const EntityService * service)
  214. {
  215. service->forEachBase([this](const Entity * entity, bool & stop)
  216. {
  217. entity->registerIcons([this](size_t index, size_t group, const std::string & listName, const std::string & imageName)
  218. {
  219. if (imageName.empty())
  220. return;
  221. auto & layout = getAnimationLayout(AnimationPath::builtin("SPRITES/" + listName));
  222. JsonNode entry;
  223. entry["file"].String() = imageName;
  224. if (index >= layout[group].size())
  225. layout[group].resize(index + 1);
  226. layout[group][index] = ImageLocator(entry);
  227. });
  228. });
  229. }
  230. void RenderHandler::onLibraryLoadingFinished(const Services * services)
  231. {
  232. addImageListEntries(services->creatures());
  233. addImageListEntries(services->heroTypes());
  234. addImageListEntries(services->artifacts());
  235. addImageListEntries(services->factions());
  236. addImageListEntries(services->spells());
  237. addImageListEntries(services->skills());
  238. }