CDefaultSpellMechanics.cpp 24 KB

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