BattleActionProcessor.cpp 53 KB

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