BattleWindow.cpp 28 KB

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