JsonRandom.cpp 16 KB

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