BattleActionProcessor.cpp 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471
  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. //TODO special bonus for genies ability
  338. if (randSpellcaster && battle.battleGetRandomStackSpell(gameHandler->getRandomGenerator(), stack, CBattleInfoCallback::RANDOM_AIMED) == SpellID::NONE)
  339. spellID = battle.battleGetRandomStackSpell(gameHandler->getRandomGenerator(), stack, CBattleInfoCallback::RANDOM_GENIE);
  340. if (spellID == SpellID::NONE)
  341. gameHandler->complain("That stack can't cast spells!");
  342. else
  343. {
  344. const CSpell * spell = SpellID(spellID).toSpell();
  345. spells::BattleCast parameters(&battle, stack, spells::Mode::CREATURE_ACTIVE, spell);
  346. int32_t spellLvl = 0;
  347. if(spellcaster)
  348. vstd::amax(spellLvl, spellcaster->val);
  349. if(randSpellcaster)
  350. vstd::amax(spellLvl, randSpellcaster->val);
  351. parameters.setSpellLevel(spellLvl);
  352. parameters.cast(gameHandler->spellEnv, target);
  353. }
  354. return true;
  355. }
  356. bool BattleActionProcessor::doHealAction(const CBattleInfoCallback & battle, const BattleAction & ba)
  357. {
  358. const CStack * stack = battle.battleGetStackByID(ba.stackNumber);
  359. battle::Target target = ba.getTarget(&battle);
  360. if (!canStackAct(battle, stack))
  361. return false;
  362. if(target.size() < 1)
  363. {
  364. gameHandler->complain("Destination required for heal action.");
  365. return false;
  366. }
  367. const battle::Unit * destStack = nullptr;
  368. std::shared_ptr<const Bonus> healerAbility = stack->getBonusLocalFirst(Selector::type()(BonusType::HEALER));
  369. if(target.at(0).unitValue)
  370. destStack = target.at(0).unitValue;
  371. else
  372. destStack = battle.battleGetUnitByPos(target.at(0).hexValue);
  373. if(stack == nullptr || destStack == nullptr || !healerAbility || healerAbility->subtype == BonusSubtypeID())
  374. {
  375. gameHandler->complain("There is either no healer, no destination, or healer cannot heal :P");
  376. }
  377. else
  378. {
  379. const CSpell * spell = healerAbility->subtype.as<SpellID>().toSpell();
  380. spells::BattleCast parameters(&battle, stack, spells::Mode::SPELL_LIKE_ATTACK, spell); //We can heal infinitely by first aid tent
  381. auto dest = battle::Destination(destStack, target.at(0).hexValue);
  382. parameters.setSpellLevel(0);
  383. parameters.cast(gameHandler->spellEnv, {dest});
  384. }
  385. return true;
  386. }
  387. bool BattleActionProcessor::canStackAct(const CBattleInfoCallback & battle, const CStack * stack)
  388. {
  389. if (!stack)
  390. {
  391. gameHandler->complain("No such stack!");
  392. return false;
  393. }
  394. if (!stack->alive())
  395. {
  396. gameHandler->complain("This stack is dead: " + stack->nodeName());
  397. return false;
  398. }
  399. if (battle.battleTacticDist())
  400. {
  401. if (stack && stack->unitSide() != battle.battleGetTacticsSide())
  402. {
  403. gameHandler->complain("This is not a stack of side that has tactics!");
  404. return false;
  405. }
  406. }
  407. else
  408. {
  409. if (stack != battle.battleActiveUnit())
  410. {
  411. gameHandler->complain("Action has to be about active stack!");
  412. return false;
  413. }
  414. }
  415. return true;
  416. }
  417. bool BattleActionProcessor::dispatchBattleAction(const CBattleInfoCallback & battle, const BattleAction & ba)
  418. {
  419. switch(ba.actionType)
  420. {
  421. case EActionType::BAD_MORALE:
  422. case EActionType::NO_ACTION:
  423. return doEmptyAction(battle, ba);
  424. case EActionType::END_TACTIC_PHASE:
  425. return doEndTacticsAction(battle, ba);
  426. case EActionType::RETREAT:
  427. return doRetreatAction(battle, ba);
  428. case EActionType::SURRENDER:
  429. return doSurrenderAction(battle, ba);
  430. case EActionType::HERO_SPELL:
  431. return doHeroSpellAction(battle, ba);
  432. case EActionType::WALK:
  433. return doWalkAction(battle, ba);
  434. case EActionType::WAIT:
  435. return doWaitAction(battle, ba);
  436. case EActionType::DEFEND:
  437. return doDefendAction(battle, ba);
  438. case EActionType::WALK_AND_ATTACK:
  439. return doAttackAction(battle, ba);
  440. case EActionType::SHOOT:
  441. return doShootAction(battle, ba);
  442. case EActionType::CATAPULT:
  443. return doCatapultAction(battle, ba);
  444. case EActionType::MONSTER_SPELL:
  445. return doUnitSpellAction(battle, ba);
  446. case EActionType::STACK_HEAL:
  447. return doHealAction(battle, ba);
  448. }
  449. gameHandler->complain("Unrecognized action type received!!");
  450. return false;
  451. }
  452. bool BattleActionProcessor::makeBattleActionImpl(const CBattleInfoCallback & battle, const BattleAction &ba)
  453. {
  454. logGlobal->trace("Making action: %s", ba.toString());
  455. const CStack * stack = battle.battleGetStackByID(ba.stackNumber);
  456. // for these events client does not expects StartAction/EndAction wrapper
  457. if (!ba.isBattleEndAction())
  458. {
  459. StartAction startAction(ba);
  460. startAction.battleID = battle.getBattle()->getBattleID();
  461. gameHandler->sendAndApply(&startAction);
  462. }
  463. bool result = dispatchBattleAction(battle, ba);
  464. if (!ba.isBattleEndAction())
  465. {
  466. EndAction endAction;
  467. endAction.battleID = battle.getBattle()->getBattleID();
  468. gameHandler->sendAndApply(&endAction);
  469. }
  470. if(ba.actionType == EActionType::WAIT || ba.actionType == EActionType::DEFEND || ba.actionType == EActionType::SHOOT || ba.actionType == EActionType::MONSTER_SPELL)
  471. battle.handleObstacleTriggersForUnit(*gameHandler->spellEnv, *stack);
  472. return result;
  473. }
  474. int BattleActionProcessor::moveStack(const CBattleInfoCallback & battle, int stack, BattleHex dest)
  475. {
  476. int ret = 0;
  477. const CStack *curStack = battle.battleGetStackByID(stack);
  478. const CStack *stackAtEnd = battle.battleGetStackByPos(dest);
  479. assert(curStack);
  480. assert(dest < GameConstants::BFIELD_SIZE);
  481. if (battle.battleGetTacticDist())
  482. {
  483. assert(battle.isInTacticRange(dest));
  484. }
  485. auto start = curStack->getPosition();
  486. if (start == dest)
  487. return 0;
  488. //initing necessary tables
  489. auto accessibility = battle.getAccesibility(curStack);
  490. std::set<BattleHex> passed;
  491. //Ignore obstacles on starting position
  492. passed.insert(curStack->getPosition());
  493. if(curStack->doubleWide())
  494. passed.insert(curStack->occupiedHex());
  495. //shifting destination (if we have double wide stack and we can occupy dest but not be exactly there)
  496. if(!stackAtEnd && curStack->doubleWide() && !accessibility.accessible(dest, curStack))
  497. {
  498. BattleHex shifted = dest.cloneInDirection(curStack->destShiftDir(), false);
  499. if(accessibility.accessible(shifted, curStack))
  500. dest = shifted;
  501. }
  502. if((stackAtEnd && stackAtEnd!=curStack && stackAtEnd->alive()) || !accessibility.accessible(dest, curStack))
  503. {
  504. gameHandler->complain("Given destination is not accessible!");
  505. return 0;
  506. }
  507. bool canUseGate = false;
  508. auto dbState = battle.battleGetGateState();
  509. if(battle.battleGetSiegeLevel() > 0 && curStack->unitSide() == BattleSide::DEFENDER &&
  510. dbState != EGateState::DESTROYED &&
  511. dbState != EGateState::BLOCKED)
  512. {
  513. canUseGate = true;
  514. }
  515. std::pair< std::vector<BattleHex>, int > path = battle.getPath(start, dest, curStack);
  516. ret = path.second;
  517. int creSpeed = curStack->speed(0, true);
  518. if (battle.battleGetTacticDist() > 0 && creSpeed > 0)
  519. creSpeed = GameConstants::BFIELD_SIZE;
  520. bool hasWideMoat = vstd::contains_if(battle.battleGetAllObstaclesOnPos(BattleHex(BattleHex::GATE_BRIDGE), false), [](const std::shared_ptr<const CObstacleInstance> & obst)
  521. {
  522. return obst->obstacleType == CObstacleInstance::MOAT;
  523. });
  524. auto isGateDrawbridgeHex = [&](BattleHex hex) -> bool
  525. {
  526. if (hasWideMoat && hex == BattleHex::GATE_BRIDGE)
  527. return true;
  528. if (hex == BattleHex::GATE_OUTER)
  529. return true;
  530. if (hex == BattleHex::GATE_INNER)
  531. return true;
  532. return false;
  533. };
  534. auto occupyGateDrawbridgeHex = [&](BattleHex hex) -> bool
  535. {
  536. if (isGateDrawbridgeHex(hex))
  537. return true;
  538. if (curStack->doubleWide())
  539. {
  540. BattleHex otherHex = curStack->occupiedHex(hex);
  541. if (otherHex.isValid() && isGateDrawbridgeHex(otherHex))
  542. return true;
  543. }
  544. return false;
  545. };
  546. if (curStack->hasBonusOfType(BonusType::FLYING))
  547. {
  548. if (path.second <= creSpeed && path.first.size() > 0)
  549. {
  550. if (canUseGate && dbState != EGateState::OPENED &&
  551. occupyGateDrawbridgeHex(dest))
  552. {
  553. BattleUpdateGateState db;
  554. db.battleID = battle.getBattle()->getBattleID();
  555. db.state = EGateState::OPENED;
  556. gameHandler->sendAndApply(&db);
  557. }
  558. //inform clients about move
  559. BattleStackMoved sm;
  560. sm.battleID = battle.getBattle()->getBattleID();
  561. sm.stack = curStack->unitId();
  562. std::vector<BattleHex> tiles;
  563. tiles.push_back(path.first[0]);
  564. sm.tilesToMove = tiles;
  565. sm.distance = path.second;
  566. sm.teleporting = false;
  567. gameHandler->sendAndApply(&sm);
  568. }
  569. }
  570. else //for non-flying creatures
  571. {
  572. std::vector<BattleHex> tiles;
  573. const int tilesToMove = std::max((int)(path.first.size() - creSpeed), 0);
  574. int v = (int)path.first.size()-1;
  575. path.first.push_back(start);
  576. // check if gate need to be open or closed at some point
  577. BattleHex openGateAtHex, gateMayCloseAtHex;
  578. if (canUseGate)
  579. {
  580. for (int i = (int)path.first.size()-1; i >= 0; i--)
  581. {
  582. auto needOpenGates = [&](BattleHex hex) -> bool
  583. {
  584. if (hasWideMoat && hex == BattleHex::GATE_BRIDGE)
  585. return true;
  586. if (hex == BattleHex::GATE_BRIDGE && i-1 >= 0 && path.first[i-1] == BattleHex::GATE_OUTER)
  587. return true;
  588. else if (hex == BattleHex::GATE_OUTER || hex == BattleHex::GATE_INNER)
  589. return true;
  590. return false;
  591. };
  592. auto hex = path.first[i];
  593. if (!openGateAtHex.isValid() && dbState != EGateState::OPENED)
  594. {
  595. if (needOpenGates(hex))
  596. openGateAtHex = path.first[i+1];
  597. //TODO we need find batter way to handle double-wide stacks
  598. //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.
  599. if (curStack->doubleWide())
  600. {
  601. BattleHex otherHex = curStack->occupiedHex(hex);
  602. if (otherHex.isValid() && needOpenGates(otherHex))
  603. openGateAtHex = path.first[i+2];
  604. }
  605. //gate may be opened and then closed during stack movement, but not other way around
  606. if (openGateAtHex.isValid())
  607. dbState = EGateState::OPENED;
  608. }
  609. if (!gateMayCloseAtHex.isValid() && dbState != EGateState::CLOSED)
  610. {
  611. if (hex == BattleHex::GATE_INNER && i-1 >= 0 && path.first[i-1] != BattleHex::GATE_OUTER)
  612. {
  613. gateMayCloseAtHex = path.first[i-1];
  614. }
  615. if (hasWideMoat)
  616. {
  617. if (hex == BattleHex::GATE_BRIDGE && i-1 >= 0 && path.first[i-1] != BattleHex::GATE_OUTER)
  618. {
  619. gateMayCloseAtHex = path.first[i-1];
  620. }
  621. else if (hex == BattleHex::GATE_OUTER && i-1 >= 0 &&
  622. path.first[i-1] != BattleHex::GATE_INNER &&
  623. path.first[i-1] != BattleHex::GATE_BRIDGE)
  624. {
  625. gateMayCloseAtHex = path.first[i-1];
  626. }
  627. }
  628. else if (hex == BattleHex::GATE_OUTER && i-1 >= 0 && path.first[i-1] != BattleHex::GATE_INNER)
  629. {
  630. gateMayCloseAtHex = path.first[i-1];
  631. }
  632. }
  633. }
  634. }
  635. bool stackIsMoving = true;
  636. while(stackIsMoving)
  637. {
  638. if (v<tilesToMove)
  639. {
  640. logGlobal->error("Movement terminated abnormally");
  641. break;
  642. }
  643. bool gateStateChanging = false;
  644. //special handling for opening gate on from starting hex
  645. if (openGateAtHex.isValid() && openGateAtHex == start)
  646. gateStateChanging = true;
  647. else
  648. {
  649. for (bool obstacleHit = false; (!obstacleHit) && (!gateStateChanging) && (v >= tilesToMove); --v)
  650. {
  651. BattleHex hex = path.first[v];
  652. tiles.push_back(hex);
  653. if ((openGateAtHex.isValid() && openGateAtHex == hex) ||
  654. (gateMayCloseAtHex.isValid() && gateMayCloseAtHex == hex))
  655. {
  656. gateStateChanging = true;
  657. }
  658. //if we walked onto something, finalize this portion of stack movement check into obstacle
  659. if(!battle.battleGetAllObstaclesOnPos(hex, false).empty())
  660. obstacleHit = true;
  661. if (curStack->doubleWide())
  662. {
  663. BattleHex otherHex = curStack->occupiedHex(hex);
  664. //two hex creature hit obstacle by backside
  665. auto obstacle2 = battle.battleGetAllObstaclesOnPos(otherHex, false);
  666. if(otherHex.isValid() && !obstacle2.empty())
  667. obstacleHit = true;
  668. }
  669. if(!obstacleHit)
  670. passed.insert(hex);
  671. }
  672. }
  673. if (!tiles.empty())
  674. {
  675. //commit movement
  676. BattleStackMoved sm;
  677. sm.battleID = battle.getBattle()->getBattleID();
  678. sm.stack = curStack->unitId();
  679. sm.distance = path.second;
  680. sm.teleporting = false;
  681. sm.tilesToMove = tiles;
  682. gameHandler->sendAndApply(&sm);
  683. tiles.clear();
  684. }
  685. //we don't handle obstacle at the destination tile -> it's handled separately in the if at the end
  686. if (curStack->getPosition() != dest)
  687. {
  688. if(stackIsMoving && start != curStack->getPosition())
  689. {
  690. stackIsMoving = battle.handleObstacleTriggersForUnit(*gameHandler->spellEnv, *curStack, passed);
  691. passed.insert(curStack->getPosition());
  692. if(curStack->doubleWide())
  693. passed.insert(curStack->occupiedHex());
  694. }
  695. if (gateStateChanging)
  696. {
  697. if (curStack->getPosition() == openGateAtHex)
  698. {
  699. openGateAtHex = BattleHex();
  700. //only open gate if stack is still alive
  701. if (curStack->alive())
  702. {
  703. BattleUpdateGateState db;
  704. db.battleID = battle.getBattle()->getBattleID();
  705. db.state = EGateState::OPENED;
  706. gameHandler->sendAndApply(&db);
  707. }
  708. }
  709. else if (curStack->getPosition() == gateMayCloseAtHex)
  710. {
  711. gateMayCloseAtHex = BattleHex();
  712. owner->updateGateState(battle);
  713. }
  714. }
  715. }
  716. else
  717. //movement finished normally: we reached destination
  718. stackIsMoving = false;
  719. }
  720. }
  721. //handle last hex separately for deviation
  722. if (VLC->settings()->getBoolean(EGameSettings::COMBAT_ONE_HEX_TRIGGERS_OBSTACLES))
  723. {
  724. if (dest == battle::Unit::occupiedHex(start, curStack->doubleWide(), curStack->unitSide())
  725. || start == battle::Unit::occupiedHex(dest, curStack->doubleWide(), curStack->unitSide()))
  726. passed.clear(); //Just empty passed, obstacles will handled automatically
  727. }
  728. if(dest == start) //If dest is equal to start, then we should handle obstacles for it anyway
  729. passed.clear(); //Just empty passed, obstacles will handled automatically
  730. //handling obstacle on the final field (separate, because it affects both flying and walking stacks)
  731. battle.handleObstacleTriggersForUnit(*gameHandler->spellEnv, *curStack, passed);
  732. return ret;
  733. }
  734. void BattleActionProcessor::makeAttack(const CBattleInfoCallback & battle, const CStack * attacker, const CStack * defender, int distance, BattleHex targetHex, bool first, bool ranged, bool counter)
  735. {
  736. if(first && !counter)
  737. handleAttackBeforeCasting(battle, ranged, attacker, defender);
  738. FireShieldInfo fireShield;
  739. BattleAttack bat;
  740. BattleLogMessage blm;
  741. blm.battleID = battle.getBattle()->getBattleID();
  742. bat.battleID = battle.getBattle()->getBattleID();
  743. bat.attackerChanges.battleID = battle.getBattle()->getBattleID();
  744. bat.stackAttacking = attacker->unitId();
  745. bat.tile = targetHex;
  746. std::shared_ptr<battle::CUnitState> attackerState = attacker->acquireState();
  747. if(ranged)
  748. bat.flags |= BattleAttack::SHOT;
  749. if(counter)
  750. bat.flags |= BattleAttack::COUNTER;
  751. const int attackerLuck = attacker->luckVal();
  752. if(attackerLuck > 0)
  753. {
  754. auto diceSize = VLC->settings()->getVector(EGameSettings::COMBAT_GOOD_LUCK_DICE);
  755. size_t diceIndex = std::min<size_t>(diceSize.size(), attackerLuck) - 1; // array index, so 0-indexed
  756. if(diceSize.size() > 0 && gameHandler->getRandomGenerator().nextInt(1, diceSize[diceIndex]) == 1)
  757. bat.flags |= BattleAttack::LUCKY;
  758. }
  759. if(attackerLuck < 0)
  760. {
  761. auto diceSize = VLC->settings()->getVector(EGameSettings::COMBAT_BAD_LUCK_DICE);
  762. size_t diceIndex = std::min<size_t>(diceSize.size(), -attackerLuck) - 1; // array index, so 0-indexed
  763. if(diceSize.size() > 0 && gameHandler->getRandomGenerator().nextInt(1, diceSize[diceIndex]) == 1)
  764. bat.flags |= BattleAttack::UNLUCKY;
  765. }
  766. if (gameHandler->getRandomGenerator().nextInt(99) < attacker->valOfBonuses(BonusType::DOUBLE_DAMAGE_CHANCE))
  767. {
  768. bat.flags |= BattleAttack::DEATH_BLOW;
  769. }
  770. const auto * owner = battle.battleGetFightingHero(attacker->unitSide());
  771. if(owner)
  772. {
  773. int chance = owner->valOfBonuses(BonusType::BONUS_DAMAGE_CHANCE, BonusSubtypeID(attacker->creatureId()));
  774. if (chance > gameHandler->getRandomGenerator().nextInt(99))
  775. bat.flags |= BattleAttack::BALLISTA_DOUBLE_DMG;
  776. }
  777. int64_t drainedLife = 0;
  778. // only primary target
  779. if(defender->alive())
  780. drainedLife += applyBattleEffects(battle, bat, attackerState, fireShield, defender, distance, false);
  781. //multiple-hex normal attack
  782. std::set<const CStack*> attackedCreatures = battle.getAttackedCreatures(attacker, targetHex, bat.shot()); //creatures other than primary target
  783. for(const CStack * stack : attackedCreatures)
  784. {
  785. if(stack != defender && stack->alive()) //do not hit same stack twice
  786. drainedLife += applyBattleEffects(battle, bat, attackerState, fireShield, stack, distance, true);
  787. }
  788. std::shared_ptr<const Bonus> bonus = attacker->getBonusLocalFirst(Selector::type()(BonusType::SPELL_LIKE_ATTACK));
  789. if(bonus && ranged) //TODO: make it work in melee?
  790. {
  791. //this is need for displaying hit animation
  792. bat.flags |= BattleAttack::SPELL_LIKE;
  793. bat.spellID = bonus->subtype.as<SpellID>();
  794. //TODO: should spell override creature`s projectile?
  795. auto spell = bat.spellID.toSpell();
  796. battle::Target target;
  797. target.emplace_back(defender, targetHex);
  798. spells::BattleCast event(&battle, attacker, spells::Mode::SPELL_LIKE_ATTACK, spell);
  799. event.setSpellLevel(bonus->val);
  800. auto attackedCreatures = spell->battleMechanics(&event)->getAffectedStacks(target);
  801. //TODO: get exact attacked hex for defender
  802. for(const CStack * stack : attackedCreatures)
  803. {
  804. if(stack != defender && stack->alive()) //do not hit same stack twice
  805. {
  806. drainedLife += applyBattleEffects(battle, bat, attackerState, fireShield, stack, distance, true);
  807. }
  808. }
  809. //now add effect info for all attacked stacks
  810. for (BattleStackAttacked & bsa : bat.bsa)
  811. {
  812. if (bsa.attackerID == attacker->unitId()) //this is our attack and not f.e. fire shield
  813. {
  814. //this is need for displaying affect animation
  815. bsa.flags |= BattleStackAttacked::SPELL_EFFECT;
  816. bsa.spellID = bonus->subtype.as<SpellID>();
  817. }
  818. }
  819. }
  820. attackerState->afterAttack(ranged, counter);
  821. {
  822. UnitChanges info(attackerState->unitId(), UnitChanges::EOperation::RESET_STATE);
  823. attackerState->save(info.data);
  824. bat.attackerChanges.changedStacks.push_back(info);
  825. }
  826. if (drainedLife > 0)
  827. bat.flags |= BattleAttack::LIFE_DRAIN;
  828. for (BattleStackAttacked & bsa : bat.bsa)
  829. bsa.battleID = battle.getBattle()->getBattleID();
  830. gameHandler->sendAndApply(&bat);
  831. {
  832. const bool multipleTargets = bat.bsa.size() > 1;
  833. int64_t totalDamage = 0;
  834. int32_t totalKills = 0;
  835. for(const BattleStackAttacked & bsa : bat.bsa)
  836. {
  837. totalDamage += bsa.damageAmount;
  838. totalKills += bsa.killedAmount;
  839. }
  840. {
  841. MetaString text;
  842. attacker->addText(text, EMetaText::GENERAL_TXT, 376);
  843. attacker->addNameReplacement(text);
  844. text.replaceNumber(totalDamage);
  845. blm.lines.push_back(text);
  846. }
  847. addGenericKilledLog(blm, defender, totalKills, multipleTargets);
  848. }
  849. // drain life effect (as well as log entry) must be applied after the attack
  850. if(drainedLife > 0)
  851. {
  852. MetaString text;
  853. attackerState->addText(text, EMetaText::GENERAL_TXT, 361);
  854. attackerState->addNameReplacement(text, false);
  855. text.replaceNumber(drainedLife);
  856. defender->addNameReplacement(text, true);
  857. blm.lines.push_back(std::move(text));
  858. }
  859. if(!fireShield.empty())
  860. {
  861. //todo: this should be "virtual" spell instead, we only need fire spell school bonus here
  862. const CSpell * fireShieldSpell = SpellID(SpellID::FIRE_SHIELD).toSpell();
  863. int64_t totalDamage = 0;
  864. for(const auto & item : fireShield)
  865. {
  866. const CStack * actor = item.first;
  867. int64_t rawDamage = item.second;
  868. const CGHeroInstance * actorOwner = battle.battleGetFightingHero(actor->unitSide());
  869. if(actorOwner)
  870. {
  871. rawDamage = fireShieldSpell->adjustRawDamage(actorOwner, attacker, rawDamage);
  872. }
  873. else
  874. {
  875. rawDamage = fireShieldSpell->adjustRawDamage(actor, attacker, rawDamage);
  876. }
  877. totalDamage+=rawDamage;
  878. //FIXME: add custom effect on actor
  879. }
  880. if (totalDamage > 0)
  881. {
  882. BattleStackAttacked bsa;
  883. bsa.battleID = battle.getBattle()->getBattleID();
  884. bsa.flags |= BattleStackAttacked::FIRE_SHIELD;
  885. bsa.stackAttacked = attacker->unitId(); //invert
  886. bsa.attackerID = defender->unitId();
  887. bsa.damageAmount = totalDamage;
  888. attacker->prepareAttacked(bsa, gameHandler->getRandomGenerator());
  889. StacksInjured pack;
  890. pack.battleID = battle.getBattle()->getBattleID();
  891. pack.stacks.push_back(bsa);
  892. gameHandler->sendAndApply(&pack);
  893. // TODO: this is already implemented in Damage::describeEffect()
  894. {
  895. MetaString text;
  896. text.appendLocalString(EMetaText::GENERAL_TXT, 376);
  897. text.replaceName(SpellID(SpellID::FIRE_SHIELD));
  898. text.replaceNumber(totalDamage);
  899. blm.lines.push_back(std::move(text));
  900. }
  901. addGenericKilledLog(blm, attacker, bsa.killedAmount, false);
  902. }
  903. }
  904. gameHandler->sendAndApply(&blm);
  905. handleAfterAttackCasting(battle, ranged, attacker, defender);
  906. }
  907. void BattleActionProcessor::attackCasting(const CBattleInfoCallback & battle, bool ranged, BonusType attackMode, const battle::Unit * attacker, const battle::Unit * defender)
  908. {
  909. if(attacker->hasBonusOfType(attackMode))
  910. {
  911. std::set<SpellID> spellsToCast;
  912. TConstBonusListPtr spells = attacker->getBonuses(Selector::type()(attackMode));
  913. for(const auto & sf : *spells)
  914. {
  915. if (sf->subtype.as<SpellID>() != SpellID())
  916. spellsToCast.insert(sf->subtype.as<SpellID>());
  917. else
  918. logMod->error("Invalid spell to cast during attack!");
  919. }
  920. for(SpellID spellID : spellsToCast)
  921. {
  922. bool castMe = false;
  923. if(!defender->alive())
  924. {
  925. logGlobal->debug("attackCasting: all attacked creatures have been killed");
  926. return;
  927. }
  928. int32_t spellLevel = 0;
  929. TConstBonusListPtr spellsByType = attacker->getBonuses(Selector::typeSubtype(attackMode, BonusSubtypeID(spellID)));
  930. for(const auto & sf : *spellsByType)
  931. {
  932. int meleeRanged;
  933. if(sf->additionalInfo.size() < 2)
  934. {
  935. // legacy format
  936. vstd::amax(spellLevel, sf->additionalInfo[0] % 1000);
  937. meleeRanged = sf->additionalInfo[0] / 1000;
  938. }
  939. else
  940. {
  941. vstd::amax(spellLevel, sf->additionalInfo[0]);
  942. meleeRanged = sf->additionalInfo[1];
  943. }
  944. if (meleeRanged == 0 || (meleeRanged == 1 && ranged) || (meleeRanged == 2 && !ranged))
  945. castMe = true;
  946. }
  947. int chance = attacker->valOfBonuses((Selector::typeSubtype(attackMode, BonusSubtypeID(spellID))));
  948. vstd::amin(chance, 100);
  949. const CSpell * spell = SpellID(spellID).toSpell();
  950. spells::AbilityCaster caster(attacker, spellLevel);
  951. spells::Target target;
  952. target.emplace_back(defender);
  953. spells::BattleCast parameters(&battle, &caster, spells::Mode::PASSIVE, spell);
  954. auto m = spell->battleMechanics(&parameters);
  955. spells::detail::ProblemImpl ignored;
  956. if(!m->canBeCastAt(target, ignored))
  957. continue;
  958. //check if spell should be cast (probability handling)
  959. if(gameHandler->getRandomGenerator().nextInt(99) >= chance)
  960. continue;
  961. //casting
  962. if(castMe)
  963. {
  964. parameters.cast(gameHandler->spellEnv, target);
  965. }
  966. }
  967. }
  968. }
  969. void BattleActionProcessor::handleAttackBeforeCasting(const CBattleInfoCallback & battle, bool ranged, const CStack * attacker, const CStack * defender)
  970. {
  971. attackCasting(battle, ranged, BonusType::SPELL_BEFORE_ATTACK, attacker, defender); //no death stare / acid breath needed?
  972. }
  973. void BattleActionProcessor::handleAfterAttackCasting(const CBattleInfoCallback & battle, bool ranged, const CStack * attacker, const CStack * defender)
  974. {
  975. if(!attacker->alive() || !defender->alive()) // can be already dead
  976. return;
  977. attackCasting(battle, ranged, BonusType::SPELL_AFTER_ATTACK, attacker, defender);
  978. if(!defender->alive())
  979. {
  980. //don't try death stare or acid breath on dead stack (crash!)
  981. return;
  982. }
  983. if(attacker->hasBonusOfType(BonusType::DEATH_STARE))
  984. {
  985. // mechanics of Death Stare as in H3:
  986. // each gorgon have 10% chance to kill (counted separately in H3) -> binomial distribution
  987. //original formula x = min(x, (gorgons_count + 9)/10);
  988. double chanceToKill = attacker->valOfBonuses(BonusType::DEATH_STARE, BonusCustomSubtype::deathStareGorgon) / 100.0f;
  989. vstd::amin(chanceToKill, 1); //cap at 100%
  990. std::binomial_distribution<> distribution(attacker->getCount(), chanceToKill);
  991. int staredCreatures = distribution(gameHandler->getRandomGenerator().getStdGenerator());
  992. double cap = 1 / std::max(chanceToKill, (double)(0.01));//don't divide by 0
  993. int maxToKill = static_cast<int>((attacker->getCount() + cap - 1) / cap); //not much more than chance * count
  994. vstd::amin(staredCreatures, maxToKill);
  995. staredCreatures += (attacker->level() * attacker->valOfBonuses(BonusType::DEATH_STARE, BonusCustomSubtype::deathStareCommander)) / defender->level();
  996. if(staredCreatures)
  997. {
  998. //TODO: death stare was not originally available for multiple-hex attacks, but...
  999. const CSpell * spell = SpellID(SpellID::DEATH_STARE).toSpell();
  1000. spells::AbilityCaster caster(attacker, 0);
  1001. spells::BattleCast parameters(&battle, &caster, spells::Mode::PASSIVE, spell);
  1002. spells::Target target;
  1003. target.emplace_back(defender);
  1004. parameters.setEffectValue(staredCreatures);
  1005. parameters.cast(gameHandler->spellEnv, target);
  1006. }
  1007. }
  1008. if(!defender->alive())
  1009. return;
  1010. int64_t acidDamage = 0;
  1011. TConstBonusListPtr acidBreath = attacker->getBonuses(Selector::type()(BonusType::ACID_BREATH));
  1012. for(const auto & b : *acidBreath)
  1013. {
  1014. if(b->additionalInfo[0] > gameHandler->getRandomGenerator().nextInt(99))
  1015. acidDamage += b->val;
  1016. }
  1017. if(acidDamage > 0)
  1018. {
  1019. const CSpell * spell = SpellID(SpellID::ACID_BREATH_DAMAGE).toSpell();
  1020. spells::AbilityCaster caster(attacker, 0);
  1021. spells::BattleCast parameters(&battle, &caster, spells::Mode::PASSIVE, spell);
  1022. spells::Target target;
  1023. target.emplace_back(defender);
  1024. parameters.setEffectValue(acidDamage * attacker->getCount());
  1025. parameters.cast(gameHandler->spellEnv, target);
  1026. }
  1027. if(!defender->alive())
  1028. return;
  1029. if(attacker->hasBonusOfType(BonusType::TRANSMUTATION) && defender->isLiving()) //transmutation mechanics, similar to WoG werewolf ability
  1030. {
  1031. double chanceToTrigger = attacker->valOfBonuses(BonusType::TRANSMUTATION) / 100.0f;
  1032. vstd::amin(chanceToTrigger, 1); //cap at 100%
  1033. if(gameHandler->getRandomGenerator().getDoubleRange(0, 1)() > chanceToTrigger)
  1034. return;
  1035. int bonusAdditionalInfo = attacker->getBonus(Selector::type()(BonusType::TRANSMUTATION))->additionalInfo[0];
  1036. if(defender->unitType()->getIndex() == bonusAdditionalInfo ||
  1037. (bonusAdditionalInfo == CAddInfo::NONE && defender->unitType()->getId() == attacker->unitType()->getId()))
  1038. return;
  1039. battle::UnitInfo resurrectInfo;
  1040. resurrectInfo.id = battle.battleNextUnitId();
  1041. resurrectInfo.summoned = false;
  1042. resurrectInfo.position = defender->getPosition();
  1043. resurrectInfo.side = defender->unitSide();
  1044. if(bonusAdditionalInfo != CAddInfo::NONE)
  1045. resurrectInfo.type = CreatureID(bonusAdditionalInfo);
  1046. else
  1047. resurrectInfo.type = attacker->creatureId();
  1048. if(attacker->hasBonusOfType((BonusType::TRANSMUTATION), BonusCustomSubtype::transmutationPerHealth))
  1049. resurrectInfo.count = std::max((defender->getCount() * defender->getMaxHealth()) / resurrectInfo.type.toCreature()->getMaxHealth(), 1u);
  1050. else if (attacker->hasBonusOfType((BonusType::TRANSMUTATION), BonusCustomSubtype::transmutationPerUnit))
  1051. resurrectInfo.count = defender->getCount();
  1052. else
  1053. return; //wrong subtype
  1054. BattleUnitsChanged addUnits;
  1055. addUnits.battleID = battle.getBattle()->getBattleID();
  1056. addUnits.changedStacks.emplace_back(resurrectInfo.id, UnitChanges::EOperation::ADD);
  1057. resurrectInfo.save(addUnits.changedStacks.back().data);
  1058. BattleUnitsChanged removeUnits;
  1059. removeUnits.battleID = battle.getBattle()->getBattleID();
  1060. removeUnits.changedStacks.emplace_back(defender->unitId(), UnitChanges::EOperation::REMOVE);
  1061. gameHandler->sendAndApply(&removeUnits);
  1062. gameHandler->sendAndApply(&addUnits);
  1063. // send empty event to client
  1064. // temporary(?) workaround to force animations to trigger
  1065. StacksInjured fakeEvent;
  1066. gameHandler->sendAndApply(&fakeEvent);
  1067. }
  1068. if(attacker->hasBonusOfType(BonusType::DESTRUCTION, BonusCustomSubtype::destructionKillPercentage) || attacker->hasBonusOfType(BonusType::DESTRUCTION, BonusCustomSubtype::destructionKillAmount))
  1069. {
  1070. double chanceToTrigger = 0;
  1071. int amountToDie = 0;
  1072. if(attacker->hasBonusOfType(BonusType::DESTRUCTION, BonusCustomSubtype::destructionKillPercentage)) //killing by percentage
  1073. {
  1074. chanceToTrigger = attacker->valOfBonuses(BonusType::DESTRUCTION, BonusCustomSubtype::destructionKillPercentage) / 100.0f;
  1075. int percentageToDie = attacker->getBonus(Selector::type()(BonusType::DESTRUCTION).And(Selector::subtype()(BonusCustomSubtype::destructionKillPercentage)))->additionalInfo[0];
  1076. amountToDie = static_cast<int>(defender->getCount() * percentageToDie * 0.01f);
  1077. }
  1078. else if(attacker->hasBonusOfType(BonusType::DESTRUCTION, BonusCustomSubtype::destructionKillAmount)) //killing by count
  1079. {
  1080. chanceToTrigger = attacker->valOfBonuses(BonusType::DESTRUCTION, BonusCustomSubtype::destructionKillAmount) / 100.0f;
  1081. amountToDie = attacker->getBonus(Selector::type()(BonusType::DESTRUCTION).And(Selector::subtype()(BonusCustomSubtype::destructionKillAmount)))->additionalInfo[0];
  1082. }
  1083. vstd::amin(chanceToTrigger, 1); //cap trigger chance at 100%
  1084. if(gameHandler->getRandomGenerator().getDoubleRange(0, 1)() > chanceToTrigger)
  1085. return;
  1086. BattleStackAttacked bsa;
  1087. bsa.attackerID = -1;
  1088. bsa.stackAttacked = defender->unitId();
  1089. bsa.damageAmount = amountToDie * defender->getMaxHealth();
  1090. bsa.flags = BattleStackAttacked::SPELL_EFFECT;
  1091. bsa.spellID = SpellID::SLAYER;
  1092. defender->prepareAttacked(bsa, gameHandler->getRandomGenerator());
  1093. StacksInjured si;
  1094. si.battleID = battle.getBattle()->getBattleID();
  1095. si.stacks.push_back(bsa);
  1096. gameHandler->sendAndApply(&si);
  1097. sendGenericKilledLog(battle, defender, bsa.killedAmount, false);
  1098. }
  1099. }
  1100. int64_t BattleActionProcessor::applyBattleEffects(const CBattleInfoCallback & battle, BattleAttack & bat, std::shared_ptr<battle::CUnitState> attackerState, FireShieldInfo & fireShield, const CStack * def, int distance, bool secondary)
  1101. {
  1102. BattleStackAttacked bsa;
  1103. if(secondary)
  1104. bsa.flags |= BattleStackAttacked::SECONDARY; //all other targets do not suffer from spells & spell-like abilities
  1105. bsa.attackerID = attackerState->unitId();
  1106. bsa.stackAttacked = def->unitId();
  1107. {
  1108. BattleAttackInfo bai(attackerState.get(), def, distance, bat.shot());
  1109. bai.deathBlow = bat.deathBlow();
  1110. bai.doubleDamage = bat.ballistaDoubleDmg();
  1111. bai.luckyStrike = bat.lucky();
  1112. bai.unluckyStrike = bat.unlucky();
  1113. auto range = battle.calculateDmgRange(bai);
  1114. bsa.damageAmount = battle.getBattle()->getActualDamage(range.damage, attackerState->getCount(), gameHandler->getRandomGenerator());
  1115. CStack::prepareAttacked(bsa, gameHandler->getRandomGenerator(), bai.defender->acquireState()); //calculate casualties
  1116. }
  1117. int64_t drainedLife = 0;
  1118. //life drain handling
  1119. if(attackerState->hasBonusOfType(BonusType::LIFE_DRAIN) && def->isLiving())
  1120. {
  1121. int64_t toHeal = bsa.damageAmount * attackerState->valOfBonuses(BonusType::LIFE_DRAIN) / 100;
  1122. attackerState->heal(toHeal, EHealLevel::RESURRECT, EHealPower::PERMANENT);
  1123. drainedLife += toHeal;
  1124. }
  1125. //soul steal handling
  1126. if(attackerState->hasBonusOfType(BonusType::SOUL_STEAL) && def->isLiving())
  1127. {
  1128. //we can have two bonuses - one with subtype 0 and another with subtype 1
  1129. //try to use permanent first, use only one of two
  1130. for(const auto & subtype : { BonusCustomSubtype::soulStealBattle, BonusCustomSubtype::soulStealPermanent})
  1131. {
  1132. if(attackerState->hasBonusOfType(BonusType::SOUL_STEAL, subtype))
  1133. {
  1134. int64_t toHeal = bsa.killedAmount * attackerState->valOfBonuses(BonusType::SOUL_STEAL, subtype) * attackerState->getMaxHealth();
  1135. bool permanent = subtype == BonusCustomSubtype::soulStealPermanent;
  1136. attackerState->heal(toHeal, EHealLevel::OVERHEAL, (permanent ? EHealPower::PERMANENT : EHealPower::ONE_BATTLE));
  1137. drainedLife += toHeal;
  1138. break;
  1139. }
  1140. }
  1141. }
  1142. bat.bsa.push_back(bsa); //add this stack to the list of victims after drain life has been calculated
  1143. //fire shield handling
  1144. if(!bat.shot() &&
  1145. !def->isClone() &&
  1146. def->hasBonusOfType(BonusType::FIRE_SHIELD) &&
  1147. !attackerState->hasBonusOfType(BonusType::SPELL_SCHOOL_IMMUNITY, BonusSubtypeID(SpellSchool::FIRE)) &&
  1148. !attackerState->hasBonusOfType(BonusType::NEGATIVE_EFFECTS_IMMUNITY, BonusSubtypeID(SpellSchool::FIRE)) &&
  1149. attackerState->valOfBonuses(BonusType::SPELL_DAMAGE_REDUCTION, BonusSubtypeID(SpellSchool::FIRE)) < 100 &&
  1150. CStack::isMeleeAttackPossible(attackerState.get(), def) // attacked needs to be adjacent to defender for fire shield to trigger (e.g. Dragon Breath attack)
  1151. )
  1152. {
  1153. //TODO: use damage with bonus but without penalties
  1154. auto fireShieldDamage = (std::min<int64_t>(def->getAvailableHealth(), bsa.damageAmount) * def->valOfBonuses(BonusType::FIRE_SHIELD)) / 100;
  1155. fireShield.push_back(std::make_pair(def, fireShieldDamage));
  1156. }
  1157. return drainedLife;
  1158. }
  1159. void BattleActionProcessor::sendGenericKilledLog(const CBattleInfoCallback & battle, const CStack * defender, int32_t killed, bool multiple)
  1160. {
  1161. if(killed > 0)
  1162. {
  1163. BattleLogMessage blm;
  1164. blm.battleID = battle.getBattle()->getBattleID();
  1165. addGenericKilledLog(blm, defender, killed, multiple);
  1166. gameHandler->sendAndApply(&blm);
  1167. }
  1168. }
  1169. void BattleActionProcessor::addGenericKilledLog(BattleLogMessage & blm, const CStack * defender, int32_t killed, bool multiple)
  1170. {
  1171. if(killed > 0)
  1172. {
  1173. const int32_t txtIndex = (killed > 1) ? 379 : 378;
  1174. std::string formatString = VLC->generaltexth->allTexts[txtIndex];
  1175. // 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)
  1176. formatString.erase(std::remove(formatString.begin(), formatString.end(), '\n'), formatString.end());
  1177. formatString.erase(std::remove(formatString.begin(), formatString.end(), '\r'), formatString.end());
  1178. boost::algorithm::trim(formatString);
  1179. boost::format txt(formatString);
  1180. if(killed > 1)
  1181. {
  1182. txt % killed % (multiple ? VLC->generaltexth->allTexts[43] : defender->unitType()->getNamePluralTranslated()); // creatures perish
  1183. }
  1184. else //killed == 1
  1185. {
  1186. txt % (multiple ? VLC->generaltexth->allTexts[42] : defender->unitType()->getNameSingularTranslated()); // creature perishes
  1187. }
  1188. MetaString line;
  1189. line.appendRawString(txt.str());
  1190. blm.lines.push_back(std::move(line));
  1191. }
  1192. }
  1193. bool BattleActionProcessor::makeAutomaticBattleAction(const CBattleInfoCallback & battle, const BattleAction & ba)
  1194. {
  1195. return makeBattleActionImpl(battle, ba);
  1196. }
  1197. bool BattleActionProcessor::makePlayerBattleAction(const CBattleInfoCallback & battle, PlayerColor player, const BattleAction &ba)
  1198. {
  1199. if (ba.side != 0 && ba.side != 1 && gameHandler->complain("Can not make action - invalid battle side!"))
  1200. return false;
  1201. if(battle.battleGetTacticDist() != 0)
  1202. {
  1203. if(!ba.isTacticsAction())
  1204. {
  1205. gameHandler->complain("Can not make actions while in tactics mode!");
  1206. return false;
  1207. }
  1208. if(player != battle.sideToPlayer(ba.side))
  1209. {
  1210. gameHandler->complain("Can not make actions in battles you are not part of!");
  1211. return false;
  1212. }
  1213. }
  1214. else
  1215. {
  1216. auto active = battle.battleActiveUnit();
  1217. if(!active && gameHandler->complain("No active unit in battle!"))
  1218. return false;
  1219. if (ba.isUnitAction() && ba.stackNumber != active->unitId())
  1220. {
  1221. gameHandler->complain("Can not make actions - stack is not active!");
  1222. return false;
  1223. }
  1224. auto unitOwner = battle.battleGetOwner(active);
  1225. if(player != unitOwner && gameHandler->complain("Can not make actions in battles you are not part of!"))
  1226. return false;
  1227. }
  1228. return makeBattleActionImpl(battle, ba);
  1229. }