RenderHandler.cpp 16 KB

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