CModHandler.cpp 43 KB

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