ModManager.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  1. /*
  2. * ModManager.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 "ModManager.h"
  12. #include "ModDescription.h"
  13. #include "ModScope.h"
  14. #include "../constants/StringConstants.h"
  15. #include "../filesystem/Filesystem.h"
  16. #include "../json/JsonNode.h"
  17. #include "../texts/CGeneralTextHandler.h"
  18. VCMI_LIB_NAMESPACE_BEGIN
  19. static std::string getModDirectory(const TModID & modName)
  20. {
  21. std::string result = modName;
  22. boost::to_upper(result);
  23. boost::algorithm::replace_all(result, ".", "/MODS/");
  24. return "MODS/" + result;
  25. }
  26. static std::string getModSettingsDirectory(const TModID & modName)
  27. {
  28. return getModDirectory(modName) + "/MODS/";
  29. }
  30. static JsonPath getModDescriptionFile(const TModID & modName)
  31. {
  32. return JsonPath::builtin(getModDirectory(modName) + "/mod");
  33. }
  34. ModsState::ModsState()
  35. {
  36. modList.push_back(ModScope::scopeBuiltin());
  37. std::vector<TModID> testLocations = scanModsDirectory("MODS/");
  38. while(!testLocations.empty())
  39. {
  40. std::string target = testLocations.back();
  41. testLocations.pop_back();
  42. modList.push_back(boost::algorithm::to_lower_copy(target));
  43. for(const auto & submod : scanModsDirectory(getModSettingsDirectory(target)))
  44. testLocations.push_back(target + '.' + submod);
  45. }
  46. }
  47. TModList ModsState::getInstalledMods() const
  48. {
  49. return modList;
  50. }
  51. uint32_t ModsState::computeChecksum(const TModID & modName) const
  52. {
  53. boost::crc_32_type modChecksum;
  54. // first - add current VCMI version into checksum to force re-validation on VCMI updates
  55. modChecksum.process_bytes(static_cast<const void*>(GameConstants::VCMI_VERSION.data()), GameConstants::VCMI_VERSION.size());
  56. // second - add mod.json into checksum because filesystem does not contains this file
  57. // FIXME: remove workaround for core mod
  58. if (modName != ModScope::scopeBuiltin())
  59. {
  60. auto modConfFile = getModDescriptionFile(modName);
  61. ui32 configChecksum = CResourceHandler::get("initial")->load(modConfFile)->calculateCRC32();
  62. modChecksum.process_bytes(static_cast<const void *>(&configChecksum), sizeof(configChecksum));
  63. }
  64. // third - add all detected text files from this mod into checksum
  65. const auto & filesystem = CResourceHandler::get(modName);
  66. auto files = filesystem->getFilteredFiles([](const ResourcePath & resID)
  67. {
  68. return resID.getType() == EResType::JSON && boost::starts_with(resID.getName(), "CONFIG");
  69. });
  70. for (const ResourcePath & file : files)
  71. {
  72. ui32 fileChecksum = filesystem->load(file)->calculateCRC32();
  73. modChecksum.process_bytes(static_cast<const void *>(&fileChecksum), sizeof(fileChecksum));
  74. }
  75. return modChecksum.checksum();
  76. }
  77. double ModsState::getInstalledModSizeMegabytes(const TModID & modName) const
  78. {
  79. ResourcePath resDir(getModDirectory(modName), EResType::DIRECTORY);
  80. std::string path = CResourceHandler::get()->getResourceName(resDir)->string();
  81. size_t sizeBytes = 0;
  82. for(boost::filesystem::recursive_directory_iterator it(path); it != boost::filesystem::recursive_directory_iterator(); ++it)
  83. {
  84. if(!boost::filesystem::is_directory(*it))
  85. sizeBytes += boost::filesystem::file_size(*it);
  86. }
  87. double sizeMegabytes = sizeBytes / double(1024*1024);
  88. return sizeMegabytes;
  89. }
  90. std::vector<TModID> ModsState::scanModsDirectory(const std::string & modDir) const
  91. {
  92. size_t depth = boost::range::count(modDir, '/');
  93. const auto & modScanFilter = [&](const ResourcePath & id) -> bool
  94. {
  95. if(id.getType() != EResType::DIRECTORY)
  96. return false;
  97. if(!boost::algorithm::starts_with(id.getName(), modDir))
  98. return false;
  99. if(boost::range::count(id.getName(), '/') != depth)
  100. return false;
  101. return true;
  102. };
  103. auto list = CResourceHandler::get("initial")->getFilteredFiles(modScanFilter);
  104. //storage for found mods
  105. std::vector<TModID> foundMods;
  106. for(const auto & entry : list)
  107. {
  108. std::string name = entry.getName();
  109. name.erase(0, modDir.size()); //Remove path prefix
  110. if(name.empty())
  111. continue;
  112. if(name.find('.') != std::string::npos)
  113. continue;
  114. if (ModScope::isScopeReserved(boost::to_lower_copy(name)))
  115. continue;
  116. if(!CResourceHandler::get("initial")->existsResource(JsonPath::builtin(entry.getName() + "/MOD")))
  117. continue;
  118. foundMods.push_back(name);
  119. }
  120. return foundMods;
  121. }
  122. ///////////////////////////////////////////////////////////////////////////////
  123. static JsonNode loadModSettings(const JsonPath & path)
  124. {
  125. if(CResourceHandler::get("local")->existsResource(ResourcePath(path)))
  126. {
  127. return JsonNode(path);
  128. }
  129. // Probably new install. Create initial configuration
  130. CResourceHandler::get("local")->createResource(path.getOriginalName() + ".json");
  131. return JsonNode();
  132. }
  133. ModsPresetState::ModsPresetState()
  134. {
  135. modConfig = loadModSettings(JsonPath::builtin("config/modSettings.json"));
  136. if(modConfig["presets"].isNull())
  137. {
  138. modConfig["activePreset"] = JsonNode("default");
  139. if(modConfig["activeMods"].isNull())
  140. createInitialPreset(); // new install
  141. else
  142. importInitialPreset(); // 1.5 format import
  143. }
  144. }
  145. void ModsPresetState::createInitialPreset()
  146. {
  147. // TODO: scan mods directory for all its content? Probably unnecessary since this looks like new install, but who knows?
  148. modConfig["presets"]["default"]["mods"].Vector().emplace_back("vcmi");
  149. }
  150. void ModsPresetState::importInitialPreset()
  151. {
  152. JsonNode preset;
  153. for(const auto & mod : modConfig["activeMods"].Struct())
  154. {
  155. if(mod.second["active"].Bool())
  156. preset["mods"].Vector().emplace_back(mod.first);
  157. for(const auto & submod : mod.second["mods"].Struct())
  158. preset["settings"][mod.first][submod.first] = submod.second["active"];
  159. }
  160. modConfig["presets"]["default"] = preset;
  161. }
  162. const JsonNode & ModsPresetState::getActivePresetConfig() const
  163. {
  164. const std::string & currentPresetName = modConfig["activePreset"].String();
  165. const JsonNode & currentPreset = modConfig["presets"][currentPresetName];
  166. return currentPreset;
  167. }
  168. TModList ModsPresetState::getActiveRootMods() const
  169. {
  170. const JsonNode & modsToActivateJson = getActivePresetConfig()["mods"];
  171. auto modsToActivate = modsToActivateJson.convertTo<std::vector<TModID>>();
  172. modsToActivate.push_back(ModScope::scopeBuiltin());
  173. return modsToActivate;
  174. }
  175. std::map<TModID, bool> ModsPresetState::getModSettings(const TModID & modID) const
  176. {
  177. const JsonNode & modSettingsJson = getActivePresetConfig()["settings"][modID];
  178. auto modSettings = modSettingsJson.convertTo<std::map<TModID, bool>>();
  179. return modSettings;
  180. }
  181. std::optional<uint32_t> ModsPresetState::getValidatedChecksum(const TModID & modName) const
  182. {
  183. const JsonNode & node = modConfig["validatedMods"][modName];
  184. if (node.isNull())
  185. return std::nullopt;
  186. else
  187. return node.Integer();
  188. }
  189. void ModsPresetState::setModActive(const TModID & modID, bool isActive)
  190. {
  191. size_t dotPos = modID.find('.');
  192. if(dotPos != std::string::npos)
  193. {
  194. std::string rootMod = modID.substr(0, dotPos);
  195. std::string settingID = modID.substr(dotPos + 1);
  196. setSettingActive(rootMod, settingID, isActive);
  197. }
  198. else
  199. {
  200. if (isActive)
  201. addRootMod(modID);
  202. else
  203. eraseRootMod(modID);
  204. }
  205. }
  206. void ModsPresetState::addRootMod(const TModID & modName)
  207. {
  208. const std::string & currentPresetName = modConfig["activePreset"].String();
  209. JsonNode & currentPreset = modConfig["presets"][currentPresetName];
  210. if (!vstd::contains(currentPreset["mods"].Vector(), JsonNode(modName)))
  211. currentPreset["mods"].Vector().emplace_back(modName);
  212. }
  213. void ModsPresetState::setSettingActive(const TModID & modName, const TModID & settingName, bool isActive)
  214. {
  215. const std::string & currentPresetName = modConfig["activePreset"].String();
  216. JsonNode & currentPreset = modConfig["presets"][currentPresetName];
  217. currentPreset["settings"][modName][settingName].Bool() = isActive;
  218. }
  219. void ModsPresetState::eraseRootMod(const TModID & modName)
  220. {
  221. const std::string & currentPresetName = modConfig["activePreset"].String();
  222. JsonNode & currentPreset = modConfig["presets"][currentPresetName];
  223. vstd::erase(currentPreset["mods"].Vector(), JsonNode(modName));
  224. }
  225. void ModsPresetState::eraseModSetting(const TModID & modName, const TModID & settingName)
  226. {
  227. const std::string & currentPresetName = modConfig["activePreset"].String();
  228. JsonNode & currentPreset = modConfig["presets"][currentPresetName];
  229. currentPreset["settings"][modName].Struct().erase(modName);
  230. }
  231. std::vector<TModID> ModsPresetState::getActiveMods() const
  232. {
  233. TModList activeRootMods = getActiveRootMods();
  234. TModList allActiveMods;
  235. for(const auto & activeMod : activeRootMods)
  236. {
  237. allActiveMods.push_back(activeMod);
  238. for(const auto & submod : getModSettings(activeMod))
  239. if(submod.second)
  240. allActiveMods.push_back(activeMod + '.' + submod.first);
  241. }
  242. return allActiveMods;
  243. }
  244. void ModsPresetState::setValidatedChecksum(const TModID & modName, std::optional<uint32_t> value)
  245. {
  246. if (value.has_value())
  247. modConfig["validatedMods"][modName].Integer() = *value;
  248. else
  249. modConfig["validatedMods"].Struct().erase(modName);
  250. }
  251. void ModsPresetState::saveConfigurationState() const
  252. {
  253. std::fstream file(CResourceHandler::get()->getResourceName(ResourcePath("config/modSettings.json"))->c_str(), std::ofstream::out | std::ofstream::trunc);
  254. file << modConfig.toCompactString();
  255. }
  256. ModsStorage::ModsStorage(const std::vector<TModID> & modsToLoad, const JsonNode & repositoryList)
  257. {
  258. JsonNode coreModConfig(JsonPath::builtin("config/gameConfig.json"));
  259. coreModConfig.setModScope(ModScope::scopeBuiltin());
  260. mods.try_emplace(ModScope::scopeBuiltin(), ModScope::scopeBuiltin(), coreModConfig, JsonNode());
  261. for(auto modID : modsToLoad)
  262. {
  263. if(ModScope::isScopeReserved(modID))
  264. continue;
  265. JsonNode modConfig(getModDescriptionFile(modID));
  266. modConfig.setModScope(modID);
  267. if(modConfig["modType"].isNull())
  268. {
  269. logMod->error("Can not load mod %s - invalid mod config file!", modID);
  270. continue;
  271. }
  272. mods.try_emplace(modID, modID, modConfig, repositoryList[modID]);
  273. }
  274. for(const auto & mod : repositoryList.Struct())
  275. {
  276. if (vstd::contains(modsToLoad, mod.first))
  277. continue;
  278. if (mod.second["modType"].isNull() || mod.second["name"].isNull())
  279. continue;
  280. mods.try_emplace(mod.first, mod.first, JsonNode(), mod.second);
  281. }
  282. }
  283. const ModDescription & ModsStorage::getMod(const TModID & fullID) const
  284. {
  285. return mods.at(fullID);
  286. }
  287. TModList ModsStorage::getAllMods() const
  288. {
  289. TModList result;
  290. for (const auto & mod : mods)
  291. result.push_back(mod.first);
  292. return result;
  293. }
  294. ModManager::ModManager()
  295. :ModManager(JsonNode())
  296. {
  297. }
  298. ModManager::ModManager(const JsonNode & repositoryList)
  299. : modsState(std::make_unique<ModsState>())
  300. , modsPreset(std::make_unique<ModsPresetState>())
  301. {
  302. //TODO: load only active mods & all their submods in game mode?
  303. modsStorage = std::make_unique<ModsStorage>(modsState->getInstalledMods(), repositoryList);
  304. eraseMissingModsFromPreset();
  305. addNewModsToPreset();
  306. std::vector<TModID> desiredModList = modsPreset->getActiveMods();
  307. depedencyResolver = std::make_unique<ModDependenciesResolver>(desiredModList, *modsStorage);
  308. }
  309. ModManager::~ModManager() = default;
  310. const ModDescription & ModManager::getModDescription(const TModID & modID) const
  311. {
  312. assert(boost::to_lower_copy(modID) == modID);
  313. return modsStorage->getMod(modID);
  314. }
  315. bool ModManager::isModActive(const TModID & modID) const
  316. {
  317. return vstd::contains(getActiveMods(), modID);
  318. }
  319. const TModList & ModManager::getActiveMods() const
  320. {
  321. return depedencyResolver->getActiveMods();
  322. }
  323. uint32_t ModManager::computeChecksum(const TModID & modName) const
  324. {
  325. return modsState->computeChecksum(modName);
  326. }
  327. std::optional<uint32_t> ModManager::getValidatedChecksum(const TModID & modName) const
  328. {
  329. return modsPreset->getValidatedChecksum(modName);
  330. }
  331. void ModManager::setValidatedChecksum(const TModID & modName, std::optional<uint32_t> value)
  332. {
  333. modsPreset->setValidatedChecksum(modName, value);
  334. }
  335. void ModManager::saveConfigurationState() const
  336. {
  337. modsPreset->saveConfigurationState();
  338. }
  339. TModList ModManager::getAllMods() const
  340. {
  341. return modsStorage->getAllMods();
  342. }
  343. double ModManager::getInstalledModSizeMegabytes(const TModID & modName) const
  344. {
  345. return modsState->getInstalledModSizeMegabytes(modName);
  346. }
  347. void ModManager::eraseMissingModsFromPreset()
  348. {
  349. const TModList & installedMods = modsState->getInstalledMods();
  350. const TModList & rootMods = modsPreset->getActiveRootMods();
  351. for(const auto & rootMod : rootMods)
  352. {
  353. if(!vstd::contains(installedMods, rootMod))
  354. {
  355. modsPreset->eraseRootMod(rootMod);
  356. continue;
  357. }
  358. const auto & modSettings = modsPreset->getModSettings(rootMod);
  359. for(const auto & modSetting : modSettings)
  360. {
  361. TModID fullModID = rootMod + '.' + modSetting.first;
  362. if(!vstd::contains(installedMods, fullModID))
  363. {
  364. modsPreset->eraseModSetting(rootMod, modSetting.first);
  365. continue;
  366. }
  367. }
  368. }
  369. }
  370. void ModManager::addNewModsToPreset()
  371. {
  372. const TModList & installedMods = modsState->getInstalledMods();
  373. for(const auto & modID : installedMods)
  374. {
  375. size_t dotPos = modID.find('.');
  376. if(dotPos == std::string::npos)
  377. continue; // only look up submods aka mod settings
  378. std::string rootMod = modID.substr(0, dotPos);
  379. std::string settingID = modID.substr(dotPos + 1);
  380. const auto & modSettings = modsPreset->getModSettings(rootMod);
  381. if (!modSettings.count(settingID))
  382. modsPreset->setSettingActive(rootMod, settingID, modsStorage->getMod(modID).keepDisabled());
  383. }
  384. }
  385. TModList ModManager::collectDependenciesRecursive(const TModID & modID) const
  386. {
  387. TModList result;
  388. TModList toTest;
  389. toTest.push_back(modID);
  390. while (!toTest.empty())
  391. {
  392. TModID currentModID = toTest.back();
  393. const auto & currentMod = getModDescription(currentModID);
  394. toTest.pop_back();
  395. result.push_back(currentModID);
  396. if (!currentMod.isInstalled())
  397. return {}; // failure. TODO: better handling?
  398. for (const auto & dependency : currentMod.getDependencies())
  399. {
  400. if (!vstd::contains(result, dependency))
  401. toTest.push_back(dependency);
  402. }
  403. }
  404. return result;
  405. }
  406. void ModManager::tryEnableMod(const TModID & modName)
  407. {
  408. auto requiredActiveMods = collectDependenciesRecursive(modName);
  409. auto additionalActiveMods = getActiveMods();
  410. assert(!vstd::contains(additionalActiveMods, modName));
  411. assert(vstd::contains(requiredActiveMods, modName));
  412. ModDependenciesResolver testResolver(requiredActiveMods, *modsStorage);
  413. assert(testResolver.getBrokenMods().empty());
  414. assert(vstd::contains(testResolver.getActiveMods(), modName));
  415. testResolver.tryAddMods(additionalActiveMods, *modsStorage);
  416. if (!vstd::contains(testResolver.getActiveMods(), modName))
  417. {
  418. // FIXME: report?
  419. return;
  420. }
  421. updatePreset(testResolver);
  422. }
  423. void ModManager::tryDisableMod(const TModID & modName)
  424. {
  425. auto desiredActiveMods = getActiveMods();
  426. assert(vstd::contains(desiredActiveMods, modName));
  427. vstd::erase(desiredActiveMods, modName);
  428. ModDependenciesResolver testResolver(desiredActiveMods, *modsStorage);
  429. if (vstd::contains(testResolver.getActiveMods(), modName))
  430. {
  431. // FIXME: report?
  432. return;
  433. }
  434. updatePreset(testResolver);
  435. }
  436. void ModManager::updatePreset(const ModDependenciesResolver & testResolver)
  437. {
  438. const auto & newActiveMods = testResolver.getActiveMods();
  439. const auto & newBrokenMods = testResolver.getBrokenMods();
  440. for (const auto & modID : newActiveMods)
  441. {
  442. assert(vstd::contains(modsState->getInstalledMods(), modID));
  443. modsPreset->setModActive(modID, true);
  444. }
  445. for (const auto & modID : newBrokenMods)
  446. modsPreset->setModActive(modID, false);
  447. std::vector<TModID> desiredModList = modsPreset->getActiveMods();
  448. depedencyResolver = std::make_unique<ModDependenciesResolver>(desiredModList, *modsStorage);
  449. modsPreset->saveConfigurationState();
  450. }
  451. ModDependenciesResolver::ModDependenciesResolver(const TModList & modsToResolve, const ModsStorage & storage)
  452. {
  453. tryAddMods(modsToResolve, storage);
  454. }
  455. const TModList & ModDependenciesResolver::getActiveMods() const
  456. {
  457. return activeMods;
  458. }
  459. const TModList & ModDependenciesResolver::getBrokenMods() const
  460. {
  461. return brokenMods;
  462. }
  463. void ModDependenciesResolver::tryAddMods(TModList modsToResolve, const ModsStorage & storage)
  464. {
  465. // Topological sort algorithm.
  466. boost::range::sort(modsToResolve); // Sort mods per name
  467. std::vector<TModID> sortedValidMods(activeMods.begin(), activeMods.end()); // Vector keeps order of elements (LIFO)
  468. std::set<TModID> resolvedModIDs(activeMods.begin(), activeMods.end()); // Use a set for validation for performance reason, but set does not keep order of elements
  469. std::set<TModID> notResolvedModIDs(modsToResolve.begin(), modsToResolve.end()); // Use a set for validation for performance reason
  470. // Mod is resolved if it has no dependencies or all its dependencies are already resolved
  471. auto isResolved = [&](const ModDescription & mod) -> bool
  472. {
  473. if (mod.isTranslation() && CGeneralTextHandler::getPreferredLanguage() != mod.getBaseLanguage())
  474. return false;
  475. if(mod.getDependencies().size() > resolvedModIDs.size())
  476. return false;
  477. for(const TModID & dependency : mod.getDependencies())
  478. if(!vstd::contains(resolvedModIDs, dependency))
  479. return false;
  480. for(const TModID & softDependency : mod.getSoftDependencies())
  481. if(vstd::contains(notResolvedModIDs, softDependency))
  482. return false;
  483. for(const TModID & conflict : mod.getConflicts())
  484. if(vstd::contains(resolvedModIDs, conflict))
  485. return false;
  486. for(const TModID & reverseConflict : resolvedModIDs)
  487. if(vstd::contains(storage.getMod(reverseConflict).getConflicts(), mod.getID()))
  488. return false;
  489. return true;
  490. };
  491. while(true)
  492. {
  493. std::set<TModID> resolvedOnCurrentTreeLevel;
  494. for(auto it = modsToResolve.begin(); it != modsToResolve.end();) // One iteration - one level of mods tree
  495. {
  496. if(isResolved(storage.getMod(*it)))
  497. {
  498. resolvedOnCurrentTreeLevel.insert(*it); // Not to the resolvedModIDs, so current node children will be resolved on the next iteration
  499. sortedValidMods.push_back(*it);
  500. it = modsToResolve.erase(it);
  501. continue;
  502. }
  503. it++;
  504. }
  505. if(!resolvedOnCurrentTreeLevel.empty())
  506. {
  507. resolvedModIDs.insert(resolvedOnCurrentTreeLevel.begin(), resolvedOnCurrentTreeLevel.end());
  508. for(const auto & it : resolvedOnCurrentTreeLevel)
  509. notResolvedModIDs.erase(it);
  510. continue;
  511. }
  512. // If there are no valid mods on the current mods tree level, no more mod can be resolved, should be ended.
  513. break;
  514. }
  515. assert(!sortedValidMods.empty());
  516. activeMods = sortedValidMods;
  517. brokenMods.insert(brokenMods.end(), modsToResolve.begin(), modsToResolve.end());
  518. }
  519. VCMI_LIB_NAMESPACE_END