BattleActionsController.cpp 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112
  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. attackInfo.attackerPos = attackFromHex;
  443. DamageEstimation estimation = owner.getBattle()->battleEstimateDamage(attackInfo, &retaliation);
  444. estimation.kills.max = std::min<int64_t>(estimation.kills.max, targetStack->getCount());
  445. estimation.kills.min = std::min<int64_t>(estimation.kills.min, targetStack->getCount());
  446. bool enemyMayBeKilled = estimation.kills.max == targetStack->getCount();
  447. return formatMeleeAttack(estimation, targetStack->getName()) + "\n" + formatRetaliation(retaliation, enemyMayBeKilled);
  448. }
  449. case PossiblePlayerBattleAction::SHOOT:
  450. {
  451. if(targetStack == nullptr) //should be true only for spell-like attack
  452. {
  453. auto spellLikeAttackBonus = owner.stacksController->getActiveStack()->getBonus(Selector::type()(BonusType::SPELL_LIKE_ATTACK));
  454. assert(spellLikeAttackBonus != nullptr);
  455. return boost::str(boost::format(LIBRARY->generaltexth->allTexts[26]) % spellLikeAttackBonus->subtype.as<SpellID>().toSpell()->getNameTranslated());
  456. }
  457. const auto * shooter = owner.stacksController->getActiveStack();
  458. DamageEstimation retaliation;
  459. BattleAttackInfo attackInfo(shooter, targetStack, 0, true );
  460. DamageEstimation estimation = owner.getBattle()->battleEstimateDamage(attackInfo, &retaliation);
  461. estimation.kills.max = std::min<int64_t>(estimation.kills.max, targetStack->getCount());
  462. estimation.kills.min = std::min<int64_t>(estimation.kills.min, targetStack->getCount());
  463. return formatRangedAttack(estimation, targetStack->getName(), shooter->shots.available());
  464. }
  465. case PossiblePlayerBattleAction::AIMED_SPELL_CREATURE:
  466. return boost::str(boost::format(LIBRARY->generaltexth->allTexts[27]) % action.spell().toSpell()->getNameTranslated() % targetStack->getName()); //Cast %s on %s
  467. case PossiblePlayerBattleAction::ANY_LOCATION:
  468. return boost::str(boost::format(LIBRARY->generaltexth->allTexts[26]) % action.spell().toSpell()->getNameTranslated()); //Cast %s
  469. case PossiblePlayerBattleAction::RANDOM_GENIE_SPELL: //we assume that teleport / sacrifice will never be available as random spell
  470. return boost::str(boost::format(LIBRARY->generaltexth->allTexts[301]) % targetStack->getName()); //Cast a spell on %
  471. case PossiblePlayerBattleAction::TELEPORT:
  472. return LIBRARY->generaltexth->allTexts[25]; //Teleport Here
  473. case PossiblePlayerBattleAction::OBSTACLE:
  474. return LIBRARY->generaltexth->allTexts[550];
  475. case PossiblePlayerBattleAction::SACRIFICE:
  476. return (boost::format(LIBRARY->generaltexth->allTexts[549]) % targetStack->getName()).str(); //sacrifice the %s
  477. case PossiblePlayerBattleAction::FREE_LOCATION:
  478. return boost::str(boost::format(LIBRARY->generaltexth->allTexts[26]) % action.spell().toSpell()->getNameTranslated()); //Cast %s
  479. case PossiblePlayerBattleAction::HEAL:
  480. return (boost::format(LIBRARY->generaltexth->allTexts[419]) % targetStack->getName()).str(); //Apply first aid to the %s
  481. case PossiblePlayerBattleAction::CATAPULT:
  482. return ""; // TODO
  483. case PossiblePlayerBattleAction::CREATURE_INFO:
  484. return (boost::format(LIBRARY->generaltexth->allTexts[297]) % targetStack->getName()).str();
  485. case PossiblePlayerBattleAction::HERO_INFO:
  486. return LIBRARY->generaltexth->translate("core.genrltxt.417"); // "View Hero Stats"
  487. }
  488. assert(0);
  489. return "";
  490. }
  491. std::string BattleActionsController::actionGetStatusMessageBlocked(PossiblePlayerBattleAction action, const BattleHex & targetHex)
  492. {
  493. switch (action.get())
  494. {
  495. case PossiblePlayerBattleAction::AIMED_SPELL_CREATURE:
  496. case PossiblePlayerBattleAction::RANDOM_GENIE_SPELL:
  497. return LIBRARY->generaltexth->allTexts[23];
  498. break;
  499. case PossiblePlayerBattleAction::TELEPORT:
  500. return LIBRARY->generaltexth->allTexts[24]; //Invalid Teleport Destination
  501. break;
  502. case PossiblePlayerBattleAction::SACRIFICE:
  503. return LIBRARY->generaltexth->allTexts[543]; //choose army to sacrifice
  504. break;
  505. case PossiblePlayerBattleAction::FREE_LOCATION:
  506. return boost::str(boost::format(LIBRARY->generaltexth->allTexts[181]) % action.spell().toSpell()->getNameTranslated()); //No room to place %s here
  507. break;
  508. default:
  509. return "";
  510. }
  511. }
  512. bool BattleActionsController::actionIsLegal(PossiblePlayerBattleAction action, const BattleHex & targetHex)
  513. {
  514. const CStack * targetStack = getStackForHex(targetHex);
  515. bool targetStackOwned = targetStack && targetStack->unitOwner() == owner.curInt->playerID;
  516. switch (action.get())
  517. {
  518. case PossiblePlayerBattleAction::CHOOSE_TACTICS_STACK:
  519. return (targetStack && targetStackOwned && targetStack->getMovementRange() > 0);
  520. case PossiblePlayerBattleAction::CREATURE_INFO:
  521. return (targetStack && targetStack->alive());
  522. case PossiblePlayerBattleAction::HERO_INFO:
  523. if (targetHex == BattleHex::HERO_ATTACKER)
  524. return owner.attackingHero != nullptr;
  525. if (targetHex == BattleHex::HERO_DEFENDER)
  526. return owner.defendingHero != nullptr;
  527. return false;
  528. case PossiblePlayerBattleAction::MOVE_TACTICS:
  529. case PossiblePlayerBattleAction::MOVE_STACK:
  530. if (!(targetStack && targetStack->alive())) //we can walk on dead stacks
  531. {
  532. if(canStackMoveHere(owner.stacksController->getActiveStack(), targetHex))
  533. return true;
  534. }
  535. return false;
  536. case PossiblePlayerBattleAction::ATTACK:
  537. case PossiblePlayerBattleAction::WALK_AND_ATTACK:
  538. case PossiblePlayerBattleAction::ATTACK_AND_RETURN:
  539. {
  540. if (owner.fieldController->isTileAttackable(targetHex)) // move isTileAttackable to be part of battleCanAttack?
  541. {
  542. BattleHex attackFromHex = owner.fieldController->fromWhichHexAttack(targetHex);
  543. if(owner.getBattle()->battleCanAttack(owner.stacksController->getActiveStack(), targetStack, attackFromHex))
  544. return true;
  545. }
  546. return false;
  547. }
  548. case PossiblePlayerBattleAction::SHOOT:
  549. {
  550. auto currentStack = owner.stacksController->getActiveStack();
  551. if(!owner.getBattle()->battleCanShoot(currentStack, targetHex))
  552. return false;
  553. if(targetStack == nullptr && owner.getBattle()->battleCanTargetEmptyHex(currentStack))
  554. {
  555. auto spellLikeAttackBonus = currentStack->getBonus(Selector::type()(BonusType::SPELL_LIKE_ATTACK));
  556. const CSpell * spellDataToCheck = spellLikeAttackBonus->subtype.as<SpellID>().toSpell();
  557. return isCastingPossibleHere(spellDataToCheck, nullptr, targetHex);
  558. }
  559. return true;
  560. }
  561. case PossiblePlayerBattleAction::NO_LOCATION:
  562. return false;
  563. case PossiblePlayerBattleAction::ANY_LOCATION:
  564. return isCastingPossibleHere(action.spell().toSpell(), nullptr, targetHex);
  565. case PossiblePlayerBattleAction::AIMED_SPELL_CREATURE:
  566. return !selectedStack && targetStack && isCastingPossibleHere(action.spell().toSpell(), nullptr, targetHex);
  567. case PossiblePlayerBattleAction::RANDOM_GENIE_SPELL:
  568. if(targetStack && targetStackOwned && targetStack != owner.stacksController->getActiveStack() && targetStack->alive()) //only positive spells for other allied creatures
  569. {
  570. SpellID spellID = owner.getBattle()->getRandomBeneficialSpell(CRandomGenerator::getDefault(), owner.stacksController->getActiveStack(), targetStack);
  571. return spellID != SpellID::NONE;
  572. }
  573. return false;
  574. case PossiblePlayerBattleAction::TELEPORT:
  575. return selectedStack && isCastingPossibleHere(action.spell().toSpell(), selectedStack, targetHex);
  576. case PossiblePlayerBattleAction::SACRIFICE: //choose our living stack to sacrifice
  577. return targetStack && targetStack != selectedStack && targetStackOwned && targetStack->alive();
  578. case PossiblePlayerBattleAction::OBSTACLE:
  579. case PossiblePlayerBattleAction::FREE_LOCATION:
  580. return isCastingPossibleHere(action.spell().toSpell(), nullptr, targetHex);
  581. case PossiblePlayerBattleAction::CATAPULT:
  582. return owner.siegeController && owner.siegeController->isAttackableByCatapult(targetHex);
  583. case PossiblePlayerBattleAction::HEAL:
  584. return targetStack && targetStackOwned && targetStack->canBeHealed();
  585. }
  586. assert(0);
  587. return false;
  588. }
  589. void BattleActionsController::actionRealize(PossiblePlayerBattleAction action, const BattleHex & targetHex)
  590. {
  591. const CStack * targetStack = getStackForHex(targetHex);
  592. switch (action.get()) //display console message, realize selected action
  593. {
  594. case PossiblePlayerBattleAction::CHOOSE_TACTICS_STACK:
  595. {
  596. owner.stackActivated(targetStack);
  597. return;
  598. }
  599. case PossiblePlayerBattleAction::MOVE_TACTICS:
  600. case PossiblePlayerBattleAction::MOVE_STACK:
  601. {
  602. const auto * activeStack = owner.stacksController->getActiveStack();
  603. const bool backwardsMove = activeStack->unitSide() == BattleSide::ATTACKER ?
  604. targetHex.getX() < activeStack->getPosition().getX():
  605. targetHex.getX() > activeStack->getPosition().getX();
  606. if(activeStack->doubleWide() && backwardsMove)
  607. {
  608. BattleHexArray acc = owner.getBattle()->battleGetAvailableHexes(activeStack, false);
  609. BattleHex shiftedDest = targetHex.cloneInDirection(activeStack->destShiftDir(), false);
  610. if(acc.contains(shiftedDest))
  611. owner.giveCommand(EActionType::WALK, shiftedDest);
  612. else
  613. owner.giveCommand(EActionType::WALK, targetHex);
  614. }
  615. else
  616. {
  617. owner.giveCommand(EActionType::WALK, targetHex);
  618. }
  619. return;
  620. }
  621. case PossiblePlayerBattleAction::ATTACK:
  622. case PossiblePlayerBattleAction::WALK_AND_ATTACK:
  623. case PossiblePlayerBattleAction::ATTACK_AND_RETURN: //TODO: allow to disable return
  624. {
  625. bool returnAfterAttack = action.get() == PossiblePlayerBattleAction::ATTACK_AND_RETURN;
  626. BattleHex attackFromHex = owner.fieldController->fromWhichHexAttack(targetHex);
  627. if(attackFromHex.isValid()) //we can be in this line when unreachable creature is L - clicked (as of revision 1308)
  628. {
  629. BattleAction command = BattleAction::makeMeleeAttack(owner.stacksController->getActiveStack(), targetHex, attackFromHex, returnAfterAttack);
  630. owner.sendCommand(command, owner.stacksController->getActiveStack());
  631. }
  632. return;
  633. }
  634. case PossiblePlayerBattleAction::SHOOT:
  635. {
  636. owner.giveCommand(EActionType::SHOOT, targetHex);
  637. return;
  638. }
  639. case PossiblePlayerBattleAction::HEAL:
  640. {
  641. owner.giveCommand(EActionType::STACK_HEAL, targetHex);
  642. return;
  643. };
  644. case PossiblePlayerBattleAction::CATAPULT:
  645. {
  646. owner.giveCommand(EActionType::CATAPULT, targetHex);
  647. return;
  648. }
  649. case PossiblePlayerBattleAction::CREATURE_INFO:
  650. {
  651. ENGINE->windows().createAndPushWindow<CStackWindow>(targetStack, false);
  652. return;
  653. }
  654. case PossiblePlayerBattleAction::HERO_INFO:
  655. {
  656. if (targetHex == BattleHex::HERO_ATTACKER)
  657. owner.attackingHero->heroLeftClicked();
  658. if (targetHex == BattleHex::HERO_DEFENDER)
  659. owner.defendingHero->heroLeftClicked();
  660. return;
  661. }
  662. case PossiblePlayerBattleAction::AIMED_SPELL_CREATURE:
  663. case PossiblePlayerBattleAction::ANY_LOCATION:
  664. case PossiblePlayerBattleAction::RANDOM_GENIE_SPELL: //we assume that teleport / sacrifice will never be available as random spell
  665. case PossiblePlayerBattleAction::TELEPORT:
  666. case PossiblePlayerBattleAction::OBSTACLE:
  667. case PossiblePlayerBattleAction::SACRIFICE:
  668. case PossiblePlayerBattleAction::FREE_LOCATION:
  669. {
  670. if (action.get() == PossiblePlayerBattleAction::AIMED_SPELL_CREATURE )
  671. {
  672. if (action.spell() == SpellID::SACRIFICE)
  673. {
  674. heroSpellToCast->aimToHex(targetHex);
  675. possibleActions.push_back({PossiblePlayerBattleAction::SACRIFICE, action.spell()});
  676. selectedStack = targetStack;
  677. return;
  678. }
  679. if (action.spell() == SpellID::TELEPORT)
  680. {
  681. heroSpellToCast->aimToUnit(targetStack);
  682. possibleActions.push_back({PossiblePlayerBattleAction::TELEPORT, action.spell()});
  683. selectedStack = targetStack;
  684. return;
  685. }
  686. }
  687. if (!heroSpellcastingModeActive())
  688. {
  689. if (action.spell().hasValue())
  690. {
  691. owner.giveCommand(EActionType::MONSTER_SPELL, targetHex, action.spell());
  692. }
  693. else //unknown random spell
  694. {
  695. owner.giveCommand(EActionType::MONSTER_SPELL, targetHex);
  696. }
  697. }
  698. else
  699. {
  700. assert(getHeroSpellToCast());
  701. switch (getHeroSpellToCast()->id.toEnum())
  702. {
  703. case SpellID::SACRIFICE:
  704. heroSpellToCast->aimToUnit(targetStack);//victim
  705. break;
  706. default:
  707. heroSpellToCast->aimToHex(targetHex);
  708. break;
  709. }
  710. owner.curInt->cb->battleMakeSpellAction(owner.getBattleID(), *heroSpellToCast);
  711. endCastingSpell();
  712. }
  713. selectedStack = nullptr;
  714. return;
  715. }
  716. }
  717. assert(0);
  718. return;
  719. }
  720. PossiblePlayerBattleAction BattleActionsController::selectAction(const BattleHex & targetHex)
  721. {
  722. assert(owner.stacksController->getActiveStack() != nullptr);
  723. assert(!possibleActions.empty());
  724. assert(targetHex.isValid());
  725. if (owner.stacksController->getActiveStack() == nullptr)
  726. return PossiblePlayerBattleAction::INVALID;
  727. if (possibleActions.empty())
  728. return PossiblePlayerBattleAction::INVALID;
  729. const CStack * targetStack = getStackForHex(targetHex);
  730. reorderPossibleActionsPriority(owner.stacksController->getActiveStack(), targetStack);
  731. for (PossiblePlayerBattleAction action : possibleActions)
  732. {
  733. if (actionIsLegal(action, targetHex))
  734. return action;
  735. }
  736. return possibleActions.front();
  737. }
  738. void BattleActionsController::onHexHovered(const BattleHex & hoveredHex)
  739. {
  740. if (owner.openingPlaying())
  741. {
  742. currentConsoleMsg = LIBRARY->generaltexth->translate("vcmi.battleWindow.pressKeyToSkipIntro");
  743. ENGINE->statusbar()->write(currentConsoleMsg);
  744. return;
  745. }
  746. if (owner.stacksController->getActiveStack() == nullptr)
  747. return;
  748. if (hoveredHex == BattleHex::INVALID)
  749. {
  750. if (!currentConsoleMsg.empty())
  751. ENGINE->statusbar()->clearIfMatching(currentConsoleMsg);
  752. currentConsoleMsg.clear();
  753. ENGINE->cursor().set(Cursor::Combat::BLOCKED);
  754. return;
  755. }
  756. auto action = selectAction(hoveredHex);
  757. std::string newConsoleMsg;
  758. if (actionIsLegal(action, hoveredHex))
  759. {
  760. actionSetCursor(action, hoveredHex);
  761. newConsoleMsg = actionGetStatusMessage(action, hoveredHex);
  762. }
  763. else
  764. {
  765. actionSetCursorBlocked(action, hoveredHex);
  766. newConsoleMsg = actionGetStatusMessageBlocked(action, hoveredHex);
  767. }
  768. if (!currentConsoleMsg.empty())
  769. ENGINE->statusbar()->clearIfMatching(currentConsoleMsg);
  770. if (!newConsoleMsg.empty())
  771. ENGINE->statusbar()->write(newConsoleMsg);
  772. currentConsoleMsg = newConsoleMsg;
  773. }
  774. void BattleActionsController::onHoverEnded()
  775. {
  776. ENGINE->cursor().set(Cursor::Combat::POINTER);
  777. if (!currentConsoleMsg.empty())
  778. ENGINE->statusbar()->clearIfMatching(currentConsoleMsg);
  779. currentConsoleMsg.clear();
  780. }
  781. void BattleActionsController::onHexLeftClicked(const BattleHex & clickedHex)
  782. {
  783. if (owner.stacksController->getActiveStack() == nullptr)
  784. return;
  785. auto action = selectAction(clickedHex);
  786. std::string newConsoleMsg;
  787. if (!actionIsLegal(action, clickedHex))
  788. return;
  789. actionRealize(action, clickedHex);
  790. ENGINE->statusbar()->clear();
  791. }
  792. void BattleActionsController::tryActivateStackSpellcasting(const CStack *casterStack)
  793. {
  794. creatureSpells.clear();
  795. bool spellcaster = casterStack->hasBonusOfType(BonusType::SPELLCASTER);
  796. if(casterStack->canCast() && spellcaster)
  797. {
  798. // faerie dragon can cast only one, randomly selected spell until their next move
  799. //TODO: faerie dragon type spell should be selected by server
  800. const auto spellToCast = owner.getBattle()->getRandomCastedSpell(CRandomGenerator::getDefault(), casterStack);
  801. if (spellToCast.hasValue())
  802. creatureSpells.push_back(spellToCast.toSpell());
  803. }
  804. TConstBonusListPtr bl = casterStack->getBonusesOfType(BonusType::SPELLCASTER);
  805. for(const auto & bonus : *bl)
  806. {
  807. if (bonus->additionalInfo[0] <= 0 && bonus->subtype.as<SpellID>().hasValue())
  808. creatureSpells.push_back(bonus->subtype.as<SpellID>().toSpell());
  809. }
  810. }
  811. const spells::Caster * BattleActionsController::getCurrentSpellcaster() const
  812. {
  813. if (heroSpellToCast)
  814. return owner.currentHero();
  815. else
  816. return owner.stacksController->getActiveStack();
  817. }
  818. spells::Mode BattleActionsController::getCurrentCastMode() const
  819. {
  820. if (heroSpellToCast)
  821. return spells::Mode::HERO;
  822. else
  823. return spells::Mode::CREATURE_ACTIVE;
  824. }
  825. bool BattleActionsController::isCastingPossibleHere(const CSpell * currentSpell, const CStack *targetStack, const BattleHex & targetHex)
  826. {
  827. assert(currentSpell);
  828. if (!currentSpell)
  829. return false;
  830. auto caster = getCurrentSpellcaster();
  831. const spells::Mode mode = heroSpellToCast ? spells::Mode::HERO : spells::Mode::CREATURE_ACTIVE;
  832. spells::Target target;
  833. if(targetStack)
  834. target.emplace_back(targetStack);
  835. target.emplace_back(targetHex);
  836. spells::BattleCast cast(owner.getBattle().get(), caster, mode, currentSpell);
  837. auto m = currentSpell->battleMechanics(&cast);
  838. spells::detail::ProblemImpl problem; //todo: display problem in status bar
  839. return m->canBeCastAt(target, problem);
  840. }
  841. bool BattleActionsController::canStackMoveHere(const CStack * stackToMove, const BattleHex & myNumber) const
  842. {
  843. BattleHexArray acc = owner.getBattle()->battleGetAvailableHexes(stackToMove, false);
  844. BattleHex shiftedDest = myNumber.cloneInDirection(stackToMove->destShiftDir(), false);
  845. if (acc.contains(myNumber))
  846. return true;
  847. else if (stackToMove->doubleWide() && acc.contains(shiftedDest))
  848. return true;
  849. else
  850. return false;
  851. }
  852. void BattleActionsController::activateStack()
  853. {
  854. const CStack * s = owner.stacksController->getActiveStack();
  855. if(s)
  856. {
  857. tryActivateStackSpellcasting(s);
  858. possibleActions = getPossibleActionsForStack(s);
  859. owner.windowObject->setPossibleActions(possibleActions);
  860. }
  861. }
  862. void BattleActionsController::onHexRightClicked(const BattleHex & clickedHex)
  863. {
  864. bool isCurrentStackInSpellcastMode = creatureSpellcastingModeActive();
  865. if (heroSpellcastingModeActive() || isCurrentStackInSpellcastMode)
  866. {
  867. endCastingSpell();
  868. CRClickPopup::createAndPush(LIBRARY->generaltexth->translate("core.genrltxt.731")); // spell cancelled
  869. return;
  870. }
  871. auto selectedStack = owner.getBattle()->battleGetStackByPos(clickedHex, true);
  872. if (selectedStack != nullptr)
  873. ENGINE->windows().createAndPushWindow<CStackWindow>(selectedStack, true);
  874. if (clickedHex == BattleHex::HERO_ATTACKER && owner.attackingHero)
  875. owner.attackingHero->heroRightClicked();
  876. if (clickedHex == BattleHex::HERO_DEFENDER && owner.defendingHero)
  877. owner.defendingHero->heroRightClicked();
  878. }
  879. bool BattleActionsController::heroSpellcastingModeActive() const
  880. {
  881. return heroSpellToCast != nullptr;
  882. }
  883. bool BattleActionsController::creatureSpellcastingModeActive() const
  884. {
  885. auto spellcastModePredicate = [](const PossiblePlayerBattleAction & action)
  886. {
  887. return action.spellcast() || action.get() == PossiblePlayerBattleAction::SHOOT; //for hotkey-eligible SPELL_LIKE_ATTACK creature should have only SHOOT action
  888. };
  889. return !possibleActions.empty() && std::all_of(possibleActions.begin(), possibleActions.end(), spellcastModePredicate);
  890. }
  891. bool BattleActionsController::currentActionSpellcasting(const BattleHex & hoveredHex)
  892. {
  893. if (heroSpellToCast)
  894. return true;
  895. if (!owner.stacksController->getActiveStack())
  896. return false;
  897. auto action = selectAction(hoveredHex);
  898. return action.spellcast();
  899. }
  900. const std::vector<PossiblePlayerBattleAction> & BattleActionsController::getPossibleActions() const
  901. {
  902. return possibleActions;
  903. }
  904. void BattleActionsController::setPriorityActions(const std::vector<PossiblePlayerBattleAction> & actions)
  905. {
  906. possibleActions = actions;
  907. }
  908. void BattleActionsController::resetCurrentStackPossibleActions()
  909. {
  910. possibleActions = getPossibleActionsForStack(owner.stacksController->getActiveStack());
  911. }