BattleSpellMechanics.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  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(BattleStateProxy * battleState, vstd::RNG & rng, 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(battleState, rng, this, targets);
  122. }
  123. else
  124. {
  125. EffectTarget filtered = effect->filterTarget(this, targets);
  126. effect->apply(battleState, rng, this, filtered);
  127. }
  128. }
  129. };
  130. effects->forEachEffect(getEffectLevel(), callback);
  131. }
  132. bool BattleSpellMechanics::canBeCast(Problem & problem) const
  133. {
  134. return effects->applicable(problem, this);
  135. }
  136. bool BattleSpellMechanics::canBeCastAt(const Target & target) const
  137. {
  138. detail::ProblemImpl problem;
  139. //TODO: send problem to caller (for battle log message in BattleInterface)
  140. Target spellTarget = transformSpellTarget(target);
  141. return effects->applicable(problem, this, target, spellTarget);
  142. }
  143. std::vector<const CStack *> BattleSpellMechanics::getAffectedStacks(const Target & target) const
  144. {
  145. Target spellTarget = transformSpellTarget(target);
  146. EffectTarget all;
  147. effects->forEachEffect(getEffectLevel(), [&all, &target, &spellTarget, this](const effects::Effect * e, bool & stop)
  148. {
  149. EffectTarget one = e->transformTarget(this, target, spellTarget);
  150. vstd::concatenate(all, one);
  151. });
  152. std::set<const CStack *> stacks;
  153. for(const Destination & dest : all)
  154. {
  155. if(dest.unitValue)
  156. {
  157. //FIXME: remove and return battle::Unit
  158. stacks.insert(cb->battleGetStackByID(dest.unitValue->unitId(), false));
  159. }
  160. }
  161. std::vector<const CStack *> res;
  162. std::copy(stacks.begin(), stacks.end(), std::back_inserter(res));
  163. return res;
  164. }
  165. void BattleSpellMechanics::cast(const PacketSender * server, vstd::RNG & rng, const Target & target)
  166. {
  167. BattleSpellCast sc;
  168. int spellCost = 0;
  169. sc.side = casterSide;
  170. sc.spellID = getSpellId();
  171. sc.tile = target.at(0).hexValue;
  172. sc.castByHero = mode == Mode::HERO;
  173. sc.casterStack = (casterUnit ? casterUnit->unitId() : -1);
  174. sc.manaGained = 0;
  175. sc.activeCast = false;
  176. affectedUnits.clear();
  177. const CGHeroInstance * otherHero = nullptr;
  178. {
  179. //check it there is opponent hero
  180. const ui8 otherSide = cb->otherSide(casterSide);
  181. if(cb->battleHasHero(otherSide))
  182. otherHero = cb->battleGetFightingHero(otherSide);
  183. }
  184. //calculate spell cost
  185. if(mode == Mode::HERO)
  186. {
  187. auto casterHero = dynamic_cast<const CGHeroInstance *>(caster);
  188. spellCost = cb->battleGetSpellCost(owner, casterHero);
  189. if(nullptr != otherHero) //handle mana channel
  190. {
  191. int manaChannel = 0;
  192. for(const CStack * stack : cb->battleGetAllStacks(true)) //TODO: shouldn't bonus system handle it somehow?
  193. {
  194. if(stack->owner == otherHero->tempOwner)
  195. {
  196. vstd::amax(manaChannel, stack->valOfBonuses(Bonus::MANA_CHANNELING));
  197. }
  198. }
  199. sc.manaGained = (manaChannel * spellCost) / 100;
  200. }
  201. sc.activeCast = true;
  202. }
  203. else if(mode == Mode::CREATURE_ACTIVE || mode == Mode::ENCHANTER)
  204. {
  205. spellCost = 1;
  206. sc.activeCast = true;
  207. }
  208. beforeCast(sc, rng, target);
  209. switch (mode)
  210. {
  211. case Mode::CREATURE_ACTIVE:
  212. case Mode::ENCHANTER:
  213. case Mode::HERO:
  214. case Mode::PASSIVE:
  215. {
  216. MetaString line;
  217. caster->getCastDescription(owner, affectedUnits, line);
  218. sc.battleLog.push_back(line);
  219. }
  220. break;
  221. default:
  222. break;
  223. }
  224. doRemoveEffects(server, affectedUnits, std::bind(&BattleSpellMechanics::counteringSelector, this, _1));
  225. for(auto & unit : affectedUnits)
  226. sc.affectedCres.insert(unit->unitId());
  227. server->sendAndApply(&sc);
  228. {
  229. BattleStateProxy proxy(server);
  230. for(auto & p : effectsToApply)
  231. p.first->apply(&proxy, rng, this, p.second);
  232. }
  233. // afterCast();
  234. if(sc.activeCast)
  235. {
  236. caster->spendMana(server, spellCost);
  237. if(sc.manaGained > 0)
  238. {
  239. assert(otherHero);
  240. otherHero->spendMana(server, -sc.manaGained);
  241. }
  242. }
  243. }
  244. void BattleSpellMechanics::beforeCast(BattleSpellCast & sc, vstd::RNG & rng, const Target & target)
  245. {
  246. affectedUnits.clear();
  247. Target spellTarget = transformSpellTarget(target);
  248. std::vector <const battle::Unit *> resisted;
  249. auto rangeGen = rng.getInt64Range(0, 99);
  250. auto filterResisted = [&, this](const battle::Unit * unit) -> bool
  251. {
  252. if(isNegativeSpell())
  253. {
  254. //magic resistance
  255. const int prob = std::min(unit->magicResistance(), 100); //probability of resistance in %
  256. if(rangeGen() < prob)
  257. return true;
  258. }
  259. return false;
  260. };
  261. auto filterUnit = [&](const battle::Unit * unit)
  262. {
  263. if(filterResisted(unit))
  264. resisted.push_back(unit);
  265. else
  266. affectedUnits.push_back(unit);
  267. };
  268. //prepare targets
  269. effectsToApply = effects->prepare(this, target, spellTarget);
  270. std::set<const battle::Unit *> unitTargets = collectTargets();
  271. //process them
  272. for(auto unit : unitTargets)
  273. filterUnit(unit);
  274. //and update targets
  275. for(auto & p : effectsToApply)
  276. {
  277. vstd::erase_if(p.second, [&](const Destination & d)
  278. {
  279. if(!d.unitValue)
  280. return false;
  281. return vstd::contains(resisted, d.unitValue);
  282. });
  283. }
  284. if(mode == Mode::MAGIC_MIRROR)
  285. {
  286. if(casterUnit)
  287. {
  288. addCustomEffect(sc, casterUnit, 3);
  289. }
  290. }
  291. for(auto unit : resisted)
  292. addCustomEffect(sc, unit, 78);
  293. }
  294. void BattleSpellMechanics::cast(IBattleState * battleState, vstd::RNG & rng, const Target & target)
  295. {
  296. //TODO: evaluate caster updates (mana usage etc.)
  297. //TODO: evaluate random values
  298. Target spellTarget = transformSpellTarget(target);
  299. effectsToApply = effects->prepare(this, target, spellTarget);
  300. std::set<const battle::Unit *> stacks = collectTargets();
  301. for(const battle::Unit * one : stacks)
  302. {
  303. auto selector = std::bind(&BattleSpellMechanics::counteringSelector, this, _1);
  304. std::vector<Bonus> buffer;
  305. auto bl = one->getBonuses(selector);
  306. for(auto item : *bl)
  307. buffer.emplace_back(*item);
  308. if(!buffer.empty())
  309. battleState->removeUnitBonus(one->unitId(), buffer);
  310. }
  311. {
  312. BattleStateProxy proxy(battleState);
  313. for(auto & p : effectsToApply)
  314. p.first->apply(&proxy, rng, this, p.second);
  315. }
  316. }
  317. void BattleSpellMechanics::addCustomEffect(BattleSpellCast & sc, const battle::Unit * target, ui32 effect)
  318. {
  319. CustomEffectInfo customEffect;
  320. customEffect.effect = effect;
  321. customEffect.stack = target->unitId();
  322. sc.customEffects.push_back(customEffect);
  323. }
  324. std::set<const battle::Unit *> BattleSpellMechanics::collectTargets() const
  325. {
  326. std::set<const battle::Unit *> result;
  327. for(const auto & p : effectsToApply)
  328. {
  329. for(const Destination & d : p.second)
  330. if(d.unitValue)
  331. result.insert(d.unitValue);
  332. }
  333. return result;
  334. }
  335. void BattleSpellMechanics::doRemoveEffects(const PacketSender * server, const std::vector<const battle::Unit *> & targets, const CSelector & selector)
  336. {
  337. SetStackEffect sse;
  338. for(auto unit : targets)
  339. {
  340. std::vector<Bonus> buffer;
  341. auto bl = unit->getBonuses(selector);
  342. for(auto item : *bl)
  343. buffer.emplace_back(*item);
  344. if(!buffer.empty())
  345. sse.toRemove.push_back(std::make_pair(unit->unitId(), buffer));
  346. }
  347. if(!sse.toRemove.empty())
  348. server->sendAndApply(&sse);
  349. }
  350. bool BattleSpellMechanics::counteringSelector(const Bonus * bonus) const
  351. {
  352. if(bonus->source != Bonus::SPELL_EFFECT)
  353. return false;
  354. for(const SpellID & id : owner->counteredSpells)
  355. {
  356. if(bonus->sid == id.toEnum())
  357. return true;
  358. }
  359. return false;
  360. }
  361. std::set<BattleHex> BattleSpellMechanics::spellRangeInHexes(BattleHex centralHex) const
  362. {
  363. using namespace SRSLPraserHelpers;
  364. std::set<BattleHex> ret;
  365. std::string rng = owner->getLevelInfo(getRangeLevel()).range + ','; //copy + artificial comma for easier handling
  366. if(rng.size() >= 2 && rng[0] != 'X') //there is at least one hex in range (+artificial comma)
  367. {
  368. std::string number1, number2;
  369. int beg, end;
  370. bool readingFirst = true;
  371. for(auto & elem : rng)
  372. {
  373. if(std::isdigit(elem) ) //reading number
  374. {
  375. if(readingFirst)
  376. number1 += elem;
  377. else
  378. number2 += elem;
  379. }
  380. else if(elem == ',') //comma
  381. {
  382. //calculating variables
  383. if(readingFirst)
  384. {
  385. beg = atoi(number1.c_str());
  386. number1 = "";
  387. }
  388. else
  389. {
  390. end = atoi(number2.c_str());
  391. number2 = "";
  392. }
  393. //obtaining new hexes
  394. std::set<ui16> curLayer;
  395. if(readingFirst)
  396. {
  397. curLayer = getInRange(centralHex, beg, beg);
  398. }
  399. else
  400. {
  401. curLayer = getInRange(centralHex, beg, end);
  402. readingFirst = true;
  403. }
  404. //adding obtained hexes
  405. for(auto & curLayer_it : curLayer)
  406. {
  407. ret.insert(curLayer_it);
  408. }
  409. }
  410. else if(elem == '-') //dash
  411. {
  412. beg = atoi(number1.c_str());
  413. number1 = "";
  414. readingFirst = false;
  415. }
  416. }
  417. }
  418. return ret;
  419. }
  420. Target BattleSpellMechanics::transformSpellTarget(const Target & aimPoint) const
  421. {
  422. Target spellTarget;
  423. if(aimPoint.size() < 1)
  424. {
  425. logGlobal->error("Aimed spell cast with no destination.");
  426. }
  427. else
  428. {
  429. const Destination & primary = aimPoint.at(0);
  430. BattleHex aimPoint = primary.hexValue;
  431. //transform primary spell target with spell range (if it`s valid), leave anything else to effects
  432. if(aimPoint.isValid())
  433. {
  434. auto spellRange = spellRangeInHexes(aimPoint);
  435. for(auto & hex : spellRange)
  436. spellTarget.push_back(Destination(hex));
  437. }
  438. }
  439. if(spellTarget.empty())
  440. spellTarget.push_back(Destination(BattleHex::INVALID));
  441. return std::move(spellTarget);
  442. }
  443. std::vector<AimType> BattleSpellMechanics::getTargetTypes() const
  444. {
  445. auto ret = BaseMechanics::getTargetTypes();
  446. if(!ret.empty())
  447. {
  448. effects->forEachEffect(getEffectLevel(), [&](const effects::Effect * e, bool & stop)
  449. {
  450. e->adjustTargetTypes(ret);
  451. stop = ret.empty();
  452. });
  453. }
  454. return ret;
  455. }
  456. std::vector<Destination> BattleSpellMechanics::getPossibleDestinations(size_t index, AimType aimType, const Target & current) const
  457. {
  458. //TODO: BattleSpellMechanics::getPossibleDestinations
  459. if(index != 0)
  460. return std::vector<Destination>();
  461. std::vector<Destination> ret;
  462. switch(aimType)
  463. {
  464. case AimType::CREATURE:
  465. case AimType::LOCATION:
  466. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  467. {
  468. BattleHex dest(i);
  469. if(dest.isAvailable())
  470. {
  471. Target tmp = current;
  472. tmp.emplace_back(dest);
  473. if(canBeCastAt(tmp))
  474. ret.emplace_back(dest);
  475. }
  476. }
  477. break;
  478. case AimType::NO_TARGET:
  479. ret.emplace_back();
  480. break;
  481. default:
  482. break;
  483. }
  484. return ret;
  485. }
  486. bool BattleSpellMechanics::isReceptive(const battle::Unit * target) const
  487. {
  488. return targetCondition->isReceptive(this, target);
  489. }
  490. std::vector<BattleHex> BattleSpellMechanics::rangeInHexes(BattleHex centralHex, bool * outDroppedHexes) const
  491. {
  492. if(isMassive() || !centralHex.isValid())
  493. return std::vector<BattleHex>(1, BattleHex::INVALID);
  494. Target aimPoint;
  495. aimPoint.push_back(Destination(centralHex));
  496. Target spellTarget = transformSpellTarget(aimPoint);
  497. std::set<BattleHex> effectRange;
  498. effects->forEachEffect(getEffectLevel(), [&](const effects::Effect * effect, bool & stop)
  499. {
  500. if(!effect->indirect)
  501. {
  502. effect->adjustAffectedHexes(effectRange, this, spellTarget);
  503. }
  504. });
  505. std::vector<BattleHex> ret;
  506. ret.reserve(effectRange.size());
  507. std::copy(effectRange.begin(), effectRange.end(), std::back_inserter(ret));
  508. return ret;
  509. }
  510. }