JsonRandom.cpp 18 KB

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