CModHandler.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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 "mapEditor"; // 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. if(modId == "mapEditor")
  162. return VLC->generaltexth->getPreferredLanguage();
  163. return getModInfo(modId).getBaseLanguage();
  164. }
  165. std::set<TModID> CModHandler::getModDependencies(const TModID & modId) const
  166. {
  167. bool isModFound;
  168. return getModDependencies(modId, isModFound);
  169. }
  170. std::set<TModID> CModHandler::getModDependencies(const TModID & modId, bool & isModFound) const
  171. {
  172. isModFound = modManager->isModActive(modId);
  173. if (isModFound)
  174. return modManager->getModDescription(modId).getDependencies();
  175. logMod->error("Mod not found: '%s'", modId);
  176. return {};
  177. }
  178. std::set<TModID> CModHandler::getModSoftDependencies(const TModID & modId) const
  179. {
  180. return modManager->getModDescription(modId).getSoftDependencies();
  181. }
  182. std::set<TModID> CModHandler::getModEnabledSoftDependencies(const TModID & modId) const
  183. {
  184. std::set<TModID> softDependencies = getModSoftDependencies(modId);
  185. vstd::erase_if(softDependencies, [this](const TModID & dependency){ return !modManager->isModActive(dependency);});
  186. return softDependencies;
  187. }
  188. void CModHandler::initializeConfig()
  189. {
  190. for(const TModID & modName : getActiveMods())
  191. {
  192. const auto & mod = getModInfo(modName);
  193. if (!mod.getLocalConfig()["settings"].isNull())
  194. VLC->settingsHandler->loadBase(mod.getLocalConfig()["settings"]);
  195. }
  196. }
  197. void CModHandler::loadTranslation(const TModID & modName)
  198. {
  199. const auto & mod = getModInfo(modName);
  200. std::string preferredLanguage = VLC->generaltexth->getPreferredLanguage();
  201. std::string modBaseLanguage = getModInfo(modName).getBaseLanguage();
  202. JsonNode baseTranslation = JsonUtils::assembleFromFiles(mod.getLocalConfig()["translations"]);
  203. JsonNode extraTranslation = JsonUtils::assembleFromFiles(mod.getLocalConfig()[preferredLanguage]["translations"]);
  204. VLC->generaltexth->loadTranslationOverrides(modName, modBaseLanguage, baseTranslation);
  205. VLC->generaltexth->loadTranslationOverrides(modName, preferredLanguage, extraTranslation);
  206. }
  207. void CModHandler::load()
  208. {
  209. logMod->info("\tInitializing content handler");
  210. content->init();
  211. const auto & activeMods = getActiveMods();
  212. validationPassed.insert(activeMods.begin(), activeMods.end());
  213. for(const TModID & modName : activeMods)
  214. {
  215. modChecksums[modName] = this->modManager->computeChecksum(modName);
  216. }
  217. for(const TModID & modName : activeMods)
  218. {
  219. const auto & modInfo = getModInfo(modName);
  220. bool isValid = content->preloadData(modInfo, isModValidationNeeded(modInfo));
  221. if (isValid)
  222. logGlobal->info("\t\tParsing mod: OK (%s)", modInfo.getID());
  223. else
  224. logGlobal->warn("\t\tParsing mod: Issues found! (%s)", modInfo.getID());
  225. if (!isValid)
  226. validationPassed.erase(modName);
  227. }
  228. logMod->info("\tParsing mod data");
  229. for(const TModID & modName : activeMods)
  230. {
  231. const auto & modInfo = getModInfo(modName);
  232. bool isValid = content->load(getModInfo(modName), isModValidationNeeded(getModInfo(modName)));
  233. if (isValid)
  234. logGlobal->info("\t\tLoading mod: OK (%s)", modInfo.getID());
  235. else
  236. logGlobal->warn("\t\tLoading mod: Issues found! (%s)", modInfo.getID());
  237. if (!isValid)
  238. validationPassed.erase(modName);
  239. }
  240. #if SCRIPTING_ENABLED
  241. VLC->scriptHandler->performRegistration(VLC);//todo: this should be done before any other handlers load
  242. #endif
  243. content->loadCustom();
  244. for(const TModID & modName : activeMods)
  245. loadTranslation(modName);
  246. logMod->info("\tLoading mod data");
  247. VLC->creh->loadCrExpMod();
  248. VLC->identifiersHandler->finalize();
  249. logMod->info("\tResolving identifiers");
  250. content->afterLoadFinalization();
  251. logMod->info("\tHandlers post-load finalization");
  252. logMod->info("\tAll game content loaded");
  253. }
  254. void CModHandler::afterLoad(bool onlyEssential)
  255. {
  256. JsonNode modSettings;
  257. for (const auto & modEntry : getActiveMods())
  258. {
  259. if (validationPassed.count(modEntry))
  260. modManager->setValidatedChecksum(modEntry, modChecksums.at(modEntry));
  261. else
  262. modManager->setValidatedChecksum(modEntry, std::nullopt);
  263. }
  264. modManager->saveConfigurationState();
  265. }
  266. bool CModHandler::isModValidationNeeded(const ModDescription & mod) const
  267. {
  268. if (settings["mods"]["validation"].String() == "full")
  269. return true;
  270. if (modManager->getValidatedChecksum(mod.getID()) == modChecksums.at(mod.getID()))
  271. return false;
  272. if (settings["mods"]["validation"].String() == "off")
  273. return false;
  274. return true;
  275. }
  276. VCMI_LIB_NAMESPACE_END