CModHandler.cpp 38 KB

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