CModHandler.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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.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.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.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. coreMod->name = "Original game files";
  186. }
  187. std::vector<std::string> CModHandler::getAllMods()
  188. {
  189. std::vector<std::string> modlist;
  190. modlist.reserve(allMods.size());
  191. for (auto & entry : allMods)
  192. modlist.push_back(entry.first);
  193. return modlist;
  194. }
  195. std::vector<std::string> CModHandler::getActiveMods()
  196. {
  197. return activeMods;
  198. }
  199. const CModInfo & CModHandler::getModInfo(const TModID & modId) const
  200. {
  201. return allMods.at(modId);
  202. }
  203. static JsonNode genDefaultFS()
  204. {
  205. // default FS config for mods: directory "Content" that acts as H3 root directory
  206. JsonNode defaultFS;
  207. defaultFS[""].Vector().resize(2);
  208. defaultFS[""].Vector()[0]["type"].String() = "zip";
  209. defaultFS[""].Vector()[0]["path"].String() = "/Content.zip";
  210. defaultFS[""].Vector()[1]["type"].String() = "dir";
  211. defaultFS[""].Vector()[1]["path"].String() = "/Content";
  212. return defaultFS;
  213. }
  214. static ISimpleResourceLoader * genModFilesystem(const std::string & modName, const JsonNode & conf)
  215. {
  216. static const JsonNode defaultFS = genDefaultFS();
  217. if (!conf["filesystem"].isNull())
  218. return CResourceHandler::createFileSystem(CModInfo::getModDir(modName), conf["filesystem"]);
  219. else
  220. return CResourceHandler::createFileSystem(CModInfo::getModDir(modName), defaultFS);
  221. }
  222. static ui32 calculateModChecksum(const std::string & modName, ISimpleResourceLoader * filesystem)
  223. {
  224. boost::crc_32_type modChecksum;
  225. // first - add current VCMI version into checksum to force re-validation on VCMI updates
  226. modChecksum.process_bytes(reinterpret_cast<const void*>(GameConstants::VCMI_VERSION.data()), GameConstants::VCMI_VERSION.size());
  227. // second - add mod.json into checksum because filesystem does not contains this file
  228. // FIXME: remove workaround for core mod
  229. if (modName != ModScope::scopeBuiltin())
  230. {
  231. auto modConfFile = CModInfo::getModFile(modName);
  232. ui32 configChecksum = CResourceHandler::get("initial")->load(modConfFile)->calculateCRC32();
  233. modChecksum.process_bytes(reinterpret_cast<const void *>(&configChecksum), sizeof(configChecksum));
  234. }
  235. // third - add all detected text files from this mod into checksum
  236. auto files = filesystem->getFilteredFiles([](const ResourcePath & resID)
  237. {
  238. return (resID.getType() == EResType::TEXT || resID.getType() == EResType::JSON) &&
  239. ( boost::starts_with(resID.getName(), "DATA") || boost::starts_with(resID.getName(), "CONFIG"));
  240. });
  241. for (const ResourcePath & file : files)
  242. {
  243. ui32 fileChecksum = filesystem->load(file)->calculateCRC32();
  244. modChecksum.process_bytes(reinterpret_cast<const void *>(&fileChecksum), sizeof(fileChecksum));
  245. }
  246. return modChecksum.checksum();
  247. }
  248. void CModHandler::loadModFilesystems()
  249. {
  250. CGeneralTextHandler::detectInstallParameters();
  251. activeMods = validateAndSortDependencies(activeMods);
  252. coreMod->updateChecksum(calculateModChecksum(ModScope::scopeBuiltin(), CResourceHandler::get(ModScope::scopeBuiltin())));
  253. for(std::string & modName : activeMods)
  254. {
  255. CModInfo & mod = allMods[modName];
  256. CResourceHandler::addFilesystem("data", modName, genModFilesystem(modName, mod.config));
  257. }
  258. }
  259. TModID CModHandler::findResourceOrigin(const ResourcePath & name)
  260. {
  261. for(const auto & modID : boost::adaptors::reverse(activeMods))
  262. {
  263. if(CResourceHandler::get(modID)->existsResource(name))
  264. return modID;
  265. }
  266. if(CResourceHandler::get("core")->existsResource(name))
  267. return "core";
  268. if(CResourceHandler::get("mapEditor")->existsResource(name))
  269. return "core"; // Workaround for loading maps via map editor
  270. assert(0);
  271. return "";
  272. }
  273. std::string CModHandler::getModLanguage(const TModID& modId) const
  274. {
  275. if ( modId == "core")
  276. return VLC->generaltexth->getInstalledLanguage();
  277. return allMods.at(modId).baseLanguage;
  278. }
  279. std::set<TModID> CModHandler::getModDependencies(const TModID & modId, bool & isModFound) const
  280. {
  281. auto it = allMods.find(modId);
  282. isModFound = (it != allMods.end());
  283. if(isModFound)
  284. return it->second.dependencies;
  285. logMod->error("Mod not found: '%s'", modId);
  286. return {};
  287. }
  288. void CModHandler::initializeConfig()
  289. {
  290. VLC->settingsHandler->load(coreMod->config["settings"]);
  291. for(const TModID & modName : activeMods)
  292. {
  293. const auto & mod = allMods[modName];
  294. if (!mod.config["settings"].isNull())
  295. VLC->settingsHandler->load(mod.config["settings"]);
  296. }
  297. }
  298. CModVersion CModHandler::getModVersion(TModID modName) const
  299. {
  300. if (allMods.count(modName))
  301. return allMods.at(modName).version;
  302. return {};
  303. }
  304. bool CModHandler::validateTranslations(TModID modName) const
  305. {
  306. bool result = true;
  307. const auto & mod = allMods.at(modName);
  308. {
  309. auto fileList = mod.config["translations"].convertTo<std::vector<std::string> >();
  310. JsonNode json = JsonUtils::assembleFromFiles(fileList);
  311. result |= VLC->generaltexth->validateTranslation(mod.baseLanguage, modName, json);
  312. }
  313. for(const auto & language : Languages::getLanguageList())
  314. {
  315. if (!language.hasTranslation)
  316. continue;
  317. if (mod.config[language.identifier].isNull())
  318. continue;
  319. if (mod.config[language.identifier]["skipValidation"].Bool())
  320. continue;
  321. auto fileList = mod.config[language.identifier]["translations"].convertTo<std::vector<std::string> >();
  322. JsonNode json = JsonUtils::assembleFromFiles(fileList);
  323. result |= VLC->generaltexth->validateTranslation(language.identifier, modName, json);
  324. }
  325. return result;
  326. }
  327. void CModHandler::loadTranslation(const TModID & modName)
  328. {
  329. const auto & mod = allMods[modName];
  330. std::string preferredLanguage = VLC->generaltexth->getPreferredLanguage();
  331. std::string modBaseLanguage = allMods[modName].baseLanguage;
  332. auto baseTranslationList = mod.config["translations"].convertTo<std::vector<std::string> >();
  333. auto extraTranslationList = mod.config[preferredLanguage]["translations"].convertTo<std::vector<std::string> >();
  334. JsonNode baseTranslation = JsonUtils::assembleFromFiles(baseTranslationList);
  335. JsonNode extraTranslation = JsonUtils::assembleFromFiles(extraTranslationList);
  336. VLC->generaltexth->loadTranslationOverrides(modBaseLanguage, modName, baseTranslation);
  337. VLC->generaltexth->loadTranslationOverrides(preferredLanguage, modName, extraTranslation);
  338. }
  339. void CModHandler::load()
  340. {
  341. CStopWatch totalTime;
  342. CStopWatch timer;
  343. logMod->info("\tInitializing content handler: %d ms", timer.getDiff());
  344. content->init();
  345. for(const TModID & modName : activeMods)
  346. {
  347. logMod->trace("Generating checksum for %s", modName);
  348. allMods[modName].updateChecksum(calculateModChecksum(modName, CResourceHandler::get(modName)));
  349. }
  350. // first - load virtual builtin mod that contains all data
  351. // TODO? move all data into real mods? RoE, AB, SoD, WoG
  352. content->preloadData(*coreMod);
  353. for(const TModID & modName : activeMods)
  354. content->preloadData(allMods[modName]);
  355. logMod->info("\tParsing mod data: %d ms", timer.getDiff());
  356. content->load(*coreMod);
  357. for(const TModID & modName : activeMods)
  358. content->load(allMods[modName]);
  359. #if SCRIPTING_ENABLED
  360. VLC->scriptHandler->performRegistration(VLC);//todo: this should be done before any other handlers load
  361. #endif
  362. content->loadCustom();
  363. for(const TModID & modName : activeMods)
  364. loadTranslation(modName);
  365. for(const TModID & modName : activeMods)
  366. if (!validateTranslations(modName))
  367. allMods[modName].validation = CModInfo::FAILED;
  368. logMod->info("\tLoading mod data: %d ms", timer.getDiff());
  369. VLC->creh->loadCrExpMod();
  370. VLC->identifiersHandler->finalize();
  371. logMod->info("\tResolving identifiers: %d ms", timer.getDiff());
  372. content->afterLoadFinalization();
  373. logMod->info("\tHandlers post-load finalization: %d ms ", timer.getDiff());
  374. logMod->info("\tAll game content loaded in %d ms", totalTime.getDiff());
  375. }
  376. void CModHandler::afterLoad(bool onlyEssential)
  377. {
  378. JsonNode modSettings;
  379. for (auto & modEntry : allMods)
  380. {
  381. std::string pointer = "/" + boost::algorithm::replace_all_copy(modEntry.first, ".", "/mods/");
  382. modSettings["activeMods"].resolvePointer(pointer) = modEntry.second.saveLocalData();
  383. }
  384. modSettings[ModScope::scopeBuiltin()] = coreMod->saveLocalData();
  385. if(!onlyEssential)
  386. {
  387. std::fstream file(CResourceHandler::get()->getResourceName(ResourcePath("config/modSettings.json"))->c_str(), std::ofstream::out | std::ofstream::trunc);
  388. file << modSettings.toJson();
  389. }
  390. }
  391. void CModHandler::trySetActiveMods(std::vector<TModID> saveActiveMods, const std::map<TModID, CModVersion> & modList)
  392. {
  393. std::vector<TModID> newActiveMods;
  394. ModIncompatibility::ModList missingMods;
  395. for(const auto & m : activeMods)
  396. {
  397. if (vstd::contains(saveActiveMods, m))
  398. continue;
  399. auto & modInfo = allMods.at(m);
  400. if(modInfo.checkModGameplayAffecting())
  401. missingMods.emplace_back(m, modInfo.version.toString());
  402. }
  403. for(const auto & m : saveActiveMods)
  404. {
  405. const CModVersion & mver = modList.at(m);
  406. if (allMods.count(m) == 0)
  407. {
  408. missingMods.emplace_back(m, mver.toString());
  409. continue;
  410. }
  411. auto & modInfo = allMods.at(m);
  412. bool modAffectsGameplay = modInfo.checkModGameplayAffecting();
  413. bool modVersionCompatible = modInfo.version.isNull() || mver.isNull() || modInfo.version.compatible(mver);
  414. bool modEnabledLocally = vstd::contains(activeMods, m);
  415. bool modCanBeEnabled = modEnabledLocally && modVersionCompatible;
  416. allMods[m].setEnabled(modCanBeEnabled);
  417. if (modCanBeEnabled)
  418. newActiveMods.push_back(m);
  419. if (!modCanBeEnabled && modAffectsGameplay)
  420. missingMods.emplace_back(m, mver.toString());
  421. }
  422. std::swap(activeMods, newActiveMods);
  423. }
  424. VCMI_LIB_NAMESPACE_END