CModHandler.cpp 16 KB

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