BattleActionProcessor.cpp 48 KB

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