BattleActionsController.cpp 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111
  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. if(!stack->hasBonusOfType(BonusType::NO_SPELLCAST_BY_DEFAULT) && targetStack != nullptr)
  214. {
  215. PlayerColor stackOwner = owner.getBattle()->battleGetOwner(targetStack);
  216. bool enemyTargetingPositiveSpellcast = item.spell().toSpell()->isPositive() && stackOwner != owner.curInt->playerID;
  217. bool friendTargetingNegativeSpellcast = item.spell().toSpell()->isNegative() && stackOwner == owner.curInt->playerID;
  218. if(!enemyTargetingPositiveSpellcast && !friendTargetingNegativeSpellcast)
  219. return 1;
  220. }
  221. return 100; //bottom priority
  222. break;
  223. case PossiblePlayerBattleAction::RANDOM_GENIE_SPELL:
  224. return 2;
  225. break;
  226. case PossiblePlayerBattleAction::SHOOT:
  227. if(targetStack == nullptr || targetStack->unitSide() == stack->unitSide() || !targetStack->alive())
  228. return 100; //bottom priority
  229. return 4;
  230. break;
  231. case PossiblePlayerBattleAction::ATTACK_AND_RETURN:
  232. return 5;
  233. break;
  234. case PossiblePlayerBattleAction::ATTACK:
  235. return 6;
  236. break;
  237. case PossiblePlayerBattleAction::WALK_AND_ATTACK:
  238. return 7;
  239. break;
  240. case PossiblePlayerBattleAction::MOVE_STACK:
  241. return 8;
  242. break;
  243. case PossiblePlayerBattleAction::CATAPULT:
  244. return 9;
  245. break;
  246. case PossiblePlayerBattleAction::HEAL:
  247. return 10;
  248. break;
  249. case PossiblePlayerBattleAction::CREATURE_INFO:
  250. return 11;
  251. break;
  252. case PossiblePlayerBattleAction::HERO_INFO:
  253. return 12;
  254. break;
  255. case PossiblePlayerBattleAction::TELEPORT:
  256. return 13;
  257. break;
  258. default:
  259. assert(0);
  260. return 200;
  261. break;
  262. }
  263. };
  264. auto comparer = [&](const PossiblePlayerBattleAction & lhs, const PossiblePlayerBattleAction & rhs)
  265. {
  266. return assignPriority(lhs) < assignPriority(rhs);
  267. };
  268. std::sort(possibleActions.begin(), possibleActions.end(), comparer);
  269. }
  270. void BattleActionsController::castThisSpell(SpellID spellID)
  271. {
  272. heroSpellToCast = std::make_shared<BattleAction>();
  273. heroSpellToCast->actionType = EActionType::HERO_SPELL;
  274. heroSpellToCast->spell = spellID;
  275. heroSpellToCast->stackNumber = -1;
  276. heroSpellToCast->side = owner.curInt->cb->getBattle(owner.getBattleID())->battleGetMySide();
  277. //choosing possible targets
  278. const CGHeroInstance *castingHero = (owner.attackingHeroInstance->tempOwner == owner.curInt->playerID) ? owner.attackingHeroInstance : owner.defendingHeroInstance;
  279. assert(castingHero); // code below assumes non-null hero
  280. PossiblePlayerBattleAction spellSelMode = owner.getBattle()->getCasterAction(spellID.toSpell(), castingHero, spells::Mode::HERO);
  281. if (spellSelMode.get() == PossiblePlayerBattleAction::NO_LOCATION) //user does not have to select location
  282. {
  283. heroSpellToCast->aimToHex(BattleHex::INVALID);
  284. owner.curInt->cb->battleMakeSpellAction(owner.getBattleID(), *heroSpellToCast);
  285. endCastingSpell();
  286. }
  287. else
  288. {
  289. possibleActions.clear();
  290. possibleActions.push_back (spellSelMode); //only this one action can be performed at the moment
  291. ENGINE->fakeMouseMove();//update cursor
  292. }
  293. owner.windowObject->blockUI(true);
  294. }
  295. const CSpell * BattleActionsController::getHeroSpellToCast( ) const
  296. {
  297. if (heroSpellToCast)
  298. return heroSpellToCast->spell.toSpell();
  299. return nullptr;
  300. }
  301. const CSpell * BattleActionsController::getStackSpellToCast(const BattleHex & hoveredHex)
  302. {
  303. if (heroSpellToCast)
  304. return nullptr;
  305. if (!owner.stacksController->getActiveStack())
  306. return nullptr;
  307. if (!hoveredHex.isValid())
  308. return nullptr;
  309. auto action = selectAction(hoveredHex);
  310. if(owner.stacksController->getActiveStack()->hasBonusOfType(BonusType::SPELL_LIKE_ATTACK))
  311. {
  312. auto bonus = owner.stacksController->getActiveStack()->getBonus(Selector::type()(BonusType::SPELL_LIKE_ATTACK));
  313. return bonus->subtype.as<SpellID>().toSpell();
  314. }
  315. if (action.spell() == SpellID::NONE)
  316. return nullptr;
  317. return action.spell().toSpell();
  318. }
  319. const CSpell * BattleActionsController::getCurrentSpell(const BattleHex & hoveredHex)
  320. {
  321. if (getHeroSpellToCast())
  322. return getHeroSpellToCast();
  323. return getStackSpellToCast(hoveredHex);
  324. }
  325. const CStack * BattleActionsController::getStackForHex(const BattleHex & hoveredHex)
  326. {
  327. const CStack * shere = owner.getBattle()->battleGetStackByPos(hoveredHex, true);
  328. if(shere)
  329. return shere;
  330. return owner.getBattle()->battleGetStackByPos(hoveredHex, false);
  331. }
  332. void BattleActionsController::actionSetCursor(PossiblePlayerBattleAction action, const BattleHex & targetHex)
  333. {
  334. switch (action.get())
  335. {
  336. case PossiblePlayerBattleAction::CHOOSE_TACTICS_STACK:
  337. ENGINE->cursor().set(Cursor::Combat::POINTER);
  338. return;
  339. case PossiblePlayerBattleAction::MOVE_TACTICS:
  340. case PossiblePlayerBattleAction::MOVE_STACK:
  341. if (owner.stacksController->getActiveStack()->hasBonusOfType(BonusType::FLYING))
  342. ENGINE->cursor().set(Cursor::Combat::FLY);
  343. else
  344. ENGINE->cursor().set(Cursor::Combat::MOVE);
  345. return;
  346. case PossiblePlayerBattleAction::ATTACK:
  347. case PossiblePlayerBattleAction::WALK_AND_ATTACK:
  348. case PossiblePlayerBattleAction::ATTACK_AND_RETURN:
  349. {
  350. static const std::map<BattleHex::EDir, Cursor::Combat> sectorCursor = {
  351. {BattleHex::TOP_LEFT, Cursor::Combat::HIT_SOUTHEAST},
  352. {BattleHex::TOP_RIGHT, Cursor::Combat::HIT_SOUTHWEST},
  353. {BattleHex::RIGHT, Cursor::Combat::HIT_WEST },
  354. {BattleHex::BOTTOM_RIGHT, Cursor::Combat::HIT_NORTHWEST},
  355. {BattleHex::BOTTOM_LEFT, Cursor::Combat::HIT_NORTHEAST},
  356. {BattleHex::LEFT, Cursor::Combat::HIT_EAST },
  357. {BattleHex::TOP, Cursor::Combat::HIT_SOUTH },
  358. {BattleHex::BOTTOM, Cursor::Combat::HIT_NORTH }
  359. };
  360. auto direction = owner.fieldController->selectAttackDirection(targetHex);
  361. assert(sectorCursor.count(direction) > 0);
  362. if (sectorCursor.count(direction))
  363. ENGINE->cursor().set(sectorCursor.at(direction));
  364. return;
  365. }
  366. case PossiblePlayerBattleAction::SHOOT:
  367. if (owner.getBattle()->battleHasShootingPenalty(owner.stacksController->getActiveStack(), targetHex))
  368. ENGINE->cursor().set(Cursor::Combat::SHOOT_PENALTY);
  369. else
  370. ENGINE->cursor().set(Cursor::Combat::SHOOT);
  371. return;
  372. case PossiblePlayerBattleAction::AIMED_SPELL_CREATURE:
  373. case PossiblePlayerBattleAction::ANY_LOCATION:
  374. case PossiblePlayerBattleAction::RANDOM_GENIE_SPELL:
  375. case PossiblePlayerBattleAction::FREE_LOCATION:
  376. case PossiblePlayerBattleAction::OBSTACLE:
  377. ENGINE->cursor().set(Cursor::Spellcast::SPELL);
  378. return;
  379. case PossiblePlayerBattleAction::TELEPORT:
  380. ENGINE->cursor().set(Cursor::Combat::TELEPORT);
  381. return;
  382. case PossiblePlayerBattleAction::SACRIFICE:
  383. ENGINE->cursor().set(Cursor::Combat::SACRIFICE);
  384. return;
  385. case PossiblePlayerBattleAction::HEAL:
  386. ENGINE->cursor().set(Cursor::Combat::HEAL);
  387. return;
  388. case PossiblePlayerBattleAction::CATAPULT:
  389. ENGINE->cursor().set(Cursor::Combat::SHOOT_CATAPULT);
  390. return;
  391. case PossiblePlayerBattleAction::CREATURE_INFO:
  392. ENGINE->cursor().set(Cursor::Combat::QUERY);
  393. return;
  394. case PossiblePlayerBattleAction::HERO_INFO:
  395. ENGINE->cursor().set(Cursor::Combat::HERO);
  396. return;
  397. }
  398. assert(0);
  399. }
  400. void BattleActionsController::actionSetCursorBlocked(PossiblePlayerBattleAction action, const BattleHex & targetHex)
  401. {
  402. switch (action.get())
  403. {
  404. case PossiblePlayerBattleAction::AIMED_SPELL_CREATURE:
  405. case PossiblePlayerBattleAction::RANDOM_GENIE_SPELL:
  406. case PossiblePlayerBattleAction::TELEPORT:
  407. case PossiblePlayerBattleAction::SACRIFICE:
  408. case PossiblePlayerBattleAction::FREE_LOCATION:
  409. ENGINE->cursor().set(Cursor::Combat::BLOCKED);
  410. return;
  411. default:
  412. if (targetHex == -1)
  413. ENGINE->cursor().set(Cursor::Combat::POINTER);
  414. else
  415. ENGINE->cursor().set(Cursor::Combat::BLOCKED);
  416. return;
  417. }
  418. assert(0);
  419. }
  420. std::string BattleActionsController::actionGetStatusMessage(PossiblePlayerBattleAction action, const BattleHex & targetHex)
  421. {
  422. const CStack * targetStack = getStackForHex(targetHex);
  423. switch (action.get()) //display console message, realize selected action
  424. {
  425. case PossiblePlayerBattleAction::CHOOSE_TACTICS_STACK:
  426. return (boost::format(LIBRARY->generaltexth->allTexts[481]) % targetStack->getName()).str(); //Select %s
  427. case PossiblePlayerBattleAction::MOVE_TACTICS:
  428. case PossiblePlayerBattleAction::MOVE_STACK:
  429. if (owner.stacksController->getActiveStack()->hasBonusOfType(BonusType::FLYING))
  430. return (boost::format(LIBRARY->generaltexth->allTexts[295]) % owner.stacksController->getActiveStack()->getName()).str(); //Fly %s here
  431. else
  432. return (boost::format(LIBRARY->generaltexth->allTexts[294]) % owner.stacksController->getActiveStack()->getName()).str(); //Move %s here
  433. case PossiblePlayerBattleAction::ATTACK:
  434. case PossiblePlayerBattleAction::WALK_AND_ATTACK:
  435. case PossiblePlayerBattleAction::ATTACK_AND_RETURN: //TODO: allow to disable return
  436. {
  437. const auto * attacker = owner.stacksController->getActiveStack();
  438. BattleHex attackFromHex = owner.fieldController->fromWhichHexAttack(targetHex);
  439. int distance = attacker->position.isValid() ? owner.getBattle()->battleGetDistances(attacker, attacker->getPosition())[attackFromHex.toInt()] : 0;
  440. DamageEstimation retaliation;
  441. BattleAttackInfo attackInfo(attacker, targetStack, distance, false );
  442. DamageEstimation estimation = owner.getBattle()->battleEstimateDamage(attackInfo, &retaliation);
  443. estimation.kills.max = std::min<int64_t>(estimation.kills.max, targetStack->getCount());
  444. estimation.kills.min = std::min<int64_t>(estimation.kills.min, targetStack->getCount());
  445. bool enemyMayBeKilled = estimation.kills.max == targetStack->getCount();
  446. return formatMeleeAttack(estimation, targetStack->getName()) + "\n" + formatRetaliation(retaliation, enemyMayBeKilled);
  447. }
  448. case PossiblePlayerBattleAction::SHOOT:
  449. {
  450. if(targetStack == nullptr) //should be true only for spell-like attack
  451. {
  452. auto spellLikeAttackBonus = owner.stacksController->getActiveStack()->getBonus(Selector::type()(BonusType::SPELL_LIKE_ATTACK));
  453. assert(spellLikeAttackBonus != nullptr);
  454. return boost::str(boost::format(LIBRARY->generaltexth->allTexts[26]) % spellLikeAttackBonus->subtype.as<SpellID>().toSpell()->getNameTranslated());
  455. }
  456. const auto * shooter = owner.stacksController->getActiveStack();
  457. DamageEstimation retaliation;
  458. BattleAttackInfo attackInfo(shooter, targetStack, 0, true );
  459. DamageEstimation estimation = owner.getBattle()->battleEstimateDamage(attackInfo, &retaliation);
  460. estimation.kills.max = std::min<int64_t>(estimation.kills.max, targetStack->getCount());
  461. estimation.kills.min = std::min<int64_t>(estimation.kills.min, targetStack->getCount());
  462. return formatRangedAttack(estimation, targetStack->getName(), shooter->shots.available());
  463. }
  464. case PossiblePlayerBattleAction::AIMED_SPELL_CREATURE:
  465. return boost::str(boost::format(LIBRARY->generaltexth->allTexts[27]) % action.spell().toSpell()->getNameTranslated() % targetStack->getName()); //Cast %s on %s
  466. case PossiblePlayerBattleAction::ANY_LOCATION:
  467. return boost::str(boost::format(LIBRARY->generaltexth->allTexts[26]) % action.spell().toSpell()->getNameTranslated()); //Cast %s
  468. case PossiblePlayerBattleAction::RANDOM_GENIE_SPELL: //we assume that teleport / sacrifice will never be available as random spell
  469. return boost::str(boost::format(LIBRARY->generaltexth->allTexts[301]) % targetStack->getName()); //Cast a spell on %
  470. case PossiblePlayerBattleAction::TELEPORT:
  471. return LIBRARY->generaltexth->allTexts[25]; //Teleport Here
  472. case PossiblePlayerBattleAction::OBSTACLE:
  473. return LIBRARY->generaltexth->allTexts[550];
  474. case PossiblePlayerBattleAction::SACRIFICE:
  475. return (boost::format(LIBRARY->generaltexth->allTexts[549]) % targetStack->getName()).str(); //sacrifice the %s
  476. case PossiblePlayerBattleAction::FREE_LOCATION:
  477. return boost::str(boost::format(LIBRARY->generaltexth->allTexts[26]) % action.spell().toSpell()->getNameTranslated()); //Cast %s
  478. case PossiblePlayerBattleAction::HEAL:
  479. return (boost::format(LIBRARY->generaltexth->allTexts[419]) % targetStack->getName()).str(); //Apply first aid to the %s
  480. case PossiblePlayerBattleAction::CATAPULT:
  481. return ""; // TODO
  482. case PossiblePlayerBattleAction::CREATURE_INFO:
  483. return (boost::format(LIBRARY->generaltexth->allTexts[297]) % targetStack->getName()).str();
  484. case PossiblePlayerBattleAction::HERO_INFO:
  485. return LIBRARY->generaltexth->translate("core.genrltxt.417"); // "View Hero Stats"
  486. }
  487. assert(0);
  488. return "";
  489. }
  490. std::string BattleActionsController::actionGetStatusMessageBlocked(PossiblePlayerBattleAction action, const BattleHex & targetHex)
  491. {
  492. switch (action.get())
  493. {
  494. case PossiblePlayerBattleAction::AIMED_SPELL_CREATURE:
  495. case PossiblePlayerBattleAction::RANDOM_GENIE_SPELL:
  496. return LIBRARY->generaltexth->allTexts[23];
  497. break;
  498. case PossiblePlayerBattleAction::TELEPORT:
  499. return LIBRARY->generaltexth->allTexts[24]; //Invalid Teleport Destination
  500. break;
  501. case PossiblePlayerBattleAction::SACRIFICE:
  502. return LIBRARY->generaltexth->allTexts[543]; //choose army to sacrifice
  503. break;
  504. case PossiblePlayerBattleAction::FREE_LOCATION:
  505. return boost::str(boost::format(LIBRARY->generaltexth->allTexts[181]) % action.spell().toSpell()->getNameTranslated()); //No room to place %s here
  506. break;
  507. default:
  508. return "";
  509. }
  510. }
  511. bool BattleActionsController::actionIsLegal(PossiblePlayerBattleAction action, const BattleHex & targetHex)
  512. {
  513. const CStack * targetStack = getStackForHex(targetHex);
  514. bool targetStackOwned = targetStack && targetStack->unitOwner() == owner.curInt->playerID;
  515. switch (action.get())
  516. {
  517. case PossiblePlayerBattleAction::CHOOSE_TACTICS_STACK:
  518. return (targetStack && targetStackOwned && targetStack->getMovementRange() > 0);
  519. case PossiblePlayerBattleAction::CREATURE_INFO:
  520. return (targetStack && targetStack->alive());
  521. case PossiblePlayerBattleAction::HERO_INFO:
  522. if (targetHex == BattleHex::HERO_ATTACKER)
  523. return owner.attackingHero != nullptr;
  524. if (targetHex == BattleHex::HERO_DEFENDER)
  525. return owner.defendingHero != nullptr;
  526. return false;
  527. case PossiblePlayerBattleAction::MOVE_TACTICS:
  528. case PossiblePlayerBattleAction::MOVE_STACK:
  529. if (!(targetStack && targetStack->alive())) //we can walk on dead stacks
  530. {
  531. if(canStackMoveHere(owner.stacksController->getActiveStack(), targetHex))
  532. return true;
  533. }
  534. return false;
  535. case PossiblePlayerBattleAction::ATTACK:
  536. case PossiblePlayerBattleAction::WALK_AND_ATTACK:
  537. case PossiblePlayerBattleAction::ATTACK_AND_RETURN:
  538. {
  539. if (owner.fieldController->isTileAttackable(targetHex)) // move isTileAttackable to be part of battleCanAttack?
  540. {
  541. BattleHex attackFromHex = owner.fieldController->fromWhichHexAttack(targetHex);
  542. if(owner.getBattle()->battleCanAttack(owner.stacksController->getActiveStack(), targetStack, attackFromHex))
  543. return true;
  544. }
  545. return false;
  546. }
  547. case PossiblePlayerBattleAction::SHOOT:
  548. {
  549. auto currentStack = owner.stacksController->getActiveStack();
  550. if(!owner.getBattle()->battleCanShoot(currentStack, targetHex))
  551. return false;
  552. if(targetStack == nullptr && owner.getBattle()->battleCanTargetEmptyHex(currentStack))
  553. {
  554. auto spellLikeAttackBonus = currentStack->getBonus(Selector::type()(BonusType::SPELL_LIKE_ATTACK));
  555. const CSpell * spellDataToCheck = spellLikeAttackBonus->subtype.as<SpellID>().toSpell();
  556. return isCastingPossibleHere(spellDataToCheck, nullptr, targetHex);
  557. }
  558. return true;
  559. }
  560. case PossiblePlayerBattleAction::NO_LOCATION:
  561. return false;
  562. case PossiblePlayerBattleAction::ANY_LOCATION:
  563. return isCastingPossibleHere(action.spell().toSpell(), nullptr, targetHex);
  564. case PossiblePlayerBattleAction::AIMED_SPELL_CREATURE:
  565. return !selectedStack && targetStack && isCastingPossibleHere(action.spell().toSpell(), nullptr, targetHex);
  566. case PossiblePlayerBattleAction::RANDOM_GENIE_SPELL:
  567. if(targetStack && targetStackOwned && targetStack != owner.stacksController->getActiveStack() && targetStack->alive()) //only positive spells for other allied creatures
  568. {
  569. SpellID spellID = owner.getBattle()->getRandomBeneficialSpell(CRandomGenerator::getDefault(), owner.stacksController->getActiveStack(), targetStack);
  570. return spellID != SpellID::NONE;
  571. }
  572. return false;
  573. case PossiblePlayerBattleAction::TELEPORT:
  574. return selectedStack && isCastingPossibleHere(action.spell().toSpell(), selectedStack, targetHex);
  575. case PossiblePlayerBattleAction::SACRIFICE: //choose our living stack to sacrifice
  576. return targetStack && targetStack != selectedStack && targetStackOwned && targetStack->alive();
  577. case PossiblePlayerBattleAction::OBSTACLE:
  578. case PossiblePlayerBattleAction::FREE_LOCATION:
  579. return isCastingPossibleHere(action.spell().toSpell(), nullptr, targetHex);
  580. case PossiblePlayerBattleAction::CATAPULT:
  581. return owner.siegeController && owner.siegeController->isAttackableByCatapult(targetHex);
  582. case PossiblePlayerBattleAction::HEAL:
  583. return targetStack && targetStackOwned && targetStack->canBeHealed();
  584. }
  585. assert(0);
  586. return false;
  587. }
  588. void BattleActionsController::actionRealize(PossiblePlayerBattleAction action, const BattleHex & targetHex)
  589. {
  590. const CStack * targetStack = getStackForHex(targetHex);
  591. switch (action.get()) //display console message, realize selected action
  592. {
  593. case PossiblePlayerBattleAction::CHOOSE_TACTICS_STACK:
  594. {
  595. owner.stackActivated(targetStack);
  596. return;
  597. }
  598. case PossiblePlayerBattleAction::MOVE_TACTICS:
  599. case PossiblePlayerBattleAction::MOVE_STACK:
  600. {
  601. const auto * activeStack = owner.stacksController->getActiveStack();
  602. const bool backwardsMove = activeStack->unitSide() == BattleSide::ATTACKER ?
  603. targetHex.getX() < activeStack->getPosition().getX():
  604. targetHex.getX() > activeStack->getPosition().getX();
  605. if(activeStack->doubleWide() && backwardsMove)
  606. {
  607. BattleHexArray acc = owner.getBattle()->battleGetAvailableHexes(activeStack, false);
  608. BattleHex shiftedDest = targetHex.cloneInDirection(activeStack->destShiftDir(), false);
  609. if(acc.contains(shiftedDest))
  610. owner.giveCommand(EActionType::WALK, shiftedDest);
  611. else
  612. owner.giveCommand(EActionType::WALK, targetHex);
  613. }
  614. else
  615. {
  616. owner.giveCommand(EActionType::WALK, targetHex);
  617. }
  618. return;
  619. }
  620. case PossiblePlayerBattleAction::ATTACK:
  621. case PossiblePlayerBattleAction::WALK_AND_ATTACK:
  622. case PossiblePlayerBattleAction::ATTACK_AND_RETURN: //TODO: allow to disable return
  623. {
  624. bool returnAfterAttack = action.get() == PossiblePlayerBattleAction::ATTACK_AND_RETURN;
  625. BattleHex attackFromHex = owner.fieldController->fromWhichHexAttack(targetHex);
  626. if(attackFromHex.isValid()) //we can be in this line when unreachable creature is L - clicked (as of revision 1308)
  627. {
  628. BattleAction command = BattleAction::makeMeleeAttack(owner.stacksController->getActiveStack(), targetHex, attackFromHex, returnAfterAttack);
  629. owner.sendCommand(command, owner.stacksController->getActiveStack());
  630. }
  631. return;
  632. }
  633. case PossiblePlayerBattleAction::SHOOT:
  634. {
  635. owner.giveCommand(EActionType::SHOOT, targetHex);
  636. return;
  637. }
  638. case PossiblePlayerBattleAction::HEAL:
  639. {
  640. owner.giveCommand(EActionType::STACK_HEAL, targetHex);
  641. return;
  642. };
  643. case PossiblePlayerBattleAction::CATAPULT:
  644. {
  645. owner.giveCommand(EActionType::CATAPULT, targetHex);
  646. return;
  647. }
  648. case PossiblePlayerBattleAction::CREATURE_INFO:
  649. {
  650. ENGINE->windows().createAndPushWindow<CStackWindow>(targetStack, false);
  651. return;
  652. }
  653. case PossiblePlayerBattleAction::HERO_INFO:
  654. {
  655. if (targetHex == BattleHex::HERO_ATTACKER)
  656. owner.attackingHero->heroLeftClicked();
  657. if (targetHex == BattleHex::HERO_DEFENDER)
  658. owner.defendingHero->heroLeftClicked();
  659. return;
  660. }
  661. case PossiblePlayerBattleAction::AIMED_SPELL_CREATURE:
  662. case PossiblePlayerBattleAction::ANY_LOCATION:
  663. case PossiblePlayerBattleAction::RANDOM_GENIE_SPELL: //we assume that teleport / sacrifice will never be available as random spell
  664. case PossiblePlayerBattleAction::TELEPORT:
  665. case PossiblePlayerBattleAction::OBSTACLE:
  666. case PossiblePlayerBattleAction::SACRIFICE:
  667. case PossiblePlayerBattleAction::FREE_LOCATION:
  668. {
  669. if (action.get() == PossiblePlayerBattleAction::AIMED_SPELL_CREATURE )
  670. {
  671. if (action.spell() == SpellID::SACRIFICE)
  672. {
  673. heroSpellToCast->aimToHex(targetHex);
  674. possibleActions.push_back({PossiblePlayerBattleAction::SACRIFICE, action.spell()});
  675. selectedStack = targetStack;
  676. return;
  677. }
  678. if (action.spell() == SpellID::TELEPORT)
  679. {
  680. heroSpellToCast->aimToUnit(targetStack);
  681. possibleActions.push_back({PossiblePlayerBattleAction::TELEPORT, action.spell()});
  682. selectedStack = targetStack;
  683. return;
  684. }
  685. }
  686. if (!heroSpellcastingModeActive())
  687. {
  688. if (action.spell().hasValue())
  689. {
  690. owner.giveCommand(EActionType::MONSTER_SPELL, targetHex, action.spell());
  691. }
  692. else //unknown random spell
  693. {
  694. owner.giveCommand(EActionType::MONSTER_SPELL, targetHex);
  695. }
  696. }
  697. else
  698. {
  699. assert(getHeroSpellToCast());
  700. switch (getHeroSpellToCast()->id.toEnum())
  701. {
  702. case SpellID::SACRIFICE:
  703. heroSpellToCast->aimToUnit(targetStack);//victim
  704. break;
  705. default:
  706. heroSpellToCast->aimToHex(targetHex);
  707. break;
  708. }
  709. owner.curInt->cb->battleMakeSpellAction(owner.getBattleID(), *heroSpellToCast);
  710. endCastingSpell();
  711. }
  712. selectedStack = nullptr;
  713. return;
  714. }
  715. }
  716. assert(0);
  717. return;
  718. }
  719. PossiblePlayerBattleAction BattleActionsController::selectAction(const BattleHex & targetHex)
  720. {
  721. assert(owner.stacksController->getActiveStack() != nullptr);
  722. assert(!possibleActions.empty());
  723. assert(targetHex.isValid());
  724. if (owner.stacksController->getActiveStack() == nullptr)
  725. return PossiblePlayerBattleAction::INVALID;
  726. if (possibleActions.empty())
  727. return PossiblePlayerBattleAction::INVALID;
  728. const CStack * targetStack = getStackForHex(targetHex);
  729. reorderPossibleActionsPriority(owner.stacksController->getActiveStack(), targetStack);
  730. for (PossiblePlayerBattleAction action : possibleActions)
  731. {
  732. if (actionIsLegal(action, targetHex))
  733. return action;
  734. }
  735. return possibleActions.front();
  736. }
  737. void BattleActionsController::onHexHovered(const BattleHex & hoveredHex)
  738. {
  739. if (owner.openingPlaying())
  740. {
  741. currentConsoleMsg = LIBRARY->generaltexth->translate("vcmi.battleWindow.pressKeyToSkipIntro");
  742. ENGINE->statusbar()->write(currentConsoleMsg);
  743. return;
  744. }
  745. if (owner.stacksController->getActiveStack() == nullptr)
  746. return;
  747. if (hoveredHex == BattleHex::INVALID)
  748. {
  749. if (!currentConsoleMsg.empty())
  750. ENGINE->statusbar()->clearIfMatching(currentConsoleMsg);
  751. currentConsoleMsg.clear();
  752. ENGINE->cursor().set(Cursor::Combat::BLOCKED);
  753. return;
  754. }
  755. auto action = selectAction(hoveredHex);
  756. std::string newConsoleMsg;
  757. if (actionIsLegal(action, hoveredHex))
  758. {
  759. actionSetCursor(action, hoveredHex);
  760. newConsoleMsg = actionGetStatusMessage(action, hoveredHex);
  761. }
  762. else
  763. {
  764. actionSetCursorBlocked(action, hoveredHex);
  765. newConsoleMsg = actionGetStatusMessageBlocked(action, hoveredHex);
  766. }
  767. if (!currentConsoleMsg.empty())
  768. ENGINE->statusbar()->clearIfMatching(currentConsoleMsg);
  769. if (!newConsoleMsg.empty())
  770. ENGINE->statusbar()->write(newConsoleMsg);
  771. currentConsoleMsg = newConsoleMsg;
  772. }
  773. void BattleActionsController::onHoverEnded()
  774. {
  775. ENGINE->cursor().set(Cursor::Combat::POINTER);
  776. if (!currentConsoleMsg.empty())
  777. ENGINE->statusbar()->clearIfMatching(currentConsoleMsg);
  778. currentConsoleMsg.clear();
  779. }
  780. void BattleActionsController::onHexLeftClicked(const BattleHex & clickedHex)
  781. {
  782. if (owner.stacksController->getActiveStack() == nullptr)
  783. return;
  784. auto action = selectAction(clickedHex);
  785. std::string newConsoleMsg;
  786. if (!actionIsLegal(action, clickedHex))
  787. return;
  788. actionRealize(action, clickedHex);
  789. ENGINE->statusbar()->clear();
  790. }
  791. void BattleActionsController::tryActivateStackSpellcasting(const CStack *casterStack)
  792. {
  793. creatureSpells.clear();
  794. bool spellcaster = casterStack->hasBonusOfType(BonusType::SPELLCASTER);
  795. if(casterStack->canCast() && spellcaster)
  796. {
  797. // faerie dragon can cast only one, randomly selected spell until their next move
  798. //TODO: faerie dragon type spell should be selected by server
  799. const auto spellToCast = owner.getBattle()->getRandomCastedSpell(CRandomGenerator::getDefault(), casterStack);
  800. if (spellToCast.hasValue())
  801. creatureSpells.push_back(spellToCast.toSpell());
  802. }
  803. TConstBonusListPtr bl = casterStack->getBonusesOfType(BonusType::SPELLCASTER);
  804. for(const auto & bonus : *bl)
  805. {
  806. if (bonus->additionalInfo[0] <= 0 && bonus->subtype.as<SpellID>().hasValue())
  807. creatureSpells.push_back(bonus->subtype.as<SpellID>().toSpell());
  808. }
  809. }
  810. const spells::Caster * BattleActionsController::getCurrentSpellcaster() const
  811. {
  812. if (heroSpellToCast)
  813. return owner.currentHero();
  814. else
  815. return owner.stacksController->getActiveStack();
  816. }
  817. spells::Mode BattleActionsController::getCurrentCastMode() const
  818. {
  819. if (heroSpellToCast)
  820. return spells::Mode::HERO;
  821. else
  822. return spells::Mode::CREATURE_ACTIVE;
  823. }
  824. bool BattleActionsController::isCastingPossibleHere(const CSpell * currentSpell, const CStack *targetStack, const BattleHex & targetHex)
  825. {
  826. assert(currentSpell);
  827. if (!currentSpell)
  828. return false;
  829. auto caster = getCurrentSpellcaster();
  830. const spells::Mode mode = heroSpellToCast ? spells::Mode::HERO : spells::Mode::CREATURE_ACTIVE;
  831. spells::Target target;
  832. if(targetStack)
  833. target.emplace_back(targetStack);
  834. target.emplace_back(targetHex);
  835. spells::BattleCast cast(owner.getBattle().get(), caster, mode, currentSpell);
  836. auto m = currentSpell->battleMechanics(&cast);
  837. spells::detail::ProblemImpl problem; //todo: display problem in status bar
  838. return m->canBeCastAt(target, problem);
  839. }
  840. bool BattleActionsController::canStackMoveHere(const CStack * stackToMove, const BattleHex & myNumber) const
  841. {
  842. BattleHexArray acc = owner.getBattle()->battleGetAvailableHexes(stackToMove, false);
  843. BattleHex shiftedDest = myNumber.cloneInDirection(stackToMove->destShiftDir(), false);
  844. if (acc.contains(myNumber))
  845. return true;
  846. else if (stackToMove->doubleWide() && acc.contains(shiftedDest))
  847. return true;
  848. else
  849. return false;
  850. }
  851. void BattleActionsController::activateStack()
  852. {
  853. const CStack * s = owner.stacksController->getActiveStack();
  854. if(s)
  855. {
  856. tryActivateStackSpellcasting(s);
  857. possibleActions = getPossibleActionsForStack(s);
  858. owner.windowObject->setPossibleActions(possibleActions);
  859. }
  860. }
  861. void BattleActionsController::onHexRightClicked(const BattleHex & clickedHex)
  862. {
  863. bool isCurrentStackInSpellcastMode = creatureSpellcastingModeActive();
  864. if (heroSpellcastingModeActive() || isCurrentStackInSpellcastMode)
  865. {
  866. endCastingSpell();
  867. CRClickPopup::createAndPush(LIBRARY->generaltexth->translate("core.genrltxt.731")); // spell cancelled
  868. return;
  869. }
  870. auto selectedStack = owner.getBattle()->battleGetStackByPos(clickedHex, true);
  871. if (selectedStack != nullptr)
  872. ENGINE->windows().createAndPushWindow<CStackWindow>(selectedStack, true);
  873. if (clickedHex == BattleHex::HERO_ATTACKER && owner.attackingHero)
  874. owner.attackingHero->heroRightClicked();
  875. if (clickedHex == BattleHex::HERO_DEFENDER && owner.defendingHero)
  876. owner.defendingHero->heroRightClicked();
  877. }
  878. bool BattleActionsController::heroSpellcastingModeActive() const
  879. {
  880. return heroSpellToCast != nullptr;
  881. }
  882. bool BattleActionsController::creatureSpellcastingModeActive() const
  883. {
  884. auto spellcastModePredicate = [](const PossiblePlayerBattleAction & action)
  885. {
  886. return action.spellcast() || action.get() == PossiblePlayerBattleAction::SHOOT; //for hotkey-eligible SPELL_LIKE_ATTACK creature should have only SHOOT action
  887. };
  888. return !possibleActions.empty() && std::all_of(possibleActions.begin(), possibleActions.end(), spellcastModePredicate);
  889. }
  890. bool BattleActionsController::currentActionSpellcasting(const BattleHex & hoveredHex)
  891. {
  892. if (heroSpellToCast)
  893. return true;
  894. if (!owner.stacksController->getActiveStack())
  895. return false;
  896. auto action = selectAction(hoveredHex);
  897. return action.spellcast();
  898. }
  899. const std::vector<PossiblePlayerBattleAction> & BattleActionsController::getPossibleActions() const
  900. {
  901. return possibleActions;
  902. }
  903. void BattleActionsController::setPriorityActions(const std::vector<PossiblePlayerBattleAction> & actions)
  904. {
  905. possibleActions = actions;
  906. }
  907. void BattleActionsController::resetCurrentStackPossibleActions()
  908. {
  909. possibleActions = getPossibleActionsForStack(owner.stacksController->getActiveStack());
  910. }