JsonBonus.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896
  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/Limiters.h"
  16. #include "../bonuses/Propagators.h"
  17. #include "../bonuses/Updaters.h"
  18. #include "../CBonusTypeHandler.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. case BonusType::SKELETON_TRANSFORMER_TARGET:
  109. {
  110. LIBRARY->identifiers()->requestIdentifier( "creature", node, [&subtype](int32_t identifier)
  111. {
  112. subtype = CreatureID(identifier);
  113. });
  114. break;
  115. }
  116. case BonusType::SPELL_IMMUNITY:
  117. case BonusType::SPELL_DURATION:
  118. case BonusType::SPECIAL_ADD_VALUE_ENCHANT:
  119. case BonusType::SPECIAL_FIXED_VALUE_ENCHANT:
  120. case BonusType::SPECIAL_PECULIAR_ENCHANT:
  121. case BonusType::SPECIAL_SPELL_LEV:
  122. case BonusType::SPECIFIC_SPELL_DAMAGE:
  123. case BonusType::SPELL:
  124. case BonusType::OPENING_BATTLE_SPELL:
  125. case BonusType::SPELL_LIKE_ATTACK:
  126. case BonusType::CATAPULT:
  127. case BonusType::CATAPULT_EXTRA_SHOTS:
  128. case BonusType::HEALER:
  129. case BonusType::SPELLCASTER:
  130. case BonusType::ENCHANTER:
  131. case BonusType::SPELL_AFTER_ATTACK:
  132. case BonusType::SPELL_BEFORE_ATTACK:
  133. case BonusType::SPECIFIC_SPELL_POWER:
  134. case BonusType::ENCHANTED:
  135. case BonusType::MORE_DAMAGE_FROM_SPELL:
  136. case BonusType::NOT_ACTIVE:
  137. {
  138. LIBRARY->identifiers()->requestIdentifier( "spell", node, [&subtype](int32_t identifier)
  139. {
  140. subtype = SpellID(identifier);
  141. });
  142. break;
  143. }
  144. case BonusType::GENERATE_RESOURCE:
  145. case BonusType::RESOURCES_CONSTANT_BOOST:
  146. case BonusType::RESOURCES_TOWN_MULTIPLYING_BOOST:
  147. {
  148. LIBRARY->identifiers()->requestIdentifier( "resource", node, [&subtype](int32_t identifier)
  149. {
  150. subtype = GameResID(identifier);
  151. });
  152. break;
  153. }
  154. case BonusType::MOVEMENT:
  155. case BonusType::WATER_WALKING:
  156. case BonusType::FLYING_MOVEMENT:
  157. case BonusType::NEGATE_ALL_NATURAL_IMMUNITIES:
  158. case BonusType::CREATURE_DAMAGE:
  159. case BonusType::FLYING:
  160. case BonusType::FIRST_STRIKE:
  161. case BonusType::GENERAL_DAMAGE_REDUCTION:
  162. case BonusType::PERCENTAGE_DAMAGE_BOOST:
  163. case BonusType::SOUL_STEAL:
  164. case BonusType::TRANSMUTATION:
  165. case BonusType::DESTRUCTION:
  166. case BonusType::DEATH_STARE:
  167. case BonusType::REBIRTH:
  168. case BonusType::VISIONS:
  169. case BonusType::SPELLS_OF_LEVEL: // spell level
  170. case BonusType::CREATURE_GROWTH: // creature level
  171. {
  172. LIBRARY->identifiers()->requestIdentifier( "bonusSubtype", node, [&subtype](int32_t identifier)
  173. {
  174. subtype = BonusCustomSubtype(identifier);
  175. });
  176. break;
  177. }
  178. default:
  179. {
  180. logMod->warn("Bonus type %s does not supports subtypes!", LIBRARY->bth->bonusToString(type));
  181. subtype = BonusSubtypeID();
  182. }
  183. }
  184. }
  185. static void loadBonusAddInfo(CAddInfo & var, BonusType type, const JsonNode & value)
  186. {
  187. const auto & getFirstValue = [](const JsonNode & jsonNode) -> const JsonNode &
  188. {
  189. if (jsonNode.isVector())
  190. return jsonNode[0];
  191. else
  192. return jsonNode;
  193. };
  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::BIND_EFFECT:
  205. case BonusType::SPELLCASTER:
  206. case BonusType::FEROCITY:
  207. case BonusType::PRIMARY_SKILL:
  208. case BonusType::ENCHANTER:
  209. case BonusType::SPECIAL_PECULIAR_ENCHANT:
  210. case BonusType::SPELL_IMMUNITY:
  211. case BonusType::DARKNESS:
  212. case BonusType::FULL_MAP_SCOUTING:
  213. case BonusType::FULL_MAP_DARKNESS:
  214. // 1 number
  215. var = getFirstValue(value).Integer();
  216. break;
  217. case BonusType::SPECIAL_UPGRADE:
  218. case BonusType::TRANSMUTATION:
  219. // 1 creature ID
  220. LIBRARY->identifiers()->requestIdentifier("creature", getFirstValue(value), [&](si32 identifier) { var = identifier; });
  221. break;
  222. case BonusType::DEATH_STARE:
  223. // 1 spell ID
  224. LIBRARY->identifiers()->requestIdentifier("spell", getFirstValue(value), [&](si32 identifier) { var = identifier; });
  225. break;
  226. case BonusType::SPELL_BEFORE_ATTACK:
  227. case BonusType::SPELL_AFTER_ATTACK:
  228. // 3 numbers
  229. if (value.isNumber())
  230. {
  231. var = getFirstValue(value).Integer();
  232. }
  233. else
  234. {
  235. var.resize(3);
  236. var[0] = value[0].Integer();
  237. var[1] = value[1].Integer();
  238. var[2] = value[2].Integer();
  239. }
  240. break;
  241. case BonusType::MULTIHEX_UNIT_ATTACK:
  242. case BonusType::MULTIHEX_ENEMY_ATTACK:
  243. case BonusType::MULTIHEX_ANIMATION:
  244. for (const auto & sequence : value.Vector())
  245. {
  246. static const std::map<char, int> charToDirection = {
  247. { 'f', 1 }, { 'l', 6}, {'r', 2}, {'b', 4}
  248. };
  249. int converted = 0;
  250. for (const auto & ch : boost::adaptors::reverse(sequence.String()))
  251. {
  252. char chLower = std::tolower(ch);
  253. if (charToDirection.count(chLower))
  254. converted = 10 * converted + charToDirection.at(chLower);
  255. }
  256. var.push_back(converted);
  257. }
  258. break;
  259. default:
  260. logMod->warn("Bonus type %s does not supports addInfo!", LIBRARY->bth->bonusToString(type) );
  261. }
  262. }
  263. static void loadBonusSourceInstance(BonusSourceID & sourceInstance, BonusSource sourceType, const JsonNode & node)
  264. {
  265. if (node.isNull())
  266. {
  267. sourceInstance = BonusCustomSource();
  268. return;
  269. }
  270. if (node.isNumber()) // Compatibility code for 1.3 or older
  271. {
  272. logMod->warn("Bonus source must be string!");
  273. sourceInstance = BonusCustomSource(node.Integer());
  274. return;
  275. }
  276. if (!node.isString())
  277. {
  278. logMod->warn("Bonus source must be string!");
  279. sourceInstance = BonusCustomSource();
  280. return;
  281. }
  282. switch (sourceType)
  283. {
  284. case BonusSource::ARTIFACT:
  285. case BonusSource::ARTIFACT_INSTANCE:
  286. {
  287. LIBRARY->identifiers()->requestIdentifier( "artifact", node, [&sourceInstance](int32_t identifier)
  288. {
  289. sourceInstance = ArtifactID(identifier);
  290. });
  291. break;
  292. }
  293. case BonusSource::OBJECT_TYPE:
  294. {
  295. LIBRARY->identifiers()->requestIdentifier( "object", node, [&sourceInstance](int32_t identifier)
  296. {
  297. sourceInstance = Obj(identifier);
  298. });
  299. break;
  300. }
  301. case BonusSource::OBJECT_INSTANCE:
  302. case BonusSource::HERO_BASE_SKILL:
  303. sourceInstance = ObjectInstanceID(ObjectInstanceID::decode(node.String()));
  304. break;
  305. case BonusSource::CREATURE_ABILITY:
  306. {
  307. LIBRARY->identifiers()->requestIdentifier( "creature", node, [&sourceInstance](int32_t identifier)
  308. {
  309. sourceInstance = CreatureID(identifier);
  310. });
  311. break;
  312. }
  313. case BonusSource::TERRAIN_OVERLAY:
  314. {
  315. LIBRARY->identifiers()->requestIdentifier( "spell", node, [&sourceInstance](int32_t identifier)
  316. {
  317. sourceInstance = BattleField(identifier);
  318. });
  319. break;
  320. }
  321. case BonusSource::SPELL_EFFECT:
  322. {
  323. LIBRARY->identifiers()->requestIdentifier( "spell", node, [&sourceInstance](int32_t identifier)
  324. {
  325. sourceInstance = SpellID(identifier);
  326. });
  327. break;
  328. }
  329. case BonusSource::TOWN_STRUCTURE:
  330. assert(0); // TODO
  331. sourceInstance = BuildingTypeUniqueID();
  332. break;
  333. case BonusSource::SECONDARY_SKILL:
  334. {
  335. LIBRARY->identifiers()->requestIdentifier( "secondarySkill", node, [&sourceInstance](int32_t identifier)
  336. {
  337. sourceInstance = SecondarySkill(identifier);
  338. });
  339. break;
  340. }
  341. case BonusSource::HERO_SPECIAL:
  342. {
  343. LIBRARY->identifiers()->requestIdentifier( "hero", node, [&sourceInstance](int32_t identifier)
  344. {
  345. sourceInstance = HeroTypeID(identifier);
  346. });
  347. break;
  348. }
  349. case BonusSource::CAMPAIGN_BONUS:
  350. sourceInstance = CampaignScenarioID(CampaignScenarioID::decode(node.String()));
  351. break;
  352. case BonusSource::ARMY:
  353. case BonusSource::STACK_EXPERIENCE:
  354. case BonusSource::COMMANDER:
  355. case BonusSource::GLOBAL:
  356. case BonusSource::TERRAIN_NATIVE:
  357. case BonusSource::OTHER:
  358. default:
  359. sourceInstance = BonusSourceID();
  360. break;
  361. }
  362. }
  363. static TUpdaterPtr parseUpdater(const JsonNode & updaterJson)
  364. {
  365. const std::map<std::string, std::shared_ptr<IUpdater>> bonusUpdaterMap =
  366. {
  367. {"TIMES_HERO_LEVEL", std::make_shared<TimesHeroLevelUpdater>()},
  368. {"TIMES_HERO_LEVEL_DIVIDE_STACK_LEVEL", std::make_shared<TimesHeroLevelDivideStackLevelUpdater>()},
  369. {"DIVIDE_STACK_LEVEL", std::make_shared<DivideStackLevelUpdater>()},
  370. {"TIMES_STACK_LEVEL", std::make_shared<TimesStackLevelUpdater>()},
  371. {"TIMES_STACK_SIZE", std::make_shared<TimesStackSizeUpdater>()},
  372. {"BONUS_OWNER_UPDATER", std::make_shared<OwnerUpdater>()}
  373. };
  374. switch(updaterJson.getType())
  375. {
  376. case JsonNode::JsonType::DATA_STRING:
  377. {
  378. auto it = bonusUpdaterMap.find(updaterJson.String());
  379. if (it != bonusUpdaterMap.end())
  380. return it->second;
  381. logGlobal->error("Unknown bonus updater type '%s'", updaterJson.String());
  382. return nullptr;
  383. }
  384. case JsonNode::JsonType::DATA_STRUCT:
  385. if(updaterJson["type"].String() == "GROWS_WITH_LEVEL")
  386. {
  387. // MOD COMPATIBILITY - parameters is deprecated in 1.7
  388. const JsonNode & param = updaterJson["parameters"];
  389. int valPer20 = updaterJson["valPer20"].isNull() ? param[0].Integer() : updaterJson["valPer20"].Integer();
  390. int stepSize = updaterJson["stepSize"].isNull() ? param[1].Integer() : updaterJson["stepSize"].Integer();
  391. return std::make_shared<GrowsWithLevelUpdater>(valPer20, std::max(1, stepSize));
  392. }
  393. if(updaterJson["type"].String() == "TIMES_HERO_LEVEL")
  394. {
  395. int stepSize = updaterJson["stepSize"].Integer();
  396. return std::make_shared<TimesHeroLevelUpdater>(std::max(1, stepSize));
  397. }
  398. if(updaterJson["type"].String() == "TIMES_STACK_SIZE")
  399. {
  400. int minimum = updaterJson["minimum"].isNull() ? std::numeric_limits<int>::min() : updaterJson["minimum"].Integer();
  401. int maximum = updaterJson["maximum"].isNull() ? std::numeric_limits<int>::max() : updaterJson["maximum"].Integer();
  402. int stepSize = updaterJson["stepSize"].Integer();
  403. if (minimum > maximum)
  404. {
  405. logMod->warn("TIMES_STACK_SIZE updater: minimum value (%d) is above maximum value(%d)!", minimum, maximum);
  406. return std::make_shared<TimesStackSizeUpdater>(maximum, minimum, std::max(1, stepSize));
  407. }
  408. return std::make_shared<TimesStackSizeUpdater>(minimum, maximum, std::max(1, stepSize));
  409. }
  410. if(updaterJson["type"].String() == "TIMES_ARMY_SIZE")
  411. {
  412. auto result = std::make_shared<TimesArmySizeUpdater>();
  413. result->minimum = updaterJson["minimum"].isNull() ? std::numeric_limits<int>::min() : updaterJson["minimum"].Integer();
  414. result->maximum = updaterJson["maximum"].isNull() ? std::numeric_limits<int>::max() : updaterJson["maximum"].Integer();
  415. result->stepSize = updaterJson["stepSize"].isNull() ? 1 : updaterJson["stepSize"].Integer();
  416. result->filteredLevel = updaterJson["filteredLevel"].isNull() ? -1 : updaterJson["filteredLevel"].Integer();
  417. if (result->minimum > result->maximum)
  418. {
  419. logMod->warn("TIMES_ARMY_SIZE updater: minimum value (%d) is above maximum value(%d)!", result->minimum, result->maximum);
  420. std::swap(result->minimum, result->maximum);
  421. }
  422. if (!updaterJson["filteredFaction"].isNull())
  423. {
  424. LIBRARY->identifiers()->requestIdentifier( "faction", updaterJson["filteredFaction"], [result](int32_t identifier)
  425. {
  426. result->filteredFaction = FactionID(identifier);
  427. });
  428. }
  429. if (!updaterJson["filteredCreature"].isNull())
  430. {
  431. LIBRARY->identifiers()->requestIdentifier( "creature", updaterJson["filteredCreature"], [result](int32_t identifier)
  432. {
  433. result->filteredCreature = CreatureID(identifier);
  434. });
  435. }
  436. return result;
  437. }
  438. else
  439. logMod->warn("Unknown updater type \"%s\"", updaterJson["type"].String());
  440. break;
  441. }
  442. return nullptr;
  443. }
  444. VCMI_LIB_NAMESPACE_BEGIN
  445. std::shared_ptr<Bonus> JsonUtils::parseBonus(const JsonVector & ability_vec)
  446. {
  447. auto b = std::make_shared<Bonus>();
  448. const JsonNode & typeNode = ability_vec[0];
  449. const JsonNode & subtypeNode = ability_vec[2];
  450. LIBRARY->identifiers()->requestIdentifier("bonus", typeNode, [b, subtypeNode](si32 bonusID)
  451. {
  452. b->type = static_cast<BonusType>(bonusID);
  453. loadBonusSubtype(b->subtype, b->type, subtypeNode);
  454. });
  455. b->val = static_cast<si32>(ability_vec[1].Float());
  456. b->additionalInfo = static_cast<si32>(ability_vec[3].Float());
  457. b->duration = BonusDuration::PERMANENT; //TODO: handle flags (as integer)
  458. b->turnsRemain = 0;
  459. return b;
  460. }
  461. std::shared_ptr<const ILimiter> JsonUtils::parseLimiter(const JsonNode & limiter)
  462. {
  463. switch(limiter.getType())
  464. {
  465. case JsonNode::JsonType::DATA_VECTOR:
  466. {
  467. const JsonVector & subLimiters = limiter.Vector();
  468. if(subLimiters.empty())
  469. {
  470. logMod->warn("Warning: empty limiter list");
  471. return std::make_shared<AllOfLimiter>();
  472. }
  473. std::shared_ptr<AggregateLimiter> result;
  474. int offset = 1;
  475. // determine limiter type and offset for sub-limiters
  476. if(subLimiters[0].getType() == JsonNode::JsonType::DATA_STRING)
  477. {
  478. const std::string & aggregator = subLimiters[0].String();
  479. if(aggregator == AllOfLimiter::aggregator)
  480. result = std::make_shared<AllOfLimiter>();
  481. else if(aggregator == AnyOfLimiter::aggregator)
  482. result = std::make_shared<AnyOfLimiter>();
  483. else if(aggregator == NoneOfLimiter::aggregator)
  484. result = std::make_shared<NoneOfLimiter>();
  485. }
  486. if(!result)
  487. {
  488. // collapse for single limiter without explicit aggregate operator
  489. if(subLimiters.size() == 1)
  490. return parseLimiter(subLimiters[0]);
  491. // implicit aggregator must be allOf
  492. result = std::make_shared<AllOfLimiter>();
  493. offset = 0;
  494. }
  495. if(subLimiters.size() == offset)
  496. logMod->warn("Warning: empty sub-limiter list");
  497. for(int sl = offset; sl < subLimiters.size(); ++sl)
  498. result->add(parseLimiter(subLimiters[sl]));
  499. return result;
  500. }
  501. break;
  502. case JsonNode::JsonType::DATA_STRING: //pre-defined limiters
  503. return parseByMap(bonusLimiterMap, &limiter, "limiter type ");
  504. break;
  505. case JsonNode::JsonType::DATA_STRUCT: //customizable limiters
  506. {
  507. std::string limiterType = limiter["type"].String();
  508. const JsonNode & parameters = limiter["parameters"];
  509. if(limiterType == "CREATURE_TYPE_LIMITER")
  510. {
  511. auto creatureLimiter = std::make_shared<CCreatureTypeLimiter>();
  512. LIBRARY->identifiers()->requestIdentifier("creature", parameters[0], [=](si32 creature)
  513. {
  514. creatureLimiter->setCreature(CreatureID(creature));
  515. });
  516. auto includeUpgrades = false;
  517. if(parameters.Vector().size() > 1)
  518. {
  519. bool success = true;
  520. includeUpgrades = parameters[1].TryBoolFromString(success);
  521. if(!success)
  522. logMod->error("Second parameter of '%s' limiter should be Bool", limiterType);
  523. }
  524. creatureLimiter->includeUpgrades = includeUpgrades;
  525. return creatureLimiter;
  526. }
  527. else if(limiterType == "HAS_ANOTHER_BONUS_LIMITER")
  528. {
  529. auto bonusLimiter = std::make_shared<HasAnotherBonusLimiter>();
  530. static const JsonNode nullNode;
  531. const JsonNode & jsonType = parameters[0];
  532. const JsonNode & jsonSubtype = parameters.Vector().size() > 2 ? parameters[1] : nullNode;
  533. const JsonNode & jsonSource = parameters.Vector().size() > 2 ? parameters[2] : parameters[1];
  534. if (!jsonType.isNull())
  535. {
  536. LIBRARY->identifiers()->requestIdentifier("bonus", jsonType, [bonusLimiter, jsonSubtype](si32 bonusID)
  537. {
  538. bonusLimiter->type = static_cast<BonusType>(bonusID);
  539. if (jsonSubtype.isNull())
  540. loadBonusSubtype(bonusLimiter->subtype, bonusLimiter->type, jsonSubtype);
  541. });
  542. }
  543. if(!jsonSource.isNull())
  544. {
  545. auto sourceIt = bonusSourceMap.find(jsonSource["type"].String());
  546. if(sourceIt != bonusSourceMap.end())
  547. {
  548. bonusLimiter->source = sourceIt->second;
  549. bonusLimiter->isSourceRelevant = true;
  550. if(!jsonSource["id"].isNull()) {
  551. loadBonusSourceInstance(bonusLimiter->sid, bonusLimiter->source, jsonSource["id"]);
  552. bonusLimiter->isSourceIDRelevant = true;
  553. }
  554. }
  555. else
  556. logMod->warn("HAS_ANOTHER_BONUS_LIMITER: unknown bonus source type '%s'!", jsonSource["type"].String());
  557. }
  558. return bonusLimiter;
  559. }
  560. else if(limiterType == "CREATURE_ALIGNMENT_LIMITER")
  561. {
  562. int alignment = vstd::find_pos(GameConstants::ALIGNMENT_NAMES, parameters[0].String());
  563. if(alignment == -1)
  564. logMod->error("Error: invalid alignment %s.", parameters[0].String());
  565. else
  566. return std::make_shared<CreatureAlignmentLimiter>(static_cast<EAlignment>(alignment));
  567. }
  568. else if(limiterType == "FACTION_LIMITER" || limiterType == "CREATURE_FACTION_LIMITER") //Second name is deprecated, 1.2 compat
  569. {
  570. auto factionLimiter = std::make_shared<FactionLimiter>();
  571. LIBRARY->identifiers()->requestIdentifier("faction", parameters[0], [=](si32 faction)
  572. {
  573. factionLimiter->faction = FactionID(faction);
  574. });
  575. return factionLimiter;
  576. }
  577. else if(limiterType == "CREATURE_LEVEL_LIMITER")
  578. {
  579. auto levelLimiter = std::make_shared<CreatureLevelLimiter>();
  580. if(!parameters.Vector().empty()) //If parameters is empty, level limiter works as CREATURES_ONLY limiter
  581. {
  582. levelLimiter->minLevel = parameters[0].Integer();
  583. if(parameters[1].isNumber())
  584. levelLimiter->maxLevel = parameters[1].Integer();
  585. }
  586. return levelLimiter;
  587. }
  588. else if(limiterType == "CREATURE_TERRAIN_LIMITER")
  589. {
  590. auto terrainLimiter = std::make_shared<CreatureTerrainLimiter>();
  591. if(!parameters.Vector().empty())
  592. {
  593. LIBRARY->identifiers()->requestIdentifier("terrain", parameters[0], [terrainLimiter](si32 terrain)
  594. {
  595. terrainLimiter->terrainType = terrain;
  596. });
  597. }
  598. return terrainLimiter;
  599. }
  600. else if(limiterType == "UNIT_ON_HEXES") {
  601. auto hexLimiter = std::make_shared<UnitOnHexLimiter>();
  602. if(!parameters.Vector().empty())
  603. {
  604. for (const auto & parameter : parameters.Vector()){
  605. if(parameter.isNumber())
  606. hexLimiter->applicableHexes.insert(BattleHex(parameter.Integer()));
  607. }
  608. }
  609. return hexLimiter;
  610. }
  611. else if(limiterType == "HAS_CHARGES_LIMITER")
  612. {
  613. auto hasChargesLimiter = std::make_shared<HasChargesLimiter>();
  614. if(!parameters.Vector().empty())
  615. {
  616. if(parameters.Vector().size() == 1 && parameters.Vector().front().isNumber())
  617. hasChargesLimiter->chargeCost = parameters.Vector().front().Integer();
  618. }
  619. return hasChargesLimiter;
  620. }
  621. else
  622. {
  623. logMod->error("Error: invalid customizable limiter type %s.", limiterType);
  624. }
  625. }
  626. break;
  627. default:
  628. break;
  629. }
  630. return nullptr;
  631. }
  632. std::shared_ptr<Bonus> JsonUtils::parseBonus(const JsonNode &ability, const TextIdentifier & descriptionID)
  633. {
  634. auto b = std::make_shared<Bonus>();
  635. if (!parseBonus(ability, b.get(), descriptionID))
  636. {
  637. // caller code can not handle this case and presumes that returned bonus is always valid
  638. logGlobal->error("Failed to parse bonus! Json config was %S ", ability.toString());
  639. b->type = BonusType::NONE;
  640. return b;
  641. }
  642. return b;
  643. }
  644. bool JsonUtils::parseBonus(const JsonNode &ability, Bonus *b, const TextIdentifier & descriptionID)
  645. {
  646. const JsonNode * value = nullptr;
  647. const JsonNode & subtypeNode = ability["subtype"];
  648. const JsonNode & addinfoNode = ability["addInfo"];
  649. if (ability["type"].isNull())
  650. {
  651. logMod->error("Failed to parse bonus. Description: '%s'. Config: '%s'", descriptionID.get(), ability.toCompactString());
  652. return false;
  653. }
  654. LIBRARY->identifiers()->requestIdentifier("bonus", ability["type"], [b, subtypeNode, addinfoNode](si32 bonusID)
  655. {
  656. b->type = static_cast<BonusType>(bonusID);
  657. loadBonusSubtype(b->subtype, b->type, subtypeNode);
  658. loadBonusAddInfo(b->additionalInfo, b->type, addinfoNode);
  659. });
  660. b->val = static_cast<si32>(ability["val"].Float());
  661. value = &ability["valueType"];
  662. if (!value->isNull())
  663. b->valType = static_cast<BonusValueType>(parseByMapN(bonusValueMap, value, "value type "));
  664. b->stacking = ability["stacking"].String();
  665. b->turnsRemain = static_cast<si32>(ability["turns"].Float());
  666. if(!ability["description"].isNull())
  667. {
  668. if (ability["description"].isString() && !ability["description"].String().empty())
  669. {
  670. if (ability["description"].String()[0] == '@')
  671. b->description.appendTextID(ability["description"].String().substr(1));
  672. else if (!descriptionID.get().empty())
  673. {
  674. LIBRARY->generaltexth->registerString(ability.getModScope(), descriptionID, ability["description"]);
  675. b->description.appendTextID(descriptionID.get());
  676. }
  677. }
  678. if (ability["description"].isNumber())
  679. b->description.appendTextID("core.arraytxt." + std::to_string(ability["description"].Integer()));
  680. }
  681. if(!ability["icon"].isNull())
  682. b->customIconPath = ImagePath::fromJson(ability["icon"]);
  683. value = &ability["effectRange"];
  684. if (!value->isNull())
  685. b->effectRange = static_cast<BonusLimitEffect>(parseByMapN(bonusLimitEffect, value, "effect range "));
  686. value = &ability["duration"];
  687. if (!value->isNull())
  688. {
  689. switch (value->getType())
  690. {
  691. case JsonNode::JsonType::DATA_STRING:
  692. b->duration = parseByMap(bonusDurationMap, value, "duration type ");
  693. break;
  694. case JsonNode::JsonType::DATA_VECTOR:
  695. {
  696. BonusDuration::Type dur = 0;
  697. for (const JsonNode & d : value->Vector())
  698. dur |= parseByMapN(bonusDurationMap, &d, "duration type ");
  699. b->duration = dur;
  700. }
  701. break;
  702. default:
  703. logMod->error("Error! Wrong bonus duration format.");
  704. }
  705. }
  706. value = &ability["sourceType"];
  707. if (!value->isNull())
  708. b->source = static_cast<BonusSource>(parseByMap(bonusSourceMap, value, "source type "));
  709. if (!ability["sourceID"].isNull())
  710. loadBonusSourceInstance(b->sid, b->source, ability["sourceID"]);
  711. value = &ability["targetSourceType"];
  712. if (!value->isNull())
  713. b->targetSourceType = static_cast<BonusSource>(parseByMap(bonusSourceMap, value, "target type "));
  714. value = &ability["limiters"];
  715. if (!value->isNull())
  716. b->limiter = parseLimiter(*value);
  717. value = &ability["propagator"];
  718. if (!value->isNull())
  719. {
  720. //ALL_CREATURES old propagator compatibility
  721. if(value->String() == "ALL_CREATURES")
  722. {
  723. logMod->warn("ALL_CREATURES propagator is deprecated. Use GLOBAL_EFFECT propagator with CREATURES_ONLY limiter");
  724. b->addLimiter(std::make_shared<CreatureLevelLimiter>());
  725. b->propagator = bonusPropagatorMap.at("GLOBAL_EFFECT");
  726. }
  727. else
  728. b->propagator = parseByMap(bonusPropagatorMap, value, "propagator type ");
  729. }
  730. value = &ability["updater"];
  731. if(!value->isNull())
  732. b->addUpdater(parseUpdater(*value));
  733. value = &ability["propagationUpdater"];
  734. if(!value->isNull())
  735. b->propagationUpdater = parseUpdater(*value);
  736. return true;
  737. }
  738. CSelector JsonUtils::parseSelector(const JsonNode & ability)
  739. {
  740. CSelector ret = Selector::all;
  741. // Recursive parsers for anyOf, allOf, noneOf
  742. const auto * value = &ability["allOf"];
  743. if(value->isVector())
  744. {
  745. for(const auto & andN : value->Vector())
  746. ret = ret.And(parseSelector(andN));
  747. }
  748. value = &ability["anyOf"];
  749. if(value->isVector())
  750. {
  751. CSelector base = Selector::none;
  752. for(const auto & andN : value->Vector())
  753. base = base.Or(parseSelector(andN));
  754. ret = ret.And(base);
  755. }
  756. value = &ability["noneOf"];
  757. if(value->isVector())
  758. {
  759. CSelector base = Selector::none;
  760. for(const auto & andN : value->Vector())
  761. base = base.Or(parseSelector(andN));
  762. ret = ret.And(base.Not());
  763. }
  764. BonusType type = BonusType::NONE;
  765. // Actual selector parser
  766. value = &ability["type"];
  767. if(value->isString())
  768. {
  769. ret = ret.And(Selector::type()(static_cast<BonusType>(*LIBRARY->identifiers()->getIdentifier("bonus", value->String()))));
  770. }
  771. value = &ability["subtype"];
  772. if(!value->isNull() && type != BonusType::NONE)
  773. {
  774. BonusSubtypeID subtype;
  775. loadBonusSubtype(subtype, type, ability);
  776. ret = ret.And(Selector::subtype()(subtype));
  777. }
  778. value = &ability["sourceType"];
  779. std::optional<BonusSource> src = std::nullopt; //Fixes for GCC false maybe-uninitialized
  780. std::optional<BonusSourceID> id = std::nullopt;
  781. if(value->isString())
  782. {
  783. auto it = bonusSourceMap.find(value->String());
  784. if(it != bonusSourceMap.end())
  785. src = it->second;
  786. }
  787. value = &ability["sourceID"];
  788. if(!value->isNull() && src.has_value())
  789. {
  790. loadBonusSourceInstance(*id, *src, ability);
  791. }
  792. if(src && id)
  793. ret = ret.And(Selector::source(*src, *id));
  794. else if(src)
  795. ret = ret.And(Selector::sourceTypeSel(*src));
  796. value = &ability["targetSourceType"];
  797. if(value->isString())
  798. {
  799. auto it = bonusSourceMap.find(value->String());
  800. if(it != bonusSourceMap.end())
  801. ret = ret.And(Selector::targetSourceType()(it->second));
  802. }
  803. value = &ability["valueType"];
  804. if(value->isString())
  805. {
  806. auto it = bonusValueMap.find(value->String());
  807. if(it != bonusValueMap.end())
  808. ret = ret.And(Selector::valueType(it->second));
  809. }
  810. CAddInfo info;
  811. value = &ability["addInfo"];
  812. if(!value->isNull())
  813. {
  814. loadBonusAddInfo(info, type, ability["addInfo"]);
  815. ret = ret.And(Selector::info()(info));
  816. }
  817. value = &ability["effectRange"];
  818. if(value->isString())
  819. {
  820. auto it = bonusLimitEffect.find(value->String());
  821. if(it != bonusLimitEffect.end())
  822. ret = ret.And(Selector::effectRange()(it->second));
  823. }
  824. value = &ability["lastsTurns"];
  825. if(value->isNumber())
  826. ret = ret.And(Selector::turns(value->Integer()));
  827. value = &ability["lastsDays"];
  828. if(value->isNumber())
  829. ret = ret.And(Selector::days(value->Integer()));
  830. return ret;
  831. }
  832. VCMI_LIB_NAMESPACE_END