CModHandler.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272
  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 (vstd::contains(data.Struct(), "index") && !data["index"].isNull())
  355. {
  356. if (modName != "core")
  357. logMod->warn("Mod %s is attempting to load original data! This should be reserved for built-in mod.", modName);
  358. // try to add H3 object data
  359. size_t index = static_cast<size_t>(data["index"].Float());
  360. if(originalData.size() > index)
  361. {
  362. logMod->trace("found original data in loadMod(%s) at index %d", name, index);
  363. JsonUtils::merge(originalData[index], data);
  364. std::swap(originalData[index], data);
  365. originalData[index].clear(); // do not use same data twice (same ID)
  366. }
  367. else
  368. {
  369. logMod->trace("no original data in loadMod(%s) at index %d", name, index);
  370. }
  371. performValidate(data, name);
  372. handler->loadObject(modName, name, data, index);
  373. }
  374. else
  375. {
  376. // normal new object
  377. logMod->trace("no index in loadMod(%s)", name);
  378. performValidate(data,name);
  379. handler->loadObject(modName, name, data);
  380. }
  381. }
  382. return result;
  383. }
  384. void ContentTypeHandler::loadCustom()
  385. {
  386. handler->loadCustom();
  387. }
  388. void ContentTypeHandler::afterLoadFinalization()
  389. {
  390. handler->afterLoadFinalization();
  391. }
  392. void CContentHandler::init()
  393. {
  394. handlers.insert(std::make_pair("heroClasses", ContentTypeHandler(&VLC->heroh->classes, "heroClass")));
  395. handlers.insert(std::make_pair("artifacts", ContentTypeHandler(VLC->arth, "artifact")));
  396. handlers.insert(std::make_pair("creatures", ContentTypeHandler(VLC->creh, "creature")));
  397. handlers.insert(std::make_pair("factions", ContentTypeHandler(VLC->townh, "faction")));
  398. handlers.insert(std::make_pair("objects", ContentTypeHandler(VLC->objtypeh, "object")));
  399. handlers.insert(std::make_pair("heroes", ContentTypeHandler(VLC->heroh, "hero")));
  400. handlers.insert(std::make_pair("spells", ContentTypeHandler(VLC->spellh, "spell")));
  401. handlers.insert(std::make_pair("skills", ContentTypeHandler(VLC->skillh, "skill")));
  402. handlers.insert(std::make_pair("templates", ContentTypeHandler(VLC->tplh, "template")));
  403. #if SCRIPTING_ENABLED
  404. handlers.insert(std::make_pair("scripts", ContentTypeHandler(VLC->scriptHandler, "script")));
  405. #endif
  406. handlers.insert(std::make_pair("battlefields", ContentTypeHandler(VLC->battlefieldsHandler, "battlefield")));
  407. handlers.insert(std::make_pair("terrains", ContentTypeHandler(VLC->terrainTypeHandler, "terrain")));
  408. handlers.insert(std::make_pair("rivers", ContentTypeHandler(VLC->riverTypeHandler, "river")));
  409. handlers.insert(std::make_pair("roads", ContentTypeHandler(VLC->roadTypeHandler, "road")));
  410. handlers.insert(std::make_pair("obstacles", ContentTypeHandler(VLC->obstacleHandler, "obstacle")));
  411. //TODO: any other types of moddables?
  412. }
  413. bool CContentHandler::preloadModData(const std::string & modName, JsonNode modConfig, bool validate)
  414. {
  415. bool result = true;
  416. for(auto & handler : handlers)
  417. {
  418. result &= handler.second.preloadModData(modName, modConfig[handler.first].convertTo<std::vector<std::string> >(), validate);
  419. }
  420. return result;
  421. }
  422. bool CContentHandler::loadMod(const std::string & modName, bool validate)
  423. {
  424. bool result = true;
  425. for(auto & handler : handlers)
  426. {
  427. result &= handler.second.loadMod(modName, validate);
  428. }
  429. return result;
  430. }
  431. void CContentHandler::loadCustom()
  432. {
  433. for(auto & handler : handlers)
  434. {
  435. handler.second.loadCustom();
  436. }
  437. }
  438. void CContentHandler::afterLoadFinalization()
  439. {
  440. for(auto & handler : handlers)
  441. {
  442. handler.second.afterLoadFinalization();
  443. }
  444. }
  445. void CContentHandler::preloadData(CModInfo & mod)
  446. {
  447. bool validate = (mod.validation != CModInfo::PASSED);
  448. // print message in format [<8-symbols checksum>] <modname>
  449. logMod->info("\t\t[%08x]%s", mod.checksum, mod.name);
  450. if (validate && mod.identifier != CModHandler::scopeBuiltin())
  451. {
  452. if (!JsonUtils::validate(mod.config, "vcmi:mod", mod.identifier))
  453. mod.validation = CModInfo::FAILED;
  454. }
  455. if (!preloadModData(mod.identifier, mod.config, validate))
  456. mod.validation = CModInfo::FAILED;
  457. }
  458. void CContentHandler::load(CModInfo & mod)
  459. {
  460. bool validate = (mod.validation != CModInfo::PASSED);
  461. if (!loadMod(mod.identifier, validate))
  462. mod.validation = CModInfo::FAILED;
  463. if (validate)
  464. {
  465. if (mod.validation != CModInfo::FAILED)
  466. logMod->info("\t\t[DONE] %s", mod.name);
  467. else
  468. logMod->error("\t\t[FAIL] %s", mod.name);
  469. }
  470. else
  471. logMod->info("\t\t[SKIP] %s", mod.name);
  472. }
  473. const ContentTypeHandler & CContentHandler::operator[](const std::string & name) const
  474. {
  475. return handlers.at(name);
  476. }
  477. static JsonNode loadModSettings(const std::string & path)
  478. {
  479. if (CResourceHandler::get("local")->existsResource(ResourceID(path)))
  480. {
  481. return JsonNode(ResourceID(path, EResType::TEXT));
  482. }
  483. // Probably new install. Create initial configuration
  484. CResourceHandler::get("local")->createResource(path);
  485. return JsonNode();
  486. }
  487. JsonNode addMeta(JsonNode config, const std::string & meta)
  488. {
  489. config.setMeta(meta);
  490. return config;
  491. }
  492. CModInfo::Version CModInfo::Version::GameVersion()
  493. {
  494. return Version(VCMI_VERSION_MAJOR, VCMI_VERSION_MINOR, VCMI_VERSION_PATCH);
  495. }
  496. CModInfo::Version CModInfo::Version::fromString(std::string from)
  497. {
  498. int major = 0;
  499. int minor = 0;
  500. int patch = 0;
  501. try
  502. {
  503. auto pointPos = from.find('.');
  504. major = std::stoi(from.substr(0, pointPos));
  505. if(pointPos != std::string::npos)
  506. {
  507. from = from.substr(pointPos + 1);
  508. pointPos = from.find('.');
  509. minor = std::stoi(from.substr(0, pointPos));
  510. if(pointPos != std::string::npos)
  511. patch = std::stoi(from.substr(pointPos + 1));
  512. }
  513. }
  514. catch(const std::invalid_argument &)
  515. {
  516. return Version();
  517. }
  518. return Version(major, minor, patch);
  519. }
  520. std::string CModInfo::Version::toString() const
  521. {
  522. return std::to_string(major) + '.' + std::to_string(minor) + '.' + std::to_string(patch);
  523. }
  524. bool CModInfo::Version::compatible(const Version & other, bool checkMinor, bool checkPatch) const
  525. {
  526. return (major == other.major &&
  527. (!checkMinor || minor >= other.minor) &&
  528. (!checkPatch || minor > other.minor || (minor == other.minor && patch >= other.patch)));
  529. }
  530. bool CModInfo::Version::isNull() const
  531. {
  532. return major == 0 && minor == 0 && patch == 0;
  533. }
  534. CModInfo::CModInfo():
  535. checksum(0),
  536. explicitlyEnabled(false),
  537. implicitlyEnabled(true),
  538. validation(PENDING)
  539. {
  540. }
  541. CModInfo::CModInfo(const std::string & identifier, const JsonNode & local, const JsonNode & config):
  542. identifier(identifier),
  543. name(config["name"].String()),
  544. description(config["description"].String()),
  545. dependencies(config["depends"].convertTo<std::set<std::string>>()),
  546. conflicts(config["conflicts"].convertTo<std::set<std::string>>()),
  547. checksum(0),
  548. explicitlyEnabled(false),
  549. implicitlyEnabled(true),
  550. validation(PENDING),
  551. config(addMeta(config, identifier))
  552. {
  553. version = Version::fromString(config["version"].String());
  554. if(!config["compatibility"].isNull())
  555. {
  556. vcmiCompatibleMin = Version::fromString(config["compatibility"]["min"].String());
  557. vcmiCompatibleMax = Version::fromString(config["compatibility"]["max"].String());
  558. }
  559. if (!config["language"].isNull())
  560. baseLanguage = config["language"].String();
  561. else
  562. baseLanguage = "english";
  563. loadLocalData(local);
  564. }
  565. JsonNode CModInfo::saveLocalData() const
  566. {
  567. std::ostringstream stream;
  568. stream << std::noshowbase << std::hex << std::setw(8) << std::setfill('0') << checksum;
  569. JsonNode conf;
  570. conf["active"].Bool() = explicitlyEnabled;
  571. conf["validated"].Bool() = validation != FAILED;
  572. conf["checksum"].String() = stream.str();
  573. return conf;
  574. }
  575. std::string CModInfo::getModDir(const std::string & name)
  576. {
  577. return "MODS/" + boost::algorithm::replace_all_copy(name, ".", "/MODS/");
  578. }
  579. std::string CModInfo::getModFile(const std::string & name)
  580. {
  581. return getModDir(name) + "/mod.json";
  582. }
  583. void CModInfo::updateChecksum(ui32 newChecksum)
  584. {
  585. // comment-out next line to force validation of all mods ignoring checksum
  586. if (newChecksum != checksum)
  587. {
  588. checksum = newChecksum;
  589. validation = PENDING;
  590. }
  591. }
  592. void CModInfo::loadLocalData(const JsonNode & data)
  593. {
  594. bool validated = false;
  595. implicitlyEnabled = true;
  596. explicitlyEnabled = !config["keepDisabled"].Bool();
  597. checksum = 0;
  598. if (data.getType() == JsonNode::JsonType::DATA_BOOL)
  599. {
  600. explicitlyEnabled = data.Bool();
  601. }
  602. if (data.getType() == JsonNode::JsonType::DATA_STRUCT)
  603. {
  604. explicitlyEnabled = data["active"].Bool();
  605. validated = data["validated"].Bool();
  606. checksum = strtol(data["checksum"].String().c_str(), nullptr, 16);
  607. }
  608. //check compatibility
  609. implicitlyEnabled &= (vcmiCompatibleMin.isNull() || Version::GameVersion().compatible(vcmiCompatibleMin));
  610. implicitlyEnabled &= (vcmiCompatibleMax.isNull() || vcmiCompatibleMax.compatible(Version::GameVersion()));
  611. if(!implicitlyEnabled)
  612. logGlobal->warn("Mod %s is incompatible with current version of VCMI and cannot be enabled", name);
  613. if (boost::iequals(config["modType"].String(), "translation")) // compatibility code - mods use "Translation" type at the moment
  614. {
  615. if (baseLanguage != VLC->generaltexth->getPreferredLanguage())
  616. {
  617. logGlobal->warn("Translation mod %s was not loaded: language mismatch!", name);
  618. implicitlyEnabled = false;
  619. }
  620. }
  621. if (isEnabled())
  622. validation = validated ? PASSED : PENDING;
  623. else
  624. validation = validated ? PASSED : FAILED;
  625. }
  626. bool CModInfo::isEnabled() const
  627. {
  628. return implicitlyEnabled && explicitlyEnabled;
  629. }
  630. void CModInfo::setEnabled(bool on)
  631. {
  632. explicitlyEnabled = on;
  633. }
  634. CModHandler::CModHandler() : content(std::make_shared<CContentHandler>())
  635. {
  636. //TODO: moddable spell schools
  637. for (auto i = 0; i < GameConstants::DEFAULT_SCHOOLS; ++i)
  638. identifiers.registerObject(CModHandler::scopeBuiltin(), "spellSchool", SpellConfig::SCHOOL[i].jsonName, SpellConfig::SCHOOL[i].id);
  639. identifiers.registerObject(CModHandler::scopeBuiltin(), "spellSchool", "any", SpellSchool(ESpellSchool::ANY));
  640. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; ++i)
  641. {
  642. identifiers.registerObject(CModHandler::scopeBuiltin(), "resource", GameConstants::RESOURCE_NAMES[i], i);
  643. }
  644. for(int i=0; i<GameConstants::PRIMARY_SKILLS; ++i)
  645. {
  646. identifiers.registerObject(CModHandler::scopeBuiltin(), "primSkill", PrimarySkill::names[i], i);
  647. identifiers.registerObject(CModHandler::scopeBuiltin(), "primarySkill", PrimarySkill::names[i], i);
  648. }
  649. }
  650. // currentList is passed by value to get current list of depending mods
  651. bool CModHandler::hasCircularDependency(const TModID & modID, std::set<TModID> currentList) const
  652. {
  653. const CModInfo & mod = allMods.at(modID);
  654. // Mod already present? We found a loop
  655. if (vstd::contains(currentList, modID))
  656. {
  657. logMod->error("Error: Circular dependency detected! Printing dependency list:");
  658. logMod->error("\t%s -> ", mod.name);
  659. return true;
  660. }
  661. currentList.insert(modID);
  662. // recursively check every dependency of this mod
  663. for(const TModID & dependency : mod.dependencies)
  664. {
  665. if (hasCircularDependency(dependency, currentList))
  666. {
  667. logMod->error("\t%s ->\n", mod.name); // conflict detected, print dependency list
  668. return true;
  669. }
  670. }
  671. return false;
  672. }
  673. // Returned vector affects the resource loaders call order (see CFilesystemList::load).
  674. // The loaders call order matters when dependent mod overrides resources in its dependencies.
  675. std::vector <TModID> CModHandler::validateAndSortDependencies(std::vector <TModID> modsToResolve) const
  676. {
  677. // Topological sort algorithm.
  678. // TODO: Investigate possible ways to improve performance.
  679. boost::range::sort(modsToResolve); // Sort mods per name
  680. std::vector <TModID> sortedValidMods; // Vector keeps order of elements (LIFO)
  681. sortedValidMods.reserve(modsToResolve.size()); // push_back calls won't cause memory reallocation
  682. std::set <TModID> resolvedModIDs; // Use a set for validation for performance reason, but set does not keep order of elements
  683. // Mod is resolved if it has not dependencies or all its dependencies are already resolved
  684. auto isResolved = [&](const CModInfo & mod) -> CModInfo::EValidationStatus
  685. {
  686. if(mod.dependencies.size() > resolvedModIDs.size())
  687. return CModInfo::PENDING;
  688. for(const TModID & dependency : mod.dependencies)
  689. {
  690. if(!vstd::contains(resolvedModIDs, dependency))
  691. return CModInfo::PENDING;
  692. }
  693. return CModInfo::PASSED;
  694. };
  695. while(true)
  696. {
  697. std::set <TModID> resolvedOnCurrentTreeLevel;
  698. for(auto it = modsToResolve.begin(); it != modsToResolve.end();) // One iteration - one level of mods tree
  699. {
  700. if(isResolved(allMods.at(*it)) == CModInfo::PASSED)
  701. {
  702. resolvedOnCurrentTreeLevel.insert(*it); // Not to the resolvedModIDs, so current node childs will be resolved on the next iteration
  703. sortedValidMods.push_back(*it);
  704. it = modsToResolve.erase(it);
  705. continue;
  706. }
  707. it++;
  708. }
  709. if(!resolvedOnCurrentTreeLevel.empty())
  710. {
  711. resolvedModIDs.insert(resolvedOnCurrentTreeLevel.begin(), resolvedOnCurrentTreeLevel.end());
  712. continue;
  713. }
  714. // If there're no valid mods on the current mods tree level, no more mod can be resolved, should be end.
  715. break;
  716. }
  717. // Left mods have unresolved dependencies, output all to log.
  718. for(const auto & brokenModID : modsToResolve)
  719. {
  720. const CModInfo & brokenMod = allMods.at(brokenModID);
  721. for(const TModID & dependency : brokenMod.dependencies)
  722. {
  723. if(!vstd::contains(resolvedModIDs, dependency))
  724. logMod->error("Mod '%s' will not work: it depends on mod '%s', which is not installed.", brokenMod.name, dependency);
  725. }
  726. }
  727. return sortedValidMods;
  728. }
  729. std::vector<std::string> CModHandler::getModList(const std::string & path) const
  730. {
  731. std::string modDir = boost::to_upper_copy(path + "MODS/");
  732. size_t depth = boost::range::count(modDir, '/');
  733. auto list = CResourceHandler::get("initial")->getFilteredFiles([&](const ResourceID & id) -> bool
  734. {
  735. if (id.getType() != EResType::DIRECTORY)
  736. return false;
  737. if (!boost::algorithm::starts_with(id.getName(), modDir))
  738. return false;
  739. if (boost::range::count(id.getName(), '/') != depth )
  740. return false;
  741. return true;
  742. });
  743. //storage for found mods
  744. std::vector<std::string> foundMods;
  745. for(const auto & entry : list)
  746. {
  747. std::string name = entry.getName();
  748. name.erase(0, modDir.size()); //Remove path prefix
  749. if (!name.empty())
  750. foundMods.push_back(name);
  751. }
  752. return foundMods;
  753. }
  754. bool CModHandler::isScopeReserved(const TModID & scope)
  755. {
  756. //following scopes are reserved - either in use by mod system or by filesystem
  757. static const std::array<TModID, 9> reservedScopes = {
  758. "core", "map", "game", "root", "saves", "config", "local", "initial", "mapEditor"
  759. };
  760. return std::find(reservedScopes.begin(), reservedScopes.end(), scope) != reservedScopes.end();
  761. }
  762. const TModID & CModHandler::scopeBuiltin()
  763. {
  764. static const TModID scope = "core";
  765. return scope;
  766. }
  767. const TModID & CModHandler::scopeGame()
  768. {
  769. static const TModID scope = "game";
  770. return scope;
  771. }
  772. const TModID & CModHandler::scopeMap()
  773. {
  774. //TODO: implement accessing map dependencies for both H3 and VCMI maps
  775. // for now, allow access to any identifiers
  776. static const TModID scope = "game";
  777. return scope;
  778. }
  779. void CModHandler::loadMods(const std::string & path, const std::string & parent, const JsonNode & modSettings, bool enableMods)
  780. {
  781. for(const std::string & modName : getModList(path))
  782. loadOneMod(modName, parent, modSettings, enableMods);
  783. }
  784. void CModHandler::loadOneMod(std::string modName, const std::string & parent, const JsonNode & modSettings, bool enableMods)
  785. {
  786. boost::to_lower(modName);
  787. std::string modFullName = parent.empty() ? modName : parent + '.' + modName;
  788. if ( isScopeReserved(modFullName))
  789. {
  790. logMod->error("Can not load mod %s - this name is reserved for internal use!", modFullName);
  791. return;
  792. }
  793. if(CResourceHandler::get("initial")->existsResource(ResourceID(CModInfo::getModFile(modFullName))))
  794. {
  795. CModInfo mod(modFullName, modSettings[modName], JsonNode(ResourceID(CModInfo::getModFile(modFullName))));
  796. if (!parent.empty()) // this is submod, add parent to dependencies
  797. mod.dependencies.insert(parent);
  798. allMods[modFullName] = mod;
  799. if (mod.isEnabled() && enableMods)
  800. activeMods.push_back(modFullName);
  801. loadMods(CModInfo::getModDir(modFullName) + '/', modFullName, modSettings[modName]["mods"], enableMods && mod.isEnabled());
  802. }
  803. }
  804. void CModHandler::loadMods(bool onlyEssential)
  805. {
  806. JsonNode modConfig;
  807. if(onlyEssential)
  808. {
  809. loadOneMod("vcmi", "", modConfig, true);//only vcmi and submods
  810. }
  811. else
  812. {
  813. modConfig = loadModSettings("config/modSettings.json");
  814. loadMods("", "", modConfig["activeMods"], true);
  815. }
  816. coreMod = CModInfo(CModHandler::scopeBuiltin(), modConfig[CModHandler::scopeBuiltin()], JsonNode(ResourceID("config/gameConfig.json")));
  817. coreMod.name = "Original game files";
  818. }
  819. std::vector<std::string> CModHandler::getAllMods()
  820. {
  821. std::vector<std::string> modlist;
  822. modlist.reserve(allMods.size());
  823. for (auto & entry : allMods)
  824. modlist.push_back(entry.first);
  825. return modlist;
  826. }
  827. std::vector<std::string> CModHandler::getActiveMods()
  828. {
  829. return activeMods;
  830. }
  831. const CModInfo & CModHandler::getModInfo(const TModID & modId) const
  832. {
  833. return allMods.at(modId);
  834. }
  835. static JsonNode genDefaultFS()
  836. {
  837. // default FS config for mods: directory "Content" that acts as H3 root directory
  838. JsonNode defaultFS;
  839. defaultFS[""].Vector().resize(2);
  840. defaultFS[""].Vector()[0]["type"].String() = "zip";
  841. defaultFS[""].Vector()[0]["path"].String() = "/Content.zip";
  842. defaultFS[""].Vector()[1]["type"].String() = "dir";
  843. defaultFS[""].Vector()[1]["path"].String() = "/Content";
  844. return defaultFS;
  845. }
  846. static ISimpleResourceLoader * genModFilesystem(const std::string & modName, const JsonNode & conf)
  847. {
  848. static const JsonNode defaultFS = genDefaultFS();
  849. if (!conf["filesystem"].isNull())
  850. return CResourceHandler::createFileSystem(CModInfo::getModDir(modName), conf["filesystem"]);
  851. else
  852. return CResourceHandler::createFileSystem(CModInfo::getModDir(modName), defaultFS);
  853. }
  854. static ui32 calculateModChecksum(const std::string & modName, ISimpleResourceLoader * filesystem)
  855. {
  856. boost::crc_32_type modChecksum;
  857. // first - add current VCMI version into checksum to force re-validation on VCMI updates
  858. modChecksum.process_bytes(reinterpret_cast<const void*>(GameConstants::VCMI_VERSION.data()), GameConstants::VCMI_VERSION.size());
  859. // second - add mod.json into checksum because filesystem does not contains this file
  860. // FIXME: remove workaround for core mod
  861. if (modName != CModHandler::scopeBuiltin())
  862. {
  863. ResourceID modConfFile(CModInfo::getModFile(modName), EResType::TEXT);
  864. ui32 configChecksum = CResourceHandler::get("initial")->load(modConfFile)->calculateCRC32();
  865. modChecksum.process_bytes(reinterpret_cast<const void *>(&configChecksum), sizeof(configChecksum));
  866. }
  867. // third - add all detected text files from this mod into checksum
  868. auto files = filesystem->getFilteredFiles([](const ResourceID & resID)
  869. {
  870. return resID.getType() == EResType::TEXT &&
  871. ( boost::starts_with(resID.getName(), "DATA") ||
  872. boost::starts_with(resID.getName(), "CONFIG"));
  873. });
  874. for (const ResourceID & file : files)
  875. {
  876. ui32 fileChecksum = filesystem->load(file)->calculateCRC32();
  877. modChecksum.process_bytes(reinterpret_cast<const void *>(&fileChecksum), sizeof(fileChecksum));
  878. }
  879. return modChecksum.checksum();
  880. }
  881. void CModHandler::loadModFilesystems()
  882. {
  883. CGeneralTextHandler::detectInstallParameters();
  884. activeMods = validateAndSortDependencies(activeMods);
  885. coreMod.updateChecksum(calculateModChecksum(CModHandler::scopeBuiltin(), CResourceHandler::get(CModHandler::scopeBuiltin())));
  886. for(std::string & modName : activeMods)
  887. {
  888. CModInfo & mod = allMods[modName];
  889. CResourceHandler::addFilesystem("data", modName, genModFilesystem(modName, mod.config));
  890. }
  891. }
  892. TModID CModHandler::findResourceOrigin(const ResourceID & name)
  893. {
  894. for(const auto & modID : boost::adaptors::reverse(activeMods))
  895. {
  896. if(CResourceHandler::get(modID)->existsResource(name))
  897. return modID;
  898. }
  899. if(CResourceHandler::get("core")->existsResource(name))
  900. return "core";
  901. if(CResourceHandler::get("mapEditor")->existsResource(name))
  902. return "core"; // Workaround for loading maps via map editor
  903. assert(0);
  904. return "";
  905. }
  906. std::string CModHandler::getModLanguage(const TModID& modId) const
  907. {
  908. if ( modId == "core")
  909. return VLC->generaltexth->getInstalledLanguage();
  910. return allMods.at(modId).baseLanguage;
  911. }
  912. std::set<TModID> CModHandler::getModDependencies(const TModID & modId, bool & isModFound) const
  913. {
  914. auto it = allMods.find(modId);
  915. isModFound = (it != allMods.end());
  916. if(isModFound)
  917. return it->second.dependencies;
  918. logMod->error("Mod not found: '%s'", modId);
  919. return {};
  920. }
  921. void CModHandler::initializeConfig()
  922. {
  923. VLC->settingsHandler->load(coreMod.config["settings"]);
  924. for(const TModID & modName : activeMods)
  925. {
  926. const auto & mod = allMods[modName];
  927. if (!mod.config["settings"].isNull())
  928. VLC->settingsHandler->load(mod.config["settings"]);
  929. }
  930. }
  931. bool CModHandler::validateTranslations(TModID modName) const
  932. {
  933. bool result = true;
  934. const auto & mod = allMods.at(modName);
  935. {
  936. auto fileList = mod.config["translations"].convertTo<std::vector<std::string> >();
  937. JsonNode json = JsonUtils::assembleFromFiles(fileList);
  938. result |= VLC->generaltexth->validateTranslation(mod.baseLanguage, modName, json);
  939. }
  940. for(const auto & language : Languages::getLanguageList())
  941. {
  942. if (!language.hasTranslation)
  943. continue;
  944. if (mod.config[language.identifier].isNull())
  945. continue;
  946. if (mod.config[language.identifier]["skipValidation"].Bool())
  947. continue;
  948. auto fileList = mod.config[language.identifier]["translations"].convertTo<std::vector<std::string> >();
  949. JsonNode json = JsonUtils::assembleFromFiles(fileList);
  950. result |= VLC->generaltexth->validateTranslation(language.identifier, modName, json);
  951. }
  952. return result;
  953. }
  954. void CModHandler::loadTranslation(const TModID & modName)
  955. {
  956. const auto & mod = allMods[modName];
  957. std::string preferredLanguage = VLC->generaltexth->getPreferredLanguage();
  958. std::string modBaseLanguage = allMods[modName].baseLanguage;
  959. auto baseTranslationList = mod.config["translations"].convertTo<std::vector<std::string> >();
  960. auto extraTranslationList = mod.config[preferredLanguage]["translations"].convertTo<std::vector<std::string> >();
  961. JsonNode baseTranslation = JsonUtils::assembleFromFiles(baseTranslationList);
  962. JsonNode extraTranslation = JsonUtils::assembleFromFiles(extraTranslationList);
  963. VLC->generaltexth->loadTranslationOverrides(modBaseLanguage, modName, baseTranslation);
  964. VLC->generaltexth->loadTranslationOverrides(preferredLanguage, modName, extraTranslation);
  965. }
  966. void CModHandler::load()
  967. {
  968. CStopWatch totalTime;
  969. CStopWatch timer;
  970. logMod->info("\tInitializing content handler: %d ms", timer.getDiff());
  971. content->init();
  972. for(const TModID & modName : activeMods)
  973. {
  974. logMod->trace("Generating checksum for %s", modName);
  975. allMods[modName].updateChecksum(calculateModChecksum(modName, CResourceHandler::get(modName)));
  976. }
  977. // first - load virtual builtin mod that contains all data
  978. // TODO? move all data into real mods? RoE, AB, SoD, WoG
  979. content->preloadData(coreMod);
  980. for(const TModID & modName : activeMods)
  981. content->preloadData(allMods[modName]);
  982. logMod->info("\tParsing mod data: %d ms", timer.getDiff());
  983. content->load(coreMod);
  984. for(const TModID & modName : activeMods)
  985. content->load(allMods[modName]);
  986. #if SCRIPTING_ENABLED
  987. VLC->scriptHandler->performRegistration(VLC);//todo: this should be done before any other handlers load
  988. #endif
  989. content->loadCustom();
  990. for(const TModID & modName : activeMods)
  991. loadTranslation(modName);
  992. for(const TModID & modName : activeMods)
  993. if (!validateTranslations(modName))
  994. allMods[modName].validation = CModInfo::FAILED;
  995. logMod->info("\tLoading mod data: %d ms", timer.getDiff());
  996. VLC->creh->loadCrExpMod();
  997. identifiers.finalize();
  998. logMod->info("\tResolving identifiers: %d ms", timer.getDiff());
  999. content->afterLoadFinalization();
  1000. logMod->info("\tHandlers post-load finalization: %d ms ", timer.getDiff());
  1001. logMod->info("\tAll game content loaded in %d ms", totalTime.getDiff());
  1002. }
  1003. void CModHandler::afterLoad(bool onlyEssential)
  1004. {
  1005. JsonNode modSettings;
  1006. for (auto & modEntry : allMods)
  1007. {
  1008. std::string pointer = "/" + boost::algorithm::replace_all_copy(modEntry.first, ".", "/mods/");
  1009. modSettings["activeMods"].resolvePointer(pointer) = modEntry.second.saveLocalData();
  1010. }
  1011. modSettings[CModHandler::scopeBuiltin()] = coreMod.saveLocalData();
  1012. if(!onlyEssential)
  1013. {
  1014. FileStream file(*CResourceHandler::get()->getResourceName(ResourceID("config/modSettings.json")), std::ofstream::out | std::ofstream::trunc);
  1015. file << modSettings.toJson();
  1016. }
  1017. }
  1018. std::string CModHandler::normalizeIdentifier(const std::string & scope, const std::string & remoteScope, const std::string & identifier)
  1019. {
  1020. auto p = vstd::splitStringToPair(identifier, ':');
  1021. if(p.first.empty())
  1022. p.first = scope;
  1023. if(p.first == remoteScope)
  1024. p.first.clear();
  1025. return p.first.empty() ? p.second : p.first + ":" + p.second;
  1026. }
  1027. void CModHandler::parseIdentifier(const std::string & fullIdentifier, std::string & scope, std::string & type, std::string & identifier)
  1028. {
  1029. auto p = vstd::splitStringToPair(fullIdentifier, ':');
  1030. scope = p.first;
  1031. auto p2 = vstd::splitStringToPair(p.second, '.');
  1032. if(!p2.first.empty())
  1033. {
  1034. type = p2.first;
  1035. identifier = p2.second;
  1036. }
  1037. else
  1038. {
  1039. type = p.second;
  1040. identifier.clear();
  1041. }
  1042. }
  1043. std::string CModHandler::makeFullIdentifier(const std::string & scope, const std::string & type, const std::string & identifier)
  1044. {
  1045. if(type.empty())
  1046. logGlobal->error("Full identifier (%s %s) requires type name", scope, identifier);
  1047. std::string actualScope = scope;
  1048. std::string actualName = identifier;
  1049. //ignore scope if identifier is scoped
  1050. auto scopeAndName = vstd::splitStringToPair(identifier, ':');
  1051. if(!scopeAndName.first.empty())
  1052. {
  1053. actualScope = scopeAndName.first;
  1054. actualName = scopeAndName.second;
  1055. }
  1056. if(actualScope.empty())
  1057. {
  1058. return actualName.empty() ? type : type + "." + actualName;
  1059. }
  1060. else
  1061. {
  1062. return actualName.empty() ? actualScope+ ":" + type : actualScope + ":" + type + "." + actualName;
  1063. }
  1064. }
  1065. VCMI_LIB_NAMESPACE_END