CModHandler.cpp 30 KB

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