JsonRandom.cpp 16 KB

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