JsonBonus.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875
  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. case BonusType::MULTIHEX_UNIT_ATTACK:
  228. case BonusType::MULTIHEX_ENEMY_ATTACK:
  229. case BonusType::MULTIHEX_ANIMATION:
  230. for (const auto & sequence : value.Vector())
  231. {
  232. static const std::map<char, int> charToDirection = {
  233. { 'f', 1 }, { 'l', 6}, {'r', 2}, {'b', 4}
  234. };
  235. int converted = 0;
  236. for (const auto & ch : boost::adaptors::reverse(sequence.String()))
  237. {
  238. char chLower = std::tolower(ch);
  239. if (charToDirection.count(chLower))
  240. converted = 10 * converted + charToDirection.at(chLower);
  241. }
  242. var.push_back(converted);
  243. }
  244. break;
  245. default:
  246. for(const auto & i : bonusNameMap)
  247. if(i.second == type)
  248. logMod->warn("Bonus type %s does not supports addInfo!", i.first );
  249. }
  250. }
  251. static void loadBonusSourceInstance(BonusSourceID & sourceInstance, BonusSource sourceType, const JsonNode & node)
  252. {
  253. if (node.isNull())
  254. {
  255. sourceInstance = BonusCustomSource();
  256. return;
  257. }
  258. if (node.isNumber()) // Compatibility code for 1.3 or older
  259. {
  260. logMod->warn("Bonus source must be string!");
  261. sourceInstance = BonusCustomSource(node.Integer());
  262. return;
  263. }
  264. if (!node.isString())
  265. {
  266. logMod->warn("Bonus source must be string!");
  267. sourceInstance = BonusCustomSource();
  268. return;
  269. }
  270. switch (sourceType)
  271. {
  272. case BonusSource::ARTIFACT:
  273. case BonusSource::ARTIFACT_INSTANCE:
  274. {
  275. LIBRARY->identifiers()->requestIdentifier( "artifact", node, [&sourceInstance](int32_t identifier)
  276. {
  277. sourceInstance = ArtifactID(identifier);
  278. });
  279. break;
  280. }
  281. case BonusSource::OBJECT_TYPE:
  282. {
  283. LIBRARY->identifiers()->requestIdentifier( "object", node, [&sourceInstance](int32_t identifier)
  284. {
  285. sourceInstance = Obj(identifier);
  286. });
  287. break;
  288. }
  289. case BonusSource::OBJECT_INSTANCE:
  290. case BonusSource::HERO_BASE_SKILL:
  291. sourceInstance = ObjectInstanceID(ObjectInstanceID::decode(node.String()));
  292. break;
  293. case BonusSource::CREATURE_ABILITY:
  294. {
  295. LIBRARY->identifiers()->requestIdentifier( "creature", node, [&sourceInstance](int32_t identifier)
  296. {
  297. sourceInstance = CreatureID(identifier);
  298. });
  299. break;
  300. }
  301. case BonusSource::TERRAIN_OVERLAY:
  302. {
  303. LIBRARY->identifiers()->requestIdentifier( "spell", node, [&sourceInstance](int32_t identifier)
  304. {
  305. sourceInstance = BattleField(identifier);
  306. });
  307. break;
  308. }
  309. case BonusSource::SPELL_EFFECT:
  310. {
  311. LIBRARY->identifiers()->requestIdentifier( "spell", node, [&sourceInstance](int32_t identifier)
  312. {
  313. sourceInstance = SpellID(identifier);
  314. });
  315. break;
  316. }
  317. case BonusSource::TOWN_STRUCTURE:
  318. assert(0); // TODO
  319. sourceInstance = BuildingTypeUniqueID();
  320. break;
  321. case BonusSource::SECONDARY_SKILL:
  322. {
  323. LIBRARY->identifiers()->requestIdentifier( "secondarySkill", node, [&sourceInstance](int32_t identifier)
  324. {
  325. sourceInstance = SecondarySkill(identifier);
  326. });
  327. break;
  328. }
  329. case BonusSource::HERO_SPECIAL:
  330. {
  331. LIBRARY->identifiers()->requestIdentifier( "hero", node, [&sourceInstance](int32_t identifier)
  332. {
  333. sourceInstance = HeroTypeID(identifier);
  334. });
  335. break;
  336. }
  337. case BonusSource::CAMPAIGN_BONUS:
  338. sourceInstance = CampaignScenarioID(CampaignScenarioID::decode(node.String()));
  339. break;
  340. case BonusSource::ARMY:
  341. case BonusSource::STACK_EXPERIENCE:
  342. case BonusSource::COMMANDER:
  343. case BonusSource::GLOBAL:
  344. case BonusSource::TERRAIN_NATIVE:
  345. case BonusSource::OTHER:
  346. default:
  347. sourceInstance = BonusSourceID();
  348. break;
  349. }
  350. }
  351. static BonusParams convertDeprecatedBonus(const JsonNode &ability)
  352. {
  353. if(vstd::contains(deprecatedBonusSet, ability["type"].String()))
  354. {
  355. logMod->warn("There is deprecated bonus found:\n%s\nTrying to convert...", ability.toString());
  356. auto params = BonusParams(ability["type"].String(),
  357. ability["subtype"].isString() ? ability["subtype"].String() : "",
  358. ability["subtype"].isNumber() ? ability["subtype"].Integer() : -1);
  359. if(params.isConverted)
  360. {
  361. if(ability["type"].String() == "SECONDARY_SKILL_PREMY" && bonusValueMap.find(ability["valueType"].String())->second == BonusValueType::PERCENT_TO_BASE) //assume secondary skill special
  362. {
  363. params.valueType = BonusValueType::PERCENT_TO_TARGET_TYPE;
  364. params.targetType = BonusSource::SECONDARY_SKILL;
  365. }
  366. logMod->warn("Please, use this bonus:\n%s\nConverted successfully!", params.toJson().toString());
  367. return params;
  368. }
  369. else
  370. logMod->error("Cannot convert bonus!\n%s", ability.toString());
  371. }
  372. BonusParams ret;
  373. ret.isConverted = false;
  374. return ret;
  375. }
  376. static TUpdaterPtr parseUpdater(const JsonNode & updaterJson)
  377. {
  378. const std::map<std::string, std::function<TUpdaterPtr()>> bonusUpdaterMap =
  379. {
  380. {"TIMES_HERO_LEVEL", std::make_shared<TimesHeroLevelUpdater>},
  381. {"TIMES_HERO_LEVEL_DIVIDE_STACK_LEVEL", std::make_shared<TimesHeroLevelDivideStackLevelUpdater>},
  382. {"DIVIDE_STACK_LEVEL", std::make_shared<DivideStackLevelUpdater>},
  383. {"TIMES_STACK_LEVEL", std::make_shared<TimesStackLevelUpdater>},
  384. {"BONUS_OWNER_UPDATER", std::make_shared<OwnerUpdater>}
  385. };
  386. switch(updaterJson.getType())
  387. {
  388. case JsonNode::JsonType::DATA_STRING:
  389. {
  390. auto it = bonusUpdaterMap.find(updaterJson.String());
  391. if (it != bonusUpdaterMap.end())
  392. return it->second();
  393. logGlobal->error("Unknown bonus updater type '%s'", updaterJson.String());
  394. return nullptr;
  395. }
  396. case JsonNode::JsonType::DATA_STRUCT:
  397. if(updaterJson["type"].String() == "GROWS_WITH_LEVEL")
  398. {
  399. auto updater = std::make_shared<GrowsWithLevelUpdater>();
  400. const JsonVector param = updaterJson["parameters"].Vector();
  401. updater->valPer20 = static_cast<int>(param[0].Integer());
  402. if(param.size() > 1)
  403. updater->stepSize = static_cast<int>(param[1].Integer());
  404. return updater;
  405. }
  406. else
  407. logMod->warn("Unknown updater type \"%s\"", updaterJson["type"].String());
  408. break;
  409. }
  410. return nullptr;
  411. }
  412. VCMI_LIB_NAMESPACE_BEGIN
  413. std::shared_ptr<Bonus> JsonUtils::parseBonus(const JsonVector & ability_vec)
  414. {
  415. auto b = std::make_shared<Bonus>();
  416. std::string type = ability_vec[0].String();
  417. auto it = bonusNameMap.find(type);
  418. if (it == bonusNameMap.end())
  419. {
  420. logMod->error("Error: invalid ability type %s.", type);
  421. return b;
  422. }
  423. b->type = it->second;
  424. b->val = static_cast<si32>(ability_vec[1].Float());
  425. loadBonusSubtype(b->subtype, b->type, ability_vec[2]);
  426. b->additionalInfo = static_cast<si32>(ability_vec[3].Float());
  427. b->duration = BonusDuration::PERMANENT; //TODO: handle flags (as integer)
  428. b->turnsRemain = 0;
  429. return b;
  430. }
  431. std::shared_ptr<ILimiter> JsonUtils::parseLimiter(const JsonNode & limiter)
  432. {
  433. switch(limiter.getType())
  434. {
  435. case JsonNode::JsonType::DATA_VECTOR:
  436. {
  437. const JsonVector & subLimiters = limiter.Vector();
  438. if(subLimiters.empty())
  439. {
  440. logMod->warn("Warning: empty limiter list");
  441. return std::make_shared<AllOfLimiter>();
  442. }
  443. std::shared_ptr<AggregateLimiter> result;
  444. int offset = 1;
  445. // determine limiter type and offset for sub-limiters
  446. if(subLimiters[0].getType() == JsonNode::JsonType::DATA_STRING)
  447. {
  448. const std::string & aggregator = subLimiters[0].String();
  449. if(aggregator == AllOfLimiter::aggregator)
  450. result = std::make_shared<AllOfLimiter>();
  451. else if(aggregator == AnyOfLimiter::aggregator)
  452. result = std::make_shared<AnyOfLimiter>();
  453. else if(aggregator == NoneOfLimiter::aggregator)
  454. result = std::make_shared<NoneOfLimiter>();
  455. }
  456. if(!result)
  457. {
  458. // collapse for single limiter without explicit aggregate operator
  459. if(subLimiters.size() == 1)
  460. return parseLimiter(subLimiters[0]);
  461. // implicit aggregator must be allOf
  462. result = std::make_shared<AllOfLimiter>();
  463. offset = 0;
  464. }
  465. if(subLimiters.size() == offset)
  466. logMod->warn("Warning: empty sub-limiter list");
  467. for(int sl = offset; sl < subLimiters.size(); ++sl)
  468. result->add(parseLimiter(subLimiters[sl]));
  469. return result;
  470. }
  471. break;
  472. case JsonNode::JsonType::DATA_STRING: //pre-defined limiters
  473. return parseByMap(bonusLimiterMap, &limiter, "limiter type ");
  474. break;
  475. case JsonNode::JsonType::DATA_STRUCT: //customizable limiters
  476. {
  477. std::string limiterType = limiter["type"].String();
  478. const JsonVector & parameters = limiter["parameters"].Vector();
  479. if(limiterType == "CREATURE_TYPE_LIMITER")
  480. {
  481. auto creatureLimiter = std::make_shared<CCreatureTypeLimiter>();
  482. LIBRARY->identifiers()->requestIdentifier("creature", parameters[0], [=](si32 creature)
  483. {
  484. creatureLimiter->setCreature(CreatureID(creature));
  485. });
  486. auto includeUpgrades = false;
  487. if(parameters.size() > 1)
  488. {
  489. bool success = true;
  490. includeUpgrades = parameters[1].TryBoolFromString(success);
  491. if(!success)
  492. logMod->error("Second parameter of '%s' limiter should be Bool", limiterType);
  493. }
  494. creatureLimiter->includeUpgrades = includeUpgrades;
  495. return creatureLimiter;
  496. }
  497. else if(limiterType == "HAS_ANOTHER_BONUS_LIMITER")
  498. {
  499. auto bonusLimiter = std::make_shared<HasAnotherBonusLimiter>();
  500. if (!parameters[0].isNull())
  501. {
  502. std::string anotherBonusType = parameters[0].String();
  503. auto it = bonusNameMap.find(anotherBonusType);
  504. if(it != bonusNameMap.end())
  505. {
  506. bonusLimiter->type = it->second;
  507. }
  508. else
  509. {
  510. logMod->error("Error: invalid ability type %s.", anotherBonusType);
  511. }
  512. }
  513. auto findSource = [&](const JsonNode & parameter)
  514. {
  515. if(parameter.getType() == JsonNode::JsonType::DATA_STRUCT)
  516. {
  517. auto sourceIt = bonusSourceMap.find(parameter["type"].String());
  518. if(sourceIt != bonusSourceMap.end())
  519. {
  520. bonusLimiter->source = sourceIt->second;
  521. bonusLimiter->isSourceRelevant = true;
  522. if(!parameter["id"].isNull()) {
  523. loadBonusSourceInstance(bonusLimiter->sid, bonusLimiter->source, parameter["id"]);
  524. bonusLimiter->isSourceIDRelevant = true;
  525. }
  526. }
  527. }
  528. return false;
  529. };
  530. if(parameters.size() > 1)
  531. {
  532. if(findSource(parameters[1]) && parameters.size() == 2)
  533. return bonusLimiter;
  534. else
  535. {
  536. loadBonusSubtype(bonusLimiter->subtype, bonusLimiter->type, parameters[1]);
  537. bonusLimiter->isSubtypeRelevant = true;
  538. if(parameters.size() > 2)
  539. findSource(parameters[2]);
  540. }
  541. }
  542. return bonusLimiter;
  543. }
  544. else if(limiterType == "CREATURE_ALIGNMENT_LIMITER")
  545. {
  546. int alignment = vstd::find_pos(GameConstants::ALIGNMENT_NAMES, parameters[0].String());
  547. if(alignment == -1)
  548. logMod->error("Error: invalid alignment %s.", parameters[0].String());
  549. else
  550. return std::make_shared<CreatureAlignmentLimiter>(static_cast<EAlignment>(alignment));
  551. }
  552. else if(limiterType == "FACTION_LIMITER" || limiterType == "CREATURE_FACTION_LIMITER") //Second name is deprecated, 1.2 compat
  553. {
  554. auto factionLimiter = std::make_shared<FactionLimiter>();
  555. LIBRARY->identifiers()->requestIdentifier("faction", parameters[0], [=](si32 faction)
  556. {
  557. factionLimiter->faction = FactionID(faction);
  558. });
  559. return factionLimiter;
  560. }
  561. else if(limiterType == "CREATURE_LEVEL_LIMITER")
  562. {
  563. auto levelLimiter = std::make_shared<CreatureLevelLimiter>();
  564. if(!parameters.empty()) //If parameters is empty, level limiter works as CREATURES_ONLY limiter
  565. {
  566. levelLimiter->minLevel = parameters[0].Integer();
  567. if(parameters[1].isNumber())
  568. levelLimiter->maxLevel = parameters[1].Integer();
  569. }
  570. return levelLimiter;
  571. }
  572. else if(limiterType == "CREATURE_TERRAIN_LIMITER")
  573. {
  574. auto terrainLimiter = std::make_shared<CreatureTerrainLimiter>();
  575. if(!parameters.empty())
  576. {
  577. LIBRARY->identifiers()->requestIdentifier("terrain", parameters[0], [terrainLimiter](si32 terrain)
  578. {
  579. terrainLimiter->terrainType = terrain;
  580. });
  581. }
  582. return terrainLimiter;
  583. }
  584. else if(limiterType == "UNIT_ON_HEXES") {
  585. auto hexLimiter = std::make_shared<UnitOnHexLimiter>();
  586. if(!parameters.empty())
  587. {
  588. for (const auto & parameter: parameters){
  589. if(parameter.isNumber())
  590. hexLimiter->applicableHexes.insert(BattleHex(parameter.Integer()));
  591. }
  592. }
  593. return hexLimiter;
  594. }
  595. else
  596. {
  597. logMod->error("Error: invalid customizable limiter type %s.", limiterType);
  598. }
  599. }
  600. break;
  601. default:
  602. break;
  603. }
  604. return nullptr;
  605. }
  606. std::shared_ptr<Bonus> JsonUtils::parseBonus(const JsonNode &ability)
  607. {
  608. auto b = std::make_shared<Bonus>();
  609. if (!parseBonus(ability, b.get()))
  610. {
  611. // caller code can not handle this case and presumes that returned bonus is always valid
  612. logGlobal->error("Failed to parse bonus! Json config was %S ", ability.toString());
  613. b->type = BonusType::NONE;
  614. return b;
  615. }
  616. return b;
  617. }
  618. bool JsonUtils::parseBonus(const JsonNode &ability, Bonus *b)
  619. {
  620. const JsonNode * value = nullptr;
  621. std::string type = ability["type"].String();
  622. auto it = bonusNameMap.find(type);
  623. auto params = std::make_unique<BonusParams>(false);
  624. if (it == bonusNameMap.end())
  625. {
  626. params = std::make_unique<BonusParams>(convertDeprecatedBonus(ability));
  627. if(!params->isConverted)
  628. {
  629. logMod->error("Error: invalid ability type %s.", type);
  630. return false;
  631. }
  632. b->type = params->type;
  633. b->val = params->val.value_or(0);
  634. b->valType = params->valueType.value_or(BonusValueType::ADDITIVE_VALUE);
  635. if(params->targetType)
  636. b->targetSourceType = params->targetType.value();
  637. }
  638. else
  639. b->type = it->second;
  640. loadBonusSubtype(b->subtype, b->type, params->isConverted ? params->toJson()["subtype"] : ability["subtype"]);
  641. if(!params->isConverted)
  642. {
  643. b->val = static_cast<si32>(ability["val"].Float());
  644. value = &ability["valueType"];
  645. if (!value->isNull())
  646. b->valType = static_cast<BonusValueType>(parseByMapN(bonusValueMap, value, "value type "));
  647. }
  648. b->stacking = ability["stacking"].String();
  649. loadBonusAddInfo(b->additionalInfo, b->type, ability);
  650. b->turnsRemain = static_cast<si32>(ability["turns"].Float());
  651. if(!ability["description"].isNull())
  652. {
  653. if (ability["description"].isString())
  654. b->description.appendTextID(ability["description"].String());
  655. if (ability["description"].isNumber())
  656. b->description.appendTextID("core.arraytxt." + std::to_string(ability["description"].Integer()));
  657. }
  658. value = &ability["effectRange"];
  659. if (!value->isNull())
  660. b->effectRange = static_cast<BonusLimitEffect>(parseByMapN(bonusLimitEffect, value, "effect range "));
  661. value = &ability["duration"];
  662. if (!value->isNull())
  663. {
  664. switch (value->getType())
  665. {
  666. case JsonNode::JsonType::DATA_STRING:
  667. b->duration = parseByMap(bonusDurationMap, value, "duration type ");
  668. break;
  669. case JsonNode::JsonType::DATA_VECTOR:
  670. {
  671. BonusDuration::Type dur = 0;
  672. for (const JsonNode & d : value->Vector())
  673. dur |= parseByMapN(bonusDurationMap, &d, "duration type ");
  674. b->duration = dur;
  675. }
  676. break;
  677. default:
  678. logMod->error("Error! Wrong bonus duration format.");
  679. }
  680. }
  681. value = &ability["sourceType"];
  682. if (!value->isNull())
  683. b->source = static_cast<BonusSource>(parseByMap(bonusSourceMap, value, "source type "));
  684. if (!ability["sourceID"].isNull())
  685. loadBonusSourceInstance(b->sid, b->source, ability["sourceID"]);
  686. value = &ability["targetSourceType"];
  687. if (!value->isNull())
  688. b->targetSourceType = static_cast<BonusSource>(parseByMap(bonusSourceMap, value, "target type "));
  689. value = &ability["limiters"];
  690. if (!value->isNull())
  691. b->limiter = parseLimiter(*value);
  692. value = &ability["propagator"];
  693. if (!value->isNull())
  694. {
  695. //ALL_CREATURES old propagator compatibility
  696. if(value->String() == "ALL_CREATURES")
  697. {
  698. logMod->warn("ALL_CREATURES propagator is deprecated. Use GLOBAL_EFFECT propagator with CREATURES_ONLY limiter");
  699. b->addLimiter(std::make_shared<CreatureLevelLimiter>());
  700. b->propagator = bonusPropagatorMap.at("GLOBAL_EFFECT");
  701. }
  702. else
  703. b->propagator = parseByMap(bonusPropagatorMap, value, "propagator type ");
  704. }
  705. value = &ability["updater"];
  706. if(!value->isNull())
  707. b->addUpdater(parseUpdater(*value));
  708. value = &ability["propagationUpdater"];
  709. if(!value->isNull())
  710. b->propagationUpdater = parseUpdater(*value);
  711. return true;
  712. }
  713. CSelector JsonUtils::parseSelector(const JsonNode & ability)
  714. {
  715. CSelector ret = Selector::all;
  716. // Recursive parsers for anyOf, allOf, noneOf
  717. const auto * value = &ability["allOf"];
  718. if(value->isVector())
  719. {
  720. for(const auto & andN : value->Vector())
  721. ret = ret.And(parseSelector(andN));
  722. }
  723. value = &ability["anyOf"];
  724. if(value->isVector())
  725. {
  726. CSelector base = Selector::none;
  727. for(const auto & andN : value->Vector())
  728. base = base.Or(parseSelector(andN));
  729. ret = ret.And(base);
  730. }
  731. value = &ability["noneOf"];
  732. if(value->isVector())
  733. {
  734. CSelector base = Selector::none;
  735. for(const auto & andN : value->Vector())
  736. base = base.Or(parseSelector(andN));
  737. ret = ret.And(base.Not());
  738. }
  739. BonusType type = BonusType::NONE;
  740. // Actual selector parser
  741. value = &ability["type"];
  742. if(value->isString())
  743. {
  744. auto it = bonusNameMap.find(value->String());
  745. if(it != bonusNameMap.end())
  746. {
  747. type = it->second;
  748. ret = ret.And(Selector::type()(it->second));
  749. }
  750. }
  751. value = &ability["subtype"];
  752. if(!value->isNull() && type != BonusType::NONE)
  753. {
  754. BonusSubtypeID subtype;
  755. loadBonusSubtype(subtype, type, ability);
  756. ret = ret.And(Selector::subtype()(subtype));
  757. }
  758. value = &ability["sourceType"];
  759. std::optional<BonusSource> src = std::nullopt; //Fixes for GCC false maybe-uninitialized
  760. std::optional<BonusSourceID> id = std::nullopt;
  761. if(value->isString())
  762. {
  763. auto it = bonusSourceMap.find(value->String());
  764. if(it != bonusSourceMap.end())
  765. src = it->second;
  766. }
  767. value = &ability["sourceID"];
  768. if(!value->isNull() && src.has_value())
  769. {
  770. loadBonusSourceInstance(*id, *src, ability);
  771. }
  772. if(src && id)
  773. ret = ret.And(Selector::source(*src, *id));
  774. else if(src)
  775. ret = ret.And(Selector::sourceTypeSel(*src));
  776. value = &ability["targetSourceType"];
  777. if(value->isString())
  778. {
  779. auto it = bonusSourceMap.find(value->String());
  780. if(it != bonusSourceMap.end())
  781. ret = ret.And(Selector::targetSourceType()(it->second));
  782. }
  783. value = &ability["valueType"];
  784. if(value->isString())
  785. {
  786. auto it = bonusValueMap.find(value->String());
  787. if(it != bonusValueMap.end())
  788. ret = ret.And(Selector::valueType(it->second));
  789. }
  790. CAddInfo info;
  791. value = &ability["addInfo"];
  792. if(!value->isNull())
  793. {
  794. loadBonusAddInfo(info, type, ability["addInfo"]);
  795. ret = ret.And(Selector::info()(info));
  796. }
  797. value = &ability["effectRange"];
  798. if(value->isString())
  799. {
  800. auto it = bonusLimitEffect.find(value->String());
  801. if(it != bonusLimitEffect.end())
  802. ret = ret.And(Selector::effectRange()(it->second));
  803. }
  804. value = &ability["lastsTurns"];
  805. if(value->isNumber())
  806. ret = ret.And(Selector::turns(value->Integer()));
  807. value = &ability["lastsDays"];
  808. if(value->isNumber())
  809. ret = ret.And(Selector::days(value->Integer()));
  810. return ret;
  811. }
  812. VCMI_LIB_NAMESPACE_END