BattleFlowProcessor.cpp 25 KB

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