BattleFlowProcessor.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794
  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. if(next->alive()) {
  273. setActiveStack(battle, next);
  274. break;
  275. }
  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: unify logic with AI?
  330. // Find best target using logic similar to H3 AI
  331. const auto & isBetterTarget = [&battle](const battle::Unit * candidate, const battle::Unit * current)
  332. {
  333. bool candidateInsideWalls = battle.battleIsInsideWalls(candidate->getPosition());
  334. bool currentInsideWalls = battle.battleIsInsideWalls(current->getPosition());
  335. if (candidateInsideWalls != currentInsideWalls)
  336. return candidateInsideWalls > currentInsideWalls;
  337. // also check for war machines - shooters are more dangerous than war machines, ballista or catapult
  338. bool candidateCanShoot = candidate->canShoot() && candidate->unitType()->warMachine == ArtifactID::NONE;
  339. bool currentCanShoot = current->canShoot() && current->unitType()->warMachine == ArtifactID::NONE;
  340. if (candidateCanShoot != currentCanShoot)
  341. return candidateCanShoot > currentCanShoot;
  342. int64_t candidateTargetValue = static_cast<int64_t>(candidate->unitType()->getAIValue() * candidate->getCount());
  343. int64_t currentTargetValue = static_cast<int64_t>(current->unitType()->getAIValue() * current->getCount());
  344. return candidateTargetValue > currentTargetValue;
  345. };
  346. const battle::Unit * target = nullptr;
  347. for(auto & elem : battle.battleGetAllStacks(true))
  348. {
  349. if (elem->unitOwner() == next->unitOwner())
  350. continue;
  351. if (!elem->isValidTarget())
  352. continue;
  353. if (!battle.battleCanShoot(next, elem->getPosition()))
  354. continue;
  355. if (target && !isBetterTarget(elem, target))
  356. continue;
  357. target = elem;
  358. }
  359. if(target == nullptr)
  360. {
  361. makeStackDoNothing(battle, next);
  362. }
  363. else
  364. {
  365. attack.aimToUnit(target);
  366. makeAutomaticAction(battle, next, attack);
  367. }
  368. return true;
  369. }
  370. if (next->unitType()->getId() == CreatureID::CATAPULT)
  371. {
  372. const auto & attackableBattleHexes = battle.getAttackableBattleHexes();
  373. if (attackableBattleHexes.empty())
  374. {
  375. makeStackDoNothing(battle, next);
  376. return true;
  377. }
  378. if (!curOwner || gameHandler->getRandomGenerator().nextInt(99) >= curOwner->valOfBonuses(BonusType::MANUAL_CONTROL, BonusSubtypeID(CreatureID(CreatureID::CATAPULT))))
  379. {
  380. BattleAction attack;
  381. attack.actionType = EActionType::CATAPULT;
  382. attack.side = next->unitSide();
  383. attack.stackNumber = next->unitId();
  384. makeAutomaticAction(battle, next, attack);
  385. return true;
  386. }
  387. }
  388. if (next->unitType()->getId() == CreatureID::FIRST_AID_TENT)
  389. {
  390. TStacks possibleStacks = battle.battleGetStacksIf([=](const CStack * s)
  391. {
  392. return s->unitOwner() == next->unitOwner() && s->canBeHealed();
  393. });
  394. if (possibleStacks.empty())
  395. {
  396. makeStackDoNothing(battle, next);
  397. return true;
  398. }
  399. if (!curOwner || gameHandler->getRandomGenerator().nextInt(99) >= curOwner->valOfBonuses(BonusType::MANUAL_CONTROL, BonusSubtypeID(CreatureID(CreatureID::FIRST_AID_TENT))))
  400. {
  401. RandomGeneratorUtil::randomShuffle(possibleStacks, gameHandler->getRandomGenerator());
  402. const CStack * toBeHealed = possibleStacks.front();
  403. BattleAction heal;
  404. heal.actionType = EActionType::STACK_HEAL;
  405. heal.aimToUnit(toBeHealed);
  406. heal.side = next->unitSide();
  407. heal.stackNumber = next->unitId();
  408. makeAutomaticAction(battle, next, heal);
  409. return true;
  410. }
  411. }
  412. stackTurnTrigger(battle, next); //various effects
  413. if(next->fear)
  414. {
  415. makeStackDoNothing(battle, next); //end immediately if stack was affected by fear
  416. return true;
  417. }
  418. return false;
  419. }
  420. bool BattleFlowProcessor::rollGoodMorale(const CBattleInfoCallback & battle, const CStack * next)
  421. {
  422. //check for good morale
  423. auto nextStackMorale = next->moraleVal();
  424. if( !next->hadMorale
  425. && !next->defending
  426. && !next->waited()
  427. && !next->fear
  428. && next->alive()
  429. && next->canMove()
  430. && nextStackMorale > 0)
  431. {
  432. auto diceSize = VLC->settings()->getVector(EGameSettings::COMBAT_GOOD_MORALE_DICE);
  433. size_t diceIndex = std::min<size_t>(diceSize.size(), nextStackMorale) - 1; // array index, so 0-indexed
  434. if(diceSize.size() > 0 && gameHandler->getRandomGenerator().nextInt(1, diceSize[diceIndex]) == 1)
  435. {
  436. BattleTriggerEffect bte;
  437. bte.battleID = battle.getBattle()->getBattleID();
  438. bte.stackID = next->unitId();
  439. bte.effect = vstd::to_underlying(BonusType::MORALE);
  440. bte.val = 1;
  441. bte.additionalInfo = 0;
  442. gameHandler->sendAndApply(&bte); //play animation
  443. return true;
  444. }
  445. }
  446. return false;
  447. }
  448. void BattleFlowProcessor::onActionMade(const CBattleInfoCallback & battle, const BattleAction &ba)
  449. {
  450. const auto * actedStack = battle.battleGetStackByID(ba.stackNumber, false);
  451. const auto * activeStack = battle.battleActiveUnit();
  452. if (ba.actionType == EActionType::END_TACTIC_PHASE)
  453. {
  454. onTacticsEnded(battle);
  455. return;
  456. }
  457. //we're after action, all results applied
  458. // check whether action has ended the battle
  459. if(owner->checkBattleStateChanges(battle))
  460. return;
  461. // tactics - next stack will be selected by player
  462. if(battle.battleGetTacticDist() != 0)
  463. return;
  464. if (ba.isUnitAction())
  465. {
  466. assert(activeStack != nullptr);
  467. assert(actedStack != nullptr);
  468. if (rollGoodMorale(battle, actedStack))
  469. {
  470. // Good morale - same stack makes 2nd turn
  471. setActiveStack(battle, actedStack);
  472. return;
  473. }
  474. }
  475. else
  476. {
  477. if (activeStack && activeStack->alive())
  478. {
  479. // this is action made by hero AND unit is alive (e.g. not killed by casted spell)
  480. // keep current active stack for next action
  481. setActiveStack(battle, activeStack);
  482. return;
  483. }
  484. }
  485. activateNextStack(battle);
  486. }
  487. void BattleFlowProcessor::makeStackDoNothing(const CBattleInfoCallback & battle, const CStack * next)
  488. {
  489. BattleAction doNothing;
  490. doNothing.actionType = EActionType::NO_ACTION;
  491. doNothing.side = next->unitSide();
  492. doNothing.stackNumber = next->unitId();
  493. makeAutomaticAction(battle, next, doNothing);
  494. }
  495. bool BattleFlowProcessor::makeAutomaticAction(const CBattleInfoCallback & battle, const CStack *stack, BattleAction &ba)
  496. {
  497. BattleSetActiveStack bsa;
  498. bsa.battleID = battle.getBattle()->getBattleID();
  499. bsa.stack = stack->unitId();
  500. bsa.askPlayerInterface = false;
  501. gameHandler->sendAndApply(&bsa);
  502. bool ret = owner->makeAutomaticBattleAction(battle, ba);
  503. return ret;
  504. }
  505. void BattleFlowProcessor::stackEnchantedTrigger(const CBattleInfoCallback & battle, const CStack * st)
  506. {
  507. auto bl = *(st->getBonuses(Selector::type()(BonusType::ENCHANTED)));
  508. for(auto b : bl)
  509. {
  510. if (!b->subtype.as<SpellID>().hasValue())
  511. continue;
  512. const CSpell * sp = b->subtype.as<SpellID>().toSpell();
  513. const int32_t val = bl.valOfBonuses(Selector::typeSubtype(b->type, b->subtype));
  514. const int32_t level = ((val > 3) ? (val - 3) : val);
  515. spells::BattleCast battleCast(&battle, st, spells::Mode::PASSIVE, sp);
  516. //this makes effect accumulate for at most 50 turns by default, but effect may be permanent and last till the end of battle
  517. battleCast.setEffectDuration(50);
  518. battleCast.setSpellLevel(level);
  519. spells::Target target;
  520. if(val > 3)
  521. {
  522. for(auto s : battle.battleGetAllStacks())
  523. if(battle.battleMatchOwner(st, s, true) && s->isValidTarget()) //all allied
  524. target.emplace_back(s);
  525. }
  526. else
  527. {
  528. target.emplace_back(st);
  529. }
  530. battleCast.applyEffects(gameHandler->spellEnv, target, false, true);
  531. }
  532. }
  533. void BattleFlowProcessor::removeObstacle(const CBattleInfoCallback & battle, const CObstacleInstance & obstacle)
  534. {
  535. BattleObstaclesChanged obsRem;
  536. obsRem.battleID = battle.getBattle()->getBattleID();
  537. obsRem.changes.emplace_back(obstacle.uniqueID, ObstacleChanges::EOperation::REMOVE);
  538. gameHandler->sendAndApply(&obsRem);
  539. }
  540. void BattleFlowProcessor::stackTurnTrigger(const CBattleInfoCallback & battle, const CStack *st)
  541. {
  542. BattleTriggerEffect bte;
  543. bte.battleID = battle.getBattle()->getBattleID();
  544. bte.stackID = st->unitId();
  545. bte.effect = -1;
  546. bte.val = 0;
  547. bte.additionalInfo = 0;
  548. if (st->alive())
  549. {
  550. //unbind
  551. if (st->hasBonus(Selector::type()(BonusType::BIND_EFFECT)))
  552. {
  553. bool unbind = true;
  554. BonusList bl = *(st->getBonuses(Selector::type()(BonusType::BIND_EFFECT)));
  555. auto adjacent = battle.battleAdjacentUnits(st);
  556. for (auto b : bl)
  557. {
  558. if(b->additionalInfo != CAddInfo::NONE)
  559. {
  560. const CStack * stack = battle.battleGetStackByID(b->additionalInfo[0]); //binding stack must be alive and adjacent
  561. if(stack)
  562. {
  563. if(vstd::contains(adjacent, stack)) //binding stack is still present
  564. unbind = false;
  565. }
  566. }
  567. else
  568. {
  569. unbind = false;
  570. }
  571. }
  572. if (unbind)
  573. {
  574. BattleSetStackProperty ssp;
  575. ssp.battleID = battle.getBattle()->getBattleID();
  576. ssp.which = BattleSetStackProperty::UNBIND;
  577. ssp.stackID = st->unitId();
  578. gameHandler->sendAndApply(&ssp);
  579. }
  580. }
  581. if (st->hasBonusOfType(BonusType::POISON))
  582. {
  583. std::shared_ptr<const Bonus> b = st->getFirstBonus(Selector::source(BonusSource::SPELL_EFFECT, BonusSourceID(SpellID(SpellID::POISON))).And(Selector::type()(BonusType::STACK_HEALTH)));
  584. if (b) //TODO: what if not?...
  585. {
  586. bte.val = std::max (b->val - 10, -(st->valOfBonuses(BonusType::POISON)));
  587. if (bte.val < b->val) //(negative) poison effect increases - update it
  588. {
  589. bte.effect = vstd::to_underlying(BonusType::POISON);
  590. gameHandler->sendAndApply(&bte);
  591. }
  592. }
  593. }
  594. if(st->hasBonusOfType(BonusType::MANA_DRAIN) && !st->drainedMana)
  595. {
  596. const CGHeroInstance * opponentHero = battle.battleGetFightingHero(battle.otherSide(st->unitSide()));
  597. if(opponentHero)
  598. {
  599. ui32 manaDrained = st->valOfBonuses(BonusType::MANA_DRAIN);
  600. vstd::amin(manaDrained, opponentHero->mana);
  601. if(manaDrained)
  602. {
  603. bte.effect = vstd::to_underlying(BonusType::MANA_DRAIN);
  604. bte.val = manaDrained;
  605. bte.additionalInfo = opponentHero->id.getNum(); //for sanity
  606. gameHandler->sendAndApply(&bte);
  607. }
  608. }
  609. }
  610. if (st->isLiving() && !st->hasBonusOfType(BonusType::FEARLESS))
  611. {
  612. bool fearsomeCreature = false;
  613. for (const CStack * stack : battle.battleGetAllStacks(true))
  614. {
  615. if (battle.battleMatchOwner(st, stack) && stack->alive() && stack->hasBonusOfType(BonusType::FEAR))
  616. {
  617. fearsomeCreature = true;
  618. break;
  619. }
  620. }
  621. if (fearsomeCreature)
  622. {
  623. if (gameHandler->getRandomGenerator().nextInt(99) < 10) //fixed 10%
  624. {
  625. bte.effect = vstd::to_underlying(BonusType::FEAR);
  626. gameHandler->sendAndApply(&bte);
  627. }
  628. }
  629. }
  630. BonusList bl = *(st->getBonuses(Selector::type()(BonusType::ENCHANTER)));
  631. bl.remove_if([](const Bonus * b)
  632. {
  633. return b->subtype.as<SpellID>() == SpellID::NONE;
  634. });
  635. int side = *battle.playerToSide(st->unitOwner());
  636. if(st->canCast() && battle.battleGetEnchanterCounter(side) == 0)
  637. {
  638. bool cast = false;
  639. while(!bl.empty() && !cast)
  640. {
  641. auto bonus = *RandomGeneratorUtil::nextItem(bl, gameHandler->getRandomGenerator());
  642. auto spellID = bonus->subtype.as<SpellID>();
  643. const CSpell * spell = SpellID(spellID).toSpell();
  644. bl.remove_if([&bonus](const Bonus * b)
  645. {
  646. return b == bonus.get();
  647. });
  648. spells::BattleCast parameters(&battle, st, spells::Mode::ENCHANTER, spell);
  649. parameters.setSpellLevel(bonus->val);
  650. //todo: not hardcode
  651. if (spellID != SpellID::ARMAGEDDON) {
  652. parameters.massive = true;
  653. parameters.smart = true;
  654. }
  655. //todo: recheck effect level
  656. if(parameters.castIfPossible(gameHandler->spellEnv, spells::Target(1, spells::Destination())))
  657. {
  658. cast = true;
  659. int cooldown = bonus->additionalInfo[0];
  660. BattleSetStackProperty ssp;
  661. ssp.battleID = battle.getBattle()->getBattleID();
  662. ssp.which = BattleSetStackProperty::ENCHANTER_COUNTER;
  663. ssp.absolute = false;
  664. ssp.val = cooldown;
  665. ssp.stackID = st->unitId();
  666. gameHandler->sendAndApply(&ssp);
  667. }
  668. }
  669. }
  670. }
  671. }
  672. void BattleFlowProcessor::setActiveStack(const CBattleInfoCallback & battle, const battle::Unit * stack)
  673. {
  674. assert(stack);
  675. BattleSetActiveStack sas;
  676. sas.battleID = battle.getBattle()->getBattleID();
  677. sas.stack = stack->unitId();
  678. gameHandler->sendAndApply(&sas);
  679. }