BattleFlowProcessor.cpp 27 KB

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