CModHandler.cpp 42 KB

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