TargetCondition.cpp 14 KB

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