CModHandler.cpp 40 KB

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