BattleActionsController.cpp 35 KB

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