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