BattleFlowProcessor.cpp 24 KB

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