CModHandler.cpp 29 KB

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