2
0

IdentifierStorage.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. /*
  2. * IdentifierStorage.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 "IdentifierStorage.h"
  12. #include "CModHandler.h"
  13. #include "ModScope.h"
  14. #include "../JsonNode.h"
  15. #include "../VCMI_Lib.h"
  16. #include "../constants/StringConstants.h"
  17. #include "../spells/CSpellHandler.h"
  18. #include <vstd/StringUtils.h>
  19. VCMI_LIB_NAMESPACE_BEGIN
  20. CIdentifierStorage::CIdentifierStorage()
  21. {
  22. //TODO: moddable spell schools
  23. for (auto i = 0; i < GameConstants::DEFAULT_SCHOOLS; ++i)
  24. registerObject(ModScope::scopeBuiltin(), "spellSchool", SpellConfig::SCHOOL[i].jsonName, SpellConfig::SCHOOL[i].id);
  25. registerObject(ModScope::scopeBuiltin(), "spellSchool", "any", SpellSchool(SpellSchool::ANY));
  26. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; ++i)
  27. registerObject(ModScope::scopeBuiltin(), "resource", GameConstants::RESOURCE_NAMES[i], i);
  28. for (int i = 0; i < std::size(GameConstants::PLAYER_COLOR_NAMES); ++i)
  29. registerObject(ModScope::scopeBuiltin(), "playerColor", GameConstants::PLAYER_COLOR_NAMES[i], i);
  30. for(int i=0; i<GameConstants::PRIMARY_SKILLS; ++i)
  31. {
  32. registerObject(ModScope::scopeBuiltin(), "primSkill", NPrimarySkill::names[i], i);
  33. registerObject(ModScope::scopeBuiltin(), "primarySkill", NPrimarySkill::names[i], i);
  34. }
  35. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "creatureDamageBoth", 0);
  36. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "creatureDamageMin", 1);
  37. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "creatureDamageMax", 2);
  38. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "damageTypeAll", -1);
  39. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "damageTypeMelee", 0);
  40. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "damageTypeRanged", 1);
  41. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "heroMovementLand", 1);
  42. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "heroMovementSea", 0);
  43. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "deathStareGorgon", 0);
  44. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "deathStareCommander", 1);
  45. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "rebirthRegular", 0);
  46. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "rebirthSpecial", 1);
  47. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "visionsMonsters", 0);
  48. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "visionsHeroes", 1);
  49. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "visionsTowns", 2);
  50. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "immunityBattleWide", 0);
  51. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "immunityEnemyHero", 1);
  52. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "transmutationPerHealth", 0);
  53. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "transmutationPerUnit", 1);
  54. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "destructionKillPercentage", 0);
  55. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "destructionKillAmount", 1);
  56. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "soulStealPermanent", 0);
  57. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "soulStealBattle", 1);
  58. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "movementFlying", 0);
  59. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "movementTeleporting", 1);
  60. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "spellLevel1", 1);
  61. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "spellLevel2", 2);
  62. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "spellLevel3", 3);
  63. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "spellLevel4", 4);
  64. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "spellLevel5", 5);
  65. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "creatureLevel1", 1);
  66. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "creatureLevel2", 2);
  67. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "creatureLevel3", 3);
  68. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "creatureLevel4", 4);
  69. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "creatureLevel5", 5);
  70. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "creatureLevel6", 6);
  71. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "creatureLevel7", 7);
  72. }
  73. void CIdentifierStorage::checkIdentifier(std::string & ID)
  74. {
  75. if (boost::algorithm::ends_with(ID, "."))
  76. logMod->warn("BIG WARNING: identifier %s seems to be broken!", ID);
  77. else
  78. {
  79. size_t pos = 0;
  80. do
  81. {
  82. if (std::tolower(ID[pos]) != ID[pos] ) //Not in camelCase
  83. {
  84. logMod->warn("Warning: identifier %s is not in camelCase!", ID);
  85. ID[pos] = std::tolower(ID[pos]);// Try to fix the ID
  86. }
  87. pos = ID.find('.', pos);
  88. }
  89. while(pos++ != std::string::npos);
  90. }
  91. }
  92. void CIdentifierStorage::requestIdentifier(ObjectCallback callback) const
  93. {
  94. checkIdentifier(callback.type);
  95. checkIdentifier(callback.name);
  96. assert(!callback.localScope.empty());
  97. if (state != ELoadingState::FINISHED) // enqueue request if loading is still in progress
  98. scheduledRequests.push_back(callback);
  99. else // execute immediately for "late" requests
  100. resolveIdentifier(callback);
  101. }
  102. CIdentifierStorage::ObjectCallback CIdentifierStorage::ObjectCallback::fromNameWithType(const std::string & scope, const std::string & fullName, const std::function<void(si32)> & callback, bool optional)
  103. {
  104. assert(!scope.empty());
  105. auto scopeAndFullName = vstd::splitStringToPair(fullName, ':');
  106. auto typeAndName = vstd::splitStringToPair(scopeAndFullName.second, '.');
  107. if (scope == scopeAndFullName.first)
  108. logMod->debug("Target scope for identifier '%s' is redundant! Identifier already defined in mod '%s'", fullName, scope);
  109. ObjectCallback result;
  110. result.localScope = scope;
  111. result.remoteScope = scopeAndFullName.first;
  112. result.type = typeAndName.first;
  113. result.name = typeAndName.second;
  114. result.callback = callback;
  115. result.optional = optional;
  116. return result;
  117. }
  118. 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)
  119. {
  120. assert(!scope.empty());
  121. auto scopeAndFullName = vstd::splitStringToPair(fullName, ':');
  122. auto typeAndName = vstd::splitStringToPair(scopeAndFullName.second, '.');
  123. if(!typeAndName.first.empty())
  124. {
  125. if (typeAndName.first != type)
  126. logMod->warn("Identifier '%s' from mod '%s' requested with different type! Type '%s' expected!", fullName, scope, type);
  127. else
  128. logMod->debug("Target type for identifier '%s' defined in mod '%s' is redundant!", fullName, scope);
  129. }
  130. if (scope == scopeAndFullName.first)
  131. logMod->debug("Target scope for identifier '%s' is redundant! Identifier already defined in mod '%s'", fullName, scope);
  132. ObjectCallback result;
  133. result.localScope = scope;
  134. result.remoteScope = scopeAndFullName.first;
  135. result.type = type;
  136. result.name = typeAndName.second;
  137. result.callback = callback;
  138. result.optional = optional;
  139. return result;
  140. }
  141. void CIdentifierStorage::requestIdentifier(const std::string & scope, const std::string & type, const std::string & name, const std::function<void(si32)> & callback) const
  142. {
  143. requestIdentifier(ObjectCallback::fromNameAndType(scope, type, name, callback, false));
  144. }
  145. void CIdentifierStorage::requestIdentifier(const std::string & scope, const std::string & fullName, const std::function<void(si32)> & callback) const
  146. {
  147. requestIdentifier(ObjectCallback::fromNameWithType(scope, fullName, callback, false));
  148. }
  149. void CIdentifierStorage::requestIdentifier(const std::string & type, const JsonNode & name, const std::function<void(si32)> & callback) const
  150. {
  151. requestIdentifier(ObjectCallback::fromNameAndType(name.meta, type, name.String(), callback, false));
  152. }
  153. void CIdentifierStorage::requestIdentifier(const JsonNode & name, const std::function<void(si32)> & callback) const
  154. {
  155. requestIdentifier(ObjectCallback::fromNameWithType(name.meta, name.String(), callback, false));
  156. }
  157. void CIdentifierStorage::tryRequestIdentifier(const std::string & scope, const std::string & type, const std::string & name, const std::function<void(si32)> & callback) const
  158. {
  159. requestIdentifier(ObjectCallback::fromNameAndType(scope, type, name, callback, true));
  160. }
  161. void CIdentifierStorage::tryRequestIdentifier(const std::string & type, const JsonNode & name, const std::function<void(si32)> & callback) const
  162. {
  163. requestIdentifier(ObjectCallback::fromNameAndType(name.meta, type, name.String(), callback, true));
  164. }
  165. std::optional<si32> CIdentifierStorage::getIdentifier(const std::string & scope, const std::string & type, const std::string & name, bool silent) const
  166. {
  167. assert(state != ELoadingState::LOADING);
  168. auto idList = getPossibleIdentifiers(ObjectCallback::fromNameAndType(scope, type, name, std::function<void(si32)>(), silent));
  169. if (idList.size() == 1)
  170. return idList.front().id;
  171. if (!silent)
  172. logMod->error("Failed to resolve identifier %s of type %s from mod %s", name , type ,scope);
  173. return std::optional<si32>();
  174. }
  175. std::optional<si32> CIdentifierStorage::getIdentifier(const std::string & type, const JsonNode & name, bool silent) const
  176. {
  177. assert(state != ELoadingState::LOADING);
  178. auto idList = getPossibleIdentifiers(ObjectCallback::fromNameAndType(name.meta, type, name.String(), std::function<void(si32)>(), silent));
  179. if (idList.size() == 1)
  180. return idList.front().id;
  181. if (!silent)
  182. logMod->error("Failed to resolve identifier %s of type %s from mod %s", name.String(), type, name.meta);
  183. return std::optional<si32>();
  184. }
  185. std::optional<si32> CIdentifierStorage::getIdentifier(const JsonNode & name, bool silent) const
  186. {
  187. assert(state != ELoadingState::LOADING);
  188. auto idList = getPossibleIdentifiers(ObjectCallback::fromNameWithType(name.meta, name.String(), std::function<void(si32)>(), silent));
  189. if (idList.size() == 1)
  190. return idList.front().id;
  191. if (!silent)
  192. logMod->error("Failed to resolve identifier %s from mod %s", name.String(), name.meta);
  193. return std::optional<si32>();
  194. }
  195. std::optional<si32> CIdentifierStorage::getIdentifier(const std::string & scope, const std::string & fullName, bool silent) const
  196. {
  197. assert(state != ELoadingState::LOADING);
  198. auto idList = getPossibleIdentifiers(ObjectCallback::fromNameWithType(scope, fullName, std::function<void(si32)>(), silent));
  199. if (idList.size() == 1)
  200. return idList.front().id;
  201. if (!silent)
  202. logMod->error("Failed to resolve identifier %s from mod %s", fullName, scope);
  203. return std::optional<si32>();
  204. }
  205. void CIdentifierStorage::registerObject(const std::string & scope, const std::string & type, const std::string & name, si32 identifier)
  206. {
  207. assert(state != ELoadingState::FINISHED);
  208. ObjectData data;
  209. data.scope = scope;
  210. data.id = identifier;
  211. std::string fullID = type + '.' + name;
  212. checkIdentifier(fullID);
  213. std::pair<const std::string, ObjectData> mapping = std::make_pair(fullID, data);
  214. if(!vstd::containsMapping(registeredObjects, mapping))
  215. {
  216. logMod->trace("registered %s as %s:%s", fullID, scope, identifier);
  217. registeredObjects.insert(mapping);
  218. }
  219. }
  220. std::vector<CIdentifierStorage::ObjectData> CIdentifierStorage::getPossibleIdentifiers(const ObjectCallback & request) const
  221. {
  222. std::set<std::string> allowedScopes;
  223. bool isValidScope = true;
  224. // called have not specified destination mod explicitly
  225. if (request.remoteScope.empty())
  226. {
  227. // special scope that should have access to all in-game objects
  228. if (request.localScope == ModScope::scopeGame())
  229. {
  230. for(const auto & modName : VLC->modh->getActiveMods())
  231. allowedScopes.insert(modName);
  232. }
  233. // normally ID's from all required mods, own mod and virtual built-in mod are allowed
  234. else if(request.localScope != ModScope::scopeBuiltin() && !request.localScope.empty())
  235. {
  236. allowedScopes = VLC->modh->getModDependencies(request.localScope, isValidScope);
  237. if(!isValidScope)
  238. return std::vector<ObjectData>();
  239. allowedScopes.insert(request.localScope);
  240. }
  241. // all mods can access built-in mod
  242. allowedScopes.insert(ModScope::scopeBuiltin());
  243. }
  244. else
  245. {
  246. //if destination mod was specified explicitly, restrict lookup to this mod
  247. if(request.remoteScope == ModScope::scopeBuiltin() )
  248. {
  249. //built-in mod is an implicit dependency for all mods, allow access into it
  250. allowedScopes.insert(request.remoteScope);
  251. }
  252. else if ( request.localScope == ModScope::scopeGame() )
  253. {
  254. // allow access, this is special scope that should have access to all in-game objects
  255. allowedScopes.insert(request.remoteScope);
  256. }
  257. else if(request.remoteScope == request.localScope )
  258. {
  259. // allow self-access
  260. allowedScopes.insert(request.remoteScope);
  261. }
  262. else
  263. {
  264. // allow access only if mod is in our dependencies
  265. auto myDeps = VLC->modh->getModDependencies(request.localScope, isValidScope);
  266. if(!isValidScope)
  267. return std::vector<ObjectData>();
  268. if(myDeps.count(request.remoteScope))
  269. allowedScopes.insert(request.remoteScope);
  270. }
  271. }
  272. std::string fullID = request.type + '.' + request.name;
  273. auto entries = registeredObjects.equal_range(fullID);
  274. if (entries.first != entries.second)
  275. {
  276. std::vector<ObjectData> locatedIDs;
  277. for (auto it = entries.first; it != entries.second; it++)
  278. {
  279. if (vstd::contains(allowedScopes, it->second.scope))
  280. {
  281. locatedIDs.push_back(it->second);
  282. }
  283. }
  284. return locatedIDs;
  285. }
  286. return std::vector<ObjectData>();
  287. }
  288. bool CIdentifierStorage::resolveIdentifier(const ObjectCallback & request) const
  289. {
  290. auto identifiers = getPossibleIdentifiers(request);
  291. if (identifiers.size() == 1) // normally resolved ID
  292. {
  293. request.callback(identifiers.front().id);
  294. return true;
  295. }
  296. if (request.optional && identifiers.empty()) // failed to resolve optinal ID
  297. {
  298. return true;
  299. }
  300. // error found. Try to generate some debug info
  301. if(identifiers.empty())
  302. logMod->error("Unknown identifier!");
  303. else
  304. logMod->error("Ambiguous identifier request!");
  305. logMod->error("Request for %s.%s from mod %s", request.type, request.name, request.localScope);
  306. for(const auto & id : identifiers)
  307. {
  308. logMod->error("\tID is available in mod %s", id.scope);
  309. }
  310. return false;
  311. }
  312. void CIdentifierStorage::finalize()
  313. {
  314. assert(state == ELoadingState::LOADING);
  315. state = ELoadingState::FINALIZING;
  316. bool errorsFound = false;
  317. while ( !scheduledRequests.empty() )
  318. {
  319. // Use local copy since new requests may appear during resolving, invalidating any iterators
  320. auto request = scheduledRequests.back();
  321. scheduledRequests.pop_back();
  322. if (!resolveIdentifier(request))
  323. errorsFound = true;
  324. }
  325. debugDumpIdentifiers();
  326. if (errorsFound)
  327. logMod->error("All known identifiers were dumped into log file");
  328. assert(errorsFound == false);
  329. state = ELoadingState::FINISHED;
  330. }
  331. void CIdentifierStorage::debugDumpIdentifiers()
  332. {
  333. logMod->trace("List of all registered objects:");
  334. std::map<std::string, std::vector<std::string>> objectList;
  335. for(const auto & object : registeredObjects)
  336. {
  337. size_t categoryLength = object.first.find('.');
  338. assert(categoryLength != std::string::npos);
  339. std::string objectCategory = object.first.substr(0, categoryLength);
  340. std::string objectName = object.first.substr(categoryLength + 1);
  341. objectList[objectCategory].push_back("[" + object.second.scope + "] " + objectName);
  342. }
  343. for(auto & category : objectList)
  344. boost::range::sort(category.second);
  345. for(const auto & category : objectList)
  346. {
  347. logMod->trace("");
  348. logMod->trace("### %s", category.first);
  349. logMod->trace("");
  350. for(const auto & entry : category.second)
  351. logMod->trace("- " + entry);
  352. }
  353. }
  354. VCMI_LIB_NAMESPACE_END