RenderHandler.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  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 "ScalableImage.h"
  14. #include "FontChain.h"
  15. #include "../gui/CGuiHandler.h"
  16. #include "../render/CAnimation.h"
  17. #include "../render/CanvasImage.h"
  18. #include "../render/CDefFile.h"
  19. #include "../render/Colors.h"
  20. #include "../render/ColorFilter.h"
  21. #include "../render/IScreenHandler.h"
  22. #include "../../lib/json/JsonUtils.h"
  23. #include "../../lib/CThreadHelper.h"
  24. #include "../../lib/filesystem/Filesystem.h"
  25. #include "../../lib/VCMIDirs.h"
  26. #include <vcmi/ArtifactService.h>
  27. #include <vcmi/CreatureService.h>
  28. #include <vcmi/Entity.h>
  29. #include <vcmi/FactionService.h>
  30. #include <vcmi/HeroTypeService.h>
  31. #include <vcmi/Services.h>
  32. #include <vcmi/SkillService.h>
  33. #include <vcmi/spells/Service.h>
  34. std::shared_ptr<CDefFile> RenderHandler::getAnimationFile(const AnimationPath & path)
  35. {
  36. AnimationPath actualPath = boost::starts_with(path.getName(), "SPRITES") ? path : path.addPrefix("SPRITES/");
  37. auto it = animationFiles.find(actualPath);
  38. if (it != animationFiles.end())
  39. return it->second;
  40. if (!CResourceHandler::get()->existsResource(actualPath))
  41. {
  42. animationFiles[actualPath] = nullptr;
  43. return nullptr;
  44. }
  45. auto result = std::make_shared<CDefFile>(actualPath);
  46. animationFiles[actualPath] = result;
  47. return result;
  48. }
  49. void RenderHandler::initFromJson(AnimationLayoutMap & source, const JsonNode & config, EImageBlitMode mode)
  50. {
  51. std::string basepath;
  52. basepath = config["basepath"].String();
  53. JsonNode base;
  54. base["margins"] = config["margins"];
  55. base["width"] = config["width"];
  56. base["height"] = config["height"];
  57. for(const JsonNode & group : config["sequences"].Vector())
  58. {
  59. size_t groupID = group["group"].Integer();//TODO: string-to-value conversion("moving" -> MOVING)
  60. source[groupID].clear();
  61. for(const JsonNode & frame : group["frames"].Vector())
  62. {
  63. JsonNode toAdd = frame;
  64. JsonUtils::inherit(toAdd, base);
  65. toAdd["file"].String() = basepath + frame.String();
  66. source[groupID].emplace_back(toAdd, mode);
  67. }
  68. }
  69. for(const JsonNode & node : config["images"].Vector())
  70. {
  71. size_t group = node["group"].Integer();
  72. size_t frame = node["frame"].Integer();
  73. if (source[group].size() <= frame)
  74. source[group].resize(frame+1);
  75. JsonNode toAdd = node;
  76. JsonUtils::inherit(toAdd, base);
  77. if (toAdd.Struct().count("file"))
  78. toAdd["file"].String() = basepath + node["file"].String();
  79. if (toAdd.Struct().count("defFile"))
  80. toAdd["defFile"].String() = basepath + node["defFile"].String();
  81. source[group][frame] = ImageLocator(toAdd, mode);
  82. }
  83. }
  84. RenderHandler::AnimationLayoutMap & RenderHandler::getAnimationLayout(const AnimationPath & path, int scalingFactor, EImageBlitMode mode)
  85. {
  86. static constexpr std::array scaledSpritesPath = {
  87. "", // 0x
  88. "SPRITES/",
  89. "SPRITES2X/",
  90. "SPRITES3X/",
  91. "SPRITES4X/",
  92. };
  93. std::string pathString = path.getName();
  94. if (boost::starts_with(pathString, "SPRITES/"))
  95. pathString = pathString.substr(std::string("SPRITES/").length());
  96. AnimationPath actualPath = AnimationPath::builtin(scaledSpritesPath.at(scalingFactor) + pathString);
  97. auto it = animationLayouts.find(actualPath);
  98. if (it != animationLayouts.end())
  99. return it->second;
  100. AnimationLayoutMap result;
  101. auto defFile = getAnimationFile(actualPath);
  102. if(defFile)
  103. {
  104. const std::map<size_t, size_t> defEntries = defFile->getEntries();
  105. for (const auto & defEntry : defEntries)
  106. result[defEntry.first].resize(defEntry.second);
  107. }
  108. auto jsonResource = actualPath.toType<EResType::JSON>();
  109. auto configList = CResourceHandler::get()->getResourcesWithName(jsonResource);
  110. for(auto & loader : configList)
  111. {
  112. auto stream = loader->load(jsonResource);
  113. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  114. stream->read(textData.get(), stream->getSize());
  115. const JsonNode config(reinterpret_cast<const std::byte*>(textData.get()), stream->getSize(), path.getOriginalName());
  116. initFromJson(result, config, mode);
  117. }
  118. animationLayouts[actualPath] = result;
  119. return animationLayouts[actualPath];
  120. }
  121. int RenderHandler::getScalingFactor() const
  122. {
  123. return GH.screenHandler().getScalingFactor();
  124. }
  125. ImageLocator RenderHandler::getLocatorForAnimationFrame(const AnimationPath & path, int frame, int group, int scaling, EImageBlitMode mode)
  126. {
  127. const auto & layout = getAnimationLayout(path, scaling, mode);
  128. if (!layout.count(group))
  129. return ImageLocator();
  130. if (frame >= layout.at(group).size())
  131. return ImageLocator();
  132. const auto & locator = layout.at(group).at(frame);
  133. if (locator.image || locator.defFile)
  134. return locator;
  135. return ImageLocator(path, frame, group, mode);
  136. }
  137. std::shared_ptr<ScalableImageShared> RenderHandler::loadImageImpl(const ImageLocator & locator)
  138. {
  139. auto it = imageFiles.find(locator);
  140. if (it != imageFiles.end())
  141. return it->second;
  142. auto sdlImage = loadImageFromFileUncached(locator);
  143. auto scaledImage = std::make_shared<ScalableImageShared>(locator, sdlImage);
  144. storeCachedImage(locator, scaledImage);
  145. return scaledImage;
  146. }
  147. std::shared_ptr<SDLImageShared> RenderHandler::loadImageFromFileUncached(const ImageLocator & locator)
  148. {
  149. if(locator.image)
  150. {
  151. // TODO: create EmptySharedImage class that will be instantiated if image does not exists or fails to load
  152. return std::make_shared<SDLImageShared>(*locator.image);
  153. }
  154. if(locator.defFile)
  155. {
  156. auto defFile = getAnimationFile(*locator.defFile);
  157. if(defFile->hasFrame(locator.defFrame, locator.defGroup))
  158. return std::make_shared<SDLImageShared>(defFile.get(), locator.defFrame, locator.defGroup);
  159. else
  160. {
  161. logGlobal->error("Frame %d in group %d not found in file: %s",
  162. locator.defFrame, locator.defGroup, locator.defFile->getName().c_str());
  163. return std::make_shared<SDLImageShared>(ImagePath::builtin("DEFAULT"));
  164. }
  165. }
  166. throw std::runtime_error("Invalid image locator received!");
  167. }
  168. void RenderHandler::storeCachedImage(const ImageLocator & locator, std::shared_ptr<ScalableImageShared> image)
  169. {
  170. imageFiles[locator] = image;
  171. }
  172. std::shared_ptr<SDLImageShared> RenderHandler::loadScaledImage(const ImageLocator & locator)
  173. {
  174. assert(locator.scalingFactor > 1);
  175. static constexpr std::array scaledDataPath = {
  176. "", // 0x
  177. "DATA/",
  178. "DATA2X/",
  179. "DATA3X/",
  180. "DATA4X/",
  181. };
  182. static constexpr std::array scaledSpritesPath = {
  183. "", // 0x
  184. "SPRITES/",
  185. "SPRITES2X/",
  186. "SPRITES3X/",
  187. "SPRITES4X/",
  188. };
  189. ImagePath pathToLoad;
  190. if(locator.defFile)
  191. {
  192. auto remappedLocator = getLocatorForAnimationFrame(*locator.defFile, locator.defFrame, locator.defGroup, locator.scalingFactor, locator.layer);
  193. // we expect that .def's are only used for 1x data, upscaled assets should use standalone images
  194. if (!remappedLocator.image)
  195. return nullptr;
  196. pathToLoad = *remappedLocator.image;
  197. }
  198. if(!locator.image)
  199. return nullptr;
  200. pathToLoad = *locator.image;
  201. std::string imagePathString = pathToLoad.getName();
  202. if(locator.layer == EImageBlitMode::ONLY_OVERLAY)
  203. imagePathString += "-OVERLAY";
  204. if(locator.layer == EImageBlitMode::ONLY_SHADOW)
  205. imagePathString += "-SHADOW";
  206. auto imagePath = ImagePath::builtin(imagePathString);
  207. auto imagePathSprites = ImagePath::builtin(imagePathString).addPrefix(scaledSpritesPath.at(locator.scalingFactor));
  208. auto imagePathData = ImagePath::builtin(imagePathString).addPrefix(scaledDataPath.at(locator.scalingFactor));
  209. if(CResourceHandler::get()->existsResource(imagePathSprites))
  210. return std::make_shared<SDLImageShared>(imagePathSprites);
  211. if(CResourceHandler::get()->existsResource(imagePathData))
  212. return std::make_shared<SDLImageShared>(imagePathData);
  213. if(CResourceHandler::get()->existsResource(imagePath))
  214. return std::make_shared<SDLImageShared>(imagePath);
  215. return nullptr;
  216. }
  217. std::shared_ptr<IImage> RenderHandler::loadImage(const ImageLocator & locator)
  218. {
  219. ImageLocator adjustedLocator = locator;
  220. std::shared_ptr<ScalableImageInstance> result;
  221. if (adjustedLocator.scalingFactor == 0)
  222. {
  223. auto scaledLocator = adjustedLocator;
  224. scaledLocator.scalingFactor = getScalingFactor();
  225. result = loadImageImpl(scaledLocator)->createImageReference();
  226. }
  227. else
  228. result = loadImageImpl(adjustedLocator)->createImageReference();
  229. if (locator.horizontalFlip)
  230. result->horizontalFlip();
  231. if (locator.verticalFlip)
  232. result->verticalFlip();
  233. return result;
  234. }
  235. std::shared_ptr<IImage> RenderHandler::loadImage(const AnimationPath & path, int frame, int group, EImageBlitMode mode)
  236. {
  237. ImageLocator locator = getLocatorForAnimationFrame(path, frame, group, 1, mode);
  238. if (!locator.empty())
  239. return loadImage(locator);
  240. else
  241. return loadImage(ImageLocator(ImagePath::builtin("DEFAULT"), mode));
  242. }
  243. std::shared_ptr<IImage> RenderHandler::loadImage(const ImagePath & path, EImageBlitMode mode)
  244. {
  245. ImageLocator locator(path, mode);
  246. return loadImage(locator);
  247. }
  248. std::shared_ptr<CanvasImage> RenderHandler::createImage(const Point & size, CanvasScalingPolicy scalingPolicy)
  249. {
  250. return std::make_shared<CanvasImage>(size, scalingPolicy);
  251. }
  252. std::shared_ptr<CAnimation> RenderHandler::loadAnimation(const AnimationPath & path, EImageBlitMode mode)
  253. {
  254. return std::make_shared<CAnimation>(path, getAnimationLayout(path, 1, mode), mode);
  255. }
  256. void RenderHandler::addImageListEntries(const EntityService * service)
  257. {
  258. service->forEachBase([this](const Entity * entity, bool & stop)
  259. {
  260. entity->registerIcons([this](size_t index, size_t group, const std::string & listName, const std::string & imageName)
  261. {
  262. if (imageName.empty())
  263. return;
  264. auto & layout = getAnimationLayout(AnimationPath::builtin("SPRITES/" + listName), 1, EImageBlitMode::SIMPLE);
  265. JsonNode entry;
  266. entry["file"].String() = imageName;
  267. if (index >= layout[group].size())
  268. layout[group].resize(index + 1);
  269. layout[group][index] = ImageLocator(entry, EImageBlitMode::SIMPLE);
  270. });
  271. });
  272. }
  273. void RenderHandler::onLibraryLoadingFinished(const Services * services)
  274. {
  275. addImageListEntries(services->creatures());
  276. addImageListEntries(services->heroTypes());
  277. addImageListEntries(services->artifacts());
  278. addImageListEntries(services->factions());
  279. addImageListEntries(services->spells());
  280. addImageListEntries(services->skills());
  281. }
  282. std::shared_ptr<const IFont> RenderHandler::loadFont(EFonts font)
  283. {
  284. if (fonts.count(font))
  285. return fonts.at(font);
  286. const int8_t index = static_cast<int8_t>(font);
  287. logGlobal->debug("Loading font %d", static_cast<int>(index));
  288. auto configList = CResourceHandler::get()->getResourcesWithName(JsonPath::builtin("config/fonts.json"));
  289. std::shared_ptr<FontChain> loadedFont = std::make_shared<FontChain>();
  290. std::string bitmapPath;
  291. for(auto & loader : configList)
  292. {
  293. auto stream = loader->load(JsonPath::builtin("config/fonts.json"));
  294. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  295. stream->read(textData.get(), stream->getSize());
  296. const JsonNode config(reinterpret_cast<const std::byte*>(textData.get()), stream->getSize(), "config/fonts.json");
  297. const JsonVector & bmpConf = config["bitmap"].Vector();
  298. const JsonNode & ttfConf = config["trueType"];
  299. bitmapPath = bmpConf[index].String();
  300. if (!ttfConf[bitmapPath].isNull())
  301. loadedFont->addTrueTypeFont(ttfConf[bitmapPath]);
  302. }
  303. loadedFont->addBitmapFont(bitmapPath);
  304. fonts[font] = loadedFont;
  305. return loadedFont;
  306. }