CDefaultSpellMechanics.cpp 23 KB

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