CDefaultSpellMechanics.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775
  1. /*
  2. * CDefaultSpellMechanics.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 "CDefaultSpellMechanics.h"
  12. #include "../BattleState.h"
  13. #include "../CGeneralTextHandler.h"
  14. namespace SRSLPraserHelpers
  15. {
  16. static int XYToHex(int x, int y)
  17. {
  18. return x + GameConstants::BFIELD_WIDTH * y;
  19. }
  20. static int XYToHex(std::pair<int, int> xy)
  21. {
  22. return XYToHex(xy.first, xy.second);
  23. }
  24. static int hexToY(int battleFieldPosition)
  25. {
  26. return battleFieldPosition/GameConstants::BFIELD_WIDTH;
  27. }
  28. static int hexToX(int battleFieldPosition)
  29. {
  30. int pos = battleFieldPosition - hexToY(battleFieldPosition) * GameConstants::BFIELD_WIDTH;
  31. return pos;
  32. }
  33. static std::pair<int, int> hexToPair(int battleFieldPosition)
  34. {
  35. return std::make_pair(hexToX(battleFieldPosition), hexToY(battleFieldPosition));
  36. }
  37. //moves hex by one hex in given direction
  38. //0 - left top, 1 - right top, 2 - right, 3 - right bottom, 4 - left bottom, 5 - left
  39. static std::pair<int, int> gotoDir(int x, int y, int direction)
  40. {
  41. switch(direction)
  42. {
  43. case 0: //top left
  44. return std::make_pair((y%2) ? x-1 : x, y-1);
  45. case 1: //top right
  46. return std::make_pair((y%2) ? x : x+1, y-1);
  47. case 2: //right
  48. return std::make_pair(x+1, y);
  49. case 3: //right bottom
  50. return std::make_pair((y%2) ? x : x+1, y+1);
  51. case 4: //left bottom
  52. return std::make_pair((y%2) ? x-1 : x, y+1);
  53. case 5: //left
  54. return std::make_pair(x-1, y);
  55. default:
  56. throw std::runtime_error("Disaster: wrong direction in SRSLPraserHelpers::gotoDir!\n");
  57. }
  58. }
  59. static std::pair<int, int> gotoDir(std::pair<int, int> xy, int direction)
  60. {
  61. return gotoDir(xy.first, xy.second, direction);
  62. }
  63. static bool isGoodHex(std::pair<int, int> xy)
  64. {
  65. return xy.first >=0 && xy.first < GameConstants::BFIELD_WIDTH && xy.second >= 0 && xy.second < GameConstants::BFIELD_HEIGHT;
  66. }
  67. //helper function for rangeInHexes
  68. static std::set<ui16> getInRange(unsigned int center, int low, int high)
  69. {
  70. std::set<ui16> ret;
  71. if(low == 0)
  72. {
  73. ret.insert(center);
  74. }
  75. std::pair<int, int> mainPointForLayer[6]; //A, B, C, D, E, F points
  76. for(auto & elem : mainPointForLayer)
  77. elem = hexToPair(center);
  78. for(int it=1; it<=high; ++it) //it - distance to the center
  79. {
  80. for(int b=0; b<6; ++b)
  81. mainPointForLayer[b] = gotoDir(mainPointForLayer[b], b);
  82. if(it>=low)
  83. {
  84. std::pair<int, int> curHex;
  85. //adding lines (A-b, B-c, C-d, etc)
  86. for(int v=0; v<6; ++v)
  87. {
  88. curHex = mainPointForLayer[v];
  89. for(int h=0; h<it; ++h)
  90. {
  91. if(isGoodHex(curHex))
  92. ret.insert(XYToHex(curHex));
  93. curHex = gotoDir(curHex, (v+2)%6);
  94. }
  95. }
  96. } //if(it>=low)
  97. }
  98. return ret;
  99. }
  100. }
  101. SpellCastContext::SpellCastContext(const DefaultSpellMechanics * mechanics_, const BattleSpellCastParameters & parameters):
  102. mechanics(mechanics_), attackedCres(), sc(), si()
  103. {
  104. prepareBattleCast(parameters);
  105. }
  106. void SpellCastContext::prepareBattleCast(const BattleSpellCastParameters & parameters)
  107. {
  108. sc.side = parameters.casterSide;
  109. sc.id = mechanics->owner->id;
  110. sc.skill = parameters.spellLvl;
  111. sc.tile = parameters.getFirstDestinationHex();
  112. sc.dmgToDisplay = 0;
  113. sc.castByHero = parameters.mode == ECastingMode::HERO_CASTING;
  114. sc.casterStack = (parameters.casterStack ? parameters.casterStack->ID : -1);
  115. sc.manaGained = 0;
  116. }
  117. ///DefaultSpellMechanics
  118. void DefaultSpellMechanics::applyBattle(BattleInfo * battle, const BattleSpellCast * packet) const
  119. {
  120. if (packet->castByHero)
  121. {
  122. if (packet->side < 2)
  123. {
  124. battle->sides[packet->side].castSpellsCount++;
  125. }
  126. }
  127. //handle countering spells
  128. for(auto stackID : packet->affectedCres)
  129. {
  130. CStack * s = battle->getStack(stackID);
  131. s->popBonuses([&](const Bonus * b) -> bool
  132. {
  133. //check for each bonus if it should be removed
  134. const bool isSpellEffect = Selector::sourceType(Bonus::SPELL_EFFECT)(b);
  135. const int spellID = isSpellEffect ? b->sid : -1;
  136. //No exceptions, ANY spell can be countered, even if it can`t be dispelled.
  137. return isSpellEffect && vstd::contains(owner->counteredSpells, spellID);
  138. });
  139. }
  140. }
  141. void DefaultSpellMechanics::battleCast(const SpellCastEnvironment * env, BattleSpellCastParameters & parameters) const
  142. {
  143. logGlobal->debugStream() << "Started spell cast. Spell: "<<owner->name<<"; mode:"<<parameters.mode;
  144. if(nullptr == parameters.caster)
  145. {
  146. env->complain("No spell-caster provided.");
  147. return;
  148. }
  149. SpellCastContext ctx(this, parameters);
  150. //check it there is opponent hero
  151. const ui8 otherSide = 1-parameters.casterSide;
  152. const CGHeroInstance * otherHero = nullptr;
  153. if(parameters.cb->battleHasHero(otherSide))
  154. otherHero = parameters.cb->battleGetFightingHero(otherSide);
  155. int spellCost = 0;
  156. //calculate spell cost
  157. if(parameters.mode == ECastingMode::HERO_CASTING)
  158. {
  159. spellCost = parameters.cb->battleGetSpellCost(owner, parameters.casterHero);
  160. if(nullptr != otherHero) //handle mana channel
  161. {
  162. int manaChannel = 0;
  163. for(const CStack * stack : parameters.cb->battleGetAllStacks(true)) //TODO: shouldn't bonus system handle it somehow?
  164. {
  165. if(stack->owner == otherHero->tempOwner)
  166. {
  167. vstd::amax(manaChannel, stack->valOfBonuses(Bonus::MANA_CHANNELING));
  168. }
  169. }
  170. ctx.sc.manaGained = (manaChannel * spellCost) / 100;
  171. }
  172. }
  173. logGlobal->debugStream() << "spellCost: " << spellCost;
  174. auto creatures = owner->getAffectedStacks(parameters.cb, parameters.mode, parameters.caster, parameters.spellLvl, parameters.getFirstDestinationHex());
  175. std::copy(creatures.begin(), creatures.end(), std::back_inserter(ctx.attackedCres));
  176. logGlobal->debugStream() << "will affect: " << ctx.attackedCres.size() << " stacks";
  177. std::vector <const CStack*> reflected;//for magic mirror
  178. //checking if creatures resist
  179. handleResistance(env, ctx.attackedCres, ctx.sc);
  180. //it is actual spell and can be reflected to single target, no recurrence
  181. const bool tryMagicMirror = owner->isNegative() && owner->level && owner->getLevelInfo(0).range == "0";
  182. if(tryMagicMirror)
  183. {
  184. for(auto s : ctx.attackedCres)
  185. {
  186. const int mirrorChance = (s)->valOfBonuses(Bonus::MAGIC_MIRROR);
  187. if(env->getRandomGenerator().nextInt(99) < mirrorChance)
  188. reflected.push_back(s);
  189. }
  190. vstd::erase_if(ctx.attackedCres, [&reflected](const CStack * s)
  191. {
  192. return vstd::contains(reflected, s);
  193. });
  194. for(auto s : reflected)
  195. {
  196. BattleSpellCast::CustomEffect effect;
  197. effect.effect = 3;
  198. effect.stack = s->ID;
  199. ctx.sc.customEffects.push_back(effect);
  200. }
  201. }
  202. for(auto cre : ctx.attackedCres)
  203. {
  204. ctx.sc.affectedCres.insert(cre->ID);
  205. }
  206. applyBattleEffects(env, parameters, ctx);
  207. env->sendAndApply(&ctx.sc);
  208. if(parameters.mode == ECastingMode::HERO_CASTING)
  209. {
  210. //spend mana
  211. SetMana sm;
  212. sm.absolute = false;
  213. sm.hid = parameters.casterHero->id;
  214. sm.val = -spellCost;
  215. env->sendAndApply(&sm);
  216. if(ctx.sc.manaGained > 0)
  217. {
  218. assert(otherHero);
  219. sm.hid = otherHero->id;
  220. sm.val = ctx.sc.manaGained;
  221. env->sendAndApply(&sm);
  222. }
  223. }
  224. else if (parameters.mode == ECastingMode::CREATURE_ACTIVE_CASTING || parameters.mode == ECastingMode::ENCHANTER_CASTING)
  225. {
  226. //reduce number of casts remaining
  227. assert(parameters.casterStack);
  228. BattleSetStackProperty ssp;
  229. ssp.stackID = parameters.casterStack->ID;
  230. ssp.which = BattleSetStackProperty::CASTS;
  231. ssp.val = -1;
  232. ssp.absolute = false;
  233. env->sendAndApply(&ssp);
  234. }
  235. if(!ctx.si.stacks.empty()) //after spellcast info shows
  236. env->sendAndApply(&ctx.si);
  237. logGlobal->debugStream() << "Finished spell cast. Spell: "<<owner->name<<"; mode:"<<parameters.mode;
  238. //Magic Mirror effect
  239. for(auto & attackedCre : reflected)
  240. {
  241. TStacks mirrorTargets = parameters.cb->battleGetStacksIf([this, parameters](const CStack * battleStack)
  242. {
  243. //Get all enemy stacks. Magic mirror can reflect to immune creature (with no effect)
  244. return battleStack->owner == parameters.casterColor && battleStack->isValidTarget(false);
  245. });
  246. if(!mirrorTargets.empty())
  247. {
  248. int targetHex = (*RandomGeneratorUtil::nextItem(mirrorTargets, env->getRandomGenerator()))->position;
  249. BattleSpellCastParameters mirrorParameters(parameters.cb, attackedCre, owner);
  250. mirrorParameters.spellLvl = 0;
  251. mirrorParameters.aimToHex(targetHex);
  252. mirrorParameters.mode = ECastingMode::MAGIC_MIRROR;
  253. mirrorParameters.selectedStack = nullptr;
  254. mirrorParameters.spellLvl = parameters.spellLvl;
  255. mirrorParameters.effectLevel = parameters.effectLevel;
  256. mirrorParameters.effectPower = parameters.effectPower;
  257. mirrorParameters.effectValue = parameters.effectValue;
  258. mirrorParameters.enchantPower = parameters.enchantPower;
  259. castMagicMirror(env, mirrorParameters);
  260. }
  261. }
  262. }
  263. void DefaultSpellMechanics::battleLogSingleTarget(std::vector<std::string> & logLines, const BattleSpellCast * packet,
  264. const std::string & casterName, const CStack * attackedStack, bool & displayDamage) const
  265. {
  266. const std::string attackedName = attackedStack->getName();
  267. const std::string attackedNameSing = attackedStack->getCreature()->nameSing;
  268. const std::string attackedNamePl = attackedStack->getCreature()->namePl;
  269. auto getPluralFormat = [attackedStack](const int baseTextID) -> boost::format
  270. {
  271. return boost::format(VLC->generaltexth->allTexts[(attackedStack->count > 1 ? baseTextID + 1 : baseTextID)]);
  272. };
  273. auto logSimple = [&logLines, getPluralFormat, attackedName](const int baseTextID)
  274. {
  275. boost::format fmt = getPluralFormat(baseTextID);
  276. fmt % attackedName;
  277. logLines.push_back(fmt.str());
  278. };
  279. auto logPlural = [&logLines, attackedNamePl](const int baseTextID)
  280. {
  281. boost::format fmt(VLC->generaltexth->allTexts[baseTextID]);
  282. fmt % attackedNamePl;
  283. logLines.push_back(fmt.str());
  284. };
  285. displayDamage = false; //in most following cases damage info text is custom
  286. switch(owner->id)
  287. {
  288. case SpellID::STONE_GAZE:
  289. logSimple(558);
  290. break;
  291. case SpellID::POISON:
  292. logSimple(561);
  293. break;
  294. case SpellID::BIND:
  295. logPlural(560);//Roots and vines bind the %s to the ground!
  296. break;
  297. case SpellID::DISEASE:
  298. logSimple(553);
  299. break;
  300. case SpellID::PARALYZE:
  301. logSimple(563);
  302. break;
  303. case SpellID::AGE:
  304. {
  305. boost::format text = getPluralFormat(551);
  306. text % attackedName;
  307. //The %s shrivel with age, and lose %d hit points."
  308. TBonusListPtr bl = attackedStack->getBonuses(Selector::type(Bonus::STACK_HEALTH));
  309. const int fullHP = bl->totalValue();
  310. bl->remove_if(Selector::source(Bonus::SPELL_EFFECT, SpellID::AGE));
  311. text % (fullHP - bl->totalValue());
  312. logLines.push_back(text.str());
  313. }
  314. break;
  315. case SpellID::THUNDERBOLT:
  316. {
  317. logPlural(367);
  318. std::string text = VLC->generaltexth->allTexts[343].substr(1, VLC->generaltexth->allTexts[343].size() - 1); //Does %d points of damage.
  319. boost::algorithm::replace_first(text, "%d", boost::lexical_cast<std::string>(packet->dmgToDisplay)); //no more text afterwards
  320. logLines.push_back(text);
  321. }
  322. break;
  323. case SpellID::DISPEL_HELPFUL_SPELLS:
  324. logPlural(555);
  325. break;
  326. case SpellID::DEATH_STARE:
  327. if (packet->dmgToDisplay > 0)
  328. {
  329. std::string text;
  330. if (packet->dmgToDisplay > 1)
  331. {
  332. text = VLC->generaltexth->allTexts[119]; //%d %s die under the terrible gaze of the %s.
  333. boost::algorithm::replace_first(text, "%d", boost::lexical_cast<std::string>(packet->dmgToDisplay));
  334. boost::algorithm::replace_first(text, "%s", attackedNamePl);
  335. }
  336. else
  337. {
  338. text = VLC->generaltexth->allTexts[118]; //One %s dies under the terrible gaze of the %s.
  339. boost::algorithm::replace_first(text, "%s", attackedNameSing);
  340. }
  341. boost::algorithm::replace_first(text, "%s", casterName); //casting stack
  342. logLines.push_back(text);
  343. }
  344. break;
  345. default:
  346. {
  347. boost::format text(VLC->generaltexth->allTexts[565]); //The %s casts %s
  348. text % casterName % owner->name;
  349. displayDamage = true;
  350. logLines.push_back(text.str());
  351. }
  352. break;
  353. }
  354. }
  355. void DefaultSpellMechanics::applyBattleEffects(const SpellCastEnvironment * env, const BattleSpellCastParameters & parameters, SpellCastContext & ctx) const
  356. {
  357. //applying effects
  358. if(owner->isOffensiveSpell())
  359. {
  360. int spellDamage = parameters.effectValue;
  361. int chainLightningModifier = 0;
  362. for(auto & attackedCre : ctx.attackedCres)
  363. {
  364. BattleStackAttacked bsa;
  365. if(spellDamage != 0)
  366. bsa.damageAmount = owner->adjustRawDamage(parameters.caster, attackedCre, spellDamage) >> chainLightningModifier;
  367. else
  368. bsa.damageAmount = owner->calculateDamage(parameters.caster, attackedCre, parameters.effectLevel, parameters.effectPower) >> chainLightningModifier;
  369. ctx.sc.dmgToDisplay += bsa.damageAmount;
  370. bsa.stackAttacked = (attackedCre)->ID;
  371. if(parameters.mode == ECastingMode::ENCHANTER_CASTING) //multiple damage spells cast
  372. bsa.attackerID = parameters.casterStack->ID;
  373. else
  374. bsa.attackerID = -1;
  375. (attackedCre)->prepareAttacked(bsa, env->getRandomGenerator());
  376. ctx.si.stacks.push_back(bsa);
  377. if(owner->id == SpellID::CHAIN_LIGHTNING)
  378. ++chainLightningModifier;
  379. }
  380. }
  381. if(owner->hasEffects())
  382. {
  383. SetStackEffect sse;
  384. //get default spell duration (spell power with bonuses for heroes)
  385. int duration = parameters.enchantPower;
  386. //generate actual stack bonuses
  387. {
  388. int maxDuration = 0;
  389. std::vector<Bonus> tmp;
  390. owner->getEffects(tmp, parameters.effectLevel);
  391. for(Bonus& b : tmp)
  392. {
  393. //use configured duration if present
  394. if(b.turnsRemain == 0)
  395. b.turnsRemain = duration;
  396. vstd::amax(maxDuration, b.turnsRemain);
  397. sse.effect.push_back(b);
  398. }
  399. //if all spell effects have special duration, use it
  400. duration = maxDuration;
  401. }
  402. //fix to original config: shield should display damage reduction
  403. if(owner->id == SpellID::SHIELD || owner->id == SpellID::AIR_SHIELD)
  404. {
  405. sse.effect.back().val = (100 - sse.effect.back().val);
  406. }
  407. //we need to know who cast Bind
  408. if(owner->id == SpellID::BIND && parameters.casterStack)
  409. {
  410. sse.effect.back().additionalInfo = parameters.casterStack->ID;
  411. }
  412. const Bonus * bonus = nullptr;
  413. if(parameters.casterHero)
  414. bonus = parameters.casterHero->getBonusLocalFirst(Selector::typeSubtype(Bonus::SPECIAL_PECULIAR_ENCHANT, owner->id));
  415. //TODO does hero specialty should affects his stack casting spells?
  416. si32 power = 0;
  417. for(const CStack * affected : ctx.attackedCres)
  418. {
  419. sse.stacks.push_back(affected->ID);
  420. //Apply hero specials - peculiar enchants
  421. const ui8 tier = std::max((ui8)1, affected->getCreature()->level); //don't divide by 0 for certain creatures (commanders, war machines)
  422. if(bonus)
  423. {
  424. switch(bonus->additionalInfo)
  425. {
  426. case 0: //normal
  427. {
  428. switch(tier)
  429. {
  430. case 1: case 2:
  431. power = 3;
  432. break;
  433. case 3: case 4:
  434. power = 2;
  435. break;
  436. case 5: case 6:
  437. power = 1;
  438. break;
  439. }
  440. Bonus specialBonus(sse.effect.back());
  441. specialBonus.val = power; //it doesn't necessarily make sense for some spells, use it wisely
  442. sse.uniqueBonuses.push_back (std::pair<ui32,Bonus> (affected->ID, specialBonus)); //additional premy to given effect
  443. }
  444. break;
  445. case 1: //only Coronius as yet
  446. {
  447. power = std::max(5 - tier, 0);
  448. Bonus specialBonus = CStack::featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, power, duration);
  449. specialBonus.sid = owner->id;
  450. sse.uniqueBonuses.push_back(std::pair<ui32,Bonus> (affected->ID, specialBonus)); //additional attack to Slayer effect
  451. }
  452. break;
  453. }
  454. }
  455. if (parameters.casterHero && parameters.casterHero->hasBonusOfType(Bonus::SPECIAL_BLESS_DAMAGE, owner->id)) //TODO: better handling of bonus percentages
  456. {
  457. int damagePercent = parameters.casterHero->level * parameters.casterHero->valOfBonuses(Bonus::SPECIAL_BLESS_DAMAGE, owner->id.toEnum()) / tier;
  458. Bonus specialBonus = CStack::featureGenerator(Bonus::CREATURE_DAMAGE, 0, damagePercent, duration);
  459. specialBonus.valType = Bonus::PERCENT_TO_ALL;
  460. specialBonus.sid = owner->id;
  461. sse.uniqueBonuses.push_back (std::pair<ui32,Bonus> (affected->ID, specialBonus));
  462. }
  463. }
  464. if(!sse.stacks.empty())
  465. env->sendAndApply(&sse);
  466. }
  467. }
  468. std::vector<BattleHex> DefaultSpellMechanics::rangeInHexes(BattleHex centralHex, ui8 schoolLvl, ui8 side, bool *outDroppedHexes) const
  469. {
  470. using namespace SRSLPraserHelpers;
  471. std::vector<BattleHex> ret;
  472. std::string rng = owner->getLevelInfo(schoolLvl).range + ','; //copy + artificial comma for easier handling
  473. if(rng.size() >= 2 && rng[0] != 'X') //there is at lest one hex in range (+artificial comma)
  474. {
  475. std::string number1, number2;
  476. int beg, end;
  477. bool readingFirst = true;
  478. for(auto & elem : rng)
  479. {
  480. if(std::isdigit(elem) ) //reading number
  481. {
  482. if(readingFirst)
  483. number1 += elem;
  484. else
  485. number2 += elem;
  486. }
  487. else if(elem == ',') //comma
  488. {
  489. //calculating variables
  490. if(readingFirst)
  491. {
  492. beg = atoi(number1.c_str());
  493. number1 = "";
  494. }
  495. else
  496. {
  497. end = atoi(number2.c_str());
  498. number2 = "";
  499. }
  500. //obtaining new hexes
  501. std::set<ui16> curLayer;
  502. if(readingFirst)
  503. {
  504. curLayer = getInRange(centralHex, beg, beg);
  505. }
  506. else
  507. {
  508. curLayer = getInRange(centralHex, beg, end);
  509. readingFirst = true;
  510. }
  511. //adding abtained hexes
  512. for(auto & curLayer_it : curLayer)
  513. {
  514. ret.push_back(curLayer_it);
  515. }
  516. }
  517. else if(elem == '-') //dash
  518. {
  519. beg = atoi(number1.c_str());
  520. number1 = "";
  521. readingFirst = false;
  522. }
  523. }
  524. }
  525. //remove duplicates (TODO check if actually needed)
  526. range::unique(ret);
  527. return ret;
  528. }
  529. std::set<const CStack *> DefaultSpellMechanics::getAffectedStacks(const CBattleInfoCallback * cb, SpellTargetingContext & ctx) const
  530. {
  531. std::set<const CStack* > attackedCres;//std::set to exclude multiple occurrences of two hex creatures
  532. const ui8 attackerSide = cb->playerToSide(ctx.caster->getOwner()) == 1;
  533. const auto attackedHexes = rangeInHexes(ctx.destination, ctx.schoolLvl, attackerSide);
  534. //TODO: more generic solution for mass spells
  535. if(owner->getLevelInfo(ctx.schoolLvl).range.size() > 1) //custom many-hex range
  536. {
  537. for(BattleHex hex : attackedHexes)
  538. {
  539. if(const CStack * st = cb->battleGetStackByPos(hex, ctx.ti.onlyAlive))
  540. {
  541. attackedCres.insert(st);
  542. }
  543. }
  544. }
  545. else if(ctx.ti.type == CSpell::CREATURE)
  546. {
  547. auto predicate = [=](const CStack * s){
  548. const bool positiveToAlly = owner->isPositive() && s->owner == ctx.caster->getOwner();
  549. const bool negativeToEnemy = owner->isNegative() && s->owner != ctx.caster->getOwner();
  550. const bool validTarget = s->isValidTarget(!ctx.ti.onlyAlive); //todo: this should be handled by spell class
  551. //for single target spells select stacks covering destination tile
  552. const bool rangeCovers = ctx.ti.massive || s->coversPos(ctx.destination);
  553. //handle smart targeting
  554. const bool positivenessFlag = !ctx.ti.smart || owner->isNeutral() || positiveToAlly || negativeToEnemy;
  555. return rangeCovers && positivenessFlag && validTarget;
  556. };
  557. TStacks stacks = cb->battleGetStacksIf(predicate);
  558. if(ctx.ti.massive)
  559. {
  560. //for massive spells add all targets
  561. for (auto stack : stacks)
  562. attackedCres.insert(stack);
  563. }
  564. else
  565. {
  566. //for single target spells we must select one target. Alive stack is preferred (issue #1763)
  567. for(auto stack : stacks)
  568. {
  569. if(stack->alive())
  570. {
  571. attackedCres.insert(stack);
  572. break;
  573. }
  574. }
  575. if(attackedCres.empty() && !stacks.empty())
  576. {
  577. attackedCres.insert(stacks.front());
  578. }
  579. }
  580. }
  581. else //custom range from attackedHexes
  582. {
  583. for(BattleHex hex : attackedHexes)
  584. {
  585. if(const CStack * st = cb->battleGetStackByPos(hex, ctx.ti.onlyAlive))
  586. attackedCres.insert(st);
  587. }
  588. }
  589. return attackedCres;
  590. }
  591. ESpellCastProblem::ESpellCastProblem DefaultSpellMechanics::canBeCast(const CBattleInfoCallback * cb, const ISpellCaster * caster) const
  592. {
  593. //no problems by default, this method is for spell-specific problems
  594. return ESpellCastProblem::OK;
  595. }
  596. ESpellCastProblem::ESpellCastProblem DefaultSpellMechanics::canBeCast(const CBattleInfoCallback * cb, const SpellTargetingContext & ctx) const
  597. {
  598. //no problems by default, this method is for spell-specific problems
  599. //common problems handled by CSpell
  600. return ESpellCastProblem::OK;
  601. }
  602. ESpellCastProblem::ESpellCastProblem DefaultSpellMechanics::isImmuneByStack(const ISpellCaster * caster, const CStack * obj) const
  603. {
  604. //by default use general algorithm
  605. return owner->internalIsImmune(caster, obj);
  606. }
  607. void DefaultSpellMechanics::doDispell(BattleInfo * battle, const BattleSpellCast * packet, const CSelector & selector) const
  608. {
  609. auto localSelector = [](const Bonus * bonus)
  610. {
  611. const CSpell * sourceSpell = bonus->sourceSpell();
  612. if(sourceSpell != nullptr)
  613. {
  614. //Special case: DISRUPTING_RAY is "immune" to dispell
  615. //Other even PERMANENT effects can be removed (f.e. BIND)
  616. if(sourceSpell->id == SpellID::DISRUPTING_RAY)
  617. return false;
  618. }
  619. return true;
  620. };
  621. for(auto stackID : packet->affectedCres)
  622. {
  623. CStack *s = battle->getStack(stackID);
  624. s->popBonuses(CSelector(localSelector).And(selector));
  625. }
  626. }
  627. void DefaultSpellMechanics::castMagicMirror(const SpellCastEnvironment* env, BattleSpellCastParameters& parameters) const
  628. {
  629. logGlobal->debugStream() << "Started spell cast. Spell: "<<owner->name<<"; mode: MAGIC_MIRROR";
  630. BattleHex destination = parameters.getFirstDestinationHex();
  631. SpellCastContext ctx(this, parameters);
  632. //calculating affected creatures for all spells
  633. auto creatures = owner->getAffectedStacks(parameters.cb, parameters.mode, parameters.caster, parameters.spellLvl, destination);
  634. std::copy(creatures.begin(), creatures.end(), std::back_inserter(ctx.attackedCres));
  635. logGlobal->debugStream() << "will affect: " << ctx.attackedCres.size() << " stacks";
  636. handleResistance(env, ctx.attackedCres, ctx.sc);
  637. for(auto cre : ctx.attackedCres)
  638. {
  639. ctx.sc.affectedCres.insert(cre->ID);
  640. }
  641. applyBattleEffects(env, parameters, ctx);
  642. env->sendAndApply(&ctx.sc);
  643. if(!ctx.si.stacks.empty()) //after spellcast info shows
  644. env->sendAndApply(&ctx.si);
  645. logGlobal->debugStream() << "Finished spell cast. Spell: "<<owner->name<<"; mode: MAGIC_MIRROR";
  646. }
  647. void DefaultSpellMechanics::handleResistance(const SpellCastEnvironment * env, std::vector<const CStack* >& attackedCres, BattleSpellCast& sc) const
  648. {
  649. //checking if creatures resist
  650. //resistance/reflection is applied only to negative spells
  651. if(owner->isNegative())
  652. {
  653. std::vector <const CStack*> resisted;
  654. for(auto s : attackedCres)
  655. {
  656. //magic resistance
  657. const int prob = std::min((s)->magicResistance(), 100); //probability of resistance in %
  658. if(env->getRandomGenerator().nextInt(99) < prob)
  659. {
  660. resisted.push_back(s);
  661. }
  662. }
  663. vstd::erase_if(attackedCres, [&resisted](const CStack * s)
  664. {
  665. return vstd::contains(resisted, s);
  666. });
  667. for(auto s : resisted)
  668. {
  669. BattleSpellCast::CustomEffect effect;
  670. effect.effect = 78;
  671. effect.stack = s->ID;
  672. sc.customEffects.push_back(effect);
  673. }
  674. }
  675. }
  676. bool DefaultSpellMechanics::requiresCreatureTarget() const
  677. {
  678. //most spells affects creatures somehow regardless of Target Type
  679. //for few exceptions see overrides
  680. return true;
  681. }