JsonBonus.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857
  1. /*
  2. * JsonUtils.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 "JsonBonus.h"
  12. #include "JsonValidator.h"
  13. #include "../texts/CGeneralTextHandler.h"
  14. #include "../GameLibrary.h"
  15. #include "../bonuses/BonusParams.h"
  16. #include "../bonuses/Limiters.h"
  17. #include "../bonuses/Propagators.h"
  18. #include "../bonuses/Updaters.h"
  19. #include "../constants/StringConstants.h"
  20. #include "../modding/IdentifierStorage.h"
  21. VCMI_LIB_USING_NAMESPACE
  22. template <typename T>
  23. const T parseByMap(const std::map<std::string, T> & map, const JsonNode * val, const std::string & err)
  24. {
  25. if (!val->isNull())
  26. {
  27. const std::string & type = val->String();
  28. auto it = map.find(type);
  29. if (it == map.end())
  30. {
  31. logMod->error("Error: invalid %s%s.", err, type);
  32. return {};
  33. }
  34. else
  35. {
  36. return it->second;
  37. }
  38. }
  39. else
  40. return {};
  41. }
  42. template <typename T>
  43. const T parseByMapN(const std::map<std::string, T> & map, const JsonNode * val, const std::string & err)
  44. {
  45. if(val->isNumber())
  46. return static_cast<T>(val->Integer());
  47. else
  48. return parseByMap<T>(map, val, err);
  49. }
  50. static void loadBonusSubtype(BonusSubtypeID & subtype, BonusType type, const JsonNode & node)
  51. {
  52. if (node.isNull())
  53. {
  54. subtype = BonusSubtypeID();
  55. return;
  56. }
  57. if (node.isNumber()) // Compatibility code for 1.3 or older
  58. {
  59. logMod->warn("Bonus subtype must be string! (%s)", node.getModScope());
  60. subtype = BonusCustomSubtype(node.Integer());
  61. return;
  62. }
  63. if (!node.isString())
  64. {
  65. logMod->warn("Bonus subtype must be string! (%s)", node.getModScope());
  66. subtype = BonusSubtypeID();
  67. return;
  68. }
  69. switch (type)
  70. {
  71. case BonusType::MAGIC_SCHOOL_SKILL:
  72. case BonusType::SPELL_DAMAGE:
  73. case BonusType::SPELLS_OF_SCHOOL:
  74. case BonusType::SPELL_DAMAGE_REDUCTION:
  75. case BonusType::SPELL_SCHOOL_IMMUNITY:
  76. case BonusType::NEGATIVE_EFFECTS_IMMUNITY:
  77. {
  78. LIBRARY->identifiers()->requestIdentifier( "spellSchool", node, [&subtype](int32_t identifier)
  79. {
  80. subtype = SpellSchool(identifier);
  81. });
  82. break;
  83. }
  84. case BonusType::NO_TERRAIN_PENALTY:
  85. {
  86. LIBRARY->identifiers()->requestIdentifier( "terrain", node, [&subtype](int32_t identifier)
  87. {
  88. subtype = TerrainId(identifier);
  89. });
  90. break;
  91. }
  92. case BonusType::PRIMARY_SKILL:
  93. {
  94. LIBRARY->identifiers()->requestIdentifier( "primarySkill", node, [&subtype](int32_t identifier)
  95. {
  96. subtype = PrimarySkill(identifier);
  97. });
  98. break;
  99. }
  100. case BonusType::IMPROVED_NECROMANCY:
  101. case BonusType::HERO_GRANTS_ATTACKS:
  102. case BonusType::BONUS_DAMAGE_CHANCE:
  103. case BonusType::BONUS_DAMAGE_PERCENTAGE:
  104. case BonusType::SPECIAL_UPGRADE:
  105. case BonusType::HATE:
  106. case BonusType::SUMMON_GUARDIANS:
  107. case BonusType::MANUAL_CONTROL:
  108. {
  109. LIBRARY->identifiers()->requestIdentifier( "creature", node, [&subtype](int32_t identifier)
  110. {
  111. subtype = CreatureID(identifier);
  112. });
  113. break;
  114. }
  115. case BonusType::SPELL_IMMUNITY:
  116. case BonusType::SPELL_DURATION:
  117. case BonusType::SPECIAL_ADD_VALUE_ENCHANT:
  118. case BonusType::SPECIAL_FIXED_VALUE_ENCHANT:
  119. case BonusType::SPECIAL_PECULIAR_ENCHANT:
  120. case BonusType::SPECIAL_SPELL_LEV:
  121. case BonusType::SPECIFIC_SPELL_DAMAGE:
  122. case BonusType::SPELL:
  123. case BonusType::OPENING_BATTLE_SPELL:
  124. case BonusType::SPELL_LIKE_ATTACK:
  125. case BonusType::CATAPULT:
  126. case BonusType::CATAPULT_EXTRA_SHOTS:
  127. case BonusType::HEALER:
  128. case BonusType::SPELLCASTER:
  129. case BonusType::ENCHANTER:
  130. case BonusType::SPELL_AFTER_ATTACK:
  131. case BonusType::SPELL_BEFORE_ATTACK:
  132. case BonusType::SPECIFIC_SPELL_POWER:
  133. case BonusType::ENCHANTED:
  134. case BonusType::MORE_DAMAGE_FROM_SPELL:
  135. case BonusType::NOT_ACTIVE:
  136. {
  137. LIBRARY->identifiers()->requestIdentifier( "spell", node, [&subtype](int32_t identifier)
  138. {
  139. subtype = SpellID(identifier);
  140. });
  141. break;
  142. }
  143. case BonusType::GENERATE_RESOURCE:
  144. case BonusType::RESOURCES_CONSTANT_BOOST:
  145. case BonusType::RESOURCES_TOWN_MULTIPLYING_BOOST:
  146. {
  147. LIBRARY->identifiers()->requestIdentifier( "resource", node, [&subtype](int32_t identifier)
  148. {
  149. subtype = GameResID(identifier);
  150. });
  151. break;
  152. }
  153. case BonusType::MOVEMENT:
  154. case BonusType::WATER_WALKING:
  155. case BonusType::FLYING_MOVEMENT:
  156. case BonusType::NEGATE_ALL_NATURAL_IMMUNITIES:
  157. case BonusType::CREATURE_DAMAGE:
  158. case BonusType::FLYING:
  159. case BonusType::FIRST_STRIKE:
  160. case BonusType::GENERAL_DAMAGE_REDUCTION:
  161. case BonusType::PERCENTAGE_DAMAGE_BOOST:
  162. case BonusType::SOUL_STEAL:
  163. case BonusType::TRANSMUTATION:
  164. case BonusType::DESTRUCTION:
  165. case BonusType::DEATH_STARE:
  166. case BonusType::REBIRTH:
  167. case BonusType::VISIONS:
  168. case BonusType::SPELLS_OF_LEVEL: // spell level
  169. case BonusType::CREATURE_GROWTH: // creature level
  170. {
  171. LIBRARY->identifiers()->requestIdentifier( "bonusSubtype", node, [&subtype](int32_t identifier)
  172. {
  173. subtype = BonusCustomSubtype(identifier);
  174. });
  175. break;
  176. }
  177. default:
  178. for(const auto & i : bonusNameMap)
  179. if(i.second == type)
  180. logMod->warn("Bonus type %s does not supports subtypes!", i.first );
  181. subtype = BonusSubtypeID();
  182. }
  183. }
  184. static void loadBonusAddInfo(CAddInfo & var, BonusType type, const JsonNode & node)
  185. {
  186. const auto & getFirstValue = [](const JsonNode & jsonNode) -> const JsonNode &
  187. {
  188. if (jsonNode.isVector())
  189. return jsonNode[0];
  190. else
  191. return jsonNode;
  192. };
  193. const JsonNode & value = node["addInfo"];
  194. if (value.isNull())
  195. return;
  196. switch (type)
  197. {
  198. case BonusType::IMPROVED_NECROMANCY:
  199. case BonusType::SPECIAL_ADD_VALUE_ENCHANT:
  200. case BonusType::SPECIAL_FIXED_VALUE_ENCHANT:
  201. case BonusType::DESTRUCTION:
  202. case BonusType::LIMITED_SHOOTING_RANGE:
  203. case BonusType::ACID_BREATH:
  204. case BonusType::SPELLCASTER:
  205. case BonusType::FEROCITY:
  206. case BonusType::PRIMARY_SKILL:
  207. // 1 number
  208. var = getFirstValue(value).Integer();
  209. break;
  210. case BonusType::SPECIAL_UPGRADE:
  211. case BonusType::TRANSMUTATION:
  212. // 1 creature ID
  213. LIBRARY->identifiers()->requestIdentifier("creature", getFirstValue(value), [&](si32 identifier) { var = identifier; });
  214. break;
  215. case BonusType::DEATH_STARE:
  216. // 1 spell ID
  217. LIBRARY->identifiers()->requestIdentifier("spell", getFirstValue(value), [&](si32 identifier) { var = identifier; });
  218. break;
  219. case BonusType::SPELL_BEFORE_ATTACK:
  220. case BonusType::SPELL_AFTER_ATTACK:
  221. // 3 numbers
  222. var.resize(3);
  223. var[0] = value[0].Integer();
  224. var[1] = value[1].Integer();
  225. var[2] = value[2].Integer();
  226. break;
  227. default:
  228. for(const auto & i : bonusNameMap)
  229. if(i.second == type)
  230. logMod->warn("Bonus type %s does not supports addInfo!", i.first );
  231. }
  232. }
  233. static void loadBonusSourceInstance(BonusSourceID & sourceInstance, BonusSource sourceType, const JsonNode & node)
  234. {
  235. if (node.isNull())
  236. {
  237. sourceInstance = BonusCustomSource();
  238. return;
  239. }
  240. if (node.isNumber()) // Compatibility code for 1.3 or older
  241. {
  242. logMod->warn("Bonus source must be string!");
  243. sourceInstance = BonusCustomSource(node.Integer());
  244. return;
  245. }
  246. if (!node.isString())
  247. {
  248. logMod->warn("Bonus source must be string!");
  249. sourceInstance = BonusCustomSource();
  250. return;
  251. }
  252. switch (sourceType)
  253. {
  254. case BonusSource::ARTIFACT:
  255. case BonusSource::ARTIFACT_INSTANCE:
  256. {
  257. LIBRARY->identifiers()->requestIdentifier( "artifact", node, [&sourceInstance](int32_t identifier)
  258. {
  259. sourceInstance = ArtifactID(identifier);
  260. });
  261. break;
  262. }
  263. case BonusSource::OBJECT_TYPE:
  264. {
  265. LIBRARY->identifiers()->requestIdentifier( "object", node, [&sourceInstance](int32_t identifier)
  266. {
  267. sourceInstance = Obj(identifier);
  268. });
  269. break;
  270. }
  271. case BonusSource::OBJECT_INSTANCE:
  272. case BonusSource::HERO_BASE_SKILL:
  273. sourceInstance = ObjectInstanceID(ObjectInstanceID::decode(node.String()));
  274. break;
  275. case BonusSource::CREATURE_ABILITY:
  276. {
  277. LIBRARY->identifiers()->requestIdentifier( "creature", node, [&sourceInstance](int32_t identifier)
  278. {
  279. sourceInstance = CreatureID(identifier);
  280. });
  281. break;
  282. }
  283. case BonusSource::TERRAIN_OVERLAY:
  284. {
  285. LIBRARY->identifiers()->requestIdentifier( "spell", node, [&sourceInstance](int32_t identifier)
  286. {
  287. sourceInstance = BattleField(identifier);
  288. });
  289. break;
  290. }
  291. case BonusSource::SPELL_EFFECT:
  292. {
  293. LIBRARY->identifiers()->requestIdentifier( "spell", node, [&sourceInstance](int32_t identifier)
  294. {
  295. sourceInstance = SpellID(identifier);
  296. });
  297. break;
  298. }
  299. case BonusSource::TOWN_STRUCTURE:
  300. assert(0); // TODO
  301. sourceInstance = BuildingTypeUniqueID();
  302. break;
  303. case BonusSource::SECONDARY_SKILL:
  304. {
  305. LIBRARY->identifiers()->requestIdentifier( "secondarySkill", node, [&sourceInstance](int32_t identifier)
  306. {
  307. sourceInstance = SecondarySkill(identifier);
  308. });
  309. break;
  310. }
  311. case BonusSource::HERO_SPECIAL:
  312. {
  313. LIBRARY->identifiers()->requestIdentifier( "hero", node, [&sourceInstance](int32_t identifier)
  314. {
  315. sourceInstance = HeroTypeID(identifier);
  316. });
  317. break;
  318. }
  319. case BonusSource::CAMPAIGN_BONUS:
  320. sourceInstance = CampaignScenarioID(CampaignScenarioID::decode(node.String()));
  321. break;
  322. case BonusSource::ARMY:
  323. case BonusSource::STACK_EXPERIENCE:
  324. case BonusSource::COMMANDER:
  325. case BonusSource::GLOBAL:
  326. case BonusSource::TERRAIN_NATIVE:
  327. case BonusSource::OTHER:
  328. default:
  329. sourceInstance = BonusSourceID();
  330. break;
  331. }
  332. }
  333. static BonusParams convertDeprecatedBonus(const JsonNode &ability)
  334. {
  335. if(vstd::contains(deprecatedBonusSet, ability["type"].String()))
  336. {
  337. logMod->warn("There is deprecated bonus found:\n%s\nTrying to convert...", ability.toString());
  338. auto params = BonusParams(ability["type"].String(),
  339. ability["subtype"].isString() ? ability["subtype"].String() : "",
  340. ability["subtype"].isNumber() ? ability["subtype"].Integer() : -1);
  341. if(params.isConverted)
  342. {
  343. if(ability["type"].String() == "SECONDARY_SKILL_PREMY" && bonusValueMap.find(ability["valueType"].String())->second == BonusValueType::PERCENT_TO_BASE) //assume secondary skill special
  344. {
  345. params.valueType = BonusValueType::PERCENT_TO_TARGET_TYPE;
  346. params.targetType = BonusSource::SECONDARY_SKILL;
  347. }
  348. logMod->warn("Please, use this bonus:\n%s\nConverted successfully!", params.toJson().toString());
  349. return params;
  350. }
  351. else
  352. logMod->error("Cannot convert bonus!\n%s", ability.toString());
  353. }
  354. BonusParams ret;
  355. ret.isConverted = false;
  356. return ret;
  357. }
  358. static TUpdaterPtr parseUpdater(const JsonNode & updaterJson)
  359. {
  360. const std::map<std::string, std::function<TUpdaterPtr()>> bonusUpdaterMap =
  361. {
  362. {"TIMES_HERO_LEVEL", std::make_shared<TimesHeroLevelUpdater>},
  363. {"TIMES_HERO_LEVEL_DIVIDE_STACK_LEVEL", std::make_shared<TimesHeroLevelDivideStackLevelUpdater>},
  364. {"DIVIDE_STACK_LEVEL", std::make_shared<DivideStackLevelUpdater>},
  365. {"TIMES_STACK_LEVEL", std::make_shared<TimesStackLevelUpdater>},
  366. {"BONUS_OWNER_UPDATER", std::make_shared<OwnerUpdater>}
  367. };
  368. switch(updaterJson.getType())
  369. {
  370. case JsonNode::JsonType::DATA_STRING:
  371. {
  372. auto it = bonusUpdaterMap.find(updaterJson.String());
  373. if (it != bonusUpdaterMap.end())
  374. return it->second();
  375. logGlobal->error("Unknown bonus updater type '%s'", updaterJson.String());
  376. return nullptr;
  377. }
  378. case JsonNode::JsonType::DATA_STRUCT:
  379. if(updaterJson["type"].String() == "GROWS_WITH_LEVEL")
  380. {
  381. auto updater = std::make_shared<GrowsWithLevelUpdater>();
  382. const JsonVector param = updaterJson["parameters"].Vector();
  383. updater->valPer20 = static_cast<int>(param[0].Integer());
  384. if(param.size() > 1)
  385. updater->stepSize = static_cast<int>(param[1].Integer());
  386. return updater;
  387. }
  388. else
  389. logMod->warn("Unknown updater type \"%s\"", updaterJson["type"].String());
  390. break;
  391. }
  392. return nullptr;
  393. }
  394. VCMI_LIB_NAMESPACE_BEGIN
  395. std::shared_ptr<Bonus> JsonUtils::parseBonus(const JsonVector & ability_vec)
  396. {
  397. auto b = std::make_shared<Bonus>();
  398. std::string type = ability_vec[0].String();
  399. auto it = bonusNameMap.find(type);
  400. if (it == bonusNameMap.end())
  401. {
  402. logMod->error("Error: invalid ability type %s.", type);
  403. return b;
  404. }
  405. b->type = it->second;
  406. b->val = static_cast<si32>(ability_vec[1].Float());
  407. loadBonusSubtype(b->subtype, b->type, ability_vec[2]);
  408. b->additionalInfo = static_cast<si32>(ability_vec[3].Float());
  409. b->duration = BonusDuration::PERMANENT; //TODO: handle flags (as integer)
  410. b->turnsRemain = 0;
  411. return b;
  412. }
  413. std::shared_ptr<ILimiter> JsonUtils::parseLimiter(const JsonNode & limiter)
  414. {
  415. switch(limiter.getType())
  416. {
  417. case JsonNode::JsonType::DATA_VECTOR:
  418. {
  419. const JsonVector & subLimiters = limiter.Vector();
  420. if(subLimiters.empty())
  421. {
  422. logMod->warn("Warning: empty limiter list");
  423. return std::make_shared<AllOfLimiter>();
  424. }
  425. std::shared_ptr<AggregateLimiter> result;
  426. int offset = 1;
  427. // determine limiter type and offset for sub-limiters
  428. if(subLimiters[0].getType() == JsonNode::JsonType::DATA_STRING)
  429. {
  430. const std::string & aggregator = subLimiters[0].String();
  431. if(aggregator == AllOfLimiter::aggregator)
  432. result = std::make_shared<AllOfLimiter>();
  433. else if(aggregator == AnyOfLimiter::aggregator)
  434. result = std::make_shared<AnyOfLimiter>();
  435. else if(aggregator == NoneOfLimiter::aggregator)
  436. result = std::make_shared<NoneOfLimiter>();
  437. }
  438. if(!result)
  439. {
  440. // collapse for single limiter without explicit aggregate operator
  441. if(subLimiters.size() == 1)
  442. return parseLimiter(subLimiters[0]);
  443. // implicit aggregator must be allOf
  444. result = std::make_shared<AllOfLimiter>();
  445. offset = 0;
  446. }
  447. if(subLimiters.size() == offset)
  448. logMod->warn("Warning: empty sub-limiter list");
  449. for(int sl = offset; sl < subLimiters.size(); ++sl)
  450. result->add(parseLimiter(subLimiters[sl]));
  451. return result;
  452. }
  453. break;
  454. case JsonNode::JsonType::DATA_STRING: //pre-defined limiters
  455. return parseByMap(bonusLimiterMap, &limiter, "limiter type ");
  456. break;
  457. case JsonNode::JsonType::DATA_STRUCT: //customizable limiters
  458. {
  459. std::string limiterType = limiter["type"].String();
  460. const JsonVector & parameters = limiter["parameters"].Vector();
  461. if(limiterType == "CREATURE_TYPE_LIMITER")
  462. {
  463. auto creatureLimiter = std::make_shared<CCreatureTypeLimiter>();
  464. LIBRARY->identifiers()->requestIdentifier("creature", parameters[0], [=](si32 creature)
  465. {
  466. creatureLimiter->setCreature(CreatureID(creature));
  467. });
  468. auto includeUpgrades = false;
  469. if(parameters.size() > 1)
  470. {
  471. bool success = true;
  472. includeUpgrades = parameters[1].TryBoolFromString(success);
  473. if(!success)
  474. logMod->error("Second parameter of '%s' limiter should be Bool", limiterType);
  475. }
  476. creatureLimiter->includeUpgrades = includeUpgrades;
  477. return creatureLimiter;
  478. }
  479. else if(limiterType == "HAS_ANOTHER_BONUS_LIMITER")
  480. {
  481. auto bonusLimiter = std::make_shared<HasAnotherBonusLimiter>();
  482. if (!parameters[0].isNull())
  483. {
  484. std::string anotherBonusType = parameters[0].String();
  485. auto it = bonusNameMap.find(anotherBonusType);
  486. if(it != bonusNameMap.end())
  487. {
  488. bonusLimiter->type = it->second;
  489. }
  490. else
  491. {
  492. logMod->error("Error: invalid ability type %s.", anotherBonusType);
  493. }
  494. }
  495. auto findSource = [&](const JsonNode & parameter)
  496. {
  497. if(parameter.getType() == JsonNode::JsonType::DATA_STRUCT)
  498. {
  499. auto sourceIt = bonusSourceMap.find(parameter["type"].String());
  500. if(sourceIt != bonusSourceMap.end())
  501. {
  502. bonusLimiter->source = sourceIt->second;
  503. bonusLimiter->isSourceRelevant = true;
  504. if(!parameter["id"].isNull()) {
  505. loadBonusSourceInstance(bonusLimiter->sid, bonusLimiter->source, parameter["id"]);
  506. bonusLimiter->isSourceIDRelevant = true;
  507. }
  508. }
  509. }
  510. return false;
  511. };
  512. if(parameters.size() > 1)
  513. {
  514. if(findSource(parameters[1]) && parameters.size() == 2)
  515. return bonusLimiter;
  516. else
  517. {
  518. loadBonusSubtype(bonusLimiter->subtype, bonusLimiter->type, parameters[1]);
  519. bonusLimiter->isSubtypeRelevant = true;
  520. if(parameters.size() > 2)
  521. findSource(parameters[2]);
  522. }
  523. }
  524. return bonusLimiter;
  525. }
  526. else if(limiterType == "CREATURE_ALIGNMENT_LIMITER")
  527. {
  528. int alignment = vstd::find_pos(GameConstants::ALIGNMENT_NAMES, parameters[0].String());
  529. if(alignment == -1)
  530. logMod->error("Error: invalid alignment %s.", parameters[0].String());
  531. else
  532. return std::make_shared<CreatureAlignmentLimiter>(static_cast<EAlignment>(alignment));
  533. }
  534. else if(limiterType == "FACTION_LIMITER" || limiterType == "CREATURE_FACTION_LIMITER") //Second name is deprecated, 1.2 compat
  535. {
  536. auto factionLimiter = std::make_shared<FactionLimiter>();
  537. LIBRARY->identifiers()->requestIdentifier("faction", parameters[0], [=](si32 faction)
  538. {
  539. factionLimiter->faction = FactionID(faction);
  540. });
  541. return factionLimiter;
  542. }
  543. else if(limiterType == "CREATURE_LEVEL_LIMITER")
  544. {
  545. auto levelLimiter = std::make_shared<CreatureLevelLimiter>();
  546. if(!parameters.empty()) //If parameters is empty, level limiter works as CREATURES_ONLY limiter
  547. {
  548. levelLimiter->minLevel = parameters[0].Integer();
  549. if(parameters[1].isNumber())
  550. levelLimiter->maxLevel = parameters[1].Integer();
  551. }
  552. return levelLimiter;
  553. }
  554. else if(limiterType == "CREATURE_TERRAIN_LIMITER")
  555. {
  556. auto terrainLimiter = std::make_shared<CreatureTerrainLimiter>();
  557. if(!parameters.empty())
  558. {
  559. LIBRARY->identifiers()->requestIdentifier("terrain", parameters[0], [terrainLimiter](si32 terrain)
  560. {
  561. terrainLimiter->terrainType = terrain;
  562. });
  563. }
  564. return terrainLimiter;
  565. }
  566. else if(limiterType == "UNIT_ON_HEXES") {
  567. auto hexLimiter = std::make_shared<UnitOnHexLimiter>();
  568. if(!parameters.empty())
  569. {
  570. for (const auto & parameter: parameters){
  571. if(parameter.isNumber())
  572. hexLimiter->applicableHexes.insert(BattleHex(parameter.Integer()));
  573. }
  574. }
  575. return hexLimiter;
  576. }
  577. else
  578. {
  579. logMod->error("Error: invalid customizable limiter type %s.", limiterType);
  580. }
  581. }
  582. break;
  583. default:
  584. break;
  585. }
  586. return nullptr;
  587. }
  588. std::shared_ptr<Bonus> JsonUtils::parseBonus(const JsonNode &ability)
  589. {
  590. auto b = std::make_shared<Bonus>();
  591. if (!parseBonus(ability, b.get()))
  592. {
  593. // caller code can not handle this case and presumes that returned bonus is always valid
  594. logGlobal->error("Failed to parse bonus! Json config was %S ", ability.toString());
  595. b->type = BonusType::NONE;
  596. return b;
  597. }
  598. return b;
  599. }
  600. bool JsonUtils::parseBonus(const JsonNode &ability, Bonus *b)
  601. {
  602. const JsonNode * value = nullptr;
  603. std::string type = ability["type"].String();
  604. auto it = bonusNameMap.find(type);
  605. auto params = std::make_unique<BonusParams>(false);
  606. if (it == bonusNameMap.end())
  607. {
  608. params = std::make_unique<BonusParams>(convertDeprecatedBonus(ability));
  609. if(!params->isConverted)
  610. {
  611. logMod->error("Error: invalid ability type %s.", type);
  612. return false;
  613. }
  614. b->type = params->type;
  615. b->val = params->val.value_or(0);
  616. b->valType = params->valueType.value_or(BonusValueType::ADDITIVE_VALUE);
  617. if(params->targetType)
  618. b->targetSourceType = params->targetType.value();
  619. }
  620. else
  621. b->type = it->second;
  622. loadBonusSubtype(b->subtype, b->type, params->isConverted ? params->toJson()["subtype"] : ability["subtype"]);
  623. if(!params->isConverted)
  624. {
  625. b->val = static_cast<si32>(ability["val"].Float());
  626. value = &ability["valueType"];
  627. if (!value->isNull())
  628. b->valType = static_cast<BonusValueType>(parseByMapN(bonusValueMap, value, "value type "));
  629. }
  630. b->stacking = ability["stacking"].String();
  631. loadBonusAddInfo(b->additionalInfo, b->type, ability);
  632. b->turnsRemain = static_cast<si32>(ability["turns"].Float());
  633. if(!ability["description"].isNull())
  634. {
  635. if (ability["description"].isString())
  636. b->description.appendTextID(ability["description"].String());
  637. if (ability["description"].isNumber())
  638. b->description.appendTextID("core.arraytxt." + std::to_string(ability["description"].Integer()));
  639. }
  640. value = &ability["effectRange"];
  641. if (!value->isNull())
  642. b->effectRange = static_cast<BonusLimitEffect>(parseByMapN(bonusLimitEffect, value, "effect range "));
  643. value = &ability["duration"];
  644. if (!value->isNull())
  645. {
  646. switch (value->getType())
  647. {
  648. case JsonNode::JsonType::DATA_STRING:
  649. b->duration = parseByMap(bonusDurationMap, value, "duration type ");
  650. break;
  651. case JsonNode::JsonType::DATA_VECTOR:
  652. {
  653. BonusDuration::Type dur = 0;
  654. for (const JsonNode & d : value->Vector())
  655. dur |= parseByMapN(bonusDurationMap, &d, "duration type ");
  656. b->duration = dur;
  657. }
  658. break;
  659. default:
  660. logMod->error("Error! Wrong bonus duration format.");
  661. }
  662. }
  663. value = &ability["sourceType"];
  664. if (!value->isNull())
  665. b->source = static_cast<BonusSource>(parseByMap(bonusSourceMap, value, "source type "));
  666. if (!ability["sourceID"].isNull())
  667. loadBonusSourceInstance(b->sid, b->source, ability["sourceID"]);
  668. value = &ability["targetSourceType"];
  669. if (!value->isNull())
  670. b->targetSourceType = static_cast<BonusSource>(parseByMap(bonusSourceMap, value, "target type "));
  671. value = &ability["limiters"];
  672. if (!value->isNull())
  673. b->limiter = parseLimiter(*value);
  674. value = &ability["propagator"];
  675. if (!value->isNull())
  676. {
  677. //ALL_CREATURES old propagator compatibility
  678. if(value->String() == "ALL_CREATURES")
  679. {
  680. logMod->warn("ALL_CREATURES propagator is deprecated. Use GLOBAL_EFFECT propagator with CREATURES_ONLY limiter");
  681. b->addLimiter(std::make_shared<CreatureLevelLimiter>());
  682. b->propagator = bonusPropagatorMap.at("GLOBAL_EFFECT");
  683. }
  684. else
  685. b->propagator = parseByMap(bonusPropagatorMap, value, "propagator type ");
  686. }
  687. value = &ability["updater"];
  688. if(!value->isNull())
  689. b->addUpdater(parseUpdater(*value));
  690. value = &ability["propagationUpdater"];
  691. if(!value->isNull())
  692. b->propagationUpdater = parseUpdater(*value);
  693. return true;
  694. }
  695. CSelector JsonUtils::parseSelector(const JsonNode & ability)
  696. {
  697. CSelector ret = Selector::all;
  698. // Recursive parsers for anyOf, allOf, noneOf
  699. const auto * value = &ability["allOf"];
  700. if(value->isVector())
  701. {
  702. for(const auto & andN : value->Vector())
  703. ret = ret.And(parseSelector(andN));
  704. }
  705. value = &ability["anyOf"];
  706. if(value->isVector())
  707. {
  708. CSelector base = Selector::none;
  709. for(const auto & andN : value->Vector())
  710. base = base.Or(parseSelector(andN));
  711. ret = ret.And(base);
  712. }
  713. value = &ability["noneOf"];
  714. if(value->isVector())
  715. {
  716. CSelector base = Selector::none;
  717. for(const auto & andN : value->Vector())
  718. base = base.Or(parseSelector(andN));
  719. ret = ret.And(base.Not());
  720. }
  721. BonusType type = BonusType::NONE;
  722. // Actual selector parser
  723. value = &ability["type"];
  724. if(value->isString())
  725. {
  726. auto it = bonusNameMap.find(value->String());
  727. if(it != bonusNameMap.end())
  728. {
  729. type = it->second;
  730. ret = ret.And(Selector::type()(it->second));
  731. }
  732. }
  733. value = &ability["subtype"];
  734. if(!value->isNull() && type != BonusType::NONE)
  735. {
  736. BonusSubtypeID subtype;
  737. loadBonusSubtype(subtype, type, ability);
  738. ret = ret.And(Selector::subtype()(subtype));
  739. }
  740. value = &ability["sourceType"];
  741. std::optional<BonusSource> src = std::nullopt; //Fixes for GCC false maybe-uninitialized
  742. std::optional<BonusSourceID> id = std::nullopt;
  743. if(value->isString())
  744. {
  745. auto it = bonusSourceMap.find(value->String());
  746. if(it != bonusSourceMap.end())
  747. src = it->second;
  748. }
  749. value = &ability["sourceID"];
  750. if(!value->isNull() && src.has_value())
  751. {
  752. loadBonusSourceInstance(*id, *src, ability);
  753. }
  754. if(src && id)
  755. ret = ret.And(Selector::source(*src, *id));
  756. else if(src)
  757. ret = ret.And(Selector::sourceTypeSel(*src));
  758. value = &ability["targetSourceType"];
  759. if(value->isString())
  760. {
  761. auto it = bonusSourceMap.find(value->String());
  762. if(it != bonusSourceMap.end())
  763. ret = ret.And(Selector::targetSourceType()(it->second));
  764. }
  765. value = &ability["valueType"];
  766. if(value->isString())
  767. {
  768. auto it = bonusValueMap.find(value->String());
  769. if(it != bonusValueMap.end())
  770. ret = ret.And(Selector::valueType(it->second));
  771. }
  772. CAddInfo info;
  773. value = &ability["addInfo"];
  774. if(!value->isNull())
  775. {
  776. loadBonusAddInfo(info, type, ability["addInfo"]);
  777. ret = ret.And(Selector::info()(info));
  778. }
  779. value = &ability["effectRange"];
  780. if(value->isString())
  781. {
  782. auto it = bonusLimitEffect.find(value->String());
  783. if(it != bonusLimitEffect.end())
  784. ret = ret.And(Selector::effectRange()(it->second));
  785. }
  786. value = &ability["lastsTurns"];
  787. if(value->isNumber())
  788. ret = ret.And(Selector::turns(value->Integer()));
  789. value = &ability["lastsDays"];
  790. if(value->isNumber())
  791. ret = ret.And(Selector::days(value->Integer()));
  792. return ret;
  793. }
  794. VCMI_LIB_NAMESPACE_END