2
0

RenderHandler.cpp 10.0 KB

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