BattleFlowProcessor.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  1. /*
  2. * BattleFlowProcessor.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 "BattleFlowProcessor.h"
  12. #include "BattleProcessor.h"
  13. #include "../CGameHandler.h"
  14. #include "../../lib/CStack.h"
  15. #include "../../lib/GameSettings.h"
  16. #include "../../lib/battle/CBattleInfoCallback.h"
  17. #include "../../lib/battle/IBattleState.h"
  18. #include "../../lib/gameState/CGameState.h"
  19. #include "../../lib/mapObjects/CGTownInstance.h"
  20. #include "../../lib/NetPacks.h"
  21. #include "../../lib/spells/BonusCaster.h"
  22. #include "../../lib/spells/ISpellMechanics.h"
  23. #include "../../lib/spells/ObstacleCasterProxy.h"
  24. BattleFlowProcessor::BattleFlowProcessor(BattleProcessor * owner)
  25. : owner(owner)
  26. , gameHandler(nullptr)
  27. {
  28. }
  29. void BattleFlowProcessor::setGameHandler(CGameHandler * newGameHandler)
  30. {
  31. gameHandler = newGameHandler;
  32. }
  33. void BattleFlowProcessor::summonGuardiansHelper(const CBattleInfoCallback & battle, std::vector<BattleHex> & output, const BattleHex & targetPosition, ui8 side, bool targetIsTwoHex) //return hexes for summoning two hex monsters in output, target = unit to guard
  34. {
  35. int x = targetPosition.getX();
  36. int y = targetPosition.getY();
  37. const bool targetIsAttacker = side == BattleSide::ATTACKER;
  38. if (targetIsAttacker) //handle front guardians, TODO: should we handle situation when units start battle near opposite side of the battlefield? Cannot happen in normal H3...
  39. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false).cloneInDirection(BattleHex::EDir::RIGHT, false), output);
  40. else
  41. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false).cloneInDirection(BattleHex::EDir::LEFT, false), output);
  42. //guardian spawn locations for four default position cases for attacker and defender, non-default starting location for att and def is handled in first two if's
  43. if (targetIsAttacker && ((y % 2 == 0) || (x > 1)))
  44. {
  45. if (targetIsTwoHex && (y % 2 == 1) && (x == 2)) //handle exceptional case
  46. {
  47. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::TOP_RIGHT, false), output);
  48. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::BOTTOM_RIGHT, false), output);
  49. }
  50. else
  51. { //add back-side guardians for two-hex target, side guardians for one-hex
  52. BattleHex::checkAndPush(targetPosition.cloneInDirection(targetIsTwoHex ? BattleHex::EDir::TOP_LEFT : BattleHex::EDir::TOP_RIGHT, false), output);
  53. BattleHex::checkAndPush(targetPosition.cloneInDirection(targetIsTwoHex ? BattleHex::EDir::BOTTOM_LEFT : BattleHex::EDir::BOTTOM_RIGHT, false), output);
  54. if (!targetIsTwoHex && x > 2) //back guard for one-hex
  55. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false), output);
  56. else if (targetIsTwoHex)//front-side guardians for two-hex target
  57. {
  58. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false).cloneInDirection(BattleHex::EDir::TOP_RIGHT, false), output);
  59. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false).cloneInDirection(BattleHex::EDir::BOTTOM_RIGHT, false), output);
  60. if (x > 3) //back guard for two-hex
  61. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false).cloneInDirection(BattleHex::EDir::LEFT, false), output);
  62. }
  63. }
  64. }
  65. else if (!targetIsAttacker && ((y % 2 == 1) || (x < GameConstants::BFIELD_WIDTH - 2)))
  66. {
  67. if (targetIsTwoHex && (y % 2 == 0) && (x == GameConstants::BFIELD_WIDTH - 3)) //handle exceptional case... equivalent for above for defender side
  68. {
  69. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::TOP_LEFT, false), output);
  70. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::BOTTOM_LEFT, false), output);
  71. }
  72. else
  73. {
  74. BattleHex::checkAndPush(targetPosition.cloneInDirection(targetIsTwoHex ? BattleHex::EDir::TOP_RIGHT : BattleHex::EDir::TOP_LEFT, false), output);
  75. BattleHex::checkAndPush(targetPosition.cloneInDirection(targetIsTwoHex ? BattleHex::EDir::BOTTOM_RIGHT : BattleHex::EDir::BOTTOM_LEFT, false), output);
  76. if (!targetIsTwoHex && x < GameConstants::BFIELD_WIDTH - 3)
  77. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false), output);
  78. else if (targetIsTwoHex)
  79. {
  80. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false).cloneInDirection(BattleHex::EDir::TOP_LEFT, false), output);
  81. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false).cloneInDirection(BattleHex::EDir::BOTTOM_LEFT, false), output);
  82. if (x < GameConstants::BFIELD_WIDTH - 4)
  83. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false).cloneInDirection(BattleHex::EDir::RIGHT, false), output);
  84. }
  85. }
  86. }
  87. else if (!targetIsAttacker && y % 2 == 0)
  88. {
  89. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false).cloneInDirection(BattleHex::EDir::TOP_LEFT, false), output);
  90. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false).cloneInDirection(BattleHex::EDir::BOTTOM_LEFT, false), output);
  91. }
  92. else if (targetIsAttacker && y % 2 == 1)
  93. {
  94. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false).cloneInDirection(BattleHex::EDir::TOP_RIGHT, false), output);
  95. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false).cloneInDirection(BattleHex::EDir::BOTTOM_RIGHT, false), output);
  96. }
  97. }
  98. void BattleFlowProcessor::tryPlaceMoats(const CBattleInfoCallback & battle)
  99. {
  100. const auto * town = battle.battleGetDefendedTown();
  101. //Moat should be initialized here, because only here we can use spellcasting
  102. if (town && town->fortLevel() >= CGTownInstance::CITADEL)
  103. {
  104. const auto * h = battle.battleGetFightingHero(BattleSide::DEFENDER);
  105. const auto * actualCaster = h ? static_cast<const spells::Caster*>(h) : nullptr;
  106. auto moatCaster = spells::SilentCaster(battle.sideToPlayer(BattleSide::DEFENDER), actualCaster);
  107. auto cast = spells::BattleCast(&battle, &moatCaster, spells::Mode::PASSIVE, town->town->moatAbility.toSpell());
  108. auto target = spells::Target();
  109. cast.cast(gameHandler->spellEnv, target);
  110. }
  111. }
  112. void BattleFlowProcessor::onBattleStarted(const CBattleInfoCallback & battle)
  113. {
  114. tryPlaceMoats(battle);
  115. gameHandler->turnTimerHandler.onBattleStart(battle.getBattle()->getBattleID());
  116. if (battle.battleGetTacticDist() == 0)
  117. onTacticsEnded(battle);
  118. }
  119. void BattleFlowProcessor::trySummonGuardians(const CBattleInfoCallback & battle, const CStack * stack)
  120. {
  121. if (!stack->hasBonusOfType(BonusType::SUMMON_GUARDIANS))
  122. return;
  123. std::shared_ptr<const Bonus> summonInfo = stack->getBonus(Selector::type()(BonusType::SUMMON_GUARDIANS));
  124. auto accessibility = battle.getAccesibility();
  125. CreatureID creatureData = CreatureID(summonInfo->subtype);
  126. std::vector<BattleHex> targetHexes;
  127. const bool targetIsBig = stack->unitType()->isDoubleWide(); //target = creature to guard
  128. const bool guardianIsBig = creatureData.toCreature()->isDoubleWide();
  129. /*Chosen idea for two hex units was to cover all possible surrounding hexes of target unit with as small number of stacks as possible.
  130. For one-hex targets there are four guardians - front, back and one per side (up + down).
  131. Two-hex targets are wider and the difference is there are two guardians per side to cover 3 hexes + extra hex in the front
  132. Additionally, there are special cases for starting positions etc., where guardians would be outside of battlefield if spawned normally*/
  133. if (!guardianIsBig)
  134. targetHexes = stack->getSurroundingHexes();
  135. else
  136. summonGuardiansHelper(battle, targetHexes, stack->getPosition(), stack->unitSide(), targetIsBig);
  137. for(auto hex : targetHexes)
  138. {
  139. if(accessibility.accessible(hex, guardianIsBig, stack->unitSide())) //without this multiple creatures can occupy one hex
  140. {
  141. battle::UnitInfo info;
  142. info.id = battle.battleNextUnitId();
  143. info.count = std::max(1, (int)(stack->getCount() * 0.01 * summonInfo->val));
  144. info.type = creatureData;
  145. info.side = stack->unitSide();
  146. info.position = hex;
  147. info.summoned = true;
  148. BattleUnitsChanged pack;
  149. pack.battleID = battle.getBattle()->getBattleID();
  150. pack.changedStacks.emplace_back(info.id, UnitChanges::EOperation::ADD);
  151. info.save(pack.changedStacks.back().data);
  152. gameHandler->sendAndApply(&pack);
  153. }
  154. }
  155. // send empty event to client
  156. // temporary(?) workaround to force animations to trigger
  157. StacksInjured fakeEvent;
  158. gameHandler->sendAndApply(&fakeEvent);
  159. }
  160. void BattleFlowProcessor::castOpeningSpells(const CBattleInfoCallback & battle)
  161. {
  162. for (int i = 0; i < 2; ++i)
  163. {
  164. auto h = battle.battleGetFightingHero(i);
  165. if (!h)
  166. continue;
  167. TConstBonusListPtr bl = h->getBonuses(Selector::type()(BonusType::OPENING_BATTLE_SPELL));
  168. for (auto b : *bl)
  169. {
  170. spells::BonusCaster caster(h, b);
  171. const CSpell * spell = SpellID(b->subtype).toSpell();
  172. spells::BattleCast parameters(&battle, &caster, spells::Mode::PASSIVE, spell);
  173. parameters.setSpellLevel(3);
  174. parameters.setEffectDuration(b->val);
  175. parameters.massive = true;
  176. parameters.castIfPossible(gameHandler->spellEnv, spells::Target());
  177. }
  178. }
  179. }
  180. void BattleFlowProcessor::onTacticsEnded(const CBattleInfoCallback & battle)
  181. {
  182. //initial stacks appearance triggers, e.g. built-in bonus spells
  183. auto initialStacks = battle.battleGetAllStacks(true);
  184. for (const CStack * stack : initialStacks)
  185. {
  186. trySummonGuardians(battle, stack);
  187. stackEnchantedTrigger(battle, stack);
  188. }
  189. castOpeningSpells(battle);
  190. // it is possible that due to opening spells one side was eliminated -> check for end of battle
  191. if (owner->checkBattleStateChanges(battle))
  192. return;
  193. startNextRound(battle, true);
  194. activateNextStack(battle);
  195. }
  196. void BattleFlowProcessor::startNextRound(const CBattleInfoCallback & battle, bool isFirstRound)
  197. {
  198. BattleNextRound bnr;
  199. bnr.battleID = battle.getBattle()->getBattleID();
  200. logGlobal->debug("Next round starts");
  201. gameHandler->sendAndApply(&bnr);
  202. // operate on copy - removing obstacles will invalidate iterator on 'battle' container
  203. auto obstacles = battle.battleGetAllObstacles();
  204. for (auto &obstPtr : obstacles)
  205. {
  206. if (const SpellCreatedObstacle *sco = dynamic_cast<const SpellCreatedObstacle *>(obstPtr.get()))
  207. if (sco->turnsRemaining == 0)
  208. removeObstacle(battle, *obstPtr);
  209. }
  210. for(auto stack : battle.battleGetAllStacks(true))
  211. {
  212. if(stack->alive() && !isFirstRound)
  213. stackEnchantedTrigger(battle, stack);
  214. }
  215. }
  216. const CStack * BattleFlowProcessor::getNextStack(const CBattleInfoCallback & battle)
  217. {
  218. std::vector<battle::Units> q;
  219. battle.battleGetTurnOrder(q, 1, 0, -1); //todo: get rid of "turn -1"
  220. if(q.empty())
  221. return nullptr;
  222. if(q.front().empty())
  223. return nullptr;
  224. auto next = q.front().front();
  225. const auto stack = dynamic_cast<const CStack *>(next);
  226. // regeneration takes place before everything else but only during first turn attempt in each round
  227. // also works under blind and similar effects
  228. if(stack && stack->alive() && !stack->waiting)
  229. {
  230. BattleTriggerEffect bte;
  231. bte.battleID = battle.getBattle()->getBattleID();
  232. bte.stackID = stack->unitId();
  233. bte.effect = vstd::to_underlying(BonusType::HP_REGENERATION);
  234. const int32_t lostHealth = stack->getMaxHealth() - stack->getFirstHPleft();
  235. if(stack->hasBonusOfType(BonusType::HP_REGENERATION))
  236. bte.val = std::min(lostHealth, stack->valOfBonuses(BonusType::HP_REGENERATION));
  237. if(bte.val) // anything to heal
  238. gameHandler->sendAndApply(&bte);
  239. }
  240. if(!next->willMove())
  241. return nullptr;
  242. return stack;
  243. }
  244. void BattleFlowProcessor::activateNextStack(const CBattleInfoCallback & battle)
  245. {
  246. // Find next stack that requires manual control
  247. for (;;)
  248. {
  249. // battle has ended
  250. if (owner->checkBattleStateChanges(battle))
  251. return;
  252. const CStack * next = getNextStack(battle);
  253. if (!next)
  254. {
  255. // No stacks to move - start next round
  256. startNextRound(battle, false);
  257. next = getNextStack(battle);
  258. if (!next)
  259. throw std::runtime_error("Failed to find valid stack to act!");
  260. }
  261. BattleUnitsChanged removeGhosts;
  262. removeGhosts.battleID = battle.getBattle()->getBattleID();
  263. auto pendingGhosts = battle.battleGetStacksIf([](const CStack * stack){
  264. return stack->ghostPending;
  265. });
  266. for(auto stack : pendingGhosts)
  267. removeGhosts.changedStacks.emplace_back(stack->unitId(), UnitChanges::EOperation::REMOVE);
  268. if(!removeGhosts.changedStacks.empty())
  269. gameHandler->sendAndApply(&removeGhosts);
  270. gameHandler->turnTimerHandler.onBattleNextStack(battle.getBattle()->getBattleID(), *next);
  271. if (!tryMakeAutomaticAction(battle, next))
  272. {
  273. setActiveStack(battle, next);
  274. break;
  275. }
  276. }
  277. }
  278. bool BattleFlowProcessor::tryMakeAutomaticAction(const CBattleInfoCallback & battle, const CStack * next)
  279. {
  280. // check for bad morale => freeze
  281. int nextStackMorale = next->moraleVal();
  282. if(!next->hadMorale && !next->waited() && nextStackMorale < 0)
  283. {
  284. auto diceSize = VLC->settings()->getVector(EGameSettings::COMBAT_BAD_MORALE_DICE);
  285. size_t diceIndex = std::min<size_t>(diceSize.size()-1, -nextStackMorale);
  286. if(diceSize.size() > 0 && gameHandler->getRandomGenerator().nextInt(1, diceSize[diceIndex]) == 1)
  287. {
  288. //unit loses its turn - empty freeze action
  289. BattleAction ba;
  290. ba.actionType = EActionType::BAD_MORALE;
  291. ba.side = next->unitSide();
  292. ba.stackNumber = next->unitId();
  293. makeAutomaticAction(battle, next, ba);
  294. return true;
  295. }
  296. }
  297. if (next->hasBonusOfType(BonusType::ATTACKS_NEAREST_CREATURE)) //while in berserk
  298. {
  299. logGlobal->trace("Handle Berserk effect");
  300. std::pair<const battle::Unit *, BattleHex> attackInfo = battle.getNearestStack(next);
  301. if (attackInfo.first != nullptr)
  302. {
  303. BattleAction attack;
  304. attack.actionType = EActionType::WALK_AND_ATTACK;
  305. attack.side = next->unitSide();
  306. attack.stackNumber = next->unitId();
  307. attack.aimToHex(attackInfo.second);
  308. attack.aimToUnit(attackInfo.first);
  309. makeAutomaticAction(battle, next, attack);
  310. logGlobal->trace("Attacked nearest target %s", attackInfo.first->getDescription());
  311. }
  312. else
  313. {
  314. makeStackDoNothing(battle, next);
  315. logGlobal->trace("No target found");
  316. }
  317. return true;
  318. }
  319. const CGHeroInstance * curOwner = battle.battleGetOwnerHero(next);
  320. const int stackCreatureId = next->unitType()->getId();
  321. if ((stackCreatureId == CreatureID::ARROW_TOWERS || stackCreatureId == CreatureID::BALLISTA)
  322. && (!curOwner || gameHandler->getRandomGenerator().nextInt(99) >= curOwner->valOfBonuses(BonusType::MANUAL_CONTROL, stackCreatureId)))
  323. {
  324. BattleAction attack;
  325. attack.actionType = EActionType::SHOOT;
  326. attack.side = next->unitSide();
  327. attack.stackNumber = next->unitId();
  328. //TODO: select target by priority
  329. const battle::Unit * target = nullptr;
  330. for(auto & elem : battle.battleGetAllStacks(true))
  331. {
  332. if(elem->unitType()->getId() != CreatureID::CATAPULT
  333. && elem->unitOwner() != next->unitOwner()
  334. && elem->isValidTarget()
  335. && battle.battleCanShoot(next, elem->getPosition()))
  336. {
  337. target = elem;
  338. break;
  339. }
  340. }
  341. if(target == nullptr)
  342. {
  343. makeStackDoNothing(battle, next);
  344. }
  345. else
  346. {
  347. attack.aimToUnit(target);
  348. makeAutomaticAction(battle, next, attack);
  349. }
  350. return true;
  351. }
  352. if (next->unitType()->getId() == CreatureID::CATAPULT)
  353. {
  354. const auto & attackableBattleHexes = battle.getAttackableBattleHexes();
  355. if (attackableBattleHexes.empty())
  356. {
  357. makeStackDoNothing(battle, next);
  358. return true;
  359. }
  360. if (!curOwner || gameHandler->getRandomGenerator().nextInt(99) >= curOwner->valOfBonuses(BonusType::MANUAL_CONTROL, CreatureID::CATAPULT))
  361. {
  362. BattleAction attack;
  363. attack.actionType = EActionType::CATAPULT;
  364. attack.side = next->unitSide();
  365. attack.stackNumber = next->unitId();
  366. makeAutomaticAction(battle, next, attack);
  367. return true;
  368. }
  369. }
  370. if (next->unitType()->getId() == CreatureID::FIRST_AID_TENT)
  371. {
  372. TStacks possibleStacks = battle.battleGetStacksIf([=](const CStack * s)
  373. {
  374. return s->unitOwner() == next->unitOwner() && s->canBeHealed();
  375. });
  376. if (possibleStacks.empty())
  377. {
  378. makeStackDoNothing(battle, next);
  379. return true;
  380. }
  381. if (!curOwner || gameHandler->getRandomGenerator().nextInt(99) >= curOwner->valOfBonuses(BonusType::MANUAL_CONTROL, CreatureID::FIRST_AID_TENT))
  382. {
  383. RandomGeneratorUtil::randomShuffle(possibleStacks, gameHandler->getRandomGenerator());
  384. const CStack * toBeHealed = possibleStacks.front();
  385. BattleAction heal;
  386. heal.actionType = EActionType::STACK_HEAL;
  387. heal.aimToUnit(toBeHealed);
  388. heal.side = next->unitSide();
  389. heal.stackNumber = next->unitId();
  390. makeAutomaticAction(battle, next, heal);
  391. return true;
  392. }
  393. }
  394. stackTurnTrigger(battle, next); //various effects
  395. if(next->fear)
  396. {
  397. makeStackDoNothing(battle, next); //end immediately if stack was affected by fear
  398. return true;
  399. }
  400. return false;
  401. }
  402. bool BattleFlowProcessor::rollGoodMorale(const CBattleInfoCallback & battle, const CStack * next)
  403. {
  404. //check for good morale
  405. auto nextStackMorale = next->moraleVal();
  406. if( !next->hadMorale
  407. && !next->defending
  408. && !next->waited()
  409. && !next->fear
  410. && next->alive()
  411. && next->canMove()
  412. && nextStackMorale > 0)
  413. {
  414. auto diceSize = VLC->settings()->getVector(EGameSettings::COMBAT_GOOD_MORALE_DICE);
  415. size_t diceIndex = std::min<size_t>(diceSize.size()-1, nextStackMorale);
  416. if(diceSize.size() > 0 && gameHandler->getRandomGenerator().nextInt(1, diceSize[diceIndex]) == 1)
  417. {
  418. BattleTriggerEffect bte;
  419. bte.battleID = battle.getBattle()->getBattleID();
  420. bte.stackID = next->unitId();
  421. bte.effect = vstd::to_underlying(BonusType::MORALE);
  422. bte.val = 1;
  423. bte.additionalInfo = 0;
  424. gameHandler->sendAndApply(&bte); //play animation
  425. return true;
  426. }
  427. }
  428. return false;
  429. }
  430. void BattleFlowProcessor::onActionMade(const CBattleInfoCallback & battle, const BattleAction &ba)
  431. {
  432. const auto * actedStack = battle.battleGetStackByID(ba.stackNumber, false);
  433. const auto * activeStack = battle.battleActiveUnit();
  434. if (ba.actionType == EActionType::END_TACTIC_PHASE)
  435. {
  436. onTacticsEnded(battle);
  437. return;
  438. }
  439. //we're after action, all results applied
  440. // check whether action has ended the battle
  441. if(owner->checkBattleStateChanges(battle))
  442. return;
  443. // tactics - next stack will be selected by player
  444. if(battle.battleGetTacticDist() != 0)
  445. return;
  446. if (ba.isUnitAction())
  447. {
  448. assert(activeStack != nullptr);
  449. assert(actedStack != nullptr);
  450. if (rollGoodMorale(battle, actedStack))
  451. {
  452. // Good morale - same stack makes 2nd turn
  453. setActiveStack(battle, actedStack);
  454. return;
  455. }
  456. }
  457. else
  458. {
  459. if (activeStack && activeStack->alive())
  460. {
  461. // this is action made by hero AND unit is alive (e.g. not killed by casted spell)
  462. // keep current active stack for next action
  463. setActiveStack(battle, activeStack);
  464. return;
  465. }
  466. }
  467. activateNextStack(battle);
  468. }
  469. void BattleFlowProcessor::makeStackDoNothing(const CBattleInfoCallback & battle, const CStack * next)
  470. {
  471. BattleAction doNothing;
  472. doNothing.actionType = EActionType::NO_ACTION;
  473. doNothing.side = next->unitSide();
  474. doNothing.stackNumber = next->unitId();
  475. makeAutomaticAction(battle, next, doNothing);
  476. }
  477. bool BattleFlowProcessor::makeAutomaticAction(const CBattleInfoCallback & battle, const CStack *stack, BattleAction &ba)
  478. {
  479. BattleSetActiveStack bsa;
  480. bsa.battleID = battle.getBattle()->getBattleID();
  481. bsa.stack = stack->unitId();
  482. bsa.askPlayerInterface = false;
  483. gameHandler->sendAndApply(&bsa);
  484. bool ret = owner->makeAutomaticBattleAction(battle, ba);
  485. return ret;
  486. }
  487. void BattleFlowProcessor::stackEnchantedTrigger(const CBattleInfoCallback & battle, const CStack * st)
  488. {
  489. auto bl = *(st->getBonuses(Selector::type()(BonusType::ENCHANTED)));
  490. for(auto b : bl)
  491. {
  492. const CSpell * sp = SpellID(b->subtype).toSpell();
  493. if(!sp)
  494. continue;
  495. const int32_t val = bl.valOfBonuses(Selector::typeSubtype(b->type, b->subtype));
  496. const int32_t level = ((val > 3) ? (val - 3) : val);
  497. spells::BattleCast battleCast(&battle, st, spells::Mode::PASSIVE, sp);
  498. //this makes effect accumulate for at most 50 turns by default, but effect may be permanent and last till the end of battle
  499. battleCast.setEffectDuration(50);
  500. battleCast.setSpellLevel(level);
  501. spells::Target target;
  502. if(val > 3)
  503. {
  504. for(auto s : battle.battleGetAllStacks())
  505. if(battle.battleMatchOwner(st, s, true) && s->isValidTarget()) //all allied
  506. target.emplace_back(s);
  507. }
  508. else
  509. {
  510. target.emplace_back(st);
  511. }
  512. battleCast.applyEffects(gameHandler->spellEnv, target, false, true);
  513. }
  514. }
  515. void BattleFlowProcessor::removeObstacle(const CBattleInfoCallback & battle, const CObstacleInstance & obstacle)
  516. {
  517. BattleObstaclesChanged obsRem;
  518. obsRem.battleID = battle.getBattle()->getBattleID();
  519. obsRem.changes.emplace_back(obstacle.uniqueID, ObstacleChanges::EOperation::REMOVE);
  520. gameHandler->sendAndApply(&obsRem);
  521. }
  522. void BattleFlowProcessor::stackTurnTrigger(const CBattleInfoCallback & battle, const CStack *st)
  523. {
  524. BattleTriggerEffect bte;
  525. bte.battleID = battle.getBattle()->getBattleID();
  526. bte.stackID = st->unitId();
  527. bte.effect = -1;
  528. bte.val = 0;
  529. bte.additionalInfo = 0;
  530. if (st->alive())
  531. {
  532. //unbind
  533. if (st->hasBonus(Selector::type()(BonusType::BIND_EFFECT)))
  534. {
  535. bool unbind = true;
  536. BonusList bl = *(st->getBonuses(Selector::type()(BonusType::BIND_EFFECT)));
  537. auto adjacent = battle.battleAdjacentUnits(st);
  538. for (auto b : bl)
  539. {
  540. if(b->additionalInfo != CAddInfo::NONE)
  541. {
  542. const CStack * stack = battle.battleGetStackByID(b->additionalInfo[0]); //binding stack must be alive and adjacent
  543. if(stack)
  544. {
  545. if(vstd::contains(adjacent, stack)) //binding stack is still present
  546. unbind = false;
  547. }
  548. }
  549. else
  550. {
  551. unbind = false;
  552. }
  553. }
  554. if (unbind)
  555. {
  556. BattleSetStackProperty ssp;
  557. ssp.battleID = battle.getBattle()->getBattleID();
  558. ssp.which = BattleSetStackProperty::UNBIND;
  559. ssp.stackID = st->unitId();
  560. gameHandler->sendAndApply(&ssp);
  561. }
  562. }
  563. if (st->hasBonusOfType(BonusType::POISON))
  564. {
  565. std::shared_ptr<const Bonus> b = st->getBonusLocalFirst(Selector::source(BonusSource::SPELL_EFFECT, SpellID::POISON).And(Selector::type()(BonusType::STACK_HEALTH)));
  566. if (b) //TODO: what if not?...
  567. {
  568. bte.val = std::max (b->val - 10, -(st->valOfBonuses(BonusType::POISON)));
  569. if (bte.val < b->val) //(negative) poison effect increases - update it
  570. {
  571. bte.effect = vstd::to_underlying(BonusType::POISON);
  572. gameHandler->sendAndApply(&bte);
  573. }
  574. }
  575. }
  576. if(st->hasBonusOfType(BonusType::MANA_DRAIN) && !st->drainedMana)
  577. {
  578. const PlayerColor opponent = battle.otherPlayer(battle.battleGetOwner(st));
  579. const CGHeroInstance * opponentHero = battle.battleGetFightingHero(opponent);
  580. if(opponentHero)
  581. {
  582. ui32 manaDrained = st->valOfBonuses(BonusType::MANA_DRAIN);
  583. vstd::amin(manaDrained, opponentHero->mana);
  584. if(manaDrained)
  585. {
  586. bte.effect = vstd::to_underlying(BonusType::MANA_DRAIN);
  587. bte.val = manaDrained;
  588. bte.additionalInfo = opponentHero->id.getNum(); //for sanity
  589. gameHandler->sendAndApply(&bte);
  590. }
  591. }
  592. }
  593. if (st->isLiving() && !st->hasBonusOfType(BonusType::FEARLESS))
  594. {
  595. bool fearsomeCreature = false;
  596. for (const CStack * stack : battle.battleGetAllStacks(true))
  597. {
  598. if (battle.battleMatchOwner(st, stack) && stack->alive() && stack->hasBonusOfType(BonusType::FEAR))
  599. {
  600. fearsomeCreature = true;
  601. break;
  602. }
  603. }
  604. if (fearsomeCreature)
  605. {
  606. if (gameHandler->getRandomGenerator().nextInt(99) < 10) //fixed 10%
  607. {
  608. bte.effect = vstd::to_underlying(BonusType::FEAR);
  609. gameHandler->sendAndApply(&bte);
  610. }
  611. }
  612. }
  613. BonusList bl = *(st->getBonuses(Selector::type()(BonusType::ENCHANTER)));
  614. int side = *battle.playerToSide(st->unitOwner());
  615. if(st->canCast() && battle.battleGetEnchanterCounter(side) == 0)
  616. {
  617. bool cast = false;
  618. while(!bl.empty() && !cast)
  619. {
  620. auto bonus = *RandomGeneratorUtil::nextItem(bl, gameHandler->getRandomGenerator());
  621. auto spellID = SpellID(bonus->subtype);
  622. const CSpell * spell = SpellID(spellID).toSpell();
  623. bl.remove_if([&bonus](const Bonus * b)
  624. {
  625. return b == bonus.get();
  626. });
  627. spells::BattleCast parameters(&battle, st, spells::Mode::ENCHANTER, spell);
  628. parameters.setSpellLevel(bonus->val);
  629. parameters.massive = true;
  630. parameters.smart = true;
  631. //todo: recheck effect level
  632. if(parameters.castIfPossible(gameHandler->spellEnv, spells::Target(1, spells::Destination())))
  633. {
  634. cast = true;
  635. int cooldown = bonus->additionalInfo[0];
  636. BattleSetStackProperty ssp;
  637. ssp.battleID = battle.getBattle()->getBattleID();
  638. ssp.which = BattleSetStackProperty::ENCHANTER_COUNTER;
  639. ssp.absolute = false;
  640. ssp.val = cooldown;
  641. ssp.stackID = st->unitId();
  642. gameHandler->sendAndApply(&ssp);
  643. }
  644. }
  645. }
  646. }
  647. }
  648. void BattleFlowProcessor::setActiveStack(const CBattleInfoCallback & battle, const battle::Unit * stack)
  649. {
  650. assert(stack);
  651. BattleSetActiveStack sas;
  652. sas.battleID = battle.getBattle()->getBattleID();
  653. sas.stack = stack->unitId();
  654. gameHandler->sendAndApply(&sas);
  655. }