BattleActionsController.cpp 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123
  1. /*
  2. * BattleActionsController.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 "BattleActionsController.h"
  12. #include "BattleFieldController.h"
  13. #include "BattleHero.h"
  14. #include "BattleInterface.h"
  15. #include "BattleSiegeController.h"
  16. #include "BattleStacksController.h"
  17. #include "BattleWindow.h"
  18. #include "../CPlayerInterface.h"
  19. #include "../GameEngine.h"
  20. #include "../GameInstance.h"
  21. #include "../gui/CIntObject.h"
  22. #include "../gui/CursorHandler.h"
  23. #include "../gui/WindowHandler.h"
  24. #include "../windows/CCreatureWindow.h"
  25. #include "../windows/InfoWindows.h"
  26. #include "../../lib/CConfigHandler.h"
  27. #include "../../lib/CRandomGenerator.h"
  28. #include "../../lib/CStack.h"
  29. #include "../../lib/GameLibrary.h"
  30. #include "../../lib/battle/BattleAction.h"
  31. #include "../../lib/battle/CPlayerBattleCallback.h"
  32. #include "../../lib/callback/CCallback.h"
  33. #include "../../lib/spells/CSpellHandler.h"
  34. #include "../../lib/spells/ISpellMechanics.h"
  35. #include "../../lib/spells/Problem.h"
  36. #include "../../lib/texts/CGeneralTextHandler.h"
  37. struct TextReplacement
  38. {
  39. std::string placeholder;
  40. std::string replacement;
  41. };
  42. using TextReplacementList = std::vector<TextReplacement>;
  43. static std::string replacePlaceholders(std::string input, const TextReplacementList & format )
  44. {
  45. for(const auto & entry : format)
  46. boost::replace_all(input, entry.placeholder, entry.replacement);
  47. return input;
  48. }
  49. static std::string translatePlural(int amount, const std::string& baseTextID)
  50. {
  51. if(amount == 1)
  52. return LIBRARY->generaltexth->translate(baseTextID + ".1");
  53. return LIBRARY->generaltexth->translate(baseTextID);
  54. }
  55. static std::string formatPluralImpl(int amount, const std::string & amountString, const std::string & baseTextID)
  56. {
  57. std::string baseString = translatePlural(amount, baseTextID);
  58. TextReplacementList replacements {
  59. { "%d", amountString }
  60. };
  61. return replacePlaceholders(baseString, replacements);
  62. }
  63. static std::string formatPlural(int amount, const std::string & baseTextID)
  64. {
  65. return formatPluralImpl(amount, std::to_string(amount), baseTextID);
  66. }
  67. static std::string formatPlural(DamageRange range, const std::string & baseTextID)
  68. {
  69. if (range.min == range.max)
  70. return formatPlural(range.min, baseTextID);
  71. std::string rangeString = std::to_string(range.min) + " - " + std::to_string(range.max);
  72. return formatPluralImpl(range.max, rangeString, baseTextID);
  73. }
  74. static std::string formatAttack(const DamageEstimation & estimation, const std::string & creatureName, const std::string & baseTextID, int shotsLeft)
  75. {
  76. TextReplacementList replacements = {
  77. { "%CREATURE", creatureName },
  78. { "%DAMAGE", formatPlural(estimation.damage, "vcmi.battleWindow.damageEstimation.damage") },
  79. { "%SHOTS", formatPlural(shotsLeft, "vcmi.battleWindow.damageEstimation.shots") },
  80. { "%KILLS", formatPlural(estimation.kills, "vcmi.battleWindow.damageEstimation.kills") },
  81. };
  82. return replacePlaceholders(LIBRARY->generaltexth->translate(baseTextID), replacements);
  83. }
  84. static std::string formatMeleeAttack(const DamageEstimation & estimation, const std::string & creatureName)
  85. {
  86. std::string baseTextID = estimation.kills.max == 0 ?
  87. "vcmi.battleWindow.damageEstimation.melee" :
  88. "vcmi.battleWindow.damageEstimation.meleeKills";
  89. return formatAttack(estimation, creatureName, baseTextID, 0);
  90. }
  91. static std::string formatRangedAttack(const DamageEstimation & estimation, const std::string & creatureName, int shotsLeft)
  92. {
  93. std::string baseTextID = estimation.kills.max == 0 ?
  94. "vcmi.battleWindow.damageEstimation.ranged" :
  95. "vcmi.battleWindow.damageEstimation.rangedKills";
  96. return formatAttack(estimation, creatureName, baseTextID, shotsLeft);
  97. }
  98. static std::string formatRetaliation(const DamageEstimation & estimation, bool mayBeKilled)
  99. {
  100. if (estimation.damage.max == 0)
  101. return LIBRARY->generaltexth->translate("vcmi.battleWindow.damageRetaliation.never");
  102. std::string baseTextID = estimation.kills.max == 0 ?
  103. "vcmi.battleWindow.damageRetaliation.damage" :
  104. "vcmi.battleWindow.damageRetaliation.damageKills";
  105. std::string prefixTextID = mayBeKilled ?
  106. "vcmi.battleWindow.damageRetaliation.may" :
  107. "vcmi.battleWindow.damageRetaliation.will";
  108. return LIBRARY->generaltexth->translate(prefixTextID) + formatAttack(estimation, "", baseTextID, 0);
  109. }
  110. BattleActionsController::BattleActionsController(BattleInterface & owner):
  111. owner(owner),
  112. selectedStack(nullptr),
  113. heroSpellToCast(nullptr)
  114. {
  115. }
  116. void BattleActionsController::endCastingSpell()
  117. {
  118. if(heroSpellToCast)
  119. {
  120. heroSpellToCast.reset();
  121. owner.windowObject->blockUI(false);
  122. }
  123. if(owner.stacksController->getActiveStack())
  124. {
  125. possibleActions = getPossibleActionsForStack(owner.stacksController->getActiveStack()); //restore actions after they were cleared
  126. owner.windowObject->setPossibleActions(possibleActions);
  127. }
  128. selectedStack = nullptr;
  129. ENGINE->fakeMouseMove();
  130. }
  131. bool BattleActionsController::isActiveStackSpellcaster() const
  132. {
  133. const CStack * casterStack = owner.stacksController->getActiveStack();
  134. if (!casterStack)
  135. return false;
  136. bool spellcaster = casterStack->hasBonusOfType(BonusType::SPELLCASTER);
  137. return (spellcaster && casterStack->canCast());
  138. }
  139. void BattleActionsController::enterCreatureCastingMode()
  140. {
  141. //silently check for possible errors
  142. if (owner.tacticsMode)
  143. return;
  144. //hero is casting a spell
  145. if (heroSpellToCast)
  146. return;
  147. if (!owner.stacksController->getActiveStack())
  148. return;
  149. if(owner.getBattle()->battleCanTargetEmptyHex(owner.stacksController->getActiveStack()))
  150. {
  151. auto actionFilterPredicate = [](const PossiblePlayerBattleAction x)
  152. {
  153. return x.get() != PossiblePlayerBattleAction::SHOOT;
  154. };
  155. vstd::erase_if(possibleActions, actionFilterPredicate);
  156. ENGINE->fakeMouseMove();
  157. return;
  158. }
  159. if (!isActiveStackSpellcaster())
  160. return;
  161. for(const auto & action : possibleActions)
  162. {
  163. if (action.get() != PossiblePlayerBattleAction::NO_LOCATION)
  164. continue;
  165. const spells::Caster * caster = owner.stacksController->getActiveStack();
  166. const CSpell * spell = action.spell().toSpell();
  167. spells::Target target;
  168. target.emplace_back();
  169. spells::BattleCast cast(owner.getBattle().get(), caster, spells::Mode::CREATURE_ACTIVE, spell);
  170. auto m = spell->battleMechanics(&cast);
  171. spells::detail::ProblemImpl ignored;
  172. const bool isCastingPossible = m->canBeCastAt(target, ignored);
  173. if (isCastingPossible)
  174. {
  175. owner.giveCommand(EActionType::MONSTER_SPELL, BattleHex::INVALID, spell->getId());
  176. selectedStack = nullptr;
  177. ENGINE->cursor().set(Cursor::Combat::POINTER);
  178. }
  179. return;
  180. }
  181. possibleActions = getPossibleActionsForStack(owner.stacksController->getActiveStack());
  182. auto actionFilterPredicate = [](const PossiblePlayerBattleAction x)
  183. {
  184. return !x.spellcast();
  185. };
  186. vstd::erase_if(possibleActions, actionFilterPredicate);
  187. ENGINE->fakeMouseMove();
  188. }
  189. std::vector<PossiblePlayerBattleAction> BattleActionsController::getPossibleActionsForStack(const CStack *stack) const
  190. {
  191. BattleClientInterfaceData data; //hard to get rid of these things so for now they're required data to pass
  192. for(const auto & spell : creatureSpells)
  193. data.creatureSpellsToCast.push_back(spell->id);
  194. data.tacticsMode = owner.tacticsMode;
  195. auto allActions = owner.getBattle()->getClientActionsForStack(stack, data);
  196. allActions.push_back(PossiblePlayerBattleAction::HERO_INFO);
  197. allActions.push_back(PossiblePlayerBattleAction::CREATURE_INFO);
  198. return std::vector<PossiblePlayerBattleAction>(allActions);
  199. }
  200. void BattleActionsController::reorderPossibleActionsPriority(const CStack * stack, const CStack * targetStack)
  201. {
  202. if(owner.tacticsMode || possibleActions.empty()) return; //this function is not supposed to be called in tactics mode or before getPossibleActionsForStack
  203. auto assignPriority = [&](const PossiblePlayerBattleAction & item
  204. ) -> uint8_t //large lambda assigning priority which would have to be part of possibleActions without it
  205. {
  206. switch(item.get())
  207. {
  208. case PossiblePlayerBattleAction::AIMED_SPELL_CREATURE:
  209. case PossiblePlayerBattleAction::ANY_LOCATION:
  210. case PossiblePlayerBattleAction::NO_LOCATION:
  211. case PossiblePlayerBattleAction::FREE_LOCATION:
  212. case PossiblePlayerBattleAction::OBSTACLE:
  213. case PossiblePlayerBattleAction::SACRIFICE:
  214. if(!stack->hasBonusOfType(BonusType::NO_SPELLCAST_BY_DEFAULT) && targetStack != nullptr)
  215. {
  216. PlayerColor stackOwner = owner.getBattle()->battleGetOwner(targetStack);
  217. bool enemyTargetingPositiveSpellcast = item.spell().toSpell()->isPositive() && stackOwner != owner.curInt->playerID;
  218. bool friendTargetingNegativeSpellcast = item.spell().toSpell()->isNegative() && stackOwner == owner.curInt->playerID;
  219. if(!enemyTargetingPositiveSpellcast && !friendTargetingNegativeSpellcast)
  220. return 1;
  221. }
  222. return 100; //bottom priority
  223. break;
  224. case PossiblePlayerBattleAction::RANDOM_GENIE_SPELL:
  225. return 2;
  226. break;
  227. case PossiblePlayerBattleAction::SHOOT:
  228. if(targetStack == nullptr || targetStack->unitSide() == stack->unitSide() || !targetStack->alive())
  229. return 100; //bottom priority
  230. return 4;
  231. break;
  232. case PossiblePlayerBattleAction::ATTACK_AND_RETURN:
  233. return 5;
  234. break;
  235. case PossiblePlayerBattleAction::ATTACK:
  236. return 6;
  237. break;
  238. case PossiblePlayerBattleAction::WALK_AND_ATTACK:
  239. return 7;
  240. break;
  241. case PossiblePlayerBattleAction::MOVE_STACK:
  242. return 8;
  243. break;
  244. case PossiblePlayerBattleAction::CATAPULT:
  245. return 9;
  246. break;
  247. case PossiblePlayerBattleAction::HEAL:
  248. return 10;
  249. break;
  250. case PossiblePlayerBattleAction::CREATURE_INFO:
  251. return 11;
  252. break;
  253. case PossiblePlayerBattleAction::HERO_INFO:
  254. return 12;
  255. break;
  256. case PossiblePlayerBattleAction::TELEPORT:
  257. return 13;
  258. break;
  259. default:
  260. assert(0);
  261. return 200;
  262. break;
  263. }
  264. };
  265. auto comparer = [&](const PossiblePlayerBattleAction & lhs, const PossiblePlayerBattleAction & rhs)
  266. {
  267. return assignPriority(lhs) < assignPriority(rhs);
  268. };
  269. std::sort(possibleActions.begin(), possibleActions.end(), comparer);
  270. }
  271. void BattleActionsController::castThisSpell(SpellID spellID)
  272. {
  273. heroSpellToCast = std::make_shared<BattleAction>();
  274. heroSpellToCast->actionType = EActionType::HERO_SPELL;
  275. heroSpellToCast->spell = spellID;
  276. heroSpellToCast->stackNumber = -1;
  277. heroSpellToCast->side = owner.curInt->cb->getBattle(owner.getBattleID())->battleGetMySide();
  278. //choosing possible targets
  279. const CGHeroInstance *castingHero = (owner.attackingHeroInstance->tempOwner == owner.curInt->playerID) ? owner.attackingHeroInstance : owner.defendingHeroInstance;
  280. assert(castingHero); // code below assumes non-null hero
  281. PossiblePlayerBattleAction spellSelMode = owner.getBattle()->getCasterAction(spellID.toSpell(), castingHero, spells::Mode::HERO);
  282. if (spellSelMode.get() == PossiblePlayerBattleAction::NO_LOCATION) //user does not have to select location
  283. {
  284. heroSpellToCast->aimToHex(BattleHex::INVALID);
  285. owner.curInt->cb->battleMakeSpellAction(owner.getBattleID(), *heroSpellToCast);
  286. endCastingSpell();
  287. }
  288. else
  289. {
  290. possibleActions.clear();
  291. possibleActions.push_back (spellSelMode); //only this one action can be performed at the moment
  292. ENGINE->fakeMouseMove();//update cursor
  293. }
  294. owner.windowObject->blockUI(true);
  295. }
  296. const CSpell * BattleActionsController::getHeroSpellToCast( ) const
  297. {
  298. if (heroSpellToCast)
  299. return heroSpellToCast->spell.toSpell();
  300. return nullptr;
  301. }
  302. const CSpell * BattleActionsController::getStackSpellToCast(const BattleHex & hoveredHex)
  303. {
  304. if (heroSpellToCast)
  305. return nullptr;
  306. if (!owner.stacksController->getActiveStack())
  307. return nullptr;
  308. if (!hoveredHex.isValid())
  309. return nullptr;
  310. auto action = selectAction(hoveredHex);
  311. if(owner.stacksController->getActiveStack()->hasBonusOfType(BonusType::SPELL_LIKE_ATTACK))
  312. {
  313. auto bonus = owner.stacksController->getActiveStack()->getBonus(Selector::type()(BonusType::SPELL_LIKE_ATTACK));
  314. return bonus->subtype.as<SpellID>().toSpell();
  315. }
  316. if (action.spell() == SpellID::NONE)
  317. return nullptr;
  318. return action.spell().toSpell();
  319. }
  320. const CSpell * BattleActionsController::getCurrentSpell(const BattleHex & hoveredHex)
  321. {
  322. if (getHeroSpellToCast())
  323. return getHeroSpellToCast();
  324. return getStackSpellToCast(hoveredHex);
  325. }
  326. const CStack * BattleActionsController::getStackForHex(const BattleHex & hoveredHex)
  327. {
  328. const CStack * shere = owner.getBattle()->battleGetStackByPos(hoveredHex, true);
  329. if(shere)
  330. return shere;
  331. return owner.getBattle()->battleGetStackByPos(hoveredHex, false);
  332. }
  333. void BattleActionsController::actionSetCursor(PossiblePlayerBattleAction action, const BattleHex & targetHex)
  334. {
  335. switch (action.get())
  336. {
  337. case PossiblePlayerBattleAction::CHOOSE_TACTICS_STACK:
  338. ENGINE->cursor().set(Cursor::Combat::POINTER);
  339. return;
  340. case PossiblePlayerBattleAction::MOVE_TACTICS:
  341. case PossiblePlayerBattleAction::MOVE_STACK:
  342. if (owner.stacksController->getActiveStack()->hasBonusOfType(BonusType::FLYING))
  343. ENGINE->cursor().set(Cursor::Combat::FLY);
  344. else
  345. ENGINE->cursor().set(Cursor::Combat::MOVE);
  346. return;
  347. case PossiblePlayerBattleAction::ATTACK:
  348. case PossiblePlayerBattleAction::WALK_AND_ATTACK:
  349. case PossiblePlayerBattleAction::ATTACK_AND_RETURN:
  350. {
  351. static const std::map<BattleHex::EDir, Cursor::Combat> sectorCursor = {
  352. {BattleHex::TOP_LEFT, Cursor::Combat::HIT_SOUTHEAST},
  353. {BattleHex::TOP_RIGHT, Cursor::Combat::HIT_SOUTHWEST},
  354. {BattleHex::RIGHT, Cursor::Combat::HIT_WEST },
  355. {BattleHex::BOTTOM_RIGHT, Cursor::Combat::HIT_NORTHWEST},
  356. {BattleHex::BOTTOM_LEFT, Cursor::Combat::HIT_NORTHEAST},
  357. {BattleHex::LEFT, Cursor::Combat::HIT_EAST },
  358. {BattleHex::TOP, Cursor::Combat::HIT_SOUTH },
  359. {BattleHex::BOTTOM, Cursor::Combat::HIT_NORTH }
  360. };
  361. auto direction = owner.fieldController->selectAttackDirection(targetHex);
  362. assert(sectorCursor.count(direction) > 0);
  363. if (sectorCursor.count(direction))
  364. ENGINE->cursor().set(sectorCursor.at(direction));
  365. return;
  366. }
  367. case PossiblePlayerBattleAction::SHOOT:
  368. if (owner.getBattle()->battleHasShootingPenalty(owner.stacksController->getActiveStack(), targetHex))
  369. ENGINE->cursor().set(Cursor::Combat::SHOOT_PENALTY);
  370. else
  371. ENGINE->cursor().set(Cursor::Combat::SHOOT);
  372. return;
  373. case PossiblePlayerBattleAction::AIMED_SPELL_CREATURE:
  374. case PossiblePlayerBattleAction::ANY_LOCATION:
  375. case PossiblePlayerBattleAction::RANDOM_GENIE_SPELL:
  376. case PossiblePlayerBattleAction::FREE_LOCATION:
  377. case PossiblePlayerBattleAction::OBSTACLE:
  378. ENGINE->cursor().set(Cursor::Spellcast::SPELL);
  379. return;
  380. case PossiblePlayerBattleAction::TELEPORT:
  381. ENGINE->cursor().set(Cursor::Combat::TELEPORT);
  382. return;
  383. case PossiblePlayerBattleAction::SACRIFICE:
  384. ENGINE->cursor().set(Cursor::Combat::SACRIFICE);
  385. return;
  386. case PossiblePlayerBattleAction::HEAL:
  387. ENGINE->cursor().set(Cursor::Combat::HEAL);
  388. return;
  389. case PossiblePlayerBattleAction::CATAPULT:
  390. ENGINE->cursor().set(Cursor::Combat::SHOOT_CATAPULT);
  391. return;
  392. case PossiblePlayerBattleAction::CREATURE_INFO:
  393. ENGINE->cursor().set(Cursor::Combat::QUERY);
  394. return;
  395. case PossiblePlayerBattleAction::HERO_INFO:
  396. ENGINE->cursor().set(Cursor::Combat::HERO);
  397. return;
  398. }
  399. assert(0);
  400. }
  401. void BattleActionsController::actionSetCursorBlocked(PossiblePlayerBattleAction action, const BattleHex & targetHex)
  402. {
  403. switch (action.get())
  404. {
  405. case PossiblePlayerBattleAction::AIMED_SPELL_CREATURE:
  406. case PossiblePlayerBattleAction::RANDOM_GENIE_SPELL:
  407. case PossiblePlayerBattleAction::TELEPORT:
  408. case PossiblePlayerBattleAction::SACRIFICE:
  409. case PossiblePlayerBattleAction::FREE_LOCATION:
  410. ENGINE->cursor().set(Cursor::Combat::BLOCKED);
  411. return;
  412. default:
  413. if (targetHex == -1)
  414. ENGINE->cursor().set(Cursor::Combat::POINTER);
  415. else
  416. ENGINE->cursor().set(Cursor::Combat::BLOCKED);
  417. return;
  418. }
  419. assert(0);
  420. }
  421. std::string BattleActionsController::actionGetStatusMessage(PossiblePlayerBattleAction action, const BattleHex & targetHex)
  422. {
  423. const CStack * targetStack = getStackForHex(targetHex);
  424. switch (action.get()) //display console message, realize selected action
  425. {
  426. case PossiblePlayerBattleAction::CHOOSE_TACTICS_STACK:
  427. return (boost::format(LIBRARY->generaltexth->allTexts[481]) % targetStack->getName()).str(); //Select %s
  428. case PossiblePlayerBattleAction::MOVE_TACTICS:
  429. case PossiblePlayerBattleAction::MOVE_STACK:
  430. if (owner.stacksController->getActiveStack()->hasBonusOfType(BonusType::FLYING))
  431. return (boost::format(LIBRARY->generaltexth->allTexts[295]) % owner.stacksController->getActiveStack()->getName()).str(); //Fly %s here
  432. else
  433. return (boost::format(LIBRARY->generaltexth->allTexts[294]) % owner.stacksController->getActiveStack()->getName()).str(); //Move %s here
  434. case PossiblePlayerBattleAction::ATTACK:
  435. case PossiblePlayerBattleAction::WALK_AND_ATTACK:
  436. case PossiblePlayerBattleAction::ATTACK_AND_RETURN: //TODO: allow to disable return
  437. {
  438. const auto * attacker = owner.stacksController->getActiveStack();
  439. BattleHex attackFromHex = owner.fieldController->fromWhichHexAttack(targetHex);
  440. int distance = attacker->position.isValid() ? owner.getBattle()->battleGetDistances(attacker, attacker->getPosition())[attackFromHex.toInt()] : 0;
  441. DamageEstimation retaliation;
  442. BattleAttackInfo attackInfo(attacker, targetStack, distance, false );
  443. attackInfo.attackerPos = attackFromHex;
  444. DamageEstimation estimation = owner.getBattle()->battleEstimateDamage(attackInfo, &retaliation);
  445. estimation.kills.max = std::min<int64_t>(estimation.kills.max, targetStack->getCount());
  446. estimation.kills.min = std::min<int64_t>(estimation.kills.min, targetStack->getCount());
  447. bool enemyMayBeKilled = estimation.kills.max == targetStack->getCount();
  448. return formatMeleeAttack(estimation, targetStack->getName()) + "\n" + formatRetaliation(retaliation, enemyMayBeKilled);
  449. }
  450. case PossiblePlayerBattleAction::SHOOT:
  451. {
  452. if(targetStack == nullptr) //should be true only for spell-like attack
  453. {
  454. auto spellLikeAttackBonus = owner.stacksController->getActiveStack()->getBonus(Selector::type()(BonusType::SPELL_LIKE_ATTACK));
  455. assert(spellLikeAttackBonus != nullptr);
  456. return boost::str(boost::format(LIBRARY->generaltexth->allTexts[26]) % spellLikeAttackBonus->subtype.as<SpellID>().toSpell()->getNameTranslated());
  457. }
  458. const auto * shooter = owner.stacksController->getActiveStack();
  459. DamageEstimation retaliation;
  460. BattleAttackInfo attackInfo(shooter, targetStack, 0, true );
  461. DamageEstimation estimation = owner.getBattle()->battleEstimateDamage(attackInfo, &retaliation);
  462. estimation.kills.max = std::min<int64_t>(estimation.kills.max, targetStack->getCount());
  463. estimation.kills.min = std::min<int64_t>(estimation.kills.min, targetStack->getCount());
  464. return formatRangedAttack(estimation, targetStack->getName(), shooter->shots.available());
  465. }
  466. case PossiblePlayerBattleAction::AIMED_SPELL_CREATURE:
  467. return boost::str(boost::format(LIBRARY->generaltexth->allTexts[27]) % action.spell().toSpell()->getNameTranslated() % targetStack->getName()); //Cast %s on %s
  468. case PossiblePlayerBattleAction::ANY_LOCATION:
  469. return boost::str(boost::format(LIBRARY->generaltexth->allTexts[26]) % action.spell().toSpell()->getNameTranslated()); //Cast %s
  470. case PossiblePlayerBattleAction::RANDOM_GENIE_SPELL: //we assume that teleport / sacrifice will never be available as random spell
  471. return boost::str(boost::format(LIBRARY->generaltexth->allTexts[301]) % targetStack->getName()); //Cast a spell on %
  472. case PossiblePlayerBattleAction::TELEPORT:
  473. return LIBRARY->generaltexth->allTexts[25]; //Teleport Here
  474. case PossiblePlayerBattleAction::OBSTACLE:
  475. return LIBRARY->generaltexth->allTexts[550];
  476. case PossiblePlayerBattleAction::SACRIFICE:
  477. return (boost::format(LIBRARY->generaltexth->allTexts[549]) % targetStack->getName()).str(); //sacrifice the %s
  478. case PossiblePlayerBattleAction::FREE_LOCATION:
  479. return boost::str(boost::format(LIBRARY->generaltexth->allTexts[26]) % action.spell().toSpell()->getNameTranslated()); //Cast %s
  480. case PossiblePlayerBattleAction::HEAL:
  481. return (boost::format(LIBRARY->generaltexth->allTexts[419]) % targetStack->getName()).str(); //Apply first aid to the %s
  482. case PossiblePlayerBattleAction::CATAPULT:
  483. return ""; // TODO
  484. case PossiblePlayerBattleAction::CREATURE_INFO:
  485. return (boost::format(LIBRARY->generaltexth->allTexts[297]) % targetStack->getName()).str();
  486. case PossiblePlayerBattleAction::HERO_INFO:
  487. return LIBRARY->generaltexth->translate("core.genrltxt.417"); // "View Hero Stats"
  488. }
  489. assert(0);
  490. return "";
  491. }
  492. std::string BattleActionsController::actionGetStatusMessageBlocked(PossiblePlayerBattleAction action, const BattleHex & targetHex)
  493. {
  494. switch (action.get())
  495. {
  496. case PossiblePlayerBattleAction::AIMED_SPELL_CREATURE:
  497. case PossiblePlayerBattleAction::RANDOM_GENIE_SPELL:
  498. return LIBRARY->generaltexth->allTexts[23];
  499. break;
  500. case PossiblePlayerBattleAction::TELEPORT:
  501. return LIBRARY->generaltexth->allTexts[24]; //Invalid Teleport Destination
  502. break;
  503. case PossiblePlayerBattleAction::SACRIFICE:
  504. return LIBRARY->generaltexth->allTexts[543]; //choose army to sacrifice
  505. break;
  506. case PossiblePlayerBattleAction::FREE_LOCATION:
  507. return boost::str(boost::format(LIBRARY->generaltexth->allTexts[181]) % action.spell().toSpell()->getNameTranslated()); //No room to place %s here
  508. break;
  509. default:
  510. return "";
  511. }
  512. }
  513. bool BattleActionsController::actionIsLegal(PossiblePlayerBattleAction action, const BattleHex & targetHex)
  514. {
  515. const CStack * targetStack = getStackForHex(targetHex);
  516. bool targetStackOwned = targetStack && targetStack->unitOwner() == owner.curInt->playerID;
  517. switch (action.get())
  518. {
  519. case PossiblePlayerBattleAction::CHOOSE_TACTICS_STACK:
  520. return (targetStack && targetStackOwned && targetStack->getMovementRange() > 0);
  521. case PossiblePlayerBattleAction::CREATURE_INFO:
  522. return (targetStack && targetStack->alive());
  523. case PossiblePlayerBattleAction::HERO_INFO:
  524. if (targetHex == BattleHex::HERO_ATTACKER)
  525. return owner.attackingHero != nullptr;
  526. if (targetHex == BattleHex::HERO_DEFENDER)
  527. return owner.defendingHero != nullptr;
  528. return false;
  529. case PossiblePlayerBattleAction::MOVE_TACTICS:
  530. case PossiblePlayerBattleAction::MOVE_STACK:
  531. if (!(targetStack && targetStack->alive())) //we can walk on dead stacks
  532. {
  533. if(canStackMoveHere(owner.stacksController->getActiveStack(), targetHex))
  534. return true;
  535. }
  536. return false;
  537. case PossiblePlayerBattleAction::ATTACK:
  538. case PossiblePlayerBattleAction::WALK_AND_ATTACK:
  539. case PossiblePlayerBattleAction::ATTACK_AND_RETURN:
  540. {
  541. if (owner.fieldController->isTileAttackable(targetHex)) // move isTileAttackable to be part of battleCanAttack?
  542. {
  543. BattleHex attackFromHex = owner.fieldController->fromWhichHexAttack(targetHex);
  544. if(owner.getBattle()->battleCanAttack(owner.stacksController->getActiveStack(), targetStack, attackFromHex))
  545. return true;
  546. }
  547. return false;
  548. }
  549. case PossiblePlayerBattleAction::SHOOT:
  550. {
  551. auto currentStack = owner.stacksController->getActiveStack();
  552. if(!owner.getBattle()->battleCanShoot(currentStack, targetHex))
  553. return false;
  554. if(targetStack == nullptr && owner.getBattle()->battleCanTargetEmptyHex(currentStack))
  555. {
  556. auto spellLikeAttackBonus = currentStack->getBonus(Selector::type()(BonusType::SPELL_LIKE_ATTACK));
  557. const CSpell * spellDataToCheck = spellLikeAttackBonus->subtype.as<SpellID>().toSpell();
  558. return isCastingPossibleHere(spellDataToCheck, nullptr, targetHex);
  559. }
  560. return true;
  561. }
  562. case PossiblePlayerBattleAction::NO_LOCATION:
  563. return false;
  564. case PossiblePlayerBattleAction::ANY_LOCATION:
  565. return isCastingPossibleHere(action.spell().toSpell(), nullptr, targetHex);
  566. case PossiblePlayerBattleAction::AIMED_SPELL_CREATURE:
  567. return !selectedStack && targetStack && isCastingPossibleHere(action.spell().toSpell(), nullptr, targetHex);
  568. case PossiblePlayerBattleAction::RANDOM_GENIE_SPELL:
  569. if(targetStack && targetStackOwned && targetStack != owner.stacksController->getActiveStack() && targetStack->alive()) //only positive spells for other allied creatures
  570. {
  571. SpellID spellID = owner.getBattle()->getRandomBeneficialSpell(CRandomGenerator::getDefault(), owner.stacksController->getActiveStack(), targetStack);
  572. return spellID != SpellID::NONE;
  573. }
  574. return false;
  575. case PossiblePlayerBattleAction::TELEPORT:
  576. return selectedStack && isCastingPossibleHere(action.spell().toSpell(), selectedStack, targetHex);
  577. case PossiblePlayerBattleAction::SACRIFICE: //choose our living stack to sacrifice
  578. {
  579. if(!targetStack)
  580. return false;
  581. auto unit = targetStack->acquire();
  582. return targetStack != selectedStack && targetStackOwned && targetStack->alive()
  583. && unit->isLiving() && !unit->hasBonusOfType(BonusType::MECHANICAL);
  584. }
  585. case PossiblePlayerBattleAction::OBSTACLE:
  586. case PossiblePlayerBattleAction::FREE_LOCATION:
  587. return isCastingPossibleHere(action.spell().toSpell(), nullptr, targetHex);
  588. case PossiblePlayerBattleAction::CATAPULT:
  589. return owner.siegeController && owner.siegeController->isAttackableByCatapult(targetHex);
  590. case PossiblePlayerBattleAction::HEAL:
  591. return targetStack && targetStackOwned && targetStack->canBeHealed();
  592. }
  593. assert(0);
  594. return false;
  595. }
  596. void BattleActionsController::actionRealize(PossiblePlayerBattleAction action, const BattleHex & targetHex)
  597. {
  598. const CStack * targetStack = getStackForHex(targetHex);
  599. switch (action.get()) //display console message, realize selected action
  600. {
  601. case PossiblePlayerBattleAction::CHOOSE_TACTICS_STACK:
  602. {
  603. owner.stackActivated(targetStack);
  604. return;
  605. }
  606. case PossiblePlayerBattleAction::MOVE_TACTICS:
  607. case PossiblePlayerBattleAction::MOVE_STACK:
  608. {
  609. const auto * activeStack = owner.stacksController->getActiveStack();
  610. if(activeStack->doubleWide())
  611. {
  612. BattleHexArray availableHexes = owner.getBattle()->battleGetAvailableHexes(activeStack, false);
  613. BattleHex shiftedDest = targetHex.cloneInDirection(activeStack->destShiftDir(), false);
  614. const bool canMoveHeadHere = availableHexes.contains(targetHex);
  615. const bool canMoveTailHere = availableHexes.contains(shiftedDest);
  616. const bool backwardsMove = activeStack->unitSide() == BattleSide::ATTACKER ?
  617. targetHex.getX() < activeStack->getPosition().getX():
  618. targetHex.getX() > activeStack->getPosition().getX();
  619. if(canMoveTailHere && (backwardsMove || !canMoveHeadHere))
  620. owner.giveCommand(EActionType::WALK, shiftedDest);
  621. else
  622. owner.giveCommand(EActionType::WALK, targetHex);
  623. }
  624. else
  625. {
  626. owner.giveCommand(EActionType::WALK, targetHex);
  627. }
  628. return;
  629. }
  630. case PossiblePlayerBattleAction::ATTACK:
  631. case PossiblePlayerBattleAction::WALK_AND_ATTACK:
  632. case PossiblePlayerBattleAction::ATTACK_AND_RETURN: //TODO: allow to disable return
  633. {
  634. bool returnAfterAttack = action.get() == PossiblePlayerBattleAction::ATTACK_AND_RETURN;
  635. BattleHex attackFromHex = owner.fieldController->fromWhichHexAttack(targetHex);
  636. if(attackFromHex.isValid()) //we can be in this line when unreachable creature is L - clicked (as of revision 1308)
  637. {
  638. BattleAction command = BattleAction::makeMeleeAttack(owner.stacksController->getActiveStack(), targetHex, attackFromHex, returnAfterAttack);
  639. owner.sendCommand(command, owner.stacksController->getActiveStack());
  640. }
  641. return;
  642. }
  643. case PossiblePlayerBattleAction::SHOOT:
  644. {
  645. owner.giveCommand(EActionType::SHOOT, targetHex);
  646. return;
  647. }
  648. case PossiblePlayerBattleAction::HEAL:
  649. {
  650. owner.giveCommand(EActionType::STACK_HEAL, targetHex);
  651. return;
  652. };
  653. case PossiblePlayerBattleAction::CATAPULT:
  654. {
  655. owner.giveCommand(EActionType::CATAPULT, targetHex);
  656. return;
  657. }
  658. case PossiblePlayerBattleAction::CREATURE_INFO:
  659. {
  660. ENGINE->windows().createAndPushWindow<CStackWindow>(targetStack, false);
  661. return;
  662. }
  663. case PossiblePlayerBattleAction::HERO_INFO:
  664. {
  665. if (targetHex == BattleHex::HERO_ATTACKER)
  666. owner.attackingHero->heroLeftClicked();
  667. if (targetHex == BattleHex::HERO_DEFENDER)
  668. owner.defendingHero->heroLeftClicked();
  669. return;
  670. }
  671. case PossiblePlayerBattleAction::AIMED_SPELL_CREATURE:
  672. case PossiblePlayerBattleAction::ANY_LOCATION:
  673. case PossiblePlayerBattleAction::RANDOM_GENIE_SPELL: //we assume that teleport / sacrifice will never be available as random spell
  674. case PossiblePlayerBattleAction::TELEPORT:
  675. case PossiblePlayerBattleAction::OBSTACLE:
  676. case PossiblePlayerBattleAction::SACRIFICE:
  677. case PossiblePlayerBattleAction::FREE_LOCATION:
  678. {
  679. if (action.get() == PossiblePlayerBattleAction::AIMED_SPELL_CREATURE )
  680. {
  681. if (action.spell() == SpellID::SACRIFICE)
  682. {
  683. heroSpellToCast->aimToHex(targetHex);
  684. possibleActions.push_back({PossiblePlayerBattleAction::SACRIFICE, action.spell()});
  685. selectedStack = targetStack;
  686. return;
  687. }
  688. if (action.spell() == SpellID::TELEPORT)
  689. {
  690. heroSpellToCast->aimToUnit(targetStack);
  691. possibleActions.push_back({PossiblePlayerBattleAction::TELEPORT, action.spell()});
  692. selectedStack = targetStack;
  693. return;
  694. }
  695. }
  696. if (!heroSpellcastingModeActive())
  697. {
  698. if (action.spell().hasValue())
  699. {
  700. owner.giveCommand(EActionType::MONSTER_SPELL, targetHex, action.spell());
  701. }
  702. else //unknown random spell
  703. {
  704. owner.giveCommand(EActionType::MONSTER_SPELL, targetHex);
  705. }
  706. }
  707. else
  708. {
  709. assert(getHeroSpellToCast());
  710. switch (getHeroSpellToCast()->id.toEnum())
  711. {
  712. case SpellID::SACRIFICE:
  713. heroSpellToCast->aimToUnit(targetStack);//victim
  714. break;
  715. default:
  716. heroSpellToCast->aimToHex(targetHex);
  717. break;
  718. }
  719. owner.curInt->cb->battleMakeSpellAction(owner.getBattleID(), *heroSpellToCast);
  720. endCastingSpell();
  721. }
  722. selectedStack = nullptr;
  723. return;
  724. }
  725. }
  726. assert(0);
  727. return;
  728. }
  729. PossiblePlayerBattleAction BattleActionsController::selectAction(const BattleHex & targetHex)
  730. {
  731. assert(owner.stacksController->getActiveStack() != nullptr);
  732. assert(!possibleActions.empty());
  733. assert(targetHex.isValid());
  734. if (owner.stacksController->getActiveStack() == nullptr)
  735. return PossiblePlayerBattleAction::INVALID;
  736. if (possibleActions.empty())
  737. return PossiblePlayerBattleAction::INVALID;
  738. const CStack * targetStack = getStackForHex(targetHex);
  739. reorderPossibleActionsPriority(owner.stacksController->getActiveStack(), targetStack);
  740. for (PossiblePlayerBattleAction action : possibleActions)
  741. {
  742. if (actionIsLegal(action, targetHex))
  743. return action;
  744. }
  745. return possibleActions.front();
  746. }
  747. void BattleActionsController::onHexHovered(const BattleHex & hoveredHex)
  748. {
  749. if (owner.openingPlaying())
  750. {
  751. currentConsoleMsg = LIBRARY->generaltexth->translate("vcmi.battleWindow.pressKeyToSkipIntro");
  752. ENGINE->statusbar()->write(currentConsoleMsg);
  753. return;
  754. }
  755. if (owner.stacksController->getActiveStack() == nullptr)
  756. return;
  757. if (hoveredHex == BattleHex::INVALID)
  758. {
  759. if (!currentConsoleMsg.empty())
  760. ENGINE->statusbar()->clearIfMatching(currentConsoleMsg);
  761. currentConsoleMsg.clear();
  762. ENGINE->cursor().set(Cursor::Combat::BLOCKED);
  763. return;
  764. }
  765. auto action = selectAction(hoveredHex);
  766. std::string newConsoleMsg;
  767. if (actionIsLegal(action, hoveredHex))
  768. {
  769. actionSetCursor(action, hoveredHex);
  770. newConsoleMsg = actionGetStatusMessage(action, hoveredHex);
  771. }
  772. else
  773. {
  774. actionSetCursorBlocked(action, hoveredHex);
  775. newConsoleMsg = actionGetStatusMessageBlocked(action, hoveredHex);
  776. }
  777. if (!currentConsoleMsg.empty())
  778. ENGINE->statusbar()->clearIfMatching(currentConsoleMsg);
  779. if (!newConsoleMsg.empty())
  780. ENGINE->statusbar()->write(newConsoleMsg);
  781. currentConsoleMsg = newConsoleMsg;
  782. }
  783. void BattleActionsController::onHoverEnded()
  784. {
  785. ENGINE->cursor().set(Cursor::Combat::POINTER);
  786. if (!currentConsoleMsg.empty())
  787. ENGINE->statusbar()->clearIfMatching(currentConsoleMsg);
  788. currentConsoleMsg.clear();
  789. }
  790. void BattleActionsController::onHexLeftClicked(const BattleHex & clickedHex)
  791. {
  792. if (owner.stacksController->getActiveStack() == nullptr)
  793. return;
  794. auto action = selectAction(clickedHex);
  795. std::string newConsoleMsg;
  796. if (!actionIsLegal(action, clickedHex))
  797. return;
  798. actionRealize(action, clickedHex);
  799. ENGINE->statusbar()->clear();
  800. }
  801. void BattleActionsController::tryActivateStackSpellcasting(const CStack *casterStack)
  802. {
  803. creatureSpells.clear();
  804. bool spellcaster = casterStack->hasBonusOfType(BonusType::SPELLCASTER);
  805. if(casterStack->canCast() && spellcaster)
  806. {
  807. // faerie dragon can cast only one, randomly selected spell until their next move
  808. //TODO: faerie dragon type spell should be selected by server
  809. const auto spellToCast = owner.getBattle()->getRandomCastedSpell(CRandomGenerator::getDefault(), casterStack);
  810. if (spellToCast.hasValue())
  811. creatureSpells.push_back(spellToCast.toSpell());
  812. }
  813. TConstBonusListPtr bl = casterStack->getBonusesOfType(BonusType::SPELLCASTER);
  814. for(const auto & bonus : *bl)
  815. {
  816. if (bonus->additionalInfo[0] <= 0 && bonus->subtype.as<SpellID>().hasValue())
  817. creatureSpells.push_back(bonus->subtype.as<SpellID>().toSpell());
  818. }
  819. }
  820. const spells::Caster * BattleActionsController::getCurrentSpellcaster() const
  821. {
  822. if (heroSpellToCast)
  823. return owner.currentHero();
  824. else
  825. return owner.stacksController->getActiveStack();
  826. }
  827. spells::Mode BattleActionsController::getCurrentCastMode() const
  828. {
  829. if (heroSpellToCast)
  830. return spells::Mode::HERO;
  831. else
  832. return spells::Mode::CREATURE_ACTIVE;
  833. }
  834. bool BattleActionsController::isCastingPossibleHere(const CSpell * currentSpell, const CStack *targetStack, const BattleHex & targetHex)
  835. {
  836. assert(currentSpell);
  837. if (!currentSpell)
  838. return false;
  839. auto caster = getCurrentSpellcaster();
  840. const spells::Mode mode = heroSpellToCast ? spells::Mode::HERO : spells::Mode::CREATURE_ACTIVE;
  841. spells::Target target;
  842. if(targetStack)
  843. target.emplace_back(targetStack);
  844. target.emplace_back(targetHex);
  845. spells::BattleCast cast(owner.getBattle().get(), caster, mode, currentSpell);
  846. auto m = currentSpell->battleMechanics(&cast);
  847. spells::detail::ProblemImpl problem; //todo: display problem in status bar
  848. return m->canBeCastAt(target, problem);
  849. }
  850. bool BattleActionsController::canStackMoveHere(const CStack * stackToMove, const BattleHex & myNumber) const
  851. {
  852. BattleHexArray acc = owner.getBattle()->battleGetAvailableHexes(stackToMove, false);
  853. BattleHex shiftedDest = myNumber.cloneInDirection(stackToMove->destShiftDir(), false);
  854. if (acc.contains(myNumber))
  855. return true;
  856. else if (stackToMove->doubleWide() && acc.contains(shiftedDest))
  857. return true;
  858. else
  859. return false;
  860. }
  861. void BattleActionsController::activateStack()
  862. {
  863. const CStack * s = owner.stacksController->getActiveStack();
  864. if(s)
  865. {
  866. tryActivateStackSpellcasting(s);
  867. possibleActions = getPossibleActionsForStack(s);
  868. owner.windowObject->setPossibleActions(possibleActions);
  869. }
  870. }
  871. void BattleActionsController::onHexRightClicked(const BattleHex & clickedHex)
  872. {
  873. bool isCurrentStackInSpellcastMode = creatureSpellcastingModeActive();
  874. if (heroSpellcastingModeActive() || isCurrentStackInSpellcastMode)
  875. {
  876. endCastingSpell();
  877. CRClickPopup::createAndPush(LIBRARY->generaltexth->translate("core.genrltxt.731")); // spell cancelled
  878. return;
  879. }
  880. auto selectedStack = owner.getBattle()->battleGetStackByPos(clickedHex, true);
  881. if (selectedStack != nullptr)
  882. ENGINE->windows().createAndPushWindow<CStackWindow>(selectedStack, true);
  883. if (clickedHex == BattleHex::HERO_ATTACKER && owner.attackingHero)
  884. owner.attackingHero->heroRightClicked();
  885. if (clickedHex == BattleHex::HERO_DEFENDER && owner.defendingHero)
  886. owner.defendingHero->heroRightClicked();
  887. }
  888. bool BattleActionsController::heroSpellcastingModeActive() const
  889. {
  890. return heroSpellToCast != nullptr;
  891. }
  892. bool BattleActionsController::creatureSpellcastingModeActive() const
  893. {
  894. auto spellcastModePredicate = [](const PossiblePlayerBattleAction & action)
  895. {
  896. return action.spellcast() || action.get() == PossiblePlayerBattleAction::SHOOT; //for hotkey-eligible SPELL_LIKE_ATTACK creature should have only SHOOT action
  897. };
  898. return !possibleActions.empty() && std::all_of(possibleActions.begin(), possibleActions.end(), spellcastModePredicate);
  899. }
  900. bool BattleActionsController::currentActionSpellcasting(const BattleHex & hoveredHex)
  901. {
  902. if (heroSpellToCast)
  903. return true;
  904. if (!owner.stacksController->getActiveStack())
  905. return false;
  906. auto action = selectAction(hoveredHex);
  907. return action.spellcast();
  908. }
  909. const std::vector<PossiblePlayerBattleAction> & BattleActionsController::getPossibleActions() const
  910. {
  911. return possibleActions;
  912. }
  913. void BattleActionsController::setPriorityActions(const std::vector<PossiblePlayerBattleAction> & actions)
  914. {
  915. possibleActions = actions;
  916. }
  917. void BattleActionsController::resetCurrentStackPossibleActions()
  918. {
  919. possibleActions = getPossibleActionsForStack(owner.stacksController->getActiveStack());
  920. }