RenderHandler.cpp 9.5 KB

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