BattleActionsController.cpp 34 KB

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