CModHandler.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780
  1. #include "StdInc.h"
  2. #include "CModHandler.h"
  3. #include "CDefObjInfoHandler.h"
  4. #include "JsonNode.h"
  5. #include "filesystem/Filesystem.h"
  6. #include "filesystem/AdapterLoaders.h"
  7. #include "filesystem/CFilesystemLoader.h"
  8. #include "CCreatureHandler.h"
  9. #include "CArtHandler.h"
  10. #include "CTownHandler.h"
  11. #include "CHeroHandler.h"
  12. #include "CObjectHandler.h"
  13. #include "StringConstants.h"
  14. #include "CStopWatch.h"
  15. #include "IHandlerBase.h"
  16. /*
  17. * CModHandler.cpp, part of VCMI engine
  18. *
  19. * Authors: listed in file AUTHORS in main folder
  20. *
  21. * License: GNU General Public License v2.0 or later
  22. * Full text of license available in license.txt file, in main folder
  23. *
  24. */
  25. void CIdentifierStorage::checkIdentifier(std::string & ID)
  26. {
  27. if (boost::algorithm::ends_with(ID, "."))
  28. logGlobal->warnStream() << "BIG WARNING: identifier " << ID << " seems to be broken!";
  29. else
  30. {
  31. size_t pos = 0;
  32. do
  33. {
  34. if (std::tolower(ID[pos]) != ID[pos] ) //Not in camelCase
  35. {
  36. logGlobal->warnStream() << "Warning: identifier " << ID << " is not in camelCase!";
  37. ID[pos] = std::tolower(ID[pos]);// Try to fix the ID
  38. }
  39. pos = ID.find('.', pos);
  40. }
  41. while(pos++ != std::string::npos);
  42. }
  43. }
  44. CIdentifierStorage::ObjectCallback::ObjectCallback(std::string localScope, std::string remoteScope, std::string type,
  45. std::string name, const std::function<void(si32)> & callback, bool optional):
  46. localScope(localScope),
  47. remoteScope(remoteScope),
  48. type(type),
  49. name(name),
  50. callback(callback),
  51. optional(optional)
  52. {}
  53. static std::pair<std::string, std::string> splitString(std::string input, char separator)
  54. {
  55. std::pair<std::string, std::string> ret;
  56. size_t splitPos = input.find(separator);
  57. if (splitPos == std::string::npos)
  58. {
  59. ret.first.clear();
  60. ret.second = input;
  61. }
  62. else
  63. {
  64. ret.first = input.substr(0, splitPos);
  65. ret.second = input.substr(splitPos + 1);
  66. }
  67. return ret;
  68. }
  69. void CIdentifierStorage::requestIdentifier(ObjectCallback callback)
  70. {
  71. checkIdentifier(callback.type);
  72. checkIdentifier(callback.name);
  73. assert(!callback.localScope.empty());
  74. scheduledRequests.push_back(callback);
  75. }
  76. void CIdentifierStorage::requestIdentifier(std::string scope, std::string type, std::string name, const std::function<void(si32)> & callback)
  77. {
  78. auto pair = splitString(name, ':'); // remoteScope:name
  79. requestIdentifier(ObjectCallback(scope, pair.first, type, pair.second, callback, false));
  80. }
  81. void CIdentifierStorage::requestIdentifier(std::string type, const JsonNode & name, const std::function<void(si32)> & callback)
  82. {
  83. auto pair = splitString(name.String(), ':'); // remoteScope:name
  84. requestIdentifier(ObjectCallback(name.meta, pair.first, type, pair.second, callback, false));
  85. }
  86. void CIdentifierStorage::requestIdentifier(const JsonNode & name, const std::function<void(si32)> & callback)
  87. {
  88. auto pair = splitString(name.String(), ':'); // remoteScope:<type.name>
  89. auto pair2 = splitString(pair.second, '.'); // type.name
  90. requestIdentifier(ObjectCallback(name.meta, pair.first, pair2.first, pair2.second, callback, false));
  91. }
  92. void CIdentifierStorage::tryRequestIdentifier(std::string scope, std::string type, std::string name, const std::function<void(si32)> & callback)
  93. {
  94. auto pair = splitString(name, ':'); // remoteScope:name
  95. requestIdentifier(ObjectCallback(scope, pair.first, type, pair.second, callback, true));
  96. }
  97. void CIdentifierStorage::tryRequestIdentifier(std::string type, const JsonNode & name, const std::function<void(si32)> & callback)
  98. {
  99. auto pair = splitString(name.String(), ':'); // remoteScope:name
  100. requestIdentifier(ObjectCallback(name.meta, pair.first, type, pair.second, callback, true));
  101. }
  102. boost::optional<si32> CIdentifierStorage::getIdentifier(std::string type, const JsonNode & name, bool silent)
  103. {
  104. auto pair = splitString(name.String(), ':'); // remoteScope:name
  105. auto idList = getPossibleIdentifiers(ObjectCallback(name.meta, pair.first, type, pair.second, std::function<void(si32)>(), silent));
  106. if (idList.size() == 1)
  107. return idList.front().id;
  108. if (!silent)
  109. logGlobal->errorStream() << "Failed to resolve identifier " << name.String() << " from mod " << type;
  110. return boost::optional<si32>();
  111. }
  112. boost::optional<si32> CIdentifierStorage::getIdentifier(const JsonNode & name, bool silent)
  113. {
  114. auto pair = splitString(name.String(), ':'); // remoteScope:<type.name>
  115. auto pair2 = splitString(pair.second, '.'); // type.name
  116. auto idList = getPossibleIdentifiers(ObjectCallback(name.meta, pair.first, pair2.first, pair2.second, std::function<void(si32)>(), silent));
  117. if (idList.size() == 1)
  118. return idList.front().id;
  119. if (!silent)
  120. logGlobal->errorStream() << "Failed to resolve identifier " << name.String() << " from mod " << name.meta;
  121. return boost::optional<si32>();
  122. }
  123. void CIdentifierStorage::registerObject(std::string scope, std::string type, std::string name, si32 identifier)
  124. {
  125. ObjectData data;
  126. data.scope = scope;
  127. data.id = identifier;
  128. std::string fullID = type + '.' + name;
  129. checkIdentifier(fullID);
  130. registeredObjects.insert(std::make_pair(fullID, data));
  131. }
  132. std::vector<CIdentifierStorage::ObjectData> CIdentifierStorage::getPossibleIdentifiers(const ObjectCallback & request)
  133. {
  134. std::set<std::string> allowedScopes;
  135. if (request.remoteScope.empty())
  136. {
  137. // normally ID's from all required mods, own mod and virtual "core" mod are allowed
  138. if (request.localScope != "core" && request.localScope != "")
  139. allowedScopes = VLC->modh->getModData(request.localScope).dependencies;
  140. allowedScopes.insert(request.localScope);
  141. allowedScopes.insert("core");
  142. }
  143. else
  144. {
  145. //...unless destination mod was specified explicitly
  146. auto myDeps = VLC->modh->getModData(request.localScope).dependencies;
  147. if (request.remoteScope == "core" || // allow only available to all core mod
  148. myDeps.count(request.remoteScope)) // or dependencies
  149. allowedScopes.insert(request.remoteScope);
  150. }
  151. std::string fullID = request.type + '.' + request.name;
  152. auto entries = registeredObjects.equal_range(fullID);
  153. if (entries.first != entries.second)
  154. {
  155. std::vector<ObjectData> locatedIDs;
  156. for (auto it = entries.first; it != entries.second; it++)
  157. {
  158. if (vstd::contains(allowedScopes, it->second.scope))
  159. {
  160. locatedIDs.push_back(it->second);
  161. }
  162. }
  163. return locatedIDs;
  164. }
  165. return std::vector<ObjectData>();
  166. }
  167. bool CIdentifierStorage::resolveIdentifier(const ObjectCallback & request)
  168. {
  169. auto identifiers = getPossibleIdentifiers(request);
  170. if (identifiers.size() == 1) // normally resolved ID
  171. {
  172. request.callback(identifiers.front().id);
  173. return true;
  174. }
  175. if (request.optional && identifiers.empty()) // failed to resolve optinal ID
  176. return true;
  177. // error found. Try to generate some debug info
  178. if (identifiers.size() == 0)
  179. logGlobal->errorStream() << "Unknown identifier!";
  180. else
  181. logGlobal->errorStream() << "Ambiguous identifier request!";
  182. logGlobal->errorStream() << "Request for " << request.type << "." << request.name << " from mod " << request.localScope;
  183. for (auto id : identifiers)
  184. {
  185. logGlobal->errorStream() << "\tID is available in mod " << id.scope;
  186. }
  187. return false;
  188. }
  189. void CIdentifierStorage::finalize()
  190. {
  191. bool errorsFound = false;
  192. for(const ObjectCallback & request : scheduledRequests)
  193. {
  194. errorsFound |= !resolveIdentifier(request);
  195. }
  196. if (errorsFound)
  197. {
  198. for(auto object : registeredObjects)
  199. {
  200. logGlobal->traceStream() << object.first << " -> " << object.second.id;
  201. }
  202. logGlobal->errorStream() << "All known identifiers were dumped into log file";
  203. }
  204. assert(errorsFound == false);
  205. }
  206. CContentHandler::ContentTypeHandler::ContentTypeHandler(IHandlerBase * handler, std::string objectName):
  207. handler(handler),
  208. objectName(objectName),
  209. originalData(handler->loadLegacyData(VLC->modh->settings.data["textData"][objectName].Float()))
  210. {
  211. for(auto & node : originalData)
  212. {
  213. node.setMeta("core");
  214. }
  215. }
  216. bool CContentHandler::ContentTypeHandler::preloadModData(std::string modName, std::vector<std::string> fileList, bool validate)
  217. {
  218. bool result;
  219. JsonNode data = JsonUtils::assembleFromFiles(fileList, result);
  220. data.setMeta(modName);
  221. ModInfo & modInfo = modData[modName];
  222. for(auto entry : data.Struct())
  223. {
  224. size_t colon = entry.first.find(':');
  225. if (colon == std::string::npos)
  226. {
  227. // normal object, local to this mod
  228. modInfo.modData[entry.first].swap(entry.second);
  229. }
  230. else
  231. {
  232. std::string remoteName = entry.first.substr(0, colon);
  233. std::string objectName = entry.first.substr(colon + 1);
  234. // patching this mod? Send warning and continue - this situation can be handled normally
  235. if (remoteName == modName)
  236. logGlobal->warnStream() << "Redundant namespace definition for " << objectName;
  237. JsonNode & remoteConf = modData[remoteName].patches[objectName];
  238. JsonUtils::merge(remoteConf, entry.second);
  239. }
  240. }
  241. return result;
  242. }
  243. bool CContentHandler::ContentTypeHandler::loadMod(std::string modName, bool validate)
  244. {
  245. ModInfo & modInfo = modData[modName];
  246. bool result = true;
  247. // apply patches
  248. if (!modInfo.patches.isNull())
  249. JsonUtils::merge(modInfo.modData, modInfo.patches);
  250. for(auto & entry : modInfo.modData.Struct())
  251. {
  252. const std::string & name = entry.first;
  253. JsonNode & data = entry.second;
  254. if (vstd::contains(data.Struct(), "index") && !data["index"].isNull())
  255. {
  256. // try to add H3 object data
  257. size_t index = data["index"].Float();
  258. if (originalData.size() > index)
  259. {
  260. JsonUtils::merge(originalData[index], data);
  261. if (validate)
  262. result &= JsonUtils::validate(originalData[index], "vcmi:" + objectName, name);
  263. handler->loadObject(modName, name, originalData[index], index);
  264. originalData[index].clear(); // do not use same data twice (same ID)
  265. continue;
  266. }
  267. }
  268. // normal new object or one with index bigger that data size
  269. if (validate)
  270. result &= JsonUtils::validate(data, "vcmi:" + objectName, name);
  271. handler->loadObject(modName, name, data);
  272. }
  273. return result;
  274. }
  275. void CContentHandler::ContentTypeHandler::afterLoadFinalization()
  276. {
  277. handler->afterLoadFinalization();
  278. }
  279. CContentHandler::CContentHandler()
  280. {
  281. handlers.insert(std::make_pair("heroClasses", ContentTypeHandler(&VLC->heroh->classes, "heroClass")));
  282. handlers.insert(std::make_pair("artifacts", ContentTypeHandler(VLC->arth, "artifact")));
  283. handlers.insert(std::make_pair("creatures", ContentTypeHandler(VLC->creh, "creature")));
  284. handlers.insert(std::make_pair("factions", ContentTypeHandler(VLC->townh, "faction")));
  285. handlers.insert(std::make_pair("heroes", ContentTypeHandler(VLC->heroh, "hero")));
  286. //TODO: spells, bonuses, something else?
  287. }
  288. bool CContentHandler::preloadModData(std::string modName, JsonNode modConfig, bool validate)
  289. {
  290. bool result = true;
  291. for(auto & handler : handlers)
  292. {
  293. result &= handler.second.preloadModData(modName, modConfig[handler.first].convertTo<std::vector<std::string> >(), validate);
  294. }
  295. return result;
  296. }
  297. bool CContentHandler::loadMod(std::string modName, bool validate)
  298. {
  299. bool result = true;
  300. for(auto & handler : handlers)
  301. {
  302. result &= handler.second.loadMod(modName, validate);
  303. }
  304. return result;
  305. }
  306. void CContentHandler::afterLoadFinalization()
  307. {
  308. for(auto & handler : handlers)
  309. {
  310. handler.second.afterLoadFinalization();
  311. }
  312. }
  313. void CContentHandler::preloadData(CModInfo & mod)
  314. {
  315. bool validate = (mod.validation != CModInfo::PASSED);
  316. // print message in format [<8-symbols checksum>] <modname>
  317. logGlobal->infoStream() << "\t\t[" << std::noshowbase << std::hex << std::setw(8) << std::setfill('0')
  318. << mod.checksum << "] " << mod.name;
  319. if (validate && mod.identifier != "core")
  320. {
  321. if (!JsonUtils::validate(mod.config, "vcmi:mod", mod.identifier))
  322. mod.validation = CModInfo::FAILED;
  323. }
  324. if (!preloadModData(mod.identifier, mod.config, validate))
  325. mod.validation = CModInfo::FAILED;
  326. }
  327. void CContentHandler::load(CModInfo & mod)
  328. {
  329. bool validate = (mod.validation != CModInfo::PASSED);
  330. if (!loadMod(mod.identifier, validate))
  331. mod.validation = CModInfo::FAILED;
  332. if (validate)
  333. {
  334. if (mod.validation != CModInfo::FAILED)
  335. logGlobal->infoStream() << "\t\t[DONE] " << mod.name;
  336. else
  337. logGlobal->errorStream() << "\t\t[FAIL] " << mod.name;
  338. }
  339. else
  340. logGlobal->infoStream() << "\t\t[SKIP] " << mod.name;
  341. }
  342. CModHandler::CModHandler()
  343. {
  344. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; ++i)
  345. {
  346. identifiers.registerObject("core", "resource", GameConstants::RESOURCE_NAMES[i], i);
  347. }
  348. for(int i=0; i<GameConstants::PRIMARY_SKILLS; ++i)
  349. identifiers.registerObject("core", "primSkill", PrimarySkill::names[i], i);
  350. }
  351. void CModHandler::loadConfigFromFile (std::string name)
  352. {
  353. settings.data = JsonUtils::assembleFromFiles("config/" + name);
  354. const JsonNode & hardcodedFeatures = settings.data["hardcodedFeatures"];
  355. settings.CREEP_SIZE = hardcodedFeatures["CREEP_SIZE"].Float();
  356. settings.WEEKLY_GROWTH = hardcodedFeatures["WEEKLY_GROWTH_PERCENT"].Float();
  357. settings.NEUTRAL_STACK_EXP = hardcodedFeatures["NEUTRAL_STACK_EXP_DAILY"].Float();
  358. settings.MAX_BUILDING_PER_TURN = hardcodedFeatures["MAX_BUILDING_PER_TURN"].Float();
  359. settings.DWELLINGS_ACCUMULATE_CREATURES = hardcodedFeatures["DWELLINGS_ACCUMULATE_CREATURES"].Bool();
  360. settings.ALL_CREATURES_GET_DOUBLE_MONTHS = hardcodedFeatures["ALL_CREATURES_GET_DOUBLE_MONTHS"].Bool();
  361. const JsonNode & gameModules = settings.data["modules"];
  362. modules.STACK_EXP = gameModules["STACK_EXPERIENCE"].Bool();
  363. modules.STACK_ARTIFACT = gameModules["STACK_ARTIFACTS"].Bool();
  364. modules.COMMANDERS = gameModules["COMMANDERS"].Bool();
  365. modules.MITHRIL = gameModules["MITHRIL"].Bool();
  366. }
  367. // currentList is passed by value to get current list of depending mods
  368. bool CModHandler::hasCircularDependency(TModID modID, std::set <TModID> currentList) const
  369. {
  370. const CModInfo & mod = allMods.at(modID);
  371. // Mod already present? We found a loop
  372. if (vstd::contains(currentList, modID))
  373. {
  374. logGlobal->errorStream() << "Error: Circular dependency detected! Printing dependency list:";
  375. logGlobal->errorStream() << "\t" << mod.name << " -> ";
  376. return true;
  377. }
  378. currentList.insert(modID);
  379. // recursively check every dependency of this mod
  380. for(const TModID & dependency : mod.dependencies)
  381. {
  382. if (hasCircularDependency(dependency, currentList))
  383. {
  384. logGlobal->errorStream() << "\t" << mod.name << " ->\n"; // conflict detected, print dependency list
  385. return true;
  386. }
  387. }
  388. return false;
  389. }
  390. bool CModHandler::checkDependencies(const std::vector <TModID> & input) const
  391. {
  392. for(const TModID & id : input)
  393. {
  394. const CModInfo & mod = allMods.at(id);
  395. for(const TModID & dep : mod.dependencies)
  396. {
  397. if (!vstd::contains(input, dep))
  398. {
  399. logGlobal->errorStream() << "Error: Mod " << mod.name << " requires missing " << dep << "!";
  400. return false;
  401. }
  402. }
  403. for(const TModID & conflicting : mod.conflicts)
  404. {
  405. if (vstd::contains(input, conflicting))
  406. {
  407. logGlobal->errorStream() << "Error: Mod " << mod.name << " conflicts with " << allMods.at(conflicting).name << "!";
  408. return false;
  409. }
  410. }
  411. if (hasCircularDependency(id))
  412. return false;
  413. }
  414. return true;
  415. }
  416. std::vector <TModID> CModHandler::resolveDependencies(std::vector <TModID> input) const
  417. {
  418. // Topological sort algorithm
  419. // May not be the fastest one but VCMI does not needs any speed here
  420. // Unless user have dozens of mods with complex dependencies this code should be fine
  421. // first - sort input to have input strictly based on name (and not on hashmap or anything else)
  422. boost::range::sort(input);
  423. std::vector <TModID> output;
  424. output.reserve(input.size());
  425. std::set <TModID> resolvedMods;
  426. // Check if all mod dependencies are resolved (moved to resolvedMods)
  427. auto isResolved = [&](const CModInfo mod) -> bool
  428. {
  429. for(const TModID & dependency : mod.dependencies)
  430. {
  431. if (!vstd::contains(resolvedMods, dependency))
  432. return false;
  433. }
  434. return true;
  435. };
  436. while (!input.empty())
  437. {
  438. std::set <TModID> toResolve; // list of mods resolved on this iteration
  439. for (auto it = input.begin(); it != input.end();)
  440. {
  441. if (isResolved(allMods.at(*it)))
  442. {
  443. toResolve.insert(*it);
  444. output.push_back(*it);
  445. it = input.erase(it);
  446. continue;
  447. }
  448. it++;
  449. }
  450. resolvedMods.insert(toResolve.begin(), toResolve.end());
  451. }
  452. return output;
  453. }
  454. static JsonNode loadModSettings(std::string path)
  455. {
  456. if (CResourceHandler::get()->existsResource(ResourceID(path)))
  457. {
  458. return JsonNode(ResourceID(path, EResType::TEXT));
  459. }
  460. // Probably new install. Create initial configuration
  461. CResourceHandler::get()->createResource(path);
  462. return JsonNode();
  463. }
  464. JsonNode addMeta(JsonNode config, std::string meta)
  465. {
  466. config.setMeta(meta);
  467. return std::move(config);
  468. }
  469. CModInfo::CModInfo(std::string identifier,const JsonNode & local, const JsonNode & config):
  470. identifier(identifier),
  471. name(config["name"].String()),
  472. description(config["description"].String()),
  473. dependencies(config["depends"].convertTo<std::set<std::string> >()),
  474. conflicts(config["conflicts"].convertTo<std::set<std::string> >()),
  475. validation(PENDING),
  476. config(addMeta(config, identifier))
  477. {
  478. loadLocalData(local);
  479. }
  480. JsonNode CModInfo::saveLocalData()
  481. {
  482. std::ostringstream stream;
  483. stream << std::noshowbase << std::hex << std::setw(8) << std::setfill('0') << checksum;
  484. JsonNode conf;
  485. conf["active"].Bool() = enabled;
  486. conf["validated"].Bool() = validation != FAILED;
  487. conf["checksum"].String() = stream.str();
  488. return conf;
  489. }
  490. void CModInfo::updateChecksum(ui32 newChecksum)
  491. {
  492. // comment-out next line to force validation of all mods ignoring checksum
  493. if (newChecksum != checksum)
  494. {
  495. checksum = newChecksum;
  496. validation = PENDING;
  497. }
  498. }
  499. void CModInfo::loadLocalData(const JsonNode & data)
  500. {
  501. bool validated = false;
  502. enabled = true;
  503. checksum = 0;
  504. if (data.getType() == JsonNode::DATA_BOOL)
  505. {
  506. enabled = data.Bool();
  507. }
  508. if (data.getType() == JsonNode::DATA_STRUCT)
  509. {
  510. enabled = data["active"].Bool();
  511. validated = data["validated"].Bool();
  512. checksum = strtol(data["checksum"].String().c_str(), nullptr, 16);
  513. }
  514. if (enabled)
  515. validation = validated ? PASSED : PENDING;
  516. else
  517. validation = validated ? PASSED : FAILED;
  518. }
  519. void CModHandler::initializeMods(std::vector<std::string> availableMods)
  520. {
  521. const JsonNode modConfig = loadModSettings("config/modSettings.json");
  522. const JsonNode & modList = modConfig["activeMods"];
  523. std::vector <TModID> detectedMods;
  524. for(std::string name : availableMods)
  525. {
  526. boost::to_lower(name);
  527. std::string modFileName = "mods/" + name + "/mod.json";
  528. if (CResourceHandler::get()->existsResource(ResourceID(modFileName)))
  529. {
  530. CModInfo mod(name, modList[name], JsonNode(ResourceID(modFileName)));
  531. allMods[name] = mod;
  532. if (mod.enabled)
  533. detectedMods.push_back(name);
  534. }
  535. else
  536. logGlobal->warnStream() << "\t\t Directory " << name << " does not contains VCMI mod";
  537. }
  538. coreMod = CModInfo("core", modConfig["core"], JsonNode(ResourceID("config/gameConfig.json")));
  539. coreMod.name = "Original game files";
  540. if (!checkDependencies(detectedMods))
  541. {
  542. logGlobal->errorStream() << "Critical error: failed to load mods! Exiting...";
  543. exit(1);
  544. }
  545. activeMods = resolveDependencies(detectedMods);
  546. loadModFilesystems();
  547. }
  548. static JsonNode genDefaultFS()
  549. {
  550. // default FS config for mods: directory "Content" that acts as H3 root directory
  551. JsonNode defaultFS;
  552. defaultFS[""].Vector().resize(2);
  553. defaultFS[""].Vector()[0]["type"].String() = "zip";
  554. defaultFS[""].Vector()[0]["path"].String() = "/Content.zip";
  555. defaultFS[""].Vector()[1]["type"].String() = "dir";
  556. defaultFS[""].Vector()[1]["path"].String() = "/Content";
  557. return defaultFS;
  558. }
  559. static ISimpleResourceLoader * genModFilesystem(const std::string & modName, const JsonNode & conf)
  560. {
  561. static const JsonNode defaultFS = genDefaultFS();
  562. if (!conf["filesystem"].isNull())
  563. return CResourceHandler::createFileSystem("mods/" + modName, conf["filesystem"]);
  564. else
  565. return CResourceHandler::createFileSystem("mods/" + modName, defaultFS);
  566. }
  567. static ui32 calculateModChecksum(const std::string modName, ISimpleResourceLoader * filesystem)
  568. {
  569. boost::crc_32_type modChecksum;
  570. // first - add current VCMI version into checksum to force re-validation on VCMI updates
  571. modChecksum.process_bytes(reinterpret_cast<const void*>(GameConstants::VCMI_VERSION.data()), GameConstants::VCMI_VERSION.size());
  572. // second - add mod.json into checksum because filesystem does not contains this file
  573. // FIXME: remove workaround for core mod
  574. if (modName != "core")
  575. {
  576. ResourceID modConfFile("mods/" + modName + "/mod", EResType::TEXT);
  577. ui32 configChecksum = CResourceHandler::getInitial()->load(modConfFile)->calculateCRC32();
  578. modChecksum.process_bytes(reinterpret_cast<const void *>(&configChecksum), sizeof(configChecksum));
  579. }
  580. // third - add all detected text files from this mod into checksum
  581. auto files = filesystem->getFilteredFiles([](const ResourceID & resID)
  582. {
  583. return resID.getType() == EResType::TEXT &&
  584. ( boost::starts_with(resID.getName(), "DATA") ||
  585. boost::starts_with(resID.getName(), "CONFIG"));
  586. });
  587. // these two files may change between two runs of vcmi and must be handled separately
  588. files.erase(ResourceID("CONFIG/SETTINGS", EResType::TEXT));
  589. files.erase(ResourceID("CONFIG/MODSETTINGS", EResType::TEXT));
  590. for (const ResourceID & file : files)
  591. {
  592. ui32 fileChecksum = filesystem->load(file)->calculateCRC32();
  593. modChecksum.process_bytes(reinterpret_cast<const void *>(&fileChecksum), sizeof(fileChecksum));
  594. }
  595. return modChecksum.checksum();
  596. }
  597. void CModHandler::loadModFilesystems()
  598. {
  599. coreMod.updateChecksum(calculateModChecksum("core", CResourceHandler::get("core")));
  600. for(std::string & modName : activeMods)
  601. {
  602. CModInfo & mod = allMods[modName];
  603. CResourceHandler::addFilesystem(modName, genModFilesystem(modName, mod.config));
  604. }
  605. }
  606. CModInfo & CModHandler::getModData(TModID modId)
  607. {
  608. CModInfo & mod = allMods.at(modId);
  609. assert(vstd::contains(activeMods, modId)); // not really necessary but won't hurt
  610. return mod;
  611. }
  612. void CModHandler::initializeConfig()
  613. {
  614. loadConfigFromFile("defaultMods.json");
  615. }
  616. void CModHandler::load()
  617. {
  618. CStopWatch totalTime, timer;
  619. CContentHandler content;
  620. logGlobal->infoStream() << "\tInitializing content handler: " << timer.getDiff() << " ms";
  621. for(const TModID & modName : activeMods)
  622. {
  623. logGlobal->traceStream() << "Generating checksum for " << modName;
  624. allMods[modName].updateChecksum(calculateModChecksum(modName, CResourceHandler::get(modName)));
  625. }
  626. // first - load virtual "core" mod that contains all data
  627. // TODO? move all data into real mods? RoE, AB, SoD, WoG
  628. content.preloadData(coreMod);
  629. for(const TModID & modName : activeMods)
  630. content.preloadData(allMods[modName]);
  631. logGlobal->infoStream() << "\tParsing mod data: " << timer.getDiff() << " ms";
  632. content.load(coreMod);
  633. for(const TModID & modName : activeMods)
  634. content.load(allMods[modName]);
  635. logGlobal->infoStream() << "\tLoading mod data: " << timer.getDiff() << "ms";
  636. VLC->creh->loadCrExpBon();
  637. VLC->creh->buildBonusTreeForTiers(); //do that after all new creatures are loaded
  638. identifiers.finalize();
  639. logGlobal->infoStream() << "\tResolving identifiers: " << timer.getDiff() << " ms";
  640. content.afterLoadFinalization();
  641. logGlobal->infoStream() << "\tHandlers post-load finalization: " << timer.getDiff() << " ms";
  642. logGlobal->infoStream() << "\tAll game content loaded in " << totalTime.getDiff() << " ms";
  643. }
  644. void CModHandler::afterLoad()
  645. {
  646. JsonNode modSettings;
  647. for (auto & modEntry : allMods)
  648. modSettings["activeMods"][modEntry.first] = modEntry.second.saveLocalData();
  649. modSettings["core"] = coreMod.saveLocalData();
  650. std::ofstream file(*CResourceHandler::get()->getResourceName(ResourceID("config/modSettings.json")), std::ofstream::trunc);
  651. file << modSettings;
  652. }