BattleFlowProcessor.cpp 27 KB

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