RenderHandler.cpp 11 KB

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