BattleSpellMechanics.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  1. /*
  2. * BattleSpellMechanics.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 "BattleSpellMechanics.h"
  12. #include "Problem.h"
  13. #include "CSpellHandler.h"
  14. #include "../battle/IBattleState.h"
  15. #include "../battle/CBattleInfoCallback.h"
  16. #include "../CStack.h"
  17. #include "../NetPacks.h"
  18. namespace spells
  19. {
  20. namespace SRSLPraserHelpers
  21. {
  22. static int XYToHex(int x, int y)
  23. {
  24. return x + GameConstants::BFIELD_WIDTH * y;
  25. }
  26. static int XYToHex(std::pair<int, int> xy)
  27. {
  28. return XYToHex(xy.first, xy.second);
  29. }
  30. static int hexToY(int battleFieldPosition)
  31. {
  32. return battleFieldPosition/GameConstants::BFIELD_WIDTH;
  33. }
  34. static int hexToX(int battleFieldPosition)
  35. {
  36. int pos = battleFieldPosition - hexToY(battleFieldPosition) * GameConstants::BFIELD_WIDTH;
  37. return pos;
  38. }
  39. static std::pair<int, int> hexToPair(int battleFieldPosition)
  40. {
  41. return std::make_pair(hexToX(battleFieldPosition), hexToY(battleFieldPosition));
  42. }
  43. //moves hex by one hex in given direction
  44. //0 - left top, 1 - right top, 2 - right, 3 - right bottom, 4 - left bottom, 5 - left
  45. static std::pair<int, int> gotoDir(int x, int y, int direction)
  46. {
  47. switch(direction)
  48. {
  49. case 0: //top left
  50. return std::make_pair((y%2) ? x-1 : x, y-1);
  51. case 1: //top right
  52. return std::make_pair((y%2) ? x : x+1, y-1);
  53. case 2: //right
  54. return std::make_pair(x+1, y);
  55. case 3: //right bottom
  56. return std::make_pair((y%2) ? x : x+1, y+1);
  57. case 4: //left bottom
  58. return std::make_pair((y%2) ? x-1 : x, y+1);
  59. case 5: //left
  60. return std::make_pair(x-1, y);
  61. default:
  62. throw std::runtime_error("Disaster: wrong direction in SRSLPraserHelpers::gotoDir!\n");
  63. }
  64. }
  65. static std::pair<int, int> gotoDir(std::pair<int, int> xy, int direction)
  66. {
  67. return gotoDir(xy.first, xy.second, direction);
  68. }
  69. static bool isGoodHex(std::pair<int, int> xy)
  70. {
  71. return xy.first >=0 && xy.first < GameConstants::BFIELD_WIDTH && xy.second >= 0 && xy.second < GameConstants::BFIELD_HEIGHT;
  72. }
  73. //helper function for rangeInHexes
  74. static std::set<ui16> getInRange(unsigned int center, int low, int high)
  75. {
  76. std::set<ui16> ret;
  77. if(low == 0)
  78. {
  79. ret.insert(center);
  80. }
  81. std::pair<int, int> mainPointForLayer[6]; //A, B, C, D, E, F points
  82. for(auto & elem : mainPointForLayer)
  83. elem = hexToPair(center);
  84. for(int it=1; it<=high; ++it) //it - distance to the center
  85. {
  86. for(int b=0; b<6; ++b)
  87. mainPointForLayer[b] = gotoDir(mainPointForLayer[b], b);
  88. if(it>=low)
  89. {
  90. std::pair<int, int> curHex;
  91. //adding lines (A-b, B-c, C-d, etc)
  92. for(int v=0; v<6; ++v)
  93. {
  94. curHex = mainPointForLayer[v];
  95. for(int h=0; h<it; ++h)
  96. {
  97. if(isGoodHex(curHex))
  98. ret.insert(XYToHex(curHex));
  99. curHex = gotoDir(curHex, (v+2)%6);
  100. }
  101. }
  102. } //if(it>=low)
  103. }
  104. return ret;
  105. }
  106. }
  107. BattleSpellMechanics::BattleSpellMechanics(const IBattleCast * event, std::shared_ptr<effects::Effects> effects_, std::shared_ptr<IReceptiveCheck> targetCondition_)
  108. : BaseMechanics(event),
  109. effects(effects_),
  110. targetCondition(targetCondition_)
  111. {}
  112. BattleSpellMechanics::~BattleSpellMechanics() = default;
  113. void BattleSpellMechanics::applyEffects(ServerCallback * server, const Target & targets, bool indirect, bool ignoreImmunity) const
  114. {
  115. auto callback = [&](const effects::Effect * effect, bool & stop)
  116. {
  117. if(indirect == effect->indirect)
  118. {
  119. if(ignoreImmunity)
  120. {
  121. effect->apply(server, this, targets);
  122. }
  123. else
  124. {
  125. EffectTarget filtered = effect->filterTarget(this, targets);
  126. effect->apply(server, this, filtered);
  127. }
  128. }
  129. };
  130. effects->forEachEffect(getEffectLevel(), callback);
  131. }
  132. bool BattleSpellMechanics::canBeCast(Problem & problem) const
  133. {
  134. auto genProblem = battle()->battleCanCastSpell(caster, mode);
  135. if(genProblem != ESpellCastProblem::OK)
  136. return adaptProblem(genProblem, problem);
  137. switch(mode)
  138. {
  139. case Mode::HERO:
  140. {
  141. const CGHeroInstance * castingHero = dynamic_cast<const CGHeroInstance *>(caster);//todo: unify hero|creature spell cost
  142. if(!castingHero)
  143. {
  144. logGlobal->debug("CSpell::canBeCast: invalid caster");
  145. genProblem = ESpellCastProblem::NO_HERO_TO_CAST_SPELL;
  146. }
  147. else if(!castingHero->getArt(ArtifactPosition::SPELLBOOK))
  148. genProblem = ESpellCastProblem::NO_SPELLBOOK;
  149. else if(!castingHero->canCastThisSpell(owner))
  150. genProblem = ESpellCastProblem::HERO_DOESNT_KNOW_SPELL;
  151. else if(castingHero->mana < battle()->battleGetSpellCost(owner, castingHero)) //not enough mana
  152. genProblem = ESpellCastProblem::NOT_ENOUGH_MANA;
  153. }
  154. break;
  155. }
  156. if(genProblem != ESpellCastProblem::OK)
  157. return adaptProblem(genProblem, problem);
  158. if(!owner->isCombat())
  159. return adaptProblem(ESpellCastProblem::ADVMAP_SPELL_INSTEAD_OF_BATTLE_SPELL, problem);
  160. const PlayerColor player = caster->getCasterOwner();
  161. const auto side = battle()->playerToSide(player);
  162. if(!side)
  163. return adaptProblem(ESpellCastProblem::INVALID, problem);
  164. //effect like Recanter's Cloak. Blocks also passive casting.
  165. //TODO: check creature abilities to block
  166. //TODO: check any possible caster
  167. if(battle()->battleMaxSpellLevel(side.get()) < getSpellLevel() || battle()->battleMinSpellLevel(side.get()) > getSpellLevel())
  168. return adaptProblem(ESpellCastProblem::SPELL_LEVEL_LIMIT_EXCEEDED, problem);
  169. return effects->applicable(problem, this);
  170. }
  171. bool BattleSpellMechanics::canBeCastAt(const Target & target, Problem & problem) const
  172. {
  173. if(!canBeCast(problem))
  174. return false;
  175. Target spellTarget = transformSpellTarget(target);
  176. return effects->applicable(problem, this, target, spellTarget);
  177. }
  178. std::vector<const CStack *> BattleSpellMechanics::getAffectedStacks(const Target & target) const
  179. {
  180. Target spellTarget = transformSpellTarget(target);
  181. EffectTarget all;
  182. effects->forEachEffect(getEffectLevel(), [&all, &target, &spellTarget, this](const effects::Effect * e, bool & stop)
  183. {
  184. EffectTarget one = e->transformTarget(this, target, spellTarget);
  185. vstd::concatenate(all, one);
  186. });
  187. std::set<const CStack *> stacks;
  188. for(const Destination & dest : all)
  189. {
  190. if(dest.unitValue)
  191. {
  192. //FIXME: remove and return battle::Unit
  193. stacks.insert(battle()->battleGetStackByID(dest.unitValue->unitId(), false));
  194. }
  195. }
  196. std::vector<const CStack *> res;
  197. std::copy(stacks.begin(), stacks.end(), std::back_inserter(res));
  198. return res;
  199. }
  200. void BattleSpellMechanics::cast(ServerCallback * server, const Target & target)
  201. {
  202. BattleSpellCast sc;
  203. int spellCost = 0;
  204. sc.side = casterSide;
  205. sc.spellID = getSpellId();
  206. sc.tile = target.at(0).hexValue;
  207. sc.castByHero = mode == Mode::HERO;
  208. sc.casterStack = caster->getCasterUnitId();
  209. sc.manaGained = 0;
  210. sc.activeCast = false;
  211. affectedUnits.clear();
  212. const CGHeroInstance * otherHero = nullptr;
  213. {
  214. //check it there is opponent hero
  215. const ui8 otherSide = battle()->otherSide(casterSide);
  216. if(battle()->battleHasHero(otherSide))
  217. otherHero = battle()->battleGetFightingHero(otherSide);
  218. }
  219. //calculate spell cost
  220. if(mode == Mode::HERO)
  221. {
  222. auto casterHero = dynamic_cast<const CGHeroInstance *>(caster);
  223. spellCost = battle()->battleGetSpellCost(owner, casterHero);
  224. if(nullptr != otherHero) //handle mana channel
  225. {
  226. int manaChannel = 0;
  227. for(const CStack * stack : battle()->battleGetAllStacks(true)) //TODO: shouldn't bonus system handle it somehow?
  228. {
  229. if(stack->owner == otherHero->tempOwner)
  230. {
  231. vstd::amax(manaChannel, stack->valOfBonuses(Bonus::MANA_CHANNELING));
  232. }
  233. }
  234. sc.manaGained = (manaChannel * spellCost) / 100;
  235. }
  236. sc.activeCast = true;
  237. }
  238. else if(mode == Mode::CREATURE_ACTIVE || mode == Mode::ENCHANTER)
  239. {
  240. spellCost = 1;
  241. sc.activeCast = true;
  242. }
  243. beforeCast(sc, *server->getRNG(), target);
  244. BattleLogMessage castDescription;
  245. switch (mode)
  246. {
  247. case Mode::CREATURE_ACTIVE:
  248. case Mode::ENCHANTER:
  249. case Mode::HERO:
  250. case Mode::PASSIVE:
  251. {
  252. MetaString line;
  253. caster->getCastDescription(owner, affectedUnits, line);
  254. if(!line.message.empty())
  255. castDescription.lines.push_back(line);
  256. }
  257. break;
  258. default:
  259. break;
  260. }
  261. doRemoveEffects(server, affectedUnits, std::bind(&BattleSpellMechanics::counteringSelector, this, _1));
  262. for(auto & unit : affectedUnits)
  263. sc.affectedCres.insert(unit->unitId());
  264. if(!castDescription.lines.empty())
  265. server->apply(&castDescription);
  266. server->apply(&sc);
  267. for(auto & p : effectsToApply)
  268. p.first->apply(server, this, p.second);
  269. // afterCast();
  270. if(sc.activeCast)
  271. {
  272. caster->spendMana(server, spellCost);
  273. if(sc.manaGained > 0)
  274. {
  275. assert(otherHero);
  276. otherHero->spendMana(server, -sc.manaGained);
  277. }
  278. }
  279. }
  280. void BattleSpellMechanics::beforeCast(BattleSpellCast & sc, vstd::RNG & rng, const Target & target)
  281. {
  282. affectedUnits.clear();
  283. Target spellTarget = transformSpellTarget(target);
  284. std::vector <const battle::Unit *> resisted;
  285. auto rangeGen = rng.getInt64Range(0, 99);
  286. auto filterResisted = [&, this](const battle::Unit * unit) -> bool
  287. {
  288. if(isNegativeSpell())
  289. {
  290. //magic resistance
  291. const int prob = std::min(unit->magicResistance(), 100); //probability of resistance in %
  292. if(rangeGen() < prob)
  293. return true;
  294. }
  295. return false;
  296. };
  297. auto filterUnit = [&](const battle::Unit * unit)
  298. {
  299. if(filterResisted(unit))
  300. resisted.push_back(unit);
  301. else
  302. affectedUnits.push_back(unit);
  303. };
  304. //prepare targets
  305. effectsToApply = effects->prepare(this, target, spellTarget);
  306. std::set<const battle::Unit *> unitTargets = collectTargets();
  307. //process them
  308. for(auto unit : unitTargets)
  309. filterUnit(unit);
  310. //and update targets
  311. for(auto & p : effectsToApply)
  312. {
  313. vstd::erase_if(p.second, [&](const Destination & d)
  314. {
  315. if(!d.unitValue)
  316. return false;
  317. return vstd::contains(resisted, d.unitValue);
  318. });
  319. }
  320. if(mode == Mode::MAGIC_MIRROR)
  321. {
  322. if(caster->getCasterUnitId() >= 0)
  323. {
  324. addCustomEffect(sc, caster->getCasterUnitId(), 3);
  325. }
  326. }
  327. for(auto unit : resisted)
  328. addCustomEffect(sc, unit, 78);
  329. }
  330. void BattleSpellMechanics::castEval(ServerCallback * server, const Target & target)
  331. {
  332. affectedUnits.clear();
  333. //TODO: evaluate caster updates (mana usage etc.)
  334. //TODO: evaluate random values
  335. Target spellTarget = transformSpellTarget(target);
  336. effectsToApply = effects->prepare(this, target, spellTarget);
  337. std::set<const battle::Unit *> unitTargets = collectTargets();
  338. auto selector = std::bind(&BattleSpellMechanics::counteringSelector, this, _1);
  339. std::copy(std::begin(unitTargets), std::end(unitTargets), std::back_inserter(affectedUnits));
  340. doRemoveEffects(server, affectedUnits, selector);
  341. for(auto & p : effectsToApply)
  342. p.first->apply(server, this, p.second);
  343. }
  344. void BattleSpellMechanics::addCustomEffect(BattleSpellCast & sc, const battle::Unit * target, ui32 effect)
  345. {
  346. addCustomEffect(sc, target->unitId(), effect);
  347. }
  348. void BattleSpellMechanics::addCustomEffect(BattleSpellCast & sc, ui32 targetId, ui32 effect)
  349. {
  350. CustomEffectInfo customEffect;
  351. customEffect.effect = effect;
  352. customEffect.stack = targetId;
  353. sc.customEffects.push_back(customEffect);
  354. }
  355. std::set<const battle::Unit *> BattleSpellMechanics::collectTargets() const
  356. {
  357. std::set<const battle::Unit *> result;
  358. for(const auto & p : effectsToApply)
  359. {
  360. for(const Destination & d : p.second)
  361. if(d.unitValue)
  362. result.insert(d.unitValue);
  363. }
  364. return result;
  365. }
  366. void BattleSpellMechanics::doRemoveEffects(ServerCallback * server, const std::vector<const battle::Unit *> & targets, const CSelector & selector)
  367. {
  368. SetStackEffect sse;
  369. for(auto unit : targets)
  370. {
  371. std::vector<Bonus> buffer;
  372. auto bl = unit->getBonuses(selector);
  373. for(auto item : *bl)
  374. buffer.emplace_back(*item);
  375. if(!buffer.empty())
  376. sse.toRemove.push_back(std::make_pair(unit->unitId(), buffer));
  377. }
  378. if(!sse.toRemove.empty())
  379. server->apply(&sse);
  380. }
  381. bool BattleSpellMechanics::counteringSelector(const Bonus * bonus) const
  382. {
  383. if(bonus->source != Bonus::SPELL_EFFECT)
  384. return false;
  385. for(const SpellID & id : owner->counteredSpells)
  386. {
  387. if(bonus->sid == id.toEnum())
  388. return true;
  389. }
  390. return false;
  391. }
  392. std::set<BattleHex> BattleSpellMechanics::spellRangeInHexes(BattleHex centralHex) const
  393. {
  394. using namespace SRSLPraserHelpers;
  395. std::set<BattleHex> ret;
  396. std::string rng = owner->getLevelInfo(getRangeLevel()).range + ','; //copy + artificial comma for easier handling
  397. if(rng.size() >= 2 && rng[0] != 'X') //there is at least one hex in range (+artificial comma)
  398. {
  399. std::string number1, number2;
  400. int beg, end;
  401. bool readingFirst = true;
  402. for(auto & elem : rng)
  403. {
  404. if(std::isdigit(elem) ) //reading number
  405. {
  406. if(readingFirst)
  407. number1 += elem;
  408. else
  409. number2 += elem;
  410. }
  411. else if(elem == ',') //comma
  412. {
  413. //calculating variables
  414. if(readingFirst)
  415. {
  416. beg = atoi(number1.c_str());
  417. number1 = "";
  418. }
  419. else
  420. {
  421. end = atoi(number2.c_str());
  422. number2 = "";
  423. }
  424. //obtaining new hexes
  425. std::set<ui16> curLayer;
  426. if(readingFirst)
  427. {
  428. curLayer = getInRange(centralHex, beg, beg);
  429. }
  430. else
  431. {
  432. curLayer = getInRange(centralHex, beg, end);
  433. readingFirst = true;
  434. }
  435. //adding obtained hexes
  436. for(auto & curLayer_it : curLayer)
  437. {
  438. ret.insert(curLayer_it);
  439. }
  440. }
  441. else if(elem == '-') //dash
  442. {
  443. beg = atoi(number1.c_str());
  444. number1 = "";
  445. readingFirst = false;
  446. }
  447. }
  448. }
  449. return ret;
  450. }
  451. Target BattleSpellMechanics::transformSpellTarget(const Target & aimPoint) const
  452. {
  453. Target spellTarget;
  454. if(aimPoint.size() < 1)
  455. {
  456. logGlobal->error("Aimed spell cast with no destination.");
  457. }
  458. else
  459. {
  460. const Destination & primary = aimPoint.at(0);
  461. BattleHex aimPointHex = primary.hexValue;
  462. //transform primary spell target with spell range (if it`s valid), leave anything else to effects
  463. if(aimPointHex.isValid())
  464. {
  465. auto spellRange = spellRangeInHexes(aimPointHex);
  466. for(auto & hex : spellRange)
  467. spellTarget.push_back(Destination(hex));
  468. }
  469. }
  470. if(spellTarget.empty())
  471. spellTarget.push_back(Destination(BattleHex::INVALID));
  472. return spellTarget;
  473. }
  474. std::vector<AimType> BattleSpellMechanics::getTargetTypes() const
  475. {
  476. auto ret = BaseMechanics::getTargetTypes();
  477. if(!ret.empty())
  478. {
  479. effects->forEachEffect(getEffectLevel(), [&](const effects::Effect * e, bool & stop)
  480. {
  481. e->adjustTargetTypes(ret);
  482. stop = ret.empty();
  483. });
  484. }
  485. return ret;
  486. }
  487. std::vector<Destination> BattleSpellMechanics::getPossibleDestinations(size_t index, AimType aimType, const Target & current) const
  488. {
  489. //TODO: BattleSpellMechanics::getPossibleDestinations
  490. if(index != 0)
  491. return std::vector<Destination>();
  492. std::vector<Destination> ret;
  493. switch(aimType)
  494. {
  495. case AimType::CREATURE:
  496. case AimType::LOCATION:
  497. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  498. {
  499. BattleHex dest(i);
  500. if(dest.isAvailable())
  501. {
  502. Target tmp = current;
  503. tmp.emplace_back(dest);
  504. detail::ProblemImpl ingored;
  505. if(canBeCastAt(tmp, ingored))
  506. ret.emplace_back(dest);
  507. }
  508. }
  509. break;
  510. case AimType::NO_TARGET:
  511. ret.emplace_back();
  512. break;
  513. default:
  514. break;
  515. }
  516. return ret;
  517. }
  518. bool BattleSpellMechanics::isReceptive(const battle::Unit * target) const
  519. {
  520. return targetCondition->isReceptive(this, target);
  521. }
  522. std::vector<BattleHex> BattleSpellMechanics::rangeInHexes(BattleHex centralHex, bool * outDroppedHexes) const
  523. {
  524. if(isMassive() || !centralHex.isValid())
  525. return std::vector<BattleHex>(1, BattleHex::INVALID);
  526. Target aimPoint;
  527. aimPoint.push_back(Destination(centralHex));
  528. Target spellTarget = transformSpellTarget(aimPoint);
  529. std::set<BattleHex> effectRange;
  530. effects->forEachEffect(getEffectLevel(), [&](const effects::Effect * effect, bool & stop)
  531. {
  532. if(!effect->indirect)
  533. {
  534. effect->adjustAffectedHexes(effectRange, this, spellTarget);
  535. }
  536. });
  537. std::vector<BattleHex> ret;
  538. ret.reserve(effectRange.size());
  539. std::copy(effectRange.begin(), effectRange.end(), std::back_inserter(ret));
  540. return ret;
  541. }
  542. const Spell * BattleSpellMechanics::getSpell() const
  543. {
  544. return owner;
  545. }
  546. }