CDefaultSpellMechanics.cpp 23 KB

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