CDefaultSpellMechanics.cpp 23 KB

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