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 "../MetaString.h"
  23. #include "../ScriptHandler.h"
  24. #include "../constants/StringConstants.h"
  25. #include "../filesystem/Filesystem.h"
  26. #include "../json/JsonUtils.h"
  27. #include "../spells/CSpellHandler.h"
  28. VCMI_LIB_NAMESPACE_BEGIN
  29. static JsonNode loadModSettings(const JsonPath & path)
  30. {
  31. if (CResourceHandler::get("local")->existsResource(ResourcePath(path)))
  32. {
  33. return JsonNode(path);
  34. }
  35. // Probably new install. Create initial configuration
  36. CResourceHandler::get("local")->createResource(path.getOriginalName() + ".json");
  37. return JsonNode();
  38. }
  39. CModHandler::CModHandler()
  40. : content(std::make_shared<CContentHandler>())
  41. , coreMod(std::make_unique<CModInfo>())
  42. {
  43. }
  44. CModHandler::~CModHandler() = default;
  45. // currentList is passed by value to get current list of depending mods
  46. bool CModHandler::hasCircularDependency(const TModID & modID, std::set<TModID> currentList) const
  47. {
  48. const CModInfo & mod = allMods.at(modID);
  49. // Mod already present? We found a loop
  50. if (vstd::contains(currentList, modID))
  51. {
  52. logMod->error("Error: Circular dependency detected! Printing dependency list:");
  53. logMod->error("\t%s -> ", mod.getVerificationInfo().name);
  54. return true;
  55. }
  56. currentList.insert(modID);
  57. // recursively check every dependency of this mod
  58. for(const TModID & dependency : mod.dependencies)
  59. {
  60. if (hasCircularDependency(dependency, currentList))
  61. {
  62. logMod->error("\t%s ->\n", mod.getVerificationInfo().name); // conflict detected, print dependency list
  63. return true;
  64. }
  65. }
  66. return false;
  67. }
  68. // Returned vector affects the resource loaders call order (see CFilesystemList::load).
  69. // The loaders call order matters when dependent mod overrides resources in its dependencies.
  70. std::vector <TModID> CModHandler::validateAndSortDependencies(std::vector <TModID> modsToResolve) const
  71. {
  72. // Topological sort algorithm.
  73. // TODO: Investigate possible ways to improve performance.
  74. boost::range::sort(modsToResolve); // Sort mods per name
  75. std::vector <TModID> sortedValidMods; // Vector keeps order of elements (LIFO)
  76. sortedValidMods.reserve(modsToResolve.size()); // push_back calls won't cause memory reallocation
  77. std::set <TModID> resolvedModIDs; // Use a set for validation for performance reason, but set does not keep order of elements
  78. // Mod is resolved if it has not dependencies or all its dependencies are already resolved
  79. auto isResolved = [&](const CModInfo & mod) -> bool
  80. {
  81. if(mod.dependencies.size() > resolvedModIDs.size())
  82. return false;
  83. for(const TModID & dependency : mod.dependencies)
  84. {
  85. if(!vstd::contains(resolvedModIDs, dependency))
  86. return false;
  87. }
  88. for(const TModID & conflict : mod.conflicts)
  89. {
  90. if(vstd::contains(resolvedModIDs, conflict))
  91. return false;
  92. }
  93. for(const TModID & reverseConflict : resolvedModIDs)
  94. {
  95. if (vstd::contains(allMods.at(reverseConflict).conflicts, mod.identifier))
  96. return false;
  97. }
  98. return true;
  99. };
  100. while(true)
  101. {
  102. std::set <TModID> resolvedOnCurrentTreeLevel;
  103. for(auto it = modsToResolve.begin(); it != modsToResolve.end();) // One iteration - one level of mods tree
  104. {
  105. if(isResolved(allMods.at(*it)))
  106. {
  107. resolvedOnCurrentTreeLevel.insert(*it); // Not to the resolvedModIDs, so current node childs will be resolved on the next iteration
  108. sortedValidMods.push_back(*it);
  109. it = modsToResolve.erase(it);
  110. continue;
  111. }
  112. it++;
  113. }
  114. if(!resolvedOnCurrentTreeLevel.empty())
  115. {
  116. resolvedModIDs.insert(resolvedOnCurrentTreeLevel.begin(), resolvedOnCurrentTreeLevel.end());
  117. continue;
  118. }
  119. // If there're no valid mods on the current mods tree level, no more mod can be resolved, should be end.
  120. break;
  121. }
  122. modLoadErrors = std::make_unique<MetaString>();
  123. auto addErrorMessage = [this](const std::string & textID, const std::string & brokenModID, const std::string & missingModID)
  124. {
  125. modLoadErrors->appendTextID(textID);
  126. if (allMods.count(brokenModID))
  127. modLoadErrors->replaceRawString(allMods.at(brokenModID).getVerificationInfo().name);
  128. else
  129. modLoadErrors->replaceRawString(brokenModID);
  130. if (allMods.count(missingModID))
  131. modLoadErrors->replaceRawString(allMods.at(missingModID).getVerificationInfo().name);
  132. else
  133. modLoadErrors->replaceRawString(missingModID);
  134. };
  135. // Left mods have unresolved dependencies, output all to log.
  136. for(const auto & brokenModID : modsToResolve)
  137. {
  138. const CModInfo & brokenMod = allMods.at(brokenModID);
  139. for(const TModID & dependency : brokenMod.dependencies)
  140. {
  141. if(!vstd::contains(resolvedModIDs, dependency) && brokenMod.config["modType"].String() != "Compatibility")
  142. addErrorMessage("vcmi.server.errors.modNoDependency", brokenModID, dependency);
  143. }
  144. for(const TModID & conflict : brokenMod.conflicts)
  145. {
  146. if(vstd::contains(resolvedModIDs, conflict))
  147. addErrorMessage("vcmi.server.errors.modConflict", brokenModID, conflict);
  148. }
  149. for(const TModID & reverseConflict : resolvedModIDs)
  150. {
  151. if (vstd::contains(allMods.at(reverseConflict).conflicts, brokenModID))
  152. addErrorMessage("vcmi.server.errors.modConflict", brokenModID, reverseConflict);
  153. }
  154. }
  155. return sortedValidMods;
  156. }
  157. std::vector<std::string> CModHandler::getModList(const std::string & path) const
  158. {
  159. std::string modDir = boost::to_upper_copy(path + "MODS/");
  160. size_t depth = boost::range::count(modDir, '/');
  161. auto list = CResourceHandler::get("initial")->getFilteredFiles([&](const ResourcePath & id) -> bool
  162. {
  163. if (id.getType() != EResType::DIRECTORY)
  164. return false;
  165. if (!boost::algorithm::starts_with(id.getName(), modDir))
  166. return false;
  167. if (boost::range::count(id.getName(), '/') != depth )
  168. return false;
  169. return true;
  170. });
  171. //storage for found mods
  172. std::vector<std::string> foundMods;
  173. for(const auto & entry : list)
  174. {
  175. std::string name = entry.getName();
  176. name.erase(0, modDir.size()); //Remove path prefix
  177. if (!name.empty())
  178. foundMods.push_back(name);
  179. }
  180. return foundMods;
  181. }
  182. void CModHandler::loadMods(const std::string & path, const std::string & parent, const JsonNode & modSettings, bool enableMods)
  183. {
  184. for(const std::string & modName : getModList(path))
  185. loadOneMod(modName, parent, modSettings, enableMods);
  186. }
  187. void CModHandler::loadOneMod(std::string modName, const std::string & parent, const JsonNode & modSettings, bool enableMods)
  188. {
  189. boost::to_lower(modName);
  190. std::string modFullName = parent.empty() ? modName : parent + '.' + modName;
  191. if ( ModScope::isScopeReserved(modFullName))
  192. {
  193. logMod->error("Can not load mod %s - this name is reserved for internal use!", modFullName);
  194. return;
  195. }
  196. if(CResourceHandler::get("initial")->existsResource(CModInfo::getModFile(modFullName)))
  197. {
  198. CModInfo mod(modFullName, modSettings[modName], JsonNode(CModInfo::getModFile(modFullName)));
  199. if (!parent.empty()) // this is submod, add parent to dependencies
  200. mod.dependencies.insert(parent);
  201. allMods[modFullName] = mod;
  202. if (mod.isEnabled() && enableMods)
  203. activeMods.push_back(modFullName);
  204. loadMods(CModInfo::getModDir(modFullName) + '/', modFullName, modSettings[modName]["mods"], enableMods && mod.isEnabled());
  205. }
  206. }
  207. void CModHandler::loadMods()
  208. {
  209. JsonNode modConfig;
  210. modConfig = loadModSettings(JsonPath::builtin("config/modSettings.json"));
  211. loadMods("", "", modConfig["activeMods"], true);
  212. coreMod = std::make_unique<CModInfo>(ModScope::scopeBuiltin(), modConfig[ModScope::scopeBuiltin()], JsonNode(JsonPath::builtin("config/gameConfig.json")));
  213. }
  214. std::vector<std::string> CModHandler::getAllMods() const
  215. {
  216. std::vector<std::string> modlist;
  217. modlist.reserve(allMods.size());
  218. for (auto & entry : allMods)
  219. modlist.push_back(entry.first);
  220. return modlist;
  221. }
  222. std::vector<std::string> CModHandler::getActiveMods() const
  223. {
  224. return activeMods;
  225. }
  226. std::string CModHandler::getModLoadErrors() const
  227. {
  228. return modLoadErrors->toString();
  229. }
  230. const CModInfo & CModHandler::getModInfo(const TModID & modId) const
  231. {
  232. return allMods.at(modId);
  233. }
  234. static JsonNode genDefaultFS()
  235. {
  236. // default FS config for mods: directory "Content" that acts as H3 root directory
  237. JsonNode defaultFS;
  238. defaultFS[""].Vector().resize(2);
  239. defaultFS[""].Vector()[0]["type"].String() = "zip";
  240. defaultFS[""].Vector()[0]["path"].String() = "/Content.zip";
  241. defaultFS[""].Vector()[1]["type"].String() = "dir";
  242. defaultFS[""].Vector()[1]["path"].String() = "/Content";
  243. return defaultFS;
  244. }
  245. static ISimpleResourceLoader * genModFilesystem(const std::string & modName, const JsonNode & conf)
  246. {
  247. static const JsonNode defaultFS = genDefaultFS();
  248. if (!conf["filesystem"].isNull())
  249. return CResourceHandler::createFileSystem(CModInfo::getModDir(modName), conf["filesystem"]);
  250. else
  251. return CResourceHandler::createFileSystem(CModInfo::getModDir(modName), defaultFS);
  252. }
  253. static ui32 calculateModChecksum(const std::string & modName, ISimpleResourceLoader * filesystem)
  254. {
  255. boost::crc_32_type modChecksum;
  256. // first - add current VCMI version into checksum to force re-validation on VCMI updates
  257. modChecksum.process_bytes(reinterpret_cast<const void*>(GameConstants::VCMI_VERSION.data()), GameConstants::VCMI_VERSION.size());
  258. // second - add mod.json into checksum because filesystem does not contains this file
  259. // FIXME: remove workaround for core mod
  260. if (modName != ModScope::scopeBuiltin())
  261. {
  262. auto modConfFile = CModInfo::getModFile(modName);
  263. ui32 configChecksum = CResourceHandler::get("initial")->load(modConfFile)->calculateCRC32();
  264. modChecksum.process_bytes(reinterpret_cast<const void *>(&configChecksum), sizeof(configChecksum));
  265. }
  266. // third - add all detected text files from this mod into checksum
  267. auto files = filesystem->getFilteredFiles([](const ResourcePath & resID)
  268. {
  269. return (resID.getType() == EResType::TEXT || resID.getType() == EResType::JSON) &&
  270. ( boost::starts_with(resID.getName(), "DATA") || boost::starts_with(resID.getName(), "CONFIG"));
  271. });
  272. for (const ResourcePath & file : files)
  273. {
  274. ui32 fileChecksum = filesystem->load(file)->calculateCRC32();
  275. modChecksum.process_bytes(reinterpret_cast<const void *>(&fileChecksum), sizeof(fileChecksum));
  276. }
  277. return modChecksum.checksum();
  278. }
  279. void CModHandler::loadModFilesystems()
  280. {
  281. CGeneralTextHandler::detectInstallParameters();
  282. activeMods = validateAndSortDependencies(activeMods);
  283. coreMod->updateChecksum(calculateModChecksum(ModScope::scopeBuiltin(), CResourceHandler::get(ModScope::scopeBuiltin())));
  284. for(std::string & modName : activeMods)
  285. {
  286. CModInfo & mod = allMods[modName];
  287. CResourceHandler::addFilesystem("data", modName, genModFilesystem(modName, mod.config));
  288. }
  289. }
  290. TModID CModHandler::findResourceOrigin(const ResourcePath & name) const
  291. {
  292. try
  293. {
  294. for(const auto & modID : boost::adaptors::reverse(activeMods))
  295. {
  296. if(CResourceHandler::get(modID)->existsResource(name))
  297. return modID;
  298. }
  299. if(CResourceHandler::get("core")->existsResource(name))
  300. return "core";
  301. if(CResourceHandler::get("mapEditor")->existsResource(name))
  302. return "core"; // Workaround for loading maps via map editor
  303. }
  304. catch( const std::out_of_range & e)
  305. {
  306. // no-op
  307. }
  308. throw std::runtime_error("Resource with name " + name.getName() + " and type " + EResTypeHelper::getEResTypeAsString(name.getType()) + " wasn't found.");
  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.toString();
  429. }
  430. }
  431. VCMI_LIB_NAMESPACE_END