CModHandler.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224
  1. /*
  2. * CModHandler.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CModHandler.h"
  12. #include "mapObjects/CObjectClassesHandler.h"
  13. #include "filesystem/FileStream.h"
  14. #include "filesystem/AdapterLoaders.h"
  15. #include "filesystem/CFilesystemLoader.h"
  16. #include "CCreatureHandler.h"
  17. #include "CArtHandler.h"
  18. #include "CTownHandler.h"
  19. #include "CHeroHandler.h"
  20. #include "mapObjects/CObjectHandler.h"
  21. #include "StringConstants.h"
  22. #include "CStopWatch.h"
  23. #include "IHandlerBase.h"
  24. #include "spells/CSpellHandler.h"
  25. #include "CSkillHandler.h"
  26. #include "ScriptHandler.h"
  27. #include "RoadHandler.h"
  28. #include "RiverHandler.h"
  29. #include "TerrainHandler.h"
  30. #include "BattleFieldHandler.h"
  31. #include "ObstacleHandler.h"
  32. #include <vstd/StringUtils.h>
  33. VCMI_LIB_NAMESPACE_BEGIN
  34. CIdentifierStorage::CIdentifierStorage():
  35. state(LOADING)
  36. {
  37. }
  38. CIdentifierStorage::~CIdentifierStorage()
  39. {
  40. }
  41. void CIdentifierStorage::checkIdentifier(std::string & ID)
  42. {
  43. if (boost::algorithm::ends_with(ID, "."))
  44. logMod->warn("BIG WARNING: identifier %s seems to be broken!", ID);
  45. else
  46. {
  47. size_t pos = 0;
  48. do
  49. {
  50. if (std::tolower(ID[pos]) != ID[pos] ) //Not in camelCase
  51. {
  52. logMod->warn("Warning: identifier %s is not in camelCase!", ID);
  53. ID[pos] = std::tolower(ID[pos]);// Try to fix the ID
  54. }
  55. pos = ID.find('.', pos);
  56. }
  57. while(pos++ != std::string::npos);
  58. }
  59. }
  60. CIdentifierStorage::ObjectCallback::ObjectCallback(
  61. std::string localScope, std::string remoteScope, std::string type,
  62. std::string name, const std::function<void(si32)> & callback,
  63. bool optional):
  64. localScope(localScope),
  65. remoteScope(remoteScope),
  66. type(type),
  67. name(name),
  68. callback(callback),
  69. optional(optional)
  70. {}
  71. void CIdentifierStorage::requestIdentifier(ObjectCallback callback)
  72. {
  73. checkIdentifier(callback.type);
  74. checkIdentifier(callback.name);
  75. assert(!callback.localScope.empty());
  76. if (state != FINISHED) // enqueue request if loading is still in progress
  77. scheduledRequests.push_back(callback);
  78. else // execute immediately for "late" requests
  79. resolveIdentifier(callback);
  80. }
  81. void CIdentifierStorage::requestIdentifier(std::string scope, std::string type, std::string name, const std::function<void(si32)> & callback)
  82. {
  83. auto pair = vstd::splitStringToPair(name, ':'); // remoteScope:name
  84. requestIdentifier(ObjectCallback(scope, pair.first, type, pair.second, callback, false));
  85. }
  86. void CIdentifierStorage::requestIdentifier(std::string scope, std::string fullName, const std::function<void(si32)>& callback)
  87. {
  88. auto scopeAndFullName = vstd::splitStringToPair(fullName, ':');
  89. auto typeAndName = vstd::splitStringToPair(scopeAndFullName.second, '.');
  90. requestIdentifier(ObjectCallback(scope, scopeAndFullName.first, typeAndName.first, typeAndName.second, callback, false));
  91. }
  92. void CIdentifierStorage::requestIdentifier(std::string type, const JsonNode & name, const std::function<void(si32)> & callback)
  93. {
  94. auto pair = vstd::splitStringToPair(name.String(), ':'); // remoteScope:name
  95. requestIdentifier(ObjectCallback(name.meta, pair.first, type, pair.second, callback, false));
  96. }
  97. void CIdentifierStorage::requestIdentifier(const JsonNode & name, const std::function<void(si32)> & callback)
  98. {
  99. auto pair = vstd::splitStringToPair(name.String(), ':'); // remoteScope:<type.name>
  100. auto pair2 = vstd::splitStringToPair(pair.second, '.'); // type.name
  101. requestIdentifier(ObjectCallback(name.meta, pair.first, pair2.first, pair2.second, callback, false));
  102. }
  103. void CIdentifierStorage::tryRequestIdentifier(std::string scope, std::string type, std::string name, const std::function<void(si32)> & callback)
  104. {
  105. auto pair = vstd::splitStringToPair(name, ':'); // remoteScope:name
  106. requestIdentifier(ObjectCallback(scope, pair.first, type, pair.second, callback, true));
  107. }
  108. void CIdentifierStorage::tryRequestIdentifier(std::string type, const JsonNode & name, const std::function<void(si32)> & callback)
  109. {
  110. auto pair = vstd::splitStringToPair(name.String(), ':'); // remoteScope:name
  111. requestIdentifier(ObjectCallback(name.meta, pair.first, type, pair.second, callback, true));
  112. }
  113. boost::optional<si32> CIdentifierStorage::getIdentifier(std::string scope, std::string type, std::string name, bool silent)
  114. {
  115. auto pair = vstd::splitStringToPair(name, ':'); // remoteScope:name
  116. auto idList = getPossibleIdentifiers(ObjectCallback(scope, pair.first, type, pair.second, std::function<void(si32)>(), silent));
  117. if (idList.size() == 1)
  118. return idList.front().id;
  119. if (!silent)
  120. logMod->error("Failed to resolve identifier %s of type %s from mod %s", name , type ,scope);
  121. return boost::optional<si32>();
  122. }
  123. boost::optional<si32> CIdentifierStorage::getIdentifier(std::string type, const JsonNode & name, bool silent)
  124. {
  125. auto pair = vstd::splitStringToPair(name.String(), ':'); // remoteScope:name
  126. auto idList = getPossibleIdentifiers(ObjectCallback(name.meta, pair.first, type, pair.second, std::function<void(si32)>(), silent));
  127. if (idList.size() == 1)
  128. return idList.front().id;
  129. if (!silent)
  130. logMod->error("Failed to resolve identifier %s of type %s from mod %s", name.String(), type, name.meta);
  131. return boost::optional<si32>();
  132. }
  133. boost::optional<si32> CIdentifierStorage::getIdentifier(const JsonNode & name, bool silent)
  134. {
  135. auto pair = vstd::splitStringToPair(name.String(), ':'); // remoteScope:<type.name>
  136. auto pair2 = vstd::splitStringToPair(pair.second, '.'); // type.name
  137. auto idList = getPossibleIdentifiers(ObjectCallback(name.meta, pair.first, pair2.first, pair2.second, std::function<void(si32)>(), silent));
  138. if (idList.size() == 1)
  139. return idList.front().id;
  140. if (!silent)
  141. logMod->error("Failed to resolve identifier %s of type %s from mod %s", name.String(), pair2.first, name.meta);
  142. return boost::optional<si32>();
  143. }
  144. boost::optional<si32> CIdentifierStorage::getIdentifier(std::string scope, std::string fullName, bool silent)
  145. {
  146. auto pair = vstd::splitStringToPair(fullName, ':'); // remoteScope:<type.name>
  147. auto pair2 = vstd::splitStringToPair(pair.second, '.'); // type.name
  148. auto idList = getPossibleIdentifiers(ObjectCallback(scope, pair.first, pair2.first, pair2.second, std::function<void(si32)>(), silent));
  149. if (idList.size() == 1)
  150. return idList.front().id;
  151. if (!silent)
  152. logMod->error("Failed to resolve identifier %s of type %s from mod %s", fullName, pair2.first, scope);
  153. return boost::optional<si32>();
  154. }
  155. void CIdentifierStorage::registerObject(std::string scope, std::string type, std::string name, si32 identifier)
  156. {
  157. ObjectData data;
  158. data.scope = scope;
  159. data.id = identifier;
  160. std::string fullID = type + '.' + name;
  161. checkIdentifier(fullID);
  162. std::pair<const std::string, ObjectData> mapping = std::make_pair(fullID, data);
  163. if(!vstd::containsMapping(registeredObjects, mapping))
  164. {
  165. logMod->trace("registered %s as %s:%s", fullID, scope, identifier);
  166. registeredObjects.insert(mapping);
  167. }
  168. }
  169. std::vector<CIdentifierStorage::ObjectData> CIdentifierStorage::getPossibleIdentifiers(const ObjectCallback & request)
  170. {
  171. std::set<std::string> allowedScopes;
  172. bool isValidScope = true;
  173. // called have not specified destination mod explicitly
  174. if (request.remoteScope.empty())
  175. {
  176. // special scope that should have access to all in-game objects
  177. if (request.localScope == CModHandler::scopeGame())
  178. {
  179. for (auto const & modName : VLC->modh->getActiveMods())
  180. allowedScopes.insert(modName);
  181. }
  182. // normally ID's from all required mods, own mod and virtual built-in mod are allowed
  183. else if(request.localScope != CModHandler::scopeBuiltin() && !request.localScope.empty())
  184. {
  185. allowedScopes = VLC->modh->getModDependencies(request.localScope, isValidScope);
  186. if(!isValidScope)
  187. return std::vector<ObjectData>();
  188. allowedScopes.insert(request.localScope);
  189. }
  190. // all mods can access built-in mod
  191. allowedScopes.insert(CModHandler::scopeBuiltin());
  192. }
  193. else
  194. {
  195. //if destination mod was specified explicitly, restrict lookup to this mod
  196. if(request.remoteScope == CModHandler::scopeBuiltin() )
  197. {
  198. //built-in mod is an implicit dependency for all mods, allow access into it
  199. allowedScopes.insert(request.remoteScope);
  200. }
  201. else if ( request.localScope == CModHandler::scopeGame() )
  202. {
  203. // allow access, this is special scope that should have access to all in-game objects
  204. allowedScopes.insert(request.remoteScope);
  205. }
  206. else if(request.remoteScope == request.localScope )
  207. {
  208. // allow self-access
  209. allowedScopes.insert(request.remoteScope);
  210. }
  211. else
  212. {
  213. // allow access only if mod is in our dependencies
  214. auto myDeps = VLC->modh->getModDependencies(request.localScope, isValidScope);
  215. if(!isValidScope)
  216. return std::vector<ObjectData>();
  217. if(myDeps.count(request.remoteScope))
  218. allowedScopes.insert(request.remoteScope);
  219. }
  220. }
  221. std::string fullID = request.type + '.' + request.name;
  222. auto entries = registeredObjects.equal_range(fullID);
  223. if (entries.first != entries.second)
  224. {
  225. std::vector<ObjectData> locatedIDs;
  226. for (auto it = entries.first; it != entries.second; it++)
  227. {
  228. if (vstd::contains(allowedScopes, it->second.scope))
  229. {
  230. locatedIDs.push_back(it->second);
  231. }
  232. }
  233. return locatedIDs;
  234. }
  235. return std::vector<ObjectData>();
  236. }
  237. bool CIdentifierStorage::resolveIdentifier(const ObjectCallback & request)
  238. {
  239. auto identifiers = getPossibleIdentifiers(request);
  240. if (identifiers.size() == 1) // normally resolved ID
  241. {
  242. request.callback(identifiers.front().id);
  243. return true;
  244. }
  245. if (request.optional && identifiers.empty()) // failed to resolve optinal ID
  246. {
  247. return true;
  248. }
  249. // error found. Try to generate some debug info
  250. if (identifiers.size() == 0)
  251. logMod->error("Unknown identifier!");
  252. else
  253. logMod->error("Ambiguous identifier request!");
  254. logMod->error("Request for %s.%s from mod %s", request.type, request.name, request.localScope);
  255. for (auto id : identifiers)
  256. {
  257. logMod->error("\tID is available in mod %s", id.scope);
  258. }
  259. return false;
  260. }
  261. void CIdentifierStorage::finalize()
  262. {
  263. state = FINALIZING;
  264. bool errorsFound = false;
  265. while ( !scheduledRequests.empty() )
  266. {
  267. // Use local copy since new requests may appear during resolving, invalidating any iterators
  268. auto request = scheduledRequests.back();
  269. scheduledRequests.pop_back();
  270. if (!resolveIdentifier(request))
  271. errorsFound = true;
  272. }
  273. if (errorsFound)
  274. {
  275. for(auto object : registeredObjects)
  276. {
  277. logMod->trace("%s : %s -> %d", object.second.scope, object.first, object.second.id);
  278. }
  279. logMod->error("All known identifiers were dumped into log file");
  280. }
  281. assert(errorsFound == false);
  282. state = FINISHED;
  283. }
  284. ContentTypeHandler::ContentTypeHandler(IHandlerBase * handler, std::string objectName):
  285. handler(handler),
  286. objectName(objectName),
  287. originalData(handler->loadLegacyData((size_t)VLC->modh->settings.data["textData"][objectName].Float()))
  288. {
  289. for(auto & node : originalData)
  290. {
  291. node.setMeta(CModHandler::scopeBuiltin());
  292. }
  293. }
  294. bool ContentTypeHandler::preloadModData(std::string modName, std::vector<std::string> fileList, bool validate)
  295. {
  296. bool result;
  297. JsonNode data = JsonUtils::assembleFromFiles(fileList, result);
  298. data.setMeta(modName);
  299. ModInfo & modInfo = modData[modName];
  300. for(auto entry : data.Struct())
  301. {
  302. size_t colon = entry.first.find(':');
  303. if (colon == std::string::npos)
  304. {
  305. // normal object, local to this mod
  306. modInfo.modData[entry.first].swap(entry.second);
  307. }
  308. else
  309. {
  310. std::string remoteName = entry.first.substr(0, colon);
  311. std::string objectName = entry.first.substr(colon + 1);
  312. // patching this mod? Send warning and continue - this situation can be handled normally
  313. if (remoteName == modName)
  314. logMod->warn("Redundant namespace definition for %s", objectName);
  315. logMod->trace("Patching object %s (%s) from %s", objectName, remoteName, modName);
  316. JsonNode & remoteConf = modData[remoteName].patches[objectName];
  317. JsonUtils::merge(remoteConf, entry.second);
  318. }
  319. }
  320. return result;
  321. }
  322. bool ContentTypeHandler::loadMod(std::string modName, bool validate)
  323. {
  324. ModInfo & modInfo = modData[modName];
  325. bool result = true;
  326. auto performValidate = [&,this](JsonNode & data, const std::string & name){
  327. handler->beforeValidate(data);
  328. if (validate)
  329. result &= JsonUtils::validate(data, "vcmi:" + objectName, name);
  330. };
  331. // apply patches
  332. if (!modInfo.patches.isNull())
  333. JsonUtils::merge(modInfo.modData, modInfo.patches);
  334. for(auto & entry : modInfo.modData.Struct())
  335. {
  336. const std::string & name = entry.first;
  337. JsonNode & data = entry.second;
  338. if (vstd::contains(data.Struct(), "index") && !data["index"].isNull())
  339. {
  340. if (modName != "core")
  341. logMod->warn("Mod %s is attempting to load original data! This should be reserved for built-in mod.", modName);
  342. // try to add H3 object data
  343. size_t index = static_cast<size_t>(data["index"].Float());
  344. if(originalData.size() > index)
  345. {
  346. logMod->trace("found original data in loadMod(%s) at index %d", name, index);
  347. JsonUtils::merge(originalData[index], data);
  348. std::swap(originalData[index], data);
  349. originalData[index].clear(); // do not use same data twice (same ID)
  350. }
  351. else
  352. {
  353. logMod->trace("no original data in loadMod(%s) at index %d", name, index);
  354. }
  355. performValidate(data, name);
  356. handler->loadObject(modName, name, data, index);
  357. }
  358. else
  359. {
  360. // normal new object
  361. logMod->trace("no index in loadMod(%s)", name);
  362. performValidate(data,name);
  363. handler->loadObject(modName, name, data);
  364. }
  365. }
  366. return result;
  367. }
  368. void ContentTypeHandler::loadCustom()
  369. {
  370. handler->loadCustom();
  371. }
  372. void ContentTypeHandler::afterLoadFinalization()
  373. {
  374. handler->afterLoadFinalization();
  375. }
  376. CContentHandler::CContentHandler()
  377. {
  378. }
  379. void CContentHandler::init()
  380. {
  381. handlers.insert(std::make_pair("heroClasses", ContentTypeHandler(&VLC->heroh->classes, "heroClass")));
  382. handlers.insert(std::make_pair("artifacts", ContentTypeHandler(VLC->arth, "artifact")));
  383. handlers.insert(std::make_pair("creatures", ContentTypeHandler(VLC->creh, "creature")));
  384. handlers.insert(std::make_pair("factions", ContentTypeHandler(VLC->townh, "faction")));
  385. handlers.insert(std::make_pair("objects", ContentTypeHandler(VLC->objtypeh, "object")));
  386. handlers.insert(std::make_pair("heroes", ContentTypeHandler(VLC->heroh, "hero")));
  387. handlers.insert(std::make_pair("spells", ContentTypeHandler(VLC->spellh, "spell")));
  388. handlers.insert(std::make_pair("skills", ContentTypeHandler(VLC->skillh, "skill")));
  389. handlers.insert(std::make_pair("templates", ContentTypeHandler((IHandlerBase *)VLC->tplh, "template")));
  390. #if SCRIPTING_ENABLED
  391. handlers.insert(std::make_pair("scripts", ContentTypeHandler(VLC->scriptHandler, "script")));
  392. #endif
  393. handlers.insert(std::make_pair("battlefields", ContentTypeHandler(VLC->battlefieldsHandler, "battlefield")));
  394. handlers.insert(std::make_pair("terrains", ContentTypeHandler(VLC->terrainTypeHandler, "terrain")));
  395. handlers.insert(std::make_pair("rivers", ContentTypeHandler(VLC->riverTypeHandler, "river")));
  396. handlers.insert(std::make_pair("roads", ContentTypeHandler(VLC->roadTypeHandler, "road")));
  397. handlers.insert(std::make_pair("obstacles", ContentTypeHandler(VLC->obstacleHandler, "obstacle")));
  398. //TODO: any other types of moddables?
  399. }
  400. bool CContentHandler::preloadModData(std::string modName, JsonNode modConfig, bool validate)
  401. {
  402. bool result = true;
  403. for(auto & handler : handlers)
  404. {
  405. result &= handler.second.preloadModData(modName, modConfig[handler.first].convertTo<std::vector<std::string> >(), validate);
  406. }
  407. return result;
  408. }
  409. bool CContentHandler::loadMod(std::string modName, bool validate)
  410. {
  411. bool result = true;
  412. for(auto & handler : handlers)
  413. {
  414. result &= handler.second.loadMod(modName, validate);
  415. }
  416. return result;
  417. }
  418. void CContentHandler::loadCustom()
  419. {
  420. for(auto & handler : handlers)
  421. {
  422. handler.second.loadCustom();
  423. }
  424. }
  425. void CContentHandler::afterLoadFinalization()
  426. {
  427. for(auto & handler : handlers)
  428. {
  429. handler.second.afterLoadFinalization();
  430. }
  431. }
  432. void CContentHandler::preloadData(CModInfo & mod)
  433. {
  434. bool validate = (mod.validation != CModInfo::PASSED);
  435. // print message in format [<8-symbols checksum>] <modname>
  436. logMod->info("\t\t[%08x]%s", mod.checksum, mod.name);
  437. if (validate && mod.identifier != CModHandler::scopeBuiltin())
  438. {
  439. if (!JsonUtils::validate(mod.config, "vcmi:mod", mod.identifier))
  440. mod.validation = CModInfo::FAILED;
  441. }
  442. if (!preloadModData(mod.identifier, mod.config, validate))
  443. mod.validation = CModInfo::FAILED;
  444. }
  445. void CContentHandler::load(CModInfo & mod)
  446. {
  447. bool validate = (mod.validation != CModInfo::PASSED);
  448. if (!loadMod(mod.identifier, validate))
  449. mod.validation = CModInfo::FAILED;
  450. if (validate)
  451. {
  452. if (mod.validation != CModInfo::FAILED)
  453. logMod->info("\t\t[DONE] %s", mod.name);
  454. else
  455. logMod->error("\t\t[FAIL] %s", mod.name);
  456. }
  457. else
  458. logMod->info("\t\t[SKIP] %s", mod.name);
  459. }
  460. const ContentTypeHandler & CContentHandler::operator[](const std::string & name) const
  461. {
  462. return handlers.at(name);
  463. }
  464. static JsonNode loadModSettings(std::string path)
  465. {
  466. if (CResourceHandler::get("local")->existsResource(ResourceID(path)))
  467. {
  468. return JsonNode(ResourceID(path, EResType::TEXT));
  469. }
  470. // Probably new install. Create initial configuration
  471. CResourceHandler::get("local")->createResource(path);
  472. return JsonNode();
  473. }
  474. JsonNode addMeta(JsonNode config, std::string meta)
  475. {
  476. config.setMeta(meta);
  477. return config;
  478. }
  479. CModInfo::Version CModInfo::Version::GameVersion()
  480. {
  481. return Version(VCMI_VERSION_MAJOR, VCMI_VERSION_MINOR, VCMI_VERSION_PATCH);
  482. }
  483. CModInfo::Version CModInfo::Version::fromString(std::string from)
  484. {
  485. int major = 0, minor = 0, patch = 0;
  486. try
  487. {
  488. auto pointPos = from.find('.');
  489. major = std::stoi(from.substr(0, pointPos));
  490. if(pointPos != std::string::npos)
  491. {
  492. from = from.substr(pointPos + 1);
  493. pointPos = from.find('.');
  494. minor = std::stoi(from.substr(0, pointPos));
  495. if(pointPos != std::string::npos)
  496. patch = std::stoi(from.substr(pointPos + 1));
  497. }
  498. }
  499. catch(const std::invalid_argument &)
  500. {
  501. return Version();
  502. }
  503. return Version(major, minor, patch);
  504. }
  505. std::string CModInfo::Version::toString() const
  506. {
  507. return std::to_string(major) + '.' + std::to_string(minor) + '.' + std::to_string(patch);
  508. }
  509. bool CModInfo::Version::compatible(const Version & other, bool checkMinor, bool checkPatch) const
  510. {
  511. return (major == other.major &&
  512. (!checkMinor || minor >= other.minor) &&
  513. (!checkPatch || minor > other.minor || (minor == other.minor && patch >= other.patch)));
  514. }
  515. bool CModInfo::Version::isNull() const
  516. {
  517. return major == 0 && minor == 0 && patch == 0;
  518. }
  519. CModInfo::CModInfo():
  520. checksum(0),
  521. enabled(false),
  522. validation(PENDING)
  523. {
  524. }
  525. CModInfo::CModInfo(std::string identifier,const JsonNode & local, const JsonNode & config):
  526. identifier(identifier),
  527. name(config["name"].String()),
  528. description(config["description"].String()),
  529. dependencies(config["depends"].convertTo<std::set<std::string> >()),
  530. conflicts(config["conflicts"].convertTo<std::set<std::string> >()),
  531. checksum(0),
  532. enabled(false),
  533. validation(PENDING),
  534. config(addMeta(config, identifier))
  535. {
  536. version = Version::fromString(config["version"].String());
  537. if(!config["compatibility"].isNull())
  538. {
  539. vcmiCompatibleMin = Version::fromString(config["compatibility"]["min"].String());
  540. vcmiCompatibleMax = Version::fromString(config["compatibility"]["max"].String());
  541. }
  542. loadLocalData(local);
  543. }
  544. JsonNode CModInfo::saveLocalData() const
  545. {
  546. std::ostringstream stream;
  547. stream << std::noshowbase << std::hex << std::setw(8) << std::setfill('0') << checksum;
  548. JsonNode conf;
  549. conf["active"].Bool() = enabled;
  550. conf["validated"].Bool() = validation != FAILED;
  551. conf["checksum"].String() = stream.str();
  552. return conf;
  553. }
  554. std::string CModInfo::getModDir(std::string name)
  555. {
  556. return "MODS/" + boost::algorithm::replace_all_copy(name, ".", "/MODS/");
  557. }
  558. std::string CModInfo::getModFile(std::string name)
  559. {
  560. return getModDir(name) + "/mod.json";
  561. }
  562. void CModInfo::updateChecksum(ui32 newChecksum)
  563. {
  564. // comment-out next line to force validation of all mods ignoring checksum
  565. if (newChecksum != checksum)
  566. {
  567. checksum = newChecksum;
  568. validation = PENDING;
  569. }
  570. }
  571. void CModInfo::loadLocalData(const JsonNode & data)
  572. {
  573. bool validated = false;
  574. enabled = true;
  575. checksum = 0;
  576. if (data.getType() == JsonNode::JsonType::DATA_BOOL)
  577. {
  578. enabled = data.Bool();
  579. }
  580. if (data.getType() == JsonNode::JsonType::DATA_STRUCT)
  581. {
  582. enabled = data["active"].Bool();
  583. validated = data["validated"].Bool();
  584. checksum = strtol(data["checksum"].String().c_str(), nullptr, 16);
  585. }
  586. //check compatibility
  587. bool wasEnabled = enabled;
  588. enabled = enabled && (vcmiCompatibleMin.isNull() || Version::GameVersion().compatible(vcmiCompatibleMin));
  589. enabled = enabled && (vcmiCompatibleMax.isNull() || vcmiCompatibleMax.compatible(Version::GameVersion()));
  590. if(wasEnabled && !enabled)
  591. logGlobal->warn("Mod %s is incompatible with current version of VCMI and cannot be enabled", name);
  592. if (enabled)
  593. validation = validated ? PASSED : PENDING;
  594. else
  595. validation = validated ? PASSED : FAILED;
  596. }
  597. CModHandler::CModHandler() : content(std::make_shared<CContentHandler>())
  598. {
  599. modules.COMMANDERS = false;
  600. modules.STACK_ARTIFACT = false;
  601. modules.STACK_EXP = false;
  602. modules.MITHRIL = false;
  603. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; ++i)
  604. {
  605. identifiers.registerObject(CModHandler::scopeBuiltin(), "resource", GameConstants::RESOURCE_NAMES[i], i);
  606. }
  607. for(int i=0; i<GameConstants::PRIMARY_SKILLS; ++i)
  608. {
  609. identifiers.registerObject(CModHandler::scopeBuiltin(), "primSkill", PrimarySkill::names[i], i);
  610. identifiers.registerObject(CModHandler::scopeBuiltin(), "primarySkill", PrimarySkill::names[i], i);
  611. }
  612. }
  613. CModHandler::~CModHandler()
  614. {
  615. }
  616. void CModHandler::loadConfigFromFile (std::string name)
  617. {
  618. std::string paths;
  619. for(auto& p : CResourceHandler::get()->getResourceNames(ResourceID("config/" + name)))
  620. {
  621. paths += p.string() + ", ";
  622. }
  623. paths = paths.substr(0, paths.size() - 2);
  624. logMod->debug("Loading hardcoded features settings from [%s], result:", paths);
  625. settings.data = JsonUtils::assembleFromFiles("config/" + name);
  626. const JsonNode & hardcodedFeatures = settings.data["hardcodedFeatures"];
  627. settings.MAX_HEROES_AVAILABLE_PER_PLAYER = static_cast<int>(hardcodedFeatures["MAX_HEROES_AVAILABLE_PER_PLAYER"].Integer());
  628. logMod->debug("\tMAX_HEROES_AVAILABLE_PER_PLAYER\t%d", settings.MAX_HEROES_AVAILABLE_PER_PLAYER);
  629. settings.MAX_HEROES_ON_MAP_PER_PLAYER = static_cast<int>(hardcodedFeatures["MAX_HEROES_ON_MAP_PER_PLAYER"].Integer());
  630. logMod->debug("\tMAX_HEROES_ON_MAP_PER_PLAYER\t%d", settings.MAX_HEROES_ON_MAP_PER_PLAYER);
  631. settings.CREEP_SIZE = static_cast<int>(hardcodedFeatures["CREEP_SIZE"].Integer());
  632. logMod->debug("\tCREEP_SIZE\t%d", settings.CREEP_SIZE);
  633. settings.WEEKLY_GROWTH = static_cast<int>(hardcodedFeatures["WEEKLY_GROWTH_PERCENT"].Integer());
  634. logMod->debug("\tWEEKLY_GROWTH\t%d", settings.WEEKLY_GROWTH);
  635. settings.NEUTRAL_STACK_EXP = static_cast<int>(hardcodedFeatures["NEUTRAL_STACK_EXP_DAILY"].Integer());
  636. logMod->debug("\tNEUTRAL_STACK_EXP\t%d", settings.NEUTRAL_STACK_EXP);
  637. settings.MAX_BUILDING_PER_TURN = static_cast<int>(hardcodedFeatures["MAX_BUILDING_PER_TURN"].Integer());
  638. logMod->debug("\tMAX_BUILDING_PER_TURN\t%d", settings.MAX_BUILDING_PER_TURN);
  639. settings.DWELLINGS_ACCUMULATE_CREATURES = hardcodedFeatures["DWELLINGS_ACCUMULATE_CREATURES"].Bool();
  640. logMod->debug("\tDWELLINGS_ACCUMULATE_CREATURES\t%d", static_cast<int>(settings.DWELLINGS_ACCUMULATE_CREATURES));
  641. settings.ALL_CREATURES_GET_DOUBLE_MONTHS = hardcodedFeatures["ALL_CREATURES_GET_DOUBLE_MONTHS"].Bool();
  642. logMod->debug("\tALL_CREATURES_GET_DOUBLE_MONTHS\t%d", static_cast<int>(settings.ALL_CREATURES_GET_DOUBLE_MONTHS));
  643. settings.WINNING_HERO_WITH_NO_TROOPS_RETREATS = hardcodedFeatures["WINNING_HERO_WITH_NO_TROOPS_RETREATS"].Bool();
  644. logMod->debug("\tWINNING_HERO_WITH_NO_TROOPS_RETREATS\t%d", static_cast<int>(settings.WINNING_HERO_WITH_NO_TROOPS_RETREATS));
  645. settings.BLACK_MARKET_MONTHLY_ARTIFACTS_CHANGE = hardcodedFeatures["BLACK_MARKET_MONTHLY_ARTIFACTS_CHANGE"].Bool();
  646. logMod->debug("\tBLACK_MARKET_MONTHLY_ARTIFACTS_CHANGE\t%d", static_cast<int>(settings.BLACK_MARKET_MONTHLY_ARTIFACTS_CHANGE));
  647. settings.NO_RANDOM_SPECIAL_WEEKS_AND_MONTHS = hardcodedFeatures["NO_RANDOM_SPECIAL_WEEKS_AND_MONTHS"].Bool();
  648. logMod->debug("\tNO_RANDOM_SPECIAL_WEEKS_AND_MONTHS\t%d", static_cast<int>(settings.NO_RANDOM_SPECIAL_WEEKS_AND_MONTHS));
  649. settings.ATTACK_POINT_DMG_MULTIPLIER = hardcodedFeatures["ATTACK_POINT_DMG_MULTIPLIER"].Float();
  650. logMod->debug("\tATTACK_POINT_DMG_MULTIPLIER\t%f", settings.ATTACK_POINT_DMG_MULTIPLIER);
  651. settings.ATTACK_POINTS_DMG_MULTIPLIER_CAP = hardcodedFeatures["ATTACK_POINTS_DMG_MULTIPLIER_CAP"].Float();
  652. logMod->debug("\tATTACK_POINTS_DMG_MULTIPLIER_CAP\t%f", settings.ATTACK_POINTS_DMG_MULTIPLIER_CAP);
  653. settings.DEFENSE_POINT_DMG_MULTIPLIER = hardcodedFeatures["DEFENSE_POINT_DMG_MULTIPLIER"].Float();
  654. logMod->debug("\tDEFENSE_POINT_DMG_MULTIPLIER\t%f", settings.DEFENSE_POINT_DMG_MULTIPLIER);
  655. settings.DEFENSE_POINTS_DMG_MULTIPLIER_CAP = hardcodedFeatures["DEFENSE_POINTS_DMG_MULTIPLIER_CAP"].Float();
  656. logMod->debug("\tDEFENSE_POINTS_DMG_MULTIPLIER_CAP\t%f", settings.DEFENSE_POINTS_DMG_MULTIPLIER_CAP);
  657. const JsonNode & gameModules = settings.data["modules"];
  658. modules.STACK_EXP = gameModules["STACK_EXPERIENCE"].Bool();
  659. logMod->debug("\tSTACK_EXP\t%d", static_cast<int>(modules.STACK_EXP));
  660. modules.STACK_ARTIFACT = gameModules["STACK_ARTIFACTS"].Bool();
  661. logMod->debug("\tSTACK_ARTIFACT\t%d", static_cast<int>(modules.STACK_ARTIFACT));
  662. modules.COMMANDERS = gameModules["COMMANDERS"].Bool();
  663. logMod->debug("\tCOMMANDERS\t%d", static_cast<int>(modules.COMMANDERS));
  664. modules.MITHRIL = gameModules["MITHRIL"].Bool();
  665. logMod->debug("\tMITHRIL\t%d", static_cast<int>(modules.MITHRIL));
  666. }
  667. // currentList is passed by value to get current list of depending mods
  668. bool CModHandler::hasCircularDependency(TModID modID, std::set <TModID> currentList) const
  669. {
  670. const CModInfo & mod = allMods.at(modID);
  671. // Mod already present? We found a loop
  672. if (vstd::contains(currentList, modID))
  673. {
  674. logMod->error("Error: Circular dependency detected! Printing dependency list:");
  675. logMod->error("\t%s -> ", mod.name);
  676. return true;
  677. }
  678. currentList.insert(modID);
  679. // recursively check every dependency of this mod
  680. for(const TModID & dependency : mod.dependencies)
  681. {
  682. if (hasCircularDependency(dependency, currentList))
  683. {
  684. logMod->error("\t%s ->\n", mod.name); // conflict detected, print dependency list
  685. return true;
  686. }
  687. }
  688. return false;
  689. }
  690. bool CModHandler::checkDependencies(const std::vector <TModID> & input) const
  691. {
  692. for(const TModID & id : input)
  693. {
  694. const CModInfo & mod = allMods.at(id);
  695. for(const TModID & dep : mod.dependencies)
  696. {
  697. if(!vstd::contains(input, dep))
  698. {
  699. logMod->error("Error: Mod %s requires missing %s!", mod.name, dep);
  700. return false;
  701. }
  702. }
  703. for(const TModID & conflicting : mod.conflicts)
  704. {
  705. if(vstd::contains(input, conflicting))
  706. {
  707. logMod->error("Error: Mod %s conflicts with %s!", mod.name, allMods.at(conflicting).name);
  708. return false;
  709. }
  710. }
  711. if(hasCircularDependency(id))
  712. return false;
  713. }
  714. return true;
  715. }
  716. // Returned vector affects the resource loaders call order (see CFilesystemList::load).
  717. // The loaders call order matters when dependent mod overrides resources in its dependencies.
  718. std::vector <TModID> CModHandler::validateAndSortDependencies(std::vector <TModID> modsToResolve) const
  719. {
  720. // Topological sort algorithm.
  721. // TODO: Investigate possible ways to improve performance.
  722. boost::range::sort(modsToResolve); // Sort mods per name
  723. std::vector <TModID> sortedValidMods; // Vector keeps order of elements (LIFO)
  724. sortedValidMods.reserve(modsToResolve.size()); // push_back calls won't cause memory reallocation
  725. std::set <TModID> resolvedModIDs; // Use a set for validation for performance reason, but set does not keep order of elements
  726. // Mod is resolved if it has not dependencies or all its dependencies are already resolved
  727. auto isResolved = [&](const CModInfo & mod) -> CModInfo::EValidationStatus
  728. {
  729. if(mod.dependencies.size() > resolvedModIDs.size())
  730. return CModInfo::PENDING;
  731. for(const TModID & dependency : mod.dependencies)
  732. {
  733. if(!vstd::contains(resolvedModIDs, dependency))
  734. return CModInfo::PENDING;
  735. }
  736. return CModInfo::PASSED;
  737. };
  738. while(true)
  739. {
  740. std::set <TModID> resolvedOnCurrentTreeLevel;
  741. for(auto it = modsToResolve.begin(); it != modsToResolve.end();) // One iteration - one level of mods tree
  742. {
  743. if(isResolved(allMods.at(*it)) == CModInfo::PASSED)
  744. {
  745. resolvedOnCurrentTreeLevel.insert(*it); // Not to the resolvedModIDs, so current node childs will be resolved on the next iteration
  746. sortedValidMods.push_back(*it);
  747. it = modsToResolve.erase(it);
  748. continue;
  749. }
  750. it++;
  751. }
  752. if(resolvedOnCurrentTreeLevel.size())
  753. {
  754. resolvedModIDs.insert(resolvedOnCurrentTreeLevel.begin(), resolvedOnCurrentTreeLevel.end());
  755. continue;
  756. }
  757. // If there're no valid mods on the current mods tree level, no more mod can be resolved, should be end.
  758. break;
  759. }
  760. // Left mods have unresolved dependencies, output all to log.
  761. for(const auto & brokenModID : modsToResolve)
  762. {
  763. const CModInfo & brokenMod = allMods.at(brokenModID);
  764. for(const TModID & dependency : brokenMod.dependencies)
  765. {
  766. if(!vstd::contains(resolvedModIDs, dependency))
  767. logMod->error("Mod '%s' will not work: it depends on mod '%s', which is not installed.", brokenMod.name, dependency);
  768. }
  769. }
  770. return sortedValidMods;
  771. }
  772. std::vector<std::string> CModHandler::getModList(std::string path)
  773. {
  774. std::string modDir = boost::to_upper_copy(path + "MODS/");
  775. size_t depth = boost::range::count(modDir, '/');
  776. auto list = CResourceHandler::get("initial")->getFilteredFiles([&](const ResourceID & id) -> bool
  777. {
  778. if (id.getType() != EResType::DIRECTORY)
  779. return false;
  780. if (!boost::algorithm::starts_with(id.getName(), modDir))
  781. return false;
  782. if (boost::range::count(id.getName(), '/') != depth )
  783. return false;
  784. return true;
  785. });
  786. //storage for found mods
  787. std::vector<std::string> foundMods;
  788. for (auto & entry : list)
  789. {
  790. std::string name = entry.getName();
  791. name.erase(0, modDir.size()); //Remove path prefix
  792. if (!name.empty())
  793. foundMods.push_back(name);
  794. }
  795. return foundMods;
  796. }
  797. bool CModHandler::isScopeReserved(const TModID & scope)
  798. {
  799. static const std::array<TModID, 3> reservedScopes = {
  800. "core", "map", "game"
  801. };
  802. return std::find(reservedScopes.begin(), reservedScopes.end(), scope) != reservedScopes.end();
  803. }
  804. const TModID & CModHandler::scopeBuiltin()
  805. {
  806. static const TModID scope = "core";
  807. return scope;
  808. }
  809. const TModID & CModHandler::scopeGame()
  810. {
  811. static const TModID scope = "game";
  812. return scope;
  813. }
  814. const TModID & CModHandler::scopeMap()
  815. {
  816. //TODO: implement accessing map dependencies for both H3 and VCMI maps
  817. // for now, allow access to any identifiers
  818. static const TModID scope = "game";
  819. return scope;
  820. }
  821. void CModHandler::loadMods(std::string path, std::string parent, const JsonNode & modSettings, bool enableMods)
  822. {
  823. for(std::string modName : getModList(path))
  824. loadOneMod(modName, parent, modSettings, enableMods);
  825. }
  826. void CModHandler::loadOneMod(std::string modName, std::string parent, const JsonNode & modSettings, bool enableMods)
  827. {
  828. boost::to_lower(modName);
  829. std::string modFullName = parent.empty() ? modName : parent + '.' + modName;
  830. if ( isScopeReserved(modFullName))
  831. {
  832. logMod->error("Can not load mod %s - this name is reserved for internal use!", modFullName);
  833. return;
  834. }
  835. if(CResourceHandler::get("initial")->existsResource(ResourceID(CModInfo::getModFile(modFullName))))
  836. {
  837. CModInfo mod(modFullName, modSettings[modName], JsonNode(ResourceID(CModInfo::getModFile(modFullName))));
  838. if (!parent.empty()) // this is submod, add parent to dependencies
  839. mod.dependencies.insert(parent);
  840. allMods[modFullName] = mod;
  841. if (mod.enabled && enableMods)
  842. activeMods.push_back(modFullName);
  843. loadMods(CModInfo::getModDir(modFullName) + '/', modFullName, modSettings[modName]["mods"], enableMods && mod.enabled);
  844. }
  845. }
  846. void CModHandler::loadMods(bool onlyEssential)
  847. {
  848. JsonNode modConfig;
  849. if(onlyEssential)
  850. {
  851. loadOneMod("vcmi", "", modConfig, true);//only vcmi and submods
  852. }
  853. else
  854. {
  855. modConfig = loadModSettings("config/modSettings.json");
  856. loadMods("", "", modConfig["activeMods"], true);
  857. }
  858. coreMod = CModInfo(CModHandler::scopeBuiltin(), modConfig[CModHandler::scopeBuiltin()], JsonNode(ResourceID("config/gameConfig.json")));
  859. coreMod.name = "Original game files";
  860. }
  861. std::vector<std::string> CModHandler::getAllMods()
  862. {
  863. std::vector<std::string> modlist;
  864. for (auto & entry : allMods)
  865. modlist.push_back(entry.first);
  866. return modlist;
  867. }
  868. std::vector<std::string> CModHandler::getActiveMods()
  869. {
  870. return activeMods;
  871. }
  872. static JsonNode genDefaultFS()
  873. {
  874. // default FS config for mods: directory "Content" that acts as H3 root directory
  875. JsonNode defaultFS;
  876. defaultFS[""].Vector().resize(2);
  877. defaultFS[""].Vector()[0]["type"].String() = "zip";
  878. defaultFS[""].Vector()[0]["path"].String() = "/Content.zip";
  879. defaultFS[""].Vector()[1]["type"].String() = "dir";
  880. defaultFS[""].Vector()[1]["path"].String() = "/Content";
  881. return defaultFS;
  882. }
  883. static ISimpleResourceLoader * genModFilesystem(const std::string & modName, const JsonNode & conf)
  884. {
  885. static const JsonNode defaultFS = genDefaultFS();
  886. if (!conf["filesystem"].isNull())
  887. return CResourceHandler::createFileSystem(CModInfo::getModDir(modName), conf["filesystem"]);
  888. else
  889. return CResourceHandler::createFileSystem(CModInfo::getModDir(modName), defaultFS);
  890. }
  891. static ui32 calculateModChecksum(const std::string modName, ISimpleResourceLoader * filesystem)
  892. {
  893. boost::crc_32_type modChecksum;
  894. // first - add current VCMI version into checksum to force re-validation on VCMI updates
  895. modChecksum.process_bytes(reinterpret_cast<const void*>(GameConstants::VCMI_VERSION.data()), GameConstants::VCMI_VERSION.size());
  896. // second - add mod.json into checksum because filesystem does not contains this file
  897. // FIXME: remove workaround for core mod
  898. if (modName != CModHandler::scopeBuiltin())
  899. {
  900. ResourceID modConfFile(CModInfo::getModFile(modName), EResType::TEXT);
  901. ui32 configChecksum = CResourceHandler::get("initial")->load(modConfFile)->calculateCRC32();
  902. modChecksum.process_bytes(reinterpret_cast<const void *>(&configChecksum), sizeof(configChecksum));
  903. }
  904. // third - add all detected text files from this mod into checksum
  905. auto files = filesystem->getFilteredFiles([](const ResourceID & resID)
  906. {
  907. return resID.getType() == EResType::TEXT &&
  908. ( boost::starts_with(resID.getName(), "DATA") ||
  909. boost::starts_with(resID.getName(), "CONFIG"));
  910. });
  911. for (const ResourceID & file : files)
  912. {
  913. ui32 fileChecksum = filesystem->load(file)->calculateCRC32();
  914. modChecksum.process_bytes(reinterpret_cast<const void *>(&fileChecksum), sizeof(fileChecksum));
  915. }
  916. return modChecksum.checksum();
  917. }
  918. void CModHandler::loadModFilesystems()
  919. {
  920. activeMods = validateAndSortDependencies(activeMods);
  921. coreMod.updateChecksum(calculateModChecksum(CModHandler::scopeBuiltin(), CResourceHandler::get(CModHandler::scopeBuiltin())));
  922. for(std::string & modName : activeMods)
  923. {
  924. CModInfo & mod = allMods[modName];
  925. CResourceHandler::addFilesystem("data", modName, genModFilesystem(modName, mod.config));
  926. }
  927. }
  928. std::set<TModID> CModHandler::getModDependencies(TModID modId, bool & isModFound)
  929. {
  930. auto it = allMods.find(modId);
  931. isModFound = (it != allMods.end());
  932. if(isModFound)
  933. return it->second.dependencies;
  934. logMod->error("Mod not found: '%s'", modId);
  935. return std::set<TModID>();
  936. }
  937. void CModHandler::initializeConfig()
  938. {
  939. loadConfigFromFile("defaultMods.json");
  940. }
  941. void CModHandler::load()
  942. {
  943. CStopWatch totalTime, timer;
  944. logMod->info("\tInitializing content handler: %d ms", timer.getDiff());
  945. content->init();
  946. for(const TModID & modName : activeMods)
  947. {
  948. logMod->trace("Generating checksum for %s", modName);
  949. allMods[modName].updateChecksum(calculateModChecksum(modName, CResourceHandler::get(modName)));
  950. }
  951. // first - load virtual builtin mod that contains all data
  952. // TODO? move all data into real mods? RoE, AB, SoD, WoG
  953. content->preloadData(coreMod);
  954. for(const TModID & modName : activeMods)
  955. content->preloadData(allMods[modName]);
  956. logMod->info("\tParsing mod data: %d ms", timer.getDiff());
  957. content->load(coreMod);
  958. for(const TModID & modName : activeMods)
  959. content->load(allMods[modName]);
  960. #if SCRIPTING_ENABLED
  961. VLC->scriptHandler->performRegistration(VLC);//todo: this should be done before any other handlers load
  962. #endif
  963. content->loadCustom();
  964. logMod->info("\tLoading mod data: %d ms", timer.getDiff());
  965. VLC->creh->loadCrExpBon();
  966. VLC->creh->buildBonusTreeForTiers(); //do that after all new creatures are loaded
  967. identifiers.finalize();
  968. logMod->info("\tResolving identifiers: %d ms", timer.getDiff());
  969. content->afterLoadFinalization();
  970. logMod->info("\tHandlers post-load finalization: %d ms ", timer.getDiff());
  971. logMod->info("\tAll game content loaded in %d ms", totalTime.getDiff());
  972. }
  973. void CModHandler::afterLoad(bool onlyEssential)
  974. {
  975. JsonNode modSettings;
  976. for (auto & modEntry : allMods)
  977. {
  978. std::string pointer = "/" + boost::algorithm::replace_all_copy(modEntry.first, ".", "/mods/");
  979. modSettings["activeMods"].resolvePointer(pointer) = modEntry.second.saveLocalData();
  980. }
  981. modSettings[CModHandler::scopeBuiltin()] = coreMod.saveLocalData();
  982. if(!onlyEssential)
  983. {
  984. FileStream file(*CResourceHandler::get()->getResourceName(ResourceID("config/modSettings.json")), std::ofstream::out | std::ofstream::trunc);
  985. file << modSettings.toJson();
  986. }
  987. }
  988. std::string CModHandler::normalizeIdentifier(const std::string & scope, const std::string & remoteScope, const std::string & identifier)
  989. {
  990. auto p = vstd::splitStringToPair(identifier, ':');
  991. if(p.first.empty())
  992. p.first = scope;
  993. if(p.first == remoteScope)
  994. p.first.clear();
  995. return p.first.empty() ? p.second : p.first + ":" + p.second;
  996. }
  997. void CModHandler::parseIdentifier(const std::string & fullIdentifier, std::string & scope, std::string & type, std::string & identifier)
  998. {
  999. auto p = vstd::splitStringToPair(fullIdentifier, ':');
  1000. scope = p.first;
  1001. auto p2 = vstd::splitStringToPair(p.second, '.');
  1002. if(p2.first != "")
  1003. {
  1004. type = p2.first;
  1005. identifier = p2.second;
  1006. }
  1007. else
  1008. {
  1009. type = p.second;
  1010. identifier.clear();
  1011. }
  1012. }
  1013. std::string CModHandler::makeFullIdentifier(const std::string & scope, const std::string & type, const std::string & identifier)
  1014. {
  1015. if(type.empty())
  1016. logGlobal->error("Full identifier (%s %s) requires type name", scope, identifier);
  1017. std::string actualScope = scope;
  1018. std::string actualName = identifier;
  1019. //ignore scope if identifier is scoped
  1020. auto scopeAndName = vstd::splitStringToPair(identifier, ':');
  1021. if(scopeAndName.first != "")
  1022. {
  1023. actualScope = scopeAndName.first;
  1024. actualName = scopeAndName.second;
  1025. }
  1026. if(actualScope.empty())
  1027. {
  1028. return actualName.empty() ? type : type + "." + actualName;
  1029. }
  1030. else
  1031. {
  1032. return actualName.empty() ? actualScope+ ":" + type : actualScope + ":" + type + "." + actualName;
  1033. }
  1034. }
  1035. VCMI_LIB_NAMESPACE_END