TargetCondition.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  1. /*
  2. * TargetCondition.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 "TargetCondition.h"
  12. #include "../GameConstants.h"
  13. #include "../CBonusTypeHandler.h"
  14. #include "../battle/CBattleInfoCallback.h"
  15. #include "../battle/Unit.h"
  16. #include "../bonuses/BonusParams.h"
  17. #include "../bonuses/BonusList.h"
  18. #include "../modding/IdentifierStorage.h"
  19. #include "../modding/ModUtility.h"
  20. #include "../serializer/JsonSerializeFormat.h"
  21. #include "../VCMI_Lib.h"
  22. VCMI_LIB_NAMESPACE_BEGIN
  23. namespace spells
  24. {
  25. class TargetConditionItemBase : public TargetConditionItem
  26. {
  27. public:
  28. bool inverted = false;
  29. bool exclusive = false;
  30. void setInverted(bool value) override
  31. {
  32. inverted = value;
  33. }
  34. void setExclusive(bool value) override
  35. {
  36. exclusive = value;
  37. }
  38. bool isExclusive() const override
  39. {
  40. return exclusive;
  41. }
  42. bool isReceptive(const Mechanics * m, const battle::Unit * target) const override
  43. {
  44. bool result = check(m, target);
  45. return inverted != result;
  46. }
  47. protected:
  48. virtual bool check(const Mechanics * m, const battle::Unit * target) const = 0;
  49. };
  50. class SelectorCondition : public TargetConditionItemBase
  51. {
  52. public:
  53. SelectorCondition(const CSelector & csel):
  54. sel(csel)
  55. {
  56. }
  57. SelectorCondition(const CSelector & csel, si32 minVal, si32 maxVal):
  58. sel(csel),
  59. minVal(minVal),
  60. maxVal(maxVal)
  61. {
  62. }
  63. protected:
  64. bool check(const Mechanics * m, const battle::Unit * target) const override
  65. {
  66. if(target->hasBonus(sel)) {
  67. auto b = target->valOfBonuses(sel,"");
  68. return b >= minVal && b <= maxVal;
  69. }
  70. return false;
  71. }
  72. private:
  73. CSelector sel;
  74. si32 minVal = std::numeric_limits<si32>::min();
  75. si32 maxVal = std::numeric_limits<si32>::max();
  76. };
  77. class ResistanceCondition : public TargetConditionItemBase
  78. {
  79. protected:
  80. bool check(const Mechanics * m, const battle::Unit * target) const override
  81. {
  82. if(m->isPositiveSpell()) //Always pass on positive
  83. return true;
  84. return target->magicResistance() < 100;
  85. }
  86. };
  87. class CreatureCondition : public TargetConditionItemBase
  88. {
  89. public:
  90. CreatureCondition(const CreatureID & type_): type(type_) {}
  91. protected:
  92. bool check(const Mechanics * m, const battle::Unit * target) const override
  93. {
  94. return target->creatureId() == type;
  95. }
  96. private:
  97. CreatureID type;
  98. };
  99. class AbsoluteLevelCondition : public TargetConditionItemBase
  100. {
  101. public:
  102. AbsoluteLevelCondition()
  103. {
  104. inverted = false;
  105. exclusive = true;
  106. }
  107. protected:
  108. bool check(const Mechanics * m, const battle::Unit * target) const override
  109. {
  110. if(!m->isMagicalEffect()) //Always pass on non-magical
  111. return true;
  112. std::stringstream cachingStr;
  113. cachingStr << "type_" << vstd::to_underlying(BonusType::LEVEL_SPELL_IMMUNITY) << "addInfo_1";
  114. TConstBonusListPtr levelImmunities = target->getBonuses(Selector::type()(BonusType::LEVEL_SPELL_IMMUNITY).And(Selector::info()(1)), cachingStr.str());
  115. return (levelImmunities->size() == 0 || levelImmunities->totalValue() < m->getSpellLevel() || m->getSpellLevel() <= 0);
  116. }
  117. };
  118. class AbsoluteSpellCondition : public TargetConditionItemBase
  119. {
  120. public:
  121. AbsoluteSpellCondition()
  122. {
  123. inverted = false;
  124. exclusive = true;
  125. }
  126. protected:
  127. bool check(const Mechanics * m, const battle::Unit * target) const override
  128. {
  129. std::stringstream cachingStr;
  130. cachingStr << "type_" << vstd::to_underlying(BonusType::SPELL_IMMUNITY) << "subtype_" << m->getSpellIndex() << "addInfo_1";
  131. return !target->hasBonus(Selector::typeSubtypeInfo(BonusType::SPELL_IMMUNITY, m->getSpellIndex(), 1), cachingStr.str());
  132. }
  133. };
  134. class ElementalCondition : public TargetConditionItemBase
  135. {
  136. public:
  137. ElementalCondition()
  138. {
  139. inverted = true;
  140. exclusive = true;
  141. }
  142. protected:
  143. bool check(const Mechanics * m, const battle::Unit * target) const override
  144. {
  145. bool elementalImmune = false;
  146. auto filter = m->getElementalImmunity();
  147. for(auto element : filter)
  148. {
  149. if(target->hasBonusOfType(element, 0)) //always resist if immune to all spells altogether
  150. {
  151. elementalImmune = true;
  152. break;
  153. }
  154. else if(!m->isPositiveSpell()) //negative or indifferent
  155. {
  156. if(target->hasBonusOfType(element, 1))
  157. {
  158. elementalImmune = true;
  159. break;
  160. }
  161. }
  162. }
  163. return elementalImmune;
  164. }
  165. };
  166. class NormalLevelCondition : public TargetConditionItemBase
  167. {
  168. public:
  169. NormalLevelCondition()
  170. {
  171. inverted = false;
  172. exclusive = true;
  173. }
  174. protected:
  175. bool check(const Mechanics * m, const battle::Unit * target) const override
  176. {
  177. if(!m->isMagicalEffect()) //Always pass on non-magical
  178. return true;
  179. TConstBonusListPtr levelImmunities = target->getBonuses(Selector::type()(BonusType::LEVEL_SPELL_IMMUNITY));
  180. return levelImmunities->size() == 0 ||
  181. levelImmunities->totalValue() < m->getSpellLevel() ||
  182. m->getSpellLevel() <= 0;
  183. }
  184. };
  185. class NormalSpellCondition : public TargetConditionItemBase
  186. {
  187. public:
  188. NormalSpellCondition()
  189. {
  190. inverted = false;
  191. exclusive = true;
  192. }
  193. protected:
  194. bool check(const Mechanics * m, const battle::Unit * target) const override
  195. {
  196. return !target->hasBonusOfType(BonusType::SPELL_IMMUNITY, m->getSpellIndex());
  197. }
  198. };
  199. //for Hypnotize
  200. class HealthValueCondition : public TargetConditionItemBase
  201. {
  202. protected:
  203. bool check(const Mechanics * m, const battle::Unit * target) const override
  204. {
  205. //todo: maybe do not resist on passive cast
  206. //TODO: what with other creatures casting hypnotize, Faerie Dragons style?
  207. int64_t subjectHealth = target->getAvailableHealth();
  208. //apply 'damage' bonus for hypnotize, including hero specialty
  209. auto maxHealth = m->applySpellBonus(m->getEffectValue(), target);
  210. return subjectHealth <= maxHealth;
  211. }
  212. };
  213. class SpellEffectCondition : public TargetConditionItemBase
  214. {
  215. public:
  216. SpellEffectCondition(const SpellID & spellID_): spellID(spellID_)
  217. {
  218. std::stringstream builder;
  219. builder << "source_" << vstd::to_underlying(BonusSource::SPELL_EFFECT) << "id_" << spellID.num;
  220. cachingString = builder.str();
  221. selector = Selector::source(BonusSource::SPELL_EFFECT, spellID.num);
  222. }
  223. protected:
  224. bool check(const Mechanics * m, const battle::Unit * target) const override
  225. {
  226. return target->hasBonus(selector, cachingString);
  227. }
  228. private:
  229. CSelector selector;
  230. std::string cachingString;
  231. SpellID spellID;
  232. };
  233. class ReceptiveFeatureCondition : public TargetConditionItemBase
  234. {
  235. protected:
  236. bool check(const Mechanics * m, const battle::Unit * target) const override
  237. {
  238. return m->isPositiveSpell() && target->hasBonus(selector, cachingString);
  239. }
  240. private:
  241. CSelector selector = Selector::type()(BonusType::RECEPTIVE);
  242. std::string cachingString = "type_RECEPTIVE";
  243. };
  244. class ImmunityNegationCondition : public TargetConditionItemBase
  245. {
  246. protected:
  247. bool check(const Mechanics * m, const battle::Unit * target) const override
  248. {
  249. const bool battleWideNegation = target->hasBonusOfType(BonusType::NEGATE_ALL_NATURAL_IMMUNITIES, 0);
  250. const bool heroNegation = target->hasBonusOfType(BonusType::NEGATE_ALL_NATURAL_IMMUNITIES, 1);
  251. //Non-magical effects is not affected by orb of vulnerability
  252. if(!m->isMagicalEffect())
  253. return false;
  254. //anyone can cast on artifact holder`s stacks
  255. if(heroNegation)
  256. {
  257. return true;
  258. }
  259. //this stack is from other player
  260. else if(battleWideNegation)
  261. {
  262. if(m->ownerMatches(target, false))
  263. return true;
  264. }
  265. return false;
  266. }
  267. };
  268. class DefaultTargetConditionItemFactory : public TargetConditionItemFactory
  269. {
  270. public:
  271. Object createAbsoluteLevel() const override
  272. {
  273. static std::shared_ptr<TargetConditionItem> antimagicCondition = std::make_shared<AbsoluteLevelCondition>();
  274. return antimagicCondition;
  275. }
  276. Object createAbsoluteSpell() const override
  277. {
  278. static std::shared_ptr<TargetConditionItem> alCondition = std::make_shared<AbsoluteSpellCondition>();
  279. return alCondition;
  280. }
  281. Object createElemental() const override
  282. {
  283. static std::shared_ptr<TargetConditionItem> elementalCondition = std::make_shared<ElementalCondition>();
  284. return elementalCondition;
  285. }
  286. Object createResistance() const override
  287. {
  288. static auto elementalCondition = std::make_shared<ResistanceCondition>();
  289. return elementalCondition;
  290. }
  291. Object createNormalLevel() const override
  292. {
  293. static std::shared_ptr<TargetConditionItem> nlCondition = std::make_shared<NormalLevelCondition>();
  294. return nlCondition;
  295. }
  296. Object createNormalSpell() const override
  297. {
  298. static std::shared_ptr<TargetConditionItem> nsCondition = std::make_shared<NormalSpellCondition>();
  299. return nsCondition;
  300. }
  301. Object createConfigurable(std::string scope, std::string type, std::string identifier) const override
  302. {
  303. if(type == "bonus")
  304. {
  305. //TODO: support custom bonus types
  306. auto it = bonusNameMap.find(identifier);
  307. if(it != bonusNameMap.end())
  308. return std::make_shared<SelectorCondition>(Selector::type()(it->second));
  309. auto params = BonusParams(identifier, "", -1);
  310. if(params.isConverted)
  311. {
  312. if(params.val)
  313. return std::make_shared<SelectorCondition>(params.toSelector(), *params.val, *params.val);
  314. return std::make_shared<SelectorCondition>(params.toSelector());
  315. }
  316. logMod->error("Invalid bonus type %s in spell target condition.", identifier);
  317. }
  318. else if(type == "creature")
  319. {
  320. auto rawId = VLC->identifiers()->getIdentifier(scope, type, identifier, true);
  321. if(rawId)
  322. return std::make_shared<CreatureCondition>(CreatureID(rawId.value()));
  323. else
  324. logMod->error("Invalid creature %s type in spell target condition.", identifier);
  325. }
  326. else if(type == "spell")
  327. {
  328. auto rawId = VLC->identifiers()->getIdentifier(scope, type, identifier, true);
  329. if(rawId)
  330. return std::make_shared<SpellEffectCondition>(SpellID(rawId.value()));
  331. else
  332. logMod->error("Invalid spell %s in spell target condition.", identifier);
  333. }
  334. else if(type == "healthValueSpecial")
  335. {
  336. return std::make_shared<HealthValueCondition>();
  337. }
  338. else
  339. {
  340. logMod->error("Invalid type %s in spell target condition.", type);
  341. }
  342. return Object();
  343. }
  344. Object createFromJsonStruct(const JsonNode & jsonStruct) const override
  345. {
  346. auto type = jsonStruct["type"].String();
  347. auto parameters = jsonStruct["parameters"];
  348. if(type == "selector")
  349. {
  350. auto minVal = std::numeric_limits<si32>::min();
  351. auto maxVal = std::numeric_limits<si32>::max();
  352. if(parameters["minVal"].isNumber())
  353. minVal = parameters["minVal"].Integer();
  354. if(parameters["maxVal"].isNumber())
  355. maxVal = parameters["maxVal"].Integer();
  356. auto sel = JsonUtils::parseSelector(parameters);
  357. return std::make_shared<SelectorCondition>(sel, minVal, maxVal);
  358. }
  359. logMod->error("Invalid type %s in spell target condition.", type);
  360. return Object();
  361. }
  362. Object createReceptiveFeature() const override
  363. {
  364. static std::shared_ptr<TargetConditionItem> condition = std::make_shared<ReceptiveFeatureCondition>();
  365. return condition;
  366. }
  367. Object createImmunityNegation() const override
  368. {
  369. static std::shared_ptr<TargetConditionItem> condition = std::make_shared<ImmunityNegationCondition>();
  370. return condition;
  371. }
  372. };
  373. const TargetConditionItemFactory * TargetConditionItemFactory::getDefault()
  374. {
  375. static std::unique_ptr<TargetConditionItemFactory> singleton;
  376. if(!singleton)
  377. singleton = std::make_unique<DefaultTargetConditionItemFactory>();
  378. return singleton.get();
  379. }
  380. bool TargetCondition::isReceptive(const Mechanics * m, const battle::Unit * target) const
  381. {
  382. if(!check(absolute, m, target))
  383. return false;
  384. for(const auto & item : negation)
  385. {
  386. if(item->isReceptive(m, target))
  387. return true;
  388. }
  389. return check(normal, m, target);
  390. }
  391. void TargetCondition::serializeJson(JsonSerializeFormat & handler, const ItemFactory * itemFactory)
  392. {
  393. if(handler.saving)
  394. {
  395. logGlobal->error("Spell target condition saving is not supported");
  396. return;
  397. }
  398. absolute.clear();
  399. normal.clear();
  400. negation.clear();
  401. absolute.push_back(itemFactory->createAbsoluteSpell());
  402. absolute.push_back(itemFactory->createAbsoluteLevel());
  403. normal.push_back(itemFactory->createElemental());
  404. normal.push_back(itemFactory->createResistance());
  405. normal.push_back(itemFactory->createNormalLevel());
  406. normal.push_back(itemFactory->createNormalSpell());
  407. negation.push_back(itemFactory->createReceptiveFeature());
  408. negation.push_back(itemFactory->createImmunityNegation());
  409. {
  410. auto anyOf = handler.enterStruct("anyOf");
  411. loadConditions(anyOf->getCurrent(), false, false, itemFactory);
  412. }
  413. {
  414. auto allOf = handler.enterStruct("allOf");
  415. loadConditions(allOf->getCurrent(), true, false, itemFactory);
  416. }
  417. {
  418. auto noneOf = handler.enterStruct("noneOf");
  419. loadConditions(noneOf->getCurrent(), true, true, itemFactory);
  420. }
  421. }
  422. bool TargetCondition::check(const ItemVector & condition, const Mechanics * m, const battle::Unit * target) const
  423. {
  424. bool nonExclusiveCheck = false;
  425. bool nonExclusiveExits = false;
  426. for(const auto & item : condition)
  427. {
  428. if(item->isExclusive())
  429. {
  430. if(!item->isReceptive(m, target))
  431. return false;
  432. }
  433. else
  434. {
  435. if(item->isReceptive(m, target))
  436. nonExclusiveCheck = true;
  437. nonExclusiveExits = true;
  438. }
  439. }
  440. return !nonExclusiveExits || nonExclusiveCheck;
  441. }
  442. void TargetCondition::loadConditions(const JsonNode & source, bool exclusive, bool inverted, const ItemFactory * itemFactory)
  443. {
  444. for(const auto & keyValue : source.Struct())
  445. {
  446. bool isAbsolute;
  447. const JsonNode & value = keyValue.second;
  448. if(value.String() == "absolute")
  449. isAbsolute = true;
  450. else if(value.String() == "normal")
  451. isAbsolute = false;
  452. else if(value.isStruct()) //assume conditions have a new struct format
  453. isAbsolute = value["absolute"].Bool();
  454. else
  455. continue;
  456. std::shared_ptr<TargetConditionItem> item;
  457. if(value.isStruct())
  458. item = itemFactory->createFromJsonStruct(value);
  459. else
  460. {
  461. std::string scope;
  462. std::string type;
  463. std::string identifier;
  464. ModUtility::parseIdentifier(keyValue.first, scope, type, identifier);
  465. item = itemFactory->createConfigurable(keyValue.second.meta, type, identifier);
  466. }
  467. if(item)
  468. {
  469. item->setExclusive(exclusive);
  470. item->setInverted(inverted);
  471. if(isAbsolute)
  472. absolute.push_back(item);
  473. else
  474. normal.push_back(item);
  475. }
  476. }
  477. }
  478. }
  479. VCMI_LIB_NAMESPACE_END