CModHandler.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  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 "CModInfo.h"
  13. #include "ModScope.h"
  14. #include "ContentTypeHandler.h"
  15. #include "IdentifierStorage.h"
  16. #include "ModIncompatibility.h"
  17. #include "../CCreatureHandler.h"
  18. #include "../CGeneralTextHandler.h"
  19. #include "../CStopWatch.h"
  20. #include "../GameSettings.h"
  21. #include "../Languages.h"
  22. #include "../ScriptHandler.h"
  23. #include "../constants/StringConstants.h"
  24. #include "../filesystem/Filesystem.h"
  25. #include "../spells/CSpellHandler.h"
  26. VCMI_LIB_NAMESPACE_BEGIN
  27. static JsonNode loadModSettings(const JsonPath & path)
  28. {
  29. if (CResourceHandler::get("local")->existsResource(ResourcePath(path)))
  30. {
  31. return JsonNode(path);
  32. }
  33. // Probably new install. Create initial configuration
  34. CResourceHandler::get("local")->createResource(path.getOriginalName() + ".json");
  35. return JsonNode();
  36. }
  37. CModHandler::CModHandler()
  38. : content(std::make_shared<CContentHandler>())
  39. , coreMod(std::make_unique<CModInfo>())
  40. {
  41. }
  42. CModHandler::~CModHandler() = default;
  43. // currentList is passed by value to get current list of depending mods
  44. bool CModHandler::hasCircularDependency(const TModID & modID, std::set<TModID> currentList) const
  45. {
  46. const CModInfo & mod = allMods.at(modID);
  47. // Mod already present? We found a loop
  48. if (vstd::contains(currentList, modID))
  49. {
  50. logMod->error("Error: Circular dependency detected! Printing dependency list:");
  51. logMod->error("\t%s -> ", mod.getVerificationInfo().name);
  52. return true;
  53. }
  54. currentList.insert(modID);
  55. // recursively check every dependency of this mod
  56. for(const TModID & dependency : mod.dependencies)
  57. {
  58. if (hasCircularDependency(dependency, currentList))
  59. {
  60. logMod->error("\t%s ->\n", mod.getVerificationInfo().name); // conflict detected, print dependency list
  61. return true;
  62. }
  63. }
  64. return false;
  65. }
  66. // Returned vector affects the resource loaders call order (see CFilesystemList::load).
  67. // The loaders call order matters when dependent mod overrides resources in its dependencies.
  68. std::vector <TModID> CModHandler::validateAndSortDependencies(std::vector <TModID> modsToResolve) const
  69. {
  70. // Topological sort algorithm.
  71. // TODO: Investigate possible ways to improve performance.
  72. boost::range::sort(modsToResolve); // Sort mods per name
  73. std::vector <TModID> sortedValidMods; // Vector keeps order of elements (LIFO)
  74. sortedValidMods.reserve(modsToResolve.size()); // push_back calls won't cause memory reallocation
  75. std::set <TModID> resolvedModIDs; // Use a set for validation for performance reason, but set does not keep order of elements
  76. // Mod is resolved if it has not dependencies or all its dependencies are already resolved
  77. auto isResolved = [&](const CModInfo & mod) -> CModInfo::EValidationStatus
  78. {
  79. if(mod.dependencies.size() > resolvedModIDs.size())
  80. return CModInfo::PENDING;
  81. for(const TModID & dependency : mod.dependencies)
  82. {
  83. if(!vstd::contains(resolvedModIDs, dependency))
  84. return CModInfo::PENDING;
  85. }
  86. return CModInfo::PASSED;
  87. };
  88. while(true)
  89. {
  90. std::set <TModID> resolvedOnCurrentTreeLevel;
  91. for(auto it = modsToResolve.begin(); it != modsToResolve.end();) // One iteration - one level of mods tree
  92. {
  93. if(isResolved(allMods.at(*it)) == CModInfo::PASSED)
  94. {
  95. resolvedOnCurrentTreeLevel.insert(*it); // Not to the resolvedModIDs, so current node childs will be resolved on the next iteration
  96. sortedValidMods.push_back(*it);
  97. it = modsToResolve.erase(it);
  98. continue;
  99. }
  100. it++;
  101. }
  102. if(!resolvedOnCurrentTreeLevel.empty())
  103. {
  104. resolvedModIDs.insert(resolvedOnCurrentTreeLevel.begin(), resolvedOnCurrentTreeLevel.end());
  105. continue;
  106. }
  107. // If there're no valid mods on the current mods tree level, no more mod can be resolved, should be end.
  108. break;
  109. }
  110. // Left mods have unresolved dependencies, output all to log.
  111. for(const auto & brokenModID : modsToResolve)
  112. {
  113. const CModInfo & brokenMod = allMods.at(brokenModID);
  114. for(const TModID & dependency : brokenMod.dependencies)
  115. {
  116. if(!vstd::contains(resolvedModIDs, dependency))
  117. logMod->error("Mod '%s' will not work: it depends on mod '%s', which is not installed.", brokenMod.getVerificationInfo().name, dependency);
  118. }
  119. }
  120. return sortedValidMods;
  121. }
  122. std::vector<std::string> CModHandler::getModList(const std::string & path) const
  123. {
  124. std::string modDir = boost::to_upper_copy(path + "MODS/");
  125. size_t depth = boost::range::count(modDir, '/');
  126. auto list = CResourceHandler::get("initial")->getFilteredFiles([&](const ResourcePath & id) -> bool
  127. {
  128. if (id.getType() != EResType::DIRECTORY)
  129. return false;
  130. if (!boost::algorithm::starts_with(id.getName(), modDir))
  131. return false;
  132. if (boost::range::count(id.getName(), '/') != depth )
  133. return false;
  134. return true;
  135. });
  136. //storage for found mods
  137. std::vector<std::string> foundMods;
  138. for(const auto & entry : list)
  139. {
  140. std::string name = entry.getName();
  141. name.erase(0, modDir.size()); //Remove path prefix
  142. if (!name.empty())
  143. foundMods.push_back(name);
  144. }
  145. return foundMods;
  146. }
  147. void CModHandler::loadMods(const std::string & path, const std::string & parent, const JsonNode & modSettings, bool enableMods)
  148. {
  149. for(const std::string & modName : getModList(path))
  150. loadOneMod(modName, parent, modSettings, enableMods);
  151. }
  152. void CModHandler::loadOneMod(std::string modName, const std::string & parent, const JsonNode & modSettings, bool enableMods)
  153. {
  154. boost::to_lower(modName);
  155. std::string modFullName = parent.empty() ? modName : parent + '.' + modName;
  156. if ( ModScope::isScopeReserved(modFullName))
  157. {
  158. logMod->error("Can not load mod %s - this name is reserved for internal use!", modFullName);
  159. return;
  160. }
  161. if(CResourceHandler::get("initial")->existsResource(CModInfo::getModFile(modFullName)))
  162. {
  163. CModInfo mod(modFullName, modSettings[modName], JsonNode(CModInfo::getModFile(modFullName)));
  164. if (!parent.empty()) // this is submod, add parent to dependencies
  165. mod.dependencies.insert(parent);
  166. allMods[modFullName] = mod;
  167. if (mod.isEnabled() && enableMods)
  168. activeMods.push_back(modFullName);
  169. loadMods(CModInfo::getModDir(modFullName) + '/', modFullName, modSettings[modName]["mods"], enableMods && mod.isEnabled());
  170. }
  171. }
  172. void CModHandler::loadMods(bool onlyEssential)
  173. {
  174. JsonNode modConfig;
  175. if(onlyEssential)
  176. {
  177. loadOneMod("vcmi", "", modConfig, true);//only vcmi and submods
  178. }
  179. else
  180. {
  181. modConfig = loadModSettings(JsonPath::builtin("config/modSettings.json"));
  182. loadMods("", "", modConfig["activeMods"], true);
  183. }
  184. coreMod = std::make_unique<CModInfo>(ModScope::scopeBuiltin(), modConfig[ModScope::scopeBuiltin()], JsonNode(JsonPath::builtin("config/gameConfig.json")));
  185. }
  186. std::vector<std::string> CModHandler::getAllMods()
  187. {
  188. std::vector<std::string> modlist;
  189. modlist.reserve(allMods.size());
  190. for (auto & entry : allMods)
  191. modlist.push_back(entry.first);
  192. return modlist;
  193. }
  194. std::vector<std::string> CModHandler::getActiveMods()
  195. {
  196. return activeMods;
  197. }
  198. const CModInfo & CModHandler::getModInfo(const TModID & modId) const
  199. {
  200. return allMods.at(modId);
  201. }
  202. static JsonNode genDefaultFS()
  203. {
  204. // default FS config for mods: directory "Content" that acts as H3 root directory
  205. JsonNode defaultFS;
  206. defaultFS[""].Vector().resize(2);
  207. defaultFS[""].Vector()[0]["type"].String() = "zip";
  208. defaultFS[""].Vector()[0]["path"].String() = "/Content.zip";
  209. defaultFS[""].Vector()[1]["type"].String() = "dir";
  210. defaultFS[""].Vector()[1]["path"].String() = "/Content";
  211. return defaultFS;
  212. }
  213. static ISimpleResourceLoader * genModFilesystem(const std::string & modName, const JsonNode & conf)
  214. {
  215. static const JsonNode defaultFS = genDefaultFS();
  216. if (!conf["filesystem"].isNull())
  217. return CResourceHandler::createFileSystem(CModInfo::getModDir(modName), conf["filesystem"]);
  218. else
  219. return CResourceHandler::createFileSystem(CModInfo::getModDir(modName), defaultFS);
  220. }
  221. static ui32 calculateModChecksum(const std::string & modName, ISimpleResourceLoader * filesystem)
  222. {
  223. boost::crc_32_type modChecksum;
  224. // first - add current VCMI version into checksum to force re-validation on VCMI updates
  225. modChecksum.process_bytes(reinterpret_cast<const void*>(GameConstants::VCMI_VERSION.data()), GameConstants::VCMI_VERSION.size());
  226. // second - add mod.json into checksum because filesystem does not contains this file
  227. // FIXME: remove workaround for core mod
  228. if (modName != ModScope::scopeBuiltin())
  229. {
  230. auto modConfFile = CModInfo::getModFile(modName);
  231. ui32 configChecksum = CResourceHandler::get("initial")->load(modConfFile)->calculateCRC32();
  232. modChecksum.process_bytes(reinterpret_cast<const void *>(&configChecksum), sizeof(configChecksum));
  233. }
  234. // third - add all detected text files from this mod into checksum
  235. auto files = filesystem->getFilteredFiles([](const ResourcePath & resID)
  236. {
  237. return (resID.getType() == EResType::TEXT || resID.getType() == EResType::JSON) &&
  238. ( boost::starts_with(resID.getName(), "DATA") || boost::starts_with(resID.getName(), "CONFIG"));
  239. });
  240. for (const ResourcePath & file : files)
  241. {
  242. ui32 fileChecksum = filesystem->load(file)->calculateCRC32();
  243. modChecksum.process_bytes(reinterpret_cast<const void *>(&fileChecksum), sizeof(fileChecksum));
  244. }
  245. return modChecksum.checksum();
  246. }
  247. void CModHandler::loadModFilesystems()
  248. {
  249. CGeneralTextHandler::detectInstallParameters();
  250. activeMods = validateAndSortDependencies(activeMods);
  251. coreMod->updateChecksum(calculateModChecksum(ModScope::scopeBuiltin(), CResourceHandler::get(ModScope::scopeBuiltin())));
  252. for(std::string & modName : activeMods)
  253. {
  254. CModInfo & mod = allMods[modName];
  255. CResourceHandler::addFilesystem("data", modName, genModFilesystem(modName, mod.config));
  256. }
  257. }
  258. TModID CModHandler::findResourceOrigin(const ResourcePath & name)
  259. {
  260. for(const auto & modID : boost::adaptors::reverse(activeMods))
  261. {
  262. if(CResourceHandler::get(modID)->existsResource(name))
  263. return modID;
  264. }
  265. if(CResourceHandler::get("core")->existsResource(name))
  266. return "core";
  267. if(CResourceHandler::get("mapEditor")->existsResource(name))
  268. return "core"; // Workaround for loading maps via map editor
  269. assert(0);
  270. return "";
  271. }
  272. std::string CModHandler::getModLanguage(const TModID& modId) const
  273. {
  274. if(modId == "core")
  275. return VLC->generaltexth->getInstalledLanguage();
  276. if(modId == "map")
  277. return VLC->generaltexth->getPreferredLanguage();
  278. return allMods.at(modId).baseLanguage;
  279. }
  280. std::set<TModID> CModHandler::getModDependencies(const TModID & modId, bool & isModFound) const
  281. {
  282. auto it = allMods.find(modId);
  283. isModFound = (it != allMods.end());
  284. if(isModFound)
  285. return it->second.dependencies;
  286. logMod->error("Mod not found: '%s'", modId);
  287. return {};
  288. }
  289. void CModHandler::initializeConfig()
  290. {
  291. VLC->settingsHandler->load(coreMod->config["settings"]);
  292. for(const TModID & modName : activeMods)
  293. {
  294. const auto & mod = allMods[modName];
  295. if (!mod.config["settings"].isNull())
  296. VLC->settingsHandler->load(mod.config["settings"]);
  297. }
  298. }
  299. CModVersion CModHandler::getModVersion(TModID modName) const
  300. {
  301. if (allMods.count(modName))
  302. return allMods.at(modName).getVerificationInfo().version;
  303. return {};
  304. }
  305. bool CModHandler::validateTranslations(TModID modName) const
  306. {
  307. bool result = true;
  308. const auto & mod = allMods.at(modName);
  309. {
  310. auto fileList = mod.config["translations"].convertTo<std::vector<std::string> >();
  311. JsonNode json = JsonUtils::assembleFromFiles(fileList);
  312. result |= VLC->generaltexth->validateTranslation(mod.baseLanguage, modName, json);
  313. }
  314. for(const auto & language : Languages::getLanguageList())
  315. {
  316. if (!language.hasTranslation)
  317. continue;
  318. if (mod.config[language.identifier].isNull())
  319. continue;
  320. if (mod.config[language.identifier]["skipValidation"].Bool())
  321. continue;
  322. auto fileList = mod.config[language.identifier]["translations"].convertTo<std::vector<std::string> >();
  323. JsonNode json = JsonUtils::assembleFromFiles(fileList);
  324. result |= VLC->generaltexth->validateTranslation(language.identifier, modName, json);
  325. }
  326. return result;
  327. }
  328. void CModHandler::loadTranslation(const TModID & modName)
  329. {
  330. const auto & mod = allMods[modName];
  331. std::string preferredLanguage = VLC->generaltexth->getPreferredLanguage();
  332. std::string modBaseLanguage = allMods[modName].baseLanguage;
  333. auto baseTranslationList = mod.config["translations"].convertTo<std::vector<std::string> >();
  334. auto extraTranslationList = mod.config[preferredLanguage]["translations"].convertTo<std::vector<std::string> >();
  335. JsonNode baseTranslation = JsonUtils::assembleFromFiles(baseTranslationList);
  336. JsonNode extraTranslation = JsonUtils::assembleFromFiles(extraTranslationList);
  337. VLC->generaltexth->loadTranslationOverrides(modBaseLanguage, modName, baseTranslation);
  338. VLC->generaltexth->loadTranslationOverrides(preferredLanguage, modName, extraTranslation);
  339. }
  340. void CModHandler::load()
  341. {
  342. CStopWatch totalTime;
  343. CStopWatch timer;
  344. logMod->info("\tInitializing content handler: %d ms", timer.getDiff());
  345. content->init();
  346. for(const TModID & modName : activeMods)
  347. {
  348. logMod->trace("Generating checksum for %s", modName);
  349. allMods[modName].updateChecksum(calculateModChecksum(modName, CResourceHandler::get(modName)));
  350. }
  351. // first - load virtual builtin mod that contains all data
  352. // TODO? move all data into real mods? RoE, AB, SoD, WoG
  353. content->preloadData(*coreMod);
  354. for(const TModID & modName : activeMods)
  355. content->preloadData(allMods[modName]);
  356. logMod->info("\tParsing mod data: %d ms", timer.getDiff());
  357. content->load(*coreMod);
  358. for(const TModID & modName : activeMods)
  359. content->load(allMods[modName]);
  360. #if SCRIPTING_ENABLED
  361. VLC->scriptHandler->performRegistration(VLC);//todo: this should be done before any other handlers load
  362. #endif
  363. content->loadCustom();
  364. for(const TModID & modName : activeMods)
  365. loadTranslation(modName);
  366. for(const TModID & modName : activeMods)
  367. if (!validateTranslations(modName))
  368. allMods[modName].validation = CModInfo::FAILED;
  369. logMod->info("\tLoading mod data: %d ms", timer.getDiff());
  370. VLC->creh->loadCrExpMod();
  371. VLC->identifiersHandler->finalize();
  372. logMod->info("\tResolving identifiers: %d ms", timer.getDiff());
  373. content->afterLoadFinalization();
  374. logMod->info("\tHandlers post-load finalization: %d ms ", timer.getDiff());
  375. logMod->info("\tAll game content loaded in %d ms", totalTime.getDiff());
  376. }
  377. void CModHandler::afterLoad(bool onlyEssential)
  378. {
  379. JsonNode modSettings;
  380. for (auto & modEntry : allMods)
  381. {
  382. std::string pointer = "/" + boost::algorithm::replace_all_copy(modEntry.first, ".", "/mods/");
  383. modSettings["activeMods"].resolvePointer(pointer) = modEntry.second.saveLocalData();
  384. }
  385. modSettings[ModScope::scopeBuiltin()] = coreMod->saveLocalData();
  386. modSettings[ModScope::scopeBuiltin()]["name"].String() = "Original game files";
  387. if(!onlyEssential)
  388. {
  389. std::fstream file(CResourceHandler::get()->getResourceName(ResourcePath("config/modSettings.json"))->c_str(), std::ofstream::out | std::ofstream::trunc);
  390. file << modSettings.toJson();
  391. }
  392. }
  393. void CModHandler::trySetActiveMods(const std::vector<std::pair<TModID, CModInfo::VerificationInfo>> & modList)
  394. {
  395. auto searchVerificationInfo = [&modList](const TModID & m) -> const CModInfo::VerificationInfo*
  396. {
  397. for(auto & i : modList)
  398. if(i.first == m)
  399. return &i.second;
  400. return nullptr;
  401. };
  402. std::vector<TModID> missingMods, excessiveMods;
  403. ModIncompatibility::ModListWithVersion missingModsResult;
  404. ModIncompatibility::ModList excessiveModsResult;
  405. for(const auto & m : activeMods)
  406. {
  407. if(searchVerificationInfo(m))
  408. continue;
  409. //TODO: support actual disabling of these mods
  410. if(getModInfo(m).checkModGameplayAffecting())
  411. excessiveMods.push_back(m);
  412. }
  413. for(const auto & infoPair : modList)
  414. {
  415. auto & remoteModId = infoPair.first;
  416. auto & remoteModInfo = infoPair.second;
  417. bool modAffectsGameplay = remoteModInfo.impactsGameplay;
  418. //parent mod affects gameplay if child affects too
  419. for(const auto & subInfoPair : modList)
  420. modAffectsGameplay |= (subInfoPair.second.impactsGameplay && subInfoPair.second.parent == remoteModId);
  421. if(!allMods.count(remoteModId))
  422. {
  423. if(modAffectsGameplay)
  424. missingMods.push_back(remoteModId); //mod is not installed
  425. continue;
  426. }
  427. auto & localModInfo = getModInfo(remoteModId).getVerificationInfo();
  428. modAffectsGameplay |= getModInfo(remoteModId).checkModGameplayAffecting();
  429. bool modVersionCompatible = localModInfo.version.isNull()
  430. || remoteModInfo.version.isNull()
  431. || localModInfo.version.compatible(remoteModInfo.version);
  432. bool modLocalyEnabled = vstd::contains(activeMods, remoteModId);
  433. if(modVersionCompatible && modAffectsGameplay && modLocalyEnabled)
  434. continue;
  435. if(modAffectsGameplay)
  436. missingMods.push_back(remoteModId); //incompatible mod impacts gameplay
  437. }
  438. //filter mods
  439. for(auto & m : missingMods)
  440. {
  441. if(auto * vInfo = searchVerificationInfo(m))
  442. {
  443. assert(vInfo->parent != m);
  444. if(!vInfo->parent.empty() && vstd::contains(missingMods, vInfo->parent))
  445. continue;
  446. missingModsResult.push_back({vInfo->name, vInfo->version.toString()});
  447. }
  448. }
  449. for(auto & m : excessiveMods)
  450. {
  451. auto & vInfo = getModInfo(m).getVerificationInfo();
  452. assert(vInfo.parent != m);
  453. if(!vInfo.parent.empty() && vstd::contains(excessiveMods, vInfo.parent))
  454. continue;
  455. excessiveModsResult.push_back(vInfo.name);
  456. }
  457. if(!missingModsResult.empty() || !excessiveModsResult.empty())
  458. throw ModIncompatibility(missingModsResult, excessiveModsResult);
  459. //TODO: support actual enabling of required mods
  460. }
  461. VCMI_LIB_NAMESPACE_END