BattleActionProcessor.cpp 45 KB

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