BattleFlowProcessor.cpp 24 KB

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