BattleActionProcessor.cpp 50 KB

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