JsonRandom.cpp 18 KB

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