JsonRandom.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. /*
  2. * JsonRandom.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 "JsonRandom.h"
  12. #include <vstd/StringUtils.h>
  13. #include "JsonNode.h"
  14. #include "CRandomGenerator.h"
  15. #include "constants/StringConstants.h"
  16. #include "VCMI_Lib.h"
  17. #include "CArtHandler.h"
  18. #include "CCreatureHandler.h"
  19. #include "CCreatureSet.h"
  20. #include "spells/CSpellHandler.h"
  21. #include "CSkillHandler.h"
  22. #include "CHeroHandler.h"
  23. #include "IGameCallback.h"
  24. #include "mapObjects/IObjectInterface.h"
  25. #include "modding/IdentifierStorage.h"
  26. #include "modding/ModScope.h"
  27. VCMI_LIB_NAMESPACE_BEGIN
  28. namespace JsonRandom
  29. {
  30. si32 loadValue(const JsonNode & value, CRandomGenerator & rng, si32 defaultValue)
  31. {
  32. if(value.isNull())
  33. return defaultValue;
  34. if(value.isNumber())
  35. return static_cast<si32>(value.Float());
  36. if(value.isVector())
  37. {
  38. const auto & vector = value.Vector();
  39. size_t index= rng.getIntRange(0, vector.size()-1)();
  40. return loadValue(vector[index], rng, 0);
  41. }
  42. if(value.isStruct())
  43. {
  44. if (!value["amount"].isNull())
  45. return static_cast<si32>(loadValue(value["amount"], rng, defaultValue));
  46. si32 min = static_cast<si32>(loadValue(value["min"], rng, 0));
  47. si32 max = static_cast<si32>(loadValue(value["max"], rng, 0));
  48. return rng.getIntRange(min, max)();
  49. }
  50. return defaultValue;
  51. }
  52. std::string loadKey(const JsonNode & value, CRandomGenerator & rng, const std::set<std::string> & valuesSet)
  53. {
  54. if(value.isString())
  55. return value.String();
  56. if(value.isStruct())
  57. {
  58. if(!value["type"].isNull())
  59. return value["type"].String();
  60. if(!value["anyOf"].isNull())
  61. return RandomGeneratorUtil::nextItem(value["anyOf"].Vector(), rng)->String();
  62. if(!value["noneOf"].isNull())
  63. {
  64. auto copyValuesSet = valuesSet;
  65. for(auto & s : value["noneOf"].Vector())
  66. copyValuesSet.erase(s.String());
  67. if(!copyValuesSet.empty())
  68. return *RandomGeneratorUtil::nextItem(copyValuesSet, rng);
  69. }
  70. }
  71. return valuesSet.empty() ? "" : *RandomGeneratorUtil::nextItem(valuesSet, rng);
  72. }
  73. TResources loadResources(const JsonNode & value, CRandomGenerator & rng)
  74. {
  75. TResources ret;
  76. if (value.isVector())
  77. {
  78. for (const auto & entry : value.Vector())
  79. ret += loadResource(entry, rng);
  80. return ret;
  81. }
  82. for (size_t i=0; i<GameConstants::RESOURCE_QUANTITY; i++)
  83. {
  84. ret[i] = loadValue(value[GameConstants::RESOURCE_NAMES[i]], rng);
  85. }
  86. return ret;
  87. }
  88. TResources loadResource(const JsonNode & value, CRandomGenerator & rng)
  89. {
  90. std::set<std::string> defaultResources(std::begin(GameConstants::RESOURCE_NAMES), std::end(GameConstants::RESOURCE_NAMES) - 1); //except mithril
  91. std::string resourceName = loadKey(value, rng, defaultResources);
  92. si32 resourceAmount = loadValue(value, rng, 0);
  93. si32 resourceID(VLC->identifiers()->getIdentifier(value.meta, "resource", resourceName).value());
  94. TResources ret;
  95. ret[resourceID] = resourceAmount;
  96. return ret;
  97. }
  98. std::vector<si32> loadPrimary(const JsonNode & value, CRandomGenerator & rng)
  99. {
  100. std::vector<si32> ret;
  101. if(value.isStruct())
  102. {
  103. for(const auto & name : NPrimarySkill::names)
  104. {
  105. ret.push_back(loadValue(value[name], rng));
  106. }
  107. }
  108. if(value.isVector())
  109. {
  110. ret.resize(GameConstants::PRIMARY_SKILLS, 0);
  111. std::set<std::string> defaultStats(std::begin(NPrimarySkill::names), std::end(NPrimarySkill::names));
  112. for(const auto & element : value.Vector())
  113. {
  114. auto key = loadKey(element, rng, defaultStats);
  115. defaultStats.erase(key);
  116. int id = vstd::find_pos(NPrimarySkill::names, key);
  117. if(id != -1)
  118. ret[id] += loadValue(element, rng);
  119. }
  120. }
  121. return ret;
  122. }
  123. std::map<SecondarySkill, si32> loadSecondary(const JsonNode & value, CRandomGenerator & rng)
  124. {
  125. std::map<SecondarySkill, si32> ret;
  126. if(value.isStruct())
  127. {
  128. for(const auto & pair : value.Struct())
  129. {
  130. SecondarySkill id(VLC->identifiers()->getIdentifier(pair.second.meta, "skill", pair.first).value());
  131. ret[id] = loadValue(pair.second, rng);
  132. }
  133. }
  134. if(value.isVector())
  135. {
  136. std::set<std::string> defaultSkills;
  137. for(const auto & skill : VLC->skillh->objects)
  138. {
  139. IObjectInterface::cb->isAllowed(2, skill->getIndex());
  140. auto scopeAndName = vstd::splitStringToPair(skill->getJsonKey(), ':');
  141. if(scopeAndName.first == ModScope::scopeBuiltin() || scopeAndName.first == value.meta)
  142. defaultSkills.insert(scopeAndName.second);
  143. else
  144. defaultSkills.insert(skill->getJsonKey());
  145. }
  146. for(const auto & element : value.Vector())
  147. {
  148. auto key = loadKey(element, rng, defaultSkills);
  149. defaultSkills.erase(key); //avoid dupicates
  150. if(auto identifier = VLC->identifiers()->getIdentifier(ModScope::scopeGame(), "skill", key))
  151. {
  152. SecondarySkill id(identifier.value());
  153. ret[id] = loadValue(element, rng);
  154. }
  155. }
  156. }
  157. return ret;
  158. }
  159. ArtifactID loadArtifact(const JsonNode & value, CRandomGenerator & rng)
  160. {
  161. if (value.getType() == JsonNode::JsonType::DATA_STRING)
  162. return ArtifactID(VLC->identifiers()->getIdentifier("artifact", value).value());
  163. std::set<CArtifact::EartClass> allowedClasses;
  164. std::set<ArtifactPosition> allowedPositions;
  165. ui32 minValue = 0;
  166. ui32 maxValue = std::numeric_limits<ui32>::max();
  167. if (value["class"].getType() == JsonNode::JsonType::DATA_STRING)
  168. allowedClasses.insert(CArtHandler::stringToClass(value["class"].String()));
  169. else
  170. for(const auto & entry : value["class"].Vector())
  171. allowedClasses.insert(CArtHandler::stringToClass(entry.String()));
  172. if (value["slot"].getType() == JsonNode::JsonType::DATA_STRING)
  173. allowedPositions.insert(ArtifactPosition::decode(value["class"].String()));
  174. else
  175. for(const auto & entry : value["slot"].Vector())
  176. allowedPositions.insert(ArtifactPosition::decode(entry.String()));
  177. if (!value["minValue"].isNull()) minValue = static_cast<ui32>(value["minValue"].Float());
  178. if (!value["maxValue"].isNull()) maxValue = static_cast<ui32>(value["maxValue"].Float());
  179. return VLC->arth->pickRandomArtifact(rng, [=](const ArtifactID & artID) -> bool
  180. {
  181. CArtifact * art = VLC->arth->objects[artID];
  182. if(!vstd::iswithin(art->getPrice(), minValue, maxValue))
  183. return false;
  184. if(!allowedClasses.empty() && !allowedClasses.count(art->aClass))
  185. return false;
  186. if(!IObjectInterface::cb->isAllowed(1, art->getIndex()))
  187. return false;
  188. if(!allowedPositions.empty())
  189. {
  190. for(const auto & pos : art->getPossibleSlots().at(ArtBearer::HERO))
  191. {
  192. if(allowedPositions.count(pos))
  193. return true;
  194. }
  195. return false;
  196. }
  197. return true;
  198. });
  199. }
  200. std::vector<ArtifactID> loadArtifacts(const JsonNode & value, CRandomGenerator & rng)
  201. {
  202. std::vector<ArtifactID> ret;
  203. for (const JsonNode & entry : value.Vector())
  204. {
  205. ret.push_back(loadArtifact(entry, rng));
  206. }
  207. return ret;
  208. }
  209. SpellID loadSpell(const JsonNode & value, CRandomGenerator & rng, std::vector<SpellID> spells)
  210. {
  211. if (value.getType() == JsonNode::JsonType::DATA_STRING)
  212. return SpellID(VLC->identifiers()->getIdentifier("spell", value).value());
  213. if (!value["level"].isNull())
  214. {
  215. int32_t spellLevel = value["level"].Float();
  216. vstd::erase_if(spells, [=](const SpellID & spell)
  217. {
  218. return VLC->spellh->getById(spell)->getLevel() != spellLevel;
  219. });
  220. }
  221. if (!value["school"].isNull())
  222. {
  223. int32_t schoolID = VLC->identifiers()->getIdentifier("spellSchool", value["school"]).value();
  224. vstd::erase_if(spells, [=](const SpellID & spell)
  225. {
  226. return !VLC->spellh->getById(spell)->hasSchool(SpellSchool(schoolID));
  227. });
  228. }
  229. if (spells.empty())
  230. {
  231. logMod->warn("Failed to select suitable random spell!");
  232. return SpellID::NONE;
  233. }
  234. return SpellID(*RandomGeneratorUtil::nextItem(spells, rng));
  235. }
  236. std::vector<SpellID> loadSpells(const JsonNode & value, CRandomGenerator & rng, const std::vector<SpellID> & spells)
  237. {
  238. std::vector<SpellID> ret;
  239. for (const JsonNode & entry : value.Vector())
  240. {
  241. ret.push_back(loadSpell(entry, rng, spells));
  242. }
  243. return ret;
  244. }
  245. std::vector<PlayerColor> loadColors(const JsonNode & value, CRandomGenerator & rng)
  246. {
  247. std::vector<PlayerColor> ret;
  248. std::set<std::string> def;
  249. for(auto & color : GameConstants::PLAYER_COLOR_NAMES)
  250. def.insert(color);
  251. for(auto & entry : value.Vector())
  252. {
  253. auto key = loadKey(entry, rng, def);
  254. auto pos = vstd::find_pos(GameConstants::PLAYER_COLOR_NAMES, key);
  255. if(pos < 0)
  256. logMod->warn("Unable to determine player color %s", key);
  257. else
  258. ret.emplace_back(pos);
  259. }
  260. return ret;
  261. }
  262. std::vector<HeroTypeID> loadHeroes(const JsonNode & value, CRandomGenerator & rng)
  263. {
  264. std::vector<HeroTypeID> ret;
  265. for(auto & entry : value.Vector())
  266. {
  267. ret.push_back(VLC->heroTypes()->getByIndex(VLC->identifiers()->getIdentifier("hero", entry.String()).value())->getId());
  268. }
  269. return ret;
  270. }
  271. std::vector<HeroClassID> loadHeroClasses(const JsonNode & value, CRandomGenerator & rng)
  272. {
  273. std::vector<HeroClassID> ret;
  274. for(auto & entry : value.Vector())
  275. {
  276. ret.push_back(VLC->heroClasses()->getByIndex(VLC->identifiers()->getIdentifier("heroClass", entry.String()).value())->getId());
  277. }
  278. return ret;
  279. }
  280. CStackBasicDescriptor loadCreature(const JsonNode & value, CRandomGenerator & rng)
  281. {
  282. CStackBasicDescriptor stack;
  283. stack.type = VLC->creh->objects[VLC->identifiers()->getIdentifier("creature", value["type"]).value()];
  284. stack.count = loadValue(value, rng);
  285. if (!value["upgradeChance"].isNull() && !stack.type->upgrades.empty())
  286. {
  287. if (int(value["upgradeChance"].Float()) > rng.nextInt(99)) // select random upgrade
  288. {
  289. stack.type = VLC->creh->objects[*RandomGeneratorUtil::nextItem(stack.type->upgrades, rng)];
  290. }
  291. }
  292. return stack;
  293. }
  294. std::vector<CStackBasicDescriptor> loadCreatures(const JsonNode & value, CRandomGenerator & rng)
  295. {
  296. std::vector<CStackBasicDescriptor> ret;
  297. for (const JsonNode & node : value.Vector())
  298. {
  299. ret.push_back(loadCreature(node, rng));
  300. }
  301. return ret;
  302. }
  303. std::vector<RandomStackInfo> evaluateCreatures(const JsonNode & value)
  304. {
  305. std::vector<RandomStackInfo> ret;
  306. for (const JsonNode & node : value.Vector())
  307. {
  308. RandomStackInfo info;
  309. if (!node["amount"].isNull())
  310. info.minAmount = info.maxAmount = static_cast<si32>(node["amount"].Float());
  311. else
  312. {
  313. info.minAmount = static_cast<si32>(node["min"].Float());
  314. info.maxAmount = static_cast<si32>(node["max"].Float());
  315. }
  316. const CCreature * crea = VLC->creh->objects[VLC->identifiers()->getIdentifier("creature", node["type"]).value()];
  317. info.allowedCreatures.push_back(crea);
  318. if (node["upgradeChance"].Float() > 0)
  319. {
  320. for(const auto & creaID : crea->upgrades)
  321. info.allowedCreatures.push_back(VLC->creh->objects[creaID]);
  322. }
  323. ret.push_back(info);
  324. }
  325. return ret;
  326. }
  327. //std::vector<Component> loadComponents(const JsonNode & value)
  328. //{
  329. // std::vector<Component> ret;
  330. // return ret;
  331. // //TODO
  332. //}
  333. std::vector<Bonus> DLL_LINKAGE loadBonuses(const JsonNode & value)
  334. {
  335. std::vector<Bonus> ret;
  336. for (const JsonNode & entry : value.Vector())
  337. {
  338. if(auto bonus = JsonUtils::parseBonus(entry))
  339. ret.push_back(*bonus);
  340. }
  341. return ret;
  342. }
  343. }
  344. VCMI_LIB_NAMESPACE_END