BattleActionProcessor.cpp 51 KB

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