BattleWindow.cpp 28 KB

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