JsonRandom.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  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 loadVariable(std::string variableGroup, const std::string & value, const Variables & variables, si32 defaultValue)
  31. {
  32. if (value.empty() || value[0] != '@')
  33. {
  34. logMod->warn("Invalid syntax in load value! Can not load value from '%s'", value);
  35. return defaultValue;
  36. }
  37. std::string variableID = variableGroup + value;
  38. if (variables.count(variableID) == 0)
  39. {
  40. logMod->warn("Invalid syntax in load value! Unknown variable '%s'", value);
  41. return defaultValue;
  42. }
  43. return variables.at(variableID);
  44. }
  45. si32 loadValue(const JsonNode & value, CRandomGenerator & rng, const Variables & variables, si32 defaultValue)
  46. {
  47. if(value.isNull())
  48. return defaultValue;
  49. if(value.isNumber())
  50. return static_cast<si32>(value.Float());
  51. if (value.isString())
  52. return loadVariable("number", value.String(), variables, defaultValue);
  53. if(value.isVector())
  54. {
  55. const auto & vector = value.Vector();
  56. size_t index= rng.getIntRange(0, vector.size()-1)();
  57. return loadValue(vector[index], rng, variables, 0);
  58. }
  59. if(value.isStruct())
  60. {
  61. if (!value["amount"].isNull())
  62. return static_cast<si32>(loadValue(value["amount"], rng, variables, defaultValue));
  63. si32 min = static_cast<si32>(loadValue(value["min"], rng, variables, 0));
  64. si32 max = static_cast<si32>(loadValue(value["max"], rng, variables, 0));
  65. return rng.getIntRange(min, max)();
  66. }
  67. return defaultValue;
  68. }
  69. template<typename IdentifierType>
  70. IdentifierType decodeKey(const std::string & modScope, const std::string & value, const Variables & variables)
  71. {
  72. if (value.empty() || value[0] != '@')
  73. return IdentifierType(*VLC->identifiers()->getIdentifier(modScope, IdentifierType::entityType(), value));
  74. else
  75. return loadVariable(IdentifierType::entityType(), value, variables, IdentifierType::NONE);
  76. }
  77. template<typename IdentifierType>
  78. IdentifierType decodeKey(const JsonNode & value, const Variables & variables)
  79. {
  80. if (value.String().empty() || value.String()[0] != '@')
  81. return IdentifierType(*VLC->identifiers()->getIdentifier(IdentifierType::entityType(), value));
  82. else
  83. return loadVariable(IdentifierType::entityType(), value.String(), variables, IdentifierType::NONE);
  84. }
  85. template<>
  86. PlayerColor decodeKey(const JsonNode & value, const Variables & variables)
  87. {
  88. return PlayerColor(*VLC->identifiers()->getIdentifier("playerColor", value));
  89. }
  90. template<>
  91. PrimarySkill decodeKey(const JsonNode & value, const Variables & variables)
  92. {
  93. return PrimarySkill(*VLC->identifiers()->getIdentifier("primarySkill", value));
  94. }
  95. /// Method that allows type-specific object filtering
  96. /// Default implementation is to accept all input objects
  97. template<typename IdentifierType>
  98. std::set<IdentifierType> filterKeysTyped(const JsonNode & value, const std::set<IdentifierType> & valuesSet)
  99. {
  100. return valuesSet;
  101. }
  102. template<>
  103. std::set<ArtifactID> filterKeysTyped(const JsonNode & value, const std::set<ArtifactID> & valuesSet)
  104. {
  105. assert(value.isStruct());
  106. std::set<CArtifact::EartClass> allowedClasses;
  107. std::set<ArtifactPosition> allowedPositions;
  108. ui32 minValue = 0;
  109. ui32 maxValue = std::numeric_limits<ui32>::max();
  110. if (value["class"].getType() == JsonNode::JsonType::DATA_STRING)
  111. allowedClasses.insert(CArtHandler::stringToClass(value["class"].String()));
  112. else
  113. for(const auto & entry : value["class"].Vector())
  114. allowedClasses.insert(CArtHandler::stringToClass(entry.String()));
  115. if (value["slot"].getType() == JsonNode::JsonType::DATA_STRING)
  116. allowedPositions.insert(ArtifactPosition::decode(value["class"].String()));
  117. else
  118. for(const auto & entry : value["slot"].Vector())
  119. allowedPositions.insert(ArtifactPosition::decode(entry.String()));
  120. if (!value["minValue"].isNull())
  121. minValue = static_cast<ui32>(value["minValue"].Float());
  122. if (!value["maxValue"].isNull())
  123. maxValue = static_cast<ui32>(value["maxValue"].Float());
  124. std::set<ArtifactID> result;
  125. for (auto const & artID : valuesSet)
  126. {
  127. CArtifact * art = VLC->arth->objects[artID];
  128. if(!vstd::iswithin(art->getPrice(), minValue, maxValue))
  129. continue;
  130. if(!allowedClasses.empty() && !allowedClasses.count(art->aClass))
  131. continue;
  132. if(!IObjectInterface::cb->isAllowed(1, art->getIndex()))
  133. continue;
  134. if(!allowedPositions.empty())
  135. {
  136. bool positionAllowed = false;
  137. for(const auto & pos : art->getPossibleSlots().at(ArtBearer::HERO))
  138. {
  139. if(allowedPositions.count(pos))
  140. positionAllowed = true;
  141. }
  142. if (!positionAllowed)
  143. continue;
  144. }
  145. result.insert(artID);
  146. }
  147. return result;
  148. }
  149. template<>
  150. std::set<SpellID> filterKeysTyped(const JsonNode & value, const std::set<SpellID> & valuesSet)
  151. {
  152. std::set<SpellID> result = valuesSet;
  153. if (!value["level"].isNull())
  154. {
  155. int32_t spellLevel = value["level"].Integer();
  156. vstd::erase_if(result, [=](const SpellID & spell)
  157. {
  158. return VLC->spellh->getById(spell)->getLevel() != spellLevel;
  159. });
  160. }
  161. if (!value["school"].isNull())
  162. {
  163. int32_t schoolID = VLC->identifiers()->getIdentifier("spellSchool", value["school"]).value();
  164. vstd::erase_if(result, [=](const SpellID & spell)
  165. {
  166. return !VLC->spellh->getById(spell)->hasSchool(SpellSchool(schoolID));
  167. });
  168. }
  169. return result;
  170. }
  171. template<typename IdentifierType>
  172. std::set<IdentifierType> filterKeys(const JsonNode & value, const std::set<IdentifierType> & valuesSet, const Variables & variables)
  173. {
  174. if(value.isString())
  175. return { decodeKey<IdentifierType>(value, variables) };
  176. assert(value.isStruct());
  177. if(value.isStruct())
  178. {
  179. if(!value["type"].isNull())
  180. return filterKeys(value["type"], valuesSet, variables);
  181. std::set<IdentifierType> filteredTypes = filterKeysTyped(value, valuesSet);
  182. if(!value["anyOf"].isNull())
  183. {
  184. std::set<IdentifierType> filteredAnyOf;
  185. for (auto const & entry : value["anyOf"].Vector())
  186. {
  187. std::set<IdentifierType> subset = filterKeys(entry, valuesSet, variables);
  188. filteredAnyOf.insert(subset.begin(), subset.end());
  189. }
  190. vstd::erase_if(filteredTypes, [&](const IdentifierType & value)
  191. {
  192. return filteredAnyOf.count(value) == 0;
  193. });
  194. }
  195. if(!value["noneOf"].isNull())
  196. {
  197. for (auto const & entry : value["noneOf"].Vector())
  198. {
  199. std::set<IdentifierType> subset = filterKeys(entry, valuesSet, variables);
  200. for (auto bannedEntry : subset )
  201. filteredTypes.erase(bannedEntry);
  202. }
  203. }
  204. return filteredTypes;
  205. }
  206. return valuesSet;
  207. }
  208. TResources loadResources(const JsonNode & value, CRandomGenerator & rng, const Variables & variables)
  209. {
  210. TResources ret;
  211. if (value.isVector())
  212. {
  213. for (const auto & entry : value.Vector())
  214. ret += loadResource(entry, rng, variables);
  215. return ret;
  216. }
  217. for (size_t i=0; i<GameConstants::RESOURCE_QUANTITY; i++)
  218. {
  219. ret[i] = loadValue(value[GameConstants::RESOURCE_NAMES[i]], rng, variables);
  220. }
  221. return ret;
  222. }
  223. TResources loadResource(const JsonNode & value, CRandomGenerator & rng, const Variables & variables)
  224. {
  225. std::set<GameResID> defaultResources{
  226. GameResID::WOOD,
  227. GameResID::MERCURY,
  228. GameResID::ORE,
  229. GameResID::SULFUR,
  230. GameResID::CRYSTAL,
  231. GameResID::GEMS,
  232. GameResID::GOLD
  233. };
  234. std::set<GameResID> potentialPicks = filterKeys(value, defaultResources, variables);
  235. GameResID resourceID = *RandomGeneratorUtil::nextItem(potentialPicks, rng);
  236. si32 resourceAmount = loadValue(value, rng, variables, 0);
  237. TResources ret;
  238. ret[resourceID] = resourceAmount;
  239. return ret;
  240. }
  241. PrimarySkill loadPrimary(const JsonNode & value, CRandomGenerator & rng, const Variables & variables)
  242. {
  243. std::set<PrimarySkill> defaultSkills{
  244. PrimarySkill::ATTACK,
  245. PrimarySkill::DEFENSE,
  246. PrimarySkill::SPELL_POWER,
  247. PrimarySkill::KNOWLEDGE
  248. };
  249. std::set<PrimarySkill> potentialPicks = filterKeys(value, defaultSkills, variables);
  250. return *RandomGeneratorUtil::nextItem(potentialPicks, rng);
  251. }
  252. std::vector<si32> loadPrimaries(const JsonNode & value, CRandomGenerator & rng, const Variables & variables)
  253. {
  254. std::vector<si32> ret;
  255. if(value.isStruct())
  256. {
  257. for(const auto & name : NPrimarySkill::names)
  258. {
  259. ret.push_back(loadValue(value[name], rng, variables));
  260. }
  261. }
  262. if(value.isVector())
  263. {
  264. std::set<PrimarySkill> defaultSkills{
  265. PrimarySkill::ATTACK,
  266. PrimarySkill::DEFENSE,
  267. PrimarySkill::SPELL_POWER,
  268. PrimarySkill::KNOWLEDGE
  269. };
  270. ret.resize(GameConstants::PRIMARY_SKILLS, 0);
  271. for(const auto & element : value.Vector())
  272. {
  273. std::set<PrimarySkill> potentialPicks = filterKeys(element, defaultSkills, variables);
  274. PrimarySkill skillID = *RandomGeneratorUtil::nextItem(potentialPicks, rng);
  275. defaultSkills.erase(skillID);
  276. ret[static_cast<int>(skillID)] += loadValue(element, rng, variables);
  277. }
  278. }
  279. return ret;
  280. }
  281. SecondarySkill loadSecondary(const JsonNode & value, CRandomGenerator & rng, const Variables & variables)
  282. {
  283. std::set<SecondarySkill> defaultSkills;
  284. for(const auto & skill : VLC->skillh->objects)
  285. if (IObjectInterface::cb->isAllowed(2, skill->getIndex()))
  286. defaultSkills.insert(skill->getId());
  287. std::set<SecondarySkill> potentialPicks = filterKeys(value, defaultSkills, variables);
  288. return *RandomGeneratorUtil::nextItem(potentialPicks, rng);
  289. }
  290. std::map<SecondarySkill, si32> loadSecondaries(const JsonNode & value, CRandomGenerator & rng, const Variables & variables)
  291. {
  292. std::map<SecondarySkill, si32> ret;
  293. if(value.isStruct())
  294. {
  295. for(const auto & pair : value.Struct())
  296. {
  297. SecondarySkill id = decodeKey<SecondarySkill>(pair.second.meta, pair.first, variables);
  298. ret[id] = loadValue(pair.second, rng, variables);
  299. }
  300. }
  301. if(value.isVector())
  302. {
  303. std::set<SecondarySkill> defaultSkills;
  304. for(const auto & skill : VLC->skillh->objects)
  305. if (IObjectInterface::cb->isAllowed(2, skill->getIndex()))
  306. defaultSkills.insert(skill->getId());
  307. for(const auto & element : value.Vector())
  308. {
  309. std::set<SecondarySkill> potentialPicks = filterKeys(element, defaultSkills, variables);
  310. SecondarySkill skillID = *RandomGeneratorUtil::nextItem(potentialPicks, rng);
  311. defaultSkills.erase(skillID); //avoid dupicates
  312. ret[skillID] = loadValue(element, rng, variables);
  313. }
  314. }
  315. return ret;
  316. }
  317. ArtifactID loadArtifact(const JsonNode & value, CRandomGenerator & rng, const Variables & variables)
  318. {
  319. std::set<ArtifactID> allowedArts;
  320. for (auto const * artifact : VLC->arth->allowedArtifacts)
  321. allowedArts.insert(artifact->getId());
  322. std::set<ArtifactID> potentialPicks = filterKeys(value, allowedArts, variables);
  323. return VLC->arth->pickRandomArtifact(rng, potentialPicks);
  324. }
  325. std::vector<ArtifactID> loadArtifacts(const JsonNode & value, CRandomGenerator & rng, const Variables & variables)
  326. {
  327. std::vector<ArtifactID> ret;
  328. for (const JsonNode & entry : value.Vector())
  329. {
  330. ret.push_back(loadArtifact(entry, rng, variables));
  331. }
  332. return ret;
  333. }
  334. SpellID loadSpell(const JsonNode & value, CRandomGenerator & rng, const Variables & variables)
  335. {
  336. std::set<SpellID> defaultSpells;
  337. for(const auto & spell : VLC->spellh->objects)
  338. if (IObjectInterface::cb->isAllowed(0, spell->getIndex()))
  339. defaultSpells.insert(spell->getId());
  340. std::set<SpellID> potentialPicks = filterKeys(value, defaultSpells, variables);
  341. if (potentialPicks.empty())
  342. {
  343. logMod->warn("Failed to select suitable random spell!");
  344. return SpellID::NONE;
  345. }
  346. return *RandomGeneratorUtil::nextItem(potentialPicks, rng);
  347. }
  348. std::vector<SpellID> loadSpells(const JsonNode & value, CRandomGenerator & rng, const Variables & variables)
  349. {
  350. std::vector<SpellID> ret;
  351. for (const JsonNode & entry : value.Vector())
  352. {
  353. ret.push_back(loadSpell(entry, rng, variables));
  354. }
  355. return ret;
  356. }
  357. std::vector<PlayerColor> loadColors(const JsonNode & value, CRandomGenerator & rng, const Variables & variables)
  358. {
  359. std::vector<PlayerColor> ret;
  360. std::set<PlayerColor> defaultPlayers;
  361. for(size_t i = 0; i < PlayerColor::PLAYER_LIMIT_I; ++i)
  362. defaultPlayers.insert(PlayerColor(i));
  363. for(auto & entry : value.Vector())
  364. {
  365. std::set<PlayerColor> potentialPicks = filterKeys(entry, defaultPlayers, variables);
  366. ret.push_back(*RandomGeneratorUtil::nextItem(potentialPicks, rng));
  367. }
  368. return ret;
  369. }
  370. std::vector<HeroTypeID> loadHeroes(const JsonNode & value, CRandomGenerator & rng)
  371. {
  372. std::vector<HeroTypeID> ret;
  373. for(auto & entry : value.Vector())
  374. {
  375. ret.push_back(VLC->heroTypes()->getByIndex(VLC->identifiers()->getIdentifier("hero", entry.String()).value())->getId());
  376. }
  377. return ret;
  378. }
  379. std::vector<HeroClassID> loadHeroClasses(const JsonNode & value, CRandomGenerator & rng)
  380. {
  381. std::vector<HeroClassID> ret;
  382. for(auto & entry : value.Vector())
  383. {
  384. ret.push_back(VLC->heroClasses()->getByIndex(VLC->identifiers()->getIdentifier("heroClass", entry.String()).value())->getId());
  385. }
  386. return ret;
  387. }
  388. CStackBasicDescriptor loadCreature(const JsonNode & value, CRandomGenerator & rng, const Variables & variables)
  389. {
  390. CStackBasicDescriptor stack;
  391. std::set<CreatureID> defaultCreatures;
  392. for(const auto & creature : VLC->creh->objects)
  393. if (!creature->special)
  394. defaultCreatures.insert(creature->getId());
  395. std::set<CreatureID> potentialPicks = filterKeys(value, defaultCreatures, variables);
  396. CreatureID pickedCreature;
  397. if (!potentialPicks.empty())
  398. pickedCreature = *RandomGeneratorUtil::nextItem(potentialPicks, rng);
  399. else
  400. logMod->warn("Failed to select suitable random creature!");
  401. stack.type = VLC->creh->objects[pickedCreature];
  402. stack.count = loadValue(value, rng, variables);
  403. if (!value["upgradeChance"].isNull() && !stack.type->upgrades.empty())
  404. {
  405. if (int(value["upgradeChance"].Float()) > rng.nextInt(99)) // select random upgrade
  406. {
  407. stack.type = VLC->creh->objects[*RandomGeneratorUtil::nextItem(stack.type->upgrades, rng)];
  408. }
  409. }
  410. return stack;
  411. }
  412. std::vector<CStackBasicDescriptor> loadCreatures(const JsonNode & value, CRandomGenerator & rng, const Variables & variables)
  413. {
  414. std::vector<CStackBasicDescriptor> ret;
  415. for (const JsonNode & node : value.Vector())
  416. {
  417. ret.push_back(loadCreature(node, rng, variables));
  418. }
  419. return ret;
  420. }
  421. std::vector<RandomStackInfo> evaluateCreatures(const JsonNode & value, const Variables & variables)
  422. {
  423. std::vector<RandomStackInfo> ret;
  424. for (const JsonNode & node : value.Vector())
  425. {
  426. RandomStackInfo info;
  427. if (!node["amount"].isNull())
  428. info.minAmount = info.maxAmount = static_cast<si32>(node["amount"].Float());
  429. else
  430. {
  431. info.minAmount = static_cast<si32>(node["min"].Float());
  432. info.maxAmount = static_cast<si32>(node["max"].Float());
  433. }
  434. const CCreature * crea = VLC->creh->objects[VLC->identifiers()->getIdentifier("creature", node["type"]).value()];
  435. info.allowedCreatures.push_back(crea);
  436. if (node["upgradeChance"].Float() > 0)
  437. {
  438. for(const auto & creaID : crea->upgrades)
  439. info.allowedCreatures.push_back(VLC->creh->objects[creaID]);
  440. }
  441. ret.push_back(info);
  442. }
  443. return ret;
  444. }
  445. std::vector<Bonus> DLL_LINKAGE loadBonuses(const JsonNode & value)
  446. {
  447. std::vector<Bonus> ret;
  448. for (const JsonNode & entry : value.Vector())
  449. {
  450. if(auto bonus = JsonUtils::parseBonus(entry))
  451. ret.push_back(*bonus);
  452. }
  453. return ret;
  454. }
  455. }
  456. VCMI_LIB_NAMESPACE_END