BattleFlowProcessor.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764
  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)
  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 = summonInfo->subtype.as<CreatureID>();
  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. fakeEvent.battleID = battle.getBattle()->getBattleID();
  159. gameHandler->sendAndApply(&fakeEvent);
  160. }
  161. void BattleFlowProcessor::castOpeningSpells(const CBattleInfoCallback & battle)
  162. {
  163. for (int i = 0; i < 2; ++i)
  164. {
  165. auto h = battle.battleGetFightingHero(i);
  166. if (!h)
  167. continue;
  168. TConstBonusListPtr bl = h->getBonuses(Selector::type()(BonusType::OPENING_BATTLE_SPELL));
  169. for (auto b : *bl)
  170. {
  171. spells::BonusCaster caster(h, b);
  172. const CSpell * spell = b->subtype.as<SpellID>().toSpell();
  173. spells::BattleCast parameters(&battle, &caster, spells::Mode::PASSIVE, spell);
  174. parameters.setSpellLevel(3);
  175. parameters.setEffectDuration(b->val);
  176. parameters.massive = true;
  177. parameters.castIfPossible(gameHandler->spellEnv, spells::Target());
  178. }
  179. }
  180. }
  181. void BattleFlowProcessor::onTacticsEnded(const CBattleInfoCallback & battle)
  182. {
  183. //initial stacks appearance triggers, e.g. built-in bonus spells
  184. auto initialStacks = battle.battleGetAllStacks(true);
  185. for (const CStack * stack : initialStacks)
  186. {
  187. trySummonGuardians(battle, stack);
  188. stackEnchantedTrigger(battle, stack);
  189. }
  190. castOpeningSpells(battle);
  191. // it is possible that due to opening spells one side was eliminated -> check for end of battle
  192. if (owner->checkBattleStateChanges(battle))
  193. return;
  194. startNextRound(battle, true);
  195. activateNextStack(battle);
  196. }
  197. void BattleFlowProcessor::startNextRound(const CBattleInfoCallback & battle, bool isFirstRound)
  198. {
  199. BattleNextRound bnr;
  200. bnr.battleID = battle.getBattle()->getBattleID();
  201. logGlobal->debug("Next round starts");
  202. gameHandler->sendAndApply(&bnr);
  203. // operate on copy - removing obstacles will invalidate iterator on 'battle' container
  204. auto obstacles = battle.battleGetAllObstacles();
  205. for (auto &obstPtr : obstacles)
  206. {
  207. if (const SpellCreatedObstacle *sco = dynamic_cast<const SpellCreatedObstacle *>(obstPtr.get()))
  208. if (sco->turnsRemaining == 0)
  209. removeObstacle(battle, *obstPtr);
  210. }
  211. for(auto stack : battle.battleGetAllStacks(true))
  212. {
  213. if(stack->alive() && !isFirstRound)
  214. stackEnchantedTrigger(battle, stack);
  215. }
  216. }
  217. const CStack * BattleFlowProcessor::getNextStack(const CBattleInfoCallback & battle)
  218. {
  219. std::vector<battle::Units> q;
  220. battle.battleGetTurnOrder(q, 1, 0, -1); //todo: get rid of "turn -1"
  221. if(q.empty())
  222. return nullptr;
  223. if(q.front().empty())
  224. return nullptr;
  225. auto next = q.front().front();
  226. const auto stack = dynamic_cast<const CStack *>(next);
  227. // regeneration takes place before everything else but only during first turn attempt in each round
  228. // also works under blind and similar effects
  229. if(stack && stack->alive() && !stack->waiting)
  230. {
  231. BattleTriggerEffect bte;
  232. bte.battleID = battle.getBattle()->getBattleID();
  233. bte.stackID = stack->unitId();
  234. bte.effect = vstd::to_underlying(BonusType::HP_REGENERATION);
  235. const int32_t lostHealth = stack->getMaxHealth() - stack->getFirstHPleft();
  236. if(stack->hasBonusOfType(BonusType::HP_REGENERATION))
  237. bte.val = std::min(lostHealth, stack->valOfBonuses(BonusType::HP_REGENERATION));
  238. if(bte.val) // anything to heal
  239. gameHandler->sendAndApply(&bte);
  240. }
  241. if(!next || !next->willMove())
  242. return nullptr;
  243. return stack;
  244. }
  245. void BattleFlowProcessor::activateNextStack(const CBattleInfoCallback & battle)
  246. {
  247. // Find next stack that requires manual control
  248. for (;;)
  249. {
  250. // battle has ended
  251. if (owner->checkBattleStateChanges(battle))
  252. return;
  253. const CStack * next = getNextStack(battle);
  254. if (!next)
  255. {
  256. // No stacks to move - start next round
  257. startNextRound(battle, false);
  258. next = getNextStack(battle);
  259. if (!next)
  260. throw std::runtime_error("Failed to find valid stack to act!");
  261. }
  262. BattleUnitsChanged removeGhosts;
  263. removeGhosts.battleID = battle.getBattle()->getBattleID();
  264. auto pendingGhosts = battle.battleGetStacksIf([](const CStack * stack){
  265. return stack->ghostPending;
  266. });
  267. for(auto stack : pendingGhosts)
  268. removeGhosts.changedStacks.emplace_back(stack->unitId(), UnitChanges::EOperation::REMOVE);
  269. if(!removeGhosts.changedStacks.empty())
  270. gameHandler->sendAndApply(&removeGhosts);
  271. gameHandler->turnTimerHandler.onBattleNextStack(battle.getBattle()->getBattleID(), *next);
  272. if (!tryMakeAutomaticAction(battle, next))
  273. {
  274. setActiveStack(battle, next);
  275. break;
  276. }
  277. }
  278. }
  279. bool BattleFlowProcessor::tryMakeAutomaticAction(const CBattleInfoCallback & battle, const CStack * next)
  280. {
  281. // check for bad morale => freeze
  282. int nextStackMorale = next->moraleVal();
  283. if(!next->hadMorale && !next->waited() && nextStackMorale < 0)
  284. {
  285. auto diceSize = VLC->settings()->getVector(EGameSettings::COMBAT_BAD_MORALE_DICE);
  286. size_t diceIndex = std::min<size_t>(diceSize.size(), -nextStackMorale) - 1; // array index, so 0-indexed
  287. if(diceSize.size() > 0 && gameHandler->getRandomGenerator().nextInt(1, diceSize[diceIndex]) == 1)
  288. {
  289. //unit loses its turn - empty freeze action
  290. BattleAction ba;
  291. ba.actionType = EActionType::BAD_MORALE;
  292. ba.side = next->unitSide();
  293. ba.stackNumber = next->unitId();
  294. makeAutomaticAction(battle, next, ba);
  295. return true;
  296. }
  297. }
  298. if (next->hasBonusOfType(BonusType::ATTACKS_NEAREST_CREATURE)) //while in berserk
  299. {
  300. logGlobal->trace("Handle Berserk effect");
  301. std::pair<const battle::Unit *, BattleHex> attackInfo = battle.getNearestStack(next);
  302. if (attackInfo.first != nullptr)
  303. {
  304. BattleAction attack;
  305. attack.actionType = EActionType::WALK_AND_ATTACK;
  306. attack.side = next->unitSide();
  307. attack.stackNumber = next->unitId();
  308. attack.aimToHex(attackInfo.second);
  309. attack.aimToUnit(attackInfo.first);
  310. makeAutomaticAction(battle, next, attack);
  311. logGlobal->trace("Attacked nearest target %s", attackInfo.first->getDescription());
  312. }
  313. else
  314. {
  315. makeStackDoNothing(battle, next);
  316. logGlobal->trace("No target found");
  317. }
  318. return true;
  319. }
  320. const CGHeroInstance * curOwner = battle.battleGetOwnerHero(next);
  321. const CreatureID stackCreatureId = next->unitType()->getId();
  322. if ((stackCreatureId == CreatureID::ARROW_TOWERS || stackCreatureId == CreatureID::BALLISTA)
  323. && (!curOwner || gameHandler->getRandomGenerator().nextInt(99) >= curOwner->valOfBonuses(BonusType::MANUAL_CONTROL, BonusSubtypeID(stackCreatureId))))
  324. {
  325. BattleAction attack;
  326. attack.actionType = EActionType::SHOOT;
  327. attack.side = next->unitSide();
  328. attack.stackNumber = next->unitId();
  329. //TODO: select target by priority
  330. const battle::Unit * target = nullptr;
  331. for(auto & elem : battle.battleGetAllStacks(true))
  332. {
  333. if(elem->unitType()->getId() != CreatureID::CATAPULT
  334. && elem->unitOwner() != next->unitOwner()
  335. && elem->isValidTarget()
  336. && battle.battleCanShoot(next, elem->getPosition()))
  337. {
  338. target = elem;
  339. break;
  340. }
  341. }
  342. if(target == nullptr)
  343. {
  344. makeStackDoNothing(battle, next);
  345. }
  346. else
  347. {
  348. attack.aimToUnit(target);
  349. makeAutomaticAction(battle, next, attack);
  350. }
  351. return true;
  352. }
  353. if (next->unitType()->getId() == CreatureID::CATAPULT)
  354. {
  355. const auto & attackableBattleHexes = battle.getAttackableBattleHexes();
  356. if (attackableBattleHexes.empty())
  357. {
  358. makeStackDoNothing(battle, next);
  359. return true;
  360. }
  361. if (!curOwner || gameHandler->getRandomGenerator().nextInt(99) >= curOwner->valOfBonuses(BonusType::MANUAL_CONTROL, BonusSubtypeID(CreatureID(CreatureID::CATAPULT))))
  362. {
  363. BattleAction attack;
  364. attack.actionType = EActionType::CATAPULT;
  365. attack.side = next->unitSide();
  366. attack.stackNumber = next->unitId();
  367. makeAutomaticAction(battle, next, attack);
  368. return true;
  369. }
  370. }
  371. if (next->unitType()->getId() == CreatureID::FIRST_AID_TENT)
  372. {
  373. TStacks possibleStacks = battle.battleGetStacksIf([=](const CStack * s)
  374. {
  375. return s->unitOwner() == next->unitOwner() && s->canBeHealed();
  376. });
  377. if (possibleStacks.empty())
  378. {
  379. makeStackDoNothing(battle, next);
  380. return true;
  381. }
  382. if (!curOwner || gameHandler->getRandomGenerator().nextInt(99) >= curOwner->valOfBonuses(BonusType::MANUAL_CONTROL, BonusSubtypeID(CreatureID(CreatureID::FIRST_AID_TENT))))
  383. {
  384. RandomGeneratorUtil::randomShuffle(possibleStacks, gameHandler->getRandomGenerator());
  385. const CStack * toBeHealed = possibleStacks.front();
  386. BattleAction heal;
  387. heal.actionType = EActionType::STACK_HEAL;
  388. heal.aimToUnit(toBeHealed);
  389. heal.side = next->unitSide();
  390. heal.stackNumber = next->unitId();
  391. makeAutomaticAction(battle, next, heal);
  392. return true;
  393. }
  394. }
  395. stackTurnTrigger(battle, next); //various effects
  396. if(next->fear)
  397. {
  398. makeStackDoNothing(battle, next); //end immediately if stack was affected by fear
  399. return true;
  400. }
  401. return false;
  402. }
  403. bool BattleFlowProcessor::rollGoodMorale(const CBattleInfoCallback & battle, const CStack * next)
  404. {
  405. //check for good morale
  406. auto nextStackMorale = next->moraleVal();
  407. if( !next->hadMorale
  408. && !next->defending
  409. && !next->waited()
  410. && !next->fear
  411. && next->alive()
  412. && next->canMove()
  413. && nextStackMorale > 0)
  414. {
  415. auto diceSize = VLC->settings()->getVector(EGameSettings::COMBAT_GOOD_MORALE_DICE);
  416. size_t diceIndex = std::min<size_t>(diceSize.size(), nextStackMorale) - 1; // array index, so 0-indexed
  417. if(diceSize.size() > 0 && gameHandler->getRandomGenerator().nextInt(1, diceSize[diceIndex]) == 1)
  418. {
  419. BattleTriggerEffect bte;
  420. bte.battleID = battle.getBattle()->getBattleID();
  421. bte.stackID = next->unitId();
  422. bte.effect = vstd::to_underlying(BonusType::MORALE);
  423. bte.val = 1;
  424. bte.additionalInfo = 0;
  425. gameHandler->sendAndApply(&bte); //play animation
  426. return true;
  427. }
  428. }
  429. return false;
  430. }
  431. void BattleFlowProcessor::onActionMade(const CBattleInfoCallback & battle, const BattleAction &ba)
  432. {
  433. const auto * actedStack = battle.battleGetStackByID(ba.stackNumber, false);
  434. const auto * activeStack = battle.battleActiveUnit();
  435. if (ba.actionType == EActionType::END_TACTIC_PHASE)
  436. {
  437. onTacticsEnded(battle);
  438. return;
  439. }
  440. //we're after action, all results applied
  441. // check whether action has ended the battle
  442. if(owner->checkBattleStateChanges(battle))
  443. return;
  444. // tactics - next stack will be selected by player
  445. if(battle.battleGetTacticDist() != 0)
  446. return;
  447. if (ba.isUnitAction())
  448. {
  449. assert(activeStack != nullptr);
  450. assert(actedStack != nullptr);
  451. if (rollGoodMorale(battle, actedStack))
  452. {
  453. // Good morale - same stack makes 2nd turn
  454. setActiveStack(battle, actedStack);
  455. return;
  456. }
  457. }
  458. else
  459. {
  460. if (activeStack && activeStack->alive())
  461. {
  462. // this is action made by hero AND unit is alive (e.g. not killed by casted spell)
  463. // keep current active stack for next action
  464. setActiveStack(battle, activeStack);
  465. return;
  466. }
  467. }
  468. activateNextStack(battle);
  469. }
  470. void BattleFlowProcessor::makeStackDoNothing(const CBattleInfoCallback & battle, const CStack * next)
  471. {
  472. BattleAction doNothing;
  473. doNothing.actionType = EActionType::NO_ACTION;
  474. doNothing.side = next->unitSide();
  475. doNothing.stackNumber = next->unitId();
  476. makeAutomaticAction(battle, next, doNothing);
  477. }
  478. bool BattleFlowProcessor::makeAutomaticAction(const CBattleInfoCallback & battle, const CStack *stack, BattleAction &ba)
  479. {
  480. BattleSetActiveStack bsa;
  481. bsa.battleID = battle.getBattle()->getBattleID();
  482. bsa.stack = stack->unitId();
  483. bsa.askPlayerInterface = false;
  484. gameHandler->sendAndApply(&bsa);
  485. bool ret = owner->makeAutomaticBattleAction(battle, ba);
  486. return ret;
  487. }
  488. void BattleFlowProcessor::stackEnchantedTrigger(const CBattleInfoCallback & battle, const CStack * st)
  489. {
  490. auto bl = *(st->getBonuses(Selector::type()(BonusType::ENCHANTED)));
  491. for(auto b : bl)
  492. {
  493. if (!b->subtype.as<SpellID>().hasValue())
  494. continue;
  495. const CSpell * sp = b->subtype.as<SpellID>().toSpell();
  496. const int32_t val = bl.valOfBonuses(Selector::typeSubtype(b->type, b->subtype));
  497. const int32_t level = ((val > 3) ? (val - 3) : val);
  498. spells::BattleCast battleCast(&battle, st, spells::Mode::PASSIVE, sp);
  499. //this makes effect accumulate for at most 50 turns by default, but effect may be permanent and last till the end of battle
  500. battleCast.setEffectDuration(50);
  501. battleCast.setSpellLevel(level);
  502. spells::Target target;
  503. if(val > 3)
  504. {
  505. for(auto s : battle.battleGetAllStacks())
  506. if(battle.battleMatchOwner(st, s, true) && s->isValidTarget()) //all allied
  507. target.emplace_back(s);
  508. }
  509. else
  510. {
  511. target.emplace_back(st);
  512. }
  513. battleCast.applyEffects(gameHandler->spellEnv, target, false, true);
  514. }
  515. }
  516. void BattleFlowProcessor::removeObstacle(const CBattleInfoCallback & battle, const CObstacleInstance & obstacle)
  517. {
  518. BattleObstaclesChanged obsRem;
  519. obsRem.battleID = battle.getBattle()->getBattleID();
  520. obsRem.changes.emplace_back(obstacle.uniqueID, ObstacleChanges::EOperation::REMOVE);
  521. gameHandler->sendAndApply(&obsRem);
  522. }
  523. void BattleFlowProcessor::stackTurnTrigger(const CBattleInfoCallback & battle, const CStack *st)
  524. {
  525. BattleTriggerEffect bte;
  526. bte.battleID = battle.getBattle()->getBattleID();
  527. bte.stackID = st->unitId();
  528. bte.effect = -1;
  529. bte.val = 0;
  530. bte.additionalInfo = 0;
  531. if (st->alive())
  532. {
  533. //unbind
  534. if (st->hasBonus(Selector::type()(BonusType::BIND_EFFECT)))
  535. {
  536. bool unbind = true;
  537. BonusList bl = *(st->getBonuses(Selector::type()(BonusType::BIND_EFFECT)));
  538. auto adjacent = battle.battleAdjacentUnits(st);
  539. for (auto b : bl)
  540. {
  541. if(b->additionalInfo != CAddInfo::NONE)
  542. {
  543. const CStack * stack = battle.battleGetStackByID(b->additionalInfo[0]); //binding stack must be alive and adjacent
  544. if(stack)
  545. {
  546. if(vstd::contains(adjacent, stack)) //binding stack is still present
  547. unbind = false;
  548. }
  549. }
  550. else
  551. {
  552. unbind = false;
  553. }
  554. }
  555. if (unbind)
  556. {
  557. BattleSetStackProperty ssp;
  558. ssp.battleID = battle.getBattle()->getBattleID();
  559. ssp.which = BattleSetStackProperty::UNBIND;
  560. ssp.stackID = st->unitId();
  561. gameHandler->sendAndApply(&ssp);
  562. }
  563. }
  564. if (st->hasBonusOfType(BonusType::POISON))
  565. {
  566. std::shared_ptr<const Bonus> b = st->getFirstBonus(Selector::source(BonusSource::SPELL_EFFECT, BonusSourceID(SpellID(SpellID::POISON))).And(Selector::type()(BonusType::STACK_HEALTH)));
  567. if (b) //TODO: what if not?...
  568. {
  569. bte.val = std::max (b->val - 10, -(st->valOfBonuses(BonusType::POISON)));
  570. if (bte.val < b->val) //(negative) poison effect increases - update it
  571. {
  572. bte.effect = vstd::to_underlying(BonusType::POISON);
  573. gameHandler->sendAndApply(&bte);
  574. }
  575. }
  576. }
  577. if(st->hasBonusOfType(BonusType::MANA_DRAIN) && !st->drainedMana)
  578. {
  579. const CGHeroInstance * opponentHero = battle.battleGetFightingHero(battle.otherSide(st->unitSide()));
  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. bl.remove_if([](const Bonus * b)
  615. {
  616. return b->subtype.as<SpellID>() == SpellID::NONE;
  617. });
  618. int side = *battle.playerToSide(st->unitOwner());
  619. if(st->canCast() && battle.battleGetEnchanterCounter(side) == 0)
  620. {
  621. bool cast = false;
  622. while(!bl.empty() && !cast)
  623. {
  624. auto bonus = *RandomGeneratorUtil::nextItem(bl, gameHandler->getRandomGenerator());
  625. auto spellID = bonus->subtype.as<SpellID>();
  626. const CSpell * spell = SpellID(spellID).toSpell();
  627. bl.remove_if([&bonus](const Bonus * b)
  628. {
  629. return b == bonus.get();
  630. });
  631. spells::BattleCast parameters(&battle, st, spells::Mode::ENCHANTER, spell);
  632. parameters.setSpellLevel(bonus->val);
  633. parameters.massive = true;
  634. parameters.smart = true;
  635. //todo: recheck effect level
  636. if(parameters.castIfPossible(gameHandler->spellEnv, spells::Target(1, spells::Destination())))
  637. {
  638. cast = true;
  639. int cooldown = bonus->additionalInfo[0];
  640. BattleSetStackProperty ssp;
  641. ssp.battleID = battle.getBattle()->getBattleID();
  642. ssp.which = BattleSetStackProperty::ENCHANTER_COUNTER;
  643. ssp.absolute = false;
  644. ssp.val = cooldown;
  645. ssp.stackID = st->unitId();
  646. gameHandler->sendAndApply(&ssp);
  647. }
  648. }
  649. }
  650. }
  651. }
  652. void BattleFlowProcessor::setActiveStack(const CBattleInfoCallback & battle, const battle::Unit * stack)
  653. {
  654. assert(stack);
  655. BattleSetActiveStack sas;
  656. sas.battleID = battle.getBattle()->getBattleID();
  657. sas.stack = stack->unitId();
  658. gameHandler->sendAndApply(&sas);
  659. }