JsonRandom.cpp 17 KB

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