BattleActionProcessor.cpp 53 KB

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