JsonRandom.cpp 18 KB

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