TargetCondition.cpp 13 KB

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