JsonRandom.cpp 10.0 KB

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