BattleWindow.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  1. /*
  2. * BattleWindow.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 "BattleWindow.h"
  12. #include "BattleInterface.h"
  13. #include "BattleInterfaceClasses.h"
  14. #include "BattleFieldController.h"
  15. #include "BattleStacksController.h"
  16. #include "BattleActionsController.h"
  17. #include "../CGameInfo.h"
  18. #include "../CPlayerInterface.h"
  19. #include "../CMusicHandler.h"
  20. #include "../gui/CursorHandler.h"
  21. #include "../gui/CGuiHandler.h"
  22. #include "../gui/Shortcut.h"
  23. #include "../gui/WindowHandler.h"
  24. #include "../windows/CSpellWindow.h"
  25. #include "../widgets/Buttons.h"
  26. #include "../widgets/Images.h"
  27. #include "../windows/CMessage.h"
  28. #include "../render/CAnimation.h"
  29. #include "../render/Canvas.h"
  30. #include "../render/IRenderHandler.h"
  31. #include "../adventureMap/CInGameConsole.h"
  32. #include "../adventureMap/TurnTimerWidget.h"
  33. #include "../../CCallback.h"
  34. #include "../../lib/CGeneralTextHandler.h"
  35. #include "../../lib/gameState/InfoAboutArmy.h"
  36. #include "../../lib/mapObjects/CGHeroInstance.h"
  37. #include "../../lib/CStack.h"
  38. #include "../../lib/CConfigHandler.h"
  39. #include "../../lib/filesystem/ResourcePath.h"
  40. #include "../../lib/StartInfo.h"
  41. #include "../../lib/battle/BattleInfo.h"
  42. #include "../../lib/CPlayerState.h"
  43. #include "../windows/settings/SettingsMainWindow.h"
  44. BattleWindow::BattleWindow(BattleInterface & owner):
  45. owner(owner),
  46. defaultAction(PossiblePlayerBattleAction::INVALID)
  47. {
  48. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  49. pos.w = 800;
  50. pos.h = 600;
  51. pos = center();
  52. PlayerColor defenderColor = owner.getBattle()->getBattle()->getSidePlayer(BattleSide::DEFENDER);
  53. PlayerColor attackerColor = owner.getBattle()->getBattle()->getSidePlayer(BattleSide::ATTACKER);
  54. bool isDefenderHuman = defenderColor.isValidPlayer() && LOCPLINT->cb->getStartInfo()->playerInfos.at(defenderColor).isControlledByHuman();
  55. bool isAttackerHuman = attackerColor.isValidPlayer() && LOCPLINT->cb->getStartInfo()->playerInfos.at(attackerColor).isControlledByHuman();
  56. onlyOnePlayerHuman = isDefenderHuman != isAttackerHuman;
  57. REGISTER_BUILDER("battleConsole", &BattleWindow::buildBattleConsole);
  58. const JsonNode config(JsonPath::builtin("config/widgets/BattleWindow2.json"));
  59. addShortcut(EShortcut::GLOBAL_OPTIONS, std::bind(&BattleWindow::bOptionsf, this));
  60. addShortcut(EShortcut::BATTLE_SURRENDER, std::bind(&BattleWindow::bSurrenderf, this));
  61. addShortcut(EShortcut::BATTLE_RETREAT, std::bind(&BattleWindow::bFleef, this));
  62. addShortcut(EShortcut::BATTLE_AUTOCOMBAT, std::bind(&BattleWindow::bAutofightf, this));
  63. addShortcut(EShortcut::BATTLE_END_WITH_AUTOCOMBAT, std::bind(&BattleWindow::endWithAutocombat, this));
  64. addShortcut(EShortcut::BATTLE_CAST_SPELL, std::bind(&BattleWindow::bSpellf, this));
  65. addShortcut(EShortcut::BATTLE_WAIT, std::bind(&BattleWindow::bWaitf, this));
  66. addShortcut(EShortcut::BATTLE_DEFEND, std::bind(&BattleWindow::bDefencef, this));
  67. addShortcut(EShortcut::BATTLE_CONSOLE_UP, std::bind(&BattleWindow::bConsoleUpf, this));
  68. addShortcut(EShortcut::BATTLE_CONSOLE_DOWN, std::bind(&BattleWindow::bConsoleDownf, this));
  69. addShortcut(EShortcut::BATTLE_TACTICS_NEXT, std::bind(&BattleWindow::bTacticNextStack, this));
  70. addShortcut(EShortcut::BATTLE_TACTICS_END, std::bind(&BattleWindow::bTacticPhaseEnd, this));
  71. addShortcut(EShortcut::BATTLE_SELECT_ACTION, std::bind(&BattleWindow::bSwitchActionf, this));
  72. addShortcut(EShortcut::BATTLE_TOGGLE_QUEUE, [this](){ this->toggleQueueVisibility();});
  73. addShortcut(EShortcut::BATTLE_TOGGLE_HEROES_STATS, [this](){ this->toggleStickyHeroWindowsVisibility();});
  74. addShortcut(EShortcut::BATTLE_USE_CREATURE_SPELL, [this](){ this->owner.actionsController->enterCreatureCastingMode(); });
  75. addShortcut(EShortcut::GLOBAL_CANCEL, [this](){ this->owner.actionsController->endCastingSpell(); });
  76. build(config);
  77. console = widget<BattleConsole>("console");
  78. owner.console = console;
  79. owner.fieldController.reset( new BattleFieldController(owner));
  80. owner.fieldController->createHeroes();
  81. createQueue();
  82. createStickyHeroInfoWindows();
  83. createTimerInfoWindows();
  84. if ( owner.tacticsMode )
  85. tacticPhaseStarted();
  86. else
  87. tacticPhaseEnded();
  88. addUsedEvents(LCLICK | KEYBOARD);
  89. }
  90. void BattleWindow::createQueue()
  91. {
  92. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  93. //create stack queue and adjust our own position
  94. bool embedQueue;
  95. bool showQueue = settings["battle"]["showQueue"].Bool();
  96. std::string queueSize = settings["battle"]["queueSize"].String();
  97. if(queueSize == "auto")
  98. embedQueue = GH.screenDimensions().y < 700;
  99. else
  100. embedQueue = GH.screenDimensions().y < 700 || queueSize == "small";
  101. queue = std::make_shared<StackQueue>(embedQueue, owner);
  102. if(!embedQueue && showQueue)
  103. {
  104. //re-center, taking into account stack queue position
  105. pos.y -= queue->pos.h;
  106. pos.h += queue->pos.h;
  107. pos = center();
  108. }
  109. if (!showQueue)
  110. queue->disable();
  111. }
  112. void BattleWindow::createStickyHeroInfoWindows()
  113. {
  114. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  115. if(owner.defendingHeroInstance)
  116. {
  117. InfoAboutHero info;
  118. info.initFromHero(owner.defendingHeroInstance, InfoAboutHero::EInfoLevel::INBATTLE);
  119. defenderHeroWindow = std::make_shared<HeroInfoBasicPanel>(info, nullptr);
  120. }
  121. if(owner.attackingHeroInstance)
  122. {
  123. InfoAboutHero info;
  124. info.initFromHero(owner.attackingHeroInstance, InfoAboutHero::EInfoLevel::INBATTLE);
  125. attackerHeroWindow = std::make_shared<HeroInfoBasicPanel>(info, nullptr);
  126. }
  127. bool showInfoWindows = settings["battle"]["stickyHeroInfoWindows"].Bool();
  128. if(!showInfoWindows)
  129. {
  130. if(attackerHeroWindow)
  131. attackerHeroWindow->disable();
  132. if(defenderHeroWindow)
  133. defenderHeroWindow->disable();
  134. }
  135. setPositionInfoWindow();
  136. }
  137. void BattleWindow::createTimerInfoWindows()
  138. {
  139. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  140. if(LOCPLINT->cb->getStartInfo()->turnTimerInfo.battleTimer != 0 || LOCPLINT->cb->getStartInfo()->turnTimerInfo.unitTimer != 0)
  141. {
  142. PlayerColor attacker = owner.getBattle()->sideToPlayer(BattleSide::ATTACKER);
  143. PlayerColor defender = owner.getBattle()->sideToPlayer(BattleSide::DEFENDER);
  144. if (attacker.isValidPlayer())
  145. {
  146. if (GH.screenDimensions().x >= 1000)
  147. attackerTimerWidget = std::make_shared<TurnTimerWidget>(Point(-92, 1), attacker);
  148. else
  149. attackerTimerWidget = std::make_shared<TurnTimerWidget>(Point(1, 135), attacker);
  150. }
  151. if (defender.isValidPlayer())
  152. {
  153. if (GH.screenDimensions().x >= 1000)
  154. defenderTimerWidget = std::make_shared<TurnTimerWidget>(Point(pos.w + 16, 1), defender);
  155. else
  156. defenderTimerWidget = std::make_shared<TurnTimerWidget>(Point(pos.w - 78, 135), defender);
  157. }
  158. }
  159. }
  160. BattleWindow::~BattleWindow()
  161. {
  162. CPlayerInterface::battleInt = nullptr;
  163. }
  164. std::shared_ptr<BattleConsole> BattleWindow::buildBattleConsole(const JsonNode & config) const
  165. {
  166. auto rect = readRect(config["rect"]);
  167. auto offset = readPosition(config["imagePosition"]);
  168. auto background = widget<CPicture>("menuBattle");
  169. return std::make_shared<BattleConsole>(background, rect.topLeft(), offset, rect.dimensions() );
  170. }
  171. void BattleWindow::toggleQueueVisibility()
  172. {
  173. if(settings["battle"]["showQueue"].Bool())
  174. hideQueue();
  175. else
  176. showQueue();
  177. }
  178. void BattleWindow::hideQueue()
  179. {
  180. if(settings["battle"]["showQueue"].Bool() == false)
  181. return;
  182. Settings showQueue = settings.write["battle"]["showQueue"];
  183. showQueue->Bool() = false;
  184. queue->disable();
  185. if (!queue->embedded)
  186. {
  187. //re-center, taking into account stack queue position
  188. pos.y += queue->pos.h;
  189. pos.h -= queue->pos.h;
  190. pos = center();
  191. }
  192. setPositionInfoWindow();
  193. GH.windows().totalRedraw();
  194. }
  195. void BattleWindow::showQueue()
  196. {
  197. if(settings["battle"]["showQueue"].Bool() == true)
  198. return;
  199. Settings showQueue = settings.write["battle"]["showQueue"];
  200. showQueue->Bool() = true;
  201. createQueue();
  202. updateQueue();
  203. setPositionInfoWindow();
  204. GH.windows().totalRedraw();
  205. }
  206. void BattleWindow::toggleStickyHeroWindowsVisibility()
  207. {
  208. if(settings["battle"]["stickyHeroInfoWindows"].Bool())
  209. hideStickyHeroWindows();
  210. else
  211. showStickyHeroWindows();
  212. }
  213. void BattleWindow::hideStickyHeroWindows()
  214. {
  215. if(settings["battle"]["stickyHeroInfoWindows"].Bool() == false)
  216. return;
  217. Settings showStickyHeroInfoWindows = settings.write["battle"]["stickyHeroInfoWindows"];
  218. showStickyHeroInfoWindows->Bool() = false;
  219. if(attackerHeroWindow)
  220. attackerHeroWindow->disable();
  221. if(defenderHeroWindow)
  222. defenderHeroWindow->disable();
  223. GH.windows().totalRedraw();
  224. }
  225. void BattleWindow::showStickyHeroWindows()
  226. {
  227. if(settings["battle"]["stickyHeroInfoWindows"].Bool() == true)
  228. return;
  229. Settings showStickyHeroInfoWindows = settings.write["battle"]["stickyHeroInfoWindows"];
  230. showStickyHeroInfoWindows->Bool() = true;
  231. createStickyHeroInfoWindows();
  232. GH.windows().totalRedraw();
  233. }
  234. void BattleWindow::updateQueue()
  235. {
  236. queue->update();
  237. }
  238. void BattleWindow::setPositionInfoWindow()
  239. {
  240. if(defenderHeroWindow)
  241. {
  242. Point position = (GH.screenDimensions().x >= 1000)
  243. ? Point(pos.x + pos.w + 15, pos.y + 60)
  244. : Point(pos.x + pos.w -79, pos.y + 195);
  245. defenderHeroWindow->moveTo(position);
  246. }
  247. if(attackerHeroWindow)
  248. {
  249. Point position = (GH.screenDimensions().x >= 1000)
  250. ? Point(pos.x - 93, pos.y + 60)
  251. : Point(pos.x + 1, pos.y + 195);
  252. attackerHeroWindow->moveTo(position);
  253. }
  254. if(defenderStackWindow)
  255. {
  256. Point position = (GH.screenDimensions().x >= 1000)
  257. ? Point(pos.x + pos.w + 15, defenderHeroWindow ? defenderHeroWindow->pos.y + 210 : pos.y + 60)
  258. : Point(pos.x + pos.w -79, defenderHeroWindow ? defenderHeroWindow->pos.y : pos.y + 195);
  259. defenderStackWindow->moveTo(position);
  260. }
  261. if(attackerStackWindow)
  262. {
  263. Point position = (GH.screenDimensions().x >= 1000)
  264. ? Point(pos.x - 93, attackerHeroWindow ? attackerHeroWindow->pos.y + 210 : pos.y + 60)
  265. : Point(pos.x + 1, attackerHeroWindow ? attackerHeroWindow->pos.y : pos.y + 195);
  266. attackerStackWindow->moveTo(position);
  267. }
  268. }
  269. void BattleWindow::updateHeroInfoWindow(uint8_t side, const InfoAboutHero & hero)
  270. {
  271. std::shared_ptr<HeroInfoBasicPanel> panelToUpdate = side == 0 ? attackerHeroWindow : defenderHeroWindow;
  272. panelToUpdate->update(hero);
  273. }
  274. void BattleWindow::updateStackInfoWindow(const CStack * stack)
  275. {
  276. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  277. bool showInfoWindows = settings["battle"]["stickyHeroInfoWindows"].Bool();
  278. if(stack && stack->unitSide() == BattleSide::DEFENDER)
  279. {
  280. defenderStackWindow = std::make_shared<StackInfoBasicPanel>(stack);
  281. defenderStackWindow->setEnabled(showInfoWindows);
  282. }
  283. else
  284. defenderStackWindow = nullptr;
  285. if(stack && stack->unitSide() == BattleSide::ATTACKER)
  286. {
  287. attackerStackWindow = std::make_shared<StackInfoBasicPanel>(stack);
  288. attackerStackWindow->setEnabled(showInfoWindows);
  289. }
  290. else
  291. attackerStackWindow = nullptr;
  292. setPositionInfoWindow();
  293. }
  294. void BattleWindow::heroManaPointsChanged(const CGHeroInstance * hero)
  295. {
  296. if(hero == owner.attackingHeroInstance || hero == owner.defendingHeroInstance)
  297. {
  298. InfoAboutHero heroInfo = InfoAboutHero();
  299. heroInfo.initFromHero(hero, InfoAboutHero::INBATTLE);
  300. updateHeroInfoWindow(hero == owner.attackingHeroInstance ? 0 : 1, heroInfo);
  301. }
  302. else
  303. {
  304. logGlobal->error("BattleWindow::heroManaPointsChanged: 'Mana points changed' called for hero not belonging to current battle window");
  305. }
  306. }
  307. void BattleWindow::activate()
  308. {
  309. GH.setStatusbar(console);
  310. CIntObject::activate();
  311. LOCPLINT->cingconsole->activate();
  312. }
  313. void BattleWindow::deactivate()
  314. {
  315. GH.setStatusbar(nullptr);
  316. CIntObject::deactivate();
  317. LOCPLINT->cingconsole->deactivate();
  318. }
  319. bool BattleWindow::captureThisKey(EShortcut key)
  320. {
  321. return owner.openingPlaying();
  322. }
  323. void BattleWindow::keyPressed(EShortcut key)
  324. {
  325. if (owner.openingPlaying())
  326. {
  327. owner.openingEnd();
  328. return;
  329. }
  330. InterfaceObjectConfigurable::keyPressed(key);
  331. }
  332. void BattleWindow::clickPressed(const Point & cursorPosition)
  333. {
  334. if (owner.openingPlaying())
  335. {
  336. owner.openingEnd();
  337. return;
  338. }
  339. InterfaceObjectConfigurable::clickPressed(cursorPosition);
  340. }
  341. void BattleWindow::tacticPhaseStarted()
  342. {
  343. auto menuBattle = widget<CIntObject>("menuBattle");
  344. auto console = widget<CIntObject>("console");
  345. auto menuTactics = widget<CIntObject>("menuTactics");
  346. auto tacticNext = widget<CIntObject>("tacticNext");
  347. auto tacticEnd = widget<CIntObject>("tacticEnd");
  348. auto alternativeAction = widget<CIntObject>("alternativeAction");
  349. menuBattle->disable();
  350. console->disable();
  351. if (alternativeAction)
  352. alternativeAction->disable();
  353. menuTactics->enable();
  354. tacticNext->enable();
  355. tacticEnd->enable();
  356. redraw();
  357. }
  358. void BattleWindow::tacticPhaseEnded()
  359. {
  360. auto menuBattle = widget<CIntObject>("menuBattle");
  361. auto console = widget<CIntObject>("console");
  362. auto menuTactics = widget<CIntObject>("menuTactics");
  363. auto tacticNext = widget<CIntObject>("tacticNext");
  364. auto tacticEnd = widget<CIntObject>("tacticEnd");
  365. auto alternativeAction = widget<CIntObject>("alternativeAction");
  366. menuBattle->enable();
  367. console->enable();
  368. if (alternativeAction)
  369. alternativeAction->enable();
  370. menuTactics->disable();
  371. tacticNext->disable();
  372. tacticEnd->disable();
  373. redraw();
  374. }
  375. void BattleWindow::bOptionsf()
  376. {
  377. if (owner.actionsController->spellcastingModeActive())
  378. return;
  379. CCS->curh->set(Cursor::Map::POINTER);
  380. GH.windows().createAndPushWindow<SettingsMainWindow>(&owner);
  381. }
  382. void BattleWindow::bSurrenderf()
  383. {
  384. if (owner.actionsController->spellcastingModeActive())
  385. return;
  386. int cost = owner.getBattle()->battleGetSurrenderCost();
  387. if(cost >= 0)
  388. {
  389. std::string enemyHeroName = owner.getBattle()->battleGetEnemyHero().name;
  390. if(enemyHeroName.empty())
  391. {
  392. logGlobal->warn("Surrender performed without enemy hero, should not happen!");
  393. enemyHeroName = "#ENEMY#";
  394. }
  395. std::string surrenderMessage = boost::str(boost::format(CGI->generaltexth->allTexts[32]) % enemyHeroName % cost); //%s states: "I will accept your surrender and grant you and your troops safe passage for the price of %d gold."
  396. owner.curInt->showYesNoDialog(surrenderMessage, [this](){ reallySurrender(); }, nullptr);
  397. }
  398. }
  399. void BattleWindow::bFleef()
  400. {
  401. if (owner.actionsController->spellcastingModeActive())
  402. return;
  403. if ( owner.getBattle()->battleCanFlee() )
  404. {
  405. auto ony = std::bind(&BattleWindow::reallyFlee,this);
  406. owner.curInt->showYesNoDialog(CGI->generaltexth->allTexts[28], ony, nullptr); //Are you sure you want to retreat?
  407. }
  408. else
  409. {
  410. std::vector<std::shared_ptr<CComponent>> comps;
  411. std::string heroName;
  412. //calculating fleeing hero's name
  413. if (owner.attackingHeroInstance)
  414. if (owner.attackingHeroInstance->tempOwner == owner.curInt->cb->getPlayerID())
  415. heroName = owner.attackingHeroInstance->getNameTranslated();
  416. if (owner.defendingHeroInstance)
  417. if (owner.defendingHeroInstance->tempOwner == owner.curInt->cb->getPlayerID())
  418. heroName = owner.defendingHeroInstance->getNameTranslated();
  419. //calculating text
  420. auto txt = boost::format(CGI->generaltexth->allTexts[340]) % heroName; //The Shackles of War are present. %s can not retreat!
  421. //printing message
  422. owner.curInt->showInfoDialog(boost::str(txt), comps);
  423. }
  424. }
  425. void BattleWindow::reallyFlee()
  426. {
  427. owner.giveCommand(EActionType::RETREAT);
  428. CCS->curh->set(Cursor::Map::POINTER);
  429. }
  430. void BattleWindow::reallySurrender()
  431. {
  432. if (owner.curInt->cb->getResourceAmount(EGameResID::GOLD) < owner.getBattle()->battleGetSurrenderCost())
  433. {
  434. owner.curInt->showInfoDialog(CGI->generaltexth->allTexts[29]); //You don't have enough gold!
  435. }
  436. else
  437. {
  438. owner.giveCommand(EActionType::SURRENDER);
  439. CCS->curh->set(Cursor::Map::POINTER);
  440. }
  441. }
  442. void BattleWindow::showAlternativeActionIcon(PossiblePlayerBattleAction action)
  443. {
  444. auto w = widget<CButton>("alternativeAction");
  445. if(!w)
  446. return;
  447. AnimationPath iconName = AnimationPath::fromJson(variables["actionIconDefault"]);
  448. switch(action.get())
  449. {
  450. case PossiblePlayerBattleAction::ATTACK:
  451. iconName = AnimationPath::fromJson(variables["actionIconAttack"]);
  452. break;
  453. case PossiblePlayerBattleAction::SHOOT:
  454. iconName = AnimationPath::fromJson(variables["actionIconShoot"]);
  455. break;
  456. case PossiblePlayerBattleAction::AIMED_SPELL_CREATURE:
  457. iconName = AnimationPath::fromJson(variables["actionIconSpell"]);
  458. break;
  459. case PossiblePlayerBattleAction::ANY_LOCATION:
  460. iconName = AnimationPath::fromJson(variables["actionIconSpell"]);
  461. break;
  462. //TODO: figure out purpose of this icon
  463. //case PossiblePlayerBattleAction::???:
  464. //iconName = variables["actionIconWalk"].String();
  465. //break;
  466. case PossiblePlayerBattleAction::ATTACK_AND_RETURN:
  467. iconName = AnimationPath::fromJson(variables["actionIconReturn"]);
  468. break;
  469. case PossiblePlayerBattleAction::WALK_AND_ATTACK:
  470. iconName = AnimationPath::fromJson(variables["actionIconNoReturn"]);
  471. break;
  472. }
  473. auto anim = GH.renderHandler().loadAnimation(iconName);
  474. w->setImage(anim);
  475. w->redraw();
  476. }
  477. void BattleWindow::setAlternativeActions(const std::list<PossiblePlayerBattleAction> & actions)
  478. {
  479. alternativeActions = actions;
  480. defaultAction = PossiblePlayerBattleAction::INVALID;
  481. if(alternativeActions.size() > 1)
  482. defaultAction = alternativeActions.back();
  483. if(!alternativeActions.empty())
  484. showAlternativeActionIcon(alternativeActions.front());
  485. else
  486. showAlternativeActionIcon(defaultAction);
  487. }
  488. void BattleWindow::bAutofightf()
  489. {
  490. if (owner.actionsController->spellcastingModeActive())
  491. return;
  492. if(settings["battle"]["endWithAutocombat"].Bool() && onlyOnePlayerHuman)
  493. {
  494. endWithAutocombat();
  495. return;
  496. }
  497. //Stop auto-fight mode
  498. if(owner.curInt->isAutoFightOn)
  499. {
  500. assert(owner.curInt->autofightingAI);
  501. owner.curInt->isAutoFightOn = false;
  502. logGlobal->trace("Stopping the autofight...");
  503. }
  504. else if(!owner.curInt->autofightingAI)
  505. {
  506. owner.curInt->isAutoFightOn = true;
  507. blockUI(true);
  508. auto ai = CDynLibHandler::getNewBattleAI(settings["server"]["friendlyAI"].String());
  509. AutocombatPreferences autocombatPreferences = AutocombatPreferences();
  510. autocombatPreferences.enableSpellsUsage = settings["battle"]["enableAutocombatSpells"].Bool();
  511. ai->initBattleInterface(owner.curInt->env, owner.curInt->cb, autocombatPreferences);
  512. ai->battleStart(owner.getBattleID(), owner.army1, owner.army2, int3(0,0,0), owner.attackingHeroInstance, owner.defendingHeroInstance, owner.getBattle()->battleGetMySide(), false);
  513. owner.curInt->autofightingAI = ai;
  514. owner.curInt->cb->registerBattleInterface(ai);
  515. owner.requestAutofightingAIToTakeAction();
  516. }
  517. }
  518. void BattleWindow::bSpellf()
  519. {
  520. if (owner.actionsController->spellcastingModeActive())
  521. return;
  522. if (!owner.makingTurn())
  523. return;
  524. auto myHero = owner.currentHero();
  525. if(!myHero)
  526. return;
  527. CCS->curh->set(Cursor::Map::POINTER);
  528. ESpellCastProblem spellCastProblem = owner.getBattle()->battleCanCastSpell(myHero, spells::Mode::HERO);
  529. if(spellCastProblem == ESpellCastProblem::OK)
  530. {
  531. GH.windows().createAndPushWindow<CSpellWindow>(myHero, owner.curInt.get());
  532. }
  533. else if (spellCastProblem == ESpellCastProblem::MAGIC_IS_BLOCKED)
  534. {
  535. //TODO: move to spell mechanics, add more information to spell cast problem
  536. //Handle Orb of Inhibition-like effects -> we want to display dialog with info, why casting is impossible
  537. auto blockingBonus = owner.currentHero()->getFirstBonus(Selector::type()(BonusType::BLOCK_ALL_MAGIC));
  538. if (!blockingBonus)
  539. return;
  540. if (blockingBonus->source == BonusSource::ARTIFACT)
  541. {
  542. const auto artID = blockingBonus->sid.as<ArtifactID>();
  543. //If we have artifact, put name of our hero. Otherwise assume it's the enemy.
  544. //TODO check who *really* is source of bonus
  545. std::string heroName = myHero->hasArt(artID) ? myHero->getNameTranslated() : owner.enemyHero().name;
  546. //%s wields the %s, an ancient artifact which creates a p dead to all magic.
  547. LOCPLINT->showInfoDialog(boost::str(boost::format(CGI->generaltexth->allTexts[683])
  548. % heroName % CGI->artifacts()->getByIndex(artID)->getNameTranslated()));
  549. }
  550. else if(blockingBonus->source == BonusSource::OBJECT_TYPE)
  551. {
  552. if(blockingBonus->sid.as<MapObjectID>() == Obj::GARRISON || blockingBonus->sid.as<MapObjectID>() == Obj::GARRISON2)
  553. LOCPLINT->showInfoDialog(CGI->generaltexth->allTexts[684]);
  554. }
  555. }
  556. else
  557. {
  558. logGlobal->warn("Unexpected problem with readiness to cast spell");
  559. }
  560. }
  561. void BattleWindow::bSwitchActionf()
  562. {
  563. if(alternativeActions.empty())
  564. return;
  565. if(alternativeActions.front() == defaultAction)
  566. {
  567. alternativeActions.push_back(alternativeActions.front());
  568. alternativeActions.pop_front();
  569. }
  570. auto actions = owner.actionsController->getPossibleActions();
  571. if(!actions.empty() && actions.front() == alternativeActions.front())
  572. {
  573. owner.actionsController->removePossibleAction(alternativeActions.front());
  574. showAlternativeActionIcon(defaultAction);
  575. }
  576. else
  577. {
  578. owner.actionsController->pushFrontPossibleAction(alternativeActions.front());
  579. showAlternativeActionIcon(alternativeActions.front());
  580. }
  581. alternativeActions.push_back(alternativeActions.front());
  582. alternativeActions.pop_front();
  583. }
  584. void BattleWindow::bWaitf()
  585. {
  586. if (owner.actionsController->spellcastingModeActive())
  587. return;
  588. if (owner.stacksController->getActiveStack() != nullptr)
  589. owner.giveCommand(EActionType::WAIT);
  590. }
  591. void BattleWindow::bDefencef()
  592. {
  593. if (owner.actionsController->spellcastingModeActive())
  594. return;
  595. if (owner.stacksController->getActiveStack() != nullptr)
  596. owner.giveCommand(EActionType::DEFEND);
  597. }
  598. void BattleWindow::bConsoleUpf()
  599. {
  600. if (owner.actionsController->spellcastingModeActive())
  601. return;
  602. console->scrollUp();
  603. }
  604. void BattleWindow::bConsoleDownf()
  605. {
  606. if (owner.actionsController->spellcastingModeActive())
  607. return;
  608. console->scrollDown();
  609. }
  610. void BattleWindow::bTacticNextStack()
  611. {
  612. owner.tacticNextStack(nullptr);
  613. }
  614. void BattleWindow::bTacticPhaseEnd()
  615. {
  616. owner.tacticPhaseEnd();
  617. }
  618. void BattleWindow::blockUI(bool on)
  619. {
  620. bool canCastSpells = false;
  621. auto hero = owner.getBattle()->battleGetMyHero();
  622. if(hero)
  623. {
  624. ESpellCastProblem spellcastingProblem = owner.getBattle()->battleCanCastSpell(hero, spells::Mode::HERO);
  625. //if magic is blocked, we leave button active, so the message can be displayed after button click
  626. canCastSpells = spellcastingProblem == ESpellCastProblem::OK || spellcastingProblem == ESpellCastProblem::MAGIC_IS_BLOCKED;
  627. }
  628. bool canWait = owner.stacksController->getActiveStack() ? !owner.stacksController->getActiveStack()->waitedThisTurn : false;
  629. setShortcutBlocked(EShortcut::GLOBAL_OPTIONS, on);
  630. setShortcutBlocked(EShortcut::BATTLE_RETREAT, on || !owner.getBattle()->battleCanFlee());
  631. setShortcutBlocked(EShortcut::BATTLE_SURRENDER, on || owner.getBattle()->battleGetSurrenderCost() < 0);
  632. setShortcutBlocked(EShortcut::BATTLE_CAST_SPELL, on || owner.tacticsMode || !canCastSpells);
  633. setShortcutBlocked(EShortcut::BATTLE_WAIT, on || owner.tacticsMode || !canWait);
  634. setShortcutBlocked(EShortcut::BATTLE_DEFEND, on || owner.tacticsMode);
  635. setShortcutBlocked(EShortcut::BATTLE_SELECT_ACTION, on || owner.tacticsMode);
  636. setShortcutBlocked(EShortcut::BATTLE_AUTOCOMBAT, (settings["battle"]["endWithAutocombat"].Bool() && onlyOnePlayerHuman) ? on || owner.tacticsMode || owner.actionsController->spellcastingModeActive() : owner.actionsController->spellcastingModeActive());
  637. setShortcutBlocked(EShortcut::BATTLE_END_WITH_AUTOCOMBAT, on || owner.tacticsMode || !onlyOnePlayerHuman || owner.actionsController->spellcastingModeActive());
  638. setShortcutBlocked(EShortcut::BATTLE_TACTICS_END, on && owner.tacticsMode);
  639. setShortcutBlocked(EShortcut::BATTLE_TACTICS_NEXT, on && owner.tacticsMode);
  640. setShortcutBlocked(EShortcut::BATTLE_CONSOLE_DOWN, on && !owner.tacticsMode);
  641. setShortcutBlocked(EShortcut::BATTLE_CONSOLE_UP, on && !owner.tacticsMode);
  642. }
  643. std::optional<uint32_t> BattleWindow::getQueueHoveredUnitId()
  644. {
  645. return queue->getHoveredUnitIdIfAny();
  646. }
  647. void BattleWindow::endWithAutocombat()
  648. {
  649. if(!owner.makingTurn() || owner.tacticsMode)
  650. return;
  651. LOCPLINT->showYesNoDialog(
  652. VLC->generaltexth->translate("vcmi.battleWindow.endWithAutocombat"),
  653. [this]()
  654. {
  655. owner.curInt->isAutoFightEndBattle = true;
  656. auto ai = CDynLibHandler::getNewBattleAI(settings["server"]["friendlyAI"].String());
  657. AutocombatPreferences autocombatPreferences = AutocombatPreferences();
  658. autocombatPreferences.enableSpellsUsage = settings["battle"]["enableAutocombatSpells"].Bool();
  659. ai->initBattleInterface(owner.curInt->env, owner.curInt->cb, autocombatPreferences);
  660. ai->battleStart(owner.getBattleID(), owner.army1, owner.army2, int3(0,0,0), owner.attackingHeroInstance, owner.defendingHeroInstance, owner.getBattle()->battleGetMySide(), false);
  661. owner.curInt->isAutoFightOn = true;
  662. owner.curInt->cb->registerBattleInterface(ai);
  663. owner.curInt->autofightingAI = ai;
  664. owner.requestAutofightingAIToTakeAction();
  665. close();
  666. owner.curInt->battleInt.reset();
  667. },
  668. nullptr
  669. );
  670. }
  671. void BattleWindow::showAll(Canvas & to)
  672. {
  673. CIntObject::showAll(to);
  674. if (GH.screenDimensions().x != 800 || GH.screenDimensions().y !=600)
  675. CMessage::drawBorder(owner.curInt->playerID, to, pos.w+28, pos.h+29, pos.x-14, pos.y-15);
  676. }
  677. void BattleWindow::show(Canvas & to)
  678. {
  679. CIntObject::show(to);
  680. LOCPLINT->cingconsole->show(to);
  681. }
  682. void BattleWindow::close()
  683. {
  684. if(!GH.windows().isTopWindow(this))
  685. logGlobal->error("Only top interface must be closed");
  686. GH.windows().popWindows(1);
  687. }