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