BattleWindow.cpp 27 KB

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