BattleFlowProcessor.cpp 26 KB

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