RenderHandler.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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/CConfigHandler.h"
  23. #include "../../lib/CThreadHelper.h"
  24. #include "../../lib/VCMIDirs.h"
  25. #include "../../lib/constants/StringConstants.h"
  26. #include "../../lib/entities/building/CBuilding.h"
  27. #include "../../lib/entities/faction/CTown.h"
  28. #include "../../lib/entities/faction/CTownHandler.h"
  29. #include "../../lib/filesystem/Filesystem.h"
  30. #include "../../lib/json/JsonUtils.h"
  31. #include <vcmi/ArtifactService.h>
  32. #include <vcmi/CreatureService.h>
  33. #include <vcmi/Entity.h>
  34. #include <vcmi/FactionService.h>
  35. #include <vcmi/HeroTypeService.h>
  36. #include <vcmi/Services.h>
  37. #include <vcmi/SkillService.h>
  38. #include <vcmi/spells/Service.h>
  39. std::shared_ptr<CDefFile> RenderHandler::getAnimationFile(const AnimationPath & path)
  40. {
  41. AnimationPath actualPath = boost::starts_with(path.getName(), "SPRITES") ? path : path.addPrefix("SPRITES/");
  42. auto it = animationFiles.find(actualPath);
  43. if (it != animationFiles.end())
  44. return it->second;
  45. if (!CResourceHandler::get()->existsResource(actualPath))
  46. {
  47. animationFiles[actualPath] = nullptr;
  48. return nullptr;
  49. }
  50. auto result = std::make_shared<CDefFile>(actualPath);
  51. animationFiles[actualPath] = result;
  52. return result;
  53. }
  54. void RenderHandler::initFromJson(AnimationLayoutMap & source, const JsonNode & config, EImageBlitMode mode)
  55. {
  56. std::string basepath;
  57. basepath = config["basepath"].String();
  58. JsonNode base;
  59. base["margins"] = config["margins"];
  60. base["width"] = config["width"];
  61. base["height"] = config["height"];
  62. for(const JsonNode & group : config["sequences"].Vector())
  63. {
  64. size_t groupID = group["group"].Integer();//TODO: string-to-value conversion("moving" -> MOVING)
  65. source[groupID].clear();
  66. for(const JsonNode & frame : group["frames"].Vector())
  67. {
  68. JsonNode toAdd = frame;
  69. JsonUtils::inherit(toAdd, base);
  70. toAdd["file"].String() = basepath + frame.String();
  71. source[groupID].emplace_back(toAdd, mode);
  72. }
  73. }
  74. for(const JsonNode & node : config["images"].Vector())
  75. {
  76. size_t group = node["group"].Integer();
  77. size_t frame = node["frame"].Integer();
  78. if (source[group].size() <= frame)
  79. source[group].resize(frame+1);
  80. JsonNode toAdd = node;
  81. JsonUtils::inherit(toAdd, base);
  82. if (toAdd.Struct().count("file"))
  83. toAdd["file"].String() = basepath + node["file"].String();
  84. if (toAdd.Struct().count("defFile"))
  85. toAdd["defFile"].String() = basepath + node["defFile"].String();
  86. source[group][frame] = ImageLocator(toAdd, mode);
  87. }
  88. }
  89. RenderHandler::AnimationLayoutMap & RenderHandler::getAnimationLayout(const AnimationPath & path, int scalingFactor, EImageBlitMode mode)
  90. {
  91. static constexpr std::array scaledSpritesPath = {
  92. "", // 0x
  93. "SPRITES/",
  94. "SPRITES2X/",
  95. "SPRITES3X/",
  96. "SPRITES4X/",
  97. };
  98. std::string pathString = path.getName();
  99. if (boost::starts_with(pathString, "SPRITES/"))
  100. pathString = pathString.substr(std::string("SPRITES/").length());
  101. AnimationPath actualPath = AnimationPath::builtin(scaledSpritesPath.at(scalingFactor) + pathString);
  102. auto it = animationLayouts.find(actualPath);
  103. if (it != animationLayouts.end())
  104. return it->second;
  105. AnimationLayoutMap result;
  106. auto defFile = getAnimationFile(actualPath);
  107. if(defFile)
  108. {
  109. const std::map<size_t, size_t> defEntries = defFile->getEntries();
  110. for (const auto & defEntry : defEntries)
  111. result[defEntry.first].resize(defEntry.second);
  112. }
  113. auto jsonResource = actualPath.toType<EResType::JSON>();
  114. auto configList = CResourceHandler::get()->getResourcesWithName(jsonResource);
  115. for(auto & loader : configList)
  116. {
  117. auto stream = loader->load(jsonResource);
  118. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  119. stream->read(textData.get(), stream->getSize());
  120. const JsonNode config(reinterpret_cast<const std::byte*>(textData.get()), stream->getSize(), path.getOriginalName());
  121. initFromJson(result, config, mode);
  122. }
  123. animationLayouts[actualPath] = result;
  124. return animationLayouts[actualPath];
  125. }
  126. int RenderHandler::getScalingFactor() const
  127. {
  128. return GH.screenHandler().getScalingFactor();
  129. }
  130. ImageLocator RenderHandler::getLocatorForAnimationFrame(const AnimationPath & path, int frame, int group, int scaling, EImageBlitMode mode)
  131. {
  132. const auto & layout = getAnimationLayout(path, scaling, mode);
  133. if (!layout.count(group))
  134. return ImageLocator();
  135. if (frame >= layout.at(group).size())
  136. return ImageLocator();
  137. const auto & locator = layout.at(group).at(frame);
  138. if (locator.image || locator.defFile)
  139. return locator;
  140. return ImageLocator(path, frame, group, mode);
  141. }
  142. std::shared_ptr<ScalableImageShared> RenderHandler::loadImageImpl(const ImageLocator & locator)
  143. {
  144. auto it = imageFiles.find(locator);
  145. if (it != imageFiles.end())
  146. return it->second;
  147. auto sdlImage = loadImageFromFileUncached(locator);
  148. auto scaledImage = std::make_shared<ScalableImageShared>(locator, sdlImage);
  149. storeCachedImage(locator, scaledImage);
  150. return scaledImage;
  151. }
  152. std::shared_ptr<SDLImageShared> RenderHandler::loadImageFromFileUncached(const ImageLocator & locator)
  153. {
  154. if(locator.image)
  155. {
  156. // TODO: create EmptySharedImage class that will be instantiated if image does not exists or fails to load
  157. return std::make_shared<SDLImageShared>(*locator.image);
  158. }
  159. if(locator.defFile)
  160. {
  161. auto defFile = getAnimationFile(*locator.defFile);
  162. if(defFile->hasFrame(locator.defFrame, locator.defGroup))
  163. return std::make_shared<SDLImageShared>(defFile.get(), locator.defFrame, locator.defGroup);
  164. else
  165. {
  166. logGlobal->error("Frame %d in group %d not found in file: %s",
  167. locator.defFrame, locator.defGroup, locator.defFile->getName().c_str());
  168. return std::make_shared<SDLImageShared>(ImagePath::builtin("DEFAULT"));
  169. }
  170. }
  171. throw std::runtime_error("Invalid image locator received!");
  172. }
  173. void RenderHandler::storeCachedImage(const ImageLocator & locator, std::shared_ptr<ScalableImageShared> image)
  174. {
  175. imageFiles[locator] = image;
  176. }
  177. std::shared_ptr<SDLImageShared> RenderHandler::loadScaledImage(const ImageLocator & locator)
  178. {
  179. static constexpr std::array scaledDataPath = {
  180. "", // 0x
  181. "DATA/",
  182. "DATA2X/",
  183. "DATA3X/",
  184. "DATA4X/",
  185. };
  186. static constexpr std::array scaledSpritesPath = {
  187. "", // 0x
  188. "SPRITES/",
  189. "SPRITES2X/",
  190. "SPRITES3X/",
  191. "SPRITES4X/",
  192. };
  193. ImagePath pathToLoad;
  194. if(locator.defFile)
  195. {
  196. auto remappedLocator = getLocatorForAnimationFrame(*locator.defFile, locator.defFrame, locator.defGroup, locator.scalingFactor, locator.layer);
  197. // we expect that .def's are only used for 1x data, upscaled assets should use standalone images
  198. if (!remappedLocator.image)
  199. return nullptr;
  200. pathToLoad = *remappedLocator.image;
  201. }
  202. if(locator.image)
  203. pathToLoad = *locator.image;
  204. if (pathToLoad.empty())
  205. return nullptr;
  206. std::string imagePathString = pathToLoad.getName();
  207. if(locator.layer == EImageBlitMode::ONLY_OVERLAY)
  208. imagePathString += "-OVERLAY";
  209. if(locator.layer == EImageBlitMode::ONLY_SHADOW)
  210. imagePathString += "-SHADOW";
  211. if(locator.playerColored.isValidPlayer())
  212. imagePathString += "-" + boost::to_upper_copy(GameConstants::PLAYER_COLOR_NAMES[locator.playerColored.getNum()]);
  213. if(locator.playerColored == PlayerColor::NEUTRAL)
  214. imagePathString += "-NEUTRAL";
  215. auto imagePath = ImagePath::builtin(imagePathString);
  216. auto imagePathSprites = ImagePath::builtin(imagePathString).addPrefix(scaledSpritesPath.at(locator.scalingFactor));
  217. auto imagePathData = ImagePath::builtin(imagePathString).addPrefix(scaledDataPath.at(locator.scalingFactor));
  218. if(CResourceHandler::get()->existsResource(imagePathSprites))
  219. return std::make_shared<SDLImageShared>(imagePathSprites);
  220. if(CResourceHandler::get()->existsResource(imagePathData))
  221. return std::make_shared<SDLImageShared>(imagePathData);
  222. if(CResourceHandler::get()->existsResource(imagePath))
  223. return std::make_shared<SDLImageShared>(imagePath);
  224. return nullptr;
  225. }
  226. std::shared_ptr<IImage> RenderHandler::loadImage(const ImageLocator & locator)
  227. {
  228. ImageLocator adjustedLocator = locator;
  229. std::shared_ptr<ScalableImageInstance> result;
  230. if (adjustedLocator.scalingFactor == 0)
  231. {
  232. auto scaledLocator = adjustedLocator;
  233. scaledLocator.scalingFactor = getScalingFactor();
  234. result = loadImageImpl(scaledLocator)->createImageReference();
  235. }
  236. else
  237. result = loadImageImpl(adjustedLocator)->createImageReference();
  238. if (locator.horizontalFlip)
  239. result->horizontalFlip();
  240. if (locator.verticalFlip)
  241. result->verticalFlip();
  242. return result;
  243. }
  244. std::shared_ptr<IImage> RenderHandler::loadImage(const AnimationPath & path, int frame, int group, EImageBlitMode mode)
  245. {
  246. ImageLocator locator = getLocatorForAnimationFrame(path, frame, group, 1, mode);
  247. if (!locator.empty())
  248. return loadImage(locator);
  249. else
  250. return loadImage(ImageLocator(ImagePath::builtin("DEFAULT"), mode));
  251. }
  252. std::shared_ptr<IImage> RenderHandler::loadImage(const ImagePath & path, EImageBlitMode mode)
  253. {
  254. ImageLocator locator(path, mode);
  255. return loadImage(locator);
  256. }
  257. std::shared_ptr<CanvasImage> RenderHandler::createImage(const Point & size, CanvasScalingPolicy scalingPolicy)
  258. {
  259. return std::make_shared<CanvasImage>(size, scalingPolicy);
  260. }
  261. std::shared_ptr<CAnimation> RenderHandler::loadAnimation(const AnimationPath & path, EImageBlitMode mode)
  262. {
  263. return std::make_shared<CAnimation>(path, getAnimationLayout(path, 1, mode), mode);
  264. }
  265. void RenderHandler::addImageListEntries(const EntityService * service)
  266. {
  267. service->forEachBase([this](const Entity * entity, bool & stop)
  268. {
  269. entity->registerIcons([this](size_t index, size_t group, const std::string & listName, const std::string & imageName)
  270. {
  271. if (imageName.empty())
  272. return;
  273. auto & layout = getAnimationLayout(AnimationPath::builtin("SPRITES/" + listName), 1, EImageBlitMode::SIMPLE);
  274. JsonNode entry;
  275. entry["file"].String() = imageName;
  276. if (index >= layout[group].size())
  277. layout[group].resize(index + 1);
  278. layout[group][index] = ImageLocator(entry, EImageBlitMode::SIMPLE);
  279. });
  280. });
  281. }
  282. static void detectOverlappingBuildings(RenderHandler * renderHandler, const Faction * factionBase)
  283. {
  284. if (!factionBase->hasTown())
  285. return;
  286. auto faction = dynamic_cast<const CFaction*>(factionBase);
  287. for (const auto & left : faction->town->clientInfo.structures)
  288. {
  289. for (const auto & right : faction->town->clientInfo.structures)
  290. {
  291. if (left->identifier <= right->identifier)
  292. continue; // only a<->b comparison is needed, not a<->a or b<->a
  293. if (left->building && right->building && left->building->getBase() == right->building->getBase())
  294. continue; // upgrades of the same buildings are expected to overlap
  295. if (left->pos.z != right->pos.z)
  296. continue; // buildings already have different z-index and have well-defined overlap logic
  297. auto leftImage = renderHandler->loadImage(left->defName, 0, 0, EImageBlitMode::SIMPLE);
  298. auto rightImage = renderHandler->loadImage(right->defName, 0, 0, EImageBlitMode::SIMPLE);
  299. Rect leftRect( left->pos.x, left->pos.y, leftImage->width(), leftImage->height());
  300. Rect rightRect( right->pos.x, right->pos.y, rightImage->width(), rightImage->height());
  301. Rect intersection = leftRect.intersect(rightRect);
  302. Point intersectionPosition;
  303. bool intersectionFound = false;
  304. for (int y = 0; y < intersection.h && !intersectionFound; ++y)
  305. {
  306. for (int x = 0; x < intersection.w && !intersectionFound; ++x)
  307. {
  308. Point leftPoint = Point(x,y) - leftRect.topLeft() + intersection.topLeft();
  309. Point rightPoint = Point(x,y) - rightRect.topLeft() + intersection.topLeft();
  310. if (!leftImage->isTransparent(leftPoint) && !rightImage->isTransparent(rightPoint))
  311. {
  312. intersectionFound = true;
  313. intersectionPosition = intersection.topLeft() + Point(x,y);
  314. }
  315. }
  316. }
  317. if (intersectionFound)
  318. logMod->warn("Town %s: Detected overlapping buildings '%s' and '%s' at (%d, %d) with same z-index!", faction->getJsonKey(), left->identifier, right->identifier, intersectionPosition.x, intersectionPosition.y);
  319. }
  320. }
  321. };
  322. void RenderHandler::onLibraryLoadingFinished(const Services * services)
  323. {
  324. addImageListEntries(services->creatures());
  325. addImageListEntries(services->heroTypes());
  326. addImageListEntries(services->artifacts());
  327. addImageListEntries(services->factions());
  328. addImageListEntries(services->spells());
  329. addImageListEntries(services->skills());
  330. if (settings["mods"]["validation"].String() == "full")
  331. {
  332. services->factions()->forEach([this](const Faction * factionBase, bool & stop)
  333. {
  334. detectOverlappingBuildings(this, factionBase);
  335. });
  336. }
  337. }
  338. std::shared_ptr<const IFont> RenderHandler::loadFont(EFonts font)
  339. {
  340. if (fonts.count(font))
  341. return fonts.at(font);
  342. const int8_t index = static_cast<int8_t>(font);
  343. logGlobal->debug("Loading font %d", static_cast<int>(index));
  344. auto configList = CResourceHandler::get()->getResourcesWithName(JsonPath::builtin("config/fonts.json"));
  345. std::shared_ptr<FontChain> loadedFont = std::make_shared<FontChain>();
  346. std::string bitmapPath;
  347. for(auto & loader : configList)
  348. {
  349. auto stream = loader->load(JsonPath::builtin("config/fonts.json"));
  350. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  351. stream->read(textData.get(), stream->getSize());
  352. const JsonNode config(reinterpret_cast<const std::byte*>(textData.get()), stream->getSize(), "config/fonts.json");
  353. const JsonVector & bmpConf = config["bitmap"].Vector();
  354. const JsonNode & ttfConf = config["trueType"];
  355. bitmapPath = bmpConf[index].String();
  356. if (!ttfConf[bitmapPath].isNull())
  357. loadedFont->addTrueTypeFont(ttfConf[bitmapPath]);
  358. }
  359. loadedFont->addBitmapFont(bitmapPath);
  360. fonts[font] = loadedFont;
  361. return loadedFont;
  362. }