BattleActionProcessor.cpp 53 KB

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