RenderHandler.cpp 11 KB

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