CModHandler.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. /*
  2. * CModHandler.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 "CModHandler.h"
  12. #include "ContentTypeHandler.h"
  13. #include "IdentifierStorage.h"
  14. #include "ModDescription.h"
  15. #include "ModManager.h"
  16. #include "ModScope.h"
  17. #include "../CConfigHandler.h"
  18. #include "../CCreatureHandler.h"
  19. #include "../GameSettings.h"
  20. #include "../ScriptHandler.h"
  21. #include "../VCMI_Lib.h"
  22. #include "../filesystem/Filesystem.h"
  23. #include "../json/JsonUtils.h"
  24. #include "../texts/CGeneralTextHandler.h"
  25. #include "../texts/Languages.h"
  26. VCMI_LIB_NAMESPACE_BEGIN
  27. CModHandler::CModHandler()
  28. : content(std::make_shared<CContentHandler>())
  29. , modManager(std::make_unique<ModManager>())
  30. {
  31. }
  32. CModHandler::~CModHandler() = default;
  33. std::vector<std::string> CModHandler::getAllMods() const
  34. {
  35. return modManager->getAllMods();
  36. }
  37. const std::vector<std::string> & CModHandler::getActiveMods() const
  38. {
  39. return modManager->getActiveMods();
  40. }
  41. const ModDescription & CModHandler::getModInfo(const TModID & modId) const
  42. {
  43. return modManager->getModDescription(modId);
  44. }
  45. static JsonNode genDefaultFS()
  46. {
  47. // default FS config for mods: directory "Content" that acts as H3 root directory
  48. JsonNode defaultFS;
  49. defaultFS[""].Vector().resize(2);
  50. defaultFS[""].Vector()[0]["type"].String() = "zip";
  51. defaultFS[""].Vector()[0]["path"].String() = "/Content.zip";
  52. defaultFS[""].Vector()[1]["type"].String() = "dir";
  53. defaultFS[""].Vector()[1]["path"].String() = "/Content";
  54. return defaultFS;
  55. }
  56. static std::string getModDirectory(const TModID & modName)
  57. {
  58. std::string result = modName;
  59. boost::to_upper(result);
  60. boost::algorithm::replace_all(result, ".", "/MODS/");
  61. return "MODS/" + result;
  62. }
  63. static ISimpleResourceLoader * genModFilesystem(const std::string & modName, const JsonNode & conf)
  64. {
  65. static const JsonNode defaultFS = genDefaultFS();
  66. if (!conf.isNull())
  67. return CResourceHandler::createFileSystem(getModDirectory(modName), conf);
  68. else
  69. return CResourceHandler::createFileSystem(getModDirectory(modName), defaultFS);
  70. }
  71. void CModHandler::loadModFilesystems()
  72. {
  73. CGeneralTextHandler::detectInstallParameters();
  74. const auto & activeMods = modManager->getActiveMods();
  75. std::map<TModID, ISimpleResourceLoader *> modFilesystems;
  76. for(const TModID & modName : activeMods)
  77. modFilesystems[modName] = genModFilesystem(modName, getModInfo(modName).getFilesystemConfig());
  78. for(const TModID & modName : activeMods)
  79. if (modName != "core") // virtual mod 'core' has no filesystem on its own - shared with base install
  80. CResourceHandler::addFilesystem("data", modName, modFilesystems[modName]);
  81. if (settings["mods"]["validation"].String() == "full")
  82. checkModFilesystemsConflicts(modFilesystems);
  83. }
  84. void CModHandler::checkModFilesystemsConflicts(const std::map<TModID, ISimpleResourceLoader *> & modFilesystems)
  85. {
  86. for(const auto & [leftName, leftFilesystem] : modFilesystems)
  87. {
  88. for(const auto & [rightName, rightFilesystem] : modFilesystems)
  89. {
  90. if (leftName == rightName)
  91. continue;
  92. if (getModDependencies(leftName).count(rightName) || getModDependencies(rightName).count(leftName))
  93. continue;
  94. if (getModSoftDependencies(leftName).count(rightName) || getModSoftDependencies(rightName).count(leftName))
  95. continue;
  96. const auto & filter = [](const ResourcePath &path){return path.getType() != EResType::DIRECTORY && path.getType() != EResType::JSON;};
  97. std::unordered_set<ResourcePath> leftResources = leftFilesystem->getFilteredFiles(filter);
  98. std::unordered_set<ResourcePath> rightResources = rightFilesystem->getFilteredFiles(filter);
  99. for (auto const & leftFile : leftResources)
  100. {
  101. if (rightResources.count(leftFile))
  102. logMod->warn("Potential confict detected between '%s' and '%s': both mods add file '%s'", leftName, rightName, leftFile.getOriginalName());
  103. }
  104. }
  105. }
  106. }
  107. TModID CModHandler::findResourceOrigin(const ResourcePath & name) const
  108. {
  109. try
  110. {
  111. auto activeMode = modManager->getActiveMods();
  112. for(const auto & modID : boost::adaptors::reverse(activeMode))
  113. {
  114. if(CResourceHandler::get(modID)->existsResource(name))
  115. return modID;
  116. }
  117. if(CResourceHandler::get("core")->existsResource(name))
  118. return "core";
  119. if(CResourceHandler::get("mapEditor")->existsResource(name))
  120. return "core"; // Workaround for loading maps via map editor
  121. }
  122. catch( const std::out_of_range & e)
  123. {
  124. // no-op
  125. }
  126. throw std::runtime_error("Resource with name " + name.getName() + " and type " + EResTypeHelper::getEResTypeAsString(name.getType()) + " wasn't found.");
  127. }
  128. std::string CModHandler::findResourceLanguage(const ResourcePath & name) const
  129. {
  130. std::string modName = findResourceOrigin(name);
  131. std::string modLanguage = getModLanguage(modName);
  132. return modLanguage;
  133. }
  134. std::string CModHandler::findResourceEncoding(const ResourcePath & resource) const
  135. {
  136. std::string modName = findResourceOrigin(resource);
  137. std::string modLanguage = findResourceLanguage(resource);
  138. bool potentiallyUserMadeContent = resource.getType() == EResType::MAP || resource.getType() == EResType::CAMPAIGN;
  139. if (potentiallyUserMadeContent && modName == ModScope::scopeBuiltin() && modLanguage == "english")
  140. {
  141. // this might be a map or campaign that player downloaded manually and placed in Maps/ directory
  142. // in this case, this file may be in user-preferred language, and not in same language as the rest of H3 data
  143. // however at the moment we have no way to detect that for sure - file can be either in English or in user-preferred language
  144. // but since all known H3 encodings (Win125X or GBK) are supersets of ASCII, we can safely load English data using encoding of user-preferred language
  145. std::string preferredLanguage = VLC->generaltexth->getPreferredLanguage();
  146. std::string fileEncoding = Languages::getLanguageOptions(preferredLanguage).encoding;
  147. return fileEncoding;
  148. }
  149. else
  150. {
  151. std::string fileEncoding = Languages::getLanguageOptions(modLanguage).encoding;
  152. return fileEncoding;
  153. }
  154. }
  155. std::string CModHandler::getModLanguage(const TModID& modId) const
  156. {
  157. if(modId == "core")
  158. return VLC->generaltexth->getInstalledLanguage();
  159. if(modId == "map")
  160. return VLC->generaltexth->getPreferredLanguage();
  161. return getModInfo(modId).getBaseLanguage();
  162. }
  163. std::set<TModID> CModHandler::getModDependencies(const TModID & modId) const
  164. {
  165. bool isModFound;
  166. return getModDependencies(modId, isModFound);
  167. }
  168. std::set<TModID> CModHandler::getModDependencies(const TModID & modId, bool & isModFound) const
  169. {
  170. isModFound = modManager->isModActive(modId);
  171. if (isModFound)
  172. return modManager->getModDescription(modId).getDependencies();
  173. logMod->error("Mod not found: '%s'", modId);
  174. return {};
  175. }
  176. std::set<TModID> CModHandler::getModSoftDependencies(const TModID & modId) const
  177. {
  178. return modManager->getModDescription(modId).getSoftDependencies();
  179. }
  180. std::set<TModID> CModHandler::getModEnabledSoftDependencies(const TModID & modId) const
  181. {
  182. std::set<TModID> softDependencies = getModSoftDependencies(modId);
  183. vstd::erase_if(softDependencies, [this](const TModID & dependency){ return !modManager->isModActive(dependency);});
  184. return softDependencies;
  185. }
  186. void CModHandler::initializeConfig()
  187. {
  188. for(const TModID & modName : getActiveMods())
  189. {
  190. const auto & mod = getModInfo(modName);
  191. if (!mod.getLocalConfig()["settings"].isNull())
  192. VLC->settingsHandler->loadBase(mod.getLocalConfig()["settings"]);
  193. }
  194. }
  195. void CModHandler::loadTranslation(const TModID & modName)
  196. {
  197. const auto & mod = getModInfo(modName);
  198. std::string preferredLanguage = VLC->generaltexth->getPreferredLanguage();
  199. std::string modBaseLanguage = getModInfo(modName).getBaseLanguage();
  200. JsonNode baseTranslation = JsonUtils::assembleFromFiles(mod.getLocalConfig()["translations"]);
  201. JsonNode extraTranslation = JsonUtils::assembleFromFiles(mod.getLocalConfig()[preferredLanguage]["translations"]);
  202. VLC->generaltexth->loadTranslationOverrides(modName, modBaseLanguage, baseTranslation);
  203. VLC->generaltexth->loadTranslationOverrides(modName, preferredLanguage, extraTranslation);
  204. }
  205. void CModHandler::load()
  206. {
  207. logMod->info("\tInitializing content handler");
  208. content->init();
  209. const auto & activeMods = getActiveMods();
  210. validationPassed.insert(activeMods.begin(), activeMods.end());
  211. for(const TModID & modName : activeMods)
  212. {
  213. modChecksums[modName] = this->modManager->computeChecksum(modName);
  214. }
  215. for(const TModID & modName : activeMods)
  216. {
  217. const auto & modInfo = getModInfo(modName);
  218. bool isValid = content->preloadData(modInfo, isModValidationNeeded(modInfo));
  219. if (isValid)
  220. logGlobal->info("\t\tParsing mod: OK (%s)", modInfo.getName());
  221. else
  222. logGlobal->warn("\t\tParsing mod: Issues found! (%s)", modInfo.getName());
  223. if (!isValid)
  224. validationPassed.erase(modName);
  225. }
  226. logMod->info("\tParsing mod data");
  227. for(const TModID & modName : activeMods)
  228. {
  229. const auto & modInfo = getModInfo(modName);
  230. bool isValid = content->load(getModInfo(modName), isModValidationNeeded(getModInfo(modName)));
  231. if (isValid)
  232. logGlobal->info("\t\tLoading mod: OK (%s)", modInfo.getName());
  233. else
  234. logGlobal->warn("\t\tLoading mod: Issues found! (%s)", modInfo.getName());
  235. if (!isValid)
  236. validationPassed.erase(modName);
  237. }
  238. #if SCRIPTING_ENABLED
  239. VLC->scriptHandler->performRegistration(VLC);//todo: this should be done before any other handlers load
  240. #endif
  241. content->loadCustom();
  242. for(const TModID & modName : activeMods)
  243. loadTranslation(modName);
  244. logMod->info("\tLoading mod data");
  245. VLC->creh->loadCrExpMod();
  246. VLC->identifiersHandler->finalize();
  247. logMod->info("\tResolving identifiers");
  248. content->afterLoadFinalization();
  249. logMod->info("\tHandlers post-load finalization");
  250. logMod->info("\tAll game content loaded");
  251. }
  252. void CModHandler::afterLoad(bool onlyEssential)
  253. {
  254. JsonNode modSettings;
  255. for (const auto & modEntry : getActiveMods())
  256. {
  257. if (validationPassed.count(modEntry))
  258. modManager->setValidatedChecksum(modEntry, modChecksums.at(modEntry));
  259. else
  260. modManager->setValidatedChecksum(modEntry, std::nullopt);
  261. }
  262. modManager->saveConfigurationState();
  263. }
  264. bool CModHandler::isModValidationNeeded(const ModDescription & mod) const
  265. {
  266. if (settings["mods"]["validation"].String() == "full")
  267. return true;
  268. if (modManager->getValidatedChecksum(mod.getID()) == modChecksums.at(mod.getID()))
  269. return false;
  270. if (settings["mods"]["validation"].String() == "off")
  271. return false;
  272. return true;
  273. }
  274. VCMI_LIB_NAMESPACE_END