BattleActionProcessor.cpp 53 KB

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