BattleActionProcessor.cpp 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599
  1. /*
  2. * BattleActionProcessor.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 "BattleActionProcessor.h"
  12. #include "BattleProcessor.h"
  13. #include "../CGameHandler.h"
  14. #include "../../lib/CGeneralTextHandler.h"
  15. #include "../../lib/CStack.h"
  16. #include "../../lib/GameSettings.h"
  17. #include "../../lib/battle/CBattleInfoCallback.h"
  18. #include "../../lib/battle/CObstacleInstance.h"
  19. #include "../../lib/battle/IBattleState.h"
  20. #include "../../lib/battle/BattleAction.h"
  21. #include "../../lib/gameState/CGameState.h"
  22. #include "../../lib/networkPacks/PacksForClientBattle.h"
  23. #include "../../lib/networkPacks/SetStackEffect.h"
  24. #include "../../lib/spells/AbilityCaster.h"
  25. #include "../../lib/spells/CSpellHandler.h"
  26. #include "../../lib/spells/ISpellMechanics.h"
  27. #include "../../lib/spells/Problem.h"
  28. BattleActionProcessor::BattleActionProcessor(BattleProcessor * owner)
  29. : owner(owner)
  30. , gameHandler(nullptr)
  31. {
  32. }
  33. void BattleActionProcessor::setGameHandler(CGameHandler * newGameHandler)
  34. {
  35. gameHandler = newGameHandler;
  36. }
  37. bool BattleActionProcessor::doEmptyAction(const CBattleInfoCallback & battle, const BattleAction & ba)
  38. {
  39. return true;
  40. }
  41. bool BattleActionProcessor::doEndTacticsAction(const CBattleInfoCallback & battle, const BattleAction & ba)
  42. {
  43. return true;
  44. }
  45. bool BattleActionProcessor::doWaitAction(const CBattleInfoCallback & battle, const BattleAction & ba)
  46. {
  47. const CStack * stack = battle.battleGetStackByID(ba.stackNumber);
  48. if (!canStackAct(battle, stack))
  49. return false;
  50. return true;
  51. }
  52. bool BattleActionProcessor::doRetreatAction(const CBattleInfoCallback & battle, const BattleAction & ba)
  53. {
  54. if (!battle.battleCanFlee(battle.sideToPlayer(ba.side)))
  55. {
  56. gameHandler->complain("Cannot retreat!");
  57. return false;
  58. }
  59. owner->setBattleResult(battle, EBattleResult::ESCAPE, !ba.side);
  60. return true;
  61. }
  62. bool BattleActionProcessor::doSurrenderAction(const CBattleInfoCallback & battle, const BattleAction & ba)
  63. {
  64. PlayerColor player = battle.sideToPlayer(ba.side);
  65. int cost = battle.battleGetSurrenderCost(player);
  66. if (cost < 0)
  67. {
  68. gameHandler->complain("Cannot surrender!");
  69. return false;
  70. }
  71. if (gameHandler->getResource(player, EGameResID::GOLD) < cost)
  72. {
  73. gameHandler->complain("Not enough gold to surrender!");
  74. return false;
  75. }
  76. gameHandler->giveResource(player, EGameResID::GOLD, -cost);
  77. owner->setBattleResult(battle, EBattleResult::SURRENDER, !ba.side);
  78. return true;
  79. }
  80. bool BattleActionProcessor::doHeroSpellAction(const CBattleInfoCallback & battle, const BattleAction & ba)
  81. {
  82. const CGHeroInstance *h = battle.battleGetFightingHero(ba.side);
  83. if (!h)
  84. {
  85. logGlobal->error("Wrong caster!");
  86. return false;
  87. }
  88. if (!ba.spell.hasValue())
  89. {
  90. logGlobal->error("Wrong spell id (%d)!", ba.spell.getNum());
  91. return false;
  92. }
  93. const CSpell * s = ba.spell.toSpell();
  94. spells::BattleCast parameters(&battle, h, spells::Mode::HERO, s);
  95. spells::detail::ProblemImpl problem;
  96. auto m = s->battleMechanics(&parameters);
  97. if(!m->canBeCast(problem))//todo: should we check aimed cast?
  98. {
  99. logGlobal->warn("Spell cannot be cast!");
  100. std::vector<std::string> texts;
  101. problem.getAll(texts);
  102. for(auto s : texts)
  103. logGlobal->warn(s);
  104. return false;
  105. }
  106. parameters.cast(gameHandler->spellEnv, ba.getTarget(&battle));
  107. return true;
  108. }
  109. bool BattleActionProcessor::doWalkAction(const CBattleInfoCallback & battle, const BattleAction & ba)
  110. {
  111. const CStack * stack = battle.battleGetStackByID(ba.stackNumber);
  112. battle::Target target = ba.getTarget(&battle);
  113. if (!canStackAct(battle, stack))
  114. return false;
  115. if(target.size() < 1)
  116. {
  117. gameHandler->complain("Destination required for move action.");
  118. return false;
  119. }
  120. int walkedTiles = moveStack(battle, ba.stackNumber, target.at(0).hexValue); //move
  121. if (!walkedTiles)
  122. {
  123. gameHandler->complain("Stack failed movement!");
  124. return false;
  125. }
  126. return true;
  127. }
  128. bool BattleActionProcessor::doDefendAction(const CBattleInfoCallback & battle, const BattleAction & ba)
  129. {
  130. const CStack * stack = battle.battleGetStackByID(ba.stackNumber);
  131. if (!canStackAct(battle, stack))
  132. return false;
  133. //defensive stance, TODO: filter out spell boosts from bonus (stone skin etc.)
  134. SetStackEffect sse;
  135. sse.battleID = battle.getBattle()->getBattleID();
  136. Bonus defenseBonusToAdd(BonusDuration::STACK_GETS_TURN, BonusType::PRIMARY_SKILL, BonusSource::OTHER, 20, BonusSourceID(), BonusSubtypeID(PrimarySkill::DEFENSE), BonusValueType::PERCENT_TO_ALL);
  137. Bonus bonus2(BonusDuration::STACK_GETS_TURN, BonusType::PRIMARY_SKILL, BonusSource::OTHER, stack->valOfBonuses(BonusType::DEFENSIVE_STANCE), BonusSourceID(), BonusSubtypeID(PrimarySkill::DEFENSE), BonusValueType::ADDITIVE_VALUE);
  138. Bonus alternativeWeakCreatureBonus(BonusDuration::STACK_GETS_TURN, BonusType::PRIMARY_SKILL, BonusSource::OTHER, 1, BonusSourceID(), BonusSubtypeID(PrimarySkill::DEFENSE), BonusValueType::ADDITIVE_VALUE);
  139. BonusList defence = *stack->getBonuses(Selector::typeSubtype(BonusType::PRIMARY_SKILL, BonusSubtypeID(PrimarySkill::DEFENSE)));
  140. int oldDefenceValue = defence.totalValue();
  141. defence.push_back(std::make_shared<Bonus>(defenseBonusToAdd));
  142. defence.push_back(std::make_shared<Bonus>(bonus2));
  143. int difference = defence.totalValue() - oldDefenceValue;
  144. std::vector<Bonus> buffer;
  145. if(difference == 0) //give replacement bonus for creatures not reaching 5 defense points (20% of def becomes 0)
  146. {
  147. difference = 1;
  148. buffer.push_back(alternativeWeakCreatureBonus);
  149. }
  150. else
  151. {
  152. buffer.push_back(defenseBonusToAdd);
  153. }
  154. buffer.push_back(bonus2);
  155. sse.toUpdate.push_back(std::make_pair(ba.stackNumber, buffer));
  156. gameHandler->sendAndApply(&sse);
  157. BattleLogMessage message;
  158. message.battleID = battle.getBattle()->getBattleID();
  159. MetaString text;
  160. stack->addText(text, EMetaText::GENERAL_TXT, 120);
  161. stack->addNameReplacement(text);
  162. text.replaceNumber(difference);
  163. message.lines.push_back(text);
  164. gameHandler->sendAndApply(&message);
  165. return true;
  166. }
  167. bool BattleActionProcessor::doAttackAction(const CBattleInfoCallback & battle, const BattleAction & ba)
  168. {
  169. const CStack * stack = battle.battleGetStackByID(ba.stackNumber);
  170. battle::Target target = ba.getTarget(&battle);
  171. if (!canStackAct(battle, stack))
  172. return false;
  173. if(target.size() < 2)
  174. {
  175. gameHandler->complain("Two destinations required for attack action.");
  176. return false;
  177. }
  178. BattleHex attackPos = target.at(0).hexValue;
  179. BattleHex destinationTile = target.at(1).hexValue;
  180. const CStack * destinationStack = battle.battleGetStackByPos(destinationTile, true);
  181. if(!destinationStack)
  182. {
  183. gameHandler->complain("Invalid target to attack");
  184. return false;
  185. }
  186. BattleHex startingPos = stack->getPosition();
  187. int distance = moveStack(battle, ba.stackNumber, attackPos);
  188. logGlobal->trace("%s will attack %s", stack->nodeName(), destinationStack->nodeName());
  189. if(stack->getPosition() != attackPos && !(stack->doubleWide() && (stack->getPosition() == attackPos.cloneInDirection(stack->destShiftDir(), false))) )
  190. {
  191. // we were not able to reach destination tile, nor occupy specified hex
  192. // abort attack attempt, but treat this case as legal - we may have stepped onto a quicksands/mine
  193. return true;
  194. }
  195. if(destinationStack && stack->unitId() == destinationStack->unitId()) //we should just move, it will be handled by following check
  196. {
  197. destinationStack = nullptr;
  198. }
  199. if(!destinationStack)
  200. {
  201. gameHandler->complain("Unit can not attack itself");
  202. return false;
  203. }
  204. if(!CStack::isMeleeAttackPossible(stack, destinationStack))
  205. {
  206. gameHandler->complain("Attack cannot be performed!");
  207. return false;
  208. }
  209. //attack
  210. int totalAttacks = stack->totalAttacks.getMeleeValue();
  211. //TODO: move to CUnitState
  212. const auto * attackingHero = battle.battleGetFightingHero(ba.side);
  213. if(attackingHero)
  214. {
  215. totalAttacks += attackingHero->valOfBonuses(BonusType::HERO_GRANTS_ATTACKS, BonusSubtypeID(stack->creatureId()));
  216. }
  217. static const auto firstStrikeSelector = Selector::typeSubtype(BonusType::FIRST_STRIKE, BonusCustomSubtype::damageTypeAll).Or(Selector::typeSubtype(BonusType::FIRST_STRIKE, BonusCustomSubtype::damageTypeMelee));
  218. const bool firstStrike = destinationStack->hasBonus(firstStrikeSelector);
  219. const bool retaliation = destinationStack->ableToRetaliate();
  220. bool ferocityApplied = false;
  221. int32_t defenderInitialQuantity = destinationStack->getCount();
  222. for (int i = 0; i < totalAttacks; ++i)
  223. {
  224. //first strike
  225. if(i == 0 && firstStrike && retaliation && !stack->hasBonusOfType(BonusType::BLOCKS_RETALIATION))
  226. {
  227. makeAttack(battle, destinationStack, stack, 0, stack->getPosition(), true, false, true);
  228. }
  229. //move can cause death, eg. by walking into the moat, first strike can cause death or paralysis/petrification
  230. if(stack->alive() && !stack->hasBonusOfType(BonusType::NOT_ACTIVE) && destinationStack->alive())
  231. {
  232. makeAttack(battle, stack, destinationStack, (i ? 0 : distance), destinationTile, i==0, false, false);//no distance travelled on second attack
  233. if(!ferocityApplied && stack->hasBonusOfType(BonusType::FEROCITY))
  234. {
  235. auto ferocityBonus = stack->getBonus(Selector::type()(BonusType::FEROCITY));
  236. int32_t requiredCreaturesToKill = ferocityBonus->additionalInfo != CAddInfo::NONE ? ferocityBonus->additionalInfo[0] : 1;
  237. if(defenderInitialQuantity - destinationStack->getCount() >= requiredCreaturesToKill)
  238. {
  239. ferocityApplied = true;
  240. int additionalAttacksCount = stack->valOfBonuses(BonusType::FEROCITY);
  241. totalAttacks += additionalAttacksCount;
  242. }
  243. }
  244. }
  245. //counterattack
  246. //we check retaliation twice, so if it unblocked during attack it will work only on next attack
  247. if(stack->alive()
  248. && !stack->hasBonusOfType(BonusType::BLOCKS_RETALIATION)
  249. && (i == 0 && !firstStrike)
  250. && retaliation && destinationStack->ableToRetaliate())
  251. {
  252. makeAttack(battle, destinationStack, stack, 0, stack->getPosition(), true, false, true);
  253. }
  254. }
  255. //return
  256. if(stack->hasBonusOfType(BonusType::RETURN_AFTER_STRIKE)
  257. && target.size() == 3
  258. && startingPos != stack->getPosition()
  259. && startingPos == target.at(2).hexValue
  260. && stack->alive())
  261. {
  262. moveStack(battle, ba.stackNumber, startingPos);
  263. //NOTE: curStack->unitId() == ba.stackNumber (rev 1431)
  264. }
  265. return true;
  266. }
  267. bool BattleActionProcessor::doShootAction(const CBattleInfoCallback & battle, const BattleAction & ba)
  268. {
  269. const CStack * stack = battle.battleGetStackByID(ba.stackNumber);
  270. battle::Target target = ba.getTarget(&battle);
  271. if (!canStackAct(battle, stack))
  272. return false;
  273. if(target.size() < 1)
  274. {
  275. gameHandler->complain("Destination required for shot action.");
  276. return false;
  277. }
  278. auto destination = target.at(0).hexValue;
  279. const CStack * destinationStack = battle.battleGetStackByPos(destination);
  280. if (!battle.battleCanShoot(stack, destination))
  281. {
  282. gameHandler->complain("Cannot shoot!");
  283. return false;
  284. }
  285. if (!destinationStack)
  286. {
  287. gameHandler->complain("No target to shoot!");
  288. return false;
  289. }
  290. static const auto firstStrikeSelector = Selector::typeSubtype(BonusType::FIRST_STRIKE, BonusCustomSubtype::damageTypeAll).Or(Selector::typeSubtype(BonusType::FIRST_STRIKE, BonusCustomSubtype::damageTypeRanged));
  291. const bool firstStrike = destinationStack->hasBonus(firstStrikeSelector);
  292. if (!firstStrike)
  293. makeAttack(battle, stack, destinationStack, 0, destination, true, true, false);
  294. //ranged counterattack
  295. if (destinationStack->hasBonusOfType(BonusType::RANGED_RETALIATION)
  296. && !stack->hasBonusOfType(BonusType::BLOCKS_RANGED_RETALIATION)
  297. && destinationStack->ableToRetaliate()
  298. && battle.battleCanShoot(destinationStack, stack->getPosition())
  299. && stack->alive()) //attacker may have died (fire shield)
  300. {
  301. makeAttack(battle, destinationStack, stack, 0, stack->getPosition(), true, true, true);
  302. }
  303. //allow more than one additional attack
  304. int totalRangedAttacks = stack->totalAttacks.getRangedValue();
  305. //TODO: move to CUnitState
  306. const auto * attackingHero = battle.battleGetFightingHero(ba.side);
  307. if(attackingHero)
  308. {
  309. totalRangedAttacks += attackingHero->valOfBonuses(BonusType::HERO_GRANTS_ATTACKS, BonusSubtypeID(stack->creatureId()));
  310. }
  311. for(int i = firstStrike ? 0:1; i < totalRangedAttacks; ++i)
  312. {
  313. if(
  314. stack->alive()
  315. && destinationStack->alive()
  316. && stack->shots.canUse()
  317. )
  318. {
  319. makeAttack(battle, stack, destinationStack, 0, destination, false, true, false);
  320. }
  321. }
  322. return true;
  323. }
  324. bool BattleActionProcessor::doCatapultAction(const CBattleInfoCallback & battle, const BattleAction & ba)
  325. {
  326. const CStack * stack = battle.battleGetStackByID(ba.stackNumber);
  327. battle::Target target = ba.getTarget(&battle);
  328. if (!canStackAct(battle, stack))
  329. return false;
  330. std::shared_ptr<const Bonus> catapultAbility = stack->getFirstBonus(Selector::type()(BonusType::CATAPULT));
  331. if(!catapultAbility || catapultAbility->subtype == BonusSubtypeID())
  332. {
  333. gameHandler->complain("We do not know how to shoot :P");
  334. }
  335. else
  336. {
  337. const CSpell * spell = catapultAbility->subtype.as<SpellID>().toSpell();
  338. spells::BattleCast parameters(&battle, stack, spells::Mode::SPELL_LIKE_ATTACK, spell); //We can shot infinitely by catapult
  339. auto shotLevel = stack->valOfBonuses(Selector::typeSubtype(BonusType::CATAPULT_EXTRA_SHOTS, catapultAbility->subtype));
  340. parameters.setSpellLevel(shotLevel);
  341. parameters.cast(gameHandler->spellEnv, target);
  342. }
  343. return true;
  344. }
  345. bool BattleActionProcessor::doUnitSpellAction(const CBattleInfoCallback & battle, const BattleAction & ba)
  346. {
  347. const CStack * stack = battle.battleGetStackByID(ba.stackNumber);
  348. battle::Target target = ba.getTarget(&battle);
  349. SpellID spellID = ba.spell;
  350. if (!canStackAct(battle, stack))
  351. return false;
  352. std::shared_ptr<const Bonus> randSpellcaster = stack->getBonus(Selector::type()(BonusType::RANDOM_SPELLCASTER));
  353. std::shared_ptr<const Bonus> spellcaster = stack->getBonus(Selector::typeSubtype(BonusType::SPELLCASTER, BonusSubtypeID(spellID)));
  354. if (!spellcaster && !randSpellcaster)
  355. {
  356. gameHandler->complain("That stack can't cast spells!");
  357. return false;
  358. }
  359. if (randSpellcaster)
  360. {
  361. if (target.size() != 1)
  362. {
  363. gameHandler->complain("Invalid target for random spellcaster!");
  364. return false;
  365. }
  366. const battle::Unit * subject = target[0].unitValue;
  367. if (target[0].unitValue == nullptr)
  368. subject = battle.battleGetStackByPos(target[0].hexValue, true);
  369. if (subject == nullptr)
  370. {
  371. gameHandler->complain("Invalid target for random spellcaster!");
  372. return false;
  373. }
  374. spellID = battle.getRandomBeneficialSpell(gameHandler->getRandomGenerator(), stack, subject);
  375. if (spellID == SpellID::NONE)
  376. {
  377. gameHandler->complain("That stack can't cast spells!");
  378. return false;
  379. }
  380. }
  381. const CSpell * spell = SpellID(spellID).toSpell();
  382. spells::BattleCast parameters(&battle, stack, spells::Mode::CREATURE_ACTIVE, spell);
  383. int32_t spellLvl = 0;
  384. if(spellcaster)
  385. vstd::amax(spellLvl, spellcaster->val);
  386. if(randSpellcaster)
  387. vstd::amax(spellLvl, randSpellcaster->val);
  388. parameters.setSpellLevel(spellLvl);
  389. parameters.cast(gameHandler->spellEnv, target);
  390. return true;
  391. }
  392. bool BattleActionProcessor::doHealAction(const CBattleInfoCallback & battle, const BattleAction & ba)
  393. {
  394. const CStack * stack = battle.battleGetStackByID(ba.stackNumber);
  395. battle::Target target = ba.getTarget(&battle);
  396. if (!canStackAct(battle, stack))
  397. return false;
  398. if(target.size() < 1)
  399. {
  400. gameHandler->complain("Destination required for heal action.");
  401. return false;
  402. }
  403. const battle::Unit * destStack = nullptr;
  404. std::shared_ptr<const Bonus> healerAbility = stack->getFirstBonus(Selector::type()(BonusType::HEALER));
  405. if(target.at(0).unitValue)
  406. destStack = target.at(0).unitValue;
  407. else
  408. destStack = battle.battleGetUnitByPos(target.at(0).hexValue);
  409. if(stack == nullptr || destStack == nullptr || !healerAbility || healerAbility->subtype == BonusSubtypeID())
  410. {
  411. gameHandler->complain("There is either no healer, no destination, or healer cannot heal :P");
  412. }
  413. else
  414. {
  415. const CSpell * spell = healerAbility->subtype.as<SpellID>().toSpell();
  416. spells::BattleCast parameters(&battle, stack, spells::Mode::SPELL_LIKE_ATTACK, spell); //We can heal infinitely by first aid tent
  417. auto dest = battle::Destination(destStack, target.at(0).hexValue);
  418. parameters.setSpellLevel(0);
  419. parameters.cast(gameHandler->spellEnv, {dest});
  420. }
  421. return true;
  422. }
  423. bool BattleActionProcessor::canStackAct(const CBattleInfoCallback & battle, const CStack * stack)
  424. {
  425. if (!stack)
  426. {
  427. gameHandler->complain("No such stack!");
  428. return false;
  429. }
  430. if (!stack->alive())
  431. {
  432. gameHandler->complain("This stack is dead: " + stack->nodeName());
  433. return false;
  434. }
  435. if (battle.battleTacticDist())
  436. {
  437. if (stack && stack->unitSide() != battle.battleGetTacticsSide())
  438. {
  439. gameHandler->complain("This is not a stack of side that has tactics!");
  440. return false;
  441. }
  442. }
  443. else
  444. {
  445. if (stack != battle.battleActiveUnit())
  446. {
  447. gameHandler->complain("Action has to be about active stack!");
  448. return false;
  449. }
  450. }
  451. return true;
  452. }
  453. bool BattleActionProcessor::dispatchBattleAction(const CBattleInfoCallback & battle, const BattleAction & ba)
  454. {
  455. switch(ba.actionType)
  456. {
  457. case EActionType::BAD_MORALE:
  458. case EActionType::NO_ACTION:
  459. return doEmptyAction(battle, ba);
  460. case EActionType::END_TACTIC_PHASE:
  461. return doEndTacticsAction(battle, ba);
  462. case EActionType::RETREAT:
  463. return doRetreatAction(battle, ba);
  464. case EActionType::SURRENDER:
  465. return doSurrenderAction(battle, ba);
  466. case EActionType::HERO_SPELL:
  467. return doHeroSpellAction(battle, ba);
  468. case EActionType::WALK:
  469. return doWalkAction(battle, ba);
  470. case EActionType::WAIT:
  471. return doWaitAction(battle, ba);
  472. case EActionType::DEFEND:
  473. return doDefendAction(battle, ba);
  474. case EActionType::WALK_AND_ATTACK:
  475. return doAttackAction(battle, ba);
  476. case EActionType::SHOOT:
  477. return doShootAction(battle, ba);
  478. case EActionType::CATAPULT:
  479. return doCatapultAction(battle, ba);
  480. case EActionType::MONSTER_SPELL:
  481. return doUnitSpellAction(battle, ba);
  482. case EActionType::STACK_HEAL:
  483. return doHealAction(battle, ba);
  484. }
  485. gameHandler->complain("Unrecognized action type received!!");
  486. return false;
  487. }
  488. bool BattleActionProcessor::makeBattleActionImpl(const CBattleInfoCallback & battle, const BattleAction &ba)
  489. {
  490. logGlobal->trace("Making action: %s", ba.toString());
  491. const CStack * stack = battle.battleGetStackByID(ba.stackNumber);
  492. // for these events client does not expects StartAction/EndAction wrapper
  493. if (!ba.isBattleEndAction())
  494. {
  495. StartAction startAction(ba);
  496. startAction.battleID = battle.getBattle()->getBattleID();
  497. gameHandler->sendAndApply(&startAction);
  498. }
  499. bool result = dispatchBattleAction(battle, ba);
  500. if (!ba.isBattleEndAction())
  501. {
  502. EndAction endAction;
  503. endAction.battleID = battle.getBattle()->getBattleID();
  504. gameHandler->sendAndApply(&endAction);
  505. }
  506. if(ba.actionType == EActionType::WAIT || ba.actionType == EActionType::DEFEND || ba.actionType == EActionType::SHOOT || ba.actionType == EActionType::MONSTER_SPELL)
  507. battle.handleObstacleTriggersForUnit(*gameHandler->spellEnv, *stack);
  508. return result;
  509. }
  510. int BattleActionProcessor::moveStack(const CBattleInfoCallback & battle, int stack, BattleHex dest)
  511. {
  512. int ret = 0;
  513. const CStack *curStack = battle.battleGetStackByID(stack);
  514. const CStack *stackAtEnd = battle.battleGetStackByPos(dest);
  515. assert(curStack);
  516. assert(dest < GameConstants::BFIELD_SIZE);
  517. if (battle.battleGetTacticDist())
  518. {
  519. assert(battle.isInTacticRange(dest));
  520. }
  521. auto start = curStack->getPosition();
  522. if (start == dest)
  523. return 0;
  524. //initing necessary tables
  525. auto accessibility = battle.getAccesibility(curStack);
  526. std::set<BattleHex> passed;
  527. //Ignore obstacles on starting position
  528. passed.insert(curStack->getPosition());
  529. if(curStack->doubleWide())
  530. passed.insert(curStack->occupiedHex());
  531. //shifting destination (if we have double wide stack and we can occupy dest but not be exactly there)
  532. if(!stackAtEnd && curStack->doubleWide() && !accessibility.accessible(dest, curStack))
  533. {
  534. BattleHex shifted = dest.cloneInDirection(curStack->destShiftDir(), false);
  535. if(accessibility.accessible(shifted, curStack))
  536. dest = shifted;
  537. }
  538. if((stackAtEnd && stackAtEnd!=curStack && stackAtEnd->alive()) || !accessibility.accessible(dest, curStack))
  539. {
  540. gameHandler->complain("Given destination is not accessible!");
  541. return 0;
  542. }
  543. bool canUseGate = false;
  544. auto dbState = battle.battleGetGateState();
  545. if(battle.battleGetSiegeLevel() > 0 && curStack->unitSide() == BattleSide::DEFENDER &&
  546. dbState != EGateState::DESTROYED &&
  547. dbState != EGateState::BLOCKED)
  548. {
  549. canUseGate = true;
  550. }
  551. std::pair< std::vector<BattleHex>, int > path = battle.getPath(start, dest, curStack);
  552. ret = path.second;
  553. int creSpeed = curStack->getMovementRange(0);
  554. if (battle.battleGetTacticDist() > 0 && creSpeed > 0)
  555. creSpeed = GameConstants::BFIELD_SIZE;
  556. bool hasWideMoat = vstd::contains_if(battle.battleGetAllObstaclesOnPos(BattleHex(BattleHex::GATE_BRIDGE), false), [](const std::shared_ptr<const CObstacleInstance> & obst)
  557. {
  558. return obst->obstacleType == CObstacleInstance::MOAT;
  559. });
  560. auto isGateDrawbridgeHex = [&](BattleHex hex) -> bool
  561. {
  562. if (hasWideMoat && hex == BattleHex::GATE_BRIDGE)
  563. return true;
  564. if (hex == BattleHex::GATE_OUTER)
  565. return true;
  566. if (hex == BattleHex::GATE_INNER)
  567. return true;
  568. return false;
  569. };
  570. auto occupyGateDrawbridgeHex = [&](BattleHex hex) -> bool
  571. {
  572. if (isGateDrawbridgeHex(hex))
  573. return true;
  574. if (curStack->doubleWide())
  575. {
  576. BattleHex otherHex = curStack->occupiedHex(hex);
  577. if (otherHex.isValid() && isGateDrawbridgeHex(otherHex))
  578. return true;
  579. }
  580. return false;
  581. };
  582. if (curStack->hasBonusOfType(BonusType::FLYING))
  583. {
  584. if (path.second <= creSpeed && path.first.size() > 0)
  585. {
  586. if (canUseGate && dbState != EGateState::OPENED &&
  587. occupyGateDrawbridgeHex(dest))
  588. {
  589. BattleUpdateGateState db;
  590. db.battleID = battle.getBattle()->getBattleID();
  591. db.state = EGateState::OPENED;
  592. gameHandler->sendAndApply(&db);
  593. }
  594. //inform clients about move
  595. BattleStackMoved sm;
  596. sm.battleID = battle.getBattle()->getBattleID();
  597. sm.stack = curStack->unitId();
  598. std::vector<BattleHex> tiles;
  599. tiles.push_back(path.first[0]);
  600. sm.tilesToMove = tiles;
  601. sm.distance = path.second;
  602. sm.teleporting = false;
  603. gameHandler->sendAndApply(&sm);
  604. }
  605. }
  606. else //for non-flying creatures
  607. {
  608. std::vector<BattleHex> tiles;
  609. const int tilesToMove = std::max((int)(path.first.size() - creSpeed), 0);
  610. int v = (int)path.first.size()-1;
  611. path.first.push_back(start);
  612. // check if gate need to be open or closed at some point
  613. BattleHex openGateAtHex, gateMayCloseAtHex;
  614. if (canUseGate)
  615. {
  616. for (int i = (int)path.first.size()-1; i >= 0; i--)
  617. {
  618. auto needOpenGates = [&](BattleHex hex) -> bool
  619. {
  620. if (hasWideMoat && hex == BattleHex::GATE_BRIDGE)
  621. return true;
  622. if (hex == BattleHex::GATE_BRIDGE && i-1 >= 0 && path.first[i-1] == BattleHex::GATE_OUTER)
  623. return true;
  624. else if (hex == BattleHex::GATE_OUTER || hex == BattleHex::GATE_INNER)
  625. return true;
  626. return false;
  627. };
  628. auto hex = path.first[i];
  629. if (!openGateAtHex.isValid() && dbState != EGateState::OPENED)
  630. {
  631. if (needOpenGates(hex))
  632. openGateAtHex = path.first[i+1];
  633. //TODO we need find batter way to handle double-wide stacks
  634. //currently if only second occupied stack part is standing on gate / bridge hex then stack will start to wait for bridge to lower before it's needed. Though this is just a visual bug.
  635. if (curStack->doubleWide())
  636. {
  637. BattleHex otherHex = curStack->occupiedHex(hex);
  638. if (otherHex.isValid() && needOpenGates(otherHex))
  639. openGateAtHex = path.first[i+2];
  640. }
  641. //gate may be opened and then closed during stack movement, but not other way around
  642. if (openGateAtHex.isValid())
  643. dbState = EGateState::OPENED;
  644. }
  645. if (!gateMayCloseAtHex.isValid() && dbState != EGateState::CLOSED)
  646. {
  647. if (hex == BattleHex::GATE_INNER && i-1 >= 0 && path.first[i-1] != BattleHex::GATE_OUTER)
  648. {
  649. gateMayCloseAtHex = path.first[i-1];
  650. }
  651. if (hasWideMoat)
  652. {
  653. if (hex == BattleHex::GATE_BRIDGE && i-1 >= 0 && path.first[i-1] != BattleHex::GATE_OUTER)
  654. {
  655. gateMayCloseAtHex = path.first[i-1];
  656. }
  657. else if (hex == BattleHex::GATE_OUTER && i-1 >= 0 &&
  658. path.first[i-1] != BattleHex::GATE_INNER &&
  659. path.first[i-1] != BattleHex::GATE_BRIDGE)
  660. {
  661. gateMayCloseAtHex = path.first[i-1];
  662. }
  663. }
  664. else if (hex == BattleHex::GATE_OUTER && i-1 >= 0 && path.first[i-1] != BattleHex::GATE_INNER)
  665. {
  666. gateMayCloseAtHex = path.first[i-1];
  667. }
  668. }
  669. }
  670. }
  671. bool stackIsMoving = true;
  672. while(stackIsMoving)
  673. {
  674. if (v<tilesToMove)
  675. {
  676. logGlobal->error("Movement terminated abnormally");
  677. break;
  678. }
  679. bool gateStateChanging = false;
  680. //special handling for opening gate on from starting hex
  681. if (openGateAtHex.isValid() && openGateAtHex == start)
  682. gateStateChanging = true;
  683. else
  684. {
  685. for (bool obstacleHit = false; (!obstacleHit) && (!gateStateChanging) && (v >= tilesToMove); --v)
  686. {
  687. BattleHex hex = path.first[v];
  688. tiles.push_back(hex);
  689. if ((openGateAtHex.isValid() && openGateAtHex == hex) ||
  690. (gateMayCloseAtHex.isValid() && gateMayCloseAtHex == hex))
  691. {
  692. gateStateChanging = true;
  693. }
  694. //if we walked onto something, finalize this portion of stack movement check into obstacle
  695. if(!battle.battleGetAllObstaclesOnPos(hex, false).empty())
  696. obstacleHit = true;
  697. if (curStack->doubleWide())
  698. {
  699. BattleHex otherHex = curStack->occupiedHex(hex);
  700. //two hex creature hit obstacle by backside
  701. auto obstacle2 = battle.battleGetAllObstaclesOnPos(otherHex, false);
  702. if(otherHex.isValid() && !obstacle2.empty())
  703. obstacleHit = true;
  704. }
  705. if(!obstacleHit)
  706. passed.insert(hex);
  707. }
  708. }
  709. if (!tiles.empty())
  710. {
  711. //commit movement
  712. BattleStackMoved sm;
  713. sm.battleID = battle.getBattle()->getBattleID();
  714. sm.stack = curStack->unitId();
  715. sm.distance = path.second;
  716. sm.teleporting = false;
  717. sm.tilesToMove = tiles;
  718. gameHandler->sendAndApply(&sm);
  719. tiles.clear();
  720. }
  721. //we don't handle obstacle at the destination tile -> it's handled separately in the if at the end
  722. if (curStack->getPosition() != dest)
  723. {
  724. if(stackIsMoving && start != curStack->getPosition())
  725. {
  726. stackIsMoving = battle.handleObstacleTriggersForUnit(*gameHandler->spellEnv, *curStack, passed);
  727. passed.insert(curStack->getPosition());
  728. if(curStack->doubleWide())
  729. passed.insert(curStack->occupiedHex());
  730. }
  731. if (gateStateChanging)
  732. {
  733. if (curStack->getPosition() == openGateAtHex)
  734. {
  735. openGateAtHex = BattleHex();
  736. //only open gate if stack is still alive
  737. if (curStack->alive())
  738. {
  739. BattleUpdateGateState db;
  740. db.battleID = battle.getBattle()->getBattleID();
  741. db.state = EGateState::OPENED;
  742. gameHandler->sendAndApply(&db);
  743. }
  744. }
  745. else if (curStack->getPosition() == gateMayCloseAtHex)
  746. {
  747. gateMayCloseAtHex = BattleHex();
  748. owner->updateGateState(battle);
  749. }
  750. }
  751. }
  752. else
  753. //movement finished normally: we reached destination
  754. stackIsMoving = false;
  755. }
  756. }
  757. //handle last hex separately for deviation
  758. if (VLC->settings()->getBoolean(EGameSettings::COMBAT_ONE_HEX_TRIGGERS_OBSTACLES))
  759. {
  760. if (dest == battle::Unit::occupiedHex(start, curStack->doubleWide(), curStack->unitSide())
  761. || start == battle::Unit::occupiedHex(dest, curStack->doubleWide(), curStack->unitSide()))
  762. passed.clear(); //Just empty passed, obstacles will handled automatically
  763. }
  764. if(dest == start) //If dest is equal to start, then we should handle obstacles for it anyway
  765. passed.clear(); //Just empty passed, obstacles will handled automatically
  766. //handling obstacle on the final field (separate, because it affects both flying and walking stacks)
  767. battle.handleObstacleTriggersForUnit(*gameHandler->spellEnv, *curStack, passed);
  768. return ret;
  769. }
  770. void BattleActionProcessor::makeAttack(const CBattleInfoCallback & battle, const CStack * attacker, const CStack * defender, int distance, BattleHex targetHex, bool first, bool ranged, bool counter)
  771. {
  772. if(first && !counter)
  773. handleAttackBeforeCasting(battle, ranged, attacker, defender);
  774. FireShieldInfo fireShield;
  775. BattleAttack bat;
  776. BattleLogMessage blm;
  777. blm.battleID = battle.getBattle()->getBattleID();
  778. bat.battleID = battle.getBattle()->getBattleID();
  779. bat.attackerChanges.battleID = battle.getBattle()->getBattleID();
  780. bat.stackAttacking = attacker->unitId();
  781. bat.tile = targetHex;
  782. std::shared_ptr<battle::CUnitState> attackerState = attacker->acquireState();
  783. if(ranged)
  784. bat.flags |= BattleAttack::SHOT;
  785. if(counter)
  786. bat.flags |= BattleAttack::COUNTER;
  787. const int attackerLuck = attacker->luckVal();
  788. if(attackerLuck > 0)
  789. {
  790. auto diceSize = VLC->settings()->getVector(EGameSettings::COMBAT_GOOD_LUCK_DICE);
  791. size_t diceIndex = std::min<size_t>(diceSize.size(), attackerLuck) - 1; // array index, so 0-indexed
  792. if(diceSize.size() > 0 && gameHandler->getRandomGenerator().nextInt(1, diceSize[diceIndex]) == 1)
  793. bat.flags |= BattleAttack::LUCKY;
  794. }
  795. if(attackerLuck < 0)
  796. {
  797. auto diceSize = VLC->settings()->getVector(EGameSettings::COMBAT_BAD_LUCK_DICE);
  798. size_t diceIndex = std::min<size_t>(diceSize.size(), -attackerLuck) - 1; // array index, so 0-indexed
  799. if(diceSize.size() > 0 && gameHandler->getRandomGenerator().nextInt(1, diceSize[diceIndex]) == 1)
  800. bat.flags |= BattleAttack::UNLUCKY;
  801. }
  802. if (gameHandler->getRandomGenerator().nextInt(99) < attacker->valOfBonuses(BonusType::DOUBLE_DAMAGE_CHANCE))
  803. {
  804. bat.flags |= BattleAttack::DEATH_BLOW;
  805. }
  806. const auto * owner = battle.battleGetFightingHero(attacker->unitSide());
  807. if(owner)
  808. {
  809. int chance = owner->valOfBonuses(BonusType::BONUS_DAMAGE_CHANCE, BonusSubtypeID(attacker->creatureId()));
  810. if (chance > gameHandler->getRandomGenerator().nextInt(99))
  811. bat.flags |= BattleAttack::BALLISTA_DOUBLE_DMG;
  812. }
  813. int64_t drainedLife = 0;
  814. // only primary target
  815. if(defender->alive())
  816. drainedLife += applyBattleEffects(battle, bat, attackerState, fireShield, defender, distance, false);
  817. //multiple-hex normal attack
  818. std::set<const CStack*> attackedCreatures = battle.getAttackedCreatures(attacker, targetHex, bat.shot()); //creatures other than primary target
  819. for(const CStack * stack : attackedCreatures)
  820. {
  821. if(stack != defender && stack->alive()) //do not hit same stack twice
  822. drainedLife += applyBattleEffects(battle, bat, attackerState, fireShield, stack, distance, true);
  823. }
  824. std::shared_ptr<const Bonus> bonus = attacker->getFirstBonus(Selector::type()(BonusType::SPELL_LIKE_ATTACK));
  825. if(bonus && ranged) //TODO: make it work in melee?
  826. {
  827. //this is need for displaying hit animation
  828. bat.flags |= BattleAttack::SPELL_LIKE;
  829. bat.spellID = bonus->subtype.as<SpellID>();
  830. //TODO: should spell override creature`s projectile?
  831. auto spell = bat.spellID.toSpell();
  832. battle::Target target;
  833. target.emplace_back(defender, targetHex);
  834. spells::BattleCast event(&battle, attacker, spells::Mode::SPELL_LIKE_ATTACK, spell);
  835. event.setSpellLevel(bonus->val);
  836. auto attackedCreatures = spell->battleMechanics(&event)->getAffectedStacks(target);
  837. //TODO: get exact attacked hex for defender
  838. for(const CStack * stack : attackedCreatures)
  839. {
  840. if(stack != defender && stack->alive()) //do not hit same stack twice
  841. {
  842. drainedLife += applyBattleEffects(battle, bat, attackerState, fireShield, stack, distance, true);
  843. }
  844. }
  845. //now add effect info for all attacked stacks
  846. for (BattleStackAttacked & bsa : bat.bsa)
  847. {
  848. if (bsa.attackerID == attacker->unitId()) //this is our attack and not f.e. fire shield
  849. {
  850. //this is need for displaying affect animation
  851. bsa.flags |= BattleStackAttacked::SPELL_EFFECT;
  852. bsa.spellID = bonus->subtype.as<SpellID>();
  853. }
  854. }
  855. }
  856. attackerState->afterAttack(ranged, counter);
  857. {
  858. UnitChanges info(attackerState->unitId(), UnitChanges::EOperation::RESET_STATE);
  859. attackerState->save(info.data);
  860. bat.attackerChanges.changedStacks.push_back(info);
  861. }
  862. if (drainedLife > 0)
  863. bat.flags |= BattleAttack::LIFE_DRAIN;
  864. for (BattleStackAttacked & bsa : bat.bsa)
  865. bsa.battleID = battle.getBattle()->getBattleID();
  866. gameHandler->sendAndApply(&bat);
  867. {
  868. const bool multipleTargets = bat.bsa.size() > 1;
  869. int64_t totalDamage = 0;
  870. int32_t totalKills = 0;
  871. for(const BattleStackAttacked & bsa : bat.bsa)
  872. {
  873. totalDamage += bsa.damageAmount;
  874. totalKills += bsa.killedAmount;
  875. }
  876. {
  877. MetaString text;
  878. attacker->addText(text, EMetaText::GENERAL_TXT, 376);
  879. attacker->addNameReplacement(text);
  880. text.replaceNumber(totalDamage);
  881. blm.lines.push_back(text);
  882. }
  883. addGenericKilledLog(blm, defender, totalKills, multipleTargets);
  884. }
  885. // drain life effect (as well as log entry) must be applied after the attack
  886. if(drainedLife > 0)
  887. {
  888. MetaString text;
  889. attackerState->addText(text, EMetaText::GENERAL_TXT, 361);
  890. attackerState->addNameReplacement(text, false);
  891. text.replaceNumber(drainedLife);
  892. defender->addNameReplacement(text, true);
  893. blm.lines.push_back(std::move(text));
  894. }
  895. if(!fireShield.empty())
  896. {
  897. //todo: this should be "virtual" spell instead, we only need fire spell school bonus here
  898. const CSpell * fireShieldSpell = SpellID(SpellID::FIRE_SHIELD).toSpell();
  899. int64_t totalDamage = 0;
  900. for(const auto & item : fireShield)
  901. {
  902. const CStack * actor = item.first;
  903. int64_t rawDamage = item.second;
  904. const CGHeroInstance * actorOwner = battle.battleGetFightingHero(actor->unitSide());
  905. if(actorOwner)
  906. {
  907. rawDamage = fireShieldSpell->adjustRawDamage(actorOwner, attacker, rawDamage);
  908. }
  909. else
  910. {
  911. rawDamage = fireShieldSpell->adjustRawDamage(actor, attacker, rawDamage);
  912. }
  913. totalDamage+=rawDamage;
  914. //FIXME: add custom effect on actor
  915. }
  916. if (totalDamage > 0)
  917. {
  918. BattleStackAttacked bsa;
  919. bsa.battleID = battle.getBattle()->getBattleID();
  920. bsa.flags |= BattleStackAttacked::FIRE_SHIELD;
  921. bsa.stackAttacked = attacker->unitId(); //invert
  922. bsa.attackerID = defender->unitId();
  923. bsa.damageAmount = totalDamage;
  924. attacker->prepareAttacked(bsa, gameHandler->getRandomGenerator());
  925. StacksInjured pack;
  926. pack.battleID = battle.getBattle()->getBattleID();
  927. pack.stacks.push_back(bsa);
  928. gameHandler->sendAndApply(&pack);
  929. // TODO: this is already implemented in Damage::describeEffect()
  930. {
  931. MetaString text;
  932. text.appendLocalString(EMetaText::GENERAL_TXT, 376);
  933. text.replaceName(SpellID(SpellID::FIRE_SHIELD));
  934. text.replaceNumber(totalDamage);
  935. blm.lines.push_back(std::move(text));
  936. }
  937. addGenericKilledLog(blm, attacker, bsa.killedAmount, false);
  938. }
  939. }
  940. gameHandler->sendAndApply(&blm);
  941. handleAfterAttackCasting(battle, ranged, attacker, defender);
  942. }
  943. void BattleActionProcessor::attackCasting(const CBattleInfoCallback & battle, bool ranged, BonusType attackMode, const battle::Unit * attacker, const CStack * defender)
  944. {
  945. if(attacker->hasBonusOfType(attackMode))
  946. {
  947. TConstBonusListPtr spells = attacker->getBonuses(Selector::type()(attackMode));
  948. std::set<SpellID> spellsToCast = getSpellsForAttackCasting(spells, defender);
  949. for(SpellID spellID : spellsToCast)
  950. {
  951. bool castMe = false;
  952. if(!defender->alive())
  953. {
  954. logGlobal->debug("attackCasting: all attacked creatures have been killed");
  955. return;
  956. }
  957. int32_t spellLevel = 0;
  958. TConstBonusListPtr spellsByType = attacker->getBonuses(Selector::typeSubtype(attackMode, BonusSubtypeID(spellID)));
  959. for(const auto & sf : *spellsByType)
  960. {
  961. int meleeRanged;
  962. vstd::amax(spellLevel, sf->additionalInfo[0]);
  963. meleeRanged = sf->additionalInfo[1];
  964. if (meleeRanged == CAddInfo::NONE || meleeRanged == 0 || (meleeRanged == 1 && ranged) || (meleeRanged == 2 && !ranged))
  965. castMe = true;
  966. }
  967. int chance = attacker->valOfBonuses((Selector::typeSubtype(attackMode, BonusSubtypeID(spellID))));
  968. vstd::amin(chance, 100);
  969. const CSpell * spell = SpellID(spellID).toSpell();
  970. spells::AbilityCaster caster(attacker, spellLevel);
  971. spells::Target target;
  972. target.emplace_back(defender);
  973. spells::BattleCast parameters(&battle, &caster, spells::Mode::PASSIVE, spell);
  974. auto m = spell->battleMechanics(&parameters);
  975. spells::detail::ProblemImpl ignored;
  976. if(!m->canBeCastAt(target, ignored))
  977. continue;
  978. //check if spell should be cast (probability handling)
  979. if(gameHandler->getRandomGenerator().nextInt(99) >= chance)
  980. continue;
  981. //casting
  982. if(castMe)
  983. {
  984. parameters.cast(gameHandler->spellEnv, target);
  985. }
  986. }
  987. }
  988. }
  989. std::set<SpellID> BattleActionProcessor::getSpellsForAttackCasting(TConstBonusListPtr spells, const CStack *defender)
  990. {
  991. std::set<SpellID> spellsToCast;
  992. constexpr int unlayeredItemsInternalLayer = -1;
  993. std::map<int, std::vector<std::shared_ptr<Bonus>>> spellsWithBackupLayers;
  994. for(int i = 0; i < spells->size(); i++)
  995. {
  996. std::shared_ptr<Bonus> bonus = spells->operator[](i);
  997. int layer = bonus->additionalInfo[2];
  998. vstd::amax(layer, -1);
  999. spellsWithBackupLayers[layer].push_back(bonus);
  1000. }
  1001. auto addSpellsFromLayer = [&](int layer) -> void
  1002. {
  1003. assert(spellsWithBackupLayers.find(layer) != spellsWithBackupLayers.end());
  1004. for(const auto & spell : spellsWithBackupLayers[layer])
  1005. {
  1006. if (spell->subtype.as<SpellID>() != SpellID())
  1007. spellsToCast.insert(spell->subtype.as<SpellID>());
  1008. else
  1009. logGlobal->error("Invalid spell to cast during attack!");
  1010. }
  1011. };
  1012. if(spellsWithBackupLayers.find(unlayeredItemsInternalLayer) != spellsWithBackupLayers.end())
  1013. {
  1014. addSpellsFromLayer(unlayeredItemsInternalLayer);
  1015. spellsWithBackupLayers.erase(unlayeredItemsInternalLayer);
  1016. }
  1017. for(auto item : spellsWithBackupLayers)
  1018. {
  1019. bool areCurrentLayerSpellsApplied = std::all_of(item.second.begin(), item.second.end(),
  1020. [&](const std::shared_ptr<Bonus> spell)
  1021. {
  1022. std::vector<SpellID> activeSpells = defender->activeSpells();
  1023. return vstd::find(activeSpells, spell->subtype.as<SpellID>()) != activeSpells.end();
  1024. });
  1025. if(!areCurrentLayerSpellsApplied || item.first == spellsWithBackupLayers.rbegin()->first)
  1026. {
  1027. addSpellsFromLayer(item.first);
  1028. break;
  1029. }
  1030. }
  1031. return spellsToCast;
  1032. }
  1033. void BattleActionProcessor::handleAttackBeforeCasting(const CBattleInfoCallback & battle, bool ranged, const CStack * attacker, const CStack * defender)
  1034. {
  1035. attackCasting(battle, ranged, BonusType::SPELL_BEFORE_ATTACK, attacker, defender); //no death stare / acid breath needed?
  1036. }
  1037. void BattleActionProcessor::handleDeathStare(const CBattleInfoCallback & battle, bool ranged, const CStack * attacker, const CStack * defender)
  1038. {
  1039. // mechanics of Death Stare as in H3:
  1040. // each gorgon have 10% chance to kill (counted separately in H3) -> binomial distribution
  1041. //original formula x = min(x, (gorgons_count + 9)/10);
  1042. /* mechanics of Accurate Shot as in HotA:
  1043. * each creature in an attacking stack has a X% chance of killing a creature in the attacked squad,
  1044. * but the total number of killed creatures cannot be more than (number of creatures in an attacking squad) * X/100 (rounded up).
  1045. * X = 3 multiplier for shooting without penalty and X = 2 if shooting with penalty. Ability doesn't work if shooting at creatures behind walls.
  1046. */
  1047. auto subtype = BonusCustomSubtype::deathStareGorgon;
  1048. if (ranged)
  1049. {
  1050. bool rangePenalty = battle.battleHasDistancePenalty(attacker, attacker->getPosition(), defender->getPosition());
  1051. bool obstaclePenalty = battle.battleHasWallPenalty(attacker, attacker->getPosition(), defender->getPosition());
  1052. if(rangePenalty)
  1053. {
  1054. if(obstaclePenalty)
  1055. subtype = BonusCustomSubtype::deathStareRangeObstaclePenalty;
  1056. else
  1057. subtype = BonusCustomSubtype::deathStareRangePenalty;
  1058. }
  1059. else
  1060. {
  1061. if(obstaclePenalty)
  1062. subtype = BonusCustomSubtype::deathStareObstaclePenalty;
  1063. else
  1064. subtype = BonusCustomSubtype::deathStareNoRangePenalty;
  1065. }
  1066. }
  1067. int singleCreatureKillChancePercent = attacker->valOfBonuses(BonusType::DEATH_STARE, subtype);
  1068. double chanceToKill = singleCreatureKillChancePercent / 100.0;
  1069. vstd::amin(chanceToKill, 1); //cap at 100%
  1070. std::binomial_distribution<> distribution(attacker->getCount(), chanceToKill);
  1071. int killedCreatures = distribution(gameHandler->getRandomGenerator().getStdGenerator());
  1072. int maxToKill = (attacker->getCount() * singleCreatureKillChancePercent + 99) / 100;
  1073. vstd::amin(killedCreatures, maxToKill);
  1074. killedCreatures += (attacker->level() * attacker->valOfBonuses(BonusType::DEATH_STARE, BonusCustomSubtype::deathStareCommander)) / defender->level();
  1075. if(killedCreatures)
  1076. {
  1077. //TODO: death stare or accurate shot was not originally available for multiple-hex attacks, but...
  1078. SpellID spellID = SpellID(SpellID::DEATH_STARE); //also used as fallback spell for ACCURATE_SHOT
  1079. auto bonus = attacker->getBonus(Selector::typeSubtype(BonusType::DEATH_STARE, subtype));
  1080. if(bonus && bonus->additionalInfo[0] != SpellID::NONE)
  1081. spellID = SpellID(bonus->additionalInfo[0]);
  1082. const CSpell * spell = spellID.toSpell();
  1083. spells::AbilityCaster caster(attacker, 0);
  1084. spells::BattleCast parameters(&battle, &caster, spells::Mode::PASSIVE, spell);
  1085. spells::Target target;
  1086. target.emplace_back(defender);
  1087. parameters.setEffectValue(killedCreatures);
  1088. parameters.cast(gameHandler->spellEnv, target);
  1089. }
  1090. }
  1091. void BattleActionProcessor::handleAfterAttackCasting(const CBattleInfoCallback & battle, bool ranged, const CStack * attacker, const CStack * defender)
  1092. {
  1093. if(!attacker->alive() || !defender->alive()) // can be already dead
  1094. return;
  1095. attackCasting(battle, ranged, BonusType::SPELL_AFTER_ATTACK, attacker, defender);
  1096. if(!defender->alive())
  1097. {
  1098. //don't try death stare or acid breath on dead stack (crash!)
  1099. return;
  1100. }
  1101. if(attacker->hasBonusOfType(BonusType::DEATH_STARE))
  1102. handleDeathStare(battle, ranged, attacker, defender);
  1103. if(!defender->alive())
  1104. return;
  1105. int64_t acidDamage = 0;
  1106. TConstBonusListPtr acidBreath = attacker->getBonuses(Selector::type()(BonusType::ACID_BREATH));
  1107. for(const auto & b : *acidBreath)
  1108. {
  1109. if(b->additionalInfo[0] > gameHandler->getRandomGenerator().nextInt(99))
  1110. acidDamage += b->val;
  1111. }
  1112. if(acidDamage > 0)
  1113. {
  1114. const CSpell * spell = SpellID(SpellID::ACID_BREATH_DAMAGE).toSpell();
  1115. spells::AbilityCaster caster(attacker, 0);
  1116. spells::BattleCast parameters(&battle, &caster, spells::Mode::PASSIVE, spell);
  1117. spells::Target target;
  1118. target.emplace_back(defender);
  1119. parameters.setEffectValue(acidDamage * attacker->getCount());
  1120. parameters.cast(gameHandler->spellEnv, target);
  1121. }
  1122. if(!defender->alive())
  1123. return;
  1124. if(attacker->hasBonusOfType(BonusType::TRANSMUTATION) && defender->isLiving()) //transmutation mechanics, similar to WoG werewolf ability
  1125. {
  1126. double chanceToTrigger = attacker->valOfBonuses(BonusType::TRANSMUTATION) / 100.0f;
  1127. vstd::amin(chanceToTrigger, 1); //cap at 100%
  1128. if(gameHandler->getRandomGenerator().getDoubleRange(0, 1)() > chanceToTrigger)
  1129. return;
  1130. int bonusAdditionalInfo = attacker->getBonus(Selector::type()(BonusType::TRANSMUTATION))->additionalInfo[0];
  1131. if(defender->unitType()->getIndex() == bonusAdditionalInfo ||
  1132. (bonusAdditionalInfo == CAddInfo::NONE && defender->unitType()->getId() == attacker->unitType()->getId()))
  1133. return;
  1134. battle::UnitInfo resurrectInfo;
  1135. resurrectInfo.id = battle.battleNextUnitId();
  1136. resurrectInfo.summoned = false;
  1137. resurrectInfo.position = defender->getPosition();
  1138. resurrectInfo.side = defender->unitSide();
  1139. if(bonusAdditionalInfo != CAddInfo::NONE)
  1140. resurrectInfo.type = CreatureID(bonusAdditionalInfo);
  1141. else
  1142. resurrectInfo.type = attacker->creatureId();
  1143. if(attacker->hasBonusOfType((BonusType::TRANSMUTATION), BonusCustomSubtype::transmutationPerHealth))
  1144. resurrectInfo.count = std::max((defender->getCount() * defender->getMaxHealth()) / resurrectInfo.type.toCreature()->getMaxHealth(), 1u);
  1145. else if (attacker->hasBonusOfType((BonusType::TRANSMUTATION), BonusCustomSubtype::transmutationPerUnit))
  1146. resurrectInfo.count = defender->getCount();
  1147. else
  1148. return; //wrong subtype
  1149. BattleUnitsChanged addUnits;
  1150. addUnits.battleID = battle.getBattle()->getBattleID();
  1151. addUnits.changedStacks.emplace_back(resurrectInfo.id, UnitChanges::EOperation::ADD);
  1152. resurrectInfo.save(addUnits.changedStacks.back().data);
  1153. BattleUnitsChanged removeUnits;
  1154. removeUnits.battleID = battle.getBattle()->getBattleID();
  1155. removeUnits.changedStacks.emplace_back(defender->unitId(), UnitChanges::EOperation::REMOVE);
  1156. gameHandler->sendAndApply(&removeUnits);
  1157. gameHandler->sendAndApply(&addUnits);
  1158. // send empty event to client
  1159. // temporary(?) workaround to force animations to trigger
  1160. StacksInjured fakeEvent;
  1161. fakeEvent.battleID = battle.getBattle()->getBattleID();
  1162. gameHandler->sendAndApply(&fakeEvent);
  1163. }
  1164. if(attacker->hasBonusOfType(BonusType::DESTRUCTION, BonusCustomSubtype::destructionKillPercentage) || attacker->hasBonusOfType(BonusType::DESTRUCTION, BonusCustomSubtype::destructionKillAmount))
  1165. {
  1166. double chanceToTrigger = 0;
  1167. int amountToDie = 0;
  1168. if(attacker->hasBonusOfType(BonusType::DESTRUCTION, BonusCustomSubtype::destructionKillPercentage)) //killing by percentage
  1169. {
  1170. chanceToTrigger = attacker->valOfBonuses(BonusType::DESTRUCTION, BonusCustomSubtype::destructionKillPercentage) / 100.0f;
  1171. int percentageToDie = attacker->getBonus(Selector::type()(BonusType::DESTRUCTION).And(Selector::subtype()(BonusCustomSubtype::destructionKillPercentage)))->additionalInfo[0];
  1172. amountToDie = static_cast<int>(defender->getCount() * percentageToDie * 0.01f);
  1173. }
  1174. else if(attacker->hasBonusOfType(BonusType::DESTRUCTION, BonusCustomSubtype::destructionKillAmount)) //killing by count
  1175. {
  1176. chanceToTrigger = attacker->valOfBonuses(BonusType::DESTRUCTION, BonusCustomSubtype::destructionKillAmount) / 100.0f;
  1177. amountToDie = attacker->getBonus(Selector::type()(BonusType::DESTRUCTION).And(Selector::subtype()(BonusCustomSubtype::destructionKillAmount)))->additionalInfo[0];
  1178. }
  1179. vstd::amin(chanceToTrigger, 1); //cap trigger chance at 100%
  1180. if(gameHandler->getRandomGenerator().getDoubleRange(0, 1)() > chanceToTrigger)
  1181. return;
  1182. BattleStackAttacked bsa;
  1183. bsa.attackerID = -1;
  1184. bsa.stackAttacked = defender->unitId();
  1185. bsa.damageAmount = amountToDie * defender->getMaxHealth();
  1186. bsa.flags = BattleStackAttacked::SPELL_EFFECT;
  1187. bsa.spellID = SpellID::SLAYER;
  1188. defender->prepareAttacked(bsa, gameHandler->getRandomGenerator());
  1189. StacksInjured si;
  1190. si.battleID = battle.getBattle()->getBattleID();
  1191. si.stacks.push_back(bsa);
  1192. gameHandler->sendAndApply(&si);
  1193. sendGenericKilledLog(battle, defender, bsa.killedAmount, false);
  1194. }
  1195. }
  1196. int64_t BattleActionProcessor::applyBattleEffects(const CBattleInfoCallback & battle, BattleAttack & bat, std::shared_ptr<battle::CUnitState> attackerState, FireShieldInfo & fireShield, const CStack * def, int distance, bool secondary)
  1197. {
  1198. BattleStackAttacked bsa;
  1199. if(secondary)
  1200. bsa.flags |= BattleStackAttacked::SECONDARY; //all other targets do not suffer from spells & spell-like abilities
  1201. bsa.attackerID = attackerState->unitId();
  1202. bsa.stackAttacked = def->unitId();
  1203. {
  1204. BattleAttackInfo bai(attackerState.get(), def, distance, bat.shot());
  1205. bai.deathBlow = bat.deathBlow();
  1206. bai.doubleDamage = bat.ballistaDoubleDmg();
  1207. bai.luckyStrike = bat.lucky();
  1208. bai.unluckyStrike = bat.unlucky();
  1209. auto range = battle.calculateDmgRange(bai);
  1210. bsa.damageAmount = battle.getBattle()->getActualDamage(range.damage, attackerState->getCount(), gameHandler->getRandomGenerator());
  1211. CStack::prepareAttacked(bsa, gameHandler->getRandomGenerator(), bai.defender->acquireState()); //calculate casualties
  1212. }
  1213. int64_t drainedLife = 0;
  1214. //life drain handling
  1215. if(attackerState->hasBonusOfType(BonusType::LIFE_DRAIN) && def->isLiving())
  1216. {
  1217. int64_t toHeal = bsa.damageAmount * attackerState->valOfBonuses(BonusType::LIFE_DRAIN) / 100;
  1218. attackerState->heal(toHeal, EHealLevel::RESURRECT, EHealPower::PERMANENT);
  1219. drainedLife += toHeal;
  1220. }
  1221. //soul steal handling
  1222. if(attackerState->hasBonusOfType(BonusType::SOUL_STEAL) && def->isLiving())
  1223. {
  1224. //we can have two bonuses - one with subtype 0 and another with subtype 1
  1225. //try to use permanent first, use only one of two
  1226. for(const auto & subtype : { BonusCustomSubtype::soulStealBattle, BonusCustomSubtype::soulStealPermanent})
  1227. {
  1228. if(attackerState->hasBonusOfType(BonusType::SOUL_STEAL, subtype))
  1229. {
  1230. int64_t toHeal = bsa.killedAmount * attackerState->valOfBonuses(BonusType::SOUL_STEAL, subtype) * attackerState->getMaxHealth();
  1231. bool permanent = subtype == BonusCustomSubtype::soulStealPermanent;
  1232. attackerState->heal(toHeal, EHealLevel::OVERHEAL, (permanent ? EHealPower::PERMANENT : EHealPower::ONE_BATTLE));
  1233. drainedLife += toHeal;
  1234. break;
  1235. }
  1236. }
  1237. }
  1238. bat.bsa.push_back(bsa); //add this stack to the list of victims after drain life has been calculated
  1239. //fire shield handling
  1240. if(!bat.shot() &&
  1241. !def->isClone() &&
  1242. def->hasBonusOfType(BonusType::FIRE_SHIELD) &&
  1243. !attackerState->hasBonusOfType(BonusType::SPELL_SCHOOL_IMMUNITY, BonusSubtypeID(SpellSchool::FIRE)) &&
  1244. !attackerState->hasBonusOfType(BonusType::NEGATIVE_EFFECTS_IMMUNITY, BonusSubtypeID(SpellSchool::FIRE)) &&
  1245. attackerState->valOfBonuses(BonusType::SPELL_DAMAGE_REDUCTION, BonusSubtypeID(SpellSchool::FIRE)) < 100 &&
  1246. CStack::isMeleeAttackPossible(attackerState.get(), def) // attacked needs to be adjacent to defender for fire shield to trigger (e.g. Dragon Breath attack)
  1247. )
  1248. {
  1249. //TODO: use damage with bonus but without penalties
  1250. auto fireShieldDamage = (std::min<int64_t>(def->getAvailableHealth(), bsa.damageAmount) * def->valOfBonuses(BonusType::FIRE_SHIELD)) / 100;
  1251. fireShield.push_back(std::make_pair(def, fireShieldDamage));
  1252. }
  1253. return drainedLife;
  1254. }
  1255. void BattleActionProcessor::sendGenericKilledLog(const CBattleInfoCallback & battle, const CStack * defender, int32_t killed, bool multiple)
  1256. {
  1257. if(killed > 0)
  1258. {
  1259. BattleLogMessage blm;
  1260. blm.battleID = battle.getBattle()->getBattleID();
  1261. addGenericKilledLog(blm, defender, killed, multiple);
  1262. gameHandler->sendAndApply(&blm);
  1263. }
  1264. }
  1265. void BattleActionProcessor::addGenericKilledLog(BattleLogMessage & blm, const CStack * defender, int32_t killed, bool multiple)
  1266. {
  1267. if(killed > 0)
  1268. {
  1269. MetaString line;
  1270. if (killed > 1)
  1271. {
  1272. line.appendTextID("core.genrltxt.379"); // %d %s perished
  1273. line.replaceNumber(killed);
  1274. }
  1275. else
  1276. line.appendTextID("core.genrltxt.378"); // One %s perishes
  1277. if (multiple)
  1278. {
  1279. if (killed > 1)
  1280. line.replaceTextID("core.genrltxt.43"); // creatures
  1281. else
  1282. line.replaceTextID("core.genrltxt.42"); // creature
  1283. }
  1284. else
  1285. line.replaceName(defender->unitType()->getId(), killed);
  1286. blm.lines.push_back(line);
  1287. }
  1288. }
  1289. bool BattleActionProcessor::makeAutomaticBattleAction(const CBattleInfoCallback & battle, const BattleAction & ba)
  1290. {
  1291. return makeBattleActionImpl(battle, ba);
  1292. }
  1293. bool BattleActionProcessor::makePlayerBattleAction(const CBattleInfoCallback & battle, PlayerColor player, const BattleAction &ba)
  1294. {
  1295. if (ba.side != 0 && ba.side != 1 && gameHandler->complain("Can not make action - invalid battle side!"))
  1296. return false;
  1297. if(battle.battleGetTacticDist() != 0)
  1298. {
  1299. if(!ba.isTacticsAction())
  1300. {
  1301. gameHandler->complain("Can not make actions while in tactics mode!");
  1302. return false;
  1303. }
  1304. if(player != battle.sideToPlayer(ba.side))
  1305. {
  1306. gameHandler->complain("Can not make actions in battles you are not part of!");
  1307. return false;
  1308. }
  1309. }
  1310. else
  1311. {
  1312. auto active = battle.battleActiveUnit();
  1313. if(!active)
  1314. {
  1315. gameHandler->complain("No active unit in battle!");
  1316. return false;
  1317. }
  1318. if (ba.isUnitAction() && ba.stackNumber != active->unitId())
  1319. {
  1320. gameHandler->complain("Can not make actions - stack is not active!");
  1321. return false;
  1322. }
  1323. auto unitOwner = battle.battleGetOwner(active);
  1324. if(player != unitOwner)
  1325. {
  1326. gameHandler->complain("Can not make actions in battles you are not part of!");
  1327. return false;
  1328. }
  1329. }
  1330. return makeBattleActionImpl(battle, ba);
  1331. }